-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather.py
1769 lines (1725 loc) · 59.8 KB
/
weather.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 datetime
from random import sample
from pathos.multiprocessing import ThreadingPool
from shutil import copy, rmtree
import os
import utm
import argparse
import pandas as pd
import sys
root = os.getcwd()
simulations = os.path.join(root, "simulations")
n_stations = 1
def read_arguments():
parser = argparse.ArgumentParser(description="Input data")
parser.add_argument(
"-M",
"--mode",
default="reanalysis",
help="Possible options: reanalysis, forecast. If reanalysis, either ERA5 or WST options should be on. \n "
"If forecast, GFS data will be downloaded and processed",
)
parser.add_argument(
"-S",
"--start_date",
default=999,
help="Start date of the sampling period. Format: DD/MM/YYYY",
)
parser.add_argument(
"-E",
"--end_date",
default=999,
help="Start date of the sampling period. Format: DD/MM/YYYY",
)
parser.add_argument(
"-SY",
"--sampled_years",
default='',
help="Specify years to sample from the time interval",
)
parser.add_argument(
"-SM",
"--sampled_months",
default='',
help="Specify months to sample from the time interval",
)
parser.add_argument(
"-SD",
"--sampled_days",
default='',
help="Specify days to sample from the time interval",
)
parser.add_argument(
"-V",
"--volc",
default=999,
help="This is the volcano ID based on the Smithsonian Institute IDs",
)
parser.add_argument("-LAT", "--lat", default=999, help="Volcano latitude")
parser.add_argument("-LON", "--lon", default=999, help="Volcano longitude")
parser.add_argument("-EL", "--elev", default=999, help="Volcano elevation")
parser.add_argument("-NS", "--samples", default=1, help="Number of days to sample")
parser.add_argument(
"-ERA5",
"--ERA5",
default="False",
help="True: Use ERA5 reanalysis. False: Do not use ERA5 reanalysis",
)
parser.add_argument(
"-WST",
"--station",
default="False",
help="True: Use weather station data. False: Do not use weather station data",
)
parser.add_argument(
"-N",
"--nproc",
default=1,
help="Maximum number of allowed simultaneous processes",
)
parser.add_argument(
"-TD",
"--twodee",
default="off",
help="on or off, to prepare additional weather data files for Twodee.",
)
parser.add_argument(
"-DG", "--disgas", default="off", help="on or off, to run Disgas"
)
args = parser.parse_args()
mode = args.mode
start_date = args.start_date
end_date = args.end_date
sampled_years_in = args.sampled_years
sampled_months_in = args.sampled_months
sampled_days_in = args.sampled_days
volc_id = int(args.volc)
volc_lat = float(args.lat)
volc_lon = float(args.lon)
elevation = float(args.elev)
nsamples = int(args.samples)
ERA5_on = args.ERA5
weather_station_on = args.station
args = parser.parse_args()
nproc = args.nproc
twodee = args.twodee
disgas = args.disgas
mode = mode.lower()
if mode != "reanalysis" and mode != "forecast":
print("ERROR. Wrong value for variable -M --mode")
sys.exit()
if ERA5_on.lower() == "true":
ERA5_on = True
elif ERA5_on.lower() == "false":
ERA5_on = False
else:
print("ERROR. Wrong value for variable -ERA5 --ERA5")
sys.exit()
if weather_station_on.lower() == "true":
weather_station_on = True
elif weather_station_on.lower() == "false":
weather_station_on = False
else:
print("ERROR. Wrong value for variable --station")
sys.exit()
if mode == "reanalysis":
if not ERA5_on and not weather_station_on:
print(
"ERROR. Either ERA5 or weather station data should be activated in reanalysis mode"
)
sys.exit()
elif mode == "forecast":
if ERA5_on:
print(
"WARNING. ERA5 data cannot be used in forecast mode. Turning ERA5 off"
)
ERA5_on = False
if weather_station_on:
print(
"WARNING. Weather station data cannot be used in forecast mode. Turning weather stations off"
)
weather_station_on = False
if weather_station_on and ERA5_on:
print(
"ERROR. It is currently not possible to use both reanalysis and weather station data"
)
sys.exit()
if volc_lat == 999 and volc_lon == 999 and elevation == 999:
try:
try:
database = pd.read_excel(
"https://webapps.bgs.ac.uk/research/volcanoes/esp/volcanoExport.xlsx",
sheetname="volcanoes",
)
except TypeError:
database = pd.read_excel(
"https://webapps.bgs.ac.uk/research/volcanoes/esp/volcanoExport.xlsx",
sheet_name="volcanoes",
)
nrows = database.shape[0]
row = 0
while True:
if database["SMITHSONIAN_ID"][row] == volc_id:
elevation = database["ELEVATION_m"][row]
volc_lat = database["LATITUDE"][row]
volc_lon = database["LONGITUDE"][row]
break
else:
row += 1
if row >= nrows:
raise NameError('Volcano ID not found')
except NameError:
print("Unable to retrieve volcano information from the ESPs database "
"and no location information have been provided")
raise
sampled_days = []
sampled_months = []
sampled_years = []
if sampled_days_in != '':
sampled_days = sampled_days_in.split(',')
for day in sampled_days:
try:
datetime.datetime.strptime(day,'%d')
except ValueError:
print('ERROR. Please provide a valid entry for -SD --sampled_days')
sys.exit()
if sampled_months_in != '':
sampled_months = sampled_months_in.split(',')
for month in sampled_months:
try:
datetime.datetime.strptime(month, '%m')
except ValueError:
print('ERROR. Please provide a valid entry for -SM --sampled_months')
sys.exit()
if sampled_years_in != '':
sampled_years = sampled_years_in.split(',')
for year in sampled_years:
try:
datetime.datetime.strptime(year, '%Y')
except ValueError:
print('ERROR. Please provide a valid entry for -SY --sampled_years')
sys.exit()
try:
max_number_processes = int(nproc)
except ValueError:
print("Please provide a valid number for the maximum number of process")
sys.exit()
out_utm = utm.from_latlon(volc_lat, volc_lon)
easting = int(round(out_utm[0] / 1000))
northing = int(round(out_utm[1] / 1000))
try:
start = start_date.split("/")
stop = end_date.split("/")
D_start_s = start[0]
MO_start_s = start[1]
Y_start_s = start[2]
D_stop_s = stop[0]
MO_stop_s = stop[1]
Y_stop_s = stop[2]
analysis_start = Y_start_s + MO_start_s + D_start_s
analysis_stop = Y_stop_s + MO_stop_s + D_stop_s
time_start = datetime.datetime(int(Y_start_s), int(MO_start_s), int(D_start_s))
time_stop = datetime.datetime(int(Y_stop_s), int(MO_stop_s), int(D_stop_s))
except IndexError:
print("Unable to process start and end date")
print(
"Please ensure the dates are provided in the format DD/MM/YYYY (e.g. 23/06/2018)"
)
sys.exit()
if twodee.lower() == "on":
twodee_on = True
elif twodee.lower() == "off":
twodee_on = False
else:
print("Please provide a valid entry for the variable -TD --twodee")
sys.exit()
if disgas.lower() == "on":
disgas_on = True
elif disgas.lower() == "off":
disgas_on = False
else:
print("Please provide a valid entry for the variable -DG --disgas")
sys.exit()
return (
mode,
nsamples,
time_start,
time_stop,
analysis_start,
analysis_stop,
ERA5_on,
weather_station_on,
elevation,
volc_lat,
volc_lon,
easting,
northing,
max_number_processes,
twodee_on,
disgas_on,
sampled_years,
sampled_months,
sampled_days,
)
def extract_grib_data(folder, validity, wtfile_prof_step):
from math import atan2, pi
file = open(wtfile_prof_step, "r", encoding="utf-8", errors="surrogateescape")
records1 = []
records2 = []
nrecords = 0
for line in file:
nrecords += 1
records1.append(line.split(":"))
records2.append(line.split("val="))
u_tmp = []
v_tmp = []
hgt_tmp = []
t_tmp = []
u = []
v = []
t = []
wind = []
direction = []
hgt = []
i = 0
while i < nrecords:
if "mb" in records1[i][4] and " mb " not in records1[i][4]:
if records1[i][3] == "UGRD":
u_tmp.append(float(records2[i][1]))
elif records1[i][3] == "VGRD":
v_tmp.append(float(records2[i][1]))
elif records1[i][3] == "GP":
hgt_tmp.append(float(records2[i][1]) / 9.8066)
elif records1[i][3] == "HGT":
hgt_tmp.append(float(records2[i][1]))
elif records1[i][3] == "TMP":
t_tmp.append(float(records2[i][1]))
i += 1
j = 0
for i in range(len(u_tmp) - 1, -1, -1):
if hgt_tmp[i] > elevation:
hgt.append(hgt_tmp[i] - elevation)
u.append(u_tmp[i])
v.append(v_tmp[i])
t.append(t_tmp[i])
wind.append((u[j] ** 2 + v[j] ** 2) ** 0.5)
wind_dir_degrees = atan2(u[j], v[j]) * 180 / pi
direction.append(wind_dir_degrees + 180)
j += 1
if j > 19:
break
else:
continue
prof_file = os.path.join(folder, "profile_data_" + validity + ".txt")
wt_output = open(prof_file, "w", encoding="utf-8", errors="surrogateescape")
wt_output.write(
"HGT[m abg] U[m/s] V[m/s] WIND[m/s] WIND_DIR[deg] T[K]\n"
)
for i in range(j - 1, -1, -1):
wt_output.write(
"%8.2f %8.2f %10.2f %10.2f %10.2f %10.2f\n"
% (hgt[i], u[i], v[i], wind[i], direction[i], t[i])
)
wt_output.close()
gamma_pl = -(t[-1] - t[0]) / ((hgt[-1] - hgt[0]) / 1000)
return wind, direction, hgt, gamma_pl
def extract_grib_data_sl(folder, validity, wtfile_sl_location_step):
from math import atan2, pi
file = open(
wtfile_sl_location_step, "r", encoding="utf-8", errors="surrogateescape"
)
records1 = []
records2 = []
nrecords = 0
for line in file:
nrecords += 1
records1.append(line.split(":"))
records2.append(line.split("val="))
i = 0
if mode == "reanalysis":
while i < nrecords:
if records1[i][3] == "UGRD":
u = float(records2[i][1])
elif records1[i][3] == "VGRD":
v = float(records2[i][1])
elif records1[i][3] == "TMP":
t2m = float(records2[i][1])
elif records1[i][3] == "PRES":
pz0 = float(records2[i][1])
else:
tz0 = float(records2[i][1])
i += 1
else:
while i < nrecords:
if records1[i][3] == "UGRD" and records1[i][4] == "10 m above ground":
u = float(records2[i][1])
elif records1[i][3] == "VGRD" and records1[i][4] == "10 m above ground":
v = float(records2[i][1])
elif records1[i][3] == "TMP" and records1[i][4] == "2 m above ground":
t2m = float(records2[i][1])
elif records1[i][3] == "PRES" and records1[i][4] == "surface":
pz0 = float(records2[i][1])
elif records1[i][3] == "TMP" and records1[i][4] == "surface":
tz0 = float(records2[i][1])
i += 1
wind = (u ** 2 + v ** 2) ** 0.5
wind_dir_degrees = atan2(u, v) * 180 / pi
direction = wind_dir_degrees + 180
prof_file = os.path.join(folder, "data_location_data_" + validity + ".txt")
wt_output = open(prof_file, "w", encoding="utf-8", errors="surrogateescape")
wt_output.write(
" U[m/s] V[m/s] WIND[m/s] WIND_DIR[deg] T2m[K] Tz0[K] Pz0[Pa]\n"
)
wt_output.write(
"%10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f\n"
% (u, v, wind, direction, t2m, tz0, pz0)
)
wt_output.close()
gamma_sl = (t2m - tz0) / 2.0
return u, v, t2m, wind, direction, tz0, gamma_sl, pz0
def prepare_diagno_files(data_folder, year, month, day):
files_list = os.listdir(data_folder)
path = os.path.normpath(data_folder)
splitted_path = path.split(os.sep)
retrieved_day_s = splitted_path[-1]
profile_data_files = []
surface_data_files = []
for file in files_list:
if "profile_" in file and "profile_" + year + month + day + ".txt" != file:
profile_data_files.append(file)
if (
"data_location_" in file
and "data_location_" + year + month + day + ".txt" != file
):
surface_data_files.append(file)
profile_data_files = sorted(profile_data_files)
surface_data_files = sorted(surface_data_files)
wind_direction_string = ""
wind_speed_string = ""
heights_string = ""
gamma_string_1 = ""
gamma_string_2 = ""
gamma_string_3 = ""
try:
diagno_preupr = open(
os.path.join(data_folder, "preupr.dat"),
"w",
encoding="utf-8",
errors="surrogateescape",
)
diagno_preupr.write("1 NSTA\n")
diagno_preupr.write("20 LEVELS\n")
diagno_preupr.write("0 NSTRHR\n")
diagno_preupr.write("23 NENDHR\n")
diagno_preupr.write("0.5 TDIF\n")
diagno_preupr.write("13 NCELL\n")
diagno_preupr.write(
"0. 1. 2. 4. 8. 16. 24. 32. 40. 60. 80. 100. 250. 500. CELLZB\n"
)
diagno_preupr.write(year[2:4] + " KYEAR\n")
diagno_preupr.write(str(int(month)) + " KMONTH\n")
diagno_preupr.write(str(int(day)) + " KDAY\n")
diagno_preupr.write("2 IOPT\n")
diagno_preupr.write(
"ST01"
+ " "
+ "{0:7.1f}".format(easting)
+ "{0:7.1f}".format(northing)
+ "{0:7.1f}".format(elevation)
+ "\n"
)
for file in profile_data_files:
validity = file.split("profile_")[1]
validity = validity.split(".txt")[0]
year = validity[0:4]
month = validity[4:6]
day = validity[6:8]
hour = validity[8:10]
wtfile_prof_step = os.path.join(data_folder, file)
# Extract and elaborate weather data
wind, direction, height, gamma_pl = extract_grib_data(
data_folder, validity, wtfile_prof_step
)
for i in range(0, len(wind) - 1):
try:
heights_string += "{:>5}".format(str(int(round(height[i]))))
except TypeError:
heights_string += " -1"
try:
if (
wind[i] > 50
): # This is the maximum speed limit accepted by DIAGNO
wind_speed_string += " -1"
else:
wind_speed_string += "{:>5}".format(
str(int(round(wind[i] * 10)))
)
except TypeError:
wind_speed_string += " -1"
try:
wind_direction_string += "{:>5}".format(
str(int(round(direction[i])))
)
except TypeError:
wind_direction_string += " -1"
diagno_preupr.write(
"{:2}".format(year[2:4])
+ "{:>2}".format(str(int(month)))
+ "{:>2}".format(str(int(day)))
+ "ST01"
+ " "
+ hour
+ "00"
+ " "
+ "MET"
+ heights_string
+ "\n"
)
diagno_preupr.write(
"{:2}".format(year[2:4])
+ "{:>2}".format(str(int(month)))
+ "{:>2}".format(str(int(day)))
+ "ST01"
+ " "
+ hour
+ "00"
+ " "
+ "DEG"
+ wind_direction_string
+ "\n"
)
diagno_preupr.write(
"{:2}".format(year[2:4])
+ "{:>2}".format(str(int(month)))
+ "{:>2}".format(str(int(day)))
+ "ST01"
+ " "
+ hour
+ "00"
+ " "
+ "MPS"
+ wind_speed_string
+ "\n"
)
wind_direction_string = ""
wind_speed_string = ""
heights_string = ""
tref_vector = []
tsoil_vector = []
press_vector = []
wind_direction_sl_string = ""
wind_speed_sl_string = ""
um_string_1 = ""
um_string_2 = ""
um_string_3 = ""
vm_string_1 = ""
vm_string_2 = ""
vm_string_3 = ""
tinf = 0
if mode == "reanalysis":
files_to_iterate = surface_data_files
file_keyword = "data_location_"
else:
files_to_iterate = profile_data_files
file_keyword = "profile_"
for file in files_to_iterate:
validity = file.split(file_keyword)[1]
validity = validity.split(".txt")[0]
year = validity[0:4]
month = validity[4:6]
day = validity[6:8]
hour = validity[8:10]
wtfile_sl_location_step = os.path.join(data_folder, file)
u, v, t2m, wind_sl, direction_sl, tz0, gamma_sl, pz0 = extract_grib_data_sl(
data_folder, validity, wtfile_sl_location_step
)
tinf += 0.5 * (tz0 + t2m)
tref_vector.append(t2m)
tsoil_vector.append(tz0)
press_vector.append(pz0)
# Extract and elaborate weather data
try:
wind_speed_sl_string += "{:>3}".format(str(int(round(wind_sl * 10))))
except TypeError:
wind_speed_sl_string += " -1"
try:
wind_direction_sl_string += "{:>3}".format(
str(int(round(direction_sl)))
)
except TypeError:
wind_direction_sl_string += " -1"
if len(um_string_1) < 48:
um_string_1 += "{:<6.1f}".format(u)
else:
if len(um_string_2) < 48:
um_string_2 += "{:<6.1f}".format(u)
else:
um_string_3 += "{:<6.1f}".format(u)
if len(vm_string_1) < 48:
vm_string_1 += "{:<6.1f}".format(v)
else:
if len(vm_string_2) < 48:
vm_string_2 += "{:<6.1f}".format(v)
else:
vm_string_3 += "{:<6.1f}".format(v)
if len(gamma_string_1) < 56:
gamma_string_1 += "{:<7.1f}".format(gamma_sl)
else:
if len(gamma_string_2) < 56:
gamma_string_2 += "{:<7.1f}".format(gamma_sl)
else:
gamma_string_3 += "{:<7.1f}".format(gamma_sl)
tinf = tinf / float(len(profile_data_files))
str_tinf = "{:<4.1f}".format(tinf)
str_tinf += " TINF\n"
um_string_1 += " UM\n"
um_string_2 += " UM\n"
um_string_3 += " UM\n"
vm_string_1 += " VM\n"
vm_string_2 += " VM\n"
vm_string_3 += " VM\n"
gamma_string_1 += " GAMMA (K/km)\n"
gamma_string_2 += " GAMMA (K/km)\n"
gamma_string_3 += " GAMMA (K/km)\n"
# Memorize the needed records in the original presfc.dat
try:
presfc_file_records = []
diagno_presfc = open(
os.path.join(data_folder, "presfc.dat"),
"r",
encoding="utf-8",
errors="surrogateescape",
)
for line in diagno_presfc:
presfc_file_records.append(line)
diagno_presfc.close()
os.remove("presfc.dat")
diagno_presfc = open(
os.path.join(data_folder, "presfc.dat"),
"w",
encoding="utf-8",
errors="surrogateescape",
)
diagno_presfc.write(str(n_stations) + " NSTA\n")
diagno_presfc.write("0 NSTRHR\n")
diagno_presfc.write("23 NENDHR\n")
diagno_presfc.write("0.5 TDIF\n")
diagno_presfc.write(year[2:4] + " KYEAR\n")
diagno_presfc.write(str(int(month)) + " KMONTH\n")
diagno_presfc.write(str(int(day)) + " KDAY\n")
diagno_presfc.write(presfc_file_records[7])
diagno_presfc.write(
"ST02"
+ " "
+ "{0:7.1f}".format(easting)
+ "{0:7.1f}".format(northing)
+ "\n"
)
diagno_presfc.write(presfc_file_records[8])
diagno_presfc.write(presfc_file_records[9])
diagno_presfc.write(
"{:2}".format(year[2:4])
+ "{:>2}".format(str(int(month)))
+ "{:>2}".format(str(int(day)))
+ " ST02"
+ " WD"
+ " DEG "
+ wind_direction_sl_string
+ "\n"
)
diagno_presfc.write(
"{:2}".format(year[2:4])
+ "{:>2}".format(str(int(month)))
+ "{:>2}".format(str(int(day)))
+ " ST02"
+ " WS"
+ " MPS "
+ wind_speed_sl_string
+ "\n"
)
except BaseException:
diagno_presfc = open(
os.path.join(data_folder, "presfc.dat"),
"w",
encoding="utf-8",
errors="surrogateescape",
)
diagno_presfc.write(str(n_stations) + " NSTA\n")
diagno_presfc.write("0 NSTRHR\n")
diagno_presfc.write("23 NENDHR\n")
diagno_presfc.write("0.5 TDIF\n")
diagno_presfc.write(year[2:4] + " KYEAR\n")
diagno_presfc.write(str(int(month)) + " KMONTH\n")
diagno_presfc.write(str(int(day)) + " KDAY\n")
diagno_presfc.write(
"ST02"
+ " "
+ "{0:7.1f}".format(easting)
+ "{0:7.1f}".format(northing)
+ "\n"
)
diagno_presfc.write(
"{:2}".format(year[2:4])
+ "{:>2}".format(str(int(month)))
+ "{:>2}".format(str(int(day)))
+ " ST02"
+ " WD"
+ " DEG "
+ wind_direction_sl_string
+ "\n"
)
diagno_presfc.write(
"{:2}".format(year[2:4])
+ "{:>2}".format(str(int(month)))
+ "{:>2}".format(str(int(day)))
+ " ST02"
+ " WS"
+ " MPS "
+ wind_speed_sl_string
+ "\n"
)
try:
diagno_records = []
diagno = open(
os.path.join(data_folder, "diagno.inp"),
"r",
encoding="utf-8",
errors="surrogateescape",
)
for line in diagno:
diagno_records.append(line)
diagno_records[42] = gamma_string_1
diagno_records[43] = gamma_string_2
diagno_records[44] = gamma_string_3
diagno_records[47] = str_tinf
diagno_records[51] = um_string_1
diagno_records[52] = um_string_2
diagno_records[53] = um_string_3
diagno_records[54] = vm_string_1
diagno_records[55] = vm_string_2
diagno_records[56] = vm_string_3
with open(
os.path.join(data_folder, "diagno.inp"),
"w",
encoding="utf-8",
errors="surrogateescape",
) as diagno:
diagno.writelines(diagno_records)
except BaseException:
print("Unable to process diagno.inp")
except BaseException:
with open(
"log.txt", "a+", encoding="utf-8", errors="surrogateescape"
) as logger:
logger.write(retrieved_day_s + "\n")
return tref_vector, tsoil_vector, press_vector
def era5_retrieve(lon_source, lat_source, retrieved_day):
def era5_request_pressure(folder, year, month, day):
import cdsapi
check_pl = 1
grib_file = os.path.join(folder, "pressure_levels.grib")
print("Downloading file from ERA5 database")
c = cdsapi.Client()
try:
print("Retrieving pressure-levels data")
c.retrieve(
"reanalysis-era5-pressure-levels",
{
"pressure_level": [
"1",
"2",
"3",
"5",
"7",
"10",
"20",
"30",
"50",
"70",
"100",
"125",
"150",
"175",
"200",
"225",
"250",
"300",
"350",
"400",
"450",
"500",
"550",
"600",
"650",
"700",
"750",
"775",
"800",
"825",
"850",
"875",
"900",
"925",
"950",
"975",
"1000",
],
"variable": [
"geopotential",
"u_component_of_wind",
"v_component_of_wind",
"temperature",
],
"time": [
"00:00",
"01:00",
"02:00",
"03:00",
"04:00",
"05:00",
"06:00",
"07:00",
"08:00",
"09:00",
"10:00",
"11:00",
"12:00",
"13:00",
"14:00",
"15:00",
"16:00",
"17:00",
"18:00",
"19:00",
"20:00",
"21:00",
"22:00",
"23:00",
],
"product_type": "reanalysis",
"year": year,
"day": day,
"month": month,
"area": area,
"format": "grib",
},
grib_file,
)
except (Exception, ConnectionError):
print("Unable to retrieve ERA5 pressure level data")
check_pl = 0
return check_pl
def era5_request_single(folder, year, month, day):
import cdsapi
check_sl = 1
print("Downloading file from ERA5 database")
grib_file = os.path.join(folder, "surface.grib")
c = cdsapi.Client()
try:
print("Retrieving single levels data")
c.retrieve(
"reanalysis-era5-single-levels",
{
"variable": [
"10m_u_component_of_wind",
"10m_v_component_of_wind",
"2m_temperature",
"soil_temperature_level_1",
"surface_pressure",
],
"time": [
"00:00",
"01:00",
"02:00",
"03:00",
"04:00",
"05:00",
"06:00",
"07:00",
"08:00",
"09:00",
"10:00",
"11:00",
"12:00",
"13:00",
"14:00",
"15:00",
"16:00",
"17:00",
"18:00",
"19:00",
"20:00",
"21:00",
"22:00",
"23:00",
],
"product_type": "reanalysis",
"year": year,
"day": day,
"month": month,
"area": area,
"format": "grib",
},
grib_file,
)
except (Exception, ConnectionError):
print("Unable to retrieve ERA5 single level data")
check_sl = 0
return check_sl
try:
retrieved_day_s = str(retrieved_day)
year = retrieved_day_s[0:4]
month = retrieved_day_s[5:7]
day = retrieved_day_s[8:10]
data_folder = os.path.join(simulations, year + month + day)
slon_source = str(lon_source)
slat_source = str(lat_source)
date_bis = year + month + day
wtfile = os.path.join(data_folder, "weather_data_" + date_bis)
wtfile_sl = os.path.join(data_folder, "weather_data_sl_" + date_bis)
lat_N = int(lat_source) + 2
lat_S = int(lat_source) - 2
lon_W = int(lon_source) - 2
lon_E = int(lon_source) + 2
area = [lat_N, lon_W, lat_S, lon_E]
# Retrieve files
check_pl = era5_request_pressure(data_folder, year, month, day)
check_sl = era5_request_single(data_folder, year, month, day)
if check_pl == 0 or check_sl == 0:
with open(
"log.txt", "a+", encoding="utf-8", errors="surrogateescape"
) as logger:
logger.write(retrieved_day_s + "\n")
return
# Convert grib1 to grib2 with the NOAA Perl script. To make it more portable and avoiding the need to set up
# many paths, I have included in the package also the required files and scripts that are originally available
# in the grib2 installation folder
print("Converting grib1 data to grib2")
pl_grib_file = os.path.join(data_folder, "pressure_levels.grib ")
sl_grib_file = os.path.join(data_folder, "surface.grib ")
os.system("grib_set -s edition=2 " + pl_grib_file + wtfile)
os.system("grib_set -s edition=2 " + sl_grib_file + wtfile_sl)
wtfile_prof = os.path.join(data_folder, "profile_" + date_bis + ".txt")
wtfile_sl_location = os.path.join(
data_folder, "data_location_" + date_bis + ".txt"
)
print("Saving weather data along the vertical at the vent location")
os.system(
"wgrib2 "
+ wtfile
+ " -s -lon "
+ slon_source
+ " "
+ slat_source
+ " >"
+ wtfile_prof
)
os.system(
"wgrib2 "
+ wtfile_sl
+ " -s -lon "
+ slon_source
+ " "
+ slat_source
+ " >"
+ wtfile_sl_location
)
# Split wtfile_prof into multiple file, each one for a specific time step
splitLen = 148
outputBase = os.path.join(data_folder, "profile_")
input = open(wtfile_prof, "r", encoding="utf-8", errors="surrogateescape")
count = 0
dest = None
steps = []
for line in input:
if count % splitLen == 0:
if dest:
dest.close()
first_line = line.split(":")
val = first_line[2].split("d=")
dest = open(
outputBase + val[1] + ".txt",
"w",
encoding="utf-8",
errors="surrogateescape",
)
steps.append(val[1])
dest.write(line)
count += 1
input.close()
dest.close()
# Split data_location into multiple file, each one for a specific time step
splitLen = 5
outputBase = os.path.join(data_folder, "data_location_")
input = open(
wtfile_sl_location, "r", encoding="utf-8", errors="surrogateescape"
)
count = 0
dest = None
steps = []
for line in input:
if count % splitLen == 0:
if dest:
dest.close()
first_line = line.split(":")
val = first_line[2].split("d=")
dest = open(
outputBase + val[1] + ".txt",
"w",
encoding="utf-8",
errors="surrogateescape",
)
steps.append(val[1])
dest.write(line)
count += 1
input.close()
dest.close()
except BaseException: