fvsparcs 0.1.0__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.
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: fvsparcs
3
+ Version: 0.1.0
4
+ Summary: A reader for the output files of the FV-SPARCS toolkit
5
+ Author-email: Christian Huettig <christian.huettig@dlr.de>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: numpy
12
+
13
+
14
+ # This repo contains the FV-SPARCS reader module (compat with GAIAv3)
15
+
16
+ Howto use:
17
+ ```py
18
+ from fvsparcs import *
19
+ ```
20
+
21
+ ## Usecases for the module
22
+
23
+ ```py
24
+
25
+ # Check what cases are in current directory (change with os.chdir)
26
+ print(getCases())
27
+
28
+ # If you only have one run in the directory:
29
+ s = Simulation()
30
+
31
+ # For a specific case:
32
+ s = Simulation(caseid = 'bl2a')
33
+
34
+ # If the simulation is not in the current directory,
35
+ s = Simulation(caseid = 'bl2a', sim_dir = 'bl')
36
+
37
+ # Simulation will try to load the grid. The gridfile is taken from an output file.
38
+ # It searches for that file in ., ../, ../grid, ../../grid and the directory from the full path.
39
+ # If you have it somewhere else, provide that directory with:
40
+
41
+ s = Simulation(grid_dir = '/my/grid/path')
42
+
43
+ #ACCESS OUTPUT
44
+ #=============
45
+
46
+ # Get the last output:
47
+ o = s.getLast()
48
+
49
+ # Get at time:
50
+ o = s.getAtTime(0.5)
51
+
52
+ # Get at iteration:
53
+ o = s.getAtIter(2549)
54
+
55
+ # Output will load all fields and create all Field instances.
56
+
57
+ #ACCESS FIELD DATA
58
+ #=================
59
+
60
+ # Fields are named after their field ID (T,P,S,v,...)
61
+ # If output detects a vector (like v) it automatically splits it into magnitude: adds "mag"; radial component: adds "r"
62
+
63
+ # The raw array with the according positions (n = amount of cells):
64
+
65
+ pos = o.grid.coords # [n, 3] array
66
+ temperature = o.temperature.data # [n, 1] array
67
+ temperature = o.temperature.data.squeeze() # [n] array
68
+
69
+ # formatted data (only 2D BOX/CYL or 3D BOX)
70
+
71
+ temperature = o.temperature.formatted_data # [n_x, n_y] array
72
+ imshow(temperature, origin="lower")
73
+
74
+ # vector magnitude:
75
+ vel_mag = o.velocitymag.data
76
+
77
+ # Cartesian component of vector
78
+ v_x = o.velocity.data[:,0]
79
+ v_y = o.velocity.data[:,1]
80
+
81
+ # Return data for a specific shell:
82
+ temperature_shell_5 = o.temperature.getShellData(5)
83
+
84
+ # Return a profile (radial averaged)
85
+ # profile has for each shell: [[radius, min, mean, max], ... nShells]
86
+ t_prof = o.temperature.getProfile()
87
+
88
+ # Get volume averaged mean of field
89
+ mean_t = o.temperature.getMean()
90
+
91
+ # Get RMS velocity
92
+ v_rms = o.velocitymag.getMean(order=2)
93
+
94
+ #ACCESS GEOMETRY
95
+ #===============
96
+
97
+ # access grid via Simulation or Output. s.grid == o.grid (reference)
98
+ s.grid.nShells
99
+ s.grid.nCells
100
+ s.grid.coords
101
+ s.grid.coordsSph
102
+ s.grid.volumes
103
+ s.grid.innerRadius
104
+ s.grid.outerRadius
105
+ s.grid.resolution # mean distance between cells
106
+ s.grid.shellOffset
107
+ s.grid.shellCoords
108
+ s.grid.shellCoordsSph
109
+ s.grid.shellRadius # or height if its a box
110
+
111
+ Or use s.grid.get_infos() directly to get a summary of the grid properties.
112
+
113
+ #GRAPHICAL OUTPUT
114
+ #================
115
+ # Other methods are directly meant for graphic processing.
116
+ # Check out the notebooks.
117
+
118
+ #TIME SERIES
119
+ #===========
120
+
121
+ stats = s.getStats()
122
+ # See timeseries notebook on how to use
123
+
124
+ #PARAMETER STUDIES
125
+ #=================
126
+ # In case a parameter study is present in the current path just use:
127
+ ps = ParameterStudy()
128
+
129
+ # A dict with all available combinations:
130
+ ps.cases
131
+
132
+ # The entries:
133
+ ps.entries
134
+
135
+ #ADD FIELD DATA TO OUTPUT
136
+ #========================
137
+ # In case you want to add a constructed field form post-processing to an output to visualize it with ParaView:
138
+ o.addScalar("L") # creates a new scalar field containing zeros, equiv. addVector("m")
139
+ o.L.data = o.temperature.data + 1
140
+ o.save() # Overwrites original file!
141
+ o.save(filename="new_dir/" + o.filename) # ... to another file
142
+ # - Only manipulate .data, do not touch raw_data !
143
+ # - Remember convention: Uppercase == Scalar, Lowercase == Vector
144
+ # - To avoid ParaView conflicts you should add the new field to all outputs of a sim
145
+
146
+ ```
147
+ ## The Direct interface (not populated to v3 yet)
148
+ This interface is available via the GAIA module's `Direct()` class. It loads `libgaia.so` in the current directory and allows control in between time-steps. A few things to note here:
149
+ - MPI version(s) do not work yet. MUMPS or CUDA (w/OMP) works.
150
+ - When building GAIA, a `libgaia.so` is always created with the executable. This is what the Direct() class needs.
151
+ - Calling order is important here!
152
+ - First call `init1()`, this will setup the `ini` instance.
153
+ - Use any number of `iniLoad()` or `setParameter()` calls.
154
+ - Call `init2()`. This is Gaia's C++ `init()` call and will load / create Grids and prepare the Simulation.
155
+ - Now you can for the first time call `getState()`
156
+ - Call `doTimestep()`, it returns the next delta time. Zero means MaxTime is reached.
157
+ - Look at the `gaia_test.py` within the C++ code for an example
158
+ ### `getState()` and God-Mode
159
+ Be careful about the contents of the returned dictionary, ***these are references to the Simulation's raw arrays, *not* copies***!
160
+ Means you can interact with the simulation in any way. You can also throw in some `setParameter()` calls. Careful, many mods do create a copy on init and never read them again.
161
+
162
+
163
+
@@ -0,0 +1,151 @@
1
+
2
+ # This repo contains the FV-SPARCS reader module (compat with GAIAv3)
3
+
4
+ Howto use:
5
+ ```py
6
+ from fvsparcs import *
7
+ ```
8
+
9
+ ## Usecases for the module
10
+
11
+ ```py
12
+
13
+ # Check what cases are in current directory (change with os.chdir)
14
+ print(getCases())
15
+
16
+ # If you only have one run in the directory:
17
+ s = Simulation()
18
+
19
+ # For a specific case:
20
+ s = Simulation(caseid = 'bl2a')
21
+
22
+ # If the simulation is not in the current directory,
23
+ s = Simulation(caseid = 'bl2a', sim_dir = 'bl')
24
+
25
+ # Simulation will try to load the grid. The gridfile is taken from an output file.
26
+ # It searches for that file in ., ../, ../grid, ../../grid and the directory from the full path.
27
+ # If you have it somewhere else, provide that directory with:
28
+
29
+ s = Simulation(grid_dir = '/my/grid/path')
30
+
31
+ #ACCESS OUTPUT
32
+ #=============
33
+
34
+ # Get the last output:
35
+ o = s.getLast()
36
+
37
+ # Get at time:
38
+ o = s.getAtTime(0.5)
39
+
40
+ # Get at iteration:
41
+ o = s.getAtIter(2549)
42
+
43
+ # Output will load all fields and create all Field instances.
44
+
45
+ #ACCESS FIELD DATA
46
+ #=================
47
+
48
+ # Fields are named after their field ID (T,P,S,v,...)
49
+ # If output detects a vector (like v) it automatically splits it into magnitude: adds "mag"; radial component: adds "r"
50
+
51
+ # The raw array with the according positions (n = amount of cells):
52
+
53
+ pos = o.grid.coords # [n, 3] array
54
+ temperature = o.temperature.data # [n, 1] array
55
+ temperature = o.temperature.data.squeeze() # [n] array
56
+
57
+ # formatted data (only 2D BOX/CYL or 3D BOX)
58
+
59
+ temperature = o.temperature.formatted_data # [n_x, n_y] array
60
+ imshow(temperature, origin="lower")
61
+
62
+ # vector magnitude:
63
+ vel_mag = o.velocitymag.data
64
+
65
+ # Cartesian component of vector
66
+ v_x = o.velocity.data[:,0]
67
+ v_y = o.velocity.data[:,1]
68
+
69
+ # Return data for a specific shell:
70
+ temperature_shell_5 = o.temperature.getShellData(5)
71
+
72
+ # Return a profile (radial averaged)
73
+ # profile has for each shell: [[radius, min, mean, max], ... nShells]
74
+ t_prof = o.temperature.getProfile()
75
+
76
+ # Get volume averaged mean of field
77
+ mean_t = o.temperature.getMean()
78
+
79
+ # Get RMS velocity
80
+ v_rms = o.velocitymag.getMean(order=2)
81
+
82
+ #ACCESS GEOMETRY
83
+ #===============
84
+
85
+ # access grid via Simulation or Output. s.grid == o.grid (reference)
86
+ s.grid.nShells
87
+ s.grid.nCells
88
+ s.grid.coords
89
+ s.grid.coordsSph
90
+ s.grid.volumes
91
+ s.grid.innerRadius
92
+ s.grid.outerRadius
93
+ s.grid.resolution # mean distance between cells
94
+ s.grid.shellOffset
95
+ s.grid.shellCoords
96
+ s.grid.shellCoordsSph
97
+ s.grid.shellRadius # or height if its a box
98
+
99
+ Or use s.grid.get_infos() directly to get a summary of the grid properties.
100
+
101
+ #GRAPHICAL OUTPUT
102
+ #================
103
+ # Other methods are directly meant for graphic processing.
104
+ # Check out the notebooks.
105
+
106
+ #TIME SERIES
107
+ #===========
108
+
109
+ stats = s.getStats()
110
+ # See timeseries notebook on how to use
111
+
112
+ #PARAMETER STUDIES
113
+ #=================
114
+ # In case a parameter study is present in the current path just use:
115
+ ps = ParameterStudy()
116
+
117
+ # A dict with all available combinations:
118
+ ps.cases
119
+
120
+ # The entries:
121
+ ps.entries
122
+
123
+ #ADD FIELD DATA TO OUTPUT
124
+ #========================
125
+ # In case you want to add a constructed field form post-processing to an output to visualize it with ParaView:
126
+ o.addScalar("L") # creates a new scalar field containing zeros, equiv. addVector("m")
127
+ o.L.data = o.temperature.data + 1
128
+ o.save() # Overwrites original file!
129
+ o.save(filename="new_dir/" + o.filename) # ... to another file
130
+ # - Only manipulate .data, do not touch raw_data !
131
+ # - Remember convention: Uppercase == Scalar, Lowercase == Vector
132
+ # - To avoid ParaView conflicts you should add the new field to all outputs of a sim
133
+
134
+ ```
135
+ ## The Direct interface (not populated to v3 yet)
136
+ This interface is available via the GAIA module's `Direct()` class. It loads `libgaia.so` in the current directory and allows control in between time-steps. A few things to note here:
137
+ - MPI version(s) do not work yet. MUMPS or CUDA (w/OMP) works.
138
+ - When building GAIA, a `libgaia.so` is always created with the executable. This is what the Direct() class needs.
139
+ - Calling order is important here!
140
+ - First call `init1()`, this will setup the `ini` instance.
141
+ - Use any number of `iniLoad()` or `setParameter()` calls.
142
+ - Call `init2()`. This is Gaia's C++ `init()` call and will load / create Grids and prepare the Simulation.
143
+ - Now you can for the first time call `getState()`
144
+ - Call `doTimestep()`, it returns the next delta time. Zero means MaxTime is reached.
145
+ - Look at the `gaia_test.py` within the C++ code for an example
146
+ ### `getState()` and God-Mode
147
+ Be careful about the contents of the returned dictionary, ***these are references to the Simulation's raw arrays, *not* copies***!
148
+ Means you can interact with the simulation in any way. You can also throw in some `setParameter()` calls. Careful, many mods do create a copy on init and never read them again.
149
+
150
+
151
+
@@ -0,0 +1,21 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fvsparcs"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name="Christian Huettig", email="christian.huettig@dlr.de" },
10
+ ]
11
+ description = "A reader for the output files of the FV-SPARCS toolkit"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = [
20
+ "numpy"
21
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+
@@ -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
+