-
Notifications
You must be signed in to change notification settings - Fork 5
/
gswarm.m
2920 lines (2858 loc) · 131 KB
/
gswarm.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 gswarm
properties(Constant)
datadir_options={...
'~/data/gswarm';...
'./data/gswarm';...
};
start_date=datetime('2013-12-01');
% for i=1:12
% disp([num2str(i),' : ',datestr(...
% dateshift(dateshift(datetime(['2022-',num2str(i,'%02i'),'-15']),'start','months')-calmonths(2),'start','quarter')-days(1)...
% )]);
% end
%NOTICE: assigns the end date of the processing according to the current month as follows:
% 1 : 30-Sep-2021
% 2 : 30-Sep-2021
% 3 : 31-Dec-2021
% 4 : 31-Dec-2021
% 5 : 31-Dec-2021
% 6 : 31-Mar-2022
% 7 : 31-Mar-2022
% 8 : 31-Mar-2022
% 9 : 30-Jun-2022
% 10 : 30-Jun-2022
% 11 : 30-Jun-2022
% 12 : 30-Sep-2022
stop_date=dateshift(dateshift(datetime('now'),'start','months')-calmonths(2),'start','quarter')-days(1);
%TODO: define a parameter for the plot_lines_over_gaps_narrower_than and addgaps(...), currently 120 and 45 resp.
end
methods(Static)
function out=dir(type)
base=file.orbdir('swarm_data',true);
switch type
case {'data','base'}
out=base;
case {'aiub','asu','ifg','igg','osu','tudelft'}
out=fullfile(base,type);
%add more directories here
otherwise
error(['Cannot handle type ''',type,'''.'])
end
end
function obj=load_models(obj,product,varargin)
% add input arguments and metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
{...
'import_dir', '.',@(i) ischar(i) && exist(i, 'dir')~=0;...
'model_format','unknonw',@ischar;...
'date_parser', 'unknonw',@ischar;...
'consistent_GM', false,@islogical;...
'consistent_R', false,@islogical;...
'max_degree' 0,@num.isscalar;...
'use_GRACE_C20', 'none',@ischar;...
'delete_C00', false,@islogical;...
'delete_C20', false,@islogical;...
'model_span', {time.zero_date,time.inf_date},@(i) isnumeric(i) && numel(i)==2;...
'static_model', 'none',@ischar;...
'overwrite_common_t',false,@islogical;...
},...
product.args...
},varargin{:});
%load all available data
[s,e]=gravity.load_dir(...
'datadir',v.import_dir,...
'format',v.model_format,...
'descriptor',product.name,...
v.varargin{:}...
);
%make sure we got a gravity object
assert(isa(s,'gravity'),['failed to load product ',product.codename])
% resolve dataname to save the data to: sometimes, the 'signal' field path is given explicitly and
% we don't want to save data to product.signal.signal and product.signal.error
dn=product.dataname;
if any(dn.isanyfield_path(v.model_types))
for i=1:numel(dn.field_path)
if any(strcmp(dn.field_path{i},v.model_types))
if i==1
dn=dn.set_field_path({});
else
dn=dn.set_field_path(dn.field_path(1:i-1));
end
end
end
end
%propagate relevant data
for i=1:numel(v.model_types)
switch lower(v.model_types{i})
case {'signal','sig','s'}
obj=obj.data_set(dn.append_field_leaf(v.model_types{i}),s);
case {'error','err','e'}
obj=obj.data_set(dn.append_field_leaf(v.model_types{i}),e);
otherwise
error(['unknown model type ''',v.model_types{i},'''.'])
end
end
end
function obj=load_project_models(obj,product,varargin)
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
% add input arguments and metadata to collection of parameters 'v'
v=varargs.wrap('sources',{product.args},varargin{:});
%loop over all requested scenarios
for i=1:numel(v.scenarios)
p=product;
p.dataname=p.dataname.append_field_leaf(v.scenarios{i});
obj=gswarm.load_models(obj,p,'import_dir',fullfile(v.import_dir,[v.project_name,'-',v.scenarios{i}]),varargin{:});
end
obj.log('@','out','product',product,'start',obj.start,'stop',obj.stop)
end
function obj=smooth_models(obj,product,varargin)
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
%retrieve relevant parameters
smoothing_degree =product.mdget('smoothing_degree');
smoothing_method =product.mdget('smoothing_method');
model_types =product.mdget('model_types','always_cell_array',true);
%sanity
assert(product.nr_sources==1,['Can only handle one source model, not ',num2str(product.nr_sources),'.'])
%loop over all models
for i=1:numel(model_types)
%gather model
m=obj.data_get_scalar(product.sources(1).append_field_leaf(model_types{i}));
%branch on the type of model, do not smooth error models
switch lower(model_types{i})
case {'error','err','e'}
%do nothing
otherwise
if smoothing_degree>0
%apply smoothing
m=m.scale(smoothing_degree,smoothing_method);
end
end
%save the smoothed model
obj=obj.data_set(product.dataname.append_field_leaf(model_types{i}),m);
end
obj.log('@','out','product',product,'start',obj.start,'stop',obj.stop)
end
function obj=combine_models(obj,product,varargin)
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
%retrieve relevant parameters
combination_type =product.mdget('combination_type');
model_type =product.dataname.field_path{end};
%collect the models
m=cell(product.nr_sources,1);
for i=1:product.nr_sources
m{i}=obj.data_get_scalar(product.sources(i));
end
%propagate relevant data
switch lower(model_type)
case {'error','err','e'}
obj=obj.data_set(product,gravity.combine(m,'mode',combination_type,'type','error'));
otherwise
obj=obj.data_set(product,gravity.combine(m,'mode',combination_type,'type','signal'));
end
obj.log('@','out','product',product,'start',obj.start,'stop',obj.stop)
end
function obj=stats(obj,product,varargin)
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
%retrieve relevant parameters
derived_quantity=product.mdget('plot_spatial_diff_quantity');
functional =product.mdget('functional');
stats =product.mdget('stats');
stats_outlier_iter=product.mdget('stats_outlier_iter');
stats_detrend =product.mdget('stats_detrend');
stats_period =product.mdget('stats_period');
stats_overlap =product.mdget('stats_overlap');
%sanity
assert(product.nr_sources==1,['Can only handle one source model, not ',num2str(product.nr_sources),'.'])
%get the model
g=obj.data_get_scalar(product.sources(1)).scale(functional,'functional');
%compute cumulative amplitude time series
ts=g.derived(derived_quantity);
%derive statistics
s=ts.stats(...
'struct_fields',stats,...
'outlier_iter',stats_outlier_iter,...
'detrend',stats_detrend,...
'period', stats_period,...
'overlap',stats_overlap...
);
%add field with degree
s.degree=0:g.lmax;
%save data
obj=obj.data_set(product,s);
obj.log('@','out','product',product,'start',obj.start,'stop',obj.stop)
end
%% plots
function out=file_root(obj,product)
%NOTICE: 'storage_period' 'direct' is needed so that only one name is returned, otherwise
% a cell array with numerous filenames may be returned, depending on the storage period
out=product.mdset('storage_period','direct').file('plot',...
'start',obj.start,...
'stop',obj.stop,...
'start_timestamp_only',false,...
'no_extension',true,...
'sub_dirs','single',...
'use_storage_period',true...
);
end
function pod=plot_ops(obj,product,varargin)
%TODO: make inventory of the the operations done in this method, maybe wrap them in a switch loop, as is the case with gravity.common_ops
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
% add input arguments and plot metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
plotting.default,...
{...
'plot_min_degree', 2 ,@num.isscalar;... %NOTICE: this needs to be handled externally!
'plot_max_degree', inf ,@num.isscalar;...
'plot_smoothing_degree', [] ,@num.isscalar;...
'plot_smoothing_method', '' ,@ischar;...
'plot_spatial_mask', 'none' ,@iscellstr;...
'stats_relative_to', 'none' ,@ischar;...
'model_types', {'*'} ,@iscellstr;...
'plot_lines_over_gaps_narrower_than',days(120),@isduration;...
'plot_time_domain_source',0 ,@num.isscalar;...
'inclusive', false ,@islogical;... %generally we want plots to be exclusive, i.e. not show non-common data (e.g. C20 from 2002-04)
'plot_force', false ,@islogical;...
},...
product.args({'stats_relative_to','model_types'}),...
product.plot_args...
},varargin{:});
% update start/stop considering the requested inclusive
obj=obj.startstop_update(...
'start',gswarm.production_date('start'),...
'stop', gswarm.production_date('stop'),...
'inclusive',v.inclusive...
);
obj.log('@','startstop_update','product',product,'start',obj.start,'stop',obj.stop)
%retrieve load/saving of plotdata: handles plot_force and plot_save_data
[loaddata,savedata]=plotting.forcing(v.varargin{:});
%first build data filename;
datafilename=obj.plotdatafilename(product);
%check if data is to be loaded
if loaddata
%check if plot data is saved
if ~isempty(datafilename) && file.exist(datafilename,v.plot_force)
str.say('Loading plot data from ',datafilename)
load(datafilename,'out')
pod=out;
%we're done
return
else
savedata=true;
end
end
%collect the models
pod.source.n=0; %this acts as a counter inside the following for loop but becomes a constant thereafter
pod.source.dat=cell(0);pod.source.datanames=cell(0);
for i=1:product.nr_sources
dn_sources=obj.data_list(product.sources(i));
%dn_sources is usually 'signal' (and 'error' sometimes) but can be anything
%NOTICE: all different dn_sources (more specifically the model_type) are clumped together under pod.source.dat
for j=1:numel(dn_sources)
%check if there's any value in the field path to define the type of model
if ~isempty(dn_sources{j}.field_path)
%model_types {'*'} gathers everything
if ~cells.isincluded(v.model_types,'*')
%only plot the relevant model types (the metadata 'model_types' defines the relevant model types)
if ~cells.isincluded(dn_sources{j}.field_path(end),v.model_types); continue;end
end
%get this model type
model_type=dn_sources{j}.field_path{end};
else
%assume signal if no field path to specify the type of model
model_type='signal';
end
%only iterate on the requested model type
if cells.isincluded({model_type},v.model_types)
pod.source.n=pod.source.n+1;
%save general dataname
pod.source.datanames(pod.source.n)=dn_sources(j);
end
%save this model_type (most likely out.source.dat{out.source.n})
pod.source.dat{pod.source.n}=obj.data_get_scalar(dn_sources(j));
%handle default value of plot_max_degree
%TODO: fix this, it makes it impossible to plot degree ranges above inclusive maximum
v.plot_max_degree=min([pod.source.dat{pod.source.n}.lmax,v.plot_max_degree]);
end
end
%enforce maximum degree
pod.source.dat=cellfun(@(i) i.set_lmax(v.plot_max_degree),pod.source.dat,'UniformOutput',false);
%enforce smoothing
if ~isempty(v.plot_smoothing_degree) && ~isempty(v.plot_smoothing_method) && ~str.none(v.plot_smoothing_method)
v.plot_smoothing_degree=cells.c2m(v.plot_smoothing_degree);
if isscalar(v.plot_smoothing_degree)
v.plot_smoothing_degree=v.plot_smoothing_degree*ones(size(pod.source.dat));
else
assert(numel(v.plot_smoothing_degree)==pod.source.n,...
['If plot_smoothing_degree is a vector (now with length ',num2str(numel(v.plot_smoothing_degree)),...
'), it needs to have the same number of elemets as sources (now equal to ',num2str(pod.source.n),').'])
end
for i=1:pod.source.n
%smooth the data
pod.source.dat{i}=pod.source.dat{i}.scale(...
v.plot_smoothing_degree(i),...
v.plot_smoothing_method...
);
%save smoothing annotations
smoothing_name=gravity.gauss_smoothing_name(v.plot_smoothing_degree(i));
pod.source.file_smooth{i}=strjoin({'smooth',v.plot_smoothing_method,smoothing_name},'_');
pod.source.title_smooth{i}=str.show({smoothing_name,...
gravity.smoothing_name(v.plot_smoothing_method),'smoothing'});
end
%NOTICE: these are used in plots where all sources are shown together
pod.file_smooth=pod.source.file_smooth{end};
pod.title_smooth=pod.source.title_smooth{end};
else
for i=1:pod.source.n
pod.source.file_smooth{i}='';
pod.source.title_smooth{i}='';
end
%NOTICE: these are used in plots where all sources are shown together
pod.file_smooth='';
pod.title_smooth='';
end
%define the time domain to plot
if v.plot_time_domain_source==0
%set time domain common to all sources
pod.t=simpletimeseries.t_mergev(pod.source.dat);
else
%set time domain equal to the requested source
pod.t=pod.source.dat{v.plot_time_domain_source}.t;
end
%enforce spatial mask
switch v.plot_spatial_mask
case 'none'
%do nothing
pod.title_masking='';
otherwise
switch v.plot_spatial_mask
case {'ocean','land'}
pod.title_masking=str.show({v.plot_spatial_mask,'areas'});
otherwise
pod.title_masking=v.plot_spatial_mask;
end
%enforce masking
for i=1:numel(pod.source.dat)
str.say('Applying',v.plot_spatial_mask,'mask to product',pod.source.datanames{i}.name)
pod.source.dat{i}=pod.source.dat{i}.spatial_mask(v.plot_spatial_mask);
end
end
%find reference product
switch v.stats_relative_to
case 'none'
pod.source.names=cellfun(...
@(i) strtrim(strrep(str.clean(i,v.plot_title_suppress),'.',' ')),...
cellfun(@(i) i.name,pod.source.datanames,'UniformOutput',false),...
'UniformOutput',false...
);
pod.mod.names=pod.source.names;
%alias sources to mods and res
pod.mod.dat=pod.source.dat;
pod.mod.res=pod.source.dat;
%patch remaining details
pod.source.ref_idx=[];
pod.source.mod_idx=1:pod.source.n;
pod.title_wrt='';
otherwise
for i=1:pod.source.n
str.say(pod.source.datanames{i}.filename,'?=',v.stats_relative_to)
if str.iseq(pod.source.datanames{i}.filename,v.stats_relative_to)
pod.mod.ref=pod.source.dat{i};
pod.source.ref_idx=i;
pod.mod.ref_name=pod.source.datanames{pod.source.ref_idx};
break
end
end
assert(isfield(pod.source,'ref_idx'),['None of the sources of product ',product.str,...
' match ''stats_relative_to'' equal to ''',v.stats_relative_to,'''.'])
%get the indexes of the sources to plot (i.e. not the reference)
pod.source.mod_idx=[1:pod.source.ref_idx-1,pod.source.ref_idx+1:pod.source.n];
%get product name difference between products to derive statistics from
if numel(pod.source.mod_idx)<2
pod.mod.names={strjoin(datanames.unique(pod.source.datanames(pod.source.mod_idx)),' ')};
pod.source.names(pod.source.mod_idx)=strrep(pod.mod.names,'_',' ');
else
pod.mod.names=cellfun(@(i) strjoin(i,' '),datanames.unique(pod.source.datanames(pod.source.mod_idx)),'UniformOutput',false);
pod.source.names(pod.source.mod_idx)=cellfun(@(i) strrep(i,'_',' '),pod.mod.names,'UniformOutput',false);
end
pod.source.names{pod.source.ref_idx}=upper(strtrim(strrep(str.clean(pod.mod.ref_name.name,v.plot_title_suppress),'.',' ')));
%reduce the models to plot
pod.mod.dat=pod.source.dat(pod.source.mod_idx);
%get reference
ref=pod.mod.ref.interp(pod.t,'interp_over_gaps_narrower_than',v.plot_lines_over_gaps_narrower_than);
%enforce consistent GM and R
pod.mod.dat=cellfun(@(i) i.scale(pod.mod.ref),pod.mod.dat,'UniformOutput',false);
%compute residual
%NOTICE: need to interpolate a second time to force explicit gaps (first time was when retrieving ref)
pod.mod.res=cellfun(...
@(i) ref-i.interp(pod.t,'interp_over_gaps_narrower_than',v.plot_lines_over_gaps_narrower_than),...
pod.mod.dat,'UniformOutput',false);
% pod.mod.res=cell(size(pod.mod.dat));
% for i=1:numel(pod.mod.dat)
% dat=pod.mod.dat{i}.interp(pod.t,'interp_over_gaps_narrower_than',v.plot_lines_over_gaps_narrower_than);
% pod.mod.res{i}=ref-dat.interp(pod.t);
% end
% %NOTICE: probably it's not a good idea to use 'interp_over_gaps_narrower_than' here because that can
% % produce different time domains and break the subtraction.
% pod.mod.res=cellfun(@(i) pod.mod.ref.interp(pod.t)-i.interp(pod.t),pod.mod.dat,'UniformOutput',false);
%title
pod.title_wrt=str.show({'wrt',pod.source.names{pod.source.ref_idx}});
end
%easier names
pod.source.names_str=strjoin(str.rep(str.clean(pod.source.names,'succ_blanks'),' ','_'),'-');
%filename particles
pod.file_root=gswarm.file_root(obj,product);
pod.file_deg=['deg',num2str(v.plot_min_degree),'-',num2str(v.plot_max_degree)];
%legend
if numel(pod.source.datanames)>1
pod.source.legend_str=cellfun(@(i) strjoin(i,' '),datanames.unique(pod.source.datanames),'UniformOutput',false);
else
pod.source.legend_str=str.rep(pod.source.datanames{1}.str,'.',' ','/',' ');
end
%patch empty legend entries (this expects there to be only one empty legend entry)
if any(cells.isempty(pod.source.legend_str))
pod.source.legend_str(cells.isempty(pod.source.legend_str))={strjoin(datanames.common(pod.source.datanames),' ')};
end
%time info in the title
for i=1:pod.source.n
pod.source.title_startstop{i}=['(',...
datestr(pod.source.dat{i}.t_masked([],'start'),'yyyy-mm'),' to ',...
datestr(pod.source.dat{i}.t_masked([],'stop' ),'yyyy-mm'),')'...
];
end
%NOTICE: this is used in plots where all sources are shown together
pod.title_startstop=['(',...
datestr(pod.source.dat{1}.t_masked([],'start'),'yyyy-mm'),' to ',...
datestr(pod.source.dat{1}.t_masked([],'stop' ),'yyyy-mm'),')'...
];
%save data if requested
if savedata
str.say('Saving plot data to ',datafilename)
out=pod;
save(datafilename,'out');
end
%start/stop
[~,pod.startlist,pod.stoplist]=product.file('data',v.varargin{:},'start',obj.start,'stop',obj.stop);
obj.log('@','out','product',product,'start',obj.start,'stop',obj.stop)
end
function obj=plot_low_degrees(obj,product,varargin)
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
% add input arguments and plot metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
plotting.default,...
{...
'plot_max_lines',inf,@num.isscalar;...
'show_legend_stats', 'yes' ,@str.islogical;...
'plot_lines_over_gaps_narrower_than',days(120),@isduration;...
'plot_legend_sorting','ascend', @ischar;...
'plot_force',false,@islogical;...
'plot_legend_include_smoothing',false,@islogical;...
},...
product.args...
},varargin{:});
%collect the models, unless given externally
v=varargs.wrap('sources',{v,...
{...
'pod',[],@isstruct;...
}...
},varargin{:});
if isempty(v.pod); v.pod=gswarm.plot_ops(obj,product,v.varargin{:}); end
%build title suffix and legend prefix
legend_str_prefix=cell(1,v.pod.source.n);
for k=1:v.pod.source.n
legend_str_prefix{k}=upper(v.pod.source.legend_str{k});
end
if v.plot_legend_include_smoothing
for k=1:v.pod.source.n
legend_str_prefix{k}=strjoin([legend_str_prefix(k),v.pod.source.title_smooth(k)],' ');
end
title_suffix=strjoin({v.pod.title_masking},' ');
else
title_suffix=strjoin({v.pod.title_masking,v.pod.title_smooth},' ');
end
%get collection of degrees/orders (this looks at arguments 'degrees' and 'orders')
[degrees,orders]=gravity.resolve_degrees_orders(v.varargin{:});
%loop over all requested degrees and orders
for i=1:numel(degrees)
d=degrees(i);
o=orders(i);
filename=file.build(v.pod.file_root,['C',num2str(d),',',num2str(o)],v.pod.file_smooth,'png');
%plot only if not done yet
if ~file.exist(filename,v.plot_force)
%build legend string
legend_str=cell(1,v.pod.source.n);
trivial_idx=true(size(legend_str));
%make room for loop records
ts_now=cell(1,v.pod.source.n); stats=cell(size(ts_now));
plotting.figure(v.varargin{:});
%loop over all models
for k=1:v.pod.source.n
%plot the time series for this degree/order and model
ts_now{k}=v.pod.source.dat{k}.ts_C(d,o).addgaps(v.plot_lines_over_gaps_narrower_than);
%don't plot trivial data
if isempty(ts_now{k}) || ts_now{k}.iszero
trivial_idx(k)=false;
stats{k}.corrcoef=-1;stats{k}.rms=inf;
continue
end
%add statistics to the legend (unless this is the product from which the stats are derived)
if k~=v.pod.source.ref_idx
mod_ref_now=v.pod.mod.ref.ts_C(d,o).interp(...
ts_now{k}.t,'interp_over_gaps_narrower_than',v.plot_lines_over_gaps_narrower_than...
);
if all(isnan(mod_ref_now.y(:)))
stats{k}.corrcoef=NaN;stats{k}.rms=NaN;
else
stats{k}=ts_now{k}.stats2(mod_ref_now,'mode','struct','struct_fields',{'corrcoef','rms'},'period',seconds(inf));
end
if v.show_legend_stats
legend_str{k}=[legend_str_prefix{k},...
' corr=',num2str(stats{k}.corrcoef,'%.2f'),...
', RMS{\Delta}=',num2str(stats{k}.rms,'%.2g')];
else
legend_str{k}=legend_str_prefix{k};
end
else
if ~isempty(v.pod.source.ref_idx)
legend_str{k}=[legend_str_prefix{k},' (reference)'];
else
legend_str{k}=legend_str_prefix{k};
end
stats{k}.corrcoef=1;stats{k}.rms=0;
end
end
%get rid of trivial data
ts_now=ts_now(trivial_idx);
legend_str=legend_str(trivial_idx);
stats=stats(trivial_idx);
%sort it (if requested)
switch v.plot_legend_sorting
case {'ascend','descend'}; [~,idx]=sort(cellfun(@(i) i.rms,stats),'ascend');
case {'none','no'}; idx=1:numel(stats);
otherwise
error(['Cannot handle ''plot_legend_sorting'' with value ''',v.plot_legend_sorting,'''.'])
end
%truncate it
idx=idx(1:min(numel(ts_now),v.plot_max_lines));
ts_now=ts_now(idx);
legend_str=legend_str(idx);
%plot it
for k=1:numel(ts_now)
%tweak markers
switch ts_now{k}.nr_valid
case 1; line_fmt='o';
case 2; line_fmt='+-';
otherwise; line_fmt='-';
end
ts_now{k}.plot('line',{line_fmt});
end
%enforce it
product.enforce_plot(v.varargin{:},...
'plot_ylabel','[ ]',...
'plot_legend',legend_str,...
'plot_line_color_order',idx,...
'plot_title',v.plot_title,...
'plot_title_default',['C',num2str(d),',',num2str(o),' ',title_suffix]...
);
plotting.save(filename,v.varargin{:})
else
disp(['NOTICE: plot already available: ',filename])
end
end
obj.log('@','out','product',product,'start',obj.start,'stop',obj.stop)
end
function obj=plot_spatial_stats(obj,product,varargin)
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
% add input arguments and plot metadata to collection of parameters 'v'
v=varargs.wrap('sources',{...
plotting.default,...
{...
'plot_min_degree', 2, @num.isscalar;...
'plot_max_degree', inf, @num.isscalar;...
'plot_functional', 'geoid', @gravity.isfunctional;...
'plot_type', 'line', @(i) cells.isincluded(i,{'line','bar'});...
'plot_show_legend_stats',false, @islogical;...
'plot_max_nr_lines', 20, @num.isscalar;...
'plot_spatial_stat_list' ,{'diff','monthly'} , @iscellstr; ... TODO: corr
'plot_spatial_diff_quantity' ,{'cumdas','gridmean'}, @(i) all(cellfun(@(j) ismethod(gravity.unit(1),j),i));... %relevant if plot_spatial_stat_list has 'diff'
'plot_spatial_monthly_quantity',{'das','triang'} , @iscellstr;... %relevant if plot_spatial_stat_list has 'monthly': one plot per month
'plot_spatial_monthly_error' ,false , @islogical;... %relevant if plot_spatial_stat_list has 'monthly': include format error in das monthly plots
'plot_spatial_monthly_last' ,inf , @num.isscalar;...%relevant if plot_spatial_stat_list has 'monthly': only plots these last months
'plot_spatial_monthly_triang_caxis',[-inf inf] , @(i) isnumeric(i) && numel(i)==2;...%relevant if plot_spatial_stat_list has 'monthly': define triang plots' caxis
'plot_legend_include_smoothing', false, @islogical;...
'plot_lines_over_gaps_narrower_than', days(120), @isduration;...
'plot_signal', false, @islogical;...
'plot_summary', true, @islogical;...
'plot_logy', false, @islogical;...
'plot_legend_sorting','ascend', @ischar;...
'plot_force', false, @islogical;...
'plot_detrended', '', @ischar;... %see simpledata.detrend for modes, empty means no detrending
'plot_outlier_iter', false, @isfinite;... %number of outlier removal iters, see simpledata.stats
'plot_Kp', false, @islogical;...
},...
product.plot_args...
},varargin{:});
%collect the models, unless given externally
v=varargs.wrap('sources',{v,...
{...
'pod',[],@isstruct;...
}...
},varargin{:});
if isempty(v.pod); v.pod=gswarm.plot_ops(obj,product,v.varargin{:}); end
%check if this plot is requested
if cells.isincluded(v.plot_spatial_stat_list,'diff')
%loop over all requested derived quantities
for qi=1:numel(v.plot_spatial_diff_quantity)
%do not detrend for gridmean
switch v.plot_spatial_diff_quantity{qi}
case 'gridmean'
plot_detrended='none';
otherwise
plot_detrended=v.plot_detrended;
end
%% prepare data for (summary) diff rms plots
%build filenames
filenames={...
file.build(v.pod.file_root, v.plot_spatial_diff_quantity{qi}, v.pod.file_smooth,'png');...
file.build(v.pod.file_root,[v.plot_spatial_diff_quantity{qi},'_summary'],v.pod.file_smooth,'png');...
};
%prepare plot data only if needed
if any(~file.exist(filenames,v.plot_force))
%build data array (number of rows is short by one if v.plot_signal && stats_relative_to)
y=cell(1,numel(v.pod.mod.res));t=cell(size(y));yc=zeros(size(y));
for di=1:numel(v.pod.mod.res)+1
%branch to retrieve data that the stats are derived relative to
switch di
case numel(v.pod.mod.res)+1
if v.plot_signal && ~str.none(product.mdget('stats_relative_to','default','none'))
tmp=v.pod.source.dat{v.pod.source.ref_idx};
else
continue
end
otherwise
tmp=v.pod.mod.res{di};
end
%operate
tmp=tmp.interp(...
v.pod.t,... %interp to common time domain
'interp_over_gaps_narrower_than',... %and remove lines connecting over large gaps
v.plot_lines_over_gaps_narrower_than...
).addgaps(... %add explicit gaps: catches the case when v.pod.t is implicitly gapped
v.plot_lines_over_gaps_narrower_than...
).scale(...
v.plot_functional,'functional'... %scale to functional
).outlier(... %maybe detrend and remove outliers, depends on value of :
'outlier_iter',v.plot_outlier_iter,... % - handled inside the obj.outlier method
'detrend',plot_detrended... % - handled inside the obj.detrend method (called by obj.outlier)
);
%save time
t{di}=tmp.t;
tmp=tmp.(...
v.plot_spatial_diff_quantity{qi}... %compute derived quantity
);
%propagate relevant data point
y{di}=tmp(:,end);
%average it
yc(di)=sum(y{di},1,'omitnan')./sum(~isnan(y{di}));
end
%sort it (if requested)
switch v.plot_legend_sorting
case {'ascend','descend'}; [yc_sorted,idx]=sort(yc,'ascend');
case {'none','no'}; yc_sorted=yc;idx=1:numel(yc);
otherwise
error(['Cannot handle ''plot_legend_sorting'' with value ''',v.plot_legend_sorting,'''.'])
end
y_sorted=y(idx);
%build legend
legend_str=upper(v.pod.mod.names);
if v.plot_legend_include_smoothing
for i=1:numel(legend_str)
legend_str{i}=strjoin([legend_str(i),v.pod.source.title_smooth(v.pod.source.mod_idx(i))],' ');
end
title_suffix=strjoin({v.pod.title_masking},' ');
else
title_suffix=strjoin({v.pod.title_masking,v.pod.title_smooth},' ');
end
%add legend signal
if v.plot_signal && ~str.none(product.mdget('stats_relative_to','default','none'))
n=numel(legend_str);
legend_str{n+1}=upper(v.pod.source.legend_str{v.pod.source.ref_idx});
for i=1:n
legend_str{i}=strjoin([legend_str(i),'diff w.r.t.',legend_str(n+1)],' ');
end
if v.plot_legend_include_smoothing
legend_str{n+1}=strjoin([legend_str(n+1),v.pod.source.title_smooth(v.pod.source.ref_idx)],' ');
end
end
%sort the legend
legend_str=legend_str(idx);
%truncate it
if v.plot_max_nr_lines < numel(idx)
y_sorted= y_sorted(1:v.plot_max_nr_lines);
yc_sorted= yc_sorted(1:v.plot_max_nr_lines);
legend_str=legend_str(1:v.plot_max_nr_lines);
idx=idx( 1:v.plot_max_nr_lines);
end
%trim nans for plotting
t_sorted=cell(size(y_sorted));
for di=1:numel(y_sorted)
plot_idx=any(num.trim_NaN(y_sorted{di}),2);
y_sorted{di}=y_sorted{di}(plot_idx);
t_sorted{di}=t{di}(plot_idx);
end
%compute abs value in case of log scale
if str.logical(v.plot_logy)
y_sorted=cellfun(@abs,y_sorted,'UniformOutput',false);
end
%plot abs value for gridmean
switch v.plot_spatial_diff_quantity{qi}
case 'gridmean'
y_sorted=cellfun(@abs,y_sorted,'UniformOutput',false);
otherwise
%do nothing
end
end
%% plot diff cumdas/gridmean
fn_idx=1;
if ~file.exist(filenames{fn_idx},v.plot_force)
%plot it
plotting.figure(v.varargin{:}); hold on
for di=1:numel(y_sorted)
switch v.plot_type
case 'bar'; bar(t_sorted{di},y_sorted{di},'EdgeColor','none');
case 'line'; plot(t_sorted{di},y_sorted{di},'Marker','o');
end
end
%deal with legend stats
if v.plot_show_legend_stats
for di=1:numel(legend_str)
legend_str{di}=[legend_str{di},...
' ',num2str(mean(y_sorted{di}(~isnan(y_sorted{di}))),2),...
' +/- ',num2str( std(y_sorted{di}(~isnan(y_sorted{di}))),2),...
' \Sigma=',num2str( sum(y_sorted{di}(~isnan(y_sorted{di}))),2)];
end
end
%deal with title prefix
switch v.plot_spatial_diff_quantity{qi}
case 'gridmean'; title_prefix='Mean diff.';
case 'cumdas'; title_prefix='RMS diff.';
otherwise
error(['cannot handle plot_spatial_diff_quantity with value ''',...
v.plot_spatial_diff_quantity{qi},'''.'])
end
%enforce it
product.enforce_plot(v.varargin{:},...
'plot_legend',legend_str,...
'plot_ylabel',gravity.functional_label(v.plot_functional),...
'plot_xdate',true,...
'plot_xlimits',[min(cellfun(@(i) i(1),t_sorted)),max(cellfun(@(i) i(end),t_sorted))+days(1)],...
'plot_line_color_order',idx,...
'plot_title',v.plot_title,...
'plot_title_default',str.show({title_prefix,v.pod.title_wrt,title_suffix})...
);
%plot Kp, if requested and this is cumdas
if strcmp(v.plot_spatial_diff_quantity{qi},'cumdas') && v.plot_Kp
%update the data (no output from this command)
kp.download
%load the data
k=kp.load('start',obj.start,'stop',obj.stop);
%plot it on the left axis
yyaxis right
area(k.t,smooth(k.F107adj,15),'FaceColor','k','FaceAlpha',0.1,'EdgeAlpha',0.1)
ylabel('F_{10.7} index (15 day average)')
%update the legend text (https://stackoverflow.com/questions/22048494/change-figure-legend-text)
hl = findobj(gcf, 'tag', 'legend');
ltext = get(hl,'string');
ltext{end} = 'F_{10.7}';
set(hl,'string',ltext);
end
plotting.save(filenames{fn_idx},v.varargin{:})
else
disp(['NOTICE: plot already available: ',filenames{fn_idx}])
end
%% plot cumulative diff rms (summary)
fn_idx=2;
if ~file.exist(filenames{fn_idx},v.plot_force) && numel(yc_sorted)>1 && v.plot_summary
%plot it
plotting.figure(v.varargin{:});
grey=[0.5 0.5 0.5];
barh(flipud(yc_sorted(:)),'EdgeColor',grey,'FaceColor',grey);
set(gca,'YTick',1:numel(legend_str),'yticklabels',str.clean(legend_str,'title'));
%enforce it
product.enforce_plot(v.varargin{:},...
'plot_legend_location','none',...
'plot_ylabel','none',...
'plot_xlabel',gravity.functional_label(v.plot_functional),...
'plot_ylimits',[0 numel(legend_str)+1],...
'plot_title',v.plot_title,...
'plot_title_default',str.show({'Cum. residual',v.pod.title_wrt,v.pod.title_startstop,title_suffix})...
);
set(gca,...
'YTick',1:numel(legend_str),...
'yticklabels',plotting.legend_replace_clean(v.varargin{:},'plot_legend',flipud(legend_str(:)))...
);
plotting.save(filenames{fn_idx},v.varargin{:})
else
disp(['NOTICE: plot already available: ',filenames{fn_idx}])
end
end
end
%% epoch-wise plots
%check if this plot is requested
if cells.isincluded(v.plot_spatial_stat_list,'monthly')
title_suffix=strjoin({v.pod.title_masking,v.pod.title_smooth},' ');
if isfinite(v.plot_spatial_monthly_last)
assert(v.plot_spatial_monthly_last>0,'the parameter ''plot_spatial_monthly_last'' must be positive')
%NOTICE: there's no need to decrement start_idx because the last model is a empty by definition
start_idx=numel(v.pod.t)-v.plot_spatial_monthly_last;
else
start_idx=1;
end
for i=start_idx:numel(v.pod.t)
%gather models valid now
dat =cellfun(@(j) j.interp(v.pod.t(i)),v.pod.source.dat,'UniformOutput',false);
dat_idx=cellfun(@(j) j.nr_valid>0,dat);
%gather error if requested
if v.plot_spatial_monthly_error
try
dat_error=cellfun(@(j) j.interp(v.pod.t(i)),v.pod.source.error,'UniformOutput',false);
catch
v.plot_spatial_monthly_error=false;
disp('WARNING: cannot plot monthly error because it is not available. Implementation needed.')
end
end
%check if there's any data to plot
if all(~dat_idx); continue;end
%reduce data
dat=dat(dat_idx);
if v.plot_spatial_monthly_error
dat_error=dat_error(dat_idx);
end
legend_str=upper(v.pod.source.names(dat_idx));
%loop over all requested derived quantities
for qi=1:numel(v.plot_spatial_monthly_quantity)
%build filename
filename=file.build(...
v.pod.file_root,v.plot_spatial_monthly_quantity{qi},...
datestr(v.pod.t(i),'YYYYmmdd'),v.pod.file_smooth,'png');...
if ~file.exist(filename,v.plot_force)
%branch on the type of plot
switch v.plot_spatial_monthly_quantity{qi}
case 'das'
plotting.figure(v.varargin{:});
for j=1:numel(dat)
dat{j}.plot('mode',v.plot_spatial_monthly_quantity{qi},'functional',v.plot_functional);
end
%enforce it
product.enforce_plot(v.varargin{:},...
'plot_legend',legend_str,...
'plot_ylabel',gravity.functional_label(v.plot_functional),...
'plot_colormap','jet',...
'plot_title',v.plot_title,...
'plot_title_default',str.show({datestr(v.pod.t(i),'yyyy-mm'),'degree-RMS',title_suffix})...
);
if v.plot_spatial_monthly_error
%get previous lines
lines_before=findobj(gca,'Type','line');
%plot errors
for j=1:numel(dat)
dat_error{j}.plot('method',v.plot_spatial_monthly_quantity{qi},'functional',v.plot_functional,'line','--');
end
%get all lines
lines_all=findobj(gca,'Type','line');
%set consistent line clours
for j=1:numel(dat)
set(lines_all(j),'Color',get(lines_before(j),'Color'),'LineWidth',v.plot_line_width)
end
axis auto
title(str.show({datestr(v.pod.t(i),'yyyy-mm'),'degree-RMS ',title_suffix}))
end
case {'triang','trianglog10'}
[~,l,w]=plotting.subplot(0,numel(dat));
plotting.figure(v.varargin{:},...
'plot_size',200+[0,0,21,9]*30.*[1 1 w l]);
for j=1:numel(dat)
plotting.subplot(j,numel(dat),true);
dat{j}.plot('method',v.plot_spatial_monthly_quantity{qi},...
'colormap',str.clean(v.plot_colormap,{'opt','zero'}),... %TODO: fix this once plotting.colormap is implemented and used in gravity.plot
'functional',v.plot_functional...
);
%enforce it
product.enforce_plot(v.varargin{:},...
'plot_colormap','none',...
'plot_caxis',v.plot_spatial_monthly_triang_caxis,...
'plot_title',v.plot_title,...
'plot_title_default',str.show({legend_str{j},datestr(v.pod.t(i),'yyyy-mm'),title_suffix})...
);
end
otherwise
error(['Cannot handle plot_spatial_monthly_quantity as ''',v.plot_spatial_monthly_quantity{qi},'''.'])
end
plotting.save(filename,v.varargin{:})
else
disp(['NOTICE: plot already available: ',filename])
end
end
end
end
%check if this plot is requested
if cells.isincluded(v.plot_spatial_stat_list,'corr')
error('not yet implemented)')
end
obj.log('@','out','product',product,'start',obj.start,'stop',obj.stop)
end
function obj=plot_temporal_stats(obj,product,varargin)
obj.log('@','in','product',product,'start',obj.start,'stop',obj.stop)
% add input arguments and plot metadata to collection of parameters 'v'
v=varargs.wrap('sources',{....
plotting.default,...
{...
'plot_min_degree', 2, @num.isscalar;...
'plot_max_degree', inf, @num.isscalar;...
'plot_rms_caxis', [-inf inf], @isnumeric;...
'plot_functional', 'geoid', @gravity.isfunctional;...
'plot_type', 'line', @(i) cells.isincluded(i,{'line','bar'});...
'plot_max_nr_lines', 20, @num.isscalar;...
'plot_temp_stat_list', {...
'corrcoeff',...
'rms',...
'std'...
}, @iscellstr; ...
'plot_temp_stat_title',{...
'temporal corr. coeff.',...
'temporal RMS\Delta',...
'temporal STD\Delta'....
}, @iscellstr; ...
'plot_legend_include_smoothing', false, @islogical;...
'plot_legend_sorting', 'ascend', @ischar;...
'plot_corrcoeff_caxis', [-1,1], @(i) isnumeric(i) && numel(i)==2 && all(abs(i)<=1)
'plot_summary', true, @islogical;...
'plot_force', false, @islogical;...
'plot_detrended', '', @ischar;... %see simpledata.detrend for modes, empty means no detrending (defined in simpledata.stats)
'plot_outlier_iter', 0, @isfinite;... %number of outlier removal iters, see simpledata.stats
'plot_lines_over_gaps_narrower_than', days(120), @isduration;...
},...
product.plot_args...
},varargin{:});
%collect the models, unless given externally
v=varargs.wrap('sources',{v,...
{...
'pod',[],@isstruct;...
}...
},varargin{:});
if isempty(v.pod); v.pod=gswarm.plot_ops(obj,product,v.varargin{:}); end
%loop over all statistics
for s=1:numel(v.plot_temp_stat_list)
%maybe nothing is requested to be plotted
if strcmp(v.plot_temp_stat_list{s},'none'); continue; end
%do not detrend for correlation coefficients
switch v.plot_temp_stat_list{s}
case {'corrcoeff','rms'}
plot_detrended='none';
otherwise
plot_detrended=v.plot_detrended;
end
%collect arguments for call to stats/stats2
stats_args={...
'mode','obj',...
'struct_fields',v.plot_temp_stat_list(s),...
'outlier_iter',v.plot_outlier_iter,...
'detrend',plot_detrended,...
'period',seconds(inf)...
};
%% triangular plots
%loop over all sources
%NOTICE: out.pod.mod.dat have one less element than out.pod.source.dat, so keep that in mind and don't mix them!
for i=1:numel(v.pod.mod.dat)
%build filename
filename=file.build(v.pod.file_root,...
{v.plot_temp_stat_list{s},'triang'},v.pod.source.file_smooth{i},strsplit(v.pod.mod.names{i},' '),'png'...
);
%plot only if not done yet
if ~file.exist(filename,v.plot_force)
plotting.figure(v.varargin{:});
tmp=v.pod.mod.dat{i}.scale(v.plot_functional,'functional');
if isfield(v.pod.mod,'ref')
%compute the requested stat between this model and mod_ref
d=tmp.stats2(...
v.pod.mod.ref.scale(v.plot_functional,'functional').interp(...
tmp.t,'interp_over_gaps_narrower_than',v.plot_lines_over_gaps_narrower_than...
),...
stats_args{:}...
);