-
Notifications
You must be signed in to change notification settings - Fork 13
/
justdoit.py
1693 lines (1455 loc) · 64.5 KB
/
justdoit.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
import astropy.constants as c
import astropy.units as u
import pandas as pd
import numpy as np
import os
from scipy import optimize
import PyMieScatt as ps
from .root_functions import advdiff, vfall,vfall_find_root,qvs_below_model, find_cond_t, solve_force_balance
from .calc_mie import fort_mie_calc, calc_new_mieff
from . import gas_properties
from . import pvaps
from .justplotit import plot_format, find_nearest_1d
from .direct_mmr_solver import direct_solver
def compute(atmo, directory = None, as_dict = True, og_solver = True,
direct_tol=1e-15, refine_TP = True, og_vfall=True, analytical_rg = True, do_virtual=True):
"""
Top level program to run eddysed. Requires running `Atmosphere` class
before running this.
Parameters
----------
atmo : class
`Atmosphere` class
directory : str, optional
Directory string that describes where refrind files are
as_dict : bool, optional
Default = False. Option to view full output as dictionary
og_solver : bool, optional
Default=True. BETA. Contact developers before changing to False.
Option to change mmr solver (True = original eddysed, False = new direct solver)
direct_tol : float , optional
Only used if og_solver =False. Default = True.
Tolerance for direct solver
refine_TP : bool, optional
Only used if og_solver =False.
Option to refine temperature-pressure profile for direct solver
og_vfall : bool, optional
Option to use original A&M or new Khan-Richardson method for finding vfall
analytical_rg : bool, optional
Only used if og_solver =False.
Option to use analytical expression for rg, or alternatively deduce rg from calculation
Calculation option will be most useful for future
inclusions of alternative particle size distributions
do_virtual : bool
If the user adds an upper bound pressure that is too low. There are cases where a cloud wants to
form off the grid towards higher pressures. This enables that.
Returns
-------
opd, w0, g0
Extinction per layer, single scattering abledo, asymmetry parameter,
All are ndarrays that are nlayer by nwave
dict
Dictionary output that contains full output. See tutorials for explanation of all output.
"""
mmw = atmo.mmw
mh = atmo.mh
condensibles = atmo.condensibles
ngas = len(condensibles)
gas_mw = np.zeros(ngas)
gas_mmr = np.zeros(ngas)
rho_p = np.zeros(ngas)
# scale-height for fsed taken at Teff (default: temp at 1bar)
H = atmo.r_atmos * atmo.Teff / atmo.g
#### First we need to either grab or compute Mie coefficients ####
for i, igas in zip(range(ngas),condensibles) :
#Get gas properties including gas mean molecular weight,
#gas mixing ratio, and the density
run_gas = getattr(gas_properties, igas)
gas_mw[i], gas_mmr[i], rho_p[i] = run_gas(mmw, mh=mh, gas_mmr=atmo.gas_mmr)
#Get mie files that are already saved in
#directory
#eventually we will replace this with nice database
qext_gas, qscat_gas, cos_qscat_gas, nwave, radius,wave_in = get_mie(igas,directory)
if i==0:
nradii = len(radius)
rmin = np.min(radius)
radius, rup, dr = get_r_grid(rmin, n_radii=nradii)
qext = np.zeros((nwave,nradii,ngas))
qscat = np.zeros((nwave,nradii,ngas))
cos_qscat = np.zeros((nwave,nradii,ngas))
#add to master matrix that contains the per gas Mie stuff
qext[:,:,i], qscat[:,:,i], cos_qscat[:,:,i] = qext_gas, qscat_gas, cos_qscat_gas
#Next, calculate size and concentration
#of condensates in balance between eddy diffusion and sedimentation
#qc = condensate mixing ratio, qt = condensate+gas mr, rg = mean radius,
#reff = droplet eff radius, ndz = column dens of condensate,
#qc_path = vertical path of condensate
# run original eddysed code
if og_solver:
#here atmo.param describes the parameterization used for the variable fsed methodology
if atmo.param == 'exp':
#the formalism of this is detailed in Rooney et al. 2021
atmo.b = 6 * atmo.b * H # using constant scale-height in fsed
fsed_in = (atmo.fsed-atmo.eps)
elif atmo.param == 'const':
fsed_in = atmo.fsed
qc, qt, rg, reff, ndz, qc_path, mixl, z_cld = eddysed(atmo.t_level, atmo.p_level, atmo.t_layer, atmo.p_layer,
condensibles, gas_mw, gas_mmr, rho_p , mmw,
atmo.g, atmo.kz, atmo.mixl,
fsed_in,
atmo.b, atmo.eps, atmo.scale_h, atmo.z_top, atmo.z_alpha, min(atmo.z), atmo.param,
mh, atmo.sig, rmin, nradii,
atmo.d_molecule,atmo.eps_k,atmo.c_p_factor,
og_vfall, supsat=atmo.supsat,verbose=atmo.verbose,do_virtual=do_virtual)
pres_out = atmo.p_layer
temp_out = atmo.t_layer
z_out = atmo.z
# run new, direct solver
else:
fsed_in = atmo.fsed
z_cld = None #temporary fix
qc, qt, rg, reff, ndz, qc_path, pres_out, temp_out, z_out,mixl = direct_solver(atmo.t_layer, atmo.p_layer,
condensibles, gas_mw, gas_mmr, rho_p , mmw,
atmo.g, atmo.kz, atmo.fsed, mh,atmo.sig, rmin, nradii,
atmo.d_molecule,atmo.eps_k,atmo.c_p_factor,
direct_tol, refine_TP, og_vfall, analytical_rg)
#Finally, calculate spectrally-resolved profiles of optical depth, single-scattering
#albedo, and asymmetry parameter.
opd, w0, g0, opd_gas = calc_optics(nwave, qc, qt, rg, reff, ndz,radius,
dr,qext, qscat,cos_qscat,atmo.sig, rmin, nradii,verbose=atmo.verbose)
if as_dict:
if atmo.param == 'exp':
fsed_out = fsed_in * np.exp((atmo.z - atmo.z_alpha) / atmo.b ) + atmo.eps
else:
fsed_out = fsed_in
return create_dict(qc, qt, rg, reff, ndz,opd, w0, g0,
opd_gas,wave_in, pres_out, temp_out, condensibles,
mh,mmw, fsed_out, atmo.sig, nradii,rmin, z_out, atmo.dz_layer,
mixl, atmo.kz, atmo.scale_h, z_cld)
else:
return opd, w0, g0
def create_dict(qc, qt, rg, reff, ndz,opd, w0, g0, opd_gas,wave,pressure,temperature, gas_names,
mh,mmw,fsed,sig,nrad,rmin,z, dz_layer, mixl, kz, scale_h, z_cld):
return {
"pressure":pressure/1e6,
"pressure_unit":'bar',
"temperature":temperature,
"temperature_unit":'kelvin',
"wave":wave[:,0],
"wave_unit":'micron',
"condensate_mmr":qc,
"cond_plus_gas_mmr":qt,
"mean_particle_r":rg*1e4,
"droplet_eff_r":reff*1e4,
"r_units":'micron',
"column_density":ndz,
"column_density_unit":'#/cm^2',
"opd_per_layer":opd,
"single_scattering" : w0,
"asymmetry": g0,
"opd_by_gas": opd_gas,
"condensibles":gas_names,
#"scalar_inputs": {'mh':mh, 'mmw':mmw,'fsed':fsed, 'sig':sig,'nrad':nrad,'rmin':rmin},
"scalar_inputs": {'mh':mh, 'mmw':mmw,'sig':sig,'nrad':nrad,'rmin':rmin},
"fsed": fsed,
"altitude":z,
"layer_thickness":dz_layer,
"z_unit":'cm',
'mixing_length':mixl,
'mixing_length_unit':'cm',
'kz':kz,
'kz_unit':'cm^2/s',
'scale_height':scale_h,
'cloud_deck':z_cld
}
def calc_optics(nwave, qc, qt, rg, reff, ndz,radius,dr,qext, qscat,cos_qscat,sig, rmin, nrad,verbose):
"""
Calculate spectrally-resolved profiles of optical depth, single-scattering
albedo, and asymmetry parameter.
Parameters
----------
nwave : int
Number of wave points
qc : ndarray
Condensate mixing ratio
qt : ndarray
Gas + condensate mixing ratio
rg : ndarray
Geometric mean radius of condensate
reff : ndarray
Effective (area-weighted) radius of condensate (cm)
ndz : ndarray
Column density of particle concentration in layer (#/cm^2)
radius : ndarray
Radius bin centers (cm)
dr : ndarray
Width of radius bins (cm)
qscat : ndarray
Scattering efficiency
qext : ndarray
Extinction efficiency
cos_qscat : ndarray
qscat-weighted <cos (scattering angle)>
sig : float
Width of the log normal particle distribution
verbose: bool
print out warnings or not
Returns
-------
opd : ndarray
extinction optical depth due to all condensates in layer
w0 : ndarray
single scattering albedo
g0 : ndarray
asymmetry parameter = Q_scat wtd avg of <cos theta>
opd_gas : ndarray
cumulative (from top) opd by condensing vapor as geometric conservative scatterers
"""
PI=np.pi
nz = qc.shape[0]
ngas = qc.shape[1]
nrad = len(radius)
opd_layer = np.zeros((nz, ngas))
scat_gas = np.zeros((nz,nwave,ngas))
ext_gas = np.zeros((nz,nwave,ngas))
cqs_gas = np.zeros((nz,nwave,ngas))
opd = np.zeros((nz,nwave))
opd_gas = np.zeros((nz,ngas))
w0 = np.zeros((nz,nwave))
g0 = np.zeros((nz,nwave))
warning=''
for iz in range(nz):
for igas in range(ngas):
# Optical depth for conservative geometric scatterers
if ndz[iz,igas] > 0:
if np.log10(rg[iz,igas]) < np.log10(rmin)+0.75*sig:
warning0 = f'Take caution in analyzing results. There have been a calculated particle radii off the Mie grid, which has a min radius of {rmin}cm and distribution of {sig}. The following errors:'
warning+='{0}cm for the {1}th gas at the {2}th grid point; '.format(str(rg[iz,igas]),str(igas),str(iz))
r2 = rg[iz,igas]**2 * np.exp( 2*np.log( sig)**2 )
opd_layer[iz,igas] = 2.*PI*r2*ndz[iz,igas]
# Calculate normalization factor (forces lognormal sum = 1.0)
rsig = sig
norm = 0.
for irad in range(nrad):
rr = radius[irad]
arg1 = dr[irad] / ( np.sqrt(2.*PI)*rr*np.log(rsig) )
arg2 = -np.log( rr/rg[iz,igas] )**2 / ( 2*np.log(rsig)**2 )
norm = norm + arg1*np.exp( arg2 )
#print (rr, rg[iz,igas],rsig,arg1,arg2)
# normalization
norm = ndz[iz,igas] / norm
for irad in range(nrad):
rr = radius[irad]
arg1 = dr[irad] / ( np.sqrt(2.*PI)*np.log(rsig) )
arg2 = -np.log( rr/rg[iz,igas] )**2 / ( 2*np.log(rsig)**2 )
pir2ndz = norm*PI*rr*arg1*np.exp( arg2 )
for iwave in range(nwave):
scat_gas[iz,iwave,igas] = scat_gas[iz,iwave,igas]+qscat[iwave,irad,igas]*pir2ndz
ext_gas[iz,iwave,igas] = ext_gas[iz,iwave,igas]+qext[iwave,irad,igas]*pir2ndz
cqs_gas[iz,iwave,igas] = cqs_gas[iz,iwave,igas]+cos_qscat[iwave,irad,igas]*pir2ndz
#TO DO ADD IN CLOUD SUBLAYER KLUGE LATER
#Sum over gases and compute spectral optical depth profile etc
for iz in range(nz):
for iwave in range(nwave):
opd_scat = 0.
opd_ext = 0.
cos_qs = 0.
for igas in range(ngas):
opd_scat = opd_scat + scat_gas[iz,iwave,igas]
opd_ext = opd_ext + ext_gas[iz,iwave,igas]
cos_qs = cos_qs + cqs_gas[iz,iwave,igas]
if( opd_scat > 0. ):
opd[iz,iwave] = opd_ext
w0[iz,iwave] = opd_scat / opd_ext
#if w0[iz,iwave]>1:
# w0[iz,iwave]=1.
g0[iz,iwave] = cos_qs / opd_scat
#cumulative optical depths for conservative geometric scatterers
opd_tot = 0.
for igas in range(ngas):
opd_gas[0,igas] = opd_layer[0,igas]
for iz in range(1,nz):
opd_gas[iz,igas] = opd_gas[iz-1,igas] + opd_layer[iz,igas]
if ((warning!='') & (verbose)): print(warning0+warning+' Turn off warnings by setting verbose=False.')
return opd, w0, g0, opd_gas
def eddysed(t_top, p_top,t_mid, p_mid, condensibles,
gas_mw, gas_mmr,rho_p,mw_atmos,gravity, kz,mixl,
fsed, b, eps, scale_h, z_top, z_alpha, z_min, param,
mh,sig, rmin, nrad,d_molecule,eps_k,c_p_factor,
og_vfall=True,do_virtual=True, supsat=0, verbose=True):
"""
Given an atmosphere and condensates, calculate size and concentration
of condensates in balance between eddy diffusion and sedimentation.
Parameters
----------
t_top : ndarray
Temperature at each layer (K)
p_top : ndarray
Pressure at each layer (dyn/cm^2)
t_mid : ndarray
Temperature at each midpoint (K)
p_mid : ndarray
Pressure at each midpoint (dyn/cm^2)
condensibles : ndarray or list of str
List or array of condensible gas names
gas_mw : ndarray
Array of gas mean molecular weight from `gas_properties`
gas_mmr : ndarray
Array of gas mixing ratio from `gas_properties`
rho_p : float
density of condensed vapor (g/cm^3)
mw_atmos : float
Mean molecular weight of the atmosphere
gravity : float
Gravity of planet cgs
kz : float or ndarray
Kzz in cgs, either float or ndarray depending of whether or not
it is set as input
fsed : float
Sedimentation efficiency coefficient, unitless
b : float
Denominator of exponential in sedimentation efficiency (if param is 'exp')
eps: float
Minimum value of fsed function (if param=exp)
scale_h : float
Scale height of the atmosphere
z_top : float
Altitude at each layer
z_alpha : float
Altitude at which fsed=alpha for variable fsed calculation
param : str
fsed parameterisation
'const' (constant), 'exp' (exponential density derivation)
mh : float
Atmospheric metallicity in NON log units (e.g. 1 for 1x solar)
sig : float
Width of the log normal particle distribution
d_molecule : float
diameter of atmospheric molecule (cm) (Rosner, 2000)
(3.711e-8 for air, 3.798e-8 for N2, 2.827e-8 for H2)
Set in Atmosphere constants
eps_k : float
Depth of the Lennard-Jones potential well for the atmosphere
Used in the viscocity calculation (units are K) (Rosner, 2000)
c_p_factor : float
specific heat of atmosphere (erg/K/g) . Usually 7/2 for ideal gas
diatomic molecules (e.g. H2, N2). Technically does slowly rise with
increasing temperature
og_vfall : bool , optional
optional, default = True. True does the original fall velocity calculation.
False does the updated one which runs a tad slower but is more consistent.
The main effect of turning on False is particle sizes in the upper atmosphere
that are slightly bigger.
do_virtual : bool,optional
optional, Default = True which adds a virtual layer if the
species condenses below the model domain.
supsat : float, optional
Default = 0 , Saturation factor (after condensation)
Returns
-------
qc : ndarray
condenstate mixing ratio (g/g)
qt : ndarray
gas + condensate mixing ratio (g/g)
rg : ndarray
geometric mean radius of condensate cm
reff : ndarray
droplet effective radius (second moment of size distrib, cm)
ndz : ndarray
number column density of condensate (cm^-3)
qc_path : ndarray
vertical path of condensate
"""
#default for everything is false, will fill in as True as we go
did_gas_condense = [False for i in condensibles]
t_bot = t_top[-1]
p_bot = p_top[-1]
z_bot = z_top[-1]
ngas = len(condensibles)
nz = len(t_mid)
qc = np.zeros((nz,ngas))
qt = np.zeros((nz, ngas))
rg = np.zeros((nz, ngas))
reff = np.zeros((nz, ngas))
ndz = np.zeros((nz, ngas))
fsed_layer = np.zeros((nz,ngas))
qc_path = np.zeros(ngas)
z_cld_out = np.zeros(ngas)
for i, igas in zip(range(ngas), condensibles):
q_below = gas_mmr[i]
#include decrease in condensate mixing ratio below model domain
if do_virtual:
z_cld=None
qvs_factor = (supsat+1)*gas_mw[i]/mw_atmos
get_pvap = getattr(pvaps, igas)
if igas == 'Mg2SiO4':
pvap = get_pvap(t_bot, p_bot, mh=mh)
else:
pvap = get_pvap(t_bot, mh=mh)
qvs = qvs_factor*pvap/p_bot
if qvs <= q_below :
#find the pressure at cloud base
# parameters for finding root
p_lo = p_bot
p_hi = p_bot * 1e3
#temperature gradient
dtdlnp = ( t_top[-2] - t_bot ) / np.log( p_bot/p_top[-2] )
# load parameters into qvs_below common block
qv_dtdlnp = dtdlnp
qv_p = p_bot
qv_t = t_bot
qv_gas_name = igas
qv_factor = qvs_factor
try:
p_base = optimize.root_scalar(qvs_below_model,
bracket=[p_lo, p_hi], method='brentq',
args=(qv_dtdlnp,qv_p, qv_t,qv_factor ,qv_gas_name,mh,q_below)
)#, xtol = 1e-20)
if verbose: print('Virtual Cloud Found: '+ qv_gas_name)
root_was_found = True
except ValueError:
root_was_found = False
if root_was_found:
#Yes, the gas did condense (below the grid)
did_gas_condense[i] = True
p_base = p_base.root
t_base = t_bot + np.log( p_bot/p_base )*dtdlnp
z_base = z_bot + scale_h[-1] * np.log( p_bot/p_base )
# Calculate temperature and pressure below bottom layer
# by adding a virtual layer
p_layer_virtual = 0.5*( p_bot + p_base )
t_layer_virtual = t_bot + np.log10( p_bot/p_layer_virtual )*dtdlnp
#we just need to overwrite
#q_below from this output for the next routine
qc_v, qt_v, rg_v, reff_v,ndz_v,q_below, z_cld, fsed_layer_v = layer( igas, rho_p[i],
#t,p layers, then t.p levels below and above
t_layer_virtual, p_layer_virtual, t_bot,t_base, p_bot, p_base,
kz[-1], mixl[-1], gravity, mw_atmos, gas_mw[i], q_below,
supsat, fsed, b, eps, z_bot, z_base, z_alpha, z_min, param,
sig,mh, rmin, nrad, d_molecule,eps_k,c_p_factor, #all scalaers
og_vfall, z_cld
)
z_cld=None
for iz in range(nz-1,-1,-1): #goes from BOA to TOA
qc[iz,i], qt[iz,i], rg[iz,i], reff[iz,i],ndz[iz,i],q_below, z_cld, fsed_layer[iz,i] = layer( igas, rho_p[i],
#t,p layers, then t.p levels below and above
t_mid[iz], p_mid[iz], t_top[iz], t_top[iz+1], p_top[iz], p_top[iz+1],
kz[iz], mixl[iz], gravity, mw_atmos, gas_mw[i], q_below,
supsat, fsed, b, eps, z_top[iz], z_top[iz+1], z_alpha, z_min, param,
sig,mh, rmin, nrad, d_molecule,eps_k,c_p_factor, #all scalars
og_vfall, z_cld
)
qc_path[i] = (qc_path[i] + qc[iz,i]*
( p_top[iz+1] - p_top[iz] ) / gravity)
z_cld_out[i] = z_cld
return qc, qt, rg, reff, ndz, qc_path,mixl, z_cld_out
def layer(gas_name,rho_p, t_layer, p_layer, t_top, t_bot, p_top, p_bot,
kz, mixl, gravity, mw_atmos, gas_mw, q_below,
supsat, fsed, b, eps, z_top, z_bot, z_alpha, z_min, param,
sig,mh, rmin, nrad, d_molecule,eps_k,c_p_factor,
og_vfall, z_cld):
"""
Calculate layer condensate properties by iterating on optical depth
in one model layer (convering on optical depth over sublayers)
gas_name : str
Name of condenstante
rho_p : float
density of condensed vapor (g/cm^3)
t_layer : float
Temperature of layer mid-pt (K)
p_layer : float
Pressure of layer mid-pt (dyne/cm^2)
t_top : float
Temperature at top of layer (K)
t_bot : float
Temperature at botton of layer (K)
p_top : float
Pressure at top of layer (dyne/cm2)
p_bot : float
Pressure at botton of layer
kz : float
eddy diffusion coefficient (cm^2/s)
mixl : float
Mixing length (cm)
gravity : float
Gravity of planet cgs
mw_atmos : float
Molecular weight of the atmosphere
gas_mw : float
Gas molecular weight
q_below : float
total mixing ratio (vapor+condensate) below layer (g/g)
supsat : float
Super saturation factor
fsed : float
Sedimentation efficiency coefficient (unitless)
b : float
Denominator of exponential in sedimentation efficiency (if param is 'exp')
eps: float
Minimum value of fsed function (if param=exp)
z_top : float
Altitude at top of layer
z_bot : float
Altitude at bottom of layer
z_alpha : float
Altitude at which fsed=alpha for variable fsed calculation
param : str
fsed parameterisation
'const' (constant), 'exp' (exponential density derivation)
sig : float
Width of the log normal particle distribution
mh : float
Metallicity NON log soar (1=1xSolar)
rmin : float
Minium radius on grid (cm)
nrad : int
Number of radii on Mie grid
d_molecule : float
diameter of atmospheric molecule (cm) (Rosner, 2000)
(3.711e-8 for air, 3.798e-8 for N2, 2.827e-8 for H2)
Set in Atmosphere constants
eps_k : float
Depth of the Lennard-Jones potential well for the atmosphere
Used in the viscocity calculation (units are K) (Rosner, 2000)
c_p_factor : float
specific heat of atmosphere (erg/K/g) . Usually 7/2 for ideal gas
diatomic molecules (e.g. H2, N2). Technically does slowly rise with
increasing temperature
og_vfall : bool
Use original or new vfall calculation
Returns
-------
qc_layer : ndarray
condenstate mixing ratio (g/g)
qt_layer : ndarray
gas + condensate mixing ratio (g/g)
rg_layer : ndarray
geometric mean radius of condensate cm
reff_layer : ndarray
droplet effective radius (second moment of size distrib, cm)
ndz_layer : ndarray
number column density of condensate (cm^-3)
q_below : ndarray
total mixing ratio (vapor+condensate) below layer (g/g)
"""
# universal gas constant (erg/mol/K)
nsub_max = 128
R_GAS = 8.3143e7
AVOGADRO = 6.02e23
K_BOLTZ = R_GAS / AVOGADRO
PI = np.pi
# Number of levels of grid refinement used
nsub = 1
# specific gas constant for atmosphere (erg/K/g)
r_atmos = R_GAS / mw_atmos
#specific gas constant for cloud (erg/K/g)
r_cloud = R_GAS/ gas_mw
# specific heat of atmosphere (erg/K/g)
c_p = c_p_factor * r_atmos
# pressure thickness of layer
dp_layer = p_bot - p_top
dlnp = np.log( p_bot/p_top )
# temperature gradient
dtdlnp = ( t_top - t_bot ) / dlnp
lapse_ratio = ( t_bot - t_top ) / dlnp / ( t_layer / c_p_factor )
# atmospheric density (g/cm^3)
rho_atmos = p_layer / ( r_atmos * t_layer )
# atmospheric scale height (cm)
scale_h = r_atmos * t_layer / gravity
# convective velocity scale (cm/s) from mixing length theory
w_convect = kz / mixl
# atmospheric number density (molecules/cm^3)
n_atmos = p_layer / ( K_BOLTZ*t_layer )
# atmospheric mean free path (cm)
mfp = 1. / ( np.sqrt(2.)*n_atmos*PI*d_molecule**2 )
# atmospheric viscosity (dyne s/cm^2)
# EQN B2 in A & M 2001, originally from Rosner+2000
# Rosner, D. E. 2000, Transport Processes in Chemically Reacting Flow Systems (Dover: Mineola)
visc = (5./16.*np.sqrt( PI*K_BOLTZ*t_layer*(mw_atmos/AVOGADRO)) /
( PI*d_molecule**2 ) /
( 1.22 * ( t_layer / eps_k )**(-0.16) ))
# --------------------------------------------------------------------
# Top of convergence loop
converge = False
while not converge:
# Zero cumulative values
qc_layer = 0.
qt_layer = 0.
ndz_layer = 0.
opd_layer = 0.
# total mixing ratio and pressure at bottom of sub-layer
qt_bot_sub = q_below
p_bot_sub = p_bot
z_bot_sub = z_bot
#SUBALYER
dp_sub = dp_layer / nsub
for isub in range(nsub):
qt_below = qt_bot_sub
p_top_sub = p_bot_sub - dp_sub
dz_sub = scale_h * np.log( p_bot_sub/p_top_sub ) # width of layer
p_sub = 0.5*( p_bot_sub + p_top_sub )
#################### CHECK #####################
z_top_sub = z_bot_sub + dz_sub
z_sub = z_bot_sub + scale_h * np.log( p_bot_sub/p_sub ) # midpoint of layer
################################################
t_sub = t_bot + np.log( p_bot/p_sub )*dtdlnp
qt_top, qc_sub, qt_sub, rg_sub, reff_sub,ndz_sub, z_cld, fsed_layer = calc_qc(
gas_name, supsat, t_sub, p_sub,r_atmos, r_cloud,
qt_below, mixl, dz_sub, gravity,mw_atmos,mfp,visc,
rho_p,w_convect, fsed, b, eps, param, z_bot_sub, z_sub, z_alpha, z_min,
sig,mh, rmin, nrad, og_vfall,z_cld)
# vertical sums
qc_layer = qc_layer + qc_sub*dp_sub/gravity
qt_layer = qt_layer + qt_sub*dp_sub/gravity
ndz_layer = ndz_layer + ndz_sub
if reff_sub > 0.:
opd_layer = (opd_layer +
1.5*qc_sub*dp_sub/gravity/(rho_p*reff_sub))
# Increment values at bottom of sub-layer
qt_bot_sub = qt_top
p_bot_sub = p_top_sub
z_bot_sub = z_top_sub
# Check convergence on optical depth
if nsub_max == 1 :
converge = True
elif nsub == 1 :
opd_test = opd_layer
elif (opd_layer == 0.) or (nsub >= nsub_max):
converge = True
elif ( abs( 1. - opd_test/opd_layer ) <= 1e-2 ) :
converge = True
else:
opd_test = opd_layer
nsub = nsub * 2
# Update properties at bottom of next layer
q_below = qt_top
#Get layer averages
if opd_layer > 0. :
reff_layer = 1.5*qc_layer / (rho_p*opd_layer)
lnsig2 = 0.5*np.log( sig )**2
rg_layer = reff_layer*np.exp( -5*lnsig2 )
else :
reff_layer = 0.
rg_layer = 0.
qc_layer = qc_layer*gravity / dp_layer
qt_layer = qt_layer*gravity / dp_layer
return qc_layer, qt_layer, rg_layer, reff_layer, ndz_layer,q_below, z_cld, fsed_layer
def calc_qc(gas_name, supsat, t_layer, p_layer
,r_atmos, r_cloud, q_below, mixl, dz_layer, gravity,mw_atmos
,mfp,visc,rho_p,w_convect, fsed, b, eps, param, z_bot, z_layer, z_alpha, z_min,
sig, mh, rmin, nrad, og_vfall=True, z_cld=None):
"""
Calculate condensate optical depth and effective radius for a layer,
assuming geometric scatterers.
gas_name : str
Name of condensate
supsat : float
Super saturation factor
t_layer : float
Temperature of layer mid-pt (K)
p_layer : float
Pressure of layer mid-pt (dyne/cm^2)
r_atmos : float
specific gas constant for atmosphere (erg/K/g)
r_cloud : float
specific gas constant for cloud species (erg/K/g)
q_below : float
total mixing ratio (vapor+condensate) below layer (g/g)
mxl : float
convective mixing length scale (cm): no less than 1/10 scale height
dz_layer : float
Thickness of layer cm
gravity : float
Gravity of planet cgs
mw_atmos : float
Molecular weight of the atmosphere
mfp : float
atmospheric mean free path (cm)
visc : float
atmospheric viscosity (dyne s/cm^2)
rho_p : float
density of condensed vapor (g/cm^3)
w_convect : float
convective velocity scale (cm/s)
fsed : float
Sedimentation efficiency coefficient (unitless)
b : float
Denominator of exponential in sedimentation efficiency (if param is 'exp')
eps: float
Minimum value of fsed function (if param=exp)
z_bot : float
Altitude at bottom of layer
z_layer : float
Altitude of midpoint of layer (cm)
z_alpha : float
Altitude at which fsed=alpha for variable fsed calculation
param : str
fsed parameterisation
'const' (constant), 'exp' (exponential density derivation)
sig : float
Width of the log normal particle distrubtion
mh : float
Metallicity NON log solar (1 = 1x solar)
rmin : float
Minium radius on grid (cm)
nrad : int
Number of radii on Mie grid
Returns
-------
qt_top : float
gas + condensate mixing ratio at top of layer(g/g)
qc_layer : float
condenstate mixing ratio (g/g)
qt_layer : float
gas + condensate mixing ratio (g/g)
rg_layer : float
geometric mean radius of condensate cm
reff_layer : float
droplet effective radius (second moment of size distrib, cm)
ndz_layer : float
number column density of condensate (cm^-3)
"""
get_pvap = getattr(pvaps, gas_name)
if gas_name == 'Mg2SiO4':
pvap = get_pvap(t_layer, p_layer,mh=mh)
else:
pvap = get_pvap(t_layer,mh=mh)
fs = supsat + 1
# atmospheric density (g/cm^3)
rho_atmos = p_layer / ( r_atmos * t_layer )
# mass mixing ratio of saturated vapor (g/g)
qvs = fs*pvap / ( (r_cloud) * t_layer ) / rho_atmos
# --------------------------------------------------------------------
# Layer is cloud free
if( q_below < qvs ):
qt_layer = q_below
qt_top = q_below
qc_layer = 0.
rg_layer = 0.
reff_layer = 0.
ndz_layer = 0.
z_cld = z_cld
fsed_mid = 0
else:
# --------------------------------------------------------------------
# Cloudy layer: first calculate qt and qc at top of layer,
# then calculate layer averages
if isinstance(z_cld,type(None)):
z_cld = z_bot
else:
z_cld = z_cld
# range of mixing ratios to search (g/g)
qhi = q_below
qlo = qhi / 1e3
# load parameters into advdiff common block
ad_qbelow = q_below
ad_qvs = qvs
ad_mixl = mixl
ad_dz = dz_layer
ad_rainf = fsed
# Find total vapor mixing ratio at top of layer
#find_root = True
#while find_root:
# try:
# qt_top = optimize.root_scalar(advdiff, bracket=[qlo, qhi], method='brentq',
# args=(ad_qbelow,ad_qvs, ad_mixl,ad_dz ,ad_rainf,
# z_bot, b, eps, param)
# )#, xtol = 1e-20)
# find_root = False
# except ValueError:
# qlo = qlo/10
#
#qt_top = qt_top.root
if param == "const":
qt_top = qvs + (q_below - qvs) * np.exp(-fsed * dz_layer / mixl)
elif param == "exp":
fs = fsed / np.exp(z_alpha / b)
qt_top = qvs + (q_below - qvs) * np.exp( - b * fs / mixl * np.exp(z_bot/b)
* (np.exp(dz_layer/b) -1) + eps*dz_layer/mixl)
# Use trapezoid rule (for now) to calculate layer averages
# -- should integrate exponential
qt_layer = 0.5*( q_below + qt_top )
# Find total condensate mixing ratio
qc_layer = np.max( [0., qt_layer - qvs] )
# --------------------------------------------------------------------
# Find <rw> corresponding to <w_convect> using function vfall()
# range of particle radii to search (cm)
rlo = 1.e-10
rhi = 10.
# precision of vfall solution (cm/s)
find_root = True
while find_root:
try:
if og_vfall:
rw_temp = optimize.root_scalar(vfall_find_root, bracket=[rlo, rhi], method='brentq',
args=(gravity,mw_atmos,mfp,visc,t_layer,p_layer, rho_p,w_convect))
else:
rw_temp = solve_force_balance("rw", w_convect, gravity, mw_atmos, mfp,
visc, t_layer, p_layer, rho_p, rlo, rhi)
find_root = False
except ValueError:
rlo = rlo/10
rhi = rhi*10
#fall velocity particle radius
if og_vfall: rw_layer = rw_temp.root
else: rw_layer = rw_temp
# geometric std dev of lognormal size distribution
lnsig2 = 0.5*np.log( sig )**2
# sigma floor for the purpose of alpha calculation
sig_alpha = np.max( [1.1, sig] )
# find alpha for power law fit vf = w(r/rw)^alpha
def pow_law(r, alpha):
return np.log(w_convect) + alpha * np.log (r / rw_layer)
r_, rup, dr = get_r_grid(r_min = rmin, n_radii = nrad)
vfall_temp = []
for j in range(len(r_)):
if og_vfall:
vfall_temp.append(vfall(r_[j], gravity, mw_atmos, mfp, visc, t_layer, p_layer, rho_p))
else:
vlo = 1e0; vhi = 1e6
find_root = True
while find_root:
try:
vfall_temp.append(solve_force_balance("vfall", r_[j], gravity, mw_atmos,
mfp, visc, t_layer, p_layer, rho_p, vlo, vhi))
find_root = False
except ValueError:
vlo = vlo/10
vhi = vhi*10
pars, cov = optimize.curve_fit(f=pow_law, xdata=r_, ydata=np.log(vfall_temp), p0=[0],
bounds=(-np.inf, np.inf))
alpha = pars[0]
# fsed at middle of layer
if param == 'exp':
fsed_mid = fs * np.exp(z_layer / b) + eps
else: # 'const'
fsed_mid = fsed
# EQN. 13 A&M
# geometric mean radius of lognormal size distribution
rg_layer = (fsed_mid**(1./alpha) *
rw_layer * np.exp( -(alpha+6)*lnsig2 ))
# droplet effective radius (cm)
reff_layer = rg_layer*np.exp( 5*lnsig2 )
# EQN. 14 A&M
# column droplet number concentration (cm^-2)
ndz_layer = (3*rho_atmos*qc_layer*dz_layer /
( 4*np.pi*rho_p*rg_layer**3 ) * np.exp( -9*lnsig2 ))
return qt_top, qc_layer,qt_layer, rg_layer,reff_layer,ndz_layer, z_cld, fsed_mid
class Atmosphere():
def __init__(self,condensibles, fsed=0.5, b=1, eps=1e-2, mh=1, mmw=2.2, sig=2.0,
param='const', verbose=True, supsat=0, gas_mmr=None):
"""
Parameters
----------
condensibles : list of str
list of gases for which to consider as cloud species
fsed : float
Sedimentation efficiency coefficient. Jupiter ~3-6. Hot Jupiters ~ 0.1-1.
b : float
Denominator of exponential in sedimentation efficiency (if param is 'exp')
eps: float
Minimum value of fsed function (if param=exp)
mh : float
metalicity
mmw : float
MMW of the atmosphere
sig : float
Width of the log normal distribution for the particle sizes
param : str
fsed parameterisation
'const' (constant), 'exp' (exponential density derivation)
verbose : bool
Prints out warning statements throughout
"""
self.mh = mh
self.mmw = mmw
self.condensibles = condensibles