-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadaptation_lqr.py
1652 lines (1427 loc) · 57.6 KB
/
adaptation_lqr.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
#!/usr/bin/env python3
# from influxdb_client.client.write_api import SYNCHRONOUS
import logging
import multiprocessing
import os
import time
from copy import deepcopy
from typing import Tuple
import numpy as np
import rclpy
from FLAIR_msg.msg import (
FLAIRTwist,
FunctionalityControllerControl,
HumanControl,
Perturbation,
SystemControl,
)
from geometry_msgs.msg import PoseWithCovarianceStamped, TwistWithCovarianceStamped
from influxdb_client import InfluxDBClient, Point, WriteOptions
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data
from scipy.spatial.transform import Rotation as R
from sensor_msgs.msg import Imu
# Defining a context to handle CUDA ressources anf Jax memory usage
# Choose forkserver as faster than spawn
context = multiprocessing.get_context("forkserver")
# Import the config
from src.flair.flair.adaptation_config_lqr import *
####################
# Common functions #
class MyStreamHandler(logging.StreamHandler):
def flush(self) -> None:
self.stream.flush()
def define_logger(logname: str, loglevel: str, header: str) -> logging.Logger:
"""Define a logger."""
llevel = getattr(logging, loglevel.upper())
if not isinstance(llevel, int):
raise ValueError(f"Invalid log level: {loglevel}")
formatter = logging.Formatter(
fmt=header + "%(asctime)s.%(msecs)03d %(name)s %(message)s" + " \x1b[0m ",
datefmt="%s",
)
sh = MyStreamHandler()
sh.setLevel(llevel)
sh.setFormatter(formatter)
logger = logging.getLogger(logname)
logger.setLevel(llevel)
logger.addHandler(sh)
return logger
def init_influx() -> InfluxDBClient:
"""Init the Influx client."""
influx_client = InfluxDBClient(
url="http://influxdb:8086",
bucket=os.environ["INFLUXDB_BUCKET"],
token=os.environ["INFLUXDB_KEY"],
org="FLAIR",
)
return influx_client.write_api(
write_options=WriteOptions(
batch_size=500,
flush_interval=1000,
jitter_interval=0,
retry_interval=5000,
max_retries=1,
max_retry_delay=30000,
max_close_wait=300000,
exponential_base=2,
)
)
def writeEntry(
influx_client: InfluxDBClient,
topic: str,
fields: list,
other_tag: str = None,
timestamp: int = None,
) -> None:
"""Write on entry to Influx."""
pt = Point(topic)
if timestamp:
pt.time(timestamp)
else:
pt.time(time.time_ns())
if other_tag:
pt.tag("other_tag", other_tag)
for f in fields:
pt = pt.field(f[0], f[1])
try:
_ = influx_client.write(
record=pt, org="FLAIR", bucket=os.environ["INFLUXDB_BUCKET"]
)
except BaseException as e:
print(e, flush=True)
pass
#############################
# Sensor Collection process #
class SensorCollection(Node):
def __init__(
self,
sensor_collection_to_rl_collection_datapoint_queue: multiprocessing.Queue,
sensor_collection_to_adaptation_datapoint_queue: multiprocessing.Queue,
sensor_collection_to_rl_training_reset_queue: multiprocessing.Queue,
sensor_collection_to_rl_collection_reset_queue: multiprocessing.Queue,
rl_collection_to_sensor_collection_start_queue: multiprocessing.Queue,
loglevel: str = "INFO",
) -> None:
super().__init__("sensorcollection")
# Import inside process to reduce memory usage
import os
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.01"
# Set up logging
self._logger = define_logger(
"SensorCollection", loglevel, "\x1b[34;20m Sensor_COLLECTION"
)
self._logger.info("SensorCollection: Starting")
# Store Queues as attribute
self.sensor_collection_to_rl_collection_datapoint_queue = (
sensor_collection_to_rl_collection_datapoint_queue
)
self.sensor_collection_to_adaptation_datapoint_queue = (
sensor_collection_to_adaptation_datapoint_queue
)
self.sensor_collection_to_rl_training_reset_queue = (
sensor_collection_to_rl_training_reset_queue
)
self.sensor_collection_to_rl_collection_reset_queue = (
sensor_collection_to_rl_collection_reset_queue
)
self.rl_collection_to_sensor_collection_start_queue = (
rl_collection_to_sensor_collection_start_queue
)
# Necessary attributes
self.start_collection = False
# Listen to reset message
self._sub_system_control = self.create_subscription(
SystemControl,
"/system_control",
self._system_control_callback,
qos_profile_sensor_data,
)
self._sub_system_control_seen = False
# Collect sensor data from IMU
self._sub_imu = self.create_subscription(
Imu, "/vectornav/imu", self._imu_callback, qos_profile_sensor_data
)
self._sub_imu_seen = False
# Collect sensor data from Zed
self._sub_zed_f = self.create_subscription(
PoseWithCovarianceStamped,
"/zed/forward/pose_with_covariance",
self._zed_callback,
qos_profile_sensor_data,
)
self._sub_zed_f_seen = False
self.f_cam_dt = None
# Initialise attributes for sensory Data
self.euler_angles = np.zeros((3,)) # roll, pitch, yaw
self.w = np.inf * np.zeros((3,)) # x, y, z
self.v = np.inf * np.zeros((3,)) # x, y, z
self.last_timestamp_zed = None
self.last_timestamp_imu = None
self.global_position = np.zeros((3,))
# Attributes for Zed-to-Robot Transform
forward_angles = [1.280, 28.417, 0]
forward_position = [0.247, 0.0595, 0.273]
self.forward_transform = np.eye(4)
self.forward_init = np.eye(4)
self.forward_transform[0:3] = np.hstack(
(
R.from_euler("xyz", forward_angles, degrees=True).as_matrix(),
np.array(forward_position).reshape(3, 1),
)
)
self.forward_init[0:3] = np.hstack(
(
R.from_euler(
"xyz", [0, 0, forward_angles[2]], degrees=True
).as_matrix(),
np.array(forward_position).reshape(3, 1),
)
)
self.forward_transform_inv = np.linalg.inv(self.forward_transform)
self._logger.info(
"SensorCollection: Completed __init__, waiting for RLCollection to start."
)
def _imu_callback(self, msg: Imu) -> None:
"""Get IMU data and send everything to other processes."""
# Get latest sensor
self.euler_angles = R.from_quat(
[msg.orientation.x, msg.orientation.y, msg.orientation.z, msg.orientation.w]
).as_euler("xyz")
self.w[0] = msg.angular_velocity.x
self.w[1] = msg.angular_velocity.y
self.w[2] = msg.angular_velocity.z # self.lp_ang_filter(msg.angular_velocity.z)
self.sensor_time = msg.header.stamp
# Store latest IMU timestamp
time_msg = self.get_clock().now()
self.last_timestamp_imu = time_msg.nanoseconds / 10**9
# Send via Queue to all other processes
self._send_sensor()
def _zed_callback(self, msg: PoseWithCovarianceStamped) -> None:
"""Get Zed data and store the outcome."""
# Get latest reading
current_pose = np.eye(4)
mat = R.from_quat(
[
msg.pose.pose.orientation.x,
msg.pose.pose.orientation.y,
msg.pose.pose.orientation.z,
msg.pose.pose.orientation.w,
]
).as_matrix()
current_pose[0:3] = np.hstack(
(
mat,
np.array(
[
msg.pose.pose.position.x,
msg.pose.pose.position.y,
msg.pose.pose.position.z,
]
).reshape(3, 1),
)
)
# Transform
old_position = self.global_position
self.global_position = (
self.forward_init @ current_pose @ self.forward_transform_inv
)
new_quat = R.from_matrix(self.global_position[:3, :3]).as_quat()
self.global_position = self.global_position[:3, 3]
camera_frame_transform = R.from_quat(new_quat).inv().as_matrix()
# camera_frame_transform = (
# R.from_quat(
# [
# msg.pose.pose.orientation.x,
# msg.pose.pose.orientation.y,
# msg.pose.pose.orientation.z,
# msg.pose.pose.orientation.w,
# ]
# )
# .inv()
# .as_matrix()
# )
# old_position = self.global_position
# self.global_position = np.array(
# [
# msg.pose.pose.position.x,
# msg.pose.pose.position.y,
# msg.pose.pose.position.z,
# ]
# )
current_timestamp = msg.header.stamp.sec + (msg.header.stamp.nanosec / 10**9)
if self.last_timestamp_zed is None:
self.v = np.zeros((3,))
else:
dt = current_timestamp - self.last_timestamp_zed
if dt > 0 and dt < 0.5:
word_frame_vel = (self.global_position - old_position) / dt
self.v = camera_frame_transform @ word_frame_vel
else:
self.v = np.inf
self.last_timestamp_zed = current_timestamp
def _system_control_callback(self, msg: SystemControl) -> None:
"""Reset the RL if asked by system topic."""
if not self._sub_system_control_seen:
self._logger.info("Present: SystemControl")
self._sub_system_control_seen = True
# This class is only interested in the reset info
if msg.adaptation_reset:
self._logger.debug("RESETING SENSOR DATASET " * 20)
# Empty datapoint queue
n_datapoint = 0
try:
for datapoint in iter(
self.sensor_collection_to_rl_collection_datapoint_queue.get_nowait,
"STOP",
):
n_datapoint += 1
except BaseException:
pass
self._logger.debug(
f"EMPTY {n_datapoint} from sensor_collection_to_rl_collection_datapoint_queue"
)
# Reseting RL Collection
self.sensor_collection_to_rl_collection_reset_queue.put((True))
# Empty reset queue
try:
self.sensor_collection_to_rl_training_reset_queue.get_nowait()
except BaseException:
pass
self._logger.debug(
"EMPTY sensor_collection_to_rl_training_reset_queue and reset RLTraining"
)
# Reseting RL
self.sensor_collection_to_rl_training_reset_queue.put((True))
def _send_sensor(self) -> None:
"""Send sensor data to other processes."""
# Get current reading
sensor_tx = self.global_position[0]
sensor_ty = self.global_position[1]
sensor_tz = self.global_position[2]
sensor_vx = self.v[0]
sensor_vy = self.v[1]
sensor_vz = self.v[2]
sensor_wx = self.w[0]
sensor_wy = self.w[1]
sensor_wz = self.w[2] * -1 # Warning: inverting z-axis here
sensor_roll = self.euler_angles[0]
sensor_pitch = self.euler_angles[1]
sensor_yaw = self.euler_angles[2]
# Compute state
state = (
sensor_vx,
sensor_vy,
sensor_wz,
sensor_tx,
sensor_ty,
sensor_yaw,
sensor_roll,
sensor_pitch,
)
# Send datapoint to RLCollection
self.sensor_collection_to_rl_collection_datapoint_queue.put(
(
self.sensor_time,
state,
sensor_tx,
sensor_ty,
sensor_tz,
sensor_vx,
sensor_vy,
sensor_vz,
sensor_yaw,
sensor_roll,
sensor_pitch,
sensor_wx,
sensor_wy,
sensor_wz,
)
)
# Empty datapoint to Adaptation queue
try:
self.sensor_collection_to_adaptation_datapoint_queue.get_nowait()
except BaseException:
pass
# Send datapoint to Adaptation
self.sensor_collection_to_adaptation_datapoint_queue.put((state, sensor_vx, sensor_wz))
# SensorCollection process
def start_sensor_collection_process(
args,
loglevel: str,
sensor_collection_to_rl_collection_datapoint_queue: multiprocessing.Queue,
sensor_collection_to_adaptation_datapoint_queue: multiprocessing.Queue,
sensor_collection_to_rl_training_reset_queue: multiprocessing.Queue,
sensor_collection_to_rl_collection_reset_queue: multiprocessing.Queue,
rl_collection_to_sensor_collection_start_queue: multiprocessing.Queue,
) -> None:
"""Process to acquire sensor information to send them for point selection."""
rclpy.init(args=args)
sensor_collection = SensorCollection(
sensor_collection_to_rl_collection_datapoint_queue,
sensor_collection_to_adaptation_datapoint_queue,
sensor_collection_to_rl_training_reset_queue,
sensor_collection_to_rl_collection_reset_queue,
rl_collection_to_sensor_collection_start_queue,
loglevel,
)
rclpy.spin(sensor_collection)
sensor_collection.destroy_node()
#########################
# RL Collection process #
def start_rl_collection_process(
args,
loglevel: str,
adaptation_to_rl_collection_command_queue: multiprocessing.Queue,
sensor_collection_to_rl_collection_datapoint_queue: multiprocessing.Queue,
rl_collection_to_rl_training_datapoint_queue: multiprocessing.Queue,
rl_training_to_rl_collection_start_queue: multiprocessing.Queue,
rl_collection_to_sensor_collection_start_queue: multiprocessing.Queue,
sensor_collection_to_rl_collection_reset_queue: multiprocessing.Queue,
) -> None:
"""Process for the RL Data Collection."""
# Import inside process to reduce memory usage
import os
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.01"
# os.environ['JAX_PLATFORMS']='cpu'
from functionality_controller.data_collection import DataCollection, DataQuality
# Init Influx Client
influx_client = init_influx()
# Set up logging
logger = define_logger("RLCollection", loglevel, "\x1b[31;20m RL_COLLECTION")
logger.info("RLCollection: Starting")
# Create the DataCollection object
data_collection = DataCollection(
logger=logger,
filter_transition=FILTER_TRANSITION,
filter_varying_angle=FILTER_VARYING_ANGLE,
filter_turning_only=FILTER_TURNING_ONLY,
buffer_size=BUFFER_SIZE,
min_delay=MIN_DELAY,
max_delay=MAX_DELAY,
selection_size=SELECTION_SIZE,
IQC_Q1=IQC_Q1,
IQC_Qn=IQC_Qn,
filter_transition_size=FILTER_TRANSITION_SIZE,
filter_transition_tolerance=FILTER_TRANSITION_TOLERANCE,
filter_varying_angle_size=FILTER_VARYING_ANGLE_SIZE,
filter_varying_angle_tolerance=FILTER_VARYING_ANGLE_TOLERANCE,
filter_turning_only_tolerance=FILTER_TURNING_ONLY_TOLERANCE,
)
# Attributes to compute datapoint quality metric
datapoints_number = 0
sensor_datapoints_number = 0
data_collection_calls = 0
data_collection_time = 0
# Send DataCollection configuration to Influx
try:
writeEntry(
influx_client,
"/lqr_collection_configuration",
[
("Filter_transition", FILTER_TRANSITION),
("Filter_varying_angle", FILTER_VARYING_ANGLE),
("Filter_turning_only", FILTER_TURNING_ONLY),
("Buffer_size", BUFFER_SIZE),
("Min_delay", MIN_DELAY),
("Max_delay", MAX_DELAY),
("Selection_size", SELECTION_SIZE),
("IQC_Q1", IQC_Q1),
("IQC_Qn", IQC_Qn),
("Filter_transition_size", FILTER_TRANSITION_SIZE),
("Filter_transition_tolerance", FILTER_TRANSITION_TOLERANCE),
("Filter_varying_angle_size", FILTER_VARYING_ANGLE_SIZE),
("Filter_varying_angle_tolerance", FILTER_VARYING_ANGLE_TOLERANCE),
("Filter_turning_only_tolerance", FILTER_TURNING_ONLY_TOLERANCE),
],
)
except BaseException as e:
logger.warning("Warning: Influx sending failed.")
logger.warning(e)
# Waiting for RLTraining to start to avoid continuous offset between collection and training
logger.info("RLCollection: Completed __init__, waiting for RLTraining to start.")
rl_training_to_rl_collection_start_queue.get()
logger.debug("RLTraining has started, waiting for commands to start collection.")
# Waiting for the first command to avoid stacking sensor datapoints that do not match any command
(
command_x,
command_y,
rl_prediction_x,
rl_prediction_y,
intent_x,
intent_y,
) = adaptation_to_rl_collection_command_queue.get()
sensor_vx = None
sensor_wz = None
next_command_x = None
# When got the first command, trigger sensor collection
logger.debug("Got the first command, triggering Sensor Collection.")
rl_collection_to_sensor_collection_start_queue.put((True))
logger.debug("Starting RLCollection.")
# Main loop
while True:
# Get a datapoint from Sensor Collection
sensor_datapoint = sensor_collection_to_rl_collection_datapoint_queue.get()
if sensor_vx is None:
sensor_time = np.array([[sensor_datapoint[0]]])
state = np.array([sensor_datapoint[1]])
sensor_tx = np.array([[sensor_datapoint[2]]])
sensor_ty = np.array([[sensor_datapoint[3]]])
sensor_tz = np.array([[sensor_datapoint[4]]])
sensor_vx = np.array([[sensor_datapoint[5]]])
sensor_vy = np.array([[sensor_datapoint[6]]])
sensor_vz = np.array([[sensor_datapoint[7]]])
sensor_yaw = np.array([[sensor_datapoint[8]]])
sensor_roll = np.array([[sensor_datapoint[9]]])
sensor_pitch = np.array([[sensor_datapoint[10]]])
sensor_wx = np.array([[sensor_datapoint[11]]])
sensor_wy = np.array([[sensor_datapoint[12]]])
sensor_wz = np.array([[sensor_datapoint[13]]])
# Initialise a timer to ensure not acquiring datapoints forever
overflow_timer = time.time()
else:
sensor_time = np.append(sensor_time, [[sensor_datapoint[0]]], axis=0)
state = np.append(state, [sensor_datapoint[1]], axis=0)
sensor_tx = np.append(sensor_tx, [[sensor_datapoint[2]]], axis=0)
sensor_ty = np.append(sensor_ty, [[sensor_datapoint[3]]], axis=0)
sensor_tz = np.append(sensor_tz, [[sensor_datapoint[4]]], axis=0)
sensor_vx = np.append(sensor_vx, [[sensor_datapoint[5]]], axis=0)
sensor_vy = np.append(sensor_vy, [[sensor_datapoint[6]]], axis=0)
sensor_vz = np.append(sensor_vz, [[sensor_datapoint[7]]], axis=0)
sensor_yaw = np.append(sensor_yaw, [[sensor_datapoint[8]]], axis=0)
sensor_roll = np.append(sensor_roll, [[sensor_datapoint[9]]], axis=0)
sensor_pitch = np.append(sensor_pitch, [[sensor_datapoint[10]]], axis=0)
sensor_wx = np.append(sensor_wx, [[sensor_datapoint[11]]], axis=0)
sensor_wy = np.append(sensor_wy, [[sensor_datapoint[12]]], axis=0)
sensor_wz = np.append(sensor_wz, [[sensor_datapoint[13]]], axis=0)
# Try to get all sensor_datapoints piled in the queue
n_sensor_datapoints = 1
start_t = time.time()
try:
for sensor_datapoint in iter(
sensor_collection_to_rl_collection_datapoint_queue.get_nowait, "STOP"
):
# start_add = time.time()
sensor_time = np.append(sensor_time, [[sensor_datapoint[0]]], axis=0)
state = np.append(state, [sensor_datapoint[1]], axis=0)
sensor_tx = np.append(sensor_tx, [[sensor_datapoint[2]]], axis=0)
sensor_ty = np.append(sensor_ty, [[sensor_datapoint[3]]], axis=0)
sensor_tz = np.append(sensor_tz, [[sensor_datapoint[4]]], axis=0)
sensor_vx = np.append(sensor_vx, [[sensor_datapoint[5]]], axis=0)
sensor_vy = np.append(sensor_vy, [[sensor_datapoint[6]]], axis=0)
sensor_vz = np.append(sensor_vz, [[sensor_datapoint[7]]], axis=0)
sensor_yaw = np.append(sensor_yaw, [[sensor_datapoint[8]]], axis=0)
sensor_roll = np.append(sensor_roll, [[sensor_datapoint[9]]], axis=0)
sensor_pitch = np.append(sensor_pitch, [[sensor_datapoint[10]]], axis=0)
sensor_wx = np.append(sensor_wx, [[sensor_datapoint[11]]], axis=0)
sensor_wy = np.append(sensor_wy, [[sensor_datapoint[12]]], axis=0)
sensor_wz = np.append(sensor_wz, [[sensor_datapoint[13]]], axis=0)
n_sensor_datapoints += 1
# logger.debug(f"Time to add one sensor_datapoint: {time.time() - start_add}")
except BaseException:
# logger.debug(e)
# logger.debug(f"Got {n_sensor_datapoints} sensor_datapoints")
pass
# Increase metric counter
# logger.debug(f"Time to get {n_sensor_datapoints} sensor_datapoints: {time.time() - start_t}")
sensor_datapoints_number += n_sensor_datapoints
# Send sensor information to Influx
try:
for n_sensor_datapoints in range(0, state.shape[0]):
timestamp = sensor_time[n_sensor_datapoints, 0]
timestamp = int(timestamp.sec) * int(1e9) + int(timestamp.nanosec)
writeEntry(
influx_client,
"/lqr_sensor",
[
("time", timestamp),
("tx", sensor_tx[n_sensor_datapoints, 0]),
("ty", sensor_ty[n_sensor_datapoints, 0]),
("tz", sensor_tz[n_sensor_datapoints, 0]),
("vx", sensor_vx[n_sensor_datapoints, 0]),
("vy", sensor_vy[n_sensor_datapoints, 0]),
("vz", sensor_vz[n_sensor_datapoints, 0]),
("yaw", sensor_yaw[n_sensor_datapoints, 0]),
("roll", sensor_roll[n_sensor_datapoints, 0]),
("pitch", sensor_pitch[n_sensor_datapoints, 0]),
("wx", sensor_wx[n_sensor_datapoints, 0]),
("wy", sensor_wy[n_sensor_datapoints, 0]),
("wz", sensor_wz[n_sensor_datapoints, 0]),
],
timestamp=timestamp,
)
except BaseException as e:
logger.warning("Warning: Influx sending failed.")
logger.warning(e)
# Attempt to get command from Adaptation
try:
(
next_command_x,
next_command_y,
next_rl_prediction_x,
next_rl_prediction_y,
next_intent_x,
next_intent_y,
) = adaptation_to_rl_collection_command_queue.get_nowait()
except BaseException as e:
pass
# If have been acquiring only sensor datapoints for more than 3secs, wait for command to restart
if next_command_x is None and (time.time() - overflow_timer) > 3:
logger.info("Entering waiting mode: no more command going through.")
next_command_x = None
sensor_vx = None
n_sensor_datapoints = 0
# Waiting for command
(
command_x,
command_y,
rl_prediction_x,
rl_prediction_y,
intent_x,
intent_y,
) = adaptation_to_rl_collection_command_queue.get()
# Empty datapoint queue
logger.debug("Got a new command, emptying Sensor Collection queue.")
n_datapoint = 0
try:
for datapoint in iter(
self.sensor_collection_to_rl_collection_datapoint_queue.get_nowait,
"STOP",
):
n_datapoint += 1
except BaseException:
pass
logger.info("Exiting waiting mode.")
# Attempt to get reset signal from Sensor Collection process
try:
_ = sensor_collection_to_rl_collection_reset_queue.get_nowait()
logger.debug("RESETING RL Collection" * 20)
# Reset Data Collection
data_collection.reset()
datapoints_number = 0
sensor_datapoints_number = 0
data_collection_calls = 0
data_collection_time = 0
command_x = next_command_x
command_y = next_command_y
rl_prediction_x = next_rl_prediction_x
rl_prediction_y = next_rl_prediction_y
intent_x = next_intent_x
intent_y = next_intent_y
next_command_x = None
sensor_vx = None
# Empty datapoint queue
n_datapoint = 0
try:
for datapoint in iter(
rl_collection_to_rl_training_datapoint_queue.get_nowait, "STOP"
):
n_datapoint += 1
except BaseException:
pass
logger.debug(
f"EMPTY {n_datapoint} from rl_collection_to_rl_training_datapoint_queue"
)
except BaseException:
pass
# If got the next command, call the DataCollection
if next_command_x is not None:
# Call the DataCollection object
try:
start_t = time.time()
(
final_datapoint,
final_datapoints_msg,
metrics,
error_code,
) = data_collection.data_collection(
state=state,
command_x=command_x,
command_y=command_y,
gp_prediction_x=rl_prediction_x,
gp_prediction_y=rl_prediction_y,
intent_x=intent_x,
intent_y=intent_y,
sensor_time=sensor_time,
sensor_x=sensor_vx,
sensor_y=sensor_wz,
sensor_wx=sensor_wx,
sensor_wy=sensor_wy,
)
collection_time = time.time() - start_t
# logger.debug(f"Data collection took {collection_time}")
except BaseException as e:
final_datapoint = None
final_datapoints_msg = None
metrics = None
collection_time = 0
logger.warning(f"Data Collection call failed.")
logger.warning(e)
# Send to Influx
try:
writeEntry(
influx_client, "/lqr_datapoint_filter", [("filter_code", error_code)]
)
except BaseException as e:
logger.warning("Warning: Influx sending failed.")
logger.warning(e)
# Update metrics
data_collection_calls += 1
data_collection_time += collection_time
# Store next commands
command_x = next_command_x
command_y = next_command_y
rl_prediction_x = next_rl_prediction_x
rl_prediction_y = next_rl_prediction_y
intent_x = next_intent_x
intent_y = next_intent_y
# Update attributes used by conditions
next_command_x = None
sensor_vx = None
# If Data Collection returned a datapoint, send it to the RL
if final_datapoint is not None:
# Send to RLTraining
# logger.debug(f"Sending 1 datapoint to RL Training.")
rl_collection_to_rl_training_datapoint_queue.put(final_datapoint)
datapoints_number += 1
# Send to Influx
try:
influx_msgs = final_datapoints_msg
writeEntry(
influx_client,
"/lqr_datapoint",
influx_msgs,
timestamp=int(final_datapoint[1]) * int(1e9)
+ int(final_datapoint[2]),
)
except BaseException as e:
logger.warning("Warning: Influx sending failed.")
logger.warning(e)
# If Data Collection returned metrics for Influx, send them to Influx
if DEBUG_RL_COLLECTION:
if metrics is not None:
try:
writeEntry(
influx_client,
"/lqr_datapoint_analysis",
[("DataCollection", metrics)],
)
except BaseException as e:
logger.debug("Warning: Influx sending failed.")
logger.debug(e)
#######################
# RL training process #
# RLtraining process
def start_rl_training_process(
loglevel: str,
rl_training_to_adaptation_model_queue: multiprocessing.Queue,
rl_collection_to_rl_training_datapoint_queue: multiprocessing.Queue,
rl_training_to_rl_collection_start_queue: multiprocessing.Queue,
rl_training_to_adaptation_start_queue: multiprocessing.Queue,
sensor_collection_to_rl_training_reset_queue: multiprocessing.Queue,
) -> None:
"""Thread for the RL Training."""
# Create a logger
logger = define_logger("RLTraining", loglevel, "\x1b[32;20m TRAINER ")
# logging.basicConfig(level=logging.DEBUG)
# Import inside process to reduce memory usage
import os
# os.environ['JAX_PLATFORMS']='cuda'
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.50"
from functionality_controller.datapoint import DataPoints
from functionality_controller.functionality_controller_utils import (
compute_borders,
compute_clipping,
compute_metric_map,
)
# Init Influx Client
influx_client = init_influx()
# Create empty DataPoints for addition
empty_datapoints = DataPoints.init(max_capacity=DATAPOINT_BATCH_SIZE, state_dims=8)
jiting_datapoints = DataPoints.add(
datapoint=empty_datapoints,
point_id=0,
sensor_time_sec=0.0,
sensor_time_nanosec=0.0,
command_time_sec=0.0,
command_time_nanosec=0.0,
state=np.zeros(8),
gp_prediction_x=0.0,
gp_prediction_y=0.0,
command_x=0.0,
command_y=0.0,
intent_x=0.0,
intent_y=0.0,
sensor_x=0.0,
sensor_y=0.0,
)
# Create RL
logger.info("RLTraining: Starting")
from functionality_controller.residual_rl_td3 import ResidualTD3
residual_td3 = ResidualTD3(
logger=logger,
jiting_datapoints=jiting_datapoints,
min_command=MIN_COMMAND,
max_command=MAX_COMMAND,
learning_rate=LEARNING_RATE,
policy_noise=POLICY_NOISE,
noise_clip=NOISE_CLIP,
gamma=GAMMA,
tau=TAU,
batch_size=BATCH_SIZE,
policy_frequency=POLICY_FREQUENCY,
min_diff_datapoint=MIN_DIFF_DATAPOINT,
dataset_size=DATASET_SIZE,
datapoint_batch_size=DATAPOINT_BATCH_SIZE,
minibatch_size=MINIBATCH_SIZE,
auto_reset_error_buffer_size=ERROR_BUFFER_SIZE,
auto_reset_angular_rot_weight=WEIGHT_ANGULAR_ROT,
auto_reset_threshold=NEW_SCENARIO_THRESHOLD,
)
# Define a reset function used multiple time within the loop
def RLTraining_reset(residual_td3: ResidualTD3, auto_reset: bool) -> None:
"""Function called for any reset of the RL."""
# Empty model queue
try:
rl_training_to_adaptation_model_queue.get_nowait()
except BaseException:
pass
logger.debug("EMPTY model from rl_training_to_adaptation_model_queue")
# Send new reseted model to Adaptation
rl_training_to_adaptation_model_queue.put(
(
residual_td3.actor_state.params,
)
)
# Empty reset queue
try:
for reset in iter(
sensor_collection_to_rl_training_reset_queue.get_nowait, "STOP"
):
num_train_counter = 0
except BaseException:
pass
logger.debug("EMPTY reset from sensor_collection_to_rl_training_reset_queue")
# Empty datapoint queue
n_datapoint = 0
try:
for datapoint in iter(
rl_collection_to_rl_training_datapoint_queue.get_nowait, "STOP"
):
n_datapoint += 1
except BaseException:
pass
logger.debug(
f"EMPTY {n_datapoint} from rl_collection_to_rl_training_datapoint_queue"
)
# Send reset to influx
try:
writeEntry(
influx_client,
"/lqr_reset",
[("reset", not (auto_reset)), ("auto_reset", auto_reset)],
)
except BaseException as e:
logger.warning("Warning: Influx sending failed.")
logger.warning(e)
# Reset everything
RLTraining_reset(residual_td3, auto_reset=False)
rl_map_sending_counter = 0
# Send RLTraining configuration to Influx
try:
writeEntry(
influx_client,
"/lqr_training_configuration",
[
("Use_reset", USE_RESET),
("Learning_rate", LEARNING_RATE),
("Policy_noise", POLICY_NOISE),
("Noise_clip", NOISE_CLIP),
("Gamma", GAMMA),
("Tau", TAU),
("Batch_size", BATCH_SIZE),
("Poliy_frequency", POLICY_FREQUENCY),
("Observation_state", OBSERVATION_STATE),
("Dataset_min_diff", MIN_DIFF_DATAPOINT),
("Dataset_batch_size", DATAPOINT_BATCH_SIZE),
("Dataset_size", DATASET_SIZE),
("Reset_minibatch_size", MINIBATCH_SIZE),
("Reset_error_buffer_size", ERROR_BUFFER_SIZE),
("Reset_weight_angular_rot", WEIGHT_ANGULAR_ROT),
("Reset_new_scenario_threshold", NEW_SCENARIO_THRESHOLD),
],
)
except BaseException as e:
logger.warning("Warning: Influx sending failed.")
logger.warning(e)
# Trigger the Data Collectiona and Adaptation only when fully started
# to avoid accumulating datapoints and the robot moving because of damage before adaptation
logger.debug("Model booted, triggering Data Collection and Adaptation")
rl_training_to_rl_collection_start_queue.put((True))
rl_training_to_adaptation_start_queue.put((True))
logger.info("RLTraining: Completed __init__")
while True:
# Wait until we get a datapoint from RLCollection
start_t = time.time()
(
point_id,
sensor_time_sec,
sensor_time_nanosec,
command_time_sec,