differt 0.0.15__tar.gz → 0.0.17__tar.gz

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.
Files changed (26) hide show
  1. {differt-0.0.15 → differt-0.0.17}/PKG-INFO +7 -4
  2. differt-0.0.17/README.md +1 -0
  3. {differt-0.0.15 → differt-0.0.17}/pyproject.toml +2 -4
  4. {differt-0.0.15 → differt-0.0.17/src}/differt/geometry/triangle_mesh.py +32 -1
  5. {differt-0.0.15 → differt-0.0.17/src}/differt/plotting/_core.py +79 -49
  6. {differt-0.0.15 → differt-0.0.17/src}/differt/plotting/_utils.py +160 -76
  7. {differt-0.0.15 → differt-0.0.17/src}/differt/utils.py +32 -2
  8. {differt-0.0.15 → differt-0.0.17}/.gitignore +0 -0
  9. {differt-0.0.15 → differt-0.0.17}/LICENSE.md +0 -0
  10. {differt-0.0.15 → differt-0.0.17/src}/differt/__init__.py +0 -0
  11. {differt-0.0.15 → differt-0.0.17/src}/differt/em/__init__.py +0 -0
  12. {differt-0.0.15 → differt-0.0.17/src}/differt/em/constants.py +0 -0
  13. {differt-0.0.15 → differt-0.0.17/src}/differt/em/special.py +0 -0
  14. {differt-0.0.15 → differt-0.0.17/src}/differt/em/utd.py +0 -0
  15. {differt-0.0.15 → differt-0.0.17/src}/differt/em/utils.py +0 -0
  16. {differt-0.0.15 → differt-0.0.17/src}/differt/geometry/__init__.py +0 -0
  17. {differt-0.0.15 → differt-0.0.17/src}/differt/geometry/utils.py +0 -0
  18. {differt-0.0.15 → differt-0.0.17/src}/differt/plotting/__init__.py +0 -0
  19. {differt-0.0.15 → differt-0.0.17/src}/differt/rt/__init__.py +0 -0
  20. {differt-0.0.15 → differt-0.0.17/src}/differt/rt/fermat.py +0 -0
  21. {differt-0.0.15 → differt-0.0.17/src}/differt/rt/image_method.py +0 -0
  22. {differt-0.0.15 → differt-0.0.17/src}/differt/rt/utils.py +0 -0
  23. {differt-0.0.15 → differt-0.0.17/src}/differt/scene/__init__.py +0 -0
  24. {differt-0.0.15 → differt-0.0.17/src}/differt/scene/sionna.py +0 -0
  25. {differt-0.0.15 → differt-0.0.17/src}/differt/scene/triangle_scene.py +0 -0
  26. {differt-0.0.15 → differt-0.0.17/src}/differt/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: DiffeRT
3
- Version: 0.0.15
3
+ Version: 0.0.17
4
4
  Summary: Differentiable Ray Tracing Toolbox for Radio Propagation Simulations
5
5
  Project-URL: Changelog, https://github.com/jeertmans/DiffeRT/releases
6
6
  Project-URL: Documentation, https://eertmans.be/DiffeRT
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.12
21
21
  Classifier: Topic :: Scientific/Engineering
22
22
  Requires-Python: >=3.9
23
23
  Requires-Dist: beartype>=0.17.2
24
- Requires-Dist: differt-core==0.0.15
24
+ Requires-Dist: differt-core==0.0.17
25
25
  Requires-Dist: equinox>=0.11.2
26
26
  Requires-Dist: jax>=0.4.20
27
27
  Requires-Dist: jaxtyping>=0.2.24
@@ -34,14 +34,14 @@ Provides-Extra: all
34
34
  Requires-Dist: ipympl; extra == 'all'
35
35
  Requires-Dist: jupyter-rfb>=0.4.2; extra == 'all'
36
36
  Requires-Dist: matplotlib>=3.8.1; extra == 'all'
37
- Requires-Dist: notebook>=7; extra == 'all'
37
+ Requires-Dist: notebook>5; extra == 'all'
38
38
  Requires-Dist: plotly>=5.18.0; extra == 'all'
39
39
  Requires-Dist: pyqt6>=6.6.1; extra == 'all'
40
40
  Requires-Dist: vispy>=0.14.1; extra == 'all'
41
41
  Provides-Extra: jupyter
42
42
  Requires-Dist: ipympl; extra == 'jupyter'
43
43
  Requires-Dist: jupyter-rfb>=0.4.2; extra == 'jupyter'
44
- Requires-Dist: notebook>=7; extra == 'jupyter'
44
+ Requires-Dist: notebook>5; extra == 'jupyter'
45
45
  Provides-Extra: matplotlib
46
46
  Requires-Dist: matplotlib>=3.8.1; extra == 'matplotlib'
47
47
  Provides-Extra: plotly
@@ -63,6 +63,7 @@ Description-Content-Type: text/markdown
63
63
  [![Latest Release][pypi-version-badge]][pypi-version-url]
64
64
  [![Python version][pypi-python-version-badge]][pypi-version-url]
65
65
  [![Documentation][documentation-badge]][documentation-url]
66
+ [![DOI][doi-badge]][doi-url]
66
67
  [![Codecov][codecov-badge]][codecov-url]
67
68
 
68
69
  </div>
