-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_mpc_pendulum.py
169 lines (138 loc) · 3.88 KB
/
test_mpc_pendulum.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
from typing import Any
import env
from mpc import ModelPredictiveControlWithoutOptimizer
from system import Pendulum, angle_normalize
# Import make_vec_env to allow parallelization
from stable_baselines3.common.env_util import make_vec_env
import torch
def cost(predicted_state, target_state, action=None, cost_dict=None):
batch_size, prediction_horizon, _ = predicted_state["theta"].shape
device = predicted_state["theta"].device
predicted_theta = predicted_state["theta"]
predicted_theta_dot = predicted_state["theta_dot"]
target_theta = target_state["theta"].unsqueeze(1).expand(-1, prediction_horizon, -1)
target_theta_dot = (
target_state["theta_dot"].unsqueeze(1).expand(-1, prediction_horizon, -1)
)
if cost_dict is None:
cost_dict = dict(
theta_weight=torch.ones(batch_size, prediction_horizon, 1, device=device)
* 10.0,
theta_dot_weight=torch.ones(
batch_size, prediction_horizon, 1, device=device
)
* 0.1,
action_weight=torch.ones(batch_size, prediction_horizon, 1, device=device)
* 0.001,
)
# cost += (
# (
# ((angle_normalize(predicted_theta) - angle_normalize(target_theta)).pow(2))
# * cost_dict["theta_weight"]
# )
# .mean(0)
# .sum()
# )
# cost += (
# (
# (predicted_theta_dot - target_theta_dot).pow(2)
# * cost_dict["theta_dot_weight"]
# )
# .mean(0)
# .sum()
# )
# cost += (action.pow(2) * cost_dict["action_weight"]).mean(0).sum()
cost = (
(
torch.nn.functional.mse_loss(
angle_normalize(predicted_theta),
angle_normalize(target_theta),
reduction="none",
)
* cost_dict["theta_weight"]
)
.mean(1)
.sum()
)
cost += (
(
torch.nn.functional.mse_loss(
predicted_theta_dot,
target_theta_dot,
reduction="none",
)
* cost_dict["theta_dot_weight"]
)
.mean(1)
.sum()
)
cost += (
(
torch.norm(
action,
p=2,
dim=-1,
keepdim=True,
)
* cost_dict["action_weight"]
)
.mean(1)
.sum()
)
return cost
def obs_to_state_target(obs) -> tuple[Any, Any]:
theta = torch.atan2(obs[:, 1], obs[:, 0]).unsqueeze(-1)
theta_dot = obs[:, 2].unsqueeze(-1)
state = dict(
theta=theta,
theta_dot=theta_dot,
)
target = dict(
theta=torch.ones_like(theta) * 0.0,
theta_dot=torch.ones_like(theta_dot) * 0.0,
)
return state, target
# Create system
system = Pendulum(
dt=0.05,
m=1.0,
g=10.0,
l=1.0,
)
# Create environment
env = make_vec_env(
"Pendulum-v1",
n_envs=1,
seed=42,
env_kwargs=dict(
g=10.0,
),
)
# Create Model Predictive Control model
mpc = ModelPredictiveControlWithoutOptimizer(
system,
cost,
action_size=1,
prediction_horizon=5,
num_optimization_step=40,
lr=1.0,
device="cpu",
)
observation = env.reset()
observation = torch.Tensor(observation.copy())
state, target = obs_to_state_target(observation)
while True:
action, cost_value = mpc(state, target)
# print(action)
action_ = action.clone().detach().numpy()
action_selected = action_[:, 0]
# print(action_selected.shape)
# print(f"Action: {action_selected}")
# print(f"Cost: {cost_value}")
observation, reward, _, information = env.step(action_selected)
# print(reward)
observation = torch.Tensor(observation.copy())
print(f"State: {observation}")
state, target = obs_to_state_target(observation)
# time.sleep(0.1)
env.render("human")