Simultipac 2.0.3__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.
simultipac/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """This library holds several modules to treat data from Simulia softwares.
2
+
3
+ In particular: CST Particle Studio and SPARK3D. It was designed for multipactor
4
+ studies.
5
+
6
+ """
7
+
8
+ import importlib.metadata
9
+
10
+ from simultipac.util.log_manager import set_up_logging
11
+
12
+ __version__ = importlib.metadata.version("simultipac")
13
+
14
+ set_up_logging("Simultipac")
@@ -0,0 +1,16 @@
1
+ """Define some constants."""
2
+
3
+ clight = 299_792_458.0
4
+ clight_in_mm_per_ns = clight * 1e-6
5
+ qelem = 1.6021766e-19
6
+
7
+ #: Associates name of variables in the library to markdown formatted strings
8
+ markdown: dict[str, str] = {
9
+ "alpha": r"$\alpha$ [ns$^{-1}$]",
10
+ "collision_angle": r"Impact angle $\theta$ [deg]",
11
+ "collision_energy": "Collision energy [eV]",
12
+ "e_acc": "$E_{acc}$ [V/m]",
13
+ "emission_energy": "Emission energy [eV]",
14
+ "population": "$n_e$",
15
+ "time": "$t$ [ns]",
16
+ }
@@ -0,0 +1 @@
1
+ """Define objects and methods to treat CST results."""
@@ -0,0 +1,161 @@
1
+ """Define helper function to load CST data."""
2
+
3
+ import logging
4
+ import os
5
+ from pathlib import Path
6
+ from pprint import pformat
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+
12
+ def get_id(folderpath: Path) -> int:
13
+ """Get the ID of the simulation stored in :file:`folderpath`.
14
+
15
+ Parameters
16
+ ----------
17
+ folderpath : Path
18
+ A :file:`mmdd-xxxxxxx` folder.
19
+
20
+ """
21
+ try:
22
+ id = int(str(folderpath).split("-")[-1])
23
+ except:
24
+ raise ValueError(
25
+ "An error occured when extracting the simulation ID of "
26
+ f"{folderpath = }. Folder name must look like: `mmdd-xxxxxxx`, "
27
+ "`xxxxxxx` beeing the simulation ID."
28
+ )
29
+ return id
30
+
31
+
32
+ def mmdd_xxxxxxx_folder_to_dict(
33
+ folderpath: Path, delimiter: str = "\t"
34
+ ) -> dict[str, Any]:
35
+ """Put all results from a CST :file:`mmdd-xxxxxxx` folder to a dict.
36
+
37
+ The expected structure should look like::
38
+
39
+ mmdd-xxxxxxx
40
+ ├── 'Adimensional e.txt'
41
+ ├── 'Adimensional h.txt'
42
+ ├── 'E_acc in MV per m.txt'
43
+ ├── Parameters.txt
44
+ ├── 'ParticleInfo [PIC]'
45
+ │ ├── 'Emitted Secondaries.txt'
46
+ │ └── 'Particle vs. Time.txt'
47
+ ├── 'TD Number of mesh cells.txt'
48
+ └── 'TD Total solver time.txt'
49
+
50
+ Corresponding output will look like:
51
+
52
+ .. code-block:: python
53
+
54
+ dic = {
55
+ 'Adimensional e': 4.2,
56
+ 'Adimensional h': 2.0,
57
+ 'E_acc in MV per m': 4.9,
58
+ 'Parameters': {'f': 1e9, 'Period': '1 / f'},
59
+ 'Emitted Secondaries': np.array([0, 2, 3]),
60
+ 'Particle vs. Time': np.array([100, 102, 105]),
61
+ 'TD Number of mesh cells': 4.2,
62
+ 'TD Total solver time': 4.2,
63
+ }
64
+
65
+ .. note::
66
+ We skip hidden files, as well as all files in a folder containing the
67
+ keyword ``"3d"``.
68
+
69
+ Parameters
70
+ ----------
71
+ folderpath : Path
72
+ Path to a :file:`mmdd-xxxxxxx` folder, holding the results of a
73
+ single simulation among a parametric simulation export.
74
+ delimiter : str, optional
75
+ Delimiter between two columns. The default is a tab character.
76
+
77
+ Returns
78
+ -------
79
+ dic : dict[str, Any]
80
+ Holds the data of the folder. The keys are the name of the files. It
81
+ will look like:
82
+
83
+ """
84
+ dic = {}
85
+
86
+ logging.debug(f"Starting exploration of {folderpath = }")
87
+ for root, _, files in os.walk(folderpath):
88
+ if os.path.split(root)[-1] == "3d":
89
+ logging.info(
90
+ f"Files in {root} were skipped because 3D files are not "
91
+ "supported yet."
92
+ )
93
+ logging.debug(f"List of skipped files:\n{pformat(files)}")
94
+ continue
95
+
96
+ for file in files:
97
+ full_path = Path(root, file)
98
+ file = full_path.stem
99
+
100
+ if file[0] == ".":
101
+ logging.debug(f"Skipped {file} because is is hidden.")
102
+ continue
103
+
104
+ if file == "Parameters":
105
+ dic[file] = _parameters_file_to_dict(full_path)
106
+ continue
107
+ data = np.loadtxt(full_path, delimiter=delimiter)
108
+
109
+ if data.shape == ():
110
+ data = float(data)
111
+ dic[file] = data
112
+
113
+ return dic
114
+
115
+
116
+ def _parameters_file_to_dict(filepath: Path) -> dict[str, float | str]:
117
+ """Put the :file:`Parameters.txt` content in a dictionary.
118
+
119
+ .. todo::
120
+ Detect integer values.
121
+
122
+ .. todo::
123
+ Evaluate simple expressions. A parameter defined as '1/2' will be a
124
+ string instead of 0.5 (float)...
125
+
126
+ Parameters
127
+ ----------
128
+ filepath : Path
129
+ Path to the file.
130
+
131
+ Returns
132
+ -------
133
+ parameters : dict[str, float | str]
134
+ Holds the name of the Parameter as a key, and the corresponding value
135
+ as a value.
136
+
137
+ """
138
+ parameters = {}
139
+ with open(filepath) as file:
140
+ for line in file:
141
+ if not line.strip():
142
+ continue
143
+ line = line.split("=")
144
+ parameters[line[0]] = line[1].strip()
145
+
146
+ for key, val in parameters.items():
147
+ try:
148
+ parameters[key] = float(val)
149
+ except ValueError:
150
+ logging.debug(
151
+ f"Could not convert {val = } from {key = } to float. Don't "
152
+ "worry."
153
+ )
154
+ continue
155
+
156
+ return parameters
157
+
158
+
159
+ def no_extension(filename: str) -> str:
160
+ """Remove extension from string corresponding to filename."""
161
+ return os.path.splitext(filename)[0]
@@ -0,0 +1,469 @@
1
+ """Define an object to store CST simulation results.
2
+
3
+ .. note::
4
+ As for now, it can only load data stored in a single file. For Position
5
+ Monitor exports (one file = one time step), see dedicated package
6
+ ``PositionMonitor``.
7
+
8
+ .. todo::
9
+ Evaluate expressions such as ``param2 = 2 * param1``
10
+
11
+ .. todo::
12
+ Allow to have P_rms instead of E_acc; E_acc does not make a lot of sense in
13
+ a lot of cases.
14
+
15
+ """
16
+
17
+ import logging
18
+ from collections.abc import Sequence
19
+ from pathlib import Path
20
+ from pprint import pformat
21
+ from typing import Any
22
+
23
+ import numpy as np
24
+
25
+ from simultipac.cst.helper import (
26
+ get_id,
27
+ mmdd_xxxxxxx_folder_to_dict,
28
+ no_extension,
29
+ )
30
+ from simultipac.particle_monitor.particle_monitor import (
31
+ FILTER_FUNC,
32
+ FILTER_KEY,
33
+ ParticleMonitor,
34
+ )
35
+ from simultipac.plotter.default import DefaultPlotter
36
+ from simultipac.plotter.plotter import Plotter
37
+ from simultipac.simulation_results.simulation_results import (
38
+ SimulationResults,
39
+ SimulationResultsFactory,
40
+ )
41
+ from simultipac.types import PARTICLE_0D_t, PARTICLE_3D_t
42
+
43
+
44
+ class MissingFileError(Exception):
45
+ """Error raised when a mandatory CST file was not found."""
46
+
47
+
48
+ class CSTResults(SimulationResults):
49
+ """Store a single CST simulation results."""
50
+
51
+ def __init__(
52
+ self,
53
+ id: int,
54
+ e_acc: float,
55
+ time: np.ndarray,
56
+ population: np.ndarray,
57
+ p_rms: float | None = None,
58
+ plotter: Plotter | None = None,
59
+ trim_trailing: bool = False,
60
+ period: float | None = None,
61
+ parameters: dict[str, float | bool | str] | None = None,
62
+ stl_alpha: float | None = None,
63
+ particle_monitor: ParticleMonitor | None = None,
64
+ **kwargs,
65
+ ) -> None:
66
+ """Instantiate, post-process.
67
+
68
+ Parameters
69
+ ----------
70
+ id :
71
+ Unique simulation identifier.
72
+ e_acc :
73
+ Accelerating field in :unit:`V/m`.
74
+ time :
75
+ Time in :unit:`ns`.
76
+ population :
77
+ Evolution of population with time. Same shape as ``time``.
78
+ p_rms :
79
+ RMS power in :unit:`W`.
80
+ plotter :
81
+ An object allowing to plot data.
82
+ trim_trailing :
83
+ To remove the last simulation points, when the population is 0.
84
+ Used with SPARK3D (``CSV`` import) for consistency with CST.
85
+ period :
86
+ RF period in :unit:`ns`. Mandatory for exponential growth fits.
87
+ parameters :
88
+ Additional information on the simulation. Typically, value of
89
+ magnetic field, number of PIC cells, simulation flags...
90
+ stl_path :
91
+ Path to the ``STL`` file holding the 3D structure of the system.
92
+ If given, we automatically load it.
93
+ stl_alpha :
94
+ Transparency for the 3D mesh.
95
+ particle_monitor :
96
+ Stores all particle monitor data.
97
+
98
+ """
99
+ super().__init__(
100
+ id=id,
101
+ e_acc=e_acc,
102
+ time=time,
103
+ population=population,
104
+ p_rms=p_rms,
105
+ plotter=plotter,
106
+ trim_trailing=trim_trailing,
107
+ period=period,
108
+ parameters=parameters,
109
+ stl_alpha=stl_alpha,
110
+ **kwargs,
111
+ )
112
+ self._particle_monitor: ParticleMonitor
113
+ if particle_monitor is not None:
114
+ self._particle_monitor = particle_monitor
115
+
116
+ def hist(
117
+ self,
118
+ x: PARTICLE_0D_t,
119
+ bins: int = 200,
120
+ hist_range: tuple[float, float] | None = None,
121
+ plotter: Plotter | None = None,
122
+ filter: FILTER_KEY | FILTER_FUNC | None = None,
123
+ **kwargs,
124
+ ) -> Any:
125
+ """Create a histogram.
126
+
127
+ Parameters
128
+ ----------
129
+ x :
130
+ Name of the data to plot.
131
+ bins :
132
+ Number of histogram bins.
133
+ hist_range :
134
+ Lower and upper value for the histogram.
135
+ plotter :
136
+ Object creating the plots.
137
+ filter :
138
+ To plot only some of the particles.
139
+
140
+ """
141
+ return self._particle_monitor.hist(
142
+ x=x,
143
+ bins=bins,
144
+ hist_range=hist_range,
145
+ plotter=plotter,
146
+ filter=filter,
147
+ **kwargs,
148
+ )
149
+
150
+ def plot_3d(self, key: PARTICLE_3D_t, **kwargs) -> Any:
151
+ if key == "trajectory":
152
+ return self.plot_trajectories(**kwargs)
153
+
154
+ def plot_trajectories(
155
+ self,
156
+ emission_color: str | None = None,
157
+ collision_color: str | None = None,
158
+ lw: int = 7,
159
+ r: int = 8,
160
+ plotter: Plotter | None = None,
161
+ filter: FILTER_KEY | FILTER_FUNC | None = None,
162
+ **kwargs,
163
+ ) -> Any:
164
+ """Plot trajectories in 3D.
165
+
166
+ Parameters
167
+ ----------
168
+ emission_color :
169
+ If provided, the first known position is colored with this color.
170
+ collision_color :
171
+ If provided, the last known position is colored with this color.
172
+ collision_point :
173
+ If provided and ``collision_color`` is not ``None``, we plot this
174
+ point instead of the last of ``points``. This is useful when the
175
+ extrapolated time is large, and actuel collision point may differ
176
+ significantly from last position points.
177
+ lw :
178
+ Trajectory line width.
179
+ r :
180
+ Size of the emission/collision points.
181
+ plotter :
182
+ An object allowing to plot data.
183
+ filter :
184
+ To select the particles to be plotted.
185
+
186
+ """
187
+ return self._particle_monitor.plot_trajectories(
188
+ emission_color=emission_color,
189
+ collision_color=collision_color,
190
+ lw=lw,
191
+ r=r,
192
+ plotter=plotter,
193
+ filter=filter,
194
+ **kwargs,
195
+ )
196
+
197
+ def plot_mesh(self, *args, **kwargs) -> Any:
198
+ """Plot the stored mesh."""
199
+ return self._particle_monitor.plot_mesh(*args, **kwargs)
200
+
201
+ def plot_trajectories(
202
+ self,
203
+ emission_color: str | None = None,
204
+ collision_color: str | None = None,
205
+ lw: int = 7,
206
+ r: int = 8,
207
+ plotter: Plotter | None = None,
208
+ filter: FILTER_KEY | FILTER_FUNC | None = None,
209
+ **kwargs,
210
+ ) -> Any:
211
+ """Plot trajectories in 3D.
212
+
213
+ Parameters
214
+ ----------
215
+ emission_color :
216
+ If provided, the first known position is colored with this color.
217
+ collision_color :
218
+ If provided, the last known position is colored with this color.
219
+ collision_point :
220
+ If provided and ``collision_color`` is not ``None``, we plot this
221
+ point instead of the last of ``points``. This is useful when the
222
+ extrapolated time is large, and actuel collision point may differ
223
+ significantly from last position points.
224
+ lw :
225
+ Trajectory line width.
226
+ r :
227
+ Size of the emission/collision points.
228
+ plotter :
229
+ An object allowing to plot data.
230
+ filter :
231
+ To select the particles to be plotted.
232
+
233
+ """
234
+ return self._particle_monitor.plot_trajectories(
235
+ emission_color=emission_color,
236
+ collision_color=collision_color,
237
+ lw=lw,
238
+ r=r,
239
+ plotter=plotter,
240
+ filter=filter,
241
+ **kwargs,
242
+ )
243
+
244
+
245
+ class CSTResultsFactory(SimulationResultsFactory):
246
+ """Define an object to easily instantiate :class:`.CSTResults`."""
247
+
248
+ _parameters_file = "Parameters.txt"
249
+ _time_population_file = "Particle vs. Time.txt"
250
+
251
+ def __init__(
252
+ self,
253
+ *args,
254
+ plotter: Plotter | None = None,
255
+ freq_ghz: float | None = None,
256
+ e_acc_parameter: Sequence[str] = (
257
+ "E_acc",
258
+ "e_acc",
259
+ "accelerating_field",
260
+ ),
261
+ e_acc_file_mv_m: str = "E_acc in MV per m.txt",
262
+ p_rms_file: str | None = None,
263
+ stl_path: Path | str | None = None,
264
+ stl_alpha: float | None = None,
265
+ **kwargs,
266
+ ) -> None:
267
+ """Instantiate object.
268
+
269
+ If necessary, override default ``e_acc`` filename.
270
+
271
+ Parameters
272
+ ----------
273
+ plotter :
274
+ Object to plot data.
275
+ freq_ghz :
276
+ RF frequency in GHz. Used to compute RF period, which is mandatory
277
+ for exp growth fitting.
278
+ e_acc_parameter :
279
+ The possible names of the accelerating field in
280
+ :file:`Parameters.txt`; we try all of them sequentially, and resort
281
+ to taking it from a file if it was not successful. You can pass in
282
+ an empty tuple to force the use of the file.
283
+ e_acc_file_mv_m :
284
+ Name of the file where the value of the accelerating field in
285
+ :unit:`MV/m` is written. This is a fallback, we prefer getting
286
+ accelerating field from the :file:`Parameters.txt` file.
287
+ e_acc_file :
288
+ Name of the file where the value of the RMS power in W is written.
289
+ If not provided, we do not load RMS power.
290
+ stl_path :
291
+ Path to the `STL` file describing the geometry. Used by
292
+ :class:`.ParticleMonitor` to compute emission and collision angles,
293
+ and realize 3D plots.
294
+ stl_alpha :
295
+ Transparency for the 3D mesh.
296
+
297
+ """
298
+ if plotter is None:
299
+ plotter = DefaultPlotter()
300
+ self._e_acc_parameter = e_acc_parameter
301
+ self._e_acc_file_mv_m = e_acc_file_mv_m
302
+ self._p_rms_file = p_rms_file
303
+ return super().__init__(
304
+ *args,
305
+ plotter=plotter,
306
+ freq_ghz=freq_ghz,
307
+ stl_path=stl_path,
308
+ stl_alpha=stl_alpha,
309
+ **kwargs,
310
+ )
311
+
312
+ @property
313
+ def mandatory_files(self) -> set[str]:
314
+ """Give the name of the mandatory files."""
315
+ mandatory = {self._parameters_file, self._time_population_file}
316
+ if len(self._e_acc_parameter) == 0:
317
+ mandatory.add(self._e_acc_file_mv_m)
318
+ return mandatory
319
+
320
+ def from_simulation_folder(
321
+ self,
322
+ folderpath: Path,
323
+ delimiter: str = "\t",
324
+ folder_particle_monitor: str | Path | None = None,
325
+ load_first_n_particles: int | None = None,
326
+ ) -> CSTResults:
327
+ """Instantiate results from a :file:`mmdd-xxxxxxx` folder.
328
+
329
+ The expected structure is the following::
330
+
331
+ mmdd-xxxxxxx
332
+ ├── 'Adimensional e.txt'
333
+ ├── 'Adimensional h.txt'
334
+ ├── 'E_acc in MV per m.txt' # Mandatory if E_acc not in :file:`Parameters.txt`
335
+ ├── Parameters.txt # Mandatory
336
+ ├── 'ParticleInfo [PIC]'
337
+ │ ├── 'Emitted Secondaries.txt'
338
+ │ └── 'Particle vs. Time.txt' # Mandatory
339
+ ├── 'TD Number of mesh cells.txt'
340
+ └── 'TD Total solver time.txt'
341
+
342
+ Non-mandatory files data will be loaded in the ``parameters``
343
+ attribute.
344
+
345
+ If you want to load particle monitor data, you must provide
346
+ ``folder_particle_monitor`` where all particle monitors are stored.
347
+ Typical structure is::
348
+
349
+ folder_particle_monitor
350
+ ├──'position monitor 1_0.117175810039043.txt'
351
+ ├──'position monitor 1_0.156234413385391.txt'
352
+ ├──'position monitor 1_0.19529302418232.txt'
353
+ ├──'position monitor 1_0.232905015349388.txt'
354
+ ├──'position monitor 1_0.271963626146317.txt'
355
+ ├──...
356
+ └──'position monitor 1_7.81172066926956E-02.txt'
357
+
358
+ Parameters
359
+ ----------
360
+ folderpath :
361
+ Path to a :file:`mmdd-xxxxxxx` folder, holding the results of a
362
+ single simulation among a parametric simulation export.
363
+ delimiter :
364
+ Delimiter between two columns.
365
+ folder_particle_monitor :
366
+ Holds all the particle monitor files.
367
+ load_first_n_particles :
368
+ If provided, we only load the ``load_first_n_particles`` first
369
+ particles. Useful for debugging/speeding up.
370
+
371
+ Returns
372
+ -------
373
+ results : CSTResults
374
+ Instantiated object.
375
+
376
+ """
377
+ assert folderpath.is_dir(), f"{folderpath = } does not exist."
378
+ id = get_id(folderpath)
379
+ raw_results = mmdd_xxxxxxx_folder_to_dict(folderpath, delimiter)
380
+
381
+ for filename in self.mandatory_files:
382
+ if no_extension(filename) not in raw_results:
383
+ raise MissingFileError(
384
+ f"{filename = } was not found in {folderpath}. However, I "
385
+ f"found {pformat(list(raw_results.keys()))}"
386
+ )
387
+
388
+ e_acc = self._pop_e_acc(raw_results, folderpath)
389
+ part_time = raw_results.pop(no_extension(self._time_population_file))
390
+ time, population = part_time[:, 0], part_time[:, 1]
391
+ p_rms = (
392
+ raw_results.pop(no_extension(self._p_rms_file))
393
+ if self._p_rms_file
394
+ else None
395
+ )
396
+
397
+ particle_monitor = None
398
+ if folder_particle_monitor is not None:
399
+ particle_monitor = ParticleMonitor.from_folder(
400
+ folder_particle_monitor,
401
+ plotter=self._plotter,
402
+ stl_path=self._stl_path,
403
+ stl_alpha=self._stl_alpha,
404
+ load_first_n_particles=load_first_n_particles,
405
+ )
406
+ results = CSTResults(
407
+ id=id,
408
+ e_acc=e_acc,
409
+ time=time,
410
+ population=population,
411
+ p_rms=p_rms,
412
+ plotter=self._plotter,
413
+ period=self._period,
414
+ parameters=raw_results.pop(no_extension(self._parameters_file)),
415
+ particle_monitor=particle_monitor,
416
+ )
417
+ return results
418
+
419
+ def _pop_e_acc(self, raw_results: dict[str, Any], folder: Path) -> float:
420
+ """Pop the value of the accelerating field from ``raw_results.``
421
+
422
+ First, we try to get it from the :file:`Parameters.txt` under the names
423
+ listed in ``self._e_acc_parameter``. If was not found, we look into the
424
+ ``self._e_acc_file_mv_m`` file.
425
+
426
+ """
427
+ parameters = raw_results[no_extension(self._parameters_file)]
428
+ for name in self._e_acc_parameter:
429
+ e_acc = parameters.pop(name, None)
430
+ if e_acc is not None:
431
+ logging.debug(
432
+ f"{folder}: took accelerating field from {name} in "
433
+ f"{self._parameters_file}."
434
+ )
435
+ return e_acc
436
+
437
+ if self._e_acc_file_mv_m is not None:
438
+ e_acc = raw_results.pop(no_extension(self._e_acc_file_mv_m), None)
439
+ if e_acc is not None:
440
+ logging.debug(
441
+ f"{folder}: took accelerating field from "
442
+ "{self._e_acc_file_mv_m} file. Multiplied it by 1e6."
443
+ )
444
+ return e_acc * 1e-6
445
+
446
+ raise ValueError(
447
+ f"Could not find accelerating field in {folder}. Tried to look for"
448
+ f" {self._e_acc_parameter = } key in Parameters.txt, and then for "
449
+ f"a file named {self._e_acc_file_mv_m = }"
450
+ )
451
+
452
+ def from_simulation_folders(
453
+ self,
454
+ master_folder: Path,
455
+ delimiter: str = "\t",
456
+ ) -> list[CSTResults]:
457
+ """Load all :file:`mmdd-xxxxxxx` folders in ``master_folder``.
458
+
459
+ Note
460
+ ----
461
+ Loading of :class:`.ParticleMonitor` for multiple simulations is
462
+ currently not supported.
463
+
464
+ """
465
+ folders = list(master_folder.iterdir())
466
+ return [
467
+ self.from_simulation_folder(folder, delimiter=delimiter)
468
+ for folder in folders
469
+ ]
@@ -0,0 +1,5 @@
1
+ """Define the modules to handle the :class:`.ParticleMonitor` files from CST.
2
+
3
+ Unis in CST should be :unit:`mm`, :unit:`GHz`, :unit:`ns` for consistency.
4
+
5
+ """
@@ -0,0 +1 @@
1
+ """Define utility functions to study particle-mesh collisions."""