-
Notifications
You must be signed in to change notification settings - Fork 0
/
results.py
1711 lines (1585 loc) · 71.7 KB
/
results.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 pandas as pd
from glob import glob
from typing import List, Dict, Tuple, cast
from typing_extensions import Literal
import numpy as np
from scipy import signal
from pyomo.environ import value as pyovalue
import acinoset_misc as misc
import acinoset_opt as opt
import shared.physical_education as pe
from common.py_utils import data_ops
from acinoset_models import PoseModelGMM
import json
def check_grf(robot: pe.system.System3D):
# This confirms that IPOPT is configured to ensure that one of the following is 0 - |x| = x^{+} + x^{-}.
for foot in pe.foot.feet(robot):
grfxy = foot["GRFxy"]
for fe, cp in robot.indices(one_based=True):
if grfxy[fe, 1, 0].value == 0.0 or grfxy[fe, 1, 1].value == 0.0:
# NOP - correct
pass
else:
print(f"Invalid state: {foot.name} ({fe})")
if grfxy[fe, 1, 2].value == 0.0 or grfxy[fe, 1, 3].value == 0.0:
# NOP - correct
pass
else:
print(f"Invalid state 2: {foot.name} ({fe})")
def plot_cost_functions():
import matplotlib.pyplot as plt
redesc_a, redesc_b, redesc_c = 3, 10, 20
# Plot
r_x = np.arange(-30, 30, 1e-1)
r_y1 = [misc.redescending_loss(i, redesc_a, redesc_b, redesc_c) for i in r_x]
r_y2 = abs(r_x)
r_y3 = r_x**2
fig = plt.figure(figsize=(6, 4), dpi=120)
plt.plot(r_x, r_y3, label="Quadratic")
plt.plot(r_x, r_y1, label="Redescending")
plt.xlabel("Error (pixels)")
plt.ylabel("Cost Value")
ax = plt.gca()
ax.set_ylim((-5, 50))
ax.legend()
plt.show(block=False)
fig.savefig("./data/cost-function.pdf", bbox_inches="tight")
plt.close()
def example_robustness(root_dir: str, dir_prefix: str):
import matplotlib.pyplot as plt
metrics = {
"single_traj_error": [],
"data_driven_traj_error": [],
"physics_based_traj_error": [],
}
test_run = ("phantom", "2019_03_07", "run")
cam_space = ((0, 1, 2, 3, 4, 5),)
for cam_idx in cam_space[0]:
# Configure trajectory.
cheetah = test_run[0]
date = test_run[1]
trial = test_run[2]
data_path = f"{date}/{cheetah}/{trial}"
print(f"{data_path}:")
# Read the scene data file and the reconstruction data.
multi_view_data = data_ops.load_pickle(os.path.join(dir_prefix, data_path, "fte_kinematic", "fte.pickle"))
# Ensure that the camera has been collected.
if not (
os.path.exists(os.path.join(dir_prefix, data_path, f"fte_kinematic_{cam_idx}"))
and os.path.exists(os.path.join(dir_prefix, data_path, f"fte_kinematic_orig_{cam_idx}"))
):
continue
single_view_data = data_ops.load_pickle(
os.path.join(dir_prefix, data_path, f"fte_kinematic_orig_{cam_idx}", "fte.pickle")
)
data_driven_data = data_ops.load_pickle(
os.path.join(dir_prefix, data_path, f"fte_kinematic_{cam_idx}", "fte.pickle")
)
physics_based_traj_error = []
for i in range(1):
physics_based_data = data_ops.load_pickle(
os.path.join(
dir_prefix, data_path, f"fte_kinetic_{cam_idx}", f"fte{i}.pickle" if i > 0 else "fte.pickle"
)
)
_, physics_based_traj_error_tmp, _ = misc.traj_error(
multi_view_data["positions"].copy(),
physics_based_data["positions"].copy(),
"physics-based model",
centered=True,
)
physics_based_traj_error.append(physics_based_traj_error_tmp)
physics_based_traj_error = np.mean(physics_based_traj_error, axis=0)
# physics_based_traj_error_std = np.std(physics_based_traj_error, axis=0)
# Calculate the trajectory error per bodypart.
_, single_traj_error, _ = misc.traj_error(
multi_view_data["positions"].copy(), single_view_data["positions"].copy(), centered=True
)
_, data_driven_traj_error, _ = misc.traj_error(
multi_view_data["positions"].copy(),
data_driven_data["positions"].copy(),
"data-driven model",
centered=True,
)
metrics["single_traj_error"].append(float(single_traj_error.mean()))
metrics["data_driven_traj_error"].append(float(data_driven_traj_error.mean()))
metrics["physics_based_traj_error"].append(float(physics_based_traj_error.mean()))
fig = plt.figure(figsize=(16, 12), dpi=120)
scenarios = ("1", "2", "3", "4", "5", "6")
width = 0.25 # the width of the bars
x = np.arange(len(scenarios))
rect1 = plt.bar(x, metrics["single_traj_error"], width, label="Default", color=misc.plot_color["charcoal"])
rect2 = plt.bar(
x + width, metrics["data_driven_traj_error"], width, label="Data-driven", color=misc.plot_color["green"]
)
rect3 = plt.bar(
x + 2 * width,
metrics["physics_based_traj_error"],
width,
label="Physics-based",
color=misc.plot_color["orange"],
)
plt.xticks(x + width, scenarios)
plt.ylabel("MPJPE (mm)")
plt.xlabel("Camera")
plt.legend()
fig.savefig(os.path.join(dir_prefix, "example-cam-robustness.pdf"), bbox_inches="tight")
plt.close()
def check_joint_estimation(root_dir: str, dir_prefix: str):
cheetah = "shiraz"
date = "2009_09_08"
trial = "04"
data_path = f"kinetic_dataset/{date}/{cheetah}/trial{trial}"
fte_gt = data_ops.load_pickle(os.path.join(dir_prefix, data_path, "fte_kinetic", "fte.pickle"))
fte = data_ops.load_pickle(os.path.join(root_dir, data_path, "fte_kinetic", "fte.pickle"))
single_view_mpjpe_mm, single_view_error, _ = misc.traj_error(fte_gt["positions"].copy(), fte["positions"].copy())
tau_gt = [list(k.ravel()) for k in fte_gt["tau"].values()]
tau = [list(k.ravel()) for k in fte["tau"].values()]
print(f"Torque RMSE: {misc.rmse(np.array(pe.utils.flatten(tau_gt)), np.array(pe.utils.flatten(tau)))}")
import matplotlib.pyplot as plt
from cycler import cycler
titles = (
"Tail base",
"Left back hip",
"Right back hip",
"Spine",
"Left front hip",
"Right front hip",
"Neck",
"Tail mid",
"Left front knee",
"Left front ankle",
"Right front knee",
"Right front ankle",
"Left back knee",
"Left back ankle",
"Right back knee",
"Right back ankle",
)
fig = plt.figure(figsize=(12, 32), dpi=120)
axs = fig.subplots(8, 2)
axs = axs.flatten()
for i, motor in enumerate(fte_gt["tau"].keys()):
axs[i].set_prop_cycle(
cycler("color", [misc.plot_color["orange"], misc.plot_color["green"], misc.plot_color["red"]])
)
axs[i].plot(fte_gt["tau"][motor], alpha=0.3)
axs[i].set_prop_cycle(
cycler("color", [misc.plot_color["orange"], misc.plot_color["green"], misc.plot_color["red"]])
)
axs[i].plot(fte["tau"][motor])
tau_err = misc.rmse(
np.array(pe.utils.flatten(fte_gt["tau"][motor])), np.array(pe.utils.flatten(fte["tau"][motor]))
)
axs[i].set_title(f"{titles[i]} ({tau_err:.3f})")
# fig.savefig(os.path.join(out_dir, "torque-profile.pdf"), bbox_inches="tight")
plt.show(block=False)
plt.close()
def contact_detection_analysis(root_dir: str, dir_prefix: str, kinetic_dataset: bool = False, monocular: bool = False):
# Need to get the 3rd camera for this set: ("arabia", "2009_09_08", "15")
# Can't get reliable kinematics for ("shiraz", "2009_09_08", "02") Not a major issue becaues the GRF data is corrupted for this test.
if kinetic_dataset:
test_set = (
("arabia", "2009_09_07", "06"),
("shiraz", "2009_09_07", "04"),
("shiraz", "2009_09_08", "04"),
("shiraz", "2009_09_11", "01"),
("shiraz", "2009_09_11", "02"),
)
else:
test_set = (
("jules", "2017_12_09/bottom", "flick2"),
("jules", "2019_03_09", "flick1"),
("phantom", "2019_03_03", "run"), # curve run (acceleration)
("phantom", "2017_08_29/top", "run1_1"), # straight run (steady-state slow)
# ("phantom", "2017_12_09/bottom", "run2"),
("jules", "2017_08_29/top", "run1_1"), # straight run (steady-state fast)
("jules", "2017_09_02/top", "run1"), # straight run (steady-state fast)
("phantom", "2017_09_02/top", "run1_2"), # straight run (deceleration)
("phantom", "2019_03_07", "run"), # straight run (steady-state slow)
("jules", "2017_08_29/top", "run1_2"), # straight run (deceleration/trot)
("jules", "2017_09_02/bottom", "run2"),
) # straight run (steady-state medium)
num_false_positives = 0
num_missed = 0
num_false_positives_tmp = 0
num_gt_contacts = 0
num_est_contacts = 0
num_est_contacts_tmp = 0
num_error = 0
num_error_tmp = 0
num_matched = 0
num_matched_tmp = 0
results = {
"total_contacts_points": 0,
"total_estimated_contacts_points": [0, 0],
"total_false_positives": [0, 0],
"total_missed": 0,
}
for test_run in test_set:
# Configure trajectory.
cheetah = test_run[0]
date = test_run[1]
trial = test_run[2]
data_path = (
f"kinetic_dataset/{date}/{cheetah}/trial{trial}" if kinetic_dataset else f"{date}/{cheetah}/{trial}"
)
estimator = opt.init_trajectory(
root_dir,
data_path,
cheetah,
solver_path="C:/Users/DSLZI/Downloads/idaes-solvers-windows-x86_64/ipopt.exe",
include_camera_constraints=False,
kinetic_dataset=kinetic_dataset,
monocular_enable=monocular,
kinematic_model=False,
)
print(f"Processing {data_path}")
robot = estimator.model
# Init from previous run FTE.
data_dir = os.path.join(dir_prefix, estimator.params.data_dir.split("/cheetah_videos/")[1])
fte_states = data_ops.load_pickle(
os.path.join(
data_dir,
(
"fte_kinematic"
if estimator.scene.cam_idx is None or (not monocular)
else f"fte_kinematic_{estimator.scene.cam_idx}"
),
"fte.pickle",
)
)
init_q = fte_states["q"][: len(robot.m.fe), :]
init_dq = fte_states["dq"][: len(robot.m.fe), :]
init_ddq = fte_states["ddq"][: len(robot.m.fe), :]
estimator.com_vel = fte_states["com_vel"]
estimator.com_pos = fte_states["com_pos"]
for fe, cp in robot.indices(one_based=True):
p = 0
for link in robot.links:
for q in link.pyomo_sets["q_set"]:
robot[link.name]["q"][fe, cp, q].value = init_q[fe - 1, p]
robot[link.name]["dq"][fe, cp, q].value = init_dq[fe - 1, p]
robot[link.name]["ddq"][fe, cp, q].value = init_ddq[fe - 1, p]
p += 1
speed = np.linalg.norm(estimator.com_vel, axis=1) # type: ignore
cheetah_speed_mps = cast(float, np.mean(speed))
contacts, contacts_tmp = misc.contact_detection(
estimator.model, estimator.params.start_frame, cheetah_speed_mps, estimator.scene.fps, data_dir, plot=False
)
with open(os.path.join(estimator.params.data_dir, "metadata.json"), "r", encoding="utf-8") as f:
metadata = json.load(f)
gt_contacts = metadata["contacts"]
results[data_path] = {"speed": cheetah_speed_mps}
for foot in pe.foot.feet(estimator.model):
gt_foot_contact = gt_contacts[foot.name]
foot_contact = contacts[foot.name]
foot_contact_tmp = contacts_tmp[foot.name]
if gt_foot_contact is not None:
gt_stance = list(range(gt_foot_contact[0][0], gt_foot_contact[0][1]))
num_gt_contacts += len(gt_stance)
# Determine whether there is a detection.
if foot_contact is not None:
results[data_path][foot.name] = {
"stance_length": foot_contact[0][1] - foot_contact[0][0],
"limb": foot_contact[0][3],
"missed": 0,
"matched": 0,
"len_diff": 0,
"start_diff": 0,
"end_diff": 0,
}
estimated_stance = list(range(foot_contact[0][0], foot_contact[0][1]))
num_est_contacts += len(estimated_stance)
combined = len(np.unique(estimated_stance + gt_stance))
matched = len(np.intersect1d(estimated_stance, gt_stance))
# error = np.abs(combined - matched)
error = np.abs(len(estimated_stance) - matched)
num_error += error
num_matched += matched
results[data_path][foot.name]["missed"] = error
results[data_path][foot.name]["matched"] = matched
results[data_path][foot.name]["len_diff"] = len(gt_stance) - len(estimated_stance)
results[data_path][foot.name]["start_diff"] = gt_foot_contact[0][0] - foot_contact[0][0]
results[data_path][foot.name]["end_diff"] = gt_foot_contact[0][1] - foot_contact[0][1]
else:
print(f"Missed of contact for {data_path}: {foot.name}")
num_missed += 1
if foot_contact_tmp is not None:
estimated_stance = list(range(foot_contact_tmp[0][0], foot_contact_tmp[0][1]))
num_est_contacts_tmp += len(estimated_stance)
combined = len(np.unique((estimated_stance, gt_stance)))
matched = len(np.intersect1d(estimated_stance, gt_stance))
# num_error_tmp += np.abs(combined - matched)
num_error_tmp += np.abs(len(estimated_stance) - matched)
num_matched_tmp += matched
else:
# Check whether there is not a false positive.
if foot_contact is not None:
num_false_positives += 1
if foot_contact_tmp is not None:
num_false_positives_tmp += 1
results["total_contacts_points"] = num_gt_contacts
results["total_missed"] = num_missed
results["total_estimated_contacts_points"] = [num_est_contacts, num_est_contacts_tmp]
results["total_false_positives"] = [num_false_positives, num_false_positives_tmp]
results["total_contact_missed"] = [num_error, num_error_tmp]
results["total_contact_matched"] = [num_matched, num_matched_tmp]
data_ops.save_pickle(
os.path.join(dir_prefix, "contact_detection_monocular.pickle" if monocular else "contact_detection.pickle"),
results,
)
disp_results = {
"contact_points": results["total_contacts_points"],
"est_contact_points": results["total_estimated_contacts_points"][0],
"est_contact_points_2": results["total_estimated_contacts_points"][1],
"missed_detection": results["total_missed"],
"missed_contact": results["total_contact_missed"][0],
"missed_contact_2": results["total_contact_missed"][1],
"matched_contact": results["total_contact_matched"][0],
"matched_contact_2": results["total_contact_matched"][1],
"false_positives": results["total_false_positives"][0],
"false_positives_2": results["total_false_positives"][1],
}
df = pd.DataFrame(disp_results, index=[0])
# Kinetic dataset uncertainty in result 5 runs * +-1 for each touchdown and takeoff events (1 stride for each run). Therefore, 5*1*4 = 10%.
# AcinoSet dataset uncertainty in result 10 runs * +-1 for each touchdown and takeoff events (1 stride for each run). Therefore, 10*1*4 = 13.6%
print(df)
print(results)
def animate_torque_plot(robot: pe.system.System3D):
import matplotlib.pyplot as plt
from matplotlib import animation
total_mass = sum(link.mass for link in robot.links)
scale_forces_by = total_mass * 9.81
torque = {}
for motor in pe.motor.torques(robot):
torque[motor.name] = [
scale_forces_by * tau.value
for tau in [motor.pyomo_vars["Tc"][fe, idx] for fe in robot.m.fe for idx in motor.pyomo_sets["Tc_set"]]
]
x1 = torque["front-left-hip-pitch"]
x2 = torque["LFL_HFL_torque"]
nfe = len(x1)
total_time = pe.utils.total_time(robot.m)
time_steps = np.linspace(0, total_time, num=nfe)
fig = plt.figure(figsize=(16, 9), dpi=120)
fig_idx = 1
ax = plt.subplot(1, 1, fig_idx)
ax.plot(time_steps, x1, label="Front Left Shoulder", color=misc.plot_color["red"])
ax.plot(time_steps, x2, label="Front Left Carpus", color=misc.plot_color["blue"])
ax.set_xlabel("Time (s)")
ax.set_ylabel("Torque (Nm)")
ax.legend()
fig_idx += 1
plt.show(block=False)
def animate(i):
ax.cla() # clear the previous image
ax.plot(time_steps[:i], x1[:i]) # plot the line
ax.plot(time_steps[:i], x2[:i]) # plot the line
ax.set_xlim([0, time_steps[-1]]) # fix the x axis
ax.set_ylim([1.1 * np.min(x1), 1.1 * np.max(x1)]) # fix the y axis
anim = animation.FuncAnimation(fig, animate, frames=len(x) + 1, interval=1, blit=False)
plt.show(block=False)
def get_power_values(robot: pe.system.System3D, force_scale: float) -> List[np.ndarray]:
nfe = len(robot.m.fe)
power_arr = []
for motor in pe.motor.torques(robot):
_power = np.array([pyovalue(P) * force_scale for P in pe.motor.power(motor, robot.pyo_variables)]).reshape(
(nfe, -1)
)
power_arr.append(_power)
return power_arr
def determine_dlc_performance():
# Arabia labeled run.
points_2d_df = misc.load_dlc_points_as_df(
[
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/arabia/trial06/dlc/cam1DLC_resnet152_CheetahOct14shuffle3_600000.h5",
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/arabia/trial06/dlc/cam2DLC_resnet152_CheetahOct14shuffle3_600000.h5",
],
verbose=False,
)
points_2d_df = points_2d_df[points_2d_df["frame"] < 199]
points_2d_df.loc[points_2d_df["likelihood"] <= 0.5, ["x", "y"]] = np.nan # ignore points with low likelihood
gt_points_2d_df = misc.load_dlc_points_as_df(
[
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/arabia/trial06/dlc_hand_labeled/cam1.h5",
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/arabia/trial06/dlc_hand_labeled/cam2.h5",
],
hand_labeled=True,
verbose=False,
)
y_actual1 = gt_points_2d_df[["x", "y"]].to_numpy(dtype=np.float32)
y_predicted1 = points_2d_df[["x", "y"]].to_numpy(dtype=np.float32)
# Shiraz labeled run.
points_2d_df = misc.load_dlc_points_as_df(
[
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/shiraz/trial04/dlc/cam1DLC_resnet152_CheetahOct14shuffle3_600000.h5",
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/shiraz/trial04/dlc/cam2DLC_resnet152_CheetahOct14shuffle3_600000.h5",
],
verbose=False,
)
points_2d_df = points_2d_df[points_2d_df["frame"] < 199]
points_2d_df.loc[points_2d_df["likelihood"] <= 0.5, ["x", "y"]] = np.nan # ignore points with low likelihood
gt_points_2d_df = misc.load_dlc_points_as_df(
[
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/shiraz/trial04/dlc_hand_labeled/cam1.h5",
"/data/zico/cheetah_videos/kinetic_dataset/2009_09_07/shiraz/trial04/dlc_hand_labeled/cam2.h5",
],
hand_labeled=True,
verbose=False,
)
y_actual2 = gt_points_2d_df[["x", "y"]].to_numpy(dtype=np.float32)
y_predicted2 = points_2d_df[["x", "y"]].to_numpy(dtype=np.float32)
y_actual = np.vstack((y_actual1, y_actual2))
y_predicted = np.vstack((y_predicted1, y_predicted2))
print(f"RMSE (pixels): {rmse(y_actual, y_predicted):.2f}")
print(f"MAD: {mad(y_actual, y_predicted):.2f}")
print(f"Mean: {np.nanmean(y_actual - y_predicted):.2f}")
print(f"STD: {std_dev(y_actual, y_predicted):.2f}")
print(f"# predictions: {y_predicted[~np.isnan(y_predicted)].shape[0]}")
print(f"# GT labels: {y_actual[~np.isnan(y_actual)].shape[0]}")
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(16, 9), dpi=120)
plt.hist((y_actual - y_predicted).flatten(), density=True, bins=100, color="b") # you may select the no. of bins
plt.xlabel("Residuals", fontsize=15)
plt.ylabel("Density", fontsize=15)
plt.show()
def rmse(predictions, targets):
differences = predictions - targets
differences_squared = differences**2
mean_of_differences_squared = np.nanmean(differences_squared.flatten())
rmse_val = np.sqrt(mean_of_differences_squared)
return rmse_val
def mad(predictions, targets):
differences = predictions - targets
median = np.nanmedian(differences.flatten())
mad_val = np.nanmedian(np.abs(differences - median))
return mad_val
def std_dev(predictions, targets):
differences = predictions - targets
std_val = np.nanstd(differences.flatten())
return std_val
"""
shiraz_0804_contact = {
# "forelimb-trailing": ["right", 32, 40],
"forelimb-trailing": ["right", 0, 0],
"forelimb-leading": ["left", 0, 0 ],
"hindlimb-leading": ["left", 10, 25],
"hindlimb-trailing": ["right", 2, 18]
}
"""
def contact_json_conversion(robot: pe.system.System3D, json_path: str):
with open(json_path, "r") as f:
contact_json = json.load(f)
start_frame = contact_json["start_frame"]
end_frame = contact_json["end_frame"]
foot_contact_order = contact_json["contacts"]
ret = {
"forelimb-trailing": ["", 0, 0],
"forelimb-leading": ["", 0, 0],
"hindlimb-leading": ["", 0, 0],
"hindlimb-trailing": ["", 0, 0],
}
for foot in pe.foot.feet(robot):
limb = "forelimb" if foot.name[1] == "F" else "hindlimb"
side = "right" if foot.name[2] == "R" else "left"
if foot.name in foot_contact_order and foot_contact_order[foot.name] is not None:
data = foot_contact_order[foot.name]
start_idx = data[0][0] - start_frame
end_idx = data[0][1] - start_frame
if data[0][1] > end_frame:
# Not the full stance period, so remove from results.
ret[f"{limb}-{data[0][3]}"] = [side, 0, 0]
else:
ret[f"{limb}-{data[0][3]}"] = [side, start_idx - 1 if start_idx > 0 else start_idx, end_idx + 1]
else:
# This will only work if we have at least 3 contacts for the trajectory - this should be the case.
# This checks the other limb whether trailing or leading, so that we make a swap.
data = foot_contact_order[f"{foot.name[:2]}{'L' if side == 'right' else 'R'}_foot"]
ret[f"{limb}-{'leading' if data[0][3] == 'trailing' else 'trailing'}"] = [side, 0, 0]
return ret
def gait_analysis(robot: pe.system.System3D, contacts):
nfe = len(robot.m.fe)
power_arr = get_power_values(robot, 1)
data = {
"angle": {},
"torque": {},
"power": {},
"hindlimb-leading-y-indices": np.arange(contacts["hindlimb-leading"][1], contacts["hindlimb-leading"][2]),
"hindlimb-trailing-y-indices": np.arange(contacts["hindlimb-trailing"][1], contacts["hindlimb-trailing"][2]),
"hindlimb-leading-x-indices": np.linspace(
0, 100, contacts["hindlimb-leading"][2] - contacts["hindlimb-leading"][1]
),
"hindlimb-trailing-x-indices": np.linspace(
0, 100, contacts["hindlimb-trailing"][2] - contacts["hindlimb-trailing"][1]
),
"forelimb-leading-y-indices": np.arange(contacts["forelimb-leading"][1], contacts["forelimb-leading"][2]),
"forelimb-trailing-y-indices": np.arange(contacts["forelimb-trailing"][1], contacts["forelimb-trailing"][2]),
"forelimb-leading-x-indices": np.linspace(
0, 100, contacts["forelimb-leading"][2] - contacts["forelimb-leading"][1]
),
"forelimb-trailing-x-indices": np.linspace(
0, 100, contacts["forelimb-trailing"][2] - contacts["forelimb-trailing"][1]
),
}
total_mass = sum(link.mass for link in robot.links)
scale_forces_by = total_mass * 9.81
power = {}
torque = {}
for motor, _power in zip(pe.motor.torques(robot), power_arr):
power[motor.name] = _power
torque[motor.name] = np.array(
[
scale_forces_by * tau.value
for tau in [motor.pyomo_vars["Tc"][fe, idx] for fe in robot.m.fe for idx in motor.pyomo_sets["Tc_set"]]
]
).reshape((nfe, -1))
body_F = pe.utils.get_vals(robot["bodyF"].pyomo_vars["q"], (robot["bodyF"].pyomo_sets["q_set"],)).squeeze(axis=1)
body_B = pe.utils.get_vals(robot["base"].pyomo_vars["q"], (robot["base"].pyomo_sets["q_set"],)).squeeze(axis=1)
body_B = body_B[:, 3:]
calf_fr = pe.utils.get_vals(robot["LFR"].pyomo_vars["q"], (robot["LFR"].pyomo_sets["q_set"],)).squeeze(axis=1)
calf_fl = pe.utils.get_vals(robot["LFL"].pyomo_vars["q"], (robot["LFL"].pyomo_sets["q_set"],)).squeeze(axis=1)
calf_br = pe.utils.get_vals(robot["LBR"].pyomo_vars["q"], (robot["LBR"].pyomo_sets["q_set"],)).squeeze(axis=1)
calf_bl = pe.utils.get_vals(robot["LBL"].pyomo_vars["q"], (robot["LBL"].pyomo_sets["q_set"],)).squeeze(axis=1)
thigh_fr = body_F - pe.utils.get_vals(robot["UFR"].pyomo_vars["q"], (robot["UFR"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
thigh_fl = body_F - pe.utils.get_vals(robot["UFL"].pyomo_vars["q"], (robot["UFL"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
thigh_br = body_B - pe.utils.get_vals(robot["UBR"].pyomo_vars["q"], (robot["UBR"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
thigh_bl = body_B - pe.utils.get_vals(robot["UBL"].pyomo_vars["q"], (robot["UBL"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
hock_fr = calf_fr - pe.utils.get_vals(robot["HFR"].pyomo_vars["q"], (robot["HFR"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
hock_fl = calf_fl - pe.utils.get_vals(robot["HFL"].pyomo_vars["q"], (robot["HFL"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
hock_br = calf_br - pe.utils.get_vals(robot["HBR"].pyomo_vars["q"], (robot["HBR"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
hock_bl = calf_bl - pe.utils.get_vals(robot["HBL"].pyomo_vars["q"], (robot["HBL"].pyomo_sets["q_set"],)).squeeze(
axis=1
)
for key, values in contacts.items():
if values[0] == "right" and "hindlimb" in key:
data["angle"][f"{key}-hip"] = np.degrees(thigh_br[data[f"{key}-y-indices"], 1])
data["angle"][f"{key}-hock"] = np.degrees(hock_br[data[f"{key}-y-indices"], 1])
data["torque"][f"{key}-hip"] = torque["back-right-hip-pitch"][data[f"{key}-y-indices"]]
data["torque"][f"{key}-hock"] = torque["LBR_HBR_torque"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hip"] = power["back-right-hip-pitch"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hock"] = power["LBR_HBR_torque"][data[f"{key}-y-indices"]]
elif values[0] == "right" and "forelimb" in key:
data["angle"][f"{key}-hip"] = np.degrees(thigh_fr[data[f"{key}-y-indices"], 1])
data["angle"][f"{key}-hock"] = np.degrees(hock_fr[data[f"{key}-y-indices"], 1])
data["torque"][f"{key}-hip"] = torque["front-right-hip-pitch"][data[f"{key}-y-indices"]]
data["torque"][f"{key}-hock"] = torque["LFR_HFR_torque"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hip"] = power["front-right-hip-pitch"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hock"] = power["LFR_HFR_torque"][data[f"{key}-y-indices"]]
elif values[0] == "left" and "hindlimb" in key:
data["angle"][f"{key}-hip"] = np.degrees(thigh_bl[data[f"{key}-y-indices"], 1])
data["angle"][f"{key}-hock"] = np.degrees(hock_bl[data[f"{key}-y-indices"], 1])
data["torque"][f"{key}-hip"] = torque["back-left-hip-pitch"][data[f"{key}-y-indices"]]
data["torque"][f"{key}-hock"] = torque["LBL_HBL_torque"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hip"] = power["back-left-hip-pitch"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hock"] = power["LBL_HBL_torque"][data[f"{key}-y-indices"]]
elif values[0] == "left" and "forelimb" in key:
data["angle"][f"{key}-hip"] = np.degrees(thigh_fl[data[f"{key}-y-indices"], 1])
data["angle"][f"{key}-hock"] = np.degrees(hock_fl[data[f"{key}-y-indices"], 1])
data["torque"][f"{key}-hip"] = torque["front-left-hip-pitch"][data[f"{key}-y-indices"]]
data["torque"][f"{key}-hock"] = torque["LFL_HFL_torque"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hip"] = power["front-left-hip-pitch"][data[f"{key}-y-indices"]]
data["power"][f"{key}-hock"] = power["LFL_HFL_torque"][data[f"{key}-y-indices"]]
return data
def plot_gait_attributes(results: List[Dict], dir_prefix: str):
import matplotlib.pyplot as plt
data_idx = (
"hindlimb-leading-hip",
"hindlimb-trailing-hip",
"forelimb-leading-shoulder",
"forelimb-trailing-shoulder",
"hindlimb-leading-hock",
"hindlimb-trailing-hock",
"forelimb-leading-carpus",
"forelimb-trailing-carpus",
)
for i, titles in enumerate((("Shoulder Joints", "Front Ankle Joints"), ("Hip Joints", "Back Ankle Joints"))):
fig, axs = plt.subplots(2, 2, figsize=(16, 9), dpi=120)
axs = axs.ravel()
for data in results:
if "Shoulder" in titles[0]:
data_idx = "forelimb"
else:
data_idx = "hindlimb"
axs[0].plot(
data[f"{data_idx}-leading-x-indices"],
data["angle"][f"{data_idx}-leading-hip"],
label="Leading",
color=misc.plot_color["green"],
)
axs[0].plot(
data[f"{data_idx}-trailing-x-indices"],
data["angle"][f"{data_idx}-trailing-hip"],
label="Trailing",
color=misc.plot_color["orange"],
)
axs[0].set_ylabel("Angle ($\degree$)")
axs[0].set_title(titles[0])
axs[2].plot(
data[f"{data_idx}-leading-x-indices"],
data["torque"][f"{data_idx}-leading-hip"],
label="Leading",
color=misc.plot_color["green"],
)
axs[2].plot(
data[f"{data_idx}-trailing-x-indices"],
data["torque"][f"{data_idx}-trailing-hip"],
label="Trailing",
color=misc.plot_color["orange"],
)
axs[2].set_ylabel("Torque (Nm)")
axs[1].plot(
data[f"{data_idx}-leading-x-indices"],
data["angle"][f"{data_idx}-leading-hock"],
label="Leading",
color=misc.plot_color["green"],
)
axs[1].plot(
data[f"{data_idx}-trailing-x-indices"],
data["angle"][f"{data_idx}-trailing-hock"],
label="Trailing",
color=misc.plot_color["orange"],
)
axs[1].set_title(titles[1])
axs[3].plot(
data[f"{data_idx}-leading-x-indices"],
data["torque"][f"{data_idx}-leading-hock"],
label="Leading",
color=misc.plot_color["green"],
)
axs[3].plot(
data[f"{data_idx}-trailing-x-indices"],
data["torque"][f"{data_idx}-trailing-hock"],
label="Trailing",
color=misc.plot_color["orange"],
)
# axs[4].plot(data[f"{data_idx}-leading-x-indices"],
# data["power"][f"{data_idx}-leading-hip"],
# label="Leading",
# color=misc.plot_color["blue"])
# axs[4].plot(data[f"{data_idx}-trailing-x-indices"],
# data["power"][f"{data_idx}-trailing-hip"],
# label="Trailing",
# color=misc.plot_color["red"])
# axs[4].set_ylabel('Power (Nm/kg)')
# axs[4].set_xlabel('$\%$ Stance')
# axs[5].plot(data[f"{data_idx}-leading-x-indices"],
# data["power"][f"{data_idx}-leading-hock"],
# label="Leading",
# color=misc.plot_color["blue"])
# axs[5].plot(data[f"{data_idx}-trailing-x-indices"],
# data["power"][f"{data_idx}-trailing-hock"],
# label="Trailing",
# color=misc.plot_color["red"])
# axs[5].set_xlabel('$\%$ Stance')
axs[3].set_xlabel("$\%$ Stance")
axs[2].set_xlabel("$\%$ Stance")
# for ax in axs:
axs[0].legend(("Leading", "Trailing"))
# for i in contacts:
# ax.axvspan(time_steps[i[0]], time_steps[i[1] - 1], facecolor='0.2', alpha=0.2)
plt.savefig(
os.path.join(os.path.join(dir_prefix, f"{'forelimb-analysis' if i == 0 else 'hindlimb-analysis'}.pdf")),
bbox_inches="tight",
)
plt.close()
def get_positions_from_pose(estimator: opt.CheetahEstimator, q: np.ndarray):
robot = estimator.model
m = robot.m
markers = misc.get_markers()
link_lengths = []
for link in robot.links:
link_lengths.append(link.length)
# link_lengths = np.tile(link_lengths, q.shape[0]).reshape(q.shape[0], -1)
states = q.tolist() + link_lengths
return [
[
estimator.position_funcs[l][0](states),
estimator.position_funcs[l][1](states),
estimator.position_funcs[l][2](states),
]
for l in range(len(markers))
]
def plot_3d_pose(estimator: opt.CheetahEstimator, pose_idx: int, display_good_pose: bool = True, view_angle=(20, 135)):
import matplotlib.pyplot as plt
fte_states = data_ops.load_pickle(os.path.join(estimator.params.data_dir, "fte_kinematic", "fte.pickle"))
# Get pose from solution and perform a transformation on the root orientation to show difference in likelihood.
pos1 = fte_states["positions"][pose_idx, :, :]
x_orig = fte_states["x"][pose_idx, :]
q_orig = fte_states["q"][pose_idx, :]
pose_gmm = PoseModelGMM(
os.path.join(".", "models", "data-driven", "dataset_full_pose.h5"), num_vars=28, ext_dim=6, n_comps=5
)
q_transformed = q_orig.copy()
q_transformed[3:12:3] = np.pi / 6
q_transformed[3:12:2] = -np.pi / 6
x_transformed = np.array(pe.utils.flatten(misc.get_relative_angles(q_transformed.reshape(1, -1), 0)))[
misc.get_relative_angle_mask()
]
pos2 = np.array(get_positions_from_pose(estimator, q_transformed))
print(f"Original pose log-likelihood: {pose_gmm.gmm.score(x_orig[6:].reshape(1, -1)):.2f}")
print(f"Transformed pose log-likelihood: {pose_gmm.gmm.score(x_transformed[6:].reshape(1, -1)):.2f}")
# Center the pose.
pos1 -= np.expand_dims(np.mean(pos1, axis=0), axis=0)
pos2 -= np.expand_dims(np.mean(pos2, axis=0), axis=0)
# Plot the pose.
fig = plt.figure(figsize=(6, 6), facecolor="w", edgecolor="k")
fig.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
lines_idxs = [
[0, 1, "charcoal"],
[0, 2, "charcoal"],
[1, 2, "charcoal"],
[1, 3, "charcoal"],
[0, 3, "charcoal"],
[2, 3, "charcoal"],
[3, 4, "charcoal"],
[4, 5, "charcoal"],
[5, 6, "charcoal"],
[6, 7, "charcoal"],
[3, 8, "charcoal"],
[4, 8, "charcoal"],
[8, 9, "red"],
[9, 10, "red"],
[10, 11, "red"], # right front leg
[3, 12, "charcoal"],
[4, 12, "charcoal"],
[12, 13, "green"],
[13, 14, "green"],
[14, 15, "green"], # left front leg
[4, 16, "charcoal"],
[5, 16, "charcoal"],
[16, 17, "red"],
[17, 18, "red"],
[18, 19, "red"], # right back leg
[4, 20, "charcoal"],
[5, 20, "charcoal"],
[20, 21, "green"],
[21, 22, "green"],
[22, 23, "green"], # left back leg
]
ax = fig.add_subplot(1, 1, 1, projection="3d")
for line in lines_idxs:
if display_good_pose:
ax.plot(
[pos1[line[0], 0], pos1[line[1], 0]],
[pos1[line[0], 1], pos1[line[1], 1]],
[pos1[line[0], 2], pos1[line[1], 2]],
color=misc.plot_color[line[2]],
# marker=".",
# markersize=20.0,
linewidth=3.0,
)
else:
ax.plot(
[pos2[line[0], 0], pos2[line[1], 0]],
[pos2[line[0], 1], pos2[line[1], 1]],
[pos2[line[0], 2], pos2[line[1], 2]],
color=misc.plot_color[line[2]],
# alpha=0.4,
# marker=".",
# markersize=20.0,
linewidth=3.0,
)
ax.view_init(*view_angle)
# ax.set_title(titles[i])
ax.set_xlabel("X-axis (m)")
ax.set_ylabel("Y-axis (m)")
ax.set_zlabel("Z-axis (m)")
ax.set_xlim((-1.0, 1.0))
ax.set_ylim((-0.5, 0.5))
ax.set_zlim((-0.5, 0.5))
ax.grid(False)
plt.show(block=False)
fig.savefig(
os.path.join(estimator.params.data_dir, f"pose-example-{'good' if display_good_pose else 'bad'}.pdf"),
bbox_inches="tight",
pad_inches=0,
)
def plot_eom_error(estimator: opt.CheetahEstimator):
import matplotlib.pyplot as plt
robot = estimator.model
eom_err = pe.utils.get_vals_v(robot.m.slack_eom, (robot.m.fe, robot.m.cp, range(len(robot.eom)))).squeeze()
nfe = len(robot.m.fe)
total_time = pe.utils.total_time(robot.m)
time_steps = np.linspace(0, total_time, num=nfe)
q, _, _ = robot.get_state_vars()
q_state = pe.utils.flatten(q.tolist())
fig = plt.figure(figsize=(18, 64), dpi=120)
axs = fig.subplots(18, 3)
axs = axs.flatten()
for i, q_val in enumerate(q_state):
axs[i].plot(time_steps, eom_err[:, i], color=misc.plot_color["orange"])
axs[i].set_title(f"{q_val} (rmse: {np.sqrt(np.mean(eom_err[:, i]**2)):.6f})")
plt.show(block=False)
plt.close()
def ablation_study(dir_prefix: str):
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
data1 = data_ops.load_pickle(os.path.join(dir_prefix, "data_driven_ablation_study.pickle"))
data2 = data_ops.load_pickle(os.path.join(dir_prefix, "physics_based_ablation_study.pickle"))
scenarios = ("Default", "Pose", "Motion", "Pose + Motion")
width = 0.25 # the width of the bars
x = np.arange(len(scenarios))
fig = plt.figure(figsize=(16, 9), dpi=120)
gs = gridspec.GridSpec(2, 4)
# gs.update(wspace=0.5)
ax1 = plt.subplot(
gs[0, :2],
)
ax2 = plt.subplot(gs[0, 2:])
ax3 = plt.subplot(gs[1, 1:3])
# axs = fig.subplots(2, 2)
# axs = axs.flatten()
rect1 = ax1.bar(
x - width / 2, [data1["mpe"][0], data1["mpe"][2], data1["mpe"][1], data1["mpe"][3]], width, label="Data-driven"
)
rect2 = ax1.bar(
x + width / 2,
[data2["mpe"][0], data2["mpe"][2], data2["mpe"][1], data2["mpe"][3]],
width,
label="Physics-based",
)
ax1.set_xticks(x)
ax1.set_xticklabels(scenarios)
ax1.set_ylabel("MPE (mm)")
ax1.set_ylim((0.0, 400.0))
# axs[0].legend()
# axs[0].bar_label(rect1, padding=3)
# axs[0].bar_label(rect2, padding=3)
rect1 = ax2.bar(
x - width / 2,
[data1["mpjpe"][0], data1["mpjpe"][2], data1["mpjpe"][1], data1["mpjpe"][3]],
width,
label="Data-driven",
)
rect2 = ax2.bar(
x + width / 2,
[data2["mpjpe"][0], data2["mpjpe"][2], data2["mpjpe"][1], data2["mpjpe"][3]],
width,
label="Physics-based",
)
ax2.set_xticks(x)
ax2.set_xticklabels(scenarios)
ax2.set_ylabel("MPJPE (mm)")
ax2.set_ylim((0.0, 150.0))
# axs[1].legend()
# axs[1].bar_label(rect1, padding=3)
# axs[1].bar_label(rect2, padding=3)
# axs[2].bar(scenaridos, [data1["centroid_vel_rmse"][0], data1["centroid_vel_rmse"][2], data1["centroid_vel_rmse"][1], data1["centroid_vel_rmse"][3]])
# axs[2].bar(scenaridos, [data2["centroid_vel_rmse"][0], data2["centroid_vel_rmse"][2], data2["centroid_vel_rmse"][1], data2["centroid_vel_rmse"][3]])
rect1 = ax3.bar(
x - width / 2,
[
data1["centroid_vel_rmse"][0],
data1["centroid_vel_rmse"][2],
data1["centroid_vel_rmse"][1],
data1["centroid_vel_rmse"][3],
],
width,
label="Data-driven",
)
rect2 = ax3.bar(
x + width / 2,
[
data2["centroid_vel_rmse"][0],
data2["centroid_vel_rmse"][2],
data2["centroid_vel_rmse"][1],
data2["centroid_vel_rmse"][3],
],
width,
label="Physics-based",
)
ax3.set_xticks(x)
ax3.set_xticklabels(scenarios)
ax3.set_ylabel("CVR (m)")
ax3.set_ylim((0.0, 2.0))
# axs[2].legend()
# axs[2].bar_label(rect1, padding=3)
# axs[2].bar_label(rect2, padding=3)
# axs[3].plot(x, data["smoothness_error"], marker="o")
# axs[3].set_xticks(x)
# axs[3].set_xticklabels(scenaridos)
# axs[3].set_ylabel("Smoothness Error (mm)")
fig.legend(("Data-driven", "Physics-based"), loc="lower right")
fig.savefig(os.path.join(dir_prefix, "ablation-study.pdf"), bbox_inches="tight")
# plt.show(block=False)
plt.close()
def data_driven_analysis(dir_prefix: str):
import matplotlib.pyplot as plt
data = data_ops.load_pickle(os.path.join(dir_prefix, "grid_search.pickle"))
n_comps = (1, 2, 3, 4, 5, 6, 7)
window_size = (1, 2, 3, 4, 5, 6, 7)
lasso = (True, False)
data_keys = []
for num_comp in n_comps:
for sparse_sol in lasso:
for w_size in window_size:
data_keys.append((num_comp, sparse_sol, w_size))