-
Notifications
You must be signed in to change notification settings - Fork 0
/
acinoset_misc.py
2056 lines (1859 loc) · 80.6 KB
/
acinoset_misc.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
from dataclasses import dataclass
import os
from typing import Iterable, List, Tuple, Dict, Optional, Union, Any, cast
import numpy as np
import sympy as sp
import pandas as pd
import pickle
from glob import glob
from errno import ENOENT
import json
import pyomo.environ as pyo
import cv2 as cv
import shared.physical_education as pe
from scipy import signal
from scipy.interpolate import UnivariateSpline
from acinoset_models import MotionModel, PoseModelGMM
from common.py_utils import data_ops
from matplotlib import rcParams, cycler
rcParams.update({"figure.autolayout": True})
rcParams.update({"font.size": 18})
rcParams.update({"font.serif": "Times New Roman"})
rcParams.update({"font.family": "serif"})
# Universal colour palatte for results.
plot_color = {
"orange": "#FF6400",
"blue": "#6699FF",
"charcoal": "#5A5A5A",
"gray": "#808080",
"green": "#2E8B57",
"red": "#DC143C",
}
rcParams["axes.prop_cycle"] = cycler(
color=[plot_color["charcoal"], plot_color["orange"], plot_color["red"], plot_color["green"]]
)
@dataclass
class TrajectoryParams:
data_dir: str
start_frame: int
end_frame: int
total_length: int
dlc_thresh: float
sync_offset: Optional[List[Dict]]
hand_labeled_data: bool
kinetic_dataset: bool
enable_shutter_delay_estimation: bool
enable_ppms: bool
@dataclass
class Scene:
scene_fpath: str
k_arr: List[float]
d_arr: List[float]
r_arr: List[List[float]]
t_arr: List[float]
cam_res: List[int]
fps: float
n_cams: int
cam_idx: Optional[int] = None
@dataclass
class SimpleLinearModel:
m: float
c: float
def __init__(self, pts: Union[List, np.ndarray], verbose: bool = False) -> None:
x_coords, y_coords = zip(*pts)
A = np.vstack([x_coords, np.ones(len(x_coords))]).T
self.m, self.c = np.linalg.lstsq(A, y_coords, rcond=None)[0] # type: ignore
if verbose:
print("Line Solution is y = {m:.3f}x + {c:.3f}".format(m=self.m, c=self.c))
def predict(self, x: float) -> float:
return self.m * x + self.c
def bound_value(val: float, slack_percentage: float):
if val > 0:
return ((1 - slack_percentage) * val, (1 + slack_percentage) * val)
elif val < 0:
return ((1 + slack_percentage) * val, (1 - slack_percentage) * val)
else:
return (-1 * slack_percentage, 1 * slack_percentage)
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 create_foot_contraints(robot: pe.system.System3D):
m = cast(pyo.ConcreteModel, robot.m)
m.HFR_height = pyo.Var(m.fe, m.cp, name="HFR_height", bounds=(0, None))
m.HFL_height = pyo.Var(m.fe, m.cp, name="HFL_height", bounds=(0, None))
m.HBR_height = pyo.Var(m.fe, m.cp, name="HBR_height", bounds=(0, None))
m.HBL_height = pyo.Var(m.fe, m.cp, name="HBL_height", bounds=(0, None))
HFR_pos_func = pe.utils.lambdify_EOM(robot["HFR"].bottom_I, robot.sp_variables)
HFL_pos_func = pe.utils.lambdify_EOM(robot["HFL"].bottom_I, robot.sp_variables)
HBR_pos_func = pe.utils.lambdify_EOM(robot["HBR"].bottom_I, robot.sp_variables)
HBL_pos_func = pe.utils.lambdify_EOM(robot["HBL"].bottom_I, robot.sp_variables)
ncp = len(cast(Any, m).cp)
def add_constraints(name: str, func, indexes):
setattr(robot.m, name, pyo.Constraint(*indexes, rule=func))
def def_foot_height(m, fe, cp): # foot height above z == 0 (xy-plane)
if fe == 1 and cp < ncp:
return pyo.Constraint.Skip
return m.HFR_height[fe, cp] == HFR_pos_func[2](robot.pyo_variables[fe, cp])
add_constraints("HFR_height_constr", def_foot_height, (m.fe, m.cp))
def def_foot_height1(m, fe, cp): # foot height above z == 0 (xy-plane)
if fe == 1 and cp < ncp:
return pyo.Constraint.Skip
return m.HFL_height[fe, cp] == HFL_pos_func[2](robot.pyo_variables[fe, cp])
add_constraints("HFL_height_constr", def_foot_height1, (m.fe, m.cp))
def def_foot_height2(m, fe, cp): # foot height above z == 0 (xy-plane)
if fe == 1 and cp < ncp:
return pyo.Constraint.Skip
return m.HBR_height[fe, cp] == HBR_pos_func[2](robot.pyo_variables[fe, cp])
add_constraints("HBR_height_constr", def_foot_height2, (m.fe, m.cp))
def def_foot_height3(m, fe, cp): # foot height above z == 0 (xy-plane)
if fe == 1 and cp < ncp:
return pyo.Constraint.Skip
return m.HBL_height[fe, cp] == HBL_pos_func[2](robot.pyo_variables[fe, cp])
add_constraints("HBL_height_constr", def_foot_height3, (m.fe, m.cp))
def create_camera_contraints(
robot: pe.system.System3D,
params: TrajectoryParams,
scene: Scene,
dlc_dir: str,
position_funcs,
hand_labeled_data: bool = False,
kinetic_dataset: bool = False,
):
q, _, _ = robot.get_state_vars()
markers = get_markers()
m = cast(pyo.ConcreteModel, robot.m)
def pt3d_to_x2d(x, y, z, K, D, R, t):
return pt3d_to_2d(x, y, z, K, D, R, t)[0] if kinetic_dataset else pt3d_to_2d_fisheye(x, y, z, K, D, R, t)[0]
def pt3d_to_y2d(x, y, z, K, D, R, t):
return pt3d_to_2d(x, y, z, K, D, R, t)[1] if kinetic_dataset else pt3d_to_2d_fisheye(x, y, z, K, D, R, t)[1]
proj_funcs = [pt3d_to_x2d, pt3d_to_y2d]
L = len(markers) # number of dlc labels per frame
# C = len(scene.k_arr) if scene.cam_idx is None else 1 # number of cameras
m.P = pyo.RangeSet(len(set(cast(Any, q))))
m.L = pyo.RangeSet(L)
# number of cameras. Note, this only works if cam index you select is within a consecutive set of cameras.
if scene.cam_idx is None:
m.C = pyo.RangeSet(len(scene.k_arr))
else:
m.C = pyo.RangeSet(scene.cam_idx + 1, scene.cam_idx + 1)
# Dimensionality of measurements
m.D2 = pyo.RangeSet(2)
m.D3 = pyo.RangeSet(3)
# Number of pairwise terms to include + the base measurement.
m.W = pyo.RangeSet(3 if params.enable_ppms else 1)
m.pose = pyo.Var(m.fe, m.L, m.D3)
m.slack_meas = pyo.Var(m.fe, m.C, m.L, m.D2, m.W, initialize=0.0)
if scene.cam_idx is None and params.enable_shutter_delay_estimation:
m.shutter_delay = pyo.Var(m.C, initialize=0.0, bounds=(-m.hm0.value, m.hm0.value))
index_dict = get_dlc_marker_indices()
pair_dict = get_pairwise_graph()
R_pw, Q = get_uncertainty_models()
if kinetic_dataset:
R_pw[:] = 7
base_data = {}
pw_data = {}
cam_idx = 0
# Extract the frame offsets to synchronise all cameras.
sync_offset_arr = [0] * scene.n_cams
if params.sync_offset is not None:
for offset in params.sync_offset:
sync_offset_arr[offset["cam"]] = offset["frame"]
df_paths = sorted(glob(os.path.join(dlc_dir, "*.h5")))
assert scene.n_cams == len(df_paths), f"# of dlc .h5 files != # of cams in {scene.n_cams}_cam_scene_sba.json"
for path in df_paths:
# Pairwise correspondence data.
h5_filename = os.path.basename(path)
if params.enable_ppms:
pw_data[cam_idx] = data_ops.load_pickle(
os.path.join(dlc_dir + "_pw", f"{h5_filename[:4]}DLC_resnet152_CheetahOct14shuffle4_650000.pickle")
)
df_temp = pd.read_hdf(os.path.join(dlc_dir, h5_filename))
base_data[cam_idx] = list(df_temp.to_numpy())
cam_idx += 1
# ======= WEIGHTS =======
def init_meas_weights(_, n, c, l, w):
# Determine if the current measurement is the base prediction or a pairwise prediction.
cam_idx = c - 1
marker = markers[l - 1]
if w < 2:
base = index_dict[marker]
if hand_labeled_data:
likelihoods = np.ones((len(markers) + 1, 1)).flatten()
x_pixel = base_data[cam_idx][(n - 1) + params.start_frame][0::2][base]
y_pixel = base_data[cam_idx][(n - 1) + params.start_frame][1::2][base]
if x_pixel == np.nan and y_pixel == np.nan:
likelihoods[base] = 0.0
else:
likelihoods = base_data[cam_idx][(n - 1) + params.start_frame - sync_offset_arr[cam_idx]][2::3]
else:
base = pair_dict[marker][w - 2]
values = pw_data[cam_idx][(n - 1) + params.start_frame - sync_offset_arr[cam_idx]]
likelihoods = values["pose"][2::3]
# Filter measurements based on DLC threshold.
# This does ensures that badly predicted points are not considered in the objective function.
return 1 / R_pw[w - 1][l - 1] if likelihoods[base] > params.dlc_thresh else 0.0
m.meas_err_weight = pyo.Param(m.fe, m.C, m.L, m.W, initialize=init_meas_weights, mutable=True)
m.model_err_weight = pyo.Param(m.P, initialize=lambda m, p: 1 / Q[p - 1] if Q[p - 1] != 0.0 else 0.0)
# ===== PARAMETERS =====
def init_measurements(_, n, c, l, d2, w):
# Determine if the current measurement is the base prediction or a pairwise prediction.
cam_idx = c - 1
marker = markers[l - 1]
if w < 2:
base = index_dict[marker]
if hand_labeled_data:
val = base_data[cam_idx][(n - 1) + params.start_frame][d2 - 1 :: 2]
else:
val = base_data[cam_idx][(n - 1) + params.start_frame - sync_offset_arr[cam_idx]][d2 - 1 :: 3]
return val[base] if val[base] != np.nan else 0.0
else:
values = pw_data[cam_idx][(n - 1) + params.start_frame - sync_offset_arr[cam_idx]]
val = values["pose"][d2 - 1 :: 3]
base = pair_dict[marker][w - 2]
val_pw = values["pws"][:, :, :, d2 - 1]
return val[base] + val_pw[0, base, index_dict[marker]]
m.meas = pyo.Param(m.fe, m.C, m.L, m.D2, m.W, initialize=init_measurements)
print("Get position variables to build pose constraint")
ncp = len(cast(Any, m).cp)
var_list = []
for fe in cast(Iterable, m.fe):
q_list = []
l_list = []
for link in robot.links:
pyo_vars = robot[link.name].get_pyomo_vars(fe, ncp)
q_list += pyo_vars[: len(robot[link.name].q)]
l_list.append(robot[link.name].pyomo_params["length"])
var_list.append(q_list + l_list)
# 3D POSE
m.pose_constraint = pyo.Constraint(
m.fe, m.L, m.D3, rule=lambda m, fe, l, d3: position_funcs[l - 1][d3 - 1](var_list[fe - 1]) == m.pose[fe, l, d3]
)
print("Add measurement model")
# Set first camera as reference for shutter delay estimation between cameras.
if hasattr(m, "shutter_delay"):
m.shutter_delay[1].fix(0)
# 2D rerojection constraint.
def measurement_constraints(m, n, c, l, d2, w):
# project
tau = m.shutter_delay[c] if hasattr(m, "shutter_delay") else 0.0
K, D, R, t = scene.k_arr[c - 1], scene.d_arr[c - 1], scene.r_arr[c - 1], scene.t_arr[c - 1]
# x, y, z = m.pose[n, l, 1], m.pose[n, l, 2], m.pose[n, l, 3]
x = m.pose[n, l, 1] + robot["base"]["dq"][n, 1, "x"] * tau + robot["base"]["ddq"][n, 1, "x"] * (tau**2)
y = m.pose[n, l, 2] + robot["base"]["dq"][n, 1, "y"] * tau + robot["base"]["ddq"][n, 1, "y"] * (tau**2)
z = m.pose[n, l, 3] + robot["base"]["dq"][n, 1, "z"] * tau + robot["base"]["ddq"][n, 1, "z"] * (tau**2)
return proj_funcs[d2 - 1](x, y, z, K, D, R, t) - m.meas[n, c, l, d2, w] - m.slack_meas[n, c, l, d2, w] == 0.0
m.measurement = pyo.Constraint(m.fe, m.C, m.L, m.D2, m.W, rule=measurement_constraints)
def add_linear_motion_model(robot: pe.system.System3D, window_size: int, lasso: bool, data_dir: str):
m = cast(pyo.ConcreteModel, robot.m)
# Train motion model and make predictions with a predefined window size.
num_vars = 28
window_time = 1
window_buf = window_size * window_time
motion_model = MotionModel(
os.path.join(".", "models", "data-driven", "dataset_full_pose.h5"),
num_vars,
window_size=window_size,
window_time=window_time,
lasso=lasso,
)
pred_var = motion_model.error_variance
pose_mask = get_relative_angle_mask()
m.R = pyo.RangeSet(num_vars)
m.motion_err_weight = pyo.Param(m.R, initialize=lambda m, p: 1 / pred_var[p - 1] if pred_var[p - 1] != 0 else 0.0)
m.slack_motion = pyo.Var(m.fe, m.cp, m.R, initialize=0.0)
# Incorporate the prediction model as constraints.
X = np.array(
[
np.array(pe.utils.flatten(get_relative_angles(robot, fe, cp)))[pose_mask]
for fe, cp in robot.indices(one_based=True)
]
)
df = data_ops.series_to_supervised(X, n_in=window_size, n_step=window_time)
X_in = df.to_numpy()[:, 0 : (num_vars * window_size)]
y_pred = motion_model.predict(X_in, matrix=True)
def motion_constr(m_temp: pyo.ConcreteModel, fe, cp, p):
if fe > window_buf:
x = np.array(pe.utils.flatten(get_relative_angles(robot, fe, cp)))[pose_mask]
return x[p - 1] - y_pred[fe - window_buf - 1, p - 1] - m.slack_motion[fe, cp, p] == 0
else:
return pyo.Constraint.Skip
print("Add LR motion model")
setattr(m, "monocular_motion_constr", pyo.Constraint(m.fe, m.cp, m.R, rule=motion_constr))
slack_motion_err = 0.0
for fe in cast(Iterable, m.fe):
for cp in cast(Iterable, m.cp):
for p in cast(Iterable, m.R):
slack_motion_err += m.motion_err_weight[p] * m.slack_motion[fe, cp, p] ** 2
return slack_motion_err, motion_model
def init_foot_height(robot: pe.system.System3D):
m = cast(pyo.ConcreteModel, robot.m)
ncp = len(cast(Any, m).cp)
for foot in pe.foot.feet(robot):
for fe in cast(Iterable, m.fe):
foot["foot_height"][fe, ncp].value = pyo.value(foot.foot_pos_func[2](robot.pyo_variables[fe, ncp]))
def init_foot_velocity(robot: pe.system.System3D) -> np.ndarray:
m = cast(pyo.ConcreteModel, robot.m)
ncp = len(cast(Any, m).cp)
# 4 - four feet, and 3 - 3D space.
ret = np.empty((len(cast(Any, m).fe), 4, 3))
data: List[List[float]] = [
[cast(Any, v).value for v in robot.pyo_variables[fe, ncp]] for fe in cast(Iterable, m.fe)
]
for j, foot in enumerate(cast(List[pe.foot.Foot3D], pe.foot.feet(robot))):
func = pe.utils.lambdify_EOM(foot.Pb_I_vel, robot.sp_variables)
for fe in cast(Iterable, m.fe):
for i in range(3):
ret[fe - 1, j, i] = func[i](data[fe - 1])
return ret
def init_3d_pose(robot: pe.system.System3D, position_funcs):
m = cast(pyo.ConcreteModel, robot.m)
q_init = pe.utils.get_vals(robot["base"].pyomo_vars["q"], (robot["base"].pyomo_sets["q_set"],)).squeeze()
link_lengths = [robot["base"].length]
for link in robot.links[1:]:
q_init = np.concatenate(
(q_init, pe.utils.get_vals(link.pyomo_vars["q"], (link.pyomo_sets["q_set"],)).squeeze(axis=1)), axis=1
)
link_lengths.append(link.length)
link_lengths = np.tile(link_lengths, q_init.shape[0]).reshape(q_init.shape[0], -1)
states = np.concatenate((q_init, link_lengths), axis=1)
for fe in cast(Iterable, m.fe):
for l in cast(Iterable, m.L):
for d3 in cast(Iterable, m.D3):
cast(Any, m).pose[fe, l, d3].value = position_funcs[l - 1][d3 - 1](states[fe - 1, :])
def create_trajectory_estimate(
robot: pe.system.System3D, params: TrajectoryParams, scene: Scene, kinetic_dataset: bool
):
# load DLC data
dlc_points_fpaths = sorted(
glob(os.path.join(params.data_dir, "dlc" if not params.hand_labeled_data else "dlc_hand_labeled", "*.h5"))
)
# load measurement dataframe (pixels, likelihood)
points_2d_df = load_dlc_points_as_df(dlc_points_fpaths, hand_labeled=params.hand_labeled_data, verbose=False)
if not params.hand_labeled_data:
points_2d_df = points_2d_df[
points_2d_df["likelihood"] > params.dlc_thresh
] # ignore points with low likelihood
# Ensure that the cameras are synchonised.
if params.sync_offset is not None:
for offset in params.sync_offset:
points_2d_df.loc[points_2d_df["camera"] == offset["cam"], "frame"] += offset["frame"]
# Add init of state vector.
if kinetic_dataset:
# Only consider the near side cameras for the initial trajectory.
points_2d_df = points_2d_df[points_2d_df["camera"] < 2]
if scene.cam_idx is None:
points_3d_df = get_pairwise_3d_points_from_df(
points_2d_df,
scene.k_arr,
scene.d_arr,
scene.r_arr,
scene.t_arr,
triangulate_points if kinetic_dataset else triangulate_points_fisheye,
)
spine_pts = points_3d_df[points_3d_df["marker"] == "spine"][["frame", "x", "y", "z"]].values
else:
points_2d_df = points_2d_df[points_2d_df["camera"] == scene.cam_idx]
spine_pts_2d = points_2d_df.query("marker == 'spine'")[["frame", "x", "y"]].to_numpy(dtype=np.float32)
spine_pts = triangulate_points_single_img(
spine_pts_2d[:, 1:],
3,
scene.k_arr[scene.cam_idx],
scene.d_arr[scene.cam_idx],
scene.r_arr[scene.cam_idx],
scene.t_arr[scene.cam_idx],
).T
spine_pts = np.c_[spine_pts_2d[:, 0], spine_pts]
spine_pts[:, 1] = spine_pts[:, 1] + cast(float, robot["base"].length) / 2.0
if params.hand_labeled_data:
num_frames = points_2d_df["frame"].max() + 1
frame_range = np.arange(num_frames, dtype=int)
w = np.isnan(spine_pts[:, 1])
spine_pts[w, 1] = 0.0
x_est = np.array(
UnivariateSpline(frame_range, spine_pts[:, 1], w=~w, k=1 if kinetic_dataset else 3)(frame_range)
)
spine_pts[w, 2] = 0.0
y_est = np.array(
UnivariateSpline(frame_range, spine_pts[:, 2], w=~w, k=1 if kinetic_dataset else 3)(frame_range)
)
spine_pts[w, 3] = 0.0
z_est = np.array(
UnivariateSpline(frame_range, spine_pts[:, 3], w=~w, k=1 if kinetic_dataset else 3)(frame_range)
)
else:
frame_est = np.arange(params.end_frame)
traj_est_x = UnivariateSpline(spine_pts[:, 0], spine_pts[:, 1], k=1 if kinetic_dataset else 3)
traj_est_y = UnivariateSpline(spine_pts[:, 0], spine_pts[:, 2], k=1 if kinetic_dataset else 3)
traj_est_z = UnivariateSpline(spine_pts[:, 0], spine_pts[:, 3], k=1 if kinetic_dataset else 3)
x_est = np.array(traj_est_x(frame_est))
y_est = np.array(traj_est_y(frame_est))
z_est = np.array(traj_est_z(frame_est))
# Calculate the initial yaw.
dx_est = np.diff(x_est) * scene.fps
dy_est = np.diff(y_est) * scene.fps
psi_est = np.arctan2(dy_est, dx_est)
# Duplicate the last heading estimate as the difference calculation returns N-1.
psi_est = np.pi + np.append(psi_est, [psi_est[-1]]) # TODO: This assumes the cheetah is running +x direction.
return x_est, y_est, z_est, psi_est
def measurement_cost(robot: pe.system.System3D, hand_labeled_data: bool = False, kinetic_dataset: bool = False):
m = cast(pyo.ConcreteModel, robot.m)
slack_meas_err = 0.0
cam_uncertainty_multiplier = (
[1.0, 1.0, 0.6, 0.6] if kinetic_dataset else [1.0] * 6
) # Assume a maximum 6-camera setup.
for fe in cast(Iterable, m.fe):
# Measurement Error
for l in cast(Iterable, m.L):
for c in cast(Iterable, m.C):
for d2 in cast(Iterable, m.D2):
for w in cast(Iterable, m.W):
if hand_labeled_data:
slack_meas_err += (
cast(Any, m).meas_err_weight[fe, c, l, w] * cast(Any, m).slack_meas[fe, c, l, d2, w]
) ** 2
else:
slack_meas_err += redescending_loss(
(cam_uncertainty_multiplier[c - 1] * cast(Any, m).meas_err_weight[fe, c, l, w])
* cast(Any, m).slack_meas[fe, c, l, d2, w],
3,
10,
20,
)
return slack_meas_err
def get_relative_angles(input: Union[pe.system.System3D, np.ndarray], fe: int, cp: int = 1, var: str = "q"):
if isinstance(input, pe.system.System3D):
# Get relative angles using pyomo variables.
angles = ["phi", "theta", "psi"]
base = [input["base"][var][fe, cp, q] for q in input["base"].pyomo_sets["q_set"]]
body_F = [input["bodyF"][var][fe, cp, q] - input["base"][var][fe, cp, q] for q in angles]
neck = [input["neck"][var][fe, cp, q] - input["bodyF"][var][fe, cp, q] for q in angles]
tail0 = [input["base"][var][fe, cp, q] - input["tail0"][var][fe, cp, q] for q in angles]
tail1 = [input["tail0"][var][fe, cp, q] - input["tail1"][var][fe, cp, q] for q in angles]
ufr = [input["bodyF"][var][fe, cp, q] - input["UFR"][var][fe, cp, q] for q in angles]
ufl = [input["bodyF"][var][fe, cp, q] - input["UFL"][var][fe, cp, q] for q in angles]
ubr = [input["base"][var][fe, cp, q] - input["UBR"][var][fe, cp, q] for q in angles]
ubl = [input["base"][var][fe, cp, q] - input["UBL"][var][fe, cp, q] for q in angles]
lfr = [input["UFR"][var][fe, cp, q] - input["LFR"][var][fe, cp, q] for q in angles]
lfl = [input["UFL"][var][fe, cp, q] - input["LFL"][var][fe, cp, q] for q in angles]
lbr = [input["UBR"][var][fe, cp, q] - input["LBR"][var][fe, cp, q] for q in angles]
lbl = [input["UBL"][var][fe, cp, q] - input["LBL"][var][fe, cp, q] for q in angles]
hfr = [input["LFR"][var][fe, cp, q] - input["HFR"][var][fe, cp, q] for q in angles]
hfl = [input["LFL"][var][fe, cp, q] - input["HFL"][var][fe, cp, q] for q in angles]
hbr = [input["LBR"][var][fe, cp, q] - input["HBR"][var][fe, cp, q] for q in angles]
hbl = [input["LBL"][var][fe, cp, q] - input["HBL"][var][fe, cp, q] for q in angles]
else:
# Get relative angles from numpy array.
base = list(input[fe, 0:6])
body_F = list(input[fe, 6:9] - input[fe, 3:6])
neck = list(input[fe, 9:12] - input[fe, 6:9])
tail0 = list(input[fe, 3:6] - input[fe, 12:15])
tail1 = list(input[fe, 12:15] - input[fe, 15:18])
ufr = list(input[fe, 6:9] - input[fe, 27:30])
ufl = list(input[fe, 6:9] - input[fe, 18:21])
ubr = list(input[fe, 3:6] - input[fe, 42:45])
ubl = list(input[fe, 3:6] - input[fe, 36:39])
lfr = list(input[fe, 27:30] - input[fe, 30:33])
lfl = list(input[fe, 18:21] - input[fe, 21:24])
lbr = list(input[fe, 42:45] - input[fe, 45:48])
lbl = list(input[fe, 36:39] - input[fe, 39:42])
hfr = list(input[fe, 30:33] - input[fe, 33:36])
hfl = list(input[fe, 21:24] - input[fe, 24:27])
hbr = list(input[fe, 45:48] - input[fe, 51:54])
hbl = list(input[fe, 39:42] - input[fe, 48:51])
return [base, body_F, neck, tail0, tail1, ufl, lfl, hfl, ufr, lfr, hfr, ubl, lbl, ubr, lbr, hbl, hbr]
def kinematic_cost(robot: pe.system.System3D, desired_q: np.ndarray, total_mass: float):
slack_kinematcs_err = 0.0
M = [
10, # x_{base_bodyB}
10, # y_{base_bodyB}
10, # z_{base_bodyB}
5, # \phi_{base_bodyB}
5, # \theta_{base_bodyB}
5, # \psi_{base_bodyB}
0, # \phi_{body_F}
5, # \theta_{body_F}
5, # \psi_{body_F}
0, # \phi_{neck}
2, # \theta_{neck}
2, # \psi_{neck}
0, # \phi_{tail0}
5, # \theta_{tail0}
5, # \psi_{tail0}
0, # \phi_{tail1}
5, # \theta_{tail1}
5, # \psi_{tail1}
0, # \phi_{UFL}
5, # \theta_{UFL}
0, # \psi_{UFL}
0, # \phi_{LFL}
2, # \theta_{LFL}
0, # \psi_{LFL}
0, # \phi_{HFL}
1, # \theta_{HFL}
0, # \psi_{HFL}
0, # \phi_{UFR}
5, # \theta_{UFR}
0, # \psi_{UFR}
0, # \phi_{LFR}
2, # \theta_{LFR}
0, # \psi_{LFR}
0, # \phi_{HFR}
1, # \theta_{HFR}
0, # \psi_{HFR}
0, # \phi_{UBL}
5, # \theta_{UBL}
0, # \psi_{UBL}
0, # \phi_{LBL}
2, # \theta_{LBL}
0, # \psi_{LBL}
0, # \phi_{UBR}
5, # \theta_{UBR}
0, # \psi_{UBR}
0, # \phi_{LBR}
2, # \theta_{LBR}
0, # \psi_{LBR}
0, # \phi_{HBL}
1, # \theta_{HBL}
0, # \psi_{HBL}
0, # \phi_{HBR}
1, # \theta_{HBR}
0, # \psi_{HBR}
]
# M = np.ones(54)
# M[0:6] = [3] * 6
for fe, cp in robot.indices(one_based=True):
p = 0
q_gt = pe.utils.flatten(get_relative_angles(desired_q, fe - 1, cp))
q_est = pe.utils.flatten(get_relative_angles(robot, fe, cp))
for q_d, q in zip(q_gt, q_est):
slack_kinematcs_err += M[p] * (q_d - q) ** 2
p += 1
return slack_kinematcs_err
def motion_smoothing_cost(robot: pe.system.System3D, fps: float):
# Minimise the linear joint acceleration.
energy_acc = 0.0
m = cast(Any, robot.m)
nfe = len(m.fe)
for fe in m.fe:
if fe < nfe - 2:
for l in m.L:
for d in m.D3:
pt_acc = fps**2 * (m.pose[fe + 2, l, d] - 2 * m.pose[fe + 1, l, d] + m.pose[fe, l, d])
energy_acc += pt_acc**2
return energy_acc
def change_in_torque_squared_cost(robot: pe.system.System3D):
m = cast(Any, robot.m)
nfe = len(m.fe)
dtau = 0.0
for motor in pe.motor.torques(robot):
Tc = motor.pyomo_vars["Tc"]
Tc_set = motor.pyomo_sets["Tc_set"]
for fe in m.fe:
if fe < nfe - 1:
for idx in Tc_set:
dtau += ((Tc[fe + 1, idx] - Tc[fe, idx]) / m.hm0) ** 2
return dtau
def eom_slack_cost(robot: pe.system.System3D):
slack_model_err = 0.0
for fe, cp in robot.indices(one_based=True):
for i in range(len(robot.eom)):
slack_model_err += robot.m.slack_eom[fe, cp, i] ** 2
return slack_model_err
def constant_acc_cost(robot: pe.system.System3D):
m = cast(pyo.ConcreteModel, robot.m)
def add_constant_acc_constraint(m: pyo.ConcreteModel, link: pe.links.Link3D):
var_name = f"{link.name}_acc_model"
ddq = link.pyomo_vars["ddq"]
setattr(m, var_name, pyo.Var(m.fe, m.cp, link.pyomo_sets["q_set"]))
setattr(
m,
f"{var_name}_constr",
pyo.Constraint(
m.fe,
m.cp,
link.pyomo_sets["q_set"],
rule=lambda m_temp, fe, cp, q: (
ddq[fe, cp, q] == ddq[fe - 1, cp, q] + getattr(m_temp, var_name)[fe, cp, q]
if fe > 1
else pyo.Constraint.Skip
),
),
)
print("Add constant acceleration model")
for link in robot.links:
add_constant_acc_constraint(m, link)
print("Add constant acceleration cost")
slack_model_err = 0.0
for fe in cast(Iterable, m.fe):
# Model Error
for cp in cast(Iterable, m.cp):
p = 1
for link in robot.links:
var_name = f"{link.name}_acc_model"
for q in link.pyomo_sets["q_set"]:
slack_model_err += cast(Any, m).model_err_weight[p] * getattr(robot.m, var_name)[fe, cp, q] ** 2
p += 1
return slack_model_err
def gmm_pose_cost(robot: pe.system.System3D, n_comps: int, data_dir: str):
from pyomo.core.expr.current import log as pyomo_log, exp
# Add GMM model if we are performing monocular reconstruction.
pose_gmm = PoseModelGMM(
os.path.join(".", "models", "data-driven", "dataset_full_pose.h5"),
num_vars=28,
ext_dim=6,
n_comps=n_comps,
)
def norm_pdf_multivariate(x: np.ndarray, mu: np.ndarray, cov: np.ndarray):
part1 = 1 / (((2 * np.pi) ** (len(x) / 2)) * (np.linalg.det(cov) ** (1 / 2)))
part2 = (-1 / 2) * ((x - mu).T.dot(np.linalg.inv(cov))).dot((x - mu))
return part1 * exp(part2)
slack_pose_err = 0.0
for fe, cp in robot.indices(one_based=True):
x = np.array(pe.utils.flatten(get_relative_angles(robot, fe, cp)))[get_relative_angle_mask()][6:]
slack_pose_err += -pyomo_log(
sum(
[
w * norm_pdf_multivariate(x, mu, cov)
for w, mu, cov in zip(pose_gmm.gmm.weights_, pose_gmm.gmm.means_, pose_gmm.gmm.covariances_)
]
)
+ 1e-12
)
# TODO: Need to double check whether this is valid? It seems to be taking the log likelihood of each mixture and summing together.
# slack_pose_err += sum([
# w * (1 / 2) * ((x - mu).T.dot(np.linalg.inv(cov))).dot((x - mu))
# for w, mu, cov in zip(pose_gmm.gmm.weights_, pose_gmm.gmm.means_, pose_gmm.gmm.covariances_)
# ])
return slack_pose_err, pose_gmm
def remove_dc_offset(x, num_samples: int = 100):
offset = np.mean(x[:num_samples], axis=0)
return x - offset
def get_com(robot: pe.system.System3D, scene: Scene) -> Tuple[np.ndarray, np.ndarray]:
m = cast(pyo.ConcreteModel, robot.m)
ncp = len(cast(Any, m.cp))
data: List[List[float]] = [
[cast(Any, v).value for v in robot.pyo_variables[fe, ncp]] for fe in cast(Iterable, m.fe)
]
# TODO: This should be placed inside the link and created at the same time as the link.
pos_funcs = [pe.utils.lambdify_EOM(link.Pb_I, robot.sp_variables) for link in robot.links]
total_mass = sum(cast(float, link.mass) for link in robot.links)
com_position = np.empty((len(data), 3))
for idx, d in enumerate(data):
com_pos = [0.0] * 3
for i, link in enumerate(robot.links):
for j, f in enumerate(pos_funcs[i]):
com_pos[j] += cast(float, link.mass) * f(d)
com_pos = np.asarray(com_pos)
com_pos *= 1 / total_mass
com_position[idx, :] = com_pos
# Return the COM position and velocities over the trajectory.
return com_position, (com_position[1:, :] - com_position[:-1, :]) * scene.fps
def contact_detection(
robot: pe.system.System3D, start_frame: int, speed: float, fps: float, data_dir: str, plot: bool = False
) -> Tuple[Dict, Dict]:
# Determine a rough linear model for stance time vs speed of cheetah (from Penny Hudson"s paper).
stance_time_model = SimpleLinearModel([[9.0, 0.09], [14.0, 0.06]])
stance_time_fe = round(stance_time_model.predict(speed) * fps)
mid_way = stance_time_fe // 2
is_even = (stance_time_fe % 2) == 0
# Init foot height.
init_foot_height(robot)
# Thresholds.
height_threshold = 0.05
# Init foot xy velocity.
foot_vel = init_foot_velocity(robot)
contacts = {}
contacts_tmp = {}
if plot:
import matplotlib.pyplot as plt
_ = plt.figure(figsize=(16, 9), dpi=120)
idx = 0
for i, foot in enumerate(pe.foot.feet(robot)):
foot_height = pe.utils.get_vals(foot.pyomo_vars["foot_height"], tuple())
if plot:
ax = plt.subplot(2, 2, idx + 1) # type: ignore
ax.plot(foot_height, label="Height", color=plot_color["charcoal"], marker="o")
ax.set_title(foot.name)
ax.legend()
ax2 = ax.twinx()
ax2.plot(foot_vel[:, idx, 2], label="Vel", color=plot_color["orange"], marker="o")
ax2.legend()
arg_height_heuristic = np.where(foot_height[:, 0] < (pe.foot.Foot3D.ground_plane_height + height_threshold))
arg_height_heuristic = group_by_consecutive_values(arg_height_heuristic[0])
_, arg_vel_zero_crossings = positive_zero_crossings(foot_vel[:, idx, 2])
idx += 1
contacts[foot.name] = []
contacts_tmp[foot.name] = []
arg_min_height = -1
for j, pos_foot_contact in enumerate(arg_height_heuristic):
if len(arg_height_heuristic[j]) == 0:
# No point in trying to determine a contact if there is nothing under the height heuristic.
continue
start_search = int(arg_min_height + 1)
arg_min_height = find_minimum_foot_height(
foot_height[:, 0],
(start_search, arg_height_heuristic[j + 1][0] if j + 1 < len(arg_height_heuristic) else -1),
)
possible_contact_detected = np.intersect1d(pos_foot_contact, arg_vel_zero_crossings)
is_contact = [arg_min_height + k not in possible_contact_detected for k in [-2, -1, 0, 1, 2]]
if np.all(is_contact):
# Update the arg_min_height to be at the end of the height heuristic so you do not detect the argmin of the same contact.
arg_min_height = arg_height_heuristic[j][-1]
continue
start_idx = int(arg_min_height - mid_way)
# start_idx = int(arg_height_heuristic[0][0])
end_idx = int(arg_min_height + mid_way)
# end_idx = start_idx + stance_time_fe
arg_min_height = arg_height_heuristic[j][-1]
if is_even:
start_idx += 1
if start_idx < 0:
end_idx -= start_idx
start_idx = 0
if end_idx >= len(robot.m.fe):
start_idx -= end_idx - len(robot.m.fe) - 1
end_idx = len(robot.m.fe) - 1
contacts[foot.name].append([start_frame + start_idx, start_frame + end_idx, i, "TBD"])
# A second approach to contact detection where only the height threshold is used and no prior on the stance length and zero velocity.
contacts_tmp[foot.name].append(
[int(start_frame + pos_foot_contact[0]), int(start_frame + pos_foot_contact[-1]), i, "TBD"]
)
# Set None for feet where there is no contact found.
if len(contacts[foot.name]) == 0:
contacts[foot.name] = None
contacts_tmp[foot.name] = None
if plot:
plt.show(block=False) # type: ignore
# Assuming a rotary gollap, trailing limb will correspond to the limb that is in contact first.
# and the leading limb will be in contact sometime after.
# TODO: When both limbs do not have a contact during the reconstruction, we can't tell which one is leading/trailing?
# Forelimbs
if contacts["HFL_foot"] != None and contacts["HFR_foot"] != None:
if contacts["HFL_foot"][0][0] > contacts["HFR_foot"][0][0]:
contacts["HFL_foot"][0][3] = "leading"
contacts["HFR_foot"][0][3] = "trailing"
else:
contacts["HFL_foot"][0][3] = "trailing"
contacts["HFR_foot"][0][3] = "leading"
# Hindlimbs
if contacts["HBL_foot"] != None and contacts["HBR_foot"] != None:
if contacts["HBL_foot"][0][0] > contacts["HBR_foot"][0][0]:
contacts["HBL_foot"][0][3] = "leading"
contacts["HBR_foot"][0][3] = "trailing"
else:
contacts["HBL_foot"][0][3] = "trailing"
contacts["HBR_foot"][0][3] = "leading"
# Save data to contacts file.
results = {"start_frame": start_frame, "end_frame": start_frame + len(cast(Any, robot).m.fe), "contacts": contacts}
results2 = {
"start_frame": start_frame,
"end_frame": start_frame + len(cast(Any, robot).m.fe),
"contacts": contacts_tmp,
}
grf_dir = os.path.join(data_dir, "grf")
os.makedirs(grf_dir, exist_ok=True)
with open(os.path.join(grf_dir, "autogen-contact.json"), "w", encoding="utf-8") as f:
json.dump(results, f)
f.close()
with open(os.path.join(grf_dir, "autogen-contact-02.json"), "w", encoding="utf-8") as f:
json.dump(results2, f)
return contacts, contacts_tmp
def synth_grf_data(
robot: pe.system.System3D,
speed: float,
direction: float,
data_dir: str,
contact_fname="autogen-contact.json",
out_fname="data_synth",
) -> None:
# Determine the linear models for the peak vertical force based on the speed of the cheetah (from Penny Hudson"s paper).
from scipy import interpolate
model_LFL = SimpleLinearModel([[9.0, 2.0], [15.0, 1.8]])
model_LHL = SimpleLinearModel([[9.0, 2.1], [15.0, 2.6]])
model_NLFL = SimpleLinearModel([[9.5, 2.1], [15.0, 2.0]])
model_NLHL = SimpleLinearModel([[9.0, 1.7], [15.0, 2.5]])
# 50% of the Fz peak will provide the cranial decceleration peak.
# 50% of the Fx dec peak will provide the cranial acceleration peak.
# Determine the contact times and generate the waveforms over that period.
with open(os.path.join(data_dir, contact_fname), "r", encoding="utf-8") 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"]
df_results = {}
for foot in pe.foot.feet(robot):
if (
foot.name in foot_contact_order
and foot_contact_order[foot.name] is not None
and foot_contact_order[foot.name][0][1] < end_frame
):
stance_start = 0
start_idx = foot_contact_order[foot.name][0][0] - 1
end_idx = foot_contact_order[foot.name][0][1] + 1
if start_idx < start_frame:
start_idx = start_frame
if end_idx > end_frame:
end_idx = end_frame
stance_end = end_idx - start_idx
peak_idx = stance_end // 2
t = np.linspace(stance_start, stance_end, stance_end)
Fz_peak, Fx_dec_peak, Fx_acc_peak = 0.0, 0.0, 0.0
if "F" in foot.name and foot_contact_order[foot.name][0][3] == "leading":
# LFL
Fz_peak = model_LFL.predict(speed)
Fx_dec_peak = direction * 0.5 * Fz_peak
Fx_acc_peak = 0.5 * -Fx_dec_peak
elif "F" in foot.name and foot_contact_order[foot.name][0][3] == "trailing":
# NLFL
Fz_peak = model_NLFL.predict(speed)
Fx_dec_peak = direction * 0.5 * Fz_peak
Fx_acc_peak = 0.5 * -Fx_dec_peak
elif "B" in foot.name and foot_contact_order[foot.name][0][3] == "leading":
# LHL
Fz_peak = model_LHL.predict(speed)
Fx_dec_peak = direction * 0.5 * Fz_peak
Fx_acc_peak = 0.5 * -Fx_dec_peak
elif "B" in foot.name and foot_contact_order[foot.name][0][3] == "trailing":
# NLHL
Fz_peak = model_NLHL.predict(speed)
Fx_dec_peak = direction * 0.5 * Fz_peak
Fx_acc_peak = 0.5 * -Fx_dec_peak
synth_Fz = Fz_peak * np.sin(np.pi * (t / stance_end))
Fx_control_pts = np.array(
[
[stance_start, 0.0],
[peak_idx // 2, Fx_dec_peak],
[peak_idx, 0.0],
[peak_idx + (stance_end - peak_idx) // 2, Fx_acc_peak],
[stance_end, 0.0],
]
)
x = interpolate.InterpolatedUnivariateSpline(Fx_control_pts[:, 0], Fx_control_pts[:, 1], k=2)
synth_Fx = x(t)
Fz_synth = np.zeros(end_frame - start_frame)
Fx_synth = np.zeros(end_frame - start_frame)
Fy_synth = np.zeros(end_frame - start_frame)
Fz_synth[start_idx - start_frame : end_idx - start_frame] = synth_Fz
Fx_synth[start_idx - start_frame : end_idx - start_frame] = synth_Fx
df_results[foot_contact_order[foot.name][0][2] - 1] = pd.DataFrame(
np.array([Fx_synth, Fy_synth, Fz_synth]).T, columns=["Fx", "Fy", "Fz"]
)
df_synth = pd.concat(df_results.values(), keys=df_results.keys(), axis=0)
df_synth.index.set_names(["force_plate", "frame"], inplace=True)
out_fname = os.path.join(data_dir, f"{out_fname}.h5")
df_synth.to_hdf(out_fname, "force_plate_data_df", format="table", mode="w")
def get_grf_profile(
robot: pe.system.System3D,
params: TrajectoryParams,
direction: float,
scale_forces_by: float,
out_dir_prefix: Optional[str] = None,
synthetic_data: bool = False,
) -> Tuple[Dict, Dict]:
# Note, this assumes a single stride! So it takes the first value for each foot in the contact JSON.
data_dir = (
params.data_dir
if (out_dir_prefix is None or not synthetic_data)
else os.path.join(out_dir_prefix, params.data_dir.split("cheetah_videos")[1])
)
grf_df = pd.read_hdf(os.path.join(data_dir, "grf", "data_synth.h5" if synthetic_data else "data.h5"))
with open(
(
os.path.join(data_dir, "grf/autogen-contact.json")
if synthetic_data
else os.path.join(params.data_dir, "metadata.json")
),
"r",
encoding="utf-8",
) as f:
contact_json = json.load(f)
start_frame = contact_json["start_frame"]
foot_contact_order = contact_json["contacts"]
gt_grf_z = {}
gt_grf_xy = {}
nfe = params.total_length
for foot in pe.foot.feet(robot):
gt_grf_z[foot.name] = [0.0] * nfe
gt_grf_xy[foot.name] = [[0.0] * foot.nsides for _ in range(nfe)]
# Check if the foot is in contact sequence.
if foot.name in foot_contact_order and foot_contact_order[foot.name] is not None:
grf = grf_df.query(f"force_plate == {foot_contact_order[foot.name][0][2]-1}")
# Resample data from 3500Hz to 200Hz i.e 2/35 factor.
if synthetic_data or (not params.kinetic_dataset):
Fz = grf["Fz"].values
Fx = grf["Fx"].values
Fy = grf["Fy"].values
else:
Fz = (
signal.resample_poly(remove_dc_offset(grf["Fz"].values, 500), up=2, down=35, axis=0)
* scale_forces_by
)
Fx = (
direction
* signal.resample_poly(remove_dc_offset(grf["Fx"].values, 500), up=2, down=35, axis=0)
* scale_forces_by
)
Fy = (
direction
* signal.resample_poly(remove_dc_offset(grf["Fy"].values, 500), up=2, down=35, axis=0)
* scale_forces_by