-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanopygrid.py
1286 lines (1015 loc) · 48.6 KB
/
canopygrid.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
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 24 11:01:50 2017
@author: slauniai
******************************************************************************
CanopyGrid:
Gridded canopy and snow hydrology model for SpaFHy -integration
Based on simple schemes for computing water flows and storages within vegetation
canopy and snowpack at daily or sub-daily timesteps.
(C) Samuli Launiainen, 2016-
last edit: Oct 2018 / Samuli
******************************************************************************
"""
import numpy as np
eps = np.finfo(float).eps
class CanopyGrid():
def __init__(self, cpara, state, outputs=False):
"""
initializes CanopyGrid -object
Args:
cpara - parameter dict:
state - dict of initial state
outputs - True saves output grids to list at each timestep
Returns:
self - object
NOTE:
Currently the initialization assumes simulation start 1st Jan,
and sets self._LAI_decid and self.X equal to minimum values.
Also leaf-growth & senescence parameters are intialized to zero.
"""
epsi = 0.01 # small number
self.Lat = cpara['loc']['lat']
self.Lon = cpara['loc']['lon']
# physiology: transpi + floor evap
self.physpara = cpara['physpara']
# phenology & LAI cycle
self.phenopara = cpara['phenopara']
# canopy parameters and state
self.hc = state['hc'] + eps
self.cf = state['cf'] + eps
#print(np.unique(self.cf))
#print(self.cf.shape)
#self.cf = self.cf * 0 + eps
#self.cf = 0.1939 * ba / (0.1939 * ba + 1.69) + epsi
# canopy closure [-] as function of basal area ba m2ha-1;
# fitted to Korhonen et al. 2007 Silva Fennica Fig.2
spec_para = cpara['spec_para']
ptypes = {}
LAI = 0.0
for pt in list(spec_para.keys()):
ptypes[pt] = spec_para[pt]
ptypes[pt]['LAImax'] = state['LAI_' + pt]
self.ptypes = ptypes
# compute gridcell average LAI and photosynthesis-stomatal conductance parameters:
LAI = 0.0
Amax = 0.0
q50 = 0.0
g1 = 0.0
for pt in self.ptypes.keys():
if self.ptypes[pt]['lai_cycle']:
pt_lai = self.ptypes[pt]['LAImax'] * self.phenopara['lai_decid_min']
else:
pt_lai = self.ptypes[pt]['LAImax']
LAI += pt_lai
Amax += pt_lai * ptypes[pt]['amax']
q50 += pt_lai * ptypes[pt]['q50']
g1 += pt_lai * ptypes[pt]['g1']
self.LAI = LAI + epsi
self.physpara.update({'Amax': Amax / self.LAI, 'q50': q50 / self.LAI, 'g1': g1 / self.LAI})
del Amax, q50, g1, pt, LAI, pt_lai
# - compute start day of senescence: starts at first doy when daylength < self.phenopara['sdl']
doy = np.arange(1, 366)
dl = daylength(self.Lat, self.Lon, doy)
ix = np.max(np.where(dl > self.phenopara['sdl']))
self.phenopara['sso'] = doy[ix] # this is onset date for senescence
del ix
# snow model
self.wmax = cpara['interc']['wmax']
self.wmaxsnow = cpara['interc']['wmaxsnow']
self.Kmelt = cpara['snow']['kmelt']
self.Kfreeze = cpara['snow']['kfreeze']
self.R = cpara['snow']['r'] # max fraction of liquid water in snow
self.cAtten = cpara['snow']['cAtten']
# --- for computing aerodynamic resistances
self.zmeas = cpara['flow']['zmeas']
self.zground =cpara['flow']['zground'] # reference height above ground [m]
self.zo_ground = cpara['flow']['zo_ground'] # ground roughness length [m]
self.gsoil = self.physpara['gsoil']
# --- state variables
self.W = np.minimum(state['w'], self.wmax*self.LAI)
self.SWE = state['swe']
self.SWEi = self.SWE
self.SWEl = np.zeros(np.shape(self.SWE))
# deciduous leaf growth stage
# NOTE: this assumes simulations start 1st Jan each year !!!
self.DDsum = 0.0
self.X = 0.0
self._relative_lai = self.phenopara['lai_decid_min']
self._growth_stage = 0.0
self._senesc_stage = 0.0
# phenological state
self.fPheno = self.phenopara['fmin']
# create dictionary of empty lists for saving results
if outputs:
self.results = {'PotInf': [], 'Trfall': [], 'Interc': [], 'Evap': [],
'ET': [], 'Transpi': [], 'Efloor': [], 'SWE': [],
'LAI': [], 'Mbe': [], 'LAIfract': [], 'Unload': []
}
def run_timestep(self, doy, dt, Ta, Prec, Rg, Par, VPD, U=2.0, CO2=380.0,
Rew=1.0, beta=1.0, P=101300.0):
"""
Runs CanopyGrid instance for one timestep
IN:
doy - day of year
dt - timestep [s]
Ta - air temperature [degC], scalar or (n x m) -matrix
prec - precipitatation rate [mm/s]
Rg - global radiation [Wm-2], scalar or matrix
Par - photos. act. radiation [Wm-2], scalar or matrix
VPD - vapor pressure deficit [kPa], scalar or matrix
U - mean wind speed at ref. height above canopy top [ms-1], scalar or matrix
CO2 - atm. CO2 mixing ratio [ppm]
Rew - relative extractable water [-], scalar or matrix
beta - term for soil evaporation resistance (Wliq/FC) [-]
P - pressure [Pa], scalar or matrix
OUT:
updated CanopyGrid instance state variables
flux grids PotInf, Trfall, Interc, Evap, ET, MBE [mm]
"""
# Rn = 0.7 * Rg #net radiation
Rn = np.maximum(2.57 * self.LAI / (2.57 * self.LAI + 0.57) - 0.2,
0.55) * Rg # Launiainen et al. 2016 GCB, fit to Fig 2a
""" --- update grid-cell phenology, LAI and average Amax, g1 and q50: self.ddsum & self.X ---"""
self.update_daily(Ta, doy)
""" --- aerodynamic conductances --- """
Ra, Rb, Ras, ustar, Uh, Ug = aerodynamics(self.LAI, self.hc, U, w=0.01, zm=self.zmeas,
zg=self.zground, zos=self.zo_ground)
""" --- interception, evaporation and snowpack --- """
PotInf, Trfall, Evap, Interc, MBE, unload, W = self.canopy_water_snow(dt, Ta, Prec,
Rn, VPD, Ra=Ra)
"""--- dry-canopy evapotranspiration [mm s-1] --- """
Transpi, Efloor, Gc = self.dry_canopy_et(VPD, Par, Rn, Ta, Ra=Ra, Ras=Ras,
CO2=CO2, Rew=Rew, beta=beta, fPheno=self.fPheno)
Transpi = Transpi * dt
Efloor = Efloor * dt
ET = Transpi + Efloor + Evap
fPheno = self.fPheno
fLAI = self.LAI
cf = self.cf
#print(np.unique(fLAI))
#print(np.unique(self.hc))
# append results to lists; use only for testing small grids!
if hasattr(self, 'results'):
self.results['PotInf'].append(PotInf)
self.results['Trfall'].append(Trfall)
self.results['Interc'].append(Interc)
self.results['Evap'].append(Evap)
self.results['ET'].append(ET)
self.results['Transpi'].append(Transpi)
self.results['Efloor'].append(Efloor)
self.results['SWE'].append(self.SWE)
self.results['LAI'].append(self.LAI)
self.results['Mbe'].append(np.nanmax(MBE))
self.results['LAIfract'].append(self._relative_lai)
self.results['Unload'].append(unload)
return PotInf, Trfall, Interc, Evap, ET, Transpi, Efloor, MBE, fPheno, fLAI, W, cf
def update_daily(self, T, doy):
"""
updates temperature sum, leaf-area development, phenology and
computes effective parameters for grid-cell
Args:
T - daily mean temperature (degC)
doy - day of year
Returns:
None
"""
self._degreeDays(T, doy)
self._photoacclim(T)
# deciduous relative leaf-area index
self._lai_dynamics(doy)
# canopy effective photosynthesis-stomatal conductance parameters:
LAI = 0.0
Amax = 0.0
q50 = 0.0
g1 = 0.0
for pt in self.ptypes.keys():
if self.ptypes[pt]['lai_cycle']:
pt_lai = self.ptypes[pt]['LAImax'] * self._relative_lai
else:
pt_lai = self.ptypes[pt]['LAImax']
LAI += pt_lai
Amax += pt_lai * self.ptypes[pt]['amax']
q50 += pt_lai * self.ptypes[pt]['q50']
g1 += pt_lai * self.ptypes[pt]['g1']
self.LAI = LAI + eps
#print(doy, LAI, Amax / self.LAI, g1 / self.LAI)
self.physpara.update({'Amax': Amax / self.LAI, 'q50': q50 / self.LAI, 'g1': g1 / self.LAI})
def _degreeDays(self, T, doy):
"""
Calculates and updates degree-day sum from the current mean Tair.
INPUT:
T - daily mean temperature (degC)
doy - day of year 1...366 (integer)
"""
To = 5.0 # threshold temperature
if doy == 1: # reset in the beginning of the year
self.DDsum = 0.
else:
self.DDsum += np.maximum(0.0, T - To)
def _photoacclim(self, T):
"""
computes new stage of temperature acclimation and phenology modifier.
Peltoniemi et al. 2015 Bor.Env.Res.
IN: object, T = daily mean air temperature
OUT: None, updates object state
"""
self.X = self.X + 1.0 / self.phenopara['tau'] * (T - self.X) # degC
S = np.maximum(self.X - self.phenopara['xo'], 0.0)
fPheno = np.maximum(self.phenopara['fmin'],
np.minimum(S / self.phenopara['smax'], 1.0))
self.fPheno = fPheno
def _lai_dynamics(self, doy):
"""
Seasonal cycle of deciduous leaf area
Args:
self - object
doy - day of year
Returns:
none, updates state variables self._relative_lai, self._growth_stage,
self._senec_stage
"""
lai_min = self.phenopara['lai_decid_min']
ddo = self.phenopara['ddo']
ddur = self.phenopara['ddur']
sso = self.phenopara['sso']
sdur = self.phenopara['sdur']
# growth phase
if self.DDsum <= ddo:
f = lai_min
self._growth_stage = 0.
self._senesc_stage = 0.
elif self.DDsum > ddo:
self._growth_stage += 1.0 / ddur
f = np. minimum(1.0, lai_min + (1.0 - lai_min) * self._growth_stage)
# senescence phase
if doy > sso:
self._growth_stage = 0.
self._senesc_stage += 1.0 / sdur
f = 1.0 - (1.0 - lai_min) * np.minimum(1.0, self._senesc_stage)
self._relative_lai = f
def dry_canopy_et(self, D, Qp, AE, Ta, Ra=25.0, Ras=250.0, CO2=380.0,
Rew=1.0, beta=1.0, fPheno=1.0):
"""
Computes ET from 2-layer canopy in absense of intercepted precipitiation,
i.e. in dry-canopy conditions
IN:
self - object
D - vpd in kPa
Qp - PAR in Wm-2
AE - available energy in Wm-2
Ta - air temperature degC
Ra - aerodynamic resistance (s/m)
Ras - soil aerodynamic resistance (s/m)
CO2 - atm. CO2 mixing ratio (ppm)
Rew - relative extractable water [-]
beta - relative soil conductance for evaporation [-]
fPheno - phenology modifier [-]
Args:
Tr - transpiration rate (mm s-1)
Efloor - forest floor evaporation rate (mm s-1)
Gc - canopy conductance (integrated stomatal conductance) (m s-1)
SOURCES:
Launiainen et al. (2016). Do the energy fluxes and surface conductance
of boreal coniferous forests in Europe scale with leaf area?
Global Change Biol.
Modified from: Leuning et al. 2008. A Simple surface conductance model
to estimate regional evaporation using MODIS leaf area index and the
Penman-Montheith equation. Water. Resources. Res., 44, W10419
Original idea Kelliher et al. (1995). Maximum conductances for
evaporation from global vegetation types. Agric. For. Met 85, 135-147
Samuli Launiainen, Luke
Last edit: 13.6.2018: TESTING UPSCALING
"""
# ---Amax and g1 as LAI -weighted average of conifers and decid.
rhoa = 101300.0 / (8.31 * (Ta + 273.15)) # mol m-3
#print('fPheno', fPheno)
Amax = self.physpara['Amax']
g1 = self.physpara['g1']
kp = self.physpara['kp'] # (-) attenuation coefficient for PAR
q50 = self.physpara['q50'] # Wm-2, half-sat. of leaf light response
rw = self.physpara['rw'] # rew parameter
rwmin = self.physpara['rwmin'] # rew parameter
tau = np.exp(-kp * self.LAI) # fraction of Qp at ground relative to canopy top
"""--- canopy conductance Gc (integrated stomatal conductance)----- """
# fQ: Saugier & Katerji, 1991 Agric. For. Met., eq. 4. Leaf light response = Qp / (Qp + q50)
fQ = 1./ kp * np.log((kp*Qp + q50) / (kp*Qp*np.exp(-kp * self.LAI) + q50 + eps) )
# the next formulation is from Leuning et al., 2008 WRR for daily Gc; they refer to
# Kelliher et al. 1995 AFM but the resulting equation is not exact integral of K95.
# fQ = 1./ kp * np.log((Qp + q50) / (Qp*np.exp(-kp*self.LAI) + q50))
# soil moisture response: Lagergren & Lindroth, xxxx"""
fRew = np.minimum(1.0, np.maximum(Rew / rw, rwmin))
# fRew = 1.0
# CO2 -response of canopy conductance, derived from APES-simulations
# (Launiainen et al. 2016, Global Change Biology). relative to 380 ppm
fCO2 = 1.0 - 0.387 * np.log(CO2 / 380.0)
# leaf level light-saturated gs (m/s)
#gs = 1.6*(1.0 + g1 / np.sqrt(D)) * Amax / CO2 / rhoa
gs = np.minimum(1.6*(1.0 + g1 / np.sqrt(D))*Amax / 380. / rhoa, 0.1) # large values if D -> 0
# canopy conductance
Gc = gs * fQ * fRew * fCO2 * fPheno
Gc[Gc == 0] = eps
Gc[np.isnan(Gc)] = eps
""" --- transpiration rate --- """
Tr = penman_monteith((1.-tau)*AE, 1e3*D, Ta, Gc, 1./Ra, units='mm')
Tr[Tr < 0] = 0.0
#print(Tr)
"""--- forest floor evaporation rate--- """
# soil conductance is function of relative water availability
# gcs = 1. / self.soilrp * beta**2.0
# beta = Wliq / FC; Best et al., 2011 Geosci. Model. Dev. JULES
Gcs = self.gsoil
Efloor = beta * penman_monteith(tau * AE, 1e3*D, Ta, Gcs, 1./Ras, units='mm')
Efloor[self.SWE > 0] = 0.0 # no evaporation from floor if snow on ground or beta == 0
return Tr, Efloor, Gc
def canopy_water_snow(self, dt, T, Prec, AE, D, Ra=25.0, U=2.0):
"""
Calculates canopy water interception and SWE during timestep dt
Args:
self - object
dt - timestep [s]
T - air temperature (degC)
Prec - precipitation rate during (mm d-1)
AE - available energy (~net radiation) (Wm-2)
D - vapor pressure deficit (kPa)
Ra - canopy aerodynamic resistance (s m-1)
Returns:
self - updated state W, Wf, SWE, SWEi, SWEl
PotInf - potential infiltration to soil profile (mm)
Trfall - throughfall to snow / soil surface (mm)
Evap - evaporation / sublimation from canopy store (mm)
Interc - interception of canopy (mm)
MBE - mass balance error (mm)
Unload - undloading from canopy storage (mm)
Samuli Launiainen & Ari Laurén 2014 - 2017
Last edit 12 / 2017
"""
# quality of precipitation
Tmin = 0.0 # 'C, below all is snow
Tmax = 1.0 # 'C, above all is water
Tmelt = 0.0 # 'C, T when melting starts
# storage capacities mm
Wmax = self.wmax * self.LAI
Wmaxsnow = self.wmaxsnow * self.LAI
# melting/freezing coefficients mm/s
Kmelt = self.Kmelt - 1.64 * self.cf / dt # Kuusisto E, 'Lumi Suomessa'
Kfreeze = self.Kfreeze
kp = self.physpara['kp']
tau = np.exp(-kp*self.LAI) # fraction of Rn at ground
# inputs to arrays, needed for indexing later in the code
gridshape = np.shape(self.LAI) # rows, cols
if np.shape(T) != gridshape:
T = np.ones(gridshape) * T
Prec = np.ones(gridshape) * Prec
AE = np.ones(gridshape) * AE
D = np.ones(gridshape) * D
Ra = np.ones(gridshape) * Ra
Prec = Prec * dt # mm
# latent heat of vaporization (Lv) and sublimation (Ls) J kg-1
Lv = 1e3 * (3147.5 - 2.37 * (T + 273.15))
Ls = Lv + 3.3e5
# compute 'potential' evaporation / sublimation rates for each grid cell
erate = np.zeros(gridshape)
ixs = np.where((Prec == 0) & (T <= Tmin))
ixr = np.where((Prec == 0) & (T > Tmin))
Ga = 1. / Ra # aerodynamic conductance
# resistance for snow sublimation adopted from:
# Pomeroy et al. 1998 Hydrol proc; Essery et al. 2003 J. Climate;
# Best et al. 2011 Geosci. Mod. Dev.
Ce = 0.01*((self.W + eps) / Wmaxsnow)**(-0.4) # exposure coeff (-)
Sh = (1.79 + 3.0*U**0.5) # Sherwood numbner (-)
gi = Sh*self.W*Ce / 7.68 + eps # m s-1
erate[ixs] = dt / Ls[ixs] * penman_monteith((1.0 - tau[ixs])*AE[ixs],
1e3*D[ixs], T[ixs], gi[ixs],
Ga[ixs], units='W')
# evaporation of intercepted water, mm
gs = np.ones(gridshape) * 1e6
erate[ixr] = dt / Lv[ixr] * penman_monteith((1.0 - tau[ixr])*AE[ixr],
1e3*D[ixr], T[ixr], gs[ixr],
Ga[ixr], units='W')
# ---state of precipitation [as water (fW) or as snow(fS)]
fW = np.zeros(gridshape)
fS = np.zeros(gridshape)
fW[T >= Tmax] = 1.0
fS[T <= Tmin] = 1.0
ix = np.where((T > Tmin) & (T < Tmax))
fW[ix] = (T[ix] - Tmin) / (Tmax - Tmin)
fS[ix] = 1.0 - fW[ix]
del ix
# --- Local fluxes (mm)
Unload = np.zeros(gridshape) # snow unloading
Interc = np.zeros(gridshape) # interception
Melt = np.zeros(gridshape) # melting
Freeze = np.zeros(gridshape) # freezing
Evap = np.zeros(gridshape)
Melt_Freeze = np.zeros(gridshape)
""" --- initial conditions for calculating mass balance error --"""
Wo = self.W # canopy storage
SWEo = self.SWE # Snow water equivalent mm
""" --------- Canopy water storage change -----"""
# snow unloading from canopy, ensures also that seasonal LAI development does
# not mess up computations
ix = (T >= Tmax)
Unload[ix] = np.maximum(self.W[ix] - Wmax[ix], 0.0)
self.W = self.W - Unload
del ix
# dW = self.W - Wo
# Interception of rain or snow: asymptotic approach of saturation.
# Hedstrom & Pomeroy 1998. Hydrol. Proc 12, 1611-1625;
# Koivusalo & Kokkonen 2002 J.Hydrol. 262, 145-164.
ix = (T < Tmin)
Interc[ix] = (Wmaxsnow[ix] - self.W[ix]) \
* (1.0 - np.exp(-(self.cf[ix] / Wmaxsnow[ix]) * Prec[ix]))
del ix
# above Tmin, interception capacity equals that of liquid precip
ix = (T >= Tmin)
Interc[ix] = np.maximum(0.0, (Wmax[ix] - self.W[ix]))\
* (1.0 - np.exp(-(self.cf[ix] / Wmax[ix]) * Prec[ix]))
del ix
self.W = self.W + Interc # new canopy storage, mm
Trfall = Prec + Unload - Interc # Throughfall to field layer or snowpack
# evaporate from canopy and update storage
Evap = np.minimum(erate, self.W) # mm
self.W = self.W - Evap
""" Snowpack (in case no snow, all Trfall routed to floor) """
'''
ix = np.where(T >= Tmelt)
Melt[ix] = np.minimum(self.SWEi[ix], Kmelt[ix] * dt * (T[ix] - Tmelt)) # mm
del ix
ix = np.where(T < Tmelt)
Freeze[ix] = np.minimum(self.SWEl[ix], Kfreeze * dt * (Tmelt - T[ix])) # mm
del ix
# amount of water as ice and liquid in snowpack
Sice = np.maximum(0.0, self.SWEi + fS * Trfall + Freeze - Melt)
Sliq = np.maximum(0.0, self.SWEl + fW * Trfall - Freeze + Melt)
PotInf = np.maximum(0.0, Sliq - Sice * self.R) # mm
Sliq = np.maximum(0.0, Sliq - PotInf) # mm, liquid water in snow
# update Snowpack state variables
self.SWEl = Sliq
self.SWEi = Sice
self.SWE = self.SWEl + self.SWEi
'''
# melting positive, freezing negative
Melt_Freeze = np.where(T >= Tmelt,
np.minimum(self.SWEi, Kmelt * dt * (T - Tmelt)),
-np.minimum(self.SWEl, Kfreeze * dt * (Tmelt - T)))
# amount of water as ice and liquid in snowpack
Sice = np.maximum(0.0, self.SWEi + fS * Trfall - Melt_Freeze)
Sliq = np.maximum(0.0, self.SWEl + fW * Trfall + Melt_Freeze)
PotInf = np.maximum(0.0, Sliq - Sice * self.R) # mm
Sliq = np.maximum(0.0, Sliq - PotInf) # mm, liquid water in snow
# update Snowpack state variables
self.SWEl = Sliq
self.SWEi = Sice
self.SWE = self.SWEl + self.SWEi
# mass-balance error mm
MBE = (self.W + self.SWE) - (Wo + SWEo) - (Prec - Evap - PotInf)
W = self.W
return PotInf, Trfall, Evap, Interc, MBE, Unload, W
def canopy_water_snow_energy(self, dt, T, Prec, AE, D, Rg, RH, Ra=25.0, U=2.0):
"""
Calculates canopy water interception and SWE during timestep dt
Args:
self - object
dt - timestep [s]
T - air temperature (degC)
Prec - precipitation rate during (mm d-1)
AE - available energy (~net radiation) (Wm-2)
D - vapor pressure deficit (kPa)
Ra - canopy aerodynamic resistance (s m-1)
Returns:
self - updated state W, Wf, SWE, SWEi, SWEl
PotInf - potential infiltration to soil profile (mm)
Trfall - throughfall to snow / soil surface (mm)
Evap - evaporation / sublimation from canopy store (mm)
Interc - interception of canopy (mm)
MBE - mass balance error (mm)
Unload - undloading from canopy storage (mm)
Samuli Launiainen & Ari Laurén 2014 - 2017
Last edit 12 / 2017
"""
## JP EDIT 22.1
# new constants for energy snow
SBc = 4.89E-9 # Stefan-Boltzmann constant {MJ/day*m2*K^4)
rooW = 1000.0 # density of water [kg/m3]
Cw = 4.2E-3 # specific heat capacity of water [MJ/kg*C]
cair = 1.29E-3 # heat capacity of air [MJ/m3*C]
ds = 0.0 # zero-plane dispalcement for snow [m] (Walter et al 2005)
zms = 0.001 # momentum roughness for snow [m] (Walter et al 2005)
zhs = 0.0002 # heat and vapour roughness parameter for snow [m] (Walter et al 2005)
k = 0.41 # von Karman's constant
Rv = 4.63E-3 # gas constant for water vapour
Rt = 0.4615 # thermodynamic vapour constant [kJ/kg*K]
lamv = 2.800 # latent heat of vaporization [MJ/kg]
lamf = 0.333 # latent heat of fusion [MJ/kg]
Ci = 2.03E-3 # specific heat capacity of ice [MJ/kg*C]
# inputs to arrays, needed for indexing later in the code
gridshape = np.shape(self.LAI) # rows, cols
if np.shape(T) != gridshape:
T = np.ones(gridshape) * T
Prec = np.ones(gridshape) * Prec
AE = np.ones(gridshape) * AE
D = np.ones(gridshape) * D
Ra = np.ones(gridshape) * Ra
RH = np.ones(gridshape) * RH
Rg = np.ones(gridshape) * Rg
U = np.ones(gridshape) * U
Prec = Prec * dt # mm/d
# quality of precipitation
Tmin = self.Tmin # 'C, equal or below all is snow
Tmax = self.Tmax # 'C, above all is water
# ---proportion of state of precipitation [as water (fW) or as snow(fS)]
fW = np.zeros(gridshape)
fS = np.zeros(gridshape)
fW[T >= Tmax] = 1.0
fS[T <= Tmin] = 1.0
ix = np.where((T > Tmin) & (T < Tmax))
fW[ix] = (T[ix] - Tmin) / (Tmax - Tmin)
fS[ix] = 1.0 - fW[ix]
del ix
# latent heat of vaporization (Lv) and sublimation (Ls) J kg-1
Lv = 1e3 * (3147.5 - 2.37 * (T + 273.15))
Ls = Lv + 3.3e5
# storage capacities m
Wmax = self.wmax * self.LAI # storage capacity for rain (m)
Wmaxsnow = self.wmaxsnow * self.LAI # storage capacity for snow (m)
#kp = self.physpara['kp'] # canopy light attenuation parameter (-)
tau = np.exp(-self.cAtten*self.LAI) # fraction of Rn at ground
# reduction of windspeed due to vegetation (Tarboton and Luke 1996) (from Ala-aho et al.)
''' sama kuih aerodynamic functions ?'''
WS = U * (1 - (0.8 * self.cf))
# compute 'potential' evaporation / sublimation rates for each grid cell
erate = np.zeros(gridshape)
ixs = np.where((Prec == 0) & (T <= Tmin))
ixr = np.where((Prec == 0) & (T > Tmin))
Ga = 1. / Ra # aerodynamic conductance
# resistance for snow sublimation adopted from:
# Pomeroy et al. 1998 Hydrol proc; Essery et al. 2003 J. Climate;
# Best et al. 2011 Geosci. Mod. Dev.
Ce = 0.01*((self.W + eps) / Wmaxsnow)**(-0.4) # exposure coeff (-)
Sh = (1.79 + 3.0*U**0.5) # Sherwood numbner (-)
gi = Sh*self.W*Ce / 7.68 + eps # m s-1
erate[ixs] = dt / Ls[ixs] * penman_monteith((1.0 - tau[ixs])*AE[ixs],
1e3*D[ixs], T[ixs], gi[ixs],
Ga[ixs], units='W')
# evaporation of intercepted water, mm
gs = 1e6
erate[ixr] = dt / Lv[ixr] * penman_monteith((1.0 - tau[ixr])*AE[ixr],
1e3*D[ixr], T[ixr], gs,
Ga[ixr], units='W')
# --- Local fluxes (mm)
Unload = np.zeros(gridshape) # snow unloading
Interc = np.zeros(gridshape) # interception
Evap = np.zeros(gridshape) # evaporation
Subl = np.zeros(gridshape) # sublimation from snowpack
Meltrate = np.zeros(gridshape) # rate of melting/refreezing [m/d]
Freezerate = np.zeros(gridshape) # rate of melting/refreezing [m/d]
Qm = np.zeros(gridshape) # melt energy content
Qc = np.zeros(gridshape) # cold content
""" --- initial conditions for calculating mass balance error --"""
Wo = self.W # canopy storage
SWEo = self.SWE # Snow water equivalent mm
""" --------- Canopy water storage change -----"""
# snow unloading from canopy, ensures also that seasonal LAI development does
# not mess up computations
ix = (T >= Tmax)
Unload[ix] = np.maximum(self.W[ix] - Wmax[ix], 0.0)
self.W = self.W - Unload
del ix
# dW = self.W - Wo
# Interception of rain or snow: asymptotic approach of saturation.
# Hedstrom & Pomeroy 1998. Hydrol. Proc 12, 1611-1625;
# Koivusalo & Kokkonen 2002 J.Hydrol. 262, 145-164.
ix = (T < Tmin)
Interc[ix] = (Wmaxsnow[ix] - self.W[ix]) \
* (1.0 - np.exp(-(self.cf[ix] / Wmaxsnow[ix]) * Prec[ix]))
del ix
# above Tmin, interception capacity equals that of liquid precip
ix = (T >= Tmin)
Interc[ix] = np.maximum(0.0, (Wmax[ix] - self.W[ix]))\
* (1.0 - np.exp(-(self.cf[ix] / Wmax[ix]) * Prec[ix]))
del ix
self.W = self.W + Interc # new canopy storage, mm
Trfall = Prec + Unload - Interc # Throughfall to field layer or snowpack
# evaporate from canopy and update storage
Evap = np.minimum(erate, self.W) # mm
self.W = self.W - Evap
#print(self.SWE)
""" Snowpack (in case no snow, all Trfall routed to floor) """
# for this part, a conversion of units to meters is necessary
Trfallice = Trfall * fS * 1e-3 # m/d
Trfallliq = Trfall * fW * 1e-3 # m/d
SWE_m = np.ones(gridshape) # temp variable for SWE energy (m)
SWE_m = self.SWE * 1e-3
SWE_m0 = SWE_m
#Wliq_m = np.zeros(gridshape) # temp variable for liquid water in snowpack (m)
#Wice_m = np.zeros(gridshape) # temp variable for liquid water in snowpack (m)
# Albedo where there is very old snow
olds = np.where((SWE_m > 0) & (self.d_snow > 100))
self.alb[olds] = (0.94**self.d_nosnow[olds]**0.58)**self.albpow
# Albedo where there is newer snow
news = np.where((SWE_m > 0) & (self.d_snow < 100))
self.alb[news] = 0.94**self.d_nosnow[news]**0.58
# Ground albedo
nos = np.where(SWE_m <= 0)
self.alb[nos] = self.albground
#print(self.alb[1])
del olds, news, nos
# INCOMING SHORTWAVE RADIATION
# [MJ*d/m2] passing through canopy and transmitted by canopy (Wigmosta et al 1996)
''' Common with AE ?'''
radRs = Rg * 1e-6 * dt # W/m2 to MJ/d/m2
radRss = radRs * (1-self.alb) * (self.tau * self.cf + (1-self.cf)) # radRss = MJ/d*m2
# NET LONGWAVE RADIATION in the snowpack emitted by atmosphere, overstorey and lost by snowpack (Wigmosta et al. 1996)
# atmosphere emissivity, different for cloudy and clear days (Walter et al 2005/Campbell and Norman
ix = np.where(Prec > self.RDthres)
self.emAir[ix] = (0.72 + 0.005 * T[ix]) * (1 - 0.84) + 0.84
ax = np.where(Prec <= self.RDthres)
self.emAir[ax] = 0.72 + 0.005 * T[ax]
# Atmospheric longwave radiation
Ld = self.emAir * SBc * (273.15 + T)**4
# Longwave emitted by overstorey, assuming emissivity of unity
L0 = SBc * (273.15 + T)**4
# longwave emitted by snow, emissivity 0.97 from (Walter et al 2005)
Lss = 0.97 * SBc * (273.15 + self.Tsnow)**4
# Net longwave radiation [MJ/d*m2]
radLs = L0 * self.cf + (Ld * (1 - self.cf)) - Lss
# net TOTAL radation on the SNOWPACK
radRns = radRss + radLs # MJ/d*m2
# Advection from precipitation
# Heat from rain, both liquid and solid (Wigmosta et al. 1994), conversion from mm to m and kj to MJ
Qp = rooW * Cw * T * (Trfallice + 0.5 * Trfallice)
# Sensible heat exchange in the snowpack ...snow temperature from previous timestep is taken as input
# resistance to heat transfer (Walter et al 2005)
ras = ((np.log((self.zmeas - ds + zms) / zms) * np.log((self.zmeas - ds + zhs) / zhs)) / (k**2 * WS)) / dt
# Sensible heat transfer by turbulent convection [MJ/d*m2]
Qs = cair * (T - self.Tsnow) / ras
# HEAT from convective VAPOUR EXCHANGE (evaporation and condensation) ...snow temperature from previous timestep is takes as input
# saturation vapour pressure in a given air temperature (Allen et al 2000), converted to mbbar and scaled to actual with relative humidity data
pVap = 0.6108 * np.exp((17.27 * T) / (T + 237.3)) * 10 * RH / 100
# vapour density of air (Dingman 1993, eq D-7a) converted to [kg/m3]
rooA = (pVap / ((T + 273.15) * Rv)) / 1000
# vapour density at the snow surface (Walter et al 2005)
rooSA = np.exp((16.78 * self.Tsnow - 116.8) / (self.Tsnow + 273.3)) * (1 / ((273.15 + self.Tsnow) * Rt))
# latent heat flux [MJ/d*m2] (Walter et al 2005)
Ql = lamv * ((rooA - rooSA) / ras)
# sum of ENERGY INPUT/OUTPUT which will results in melting/refreezing and heating/cooling the snowpack
# positive fluxes add energy to the snowpack and negative remove energy from snowpack
Esum = radRns + Qp + Qs + Ql # MJ/dt*m2
#print('Esum = ', Esum)
# Energy for melt with different conditions
# if there is no snow, there can be no melt or refreezing
nos = np.where(SWE_m == 0)
Qm[nos] = 0
# If there is snow and energy to melt it
ix = np.where((SWE_m > 0) & (Esum > 0) & (self.Tsnow < 0))
# what is available for melt after heating the snowpack.
# If more cold content than heat, nothing left for melt (add 0.00001 for numerical stability)
Qm[ix] = np.maximum(0, Esum[ix] - (0 - self.Tsnow[ix]) * (1 / (Ci * (SWE_m[ix] + 0.00001) * rooW)))
# Snowpack isothermal, all energy is diverted to snowmelt !
ax = np.where((SWE_m > 0) & (Esum <= 0) & (self.Tsnow >= 0))
Qm[ax] = Esum[ax]
# If Esum negative but no water to freeze -> Qm = 0
ex = np.where((SWE_m > 0) & (Esum <= 0) & (self.Wliq == 0))
Qm[ex] = 0
# Esum negative and Wliq to freeze
yx = np.where((SWE_m > 0) & (Esum <= 0) & (self.Wliq != 0))
Qm[yx] = np.maximum(-rooW * lamf * self.Wliq[yx], Esum[yx])
del ix, ax, ex, yx
# snowpack cold content change
Qc = Esum - Qm
#print('Qc = ', Qc)
#print('Wliq', self.Wliq)
# mass balance formulation concept from (Wigmosta 1994) except that sublimation/deposition takes place from ice phase
# store values from previous timestep
Wliq_o = self.Wliq
Wice_o = self.Wice
self.Wice = np.maximum(0.0, self.Wice + Trfallice)
#print('Qm = ', Qm)
ix = np.where(Qm < 0)
Freezerate[ix] = np.maximum(Qm[ix] / (rooW * lamf), -self.Wliq[ix]) # rate of freezing
ax = np.where(Qm >= 0)
Meltrate[ax] = np.minimum(Qm[ax] / (rooW * lamf), self.Wice[ax]) # rate of melting
del ix, ax
self.Wice = np.maximum(0, self.Wice - Meltrate - Freezerate)
# calculate and limit evaporation/deposition
# sublimation/deposition to the solid ice phase, assuming there is ice left !! no evaporation from liquid phase...!
ix = np.where(self.Wice > 0)
Subl[ix] = np.maximum(Ql[ix] / (rooW * lamv), -self.Wice[ix])
del ix
# update the mass balance of the ice phase
# update snow ice content after sublimation, cannot go negative
self.Wice = np.maximum(0, self.Wice + Subl)
# mass balance for liquid phase
# liquid water in the snowpack [m], cannot exceed water retention capacity or go negative
# water is added via rain and added/removed via melting/freezing
self.Wliq = np.maximum(0, np.minimum(self.R * self.Wice, self.Wliq + Trfallliq + Meltrate))
# water flow out of the snowpack, a certain volume retained
self.Wliqout = np.maximum(0, (Wliq_o + Trfallliq + Meltrate) - self.R * self.Wice)
# COMFORM to variable naming and convert to [mm/d]
#Melt = self.Wliqout * 1000
self.Wliq = np.maximum(0, self.Wliq - self.Wliqout)
#print('Wliq out = ', self.Wliqout)
#print('Wliq = ', self.Wliq)
#print('Wice = ', self.Wice)
# total water content in snowpack
# total snow water equivalent a sum of liquid and ice fraction
SWE_m = self.Wice + self.Wliq
# save the change in SWE
self.deltaSWE = SWE_m - SWEo
# update snow temperature according to energy and mass balance
self.Tsnow0 = self.Tsnow
# constrain snow temperature
# with shallow snow depths snow temp equals air temp
ix = np.where(SWE_m < 0.05)
self.Tsnow[ix] = T[ix]
# excess energy from melting
ax = np.where(SWE_m >= 0.05)
self.Tsnow[ax] = self.Tsnow0[ax] + (Qc[ax] / (Ci * SWE_m[ax] * rooW)) # excess energy from melting
# during melt Tsnow = 0
ex = np.where(Qm > 0)
self.Tsnow[ex] = 0.0
# cannot go too cold, miniimise to AT. This breaks the energy conservation so this could be improved. Perhaps introduce soil energy store where excess energy/cold content is diverted
# if snow temperature tries to go below -4, set lower limit to air temperature
yx = np.where(self.Tsnow < -4.0)
self.Tsnow[yx] = np.maximum(self.Tsnow[yx], T[yx])
self.Tsnow = np.minimum(self.Tsnow, 0.0) # cannot be positive
# set the internal energy flux variables to 0 as long as the SWE is 0
xx = np.where(SWE_m == 0)
Ql[xx] = 0.0
Qs[xx] = 0.0
Qc[xx] = 0.0
Qm[xx] = 0.0
del ix, ax, ex, yx
self.SWE = SWE_m * 100
PotInf = np.maximum(0.0, self.Wliq - self.Wice * self.R)
PotInf = PotInf * 1000
# mass-balance error mm
MBE = (self.W + self.SWE) - (Wo + SWEo) - (Prec - Evap - PotInf)
#print('ESUM = ', Esum)
#print('Potinf =', PotInf)
#print('Wliq = ', self.Wliq)
#print('Wice =', self.Wice)
###################################################################################################################################################################
###################################################################################################################################################################
###################################################################################################################################################################
###################################################################################################################################################################
'''
ix = np.where(T >= Tmelt)
Melt[ix] = np.minimum(self.SWEi[ix], Kmelt[ix] * dt * (T[ix] - Tmelt)) # mm
del ix
ix = np.where(T < Tmelt)
Freeze[ix] = np.minimum(self.SWEl[ix], Kfreeze * dt * (Tmelt - T[ix])) # mm
del ix
# amount of water as ice and liquid in snowpack
Sice = np.maximum(0.0, self.SWEi + fS * Trfall + Freeze - Melt)
Sliq = np.maximum(0.0, self.SWEl + fW * Trfall - Freeze + Melt)
PotInf = np.maximum(0.0, Sliq - Sice * self.R) # mm
Sliq = np.maximum(0.0, Sliq - PotInf) # mm, liquid water in snow
# update Snowpack state variables
self.SWEl = Sliq
self.SWEi = Sice
self.SWE = self.SWEl + self.SWEi
'''
ix = np.where(Trfallice < 0.001)
self.d_nosnow[ix] = np.minimum(30, self.d_nosnow[ix] + 1)
ax = np.where(Trfallice > 0.001)
self.d_nosnow[ax] = 1