-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsimpletimeseries.m
2260 lines (2252 loc) · 80.1 KB
/
simpletimeseries.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 simpletimeseries < simpledata
%static
properties(Constant,GetAccess=private)
%NOTE: edit this if you add a new parameter
parameter_list={...
'format', 'modifiedjuliandate',@(i)ischar(i)||isdatetime(i);...
't_tol', 2e-6, @num.isscalar;...
'timesystem','utc', @ischar;...
'data_dir' file.orbdir('data'), @ischar;...
'x_units', 'seconds', @ischar;...
'epoch', time.zero_date, @isdatetime;...
};
%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={'timesystem','epoch'};
%define periods when CSR calmod is upside down
csr_acc_mod_invert_periods=datetime({...
'2016-01-28','2016-03-02';...
});
end
properties(Constant)
valid_timesystems={'utc','gps'};
end
%NOTE: edit this if you add a new parameter (if read only)
properties(SetAccess=private)
step
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)
format
t_tol
timesystem
data_dir
end
%private (visible only to this object)
properties(GetAccess=private)
epochi %absolute epoch (datetime class), from which x in simpledata is relative to
end
%calculated only when asked for
properties(Dependent)
t
t_formatted %this handles the numeric/char version of t
epoch
start
stop
tsys
first
last
end
methods(Static)
function out=parameters(varargin)
persistent v
if isempty(v); v=varargs(simpletimeseries.parameter_list); end
out=v.picker(varargin{:});
end
function out=timescale(in,time_units)
if ~exist('time_units','var') || isempty(time_units)
time_units=simpletimeseries.parameters('x_units');
end
%NOTICE: this method handles both duration and numeric inputs, returning the other data type.
out=time.num2duration(in,time_units);
end
function out=valid_t(in)
out=isdatetime(in);
end
function out=valid_epoch(in)
out=isdatetime(in) && isscalar(in);
end
function out=valid_timesystem(in)
switch lower(in)
case simpletimeseries.valid_timesystems
out=true;
otherwise
out=false;
end
end
function out=time2num(in,epoch,time_units)
%NOTICE: when calling obj.x_units=..., there can be the case that 'in' is empty
if isempty(in)
out=[];
return
end
if ~exist('epoch','var') || isempty(epoch)
epoch=in(1);
end
if ~exist('time_units','var') || isempty(time_units)
time_units=simpletimeseries.parameters('x_units');
end
if isfinite(epoch)
out=simpletimeseries.timescale(in-epoch,time_units);
elseif any(isfinite(in))
out=simpletimeseries.timescale(in-min(in),time_units);
else
out=Inf(size(in));
end
end
function out=num2time(in,epoch,time_units)
if ~exist('epoch','var') || isempty(epoch)
error('need input ''epoch''.')
end
if ~exist('time_units','var') || isempty(time_units)
time_units=simpletimeseries.parameters('x_units');
end
out=epoch+simpletimeseries.timescale(in,time_units);
end
function out=ist(mode,t1,t2,tol)
%expect vectors as well
if numel(t1)~=numel(t2)
out=false;
return
end
%this handles infinites
if t1(:)~=t2(:)
out=simpledata.isx(mode,seconds(t1(:)-t2(:)),0,tol);
else
out=true;
end
end
function presence=ispresent(parser,fields)
% defaults
if ~exist('fields','var') || isempty(fields)
fields={'t','x'};
check_for_concurrence=true;
else
check_for_concurrence=false;
end
%sanity
if ~iscell(fields)
error('input argument ''fields'' must be a cell array.')
end
% look for existence
for i=1:numel(fields)
if any(strcmp(parser.Parameters,fields{i}))
presence.(fields{i})=~any(strcmp(parser.UsingDefaults,fields{i}));
else
presence.(fields{i})=isfield(parser.Unmatched,fields{i});
end
end
%this is often how this routine is called
if check_for_concurrence
%cannot have both 't' and 'x'
if presence.x && presence.t
error('cannot handle both inputs ''x'' and ''t''.')
end
end
end
function out=transmute(in)
if isa(in,'simpletimeseries')
%trivial call
out=in;
else
%transmute into this object
if obj.is_timeseries
out=simpletimeseries(in.t,in.y,in.varargin{:});
else
out=simpletimeseries(in.x,in.y,in.varargin{:});
end
end
end
function out=timestep(in,varargin)
p=machinery.inputParser;
p.addRequired( 'in', @isdatetime);
p.addParameter('nsigma', 4, @num.isscalar);
p.addParameter('max_iter', 10, @num.isscalar);
p.addParameter('sigma_iter',2, @num.isscalar);
p.addParameter('sigma_crit',1e-9, @num.isscalar);
p.addParameter('max_mean_ratio',1e3,@num.isscalar);
p.addParameter('curr_iter', 0, @num.isscalar);
p.addParameter('disp_flag', false, @islogical);
p.addParameter('time_units',simpletimeseries.parameters('x_units'), @ischar);
% parse it
p.parse(in,varargin{:});
%handle singularities
switch numel(in)
case 0
error('cannot handle empty time stamps')
case 1
out=0;
return
end
%get numeric diff of time
tdiff=simpletimeseries.timescale(diff(in),p.Results.time_units);
%large jumps produce erroneous results, so get rid of those first
while std(tdiff)~=0 && max(tdiff)/mean(tdiff)>p.Results.max_mean_ratio
%save stats
stdtdiff=std(tdiff);
ratiotdiff=max(tdiff)/mean(tdiff);
%remove large gaps
tdiff=simpledata.rm_outliers(tdiff,varargin{:});
%send feedback
if p.Results.disp_flag
disp([' removed ',num2str(sum(isnan(tdiff))),' large gaps, since ',...
'std(delta t) is ',num2str(stdtdiff),' and ',...
'max(delta t) is ',num2str(ratiotdiff),' times larger than mean(delta).'])
end
%remove nans
tdiff=tdiff(~isnan(tdiff));
end
%get diff of time domain without jumps
outdiff=simpledata.rm_outliers(tdiff,varargin{:});
%get rid of nans
outdiff=outdiff(~isnan(outdiff));
%check if there are still lots of gaps in the data
if std(outdiff)>p.Results.sigma_crit*mean(outdiff) && p.Results.curr_iter < p.Results.max_iter
%reduce sigma
nsigma_new=p.Results.nsigma/p.Results.sigma_iter;
%send feedback
if p.Results.disp_flag
disp([' failed to determine the timestep, since std(delta t) is ',num2str(std(outdiff)),...
'. Reducing NSIGMA from ',num2str(p.Results.nsigma),' to ',num2str(nsigma_new),'.'])
end
%recursive call
vararginnow=cells.vararginclean(varargin,{'nsigma','curr_iter','disp_flag'});
out=simpletimeseries.timestep(in,...
'nsigma',nsigma_new,...
'curr_iter',p.Results.curr_iter+1,...
'disp_flag',false,...
vararginnow{:});
elseif isempty(outdiff)
%dead end, sigma was reduced too much and all data is flagged as
%outliers: nothing to do but to give some estimated of the previous
%sigma (rounded to micro-seconds to avoid round off errors)
vararginnow=cells.vararginclean(varargin,{'nsigma'});
outdiff=simpledata.rm_outliers(tdiff,...
'nsigma',p.Results.nsigma*p.Results.sigma_iter,...
vararginnow{:});
out=simpletimeseries.timescale(...
round(...
mean(...
outdiff(~isnan(outdiff))...
)*1e6...
)*1e-6...
);
else
out=simpletimeseries.timescale(outdiff(1));
end
%send feedback if needed
if p.Results.disp_flag
disp([' final timestep is ',char(out),'.'])
end
end
function v=fix_interp_over_gaps_narrower_than(v)
if ~iscell(v)
error(['expecting input ''v'' to be a cell array, not a ',class(v),'.'])
end
for i=1:numel(v)
if strcmp(v{i},'interp_over_gaps_narrower_than')
if isduration(v{i+1})
v{i+1}=simpletimeseries.timescale(v{i+1});
end
break
end
end
end
%% internally-consistent naming of satellites
function out=translatesat(in)
%search for satellite name
switch lower(in)
case {'champ','ch'}
out='ch';
case {'swarm-a','swarma','swarm a','swma','sa','l47'}
out='sa';
case {'swarm-b','swarmb','swarm b','swmb','sb','l48'}
out='sb';
case {'swarm-c','swarmc','swarm c','swmc','sc','l49'}
out='sc';
case {'goce','go'}
out='go';
case {'unknown','test'}
out=in;
otherwise
success=false;
%try grace.m
[out,success]=machinery.trycatch(success,'grace:BadSat',@grace.translatesat,{in});
%add additional class calls to translatesat (using the same structure above)
%check something worked
assert(success,['Cannot translate satellite ''',in,'''.'])
end
end
function out=translatesatname(in)
%search for satellite name
switch simpletimeseries.translatesat(in)
case 'ch'; out='CHAMP';
case 'sa'; out='Swarm-A';
case 'sb'; out='Swarm-B';
case 'sc'; out='Swarm-C';
case 'go'; out='GOCE';
case {'unknown','test'}; out=in;
otherwise
success=false;
%try grace.m
[out,success]=machinery.trycatch(success,'grace:BadSatName',@grace.translatesatname,{in});
%add additional class calls to translatesat (using the same structure above)
%check something worked
assert(success,['Cannot translate satellite ''',in,'''.'])
end
end
%% consistent reference frame names
function out=translateframe(in)
if ischar(in)
switch lower(in)
case {'crs','crf','eci','icrf','gcrf','j2000','eme2000','celestial','inertial'}
out='crf';
case {'m50'}
out='m50';
case {'teme'}
out='teme';
case {'trs','trf','ecf','ecef','itrf','terrestrial','rotating','co-rotating',}
out='trf';
case {'body','satellite','srf'}
out='srf';
otherwise
out='';
end
else
out='';
end
end
function out=isframe(in)
out=~isempty(simpletimeseries.translateframe(in));
end
%% import methods
%NOTICE: the mat-file handling in this method is so that there are mat files duplicating the raw data: one raw file, one mat file. This is not a datastorage-type of structuring the data.
%TODO: consider retiring cut24hrs
function obj=batch_import(filename,varargin)
%additional options, from dependencies:
% - simpletimeseries.import:
% p.addParameter('format','',@ischar);
% - file.load_mat:
% p.addParameter('data_var' ,'out', @ischar);
% - file.save_mat:
% p.addParameter('save_mat', true, @(i) isscalar(i) && islogical(i))
% p.addParameter('data_var','out', @ischar);
% - file.delete_compressed:
% p.addParameter('del_arch', true, @(i) isscalar(i) && islogical(i))
p=machinery.inputParser;
p.addRequired( 'filename', @(i) ischar(i) || iscellstr(i));
p.addParameter('cut24hrs', true, @(i) isscalar(i) && islogical(i))
p.parse(filename,varargin{:})
%unwrap wildcards and place holders (output is always a cellstr)
filename=file.unwrap(filename,varargin{:});
%loop over all files (maybe only one, resolved by cells.scalar)
for i=1:numel(filename)
disp([' reading data from file ',filename{i}])
%read the data from a single file
obj_now=simpletimeseries.import(filename{i},varargin{:});
%skip if empty
if isempty(obj_now)
continue
end
%handle cutting data to requested periods
if p.Results.cut24hrs
%determine current day
day_now=datetime(yyyymmdd(obj_now.t(round(obj_now.length/2))),'ConvertFrom','yyyymmdd');
%get rid of overlaps
obj_now=obj_now.trim(day_now,day_now+hours(24)-obj_now.step);
end
%append or initialize
if ~exist('obj','var')
obj=obj_now;
else
try
obj=obj.append(obj_now);
catch
obj=obj.augment(obj_now);
end
end
end
%in case there are no files, 'filename' will be empty and the loop will be skipped
if ~exist('obj','var')
obj=[];
end
end
function obj=import(filename,varargin)
%additional options, from dependencies
% - file.load_mat:
% p.addParameter('data_var' ,'out', @ischar);
% - file.save_mat:
% p.addParameter('save_mat', true, @(i) isscalar(i) && islogical(i))
% p.addParameter('data_var','out', @ischar);
% - file.delete_compressed:
% p.addParameter('del_arch', true, @(i) isscalar(i) && islogical(i))
p=machinery.inputParser;
p.addParameter( 'format','',@ischar);
p.parse(varargin{:})
%resolve scalar cell
filename=cells.scalar(filename,'get');
%make sure this is a filename
assert(ischar(filename),['Input ''filename'' must be of class ''char'', not ''',...
class(filename),'''; consider using the simpletimeseries.batch_import method.'])
%try to load mat file
[obj,loaded_flag]=file.load_mat(filename,...
'default_dir',simpletimeseries.parameters('value','data_dir'),...
'data_var','obj',...
varargin{:}...
);
%if loaded something, we're done
if loaded_flag, return, end
%enforce format given as argument
if ~isempty(p.Results.format)
format=p.Results.format;
else
%split into parts and propagate the extension as the format
[~,~,format]=fileparts(filename);
end
%call format interface aggregator
obj=simpletimeseries.import_format(filename,format);
%possibly save this object as a mat file
file.save_mat(obj,filename,'data_var','obj',varargin{:});
%possibly delete uncompressed file
file.delete_uncompressed(filename,varargin{:});
end
function obj=import_format(filename,format)
%branch on extension/format ID
switch format
case 'seconds'
%define data cols
data_cols=2:4;
%load the data
raw=file.textscan(filename,'%f %f %f %f');
%get the labels (from the header)
labels={'RL06_grav','RL05_grav','res_grav'};
%build units
units=cell(size(data_cols));
units(:)={'m/s'};
t=datetime([2000 01 01 0 0 0])+seconds(raw(:,1));
%building object
obj=simpletimeseries(t,raw(:,data_cols),...
'format','datetime',...
'units',units,...
'labels', labels,...
'timesystem','gps',...
'descriptor',['KBR postfits ',filename]...
);
case {'TAS-2','TAS-12'}
%define data cols
data_cols=2:1+str2double(strrep(format,'TAS-',''));
%load the data
raw=file.textscan(filename,'%f %f %f %f');
switch numel(data_cols)
case 2
labels={'SS_DistanceMeasurementError','NonGravDiffAccelMeasErr'};
units={'m','m/s^2'};
case 12
labels={...
'TestMass2_LinAcc_Noise_X','TestMass2_LinAcc_Noise_Y','TestMass2_LinAcc_Noise_X',...
'TestMass3_LinAcc_Noise_X','TestMass3_LinAcc_Noise_Y','TestMass3_LinAcc_Noise_X',...
'TestMass5_LinAcc_Noise_X','TestMass5_LinAcc_Noise_Y','TestMass5_LinAcc_Noise_X',...
'TestMass6_LinAcc_Noise_X','TestMass6_LinAcc_Noise_Y','TestMass6_LinAcc_Noise_X',...
};
units=cell(size(labels));
units(:)={'m/s^2'};
end
t=datetime([2000 01 01 0 0 0])+seconds(raw(:,1));
%building object
obj=simpletimeseries(t,raw(:,data_cols),...
'format','datetime',...
'units',units,...
'labels', labels,...
'timesystem','gps',...
'descriptor',[format,' ',filename]...
);
otherwise
success=false;
%grace.m
[obj,success]=machinery.trycatch(success,'grace:BadImportFormat',@grace.import_format,{filename,format});
%add additional class calls to translatesat (using the same structure above)
%check something worked
assert(success,['Cannot handle files of type ''',format,'''.'])
end
end
function obj=GRACEaltitude(varargin)
p=machinery.inputParser;
p.addParameter('datafile',file.resolve_home(fullfile('~','data','grace','altitude','GRACE.altitude.dat')));
p.parse(varargin{:});
obj=simpletimeseries.import(p.Results.datafile,...
'format','mjd',...
'cut24hrs',false...
);
end
%% utilities
function out=list(start,stop,period)
p=machinery.inputParser;
p.addRequired( 'start', @(i) isscalar(i) && isdatetime(i));
p.addRequired( 'stop', @(i) isscalar(i) && isdatetime(i));
p.addRequired( 'period', @(i) isscalar(i) && isduration(i));
p.parse(start,stop,period)
out=datetime([],[],[]);
for i=1:ceil((stop-start)/period)+1
out(i)=start+(i-1)*period;
end
%trim end if after stop date
if out(end)>stop
out=out(1:end-1);
end
end
function out=t_mergev(obj_list)
for i=2:numel(obj_list)
obj_list{1}=obj_list{1}.t_merge(obj_list{i}.t);
end
out=obj_list{1}.t;
end
%% constructors
function out=one(t,width,varargin)
out=simpletimeseries(t(:),ones(numel(t),width),'descriptor','unit',varargin{:});
end
function out=zero(t,width,varargin)
out=simpletimeseries(t(:),zeros(numel(t),width),'descriptor','zero',varargin{:});
end
function out=randn(t,width,varargin)
out=simpletimeseries(t(:),randn(numel(t),width),'descriptor','randn',varargin{:});
end
function out=sinusoidal(t,w,varargin)
y=cell2mat(arrayfun(@(i) sin((t(:)-t(1))*pi/i),w,'UniformOutput',false));
out=simpletimeseries(t(:),y,'descriptor','sinusoidal',varargin{:});
end
%% general test for the current object
function test(method,l,w)
if ~exist('method','var') || isempty(method)
method='all';
end
if ~exist('l','var') || isempty(l)
l=1000;
end
if ~exist('w','var') || isempty(w)
w=3;
end
%get common parameters
args=varargs(simpledata.test_parameters('args',l,w));
%need to replace x_units
args.x_units='days';
now=juliandate(datetime('now'),'modifiedjuliandate');
t=datetime(now, 'convertfrom','modifiedjuliandate'):...
datetime(now+round(l)-1,'convertfrom','modifiedjuliandate');
%init object
a=simpletimeseries(...
t,...
simpledata.test_parameters('y_all',l,w),...
'mask',simpledata.test_parameters('mask',l,w),...
args.varargin{:}...
);
switch method
case 'all'
%TODO: add 'component_split'
for i={'calibrate_poly','median','fill-resample','append','trim','resample','extend','slice','pardecomp'}
simpletimeseries.test(i{1},l);
end
case 'component_split'
a=simpletimeseries.randn(t,w,args.varargin{:});
a=a.scale(0.05);
idx=2:4;
for i=1:numel(idx)
as=simpletimeseries.sinusoidal(t,days(l/3)/idx(i)*ones(1,w),args.varargin{:});
as=as.scale(rand(1,w));
a=a+as;
end
a.descriptor='original';
i=0;c=1;
i=i+1;h{i}=plotting.figure('visible','on');
subplot(2,2,1)
a.plot('column',c)
legend off
subplot(2,2,2)
[out,res,J,segs]=a.component_ampl(days(2*l/5));
for si=1:numel(segs)
segs{si}.plot('column',c)
end
title('segmented'); legend off
subplot(2,2,3)
plot(out(:,1))
title('average and repeated'); legend off
subplot(2,2,4)
plot(res(:,1))
title(['residuals (relative norm=',num2str(J),')']); legend off
%TODO: finish this test
case 'calibrate_poly'
a=simpletimeseries.sinusoidal(t,days(l./(1:w)),args.varargin{:});
bn=simpletimeseries.randn(t,w,args.varargin{:});
a=a+bn.scale(0.05);
b=a.scale(rand(1,w))+bn.scale(0.1)+ones(a.length,1)*randn(1,w);
c=a.calibrate_poly(b);
figure
a.plot('columns',1)
b.plot('columns',1)
c.plot('columns',1)
legend('uncal','target','cal')
title(method)
case 'median'
figure
a.plot( 'columns',1,'line',{'o-'});
a.medfilt(10).plot('columns',1,'line',{'+-'});
a.median( 10).plot('columns',1,'line',{'x-'});
legend('origina','median','medfilt')
title(method)
case 'fill-resample'
%TODO: make this test more illustrative
b=a.resample;
c=a.fill;
figure;
a.plot('columns',1,'line',{'o-'})
b.plot('columns',1,'line',{'+-'})
c.plot('columns',1,'line',{'x-'})
legend('original','fill','resample')
title(method)
case 'append'
b=a.append(...
simpletimeseries(...
a.stop+(round(l/3):round(4*l/3)-1),...
simpledata.test_parameters('y_all',l,w),...
'mask',simpledata.test_parameters('mask',l,w),...
args.varargin{:}...
)...
);
figure;
a.plot('columns',1,'line',{'o-'})
b.plot('columns',1,'line',{'+-'})
legend('original','appended')
title(method)
case 'trim'
b=a.trim(...
datetime(now+round(l*0.3),'convertfrom','modifiedjuliandate'),...
datetime(now+round(l*0.7),'convertfrom','modifiedjuliandate')...
);
figure;
a.plot('columns',1,'line',{'o-'})
b.plot('columns',1,'line',{'+-'})
legend('original','trimmed')
title(method)
case 'resample'
b=a.resample(...
days(0.8) ...
);
figure;
a.plot('columns',1,'line',{'o-'})
b.plot('columns',1,'line',{'+-'})
legend('original','resampled')
title(method)
case 'extend'
b=a.extend(...
round(l/4) ...
).extend(...
-round(l/2) ...
);
figure;
a.plot('columns',1,'line',{'o-'})
b.plot('columns',1,'line',{'+-'})
legend('original','extended')
title(method)
case 'slice'
b=a.slice(...
datetime(now+round( l/5),'convertfrom','modifiedjuliandate'),...
datetime(now+round( l/2),'convertfrom','modifiedjuliandate')...
);
figure;
a.plot('columns',1,'line',{'o-'})
b.plot('columns',1,'line',{'+-'})
legend('original','sliced')
title(method)
case 'pardecomp'
a=simpletimeseries(...
t,...
simpledata.test_parameters('y_all_T',l,w),...
'mask',simpledata.test_parameters('mask',l,w),...
args.varargin{:}...
);
%test parameters
poly_coeffs=simpledata.test_parameters('y_poly_scale');
sin_periods=simpledata.test_parameters('T',l);
sin_coeffs=simpledata.test_parameters('y_sin_scale');
cos_coeffs=simpledata.test_parameters('y_cos_scale');
%inform
disp(['poly_coeffs : ',num2str(poly_coeffs(:)')])
disp(['sin_periods : ',num2str(sin_periods(:)')])
disp(['sin_coeffs : ',num2str(sin_coeffs(:)')])
disp(['cos_coeffs : ',num2str(cos_coeffs(:)')])
%derived parameters
[b,pd_set]=a.pardecomp(...
'np',numel(poly_coeffs),...
'T',sin_periods,...
'timescale','days'...
);
figure;
a.plot('columns',1,'line',{'o-'})
b.plot('columns',1,'line',{'+-'})
legend('original','pardecomp')
title(method)
disp(pardecomp.table(pd_set,'tablify',true))
case 'x_units'
t=datetime('now')-years(10:-1:0);
a=simpletimeseries.zero(t,2,'x_units','seconds');
b=simpletimeseries.zero(t,2,'x_units','years');
disp('First column was created with x_units=seconds and second column with x_units=years')
disp('t-domains:')
disp([a.t,b.t])
disp('x-domains:')
disp([a.x,b.x])
assert(all(a.t==b.t),'test failed')
case {'minus','minus-scalar'}
switch method
case 'minus', t=datetime('now')-years(10:-1:0);
case 'minus-scalar', t=datetime('now');
end
a=simpletimeseries.one(t,2,'x_units','seconds','epoch',datetime('now'));
b=simpletimeseries.one(t,2,'x_units','years', 'epoch',datetime('now')+days(1));
c=a-b;
disp('First column: x_units=seconds,epoch=now')
disp('Second column: x_units=year ,epoch=now+1 day')
disp('Third column: first - second objects')
disp('epochs:')
disp(datestr([a.epoch,b.epoch,c.epoch]))
disp('x_units:')
disp([a.x_units,' ',b.x_units,' ',c.x_units])
disp('t-domains:')
disp([a.t,b.t,c.t])
disp('x-domains:')
disp([a.x,b.x,c.x])
disp('time2num:')
disp([...
simpletimeseries.time2num(a.t,a.epoch,a.x_units),...
simpletimeseries.time2num(b.t,b.epoch,b.x_units),...
simpletimeseries.time2num(c.t,c.epoch,c.x_units)...
])
disp('num2time:')
disp([...
simpletimeseries.num2time(a.x,a.epoch,a.x_units),...
simpletimeseries.num2time(b.x,b.epoch,b.x_units),...
simpletimeseries.num2time(c.x,c.epoch,c.x_units)...
])
assert(all(c.y(:)==0),'test failed')
end
end
end
methods
%% constructor
function obj=simpletimeseries(t,y,varargin)
% input parsing
p=machinery.inputParser;
p.addRequired( 't' ); %this can be char, double or datetime
p.addRequired( 'y', @(i) simpledata.valid_y(i));
%create argument object, declare and parse parameters, save them to obj
[v,p]=varargs.wrap('parser',p,'sources',{simpletimeseries.parameters('obj')},'mandatory',{t,y},varargin{:});
% get datetime
[t,f]=time.ToDateTime(t,p.Results.format);
%check if epoch and/or x_units are given
if time.iszero(v.epoch); v.epoch=t(1); end
%make sure the x_units are relevant to time
v.x_units=time.translate_units(v.x_units);
%call superclass (create empty object, assignment comes later)
obj=obj@simpledata(simpletimeseries.time2num(t,v.epoch,v.x_units),y,...
v.varargin{:}...
);
% save the arguments v into this object
obj=v.save(obj,{'t','y'});
%save input format (can be different from p.Results.format)
obj.format=f;
end
function obj=assign(obj,y,varargin)
p=machinery.inputParser;
p.addRequired( 'y' , @(i) simpledata.valid_y(i));
p.addParameter('t' ,obj.t, @(i) simpletimeseries.valid_t(i));
p.addParameter('epoch' ,obj.epoch,@(i) simpletimeseries.valid_epoch(i));
% parse it
p.parse(y,varargin{:});
% simpler names
presence=simpletimeseries.ispresent(p);
%if 't' is not present, then pass it on to simple data
if ~presence.t
obj=assign@simpledata(obj,y,varargin{:});
%if there is no 'x', then this is a simple assignment of y
if ~presence.x; return; end
end
%if 't' is present, assign it to 'x'
if presence.t
obj=assign@simpledata(obj,y,'x',obj.t2x(p.Results.t),varargin{:});
end
%update epoch (needed to derive obj.t from obj.x)
%NOTICE: don't use obj.epoch= here, because at init that is not possible
if ~isempty(p.Results.epoch)
obj.epochi=p.Results.epoch;
elseif presence.t
obj.epochi=p.Results.t(1);
else
error('cannot derive epoch without either input ''epoch'' or ''t''.')
end
%update local records
obj.step=simpletimeseries.timestep(obj.t);
%sanitize (don't pass t, since it can be deliberatly changed)
obj.check_st
end
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
%call superclass
obj=copy_metadata@simpledata(obj,obj_in,[simpletimeseries.parameters('list');more_parameters(:)],less_parameters);
end
function out=metadata(obj,more_parameters)
if ~exist('more_parameters','var')
more_parameters={};
end
%call superclass
out=metadata@simpledata(obj,[simpletimeseries.parameters('list');more_parameters(:)]);
end
%the varargin method can be called directly
%% info methods
function print(obj,tab)
if ~exist('tab','var') || isempty(tab)
tab=12;
end
%parameters
relevant_parameters={'step','format','epoch','start','stop','timesystem'};
for i=1:numel(relevant_parameters)
obj.disp_field(relevant_parameters{i},tab);
end
%print superclass
print@simpledata(obj,tab)
end
function out=stats(obj,varargin)
p=machinery.inputParser;
p.addParameter('period', seconds(inf), @isduration);
p.addParameter('overlap',seconds(0), @isduration);
p.addParameter('mode', 'struct', @ischar);
% parse it
p.parse(varargin{:});
% call upstream method if period is infinite
if ~isfinite(p.Results.period)
out=stats@simpledata(obj,varargin{:});
return
end
% separate time series into segments
ts=segmentedfreqseries.time_segmented(obj.t,p.Results.period,p.Results.overlap);
% derive statistics for each segment
s.msg=['deriving segment-wise statistics for ',str.clean(obj.descriptor,'file')]; s.n=numel(ts);
for i=1:numel(ts)
%call upstream procedure
dat(i)=stats@simpledata(obj.trim(ts{i}(1),ts{i}(end)),varargin{:},'mode','struct'); %#ok<AGROW>
% inform about progress
s=time.progress(s,i);
end
% add time stamps
for i=1:numel(ts)
dat(i).t=mean(ts{i});
end
% unwrap data
fn=fieldnames(dat);
for i=1:numel(fn)
%skip time
if strcmp(fn{i},'t')
continue
end
%resolving units
switch lower(fn{i})
case {'min','max','mean','std','rms','meanabs','stdabs','rmsabs'}
units=obj.units;
case {'length','gaps'}
units=repmat({' '},1,obj.width);
end
out.(fn{i})=simpletimeseries(...
transpose([dat.t]),...
transpose(reshape([dat.(fn{i})],size(dat(1).(fn{i}),2),numel(dat))),...
'format','datetime',...
'labels',obj.labels,...
'timesystem',obj.timesystem,...
'units',units,...
'descriptor',[fn{i},' ',str.clean(obj.descriptor,'file')]...
);
end
end
function out=stats2(obj1,obj2,varargin)
p=machinery.inputParser;
p.addParameter('period', seconds(inf), @isduration); %30*max([obj1.step,obj2.step])
p.addParameter('overlap',seconds(0), @isduration);
% parse it
p.parse(varargin{:});
% call upstream method if period is infinite
if ~isfinite(p.Results.period)
out=stats2@simpledata(obj1,obj2,varargin{:});
return
end
% separate time series into segments
ts=segmentedfreqseries.time_segmented(...
simpledata.union(obj1.t,obj2.t),...
p.Results.period,...
p.Results.overlap...
);
% derive statistics for each segment
s.msg=['deriving segment-wise statistics for ',...
str.clean(obj1.descriptor,'file'),' and ',...
str.clean(obj2.descriptor,'file')...
]; s.n=numel(ts);
for i=1:numel(ts)
%call upstream procedure
dat(i)=stats2@simpledata(...
obj1.trim(ts{i}(1),ts{i}(end)),...
obj2.trim(ts{i}(1),ts{i}(end)),...
'mode','struct',varargin{:}...
); %#ok<AGROW>
% inform about progress
s=time.progress(s,i);
end
% add time stamps
for i=1:numel(ts)
dat(i).t=mean(ts{i});
end
% unwrap data and build timeseries obj
fn=fieldnames(dat);
for i=1:numel(fn)
%skip time
if strcmp(fn{i},'t')
continue
end
%resolving units
units=cell(1,obj1.width);
for j=1:numel(units)
switch lower(fn{i})
case 'cov'
units{j}=[obj1.units{j},'.',obj2.units{j}];
case {'corrcoef','length'}
units{j}=' ';
end
end
out.(fn{i})=simpletimeseries(...
[dat.t],...
transpose(reshape([dat.(fn{i})],size(dat(1).(fn{i}),2),numel(dat))),...
'format','datetime',...
'labels',obj1.labels,...
'timesystem',obj1.timesystem,...
'units',units,...
'descriptor',[fn{i},' ',str.clean(obj1.descriptor,'file'),'x',str.clean(obj2.descriptor,'file')]...
);
end
end
function out=str(obj)
out=[datestr(obj.start),' -> ',datestr(obj.stop),' (',num2str(obj.nr_gaps),' gaps)'];
end
%% t methods
function x_out=t2x(obj,t_now)
if ~exist('t_now','var')
t_now=obj.t;
end
if simpletimeseries.valid_t(t_now)
x_out=simpletimeseries.time2num(t_now,obj.epoch,obj.x_units);
else
x_out=t_now;
end
end
function t_out=x2t(obj,x_now)
if ~exist('x_now','var')
x_now=obj.x;
end
switch class(x_now)
case 'datetime'; t_out=x_now;
otherwise
if simpledata.valid_x(x_now)
t_out=simpletimeseries.num2time(x_now,obj.epoch,obj.x_units);
else
t_out=x_now;
end
end
end
function obj=set.t(obj,t_now)
%NOTICE: this blindly changes the time domain!
obj=obj.assign(obj.y,'t',t_now);
obj.epoch=t_now(1);
end
function obj=set_t(obj,t_now)
obj.t=t_now;
end
function out=get.t(obj)
if isempty(obj.x)
out=[];
else
out=obj.x2t(obj.x);
end
end
function out=isx1zero(obj)
%handle empty object
if isempty(obj.x)
out=true;
return
end
%this function checks that:
%if obj.x(1) is zero, then obj.epoch and obj.t(1) are equal
test=[obj.x(1)==0,obj.start==obj.epoch];
%sanity
if test(1)~=test(2)
error([...
'obj.x(1)=',num2str(obj.x(1)),10,...