@@ -174,5 +175,7 @@ pytest --benchmark-only
174
175
  [pypi-python-version-badge]: https://img.shields.io/pypi/pyversions/DiffeRT?color=orange
175
176
  [documentation-badge]: https://readthedocs.org/projects/differt/badge/?version=latest
176
177
  [documentation-url]: https://differt.readthedocs.io/latest/?badge=latest
178
+ [doi-badge]: https://zenodo.org/badge/DOI/10.5281/zenodo.11386432.svg
179
+ [doi-url]: https://doi.org/10.5281/zenodo.11386432
177
180
  [codecov-badge]: https://codecov.io/gh/jeertmans/DiffeRT/branch/main/graph/badge.svg?token=v63alnTWzu
178
181
  [codecov-url]: https://codecov.io/gh/jeertmans/DiffeRT
@@ -0,0 +1 @@
1
+ ../README.md
@@ -16,7 +16,7 @@ classifiers = [
16
16
  ]
17
17
  dependencies = [
18
18
  "beartype>=0.17.2",
19
- "differt-core==0.0.15",
19
+ "differt-core==0.0.17",
20
20
  "equinox>=0.11.2",
21
21
  "jax>=0.4.20",
22
22
  "jaxtyping>=0.2.24",
@@ -37,7 +37,7 @@ requires-python = ">=3.9"
37
37
  all = [
38
38
  "differt[jupyter,matplotlib,plotly,vispy,vispy-backend]",
39
39
  ]
40
- jupyter = ["notebook>=7", "jupyter-rfb>=0.4.2", "ipympl"]
40
+ jupyter = ["notebook>5", "jupyter-rfb>=0.4.2", "ipympl"]
41
41
  matplotlib = ["matplotlib>=3.8.1"]
42
42
  plotly = ["plotly>=5.18.0"]
43
43
  vispy = ["vispy>=0.14.1"]
@@ -56,13 +56,11 @@ exclude = [
56
56
  "conftest.py",
57
57
  "tests",
58
58
  ]
59
- packages = ["src/differt"]
60
59
 
61
60
  [tool.hatch.build.targets.wheel]
62
61
  exclude = [
63
62
  "conftest.py",
64
63
  ]
65
- packages = ["src/differt"]
66
64
 
67
65
  [tool.hatch.metadata]
68
66
  allow-direct-references = true
@@ -4,10 +4,11 @@ from functools import cached_property
4
4
  from typing import Any
5
5
 
6
6
  import equinox as eqx
7
+ import jax
7
8
  import jax.numpy as jnp
8
9
  import numpy as np
9
10
  from beartype import beartype as typechecker
10
- from jaxtyping import Array, Bool, Float, UInt, jaxtyped
11
+ from jaxtyping import Array, Bool, Float, PRNGKeyArray, UInt, jaxtyped
11
12
 
12
13
  import differt_core.geometry.triangle_mesh
13
14
 
@@ -134,6 +135,13 @@ class TriangleMesh(eqx.Module):
134
135
  """The diffraction edges."""
135
136
  raise NotImplementedError
136
137
 
138
+ @cached_property
139
+ def bounding_box(self) -> Float[Array, "2 3"]:
140
+ """The bounding box (min. and max. coordinates)."""
141
+ return jnp.vstack(
142
+ (jnp.min(self.vertices, axis=0), jnp.max(self.vertices, axis=0))
143
+ )
144
+
137
145
  @classmethod
138
146
  def empty(cls) -> "TriangleMesh":
139
147
  """
@@ -207,3 +215,26 @@ class TriangleMesh(eqx.Module):
207
215
  triangles=np.asarray(self.triangles),
208
216
  **kwargs,
209
217
  )
218
+
219
+ @eqx.filter_jit
220
+ def sample(
221
+ self, size: int, replace: bool = False, *, key: PRNGKeyArray
222
+ ) -> "TriangleMesh":
223
+ """
224
+ Generate a new mesh by randomly sampling triangles from this geometry.
225
+
226
+ Args:
227
+ size: The size of the sample, i.e., the number of triangles.
228
+ replace: Whether to sample with or without replacement.
229
+ key: The :func:`jax.random.PRNGKey` to be used.
230
+
231
+ Return:
232
+ A new random mesh.
233
+ """
234
+ triangles = self.triangles[
235
+ jax.random.choice(
236
+ key, self.triangles.shape[0], shape=(size,), replace=replace
237
+ ),
238
+ :,
239
+ ]
240
+ return TriangleMesh(vertices=self.vertices, triangles=triangles)
@@ -1,9 +1,7 @@
1
1
  """Core plotting implementations."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  from collections.abc import Mapping, Sequence
6
- from typing import TYPE_CHECKING, Any
4
+ from typing import Any, Optional, Union
7
5
 
8
6
  import numpy as np
9
7
  from jaxtyping import Float, Num, UInt
@@ -15,18 +13,34 @@ from ._utils import (
15
13
  process_vispy_kwargs,
16
14
  )
17
15
 
18
- if TYPE_CHECKING:
16
+ # We cannot use from __future__ import annotations because
17
+ # otherwise array annotations do not render correctly.
18
+ # We cannot rely on TYPE_CHECKING-guarded annotation
19
+ # because Sphinx will fail to import this NumPy or Jax typing
20
+ # Hence, we prefer to silence pyright instead.
21
+
22
+ try:
19
23
  from matplotlib.figure import Figure as MplFigure
24
+ except ImportError:
25
+ MplFigure = Any
26
+
27
+ try:
20
28
  from plotly.graph_objects import Figure
29
+ except ImportError:
30
+ Figure = Any
31
+
32
+ try:
21
33
  from vispy.scene.canvas import SceneCanvas as Canvas
34
+ except ImportError:
35
+ Canvas = Any
22
36
 
23
37
 
24
- @dispatch # type: ignore
38
+ @dispatch
25
39
  def draw_mesh(
26
40
  vertices: Float[np.ndarray, "num_vertices 3"],
27
41
  triangles: UInt[np.ndarray, "num_triangles 3"],
28
42
  **kwargs: Any,
29
- ) -> Canvas | MplFigure | Figure: # type: ignore
43
+ ) -> Union[Canvas, MplFigure, Figure]: # type: ignore[reportInvalidTypeForm]
30
44
  """
31
45
  Plot a 3D mesh made of triangles.
32
46
 
@@ -72,7 +86,7 @@ def _(
72
86
  vertices: Float[np.ndarray, "num_vertices 3"],
73
87
  triangles: UInt[np.ndarray, "num_triangles 3"],
74
88
  **kwargs: Any,
75
- ) -> Canvas:
89
+ ) -> Canvas: # type: ignore[reportInvalidTypeForm]
76
90
  from vispy.scene.visuals import Mesh
77
91
 
78
92
  canvas, view = process_vispy_kwargs(kwargs)
@@ -88,7 +102,7 @@ def _(
88
102
  vertices: Float[np.ndarray, "num_vertices 3"],
89
103
  triangles: UInt[np.ndarray, "num_triangles 3"],
90
104
  **kwargs: Any,
91
- ) -> MplFigure:
105
+ ) -> MplFigure: # type: ignore[reportInvalidTypeForm]
92
106
  fig, ax = process_matplotlib_kwargs(kwargs)
93
107
 
94
108
  x, y, z = vertices.T
@@ -102,7 +116,7 @@ def _(
102
116
  vertices: Float[np.ndarray, "num_vertices 3"],
103
117
  triangles: UInt[np.ndarray, "num_triangles 3"],
104
118
  **kwargs: Any,
105
- ) -> Figure:
119
+ ) -> Figure: # type: ignore[reportInvalidTypeForm]
106
120
  fig = process_plotly_kwargs(kwargs)
107
121
 
108
122
  x, y, z = vertices.T
@@ -111,10 +125,10 @@ def _(
111
125
  return fig.add_mesh3d(x=x, y=y, z=z, i=i, j=j, k=k, **kwargs)
112
126
 
113
127
 
114
- @dispatch # type: ignore
128
+ @dispatch
115
129
  def draw_paths(
116
- paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any
117
- ) -> Canvas | MplFigure | Figure: # type: ignore
130
+ paths: Float[np.ndarray, r"\*batch path_length 3"], **kwargs: Any
131
+ ) -> Union[Canvas, MplFigure, Figure]: # type: ignore[reportInvalidTypeForm]
118
132
  """
