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 @@
1
+ """Define objects and methods to treat Spark3D results."""
@@ -0,0 +1,159 @@
1
+ """Define an object to store SPARK3D simulation results."""
2
+
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+
7
+ from simultipac.plotter.plotter import Plotter
8
+ from simultipac.simulation_results.simulation_results import (
9
+ SimulationResults,
10
+ SimulationResultsFactory,
11
+ )
12
+
13
+
14
+ class Spark3DResults(SimulationResults):
15
+ """Store a single SPARK3D simulation results."""
16
+
17
+
18
+ class Spark3DResultsFactory(SimulationResultsFactory):
19
+ """Define an object to easily instantiate :class:`.Spark3DResults`."""
20
+
21
+ def __init__(
22
+ self,
23
+ plotter: Plotter | None = None,
24
+ freq_ghz: float | None = None,
25
+ *args,
26
+ **kwargs,
27
+ ) -> None:
28
+ super().__init__(plotter=plotter, freq_ghz=freq_ghz, *args, **kwargs)
29
+
30
+ def from_file(
31
+ self, filepath: Path, e_acc: np.ndarray, delimiter: str = " ", **kwargs
32
+ ) -> list[Spark3DResults]:
33
+ """Load a ``TXT`` or ``CSV`` file and create associated objects."""
34
+ filetype = filepath.suffix
35
+ if filetype == ".txt":
36
+ return self._from_txt(
37
+ filepath=filepath, e_acc=e_acc, delimiter=delimiter, **kwargs
38
+ )
39
+ if filetype == ".csv":
40
+ return self._from_csv(
41
+ filepath=filepath, e_acc=e_acc, delimiter=delimiter, **kwargs
42
+ )
43
+ raise OSError(f"SPARK3D files must be CSV or TXT. I got {filetype = }")
44
+
45
+ def _from_txt(
46
+ self, filepath: Path, e_acc: np.ndarray, delimiter: str = " ", **kwargs
47
+ ) -> list[Spark3DResults]:
48
+ """
49
+ Create several :class:`.Spark3DResults` from :file:`time_results.txt`.
50
+
51
+ These file are generally produced with SPARK3D CLI. ``TXT`` files look
52
+ like this::
53
+
54
+ #Sim num Power(W) Time(s) Num.elec.
55
+ 1 100 0 1000
56
+ 1 100 1 1010
57
+ 1 100 2 1020
58
+ ... ... ... ...
59
+ 2 50 0 1000
60
+ 2 50 1 900
61
+ 2 50 2 500
62
+ ... ... ... ...
63
+
64
+ .. todo::
65
+ Handle malformed files. In particular what happens if simulation
66
+ numbers are mixed?
67
+
68
+ Parameters
69
+ ----------
70
+ filepath : Path
71
+ Path to the file to load.
72
+ e_acc : np.ndarray
73
+ Accelerating field values in :unit:`V/m`.
74
+ delimiter : str, optional
75
+ Delimiter between columns. The default is a space.
76
+
77
+ """
78
+ raw_data = np.loadtxt(filepath, delimiter=delimiter)
79
+ raw_data[:, 2] *= 1e9
80
+
81
+ results: list[Spark3DResults] = []
82
+
83
+ for i, this_e_acc in enumerate(e_acc, start=1):
84
+ idx_lines = np.where(raw_data[:, 0] == float(i))[0]
85
+ power = raw_data[idx_lines, 1][0]
86
+ time = raw_data[idx_lines, 2]
87
+ num_elec = raw_data[idx_lines, 3]
88
+
89
+ results.append(
90
+ Spark3DResults(
91
+ id=i,
92
+ e_acc=this_e_acc,
93
+ time=time,
94
+ population=num_elec,
95
+ p_rms=power,
96
+ plotter=self._plotter,
97
+ period=self._period,
98
+ )
99
+ )
100
+
101
+ return results
102
+
103
+ def _from_csv(
104
+ self, filepath: Path, e_acc: np.ndarray, delimiter: str = " ", **kwargs
105
+ ) -> list[Spark3DResults]:
106
+ """
107
+ Create several :class:`.Spark3DResults` from :file:`time_results.csv`.
108
+
109
+ Right-click on ``Multipactor results``, ``Export to CSV``.
110
+ These file are manually produed by the user. ``CSV`` files look like
111
+ this::
112
+
113
+ 0 1000 1000 1000 1000
114
+ 1e-9 1010 900 999 1001
115
+ 2e-9 1020 500 998 1002
116
+ 3e-9 1040 100 990 1003
117
+ 4e-9 1050 0 950 1004
118
+ ...
119
+
120
+ There are no headers. The first column holds the time in seconds.
121
+ Following columns hold the number of electrons for every simulation
122
+ (one simulation on one column).
123
+
124
+ .. note::
125
+ In order to be consistent with CST import, we remove the end of the
126
+ simulations, when the population is 0.
127
+
128
+ Parameters
129
+ ----------
130
+ filepath : Path
131
+ Path to the file to load.
132
+ e_acc : np.ndarray
133
+ Accelerating field values in :unit:`V/m`.
134
+ delimiter : str, optional
135
+ Delimiter between columns. The default is a space.
136
+
137
+ """
138
+ raw_data = np.loadtxt(filepath, delimiter=delimiter)
139
+ time = raw_data[:, 0] * 1e9
140
+ p_rms = None
141
+
142
+ results: list[Spark3DResults] = []
143
+
144
+ for idx_col, this_e_acc in enumerate(e_acc, start=1):
145
+ population = raw_data[:, idx_col]
146
+ results.append(
147
+ Spark3DResults(
148
+ id=idx_col,
149
+ e_acc=this_e_acc,
150
+ time=time,
151
+ population=population,
152
+ p_rms=p_rms,
153
+ plotter=self._plotter,
154
+ trim_trailing=True,
155
+ period=self._period,
156
+ )
157
+ )
158
+
159
+ return results
simultipac/types.py ADDED
@@ -0,0 +1,31 @@
1
+ """Define types and type hints."""
2
+
3
+ from typing import Literal
4
+
5
+ #: :class:`.SimulationResults` attributes stored as float.
6
+ DATA_0D = ("id", "e_acc", "p_rms", "alpha")
7
+ #: :class:`.SimulationResults` attributes stored as float.
8
+ DATA_0D_t = Literal["id", "e_acc", "p_rms", "alpha"]
9
+
10
+ #: :class:`.SimulationResults` attributes stored as 1D arrays.
11
+ DATA_1D = ("time", "population", "modelled_population")
12
+ #: :class:`.SimulationResult` attributes stored as 1D arrays.
13
+ DATA_1D_t = Literal["time", "population", "modelled_population"]
14
+
15
+ #: :class:`.CSTSimulationResults` attributes if :class:`.ParticleMonitor` was
16
+ # defined
17
+ PARTICLE_0D = ("emission_energy", "collision_energy", "collision_angle")
18
+ #: :class:`.CSTSimulationResults` attributes if :class:`.ParticleMonitor` was
19
+ # defined
20
+ PARTICLE_0D_t = Literal[
21
+ "emission_energy", "collision_energy", "collision_angle"
22
+ ]
23
+
24
+ #: :class:`.CSTSimulationResults` attributes if :class:`.ParticleMonitor` was
25
+ # defined
26
+ PARTICLE_3D = ("trajectory", "collision_distribution", "emission_distribution")
27
+ #: :class:`.CSTSimulationResults` attributes if :class:`.ParticleMonitor` was
28
+ # defined
29
+ PARTICLE_3D_t = Literal[
30
+ "trajectory", "collision_distribution", "emission_distribution"
31
+ ]
@@ -0,0 +1,7 @@
1
+ """
2
+ In this package we store tools that can be used in the whole code.
3
+
4
+ .. todo::
5
+ Move ``exp_growth`` module?
6
+
7
+ """
@@ -0,0 +1,369 @@
1
+ r"""Define exponential growth model as well as fitting function.
2
+
3
+ .. note::
4
+ Other models that I tried:
5
+
6
+ .. math::
7
+ N(t) = N_0 (1 + K \cos{(\omega_0 t + \phi_0)}) \mathrm{e}^{\alpha t}
8
+
9
+ N(t) = N_0 (1 + K \cos{(\omega_0 t / T_{MP} + \phi_0)})
10
+ \mathrm{e}^{\alpha t}
11
+
12
+ I dropped them as with too much unkowns, any model can fit anything.
13
+
14
+ """
15
+
16
+ import logging
17
+ import math
18
+ import warnings
19
+ from collections.abc import Callable
20
+ from functools import partial
21
+ from typing import TypedDict
22
+
23
+ import numpy as np
24
+ from scipy.ndimage import uniform_filter1d
25
+ from scipy.optimize import OptimizeWarning, curve_fit
26
+
27
+ warnings.simplefilter("error", OptimizeWarning)
28
+
29
+
30
+ class ExpGrowthParameters(TypedDict):
31
+ """Define parameters for exp growth model."""
32
+
33
+ #: Number of electrons at ``t=t_0``.
34
+ n_0: float
35
+ #: Exponential growth factor in :unit:`ns^{-1}`.
36
+ alpha: float
37
+ #: Starting time of exponential growth in :unit:`ns`.
38
+ t_0: float
39
+ #: Exponential growth function.
40
+ model: Callable[[np.ndarray, float, float, float], np.ndarray]
41
+
42
+
43
+ def exp_growth(
44
+ time: np.ndarray,
45
+ n_0: float,
46
+ alpha: float,
47
+ t_0: float = 0.0,
48
+ **kwargs,
49
+ ) -> np.ndarray:
50
+ r"""Exponential growth factor function.
51
+
52
+ .. math::
53
+ N(t) = N_0 \mathrm{e}^{\alpha (t-t_0)}
54
+
55
+ Parameters
56
+ ----------
57
+ time : np.ndarray
58
+ Time in :unit:`ns`.
59
+ n_0 : float
60
+ Number of electrons at the start of the exponential growth.
61
+ alpha : float
62
+ Exponential growth factor in :unit:`ns^{-1}`.
63
+ t_0 : float, optional
64
+ Time at which the exponential growth starts, in :unit:`ns`. The
65
+ default is 0.0.
66
+
67
+ Returns
68
+ -------
69
+ population : np.ndarray
70
+ Modelled population evolution. It is filled with NaN for times before
71
+ ``t_0``.
72
+
73
+ """
74
+ population = np.full(len(time), np.nan)
75
+ after_t_0 = np.where(time >= t_0)
76
+ population[after_t_0] = n_0 * np.exp(alpha * (time[after_t_0] - t_0))
77
+ return population
78
+
79
+
80
+ def exp_growth_log(
81
+ time: np.ndarray,
82
+ n_0: float,
83
+ alpha: float,
84
+ t_0: float = 0.0,
85
+ **kwargs,
86
+ ) -> np.ndarray:
87
+ r"""Exponential growth factor function, in log form.
88
+
89
+ .. math::
90
+ \log{N(t)} = \log{N_0} + \alpha (t-t_0)
91
+
92
+ In general, better results for the fit process than the classic
93
+ :func:`exp_growth`.
94
+
95
+ Parameters
96
+ ----------
97
+ time : np.ndarray
98
+ Time in :unit:`ns`.
99
+ n_0 : float
100
+ Number of electrons at the start of the exponential growth.
101
+ alpha : float
102
+ Exponential growth factor in :unit:`ns^{-1}`.
103
+ t_0 : float, optional
104
+ Time at which the exponential growth starts, in :unit:`ns`. The default
105
+ is 0.0.
106
+
107
+ Returns
108
+ -------
109
+ log_population : np.ndarray
110
+ Log of modelled population evolution. It is filled with NaN for times
111
+ before ``t_0``.
112
+
113
+ """
114
+ log_population = np.full(len(time), np.nan)
115
+ log_population[np.where(time >= t_0)] = math.log(n_0) + alpha * (
116
+ time - t_0
117
+ )
118
+ return log_population
119
+
120
+
121
+ def fit_alpha(
122
+ time: np.ndarray,
123
+ population: np.ndarray,
124
+ fitting_range: float,
125
+ period: float,
126
+ running_mean: bool = True,
127
+ log_fit: bool = True,
128
+ minimum_final_number_of_electrons: int = 0,
129
+ bounds: tuple[list[float], list[float]] = ([1e-10, -10.0], [np.inf, 10.0]),
130
+ initial_values: list[float] = [0.0, 0.0],
131
+ **kwargs,
132
+ ) -> ExpGrowthParameters:
133
+ """Perform the exponential growth fitting.
134
+
135
+ Parameters
136
+ ----------
137
+ time : np.ndarray
138
+ Time in :unit:`ns`.
139
+ population : np.ndarray
140
+ Evolution of electron population with time.
141
+ fitting_range : float
142
+ Time over which the exp growth is searched. Longer is better, but you
143
+ do not want to start the fit before the exp growth starts.
144
+ running_mean : bool, optional
145
+ To tell if you want to average the number of particles over one period.
146
+ Highly recommended. The default is True.
147
+ log_fit : bool, optional
148
+ To perform the fit on :func:`exp_growth_log` rather than
149
+ :func:`exp_growth`. The default is True, as it generally shows better
150
+ convergence.
151
+ minimum_final_number_of_electrons : int, optional
152
+ Under this final number of electrons, we do no bother finding the exp
153
+ growth factor and return a ``NaN``.
154
+ bounds : tuple[list[float], list[float]], optional
155
+ Upper bound and lower bound for the two variables: initial number of
156
+ electrons, exp growth factor.
157
+ initial_values: list[float | None], optional
158
+ Initial values for the two variables: initial number of electrons, exp
159
+ growth factor.
160
+ kwargs :
161
+ Other keyword arguments passed to the ``curve_fit`` function.
162
+
163
+ Returns
164
+ -------
165
+ exp_growth_parameters : ExpGrowthParameters
166
+ Holds the fit parameters.
167
+
168
+ """
169
+ exp_growth_parameters = ExpGrowthParameters(
170
+ n_0=np.nan, alpha=np.nan, t_0=np.nan, model=exp_growth
171
+ )
172
+ n_points = len(time)
173
+ if len(population) != n_points:
174
+ raise ValueError(f"{len(time) = } while {len(population) = }")
175
+
176
+ if final_number := population[-1] < minimum_final_number_of_electrons:
177
+ logging.debug(
178
+ f"{final_number = } while {minimum_final_number_of_electrons = }. "
179
+ "We return alpha = NaN."
180
+ )
181
+ return exp_growth_parameters
182
+
183
+ fit_args = _to_fit(time, population, fitting_range, log_fit=log_fit)
184
+ fit_func, fit_time, fit_pop = fit_args
185
+ exp_growth_parameters["t_0"] = float(fit_time[0])
186
+
187
+ if running_mean:
188
+ width = _n_points_in_a_period(fit_time, period)
189
+ population = _smoothen(fit_pop, width)
190
+
191
+ bounds, initial_values = _design_space(
192
+ log_fit, fit_pop, bounds, initial_values
193
+ )
194
+
195
+ try:
196
+ result = curve_fit(
197
+ fit_func,
198
+ fit_time,
199
+ fit_pop,
200
+ p0=initial_values,
201
+ bounds=bounds,
202
+ maxfev=5000,
203
+ **kwargs,
204
+ )[0]
205
+
206
+ except OptimizeWarning as e:
207
+ logging.info(f"Fit failed, returnin NaN parameters.\n{e}")
208
+ return exp_growth_parameters
209
+
210
+ exp_growth_parameters["n_0"] = float(result[0])
211
+ exp_growth_parameters["alpha"] = float(result[1])
212
+ return exp_growth_parameters
213
+
214
+
215
+ def _to_fit(
216
+ time: np.ndarray,
217
+ population: np.ndarray,
218
+ fitting_range: float,
219
+ log_fit: bool = True,
220
+ ) -> tuple[Callable, np.ndarray, np.ndarray]:
221
+ """Determine the ``x``, ``f(x)`` arrays as well as ``f`` for the fit.
222
+
223
+ Parameters
224
+ ----------
225
+ time : np.ndarray
226
+ Full array of times.
227
+ population : np.ndarray
228
+ Corresponding population evolution,
229
+ fitting_range : float
230
+ Time over which the exp growth is searched. Longer is better, but you
231
+ do not want to start the fit before the exp growth starts.
232
+ log_fit : bool, optional
233
+ To perform the fit on :func:`exp_growth_log` rather than
234
+ :func:`exp_growth`. The default is True, as it generally shows better
235
+ convergence.
236
+
237
+ Returns
238
+ -------
239
+ fit_func : Callable
240
+ The ``f`` we want to retrieve parameters.
241
+ fit_time : np.ndarray
242
+ The ``x`` values for the fit.
243
+ fit_pop : np.ndarray
244
+ The ``f(x)`` we will try to retrieve.
245
+
246
+ """
247
+
248
+ indexes = _indexes_for_fit(time, population, fitting_range)
249
+
250
+ fit_time = time[indexes]
251
+ t_0 = fit_time[0]
252
+ fit_pop = population[indexes]
253
+ if not log_fit:
254
+ fit_func = partial(exp_growth, t_0=t_0)
255
+ return fit_func, fit_time, fit_pop
256
+
257
+ fit_func = partial(exp_growth_log, t_0=t_0)
258
+ return fit_func, fit_time, np.log(fit_pop)
259
+
260
+
261
+ def _indexes_for_fit(
262
+ time: np.ndarray,
263
+ population: np.ndarray,
264
+ fitting_range: float,
265
+ minimum_number_of_points: int = 5,
266
+ ) -> range:
267
+ """Determine the indexes on which the fit should be performed.
268
+
269
+ The fit is performed over ``fitting_range``, ending at the last non-zero
270
+ population count (first zero-population count is excluded to avoid
271
+ messing with log(population)).
272
+
273
+ """
274
+ if fitting_range <= 0.0:
275
+ raise ValueError(f"Cannot perform a fit on {fitting_range = }")
276
+
277
+ null_population_indexes = np.where(population == 0)[0]
278
+
279
+ idx_end = len(time) - 1
280
+ if len(null_population_indexes) > 0:
281
+ idx_end = null_population_indexes[0] - 1
282
+
283
+ final_time = float(time[idx_end])
284
+
285
+ start_time = final_time - fitting_range
286
+ if start_time < 0.0:
287
+ logging.warning("Fitting range is larger than simulation time")
288
+ idx_start = np.argmin(np.abs(time - start_time))
289
+
290
+ if not isinstance(idx_start, int):
291
+ idx_start = int(idx_start)
292
+
293
+ if (n_fit_points := idx_end - idx_start) < minimum_number_of_points:
294
+ logging.warning(
295
+ f"Fit performed on {n_fit_points} data points, which may be too "
296
+ "low. This usually happens when time is given in seconds instead "
297
+ f"of nanoseconds. Does {final_time = } seems right? What about "
298
+ f"{fitting_range = }?"
299
+ )
300
+ logging.debug(f"Fit will be performed from index {idx_start} to {idx_end}")
301
+ return range(idx_start, idx_end + 1)
302
+
303
+
304
+ def _n_points_in_a_period(
305
+ time: np.ndarray, period: float, min_points_per_period: int = 5
306
+ ) -> int:
307
+ """Get the number of data points in a single RF period.
308
+
309
+ Print a warning if the number of points is lower than
310
+ ``min_points_per_period``.
311
+
312
+ """
313
+ n_points = np.argmin(np.abs(time - time[0] - period))
314
+ if not isinstance(n_points, int):
315
+ n_points = int(n_points)
316
+ if n_points < min_points_per_period:
317
+ logging.warning(
318
+ f"There are {n_points} data points per RF period, which may be too"
319
+ " low for the running mean routine. Maybe time (final value: "
320
+ f"{time[-1]:.2e}) and {period = :.2e} have different units?"
321
+ )
322
+ return n_points
323
+
324
+
325
+ def _design_space(
326
+ log_fit: bool,
327
+ fit_pop: np.ndarray,
328
+ bounds: tuple[list[float], list[float]] = ([1e-10, -10.0], [np.inf, 10.0]),
329
+ initial_values: list[float] = [0.0, 0.0],
330
+ ) -> tuple[tuple[list[float], list[float]], list[float]]:
331
+ """Set initial value and bounds.
332
+
333
+ As for now, only set the initial value of ``n_0`` to the population count
334
+ at the start of the fit.
335
+
336
+ .. note::
337
+ ``n_0`` is the actual population count, not the log of the pop count.
338
+
339
+ """
340
+ n_0 = fit_pop[0]
341
+ if log_fit:
342
+ n_0 = math.exp(fit_pop[0])
343
+
344
+ initial_values[0] = n_0
345
+ return bounds, initial_values
346
+
347
+
348
+ def _smoothen(population: np.ndarray, width: int) -> np.ndarray:
349
+ """Smooth data (running mean).
350
+
351
+ Used to compensate the periodic population oscillations (period: RF
352
+ period).
353
+
354
+ See also: https://stackoverflow.com/a/43200476/12188681
355
+
356
+ .. todo::
357
+ Better unit testing for this function.
358
+
359
+ """
360
+ # Old implementation, kept if needed
361
+ # https://stackoverflow.com/a/43200476/12188681
362
+ # run = uniform_filter1d(np.log(data[:, 1]), size=i_width,
363
+ # mode='nearest')
364
+ # # We do the running mean on the log to center the running metric on the
365
+ # # oscillations
366
+ # data_to_fit = np.column_stack((data[:, 0], run))
367
+ # # data_to_fit = data_to_fit[idx_start:i_remove]
368
+ # data_to_fit = data_to_fit[idx_start:idx_end + 1]\
369
+ return uniform_filter1d(population, size=width, mode="nearest")