-
Notifications
You must be signed in to change notification settings - Fork 0
/
HRI_communication.py
1588 lines (1030 loc) · 49.1 KB
/
HRI_communication.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
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 30 15:43:19 2018
@author: matteomacchini
"""
########################################################
import os
import time
import numpy as np
import pandas as pd
import struct
import datetime
import shutil
import utilities.HRI as HRI
import HRI_mapping
import dataset_handling.user_data as user_data
import dataset_handling.CalibrationDataset as CalibrationDataset
#import remote_handler
import communication.UDP_handler as udp
import utilities.utils as utils
from settings.settings import get_settings
from settings.settings import get_feat_names
import logging
########################################################
settings = get_settings()
feat_names = get_feat_names()
logging.basicConfig(level=settings['logging_level'])
MANY_DATA = 10000000
N_FLOATS_UDP = 10
_DEBUG = {}
# calib_maneuver_dict = {0 : 'straight',
# 1 : 'just_left',
# 2 : 'just_right',
# 3 : 'just_up',
# 4 : 'just_down',
# 5 : 'up_right',
# 6 : 'up_left',
# 7 : 'down_right',
# 8 : 'down_left'}
calib_maneuver_dict = {0 : 'forward',
1 : 'backward',
2 : 'yaw_right',
3 : 'yaw_left',
4 : 'up',
5 : 'down',
6 : 'left_tilt',
7 : 'right_tilt',
8 : 'just_rest',
9 : 'right',
10 : 'left',
11 : 'roll_up',
12 : 'roll_down',
13 : 'pitch_up',
14 : 'pitch_down',
15 : 'yaw_up',
16 : 'yaw_down',
17 : 'no_input',
18 : 'just_right',
19 : 'just_left',
20 : 'just_up',
21 : 'just_down',
22 : 'up_right',
23 : 'up_left',
24 : 'down_right',
25 : 'down_left',
26 : 'fast',
27 : 'slow',
28 : 'straight'}
class HRI_communication():
""""""""""""""""""""""""
""" CLASS FUNCTIONS """
""""""""""""""""""""""""
####################################################
def __init__(self):
self.settings = settings
# define data structure and settings['headers']
self._DEBUG = _DEBUG
self.calib_maneuver_dict = calib_maneuver_dict
####################################################
""""""""""""""""""""""""""""""
""""" PRIVATE FUNCTIONS """""
""""""""""""""""""""""""""""""
####################################################
def _import_dummy(self):
self.mapp.import_data(which_user = 'test', clean = False)
self.dummy_data = HRI.merge_data_df(self.mapp.motion_data_umprocessed['test'])[self.mapp.settings.init_values_to_remove:]
####################################################
def _run_avatar(self):
count = 0
while count<settings['n_readings']:
count += 1
# update skeleton
(skel) = self._read_motive_skeleton()
flag = ''
# check if unity flag
unity_flag = self._acquire_unity_flag()
# if flag : send skeleton
if unity_flag=='r':
if settings['debug']:
logging.debug('sending skeleton to UNITY')
# send skeleton
write_sk_to_unity(Write_unity_sk, unity_sk_client, skel)
elif unity_flag=='q':
# close unity write socket
Read_unity_flag.socket.close()
break
####################################################
def _write_sk_to_unity(self, skel):
skel_msg = np.reshape(skel[: , :-3], 21 * 8)
arr = skel_msg.tolist()
arr = arr + [float(count)]
strs = ""
# one int and 7 floats, '21' times
for i in range(0, len(arr) // 4):
if i % 8 == 0:
strs += "i"
else:
strs += "f"
logging.debug(arr)
# logging.debug(len(arr))
message = struct.pack('%sf' % len(arr), *arr)
# logging.debug(message)
self._udp_write(message)
####################################################
""""""""""""""""""""""""
""" PUBLIC FUNCTIONS """
""""""""""""""""""""""""
####################################################
def run(self, mode = None):
""" runs acquisition/control depending on mode """
run(mode)
########################################################
########################################################
########################################################
""""""""""""""""""""""""""""""
""""" PRIVATE FUNCTIONS """""
""""""""""""""""""""""""""""""
def _acquire_input_data():
""" acquires data from the input device (MoCap, remote, IMU...) specified in settings """
logging.debug('collecting input data')
if settings['input_device'] == 'motive':
if settings['dummy_read']: # if you want a dummy msg
# generates dummy skeleton
input_data = []
for i in range(settings['n_rigid_bodies_in_skeleton']): # one dummy rigid body per each rigid body in skeleton
# generates dummy rigid body
one_rb = bytearray(struct.pack("ifffffff", i+1, 0, 0, 0, 0, 0, 0, 1)) # 1 int x ID, 3 float x pos, 4 float x quaternion, total length is 32
input_data = input_data + one_rb if len(input_data) else one_rb # concatenate
logging.debug('acquired dummy skeleton')
else:
input_data = _read_motive_skeleton()
elif settings['input_device'] == 'remote':
if settings['dummy_read']: # if you want a dummy msg
input_data = [0, 0, 0, 0] # generates dummy input (all zeros)
logging.debug('acquired dummy remote')
else:
input_data = remote_handler.data
elif settings['input_device'] == 'imu':
if settings['dummy_read']: # if you want a dummy msg
input_data = [0, 0, 0] # generates dummy input (all zeros)
logging.debug('acquired dummy remote')
else:
input_data = _read_imu()
if settings['input_device'] == 'imus':
if settings['dummy_read']: # if you want a dummy msg
# generates dummy imus
input_data = []
for i in range(len(settings['used_body_parts'])): # simulate two imus
# generates dummy rigid body (works up to i=10)
one_rb = bytearray(struct.pack("qqccccccccdddddddddd", 0, 0, '0'.encode(), '0'.encode(), '0'.encode(), '0'.encode(), '0'.encode(), '0'.encode(), '0'.encode(), str(i).encode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)) # 104 values
input_data = input_data + one_rb if len(input_data) else one_rb # concatenate
logging.debug('acquired dummy imu set')
else:
input_data = _read_imus()
if _timeout(input_data):
logging.debug(settings['input_device'] + ' acquisition timeout')
logging.debug('input data = ' + str(input_data))
return input_data
########################################################
def _control_routine(input_data_num, mapp, control_history_raw_num, control_history_num, count):
""" processes input and sends command data to unity/hardware """
if input_data_num is 't':
raise NameError('No data from input device!')
# import dummy data (if required)
if not settings['control_from_dummy_data']:
_DEBUG['input_data_num_unproc'] = input_data_num ### TODO : store in list using count
# skeleton data from binary to list
if settings['input_device'] == 'motive':
input_data_num = _process_motive_skeleton(input_data_num)
# input_data =
elif settings['input_device'] == 'imus':
input_data_num = _process_imus(input_data_num)
### TODO : and make this part a function of the InputData class (simply 'skeleton.process')
_DEBUG['input_data_num'] = input_data_num
if settings['input_device'] == 'motive':
if settings['control_from_dummy_data']: ### TOFIX
# input_data = user_data.skeleton(np.reshape(input_data_num[settings['headers']['motive']].values, (settings['n_rigid_bodies_in_skeleton'],-1)))
input_data = dict(zip(settings['headers']['motive'], input_data_num))
else:
# input is a motive skeleton
input_data = user_data.skeleton(input_data_num)
# store in history input data array
control_history_raw_num[count] = input_data.values
if settings['input_device'] == 'imus':
if settings['control_from_dummy_data']: ### TOFIX
pass
# input_data = user_data.skeleton(np.reshape(input_data_num[settings['headers']['motive']].values, (settings['n_rigid_bodies_in_skeleton'],-1)))
else:
# input is a imu set
input_data = user_data.imus(np.resize(input_data_num, [len(settings['used_body_parts']), settings['n_elements_per_imu']]))
# store in history input data array
control_history_raw_num[count] = input_data.values
elif settings['input_device'] == 'remote':
# input is a remote read
input_data = user_data.remote(input_data_num)
input_data = input_data.values if input_data.values is not None else np.array([128, 128, 128, 128]) # if input is None read a dummy
# store in history input data array
control_history_raw_num[count] = input_data
elif settings['input_device'] == 'imu':
# input is an imu read
input_data = user_data.imu(input_data_num)
input_data = input_data.values if input_data.values is not None else np.array([0, 0, 0]) # if input is None read a dummy
# store in history input data array
control_history_raw_num[count] = input_data
if settings['input_device'] == 'motive':
# first skeleton preprocessing
skel = _skeleton_preprocessing(input_data)
if settings['control_style'] == 'simple':
# get only torso pitch and roll
angles_scaled = - skel.values[0, 8:11]/np.pi * 2 # minus sign because angles are reversed
# scaling values (coming from Miehlbradt's paper)
y_score_scaled = np.array([angles_scaled[0] - 2*angles_scaled[2], angles_scaled[1]])
logging.debug('torso pitch and roll = ' + str(skel.values[0, 8:11]))
else:
# second skeleton processing
commands_tofit = _skeleton_preprocessing_II(skel, mapp)
if settings['input_device'] == 'imus':
# first skeleton preprocessing
skel = _skeleton_preprocessing(input_data)
if settings['control_style'] == 'simple':
# get only torso pitch and roll
angles_scaled = - skel.values[0, 8:11]/np.pi * 2 # minus sign because angles are reversed
# scaling values (coming from Miehlbradt's paper)
y_score_scaled = np.array([angles_scaled[0] - 2*angles_scaled[2], angles_scaled[1]])
logging.debug('torso pitch and roll = ' + str(skel.values[0, 8:11]))
else:
# second skeleton processing
commands_tofit = _skeleton_preprocessing_II(skel, mapp)
elif settings['input_device'] == 'remote':
_DEBUG['input_raw'] = input_data
if settings['control_style'] == 'simple':
# reading inputs 0 and 1
controls_raw = np.array(input_data[-1:-3:-1])
# scaling factors for [### TODO : check] remote
controls_av = np.array([120, 124])
controls_range = np.array([107, 114])
# scaling values based on [### TODO : check] remote
y_score_scaled = (controls_raw - controls_av)/(controls_range/settings['remote_gain'])
else:
# remote processing
commands_tofit = _remote_preprocessing_II(input_data, mapp)
elif settings['input_device'] == 'imu':
_DEBUG['input_raw'] = input_data
if settings['control_style'] == 'simple':
# reading inputs 0 and 1
controls_raw = np.array(input_data[-1:-3:-1])
# scaling factors for imu
controls_av = np.array([0, 0, 0])
controls_range = np.array([360, 360, 360])
# scaling values based imu factors
y_score_scaled = (controls_raw - controls_av)/(controls_range/settings['imu_gain'])
else:
# imu processing
commands_tofit = _imu_preprocessing_II(input_data, mapp)
if not settings['control_style'] == 'simple':
if settings['control_style'] == 'maxmin':
# process using linear regression
y_score_scaled = _maxmin(commands_tofit, mapp)
elif settings['control_style'] == 'new':
# process using nonlinear regression
y_score_scaled = _new(commands_tofit, mapp)
controls = np.zeros(N_FLOATS_UDP) # longer than longer input
for i, out in enumerate(settings['regression_outputs']):
# add zero values for unity (expecting 5 floats)
controls[i] = y_score_scaled[out]
controls = controls.tolist() # comment for HW ### TODO : make option
# store in history input data array ### TODO : do outside of function
control_history_num[count] = controls
# send commands to unity
_write_commands_to_unity(controls)
return control_history_raw_num, control_history_num
########################################################
def _create_hri_folders():
""" create all the needed folders to store data """
HRI.create_dir_safe(settings['data_folder'])
HRI.create_dir_safe(settings['subject_folder'])
HRI.create_dir_safe(settings['control_folder'])
########################################################
def _acquire_unity_flag():
""" read and process flag from unity """
# read and process flag
flag = udp.udp_read(udp.sockets['read_unity_flag'], keep_last = False)
flag = _process_unity_flag(flag)
logging.debug('UNITY flag = ' + flag)
return flag
########################################################
def _import_mapping(is_struct = False):
""" imports results from mapping procedure """
def extract_parameters(normalization_values, used_body_parts, outputs, outputs_no_pll):
""" processes parameters from the given mapping variable """
param = {}
if settings['input_device'] == 'motive' or settings['input_device'] == 'imus':
# gets the normalization values from [normalization_values] based on the given features
feats = HRI.select_motive_features(settings, feat_names)
param['normalization_values'] = normalization_values.iloc[:,:-2][feats]
# reshape on the correct form based on the acquisition hardware
parameters_val = param['normalization_values'].values
param['norm_av'] = parameters_val[0,:].reshape(len(settings['used_body_parts']),-1)
param['norm_std'] = parameters_val[1,:].reshape(len(settings['used_body_parts']),-1)
elif settings['input_device'] == 'remote':
# gets the normalization values from [normalization_values] based on the given features
param['normalization_values'] = normalization_values.drop(outputs + outputs_no_pll, axis=1)
# reshape on the correct form based on the acquisition hardware
parameters_val = param['normalization_values'].values
param['norm_av'] = parameters_val[0,:].reshape(4,-1)
param['norm_std'] = parameters_val[1,:].reshape(4,-1) # 4 inputs from remote
elif settings['input_device'] == 'imu':
# gets the normalization values from [normalization_values] based on the given features
param['normalization_values'] = normalization_values.drop(outputs + outputs_no_pll, axis=1)
# reshape on the correct form based on the acquisition hardware
parameters_val = param['normalization_values'].values
param['norm_av'] = parameters_val[0,:].reshape(3,-1)
param['norm_std'] = parameters_val[1,:].reshape(3,-1) # 3 inputs from imu
return param
if is_struct:
mapp = {}
# load mapping
mapp_temp = HRI_mapping.HRI_mapping() # in this case, mapp_temp is a class HRI_mapping.HRI_mapping()
mapp_temp = HRI.load_obj(os.path.join(settings['subject_folder'], settings['control_style']))
# puts data in dict
mapp['parameters'] = extract_parameters(mapp_temp.param.normalization_values, mapp_temp.settings.used_body_parts, mapp_temp.settings.outputs, mapp_temp.settings.outputs_no_pll) # processes parameters from class HRI_mapping.HRI_mapping()
mapp['features'] = mapp_temp.settings.feats_reduced
mapp['test_info'] = mapp_temp.test_info
mapp['test_results'] = mapp_temp.test_results
else:
# load mapping
mapp = HRI.load_obj(os.path.join(settings['subject_folder'], '{}_{}'.format(settings['input_device'], settings['control_style'])))
# puts data in dict
mapp['parameters'] = extract_parameters(mapp['parameters'], mapp['settings']['used_body_parts'], mapp['settings']['outputs'], mapp['settings']['outputs_no_pll'])
return mapp
########################################################
def _imu_preprocessing_II(input_data, mapp):
""" normalizes and applies dimensionality reduction to imu data """
# get input values in np array
controls_raw = np.array(input_data) # reading inputs 0 and 1
# normalize
[controls_norm, _] = utils.normalize(controls_raw, [mapp['parameters']['norm_av'], mapp['parameters']['norm_std']])
logging.debug(controls_norm)
# store in a dictonary
controls_dict = {'roll_imu' : controls_norm[0],
'pitch_imu' : controls_norm[1],
'yaw_imu' : controls_norm[2]}
# get dim_reduced data
remote_tofit = np.array([controls_dict[x] for x in mapp['features']])
remote_tofit = remote_tofit.reshape(1, -1)
return remote_tofit
########################################################
def _maxmin(skel_tofit, mapp):
""" performs linear regression on input data """
y_score_scaled = {}
skel_tofit_red = {}
for out in settings['regression_outputs']:
# dimensionality reduction
dim_red = mapp['dimred']
skel_tofit_red[out] = HRI_mapping.transform_cca(skel_tofit[out], dim_red[out])
# linear regression
# minmax_map = mapp['test_info']['maxmin_map']
# y_score = HRI_mapping._predict_maxmin(skel_tofit_red, minmax_map) # fit
best_mapping = mapp['test_info'][out]['results'][mapp['test_info'][out]['best']]['reg']
y_score = best_mapping.predict(skel_tofit_red[out])
# scale data
y_score_scaled[out] = y_score.flatten()
return y_score_scaled
########################################################
def _new(skel_tofit, mapp):
""" performs nonlinear regression on input data """
# dimensionality reduction
dim_red = mapp['test_info']['dim_red']
skel_tofit_red = HRI_mapping.transform_cca(skel_tofit, dim_red)
logging.debug('')
logging.debug('')
logging.debug('full = ', skel_tofit_red)
# clamp between min and max of calibration
max_inputs = mapp['test_info']['max_values']
min_inputs= mapp['test_info']['min_values']
for count, i in enumerate(skel_tofit_red[0]):
logging.debug(i)
if skel_tofit_red[0][count] > max_inputs[count]:
skel_tofit_red[0][count] = max_inputs[count]
elif skel_tofit_red[0][count] < min_inputs[count]:
skel_tofit_red[0][count] = min_inputs[count]
logging.debug('clipped = ', skel_tofit_red)
logging.debug('')
logging.debug('')
# nonlinear regression
best_mapping = mapp['test_results'][mapp['test_info']['best']]['reg']
y_score = best_mapping.predict(skel_tofit_red)
# scale data
y_score_scaled = y_score.flatten()/90.0
return y_score_scaled
########################################################
previous_imu_data = None
THRESHOLD = 180
MINI_THRESHOLD = 1
DEG_CORRECTION = 360
def _process_imu(data):
if _timeout(data):
return data
# print("Byte Length of Message :", len(data), "\n")
how_many = int(len(data)/64)
strs = "dddd"#*how_many
data_ump = struct.unpack(strs, data)[1:4]
### check if they changed "too much"
### MAKE SURE THAT THIS IS NOT DUE TO A RESET
global previous_imu_data
if previous_imu_data is not None:
for idx, i in enumerate(unity_control):
if abs(i-previous_imu_data[idx]) > THRESHOLD: #check treshold
tmp = list(unity_control)
if abs(i-0) > MINI_THRESHOLD: #enter this statement only if not reset
DEG_CORRECTION = abs(i-previous_imu_data[idx])
if i-previous_imu_data[idx] > 0:
tmp[idx] = -DEG_CORRECTION + unity_control[idx]
else:
tmp[idx] = DEG_CORRECTION + unity_control[idx]
unity_control = tmp
previous_imu_data = unity_control
prev = struct.unpack(strs,Read_struct.previous_state)[1:4]
unity_control = struct.unpack(strs, data)[1:4]
return unity_control
########################################################
def _process_motive_skeleton(data):
# print(data)
if _timeout(data):
return data
strs = ""
# one int and 7 floats, '21' times
for i in range(0, len(data) // 4):
if i % 8 == 0:
strs += "i"
else:
strs += "f"
data_ump = struct.unpack(strs, data)
# Q_ORDER = [3, 0, 1, 2]
Q_ORDER = [0, 1, 2, 3] # apparently natnet is now streaming [qx, qy, qy, qw]
for i in range(0, len(data_ump) // settings['n_data_per_rigid_body']):
bone = list(data_ump[i*settings['n_data_per_rigid_body'] : (1+i)*settings['n_data_per_rigid_body']])
# print bone
if i == 0:
ID = [(int(bin(bone[0])[-8:], 2))]
position = np.array(bone[1:4])
quaternion_t = np.array(bone[4:])
quaternion = np.array([quaternion_t[j] for j in Q_ORDER])
else:
ID = ID + [(int(bin(bone[0])[-8:], 2))]
position = np.vstack((position, bone[1:4]))
quaternion_t = bone[4:]
quaternion = np.vstack((quaternion, [quaternion_t[j] for j in Q_ORDER]))
ID = np.array(ID)
data = np.c_[ID, position, quaternion]
# sort by ID
data = data[data[:, 0].argsort()]
# print(data)
return data
########################################################
def _process_imus(data):
if _timeout(data):
return data
str_base = settings['types_in_imus']
str_l = len(str_base)
how_many = int(len(data)/settings['n_bytes_per_imu'])
strs = str_base*how_many
data_ump = struct.unpack(strs, data)
imus = []
for i in range(how_many):
imus.append({})
idx = str_l*i
imus[-1]['ts'] = data_ump[idx+0]
imus[-1]['ID'] = settings['imu_ID'][(data_ump[idx+2].decode("utf-8") + data_ump[idx+3].decode("utf-8") + data_ump[idx+4].decode("utf-8") + data_ump[idx+5].decode("utf-8") + data_ump[idx+6].decode("utf-8") + data_ump[idx+7].decode("utf-8") + data_ump[idx+8].decode("utf-8") + data_ump[idx+9].decode("utf-8")).lower()]
imus[-1]['Euler'] = data_ump[idx+13:idx+16]
imus[-1]['Quat'] = data_ump[idx+16:idx+20]
ids = [x['ID'] for x in imus]
data = []
for id in ids:
data = data + [imus[id-1]['ID']] + list(imus[id-1]['Euler']) + list(imus[id-1]['Quat'])
# sort by ID
data = np.array(data)
return data
########################################################
def _process_input_data(input_data, unity_num):
""" postprocessing of acquired data (received as binary) """
### HANDLING INPUT DATA ###
# timer for debugging
start = time.clock()
# delete empty rows
input_data = [x for x in input_data if x is not None]
# if acquired from motive
if settings['input_device'] == 'motive':
# create empty numpy array to store data
input_data_num = np.empty([len(input_data), settings['n_rigid_bodies_in_skeleton']*settings['n_elements_in_rigid_body']]) # 1 skel = [n_rigid_bodies_in_skeleton] * [n_elements_in_rigid_body] (see header for details)
for i in range(0, len(input_data)):
# process list of binaries into numpy array
skel_np_t = _process_motive_skeleton(input_data[i])
skel_np_t.resize(1, skel_np_t.size)
input_data_num[i] = skel_np_t
logging.debug('input processed ' + str(i) + ' of ' + str(len(input_data)))
# if acquired from remote
if settings['input_device'] == 'remote':
# create empty numpy array to store data
input_data_num = np.empty([len(input_data), 4]) # 1 remote = 4 values (see header for details)
# store list of values into numpy array
input_data_num = np.array(input_data)
# if acquired from imu
if settings['input_device'] == 'imu':
# create empty numpy array to store data
input_data_num = np.empty([len(input_data), 3]) # 1 imu = 3 values (see header for details)
# store list of values into numpy array
input_data_num = np.array(input_data)
logging.debug('input processed in ' + str(time.clock() - start))
# if acquired from imus
if settings['input_device'] == 'imus':
# create empty numpy array to store data
n_imus = int(len(input_data[0])/settings['n_bytes_per_imu'])
n_data = int(n_imus * settings['n_elements_per_imu'])
input_data_num = np.empty([len(input_data), n_data]) # 1 skel = [n_rigid_bodies_in_skeleton] * [n_elements_in_rigid_body] (see header for details)
global _DEBUG
_DEBUG['n_imus'] = n_imus
for i in range(0, len(input_data)):
# process list of binaries into numpy array
imus_np_t = _process_imus(input_data[i])
imus_np_t.resize(1, imus_np_t.size)
input_data_num[i] = imus_np_t
logging.debug('input processed ' + str(i) + ' of ' + str(len(input_data)))
### HANDLING UNITY DATA ###
# delete empty rows
unity_data = [x for x in unity_num if x is not None]
# create empty numpy array to store data
unity_num = np.empty([len(unity_data), len(unity_data[0])]) # normally 32 values (see header for details)
# timer for debugging
start = time.clock()
# store list of values into numpy array
unity_num = np.array(unity_data)
logging.debug('unity data processed in ' + str(time.clock() - start))
return input_data, input_data_num, unity_data, unity_num
########################################################
def _process_unity_calib(data):
if _timeout(data):
return data
# print("Byte Length of Message :", len(data), "\n")
strs = ""
for i in range(0, len(data)//4):
strs += "f"
# print(strs)
# print(len(data))
unity_control = struct.unpack(strs, data)
# print("Message Data :", unity_control, "\n")
return unity_control
########################################################
def _process_unity_flag(data):
if _timeout(data):
return data
# we receive a char
flag = data.decode("utf-8")
return flag
########################################################
def _read_imu():
""" acquires data from imu """
# acquire imu data
imu_data_temp = udp.udp_read(udp.sockets['read_imu'], keep_last = True)
# process online if not timeout
if not _timeout(imu_data_temp):
imu_data_temp = _process_imu(imu_data_temp)
return imu_data_temp
########################################################
def _read_imus():
""" acquires data from imu set """
# acquire imu data
imu_data_temp = udp.udp_read(udp.sockets['read_imus'], keep_last = True)
# # process online if not timeout
# if not _timeout(imu_data_temp):
# imu_data_temp = _process_imu(imu_data_temp)
return imu_data_temp
########################################################
def _read_motive_skeleton():
""" reads skeleton data from motive """
return udp.udp_read(udp.sockets['read_motive_sk'])
########################################################
def _acquire_unity_data(unity_num, count):
""" acquires data from the unity simulator """
logging.debug('collecting unity data')
# read and process unity calibration data
unity_calib_data = udp.udp_read(udp.sockets['read_unity_control'])
unity_calib = np.array(_process_unity_calib(unity_calib_data))
# if you want a dummy msg
if settings['dummy_unity']:
# generates dummy input (all zeros)
unity_calib = np.array([0] * settings['headers']['unity'].size)
logging.debug('acquired dummy unity data')
if _timeout(unity_calib):
logging.debug('unity calib timeout')
logging.debug('received unity calibration data')
# store value in array
if unity_calib.size == settings['headers']['unity'].size: # if data match header size
unity_num[count] = unity_calib # saves data
else:
unity_num[count] = unity_num[count - 1] # saves the previous one
logging.warning('header not matching data size') # warning
return unity_calib, unity_num
########################################################
def _remote_preprocessing_II(input_data, mapp):
""" normalizes and applies dimensionality reduction to remote data """
# get input values in np array
controls_raw = np.array(input_data) # reading inputs 0 and 1
# normalize
[controls_norm, _] = utils.normalize(controls_raw, [mapp['parameters']['norm_av'], mapp['parameters']['norm_std']])
logging.debug(controls_norm)
# store in a dictonary
controls_dict = {'remote1' : controls_norm[0],
'remote2' : controls_norm[1],
'remote3' : controls_norm[2],
'remote4' : controls_norm[3]}
# get dim_reduced data
remote_tofit = np.array([controls_dict[x] for x in mapp['features']])
remote_tofit = remote_tofit.reshape(1, -1)
return remote_tofit
########################################################
def _run_acquisition(count = 0):
""" run the acquisition routine until a 'q' (quit flag) is received from unity or count == settings['n_readings'] """
last = time.clock()
idle = 1 #stop reading if idle for 1 sec
# initialize unity and input data arrays
unity_num = [None] * MANY_DATA
input_data = [None] * MANY_DATA
logging.info('started acquisition')
# acquisition stop flag