119
133
  Plot a batch of paths of the same length.
120
134
 
@@ -137,12 +151,12 @@ def draw_paths(
137
151
  >>> from differt.plotting import draw_paths
138
152
  >>>
139
153
  >>> def rotation(angle: float) -> np.ndarray:
140
- ... c = np.cos(angle)
141
- ... s = np.sin(angle)
154
+ ... co = np.cos(angle)
155
+ ... si = np.sin(angle)
142
156
  ... return np.array(
143
157
  ... [
144
- ... [+c, -s, 0.0],
145
- ... [+s, +c, 0.0],
158
+ ... [+co, -si, 0.0],
159
+ ... [+si, +co, 0.0],
146
160
  ... [0.0, 0.0, 1.0],
147
161
  ... ]
148
162
  ... )
@@ -172,7 +186,7 @@ def draw_paths(
172
186
 
173
187
 
174
188
  @draw_paths.register("vispy")
175
- def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> Canvas:
189
+ def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> Canvas: # type: ignore[reportInvalidTypeForm]
176
190
  from vispy.scene.visuals import LinePlot
177
191
 
178
192
  canvas, view = process_vispy_kwargs(kwargs)
@@ -186,7 +200,7 @@ def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> Canvas
186
200
 
187
201
 
188
202
  @draw_paths.register("matplotlib")
189
- def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> MplFigure:
203
+ def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> MplFigure: # type: ignore[reportInvalidTypeForm]
190
204
  fig, ax = process_matplotlib_kwargs(kwargs)
191
205
 
192
206
  for i in np.ndindex(paths.shape[:-2]):
@@ -196,7 +210,7 @@ def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> MplFig
196
210
 
197
211
 
198
212
  @draw_paths.register("plotly")
199
- def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> Figure:
213
+ def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> Figure: # type: ignore[reportInvalidTypeForm]
200
214
  fig = process_plotly_kwargs(kwargs)
201
215
 
202
216
  for i in np.ndindex(paths.shape[:-2]):
@@ -206,13 +220,13 @@ def _(paths: Float[np.ndarray, "*batch path_length 3"], **kwargs: Any) -> Figure
206
220
  return fig
207
221
 
208
222
 
209
- @dispatch # type: ignore
223
+ @dispatch
210
224
  def draw_markers(
211
225
  markers: Float[np.ndarray, "num_markers 3"],
212
- labels: Sequence[str] | None = None,
213
- text_kwargs: Mapping[str, Any] | None = None,
226
+ labels: Optional[Sequence[str]] = None,
227
+ text_kwargs: Optional[Mapping[str, Any]] = None,
214
228
  **kwargs: Any,
215
- ) -> Canvas | MplFigure | Figure: # type: ignore
229
+ ) -> Union[Canvas, MplFigure, Figure]: # type: ignore[reportInvalidTypeForm]
216
230
  """
217
231
  Plot markers and, optionally, their label.
218
232
 
@@ -259,10 +273,10 @@ def draw_markers(
259
273
  @draw_markers.register("vispy")
260
274
  def _(
261
275
  markers: Float[np.ndarray, "num_markers 3"],
262
- labels: Sequence[str] | None = None,
263
- text_kwargs: Mapping[str, Any] | None = None,
276
+ labels: Optional[Sequence[str]] = None,
277
+ text_kwargs: Optional[Mapping[str, Any]] = None,
264
278
  **kwargs: Any,
265
- ) -> Canvas:
279
+ ) -> Canvas: # type: ignore[reportInvalidTypeForm]
266
280
  from vispy.scene.visuals import Markers, Text
267
281
 
268
282
  canvas, view = process_vispy_kwargs(kwargs)
@@ -280,20 +294,20 @@ def _(
280
294
  @draw_markers.register("matplotlib")
281
295
  def _(
282
296
  markers: Float[np.ndarray, "num_markers 3"],
283
- labels: Sequence[str] | None = None,
284
- text_kwargs: Mapping[str, Any] | None = None,
297
+ labels: Optional[Sequence[str]] = None,
298
+ text_kwargs: Optional[Mapping[str, Any]] = None,
285
299
  **kwargs: Any,
286
- ) -> MplFigure:
300
+ ) -> MplFigure: # type: ignore[reportInvalidTypeForm]
287
301
  raise NotImplementedError # TODO
288
302
 
289
303
 
290
304
  @draw_markers.register("plotly")
291
305
  def _(
292
306
  markers: Float[np.ndarray, "num_markers 3"],
293
- labels: Sequence[str] | None = None,
294
- text_kwargs: Mapping[str, Any] | None = None,
307
+ labels: Optional[Sequence[str]] = None,
308
+ text_kwargs: Optional[Mapping[str, Any]] = None,
295
309
  **kwargs: Any,
296
- ) -> Figure:
310
+ ) -> Figure: # type: ignore[reportInvalidTypeForm]
297
311
  fig = process_plotly_kwargs(kwargs)
298
312
 
299
313
  if labels:
@@ -309,14 +323,18 @@ def _(
309
323
  )
310
324
 
311
325
 
312
- @dispatch # type: ignore
326
+ @dispatch
313
327
  def draw_image(
314
- data: Num[np.ndarray, "m n"] | Num[np.ndarray, "m n 3"] | Num[np.ndarray, "m n 4"],
315
- x: Float[np.ndarray, " *m"] | None = None,
316
- y: Float[np.ndarray, " *n"] | None = None,
328
+ data: Union[
329
+ Num[np.ndarray, "rows cols"],
330
+ Num[np.ndarray, "rows cols 3"],
331
+ Num[np.ndarray, "rows cols 4"],
332
+ ],
333
+ x: Optional[Float[np.ndarray, " rows"]] = None,
334
+ y: Optional[Float[np.ndarray, " cols"]] = None,
317
335
  z0: float = 0.0,
318
336
  **kwargs: Any,
319
- ) -> Canvas | MplFigure | Figure: # type: ignore
337
+ ) -> Union[Canvas, MplFigure, Figure]: # type: ignore[reportInvalidTypeForm]
320
338
  """
321
339
  Plot a 2D image on a 3D canvas, at using a fixed z-coordinate.
322
340
 
@@ -368,12 +386,16 @@ def draw_image(
368
386
 
369
387
  @draw_image.register("vispy")
370
388
  def _(
371
- data: Num[np.ndarray, "m n"] | Num[np.ndarray, "m n 3"] | Num[np.ndarray, "m n 4"],
372
- x: Float[np.ndarray, " ..."] | None = None,
373
- y: Float[np.ndarray, " ..."] | None = None,
389
+ data: Union[
390
+ Num[np.ndarray, "rows cols"],
391
+ Num[np.ndarray, "rows cols 3"],
392
+ Num[np.ndarray, "rows cols 4"],
393
+ ],
394
+ x: Optional[Float[np.ndarray, " rows"]] = None,
395
+ y: Optional[Float[np.ndarray, " cols"]] = None,
374
396
  z0: float = 0.0,
375
397
  **kwargs: Any,
376
- ) -> Canvas:
398
+ ) -> Canvas: # type: ignore[reportInvalidTypeForm]
377
399
  from vispy.scene.visuals import Image
378
400
  from vispy.visuals.transforms import STTransform
379
401
 
@@ -416,12 +438,16 @@ def _(
416
438
 
417
439
  @draw_image.register("matplotlib")
418
440
  def _(
419
- data: Num[np.ndarray, "m n"] | Num[np.ndarray, "m n 3"] | Num[np.ndarray, "m n 4"],
420
- x: Float[np.ndarray, " ..."] | None = None,
421
- y: Float[np.ndarray, " ..."] | None = None,
441
+ data: Union[
442
+ Num[np.ndarray, "rows cols"],
443
+ Num[np.ndarray, "rows cols 3"],
444
+ Num[np.ndarray, "rows cols 4"],
445
+ ],
446
+ x: Optional[Float[np.ndarray, " rows"]] = None,
447
+ y: Optional[Float[np.ndarray, " cols"]] = None,
422
448
  z0: float = 0.0,
423
449
  **kwargs: Any,
424
- ) -> MplFigure:
450
+ ) -> MplFigure: # type: ignore[reportInvalidTypeForm]
425
451
  fig, ax = process_matplotlib_kwargs(kwargs)
426
452
 
427
453
  ax.plot_surface(X=x, Y=y, Z=np.full_like(data, z0), color=data, **kwargs)
@@ -431,12 +457,16 @@ def _(
431
457
 
432
458
  @draw_image.register("plotly")
433
459
  def _(
434
- data: Num[np.ndarray, "m n"] | Num[np.ndarray, "m n 3"] | Num[np.ndarray, "m n 4"],
435
- x: Float[np.ndarray, " ..."] | None = None,
436
- y: Float[np.ndarray, " ..."] | None = None,
460
+ data: Union[
461
+ Num[np.ndarray, "rows cols"],
462
+ Num[np.ndarray, "rows cols 3"],
463
+ Num[np.ndarray, "rows cols 4"],
464
+ ],
465
+ x: Optional[Float[np.ndarray, " rows"]] = None,
466
+ y: Optional[Float[np.ndarray, " cols"]] = None,
437
467
  z0: float = 0.0,
438
468
  **kwargs: Any,
439
- ) -> Figure:
469
+ ) -> Figure: # type: ignore[reportInvalidTypeForm]
440
470
  fig = process_plotly_kwargs(kwargs)
441
471
 
442
472
  return fig.add_surface(
@@ -1,13 +1,13 @@
1
1
  """Useful decorators for plotting."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  import importlib
4
+ import sys
5
+ import types
6
6
  from collections.abc import Iterator, MutableMapping
7
7
  from contextlib import contextmanager
8
8
  from functools import wraps
9
9
  from threading import Lock
10
- from typing import TYPE_CHECKING, Any, Callable, Generic, Protocol, TypeVar
10
+ from typing import TYPE_CHECKING, Any, Callable, Generic, Optional, TypeVar, Union
11
11
 
12
12
  # Immutables
13
13
 
@@ -24,28 +24,31 @@ DEFAULT_BACKEND = "vispy"
24
24
  DEFAULT_KWARGS: MutableMapping[str, Any] = {}
25
25
  """The default keyword arguments."""
26
26
 
27
- if TYPE_CHECKING:
28
- import sys
29
27
 
28
+ if sys.version_info >= (3, 10):
29
+ from typing import ParamSpec
30
+ else:
31
+ from typing_extensions import ParamSpec
32
+
33
+ P = ParamSpec("P")
34
+
35
+ if TYPE_CHECKING:
30
36
  from matplotlib.figure import Figure as MplFigure
31
37
  from mpl_toolkits.mplot3d import Axes3D
32
38
  from plotly.graph_objects import Figure
33
- from vispy.scene.canvas import SceneCanvas
39
+ from vispy.scene.canvas import SceneCanvas as Canvas
34
40
  from vispy.scene.widgets.viewbox import ViewBox
35
-
36
- if sys.version_info >= (3, 10):
37
- from typing import ParamSpec
38
- else:
39
- from typing_extensions import ParamSpec
40
-
41
- P = ParamSpec("P")
42
- T = TypeVar("T", SceneCanvas, MplFigure, Figure)
43
41
  else:
44
- P = TypeVar("P")
45
- T = TypeVar("T")
42
+ MplFigure = Any
43
+ Axes3D = Any
44
+ Figure = Any
45
+ Canvas = Any
46
+ ViewBox = Any
46
47
 
48
+ T = TypeVar("T", Canvas, MplFigure, Figure)
47
49
 
48
- def set_defaults(backend: str | None = None, **kwargs: Any) -> str:
50
+
51
+ def set_defaults(backend: Optional[str] = None, **kwargs: Any) -> str:
49
52
  """
50
53
  Set default keyword arguments for future plotting utilities.
51
54
 
@@ -64,35 +67,45 @@ def set_defaults(backend: str | None = None, **kwargs: Any) -> str:
64
67
  ImportError: If the backend is not installed.
65
68
 
66
69
  Examples:
67
- The following example shows how to set the default plotting backend.
70
+ The following example shows how to set the default plotting backend
71
+ and other plotting defaults.
68
72
 
69
73
  >>> import differt.plotting as dplt
70
74
  >>>
71
75
  >>> @dplt.dispatch
72
- ... def my_plot():
76
+ ... def my_plot(*args, **kwargs):
73
77
  ... pass
74
78
  >>>
75
79
  >>> @my_plot.register("vispy")
76
- ... def _():
77
- ... print("Using vispy backend")
80
+ ... def _(*args, **kwargs):
81
+ ... dplt.process_vispy_kwargs(kwargs)
82
+ ... print(f"Using vispy backend with {args = }, {kwargs = }")
78
83
  >>>
79
84
  >>> @my_plot.register("matplotlib")
80
- ... def _():
81
- ... print("Using matplotlib backend")
85
+ ... def _(*args, **kwargs):
86
+ ... dplt.process_matplotlib_kwargs(kwargs)
87
+ ... print(f"Using matplotlib backend with {args = }, {kwargs = }")
82
88
  >>>
83
89
  >>> my_plot() # When not specified, use default backend
84
- Using vispy backend
85
- >>>
86
- >>> my_plot(backend="matplotlib") # We can force the backend
87
- Using matplotlib backend
90
+ Using vispy backend with args = (), kwargs = {}
88
91
  >>>
89
- >>> dplt.set_defaults("matplotlib") # Or change the default backend...
92
+ >>> dplt.set_defaults("matplotlib") # We can change the default backend
90
93
  'matplotlib'
91
94
  >>> my_plot() # So that now it defaults to 'matplotlib'
92
- Using matplotlib backend
95
+ Using matplotlib backend with args = (), kwargs = {}
93
96
  >>>
97
+ >>> dplt.set_defaults(
98
+ ... "matplotlib", color="red"
99
+ ... ) # We can also specify additional defaults
100
+ 'matplotlib'
101
+ >>> my_plot() # So that now it defaults to 'matplotlib' and color='red'
102
+ Using matplotlib backend with args = (), kwargs = {'color': 'red'}
94
103
  >>> my_plot(backend="vispy") # Of course, the 'vispy' backend is still available
95
- Using vispy backend
104
+ Using vispy backend with args = (), kwargs = {'color': 'red'}
105
+ >>> my_plot(backend="vispy", color="green") # And we can also override any default
106
+ Using vispy backend with args = (), kwargs = {'color': 'green'}
107
+ >>> dplt.set_defaults("vispy") # Reset all defaults
108
+ 'vispy'
96
109
  """
97
110
  global DEFAULT_BACKEND, DEFAULT_KWARGS
98
111
 
@@ -104,16 +117,15 @@ def set_defaults(backend: str | None = None, **kwargs: Any) -> str:
104
117
  f"We currently support: {', '.join(SUPPORTED_BACKENDS)}."
105
118
  )
106
119
 
107
- with BACKEND_LOCK:
108
- try:
109
- importlib.import_module(f"{backend}")
110
- DEFAULT_BACKEND = backend
111
- DEFAULT_KWARGS = kwargs
112
- return backend
113
- except ImportError:
114
- raise ImportError(
115
- f"Could not load backend '{backend}', did you install it?"
116
- ) from None
120
+ try:
121
+ importlib.import_module(f"{backend}")
122
+ DEFAULT_BACKEND = backend
123
+ DEFAULT_KWARGS = kwargs
124
+ return backend
125
+ except ImportError:
126
+ raise ImportError(
127
+ f"Could not load backend '{backend}', did you install it?"
128
+ ) from None
117
129
 
118
130
 
119
131
  @contextmanager
@@ -132,34 +144,68 @@ def use(*args: Any, **kwargs: Any) -> Iterator[str]:
132
144
 
133
145
  Return:
134
146
  The name of the default backend used in this context.
147
+
148
+ Examples:
149
+ The following example shows how set plot defaults in a context.
150
+
151
+ >>> import differt.plotting as dplt
152
+ >>>
153
+ >>> @dplt.dispatch
154
+ ... def my_plot(*args, **kwargs):
155
+ ... pass
156
+ >>>
157
+ >>> @my_plot.register("vispy")
158
+ ... def _(*args, **kwargs):
159
+ ... dplt.process_vispy_kwargs(kwargs)
160
+ ... print(f"Using vispy backend with {args = }, {kwargs = }")
161
+ >>>
162
+ >>> @my_plot.register("plotly")
163
+ ... def _(*args, **kwargs):
164
+ ... dplt.process_plotly_kwargs(kwargs)
165
+ ... print(f"Using plotly backend with {args = }, {kwargs = }")
166
+ >>>
167
+ >>> my_plot() # When not specified, use default backend
168
+ Using vispy backend with args = (), kwargs = {}
169
+ >>> with dplt.use(): # No parameters = reset defaults (except the default backend)
170
+ ... my_plot()
171
+ Using vispy backend with args = (), kwargs = {}
172
+ >>> with dplt.use("plotly"): # We can change the default backend
173
+ ... my_plot() # So that now it defaults to 'matplotlib'
174
+ Using plotly backend with args = (), kwargs = {}
175
+ >>>
176
+ >>> with dplt.use(
177
+ ... "plotly", color="black"
178
+ ... ): # We can also specify additional defaults
179
+ ... my_plot()
180
+ Using plotly backend with args = (), kwargs = {'color': 'black'}
135
181
  """
136
182
  global DEFAULT_BACKEND, DEFAULT_KWARGS
137
183
  default_backend = DEFAULT_BACKEND
138
184
  default_kwargs = DEFAULT_KWARGS
139
185
 
140
- try:
141
- yield set_defaults(*args, **kwargs)
142
- finally:
143
- DEFAULT_BACKEND = default_backend
144
- DEFAULT_KWARGS = default_kwargs
186
+ with BACKEND_LOCK:
187
+ try:
188
+ yield set_defaults(*args, **kwargs)
189
+ finally:
190
+ DEFAULT_BACKEND = default_backend
191
+ DEFAULT_KWARGS = default_kwargs
145
192
 
146
193
 
147
- class Dispatcher(Protocol, Generic[P, T]): # pragma: no cover
194
+ class _Dispatcher(Generic[P, T]):
195
+ registry: types.MappingProxyType[str, Callable[P, T]]
196
+
148
197
  def __call__(
149
198
  self,
150
199
  *args: P.args,
151
200
  **kwargs: P.kwargs,
152
201
  ) -> T: ...
153
-
154
202
  def register(
155
203
  self,
156
204
  backend: str,
157
205
  ) -> Callable[[Callable[P, T]], Callable[P, T]]: ...
158
206
 
159
- def dispatch(self, backend: str) -> Callable[P, T]: ...
160
207
 
161
-
162
- def dispatch(fun: Callable[P, T]) -> Dispatcher[P, T]:
208
+ def dispatch(fun: Callable[P, T]) -> _Dispatcher[P, T]:
163
209
  """
164
210
  Transform a function into a backend dispatcher for plot functions.
165
211
 
@@ -168,8 +214,12 @@ def dispatch(fun: Callable[P, T]) -> Dispatcher[P, T]:
168
214
  functions for each backend implementation.
169
215
 
170
216
  Return:
171
- The same callable, wrapped in a :py:class:`Dispatcher`
172
- class instance.
217
+ A callable that can register backend implementations with ``register``.
218
+
219
+ Notes:
220
+ Only the functions registered with ``register`` will be called.
221
+ The :data:`fun` argument wrapped inside :func:`dispatch` is
222
+ only used for documentation, but never called.
173
223
 
174
224
  Examples:
175
225
  The following example shows how one can implement plotting
@@ -222,12 +272,21 @@ def dispatch(fun: Callable[P, T]) -> Dispatcher[P, T]:
222
272
  Traceback (most recent call last):
223
273
  ValueError: Unsupported backend 'numpy', allowed values are: ...
224
274
  """
225
- registry = {}
275
+ registry: dict[str, Callable[P, T]] = {}
226
276
 
227
277
  def register(
228
278
  backend: str,
229
279
  ) -> Callable[[Callable[P, T]], Callable[P, T]]:
230
- """Register a new implementation."""
280
+ """
281
+ Return a wrapper that will call the decorated function for the specified backend.
282
+
283
+ Args:
284
+ backend: The name of backend for which the decorated
285
+ function will be called.
286
+
287
+ Return:
288
+ A wrapper to be put before the backend-specific implementation.
289
+ """
231
290
  if backend not in SUPPORTED_BACKENDS:
232
291
  raise ValueError(
233
292
  f"Unsupported backend '{backend}', "
@@ -254,19 +313,21 @@ def dispatch(fun: Callable[P, T]) -> Dispatcher[P, T]:
254
313
 
255
314
  return wrapper
256
315
 
257
- def dispatch(backend: str) -> Callable[P, T]:
258
- try:
259
- return registry[backend]
260
- except KeyError:
261
- raise NotImplementedError(
262
- f"No backend implementation for '{backend}'"
263
- ) from None
264
-
265
316
  @wraps(fun)
266
- def main_wrapper(
317
+ def wrapper(
267
318
  *args: P.args,
268
319
  **kwargs: P.kwargs,
269
320
  ) -> T:
321
+ """
322
+ Call the appropriate backend implementation based on the default backend and the provided arguments.
323
+
324
+ Args:
325
+ args: Positional arguments passed to the correct backend implementation.
326
+ kwargs: Keyword arguments passed to the correct backend implementation.
327
+
328
+ Return:
329
+ The result of the call.
330
+ """
270
331
  # We cannot currently add keyword argument to the signature,
271
332
  # at least Pyright will not allow that,
272
333
  # see: https://github.com/microsoft/pyright/issues/5844.
@@ -274,16 +335,23 @@ def dispatch(fun: Callable[P, T]) -> Dispatcher[P, T]:
274
335
  # The motivation is detailed in P612:
275
336
  # https://peps.python.org/pep-0612/#concatenating-keyword-parameters.
276
337
  backend: str = kwargs.pop("backend", DEFAULT_BACKEND) # type: ignore
277
- return dispatch(backend)(*args, **kwargs)
278
338
 
279
- main_wrapper.register = register # type: ignore[attr-defined]
280
- main_wrapper.dispatch = dispatch # type: ignore[attr-defined]
281
- main_wrapper.registry = registry # type: ignore[attr-defined]
339
+ try:
340
+ return registry[backend](*args, **kwargs)
341
+ except KeyError:
342
+ raise NotImplementedError(
343
+ f"No backend implementation for '{backend}'"
344
+ ) from None
282
345
 
283
- return main_wrapper # type: ignore[return-value]
346
+ return wrapper
347
+
348
+ wrapper.register = register # type: ignore
349
+ wrapper.registry = types.MappingProxyType(registry) # type: ignore
284
350
 
351
+ return wrapper # type: ignore
285
352
 
286
- def view_from_canvas(canvas: SceneCanvas) -> ViewBox:
353
+
354
+ def view_from_canvas(canvas: Canvas) -> ViewBox:
287
355
  """
288
356
  Return the view from the specified canvas.
289
357
 
@@ -321,7 +389,7 @@ def view_from_canvas(canvas: SceneCanvas) -> ViewBox:
321
389
 
322
390
  def process_vispy_kwargs(
323
391
  kwargs: MutableMapping[str, Any],
324
- ) -> tuple[SceneCanvas, ViewBox]:
392
+ ) -> tuple[Canvas, ViewBox]:
325
393
  """
326
394
  Process keyword arguments passed to some VisPy plotting utility.
327
395
 
@@ -333,7 +401,7 @@ def process_vispy_kwargs(
333
401
  The keys specified below will be removed from the mapping.
334
402
 
335
403
  Keyword Args:
336
- convas (:py:class:`SceneCanvas<vispy.scene.canvas.SceneCanvas>`):
404
+ canvas (:py:class:`SceneCanvas<vispy.scene.canvas.SceneCanvas>`):
337
405
  The canvas that draws contents of the scene. If not provided,
338
406
  will try to access canvas from ``view`` (if supplied).
339
407
  view (:py:class:`Viewbox<vispy.scene.widgets.viewbox.ViewBox>`):
@@ -410,7 +478,7 @@ def process_matplotlib_kwargs(
410
478
  or plt.figure()
411
479
  )
412
480
 
413
- def current_ax3d() -> Axes3D | None:
481
+ def current_ax3d() -> Optional[Axes3D]:
414
482
  if len(figure.axes) > 0:
415
483
  ax = figure.gca()
416
484
  if isinstance(ax, Axes3D):
@@ -455,20 +523,36 @@ def process_plotly_kwargs(
455
523
 
456
524
 
457
525
  @contextmanager
458
- def reuse(**kwargs: Any) -> Iterator[SceneCanvas | MplFigure | Figure]:
526
+ def reuse(**kwargs: Any) -> Iterator[Union[Canvas, MplFigure, Figure]]:
459
527
  """Create a context manager that will automatically reuse the current canvas / figure.
460
528
 
461
529
  Args:
462
- args: Positional arguments passed to
463
- :py:func:`set_defaults`.
464
530
  kwargs: Keywords arguments passed to
465
531
  :py:func:`set_defaults`.
466
532
 
467
533
  Return:
468
534
  The canvas or figure that is reused for this context.
535
+
536
+ Examples:
537
+ The following example show how the same figure is reused
538
+ for multiple plots.
539
+
540
+ .. plotly::
541
+
542
+ >>> from differt.plotting import draw_image, reuse
543
+ >>>
544
+ >>> x = np.linspace(-1.0, +1.0, 100)
545
+ >>> y = np.linspace(-4.0, +4.0, 200)
546
+ >>> X, Y = np.meshgrid(x, y)
547
+ >>>
548
+ >>> with reuse(backend="plotly") as fig: # doctest: +SKIP
549
+ ... for z0, w in enumerate(jnp.linspace(0, 10 * jnp.pi, 5)):
550
+ ... Z = np.cos(w * X) * np.sin(w * Y)
551
+ ... draw_image(Z, x=x, y=y, z0=z0) # TODO: fix colorbar
552
+ >>> fig # doctest: +SKIP
469
553
  """
470
554
  global DEFAULT_KWARGS
471
- backend: str | None = kwargs.pop("backend", None)
555
+ backend: Optional[str] = kwargs.pop("backend", None)
472
556
 
473
557
  with use(backend=backend) as b:
474
558
  try:
@@ -5,12 +5,13 @@ from collections.abc import Iterable, Mapping
5
5
  from functools import partial
6
6
  from typing import Any, Callable, Optional, Union
7
7
 
8
- import chex # TODO: fixme, chex is not a dependency
8
+ import chex
9
+ import equinox as eqx
9
10
  import jax
10
11
  import jax.numpy as jnp
11
12
  import optax
12
13
  from beartype import beartype as typechecker
13
- from jaxtyping import Array, Num, Shaped, jaxtyped
14
+ from jaxtyping import Array, Float, Num, PRNGKeyArray, Shaped, jaxtyped
14
15
 
15
16
  if sys.version_info >= (3, 11):
16
17
  from typing import TypeVarTuple, Unpack
@@ -229,3 +230,32 @@ def minimize(
229
230
  (x, _), losses = jax.lax.scan(f, init=(x0, opt_state), xs=None, length=steps)
230
231
 
231
232
  return x, losses[-1]
233
+
234
+
235
+ @eqx.filter_jit
236
+ @jaxtyped(typechecker=typechecker)
237
+ def sample_points_in_bounding_box(
238
+ bounding_box: Float[Array, "2 3"], size: Optional[int] = None, *, key: PRNGKeyArray
239
+ ) -> Union[Float[Array, "size 3"], Float[Array, "3"]]:
240
+ """
241
+ Sample point(s) in a 3D bounding box.
242
+
243
+ Args:
244
+ bounding_box: The bounding box (min. and max. coordinates).
245
+ size: The sample size or :py:data:`None`. If :py:data:`None`,
246
+ the returned array is 1D. Otherwise, it is 2D.
247
+ key: The :class:`jax.random.PRNGKey` to be used.
248
+
249
+ Return:
250
+ An array of points randomly sampled.
251
+ """
252
+ amin = bounding_box[0, :]
253
+ amax = bounding_box[1, :]
254
+ scale = amax - amin
255
+
256
+ if size is None:
257
+ r = jax.random.uniform(key, shape=(3,))
258
+ return r * scale + amin
259
+
260
+ r = jax.random.uniform(key, shape=(size, 3))
261
+ return r * scale[None, :] + amin[None, :]
File without changes
File without changes
File without changes