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 +14 -0
- simultipac/constants.py +16 -0
- simultipac/cst/__init__.py +1 -0
- simultipac/cst/helper.py +161 -0
- simultipac/cst/simulation_results.py +469 -0
- simultipac/particle_monitor/__init__.py +5 -0
- simultipac/particle_monitor/collisions/__init__.py +1 -0
- simultipac/particle_monitor/collisions/util.py +98 -0
- simultipac/particle_monitor/collisions/vedo_mesh_collisions.py +38 -0
- simultipac/particle_monitor/converters.py +87 -0
- simultipac/particle_monitor/particle.py +416 -0
- simultipac/particle_monitor/particle_monitor.py +722 -0
- simultipac/particle_monitor/vector.py +210 -0
- simultipac/plotter/__init__.py +1 -0
- simultipac/plotter/default.py +331 -0
- simultipac/plotter/plotter.py +178 -0
- simultipac/simulation_results/__init__.py +1 -0
- simultipac/simulation_results/simulation_results.py +361 -0
- simultipac/simulation_results/simulations_results.py +724 -0
- simultipac/spark3d/__init__.py +1 -0
- simultipac/spark3d/simulation_results.py +159 -0
- simultipac/types.py +31 -0
- simultipac/util/__init__.py +7 -0
- simultipac/util/exponential_growth.py +369 -0
- simultipac/util/log_manager.py +192 -0
- simultipac/util/singleton.py +16 -0
- simultipac-2.0.3.dist-info/METADATA +103 -0
- simultipac-2.0.3.dist-info/RECORD +31 -0
- simultipac-2.0.3.dist-info/WHEEL +5 -0
- simultipac-2.0.3.dist-info/licenses/LICENSE +21 -0
- simultipac-2.0.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,724 @@
|
|
|
1
|
+
"""Define a set of simulation results."""
|
|
2
|
+
|
|
3
|
+
import bisect
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Collection, Generator, Iterable, Sequence
|
|
6
|
+
from functools import reduce
|
|
7
|
+
from itertools import product
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Iterator, Literal
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
|
|
14
|
+
from simultipac.cst.simulation_results import CSTResultsFactory
|
|
15
|
+
from simultipac.plotter.default import DefaultPlotter
|
|
16
|
+
from simultipac.plotter.plotter import Plotter
|
|
17
|
+
from simultipac.simulation_results.simulation_results import SimulationResults
|
|
18
|
+
from simultipac.spark3d.simulation_results import Spark3DResultsFactory
|
|
19
|
+
from simultipac.types import DATA_0D, DATA_0D_t, DATA_1D_t
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class UnsupportedToolError(Exception):
|
|
23
|
+
"""Raise for simulation tool different from SPARK3D or CST."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DuplicateIndexError(Exception):
|
|
27
|
+
"""Raise for simulation ID already existing."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class NonExistingIDError(Exception):
|
|
31
|
+
"""Raise when asking a non-existent ID."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SimulationsResults:
|
|
35
|
+
"""Store multiple :class:`.SimulationResults` with retrieval methods.
|
|
36
|
+
|
|
37
|
+
:class:`.SimulationResult` are stored in ``self`` in the order they are
|
|
38
|
+
given.
|
|
39
|
+
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
simulations_results: Iterable[SimulationResults],
|
|
45
|
+
plotter: Plotter | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
"""Sort and store the given :class:`.SimulationResults` instances.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
simulations_results :
|
|
52
|
+
The individual results instances.
|
|
53
|
+
plotter :
|
|
54
|
+
An object to create the plots.
|
|
55
|
+
|
|
56
|
+
"""
|
|
57
|
+
self._results_by_id: dict[int, SimulationResults] = {}
|
|
58
|
+
|
|
59
|
+
#: :class:`.SimulationResults` sorted by increasing accelerating field
|
|
60
|
+
self._results: list[SimulationResults] = []
|
|
61
|
+
for x in simulations_results:
|
|
62
|
+
self._add(x)
|
|
63
|
+
|
|
64
|
+
if plotter is None:
|
|
65
|
+
plotter = DefaultPlotter()
|
|
66
|
+
self._plotter = plotter
|
|
67
|
+
self._color: Any = None
|
|
68
|
+
|
|
69
|
+
def __iter__(self) -> Iterator[SimulationResults]:
|
|
70
|
+
"""Allow iteration over stored results."""
|
|
71
|
+
return iter(self._results)
|
|
72
|
+
|
|
73
|
+
def __len__(self) -> int:
|
|
74
|
+
"""Return number of elements."""
|
|
75
|
+
return len(self._results)
|
|
76
|
+
|
|
77
|
+
def _add(self, result: SimulationResults) -> None:
|
|
78
|
+
"""Add a new :class:`SimulationResults` instance."""
|
|
79
|
+
if result.id in self._results_by_id:
|
|
80
|
+
raise DuplicateIndexError(
|
|
81
|
+
f"SimulationResult with id {result.id} already exists."
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
self._results_by_id[result.id] = result
|
|
85
|
+
bisect.insort(self._results, result, key=lambda r: r.e_acc)
|
|
86
|
+
|
|
87
|
+
def get_by_id(self, result_id: int) -> SimulationResults:
|
|
88
|
+
"""Retrieve a :class:`SimulationResults` by its ID."""
|
|
89
|
+
result = self._results_by_id.get(result_id)
|
|
90
|
+
if result is not None:
|
|
91
|
+
return result
|
|
92
|
+
raise NonExistingIDError(f"No simulation results with ID {result_id}")
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def to_list(self) -> list[SimulationResults]:
|
|
96
|
+
"""Retrieve all results sorted by ``acc_field``."""
|
|
97
|
+
return self._results
|
|
98
|
+
|
|
99
|
+
def plot(
|
|
100
|
+
self,
|
|
101
|
+
x: DATA_0D_t | DATA_1D_t,
|
|
102
|
+
y: DATA_0D_t | DATA_1D_t,
|
|
103
|
+
idx_to_plot: Iterable[int] | None = None,
|
|
104
|
+
id_to_plot: Iterable[int] | None = None,
|
|
105
|
+
to_plot: Iterable[SimulationResults] | None = None,
|
|
106
|
+
plotter: Plotter | None = None,
|
|
107
|
+
label: str | Literal["auto"] | None = "auto",
|
|
108
|
+
grid: bool = True,
|
|
109
|
+
axes: Any | None = None,
|
|
110
|
+
sort_by_parameter: Collection[str] | None = None,
|
|
111
|
+
**kwargs,
|
|
112
|
+
) -> Any:
|
|
113
|
+
"""Recursively call :meth:`.SimulationResults.plot`.
|
|
114
|
+
|
|
115
|
+
.. note::
|
|
116
|
+
0D ``x`` vs ``y`` not implemented yet.
|
|
117
|
+
|
|
118
|
+
Parameters
|
|
119
|
+
----------
|
|
120
|
+
x, y :
|
|
121
|
+
Name of properties to plot.
|
|
122
|
+
idx_to_plot :
|
|
123
|
+
Positions in the list of :class:`.SimulationResults` sorted by
|
|
124
|
+
growing accelerating field / power. Not considered if
|
|
125
|
+
``id_to_plot`` or ``to_plot`` is provided.
|
|
126
|
+
id_to_plot :
|
|
127
|
+
ID attributes; takes preceedence over ``idx_to_plot``. Not
|
|
128
|
+
considered if ``to_plot`` is provided.
|
|
129
|
+
to_plot :
|
|
130
|
+
Objects to plot; takes preceedence over ``idx_to_plot`` and
|
|
131
|
+
``id_to_plot``.
|
|
132
|
+
plotter :
|
|
133
|
+
Object to use for plot. If not provided, we use :attr:`._plotter`.
|
|
134
|
+
label :
|
|
135
|
+
If provided, overrides the legend. Useful when several simulations
|
|
136
|
+
are shown on the same plot. Use the magic keyword ``"auto"`` to
|
|
137
|
+
legend with a short description of current object.
|
|
138
|
+
grid :
|
|
139
|
+
If grid should be plotted. Default is True.
|
|
140
|
+
axes :
|
|
141
|
+
Axes to re-use, if provided.
|
|
142
|
+
sort_by_parameter :
|
|
143
|
+
If provided, results are grouped by the given parameters before
|
|
144
|
+
plotting.
|
|
145
|
+
kwargs :
|
|
146
|
+
Other keyword arguments passed to the :meth:`.Plotter.plot` method.
|
|
147
|
+
|
|
148
|
+
Returns
|
|
149
|
+
-------
|
|
150
|
+
Any
|
|
151
|
+
Objects created by the :meth:`.Plotter.plot`.
|
|
152
|
+
|
|
153
|
+
"""
|
|
154
|
+
if plotter is None:
|
|
155
|
+
plotter = self._plotter
|
|
156
|
+
|
|
157
|
+
if sort_by_parameter is not None:
|
|
158
|
+
parameters_values = self.parameter_values(*sort_by_parameter)
|
|
159
|
+
for param_combination in product(
|
|
160
|
+
*[parameters_values[p] for p in sort_by_parameter]
|
|
161
|
+
):
|
|
162
|
+
filters = dict(zip(sort_by_parameter, param_combination))
|
|
163
|
+
to_plot = self.with_parameter_value(filters)
|
|
164
|
+
label = ", ".join(f"{p}={v}" for p, v in filters.items())
|
|
165
|
+
axes = self.plot(
|
|
166
|
+
x=x,
|
|
167
|
+
y=y,
|
|
168
|
+
plotter=plotter,
|
|
169
|
+
label=label,
|
|
170
|
+
grid=grid,
|
|
171
|
+
axes=axes,
|
|
172
|
+
to_plot=to_plot,
|
|
173
|
+
sort_by_parameter=None,
|
|
174
|
+
color=None,
|
|
175
|
+
**kwargs,
|
|
176
|
+
)
|
|
177
|
+
return axes
|
|
178
|
+
|
|
179
|
+
to_plot = self._to_plot(idx_to_plot, id_to_plot, to_plot)
|
|
180
|
+
|
|
181
|
+
if x in DATA_0D and y in DATA_0D:
|
|
182
|
+
return self._plot_0d(
|
|
183
|
+
x=x,
|
|
184
|
+
y=y,
|
|
185
|
+
plotter=plotter,
|
|
186
|
+
label=label,
|
|
187
|
+
grid=grid,
|
|
188
|
+
axes=axes,
|
|
189
|
+
to_plot=to_plot,
|
|
190
|
+
**kwargs,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
for result in to_plot:
|
|
194
|
+
axes = result.plot(
|
|
195
|
+
x=x,
|
|
196
|
+
y=y,
|
|
197
|
+
plotter=plotter,
|
|
198
|
+
label=label,
|
|
199
|
+
grid=grid,
|
|
200
|
+
axes=axes,
|
|
201
|
+
**kwargs,
|
|
202
|
+
)
|
|
203
|
+
return axes
|
|
204
|
+
|
|
205
|
+
def _to_plot(
|
|
206
|
+
self,
|
|
207
|
+
idx_to_plot: Iterable[int] | None = None,
|
|
208
|
+
id_to_plot: Iterable[int] | None = None,
|
|
209
|
+
to_plot: Iterable[SimulationResults] | None = None,
|
|
210
|
+
) -> list[SimulationResults]:
|
|
211
|
+
"""Give the :class:`.SimulationResults` to plot.
|
|
212
|
+
|
|
213
|
+
When all arguments are ``None``, we return all the stored
|
|
214
|
+
:class:`.SimulationResults`.
|
|
215
|
+
|
|
216
|
+
Parameters
|
|
217
|
+
----------
|
|
218
|
+
idx_to_plot :
|
|
219
|
+
Positions in the list of :class:`.SimulationResults` sorted by
|
|
220
|
+
growing accelerating field / power. Not considered if
|
|
221
|
+
``id_to_plot`` or ``to_plot`` is provided.
|
|
222
|
+
id_to_plot :
|
|
223
|
+
ID attributes; takes preceedence over ``idx_to_plot``. Not
|
|
224
|
+
considered if ``to_plot`` is provided.
|
|
225
|
+
to_plot :
|
|
226
|
+
Objects to plot; takes preceedence over ``idx_to_plot`` and
|
|
227
|
+
``id_to_plot``.
|
|
228
|
+
|
|
229
|
+
"""
|
|
230
|
+
if to_plot is not None:
|
|
231
|
+
return [r for r in to_plot]
|
|
232
|
+
if id_to_plot is not None:
|
|
233
|
+
return [self.get_by_id(id) for id in id_to_plot]
|
|
234
|
+
if idx_to_plot is None:
|
|
235
|
+
idx_to_plot = range(len(self))
|
|
236
|
+
return [self._results[idx] for idx in idx_to_plot]
|
|
237
|
+
|
|
238
|
+
def _plot_0d(
|
|
239
|
+
self,
|
|
240
|
+
x: DATA_0D_t,
|
|
241
|
+
y: DATA_0D_t,
|
|
242
|
+
plotter: Plotter,
|
|
243
|
+
label: str | Literal["auto"] | None = None,
|
|
244
|
+
grid: bool = True,
|
|
245
|
+
axes: Any | None = None,
|
|
246
|
+
to_plot: Sequence[SimulationResults] | None = None,
|
|
247
|
+
color: Any = "auto",
|
|
248
|
+
**kwargs,
|
|
249
|
+
) -> Any:
|
|
250
|
+
"""Concatenate and plot 0D data from ``results``.
|
|
251
|
+
|
|
252
|
+
Parameters
|
|
253
|
+
----------
|
|
254
|
+
x, y :
|
|
255
|
+
Name of properties to plot.
|
|
256
|
+
plotter :
|
|
257
|
+
Object to use for plot.
|
|
258
|
+
label :
|
|
259
|
+
If provided, overrides the legend. Useful when several simulations
|
|
260
|
+
are shown on the same plot. Use the magic keyword ``"auto"`` to
|
|
261
|
+
legend with a short description of current object.
|
|
262
|
+
grid :
|
|
263
|
+
If grid should be plotted. Default is True.
|
|
264
|
+
axes :
|
|
265
|
+
Axes to re-use, if provided.
|
|
266
|
+
to_plot :
|
|
267
|
+
The objects to plot. If not given, plot all the objects.
|
|
268
|
+
color :
|
|
269
|
+
Color for the plot. If "auto", we use the
|
|
270
|
+
:attr:`.SimulationsResults._color` attribute.
|
|
271
|
+
kwargs :
|
|
272
|
+
Other keyword arguments passed to the :meth:`.Plotter.plot` method.
|
|
273
|
+
|
|
274
|
+
Returns
|
|
275
|
+
-------
|
|
276
|
+
Any
|
|
277
|
+
Objects created by the :meth:`.Plotter.plot`.
|
|
278
|
+
|
|
279
|
+
"""
|
|
280
|
+
data = self._to_pandas(x, y, results=to_plot)
|
|
281
|
+
|
|
282
|
+
if label == "auto":
|
|
283
|
+
n_simulations = f"{len(self)} simulations"
|
|
284
|
+
if to_plot is not None:
|
|
285
|
+
n_simulations = f"{len(to_plot)} simulations"
|
|
286
|
+
label = f"SimulationsResults ({n_simulations})"
|
|
287
|
+
|
|
288
|
+
axes, color = plotter.plot(
|
|
289
|
+
data,
|
|
290
|
+
x=x,
|
|
291
|
+
y=y,
|
|
292
|
+
grid=grid,
|
|
293
|
+
axes=axes,
|
|
294
|
+
label=label,
|
|
295
|
+
color=self._color if color == "auto" else color,
|
|
296
|
+
**kwargs,
|
|
297
|
+
)
|
|
298
|
+
if self._color is None:
|
|
299
|
+
self._color = color
|
|
300
|
+
return axes
|
|
301
|
+
|
|
302
|
+
def _to_pandas(
|
|
303
|
+
self,
|
|
304
|
+
*args: DATA_0D_t,
|
|
305
|
+
results: Sequence[SimulationResults] | None = None,
|
|
306
|
+
) -> pd.DataFrame:
|
|
307
|
+
"""Concatenate all attributes which name is in ``args`` to a dataframe.
|
|
308
|
+
|
|
309
|
+
.. todo::
|
|
310
|
+
Review this and its error handling
|
|
311
|
+
|
|
312
|
+
Parameters
|
|
313
|
+
----------
|
|
314
|
+
args :
|
|
315
|
+
Name of :class:`.SimulationResults` arguments to concatenate.
|
|
316
|
+
results :
|
|
317
|
+
If given, we concatenate only the data frome these
|
|
318
|
+
:class:`.SimulationResults`.
|
|
319
|
+
|
|
320
|
+
Returns
|
|
321
|
+
-------
|
|
322
|
+
pandas.DataFrame
|
|
323
|
+
Holds the values of every element of ``args``.
|
|
324
|
+
|
|
325
|
+
Raises
|
|
326
|
+
------
|
|
327
|
+
ValueError:
|
|
328
|
+
If one of the ``args`` is an array or is missing.
|
|
329
|
+
|
|
330
|
+
"""
|
|
331
|
+
if results is None:
|
|
332
|
+
results = self.to_list
|
|
333
|
+
|
|
334
|
+
data: dict[str, list[float]] = {}
|
|
335
|
+
|
|
336
|
+
for arg in args:
|
|
337
|
+
concat: list[float] = []
|
|
338
|
+
for result in results:
|
|
339
|
+
value = getattr(result, arg, None)
|
|
340
|
+
if not isinstance(value, (float, int)):
|
|
341
|
+
logging.debug(
|
|
342
|
+
f"The {arg} attribute of {result} is not a float but a"
|
|
343
|
+
f" {type(value)}, so it was not added to the "
|
|
344
|
+
"dataframe."
|
|
345
|
+
)
|
|
346
|
+
continue
|
|
347
|
+
concat.append(value)
|
|
348
|
+
data[arg] = concat
|
|
349
|
+
|
|
350
|
+
lengths = {key: len(value) for key, value in data.items()}
|
|
351
|
+
if len(set(lengths.values())) > 1:
|
|
352
|
+
raise ValueError(
|
|
353
|
+
"All the lists in data must have the same length. Maybe "
|
|
354
|
+
f"{results = } is a Generator? Or maybe one of the keys was "
|
|
355
|
+
"not found in one or more of the SimulationResults?\n"
|
|
356
|
+
f"{lengths = }"
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
try:
|
|
360
|
+
return pd.DataFrame(data)
|
|
361
|
+
except ValueError as e:
|
|
362
|
+
raise ValueError(
|
|
363
|
+
f"Could not get a data, creating malformed dataframe.\n{e}"
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
def fit_alpha(
|
|
367
|
+
self,
|
|
368
|
+
fitting_periods: int,
|
|
369
|
+
running_mean: bool = True,
|
|
370
|
+
log_fit: bool = True,
|
|
371
|
+
minimum_final_number_of_electrons: int = 0,
|
|
372
|
+
bounds: tuple[list[float], list[float]] = (
|
|
373
|
+
[1e-10, -10.0],
|
|
374
|
+
[np.inf, 10.0],
|
|
375
|
+
),
|
|
376
|
+
initial_values: list[float] = [0.0, 0.0],
|
|
377
|
+
**kwargs,
|
|
378
|
+
) -> None:
|
|
379
|
+
"""Fit exp growth factor.
|
|
380
|
+
|
|
381
|
+
Parameters
|
|
382
|
+
----------
|
|
383
|
+
fitting_periods :
|
|
384
|
+
Number of periods over which the exp growth is searched. Longer is
|
|
385
|
+
better, but you do not want to start the fit before the exp growth
|
|
386
|
+
starts.
|
|
387
|
+
running_mean :
|
|
388
|
+
To tell if you want to average the number of particles over one
|
|
389
|
+
period. Highly recommended.
|
|
390
|
+
log_fit :
|
|
391
|
+
To perform the fit on :func:`exp_growth_log` rather than
|
|
392
|
+
:func:`exp_growth`. The default is True, as it generally shows
|
|
393
|
+
better convergence.
|
|
394
|
+
minimum_final_number_of_electrons :
|
|
395
|
+
Under this final number of electrons, we do no bother finding the
|
|
396
|
+
exp growth factor and set all fit parameters to ``NaN``.
|
|
397
|
+
bounds :
|
|
398
|
+
Upper bound and lower bound for the two variables: initial number
|
|
399
|
+
of electrons, exp growth factor.
|
|
400
|
+
initial_values: list[float], optional
|
|
401
|
+
Initial values for the two variables: initial number of electrons,
|
|
402
|
+
exp growth factor.
|
|
403
|
+
|
|
404
|
+
"""
|
|
405
|
+
for result in self:
|
|
406
|
+
result.fit_alpha(
|
|
407
|
+
fitting_periods=fitting_periods,
|
|
408
|
+
running_mean=running_mean,
|
|
409
|
+
log_fit=log_fit,
|
|
410
|
+
minimum_final_number_of_electrons=minimum_final_number_of_electrons,
|
|
411
|
+
bounds=bounds,
|
|
412
|
+
initial_values=initial_values,
|
|
413
|
+
**kwargs,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
def save(
|
|
417
|
+
self,
|
|
418
|
+
filepath: Path | str,
|
|
419
|
+
*to_save: DATA_0D_t | DATA_1D_t,
|
|
420
|
+
sep: str = ",",
|
|
421
|
+
merge_on: DATA_0D_t | DATA_1D_t | None = None,
|
|
422
|
+
**kwargs,
|
|
423
|
+
) -> None:
|
|
424
|
+
"""Concatenate all data named ``to_save`` and save it to a file.
|
|
425
|
+
|
|
426
|
+
Parameters
|
|
427
|
+
----------
|
|
428
|
+
filepath :
|
|
429
|
+
Where to save the file.
|
|
430
|
+
to_save :
|
|
431
|
+
The list of quantities to save.
|
|
432
|
+
sep :
|
|
433
|
+
Column separator. Default is a comma.
|
|
434
|
+
merge_on :
|
|
435
|
+
If provided, the different dataframe will be merged against this
|
|
436
|
+
column. Typical usage is ``merge_on="time"`` to have a single time
|
|
437
|
+
column.
|
|
438
|
+
|
|
439
|
+
"""
|
|
440
|
+
if isinstance(filepath, str):
|
|
441
|
+
filepath = Path(filepath)
|
|
442
|
+
|
|
443
|
+
df = self._format_for_save(*to_save, merge_on=merge_on, **kwargs)
|
|
444
|
+
|
|
445
|
+
df.to_csv(filepath, sep=sep, **kwargs)
|
|
446
|
+
logging.info(f"File saved to {filepath.absolute()}")
|
|
447
|
+
return
|
|
448
|
+
|
|
449
|
+
def _format_for_save(
|
|
450
|
+
self,
|
|
451
|
+
*to_save: DATA_0D_t | DATA_1D_t,
|
|
452
|
+
merge_on: DATA_0D_t | DATA_1D_t | None = None,
|
|
453
|
+
**kwargs,
|
|
454
|
+
) -> pd.DataFrame:
|
|
455
|
+
"""Concatanate desired data into a single dataframe.
|
|
456
|
+
|
|
457
|
+
Parameters
|
|
458
|
+
----------
|
|
459
|
+
to_save :
|
|
460
|
+
The list of quantities to save.
|
|
461
|
+
merge_on :
|
|
462
|
+
If provided, the different dataframe will be merged against this
|
|
463
|
+
column. Typical usage is ``merge_on="time"`` to have a single time
|
|
464
|
+
column.
|
|
465
|
+
|
|
466
|
+
Returns
|
|
467
|
+
-------
|
|
468
|
+
pd.DataFrame
|
|
469
|
+
Contains all the data to save, with proper format.
|
|
470
|
+
|
|
471
|
+
"""
|
|
472
|
+
if all(arg in DATA_0D for arg in to_save):
|
|
473
|
+
return self._to_pandas(*to_save, **kwargs) # type: ignore
|
|
474
|
+
|
|
475
|
+
all_df = [x.to_pandas(*to_save, **kwargs) for x in self.to_list]
|
|
476
|
+
|
|
477
|
+
if merge_on is None:
|
|
478
|
+
return pd.concat(all_df, axis=1)
|
|
479
|
+
|
|
480
|
+
assert merge_on in to_save, (
|
|
481
|
+
f"Cannot merge dataframes on column {merge_on} because it does not"
|
|
482
|
+
f" exist. Please add it to {to_save = }"
|
|
483
|
+
)
|
|
484
|
+
renamed_dfs = []
|
|
485
|
+
for df, res in zip(all_df, self.to_list):
|
|
486
|
+
new_cols = {
|
|
487
|
+
col: f"{col}_{res.id}" for col in to_save if col != merge_on
|
|
488
|
+
}
|
|
489
|
+
renamed_dfs.append(df.rename(columns=new_cols))
|
|
490
|
+
merged_df = reduce(
|
|
491
|
+
lambda left, right: left.merge(right, on=merge_on), renamed_dfs
|
|
492
|
+
)
|
|
493
|
+
return merged_df
|
|
494
|
+
|
|
495
|
+
def parameter_values(
|
|
496
|
+
self,
|
|
497
|
+
*parameters: str,
|
|
498
|
+
default: Any = None,
|
|
499
|
+
allow_missing: bool = False,
|
|
500
|
+
) -> dict[str, set]:
|
|
501
|
+
"""Get the existing values of all ``parameters`` in the stored results.
|
|
502
|
+
|
|
503
|
+
If no parameters are given, return all parameters with their possible
|
|
504
|
+
values.
|
|
505
|
+
|
|
506
|
+
Parameters
|
|
507
|
+
----------
|
|
508
|
+
*parameters :
|
|
509
|
+
Name of the parameter(s) to get. Must be key in the ``parameters``
|
|
510
|
+
dictionary of the stored :class:`.SimulationResult`. If empty, all
|
|
511
|
+
parameters found in any result are returned.
|
|
512
|
+
default :
|
|
513
|
+
The fallback value when the ``parameter`` is not a key of a
|
|
514
|
+
:attr:`.SimulationResult.parameters`.
|
|
515
|
+
allow_missing :
|
|
516
|
+
If True, an error is raised when ``default`` is present in the
|
|
517
|
+
output set.
|
|
518
|
+
|
|
519
|
+
Returns
|
|
520
|
+
-------
|
|
521
|
+
all_values : dict[str, set]
|
|
522
|
+
Keys are all the ``parameters``. Values corresponding values in
|
|
523
|
+
every storred :class:`.SimulationResult`.
|
|
524
|
+
|
|
525
|
+
"""
|
|
526
|
+
all_values = {}
|
|
527
|
+
|
|
528
|
+
if not parameters:
|
|
529
|
+
parameters = tuple(
|
|
530
|
+
{key for result in self.to_list for key in result.parameters}
|
|
531
|
+
)
|
|
532
|
+
for parameter in parameters:
|
|
533
|
+
values = set()
|
|
534
|
+
missing_results = []
|
|
535
|
+
|
|
536
|
+
for result in self.to_list:
|
|
537
|
+
value = result.parameters.get(parameter, default)
|
|
538
|
+
values.add(value)
|
|
539
|
+
if value is default:
|
|
540
|
+
missing_results.append(result)
|
|
541
|
+
|
|
542
|
+
all_values[parameter] = values
|
|
543
|
+
if not missing_results:
|
|
544
|
+
continue
|
|
545
|
+
|
|
546
|
+
logging.debug(
|
|
547
|
+
f"Missing {parameter} in {len(missing_results)} results"
|
|
548
|
+
)
|
|
549
|
+
if not allow_missing:
|
|
550
|
+
raise ValueError(
|
|
551
|
+
f"Missing {parameter} in the following SimulationResults:"
|
|
552
|
+
f"\n{missing_results}"
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
return all_values
|
|
556
|
+
|
|
557
|
+
def with_parameter_value(
|
|
558
|
+
self, parameters: dict[str, Any]
|
|
559
|
+
) -> Generator[SimulationResults, None, None]:
|
|
560
|
+
"""Yield :class:`.SimulationResults` matching given parameter values.
|
|
561
|
+
|
|
562
|
+
Parameters
|
|
563
|
+
----------
|
|
564
|
+
parameters :
|
|
565
|
+
Parameter names and their required values.
|
|
566
|
+
|
|
567
|
+
Yields
|
|
568
|
+
------
|
|
569
|
+
SimulationResults
|
|
570
|
+
:class:`.SimulationResults` instances whose parameters match the
|
|
571
|
+
given values.
|
|
572
|
+
|
|
573
|
+
"""
|
|
574
|
+
for result in self.to_list:
|
|
575
|
+
if all(
|
|
576
|
+
result.parameters.get(param) == value
|
|
577
|
+
for param, value in parameters.items()
|
|
578
|
+
):
|
|
579
|
+
yield result
|
|
580
|
+
|
|
581
|
+
def show(self) -> None:
|
|
582
|
+
"""Show the plots that were produced.
|
|
583
|
+
|
|
584
|
+
Useful for the bash interface.
|
|
585
|
+
|
|
586
|
+
"""
|
|
587
|
+
return self._plotter.show()
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
class SimulationsResultsFactory:
|
|
591
|
+
"""An object to create a :class:`.SimulationsResults`."""
|
|
592
|
+
|
|
593
|
+
def __init__(
|
|
594
|
+
self,
|
|
595
|
+
tool: Literal["SPARK3D", "CST"],
|
|
596
|
+
plotter: Plotter | None = None,
|
|
597
|
+
freq_ghz: float | None = None,
|
|
598
|
+
*args,
|
|
599
|
+
**kwargs,
|
|
600
|
+
) -> None:
|
|
601
|
+
"""Create object to easily generate simulation results.
|
|
602
|
+
|
|
603
|
+
Parameters
|
|
604
|
+
----------
|
|
605
|
+
tool: str
|
|
606
|
+
Name of the tool.
|
|
607
|
+
plotter :
|
|
608
|
+
Object to create the plots.
|
|
609
|
+
freq_ghz :
|
|
610
|
+
RF frequency in GHz. Used to compute RF period, which is mandatory
|
|
611
|
+
for exp growth fitting.
|
|
612
|
+
|
|
613
|
+
"""
|
|
614
|
+
if plotter is None:
|
|
615
|
+
plotter = DefaultPlotter()
|
|
616
|
+
self._tool = tool
|
|
617
|
+
self._plotter = plotter
|
|
618
|
+
self._freq_ghz = freq_ghz
|
|
619
|
+
|
|
620
|
+
def create(
|
|
621
|
+
self,
|
|
622
|
+
*,
|
|
623
|
+
filepath: Path | None = None,
|
|
624
|
+
master_folder: Path | None = None,
|
|
625
|
+
e_acc: np.ndarray | None = None,
|
|
626
|
+
**kwargs,
|
|
627
|
+
) -> SimulationsResults:
|
|
628
|
+
"""Create all the objects.
|
|
629
|
+
|
|
630
|
+
Parameters
|
|
631
|
+
----------
|
|
632
|
+
plotter :
|
|
633
|
+
An object to plot data.
|
|
634
|
+
filepath :
|
|
635
|
+
Filepath to a ``TXT`` or ``CSV`` file for SPARK3D.
|
|
636
|
+
master_folder :
|
|
637
|
+
Filepath to the folder holding all the ``mmdd-xxxxxxx`` folders for
|
|
638
|
+
CST.
|
|
639
|
+
e_acc :
|
|
640
|
+
The accelerating fields, used by SPARK3D.
|
|
641
|
+
kwargs :
|
|
642
|
+
Keyword arguments passed to the appropriate subclass of
|
|
643
|
+
:class:`.SimulationResultsFactory`.
|
|
644
|
+
|
|
645
|
+
Returns
|
|
646
|
+
-------
|
|
647
|
+
SimulationsResults
|
|
648
|
+
A concatenation of the individual simulations.
|
|
649
|
+
|
|
650
|
+
"""
|
|
651
|
+
individual_simulation_results = self._create_individual(
|
|
652
|
+
filepath=filepath,
|
|
653
|
+
master_folder=master_folder,
|
|
654
|
+
e_acc=e_acc,
|
|
655
|
+
plotter=self._plotter,
|
|
656
|
+
**kwargs,
|
|
657
|
+
)
|
|
658
|
+
simulations_results = SimulationsResults(
|
|
659
|
+
individual_simulation_results,
|
|
660
|
+
plotter=self._plotter,
|
|
661
|
+
)
|
|
662
|
+
return simulations_results
|
|
663
|
+
|
|
664
|
+
def _create_individual(
|
|
665
|
+
self,
|
|
666
|
+
*,
|
|
667
|
+
plotter: Plotter,
|
|
668
|
+
filepath: Path | None = None,
|
|
669
|
+
master_folder: Path | None = None,
|
|
670
|
+
e_acc: np.ndarray | None = None,
|
|
671
|
+
**kwargs,
|
|
672
|
+
) -> Sequence[SimulationResults]:
|
|
673
|
+
"""Create several individual :class:`.SimulationResults`.
|
|
674
|
+
|
|
675
|
+
Parameters
|
|
676
|
+
----------
|
|
677
|
+
plotter :
|
|
678
|
+
An object to plot data.
|
|
679
|
+
filepath :
|
|
680
|
+
Filepath to a ``TXT`` or ``CSV`` file for SPARK3D.
|
|
681
|
+
master_folder :
|
|
682
|
+
Filepath to the folder holding all the ``mmdd-xxxxxxx`` folders for
|
|
683
|
+
CST.
|
|
684
|
+
e_acc :
|
|
685
|
+
The accelerating fields, used by SPARK3D.
|
|
686
|
+
kwargs :
|
|
687
|
+
Keyword arguments passed to the appropriate subclass of
|
|
688
|
+
:class:`.SimulationResultsFactory`.
|
|
689
|
+
|
|
690
|
+
Returns
|
|
691
|
+
-------
|
|
692
|
+
Sequence[SimulationResults]
|
|
693
|
+
The individual :class:`.SimulationResults`.
|
|
694
|
+
|
|
695
|
+
Raises
|
|
696
|
+
------
|
|
697
|
+
NotImplementedError:
|
|
698
|
+
When ``self._tool`` is not in ``("CST", "SPARK3D")``.
|
|
699
|
+
|
|
700
|
+
"""
|
|
701
|
+
if self._tool == "CST":
|
|
702
|
+
assert (
|
|
703
|
+
master_folder is not None
|
|
704
|
+
), "You must provide the path to the CST mmdd-xxxxxxx folders"
|
|
705
|
+
assert master_folder.is_dir(), f"{master_folder = } must exist"
|
|
706
|
+
factory = CSTResultsFactory(
|
|
707
|
+
plotter=plotter, freq_ghz=self._freq_ghz, **kwargs
|
|
708
|
+
)
|
|
709
|
+
return factory.from_simulation_folders(master_folder=master_folder)
|
|
710
|
+
|
|
711
|
+
if self._tool == "SPARK3D":
|
|
712
|
+
assert (
|
|
713
|
+
filepath is not None
|
|
714
|
+
), "You must provide the path to the SPARK3D file results."
|
|
715
|
+
assert filepath.is_file(), f"{filepath = } must exist"
|
|
716
|
+
assert isinstance(e_acc, np.ndarray), (
|
|
717
|
+
"You must provide an array of accelerating fields. You gave "
|
|
718
|
+
f"{e_acc = }"
|
|
719
|
+
)
|
|
720
|
+
factory = Spark3DResultsFactory(
|
|
721
|
+
plotter=plotter, freq_ghz=self._freq_ghz, **kwargs
|
|
722
|
+
)
|
|
723
|
+
return factory.from_file(filepath, e_acc=e_acc)
|
|
724
|
+
raise NotImplementedError(f"The tool {self._tool} is not implemented.")
|