kgsim 0.3.2__tar.gz → 0.3.3__tar.gz

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 (32) hide show
  1. {kgsim-0.3.2 → kgsim-0.3.3}/PKG-INFO +1 -1
  2. {kgsim-0.3.2 → kgsim-0.3.3}/pyproject.toml +1 -1
  3. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/dhybridr/dhybridr.py +42 -4
  4. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/fields/__init__.py +1 -0
  5. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/fields/scalar.py +2 -2
  6. kgsim-0.3.3/src/kgsim/fields/structure.py +161 -0
  7. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/fields/vector.py +15 -5
  8. {kgsim-0.3.2 → kgsim-0.3.3}/README.md +0 -0
  9. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/__init__.py +0 -0
  10. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/athena/__init__.py +0 -0
  11. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/athena/athena.py +0 -0
  12. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/athena/athena_read.py +0 -0
  13. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/dhybridr/__init__.py +0 -0
  14. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/dhybridr/anvil_submit.py +0 -0
  15. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/dhybridr/initializer.py +0 -0
  16. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/dhybridr/io.py +0 -0
  17. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/dhybridr/turbulence.py +0 -0
  18. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/exceptions.py +0 -0
  19. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/fields/calc.py +0 -0
  20. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/particles.py +0 -0
  21. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/simulation.py +0 -0
  22. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/3dHybridR/config +0 -0
  23. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/3dHybridR/input/input +0 -0
  24. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/3dHybridR/sim_init_3D.py +0 -0
  25. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/3dHybridR/submit_anvil.sh +0 -0
  26. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/__init__.py +0 -0
  27. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/dHybridR/input/input +0 -0
  28. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/dHybridR/sim_init.py +0 -0
  29. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/templates/dHybridR/submit_anvil.sh +0 -0
  30. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/tristan/__init__.py +0 -0
  31. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/tristan/kappa.py +0 -0
  32. {kgsim-0.3.2 → kgsim-0.3.3}/src/kgsim/tristan/tristan.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: kgsim
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary: A library to interact with simulations with.
5
5
  Author: Keyan Gootkin
6
6
  Author-email: Keyan Gootkin <keyangootkin@gmail.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "kgsim"
3
- version = "0.3.2"
3
+ version = "0.3.3"
4
4
  description = "A library to interact with simulations with."
