-
Notifications
You must be signed in to change notification settings - Fork 5
/
slr.m
1262 lines (1254 loc) · 48.6 KB
/
slr.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 slr < gravity
properties(Constant)
data_options={...
'~/data/SLR';...
'./data/SLR';...
};
%default value of parameters
%NOTICE: needs updated when adding a new parameter
parameter_list={...
'verbose', false, @islogical;...
'C20mean',-4.8416945732000E-04, @isscalar;...
};
%These parameter are considered when checking if two data sets are
%compatible (and only these).
%NOTICE: needs updated when adding a new data type (if relevant)
compatible_parameter_list={};
end
%NOTICE: needs updated when adding a new parameter
properties
%parameters
verbose
end
%NOTICE: needs updated when adding a new data type
properties(SetAccess=private)
type
end
%calculated only when asked for
properties(Dependent)
time
end
methods(Static)
%% directories
function out=dir(type)
switch type %NEEDS UPDATE WHEN ADDING A NEW MODEL
case 'data'
for i=1:numel(slr.data_options)
if file.exist(slr.data_options{i})
out=slr.data_options{i};
return
end
end
case 'CSR2x2'; out=fullfile(slr.dir('data'),'csr' ,'2x2' );
case 'CSR5x5'; out=fullfile(slr.dir('data'),'csr' ,'5x5' );
case 'TN-07'; out=fullfile(slr.dir('data'),'csr' ,'TN-07');
case 'TN-11'; out=fullfile(slr.dir('data'),'csr' ,'TN-11');
case 'CSR-RL06'; out=fullfile(slr.dir('data'),'csr' ,'RL06' );
case 'GSFC5x5'; out=fullfile(slr.dir('data'),'gsfc','5x5' );
case 'TN-14'; out=fullfile(slr.dir('data'),'gsfc','TN-14');
case 'GSFC'; out=fullfile(slr.dir('data'),'gsfc','C20' );
case 'GSFC-7DAY'; out=fullfile(slr.dir('data'),'gsfc','7day' );
%add more directories here
otherwise
error(['Cannot handle type ''',type,'''.'])
end
end
%% interface methods to object constants
function out=parameters(varargin)
persistent v
if isempty(v); v=varargs(slr.parameter_list); end
out=v.picker(varargin{:});
end
%% retrieves the Monthly estimates of C20 from 5 SLR satellites based on GRACE RL05/RL06 models
%TODO: retire this method and use slr.load
function out=graceC20(varargin)
%parse arguments that are required later
v=varargs.wrap('sources',{...
{...
'time', [], @(i) isdatetime(i) || isempty(i);...
'mode', 'read', @ischar;...
'descriptor', '', @ischar;...
'source', 'TN-14', @(i) ischar(i) || iscellstr(i);...
'start',time.zero_date, @isdatetime;...
'stop', time.inf_date, @isdatetime;...
'C20mean',-4.8416945732000E-04, @isscalar;...
'force',false,@islogical;...
},...
},varargin{:});
%parse using a model or the original data
if contains(v.source,'-model')
new_mode=['model-',strrep(v.mode,'model-','')];
new_source=strrep(v.source,'-model','');
str.say('WARNING: over-writing input mode',str.quote(v.mode),'with',str.quote(new_mode),...
'since input source is',str.quote(v.source),', now passed along as',str.quote(new_source),'.')
out=slr.graceC20(varargin{:},'mode',new_mode,'source',new_source);
return
end
switch v.mode
case 'model-poly'
out=3;
case 'model-periods-datfile'
[p,n]=fileparts(GetGRACEC20('mode','data_file','source',v.source));
out=fullfile(p,[n,'_periods.mat']);
case {'model-compute','model-periods'}
%get data file
f=slr.graceC20(varargin{:},'mode','model-periods-datfile');
%check if periods were already computed
if ~file.exist(f)
%loading necessary data
c20=slr.graceC20(varargin{:},'mode','read','force',v.force);
np=slr.graceC20(varargin{:},'mode','model-poly');
%compute periods
[~,pd]=c20.pardecomp_search('np',np,'T',[365.2426,182.6213],'timescale','days');
out=pd.T;
%save periods
save(f,'out');
else
disp(['Loading parametric decomposition from ',f])
%load periods
load(f,'out');
end
% %build strings to save to file
% h=strsplit(c20.descriptor,newline);
% s=strjoin([...
% cellfun(@(i) ['%',i],h(:),'UniformOutput',false);...
% {'out=[...'};...
% arrayfun(@(i) [' ',num2str(i,'%.12e'),';...'],out(:),'UniformOutput',false);...
% {'];'};...
% ],newline);
% f=slr.graceC20(varargin{:},'mode','model-periods-datfile');
% b=file.strsave(f,s);
% str.say('Written',b,'bytes of data to file:',newline,f,newline,'related to the periods of:',newline,c20.descriptor);
case 'model-datfile'
[p,n]=fileparts(GetGRACEC20(varargin{:},'mode','data_file'));
out=fullfile(p,[n,'_graceC20_pd.mat']);
case 'model-md5file'
[p,n]=fileparts(GetGRACEC20(varargin{:},'mode','data_file'));
out=fullfile(p,[n,'.md5']);
case 'model-md5'
out=file.md5(GetGRACEC20(varargin{:},'mode','data_file'));
case 'model-md5set'
out=file.strsave(...
slr.graceC20(varargin{:},'mode','model-md5file'),...
slr.graceC20(varargin{:},'mode','model-md5')...
);
case 'model-md5get'
md5file=slr.graceC20(varargin{:},'mode','model-md5file');
if ~file.exist(md5file)
slr.graceC20(varargin{:},'mode','model-md5set');
end
out=file.strload(md5file);
case 'model-md5check'
out=strcmp(...
slr.graceC20(varargin{:},'mode','model-md5get'),...
slr.graceC20(varargin{:},'mode','model-md5')...
);
case {'model','model-get','model-set','model-read','model-reload'}
%loading necessary data
c20=slr.graceC20(varargin{:},'mode','read','force',v.force);
np=slr.graceC20(varargin{:},'mode','model-poly');
T=slr.graceC20(varargin{:},'mode','model-periods');
%check if pdset is already available
f_pdset=slr.graceC20(varargin{:},'mode','model-list-datfile');
f_pd =slr.graceC20(varargin{:},'mode','model-datfile');
if ~file.exist(f_pdset) || ~file.exist(f_pd) || ~slr.graceC20(varargin{:},'mode','model-md5check') || v.force
%get the coefficients; NOTICE: always use c20.t so that f_pdset is not dependent on inputs
[~,pd_set]=c20.pardecomp('np',np,'T',T,...
'timescale','days','time',c20.t_domain(days(7)));
%save them
save(f_pdset,'pd_set')
%update md5 of data
slr.graceC20(varargin{:},'mode','model-md5set')
else
load(f_pdset,'pd_set')
end
%handle different time domains
if isempty(v.time); v.time=c20.t; end
%implement default start/stop for modelling
if time.iszero(v.start); v.start=v.time(1 ); end
if time.isinf( v.stop ); v.stop=v.time(end); end
%enforce start/stop
v.time=v.time(v.time>=v.start & v.time<=v.stop);
%evaluate model at requested time domain
out=pardecomp.join( pd_set,'time',v.time);
case 'model-list-datfile'
[p,n]=fileparts(GetGRACEC20(varargin{:},'mode','data_file'));
out=fullfile(p,[n,'_pdset.mat']);
case {'model-list','model-list-tex'}
%check if pdset is already available
f=slr.graceC20(varargin{:},'mode','model-list-datfile');
if ~file.exist(f) || v.force
%compute the model (saving is done inside)
slr.graceC20(varargin{:},'mode','model');
end
%load it
load(f,'pd_set')
%output it
switch v.mode
case 'model-list'; out=pardecomp.table(pd_set,'tablify',true);
case 'model-list-tex'; out=pardecomp.table(pd_set,'tablify',false,'latex_table',true);
end
case 'model-plot'
%retrieve the orignal data
c20o=slr.graceC20(varargin{:},'mode','read','force',v.force);
%resample to a finer time domain
c20r=c20o.interp(c20o.t_domain(days(7)),...
'interp_over_gaps_narrower_than',days(45),...
'interp1_args',{'pchip'}...
);
c20m=slr.graceC20(varargin{:},'mode','model','time',c20o.t_domain(days(7)),'force',v.force);
c20e=c20r-c20m;
%compute means
c20om=c20o.stats('mode','mean');
c20mm=c20m.stats('mode','mean');
c20em=c20e.stats('mode','mean');
%compute stds
c20os=c20o.stats('mode','std');
c20ms=c20m.stats('mode','std');
c20es=c20e.stats('mode','std');
%remove the mean
c20o=c20o-c20om(1);
c20m=c20m-c20mm(1);
c20e=c20e-c20em(1);
%plot it
plotting.figure;
c20o.addgaps(days(35)).plot('columns',1);
c20m.plot('columns',1);
c20e.plot('columns',1);
plotting.enforce(varargin{:},...
'plot_legend',...
{...
['Original \mu=',num2str(c20om(1),'%.3e'),' \sigma=',num2str(c20os(1),'%.3e')],...
['Modelled \mu=',num2str(c20mm(1),'%.3e'),' \sigma=',num2str(c20ms(1),'%.3e')],...
['Residual \mu=',num2str(c20em(1),'%.3e'),' \sigma=',num2str(c20es(1),'%.3e')],...
},...
'plot_xlabel','none',...
'plot_title',c20o.descriptor...
);
out=c20e;
case 'interp'
assert(~isempty(v.time),['If mode is ''',v.mode,''', need argument ''time''.'])
out=slr.graceC20(varargin{:},'mode','read','force',v.force);
out=out.interp(v.time);
case 'plot-all'
if iscellstr(v.source)
source_list=v.source;
else
source_list={'GSFC-7day','GSFC','CSR-RL06','TN-14','TN-11','TN-07'};
end
dat_list=cell(size(source_list));
plotting.figure(varargin{:});
for i=1:numel(source_list)
%pick keywords
kw=strsplit(source_list{i},'-');
%branch on them (NOTICE: always last)
switch kw{end}
case 'model'
if i>1
%NOTICE: to get the model with the most complete time domain, out it last in the 'source' input
dat_list{i}=slr.graceC20('mode','model','force',v.force,...
'source',strrep(source_list{i},'-model',''),...
'time',time.union(cellfun(@(j) j.t,dat_list(1:i-1),'UniformOutput',false),days(7))...
);
else
dat_list{i}=slr.graceC20('mode','model','force',v.force,...
'source',strrep(source_list{i},'-model','')...
);
end
otherwise
dat_list{i}=slr.graceC20('mode','read','source',source_list{i},'force',v.force);
dat_list{i}=dat_list{i}.interp(dat_list{i}.t_domain(days(7)),...
'interp_over_gaps_narrower_than',days(45)...
);
end
dat_list{i}=dat_list{i}-v.C20mean;
dat_list{i}.plot('columns',1);
end
plotting.enforce(varargin{:},...
'plot_legend',source_list,...
'plot_xlabel','none');
title(['mean C_{20}: ',num2str(v.C20mean,'%e')]);
out=dat_list;
otherwise
%call mother routine
try
[t,s,e,d]=GetGRACEC20(varargin{:},'mode',v.mode);
catch ME
switch ME.identifier
case 'MATLAB:unassignedOutputs'
[t,s]=GetGRACEC20(varargin{:},'mode',v.mode);
otherwise
rethrow(ME)
end
end
if ~isempty(s)
%create time series
out=simpletimeseries(t,[s,e],...
'labels',{'C20','error C20'},...
'units',{'',''},...
'timesystem','gps',...
'descriptor',d...
);
else
out=t;
end
end
end
%% load predefined SLR data
function obj=load(source,varargin)
%parse arguments that are required later
v=varargs.wrap('sources',{...
{...
'time', [], @(i) isdatetime(i) || isempty(i);...
'remove_C20mean', false, @islogical;...
},...
},varargin{:});
%handle producing the parametric model
if contains(source,'-model')
%save data source
data_source=strrep(source,'-model','');
%build parametric model data filename
[p,n]=fileparts(fullfile(slr.dir(data_source),data_source));
datafile=fullfile(p,[n,'_pd.mat']);
%check if data file is missing or it's old
if ~file.exist(datafile) || file.age(datafile)>days(30)
%need to clean vararing of 'start' and 'stop' so that the model can be built from all data
varargin_now=cells.vararginclean(varargin,{'start','stop'});
%load the data
data=slr.load(data_source,varargin_now{:});
%get the modelled coefficients; NOTICE: always use data.t so that f_pdset is not dependent on inputs
[~,pd_set]=data.ts_C(2,0).pardecomp_search(...
'np',2,...
'T',[1,1/2]*days(years(1)),...
'timescale','days'...
);
%append important information
pd_set.metadata=structs.copy(data.metadata,pd_set.metadata);
%remove units and labels (they are not correct because original data likely has multiple coefficients)
pd_set.metadata=rmfield(pd_set.metadata,{'labels','units'});
%save the data
save(datafile,'pd_set')
else
%load the data
load(datafile,'pd_set')
end
%patch the time domain if none was given
if isempty(v.time)
v.time=pd_set.time;
end
%evaluate model at the data source time domain
model=pardecomp.join( pd_set,'time',v.time);
%propagate relevant information
t=model.t;
y=zeros(numel(t),gravity.y_length(2));
y(:,gravity.colidx(2,0,2))=model.y;
header=pd_set.metadata;
else
%branch on type of SLR data
switch source %NEEDS UPDATE WHEN ADDING A NEW MODEL
case 'CSR2x2'
[t,y,header]=import_CSR2x2(varargin{:});
case 'CSR5x5'
[t,y,header]=import_CSR5x5(varargin{:});
case 'GSFC5x5'
[t,y,header]=import_GSFC5x5(varargin{:});
case {'TN-07','TN-11','CSR-RL06','TN-14','GSFC','GSFC-7DAY'}
[t,y,header]=import_C20('source',source,varargin{:});
otherwise
error(['Cannot handle SLR data of type ''',source,'''.'])
end
if v.remove_C20mean
y=y-slr.parameters('C20mean');
end
if ~isempty(v.time)
%enfore requested times
y=interp1(t,y,v.time,'linear',NaN);
t=v.time;
end
end
obj=slr(t,y,varargs(header).varargin{:},varargin{:});
end
%% testing for the current object
function out=test_parameters(field)
switch lower(field)
case 'start'
out=datetime('2010-01-01');
case 'stop'
out=datetime('2020-12-31');
otherwise
error(['unknown field ',field,'.'])
end
end
function out=test(method)
if ~exist('method','var') || isempty(method)
method='all';
end
start=slr.test_parameters('start');
stop= slr.test_parameters('stop' );
test_list={'CSR2x2','CSR5x5','GSFC5x5','TN-07','TN-11','CSR-RL06','TN-14','GSFC','GSFC-7DAY'};
switch(method)
case {'all','C20'}
plotting.figure;
cellfun(@(i) slr.load(...
i,'start',start,'stop',stop...
).plot(...
'method','timeseries','degrees',2,'orders',0 ...
),test_list);
plotting.enforce(...
'plot_line_color','spiral',...
'plot_legend',test_list...
);
case 'C20-model'
for i=1:numel(test_list)
plotting.figure;
slr.load( test_list{i}, 'start',start,'stop',stop).plot('method','timeseries','degrees',2,'orders',0);
slr.load([test_list{i},'-model'],'start',start,'stop',stop).plot('method','timeseries');
plotting.enforce(...
'plot_legend',{test_list{i},'model'}...
);
end
case {'CSR5x5','CSR2x2','GSFC5x5'} %MAY NEED UPDATE WHEN ADDING A NEW MODEL
out=slr.load(method);
out.plot('method','timeseries','degrees',[2,2,2,2,2],'orders',[-2,-1,-0,1,2],'zeromean',true);
case {'TN-07','TN-11','CSR-RL06','TN-14','GSFC','GSFC-7DAY'} %MAY NEED UPDATE WHEN ADDING A NEW MODEL
out=slr.load(method);
out.plot('method','timeseries','degrees',2,'orders',0);
otherwise
error(['Cannot handle test method ''',method,'''.'])
end
end
end
methods
%% constructor
function obj=slr(t,y,varargin)
%NOTICE: a bunch of options get handled in the gravity init, notably:
% - 'GM'
% - 'R'
% - 'descriptor'
% - 'tide_system'
% - 'origin'
% - 'start'/'stop'
% - 'static_model'
% %input parsing
% p=machinery.inputParser;
% p.addRequired( 't' ); %this can be char, double or datetime
% p.addRequired( 'y', @(i) simpledata.valid_y(i));
% % parse it
% p.parse(in,varargin{:});
% % create argument object, declare and parse parameters, save them to obj
% [v,~]=varargs.wrap('parser',p,'sources',{slr.parameters('obj')},'mandatory',{t,y},varargin{:});
%init the object
%NOTICE: generally, the following options should be in varargin: 'GM', 'R' and 'descriptor'
obj=obj@gravity(t,y,varargin{:});
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@gravity(obj,obj_in,[gravity.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@gravity(obj,[slr.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=20;
end
disp(' --- Parameters --- ')
for i=1:numel(slr.parameters('list'))
%shorter names
p=slr.parameters('value',i);
disp([p,repmat(' ',1,tab-length(p)),' : ',str.show(obj.(p))])
end
d_list=slr.data_types;
for i=1:numel(d_list)
%shorter names
d=d_list{i};
if ~isempty(obj.(d))
disp([' --- ',d,' --- '])
obj.(d).print
end
end
end
function msg(obj,in)
if obj.verbose
disp(in)
end
end
end
end
%TODO: need to retreive y_out_error in all import_* function
function [t_out,y_out,header]=import_CSR2x2(varargin)
% add input arguments and metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
{...
'import_dir', slr.dir('CSR2x2'),@ischar;...
'format', 'csr',@ischar;...
'data_dir_url', 'http://ftp.csr.utexas.edu/pub/slr/degree_2',@ischar;...
'suffix', 'RL06',@ischar;...
'prefixes',{'C20','C21_S21','C22_S22'},@iscellstr;
'degrees', [ 2, 2, 2] ,@isnumeric; %NOTICE: this cannot be a cell because each entry must be scalar
'orders', { 0,[ 1, -1],[ 2, -2]},@(i) all(cellfun(@isnumeric,i));
},...
},varargin{:});
%sanity
assert(numel(v.prefixes)==numel(v.degrees)&& numel(v.prefixes)==numel(v.orders),...
'Metadata ''prefixes'' ''degrees'' and ''orders'' must all have the same size.')
%shortcuts
lmax=max(v.degrees);
%look for aggregated data file
agg_data=fullfile(v.import_dir,'CSR2x2.mat');
%check the format of the data
if file.exist(agg_data)
%load the data
[out,loaded_flag]=file.load_mat(agg_data,'data_var','out');
assert(loaded_flag,['BUG TRAP: could not load the data from ',agg_data])
%unpack the data
t_out=out.t_out;
y_out=out.y_out;
header=out.header;
else
%init records
t=cell(1,numel(v.prefixes)); y=cell(1,numel(v.prefixes)); h=cell(1,numel(v.prefixes));
%loop over all data files
for i=1:numel(v.prefixes)
%define the data file name
data_file=[v.prefixes{i},'_',v.suffix,'.txt'];
local_data=fullfile(v.import_dir,data_file);
%download the data (done inside file.unwrap)
local_data=file.unwrap(local_data,'remote_url',v.data_dir_url,'scalar_as_strings',true,varargin{:});
%check the format of the data
if file.isext(local_data,'.mat')
%load the data
[out,loaded_flag]=file.load_mat(local_data,'data_var','out');
assert(loaded_flag,['BUG TRAP: could not load the data from ',local_data])
%unpack the data
t{i}=out.t;
y{i}=out.y;
h{i}=out.header;
else
%need to make sure file.unwrap returned the txt file
assert(file.isext(local_data,'.txt'),'BUG TRAP: expecting a txt file')
%build the header info (GM, R and tide_system is assumed to be the same as CSR5x5)
h{i}=struct(...
'origin',local_data,...
'raw',file.header(local_data,30),... %load the text (search for the end of the header up until line 30)
'd',v.degrees(i),...
'o',v.orders{i}...
);
%branch on files with one or two coefficients
if contains(h{i}.raw,'C21') || contains(h{i}.raw,'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];
sigm_cols=[4 5];
corr_cols=[6 7];
% units={'',''};
% if ~contains(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;
sigm_cols=4;
corr_cols=5;
% units={''};
% if contains(header,'C20'); labels={'C2,0'}; end
% if contains(header,'C40'); labels={'C4,0'}; end
end
raw=file.textscan(local_data,file_fmt);
%build the time domain
t{i}=datetime('0000-01-01 00:00:00')+years(raw(:,1));
%building data domain
switch v.format
case 'csr' %NOTICE: this includes AOD mean for the solution period (aka correction, or 'corr')
y_raw=raw(:,data_cols);
case 'csr-grace' %NOTICE: this removes the AOD correction from SLR, making it more suitable to replace the GRACE C20
y_raw=raw(:,data_cols)-raw(:,corr_cols)*1e-10;
case 'csr-corr' %NOTICE: this is the AOD correction
y_raw=raw(:,corr_cols)*1e-10;
case 'csr-sigma' %NOTICE: this is the solution sigma
y_raw=raw(:,sigm_cols)*1e-10;
end
%building aggregated records
for j=1:numel(v.orders{i}) %NOTICE: this is why v.degrees{i} should be scalar
d=v.degrees(i);
o=v.orders{i}(j);
y{i}(:,gravity.colidx(d,o,lmax))=y_raw(:,j);
end
%save the data in mat format
file.save_mat(struct('t',t{i},'y',y{i},'header',h{i}),local_data,'data_var','out')
end
end
%aggregate the data from the separate files, define header
header=struct(...
'GM',3.986004415E+14,...
'R',6.378136300E+06,...
'lmax',lmax,...
'tide_system','zero_tide',...
'descriptor','UT/CSR monthly 2x2 RL-06 time series from SLR',...
'origin','',...
'raw',{cell(1,numel(h))}... %NOTICE: this {} syntax is needed so that header is not a vector
);
%init y_out
y_out=zeros(numel(t{1}),gravity.y_length(lmax));
for i=1:numel(v.prefixes)
%retrieve/sanitize time
if i==1
t_out=t{i};
else
assert(~any(~simpletimeseries.ist('==',t{i},t_out)),'time domain inconsistency')
end
%aggregate coefficients
for j=1:numel(v.orders{i}) %NOTICE: this is why v.degrees{i} should be scalar
colidx=gravity.colidx(h{i}.d,h{i}.o(j),lmax);
y_out(:,colidx)=y{i}(:,colidx);
end
%save header info
header.raw{i}=h{i}.raw;
header.origin=strjoin({header.origin,h{i}.origin},'; ');
end
%save the data in mat format
file.save_mat(struct('t_out',t_out,'y_out',y_out,'header',header),agg_data,'data_var','out')
end
end
function [t_out,y_out,header,y_out_error,y_out_AOD]=import_CSR5x5(varargin)
% add input arguments and metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
{...
'import_dir', slr.dir('CSR5x5'),@ischar;...
'data_dir_url', 'http://ftp.csr.utexas.edu/pub/slr/degree_5',@ischar;...
'data_file', 'CSR_Monthly_5x5_Gravity_Harmonics.txt',@ischar;...
'data_labels', {'n','m','Cnm','Snm','Cnm+AOD','Snm+AOD','C-sigma','S-sigma','Year_mid_point'},@iscellstr;
'lmax', 5, @(i) isscalar(i) && isnumeric(i);...
},...
},varargin{:});
%define the local data file name
local_data=fullfile(v.import_dir,v.data_file);
%download the data (done inside file.unwrap)
local_data=file.unwrap(local_data,'remote_url',v.data_dir_url,'scalar_as_strings',true,varargin{:});
%check the format of the data
if file.isext(local_data,'.mat')
%load the data
[out,loaded_flag]=file.load_mat(local_data,'data_var','out');
assert(loaded_flag,['BUG TRAP: could not load the data from ',local_data])
%unpack the data
t_out =out.t_out;
y_out =out.y_out;
y_out_AOD =out.y_out_AOD;
y_out_error=out.y_out_error;
header =out.header;
else
%need to make sure file.unwrap returned the txt file
assert(file.isext(local_data,'.txt'),'BUG TRAP: expecting a txt file')
%declare header structure
header=struct(...
'GM',0,...
'R',0,...
'lmax',v.lmax,...
'tide_system','unknown',...
'descriptor','unknown',...
'origin',local_data,...
'labels',{{}},...
'idx',struct([]),...
'scale',1 ...
);
%define known details
header.descriptor='UT/CSR monthly 5x5 gravity harmonics';
%open the file
fid=file.open(local_data);
% Read header
while true
s=fgets(fid);
if contains(s,'end of header')
break
end
if contains(s,'earth_gravity_constant')
header.GM = str2double(strtrim(strrep(s,'earth_gravity_constant','')));
end
if (contains(s, 'radius'))
header.R=str2double(strtrim(strrep(s,'radius','')));
end
if (contains(s, 'tide_system'))
header.tide_system=strtrim(strrep(s,'tide_system',''));
end
if (contains(s, 'Units'))
header.scale=str2double(strtrim(strrep(s,'Units','')));
end
if (contains(s, 'Coefficients:'))
header.labels=cells.rm_empty(strsplit(strtrim(str.rep(s,'Coefficients:','',',',''))));
%build index records
for i=1:numel(v.data_labels)
%build fieldname (label may have ilegal characters)
fn=str.clean(v.data_labels{i},'fieldname');
%find where this data label is located in the header labels
header.idx(1).(fn)=cells.strequal(header.labels,v.data_labels{i});
%make sure it is found
assert(~isempty(header.idx(1).(fn)),['Cannot find reference to data label ''',...
v.data_labels{i},''' in the header of ',local_data])
end
end
if (contains(s, '===================='))
%init loop variables
counter=0;
%read the static coefficients
while true
%get the next line
s=fgets(fid);
%split line into columns and remove empty entries
s=cells.rm_empty(strsplit(s));
%exist criteria
if numel(s)~=6
break
end
%increment line counter
counter=counter+1;
%save the data
header.static(counter,:)=cells.c2m(cells.num(s));
end
%convert the header.static data to gravity-friendly format
for j=1:size(header.static,1)
d=header.static(j,1);
%skip if this degree is above the requested lmax
if d>header.lmax; continue; end
%cosine coefficients are in the 3rd column (errors in the 5th)
o=header.static(j,2);
static_signal(gravity.colidx(d,o,header.lmax))=header.static(j,3); %#ok<AGROW>
static_error( gravity.colidx(d,o,header.lmax))=header.static(j,5); %#ok<AGROW>
if o==0, continue;end
%sine coefficients are in the 4th column (errors in the 6th)
o=-o;
static_signal(gravity.colidx(d,o,header.lmax))=header.static(j,4); %#ok<AGROW>
static_error( gravity.colidx(d,o,header.lmax))=header.static(j,6); %#ok<AGROW>
end
end
end
% some sanity
assert(~isempty(header.static),'Could not retrieve the static gravity field coefficients')
%init output
y_out=zeros(1,gravity.y_length(header.lmax));
y_out_error=y_out;y_out_AOD=y_out;
% read data
while true
s=fgets(fid);
if ~ischar(s)
break
end
%split line into columns and remove empty entries
s=cells.c2m(cells.num(cells.rm_empty(strsplit(s))));
%branch on the number of columns
switch numel(s)
case 7
arc=s(1);
case 10
%get degree and order
d=s(header.idx.n);
o=s(header.idx.m);
%skip if this degree is above the requested lmax
if d>header.lmax; continue; end
%get the epoch
t_out(arc)=datetime([0 0 0 0 0 0])+years(s(header.idx.Year_mid_point)); %#ok<AGROW>
%save cosine coefficient, error and value with AOD
y_out( arc,gravity.colidx(d,o,header.lmax))=s(header.idx.Cnm);
y_out_error(arc,gravity.colidx(d,o,header.lmax))=s(header.idx.Csigma);
y_out_AOD( arc,gravity.colidx(d,o,header.lmax))=s(header.idx.CnmAOD);
if o==0, continue;end
%save sine coefficient, error and value with AOD
o=-o;
y_out( arc,gravity.colidx(d,o,header.lmax))=s(header.idx.Snm);
y_out_error(arc,gravity.colidx(d,o,header.lmax))=s(header.idx.Ssigma);
y_out_AOD( arc,gravity.colidx(d,o,header.lmax))=s(header.idx.SnmAOD);
otherwise
disp(['WARNING: ignoring line: ',strjoin(s,' ')])
end
end
fclose(fid);
%add static signal and error
scale=header.scale*ones(size(y_out,1),1);
y_out = scale.*y_out + static_signal;
y_out_AOD = scale.*y_out_AOD + static_signal;
y_out_error=sqrt((scale.*y_out_error).^2 + static_error.^2);
%save the data in mat format
file.save_mat(struct('t_out',t_out,'y_out',y_out,'y_out_AOD',y_out_AOD,'y_out_error',y_out_error,'header',header),local_data,'data_var','out')
end
end
function [t_out,y_out,header]=import_GSFC5x5(varargin)
% add input arguments and metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
{...
'import_dir', slr.dir('GSFC5x5'),@ischar;...
'data_dir_url', 'https://earth.gsfc.nasa.gov/sites/default/files/geo/slr-weekly',@ischar;...
'data_file', 'GSFC_SLR_5x5c61s61.txt',@ischar;...
'data_labels', {'n','m','C','S'},@iscellstr;
'lmax', 5, @(i) isscalar(i) && isnumeric(i);...
},...
},varargin{:});
%define the local data file name
local_data=fullfile(v.import_dir,v.data_file);
%download the data (done inside file.unwrap)
local_data=file.unwrap(local_data,'remote_url',v.data_dir_url,'scalar_as_strings',true,varargin{:});
%check the format of the data
if file.isext(local_data,'.mat')
%load the data
[out,loaded_flag]=file.load_mat(local_data,'data_var','out');
assert(loaded_flag,['BUG TRAP: could not load the data from ',local_data])
%unpack the data
t_out=out.t_out;
y_out=out.y_out;
header=out.header;
else
%need to make sure file.unwrap returned the txt file
assert(file.isext(local_data,'.txt'),'BUG TRAP: expecting a txt file')
%declare header structure
header=struct(...
'GM',0,...
'R',0,...
'lmax',v.lmax,...
'tide_system','unknown',...
'descriptor','unknown',...
'origin',local_data,...
'labels',{{}},...
'idx',struct([])...
);
%define known details
header.descriptor='NASA GSFC SLR 5x5+C61/S61 time variable gravity';
%open the file
fid=file.open(local_data);
% Read header
while true
s=fgets(fid);
if contains(s,'end of header')
break
end
if contains(s,'Title: ')
header.descriptor = strtrim(strrep(s,'Title: ',''));
end
if contains(s,'GM:')
l=strsplit(s);
header.GM = str2double(l{3});
end
if (contains(s, 'R:'))
l=strsplit(s);
header.R=str2double(l{3});
end
if (contains(s, 'C20 is'))
header.tide_system=strtrim(strrep(s,'C20 is',''));
end
if (contains(s, 'Coefficient lines:'))
header.labels=cells.rm_empty(...
strsplit(...
str.clean(...
s,{...
'(I3,I3,1X,E20.13,1X,E20.13)','Coefficient','lines:',','...
}...
)...
)...
);
%build index records
for i=1:numel(v.data_labels)
%build fieldname (label may have ilegal characters)
fn=str.clean(v.data_labels{i},'fieldname');
%find where this data label is located in the header labels
%NOTICE: -2 is needed to offset the two words 'Coefficient lines:'
header.idx(1).(fn)=cells.strequal(header.labels,v.data_labels{i});
%make sure it is found
assert(~isempty(header.idx(1).(fn)),['Cannot find reference to data label ''',...
v.data_labels{i},''' in the header of ',local_data])
end
end
if contains(s, 'Product:')
break
end
end
%init loop variables
arc=0; y_out=zeros(1,gravity.y_length(header.lmax));
% read data
while true
s=fgets(fid);
if ~ischar(s)
break
end
%split line into columns and remove empty entries
s=cells.c2m(cells.num(cells.rm_empty(strsplit(s))));
%branch on the number of columns
switch numel(s)
case 2
%increment loop var
arc=arc+1;
%get the epoch
t_out(arc)=time.ToDateTime(s(1),'modifiedjuliandate'); %#ok<AGROW>
case 4
%get degree and order
d=s(header.idx.n);
o=s(header.idx.m);
%skip if this degree is above the requested lmax
if d>header.lmax; continue; end
%save cosine coefficient
y_out(arc,gravity.colidx(d,o,header.lmax))=s(header.idx.C);
if o==0, continue;end
%save sine coefficient
o=-o;
y_out(arc,gravity.colidx(d,o,header.lmax))=s(header.idx.S);
otherwise
disp(['WARNING: ignoring line: ',strjoin(s,' ')])
end
end
fclose(fid);
%save the data in mat format
file.save_mat(struct('t_out',t_out,'y_out',y_out,'header',header),local_data,'data_var','out')
end
end
function [t_out,y_out,header]=import_C20(varargin)
%TODO: - TN-07 and TN-11 (half a month?)
% add input arguments and metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
{...
'source' , 'TN-14',@ischar;...
'import_dir' , slr.dir('TN-14'),@ischar;...
'data_dir_url' , '',@ischar;...
'data_file' , '',@ischar;...
'time_column' , 1,@isnumeric;...
'signal_column', 3,@isnumeric;...
'error_column' , 5,@isnumeric;...
'comment_style', '*',@iscahr;...
'data_format' , '%7.1f%10.4f%22.13f%8.4f%8.4f',@ischar;...
},...
},varargin{:});
%upper-case source name
v.source=upper(v.source);
%update local import dir
v.import_dir=slr.dir(v.source);
%parse dependent arguments (can be over-written)
switch v.source
case 'TN-07'
v.data_file=[v.source,'_C20_SLR.txt'];
% v.data_dir_url='ftp://podaac.jpl.nasa.gov/allData/grace/docs/'; %NOTICE: this no longer works
v.data_dir_url='none';
case 'TN-11'
v.data_file=[v.source,'_C20_SLR.txt'];
% v.data_dir_url=['https://podaac-w10n.jpl.nasa.gov/w10n/allData/grace/docs/',v.data_file];
v.data_dir_url='https://podaac-tools.jpl.nasa.gov/drive/files/allData/grace/docs/';
v.data_format='%7.1f%10.4f%22.13f%8.4f%8.4f%8.1f%10.4f';
v.time_column=[1 6];
case 'CSR-RL06'
v.data_file='C20_RL06.txt';
v.data_dir_url='http://download.csr.utexas.edu/pub/slr/degree_2/';
v.data_format='%10.4f%19.10f%8.4f%8.4f%8.4f%16.4f%16.4f';
v.comment_style='#';
v.signal_column=2;
v.error_column=4;
case 'TN-14'
v.data_file=[v.source,'_C30_C20_SLR_GSFC.txt'];
v.data_dir_url='ftp://isdcftp.gfz-potsdam.de/grace/DOCUMENTS/TECHNICAL_NOTES/';
v.data_format='%7.1f%10.4f%22.13f%8.4f%8.4f%22.13f%8.4f%8.4f%8.1f%10.4f';
case 'GSFC'
v.data_file='GSFC_SLR_C20_GSM_replacement.txt';
v.data_dir_url='https://earth.gsfc.nasa.gov/sites/default/files/neptune/images_db/';
case 'GSFC-7DAY'
%NOTICE: this was periodically sent by Bryant Loomis but has been replaced by GSFC5x5 (you can still manually copy-paste the data from there into this file)
v.data_file='GSFC_SLR_C20_7day.txt';
v.data_dir_url='none';
v.data_format='%10.4f%23.13f';
v.time_column=1;
v.signal_column=2;
v.error_column=0;
otherwise
warning([...
'Loading ',v.source,' C20 timeseries with externally-defined details:',newline,...
'import_dir :',v.import_dir,newline,...
'data_dir_url :',v.data_dir_url,newline,...
'data_file :',v.data_file,newline,...
'time_column :',v.time_column,newline, ...
'signal_column:',v.signal_column,newline,...
'error_column :',v.error_column,newline,...
'comment_style:',v.comment_style,newline,...
'data_format :',v.data_format,newline,...
])
end
%define the local data file name
local_data=fullfile(v.import_dir,v.data_file);
%download the data (done inside file.unwrap)
local_data=file.unwrap(local_data,'remote_url',v.data_dir_url,'scalar_as_strings',true,varargin{:});
%check the format of the data
if file.isext(local_data,'.mat')
%load the data
[out,loaded_flag]=file.load_mat(local_data,'data_var','out');
assert(loaded_flag,['BUG TRAP: could not load the data from ',local_data])
%unpack the data
t_out=out.t_out;
y_out=out.y_out;
header=out.header;
else
%default header
%NOTICE: most of this info is assumed, becase there's no info on the data files