-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextras.py
1853 lines (1565 loc) · 77.4 KB
/
extras.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import numpy as np
import pylab as pl
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['mathtext.fontset'] = 'cm'
plt.rcParams['mathtext.rm'] = 'serif'
import osimpipeline as osp
from osimpipeline import utilities as util
from osimpipeline import postprocessing as pp
from matplotlib import colors as mcolors
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
class TaskMRSDeGrooteGenericMTParamsSetup(osp.TaskMRSDeGrooteSetup):
REGISTRY = []
def __init__(self, trial, cost='Default', **kwargs):
super(TaskMRSDeGrooteGenericMTParamsSetup, self).__init__(trial,
cost=cost, alt_tool_name='mrs_genericMTparams', **kwargs)
self.scaled_generic_model = os.path.join(
self.study.config['results_path'], 'experiments',
self.subject.name, '%s.osim' % self.subject.name)
self.file_dep += [self.scaled_generic_model]
def fill_setup_template(self, file_dep, target,
init_time=None, final_time=None):
with open(file_dep[0]) as ft:
content = ft.read()
content = content.replace('@STUDYNAME@', self.study.name)
content = content.replace('@NAME@', self.tricycle.id)
# TODO should this be an RRA-adjusted model?
content = content.replace('@MODEL@', os.path.relpath(
self.scaled_generic_model, self.path))
content = content.replace('@REL_PATH_TO_TOOL@', os.path.relpath(
self.study.config['optctrlmuscle_path'], self.path))
# TODO provide slop on either side? start before the cycle_start?
# end after the cycle_end?
content = content.replace('@INIT_TIME@',
'%.5f' % init_time)
content = content.replace('@FINAL_TIME@',
'%.5f' % final_time)
content = content.replace('@IK_SOLUTION@',
self.rel_kinematics_file)
content = content.replace('@ID_SOLUTION@',
self.rel_kinetics_file)
content = content.replace('@SIDE@',
self.trial.primary_leg[0])
content = content.replace('@COST@', self.cost)
with open(target[0], 'w') as f:
f.write(content)
def construct_multiindex_tuples_for_subject(subject, conditions,
muscles=None, cycles_to_exclude=None):
''' Construct multiindex tuples and list of cycles for DataFrame indexing.
'''
multiindex_tuples = list()
cycles = list()
for cond_name in conditions:
cond = subject.get_condition(cond_name)
if not cond: continue
# We know there is only one overground trial, but perhaps it
# has not yet been added for this subject.
assert len(cond.trials) <= 1
if len(cond.trials) == 1:
trial = cond.trials[0]
for cycle in trial.cycles:
if cycle.name in cycles_to_exclude: continue
cycles.append(cycle)
if not muscles:
multiindex_tuples.append((
cycle.condition.name,
# This must be the full ID, not just the cycle
# name, because 'cycle01' from subject 1 has
# nothing to do with 'cycle01' from subject 2
# (whereas the 'walk2' condition for subject 1 is
# related to 'walk2' for subject 2).
cycle.id))
if muscles:
for mname in muscles:
multiindex_tuples.append((
cycle.condition.name,
cycle.id,
mname))
return multiindex_tuples, cycles
class TaskCalibrateParametersSetup(osp.SetupTask):
REGISTRY = []
def __init__(self, trial, param_dict, cost_dict, passive_precalibrate=False,
**kwargs):
super(TaskCalibrateParametersSetup, self).__init__('calibrate', trial,
**kwargs)
self.doc = "Create a setup file for a parameter calibration tool."
self.kinematics_file = os.path.join(self.trial.results_exp_path, 'ik',
'%s_%s_ik_solution.mot' % (self.study.name, self.trial.id))
self.rel_kinematics_file = os.path.relpath(self.kinematics_file,
self.path)
self.kinetics_file = os.path.join(self.trial.results_exp_path,
'id', 'results', '%s_%s_id_solution.sto' % (self.study.name,
self.trial.id))
self.rel_kinetics_file = os.path.relpath(self.kinetics_file,
self.path)
self.emg_file = os.path.join(self.trial.results_exp_path,
'expdata', 'emg.sto')
self.rel_emg_file = os.path.relpath(self.emg_file, self.path)
self.results_setup_fpath = os.path.join(self.path, 'setup.m')
self.results_output_fpath = os.path.join(self.path,
'%s_%s_calibrate.mat' % (self.study.name, self.tricycle.id))
self.param_dict = param_dict
self.cost_dict = cost_dict
self.passive_precalibrate = passive_precalibrate
# Fill out setup.m template and write to results directory
self.create_setup_action()
def create_setup_action(self):
self.add_action(
['templates/%s/setup.m' % self.tool],
[self.results_setup_fpath],
self.fill_setup_template,
init_time=self.init_time,
final_time=self.final_time,
)
def fill_setup_template(self, file_dep, target,
init_time=None, final_time=None):
with open(file_dep[0]) as ft:
content = ft.read()
possible_params = ['optimal_fiber_length', 'tendon_slack_length',
'pennation_angle', 'muscle_strain']
paramstr = ''
for param in possible_params:
if param in self.param_dict:
paramstr += param + ' = true;\n'
else:
paramstr += param + ' = false;\n'
possible_costs = ['emg']
coststr = ''
for cost in possible_costs:
if cost in self.cost_dict:
coststr += cost + ' = true;\n'
else:
coststr += cost + ' = false;\n'
pass_cal = ''
if self.passive_precalibrate:
pass_cal = 'Misc.passive_precalibrate = true;\n'
content = content.replace('Misc = struct();',
'Misc = struct();\n' + paramstr + coststr + pass_cal + '\n')
content = content.replace('@STUDYNAME@', self.study.name)
content = content.replace('@NAME@', self.tricycle.id)
# TODO should this be an RRA-adjusted model?
content = content.replace('@MODEL@', os.path.relpath(
self.subject.scaled_model_fpath, self.path))
content = content.replace('@REL_PATH_TO_TOOL@', os.path.relpath(
self.study.config['optctrlmuscle_path'], self.path))
# TODO provide slop on either side? start before the cycle_start?
# end after the cycle_end?
content = content.replace('@INIT_TIME@',
'%.5f' % init_time)
content = content.replace('@FINAL_TIME@',
'%.5f' % final_time)
content = content.replace('@IK_SOLUTION@',
self.rel_kinematics_file)
content = content.replace('@ID_SOLUTION@',
self.rel_kinetics_file)
content = content.replace('@SIDE@',
self.trial.primary_leg[0])
content = content.replace('@EMG_PATH@', self.rel_emg_file)
if 'optimal_fiber_length' in self.param_dict:
content = content.replace('@lMo_MUSCLES@',
','.join(self.param_dict['optimal_fiber_length']))
if 'tendon_slack_length' in self.param_dict:
content = content.replace('@lTs_MUSCLES@',
','.join(self.param_dict['tendon_slack_length']))
if 'pennation_angle' in self.param_dict:
content = content.replace('@alf_MUSCLES@',
','.join(self.param_dict['pennation_angle']))
if 'muscle_strain' in self.param_dict:
content = content.replace('@e0_MUSCLES@',
','.join(self.param_dict['muscle_strain']))
if 'emg' in self.cost_dict:
content = content.replace('@emg_MUSCLES@',
','.join(self.cost_dict['emg']))
with open(target[0], 'w') as f:
f.write(content)
class TaskCalibrateParameters(osp.ToolTask):
REGISTRY = []
def __init__(self, trial, calibrate_setup_task, **kwargs):
super(TaskCalibrateParameters, self).__init__(calibrate_setup_task,
trial, opensim=False, **kwargs)
self.doc = "Run parameter calibration tool via DeGroote MRS solver."
self.results_setup_fpath = calibrate_setup_task.results_setup_fpath
self.results_output_fpath = calibrate_setup_task.results_output_fpath
self.file_dep += [
self.results_setup_fpath,
self.subject.scaled_model_fpath,
# calibrate_setup_task.kinematics_file,
# calibrate_setup_task.kinetics_file,
calibrate_setup_task.emg_file,
]
self.actions += [
self.run_parameter_calibration,
self.delete_muscle_analysis_results,
]
self.targets += [
self.results_output_fpath
]
def run_parameter_calibration(self):
with util.working_directory(self.path):
# On Mac, CmdAction was causing MATLAB ipopt with GPOPS output to
# not display properly.
status = os.system('matlab %s -logfile matlab_log.txt -wait -r "try, '
"run('%s'); disp('SUCCESS'); "
'catch ME; disp(getReport(ME)); exit(2), end, exit(0);"\n'
% ('-automation' if os.name == 'nt' else '',
self.results_setup_fpath)
)
if status != 0:
# print 'Non-zero exist status. Continuing....'
raise Exception('Non-zero exit status.')
# Wait until output mat file exists to finish the action
import time
while True:
time.sleep(3.0)
mat_exists = os.path.isfile(self.results_output_fpath)
if mat_exists:
break
def delete_muscle_analysis_results(self):
if os.path.exists(os.path.join(self.path, 'results')):
import shutil
shutil.rmtree(os.path.join(self.path, 'results'))
class TaskCalibrateParametersPost(osp.PostTask):
REGISTRY = []
def __init__(self, trial, calibrate_setup_task, **kwargs):
super(TaskCalibrateParametersPost, self).__init__(calibrate_setup_task,
trial, **kwargs)
self.doc = 'Postprocessing of parameter calibration results.'
self.setup_task = calibrate_setup_task
self.results_output_fpath = self.setup_task.results_output_fpath
self.emg_fpath = os.path.join(trial.results_exp_path, 'expdata',
'emg_with_headers.sto')
self.add_action([self.emg_fpath,
self.results_output_fpath],
[os.path.join(self.path, 'muscle_activity'),
os.path.join(self.path, 'reserve_activity.pdf')],
self.plot_muscle_and_reserve_activity)
self.add_action([self.results_output_fpath],
[os.path.join(self.path, 'optimal_fiber_length.pdf'),
os.path.join(self.path, 'tendon_slack_length.pdf'),
os.path.join(self.path, 'pennation_angle.pdf'),
os.path.join(self.path, 'muscle_strain.pdf')],
self.plot_muscle_parameters)
def plot_muscle_and_reserve_activity(self, file_dep, target):
emg = util.storage2numpy(file_dep[0])
time = emg['time']
def min_index(vals):
idx, val = min(enumerate(vals), key=lambda p: p[1])
return idx
start_idx = min_index(abs(time-self.setup_task.cycle.start))
end_idx = min_index(abs(time-self.setup_task.cycle.end))
# Load mat file fields
muscle_names = util.hdf2list(file_dep[1], 'MuscleNames', type=str)
df_exc = util.hdf2pandas(file_dep[1], 'MExcitation', labels=muscle_names)
df_act = util.hdf2pandas(file_dep[1], 'MActivation', labels=muscle_names)
dof_names = util.hdf2list(file_dep[1], 'DatStore/DOFNames',
type=str)
pgc_emg = np.linspace(0, 100, len(time[start_idx:end_idx]))
pgc_exc = np.linspace(0, 100, len(df_exc.index))
pgc_act = np.linspace(0, 100, len(df_act.index))
muscles = self.study.muscle_names
fig = pl.figure(figsize=(12, 12))
nice_muscle_names_dict = self.study.nice_muscle_names_dict
emg_map = {
'med_gas_r': 'gasmed_r',
'glut_max2_r': 'glmax2_r',
'rect_fem_r': 'recfem_r',
'semimem_r': 'semimem_r',
'soleus_r': 'soleus_r',
'tib_ant_r': 'tibant_r',
'vas_int_r': 'vasmed_r',
}
emg_muscles = ['bflh_r', 'gaslat_r', 'gasmed_r', 'glmax1_r', 'glmax2_r',
'glmax3_r', 'glmed1_r', 'glmed2_r', 'glmed3_r',
'recfem_r', 'semimem_r', 'semiten_r', 'soleus_r',
'tibant_r', 'vaslat_r', 'vasmed_r']
for imusc, musc_name in enumerate(muscles):
side_len = np.ceil(np.sqrt(len(muscles)))
ax = fig.add_subplot(side_len, side_len, imusc + 1)
ax.axhline(color='k', linewidth=0.5, zorder=0)
y_exc = df_exc[musc_name]
y_act = df_act[musc_name]
exc_plot, = ax.plot(pgc_exc, y_exc, color='blue',
linestyle='--')
act_plot, = ax.plot(pgc_act, y_act, color='red',
linestyle='--')
handles = [exc_plot, act_plot ]
labels = ['%s exc.' % nice_muscle_names_dict[musc_name],
'%s act.' % nice_muscle_names_dict[musc_name]]
ax.legend(handles, labels)
if emg_map.get(musc_name):
y_emg = emg[emg_map[musc_name]]
ax.plot(pgc_emg, y_emg[start_idx:end_idx], color='black',
linestyle='-')
# ax.legend(frameon=False, fontsize=6)
ax.set_xlim(0, 100)
ax.set_ylim(0, 1.0)
ax.set_title(nice_muscle_names_dict[musc_name])
ax.set_xlabel('time (% gait cycle)')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
fig.tight_layout()
fig.savefig(target[0]+'.pdf')
fig.savefig(target[0]+'.png', dpi=600)
pl.close(fig)
# Plot reserve activity
df_res = util.hdf2pandas(file_dep[1],'RActivation', labels=dof_names)
pp.plot_reserve_activity(target[1], df_res)
def plot_muscle_parameters(self, file_dep, target):
lMo, lTs, alf, e0, musc_names = get_muscle_parameters_as_dict(
file_dep[0])
# Plot muscle parameters
def param_barplot(param_name, param, output_fpath):
fig = pl.figure(figsize=(11,6))
ax = fig.add_subplot(1,1,1)
musc_names = list(param.keys())
pos = np.arange(len(musc_names))
param_to_plot = [(val - 1.0)*100 for val in param.values()]
bar = ax.bar(pos, param_to_plot, color='green')
ax.set_xticks(pos)
ax.set_xticklabels(musc_names, fontsize=10)
ax.set_ylabel('Percent Change in ' + param_name, fontsize=12)
ax.set_ylim([-30, 30])
ax.set_yticks(np.linspace(-30, 30, 13))
ax.grid(which='both', axis='both', linestyle='--')
ax.set_axisbelow(True)
fig.tight_layout()
fig.savefig(output_fpath)
pl.close(fig)
if lMo:
param_barplot('Optimal Fiber Length', lMo, target[0])
if lTs:
param_barplot('Tendon Slack Length', lTs, target[1])
if alf:
param_barplot('Pennation Angle', alf, target[2])
if e0:
param_barplot('Muscle Strain', e0, target[3])
class TaskAggregateMuscleParameters(osp.SubjectTask):
"""Aggregate calibrated muscle parameters for a given subject."""
REGISTRY = []
def __init__(self, subject, param_dict,
conditions=['walk1','walk2','walk3'],
cycles_to_exclude=['cycle03']):
super(TaskAggregateMuscleParameters, self).__init__(subject)
self.name = '%s_aggregate_muscle_parameters' % self.subject.name
self.csv_fpaths = list()
self.csv_params = list()
self.param_dict = param_dict
self.conditions = conditions
self.cycles_to_exclude = cycles_to_exclude
for param in param_dict:
muscle_names = param_dict[param]
multiindex_tuples, cycles = construct_multiindex_tuples_for_subject(
self.subject, conditions, muscle_names, self.cycles_to_exclude)
# Prepare for processing simulations of experiments.
deps = list()
for cycle in cycles:
if cycle.name in cycles_to_exclude: continue
deps.append(os.path.join(
cycle.trial.results_exp_path, 'calibrate', cycle.name,
'%s_%s_calibrate.mat' % (self.study.name, cycle.id))
)
csv_path = os.path.join(self.subject.results_exp_path,
'%s_agg.csv' % param)
self.csv_params.append(param)
self.csv_fpaths.append(csv_path)
self.add_action(deps,
[csv_path],
self.aggregate_muscle_parameters, param, multiindex_tuples)
def aggregate_muscle_parameters(self, file_dep, target, param,
multiindex_tuples):
from collections import OrderedDict
muscle_params = OrderedDict()
for ifile, fpath in enumerate(file_dep):
lMo, lTs, alf, e0, musc_names = get_muscle_parameters_as_dict(fpath)
if not param in muscle_params:
muscle_params[param] = list()
for musc in self.param_dict[param]:
if param == 'optimal_fiber_length':
muscle_params[param].append(lMo[musc])
elif param == 'tendon_slack_length':
muscle_params[param].append(lTs[musc])
elif param == 'pennation_angle':
muscle_params[param].append(alf[musc])
elif param == 'muscle_strain':
muscle_params[param].append(e0[musc])
# http://pandas.pydata.org/pandas-docs/stable/advanced.html#advanced-hierarchical
index = pd.MultiIndex.from_tuples(multiindex_tuples,
names=['condition', 'cycle', 'muscle'])
df = pd.DataFrame(muscle_params, index=index)
target_dir = os.path.dirname(target[0])
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with file(target[0], 'w') as f:
f.write('# columns contain calibrated muscle parameters for '
'%s \n' % self.subject.name)
df.to_csv(f)
class TaskPlotMuscleParameters(osp.SubjectTask):
REGISTRY = []
def __init__(self, subject, agg_task, cycles_to_exclude=None, **kwargs):
super(TaskPlotMuscleParameters, self).__init__(subject)
self.name = '%s_plot_muscle_parameters' % subject.name
self.doc = 'Plot aggregated muscle parameters from calibration.'
self.agg_task = agg_task
self.cycles_to_exclude = cycles_to_exclude
for csv_fpath, param in zip(agg_task.csv_fpaths, agg_task.csv_params):
self.add_action([csv_fpath],
[os.path.join(self.subject.results_exp_path, param)],
self.plot_muscle_parameters, param)
def plot_muscle_parameters(self, file_dep, target, param):
# Process muscle parameters
df = pd.read_csv(file_dep[0], index_col=[0, 1, 2], skiprows=1)
if self.cycles_to_exclude:
for cycle in self.cycles_to_exclude:
for cond in self.agg_task.conditions:
cycle_id = '%s_%s_%s' % (self.subject.name, cond, cycle)
df.drop(cycle_id, level='cycle', inplace=True)
df_mean = df.mean(level='muscle')
df_std = df.std(level='muscle')
def param_barplot(param_name, param_mean, param_std, musc_names,
output_fpath):
fig = pl.figure(figsize=(11,6))
ax = fig.add_subplot(1,1,1)
pos = np.arange(len(musc_names))
param_mean_to_plot = [(val - 1.0)*100 for val in param_mean]
param_std_to_plot = [val*100 for val in param_std]
bar = ax.bar(pos, param_mean_to_plot, yerr=param_std_to_plot,
color='green')
ax.set_xticks(pos)
ax.set_xticklabels(musc_names, fontsize=10)
ax.set_ylabel('Percent Change in ' + param_name, fontsize=12)
ax.set_ylim([-30, 30])
ax.set_yticks(np.linspace(-30, 30, 13))
ax.grid(which='both', axis='both', linestyle='--')
ax.set_axisbelow(True)
fig.tight_layout()
fig.savefig(output_fpath)
pl.close(fig)
if param == 'optimal_fiber_length':
lMo_mean = df_mean['optimal_fiber_length']
lMo_std = df_std['optimal_fiber_length']
param_barplot('Optimal Fiber Length', lMo_mean, lMo_std,
lMo_mean.index, target[0]+'.pdf')
lMo_mean.to_csv(target[0]+'.csv')
if param == 'tendon_slack_length':
lTs_mean = df_mean['tendon_slack_length']
lTs_std = df_std['tendon_slack_length']
param_barplot('Tendon Slack Length', lTs_mean, lTs_std,
lTs_mean.index, target[0]+'.pdf')
lTs_mean.to_csv(target[0]+'.csv')
if param == 'pennation_angle':
alf_mean = df_mean['pennation_angle']
alf_std = df_std['pennation_angle']
param_barplot('Pennation Angle', alf_mean, alf_std,
alf_mean.index, target[0]+'.pdf')
alf_mean.to_csv(target[0]+'.csv')
if param == 'muscle_strain':
e0_mean = df_mean['muscle_strain']
e0_std = df_std['muscle_strain']
param_barplot('Muscle Strain', e0_mean, e0_std,
e0_mean.index, target[0]+'.pdf')
e0_mean.to_csv(target[0]+'.csv')
class TaskFitOptimizedExoSetup(osp.SetupTask):
REGISTRY = []
def __init__(self, trial, mrsmod_task, param_info, fit, **kwargs):
super(TaskFitOptimizedExoSetup, self).__init__('fitopt', trial, **kwargs)
self.doc = 'Setup optimized exoskeleton torque fitting.'
self.mrsmod_task = mrsmod_task
self.fit = fit
self.name = '%s_%s_%s_%s_setup_%s' % (trial.id, self.tool, self.fit,
self.mrsmod_task.mod_name.replace('mrsmod_',''), self.cycle.name)
if not (self.mrsmod_task.cost == 'Default'):
self.name += '_%s' % self.mrsmod_task.cost
self.min_param = param_info['min_param']
self.max_param = param_info['max_param']
self.start_time = 0
if hasattr(self.tricycle, 'fit_start_time'):
self.start_time = self.tricycle.fit_start_time
self.mrs_setup_task = self.mrsmod_task.mrs_setup_task
self.path = os.path.join(self.study.config['results_path'],
'fitopt_%s_%s' % (self.fit,
self.mrsmod_task.mod_name.replace('mrsmod_','')),
'fitopt', trial.rel_path,
self.mrs_setup_task.cycle.name if self.mrs_setup_task.cycle else '',
self.mrsmod_task.costdir)
self.mrsmod_output_fpath = mrsmod_task.results_output_fpath
if '_multControls' in self.mrsmod_output_fpath:
self.mrsmod_output_fpath = self.mrsmod_output_fpath.replace(
'_multControls', '')
self.results_setup_fpath = os.path.join(self.path, 'setup.m')
self.results_output_fpath = os.path.join(self.path, '%s_%s_fitopt_%s.mat' %
(self.study.name, self.tricycle.id, self.fit))
# Fill out setup.m template and write to results directory
self.create_setup_action()
def create_setup_action(self):
self.add_action(
['templates/%s/%s/setup.m' % (self.tool, self.fit)],
[self.results_setup_fpath],
self.fill_setup_template,
)
def fill_setup_template(self, file_dep, target):
self.add_setup_dir()
with open(file_dep[0]) as ft:
content = ft.read()
content = content.replace('@STUDYNAME@', self.study.name)
content = content.replace('@NAME@', self.tricycle.id)
content = content.replace('@REL_PATH_TO_TOOL@', os.path.relpath(
self.study.config['optctrlmuscle_path'], self.path))
content = content.replace('@FIT@', self.fit)
if not (self.fit == 'zhang2017'):
content = content.replace('@MIN_PARAM@', str(self.min_param))
content = content.replace('@MAX_PARAM@', str(self.max_param))
content = content.replace('@START_TIME@', str(self.start_time))
content = content.replace('@MRSMOD_OUTPUT@',
self.mrsmod_output_fpath)
content = content.replace('@MOD_NAME@', self.mrsmod_task.mod_name)
content = content.replace('@NORM_HIP_MAX_TORQUE@',
str(self.study.config['norm_hip_max_torque']))
content = content.replace('@NORM_KNEE_MAX_TORQUE@',
str(self.study.config['norm_knee_max_torque']))
content = content.replace('@NORM_ANKLE_MAX_TORQUE@',
str(self.study.config['norm_ankle_max_torque']))
with open(target[0], 'w') as f:
f.write(content)
def add_setup_dir(self):
if not os.path.exists(self.path): os.makedirs(self.path)
class TaskFitOptimizedExo(osp.ToolTask):
REGISTRY = []
def __init__(self, trial, fitopt_setup_task, **kwargs):
super(TaskFitOptimizedExo, self).__init__(fitopt_setup_task, trial,
opensim=False, **kwargs)
self.doc = 'Fit parameterized curve optimized exoskeleton torque curve.'
self.name = fitopt_setup_task.name.replace('_setup','')
self.results_setup_fpath = fitopt_setup_task.results_setup_fpath
self.results_output_fpath = fitopt_setup_task.results_output_fpath
self.file_dep += [self.results_setup_fpath]
self.actions += [self.run_fitting_script]
self.targets += [self.results_output_fpath]
def run_fitting_script(self):
with util.working_directory(self.path):
# On Mac, CmdAction was causing MATLAB ipopt with GPOPS output to
# not display properly.
status = os.system('matlab %s -logfile matlab_log.txt -wait -r "try, '
"run('%s'); disp('SUCCESS'); "
'catch ME; disp(getReport(ME)); exit(2), end, exit(0);"\n'
% ('-automation' if os.name == 'nt' else '',
self.results_setup_fpath)
)
if status != 0:
# print 'Non-zero exist status. Continuing....'
raise Exception('Non-zero exit status.')
# Wait until output mat file exists to finish the action
import time
while True:
time.sleep(3.0)
mat_exists = os.path.isfile(self.results_output_fpath)
if mat_exists:
break
def get_parameter_info(study, mod_name):
fixed_params = ['fix_peak_torque', 'fix_peak_time', 'fix_rise_time',
'fix_fall_time', 'fix_all_times', 'fix_all_torques']
for fixed_param in fixed_params:
if fixed_param in mod_name:
mod_name = mod_name.replace('_' + fixed_param, '')
param_bounds_all = study.config['param_bounds']
param_names = list()
param_bounds = dict()
param_bounds['lower'] = list()
param_bounds['upper'] = list()
param_names.append('peak torque')
peak_torque_bounds = param_bounds_all['peak_torque']
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('peak time')
peak_time_bounds = param_bounds_all['peak_time']
param_bounds['lower'].append(peak_time_bounds[0])
param_bounds['upper'].append(peak_time_bounds[1])
param_names.append('rise time')
rise_time_bounds = param_bounds_all['rise_time']
param_bounds['lower'].append(rise_time_bounds[0])
param_bounds['upper'].append(rise_time_bounds[1])
param_names.append('fall time')
fall_time_bounds = param_bounds_all['fall_time']
param_bounds['lower'].append(fall_time_bounds[0])
param_bounds['upper'].append(fall_time_bounds[1])
if 'fitreopt_zhang2017_actHfAp' == mod_name:
param_names.append('ankle peak torque')
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
elif 'fitreopt_zhang2017_actHfKf' == mod_name:
param_names.append('knee peak torque')
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
elif 'fitreopt_zhang2017_actKfAp' == mod_name:
param_names.append('ankle peak torque')
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
elif 'fitreopt_zhang2017_actHfKfAp' == mod_name:
param_names.append('knee peak torque')
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('ankle peak torque')
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
elif 'fitreopt_zhang2017_actHeKe' == mod_name:
param_names.append('knee peak torque')
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
if 'fitreopt_zhang2017_actHfAp_multControls' == mod_name:
param_names.append('peak torque 2')
peak_torque_bounds = param_bounds_all['peak_torque']
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('peak time 2')
peak_time_bounds = param_bounds_all['peak_time']
param_bounds['lower'].append(peak_time_bounds[0])
param_bounds['upper'].append(peak_time_bounds[1])
param_names.append('rise time 2')
rise_time_bounds = param_bounds_all['rise_time']
param_bounds['lower'].append(rise_time_bounds[0])
param_bounds['upper'].append(rise_time_bounds[1])
param_names.append('fall time 2')
fall_time_bounds = param_bounds_all['fall_time']
param_bounds['lower'].append(fall_time_bounds[0])
param_bounds['upper'].append(fall_time_bounds[1])
elif 'fitreopt_zhang2017_actHfKf_multControls' == mod_name:
param_names.append('peak torque 2')
peak_torque_bounds = param_bounds_all['peak_torque']
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('peak time 2')
peak_time_bounds = param_bounds_all['peak_time']
param_bounds['lower'].append(peak_time_bounds[0])
param_bounds['upper'].append(peak_time_bounds[1])
param_names.append('rise time 2')
rise_time_bounds = param_bounds_all['rise_time']
param_bounds['lower'].append(rise_time_bounds[0])
param_bounds['upper'].append(rise_time_bounds[1])
param_names.append('fall time 2')
fall_time_bounds = param_bounds_all['fall_time']
param_bounds['lower'].append(fall_time_bounds[0])
param_bounds['upper'].append(fall_time_bounds[1])
elif 'fitreopt_zhang2017_actKfAp_multControls' == mod_name:
param_names.append('peak torque 2')
peak_torque_bounds = param_bounds_all['peak_torque']
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('peak time 2')
peak_time_bounds = param_bounds_all['peak_time']
param_bounds['lower'].append(peak_time_bounds[0])
param_bounds['upper'].append(peak_time_bounds[1])
param_names.append('rise time 2')
rise_time_bounds = param_bounds_all['rise_time']
param_bounds['lower'].append(rise_time_bounds[0])
param_bounds['upper'].append(rise_time_bounds[1])
param_names.append('fall time 2')
fall_time_bounds = param_bounds_all['fall_time']
param_bounds['lower'].append(fall_time_bounds[0])
param_bounds['upper'].append(fall_time_bounds[1])
elif 'fitreopt_zhang2017_actHfKfAp_multControls' == mod_name:
param_names.append('peak torque 2')
peak_torque_bounds = param_bounds_all['peak_torque']
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('peak time 2')
peak_time_bounds = param_bounds_all['peak_time']
param_bounds['lower'].append(peak_time_bounds[0])
param_bounds['upper'].append(peak_time_bounds[1])
param_names.append('rise time 2')
rise_time_bounds = param_bounds_all['rise_time']
param_bounds['lower'].append(rise_time_bounds[0])
param_bounds['upper'].append(rise_time_bounds[1])
param_names.append('fall time 2')
fall_time_bounds = param_bounds_all['fall_time']
param_bounds['lower'].append(fall_time_bounds[0])
param_bounds['upper'].append(fall_time_bounds[1])
param_names.append('peak torque 3')
peak_torque_bounds = param_bounds_all['peak_torque']
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('peak time 3')
peak_time_bounds = param_bounds_all['peak_time']
param_bounds['lower'].append(peak_time_bounds[0])
param_bounds['upper'].append(peak_time_bounds[1])
param_names.append('rise time 3')
rise_time_bounds = param_bounds_all['rise_time']
param_bounds['lower'].append(rise_time_bounds[0])
param_bounds['upper'].append(rise_time_bounds[1])
param_names.append('fall time 3')
fall_time_bounds = param_bounds_all['fall_time']
param_bounds['lower'].append(fall_time_bounds[0])
param_bounds['upper'].append(fall_time_bounds[1])
elif 'fitreopt_zhang2017_actHeKe_multControls' == mod_name:
param_names.append('peak torque 2')
peak_torque_bounds = param_bounds_all['peak_torque']
param_bounds['lower'].append(peak_torque_bounds[0])
param_bounds['upper'].append(peak_torque_bounds[1])
param_names.append('peak time 2')
peak_time_bounds = param_bounds_all['peak_time']
param_bounds['lower'].append(peak_time_bounds[0])
param_bounds['upper'].append(peak_time_bounds[1])
param_names.append('rise time 2')
rise_time_bounds = param_bounds_all['rise_time']
param_bounds['lower'].append(rise_time_bounds[0])
param_bounds['upper'].append(rise_time_bounds[1])
param_names.append('fall time 2')
fall_time_bounds = param_bounds_all['fall_time']
param_bounds['lower'].append(fall_time_bounds[0])
param_bounds['upper'].append(fall_time_bounds[1])
return param_names, param_bounds
class TaskAggregateTorqueParameters(osp.StudyTask):
REGISTRY = []
def __init__(self, study, mod, subjects=None,
cond_names=['walk1','walk2','walk3','walk4']):
super(TaskAggregateTorqueParameters, self).__init__(study)
self.mod_dir = mod.replace('/','\\\\')
if len(mod.split('/')) > 1:
self.mod_name = '_'.join(mod.split('/'))
else:
self.mod_name = mod
if not ('fitreopt' in self.mod_name):
Exception('Only "fitreopt" tasks accepted for this aggregate task.')
suffix = '_' + self.mod_name
cost = ''
self.costdir = ''
if not (study.costFunction == 'Default'):
suffix += '_%s' % study.costFunction
cost = '_' + study.costFunction
self.costdir = study.costFunction
self.name = 'aggregate_torque_parameters%s' % suffix
self.doc = 'Aggregate torque parameters into a data file.'
if subjects == None:
subjects = [s.name for s in study.subjects]
# Parameter names and bounds
self.param_names, self.param_bounds = \
get_parameter_info(study, self.mod_name)
self.cycles = dict()
self.output_fpaths = list()
for cond_name in cond_names:
self.cycles[cond_name] = list()
deps = []
for subject in study.subjects:
if not subject.name in subjects: continue
cond = subject.get_condition(cond_name)
if not cond: continue
# We know there is only one overground trial, but perhaps it
# has not yet been added for this subject.
assert len(cond.trials) <= 1
if len(cond.trials) == 1:
trial = cond.trials[0]
for cycle in trial.cycles:
if study.test_cycles:
if not (cycle.name in study.test_cycles):
continue
self.cycles[cond_name].append(cycle)
# Results MAT file paths
fpath = os.path.join(study.config['results_path'],
self.mod_dir, subject.name, cond.name, 'mrs',
cycle.name, self.costdir,
'%s_%s_mrs.mat' % (study.name, cycle.id))
deps.append(fpath)
output_fpath = os.path.join(study.config['results_path'],
self.mod_dir,'%s_%s_torque_parameters%s.csv' % (
self.mod_name, cond_name, cost))
self.output_fpaths += [output_fpath]
self.add_action([], [], self.aggregate_torque_parameters, cond_name,
deps, output_fpath)
def aggregate_torque_parameters(self, file_dep, target, cond_name, deps,
output_fpath):
subject_array = list()
cycle_array = list()
param_array = list()
all_parameters = list()
lower_bounds = list()
upper_bounds = list()
for icycle, fpath in enumerate(deps):
cycle = self.cycles[cond_name][icycle]
parametersScaled = util.hdf2numpy(fpath,
'OptInfo/result/solution/parameter')
paramsLowerBound = util.hdf2numpy(fpath,
'OptInfo/result/setup/auxdata/paramsLower')
paramsUpperBound = util.hdf2numpy(fpath,
'OptInfo/result/setup/auxdata/paramsUpper')
# Parameters were scaled between [-1,1] for optimizations. Now
# rescale them into values within original parameter value ranges.
# parameters = 0.5*np.multiply(paramsUpperBound-paramsLowerBound,
# parametersScaled + 1) + paramsLowerBound
parameters = parametersScaled
subject_array.append(cycle.subject.name)
cycle_array.append(cycle.id)
all_parameters.append(parameters[0])
lower_bounds.append(paramsLowerBound[0])
upper_bounds.append(paramsUpperBound[0])
all_parameters_array = np.array(all_parameters).transpose()
lower_bounds_array = np.array(lower_bounds).transpose()
upper_bounds_array = np.array(upper_bounds).transpose()
multiindex_arrays = [subject_array, cycle_array]
columns = pd.MultiIndex.from_arrays(multiindex_arrays,
names=['subject', 'cycle'])
all_parameters_df = pd.DataFrame(all_parameters_array, columns=columns,
index=self.param_names)
target_dir = os.path.dirname(output_fpath)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with file(output_fpath, 'w') as f:
f.write('# all columns are torque parameter.\n')
all_parameters_df.to_csv(f)
lower_bounds_df = pd.DataFrame(lower_bounds_array, columns=columns,
index=self.param_names)
lower_bounds_fpath = output_fpath.replace('torque_parameters',
'torque_parameters_lower_bound')
target_dir = os.path.dirname(lower_bounds_fpath)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with file(lower_bounds_fpath, 'w') as f:
f.write('# all columns are torque parameter lower bounds.\n')
lower_bounds_df.to_csv(f)
upper_bounds_df = pd.DataFrame(upper_bounds_array, columns=columns,
index=self.param_names)
upper_bounds_fpath = output_fpath.replace('torque_parameters',
'torque_parameters_upper_bound')
target_dir = os.path.dirname(upper_bounds_fpath)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with file(upper_bounds_fpath, 'w') as f:
f.write('# all columns are torque parameter upper bounds.\n')
upper_bounds_df.to_csv(f)
class TaskPlotTorqueParameters(osp.StudyTask):
REGISTRY = []
def __init__(self, study, agg_task):
super(TaskPlotTorqueParameters, self).__init__(study)
self.agg_task = agg_task
self.task_name = self.agg_task.mod_name if hasattr(self.agg_task,
'mod_name') else 'experiment'
suffix = '_' + self.task_name
self.costdir = ''
if not (study.costFunction == 'Default'):
suffix += '_%s' % study.costFunction
self.costdir = study.costFunction
self.name = 'plot_torque_parameters%s' % suffix
self.doc = 'Plot torque parameters'
for icond, agg_target in enumerate(agg_task.output_fpaths):
# This assumes csv_task.targets and csv_task.cycles hold cycles in