differt 0.0.38__tar.gz → 0.1.1__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 (34) hide show
  1. {differt-0.0.38 → differt-0.1.1}/PKG-INFO +13 -4
  2. {differt-0.0.38 → differt-0.1.1}/README.md +11 -2
  3. {differt-0.0.38 → differt-0.1.1}/pyproject.toml +1 -1
  4. {differt-0.0.38 → differt-0.1.1}/src/differt/em/_interaction_type.py +1 -1
  5. {differt-0.0.38 → differt-0.1.1}/src/differt/em/_material.py +3 -1
  6. {differt-0.0.38 → differt-0.1.1}/src/differt/geometry/_paths.py +79 -14
  7. {differt-0.0.38 → differt-0.1.1}/src/differt/geometry/_triangle_mesh.py +3 -2
  8. {differt-0.0.38 → differt-0.1.1}/src/differt/geometry/_utils.py +2 -2
  9. {differt-0.0.38 → differt-0.1.1}/src/differt/plotting/_core.py +1 -1
  10. differt-0.1.1/src/differt/plugins/__init__.py +4 -0
  11. differt-0.1.1/src/differt/plugins/_deepmimo_types.py +9 -0
  12. differt-0.1.1/src/differt/plugins/deepmimo.py +577 -0
  13. {differt-0.0.38 → differt-0.1.1}/src/differt/rt/_utils.py +2 -1
  14. {differt-0.0.38 → differt-0.1.1}/src/differt/scene/_triangle_scene.py +92 -3
  15. {differt-0.0.38 → differt-0.1.1}/src/differt/utils.py +1 -1
  16. {differt-0.0.38 → differt-0.1.1}/.gitignore +0 -0
  17. {differt-0.0.38 → differt-0.1.1}/LICENSE.md +0 -0
  18. {differt-0.0.38 → differt-0.1.1}/src/differt/__init__.py +0 -0
  19. {differt-0.0.38 → differt-0.1.1}/src/differt/_version.py +0 -0
  20. {differt-0.0.38 → differt-0.1.1}/src/differt/em/__init__.py +0 -0
  21. {differt-0.0.38 → differt-0.1.1}/src/differt/em/_antenna.py +0 -0
  22. {differt-0.0.38 → differt-0.1.1}/src/differt/em/_constants.py +0 -0
  23. {differt-0.0.38 → differt-0.1.1}/src/differt/em/_fresnel.py +0 -0
  24. {differt-0.0.38 → differt-0.1.1}/src/differt/em/_utd.py +0 -0
  25. {differt-0.0.38 → differt-0.1.1}/src/differt/em/_utils.py +0 -0
  26. {differt-0.0.38 → differt-0.1.1}/src/differt/geometry/__init__.py +0 -0
  27. {differt-0.0.38 → differt-0.1.1}/src/differt/plotting/__init__.py +0 -0
  28. {differt-0.0.38 → differt-0.1.1}/src/differt/plotting/_utils.py +0 -0
  29. {differt-0.0.38 → differt-0.1.1}/src/differt/py.typed +0 -0
  30. {differt-0.0.38 → differt-0.1.1}/src/differt/rt/__init__.py +0 -0
  31. {differt-0.0.38 → differt-0.1.1}/src/differt/rt/_fermat.py +0 -0
  32. {differt-0.0.38 → differt-0.1.1}/src/differt/rt/_image_method.py +0 -0
  33. {differt-0.0.38 → differt-0.1.1}/src/differt/scene/__init__.py +0 -0
  34. {differt-0.0.38 → differt-0.1.1}/src/differt/scene/_sionna.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: DiffeRT
3
- Version: 0.0.38
3
+ Version: 0.1.1
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.13
21
21
  Classifier: Topic :: Scientific/Engineering
22
22
  Requires-Python: >=3.10
23
23
  Requires-Dist: chex>=0.1.86
24
- Requires-Dist: differt-core==0.0.38
24
+ Requires-Dist: differt-core==0.1.1
25
25
  Requires-Dist: equinox>=0.12.2
26
26
  Requires-Dist: filelock>=3.15.4
27
27
  Requires-Dist: jax<0.6,>=0.4.32
@@ -132,8 +132,17 @@ for a detailed step-by-step procedure.
132
132
 
133
133
  ## Citing
134
134
 
