fvsparcs 0.1.0__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.
fvsparcs/Direct.py ADDED
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Sun Jul 7 21:57:49 2024
5
+
6
+ Python Interface for libGAIA.
7
+
8
+ @author: huettig
9
+ """
10
+
11
+ from ctypes import *
12
+ import numpy as np
13
+
14
+ class PyState(Structure):
15
+ _fields_ = [
16
+ # CONFIG Histogram
17
+ ("temperature", POINTER(c_double)),
18
+ ("pressure", POINTER(c_double)),
19
+ ("viscosity", POINTER(c_double)),
20
+ ("velocity", POINTER(c_double)),
21
+ ("position", POINTER(c_double)),
22
+ ("volume", POINTER(c_double)),
23
+ ("n_gp", c_uint32),
24
+ ("n_shells", c_uint32),
25
+ ("time", c_double),
26
+ ("last_ts", c_double),
27
+ ]
28
+
29
+ class Direct:
30
+ def __init__(self):
31
+ self.lib = CDLL("libgaia.so")
32
+ self.lib.py_iniload.argtype = [c_char_p]
33
+ self.lib.py_iniset.argtype = [c_char_p, c_char_p]
34
+ self.lib.py_doTimeStep.restype = c_double;
35
+ self.lib.py_get_state.restype = POINTER(PyState)
36
+
37
+ def init1(self):
38
+ self.lib.py_init1()
39
+
40
+ def iniLoad(self, inifile):
41
+ self.lib.py_iniload(inifile.encode("ascii"))
42
+
43
+ def iniSet(self, param, value):
44
+ self.lib.py_iniset(param.encode("ascii"), value.encode("ascii"))
45
+
46
+ def init2(self):
47
+ self.lib.py_init2()
48
+
49
+ def doTimestep(self):
50
+ return self.lib.py_doTimeStep()
51
+
52
+ # casts C++ space valarray or vector to numpy array, no copy is done.
53
+ # If you modify these arrays between TS, GAIA will react!
54
+ def getState(self):
55
+ s = self.lib.py_get_state().contents
56
+ result = {}
57
+ result["T"] = np.ctypeslib.as_array(s.temperature,shape=(s.n_gp,))
58
+ result["P"] = np.ctypeslib.as_array(s.pressure,shape=(s.n_gp,))
59
+ result["V"] = np.ctypeslib.as_array(s.viscosity,shape=(s.n_gp,))
60
+ result["v"] = np.ctypeslib.as_array(s.velocity,shape=(s.n_gp,3))
61
+ result["pos"] = np.ctypeslib.as_array(s.position,shape=(s.n_gp,3))
62
+ result["vol"] = np.ctypeslib.as_array(s.volume,shape=(s.n_gp,))
63
+ result["raw"] = s
64
+ return result
65
+
66
+
fvsparcs/Field.py ADDED
@@ -0,0 +1,257 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Nov 10 14:03:35 2015
4
+
5
+ @author: huettig
6
+ """
7
+
8
+ from numpy import *
9
+ #from .tools import *
10
+ from gaia import *
11
+
12
+ class Field:
13
+ def __init__(self, data, grid_obj):
14
+ self.raw_data = data
15
+ self.data = data.view() # Will be properly transformed
16
+ grid = self.grid = grid_obj
17
+ if data.size % grid.nCells != 0: # This is not scalar data and does not correspond to N cells. We don't know what to do here.
18
+ self.components = 0
19
+ return
20
+
21
+ self.components = int(data.size / grid.nCells)
22
+ #if (self.components > 1):
23
+ self.data = self.data.reshape([grid.nCells, self.components])
24
+
25
+ # Detect 2D data
26
+ if not grid.is3D:
27
+ try:
28
+ self.formatted_data = self.data.reshape([grid.nShells, grid.nCellsPerShell[0] , self.components])
29
+ except ValueError:
30
+ pass # Well, we tried... Probably not a projected grid.
31
+ else:
32
+ # Detect cube
33
+ try:
34
+ self.formatted_data = self.data.reshape([grid.nShells, int(sqrt(grid.nCellsPerShell[0])), int(sqrt(grid.nCellsPerShell[0])), self.components])
35
+ except ValueError:
36
+ pass # Well, we tried... Probably not a projected grid.
37
+ #self.data = self.data.squeeze() # Remove single-dimensional array (if elements=1)
38
+
39
+ def getShellData(self, shell_no, boundary_excluded = False):
40
+ if self.grid.is3D and (self.grid.type == "REG" or self.grid.type == "BOX"):
41
+ shape = self.formatted_data.shape
42
+ if boundary_excluded:
43
+ return self.formatted_data[shell_no, 1:shape[1]-1, 1:shape[2]-1, :] # cuts boundary, but yields inconsistency with grid-coords. :(
44
+ else:
45
+ return self.formatted_data[shell_no, 0:shape[1], 0:shape[2], :]
46
+ ofs = self.grid.shellOffset[shell_no]
47
+ if shell_no + 1 >= self.grid.nShells:
48
+ ofs2 = self.grid.nCells
49
+ else:
50
+ ofs2 = self.grid.shellOffset[shell_no + 1]
51
+ return self.data[ofs : ofs2]
52
+
53
+ # Returns min, mean, max, always side-boundary excluded. Mean is vol-averaged.
54
+ def getShellStats(self, shell_no):
55
+ vol_field = Field(self.grid.volumes, self.grid)
56
+ has_side_boundary = self.grid.type == "REG" or self.grid.type == "BOX"
57
+ if self.grid.is3D and has_side_boundary:
58
+ shape = self.formatted_data.shape
59
+ data = self.formatted_data[shell_no, 1:shape[0]-1, 1:shape[2]-1, :] # cuts boundary, but yields inconsistency with grid-coords. :(
60
+ vol = vol_field.formatted_data[shell_no, 1:shape[0]-1, 1:shape[2]-1, :]
61
+ else:
62
+ ofs = self.grid.shellOffset[shell_no] + (1 if has_side_boundary else 0) # must be 2D case with side BCs, so +1 / -1 for ofs
63
+ if shell_no + 1 >= self.grid.nShells:
64
+ ofs2 = self.grid.nCells
65
+ else:
66
+ ofs2 = self.grid.shellOffset[shell_no + 1]
67
+ ofs2 -= 1 if has_side_boundary else 0
68
+ data = self.data[ofs : ofs2]
69
+ vol = vol_field.data[ofs : ofs2]
70
+ if len(data) == 0:
71
+ return 0,0,0
72
+
73
+ min_data = data.min()
74
+ max_data = data.max()
75
+
76
+ mean_data = ((data * vol).mean() / vol.mean()) if vol.mean() > 0 else data.mean()
77
+ return min_data, mean_data, max_data
78
+
79
+ def getProfile(self, is_T=True, component=''):
80
+ prof = zeros([self.grid.nShells, 4])
81
+ n = self.grid.nShells
82
+ field = self
83
+ if self.components > 1:
84
+ if component == '':
85
+ field = self.getMag()
86
+ else:
87
+ field = self.getComponent(component)
88
+
89
+ for shell in range(n):
90
+ if self.grid.nCellsPerShell[shell] == 0:
91
+ continue
92
+ prof[shell, 0] = self.grid.shellRadius[shell]
93
+ prof[shell, 1], prof[shell, 2], prof[shell, 3] = field.getShellStats(shell)
94
+
95
+ # Radius correction for first/last shell
96
+ if is_T:
97
+ prof[0, 0] = mean([prof[0,0], prof[1,0]])
98
+ prof[n-1, 0] = mean([prof[n-1,0], prof[n-2,0]])
99
+
100
+ return prof
101
+
102
+ def getSlice(self, axis=0, var=0.05):
103
+ pos = self.grid.coords.copy()
104
+ flt = logical_and(pos[:, axis] > (-var/2), pos[:, axis] < var) # this strange slicing range improves reg-sph.
105
+ pos_slice = pos[flt,:]
106
+ xdata = self.data.copy()
107
+ xdata[0:self.grid.shellOffset[1]] = 0
108
+ data_slice = xdata[flt,:]
109
+ result = zeros([len(pos_slice[:,0]), self.components + 2], dtype="float64")
110
+ if axis == 0:
111
+ result[:, 0] = pos_slice[:, 1]
112
+ result[:, 1] = pos_slice[:, 2]
113
+ elif axis == 1:
114
+ result[:, 0] = pos_slice[:, 0]
115
+ result[:, 1] = pos_slice[:, 2]
116
+ elif axis == 2:
117
+ result[:, 0] = pos_slice[:, 0]
118
+ result[:, 1] = pos_slice[:, 1]
119
+
120
+ result[:, 2 : self.components+2] = data_slice
121
+ return result
122
+
123
+
124
+
125
+ def getLatLon(self, shell=1):
126
+ #if (self.components != 1):
127
+ # raise Exception("Ambiguous call. Field is not scalar.")
128
+ pos = self.grid.shellCoordsSph[shell].copy()
129
+ pos[:,1] -= pi/2
130
+ pos[:,1] *= 180. / pi
131
+ pos[:,2] *= 180. / pi
132
+ data = self.getShellData(shell)
133
+ result = zeros([self.grid.nCellsPerShell[shell], self.components + 2], dtype="float64")
134
+ result[:, 0:2] = pos[:, 1:3]
135
+ result[:, 2:self.components+2] = data
136
+ return result
137
+
138
+ def getProjection(self, shell=1):
139
+ latlon = self.getLatLon(shell)
140
+ lat = latlon[:, 0] * (pi / 180)
141
+ lon = latlon[:, 1] * (pi / 180)
142
+ # Only Hammer-Aitoff
143
+ x = (2 * sqrt(2) * cos(lat) * sin(lon/2)) / sqrt(1 + cos(lat) * cos(lon / 2))
144
+ y = sqrt(2) * sin(lat) / sqrt(1 + cos(lat) * cos(lon / 2))
145
+ latlon[:, 0] = x
146
+ latlon[:, 1] = y
147
+ return latlon
148
+
149
+ def getMean(self, order=1, vol_weight=True):
150
+ if self.components != 1:
151
+ raise Exception("Only for scalar fields!")
152
+ order = float64(order)
153
+ vol = self.grid.volumes
154
+ ni = self.grid.shellOffset[1]
155
+ no = self.grid.shellOffset[self.grid.nShells - 1]
156
+ vol = vol[ni:no].copy()
157
+ v = self.data.squeeze()[ni:no]
158
+ if not vol_weight:
159
+ vol[vol > 0] = 1
160
+ r = (1./vol.sum() * (vol * v ** order).sum()) ** (1./order)
161
+ return r
162
+
163
+ # Vector specials
164
+ def getMag(self):
165
+ if self.components != 3:
166
+ raise Exception("Not a vector.")
167
+ v = self.data ** 2
168
+ return Field(sqrt(v.sum(1)), self.grid)
169
+
170
+ # Returns Field() with single component extracted
171
+ def getComponent(self, component):
172
+ if self.components == 1:
173
+ raise Exception("Single component field already")
174
+ if component in ('x','X','u','U', 0):
175
+ data = self.data[:,0]
176
+ elif component in ('y','Y', 'v', 'V' ,1):
177
+ data = self.data[:,1]
178
+ elif component in ('z','Z', 'w', 'W', 2):
179
+ data = self.data[:,2]
180
+ else:
181
+ raise Exception("Unknown component: "+str(component))
182
+ return Field(data, self.grid)
183
+
184
+ # get radial component of vector field
185
+ def getR(self):
186
+ if self.components != 3:
187
+ raise Exception("Not a vector.")
188
+ if self.grid.type == "BOX":
189
+ if self.grid.is3D:
190
+ return Field(self.data[:,2].squeeze(), self.grid)
191
+ else:
192
+ return Field(self.data[:,1].squeeze(), self.grid)
193
+
194
+ pos = self.grid.coords.copy()
195
+ # Normalize coords
196
+ pos[:,0] /= self.grid.coordsSph[:, 0]
197
+ pos[:,1] /= self.grid.coordsSph[:, 0]
198
+ pos[:,2] /= self.grid.coordsSph[:, 0]
199
+ r = (pos * self.data).sum(1) # element wise mul
200
+ return Field(r, self.grid)
201
+
202
+ # get lateral vector, NOT toroidal...
203
+ def getLateral(self):
204
+ if self.components != 3:
205
+ raise Exception("Not a vector.")
206
+ if self.grid.type == "BOX": # Does not make sense, return self
207
+ return self
208
+
209
+ pos = self.grid.coords.copy()
210
+ # Normalize coords by dividing length
211
+ pos[:,0] /= self.grid.coordsSph[:, 0]
212
+ pos[:,1] /= self.grid.coordsSph[:, 0]
213
+ pos[:,2] /= self.grid.coordsSph[:, 0]
214
+ r = pos * self.data
215
+ return Field(self.data - r, self.grid)
216
+
217
+ # create a field that has its mean value subtracted
218
+ def getResidual(self):
219
+ if self.components != 1:
220
+ raise Exception("Residuals only for single component fields.")
221
+ data = self.data.squeeze().copy()
222
+ g = self.grid
223
+ for i_shell in range(0, g.nShells):
224
+ stats_min, stats_mean, stats_max = self.getShellStats(i_shell)
225
+ data[g.shellOffset[i_shell]: g.shellOffset[i_shell+1] if i_shell < g.nShells-1 else len(data)] -= stats_mean
226
+ return Field(data, self.grid)
227
+
228
+
229
+
230
+ # shell : number of the shell to request SHs, otherwise all shells.
231
+ # lmax : max degree, -1 tries to autodetect from point distribution. This is repeated for each shell and may yield different lmax for each shell in case of spiral grid.
232
+ # Returns: spherical harmonic coefficients of the current field [n_shells:[array(2, lmax+1, lmax+1)]]
233
+ def getSphericalHarmonics(self, shell=-1, lmax=-1):
234
+ try:
235
+ import pyshtools.shtools as sht
236
+ except ImportError:
237
+ print("getSphericalHarmonics() requires pyshtools module!")
238
+ return [0]
239
+ result = []
240
+ g = self.grid
241
+ if g.type != "SPH":
242
+ print("Grid ID not SPH, not a spherical shape!")
243
+ return [0]
244
+ start_shell = 0 if shell == -1 else shell
245
+ end_shell = g.nShells if shell == -1 else start_shell + 1
246
+ for i_shell in range(start_shell, end_shell):
247
+ lat_lon_data = self.getLatLon(i_shell)
248
+ ncsh = g.nCellsPerShell[i_shell] # number of points per shells
249
+ lat_sh = lat_lon_data[:,0] # Co-latitude from GAIA is between 0 and 180, need -90 to 90
250
+ lon_sh = lat_lon_data[:,1] + 180
251
+ f = lat_lon_data[:,2]
252
+ # Spherical harmonic analysis
253
+ f_lm, chi2 = sht.SHExpandLSQ(f, lat_sh, lon_sh, lmax, norm=1, csphase=1)
254
+ result.append(f_lm) # python array is a list that allows appending different length arrays
255
+ return result
256
+
257
+
fvsparcs/Grid.py ADDED
@@ -0,0 +1,277 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Nov 10 14:03:02 2015
4
+
5
+ @author: huettig
6
+ """
7
+
8
+ from numpy import *
9
+ from .tools import *
10
+ import struct
11
+
12
+ class Face:
13
+ def __init__(self, fd = None):
14
+ if fd == None:
15
+ self.n1 = -1
16
+ self.n2 = -1
17
+ self.area = 0.
18
+ self.vvert_indices = []
19
+ else:
20
+ self.n1 = readInt(fd)
21
+ self.n2 = readInt(fd)
22
+ self.area = readDouble(fd)
23
+ vv_len = readInt(fd)
24
+ self.vvert_indices = np.zeros(vv_len, dtype=np.int32)
25
+ fd.readinto(self.vvert_indices)
26
+
27
+ def writeTo(self, fd):
28
+ #f.write(struct.pack('I', len(self.faces)))
29
+ #for face in self.faces:
30
+ fd.write(struct.pack('I', self.n1)) # N1
31
+ fd.write(struct.pack('I', self.n2)) # N2
32
+ fd.write(struct.pack('d', self.area))
33
+ fd.write(struct.pack('i', len(self.vvert_indices)))
34
+ fd.write(struct.pack('i'*len(self.vvert_indices), *self.vvert_indices))
35
+
36
+
37
+
38
+ class Grid:
39
+ """
40
+ Grid class contains information about geometry
41
+ Optional: triangulation: Read delaunay connections, full_read: vverts + faces (slow!)
42
+ """
43
+
44
+ def __init__(self, gridfile, directory='.', triangulation = False, full_read = False):
45
+ self.gridfile = gridfile
46
+ ridx = self.gridfile.rfind("/")
47
+ if ridx >= 0:
48
+ fname = self.gridfile[ridx+1:]
49
+ fpath = self.gridfile[0:ridx]
50
+ else:
51
+ fname = self.gridfile
52
+ fpath = "."
53
+ print(fname + " PATH " + fpath)
54
+ directories = [directory, "..", "../grid", "../../grid", fpath, "."]
55
+
56
+ for d in directories:
57
+ f = False
58
+ try:
59
+ f = open(d + '/' + fname, 'rb')
60
+ except:
61
+ print('Failed to open: ' + d + '/' + fname)
62
+ pass
63
+ else:
64
+ break
65
+ if (f == False):
66
+ raise Exception("Gridfile not found '" + gridfile + "' dirs: " + str(directories))
67
+ self.id = readString(f, 12)
68
+ self.is3D = self.id[3] == '3'
69
+ if (self.id[4:8] != 'GRID'):
70
+ raise Exception("Invalid grid file")
71
+ self.binary = self.id[9] == 'B'
72
+ if (not self.binary):
73
+ raise Exception("Cannot handle ASCII grids yet")
74
+ self.type = self.id[0:3]
75
+ self.version = int(self.id[10:12])
76
+ if (self.version < 4):
77
+ print("WARNING: Old grid type: " + self.version)
78
+ self.innerRadius = readDouble(f)
79
+ self.outerRadius = readDouble(f)
80
+ self.resolution = readDouble(f)
81
+ self.nShells = readInt(f)
82
+ self.nCells = 0
83
+ self.nCellsPerShell = []
84
+ self.shellOffset = []
85
+ self.shellCoords = []
86
+ self.shellCoordsSph = []
87
+ self.shellRadius = [] # or height if its a box
88
+ for i in range(self.nShells):
89
+ n_points = readInt(f)
90
+ # print("%d %d " % (i, n_points))
91
+ self.nCellsPerShell.append(n_points)
92
+ self.shellOffset.append(self.nCells)
93
+ pos = zeros([n_points, 3], dtype='float64')
94
+ f.readinto(pos)
95
+ self.shellCoords.append(pos)
96
+ self.shellCoordsSph.append(cart2sph(pos))
97
+ if self.type == "BOX":
98
+ self.shellRadius.append(pos[0,1])
99
+ else:
100
+ self.shellRadius.append(0 if n_points == 0 else cart2sph(pos)[:,0].mean())
101
+ self.nCells += n_points
102
+
103
+ #concat coords from shell array
104
+ self.coords = zeros([self.nCells, 3])
105
+ for i in range(self.nShells):
106
+ self.coords[self.shellOffset[i] : self.shellOffset[i] + self.nCellsPerShell[i],:] = self.shellCoords[i]
107
+
108
+ self.coordsSph = cart2sph(self.coords)
109
+ r = self.coordsSph[:,0]
110
+ r[r == 0] = 1
111
+ self.coordsSph[:,0] = r
112
+
113
+
114
+ n_vverts = int64(readInt(f))
115
+ if full_read:
116
+ self.vverts = zeros([n_vverts, 3], dtype='float64')
117
+ f.readinto(self.vverts)
118
+ else:
119
+ f.seek(f.tell() + n_vverts * 8 * 3)
120
+
121
+ n_surf = readInt(f)
122
+ self.surfaces = zeros(n_surf, dtype='float64')
123
+ f.readinto(self.surfaces)
124
+
125
+ n_vol = readInt(f)
126
+ self.volumes = zeros(n_vol, dtype='float64')
127
+ f.readinto(self.volumes)
128
+ self.volumes[self.volumes < 0] = 0
129
+ self.nTets = 0
130
+
131
+ if not triangulation and not full_read:
132
+ return
133
+ # read delaunay info only if requested (could be huge)
134
+
135
+ self.nTets = readUInt32(f)
136
+ self.tets = zeros(self.nTets * 4, dtype='int32')
137
+ f.readinto(self.tets)
138
+
139
+ if full_read:
140
+ self.nFaces = readUInt32(f)
141
+ print("Reading ", self.nFaces, " faces...")
142
+ self.faces = []
143
+
144
+ # 1. Read all remaining face data into memory at once.
145
+ # This completely eliminates microscopic file I/O overhead.
146
+ buffer = f.read()
147
+ offset = 0
148
+
149
+ for i in range(self.nFaces):
150
+ # Initialize an empty face using your existing `fd=None` logic
151
+ face = Face()
152
+
153
+ # 2. Parse the static headers in one C-level shot.
154
+ # '=' means standard size with no C-struct alignment padding.
155
+ # 'iidi' = int(4) + int(4) + double(8) + int(4) = 20 bytes.
156
+ face.n1, face.n2, face.area, vv_len = struct.unpack_from('=iidi', buffer, offset)
157
+ offset += 20
158
+
159
+ # 3. The magic trick: Zero-copy numpy parsing.
160
+ # Instead of allocating a new array and copying data into it,
161
+ # we just map a numpy array directly over the existing memory buffer.
162
+ face.vvert_indices = np.frombuffer(buffer, dtype=np.int32, count=vv_len, offset=offset)
163
+ offset += vv_len * 4
164
+
165
+ self.faces.append(face)
166
+
167
+ # If your file has more data to read after the faces,
168
+ # you must reset the file pointer to where the buffer parsing stopped:
169
+ # f.seek(f.tell() - len(buffer) + offset)
170
+ # finish reading
171
+
172
+ if not self.is3D:
173
+ return
174
+
175
+ # eliminate small tets
176
+ print("Small tet elimination...")
177
+ # Compute all tetrahedron volumes in one vectorized operation
178
+ cc = self.coords[self.tets] # shape (nTets*4, 3)
179
+ a = cc[0::4] - cc[3::4]
180
+ b = cc[1::4] - cc[3::4]
181
+ c = cc[2::4] - cc[3::4]
182
+ crossp = np.cross(b, c)
183
+ self.tetVolumes = np.abs((a * crossp).sum(axis=1)) / 6
184
+
185
+ # Create mask of tets to keep (volume >= threshold)
186
+ valid_mask = self.tetVolumes >= 1e-10
187
+ n_removed = (~valid_mask).sum()
188
+ removed_vol = self.tetVolumes[~valid_mask].sum()
189
+
190
+ # Filter both arrays using the mask to keep them aligned
191
+ if n_removed > 0:
192
+ self.tets = self.tets.reshape(-1, 4)[valid_mask].flatten()
193
+ self.tetVolumes = self.tetVolumes[valid_mask]
194
+ print("Removed", n_removed, "tets (combined volume", removed_vol, ") ->", len(self.tetVolumes), "remaining")
195
+ else:
196
+ print("No small tets removed")
197
+
198
+ self.tets = self.tets.astype(np.int64)
199
+
200
+
201
+ def annulus_transform(self):
202
+ if hasattr(self, "ANNULUS"):
203
+ return
204
+ # Do volume transformation here, assume grid is fully read and self.faces are present
205
+ # Only applicable to 2D SPH grids
206
+
207
+ from numpy import pi, arctan2, fmax, fmin, inf, sqrt
208
+
209
+ if self.is3D or self.type != "SPH":
210
+ print("Annulus only applicable to 2D SPH grids.")
211
+ return
212
+
213
+ # Re-initialize with full_read=True if vverts or faces don't exist
214
+ if not hasattr(self, 'vverts') or self.vverts is None or not hasattr(self, 'faces') or self.faces is None:
215
+ print("Re-reading grid with full_read=True for annulus transform...")
216
+ self.__init__(self.gridfile, directory='.', triangulation=False, full_read=True)
217
+
218
+ # Build cell -> vverts graph: each cell gets a set of all its corner vverts
219
+ cell_vverts = [set() for _ in range(self.nCells)]
220
+ for face in self.faces:
221
+ # face.n1 and n2 are the cells this face divides
222
+ if face.n1 >= 0 and face.n1 < self.nCells:
223
+ cell_vverts[face.n1].update(face.vvert_indices)
224
+ if face.n2 >= 0 and face.n2 < self.nCells:
225
+ cell_vverts[face.n2].update(face.vvert_indices)
226
+
227
+ # Compute volumes for each cell
228
+ for cell_idx in range(self.nCells):
229
+ vverts = cell_vverts[cell_idx]
230
+ if len(vverts) == 0:
231
+ continue
232
+
233
+ # Calculate min/max phi and r from vverts
234
+ min_phi = inf
235
+ max_phi = -inf
236
+ min_r = inf
237
+ max_r = -inf
238
+
239
+ for vvert_idx in vverts:
240
+ v = self.vverts[vvert_idx]
241
+ r = sqrt(v[0]**2 + v[1]**2 + v[2]**2)
242
+ phi = arctan2(v[1], v[0]) # azimuthal angle in [-pi, pi]
243
+ if phi < 0:
244
+ phi += 2 * pi # normalize to [0, 2*pi]
245
+
246
+ min_phi = fmin(min_phi, phi)
247
+ max_phi = fmax(max_phi, phi)
248
+ min_r = fmin(min_r, r)
249
+ max_r = fmax(max_r, r)
250
+
251
+ # Calculate lateral segment (angular span)
252
+ # Handle wraparound case where cell spans across 0/2π boundary
253
+ lateral_segment = max_phi - min_phi
254
+ if lateral_segment > pi:
255
+ # Cell wraps around the 0/2π boundary; actual span is the complement
256
+ lateral_segment = 2 * pi - lateral_segment
257
+
258
+ if lateral_segment < 1e-10 or (max_r - min_r) < 1e-10:
259
+ continue
260
+
261
+ # Calculate volume: V = 4/3 * pi * (max_r^3 - min_r^3) * (lateral_segment / 2*pi)
262
+ self.volumes[cell_idx] = (4./3.) * pi * (max_r**3 - min_r**3) * (lateral_segment / (2 * pi))
263
+
264
+ # Verify total volume
265
+ total_vol = self.volumes.sum()
266
+ expected_vol = (4./3.) * pi * (self.outerRadius**3 - self.innerRadius**3)
267
+ print(f"Annulus volume (3D spherical sector): {total_vol}, theoretical spherical volume: {expected_vol}")
268
+
269
+ # Finally, to avoid applying it twice:
270
+ self.ANNULUS = True
271
+ self.type = "ANN"
272
+
273
+ def get_infos(self):
274
+ print("Grid info (grid version=" + str(self.version) + "):")
275
+ print("Inner radius = %f, outer radius = %f" % (self.innerRadius, self.outerRadius))
276
+ print("nShells = %d, resolution = %f" % (self.nShells, self.resolution))
277
+ print("Gross points = %d" % self.nCells)
fvsparcs/LOReader.py ADDED
@@ -0,0 +1,60 @@
1
+ # LineOut module reader
2
+
3
+ # Examples:
4
+ # lo = LineOut("PX_LO_zhong_A1.txt")
5
+ # plot(lo.getCol("Time"), lo.getCol("Temperature mean 1"))
6
+ # plot(lo.getCol("Time"), lo.getCol("C mean 1"))
7
+ # contour(lo.getProfile("Temperature"))
8
+ # contour(lo.getProfile("Velocity Magnitude"))
9
+
10
+ import csv
11
+ import numpy as np
12
+
13
+ class LineOut:
14
+ def __init__(self, fname):
15
+ self.header = []
16
+ self.data = []
17
+ self.shells = 0
18
+ self.shell_radius = dict()
19
+ self.single_valued_columns = set()
20
+ self.profiles = set()
21
+ self.profile_start_col = dict()
22
+ with open(fname) as csvfile:
23
+ spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
24
+ for row in spamreader:
25
+ if row[0] == "#":
26
+ self.header = row[:-1]
27
+ else:
28
+ if float(row[1]) > float(self.data[-1][1]) if len(self.data) > 0 else -1:
29
+ self.data.append(row[:-1])
30
+ self.header = [x.strip() for x in self.header] # Strip first space
31
+ # If profiles are present, check how many shells
32
+ for colhdr in self.header:
33
+ if "shell" in colhdr:
34
+ shell = int(colhdr.split()[-1])
35
+ self.shells = max(self.shells, shell)
36
+ r = float(colhdr.split()[-3].split("=")[-1].split("]")[0])
37
+ self.shell_radius[shell] = r
38
+ self.profiles.add(colhdr.split()[0])
39
+ if shell == 0:
40
+ self.profile_start_col[colhdr.split()[0]] = self.header.index(colhdr)
41
+ else:
42
+ self.single_valued_columns.add(colhdr)
43
+ # Convert data array to numpy
44
+ #self.orig_data = self.data
45
+ self.data = np.array(self.data)
46
+ self.data = self.data.astype(np.float64).transpose() # Now col is on first axis
47
+ for svcname in self.single_valued_columns:
48
+ setattr(self, svcname.replace(" ", "_"), self.getCol(svcname))
49
+ for pname in self.profiles:
50
+ setattr(self, pname.replace(" ", "_"), self.getProfile(pname))
51
+
52
+
53
+ def getCol(self, name):
54
+ return self.data[self.header.index(name),:]
55
+
56
+ # Will throw if not exist, name is something like "Temperature" or "C"
57
+ def getProfile(self, name):
58
+ idx = self.profile_start_col[name]
59
+ return self.data[idx:idx + self.shells,:]
60
+