-
Notifications
You must be signed in to change notification settings - Fork 0
/
cartpole.py
131 lines (118 loc) · 5.37 KB
/
cartpole.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
import numpy as np
import sys
import pickle
from controllers.energy_controller import CartpoleController
from lyapunov_controller import LyapunovCartpoleController
from easy_c2g import compute_lyapunov_function
import function_fuser
from pydrake.math import RigidTransform, RollPitchYaw
from pydrake.multibody.plant import AddMultibodyPlantSceneGraph
from pydrake.systems.controllers import LinearQuadraticRegulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.meshcat_visualizer import ConnectMeshcatVisualizer
from pydrake.systems.analysis import Simulator
from pydrake.systems.primitives import FirstOrderTaylorApproximation
from pydrake.multibody.parsing import Parser
from pydrake.multibody.tree import PrismaticJoint, LinearSpringDamper
from pydrake.common import FindResourceOrThrow
import matplotlib.pyplot as plt
stiffness = 5
base_wall_offset =9.8 #23.8
spring_length = 8.3
def xyz_rpy_deg(xyz, rpy_deg):
"""Shorthand for defining a pose."""
rpy_deg = np.asarray(rpy_deg)
return RigidTransform(RollPitchYaw(rpy_deg * np.pi / 180), xyz)
def setup_walls(plant):
wall_right = Parser(plant).AddModelFromFile("wall.sdf")
spring_wall_right = Parser(plant).AddModelFromFile("wall.sdf", "springy_wall_right")
plant.WeldFrames(
frame_on_parent_P=plant.world_frame(),
frame_on_child_C=plant.GetFrameByName("Wall", wall_right),
X_PC=xyz_rpy_deg([base_wall_offset, 0, 0], [0, 0, 0]))
right_joint = PrismaticJoint(
"right_joint", plant.GetFrameByName("Wall", wall_right),
plant.GetFrameByName("Wall", spring_wall_right), np.array([1, 0, 0]))
right_joint.set_default_translation(-spring_length)
plant.AddJoint(right_joint)
right_spring = LinearSpringDamper(
plant.GetBodyByName("Wall", wall_right), np.array([0, 0, 0]),
plant.GetBodyByName("Wall", spring_wall_right), np.array([0, 0, 0]),
spring_length, stiffness, 0.0)
plant.AddForceElement(right_spring)
wall_left = Parser(plant).AddModelFromFile("wall.sdf", "wall_left")
spring_wall_left = Parser(plant).AddModelFromFile("wall.sdf", "springy_wall_left")
plant.WeldFrames(
frame_on_parent_P=plant.world_frame(),
frame_on_child_C=plant.GetFrameByName("Wall", wall_left),
X_PC=xyz_rpy_deg([-base_wall_offset, 0, 0], [0, 0, 0]))
left_joint = PrismaticJoint(
"left_joint", plant.GetFrameByName("Wall", wall_left),
plant.GetFrameByName("Wall", spring_wall_left), np.array([1, 0, 0]))
left_joint.set_default_translation(spring_length)
plant.AddJoint(left_joint)
left_spring = LinearSpringDamper(
plant.GetBodyByName("Wall", wall_left), np.array([0, 0, 0]),
plant.GetBodyByName("Wall", spring_wall_left), np.array([0, 0, 0]),
spring_length, stiffness, 0.0)
plant.AddForceElement(left_spring)
V_free = compute_lyapunov_function(deg_V=2, deg_L=2)
V_cart_left = compute_lyapunov_function(deg_V=2, deg_L=2, mode="cart_left")
V_cart_right = compute_lyapunov_function(deg_V=2, deg_L=2, mode="cart_right")
V_pole_left = compute_lyapunov_function(deg_V=2, deg_L=2, mode="pole_left")
V_pole_right = compute_lyapunov_function(deg_V=2, deg_L=2, mode="pole_right")
Vs = [V_free, V_cart_left, V_pole_left, V_cart_right, V_pole_right]
#Vs = [V_free, V_free, V_free, V_free, V_free]
"""
V_free, V_cart_left = function_fuser.fuse_functions(V_free, V_cart_left)
V_free, V_pole_left = function_fuser.fuse_functions(V_free, V_pole_left)
V_free, V_cart_right = function_fuser.fuse_functions(V_free, V_cart_right)
V_free, V_pole_right = function_fuser.fuse_functions(V_free, V_pole_right)
"""
cost_to_gos = [V.ToExpression() for V in Vs]
builder = DiagramBuilder()
plant, scene_graph = AddMultibodyPlantSceneGraph(builder, time_step=0.0)
cartpole = Parser(plant).AddModelFromFile("cart_pole.sdf")
setup_walls(plant)
plant.Finalize()
# Setup visualization
visualizer = ConnectMeshcatVisualizer(
builder,
scene_graph=scene_graph,
zmq_url="new")
visualizer.vis.delete()
#visualizer.set_planar_viewpoint(xmin=-2.5, xmax=2.5, ymin=-1.0, ymax=2.5)
#controller = builder.AddSystem(CartpoleController(plant))
controller = builder.AddSystem(LyapunovCartpoleController(plant, cost_to_gos))
builder.Connect(plant.get_state_output_port(), controller.get_input_port(0))
builder.Connect(controller.get_output_port(0),plant.get_actuation_input_port())
diagram = builder.Build()
# Set up a simulator to run this diagram
simulator = Simulator(diagram)
context = simulator.get_mutable_context()
plant_context = plant.GetMyContextFromRoot(context)
#plant.get_actuation_input_port(cartpole).FixValue(plant_context, np.array([0]))
# Set the initial conditions
context.SetContinuousState([-1.0, np.pi - 0.5, -spring_length, spring_length, 0.0, 0.0, 0, 0.00]) # x, theta, wall1, wall2, xdot, thetadot, wall1dot, wall2dot
context.SetTime(0.0)
visualizer.start_recording()
simulator.AdvanceTo(25.5)
visualizer.publish_recording()
visualizer.vis.render_static()
print("on input")
input()
pickle.dump([controller.x_history, controller.theta_history], open("traj_data/notfused.p", "wb"))
"""
plt.plot(controller.theta_dots)
plt.plot(controller.thetas)
plt.plot(controller.energies)
"""
"""
plt.title("trajectory of cartpole (optimizied policy)")
plt.plot([0], [np.pi], 'o', color='g')
plt.plot([-1.0], [np.pi - 0.5], 'o', color='r')
plt.xlabel("x position")
plt.ylabel("theta")
plt.plot(controller.x_history, controller.theta_history)
plt.show()
"""