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.
@@ -0,0 +1,178 @@
1
+ """Define the generic :class:`Plotter`."""
2
+
3
+ from abc import abstractmethod
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from numpy.typing import NDArray
10
+
11
+ from simultipac.types import PARTICLE_0D_t, PARTICLE_3D_t
12
+
13
+
14
+ class Plotter:
15
+ """An object used to plot data."""
16
+
17
+ def __init__(self, *args, **kwargs) -> None:
18
+ return
19
+
20
+ @abstractmethod
21
+ def plot(
22
+ self,
23
+ data: pd.DataFrame,
24
+ x: str,
25
+ y: str,
26
+ grid: bool = True,
27
+ axes: Any | None = None,
28
+ xlabel: str | None = None,
29
+ ylabel: str | None = None,
30
+ label: str | None = None,
31
+ **kwargs,
32
+ ) -> tuple[Any, Any]:
33
+ """Plot 2D data.
34
+
35
+ Parameters
36
+ ----------
37
+ data : pandas.DataFrame
38
+ Holds all data to plot.
39
+ x, y : str
40
+ Name of column in ``data`` for x/y.
41
+ grid : bool, optional
42
+ If grid should be plotted. Default is True.
43
+ axes : Any | None, optional
44
+ Axes to re-use, if provided. The default is None (plot on new
45
+ axis).
46
+ xlabel, ylabel : str | None, optional
47
+ Name of the labels. If not provided, we use the markdown equivalent
48
+ of x/y, if defined in :data:`.markdown`.
49
+ label : str | None, optional
50
+ If provided, overrides the legend. Useful when several simulations
51
+ are shown on the same plot.
52
+ kwargs :
53
+ Other keyword passed to the actual plot method.
54
+
55
+ Returns
56
+ -------
57
+ Any
58
+ Axis object.
59
+ Any
60
+ Color used for the plot.
61
+
62
+ """
63
+
64
+ @abstractmethod
65
+ def hist(
66
+ self,
67
+ data: pd.DataFrame,
68
+ x: PARTICLE_0D_t,
69
+ bins: int = 200,
70
+ hist_range: tuple[float, float] | None = None,
71
+ **kwargs,
72
+ ) -> Any:
73
+ """Plot a histogram.
74
+
75
+ Parameters
76
+ ----------
77
+ data : pandas.DataFrame
78
+ Holds all data to plot.
79
+ x : PARTICLE_0D_t
80
+ Name of the column in ``data`` to plot.
81
+ bins : int, optional
82
+ Number of bins in the histogram. The default is 200.
83
+ hist_range : tuple[float, float] | None, optional
84
+ Lower and upper range for the calculation of the histogram. The
85
+ default is None.
86
+ kwargs :
87
+ Other keyword arguments passed to the actual plot method.
88
+
89
+ Returns
90
+ -------
91
+ Any
92
+ Axis object.
93
+
94
+ """
95
+
96
+ @abstractmethod
97
+ def plot_3d(
98
+ self,
99
+ data: Any,
100
+ key: PARTICLE_3D_t,
101
+ *args,
102
+ **kwargs,
103
+ ) -> Any:
104
+ """Create a 3D plot.
105
+
106
+ Parameters
107
+ ----------
108
+ data : Any
109
+ Object storing the data to plot.
110
+ key : PARTICLE_3D_t
111
+ Name/nature of the data to plot.
112
+
113
+ """
114
+
115
+ @abstractmethod
116
+ def load_mesh(
117
+ self, stl_path: str | Path, stl_alpha: float | None = None, **kwargs
118
+ ) -> Any:
119
+ """Load the 3D mesh.
120
+
121
+ Parameters
122
+ ----------
123
+ stl_path : str | Path
124
+ Path to the ``STL`` file.
125
+ stl_alpha : float | None, optional
126
+ Transparency for the mesh. The default is None.
127
+
128
+ Returns
129
+ -------
130
+ Any
131
+ Mesh object.
132
+
133
+ """
134
+
135
+ @abstractmethod
136
+ def plot_mesh(self, mesh: Any, *args, **kwargs) -> Any:
137
+ """Plot a 3D mesh."""
138
+
139
+ @abstractmethod
140
+ def plot_trajectory(
141
+ self,
142
+ points: list[NDArray[np.float64]],
143
+ emission_color: str | None = None,
144
+ collision_color: str | None = None,
145
+ collision_point: NDArray[np.float64] = np.array([], dtype=np.float64),
146
+ lw: int = 7,
147
+ r: int = 8,
148
+ **kwargs,
149
+ ) -> Any:
150
+ """Plot the :class:`.Particle` trajectory stored in ``points``.
151
+
152
+ Parameters
153
+ ----------
154
+ points :
155
+ List of positions, as returned by :meth:`.Vector.to_list`.
156
+ emission_color :
157
+ If provided, the first known position is colored with this color.
158
+ collision_color :
159
+ If provided, the last known position is colored with this color.
160
+ collision_point :
161
+ If provided and ``collision_color`` is not ``None``, we plot this
162
+ point instead of the last of ``points``. This is useful when the
163
+ extrapolated time is large, and actuel collision point may differ
164
+ significantly from last position points.
165
+ lw :
166
+ Trajectory line width.
167
+ r :
168
+ Size of the emission/collision points.
169
+
170
+ """
171
+
172
+ def show(self) -> None:
173
+ """Show the plots that were produced.
174
+
175
+ Useful for the bash interface.
176
+
177
+ """
178
+ return
@@ -0,0 +1 @@
1
+ """Define an object to store simulation results."""
@@ -0,0 +1,361 @@
1
+ """Define a base object to store a multipactor simulation results."""
2
+
3
+ import logging
4
+ from abc import ABC
5
+ from pathlib import Path
6
+ from typing import Any, Callable, Literal
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from simultipac.plotter.default import DefaultPlotter
12
+ from simultipac.plotter.plotter import Plotter
13
+ from simultipac.types import DATA_0D_t, DATA_1D_t
14
+ from simultipac.util.exponential_growth import ExpGrowthParameters, fit_alpha
15
+
16
+
17
+ class ShapeMismatchError(Exception):
18
+ """Raise error when ``population`` and ``time`` have different shapes."""
19
+
20
+
21
+ class MissingDataError(Exception):
22
+ """Error raised when trying to access non-existing data."""
23
+
24
+
25
+ class SimulationResults(ABC):
26
+ """Store a single simulation results."""
27
+
28
+ def __init__(
29
+ self,
30
+ id: int,
31
+ e_acc: float,
32
+ time: np.ndarray,
33
+ population: np.ndarray,
34
+ p_rms: float | None = None,
35
+ plotter: Plotter | None = None,
36
+ trim_trailing: bool = False,
37
+ period: float | None = None,
38
+ parameters: dict[str, float | bool | str] | None = None,
39
+ **kwargs,
40
+ ) -> None:
41
+ """Instantiate, post-process.
42
+
43
+ Parameters
44
+ ----------
45
+ id :
46
+ Unique simulation identifier.
47
+ e_acc :
48
+ Accelerating field in :unit:`V/m`.
49
+ time :
50
+ Time in :unit:`ns`.
51
+ population :
52
+ Evolution of population with time. Same shape as ``time``.
53
+ p_rms :
54
+ RMS power in :unit:`W`.
55
+ plotter :
56
+ An object allowing to plot data.
57
+ trim_trailing :
58
+ To remove the last simulation points, when the population is 0.
59
+ Used with SPARK3D (``CSV`` import) for consistency with CST.
60
+ period :
61
+ RF period in :unit:`ns`. Mandatory for exponential growth fits.
62
+ parameters :
63
+ Additional information on the simulation. Typically, value of
64
+ magnetic field, number of PIC cells, simulation flags...
65
+
66
+ """
67
+ self.id = id
68
+ self.e_acc = e_acc
69
+ self.p_rms = p_rms
70
+ self.time = time
71
+ self.population = population
72
+ if plotter is None:
73
+ plotter = DefaultPlotter()
74
+ self._plotter = plotter
75
+ self._check_consistent_shapes()
76
+ if trim_trailing:
77
+ self._trim_trailing()
78
+ self._exp_growth_parameters: ExpGrowthParameters | dict[str, float] = (
79
+ {}
80
+ )
81
+ self._period: float | None = period
82
+ self._modelled_population: np.ndarray | None = None
83
+ self._color: Any = None
84
+ self._alpha: float | None = None
85
+
86
+ self.parameters: dict[str, Any] = (
87
+ {} if parameters is None else parameters
88
+ )
89
+
90
+ def __str__(self) -> str:
91
+ """Print info on current simulation."""
92
+ info = [f"Sim. #{self.id}", f"E_acc = {self.e_acc:.2e} V/m"]
93
+ if len(self._exp_growth_parameters) == 0:
94
+ return ", ".join(info)
95
+ info.append(r"$\alpha = $" + f"{self.alpha:.3f} ns^-1")
96
+ return ", ".join(info)
97
+
98
+ def __repr__(self) -> str:
99
+ """Print minimal info on current simulation."""
100
+ return f"SimulationResults(id={self.id}, e_acc={self.e_acc:.2e})"
101
+
102
+ def _check_consistent_shapes(self) -> None:
103
+ """Raise an error if ``time`` and ``population`` have diff shapes."""
104
+ if self.time.shape == self.population.shape:
105
+ return
106
+ raise ShapeMismatchError(
107
+ f"{self.time.shape = } but {self.population.shape = }"
108
+ )
109
+
110
+ def _trim_trailing(self) -> None:
111
+ """Remove data for which population is null."""
112
+ idx_to_remove = np.argwhere(self.population == 0.0)
113
+ if idx_to_remove.size == 0:
114
+ return
115
+ last_idx = idx_to_remove[0][0]
116
+ self.population = self.population[:last_idx]
117
+ self.time = self.time[:last_idx]
118
+
119
+ @property
120
+ def alpha(self) -> float:
121
+ """Return the exponential growth factor in :unit:`ns^{-1}`."""
122
+ if self._alpha is not None:
123
+ return self._alpha
124
+
125
+ alpha = self._exp_growth_parameters.get("alpha", None)
126
+ if alpha is not None:
127
+ self.alpha = alpha
128
+ return alpha
129
+
130
+ logging.warning(
131
+ "Exponential growth factor not calculated yet. Returnin NaN."
132
+ )
133
+ return np.nan
134
+
135
+ @alpha.setter
136
+ def alpha(self, value: float) -> None:
137
+ """Set the value of exp growth factor."""
138
+ self._alpha = value
139
+
140
+ @alpha.deleter
141
+ def alpha(self) -> None:
142
+ """Delete the value."""
143
+ self._alpha = None
144
+
145
+ def fit_alpha(
146
+ self,
147
+ fitting_periods: int,
148
+ running_mean: bool = False,
149
+ log_fit: bool = True,
150
+ minimum_final_number_of_electrons: int = 0,
151
+ bounds: tuple[list[float], list[float]] = (
152
+ [1e-10, -10.0],
153
+ [np.inf, 10.0],
154
+ ),
155
+ initial_values: list[float] = [0.0, 0.0],
156
+ **kwargs,
157
+ ) -> None:
158
+ """Fit exp growth factor.
159
+
160
+ Parameters
161
+ ----------
162
+ fitting_periods :
163
+ Number of periods over which the exp growth is searched. Longer is
164
+ better, but you do not want to start the fit before the exp growth
165
+ starts.
166
+ running_mean :
167
+ To tell if you want to average the number of particles over one
168
+ period. It is recommended with CST, but does not bring anything for
169
+ SPARK3D. The default is False.
170
+ log_fit :
171
+ To perform the fit on :func:`exp_growth_log` rather than
172
+ :func:`exp_growth`. The default is True, as it generally shows
173
+ better convergence.
174
+ minimum_final_number_of_electrons :
175
+ Under this final number of electrons, we do no bother finding the
176
+ exp growth factor and set all fit parameters to ``NaN``.
177
+ bounds :
178
+ Upper bound and lower bound for the two variables: initial number
179
+ of electrons, exp growth factor.
180
+ initial_values: list[float], optional
181
+ Initial values for the two variables: initial number of electrons,
182
+ exp growth factor.
183
+
184
+ """
185
+ assert self._period is not None, "RF period is needed."
186
+ fitting_range = self._period * fitting_periods
187
+
188
+ self._exp_growth_parameters = fit_alpha(
189
+ self.time,
190
+ self.population,
191
+ fitting_range=fitting_range,
192
+ period=self._period,
193
+ running_mean=running_mean,
194
+ log_fit=log_fit,
195
+ minimum_final_number_of_electrons=minimum_final_number_of_electrons,
196
+ bounds=bounds,
197
+ initial_values=initial_values,
198
+ **kwargs,
199
+ )
200
+
201
+ @property
202
+ def modelled_population(self) -> np.ndarray:
203
+ """Define evolution of population, as modelled."""
204
+ if self._modelled_population is not None:
205
+ return self._modelled_population
206
+ if self._exp_growth_parameters is None:
207
+ raise ValueError(
208
+ "Cannot model population evolution if fit not performed."
209
+ )
210
+ model = self._exp_growth_parameters["model"]
211
+ assert isinstance(model, Callable)
212
+ self._modelled_population = model(
213
+ self.time, **self._exp_growth_parameters
214
+ )
215
+ assert isinstance(self._modelled_population, np.ndarray)
216
+ return self._modelled_population
217
+
218
+ def plot(
219
+ self,
220
+ x: DATA_0D_t | DATA_1D_t,
221
+ y: DATA_0D_t | DATA_1D_t,
222
+ plotter: Plotter | None = None,
223
+ label: str | Literal["auto"] | None = None,
224
+ grid: bool = True,
225
+ axes: Any | None = None,
226
+ **kwargs,
227
+ ) -> Any:
228
+ """Plot ``y`` vs ``x`` using ``plotter.plot()`` method.
229
+
230
+ Parameters
231
+ ----------
232
+ x, y :
233
+ Name of properties to plot.
234
+ plotter :
235
+ Object to use for plot. If not provided, we use :attr:`._plotter`.
236
+ label :
237
+ If provided, overrides the legend. Useful when several simulations
238
+ are shown on the same plot. Use the magic keyword ``"auto"`` to
239
+ legend with a short description of current object.
240
+ grid :
241
+ If grid should be plotted. Default is True.
242
+ axes :
243
+ Axes to re-use, if provided. The default is None (plot on new
244
+ axis).
245
+ kwargs :
246
+ Other keyword arguments passed to the :meth:`.Plotter.plot` method.
247
+
248
+ Returns
249
+ -------
250
+ Any
251
+ Objects created by the :meth:`.Plotter.plot`.
252
+
253
+ """
254
+ if plotter is None:
255
+ plotter = self._plotter
256
+ data = self.to_pandas(x, y)
257
+
258
+ if label == "auto":
259
+ label = str(self)
260
+
261
+ axes, color = plotter.plot(
262
+ data,
263
+ x=x,
264
+ y=y,
265
+ grid=grid,
266
+ axes=axes,
267
+ label=label,
268
+ color=self._color,
269
+ **kwargs,
270
+ )
271
+ if self._color is None:
272
+ self._color = color
273
+ return axes
274
+
275
+ def hist(self, *args, **kwargs) -> Any:
276
+ raise NotImplementedError
277
+
278
+ def to_pandas(self, *args: DATA_0D_t | DATA_1D_t) -> pd.DataFrame:
279
+ """Concatenate all attribute arrays which name is in ``args`` to a df.
280
+
281
+ Parameters
282
+ ----------
283
+ args :
284
+ Name of arguments as saved in current objects. Example:
285
+ ``"population"``, ``"time"``...
286
+
287
+ Returns
288
+ -------
289
+ pandas.DataFrame
290
+ Concatenates all desired data.
291
+
292
+ Raises
293
+ ------
294
+ MissingDataError:
295
+ If a string in ``args`` does not correspond to any attribute in
296
+ ``self`` (or if corresponding value is ``None``).
297
+ ValueError:
298
+ If all the ``args`` are a single value (float/int/bool).
299
+
300
+ """
301
+ data: dict[str, float | np.ndarray] = {
302
+ arg: value
303
+ for arg in args
304
+ if (value := getattr(self, arg, None)) is not None
305
+ }
306
+ if len(data) == len(args):
307
+ try:
308
+ return pd.DataFrame(data)
309
+ except ValueError as e:
310
+ raise ValueError(
311
+ "Floats/ints/bools are not gettable with this method if "
312
+ f"no array is asked at the same time.\n{e}"
313
+ )
314
+
315
+ missing = [arg for arg in args if getattr(self, arg, None) is None]
316
+ raise MissingDataError(f"{missing} not found in {self}")
317
+
318
+ def show(self) -> None:
319
+ """Show the plots that were produced.
320
+
321
+ Useful for the bash interface.
322
+
323
+ """
324
+ return self._plotter.show()
325
+
326
+
327
+ class SimulationResultsFactory(ABC):
328
+ """Easily create :class:`.SimulationResults`."""
329
+
330
+ def __init__(
331
+ self,
332
+ plotter: Plotter | None = None,
333
+ freq_ghz: float | None = None,
334
+ stl_path: str | Path | None = None,
335
+ stl_alpha: float | None = None,
336
+ *args,
337
+ **kwargs,
338
+ ) -> None:
339
+ """Instantiate object.
340
+
341
+ Parameters
342
+ ----------
343
+ plotter :
344
+ Object to create the plots.
345
+ freq_ghz :
346
+ RF frequency in :unit:`GHz`. Used to compute RF period, which is
347
+ mandatory for exp growth fitting.
348
+ stl_path :
349
+ Path to the ``STL`` file holding the 3D structure of the system.
350
+ The default is None.
351
+ stl_alpha :
352
+ Transparency setting for the mesh.
353
+
354
+ """
355
+ if plotter is None:
356
+ plotter = DefaultPlotter()
357
+ self._plotter = plotter
358
+ self._freq_ghz = freq_ghz
359
+ self._period = 1.0 / freq_ghz if freq_ghz is not None else None
360
+ self._stl_path = stl_path
361
+ self._stl_alpha = stl_alpha