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,722 @@
|
|
|
1
|
+
"""Define :class:`ParticleMonitor`.
|
|
2
|
+
|
|
3
|
+
This dictionary-based object holds :class:`Particle` objects. Keys of the
|
|
4
|
+
dictionary are the particle id of the :class:`Particle`.
|
|
5
|
+
|
|
6
|
+
.. todo::
|
|
7
|
+
Raise error when folder is not found.
|
|
8
|
+
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Callable, Collection, Generator
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Literal, Self
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
import vedo
|
|
21
|
+
from numpy._typing import NDArray
|
|
22
|
+
|
|
23
|
+
from simultipac.particle_monitor.particle import Particle, PartMonLine
|
|
24
|
+
from simultipac.plotter.default import DefaultPlotter
|
|
25
|
+
from simultipac.plotter.plotter import Plotter
|
|
26
|
+
from simultipac.types import PARTICLE_0D_t
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _load_particle_monitor_file(
|
|
30
|
+
filepath: Path, delimiter: str | None = None
|
|
31
|
+
) -> tuple[PartMonLine, ...]:
|
|
32
|
+
"""Load a single Particle Monitor file.
|
|
33
|
+
|
|
34
|
+
A Particle Monitor file holds the ID, position, momentum of every particle
|
|
35
|
+
alive at a specific time.
|
|
36
|
+
|
|
37
|
+
.. todo::
|
|
38
|
+
Type hints could be cleaner.
|
|
39
|
+
|
|
40
|
+
"""
|
|
41
|
+
n_header = 6
|
|
42
|
+
|
|
43
|
+
with open(filepath, encoding="utf-8") as file:
|
|
44
|
+
particles_info = tuple(
|
|
45
|
+
tuple(line.split(delimiter))
|
|
46
|
+
for i, line in enumerate(file)
|
|
47
|
+
if i > n_header
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
return particles_info # type: ignore
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
FILTER_KEY = Literal["seed", "emitted", "collision", "no collision"]
|
|
54
|
+
FILTER_FUNC = Callable[[Particle], bool]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ParticleMonitor(dict):
|
|
58
|
+
"""Holds all :class:`Particle` objects as values, particle id as keys.
|
|
59
|
+
|
|
60
|
+
Attributes
|
|
61
|
+
----------
|
|
62
|
+
max_time :
|
|
63
|
+
Time at which the simulation ended.
|
|
64
|
+
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
FILTERS: dict[str, FILTER_FUNC] = {
|
|
68
|
+
"_default": lambda _: True,
|
|
69
|
+
"seed": lambda p: p.source_id == 0,
|
|
70
|
+
"emitted": lambda p: p.source_id == 1,
|
|
71
|
+
"collision": lambda p: not p.alive_at_end,
|
|
72
|
+
"no collision": lambda p: p.alive_at_end,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
dict_of_parts: dict[int, Particle],
|
|
78
|
+
max_time: float,
|
|
79
|
+
stl_path: str | Path | None = None,
|
|
80
|
+
stl_alpha: float | None = None,
|
|
81
|
+
plotter: Plotter | None = None,
|
|
82
|
+
**kwargs,
|
|
83
|
+
) -> None:
|
|
84
|
+
"""Create the object, ordered list of filepaths beeing provided.
|
|
85
|
+
|
|
86
|
+
Also handle mesh related operations: collision/emission angles
|
|
87
|
+
calculation.
|
|
88
|
+
|
|
89
|
+
Parameters
|
|
90
|
+
----------
|
|
91
|
+
dict_of_parts :
|
|
92
|
+
Dictionary which values are :class:`.Particle` instances and keys
|
|
93
|
+
are the associated unique ID.
|
|
94
|
+
max_time :
|
|
95
|
+
Simulation end time. Used to determine which particles were alive
|
|
96
|
+
at the end of the simulation.
|
|
97
|
+
stl_path :
|
|
98
|
+
Path to the structure mesh. In particular, used to compute the
|
|
99
|
+
collision and emission angles.
|
|
100
|
+
stl_alpha :
|
|
101
|
+
Mesh transparency setting.
|
|
102
|
+
plotter :
|
|
103
|
+
Object to create the plots.
|
|
104
|
+
|
|
105
|
+
"""
|
|
106
|
+
if plotter is None:
|
|
107
|
+
plotter = DefaultPlotter()
|
|
108
|
+
self._plotter = plotter
|
|
109
|
+
self._stl_path = stl_path
|
|
110
|
+
self._mesh: vedo.Mesh
|
|
111
|
+
self._kwargs = kwargs
|
|
112
|
+
super().__init__(dict_of_parts)
|
|
113
|
+
|
|
114
|
+
self.max_time = max_time
|
|
115
|
+
for particle in self.values():
|
|
116
|
+
particle.determine_if_alive_at_end(self.max_time)
|
|
117
|
+
|
|
118
|
+
if stl_path is not None:
|
|
119
|
+
self._mesh = self._load_mesh(
|
|
120
|
+
stl_path, stl_alpha=stl_alpha, **kwargs
|
|
121
|
+
)
|
|
122
|
+
self.compute_collision_angles(self._mesh)
|
|
123
|
+
return
|
|
124
|
+
|
|
125
|
+
def __repr__(self) -> str:
|
|
126
|
+
"""Return how the object was initialized."""
|
|
127
|
+
return (
|
|
128
|
+
f"ParticleMonitor(dict_of_parts={len(self)} particles, "
|
|
129
|
+
f"stl_path={self._stl_path}, plotter={self._plotter}, kwargs="
|
|
130
|
+
f"{self._kwargs})"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def from_folder(
|
|
135
|
+
cls,
|
|
136
|
+
folder: str | Path,
|
|
137
|
+
delimiter: str | None = None,
|
|
138
|
+
stl_path: str | Path | None = None,
|
|
139
|
+
stl_alpha: float | None = None,
|
|
140
|
+
plotter: Plotter | None = None,
|
|
141
|
+
load_first_n_particles: int | None = None,
|
|
142
|
+
particle_monitor_ignore: Collection[str] = (".swp",),
|
|
143
|
+
**kwargs,
|
|
144
|
+
) -> Self:
|
|
145
|
+
"""Load all the particle monitor files and create object.
|
|
146
|
+
|
|
147
|
+
Parameters
|
|
148
|
+
----------
|
|
149
|
+
folder :
|
|
150
|
+
Where all the CST particle monitor files are stored.
|
|
151
|
+
delimiter :
|
|
152
|
+
Delimiter between columns.
|
|
153
|
+
stl_path :
|
|
154
|
+
Path to the mesh file, saved as ``STL``.
|
|
155
|
+
stl_alpha :
|
|
156
|
+
Transparency for the 3D mesh.
|
|
157
|
+
plotter :
|
|
158
|
+
Object realizing the plots.
|
|
159
|
+
load_first_n_particles :
|
|
160
|
+
To only load the first particles that are found in the ``folder``.
|
|
161
|
+
particle_monitor_ignore :
|
|
162
|
+
File extensions to skip when exploring the particle monitor folder.
|
|
163
|
+
|
|
164
|
+
Returns
|
|
165
|
+
-------
|
|
166
|
+
particle_monitor : ParticleMonitor
|
|
167
|
+
Instantiated object.
|
|
168
|
+
|
|
169
|
+
"""
|
|
170
|
+
if stl_path is None:
|
|
171
|
+
raise ValueError
|
|
172
|
+
if isinstance(folder, str):
|
|
173
|
+
folder = Path(folder)
|
|
174
|
+
dict_of_parts: dict[int, Particle] = {}
|
|
175
|
+
|
|
176
|
+
filepaths, max_time = _sorted_particle_monitor_files(
|
|
177
|
+
folder, particle_monitor_ignore=particle_monitor_ignore
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
for filepath in filepaths:
|
|
181
|
+
particles_info = _load_particle_monitor_file(
|
|
182
|
+
filepath, delimiter=delimiter
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
for part_mon_line in particles_info:
|
|
186
|
+
particle_id = int(part_mon_line[10])
|
|
187
|
+
|
|
188
|
+
if (
|
|
189
|
+
load_first_n_particles is not None
|
|
190
|
+
and particle_id > load_first_n_particles
|
|
191
|
+
):
|
|
192
|
+
continue
|
|
193
|
+
|
|
194
|
+
if particle_id in dict_of_parts:
|
|
195
|
+
dict_of_parts[particle_id].add_a_file(part_mon_line)
|
|
196
|
+
continue
|
|
197
|
+
|
|
198
|
+
dict_of_parts[particle_id] = Particle(part_mon_line)
|
|
199
|
+
|
|
200
|
+
for particle in dict_of_parts.values():
|
|
201
|
+
particle.finalize()
|
|
202
|
+
particle.extrapolate_pos_and_mom_one_time_step_further()
|
|
203
|
+
|
|
204
|
+
return cls(
|
|
205
|
+
dict_of_parts,
|
|
206
|
+
stl_path=stl_path,
|
|
207
|
+
stl_alpha=stl_alpha,
|
|
208
|
+
plotter=plotter,
|
|
209
|
+
max_time=max_time,
|
|
210
|
+
**kwargs,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def seed_electrons(self) -> dict[int, Particle]:
|
|
215
|
+
"""Return only seed electrons."""
|
|
216
|
+
return _filter_source_id(self, 0)
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def emitted_electrons(self) -> dict[int, Particle]:
|
|
220
|
+
"""Return only emitted electrons."""
|
|
221
|
+
return _filter_source_id(self, 1)
|
|
222
|
+
|
|
223
|
+
def __str__(self) -> str:
|
|
224
|
+
"""Resume information on the simulation."""
|
|
225
|
+
n_total_particles = len(self.keys())
|
|
226
|
+
n_seed_electrons = len(self.seed_electrons.keys())
|
|
227
|
+
n_emitted_electrons = len(self.emitted_electrons.keys())
|
|
228
|
+
n_collisions = len(_filter_out_alive_at_end(self).keys())
|
|
229
|
+
n_alive_at_end = len(_filter_out_dead_at_end(self).keys())
|
|
230
|
+
out = f"This simulation involved {n_total_particles} electrons."
|
|
231
|
+
out += f"\n\t{n_seed_electrons} where seed electrons."
|
|
232
|
+
out += f"\n\t{n_emitted_electrons} where emitted electrons."
|
|
233
|
+
out += f"\n\t{n_alive_at_end} where still alive at end of simulation."
|
|
234
|
+
out += f"\n\tThere was {n_collisions} collisions."
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
def emission_energies(
|
|
238
|
+
self, source_id: int | None = None
|
|
239
|
+
) -> NDArray[np.float64]:
|
|
240
|
+
"""Get emission energies of all or only a subset of particles."""
|
|
241
|
+
subset = self
|
|
242
|
+
if source_id is not None:
|
|
243
|
+
subset = _filter_source_id(subset, source_id)
|
|
244
|
+
out = [part.emission_energy for part in subset.values()]
|
|
245
|
+
return np.array(out)
|
|
246
|
+
|
|
247
|
+
def collision_energies(
|
|
248
|
+
self,
|
|
249
|
+
source_id: int | None = None,
|
|
250
|
+
extrapolation: bool = True,
|
|
251
|
+
remove_alive_at_end: bool = True,
|
|
252
|
+
) -> NDArray[np.float64]:
|
|
253
|
+
"""Get all collision energies in :unit:`eV`.
|
|
254
|
+
|
|
255
|
+
Parameters
|
|
256
|
+
----------
|
|
257
|
+
source_id : int | None, optional
|
|
258
|
+
If set, we only take particles which source_id is ``source_id``.
|
|
259
|
+
The default is None.
|
|
260
|
+
extrapolation : bool, optional
|
|
261
|
+
If True, we extrapolate over the last time steps to refine the
|
|
262
|
+
collision energy. Otherwise, we simply take the last known energy
|
|
263
|
+
of the particle. The default is True.
|
|
264
|
+
remove_alive_at_end : bool, optional
|
|
265
|
+
To remove particles alive at the end of the simulation (did not
|
|
266
|
+
impact a wall). The default is True.
|
|
267
|
+
|
|
268
|
+
"""
|
|
269
|
+
subset = self
|
|
270
|
+
if source_id is not None:
|
|
271
|
+
subset = _filter_source_id(subset, source_id)
|
|
272
|
+
if remove_alive_at_end:
|
|
273
|
+
subset = _filter_out_alive_at_end(subset)
|
|
274
|
+
|
|
275
|
+
out = [
|
|
276
|
+
part.collision_energy(extrapolation) for part in subset.values()
|
|
277
|
+
]
|
|
278
|
+
return np.array(out)
|
|
279
|
+
|
|
280
|
+
def emission_angles(
|
|
281
|
+
self,
|
|
282
|
+
source_id: int | None = None,
|
|
283
|
+
extrapolation: bool = True,
|
|
284
|
+
) -> NDArray[np.float64]:
|
|
285
|
+
"""Get all emission angles in :unit:`deg`.
|
|
286
|
+
|
|
287
|
+
Parameters
|
|
288
|
+
----------
|
|
289
|
+
source_id : int | None, optional
|
|
290
|
+
If set, we only take particles which source_id is ``source_id``.
|
|
291
|
+
The default is None.
|
|
292
|
+
extrapolation : bool, optional
|
|
293
|
+
If True, we extrapolate over the last time steps to refine the
|
|
294
|
+
collision energy. Otherwise, we simply take the last known energy
|
|
295
|
+
of the particle. The default is True.
|
|
296
|
+
remove_alive_at_end : bool, optional
|
|
297
|
+
To remove particles alive at the end of the simulation (did not
|
|
298
|
+
impact a wall). The default is True.
|
|
299
|
+
|
|
300
|
+
Returns
|
|
301
|
+
-------
|
|
302
|
+
out : NDArray[np.float64]
|
|
303
|
+
Emission angles in degrees.
|
|
304
|
+
|
|
305
|
+
"""
|
|
306
|
+
raise NotImplementedError
|
|
307
|
+
subset = self
|
|
308
|
+
if source_id is not None:
|
|
309
|
+
subset = _filter_source_id(subset, source_id)
|
|
310
|
+
out = [part.emission_angle for part in subset.values()]
|
|
311
|
+
return np.array(out)
|
|
312
|
+
|
|
313
|
+
def collision_angles(
|
|
314
|
+
self,
|
|
315
|
+
source_id: int | None = None,
|
|
316
|
+
remove_alive_at_end: bool = True,
|
|
317
|
+
) -> NDArray[np.float64]:
|
|
318
|
+
"""Get all collision angles in :unit:`deg`.
|
|
319
|
+
|
|
320
|
+
Parameters
|
|
321
|
+
----------
|
|
322
|
+
source_id :
|
|
323
|
+
If set, we only take particles which source_id is ``source_id``.
|
|
324
|
+
The default is None.
|
|
325
|
+
remove_alive_at_end :
|
|
326
|
+
To remove particles alive at the end of the simulation (did not
|
|
327
|
+
impact a wall). The default is True.
|
|
328
|
+
|
|
329
|
+
"""
|
|
330
|
+
subset = self
|
|
331
|
+
if source_id is not None:
|
|
332
|
+
subset = _filter_source_id(subset, source_id)
|
|
333
|
+
if remove_alive_at_end:
|
|
334
|
+
subset = _filter_out_alive_at_end(subset)
|
|
335
|
+
|
|
336
|
+
out = [part.collision_angle for part in subset.values()]
|
|
337
|
+
return np.array(out)
|
|
338
|
+
|
|
339
|
+
def last_known_position(
|
|
340
|
+
self,
|
|
341
|
+
source_id: int | None = None,
|
|
342
|
+
remove_alive_at_end: bool = True,
|
|
343
|
+
) -> NDArray[np.float64]:
|
|
344
|
+
"""Get the last recorded position of every particle.
|
|
345
|
+
|
|
346
|
+
Parameters
|
|
347
|
+
----------
|
|
348
|
+
source_id : int | None, optional
|
|
349
|
+
If set, we only take particles which source_id is ``source_id``.
|
|
350
|
+
The default is None.
|
|
351
|
+
to_numpy : bool, optional
|
|
352
|
+
If True, output list is transformed to an array. The default is
|
|
353
|
+
True.
|
|
354
|
+
remove_alive_at_end : bool, optional
|
|
355
|
+
To remove particles alive at the end of the simulation (did not
|
|
356
|
+
impact a wall). The default is True.
|
|
357
|
+
|
|
358
|
+
Returns
|
|
359
|
+
-------
|
|
360
|
+
out : NDArray[np.float64]
|
|
361
|
+
Last known position in :unit:`mm` of every particle.
|
|
362
|
+
|
|
363
|
+
"""
|
|
364
|
+
subset = self
|
|
365
|
+
if source_id is not None:
|
|
366
|
+
subset = _filter_source_id(subset, source_id)
|
|
367
|
+
if remove_alive_at_end:
|
|
368
|
+
subset = _filter_out_alive_at_end(subset)
|
|
369
|
+
|
|
370
|
+
out = [part.position.last for part in subset.values()]
|
|
371
|
+
return np.array(out)
|
|
372
|
+
|
|
373
|
+
def last_known_direction(
|
|
374
|
+
self,
|
|
375
|
+
source_id: int | None = None,
|
|
376
|
+
normalize: bool = True,
|
|
377
|
+
remove_alive_at_end: bool = True,
|
|
378
|
+
) -> NDArray[np.float64]:
|
|
379
|
+
"""
|
|
380
|
+
Get the last recorded direction of every particle.
|
|
381
|
+
|
|
382
|
+
.. todo::
|
|
383
|
+
Why did I choose to compute position difference rather than just
|
|
384
|
+
taking the momentum array when not normalizing???
|
|
385
|
+
|
|
386
|
+
Parameters
|
|
387
|
+
----------
|
|
388
|
+
source_id : int | None, optional
|
|
389
|
+
If set, we only take particles which source_id is ``source_id``.
|
|
390
|
+
The default is None.
|
|
391
|
+
normalize : bool, optional
|
|
392
|
+
To normalize the direction vector. The default is True.
|
|
393
|
+
remove_alive_at_end : bool, optional
|
|
394
|
+
To remove particles alive at the end of the simulation (did not
|
|
395
|
+
impact a wall). The default is True.
|
|
396
|
+
|
|
397
|
+
Returns
|
|
398
|
+
-------
|
|
399
|
+
out : NDArray[np.float64]
|
|
400
|
+
Last known moment vector of every particle.
|
|
401
|
+
|
|
402
|
+
"""
|
|
403
|
+
subset = self
|
|
404
|
+
if source_id is not None:
|
|
405
|
+
subset = _filter_source_id(subset, source_id)
|
|
406
|
+
if remove_alive_at_end:
|
|
407
|
+
subset = _filter_out_alive_at_end(subset)
|
|
408
|
+
|
|
409
|
+
out = [part.momentum.last for part in subset.values()]
|
|
410
|
+
|
|
411
|
+
if normalize:
|
|
412
|
+
out = [mom / np.linalg.norm(mom) for mom in out]
|
|
413
|
+
|
|
414
|
+
return np.array(out)
|
|
415
|
+
|
|
416
|
+
def compute_collision_angles(self, mesh: vedo.Mesh, **kwargs) -> None:
|
|
417
|
+
"""Find all collisions."""
|
|
418
|
+
mesh.compute_normals(points=False, cells=True)
|
|
419
|
+
for particle in self.values():
|
|
420
|
+
particle.find_collision(mesh, **kwargs)
|
|
421
|
+
particle.compute_collision_angle(mesh)
|
|
422
|
+
|
|
423
|
+
def hist(
|
|
424
|
+
self,
|
|
425
|
+
x: PARTICLE_0D_t,
|
|
426
|
+
bins: int = 200,
|
|
427
|
+
hist_range: tuple[float, float] | None = None,
|
|
428
|
+
plotter: Plotter | None = None,
|
|
429
|
+
filter: FILTER_KEY | FILTER_FUNC | None = None,
|
|
430
|
+
title: str | None = None,
|
|
431
|
+
**kwargs,
|
|
432
|
+
) -> Any:
|
|
433
|
+
"""Create a histogram.
|
|
434
|
+
|
|
435
|
+
Parameters
|
|
436
|
+
----------
|
|
437
|
+
x :
|
|
438
|
+
Name of the data to plot.
|
|
439
|
+
bins :
|
|
440
|
+
Number of histogram bins.
|
|
441
|
+
hist_range :
|
|
442
|
+
Lower and upper value for the histogram.
|
|
443
|
+
plotter :
|
|
444
|
+
Object creating the plots.
|
|
445
|
+
filter :
|
|
446
|
+
To plot only some of the particles.
|
|
447
|
+
title :
|
|
448
|
+
Figure title. If not provided, we take a default according to the
|
|
449
|
+
value of ``filter``.
|
|
450
|
+
|
|
451
|
+
"""
|
|
452
|
+
if plotter is None:
|
|
453
|
+
plotter = self._plotter
|
|
454
|
+
data = self.to_pandas(x, filter=filter)
|
|
455
|
+
|
|
456
|
+
if title is None:
|
|
457
|
+
if isinstance(filter, str):
|
|
458
|
+
title = filter
|
|
459
|
+
elif filter is None:
|
|
460
|
+
title = None
|
|
461
|
+
else:
|
|
462
|
+
title = "Personnalized filter"
|
|
463
|
+
|
|
464
|
+
return self._plotter.hist(
|
|
465
|
+
data, x, bins=bins, hist_range=hist_range, title=title, **kwargs
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
def plot_mesh(
|
|
469
|
+
self, plotter: Plotter | None = None, *args, **kwargs
|
|
470
|
+
) -> Any:
|
|
471
|
+
"""Plot the stored mesh."""
|
|
472
|
+
if plotter is None:
|
|
473
|
+
plotter = self._plotter
|
|
474
|
+
return plotter.plot_mesh(self._mesh, *args, **kwargs)
|
|
475
|
+
|
|
476
|
+
def plot_trajectories(
|
|
477
|
+
self,
|
|
478
|
+
emission_color: str | None = None,
|
|
479
|
+
collision_color: str | None = None,
|
|
480
|
+
lw: int = 7,
|
|
481
|
+
r: int = 8,
|
|
482
|
+
plotter: Plotter | None = None,
|
|
483
|
+
filter: FILTER_KEY | FILTER_FUNC | None = None,
|
|
484
|
+
**kwargs,
|
|
485
|
+
) -> Any:
|
|
486
|
+
"""Plot trajectories in 3D.
|
|
487
|
+
|
|
488
|
+
Parameters
|
|
489
|
+
----------
|
|
490
|
+
emission_color :
|
|
491
|
+
If provided, the first known position is colored with this color.
|
|
492
|
+
collision_color :
|
|
493
|
+
If provided, the last known position is colored with this color.
|
|
494
|
+
collision_point :
|
|
495
|
+
If provided and ``collision_color`` is not ``None``, we plot this
|
|
496
|
+
point instead of the last of ``points``. This is useful when the
|
|
497
|
+
extrapolated time is large, and actuel collision point may differ
|
|
498
|
+
significantly from last position points.
|
|
499
|
+
lw :
|
|
500
|
+
Trajectory line width.
|
|
501
|
+
r :
|
|
502
|
+
Size of the emission/collision points.
|
|
503
|
+
plotter :
|
|
504
|
+
An object allowing to plot data.
|
|
505
|
+
filter :
|
|
506
|
+
To select the particles to be plotted.
|
|
507
|
+
|
|
508
|
+
"""
|
|
509
|
+
if plotter is None:
|
|
510
|
+
plotter = self._plotter
|
|
511
|
+
particles = self.filter_particles(filter)
|
|
512
|
+
|
|
513
|
+
veplotter = None
|
|
514
|
+
for p in particles:
|
|
515
|
+
veplotter = p.plot_trajectory(
|
|
516
|
+
plotter=plotter,
|
|
517
|
+
emission_color=emission_color,
|
|
518
|
+
collision_color=collision_color,
|
|
519
|
+
lw=lw,
|
|
520
|
+
r=r,
|
|
521
|
+
**kwargs,
|
|
522
|
+
)
|
|
523
|
+
return veplotter
|
|
524
|
+
|
|
525
|
+
@property
|
|
526
|
+
def to_list(self) -> list[Particle]:
|
|
527
|
+
"""Return stored :class:`.Particle` as a list."""
|
|
528
|
+
return list(self.values())
|
|
529
|
+
|
|
530
|
+
def to_pandas(
|
|
531
|
+
self,
|
|
532
|
+
*args: PARTICLE_0D_t,
|
|
533
|
+
filter: FILTER_KEY | FILTER_FUNC | None = None,
|
|
534
|
+
) -> pd.DataFrame:
|
|
535
|
+
particles = self.filter_particles(filter)
|
|
536
|
+
|
|
537
|
+
data: dict[str, list[float]] = {}
|
|
538
|
+
|
|
539
|
+
for arg in args:
|
|
540
|
+
concat: list[float] = []
|
|
541
|
+
for result in particles:
|
|
542
|
+
value = getattr(result, arg, None)
|
|
543
|
+
if not isinstance(value, (float, int)):
|
|
544
|
+
logging.debug(
|
|
545
|
+
f"The {arg} attribute of {result} is not a float but a"
|
|
546
|
+
f" {type(value)}, so it was not added to the "
|
|
547
|
+
"dataframe."
|
|
548
|
+
)
|
|
549
|
+
continue
|
|
550
|
+
concat.append(value)
|
|
551
|
+
data[arg] = concat
|
|
552
|
+
|
|
553
|
+
lengths = {key: len(value) for key, value in data.items()}
|
|
554
|
+
if len(set(lengths.values())) > 1:
|
|
555
|
+
raise ValueError(
|
|
556
|
+
"All the lists in data must have the same length. Maybe "
|
|
557
|
+
f"{particles = } is a Generator? Or maybe one of the keys was "
|
|
558
|
+
"not found in one or more of the Particles?\n"
|
|
559
|
+
f"{lengths = }"
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
try:
|
|
563
|
+
return pd.DataFrame(data)
|
|
564
|
+
except ValueError as e:
|
|
565
|
+
raise ValueError(
|
|
566
|
+
f"Could not get a data, creating malformed dataframe.\n{e}"
|
|
567
|
+
)
|
|
568
|
+
|
|
569
|
+
def filter_particles(
|
|
570
|
+
self, filter: FILTER_KEY | FILTER_FUNC | None
|
|
571
|
+
) -> list[Particle]:
|
|
572
|
+
"""Return a list of particles that match the given criterion."""
|
|
573
|
+
if isinstance(filter, str):
|
|
574
|
+
filter = self.FILTERS.get(filter)
|
|
575
|
+
if filter is None:
|
|
576
|
+
logging.error(
|
|
577
|
+
f"Unknown filter: {filter}. Returning all particles."
|
|
578
|
+
)
|
|
579
|
+
if filter is None:
|
|
580
|
+
filter = self.FILTERS["_default"]
|
|
581
|
+
|
|
582
|
+
return [p for p in self.values() if filter(p)]
|
|
583
|
+
|
|
584
|
+
def _load_mesh(
|
|
585
|
+
self, stl_path: Path | str, stl_alpha: float | None = None, **kwargs
|
|
586
|
+
) -> vedo.Mesh:
|
|
587
|
+
"""Load the ``STL`` file with :meth:`self._plotter.load_mesh`."""
|
|
588
|
+
if isinstance(stl_path, str):
|
|
589
|
+
stl_path = Path(stl_path)
|
|
590
|
+
assert stl_path.is_file, f"{stl_path = } does not exist."
|
|
591
|
+
return self._plotter.load_mesh(stl_path, stl_alpha=stl_alpha, **kwargs)
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _absolute_file_paths(
|
|
595
|
+
directory: Path, particle_monitor_ignore: Collection[str] = (".swp",)
|
|
596
|
+
) -> Generator[Path, Path, None]:
|
|
597
|
+
"""Get all filepaths in absolute from dir, remove unwanted files.
|
|
598
|
+
|
|
599
|
+
Parameters
|
|
600
|
+
----------
|
|
601
|
+
directory :
|
|
602
|
+
Folder to explore.
|
|
603
|
+
particle_monitor_ignore :
|
|
604
|
+
Extensions to skip.
|
|
605
|
+
|
|
606
|
+
"""
|
|
607
|
+
for dirpath, _, filenames in os.walk(directory):
|
|
608
|
+
for dirpath, _, filenames in os.walk(directory):
|
|
609
|
+
for f in filenames:
|
|
610
|
+
f = Path(f)
|
|
611
|
+
if f.suffix in particle_monitor_ignore:
|
|
612
|
+
continue
|
|
613
|
+
yield Path(dirpath, f)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _get_float_from_filename(filename: Path) -> float:
|
|
617
|
+
"""Extract the float value from the filename.
|
|
618
|
+
|
|
619
|
+
Parameters
|
|
620
|
+
----------
|
|
621
|
+
filename :
|
|
622
|
+
Filename, looking like
|
|
623
|
+
:file:`position monitor 1_0.117175810039043.txt`
|
|
624
|
+
|
|
625
|
+
"""
|
|
626
|
+
match = re.search(
|
|
627
|
+
r"_(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?=\.txt$)", filename.name
|
|
628
|
+
)
|
|
629
|
+
if match:
|
|
630
|
+
return float(match.group(1))
|
|
631
|
+
raise ValueError(
|
|
632
|
+
f"Cannot extract float from {filename = }. Expected format: "
|
|
633
|
+
"`position monitor 1_0.117175810039043.txt`."
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def _sorted_particle_monitor_files(
|
|
638
|
+
directory: Path, particle_monitor_ignore: Collection[str] = (".swp",)
|
|
639
|
+
) -> tuple[list[Path], float]:
|
|
640
|
+
"""Recursively get and sort all particle monitor files.
|
|
641
|
+
|
|
642
|
+
Typical structure is::
|
|
643
|
+
|
|
644
|
+
directory
|
|
645
|
+
├──'position monitor 1_0.117175810039043.txt'
|
|
646
|
+
├──'position monitor 1_0.156234413385391.txt'
|
|
647
|
+
├──'position monitor 1_0.19529302418232.txt'
|
|
648
|
+
├──'position monitor 1_0.232905015349388.txt'
|
|
649
|
+
├──'position monitor 1_0.271963626146317.txt'
|
|
650
|
+
├──...
|
|
651
|
+
└──'position monitor 1_7.81172066926956E-02.txt'
|
|
652
|
+
|
|
653
|
+
Parameters
|
|
654
|
+
----------
|
|
655
|
+
directory :
|
|
656
|
+
Folder to explore.
|
|
657
|
+
particle_monitor_ignore :
|
|
658
|
+
Extensions to skip.
|
|
659
|
+
|
|
660
|
+
Returns
|
|
661
|
+
-------
|
|
662
|
+
files : list[Path]
|
|
663
|
+
The sorted filepaths.
|
|
664
|
+
max_time : float
|
|
665
|
+
Highest time among provided files.
|
|
666
|
+
|
|
667
|
+
"""
|
|
668
|
+
files = list(
|
|
669
|
+
_absolute_file_paths(
|
|
670
|
+
directory, particle_monitor_ignore=particle_monitor_ignore
|
|
671
|
+
)
|
|
672
|
+
)
|
|
673
|
+
sorted_files = sorted(files, key=_get_float_from_filename)
|
|
674
|
+
max_time = (
|
|
675
|
+
_get_float_from_filename(sorted_files[-1]) if sorted_files else 0.0
|
|
676
|
+
)
|
|
677
|
+
return sorted_files, max_time
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def _filter_source_id(
|
|
681
|
+
input_dict: dict[int, Particle],
|
|
682
|
+
wanted_id: int,
|
|
683
|
+
) -> dict[int, Particle]:
|
|
684
|
+
"""Filter Particles against the sourceID field."""
|
|
685
|
+
return {
|
|
686
|
+
pid: part
|
|
687
|
+
for pid, part in input_dict.items()
|
|
688
|
+
if part.source_id == wanted_id
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _filter_out_dead_at_end(
|
|
693
|
+
input_dict: dict[int, Particle],
|
|
694
|
+
) -> dict[int, Particle]:
|
|
695
|
+
"""Filter out Particles that collisioned during simulation."""
|
|
696
|
+
particles_alive_at_end = {
|
|
697
|
+
pid: part for pid, part in input_dict.items() if part.alive_at_end
|
|
698
|
+
}
|
|
699
|
+
return particles_alive_at_end
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _filter_out_alive_at_end(
|
|
703
|
+
input_dict: dict[int, Particle],
|
|
704
|
+
) -> dict[int, Particle]:
|
|
705
|
+
"""Filter out Particles that were alive at the end of simulation."""
|
|
706
|
+
particles_that_collisioned_during_simulation = {
|
|
707
|
+
pid: part for pid, part in input_dict.items() if not part.alive_at_end
|
|
708
|
+
}
|
|
709
|
+
return particles_that_collisioned_during_simulation
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _filter_out_part_with_one_time_step(
|
|
713
|
+
input_dict: dict[int, Particle],
|
|
714
|
+
) -> dict[int, Particle]:
|
|
715
|
+
"""Remove particle with only one known position.
|
|
716
|
+
|
|
717
|
+
This is useful when the time resolution is low.
|
|
718
|
+
|
|
719
|
+
"""
|
|
720
|
+
return {
|
|
721
|
+
pid: part for pid, part in input_dict.items() if len(part.time) > 1
|
|
722
|
+
}
|