[794894]: / feasible_joint_stiffness / opensim_utils.py

Download this file

309 lines (265 with data), 10.7 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# \brief A variety of useful OpenSim utilities.
#
# @author Dimitar Stanev (jimstanev@gmail.com)
#
import os
import opensim
from tqdm import tqdm
import numpy as np
from util import plot_sto
def calculate_muscle_data(model_file, ik_file):
"""This function calculates the moment arm and maximum muscle force provided an
OpenSim model and a motion from inverse kinematics.
Parameters
----------
model_file: string
OpenSim .osim file
ik_file: string
.mot from inverse kinematics
Returns
-------
tuple:
(moment arm[time x coordinates x muscles], max_force[time x muscles])
"""
model = opensim.Model(model_file)
state = model.initSystem()
# model coordinates dictionary
model_coordinates = {}
for i in range(0, model.getNumCoordinates()):
model_coordinates[model.getCoordinateSet().get(i).getName()] = i
# model muscles dictionary
model_muscles = {}
for i in range(0, model.getNumControls()):
model_muscles[model.getMuscles().get(i).getName()] = i
# process the motion
motion = opensim.Storage(ik_file)
labels = motion.getColumnLabels()
isInDeg = motion.isInDegrees()
# calculate moment arm and max force
max_force = np.empty([motion.getSize(), len(model_muscles)], float)
moment_arm = np.empty([motion.getSize(),
len(model_coordinates),
len(model_muscles)],
float)
for t in tqdm(range(0, motion.getSize())):
state_vector = motion.getStateVector(t)
state_data = state_vector.getData()
# update model pose
for j in range(0, state_data.getSize()):
coordinate = model_coordinates[labels.get(j + 1)] # time is 0
if isInDeg:
value = np.deg2rad(state_data.get(j))
else:
value = state_data.get(j)
model.updCoordinateSet().get(coordinate).setValue(state, value)
model.realizePosition(state)
# calculate muscle moment arm
for coordinate_index in model_coordinates.values():
for muscle_index in model_muscles.values():
coordinate = model.getCoordinateSet().get(coordinate_index)
muscle = model.getMuscles().get(muscle_index)
ma = muscle.computeMomentArm(state, coordinate)
moment_arm[t, coordinate_index, muscle_index] = ma
# calculate max force (TODO use force-length/velocity relations)
for muscle_index in model_muscles.values():
muscle = model.getMuscles().get(muscle_index)
max_force[t, muscle_index] = muscle.getMaxIsometricForce()
return (moment_arm, max_force)
def construct_ik_task_set(model, marker_data, task_set):
"""Construct OpenSim Inverse Kinematics task set.
In older versions of OpenSim (e.g. 3.3) IK will not execute when there are
virtual markers that do not exist in the marker data.
"""
virtual_markers = model.getMarkerSet()
marker_names = marker_data.getMarkerNames()
for i in range(0, marker_names.getSize()):
marker_name = marker_names.get(i)
exists = False
for j in range(0, virtual_markers.getSize()):
if virtual_markers.get(j).getName() == marker_name:
task = opensim.IKMarkerTask()
task.setName(marker_name)
task.setApply(True)
task.setWeight(1)
task_set.adoptAndAppend(task)
exists = True
break
if not exists:
task = opensim.IKMarkerTask()
task.setName(marker_name)
task.setApply(False)
task.setWeight(1)
task_set.adoptAndAppend(task)
def perform_ik(model_file, trc_file, results_dir):
"""Performs Inverse Kinematics using OpenSim.
Parameters
----------
model_file: str
OpenSim model (.osim)
trc_file: str
the experimentally measured marker trajectories (.trc)
results_dir: str
directory to store the results
"""
model = opensim.Model(model_file)
model.initSystem()
marker_data = opensim.MarkerData(trc_file)
name = os.path.basename(trc_file)[:-4]
ik_tool = opensim.InverseKinematicsTool()
task_set = ik_tool.getIKTaskSet()
construct_ik_task_set(model, marker_data, task_set)
ik_tool.setName(name)
ik_tool.setModel(model)
ik_tool.setStartTime(marker_data.getStartFrameTime())
ik_tool.setEndTime(marker_data.getLastFrameTime())
ik_tool.setMarkerDataFileName(trc_file)
ik_tool.setResultsDir(results_dir)
ik_file = results_dir + name + '_ik.mot'
ik_tool.setOutputMotionFileName(ik_file)
ik_tool.run()
return ik_file
def visualize_ik_results(ik_file, ik_errors=None):
"""A utility for visualizing the Inverse Kinematics results.
Parameters
----------
ik_file: str
coordinate results from IK (.mot)
ik_errors: str, optional
marker errors (.sto)
"""
plot_sto(ik_file, 4)
if ik_errors is not None:
plot_sto(ik_errors, 3)
def perform_so(model_file, ik_file, grf_file, grf_xml, reserve_actuators,
results_dir):
"""Performs Static Optimization using OpenSim.
Parameters
----------
model_file: str
OpenSim model (.osim)
ik_file: str
kinematics calculated from Inverse Kinematics
grf_file: str
the ground reaction forces
grf_xml: str
xml description containing how to apply the GRF forces
reserve_actuators: str
path to the reserve actuator .xml file
results_dir: str
directory to store the results
"""
# model
model = opensim.Model(model_file)
# prepare external forces xml file
name = os.path.basename(grf_file)[:-8]
external_loads = opensim.ExternalLoads(model, grf_xml)
external_loads.setExternalLoadsModelKinematicsFileName(ik_file)
external_loads.setDataFileName(grf_file)
external_loads.setLowpassCutoffFrequencyForLoadKinematics(6)
external_loads.printToXML(results_dir + name + '.xml')
# add reserve actuators
force_set = opensim.ForceSet(model, reserve_actuators)
force_set.setMemoryOwner(False) # model will be the owner
for i in range(0, force_set.getSize()):
model.updForceSet().append(force_set.get(i))
# construct static optimization
motion = opensim.Storage(ik_file)
static_optimization = opensim.StaticOptimization()
static_optimization.setStartTime(motion.getFirstTime())
static_optimization.setEndTime(motion.getLastTime())
static_optimization.setUseModelForceSet(True)
static_optimization.setUseMusclePhysiology(True)
static_optimization.setActivationExponent(2)
static_optimization.setConvergenceCriterion(0.0001)
static_optimization.setMaxIterations(100)
model.addAnalysis(static_optimization)
# analysis
analysis = opensim.AnalyzeTool(model)
analysis.setName(name)
analysis.setModel(model)
analysis.setInitialTime(motion.getFirstTime())
analysis.setFinalTime(motion.getLastTime())
analysis.setLowpassCutoffFrequency(6)
analysis.setCoordinatesFileName(ik_file)
analysis.setExternalLoadsFileName(results_dir + name + '.xml')
analysis.setLoadModelAndInput(True)
analysis.setResultsDir(results_dir)
analysis.run()
so_force_file = results_dir + name + '_StaticOptimization_force.sto'
so_activations_file = results_dir + name + \
'_StaticOptimization_activation.sto'
return (so_force_file, so_activations_file)
def visualize_so_results(activations_file, forces_file=None):
"""A utility for visualizing the Static Optimization results.
Parameters
----------
activations_file: str
activations results from SO (.sto)
forces_file: str, optional
forces (.sto)
"""
plot_sto(activations_file, 8, '_r')
if forces_file is not None:
plot_sto(forces_file, 8, '_r')
def perform_jra(model_file, ik_file, grf_file, grf_xml, reserve_actuators,
muscle_forces_file, results_dir, prefix=''):
"""Performs Static Optimization using OpenSim.
Parameters
----------
model_file: str
OpenSim model (.osim)
ik_file: str
kinematics calculated from Inverse Kinematics
grf_file: str
the ground reaction forces
grf_xml: str
xml description containing how to apply the GRF forces
reserve_actuators: str
path to the reserve actuator .xml file
muscle_forces_file: str
path to the file containing the muscle forces from SO
results_dir: str
directory to store the results
prefix: str
prefix of the resultant joint reaction loads
"""
# model
model = opensim.Model(model_file)
# prepare external forces xml file
name = os.path.basename(grf_file)[:-8]
external_loads = opensim.ExternalLoads(model, grf_xml)
external_loads.setExternalLoadsModelKinematicsFileName(ik_file)
external_loads.setDataFileName(grf_file)
external_loads.setLowpassCutoffFrequencyForLoadKinematics(6)
external_loads.printToXML(results_dir + name + '.xml')
# TODO this may not be needed
# add reserve actuators (must not be appended when performing JRA)
# force_set = opensim.ForceSet(model, reserve_actuators)
# force_set.setMemoryOwner(False) # model will be the owner
# for i in range(0, force_set.getSize()):
# model.updForceSet().append(force_set.get(i))
# # model.addForce(force_set.get(i))
# construct joint reaction analysis
motion = opensim.Storage(ik_file)
joint_reaction = opensim.JointReaction(model)
joint_reaction.setName('JointReaction')
joint_reaction.setStartTime(motion.getFirstTime())
joint_reaction.setEndTime(motion.getLastTime())
joint_reaction.setForcesFileName(muscle_forces_file)
model.addAnalysis(joint_reaction)
model.initSystem()
# analysis
analysis = opensim.AnalyzeTool(model)
analysis.setName(prefix + name)
analysis.setModel(model)
analysis.setModelFilename(model_file)
analysis.setInitialTime(motion.getFirstTime())
analysis.setFinalTime(motion.getLastTime())
analysis.setLowpassCutoffFrequency(6)
analysis.setCoordinatesFileName(ik_file)
analysis.setExternalLoadsFileName(results_dir + name + '.xml')
analysis.setLoadModelAndInput(True)
analysis.setResultsDir(results_dir)
analysis.run()
jra_file = results_dir + name + '_JointReaction_ReactionLoads.sto'
return jra_file