[535f03]: / osim / env / legacy / osim.py

Download this file

196 lines (152 with data), 5.6 kB

  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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import opensim
import math
import numpy as np
import os
from .utils.mygym import convert_to_gym
import gym
class Osim(object):
# Initialize simulation
model = None
state = None
state0 = None
joints = []
bodies = []
brain = None
maxforces = []
curforces = []
def __init__(self, model_path, visualize):
self.model = opensim.Model(model_path)
self.model.initSystem()
self.brain = opensim.PrescribedController()
# Enable the visualizer
self.model.setUseVisualizer(visualize)
self.muscleSet = self.model.getMuscles()
self.forceSet = self.model.getForceSet()
self.bodySet = self.model.getBodySet()
self.jointSet = self.model.getJointSet()
self.contactGeometrySet = self.model.getContactGeometrySet()
for j in range(self.muscleSet.getSize()):
func = opensim.Constant(1.0)
self.brain.addActuator(self.muscleSet.get(j))
self.brain.prescribeControlForActuator(j, func)
self.maxforces.append(self.muscleSet.get(j).getMaxIsometricForce())
self.curforces.append(1.0)
self.model.addController(self.brain)
def set_strength(self, strength):
self.curforces = strength
for i in range(len(self.curforces)):
self.muscleSet.get(i).setMaxIsometricForce(self.curforces[i] * self.maxforces[i])
def get_body(self, name):
return self.bodySet.get(name)
def get_joint(self, name):
return self.jointSet.get(name)
def get_muscle(self, name):
return self.muscleSet.get(name)
def get_contact_geometry(self, name):
return self.contactGeometrySet.get(name)
def get_force(self, name):
return self.forceSet.get(name)
def initializeState(self):
self.state = self.model.initializeState()
def revert(self, state):
self.state = state
class Spec(object):
def __init__(self, *args, **kwargs):
self.id = 0
self.timestep_limit = 1000
class OsimEnv(gym.Env):
stepsize = 0.01
integration_accuracy = 1e-3
timestep_limit = 1000
test = False
action_space = None
observation_space = None
osim_model = None
istep = 0
model_path = ""
visualize = False
ninput = 0
noutput = 0
last_action = None
spec = None
metadata = {
'render.modes': ['human'],
'video.frames_per_second' : 50
}
def __getstate__(self):
state = self.__dict__.copy()
del state['osim_model']
print ("HERE1")
return state
def __setstate__(self, newstate):
self.__dict__.update(newstate)
self.osim_model = Osim(self.model_path, True)
self.configure()
def angular_dist(self, t,s):
x = (t-s) % (2*math.pi)
return min(x, 2*math.pi-x)
def compute_reward(self):
return 0.0
def is_done(self):
return False
def terminate(self):
pass
def __init__(self, visualize = True, noutput = None):
self.visualize = visualize
self.osim_model = Osim(self.model_path, self.visualize)
self.noutput = noutput
if not noutput:
self.noutput = self.osim_model.muscleSet.getSize()
if not self.action_space:
self.action_space = ( [0.0] * self.noutput, [1.0] * self.noutput )
if not self.observation_space:
self.observation_space = ( [-math.pi] * self.ninput, [math.pi] * self.ninput )
self.action_space = convert_to_gym(self.action_space)
self.observation_space = convert_to_gym(self.observation_space)
self.spec = Spec()
self.horizon = self.spec.timestep_limit
self.configure()
# self.reset()
def configure(self):
pass
super(OsimEnv, self).reset()
self.istep = 0
self.osim_model.initializeState()
return self.get_observation()
def sanitify(self, x):
if math.isnan(x):
return 0.0
BOUND = 1000.0
if x > BOUND:
x = BOUND
if x < -BOUND:
x = -BOUND
return x
def activate_muscles(self, action):
if np.any(np.isnan(action)):
raise ValueError("NaN passed in the activation vector. Values in [0,1] interval are required.")
action = np.clip(action, 0.0, 1.0)
self.last_action = action
brain = opensim.PrescribedController.safeDownCast(self.osim_model.model.getControllerSet().get(0))
functionSet = brain.get_ControlFunctions()
for j in range(functionSet.getSize()):
func = opensim.Constant.safeDownCast(functionSet.get(j))
func.setValue( float(action[j]) )
def step(self, action):
self.activate_muscles(action)
# Integrate one step
if self.istep == 0:
print ("Initializing the model!")
self.manager = opensim.Manager(self.osim_model.model)
self.osim_model.state.setTime(self.stepsize * self.istep)
self.manager.initialize(self.osim_model.state)
try:
self.osim_model.state = self.manager.integrate(self.stepsize * (self.istep + 1))
except Exception as e:
print (e)
return self.get_observation(), -500, True, {}
self.istep = self.istep + 1
res = [ self.get_observation(), self.compute_reward(), self.is_done(), {} ]
return res
def render(self, mode='human', close=False):
pass