-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpipeline_functions.py
4436 lines (3544 loc) · 188 KB
/
pipeline_functions.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
'''
Urban-PLUMBER processing code
Associated with the manuscript: Harmonized, gap-filled dataset from 20 urban flux tower sites
Copyright 2021 Mathew Lipson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__title__ = "Pipeline functions for processing site information in the Urban-PLUMBER project"
__version__ = "2022-09-16"
__author__ = "Mathew Lipson"
__email__ = "[email protected]"
__description__ = 'When run on NCI:Gadi this script collects ERA5 and WFDE5 surface data and applies correction based on observations. Output intended for driving land surface models'
import numpy as np
import xarray as xr
import pandas as pd
import matplotlib.pyplot as plt
import netCDF4
import os
import sys
import glob
from datetime import datetime
from collections import OrderedDict
import statsmodels.api as sm
import qc_observations as qco
era5path = '/g/data/rt52/era5/single-levels/reanalysis'
wfdepath = '/g/data/rt52/era5-derived/wfde5/v1-1/cru'
##########################################################################
# USER INPUTS
##########################################################################
wind_hgt = 10. # era5 wind height variable (100m has poor diurnal pattern, use 10m)
img_fmt = 'png' # image saving format
##########################################################################
# main
##########################################################################
def main(datapath,sitedata,siteattrs,raw_ds,fullpipeline=True,qcplotdetail=False):
'''
This function is called from individual site scripts "create_dataset_{sitename}.py"
Main sections are:
1. CLEAN SITE OBSERVATIONS
2. EXTRACT WFDE5
3. EXTRACT ERA5
4. CORRECT ERA5
5. CORRECT ERA5 USING LINEAR REGRESSION
6. FILL FORCING VARIABLES
7. PREPEND FORCING VARIABLES WITH ERA5
8. CREATE ANALYSIS FILES
'''
extract_wfde5 = False
extract_era5 = False
if fullpipeline:
clean_obs_nc = True
correct_era5 = True
correct_era5_linear = True
create_filled_forcing = True
create_analysis = True
write_to_text = True # can also use seperate program if necessary (convert_nc_to_text.py)
else:
clean_obs_nc = False
correct_era5 = False
correct_era5_linear = False
create_filled_forcing = False
create_analysis = False
write_to_text = False
##############################################################
sitename = siteattrs['sitename']
sitepath = siteattrs['sitepath']
# raw_ds = xr.open_dataset(f'{sitepath}/timeseries/{sitename}_raw_observations_{siteattrs["out_suffix"]}.nc')
##############################################################
######## CLEAN SITE OBSERVATIONS ########
##############################################################
if clean_obs_nc:
print('cleaning observational data\n')
clean_ds = qco.main(raw_ds, sitedata, siteattrs, sitepath, plotdetail=qcplotdetail)
print('setting clean attributes\n')
clean_ds.attrs['time_analysis_start'] = raw_ds.attrs['time_coverage_start']
clean_ds.attrs['timestep_number_analysis'] = raw_ds.attrs['timestep_number_analysis']
clean_ds = set_global_attributes(clean_ds,siteattrs,ds_type='clean_obs')
clean_ds = set_variable_attributes(clean_ds)
# clean_ds = clean_ds.merge(assign_sitedata(siteattrs))
print(f'writing cleaned observations to NetCDF\n')
fpath = f'{sitepath}/timeseries/{sitename}_clean_observations_{siteattrs["out_suffix"]}.nc'
write_netcdf_file(ds=clean_ds,fpath_out=fpath)
else:
print('loading clean observations from NetCDF\n')
clean_ds = xr.open_dataset(f'{sitepath}/timeseries/{sitename}_clean_observations_{siteattrs["out_suffix"]}.nc')
calc_midday_albedo(clean_ds,siteattrs['local_utc_offset_hours'])
# observed time period
syear = pd.to_datetime(clean_ds.time.values[0]).year - 10
eyear = pd.to_datetime(clean_ds.time.values[-1]).year
##############################################################
######## EXTRACT WFDE5 ########
##############################################################
if extract_wfde5:
print('extracting WFDE5 data for site location')
watch_ds = get_wfde5_data(sitename,sitedata,syear,eyear,wfdepath)
# make directories if necessary
if not os.path.exists(f'{datapath}/{sitename}'):
os.makedirs(f'{datapath}/{sitename}')
# write
fpath = f'{datapath}/{sitename}/{sitename}_wfde5_v1-1.nc'
write_netcdf_file(ds=watch_ds,fpath_out=fpath)
else:
watch_ds = xr.open_dataset(f'{datapath}/{sitename}/{sitename}_wfde5_v1-1.nc')
##############################################################
######## EXTRACT ERA5 ########
##############################################################
if extract_era5: # from GADI
# era_ds = get_era5_main_rt52(sitename,sitedata,syear,eyear,era5path,sitepath)
print('Using GADI/RT52')
# native
print('import ERA5 site native datafile and select time of spinup and observation')
era_native = get_era5_data(sitename, sitedata, syear, eyear, era5path, sitepath)
fpath = f'{sitepath}/{sitename}_era_native.nc'
write_netcdf_file(ds=era_native,fpath_out=fpath)
# ALMA
print('convert ERA5 site raw datafile to ALMA standard variables')
era_ds = convert_era5_to_alma(era_native,siteattrs,sitename)
# make directories if necessary
if not os.path.exists(f'{datapath}/{sitename}'):
os.makedirs(f'{datapath}/{sitename}')
# write
fpath = f'{datapath}/{sitename}/{sitename}_era5_raw.nc'
write_netcdf_file(ds=era_ds,fpath_out=fpath)
add_era_vegtype(era_ds,fpath)
else: # if era5 data already pulled use:
print('loading ERA5 data for site location')
era_ds = xr.open_dataset(f'{datapath}/{sitename}/{sitename}_era5_raw.nc')
##############################################################
######## CORRECT ERA5 ########
##############################################################
if correct_era5:
print('making corrections to ERA5 data based on local site information')
corr_ds = calc_era5_corrections(era_ds,watch_ds,sitename,sitedata,sitepath,plot_bias='all',obs_ds=clean_ds)
corr_ds = set_global_attributes(corr_ds,siteattrs,ds_type='era5_corrected')
corr_ds = set_variable_attributes(corr_ds)
# write
fpath = f'{sitepath}/timeseries/{sitename}_era5_corrected_{siteattrs["out_suffix"]}.nc'
print(f'writing corrected era5 data to {fpath.split("/")[-1]}')
write_netcdf_file(ds=corr_ds,fpath_out=fpath)
else:
print('loading corrected ERA5 data for site location')
corr_ds = xr.open_dataset(f'{sitepath}/timeseries/{sitename}_era5_corrected_{siteattrs["out_suffix"]}.nc')
##############################################################
######## CORRECT ERA5 USING LINEAR REGRESSION ########
##############################################################
if correct_era5_linear:
lin_ds = calc_era5_linear_corrections(era_ds,watch_ds,clean_ds,siteattrs,sitedata)
lin_ds = set_global_attributes(lin_ds,siteattrs,ds_type='era5_linear')
lin_ds = set_variable_attributes(lin_ds)
# write
fpath = f'{sitepath}/timeseries/{sitename}_era5_linear_{siteattrs["out_suffix"]}.nc'
print(f'writing linearly debiased era5 data to {fpath.split("/")[-1]}')
write_netcdf_file(ds=lin_ds,fpath_out=fpath)
else:
print('loading corrected ERA5 data for site location')
lin_ds = xr.open_dataset(f'{sitepath}/timeseries/{sitename}_era5_linear_{siteattrs["out_suffix"]}.nc')
##############################################################
######## FILL FORCING VARIABLES ########
##############################################################
if create_filled_forcing:
print('gap filling forcing')
# get dataframes for filling
forcing_fluxes = ['SWdown', 'LWdown', 'Tair', 'Qair', 'PSurf', 'Rainf', 'Snowf', 'Wind_N','Wind_E']
filling = clean_ds.squeeze().to_dataframe()[forcing_fluxes]
qc_keys = [f'{x}_qc' for x in forcing_fluxes]
filling_qc = clean_ds.to_dataframe()[qc_keys]
corr_df = corr_ds[forcing_fluxes].sel(time=slice(str(syear),str(eyear+1))).to_dataframe()[forcing_fluxes]
instant_flux = ['Tair', 'Qair', 'PSurf', 'Wind_N','Wind_E']
average_flux = ['SWdown', 'LWdown','Rainf', 'Snowf']
if clean_ds.timestep_interval_seconds == 1800.:
print('resampling era5 data to 30Min')
era_to_fill = corr_df.resample('30Min').asfreq()
era_to_fill[instant_flux] = era_to_fill[instant_flux].interpolate()
era_to_fill[average_flux] = era_to_fill[average_flux].backfill()
max_gap = 4
elif clean_ds.timestep_interval_seconds == 3600.:
era_to_fill = corr_df.copy()
max_gap = 2
else:
print('timesteps must be 30min or 60min, check netcdf')
# 0=observed, 1=gapfilled_from_obs, 2=gapfilled_from_era5, 3=missing
for key in forcing_fluxes:
print(f'updating {key} qc flags')
filling[f'{key}_qc'] = clean_ds[f'{key}_qc'].to_series()
####################################################################
#### Step 1) Contemporaneous and nearby flux tower or weather observing sites (where available and provided by observing groups)
#### already done during site data import
####################################################################
#### Step 2) Small gaps (≤ 2 hours) are linearly interpolated from the adjoining observations
# fill small gaps linearly, qc = 1 (filled from obs)
ser_filled,qc = linearly_fill_gaps(filling[key],max_gap=max_gap,qc_flag=1)
filling[key] = ser_filled
# update qc flag with non-nan values
filling[f'{key}_qc'].update(qc)
####################################################################
#### Step 3) Larger gaps (and a 10-year spin-up period) are filled using corrected ERA5 data
# fill remaining gaps with era, qc = 2 (filled from era)
ser_filled,qc = era_fill_gaps(filling[key],era_to_fill[key],qc_flag=2)
filling[key] = ser_filled
# update qc flag with non-nan values
filling[f'{key}_qc'].update(qc)
assert filling[key].isna().sum() == 0, f'ERROR: gaps still remaining in {key}'
print('done filling gaps\n')
filled_ds = filling.to_xarray()
# use ERA5 for Snowf (all sites except JP-Yoyogi which includes snow)
# if no snow must correct observed rainf which is likely to include melted snow
if clean_ds.Snowf.to_series().count()==0:
# set observed rain and snow partitioning from era5 snowfall data
print('partitioning observed precipitation into snowfall and rainfall from era5')
obs_partition = filled_ds.to_dataframe()[['Rainf','Snowf']]
era_partition = era_to_fill.loc[clean_ds.time_coverage_start:clean_ds.time_coverage_end,['Rainf','Snowf']]
new_partition = pd.DataFrame(index=obs_partition.index, columns=['Rainf','Snowf'])
era_snowf, obs_precip = era_partition.Snowf, obs_partition.Rainf
# maintain mass balance by removing era5 snow from observed rain
new_partition[['Rainf','Snowf']],swe = partition_precip_to_snowf_rainf(era_snowf,obs_precip)
filled_ds['Rainf'].values = new_partition['Rainf'].values
filled_ds['Snowf'].values = new_partition['Snowf'].values
else:
print('not partitioning precipitation (using snow from site observations)')
print('setting attributes\n')
filled_ds.attrs['time_analysis_start'] = clean_ds.attrs['time_coverage_start']
filled_ds.attrs['timestep_number_analysis'] = clean_ds.attrs['timestep_number_analysis']
filled_ds = set_global_attributes(filled_ds,siteattrs,ds_type='forcing')
filled_ds = set_variable_attributes(filled_ds)
# print(f'writing filled observations to NetCDF\n')
# fpath = f'{sitepath}/timeseries/{sitename}_filled_observations_{siteattrs["out_suffix"]}.nc'
# write_netcdf_file(ds=filled_ds,fpath_out=fpath)
##############################################################
######## PREPEND FORCING VARIABLES WITH ERA5 ########
##############################################################
print('combining era5 and obs data')
# if clean_ds.timestep_interval_seconds == 1800.:
# print('resampling era5 data to 30Min')
# rsmp_ds = corr_ds.sel(time=slice(str(syear),str(eyear))).resample(time='30Min').interpolate()
# else:
# rsmp_ds = corr_ds.sel(time=slice(str(syear),str(eyear))).copy()
era_to_fill_ds = era_to_fill.to_xarray()
# add qc flag = 2 for all notnull values in era, else = 3
for key in forcing_fluxes:
era_to_fill_ds['%s_qc' %key] = xr.DataArray(
data = np.where(era_to_fill_ds[key].notnull(),2,3),
dims =['time'],
coords = {'time': era_to_fill_ds.time.values})
# combine forcing and era-corrected dataset, using forcing where there is overlap
final_period = clean_ds.time_coverage_end
forcing_ds = filled_ds.combine_first(era_to_fill_ds).sel(time=slice(None, final_period))
forcing_ds = build_new_dataset_forcing(forcing_ds)
print('setting forcing attributes\n')
forcing_ds.attrs['time_analysis_start'] = pd.to_datetime(raw_ds.time[0].values).strftime('%Y-%m-%d %H:%M:%S')
forcing_ds.attrs['timestep_number_analysis'] = len(raw_ds.time)
forcing_ds = set_global_attributes(forcing_ds,siteattrs,ds_type='forcing')
forcing_ds = set_variable_attributes(forcing_ds)
forcing_ds = forcing_ds.merge(assign_sitedata(siteattrs))
# write
fpath = f'{sitepath}/timeseries/{sitename}_metforcing_{siteattrs["out_suffix"]}.nc'
write_netcdf_file(ds=forcing_ds,fpath_out=fpath)
else:
# print('loading filled observations from NetCDF\n')
# filled_ds = xr.open_dataset(f'{sitepath}/timeseries/{sitename}_filled_observations_{siteattrs["out_suffix"]}.nc')
print('loading forcing from NetCDF\n')
forcing_ds = xr.open_dataset(f'{sitepath}/timeseries/{sitename}_metforcing_{siteattrs["out_suffix"]}.nc')
if write_to_text:
print('writing raw obs to text file')
fpath = f'{sitepath}/timeseries/{sitename}_raw_observations_{siteattrs["out_suffix"]}.txt'
write_netcdf_to_text_file(ds=raw_ds,fpath_out=fpath)
print('writing clean obs to text file')
fpath = f'{sitepath}/timeseries/{sitename}_clean_observations_{siteattrs["out_suffix"]}.txt'
write_netcdf_to_text_file(ds=clean_ds,fpath_out=fpath)
# print('writing era5 corrected to text file')
# fpath = f'{sitepath}/timeseries/{sitename}_era5_corrected_{siteattrs["out_suffix"]}.txt'
# write_netcdf_to_text_file(ds=corr_ds,fpath_out=fpath)
print('writing met forcing to text file')
fpath = f'{sitepath}/timeseries/{sitename}_metforcing_{siteattrs["out_suffix"]}.txt'
write_netcdf_to_text_file(ds=forcing_ds,fpath_out=fpath)
# ##############################################################
# ######## CREATE ANALYSIS FILES (for modelevaluation.org) ########
# ##############################################################
# if create_analysis:
# data = clean_ds.squeeze().to_dataframe()
# times = forcing_ds.time.to_series().index
# data = data.reindex(times)
# analysis_ds = build_new_dataset_analysis(data,sitedata)
# print('setting analysis attributes\n')
# analysis_ds.attrs['time_analysis_start'] = pd.to_datetime(raw_ds.time[0].values).strftime('%Y-%m-%d %H:%M:%S')
# analysis_ds.attrs['timestep_number_analysis'] = len(raw_ds.time)
# analysis_ds = set_global_attributes(analysis_ds,siteattrs,ds_type='analysis')
# print('writing analysis NetCDF')
# fpath = f'{sitepath}/timeseries/{sitename}_analysis_{siteattrs["out_suffix"]}.nc'
# write_netcdf_file(ds=analysis_ds,fpath_out=fpath)
# else:
# print('loading analysis from NetCDF\n')
# analysis_ds = xr.open_dataset(f'{sitepath}/timeseries/{sitename}_analysis_{siteattrs["out_suffix"]}.nc')
return raw_ds, clean_ds, watch_ds, era_ds, corr_ds, lin_ds, forcing_ds
###############################################################################
# Shared functions
###############################################################################
def prep_site(sitename, sitepath, out_suffix, sitedata_suffix, long_sitename,
local_utc_offset_hours, obs_contact, obs_reference, obs_comment,
history, photo_source, get_globaldata, datapath):
'''
prepare site folders, attributes and show local characteristics from global datasets
run at start of create_dataset_{sitename}.py main function
'''
for dirname in ['processing','precip_plots','era_correction','obs_plots','images','timeseries']:
# make directories if necessary
if not os.path.exists(f'{sitepath}/{dirname}'):
print(f'making {dirname} dir')
os.makedirs(f'{sitepath}/{dirname}')
print('loading site parameters for %s' %sitename)
fpath = f'{sitepath}/{sitename}_sitedata_{sitedata_suffix}.csv'
sitedata_full = pd.read_csv(fpath, index_col=1, delimiter=',')
sitedata = pd.to_numeric(sitedata_full['value'])
check_area_fractions(sitedata)
if get_globaldata:
print('loading global paramaters for site:\n')
globalpath = f'{datapath}/global_datasets'
_,_,_ = get_global_soil(globalpath,sitedata)
_,_ = get_global_qanth(globalpath,sitedata)
_,_ = get_climate(globalpath,sitedata)
# site attrs
print('setting attributes\n')
siteattrs = pd.Series(name='siteattrs',dtype='object')
siteattrs['sitename'] = sitename
siteattrs['sitepath'] = sitepath
siteattrs['out_suffix'] = out_suffix
siteattrs['sitedata_suffix'] = sitedata_suffix
siteattrs['long_sitename'] = long_sitename
siteattrs['local_utc_offset_hours'] = local_utc_offset_hours
siteattrs['obs_contact'] = obs_contact
siteattrs['obs_reference'] = obs_reference
siteattrs['obs_comment'] = obs_comment
siteattrs['history'] = history
siteattrs['photo_source'] = photo_source
fpath = f'{sitepath}/{sitename}_siteattrs_{out_suffix}.csv'
siteattrs.to_csv(fpath,header=True,index=True)
siteattrs = pd.read_csv(fpath,index_col=0,squeeze=True)
# reformat loaded utc_offset as float
siteattrs['local_utc_offset_hours'] = float(siteattrs['local_utc_offset_hours'])
return sitedata,siteattrs
def set_raw_attributes(raw_ds, siteattrs):
sitename = siteattrs['sitename']
sitepath = siteattrs['sitepath']
print('setting raw attributes\n')
raw_ds.attrs['time_analysis_start'] = pd.to_datetime(raw_ds.time[0].values).strftime('%Y-%m-%d %H:%M:%S')
raw_ds.attrs['timestep_number_analysis'] = len(raw_ds.time)
raw_ds = set_global_attributes(raw_ds,siteattrs,ds_type='raw_obs')
raw_ds = set_variable_attributes(raw_ds)
print(f'writing raw observations to NetCDF\n')
fpath = f'{sitepath}/timeseries/{sitename}_raw_observations_{siteattrs["out_suffix"]}.nc'
write_netcdf_file(ds=raw_ds,fpath_out=fpath)
return raw_ds
def post_process_site(sitedata,siteattrs,datapath,
raw_ds,forcing_ds,clean_ds,era_ds,watch_ds,corr_ds,lin_ds,
forcingplots,create_outofsample_obs):
'''
final site data plotting and error calculation
runs after pipeline main from create_dataset_{sitename}.py
'''
sitename = siteattrs['sitename']
sitepath = siteattrs['sitepath']
# make website
create_markdown_observations(forcing_ds,siteattrs)
# compare corrected, era5 and wfde5 (watch) errors
compare_corrected_errors(clean_ds,era_ds,watch_ds,corr_ds,lin_ds,sitename,sitepath,'all')
if forcingplots:
plot_forcing(datapath,siteattrs,forcing_ds,with_era=False)
if create_outofsample_obs:
in_ds, out_ds = test_out_of_sample(clean_ds,era_ds,watch_ds,sitedata,siteattrs)
# Snow partitioning plot
plot_snow_partitioning(raw_ds,forcing_ds,era_ds,sitepath,sitename)
return
def get_era5_data(sitename,sitedata,syear,eyear,era5path,sitepath):
'''
get native era5 netcdf variables from raijin and combine into xarray dataset
'''
# era5 variables to collect from gadi
vz = '%iv' %wind_hgt # default v10
uz = '%iu' %wind_hgt # default u10
# ncvars = ['msdwswrf','msnswrf','msdwlwrf','msnlwrf','2t','2d','sp',vz,uz,'mtpr','msr','msshf','mslhf']
ncvars = ['msdwswrf','msdwlwrf','2t','2d','sp',vz,uz,'mtpr','msr']
if sitename in ['SG-TelokKurau','SG-TelokKurau06']: # nearest era tile over water, move to land
sitedata['latitude'] = sitedata['latitude'] + 0.25
sitedata['longitude'] = sitedata['longitude'] - 0.25
# longitude correction for era5 using 0<lon<360
lat = sitedata['latitude']
lon = sitedata['longitude']
if lon < 0.:
lon = lon + 360.
assert (0 <= lon < 360), 'longitude in era5 needs to be 0<lon<360'
assert (-90 <= lat < 90), 'latutude in era5 needs to be -90<lat<90'
ds = xr.Dataset()
years = [str(year) for year in range(syear,eyear+1)]
# loop through variables
for ncvar in ncvars:
print('collecting %s data' %ncvar)
files = []
# get list of files in path using glob wildcard
for year in years:
files = sorted(glob.glob('%s/%s/%s/*' %(era5path,ncvar,year)))
assert len(files)>0, 'no files found in %s/%s/%s/*' %(era5path,ncvar,year)
for file in files:
print('opening %s' %file)
tmp = xr.open_dataset(file).sel(latitude=sitedata['latitude'],
longitude=sitedata['longitude'],
method='nearest')
ds = xr.merge([ds,tmp])
longname = tmp[list(tmp.keys())[0]].long_name.lower()
print('done merging %s (%s)' %(longname,ncvar))
############################################################################
ds.attrs['source'] = era5path
# get static information (veg frac, type, soil, geopotential, land/sea mask, roughness)
for ncvar in ['cvl','cvh','tvl','tvh','slt','z','lsm','fsr']:
static = xr.open_dataset(f'{era5path}/{ncvar}/2000/{ncvar}_era5_oper_sfc_20000101-20000131.nc').sel(
latitude=sitedata['latitude'],longitude=sitedata['longitude'],time='2000-01-01 00:00', method='nearest')
ds[ncvar] = static[ncvar]
return ds
############################################################################
def convert_era5_to_alma(era5,siteattrs,sitename):
'''
opens ERA5 native datafile from site and converts to alma standard variables
'''
# convert dewtemp to specific humidity data
Qdata_np = convert_dewtemp_to_qair(
dewtemp = era5['d2m'].values,
temp = era5['t2m'].values,
pressure = era5['sp'].values)
Qair_xr = xr.DataArray(Qdata_np, coords=[era5.time.values], dims='time')
# convert era5 to alma form
ds = xr.Dataset()
ds = ds.assign( time = era5['time'])
ds = ds.assign( SWdown = era5['msdwswrf'],
LWdown = era5['msdwlwrf'],
Wind_N = era5['v%i' %wind_hgt],
Wind_E = era5['u%i' %wind_hgt],
Wind = (era5['v%i' %wind_hgt]**2 + era5['u%i' %wind_hgt]**2)**(1/2),
PSurf = era5['sp'],
Tair = era5['t2m'],
Qair = Qair_xr,
Rainf = era5['mtpr'] - era5['msr'],
Snowf = era5['msr'],
era_wind_hgt = wind_hgt)
for ncvar in ['cvl','cvh','tvl','tvh','slt','z','lsm','fsr']:
ds[ncvar] = era5[ncvar]
# # setting unphysical negative values to zero
ds.Rainf.values = ds.Rainf.where(ds.Rainf>1E-9,0.).values
ds.Snowf.values = ds.Snowf.where(ds.Snowf>1E-9,0.).values
ds.SWdown.values = ds.SWdown.where(ds.SWdown>1E-9,0.).values
ds = set_variable_attributes(ds)
ds = set_global_attributes(ds,siteattrs,ds_type='era5_raw')
return ds
###############################################################################
def correct_wind(ref_wind,local_z0,local_d0,local_wind_hgt,ref_wind_hgt,ref_z0,ref_d0,mode):
'''correct wind speed assuming log wind profile assuming all neutral conditions
Parameters
----------
ref_wind [m/s] reanalysis grid scalar wind speed at ref_wind_hgt
local_z0 [m] local zero-plane displacment
local_d0 [m] local roughness length (assumed constant)
local_wind_hgt [m] local site measurement height for wind
ref_wind_hgt [m] reanlysis site measurement height for wind
ref_z0 [m] reanalysis grid roughness length (assumed constant)
ref_d0 [m] reanalysis grid zero-plane displacment
mode [0,1] two different methods to calculate:
mode=0: including displacement height from Goret et al. 2019 Eq 9 (https://doi.org/10.1016/j.aeaoa.2019.100042)
mode=1: excluding displacement height from https://websites.pmc.ucsc.edu/~jnoble/wind/extrap/
Method results depend on assumptions about grid z_0 and d_0,
method=1 results in higher wind speeds overall
'''
# ref_wind_hgt = 10. # basis of measurement height for era5
if mode == 0: # log law with displacement height
local_wind = ref_wind*( ( np.log((local_wind_hgt-local_d0)/local_z0) )/( np.log((ref_wind_hgt-ref_d0)/ref_z0) ) )
if mode == 1: # log law described at: https://websites.pmc.ucsc.edu/~jnoble/wind/extrap/
local_wind = ref_wind*(np.log(local_wind_hgt/local_z0))/(np.log(ref_wind_hgt/ref_z0))
return local_wind
def correct_pressure(ref_height,ref_temp,ref_pressure,local_temp,local_height,mode=1):
'''correct pressure to local site based on height difference
Parameters
----------
ref_height [m] reference (converted from) height above sea level (asl)
ref_temp [K] reference (converted from) 2m air temperature
ref_pressure [Pa] reference (converted from) surface air pressure
local_temp [K] local site 2m air temperature
local_height [m] local site height for correction
mode [0,1] two different methods to calculate:
- 0: Hypsometric equation (assuming constant temperature)
- 1: Barometric equation (includes lapse rate)
- 2: Hydrostatic equation P = rho * grav * h_diff
- 3: WATCH method from Weeedon et al. (2010)
Negligible difference between methods
'''
rd = 287.04 # Gas constant for dry air [J K^-1 kg^-1]
grav = 9.80616 # gravity [m s^-2]
env_lapse = 6.5/1000. # environmental lapse rate [K m^-1]
if mode == 0: # hypsometric equation assumes constant temperature
local_pressure = ref_pressure*np.exp( (grav*(ref_height-local_height))/(rd*ref_temp) )
elif mode == 1: # barometric equation with varying temperature
local_pressure = ref_pressure*(ref_temp/local_temp)**(grav/(-env_lapse*rd))
elif mode == 2: # hydrostatic equation
air_density = 1.2
local_pressure = ref_pressure + air_density * grav * (ref_height - local_height)
elif mode ==3: # WATCH method
# weedon et al (2010) eq. 2
ref_temp_sea_level = ref_temp + ref_height * env_lapse
# weedon et al (2010) eq. 7
ref_pressure_sea_level = ref_pressure / ( ref_temp/ ref_temp_sea_level )**(grav/(-env_lapse*rd))
# weedon et al (2010) eq. 9
local_temp_sea_level = local_temp + ref_height * env_lapse
# weedon et al (2010) eq. 10
local_pressure = ref_pressure_sea_level * ( local_temp/local_temp_sea_level )**(grav/(-env_lapse*rd))
else:
raise SystemExit(0)
local_pressure = np.where(local_pressure < 90000, 100000, local_pressure)
return local_pressure
def calc_esat(temp,pressure,mode=0):
'''Calculates vapor pressure at saturation
From Weedon 2010, through Buck 1981:
New Equations for Computing Vapor Pressure and Enhancement Factor, Journal of Applied Meteorology
----------
temp [K] 2m air temperature
pressure [Pa] air pressure
mode [0,1] two different methods to calculate:
mode=0: from Wheedon et al. 2010
mode=1: from Ukkola et al., 2017
NOTE: mode 0 and 1 nearly identical
Ukkola et al uses the ws=qs approximation (which is not used here, see Weedon 2010)
'''
# constants
Rd = 287.05 # specific gas constant for dry air
Rv = 461.52 #specific gas constant for water vapour
Epsilon = Rd/Rv # = 0.622...
Beta = (1.-Epsilon) # = 0.378 ...
temp_C = temp - 273.15 # temperature conversion to [C]
if mode == 0: # complex calculation from Weedon et al. 2010
# values when over: water, ice
A = np.where( temp_C > 0., 6.1121, 6.1115 )
B = np.where( temp_C > 0., 18.729, 23.036 )
C = np.where( temp_C > 0., 257.87, 279.82 )
D = np.where( temp_C > 0., 227.3, 333.7 )
X = np.where( temp_C > 0., 0.00072, 0.00022 )
Y = np.where( temp_C > 0., 3.2E-6, 3.83E-6 )
Z = np.where( temp_C > 0., 5.9E-10, 6.4E-10 )
esat = A * np.exp( ((B - (temp_C/D) ) * temp_C)/(temp_C + C))
enhancement = 1. + X + pressure/100. * (Y + (Z*temp_C**2))
esat = esat*enhancement*100.
elif mode == 1:
'''simpler calculation from Ukkola et al., 2017
From Jones (1992), Plants and microclimate: A quantitative approach
to environmental plant physiology, p110 '''
esat = 613.75*np.exp( (17.502*temp_C)/(240.97+temp_C) )
else:
raise SystemExit(0)
return esat
def calc_qsat(esat,pressure):
'''Calculates specific humidity at saturation
Parameters
----------
esat [Pa] vapor pressure at saturation
pressure [Pa] air pressure
Returns
-------
qsat [g/g] specific humidity at saturation
'''
# constants
Rd = 287.05 # specific gas constant for dry air
Rv = 461.52 #specific gas constant for water vapour
Epsilon = Rd/Rv # = 0.622...
Beta = (1.-Epsilon) # = 0.378 ...
qsat = (Epsilon*esat)/(pressure - Beta*esat)
return qsat
def calc_density(temp,pressure):
'''https://www.omnicalculator.com/physics/air-density
'''
Rd = 287.05 # specific gas constant for dry air
Rv = 461.52 #specific gas constant for water vapour
esat = calc_esat(temp,pressure)
density = (pressure / (Rd * temp) ) + ( esat / (Rv * temp) )
return density
###############################################################################
################################# conversions #################################
###############################################################################
def convert_dewtemp_to_qair(dewtemp,temp,pressure,mode=0):
''' using equations from Weedon 2010 & code from Cucchi 2020 '''
# calculate saturation vapor pressure
esat = calc_esat(temp,pressure)
# calculate saturation vapor pressure at dewpoint
esat_dpt = calc_esat(dewtemp,pressure)
# calculate saturation specific humidity
qsat = calc_qsat(esat,pressure)
# calculate specific humidity
qair = qsat * (esat_dpt/esat)
return qair
def convert_dewtemp_to_rh(dewtemp,temp,pressure):
''' using equations from Weedon 2010 & code from Cucchi 2020 '''
# calculate saturation vapor pressure
esat = calc_esat(temp,pressure)
# calculate saturation vapor pressure at dewpoint
esat_dpt = calc_esat(dewtemp,pressure)
# calculate saturation specific humidity
qsat = calc_qsat(esat,pressure)
# calculate relative humidity
rh = esat_dpt/esat*100
assert rh.where(rh<=105).all(), 'relative humidity values > 105. check input'
assert rh.where(rh>0).any(), 'relative humidity values < 0. check input'
assert rh.max()>1., 'relative humidity values betwen 0-1 (should be 0-100)'
return rh
def convert_rh_to_qair(rh,temp,pressure):
''' using equations from Weedon 2010 & code from Cucchi 2020 '''
assert rh.where(rh<=105).all(), 'relative humidity values > 105. check input'
assert rh.where(rh>0).any(), 'relative humidity values < 0. check input'
assert rh.max()>1., 'relative humidity values betwen 0-1 (should be 0-100)'
# calculate saturation vapor pressure
esat = calc_esat(temp,pressure)
# calculate saturation specific humidity
qsat = calc_qsat(esat,pressure)
# calculate specific humidity
qair = qsat*rh/100.
return qair
def convert_qair_to_rh(qair,temp,pressure):
''' using equations from Weedon 2010 & code from Cucchi 2020 '''
# calculate saturation vapor pressure
esat = calc_esat(temp,pressure)
# calculate saturation specific humidity
qsat = calc_qsat(esat,pressure)
# calculate relative humidity
rh = 100.*qair/qsat
assert rh.where(rh<=105).all(), 'relative humidity values > 105. check input'
assert rh.where(rh>0).any(), 'relative humidity values < 0. check input'
assert rh.max()>1., 'relative humidity values betwen 0-1 (should be 0-100)'
return rh
def convert_vapour_pressure_to_qair(e,temp,pressure):
''' using equations from Weedon 2010 & code from Cucchi 2020 '''
# calculate saturation vapor pressure
esat = calc_esat(temp,pressure)
# calculate saturation specific humidity
qsat = calc_qsat(esat,pressure)
# calculate specific humidity
rh = e/esat*100
qair = qsat*rh/100.
return qair
def convert_uv_to_wdir(u,v):
''' Converts 2 component wind velocity to wind direction scalar
NOTE: wdir is wind direction FROM
Parameters
----------
u (np array): eastward wind component [m/s]
v (np array): northward wind component [m/s]
Returns
------
wdir (np array): wind direction from North [deg]
'''
wdir = (180./np.pi)*np.arctan2(u, v) - 180
# convert negative angles to positive
wdir = np.where(wdir<0, wdir+360., wdir)
return wdir
def convert_uv_to_wind(u,v):
''' Converts 2 component wind velocity to wind speed scalar
Parameters
----------
u (np array): eastward wind component [m/s]
v (np array): northward wind component [m/s]
Returns
------
wind (np array): wind speed scalar [m/s]
'''
wind = np.sqrt(u**2 + v**2)
return wind
def convert_wdir_to_uv(speed,wind_dir_from):
''' Converts 2 component wind velocity to wind direction scalar
NOTE: wdir is wind direction FROM by default
see: https://unidata.github.io/MetPy/latest/_modules/metpy/calc/basic.html#wind_components
Parameters
----------
u (np array): eastward wind component [m/s]
v (np array): northward wind component [m/s]
Returns
------
wdir (np array): wind direction from North [deg]
'''
wdir_rad = wind_dir_from*np.pi/180.
u = -speed * np.sin(wdir_rad)
v = -speed * np.cos(wdir_rad)
return u,v
def convert_ustar_to_qtau(ustar,temp,pressure,air_density):
qtau = ustar**2/air_density
return qtau
def convert_qtau_to_ustar(qtau,temp,pressure,air_density):
ustar = np.sqrt(qtau*air_density)
return ustar
def calc_site_roughness(bldhgt_ave,sigma_h,lambda_p,lambda_pv,lambda_f,bldhgt_max=None,mode=0):
'''estimate urban site roughness length for momentum and zero-plane displacement based on various methods
as described in Grimmond and Oke (1999): Aerodynamic Properties of Urban Areas Derived from Analysis of Surface Form .
modes: four different morphometric methods to calculate roughness and displacement:
- 0: Macdonald et al. 1998: An improved method for the estimation of surface roughness of obstacle arrays
- 1: Kent et al 2017: Aerodynamic roughness parameters in cities: Inclusion of vegetation
- 2: Millward-Hopkins et al., (2011) per Kent et al. 2017 eq 11 and 12 # TYPO IN EQ 12 OF KENT PAPER
- 3: Kanda et al., 2013
Inputs
------
bldhgt_ave [m] : building mean height
sigma_h [m] : building height standard deviation
lambda_p [0-1] : building plan area fraction
lambda_pv [0-1]: tree plan area fraction
lambda_f [1] : wall frontal area fraction
bldhgt_max [m] : maximum building height (if none assume 1.25 times SD)
Returns
-------
zd [m] zero-plane displacement
z0 [m] rougness length for momentum
Warning
-------
in mode=0 wall frontal area (assuming random canyon orientation) calculated from Porsen et al 2010 (DOI:10.1002/qj.668)
in mode=1 (including vegetation), vegetation frontal area index assumed to be equal to tree plan fraction (from Table 1 in Kent et al 2017)
in mode=3 (Kanda) maximum building height assumed to be 2 standard deviations
'''
vonkarm = 0.4
dragbld = 1.2
if mode==0:
print('zd,z0 from Macdonald et al. 1998')
alpha = 4.43 # for staggered arrays
beta = 1.0 # for staggered arrays
zd = (1. + alpha**(-lambda_p)*(lambda_p - 1.))*bldhgt_ave # eq 23 from Mac1998
z0 = ((1. - zd/bldhgt_ave) * np.exp( -1.*(0.5*beta*(dragbld/vonkarm**2)*(1.-zd/bldhgt_ave)*lambda_f)**(-0.5) ))*bldhgt_ave # eq 26 from Mac1998
if mode == 1: # with veg from Kent et al (2018) https://doi.org/10.1007/s11252-017-0710-1
print('zd,z0 from Macdonald with vegetation from Kent et al. 2017 and 2018')
# Aerodynamic roughness variation with vegetation: analysis in a suburban neighbourhood and a city park
alpha = 4.43 # for staggered arrays
beta = 1.0 # for staggered arrays
lambda_fv = lambda_pv # estimated equality based on Table 1 of Kent et al 2017 for different sites
P_3D = 0.4 # leaf-on porosity
lambda_tot = (lambda_p + lambda_pv*(1. - P_3D)) # eq 4 from Kent et al (2018)
Pv = (-1.251*P_3D**2 + 0.489*P_3D + 0.803)/dragbld # eq 7 from Kent et al (2018)
weighted_frontal_area = lambda_f + lambda_fv*Pv
zd = (1. + alpha**(-lambda_tot)*(lambda_tot-1.))*bldhgt_ave # eq 5
z0 = (1. - zd/bldhgt_ave)*np.exp( -1.*(0.5*beta*(dragbld/vonkarm**2)*(1.-zd/bldhgt_ave)*weighted_frontal_area)**(-0.5) )*bldhgt_ave # eq 6
if mode == 2: # Millward-Hopkins et al. (2011), per Kent et al. 2017 eq 11 and 12
print('zd,z0 from Millward-Hopkins et al. 2011, per Kent et al. 2017 eq 11 and 12')
MhoUzd_on_Hav_A = (19.2*lambda_p - 1. + np.exp(-19.2*lambda_p))/(19.2*lambda_p*(1.- np.exp(-19.2*lambda_p)))
MhoUzd_on_Hav_B = (117*lambda_p + (187.2*lambda_p**3 - 6.1)*(1.- np.exp(-19.2*lambda_p)) )/( (1.+114*lambda_p + 187*lambda_p**3)*(1.-np.exp(-19.2*lambda_p)) )
MhoUzd_on_Hav = np.where( lambda_p >= 0.19, MhoUzd_on_Hav_A, MhoUzd_on_Hav_B )
Mho_exp = np.exp( -1.*(0.5*dragbld*vonkarm**(-2)*lambda_f)**(-0.5) )
MhoUz0_on_Hav = ( (1. - MhoUzd_on_Hav)*Mho_exp)
zd = bldhgt_ave*(MhoUzd_on_Hav + ((0.2375 * np.log(lambda_p) + 1.1738)*(sigma_h/bldhgt_ave)) )
# z0 = bldhgt_ave*(MhoUz0_on_Hav + (np.exp(0.8867*lambda_f) - 1.)*(sigma_h/bldhgt_ave)**(np.exp(2.3271*lambda_f))) # TYPO IN KENT ET AL PAPER
z0 = bldhgt_ave*(MhoUz0_on_Hav + np.exp(0.8867*lambda_f - 1.)*(sigma_h/bldhgt_ave)**(np.exp(2.3271*lambda_f))) # based on UMEP
if mode == 3:
print('zd,z0 Kanda et al 2013')
alpha = 4.43 # for staggered arrays
beta = 1.0 # for staggered arrays
if bldhgt_max==None:
bldhgt_max = 1.5*sigma_h + bldhgt_ave # assume bldhgt_max
# bldhgt_max = 12.51*sigma_h**0.77 # eq 3 from Kanda et al 2013
# first calculate macdonald et al 1998 (for later scaling)