-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcm_log_processing.py
More file actions
2566 lines (2231 loc) · 111 KB
/
lcm_log_processing.py
File metadata and controls
2566 lines (2231 loc) · 111 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
"""Get messages from desired LCM channels from an LCM log between provided
start and end times. Uses the virtual environment installed at
ci_mpc_utils/venv.
source /home/bibit/ci_mpc_utils/venv/bin/activate
Example usage:
# TODO: `single` command is currently broken.
python lcm_log_processing.py single /mnt/data2/sharanya/logs/2024/12_16_24/000006/ --interactive --start=50 --end=100
python lcm_log_processing.py multi /home/bibit/Videos/franka_experiments/2025/01_29_25/000007
"""
import click
import os
import os.path as op
import pickle
import shutil
import subprocess
from tqdm import tqdm
from typing import List, Tuple
from lcm import EventLog
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
import matplotlib.ticker as mtick
import numpy as np
from scipy.spatial.transform import Rotation as R
from scipy.stats import gaussian_kde
import yaml
from pydrake.common.eigen_geometry import Quaternion
from pydrake.geometry import HalfSpace, MeshcatVisualizer, StartMeshcat, \
ClippingRange, DepthRange, DepthRenderCamera, \
RenderCameraCore, MakeRenderEngineVtk, RenderEngineVtkParams
from pydrake.math import RigidTransform, RollPitchYaw
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import AddMultibodyPlant, MultibodyPlantConfig
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.sensors import CameraInfo, RgbdSensor
from pydrake.trajectories import PiecewisePolynomial, \
PiecewiseQuaternionSlerp, StackedTrajectory
from pydrake.visualization import VideoWriter
import file_utils
file_utils.add_dair_lcmtypes_to_path()
import dairlib
# Add to this dictionary to include more LCM channels from which to read.
ALL_CHANNELS_AND_LCMT = {
'C3_ACTUAL': dairlib.lcmt_c3_state,
'C3_FINAL_TARGET': dairlib.lcmt_c3_state,
'SAMPLE_BUFFER': dairlib.lcmt_sample_buffer,
'SAMPLE_LOCATIONS': dairlib.lcmt_timestamped_saved_traj,
'SAMPLE_COSTS': dairlib.lcmt_timestamped_saved_traj,
'C3_TRAJECTORY_ACTOR_CURR_PLAN': dairlib.lcmt_timestamped_saved_traj,
'C3_TRAJECTORY_ACTOR_BEST_PLAN': dairlib.lcmt_timestamped_saved_traj,
'SAMPLING_C3_DEBUG': dairlib.lcmt_sampling_c3_debug,
'SAMPLING_C3_RADIO': dairlib.lcmt_radio_out,
'FRANKA_STATE': dairlib.lcmt_robot_output,
'FRANKA_STATE_SIMULATION': dairlib.lcmt_robot_output,
'OBJECT_STATE': dairlib.lcmt_object_state,
}
MINIMAL_CHANNELS_AND_LCMT = {
'SAMPLE_BUFFER': dairlib.lcmt_sample_buffer,
'SAMPLING_C3_DEBUG': dairlib.lcmt_sampling_c3_debug,
}
MINIMAL_CHANNELS_AND_LCMT_FOR_VIDEO = {
'SAMPLE_BUFFER': dairlib.lcmt_sample_buffer,
'SAMPLING_C3_DEBUG': dairlib.lcmt_sampling_c3_debug,
'C3_ACTUAL': dairlib.lcmt_c3_state,
'C3_FINAL_TARGET': dairlib.lcmt_c3_state,
}
MINIMAL_CHANNELS_AND_LCMT_FOR_MJPC = {
'C3_ACTUAL': dairlib.lcmt_c3_state,
'C3_FINAL_TARGET': dairlib.lcmt_c3_state,
}
CHANNELS_AND_LCMT_TO_SYNC = {
key: val for key, val in ALL_CHANNELS_AND_LCMT.items() \
if key not in ['SAMPLING_C3_RADIO', 'FRANKA_STATE', 'OBJECT_STATE']}
LCM_TIME_KEY = 'lcm_seconds'
MESSAGE_TIME_KEY = 'msg_seconds'
MESSAGE_KEY = 'message'
JOINT_LIMIT_VIO_KEY = 'joint_limit_violation'
JOINT_VEL_VIO_KEY = 'joint_velocity_violation'
JOINT_ACC_VIO_KEY = 'joint_acceleration_violation'
JOINT_JERK_VIO_KEY = 'joint_jerk_violation'
JOINT_TORQUE_VIO_KEY = 'joint_torque_violation'
WSL_VIO_KEY = 'workspace_limit_violation'
TRAJ_PARAM_POS_TOL_KEY = 'position_success_threshold'
TRAJ_PARAM_RAD_TOL_KEY = 'orientation_success_threshold'
C3_PARAM_WSL_X_KEY = 'world_x_limits'
C3_PARAM_WSL_Y_KEY = 'world_y_limits'
C3_PARAM_WSL_Z_KEY = 'world_z_limits'
C3_PARAM_WSL_R_KEY = 'robot_radius_limits'
EXPORT_FOLDER = '/mnt/data2/bibit/control_exports'
# Labels for the source of repositioning targets.
NO_TARGET_LABEL = 'N/A'
PREV_REPOS_TARGET_LABEL = 'previous repositioning target'
NEW_SAMPLE_TARGET_LABEL = 'new sample target'
BUFFER_SAMPLE_TARGET_LABEL = 'buffer sample target'
PURSUED_TARGET_LABELS = [NO_TARGET_LABEL,
PREV_REPOS_TARGET_LABEL,
NEW_SAMPLE_TARGET_LABEL,
BUFFER_SAMPLE_TARGET_LABEL]
# Labels for the reason behind switching modes.
NO_SWITCH_LABEL = 'N/A'
TO_C3_LOWER_COST_SWITCH_LABEL = 'Switch to Contact-Rich: lower cost'
TO_C3_REACHED_TARGET_SWITCH_LABEL = \
'Switch to Contact-Rich: reached pursued sample'
TO_REPOS_LOWER_COST_SWITCH_LABEL = 'Switch to Contact-Free: lower cost'
TO_REPOS_UNPRODUCTIVE_SWITCH_LABEL = 'Switch to Contact-Free: unproductivity'
TO_C3_XBOX_FORCED_SWITCH_LABEL = 'Switch to Contact-Rich: Xbox'
MODE_SWITCH_LABELS = [NO_SWITCH_LABEL,
TO_C3_LOWER_COST_SWITCH_LABEL,
TO_C3_REACHED_TARGET_SWITCH_LABEL,
TO_REPOS_LOWER_COST_SWITCH_LABEL,
TO_REPOS_UNPRODUCTIVE_SWITCH_LABEL,
TO_C3_XBOX_FORCED_SWITCH_LABEL]
MODE_SWITCH_COLORS = ['black', '#f78b8e', '#ffcc80', '#a5c493', '#c495f0',
'purple']
CF_COLOR = '#bbbbbb'
CR_COLOR = 'white'
POS_ERROR_COLOR = 'black'
RAD_ERROR_COLOR = 'purple'
# Other success thresholds.
# POS_SUCCESS_THRESHOLDS = np.array([0.01, 0.02, 0.03, 0.04, 0.05])
# RAD_SUCCESS_THRESHOLDS = np.array([0.05, 0.1, 0.2, 0.3, 0.4])
# THRESHOLD_COLORS = ['black', 'red', 'darkorange', 'gold', 'green']
POS_SUCCESS_THRESHOLDS = np.array([0.02, 0.05])
RAD_SUCCESS_THRESHOLDS = np.array([0.1, 0.4])
THRESHOLD_COLORS = ['red', 'blue']
EPS = 1e-5
TIME_SYNCH_THRESH = 0.03
HIST_BINS = 10
CDF_TIME_CUTOFF = 300
TOO_LONG_TIME_CUTOFF = 400
CAM_FOV = np.pi/6
VIDEO_PIXELS = [480, 640]
VIDEO_FPS = 30
# Front video view (for the jack).
SENSOR_RPY_FRONT = np.array([-np.pi / 2, 0, np.pi / 2])
SENSOR_POSITION_FRONT = np.array([2., 0., 0.2])
SENSOR_POSE_FRONT_VIEW = RigidTransform(
RollPitchYaw(SENSOR_RPY_FRONT).ToQuaternion(), SENSOR_POSITION_FRONT)
JACK_LOCKED_CAMERA_OFFSET = np.array([0.6, 0, 0]).reshape(3, 1)
JACK_LOCKED_CAMERA_QUAT = SENSOR_POSE_FRONT_VIEW.rotation().ToQuaternion(
).wxyz().reshape(4, 1)
# Top video view (for the T).
SENSOR_RPY_TOP = np.array([np.pi, 0, np.pi / 2])
SENSOR_POSITION_TOP = np.array([0., 0., 2.])
SENSOR_POSE_TOP_VIEW = RigidTransform(
RollPitchYaw(SENSOR_RPY_TOP).ToQuaternion(), SENSOR_POSITION_TOP)
T_LOCKED_CAMERA_OFFSET = np.array([0, 0, 0.8]).reshape(3, 1)
T_LOCKED_CAMERA_QUAT = SENSOR_POSE_TOP_VIEW.rotation().ToQuaternion(
).wxyz().reshape(4, 1)
ACTUAL_JACK_URDF_PATH = file_utils.jack_with_triad_urdf_path()
GOAL_JACK_URDF_PATH = file_utils.goal_triad_urdf_path()
ACTUAL_T_URDF_PATH = file_utils.push_t_urdf_path()
GOAL_T_URDF_PATH = file_utils.goal_push_t_urdf_path()
CAMERA_URDF_PATH = file_utils.camera_urdf_path()
SECOND_CAMERA_URDF_PATH = file_utils.camera_urdf_path(first=False)
# ACTUAL_JACK_URDF_PATH = 'examples/jacktoy/urdf/jack_with_triad.urdf'
# GOAL_JACK_URDF_PATH = 'examples/jacktoy/urdf/goal_triad.urdf'
# ACTUAL_T_URDF_PATH = 'examples/push_T/urdf/T_vertical_obj.urdf'
# GOAL_T_URDF_PATH = 'examples/push_T/urdf/T_vertical_obj_green.urdf'
# CAMERA_URDF_PATH = 'examples/jacktoy/urdf/camera_model.urdf'
# SECOND_CAMERA_URDF_PATH = 'examples/jacktoy/urdf/camera_model_2.urdf'
BOTTOM_LEFT_PLACEMENT = '1400:690'
BOTTOM_RIGHT_PLACEMENT = '20:690'
BOTTOM_LEFT_BOX_PLACEMENT = 'x=10:y=680'
BOTTOM_RIGHT_BOX_PLACEMENT = 'x=1380:y=680'
UPPER_LEFT_TEXT_PLACEMENT = 'x=50:y=50'
UPPER_RIGHT_TEXT_PLACEMENT = 'x=1200:y=50'
# Franka limits, from:
# https://frankaemika.github.io/docs/control_parameters.html#limits-for-panda
FRANKA_JOINT_MINS = np.array(
[-2.8973, -1.7628, -2.8973, -3.0718, -2.8976, -0.0175, -2.8973])
FRANKA_JOINT_MAXS = np.array(
[2.8973, 1.7628, 2.8973, -0.0698, 2.8976, 3.7525, 2.8973])
FRANKA_JOINT_VEL_LIMITS = np.array(
[2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61])
FRANKA_JOINT_ACC_LIMITS = np.array([15, 7.5, 10, 12.5, 15, 20, 20])
FRANKA_JOINT_JERK_LIMITS = np.array(
[7500, 3750, 5000, 6250, 7500, 10000, 10000])
FRANKA_JOINT_TORQUE_LIMITS = np.array([87, 87, 87, 87, 12, 12, 12])
# An alternative source, from:
# https://frankaemika.github.io/docs/franka_ros.html#franka-control
# FRANKA_JOINT_TORQUE_LIMITS = np.array([20, 20, 18, 18, 16, 14, 12])
# Keyed by the log file, has a tuple of the long video filepath and a directory
# to which single-goal videos can be written.
LOG_FILEPATHS_TO_VIDEOS = {
# Jack hardware videos, random goals with tight tolerances:
'/mnt/data2/sharanya/logs/2025/01_29_25/000007/hwlog-000007':
(op.join('/mnt/data2/sharanya/Hardware_videos_Sharanya/Jan29/Dump1',
'20250129_124229_log7_cut_2.mp4'),
'/mnt/data2/bibit/log_videos/01_29_25_log_7/'),
'/mnt/data2/sharanya/logs/2025/01_29_25/000031/hwlog-000031':
(op.join('/mnt/data2/sharanya/Hardware_videos_Sharanya/Jan29/Dump2',
'20250129_162050_log31_cut_2.mp4'),
'/mnt/data2/bibit/log_videos/01_29_25_log_31/'),
'/mnt/data2/sharanya/logs/2025/01_29_25/000032/hwlog-000032':
(op.join('/mnt/data2/sharanya/Hardware_videos_Sharanya/Jan29/Dump2',
'20250129_170022_log32_cut.mp4'),
'/mnt/data2/bibit/log_videos/01_29_25_log_32/'),
'/mnt/data2/sharanya/logs/2025/01_29_25/000033/hwlog-000033':
(op.join('/mnt/data2/sharanya/Hardware_videos_Sharanya/Jan29/Dump2',
'20250129_173127_log33_cut_2.mp4'),
'/mnt/data2/bibit/log_videos/01_29_25_log_33/'),
# Jack hardware videos, orientation cycling with loose tolerances:
'/mnt/data2/sharanya/logs/2025/01_14_25/000029/hwlog-000029':
(op.join('/mnt/data2/sharanya/Hardware_videos_Sharanya/',
'20250114_log29_cut_2.MOV'),
'/mnt/data2/bibit/log_videos/01_14_25_log_29/'),
# # Box sim videos:
# '/mnt/data2/sharanya/logs/2025/01_24_25/000021/hwlog-000021':
# ('/mnt/data2/sharanya/sim_videos/Jan24_log21_box.webm',
# '/mnt/data2/bibit/log_videos/01_24_25_log_21/'),
# '/mnt/data2/sharanya/logs/2025/01_24_25/000032/hwlog-000032':
# ('/mnt/data2/sharanya/sim_videos/Jan24_log32_box.webm',
# '/mnt/data2/bibit/log_videos/01_24_25_log_32/'),
# One for a local test:
'/home/bibit/Videos/franka_experiments/2025/01_29_25/000007/hwlog-000007':
(op.join('/home/bibit/Videos/franka_experiments/2025/01_29_25',
'20250129_124229_log7_cut.mp4'),
'/home/bibit/Videos/franka_experiments/2025/01_29_25/'),
# Push T hardware videos, all tight tolerances:
'/mnt/data2/sharanya/logs/2025/03_19_25/000016/hwlog-000016':
(None, # TODO this recording must be on Sharanya's phone
'/mnt/data2/bibit/log_videos/03_19_25_log_16/'),
'/mnt/data2/sharanya/logs/2025/03_19_25/000018/hwlog-000018':
('/mnt/data2/bibit/hardware_videos/03_19_2025_log_18_trimmed.MOV',
'/mnt/data2/bibit/log_videos/03_19_25_log_18/'),
'/mnt/data2/sharanya/logs/2025/03_19_25/000024/hwlog-000024':
('/mnt/data2/bibit/hardware_videos/03_19_2025_log_24_trimmed.MOV',
'/mnt/data2/bibit/log_videos/03_19_25_log_24/'),
'/mnt/data2/sharanya/logs/2025/03_19_25/000029/hwlog-000029':
('/mnt/data2/bibit/hardware_videos/03_19_2025_log_29_trimmed.MOV',
'/mnt/data2/bibit/log_videos/03_19_25_log_29/'),
}
PUSH_T_LOG_PATHS = [
'/mnt/data2/sharanya/logs/2025/03_19_25/000016/hwlog-000016',
'/mnt/data2/sharanya/logs/2025/03_19_25/000018/hwlog-000018',
'/mnt/data2/sharanya/logs/2025/03_19_25/000024/hwlog-000024',
'/mnt/data2/sharanya/logs/2025/03_19_25/000029/hwlog-000029'
]
JACK_LOG_PATHS = list(LOG_FILEPATHS_TO_VIDEOS.keys())
for push_t_path in PUSH_T_LOG_PATHS:
if push_t_path in JACK_LOG_PATHS: JACK_LOG_PATHS.remove(push_t_path)
MJPC_CUT_OFF_GOALS_PER_EE_VEL = {
0.03: 0, 0.06: 0, 0.09: 0, 0.12: 2, 0.15: 0, 0.18: 1, 0.21: 1, 0.24: 7,
0.27: 5, 1000: 0
}
MJPC_COLORS_PER_EE_VEL = {
0.03: '#fedbda',
0.06: '#fdb7b5',
0.09: '#fc9490',
0.12: '#fb706a',
0.15: '#fb4d46',
0.18: '#c83d38',
0.21: '#962e2a',
0.24: '#641e1c',
0.27: '#320f0e',
1000: '#30ba8f', # For our controller.
}
COLOR_PER_GOAL_OUTCOME = {
'Success': '#70AD47',
'Violated hardware limits': '#ED7D31',
'Cut off after 400s': '#A5A5A5'
}
global_is_interactive = False
def get_date_and_log_num_from_log_filepath(log_filepath: str) -> Tuple[str,
int]:
"""Returns the date and log number as strings."""
log_folder, log_filename = op.split(log_filepath)
log_num = int(log_filename.split('-')[-1])
date_str = op.split(op.split(log_folder)[0])[-1]
return date_str, log_num
def get_video_duration(filepath: str) -> float:
result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
"format=duration", "-of",
"default=noprint_wrappers=1:nokey=1", filepath],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return float(result.stdout)
def save_current_figure(filename: str, store_folder: str = None):
if store_folder is not None:
filepath = op.join(store_folder, f'{filename}.png')
else:
filepath = op.join(file_utils.tmp_dir(), f'{filename}.png')
plt.savefig(filepath)
print(f'Wrote plot to {filepath}')
global global_is_interactive
if not global_is_interactive:
plt.close()
def get_shading_masks(bool_array):
bool_array = bool_array.squeeze()
assert bool_array.ndim == 1
bool_array = bool_array.astype(bool)
right_shifted_yes = np.append(bool_array[0], bool_array[:-1])
yes_shading_mask = np.ravel(np.column_stack(
(right_shifted_yes, bool_array)))
no_shading_mask = np.ravel(np.column_stack(
(~right_shifted_yes, ~bool_array)))
return yes_shading_mask, no_shading_mask
# TODO implement and remove
def visualize_sample_buffer(messages_by_channel: dict, log_folder: str = None):
# First start with just a simple matplotlib plot of the buffer contents.
sample_buffers = messages_by_channel['SAMPLE_BUFFER'][MESSAGE_KEY]
states = messages_by_channel['C3_ACTUAL'][MESSAGE_KEY]
debugs = messages_by_channel['SAMPLING_C3_DEBUG'][MESSAGE_KEY]
times = messages_by_channel['SAMPLE_BUFFER'][LCM_TIME_KEY]
n_in_buffers = []
quats, xyzs, ee_xyzs = [], [], []
# Store orientation error in full rotation units for easier viewing on same
# axis as meter distance error.
pos_errors, full_rotation_errors = [], []
for buffer, state, debug in zip(sample_buffers, states, debugs):
n_in_buffers.append(buffer.num_in_buffer)
quats.append(state.state[3:7])
xyzs.append(state.state[7:10])
ee_xyzs.append(state.state[:3])
pos_errors.append(debug.current_pos_error)
full_rotation_errors.append(debug.current_rot_error / (2*np.pi))
_fig, axs = plt.subplots(2, 1, figsize=(6, 9), sharex=True)
axs[0].plot(times, n_in_buffers)
axs[0].set_xlabel('Time (s)')
axs[0].set_ylabel('Number of samples')
axs[0].set_title('Number of active samples in buffer')
axs[1].plot(times, pos_errors, label='Position error')
axs[1].plot(times, full_rotation_errors, label='Rotation error')
axs[1].set_xlabel('Time (s)')
axs[1].set_ylabel('Error [m or full rotation]')
axs[1].set_title('Error between current and goal states')
plt.legend()
save_current_figure('sample_buffer', store_folder=log_folder)
def inspect_mode_switching_by_goal(times: np.ndarray,
is_c3_mode_flags: np.ndarray,
switch_reasons: list,
pos_errors: np.ndarray,
rad_errors: np.ndarray,
pos_tol: float, rad_tol: float,
goal_num: int,
log_folder: str = None):
print(f'Making plot for goal {goal_num}...')
times = times - times[0]
double_t = np.repeat(times, 2)
if is_c3_mode_flags is not None:
c3_mask, repos_mask = get_shading_masks(is_c3_mode_flags)
deg_errors = rad_errors * 180 / np.pi
# A more presentable plot: position and rotation errors with mode shading
# and mode switch lines.
fig, axs = plt.subplots(1, 1, figsize=(14.3, 4))
ax0 = axs
ax1 = ax0.twinx()
if is_c3_mode_flags is not None:
ax0.fill_between(double_t, 0, 1.05, where=repos_mask, color=CF_COLOR,
alpha=0.5, transform=ax0.get_xaxis_transform())
ax0.fill_between(double_t, 0, 1.05, where=c3_mask, color=CR_COLOR,
alpha=0.5, transform=ax0.get_xaxis_transform())
# Add mode switch lines.
if switch_reasons is not None:
for i, mode_switch_reason in enumerate(MODE_SWITCH_LABELS):
if i == 0:
continue
switch_ts = np.array(times)[np.array(switch_reasons) == i]
prefix = ''
for switch_t in switch_ts:
ax0.axvline(x=switch_t, color=MODE_SWITCH_COLORS[i],
linewidth=4, label=prefix + mode_switch_reason)
prefix = '_'
ax0.plot(times, pos_errors, color=POS_ERROR_COLOR, label='Position error')
ax1.plot(times, deg_errors, color=RAD_ERROR_COLOR,
label='Orientation error')
ax0.axhline(y=pos_tol, linestyle='--', color=POS_ERROR_COLOR,
label='Position success threshold')
ax1.axhline(y=rad_tol * 180/np.pi, linestyle='--', color=RAD_ERROR_COLOR,
label='Orientation success threshold')
ax0.set_xlabel('Time (s)', fontsize=16)
ax0.set_ylabel('Position Error [m]', fontsize=16)
ax0.set_ylim([0, np.max(pos_errors) + 0.01])
ax0.set_xlim([np.min(times), np.max(times)])
ax1.set_ylabel('Orientation Error [deg]', color=RAD_ERROR_COLOR, fontsize=16)
ax1.set_ylim([0, np.max(deg_errors) + 10])
ax1.tick_params(axis='y', labelcolor=RAD_ERROR_COLOR)
fig.suptitle(f'Errors over Time with Mode Switching for Goal {goal_num}', fontsize=18)
# Legend: need to add patches manually.
cf_patch = Patch(facecolor=CF_COLOR, alpha=0.5, edgecolor='black',
linewidth=1, label='Contact-free mode')
cr_patch = Patch(facecolor=CR_COLOR, alpha=0.5, edgecolor='black',
linewidth=1, label='Contact-rich mode')
ax0.legend(
handles=ax0.get_legend_handles_labels()[0] + \
ax1.get_legend_handles_labels()[0] + [cf_patch, cr_patch],
bbox_to_anchor=(1.2, 1), loc='upper left', fontsize=14,
title_fontsize=16)
plt.tight_layout()
save_current_figure(
f'shading_goal_{goal_num}' if log_folder is not None else \
'shading_goal', store_folder=log_folder)
# TODO implement and remove
def inspect_lcm_traffic(messages_by_channel: dict):
buffer_ts = messages_by_channel['SAMPLE_BUFFER'][LCM_TIME_KEY]
franka_ts = messages_by_channel['FRANKA_STATE'][LCM_TIME_KEY]
radio_ts = messages_by_channel['SAMPLING_C3_RADIO'][LCM_TIME_KEY]
buffer_ts = np.array(buffer_ts)
franka_ts = np.array(franka_ts)
radio_ts = np.array(radio_ts)
print(f'Max buffer time: {np.max(buffer_ts)}')
print(f'Max Franka time: {np.max(franka_ts)}')
print(f'Max radio time: {np.max(radio_ts)}')
plt.figure()
plt.plot(buffer_ts, label='Buffer times')
plt.plot(franka_ts, label='Franka times')
plt.plot(radio_ts, label='Radio times')
plt.legend()
plt.show()
def log_is_push_t(log_path: str):
if log_path in JACK_LOG_PATHS:
return False
if log_path in PUSH_T_LOG_PATHS:
return True
raise ValueError(f'Unsure if {log_path} is push T or jack log.')
def relative_angle_from_quats(q, r):
q /= np.linalg.norm(q)
r /= np.linalg.norm(r)
qr = R.from_quat([q[1], q[2], q[3], q[0]])
rr = R.from_quat([r[1], r[2], r[3], r[0]])
angle = (qr * rr.inv()).magnitude()
return angle
def joint_mjpc_cdf(ras_by_ee_vel: dict, our_ra, long_legend: bool = True):
ee_vels = np.array(list(ras_by_ee_vel.keys()) + [1000])
ras = np.array(list(ras_by_ee_vel.values()) + [our_ra])
# Sort based on EE velocity cost.
sorted_idx = ee_vels.argsort()
sorted_ee_vels = ee_vels[sorted_idx]
sorted_ras = ras[sorted_idx]
# Plot formatting.
plt.rcParams.update({'font.family': 'serif'})
# Generate a plot of cumulative distribution functions.
figsize = (10,4) if long_legend else (8,4)
fig, axs = plt.subplots(1, 1, figsize=figsize)
for ee_vel, ra in zip(sorted_ee_vels, sorted_ras):
color = MJPC_COLORS_PER_EE_VEL[ee_vel]
# Get the tightest threshold data.
data = ra.times_to_thresholds[:, 0]
# Compute the fraction of invalid goals.
problem_goals = []
problem_goals += ra.goal_violations[JOINT_LIMIT_VIO_KEY]
problem_goals += ra.goal_violations[JOINT_VEL_VIO_KEY]
problem_goals += ra.goal_violations[JOINT_TORQUE_VIO_KEY]
valid_goal_mask = np.array([i not in problem_goals for i in range(
1, ra.n_goals_achieved[-1].item() + 2)])
invalid_fraction = (~valid_goal_mask).sum()/valid_goal_mask.shape[0]
trials = len(data)
cut_off = MJPC_CUT_OFF_GOALS_PER_EE_VEL[ee_vel]
hw_viols = f'{100*invalid_fraction:.1f}%'
# Include the few goals that were manually cut off after > 400s.
for _ in range(MJPC_CUT_OFF_GOALS_PER_EE_VEL[ee_vel]):
data = np.concatenate((data, np.array([400])))
count, bins_count = np.histogram(
data, bins=11, range=(0, TOO_LONG_TIME_CUTOFF))
pdf = count / sum(count)
cdf = np.cumsum(pdf)
bins_count[0] = 0
cdf = np.concatenate([[0], cdf])
if long_legend:
label = f'MJPC {ee_vel:.2f}' if ee_vel < 1000 else 'Ours '
label += f' / {trials} / {cut_off} / {hw_viols}'
else:
label = f'MJPC {ee_vel:.2f}' if ee_vel < 1000 else 'Ours'
axs.plot(bins_count, cdf, color=color, linewidth=5, label=label)
axs.set_xlabel('Time Limit [s]', fontsize=16)
axs.set_ylabel('Fraction of Trials', fontsize=16)
axs.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
axs.set_yticks(np.linspace(0, 1, 11))
axs.set_ylim([0, 1])
axs.set_xlim([0, CDF_TIME_CUTOFF])
axs.tick_params(axis='both', which='major', labelsize=12)
fig.suptitle('3D Jack Simulation, Goal Fraction Achieved Within Time Limit',
fontsize=18)
legend_title = 'Approach / AG\u2191 / COG\u2193 / HWV\u2193' \
if long_legend else None
axs.legend(bbox_to_anchor=(1.02, 1.04), loc='upper left',
title=legend_title, fontsize=14, title_fontsize=15)
plt.tight_layout()
plt.grid()
plt_name = 'mjpc_cdf' if long_legend else 'mjpc_cdf_concise'
save_current_figure(plt_name, store_folder=ra.save_folder)
def joint_mjpc_violations_bar(ras_by_ee_vel: dict, our_ra):
ee_vels = np.array(list(ras_by_ee_vel.keys()) + [1000])
ras = np.array(list(ras_by_ee_vel.values()) + [our_ra])
# Sort based on EE velocity cost (put higher cost at the bottom, to match
# CDF plot).
sorted_idx = np.flip(ee_vels.argsort())
sorted_ee_vels = ee_vels[sorted_idx]
sorted_ras = ras[sorted_idx]
# Plot formatting.
plt.rcParams.update({'font.family': 'serif'})
# Keep track of successful, violating, and cut off goal attempts.
labels = []
n_successful_no_violations, n_violations, n_cut_offs = [], [], []
for ee_vel, ra in zip(sorted_ee_vels, sorted_ras):
labels.append(f'MJPC {ee_vel:.2f}' if ee_vel < 1000 else 'Ours')
# Get the hardware violations.
problem_goals = []
problem_goals += ra.goal_violations[JOINT_LIMIT_VIO_KEY]
problem_goals += ra.goal_violations[JOINT_VEL_VIO_KEY]
problem_goals += ra.goal_violations[JOINT_TORQUE_VIO_KEY]
valid_goal_mask = np.array([i not in problem_goals for i in range(
1, ra.n_goals_achieved[-1].item() + 2)])
n_successful_no_violations.append(valid_goal_mask.sum())
n_violations.append((~valid_goal_mask).sum())
n_cut_offs.append(MJPC_CUT_OFF_GOALS_PER_EE_VEL[ee_vel])
goal_outcome_to_data = {}
goal_outcome_to_data['Success'] = np.array(n_successful_no_violations)
goal_outcome_to_data['Violated hardware limits'] = np.array(n_violations)
goal_outcome_to_data['Cut off after 400s'] = np.array(n_cut_offs)
# Generate a bar chart.
fig, ax = plt.subplots(figsize=(8,4))
bottom = np.zeros_like(goal_outcome_to_data['Success'])
height = 1.0
for outcome, counts in goal_outcome_to_data.items():
p = ax.barh(labels, counts, height, label=outcome, left=bottom,
color=COLOR_PER_GOAL_OUTCOME[outcome])
bottom += counts
count_labels = [str(num) if num > 0 else '' for num in counts.tolist()]
ax.bar_label(p, labels=count_labels, label_type='center')
ax.set_title('3D Jack Simulation, Goal Outcomes', fontsize=18)
ax.legend(fontsize=14) #, loc=(0.35, 0.335))
ax.set_ylim([-0.5, 9.5])
ax.set_xlim([0, 60])
ax.set_xlabel('Attempted Goals', fontsize=16)
ax.tick_params(axis='y', which='major', labelsize=14)
plt.tight_layout()
save_current_figure('mjpc_hwv', store_folder=ra.save_folder)
class ResultsAnalyzer:
"""Analyzes the results of a sampling-based C3 or MuJoCo MPC log by
extracting information out of one or multiple associated LCM logs, with the
ability to generate visuals."""
def __init__(self, log_filepaths: List[str], channels: List[str],
sync_channels: List[str] = None,
start_times: List[float] = None, end_times: List[float] = None,
save_folder: str = None, verbose: bool = True,
trim_bookends: bool = False):
assert len(channels) > 0, 'Need at least one channel to visualize.'
if start_times is not None:
assert len(start_times) == len(log_filepaths), f'Need either no' + \
f' or all start times.'
else:
start_times = [None] * len(log_filepaths)
if end_times is not None:
assert len(end_times) == len(log_filepaths), f'Need either no ' + \
f'or all end times.'
else:
end_times = [None] * len(log_filepaths)
self.log_filepaths = log_filepaths
self.start_times = start_times
self.end_times = end_times
self._channels = channels if type(channels) == list else list(channels)
self.save_folder = save_folder
self.trim_bookends = trim_bookends
self._use_debug_instead_of_target = 'SAMPLING_C3_DEBUG' in channels
# Load and stitch together each log file.
self.lcm_t_adj = 0
self.msg_t_adj = 0
self.messages_by_channel = {
key: {LCM_TIME_KEY: [], MESSAGE_TIME_KEY: [], MESSAGE_KEY: []}
for key in self._channels
}
# The start LCM times per log will be one longer than the number of logs
# since it includes the end time of the last log.
self.log_lcm_start_times = [self.lcm_t_adj]
self.goals_per_log = []
for log_file, start, end in zip(log_filepaths, start_times, end_times):
self._add_messages_from_log(
log_file, start_time=start, end_time=end, verbose=verbose)
self.log_lcm_start_times.append(self.lcm_t_adj)
# Synchronize according to channels.
self._synchronize_messages(
sync_channels=sync_channels, visualize=verbose)
def _get_trajectory_tolerances(self):
"""Get the position and orientation tolerances from the trajectory
parameters files, ensuring that all logs have the same tolerances.
Store them as self.pos_tol and self.rad_tol."""
if hasattr(self, 'pos_tol') and hasattr(self, 'rad_tol'):
return
pos_tol = None
rad_tol = None
# Get the trajectory parameters.
for log_filepath in self.log_filepaths:
log_folder, log_filename = op.split(log_filepath)
log_number = log_filename.split('-')[-1]
trajectory_params_filepath = op.join(
log_folder, f'trajectory_params_{log_number}.yaml')
with open(trajectory_params_filepath, 'r') as file:
traj_params = yaml.safe_load(file)
if pos_tol is None:
pos_tol = traj_params[TRAJ_PARAM_POS_TOL_KEY]
rad_tol = traj_params[TRAJ_PARAM_RAD_TOL_KEY]
else:
assert pos_tol == traj_params[TRAJ_PARAM_POS_TOL_KEY], \
'Position success thresholds do not match: ' + \
f'{pos_tol} vs. {traj_params[TRAJ_PARAM_POS_TOL_KEY]}'
assert rad_tol == traj_params[TRAJ_PARAM_RAD_TOL_KEY], \
'Orientation success thresholds do not match: ' + \
f'{rad_tol} vs. {traj_params[TRAJ_PARAM_RAD_TOL_KEY]}'
self.pos_tol = pos_tol
self.rad_tol = rad_tol
def _get_workspace_limits(self):
"""Get the x, y, z, and radius limits from the C3 parameter files,
ensuring that all logs have the same workspace limits. Store them as
self.wsl_x, wsl_y, wsl_z, and wsl_r."""
if hasattr(self, 'wsl_x'):
return
wsl_x = None
wsl_y = None
wsl_z = None
wsl_r = None
# Get the C3 options.
for log_filepath in self.log_filepaths:
log_folder, log_filename = op.split(log_filepath)
log_number = log_filename.split('-')[-1]
c3_params_filepath = op.join(
log_folder, f'c3_gains_{log_number}.yaml')
with open(c3_params_filepath, 'r') as file:
c3_params = yaml.safe_load(file)
if wsl_x is None:
wsl_x = c3_params[C3_PARAM_WSL_X_KEY]
wsl_y = c3_params[C3_PARAM_WSL_Y_KEY]
wsl_z = c3_params[C3_PARAM_WSL_Z_KEY]
wsl_r = c3_params[C3_PARAM_WSL_R_KEY]
else:
assert wsl_x == c3_params[C3_PARAM_WSL_X_KEY], \
'X workspace limits do not match: ' + \
f'{wsl_x} vs. {c3_params[C3_PARAM_WSL_X_KEY]}'
assert wsl_y == c3_params[C3_PARAM_WSL_Y_KEY], \
'X workspace limits do not match: ' + \
f'{wsl_y} vs. {c3_params[C3_PARAM_WSL_Y_KEY]}'
assert wsl_z == c3_params[C3_PARAM_WSL_Z_KEY], \
'X workspace limits do not match: ' + \
f'{wsl_z} vs. {c3_params[C3_PARAM_WSL_Z_KEY]}'
assert wsl_r == c3_params[C3_PARAM_WSL_R_KEY], \
'X workspace limits do not match: ' + \
f'{wsl_r} vs. {c3_params[C3_PARAM_WSL_R_KEY]}'
self.wsl_x = wsl_x
self.wsl_y = wsl_y
self.wsl_z = wsl_z
self.wsl_r = wsl_r
def _add_messages_from_log(self, log_filepath: str, start_time: float = 0.0,
end_time: float = 1e12, verbose: bool = True):
"""Add messages and times for every channel of interest into the
current self.messages_and_channels dictionary, appending the new data
to the end as if it were a continuous experiment."""
start_time = 0.0 if start_time is None else start_time
end_time = 1e12 if end_time is None else end_time
start_utime = int(start_time*1e6)
end_utime = int(end_time*1e6)
# Open the LCM log.
log_file = EventLog(log_filepath, 'r')
# Read through the log file.
event = log_file.read_next_event()
while event.channel not in self._channels:
event = log_file.read_next_event()
init_lcm_utime = event.timestamp
init_msg_utime = ALL_CHANNELS_AND_LCMT[
event.channel].decode(event.data).utime
event = log_file.seek_to_timestamp(init_lcm_utime + start_utime)
event = log_file.read_next_event()
t_lcm_init = (event.timestamp - init_lcm_utime)*1e-6
t_msg_init = (ALL_CHANNELS_AND_LCMT[
event.channel].decode(event.data).utime - init_msg_utime)*1e-6
lcm_t_of_last_goal_change = 0
msg_t_of_last_goal_change = 0
experiment_started = False
goals_achieved = 0
last_goal = None
channels_and_n_msgs = {}
while event is not None:
if event.timestamp - init_lcm_utime > end_utime:
break
if event.channel not in channels_and_n_msgs.keys():
channels_and_n_msgs[event.channel] = 1
else:
channels_and_n_msgs[event.channel] += 1
if event.channel in self._channels:
try:
msg_contents = ALL_CHANNELS_AND_LCMT[event.channel].decode(
event.data)
except ValueError:
print(f'Failed to decode message from {event.channel}.')
breakpoint()
lcm_secs = (event.timestamp - init_lcm_utime)*1e-6 - t_lcm_init
msg_utime = msg_contents.utime
msg_secs = (msg_utime - init_msg_utime)*1e-6 - t_msg_init
# Cut off initial teleop -- detect goals based on the debug
# message or the goal message.
if self._use_debug_instead_of_target and \
event.channel == 'SAMPLING_C3_DEBUG':
if (not experiment_started) and \
(not msg_contents.is_teleop or not self.trim_bookends):
experiment_started = True
lcm_start_t = lcm_secs
msg_start_t = msg_secs
goals_achieved = msg_contents.detected_goal_changes
if experiment_started and \
(msg_contents.detected_goal_changes > goals_achieved):
goals_achieved = msg_contents.detected_goal_changes
lcm_t_of_last_goal_change = lcm_secs - lcm_start_t + \
self.lcm_t_adj
msg_t_of_last_goal_change = msg_secs - msg_start_t + \
self.msg_t_adj
print(f'Goal {goals_achieved} achieved at ' + \
f'{lcm_t_of_last_goal_change:.2f} s (' + \
f'{msg_t_of_last_goal_change:.2f} s from msg).')
elif not self._use_debug_instead_of_target and \
event.channel == 'C3_FINAL_TARGET':
if not experiment_started:
experiment_started = True
lcm_start_t = lcm_secs
msg_start_t = msg_secs
last_goal = np.array(msg_contents.state[3:10])
new_goal = np.array(msg_contents.state[3:10])
if experiment_started and \
(np.linalg.norm(new_goal - last_goal) >= 1e-3):
goals_achieved += 1
last_goal = new_goal
if (msg_secs - msg_start_t + self.msg_t_adj) < \
msg_t_of_last_goal_change:
print(f'Found erroneously stitched experiments,' + \
f' breaking.')
break
lcm_t_of_last_goal_change = lcm_secs - lcm_start_t + \
self.lcm_t_adj
msg_t_of_last_goal_change = msg_secs - msg_start_t + \
self.msg_t_adj
print(f'Goal {goals_achieved} achieved at ' + \
f'{lcm_t_of_last_goal_change:.2f} s (' + \
f'{msg_t_of_last_goal_change:.2f} s from msg).')
if experiment_started:
self.messages_by_channel[event.channel][LCM_TIME_KEY
].append(lcm_secs - lcm_start_t + self.lcm_t_adj)
self.messages_by_channel[event.channel][MESSAGE_KEY].append(
msg_contents)
try:
self.messages_by_channel[event.channel][MESSAGE_TIME_KEY
].append(msg_secs - msg_start_t + self.msg_t_adj)
except:
pass
event = log_file.read_next_event()
self.goals_per_log.append(goals_achieved)
# Before trimming:
print(f'Channels and messages before trimming:')
for key, val in channels_and_n_msgs.items():
print(f'\t{key}: {val} messages')
# Cut off the last goal since it was not achieved.
if self.trim_bookends:
trim_channel = 'SAMPLING_C3_DEBUG' if \
self._use_debug_instead_of_target else 'C3_FINAL_TARGET'
i_cutoff = self.messages_by_channel[trim_channel][
LCM_TIME_KEY].index(lcm_t_of_last_goal_change)
self.messages_by_channel[trim_channel][LCM_TIME_KEY] = \
self.messages_by_channel[trim_channel][LCM_TIME_KEY][:i_cutoff]
self.messages_by_channel[trim_channel][MESSAGE_TIME_KEY] = \
self.messages_by_channel[trim_channel][MESSAGE_TIME_KEY][
:i_cutoff]
self.messages_by_channel[trim_channel][MESSAGE_KEY] = \
self.messages_by_channel[trim_channel][MESSAGE_KEY][:i_cutoff]
self.lcm_t_adj = lcm_t_of_last_goal_change
self.msg_t_adj = msg_t_of_last_goal_change
if verbose:
for channel, contents in self.messages_by_channel.items():
print(f'Channel: {channel}')
print(f'\tNum messages: {len(contents[LCM_TIME_KEY])}',
end = ', ')
print(f'Time range: {contents[LCM_TIME_KEY][0]:.2f} to ' + \
f'{contents[LCM_TIME_KEY][-1]:.2f}')
print(f'\nFinished processing log file at {log_filepath}.\n')
def _downsample_channels(self, sync_time_key: str):
"""No need to keep more than 60Hz of information, so ensure every
channel's messages are no more frequent than that."""
for channel_name in self._channels:
full_lcm_times = self.messages_by_channel[channel_name][
LCM_TIME_KEY].copy()
full_msg_times = self.messages_by_channel[channel_name][
MESSAGE_TIME_KEY].copy()
full_msgs = self.messages_by_channel[channel_name][
MESSAGE_KEY].copy()
print(f'Downsampling the "{channel_name}" channel to <=60Hz: ' + \
f'{len(full_lcm_times)} to ', end='')
new_lcm_times = []
new_msg_times = []
new_msgs = []
last_t = -1
for i in range(len(full_lcm_times)):
new_t = self.messages_by_channel[channel_name][sync_time_key][i]
if new_t - last_t > (1.0/60):
last_t = new_t
new_lcm_times.append(full_lcm_times[i])
new_msg_times.append(full_msg_times[i])
new_msgs.append(full_msgs[i])
self.messages_by_channel[channel_name][LCM_TIME_KEY] = new_lcm_times
self.messages_by_channel[channel_name][MESSAGE_TIME_KEY] = \
new_msg_times
self.messages_by_channel[channel_name][MESSAGE_KEY] = new_msgs
retention_percentage = 100*len(new_lcm_times)/len((full_lcm_times))
print(f'{len(new_lcm_times)} ({retention_percentage:.2f}%)')
def _synchronize_messages(self, sync_channels: List[str] = None,
synchronize_to_channel: str = 'SAMPLING_C3_DEBUG',
use_lcm_times: bool = True,
visualize: bool = True):
"""Synchronize the messages in the sync_channels list so their times
match to within TIME_SYNC_THRESH of every message in the
synchronize_to_channel. If any channel in the sync_channels list cannot
be synchronized at a given time, the time is discarded. The result is
all channels in sync_channels have the same number of messages, and each
index corresponds across channels."""
sync_channels = sync_channels if sync_channels is not None else \
self._channels
synchronize_to_channel = 'SAMPLING_C3_DEBUG' if 'SAMPLING_C3_DEBUG' in \
self._channels else 'C3_FINAL_TARGET'
time_key = LCM_TIME_KEY if use_lcm_times else MESSAGE_TIME_KEY
# First, downsample the synchronize to channel if it is very high rate.
self._downsample_channels(time_key)
# Detect which channel had the fewest messages.
min_num_channels = np.inf
max_num_channels = 0
min_channel = None
max_channel = None
for channel in sync_channels:
n_msgs = len(self.messages_by_channel[channel][time_key])
if n_msgs < min_num_channels:
min_num_channels = n_msgs
min_channel = channel
if n_msgs > max_num_channels:
max_num_channels = n_msgs
max_channel = channel
print(f'{min_channel} had fewest messages at {min_num_channels}')
print(f'{max_channel} had most messages at {max_num_channels}')
print(f'Synchronizing...', end=' ', flush=True)
if visualize:
_fig, axs = plt.subplots(2, 2, figsize=(12, 9), sharex=True,
gridspec_kw={'height_ratios': [2, 1]})
axs[0,0].sharey(axs[0,1])
for channel in sync_channels:
axs[0,0].plot(self.messages_by_channel[channel][time_key],
marker='o', label=channel)
axs[0,0].set_title('All messages')
axs[0,0].set_xlabel('Index')
axs[0,0].set_ylabel('Time (s)')
axs[0,0].legend()
axs[1,0].plot(
np.array(self.messages_by_channel[min_channel][time_key]) - \
np.array(self.messages_by_channel[max_channel][time_key][
:min_num_channels]))
axs[1,0].set_title(f'Time difference {min_channel} to ' + \
f'{max_channel}')
axs[1,0].set_xlabel('Index')
axs[1,0].set_ylabel('Time difference (s)')
# Detect timestamps that are shared between all channels.
ts = self.messages_by_channel[synchronize_to_channel][time_key].copy()
problem_ts = []
channel_problem_ts = []
for channel in sync_channels:
if channel == synchronize_to_channel:
continue
channel_ts = np.array(self.messages_by_channel[channel][time_key])
for t in ts:
delta = np.min(np.abs(channel_ts - t))
if delta > TIME_SYNCH_THRESH and t not in problem_ts:
problem_ts.append(t)
channel_problem_ts.append(channel)
for problem_t in problem_ts:
ts.remove(problem_t)
# Do some time synchronization to the minimum set of messages.
for channel in sync_channels:
new_lcm_times = []
new_msg_times = []
new_msgs = []