-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
4075 lines (3265 loc) · 139 KB
/
tools.py
File metadata and controls
4075 lines (3265 loc) · 139 KB
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
#!/usr/bin/env python3
"""
@author: Tanguy LUNEL
Creation : 07/01/2021
Module gathering various functions used in different part of the codes
"""
import os
#from scipy.stats import circmean
import copy
import time
import numpy as np
from scipy import interpolate, integrate, stats
import matplotlib.pyplot as plt
import pandas as pd
import xarray as xr
# from metpy.units import units
# import metpy.calc as mcalc
# import metpy.constants as constants
import re
import global_variables as gv
from datetime import datetime
# from shapely.geometry import Point
#from difflib import SequenceMatcher
import warnings
import epygram
# from dask import compute
# from dask.delayed import delayed
# import dask
#%% Load MNH/SFX/AROME files
def load_series_dataset(varname_sim_list, model, concat_if_not_existing=True,
out_suffix='', file_suffix='dg',
global_simu_folder = gv.global_simu_folder):
"""
Load a simulation file in netcdf format. If not already existing,
tries to concatenate multiple instantaneous output files into a series.
Parameters:
varname_sim_list: ex:['T2M_ISBA', 'H_P9']
model: 'std_d1', 'irr_d1', 'irrlagrip30_d1'
concat_if_not_existing: Try to concatenate or not if the concatenated file
does not exist yet
"""
for i, varname_item in enumerate(varname_sim_list):
# get format of file to concatenate
# in_filenames_sim = gv.format_filename_simu_wildcards[model]
# -- old way:
# in_filenames_sim = gv.format_filename_simu_new[model].format(
# seg_nb='??', output_nb_3f='???', output_nb_2f='??',
# out_suffix=out_suffix, file_suffix=file_suffix)
in_filenames_sim = gv.simu_filenames_rules[model]['format'].format(
seg_nb='??', output_nb_3f='???', output_nb_2f='??',
out_suffix=out_suffix, file_suffix=file_suffix)
gridnest_nb = in_filenames_sim[6] # integer: 1 or 2 in my case
# -- if normal work on lustre:
# set name of concatenated output file
# out_filename_sim = f'LIAIS.{gridnest_nb}.{varname_item}{out_suffix}.nc'
# path of file
# datafolder = global_simu_folder + gv.simu_folders[model]
# -- if work in local:
out_filename_sim_short = f'LIAIS.{gridnest_nb}.{varname_item}{out_suffix}.nc'
out_filename_sim = '/home/lunelt/Data/data_LIAISE/' + out_filename_sim_short
datafolder = ''
# concatenate multiple days if not already existing
if concat_if_not_existing:
concat_simu_files_1var(datafolder, varname_item,
# in_filenames_sim, out_filename_sim)
in_filenames_sim, out_filename_sim)
if i == 0: # if first data, create new dataset
ds = xr.open_dataset(datafolder + out_filename_sim)
else: # append data to existing dataset
ds_temp = xr.open_dataset(datafolder + out_filename_sim)
ds = ds.merge(ds_temp)
return ds
def load_dataset(varname_sim_list, model, concat_if_not_existing=True,
out_suffix='', file_suffix='dg'):
warnings.warn(
"""Deprecation warning:
'load_dataset' should be replaced by 'load_series_dataset'.
""")
return load_series_dataset(varname_sim_list,
model, concat_if_not_existing=True,
out_suffix='', file_suffix='dg')
def open_profiler_file(filename, profiler_name):
"""
Open a diachronic file to read the data of a profiler.
Concatenate atmospheric profile and surface data
and replace time with correct time format
"""
meta = xr.open_dataset(filename)
profile_raw = xr.open_dataset(
filename, group=f"Profilers/{profiler_name}/Vertical_profile")
profile = flux_pt_to_mass_pt(profile_raw, only_basic_vars=False)
surface_data = xr.open_dataset(
filename, group=f"Profilers/{profiler_name}/Point")
ds = xr.merge([profile, surface_data])
ds['time_profiler'] = meta.time_profiler
return ds
def open_budget_file(filename, budget_type):
"""
Add longitude, latitude, ni, nj coordinates to a dataset which does not
have it.
/!\ the longitude, latitude, ni, nj coordinates may not be the same than
those of outer domain (may correspond to latitude_u, ni_u,
of outer domain etc for ex.)
"""
meta = xr.open_dataset(filename) # metadata of the entire simulation domain, not only the budget one
ds = xr.open_dataset(filename, group=f"Budgets/{budget_type}")
if budget_type == 'UU':
cart_nj_X = 'cart_nj_u'
cart_ni_X = 'cart_ni_u'
cart_level_X = 'cart_level'
nj_X = 'nj_u'
ni_X = 'ni_u'
latitude_X = 'latitude_u'
longitude_X = 'longitude_u'
elif budget_type == 'VV':
cart_nj_X = 'cart_nj_v'
cart_ni_X = 'cart_ni_v'
cart_level_X = 'cart_level'
nj_X = 'nj_v'
ni_X = 'ni_v'
latitude_X = 'latitude_v'
longitude_X = 'longitude_v'
elif budget_type == 'WW':
cart_nj_X = 'cart_nj'
cart_ni_X = 'cart_ni'
cart_level_X = 'cart_level_w'
nj_X = 'nj'
ni_X = 'ni'
latitude_X = 'latitude'
longitude_X = 'longitude'
elif budget_type in ['TH', 'RV', 'TK']:
cart_nj_X = 'cart_nj'
cart_ni_X = 'cart_ni'
cart_level_X = 'cart_level'
nj_X = 'nj'
ni_X = 'ni'
latitude_X = 'latitude'
longitude_X = 'longitude'
lon_arr = np.zeros([len(meta[cart_nj_X]), len(meta[cart_ni_X])])
lat_arr = np.zeros([len(meta[cart_nj_X]), len(meta[cart_ni_X])])
nj_arr = np.zeros([len(meta[cart_nj_X]),])
ni_arr = np.zeros([len(meta[cart_ni_X]),])
for i, ni_val in enumerate(meta[cart_ni_X].values):
for j, nj_val in enumerate(meta[cart_nj_X].values):
if budget_type == 'UU':
pt = meta.sel(ni_u=ni_val, nj_u=nj_val)
elif budget_type == 'VV':
pt = meta.sel(ni_v=ni_val, nj_v=nj_val)
elif budget_type in ['TH', 'RV', 'TK', 'WW']:
pt = meta.sel(ni=ni_val, nj=nj_val)
lat_arr[j, i] = float(pt[latitude_X])
lon_arr[j, i] = float(pt[longitude_X])
nj_arr[j] = nj_val
ni_arr[i] = ni_val
ds[longitude_X] = xr.DataArray(lon_arr,
coords={cart_nj_X: ds[cart_nj_X].values,
cart_ni_X: ds[cart_ni_X].values,})
ds[latitude_X] = xr.DataArray(lat_arr,
coords={cart_nj_X: ds[cart_nj_X].values,
cart_ni_X: ds[cart_ni_X].values})
ds[ni_X] = xr.DataArray(ni_arr,
coords={cart_ni_X: ds[cart_ni_X].values})
ds[nj_X] = xr.DataArray(nj_arr,
coords={cart_nj_X: ds[cart_nj_X].values})
ds[cart_level_X] = xr.DataArray(meta[cart_level_X],
coords={cart_level_X: meta[cart_level_X]})
ds = ds.set_coords([latitude_X, longitude_X, nj_X, ni_X])
ds = ds.swap_dims({cart_nj_X: nj_X, cart_ni_X: ni_X,})
ds = ds.drop([cart_nj_X, cart_ni_X])
# rename for simplicity in processing in other functions, but may be risky...
ds = ds.rename({cart_level_X: 'level'})
ds['time_budget'] = meta.time_budget
if budget_type in ['VV', 'UU']:
meta_subset = subset_ds(meta,
lat_range=[ds[latitude_X].min(), ds[latitude_X].max()],
lon_range=[ds[longitude_X].min(), ds[longitude_X].max()],
)
# interpolate on mass points (center of grid)
if budget_type == 'UU':
ds = ds.interp(ni_u=meta_subset.ni.values, nj_u=meta_subset.nj.values)
elif budget_type == 'VV':
ds = ds.interp(ni_v=meta_subset.ni.values, nj_v=meta_subset.nj.values)
ds = ds.rename({nj_X: 'nj', ni_X: 'ni',
longitude_X: 'longitude', latitude_X: 'latitude'})
return ds
def open_les_budget_file(filename, LES_budgets_type = 'Mean',
LES_budgets_averaging = 'Time_averaged'):
"""
Add time and level coordinates to a dataset which does not have it.
"""
meta = xr.open_dataset(filename) # metadata of the entire simulation domain, not only the budget one
if isinstance(LES_budgets_type, list):
ds_list = []
for les_bu_type in LES_budgets_type:
groupname_les_budget = f"LES_budgets/{les_bu_type}/Cartesian/{LES_budgets_averaging}/Not_normalized/cart"
ds_list.append(xr.open_dataset(filename,
group=groupname_les_budget))
ds = xr.merge(ds_list)
else:
groupname_les_budget = f"LES_budgets/{LES_budgets_type}/Cartesian/{LES_budgets_averaging}/Not_normalized/cart"
ds = xr.open_dataset(filename, group=groupname_les_budget)
ds['level_les'] = meta.level_les
ds['time_les_avg'] = meta.time_les_avg
return ds
def open_multiple_budget_file(filename_bu, budget_type_list=['UU', 'VV'],
wanted_datetime=None):
"""
Create xarray.Dataset with compound budget, typically UU and VV data
(code need adaptation in order to work with var different from UU and VV).
The variables of the budget datasets merged are renamed:
[varname] -> [varname]_[budget_type]
ex: 'PRES' becomes 'PRES_UU'
return:
xarray.Dataset
"""
budget_file_dict = {}
# Load separately the different budget files
for bu in budget_type_list:
budget_file_dict[bu] = open_budget_file(filename_bu, bu)
# Ensure that dataset are of the same size: -> NOT NEEDED I THINK: 'join' = outer anyway for the merge step
# ds_bu_UU == ds_bu_UU.where(ds_bu_VV.nj==ds_bu_UU.nj).where(ds_bu_VV.ni==ds_bu_UU.ni)
# ds_bu_VV = ds_bu_VV.where(ds_bu_VV.nj==ds_bu_UU.nj).where(ds_bu_VV.ni==ds_bu_UU.ni)
# Change names of variable by adding the budget type
for bu in budget_type_list:
for var_name in list(budget_file_dict[bu].keys()):
budget_file_dict[bu] = budget_file_dict[bu].rename({var_name: f'{var_name}_{bu}'})
# Merge the datasets in 1
# fix unsignificant differences in lat/lon coords between datasets
# note that 1e-5=0.00001° in latitude or longitude ~= 1m
for i, bu in enumerate(budget_type_list):
if i==0:
ds_out = budget_file_dict[bu]
else:
if np.abs(budget_file_dict[bu].latitude - ds_out.latitude).max() < 1e-5:
budget_file_dict[bu]['latitude'] = ds_out.latitude
if np.abs(budget_file_dict[bu].longitude - ds_out.longitude).max() < 1e-5:
budget_file_dict[bu]['longitude'] = ds_out.longitude
# concatenate the datasets together
ds_out = ds_out.merge(budget_file_dict[bu])
# if a specific datetime is requested:
if wanted_datetime is not None:
hour = pd.Timestamp(wanted_datetime).hour
ds_out = ds_out.isel(time_budget=hour)
ds_out = ds_out.assign_coords({'time': pd.Timestamp(wanted_datetime)})
return ds_out
def compound_budget_file(filename_bu, budget_type_list=['UU', 'VV']):
warnings.warn(
"""Deprecation warning:
'compound_budget_file' should be replaced by 'open_multiple_budget_file'.
""")
return open_multiple_budget_file(filename_bu,
budget_type_list=['UU', 'VV'])
def open_relevant_file(model, wanted_date, var_simu):
"""
Choose the file to open depending on the variable wanted.
"""
# --- Retrieve and open file
# Budget variables
if var_simu[-3:] in ['_TH', '_RV', '_TK', '_UU', '_VV', '_WW',]:
filename_simu = get_simu_filepath(model, wanted_date,
filetype='000',)
ds = open_multiple_budget_file(filename_simu, [var_simu[-2:],],
wanted_datetime=wanted_date)
elif var_simu[-3:] in ['_UV',]:
raise NameError('to be coded')
# code below could do?
# filename_simu = tools.get_simu_filepath(model, wanted_date,
# filetype='000',)
# ds = tools.open_multiple_budget_file(filename_simu, ['UU', 'VV'])
# ds[f'{var_simu[:-3]}}_VAL'], ds_bu[f'{var_simu[:-3]}}_DIR'] = tools.calc_ws_wd(
# ds_bu[f'{var_simu[:-3]}_UU'], ds_bu[f'{var_simu[:-3]}_VV'])
# Variable available in OUTPUT files:
elif var_simu in ['RVT', 'THT', 'THTV', 'WT', 'UT', 'VT', 'WS', 'TKET']:
output_freq = gv.output_freq_dict[model]
try:
filename_simu = get_simu_filepath(model, wanted_date,
file_suffix='', #'dg' or ''
out_suffix='.OUT',
output_freq=output_freq)
except FileNotFoundError:
filename_simu = get_simu_filepath(model, wanted_date,
file_suffix='dg', #'dg' or ''
out_suffix='',)
ds = xr.open_dataset(filename_simu)
ds['THTV'] = ds['THT']*(1 + 0.61*ds['RVT'])
if var_simu == 'WS':
ds = center_uvw(ds)
ds['WS'], _ = calc_ws_wd(ds['UT'], ds['VT'])
# Other variables:
else:
filename_simu = get_simu_filepath(model, wanted_date,
file_suffix='dg', #'dg' or ''
out_suffix='',)
ds = xr.open_dataset(filename_simu)
return ds
def get_simu_filepath_old(model, date='20210722-1200',
filetype='synchronous', # synchronous or diachronic (=000)
file_suffix='dg', #'dg' or ''
out_suffix='', #'.OUT' or ''
output_freq=None, # [min]
global_simu_folder=gv.global_simu_folder,
verbose=False,
):
"""
Returns the whole string for filename and path.
Chooses the right SEG (segment) number and suffix corresponding to date
Parameters:
model: str,
'irr_d2' or 'std_d1'
wanted_date: str with format accepted by pd.Timestamp ('20210722-1200')
or pd.Timestamp
Returns:
filename: str, full path and filename
"""
pd_date = pd.Timestamp(date)
seg_nb = str(pd_date.day)
if filetype in ['synchronous', '']:
if output_freq is None: # set default according to file types
if out_suffix == '' and file_suffix == 'dg':
output_freq = 60
elif out_suffix == '.OUT' and file_suffix == '':
output_freq = 30
else:
print('output_freq not defined')
if out_suffix == '' and file_suffix == 'dg' and output_freq==60:
output_nb = str(pd_date.hour)
elif out_suffix == '.OUT' and file_suffix == '':
minute_total_day = pd_date.minute + pd_date.hour*60
output_nb = str(int(minute_total_day/output_freq))
print('output_nb = {0}'.format(output_nb))
else:
raise ValueError('out_suffix and file_suffix values not consistent')
# Reformat the output_nb with 2 and 3 digits:
output_nb_2f = output_nb.zfill(2)
output_nb_3f = output_nb.zfill(3)
elif filetype in ['diachronic', '000']:
output_nb_2f = str(pd_date.hour).zfill(2)
output_nb_3f = '000'
file_suffix = ''
out_suffix = ''
# Midnight case
if output_nb_2f == "00":
output_nb_2f = "24"
output_nb_3f = "024"
seg_nb = str(pd_date.day - 1)
# retrieve filename
filename = gv.format_filename_simu[model].format(
seg_nb=seg_nb,
output_nb_2f=output_nb_2f,
output_nb_3f=output_nb_3f,
file_suffix=file_suffix,
out_suffix=out_suffix)
filepath = global_simu_folder + gv.simu_folders[model] + filename
#check if nomenclature of filename is ok
if filetype in ['synchronous', '']:
check_filename_datetime(filepath)
if verbose:
print(filepath)
return filepath
def get_simu_filepath(
model, wanted_date='19700101T0000',
output_type='backup', # backup, output, diachronic (=000), diag
global_simu_folder=gv.global_simu_folder,
verbose=False,
error_processing='error',
):
"""
Returns the whole string for filename and path.
Chooses the right SEG (segment) number and suffix corresponding to date
Parameters:
model: str,
ex: 'irr_d2', '1_planier_0105/0211_40m/'
wanted_date: str with format accepted by pd.Timestamp ('20210722-1200')
or pd.Timestamp
Returns:
filename: str, full path and filename
"""
# rename for 000 case
if output_type == '000':
output_type = 'diachronic'
if output_type != 'diachronic':
pd_date = pd.Timestamp(wanted_date)
if model in gv.simu_folders.keys():
local_simu_folder = gv.simu_folders[model]
else:
local_simu_folder = model
naming_prop = gv.simu_filenames_rules[model]
simu_start = naming_prop['simu_start']
if output_type == 'diag':
name_rules = naming_prop['backup']
file_suffix = 'dg'
else:
name_rules = naming_prop[output_type]
file_suffix = name_rules['file_suffix']
out_suffix = name_rules['out_suffix']
# SEG number
if name_rules['seg_nb'] == 'day':
seg_nb = str(pd_date.day)
else:
seg_nb = name_rules['seg_nb']
# Get timedelta between wanted_date and beginning of run in minutes
timestep_simu = pd.Timestamp(wanted_date) - pd.Timestamp(simu_start)
timestep_simu_min = timestep_simu.value/(60*1e9)
# How to translate this timedelta into output number
#ex: output_nb_rule='H-2x6': 03h10m = 3.166-2 = 1.166 -> x6 = 007
output_nb_rule = name_rules['output_nb']
if re.match('H-.*x.*', output_nb_rule):
splitted_rule = re.split('[-x]', output_nb_rule)
start_offset_min = float(splitted_rule[1]) * 60
output_freq = 60 / float(splitted_rule[2])
elif re.match('H-.*', output_nb_rule):
splitted_rule = re.split('[-]', output_nb_rule)
start_offset_min = float(splitted_rule[1]) * 60
output_freq = 60
elif re.match('Hx.*', output_nb_rule):
splitted_rule = re.split('[x]', output_nb_rule)
start_offset_min = 0
output_freq = 60 / float(splitted_rule[1])
elif output_nb_rule in ['H', 'HH']:
start_offset_min = 0
output_freq = 60
elif output_nb_rule in ['hour']:
pass # directly set later
elif output_nb_rule == '000':
pass # diachronic file
else:
raise ValueError('Format of output_nb_rule is unknown')
if output_nb_rule == '000':
output_nb = '000'
if output_nb_rule == 'hour':
output_nb = str(pd_date.hour).zfill(2)
else:
output_nb = str(int((timestep_simu_min - start_offset_min)/output_freq))
if int(output_nb) < 0:
raise KeyError('No corresponding simu files (output number not existing)')
elif int(output_nb) == 0 and output_type != 'diachronic':
raise KeyError('No corresponding simu files (output number not existing)')
#Midnight case
if output_nb == "00":
print('midnight case -- check code here (needed?)')
output_nb = "24"
# Reformat the output_nb with 2 and 3 digits:
output_nb_2f = output_nb.zfill(2)
output_nb_3f = output_nb.zfill(3)
# Retrieve filename and absolute filepath
# filename = gv.format_filename_simu[model].format(
filename = naming_prop['format'].format(
seg_nb=seg_nb,
output_nb_2f=output_nb_2f,
output_nb_3f=output_nb_3f,
file_suffix=file_suffix,
out_suffix=out_suffix)
filepath = global_simu_folder + local_simu_folder + '/' + filename
#check if nomenclature of filename is ok
if output_type in ['backup', 'output']:
check_filename_datetime(filepath, wanted_date,
error_processing=error_processing)
if verbose:
print(filepath)
return filepath
def extract_profile_arome(site, wanted_date, varname,
max_height=3000,
folder_path='/home/lunelt/Data/analysis/',
file_prefix='arome.AN.',
save_to_pickle=True,
save_folder_pickle='/home/lunelt/Data/data_NEMO/arome_profiles/',
verbose=True):
"""
Parameters
----------
site : string
name of site above to perform the extraction.
Must be in global_variables
wanted_date : string with format YYYYMMDD.HH
ex: 20230725.00
varname : string
must be in [tke, t, u, v, q, ws, wd]
max_height : TYPE, optional
DESCRIPTION. The default is 3000.
folder_path : TYPE, optional
DESCRIPTION. The default is '/home/lunelt/Data/analysis/'.
file_prefix : TYPE, optional
DESCRIPTION. The default is 'arome.AN.'.
Returns
-------
verti_profiles: dict of dict, first key is the varname(s),
second are the heights as keys
"""
try:
# Convert the input string to a pandas timestamp
timestamp = pd.to_datetime(wanted_date)
# Format the timestamp to the desired format
formatted_date = timestamp.strftime('%Y%m%d.%H')
except Exception as e:
raise ValueError(f"Invalid input wanted_date: {wanted_date}. Error: {e}")
epygram.init_env()
lon = gv.whole[site]['lon']
lat = gv.whole[site]['lat']
filename = f'{file_prefix}{formatted_date}'
file = epygram.formats.resource(filename=f'{folder_path}/{filename}',
openmode='r')
temp_res = {}
verti_profile = {}
verti_profiles = {}
if verbose:
print('processing of level nb:')
# if varname in ['ws', 'wd', 'wind']:
# for level, height in gv.level_height_AROME_mean.items():
# if height > max_height:
# pass
# else:
# if verbose:
# print(level)
# # u component
# u = file.find_fields_in_resource(f'shortName:u, level:{level}')
# field_u = file.readfields(u[0])[0]
# pt_u = float(field_u.extract_point(lat=lat, lon=lon).data)
# # v component
# v = file.find_fields_in_resource(f'shortName:v, level:{level}')
# field_v = file.readfields(v[0])[0]
# pt_v = float(field_v.extract_point(lat=lat, lon=lon).data)
# # ws,wd computation
# temp_res['ws'], temp_res['wd'] = calc_ws_wd(pt_u, pt_v)
# if varname == 'wind':
# verti_profile[height] = temp_res['ws'], temp_res['wd']
# else:
# verti_profile[height] = temp_res[varname]
# if varname == 'wind':
# # Initialize two new dictionaries
# dict_ws = {}
# dict_wd = {}
# # Loop through the original dictionary
# for altitude, values in verti_profile.items():
# dict_ws[altitude] = values[0] # First value of the tuple
# dict_wd[altitude] = values[1]
# verti_profiles['ws'] = dict_ws
# verti_profiles['wd'] = dict_wd
# else:
# verti_profiles[varname] = verti_profile
# else:
for level, height in gv.level_height_AROME_mean.items():
if height > max_height:
pass
else:
if verbose:
print(level)
fid = file.find_fields_in_resource(f'shortName:{varname}, level:{level}')
field = file.readfields(fid[0])[0]
verti_profile[height] = float(field.extract_point(lat=lat, lon=lon).data)
verti_profiles[varname] = verti_profile
if save_to_pickle:
# -- Save profile to pickle
formatted_date = wanted_date.strftime('%Y%m%d.%H')
filename_pickle = f"verti_profile_arome_{site}_{formatted_date}"
# Format pd.DataFrame:
df = pd.DataFrame(verti_profiles)
df.to_pickle(f'{save_folder_pickle}/{site}/{filename_pickle}.pickle')
return verti_profiles
def extract_profile_arome_parallel(site, wanted_date, varname,
max_height=3000, folder_path='/home/lunelt/Data/analysis/',
file_prefix='arome.AN.'):
"""
Not working yet, need to fix issue with Dask
Parameters
----------
site : string
name of site above to perform the extraction.
Must be in global_variables
wanted_date : string with format YYYYMMDD.HH
ex: 20230725.00
varname : string
must be in [tke, t, u, v, q, ws, wd]
max_height : TYPE, optional
DESCRIPTION. The default is 3000.
folder_path : TYPE, optional
DESCRIPTION. The default is '/home/lunelt/Data/analysis/'.
file_prefix : TYPE, optional
DESCRIPTION. The default is 'arome.AN.'.
Returns
-------
dict verti_profile with height as keys
"""
try:
# Convert the input string to a pandas timestamp
timestamp = pd.to_datetime(wanted_date)
# Format the timestamp to the desired format
formatted_date = timestamp.strftime('%Y%m%d.%H')
except Exception as e:
raise ValueError(f"Invalid input wanted_date: {wanted_date}. Error: {e}")
epygram.init_env()
lon = gv.sites[site]['lon']
lat = gv.sites[site]['lat']
filename = f'{file_prefix}{wanted_date}'
file = epygram.formats.resource(filename=f'{folder_path}/{filename}',
openmode='r')
# Create a dictionary to hold the delayed tasks
verti_profile_tasks = {}
# Iterate through the levels and heights in parallel using Dask's delayed
for level, height in gv.level_height_AROME_mean.items():
if height > max_height:
continue
@delayed
def process_level(level, height):
print(level)
fid = file.find_fields_in_resource(f'shortName:{varname}, level:{level}')
field = file.readfields(fid[0])[0]
return height, float(field.extract_point(lat=lat, lon=lon).data)
verti_profile_tasks[level] = process_level(level, height)
# Compute all delayed tasks in parallel
results = compute(*verti_profile_tasks.values(), scheduler='threads')
# Assemble the results into the final dictionary
verti_profile = {height: value for height, value in results}
return verti_profile
#%% Load OBS data
def open_ukmo_mast(datafolder, filename, create_netcdf=True, remove_modi=True,
remove_outliers=False):
"""
Open the 50m mast from UK MetOffice formatted under .txt,
create netcdf file, and returns a xarray dataset.
"""
filename_modi = filename + '_modi'
#replace multi space by tab
os.system('''
cd {0}
cp {1} {2}
sed -i 's/ \+ /\t/g' {2}
'''.format(datafolder, filename, filename_modi))
#Version de Guylaine :
#sed -i -e 's/ | /;/g' LIAISE_20210614_30.dat
#sed -i -e 's/ | /;/g' LIAISE_20210614_30.dat
#sed -i -e 's/ m /;/g' LIAISE_20210614_30.dat
#sed -i -e 's/ D /;/g' LIAISE_20210614_30.dat
#sed -i -e 's/ D /;/g' LIAISE_20210614_30.dat
#sed -i -e 's/ X /;/g' LIAISE_20210614_30.dat
#read header
with open(datafolder + filename_modi) as f:
fulltext = f.readlines() # read all lines
#Get date of file
line = fulltext[1]
strings = line.split(sep=' ')
day = strings[2][:2]
month = strings[2][3:5]
year = strings[2][6:10]
datetime = pd.Timestamp('{0}-{1}-{2}'.format(year, month, day))
#Get length of header (part starting by '!')
head_len = np.array([line.startswith('!') for line in fulltext]).sum()
#Get variables
var = fulltext[head_len-1].split(sep='\t')
#gGt height of measures
meas_height = fulltext[head_len-2].split(sep='\t')
columns=[]
for i in range(len(var)):
columns.append(var[i] + '_' + meas_height[i])
#removes flags corresponding to each measure
os.system('''
cd {0}
sed -i -e 's/|//g' -e 's/D//g' -e 's/X//g' -e 's/m//g' {1}
sed -i 's/ \+ /\t/g' {2}
'''.format(datafolder, filename, filename_modi))
#read data
obs_ukmo = pd.read_table(datafolder + filename_modi,
sep="\t",
header=head_len-1,
names=columns)
obs_ukmo.replace(['nan ', 'nan', ' '], np.nan, inplace=True)
# set data to numeric type
obs_ukmo = obs_ukmo.astype(float)
# add time column with datetime
# time_list = [(pd.Timedelta(val, unit='s') + datetime).round(freq='T') for val in obs_ukmo['HOUR_time']]
time_list = [(pd.Timedelta(val, unit='h') + datetime) for val in obs_ukmo['HOUR_time']]
obs_ukmo['time'] = pd.to_datetime(time_list)
# obs_ukmo.set_index('time', inplace=True)
#drop NaN column
obs_ukmo.dropna(axis=1, how='all', inplace=True)
# obs_ukmo.drop('!_!', axis=1, inplace=True)
obs_ukmo.drop('VIS\n_vis\n', axis=1, inplace=True)
#set time as index
obs_ukmo.set_index('time', inplace =True)
# obs_ukmo.rename(columns = {
# 'TEMP_2m':'ta_2', 'TEMP_10m':'ta_3', 'TEMP_25m':'ta_4',
# 'UTOT_2m':'ws_2', 'UTOT_10m':'ws_3', 'UTOT_25m':'ws_4',
# 'DIR_2m':'wd_2', 'DIR_10m':'wd_3', 'DIR_25m':'wd_4',
# 'RHUM_2m':'hur_2', 'RHUM_10m':'hur_3', 'RHUM_25m':'hur_4',
## 'WQ_2m' #
# }, inplace=True)
#remove outliers lying outside of 4 standard deviation
if remove_outliers:
obs_ukmo = obs_ukmo[(obs_ukmo-obs_ukmo.mean()) <= (4*obs_ukmo.std())]
obs_ukmo_xr = xr.Dataset.from_dataframe(obs_ukmo
# [['time', 'TEMP_2m','RHUM_10mB']]
)
if create_netcdf:
obs_ukmo_xr.to_netcdf(datafolder+filename.replace('.dat', '.temp'),
engine='netcdf4')
os.system('''
cd {0}
ncks -O --mk_rec_dmn time {1} {2}
'''.format(datafolder, filename.replace('.dat', '.temp'),
filename.replace('.dat', '.nc')))
#we can add 'rm -f {1}' after to remove temp file
if remove_modi:
os.system('''
cd {0}
rm -f {1}'''.format(datafolder, filename_modi))
return obs_ukmo_xr
def open_ukmo_rs(datafolder, filename, add_metpy_units=False):
"""
Open the radiosounding from UK MetOffice formatted under .txt,
and return it into xarray dataset with same variable names
than .nc file from cnrm.
"""
filename_modi = filename + '_modi'
os.system('''
cd {0}
sed -e 's/Latitude/Lat /g' -e 's/Longitude/Lon /g' {1} > {2}
sed -i 's/ \+ /\t/g' {2}
'''.format(datafolder, filename, filename_modi))
#read header
with open(datafolder + filename_modi) as f:
fulltext = f.readlines()
for i in [0, 4]:
line = fulltext[i]
key, value = line.split(sep='\t')
if i == 0:
datetime = pd.Timestamp(value)
if i == 4:
start_alti = float(value.replace(' m', ''))
#reard data
obs_ukmo = pd.read_table(datafolder + filename_modi,
sep="\t",
header=7)
obs_ukmo.dropna(axis=1, how='all', inplace=True)
obs_ukmo.rename(columns = {'Time':'seconds',
'Height':'height',
'Pres':'pressure',
'Temp':'temperature',
'RH':'humidity',
'Dewp':'dewPoint',
'MixR':'mixingRatio',
'Dir':'windDirection',
'Speed':'windSpeed',
'Lat':'latitude',
'Lon':'longitude',
# 'Range',
# 'Azimuth'
}, inplace=True)
units_row = obs_ukmo.iloc[0] #retrieve first row (of units)
units_row.replace('deg C', 'degC', inplace=True)
obs_ukmo.drop(index=0, inplace=True) #drop first row (units)
#convert all string number to float
obs_ukmo = obs_ukmo.astype(float)
#compute altitude ASL from height AGL
obs_ukmo['altitude'] = obs_ukmo['height'] + start_alti
units_row['altitude'] = units_row['height']
#compute datetimes from time
obs_ukmo['time'] = pd.to_timedelta(obs_ukmo['seconds'], 'S') + datetime
obs_ukmo_xr = xr.Dataset.from_dataframe(obs_ukmo)
# add units
if add_metpy_units:
raise DeprecationWarning("""metpy not used anymore in here.
No units added.""")
# for key in units_row.index:
# obs_ukmo_xr[key] = obs_ukmo_xr[key]*units(units_row[key])
return obs_ukmo_xr
def open_ukmo_lidar(datafolder,
filter_low_data=True, level_low_filter=100,
create_netcdf=True,):
"""
Open the lidar doppler data from UK MetOffice formatted under .txt,
and return it into xarray dataset with same variable names
than .nc file from cnrm.
Parameters:
datafolder: str, contains multiple files that will be concatenated
together
filter_low_data: bool, to remove or not the lowest data
that may be inacurrate
level_low_filter: float, UKMO mentions that below 100m, data may be
inacurrate.
create_netcdf: bool
"""
fnames = os.listdir(datafolder)
fnames = [f for f in fnames if '.hpl' in f] # keep only .hpl files
fnames.sort()
dict_ws = {}
dict_wd = {}
for filename in fnames:
datetime = pd.Timestamp(filename[58:73])
# datetime = filename[58:73] # string format
obs_ukmo = pd.read_table(datafolder + filename,
skiprows=1,
delim_whitespace=True, # one or more space as delimiter
names=['level_agl', 'WD', 'WS'])
#drop rows that are null
obs_ukmo = obs_ukmo[obs_ukmo['WS'] != 0]
if filter_low_data:
obs_ukmo = obs_ukmo[obs_ukmo['level_agl'] > level_low_filter]
obs_ukmo.set_index(['level_agl'], inplace=True)
dict_ws[datetime] = obs_ukmo['WS']
dict_wd[datetime] = obs_ukmo['WD']
df_ws = pd.DataFrame(dict_ws)
df_wd = pd.DataFrame(dict_wd)
obs_ukmo_xr = xr.merge([xr.DataArray(df_ws, name='WS'),
xr.DataArray(df_wd, name='WD')],)
obs_ukmo_xr = obs_ukmo_xr.rename({'dim_1': 'time'})
if create_netcdf:
out_filename = filename[:64] + '.nc' # out_filename= 'LIAISE_[...]-30MIN_L1_202107.nc'
obs_ukmo_xr.to_netcdf(datafolder + out_filename,
engine='netcdf4')
return obs_ukmo_xr
def open_uib_seb(QC_threshold = 9, create_netcdf=True):
"""
Convert the csv files coming from UIB (universidad de los baleares)
into netCDF files to be used in other functions
QC_threshold: int,
Threshold below which function does not keep the data.
1 is the highest quality data, 9 the worst
"""
filename1_orig = 'LIAISE_IRTA-CORN_UIB_SEB1-10MIN_L2.dat_orig'
filename2_orig = 'LIAISE_IRTA-CORN_UIB_SEB2-10MIN_L2.dat_orig'
datafolder = '/cnrm/surface/lunelt/data_LIAISE/irta-corn/seb/'
filename1 = filename1_orig.replace('_orig', '')