-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
1620 lines (1410 loc) · 68.6 KB
/
app.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
"""
This is the main script for the Radar Simulator application. It is a Dash application that
allows users to simulate radar operations, including the generation of radar data, placefiles, and
hodographs. The application is designed to mimic the behavior of a radar system over a
specified period, starting from a predefined date and time. It allows for the simulation of
radar data generation, including the handling of time shifts and geographical coordinates.
"""
# from flask import Flask, render_template
import os
import shutil
import zipfile
#import gzip
import re
import subprocess
from pathlib import Path
from glob import glob
import time
from datetime import datetime, timedelta, timezone
import calendar
import math
import json
import logging
import mimetypes
import signal
import io
import base64
#import smtplib
#from email.mime.text import MIMEText
#from email.mime.multipart import MIMEMultipart
import psutil
import pytz
import pandas as pd
# from time import sleep
from dash import Dash, html, Input, Output, dcc, ctx, State # , callback
from dash.exceptions import PreventUpdate
# from dash import diskcache, DiskcacheManager, CeleryManager
# from uuid import uuid4
# import diskcache
import numpy as np
from botocore.client import Config
# bootstrap is what helps styling for a better presentation
import dash_bootstrap_components as dbc
import config
from config import app
import layout_components as lc
from scripts.obs_placefile import Mesowest
from scripts.Nexrad import NexradDownloader
from scripts.munger import Munger
from scripts.update_dir_list import UpdateDirList
from scripts.update_hodo_page import UpdateHodoHTML
from scripts.update_placefiles import UpdatePlacefiles
from scripts.nse import Nse
import utils
mimetypes.add_type("text/plain", ".cfg", True)
mimetypes.add_type("text/plain", ".list", True)
# Earth radius (km)
R = 6_378_137
# Regular expressions. First one finds lat/lon pairs, second finds the timestamps.
LAT_LON_REGEX = "[0-9]{1,2}.[0-9]{1,100},[ ]{0,1}[|\\s-][0-9]{1,3}.[0-9]{1,100}"
TIME_REGEX = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z"
"""
Idea is to move all of these functions to some other utility file within the main dir
to get them out of the app.
"""
def create_logfile(LOG_DIR):
"""
Generate the main logfile for the download and processing scripts.
"""
logging.basicConfig(
filename=f'{LOG_DIR}/scripts.txt', # Log file location
# Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
level=logging.INFO,
format='%(levelname)s %(asctime)s :: %(message)s',
datefmt="%Y-%m-%d %H:%M:%S"
)
def shift_placefiles(PLACEFILES_DIR, sim_times, radar_info) -> None:
"""
# While the _shifted placefiles should be purged for each run, just ensure we're
# only querying the "original" placefiles to shift (exclude any with _shifted.txt)
"""
filenames = glob(f"{PLACEFILES_DIR}/*.txt")
filenames = [x for x in filenames if "shifted" not in x]
for file_ in filenames:
outfilename = f"{file_[0:file_.index('.txt')]}_shifted.txt"
outfile = open(outfilename, 'w', encoding='utf-8')
with open(file_, 'r', encoding='utf-8') as f:
data = f.readlines()
try:
for line in data:
new_line = line
if sim_times['simulation_seconds_shift'] is not None and \
any(x in line for x in ['Valid', 'TimeRange', 'Time']):
new_line = shift_time(
line, sim_times['simulation_seconds_shift'])
# Shift this line in space. Only perform if both an original and
# transpose radar have been specified.
if radar_info['new_radar'] != 'None' and radar_info['radar'] is not None:
regex = re.findall(LAT_LON_REGEX, line)
if len(regex) > 0:
idx = regex[0].index(',')
plat, plon = float(regex[0][0:idx]), float(regex[0][idx+1:])
lat_out, lon_out = move_point(plat, plon, radar_info['lat'],
radar_info['lon'],
radar_info['new_lat'],
radar_info['new_lon'])
new_line = line.replace(regex[0], f"{lat_out}, {lon_out}")
outfile.write(new_line)
except (IOError, ValueError, KeyError) as e:
outfile.truncate(0)
outfile.write(f"Errors shifting this placefile: {e}")
outfile.close()
def shift_time(line: str, simulation_seconds_shift: int) -> str:
"""
Shifts the time-associated lines in a placefile.
These look for 'Valid' and 'TimeRange'.
"""
simulation_time_shift = timedelta(seconds=simulation_seconds_shift)
new_line = line
if 'Valid:' in line:
idx = line.find('Valid:')
# Leave off \n character
valid_timestring = line[idx+len('Valid:')+1:-1]
dt = datetime.strptime(valid_timestring, '%H:%MZ %a %b %d %Y')
new_validstring = datetime.strftime(dt + simulation_time_shift,
'%H:%MZ %a %b %d %Y')
new_line = line.replace(valid_timestring, new_validstring)
if 'TimeRange' in line:
regex = re.findall(TIME_REGEX, line)
dt = datetime.strptime(regex[0], '%Y-%m-%dT%H:%M:%SZ')
new_datestring_1 = datetime.strftime(dt + simulation_time_shift,
'%Y-%m-%dT%H:%M:%SZ')
dt = datetime.strptime(regex[1], '%Y-%m-%dT%H:%M:%SZ')
new_datestring_2 = datetime.strftime(dt + simulation_time_shift,
'%Y-%m-%dT%H:%M:%SZ')
new_line = line.replace(f"{regex[0]} {regex[1]}",
f"{new_datestring_1} {new_datestring_2}")
# For LSR placefiles
if 'LSR Time' in line:
regex = re.findall(TIME_REGEX, line)
dt = datetime.strptime(regex[0], '%Y-%m-%dT%H:%M:%SZ')
new_datestring = datetime.strftime(dt + simulation_time_shift,
'%Y-%m-%dT%H:%M:%SZ')
new_line = line.replace(regex[0], new_datestring)
return new_line
def move_point(plat, plon, lat, lon, new_radar_lat, new_radar_lon):
"""
Shift placefiles to a different radar site. Maintains the original azimuth and range
from a specified RDA and applies it to a new radar location.
Parameters:
-----------
plat: float
Original placefile latitude
plon: float
Original palcefile longitude
lat and lon is the lat/lon pair for the original radar
new_lat and new_lon is for the transposed radar. These values are set in
the transpose_radar function after a user makes a selection in the
new_radar_selection dropdown.
"""
def _clamp(n, minimum, maximum):
"""
Helper function to make sure we're not taking the square root of a negative
number during the calculation of `c` below.
"""
return max(min(maximum, n), minimum)
# Compute the initial distance from the original radar location
phi1, phi2 = math.radians(lat), math.radians(plat)
d_phi = math.radians(plat - lat)
d_lambda = math.radians(plon - lon)
a = math.sin(d_phi/2)**2 + (math.cos(phi1) *
math.cos(phi2) * math.sin(d_lambda/2)**2)
a = _clamp(a, 0, a)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = R * c
# Compute the bearing
y = math.sin(d_lambda) * math.cos(phi2)
x = (math.cos(phi1) * math.sin(phi2)) - (math.sin(phi1) * math.cos(phi2) *
math.cos(d_lambda))
theta = math.atan2(y, x)
bearing = (math.degrees(theta) + 360) % 360
# Apply this distance and bearing to the new radar location
phi_new, lambda_new = math.radians(
new_radar_lat), math.radians(new_radar_lon)
phi_out = math.asin((math.sin(phi_new) * math.cos(d/R)) + (math.cos(phi_new) *
math.sin(d/R) * math.cos(math.radians(bearing))))
lambda_out = lambda_new + math.atan2(math.sin(math.radians(bearing)) *
math.sin(d/R) * math.cos(phi_new),
math.cos(d/R) - math.sin(phi_new) * math.sin(phi_out))
return math.degrees(phi_out), math.degrees(lambda_out)
def copy_grlevel2_cfg_file(cfg) -> None:
"""
Ensures a grlevel2.cfg file is copied into the polling directory.
This file is required for GR2Analyst to poll for radar data.
"""
source = f"{cfg['BASE_DIR']}/grlevel2.cfg"
destination = f"{cfg['POLLING_DIR']}/grlevel2.cfg"
try:
shutil.copyfile(source, destination)
except (FileNotFoundError, PermissionError) as e:
print(f"Error copying {source} to {destination}: {e}")
def remove_files_and_dirs(cfg) -> None:
"""
Cleans up files and directories from the previous simulation so these datasets
are not included in the current simulation.
"""
dirs = [cfg['RADAR_DIR'], cfg['POLLING_DIR'], cfg['HODOGRAPHS_DIR'], cfg['MODEL_DIR'],
cfg['PLACEFILES_DIR'], cfg['USER_DOWNLOADS_DIR']]
for directory in dirs:
for root, dirs, files in os.walk(directory, topdown=False):
for name in files:
if name != 'grlevel2.cfg':
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
def remove_munged_radar_files(cfg) -> None:
"""
Removes uncompressed and 'munged' radar files within the /data/xx/radar directory
after the pre-processing scripts have completed. These files are no longer needed
as the appropriate files have been exported to the /assets/xx/polling directory.
copies the original files to the user downloads directory so they can be
downloaded by the user if desired.
"""
regex_pattern = r'^(.{4})(\d{8})_(\d{6})$'
raw_pattern = r'^(.{4})(\d{8})_(\d{6})_(V\d{2})$'
for root, _, files in os.walk(cfg['RADAR_DIR']):
if Path(root).name == 'downloads':
for name in files:
thisfile = os.path.join(root, name)
matched = re.match(regex_pattern, name)
raw_matched = re.match(raw_pattern, name)
if matched or '.uncompressed' in name:
os.remove(thisfile)
if raw_matched:
shutil.copy2(thisfile, cfg['USER_DOWNLOADS_DIR'])
def zip_downloadable_radar_files(cfg) -> None:
"""
After all radar files have been processed and are ready for download, this function
zips up the radar files already in the user downloads directory.
"""
shutil.make_archive('radar_files', 'zip', cfg['USER_DOWNLOADS_DIR'])
shutil.move('radar_files.zip', f"{cfg['USER_DOWNLOADS_DIR']}/original_radar_files.zip")
def zip_original_placefiles(cfg) -> None:
"""
After the placefiles have been shifted and are ready for download, this function
zips up the original placefiles.
"""
zip_filepath = f"{cfg['USER_DOWNLOADS_DIR']}/original_placefiles.zip"
with zipfile.ZipFile(zip_filepath, 'w') as zipf:
for root, _, files in os.walk(cfg['PLACEFILES_DIR']):
for file in files:
if 'txt' in file and 'updated' not in file and 'shifted' not in file:
file_path = os.path.join(root, file)
zipf.write(file_path, file)
def date_time_string(dt) -> str:
"""
Converts a datetime object to a string.
"""
return datetime.strftime(dt, "%Y-%m-%d %H:%M")
def make_simulation_times(event_start_time, event_duration) -> dict:
"""
playback_end_time: datetime object
- set to current time then rounded down to nearest 15 min.
playback_start_time: datetime object
- the time the simulation starts.
- playback_end_time minus the event duration
- This is "recent enough" for GR2Analyst to poll data
playback_timer: datetime object
- the "current" displaced realtime during the playback
event_start_time: datetime object
- the historical time the actual event started.
- based on user inputs of the event start time
simulation_time_shift: timedelta object
the difference between the playback start time and the event start time
simulation_seconds_shift: int
the difference between the playback start time and the event start time in seconds
Variables ending with "_str" are the string representations of the datetime objects
"""
now = datetime.now(pytz.utc).replace(second=0, microsecond=0)
playback_end = now - timedelta(minutes=now.minute % 15)
playback_end_str = date_time_string(playback_end)
playback_start = playback_end - timedelta(minutes=event_duration)
playback_start_str = date_time_string(playback_start)
# The playback clock is set to 10 minutes after the start of the simulation
playback_clock = playback_start + timedelta(seconds=600)
playback_clock_str = date_time_string(playback_clock)
# a timedelta object is not JSON serializable, so cannot be included in the output
# dictionary stored in the dcc.Store object. All references to simulation_time_shift
# will need to use the simulation_seconds_shift reference instead.
simulation_time_shift = playback_start - event_start_time
simulation_seconds_shift = round(simulation_time_shift.total_seconds())
event_start_str = date_time_string(event_start_time)
increment_list = []
for t in range(0, int(event_duration/5) + 1, 1):
new_time = playback_start + timedelta(seconds=t*300)
new_time_str = date_time_string(new_time)
increment_list.append(new_time_str)
playback_dropdown_dict = [
{'label': increment, 'value': increment} for increment in increment_list]
sim_times = {
'event_start_str': event_start_str,
'simulation_seconds_shift': simulation_seconds_shift,
'playback_start_str': playback_start_str,
'playback_start': playback_start,
'playback_end_str': playback_end_str,
'playback_end': playback_end,
'playback_clock_str': playback_clock_str,
'playback_clock': playback_clock,
'playback_dropdown_dict': playback_dropdown_dict,
'event_duration': event_duration
}
return sim_times
def create_radar_dict(sa) -> dict:
"""
Creates dictionary of radar sites and their metadata to be used in the simulation.
"""
for _i, radar in enumerate(sa['radar_list']):
sa['lat'] = lc.df[lc.df['radar'] == radar]['lat'].values[0]
sa['lon'] = lc.df[lc.df['radar'] == radar]['lon'].values[0]
asos_one = lc.df[lc.df['radar'] == radar]['asos_one'].values[0]
asos_two = lc.df[lc.df['radar'] == radar]['asos_two'].values[0]
sa['radar_dict'][radar.upper()] = {'lat': sa['lat'], 'lon': sa['lon'],
'asos_one': asos_one, 'asos_two': asos_two,
'radar': radar.upper(), 'file_list': []}
################################################################################################
# ----------------------------- Build the layout ---------------------------------------------
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
playback_time_options = dbc.Col(html.Div([
dcc.Dropdown(options={'label': 'Sim not started', 'value': ''}, id='change_time',
disabled=True, clearable=False)]))
playback_time_options_col = dbc.Col(html.Div([lc.change_playback_time_label, lc.spacer_mini,
playback_time_options]))
playback_controls = dbc.Container(
html.Div([dbc.Row([lc.playback_speed_col, lc.playback_status_box,
playback_time_options_col])]))
simulation_playback_section = dbc.Container(
dbc.Container(
html.Div([lc.playback_banner, lc.spacer, lc.playback_buttons_container, lc.spacer,
lc.playback_timer_readout_container, lc.spacer,
playback_controls, lc.spacer_mini,
]), style=lc.section_box_pad))
@app.callback(
Output('dynamic_container', 'children'),
Output('layout_has_initialized', 'data'),
# Input('container_init', 'n_intervals'),
State('layout_has_initialized', 'data'),
State('dynamic_container', 'children'),
Input('configs', 'data')
)
def generate_layout(layout_has_initialized, children, configs):
"""
Dynamically generate the layout, which was started in the config file to set up
the unique session id. This callback should only be executed once at page load in.
Thereafter, layout_has_initialized will be set to True
"""
if not layout_has_initialized['added'] and configs is not None:
if children is None:
children = []
# Initialize configurable variables for load in
event_start_year = 2024
event_start_month = 5
event_start_day = 7
event_start_hour = 21
event_start_minute = 30
event_duration = 60
playback_speed = 1.0
number_of_radars = 1
radar_list = []
radar_dict = {}
radar = None
new_radar = 'None'
lat = None
lon = None
new_lat = None
new_lon = None
radar_files_dict = {}
#################################################
monitor_store = {}
monitor_store['radar_dl_completion'] = 0
monitor_store['hodograph_completion'] = 0
monitor_store['munger_completion'] = 0
monitor_store['placefile_status_string'] = ""
monitor_store['model_list'] = []
monitor_store['model_warning'] = ""
monitor_store['scripts_previously_running'] = False
radar_info = {
'number_of_radars': number_of_radars,
'radar_list': radar_list,
'radar_dict': radar_dict,
'radar': radar,
'new_radar': new_radar,
'lat': lat,
'lon': lon,
'new_lat': new_lat,
'new_lon': new_lon,
'radar_files_dict': radar_files_dict
}
# Settings for date dropdowns moved here to avoid specifying different values in
# the layout
now = datetime.now(pytz.utc)
sim_year_section = dbc.Col(html.Div([lc.step_year, dcc.Dropdown(
np.arange(1992, now.year +
1), event_start_year,
id='start_year', clearable=False),]))
sim_month_section = dbc.Col(html.Div([lc.step_month, dcc.Dropdown(
np.arange(1, 13), event_start_month,
id='start_month', clearable=False),]))
sim_day_selection = dbc.Col(html.Div([lc.step_day, dcc.Dropdown(
np.arange(1, 31), event_start_day,
id='start_day', clearable=False)]))
sim_hour_section = dbc.Col(html.Div([lc.step_hour, dcc.Dropdown(
np.arange(0, 24), event_start_hour,
id='start_hour', clearable=False),]))
sim_minute_section = dbc.Col(html.Div([lc.step_minute, dcc.Dropdown(
[0, 15, 30, 45], event_start_minute,
id='start_minute', clearable=False),]))
sim_duration_section = dbc.Col(html.Div([lc.step_duration, dcc.Dropdown(
np.arange(0, 180, 15), event_duration,
id='duration', clearable=False),]))
polling_section = html.Div(
[
dbc.Row([
dbc.Col(dbc.ListGroupItem("Polling address for GR2Analyst"),
style=lc.polling_address_label, width=4),
dbc.Col(dbc.ListGroupItem(f"{configs['LINK_BASE']}/polling",
href="", target="_blank", style={'color': '#555555'}, id="polling_link"),
style=lc.polling_link, width=8)
])
])
links_section = dbc.Container(dbc.Container(dbc.Container(html.Div(
[lc.placefiles_banner, lc.spacer, polling_section,
lc.spacer,
dbc.Row(
[
dbc.Col("Facilitator Links", style=lc.group_header_style, width=6),
], style={"display": "flex", "flexWrap": "wrap"}),
lc.spacer_mini,lc.spacer_mini,
dbc.Row(
[dbc.Col(dbc.ListGroupItem("** SHAREABLE LINKS PAGE **",
href=f"{configs['LINK_BASE']}/links.html",
target="_blank"),style={'color':lc.graphics_c},width=4),
dbc.Col(dbc.ListGroupItem("Facilitator Events Guide (html)",
href=f"{configs['LINK_BASE']}/events.html",
target="_blank"),style={'color':lc.graphics_c},width=4),
dbc.Col(dbc.ListGroupItem("Facilitator Events Guide (txt)",
href=f"{configs['LINK_BASE']}/events.txt",
target="_blank"), style={'color':lc.graphics_c},width=4),
],
style={"display": "flex", "flexWrap": "wrap"}
),
dbc.Row(
[dbc.Col(dbc.ListGroupItem("Download Original Radar Files",
href=f"{configs['LINK_BASE']}/downloads/original_radar_files.zip"),
style={'color':lc.graphics_c},width=4),
dbc.Col(dbc.ListGroupItem("Download Original Unshifted Placefiles",
href=f"{configs['LINK_BASE']}/downloads/original_placefiles.zip"),
style={'color':lc.graphics_c},width=4),
dbc.Col(dbc.ListGroupItem("Hodograph Creation Instructions",
href="https://docs.google.com/document/d/1pRT0l27Zo3WusVnGS-nvJiQXcW3AkyJ91RH8gISqoDQ/edit", target="_blank"),
style={'color':lc.graphics_c},width=4),
],
style={"display": "flex", "flexWrap": "wrap"}
),
]
))))
full_links_section = dbc.Container(
dbc.Container(
html.Div([
links_section
]), id="placefiles_section", style=lc.section_box_pad))
new_items = dbc.Container([
dcc.Interval(id='playback_timer', disabled=True, interval=15*1000),
# dcc.Store(id='tradar'),
dcc.Store(id='dummy'),
dcc.Store(id='playback_running_store', data=False),
dcc.Store(id='playback_start_store'), # might be unused
dcc.Store(id='playback_end_store'), # might be unused
dcc.Store(id='playback_clock_store'), # might be unused
dcc.Store(id='radar_info', data=radar_info),
dcc.Store(id='sim_times'),
dcc.Store(id='playback_speed_store', data=playback_speed),
dcc.Store(id='playback_specs'),
# For app/script monitoring
dcc.Interval(id='directory_monitor', interval=2000),
dcc.Store(id='monitor_store', data=monitor_store),
lc.top_section, lc.top_banner,
dbc.Container([
dbc.Container([
html.Div([html.Div([lc.step_select_event_time_section, lc.spacer,
dbc.Row([
sim_year_section, sim_month_section, sim_day_selection,
sim_hour_section, sim_minute_section,
sim_duration_section, lc.spacer,
lc.step_time_confirm])], style={'padding': '1em'}),
], style=lc.section_box_pad)])
]), lc.spacer,lc.spacer_mini,
lc.full_radar_select_section, lc.spacer_mini,
lc.map_section,
lc.full_transpose_section,
lc.spacer,
lc.full_upload_section, lc.spacer,
lc.scripts_button,
lc.status_section,
lc.spacer, #lc.toggle_placefiles_btn, lc.spacer_mini,
full_links_section, lc.spacer,lc.spacer_mini,
simulation_playback_section,
lc.radar_id, lc.bottom_section
])
# Append the new component to the current list of children
children = list(children)
children.append(new_items)
layout_has_initialized['added'] = True
create_logfile(configs['LOG_DIR'])
return children, layout_has_initialized
return children, layout_has_initialized
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
################################################################################################
# ----------------------------- Radar map section ---------------------------------------------
################################################################################################
@app.callback(
Output('show_radar_selection_feedback', 'children'),
Output('confirm_radars_btn', 'children'),
Output('confirm_radars_btn', 'disabled'),
Output('radar_info', 'data'),
[Input('radar_quantity', 'value'),
Input('graph', 'clickData'),
State('radar_info', 'data')],
prevent_initial_call=True
)
def display_click_data(quant_str: str, click_data: dict, radar_info: dict):
"""
Any time a radar site is clicked,
this function will trigger and update the radar list.
"""
# initially have to make radar selections and can't finalize
select_action = 'Make'
btn_deactivated = True
triggered_id = ctx.triggered_id
radar_info['number_of_radars'] = int(quant_str[0:1])
if triggered_id == 'radar_quantity':
radar_info['number_of_radars'] = int(quant_str[0:1])
radar_info['radar_list'] = []
radar_info['radar_dict'] = {}
return f'Use map to select {quant_str}', f'{select_action} selections', True, radar_info
try:
radar = click_data['points'][0]['customdata']
except (KeyError, IndexError, TypeError):
return 'No radar selected ...', f'{select_action} selections', True, radar_info
if radar not in radar_info['radar_list']:
radar_info['radar_list'].append(radar)
if len(radar_info['radar_list']) > radar_info['number_of_radars']:
radar_info['radar_list'] = radar_info['radar_list'][-radar_info['number_of_radars']:]
if len(radar_info['radar_list']) == radar_info['number_of_radars']:
select_action = 'Finalize'
btn_deactivated = False
radar_info['radar'] = radar
listed_radars = ', '.join(radar_info['radar_list'])
return listed_radars, f'{select_action} selections', btn_deactivated, radar_info
@app.callback(
[Output('graph-container', 'style'),
Output('map_btn', 'children')],
Input('map_btn', 'n_clicks'),
Input('confirm_radars_btn', 'n_clicks'))
def toggle_map_display(map_n, confirm_n) -> dict:
"""
based on button click, show or hide the map by returning a css style dictionary
to modify the associated html element
"""
total_clicks = map_n + confirm_n
if total_clicks % 2 == 0:
return {'display': 'none'}, 'Show Radar Map'
return lc.map_section_style, 'Hide Radar Map'
@app.callback(
[Output('full_transpose_section_id', 'style'),
Output('skip_transpose_id', 'style'),
Output('allow_transpose_id', 'style'),
Output('run_scripts_btn', 'disabled')
], Input('confirm_radars_btn', 'n_clicks'),
Input('radar_quantity', 'value'),
State('radar_info', 'data'),
prevent_initial_call=True)
def finalize_radar_selections(clicks: int, _quant_str: str, radar_info: dict) -> dict:
"""
This will display the transpose section on the page if the user has selected a single radar.
"""
disp_none = {'display': 'none'}
# script_style = {'padding': '1em', 'vertical-align': 'middle'}
triggered_id = ctx.triggered_id
if triggered_id == 'radar_quantity':
return disp_none, disp_none, disp_none, True
if clicks > 0:
if radar_info['number_of_radars'] == 1 and len(radar_info['radar_list']) == 1:
return lc.section_box_pad, disp_none, {'display': 'block'}, False
return lc.section_box_pad, {'display': 'block'}, disp_none, False
################################################################################################
# ----------------------------- Transpose radar section ---------------------------------------
################################################################################################
@app.callback(
Output('radar_info', 'data', allow_duplicate=True),
[Input('new_radar_selection', 'value'),
Input('radar_quantity', 'value'),
State('radar_info', 'data')],
prevent_initial_call=True
)
def transpose_radar(value, radar_quantity, radar_info):
"""
If a user switches from a selection BACK to "None", without this, the application
will not update new_radar to None. Instead, it'll be the previous selection.
Since we always evaluate "value" after every user selection, always set new_radar
initially to None.
"""
radar_info['new_radar'] = 'None'
radar_info['new_lat'] = None
radar_info['new_lon'] = None
radar_info['number_of_radars'] = int(radar_quantity[0:1])
if value != 'None' and radar_info['number_of_radars'] == 1:
new_radar = value
radar_info['new_radar'] = new_radar
radar_info['new_lat'] = lc.df[lc.df['radar']
== new_radar]['lat'].values[0]
radar_info['new_lon'] = lc.df[lc.df['radar']
== new_radar]['lon'].values[0]
return radar_info
################################################################################################
# ----------------------------- Run Scripts button --------------------------------------------
################################################################################################
def query_radar_files(cfg, radar_info, sim_times):
"""
Get the radar files from the AWS bucket. This is a preliminary step to build the progess bar.
"""
# Need to reset the expected files dictionary with each call. Otherwise, if a user
# cancels a request, the previously-requested files will still be in the dictionary.
# radar_files_dict = {}
radar_info['radar_files_dict'] = {}
for _r, radar in enumerate(radar_info['radar_list']):
radar = radar.upper()
args = [radar, str(sim_times['event_start_str']), str(sim_times['event_duration']),
str(False), cfg['RADAR_DIR']]
# logging.info(f"{cfg['SESSION_ID']} :: Passing {args} to Nexrad.py")
results = utils.exec_script(
Path(cfg['NEXRAD_SCRIPT_PATH']), args, cfg['SESSION_ID'])
if results['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
logging.warning(
f"{cfg['SESSION_ID']} :: User cancelled query_radar_files()")
break
json_data = results['stdout'].decode('utf-8')
logging.info(
f"{cfg['SESSION_ID']} :: Nexrad.py returned with {json_data}")
radar_info['radar_files_dict'].update(json.loads(json_data))
# Write radar metadata for this simulation to a text file. More complicated updating the
# dcc.Store object with this information since this function isn't a callback.
with open(f'{cfg['RADAR_DIR']}/radarinfo.json', 'w', encoding='utf-8') as json_file:
json.dump(radar_info['radar_files_dict'], json_file)
return results
def call_function(func, *args, **kwargs):
# For the main script calls
if len(args) > 2 and func.__name__ != 'query_radar_files':
logging.info(f"Sending {args[1]} to {args[0]}")
result = func(*args, **kwargs)
if len(result['stderr']) > 0:
logging.error(result['stderr'].decode('utf-8'))
if 'exception' in result:
logging.error(f"Exception {result['exception']} occurred in {
func.__name__}"
)
return result
def run_with_cancel_button(cfg, sim_times, radar_info):
"""
This version of the script-launcher trying to work in cancel button
"""
UpdateHodoHTML('None', cfg['HODOGRAPHS_DIR'], cfg['HODOGRAPHS_PAGE'])
# writes a black event_times.txt file to the assets directory
args = [str(sim_times['simulation_seconds_shift']), 'None', cfg['RADAR_DIR'],
cfg['EVENTS_HTML_PAGE'], cfg['EVENTS_TEXT_FILE']]
res = call_function(utils.exec_script, Path(cfg['EVENT_TIMES_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# based on list of selected radars, create a dictionary of radar metadata
try:
create_radar_dict(radar_info)
copy_grlevel2_cfg_file(cfg)
except (IOError, ValueError, KeyError) as e:
logging.exception(
"Error creating radar dict or config file: %s",e,exc_info=True)
log_string = (
f"\n"
f"=========================Simulation Settings========================\n"
f"Session ID: {cfg['SESSION_ID']}\n"
f"{sim_times}\n"
f"{radar_info}\n"
f"====================================================================\n"
)
logging.info(log_string)
if len(radar_info['radar_list']) > 0:
# Create initial dictionary of expected radar files.
# TO DO: report back issues with radar downloads (e.g. 0 files found)
res = call_function(query_radar_files, cfg, radar_info, sim_times)
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# Radar downloading and mungering steps
for _r, radar in enumerate(radar_info['radar_list']):
radar = radar.upper()
try:
if radar_info['new_radar'] == 'None':
new_radar = radar
else:
new_radar = radar_info['new_radar'].upper()
except (IOError, ValueError, KeyError) as e:
logging.exception("Error defining new radar: %s",e,exc_info=True)
# --------- Links Page -----------------------------------------------------
#cfg['LINK_BASE'], cfg['LINKS_HTML_PAGE']
args = [cfg['LINK_BASE'], cfg['LINKS_HTML_PAGE']]
res = call_function(utils.exec_script, Path(cfg['LINKS_PAGE_SCRIPT_PATH']),
args, cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# Radar download
args = [radar, str(sim_times['event_start_str']),
str(sim_times['event_duration']), str(True), cfg['RADAR_DIR']]
res = call_function(utils.exec_script, Path(cfg['NEXRAD_SCRIPT_PATH']),
args, cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# Munger
args = [radar, str(sim_times['playback_start_str']),
str(sim_times['event_duration']),
str(sim_times['simulation_seconds_shift']
), cfg['RADAR_DIR'],
cfg['POLLING_DIR'], cfg['USER_DOWNLOADS_DIR'], cfg['L2MUNGER_FILEPATH'], cfg['DEBZ_FILEPATH'],
new_radar]
res = call_function(utils.exec_script, Path(cfg['MUNGER_SCRIPT_FILEPATH']),
args, cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# this gives the user some radar data to poll while other scripts are running
try:
UpdateDirList(new_radar, 'None',
cfg['POLLING_DIR'], initialize=True)
except (IOError, ValueError, KeyError) as e:
print(f"Error with UpdateDirList: {e}")
logging.exception("Error with UpdateDirList: %s",e, exc_info=True)
# Delete the uncompressed/munged radar files from the data directory
try:
remove_munged_radar_files(cfg)
except KeyError as e:
logging.exception("Error removing munged radar files ", exc_info=True)
# --------- LSR Placefiles -----------------------------------------------------
# Not monitored currently due to how quick this executes
# center lat, center lon, event start, duration, LSR csv source dir, placefile output dir
args = [str(radar_info['lat']), str(radar_info['lon']),
str(sim_times['event_start_str']), str(sim_times['event_duration']),
cfg['DATA_DIR'], cfg['PLACEFILES_DIR']]
res = call_function(utils.exec_script, Path(cfg['LSR_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# --------- event times text file ----------------------------------------------
# -- seconds_shift, csv_dir, radar_dir, html_file, text_file -------------------
args = [str(sim_times['simulation_seconds_shift']), cfg['DATA_DIR'], cfg['RADAR_DIR'],
cfg['EVENTS_HTML_PAGE'], cfg['EVENTS_TEXT_FILE']]
res = call_function(utils.exec_script, Path(cfg['EVENT_TIMES_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# Now that all radar files are in assets/{}/downloads dir, zip them up
try:
zip_downloadable_radar_files(cfg)
except KeyError as e:
logging.exception("Error zipping radar files ", exc_info=True)
# --------- Surface observations placefiles -------------------------------------
# center lat, center lon, start timestr, duration, placefile output directory
args = [str(radar_info['lat']), str(radar_info['lon']),
sim_times['event_start_str'], str(sim_times['event_duration']),
cfg['PLACEFILES_DIR']]
res = call_function(utils.exec_script, Path(cfg['OBS_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# --------- ProbSevere download -------------------------------------------------
args = [str(sim_times['event_start_str']), str(sim_times['event_duration']),
cfg['PROBSEVERE_DIR']]
res = call_function(utils.exec_script, Path(cfg['PROBSEVERE_DOWNLOAD_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# --------- ProbSevere placefiles -----------------------------------------------
# -- center lat, center lon, data source directory, placefile output directory --
args = [str(radar_info['lat']), str(radar_info['lon']),cfg['PROBSEVERE_DIR'],
cfg['PLACEFILES_DIR']]
res = call_function(utils.exec_script, Path(cfg['PROBSEVERE_PLACEFILE_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# --------- NSE placefiles ------------------------------------------------------
args = [str(sim_times['event_start_str']), str(sim_times['event_duration']),
cfg['SCRIPTS_DIR'], cfg['DATA_DIR'], cfg['PLACEFILES_DIR']]
res = call_function(utils.exec_script, Path(cfg['NSE_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
# Now that all original placefiles should be available, zip them up
try:
zip_original_placefiles(cfg)
except KeyError as e:
logging.exception("Error zipping original placefiles ", exc_info=True)
# There always is a timeshift with a simulation, so this script needs to
# execute every time, even if a user doesn't select a radar to transpose to.
logging.info("Entering function run_transpose_script")
run_transpose_script(cfg['PLACEFILES_DIR'], sim_times, radar_info)
# --------- Hodographs ---------------------------------------------------------
for radar, data in radar_info['radar_dict'].items():
try:
asos_one = data['asos_one']
asos_two = data['asos_two']
except KeyError as e:
logging.exception("Error getting radar metadata: ", exc_info=True)
# Execute hodograph script
args = [radar, radar_info['new_radar'], asos_one, asos_two,
str(sim_times['simulation_seconds_shift']), cfg['RADAR_DIR'],
cfg['HODOGRAPHS_DIR']]
res = call_function(utils.exec_script, Path(cfg['HODO_SCRIPT_PATH']), args,
cfg['SESSION_ID'])
if res['returncode'] in [signal.SIGTERM, -1*signal.SIGTERM]:
return
try:
UpdateHodoHTML(
'None', cfg['HODOGRAPHS_DIR'], cfg['HODOGRAPHS_PAGE'])
except (IOError, ValueError, KeyError) as e:
print("Error updating hodo html: ", e)
logging.exception("Error updating hodo html: %s",e, exc_info=True)
# def send_email(subject, body, to_email):
# from_email = "[email protected]"
# from_password = "your_password"
# msg = MIMEMultipart()
# msg['From'] = from_email
# msg['To'] = to_email
# msg['Subject'] = subject
# msg.attach(MIMEText(body, 'plain'))
# try:
# server = smtplib.SMTP('smtp.example.com', 587)
# server.starttls()
# server.login(from_email, from_password)
# text = msg.as_string()
# server.sendmail(from_email, to_email, text)
# server.quit()
# print("Email sent successfully")
# except (smtplib.SMTPException, ConnectionError) as e:
# print(f"Failed to send email: {e}")
@app.callback(
Output('show_script_progress', 'children', allow_duplicate=True),
[Input('run_scripts_btn', 'n_clicks'),
State('configs', 'data'),
State('sim_times', 'data'),
State('radar_info', 'data')],
prevent_initial_call=True,
running=[
(Output('start_year', 'disabled'), True, False),
(Output('start_month', 'disabled'), True, False),
(Output('start_day', 'disabled'), True, False),
(Output('start_hour', 'disabled'), True, False),