Repository navigation
Expand file tree
/
Copy pathdata_processing.py
More file actions
2846 lines (2359 loc) · 112 KB
/
Copy pathdata_processing.py
File metadata and controls
2846 lines (2359 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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 numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, Sampler
from sklearn.preprocessing import LabelEncoder
from torch.nn.utils.rnn import pad_sequence as pad_sequence_rnn
from scipy.spatial.transform import Rotation as R
from features import calculate_angular_velocity_from_quat, calculate_angular_distance
from augmentation import (
temporal_crop_augmentation,
sensor_dropout_augmentation,
simulate_sensor_communication_failure,
sensor_permutation_augmentation,
)
def remove_gravity_from_acc_improved(acc_data, rot_data):
"""Remove gravity component from acceleration using quaternion orientation with SLERP interpolation for missing quaternions."""
if isinstance(acc_data, pd.DataFrame):
acc_values = acc_data[["acc_x", "acc_y", "acc_z"]].values
else:
acc_values = acc_data
if isinstance(rot_data, pd.DataFrame):
quat_values = rot_data[["rot_x", "rot_y", "rot_z", "rot_w"]].values
else:
quat_values = rot_data
num_samples = acc_values.shape[0]
linear_accel = np.zeros_like(acc_values)
gravity_world = np.array([0, 0, 9.81])
# First pass: identify valid quaternions and create interpolated quaternions for missing ones
valid_mask = np.zeros(num_samples, dtype=bool)
interpolated_quats = quat_values.copy()
for i in range(num_samples):
is_valid = not (
np.all(np.isnan(quat_values[i])) or np.all(np.isclose(quat_values[i], 0))
)
if is_valid:
try:
# Test if quaternion is valid for scipy
R.from_quat(quat_values[i])
valid_mask[i] = True
except ValueError:
valid_mask[i] = False
else:
valid_mask[i] = False
# If we have at least 2 valid quaternions, interpolate missing ones
if np.sum(valid_mask) >= 2:
valid_indices = np.where(valid_mask)[0]
# Interpolate missing quaternions using SLERP
for i in range(num_samples):
if not valid_mask[i]:
# Find the nearest valid quaternions for interpolation
prev_idx = None
next_idx = None
# Find previous valid quaternion
for j in range(i - 1, -1, -1):
if valid_mask[j]:
prev_idx = j
break
# Find next valid quaternion
for j in range(i + 1, num_samples):
if valid_mask[j]:
next_idx = j
break
if prev_idx is not None and next_idx is not None:
# Interpolate between previous and next
t = (i - prev_idx) / (next_idx - prev_idx)
try:
rot_prev = R.from_quat(quat_values[prev_idx])
rot_next = R.from_quat(quat_values[next_idx])
# Use SLERP for smooth interpolation
rot_interp = rot_prev.inv() * rot_next
rot_slerp = rot_prev * R.from_rotvec(rot_interp.as_rotvec() * t)
interpolated_quats[i] = rot_slerp.as_quat()
except ValueError:
# If interpolation fails, use nearest valid quaternion
if t < 0.5:
interpolated_quats[i] = quat_values[prev_idx]
else:
interpolated_quats[i] = quat_values[next_idx]
elif prev_idx is not None:
# Only previous quaternion available, use it
interpolated_quats[i] = quat_values[prev_idx]
elif next_idx is not None:
# Only next quaternion available, use it
interpolated_quats[i] = quat_values[next_idx]
# If no valid quaternions found, will fall back to original acceleration
# Second pass: remove gravity using interpolated quaternions
for i in range(num_samples):
# Check if we have a valid quaternion (original or interpolated)
current_quat = interpolated_quats[i]
if np.all(np.isnan(current_quat)) or np.all(np.isclose(current_quat, 0)):
# Fall back to original acceleration if no quaternion available
linear_accel[i] = acc_values[i]
continue
try:
rotation = R.from_quat(current_quat)
gravity_sensor_frame = rotation.apply(gravity_world, inverse=True)
linear_accel[i] = acc_values[i] - gravity_sensor_frame
except ValueError:
# If quaternion is still invalid, fall back to original acceleration
linear_accel[i] = acc_values[i]
return linear_accel
def quaternion_multiply(q1, q2):
"""Multiply two quaternions q1 * q2
Args:
q1: quaternion [x, y, z, w]
q2: quaternion [x, y, z, w]
Returns:
quaternion product [x, y, z, w]
"""
x1, y1, z1, w1 = q1
x2, y2, z2, w2 = q2
x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
y = w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2
z = w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2
w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
return np.array([x, y, z, w])
def quaternion_conjugate(q):
"""Compute quaternion conjugate [x, y, z, w] -> [-x, -y, -z, w]
Args:
q: quaternion [x, y, z, w]
Returns:
quaternion conjugate [x, y, z, w]
"""
return np.array([-q[0], -q[1], -q[2], q[3]])
def quaternion_normalize(q):
"""Normalize quaternion to unit length
Args:
q: quaternion [x, y, z, w]
Returns:
normalized quaternion [x, y, z, w]
"""
norm = np.sqrt(np.sum(q**2))
if norm < 1e-8:
return np.array([0, 0, 0, 1]) # Identity quaternion
return q / norm
def quaternion_inverse(q):
"""Compute quaternion inverse (conjugate for unit quaternions)
Args:
q: quaternion [x, y, z, w]
Returns:
quaternion inverse [x, y, z, w]
"""
# For unit quaternions, inverse = conjugate
return quaternion_conjugate(q)
def quaternion_slerp(q1, q2, t):
"""Spherical linear interpolation between two quaternions
SLERP provides smooth interpolation between quaternions while preserving
the unit sphere property and avoiding gimbal lock issues.
Args:
q1: starting quaternion [x, y, z, w]
q2: ending quaternion [x, y, z, w]
t: interpolation parameter (0.0 = q1, 1.0 = q2)
Returns:
interpolated quaternion [x, y, z, w]
"""
# Ensure quaternions are normalized
q1 = quaternion_normalize(q1)
q2 = quaternion_normalize(q2)
# Compute the cosine of the angle between the quaternions
dot = np.dot(q1, q2)
# If the dot product is negative, slerp would take the long route
# To avoid this, we can flip one quaternion
if dot < 0.0:
q2 = -q2
dot = -dot
# If the quaternions are very close, use linear interpolation to avoid numerical instability
if dot > 0.9995:
result = q1 + t * (q2 - q1)
return quaternion_normalize(result)
# Calculate the angle between the quaternions
theta_0 = np.arccos(np.abs(dot))
sin_theta_0 = np.sin(theta_0)
theta = theta_0 * t
sin_theta = np.sin(theta)
# Compute the interpolated quaternion
s0 = np.cos(theta) - dot * sin_theta / sin_theta_0
s1 = sin_theta / sin_theta_0
result = s0 * q1 + s1 * q2
return quaternion_normalize(result)
def create_time_warped_sequences(df, warp_factors=[0.5, 2.0], include_original=True):
"""Create time-warped versions of sequences using proper interpolation
This function creates new sequences by resampling the original sequences at different
temporal scales. For each sequence, it generates:
- 0.5x speed (half timesteps): sequence is stretched in time (slower motion)
- 1.0x speed (original): unchanged sequence (optional)
- 2.0x speed (double timesteps): sequence is compressed in time (faster motion)
Uses SLERP for quaternions and linear interpolation for accelerations.
Args:
df: DataFrame with sequences containing 'sequence_id', quaternion, and acceleration columns
warp_factors: List of time warp factors (e.g., [0.5, 2.0] for half and double speed)
include_original: Whether to include the original sequences (1.0x speed)
Returns:
DataFrame with original and time-warped sequences
"""
print(f" Creating time-warped sequences with factors: {warp_factors}")
# Identify quaternion and acceleration columns
quat_cols = ["rot_x", "rot_y", "rot_z", "rot_w"]
acc_cols = ["acc_x", "acc_y", "acc_z"]
linear_acc_cols = ["linear_acc_x", "linear_acc_y", "linear_acc_z"]
# Check which columns exist in the dataframe
available_quat_cols = [col for col in quat_cols if col in df.columns]
available_acc_cols = [col for col in acc_cols if col in df.columns]
available_linear_acc_cols = [col for col in linear_acc_cols if col in df.columns]
if len(available_quat_cols) != 4:
raise ValueError(
f"Missing quaternion columns. Expected {quat_cols}, found {available_quat_cols}"
)
if len(available_acc_cols) != 3:
raise ValueError(
f"Missing acceleration columns. Expected {acc_cols}, found {available_acc_cols}"
)
# Other columns that need linear interpolation
other_numeric_cols = []
for col in df.columns:
if col not in (
[
"sequence_id",
"subject",
"gesture",
"orientation",
"phase",
"sequence_counter",
]
+ available_quat_cols
+ available_acc_cols
+ available_linear_acc_cols
):
# Check if column is numeric and not categorical
if pd.api.types.is_numeric_dtype(df[col]) and not (
df[col].dtype.name.startswith("int") and col.endswith("_int")
):
other_numeric_cols.append(col)
all_sequences = []
sequences_to_process = df.groupby("sequence_id")
# Add original sequences if requested
if include_original:
all_sequences.append(df.copy())
print(f" Including {len(sequences_to_process)} original sequences")
# Process each warp factor
for warp_factor in warp_factors:
print(f" Creating sequences with warp factor {warp_factor}x...")
warped_sequences = []
for seq_id, seq_df in sequences_to_process:
# Sort by sequence_counter to ensure temporal order
seq_df = seq_df.sort_values("sequence_counter").reset_index(drop=True)
original_length = len(seq_df)
if original_length < 3:
# Skip sequences that are too short for interpolation
continue
# Calculate new length based on warp factor
# warp_factor < 1.0: stretch sequence (more timesteps, slower motion)
# warp_factor > 1.0: compress sequence (fewer timesteps, faster motion)
new_length = max(2, int(original_length / warp_factor))
# Create interpolation indices
original_indices = np.arange(original_length)
new_indices = np.linspace(0, original_length - 1, new_length)
# Initialize warped sequence dataframe
warped_seq = seq_df.iloc[[0]].copy() # Start with first row as template
warped_seq = pd.concat([warped_seq] * new_length, ignore_index=True)
warped_seq = (
warped_seq.copy()
) # Ensure we have a clean copy to avoid warnings
# Update sequence metadata
warped_seq["sequence_id"] = f"{seq_id}_warp_{warp_factor:g}x"
warped_seq["sequence_counter"] = np.arange(new_length)
# Interpolate quaternions using SLERP
original_quats = seq_df[available_quat_cols].values
# Pre-allocate quaternion arrays for efficiency
new_quats = np.zeros((new_length, 4))
for i, new_idx in enumerate(new_indices):
if new_idx == int(new_idx) and int(new_idx) < original_length:
# Exact match, no interpolation needed
new_quats[i] = original_quats[int(new_idx)]
else:
# Interpolation needed
idx_low = int(np.floor(new_idx))
idx_high = min(idx_low + 1, original_length - 1)
t = new_idx - idx_low
if idx_low == idx_high:
# At the end, use the last quaternion
new_quats[i] = original_quats[idx_low]
else:
# SLERP between two quaternions
q1 = original_quats[idx_low]
q2 = original_quats[idx_high]
new_quats[i] = quaternion_slerp(q1, q2, t)
# Update all quaternion columns at once
warped_seq[available_quat_cols] = new_quats
# Interpolate accelerations using linear interpolation
for col_group in [available_acc_cols, available_linear_acc_cols]:
if not col_group:
continue
for col in col_group:
original_values = seq_df[col].values
interpolated_values = np.interp(
new_indices, original_indices, original_values
)
warped_seq[col] = interpolated_values
# Interpolate other numeric columns using linear interpolation
for col in other_numeric_cols:
if col in seq_df.columns:
original_values = seq_df[col].values
# Handle NaN values
if np.any(np.isnan(original_values)):
# For columns with NaN, interpolate only non-NaN values
valid_mask = ~np.isnan(original_values)
if np.sum(valid_mask) > 1:
valid_indices = original_indices[valid_mask]
valid_values = original_values[valid_mask]
interpolated_values = np.interp(
new_indices, valid_indices, valid_values
)
else:
# Not enough valid values, fill with the first valid value or 0
fill_value = (
original_values[valid_mask][0]
if np.sum(valid_mask) > 0
else 0.0
)
interpolated_values = np.full(new_length, fill_value)
else:
interpolated_values = np.interp(
new_indices, original_indices, original_values
)
warped_seq[col] = interpolated_values
# Copy non-numeric columns from the first row (they should be the same for the whole sequence)
categorical_cols = ["subject", "gesture", "orientation", "phase"]
for col in categorical_cols:
if col in seq_df.columns:
warped_seq[col] = seq_df[col].iloc[0]
# Copy integer label columns from the first row
label_cols = [col for col in seq_df.columns if col.endswith("_int")]
for col in label_cols:
warped_seq[col] = seq_df[col].iloc[0]
warped_sequences.append(warped_seq)
if warped_sequences:
warped_df = pd.concat(warped_sequences, ignore_index=True)
all_sequences.append(warped_df)
print(
f" Created {len(warped_sequences)} warped sequences with factor {warp_factor}x"
)
# Combine all sequences
if all_sequences:
result_df = pd.concat(all_sequences, ignore_index=True)
original_count = len(sequences_to_process)
total_count = len(result_df.groupby("sequence_id"))
print(" ✅ Time warping completed:")
print(f" Original sequences: {original_count}")
print(f" Total sequences (including warped): {total_count}")
print(f" Total timesteps: {len(result_df)}")
return result_df
else:
print(" ⚠️ No sequences could be processed for time warping")
return df
def test_time_warping():
"""Test time warping functionality with a simple synthetic sequence"""
print(" Testing time warping implementation...")
# Create a simple test sequence
test_data = {
"sequence_id": ["test_seq"] * 10,
"sequence_counter": list(range(10)),
"subject": ["test_subject"] * 10,
"gesture": ["test_gesture"] * 10,
"orientation": ["test_orientation"] * 10,
"phase": ["Gesture"] * 10,
# Simple quaternion rotation (90 degree rotation around Z-axis over time)
"rot_x": [0.0] * 10,
"rot_y": [0.0] * 10,
"rot_z": np.sin(np.linspace(0, np.pi / 4, 10)), # Gradual rotation
"rot_w": np.cos(np.linspace(0, np.pi / 4, 10)),
# Simple acceleration pattern
"acc_x": np.sin(np.linspace(0, 2 * np.pi, 10)),
"acc_y": np.cos(np.linspace(0, 2 * np.pi, 10)),
"acc_z": [9.81] * 10, # Gravity
"linear_acc_x": np.sin(np.linspace(0, 2 * np.pi, 10)),
"linear_acc_y": np.cos(np.linspace(0, 2 * np.pi, 10)),
"linear_acc_z": [0.0] * 10,
}
df_test = pd.DataFrame(test_data)
# Test time warping
try:
df_warped = create_time_warped_sequences(
df_test, warp_factors=[0.5, 2.0], include_original=True
)
# Verify results
sequence_ids = df_warped["sequence_id"].unique()
expected_ids = ["test_seq", "test_seq_warp_0.5x", "test_seq_warp_2x"]
assert len(sequence_ids) == 3, f"Expected 3 sequences, got {len(sequence_ids)}"
for expected_id in expected_ids:
assert expected_id in sequence_ids, f"Missing sequence: {expected_id}"
# Check sequence lengths
for seq_id in sequence_ids:
seq_data = df_warped[df_warped["sequence_id"] == seq_id]
if seq_id == "test_seq":
assert len(seq_data) == 10, (
f"Original sequence should have 10 timesteps, got {len(seq_data)}"
)
elif seq_id == "test_seq_warp_0.5x":
assert len(seq_data) == 20, (
f"0.5x warped sequence should have 20 timesteps, got {len(seq_data)}"
)
elif seq_id == "test_seq_warp_2x":
assert len(seq_data) == 5, (
f"2x warped sequence should have 5 timesteps, got {len(seq_data)}"
)
# Check quaternion normalization
for seq_id in sequence_ids:
seq_data = df_warped[df_warped["sequence_id"] == seq_id]
quat_norms = np.sqrt(
seq_data["rot_x"] ** 2
+ seq_data["rot_y"] ** 2
+ seq_data["rot_z"] ** 2
+ seq_data["rot_w"] ** 2
)
assert np.allclose(quat_norms, 1.0, atol=1e-6), (
f"Quaternions not normalized in {seq_id}"
)
print(" ✅ Time warping test passed:")
print(f" Created {len(sequence_ids)} sequences from 1 original")
print(
f" Sequence lengths: {[len(df_warped[df_warped['sequence_id'] == sid]) for sid in sequence_ids]}"
)
print(" Quaternion normalization preserved")
print(" Interpolation completed successfully")
return True
except Exception as e:
print(f" ❌ Time warping test failed: {e}")
return False
def normalize_quaternion_sequence(quaternion_sequence):
"""Normalize a quaternion sequence to start at identity quaternion
This function takes the first quaternion in the sequence as the reference
orientation and rotates all quaternions in the sequence such that the
sequence starts at the identity quaternion [0, 0, 0, 1].
This removes initial orientation bias and makes sequences comparable
regardless of starting hand position.
Args:
quaternion_sequence: array of quaternions with shape (n_timesteps, 4)
columns should be [x, y, z, w]
Returns:
normalized quaternion sequence with same shape, starting at identity
"""
if len(quaternion_sequence) == 0:
return quaternion_sequence
# Get the first quaternion as reference orientation
q_reference = quaternion_sequence[0].copy()
q_reference = quaternion_normalize(q_reference) # Ensure normalized
# Compute the inverse of the reference quaternion
q_reference_inv = quaternion_inverse(q_reference)
# Apply the inverse rotation to all quaternions in the sequence
normalized_sequence = np.zeros_like(quaternion_sequence)
for i, q_current in enumerate(quaternion_sequence):
q_current = quaternion_normalize(q_current) # Ensure normalized
# q_normalized = q_reference_inv * q_current
q_normalized = quaternion_multiply(q_reference_inv, q_current)
q_normalized = quaternion_normalize(q_normalized) # Ensure result is normalized
normalized_sequence[i] = q_normalized
return normalized_sequence
def normalize_quaternion_sequences_dataframe(df, enable_normalization=True):
"""Normalize quaternion sequences in a DataFrame to start at identity
This function processes all sequences in the DataFrame and normalizes
their quaternion data so each sequence starts at the identity quaternion.
Args:
df: DataFrame with columns ['sequence_id', 'rot_x', 'rot_y', 'rot_z', 'rot_w']
enable_normalization: If False, returns original df unchanged
Returns:
DataFrame with normalized quaternion sequences
"""
if not enable_normalization:
print(" Quaternion sequence normalization disabled")
return df
print(" Normalizing quaternion sequences to start at identity orientation...")
df_normalized = df.copy()
# Process each sequence separately
for seq_id, seq_group in df.groupby("sequence_id"):
# Extract quaternion data
quat_data = seq_group[["rot_x", "rot_y", "rot_z", "rot_w"]].values
# Normalize the quaternion sequence
quat_normalized = normalize_quaternion_sequence(quat_data)
# Update the DataFrame with normalized quaternions
seq_indices = seq_group.index
df_normalized.loc[seq_indices, "rot_x"] = quat_normalized[:, 0]
df_normalized.loc[seq_indices, "rot_y"] = quat_normalized[:, 1]
df_normalized.loc[seq_indices, "rot_z"] = quat_normalized[:, 2]
df_normalized.loc[seq_indices, "rot_w"] = quat_normalized[:, 3]
# Validate normalization
first_quaternions = df_normalized.groupby("sequence_id")[
["rot_x", "rot_y", "rot_z", "rot_w"]
].first()
identity_check = np.allclose(
first_quaternions[["rot_x", "rot_y", "rot_z"]].values, 0.0, atol=1e-6
) and np.allclose(first_quaternions["rot_w"].values, 1.0, atol=1e-6)
if identity_check:
print(
f" ✅ All {len(first_quaternions)} sequences now start at identity quaternion"
)
else:
print(" ⚠️ Warning: Some sequences may not have been properly normalized")
# Print some stats for debugging
print(
f" First rot_x range: [{first_quaternions['rot_x'].min():.6f}, {first_quaternions['rot_x'].max():.6f}]"
)
print(
f" First rot_y range: [{first_quaternions['rot_y'].min():.6f}, {first_quaternions['rot_y'].max():.6f}]"
)
print(
f" First rot_z range: [{first_quaternions['rot_z'].min():.6f}, {first_quaternions['rot_z'].max():.6f}]"
)
print(
f" First rot_w range: [{first_quaternions['rot_w'].min():.6f}, {first_quaternions['rot_w'].max():.6f}]"
)
return df_normalized
def test_quaternion_sequence_normalization():
"""Test quaternion sequence normalization with known test cases"""
print(" Testing quaternion sequence normalization...")
# Test case 1: Sequence starting with identity should remain unchanged
seq_identity = np.array(
[
[0, 0, 0, 1], # Identity quaternion
[0.1, 0.2, 0.3, 0.9], # Some rotation
[0.2, 0.1, 0.4, 0.8], # Another rotation
]
)
# Normalize the test quaternions first
for i in range(len(seq_identity)):
seq_identity[i] = quaternion_normalize(seq_identity[i])
normalized = normalize_quaternion_sequence(seq_identity)
# First quaternion should be identity
identity_check = np.allclose(normalized[0], [0, 0, 0, 1], atol=1e-6)
assert identity_check, "First quaternion should be identity after normalization"
# Test case 2: Sequence starting with arbitrary quaternion
seq_arbitrary = np.array(
[
[0.5, 0.3, 0.2, 0.8], # Starting orientation
[0.1, 0.4, 0.1, 0.9], # Some rotation from start
[0.3, 0.2, 0.5, 0.7], # Another rotation
]
)
# Normalize the test quaternions first
for i in range(len(seq_arbitrary)):
seq_arbitrary[i] = quaternion_normalize(seq_arbitrary[i])
normalized = normalize_quaternion_sequence(seq_arbitrary)
# First quaternion should be identity
identity_check = np.allclose(normalized[0], [0, 0, 0, 1], atol=1e-6)
assert identity_check, "First quaternion should be identity after normalization"
# All quaternions should be normalized
for i, q in enumerate(normalized):
norm = np.sqrt(np.sum(q**2))
assert np.allclose(norm, 1.0, atol=1e-6), (
f"Quaternion {i} not normalized: norm = {norm}"
)
# Test case 3: Verify relative rotations are preserved
# The angular difference between consecutive quaternions should be preserved
def quaternion_angular_distance(q1, q2):
"""Calculate angular distance between two quaternions"""
# Compute relative rotation: q_rel = q2 * conjugate(q1)
q1_conj = quaternion_conjugate(q1)
q_rel = quaternion_multiply(q2, q1_conj)
# Angular distance is 2 * arccos(|w|) where w is the scalar part
return 2 * np.arccos(np.abs(q_rel[3]).clip(0, 1))
# Calculate angular distances in original sequence
original_distances = []
for i in range(len(seq_arbitrary) - 1):
dist = quaternion_angular_distance(seq_arbitrary[i], seq_arbitrary[i + 1])
original_distances.append(dist)
# Calculate angular distances in normalized sequence
normalized_distances = []
for i in range(len(normalized) - 1):
dist = quaternion_angular_distance(normalized[i], normalized[i + 1])
normalized_distances.append(dist)
# Angular distances should be preserved (relative motion is the same)
distances_preserved = np.allclose(
original_distances, normalized_distances, rtol=1e-3, atol=1e-6
)
assert distances_preserved, (
"Relative angular motions should be preserved after normalization"
)
print(" - Quaternion sequence normalization tests passed")
print(" - Identity starting position verified")
print(" - Quaternion normalization verified")
print(" - Relative motion preservation verified")
def apply_quaternion_reflection(q, reflection_axis="y"):
"""Apply reflection transformation to quaternion
For left-right hand flipping (reflection across Y-Z plane):
- reflection_axis='y': reflects across Y-Z plane (flips X-axis) - CORRECT for hand flipping
- reflection_axis='x': reflects across X-Z plane (flips Y-axis) - INCORRECT for hand flipping
- reflection_axis='z': reflects across X-Y plane (flips Z-axis)
Args:
q: quaternion [x, y, z, w]
reflection_axis: axis of reflection ('x', 'y', or 'z')
Returns:
reflected quaternion [x, y, z, w]
"""
# For left-right hand flipping (reflection across Y-Z plane), we need to flip the X-axis
# This is equivalent to negating the X component of the quaternion
# The correct transformation is: [x, y, z, w] -> [-x, y, z, w]
if reflection_axis == "y":
# Reflection across Y-Z plane (flips X-axis)
q_reflected = np.array([-q[0], q[1], q[2], q[3]])
elif reflection_axis == "x":
# Reflection across X-Z plane (flips Y-axis)
q_reflected = np.array([q[0], -q[1], q[2], q[3]])
elif reflection_axis == "z":
# Reflection across X-Y plane (flips Z-axis)
q_reflected = np.array([q[0], q[1], -q[2], q[3]])
else:
raise ValueError(
f"Invalid reflection axis: {reflection_axis}. Must be 'x', 'y', or 'z'"
)
# Note: We don't normalize here because the input quaternion should already be normalized
# and the reflection transformation preserves the norm (magnitude)
# The small numerical differences are expected and handled by the validation functions
return q_reflected
def apply_quaternion_reflection_vectorized(quaternions, reflection_axis="y"):
"""Apply reflection transformation to quaternions (vectorized version)
Args:
quaternions: array of quaternions with shape (n_samples, 4) or DataFrame with rot_x, rot_y, rot_z, rot_w columns
reflection_axis: axis of reflection ('x', 'y', or 'z')
Returns:
reflected quaternions with same shape as input
"""
if isinstance(quaternions, pd.DataFrame):
# Extract quaternion components
q_array = quaternions[["rot_x", "rot_y", "rot_z", "rot_w"]].values
is_dataframe = True
else:
q_array = quaternions
is_dataframe = False
# Apply reflection to each quaternion
reflected_quaternions = np.zeros_like(q_array)
for i in range(len(q_array)):
reflected_quaternions[i] = apply_quaternion_reflection(
q_array[i], reflection_axis
)
if is_dataframe:
# Return as DataFrame with same column names
result_df = quaternions.copy()
result_df["rot_x"] = reflected_quaternions[:, 0]
result_df["rot_y"] = reflected_quaternions[:, 1]
result_df["rot_z"] = reflected_quaternions[:, 2]
result_df["rot_w"] = reflected_quaternions[:, 3]
return result_df
else:
return reflected_quaternions
class FixedLengthSampler(Sampler):
"""Samples a fixed number of batches per epoch, regardless of dataset size."""
def __init__(self, dataset, steps_per_epoch=1000, batch_size=32):
super().__init__(dataset)
self.dataset_len = len(dataset)
self.steps_per_epoch = steps_per_epoch
self.batch_size = batch_size
self.total_samples = self.steps_per_epoch * self.batch_size
def __iter__(self):
# Generate indices for the entire epoch at once
indices = np.random.randint(
0, self.dataset_len, size=(self.steps_per_epoch, self.batch_size)
)
# Flatten the batch dimension to match DataLoader's expectations
return iter(indices.flatten().tolist())
def __len__(self):
return self.total_samples
def prepare_training_data(
df,
train_dem_df,
enable_quaternion_normalization=False,
target_column="gesture",
enable_time_warping=True,
time_warp_factors=[0.5, 2.0],
):
"""Prepare and engineer features for training data"""
# CRITICAL: Ensure temporal ordering before ANY diff() operations
print(" Ensuring temporal ordering by sequence_counter...")
if "sequence_counter" not in df.columns:
raise ValueError(
"sequence_counter column is required for temporal ordering but not found in data!"
)
# Sort by sequence_id and sequence_counter to guarantee temporal order within each sequence
df = df.sort_values(["sequence_id", "sequence_counter"]).reset_index(drop=True)
print(
f" ✅ Data sorted by temporal order: {len(df)} timesteps across {df['sequence_id'].nunique()} sequences"
)
# Apply time warping BEFORE any feature engineering to create temporal variations
if enable_time_warping:
print(" Applying time warping augmentation...")
df = create_time_warped_sequences(
df, warp_factors=time_warp_factors, include_original=True
)
print(
f" ✅ Time warping completed: {len(df)} timesteps across {df['sequence_id'].nunique()} sequences"
)
df_for_groups = pd.merge(df.copy(), train_dem_df, on="subject", how="left")
# Create timestep-level labels
print(" Creating timestep-level labels...")
# When phase is "Gesture", use the gesture class; when "Transition", use "Transition" class
df["timestep_label"] = df.apply(
lambda row: row["gesture"] if row["phase"] == "Gesture" else "Transition",
axis=1,
)
# Create label encoder for timestep-level labels (includes "Transition" class)
le = LabelEncoder()
df["timestep_label_int"] = le.fit_transform(df["timestep_label"])
# Create separate label encoder for original target labels (for stratification)
le_gesture = LabelEncoder()
le_orientation = LabelEncoder()
if isinstance(target_column, list):
df[f"{target_column[0]}_int"] = le_gesture.fit_transform(df[target_column[0]])
df[f"{target_column[1]}_int"] = le_orientation.fit_transform(
df[target_column[1]]
)
else:
df[f"{target_column}_int"] = le_gesture.fit_transform(df[target_column])
# CRITICAL: Remove gravity FIRST using original absolute quaternions
# Gravity removal needs absolute orientation information to work correctly
print(" Removing gravity using original absolute quaternions...")
linear_accel_list = []
for _, group in df.groupby("sequence_id"):
acc_data_group = group[["acc_x", "acc_y", "acc_z"]]
rot_data_group = group[["rot_x", "rot_y", "rot_z", "rot_w"]]
linear_accel_group = remove_gravity_from_acc_improved(
acc_data_group, rot_data_group
)
linear_accel_list.append(
pd.DataFrame(
linear_accel_group,
columns=["linear_acc_x", "linear_acc_y", "linear_acc_z"],
index=group.index,
)
) # type: ignore
df_linear_accel = pd.concat(linear_accel_list)
df = pd.concat([df, df_linear_accel], axis=1)
# NOW apply quaternion sequence normalization AND acceleration alignment AFTER gravity removal
# This preserves correct gravity removal while ensuring frame consistency
if enable_quaternion_normalization:
# test_quaternion_sequence_normalization() # Run tests first
df = normalize_quaternion_sequences_with_acceleration_alignment(
df, enable_normalization=True
)
print(
" ✅ Quaternion sequence normalization completed - all sequences start at identity"
)
print(
" ✅ Acceleration alignment completed - accelerations now in normalized frame"
)
print(" ✅ Frame consistency ensured between quaternions and accelerations")
else:
print(" Quaternion sequence normalization disabled")
print(
" Calculating base engineered IMU features (magnitude, angle) from normalized quaternions..."
)
df["acc_mag"] = np.sqrt(df["acc_x"] ** 2 + df["acc_y"] ** 2 + df["acc_z"] ** 2)
df["rot_angle"] = 2 * np.arccos(df["rot_w"].clip(-1, 1))
print(" Calculating engineered IMU derivatives (jerk, angular velocity)...")
df["acc_mag_jerk"] = df.groupby("sequence_id")["acc_mag"].diff().fillna(0)
df["rot_angle_vel"] = df.groupby("sequence_id")["rot_angle"].diff().fillna(0)
df["linear_acc_mag"] = np.sqrt(
df["linear_acc_x"] ** 2 + df["linear_acc_y"] ** 2 + df["linear_acc_z"] ** 2
)
df["linear_acc_mag_jerk"] = (
df.groupby("sequence_id")["linear_acc_mag"].diff().fillna(0)
)
print(" Calculating gravity-aware features...")
# Ratio of total to linear acceleration magnitude (captures gravity influence)
df["gravity_influence_ratio"] = df["acc_mag"] / (
df["linear_acc_mag"] + 1e-8
) # Add small epsilon to avoid division by zero
# Difference between raw and linear acceleration magnitudes (gravity component magnitude)
df["gravity_component_mag"] = df["acc_mag"] - df["linear_acc_mag"]
print(" Calculating angular velocity from normalized quaternion derivatives...")
angular_vel_list = []
for _, group in df.groupby("sequence_id"):
rot_data_group = group[["rot_x", "rot_y", "rot_z", "rot_w"]]
angular_vel_group = calculate_angular_velocity_from_quat(rot_data_group)
angular_vel_list.append(
pd.DataFrame(
angular_vel_group,
columns=["angular_vel_x", "angular_vel_y", "angular_vel_z"],
index=group.index,
)
) # type: ignore
df_angular_vel = pd.concat(angular_vel_list)
df = pd.concat([df, df_angular_vel], axis=1)
# Angular speed magnitude (per-sample, constant dt assumed)
# df['angular_vel_mag'] = np.sqrt(
# df['angular_vel_x']**2 + df['angular_vel_y']**2 + df['angular_vel_z']**2
# )
# First derivative of angular speed magnitude (per-sample diff within sequence)
# df['angular_vel_mag_accel'] = df.groupby('sequence_id')['angular_vel_mag'].diff().fillna(0)
print(" Calculating angular distance between successive normalized quaternions...")
angular_distance_list = []
for _, group in df.groupby("sequence_id"):
rot_data_group = group[["rot_x", "rot_y", "rot_z", "rot_w"]]
angular_dist_group = calculate_angular_distance(rot_data_group)
angular_distance_list.append(
pd.DataFrame(
angular_dist_group, columns=["angular_distance"], index=group.index
)
) # type: ignore
df_angular_distance = pd.concat(angular_distance_list)
df = pd.concat([df, df_angular_distance], axis=1)
print(
" Calculating per-axis derivatives (jerk, snap) and integrals (velocity, position)..."
)
# Per-axis derivatives for raw acceleration (includes gravity effects)
df["acc_x_jerk"] = df.groupby("sequence_id")["acc_x"].diff().fillna(0)
df["acc_y_jerk"] = df.groupby("sequence_id")["acc_y"].diff().fillna(0)
df["acc_z_jerk"] = df.groupby("sequence_id")["acc_z"].diff().fillna(0)
df["acc_x_snap"] = df.groupby("sequence_id")["acc_x_jerk"].diff().fillna(0)
df["acc_y_snap"] = df.groupby("sequence_id")["acc_y_jerk"].diff().fillna(0)
df["acc_z_snap"] = df.groupby("sequence_id")["acc_z_jerk"].diff().fillna(0)
# Per-axis derivatives for linear acceleration (gravity-removed)
df["linear_acc_x_jerk"] = df.groupby("sequence_id")["linear_acc_x"].diff().fillna(0)
df["linear_acc_y_jerk"] = df.groupby("sequence_id")["linear_acc_y"].diff().fillna(0)
df["linear_acc_z_jerk"] = df.groupby("sequence_id")["linear_acc_z"].diff().fillna(0)
df["linear_acc_x_snap"] = (
df.groupby("sequence_id")["linear_acc_x_jerk"].diff().fillna(0)
)