forked from sccn/mobilab
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mocapRigidBody.m
2167 lines (1889 loc) · 107 KB
/
mocapRigidBody.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
%% mocapRigidBody 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 mocapRigidBody < 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 = mocapRigidBody(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)
% Adds channels to the data stream. Channels will be appended automatically at the end.
%
% Input arguments:
% channelLabels: A cell containing strings for labels of the additional channels
% data: a matrix for the new channels.
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% newMocapObj = mocapObj.addChannels(channelLabels, dataMatrix);
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 = degToRad(obj,varargin)
% Converts data channels from degree to radian (rad = deg / 180 * pi), mostly for better visualization in the same plot since the
% scale is similar to the position then.
%
% Input arguments:
% channels
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% newMocapObj = mocapObj.degToRad(channelsToConvert);
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 channels to convert!'};
dlg_title = 'Input parameters';
num_lines = 1;
def = {''};
channelsToConvert = inputdlg2(prompt,dlg_title,num_lines,def);
varargin{1} = str2num(channelsToConvert{1});
if isempty(varargin), return;end
dispCommand = true;
end
commandHistory.commandName = 'degToRad';
commandHistory.uuid = obj.uuid;
commandHistory.varargin{1} = varargin{1};
cobj = obj.copyobj(commandHistory);
cobj.mmfObj.Data.x = obj.mmfObj.Data.x;
if dispCommand
disp('Running:');
disp([' ' cobj.history]);
end
cobj.mmfObj.Data.x(:,varargin{1}) = cobj.mmfObj.Data.x(:,varargin{1}) / 180 * pi;
end
%%
function cobj = unflipSigns(obj,varargin)
% Heuristic for unflipping the sign of quaternion values to anable filtering. Quaternions can represent the
% same value two ways, whereas only the sign changes. Sometimes the representation flips in the time series.
% If this gets filtered, it creates an artifact, so this is why we want to unflip it first. It won't make a
% difference later when transforming the values to Euler angles.
% The principle idea is to check if the difference between consecutive values becomes smaller if we flip them.
%
% Input arguments:
% none.
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% newMocapObj = mocapObj.unflipSigns();
for channel = 1:obj.numberOfChannels
% checking for already present eulers
if ~isempty(strfind(lower(obj.label{channel}),'euler'))
error('You can only unflip Quaternions, try it with the original data set.')
end
end
commandHistory.commandName = 'unflipSigns';
commandHistory.uuid = obj.uuid;
cobj = obj.copyobj(commandHistory);
data = obj.mmfObj.Data.x;
disp('Running:');
disp([' ' cobj.history]);
% find correct channelnumber for the quaternion values of
% this RB
quaternionX = ~cellfun(@isempty,strfind(lower(obj.label),'quat_x'));
quaternionY = ~cellfun(@isempty,strfind(lower(obj.label),'quat_y'));
quaternionZ = ~cellfun(@isempty,strfind(lower(obj.label),'quat_z'));
quaternionW = ~cellfun(@isempty,strfind(lower(obj.label),'quat_w'));
% take the values
X = data(:,quaternionX);
Y = data(:,quaternionY);
Z = data(:,quaternionZ);
W = data(:,quaternionW);
for dataPoint = 5:size(data,1)
epsilon = 0.5;
Adiff = abs(X(dataPoint-1) - X(dataPoint));
Adiff2 = abs(X(dataPoint-2) - X(dataPoint-1));
Adiff3 = abs(X(dataPoint-3) - X(dataPoint-2));
Adiff4 = abs(X(dataPoint-4) - X(dataPoint-3));
AsumOfPreviousDiffs = Adiff2 + Adiff3 + Adiff4;
AflippedDataPoint = -X(dataPoint);
AdiffFlipped = abs(X(dataPoint-1) - AflippedDataPoint);
AconditionMet = AdiffFlipped<Adiff;% & Adiff > AsumOfPreviousDiffs;
AbigJump = AdiffFlipped> 0.5;
Bdiff = abs(Y(dataPoint-1) - Y(dataPoint));
Bdiff2 = abs(Y(dataPoint-2) - Y(dataPoint-1));
Bdiff3 = abs(Y(dataPoint-3) - Y(dataPoint-2));
Bdiff4 = abs(Y(dataPoint-4) - Y(dataPoint-3));
BsumOfPreviousDiffs = Bdiff2 + Bdiff3 + Bdiff4;
BflippedDataPoint = -Y(dataPoint);
BdiffFlipped = abs(Y(dataPoint-1) - BflippedDataPoint);
BconditionMet = BdiffFlipped<Bdiff;% & Bdiff > BsumOfPreviousDiffs;
BbigJump = BdiffFlipped> epsilon;
Cdiff = abs(Z(dataPoint-1) - Z(dataPoint));
Cdiff2 = abs(Z(dataPoint-2) - Z(dataPoint-1));
Cdiff3 = abs(Z(dataPoint-3) - Z(dataPoint-2));
Cdiff4 = abs(Z(dataPoint-4) - Z(dataPoint-3));
CsumOfPreviousDiffs = Cdiff2 + Cdiff3 + Cdiff4;
CflippedDataPoint = -Z(dataPoint);
CdiffFlipped = abs(Z(dataPoint-1) - CflippedDataPoint);
CconditionMet = CdiffFlipped<Cdiff;% & Cdiff > CsumOfPreviousDiffs;
CbigJump = CdiffFlipped> epsilon;
Ddiff = abs(W(dataPoint-1) - W(dataPoint));
Ddiff2 = abs(W(dataPoint-2) - W(dataPoint-1));
Ddiff3 = abs(W(dataPoint-3) - W(dataPoint-2));
Ddiff4 = abs(W(dataPoint-4) - W(dataPoint-3));
DsumOfPreviousDiffs = Ddiff2 + Ddiff3 + Ddiff4;
DflippedDataPoint = -W(dataPoint);
DdiffFlipped = abs(W(dataPoint-1) - DflippedDataPoint);
DconditionMet = DdiffFlipped<Ddiff;% & Ddiff > DsumOfPreviousDiffs;
DbigJump = DdiffFlipped> epsilon;
if (AconditionMet+BconditionMet+CconditionMet+DconditionMet >= 2 && AbigJump+BbigJump+CbigJump+DbigJump == 0)
X(dataPoint) = -X(dataPoint);
Y(dataPoint) = -Y(dataPoint);
Z(dataPoint) = -Z(dataPoint);
W(dataPoint) = -W(dataPoint);
end
end
data(:,quaternionX) = X;
data(:,quaternionY) = Y;
data(:,quaternionZ) = Z;
data(:,quaternionW) = W;
% end
cobj.mmfObj.Data.x = data;
end
%%
function cobj = switchCoordinateSystem(obj,varargin)
% switches between a left- and right hand sided coordinate system. Necessary if your VR system or one of the
% mocap systems has a flipped axis. Basically just flips the sign of left/right. Skip this if you don't have
% any issues!
%
% Input arguments:
% none.
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% newMocapObj = mocapObj.switchCoordinateSystem();
% make new object
commandHistory.commandName = 'switchCoordinateSystem';
commandHistory.uuid = obj.uuid;
cobj = obj.copyobj(commandHistory);
disp('Running:');
disp([' ' cobj.history]);
data = obj.mmfObj.Data.x;
% now fill with data
for channel = 1:obj.numberOfChannels
if ~isempty(strfind(lower(obj.label{channel}),'rigid_z')) ||...
~isempty(strfind(lower(obj.label{channel}),'pos_z')) ||...
~isempty(strfind(lower(obj.label{channel}),'quat_x')) ||...
~isempty(strfind(lower(obj.label{channel}),'quat_y')) ||...
~isempty(strfind(lower(obj.label{channel}),'euler_yaw')) ||...
~isempty(strfind(lower(obj.label{channel}),'euler_pitch'))
data(:,channel) = data(:,channel) .* -1;
end
end
cobj.mmfObj.Data.x = data;
end
%%
function cobj = quaternionsToEuler(obj,varargin)
% Transforms Quaternion angle values (4 dimensions) into Euler angles (3 dimensions yaw, pitch, roll) to
% make them human-interpretable. Quat values will be taken out, and Euler angles will be assigned as new channels
%
% Input arguments:
% none.
%
% Output argument:
% cobj: handle to the new object
%
% Usage:
% mocapObj = mobilab.allStreams.item{ mocapItem };
% newMocapObj = mocapObj.quaternionsToEuler();
for channel = 1:obj.numberOfChannels
% checking for already present eulers
if ~isempty(strfind(lower(obj.label{channel}),'euler'))
error('Don''t try to convert to Euler twice... that''s kinda obvious, isn''t it?')
end
end
% no eulers are present, therefore each RB has 7 channels:
% XYZABCD, from which ABCD are the quaternion values
data = obj.mmfObj.Data.x;
newData = zeros(size(obj.mmfObj.Data.x,1),0);
newLabel = cell(0,1);
% the new Euler data has 1 channel less than the quaternions
% fill the new data set and its label with all initial position data
non_quat_indices = cellfun(@isempty,strfind(lower(obj.label),'quat'));
newLabel(1:sum(non_quat_indices)) = obj.label(non_quat_indices);
newData(:,1:sum(non_quat_indices)) = obj.mmfObj.Data.x(:,non_quat_indices);
% fill also with additional data if there are more channels
% than just 7
%
% numberOfExcessChannels = obj.numberOfChannels - 7;
%
% if numberOfExcessChannels > 0
%
% newLabel(7:(7+numberOfExcessChannels-1)) = obj.label(8:(7+numberOfExcessChannels));
% newData(:,7:(7+numberOfExcessChannels-1)) = obj.mmfObj.Data.x(:,8:(7+numberOfExcessChannels));
%
% end
% now fill with euler data
quat_indices = ~cellfun(@isempty,strfind(lower(obj.label),'quat'));
assert(sum(quat_indices)==4,'There must be exactly 4 quaternion channels containing the label ''quat_<x,y,z,w>''!')
% find correct channelnumber for the quaternion values of
% this RB
quaternionX = ~cellfun(@isempty,strfind(lower(obj.label),'quat_x'));
assert(sum(quaternionX)==1,'There must be exactly 1 quaternion channel containing the label ''quat_x''!')
quaternionY = ~cellfun(@isempty,strfind(lower(obj.label),'quat_y'));
assert(sum(quaternionY)==1,'There must be exactly 1 quaternion channel containing the label ''quat_y''!')
quaternionZ = ~cellfun(@isempty,strfind(lower(obj.label),'quat_z'));
assert(sum(quaternionZ)==1,'There must be exactly 1 quaternion channel containing the label ''quat_z''!')
quaternionW = ~cellfun(@isempty,strfind(lower(obj.label),'quat_w'));
assert(sum(quaternionW)==1,'There must be exactly 1 quaternion channel containing the label ''quat_w''!')
% take the values
% The orientation axes' labels in PhaseSpace are different from the
% ones in Wikipedia: Forward is z (Wikipedia x), sideways is x (Wikipedia y), upways is
% y (Wikipedia z)
z = data(:,quaternionX);
x = data(:,quaternionY);
y = data(:,quaternionZ);
w = data(:,quaternionW);
% check if values are [-1 1] - could have been messed up by
% interpolating
w(w>=1) = 0.99999;
w(w<=-1) = -0.99999;
x(x>=1) = 0.99999;
x(x<=-1) = -0.99999;
y(y>=1) = 0.99999;
y(y<=-1) = -0.99999;
z(z>=1) = 0.99999;
z(z<=-1) = -0.99999;
% transform those values to euler angles
% see https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
% the rotation occurs in the order yaw, pitch, roll (about body-fixed axes).
% now since we took the different axes for the quaternions
% before, this has to be taken backwards to obtain the
% correct values for yaw, pitch and roll
% -> this means that roll (rotation about x) becomes yaw, pitch (rotation about y) becomes
% roll and yaw (rotation about z) becomes pitch.
% for some reason after filtering the quaternion values, it
% can happen that the transformation below results in
% complex numbers, whereas the real part is exactly pi (or
% -pi) and the complex number has some kind of "excess"
% value. I don't know why this happens, but I just take the
% real part, since it's the most reasonable thing to do, I
% guess...
channelEulerYaw = real(atan2(2.*(w.*x + y.*z),1 - 2.*(x.^2 + y.^2))); % wikipedia roll (rotation about x)
channelEulerRoll = real(asin(2.*(w.*y - z.*x))); % wikipedia pitch (rotation about y)
channelEulerPitch = real(atan2(2.*(w.*z + x.*y),1-2.*(y.^2+z.^2))); % wikipedia yaw (rotation about z)
% convert from radian to degree
factor = 180/pi;
channelEulerYaw = channelEulerYaw*factor;
channelEulerRoll = channelEulerRoll*factor;
channelEulerPitch = channelEulerPitch*factor;
% actually fill new data set and labels
newData(:,end+1) = channelEulerYaw;
newData(:,end+1) = channelEulerPitch;
newData(:,end+1) = channelEulerRoll;
% take the original prefix before 'quat_x' as a prefix for all new euler channels
newLabel{end+1} = strcat(obj.label{4}(1:strfind(lower(obj.label{4}),'quat_x')-1),'euler_yaw');
newLabel{end+1} = strcat(obj.label{4}(1:strfind(lower(obj.label{4}),'quat_x')-1),'euler_pitch');
newLabel{end+1} = strcat(obj.label{4}(1:strfind(lower(obj.label{4}),'quat_x')-1),'euler_roll');
% make new object
commandHistory.commandName = 'quaternionsToEuler';
commandHistory.uuid = obj.uuid;
commandHistory.newLabels = newLabel;
cobj = obj.copyobj(commandHistory);
disp('Running:');
disp([' ' cobj.history]);
cobj.mmfObj.Data.x = newData;
cobj.label = newLabel;
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; % one of the quaternion channels is 1 if occluded
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)};
def = {num2str(3)};
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 G?ry 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 Quaternionvalues
if sum(~cellfun('isempty',strfind(obj.label,'_A')))>0, error('Please transform quaternion values to euler angles 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(lower(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);