forked from sccn/mobilab
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mocapPhasespace.m
1664 lines (1490 loc) · 84.4 KB
/
mocapPhasespace.m
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
%% mocapPhasespace class
% Creates and uses a mocap object using predefined rigidbodies in the mocap data.
%
% Author: Marius Klug, TU Berlin, 13-Sep-2016, adapted from Alejandro Ojeda
%%
classdef mocapPhasespace < dataStream
properties(GetAccess = public, SetAccess = public)
animationParameters; % Structure used for animating stick figures.
% It should have the following fields:
% limits: [min _x max_x; min_y max_y; min_z max_z]
% specifying the dimensions of the mocap space
% conn: [marker_i marker_j] matrix specifying connections
% between markers.
lsMarker2JointMapping
end
properties(GetAccess = public, SetAccess = protected, AbortSet = true)
bodyModelFile
end
properties(Dependent)
dataInXYZ % Dependent property that reshapes the second dimension
% of the field data to allows accessing directly xyz
% coordinates of motion capture markers.
magnitude % Dependent property that computes the magnitude (distance
% from the origin) of xyz motion capture markers.
end
methods
%%
function obj = mocapPhasespace(header)
% Creates a mocap object.
%
% Input arguments:
% header: header file (string)
%
% Output arguments:
% obj: mocap object (handle)
if nargin < 1, error('Not enough input arguments.');end
obj@dataStream(header);
end
%%
function animationParameters = get.animationParameters(obj)
stack = dbstack;
if any(strcmp({stack.name},'coreStreamObject.set.animationParameters'))
animationParameters = obj.animationParameters;
return;
end
if isempty(obj.animationParameters)
try obj.animationParameters = retrieveProperty(obj,'animationParameters');
catch
animationParameters = struct('limits',[],'conn',[],'bodymodel',[]);
save(obj.header,'-mat','-append','animationParameters')
obj.animationParameters = animationParameters;
end
end
saveIt = false;
if ~isfield(obj.animationParameters,'limits'), obj.animationParameters.limits = [];saveIt=true;end
if ~isfield(obj.animationParameters,'conn'), obj.animationParameters.conn = [];saveIt=true;end
if ~isfield(obj.animationParameters,'bodymodel'), obj.animationParameters.bodymodel = [];saveIt=true;end
if isempty(obj.animationParameters.limits)
mx = 1.05*max(max(abs(squeeze(obj.dataInXYZ(1:100:end,1,:)))));
my = 1.05*max(max(abs(squeeze(obj.dataInXYZ(1:100:end,2,:)))));
mz = 1.05*max(max(abs(squeeze(obj.dataInXYZ(1:100:end,3,:)))));
mnz = min(min(squeeze(obj.dataInXYZ(1:100:end,3,:))));
obj.animationParameters.limits = [-mx mx;-my my;mnz mz];
end
animationParameters = obj.animationParameters;
if saveIt, save(obj.header,'-mat','-append','animationParameters');end
end
function set.animationParameters(obj,animationParameters)
stack = dbstack;
if any(strcmp({stack.name},'coreStreamObject.get.animationParameters'))
obj.animationParameters = animationParametersj;
return;
end
if ~isfield(animationParameters,'limits'), animationParameters.limits = [];end
if ~isfield(animationParameters,'conn'), animationParameters.conn = [];end
if ~isfield(animationParameters,'bodymodel'), animationParameters.bodymodel = [];end
saveProperty(obj,'animationParameters',animationParameters);
obj.animationParameters = animationParameters;
end
%%
function lsMarker2JointMapping = get.lsMarker2JointMapping(obj)
stack = dbstack;
if any(strcmp({stack.name},'coreStreamObject.set.lsMarker2JointMapping'))
lsMarker2JointMapping = obj.lsMarker2JointMapping;
return;
end
if isempty(obj.lsMarker2JointMapping), obj.lsMarker2JointMapping = retrieveProperty(obj,'lsMarker2JointMapping');end
lsMarker2JointMapping = obj.lsMarker2JointMapping;
end
function set.lsMarker2JointMapping(obj,lsMarker2JointMapping)
stack = dbstack;
if any(strcmp({stack.name},'coreStreamObject.get.lsMarker2JointMapping'))
obj.lsMarker2JointMapping = lsMarker2JointMapping;
return;
end
save(obj.header,'-mat','-append','lsMarker2JointMapping');
obj.lsMarker2JointMapping = lsMarker2JointMapping;
end
%%
function data = get.dataInXYZ(obj)
data = [];
if obj.isMemoryMappingActive
if obj.numberOfChannels/3 > 1
perm = 1:3;
if isempty(obj.hardwareMetaData.name) || strcmpi(obj.hardwareMetaData.name,'phasespace') %&& isa(obj.hardwareMetaData,'hardwareMetaData')
perm = [1 3 2];
elseif isempty(obj.hardwareMetaData.name) || ~isempty(strfind(obj.hardwareMetaData.name,'KinectMocap'))
perm = [1 3 2];
end
%if strcmp(obj.hardwareMetaData.name,'optitrack')
% perm = 1:3;%perm = [3 1 2];
%else
% perm = [1 3 2];
%end
dim = obj.size;
obj.reshape([dim(1) 3 dim(2)/3]);
data = obj.mmfObj.Data.x(:,perm,:);
obj.reshape(dim);
else data = obj.mmfObj.Data.x;
end
else disp('Cannot read the binary file.');
end
end
%%
function set.dataInXYZ(obj,data)
obj.mmfObj.Writable = obj.writable;
if strcmpi(obj.hardwareMetaData.name,'phasespace') && isa(obj.hardwareMetaData,'hardwareMetaData')
perm = [1 3 2];
else perm = [1 2 3];
end
if obj.numberOfChannels/3 > 1
dim = obj.size;
obj.reshape([dim(1) 3 dim(2)/3]);
obj.mmfObj.Data.x = data(:,perm,:);
obj.reshape(dim);
else obj.mmfObj.Data.x = data(:,perm,:);
end
obj.mmfObj.Writable = false;
end
%%
function mag = get.magnitude(obj)
dim = obj.size;
if ~mod(obj.numberOfChannels,3)
obj.reshape([dim(1) 3 dim(2)/3]);
elseif ~mod(obj.numberOfChannels,2)
obj.reshape([dim(1) 2 dim(2)/2]);
end
mag = squeeze(sqrt(sum(obj.mmfObj.Data.x.^2,2)));
obj.reshape(dim);
end
%%
function jsonObj = serialize(obj)
metadata = saveobj(obj);
metadata.class = class(obj);
metadata.size = size(obj);
metadata.event = obj.event.uniqueLabel;
metadata.artifactMask = sum(metadata.artifactMask(:) ~= 0);
metadata.writable = double(metadata.writable);
metadata.history = obj.history;
if isempty(metadata.animationParameters.conn)
metadata.hasStickFigure = 'no';
else
metadata.hasStickFigure = 'yes';
end
metadata = rmfield(metadata,'animationParameters');
metadata = rmfield(metadata,{'parentCommand' 'timeStamp','hardwareMetaData'});
jsonObj = savejson('',metadata,'ForceRootName', false);
end
%%
function loadConnectedBody(obj,file)
% Loads from a .mat file a matrix called 'connectedBody' containing
% the connections among markers. It fills the connections to
% animationParameters.conn.
%
% Input argument:
% file: Pointer to the .mat file containing the connections
%
% Usage:
% file = mobilab.preferences.mocap.stickFigure;
% mocapObj = mobilab.allStreams.item{ mocapItem };
% mocapObj.loadConnectedBody( file );
% plot( mocapObj );
if nargin < 2
[filename,path] = uigetfile2('*.mat','Select the file containing the connections',obj.container.container.preferences.mocap.stickFigure);
if isnumeric(filename), return;end
file = fullfile(path,filename);
end
if ~ischar(file)
[filename,path] = uigetfile2('*.mat','Select the file containing the connections',obj.container.container.preferences.mocap.stickFigure);
if isnumeric(filename), return;end
file = fullfile(path,filename);
end
if ~exist(file,'file'), error('The file does''t exist.');end
warning off %#ok
load(file,'connectedBody');
warning on %#ok
if ~exist('connectedBody','var'), error(' Variable ''connectedBody'' not found. ');end
if ~all(ismember(unique(connectedBody(:))',1:obj.numberOfChannels/3)) %#ok
error('MoBILAB:stickFigureDoesntMatch','The stick figure doesn''t match the channels in the mocap object.');
end
obj.animationParameters.conn = connectedBody;
saveProperty(obj,'animationParameters',obj.animationParameters);
end
%%
function cobj = throwOutChannels(obj,varargin)
% Throws out selected channels.
%
% Input arguments:
% channels
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% newMocapObj = mocapObj.throwOutChannels(channelsToThrow);
%
dispCommand = false;
if ~isempty(varargin) && iscell(varargin) && isnumeric(varargin{1}) && varargin{1}(1) == -1
prompt = {'Enter channel numbers to throw out.'};
dlg_title = 'Input parameters';
num_lines = 1;
channelsToThrow = inputdlg2(prompt,dlg_title,num_lines,{''});
varargin{1} = str2num(channelsToThrow{1});
if isempty(varargin), return;end
dispCommand = true;
end
commandHistory.commandName = 'throwOutChannels';
commandHistory.uuid = obj.uuid;
commandHistory.varargin{1} = varargin{1};
cobj = obj.copyobj(commandHistory);
if dispCommand
disp('Running:');
disp([' ' cobj.history]);
end
channelsToThrow = commandHistory.varargin{1};
channelsToKeep = 1:obj.numberOfChannels;
channelsToKeep(channelsToThrow) = [];
cobj.mmfObj.Data.x = obj.mmfObj.Data.x(:,channelsToKeep);
end
%%
function cobj = addChannels(obj,varargin)
% 2 inputs: A cell containing strings for labels of the additional channels, a data matrix for the new
% channels. Channels will be appended automatically at the end.
dispCommand = false;
if ~isempty(varargin) && iscell(varargin) && isnumeric(varargin{1}) && varargin{1} == -1
error('Dont use the GUI for this, its not implemented.');
else
if length(varargin) ~= 2
error('Enter two arguments: The number of channels to add and the data matrix of them!')
end
end
allData = obj.mmfObj.Data.x;
allData(:,end+1:end+size(varargin{2},2)) = varargin{2};
allLabels = obj.label;
allLabels(end+1:end+length(varargin{1})) = varargin{1};
commandHistory.commandName = 'addChannels';
commandHistory.uuid = obj.uuid;
commandHistory.varargin{1} = varargin{1};
commandHistory.varargin{2} = 'This would be the data matrix of the added channels.';
cobj = obj.copyobj(commandHistory);
cobj.mmfObj.Data.x = allData;
end
%%
function cobj = removeOcclusionArtifact(obj,varargin)
% Fills-in occluded time points. In optical mocap systems like PhaseSpace
% (http://www.phasespace.com/), sometimes markers go missing from more than
% one camera causing the system to put zero or some other predetermined value
% in that sample. This method identifies the samples that are exactly zero and
% interpolates them.
%
% Input arguments:
% method: could be nearest, linear, spline, or pchip, default: pchip
% channels: channels to fix if needed, default: all
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% method = 'pchip';
% newMocapObj = mocapObj.removeOcclusionArtifact( method);
%
% figure;plot(mocapObj.timeStamp, [mocapObj.data(:,1) newMocapObj.data(:,1)])
% xlabel('Time (sec)');legend({mocapObj.name newMocapObj.name});
if length(varargin) == 1 && iscell(varargin{1}), varargin = varargin{1};end
dispCommand = false;
if ~isempty(varargin) && iscell(varargin) && isnumeric(varargin{1}) && varargin{1} == -1
prompt = {'Enter interpolation method: (''pchip'', ''spline'', ''linear'', ''nearest'')'};
dlg_title = 'Input parameters';
num_lines = 1;
def = {obj.container.container.preferences.mocap.interpolation};
varargin = inputdlg2(prompt,dlg_title,num_lines,def);
if isempty(varargin), return;end
dispCommand = true;
end
if nargin < 2, method = 'pchip'; else method = varargin{1};end
if nargin < 3, channels = 1:obj.numberOfChannels;else channels = varargin{2};end
if ~ischar(method), error('prog:input','First argument must be a string that specify the interpolation method.');end
switch lower(method)
case 'nearest'
case 'linear'
case 'spline'
case 'pchip'
otherwise
error('prog:input','Unknown interpolation method. Go to interp1 help page to see the alternatives.');
end
if ~isnumeric(channels), error('Invalid input argument.');end
if ~all(intersect(channels,1:obj.numberOfChannels)), error('Invalid input channels.');end
try
data = obj.mmfObj.Data.x;
commandHistory.commandName = 'removeOcclusionArtifact';
commandHistory.uuid = obj.uuid;
commandHistory.varargin{1} = method;
commandHistory.varargin{2} = channels;
cobj = obj.copyobj(commandHistory);
cobj.mmfObj.Data.x = obj.mmfObj.Data.x;
if dispCommand
disp('Running:');
disp([' ' cobj.history]);
end
% fill occlusions interpolating the signal
obj.initStatusbar(1,cobj.numberOfChannels,'Filling-in occluded time points...');
for it=1:cobj.numberOfChannels
indi = data(:,channels(it))==0 | data(:,channels(it))==1;
if any(indi) && sum(indi) < length(obj.timeStamp)-1
cobj.mmfObj.Data.x(indi,it) = interp1(obj.timeStamp(~indi),data(~indi,channels(it)),obj.timeStamp(indi),method);
if ~data(end,channels(it))
loc = find(~indi, 1, 'last' );
cobj.mmfObj.Data.x(loc+1:end,it) = data(loc,channels(it));
end
if ~data(1,channels(it))
loc = find(~indi, 1, 'first' );
cobj.mmfObj.Data.x(1:loc-1,it) = data(loc,channels(it));
end
end
obj.statusbar(it);
end
cobj.mmfObj.Writable = false;
catch ME
obj.statusbar(obj.numberOfChannels);
if exist('cobj','var'), obj.container.deleteItem(obj.container.findItem(cobj.uuid));end
ME.rethrow;
end
end
%%
function cobj = lowpass(obj, varargin)
% Filters the motion capture data with a zero-lag lowpass FIR
% filter calling the method filter defined in dataStream.
%
% Input arguments:
% cutOff: lowpass cutoff frequency (in Hz)
% channels: channel to filter, default: all
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% cutOff = 6; % lowpass at 6 Hz
% mocapObjFilt = mocapObj.lowpass( cutOff );
%
% figure;plot(mocapObj.timeStamp, [mocapObj.data(:,1) mocapObjFilt.data(:,1)])
% xlabel('Time (sec)');legend({mocapObj.name mocapObjFilt.name});
dispCommand = false;
if length(varargin) == 1 && iscell(varargin{1}), varargin = varargin{1};end
if ~isempty(varargin) && iscell(varargin) && isnumeric(varargin{1}) && varargin{1} == -1
prompt = {'Enter the cutoff frequency:'};
dlg_title = 'Filter input parameters';
num_lines = 1;
def = {num2str(obj.container.container.preferences.mocap.lowpassCutoff)};
varargin = inputdlg2(prompt,dlg_title,num_lines,def);
if isempty(varargin), return;end
varargin{1} = str2double(varargin{1});
if isnan(varargin{1}), return;end
dispCommand = true;
end
% Cutoff Frequency
if nargin < 2, fc = 6; else fc = varargin{1};end
if nargin < 3, channels = 1:obj.numberOfChannels; else channels = varargin{2};end
if nargin < 4
N = 128;
disp('Third argument must be the length of the filter (integer type). Using the default: 128.');
elseif isnumeric(varargin{3})
N = varargin{3};
else N = 128;
end
try cobj = obj.filter('lowpass',fc,channels,N);
if dispCommand
disp('Running:');
disp([' ' cobj.history]);
end
catch ME
if exist('cobj','var'), obj.container.deleteItem(obj.container.findItem(cobj.uuid));end
ME.rethrow;
end
end
%%
function cobj = oneEuroFilter(obj, varargin)
% Filters the motion capture data with a one euro filter.
% See Gery Casiez, Nicolas Roussel, Daniel Vogel. 1 ? Filter: A Simple Speed-based Low-pass Filter for
% Noisy Input in Interactive Systems. CHI?12, the 30th Conference on Human Factors in Computing
% Systems, May 2012, Austin, United States. ACM, pp.2527-2530, 2012, <10.1145/2207676.2208639>.
% <hal-00670496>
%
% Input arguments:
% mincutoff: minimum lowpass cutoff frequency (in Hz)
% beta: beta value for adaptation of the filter -> higher value lead to less lag and more jitter for
% high frequency data
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mincutoff = 1;
% beta = 2;
% mocapObjFilt = mobilab.allStreams.item{7}.oneEuroFilter( mincutoff , beta );
dispCommand = false;
if length(varargin) == 1 && iscell(varargin{1}), varargin = varargin{1};end
if ~isempty(varargin) && iscell(varargin) && isnumeric(varargin{1}) && varargin{1} == -1
prompt = {'Enter the minimal cutoff frequency:'};
dlg_title = 'Filter input parameters';
num_lines = 1;
%def = {num2str(obj.container.container.preferences.mocap.lowpassCutoff)};
def = {num2str(1.0)};
inputFromDialog = inputdlg2(prompt,dlg_title,num_lines,def);
if isempty(inputFromDialog), return;end
varargin{1} = str2double(inputFromDialog{1});
if isnan(varargin{1}), return;end
prompt = {'Enter the beta value:'};
dlg_title = 'Filter input parameters';
num_lines = 1;
%def = {num2str(obj.container.container.preferences.mocap.lowpassCutoff)};
def = {num2str(15.0)};
inputFromDialog = inputdlg2(prompt,dlg_title,num_lines,def);
if isempty(inputFromDialog), return;end
varargin{2} = str2double(inputFromDialog{1});
if isnan(varargin{2}), return;end
dispCommand = true;
end
% Cutoff Frequency and beta values
if nargin < 1, mincutoff = 1.0; else mincutoff = varargin{1};end
if nargin < 2, beta = 15.0; else beta = varargin{2};end
try
noisySignal = obj.mmfObj.Data.x;
commandHistory.commandName = 'oneEuroFilter';
commandHistory.uuid = obj.uuid;
commandHistory.varargin{1} = mincutoff;
commandHistory.varargin{2} = beta;
cobj = obj.copyobj(commandHistory);
if dispCommand
disp('Running:');
disp([' ' cobj.history]);
end
%Declare oneEuro object
theOneEuroFilter = oneEuro;
%Alter filter parameters to tune
theOneEuroFilter.mincutoff = mincutoff;
theOneEuroFilter.beta = beta;
filteredSignal = zeros(size(noisySignal));
obj.initStatusbar(1,size(noisySignal,2),'Filtering...');
% filter all channels
for channelToFilter = 1:size(noisySignal,2)
% the filter goes through all data points
for dataPoint = 1:size(noisySignal,1)
filteredSignal(dataPoint,channelToFilter) = theOneEuroFilter.filter(noisySignal(dataPoint,channelToFilter),obj.samplingRate);
end
obj.statusbar(channelToFilter);
end
% add the filtered data
cobj.mmfObj.Data.x = filteredSignal;
catch ME
if exist('cobj','var'), obj.container.deleteItem(obj.container.findItem(cobj.uuid));end
ME.rethrow;
end
end
%%
function cobj = timeDerivative(obj,varargin)
% Computes the time derivatives of motion capture data. It smooths
% the signals after each order of derivation to minimize cumulative
% precision errors. As smoother it uses a zero-lag FIR lowpass filter.
% Each new derivative is stored in a new object.
%
% Input arguments:
% order: maximum order of derivation, default: 3 (1 = velocity,
% 2 = acceleration, 3 = jerk)
% cutOff: lowpass filter cutoff, default: 18 Hz.
%
% Output argument:
% cobj: handle to the object containing the latest order of
% derivation
%
% Uses:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% order = 3;
% mocapObj.timeDerivative( order );
%
% figure;
% subplot(411);plot(mocapObj.timeStamp,mocapObj.data(:,1));xlabel('Time (sec)');title(mocapObj.name)
% subplot(412);plot(mocapObj.timeStamp, mocapObj.children{1}.data(:,1));xlabel('Time (sec)');title(mocapObj.children{1}.name)
% subplot(413);plot(mocapObj.timeStamp, mocapObj.children{2}.data(:,1));xlabel('Time (sec)');title(mocapObj.children{2}.name)
% subplot(414);plot(mocapObj.timeStamp, mocapObj.children{3}.data(:,1));xlabel('Time (sec)');title(mocapObj.children{3}.name)
dispCommand = false;
if length(varargin) == 1 && iscell(varargin{1}), varargin = varargin{1};end
if ~isempty(varargin) && isnumeric(varargin{1}) && length(varargin{1}) == 1 && varargin{1} == -1
prompt = {'Enter the order of the time derivative: ( 1->vel, 2->acc, 3->jerk,... or 1:3->for all of them)'};
dlg_title = 'Time derivative input parameter';
num_lines = 1;
def = {num2str(obj.container.container.preferences.mocap.derivationOrder)};
varargin = inputdlg2(prompt,dlg_title,num_lines,def);
if isempty(varargin), return;end
varargin{1} = eval(varargin{1});
dispCommand = true;
end
if nargin < 2, order = 3;else order = varargin{1};end
if nargin < 3, fc = 6; else fc = varargin{2};end
if nargin < 4, channels = 1:obj.numberOfChannels;else channels = varargin{3};end
if nargin < 5, filterOrder = 128;else filterOrder = varargin{4};end
if ~isnumeric(order), error('prog:input','First argument must be the order of the derivative (1=veloc, 2=acc, 3=jerk).');end
if ~isnumeric(fc), error('prog:input','Second argument must be the cut off frequency.');end
if ~isnumeric(channels), error('Invalid channel.');end
if ~all(intersect(channels,1:obj.numberOfChannels)), error('Invalid channel.');end
% checking for Quaternion values
if sum(~cellfun('isempty',strfind(obj.label,'_A')))>0, error('Please throw out Quaternion values before calculating time derivatives!');end
Nch = length(channels);
dt = 1/obj.samplingRate;
% dt = 1e3*dt; % from seconds to mili seconds
order = unique(1:max(order));
N = max(order);
try
% smooth the data by 0 phase shifting moving average
a = 1;
b = obj.firDesign(filterOrder,'lowpass',fc);
commandHistory.commandName = 'timeDerivative';
commandHistory.uuid = obj.uuid;
commandHistory.varargin{2} = fc;
commandHistory.varargin{3} = channels;
obj.initStatusbar(1,N*Nch,'Computing time derivatives...');
tmpObj = obj;
tmpData = obj.mmfObj.Data.x;
for derivative=1:N
for channel=1:size(tmpData,2)
% deriving
tmpData(1:end-1,channel) = diff(tmpData(:,channel),1)/dt;
tmpData(end,channel) = tmpData(end-1,channel);
% check if channel is Euler angles and if so,
% correct for turns over pi or -pi respectively
if strfind(obj.label{channel},'Euler')
% cobj.mmfObj.Data.x(cobj.mmfObj.Data.x > 2*pi, jt) = cobj.mmfObj.Data.x(cobj.mmfObj.Data.x > 2*pi, jt) - 2*pi;
% cobj.mmfObj.Data.x(cobj.mmfObj.Data.x < -2*pi, jt) = cobj.mmfObj.Data.x(cobj.mmfObj.Data.x < -2*pi, jt) + 2*pi;
dataChannel = tmpData(:,channel);
% turning rates of more than half a circle per frame are not possible
dataChannel(dataChannel > 180/dt) = dataChannel(dataChannel > 180/dt) - 2*180/dt;
dataChannel(dataChannel < -180/dt) = dataChannel(dataChannel < -180/dt) + 2*180/dt;
tmpData(:,channel) = dataChannel;
end
% smoothing
% % cobj.mmfObj.Data.x(:,jt) = filtfilt_fast(b,a,cobj.mmfObj.Data.x(:,jt));
obj.statusbar((Nch*(derivative-1)+channel));
end
% creating the new object and filling the derived data
commandHistory.varargin{1} = derivative;
cobj = tmpObj.copyobj(commandHistory);
cobj.mmfObj.Data.x = tmpData;
% soft masking
if derivative==1, artifactIndices = cobj.artifactMask(:) ~= 0;end
if any(artifactIndices), cobj.mmfObj.Data.x(artifactIndices) = cobj.mmfObj.Data.x(artifactIndices).*(1-cobj.artifactMask(artifactIndices));end
tmpObj = cobj;
end
if dispCommand
disp('Running:');
disp([' ' cobj.history]);
end
catch ME
obj.statusbar(N*Nch);
try obj.container.deleteItem(cobj.uuid);end %#ok
ME.rethrow;
end
end
%%
function browserObj = plot(obj)
% Overwrites the plot method defined in its base class to display
% mocap data as stick figures in three dimensional space.
browserObj = mocapBrowser(obj);
end
function browserObj = mocapBrowser(obj,defaults)
if nargin < 2, defaults.browser = @mocapBrowserHandle;end
if ~isfield(defaults,'browser'), defaults.browser = @mocapBrowserHandle;end
browserObj = defaults.browser(obj,defaults);
end
%%
function cobj = projectDataPCA(obj,varargin)
dispCommand = false;
if isnumeric(varargin{1}) && length(varargin{1}) == 1 && varargin{1} == -1
prefObj = [...
PropertyGridField('startLatency',obj.timeStamp(1),'DisplayName','Start latency of clean segments','Description','Latency in seconds of the start of the clean segments of data.')...
PropertyGridField('endLatency',obj.timeStamp(end),'DisplayName','Final latency of clean segments','Description','Latency in seconds of the end of the clean segments of data.')...
PropertyGridField('robustPcaFlag',false,'DisplayName','Compute robust PCA','Description','Fits a Gaussian Mixture Model removing the component associated with the artefacts.')...
PropertyGridField('numberOfGaussianMixtures',3,'DisplayName','Number of gaussians','Description','Fits n+1 Gaussians. The last one is usually associated with the non-structured part of the data (noise).')...
];
% create figure
hFigure = figure('MenuBar','none','Name','PCA','NumberTitle', 'off','Toolbar', 'none');
position = get(hFigure,'position');
set(hFigure,'position',[position(1:2) 303 231]);
hPanel = uipanel(hFigure,'Title','','BackgroundColor','white','Units','pixels','Position',[0 55 303 180],'BorderType','none');
g = PropertyGrid(hPanel,'Properties', prefObj,'Position', [0 0 1 1]);
uicontrol(hFigure,'Position',[72 15 70 21],'String','Cancel','ForegroundColor',obj.container.container.preferences.gui.fontColor,...
'BackgroundColor',obj.container.container.preferences.gui.buttonColor,'Callback',@cancelCallback);
uicontrol(hFigure,'Position',[164 15 70 21],'String','Ok','ForegroundColor',obj.container.container.preferences.gui.fontColor,...
'BackgroundColor',obj.container.container.preferences.gui.buttonColor,'Callback',@okCallback);
uiwait(hFigure);
if ~ishandle(hFigure), return;end
if ~get(hFigure,'userData')
close(hFigure);
cobj = [];
return;
end
close(hFigure);
drawnow
val = g.GetPropertyValues();
if length(val.startLatency) ~= length(val.endLatency), error('Latencies must have the same length.');end
varargin{1} = [val.startLatency(:) val.endLatency(:)];
varargin{2} = val.robustPcaFlag;
varargin{3} = val.numberOfGaussianMixtures;
dispCommand = true;
end
if narg < 1, varargin{1} = obj.timeStamp([1 end]);end
if ~ismatrix(varargin{1}), error('First argument must be a matrix (n-chunks x 2) with pointers to clean chunks of data.');end
segmentObj = basicSegment(varargin{1});
if narg < 2, varargin{2} = false; end
if ~isnumeric(varargin{2}), error('Second argument must be a either logical or numeric type.');end
robustPcaFlag = varargin{2};
if robustPcaFlag && narg < 3 error('Third argument is the number of gaussians.');end
if robustPcaFlag && narg == 3 && ~isnumeric(varargin{3}), error('Third argument is the number of gaussians.');end
if robustPcaFlag && narg == 3, numberOfGaussianMixtures = varargin{3};end
commandHistory.commandName = 'projectDataPCA';
commandHistory.uuid = obj.uuid;
commandHistory.varargin = varargin;
cobj = obj.copyobj(commandHistory);
if dispCommand
disp('Running:');
disp([' ' cobj.history]);
end
indices = false(1,size(obj,1));
for it=1:length(segmentObj.startLatency), indices = indices | (obj.timeStamp >= segmentObj.startLatency(it) & obj.timeStamp < segmentObj.endLatency(it));end
indices = find(indices(:));
data = obj.dataInXYZ(indices,:,:);
cobj.projectionMatrix = zeros(3,3,cobj.numberOfChannels/length(cobj.componetsToProject));
projectionMatrix = cobj.projectionMatrix;
I = repmat({1:length(indices)},obj.numberOfChannels/3,1);
try
obj.initStatusbar(1,obj.numberOfChannels/3,'Computing PCA rotation matrix...')
for it=1:obj.numberOfChannels/3
%-- getting rid of outliers
if robustPcaFlag, I{it} = rmOutlier(data(:,:,it),numberOfGaussianMixtures);end
%-- estimating canonical axes in 3D
[R1,pc] = princomp(data(I{it},:,it));
%-- estimating rotation on z-axis
[~,loc] = max(corr(pc,data(I{it},:,it)));
z_axis = 3;find(loc==3);
p_axis = setdiff(loc(1:2),z_axis);
p_axis = p_axis(1);
target = data(I{it},[p_axis z_axis],it);
target = bsxfun(@minus,target,mean(target));
[~,~,T] = procrustes(pc(:,1:2),target);
R2 = T.T;
R2(end+1,end+1) = 0; %#ok
R2(end,end) = 1;
%--
if sign(det(R2))==1
projectionMatrix(:,:,it) = R1/R2; % clockwise rotation
else
projectionMatrix(:,:,it) = R1*R2; % counter clock
end
obj.statusbar(it);
end
obj.initStatusbar(1,obj.numberOfChannels/3,'Correcting orientation...')
for it=2:obj.numberOfChannels/3
if sign(det(projectionMatrix(:,:,it)))==1
% projectionMatrix(:,:,it) = inv(projectionMatrix(:,:,it)); % clockwise rotation
projectionMatrix(:,:,it) = projectionMatrix(:,:,1); % clockwise rotation
end
obj.statusbar(it);
end
cobj.projectionMatrix = projectionMatrix;
obj.initStatusbar(1,obj.numberOfChannels/3,'Projecting data...')
for it=1:obj.numberOfChannels/3
pc = data(I{it},:,it)*cobj.projectionMatrix(:,:,it);
pc = bsxfun(@minus,pc,mean(pc));
cobj.dataInXY(indices(I{it}),:,it) = pc(:,1:2);
obj.statusbar(it);
end
catch ME
obj.statusbar(obj.numberOfChannels/3);
try obj.container.deleteItem(obj.container.findItem(cobj.uuid));end %#ok
ME.rethrow;
end
end
%%
function cobj = projectDataOntoCanonicalAxes(obj,plane)
if nargin < 2, error('MoBILAB:noArguments','First argument must be a the axes: ''xy'', ''xz'', ''yz''.');end
if nargin > 1 || isnumeric(plane)
prompt = {'Enter the axes (''xy'',''xz'',''yz'')'};
dlg_title = 'Project data onto canonical axes';
num_lines = 1;
def = {'xz'};
plane = inputdlg2(prompt,dlg_title,num_lines,def);
if isempty(plane), return;end
end
if ~ischar(plane), error('MoBILAB:noArguments','First argument must be a the axes: ''xy'', ''xz'', ''yz''.');end
switch lower(plane)
case 'xy'
R = [1 0 0;0 1 0;0 0 0];
keepComponents = [1 2];
case 'xz'
R = [1 0 0;0 0 0;0 0 1];
keepComponents = [1 3];
case 'yz'
R = [0 0 0;0 1 0;0 0 1];
keepComponents = [2 3];
otherwise
error('MoBILAB:noArguments','First argument must be a the axes: ''xy'', ''xz'', ''yz''.');
end
cobj = projectData(obj,R,keepComponents);
end
%%
function cobj = projectData(obj,R,keepComponents)
if nargin < 2, error('MoBILAB:noArguments','First argument must be a rotation matrix');end
if ~ismatrix(R), error('MoBILAB:noArguments','First argument must be a rotation matrix');end
R = reshape(R,[3 3 length(R)/9]);
if nargin < 3, keepComponents = 1:2;end
if keepComponents < 1 || keepComponents > 3 || length(keepComponents) ~=2, keepComponents = 1:2;end
commandHistory.commandName = 'projectData';
commandHistory.uuid = obj.uuid;
commandHistory.varargin{1} = R;
commandHistory.varargin{2} = keepComponents;
cobj = copyobj(commandHistory);
for it=1:obj.numberOfChannels/3
pc = obj.dataInXYZ(:,:,it)*cobj.projectionMatrix(:,:,it);
pc = bsxfun(@minus,pc,mean(pc));
cobj.dataInXY(I{it},:,it) = pc(:,keepComponents);
end
end
%%
function epochObj = epoching(obj,eventLabelOrLatency, timeLimits, channels, condition,subjectID)
if nargin < 2, error('Not enough input arguments.');end
if nargin < 3, warning('MoBILAB:noTImeLimits','Undefined time limits, assuming [-1 1] seconds.'); timeLimits = [-1 1];end
if nargin < 4, warning('MoBILAB:noChannels','Undefined channels to epoch, epoching all.'); channels = 1:obj.numberOfChannels;end
if nargin < 5, condition = 'unknown';end
if nargin < 6, subjectID = obj.uuid;end
children = obj.children;
if isempty(children)
epochObj = epoching@dataStream(obj,eventLabelOrLatency, timeLimits, channels, condition);
return;
end
[xy,time,eventInterval] = epoching@coreStreamObject(obj,eventLabelOrLatency, timeLimits, channels);
[n,m,p] = size(xy);
xy = squeeze(mean(xy,2));
children = obj.children;
nc = length(children);
if ~isempty(children)
derivativeLabel = cell(nc,1);
data = zeros(n,p*nc,m);
indices = reshape(1:p*nc,[p nc]);
for it=1:nc
data(:,indices(:,it),:) = permute( epoching@coreStreamObject(children{it},eventLabelOrLatency, timeLimits, channels), [1 3 2] );
if ~isempty(strfind(children{it}.name,'vel')), derivativeLabel{it} = 'Velocity';
elseif ~isempty(strfind(children{it}.name,'acc')), derivativeLabel{it} = 'Acceleration';
elseif ~isempty(strfind(children{it}.name,'jerk')), derivativeLabel{it} = 'Jerk';
else derivativeLabel{it} = ['Dt' num2str(it)];
end
end
pdata = zeros([n,nc,m]);
for it=2:nc, pdata(:,it,:) = projectAB(data(:,indices(:,it),:),data(:,indices(:,1),:));end
pdata(:,1,:) = sqrt(sum(data(:,indices(:,1),:).^2,2));
else pdata = [];
end
epochObj = mocapEpoch(pdata,time,obj.label(channels),condition,eventInterval,subjectID,xy,derivativeLabel);
end
function epochObj = epochingTW(obj,latency, channels, condition, subjectID)
if nargin < 2, error('Not enough input arguments.');end
if nargin < 3, warning('MoBILAB:noChannels','Undefined channels to epoch, epoching all.'); channels = 1:obj.numberOfChannels;end
if nargin < 4, condition = 'unknownCondition';end
if nargin < 5, subjectID = obj.uuid;end
if isa(obj,'mocap'), I = reshape(1:obj.numberOfChannels,[2 obj.numberOfChannels/2]);
else I = reshape(1:obj.numberOfChannels,[3 obj.numberOfChannels/3]);
end
channelLabel = cell(length(channels),1);
for it=1:length(channels), channelLabel{it} = num2str(channels(it));end
channels = I(:,channels);
channels = channels(:);
[xy,~,eventInterval] = epochingTW@coreStreamObject(obj,latency, channels);
[n,m,p] = size(xy);
xy = squeeze(mean(xy,2));
children = obj.children;
nc = length(children);
if ~isempty(children)
derivativeLabel = cell(nc,1);
data = zeros(n,p*nc,m);
indices = reshape(1:p*nc,[p nc]);
for it=1:nc
data(:,indices(:,it),:) = permute( epochingTW@coreStreamObject(children{it},latency, channels), [1 3 2] );
if ~isempty(strfind(children{it}.name,'vel')), derivativeLabel{it} = 'Velocity';
elseif ~isempty(strfind(children{it}.name,'acc')), derivativeLabel{it} = 'Acceleration';
elseif ~isempty(strfind(children{it}.name,'jerk')), derivativeLabel{it} = 'Jerk';
else derivativeLabel{it} = ['Dt' num2str(it)];
end
end
pdata = zeros([n,nc,m]);
for it=2:nc, pdata(:,it,:) = projectAB(data(:,indices(:,it),:),data(:,indices(:,1),:));end
pdata(:,1,:) = sqrt(sum(data(:,indices(:,1),:).^2,2));
else pdata = [];
end
if size(latency,1) > 1, dl = round(mean(diff(latency,[],2))); else dl = diff(latency,[],2);end
dlsum = cumsum(dl);
if length(dl) > 3
time = -fliplr(0:dlsum(2))/obj.samplingRate;
time(end) = [];
time = [time (0:dlsum(end) - dlsum(2)-1)/obj.samplingRate];
else
time = -fliplr(0:dlsum(1))/obj.samplingRate;
time(end) = [];
time = [time (0:dlsum(2) - dlsum(1)-1)/obj.samplingRate];
end
epochObj = mocapEpoch(pdata,time,channelLabel,condition,eventInterval,subjectID,xy,derivativeLabel);
end
%%
function addEventsFromDerivatives(obj,varargin)
% Adds all events from time derivative streams (vel, acc, jerk, DtX) of this stream into this stream. Mostly
% to be used for visually inspecting movement on and offset event markers
%
% Input arguments:
% none
%
% Output argument:
% none. The events will be saved in the present data set.
%
% Uses:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% mocapObj.addEventsFromDerivatives();
disp('Running:');
disp('obj.addEventsFromDerivatives()');
for children = 1:size(obj.children,2)
if ~isempty(strfind(obj.children{children}.name,'vel')) ||...
~isempty(strfind(obj.children{children}.name,'acc')) ||...
~isempty(strfind(obj.children{children}.name,'jerk')) ||...
~isempty(strfind(obj.children{children}.name,'Dt'))
derivativeEvent = obj.children{children}.event;
obj.event = obj.event.addEvent(derivativeEvent.latencyInFrame,derivativeEvent.label);
end
end
end
%%
function deleteMarkers(obj,varargin)
% Removes event markers in the stream. Optionally keeps specified markers.
%
% Input arguments:
% markersToKeep: (OPTIONAL) Cell array of markers that should be kept in the data stream.
%
% Output argument:
% none. The events will be saved in the present data set.
%
% Uses:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% mocapObj.deleteMarkers();
% mocapObj.deleteMarkers(markersToKeep);
dispCommand = false;
if ~isempty(varargin) && iscell(varargin) && isnumeric(varargin{1}) && varargin{1} == -1
prompt = {'Which markers to keep?'};
dlg_title = 'Input parameters';
num_lines = 1;
def = {''};
markersToKeep = inputdlg2(prompt,dlg_title,num_lines,def);
if isempty(varargin), return;end
markersToKeep = strsplit(markersToKeep{1}, ' ');
dispCommand = true;
else
if ~isempty(varargin)
markersToKeep = varargin{1};
else
markersToKeep = {''};
end
end
command = 'Delete Markers, keep only:';
for marker = 1:numel(markersToKeep)
command = strcat(command, {' '}, markersToKeep(marker));
end
if dispCommand
disp('Running:');
disp(command);
end
% determine for each unique marker if it is of the markers to keep or not
if ~isempty(obj.event.uniqueLabel)
for uniqueLabelInd = 1:size(obj.event.uniqueLabel,1)