mattritchey commited on
Commit
de0d462
·
1 Parent(s): 388bd7c

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +375 -0
  2. requirements.txt +14 -0
app.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Dec 6 09:56:29 2022
4
+
5
+ @author: mritchey
6
+ """
7
+ #streamlit run "C:\Users\mritchey\.spyder-py3\Python Scripts\streamlit projects\mrms\mrms_all buffer.py"
8
+
9
+ import plotly.express as px
10
+
11
+ from joblib import Parallel, delayed
12
+ import pandas as pd
13
+ import streamlit as st
14
+ from geopy.extra.rate_limiter import RateLimiter
15
+ from geopy.geocoders import Nominatim
16
+ import folium
17
+ from streamlit_folium import st_folium
18
+ import math
19
+ import geopandas as gpd
20
+ from skimage.io import imread
21
+ from streamlit_plotly_events import plotly_events
22
+ import requests
23
+ import rasterio
24
+ import rioxarray
25
+ import numpy as np
26
+ import base64
27
+ import re
28
+
29
+
30
+ @st.cache
31
+ def geocode(address, buffer_size):
32
+ try:
33
+ address2 = address.replace(' ', '+').replace(',', '%2C')
34
+ df = pd.read_json(
35
+ f'https://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address={address2}&benchmark=2020&format=json')
36
+ results = df.iloc[:1, 0][0][0]['coordinates']
37
+ lat, lon = results['y'], results['x']
38
+ except:
39
+ geolocator = Nominatim(user_agent="GTA Lookup")
40
+ geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
41
+ location = geolocator.geocode(address)
42
+ lat, lon = location.latitude, location.longitude
43
+
44
+ df = pd.DataFrame({'Lat': [lat], 'Lon': [lon]})
45
+ gdf = gpd.GeoDataFrame(
46
+ df, geometry=gpd.points_from_xy(df.Lon, df.Lat, crs=4326))
47
+ gdf['buffer'] = gdf['geometry'].to_crs(
48
+ 3857).buffer(buffer_size/2*2580).to_crs(4326)
49
+ return gdf
50
+
51
+
52
+ def get_pngs(date):
53
+ year, month, day = date[:4], date[4:6], date[6:]
54
+ url = f'https://mrms.nssl.noaa.gov/qvs/product_viewer/local/render_multi_domain_product_layer.php?mode=run&cpp_exec_dir=/home/metop/web/specific/opv/&web_resources_dir=/var/www/html/qvs/product_viewer/resources/&prod_root={prod_root}&qperate_pal_option=0&qpe_pal_option=0&year={year}&month={month}&day={day}&hour={hour}&minute={minute}&clon={lon}&clat={lat}&zoom={zoom}&width=920&height=630'
55
+ data = imread(url)[:, :, :3]
56
+ data2 = data.reshape(630*920, 3)
57
+ data2_df = pd.DataFrame(data2, columns=['R', 'G', 'B'])
58
+ data2_df2 = pd.merge(data2_df, lut[['R', 'G', 'B', 'Value', ]], on=['R', 'G', 'B'],
59
+ how='left')[['Value', ]]
60
+ data2_df2['Date'] = date
61
+ return data2_df2.reset_index()
62
+
63
+
64
+ @st.cache
65
+ def get_pngs_parallel(dates):
66
+ results1 = Parallel(n_jobs=32, prefer="threads")(
67
+ delayed(get_pngs)(i) for i in dates)
68
+ return results1
69
+
70
+
71
+ def png_data(date):
72
+ year, month, day = date[:4], date[4:6], date[6:]
73
+ url = f'https://mrms.nssl.noaa.gov/qvs/product_viewer/local/render_multi_domain_product_layer.php?mode=run&cpp_exec_dir=/home/metop/web/specific/opv/&web_resources_dir=/var/www/html/qvs/product_viewer/resources/&prod_root={prod_root}&qperate_pal_option=0&qpe_pal_option=0&year={year}&month={month}&day={day}&hour={hour}&minute={minute}&clon={lon}&clat={lat}&zoom={zoom}&width=920&height=630'
74
+ data = imread(url)
75
+ return data
76
+
77
+
78
+ @st.cache(allow_output_mutation=True)
79
+ def map_folium(data, gdf):
80
+ m = folium.Map(location=[lat, lon], zoom_start=zoom, height=300)
81
+ folium.Marker(
82
+ location=[lat, lon],
83
+ popup=address).add_to(m)
84
+
85
+ folium.GeoJson(gdf['buffer']).add_to(m)
86
+ folium.raster_layers.ImageOverlay(
87
+ data, opacity=0.8, bounds=bounds).add_to(m)
88
+ return m
89
+
90
+
91
+ def to_radians(degrees):
92
+ return degrees * math.pi / 180
93
+
94
+
95
+ def lat_lon_to_bounds(lat, lng, zoom, width, height):
96
+ earth_cir_m = 40075016.686
97
+ degreesPerMeter = 360 / earth_cir_m
98
+ m_pixel_ew = earth_cir_m / math.pow(2, zoom + 8)
99
+ m_pixel_ns = earth_cir_m / \
100
+ math.pow(2, zoom + 8) * math.cos(to_radians(lat))
101
+
102
+ shift_m_ew = width/2 * m_pixel_ew
103
+ shift_m_ns = height/2 * m_pixel_ns
104
+
105
+ shift_deg_ew = shift_m_ew * degreesPerMeter
106
+ shift_deg_ns = shift_m_ns * degreesPerMeter
107
+
108
+ return [[lat-shift_deg_ns, lng-shift_deg_ew], [lat+shift_deg_ns, lng+shift_deg_ew]]
109
+
110
+
111
+ def image_to_geotiff(bounds, input_file_path, output_file_path='template.tiff'):
112
+ south, west, north, east = tuple(
113
+ [item for sublist in bounds for item in sublist])
114
+ dataset = rasterio.open(input_file_path, 'r')
115
+ bands = [1, 2, 3]
116
+ data = dataset.read(bands)
117
+ transform = rasterio.transform.from_bounds(west, south, east, north,
118
+ height=data.shape[1],
119
+ width=data.shape[2])
120
+ crs = {'init': 'epsg:4326'}
121
+
122
+ with rasterio.open(output_file_path, 'w', driver='GTiff',
123
+ height=data.shape[1],
124
+ width=data.shape[2],
125
+ count=3, dtype=data.dtype, nodata=0,
126
+ transform=transform, crs=crs,
127
+ compress='lzw') as dst:
128
+ dst.write(data, indexes=bands)
129
+
130
+
131
+ def get_mask(bounds, buffer_size):
132
+ year, month, day = date[:4], date[4:6], date[6:]
133
+ url = f'https://mrms.nssl.noaa.gov/qvs/product_viewer/local/render_multi_domain_product_layer.php?mode=run&cpp_exec_dir=/home/metop/web/specific/opv/&web_resources_dir=/var/www/html/qvs/product_viewer/resources/&prod_root={prod_root}&qperate_pal_option=0&qpe_pal_option=0&year={year}&month={month}&day={day}&hour={hour}&minute={minute}&clon={lon}&clat={lat}&zoom={zoom}&width=920&height=630'
134
+ img_data = requests.get(url, verify=False).content
135
+ input_file_path = f'image_name_{date}_{var}.png'
136
+ output_file_path = 'template.tiff'
137
+ with open(input_file_path, 'wb') as handler:
138
+ handler.write(img_data)
139
+
140
+ image_to_geotiff(bounds, input_file_path, output_file_path)
141
+ rds = rioxarray.open_rasterio(output_file_path)
142
+ # rds.plot.imshow()
143
+ rds = rds.assign_coords(distance=(haversine(rds.x, rds.y, lon, lat)))
144
+ mask = rds['distance'].values <= buffer_size
145
+ mask = np.transpose(np.stack([mask, mask, mask]), (1, 2, 0))
146
+ return mask
147
+
148
+
149
+ def haversine(lon1, lat1, lon2, lat2):
150
+ # convert decimal degrees to radians
151
+ lon1 = np.deg2rad(lon1)
152
+ lon2 = np.deg2rad(lon2)
153
+ lat1 = np.deg2rad(lat1)
154
+ lat2 = np.deg2rad(lat2)
155
+
156
+ # haversine formula
157
+ dlon = lon2 - lon1
158
+ dlat = lat2 - lat1
159
+ a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
160
+ c = 2 * np.arcsin(np.sqrt(a))
161
+ r = 6371
162
+ return c * r
163
+
164
+
165
+ def render_svg(svg):
166
+ """Renders the given svg string."""
167
+ b64 = base64.b64encode(svg.encode('utf-8')).decode("utf-8")
168
+ html = r'<img src="data:image/svg+xml;base64,%s"/>' % b64
169
+ st.write(html, unsafe_allow_html=True)
170
+
171
+
172
+ def rgb_to_hex(rgb):
173
+ return '#'+'%02x%02x%02x' % rgb
174
+
175
+
176
+ def get_legend_lut(prod_root):
177
+ url_legend = f'https://mrms.nssl.noaa.gov/qvs/product_viewer/shared/fetch_svg_legend_via_config.php?web_resources_dir=/var/www/html/qvs/product_viewer/resources/&config_name=title_and_legend_config.txt&product={prod_root}'
178
+ r = requests.get(url_legend) # Get the webpage
179
+ svg = r.content.decode() # Decoded response content with the svg string
180
+
181
+ if svg.find('size="16">mm</text>') > 0:
182
+ svg = svg.replace('size="16">mm</text>', 'size="16">in</text>')
183
+ beg_string = '"13">'
184
+ end_string = '</text>'
185
+ res = re.findall('%s(.*)%s' % (beg_string, end_string), svg)
186
+ for mm in res:
187
+ inc = round(float(mm)*0.0393701, 2)
188
+ svg = svg.replace(f'{beg_string}{mm}{end_string}',
189
+ f'{beg_string}{str(inc)}{end_string}')
190
+
191
+ elif svg.find('font-size="12">') > 0:
192
+ beg_string = '"12">'
193
+ end_string = '</text>'
194
+
195
+ else:
196
+ beg_string = '"13">'
197
+ end_string = '</text>'
198
+
199
+ #Make LUT
200
+ values = re.findall('%s(.*)%s' % (beg_string, end_string), svg)
201
+
202
+ beg_string, end_string = 'fill="rgb(', ')" />'
203
+ rgb = re.findall('%s(.*)%s' % (beg_string, end_string), svg)
204
+ rgb = [eval(i[0]) for i in rgb]
205
+
206
+ beg_string, end_string = 'style="fill:rgb(', ');" />'
207
+ rgb2 = re.findall('%s(.*)%s' % (beg_string, end_string), svg)
208
+ rgb2 = [eval(i[0]) for i in rgb2]
209
+
210
+ rgb = rgb2+rgb
211
+
212
+ lut = pd.DataFrame({'Value': values,
213
+ 'RGB': rgb})
214
+ lut['R'], lut['G'], lut['B'] = lut['RGB'].str
215
+ lut[['R', 'G', 'B']] = lut[['R', 'G', 'B']].astype('uint8')
216
+ lut['Value'] = lut['Value'].astype(float)
217
+ lut['hex'] = lut['RGB'].apply(rgb_to_hex)
218
+ return svg, lut
219
+
220
+
221
+ #Set Columns
222
+ st.set_page_config(layout="wide")
223
+
224
+
225
+ #Input Data
226
+ zoom = 10
227
+ address = st.sidebar.text_input(
228
+ "Address", "cape coral, fl")
229
+ var = st.sidebar.selectbox(
230
+ 'Product:', ('Hail', 'Flooding', 'Rain: Radar', 'Rain: Multi Sensor', 'Tornado'))
231
+
232
+ date = st.sidebar.date_input("Date", pd.Timestamp(
233
+ 2022, 9, 28), key='date').strftime('%Y%m%d')
234
+ d = pd.Timestamp(date)
235
+ days_within = st.sidebar.selectbox('Within Days:', (5, 30, 60))
236
+
237
+ mask_select = st.sidebar.radio('Only Show Buffer Data:', ("No", "Yes"))
238
+ buffer_size = st.sidebar.radio('Buffer Size (miles):', (5, 10, 15))
239
+
240
+ year, month, day = date[:4], date[4:6], date[6:]
241
+ hour = 23
242
+ minute = 0
243
+
244
+
245
+ #Select Variable
246
+ if var == 'Hail':
247
+ var_input = 'hails&product=MESHMAX1440M'
248
+ elif var == 'Flooding':
249
+ var_input = 'flash&product=FL_ARI24H'
250
+ elif var == 'Rain: Radar':
251
+ var_input = 'q3rads&product=Q3EVAP24H'
252
+ elif var == 'Rain: Multi Sensor':
253
+ var_input = 'q3mss&product=P1_Q3MS24H'
254
+ elif var == 'Tornado':
255
+ var_input = 'azsh&product=RT1440M'
256
+
257
+ prod_root = var_input[var_input.find('=')+1:]
258
+
259
+ #Geocode
260
+ gdf = geocode(address, buffer_size)
261
+ lat, lon = tuple(gdf[['Lat', 'Lon']].values[0])
262
+
263
+ #Get Value
264
+ url = 'https://mrms.nssl.noaa.gov/qvs/product_viewer/local/get_multi_domain_rect_binary_value.php?mode=run&cpp_exec_dir=/home/metop/web/specific/opv/&web_resources_dir=/var/www/html/qvs/product_viewer/resources/'\
265
+ + f'&prod_root={prod_root}&lon={lon}&lat={lat}&year={year}&month={month}&day={day}&hour={hour}&minute={minute}'
266
+
267
+ response = requests.get(url, verify=False).json()
268
+ qvs_values = pd.DataFrame(response, index=[0])[
269
+ ['qvs_value', 'qvs_units']].values[0]
270
+ qvs_value = qvs_values[0]
271
+ qvs_unit = qvs_values[1]
272
+
273
+ #Get PNG Focus
274
+ data = png_data(date)
275
+
276
+ #Get PNG Max
277
+ start_date, end_date = d - \
278
+ pd.Timedelta(days=days_within), d+pd.Timedelta(days=days_within)
279
+ dates = pd.date_range(start_date,
280
+ end_date).strftime('%Y%m%d')
281
+ #Get SVG and Lut
282
+ svg, lut = get_legend_lut(prod_root)
283
+
284
+ bounds = lat_lon_to_bounds(lat, lon, zoom, 920, 630)
285
+
286
+ results1 = get_pngs_parallel(dates)
287
+ # results1 = Parallel(n_jobs=32, prefer="threads")(delayed(get_pngs)(i) for i in dates)
288
+ results = pd.concat(results1).fillna(0)
289
+ max_data = results.groupby('index')[['Value']].max()
290
+
291
+ max_data2 = pd.merge(max_data,
292
+ lut[['R', 'G', 'B', 'Value']],
293
+ on=['Value'],
294
+ how='left')[['R', 'G', 'B']]
295
+
296
+ data_max = max_data2.values.reshape(630, 920, 3)
297
+
298
+ #Masked Data
299
+ if mask_select == "Yes":
300
+ mask = get_mask(bounds, buffer_size)
301
+ mask1 = mask[:, :, 0].reshape(630*920)
302
+ results = pd.concat([i[mask1] for i in results1])
303
+ data_max = data_max*mask
304
+ else:
305
+ pass
306
+
307
+
308
+ #Bar
309
+ if var == 'Tornado':
310
+ bar = results.query("Value>.006").groupby(
311
+ ['Date', 'Value'])['index'].count().reset_index()
312
+ else:
313
+ bar = results.query("Value>.2").groupby(['Date', 'Value'])[
314
+ 'index'].count().reset_index()
315
+
316
+ bar['Date'] = pd.to_datetime(bar['Date'])
317
+
318
+ bar = bar.reset_index()
319
+ bar.columns = ['level_0', 'Date', 'Value', 'count']
320
+ bar = bar.sort_values('Value', ascending=True)
321
+ bar['Value'] = bar['Value'].astype(str)
322
+
323
+
324
+ color_discrete_map = lut[['Value', 'hex']].sort_values(
325
+ 'Value', ascending=True).astype(str)
326
+ color_discrete_map = color_discrete_map.set_index(
327
+ 'Value').to_dict()['hex']
328
+
329
+ fig = px.bar(bar, x="Date", y="count", color="Value",
330
+ barmode='stack',
331
+ color_discrete_map=color_discrete_map)
332
+
333
+ #Submit Url to New Tab
334
+ url = f'https://mrms.nssl.noaa.gov/qvs/product_viewer/index.php?web_exec_mode=run&menu=menu_config.txt&year={year}&month={month}&day={day}&hour=23&minute=30&time_mode=static&zoom=9&clon={lon}&clat={lat}&base=0&overlays=1&mping_mode=0&product_type={var_input}&qpe_pal_option=0&opacity=.75&looping_active=off&num_frames=6&frame_step=200&seconds_step=600'
335
+
336
+
337
+ #Map Focus
338
+ m = map_folium(data, gdf)
339
+ #Map Max
340
+ m_max = map_folium(data_max, gdf)
341
+
342
+ with st.container():
343
+ col1, col2 = st.columns(2)
344
+
345
+ with col1:
346
+ st.header(f'{var} on {pd.Timestamp(date).strftime("%D")}')
347
+ st_folium(m, height=300)
348
+ with col2:
349
+ st.header(
350
+ f'Max from {start_date.strftime("%D")} to {end_date.strftime("%D")}')
351
+ st_folium(m_max, height=300)
352
+
353
+ with st.container():
354
+ col1, col2, col3 = st.columns((1, 10, 6))
355
+ with col1:
356
+ render_svg(svg)
357
+ with col2:
358
+ link = f'[Go To MRMS Site]({url})'
359
+ st.markdown(link, unsafe_allow_html=True)
360
+ selected_points = plotly_events(
361
+ fig, click_event=True, hover_event=False)
362
+ with col3:
363
+ try:
364
+ date2 = pd.Timestamp(selected_points[0]['x']).strftime('%Y%m%d')
365
+ data2 = png_data(date2)
366
+ m3 = map_folium(data2, gdf)
367
+ st.header(f'{var} on {pd.Timestamp(date2).strftime("%D")}')
368
+ st_folium(m3, height=300)
369
+ except:
370
+ pass
371
+
372
+ st.markdown(""" <style>
373
+ #MainMenu {visibility: hidden;}
374
+ footer {visibility: hidden;}
375
+ </style> """, unsafe_allow_html=True)
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ folium==0.12.1
2
+ geopandas==0.10.2
3
+ geopy==2.2.0
4
+ joblib==1.1.0
5
+ numpy==1.21.5
6
+ pandas==1.4.2
7
+ plotly==5.7.0
8
+ rasterio==1.2.10
9
+ requests==2.27.1
10
+ rioxarray==0.12.2
11
+ scikit_image==0.19.2
12
+ streamlit==1.4.0
13
+ streamlit_folium==0.6.15
14
+ streamlit_plotly_events==0.0.6