forked from jgte/orb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpletimeseries.m
More file actions
2748 lines (2720 loc) · 98.7 KB
/
simpletimeseries.m
File metadata and controls
2748 lines (2720 loc) · 98.7 KB
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={...
'units', {''}, @iscellstr;... %this parameters is not a property of this object:
%it gets translated into y_units at init
'format', 'modifiedjuliandate',@ischar;...
't_tol', 2e-6, @num.isscalar;...
'timesystem','utc', @ischar;...
'debug', false, @(i) islogical(i) && isscalar(i);...
'data_dir' file.orbdir('data'), @ischar;...
};
%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'};
%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
debug
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)
assert(isduration(in) || isnumeric(in),['Cannot handle inputs of class ',class(in),'.'])
out=seconds(in);
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)
if ~exist('epoch','var') || isempty(epoch)
epoch=in(1);
end
if isfinite(epoch)
out=simpletimeseries.timescale(in-epoch);
elseif any(isfinite(in))
out=simpletimeseries.timescale(in-min(in));
else
out=Inf(size(in));
end
end
function out=num2time(in,epoch)
if ~exist('epoch','var') || isempty(epoch)
error([mfilename,': need input ''epoch''.'])
end
out=epoch+simpletimeseries.timescale(in);
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([mfilename,': 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([mfilename,': 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 isprop(in,'t')
out=simpletimeseries(in.t,in.y,in.metadata{:});
elseif isprop(in,'x')
out=simpletimeseries(in.x,in.y,in.metadata{:});
else
error('Cannot find ''t'' or ''x''. Cannot continue.')
end
end
end
function out=timestep(in,varargin)
p=inputParser;
p.KeepUnmatched=true;
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);
% parse it
p.parse(in,varargin{:});
%handle singularities
switch numel(in)
case 0
error([mfilename,': cannot handle empty time stamps'])
case 1
out=0;
return
end
%get numeric diff of time
tdiff=simpletimeseries.timescale(diff(in));
%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([mfilename,': 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([mfilename,': 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([mfilename,': final timestep is ',char(out),'.'])
end
end
function v=fix_interp_over_gaps_narrower_than(v)
if ~iscell(v)
error([mfilename,': 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
%general test for the current object
function out=test(l,w)
if ~exist('l','var') || isempty(l)
l=1000;
end
if ~exist('w','var') || isempty(w)
w=3;
end
%test current object
args=simpledata.test_parameters('args',l,w);
now=juliandate(datetime('now'),'modifiedjuliandate');
t=datetime(now-l,'convertfrom','modifiedjuliandate'):...
datetime(now+l,'convertfrom','modifiedjuliandate');
a=simpletimeseries.randn(t,w,args{:});
a=a.scale(0.05);
idx=2:4;
for i=1:numel(idx)
as=simpletimeseries.sin(t,days(l/3)/idx(i)*ones(1,w),args{:});
as=as.scale(rand(1,w));
a=a+as;
end
a.descriptor='original';
a.component_split_plot(days(l/3)./idx,'columns',1);
return
i=0;c=1;
i=i+1;h{i}=figure('visible','on');
a.plot('column',c)
[m,s,segs]=a.component_ampl(days(2*l/5));
for si=1:numel(segs)
i=i+1;h{i}=figure('visible','on');
segs{si}.plot('column',c)
end
i=i+1;h{i}=figure('visible','on');
plot(m(:,1))
title('mean')
i=i+1;h{i}=figure('visible','on');
plot(s(:,1))
title('std')
return
i=0;
bn=simpletimeseries.randn(t,w,args{:});
bs=simpletimeseries.sin(t,days(l./(1:w)),args{:});
b=bs.scale(rand(1,w))+bn.scale(0.1)+ones(bs.length,1)*randn(1,w);
c=a.calibrate_poly(b);
i=i+1;h{i}=figure('visible','on');
for i=1:w
subplot(1,w,i)
a.plot('column',i)
b.plot('column',i)
c.plot('column',i)
legend('uncal','target','cal')
title(['column ',num2str(i)])
end
return
lines1=cell(w,1);lines1(:)={'-o'};
lines2=cell(w,1);lines2(:)={'-x'};
lines3=cell(w,1);lines3(:)={'-+'};
i=i+1;h{i}=figure('visible','on');
a.plot('line',lines1)
a.median(10).plot('line',lines2);
a.medfilt(10).plot('line',lines3);
legend('origina','median','medfilt')
title('median (operation not saved)');
b=a.resample;
a=a.fill;
i=i+1;h{i}=figure('visible','off');
a.plot('line',lines1); hold on; b.plot('title','fill','line',lines2)
legend('fill','resample')
a=a.append(...
simpletimeseries(...
a.stop+(round(l/3):round(4*l/3)-1),...
simpledata.test_parameters('y',l,w),...
'mask',simpledata.test_parameters('mask',l,w),...
args{:}...
)...
);
i=i+1;h{i}=figure('visible','off'); a.plot('title','append')
a=a.trim(...
datetime(now+round(-l/2),'convertfrom','modifiedjuliandate'),...
datetime(now+round( l/2),'convertfrom','modifiedjuliandate')...
);
i=i+1;h{i}=figure('visible','off'); a.plot('title','trim')
b=a.resample(...
days(0.8) ...
);
i=i+1;h{i}=figure('visible','off');
a.plot('line',lines1); hold on; b.plot('title','resampled','line',lines2)
legend('original','resampled')
a=a.extend(...
100 ...
).extend(...
-100 ...
);
i=i+1;h{i}=figure('visible','off'); a.plot('title','extend')
a=a.slice(...
datetime(now+round(-l/5),'convertfrom','modifiedjuliandate'),...
datetime(now+round( l/5),'convertfrom','modifiedjuliandate')...
);
i=i+1;h{i}=figure('visible','off'); a.plot('title','delete')
a=simpledata.test_parameters('all_T',l,w);
i=i+1;h{i}=figure('visible','off'); a.plot('title', 'parametric decomposition','columns',1)
%decompose
out=pardecomp.split(a,...
'np',numel(simpledata.test_parameters('y_poly_scale')),...
't0',a.x(round(a.length/2)),...
'T',simpledata.test_parameters('T',l)...
);
fn=fields(out);tot=[];legend_str={};
for i=1:numel(fn);
if ~isempty(strfind(fn{i},'ts_'))
legend_str{end+1}=fn{i};
out.(fn{i}).plot('columns',1)
if isempty(tot)
tot=out.(fn{i});
else
tot=tot+out.(fn{i});
end
end
end
tot.plot('columns',1)
legend_str=strrep(legend_str,'_','\_');
legend('original',legend_str{:},'sum')
a=simpledata.test_parameters('all_T',l,w);
i=i+1;h{i}=figure('visible','off'); a.plot('title', 'parametric reconstruction','columns',1,'line',{'x-'})
%reconstruct
b=pardecomp.join(out,transpose(0:1.2:round(1.2*l)-1));
b.plot('columns',1,'line',{'o-'})
legend('original','reconstructed')
for i=numel(h):-1:1
set(h{i},'visible','on')
end
end
%% internally-consistent naming of satellites
function out=translatesat(in)
%search for satellite name
switch lower(in)
case {'champ','ch'}
out='ch';
case {'grace-a','gracea','grace a','ga'}
out='ga';
case {'grace-b','graceb','grace b','gb'}
out='gb';
case {'grace-c','gracec','grace c','gc'}
out='gc';
case {'grace-d','graced','grace d','gd'}
out='gd';
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
error([mfilename,': cannot handle satellite ''',in,'''.'])
end
end
function out=translatesatname(in)
%search for satellite name
switch simpletimeseries.translatesat(in)
case 'ch'; out='CHAMP';
case 'ga'; out='GRACE-A';
case 'gb'; out='GRACE-B';
case 'gc'; out='GRACE-C';
case 'gd'; out='GRACE-D';
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
error([mfilename,': cannot handle 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
%% specific data name-handling methods
function sat=grace_l1b_sat(satname)
switch simpletimeseries.translatesat(satname)
case 'ga'; sat='A';
case 'gb'; sat='B';
case 'gc'; sat='C';
case 'gd'; sat='D';
otherwise
error([mfilenane,': cannot handle GRACE satname ''',satname,'''.'])
end
end
function satname=grace_l1b_satname(sat)
switch attitude.translatesat(sat)
case 'A'; satname='ga';
case 'B'; satname='gb';
case 'C'; satname='gc';
case 'D'; satname='gd';
otherwise
error([mfilenane,': cannot handle GRACE sat ''',sat,''', debug needed!'])
end
end
function version=grace_l1b_version(product)
switch product
case {'KBR1B'|'SCA1B'}
version='03';
case {'AHK1B','GNV1B','MAS1B','THR1B','CLK1B','GPS1B',...
'IHK1B','MAG1B','TIM1B','TNK1B','USO1B','VSL1B'}
version='02';
otherwise
error(['Cannot handle GRACE product ''',product,'''.'])
end
end
%NOTICE: data_dir is the top-most data dir, without specifying the satellite, data, etc
function filename=grace_l1b_filename(product,satname,start,version,data_dir)
if ~exist('version','var') || isempty(version)
version=simpletimeseries.grace_l1b_version(product);
end
%NOTICE: empty data_dir gets handled in grace_dirname
if ~exist('data_dir','var')
data_dir='';
end
sat=simpletimeseries.grace_l1b_sat(satname);
date=time.FromDateTime(start,'yyyy-MM-dd');
dirname=simpletimeseries.grace_l1b_dirname(start,version,data_dir);
filename=fullfile(dirname,[product,'_',date,'_',sat,'_',version,'.dat']);
end
%passes data_dir to dirname unless it is non-existing, empty or '.' (in which case, it
%builds the default directory structure of the GRACE data dir
function dirname=grace_l1b_dirname(start,version,data_dir)
if ~exist('data_dir','var') ...
|| isempty(data_dir) ...
|| strcmp(data_dir,'.') ...
|| strcmp(data_dir,simpletimeseries.parameters('value','data_dir'))
year=time.FromDateTime(start,'yyyy');
dirname=fullfile(simpletimeseries.parameters('value','data_dir'),...
'grace','L1B','JPL',['RL',version],year);
else
dirname=data_dir;
end
end
%GRACE L1B file names must be: <product>_yyyy-mm-dd_<sat>_<version>.dat
function [product,sat,date,version,dirname]=strings_from_grace_l1b_filename(filename)
%split input
[d,f]=fileparts(filename);
%split name of file
fp=strsplit(f,'_');
product=fp{1};
date=fp{2};
sat=fp{3};
version=fp{4};
dirname=simpletimeseries.grace_l1b_dirname(time.ToDateTime(date,'yyyy-MM-dd'),version,d);
end
function [product,satname,start,version,dirname]=details_from_grace_l1b_filename(filename)
%get strings
[product,sat,date,version,dirname]=strings_from_grace_l1b_filename(filename);
%convert
start=time.ToDateTime(date,'yyyy-MM-dd');
satname=simpletimeseries.grace_l1b_satname(sat);
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=import(filename,varargin)
p=inputParser;
p.KeepUnmatched=true;
p.addParameter( 'save_mat', true, @(i) isscalar(i) && islogical(i))
p.addParameter( 'cut24hrs', true, @(i) isscalar(i) && islogical(i))
p.addParameter( 'del_arch', true, @(i) isscalar(i) && islogical(i))
p.addParameter( 'format', '', @ischar);
p.parse(varargin{:})
%unwrap wildcards and place holders (output is always a cellstr)
filename=file.unwrap(filename,varargin{:});
%if argument is a cell string, then load all those files
if iscellstr(filename)
for i=1:numel(filename)
disp([mfilename,': 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
return
end
%split into parts and propagate the extension as the format
[d,f,ext]=fileparts(filename);
%plug data dir, if no dir is given
if isempty(d) || strcmp(d,'.')
d=simpletimeseries.parameters('value','data_dir');
end
%check if mat file is available
datafile=fullfile(d,[f,'.mat']);
if file.exist(datafile)
load(datafile)
%sanity on the loaded data
if ~exist('obj','var')
error([mfilename,': expecting to load variables ''obj'' from file ',datafile,'.'])
end
%we're done
return
end
%assume format is given by extension
format=ext;
%some files have the format ID in front
for i={...
'ACC1B','AHK1B','GNV1B','KBR1B','MAS1B','SCA1B','THR1B','CLK1B',...
'GPS1B','IHK1B','MAG1B','TIM1B','TNK1B','USO1B','VSL1B'...
}
if ~isempty(regexp(filename,i{1},'once'))
if strcmp(ext,'.asc')
format=[i{1},'-ascii'];
else
format=i{1};
end
break
end
end
%enforce format given as argument
if ~isempty(p.Results.format)
format=p.Results.format;
end
%branch on extension/format ID
switch format
% --------------
% CSR formats
% --------------
case '.resid'
fid=file.open(filename);
raw = textscan(fid,'%f %f %f %f %f %f %f','delimiter',' ','MultipleDelimsAsOne',1,'Headerlines',1);
fclose(fid);
%building time domain
t=time.utc2gps(datetime(raw{1},...
'convertfrom','epochtime',...
'epoch','2000-01-01'...
));
%building data domain
y=[raw{5:7}];
%determine coordinate
coords={'AC0X','AC0Y','AC0Z'};
idx=cells.strfind(filename,coords);
%sanity
assert(sum(idx)==1,[mfilename,': the name for .resid files must include (one of) AC0X, AC0Y or AC0Z, not ''',...
filename,'''.'])
%building object
obj=simpletimeseries(t,y,...
'format','datetime',...
'y_units',{'m^2','m^2','m^2'},...
'labels', {coords{idx},[coords{idx},'D'],[coords{idx},'Q']},...
'timesystem','gps',...
'descriptor',['model response from file ',filename]...
);
case '.sigma'
fid=file.open(filename);
raw = textscan(fid,'%d %d %d %d %d %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f','delimiter',' ','MultipleDelimsAsOne',1);
fclose(fid);
%building time domain
t=datetime([double([raw{1:5}]),raw{6}]);
%building data domain
y=[raw{7:end}];
%building object
obj=simpletimeseries(t,y,...
'format','datetime',...
'y_units',{'m','m','m','s','m^2','m^2','m^2','s^2','m^2','m^2','ms','m^s','ms','ms'},...
'labels', {'x','y','z','t','xx', 'yy', 'zz', 'tt', 'xy', 'xz', 'xt','yz', 'yt','zt'},...
'timesystem','utc',...
'descriptor',['kinematic orbit from file ',filename]...
);
case '.GraceAccCal'
fmt='';
if ~isempty(regexp(filename,'AC0[XYZ]\d?\.aak','once')) || ~isempty(regexp(filename,'AC0[XYZ]\d?\.accatt','once'))
% 2002 04 05 2002.4.4. 23.59.47.00000000 1498260002 0.2784215319157E-07
fmt='%d %d %d %s %s %d %f';
units={'m/s^2',''};
labels={str.clean(filename,{'file','grace','.'}),'Job ID','arc start'};
time_fh=@(raw) time.utc2gps(...
datetime(...
strcat(...
strrep(cellfun(@(x) [x(1:end-1),' '],raw{4},'UniformOutput',false),'.','/'),...
strrep(strrep(raw{5},'.00000000',''),'.',':')...
),'InputFormat','yyyy/MM/dd HH:mm:ss'...
)...
);
data_fh=@(raw) [raw{7},double(raw{6})];
timesystem='gps';
sanity_check=@(raw) true;
end
if ~isempty(regexp(filename,'AC0[XYZ][QD]\d?\.aak','once')) || ~isempty(regexp(filename,'AC0[XYZ][QD]\d?\.accatt','once'))
% 2002 04 05 2002.4.4. 23.59.47.00000000 1498260002 0.1389481692269E-07 52368.99985
fmt='%d %d %d %s %s %d %f %f';
units={'m/s^2','','MJD days'};
labels={str.clean(filename,{'file','grace','.'}),'Job ID','t_0','arc start'};
time_fh=@(raw) time.utc2gps(...
datetime(...
strcat(...
strrep(cellfun(@(x) [x(1:end-1),' '],raw{4},'UniformOutput',false),'.','/'),...
strrep(strrep(raw{5},'.00000000',''),'.',':')...
),'InputFormat','yyyy/MM/dd HH:mm:ss'...
)...
);
data_fh=@(raw) [raw{7},double(raw{6}),raw{8}];
timesystem='gps';
sanity_check=@(raw) true;
end
if ~isempty(regexp(filename,'AC0[XYZ]\d?\.estim','once')) || ~isempty(regexp(filename,'AC0[XYZ][DQ]\d?\.estim','once'))
% 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
% 2002 04 05 04/05/02 52369 1 0.0 26400.0 1593715 3.774424464092000e-08 -3.585594302740665e-09 3.415865033817934e-08 2.82822E-09 71279987.
fmt='%d %d %d %d/%d/%d %f %d %f %f %d %f %f %f %f %f';
units={'m/s^2','','sec','sec','mjd','','m/s^2'};
labels={str.clean(filename,{'file','grace','.'}),'Job ID','arc duration','arc start','arc t0','arc nr','TBD'};
time_fh=@(raw) datetime(raw{7}+raw{9}/seconds(days(1)),...
'ConvertFrom','modifiedjuliandate'...
);
data_fh=@(raw) [raw{14},double(raw{11}),raw{10},raw{9},time.mjd(time.utc2gps(time.ToDateTime(double(raw{16}),'J2000sec'))),double(raw{8}),double(raw{15})];
timesystem='gps';
sanity_check=@(raw) all(all([ raw{1}-2000==raw{6},raw{2}==raw{4},raw{3}==raw{5}]));
end
if isempty(fmt)
error([mfilename,': cannot handle the GraceAccCal file ''',filename,'''.'])
end
%reading data
fid = file.open(filename);
raw = textscan(fid,fmt,'delimiter',' ','MultipleDelimsAsOne',1);
fclose(fid);
%keep some sanity
assert(sanity_check(raw),['Failed sanity check on ',filename]);
%building time domain
t=time_fh(raw);
%building data domain
y=data_fh(raw);
%sanity
if isempty(t) || isempty(y)
disp([mfilename,': this file has no data ',filename])
obj=[];
else
iter=0;
while any(diff(t)==0)
%loop inits
n0=numel(t);
iter=iter+1;
%need to remove duplicate entries with different job IDs
mask=true(size(t));
for i=2:numel(t)
%get rid of those entries with zero or negative time stamp delta and lower ID
if t(i)<=t(i-1) && mask(i)
if y(i,2) > y(i-1,2)
mask(i-1)=false;
else
mask(i)=false;
end
end
end
t=t(mask);
y=y(mask,:);
disp(['At iter ',num2str(iter),', removed ',num2str(n0-numel(t),'%04d'),' duplicate time entries (',filename,').'])
end
%need to monotonize the data (sometimes the entries are ordered according to arc number and not chronologically)
if any(diff(t)<0)
[t,i]=sort(t);
y=y(i,:);
disp(['Sorted ',num2str(sum(i~=transpose(1:numel(i))),'%04d'),' time entries (',filename,').'])
end
%building object
obj=simpletimeseries(t,y,...
'format','datetime',...
'labels',labels,...
'units',units,...
'timesystem',timesystem,...
'descriptor',filename,...
'monotonize','remove'...
);
end
% --------------
% GRACE L1B formats
% --------------
case 'ACC1B-asc'
obj=load_ACC1B(filename);
case 'AHK1B-asc'
obj=load_AHK1B(filename);
case 'SCA1B-asc'
obj=load_SCA1B(filename);
case {...
'ACC1B','AHK1B','GNV1B','KBR1B','MAS1B','SCA1B','THR1B','CLK1B',...
'GPS1B','IHK1B','MAG1B','TIM1B','TNK1B','USO1B','VSL1B'}
%get particles from filename
[product,sat,date,version,dirname]=...
simpletimeseries.strings_from_grace_l1b_filename(fullfile(d,f));
%define output file
o=fullfile(dirname,[f,'.asc']);
%invoke L1B cat script
com=['~/data/grace/cat-l1b.sh ',...
strrep(date,'-',''),' ',product,' ',sat,' ',version,' JPL > ',o];
disp(com)
%make sure there's a directory for o
if ~exist(dirname,'dir'); mkdir(dirname); end
%issue com
file.system(com,[],true);
%recursive call to retrieve the data
obj=simpletimeseries.import(o,'format',[format,'-asc']);
%NOTICE: the data_dir was changed above, so need to bail to avoid writing a duplicate mat file in the default data_dir
return
case 'grc[AB]_gps_orb_.*\.acc'
%load data
[raw,header]=file.textscan(filename,'%f %f %f %f %f %f %f %f',[],'%');
%retrieve GPS time epoch
header_line='+unitfacor ';
header=strsplit(header,'\n');
for i=1:numel(header)
if strfind(header{i},header_line)
unitfactor=str2double(strrep(header{i},header_line,''));
break
end
end
%building time domain
t=time.ToDateTime(raw(:,1:3),'yeardoysec');
%gather data domain
y=raw(:,5:7)./unitfactor;
%skip empty data files
if isempty(t) || isempty(y)
disp([mfilename,': this file has no data ',filename{i}])
obj=[];
else
%building object
obj=simpletimeseries(t,y,...
'format','datetime',...
'y_units',{'m/s^2','m/s^2','m/s^2'},...
'labels', {'x','y','z'},...
'timesystem','gps',...
'descriptor',strjoin(header,'\n')...
).fill;
end
%flip model upside down if needed
for j=1:size(simpletimeseries.csr_acc_mod_invert_periods,1)
invert_idx=simpletimeseries.csr_acc_mod_invert_periods(j,1) <= t & ...
simpletimeseries.csr_acc_mod_invert_periods(j,2) >= t;
if any(invert_idx)
assert(all(invert_idx),['Expecting all data between ',datestr(t(1)),' and ',datestr(t(end)),' to be withing ',...
'one single inverted period, as defined in ''simpletimeseries.csr_acc_mod_invert_periods''.'])
obj=obj.scale(-1);
end
end
case 'msodp-acc'
error([mfilename,': implementation needed'])
case {'slr-csr','slr-csr-grace','slr-csr-corr'}
%load the header
header=file.header(filename,20);
%branch on files with one or two coefficients
if ~isempty(strfind(header,'C21')) || ~isempty(strfind(header,'C22'))
%2002.0411 2.43934614E-06 -1.40026049E-06 0.4565 0.4247 -0.0056 0.1782 20020101.0000 20020201.0000
file_fmt='%f %f %f %f %f %f %f %f %f';
data_cols=[2 3];
corr_cols=[5 6];
units={'',''};
if isempty(strfind(header,'C21'))
labels={'C2,1','C2,-1'};
else
labels={'C2,2','C2,-2'};
end
else
%2002.0411 -4.8416939379E-04 0.7852 0.3148 0.6149 20020101.0000 20020201.0000
file_fmt='%f %f %f %f %f %f %f';
data_cols=2;
corr_cols=5;
units={''};
if ~isempty(strfind(header,'C20')); labels={'C2,0'}; end
if ~isempty(strfind(header,'C40')); labels={'C4,0'}; end
end
raw=file.textscan(filename,file_fmt);
%build the time domain
t=datetime([0 0 0 0 0 0])+years(raw(:,1));
%building data domain
switch format
case 'slr-csr'
y=raw(:,data_cols);
case 'slr-csr-grace'
y=raw(:,data_cols)-raw(:,corr_cols)*1e-10;
case 'slr-csr-corr'
y=raw(:,corr_cols)*1e-10;
end
%building object
obj=simpletimeseries(t,y,...
'format','datetime',...
'y_units',units,...
'labels', labels,...
'timesystem','gps',...
'descriptor',['SLR Stokes coeff. from ',filename]...
);
case 'slr-csr-Cheng'
%define data cols
data_cols=3:9;
%load the data
[raw,header]=file.textscan(filename,'%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f');
%get the labels (from the header)
labels=strsplit(header,' ');
%build units
units=cell(size(data_cols));
units(:)={''};
t=datetime([0 0 0 0 0 0])+years(raw(:,2));
%building object
obj=simpletimeseries(t,raw(:,data_cols)*1e-10,...
'format','datetime',...
'y_units',units,...
'labels', labels(data_cols),...
'timesystem','gps',...
'descriptor',['SLR Stokes coeff. from ',filename]...
);
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',...
'y_units',units,...
'labels', labels,...
'timesystem','gps',...
'descriptor',['KBR postfits ',filename]...
);
case 'mjd'
%define data cols
data_cols=2;
%load the data
raw=file.textscan(filename,'%f %f');
%get the labels (from the header)
labels={'altitude'};
%build units
units=cell(size(data_cols));
units(:)={'m'};
%sort data
[t,idx]=sort(raw(:,1));
%remove duplicate data
dup=diff(t)==0;
%conver to datetime
t=time.ToDateTime(t(~dup),'modifiedjuliandate');
%building object
obj=simpletimeseries(t,raw(idx(~dup),data_cols),...
'format','datetime',...
'y_units',units,...
'labels', labels,...
'timesystem','gps',...
'descriptor','GRACE altitude'...
);
otherwise
error([mfilename,': cannot handle files of type ''',format,'''.'])
end
%save mat file if requested
if p.Results.save_mat && ~isempty(obj)
save(datafile,'obj')
end
%delete uncompressed file if compressed file is there
if p.Results.del_arch
for i={'.z','.zip','.tgz','.gz','.tar','.gzip'}
if file.exist(fullfile(d,[f,i{1}]))
delete(filename)
disp(['Deleted uncompressed file ''',in,'''.'])
end
end
end
end
function obj=GRACEaltitude(varargin)
p=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=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