import cv2
import numpy as np
import gym
from gym import spaces
from stable_baselines3 import PPO
class SimpleReactorEnv(gym.Env):
def __init__(self):
super(SimpleReactorEnv, self).__init__()
self.observation_space = spaces.Box(low=0, high=255, shape=(64, 64, 1), dtype=np.uint8)
self.action_space = spaces.Discrete(3) # 0: reduce, 1: maintain, 2: increase
self.state = np.zeros((64, 64), dtype=np.uint8) # Initial empty reactor image
self.target = np.random.randint(0, 255, (64, 64), dtype=np.uint8)
def reset(self):
self.state = np.zeros((64, 64), dtype=np.uint8)
return self.state
def step(self, action):
if action == 0:
self.state = np.maximum(self.state - 5, 0)
if action == 1:
pass # Maintain current state
if action == 2:
self.state = np.minimum(self.state + 5, 255)
# Compute reward
diff = cv2.absdiff(self.state, self.target)
reward = -np.sum(diff) / (64 * 64) # Minimize difference to target
done = np.array_equal(self.state, self.target)
return self.state, reward, done, {}
def render(self, mode='human'):
cv2.imshow('Reactor', self.state)
cv2.waitKey(1)
# Create the environment
env = SimpleReactorEnv()
# Instantiate the agent
model = PPO("CnnPolicy", env, verbose=1)
# Train the agent
model.learn(total_timesteps=10000)
# Test the agent
obs = env.reset()
for _ in range(1000):
action, _states = model.predict(obs, deterministic=True)
obs, rewards, done, info = env.step(action)
env.render()
if done:
obs = env.reset()
env.close()