5
5
  authors = [
6
6
  { name="Keyan Gootkin", email="keyangootkin@gmail.com" },
@@ -7,11 +7,11 @@ from glob import glob
7
7
  from os import system
8
8
  from os.path import exists
9
9
  from h5py import File as h5File
10
- from numpy import mean, linspace, diff, exp, array, prod, inf, vstack, nanmin, \
11
- nanmax, append
10
+ from numpy import mean, linspace, diff, exp, array, prod, inf, vstack, nanmin, nanmax, append, \
11
+ ndarray
12
12
  from numpy.random import choice
13
13
 
14
- from kgsim.fields import ScalarField, VectorField, Az
14
+ from kgsim.fields import ScalarField, VectorField, Az, single_point_single_lag_structure_function
15
15
  from kgsim.simulation import GenericSimulation, SimulationGroup
16
16
  from kgsim.particles import Species, Particle
17
17
  from kgsim.dhybridr.io import dHybridRinput, dHybridRout
@@ -22,7 +22,7 @@ from kgsim.templates import dHybridRtemplate
22
22
  from kplot import show, func_video
23
23
  from kbasic.bar import verbose_bar
24
24
  from kbasic.strings import purple
25
- from kbasic.parsing import Folder
25
+ from kbasic.parsing import Folder, Path
26
26
  from kbasic.vectors import Vector
27
27
 
28
28
  # !==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==
@@ -35,6 +35,12 @@ track_keys = [
35
35
  # !==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==
36
36
  # >-|===|> Functions <|===|-<
37
37
  # !==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==
38
+ def create_dhybridr_data_file(data: ndarray, path: Path) -> h5File:
39
+ """docstring"""
40
+ with h5File(path, 'a') as file:
41
+ file['DATA'] = data
42
+ return file
43
+
38
44
  # simulation parsing
39
45
  def extract_energy(file_name: str) -> tuple:
40
46
  """docstring"""
@@ -45,9 +51,13 @@ def extract_energy(file_name: str) -> tuple:
45
51
  dlne = diff(lne)[0]
46
52
  E = exp(lne)
47
53
  return E, fE, dlne
54
+
55
+
48
56
  def iters(simulation) -> list[int]:
49
57
  """Grab the iterations of each snapshot for a simulation"""
50
58
  return [int(fn[-11:-3]) for fn in simulation.density.file_names]
59
+
60
+
51
61
  def times(simulation: GenericSimulation, ndigits: int = 7) -> list[float]:
52
62
  """return the time (in simulation units) of each measurement
53
63
 
@@ -61,6 +71,8 @@ def times(simulation: GenericSimulation, ndigits: int = 7) -> list[float]:
61
71
  """
62
72
  x = list(array(iters(simulation)).astype(float) * simulation.dt)
63
73
  return [round(xi, ndigits) for xi in x]
74
+
75
+
64
76
  def particle_video(
65
77
  sim,
66
78
  particles: list[str] | int,
@@ -139,9 +151,11 @@ class dHybridRparticle(Particle):
139
151
  Particle.__init__(self, species=species, tag=tag)
140
152
  self.loaded: bool = False
141
153
  if load: self.load()
154
+
142
155
  def __len__(self) -> int:
143
156
  assert self.loaded, f"Tried to take the length of {self} without loading first"
144
157
  return len(self.x)
158
+
145
159
  def load(self):
146
160
  """docstring"""
147
161
  with h5File(self.species.path) as file:
@@ -158,6 +172,20 @@ class dHybridRparticle(Particle):
158
172
  self.B = Vector(self.B1, self.B2, self.B3)
159
173
  self.E = Vector(self.E1, self.E2, self.E3)
160
174
  self.loaded: bool = True
175
+
176
+ def structure_function(self, l):
177
+ """docstring"""
178
+ u = abs(self.parent.u)
179
+ xcells = (self.x // self.parent.dx).astype(int)
180
+ ycells = (self.y // self.parent.dy).astype(int)
181
+ bis = [i for _ in range(self.species.pipsi) for i in range(len(self.parent))]
182
+ return array([
183
+ single_point_single_lag_structure_function(
184
+ xcells[i], ycells[i], 1, u[bi], l
185
+ ) for i,bi in verbose_bar(zip(range(len(self.parent)), bis), self.parent.verbose)
186
+ ])
187
+
188
+
161
189
  class dHybridRspecies(Species):
162
190
  def __init__(
163
191
  self,
@@ -176,11 +204,15 @@ class dHybridRspecies(Species):
176
204
  if self.input.track_dump:
177
205
  self.path = parent.path+f"/Output/Tracks/Sp{self.nstr}/track_Sp{self.nstr}.h5"
178
206
  self.load()
207
+
179
208
  def __repr__(self) -> str: return self.name
209
+
180
210
  def __str__(self) -> str: return self.name
211
+
181
212
  def __len__(self) -> int:
182
213
  assert self.loaded, f"Tried to take the length of {self} without loading first"
183
214
  return len(self.tags)
215
+
184
216
  def __getitem__(self, key):
185
217
  match key:
186
218
  case str(tag): return dHybridRparticle(self, tag)
@@ -193,6 +225,7 @@ class dHybridRspecies(Species):
193
225
  1 if di is None else di
194
226
  )
195
227
  ]
228
+
196
229
  def load(self):
197
230
  """docstring"""
198
231
  with h5File(self.path) as file:
@@ -209,6 +242,8 @@ class dHybridRspecies(Species):
209
242
  ])
210
243
  if len(particle_list)==1: return particle_list[0]
211
244
  else: return particle_list
245
+
246
+
212
247
  class dHybridR(GenericSimulation):
213
248
  """
214
249
  A simulation class to interact with dHybridR simulations in python
@@ -304,11 +339,13 @@ class dHybridR(GenericSimulation):
304
339
  self.dy: float = self.input.boxsize[1]/self.input.ncells[1]
305
340
  self.dz: float = self.input.boxsize[2]/self.input.ncells[2] \
306
341
  if len(self.input.boxsize)==3 else inf
342
+
307
343
  def run(self, initializer: dHybridRinitializer, submit_script: AnvilSubmitScript) -> None:
308
344
  """docstring"""
309
345
  initializer.prepare_simulation()
310
346
  submit_script.write()
311
347
  system(f"sh {submit_script.path}")
348
+
312
349
  def parse_output(self) -> None:
313
350
  """docstring"""
314
351
  self.out = dHybridRout(self.path+"/out")
@@ -413,6 +450,7 @@ class dHybridR(GenericSimulation):
413
450
  self.start = time()
414
451
  self.iter = array(iters(self))
415
452
  self.time = array(times(self))
453
+
416
454
  def magnetic_potential_extrema(self):
417
455
  """docstring"""
418
456
  n, x = inf, -inf
@@ -1,3 +1,4 @@
1
+ from kgsim.fields.structure import *
1
2
  from kgsim.fields.scalar import *
2
3
  from kgsim.fields.vector import *
3
4
  from kgsim.fields.calc import *
@@ -63,7 +63,7 @@ class ScalarField:
63
63
  caching: bool = False,
64
64
  verbose: bool = False,
65
65
  debug: bool = False,
66
- ) -> None:
66
+ ) -> None:
67
67
  self.name: str = name
68
68
  self.latex: str = latex
69
69
  self.parent = parent
@@ -212,7 +212,7 @@ class ScalarField:
212
212
  if hasattr(self.parent, 'dx'):
213
213
  x_ticks = arange(0, self.parent.input.boxsize[0], self.parent.dx)
214
214
  y_ticks = arange(0, self.parent.input.boxsize[1], self.parent.dy)
215
- show(self[item], x=x_ticks, y=y_ticks, **kwargs)
215
+ return show(self[item], x=x_ticks, y=y_ticks, **kwargs)
216
216
  assert False
217
217
  def movie(self, file_name=None, norm='none', cmap=default_cmap, func=None,**kwds) -> None:
218
218
  """docstring"""
@@ -0,0 +1,161 @@
1
+ """calculate the structure function of arrays and fields"""
2
+ # !==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==
3
+ # >-|===|> Imports <|===|-<
4
+ # !==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==
5
+ from math import sqrt
6
+ from collections.abc import Iterable
7
+ from kbasic import verbose_bar, Tex
8
+ from numpy import ndarray, array, mgrid, random, floor_divide, hypot, where, roll, interp, log10, \
9
+ argsort
10
+ from numpy import abs as npabs
11
+ from numpy import mean as npmean
12
+
13
+ # !==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==
14
+ # >-|===|> Functions <|===|-<
15
+ # !==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==!==
16
+ def select_random_pixels(image: ndarray, fill_fraction):
17
+ """select fill_fraction of pixels of image randomly"""
18
+ (Nx, Ny) = image.shape
19
+ if fill_fraction==1:
20
+ X2D, Y2D = mgrid[:Nx, :Ny]
21
+ x, y = X2D.flatten(), Y2D.flatten()
22
+ return x, y
23
+ pixel_numbers = random.choice(
24
+ image.size,
25
+ size=int((image.size*fill_fraction)//1),
26
+ replace=False
27
+ )
28
+ x = floor_divide(pixel_numbers, Nx)
29
+ y = pixel_numbers % Nx
30
+ return x, y
31
+
32
+ def single_point_single_lag_structure_function(i, j, p, u, l):
33
+ """docstring"""
34
+ (Nx, Ny) = u.shape
35
+ # prepare annulus selection function
36
+ grid = mgrid[-Nx//2:Nx//2, -Ny//2:Ny//2]
37
+ grid = hypot(grid[0], grid[1])
38
+ grid = where(grid//1 == l, True, False)
39
+ in_annulus = lambda i, j: roll(grid, (i - Nx//2, j - Ny//2), axis=(0,1))
40
+ return npmean(npabs(u[i,j] - u[in_annulus(i,j)])**p)
41
+
42
+ def single_structure_function(p, u, l, sample, verbose, _is_multi: bool = False):
43
+ """
44
+ for a single value of l, return the structure function
45
+
46
+ Args:
47
+ p (int): structure function order
48
+ u (ndarray): the field to compute the structure function for
49
+ l (int): lag
50
+ sample (str|float): 'all' if you want to sample every point else the fraction
51
+ of possible points to select
52
+ verbose (bool): whether to provide verbose output
53
+
54
+ Returns:
55
+ ndarray: The p^th order structure function of u with lag l
56
+ """
57
+ (Nx, Ny) = u.shape
58
+ # select the pixels to calculate the structure function for
59
+ x_selected, y_selected = select_random_pixels(u, 1 if sample=='all' else sample)
60
+ # prepare annulus selection function
61
+ grid = mgrid[-Nx//2:Nx//2, -Ny//2:Ny//2]
62
+ grid = hypot(grid[0], grid[1])
63
+ grid = where(grid//1 == l, True, False)
64
+ in_annulus = lambda i, j: roll(grid, (i - Nx//2, j - Ny//2), axis=(0,1))
65
+ if sample=='all':
66
+ return array([
67
+ # for pixel i,j
68
+ npmean(
69
+ # take the mean of |u_ij - u_annulus|^p for all values of u in the annulus
70
+ npabs(u[i, j] - u[in_annulus(i, j)]) ** p
71
+ ) for i,j in verbose_bar(zip(x_selected, y_selected), verbose, total=len(x_selected))
72
+ ]).reshape(u.shape)
73
+ br = verbose_bar(
74
+ zip(x_selected, y_selected),
75
+ verbose,
76
+ desc=Tex(rf"calculate \mathcal[S]^{p}(\ell={l})").string,
77
+ total=len(x_selected),
78
+ position=1,
79
+ leave=False
80
+ )
81
+ # take the mean of |u_ij - u_annulus|^p for all selected pixels
82
+ return npmean(array([
83
+ npmean(
84
+ npabs(u[i, j] - u[in_annulus(i, j)]) ** p
85
+ ) for i,j in br
86
+ ]))
87
+
88
+ def S(
89
+ p: int,
90
+ u: ndarray,
91
+ l: int|ndarray|list,
92
+ sample: str|float = "all",
93
+ verbose: bool = True
94
+ ):
95
+ """structure function factory
96
+
97
+ Args:
98
+ p (int): _description_
99
+ u (ndarray): _description_
100
+ l (int | ndarray | list): _description_
101
+ sample (str | float, optional): _description_. Defaults to "all".
102
+ verbose (bool, optional): _description_. Defaults to True.
103
+
104
+ Returns:
105
+ _type_: _description_
106
+ """
107
+ match l:
108
+ # if l is a single number
109
+ case int(): return single_structure_function(p,u,l,sample,verbose)
110
+ # if we want to calculate a series of l's
111
+ case Iterable():
112
+ lbar = verbose_bar(l, verbose, total=len(l), position=0)
113
+ return array([
114
+ single_structure_function(p,u,li,sample,False,_is_multi=True) for li in lbar
115
+ ])
116
+
117
+ def log_interp(x_interp, x, y):
118
+ """perform interpolation in logspace"""
119
+ return 10**interp(log10(x_interp), log10(x), log10(y))
120
+
121
+ def sonic_scale(u, sample=0.01, tolerance=0.05, Ntries=10, return_spectrum=False, verbose=True):
122
+ """compute the lag at which S(1, u, l)=1"""
123
+ du = lambda li: S(1, u, li, verbose=False, sample=sample)
124
+
125
+ left = 1
126
+ Sl = du(left)
127
+ right = int(max(u.shape)//sqrt(2))
128
+ Sr = du(right)
129
+ assert Sl < 1 and Sr > 1, f"Sonic point {'above' if Sr < 1 else 'below'} inertial range of \
130
+ {left}-{right} and {Sl}-{Sr}."
131
+
132
+ guess = int(log_interp(1, [Sl, Sr], [left, right])//1)
133
+ Sg = du(guess)
134
+ Ng = 0
135
+
136
+ all_l, all_s = [left, guess, right], [Sl, Sg, Sr]
137
+
138
+ while npabs(Sg-1) > tolerance:
139
+ if Sg>1:
140
+ Sr=Sg
141
+ right=guess
142
+ else:
143
+ Sl=Sg
144
+ left=guess
145
+
146
+ if left-right==1:
147
+ if verbose: print("didn't hit tolerance, but guess range is 1")
148
+ break
149
+ guess = int(log_interp(1, [Sl, Sr], [left, right])//1)
150
+ all_l.append(guess)
151
+ Sg = du(guess)
152
+ all_s.append(Sg)
153
+ Ng+=1
154
+ if Ng>=Ntries:
155
+ if verbose: print(f"didn't hit tolerance of {tolerance} in {Ntries} tries")
156
+ if verbose: print(f"S({guess})={Sg}")
157
+ break
158
+ if return_spectrum:
159
+ sort = argsort(all_l)
160
+ return guess, array(all_l)[sort], array(all_s)[sort]
161
+ return guess
@@ -64,13 +64,15 @@ class VectorField:
64
64
  self.caching = caching
65
65
  # set self.components, self.ndims, self.size
66
66
  self._parse_components(components)
67
+
67
68
  def __len__(self) -> int: return min([len(c) for c in self.components])
69
+
68
70
  def __abs__(self) -> NDArray | ScalarField:
69
71
  if hasattr(self, 'magnitude'):
70
- return self.magnitude
71
- if (p:=self.path / "Intensity").exists:
72
+ return getattr(self, 'magnitude')
73
+ if type(p:=self.path / "Intensity")==Folder:
72
74
  self.magnitude = ScalarField(
73
- p,
75
+ p,
74
76
  name=self.name+'_magnitude',
75
77
  latex=f"$|{self.latex}|$",
76
78
  parent=self.parent,
@@ -79,8 +81,9 @@ class VectorField:
79
81
  debug=self.debug
80
82
  )
81
83
  return self.magnitude
84
+ self.magnitude = _vector_mag(self)
85
+ return self.magnitude
82
86
 
83
- return _vector_mag(self)
84
87
  def __getitem__(self, item: int|slice) -> NDArray:
85
88
  match type(item):
86
89
  case int(): return array([c[item] for c in self.components])
@@ -97,6 +100,7 @@ class VectorField:
97
100
  c[i] for c in self.components
98
101
  ] for i in item_iters
99
102
  ])
103
+
100
104
  def _parse_components(self, source: tuple) -> None:
101
105
  """
102
106
  Parse user input components into class attributes
@@ -153,6 +157,7 @@ class VectorField:
153
157
  for j in range(other.shape[1])]
154
158
  for k in verbose_bar(range(len(other)), self.verbose, desc="constructing B...")])