135
- If you use this software, please cite it as
136
- [detailed here](https://differt.readthedocs.io/latest/citing.html).
135
+ If you use this software, please cite it as:
136
+
137
+ ```bibtex
138
+ @software{Eertmans_Differentiable_Ray_Tracing,
139
+ title = {{DiffeRT: A Differentiable Ray Tracing Toolbox for Radio Propagation Simulations}},
140
+ author = {Eertmans, Jérome},
141
+ url = {https://github.com/jeertmans/DiffeRT},
142
+ license = {MIT},
143
+ version = {v0.1.1}
144
+ }
145
+ ```
137
146
 
138
147
  [pypi-version-badge]: https://img.shields.io/pypi/v/DiffeRT?label=DiffeRT&color=blueviolet
139
148
  [pypi-version-url]: https://pypi.org/project/DiffeRT/
@@ -75,8 +75,17 @@ for a detailed step-by-step procedure.
75
75
 
76
76
  ## Citing
77
77
 
78
- If you use this software, please cite it as
79
- [detailed here](https://differt.readthedocs.io/latest/citing.html).
78
+ If you use this software, please cite it as:
79
+
80
+ ```bibtex
81
+ @software{Eertmans_Differentiable_Ray_Tracing,
82
+ title = {{DiffeRT: A Differentiable Ray Tracing Toolbox for Radio Propagation Simulations}},
83
+ author = {Eertmans, Jérome},
84
+ url = {https://github.com/jeertmans/DiffeRT},
85
+ license = {MIT},
86
+ version = {v0.1.1}
87
+ }
88
+ ```
80
89
 
81
90
  [pypi-version-badge]: https://img.shields.io/pypi/v/DiffeRT?label=DiffeRT&color=blueviolet
82
91
  [pypi-version-url]: https://pypi.org/project/DiffeRT/
@@ -16,7 +16,7 @@ classifiers = [
16
16
  ]
17
17
  dependencies = [
18
18
  "chex>=0.1.86",
19
- "differt-core==0.0.38",
19
+ "differt-core==0.1.1",
20
20
  "equinox>=0.12.2",
21
21
  "filelock>=3.15.4",
22
22
  "jax>=0.4.32,<0.6", # TODO: fixme, issue with pmap
@@ -6,7 +6,7 @@ class InteractionType(IntEnum):
6
6
  """Enumeration of interaction types."""
7
7
 
8
8
  REFLECTION = 0
9
- """Specular reflection on an surface."""
9
+ """Specular reflection on a surface."""
10
10
  DIFFRACTION = 1
11
11
  """Diffraction on an edge."""
12
12
  SCATTERING = 2
@@ -1,5 +1,7 @@
1
1
  # ruff: noqa: FURB152
2
+
2
3
  import operator
4
+ import os
3
5
  from collections.abc import Callable
4
6
  from functools import partial
5
7
  from typing import TYPE_CHECKING, Any
@@ -9,7 +11,7 @@ import jax
9
11
  import jax.numpy as jnp
10
12
  from jaxtyping import Array, ArrayLike, Float
11
13
 
12
- if TYPE_CHECKING:
14
+ if TYPE_CHECKING or "READTHEDOCS" in os.environ:
13
15
  import sys
14
16
 
15
17
  if sys.version_info >= (3, 11):
@@ -1,3 +1,5 @@
1
+ import math
2
+ import os
1
3
  import warnings
2
4
  from collections.abc import Callable, Iterator, Sequence
3
5
  from dataclasses import KW_ONLY
@@ -10,7 +12,7 @@ from jaxtyping import Array, ArrayLike, Bool, Float, Int, Num, Shaped
10
12
 
11
13
  from differt.plotting import PlotOutput, draw_paths, reuse
12
14
 
13
- if TYPE_CHECKING:
15
+ if TYPE_CHECKING or "READTHEDOCS" in os.environ:
14
16
  import sys
15
17
 
16
18
  if sys.version_info >= (3, 11):
@@ -133,6 +135,16 @@ class Paths(eqx.Module):
133
135
  )
134
136
  warnings.warn(msg, UserWarning, stacklevel=2)
135
137
 
138
+ @property
139
+ def shape(self) -> tuple[int, ...]:
140
+ """
141
+ Return the batch shape of the paths.
142
+
143
+ Returns:
144
+ The shape of paths' batch dimensions.
145
+ """
146
+ return self.vertices.shape[:-2]
147
+
136
148
  def reshape(self, *batch: int) -> Self:
137
149
  """
138
150
  Return a copy with reshaped paths' batch dimensions to match a given shape.
@@ -270,16 +282,26 @@ class Paths(eqx.Module):
270
282
  for _ in range(max(ndim - 1, 0)):
271
283
  f = jax.vmap(f)
272
284
 
273
- # TODO: mask the 'confidence' attribute too
285
+ non_duplicates = f(objects)
286
+ non_duplicates = jnp.moveaxis(non_duplicates, -1, axis)
274
287
 
275
- mask = f(objects)
276
- mask = jnp.moveaxis(mask, -1, axis)
277
- mask = mask & self.mask if self.mask is not None else mask
288
+ if self.mask is not None:
289
+ return eqx.tree_at(
290
+ lambda p: p.mask,
291
+ self,
292
+ self.mask & non_duplicates,
293
+ )
294
+ if self.confidence is not None:
295
+ return eqx.tree_at(
296
+ lambda p: p.confidence,
297
+ self,
298
+ self.confidence * non_duplicates,
299
+ )
278
300
 
279
301
  return eqx.tree_at(
280
302
  lambda p: p.mask,
281
303
  self,
282
- mask,
304
+ non_duplicates,
283
305
  is_leaf=lambda x: x is None,
284
306
  )
285
307
 
@@ -291,7 +313,7 @@ class Paths(eqx.Module):
291
313
  @property
292
314
  def order(self) -> int:
293
315
  """The length (i.e., number of vertices) of each individual path, excluding start and end vertices."""
294
- return self.objects.shape[-1] - 2
316
+ return self.path_length - 2
295
317
 
296
318
  @property
297
319
  def num_valid_paths(self) -> int | Int[Array, " "]:
@@ -303,7 +325,7 @@ class Paths(eqx.Module):
303
325
  return self.mask.sum()
304
326
  if self.confidence is not None:
305
327
  return (self.confidence >= self.confidence_threshold).sum()
306
- return self.objects[..., 0].size
328
+ return math.prod(self.objects.shape[:-1])
307
329
 
308
330
  @property
309
331
  def masked_vertices(
@@ -340,6 +362,51 @@ class Paths(eqx.Module):
340
362
  return objects[mask, ...]
341
363
  return objects
342
364
 
365
+ def masked(self) -> Self:
366
+ """Return a flattened copy of this object that only keeps valid paths.
367
+
368
+ The returned object has all batch dimensions flattened into one,
369
+ keeping only the paths where :attr:`mask` is :data:`True` (or where :attr:`confidence` is greater than or equal to :attr:`confidence_threshold`), and :attr:`mask` and :attr:`confidence` attributes are set to :data:`None`.
370
+
371
+ Returns:
372
+ A new paths instance with flattened batch dimensions and only valid paths.
373
+ """
374
+ batch_len = len(self.vertices.shape) - 2
375
+ self = jax.tree.map( # noqa: PLW0642
376
+ lambda arr: arr.reshape(-1, *arr.shape[batch_len:])
377
+ if jnp.ndim(arr) >= batch_len
378
+ else arr,
379
+ self,
380
+ )
381
+
382
+ if self.mask is not None:
383
+ mask = self.mask.reshape(-1)
384
+ elif self.confidence is not None:
385
+ mask = self.confidence.reshape(-1) >= self.confidence_threshold
386
+ else:
387
+ mask = slice(None, None, None)
388
+
389
+ return eqx.tree_at(
390
+ lambda p: (
391
+ p.vertices,
392
+ p.objects,
393
+ p.mask,
394
+ p.interaction_types,
395
+ p.confidence,
396
+ ),
397
+ self,
398
+ (
399
+ self.vertices[mask, ...],
400
+ self.objects[mask, ...],
401
+ None,
402
+ self.interaction_types[mask, ...]
403
+ if self.interaction_types is not None
404
+ else None,
405
+ None,
406
+ ),
407
+ is_leaf=lambda x: x is None,
408
+ )
409
+
343
410
  @eqx.filter_jit
344
411
  def multipath_cells(
345
412
  self,
@@ -390,7 +457,8 @@ class Paths(eqx.Module):
390
457
  if self.mask is not None:
391
458
  mask = jnp.moveaxis(self.mask, axis, -1)
392
459
  else:
393
- mask = jnp.moveaxis(self.confidence >= self.confidence_threshold, axis, -1)
460
+ # Looks like Pyright is not able to infer this
461
+ mask = jnp.moveaxis(self.confidence >= self.confidence_threshold, axis, -1) # type: ignore[reportOperatorIssue]
394
462
  *partial_batch, last_axis = mask.shape
395
463
 
396
464
  return _cell_ids(mask.reshape(-1, last_axis)).reshape(partial_batch)
@@ -568,11 +636,8 @@ class SBRPaths(Paths):
568
636
  )
569
637
 
570
638
  def plot(self, **kwargs: Any) -> PlotOutput:
571
- backend = kwargs.pop(
572
- "backend", None
573
- ) # TODO: check if kwargs may not cause issues
574
- with reuse(backend=backend) as output:
639
+ with reuse(**kwargs, pass_all_kwargs=True) as output:
575
640
  for order in range(self.order + 1):
576
- self.get_paths(order).plot(**kwargs)
641
+ self.get_paths(order).plot()
577
642
 
578
643
  return output
@@ -1,5 +1,6 @@
1
1
  # ruff: noqa: ERA001
2
2
 
3
+ import os
3
4
  from collections.abc import Callable, Iterator, Mapping
4
5
  from dataclasses import replace
5
6
  from typing import TYPE_CHECKING, Any, Generic, TypeVar, overload
@@ -14,7 +15,7 @@ from differt.plotting import PlotOutput, draw_mesh, draw_paths, draw_rays, reuse
14
15
 
15
16
  from ._utils import normalize, orthogonal_basis, rotation_matrix_along_axis
16
17
 
17
- if TYPE_CHECKING:
18
+ if TYPE_CHECKING or "READTHEDOCS" in os.environ:
18
19
  import sys
19
20
 
20
21
  if sys.version_info >= (3, 11):
@@ -278,7 +279,7 @@ class TriangleMesh(eqx.Module):
278
279
 
279
280
  def iter_objects(self) -> Iterator[Self]:
280
281
  """
281
- Iterator over sub meshes (i.e., objects) defined by :attr:`object_bounds`.
282
+ Return an iterator over sub meshes (i.e., objects) defined by :attr:`object_bounds`.
282
283
 
283
284
  If :attr:`object_bounds` is :data:`None`, then yield ``self``.
284
285
 
@@ -802,8 +802,8 @@ def cartesian_to_spherical(
802
802
  xyz = jnp.asarray(xyz)
803
803
  r = jnp.linalg.norm(xyz, axis=-1)
804
804
  r: Array = jnp.where(r == 0.0, jnp.ones_like(r), r)
805
- p = jnp.arccos(xyz[..., -1] / r)
806
- a = jnp.arctan2(xyz[..., 1], xyz[..., 0])
805
+ p = jnp.acos(xyz[..., -1] / r)
806
+ a = jnp.atan2(xyz[..., 1], xyz[..., 0])
807
807
 
808
808
  return jnp.stack((r, p, a), axis=-1)
809
809
 
@@ -544,7 +544,7 @@ def _(
544
544
 
545
545
  xs, ys, zs = np.asarray(markers).reshape(-1, 3).T
546
546
 
547
- ax.scatter(xs, ys, zs=zs, **kwargs)
547
+ ax.scatter(xs, ys, zs=zs, **kwargs) # type: ignore[reportArgumentType]
548
548
 
549
549
  return fig
550
550
 
@@ -0,0 +1,4 @@
1
+ """DiffeRT plugins.
2
+
3
+ Plugins extend the functionality of DiffeRT by providing additional features or integrations with other libraries.
4
+ """
@@ -0,0 +1,9 @@
1
+ __all__ = ("ArrayType",)
2
+
3
+ from typing import TypeVar
4
+
5
+ import numpy as np
6
+ from jaxtyping import Array
7
+
8
+ # NOTE: we declare this is another module to be able to patch it when building the docs
9
+ ArrayType = TypeVar("ArrayType", bound=Array | np.ndarray)
@@ -0,0 +1,577 @@
1
+ """Utilities to work with the DeepMIMO framework."""
2
+
3
+ __all__ = ("DeepMIMO", "export")
4
+
5
+ from collections.abc import Iterable, Iterator, Mapping
6
+ from dataclasses import KW_ONLY, asdict
7
+ from typing import Any, Generic
8
+
9
+ import equinox as eqx
10
+ import jax
11
+ import jax.numpy as jnp
12
+ import numpy as np
13
+ from jaxtyping import Array, ArrayLike, Bool, Float, Int
14
+
15
+ from differt.em import (
16
+ InteractionType,
17
+ Material,
18
+ c,
19
+ materials,
20
+ reflection_coefficients,
21
+ sp_directions,
22
+ z_0,
23
+ )
24
+ from differt.geometry import (
25
+ Paths,
26
+ cartesian_to_spherical,
27
+ normalize,
28
+ )
29
+ from differt.plotting import PlotOutput, draw_paths, reuse
30
+ from differt.rt import SizedIterator
31
+ from differt.scene import TriangleScene
32
+ from differt.utils import dot, safe_divide
33
+
34
+ from ._deepmimo_types import ArrayType
35
+
36
+
37
+ class DeepMIMO(eqx.Module, Generic[ArrayType]):
38
+ """DeepMIMO format data structure.
39
+
40
+ The generic type parameter ``ArrayType`` can be either a JAX array or a NumPy array, indicating
41
+ whether the data is in JAX or NumPy format.
42
+
43
+ For elevation and azimuth angles, the reference coordinate system is detailed in :ref:`conventions`.
44
+ """
45
+
46
+ _: KW_ONLY
47
+ power: Float[ArrayType, "num_tx num_rx num_paths"]
48
+ r"""Tap power. Received power in dBW for each path, assuming 0 dBW transmitted power. :math:`10\log10(|a|^2)`, where :math:`a` is the complex channel amplitude"""
49
+ phase: Float[ArrayType, "num_tx num_rx num_paths"]
50
+ r"""Tap phase. Phase of received signal for each path in degrees. :math:`\angle a` (angle of :math:`a`), where :math:`a` is the complex channel amplitude"""
51
+ delay: Float[ArrayType, "num_tx num_rx num_paths"]
52
+ """Tap delay. Propagation delay for each path in seconds."""
53
+ aoa_az: Float[ArrayType, "num_tx num_rx num_paths"]
54
+ """Angle of arrival (azimuth) for each path in degrees."""
55
+ aoa_el: Float[ArrayType, "num_tx num_rx num_paths"]
56
+ """Angle of arrival (elevation) for each path in degrees."""
57
+ aod_az: Float[ArrayType, "num_tx num_rx num_paths"]
58
+ """Angle of departure (azimuth) for each path in degrees."""
59
+ aod_el: Float[ArrayType, "num_tx num_rx num_paths"]
60
+ """Angle of departure (elevation) for each path in degrees."""
61
+ primitives: (
62
+ Int[ArrayType, "num_tx num_rx num_paths max_num_interactions"] | None
63
+ ) = None
64
+ """Indices of primitives hit along each path.
65
+
66
+ .. note::
67
+
68
+ This field is optional and is provided if ``include_primitives`` is set to :data:`True` in the
69
+ :func:`export` function.
70
+
71
+ A value of -1 indicates no primitive hit, i.e., a path that is terminated early.
72
+ """
73
+ inter: Int[ArrayType, "num_tx num_rx num_paths max_num_interactions"]
74
+ """Type of interactions along each path.
75
+
76
+ Matches :class:`InteractionType<differt.em.InteractionType>`, but a value of -1 indicates no interaction,
77
+ i.e., a path that is terminated early.
78
+ """
79
+ inter_pos: Float[ArrayType, "num_tx num_rx num_paths max_num_interactions 3"]
80
+ """3D coordinates in meters of each interaction point along paths."""
81
+ rx_pos: Float[ArrayType, "num_rx 3"]
82
+ """Receiver positions in 3D coordinates in meters."""
83
+ tx_pos: Float[ArrayType, "num_tx 3"]
84
+ """Transmitter positions in 3D coordinates in meters."""
85
+ mask: Bool[ArrayType, "num_tx num_rx num_paths"]
86
+ """Mask indicating valid paths."""
87
+
88
+ @property
89
+ def num_tx(self) -> int:
90
+ """Number of transmitters."""
91
+ return self.mask.shape[0]
92
+
93
+ @property
94
+ def num_rx(self) -> int:
95
+ """Number of receivers."""
96
+ return self.mask.shape[1]
97
+
98
+ @property
99
+ def num_paths(self) -> int:
100
+ """Number of paths."""
101
+ return self.mask.shape[2]
102
+
103
+ def asdict(self) -> dict[str, ArrayType]:
104
+ """
105
+ Convert this class to a dictionary.
106
+
107
+ Returns:
108
+ A dictionary where keys are attribute names and values are arrays.
109
+ """
110
+ return asdict(self)
111
+
112
+ def _sort(
113
+ self,
114
+ paths: "sionna.rt.Paths", # type: ignore[reportUndefinedVariable] # noqa: F821
115
+ ) -> "DeepMIMO[ArrayType]":
116
+ """Utility function to sort the DeepMIMO based on :class:`sionna.rt.Paths`' vertices.""" # noqa: DOC201, DOC501
117
+ vertices = jnp.moveaxis(paths.vertices.jax(), 0, -2)
118
+ interactions = (
119
+ jnp.moveaxis(paths.interactions.jax(), 0, -1).astype(self.inter.dtype) - 1
120
+ )
121
+
122
+ if vertices.shape != self.inter_pos.shape: # pragma: no cover
123
+ msg = "Cannot sort based on provided paths: shape mismatch, got {vertices.shape!r} but expected {self.inter_pos.shape!r}."
124
+ raise ValueError(msg)
125
+
126
+ max_num_interactions = self.inter.shape[-1]
127
+ indices = (
128
+ jnp.linalg.norm(
129
+ self.inter_pos.reshape(-1, 1, max_num_interactions, 3)
130
+ - vertices.reshape(
131
+ 1,
132
+ -1,
133
+ max_num_interactions,
134
+ 3,
135
+ ),
136
+ axis=3,
137
+ )
138
+ .sum(
139
+ axis=2,
140
+ initial=jnp.where(
141
+ (
142
+ self.inter.reshape(-1, 1, max_num_interactions)
143
+ == interactions.reshape(1, -1, max_num_interactions)
144
+ ).all(axis=-1),
145
+ jnp.inf,
146
+ 0,
147
+ ),
148
+ where=self.inter.reshape(-1, 1, max_num_interactions) != -1,
149
+ )
150
+ .argmin(axis=1)
151
+ )
152
+
153
+ shape_prefix = (self.num_tx, self.num_rx, self.num_paths)
154
+
155
+ def sort_fn(x: ArrayType) -> ArrayType:
156
+ if x.shape[: len(shape_prefix)] != shape_prefix:
157
+ return x
158
+
159
+ y = x.reshape(-1, *x.shape[len(shape_prefix) :])
160
+ y = y[indices, ...]
161
+ return y.reshape(x.shape) # type: ignore[reportReturnType]
162
+
163
+ return jax.tree.map(sort_fn, self)
164
+
165
+ def jax(self) -> "DeepMIMO[Array]":
166
+ """
167
+ Return a copy of this class with arrays converted to JAX arrays.
168
+
169
+ Returns:
170
+ A copy of this with JAX arrays.
171
+ """
172
+ return jax.tree.map(jnp.asarray, self)
173
+
174
+ def numpy(self) -> "DeepMIMO[np.ndarray]":
175
+ """
176
+ Return a copy of this class with arrays converted to NumPy arrays.
177
+
178
+ Returns:
179
+ A copy of this with NumPy arrays.
180
+ """
181
+ return jax.tree.map(np.asarray, self)
182
+
183
+ def iter_paths(
184
+ self,
185
+ ) -> SizedIterator[Float[Array, "num_tx num_rx num_paths num_interactions 3"]]:
186
+ """
187
+ Return an iterator over the path vertices in this DeepMIMO object.
188
+
189
+ Returns:
190
+ An iterator of path vertices, grouped by ascending number of interactions, from
191
+ ``0`` to ``max_num_interactions``.
192
+ """
193
+ max_num_interactions = self.inter.shape[-1]
194
+
195
+ def it() -> Iterator[
196
+ Float[Array, "num_tx num_rx num_paths num_interactions 3"]
197
+ ]:
198
+ num_interactions = jnp.min(
199
+ jnp.broadcast_to(jnp.arange(max_num_interactions), self.inter.shape),
200
+ initial=max_num_interactions,
201
+ where=self.inter == -1,
202
+ axis=-1,
203
+ )
204
+
205
+ for num in range(max_num_interactions + 1):
206
+ where = (self.mask & (num_interactions == num)).reshape(-1)
207
+ tx_pos = jnp.broadcast_to(
208
+ self.tx_pos[:, None, None, :],
209
+ (self.num_tx, self.num_rx, self.num_paths, 3),
210
+ ).reshape(-1, 3)[where, :]
211
+ rx_pos = jnp.broadcast_to(
212
+ self.rx_pos[None, :, None, :],
213
+ (self.num_tx, self.num_rx, self.num_paths, 3),
214
+ ).reshape(-1, 3)[where, :]
215
+ inter_pos = self.inter_pos.reshape(-1, max_num_interactions, 3)[
216
+ where, :num, :
217
+ ]
218
+ yield jnp.concatenate(
219
+ (tx_pos[..., None, :], inter_pos, rx_pos[..., None, :]), axis=-2
220
+ )
221
+
222
+ return SizedIterator(it(), size=max_num_interactions + 1)
223
+
224
+ def plot_paths(self, **kwargs: Any) -> PlotOutput:
225
+ """
226
+ Plot the valid paths in this DeepMIMO object.
227
+
228
+ Args:
229
+ kwargs: Keyword arguments passed to
230
+ :func:`draw_paths<differt.plotting.draw_paths>`.
231
+
232
+ Returns:
233
+ The resulting plot output.
234
+
235
+ Examples:
236
+ The following example shows how to call :func:`export` and use
237
+ the :class:`DeepMIMO` object to plot all paths.
238
+
239
+ .. plotly::
240
+ :fig-vars: fig
241
+
242
+ >>> import equinox as eqx
243
+ >>> from differt.plugins import deepmimo
244
+ >>> from differt.scene import TriangleScene, get_sionna_scene
245
+ >>> from differt.plotting import reuse
246
+ >>>
247
+ >>> file = get_sionna_scene("simple_street_canyon")
248
+ >>> scene = TriangleScene.load_xml(file)
249
+ >>> scene = eqx.tree_at(
250
+ ... lambda s: s.transmitters, scene, jnp.array([-33.0, 0.0, 32.0])
251
+ ... )
252
+ >>> scene = eqx.tree_at(
253
+ ... lambda s: s.receivers, scene, jnp.array([33.0, 0.0, 2.0])
254
+ ... )
255
+ >>>
256
+ >>> with reuse(backend="plotly") as fig: # doctest: +SKIP
257
+ ... scene.plot()
258
+ ... paths = (
259
+ ... scene.compute_paths(order=order) for order in [0, 1, 2]
260
+ ... )
261
+ ... dm = deepmimo.export(paths=paths, scene=scene, frequency=2.4e9)
262
+ ... dm.plot_paths()
263
+ >>> fig # doctest: +SKIP
264
+ """
265
+ with reuse(**kwargs, pass_all_kwargs=True) as output:
266
+ for paths in self.iter_paths():
267
+ draw_paths(
268
+ paths,
269
+ )
270
+
271
+ return output
272
+
273
+
274
+ def export( # noqa: PLR0915
275
+ *,
276
+ paths: Paths | Iterable[Paths],
277
+ scene: TriangleScene,
278
+ radio_materials: Mapping[str, Material] | None = None,
279
+ frequency: Float[ArrayLike, " "],
280
+ include_primitives: bool = False,
281
+ ) -> DeepMIMO[Array]:
282
+ """
283
+ Export a Ray Tracing simulation to the DeepMIMO format.
284
+
285
+ .. note::
286
+ The current implementation assumes far-field propagation in free space, and isotropic antennas with vertical polarization.
287
+
288
+ While tests show a good match with Sionna's :class:`sionna.rt.PathSolver` for most attributes,
289
+ :attr:`DeepMIMO.power` and :attr:`DeepMIMO.phase` are not exactly equals, and we don't know yet if our implementation is 100% correct. If you know how to improve this, please open an issue or a pull-request on GitHub!
290
+
291
+ Args:
292
+ paths: The geometrical paths.
293
+
294
+ You can provide paths with different numbers of interactions by passing an iterable.
295
+
296
+ E.g., the return value of :meth:`TriangleScene.compute_paths<differt.scene.TriangleScene.compute_paths>`.
297
+
298
+ scene: The scene that was used to compute the paths.
299
+ radio_materials: The list of materials in the scene.
300
+
301
+ If not provided, :data:`materials<differt.em._material.materials>` will be used.
302
+ frequency: The operating frequency (in Hz).
303
+ include_primitives: If :data:`True`, include the primitive indices in the output.
304
+
305
+ Returns:
306
+ The exported DeepMIMO data as JAX arrays.
307
+
308
+ Raises:
309
+ ValueError: If the scene does not contain information about face materials.
310
+ """
311
+ if scene.mesh.face_materials is None:
312
+ msg = "Scene must contain information about face materials."
313
+ raise ValueError(msg)
314
+ if radio_materials is None:
315
+ radio_materials = materials
316
+
317
+ paths_iter = [paths] if isinstance(paths, Paths) else paths
318
+ del paths
319
+
320
+ eta_r = jnp.array([
321
+ materials[mat_name].relative_permittivity(frequency)
322
+ for mat_name in scene.mesh.material_names
323
+ ])
324
+ n_r = jnp.sqrt(eta_r)
325
+
326
+ tx_pos = scene.transmitters.reshape(-1, 3)
327
+ num_tx = tx_pos.shape[0]
328
+ rx_pos = scene.receivers.reshape(-1, 3)
329
+ num_rx = rx_pos.shape[0]
330
+
331
+ no_interaction = -1 # Placeholder for no interaction
332
+
333
+ # Fields array
334
+ fields = jnp.zeros((num_tx, num_rx, 0, 3), dtype=complex)
335
+ polarization = jnp.array([0.0, 0.0, 1.0], dtype=float)
336
+ # Direction of departure (DoD) and direction of arrival (DoA) segments
337
+ k_d = jnp.zeros((num_tx, num_rx, 0, 3), dtype=float)
338
+ k_a = jnp.zeros_like(k_d)
339
+ # Path lengths
340
+ lengths = jnp.zeros((num_tx, num_rx, 0), dtype=float)
341
+ if include_primitives:
342
+ # Primitive indices
343
+ primitives = jnp.zeros((num_tx, num_rx, 0, 0), dtype=int)
344
+ else:
345
+ primitives = None
346
+ # Interaction types
347
+ inter = jnp.zeros((num_tx, num_rx, 0, 0), dtype=int)
348
+ # Interaction point positions
349
+ inter_pos = jnp.zeros((num_tx, num_rx, 0, 0, 3), dtype=float)
350
+ # Mask for valid paths
351
+ mask = jnp.zeros((num_tx, num_rx, 0), dtype=bool)
352
+
353
+ for paths in paths_iter:
354
+ # Reshape any batch of tx and rx positions into the expected shape
355
+ paths = paths.reshape(num_tx, num_rx, -1) # noqa: PLW2901
356
+
357
+ # [num_tx num_rx num_path_candidates order+1 3]
358
+ path_segments = jnp.diff(paths.vertices, axis=-2)
359
+
360
+ max_num_interactions = max(paths.order, inter.shape[-1])
361
+ # [num_tx num_rx num_paths max_num_interactions]
362
+ if primitives is not None:
363
+ primitives = jnp.concatenate(
364
+ (
365
+ jnp.concatenate(
366
+ (
367
+ primitives,
368
+ jnp.full(
369
+ (
370
+ *primitives.shape[:-1],
371
+ max_num_interactions - primitives.shape[-1],
372
+ ),
373
+ no_interaction,
374
+ dtype=primitives.dtype,
375
+ ),
376
+ ),
377
+ axis=-1,
378
+ ),
379
+ jnp.concatenate(
380
+ (
381
+ paths.objects[..., 1:-1],
382
+ jnp.full(
383
+ (
384
+ *paths.objects.shape[:-1],
385
+ max_num_interactions - paths.order,
386
+ ),
387
+ no_interaction,
388
+ dtype=primitives.dtype,
389
+ ),
390
+ ),
391
+ axis=-1,
392
+ ),
393
+ ),
394
+ axis=-2,
395
+ )
396
+ # [num_tx num_rx num_paths max_num_interactions]
397
+ inter = jnp.concatenate(
398
+ (
399
+ jnp.concatenate(
400
+ (
401
+ inter,
402
+ jnp.full(
403
+ (*inter.shape[:-1], max_num_interactions - inter.shape[-1]),
404
+ no_interaction,
405
+ dtype=inter.dtype,
406
+ ),
407
+ ),
408
+ axis=-1,
409
+ ),
410
+ jnp.concatenate(
411
+ (
412
+ paths.interaction_types
413
+ if paths.interaction_types is not None
414
+ else jnp.full_like(
415
+ paths.objects[..., 1:-1],
416
+ InteractionType.REFLECTION,
417
+ dtype=inter.dtype,
418
+ ),
419
+ jnp.full(
420
+ (
421
+ *paths.objects.shape[:-1],
422
+ max_num_interactions - paths.order,
423
+ ),
424
+ no_interaction,
425
+ dtype=inter.dtype,
426
+ ),
427
+ ),
428
+ axis=-1,
429
+ ),
430
+ ),
431
+ axis=-2,
432
+ )
433
+ # [num_tx num_rx num_paths max_num_interactions 3]
434
+ inter_pos = jnp.concatenate(
435
+ (
436
+ jnp.concatenate(
437
+ (
438
+ inter_pos,
439
+ jnp.zeros(
440
+ (
441
+ *inter_pos.shape[:-2],
442
+ max_num_interactions - inter_pos.shape[-2],
443
+ 3,
444
+ ),
445
+ dtype=inter_pos.dtype,
446
+ ),
447
+ ),
448
+ axis=-2,
449
+ ),
450
+ jnp.concatenate(
451
+ (
452
+ paths.vertices[..., 1:-1, :],
453
+ jnp.zeros(
454
+ (
455
+ *paths.vertices.shape[:-2],
456
+ max_num_interactions - paths.order,
457
+ 3,
458
+ ),
459
+ dtype=inter_pos.dtype,
460
+ ),
461
+ ),
462
+ axis=-2,
463
+ ),
464
+ ),
465
+ axis=-3,
466
+ )
467
+ # [num_tx num_rx num_path_candidates order+1 3],
468
+ # [num_tx num_rx num_path_candidates order+1 1]
469
+ k, s = normalize(path_segments, keepdims=True)
470
+ # [num_tx num_rx num_path_candidates order 3]
471
+ k_i = k[..., :-1, :]
472
+ k_r = k[..., +1:, :]
473
+ # [num_tx num_rx num_paths 3]
474
+ k_d = jnp.concatenate((k_d, k[..., 0, :]), axis=-2)
475
+ k_a = jnp.concatenate((k_a, -k[..., -1, :]), axis=-2)
476
+
477
+ # Dummy isotropic antenna fields
478
+ # [num_tx num_rx num_paths 3]
479
+ fields_i = polarization.astype(fields.dtype)
480
+
481
+ if paths.order > 0:
482
+ # [num_tx num_rx num_path_candidates order]
483
+ obj_indices = paths.objects[..., 1:-1]
484
+ # [num_tx num_rx num_path_candidates order]
485
+ mat_indices = jnp.take(scene.mesh.face_materials, obj_indices, axis=0)
486
+ # [num_tx num_rx num_path_candidates order 3]
487
+ obj_normals = jnp.take(scene.mesh.normals, obj_indices, axis=0)
488
+ # [num_tx num_rx num_path_candidates order]
489
+ obj_n_r = jnp.take(n_r, mat_indices, axis=0)
490
+ # [num_tx num_rx num_path_candidates order 3]
491
+ (e_i_s, e_i_p), (e_r_s, e_r_p) = sp_directions(k_i, k_r, obj_normals)
492
+ # [num_tx num_rx num_path_candidates order 1]
493
+ cos_theta = dot(obj_normals, -k_i, keepdims=True)
494
+ # [num_tx num_rx num_path_candidates order 1]
495
+ r_s, r_p = reflection_coefficients(obj_n_r[..., None], cos_theta)
496
+ # [num_tx num_rx num_path_candidates 1]
497
+ r_s = jnp.prod(r_s, axis=-2)
498
+ r_p = jnp.prod(r_p, axis=-2)
499
+ # [num_tx num_rx num_path_candidates order 3]
500
+ (e_i_s, e_i_p), (e_r_s, e_r_p) = sp_directions(k_i, k_r, obj_normals)
501
+ # [num_tx num_rx num_path_candidates 1]
502
+ fields_i_s = dot(fields_i, e_i_s[..., 0, :], keepdims=True)
503
+ fields_i_p = dot(fields_i, e_i_p[..., 0, :], keepdims=True)
504
+ # [num_tx num_rx num_path_candidates 1]
505
+ fields_r_s = r_s * fields_i_s
506
+ fields_r_p = r_p * fields_i_p
507
+ # [num_tx num_rx num_path_candidates 3]
508
+ fields_r = fields_r_s * e_r_s[..., -1, :] + fields_r_p * e_r_p[..., -1, :]
509
+ else:
510
+ # [num_tx num_rx num_path_candidates 3]
511
+ fields_r = fields_i
512
+
513
+ # [num_tx num_rx num_path_candidates 1]
514
+ s_tot = s.sum(axis=-2)
515
+ spreading_factor = safe_divide(1.0, s_tot) # Far-field approximation
516
+ phase = -2 * jnp.pi * frequency * s_tot / c
517
+ phase_shift = jax.lax.complex(jnp.cos(phase), jnp.sin(phase))
518
+ # [num_tx num_rx num_path_candidates 3]
519
+ fields_r *= spreading_factor * phase_shift
520
+
521
+ fields = jnp.concatenate((fields, fields_r), axis=-2)
522
+
523
+ # [num_tx num_rx num_paths]
524
+ lengths = jnp.concatenate(
525
+ (lengths, s_tot[..., 0]),
526
+ axis=-1,
527
+ )
528
+
529
+ # [num_tx num_rx num_paths]
530
+ mask = jnp.concatenate(
531
+ (
532
+ mask,
533
+ paths.mask
534
+ if paths.mask is not None
535
+ else jnp.ones((num_tx, num_rx, paths.vertices.shape[2]), dtype=bool),
536
+ ),
537
+ axis=-1,
538
+ )
539
+
540
+ a = dot(fields, polarization)
541
+ wavelength = c / frequency
542
+ a *= wavelength / (4 * jnp.pi)
543
+ power = jnp.abs(a) ** 2 / z_0
544
+ power = 10 * jnp.log10(power) # Convert to dBW
545
+ phase = jnp.angle(a, deg=True)
546
+
547
+ delay = lengths / c
548
+ _, aoa_el, aoa_az = jnp.split(
549
+ cartesian_to_spherical(k_a),
550
+ 3,
551
+ axis=-1,
552
+ )
553
+ aoa_az = jnp.rad2deg(aoa_az).squeeze(axis=-1)
554
+ aoa_el = jnp.rad2deg(aoa_el).squeeze(axis=-1)
555
+ _, aod_el, aod_az = jnp.split(
556
+ cartesian_to_spherical(k_d),
557
+ 3,
558
+ axis=-1,
559
+ )
560
+ aod_az = jnp.rad2deg(aod_az).squeeze(axis=-1)
561
+ aod_el = jnp.rad2deg(aod_el).squeeze(axis=-1)
562
+
563
+ return DeepMIMO(
564
+ power=power,
565
+ phase=phase,
566
+ delay=delay,
567
+ aoa_az=aoa_az,
568
+ aoa_el=aoa_el,
569
+ aod_az=aod_az,
570
+ aod_el=aod_el,
571
+ inter=inter,
572
+ inter_pos=inter_pos,
573
+ rx_pos=rx_pos,
574
+ tx_pos=tx_pos,
575
+ mask=mask,
576
+ primitives=primitives,
577
+ )
@@ -1,5 +1,6 @@
1
1
  # ruff: noqa: ERA001
2
2
 
3
+ import os
3
4
  from collections.abc import Callable, Iterator, Sized
4
5
  from functools import cache
5
6
  from typing import TYPE_CHECKING, Any, TypeVar, overload
@@ -13,7 +14,7 @@ from differt.geometry import fibonacci_lattice, viewing_frustum
13
14
  from differt.utils import dot, smoothing_function
14
15
  from differt_core.rt import CompleteGraph
15
16
 
16
- if TYPE_CHECKING:
17
+ if TYPE_CHECKING or "READTHEDOCS" in os.environ:
17
18
  import sys
18
19
 
19
20
  if sys.version_info >= (3, 11):
@@ -1,4 +1,5 @@
1
1
  import math
2
+ import os
2
3
  import warnings
3
4
  from collections.abc import Mapping
4
5
  from typing import TYPE_CHECKING, Any, Literal, overload
@@ -35,15 +36,21 @@ from differt.rt import (
35
36
  )
36
37
  from differt.utils import dot, smoothing_function
37
38
 
38
- if TYPE_CHECKING:
39
+ if TYPE_CHECKING or "READTHEDOCS" in os.environ:
39
40
  import sys
40
41
 
41
42
  if sys.version_info >= (3, 11):
42
43
  from typing import Self
43
44
  else:
44
45
  from typing_extensions import Self
46
+
47
+ try:
48
+ from sionna.rt import Scene as SionnaScene
49
+ except ImportError:
50
+ SionnaScene = Any
45
51
  else:
46
52
  Self = Any # Because runtime type checking from 'beartype' will fail when combined with 'jaxtyping'
53
+ SionnaScene = Any
47
54
 
48
55
 
49
56
  @eqx.filter_jit
@@ -555,12 +562,12 @@ class TriangleScene(eqx.Module):
555
562
  @property
556
563
  def num_transmitters(self) -> int:
557
564
  """The number of transmitters."""
558
- return self.transmitters[..., 0].size
565
+ return math.prod(self.transmitters.shape[:-1])
559
566
 
560
567
  @property
561
568
  def num_receivers(self) -> int:
562
569
  """The number of receivers."""
563
- return self.receivers[..., 0].size
570
+ return math.prod(self.receivers.shape[:-1])
564
571
 
565
572
  def set_assume_quads(self, flag: bool = True) -> Self:
566
573
  """
@@ -743,6 +750,88 @@ class TriangleScene(eqx.Module):
743
750
  core_scene = differt_core.scene.TriangleScene.load_xml(file)
744
751
  return cls.from_core(core_scene)
745
752
 
753
+ @classmethod
754
+ def from_mitsuba(cls, mi_scene) -> Self: # noqa: ANN001 # for some reason, mi.Scene cannot be imported, but only supports delayed annotations, which is not compatible with jaxtyping
755
+ """
756
+ Load a triangle scene from a Mitsuba scene object.
757
+
758
+ This method does not extract any transmitters or receivers from the Mitsuba scene,
759
+ as Mitsuba does not provide any explicit information about them, and they are usually
760
+ part of the Sionna scene object, see :meth:`from_sionna`.
761
+
762
+ Args:
763
+ mi_scene (mitsuba.Scene): The Mitsuba scene object.
764
+
765
+ You can obtain the Mitsuba scene object from a Sionna scene
766
+ its ``.mi_scene`` attribute.
767
+
768
+ Returns:
769
+ The corresponding scene containing only triangle meshes.
770
+
771
+ .. seealso::
772
+
773
+ :meth:`from_sionna`
774
+ """
775
+ mesh = TriangleMesh.empty()
776
+
777
+ for shape in mi_scene.shapes():
778
+ rm = shape.bsdf().radio_material
779
+ mesh += (
780
+ TriangleMesh(
781
+ vertices=shape.vertex_positions_buffer().jax().reshape(-1, 3),
782
+ triangles=shape.faces_buffer().jax().reshape(-1, 3),
783
+ )
784
+ .set_face_colors(jnp.asarray(rm.color))
785
+ .set_materials(f"itu_{rm.itu_type}")
786
+ .set_face_materials(0)
787
+ )
788
+
789
+ return cls(
790
+ mesh=mesh,
791
+ )
792
+
793
+ @classmethod
794
+ def from_sionna(cls, sionna_scene: SionnaScene) -> Self: # type: ignore[reportUndefinedVariable]
795
+ """
796
+ Load a triangle scene from a Sionna scene object.
797
+
798
+ This method uses :meth:`from_mitsuba` internally to load the scene objects.
799
+
800
+ .. warning::
801
+ Using this method is only recommended if you already have a Sionna scene object.
802
+ Otherwise, you can use :meth:`load_xml` to load a scene from a XML file, compatible with Sionna,
803
+ at a faster speed.
804
+
805
+ .. warning::
806
+ This method does not *currently* use any information about possible antenna arrays.
807
+
808
+ Args:
809
+ sionna_scene: The Sionna scene object.
810
+
811
+ Returns:
812
+ The corresponding scene containing only triangle meshes.
813
+ """
814
+ scene = cls.from_mitsuba(sionna_scene.mi_scene)
815
+
816
+ return eqx.tree_at(
817
+ lambda s: (s.transmitters, s.receivers),
818
+ scene,
819
+ (
820
+ jnp.concatenate([
821
+ tx.position.jax().reshape(1, 3)
822
+ for tx in sionna_scene.transmitters.values()
823
+ ])
824
+ if sionna_scene.transmitters
825
+ else jnp.empty((0, 3)),
826
+ jnp.concatenate([
827
+ rx.position.jax().reshape(1, 3)
828
+ for rx in sionna_scene.receivers.values()
829
+ ])
830
+ if sionna_scene.receivers
831
+ else jnp.empty((0, 3)),
832
+ ),
833
+ )
834
+
746
835
  @overload
747
836
  def compute_paths(
748
837
  self,
@@ -223,7 +223,7 @@ def minimize(
223
223
  >>>
224
224
  >>> # You can also change the optimizer and the number of steps
225
225
  >>> import optax
226
- >>> optimizer = optax.noisy_sgd(learning_rate=0.003)
226
+ >>> optimizer = optax.noisy_sgd(learning_rate=0.003, key=jax.random.key(1234))
227
227
  >>> x, y = minimize(
228
228
  ... f, jnp.zeros(5), args=(4.0,), steps=10000, optimizer=optimizer
229
229
  ... )
File without changes
File without changes
File without changes
File without changes