cleopy 0.57.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. cleopy/__init__.py +22 -0
  2. cleopy/cxx2py.py +136 -0
  3. cleopy/editconfigfile.py +61 -0
  4. cleopy/gbxboundariesbinary_src/__init__.py +16 -0
  5. cleopy/gbxboundariesbinary_src/create_gbxboundaries.py +197 -0
  6. cleopy/gbxboundariesbinary_src/read_gbxboundaries.py +350 -0
  7. cleopy/geninitconds.py +144 -0
  8. cleopy/initsuperdropsbinary_src/__init__.py +15 -0
  9. cleopy/initsuperdropsbinary_src/attrsgen.py +206 -0
  10. cleopy/initsuperdropsbinary_src/crdgens.py +101 -0
  11. cleopy/initsuperdropsbinary_src/create_initsuperdrops.py +360 -0
  12. cleopy/initsuperdropsbinary_src/dryrgens.py +31 -0
  13. cleopy/initsuperdropsbinary_src/probdists.py +239 -0
  14. cleopy/initsuperdropsbinary_src/read_initsuperdrops.py +465 -0
  15. cleopy/initsuperdropsbinary_src/rgens.py +81 -0
  16. cleopy/readbinary.py +120 -0
  17. cleopy/readconfigfile.py +61 -0
  18. cleopy/sdmout_src/__init__.py +16 -0
  19. cleopy/sdmout_src/massmoms.py +83 -0
  20. cleopy/sdmout_src/pygbxsdat.py +59 -0
  21. cleopy/sdmout_src/pysetuptxt.py +90 -0
  22. cleopy/sdmout_src/pyzarr.py +158 -0
  23. cleopy/sdmout_src/sdtracing.py +141 -0
  24. cleopy/sdmout_src/superdrops.py +428 -0
  25. cleopy/sdmout_src/supersdata.py +228 -0
  26. cleopy/sdmout_src/thermodata.py +146 -0
  27. cleopy/sdmout_src/thermoeqns.py +129 -0
  28. cleopy/sdmout_src/timedata.py +54 -0
  29. cleopy/thermobinary_src/__init__.py +16 -0
  30. cleopy/thermobinary_src/create_thermodynamics.py +256 -0
  31. cleopy/thermobinary_src/read_thermodynamics.py +498 -0
  32. cleopy/thermobinary_src/thermodyngen.py +56 -0
  33. cleopy/thermobinary_src/thermogen.py +466 -0
  34. cleopy/thermobinary_src/windsgen.py +228 -0
  35. cleopy/writebinary.py +218 -0
  36. cleopy-0.57.4.dist-info/METADATA +47 -0
  37. cleopy-0.57.4.dist-info/RECORD +39 -0
  38. cleopy-0.57.4.dist-info/WHEEL +4 -0
  39. cleopy-0.57.4.dist-info/licenses/LICENSE.md +43 -0