155
159
  return sum(A * B, axis=2)
160
+
156
161
  def cross(self, other: Self, k:int) -> NDArray:
157
162
  if type(other)==VectorField:
158
163
  assert self.ndims==3, "only 3D vector fields can be crossed at this time"
@@ -162,11 +167,13 @@ class VectorField:
162
167
  self.z[k]*other.x[k] - self.x[k]*other.z[k],
163
168
  self.x[k]*other.y[k] - self.y[k]*other.x[k]
164
169
  ])
170
+
165
171
  @cached_property
166
172
  def potential(self) -> NDArray:
167
173
  match len(self.x.shape):
168
174
  case 2:
169
175
  return array([Az(self.x[i], self.y[i], dx=self.dx, dy=self.dy) for i in range(len(self))])
176
+
170
177
  def calc_perp(self, item=None) -> NDArray:
171
178
  if not item:
172
179
  self.perp = array([
@@ -185,6 +192,7 @@ class VectorField:
185
192
  ]
186
193
  self.perp = array([hypot(self.perpendicular[0][j], self.perpendicular[1][j]) for j in item_iters])
187
194
  else: raise TypeError(f"calc_perp only takes ints, slices, or None for item, not {type(item)}-type objects")
195
+
188
196
  def set_parallel(self, component:str) -> None:
189
197
  match component.lower():
190
198
  case 'x':
@@ -196,6 +204,7 @@ class VectorField:
196
204
  case 'z':
197
205
  self.parallel = None if not hasattr(self, 'z') else self.z
198
206
  self.perpendicular = self.x, self.y
207
+
199
208
  def movie(self, mode='mag', norm='none', cmap=default_cmap, **kwrg) -> None:
200
209
  match mode.lower():
201
210
  case 'mag'|'magnitude'|'abs':
@@ -214,6 +223,7 @@ class VectorField:
214
223
  )
215
224
  def reveal_thyself(s, **kwargs): return array([self.parallel[i] for i in range(len(self))])
216
225
  reveal_thyself(self if self.parent is None else self.parent, **kwrg)
226
+
217
227
  def quiver(
218
228
  self,
219
229
  ind: int,
@@ -225,7 +235,7 @@ class VectorField:
225
235
  transpose: bool = False,
226
236
  #everything else goes into matplotlib command
227
237
  **kwargs
228
- ) -> None:
238
+ ) -> None:
229
239
  if not ax: ax = gca()
230
240
  match x, y:
231
241
  case None, None:
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes