-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsimpledata.m
2965 lines (2955 loc) · 104 KB
/
simpledata.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
classdef simpledata
%static
properties(Constant,GetAccess=private)
%NOTE: edit this if you add a new parameter
parameter_list={...
'x_tol', 1e-6, @num.isscalar;...
'peeklength', 10, @num.isscalar;...
'peekwidth', 10, @num.isscalar;...
'labels', {''}, @iscell;...
'units', {''}, @iscellstr;...
'x_units', '', @ischar;...
'descriptor', '', @ischar;...
'plot_zeros', true, @(i) islogical(i) && isscalar(i);...
'invalid', 999999999,@num.isscalar;...
'outlier_sigma',4, @num.isscalar;...
'cdate',datetime('now'), @isdatetime;...
'debug', false, @(i) islogical(i) && isscalar(i);...
};
%These parameter are considered when checking if two data sets are
%compatible (and only these).
%NOTE: edit this if you add a new parameter (if relevant)
compatible_parameter_list={'units','x_units'};
end
%read only
properties(SetAccess=private)
length
width
x
y
mask
x_unitsi
end
%These parameters should not modify the data in any way; they should
%only describe the data or the input/output format of it.
%NOTE: edit this if you add a new parameter (if read/write)
properties(GetAccess=public,SetAccess=public)
labels
units
descriptor
peeklength
peekwidth
x_tol
plot_zeros
invalid
outlier_sigma
cdate
debug
end
properties(Dependent)
x_units
end
methods(Static)
function out=parameters(varargin)
persistent v
if isempty(v); v=varargs(simpledata.parameter_list); end
out=v.picker(varargin{:});
end
function out=valid_x(x)
out=(isnumeric(x) && ~isempty(x) && isvector(x)) || simpletimeseries.valid_t(x);
end
function [x,y,mask]=monotonic(x,y,mask,mode,debug)
if ~exist('mode','var') || isempty(mode)
mode='check';
end
if ~exist('debug','var') || isempty(debug)
debug=true;
end
if ~issorted(x)
[x,idx]=sort(x);
y=y(idx,:);
if ~isempty(mask)
mask=mask(idx);
end
end
%data should be soft monotonic now
assert(~any(diff(x)<0),'sorting failed')
%get index of duplicates (last one is not duplicate by definition)
bad_idx=[diff(x)==0;false];
if any(bad_idx)
switch lower(mode)
case 'check'
%get index+1 of duplicates
bad_idx1=circshift(bad_idx,1,1);
%make sure the values are the same: check along columns
for i=1:size(y,2)
assert(~any(y(bad_idx,i)~=y(bad_idx1,i)),['cannot monotonize the data because column ',...
num2str(i),' has different data in common epochs.'])
end
case {'remove','clear','clean'}
disp([' WARNING: blindly removing ',num2str(sum(bad_idx)),' epoch(s) to make abcissae monotonic.'])
%this is done below and is valid for all modes
case {'average','mean'}
disp([' WARNING: need to average ',num2str(sum(bad_idx)),' epoch(s) to make abcissae monotonic.'])
%convert logical array to indexes
bi=find(bad_idx);
%loop over all indexes
for i=1:numel(bi)
%find idx in the data that have the same x-values
idx=find(x==x(bi(i)));
%get the index of the data entry where the average is going to be save into (c of 'collapsed')
cidx=setdiff(idx,bi);
%compute the collapsed y values
cy=mean(y(idx,:));
%noisy debug
if debug
tab=20;
disp('DEBUG: from the following bad_idx:')
disp(str.tablify(tab,bi(i),x(bi(i)),y(bi(i),:)))
disp(['DEBUG: from bad_idx(',num2str(i),')=',num2str(bi(i)),', averaged the following data:'])
disp(str.tablify(tab,'idx','x(idx)','y(idx)'))
for j=1:numel(idx)
disp(str.tablify(tab,idx(j),x(idx(j)),y(idx(j),:)))
end
disp('DEBUG: into the following single epoch:')
disp(str.tablify(tab,cidx,x(cidx),cy))
end
%save the averaged y value
y(cidx,:)=cy;
end
otherwise
error(['unknown mode ''',mode,'''.'])
end
%remove duplicate epochs
x=x(~bad_idx);
y=y(~bad_idx,:);
if ~isempty(mask)
mask=mask(~bad_idx);
end
end
end
function out=valid_y(y)
out=isnumeric(y) && ~isempty(y); % && size(y,1) > size(y,2);
end
function out=valid_mask(mask)
out=islogical(mask) && ~isempty(mask) && isvector(mask);
end
function out=isx(mode,x1,x2,tol)
if ~exist('tol','var') || isempty(tol)
tol=simpledata.parameters('x_tol');
end
switch mode
case {'=','==','equal'}
if numel(x1)==numel(x2)
out=(x1(:)-x2(:)).^2<tol.^2;
elseif isscalar(x1)
out=(x1-x2(:)).^2<tol.^2;
elseif isscalar(x2)
out=(x1(:)-x2).^2<tol.^2;
else
out=false;
end
return
case {'<','less','smaller'}
out=x1<x2;
out(simpledata.isx('==',x1,x2,tol))=false;
case {'<=','lessorequal'}
out=x1<x2;
out(simpledata.isx('==',x1,x2,tol))=true;
case {'>','more','larger'}
out=x1>x2;
out(simpledata.isx('==',x1,x2,tol))=false;
case {'>=','moreorequal','largerorequal'}
out=x1>x2;
out(simpledata.isx('==',x1,x2,tol))=true;
otherwise
error(['unknown mode ''',mode,'''.'])
end
end
function out=transmute(in)
if isa(in,'simpledata')
%trivial call
out=in;
else
%transmute into this object
if obj.is_timeseries
out=simpledata(simpletimeseries.time2num(in.t,in.epoch,in.x_units),in.y,in.varargin{:});
else
out=simpledata(in.x,in.y,in.varargin{:});
end
end
end
function [x,varargout] = union(x1,x2,tol)
%If x1 and x2 are (for example) time domains, with each entry being a time
%value, x is the vector of entries in either <x1> or <x2>.
%
%<indx1> and <indx2> have the indexes that relate <x> to <x1> and <x2>, so
%that:
%
%x(ind1) = x1;
%x(ind2) = x2;
%
%All outputs are column vectors.
%
%This is an OR operation, x has elements of any x1 or x2.
%
%A practical application for this would be to reconstruct a signal that is
%measured with two sensors, each in its own time domain.
%
% t1 = [1 2 3 4 5 6];
% s1 = sin(t1);
% t2 = [0 1.5 3 4.5 6 7.5];
% s2 = sin(t2);
% [t,i1,i2] = union(t1,t2);
% s(i1) = s1;
% s(i2) = s2;
% plot(t1,s1,'bo',t2,s2,'ro',t,s)
%trivial call
if isempty(x1) || isempty(x2)
x = [];
varargout={[],[]};
return
end
if ~exist('tol','var') || isempty(tol)
tol=1e-6;
end
%sanity
if ~isvector(x1) || ~isvector(x2)
error('inputs <x1> and <x2> must be 1D vectors.');
end
if (isnumeric(x1) && any(isnan(x1))) || ...
(isnumeric(x2) && any(isnan(x2)))
error('cannot handle NaNs in the input arguments. Clean them first.')
end
%shortcuts
if numel(x1)==numel(x2) && all(x1(:)==x2(:))
x=x1;
varargout={true(size(x1)),true(size(x2))};
return
end
%get first output argument (need to use tolerance to captures time system conversion errors)
xt=[x1(:);x2(:)];
tol=tol/max(abs(xt));
x=uniquetol(xt,tol);
%maybe we're done here
if nargout==1
return
end
%get second argument
varargout(1)={ismembertol(x,x1,tol)};
%maybe we're done here
if nargout==2
return
end
%get third argument
varargout(2)={ismembertol(x,x2,tol)};
end
function [out,idx]=rm_outliers(in,varargin)
% NOTE: greatly simplified the version of this routine described below:
%
% [OUT,IDX,STD_ERR]=NUM_RM_OUTLIERS(IN,NSIGMA,SMOOTH_METHOD,SPAN_FACTOR,PLOTFLAG)
% is an outlier detection routine. It looks at the points in IN and flags
% the ones that deviate from the reference by NSGIMA*std as outliers.
% OUT is equal to IN, with NaN's replacing the flagged outliers. IDX is
% a logical mask which contains indexes of IN flagged as outliers.
%
% NUM_RM_OUTLIERS(IN) removes the outliers in input IN using default
% settings.
%
% NUM_RM_OUTLIERS(IN,NSIGMA) additionally specifies how many
% times bigger than the STD are the outliers. Default value is 4.
%
% NUM_RM_OUTLIERS(IN,NSIGMA,METHOD,SPAN_FACTOR) can be used to specify
% different methods of outlier detection. In general an outlier can be
% seen as a data-point which deviates from a certain reference by a
% statistical limit. The reference taken depends greatly on the type of
% input signal IN. If IN is a random zero-mean process than outliers
% can be computed by the distance to the x-axis. However if IN is a noisy
% sinusoidal signal the above reference (x-axis) result in cropping
% the wave at min and max regions. For that reason different methods
% are available to defined the reference points,
% The following methods are available,
% 'zero' - Outliers referenced to the x-axis.
% 'mean' - Outliers referenced to the mean of the signal [default]
% 'detrend' - Outliers referenced to the best fitting line to IN
% 'polyfit' - Outliers referenced to the best fitting polynom of degree
% POLYDEGREE. This method requires the additional input:
% NUM_RM_OUTLIERS(IN,NSIGMA,METHOD,POLYDEGREE)
%
% Additional methods are available throught the internal use of the
% 'smooth' function. There are 'moving','lowess','loess','sgolay',
% 'rlowess','rloess'. For all these methods an additional input SPAN is
% required,
% [OUT,IDX]=NUM_RM_OUTLIERS(IN,NSIGMA,METHOD,SPAN) which specifies
% the length SPAN of the smoothing window relative to the lenght of
% the input. The default span is 0.1. Negative values of SPAN are also
% possible and they are implemented to allow the user to set a SPAN
% which is independent of the signal length.
%
% NUM_RM_OUTLIERS(...,PLOTFLAG) with PLOTFLAG set to 'true' or to a
% figure handle will plot the flagged outliers and the reference signal.
% Created by J.Encarnacao <[email protected]>
% List of Changes:
% Pedro Inacio <[email protected]>, reorganized outlier detection
% routine.
% Handle Inputs
p=machinery.inputParser;
p.addRequired( 'in', @isnumeric);
p.addParameter('outlier_sigma',...
simpledata.parameters('outlier_sigma'), @num.isscalar);
p.addParameter('outlier_value', nan, @num.isscalar);
% parse it
p.parse(in,varargin{:});
%assume there are no outliers
out=in;
idx=false(size(in));
%ignore non-positive outlier_sigmas
if p.Results.outlier_sigma>0 && numel(in)>1
% ignore NaNs
nanidx = isnan(in(:));
% make aux containers with the same size as input
err=zeros(size(in));
% compute error
err(~nanidx) = in(~nanidx)-mean(in(~nanidx));
std_err = std(err(~nanidx));
%trivial call
if std_err>0
%outlier indexes
idx = abs(err)>p.Results.outlier_sigma*std_err;
%flag outliers
out(idx(:))=p.Results.outlier_value;
end
end
end
function obj_list=op_multiple(op,obj_list,msg)
%vector mode
if iscellstr(op)
if ~exist('msg','var');msg='';end
for i=1:numel(op)
obj_list=simpledata.op_multiple(op{i},obj_list,msg);
end
return
end
%sanity
if ~iscell(obj_list)
error(['need input ''obj_list'' to be a cell array, not a ',class(obj_list),'.'])
end
% save timing info
if ~exist('msg','var') || isempty(msg)
s.msg=[op,' op'];
else
s.msg=[op,' op for ',msg];
end
s.n=2*(numel(obj_list)-1); c=0;
%forward op
for i=1:numel(obj_list)-1
[obj_list{i},obj_list{i+1}]=obj_list{i}.(op)(obj_list{i+1});
c=c+1;s=time.progress(s,c);
end
%backward op
for i=numel(obj_list):-1:2
[obj_list{i},obj_list{i-1}]=obj_list{i}.(op)(obj_list{i-1});
c=c+1;s=time.progress(s,c);
end
end
function out=isequal_multiple(obj_list,columns,msg)
%sanity
if ~iscell(obj_list)
error(['need input ''obj_list'' to be a cell array, not a ',class(obj_list),'.'])
end
% save timing info
if ~exist('msg','var') || isempty(msg)
s.msg='isequal op';
else
s.msg=['isequal op for ',msg];
end
s.n=numel(obj_list)-1; c=0;
%declare type of output argument
out=cell(numel(obj_list)-1,1);
%loop over obj list
for i=1:numel(obj_list)-1
out{i}=obj_list{i}.isequal(obj_list{i+1},columns);
c=c+1;s=time.progress(s,c);
end
end
%% vector operators
function out=vmean(obj_list,varargin)
p=machinery.inputParser;
p.addRequired( 'obj_list', @iscell);
p.addParameter('weights',ones(size(obj_list))/numel(obj_list),@(i) isnumeric(i) && all(size(obj_list)==size(i)))
p.parse(obj_list,varargin{:})
out=obj_list{1}.*p.Results.weights(1);
for i=2:numel(obj_list)
out=out+obj_list{i}.*p.Results.weights(i);
end
end
function out=vtimes(obj_list1,obj_list2)
p=machinery.inputParser;
p.addRequired( 'obj_list1', @iscell);
p.addRequired( 'obj_list2', @(i) iscell(i) && all(size(obj_list1)==size(obj_list2)) )
p.parse(obj_list1,obj_list2)
out=cell(size(obj_list1));
for i=1:numel(obj_list1)
out{i}=obj_list1{i}.*obj_list2{i};
end
end
function out=vscale(obj_list,scales)
p=machinery.inputParser;
p.addRequired( 'obj_list', @iscell);
p.addRequired( 'scales', @(i) isnumeric(i) && all(numel(obj_list)==numel(scales)) )
p.parse(obj_list,scales)
out=cell(size(obj_list));
for i=1:numel(obj_list)
out{i}=obj_list{i}.*scales(i);
end
end
function out=vsqrt(obj_list)
p=machinery.inputParser;
p.addRequired( 'obj_list', @iscell);
p.parse(obj_list)
out=cell(size(obj_list));
for i=1:numel(obj_list)
out{i}=obj_list{i}.sqrt;
end
end
%% constructors
function out=one(x,width,varargin)
out=simpledata(x(:),ones(numel(x),width),varargin{:});
end
function out=zero(x,width,varargin)
out=simpledata(x(:),zeros(numel(x),width),varargin{:});
end
function out=randn(x,width,varargin)
out=simpledata(x(:),randn(numel(x),width),varargin{:});
end
function out=sinusoidal(x,w,varargin)
y_now=cell2mat(arrayfun(@(i) sin(x(:)*i),w,'UniformOutput',false));
out=simpledata(x(:),y_now,varargin{:});
end
%% aux routines
function out=parametric_component_fieldnames(varargin)
%converts {'polynomial',[1 1 1],'sinusoidal',[n1, n2, n3]} into {p0,p1,p2,s1,s2,s3,c1,c2,c3}
p=machinery.inputParser;
p.addParameter('polynomial',[], @(i) isnumeric(i) || isempty(i));
p.addParameter('sinusoidal',[], @(i) isnumeric(i) || isduration(i) || isempty(i));
p.parse(varargin{:});
out=cell(1,numel(p.Results.polynomial)+2*numel(p.Results.sinusoidal));
for i=1:numel(p.Results.polynomial)
out{i}=['p',num2str(i-1)];
end
for i=1:numel(p.Results.sinusoidal)
out{numel(p.Results.polynomial)+i}=['s',num2str(i)];
end
for i=1:numel(p.Results.sinusoidal)
out{numel(p.Results.polynomial)+numel(p.Results.sinusoidal)+i}=['c',num2str(i)];
end
end
%% general test for the current object
function out=test_parameters(field,varargin)
%basic parameters
switch field
case 'l'; out=100; return
case 'w'; out=4; return
end
%optional parameters
switch numel(varargin)
case 0
l=simpledata.test_parameters('l');
w=simpledata.test_parameters('w');
case 1
l=varargin{1};
w=simpledata.test_parameters('w');
case 2
l=varargin{1};
w=varargin{2};
end
%more parameters
switch field
case 'args'
out={...
'units', strcat(cellstr(repmat('y_unit-',w,1)),cellstr(num2str((1:w)'))),...
'labels', strcat(cellstr(repmat('label-', w,1)),cellstr(num2str((1:w)'))),...
'x_units', 'x_units',...
'descriptor','original'...
};
case 'x'; out=transpose(0:l-1);
case 'T'; out=l./[3 5];
case 'y_randn_scale'; out=0.2;
case 'y_poly_scale'; out=[1 1 1]./[1 l l^2];
case 'y_sin_scale'; out=[0.8 0.5];
case 'y_cos_scale'; out=[0.2 1.2];
case 'y_randn'
out=simpledata.test_parameters('y_randn_scale')*randn(l,w);
case 'y_poly'
out=pardecomp(...
simpledata.test_parameters('x',l),...
[],...
'np',numel(simpledata.test_parameters('y_poly_scale')),...
'T',[],...
'x',simpledata.test_parameters('y_poly_scale',l)'...
).y_sum*ones(1,w);
% % The code below is the same as the code above
% c=simpledata.test_parameters('y_poly_scale',l);
% x1=simpledata.test_parameters('x',l);
% out=zeros(l,w);
% for i=1:numel(c)
% out=out+c(i)*(x1).^(i-1)*ones(1,w);
% end
case 'y_sin_T'
out=pardecomp(...
simpledata.test_parameters('x',l),...
[],...
'np',0,...
'T',simpledata.test_parameters('T',l),...
'x',[simpledata.test_parameters('y_sin_scale'),zeros(size(simpledata.test_parameters('y_cos_scale')))]'...
).y_sum*ones(1,w);
% % The code below is the same as the code above
% c=simpledata.test_parameters('y_sin_scale');
% T=simpledata.test_parameters('T',l);
% x1=simpledata.test_parameters('x',l);
% out=zeros(l,w);
% for i=1:numel(T)
% out=out+c(i)*sin( ...
% 2*pi/T(i)*x1*ones(1,w)...
% );
% end
case 'y_cos_T'
out=pardecomp(...
simpledata.test_parameters('x',l),...
[],...
'np',0,...
'T',simpledata.test_parameters('T',l),...
'x',[zeros(size(simpledata.test_parameters('y_sin_scale'))),simpledata.test_parameters('y_cos_scale')]'...
).y_sum*ones(1,w);
% % The code below is the same as the code above
% c=simpledata.test_parameters('y_cos_scale');
% T=simpledata.test_parameters('T',l);
% x1=simpledata.test_parameters('x',l);
% out=zeros(l,w);
% for i=1:numel(T)
% out=out+c(i)*cos( ...
% 2*pi/T(i)*x1*ones(1,w)...
% );
% end
case 'y_sin'
c=simpledata.test_parameters('y_sin_scale');
T=simpledata.test_parameters('T',l);
x1=simpledata.test_parameters('x',l);
out=zeros(l,w);
for i=1:numel(T)
out=out+c(i)*sin(2*pi/T(i)*x1*randn(1,w) + ones(l,1)*randn(1,w));
end
case 'y_all'
out=...
simpledata.test_parameters('y_randn',l,w)+...
simpledata.test_parameters('y_poly', l,w)+...
simpledata.test_parameters('y_sin', l,w);
case 'y_all_T'
out=...
simpledata.test_parameters('y_randn',l,w)+...
simpledata.test_parameters('y_poly', l,w)+...
simpledata.test_parameters('y_sin_T',l,w)+...
simpledata.test_parameters('y_cos_T',l,w);
case {'randn','trend','sin','all','all_T'}
args=simpledata.test_parameters('args',l,w);
out=simpledata(...
simpledata.test_parameters('x',l,w),...
simpledata.test_parameters(['y_',field],l,w),...
args{:}...
);
case 'mask'
out=rand(l,1)<0.9;
case 'no-mask'
out=true(l,1);
case 'columns'
%NOTICE: this return from 1 to w columns
out=[1,find(randn(1,w-1)>0)+1];
case 'obj'
args=simpledata.test_parameters('args',l,w);
out=simpledata(...
simpledata.test_parameters('x', l,w),...
simpledata.test_parameters('y_all',l,w),...
'mask',simpledata.test_parameters('mask',l,w),...
args{:}...
);
otherwise
error(['cannot understand field ''',field,'''.'])
end
end
function test(method,l,w)
if ~exist('method','var') || isempty(method)
method='all';
end
if ~exist('l','var') || isempty(l)
l=simpledata.test_parameters('l');
end
if ~exist('w','var') || isempty(w)
w=simpledata.test_parameters('w');
end
%get common parameters
args=simpledata.test_parameters('args',l,w);
columns=simpledata.test_parameters('columns',l,w);
%init object
a=simpledata.test_parameters('obj',l,w);
switch method
case 'all'
for i={'plot','append','median','trim','slice','interp','detrend','outlier','plus','pardecomp','augment','vmean'}
simpledata.test(i{1},l);
end
case 'plot'
figure
a.plot('columns', columns)
case 'append'
b=a.append(...
simpledata(-l-1:-1,simpledata.test_parameters('y_all',l+1,w),...
'mask',simpledata.test_parameters('mask',l+1,w),...
args{:}...
)...
);
figure
subplot(2,1,1)
a.plot('columns', columns)
title('original')
subplot(2,1,2)
b.plot('columns', columns)
title(method)
case 'median'
lines1=cell(size(columns));lines1(:)={'-o'};
lines2=cell(size(columns));lines2(:)={'-x'};
figure
a.median(10 ).plot('columns', columns,'line',lines1);
a.medfilt(10).plot('columns', columns,'line',lines2);
legend('median','medfilt')
title(method)
case 'trim'
b=a.trim(...
round(-l/2),...
round( l/3)...
);
figure
subplot(2,1,1)
a.plot('columns', columns)
title('original')
subplot(2,1,2)
b.plot('columns', columns)
title(method)
case 'slice'
b=a.slice(...
round(l*0.3),...
round(l*0.4)...
);
figure
a.plot('columns', columns,'line',repmat({'+-'},numel(columns),1))
b.plot('columns', columns,'line',repmat({'o-'},numel(columns),1))
legend_str={};
for i=1:numel(columns);legend_str{end+1}=['original-',num2str(i)]; end %#ok<AGROW>
for i=1:numel(columns);legend_str{end+1}=['sliced-', num2str(i)]; end %#ok<AGROW>
%%
%%
legend(legend_str)
title(method)
case 'interp'
figure
legend_str={};
%define interpolated time domain
t_interp=round(-l*0.1):0.4:round(l*0.7);
%add some gaps to the data
mask=a.mask;
mask(a.idx(round(l*0.45)):a.idx(round(l*0.5)))=false;
a=a.mask_and(mask);
%plot it
legend_str{end+1}='original';
a.plot('columns',1,'line',{'o:'});
legend_str{end+1}='linear interp over gaps narrower than=0';
a.interp(...
t_interp,'interp_over_gaps_narrower_than',0 ...
).plot('columns',1,'line',{'x-'});
legend_str{end+1}='spline interp over gaps narrower than 3';
a.interp(...
t_interp,'interp_over_gaps_narrower_than',3 ...
).plot('columns',1,'line',{'d-'});
legend_str{end+1}='spline interp over gaps narrower than \infty';
a.interp(...
t_interp,'interp_over_gaps_narrower_than',inf ...
).plot('columns',1,'line',{'s-'});
legend(legend_str)
case 'detrend'
b=a.detrend;
figure
subplot(2,1,1)
a.plot('columns', columns)
title('original')
subplot(2,1,2)
b.plot('columns', columns)
title(method)
case 'outlier'
%TODO: need to revise the outlier method, this test is giving strange results
outlier_iter=2;
figure
a=a.assign(simpledata.test_parameters('y_randn',l,w));
a.plot('columns', 1,'line',{'x-'});
legend_str{1}=a.descriptor;
[a,o]=a.outlier('outlier_iter',outlier_iter,'outlier_sigma',3);
a.plot(...
'columns', 1,...
'masked',true,...
'line',{'o'}...
);
legend_str{2}=[a.descriptor,' w/out outliers'];
for i=1:outlier_iter
if any(o{i}.mask)
o{i}.plot(...
'columns', 1,...
'masked',true,...
'line',{'d'}...
);
legend_str{i+2}=o{i}.descriptor;
end
end
legend(legend_str)
title(method)
case 'plus'
a=simpledata(0:l,simpledata.test_parameters('y_all',l+1,w),...
'mask',[true(0.2*l+1,1);false(0.2*l,1);true(0.6*l,1)],...
args{:}...
);
b=simpledata(-l/2:2:3/2*l,simpledata.test_parameters('y_all',l+1,w),...
'mask',[true(0.3*l+1,1);false(0.2*l,1);true(0.2*l,1);false(0.1*l,1);true(0.2*l,1)],...
args{:}...
);
figure
a.plot('columns',1,'line',{'+-'})
b.plot('columns',1,'line',{'x-'})
c=a+b;
c.plot('columns',1,'line',{'o-'})
legend('a','b','a+b')
title(method)
%the tests below do not require the object 'a', defined above
case 'pardecomp'
%NOTICE: this uses a deprecated method
t=simpledata.test_parameters('x',l);
y=simpledata.test_parameters('y_all_T',l,w);
a=num.pardecomp(t,y(:,1),...
'polynomial',numel(simpledata.test_parameters('y_poly_scale'))-1,...
'sinusoidal',simpledata.test_parameters('T',l)...
);
disp(['sin_periods : ',num2str(simpledata.test_parameters('T',l))])
disp(['poly_coeffs : ',num2str(simpledata.test_parameters('y_poly_scale'))])
disp(['sin_coeffs : ',num2str(simpledata.test_parameters('y_sin_scale'))])
disp(['cos_coeffs : ',num2str(simpledata.test_parameters('y_cos_scale'))])
disp(['randn_scale : ',num2str(simpledata.test_parameters('y_randn_scale'))])
num.plot_pardecomp(a)
case 'augment'
a=simpledata([1:4,5 7 9 11],[11 12 13 14 15 17 19 31]',...
'mask',logical([1 1 0 0 1 1 0 0])...
);
b=simpledata([1:4,6,8,10 12],[21 22 23 24 26 28 40 42]',...
'mask',logical([1 0 1 0 1 0 1 0])...
);
disp('Augment test: a')
a.peek
disp('Augment test: b')
b.peek
disp('Augment test: a.augment(b,common=[true,false],new=true,old=true)')
a.augment(b,'quiet',true,'common',true,'new',true,'old',true,'skip_gaps',false).peek
disp('---')
a.augment(b,'quiet',true,'common',false,'new',true,'old',true,'skip_gaps',false).peek
disp('Augment test: a.augment(b,common=[true,false],new=false,old=true)')
a.augment(b,'quiet',true,'common',true,'new',false,'old',true,'skip_gaps',false).peek
disp('---')
a.augment(b,'quiet',true,'common',false,'new',false,'old',true,'skip_gaps',false).peek
disp('Augment test: a.augment(b,common=true,new=true,old=true,skip_gaps=[false,true])')
a.augment(b,'quiet',true,'common',true,'new',true,'old',true,'skip_gaps',false).peek
disp('---')
a.augment(b,'quiet',true,'common',true,'new',true,'old',true,'skip_gaps',true).peek
case 'vmean'
figure('visible','on');
a=cell(1,w*2);
legend_str=cell(1,numel(a)+1);
for i=1:numel(a)
a{i}=simpledata.randn(1:l,w);
a{i}.plot('columns',1,'line',{'.'})
legend_str{i}=['a',num2str(i)];
end
b=simpledata.vmean(a);
b.plot('columns',1)
legend_str{end}='mean(a_i)';
legend(legend_str)
otherwise
error(['Cannot handle test method ''',method,'''.'])
end
end
end
methods
%% constructor
function obj=simpledata(x,y,varargin)
% input parsing
p=machinery.inputParser;
p.addRequired( 'x' , @(i) simpledata.valid_x(i));
p.addRequired( 'y' , @(i) simpledata.valid_y(i));
p.addParameter('mask' ,true(size(x(:))), @(i) simpledata.valid_mask(i));
%create argument object, declare and parse parameters, save them to obj
[~,~,obj]=varargs.wrap('sinks',{obj},'parser',p,'sources',{simpledata.parameters('obj')},'mandatory',{x,y},varargin{:});
%assign (this needs to come before the parameter check, so that sizes are known)
varargin=cells.vararginclean(varargin,'t');
obj=obj.assign(y,'x',x,varargin{:});
%rowize labels and units
obj.labels =transpose(obj.labels( :));
obj.units=transpose(obj.units(:));
% check parameters
for i=1:simpledata.parameters('length')
obj=check_annotation(obj,simpledata.parameters('name',i));
end
end
%NOTICE: this method blindly assigns data
function obj=assign_x(obj,x)
%propagate x
obj.x=x(:);
%update length
obj.length=numel(obj.x);
end
%NOTICE: this method blindly assigns data
function obj=assign_y(obj,y)
%propagate y
obj.y=y;
%update width
obj.width=size(y,2);
end
%NOTICE: this method blindly assigns data
function obj=assign_mask(obj,mask)
obj.mask=mask;
end
%NOTICE: unlike the assign_* methods above, this method does some checking
function obj=assign(obj,y,varargin)
p=machinery.inputParser;
p.addRequired( 'y' , @(i) simpledata.valid_y(i));
p.addParameter('x' ,obj.x, @(i) simpledata.valid_x(i));
p.addParameter('mask' ,obj.mask,@(i) simpledata.valid_mask(i));
p.addParameter('reset_width',false, @isscalar);
p.addParameter('monotonize','none', @ischar);
% parse it
p.parse(y,varargin{:});
% ---- x ----
if numel(p.Results.x)~=size(y,1)
error(['number of elements of input ''x'' (',num2str(numel(p.Results.x)),...
') must be the same as the number of rows of input ''y'' (',num2str(size(y,1)),').'])
end
%propagate x
obj=obj.assign_x(p.Results.x(:));
% ---- y ----
if ~logical(p.Results.reset_width) && ~isempty(obj.width) && size(y,2) ~= obj.width
error(['data width changed from ',num2str(obj.width),' to ',num2str(size(y,2)),'.'])
end
if obj.length~=size(y,1)
error(['data length different than size(y,2), i.e. ',...
num2str(obj.length),' ~= ',num2str(size(y1m)),'.'])
end
%propagate y
obj=obj.assign_y(y);
% ---- mask ----
%check if explicit mask was given
if ~any(strcmp(p.UsingDefaults,'mask'))
%make sure things make sense
assert(obj.length==numel(p.Results.mask),[' ',...
'number of elements of input ''mask'' (',num2str(numel(p.Results.mask)),...
') must be the same as the data length (',num2str(obj.length),').'])
%propagate mask
obj=obj.assign_mask(p.Results.mask(:));
else
%using existing mask (the default), data length may have changed: set mask from y
obj=obj.mask_reset;
end
%sanitize done inside mask_update
obj=mask_update(obj);
%monotonize the data if requested
switch lower(p.Results.monotonize)
case 'none'
%do nothing
otherwise
obj=obj.monotonize(p.Results.monotonize);
end
end
function obj=assign_tx_mask(obj,y,tx,mask,varargin)
if obj.is_timeseries; obj=obj.assign( y,'mask',mask,'t',tx,varargin{:});
else ; obj=obj.assign_x(y,'mask',mask,'x',tx,varargin{:});
end
end
%NOTICE: obj2=simpledata(t,y,obj1.varargin{:}) is preferable to obj2=simpledata(t,y).copy_metadata(obj1)
%TODO: check if it's possible to ditch the copy_metadata members because of the reason above
function obj=copy_metadata(obj,obj_in,more_parameters,less_parameters)
if ~exist('less_parameters','var')
less_parameters={};
end
if ~exist('more_parameters','var')
more_parameters={};
end
pn=[simpledata.parameters('list');more_parameters(:)];
for i=1:numel(pn)
%skip less parameters
if ismember(pn{i},less_parameters)
continue
end
%check if this is a relevant parameter to this object and obj_in
if isprop(obj,pn{i}) && isprop(obj_in,pn{i})
obj.(pn{i})=obj_in.(pn{i});
end
end
end
function out=metadata(obj,more_parameters)
if ~exist('more_parameters','var')
more_parameters={};
end
warning off MATLAB:structOnObject
out=structs.filter(struct(obj),[simpledata.parameters('list');more_parameters(:)]);
warning on MATLAB:structOnObject
out=structs.rm_empty(out);
end
function out=varargin(obj,more_parameters)
if ~exist('more_parameters','var')
more_parameters={};
end
out=varargs(obj.metadata(more_parameters)).varargin;
end
%% info methods
function print(obj,tab)
if ~exist('tab','var') || isempty(tab)
tab=12;
end
%parameters
for i=1:simpledata.parameters('length')
obj.disp_field(simpledata.parameters('name',i),tab);
end
%some parameters are not listed
more_parameters={'length','width'};
for i=1:numel(more_parameters)
obj.disp_field(more_parameters{i},tab);
end
%add some more info
obj.disp_field('nr gaps', tab,sum(~obj.mask))
obj.disp_field('first datum',tab,sum(obj.x(1)))
obj.disp_field('last datum', tab,sum(obj.x(end)))
switch class(obj)
case 'simplegrid'
%do nothing, the str-nl mode does not work with simplegrid.stats
%TODO: figure out a way to show grid statistics with the print method
otherwise
obj.disp_field('statistics', tab,[10,stats(obj,...
'mode','str-nl',...
'tab',tab,...
'period',seconds(inf),...
'columns',1:min([obj.peekwidth,obj.width])...
)])
end
% obj.peek
end
function disp_field(obj,field,tab,value)
if ~exist('value','var') || isempty(value)
value=obj.(field);
if isnumeric(value) || iscell(value)
value=value(1:min([numel(value),obj.peekwidth]));
end
end
disp([str.tabbed(field,tab),' : ',str.show(transpose(value(:)))])
end
function out=peek_idx(obj)
out=[...
1:min([ obj.peeklength, round(0.5*obj.length) ]),...
max([obj.length-obj.peeklength+1,round(0.5*obj.length)+1]):obj.length...
];
end
function out=peek(obj,idx,tab)
if ~exist('tab','var') || isempty(tab)
tab=12;
end
if ~exist('idx','var') || isempty(idx)
idx=obj.peek_idx;
elseif strcmp(idx,'all')
idx=1:obj.length;
end
%check if formatted time stamp is possible
formatted_time=obj.is_timeseries;
%adapt tab to formatted time
if tab<19 && formatted_time
tab_x=19;
else
tab_x=tab;
end
out=cell(numel(idx),1);
for i=1:numel(idx)
tmp=cell(1,min([obj.peekwidth,obj.width]));
for j=1:numel(tmp)
tmp{j}=str.tabbed(num2str(obj.y(idx(i),j)),tab,true);
end
%use formatted dates is object supports them
if formatted_time
x_str=datestr(obj.t(idx(i)),'yyyy-mm-dd HH:MM:SS');
else
x_str=num2str(obj.x(idx(i)));
end
out{i,:}=[...
str.tabbed(x_str,tab_x,true),' ',...
strjoin(tmp),' ',...
str.show(obj.mask(idx(i)))...