/
statistics.ncl
1890 lines (1688 loc) · 56.9 KB
/
statistics.ncl
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
; #############################################################################
; GENERAL ROUTINES FOR STATISTICS
; #############################################################################
; Please consider using of extending existing routines before adding new ones.
; Check the header of each routine for documentation.
;
; Contents:
; function dim_stddev_wgt_Wrap
; function time_operations
; function calc_season_index
; function extract_season
; function month_to_season_extended
; function coswgt_areaave
; function coswgt_arearmse
; function coswgt_pattern_cor
; function interannual_variability
; function calculate_metric
; function normalize_metric
; function distrib_stats
; function lognormal_dist
; function filter121
; function get_average
;
; #############################################################################
load "$diag_scripts/../interface_scripts/auxiliary.ncl"
load "$diag_scripts/../interface_scripts/logging.ncl"
load "$diag_scripts/shared/latlon.ncl"
load "$diag_scripts/shared/regridding.ncl"
; #############################################################################
undef("dim_stddev_wgt_Wrap")
function dim_stddev_wgt_Wrap(field[*]:numeric,
ww[*]:numeric,
opt[1]:integer)
;
; Arguments
; field: a one-dimensional numeric array.
; ww: a one-dimensional numeric array of the same size of field.
; opt: a scalar, it has the same meaning as in the corresponding NCL
; function dim_avg_wgt_Wrap
;
; Return value
; A float or a double depending on the type of input
;
; Description
; Calculates the (unbiased) weighted standard deviation consistently with
; the NCL function dim_std_dev (i.e. it divides by N-1 instead of N). For
; the weighted case this means applying a correction factor:
; sum(w_i)/[sum(w_i)^2 - sum(w_i^2)]
; Missing values are ignored.
;
; Caveats
;
; References
; en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance
;
; Modification history
; 20150511-lauer_axel: modified routine "calculate_metric":
; added "no weigth" (nowgt) option
; 20141215-righi_mattia: written.
;
local funcname, scriptname, wavg, wgt, v1, v2, d2, arg
begin
funcname = "dim_stddev_wgt_Wrap"
scriptname = "diag_scripts/shared/statistics.ncl"
enter_msg(scriptname, funcname)
; Copy to local
wgt = ww
wgt@_FillValue = default_fillvalue(typeof(wgt))
if (dimsizes(field).lt.2) then
error_msg("f", scriptname, funcname, "input field contains " + \
"only 1 element, cannot calculate standard deviation")
end if
; Calculate weighted mean
wavg = dim_avg_wgt_Wrap(field, ww, opt)
; Filter missing values
if (.not.all(ismissing(field))) then
v1 = sum(where(ismissing(field), wgt@_FillValue, wgt))
v2 = sum(where(ismissing(field), wgt@_FillValue, wgt) ^ 2)
else
out = 1. ; initialize
out@_FillValue = field@_FillValue
out = field@_FillValue
return(out)
end if
; Calculate weighted standard deviation
d2 = (field - wavg) ^ 2
arg = dim_sum_wgt_Wrap(d2, ww, opt)
out = sqrt(v1 / (v1 ^ 2 - v2) * arg)
leave_msg(scriptname, funcname)
return(out)
end
; #############################################################################
undef("time_operations")
function time_operations(field:numeric,
y1[1]:integer,
y2[1]:integer,
oper[1]:string,
opt[1]:string,
l_wgt[1]:logical)
;
; Arguments
; field: a numeric array of rank 1 to 4, first dimension must be time.
; y1: start year of the time period to be averaged (-1 for full range).
; y2: end year of the time period to be averaged (-1 for full range).
; oper: type of operations:
; "extract": no average, just extract selected period.
; "average": average.
; "stddev": (unbiased) standard deviation.
; opt: operation options (has no effect is oper = extract):
; "annualclim": annual climatology.
; "seasonalclim": seasonal climatology for the standard seasons DJF,
; MAM, JJA, SON.
; "monthlyclim": monthly climatology jan-dec.
; "yearly": time average over every year in [y1:y2].
; [month strings]: climatology of selected (consecutive) months
; (e.g., "MAM", "SONDJ").
; [1, 12]: climatology of the selected month ("1"=Jan, "2"=Feb, ...,
; "12"=Dec).
; l_wgt: if True, calculate weighted average, with days-per-month as
; weights (has no effect is opt = "extract").
;
; Return value
; An array of the same rank as field or of rank-1, depending on oper/opt.
;
; Description
; Performs differnt types of time average, standard deviation or extraction
; of a selected time period. Weighted average (with days-per-month as
; weights) can be optionally applied.
;
; Caveats
; The weighted standard deviation is not yet implmented for all cases
; The weighted standard deviation is calculated using the unbiased estimator
; This should take into account missing values and exclude the w_i for
; which the field contains only missing values. This feature is not
; implemented yet.
;
; References
;
; Modification history
; 20201214-lauer_axel: bugfix time weights
; 20190503-righi_mattia: removed obsolete option "mymm" (used only in
; reformat_obs, now outdated).
; 20140703-gottschaldt_klaus-dirk: added option "mymm".
; 20140312-righi_mattia: extended with standard deviation.
; 20140109-righi_mattia: written.
;
local funcname, scriptname, monthstr, date, year, month, idx1, idx2, loc_y1, \
loc_y2, rank, subfield, weights, idx, idx_win, idx_spr, idx_sum, idx_aut, \
mm, idx_1st, idx_arr, p1, p2, d2, arg, v1, v2, ym_in, years, nyear, ym, \
dims, timec, FillValue, index
begin
funcname = "time_operations"
scriptname = "diag_scripts/shared/statistics.ncl"
enter_msg(scriptname, funcname)
; Check arguments
if (all(oper.ne.(/"extract", "average", "stddev"/))) then
error_msg("f", scriptname, funcname, "unrecognized operation " + oper)
end if
; Check for time dimension
if (field!0.ne."time") then
error_msg("f", scriptname, funcname, "the first dimension " + \
"of input is not time")
end if
; Check for calendar attribute
if (.not.isatt(field&time, "calendar")) then
error_msg("f", scriptname, funcname, "time dimension of " + \
"input must have a calendar attribute")
end if
; Define months string
monthstr = "JFMAMJJASOND"
monthstr = monthstr + monthstr
; Define flags
l_ext = oper.eq."extract"
l_avg = oper.eq."average"
l_std = oper.eq."stddev"
; Calculate date from time coordinate
date := cd_calendar(field&time, 0)
year := date(:, 0)
month := date(:, 1)
cal = field&time@calendar
; check that calendar is supported by 'days_in_month'
valid_cal = (/"standard", "gregorian", "julian", "360_day", "360", \
"365_day", "365", "366_day", "366", "noleap", "no_leap", \
"allleap", "all_leap", "none"/)
if (ismissing(ind(valid_cal .eq. cal))) then
log_info("Warning: unsupported calendar in function " + funcname + \
" (" + scriptname + "): " + cal + ". Using 'standard' instead.")
cal = "standard"
end if
; Determine indexes for the requested time range
if (y1.eq.-1) then
idx1 = 0
loc_y1 = toint(min(date(:, 0)))
else
idx1 = min(ind(year.eq.y1))
loc_y1 = y1
end if
if (y2.eq.-1) then
idx2 = dimsizes(field&time) - 1
loc_y2 = toint(max(date(:, 0)))
else
idx2 = max(ind(year.eq.y2))
loc_y2 = y2
end if
if (ismissing(idx1).or.ismissing(idx2)) then
error_msg("f", scriptname, funcname, "the selected time " + \
"period is out of range")
end if
delete(date)
delete(year)
delete(month)
; Extract requested time range
rank = dimsizes(dimsizes(field))
if (rank.eq.4) then
subfield = field(idx1:idx2, :, :, :)
end if
if (rank.eq.3) then
subfield = field(idx1:idx2, :, :)
end if
if (rank.eq.2) then
subfield = field(idx1:idx2, :)
end if
if (rank.eq.1) then
subfield = field(idx1:idx2)
end if
; Re-calculate date for subfield
date := cd_calendar(subfield&time, 0)
year := date(:, 0)
month := date(:, 1)
rank := dimsizes(dimsizes(subfield))
; Define weights as days-per-month
if (l_wgt) then
iyear = toint(year)
iyear@calendar = cal
weights = days_in_month(iyear, toint(month))
else
weights = tofloat(subfield&time)
weights = 1.
end if
; Extract only
if (l_ext .and. opt.eq."") then
leave_msg(scriptname, funcname)
return(subfield)
end if
; Calculate time average/standard deviation according to the opt argument
; Multi-year average
if (opt.eq."annualclim") then
if (l_avg) then
out = dim_avg_wgt_n_Wrap(subfield, weights, 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
leave_msg(scriptname, funcname)
return(out)
end if
; Year average
if (opt.eq."yearly") then
ny = loc_y2 - loc_y1 + 1
if (rank.eq.4) then
out = subfield(0:ny - 1, :, :, :) ; Copy metadata
do yy = loc_y1, loc_y2
idx = ind(year.eq.yy)
if (l_avg) then
out(yy - loc_y1, :, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx, :, :, :), weights(idx), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
delete(idx)
end do
end if
if (rank.eq.3) then
out = subfield(0:ny - 1, :, :) ; Copy metadata
do yy = loc_y1, loc_y2
idx = ind(year.eq.yy)
if (l_avg) then
out(yy - loc_y1, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx, :, :), weights(idx), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
delete(idx)
end do
end if
if (rank.eq.2) then
out = subfield(0:ny - 1, :) ; Copy metadata
do yy = loc_y1, loc_y2
idx = ind(year.eq.yy)
if (l_avg) then
out(yy - loc_y1, :) = \
dim_avg_wgt_n_Wrap(subfield(idx, :), weights(idx), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
delete(idx)
end do
end if
if (rank.eq.1) then
out = subfield(0:ny - 1) ; Copy metadata
do yy = loc_y1, loc_y2
idx = ind(year.eq.yy)
if (l_avg) then
out(yy - loc_y1) = \
dim_avg_wgt_Wrap(subfield(idx), weights(idx), 1)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
delete(idx)
end do
end if
out!0 = "year"
delete(out&year)
out&year = ispan(loc_y1, loc_y2, 1)
leave_msg(scriptname, funcname)
return(out)
end if
; Season average
if (opt.eq."seasonalclim") then
idx_win = ind(month.eq.1.or.month.eq.2.or.month.eq.12)
idx_spr = ind(month.eq.3.or.month.eq.4.or.month.eq.5)
idx_sum = ind(month.eq.6.or.month.eq.7.or.month.eq.8)
idx_aut = ind(month.eq.9.or.month.eq.10.or.month.eq.11)
if (rank.eq.4) then
out = subfield(0:3, :, :, :)
if (l_avg) then
out(0, :, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_win, :, :, :), \
weights(idx_win), 1, 0)
out(1, :, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_spr, :, :, :), \
weights(idx_spr), 1, 0)
out(2, :, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_sum, :, :, :), \
weights(idx_sum), 1, 0)
out(3, :, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_aut, :, :, :), \
weights(idx_aut), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
if (rank.eq.3) then
out = subfield(0:3, :, :)
if (l_avg) then
out(0, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_win, :, :), weights(idx_win), 1, 0)
out(1, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_spr, :, :), weights(idx_spr), 1, 0)
out(2, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_sum, :, :), weights(idx_sum), 1, 0)
out(3, :, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_aut, :, :), weights(idx_aut), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
if (rank.eq.2) then
out = subfield(0:3, :)
if (l_avg) then
out(0, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_win, :), weights(idx_win), 1, 0)
out(1, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_spr, :), weights(idx_spr), 1, 0)
out(2, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_sum, :), weights(idx_sum), 1, 0)
out(3, :) = \
dim_avg_wgt_n_Wrap(subfield(idx_aut, :), weights(idx_aut), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
if (rank.eq.1) then
out = subfield(0:3)
if (l_avg) then
out(0) = dim_avg_wgt_Wrap(subfield(idx_win), weights(idx_win), 1)
out(1) = dim_avg_wgt_Wrap(subfield(idx_spr), weights(idx_spr), 1)
out(2) = dim_avg_wgt_Wrap(subfield(idx_sum), weights(idx_sum), 1)
out(3) = dim_avg_wgt_Wrap(subfield(idx_aut), weights(idx_aut), 1)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
delete(out&time)
out!0 = "season"
out&season = (/"DJF", "MAM", "JJA", "SON"/)
leave_msg(scriptname, funcname)
return(out)
end if
; Annual cycle
if (opt.eq."monthlyclim") then
if (rank.eq.4) then
out = subfield(0:11, :, :, :) ; Copy metadata
do mm = 0, 11
if (l_avg) then
out(mm, :, :, :) = \
dim_avg_wgt_n_Wrap(subfield(mm::12, :, :, :), \
weights(mm::12), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end do
end if
if (rank.eq.3) then
out = subfield(0:11, :, :) ; Copy metadata
do mm = 0, 11
if (l_avg) then
out(mm, :, :) = \
dim_avg_wgt_n_Wrap(subfield(mm::12, :, :), weights(mm::12), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end do
end if
if (rank.eq.2) then
out = subfield(0:11, :) ; Copy metadata
do mm = 0, 11
if (l_avg) then
out(mm, :) = \
dim_avg_wgt_n_Wrap(subfield(mm::12, :), weights(mm::12), 1, 0)
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end do
end if
if (rank.eq.1) then
out = subfield(0:11) ; Copy metadata
do mm = 0, 11
if (l_avg) then
out(mm) = dim_avg_wgt_Wrap(subfield(mm::12), weights(mm::12), 1)
end if
if (l_std) then
out(mm) = dim_stddev_wgt_Wrap(subfield(mm::12), weights(mm::12), 1)
end if
end do
end if
out!0 = "month"
delete(out&month)
out&month = (/"J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"/)
leave_msg(scriptname, funcname)
return(out)
end if
; Months string (at least 2 consecutive months): define indexes
if (.not.ismissing(str_match_ind_ic(monthstr, opt)).and. \
strlen(opt).ge.2.and.strlen(opt).le.12) then
idx_1st = str_index_of_substr(monthstr, str_upper(opt), 1)
idx_arr = new(strlen(opt), integer)
do ii = 0, strlen(opt) - 1
idx_arr(ii) = idx_1st + ii
end do
idx_arr = where(idx_arr.ge.12, idx_arr - 12, idx_arr) ; Periodicity
idx_arr = idx_arr + 1 ; From 0-based to month number
do ii = 0, dimsizes(idx_arr) - 1
if (.not.isdefined("idx")) then
idx = ind(month.eq.idx_arr(ii))
else
tmp = array_append_record(idx, ind(month.eq.idx_arr(ii)), 0)
delete(idx)
idx = tmp
delete(tmp)
end if
end do
delete(idx_1st)
delete(idx_arr)
end if
; Specific-month average: define indexes
if (any(opt.eq.tostring(ispan(1, 12, 1)))) then
idx = ind(month.eq.toint(opt))
end if
; Extract or average over the above indexes
if (isdefined("idx")) then
if (rank.eq.4) then
if (l_ext) then
out = subfield(idx, :, :, :)
end if
if (l_avg) then
if (dimsizes(idx) .eq. 1) then
out = \
dim_avg_wgt_n_Wrap(subfield(idx:idx, :, :, :), weights(idx), 1, 0)
else
out = dim_avg_wgt_n_Wrap(subfield(idx, :, :, :), weights(idx), 1, 0)
end if
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
if (rank.eq.3) then
if (l_ext) then
out = subfield(idx, :, :)
end if
if (l_avg) then
if (dimsizes(idx) .eq. 1) then
out = dim_avg_wgt_n_Wrap(subfield(idx:idx, :, :), weights(idx), 1, 0)
else
out = dim_avg_wgt_n_Wrap(subfield(idx, :, :), weights(idx), 1, 0)
end if
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
if (rank.eq.2) then
if (l_ext) then
out = subfield(idx, :)
end if
if (l_avg) then
if (dimsizes(idx) .eq. 1) then
out = dim_avg_wgt_n_Wrap(subfield(idx:idx, :), weights(idx), 1, 0)
else
out = dim_avg_wgt_n_Wrap(subfield(idx, :), weights(idx), 1, 0)
end if
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
if (rank.eq.1) then
if (l_ext) then
out = subfield(idx)
end if
if (l_avg) then
if (dimsizes(idx) .eq. 1) then
out = dim_avg_wgt_n_Wrap(subfield(idx:idx), weights(idx), 1, 0)
else
out = dim_avg_wgt_n_Wrap(subfield(idx), weights(idx), 1, 0)
end if
end if
if (l_std) then
error_msg("f", scriptname, funcname, "feature not yet implemented")
end if
end if
leave_msg(scriptname, funcname)
return(out)
end if
error_msg("f", scriptname, funcname, "unrecognized option " + opt)
end
; #############################################################################
undef("calc_season_index")
function calc_season_index(season[1]:string)
;
; Arguments
; season: the season in upper case.
;
; Return value
; The indices to the months in season, e.g. "JFM" returns (/0, 1, 2/).
;
; Description
; Given the "season", i.e., any substring from "JFMAMJJASOND", retrieves
; the corresponding indices. Crashes if given substring is not unique or
; does not exist.
;
; Caveats
;
; References
;
; Modification history
;
local funcname, scriptname, current_search_set, DEBUG, i, indices, months, \
start_index, strIndex, stringmonths, string_search_set, subStringLength
begin
funcname = "calc_season_index"
scriptname = "diag_scripts/shared/statistics.ncl"
enter_msg(scriptname, funcname)
DEBUG = False
; The months with a wrap around of six months
; (so we can find "DJF", etc..)
stringmonths = "JFMAMJJASONDJFMAMJ"
months = stringtochar(stringmonths)
; Loop using twelve months at a time from 'stringmonths', i.e, first
; iteration uses Jan -> Dec, next iteration uses April -> March, ...
do start_index = 0, 6, 3
current_search_set = months(start_index:start_index + 11)
string_search_set = charactertostring(current_search_set)
if (DEBUG) then
error_msg("f", scriptname, funcname, "string_search_set = " + \
string_search_set)
end if
strIndex = str_index_of_substr(string_search_set, season, 0)
if (DEBUG) then
error_msg("f", scriptname, funcname, "strIndex = " + strIndex)
end if
; Exit immediately if our substring 'season' is not unique
; (e.g., season="J")
if (dimsizes(strIndex) .gt. 1) then
error_msg("f", scriptname, funcname, "multiple occurences of substring")
end if
; If there is no match, grab a new set of twelve months
; from the wrap-around 'stringmonths'
if (ismissing(strIndex)) then
continue
end if
break
end do
; Exit if there is no match
if (ismissing(strIndex)) then
error_msg("f", scriptname, funcname, "could not find substring")
end if
; Compute the indices for the requested season
subStringLength = sizeof(stringtochar(season)) - 1
if (DEBUG) then
error_msg("f", scriptname, funcname, "subStringLength = " + \
subStringLength)
end if
indices = ispan(strIndex, strIndex + subStringLength - 1, 1)
indices = indices + start_index
if (DEBUG) then
error_msg("f", scriptname, funcname, "indices=" + indices)
end if
; Subtract indices larger than 11 (i.e., we have a wrap around case)
do i = 0, dimsizes(indices) - 1
if (indices(i) .gt. 11) then
indices(i) = indices(i) - 12
end if
end do
leave_msg(scriptname, funcname)
return(indices)
end
; #############################################################################
undef("extract_season")
function extract_season(data:numeric,
season[1]:string)
;
; Arguments
; data: a numeric field with time dimension.
; season: the season in upper case.
;
; Return value
; The temporal subset of indata defined by the 'season' string.
;
; Description
; Given the "season", i.e., any substring from "JFMAMJJASOND", retrieves
; the corresponding months from data.
;
; Caveats
;
; References
;
; Modification history
;
local funcname, scriptname, idx, subset_selection, months, newtime, \
seasonal_selection_ind, season_monthly_indices, sizes, start_of_year, \
tmp, local_indata, ndims
begin
funcname = "extract_season"
scriptname = "diag_scripts/shared/statistics.ncl"
enter_msg(scriptname, funcname)
season_monthly_indices = calc_season_index(season)
months = tointeger(cd_convert(data&time, "months since 1850-01-01 00:00"))
local_data = data
; Ensure first month is January
if (months(0) % 12 .ne. 0) then
start_of_year = ind(tointeger(months) % 12 .eq. 0)
sizes = dimsizes(local_data&time)
tmp = local_data(time|start_of_year(0):sizes - 1, lat|:, lon|:)
delete(local_data)
local_data = tmp
delete(tmp)
delete(months)
months = tointeger( \
cd_convert(local_data&time, "months since 1800-01-01 00:00"))
end if
months = months - min(months)
; Extract the given months
seasonal_selection_ind = ind(months % 12 .eq. season_monthly_indices(0))
do idx = 1, dimsizes(season_monthly_indices) - 1
tmp = array_append_record(seasonal_selection_ind, \
ind(months % 12.eq. \
season_monthly_indices(idx)), 0)
delete(seasonal_selection_ind)
seasonal_selection_ind = tmp
delete(tmp)
end do
qsort(seasonal_selection_ind)
ndims = dimsizes(dimsizes(local_data))
if (ndims .eq. 4) then ; Assume time, plev, lat, lon
subset_selection = \
local_data(time|seasonal_selection_ind, plev|:, lat|:, lon|:)
else if (ndims .eq. 3) then ; Assume time, lat, lon
subset_selection = local_data(time|seasonal_selection_ind, lat|:, lon|:)
else if (ndims .eq. 2) then ; Assume time, lat
subset_selection = local_data(time|seasonal_selection_ind, lat|:)
else if (ndims .eq. 1) then ; Assume time is only dimension
subset_selection = local_data(time|seasonal_selection_ind)
else
printVarSummary(local_data)
error_msg("fatal", scriptname, funcname,\
"ndims (=" + ndims + ") is assumed 1 <= ndims <= 4")
status_exit(1)
end if
end if
end if
end if
leave_msg(scriptname, funcname)
return(subset_selection)
end
; #############################################################################
undef("month_to_season_extended")
function month_to_season_extended(indata:float,
season[1]:string)
;
; Arguments
; indata: a [lat][lon][time] or.
; a [lat][lon][plev|[time] array
; season: compute the average for this season.
;
; Return value
; An array with the seasonal average for each year.
;
; Description
; For each year in the input data, averages indata over the given season.
;
; Caveats
;
; References
;
; Modification history
;
local funcname, scriptname, season_indices, dim_season_indices, \
runaveragedata, start_index, averagedata, dim
begin
funcname = "month_to_season_extended"
scriptname = "diag_scripts/shared/statistics.ncl"
enter_msg(scriptname, funcname)
indata_size = dimsizes(indata)
if (dimsizes(indata&time) % 12 .ne. 0) then
error_msg("f", scriptname, funcname, "time dimension must " + \
"be divisible by 12" + indata&time % 12)
end if
season_indices = calc_season_index(season)
dim_season_indices = dimsizes(season_indices)
; Compute average over 'dim_season_indices' number of months with the help
; of a running average
if (dimsizes(indata_size) .eq. 3) then
runaveragedata = \
runave_Wrap(indata({lat|:}, {lon|:}, time|:), dim_season_indices, 0)
else if(dimsizes(indata_size) .eq. 4) then
runaveragedata = \
runave_Wrap(indata({plev|:}, {lat|:}, {lon|:}, time|:), \
dim_season_indices, 0)
else
error_msg("f", scriptname, funcname, "wrong number of dimensions: " + \
dimsizes(indata_size) + ", only arrays with 3 or 4 " + \
"dimensions are supported")
end if
end if
; By picking the correct 'start_index' in the running average array we
; will retrieve the average over the indicated season
; (see runave-documentation for details)
if (dim_season_indices % 2 .eq. 0) then
start_index = season_indices(0) + (dim_season_indices - 2) / 2
else
start_index = season_indices(0) + (dim_season_indices - 1) / 2
end if
; Extract seasonal average for every year
if (dimsizes(indata_size) .eq. 3) then
averagedata = (/runaveragedata(time|start_index::12, lat|:, lon|:)/)
else if(dimsizes(indata_size) .eq. 4) then
averagedata = \
(/runaveragedata(time|start_index::12, plev|:, lat|:, lon|:)/)
else
error_msg("f", scriptname, funcname, "wrong number of dimensions: " + \
dimsizes(indata_size) + ", only arrays with 3 or 4 " + \
"dimensions are supported")
end if
end if
dim = 0
averagedata!dim = "time"
averagedata&time = runaveragedata&time(start_index::12)
dim = dim + 1
if(dimsizes(indata_size) .eq. 4) then
averagedata!dim = "plev"
averagedata&plev = runaveragedata&plev
dim = dim + 1
end if
averagedata!dim = "lat"
averagedata&lat = runaveragedata&lat
dim = dim + 1
averagedata!dim = "lon"
averagedata&lon = runaveragedata&lon
copy_VarAtts(indata, averagedata)
leave_msg(scriptname, funcname)
return(averagedata)
end
; #############################################################################
undef("coswgt_areaave")
function coswgt_areaave(field:numeric)
;
; Arguments
; field: numeric field.
;
; Return value
; The area average using cosine lat weights.
;
; Description
; Computes the area average using cosine lat weights and lon weights=1.
;
; Caveats
;
; References
;
; Modification history
; 20131209-evaldsson_martin: written.
;
local funcname, scriptname, lat, wgt_lat, lon, lon_size, wgt_lon, ave
begin
funcname = "coswgt_areaave"
scriptname = "diag_scripts/shared/statistics.ncl"
enter_msg(scriptname, funcname)
lat = field&lat
wgt_lat = tofloat(NormCosWgtGlobe(lat))
lon = field&lon
lon_size = dimsizes(lon)
wgt_lon = new((/lon_size(0)/), float)
wgt_lon = 1.0
ave = wgt_areaave_Wrap(field, wgt_lat, wgt_lon, 0)
leave_msg(scriptname, funcname)
return(ave)
end
; #############################################################################
undef("coswgt_arearmse")
function coswgt_arearmse(field1:numeric,
field2:numeric)
;
; Arguments
; field1: numeric field
; field2: numeric field
;
; Return value
; Area rmse average using cosine lat weights.
;
; Description
; Computes area rmse areage using cosine lat weights and lon weights=1.
;
; Caveats
;
; References
;
; Modification history
; 20131209-evaldsson_martin: written.
;
local funcname, scriptname, lat, wgt_lat, lon, lon_size, wgt_lon, rmse, \
local_field1, local_field2
begin
funcname = "coswgt_arearmse"
scriptname = "diag_scripts/shared/statistics.ncl"
enter_msg(scriptname, funcname)
field1_grid_size = guestimate_average_grid_area(field1)
field2_grid_size = guestimate_average_grid_area(field2)
if (field1_grid_size .gt. field2_grid_size) then
local_field2 = rect2rect_interp(field2, field1)
local_field1 = field1
else
local_field1 = rect2rect_interp(field1, field2)
local_field2 = field2
end if
lat = local_field1&lat
wgt_lat = tofloat(NormCosWgtGlobe(lat))
lon = local_field1&lon
lon_size = dimsizes(lon)
wgt_lon = new((/lon_size(0)/), float)
wgt_lon = 1.0
rmse = wgt_arearmse(local_field1, local_field2, wgt_lat, wgt_lon, 0)
leave_msg(scriptname, funcname)
return(rmse)
end
; #############################################################################
undef("coswgt_pattern_cor")
function coswgt_pattern_cor(field1:numeric,
field2:numeric)
;
; Arguments
; field1: numeric field.
; field2: numeric field.
;
; Return value
; Pattern correlation cosine lat weights.
;
; Description
;
; Caveats
;
; References
;
; Modification history
; 20140115-evaldsson_martin: written.
;
local funcname, scriptname, lat, wgt_lat, lon, lon_size, wgt_lon, \
pattern_correlation, local_field1, local_field2
begin
funcname = "coswgt_pattern_cor"
scriptname = "diag_scripts/shared/statistics.ncl"