-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoptimisation.py
More file actions
2805 lines (2754 loc) · 180 KB
/
optimisation.py
File metadata and controls
2805 lines (2754 loc) · 180 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
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 13:52:00 2019
@author: Bosman Peter
"""
import numpy as np
import copy as cp
import forwardmodel as fwdm
import inverse_modelling as im
from scipy import optimize
import matplotlib.pyplot as plt
import shutil
import os
from joblib import Parallel, delayed
import pandas as pd
import glob
import matplotlib.style as style
import pickle
style.use('classic')
##################################
###### user input: settings ######
##################################
ana_deriv = True #use analytical or numerical derivative
use_backgr_in_cost = True #include the background (prior) part of the cost function
write_to_f = True #write output and figures to files
use_ensemble = True #use an ensemble of optimisations
if use_ensemble:
nr_of_members = 175 #number of members in the ensemble of optimisations (including the one with unperturbed prior)
use_covar_to_pert = True #whether to take prior covariance (if specified) into account when perturbing the ensemble
pert_non_state_param = False #perturb parameters that are not in the state
est_post_pdf_covmatr = True #estimate the posterior pdf and covariance matrix of the state (and more)
if est_post_pdf_covmatr:
nr_bins = int(nr_of_members/10) #nr of bins for the pdfs
succes_opt_crit = 2.0 #the chi squared at which an optimisation is considered successful (lower or equal to is succesfull)
pert_obs_ens = False #Perturb observations of every ensemble member (except member 0)
if pert_obs_ens:
use_sigma_O = False #If True, the total observational error is used to perturb the obs, if False only the measurement error is used
plot_perturbed_obs = False #Plot the perturbed observations of the ensemble members
pert_Hx_min_sy_ens = True #Perturb the data part of the cost function (in every ensemble member except member 0), by perturbing H(x) - sy with a random number from a distribution with standard deviation sigma_O
print_status_dur_ens = False #whether to print state etc info during ensemble of optimisations (during member 0 printing will always take place)
estimate_model_err = False #estimate the model error standard deviations by perturbing specified non-state parameters
if estimate_model_err:
nr_of_members_moderr = 30 #number of members for the ensemble that estimates the model error
imposeparambounds = True #force the optimisation to keep parameters within specified bounds (tnc only) and when using ensemble, keep priors within bounds (tnc and bfgs)
paramboundspenalty = False #add a penalty to the cost function when parameter bounds exceeded in the optimisation
if paramboundspenalty:
setNanCostfOutBoundsTo0 = True #when cost function becomes nan when params outside specified bounds, set cost func to zero before adding penalty (nan + number gives nan)
penalty_exp = 60 #exponent to use in the penalty function (see manual)
remove_prev = True #Use with caution, be careful for other files in working directory! Removes certain files that might have remained from previous optimisations. See manual for more info on what files are removed
abort_slow_minims = True #Abort minimisations that proceed too slow (can be followed by a restart)
optim_method = 'tnc' #bfgs or tnc, the chosen optimisation algorithm. tnc recommended
if optim_method == 'tnc':
maxnr_of_restarts = 1 #The maximum number of times to restart the optimisation if the cost function is not as low as specified in stopcrit. Only implemented for tnc method at the moment.
if maxnr_of_restarts > 0:
stopcrit = 40.0#If the cost function is equal or lower than this value, no restart will be attempted
disp_fmin_tnc = False # If False, no messages from optimize.fmin_tnc function will be shown during minimisation
elif optim_method == 'bfgs':
gtol = 1e-05 # A parameter for the bfgs algorithm. From scipy documentation: 'Gradient norm must be less than gtol before successful termination.'
if estimate_model_err or use_ensemble:
run_multicore = True #Run part of the code on multiple cores simultaneously
if run_multicore:
max_num_cores = 'all' #'all' to use all available cores, otherwise specify an integer (without quotation marks)
set_seed = True #Set the seed in case the output should be reproducable
if set_seed:
seedvalue = 18 #the chosen value of the seed. No floating point numbers and no negative numbers
discard_nan_minims = False #if False, if in a minimisation nan is encountered, it will use the state from the best simulation so far, if True, the minimisation will result in a state with nans
use_mean = False #switch for using mean of obs over several days (and mean during hour)
use_weights = True #weights for the cost function, to enlarge or reduce the importance of certain obs, or to modify the relative importance of the obs vs the background part
if use_weights:
weight_morninghrs = 1 #to change weights of obs in the morning (the hour at which the morning ends is specified in variable 'end_morninghrs'), when everything less well mixed. 1 means equal weights compared to the other parts of the day
end_morninghrs = 10 #At all times smaller than this time (UTC, decimal hour), weight_morninghrs is applied
if (use_backgr_in_cost and use_weights):
obs_vs_backgr_weight = 1.0 # a scaling factor for the importance of all the observations in the cost function
if write_to_f:
wr_obj_to_pickle_files = True #write certain variables to files for possible postprocessing later
figformat = 'eps' #the format in which you want figure output, e.g. 'png'
plot_errbars = True #plot error bars in the figures
if plot_errbars:
plot_errbars_at_sca_obs = True #The y-location where to plot the error bars in the observation fit figures, if True the error bars will be placed around the scaled observations (if obs scales are used).
plotfontsize = 12 #plot font size, except for legend
legendsize = plotfontsize - 1
######################################
###### end user input: settings ######
######################################
plt.rc('font', size=plotfontsize)
#some input checks
if use_ensemble:
if (nr_of_members < 2 or type(nr_of_members) != int):
raise Exception('When use_ensemble is True, nr_of_members should be an integer and > 1')
if est_post_pdf_covmatr and not (pert_obs_ens or pert_Hx_min_sy_ens):
raise Exception('est_post_pdf_covmatr is set to True, but both switches pert_obs_ens and pert_Hx_min_sy_ens are set to False')
if pert_Hx_min_sy_ens and pert_obs_ens:
raise Exception('pert_Hx_min_sy_ens and pert_obs_ens should not both be set to True')
if write_to_f:
if type(figformat) != str:
raise Exception('figformat should be of type str, e.g. \'png\'')
if use_ensemble or estimate_model_err:
if run_multicore:
if not (max_num_cores == 'all' or type(max_num_cores) == int):
raise Exception('Invalid input for max_num_cores')
elif type(max_num_cores) == int:
if max_num_cores < 2:
raise Exception('max_num_cores should be larger or equal than 2')
if write_to_f:
if wr_obj_to_pickle_files:
vars_to_pickle = ['priormodel','priorinput','obsvarlist','disp_units','disp_units_par','display_names','disp_nms_par','optim','obs_times','measurement_error','optimalinput','optimalinput_onsp','optimalmodel','optimalmodel_onsp','PertData_mems'] #list of strings
for item in vars_to_pickle:
if item in vars(): #check if variable exists, if so, delete so we do not write anything from a previous script/run to files
del(vars()[item])
storefolder_objects = 'pickle_objects' #the folder where to store pickled variables when wr_obj_to_pickle_files == True
#remove previous files
if remove_prev:
filelist_list = []
filelist_list += [glob.glob('Optimfile*')] #add Everything starting with 'Optimfile' to the list
filelist_list += [glob.glob('Gradfile*')]
filelist_list += [glob.glob('Optstatsfile.txt')]
filelist_list += [glob.glob('Modelerrorfile.txt')]
filelist_list += [glob.glob('pdf_posterior*')]
filelist_list += [glob.glob('pdf_nonstate_*')]
filelist_list += [glob.glob('fig_fit*')]
filelist_list += [glob.glob('fig_obs*')]
filelist_list += [glob.glob('pp_*')]
filelist_list += [glob.glob(storefolder_objects+'/*')]
for filelist in filelist_list:
for filename in filelist:
if os.path.isfile(filename): #in case file occurs in two filelists in filelist_list, two attempts to remove would give error
os.remove(filename)
##################################
###### user input: load obs ######
##################################
canopy_height = 0 #m
#constants
Eps = 18.005/28.964 #p3.3 intro atm
g = 9.81
selectedyears = [2003.]
selectedmonths = [9]
selectedday = 25 #only used when not use_mean = True
selecteddays = [24,25,26]#[24,25,26] #period over which we average in case use_mean is True
selectedminutes = [5,15,25,35,45,55]#use an array! Do not include the same element twice. This list is not for all datafiles relevant.
starthour = 9 #utc, start of obs (use an integer!)
endhour = 15 #(use an integer!). Obs at this hour will not be included. Model runs up to and including this time
directory = 'Cabauw_obs'
data_Temp = pd.read_csv(directory+'/'+'caboper_air_temperature_200309-24-25-26.lot', skiprows=[0,1,3],delim_whitespace=True)
#data_Temp.loc[data_Temp['TA200'] == -9999 ,'TA200'] = np.nan #set -9999 to nan
for column in data_Temp.drop(columns=['day','btime','etime']): #We leave these three columns out using the drop function, otherwise they would be converted to floats. They remain in the dataframe itself using this statement.
data_Temp.loc[data_Temp[column] == -9999 ,column] = np.nan
data_Press = pd.read_csv(directory+'/'+'caboper_surface_pressure_200309-24-25-26.lot', skiprows=[0,1,3],delim_whitespace=True)
for column in data_Press.drop(columns=['day','btime','etime']):
data_Press.loc[data_Press[column] == -9999 ,column] = np.nan
data_DewP = pd.read_csv(directory+'/'+'caboper_dew_point_200309-24-25-26.lot', skiprows=[0,1,3],delim_whitespace=True)
for column in data_DewP.drop(columns=['day','btime','etime']):
data_DewP.loc[data_DewP[column] == -9999 ,column] = np.nan
data_Flux = pd.read_csv(directory+'/'+'cabsurf_surface_flux_200309-24-25-26.lot', skiprows=[0,1,3],delim_whitespace=True)
for column in data_Flux.drop(columns=['day','btime','etime']):
data_Flux.loc[data_Flux[column] == -9999 ,column] = np.nan
data_Rad = pd.read_csv(directory+'/'+'caboper_radiation_200309-24-25-26.lot', skiprows=[0,1,3],delim_whitespace=True)
for column in data_Rad.drop(columns=['day','btime','etime']):
data_Rad.loc[data_Rad[column] == -9999 ,column] = np.nan
data_Windsp = pd.read_csv(directory+'/'+'caboper_wind_speed_200309-24-25-26.lot', skiprows=[0,1,3],delim_whitespace=True)
for column in data_Windsp.drop(columns=['day','btime','etime']):
data_Windsp.loc[data_Windsp[column] == -9999 ,column] = np.nan
data_Winddir = pd.read_csv(directory+'/'+'caboper_wind_direction_200309-24-25-26.lot', skiprows=[0,1,3],delim_whitespace=True)
for column in data_Winddir.drop(columns=['day','btime','etime']):
data_Winddir.loc[data_Winddir[column] == -9999 ,column] = np.nan
date = data_Temp['day'] #
btime = data_Temp['btime']#begintime
etime = data_Temp['etime']#endtime
btimehour = np.zeros(len(btime))
btimeminute = np.zeros(len(btime))
for i in range(len(btime)):
if len(str(btime[i])) <= 2:
btimehour[i] = 0
btimeminute[i] = btime[i]
else:
btimehour[i] = float(str(btime[i])[0:-2])
btimeminute[i] = float(str(btime[i])[-2:])
etimehour = np.zeros(len(etime))
etimeminute = np.zeros(len(etime))
for i in range(len(etime)):
if len(str(etime[i])) <= 2:
etimehour[i] = 0
etimeminute[i] = etime[i]
else:
etimehour[i] = float(str(etime[i])[0:-2])
etimeminute[i] = float(str(etime[i])[-2:])
hour = np.zeros(len(btime),dtype = int)
minute = np.zeros(len(btime),dtype = int)
for i in range(len(btime)):
if etimeminute[i] == 0 and (btimeminute[i] == 50 and etimehour[i] == btimehour[i] + 1):
minute[i] = 55
hour[i] = btimehour[i]
else:
minute[i] = (btimeminute[i] + etimeminute[i]) / 2
hour[i] = btimehour[i]
year = np.array([int(str(date[i])[0:4]) for i in range(len(date))])
month = np.array([int(str(date[i])[4:6]) for i in range(len(date))])
day = np.array([int(str(date[i])[6:]) for i in range(len(date))])
minute_True_False = np.zeros(len(btime),dtype=bool)
month_True_False = np.zeros(len(btime),dtype=bool)
year_True_False = np.zeros(len(btime),dtype=bool)
day_True_False = np.zeros(len(btime),dtype=bool)
for i in range(len(minute_True_False)):
if minute[i] in selectedminutes:
minute_True_False[i] = True
if month[i] in selectedmonths:
month_True_False[i] = True
if year[i] in selectedyears:
year_True_False[i] = True
if day[i] in selecteddays:
day_True_False[i] = True #True for all selected days only
if use_mean != True:
timeselection = np.logical_and(np.logical_and(day == selectedday,np.logical_and(month_True_False,year_True_False)),np.logical_and(np.logical_and(hour>=starthour,hour<endhour),minute_True_False))
Temp200_selected = data_Temp[timeselection]['TA200'] +273.15
Temp140_selected = data_Temp[timeselection]['TA140'] +273.15
Temp80_selected = data_Temp[timeselection]['TA080'] +273.15
Temp40_selected = data_Temp[timeselection]['TA040'] +273.15
Temp20_selected = data_Temp[timeselection]['TA020'] +273.15
Temp10_selected = data_Temp[timeselection]['TA010'] +273.15
Temp2_selected = data_Temp[timeselection]['TA002'] +273.15
TD200_selected = data_DewP[timeselection]['TD200'] +273.15
TD140_selected = data_DewP[timeselection]['TD140'] +273.15
TD80_selected = data_DewP[timeselection]['TD080'] +273.15
TD40_selected = data_DewP[timeselection]['TD040'] +273.15
TD20_selected = data_DewP[timeselection]['TD020'] +273.15
TD10_selected = data_DewP[timeselection]['TD010'] +273.15
TD2_selected = data_DewP[timeselection]['TD002'] +273.15
Press_selected = data_Press[timeselection]['AP0']*100. #Pa
e200_selected = 610.7 * np.exp(17.2694*(TD200_selected - 273.16) / (TD200_selected - 35.86)) #eq 3.3 and 3.7 intro atm
e140_selected = 610.7 * np.exp(17.2694*(TD140_selected - 273.16) / (TD140_selected - 35.86)) #eq 3.3 and 3.7 intro atm
e80_selected = 610.7 * np.exp(17.2694*(TD80_selected - 273.16) / (TD80_selected - 35.86)) #eq 3.3 and 3.7 intro atm
e40_selected = 610.7 * np.exp(17.2694*(TD40_selected - 273.16) / (TD40_selected - 35.86)) #eq 3.3 and 3.7 intro atm
e20_selected = 610.7 * np.exp(17.2694*(TD20_selected - 273.16) / (TD20_selected - 35.86)) #eq 3.3 and 3.7 intro atm
e10_selected = 610.7 * np.exp(17.2694*(TD10_selected - 273.16) / (TD10_selected - 35.86)) #eq 3.3 and 3.7 intro atm
e2_selected = 610.7 * np.exp(17.2694*(TD2_selected - 273.16) / (TD2_selected - 35.86)) #eq 3.3 and 3.7 intro atm
rho80 = (Press_selected - 1.22030 * g * 80) / (287.04 * Temp80_selected) #1.22030 from us standard atmopsphere 40m
q200_selected = Eps * e200_selected / (Press_selected - rho80 * g * 200 - (1 - Eps) * e200_selected) #eq 3.4 intro atm
q140_selected = Eps * e140_selected / (Press_selected - rho80 * g * 140 - (1 - Eps) * e140_selected) #eq 3.4 intro atm
q80_selected = Eps * e80_selected / (Press_selected - rho80 * g * 80 - (1 - Eps) * e80_selected) #eq 3.4 intro atm
q40_selected = Eps * e40_selected / (Press_selected - rho80 * g * 40 - (1 - Eps) * e40_selected) #eq 3.4 intro atm
q20_selected = Eps * e20_selected / (Press_selected - rho80 * g * 20 - (1 - Eps) * e20_selected) #eq 3.4 intro atm
q10_selected = Eps * e10_selected / (Press_selected - rho80 * g * 10 - (1 - Eps) * e10_selected) #eq 3.4 intro atm
q2_selected = Eps * e2_selected / (Press_selected - rho80 * g * 2 - (1 - Eps) * e2_selected) #eq 3.4 intro atm
H_selected = data_Flux[timeselection]['HSON'] #W/m2
LE_selected = data_Flux[timeselection]['LEED'] #W/m2
G_selected = data_Flux[timeselection]['FG0'] #W/m2
ustar_selected = data_Flux[timeselection]['USTED'] #W/m2
wCO2_selected = data_Flux[timeselection]['FCED'] #mg CO2/m2/s
SWU_selected = data_Rad[timeselection]['SWU'] #W m-2
SWD_selected = data_Rad[timeselection]['SWD'] #W m-2
LWU_selected = data_Rad[timeselection]['LWU'] #W m-2
LWD_selected = data_Rad[timeselection]['LWD'] #W m-2
Windsp200_selected = data_Windsp[timeselection]['F200'] #m s-1
Windsp10_selected = data_Windsp[timeselection]['F010'] #m s-1
stdevWindsp200_selected = data_Windsp[timeselection]['SF200'] #m s-1 #standard dev 200m, see Cabauw_TR.pdf
stdevWindsp10_selected = data_Windsp[timeselection]['SF010'] #m s-1
Winddir200_selected = data_Winddir[timeselection]['D200'] #deg
Winddir10_selected = data_Winddir[timeselection]['D010'] #deg
stdevWinddir200_selected = data_Winddir[timeselection]['SD200'] #deg #see Cabauw_TR.pdf
stdevWinddir10_selected = data_Winddir[timeselection]['SD010'] #deg
u200_selected = Windsp200_selected * np.cos((270. - Winddir200_selected)*2*np.pi/360) #2*np.pi/360 for conversion to rad. Make drawing to see the 270 minus wind dir
v200_selected = Windsp200_selected * np.sin((270. - Winddir200_selected)*2*np.pi/360)
u10_selected = Windsp10_selected * np.cos((270. - Winddir10_selected)*2*np.pi/360) #2*np.pi/360 for conversion to rad. Make drawing to see the 270 minus wind dir
v10_selected = Windsp10_selected * np.sin((270. - Winddir10_selected)*2*np.pi/360)
else:
stdevTemp200_hourly = np.zeros((endhour-starthour))
stdevTemp140_hourly = np.zeros((endhour-starthour))
stdevTemp80_hourly = np.zeros((endhour-starthour))
stdevTemp40_hourly = np.zeros((endhour-starthour))
stdevTemp20_hourly = np.zeros((endhour-starthour))
stdevTemp10_hourly = np.zeros((endhour-starthour))
stdevTemp2_hourly = np.zeros((endhour-starthour))
stdevq200_hourly = np.zeros((endhour-starthour))
stdevq140_hourly = np.zeros((endhour-starthour))
stdevq80_hourly = np.zeros((endhour-starthour))
stdevq40_hourly = np.zeros((endhour-starthour))
stdevq20_hourly = np.zeros((endhour-starthour))
stdevq10_hourly = np.zeros((endhour-starthour))
stdevq2_hourly = np.zeros((endhour-starthour))
stdevPress_hourly = np.zeros((endhour-starthour))
stdevH_hourly = np.zeros((endhour-starthour))
stdevLE_hourly = np.zeros((endhour-starthour))
stdevG_hourly = np.zeros((endhour-starthour))
stdevustar_hourly = np.zeros((endhour-starthour))
stdevwCO2_hourly = np.zeros((endhour-starthour))
Temp200_mean = np.zeros((endhour-starthour))
Temp140_mean = np.zeros((endhour-starthour))
Temp80_mean = np.zeros((endhour-starthour))
Temp40_mean = np.zeros((endhour-starthour))
Temp20_mean = np.zeros((endhour-starthour))
Temp10_mean = np.zeros((endhour-starthour))
Temp2_mean = np.zeros((endhour-starthour))
q200_mean = np.zeros((endhour-starthour))
q140_mean = np.zeros((endhour-starthour))
q80_mean = np.zeros((endhour-starthour))
q40_mean = np.zeros((endhour-starthour))
q20_mean = np.zeros((endhour-starthour))
q10_mean = np.zeros((endhour-starthour))
q2_mean = np.zeros((endhour-starthour))
Press_mean = np.zeros((endhour-starthour))
hours_mean = np.zeros((endhour-starthour))
H_mean = np.zeros((endhour-starthour))
LE_mean = np.zeros((endhour-starthour))
G_mean = np.zeros((endhour-starthour))
ustar_mean = np.zeros((endhour-starthour))
wCO2_mean = np.zeros((endhour-starthour))
Windsp200_mean = np.zeros((endhour-starthour))
Windsp10_mean = np.zeros((endhour-starthour))
for i in range(endhour-starthour):
timeselection2 = np.logical_and(np.logical_and(day_True_False,np.logical_and(month_True_False,year_True_False)),np.logical_and(np.logical_and(hour>=starthour,hour<endhour),np.logical_and(np.logical_and(hour>=starthour+i,hour<starthour+i+1),minute_True_False)))
Temp200toaverage = data_Temp[timeselection2]['TA200'] +273.15
Temp140toaverage = data_Temp[timeselection2]['TA140'] +273.15
Temp80toaverage = data_Temp[timeselection2]['TA080'] +273.15
Temp40toaverage = data_Temp[timeselection2]['TA040'] +273.15
Temp20toaverage = data_Temp[timeselection2]['TA020'] +273.15
Temp10toaverage = data_Temp[timeselection2]['TA010'] +273.15
Temp2toaverage = data_Temp[timeselection2]['TA002'] +273.15
TD200_selected = data_DewP[timeselection2]['TD200'] +273.15
TD140_selected = data_DewP[timeselection2]['TD140'] +273.15
TD80_selected = data_DewP[timeselection2]['TD080'] +273.15
TD40_selected = data_DewP[timeselection2]['TD040'] +273.15
TD20_selected = data_DewP[timeselection2]['TD020'] +273.15
TD10_selected = data_DewP[timeselection2]['TD010'] +273.15
TD2_selected = data_DewP[timeselection2]['TD002'] +273.15
Presstoaverage = data_Press[timeselection2]['AP0']*100 #Pa
e200_selected = 610.7 * np.exp(17.2694*(TD200_selected - 273.16) / (TD200_selected - 35.86)) #eq 3.3 intro atm and 3.7 intro atm
e140_selected = 610.7 * np.exp(17.2694*(TD140_selected - 273.16) / (TD140_selected - 35.86)) #eq 3.3 intro atm and 3.7 intro atm
e80_selected = 610.7 * np.exp(17.2694*(TD80_selected - 273.16) / (TD80_selected - 35.86)) #eq 3.3 intro atm and 3.7 intro atm
e40_selected = 610.7 * np.exp(17.2694*(TD40_selected - 273.16) / (TD40_selected - 35.86)) #eq 3.3 intro atm and 3.7 intro atm
e20_selected = 610.7 * np.exp(17.2694*(TD20_selected - 273.16) / (TD20_selected - 35.86)) #eq 3.3 intro atm and 3.7 intro atm
e10_selected = 610.7 * np.exp(17.2694*(TD10_selected - 273.16) / (TD10_selected - 35.86)) #eq 3.3 intro atm and 3.7 intro atm
e2_selected = 610.7 * np.exp(17.2694*(TD2_selected - 273.16) / (TD2_selected - 35.86)) #eq 3.3 intro atm and 3.7 intro atm
rho80 = (Presstoaverage - 1.22030 * g * 80) / (287.04 * Temp80toaverage) #1.22030 from us standard atmopsphere 40m
q200toaverage = Eps * e200_selected / (Presstoaverage - rho80 * g * 200 - (1 - Eps) * e200_selected) #eq 3.4 intro atm
q140toaverage = Eps * e140_selected / (Presstoaverage - rho80 * g * 140 - (1 - Eps) * e140_selected) #eq 3.4 intro atm
q80toaverage = Eps * e80_selected / (Presstoaverage - rho80 * g * 80 - (1 - Eps) * e80_selected) #eq 3.4 intro atm
q40toaverage = Eps * e40_selected / (Presstoaverage - rho80 * g * 40 - (1 - Eps) * e40_selected) #eq 3.4 intro atm
q20toaverage = Eps * e20_selected / (Presstoaverage - rho80 * g * 20 - (1 - Eps) * e20_selected) #eq 3.4 intro atm
q10toaverage = Eps * e10_selected / (Presstoaverage - rho80 * g * 10 - (1 - Eps) * e10_selected) #eq 3.4 intro atm
q2toaverage = Eps * e2_selected / (Presstoaverage - rho80 * g * 2 - (1 - Eps) * e2_selected) #eq 3.4 intro atm
Htoaverage = data_Flux[timeselection2]['HSON'] #W/m2
LEtoaverage = data_Flux[timeselection2]['LEED'] #W/m2
Gtoaverage = data_Flux[timeselection2]['FG0'] #W/m2
ustartoaverage = data_Flux[timeselection2]['USTED'] #m/s
wCO2toaverage = data_Flux[timeselection2]['FCED']
Windsp200toaverage = data_Windsp[timeselection2]['F200'] #m s-1
Windsp10toaverage = data_Windsp[timeselection2]['F010'] #m s-1
Temp200_mean[i] = np.mean(Temp200toaverage)
Temp140_mean[i] = np.mean(Temp140toaverage)
Temp80_mean[i] = np.mean(Temp80toaverage)
Temp40_mean[i] = np.mean(Temp40toaverage)
Temp20_mean[i] = np.mean(Temp20toaverage)
Temp10_mean[i] = np.mean(Temp10toaverage)
Temp2_mean[i] = np.mean(Temp2toaverage)
q200_mean[i] = np.mean(q200toaverage)
q140_mean[i] = np.mean(q140toaverage)
q80_mean[i] = np.mean(q80toaverage)
q40_mean[i] = np.mean(q40toaverage)
q20_mean[i] = np.mean(q20toaverage)
q10_mean[i] = np.mean(q10toaverage)
q2_mean[i] = np.mean(q2toaverage)
Windsp200_mean[i] = np.mean(Windsp200toaverage)
Windsp10_mean[i] = np.mean(Windsp10toaverage)
Press_mean[i] = np.mean(Presstoaverage)
H_mean[i] = np.mean(Htoaverage)
LE_mean[i] = np.mean(LEtoaverage)
G_mean[i] = np.mean(Gtoaverage)
ustar_mean[i] = np.mean(ustartoaverage)
wCO2_mean[i] = np.mean(wCO2toaverage)
stdevTemp200_hourly[i] = np.std(Temp200toaverage)
stdevTemp140_hourly[i] = np.std(Temp140toaverage)
stdevTemp80_hourly[i] = np.std(Temp80toaverage)
stdevTemp40_hourly[i] = np.std(Temp40toaverage)
stdevTemp20_hourly[i] = np.std(Temp20toaverage)
stdevTemp10_hourly[i] = np.std(Temp10toaverage)
stdevTemp2_hourly[i] = np.std(Temp2toaverage)
stdevq200_hourly[i] = np.std(q200toaverage)
stdevq140_hourly[i] = np.std(q140toaverage)
stdevq80_hourly[i] = np.std(q80toaverage)
stdevq40_hourly[i] = np.std(q40toaverage)
stdevq20_hourly[i] = np.std(q20toaverage)
stdevq10_hourly[i] = np.std(q10toaverage)
stdevq2_hourly[i] = np.std(q2toaverage)
stdevH_hourly[i] = np.std(Htoaverage)
stdevLE_hourly[i] = np.std(LEtoaverage)
stdevG_hourly[i] = np.std(Gtoaverage)
stdevustar_hourly[i] = np.std(ustartoaverage)
stdevwCO2_hourly[i] = np.std(wCO2toaverage)
hours_mean[i] = starthour + i + 0.5
#this dataset contains less
if use_mean:
if (2003 in selectedyears and (9 in selectedmonths and 25 in selecteddays)):
data_BLH = pd.read_csv(directory+'/'+'BLheight.txt',delim_whitespace=True)
date_BLH = data_BLH['Date'] #
year_BLH = np.array([int(str(date_BLH[i])[0:4]) for i in range(len(date_BLH))])
month_BLH = np.array([int(str(date_BLH[i])[4:6]) for i in range(len(date_BLH))])
day_BLH = np.array([int(str(date_BLH[i])[6:]) for i in range(len(date_BLH))])
dhour_BLH = data_BLH['dhour'] #
BLH_mean = np.zeros((endhour-starthour))
dhour_BLH_mean = np.zeros((endhour-starthour))
for i in range(endhour-starthour):
timeselection_BLH = np.logical_and(np.logical_and(dhour_BLH>=starthour,dhour_BLH<endhour),np.logical_and(dhour_BLH>=starthour+i,dhour_BLH<starthour+i+1))
BLH_toaverage = data_BLH[timeselection_BLH]['BLH'].astype(float) #astype(float), as it can give error if it are integers or strings
BLH_mean[i] = np.mean(BLH_toaverage)
dhour_BLH_toaverage = dhour_BLH[timeselection_BLH]
dhour_BLH_mean[i] = np.mean(dhour_BLH_toaverage)
else:
if (2003 in selectedyears and (9 in selectedmonths and selectedday == 25)):
data_BLH = pd.read_csv(directory+'/'+'BLheight.txt',delim_whitespace=True)
date_BLH = data_BLH['Date'] #
year_BLH = np.array([int(str(date_BLH[i])[0:4]) for i in range(len(date_BLH))])
month_BLH = np.array([int(str(date_BLH[i])[4:6]) for i in range(len(date_BLH))])
day_BLH = np.array([int(str(date_BLH[i])[6:]) for i in range(len(date_BLH))])
dhour_BLH = data_BLH['dhour'] #
timeselection_BLH = np.logical_and(dhour_BLH>=starthour,dhour_BLH<endhour)
BLH_selected = data_BLH[timeselection_BLH]['BLH'].astype(float) #astype(float), as it can give error if it are integers or strings
dhour_BLH_selected = dhour_BLH[timeselection_BLH]
#CO2 datafile
data_CO2 = pd.read_csv(directory+'/'+'CO2-September2003.txt',skiprows = 3,delim_whitespace=True)
date_CO2 = data_CO2['Date'] #
time_CO2 = data_CO2['Time'] #
hour_CO2 = np.zeros(len(time_CO2))
day_CO2 = np.zeros(len(time_CO2),dtype=int)
month_CO2 = np.zeros(len(time_CO2),dtype=int)
year_CO2 = np.zeros(len(time_CO2),dtype=int)
for i in range(len(date_CO2)):
day_CO2[i] = int(str(date_CO2[i])[0:2])
month_CO2[i] = int(str(date_CO2[i])[3:5])
year_CO2[i] = int(str(date_CO2[i])[6:])
for i in range(len(time_CO2)):
hour_CO2[i] = float(str(time_CO2[i])[-5:-3])
if hour_CO2[i] != 0: #Date/time indicates end of 1 hour averaging interval in UTC in the datafile
hour_CO2[i] = hour_CO2[i] - 0.5
else:
hour_CO2[i] = 23.5
day_CO2[i] = day_CO2[i] - 1 #then it is from previous day
month_True_False = np.zeros(len(time_CO2),dtype=bool)
year_True_False = np.zeros(len(time_CO2),dtype=bool)
for i in range(len(month_True_False)):
if month_CO2[i] in selectedmonths:
month_True_False[i] = True
if year_CO2[i] in selectedyears:
year_True_False[i] = True
if use_mean != True:
timeselection = np.logical_and(np.logical_and(day_CO2 == selectedday,np.logical_and(month_True_False,year_True_False)),np.logical_and(hour_CO2>=starthour,hour_CO2<endhour))
CO2_200_selected = data_CO2[timeselection]['CO2_200'] #ppm. Here the data file has e.g. header CO2_200, but measurements are made at 207, 127, 67 and 27 m, see Notes.txt
CO2_120_selected = data_CO2[timeselection]['CO2_120'] #ppm
CO2_60_selected = data_CO2[timeselection]['CO2_60'] #ppm
CO2_20_selected = data_CO2[timeselection]['CO2_20'] #ppm
hour_CO2_selected = hour_CO2[timeselection]
else:
day_True_False = np.zeros(len(time_CO2),dtype=bool)
for i in range(len(month_True_False)):
if day_CO2[i] in selecteddays:
day_True_False[i] = True #True for all selected days only
stdevCO2_200_hourly = np.zeros((endhour-starthour))
stdevCO2_120_hourly = np.zeros((endhour-starthour))
stdevCO2_60_hourly = np.zeros((endhour-starthour))
stdevCO2_20_hourly = np.zeros((endhour-starthour))
CO2_200_mean = np.zeros((endhour-starthour))
CO2_120_mean = np.zeros((endhour-starthour))
CO2_60_mean = np.zeros((endhour-starthour))
CO2_20_mean = np.zeros((endhour-starthour))
for i in range(endhour-starthour):
timeselection2 = np.logical_and(np.logical_and(day_True_False,np.logical_and(month_True_False,year_True_False)),np.logical_and(np.logical_and(hour_CO2>=starthour,hour_CO2<endhour),np.logical_and(hour_CO2>=starthour+i,hour_CO2<starthour+i+1)))
CO2_200toaverage = data_CO2[timeselection2]['CO2_200'] #ppm
CO2_120toaverage = data_CO2[timeselection2]['CO2_120'] #ppm
CO2_60toaverage = data_CO2[timeselection2]['CO2_60'] #ppm
CO2_20toaverage = data_CO2[timeselection2]['CO2_20'] #ppm
CO2_200_mean[i] = np.mean(CO2_200toaverage)
CO2_120_mean[i] = np.mean(CO2_120toaverage)
CO2_60_mean[i] = np.mean(CO2_60toaverage)
CO2_20_mean[i] = np.mean(CO2_20toaverage)
stdevCO2_200_hourly[i] = np.std(CO2_200toaverage)
stdevCO2_120_hourly[i] = np.std(CO2_120toaverage)
stdevCO2_60_hourly[i] = np.std(CO2_60toaverage)
stdevCO2_20_hourly[i] = np.std(CO2_20toaverage)
######################################
###### end user input: load obs ######
######################################
#optimisation
priormodinput = fwdm.model_input()
###########################################
###### user input: prior model param ######
###########################################
priormodinput.COS = 0.400 #ppb
priormodinput.CO2measuring_height = 207. - canopy_height
priormodinput.CO2measuring_height2 = 127 - canopy_height
priormodinput.CO2measuring_height3 = 67 - canopy_height
priormodinput.CO2measuring_height4 = 27 - canopy_height
priormodinput.Tmeasuring_height = 200 - canopy_height #0 would be a problem
priormodinput.Tmeasuring_height2 = 140 - canopy_height #0 would be a problem
priormodinput.Tmeasuring_height3 = 80 - canopy_height #0 would be a problem
priormodinput.Tmeasuring_height4 = 40 - canopy_height #0 would be a problem
priormodinput.Tmeasuring_height5 = 20 - canopy_height #0 would be a problem
priormodinput.Tmeasuring_height6 = 10 - canopy_height #0 would be a problem
priormodinput.Tmeasuring_height7 = 2 - canopy_height #0 would be a problem
priormodinput.qmeasuring_height = 200. - canopy_height
priormodinput.qmeasuring_height2 = 140. - canopy_height
priormodinput.qmeasuring_height3 = 80. - canopy_height
priormodinput.qmeasuring_height4 = 40. - canopy_height
priormodinput.qmeasuring_height5 = 20. - canopy_height
priormodinput.qmeasuring_height6 = 10. - canopy_height
priormodinput.qmeasuring_height7 = 2. - canopy_height
priormodinput.sca_sto = 1
priormodinput.gciCOS = 0.2 /(1.2*1000) * 28.9
priormodinput.ags_C_mode = 'MXL'
priormodinput.sw_useWilson = False
priormodinput.dt = 60 # time step [s]
priormodinput.tstart = starthour # time of the day [h UTC]
priormodinput.runtime = (endhour-priormodinput.tstart)*3600 + priormodinput.dt # total run time [s]
priormodinput.sw_ml = True # mixed-layer model switch
priormodinput.sw_shearwe = True # shear growth mixed-layer switch
priormodinput.sw_fixft = False # Fix the free-troposphere switch
if use_mean:
priormodinput.Ps = Press_mean[0] # surface pressure [Pa]
priormodinput.h = BLH_mean[0] # initial ABL height [m]
else:
priormodinput.Ps = np.array(Press_selected)[0] # surface pressure [Pa]
priormodinput.h = np.array(BLH_selected)[0] # initial ABL height [m]
priormodinput.divU = 0.00 # horizontal large-scale divergence of wind [s-1]
if use_mean:
priormodinput.theta = np.array(Temp200_mean)[0]*((np.array(Press_mean)[0]-200*9.81*np.array(rho80)[0])/100000)**(-287.04/1005) # initial mixed-layer potential temperature [K]
else:
priormodinput.theta = np.array(Temp200_selected)[0]*((np.array(Press_selected)[0]-200*9.81*np.array(rho80)[0])/100000)**(-287.04/1005) # initial mixed-layer potential temperature [K]
priormodinput.deltatheta = 4.20 # initial temperature jump at h [K]
priormodinput.gammatheta = 0.0036 # free atmosphere potential temperature lapse rate [K m-1]
priormodinput.gammatheta2 = 0.015 # free atmosphere potential temperature lapse rate for h > htrans [K m-1]
priormodinput.htrans = 95000 #height of BL above which to use gammatheta2 instead of gammatheta
priormodinput.advtheta = 0 # advection of heat [K s-1]
priormodinput.beta = 0.2 # entrainment ratio for virtual heat [-]
if use_mean:
priormodinput.q = np.array(q200_mean)[0] # initial mixed-layer specific humidity [kg kg-1]
else:
priormodinput.q = np.array(q200_selected)[0]
priormodinput.deltaq = -0.0008 # initial specific humidity jump at h [kg kg-1]
priormodinput.gammaq = -1.2e-6 # free atmosphere specific humidity lapse rate [kg kg-1 m-1]
priormodinput.advq = 0 # advection of moisture [kg kg-1 s-1]
if use_mean:
priormodinput.CO2 = np.array(CO2_200_mean)[0] # initial mixed-layer CO2 [ppm]
else:
priormodinput.CO2 = np.array(CO2_200_selected)[0] # initial mixed-layer CO2 [ppm]
priormodinput.deltaCO2 = -44. # initial CO2 jump at h [ppm]
priormodinput.deltaCOS = 0.050 # initial COS jump at h [ppb]
priormodinput.gammaCO2 = -0.000 # free atmosphere CO2 lapse rate [ppm m-1]
priormodinput.gammaCOS = 0.00 # free atmosphere COS lapse rate [ppb m-1]
priormodinput.advCO2 = 0 # advection of CO2 [ppm s-1]
priormodinput.advCOS = 0. # advection of COS [ppb s-1]
priormodinput.wCOS = 0.01 # surface kinematic COS flux [ppb m s-1]
priormodinput.sw_wind = True # prognostic wind switch
if use_mean:
priormodinput.u = np.array(Windsp200_mean)[0] # initial mixed-layer u-wind speed [m s-1]
else:
priormodinput.u = np.array(Windsp200_selected)[0] # initial mixed-layer u-wind speed [m s-1]
priormodinput.deltau = 3. # initial u-wind jump at h [m s-1]
priormodinput.gammau = 0.002 # free atmosphere u-wind speed lapse rate [s-1]
priormodinput.advu = 0. # advection of u-wind [m s-2]
priormodinput.v = 0 # initial mixed-layer v-wind speed [m s-1]
priormodinput.deltav = 0 # initial v-wind jump at h [m s-1]
priormodinput.gammav = 0. # free atmosphere v-wind speed lapse rate [s-1]
priormodinput.advv = 0. # advection of v-wind [m s-2]
priormodinput.sw_sl = True # surface layer switch
priormodinput.ustar = 0.3 # surface friction velocity [m s-1]
priormodinput.z0m = 0.05 # roughness length for momentum [m]
priormodinput.z0h = 0.01 # roughness length for scalars [m]
priormodinput.sw_rad = True # radiation switch
priormodinput.lat = 51.971 # latitude [deg] #https://icdc.cen.uni-hamburg.de/1/daten/atmosphere/weathermast-cabauw.html and https://latitude.to/articles-by-country/nl/netherlands/204321/knmi-mast-cabauw
priormodinput.lon = 4.927 # longitude [deg]
priormodinput.doy = 268. # day of the year [-]
priormodinput.fc = 2 * 7.2921e-5 * np.sin(priormodinput.lat*2*np.pi/360.) # Coriolis parameter [m s-1]
priormodinput.cc = 0.0 # cloud cover fraction [-]
priormodinput.dFz = 0. # cloud top radiative divergence [W m-2]
priormodinput.sw_ls = True # land surface switch
priormodinput.ls_type = 'ags' # land-surface parameterization ('js' for Jarvis-Stewart or 'ags' for A-Gs)
priormodinput.wg = 0.48 # volumetric water content top soil layer [m3 m-3]
priormodinput.w2 = 0.48 # volumetric water content deeper soil layer [m3 m-3]
priormodinput.cveg = 0.9 # vegetation fraction [-]
priormodinput.Tsoil = 282. # temperature top soil layer [K]
priormodinput.T2 = 285 # temperature deeper soil layer [K]
priormodinput.a = 0.083 # Clapp and Hornberger retention curve parameter a
priormodinput.b = 11.4 # Clapp and Hornberger retention curve parameter b
priormodinput.p = 12. # Clapp and Hornberger retention curve parameter c
priormodinput.CGsat = 3.6e-6 # saturated soil conductivity for heat
priormodinput.wsat = 0.6 # saturated volumetric water content ECMWF config [-]
priormodinput.wfc = 0.491 # volumetric water content field capacity [-]
priormodinput.wwilt = 0.314 # volumetric water content wilting point [-]
priormodinput.C1sat = 0.342
priormodinput.C2ref = 0.3
priormodinput.LAI = 2. # leaf area index [-]
priormodinput.gD = None # correction factor transpiration for VPD [-]
priormodinput.rsmin = 110. # minimum resistance transpiration [s m-1]
priormodinput.rssoilmin = 50. # minimum resistance soil evaporation [s m-1]
priormodinput.alpha = 0.25 # surface albedo [-]
priormodinput.Ts = 284 # initial surface temperature [K]
priormodinput.Wmax = 0.0002 # thickness of water layer on wet vegetation [m]
priormodinput.Wl = 0.00014 # equivalent water layer depth for wet vegetation [m]
priormodinput.Lambda = 5.9 # thermal diffusivity skin layer [-]
priormodinput.c3c4 = 'c3' # Plant type ('c3' or 'c4')
priormodinput.sw_cu = False # Cumulus parameterization switch
priormodinput.dz_h = 150. # Transition layer thickness [m]
priormodinput.Cs = 1e12 # drag coefficient for scalars [-]
priormodinput.sw_dynamicsl_border = True
priormodinput.sw_model_stable_con = True
priormodinput.sw_printwarnings = False
priormodinput.sw_use_ribtol = True
priormodinput.sw_advfp = True #prescribed advection to take place over full profile (also in Free troposphere), only in ML if FALSE
priormodinput.R10 = 0.23
#tsteps = int(np.floor(priormodinput.runtime / priormodinput.dt)) #the number of timesteps, used below
#priormodinput.wtheta_input = np.zeros(tsteps)
#priormodinput.wq_input = np.zeros(tsteps)
#priormodinput.wCO2_input = np.zeros(tsteps)
#for t in range(tsteps):
# if (t*priormodinput.dt >= 1.5*3600) and (t*priormodinput.dt <= 9*3600):
# priormodinput.wtheta_input[t] = 0.08 * np.sin(np.pi*(t*priormodinput.dt-5400)/27000)
# else:
# priormodinput.wtheta_input[t] = 0
# priormodinput.wq_input[t] = 0.087 * np.sin(np.pi * t*priormodinput.dt/43200) /1000 #/1000 for conversion to kg/kg m s-1
# if (t*priormodinput.dt >= 2*3600) and (t*priormodinput.dt <= 9.5*3600):
# priormodinput.wCO2_input[t] = -0.1*np.sin(np.pi*(t*priormodinput.dt-7200)/27000)
# else:
# priormodinput.wCO2_input[t] = 0.
#priormodinput.wCO2 = priormodinput.wCO2_input[0] # surface total CO2 flux [mgCO2 m-2 s-1]
#priormodinput.wq = priormodinput.wq_input[0] # surface kinematic moisture flux [kg kg-1 m s-1]
#priormodinput.wtheta = priormodinput.wtheta_input[0] # surface kinematic heat flux [K m s-1]
priormodinput.wCO2 = 0.0000001 # surface total CO2 flux [mgCO2 m-2 s-1]
priormodinput.wq = 0.0000001 # surface kinematic moisture flux [kg kg-1 m s-1]
priormodinput.wtheta = 0.0000001 # surface kinematic heat flux [K m s-1]
###############################################
###### end user input: prior model param ######
###############################################
#run priormodel to initialise properly
priormodel = fwdm.model(priormodinput)
priormodel.run(checkpoint=True,updatevals_surf_lay=True,delete_at_end=False,save_vars_indict=False) #delete_at_end should be false, to keep tsteps of model
priorinput = cp.deepcopy(priormodinput)
##########################################################################
###### user input: state, list of used obs and non-model priorinput ######
##########################################################################
#e.g. state=['h','q','theta','gammatheta','deltatheta','deltaq','alpha','gammaq','wg','wtheta','z0h','z0m','ustar','wq','divU']
state=['advtheta','advq','advCO2','deltatheta','gammatheta','deltaq','gammaq','deltaCO2','gammaCO2','sca_sto','alpha','FracH','wg','R10']
obsvarlist =['Tmh','Tmh2','Tmh3','Tmh4','Tmh5','Tmh6','Tmh7','qmh','qmh2','qmh3','qmh4','qmh5','qmh6','qmh7','CO2mh','CO2mh2','CO2mh3','CO2mh4','h','LE','H','wCO2','Swout']
#below we can add some input necessary for the state in the optimisation, that is not part of the model input (a scale for some of the observations in the costfunction if desired). Or FracH
if 'FracH' in state:
priorinput.FracH = 0.6
#priorinput.obs_sca_cf_H = 1.0 #Always use this format, 'obs_sca_cf_' plus the observation type you want to scale
##e.g. priorinput.obs_sca_cf_H = 1.5 means that in the cost function all obs of H will be multiplied with 1.5. But only if obs_sca_cf_H also in the state!
#priorinput.obs_sca_cf_LE = 1.0
##############################################################################
###### end user input: state, list of used obs and non-model priorinput ######
##############################################################################
if len(set(state)) != len(state):
raise Exception('Mulitiple occurences of same item in state')
if len(set(obsvarlist)) != len(obsvarlist):
raise Exception('Mulitiple occurences of same item in obsvarlist')
if ('FracH' in state and ('obs_sca_cf_H' in state or 'obs_sca_cf_LE' in state)):
raise Exception('When FracH in state, you cannot include obs_sca_cf_H or obs_sca_cf_LE in state as well')
for item in state:
if item.startswith('obs_sca_cf_'):
obsname = item.split("obs_sca_cf_",1)[1]
if obsname not in obsvarlist:
raise Exception(item+' included in state, but '+obsname+' not included in obsvarlist')
if item not in priorinput.__dict__ or priorinput.__dict__[item] is None:
raise Exception(item +' included in state, but no prior given!')
for item in priorinput.__dict__: #just a check
if item.startswith('obs_sca_cf') and (item not in state):
raise Exception(item +' given in priorinput, but not part of state. Remove from priorinput or add '+item+' to the state')
elif item == 'FracH' and (item not in state):
raise Exception(item +' given in priorinput, but not part of state. Remove from priorinput or add '+item+' to the state')
for item in obsvarlist:
if not hasattr(priormodel.out,item):
raise Exception(item +' from obsvarlist is not a model variable occurring in class \'model_output\' in forwardmodel.py')
if len(state) < 1:
raise Exception('Variable \'state\' is empty')
if len(obsvarlist) < 1:
raise Exception('Variable \'obsvarlist\' is empty')
if use_backgr_in_cost or use_ensemble:
priorvar = {}
priorcovar={}
###########################################################
###### user input: prior variance/covar (if used) #########
###########################################################
#if not use_backgr_in_cost, then these are only used for perturbing the ensemble (when use_ensemble = True)
#prior variances of the items in the state:
priorvar['alpha'] = 0.1**2
priorvar['gammatheta'] = 0.003**2
priorvar['gammatheta2'] = 0.003**2
priorvar['gammaq'] = (0.002e-3)**2
priorvar['gammaCO2'] = (30.e-3)**2
priorvar['deltatheta'] = 1.5**2
priorvar['deltaq'] = 0.002**2
priorvar['theta'] = 1**2
priorvar['deltaCO2'] = 25**2
priorvar['CO2'] = 30**2
priorvar['sca_sto'] = 0.25**2
priorvar['z0m'] = 0.05**2
priorvar['z0h'] = 0.05**2
priorvar['advtheta'] = (2/3600)**2
priorvar['advq'] = (0.002/3600)**2
priorvar['advCO2'] = (15/3600)**2
priorvar['wg'] = (0.15)**2
# priorvar['obs_sca_cf_H'] = 0.4**2
# priorvar['obs_sca_cf_LE'] = 0.4**2
if 'FracH' in state:
priorvar['FracH'] = 0.3**2
priorvar['cc'] = 0.2**2
priorvar['R10'] = 0.3**2
# priorvar['wtheta'] = (150/1.1/1005)**2
# priorvar['wq'] = (0.1e-3)**2
# priorvar['ustar'] = (0.7)**2
# priorvar['h'] = 200**2
# priorvar['q'] = 0.003**2
# priorvar['wg'] = 0.2**2
# priorvar['deltaCOS'] = 0.02**2
# priorvar['COS'] = 0.1**2
# priorvar['fCA'] = 1.e3**2
# priorvar['divU'] = 0.0001**2
# priorvar['u'] = 1.5**2
# priorvar['v'] = 1.5**2
# priorvar['deltau'] = 1.5**2
# priorvar['deltav'] = 1.5**2
# priorvar['gammau'] = 0.02**2
# priorvar['gammav'] = 0.02**2
# priorvar['advu'] = 0.0006**2
# priorvar['advv'] = 0.0006**2
#below we can specify covariances as well, for the background information matrix. If covariances are not specified, they are taken as 0
#e.g. priorcovar['gammatheta,gammaq'] = 5.
###########################################################
###### end user input: prior variance/covar (if used) #####
###########################################################
for thing in priorvar:
if thing not in priorinput.__dict__:
raise Exception('Parameter \''+thing +'\' specified in priorvar, but does not exist in priorinput')
if priorvar[thing] <= 0:
raise Exception('Prior variance for '+thing+' should be greater than zero!')
b_cov = np.diag(np.zeros(len(state)))
i = 0
for item in state:
if item not in priorvar:
raise Exception('No prior variance specified for '+item)
b_cov[i][i] = priorvar[item] #b_cov stands for background covariance matrix, b already exists as model parameter
i += 1
#in b_cov, params should have same order as in state
if bool(priorcovar):# check if covar dictionary not empty
for thing in priorcovar:
if thing.count(',') != 1:
raise Exception('Invalid key \''+thing+'\' in priorcovar')
if ''.join(thing.split()) != thing: #if a whitespace present, the LHS will not be equal to the RHS
raise Exception('Invalid key \''+thing+'\' in priorcovar')
thing1,thing2 = thing.split(',')
if thing1 not in priorinput.__dict__:
raise Exception('Parameter \''+thing1 +'\' specified in priorcovar, but does not exist in priorinput')
elif thing2 not in priorinput.__dict__:
raise Exception('Parameter \''+thing2 +'\' specified in priorcovar, but does not exist in priorinput')
if priorcovar[thing] > 1 * np.sqrt(priorvar[thing1])*np.sqrt(priorvar[thing2]) or priorcovar[thing] < -1 * np.sqrt(priorvar[thing1])*np.sqrt(priorvar[thing2]):
raise Exception('Prior covariance of '+thing + ' inconsistent with specified variances (deduced correlation not in [-1,1]).')
for i in range(len(state)):
item = state[i]
for item2 in np.delete(state,i): #exclude item2 == item, that is for variance, not covar
if item+','+item2 in priorcovar:
b_cov[i][state.index(item2)] = priorcovar[item+','+item2]
b_cov[state.index(item2)][i] = priorcovar[item+','+item2]
elif item2+','+item in priorcovar:
b_cov[i][state.index(item2)] = priorcovar[item2+','+item]
b_cov[state.index(item2)][i] = priorcovar[item2+','+item]
if not np.all(np.linalg.eigvals(b_cov) > 0):
raise Exception('Prior error covariance matrix is not positive definite, check the specified elements')#See page 12 (page498) and 13 (page499) of Brasseur and Jacob 2017
else:
b_cov = None
boundedvars = {}
if imposeparambounds or paramboundspenalty:
#############################################################
###### user input: parameter bounds #########################
#############################################################
boundedvars['deltatheta'] = [0.2,7] #lower and upper bound
boundedvars['deltaCO2'] = [-200,200]
boundedvars['deltaq'] = [-0.009,0.009]
boundedvars['alpha'] = [0.05,0.8]
boundedvars['sca_sto'] = [0.1,5]
boundedvars['wg'] = [priorinput.wwilt+0.001,priorinput.wsat-0.001]
boundedvars['h'] = [50,3200]
boundedvars['gammatheta'] = [0.001,0.018]
boundedvars['gammatheta2'] = [0.001,0.018]
boundedvars['gammaq'] = [-9e-6,9e-6]
boundedvars['z0m'] = [0.0001,5]
boundedvars['z0h'] = [0.0001,5]
boundedvars['FracH'] = [0,1]
boundedvars['R10'] = [0,15]
boundedvars['advq'] = [-5/3600/1000,15/3600/1000] #15/3600/1000 means upper bound set to 15 g/kg/hour
# boundedvars['wtheta'] = [0.05,0.6]
# boundedvars['divU'] = [0,1e-4]
# boundedvars['fCA'] = [0.1,1e8]
# boundedvars['CO2'] = [100,1000]
# boundedvars['ustar'] = [0.01,50]
# boundedvars['theta'] = [274,310]
# boundedvars['cc'] = [0,1]
# boundedvars['q'] = [0.002,0.020]
# boundedvars['wq'] = [0,0.1] #negative flux seems problematic because L going to very small values
#############################################################
###### end user input: parameter bounds ####################
#############################################################
for param in boundedvars:
if not hasattr(priorinput,param):
raise Exception('Parameter \''+ param + '\' in boundedvars does not occur in priorinput')
if boundedvars[param][0] is None:
boundedvars[param][0] = -np.inf
if boundedvars[param][1] is None:
boundedvars[param][1] = np.inf
#create inverse modelling framework, do check,...
optim = im.inverse_modelling(priormodel,write_to_file=write_to_f,use_backgr_in_cost=use_backgr_in_cost,StateVarNames=state,obsvarlist=obsvarlist,
pri_err_cov_matr=b_cov,paramboundspenalty=paramboundspenalty,abort_slow_minims=abort_slow_minims,boundedvars=boundedvars)
Hx_prior = {}
for item in obsvarlist:
Hx_prior[item] = priormodel.out.__dict__[item]
#The observations
obs_times = {}
obs_weights = {}
disp_units = {}
display_names = {}
measurement_error = {}
for item in obsvarlist:
###########################################################
###### user input: observation information ################
###########################################################
#for each of the variables provided in the observation list, link the model output variable
#to the correct observations that were read in. Also, specify the times, standard deviations of observational errors, and optional weights
#Optionally, you can provide a display name here, a name which name will be shown for the observations in the plots
#please use np.array or list as datastructure for the obs, obs errors, observation times or weights
if use_mean:
if item == 'Tmh':
optim.__dict__['obs_'+item] = np.array(Temp200_mean) #it is already a numpy array, but this might prevent modifying the original Temp200_mean array when optim.__dict__['obs_'+item] would get modified.
measurement_error[item] = np.array(stdevTemp200_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'K'
display_names[item] = 'T_200'
if item == 'Tmh2':
optim.__dict__['obs_'+item] = np.array(Temp140_mean)
measurement_error[item] = np.array(stdevTemp140_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'K'
if item == 'Tmh3':
optim.__dict__['obs_'+item] = np.array(Temp80_mean)
measurement_error[item] = np.array(stdevTemp80_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'K'
if item == 'Tmh4':
optim.__dict__['obs_'+item] = np.array(Temp40_mean)
measurement_error[item] = np.array(stdevTemp40_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'K'
if item == 'Tmh5':
optim.__dict__['obs_'+item] = np.array(Temp20_mean)
measurement_error[item] = np.array(stdevTemp20_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'K'
if item == 'Tmh6':
optim.__dict__['obs_'+item] = np.array(Temp10_mean)
measurement_error[item] = np.array(stdevTemp10_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'K'
if item == 'Tmh7':
optim.__dict__['obs_'+item] = np.array(Temp2_mean)
measurement_error[item] = np.array(stdevTemp2_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'K'
elif item == 'CO2mh':
optim.__dict__['obs_'+item] = np.array(CO2_200_mean)
measurement_error[item] = stdevCO2_200_hourly
obs_times[item] = hours_mean * 3600. #same as for temperature
disp_units[item] = 'ppm'
if use_weights:
obs_weights[item] = [1./4 for j in range(len(optim.__dict__['obs_'+item]))]
elif item == 'CO2mh2':
optim.__dict__['obs_'+item] = np.array(CO2_120_mean)
measurement_error[item] = stdevCO2_120_hourly
obs_times[item] = hours_mean * 3600.
if use_weights:
obs_weights[item] = [1./4 for j in range(len(optim.__dict__['obs_'+item]))]
disp_units[item] = 'ppm'
elif item == 'CO2mh3':
optim.__dict__['obs_'+item] = np.array(CO2_60_mean)
measurement_error[item] = stdevCO2_60_hourly
obs_times[item] = hours_mean * 3600.
if use_weights:
obs_weights[item] = [1./4 for j in range(len(optim.__dict__['obs_'+item]))]
disp_units[item] = 'ppm'
elif item == 'CO2mh4':
optim.__dict__['obs_'+item] = np.array(CO2_20_mean)
measurement_error[item] = stdevCO2_20_hourly
obs_times[item] = hours_mean * 3600.
if use_weights:
obs_weights[item] = [1./4 for j in range(len(optim.__dict__['obs_'+item]))]
disp_units[item] = 'ppm'
elif item == 'wCO2':
optim.__dict__['obs_'+item] = np.array(wCO2_mean)
measurement_error[item] = stdevwCO2_hourly
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'mg CO2 m$^{-2}$s$^{-1}$'
elif item == 'h':
optim.__dict__['obs_'+item] = np.array(BLH_mean) #we just have one day
print('WARNING: the obs of h are not really a mean...')
measurement_error[item] = [100 for j in range(len(optim.__dict__['obs_'+item]))]#we don't have info on this
obs_times[item] = np.array(dhour_BLH_mean) * 3600.
for i in range(len(obs_times[item])):
obs_times[item][i] = round(obs_times[item][i],0) #Very important, since otherwise the obs will be a fraction of a second off and will not be used
disp_units[item] = 'm'
elif item == 'qmh':
optim.__dict__['obs_'+item] = np.array(q200_mean)
measurement_error[item] = np.array(stdevq200_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'g kg$^{-1}$'
elif item == 'qmh2':
optim.__dict__['obs_'+item] = np.array(q140_mean)
measurement_error[item] = np.array(stdevq140_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'g kg$^{-1}$'
elif item == 'qmh3':
optim.__dict__['obs_'+item] = np.array(q80_mean)
measurement_error[item] = np.array(stdevq80_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'g kg$^{-1}$'
elif item == 'qmh4':
optim.__dict__['obs_'+item] = np.array(q40_mean)
measurement_error[item] = np.array(stdevq40_hourly)
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'g kg$^{-1}$'
elif item == 'qmh5':
optim.__dict__['obs_'+item] = np.array(q20_mean)
measurement_error[item] = stdevq20_hourly
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'g kg$^{-1}$'
elif item == 'qmh6':
optim.__dict__['obs_'+item] = np.array(q10_mean)
measurement_error[item] = stdevq10_hourly
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'g kg$^{-1}$'
elif item == 'qmh7':
optim.__dict__['obs_'+item] = np.array(q2_mean)
measurement_error[item] = stdevq2_hourly
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'g kg$^{-1}$'
elif item == 'ustar':
optim.__dict__['obs_'+item] = np.array(ustar_mean)
measurement_error[item] = stdevustar_hourly
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'm s$^{-1}$'
elif item == 'H':
optim.__dict__['obs_'+item] = np.array(H_mean)
measurement_error[item] = stdevH_hourly
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'W m$^{-2}$'
elif item == 'LE':
optim.__dict__['obs_'+item] = np.array(LE_mean)
measurement_error[item] = stdevLE_hourly
obs_times[item] = hours_mean * 3600.
disp_units[item] = 'W m$^{-2}$'
else:
refnumobs = np.sum(~np.isnan(np.array(BLH_selected))) #only for the weights, a reference number of the number of non-nan obs, chosen to be based on h here. When e.g. wco2 has more obs than this number,
#it will be given a lower weight per individual observation than h
obstimes_T = []
for i in range(starthour,endhour):
for minute in selectedminutes:
obstimes_T.append(i * 3600. + minute * 60.)
if item == 'Tmh':
optim.__dict__['obs_'+item] = np.array(Temp200_selected) #np.array since it is a pandas dataframe
measurement_error[item] = [0.1 for j in range(len(optim.__dict__['obs_'+item]))]#we don't have info on this
obs_times[item] = np.array(obstimes_T)
disp_units[item] = 'K'
display_names[item] = 'T$_{200}$'
if use_weights:
obs_weights[item] = [1./7*refnumobs*1/np.sum(~np.isnan(optim.__dict__['obs_'+item])) for j in range(len(optim.__dict__['obs_'+item]))]
# np.sum(~np.isnan(optim.__dict__['obs_'+item])) used here instead of len(optim.__dict__['obs_'+item]), since nan data should not count for the length of the observation array. ~ inverts the np.isnan array.
if item == 'Tmh2':
optim.__dict__['obs_'+item] = np.array(Temp140_selected)
measurement_error[item] = [0.1 for j in range(len(optim.__dict__['obs_'+item]))]#we don't have info on this
obs_times[item] = np.array(obstimes_T)
disp_units[item] = 'K'
display_names[item] = 'T$_{140}$'