@@ -0,0 +1,239 @@
1
+ """
2
+ ----- CLEO -----
3
+ File: probdists.py
4
+ Project: initsuperdropsbinary_src
5
+ Created Date: Wednesday 22nd November 2023
6
+ Author: Clara Bayley (CB)
7
+ Additional Contributors:
8
+ -----
9
+ License: BSD 3-Clause "New" or "Revised" License
10
+ https://opensource.org/licenses/BSD-3-Clause
11
+ -----
12
+ Copyright (c) 2023 MPI-M, Clara Bayley
13
+ -----
14
+ File Description:
15
+ Class calls' return normalised probability
16
+ of radii for various probability distributions
17
+ assuming bins are evenly spaced in log10(r)
18
+ """
19
+
20
+ import numpy as np
21
+ from scipy import special
22
+
23
+
24
+ class MinXiDistrib:
25
+ """probability of radius for a given probability distribution but with a
26
+ minimum value such that xi>='xi_min'"""
27
+
28
+ def __init__(self, probdistrib, xi_min):
29
+ self.probdistrib = probdistrib
30
+ self.xi_min = xi_min
31
+
32
+ def __call__(self, radii, totxi):
33
+ """returns probability for radii from a certain distribution or the
34
+ probability such that xi has minimum value 'xi_min'"""
35
+ prob = self.probdistrib(radii, totxi)
36
+ prob_min = self.xi_min / totxi
37
+ return np.where(prob < prob_min, prob_min, prob)
38
+
39
+
40
+ class CombinedRadiiProbDistribs:
41
+ """probability of radius from the sum of several
42
+ probability distributions"""
43
+
44
+ def __init__(self, probdistribs, scalefacs):
45
+ self.probdistribs = probdistribs
46
+ self.scalefacs = scalefacs
47
+
48
+ if len(scalefacs) != len(probdistribs):
49
+ errmsg = "relative height of each probability distribution must be given"
50
+ raise ValueError(errmsg)
51
+
52
+ def __call__(self, radii, totxi):
53
+ return self._probdistrib(radii, totxi)
54
+
55
+ def _probdistrib(self, radii, totxi):
56
+ """returns distribution for radii given by the
57
+ sum of the distributions in probdistribs list"""
58
+
59
+ probs = np.zeros(radii.shape)
60
+ for distrib, sf in zip(self.probdistribs, self.scalefacs):
61
+ probs += sf * distrib(radii, totxi)
62
+
63
+ return probs / np.sum(probs) # normalise so sum(prob) = 1
64
+
65
+
66
+ class DiracDelta:
67
+ """probability of radius nonzero if it is
68
+ closest value in sample of radii to r0"""
69
+
70
+ def __init__(self, r0):
71
+ self.r0 = r0
72
+
73
+ def __call__(self, radii, totxi):
74
+ return self._probdistrib(radii)
75
+
76
+ def _probdistrib(self, radii):
77
+ """Returns probability of radius in radii sample for
78
+ discrete version of dirac delta function centred on
79
+ value of r in radii closest to r0. For each radius in radii,
80
+ probability of that radius = 0 if it's not the closest value
81
+ in radii to r0. If it is the closest, the probability is maximal
82
+ (ie. prob = 1 and is then re-normalised such that sum of the
83
+ probalilities over the sample = 1)"""
84
+
85
+ if radii.any():
86
+ diff = np.abs(radii - self.r0)
87
+
88
+ probs = np.where(diff == np.min(diff), 1, 0)
89
+
90
+ return probs / np.sum(probs) # normalise so sum(prob) = 1
91
+ else:
92
+ return np.array([])
93
+
94
+
95
+ class VolExponential:
96
+ """probability of radius given by exponential in
97
+ volume distribution as defined by Shima et al. (2009)"""
98
+
99
+ def __init__(self, radius0, rspan):
100
+ self.radius0 = radius0 # peak of volume exponential distribution [m]
101
+ self.rspan = rspan
102
+
103
+ def __call__(self, radii, totxi):
104
+ return self._probdistrib(radii)
105
+
106
+ def _probdistrib(self, radii):
107
+ """Returns probability of eaach radius in radii according to
108
+ distribution where probability of volume is exponential and bins
109
+ for radii are evently spaced in ln(r).
110
+ typical parameter values:
111
+ radius0 = 30.531e-6 # [m]
112
+ numconc = 2**(23) # [m^-3]"""
113
+
114
+ rwdth = np.log(
115
+ self.rspan[-1] / self.rspan[0]
116
+ ) # assume equally spaced bins in ln(r)
117
+
118
+ dn_dV = np.exp(-((radii / self.radius0) ** 3)) # prob density P(volume)
119
+
120
+ probs = rwdth * radii**3 * dn_dV # prob density * ln(r) bin width
121
+
122
+ return probs / np.sum(probs) # normalise so sum(prob) = 1
123
+
124
+
125
+ class LnNormal:
126
+ """probability of radius given by lognormal distribution
127
+ as defined by section 5.2.3 of "An Introduction to clouds from
128
+ the Microscale to Climate" by Lohmann, Luond and Mahrt and radii
129
+ sampled from evenly spaced bins in ln(r).
130
+ typical parameter values:
131
+ geomeans = [0.02e-6, 0.2e-6, 3.5e-6] # [m]
132
+ geosigs = [1.55, 2.3, 2]
133
+ scalefacs = [1e6, 0.3e6, 0.025e6]
134
+ numconc = 1e9 # [m^-3]"""
135
+
136
+ def __init__(self, geomeans, geosigs, scalefacs):
137
+ nmodes = len(geomeans)
138
+ if nmodes != len(geosigs) or nmodes != len(scalefacs):
139
+ errmsg = "parameters for number of lognormal modes is not consistent"
140
+ raise ValueError(errmsg)
141
+ else:
142
+ self.nmodes = nmodes
143
+ self.geomeans = geomeans
144
+ self.geosigs = geosigs
145
+ self.scalefacs = scalefacs
146
+
147
+ def __call__(self, radii, totxi):
148
+ return self._probdistrib(radii)
149
+
150
+ def _probdistrib(self, radii):
151
+ """Returns probability of each radius in radii derived
152
+ from superposition of Logarithmic (in e) Normal Distributions"""
153
+
154
+ probs = np.zeros(radii.shape)
155
+ for n in range(self.nmodes):
156
+ probs += self.lnnormaldist(
157
+ radii, self.scalefacs[n], self.geomeans[n], self.geosigs[n]
158
+ )
159
+
160
+ return probs / np.sum(probs) # normalise so sum(prob) = 1
161
+
162
+ def lnnormaldist(self, radii, scalefac, geomean, geosig):
163
+ """calculate probability of radii given the paramters of a
164
+ lognormal dsitribution accordin to equation 5.8 of "An
165
+ Introduction to clouds from the Microscale to Climate"
166
+ by Lohmann, Luond and Mahrt"""
167
+
168
+ sigtilda = np.log(geosig)
169
+ mutilda = np.log(geomean)
170
+
171
+ norm = scalefac / (np.sqrt(2 * np.pi) * sigtilda)
172
+ exponent = -((np.log(radii) - mutilda) ** 2) / (2 * sigtilda**2)
173
+
174
+ dn_dlnr = norm * np.exp(exponent) # eq.5.8 [lohmann intro 2 clouds]
175
+
176
+ return dn_dlnr
177
+
178
+
179
+ class ClouddropsHansenGamma:
180
+ """probability of radius according to gamma distribution for
181
+ shallow cumuli cloud droplets from Poertge et al. 2023"""
182
+
183
+ def __init__(self, reff, nueff):
184
+ self.reff = reff
185
+ self.nueff = nueff
186
+
187
+ def __call__(self, radii, totxi):
188
+ return self._probdistrib(radii)
189
+
190
+ def _probdistrib(self, radii):
191
+ """return gamma distribution for cloud droplets
192
+ given radius [m] using parameters from Poertge
193
+ et al. 2023 for shallow cumuli (figure 12).
194
+ typical values:
195
+ reff = 7e-6 #[m]
196
+ nueff = 0.08 # []"""
197
+
198
+ xp = (1 - 2 * self.nueff) / self.nueff
199
+ n0const = (self.reff * self.nueff) ** (-xp)
200
+ n0const = n0const / special.gamma(xp)
201
+
202
+ term1 = radii ** ((1 - 3 * self.nueff) / self.nueff)
203
+ term2 = np.exp(-radii / (self.reff * self.nueff))
204
+
205
+ probs = n0const * term1 * term2 # dn_dr [prob m^-1]
206
+
207
+ return probs / np.sum(probs) # normalise so sum(prob) = 1
208
+
209
+
210
+ class RaindropsGeoffroyGamma:
211
+ """probability of radius given gamma distribution for
212
+ shallow cumuli rain droplets from Geoffroy et al. 2014"""
213
+
214
+ def __init__(self, nrain, qrain, dvol):
215
+ self.nrain = nrain # raindrop concentration [ndrops/m^3]
216
+ self.qrain = qrain # rainwater content [g/m^3]
217
+ self.dvol = dvol # volume mean raindrop diameter [m]
218
+
219
+ def __call__(self, radii, totxi):
220
+ return self._probdistrib(radii)
221
+
222
+ def _probdistrib(self, radii):
223
+ """returns probability of each radius according to a
224
+ gamma distribution for rain droplets using parameters
225
+ from Geoffroy et al. 2014 for precipitating shallow
226
+ cumuli RICO (see figure 3 and equations 2,3 and 5).
227
+ typical parameter values:
228
+ nrain = 3 / 0.001 # [ndrops/m^3]
229
+ qrain = 0.9 # [g/m^3]
230
+ dvol = 800e-6 #[m]"""
231
+
232
+ nu = 18 / ((self.nrain * self.qrain) ** 0.25) # []
233
+ lamda = (nu * (nu + 1) * (nu + 2)) ** (1 / 3) / self.dvol # [m^-1]
234
+ const = self.nrain * lamda**nu / special.gamma(nu)
235
+
236
+ diam = 2 * radii # [m]
237
+ probs = const * diam ** (nu - 1) * np.exp(-lamda * diam) # dn_dr [prob m^-1]
238
+
239
+ return probs / np.sum(probs) # normalise so sum(prob) = 1
@@ -0,0 +1,465 @@
1
+ """
2
+ Copyright (c) 2024 MPI-M, Clara Bayley
3
+
4
+
5
+ ----- CLEO -----
6
+ File: read_initsuperdrops.py
7
+ Project: initsuperdropsbinary_src
8
+ Created Date: Friday 13th October 2023
9
+ Author: Clara Bayley (CB)
10
+ Additional Contributors:
11
+ -----
12
+ License: BSD 3-Clause "New" or "Revised" License
13
+ https://opensource.org/licenses/BSD-3-Clause
14
+ -----
15
+ File Description:
16
+ """
17
+
18
+ import numpy as np
19
+ import matplotlib.pyplot as plt
20
+
21
+ from .create_initsuperdrops import initsupers_inputsdict, ManyAttrs
22
+ from ..readbinary import readbinary
23
+ from ..gbxboundariesbinary_src.read_gbxboundaries import get_gbxvols_from_gridfile
24
+
25
+
26
+ def plot_initGBxs_distribs(
27
+ config_filename,
28
+ constants_filename,
29
+ initsupers_filename,
30
+ grid_filename,
31
+ gbxs2plt,
32
+ savefig=False,
33
+ savefigpath=None,
34
+ savelabel="",
35
+ ):
36
+ """plot initial superdroplet distribution from initsupersfile binary
37
+ of every gridbox with index in gbx2plts"""
38
+
39
+ plot_initGBxs_attrdistribs(
40
+ config_filename,
41
+ constants_filename,
42
+ initsupers_filename,
43
+ grid_filename,
44
+ gbxs2plt,
45
+ savefigpath,
46
+ savefig,
47
+ savelabel,
48
+ )
49
+ plot_initGBxs_dropletmasses(
50
+ config_filename,
51
+ constants_filename,
52
+ initsupers_filename,
53
+ grid_filename,
54
+ gbxs2plt,
55
+ savefigpath,
56
+ savefig,
57
+ savelabel,
58
+ )
59
+
60
+
61
+ def get_superdroplet_attributes(
62
+ config_filename, constants_filename, initsupers_filename
63
+ ):
64
+ """get gridbox boundaries from binary file and
65
+ re-dimensionalise usign COORD0 const from constants_filename"""
66
+
67
+ inputs = initsupers_inputsdict(config_filename, constants_filename)
68
+
69
+ attrs = read_dimless_superdrops_binary(initsupers_filename, isprint=False)
70
+
71
+ # re-dimensionalise SD attributes
72
+ attrs.radius = attrs.radius * inputs["R0"]
73
+ attrs.msol = attrs.msol * inputs["MASS0"]
74
+ attrs.coord3 = attrs.coord3 * inputs["COORD0"]
75
+ attrs.coord1 = attrs.coord1 * inputs["COORD0"]
76
+ attrs.coord2 = attrs.coord2 * inputs["COORD0"]
77
+
78
+ return attrs
79
+
80
+
81
+ def read_dimless_superdrops_binary(filename, isprint=True):
82
+ """return dimenionsless gbx boundaries by reading binary file"""
83
+
84
+ datatypes = [np.uintc, np.uint, np.double, np.double]
85
+ datatypes += [np.double] * 3
86
+ data, ndata_pervar = readbinary(filename, isprint=isprint)
87
+
88
+ ll = [0, 0, 0, 0, 0, 0] # indexs for division of data list between each variable
89
+ for n in range(1, len(ndata_pervar)):
90
+ ll[n - 1] = np.sum(ndata_pervar[:n])
91
+
92
+ attrs = ManyAttrs()
93
+ attrs.sdgbxindex = np.asarray(data[: ll[0]], dtype=datatypes[0])
94
+ attrs.xi = np.asarray(data[ll[0] : ll[1]], dtype=datatypes[1])
95
+ attrs.radius = np.asarray(data[ll[1] : ll[2]], dtype=datatypes[2])
96
+ attrs.msol = np.asarray(data[ll[2] : ll[3]], dtype=datatypes[3])
97
+ attrs.coord3 = np.asarray(data[ll[3] : ll[4]], dtype=datatypes[4])
98
+ attrs.coord1 = np.asarray(data[ll[4] : ll[5]], dtype=datatypes[5])
99
+ attrs.coord2 = np.asarray(data[ll[5] :], dtype=datatypes[6])
100
+
101
+ print(
102
+ "attribute shapes: ",
103
+ attrs.sdgbxindex.shape,
104
+ attrs.xi.shape,
105
+ attrs.radius.shape,
106
+ attrs.msol.shape,
107
+ attrs.coord3.shape,
108
+ attrs.coord1.shape,
109
+ attrs.coord2.shape,
110
+ )
111
+
112
+ return attrs
113
+
114
+
115
+ def totmass(radius, msol, RHO_L, RHO_SOL):
116
+ """droplet totmass = mass of water + solute"""
117
+ massconst = 4.0 / 3.0 * np.pi * radius * radius * radius * RHO_L
118
+ density_factor = 1.0 - RHO_L / RHO_SOL
119
+ totmass = msol * density_factor + massconst
120
+
121
+ return totmass
122
+
123
+
124
+ def print_initsupers_infos(
125
+ initsupers_filename, config_filename, constants_filename, grid_filename
126
+ ):
127
+ gbxvols = np.asarray(
128
+ get_gbxvols_from_gridfile(
129
+ grid_filename, constants_filename=constants_filename, isprint=False
130
+ )
131
+ )
132
+
133
+ attrs = get_superdroplet_attributes(
134
+ config_filename, constants_filename, initsupers_filename
135
+ )
136
+
137
+ xi = attrs.xi.flatten()
138
+ vol = np.sum(gbxvols)
139
+ numconc = np.sum(xi) / vol / 1e6 # [/cm^3]
140
+ massconc = np.sum(attrs.msol.flatten() * xi) / vol * 1000 # [g m^-3]
141
+ dropvol = 4 / 3 * np.pi * np.sum((attrs.radius.flatten() ** 3) * xi)
142
+ m_w_conc = (
143
+ dropvol * 1000 / vol * 1000
144
+ ) # mass as if drops had density of water=1000Kg/m^3 [g m^3]
145
+
146
+ inforstr = (
147
+ "\n------ DOMAIN SUPERDROPLETS INFO ------\n"
148
+ + "total droplet number conc: {:3g}".format(numconc)
149
+ + " /cm^3\n"
150
+ + "total droplet mass: {:3g}".format(massconc)
151
+ + " g/m^3\n"
152
+ + " as if water: {:3g}".format(m_w_conc)
153
+ + " g/m^3"
154
+ + "\n------------------------------------\n"
155
+ )
156
+ print(inforstr)
157
+
158
+
159
+ def plot_initdistribs(attrs, gbxvols, gbxidxs):
160
+ plt.rcParams.update({"font.size": 14})
161
+ fig, axs = figure_setup(attrs.coord3, attrs.coord1, attrs.coord2)
162
+
163
+ # create nbins evenly spaced in log10(r)
164
+ nbins = 20
165
+ minr, maxr = np.min(attrs.radius) / 10, np.max(attrs.radius) * 10
166
+ hedgs = np.linspace(np.log10(minr), np.log10(maxr), nbins + 1) # edges to lnr bins
167
+
168
+ for idx in gbxidxs:
169
+ vol = gbxvols[idx]
170
+ sl = np.s_[attrs.sdgbxindex == idx]
171
+ l0 = plot_radiusdistrib(axs[0], hedgs, attrs.radius[sl], attrs.xi[sl])
172
+ l1 = plot_numconcdistrib(axs[1], hedgs, attrs.xi[sl], attrs.radius[sl], vol)
173
+ l2 = plot_masssolutedistrib(
174
+ axs[2], hedgs, attrs.xi[sl], attrs.radius[sl], attrs.msol[sl], vol
175
+ )
176
+ ls = plot_coorddistribs(axs, sl, hedgs, attrs)
177
+
178
+ fig.tight_layout()
179
+
180
+ return fig, axs, [l0, l1, l2, ls]
181
+
182
+
183
+ def plot_initGBxs_attrdistribs(
184
+ config_filename,
185
+ constants_filename,
186
+ initsupers_filename,
187
+ grid_filename,
188
+ gbxs2plt,
189
+ savefigpath,
190
+ savefig,
191
+ savelabel,
192
+ ):
193
+ """plot initial superdroplet distribution from initsupersfile binary
194
+ of every gridbox with index in gbx2plts"""
195
+
196
+ gbxvols = get_gbxvols_from_gridfile(
197
+ grid_filename, constants_filename=constants_filename, isprint=False
198
+ )
199
+ attrs = get_superdroplet_attributes(
200
+ config_filename, constants_filename, initsupers_filename
201
+ )
202
+
203
+ if isinstance(gbxs2plt, int):
204
+ gbxidxs = [gbxs2plt]
205
+ savename = "initGBx" + str(gbxs2plt) + "_distrib" + savelabel + ".png"
206
+ elif gbxs2plt == "all":
207
+ gbxidxs = np.unique(attrs.sdgbxindex)
208
+ savename = "initallGBxs_distribs" + savelabel + ".png"
209
+ else:
210
+ gbxidxs = [int(g) for g in gbxs2plt]
211
+ savename = "initGBxs_distribs" + savelabel + ".png"
212
+
213
+ fig, axs, lines = plot_initdistribs(attrs, gbxvols, gbxidxs)
214
+
215
+ fig.tight_layout()
216
+
217
+ if savefig:
218
+ savename = savefigpath / savename
219
+ fig.savefig(savename, dpi=400, bbox_inches="tight", facecolor="w", format="png")
220
+ print("Figure .png saved as: " + str(savename))
221
+
222
+
223
+ def figure_setup(coord3, coord1, coord2):
224
+ ncoords = 3 - sum(not x.any() for x in [coord3, coord2, coord1])
225
+
226
+ if ncoords == 0:
227
+ fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(14, 4))
228
+ elif ncoords == 1:
229
+ fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(14, 8))
230
+ else:
231
+ fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(14, 8))
232
+
233
+ fig.suptitle(str(ncoords) + "-D SDM Initial Superdroplet Conditions")
234
+ axs = axs.flatten()
235
+ if ncoords == 2:
236
+ axs[-1].remove()
237
+
238
+ return fig, axs
239
+
240
+
241
+ def log10r_frequency_distribution(radius, hedgs, wghts):
242
+ """get distribution of data with weights 'wghts' against
243
+ log10(r). Uses np.histogram to get frequency of a particular
244
+ value of data that falls in each bin (with each bin defined
245
+ by it's edges 'hedgs'). Return distirbution alongside the radius
246
+ bin centers and widths in [m]"""
247
+
248
+ if type(wghts) != np.ndarray:
249
+ wghts = np.full(np.shape(radius), wghts)
250
+
251
+ hist, hedgs = np.histogram(
252
+ np.log10(radius), bins=hedgs, weights=wghts, density=None
253
+ )
254
+
255
+ # convert [m] to [micron]
256
+ hedgs = (10 ** (hedgs)) * 1e6
257
+ # radius bin widths [micron]
258
+ hwdths = hedgs[1:] - hedgs[:-1]
259
+ # radius bin centres [micron]
260
+ hcens = (hedgs[1:] + hedgs[:-1]) / 2
261
+
262
+ return hist, hedgs, hwdths, hcens
263
+
264
+
265
+ def plot_radiusdistrib(ax, hedgs, radius, xi):
266
+ """get and plotthe superdroplet radius in each log10(r)
267
+ bin and as a scatter on a twinx axis with their multiplicities"""
268
+
269
+ l1 = ax.scatter(radius * 1e6, xi, zorder=1, label="multiplicities")
270
+
271
+ ax2 = ax.twinx()
272
+ hist, hedgs, hwdths, hcens = log10r_frequency_distribution(radius, hedgs, 1)
273
+ l2 = ax2.step(
274
+ hcens,
275
+ hist,
276
+ where="mid",
277
+ alpha=0.8,
278
+ zorder=0,
279
+ color="grey",
280
+ label="number distribution",
281
+ )
282
+
283
+ ax.set_xscale("log")
284
+ ax.set_xlabel("radius, r, /\u03BCm")
285
+ ax.set_yscale("log")
286
+
287
+ ax.set_ylabel("superdroplet multiplicity")
288
+ ax2.set_ylabel("superdroplet number distribution")
289
+
290
+ if not ax.get_legend():
291
+ ax.legend(loc="lower left")
292
+ ax2.legend(loc="lower right")
293
+
294
+ return [l1, l2]
295
+
296
+
297
+ def plot_numconcdistrib(ax, hedgs, xi, radius, vol):
298
+ """get and plot frequency of real droplets in each log10(r) bin"""
299
+
300
+ wghts = xi / vol / 1e6 # [cm^-3]
301
+ hist, hedgs, hwdths, hcens = log10r_frequency_distribution(radius, hedgs, wghts)
302
+
303
+ line = ax.step(hcens, hist, label="binned distribution", where="mid")
304
+ ax.set_xscale("log")
305
+ ax.set_xlabel("radius, r, /\u03BCm")
306
+ ax.set_ylabel("real droplet number\nconcentration / cm$^{-3}$")
307
+
308
+ if not ax.get_legend():
309
+ ax.legend(loc="lower left")
310
+
311
+ return line
312
+
313
+
314
+ def plot_masssolutedistrib(ax, hedgs, xi, radius, msol, vol):
315
+ """get and plot frequency of real droplets in each log10(r) bin"""
316
+
317
+ wghts = msol * xi / vol * 1000 / 1e6 # [g cm^-3]
318
+ hist, hedgs, hwdths, hcens = log10r_frequency_distribution(radius, hedgs, wghts)
319
+
320
+ line = ax.step(hcens, hist, where="mid")
321
+ ax.set_xscale("log")
322
+ ax.set_xlabel("radius, r, /\u03BCm")
323
+ ax.set_ylabel("solute mass per unit volume / g cm$^{-3}$")
324
+
325
+ return line
326
+
327
+
328
+ def plot_totmassdistrib(ax, hedgs, xi, radius, msol, vol, RHO_L, RHO_SOL):
329
+ """get and plot frequency of real droplets in each log10(r) bin"""
330
+
331
+ mass = totmass(radius, msol, RHO_L, RHO_SOL)
332
+ wghts = mass * xi / vol * 1000 / 1e6 # [g cm^-3]
333
+ hist, hedgs, hwdths, hcens = log10r_frequency_distribution(radius, hedgs, wghts)
334
+
335
+ line = ax.step(hcens, hist, where="mid")
336
+ ax.set_xscale("log")
337
+ ax.set_xlabel("radius, r, /\u03BCm")
338
+ ax.set_ylabel("droplet mass per unit volume / g cm$^{-3}$")
339
+
340
+ return line
341
+
342
+
343
+ def scatter_totmass_solutemass(ax, radius, msol, RHO_L, RHO_SOL):
344
+ mass = totmass(radius, msol, RHO_L, RHO_SOL)
345
+
346
+ line = ax.scatter(mass * 1000, msol * 1000, marker="x")
347
+
348
+ ax.set_xscale("log")
349
+ ax.set_yscale("log")
350
+ ax.set_xlabel("total mass / g")
351
+ ax.set_ylabel("solute mass / g")
352
+
353
+ return line
354
+
355
+
356
+ def plot_coorddistribs(axs, i2plt, hedgs, attrs):
357
+ ls = []
358
+ if attrs.coord3.any():
359
+ ls.append(
360
+ plot_coorddist(axs[3], hedgs, attrs.coord3[i2plt], attrs.radius[i2plt], 3)
361
+ )
362
+ if attrs.coord1.any():
363
+ ls.append(
364
+ plot_coorddist(
365
+ axs[4], hedgs, attrs.coord1[i2plt], attrs.radius[i2plt], 1
366
+ )
367
+ )
368
+ if attrs.coord2.any():
369
+ ls.append(
370
+ plot_coorddist(
371
+ axs[5], hedgs, attrs.coord2[i2plt], attrs.radius[i2plt], 2
372
+ )
373
+ )
374
+ return ls
375
+
376
+
377
+ def plot_coorddist(ax, hedgs, coord3, radius, coordnum):
378
+ line = None
379
+ if any(coord3):
380
+ line = ax.scatter(radius * 1e6, coord3)
381
+
382
+ ax.set_xscale("log")
383
+ ax.set_xlabel("radius, r, /\u03BCm")
384
+ ax.set_ylabel("superdroplet coord" + str(coordnum) + " / m")
385
+
386
+ return line
387
+
388
+
389
+ def plot_initGBxs_dropletmasses(
390
+ config_filename,
391
+ constants_filename,
392
+ initsupers_filename,
393
+ grid_filename,
394
+ gbxs2plt,
395
+ savefigpath,
396
+ savefig,
397
+ savelabel,
398
+ ):
399
+ """plot initial superdroplet mass distributions
400
+ from initsupersfile binary of every gridbox with index
401
+ in gbx2plts"""
402
+
403
+ gbxvols = get_gbxvols_from_gridfile(
404
+ grid_filename, constants_filename=constants_filename, isprint=False
405
+ )
406
+ attrs = get_superdroplet_attributes(
407
+ config_filename, constants_filename, initsupers_filename
408
+ )
409
+ inputs = initsupers_inputsdict(config_filename, constants_filename)
410
+
411
+ if isinstance(gbxs2plt, int):
412
+ gbxidxs = [gbxs2plt]
413
+ savename = "initGBx" + str(gbxs2plt) + "_dropletmasses" + savelabel + ".png"
414
+ elif gbxs2plt == "all":
415
+ gbxidxs = np.unique(attrs.sdgbxindex)
416
+ savename = "initallGBxs_dropletmasses" + savelabel + ".png"
417
+ else:
418
+ gbxidxs = [int(g) for g in gbxs2plt]
419
+ savename = "initGBxs_dropletmasses" + savelabel + ".png"
420
+
421
+ fig, axs, lines = plot_massdistribs(
422
+ attrs, gbxvols, gbxidxs, inputs["RHO_L"], inputs["RHO_SOL"]
423
+ )
424
+
425
+ fig.tight_layout()
426
+
427
+ if savefig:
428
+ savename = savefigpath / savename
429
+ fig.savefig(savename, dpi=400, bbox_inches="tight", facecolor="w", format="png")
430
+ print("Figure .png saved as: " + str(savename))
431
+
432
+
433
+ def plot_massdistribs(attrs, gbxvols, gbxidxs, RHO_L, RHO_SOL):
434
+ plt.rcParams.update({"font.size": 14})
435
+ fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(14, 4))
436
+ fig.suptitle("SDM Initial Superdroplet Mass Distributions")
437
+
438
+ # create nbins evenly spaced in log10(r)
439
+ nbins = 20
440
+ minr, maxr = np.min(attrs.radius) / 10, np.max(attrs.radius) * 10
441
+ hedgs = np.linspace(np.log10(minr), np.log10(maxr), nbins + 1) # edges to lnr bins
442
+
443
+ for idx in gbxidxs:
444
+ vol = gbxvols[idx]
445
+ sl = np.s_[attrs.sdgbxindex == idx]
446
+ l0 = plot_totmassdistrib(
447
+ axs[0],
448
+ hedgs,
449
+ attrs.xi[sl],
450
+ attrs.radius[sl],
451
+ attrs.msol[sl],
452
+ vol,
453
+ RHO_L,
454
+ RHO_SOL,
455
+ )
456
+ l1 = plot_masssolutedistrib(
457
+ axs[1], hedgs, attrs.xi[sl], attrs.radius[sl], attrs.msol[sl], vol
458
+ )
459
+ l2 = scatter_totmass_solutemass(
460
+ axs[2], attrs.radius[sl], attrs.msol[sl], RHO_L, RHO_SOL
461
+ )
462
+
463
+ fig.tight_layout()
464
+
465
+ return fig, axs, [l0, l1, l2]