-
Notifications
You must be signed in to change notification settings - Fork 1
/
pipeline.py
1334 lines (1158 loc) · 49.6 KB
/
pipeline.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
# Module for quick access to analysis pipelines.
# These are functions that iterate over multiple individuals or trials.
# 2017-03-31
import pickle
import numpy as np
import os
from .data_access import *
from .axis_neuron import *
from .utils import *
from .filter import *
from numpy import pi
def distance_dtw(spec_list,trial_type,trials,
precision=.1,
firstix=0,
disp=1):
"""
Calculate dtw statistics over all given trials for given window specs.
Parameters
----------
spec_list : list
List of twoples (invisible_fraction,window_duration).
trial_type : str
Trial type. 'hand' or 'avatar'
trials : list of VRTrial instances
precision : float,.1
firstix : int
disp : bool,True
Returns
-------
distmat : ndarray
dtmat : ndarray
Cols are [avg_dt,std_dt,min,max]
"""
# In last dim, first three cols correspond to xyz dimensions and last col is norm.
distmat = np.zeros((len(trials),len(spec_list),4))
dtmat = np.zeros((len(trials),len(spec_list),4))
for itrial,trial in enumerate(trials):
for specix,spec in enumerate(spec_list):
# Get subject and template velocities.
output = _compare_dtw(trial,[spec]*2,[trial_type]*2,[precision]*2,
firstix=firstix,disp=disp)
if not output is None:
distmat[itrial,specix,:] = np.sqrt( (output[0]**2).mean(0) )
dt = np.diff(output[1],1)/30
dtmat[itrial,specix,:] = dt.mean(),dt.std(),dt.min(),dt.max()
else:
distmat[itrial,specix,:] = np.nan
dtmat[itrial,specix,:] = np.nan
return distmat,dtmat
def _compare_dtw(trial,windows,trial_types,precisions,
firstix=0,disp=True,
template_only=False):
"""
Compare coherence for the given windows specified for the subject and for the template.
Parameters
----------
trial : VRTrial
windows : list of tuples
trial_types : list of strings
precisions : list of precision
firstix : int,0
disp : bool,True
template_only : bool,False
Returns
-------
dist : ndarray
(n_time,4) Cols are x, y, z then cosine of angle between velocity vectors.
path : ndarray
"""
from fastdtw import fastdtw
try:
if template_only:
sspec,t,subjectv = trial.template_by_window_spec([windows[0]],
trial_types[0],
precisions[0]
)[firstix]
else:
sspec,t,subjectv = trial.subject_by_window_spec([windows[0]],
trial_types[0],
precisions[0]
)[firstix]
tspec,t,templatev = trial.template_by_window_spec([windows[1]],
trial_types[1],
precisions[1]
)[firstix]
# Ensure that data sets are of the same size.
#t = t[-1200:]
#subjectv = subjectv[-1200:]
#templatev = templatev[-1200:]
#assert (len(subjectv)==1200) and (len(templatev)==1200)
if disp:
print("Subject: (%1.1f,%1.1f), Template: (%1.1f,%1.1f)"%(sspec[0],sspec[1],
tspec[0],tspec[1]))
if len(subjectv)==0:
return
# Run dtw.
dtwdist,path = fastdtw(subjectv,templatev)
path = np.vstack(path)
dist = np.zeros((len(path),4))
for dimIx in range(3):
dist[:,dimIx] = subjectv[path[:,0],dimIx]-templatev[path[:,1],dimIx]
dist[:,3] = ( (subjectv[path[:,0]]*templatev[path[:,1]]).sum(1) /
np.linalg.norm(subjectv[path[:,0]],axis=1)/np.linalg.norm(templatev[path[:,1]],axis=1) )
return dist,path
except Exception as err:
if disp:
print("No data for window spec (%1.1f,%1.1f)."%(windows[0][0],
windows[0][1]))
return
def pipeline_phase_lag(v1,v2,dt,
maxshift=60,
windowlength=100,
v_threshold=.03,
measure='dot',
save='temp.p'):
"""
Find phase lag for each dimension separately and for the vector including all dimensions together.
Params:
-------
v1,v2,dt
maxshift (int=60)
windowlength (int=100)
v_threshold (float=.03)
save (str='temp.p')
"""
import pickle as pickle
phasexyz,overlapcostxyz = [],[]
for i in range(3):
p,o = phase_lag(v1[:,i],v2[:,i],maxshift,windowlength,
measure=measure,dt=dt)
phasexyz.append(p)
overlapcostxyz.append(o)
phase,overlapcost = phase_lag(v1,v2,maxshift,windowlength,
measure=measure,dt=dt)
if save:
print("Pickling results as %s"%save)
pickle.dump({'phase':phase,'overlapcost':overlapcost,
'phasexyz':phasexyz,'overlapcostxyz':overlapcostxyz,
'maxshift':maxshift,'windowlength':windowlength,
'measure':measure,
'v1':v1,'v2':v2},
open(save,'wb'),-1)
return phasexyz,phase,overlapcostxyz,overlapcost
def max_coherence(windowSpec,trials):
"""
Time shifted max coherence across all trials.
"""
maxcoh = np.zeros((len(trials),4))
for trialno,trial in enumerate(trials):
subjectVel = trial.subject_by_window_spec([windowSpec],'hand',(.05,.11))
templateVel = trial.template_by_window_spec([windowSpec],'hand',(.05,.11))
visWindow = trial.visibility_by_window_spec([windowSpec],'hand',(.05,.11))
# Load data.
if len(subjectVel[0][2])>0:
subt = subjectVel[0][1]
subv = subjectVel[0][2]
subt = subt[:len(subv)]
temt = templateVel[0][1]
temv = templateVel[0][2]
mnlen = min([len(subt),len(temt)])
temt,temv = temt[:mnlen],temv[:mnlen]
vist = visWindow[0][1]
# coherence as graphs are time shifted.
cohdtShifts = np.zeros(3)
for i in range(3):
cohdtShifts[i] = max_coh_time_shift(subv[:,i],temv[:,i],
disp=False,dtgrid=np.linspace(-1,1,100))
firstix = 0
maxcoh[trialno],_ = coherence([subjectVel[0][0]],'hand',[trial],
firstix=firstix,
precision=(.05,.1),
offset=int(-cohdtShifts[1:].mean()*60))
else:
maxcoh[trialno] = np.nan
return maxcoh
def coherence(spec_list,trial_type,trials,
mx_freq=10,
precision=.1,
firstix=0,
offset=None,
cwt=False,
disp=1):
"""
Calculate average coherence over all given trials for given window specs.
Parameters
----------
spec_list : list
List of twoples (invisible_fraction,window_duration).
trial_type : str
Trial type. 'hand' or 'avatar'
trials : list of VRTrial instances
mx_freq : int,10
Maximum frequency over which to average coherence
precision : float,.1
firstix : int
offset : int,None
Number of indices to offset the subject and template time series. If offset>0, we skip the
first offset elements from subject. If offset<0, -offset elements are removed from the
subject.
disp : bool,True
Returns
-------
cohmat : ndarray
Coherence statistic for all trials and all given window specs for xyz and vel norm.
cohmaterr : ndarray
Standard error of the mean of coherence statistic across trials.
"""
# In last dim, first three cols correspond to xyz dimensions and last col is norm.
cohmat = np.zeros((len(trials),len(spec_list),4))
for itrial,trial in enumerate(trials):
for specix,spec in enumerate(spec_list):
# Get subject and template velocities.
cohOutput = _compare_coherence(trial,[spec]*2,[trial_type]*2,[precision]*2,mx_freq,
firstix=firstix,disp=disp,offset=offset,cwt=cwt)
if not cohOutput is None:
f,cohmat[itrial,specix,:] = cohOutput
else:
cohmat[itrial,specix,:] = np.nan
return cohmat,np.nanstd(cohmat,axis=0)/np.sqrt((np.isnan(cohmat[:,0,0])==0).sum())
def coherence_null_visible(spec_list,trial_type,trials,
mx_freq=10,
precision=.1,
firstix=0,
offset=None,
disp=1):
"""
Calculate coherence between trials and flashing visibility window.
Parameters
----------
spec_list : list
List of twoples (invisible_fraction,window_duration).
trial_type : str
Trial type. 'hand' or 'avatar'
trials : list of VRTrial instances
mx_freq : int,10
Maximum frequency over which to average coherence
precision : float,.1
firstix : int,0
offset : int,None
Number of indices to offset the subject and template time series. If offset>0, we skip the
first offset elements from subject. If offset<0, -offset elements are removed from the
subject.
disp : bool,1
Returns
-------
cohmat : ndarray
Average coherence statistic over all trials. First three cols correspond to xyz dimensions
and last col is norm.
cohmaterr : ndarray
Standard error of the mean of coherence statistic down the columns.
"""
# First three cols correspond to xyz dimensions and last col is norm.
cohmat = np.zeros((len(trials),len(spec_list),4))
for itrial,trial in enumerate(trials):
for specix,spec in enumerate(spec_list):
cohOutput = _compare_coherence_vis(trial,spec,trial_type,
precision,mx_freq,
firstix,disp,offset)
if not cohOutput is None:
f,cohmat[itrial,specix,:] = cohOutput
else:
cohmat[itrial,specix,:] = np.nan
return cohmat,np.nanstd(cohmat,axis=0)/np.sqrt((np.isnan(cohmat[:,0,0])==0).sum())
def coherence_null_time_shift(spec_list,trial_type,trials,
mx_freq=10,
precision=.1,
firstix=0,
offset=None,
disp=1):
"""
Calculate coherence between trials and time shifted version of signal.
Parameters
----------
spec_list : list
List of twoples (invisible_fraction,window_duration).
trial_type : str
Trial type. 'hand' or 'avatar'
trials : list of VRTrial instances
mx_freq : int,10
Maximum frequency over which to average coherence
precision : float,.1
firstix : int
offset : int,None
Number of indices to offset the subject and template time series. If offset>0, we skip the
first offset elements from subject. If offset<0, -offset elements are removed from the
subject.
disp : bool,True
Returns
-------
cohmat : ndarray
Average coherence statistic over all trials. First three cols correspond to xyz dimensions
and last col is norm.
cohmaterr : ndarray
Standard error of the mean of coherence statistic.
"""
# First three cols correspond to xyz dimensions and last col is norm.
cohmat = np.zeros((len(trials),len(spec_list),4))
for itrial,trial in enumerate(trials):
for specix,spec in enumerate(spec_list):
cohOutput = _compare_coherence(trial,[spec,spec],[trial_type]*2,
[precision]*2,mx_freq,
firstix,disp,offset,template_only=True)
if not cohOutput is None:
f,cohmat[itrial,specix,:] = cohOutput
else:
cohmat[itrial,specix,:] = np.nan
return cohmat,np.nanstd(cohmat,axis=0)/np.sqrt((np.isnan(cohmat[:,0,0])==0).sum())
def coherence_null(spec_list,trial_type,trials,test_signal,
mx_freq=10,
precision=.1,
firstix=0,
offset=None,
disp=1):
"""
Calculate coherence between trials and an arbitrary signal.
Parameters
----------
spec_list : list
List of twoples (invisible_fraction,window_duration).
trial_type : str
Trial type. 'hand' or 'avatar'
trials : list of VRTrial instances
mx_freq : int,10
Maximum frequency over which to average coherence
precision : float,.1
firstix : int,0
offset : int,None
Number of indices to offset the subject and template time series. If offset>0, we skip the
first offset elements from subject. If offset<0, -offset elements are removed from the
subject.
disp : bool,True
Returns
-------
cohmat : ndarray
Average coherence statistic over all trials. First three cols correspond to xyz dimensions
and last col is norm.
cohmaterr : ndarray
Standard error of the mean of coherence statistic.
"""
# First three cols correspond to xyz dimensions and last col is norm.
cohmat = np.zeros((len(trials),len(spec_list),4))
for itrial,trial in enumerate(trials):
for specix,spec in enumerate(spec_list):
cohOutput = _compare_coherence_given_vel(trial,spec,trial_type,
precision,test_signal,
mx_freq,
firstix=firstix,disp=disp,offset=offset)
if not cohOutput is None:
f,cohmat[itrial,specix,:] = cohOutput
else:
cohmat[itrial,specix,:] = np.nan
return cohmat,np.nanstd(cohmat,axis=0)/np.sqrt((np.isnan(cohmat[:,0,0])==0).sum())
def _coherence_null(ignore_spec,trial_type,trials,
mx_freq=10,
precision=.1,
firstix=0,
offset=None,
disp=1):
"""
Calculate average coherence over all given trials excluding the particular one of interest.
Parameters
----------
spec_list : list
List of twoples (invisible_fraction,window_duration).
trial_type : str
Trial type. 'hand' or 'avatar'
trials : list of VRTrial instances
mx_freq : int,10
Maximum frequency over which to average coherence
precision : float,.1
firstix : int
offset : int,None
Number of indices to offset the subject and template time series. If offset>0, we skip the
first offset elements from subject. If offset<0, -offset elements are removed from the
subject.
Returns
-------
cohmat : ndarray
Average coherence statistic over all trials. First three cols correspond to xyz dimensions
and last col is norm.
cohmaterr : ndarray
Standard error of the mean of coherence statistic.
"""
# First three cols correspond to xyz dimensions and last col is norm.
cohmat = []
cohmaterr = []
for itrial,trial in enumerate(trials):
counter = 0
spec_list = [w[0] for w in trial.windowsByPart[trial_type] if not
isclose(w[0],ignore_spec,precision)]
cohmat.append( np.zeros((len(spec_list),4)) )
for specix,spec in enumerate(spec_list):
cohOutput = _compare_coherence(trial,[ignore_spec,spec],[trial_type]*2,
[precision]*2,mx_freq,
firstix,disp,offset)
if not cohOutput is None:
f,cxy = cohOutput
for dimIx,c in enumerate(cxy):
cohmat[-1][specix,dimIx] += c
counter += 1
ntrialmat = (cohmat[-1]!=0).sum(0) # number of trials available for each window spec
# used for normalization
cohmat[-1][cohmat[-1]==0] = np.nan
cohmaterr.append( np.nanstd(cohmat[-1],axis=0) )
cohmat[-1] = np.nansum(cohmat[-1],axis=0)
cohmat[-1] /= ntrialmat # averaged over number of data points
cohmaterr[-1] /= np.sqrt(ntrialmat) # standard error of the mean
return cohmat,cohmaterr
def coherence_null_null(ignore_spec,trial_type,trials,
mx_freq=10,
precision=.1,
firstix=0,
offset=None,
disp=1):
"""
Calculate coherence by comparing one window with all the other windows. The original idea was
that this would be a good null for checking performance of individuals, but this turns out not
to be so useful because the avatar's motion is pretty similar across some windows. This means
that this is not such a good null.
Instead a better idea might be to just make two different models for nulls: the same trajectory
displaced by a time delay and a periodic jerking motion.
Parameters
----------
spec_list : list
List of twoples (invisible_fraction,window_duration).
trial_type : str
Trial type. 'hand' or 'avatar'
trials : list of VRTrial instances
mx_freq : int,10
Maximum frequency over which to average coherence
precision : float,.1
firstix : int
offset : int,None
Number of indices to offset the subject and template time series. If offset>0, we skip the
first offset elements from subject. If offset<0, -offset elements are removed from the
subject.
Returns
-------
cohmat : ndarray
Average coherence statistic over all trials. First three cols correspond to xyz dimensions
and last col is norm.
cohmaterr : ndarray
Standard error of the mean of coherence statistic.
"""
# First three cols correspond to xyz dimensions and last col is norm.
cohmat = []
cohmaterr = []
for itrial,trial in enumerate(trials):
counter = 0
spec_list = [w[0] for w in trial.windowsByPart[trial_type] if not
isclose(w[0],ignore_spec,precision)]
cohmat.append( np.zeros((len(spec_list),4)) )
for specix,spec in enumerate(spec_list):
cohOutput = _compare_coherence(trial,[ignore_spec,spec],[trial_type]*2,
[precision]*2,mx_freq,
firstix,disp,offset,template_only=True)
if not cohOutput is None:
f,cxy = cohOutput
for dimIx,c in enumerate(cxy):
cohmat[-1][specix,dimIx] += c
counter += 1
ntrialmat = (cohmat[-1]!=0).sum(0) # number of trials available for each window spec
# used for normalization
cohmat[-1][cohmat[-1]==0] = np.nan
cohmaterr.append( np.nanstd(cohmat[-1],axis=0) )
cohmat[-1] = np.nansum(cohmat[-1],axis=0)
cohmat[-1] /= ntrialmat # averaged over number of data points
cohmaterr[-1] /= np.sqrt(ntrialmat) # standard error of the mean
return cohmat,cohmaterr
def isclose(spec1,spec2,precision):
"""
Compare two different specs.
"""
if not type(precision) is tuple:
precision = (precision,precision)
if (abs(spec1[0]-spec2[0])<=precision[0]) and (abs(spec1[1]-spec2[1])<=precision[1]):
return True
return False
def _compare_coherence(trial,windows,trial_types,precisions,mx_freq,
firstix=0,disp=True,offset=None,
template_only=False,cwt=False):
"""
Compare coherence for the given windows specified for the subject and for the template.
Parameters
----------
trial : VRTrial
windows : list of tuples
trial_types : list of strings
precisions : list of precision
mx_freq : float
firstix : int,0
disp : bool,True
offset : int,None
template_only : bool,False
cwt : bool,False
If True, compute coherence using continuous wavelet transform.
Returns
-------
"""
from scipy.signal import coherence
try:
if template_only:
sspec,t,subjectv = trial.template_by_window_spec([windows[0]],
trial_types[0],
precisions[0]
)[firstix]
else:
sspec,t,subjectv = trial.subject_by_window_spec([windows[0]],
trial_types[0],
precisions[0]
)[firstix]
tspec,t,templatev = trial.template_by_window_spec([windows[1]],
trial_types[1],
precisions[1]
)[firstix]
if not offset is None:
if offset>0:
t,subjectv = t[-1200:][:-offset],subjectv[-1200:][offset:]
templatev = templatev[-1200:][:-offset]
elif offset<0:
t = t[-1200:][:offset]
subjectv = subjectv[-1200:][:offset],
templatev = templatev[-1200:][-offset:]
else:
t = t[-1200:]
subjectv = subjectv[-1200:]
templatev = templatev[-1200:]
assert (len(subjectv)==1200) and (len(templatev)==1200)
if disp:
print("Subject: (%1.1f,%1.1f), Template: (%1.1f,%1.1f)"%(sspec[0],sspec[1],
tspec[0],tspec[1]))
if len(subjectv)==0:
return
# Calculate coherence for each dimension.
cxy = np.zeros(4) # averaged coherence
noverlap,nperseg = 30,90
nfft = nperseg*2
for dimIx in range(3):
if cwt:
f,cxy_ = cwt_coherence(subjectv[:,dimIx],templatev[:,dimIx],noverlap)
cxy_ *= -1
else:
f,cxy_ = coherence(subjectv[:,dimIx],templatev[:,dimIx],
fs=60,nperseg=nperseg,noverlap=noverlap,nfft=nfft)
cxy[dimIx] = np.trapz( cxy_[f<mx_freq],x=f[f<mx_freq] )/(f[f<mx_freq].max()-f[f<mx_freq].min())
# Coherence for velocity magnitude.
if cwt:
f,cxy_ = cwt_coherence(subjectv[:,dimIx],templatev[:,dimIx],noverlap)
cxy_ *= -1
else:
f,cxy_ = coherence(np.linalg.norm(subjectv,axis=1),
np.linalg.norm(templatev,axis=1),
fs=60,nperseg=nperseg,noverlap=noverlap,nfft=nfft)
cxy[3] = np.trapz( cxy_[f<mx_freq],x=f[f<mx_freq] )/(f[f<mx_freq].max()-f[f<mx_freq].min())
return f,cxy
except Exception as err:
if disp:
print("No data for window spec (%1.1f,%1.1f)."%(windows[0][0],
windows[0][1]))
return
def _compare_coherence_vis(trial,window,trial_type,precision,mx_freq,
firstix=0,disp=True,offset=None):
"""
Compare coherence.
Parameters
----------
trial : VRTrial
window
trial_type
precision
mx_freq
firstix : int,0
disp : bool,True
offset : int,None
"""
from scipy.signal import coherence
try:
sspec,t,visibility = trial.visibility_by_window_spec([window],
trial_type,
precision
)[firstix]
tspec,t,templatev = trial.template_by_window_spec([window],
trial_type,
precision
)[firstix]
if not offset is None:
if offset>0:
t,visibility = t[-1200:][:-offset],visibility[-1200:][offset:]
templatev = templatev[-1200:][:-offset]
elif offset<0:
t = t[-1200:][:offset]
visibility = visibility[-1200:][:offset],
templatev = templatev[-1200:][-offset:]
else:
t = t[-1200:]
visibility = visibility[-1200:]
templatev = templatev[-1200:]
assert (len(visibility)==1200) and (len(templatev)==1200)
if disp:
print("Subject: (%1.1f,%1.1f), Template: (%1.1f,%1.1f)"%(sspec[0],sspec[1],
tspec[0],tspec[1]))
if len(visibility)==0:
return
# Calculate coherence for each dimension.
cxy = np.zeros(4)
for dimIx in range(3):
f,cxy_ = coherence(visibility,templatev[:,dimIx],
fs=60,nperseg=120)
cxy[dimIx] = np.trapz( cxy_[f<mx_freq],x=f[f<mx_freq] )/(f[f<mx_freq].max()-f[f<mx_freq].min())
# Coherence for velocity magnitude.
f,cxy_ = coherence(visibility,
np.linalg.norm(templatev,axis=1),
fs=60,nperseg=120)
cxy[3] = np.trapz( cxy_[f<mx_freq],x=f[f<mx_freq] )/(f[f<mx_freq].max()-f[f<mx_freq].min())
return f,cxy
except Exception as err:
if disp:
print("No data for window spec (%1.1f,%1.1f)."%window)
return
def _compare_coherence_given_vel(trial,window,trial_type,precision,test_signal,mx_freq,
firstix=0,disp=True,offset=None):
"""
Compare coherence for the given windows specified for the subject and for the template.
Parameters
----------
trial : VRTrial
windows
trial_types
precisions
"""
from scipy.signal import coherence
assert len(test_signal)>=1200
try:
subjectv = test_signal
tspec,t,templatev = trial.template_by_window_spec([window],
trial_type,
precision
)[firstix]
if not offset is None:
if offset>0:
t,subjectv = t[-1200:][:-offset],subjectv[-1200:][offset:]
templatev = templatev[-1200:][:-offset]
elif offset<0:
t = t[-1200:][:offset]
subjectv = subjectv[-1200:][:offset],
templatev = templatev[-1200:][-offset:]
else:
t = t[-1200:]
subjectv = subjectv[-1200:]
templatev = templatev[-1200:]
assert (len(subjectv)==1200) and (len(templatev)==1200)
if disp:
print("Template: (%1.1f,%1.1f)"%(tspec[0],tspec[1]))
if len(subjectv)==0:
return
# Calculate coherence for each dimension.
cxy = np.zeros(4)
for dimIx in range(3):
f,cxy_ = coherence(subjectv[:,dimIx],templatev[:,dimIx],
fs=60,nperseg=120)
cxy[dimIx] = np.trapz( cxy_[f<mx_freq],x=f[f<mx_freq] )/(f[f<mx_freq].max()-f[f<mx_freq].min())
# Coherence for velocity magnitude.
f,cxy_ = coherence(np.linalg.norm(subjectv,axis=1),
np.linalg.norm(templatev,axis=1),
fs=60,nperseg=120)
cxy[3] = np.trapz( cxy_[f<mx_freq],x=f[f<mx_freq] )/(f[f<mx_freq].max()-f[f<mx_freq].min())
return f,cxy
except Exception as err:
if disp:
print("No data for window spec (%1.1f,%1.1f)."%(window[0],
window[1]))
return
def extract_motionbuilder_test(hand,
clear_pickle=False,
reverse_time=False):
"""
Load model motion data. Assuming the play rate is a constant 1/60 Hz as has been set in MotionBuilder when
exported. Returned data is put into standard global coordinate frame: x-axis is the axis between the two
subjects where positive is towards the front, y is the side to side, and z is up and down such that
positive y is determined by following the right hand rule.
These are pickled csv files that were exported from Mokka after preprocessing in Motionbuilder. Note that
the coordinate system in Motionbuilder and Mokka are different.
NOTE: Directory where animation data is stored is hard-coded.
Parameters
----------
hand : str
Hand of the model.
fname : str,'Eddie_Grid_Model_%s_Anim_Export_Take_001'
Name of file with %s to replace with handedness.
reverse_time : bool,False
Read data backwards from end.
Returns
-------
mbV : scipy.interpolate.interp1d
Returns (n_samples,3) dimensional matrix.
mbT : ndarray of float
Number of seconds since the beginning of the avatar motion file.
"""
from datetime import datetime,timedelta
import pickle as pickle
from scipy.interpolate import interp1d
assert hand=='Left' or hand=='Right'
fname='mb_test'
dr = ( os.path.expanduser('~')+'/Dropbox/Research/tango/data/UE4_Experiments/'+
'Simple_MB_Test' )
if (not os.path.exists('%s/%s.p'%(dr,fname))) or clear_pickle:
from .axis_neuron import load_csv
mbdf = load_csv('%s/%s.csv'%(dr,fname))
mbdf.to_pickle('%s/%s.p'%(dr,fname))
mbdf = pickle.load(open('%s/%s.p'%(dr,fname),'rb'))
mbT = mbdf['Time'].values.astype(float)
mbT -= mbT[0]
mbV = savgol_filter( mbdf['%sHand'%hand].values,31,3,deriv=1,axis=0,delta=1/60 )/1000 # units of m/s
mbV[:,:] = mbV[:,[1,0,2]]
mbV[:,1] *= -1
if reverse_time:
mbV = mbV[::-1]
mbV = interp1d(mbT,mbV,axis=0,assume_sorted=True,copy=False)
return mbV,mbT
def extract_motionbuilder_model3_3(hand,
dr=( os.path.expanduser('~')+'/Dropbox/Research/tango/data/UE4_Experiments/'+
'Animations/Eddie_Grid_Model' ),
fname='Eddie_Grid_Model_%s_Anim_Export_Take_001',
reverse_time=False):
"""
Load model motion data. Assuming the play rate is a constant 1/60 Hz as has been set in MotionBuilder when
exported. Returned data is put into standard global coordinate frame: x-axis is the axis between the two
subjects where positive is towards the front, y is the side to side, and z is up and down such that
positive y is determined by following the right hand rule.
These are pickled csv files that were exported from Mokka after preprocessing in Motionbuilder. Note that
the coordinate system in Motionbuilder and Mokka are different.
Parameters
----------
hand : str
Hand of the model. Must be 'Left' or 'Right'.
fname : str,'Eddie_Grid_Model_%s_Anim_Export_Truncate_Take_001'
Name of file with %s to replace with handedness.
reverse_time : bool,False
Read data backwards from end. This option is used when the avatar's motion is played in reverse.
Returns
-------
mbV : scipy.interpolate.interp1d
Returns (n_samples,3) dimensional matrix.
mbT : ndarray of float
Number of seconds since the beginning of the avatar motion file.
"""
from datetime import datetime,timedelta
import pickle as pickle
from scipy.interpolate import interp1d
assert hand=='Left' or hand=='Right'
fname = fname%hand
# Create pickle if it doesn't already exist.
if not os.path.exists('%s/%s.p'%(dr,fname)):
from .axis_neuron import load_csv
mbdf = load_csv('%s/%s.csv'%(dr,fname))
mbdf.to_pickle('%s/%s.p'%(dr,fname))
mbdf = pickle.load(open('%s/%s.p'%(dr,fname),'rb'))
mbT = mbdf['Time'].values.astype(float)
print("MB start and end times: %1.2f and %1.2f"%(mbT[0],mbT[-1]))
mbT -= mbT[0]
mbV = savgol_filter( mbdf['%sHand'%hand].values,31,3,deriv=1,axis=0,delta=1/60 )/1000 # units of m/s
mbV[:,:] = mbV[:,[1,0,2]]
if reverse_time:
# When you reverse time, you must also reverse the velocities.
mbV = -mbV[::-1]
# Put these in the standard global coordinate system such that avatars are facing +x direction. See Tango
# III pg 45.
if hand=='Left':
mbV[:,0] *= -1
else:
# With right hand, the avatar starts facing the opposite direction so she is already facing the
# same direction as the original y-axis.
mbV[:,1] *= -1
# y-axis needs to be reflected to put into same chirality as subject
mbV[:,1] *= -1
mbV = interp1d(mbT,mbV,axis=0,assume_sorted=True,copy=False)
return mbV,mbT
def extract_motionbuilder_Eddie_Grid_Model_2(hand,
dr=( os.path.expanduser('~')+'/Dropbox/Research/tango/data/UE4_Experiments/'+
'Animations/Eddie_Grid_Model_2' ),
fname='Eddie_Grid_Model_2_%s_Take_001',
reverse_time=False):
"""
See extract_motionbuilder_model3_3 for notes. The only difference here is that the orientation
of the avatar in Mokka is in the -x direction for both left and right hands.
Parameters
----------
hand : str
Hand of the model. Must be 'Left' or 'Right'.
dr : str,( os.path.expanduser('~')+'/Dropbox/Research/tango/data/UE4_Experiments/'+
'Animations/Eddie_Grid_Model_2' )
fname : str,'Eddie_Grid_Model_%s_Anim_Export_Take_001'
Name of file with %s to replace with handedness.
reverse_time : bool,False
Read data backwards from end. This option is used when the avatar's motion is played in reverse.
Returns
-------
mbV : scipy.interpolate.interp1d
Returns (n_samples,3) dimensional matrix.
mbT : ndarray of float
Number of seconds since the beginning of the avatar motion file.
"""
from datetime import datetime,timedelta
import pickle as pickle
from scipy.interpolate import interp1d
assert hand=='Left' or hand=='Right'
fname = fname%hand
# Create pickle if it doesn't already exist.
if not os.path.exists('%s/%s.p'%(dr,fname)):
from .axis_neuron import load_csv
mbdf = load_csv('%s/%s.csv'%(dr,fname))
mbdf.to_pickle('%s/%s.p'%(dr,fname))
mbdf = pickle.load(open('%s/%s.p'%(dr,fname),'rb'))
mbT = mbdf['Time'].values.astype(float)
mbT -= mbT[0]
mbV = savgol_filter( mbdf['%sHand'%hand].values,31,3,deriv=1,axis=0,delta=1/60 )/1000 # units of m/s
if reverse_time:
# When you reverse time, you must also reverse the velocities.
mbV = -mbV[::-1]
# Put these in the standard global coordinate system such that avatars are facing +x direction. See Tango
# III pg 45. Only 180 degree rotation about z-axis is required here.
mbV[:,:2] *= -1
# y-axis needs to be reflected to put into same chirality as subject
mbV[:,1] *= -1
mbV = interp1d(mbT,mbV,axis=0,assume_sorted=True,copy=False)
return mbV,mbT
def extract_motionbuilder_model3(hand,
fname='Eddie_Grid_Model_%s_Anim_Export_Take_001',
reverse_time=False):
"""
Load model motion data. Assuming the play rate is a constant 1/60 Hz as has been set in MotionBuilder when
exported. Returned data is put into standard global coordinate frame: x-axis is the axis between the two
subjects where positive is towards the front, y is the side to side, and z is up and down such that
positive y is determined by following the right hand rule.
These are pickled csv files that were exported from Mokka after preprocessing in Motionbuilder. Note that
the coordinate system in Motionbuilder and Mokka are different.
NOTE: Directory where animation data is stored is hard-coded.
Parameters
----------
hand : str
Hand of the model.
fname : str,'Eddie_Grid_Model_%s_Anim_Export_Take_001'
Name of file with %s to replace with handedness.
reverse_time : bool,False
Read data backwards from end.
Returns
-------
mbV : scipy.interpolate.interp1d
Returns (n_samples,3) dimensional matrix.
mbT : ndarray of float
Number of seconds since the beginning of the avatar motion file.
"""
from datetime import datetime,timedelta
import pickle as pickle
from scipy.interpolate import interp1d
assert hand=='Left' or hand=='Right'
dr = ( os.path.expanduser('~')+'/Dropbox/Research/tango/data/UE4_Experiments/'+
'Animations/Eddie_Grid_Model' )
fname = fname%hand
# Create pickle if it doesn't already exist.
if not os.path.exists('%s/%s.p'%(dr,fname)):
from .axis_neuron import load_csv
mbdf = load_csv('%s/%s.csv'%(dr,fname))
mbdf.to_pickle('%s/%s.p'%(dr,fname))
mbdf = pickle.load(open('%s/%s.p'%(dr,fname),'rb'))
mbT = mbdf['Time'].values.astype(float)
mbT -= mbT[0]
mbV = savgol_filter( mbdf['%sHand'%hand].values,31,3,deriv=1,axis=0,delta=1/60 )/1000 # units of m/s
mbV[:,:] = mbV[:,[1,0,2]]
if reverse_time:
mbV = -mbV[::-1]