pion-reader 2.0.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.
pion_reader/util.py ADDED
@@ -0,0 +1,250 @@
1
+ from .SiloHeader_data import OpenData
2
+ from .ReadData import ReadData
3
+ import astropy.units as unit
4
+ import os
5
+ import glob
6
+ import re
7
+ import warnings
8
+
9
+
10
+ def exit_with_error(message):
11
+ """Stop with an error (raises RuntimeError)."""
12
+ raise RuntimeError(message)
13
+
14
+
15
+ def warning(message):
16
+ """Print a warning (Python's warnings module)."""
17
+ warnings.warn(message, stacklevel=2)
18
+
19
+
20
+ ######################################################################################
21
+ # batch silo files
22
+ ######################################################################################
23
+ def batch_silos(dir,
24
+ filebase,
25
+ start_time=None,
26
+ finish_time=None,
27
+ time_unit=None,
28
+ out_frequency=None):
29
+ '''
30
+ Organizes silo files into groups based on their corresponding time instants.
31
+ This function scans a specified directory for silo files with a given base name,
32
+ and if the simulation involves multiple grid levels, it groups the files by time instant.
33
+ For each time instant, it creates a sublist containing silo files from different grid levels.
34
+
35
+ The function allows running from a particular start time to a finish time, enabling users to
36
+ process specific intervals of simulation data. Additionally, one can restart the processing
37
+ by adjusting the start time, making it flexible for iterative analysis or simulations.
38
+
39
+ :param dir: Directory path where the silo files are located.
40
+ :param filebase: Base name of the silo files to search for.
41
+ :param start_time: The start time for processing, in the given time_unit.
42
+ :param finish_time: The finish time for processing, in the given time_unit.
43
+ :param time_unit: The time unit for start_time and finish_time ('sec', 'yr', or 'kyr').
44
+ :return: A list of lists, where each sublist contains silo files for a specific time instant,
45
+ with each file in the sublist representing a different grid level.
46
+ :raises: RuntimeError if no silo files are found or if expected files for certain levels are missing.
47
+ '''
48
+ conversion_factors = {'kyr': 3.154e+10, 'yr': 3.154e+7, 'sec': 1}
49
+
50
+ inverse_conversion_factors = {
51
+ 'kyr': 1 / 3.154e+10,
52
+ 'yr': 1 / 3.154e+7,
53
+ 'sec': 1
54
+ }
55
+
56
+ # Convert start_time and finish_time to seconds based on time_unit
57
+ factor = conversion_factors.get(
58
+ time_unit, 1) # Default to 1 if time_unit is None or unrecognized
59
+ start_time_sec = start_time * factor if start_time is not None else None
60
+ finish_time_sec = finish_time * factor if finish_time is not None else None
61
+
62
+ print(" ---------------------------")
63
+ print(" batching silo files into time instances:")
64
+ print(f" starting time: {start_time} {time_unit}")
65
+ print(f" finishing time: {finish_time} {time_unit}")
66
+ print(f" output frequency: {out_frequency}")
67
+
68
+ # Construct search pattern for silo files
69
+ search_pattern = os.path.join(dir, f"{filebase}_*.silo")
70
+ all_silos = glob.glob(search_pattern)
71
+
72
+ if not all_silos:
73
+ exit_with_error(f"no '{filebase}' silo files found in '{dir}'")
74
+
75
+ # Assume the number of grid levels; this may need to be adjusted based on actual usage
76
+ # Open header data
77
+ header_data = OpenData(all_silos)
78
+ # Set the directory to '/header'
79
+ header_data.db.SetDir('/header')
80
+ # Retrieve what coordinate system is used
81
+ coord_sys = header_data.db.GetVar("coord_sys")
82
+ # Retrieve no of nested grid levels
83
+ Nlevels = header_data.db.GetVar("grid_nlevels")
84
+ # close the object
85
+ header_data.close()
86
+ # set number of time instance
87
+ Ninstances = 0
88
+
89
+ # for uniform grid *********************************************************************
90
+ if Nlevels == 1:
91
+ print(f" grid: uniform")
92
+ # only the first file (PMPIO group 0) of each snapshot
93
+ group = re.compile(r'_(\d{4})\.\d+\.silo$')
94
+ silos = sorted(
95
+ f for f in all_silos
96
+ if not group.search(f) or group.search(f).group(1) == '0000')
97
+ batched_silos = [[silo] for silo in silos]
98
+ selected_silos = []
99
+ for i, silo in enumerate(batched_silos):
100
+ data = ReadData(silo)
101
+ basic = data.get_1Darray('Density')
102
+ sim_time = (basic['sim_time'] * unit.s).value
103
+ data.close()
104
+
105
+ if (start_time_sec is not None and sim_time < start_time_sec) or \
106
+ (finish_time_sec is not None and sim_time > finish_time_sec):
107
+ continue # Skip this silo if it doesn't meet the criteria
108
+ selected_silos.append(silo)
109
+
110
+ batched_silos = selected_silos
111
+ # Keep files based on the output frequency if specified
112
+ if out_frequency is not None:
113
+ Ninstances = len(batched_silos)
114
+ # indices to keep: multiples of out_freq, plus the first and last index
115
+ #indices_to_keep = sorted(set(range(0, Ninstances, out_frequency)) | {0, Ninstances - 1})
116
+ indices_to_keep = sorted(set(range(0, Ninstances, out_frequency)))
117
+ batched_silos = [batched_silos[i] for i in indices_to_keep]
118
+
119
+ Ninstances = len(batched_silos)
120
+ print(
121
+ f" {Ninstances} time instances between {start_time} {time_unit} and {finish_time} {time_unit}"
122
+ )
123
+ print(" batching completed")
124
+ return batched_silos
125
+
126
+ # for nested grid *********************************************************************
127
+ else:
128
+ print(f" grid: nested with {Nlevels} levels")
129
+ # Pattern to match level 00 files
130
+ pattern = re.compile(r'_level00_0000\.\d+\.silo$')
131
+ # Find and sort level 00 files, one per time instant
132
+ level00_instants = [file for file in all_silos if pattern.search(file)]
133
+ # Snapshots with all levels in one set of files (PION since
134
+ # 3.0.0-dev.2): the _0000 file of each snapshot.
135
+ single_file = not level00_instants
136
+ if single_file:
137
+ pattern = re.compile(r'_0000\.\d+\.silo$')
138
+ level00_instants = [
139
+ file for file in all_silos if pattern.search(file)
140
+ and '_level' not in os.path.basename(file)
141
+ ]
142
+ batched_silos = [[file] for file in sorted(level00_instants)]
143
+
144
+ # check if level 00 batched silos are within the asked time range
145
+ selected_silos = []
146
+ for i, silo in enumerate(batched_silos):
147
+ data = ReadData(silo)
148
+ if coord_sys == 3:
149
+ basic = data.get_1Darray('Density')
150
+ elif coord_sys == 2:
151
+ basic = data.get_2Darray('Density')
152
+ elif coord_sys == 1:
153
+ basic = data.get_3Darray('Density')
154
+ sim_time = (basic['sim_time'] * unit.s).value
155
+ data.close()
156
+
157
+ if (start_time_sec is not None and sim_time < start_time_sec) or \
158
+ (finish_time_sec is not None and sim_time > finish_time_sec):
159
+ continue # Skip this silo if it doesn't meet the criteria
160
+ selected_silos.append(silo)
161
+
162
+ batched_silos = selected_silos
163
+
164
+ # Keep files based on the output frequency if specified
165
+ if out_frequency is not None:
166
+ Ninstances = len(batched_silos)
167
+ # indices to keep: multiples of out_freq, plus the first and last index
168
+ indices_to_keep = sorted(
169
+ set(range(0, Ninstances, out_frequency)) | {0, Ninstances - 1})
170
+ batched_silos = [batched_silos[i] for i in indices_to_keep]
171
+
172
+ # appending other level silos to corresponding time instant (old
173
+ # layout, one file per level)
174
+ for i, instant in enumerate([] if single_file else batched_silos):
175
+ # Extract the time instant from the level 00 file
176
+ file_name = instant[0].split('/')[-1]
177
+ instant_extension = file_name.split('_')[-1].replace('.silo', '')
178
+
179
+ # Find and append silo files for the same time instant across other levels
180
+ for level in range(1, Nlevels):
181
+ level_pattern = re.compile(
182
+ f'level{str(level).zfill(2)}_{instant_extension}.silo')
183
+
184
+ # Find the file for the current level
185
+ level_instant_file = next(
186
+ (file for file in all_silos if level_pattern.search(file)),
187
+ None)
188
+
189
+ if level_instant_file is None:
190
+ (f"missing silo file for level {level} instant {instant_extension}"
191
+ )
192
+ else:
193
+ # Append the found file to the corresponding time instant group
194
+ batched_silos[i].append(level_instant_file)
195
+
196
+ # common to both uniform and nested grid
197
+ if start_time is None:
198
+ data = ReadData(batched_silos[0])
199
+ if coord_sys == 3:
200
+ basic = data.get_1Darray('Density')
201
+ elif coord_sys == 2:
202
+ basic = data.get_2Darray('Density')
203
+ elif coord_sys == 1:
204
+ basic = data.get_3Darray('Density')
205
+ sim_time = (basic['sim_time'] * unit.s).value
206
+ data.close()
207
+ start_time = sim_time * inverse_conversion_factors.get(
208
+ time_unit, 1)
209
+
210
+ if finish_time is None:
211
+ data = ReadData(batched_silos[-1])
212
+ if coord_sys == 3:
213
+ basic = data.get_1Darray('Density')
214
+ elif coord_sys == 2:
215
+ basic = data.get_2Darray('Density')
216
+ elif coord_sys == 1:
217
+ basic = data.get_3Darray('Density')
218
+ sim_time = (basic['sim_time'] * unit.s).value
219
+ data.close()
220
+ finish_time = sim_time * inverse_conversion_factors.get(
221
+ time_unit, 1)
222
+
223
+ if finish_time is not None:
224
+ data = ReadData(batched_silos[-1])
225
+ if coord_sys == 3:
226
+ basic = data.get_1Darray('Density')
227
+ elif coord_sys == 2:
228
+ basic = data.get_2Darray('Density')
229
+ elif coord_sys == 1:
230
+ basic = data.get_3Darray('Density')
231
+ sim_walltime_sec = (basic['sim_time'] * unit.s).value
232
+ data.close()
233
+ #finish_time_sec = finish_time * conversion_factors.get(time_unit, 1)
234
+ if finish_time_sec > sim_walltime_sec:
235
+ sim_walltime = sim_walltime_sec * inverse_conversion_factors.get(
236
+ time_unit, 1)
237
+ warning(
238
+ f"specified finish time {float(finish_time):.3f} {time_unit} exceeds the simulation"
239
+ f" walltime {float(sim_walltime):.3f} {time_unit}")
240
+
241
+ Ninstances = len(batched_silos)
242
+ print(
243
+ f" {Ninstances} time instances between {start_time:.3f} {time_unit} and {finish_time:.3f} {time_unit}"
244
+ )
245
+ print(" silo batching completed")
246
+ if not batched_silos:
247
+ exit_with_error(
248
+ 'no silo files found in the specified time range, check your selection criteria'
249
+ )
250
+ return batched_silos
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.4
2
+ Name: pion-reader
3
+ Version: 2.0.0
4
+ Summary: Read and plot the Silo snapshot files of the PION (radiation-)MHD code
5
+ Author: Sam Green, Jonathan Mackey, Arun Mathew
6
+ License-Expression: BSD-3-Clause
7
+ Project-URL: Homepage, https://github.com/jmackey-astro/PyPion-dev
8
+ Project-URL: Documentation, https://pion-docs-dev.readthedocs.io/en/latest/python.html
9
+ Project-URL: Issues, https://github.com/jmackey-astro/PyPion-dev/issues
10
+ Keywords: pion,pypion,silo,visualisation,computational fluid dynamics
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE.md
17
+ Requires-Dist: numpy
18
+ Requires-Dist: astropy
19
+ Requires-Dist: matplotlib
20
+ Provides-Extra: yt
21
+ Requires-Dist: yt>=4.4.0; extra == "yt"
22
+ Dynamic: license-file
23
+
24
+ # pion-reader: Python library for PION
25
+
26
+ Reads and plots the Silo snapshot files written by
27
+ [PION](https://gitlab.git.nrw/jmackey1/pion-dev), on uniform and nested
28
+ grids in 1D, 2D and 3D: both the current layout (all levels of a snapshot
29
+ in one set of files, PION 3.0.0-dev.2 and later) and the older one (one file
30
+ per level). It continues PyPion (Sam Green et al.; the `pypion` package on
31
+ PyPI), with the module renamed from `pypion` to `pion_reader`.
32
+
33
+ The source is in `src/pion_reader`, example plotting scripts are in
34
+ `examples/`, and `tests/` reads PION snapshots of both layouts
35
+ (`pytest tests`).
36
+
37
+ # Installation
38
+
39
+ ```
40
+ python3 -m pip install pion-reader # or "pion-reader[yt]" with yt
41
+ ```
42
+
43
+ ```python
44
+ from pion_reader.ReadData import ReadData
45
+ data = ReadData("MyRun_0000.00000100.silo") # all levels of a snapshot
46
+ rho = data.get_2Darray("Density") # one array per level
47
+ ```
48
+
49
+ Scripts written for PyPion only need `pypion` replaced by `pion_reader` in
50
+ their imports.
51
+
52
+ The Silo Python module is installed separately: see the
53
+ [PION documentation](https://pion-docs-dev.readthedocs.io/en/latest/python.html)
54
+ (or the script in `src/silo/` of this repository).
55
+
56
+ # Documentation
57
+
58
+ Usage: https://pion-docs-dev.readthedocs.io/en/latest/python.html
59
+
60
+ Developers: see `doc/dev.md`; format the code with `tools/format.sh`
61
+ (yapf) before committing.
62
+
63
+ # Developers/Maintainers
64
+
65
+ * Samuel Green
66
+ * Jonathan Mackey
67
+ * Arun Mathew
@@ -0,0 +1,14 @@
1
+ pion_reader/Plotting_Classes.py,sha256=UNUn1khIxAo4kAqSzYHfq23OL9g51q6cwpl9sEB-KqM,10465
2
+ pion_reader/ReadData.py,sha256=asI9WvbuxmW2el_X_9PYoq-VyhVc7fL13JBdp6WpVyk,7268
3
+ pion_reader/SiloHeader_data.py,sha256=Fto16kwWIl9TodqqcJzj2PyQtFAt7_EzPxzWhT9upTg,9803
4
+ pion_reader/__init__.py,sha256=QsKskFYjEKTciZ9ORK9Ko4eUPseDV-a3_vMDZQx7n0E,127
5
+ pion_reader/derived_fields_yt.py,sha256=obvA9xike8VKgB2DcBX9I3Njq6XT1wpnNJPOlXWu7Jw,28394
6
+ pion_reader/example_plots_yt.py,sha256=bcUWtmU2G9iMEgBuyIR_F25-CECjT6JE90pXvce9N7g,41172
7
+ pion_reader/microphysics.py,sha256=oFE2jcnMe5p44yIJyXIkQhQ4-GPQNYuKfiGRY12Go24,10192
8
+ pion_reader/pion2yt.py,sha256=desVBKdxy56TapVRkVrOZ__noqzwitq01vuOEAtAWUM,20306
9
+ pion_reader/util.py,sha256=_lJdwRoKJuKtZDU68MM6_mhYgX875F4ceiegruQfaug,11044
10
+ pion_reader-2.0.0.dist-info/licenses/LICENSE.md,sha256=MnMNRZbISz4a1RlqXzPqJ3PwkrQLuIEEqm8GUcdfqnI,1519
11
+ pion_reader-2.0.0.dist-info/METADATA,sha256=MykjD2SiZ0WuGGehA5DyELddjd-HIJwKokh1IaVN_CE,2341
12
+ pion_reader-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
13
+ pion_reader-2.0.0.dist-info/top_level.txt,sha256=m9B_yGhHw7jOKoofsb5z8ukTuTcShW9-VDiJ8NpzQPQ,12
14
+ pion_reader-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2020, Samuel Green
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ pion_reader