-
Notifications
You must be signed in to change notification settings - Fork 1
/
ecape_parcel.py
1813 lines (1454 loc) · 61.4 KB
/
ecape_parcel.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
"""Calculate the entraining CAPE (ECAPE) of a parcel"""
import math
import sys
from typing import Callable, Tuple
import metpy.calc as mpcalc
import numpy as np
import pint
from metpy.constants import dry_air_spec_heat_press, earth_gravity
from metpy.units import check_units, units
from numpy.typing import NDArray as PintList
@check_units("[pressure]", "[temperature]", "[temperature]")
def _get_parcel_profile(
pressure: PintList,
temperature: PintList,
dew_point_temperature: PintList,
parcel_func: Callable = None,
) -> PintList:
"""
Retrieve a parcel's temperature profile.
Args:
pressure:
Total atmospheric pressure
temperature:
Air temperature
dew_point_temperature:
Dew point temperature
parcel_func:
parcel profile retrieval callable via MetPy
Returns:
parcel_profile
"""
# if surface-based, skip this process, None is default for lfc, el MetPy calcs
if parcel_func:
# calculate the parcel's starting temperature, then parcel temperature profile
parcel_p, parcel_t, parcel_td, *parcel_i = parcel_func(
pressure, temperature, dew_point_temperature
)
parcel_profile = mpcalc.parcel_profile(pressure, parcel_t, parcel_td)
else:
parcel_profile = None
return parcel_profile
@check_units("[pressure]", "[length]", "[temperature]", "[temperature]")
def calc_lfc_height(
pressure: PintList,
height_msl: PintList,
temperature: PintList,
dew_point_temperature: PintList,
parcel_func: Callable,
) -> Tuple[int, pint.Quantity]:
"""
Retrieve a parcel's level of free convection (lfc).
Args:
pressure:
Total atmospheric pressure
height_msl:
Atmospheric heights at the levels given by 'pressure'.
temperature:
Air temperature
dew_point_temperature:
Dew point temperature
parcel_func:
parcel profile retrieval callable via MetPy
Returns:
lfc:
index of the last instance of negative buoyancy below the lfc
lfc_z:
height of the last instance of negative buoyancy below the lfc
"""
# calculate the parcel's temperature profile
parcel_profile = _get_parcel_profile(pressure, temperature, dew_point_temperature, parcel_func)
# print("profile:", parcel_func)
# for i in range(len(temperature)):
# print(i, temperature[i], parcel_profile[i].to('degC'))
# calculate the lfc, select the appropriate index & associated height
lfc_p, lfc_t = mpcalc.lfc(
pressure, temperature, dew_point_temperature, parcel_temperature_profile=parcel_profile
)
if math.isnan(lfc_p.m):
return None, None
lfc_idx = (pressure - lfc_p > 0).nonzero()[0][-1]
lfc_z = height_msl[lfc_idx]
return lfc_idx, lfc_z
@check_units("[pressure]", "[length]", "[temperature]", "[temperature]")
def calc_el_height(
pressure: PintList,
height_msl: PintList,
temperature: PintList,
dew_point_temperature: PintList,
parcel_func: Callable,
) -> Tuple[int, pint.Quantity]:
"""
Retrieve a parcel's equilibrium level (el).
Args:
pressure:
Total atmospheric pressure
height_msl:
Atmospheric heights at the levels given by 'pressure'.
temperature:
Air temperature
dew_point_temperature:
Dew point temperature
parcel_func:
parcel profile retrieval callable via MetPy
Returns:
el_idx:
index of the last instance of positive buoyancy below the el
el_z:
height of the last instance of positive buoyancy below the el
"""
# calculate the parcel's temperature profile
parcel_profile = _get_parcel_profile(pressure, temperature, dew_point_temperature, parcel_func)
# calculate the el, select the appropriate index & associated height
el_p, el_t = mpcalc.el(
pressure, temperature, dew_point_temperature, parcel_temperature_profile=parcel_profile
)
if math.isnan(el_p.m):
return None, None
el_idx = (pressure - el_p > 0).nonzero()[0][-1]
el_z = height_msl[el_idx]
return el_idx, el_z
@check_units("[pressure]", "[speed]", "[speed]", "[length]")
def calc_sr_wind(
pressure: PintList,
u_wind: PintList,
v_wind: PintList,
height_msl: PintList,
infl_bottom: pint.Quantity = 0 * units("m"),
infl_top: pint.Quantity = 1000 * units("m"),
storm_motion_type: str = "right_moving",
sm_u: pint.Quantity = None,
sm_v: pint.Quantity = None,
) -> pint.Quantity:
"""
Calculate the mean storm relative (as compared to Bunkers right motion) wind magnitude in the 0-1 km AGL layer
Modified by Amelia Urquhart to allow for custom inflow layers as well as a choice between Bunkers right, Bunkers left, and Mean Wind
Args:
pressure:
Total atmospheric pressure
u_wind:
X component of the wind
v_wind
Y component of the wind
height_msl:
Atmospheric heights at the levels given by 'pressure'.
Returns:
sr_wind:
0-1 km AGL average storm relative wind magnitude
"""
height_agl = height_msl - height_msl[0]
bunkers_right, bunkers_left, mean_wind = mpcalc.bunkers_storm_motion(
pressure, u_wind, v_wind, height_agl
) # right, left, mean
u_sr = None
v_sr = None
if "left_moving" == storm_motion_type:
u_sr = u_wind - bunkers_left[0] # u-component
v_sr = v_wind - bunkers_left[1] # v-component
elif "mean_wind" == storm_motion_type:
u_sr = u_wind - mean_wind[0] # u-component
v_sr = v_wind - mean_wind[1] # v-component
elif "user_defined" == storm_motion_type and sm_u != None and sm_v != None:
u_sr = u_wind - sm_u # u-component
v_sr = v_wind - sm_v # v-component
else:
u_sr = u_wind - bunkers_right[0] # u-component
v_sr = v_wind - bunkers_right[1] # v-component
u_sr_1km = u_sr[np.nonzero((height_agl >= infl_bottom) & (height_agl <= infl_top))]
v_sr_1km = v_sr[np.nonzero((height_agl >= infl_bottom) & (height_agl <= infl_top))]
sr_wind = np.mean(mpcalc.wind_speed(u_sr_1km, v_sr_1km))
return sr_wind
@check_units("[pressure]", "[length]", "[temperature]", "[mass]/[mass]")
def calc_mse(
pressure: PintList, height_msl: PintList, temperature: PintList, specific_humidity: PintList
) -> Tuple[PintList, PintList]:
"""
Calculate the moist static energy terms of interest.
Args:
pressure:
Total atmospheric pressure
height_msl:
Atmospheric heights at the levels given by 'pressure'.
temperature:
Air temperature
specific_humidity:
Specific humidity
Returns:
moist_static_energy_bar:
Mean moist static energy from the surface to a layer
moist_static_energy_star:
Saturated moist static energy
"""
# calculate MSE_bar
moist_static_energy = mpcalc.moist_static_energy(height_msl, temperature, specific_humidity)
moist_static_energy_bar = np.cumsum(moist_static_energy) / np.arange(
1, len(moist_static_energy) + 1
)
moist_static_energy_bar = moist_static_energy_bar.to("J/kg")
# calculate MSE*
saturation_mixing_ratio = mpcalc.saturation_mixing_ratio(pressure, temperature)
moist_static_energy_star = mpcalc.moist_static_energy(
height_msl, temperature, saturation_mixing_ratio
)
moist_static_energy_star = moist_static_energy_star.to("J/kg")
return moist_static_energy_bar, moist_static_energy_star
@check_units("[energy]/[mass]", "[energy]/[mass]", "[temperature]")
def calc_integral_arg(moist_static_energy_bar, moist_static_energy_star, temperature) -> PintList:
"""
Calculate the contents of the integral defined in the NCAPE equation (54).
Args:
moist_static_energy_bar:
Mean moist static energy from the surface to a layer
moist_static_energy_star:
Saturated moist static energy
temperature:
Air temperature
Returns:
integral_arg:
Contents of integral defined in NCAPE eqn. 54
"""
# NCAPE eqn 54 integrand, see compute_NCAPE.m L32
integral_arg = -(earth_gravity / (dry_air_spec_heat_press * temperature)) * (
moist_static_energy_bar - moist_static_energy_star
)
return integral_arg
@check_units("[length]/[time]**2", "[length]", "[dimensionless]", "[dimensionless]")
def calc_ncape(
integral_arg: PintList, height_msl: PintList, lfc_idx: int, el_idx: int
) -> pint.Quantity:
"""
Calculate the buoyancy dilution potential (NCAPE)
Args:
integral_arg:
Contents of integral defined in NCAPE eqn. 54
height_msl:
Atmospheric heights at the levels given by 'pressure'.
lfc_idx:
Index of the last instance of negative buoyancy below the lfc
el_idx:
Index of the last instance of positive buoyancy below the el
Returns:
ncape:
Buoyancy dilution potential of the free troposphere (eqn. 54)
"""
# see compute_NCAPE.m L41
ncape = np.sum(
(0.5 * integral_arg[lfc_idx:el_idx] + 0.5 * integral_arg[lfc_idx + 1 : el_idx + 1])
* (height_msl[lfc_idx + 1 : el_idx + 1] - height_msl[lfc_idx:el_idx])
)
return ncape
# Borrowed directly from ECAPE_FUNCTIONS
# ==============================================================================
# descriminator function between liquid and ice (i.e., omega defined in the
# beginning of section 2e in Peters et al. 2022)
def omega(T, T1, T2):
return ((T - T1) / (T2 - T1)) * np.heaviside((T - T1) / (T2 - T1), 1) * np.heaviside(
(1 - (T - T1) / (T2 - T1)), 1
) + np.heaviside(-(1 - (T - T1) / (T2 - T1)), 1)
def domega(T, T1, T2):
return (np.heaviside(T1 - T, 1) - np.heaviside(T2 - T, 1)) / (T2 - T1)
# ==============================================================================
# Borrowed directly from ECAPE_FUNCTIONS
# ==============================================================================
# FUNCTION THAT CALCULATES THE SATURATION MIXING RATIO
def compute_rsat(T, p, iceflag, T1, T2):
# THIS FUNCTION COMPUTES THE SATURATION MIXING RATIO, USING THE INTEGRATED
# CLAUSIUS CLAPEYRON EQUATION (eq. 7-12 in Peters et al. 2022).
# https://doi-org.ezaccess.libraries.psu.edu/10.1175/JAS-D-21-0118.1
# input arguments
# T temperature (in K)
# p pressure (in Pa)
# iceflag (give mixing ratio with respect to liquid (0), combo liquid and
# ice (2), or ice (3)
# T1 warmest mixed-phase temperature
# T2 coldest mixed-phase temperature
# NOTE: most of my scripts and functions that use this function need
# saturation mass fraction qs, not saturation mixing ratio rs. To get
# qs from rs, use the formula qs = (1 - qt)*rs, where qt is the total
# water mass fraction
# CONSTANTS
Rd = 287.04 # %dry gas constant
Rv = 461.5 # water vapor gas constant
epsilon = Rd / Rv
cp = 1005 # specific heat of dry air at constant pressure
g = 9.81 # gravitational acceleration
xlv = 2501000 # reference latent heat of vaporization at the triple point temperature
xls = 2834000 # reference latent heat of sublimation at the triple point temperature
cpv = 1870 # specific heat of water vapor at constant pressure
cpl = 4190 # specific heat of liquid water
cpi = 2106 # specific heat of ice
ttrip = 273.15 # triple point temperature
eref = 611.2 # reference pressure at the triple point temperature
omeg = omega(T, T1, T2)
if iceflag == 0:
term1 = (cpv - cpl) / Rv
term2 = (xlv - ttrip * (cpv - cpl)) / Rv
esl = np.exp((T - ttrip) * term2 / (T * ttrip)) * eref * (T / ttrip) ** (term1)
qsat = epsilon * esl / (p - esl)
elif (
iceflag == 1
): # give linear combination of mixing ratio with respect to liquid and ice (eq. 20 in Peters et al. 2022)
term1 = (cpv - cpl) / Rv
term2 = (xlv - ttrip * (cpv - cpl)) / Rv
esl_l = np.exp((T - ttrip) * term2 / (T * ttrip)) * eref * (T / ttrip) ** (term1)
qsat_l = epsilon * esl_l / (p - esl_l)
term1 = (cpv - cpi) / Rv
term2 = (xls - ttrip * (cpv - cpi)) / Rv
esl_i = np.exp((T - ttrip) * term2 / (T * ttrip)) * eref * (T / ttrip) ** (term1)
qsat_i = epsilon * esl_i / (p - esl_i)
qsat = (1 - omeg) * qsat_l + (omeg) * qsat_i
elif iceflag == 2: # only give mixing ratio with respect to ice
term1 = (cpv - cpi) / Rv
term2 = (xls - ttrip * (cpv - cpi)) / Rv
esl = np.exp((T - ttrip) * term2 / (T * ttrip)) * eref * (T / ttrip) ** (term1)
esl = min(esl, p * 0.5)
qsat = epsilon * esl / (p - esl)
return qsat
# ==============================================================================
# Borrowed directly from ECAPE_FUNCTIONS
# ==============================================================================
# FUNCTION THAT COMPUTES NCAPE
def compute_NCAPE(T0, p0, q0, z0, T1, T2, LFC, EL):
Rd = 287.04 # %DRY GAS CONSTANT
Rv = 461.5 # %GAS CONSTANT FOR WATEEER VAPRR
epsilon = Rd / Rv # %RATO OF THE TWO
cp = 1005 # HEAT CAPACITY OF DRY AIR AT CONSTANT PRESSUREE
gamma = Rd / cp # POTENTIAL TEMPERATURE EXPONENT
g = 9.81 # GRAVITATIONAL CONSTANT
Gamma_d = g / cp # DRY ADIABATIC LAPSE RATE
xlv = 2501000 # LATENT HEAT OF VAPORIZATION AT TRIPLE POINT TEMPERATURE
xls = 2834000 # LATENT HEAT OF SUBLIMATION AT TRIPLE POINT TEMPERATURE
cpv = 1870 # HEAT CAPACITY OF WATER VAPOR AT CONSTANT PRESSURE
cpl = 4190 # HEAT CAPACITY OF LIQUID WATER
cpi = 2106 # HEAT CAPACITY OF ICE
pref = 611.65 # REFERENCE VAPOR PRESSURE OF WATER VAPOR AT TRIPLE POINT TEMPERATURE
ttrip = 273.15 # TRIPLE POINT TEMPERATURE
# COMPUTE THE MOIST STATIC ENERGY
MSE0 = cp * T0 + xlv * q0 + g * z0
# COMPUTE THE SATURATED MOIST STATIC ENERGY
rsat = compute_rsat(T0, p0, 0, T1, T2)
qsat = (1 - rsat) * rsat
MSE0_star = cp * T0 + xlv * qsat + g * z0
# COMPUTE MSE0_BAR
MSE0bar = np.zeros(MSE0.shape)
# for iz in np.arange(0,MSE0bar.shape[0],1):
# MSE0bar[iz]=np.mean(MSE0[1:iz])
MSE0bar[0] = MSE0[0]
for iz in np.arange(1, MSE0bar.shape[0], 1):
MSE0bar[iz] = (
0.5
* np.sum((MSE0[0:iz] + MSE0[1 : iz + 1]) * (z0[1 : iz + 1] - z0[0:iz]))
/ (z0[iz] - z0[0])
)
int_arg = -(g / (cp * T0)) * (MSE0bar - MSE0_star)
ddiff = abs(z0 - LFC)
mn = np.min(ddiff)
ind_LFC = np.where(ddiff == mn)[0][0]
ddiff = abs(z0 - EL)
mn = np.min(ddiff)
ind_EL = np.where(ddiff == mn)[0][0]
# ind_LFC=max(ind_LFC);
# ind_EL=max(ind_EL);
NCAPE = np.maximum(
np.nansum(
(0.5 * int_arg[ind_LFC : ind_EL - 1] + 0.5 * int_arg[ind_LFC + 1 : ind_EL])
* (z0[ind_LFC + 1 : ind_EL] - z0[ind_LFC : ind_EL - 1])
),
0,
)
return NCAPE, MSE0_star, MSE0bar
# ==============================================================================
@check_units("[speed]", "[dimensionless]", "[length]**2/[time]**2", "[energy]/[mass]")
def calc_ecape_a(
sr_wind: PintList, psi: pint.Quantity, ncape: pint.Quantity, cape: pint.Quantity
) -> pint.Quantity:
"""
Calculate the entraining cape of a parcel
Args:
sr_wind:
0-1 km AGL average storm relative wind magnitude
psi:
Parameter defined in eqn. 52, constant for a given equilibrium level
ncape:
Buoyancy dilution potential of the free troposphere (eqn. 54)
cape:
Convective available potential energy (CAPE, user-defined type)
Returns:
ecape:
Entraining CAPE (eqn. 55)
"""
# broken into terms for readability
term_a = sr_wind**2 / 2.0
term_b = (-1 - psi - (2 * psi / sr_wind**2) * ncape) / (4 * psi / sr_wind**2)
term_c = (
np.sqrt(
(1 + psi + (2 * psi / sr_wind**2) * ncape) ** 2
+ 8 * (psi / sr_wind**2) * (cape - (psi * ncape))
)
) / (4 * psi / sr_wind**2)
ecape_a = term_a + term_b + term_c
# set to 0 if negative
return ecape_a.to("J/kg") if ecape_a >= 0 else 0
@check_units("[length]")
def calc_psi(el_z: pint.Quantity) -> pint.Quantity:
"""
Calculate the constant psi as denoted in eqn. 52
Args:
el_z:
height of the last instance of positive buoyancy below the el
Returns:
psi:
Parameter defined in eqn. 52, constant for a given equilibrium level, see COMPUTE_ECAPE.m L88 (pitchfork)
"""
# additional constants as denoted in section 4 step 1.
sigma = 1.1 * units("dimensionless")
alpha = 0.8 * units("dimensionless")
l_mix = 120.0 * units("m")
pr = (1.0 / 3.0) * units("dimensionless") # prandtl number
ksq = 0.18 * units("dimensionless") # von karman constant
psi = (ksq * alpha**2 * np.pi**2 * l_mix) / (4 * pr * sigma**2 * el_z)
return psi
@check_units("[length]", "[pressure]", "[temperature]", "[mass]/[mass]", "[speed]", "[speed]")
def calc_ecape(
height_msl: PintList,
pressure: PintList,
temperature: PintList,
specific_humidity: PintList,
u_wind: PintList,
v_wind: PintList,
cape_type: str = "most_unstable",
undiluted_cape: pint.Quantity = None,
inflow_bottom: pint.Quantity = 0 * units("m"),
inflow_top: pint.Quantity = 1000 * units("m"),
storm_motion: str = "right_moving",
lfc: pint.Quantity = None,
el: pint.Quantity = None,
u_sm: pint.Quantity = None,
v_sm: pint.Quantity = None,
) -> pint.Quantity:
"""
Calculate the entraining CAPE (ECAPE) of a parcel
Parameters:
------------
height_msl: np.ndarray[pint.Quantity]
Atmospheric heights at the levels given by 'pressure' (MSL)
pressure: np.ndarray[pint.Quantity]
Total atmospheric pressure
temperature: np.ndarray[pint.Quantity]
Air temperature
specific humidity: np.ndarray[pint.Quantity]
Specific humidity
u_wind: np.ndarray[pint.Quantity]
X component of the wind
v_wind np.ndarray[pint.Quantity]
Y component of the wind
cape_type: str
Variation of CAPE desired. 'most_unstable' (default), 'surface_based', or 'mixed_layer'
undiluted_cape: pint.Quantity
User-provided undiluted CAPE value
Returns:
----------
ecape : 'pint.Quantity'
Entraining CAPE
"""
cape_func = {
"most_unstable": mpcalc.most_unstable_cape_cin,
"surface_based": mpcalc.surface_based_cape_cin,
"mixed_layer": mpcalc.mixed_layer_cape_cin,
}
parcel_func = {
"most_unstable": mpcalc.most_unstable_parcel,
"surface_based": None,
"mixed_layer": mpcalc.mixed_parcel,
}
# calculate cape
dew_point_temperature = mpcalc.dewpoint_from_specific_humidity(
pressure, temperature, specific_humidity
)
# whether the user has not / has overidden the cape calculations
if not undiluted_cape:
cape, _ = cape_func[cape_type](pressure, temperature, dew_point_temperature)
else:
cape = undiluted_cape
# lfc_idx = None
lfc_z = None
# el_idx = None
el_z = None
# print("cape_type:", cape_type)
# print("parcel_func:", parcel_func[cape_type])
if lfc is None:
# print("doing lfc_idx as calc lfc height")
# calculate the level of free convection (lfc) and equilibrium level (el) indexes
_, lfc_z = calc_lfc_height(
pressure, height_msl, temperature, dew_point_temperature, parcel_func[cape_type]
)
_, el_z = calc_el_height(
pressure, height_msl, temperature, dew_point_temperature, parcel_func[cape_type]
)
else:
# print("doing lfc_idx as np where")
# lfc_idx = np.where(height_msl > lfc)[0][0]
# el_idx = np.where(height_msl > el)[0][0]
# print(i, temperature[i], parcel_profile[i].to('degC'))
el_z = el
lfc_z = lfc
# calculate the buoyancy dilution potential (ncape)
# moist_static_energy_bar, moist_static_energy_star = calc_mse(pressure, height_msl, temperature, specific_humidity)
# integral_arg = calc_integral_arg(moist_static_energy_bar, moist_static_energy_star, temperature)
# ncape = calc_ncape(integral_arg, height_msl, lfc_idx, el_idx)
ncape = compute_NCAPE(
temperature.to("degK").magnitude,
pressure.to("Pa").magnitude,
specific_humidity.to("kg/kg").magnitude,
height_msl.to("m").magnitude,
273.15,
253.15,
lfc_z.to("m").magnitude,
el_z.to("m").magnitude,
)
ncape = ncape[0] * units("J/kg")
# calculate the storm relative (sr) wind
sr_wind = calc_sr_wind(
pressure,
u_wind,
v_wind,
height_msl,
infl_bottom=inflow_bottom,
infl_top=inflow_top,
storm_motion_type=storm_motion,
sm_u=u_sm,
sm_v=v_sm,
)
# calculate the entraining cape (ecape)
psi = calc_psi(el_z)
ecape_a = calc_ecape_a(sr_wind, psi, ncape, cape)
return ecape_a
@check_units("[length]", "[pressure]", "[temperature]", "[mass]/[mass]", "[speed]", "[speed]")
def calc_ecape_ncape(
height_msl: PintList,
pressure: PintList,
temperature: PintList,
specific_humidity: PintList,
u_wind: PintList,
v_wind: PintList,
cape_type: str = "most_unstable",
undiluted_cape: pint.Quantity = None,
inflow_bottom: pint.Quantity = 0 * units("m"),
inflow_top: pint.Quantity = 1000 * units("m"),
storm_motion: str = "right_moving",
lfc: pint.Quantity = None,
el: pint.Quantity = None,
u_sm: pint.Quantity = None,
v_sm: pint.Quantity = None,
) -> pint.Quantity:
"""
Calculate the entraining CAPE (ECAPE) of a parcel
Parameters:
------------
height_msl: np.ndarray[pint.Quantity]
Atmospheric heights at the levels given by 'pressure' (MSL)
pressure: np.ndarray[pint.Quantity]
Total atmospheric pressure
temperature: np.ndarray[pint.Quantity]
Air temperature
specific humidity: np.ndarray[pint.Quantity]
Specific humidity
u_wind: np.ndarray[pint.Quantity]
X component of the wind
v_wind np.ndarray[pint.Quantity]
Y component of the wind
cape_type: str
Variation of CAPE desired. 'most_unstable' (default), 'surface_based', or 'mixed_layer'
undiluted_cape: pint.Quantity
User-provided undiluted CAPE value
Returns:
----------
ecape : 'pint.Quantity'
Entraining CAPE
"""
cape_func = {
"most_unstable": mpcalc.most_unstable_cape_cin,
"surface_based": mpcalc.surface_based_cape_cin,
"mixed_layer": mpcalc.mixed_layer_cape_cin,
}
parcel_func = {
"most_unstable": mpcalc.most_unstable_parcel,
"surface_based": None,
"mixed_layer": mpcalc.mixed_parcel,
}
# calculate cape
dew_point_temperature = mpcalc.dewpoint_from_specific_humidity(
pressure, temperature, specific_humidity
)
# whether the user has not / has overidden the cape calculations
if not undiluted_cape:
cape, _ = cape_func[cape_type](pressure, temperature, dew_point_temperature)
else:
cape = undiluted_cape
lfc_idx = None
lfc_z = None
el_idx = None
el_z = None
# print("cape_type:", cape_type)
# print("parcel_func:", parcel_func[cape_type])
if lfc == None:
# print("doing lfc_idx as calc lfc height")
# calculate the level of free convection (lfc) and equilibrium level (el) indexes
lfc_idx, lfc_z = calc_lfc_height(
pressure, height_msl, temperature, dew_point_temperature, parcel_func[cape_type]
)
el_idx, el_z = calc_el_height(
pressure, height_msl, temperature, dew_point_temperature, parcel_func[cape_type]
)
else:
# print("doing lfc_idx as np where")
lfc_idx = np.where(height_msl > lfc)[0][0]
el_idx = np.where(height_msl > el)[0][0]
# print(i, temperature[i], parcel_profile[i].to('degC'))
el_z = el
lfc_z = lfc
# calculate the buoyancy dilution potential (ncape)
# moist_static_energy_bar, moist_static_energy_star = calc_mse(pressure, height_msl, temperature, specific_humidity)
# integral_arg = calc_integral_arg(moist_static_energy_bar, moist_static_energy_star, temperature)
# ncape = calc_ncape(integral_arg, height_msl, lfc_idx, el_idx)
ncape = compute_NCAPE(
temperature.to("degK").magnitude,
pressure.to("Pa").magnitude,
specific_humidity.to("kg/kg").magnitude,
height_msl.to("m").magnitude,
273.15,
253.15,
lfc_z.to("m").magnitude,
el_z.to("m").magnitude,
)
ncape = ncape[0] * units("J/kg")
# calculate the storm relative (sr) wind
sr_wind = calc_sr_wind(
pressure,
u_wind,
v_wind,
height_msl,
infl_bottom=inflow_bottom,
infl_top=inflow_top,
storm_motion_type=storm_motion,
sm_u=u_sm,
sm_v=v_sm,
)
# calculate the entraining cape (ecape)
psi = calc_psi(el_z)
ecape_a = calc_ecape_a(sr_wind, psi, ncape, cape)
return ecape_a, ncape
#
# AUTHOR: Amelia Urquhart (https://github.com/a-urq)
# VERSION: 1.2.2
# DATE: March 25, 2024
#
# relevant ECAPE constants
sigma = 1.6
alpha = 0.8
k2 = 0.18
L_mix = 120
Pr = 1 / 3
# @param updraftRadius Units: Meters
# @return entrainment_rate: Units: m^-1
def entrainment_rate(
cape: float, ecape: float, ncape: float, vsr: float, storm_column_height: float
) -> float:
E_A_tilde = ecape / cape
N_tilde = ncape / cape
vsr_tilde = vsr / np.sqrt(2 * cape)
E_tilde = E_A_tilde - vsr_tilde**2
entrainment_rate = (2 * (1 - E_tilde) / (E_tilde + N_tilde)) / (storm_column_height)
return entrainment_rate
def updraft_radius(entrainment_rate: float) -> float:
updraft_radius = np.sqrt(2 * k2 * L_mix / (Pr * entrainment_rate))
return updraft_radius
ECAPE_PARCEL_DZ: pint.Quantity = 20 * units.meter
# Unlike the Java version, this expects arrays sorted in order of increasing height, decreasing pressure
# This is to keep in line with MetPy conventions
# Returns Tuple of { parcel_pressure, parcel_height, parcel_temperature, parcel_qv, parcel_qt }
@check_units("[pressure]", "[length]", "[temperature]", "[temperature]", "[speed]", "[speed]")
def calc_ecape_parcel(
pressure: PintList,
height: PintList,
temperature: PintList,
dewpoint: PintList,
u_wind: PintList,
v_wind: PintList,
align_to_input_pressure_values: bool,
entrainment_switch: bool = True,
pseudoadiabatic_switch: bool = True,
cape_type: str = "most_unstable",
mixed_layer_depth_pressure: pint.Quantity = 100 * units("hPa"),
mixed_layer_depth_height: pint.Quantity = None,
storm_motion_type: str = "right_moving",
inflow_layer_bottom: pint.Quantity = 0 * units.kilometer,
inflow_layer_top: pint.Quantity = 1 * units.kilometer,
cape: pint.Quantity = None,
lfc: pint.Quantity = None,
el: pint.Quantity = None,
storm_motion_u: pint.Quantity = None,
storm_motion_v: pint.Quantity = None,
origin_pressure: pint.Quantity = None,
origin_height: pint.Quantity = None,
origin_temperature: pint.Quantity = None,
origin_dewpoint: pint.Quantity = None,
) -> Tuple[pint.Quantity, pint.Quantity, pint.Quantity, pint.Quantity, pint.Quantity]:
if cape_type not in ["most_unstable", "mixed_layer", "surface_based", "user_defined"]:
sys.exit(
"Invalid 'cape_type' kwarg. Valid cape_types include ['most_unstable', 'mixed_layer', 'surface_based', 'user_defined']"
)
if storm_motion_type not in ["right_moving", "left_moving", "mean_wind", "user_defined"]:
sys.exit(
"Invalid 'storm_motion_type' kwarg. Valid storm_motion_types include ['right_moving', 'left_moving', 'mean_wind', 'user_defined']"
)
specific_humidity = []
for i in range(len(pressure)):
pressure_0 = pressure[i]
dewpoint_0 = dewpoint[i]
q_0 = mpcalc.specific_humidity_from_dewpoint(pressure_0, dewpoint_0).magnitude
specific_humidity.append(q_0)
# print("amelia q0: ", pressure_0, q_0)
specific_humidity *= units("dimensionless")
# print(specific_humidity)
# moist_static_energy = mpcalc.moist_static_energy(height, temperature, specific_humidity).to("J/kg")
parcel_pressure = -1024
parcel_height = -1024
parcel_temperature = -1024
parcel_dewpoint = -1024
# have a "user_defined" switch option
if "user_defined" == cape_type:
if origin_pressure != None:
parcel_pressure = origin_pressure
else:
parcel_pressure = pressure[0]
if origin_height != None:
parcel_height = origin_height
else:
parcel_height = height[0]
if origin_temperature != None:
parcel_temperature = origin_temperature
else:
parcel_temperature = temperature[0]
if origin_dewpoint != None:
parcel_dewpoint = origin_dewpoint
else:
parcel_dewpoint = dewpoint[0]
elif "most_unstable" == cape_type:
parcel_pressure, parcel_temperature, parcel_dewpoint, mu_idx = mpcalc.most_unstable_parcel(
pressure, temperature, dewpoint
)
parcel_height = height[mu_idx]
elif "mixed_layer" == cape_type:
env_potential_temperature = mpcalc.potential_temperature(pressure, temperature)
env_specific_humidity = mpcalc.specific_humidity_from_dewpoint(pressure, dewpoint)
env_idxs_to_include_in_average = None
if mixed_layer_depth_pressure != None:
mixed_layer_top_pressure = pressure[0] - mixed_layer_depth_pressure
env_idxs_to_include_in_average = np.where(pressure >= mixed_layer_top_pressure)[0]
elif mixed_layer_depth_height != None:
mixed_layer_top_height = height[0] + mixed_layer_depth_height
env_idxs_to_include_in_average = np.where(height <= mixed_layer_top_height)[0]
pass
else:
mixed_layer_depth_pressure = 100 * units("hPa")
mixed_layer_top_pressure = pressure[0] - mixed_layer_depth_pressure
env_idxs_to_include_in_average = np.where(pressure >= mixed_layer_top_pressure)[0]
avg_potential_temperature_sum = 0.0
avg_specific_humidity_sum = 0.0
for i in range(len(env_idxs_to_include_in_average)):
avg_potential_temperature_sum += env_potential_temperature[
env_idxs_to_include_in_average[i]
]
avg_specific_humidity_sum += env_specific_humidity[env_idxs_to_include_in_average[i]]
avg_potential_temperature = avg_potential_temperature_sum / len(
env_idxs_to_include_in_average
)
avg_specific_humidity = avg_specific_humidity_sum / len(env_idxs_to_include_in_average)
parcel_pressure = pressure[0]
parcel_height = height[0]
parcel_temperature = mpcalc.temperature_from_potential_temperature(
parcel_pressure, avg_potential_temperature
)
parcel_dewpoint = mpcalc.dewpoint_from_specific_humidity(
parcel_pressure, parcel_temperature, avg_specific_humidity
)
elif "surface_based" == cape_type:
parcel_pressure = pressure[0]
parcel_height = height[0]
parcel_temperature = temperature[0]
parcel_dewpoint = dewpoint[0]
else:
parcel_pressure = pressure[0]
parcel_height = height[0]
parcel_temperature = temperature[0]
parcel_dewpoint = dewpoint[0]
# print("in house cape/el calc:", cape, el, entrainment_switch)
if (cape == None or lfc == None or el == None) and entrainment_switch == True:
# print("-- using in-house cape --")
undiluted_parcel_profile = calc_ecape_parcel(
pressure,
height,
temperature,
dewpoint,
u_wind,
v_wind,
align_to_input_pressure_values,
False,
pseudoadiabatic_switch,
cape_type,
mixed_layer_depth_pressure,
mixed_layer_depth_height,
storm_motion_type,
inflow_layer_bottom,
inflow_layer_top,
origin_pressure=origin_pressure,
origin_height=origin_height,
origin_temperature=origin_temperature,
origin_dewpoint=origin_dewpoint,
)
undiluted_parcel_profile_z = undiluted_parcel_profile[1]
undiluted_parcel_profile_T = undiluted_parcel_profile[2]
undiluted_parcel_profile_qv = undiluted_parcel_profile[3]
undiluted_parcel_profile_qt = undiluted_parcel_profile[4]
undil_cape, _, undil_lfc, undil_el = custom_cape_cin_lfc_el(
undiluted_parcel_profile_z,
undiluted_parcel_profile_T,
undiluted_parcel_profile_qv,
undiluted_parcel_profile_qt,
height,