-
Notifications
You must be signed in to change notification settings - Fork 2
/
03_hindcast_dyn_map.py
1723 lines (1406 loc) · 60.3 KB
/
03_hindcast_dyn_map.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
# coding: utf-8
"""
Dynamic map hindcast implementation
"""
__author__ = "Saeed Moghimi"
__copyright__ = "Copyright 2018, UCAR/NOAA"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "[email protected]"
#Thu 19 Apr 2018 03:08:06 PM EDT
###############################################################
# Original development from https://github.com/ocefpaf/python_hurricane_gis_map
# # Exploring the NHC GIS Data
#
# This notebook aims to demonstrate how to create a simple interactive GIS map with the National Hurricane Center predictions [1] and CO-OPS [2] observations along the Hurricane's path.
#
#
# 1. http://www.nhc.noaa.gov/gis/
# 2. https://opendap.co-ops.nos.noaa.gov/ioos-dif-sos/
#
#
# NHC codes storms are coded with 8 letter names:
# - 2 char for region `al` → Atlantic
# - 2 char for number `11` is Irma
# - and 4 char for year, `2017`
#
# Browse http://www.nhc.noaa.gov/gis/archive_wsurge.php?year=2017 to find other hurricanes code.
###############################################################
import pandas as pd
import numpy as np
import string
#
import os
import sys
from glob import glob
#
import arrow
#
from shapely.geometry import LineString
import netCDF4
#
import folium
from folium.plugins import Fullscreen, MarkerCluster,MousePosition,FloatImage
from ioos_tools.ioos import get_coordinates
from branca.element import *
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.tri as Tri
import matplotlib.pyplot as plt
from shapely.geometry import mapping, Polygon
import fiona
from bokeh.resources import CDN
from bokeh.plotting import figure
from bokeh.models import Title
from bokeh.embed import file_html
from bokeh.models import Range1d, LinearAxis, HoverTool
from bokeh.layouts import gridplot
from bokeh.models import ColumnDataSource
from folium import IFrame
from geopandas import GeoDataFrame
import pickle
try:
os.system('rm __pycache__/hurricane_funcs*.pyc' )
os.system('rm hurricane_funcs*.pyc' )
except:
pass
if 'hurricane_funcs' in sys.modules:
del(sys.modules["hurricane_funcs"])
from hurricane_funcs import *
try:
os.system('rm __pycache__/base_info_folium*.pyc' )
os.system('rm base_info_folium*.pyc' )
except:
pass
if 'base_info_folium' in sys.modules:
del(sys.modules["base_info_folium"])
from base_info_folium import *
############################
from matplotlib.colors import LinearSegmentedColormap
cdict = {'red': ((0. , 1 , 1),
(0.05, 1 , 1),
(0.11, 0 , 0),
(0.66, 1, 1),
(0.89, 1, 1),
(1 , 0.5, 0.5)),
'green': ((0., 1, 1),
(0.05, 1, 1),
(0.11, 0, 0),
(0.375, 1, 1),
(0.64, 1, 1),
(0.91, 0, 0),
(1, 0, 0)),
'blue': ((0., 1, 1),
(0.05, 1, 1),
(0.11, 1, 1),
(0.34, 1, 1),
(0.65, 0, 0),
(1, 0, 0))}
jetMinWi = LinearSegmentedColormap('my_colormap',cdict,256)
my_cmap = plt.cm.jet
###############################################################
#Functions
######################################
# Let's create a color code for the point track.
colors_hurricane_condition = {
'subtropical depression': '#ffff99',
'tropical depression': '#ffff66',
'tropical storm': '#ffcc99',
'subtropical storm': '#ffcc66',
'hurricane': 'red',
'major hurricane': 'crimson',
}
#######################################
############################################################
# plot ssh to pop up when click on obs locations
##
tools = "pan,box_zoom,reset"
width, height = 750, 250
def make_plot_2axes(ssh, wind):
p = figure(toolbar_location='above',
x_axis_type='datetime',
width=width,
height=height,
tools=tools,
title=ssh.name)
p.yaxis.axis_label = 'wind speed (m/s)'
l0 = p.line(
x=wind.index,
y=wind.values,
line_width=5,
line_cap='round',
line_join='round',
legend='wind speed (m/s)',
color='#9900cc',
alpha=0.5,
)
p.extra_y_ranges = {}
p.extra_y_ranges['y2'] = Range1d(
start=-1,
end=3.5
)
p.add_layout(
LinearAxis(
y_range_name='y2',
axis_label='ssh (m)'),
'right'
)
l1 = p.line(
x=ssh.index,
y=ssh.values,
line_width=5,
line_cap='round',
line_join='round',
legend='ssh (m)',
color='#0000ff',
alpha=0.5,
y_range_name='y2',
)
p.legend.location = 'top_left'
p.add_tools(
HoverTool(
tooltips=[
('wind speed (m/s)', '@y'),
],
renderers=[l0],
),
HoverTool(
tooltips=[
('ssh (m)', '@y'),
],
renderers=[l1],
),
)
return p
def make_plot_obs(obs,label=None):
#TOOLS="hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select,"
TOOLS="crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,reset,save,"
p = figure(toolbar_location='above',
x_axis_type='datetime',
width=width,
height=height,
tools=TOOLS)
p.add_layout(Title(text='Station: '+obs._metadata['station_code'], text_font_style="italic"), 'above')
p.add_layout(Title(text=obs._metadata['station_name'], text_font_size="10pt"), 'above')
p.yaxis.axis_label = label
obs_val = obs.values.squeeze()
l1 = p.line(
x=obs.index,
y=obs_val,
line_width=5,
line_cap='round',
line_join='round',
legend='obs.',
color='#0000ff',
alpha=0.7,
)
minx = obs.index.min()
maxx = obs.index.max()
p.x_range = Range1d(
start = minx,
end = maxx
)
p.legend.location = 'top_left'
p.add_tools(
HoverTool(
tooltips=[
('obs.', '@y'),
],
renderers=[l1],
),
)
return p
#def make_plot(obs, model = None,label,remove_mean_diff=False,bbox_bias=None):
def make_plot(obs, model = None,label=None,remove_mean_diff=False,bbox_bias=0.0):
#TOOLS="hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select,"
TOOLS="crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,reset,save,"
p = figure(toolbar_location='above',
x_axis_type='datetime',
width=width,
height=height,
tools=TOOLS)
p.add_layout(Title(text='Station: '+obs._metadata['station_code'], text_font_style="italic"), 'above')
p.add_layout(Title(text=obs._metadata['station_name'], text_font_size="10pt"), 'above')
p.yaxis.axis_label = label
obs_val = obs.values.squeeze()
l1 = p.line(
x=obs.index,
y=obs_val,
line_width=5,
line_cap='round',
line_join='round',
legend='obs.',
color='#0000ff',
alpha=0.7,
)
if model is not None:
mod_val = model.values.squeeze()
if ('SSH' in label) and remove_mean_diff:
mod_val = mod_val + obs_val.mean() - mod_val.mean()
if ('SSH' in label) and bbox_bias is not None:
mod_val = mod_val + bbox_bias
l0 = p.line(
x=model.index,
y=mod_val,
line_width=5,
line_cap='round',
line_join='round',
legend='model',
color='#9900cc',
alpha=0.7,
)
minx = max (model.index.min(),obs.index.min())
maxx = min (model.index.max(),obs.index.max())
minx = model.index.min()
maxx = model.index.max()
else:
minx = obs.index.min()
maxx = obs.index.max()
p.x_range = Range1d(
start = minx,
end = maxx
)
p.legend.location = 'top_left'
p.add_tools(
HoverTool(
tooltips=[
('model', '@y'),
],
renderers=[l0],
),
HoverTool(
tooltips=[
('obs.', '@y'),
],
renderers=[l1],
),
)
return p
#def make_plot(obs, model = None,label,remove_mean_diff=False,bbox_bias=None):
def make_dual_plot(obs, model = None,label=None,remove_mean_diff=False,bbox_bias=0.0):
#TOOLS="hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select,"
if model is None:
sys.exit('Model can not be none')
df = obs.copy()
df ['obs'] = obs.values
df ['mod'] = model
df = df.dropna()
if True:
if ('SSH' in label) and remove_mean_diff:
df ['mod'] = df ['mod'] + df ['obs'].mean() - df ['mod'].mean()
if ('SSH' in label) and bbox_bias is not None:
df ['mod'] = df ['mod'] + bbox_bias
# https://bokeh.pydata.org/en/latest/docs/user_guide/interaction/linking.html#linked-brushing
# create a column data source for the plots to share
src = ColumnDataSource(data=dict(x = df.index.to_pydatetime(),
yo = df['obs'].values,
ym = df['mod'].values))
TOOLS="box_select,lasso_select,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,reset,save,help,"
left = figure(toolbar_location='above',
x_axis_type='datetime',
width=width,
height=height,
tools=TOOLS)
left.add_layout(Title(text='Station: '+obs._metadata['station_code'], text_font_style="italic"), 'above')
left.add_layout(Title(text=obs._metadata['station_name'], text_font_size="10pt"), 'above')
left.yaxis.axis_label = label
left.xaxis.axis_label = 'DateTime'
l1 = left.line(
x='x',
y='yo',
line_width=5,
line_cap='round',
line_join='round',
legend='obs.',
color='#0000ff',
alpha=0.7,
source = src,
)
l0 = left.line(
x='x',
y='ym',
line_width=5,
line_cap='round',
line_join='round',
legend='model',
color='#9900cc',
alpha=0.7,
source =src
)
left.x_range = Range1d(
start = df.index.min(),
end = df.index.max()
)
left.legend.location = 'top_left'
left.add_tools(
HoverTool(
tooltips=[
('Model', '@ym'),
],
renderers=[l0],
# display a tooltip whenever the cursor is vertically in line with a glyph
mode='vline',
),
HoverTool(
tooltips=[
('Obs.', '@yo'),
],
renderers=[l1],
# display a tooltip whenever the cursor is vertically in line with a glyph
mode='vline',
),
)
# left.add_tools(
# HoverTool(
# tooltips=[
# ('Model', '@ym'),
# ('Obs.', '@yo'),
# ],
# # display a tooltip whenever the cursor is vertically in line with a glyph
# mode='vline'
# ),
#
# )
## display a tooltip whenever the cursor is vertically in line with a glyph
#mode='vline'
#### https://bokeh.pydata.org/en/latest/docs/user_guide/tools.html
# https://bokeh.pydata.org/en/1.0.0/docs/user_guide/examples/tools_hover_tooltip_formatting.html
#rTOOLTIPS = [
#("Date" , "$x"),
#("Obs." , "$yo"),
#("Model", "$ym"),
#]
#hover_tool.formatters = { "x": "datetime"}
#right = figure(tools=TOOLS, plot_width=height, plot_height=height, title='Select',tooltips=rTOOLTIPS)
right = figure(tools=TOOLS, plot_width=height, plot_height=height, title='Select from ...')
right.circle('yo', 'ym', source=src)
right.yaxis.axis_label = 'Model'
right.xaxis.axis_label = 'Obs.'
right.add_tools(
HoverTool(
tooltips=[
#('Date' , '@x'),
('Model', '@ym'),
('Obs.' , '@yo'),
],
formatters={
'x' : 'datetime', # use 'datetime' formatter for 'date' field
# use default 'numeral' formatter for other fields
},
),
)
p = gridplot([[right,left]])
return p
#################
def make_marker(p, location, fname , color = 'green',icon= 'stats'):
html = file_html(p, CDN, fname)
#iframe = IFrame(html , width=width+45+height, height=height+80)
iframe = IFrame(html , width=width * 1.1, height=height * 1.2)
#popup = folium.Popup(iframe, max_width=2650+height)
popup = folium.Popup(iframe)
iconm = folium.Icon(color = color, icon=icon)
marker = folium.Marker(location=location,
popup=popup,
icon=iconm)
return marker
###############################
###try to add countor to map
def Read_maxele_return_plot_obj(fgrd='depth_hsofs_inp.nc',felev='maxele.63.nc'):
"""
"""
ncg = netCDF4.Dataset(fgrd)
ncgv = ncg.variables
#read maxelev
nc0 = netCDF4.Dataset(felev)
ncv0 = nc0.variables
data = ncv0['zeta_max'][:]
#data = ncv0['surge'][:]
#dep0 = ncv0['depth'][:]
lon0 = ncv0['x'][:]
lat0 = ncv0['y'][:]
elems = ncgv['element'][:,:]-1 # Move to 0-indexing by subtracting 1
data[data.mask] = 0.0
MinVal = np.min(data)
MaxVal = np.max(data)
NumLevels = 21
if True:
MinVal = max(MinVal,1)
MaxVal = min(MaxVal,4)
NumLevels = 11
levels = np.linspace(MinVal, MaxVal, num=NumLevels)
tri = Tri.Triangulation(lon0,lat0, triangles=elems)
contour = plt.tricontourf(tri, data,levels=levels,cmap = my_cmap ,extend='max')
return contour,MinVal,MaxVal,levels
#############################################################
def collec_to_gdf(collec_poly):
"""Transform a `matplotlib.contour.QuadContourSet` to a GeoDataFrame"""
polygons, colors = [], []
for i, polygon in enumerate(collec_poly.collections):
mpoly = []
for path in polygon.get_paths():
try:
path.should_simplify = False
poly = path.to_polygons()
# Each polygon should contain an exterior ring + maybe hole(s):
exterior, holes = [], []
if len(poly) > 0 and len(poly[0]) > 3:
# The first of the list is the exterior ring :
exterior = poly[0]
# Other(s) are hole(s):
if len(poly) > 1:
holes = [h for h in poly[1:] if len(h) > 3]
mpoly.append(Polygon(exterior, holes))
except:
print('Warning: Geometry error when making polygon #{}'
.format(i))
if len(mpoly) > 1:
mpoly = MultiPolygon(mpoly)
polygons.append(mpoly)
colors.append(polygon.get_facecolor().tolist()[0])
elif len(mpoly) == 1:
polygons.append(mpoly[0])
colors.append(polygon.get_facecolor().tolist()[0])
return GeoDataFrame(
geometry=polygons,
data={'RGBA': colors},
crs={'init': 'epsg:4326'})
#################
def convert_to_hex(rgba_color) :
red = str(hex(int(rgba_color[0]*255)))[2:].capitalize()
green = str(hex(int(rgba_color[1]*255)))[2:].capitalize()
blue = str(hex(int(rgba_color[2]*255)))[2:].capitalize()
if blue=='0':
blue = '00'
if red=='0':
red = '00'
if green=='0':
green='00'
return '#'+ red + green + blue
#################
def get_station_ssh(fort61):
"""
Read model ssh
"""
nc0 = netCDF4.Dataset(fort61)
ncv0 = nc0.variables
sta_lon = ncv0['x'][:]
sta_lat = ncv0['y'][:]
sta_nam = ncv0['station_name'][:].squeeze()
sta_zeta = ncv0['zeta'] [:].squeeze()
sta_date = netCDF4.num2date(ncv0['time'][:], ncv0['time'].units)
stationIDs = []
mod = []
ind = np.arange(len(sta_lat))
for ista in ind:
stationID = sta_nam[ista].tostring().decode().rstrip()
stationIDs.append(stationID)
mod_tmp = pd.DataFrame(data = np.c_[sta_date, sta_zeta[:,ista]], columns=['date_time', 'ssh']).set_index('date_time')
mod_tmp._metadata = stationID
mod.append(mod_tmp)
stationIDs = np.array(stationIDs)
mod_table = pd.DataFrame(data = np.c_[ind, stationIDs], columns=['ind', 'station_code'])
return mod,mod_table
#################
def get_station_wnd_all(fort61):
"""
Read model wind
"""
nc0 = netCDF4.Dataset(fort61)
ncv0 = nc0.variables
try:
sta_lon = ncv0['x'][:]
except:
sta_lon = ncv0['lon'][:]
try:
sta_lat = ncv0['y'][:]
except:
sta_lon = ncv0['lat'][:]
sta_nam = ncv0['station_name'][:].squeeze()
sta_uwnd = ncv0['uwnd'] [:].squeeze()
sta_vwnd = ncv0['vwnd'] [:].squeeze()
sta_pres = ncv0['pres'] [:].squeeze()
sta_date = netCDF4.num2date(ncv0['time'][:], ncv0['time'].units)
stationIDs = []
mod = []
ind = np.arange(len(sta_lat))
for ista in ind:
stationID = sta_nam[ista].tostring().decode().rstrip()
stationIDs.append(stationID)
mod_tmp = pd.DataFrame(data = np.c_[sta_date,sta_uwnd[:,ista],sta_vwnd[:,ista],sta_pres[:,ista]],
columns = ['date_time', 'uwnd' , 'vwnd', 'pres']).set_index('date_time')
mod_tmp._metadata = stationID
mod.append(mod_tmp)
stationIDs = np.array(stationIDs)
mod_table = pd.DataFrame(data = np.c_[ind, stationIDs], columns=['ind', 'station_code'])
return mod,mod_table
#################
def get_station_wnd(fort61):
"""
Read model wind
"""
nc0 = netCDF4.Dataset(fort61)
ncv0 = nc0.variables
try:
sta_lon = ncv0['x'][:]
except:
sta_lon = ncv0['lon'][:]
try:
sta_lat = ncv0['y'][:]
except:
sta_lat = ncv0['lat'][:]
sta_nam = ncv0['station_name'][:].squeeze()
sta_wnd = np.sqrt ( ncv0['uwnd'] [:].squeeze() ** 2 + ncv0['vwnd'] [:].squeeze() ** 2 )
sta_date = netCDF4.num2date(ncv0['time'][:], ncv0['time'].units)
stationIDs = []
mod = []
ind = np.arange(len(sta_lat))
for ista in ind:
stationID = sta_nam[ista].tostring().decode().rstrip()
stationIDs.append(stationID)
mod_tmp = pd.DataFrame(data = np.c_[sta_date,sta_wnd[:,ista]],
columns = ['date_time', 'wnd' ]).set_index('date_time')
mod_tmp._metadata = stationID
mod.append(mod_tmp)
stationIDs = np.array(stationIDs)
mod_table1 = pd.DataFrame(data = np.c_[ind, stationIDs], columns=['ind', 'station_code'])
nc0.close()
return mod,mod_table1
def get_model_at_station_wave(wav_at_nbdc):
"""
Read model wave
"""
nc0 = netCDF4.Dataset(wav_at_nbdc)
ncv0 = nc0.variables
sta_hsig = ncv0['hsig'] [:].squeeze()
sta_hsig [sta_hsig > 1e3 ] = 0.0
sta_date = netCDF4.num2date(ncv0['time'][:], ncv0['time'].units)
sta_nam = ncv0['station_name'][:].squeeze()
sta_lon = ncv0['lon'][:]
sta_lat = ncv0['lat'][:]
nc0.close()
stationIDs = []
mod = []
ind = np.arange(len(sta_lat))
for ista in ind:
stationID = sta_nam[ista][~sta_nam.mask[ista]].tostring().decode().split('.')[0]
stationIDs.append(stationID)
mod_tmp = pd.DataFrame(data = np.c_[sta_date,sta_hsig[:,ista]],
columns = ['date_time', 'hsig' ]).set_index('date_time')
mod_tmp._metadata = stationID
mod.append(mod_tmp)
stationIDs = np.array(stationIDs)
mod_table = pd.DataFrame(data = np.c_[ind, stationIDs], columns=['ind', 'station_code'])
return mod,mod_table
def get_model_at_station_wind(wnd_at_nbdc):
"""
Read model wind
"""
nc0 = netCDF4.Dataset(wnd_at_nbdc)
ncv0 = nc0.variables
sta_wnd = np.sqrt ( ncv0['uwnd'] [:].squeeze() ** 2 + ncv0['vwnd'] [:].squeeze() ** 2 )
sta_wnd [sta_wnd > 1e3 ] = 0.0
sta_date = netCDF4.num2date(ncv0['time'][:], ncv0['time'].units)
sta_nam = ncv0['station_name'][:].squeeze()
sta_lon = ncv0['lon'][:]
sta_lat = ncv0['lat'][:]
nc0.close()
stationIDs = []
mod = []
ind = np.arange(len(sta_lat))
for ista in ind:
stationID = sta_nam[ista][~sta_nam.mask[ista]].tostring().decode()
stationIDs.append(stationID)
mod_tmp = pd.DataFrame(data = np.c_[sta_date,sta_wnd[:,ista]],
columns = ['date_time', 'wnd' ]).set_index('date_time')
mod_tmp._metadata = stationID
mod.append(mod_tmp)
stationIDs = np.array(stationIDs)
mod_table = pd.DataFrame(data = np.c_[ind, stationIDs], columns=['ind', 'station_code'])
return mod,mod_table
#############################################################
def make_map(bbox, **kw):
"""
Creates a folium map instance.
Examples
--------
>>> from folium import Map
>>> bbox = [-87.40, 24.25, -74.70, 36.70]
>>> m = make_map(bbox)
>>> isinstance(m, Map)
True
"""
import folium
line = kw.pop('line', True)
layers = kw.pop('layers', True)
zoom_start = kw.pop('zoom_start', 5)
lon, lat = np.array(bbox).reshape(2, 2).mean(axis=0)
#
m = folium.Map(width='100%', height='100%',
location=[lat, lon], zoom_start=zoom_start)
if layers:
add = 'MapServer/tile/{z}/{y}/{x}'
base = 'http://services.arcgisonline.com/arcgis/rest/services'
ESRI = dict(Imagery='World_Imagery/MapServer',
#Ocean_Base='Ocean/World_Ocean_Base',
#Topo_Map='World_Topo_Map/MapServer',
#Physical_Map='World_Physical_Map/MapServer',
#Terrain_Base='World_Terrain_Base/MapServer',
#NatGeo_World_Map='NatGeo_World_Map/MapServer',
#Shaded_Relief='World_Shaded_Relief/MapServer',
#Ocean_Reference='Ocean/World_Ocean_Reference',
#Navigation_Charts='Specialty/World_Navigation_Charts',
#Street_Map='World_Street_Map/MapServer'
)
for name, url in ESRI.items():
url = '{}/{}/{}'.format(base, url, add)
w = folium.TileLayer(tiles=url,
name=name,
attr='ESRI',
overlay=False)
w.add_to(m)
if line: # Create the map and add the bounding box line.
p = folium.PolyLine(get_coordinates(bbox),
color='#FF0000',
weight=2,
opacity=0.5,
latlon=True)
p.add_to(m)
folium.LayerControl().add_to(m)
return m
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER,
LATITUDE_FORMATTER)
import cartopy.feature as cfeature
def make_map_cartopy(projection=ccrs.PlateCarree()):
"""
Generate fig and ax using cartopy
input: projection
output: fig and ax
"""
alpha = 0.5
subplot_kw = dict(projection=projection)
fig, ax = plt.subplots(figsize=(9, 13),
subplot_kw=subplot_kw)
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
# Put a background image on for nice sea rendering.
ax.stock_img()
# Create a feature for States/Admin 1 regions at 1:50m from Natural Earth
states_provinces = cfeature.NaturalEarthFeature(
category='cultural',
name='admin_1_states_provinces_lines',
scale='50m',
facecolor='none')
SOURCE = 'Natural Earth'
LICENSE = 'public domain'
ax.add_feature(cfeature.LAND,zorder=0,alpha=alpha)
ax.add_feature(cfeature.COASTLINE,zorder=1,alpha=alpha)
ax.add_feature(cfeature.BORDERS,zorder=1,alpha=2*alpha)
ax.add_feature(states_provinces, edgecolor='gray',zorder=1)
# Add a text annotation for the license information to the
# the bottom right corner.
text = AnchoredText(r'$\mathcircled{{c}}$ {}; license: {}'
''.format(SOURCE, LICENSE),
loc=4, prop={'size': 9}, frameon=True)
ax.add_artist(text)
ax.set_xlim(-132,-65) #lon limits
ax.set_ylim( 20 , 55) #lat limits
return fig, ax
#calculate bias for bbox region
def get_bias(bias_bbox,ssh,ssh_table,fort61 ):
ind = get_ind (bias_bbox,ssh_table.lon,ssh_table.lat)
mask = get_mask(bias_bbox,ssh_table.lon,ssh_table.lat)
#
ssh_bias_table = ssh_table[~mask]
#
ssh_bias = []
ssh_biad_tab = []
for in0 in ind:
ssh_bias.append(ssh[in0])
########### Read SSH data
mod , mod_table = get_station_ssh(fort61)
############# Sea Surface height analysis ########################
# For simplicity we will use only the stations that have both wind speed and sea surface height and reject those that have only one or the other.
common = set(ssh_bias_table['station_code']).intersection(mod_table ['station_code'].values)
ssh_obs, ssh_mod = [], []
for station in common:
ssh_obs.extend([obs for obs in ssh if obs._metadata['station_code'] == station])
ssh_mod.extend([obm for obm in mod if obm._metadata == station])
index = pd.date_range(
start = bias_calc_start.replace(tzinfo=None),
end = bias_calc_end.replace (tzinfo=None),
freq=freq
)
#############################################################
#organize and re-index both observations
# Re-index and rename series.
ssh_observations = []
ssh_all = []
for series in ssh_obs:
_metadata = series._metadata
obs = series.tz_localize(None).reindex(index=index, limit=1, method='nearest')
obs._metadata = _metadata
obs.name = _metadata['station_name']
ssh_observations.append(obs)
ssh_all.append( obs['water_surface_height_above_reference_datum (m)'].values)
##############################################################
#model
ssh_from_model = []
mod_all = []
for series in ssh_mod:
_metadata = series._metadata
obs = series.tz_localize(None).reindex(index=index, limit=1, method='nearest')
obs._metadata = _metadata
obs.name = _metadata
ssh_from_model.append(obs)
mod_all.append( obs['ssh'].values)
ssh_all = np.array(ssh_all).flatten()
mask = np.isnan(ssh_all)
mod_all = np.array(mod_all).flatten()
bias = (ssh_all[~mask] - mod_all [~mask]).mean()
return bias
########################################
#### MAIN CODE from HERE #####
########################################
for key in storms.keys():
name = storms[key]['name']
year = storms[key]['year']
print('\n\n\n\n\n\n********************************************************')
print( '***** Storm name ',name, ' Year ', year, ' *********')
print( '******************************************************** \n\n\n\n\n\n')
wnd_ocn_observs = wnd_ocn_models = wnd_ocn = None
wav_ocn = wav_observs = wav_models = None
wnd_obs = wnd_observs = wnd_models = None
ssh = ssh_observations = ssh_from_model = None
name = name #[:3]
obs_dir = os.path.join(base_dirf,'work_dir','obs')
mod_dir = os.path.join(base_dirf,'work_dir','mod')
print ( ' > Read NHC information ... ')
al_code , hurricane_gis_files, df = get_nhc_storm_info (year,name)
#donload gis zip files
base = download_nhc_gis_files(hurricane_gis_files)
# get advisory cones and track points
cones , points , pts = read_advisory_cones_info(hurricane_gis_files,base,year,al_code)
# Find the bounding box to search the data.
bbox_from_track = True
if bbox_from_track:
last_cone = cones[-1]['geometry'].iloc[0]
track = LineString([point['geometry'] for point in points])
track_lons = track.coords.xy[0]
track_lats = track.coords.xy[1]
bbox = min(track_lons)-2, min(track_lats)-2, max(track_lons)+2, max(track_lats)+2
else:
bounds = np.array([last_cone.buffer(2).bounds, track.buffer(2).bounds]).reshape(4, 2)
lons, lats = bounds[:, 0], bounds[:, 1]
bbox = lons.min(), lats.min(), lons.max(), lats.max()
if storms[key]['bbox'] is not None: