-
Notifications
You must be signed in to change notification settings - Fork 5
/
mcrecovery.m
1365 lines (1184 loc) · 50.3 KB
/
mcrecovery.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
function [filledsequence] = mcrecovery(mysequence, options)
%{
Created by Mickaël Tits, numediart Institute, University of Mons, Belgium
21/12/2017
Contact: [email protected] or [email protected]
Inputs :
- mysequence: MoCap data structure from the MoCap Toolbox
- options: optional structure, containing various optional fields:
*binary (0 = no, any other value = yes):
- verbose: print/display debug information. (default: 0)
- quiet: nothing is printed/displayed (override verbose). (default: 0)
- method1 to method5: specify any individual recovery method to use.
(default: all to 1). As soon as a methodx parameter is specified in the
options, other methods are set to 0.
o method1: local interpolation
o method2: local polynomial regression
o method3: local GRNN
o method4: global linear regression
o method5: weighted PCA (Gloersen et al. 2016 PLoS One)
- spaceconstraint: use space constraint. (default: 1)
- tripleconstraint: use space constraint with 3 neighbours. If 0, only
the distance with the first neighbour is considered. (default: 1)
- timeconstraint: use time constraint. (default: 1)
- recursivefilling: each filled trajectory can be used for
reconstruction of the next trajectory to fill (markers with smallest
gaps are reconstructed first). (default: 1)
- filtering: filter input data before process, and filter and recovered data
(median and average symmetric sliding adaptive windows). (default: 1)
- filterref: filter local references. (default: 1)
- saveastsv: save recovered sequence as tsv file. (default: 0)
- advancedordering: (under development) order possible references both
considering maximal windowed standard deviation, and maximal distance (default:
0)
- advancedorderingweight: (under development) weight to ponderate
either windowed standard deviation, or maximal distance criteria for
ordering references (default: 20). Not used if advancedordering = 0.
The bigger it is, the more we consider maximal windowed standard deviation over
maximal distance
*other:
- fps: use this parameter if no fps is indicated in the MoCap data
structure (mysequence). (default: 30)
- window: filters sliding window size. Note that
full-body motion useful information is generally below 10-20Hz. Finer
movement may need a higher rate (e.g. finger movements). (default: 0.07)
- presenceMin [0 - 100]: markers less present than presenceMin (in percent of
available frames) are removed from the sequence before the process.
(default: 30)
- threhsold: threshold on the distance variation (standard deviation) between the
marker to fill and a potential reference. If the standard deviation >
threshold, the reference is not valid for reconstruction. It can be
used to avoid unreliable recovery. (default: inf)
- combined_threshold: threshold on the summed distance variation (standard deviation)
between the marker to fill and three potential references. If the sum of the standard
deviations > combined_threshold, the references are not valid together for
reconstruction. (default: inf)
- smooth: smoothing parameter for grnn regression (default: 0.3)
- weightThres: weight threshold parameter for global linear regression
method (default: 50 mm)
Output: recovered sequence
%}
%%% Parameters %%%
if nargin < 2
options = [];
end
%if verbose = 1, debug information is printed/displayed on the process.
% (default: 0)
if isfield(options,'verbose') && isnumeric(options.verbose)
verbose = options.verbose;
else
verbose = 0;
end
%if quiet = 1, nothing is printed
% (default: 0)
if isfield(options,'quiet') && isnumeric(options.quiet)
quiet = options.quiet;
else
quiet = 0;
end
if quiet
verbose = 0;
end
% methods to use for gap recovery (put 0 to avoid the method).
%By default, we use all methods
% method1 : local interpolation
if isfield(options,'method1') && isnumeric(options.method1)
method1 = options.method1;
else
method1 = 0;
end
% method2 : local polynomial regression
if isfield(options,'method2') && isnumeric(options.method2)
method2 = options.method2;
else
method2 = 0;
end
% method3 : local GRNN
if isfield(options,'method3') && isnumeric(options.method3)
method3 = options.method3;
else
method3 = 0;
end
% method4 : global weighted linear regression
if isfield(options,'method4') && isnumeric(options.method4)
method4 = options.method4;
else
method4 = 0;
end
% method5 : Gloersen (PCA-based method)
if isfield(options,'method5') && isnumeric(options.method5)
method5 = options.method5;
else
method5 = 0;
end
% spaceconstraint : if ~= 0, soft constraint on distance of marker to fill with
% closest neighbours
% (default: 1)
if isfield(options,'spaceconstraint') && isnumeric(options.spaceconstraint)
spaceconstraint = options.spaceconstraint;
else
spaceconstraint = 1;
end
% tripleconstraint : if ~= 0, soft constraint on distance of marker to fill with
% 3 closest neighbours (otherwise 1 neighbour only).
% (default: 1)
if isfield(options,'tripleconstraint') && isnumeric(options.tripleconstraint)
tripleconstraint = options.tripleconstraint;
else
tripleconstraint = 1;
end
% timeconstraint : if ~= 0, linear ramp correction to force trajectory
% time continuity
% (default: 1)
if isfield(options,'timeconstraint') && isnumeric(options.timeconstraint)
timeconstraint = options.timeconstraint;
else
timeconstraint = 1;
end
%recursivefilling : if ~= 0, each filled trajectory can be used for
%reconstruction of the next trajectory to fill (markers with smallest gaps
%are reconstructed first)
% (default: 1)
if isfield(options,'recursivefilling') && isnumeric(options.recursivefilling)
recursivefilling = options.recursivefilling;
else
recursivefilling = 1;
end
if isfield(options,'advancedordering') && isnumeric(options.advancedordering)
advancedordering = options.advancedordering;
else
advancedordering = 0;
end
if isfield(options,'advancedorderingweight') && isnumeric(options.advancedorderingweight)
advancedorderingweight = options.advancedorderingweight;
else
advancedorderingweight = 20;
end
%if no method is selected, use all of them (default)
if method1+method2+method3+method4+method5 == 0
if verbose
warning('No method indicated in sequence or in options. Default value is taken instead.');
end
method1=1;
method2=1;
method3=1;
method4=1;
method5=1;
end
%filter the sequence before filling (median and average symmetric sliding windows)
if isfield(options,'filtering')
filtering = options.filtering;
else
if verbose
warning('No filtering parameter indicated in sequence or in options. Default value is taken instead.');
end
filtering = 1;
end
%filter references or not for local reconstruction (median and average symmetric sliding windows)
if isfield(options,'filterref')
filterref = options.filterref;
else
if verbose
warning('No filterref parameter indicated in sequence or in options. Default value is taken instead.');
end
filterref = 1;
end
if isfield(mysequence,'freq')
fps = mysequence.freq;
elseif isfield(options,'fps') && isnumeric(options.fps)
fps = options.fps;
else
if verbose && (filtering || filterref)
warning('No fps indicated in sequence or in options (it is needed for filtering). Default value is taken instead.');
end
fps = 30;
end
if isfield(options,'window')
window = options.window;
else
if verbose && (filtering || filterref)
warning('No window parameter indicated in sequence or in options (it is needed for filtering). Default value is taken instead.');
end
window = 0.07;
end
% markers less present than presenceMin (in % of present frames) are removed
% from the sequence before the process
if isfield(options,'presenceMin') && isnumeric(options.presenceMin)
presenceMin = options.presenceMin;
else
presenceMin = 30;
end
if presenceMin < 0
warning('Invalid presenceMin parameter');
presenceMin = 0;
elseif presenceMin >= 100
warning('Invalid presenceMin parameter');
presenceMin = 0;
end
% threshold on the distance variation (standard deviation) between the
% marker to fill and a potential reference. If the standard deviation >
% threshold, the reference is not valid for reconstruction. (default: inf)
if isfield(options,'threshold') && isnumeric(options.threshold)
threshold = options.threshold;
else
threshold = inf;
end
% threshold on the summed distance variation (standard deviation) between the
% marker to fill and three potential references. If the sum of the standard
% deviations > combined_threshold, the references are not valid together for
% reconstruction. (default: inf)
if isfield(options,'combined_threshold') && isnumeric(options.combined_threshold)
combined_threshold = options.combined_threshold;
else
combined_threshold = inf;
end
%if saveastsv = 1, the recovered motion is saved in a .tsv file.
% (default: 0)
if isfield(options,'saveastsv') && isnumeric(options.saveastsv)
saveastsv = options.saveastsv;
else
saveastsv = 0;
end
%smoothing parameter for grnn method (default: 0.3)
if isfield(options,'smooth') && isnumeric(options.smooth)
smooth = options.smooth;
else
smooth = 0.3;
end
%weight threshold parameter for global linear regression method (default: 50 mm)
if isfield(options,'weightThres') && isnumeric(options.weightThres)
weightThres = options.weightThres;
else
weightThres = 50;
end
%% First check if there are missing data
[~, ~, mgrid] = mcmissing(mysequence);
if mean(mean(mgrid))==0
%No missing data!
filledsequence = mysequence;
if ~quiet
disp('There are no missing data in this sequence');
end
if saveastsv
mcwritetsv2(filledsequence);
end
return;
end
%% Remove markers with too many missing frames
absence=mean(mgrid);
presence=(1-absence)*100;
idx = 1:mysequence.nMarkers;
markers = idx(presence>=presenceMin);
if ~quiet
fprintf('Minimum presence: %.1f%%\n', min(presence));
if size(markers) < mysequence.nMarkers
fprintf('----WARNING----: Some markers have less than %.1f%% presence and are thus removed from the sequence!\n', presenceMin);
end
end
initialsequence = mysequence;
mysequence = mcgetmarker(mysequence,markers);
%% Initialize process
mysequence.nFrames=size(mysequence.data,1);
missing = mcviewmissing(mysequence,verbose);%Diagnosis
presence=presence(markers);
name = mysequence.markerName;
x = mysequence.data;
nframes = size(x,1);
nmarkers = mysequence.nMarkers;
%% Filter data
unfiltered = mysequence;
if filtering
% for m = 1:mysequence.nMarkers
% mysequence.data(:,(3*m-2):3*m) = symfilter(mysequence.data(:,(3*m-2):3*m),ceil(window*fps));
% end
mysequence.data = symfilter(mysequence.data,ceil(window*fps));
end
%% Subtract average marker trajectory (to obtain a coordinate system moving with the subject)
cols_with_nans = any(isnan(x),1);
x_nonnan = x;
x_nonnan(:,cols_with_nans)=[];
%Center of mass of markers always presents
com.x = mean(x_nonnan(:,1:3:end),2);
com.y = mean(x_nonnan(:,2:3:end),2);
com.z = mean(x_nonnan(:,3:3:end),2);
x(:,1:3:end) = bsxfun(@minus,x(:,1:3:end),com.x);%x(:,1:3:end) - com.x %(for newer versions)
x(:,2:3:end) = bsxfun(@minus,x(:,2:3:end),com.y);
x(:,3:3:end) = bsxfun(@minus,x(:,3:3:end),com.z);
mysequence.data = x;
%% Compute 3D distances variations (standard deviation)
%Calculate distance on downsampled data for speed considerations (let's take maximum
%5000 frames randomly in data)
subsampled = mysequence;
%Keep only frames without nans
tmpdata = mysequence.data;
nanframes = any(isnan(tmpdata),2);
if size(tmpdata,1) - sum(nanframes) > 300 %Verify if we have still a sufficient number of frames
tmpdata(nanframes,:) = [];
end
NF = min(size(tmpdata,1),5000);
randframes = randperm(size(tmpdata,1));
randframes=randframes(1:NF);
subsampled.data=tmpdata(randframes,:);
subsampled.nFrames=size(subsampled.data,1);
distances = inf(nmarkers,nmarkers);%inf avoids to reconstruct a marker with itself as reference
for i=1:nmarkers
for j=(i+1):nmarkers
distance = mcmarkerdist(subsampled,i,j);
if ~advancedordering
distances(i,j) = nanstd(distance);
else
%maximal distance
maxdist = max(distance);
%maximal windowed standard deviation (to consider the std only
%during movement)
stddist = max(movstd(distance,min(250,NF/2),'omitnan'));
%manual weighted combination of both criteria...
distances(i,j) = maxdist + advancedorderingweight*stddist;
end
distances(j,i) = distances(i,j);
end
end
if verbose
figure;
imagesc(distances);colorbar();title('Standard deviation of distance between markers');
end
[dev,refs] = sort(distances);
if verbose
figure;
imagesc(dev);colorbar();title('Standard deviation of distance between markers (sorted)');
end
% refs are the markers that are the most linked to the marker to
% reconstruct (based on sorted distances stds for each marker).
% They are linked if the standard deviation of their distance if low (less variable
% distance). Two markers on the same segment will have a low distance std,
% but a marker on a foot and a marker on a hand will generally have a very large
% distance std.
%% Fill gaps
%Only process markers with gaps (nans)
miss = mcnumbers(name,missing)';
%Order then by presence before gap-filling (fill most present first)
[~,order] = sort(presence(miss),'descend');
miss=miss(order);
xfilled = x;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Gloersen (PCA-based method)
if method5
try
gloersen = PredictMissingMarkers_Edited(x,'Algorithm',2);
catch
warning('PCA-Gloersen method (5) failed and will be ignored for reconstruction');
gloersen = x;
if method1+method2+method3+method4 == 0
warning('No other method than PCA-Gloersen (5) was selected. Reconstruction is thus not possible');
warning('Consider using another method...');
filledsequence = mysequence;
return;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Fill each missing marker
for k=miss
%Extract signal
P0=mcgetmarker(mysequence,k);
P0filled = P0;
linregfilled = P0;
gloersenfilled = P0;
p0 = P0.data;
p0filled = P0filled.data;
%Indexes of valid references for reconstruction
validref=refs(1:end-1,k); %last one is the signal to reconstruct itself
%Corresponding distance deviations of the valid references
deviations = dev(1:end-1,k);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Gloersen - continuity correction
if method5
gloersenfilled.data = gloersen(:,3*k-2:3*k);
%continuity correction
absence = isnan(P0.data(:,1))';
%Search gaps
begs=strfind(absence,[0 1])+1; %gaps first frames
if absence(1)==1
begs = [1 begs]; %in case gap at the beginning of the sequence
end
lasts=strfind(absence,[1 0]); %gaps last frames
if absence(end)==1
lasts = [lasts size(absence,2)]; %in case gap at the end on the sequence
end
lborders=begs-1; %gaps left borders
lborders(lborders==0)=1; %in case gap at the beginning of the sequence
rborders=lasts+1; %gaps right borders
rborders(rborders>nframes)=P0.nFrames; %in case gap at the end on the sequence
ngaps = size(lasts,2);
temp = gloersenfilled.data;
%Continuity correction for each gap
if timeconstraint
for g=1:ngaps
id0=lborders(g); %left border
id1=rborders(g); %right border
gapsize = id1-id0-1;
t1=lborders(g)+1;
t2=rborders(g)-1;
for ax=1:3
if id0 == 1 %left extremity
Dt1 = 0; %no correction
else
Dt1 = temp(t1,ax)-p0(t1-1,ax);
end
if id1 == nframes
Dt2 = 0; %no correction
else
Dt2 = temp(t2,ax)-p0(t2+1,ax);
end
if id0 == 1 && id1 ~= nframes
Dt1 = Dt2;
elseif id1 == nframes && id0 ~= 1
Dt2 = Dt1;
end
correction = -linspace(Dt1,Dt2,gapsize+2)'; %linear ramp correction
temp(t1:t2,ax) = temp(t1:t2,ax)+correction(2:end-1);
end
end
gloersenfilled.data = temp;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Global linear regression (on all present markers)
if method4
while true %break when trajectory is filled
absence = isnan(linregfilled.data(:,1))';
if mean(absence)==1 %empty marker trajectory, no filling possible
break;
end
if sum(absence)==0 %trajectory is filled!
break;
end
%Search gaps to fill with interpolated values
begs=strfind(absence,[0 1])+1; %gaps first frames
if absence(1)==1
begs = [1 begs]; %in case gap at the beginning of the sequence
end
lasts=strfind(absence,[1 0]); %gaps last frames
if absence(end)==1
lasts = [lasts size(absence,2)]; %in case gap at the end on the sequence
end
lborders=begs-1; %gaps left borders
lborders(lborders==0)=1; %in case gap at the beginning of the sequence
rborders=lasts+1; %gaps right borders
rborders(rborders>nframes)=P0.nFrames; %in case gap at the end on the sequence
%For each gap, check number of other markers that are present
ngaps = size(lasts,2);
presentDuringGaps=cell(ngaps,1);
npresent = zeros(ngaps,1);
for j=1:ngaps
id0=lborders(j); %left border
id1=rborders(j); %right border
gapsequence = mctrim(mysequence,id0,id1,'frame');
tmp = gapsequence.data(:,1:3:end);
tmp = ~isnan(tmp);
presentDuringGaps{j} = mean(tmp)==1;
npresent(j) = sum(presentDuringGaps{j});
end
%Fill gaps with the most other present markers to recover them
[nmarkers,gapidx]=max(npresent);
if nmarkers <= 3 %not enough markers for regression
break;
end
%Check if these markers are valid to fill several gaps
refset = presentDuringGaps{gapidx};
gapstofill = [gapidx];
for j=1:ngaps
if j ~= gapidx && isequal(refset, presentDuringGaps{j})
gapstofill = [gapstofill j];
end
end
%Regression
refidx = find(refset);
tmp = mcgetmarker(mysequence,refidx);
X = tmp.data;
linpredictor = [ ones(nframes,1) X];
%Ponderate predictors according to distance variability
weights = distances(k,refset);
if min(weights) > weightThres
weights = ones(size(weights));
end
weights = [1 reshape([1 1 1]'*weights,1,[])];
avoidids = weights > weightThres;
linpredictor(:,avoidids)=[];
regressand = p0;
%remove nan frames for training
nonnans = ~(isnan(regressand(:,1)) | any(isnan(linpredictor),2));
regressand = regressand(nonnans,:);
nonnanlinpredictor = linpredictor(nonnans,:);
nonnanframes = size(regressand,1);
% nmaxframes frames should be sufficient to train marker movement model
nmaxframes = 500;
if nonnanframes < nmaxframes
ids=1:nonnanframes;
elseif nonnanframes >= nmaxframes && nonnanframes < 2*nmaxframes
%Take random frames sample to accelerate process
ids = randperm(nonnanframes);
ids=ids(1:nmaxframes);
ids=sort(ids);
elseif nonnanframes >= 2*nmaxframes
%Downsample to accelerate process
down = floor(nonnanframes/nmaxframes);
ids=1:down:nonnanframes;
end
%%% Sampled data for training (faster)
%Predictors
predictors = nonnanlinpredictor(ids,:);%subsample
%Regressands
regressands = regressand(ids,:);
[regressands, mu, sigma] = featureNormalize(regressands);
p0pred=zeros(size(p0));
for ax=1:3
regressand = regressands(:,ax);
warning('off');
coeffs = regress(regressand,predictors);
warning('on');
pred = linpredictor*coeffs;
pred=pred*sigma(ax)+mu(ax);
p0pred(:,ax)=pred;
%Continuity correction
if timeconstraint
for g=gapstofill
t1=lborders(g)+1;
t2=rborders(g)-1;
id0=lborders(g);
id1 = rborders(g);
gapsize = id1-id0-1;
if id0 == 1 %left extremity
Dt1 = 0; %no correction
else
Dt1 = p0pred(t1-1,ax)-p0(t1-1,ax);
end
if id1 == nframes
Dt2=0; %no correction
else
Dt2 = p0pred(t2+1,ax)-p0(t2+1,ax);
end
if id0 == 1 && id1 ~= nframes
Dt1 = Dt2;
elseif id1 == nframes && id0 ~= 1
Dt2 = Dt1;
end
correction = -linspace(Dt1,Dt2,gapsize+2)'; %linear ramp correction
p0pred(id0:id1,ax) = p0pred(id0:id1,ax)+correction;
end
end
end
for g=gapstofill
%fill gap
id0 = lborders(g);
id1=rborders(g);
linregfilled.data(id0:id1,:) = p0pred(id0:id1,:);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Local projection based methods
%Fill with each reference UNTIL completely filled (see break in the loop)
while(size(validref,1) >= 3) %We need at least 3 points for local projection
if any(isnan(p0filled(:)))==0
%Completely filled!
xfilled(:,3*k-2:3*k) = p0filled;
break;
end
P0filled.data = p0filled;
%Search gaps to fill with interpolated values
absence = isnan(p0filled(:,1))';
if mean(absence)==1 %empty marker trajectory, no filling possible
validref=[];
end
begs=strfind(absence,[0 1])+1; %gaps first frames
if absence(1)==1
begs = [1 begs]; %in case gap at the beginning of the sequence
end
lasts=strfind(absence,[1 0]); %gaps last frames
if absence(end)==1
lasts = [lasts size(absence,2)]; %in case gap at the end on the sequence
end
lborders=begs-1; %gaps left borders
lborders(lborders==0)=1; %in case gap at the beginning of the sequence
rborders=lasts+1; %gaps right borders
rborders(rborders>nframes)=P0.nFrames; %in case gap at the end on the sequence
%Look for valid references for local methods
%References are valid if they are present during and around the gaps
%of the signal to reconstruct, and if their distance with the signal is
%almost constant (distance variability < threshold)
%Check reference individual validity
j=0;
for loop=1:size(validref,1)
j=j+1;
if j > size(validref,1)
break;
end
%Check reference presence during and around signal gap
%If they are not present around (on borders), interpolation is
%not possible, and if they are not present at all during, projection
%is not possible (all nans again and we have an infinite loop)
reftmp=mcgetmarker(mysequence,validref(j));
nans=isnan(reftmp.data(:,1))';
absentAroundGaps = nans(lborders) | nans(rborders); %at least one missing data at gap borders (no interpolation possible)
absentDuringGaps=zeros(size(absentAroundGaps));
for i=1:length(begs)
absentDuringGaps(i) = mean(nans(begs(i):lasts(i)))>=1; %no data during gap
end
if mean(absentAroundGaps | absentDuringGaps) >= 1 || deviations(j) > threshold
if verbose
fprintf('Reference marker %d not valid for reconstruction of marker %d.\n', validref(j), k);
end
validref(j)=[]; %remove this marker from valid references
deviations(j)=[];
j=j-1;
end
end
if size(validref,1) < 3
if ~quiet
fprintf('Not enough valid references. Marker %d could not be completely filled.\n', k);
end
xfilled(:,3*k-2:3*k) = p0filled;
break;
end
%Check combined validity (the 3 references must be present at the
%same time, during and around gap, and the global deviation must be small)
refselected = false;
breaking = false;
%Counters storing combinations of references
%We must re-initialize the counters as validref may have changed.
%It should work as previous valid combinations are no
%more valid once used for interpolation
c1=1;
c2=2;
c3=3;
while refselected == false
%Combined presence (0 if present, 1 if absent)
reftmp=mcgetmarker(mysequence,validref(c1));
nans1=isnan(reftmp.data(:,1))';
reftmp=mcgetmarker(mysequence,validref(c2));
nans2=isnan(reftmp.data(:,1))';
reftmp=mcgetmarker(mysequence,validref(c3));
nans3=isnan(reftmp.data(:,1))';
totnans = nans1 | nans2 | nans3;
%Check presence during and around gaps for the combination of
%the three references. They must be valid together at least for
%one gap to be selected
absentAroundGaps = totnans(lborders) | totnans(rborders); %at least one missing data at gap borders (no interpolation possible)
absentDuringGaps=zeros(size(absentAroundGaps));
for i=1:length(begs)
absentDuringGaps(i) = mean(totnans(begs(i):lasts(i)))>=1; %no data during gap
end
totdeviation = deviations(c1)+deviations(c2)+deviations(c3);
totvaliditypergap = absentAroundGaps | absentDuringGaps;
%We need at least one gap valid (at least one 0 in totvaliditypergap) for the three references at the
%same time
if mean(totvaliditypergap) >= 1 || totdeviation > combined_threshold
%This combination of references is not valid
if verbose
fprintf('Not valid references : %d, %d, %d\n', c1,c2,c3);
end
%Try next combination
c3=c3+1;
if c3 > size(validref,1) || deviations(c1)+deviations(c2)+deviations(c3) > combined_threshold
c2=c2+1;
c3=c2+1;
end
if c3 > size(validref,1) || deviations(c1)+deviations(c2)+deviations(c3) > combined_threshold
c1=c1+1;
c2=c1+1;
c3=c2+1;
end
if c3 > size(validref,1) || deviations(c1)+deviations(c2)+deviations(c3) > combined_threshold
% All possible combination tried, exit loop
if ~quiet
fprintf('Not enough valid references. Marker %d could not be completely filled.\n', k);
end
xfilled(:,3*k-2:3*k) = p0filled;
breaking = true;
refselected = true;
end
else
%This combination of references is valid, exit loop
refselected = true;
end
end
if breaking == true
% All possible combination tried
break;
end
%Extract references
r1=validref(c1);
r2=validref(c2);
r3=validref(c3);
P1 = mcgetmarker(mysequence,r1);
P2 = mcgetmarker(mysequence,r2);
P3 = mcgetmarker(mysequence,r3);
p1 = P1.data;
p2 = P2.data;
p3 = P3.data;
%Filter data to avoid noise propagation
if filterref
p0 = symfilter(p0,ceil(window*fps));
p1 = symfilter(p1,ceil(window*fps));
p2 = symfilter(p2,ceil(window*fps));
p3 = symfilter(p3,ceil(window*fps));
end
d1 = sqrt(sum((p1-p0).^2,2));
d2 = sqrt(sum((p2-p0).^2,2));
d3 = sqrt(sum((p3-p0).^2,2));
if ~quiet
fprintf('Reconstructing trajectory %s with references %s, %s and %s\n', name{k}, name{r1}, name{r2}, name{r3});
end
p0p = projection3D(p1, p2, p3, p0filled);
%%% Train regression models
%%% Predictors: local coordinates of P1,P2,P3
d12 = sqrt(sum((p1-p2).^2,2));
%projection of P1 is (zeros, zeros, zeros) (new origin)
%projection of P2 is (d12, zeros, zeros)
%projection of P3 is (P3p_x, 0, P3p_z)
p3p = projection3D(p1, p2, p3, p3);
X=[d12 p3p(:,[1 3])];%
linpredictor = [ ones(nframes,1) featureNormalize(X)];
X=mapFeatureMat(X,2); % polynomial version
polypredictor = [ ones(nframes,1) featureNormalize(X)];
regressand = p0p;
%remove nan frames for training
nonnans = ~(isnan(regressand(:,1)) | any(isnan(linpredictor),2));
regressand = regressand(nonnans,:);
nonnanlinpredictor = linpredictor(nonnans,:);
nonnanpolypredictor = polypredictor(nonnans,:);
nonnanframes = size(regressand,1);
% 2000 frames should be sufficient to train marker movement model
nmaxframes = 1000;
if nonnanframes < nmaxframes
ids=1:nonnanframes;
elseif nonnanframes >= nmaxframes && nonnanframes < 2*nmaxframes
%Take random frames sample to accelerate process
ids = randperm(nonnanframes);
ids=ids(1:nmaxframes);
ids=sort(ids);
elseif nonnanframes >= 2*nmaxframes
%Downsample regressand to accelerate process
down = floor(nonnanframes/nmaxframes);
ids=1:down:nonnanframes;
end
%%% Sampled data for training (faster)
%Predictors
linpredictors = nonnanlinpredictor(ids,:);%subsample
polypredictors = nonnanpolypredictor(ids,:);%subsample
%Regressands
regressands = regressand(ids,:);
[regressands, mu, sigma] = featureNormalize(regressands);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Polynomial regression on local data (3 references) with
% continuity correction - Training
% Used input data: local coordinates of references
coeffs = cell(3,1);
if method2
for ax=1:3 %regression on each axis
regressand = regressands(:,ax);
warning('off');
coeffs{ax} = regress(regressand,polypredictors);
warning('on');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NN regression on local data (3 references) with
% continuity correction - Training
if method3
net = newgrnn(linpredictors',regressands',smooth);
end
%%% Estimate probability density function of d1, d2 and d3
%(200 points should be enough)
nmaxframes = 500;
nonnans = ~isnan(d1);
d1bis = d1(nonnans);
if length(d1bis) > nmaxframes
d1bis = d1bis(randperm(length(d1bis),nmaxframes));
end
nonnans = ~isnan(d2);
d2bis = d2(nonnans);
if length(d2bis) > nmaxframes
d2bis = d2bis(randperm(length(d2bis),nmaxframes));
end
nonnans = ~isnan(d3);
d3bis = d3(nonnans);
if length(d3bis) > nmaxframes
d3bis = d3bis(randperm(length(d3bis),nmaxframes));
end
% [pdf1,pdfi1] = ksdensity(d1bis,'NumPoints',300);
% [pdf2,pdfi2] = ksdensity(d2bis,'NumPoints',300);
% [pdf3,pdfi3] = ksdensity(d3bis,'NumPoints',300);
%Fill each gap
for j=1:size(lasts,2)
if totvaliditypergap(j)==1 %(valid if 0 here)
%We cannot fill this gap with these references
else
id0=lborders(j); %left border
id1=rborders(j); %right border
gapsize = id1-id0-1;
%Extract refs around gaps (just before to just after)
P1m = mctrim(P1, id0, id1,'frame');
P2m = mctrim(P2, id0, id1,'frame');
P3m = mctrim(P3, id0, id1,'frame');
P0m = mctrim(P0filled ,id0, id1,'frame');
p1m = P1m.data;
p2m = P2m.data;
p3m = P3m.data;
p0m = P0m.data;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Local interpolation on 3 references
if method1
invproj = local_interpolation(P1m,P2m,P3m,P0m);
locinterp=invproj.data;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Local polynomial regression - prediction and continuity correction
if method2
temp = p0p(id0:id1,:);
for ax=1:3
pred = polypredictor(id0:id1,:)*coeffs{ax};
pred=pred*sigma(ax)+mu(ax);
temp(:,ax)=pred;
if timeconstraint
if id0==1
Dt1=0;
else
Dt1 = temp(1,ax)-p0p(id0,ax);
end
if id1 == nframes
Dt2=0;
else
Dt2 = temp(end,ax)-p0p(id1,ax);
end
if id0 == 1 && id1 ~= nframes
Dt1 = Dt2;
elseif id1 == nframes && id0 ~= 1
Dt2 = Dt1;
end
correction = -linspace(Dt1,Dt2,gapsize+2)'; %linear ramp correction
temp(:,ax) = temp(:,ax)+correction;
end
end
%Inverse projection
locreg = projection3D(p1m, p2m, p3m, temp, 1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Local NN regression - prediction and continuity correction
if method3
%temp = p0plocNN(id0:id1,:);
tmppredictor = linpredictor(id0:id1,:);
pred = sim(net,tmppredictor');