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,210 @@
1
+ """Define simple classes to lighten :class:`.Particle`."""
2
+
3
+ import logging
4
+ from collections.abc import Iterable, Sequence
5
+
6
+ import numpy as np
7
+ from numpy.typing import NDArray
8
+
9
+ from simultipac.particle_monitor.converters import (
10
+ adim_momentum_to_eV,
11
+ adim_momentum_to_speed_mm_per_ns,
12
+ )
13
+
14
+
15
+ class Vector:
16
+ """Hold a vector with three coordinates."""
17
+
18
+ def __init__(
19
+ self,
20
+ x: Sequence[float] | None = None,
21
+ y: Sequence[float] | None = None,
22
+ z: Sequence[float] | None = None,
23
+ is_extrapolated: bool = False,
24
+ ) -> None:
25
+ """Create empty lists."""
26
+ self.x: list[float] = list(x) if x is not None else []
27
+ self.y: list[float] = list(y) if y is not None else []
28
+ self.z: list[float] = list(z) if z is not None else []
29
+
30
+ self._array: NDArray[np.float64] | None = None
31
+
32
+ self._is_extrapolated = is_extrapolated
33
+ self._extrapolated: Vector
34
+ if not is_extrapolated:
35
+ self._extrapolated = Vector(is_extrapolated=True)
36
+ self._is_reordered = False
37
+ self._is_normalized = False
38
+
39
+ def append(self, coords: Sequence[float]) -> None:
40
+ """Append new coordinates. Reset ``array``."""
41
+ if self._is_normalized or self._is_reordered:
42
+ logging.warning(
43
+ "Normal behavior is following: load all data first, modify it "
44
+ "(sorting, normalization) afterwards."
45
+ )
46
+ self.x.append(coords[0])
47
+ self.y.append(coords[1])
48
+ self.z.append(coords[2])
49
+ if self._array is not None:
50
+ self._array = None
51
+
52
+ def reorder(self, ordered_time_idx: NDArray[np.int64]) -> None:
53
+ """Sort coordinates by increasing time values."""
54
+ self.x = [self.x[i] for i in ordered_time_idx]
55
+ self.y = [self.y[i] for i in ordered_time_idx]
56
+ self.z = [self.z[i] for i in ordered_time_idx]
57
+ if self._array is not None:
58
+ self._array = None
59
+
60
+ def extrapolate(self, *args, **kwargs) -> None:
61
+ """Extrapolate vector one time step further."""
62
+ if self._array is not None:
63
+ self._array = None
64
+ self._is_extrapolated = True
65
+
66
+ def normalize(self) -> None:
67
+ """Normalize to proper units."""
68
+ if self._array is not None:
69
+ self._array = None
70
+ self._is_normalized = True
71
+
72
+ @property
73
+ def array(self) -> NDArray[np.float64]:
74
+ """2D array, of shape (N, 3) where N is number of time steps.
75
+
76
+ .. note::
77
+ ``array[10, 0]``: x coordinate at 11th time step
78
+ ``array[0, 10]``: NO
79
+
80
+ """
81
+ if self._array is None:
82
+ self._array = np.column_stack([self.x, self.y, self.z])
83
+ return self._array
84
+
85
+ @property
86
+ def to_list(self) -> list[NDArray[np.float64]]:
87
+ """List of positions, each of size 3."""
88
+ return list(self.array)
89
+
90
+ @property
91
+ def last(self) -> NDArray[np.float64]:
92
+ """1D array containing last coordinates."""
93
+ return self.array[-1, :]
94
+
95
+ @property
96
+ def first(self) -> NDArray[np.float64]:
97
+ """1D array containing first coordinates."""
98
+ return self.array[0, :]
99
+
100
+ @property
101
+ def n_steps(self) -> int:
102
+ """Return number of stored time steps."""
103
+ return len(self.x)
104
+
105
+ @property
106
+ def extrapolated(self) -> NDArray[np.float64]:
107
+ """Shortcut to ``self._extrapolated.array``."""
108
+ return self._extrapolated.array
109
+
110
+
111
+ class Momentum(Vector):
112
+ """Specialized class for momentum."""
113
+
114
+ def __init__(
115
+ self,
116
+ x: Sequence[float] | None = None,
117
+ y: Sequence[float] | None = None,
118
+ z: Sequence[float] | None = None,
119
+ is_extrapolated: bool = False,
120
+ ) -> None:
121
+ super().__init__(x, y, z, is_extrapolated)
122
+
123
+ def extrapolate(
124
+ self,
125
+ known_times: NDArray[np.float64],
126
+ desired_times: NDArray[np.float64],
127
+ poly_fit_deg: int,
128
+ n_points: int = 3,
129
+ ) -> None:
130
+ """Extrapolate the momentum.
131
+
132
+ Parameters
133
+ ----------
134
+ known_times : NDArray
135
+ 1D array containing x-data used for extrapolation.
136
+ desired_times : NDArray
137
+ 1D array containing time momentum should be extrapolated on. Should
138
+ not start at 0.
139
+ poly_fit_deg : int
140
+ Degree of the polynomial fit.
141
+ n_points : int
142
+ Number of time steps to extrapolate on.
143
+
144
+ """
145
+ polynom = np.polyfit(
146
+ known_times[-n_points:], self.array[-n_points:], poly_fit_deg
147
+ )
148
+ polynom = np.flip(polynom, axis=0)
149
+
150
+ n_time_subdivisions = desired_times.shape[0]
151
+ for i in range(n_time_subdivisions):
152
+ new = [0.0, 0.0, 0.0]
153
+ for deg in range(poly_fit_deg + 1):
154
+ for j in range(3):
155
+ new[j] += polynom[deg, j] * desired_times[i] ** deg
156
+ self._extrapolated.append(new)
157
+
158
+ return super().extrapolate()
159
+
160
+ def emission_energy(self, mass_eV: float) -> float:
161
+ """Get first energy in eV."""
162
+ return adim_momentum_to_eV(self.first, mass_eV)
163
+
164
+ def collision_energy(self, mass_eV: float) -> float:
165
+ """Get last energy in eV."""
166
+ return adim_momentum_to_eV(self.last, mass_eV)
167
+
168
+
169
+ class Position(Vector):
170
+ """Specialized class for position."""
171
+
172
+ def extrapolate(
173
+ self,
174
+ momentum: NDArray[np.float64] | Momentum,
175
+ delta_t: Iterable[float] | NDArray[np.float64],
176
+ ) -> None:
177
+ """Extrapolate the position using the last known momentum.
178
+
179
+ This is a first-order approximation. We consider that the momentum is
180
+ constant over ``desired_time``. Not adapted to extrapolation on long
181
+ time spans.
182
+
183
+ .. todo::
184
+ Check is position is normalized or not.
185
+
186
+ Parameters
187
+ ----------
188
+ momentum : NDArray | Momentum
189
+ 1D array containing last known momentum, adimensionned. You can
190
+ also directly provide the :class:`Momentum` instance.
191
+ delta_t : Iterable[float] | NDArray[np.float64]
192
+ 1D array containing time at which position should be extrapolated.
193
+ Should look like ``[delta, 2*delta, 3*delta]``.
194
+
195
+ """
196
+ if isinstance(momentum, Momentum):
197
+ momentum = momentum.last
198
+ last_speed = adim_momentum_to_speed_mm_per_ns(momentum, force_2d=False)
199
+
200
+ for time in delta_t:
201
+ new_pos = [self.last[i] + last_speed[i] * time for i in range(3)]
202
+ self._extrapolated.append(new_pos)
203
+ return super().extrapolate()
204
+
205
+ def normalize(self) -> None:
206
+ """Change units to :unit:`mm`."""
207
+ self.x = [x * 1e3 for x in self.x]
208
+ self.y = [y * 1e3 for y in self.y]
209
+ self.z = [z * 1e3 for z in self.z]
210
+ return super().normalize()
@@ -0,0 +1 @@
1
+ """Define generic :class:`.Plotter` object."""
@@ -0,0 +1,331 @@
1
+ """Define a default plotter."""
2
+
3
+ import logging
4
+ from pathlib import Path
5
+ from typing import Any, Literal
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import pandas as pd
10
+ import vedo
11
+ import vedo.backends
12
+ from matplotlib.axes import Axes
13
+ from matplotlib.typing import ColorType
14
+ from numpy.typing import NDArray
15
+ from vedo.mesh import Points
16
+
17
+ from simultipac.constants import markdown
18
+ from simultipac.plotter.plotter import Plotter
19
+ from simultipac.types import PARTICLE_0D_t, PARTICLE_3D_t
20
+
21
+ VEDO_BACKENDS_t = Literal["k3d", "vtk", "2d"]
22
+
23
+
24
+ class DefaultPlotter(Plotter):
25
+ """An object using maptlotlib for 2D, Vedo for 3D."""
26
+
27
+ def __init__(
28
+ self, vedo_backend: VEDO_BACKENDS_t = "2d", *args, **kwargs
29
+ ) -> None:
30
+ """Set basic settings for the 3D Vedo plotter.
31
+
32
+ Parameters
33
+ ----------
34
+ vedo_backend :
35
+ The backend used by ``vedo``. The options that I tested were:
36
+
37
+ - ``"k3d"``: Needs ``k3d`` library. Would be the ideal setting.
38
+ But raises error in Jupyter Notebooks: ``TraitError: The
39
+ 'point_size' trait of a Points instance expected a float or a
40
+ dict, not the float64 0.0.``
41
+ - ``"vtk"``: Interactive 3D plots. Does not appear in ``HTML``
42
+ (documentation).
43
+ - ``"2d"``: Non-interactive 2D plots. Does appear in ``HTML``
44
+ outputs.
45
+
46
+ """
47
+ self._vedo_backend: VEDO_BACKENDS_t
48
+ self.vedo_backend = vedo_backend
49
+ self._plotter_3d = vedo.Plotter()
50
+ self._show_3d = False
51
+
52
+ return super().__init__(*args, **kwargs)
53
+
54
+ @property
55
+ def vedo_backend(self) -> VEDO_BACKENDS_t:
56
+ """The name of the vedo backend; *a priori*, no need to access that."""
57
+ return self._vedo_backend
58
+
59
+ @vedo_backend.setter
60
+ def vedo_backend(self, value: VEDO_BACKENDS_t) -> None:
61
+ """Update the vedo backend."""
62
+ vedo.settings.default_backend = value
63
+ self._vedo_backend = value
64
+
65
+ if value in ("k3d",):
66
+ self._k3d_patch()
67
+
68
+ def plot(
69
+ self,
70
+ data: pd.DataFrame,
71
+ x: str,
72
+ y: str,
73
+ grid: bool = True,
74
+ axes: Axes | None = None,
75
+ xlabel: str | None = None,
76
+ ylabel: str | None = None,
77
+ label: str | None = None,
78
+ **kwargs,
79
+ ) -> tuple[Axes | NDArray[Any], ColorType]:
80
+ """Plot 2D data.
81
+
82
+ Parameters
83
+ ----------
84
+ data :
85
+ Holds all data to plot.
86
+ x, y :
87
+ Name of column in ``data`` for x/y.
88
+ grid :
89
+ If grid should be plotted. Default is True.
90
+ axes :
91
+ Axes to re-use, if provided. The default is None (plot on new
92
+ axis).
93
+ xlabel, ylabel :
94
+ Name of the labels. If not provided, we use the markdown equivalent
95
+ of x/y, if defined in :data:`.markdown`.
96
+ label :
97
+ If provided, overrides the legend. Useful when several simulations
98
+ are shown on the same plot.
99
+ kwargs :
100
+ Other keyword passed to the ``pd.DataFrame.plot`` method.
101
+
102
+ Returns
103
+ -------
104
+ axes : Axes | NDArray[Any]
105
+ Objects created by the ``pd.DataFrame.plot`` method.
106
+ color : ColorType
107
+ Color used for the plot.
108
+
109
+ """
110
+ if xlabel is None:
111
+ xlabel = markdown.get(x, x)
112
+ if ylabel is None:
113
+ ylabel = markdown.get(y, y)
114
+ axes = data.plot(
115
+ x=x,
116
+ y=y,
117
+ grid=grid,
118
+ ax=axes,
119
+ xlabel=xlabel,
120
+ ylabel=ylabel,
121
+ label=label,
122
+ **kwargs,
123
+ )
124
+ assert axes is not None
125
+ color = self._get_color_from_last_plot(axes)
126
+ return axes, color
127
+
128
+ def _get_color_from_last_plot(
129
+ self, axes: Axes | NDArray[Any]
130
+ ) -> ColorType:
131
+ """Get the color used for the last plot."""
132
+ ax = axes if isinstance(axes, Axes) else axes[-1]
133
+ assert isinstance(ax, Axes)
134
+ lines = ax.get_lines()
135
+ color = lines[-1].get_color()
136
+ return color
137
+
138
+ def hist(
139
+ self,
140
+ data: pd.DataFrame,
141
+ x: PARTICLE_0D_t,
142
+ bins: int = 200,
143
+ hist_range: tuple[float, float] | None = None,
144
+ xlabel: str | None = None,
145
+ title: str | None = None,
146
+ **kwargs,
147
+ ) -> Any:
148
+ if xlabel is None:
149
+ xlabel = markdown.get(x, x)
150
+ axes = data.plot(
151
+ kind="hist",
152
+ bins=bins,
153
+ range=hist_range,
154
+ xlabel=xlabel,
155
+ title=title,
156
+ **kwargs,
157
+ )
158
+ assert axes is not None
159
+ return axes
160
+
161
+ def plot_3d(
162
+ self,
163
+ data: Any,
164
+ key: PARTICLE_3D_t,
165
+ *args,
166
+ **kwargs,
167
+ ) -> Any:
168
+ self._show_3d = True
169
+ raise NotImplementedError
170
+
171
+ def plot_mesh(self, mesh: vedo.Mesh, *args, **kwargs) -> vedo.Plotter:
172
+ """Plot the mesh (``STL`` file)."""
173
+ self._show_3d = True
174
+ self._plotter_3d += mesh
175
+ return self._plotter_3d
176
+
177
+ def plot_trajectory(
178
+ self,
179
+ points: list[NDArray[np.float64]],
180
+ emission_color: str | None = None,
181
+ collision_color: str | None = None,
182
+ collision_point: NDArray[np.float64] = np.array([], dtype=np.float64),
183
+ lw: int = 7,
184
+ r: int = 2,
185
+ **kwargs,
186
+ ) -> vedo.Plotter:
187
+ """Plot the :class:`.Particle` trajectory stored in ``points``.
188
+
189
+ Parameters
190
+ ----------
191
+ points :
192
+ List of positions, as returned by :meth:`.Vector.to_list`.
193
+ emission_color :
194
+ If provided, the first known position is colored with this color.
195
+ collision_color :
196
+ If provided, the last known position is colored with this color.
197
+ collision_point :
198
+ If provided and ``collision_color`` is not ``None``, we plot this
199
+ point instead of the last of ``points``. This is useful when the
200
+ extrapolated time is large, and actuel collision point may differ
201
+ significantly from last position points.
202
+ lw :
203
+ Trajectory line width.
204
+ r :
205
+ Size of the emission/collision points.
206
+
207
+ """
208
+ self._show_3d = True
209
+ objects = vedo.Lines(points[:-1], points[1:], lw=lw, **kwargs)
210
+
211
+ if emission_color is not None:
212
+ objects += vedo.Point(pos=points[0], r=r, c=emission_color)
213
+
214
+ if collision_color is not None:
215
+ if len(collision_point) == 0:
216
+ collision_point = points[-1]
217
+ objects += vedo.Point(pos=collision_point, r=r, c=collision_color)
218
+
219
+ self._plotter_3d += objects
220
+ return self._plotter_3d
221
+
222
+ def load_mesh(
223
+ self, stl_path: str | Path, stl_alpha: float | None = None, **kwargs
224
+ ) -> vedo.Mesh:
225
+ mesh = vedo.load(stl_path)
226
+ if stl_alpha is not None:
227
+ mesh.alpha(stl_alpha)
228
+ return mesh
229
+
230
+ def show(self) -> None:
231
+ """Show the plots that were produced.
232
+
233
+ Useful for the bash interface.
234
+ """
235
+ plt.show()
236
+ if not self._show_3d:
237
+ return
238
+
239
+ _plotter_3d: vedo.Plotter = self._plotter_3d
240
+
241
+ _plotter_3d.show()
242
+
243
+ def _k3d_patch(self) -> None:
244
+ """Patch ``point_size`` to avoid following error.
245
+
246
+ .. code-block::
247
+
248
+ File "/home/placais/Documents/simulation/python/simultipac/examples/./analyze_cst_particle_monitor.py", line 61, in <module>
249
+ result.show()
250
+ ~~~~~~~~~~~^^
251
+ File "/home/placais/Documents/simulation/python/simultipac/src/simultipac/simulation_results/simulation_results.py", line 324, in show
252
+ return self._plotter.show()
253
+ ~~~~~~~~~~~~~~~~~~^^
254
+ File "/home/placais/Documents/simulation/python/simultipac/src/simultipac/plotter/default.py", line 235, in show
255
+ _plotter_3d.show()
256
+ ~~~~~~~~~~~~~~~~^^
257
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/vedo/plotter.py", line 3337, in show
258
+ return backends.get_notebook_backend(self.objects)
259
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
260
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/vedo/backends.py", line 31, in get_notebook_backend
261
+ return start_k3d(actors2show)
262
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/vedo/backends.py", line 349, in start_k3d
263
+ kobj = k3d.points(
264
+ ia.coordinates.astype(np.float32),
265
+ ...<5 lines>...
266
+ name=name,
267
+ )
268
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/k3d/factory.py", line 620, in points
269
+ Points(
270
+ ~~~~~~^
271
+ positions=positions,
272
+ ^^^^^^^^^^^^^^^^^^^^
273
+ ...<15 lines>...
274
+ compression_level=compression_level,
275
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
276
+ ),
277
+ ^
278
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/k3d/objects.py", line 735, in __init__
279
+ super(Points, self).__init__(**kwargs)
280
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
281
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/k3d/objects.py", line 194, in __init__
282
+ super(DrawableWithCallback, self).__init__(**kwargs)
283
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
284
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/k3d/objects.py", line 108, in __init__
285
+ super(Drawable, self).__init__(**kwargs)
286
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
287
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/ipywidgets/widgets/widget.py", line 478, in __init__
288
+ super(Widget, self).__init__(**kwargs)
289
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
290
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/traitlets/traitlets.py", line 1355, in __init__
291
+ setattr(self, key, value)
292
+ ~~~~~~~^^^^^^^^^^^^^^^^^^
293
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/traitlets/traitlets.py", line 716, in __set__
294
+ self.set(obj, value)
295
+ ~~~~~~~~^^^^^^^^^^^^
296
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/traitlets/traitlets.py", line 690, in set
297
+ new_value = self._validate(obj, value)
298
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/traitlets/traitlets.py", line 722, in _validate
299
+ value = self.validate(obj, value)
300
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/traitlets/traitlets.py", line 2460, in validate
301
+ self.error(obj, value)
302
+ ~~~~~~~~~~^^^^^^^^^^^^
303
+ File "/home/placais/.pyenv/versions/simultipac/lib/python3.13/site-packages/traitlets/traitlets.py", line 831, in error
304
+ raise TraitError(e)
305
+ traitlets.traitlets.TraitError: The 'point_size' trait of a Points instance expected a float or a dict, not the float64 np.float64(0.0).
306
+
307
+ This method overrides the default ``k3d.objects.Points`` constructor.
308
+ May be related to
309
+ [this issue](https://github.com/marcomusy/vedo/issues/1197).
310
+
311
+ """
312
+ logging.info("Applying patch for k3d.")
313
+
314
+ import k3d
315
+
316
+ original_k3d_points = k3d.points
317
+
318
+ def patched_k3d_points(*args, **kwargs) -> k3d.objects.Points:
319
+ """Instantiate ``k3d`` points with proper ``point_size`` arg."""
320
+ ps = kwargs.get("point_size")
321
+ if ps is None:
322
+ return original_k3d_points(*args, **kwargs)
323
+
324
+ if ps <= 0.0:
325
+ logging.info("patching invalid point_size=0.0 -> 1.0.")
326
+ ps = 1.0
327
+
328
+ kwargs["point_size"] = ps
329
+ return original_k3d_points(*args, **kwargs)
330
+
331
+ k3d.points = patched_k3d_points