-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasiccontrol.py
More file actions
32 lines (25 loc) · 875 Bytes
/
Copy pathbasiccontrol.py
File metadata and controls
32 lines (25 loc) · 875 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/env python3
import gymnasium as gym
class PD:
def __init__(self, kp, kd, goal):
self.kp = kp
self.kd = kd
self.goal = goal
self.last_error = 0
def observe(self, x):
error = self.goal - x
d_error = error - self.last_error
self.last_error = error
return self.kp * error + self.kd * d_error
if __name__ == "__main__":
controller = PD(kp=5, kd=100, goal=0)
env = gym.make("CartPole-v1", render_mode="human")
observation, info = env.reset()
for _ in range(1000):
pole_angle = observation[2]
control_output = controller.observe(pole_angle)
action = 1 if control_output < 0 else 0
observation, reward, terminated, truncated, info = env.step(action)
if terminated or truncated:
observation, info = env.reset()
env.close()