-
Notifications
You must be signed in to change notification settings - Fork 0
/
fcst_metrics_tc.py
2403 lines (1895 loc) · 103 KB
/
fcst_metrics_tc.py
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
import os, sys, copy
import numpy as np
import xarray as xr
import json
import numpy as np
import datetime as dt
import logging
import configparser
import matplotlib
from IPython.core.pylabtools import figsize, getfigs
import importlib
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from eofs.standard import Eof
from eofs.xarray import Eof as Eof_xarray
from SensPlotRoutines import background_map
##### Function to compute the great circle distance between two points
def great_circle(lon1, lat1, lon2, lat2):
'''
Function that computes the distance between two lat/lon pairs. The result of this function
is the distance in kilometers.
Attributes
lon1 (float): longitude of first point
lat1 (float): latitude of first point
lon2 (float): longitude of second point. Can be an array
lat2 (float): latitude of second point. Can be an array
'''
dist = np.empty(lon2.shape)
lon1a = np.radians(lon1)
lat1a = np.radians(lat1)
lon2a = np.radians(lon2[:])
lat2a = np.radians(lat2[:])
dist[:] = np.sin(lat1a) * np.sin(lat2a[:]) + np.cos(lat1a) * np.cos(lat2a[:]) * np.cos(lon1a - lon2a[:])
return 6371. * np.arccos(np.minimum(dist,1.0))
class ComputeForecastMetrics:
'''
Function that computes ensemble-based estimates of TC forecast metrics based on the information
within the configuration file. Each of these metrics is stored in a seperate netCDF file that
is used to compute the sensitivity.
Attributes:
datea (string): initialization date of the forecast (yyyymmddhh format)
atcf (class): ATCF class object that includes ensemble information
config (dict.): dictionary that contains configuration options (read from file)
'''
def __init__(self, datea, storm, atcf, config):
# Define class-specific variables
self.fhr = None
self.deg2rad = 0.01745
self.earth_radius = 6378.388
self.missing = -9999.
self.deg2km = self.earth_radius * np.radians(1)
if 'metric_hours' in config['metric']:
fhr_list = json.loads(config['metric'].get('metric_hours'))
else:
fhr_list = []
self.nens = atcf.num_atcf_files
self.datea_str = datea
self.datea = dt.datetime.strptime(datea, '%Y%m%d%H')
self.datea_s = self.datea.strftime("%m%d%H%M")
self.outdir = config['locations']['work_dir']
self.storm = storm
self.metlist = []
self.dpp = importlib.import_module(config['model']['io_module'])
self.config = config
self.atcf = atcf
for self.fhr in fhr_list:
self.fff = str(self.fhr + 1000)[1:]
logging.warning(' Computing Forecast Metrics for F{0}'.format(self.fff))
# Obtain the TC latitude/longitude during, before and after time
self.ens_lat, self.ens_lon = self.atcf.ens_lat_lon_time(self.fhr)
self.ens_lat1, self.ens_lon1 = self.atcf.ens_lat_lon_time(self.fhr - 6)
self.ens_lat2, self.ens_lon2 = self.atcf.ens_lat_lon_time(self.fhr + 6)
e_cnt = 0
for n in range(self.nens):
if self.ens_lat[n] != self.atcf.missing and self.ens_lon[n] != self.atcf.missing:
e_cnt = e_cnt + 1
# Go to the next potential forecast hour if there are not enough members
if e_cnt <= 1:
logging.warning(' forecast hour does not have any members; moving on.')
continue
# Calculate the distance along major axis and along/across track distance
self.forecast_maj_track, self.forecast_min_track = self.__f_metric_tc_el_track()
if self.fhr == 0.0:
self.forecast_maj_track_0 = self.forecast_maj_track
self.forecast_al_track, self.forecast_ax_track = self.__f_metric_tc_ax_track()
# Determine the along/across track direction relative to major variability axis.
# Reorient, so that positive major axis is along and to right of track
alx = self.forecast_al_track['attrs']['X_DIRECTION_VECTOR']
aly = self.forecast_al_track['attrs']['Y_DIRECTION_VECTOR']
axx = self.forecast_ax_track['attrs']['X_DIRECTION_VECTOR']
axy = self.forecast_ax_track['attrs']['Y_DIRECTION_VECTOR']
elx = self.forecast_maj_track['attrs']['X_DIRECTION_VECTOR']
ely = self.forecast_maj_track['attrs']['Y_DIRECTION_VECTOR']
almag = alx * elx + aly * ely
axmag = alx * elx + aly * ely
if abs(almag) > abs(axmag):
if almag < 0:
fmet = self.forecast_maj_track['data_vars']["fore_met_init"]['data']
self.forecast_maj_track['data_vars']["fore_met_init"]['data'] = list(-1.0 * np.array(fmet))
self.forecast_maj_track['attrs']['X_DIRECTION_VECTOR'] = -elx
self.forecast_maj_track['attrs']['Y_DIRECTION_VECTOR'] = -ely
fmet = self.forecast_min_track['data_vars']["fore_met_init"]['data']
self.forecast_min_track['data_vars']["fore_met_init"]['data'] = list(-1.0 * np.array(fmet))
self.forecast_min_track['attrs']['X_DIRECTION_VECTOR'] = -elx
self.forecast_min_track['attrs']['Y_DIRECTION_VECTOR'] = -ely
else:
if axmag < 0:
fmet = self.forecast_maj_track['data_vars']["fore_met_init"]['data']
self.forecast_maj_track['data_vars']["fore_met_init"]['data'] = list(-1.0 * np.array(fmet))
self.forecast_maj_track['attrs']['X_DIRECTION_VECTOR'] = -elx
self.forecast_maj_track['attrs']['Y_DIRECTION_VECTOR'] = -ely
fmet = self.forecast_min_track['data_vars']["fore_met_init"]['data']
self.forecast_min_track['data_vars']["fore_met_init"]['data'] = list(-1.0 * np.array(fmet))
self.forecast_min_track['attrs']['X_DIRECTION_VECTOR'] = -elx
self.forecast_min_track['attrs']['Y_DIRECTION_VECTOR'] = -ely
# Compute metric that is distance from the ensemble-mean position
fore_met_min = self.forecast_min_track['data_vars']["fore_met_init"]['data']
vmin = np.var(fore_met_min)
fore_met_maj = self.forecast_maj_track['data_vars']["fore_met_init"]['data']
vmaj = np.var(fore_met_maj)
#out_stat = list(np.zeros(4))
#out_stat[0] = np.sqrt(vmaj) / (np.sqrt(vmin) + 0.0001)
# f_max_miss = 0.6667
# f_missing = len(np.where(fore_met_maj == 0.0)[0]) / len(fore_met_maj)
# if f_missing < f_max_miss or self.fhr <= 0.0:
# if self.fhr > 0.0:
# f_met0 = self.forecast_maj_track_0['data_vars']["fore_met_init"]['data']
# mdist = np.mean(f_met0)
# vf_met0 = np.var(f_met0)
# out_stat[1] = max(np.log(np.sqrt(vmaj) / (max(np.sqrt(vf_met0), 10.0))), 1.0)
f_met = list(np.zeros(len(fore_met_min)))
f_met[:] = [np.sqrt((i ** 2) + (j ** 2)) for i, j in zip(fore_met_maj, fore_met_min)]
self.forecast_m_dist = {'coords': {},
'attrs': {'FORECAST_METRIC_LEVEL': '',
'FORECAST_METRIC_NAME': 'ensemble distance',
'FORECAST_METRIC_SHORT_NAME': 'emdist',
'FORECAST_VALID_DATE': str(self.datea)},
'dims': {'num_ens': self.nens},
'data_vars': {'fore_met_init': {'dims': ('num_ens',),
'attrs': {'units': 'km',
'description': 'distance from ensemble-mean position'},
'data': f_met}}}
# Write track-related metrics to netcdf files for future use.
xr.Dataset.from_dict(self.forecast_maj_track).to_netcdf(
self.outdir + "/{1}_f{0}_majtrack.nc".format(self.fff, str(self.datea_str)), encoding={'fore_met_init': {'dtype': 'float32'}})
xr.Dataset.from_dict(self.forecast_min_track).to_netcdf(
self.outdir + "/{1}_f{0}_mintrack.nc".format(self.fff, str(self.datea_str)), encoding={'fore_met_init': {'dtype': 'float32'}})
xr.Dataset.from_dict(self.forecast_al_track).to_netcdf(
self.outdir + "/{1}_f{0}_altrack.nc".format(self.fff, str(self.datea_str)), encoding={'fore_met_init': {'dtype': 'float32'}})
xr.Dataset.from_dict(self.forecast_ax_track).to_netcdf(
self.outdir + "/{1}_f{0}_axtrack.nc".format(self.fff, str(self.datea_str)), encoding={'fore_met_init': {'dtype': 'float32'}})
xr.Dataset.from_dict(self.forecast_m_dist).to_netcdf(
self.outdir + "/{1}_f{0}_dist.nc".format(self.fff, str(self.datea_str)), encoding={'fore_met_init': {'dtype': 'float32'}})
# Calculate various intensity-related metrics
self.__intensity_metrics()
# Compute integrated position EOF metric
if eval(self.config['metric'].get('track_eof_metric', 'True')):
self.__position_eof()
# Compute integrated intensity EOF metric
if self.config['metric'].get('intensity_eof_metric', 'True') == 'True':
self.__intensity_eof()
# Compute combined track-intensity EOF metric
if self.config['metric'].get('track_inten_eof_metric', 'False') == 'True':
self.__track_inten_eof()
# Compute precipitation EOF metric
if self.config['metric'].get('wind_speed_eof_metric', 'False') == 'True':
self.__wind_speed_eof()
# Compute mean precipitation metric
if self.config['metric'].get('precipitation_metric', 'False') == 'True':
self.__precipitation_mean()
# Compute precipitation EOF metric
if self.config['metric'].get('precip_eof_metric', 'False') == 'True':
self.__precipitation_eof()
def get_metlist(self):
'''
Function that returns a list of metrics being considered
'''
return self.metlist
def __f_metric_tc_el_track(self):
'''
Function that computes the ensemble member's displacement from the ensemble-mean position in the direction
of the largest ensemble position variability and in the direction that is normal to it. The result of
this function is two xarray objects with the ensemble estimates of these two forecast metrics (these are
saved into netCDF files in the main routine).
'''
e_cnt = 0.0
x_mean = 0.0
y_mean = 0.0
m_lat = 0.0
m_lon = 0.0
x_var = 0.0
y_var = 0.0
xy_cov = 0.0
fx_dir = list(np.zeros(self.nens))
fy_dir = list(np.zeros(self.nens))
f_met_maj = list(np.zeros(self.nens))
f_met_min = list(np.zeros(self.nens))
# Compute the ensemble-mean if lat/lon pair is not missing
for n in range(self.nens):
if self.ens_lat[n] != self.atcf.missing and self.ens_lon[n] != self.atcf.missing:
e_cnt = e_cnt + 1
m_lat = m_lat + self.ens_lat[n]
m_lon = m_lon + self.ens_lon[n]
m_lon = m_lon / e_cnt
m_lat = m_lat / e_cnt
# Compute the distance in zonal and meridonal direction from mean
for n in range(self.nens):
if self.ens_lat[n] != self.atcf.missing and self.ens_lon[n] != self.atcf.missing:
fx_dir[n] = (self.ens_lon[n] - m_lon) * \
self.deg2km * np.cos(np.radians(0.5 * (self.ens_lat[n] + m_lat)))
fy_dir[n] = (self.ens_lat[n] - m_lat) * self.deg2km
x_mean = x_mean + fx_dir[n]
y_mean = y_mean + fy_dir[n]
else:
fx_dir[n] = 0.0
fy_dir[n] = 0.0
# Compute variance and covariance in zonal/meridional distance
x_mean = x_mean / e_cnt
y_mean = y_mean / e_cnt
for n in range(self.nens):
if self.ens_lat[n] != self.atcf.missing and self.ens_lon[n] != self.atcf.missing:
x_var = x_var + (fx_dir[n] - x_mean) ** 2
y_var = y_var + (fy_dir[n] - y_mean) ** 2
xy_cov = xy_cov + (fx_dir[n] - x_mean) * (fy_dir[n] - y_mean)
x_var = x_var / (e_cnt - 1.0)
y_var = y_var / (e_cnt - 1.0)
xy_cov = xy_cov / (e_cnt - 1.0)
# Compute major and minor axis based on variance/covariance
m_trace = x_var + y_var
m_det = (x_var * y_var) - (xy_cov * xy_cov)
eval1 = max(0.5 * m_trace + np.sqrt(m_trace * m_trace / 4.0 - m_det),
0.5 * m_trace - np.sqrt(m_trace * m_trace / 4.0 - m_det))
maj_ax = [0.0, 0.0]
min_ax = [0.0, 0.0]
if abs(xy_cov) > 0:
maj_ax[0] = eval1 - y_var
maj_ax[1] = xy_cov
else:
maj_ax[0] = 1.0
maj_ax[1] = 0.0
vec_len = np.sqrt((maj_ax[0] * maj_ax[0] + maj_ax[1] * maj_ax[1]))
maj_ax[0] = maj_ax[0] / vec_len
maj_ax[1] = maj_ax[1] / vec_len
min_ax[0] = maj_ax[1]
min_ax[1] = -maj_ax[0]
rand1 = np.random.normal(0.0, 0.1, len(fx_dir))
# Compute distance between major/minor axis direction for each member
for n in range(self.nens):
f_met_maj[n] = maj_ax[0] * (fx_dir[n] - x_mean) + maj_ax[1] * (fy_dir[n] - y_mean) + rand1[n]
f_met_min[n] = min_ax[0] * (fx_dir[n] - x_mean) + min_ax[1] * (fy_dir[n] - y_mean) + rand1[n]
forecast_maj_track = {'coords': {},
'attrs': {'FORECAST_METRIC_SHORT_NAME': 'majpos',
'FORECAST_METRIC_NAME': 'major track error',
'FORECAST_METRIC_LEVEL': '',
'VERIFICATION': 0.0,
'X_DIRECTION_VECTOR': maj_ax[0],
'Y_DIRECTION_VECTOR': maj_ax[1]},
'dims': {'num_ens': self.nens},
'data_vars': {'fore_met_init': {'dims': ('num_ens',),
'attrs': {'description': 'TC major axis track error',
'units': 'km', '_FillValue': self.missing},
'data': f_met_maj}}}
forecast_min_track = {'coords': {},
'attrs': {'FORECAST_METRIC_SHORT_NAME': 'minpos',
'FORECAST_METRIC_NAME': 'minor track error',
'FORECAST_METRIC_LEVEL': '',
'VERIFICATION': 0.0,
'X_DIRECTION_VECTOR': min_ax[0],
'Y_DIRECTION_VECTOR': min_ax[1]},
'dims': {'num_ens': self.nens},
'data_vars': {'fore_met_init': {'dims': ('num_ens',),
'attrs': {'description': 'TC minor axis track error',
'units': 'km', '_FillValue': self.missing},
'data': f_met_min}}}
self.metlist.append('f{0}_majtrack'.format(self.fff))
return forecast_maj_track, forecast_min_track
def __f_metric_tc_ax_track(self):
'''
Function that computes the ensemble member's displacement from the ensemble-mean position in the along
and across direction. The result of this function is two xarray objects with the ensemble estimates of
these two forecast metrics (these are saved into netCDF files in the main routine).
'''
m_lat = 0.0
m_lon = 0.0
e_cnt = 0.0
f_met_ax = list(np.zeros(self.nens))
f_met_al = list(np.zeros(self.nens))
# Compute the ensemble-mean position at center time
for n in range(self.nens):
if self.ens_lat[n] != self.atcf.missing and self.ens_lon[n] != self.atcf.missing:
e_cnt = e_cnt + 1
m_lat = m_lat + self.ens_lat[n]
m_lon = m_lon + self.ens_lon[n]
m_lon = m_lon / e_cnt
m_lat = m_lat / e_cnt
m_lat1 = 0.0
m_lon1 = 0.0
e_cnt = 0.0
# Compute mean lat/lon at time before
for n in range(self.nens):
if self.ens_lat1[n] != self.atcf.missing and self.ens_lon1[n] != self.atcf.missing:
e_cnt = + 1
m_lat1 = + self.ens_lat1[n]
m_lon1 = + self.ens_lon1[n]
if e_cnt > 0:
m_lat1 = m_lat1 / e_cnt
m_lon1 = m_lon1 / e_cnt
else:
m_lat1 = m_lat
m_lon1 = m_lon
m_lat2 = 0.0
m_lon2 = 0.0
e_cnt = 0.0
# Compute mean lat/lon at time after
for n in range(self.nens):
if self.ens_lat2[n] != self.atcf.missing and self.ens_lon2[n] != self.atcf.missing:
e_cnt = e_cnt + 1
m_lat2 = m_lat2 + self.ens_lat2[n]
m_lon2 = m_lon2 + self.ens_lon2[n]
if e_cnt > 0:
m_lat2 = m_lat2 / e_cnt
m_lon2 = m_lon2 / e_cnt
else:
m_lat2 = m_lat
m_lon2 = m_lon
# Compute the along - track direction
x_dir = (m_lon2 - m_lon1) * self.deg2km * np.cos(0.5 * np.radians(m_lat1 + m_lat2))
y_dir = (m_lat2 - m_lat1) * self.deg2km
v_len = max(np.sqrt(x_dir * x_dir + y_dir * y_dir), 0.00001)
# Compute unit vectors in along/across directions
alx_dir = x_dir / v_len
aly_dir = y_dir / v_len
axx_dir = aly_dir
axy_dir = -alx_dir
rand1 = np.random.normal(0.0, 0.1, len(self.ens_lat2))
# Compute the distance in the along/across directions
for n in range(self.nens):
if self.ens_lat[n] != self.atcf.missing and self.ens_lon[n] != self.atcf.missing:
x_dir = (self.ens_lon[n] - m_lon) \
* self.deg2km * np.cos(0.5 * np.radians(self.ens_lat[n] + m_lat))
y_dir = (self.ens_lat[n] - m_lat) * self.deg2km
f_met_al[n] = x_dir * alx_dir + y_dir * aly_dir + rand1[n]
f_met_ax[n] = x_dir * axx_dir + y_dir * axy_dir + rand1[n]
else:
f_met_al[n] = 0.0
f_met_ax[n] = 0.0
forecast_al_track = {'coords': {},
'attrs': {'FORECAST_METRIC_SHORT_NAME': 'alposk',
'FORECAST_METRIC_NAME': 'TC along track error',
'FORECAST_METRIC_LEVEL': '',
'VERIFICATION': 0.0,
'X_DIRECTION_VECTOR': alx_dir,
'Y_DIRECTION_VECTOR': aly_dir,
'TC_LATITUDE': 0.0,
'TC_LONGITUDE': 0.0},
'dims': {'num_ens': self.nens},
'data_vars': {'fore_met_init': {'dims': ('num_ens',),
'attrs': {'description': 'TC along track error',
'units': 'km', '_FillValue': self.missing},
'data': f_met_al}}}
forecast_ax_track = {'coords': {},
'attrs': {'FORECAST_METRIC_SHORT_NAME': 'axpos',
'FORECAST_METRIC_NAME': 'TC across track error',
'FORECAST_METRIC_LEVEL': '',
'VERIFICATION': 0.0,
'X_DIRECTION_VECTOR': axx_dir,
'Y_DIRECTION_VECTOR': axy_dir,
'TC_LATITUDE': 0.0,
'TC_LONGITUDE': 0.0},
'dims': {'num_ens': self.nens},
'data_vars': {'fore_met_init': {'dims': ('num_ens',),
'attrs': {'description': 'TC across track error',
'units': 'km', '_FillValue': self.missing},
'data': f_met_ax}}}
return forecast_al_track, forecast_ax_track
def __intensity_metrics(self):
"""
Routine that computes TC intensity-based forecast metrics from each ensemble member. Currently, the
code computes the minimum SLP (always) and kinetic energy within a certain distance of the TC center
on a certain pressure level (optional). The result of this function is the ensemble forecast metrics,
which are saved to netCDF files.
"""
# Read the ATCF information for this lead time
g1 = self.dpp.ReadGribFiles(self.datea_str, self.fhr, self.config)
lat_vec, lon_vec = self.atcf.ens_lat_lon_time(self.fhr)
# Compute the mean latitude and longitude, if missing, replace with ensemble mean
e_cnt = 0
m_lat = 0.0
m_lon = 0.0
for n in range(self.nens):
if lat_vec[n] != self.atcf.missing and lon_vec[n] != self.atcf.missing:
e_cnt = e_cnt + 1
m_lat = m_lat + lat_vec[n]
m_lon = m_lon + lon_vec[n]
m_lon = m_lon / e_cnt
m_lat = m_lat / e_cnt
# Replace missing lat/lon with the ensemble mean.
for n in range(self.nens):
if lat_vec[n] == self.atcf.missing or lon_vec[n] == self.atcf.missing:
lat_vec[n] = m_lat
lon_vec[n] = m_lon
mslp_dll = 2.0
f_met_slp = list(np.zeros(self.nens))
for n in range(self.nens):
# Read SLP field, compute the minimum SLP within a specified distance of the center
vDict = {'latitude': (lat_vec[n]-mslp_dll, lat_vec[n]+mslp_dll), 'longitude': (lon_vec[n]-mslp_dll, lon_vec[n]+mslp_dll)}
vDict = g1.set_var_bounds('sea_level_pressure', vDict)
f_met_slp[n] = np.min(g1.read_grib_field('sea_level_pressure', n, vDict))*0.01
# if self.fhr > 0.0:
# f_met0_slp = xr.open_dataset(self.outdir + '/' + str(self.datea_str) + '_f000_minslp.nc').to_dict()['data_vars']["fore_met_init"]['data']
# mdist_slp = np.mean(f_met0_slp)
# vf_met0_slp = np.var(f_met0_slp)
# v_fmet_slp = np.var(f_met_slp)
# out_stat[2] = max((np.sqrt(v_fmet_slp) /
# (max(np.sqrt(vf_met0_slp), 2.0))
# ), 1.0)
f_met_slp_nc = {'coords': {},
'attrs': {'FORECAST_METRIC_LEVEL': '',
'FORECAST_METRIC_NAME': 'minimum SLP',
'FORECAST_METRIC_SHORT_NAME': 'minslp',
'FORECAST_VALID_DATE': str(self.datea)},
'dims': {'num_ens': self.nens},
'data_vars': {'fore_met_init': {'dims': ('num_ens',),
'attrs': {'units': 'hPa',
'description': 'minimum sea-level pressure'},
'data': f_met_slp}}}
xr.Dataset.from_dict(f_met_slp_nc).to_netcdf(
self.outdir + "/{1}_f{0}_minslp.nc".format(self.fff, str(self.datea_str)), encoding={'fore_met_init': {'dtype': 'float32'}})
self.metlist.append('f{0}_minslp'.format(self.fff))
if self.config['metric'].get('kinetic_energy_metric', 'True') == 'True':
ke_dll = 4.0
ke_radius = self.config['metric'].get('kinetic_energy_radius',200.)
ke_level = self.config['metric'].get('kinetic_energy_level',1000.)
logging.warning(' Computing {0} hPa Kinetic Energy'.format(str(ke_level)))
fmet_kmetric = np.zeros(self.nens)
for n in range(self.nens):
vDict = {'latitude': (lat_vec[n]-ke_dll, lat_vec[n]+ke_dll),
'longitude': (lon_vec[n]-ke_dll, lon_vec[n]+ke_dll), 'isobaricInhPa': (ke_level, ke_level)}
vDict = g1.set_var_bounds('zonal_wind', vDict)
# Read zonal and meridonal wind within certain distance of TC center
ul = g1.read_grib_field('zonal_wind', n, vDict).squeeze()
vl = g1.read_grib_field('meridional_wind', n, vDict).squeeze()
nlat = len(ul.latitude.values)
nlon = len(ul.longitude.values)
lonarr, latarr = np.meshgrid(ul.longitude.values, ul.latitude.values)
dist = great_circle(lon_vec[n], lat_vec[n], lonarr, latarr)
# Compute lat/lon weights, replace with zeros where greater than radius
awght = np.zeros(dist.shape)
for j in range(nlat):
awght[j,:] = np.cos(np.radians(ul.latitude.values[j]))
awght = np.where(dist <= ke_radius, awght, 0.)
# Compute the kinetic energy
fmet_kmetric[n] = 0.5 * np.sum(awght[:,:] * (ul[:,:]**2 + vl[:,:]**2)) / np.sum(awght)
# if self.fhr > 0.0:
#
# f_met0_kmetric = xr.open_dataset(self.outdir + '/' + str(self.datea_str) + '_f000' +
# '_ke_10m.nc').to_dict()['data_vars']["fore_met_init"]['data']
# vf_met0_kmetric = np.var(f_met0_kmetric)
#
# v_fmet_kmetric = np.var(fmet_kmetric)
# out_stat[3] = max((np.sqrt(v_fmet_kmetric) /
# (max(np.sqrt(vf_met0_kmetric), 2.0))), 1.0)
f_met_kmetric_nc = {'coords': {},
'attrs': {'FORECAST_METRIC_LEVEL': '',
'FORECAST_METRIC_NAME': 'Kinetic Energy',
'FORECAST_METRIC_SHORT_NAME': 'ke',
'FORECAST_VALID_DATE': str(self.datea)},
'dims': {'num_ens': self.nens},
'data_vars': {'fore_met_init': {'dims': ('num_ens',),
'attrs': {'units': 'm2/s2',
'description': '10 m Kinetic Energy averaged '
'within 200 km of TC center'},
'data': fmet_kmetric}}}
xr.Dataset.from_dict(f_met_kmetric_nc).to_netcdf(
self.outdir + "/{1}_f{0}_ke_10m.nc".format(self.fff, str(self.datea_str)), encoding={'fore_met_init': {'dtype': 'float32'}})
def __position_eof(self):
'''
Function that computes time-integrated track metric, which is calculated by taking the EOF of
the ensemble latitude and longitude for the lead times specified. The resulting forecast metric is the
principal component of the EOF. The function also plots a figure showing the TC tracks and the
track perturbation that is consistent with the first EOF.
'''
logging.warning(' Computing time-integrated track metric')
ens_min = int(float(self.config['metric'].get('track_eof_member_frac', 0.5))*float(self.nens))
ellfreq = 24.0
esign = self.config['metric'].get('track_eof_esign', 1.0)
fhr1 = int(self.config['metric'].get('track_eof_hour_init', 24))
fint = int(self.config['metric'].get('track_eof_hour_int', 6))
fhr2 = int(self.config['metric'].get('track_eof_hour_final', 120))
ntimes = int((fhr2-fhr1) / fint) + 1
p1 = -2
ensvec = np.zeros((self.nens, 2*ntimes))
for t in range(ntimes):
fhr=fhr1+t*fint
lat, lon=self.atcf.ens_lat_lon_time(fhr)
# Compute the ensemble mean for members that have lat/lon values at this time
e_cnt = 0
m_lat_t = 0.0
m_lon_t = 0.0
for n in range(self.nens):
if lat[n] != self.atcf.missing and lon[n] != self.atcf.missing:
e_cnt = e_cnt + 1
if self.storm[-1] == "e" or self.storm[-1] == "c":
lon[n] = (lon[n] + 360.) % 360.
m_lon_t = m_lon_t + lon[n]
m_lat_t = m_lat_t + lat[n]
# Only consider this time if a critical number of members are present
if e_cnt >= ens_min:
m_lon_t = m_lon_t / e_cnt
m_lat_t = m_lat_t / e_cnt
# Compute distance in x/y directions if member is not missing
p1 = p1 + 2
p2 = p1 + 1
for n in range(self.nens):
if lat[n] != self.atcf.missing and lon[n] != self.atcf.missing:
ensvec[n,p1] = np.radians(lat[n]-m_lat_t)*self.earth_radius
ensvec[n,p2] = np.radians(lon[n]-m_lon_t)*self.earth_radius*np.cos(np.radians(m_lat_t))
else:
ensvec[n,p1] = 0.0
ensvec[n,p2] = 0.0
if p1 < 0:
logging.error(' No TC positions in the time window. Skipping metric.')
return None
# Compute EOF/PCs of the track perturbations
solver = Eof(ensvec[:,0:(p2+1)])
pc1 = np.squeeze(solver.pcs(npcs=1, pcscaling=1))
pc1[:] = pc1[:] / np.std(pc1)
f1 = 0
f2 = np.max([120, fhr2])
ntimes = int((f2-f1) / 6.) + 1
m_lat = np.zeros(ntimes)
m_lon = np.zeros(ntimes)
dx = np.zeros(ntimes)
dy = np.zeros(ntimes)
ens_lat = np.zeros((self.nens, ntimes))
ens_lon = np.zeros((self.nens, ntimes))
# Loop over all times, determine the perturbation distance in x/y for a 1.0 unit PC
for t in range(ntimes):
fhr=f1+t*6
ens_lat[:,t], ens_lon[:,t]=self.atcf.ens_lat_lon_time(fhr)
e_cnt = 0
for n in range(self.nens):
if ens_lat[n,t] != self.atcf.missing and ens_lon[n,t] != self.atcf.missing:
e_cnt = e_cnt + 1
if self.storm[-1] == "e" or self.storm[-1] == "c":
ens_lon[n,t] = (ens_lon[n,t] + 360.) % 360.
m_lon[t] = m_lon[t] + ens_lon[n,t]
m_lat[t] = m_lat[t] + ens_lat[n,t]
if e_cnt > 2:
m_lon[t] = m_lon[t] / e_cnt
m_lat[t] = m_lat[t] / e_cnt
for n in range(self.nens):
if ens_lat[n,t] != self.atcf.missing and ens_lon[n,t] != self.atcf.missing:
dy[t] = dy[t] + np.radians(ens_lat[n,t]-m_lat[t])*self.earth_radius * pc1[n]
dx[t] = dx[t] + np.radians(ens_lon[n,t]-m_lon[t])*self.earth_radius*np.cos(np.radians(m_lat[t])) * pc1[n]
dy[t] = dy[t] / e_cnt
dx[t] = dx[t] / e_cnt
else:
m_lat[t] = np.nan
m_lon[t] = np.nan
imsum = 0.
jmsum = 0.
alsum = 0.
axsum = 0.
# Determine the extent to which the PC is aligned with the along/right of track direction
for t in range(ntimes):
fhr = f1+t*6
if fhr >= fhr1 and fhr <= fhr2:
t1 = max((t-1,0))
t2 = min((t+1,ntimes-1))
aloi = np.radians(m_lon[t2]-m_lon[t1])*self.earth_radius*np.cos(np.radians(0.5*(m_lat[t1]+m_lat[t2])))
aloj = np.radians(m_lat[t2]-m_lat[t1])*self.earth_radius
veclen = np.sqrt(aloi*aloi + aloj*aloj)
aloi = aloi / veclen
aloj = aloj / veclen
acri = aloj
acrj = -aloi
veclen = np.sqrt(dx[t]**2 + dy[t]**2)
peri = dx[t] / np.max([veclen,0.000001])
perj = dy[t] / np.max([veclen,0.000001])
adist = aloi*peri + aloj*perj
xdist = acri*peri + acrj*perj
alsum = alsum + adist
axsum = axsum + xdist
if abs(adist) > abs(xdist):
if adist < 0:
imsum = imsum - peri
jmsum = jmsum - perj
else:
imsum = imsum + peri
jmsum = jmsum + perj
else:
if xdist < 0:
imsum = imsum - peri
jmsum = jmsum - perj
else:
imsum = imsum + peri
jmsum = jmsum + perj
# Flip the sign of the EOF, so positive values are along and to right of track
veclen = np.sqrt(imsum*imsum + jmsum*jmsum)
imsum = imsum / veclen
jmsum = jmsum / veclen
if abs(alsum) >= abs(axsum):
if alsum < 0.0:
esign = -esign
else:
if axsum < 0.0:
esign = -esign
pc1[:] = esign * pc1[:]
dx[:] = esign * dx[:]
dy[:] = esign * dy[:]
# Compute perturbed lat/lon for plotting track EOF
p_lat = np.zeros(ntimes)
p_lon = np.zeros(ntimes)
for t in range(ntimes):
p_lat[t] = m_lat[t] + dy[t] / (self.deg2rad*self.earth_radius)
p_lon[t] = m_lon[t] + dx[t] / (self.deg2rad*self.earth_radius*np.cos(np.radians(m_lat[t])))
plot_ellipse = self.config['vitals_plot'].get('plot_ellipse',True)
ell_freq = float(self.config['vitals_plot'].get('ellipse_frequency', 24))
ellcol = ["#551A8B", "#00FFFF", "#00EE00", "#FF0000", "#FF00FF", "#551A8B", "#00FFFF", "#00EE00", "#FF0000"]
minLat = 90.
maxLat = -90.
minLon = 360.
maxLon = -180.
# Determine range of figure
for n in range(self.nens):
for t in range(ntimes):
if ens_lat[n,t] != self.atcf.missing and ens_lon[n,t] != self.atcf.missing:
minLat = min([minLat, ens_lat[n,t]])
maxLat = max([maxLat, ens_lat[n,t]])
minLon = min([minLon, ens_lon[n,t]])
maxLon = max([maxLon, ens_lon[n,t]])
minLat = minLat - 2.5
maxLat = maxLat + 2.5
minLon = minLon - 2.5
maxLon = maxLon + 2.5
trackDict = {}
trackDict['grid_interval'] = self.config['vitals_plot'].get('grid_interval', 5)
trackDict['left_labels'] = 'True'
trackDict['right_labels'] = 'None'
# Create basic figure plotting options
fig = plt.figure(figsize=(11,8.5))
ax = background_map(self.config['vitals_plot'].get('projection', 'PlateCarree'), minLon, maxLon, minLat, maxLat, trackDict)
x_ell = np.zeros(361)
y_ell = np.zeros(361)
pb = np.zeros((2, 2))
# Plot the individual ensemble members
for n in range(self.nens):
x = []
y = []
for t in range(ntimes):
if ens_lat[n,t] != self.atcf.missing and ens_lon[n,t] != self.atcf.missing:
y.append(ens_lat[n,t])
x.append(ens_lon[n,t])
if len(x) > 0:
ax.plot(x, y, color='lightgray', zorder=1, transform=ccrs.PlateCarree())
# Plot the ensemble mean and track perturbation
ax.plot(m_lon, m_lat, color='black', linewidth=3, zorder=15, transform=ccrs.PlateCarree())
ax.plot(p_lon, p_lat, '--', color='black', linewidth=3, zorder=15, transform=ccrs.PlateCarree())
# Plot the ellipses and points
color_index = 0
for t in range(ntimes):
fhr = f1+t*6
if (fhr % ell_freq) == 0 and fhr > 0:
x_ens = []
y_ens = []
e_cnt = 0
for n in range(self.nens):
if ens_lat[n,t] != self.atcf.missing and ens_lon[n,t] != self.atcf.missing:
e_cnt = e_cnt + 1
y_ens.append(ens_lat[n,t])
x_ens.append(ens_lon[n,t])
if e_cnt > 2:
ax.scatter(x_ens, y_ens, s=2, color=ellcol[color_index], zorder=20, transform=ccrs.PlateCarree())
ax.scatter(m_lon[t], m_lat[t], s=14, color=ellcol[color_index], zorder=20, transform=ccrs.PlateCarree())
ax.scatter(p_lon[t], p_lat[t], s=14, color=ellcol[color_index], zorder=20, transform=ccrs.PlateCarree())
else:
break
pb[:,:] = 0.0
for n in range(len(x_ens)):
fx = np.radians(x_ens[n]-m_lon[t]) * self.earth_radius * np.cos(np.radians(0.5*(y_ens[n] + m_lat[t])))
fy = np.radians(y_ens[n]-m_lat[t]) * self.earth_radius
pb[0,0] = pb[0,0] + fx**2
pb[1,1] = pb[1,1] + fy**2
pb[1,0] = pb[1,0] + fx*fy
pb[0,1] = pb[1,0]
pb[:,:] = pb[:,:] / float(e_cnt-1)
rho = pb[1,0] / (np.sqrt(pb[0,0]) * np.sqrt(pb[1,1]))
sigma_x = np.sqrt(pb[0,0])
sigma_y = np.sqrt(pb[1,1])
fac = 1. / (2. * (1. - rho * rho))
rdex = 0
for rad in range(int(np.degrees(2*np.pi))+1):
x_start = np.cos(np.radians(rad))
y_start = np.sin(np.radians(rad))
for r_distance in range(4000):
x_loc = x_start * r_distance
y_loc = y_start * r_distance
prob = np.exp(-1.0 * fac * ((x_loc / sigma_x) ** 2 + (y_loc / sigma_y) ** 2 -
2.0 * rho * (x_loc / sigma_x) * (y_loc / sigma_y)))
if prob < 0.256:
x_ell[rdex] = m_lon[t] + x_loc / (self.deg2rad*self.earth_radius*np.cos(np.radians(m_lat[t])))
y_ell[rdex] = m_lat[t] + y_loc / (self.deg2rad*self.earth_radius)
rdex = rdex + 1
break
ax.plot(x_ell, y_ell, color=ellcol[color_index], zorder=20, transform=ccrs.PlateCarree())
color_index += 1
fracvar = '%4.3f' % solver.varianceFraction(neigs=1)
plt.title(self.config['metric'].get('title_string','{0} {1} forecast of {2}, {3} of variance'.format(self.datea_str, \
self.config['model'].get('model_src',''), self.storm, fracvar)))
if eval(self.config['metric'].get('legend','False')):
plt.text(minLon+(maxLon-minLon)*0.90, minLat+(maxLat-minLat)*0.58, '24 h', fontsize=15, color=ellcol[0], backgroundcolor='#FFFFFF')
plt.text(minLon+(maxLon-minLon)*0.90, minLat+(maxLat-minLat)*0.54, '48 h', fontsize=15, color=ellcol[1], backgroundcolor='#FFFFFF')
plt.text(minLon+(maxLon-minLon)*0.90, minLat+(maxLat-minLat)*0.50, '72 h', fontsize=15, color=ellcol[2], backgroundcolor='#FFFFFF')
plt.text(minLon+(maxLon-minLon)*0.90, minLat+(maxLat-minLat)*0.46, '96 h', fontsize=15, color=ellcol[3], backgroundcolor='#FFFFFF')
plt.text(minLon+(maxLon-minLon)*0.90, minLat+(maxLat-minLat)*0.42, '120 h', fontsize=15, color=ellcol[4], backgroundcolor='#FFFFFF')
outdir = '{0}/f{1}_intmajtrack'.format(self.config['locations']['figure_dir'],'%0.3i' % fhr2)
if not os.path.isdir(outdir):
try:
os.makedirs(outdir)
except OSError as e:
raise e
plt.savefig('{0}/metric.png'.format(outdir), format='png', dpi=150, bbox_inches='tight')
plt.close(fig)
# Create xarray object of forecast metric, write to file.
fmetatt = {'FORECAST_METRIC_LEVEL': '', 'FORECAST_METRIC_NAME': 'integrated track PC', 'FORECAST_METRIC_SHORT_NAME': 'trackeof', \
'FORECAST_HOUR1': int(fhr1), 'FORECAST_HOUR2': int(fhr2), 'X_DIRECTION_VECTOR': imsum, 'Y_DIRECTION_VECTOR': jmsum, \
'EOF_NUMBER': int(1), 'FRACTION_VARIANCE': solver.varianceFraction(neigs=1), 'MIN_ENSEMBLE': int(ens_min)}
f_met = {'coords': {}, 'attrs': fmetatt, 'dims': {'num_ens': self.nens}, \
'data_vars': {'fore_met_init': {'dims': ('num_ens',), 'attrs': {'units': '', 'description': 'integrated track PC'}, 'data': pc1.data}}}
xr.Dataset.from_dict(f_met).to_netcdf(
"{0}/{1}_f{2}_intmajtrack.nc".format(self.outdir,str(self.datea_str),'%0.3i' % fhr2), encoding={'fore_met_init': {'dtype': 'float32'}})
self.metlist.append('f{0}_intmajtrack'.format('%0.3i' % fhr2))
del f_met
def __intensity_eof(self):
'''
Function that computes time-integrated minimum SLP metric, which is calculated by taking the EOF of
the ensemble minimum SLP forecast. The resulting forecast metric is the principal component of the
EOF. The function also plots a figure showing the TC minimum SLP and maximum wind, along with the
min. SLP and max. wind perturbation that is consistent with the first EOF.
'''
logging.warning(' Computing time-integrated intensity metric')
ens_min = int(float(self.config['metric'].get('intensity_eof_member_frac', 0.5))*float(self.nens))
esign=1.0
fhr1 = int(self.config['metric'].get('intensity_eof_hour_init', 24))
fint = int(self.config['metric'].get('intensity_eof_hour_int', 6))
fhr2 = int(self.config['metric'].get('intensity_eof_hour_final', 96))
ntimes = int((fhr2-fhr1) / fint) + 1
ensvec = np.zeros((self.nens, ntimes))
tt = -1
# Loop over all times, calculate ensemble-mean SLP
for t in range(ntimes):
fhr=fhr1+t*fint
slp, wnd=self.atcf.ens_intensity_time(fhr)
e_cnt = 0
m_slp_t = 0.0
for n in range(self.nens):
if slp[n] != self.atcf.missing:
e_cnt = e_cnt + 1
m_slp_t = m_slp_t + slp[n]
# Only consider times where at least half of members have storm for EOF
if e_cnt >= ens_min:
m_slp_t = m_slp_t / e_cnt
tt = tt + 1
for n in range(self.nens):
if slp[n] != self.atcf.missing:
ensvec[n,tt] = slp[n]-m_slp_t
else:
ensvec[n,tt] = 0.0
if tt < 0:
logging.error(' No TC intensity data in the time window. Skipping metric.')
return None
# Compute the EOF of the MSLP time series
solver = Eof(ensvec)
pc1 = np.squeeze(solver.pcs(npcs=1, pcscaling=1))
pc1[:] = pc1[:] / np.std(pc1)
f1 = 0
f2 = np.max([120, fhr2])
ntimes = int((f2-f1) / 6.) + 1
m_fhr = np.zeros(ntimes)
m_slp = np.zeros(ntimes)
m_wnd = np.zeros(ntimes)
dslp = np.zeros(ntimes)
dwnd = np.zeros(ntimes)
ens_slp = np.zeros((self.nens, ntimes))
ens_wnd = np.zeros((self.nens, ntimes))
sumslp = 0.
# Loop over all times, get MSLP, compute mean and EOF perturbation
for t in range(ntimes):
fhr=f1+t*6
ens_slp[:,t], ens_wnd[:,t]=self.atcf.ens_intensity_time(fhr)
e_cnt = 0
for n in range(self.nens):
if ens_slp[n,t] != self.atcf.missing:
e_cnt = e_cnt + 1
m_slp[t] = m_slp[t] + ens_slp[n,t]
m_wnd[t] = m_wnd[t] + ens_wnd[n,t]
m_fhr[t] = fhr
if e_cnt > 1:
m_slp[t] = m_slp[t] / e_cnt
m_wnd[t] = m_wnd[t] / e_cnt
else:
m_slp[t] = None
m_wnd[t] = None