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,141 @@
1
+ """
2
+ ----- CLEO -----
3
+ File: sdtracing.py
4
+ Project: sdmout_src
5
+ Created Date: Tuesday 24th October 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
+ !!!NOTE!!! DEPRECIATED SINCE V0.40.0, REPLACED BY SUPERDROPS MODULE !!!!!!
16
+ functions to extract attribute data for specifc superdroplets based on the sdIds
17
+ e.g. for tracing their trajectories
18
+ """
19
+
20
+
21
+ import numpy as np
22
+ import awkward as ak
23
+ import random
24
+ import warnings
25
+
26
+ warnings.warn(
27
+ "sdtracing module is depreciated since CLEO v0.40.0,\nreplaced by superdrops"
28
+ )
29
+
30
+
31
+ def attr_for_superdroplet(sddata, Id, attr):
32
+ """selects attribute from sddata belonging
33
+ to superdroplet with identitiy 'Id'
34
+ at every output time"""
35
+
36
+ bools = ak.Array(sddata.sdId == Id) # True/False id is found in sdId at each time
37
+ attr4Id = sddata[attr][bools] # attribute where sdId = Id
38
+
39
+ num = ak.num(
40
+ attr4Id
41
+ ) # at each time, number of positions where sdId is found (should be 0 or 1)
42
+ if any(num[num != 1]):
43
+ errmsg = (
44
+ "attribute timeseries has times when more"
45
+ + " than one sdId==Id. num should be list of either 1 or 0"
46
+ + " (for Id found in sddata at given time or not)"
47
+ )
48
+ raise ValueError(errmsg)
49
+
50
+ attr4Id = ak.where(
51
+ num == 0, ak.Array([[np.nan]]), attr4Id
52
+ ) # replace empty values with np.nan
53
+
54
+ return ak.flatten(attr4Id, axis=1) # remove excess dimension
55
+
56
+
57
+ def attributes_for1superdroplet(sddata, Id, attrs):
58
+ """selects attributes in 'attrs' from sddata
59
+ belonging to superdroplet with identitiy 'Id'
60
+ at every output time"""
61
+
62
+ attrs4Id = {}
63
+ for attr in attrs:
64
+ attrs4Id[attr] = attr_for_superdroplet(sddata, Id, attr)
65
+
66
+ return attrs4Id
67
+
68
+
69
+ def attribute_for_superdroplets_sample(
70
+ sddata, attr, ndrops2sample=0, minid=0, maxid=0, ids=[]
71
+ ):
72
+ """returns 2D array with dimensions [time, SD]
73
+ containing attribute data over time for a sample of
74
+ superdroplets. Sample is either for superdroplets with
75
+ specific Ids in 'ids' list, or sample of 'ndrops2sample'
76
+ randomly selected superdrops with Ids in the range
77
+ [minid, maxid]"""
78
+
79
+ if np.any(ids):
80
+ sample = ids
81
+ else: # ids == []
82
+ population = list(range(minid, maxid, 1))
83
+ if ndrops2sample == 0:
84
+ ndrops2sample = maxid
85
+ sample = random.sample(population, ndrops2sample)
86
+
87
+ ndrops_attr = []
88
+ for id in sample:
89
+ attr4Id = attr_for_superdroplet(sddata, id, attr)
90
+ ndrops_attr.append(attr4Id)
91
+
92
+ return np.asarray(ndrops_attr).T
93
+
94
+
95
+ def attr_at_times(attrdata, time, times2sel):
96
+ """selects attribute (for all superdroplets)
97
+ at times closest to 'times2sel'"""
98
+
99
+ inds = [] # list containing indexes of times closest to times2sel
100
+ for t in times2sel:
101
+ inds.append(np.argmin(abs(time - t)))
102
+
103
+ return attrdata[inds]
104
+
105
+
106
+ def attributes_at_times(sddata, time, times2sel, attrs2sel):
107
+ """selects attributes at given times from
108
+ sddata (for all superdroplets in sddata)"""
109
+
110
+ selected_data = {} # dict containting selected attributes at selected times
111
+
112
+ for attr in attrs2sel:
113
+ selattr_data = attr_at_times(sddata[attr], time, times2sel)
114
+ selected_data[attr] = selattr_data
115
+
116
+ return selected_data
117
+
118
+
119
+ def attrs_for_superdroplets_sample(
120
+ sddata, attrs, ndrops2sample=0, minid=0, maxid=0, ids=[]
121
+ ):
122
+ """returns dictionary of 2D arrays (with dimensions [time, SD])
123
+ for each attribute in 'attrs' list for a sample of
124
+ superdroplets. Sample is either for superdroplets with
125
+ specific Ids in 'ids' list, or sample of 'ndrops2sample'
126
+ randomly selected superdrops with Ids in the range
127
+ [minid, maxid]"""
128
+
129
+ if np.any(ids):
130
+ sample = ids
131
+ else: # ids == []
132
+ population = list(range(minid, maxid, 1))
133
+ if ndrops2sample == 0:
134
+ ndrops2sample = maxid
135
+ sample = random.sample(population, ndrops2sample)
136
+
137
+ data = {}
138
+ for a in attrs:
139
+ data[a] = attribute_for_superdroplets_sample(sddata, a, ids=sample)
140
+
141
+ return data
@@ -0,0 +1,428 @@
1
+ """
2
+ Copyright (c) 2025 MPI-M, Clara Bayley
3
+
4
+
5
+ ----- CLEO -----
6
+ File: superdrops.py
7
+ Project: sdmout_src
8
+ Created Date: Thursday 29th May 2025
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
+ python class(es) to handle superdroplet attributes data from SDM zarr store in ragged array format.
17
+ Non-compatible update on supersdata and sdtracing modules
18
+ """
19
+
20
+
21
+ import awkward as ak
22
+ import numpy as np
23
+ import random
24
+ import warnings
25
+ import xarray as xr
26
+
27
+ from pathlib import Path
28
+
29
+
30
+ class SuperdropProperties:
31
+ """Contains attributes common to all superdroplets and functions
32
+ for calculating derived ones"""
33
+
34
+ def __init__(self, consts: dict, is_print=False):
35
+ """Common attributes shared by superdroplets:
36
+ RHO_L = density of liquid in droplets (=density of water at 300K) [Kg/m^3]
37
+ RHO_SOL = density of (dry) solute [Kg/m^3]
38
+ MR_SOL = Mr of solute [g/mol]
39
+ IONIC = degree ionic dissociation (van't Hoff factor)
40
+ """
41
+ # properties: value
42
+ self._props = {
43
+ "RHO_L": consts["RHO_L"],
44
+ "RHO_SOL": consts["RHO_SOL"],
45
+ "MR_SOL": consts["MR_SOL"],
46
+ "IONIC": consts["IONIC"],
47
+ "RHO_L_units": "Kg m^{-3}",
48
+ "RHO_SOL_units": "Kg m^{-3}",
49
+ "MR_SOL_units": "g mol^{-1}",
50
+ }
51
+
52
+ if is_print:
53
+ self.print_properties()
54
+
55
+ def get_props(self, var: str, units: bool):
56
+ if not units:
57
+ return self._props[var]
58
+ else:
59
+ return self._props[var], self._props[var + "_units"]
60
+
61
+ def RHO_L(self, units=False):
62
+ return self.get_props("RHO_L", units=units)
63
+
64
+ def RHO_SOL(self, units=False):
65
+ return self.get_props("RHO_SOL", units=units)
66
+
67
+ def MR_SOL(self, units=False):
68
+ return self.get_props("MR_SOL", units=units)
69
+
70
+ def IONIC(self, units=False):
71
+ if units:
72
+ print("degree ionic dissociation (van't Hoff factor) has no units")
73
+ return self.get_props("IONIC", units=False)
74
+
75
+ def __getitem__(self, key):
76
+ return self._props[key]
77
+
78
+ def print_properties(self):
79
+ print("---- Superdrop Properties -----")
80
+ print("RHO_L =", self.RHO_L())
81
+ print("RHO_SOL =", self.RHO_SOL())
82
+ print("MR_SOL =", self.MR_SOL())
83
+ print("IONIC =", self.IONIC())
84
+ print("-------------------------------")
85
+
86
+ def rhoeff(self, r, msol):
87
+ """calculates effective density [g m^-3] of
88
+ droplet such that mass_droplet, m = 4/3*pi*r^3 * rhoeff
89
+ taking into account mass of liquid and mass of
90
+ solute assuming solute occupies volume it
91
+ would given its (dry) density, RHO_SOL."""
92
+
93
+ msol = msol / 1000 # convert from grams to Kg
94
+ r = r / 1e6 # convert microns to m
95
+
96
+ solfactor = 3 * msol / (4.0 * np.pi * (r**3))
97
+ rhoeff = self._props["RHO_L"] + solfactor * (
98
+ 1 - self._props["RHO_L"] / self._props["RHO_SOL"]
99
+ )
100
+
101
+ return rhoeff * 1000 # [g/m^3]
102
+
103
+ def vol(self, r):
104
+ """volume of droplet [m^3]"""
105
+
106
+ r = r / 1e6 # convert microns to m
107
+
108
+ return 4.0 / 3.0 * np.pi * r**3
109
+
110
+ def mass(self, r, msol):
111
+ """
112
+ total mass of droplet (water + (dry) areosol) [g],
113
+ m = 4/3*pi*rho_l**3 + msol(1-rho_l/rho_sol)
114
+ ie. m = 4/3*pi*rhoeff*R**3
115
+ """
116
+
117
+ msol = msol / 1000 # convert from grams to Kg
118
+ r = r / 1e6 # convert microns to m
119
+
120
+ msoleff = msol * (
121
+ 1 - self._props["RHO_L"] / self._props["RHO_SOL"]
122
+ ) # effect of solute on mass
123
+ m = msoleff + 4 / 3.0 * np.pi * (r**3) * self._props["RHO_L"]
124
+
125
+ return m * 1000 # [g]
126
+
127
+ def m_water(self, r, msol):
128
+ """mass of only water in droplet [g]"""
129
+
130
+ msol = msol / 1000 # convert msol from grams to Kg
131
+ r = r / 1e6 # convert microns to m
132
+
133
+ v_sol = msol / self._props["RHO_SOL"]
134
+ v_w = 4 / 3.0 * np.pi * (r**3) - v_sol
135
+
136
+ return self._props["RHO_L"] * v_w * 1000 # [g]
137
+
138
+
139
+ class Superdrops(SuperdropProperties):
140
+ def __init__(self, dataset, consts=None, is_print=False):
141
+ if isinstance(dataset, Superdrops):
142
+ SuperdropProperties.__init__(self, dataset._props, is_print=is_print)
143
+ self._variables = dataset._variables
144
+ self._raw_data = dataset._raw_data
145
+ self._units = dataset._units
146
+
147
+ elif (
148
+ isinstance(dataset, xr.Dataset)
149
+ or isinstance(dataset, str)
150
+ or isinstance(dataset, Path)
151
+ ):
152
+ if consts is not None:
153
+ SuperdropProperties.__init__(self, consts, is_print=is_print)
154
+ else:
155
+ warnings.warn(
156
+ "No superdroplet properties attached to superdroplet dataset"
157
+ )
158
+
159
+ ds = self.tryopen_dataset(dataset)
160
+ raggedcount = ds["raggedcount"] # ragged count variable
161
+ self._variables = (
162
+ "sdId",
163
+ "sdgbxindex",
164
+ "xi",
165
+ "radius",
166
+ "msol",
167
+ "coord3",
168
+ "coord1",
169
+ "coord2",
170
+ )
171
+ self._raw_data = {
172
+ var: self.tryvar(ds, raggedcount, var) for var in self._variables
173
+ }
174
+ self._units = {
175
+ "radius_units": self.tryunits(ds, "radius"), # probably microns
176
+ "msol_units": self.tryunits(ds, "msol"), # probably gramms
177
+ "coord3_units": self.tryunits(ds, "coord3"), # probably meters
178
+ "coord1_units": self.tryunits(ds, "coord1"), # probably meters
179
+ "coord2_units": self.tryunits(ds, "coord2"), # probably meters
180
+ }
181
+ else:
182
+ raise ValueError("unknow type of dataset to make superdroplets from")
183
+
184
+ def tryopen_dataset(self, dataset: Path):
185
+ if isinstance(dataset, str) or isinstance(dataset, Path):
186
+ print("supers dataset: ", dataset)
187
+ return xr.open_dataset(dataset, engine="zarr", consolidated=False)
188
+ else:
189
+ return dataset
190
+
191
+ def tryvar(self, ds: xr.Dataset, raggedcount: xr.DataArray, var: str):
192
+ """attempts to return variable in form of ragged array
193
+ (ak.Array) with dims [time, raggedcount]
194
+ for a variable "var" in xarray dataset 'ds'.
195
+ If attempt fails, returns empty array instead"""
196
+ try:
197
+ return ak.unflatten(ds[var].values, raggedcount.values)
198
+ except KeyError:
199
+ return ak.Array([])
200
+
201
+ def tryunits(self, ds: xr.Dataset, var: str):
202
+ """attempts to return the units of a variable
203
+ in xarray dataset 'ds'. If attempt fails, returns null"""
204
+ try:
205
+ return ds[var].units
206
+ except KeyError:
207
+ return ""
208
+
209
+ def get_units(self, var: str):
210
+ return self._units[var + "_units"]
211
+
212
+ def get_variable(self, var: str, units: bool):
213
+ if not units:
214
+ return self._raw_data[var]
215
+ else:
216
+ return self._raw_data[var], self.get_units(var)
217
+
218
+ def sdId(self, units=False):
219
+ return self.get_variable("sdId", units)
220
+
221
+ def sdgbxindex(self, units=False):
222
+ return self.get_variable("sdgbxindex", units)
223
+
224
+ def xi(self, units=False):
225
+ return self.get_variable("xi", units)
226
+
227
+ def radius(self, units=False):
228
+ return self.get_variable("radius", units)
229
+
230
+ def msol(self, units=False):
231
+ return self.get_variable("msol", units)
232
+
233
+ def coord3(self, units=False):
234
+ return self.get_variable("coord3", units)
235
+
236
+ def coord1(self, units=False):
237
+ return self.get_variable("coord1", units)
238
+
239
+ def coord2(self, units=False):
240
+ return self.get_variable("coord2", units)
241
+
242
+ def time(self, units=False):
243
+ if "time" in self._variables:
244
+ return self.get_variable("time", units)
245
+ print("time is not attached to superdrops")
246
+ return None
247
+
248
+ def radius_units(self):
249
+ return self.get_units("radius")
250
+
251
+ def msol_units(self):
252
+ return self.get_units("msol")
253
+
254
+ def coord3_units(self):
255
+ return self.get_units("coord3")
256
+
257
+ def coord1_units(self):
258
+ return self.get_units("coord1")
259
+
260
+ def coord2_units(self):
261
+ return self.get_units("coord2")
262
+
263
+ def time_units(self):
264
+ if "time" in self._variables:
265
+ return self.get_units("time")
266
+ print("time is not attached to superdrops")
267
+ return None
268
+
269
+ def __getitem__(self, key):
270
+ if key == "sdId":
271
+ return self.sdId()
272
+ elif key == "sdgbxindex":
273
+ return self.sdgbxindex()
274
+ elif key == "xi":
275
+ return self.xi()
276
+ elif key == "radius":
277
+ return self.radius()
278
+ elif key == "msol":
279
+ return self.msol()
280
+ elif key == "coord3":
281
+ return self.coord3()
282
+ elif key == "coord1":
283
+ return self.coord1()
284
+ elif key == "coord2":
285
+ return self.coord2()
286
+ elif key == "time":
287
+ return self.time()
288
+ elif key == "radius_units":
289
+ return self.radius_units()
290
+ elif key == "msol_units":
291
+ return self.msol_units()
292
+ elif key == "coord3_units":
293
+ return self.coord3_units()
294
+ elif key == "coord1_units":
295
+ return self.coord1_units()
296
+ elif key == "coord2_units":
297
+ return self.coord2_units()
298
+ elif key == "time_units":
299
+ return self.time_units()
300
+ else:
301
+ err = "no known return provided for " + key + " key"
302
+ raise ValueError(err)
303
+
304
+ def attach_time(
305
+ self, time: np.ndarray, time_units: str, do_reshape=False, var4reshape="sdId"
306
+ ):
307
+ if "time" not in self._raw_data:
308
+ if do_reshape:
309
+ # e.g. use sdId array to make 1-D time array have matching (ragged) dimension
310
+ time = ak.broadcast_arrays(self._raw_data[var4reshape], time)[1]
311
+ self._variables = tuple(list(self._variables) + ["time"])
312
+ self._raw_data["time"] = ak.Array(time)
313
+ self._units["time_units"] = time_units
314
+ else:
315
+ print("time already attached to superdrops")
316
+
317
+ def detach_time(self):
318
+ if "time" not in self._raw_data:
319
+ print("time is not attached to superdrops")
320
+ else:
321
+ variables = list(self._variables)
322
+ variables.remove("time")
323
+ self._variables = tuple(variables)
324
+ del self._raw_data["time"]
325
+ del self._units["time_units"]
326
+
327
+ def sample(self, sample_var: str, sample_values="all", variables2sample="all"):
328
+ if isinstance(sample_var, str):
329
+ sample_var = self._raw_data[sample_var]
330
+
331
+ if isinstance(sample_values, str) and sample_values == "all":
332
+ sample_values = list(np.unique(ak.flatten(sample_var)))
333
+ elif not isinstance(sample_values, list):
334
+ sample_values = [sample_values]
335
+
336
+ if isinstance(variables2sample, str) and variables2sample == "all":
337
+ variables2sample = self._variables
338
+ elif not isinstance(variables2sample, list):
339
+ variables2sample = [variables2sample]
340
+
341
+ raw_data = {var: [] for var in variables2sample}
342
+ for value in sample_values:
343
+ mask = ak.Array(sample_var == value)
344
+ for var in variables2sample:
345
+ var_for_sample_value = ak.flatten(
346
+ ak.drop_none(self._raw_data[var].mask[mask])
347
+ )
348
+ raw_data[var].append(var_for_sample_value)
349
+
350
+ superdrops_sample = Superdrops(self)
351
+ superdrops_sample._variables = raw_data.keys()
352
+ superdrops_sample._raw_data = raw_data
353
+
354
+ return superdrops_sample
355
+
356
+ def random_sample(
357
+ self,
358
+ sample_var: str,
359
+ ndrops2sample: int,
360
+ sample_population="all",
361
+ variables2sample="all",
362
+ ):
363
+ if isinstance(sample_var, str):
364
+ sample_var = self._raw_data[sample_var]
365
+
366
+ if sample_population == "all":
367
+ sample_population = list(np.unique(ak.flatten(sample_var)))
368
+
369
+ sample_values = random.sample(sample_population, ndrops2sample)
370
+ return self.sample(
371
+ sample_var, sample_values=sample_values, variables2sample=variables2sample
372
+ )
373
+
374
+ def indexes_of_time_slices(self, time, times2select):
375
+ if isinstance(time, list):
376
+ time_indexes = []
377
+ for i in range(len(time)):
378
+ time_indexes.append(self.indexes_of_time_slices(time[i], times2select))
379
+ return time_indexes
380
+
381
+ if len(time) == ak.count(time): # time is 1-D array
382
+ time_indexes = []
383
+ for t in times2select:
384
+ idx = ak.argmin(abs((time - t)))
385
+ time_indexes.append(idx)
386
+ else: # time assumed to be ragged array like superdrops data
387
+ time_indexes = []
388
+ for t in times2select:
389
+ idx = ak.nanargmin(abs((time - t)), axis=0)[0]
390
+ time_indexes.append(idx)
391
+
392
+ return time_indexes
393
+
394
+ def time_slice(
395
+ self,
396
+ times2select,
397
+ variables2slice="all",
398
+ attach_time=False,
399
+ time=None,
400
+ time_units=None,
401
+ ):
402
+ if attach_time:
403
+ self.attach_time(time, time_units, do_reshape=False)
404
+
405
+ if isinstance(variables2slice, str) and variables2slice == "all":
406
+ variables2slice = self._variables
407
+ elif not isinstance(variables2slice, list):
408
+ variables2slice = [variables2slice]
409
+
410
+ time_indexes = self.indexes_of_time_slices(self.time(), times2select)
411
+
412
+ raw_data = {var: [] for var in variables2slice}
413
+ for var in variables2slice:
414
+ if isinstance(
415
+ self._raw_data[var], list
416
+ ): # superdrops sample is being sliced
417
+ time_slice_var = []
418
+ for i in range(len(self._raw_data[var])):
419
+ time_slice_var.append(self._raw_data[var][i][time_indexes[i]])
420
+ else:
421
+ time_slice_var = self._raw_data[var][time_indexes]
422
+ raw_data[var] = time_slice_var
423
+
424
+ superdrops_timeslice = Superdrops(self)
425
+ superdrops_timeslice._variables = raw_data.keys()
426
+ superdrops_timeslice._raw_data = raw_data
427
+
428
+ return superdrops_timeslice