-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgravity.m
3662 lines (3636 loc) · 129 KB
/
gravity.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 gravity < simpletimeseries
%static
properties(Constant)
%this is used to define the epoch of static fields (in the gravity.load method)
static_select_date=time.zero_date;
static_start_date=time.zero_date;
static_stop_date=time.inf_date;
% Supported functionals are the following,
% 'nondim' - non-dimensional Stoked coefficients.
% 'eqwh' - equivalent water height [m]
% 'geoid' - geoid height [m]
% 'potential' - [m2/s2]
% 'gravity' - [m /s2], if input represents the disturbing potential,
% then the output represents the gravity disturbances.
% Otherwise, it represents the gravity accelerations
% (-dU/dr).
% 'anomalies' - If input represents the disturbing potential, then
% the output represents the gravity anomalies.
% Otherwise, it represents (-dU/dr - 2/r*U).
% 'vertgravgrad' - vertical gravity gradient.
functional_details=struct(...
'nondim', struct('units',' ', 'name','Stokes Coeff.'),...
'eqwh', struct('units','m', 'name','Eq. Water Height'),...
'geoid', struct('units','m', 'name','Geoid Height'),...
'potential', struct('units','m^2.s^{-2}','name','Geopotential'),...
'anomalies', struct('units','m.s^{-2}', 'name','Gravity Anomalies'),...
'vertgravgrad', struct('units','s^{-2}', 'name','Vert. Gravity Gradient'),...
'gravity', struct('units','m.s^{-2}', 'name','Gravity Acc.')...
);
%NOTICE: the sequence of operations is important:
% - use_GRACE_C20 before static_model means the SLR C20 will be ~1e-10 (the residual relative to the static), not ~1e-4 (mainly the static)
% - tide_system should come before use_GRACE_C20 because the tide system of the SLR data is handled before it is replaced in this model
% - delete_C20 makes more sense after use_GRACE_C20, static_model and tide_system (otherwise, those components will remain)
common_ops_mode_list={...
'consistent_GM','consistent_R','max_degree',...
'tide_system','use_GRACE_C20','static_model',...
'start','stop','delete_C00','delete_C20',...
};
%list of GRACE days missing from the models: start (at 00:00:00) and stop (at 23:59:59) of gap in one line
grace_missing_data=cellfun(@(i) datetime(i),{...
' -inf','2002-04-04';...
'2002-05-01','2002-05-02';...
'2002-05-17','2002-07-31';...
'2003-05-22','2003-06-30';...
'2004-01-14','2004-02-03';...
'2010-12-28','2011-02-07';...
'2011-06-01','2011-07-04';...
'2011-11-16','2011-12-12';...
'2012-04-19','2012-05-31';...
'2012-09-26','2012-11-05';...
'2013-02-27','2013-04-10';...
'2013-08-01','2013-09-30';...
'2014-01-17','2014-03-02';...
'2014-06-25','2014-07-31';...
'2014-12-01','2015-01-12';...
'2015-05-12','2015-06-28';...
'2015-09-28','2015-12-10';...
'2016-04-01','2016-05-07';...
'2016-07-28','2016-08-07';...
'2016-09-04','2016-11-13';...
'2017-02-04','2017-03-16';...
'2017-06-27','2018-05-31';...
'2018-07-19','2018-10-21';...
});
%list of GRACE monthly solutions with days outside the calendar month by which they are
%usually called: start date, end date, year, month
grace_odd_months={...
datetime('2011-10-16'),datetime('2011-11-15'),2011,10;...
datetime('2011-12-13'),datetime('2012-01-11'),2011,12;...
datetime('2012-03-20'),datetime('2012-04-18'),2012,04;...
datetime('2015-04-12'),datetime('2015-05-11'),2015,04;...
datetime('2015-06-29'),datetime('2015-07-31'),2015,07;...
datetime('2015-12-11'),datetime('2016-01-03'),2015,12;...
datetime('2016-01-29'),datetime('2016-02-29'),2016,02;...
datetime('2016-08-08'),datetime('2016-09-03'),2016,08;...
datetime('2016-11-14'),datetime('2016-12-10'),2016,11;...
datetime('2016-12-11'),datetime('2017-01-06'),2016,12;...
datetime('2017-01-07'),datetime('2017-02-03'),2017,01;...
datetime('2017-03-17'),datetime('2017-04-14'),2017,03;...
datetime('2017-04-10'),datetime('2017-05-08'),2017,04;...
datetime('2017-05-23'),datetime('2017-06-28'),2017,06;...
datetime('2018-10-22'),datetime('2018-11-09'),2018,10;...
datetime('2019-01-26'),datetime('2019-03-06'),2019,02;...
};
end
properties(Constant,GetAccess=private)
%TODO: the parameters below are a mix of physical constants and default values for properties; find a way to fix this
%default value of some internal parameters
parameter_list={...
'GM', 398600.4415e9, @num.isscalar;... % Standard gravitational parameter [m^3 s^-2]
'R', 6378136.460, @num.isscalar;... % Earth's equatorial radius [m]
'rho_earth',5514.32310829, @num.isscalar;... % average density of the Earth = (GM/G) / (4/3*pi*R_av^3) [kg/m3]
'rho_water',1000, @num.isscalar;... % water density [kg/m3]
'G', 6.67408e-11, @(i) (num.isscalar(i)) || isempty(i);... % Gravitational constant [m3/kg/s2]
'Rm', 6371000, @(i) (num.isscalar(i)) || isempty(i);... % Earth's mean radius [m]
'love', [ 0 0.000;...
1 0.027;...
2 -0.303;...
3 -0.194;...
4 -0.132;...
5 -0.104;...
6 -0.089;...
7 -0.081;...
8 -0.076;...
9 -0.072;...
10 -0.069;...
12 -0.064;...
15 -0.058;...
20 -0.051;...
30 -0.040;...
40 -0.033;...
50 -0.027;...
70 -0.020;...
100 -0.014;...
150 -0.010;...
200 -0.007], @(i) isnumeric(i) && size(i,2)==2;... % Love numbers: http://dx.doi.org/10.1029/98JB02844
'origin', 'unknown', @ischar;... % (arbitrary string)
'functional', 'nondim', @(i) ischar(i) && any(strcmp(i,gravity.functionals)); %see above
'zf_love', 0.30190, @num.isscalar;... % zero frequency Love number: reported in IERS2003 Section 6.3 as "k20"
'pt_factor',1.391413e-08, @num.isscalar;... % permanent tide factor: reported in IERS2003 Section 6.3 as "A0*H0", (4.4228e-8)*(0.31460)
'static_model', 'none', @ischar;... %assume there is no static model; if there is one, it has to be specified
'common_ops_done', false, @islogical;...
'tide_system','zero_tide',@ischar;...
'grace_month_records','~/data/grace/grace-dates.list',@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={'GM','R','functional','lmax','static_model','common_ops_done','tide_system'};
end
properties(SetAccess=public)
GM
R
functional
origin
static_model
%This parameter enures the common ops are not applied twice to derived models, i.e. if
%you compute a model residual from two models which have already had a (the same) static
%model removed (and possibly have already been converted to non-dim functionals), you don't
%want common_ops to kick in, notably consistent_R, consistent_GM and tide_system
common_ops_done
tide_system
end
%calculated only when asked for
properties(Dependent)
lmax
mat
cs
tri
mod
checksum
funct %handles empty values of functional
end
methods(Static)
function out=parameters(varargin)
persistent v
if isempty(v); v=varargs(gravity.parameter_list); end
out=v.picker(varargin{:});
end
function out=issquare(in)
in_sqrt=sqrt(in);
out=(in_sqrt-round(in_sqrt)==0);
end
function out=functionals
out=fieldnames(gravity.functional_details);
end
function out=functional_units(functional)
assert(gravity.isfunctional(functional),['Ilegal functional ''',functional,'''.'])
out=gravity.functional_details.(functional).units;
end
function out=functional_names(functional)
assert(gravity.isfunctional(functional),['Ilegal functional ''',functional,'''.'])
out=gravity.functional_details.(functional).name;
end
function out=functional_label(functional)
out=[gravity.functional_names(functional),' [',gravity.functional_units(functional),']'];
end
function out=isfunctional(in)
out=isfield(gravity.functional_details,in);
end
%% y representation
function out=y_valid(y)
out=size(y,1)==1 && gravity.issquare(numel(y));
end
function lmax=y_lmax(y)
lmax=sqrt(numel(y))-1;
end
function s=y_length(lmax)
s=(lmax+1).^2;
end
%% mat representation
function out=mat_valid(mat)
out=size(mat,1)==size(mat,2);
end
function lmax=mat_lmax(mat)
lmax=gravity.y_lmax(mat(:));
end
function s=mat_length(lmax)
s=[lmax+1,lmax+1];
end
%% cs representation
function out=cs_valid(in)
out=isfield(in,'C') && isfield(in,'S');
if ~out,return,end
z=triu(in.C,1)+triu([in.S(:,2:end),zeros(size(in.C,1),1)],0);
out=all(size(in.C)==size(in.S)) && size(in.C,1) == size(in.C,2) && all(z(:)==0) ;
end
function lmax=cs_lmax(cs)
lmax=gravity.y_lmax(cs(1).C(:));
for i=2:numel(cs)
assert(lmax==gravity.y_lmax(cs(i).C(:)),'found discrepancy in sizes in ''cs'' representation. Debug needed.');
end
end
function s=cs_length(lmax)
s=gravity.mat_length(lmax);
end
%% tri representation
function out=tri_valid(tri)
lmax=gravity.tri_lmax(tri);
out=size(tri,1)==lmax+1 && round(lmax)==lmax && gravity.cs_valid(gravity.tri2cs(tri));
end
function lmax=tri_lmax(tri)
lmax=(size(tri,2)+1)/2-1;
end
function s=tri_length(lmax)
s1=gravity.mat_length(lmax);
s=[s1(1),2*(lmax+1)-1];
end
%% mod representation
function out=mod_valid(mod)
n=gravity.mod_lmax(mod)+1;
out=size(mod,2)==4 && size(mod,1)==n*(n+1)/2;
end
function lmax=mod_lmax(mod)
lmax=max(mod(:,1));
end
function s=mod_length(lmax)
s=[(lmax*(lmax+1))/2,2*(lmax+1)-1];
end
%% y and mat convertions
function mat=y2mat(y)
mat=zeros(sqrt(numel(y)));
mat(:)=y;
end
function y=mat2y(mat)
y=transpose(mat(:));
end
%% cs and mat convertions
function cs=mat2cs(mat)
S=transpose(triu(mat,1));
cs=struct(...
'C',tril(mat,0),...
'S',[zeros(size(mat,1),1),S(:,1:end-1)]...
);
end
function mat=cs2mat(cs)
mat=cs.C+transpose([cs.S(:,2:end),zeros(size(cs.C,1),1)]);
end
%% cs and tri convertions
function tri=cs2tri(cs)
tri=[fliplr(cs.S(:,2:end)),cs.C];
end
function cs=tri2cs(tri)
n=(size(tri,2)+1)/2;
cs=struct(...
'S',[zeros(n,1),fliplr(tri(:,1:n-1))],...
'C',tri(:,n:end)...
);
end
%% cs and mod convertions
function mod=cs2mod(in)
%shortcuts
n=size(in.C,1);
%create lower triangle index matrix
idxm=zeros(n);
idxm(:)=1:n*n;
idxm(idxm==triu(idxm,1))=NaN;
%create index list
[d,o]=ind2sub(n,idxm(:));
%get location of NaNs
i=isnan(d);
%flatten coefficients
C=in.C(:);S=in.S(:);
%filter out upper diagonals
d(i)=[];
o(i)=[];
C(i)=[];
S(i)=[];
%assemble
mod=[d-1,o-1,C,S];
end
function out=mod2cs(mod)
%make room
out=struct(...
'C',zeros(max(mod(:,1))+1),...
'S',zeros(max(mod(:,1))+1)...
);
%propagate
for i=1:size(mod,1)
out.C(mod(i,1)+1,mod(i,2)+1) = mod(i,3);
out.S(mod(i,1)+1,mod(i,2)+1) = mod(i,4);
end
end
%% agregator routines
%data type converter
function out=dtc(from,to,in)
%trivial call
if strcmpi(from,to)
out=in;
return
end
%check input
if ~gravity.dtv(from,in)
error(['invalid data of type ''',from,'''.'])
end
%convert to required types
switch lower(from)
case 'y'
switch lower(to)
case 'mat'; out=gravity.y2mat(in);
case 'cs'; out=gravity.mat2cs(gravity.y2mat(in));
case 'tri'; out=gravity.cs2tri(gravity.mat2cs(gravity.y2mat(in)));
case 'mod'; out=gravity.cs2mod(gravity.mat2cs(gravity.y2mat(in)));
end
case 'mat'
switch lower(to)
case 'y'; out=gravity.mat2y(in);
case 'cs'; out=gravity.mat2cs(in);
case 'tri'; out=gravity.cs2tri(gravity.mat2cs(in));
case 'mod'; out=gravity.cs2mod(gravity.mat2cs(in));
end
case 'cs'
switch lower(to)
case 'y'; out=gravity.mat2y(gravity.cs2mat(in));
case 'mat'; out=gravity.cs2mat(in);
case 'tri'; out=gravity.cs2tri(in);
case 'mod'; out=gravity.cs2mod(in);
end
case 'tri'
switch lower(to)
case 'y'; out=gravity.mat2y(gravity.cs2mat(gravity.tri2cs(in)));
case 'mat'; out=gravity.cs2mat(gravity.tri2cs(in));
case 'cs'; out=gravity.tri2cs(in);
case 'mod'; out=gravity.cs2mod(gravity.tri2cs(in));
end
case 'mod'
switch lower(to)
case 'y'; out=gravity.mat2y(gravity.cs2mat(gravity.mod2cs(in)));
case 'mat'; out=gravity.cs2mat(gravity.mod2cs(in));
case 'cs'; out=gravity.mod2cs(in);
case 'tri'; out=gravity.cs2tri(gravity.mod2cs(in));
end
end
end
%data type validity
function c=dtv(type,in)
switch lower(type)
case 'y'; c=gravity.y_valid(in);
case 'mat';c=gravity.mat_valid(in);
case 'cs'; c=gravity.cs_valid(in);
case 'tri';c=gravity.tri_valid(in);
case 'mod';c=gravity.mod_valid(in);
otherwise
error(['unknown data type ''',from,'''.'])
end
end
%data type lmax
function c=dtlmax(type,in)
switch lower(type)
case 'y'; c=gravity.y_lmax(in);
case 'mat';c=gravity.mat_lmax(in);
case 'cs'; c=gravity.cs_lmax(in);
case 'tri';c=gravity.tri_lmax(in);
case 'mod';c=gravity.mod_lmax(in);
otherwise
error(['unknown data type ''',from,'''.'])
end
end
%data type length
function s=dtlength(type,in)
switch lower(type)
case 'y'; s=gravity.y_length(in);
case 'mat';s=gravity.mat_length(in);
case 'cs'; s=gravity.cs_length(in);
case 'tri';s=gravity.tri_length(in);
case 'mod';s=gravity.mod_length(in);
otherwise
error(['unknown data type ''',from,'''.'])
end
end
%% degree/order index mapping
function out=mapping(lmax)
%create triangular matrix for degrees
d=(0:lmax)'*ones(1,2*lmax+1).*gravity.dtc('mat','tri',ones(lmax+1));
%create triangular matrix for orders
o=ones(lmax+1,1)*(-lmax:lmax).*gravity.dtc('mat','tri',ones(lmax+1));
%convert to vector
d=gravity.dtc('tri','y',d);
o=gravity.dtc('tri','y',o);
out=[d;o];
end
function [l,u]=labels(lmax,units_str)
map=gravity.mapping(lmax);
l=cell(1,size(map,2));
for i=1:size(map,2)
if map(2,i)<0
l{i}=sprintf('S%i,%i',map(1,i),-map(2,i));
else
l{i}=sprintf('C%i,%i',map(1,i),map(2,i));
end
end
if nargin>1 && nargout>1
u=cell(size(l));
u(:)={units_str};
end
end
function out=colidx(d,o,lmax)
if any(size(d)~=size(o))
error('inputs ''d'' and ''o'' must have the same size(s).')
end
m=gravity.mapping(lmax);
out=false(1,size(m,2));
for i=1:numel(d)
out=out | (m(1,:)==d(i) & m(2,:)==o(i));
end
out=find(out);
end
%% constructors
function obj=unit(lmax,varargin)
%create argument object, declare and parse parameters, save them to obj
v=varargs.wrap('sources',{gravity.parameters('obj'),...
{...
'scale', 1, @num.isscalar;...
'scale_per_degree',ones(lmax+1,1), @(i) isvector(i) && lmax+1 == numel(i);...
'scale_per_coeff', ones(lmax+1), @(i) ismatrix(i) && all([lmax+1,lmax+1] == size(i));...
't', datetime('now'),@(i) isdatetime(i) || isvector(i);...
}...
},varargin{:});
%create unitary triangular matrix
u=gravity.dtc('mat','tri',ones(lmax+1));
%scale along degrees (if needed)
if any(v.scale_per_degree(:)~=1)
u=v.scale_per_degree(:)*ones(1,size(u,2)).*u;
end
%scale per coefficient (if needed)
if any(v.scale_per_coeff(:)~=1)
u=gravity.dtc('mat','tri',v.scale_per_coeff).*u;
end
%replicate by the nr of elements of t
u=ones(numel(v.t),1)*gravity.dtc('tri','y',u);
%initialize
obj=gravity(v.t,u,v.dup.delete('t').varargin{:},'skip_common_ops',true,varargin{:});
% save the arguments v into this object
obj=v.save(obj,{'t','lmax'});
%call upstream scale method for global scale
obj=obj.scale(v.scale);
end
% creates a unit model with per-degree amplitude equal to 1
function obj=unit_amplitude(lmax,varargin)
obj=gravity.unit(lmax,'scale_per_degree',1./sqrt(2*(0:lmax)+1),varargin{:});
end
% creates a unit model with per-degree RMS equal to 1
function obj=unit_rms(lmax,varargin)
obj=gravity.unit(lmax,'scale_per_degree',gravity.unit(lmax).drms,varargin{:},'skip_common_ops',true);
end
% create a model with coefficients following Kaula's rule of thumb
function obj=kaula(lmax,varargin)
obj=gravity.unit(lmax,'scale_per_degree',[0,1e-5./(1:lmax).^2],varargin{:},'skip_common_ops',true);
end
function obj=nan(lmax,varargin)
obj=gravity.unit(lmax,'scale',nan,varargin{:},'skip_common_ops',true);
end
function obj=zero(lmax,varargin)
obj=gravity.unit(lmax,'scale',0,varargin{:},'skip_common_ops',true);
end
% Creates a random model with mean 0 and std 1 (per degree)
function obj=randn(lmax,varargin)
obj=gravity.unit(lmax,'scale_per_coeff',randn(lmax+1),varargin{:},'skip_common_ops',true);
end
function [obj,w]=sin(lmax,w,varargin)
%NOTICE: it's probably a good idea to define a time domain when calling this method
obj=gravity.unit(lmax,varargin{:},'skip_common_ops',true);
%handle definitions of w
switch class(w)
case 'char'
switch w
case 'randn'; w=abs(randn(1,obj.width));
case 'seq' ; w=1:obj.width;
otherwise
error(['Cannot handle input ''w'' with value ',w,'.'])
end
case 'double'
assert(numel(w)==obj.width,'Input ''w'' must be defined for every coefficient')
otherwise
error(['Cannot handle input ''w'' of class ',class(w),'.'])
end
obj=obj.assign(cell2mat(arrayfun(@(i) sin(obj.t2x*pi/i),w,'UniformOutput',false)));
if isempty(obj.descriptor),obj.descriptor='sinusoidal';end
end
%% data loading
% epoch-parsing functions, needed by the load functions below
function out=parse_epoch_grace(filename)
[~,f]=fileparts(filename);
%GSM-2_2015180-2015212_0027_JPLEM_0001_0005.gsm
%123456789012345678901234567890
start=dateshift(...
time.doy2datetime(...
str2double(f(7 :10)),...
str2double(f(11:13))...
),...
'start','day');
stop =dateshift(...
time.doy2datetime(...
str2double(f(15:18)),...
str2double(f(19:21))...
),...
'end','day');
out=mean([start,stop]);
end
function out=parse_epoch_aiub(filename)
[~,f]=fileparts(filename);
%AIUB_swarmABC_201312_70x70.gfc
%123456789012345678901234567890
start=dateshift(datetime([f(15:18),'-',f(19:20),'-01']),'start','month');
stop =dateshift(datetime([f(15:18),'-',f(19:20),'-01']),'end', 'month');
out=mean([start,stop]);
end
function out=parse_epoch_aiub_slr(filename)
[~,f]=fileparts(filename);
%AIUB-SLR_0301_1010.gfc
%123456789012345678901234567890
start=dateshift(datetime(['20',f(10:11),'-',f(12:13),'-01']),'start','month');
stop =dateshift(datetime(['20',f(10:11),'-',f(12:13),'-01']),'end', 'month');
out=mean([start,stop]);
end
function out=parse_epoch_asu(filename)
[~,f]=fileparts(filename);
%asu-swarm-2014-10-nmax40-orbits-aiub.gfc
%123456789012345678901234567890
start=dateshift(datetime([f(11:14),'-',f(16:17),'-01']),'start','month');
stop =dateshift(datetime([f(11:14),'-',f(16:17),'-01']),'end', 'month');
out=mean([start,stop]);
end
function out=parse_epoch_ifg(filename)
[~,f]=fileparts(filename);
%coeff-2015-03-SaSbSc-AIUB.gfc
%123456789012345678901234567890
start=dateshift(datetime([f(07:10),'-',f(12:13),'-01']),'start','month');
stop =dateshift(datetime([f(07:10),'-',f(12:13),'-01']),'end', 'month');
out=mean([start,stop]);
end
function out=parse_epoch_csr(filename)
%2016-11.GEO.716424
%12345678901234567890
[~,file]=fileparts(filename);
year =str2double(file(1:4));
month=str2double(file(6:7));
out=gravity.CSR_RL05_date(year,month);
end
function out=parse_epoch_gswarm(filename)
[~,file]=fileparts(filename);
persistent kv
if isempty(kv)
%GSWARM_GF_SABC_COMBINED_2014-11_01.gfc
%0000000001111111111222222222233333333334
%1234567890123456789012345678901234567890
kv={...
'COMBINED',25;...
'AIUB', 21;...
'ASU', 20;...
'IFG', 20;...
'OSU', 20;...
'IGG', 20;...
};
end
idx=0;
for i=1:size(kv,1)
if strcmp(file(16:16+length(kv{i,1})-1),kv{i,1})
idx=kv{i,2}; break
end
end
assert(idx>0,['Cannot find any of the keywords ''',strjoin(kv(:,1),''', '''),''' in the filename ''',filename,'''.'])
year =str2double(file(idx :idx+3));
month=str2double(file(idx+5:idx+6));
out=datetime(year,month,1);
out=out+(dateshift(out,'end','month')-out)/2;
end
function out=parse_epoch_swarm(filename)
%SW_OPER_EGF_SHA_2__20210701T000000_20210731T235959_0101
[~,file]=fileparts(filename);
file=strsplit(file,'_');
out=mean([...
time.ToDateTime(file{6},'yyyyMMdd''T''HHmmss'),...
time.ToDateTime(file{7},'yyyyMMdd''T''HHmmss')+seconds(1),...
]);
end
function out=parse_epoch_tn14(filename)
%NOTICE: these data live in ~/data/SLR/TN-14/ (not set explicitly)
%NOTICE: these data need to be converted with ~/data/SLR/TN-14/convert_TN-14.sh
%NOTICE: graceC20 handles these data directly from the published data file
%TN-14_C30_C20_GSFC_SLR.55942.5.gfc
%1234567890123456789012345678901234567890
[~,file]=fileparts(filename);
out=time.ToDateTime(str2double(file(24:30)),'mjd');
end
function out=parse_epoch_esamtm(filename)
%mtmshc_A_19950104_06.180.mat
[~,file]=fileparts(filename);
file=strsplit(file,'_');
out=time.ToDateTime([file{3},'T',file{4}(1:2),'0000'],'yyyyMMdd''T''HHmmss');
end
% load functions
function [m,e]=load(file_name,varargin)
v=varargs.wrap('sources',{...
{...
'format', 'auto', @ischar;...
'time',datetime('now'), @isdatetime;...
'force', false, @(i) islogical(i) || ischar(i);...
'force_time', false, @(i) islogical(i) || ischar(i);...
},...
},varargin{:});
%default type
if isempty(v.format) || strcmp(v.format,'auto')
[~,fn,v.format]=fileparts(file_name);
%get rid of the dot
v.format=v.format(2:end);
%check if this is CSR format
if strcmp(fn,'GEO') || strcmp(v.format,'.GEO')
v.format='csr';
end
end
%handle mat files
[~,~,ext]=fileparts(file_name);
if strcmp(ext,'.mat')
datafile=file_name;
file_name=strrep(file_name,'.mat','');
else
datafile=[file_name,'.mat'];
end
%check if mat file is already available
if ~file.exist(datafile) || v.force
switch lower(v.format)
case 'gsm'
[m,e]=load_gsm(file_name,v.time);
case {'csr','geo'}
[m,e]=load_csr(file_name,v.time);
case {'icgem','gfc'}
[m,e]=load_icgem(file_name,v.time);
case 'mod'
[m,e]=load_mod(file_name,v.time);
case 'esamtm'
error('BUG TRAP: The ''esamtm'' format is always storred in mat files')
otherwise
error(['cannot handle models of type ''',v.format,'''.'])
end
try
save(datafile,'m','e')
catch
disp(['Could not save ''',datafile,'''.'])
end
else
switch lower(v.format)
case 'esamtm'
[m,e]=load_esamtm(datafile,v.time);
otherwise
%NOTICE: input argument 'time' is ignored here; only by coincidence (or design,
% e.g. if gravity.load_dir is used) will time be same as the one saved
% in the mat file.
load(datafile,'m','e')
%handle particular cases
if ~exist('m','var')
if exist('sol','var')
m=sol.mod.(sol.names{1}).dat;
e=[];
else
error(['Cannot handle mat file ',datafile,'; consider deleting so it is re-generated'])
end
end
end
end
%enforce input 'time', if requested
%NOTICE: this is used to be done automatically when loading the mat file
% (and there's no practical use for it at the moment)
if v.force_time
if m.t~=v.time;m.t=v.time;end
if ~isempty(e) && e.t~=v.time;e.t=v.time;end
end
%update start/stop for static fields, i.e. those with v.time=gravity.static_start_date
if v.time==gravity.static_select_date
%enforece static start date
m.t=gravity.static_start_date;
%duplicate model and set it to static stop date
m_stop=m;
m_stop.t=gravity.static_stop_date;
%append them together
m=m.append(m_stop);
%do the same to the error model if there is one
if ~isempty(e)
e.t=gravity.static_start_date;
e_stop=e;
e_stop.t=gravity.static_stop_date;
e=e.append(e_stop);
end
end
end
% NOTICE: the single-file load functions generally do not accept common_ops arguments so that
% the model parameters defined in the data files are honoured and cannot be overwriten
% NOTICE: unlike the single-file load functions, the load_dir function accepts common_ops arguments,
% which are enforced after loading the individual data files, and saved in the datastorage
% data products
function [m,e]=load_dir(varargin)
v=varargs.wrap('sources',{...
{...
'datadir', '.', @ischar;...
'date_parser', 'gravity.parse_epoch_grace', @ischar;...
'wildcarded_filename','*.gfc', @ischar;...
'descriptor', '', @ischar;...
'start', [], @(i) isempty(i) || (isdatetime(i) && isscalar(i));... %NOTICE: start/stop is only used to avoid loading models outside a certain time range
'stop', [], @(i) isempty(i) || (isdatetime(i) && isscalar(i));... %NOTICE: start/stop is only used to avoid loading models outside a certain time range
'overwrite_common_t', false, @islogical;
'skip_common_ops', false, @islogical;
'show_time', true, @islogical;
},...
},varargin{:});
%retrieve all gsm files in the specified dir
filelist=file.unwrap(fullfile(v.datadir,v.wildcarded_filename));
assert(~isempty(filelist{1}),['Need valid dir, not ''',fileparts(filelist{1}),'''.'])
%this counter is needed to report the duplicate models correctly
c=0;init_flag=true;
if v.show_time
%show remaining time to load models
s.msg=['Loading models from ',v.datadir]; s.n=numel(filelist);
end
%loop over all models
for i=1:numel(filelist)
%skip png and yamls files (some files inheret the name of the models)
[~,~,ext]=fileparts(filelist{i});
if cells.isincluded({'.png','.yaml'},ext); c=c+1; continue; end
%get time of the model in this file
if strcmpi(v.date_parser,'static')
%if a static field is requested, there should be only one file
if numel(filelist)~= 1
error(['when requested a static field, can only handle a single file, not ',...
num2str(numel(filelist)),'.'])
end
%patch missing start epoch (static fields have no epoch)
t=gravity.static_select_date;
else
f_date_parser=str2func(v.date_parser);
t=f_date_parser(filelist{i});
%skip if this t is outside the required range (or invalid)
if isempty(t) || ( time.isfinite(v.start) && time.isfinite(v.stop) && (t<v.start || v.stop<t) )
c=c+1; continue
end
end
%user feedback
[~,f]=fileparts(filelist{i});
if ~v.show_time
disp(['Loading ',f,' (to date ',datestr(t),')'])
end
%load the data
if init_flag
%init output objects
[m,e]=gravity.load(filelist{i},'time',t);
%init no more
init_flag=false;
else
%use temp container
[m1,e1]=gravity.load(filelist{i},'time',t);
%check if there are multiple models defined at the same epoch
if any(m.istavail(m1.t))
%find the model with the same epoch that has already been loaded
[~,f_saved ]=fileparts(filelist{m.idx(m1.t)+c});
if v.overwrite_common_t
disp(['Replacing ',f_saved,' with ',f,' (same epoch).'])
else
disp(['Ignoring ',f,' because this epoch was already loaded from model ',f_saved,'.'])
c=c+1; continue
end
end
%ensure R and GM are compatible append to output objects
m1=m1.scale(m);
m=m.append(m1.set_lmax(m.lmax),v.overwrite_common_t);
%same for error models, if there
if ~isempty(e1)
e1=e1.scale(e);
e=e.append(e1.set_lmax(e.lmax),v.overwrite_common_t);
end
end
if v.show_time
s=time.progress(s,i);
end
end
%fix some parameters
m.origin=v.datadir;
e.origin=v.datadir;
if ~isempty(v.descriptor)
m.descriptor=v.descriptor;
e.descriptor=['error of ',v.descriptor];
end
%enforce common ops
if ~v.skip_common_ops
m=gravity.common_ops('all',m,varargin{:});
e=gravity.common_ops('all',e,varargin{:});
end
end
function out=sh2grid(in_file,varargin)
[d,f,e]=fileparts(in_file);
%TODO: Need to defer any option that is already implemented in common ops to be passed
% transparently to it (through gravity.load_dir)
v=varargs.wrap('sources',{...
{...
'datadir', d, @ischar;...
'date_parser', 'gravity.parse_epoch_grace', @ischar;...
'wildcarded_filename', [f,e], @ischar;...
'static', 'ggm05c', @ischar;...
'smoothing_radius', 750e3, @isnumeric;...
'functional', 'eqwh', @ischar;...
'spatial_step', 1, @isnumeric;
'C20_replacement', 'none', @ischar;... %NOTICE: 'GSFC5x5' is a good option for this
'lmax', -1, @isnumeric;
},...
},varargin{:});
%load the data
g=gravity.load_dir(...
'datadir',v.datadir,...
'date_parser','gravity.parse_epoch_gswarm',...
'wildcarded_filename',v.wildcarded_filename,...
'descriptor',v.wildcarded_filename...
);
%set max degree
if v.lmax>0
g.lmax=v.lmax;
end
%replace C20
if ~str.none(v.C20_replacement)
c20=slr.load(v.C20_replacement,'time',g.t);
g=g.setC(2,0,c20.C(2,0));
end
%remove static model
g=g-gravity.static(v.static).set_lmax(g.lmax).scale(g).set_t(g.t(1));
%convert to equivalent water height
g=g.scale(v.smoothing_radius,'gauss').scale(v.functional,'functional');
%convert to grid
out=g.grid('spatial_step',v.spatial_step).center_resample;
%export to xyz format
out_file=str.rep(in_file,'*','_','.gfc',['.',v.functional,'.xyz']);
disp(['Grid of ',in_file,' saved to ',out_file])
out.xyz(out_file)
end
%% vector operations to make models compatible
function lmax=vlmax(model_list)
p=machinery.inputParser;
p.addRequired( 'model_list', @(i) iscell(i) && all(cellfun(isa(i,'gravity'))))
p.parse(model_list)
lmax=min(cell2mat(cellfun(@(i) i.lmax,model_list)));
end
function gm=vGM(model_list)
p=machinery.inputParser;
p.addRequired( 'model_list', @(i) iscell(i) && all(cellfun(isa(i,'gravity'))))
p.parse(model_list)
gm=min(cell2mat(cellfun(@(i) i.GM,model_list)));
end
function r=vR(model_list)
p=machinery.inputParser;
p.addRequired( 'model_list', @(i) iscell(i) && all(cellfun(isa(i,'gravity'))))
p.parse(model_list)
r=min(cell2mat(cellfun(@(i) i.R,model_list)));
end
%% common operations
function out=common_ops_args
out={...
'max_degree', -1 , @(i) isnumeric(i) && isscalar(i);...
'smoothing_radius', 750e3, @isnumeric;...
'functional', 'eqwh', @ischar;...
'use_GRACE_C20', false , @(i) ischar(i) || islogical(i); ...
'delete_C00', false , @islogical; ...
'delete_C20', false , @islogical; ...
'start', time.zero_date , @isdatetime; ...
'stop', time.inf_date , @isdatetime; ...
'static_model', 'none' , @ischar; ...
'tide_system', gravity.parameters('tide_system'), @ischar;...
};
end
%define the data filename for various products
function out=common_ops_filename(varargin)
%parse varargin values
v=varargs.wrap('sources',{...
%these are parameters that define the common ops
gravity.common_ops_args ...
%these are parameters relevant to the operations of this method
{...
'data_dir', '.' , @ischar;...
'product', 'grace' , @ischar;...
}...
},varargin{:});
%get unparsed common_ops_args (i.e. the defaults values)
v0=varargs(gravity.common_ops_args);
%get list of common ops argument names
arg_list=v0.Parameters;
%init parameters that have default values and do not need to show up in the filename
no_name_parameters=cell(1,numel(arg_list)+2);
no_name_parameters{1}='data_dir';
no_name_parameters{2}='product';
%loop over all common ops arguments
for i=1:numel(arg_list)
if strcmp(str.show(v.(arg_list{i})),str.show(v0.(arg_list{i})))
no_name_parameters(i+2)=arg_list(i);
end
end
out=fullfile(...
v.data_dir,...
str.clean(...
strjoin(...
{...
v.product,...
v.name(...
cells.rm_empty(no_name_parameters)...
),'mat'...
},'.'...
),'succ','.'...
)...
);
end
function mod=common_ops(mode,mod,varargin)
%trivial call
if mod.common_ops_done
%this means the common ops have already been done, most likely on models that have
%been used to compute the one being considered now (e.g. model differences)
return
end
%handle vector call on mode
if iscellstr(mode)
for i=1:numel(mode)
mod=gravity.common_ops(mode{i},mod,varargin{:});
end
else
% parse input arguments
v=varargs.wrap('sources',{...
%these are parameters that define the common ops
gravity.common_ops_args, ...
{...
%there's no good reason to change these parameters
'consistent_R', true , @islogical; ...
'consistent_GM', true , @islogical; ...
%these are parameters relevant to the operations of this method
'use_GRACE_C20_plot', false , @islogical; ...
'date_parser', 'none' , @ischar; ...
'model_type', 'signal', @ischar;...
'debug', false , @islogical;...
'silent', false , @islogical;...
},...
},varargin{:});
%sanity
if exist('mod','var') && ~isa(mod,'gravity')
str.say(['Ignoring model ',mod.descriptor,' since it is of class ''',class(mod),''' and not of class ''gravity''.'])
return
end
%inits user feedback vars
msg='';
switch mode
case 'all'
mod=gravity.common_ops(gravity.common_ops_mode_list,mod,v.varargin{:});
%update records
mod.common_ops_done=true;
%get out so that no message is shown for sure
return
case 'consistent_GM'
if str.logical(v.consistent_GM)
mod=mod.setGM(gravity.parameters('GM'));
msg=['set to ',num2str(gravity.parameters('GM'))];
end
case 'consistent_R'
if str.logical(v.consistent_R)
mod=mod.setR( gravity.parameters('R'));
msg=['set to ',num2str(gravity.parameters('R'))];
end
case 'max_degree'
%set maximum degree (if requested)
if v.max_degree>0
mod.lmax=v.max_degree;
msg=['set to ',num2str(v.max_degree)];
end
case 'smoothing_radius'
if str.logical(v.smoothing_radius)
mod=mod.scale(v.smoothing_radius,'gauss');
msg=['set to ',num2str(v.smoothing_radius)];
end
case 'functional'
if str.logical(v.functional)
mod=mod.scale(v.functional,'functional');
msg=['set to ',num2str(v.functional)];
end
case 'use_GRACE_C20'
%set C20 coefficient
if ~str.none(v.use_GRACE_C20) && strcmp(v.model_type,'signal')