differt 0.0.32__tar.gz → 0.0.34__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 (31) hide show
  1. {differt-0.0.32 → differt-0.0.34}/PKG-INFO +2 -2
  2. {differt-0.0.32 → differt-0.0.34}/pyproject.toml +1 -1
  3. {differt-0.0.32 → differt-0.0.34}/src/differt/em/_material.py +2 -0
  4. {differt-0.0.32 → differt-0.0.34}/src/differt/geometry/_triangle_mesh.py +287 -17
  5. {differt-0.0.32 → differt-0.0.34}/src/differt/scene/_sionna.py +24 -3
  6. {differt-0.0.32 → differt-0.0.34}/src/differt/scene/_triangle_scene.py +3 -0
  7. {differt-0.0.32 → differt-0.0.34}/.gitignore +0 -0
  8. {differt-0.0.32 → differt-0.0.34}/LICENSE.md +0 -0
  9. {differt-0.0.32 → differt-0.0.34}/README.md +0 -0
  10. {differt-0.0.32 → differt-0.0.34}/src/differt/__init__.py +0 -0
  11. {differt-0.0.32 → differt-0.0.34}/src/differt/_version.py +0 -0
  12. {differt-0.0.32 → differt-0.0.34}/src/differt/em/__init__.py +0 -0
  13. {differt-0.0.32 → differt-0.0.34}/src/differt/em/_antenna.py +0 -0
  14. {differt-0.0.32 → differt-0.0.34}/src/differt/em/_constants.py +0 -0
  15. {differt-0.0.32 → differt-0.0.34}/src/differt/em/_fresnel.py +0 -0
  16. {differt-0.0.32 → differt-0.0.34}/src/differt/em/_interaction_type.py +0 -0
  17. {differt-0.0.32 → differt-0.0.34}/src/differt/em/_utd.py +0 -0
  18. {differt-0.0.32 → differt-0.0.34}/src/differt/em/_utils.py +0 -0
  19. {differt-0.0.32 → differt-0.0.34}/src/differt/geometry/__init__.py +0 -0
  20. {differt-0.0.32 → differt-0.0.34}/src/differt/geometry/_paths.py +0 -0
  21. {differt-0.0.32 → differt-0.0.34}/src/differt/geometry/_utils.py +0 -0
  22. {differt-0.0.32 → differt-0.0.34}/src/differt/plotting/__init__.py +0 -0
  23. {differt-0.0.32 → differt-0.0.34}/src/differt/plotting/_core.py +0 -0
  24. {differt-0.0.32 → differt-0.0.34}/src/differt/plotting/_utils.py +0 -0
  25. {differt-0.0.32 → differt-0.0.34}/src/differt/py.typed +0 -0
  26. {differt-0.0.32 → differt-0.0.34}/src/differt/rt/__init__.py +0 -0
  27. {differt-0.0.32 → differt-0.0.34}/src/differt/rt/_fermat.py +0 -0
  28. {differt-0.0.32 → differt-0.0.34}/src/differt/rt/_image_method.py +0 -0
  29. {differt-0.0.32 → differt-0.0.34}/src/differt/rt/_utils.py +0 -0
  30. {differt-0.0.32 → differt-0.0.34}/src/differt/scene/__init__.py +0 -0
  31. {differt-0.0.32 → differt-0.0.34}/src/differt/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: DiffeRT
3
- Version: 0.0.32
3
+ Version: 0.0.34
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.32
24
+ Requires-Dist: differt-core==0.0.34
25
25
  Requires-Dist: equinox>=0.11.5
26
26
  Requires-Dist: filelock>=3.15.4
27
27
  Requires-Dist: jax>=0.4.32
@@ -16,7 +16,7 @@ classifiers = [
16
16
  ]
17
17
  dependencies = [
18
18
  "chex>=0.1.86",
19
- "differt-core==0.0.32",
19
+ "differt-core==0.0.34",
20
20
  "equinox>=0.11.5",
21
21
  "filelock>=3.15.4",
22
22
  "jax>=0.4.32",
@@ -42,6 +42,8 @@ class Material(eqx.Module):
42
42
  Returns:
43
43
  A tuple containing the relative permittivity and conductivity of the material.
44
44
  """
45
+ thickness: Float[ArrayLike, ""] | None = eqx.field(default=None)
46
+ """The thickness of the material."""
45
47
  aliases: tuple[str, ...] = eqx.field(default=(), static=True)
46
48
  """
47
49
  A tuple of name aliases for the material.
@@ -1,7 +1,8 @@
1
1
  # ruff: noqa: ERA001
2
2
 
3
- from collections.abc import Iterator
4
- from typing import TYPE_CHECKING, Any, overload
3
+ from collections.abc import Callable, Iterator
4
+ from dataclasses import replace
5
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, overload
5
6
 
6
7
  import equinox as eqx
7
8
  import jax
@@ -86,6 +87,101 @@ def triangles_contain_vertices_assuming_inside_same_plane(
86
87
  return all_pos | all_neg
87
88
 
88
89
 
90
+ _Index = slice | Int[ArrayLike, " "] | Int[Array, " n"] | Bool[Array, " num_triangles"]
91
+ _T = TypeVar("_T", bound="TriangleMesh")
92
+
93
+
94
+ class _TriangleMeshVerticesUpdateHelper(Generic[_T]):
95
+ """A helper class to update vertices of a triangle mesh."""
96
+
97
+ __slots__ = ("mesh",)
98
+
99
+ def __init__(self, mesh: _T) -> None:
100
+ self.mesh = mesh
101
+
102
+ def __getitem__(self, index: _Index) -> "_TriangleMeshVerticesUpdateRef[_T]":
103
+ return _TriangleMeshVerticesUpdateRef(self.mesh, index)
104
+
105
+ def __repr__(self) -> str:
106
+ return f"_TriangleMeshVerticesUpdateHelper({self.mesh!r})"
107
+
108
+
109
+ class _TriangleMeshVerticesUpdateRef(Generic[_T]):
110
+ """A reference to update vertices of a triangle mesh."""
111
+
112
+ __slots__ = ("index", "mesh")
113
+
114
+ def __init__(self, mesh: _T, index: _Index) -> None:
115
+ self.mesh = mesh
116
+ self.index = index
117
+
118
+ def __repr__(self) -> str:
119
+ return f"_TriangleMeshVerticesUpdateRef({self.mesh!r}, {self.index!r})"
120
+
121
+ def _triangles_index(self, **kwargs: Any) -> _Index:
122
+ if self.index == slice(None):
123
+ # TODO: check if we can use fast path but avoid updating vertices
124
+ # that are not referenced by any triangle
125
+ return self.index # Fast path
126
+ index = self.mesh.triangles.at[self.index, :].get(**kwargs).reshape(-1)
127
+ return jnp.unique(
128
+ index, size=len(index), fill_value=self.mesh.vertices.shape[0]
129
+ )
130
+
131
+ def set(self, values: Any, **kwargs: Any) -> _T:
132
+ index = self._triangles_index(**kwargs)
133
+ return eqx.tree_at(
134
+ lambda m: m.vertices,
135
+ self.mesh,
136
+ self.mesh.vertices.at[index, :].set(
137
+ values, indices_are_sorted=True, unique_indices=True
138
+ ),
139
+ )
140
+
141
+ def get(self, **kwargs: Any) -> Float[ArrayLike, "num_indexed_triangles 3"]:
142
+ index = self._triangles_index(**kwargs)
143
+ return self.mesh.vertices.at[index, :].get(
144
+ indices_are_sorted=True, unique_indices=True
145
+ )
146
+
147
+ def apply(
148
+ self,
149
+ func: Callable[
150
+ [Float[ArrayLike, "num_indexed_triangles 3"]],
151
+ Float[Array, "num_indexed_triangles 3"],
152
+ ],
153
+ **kwargs: Any,
154
+ ) -> _T:
155
+ index = self._triangles_index(**kwargs)
156
+ return eqx.tree_at(
157
+ lambda m: m.vertices,
158
+ self.mesh,
159
+ self.mesh.vertices.at[index, :].apply(
160
+ func, indices_are_sorted=True, unique_indices=True
161
+ ),
162
+ )
163
+
164
+ def add(self, values: Any, **kwargs: Any) -> _T:
165
+ index = self._triangles_index(**kwargs)
166
+ return eqx.tree_at(
167
+ lambda m: m.vertices,
168
+ self.mesh,
169
+ self.mesh.vertices.at[index, :].add(
170
+ values, indices_are_sorted=True, unique_indices=True
171
+ ),
172
+ )
173
+
174
+ def mul(self, values: Any, **kwargs: Any) -> _T:
175
+ index = self._triangles_index(**kwargs)
176
+ return eqx.tree_at(
177
+ lambda m: m.vertices,
178
+ self.mesh,
179
+ self.mesh.vertices.at[index, :].mul(
180
+ values, indices_are_sorted=True, unique_indices=True
181
+ ),
182
+ )
183
+
184
+
89
185
  class TriangleMesh(eqx.Module):
90
186
  """A simple geometry made of triangles."""
91
187
 
@@ -292,6 +388,95 @@ class TriangleMesh(eqx.Module):
292
388
  (jnp.min(vertices, axis=0), jnp.max(vertices, axis=0)),
293
389
  )
294
390
 
391
+ @property
392
+ def at(self): # noqa: ANN202
393
+ """Helper property for updating a subset of triangle vertices.
394
+
395
+ This ``at`` property is used to update vertices of a triangle mesh,
396
+ based on triangles indices,
397
+ similar to how the ``at`` property is used in :attr:`jax.numpy.ndarray.at`.
398
+
399
+ In particular, the following methods are available:
400
+
401
+ - ``set(values, **kwargs)``: Set the vertices of selected triangles to some values;
402
+ - ``apply(func, **kwargs)``: Apply a function to the vertices of selected triangles;
403
+ - ``add(values, **kwargs)``: Add some values to the vertices of selected triangles;
404
+ - ``mul(values, **kwargs)``: Multiply the vertices of selected triangles by some values;
405
+ - ``get(values, **kwargs)``: Get the vertices of selected triangles.
406
+
407
+ E.g., ``mesh.at[0:2].add([1.0, 2.0, 3.0])`` will translate the first two triangles.
408
+
409
+ Each method takes additional keyword parameters that are passed to the methods
410
+ of :attr:`jax.numpy.ndarray.at`. Because the vertices of a triangle mesh may be shared
411
+ between multiple triangles, this method prevents update the same vertice multiple times
412
+ by ignoring duplicate vertex indices. As a result, providing duplicate triangle indices
413
+ will not result in duplicate updates.
414
+
415
+ Warning:
416
+ As duplicate vertices are ignored, the number of update vertices is not
417
+ necessarily equal to the number of triangles selected times three. Moreover,
418
+ vertices are re-ordered when duplicates are removed. As a results, you should
419
+ not apply any update that depends on the order of or the number of updated
420
+ the vertices.
421
+
422
+ Examples:
423
+ The following example shows how to translate the first two (triangle) faces.
424
+
425
+ .. plotly::
426
+
427
+ >>> from differt.geometry import TriangleMesh
428
+ >>>
429
+ >>> mesh = (
430
+ ... sum(
431
+ ... TriangleMesh.box().iter_objects(),
432
+ ... start=TriangleMesh.empty(),
433
+ ... )
434
+ ... .at[0:2]
435
+ ... .add([1.0, 1.0, 0.0])
436
+ ... )
437
+ >>> fig = mesh.plot(opacity=0.5, backend="plotly")
438
+ >>> fig # doctest: +SKIP
439
+
440
+ In the above example, splitting the cube mesh into separate objects is necessary,
441
+ as the vertices of the cube are shared between the faces. If the cube was not split,
442
+ the translation would be applied to all the faces that share the vertices of the first two faces.
443
+
444
+ .. plotly::
445
+
446
+ >>> from differt.geometry import TriangleMesh
447
+ >>>
448
+ >>> mesh = TriangleMesh.box().at[0:2].add([1.0, 1.0, 0.0])
449
+ >>> fig = mesh.plot(opacity=0.5, backend="plotly")
450
+ >>> fig # doctest: +SKIP
451
+
452
+ Finally, the :attr:`at` property is lazily evaluated, so checking that the index
453
+ is valid is not performed until a method is called.
454
+
455
+ >>> from differt.geometry import TriangleMesh
456
+ >>>
457
+ >>> mesh = TriangleMesh.box()
458
+ >>> mesh.at
459
+ _TriangleMeshVerticesUpdateHelper(TriangleMesh(
460
+ vertices=f32[8,3],
461
+ triangles=i32[10,3],
462
+ material_names=(),
463
+ object_bounds=i32[5,2]
464
+ ))
465
+ >>> index = jnp.array([True, False])
466
+ >>> mesh.at[index]
467
+ _TriangleMeshVerticesUpdateRef(TriangleMesh(
468
+ vertices=f32[8,3],
469
+ triangles=i32[10,3],
470
+ material_names=(),
471
+ object_bounds=i32[5,2]
472
+ ), Array([ True, False], dtype=bool))
473
+ >>> mesh.at[index].add(1.0) # doctest: +IGNORE_EXCEPTION_DETAIL
474
+ Traceback (most recent call last):
475
+ IndexError: boolean index did not match shape of indexed array in index 0:
476
+ got (2,), expected (10,)
477
+ """
478
+ return _TriangleMeshVerticesUpdateHelper(self)
479
+
295
480
  def rotate(self, rotation_matrix: Float[ArrayLike, "3 3"]) -> Self:
296
481
  """
297
482
  Return a new mesh by applying a rotation matrix to all triangle coordinates.
@@ -350,7 +535,7 @@ class TriangleMesh(eqx.Module):
350
535
  """
351
536
  return cls(vertices=jnp.empty((0, 3)), triangles=jnp.empty((0, 3), dtype=int))
352
537
 
353
- def append(self, other: "TriangleMesh") -> "TriangleMesh":
538
+ def append(self, other: "TriangleMesh") -> Self:
354
539
  """
355
540
  Return a new mesh by appending another mesh to this one.
356
541
 
@@ -358,11 +543,25 @@ class TriangleMesh(eqx.Module):
358
543
 
359
544
  For convenience, you can also use the ``+`` operator.
360
545
 
361
- .. todo::
362
-
363
- Document how optional arguments are merged,
364
- as well as the behavior of :attr:`assume_quads`,
365
- and the specific case of empty meshes.
546
+ .. note::
547
+
548
+ The following rules are applied when merging two meshes:
549
+ - The vertices are concatenated;
550
+ - The triangles are concatenated, and the indices of the second mesh are updated;
551
+ - The face colors are concatenated. If one mesh has colors while the other does not,
552
+ then mesh with no colors will have its face colors set to black (0, 0, 0);
553
+ - The face materials are concatenated. If ``other`` has face materials not included
554
+ in ``self``, then the face materials from ``other`` are renumbered.
555
+ If one mesh has colors while the other does not,
556
+ then mesh with no colors will have its face materials set to ``-1``;
557
+ - The material names are merged, keeping only unique names;
558
+ - The object bounds are concatenated only if both meshes have them set,
559
+ otherwise, the object bounds are set to :data:`None`;
560
+ - The :attr:`assume_quads` flag is set to :data:`True` if both meshes have it set to :data:`True`.
561
+
562
+ Two important exceptions are:
563
+ - If one mesh is empty, a copy of the other mesh is returned as is;
564
+ - If both meshes are empty, then a copy of ``self`` is returned.
366
565
 
367
566
  Args:
368
567
  other: The mesh to append.
@@ -387,10 +586,10 @@ class TriangleMesh(eqx.Module):
387
586
  >>> fig = mesh.plot(opacity=0.5, backend="plotly")
388
587
  >>> fig # doctest: +SKIP
389
588
  """
390
- if self.is_empty:
391
- return eqx.tree_at(lambda _: (), other, ())
392
589
  if other.is_empty:
393
590
  return eqx.tree_at(lambda _: (), self, ())
591
+ if self.is_empty:
592
+ return eqx.tree_at(lambda _: (), other, ())
394
593
 
395
594
  vertices = jnp.concatenate((self.vertices, other.vertices), axis=0)
396
595
  triangles = jnp.concatenate(
@@ -472,13 +671,18 @@ class TriangleMesh(eqx.Module):
472
671
  else None
473
672
  )
474
673
  assume_quads = self.assume_quads and other.assume_quads
475
- return TriangleMesh(
476
- vertices=vertices,
477
- triangles=triangles,
478
- face_colors=face_colors,
479
- face_materials=face_materials,
480
- object_bounds=object_bounds,
481
- assume_quads=assume_quads,
674
+ mesh = replace(self, material_names=material_names, assume_quads=assume_quads)
675
+ return eqx.tree_at(
676
+ lambda m: (
677
+ m.vertices,
678
+ m.triangles,
679
+ m.face_colors,
680
+ m.face_materials,
681
+ m.object_bounds,
682
+ ),
683
+ mesh,
684
+ (vertices, triangles, face_colors, face_materials, object_bounds),
685
+ is_leaf=lambda x: x is None,
482
686
  )
483
687
 
484
688
  __add__ = append
@@ -649,6 +853,72 @@ class TriangleMesh(eqx.Module):
649
853
  is_leaf=lambda x: x is None,
650
854
  )
651
855
 
856
+ def set_materials(self, *names: str) -> Self:
857
+ """
858
+ Return a copy of this mesh, with new face materials from material names.
859
+
860
+ If a material name is not in :attr:`material_names`, it is added.
861
+
862
+ Args:
863
+ names: The material names.
864
+ If one name is provided, it will be applied to all triangles.
865
+
866
+ Returns:
867
+ A new mesh with updated face materials.
868
+
869
+ Raises:
870
+ ValueError: If the number of names is not 1, :attr:`num_triangles`, or :attr:`num_objects` (if :attr:`assume_quads` is set to :data:`True`).
871
+ """
872
+ if len(names) not in {1, self.num_triangles, self.num_objects}:
873
+ if self.assume_quads:
874
+ msg = f"Expected either 1, {self.num_triangles}, or {self.num_objects} names, got {len(names)}."
875
+ else:
876
+ msg = f"Expected either 1, or {self.num_triangles} names, got {len(names)}."
877
+ raise ValueError(msg)
878
+ material_names = dict.fromkeys(self.material_names)
879
+ if all(name in material_names for name in names):
880
+ material_names = {name: i for i, name in enumerate(material_names)}
881
+ face_materials = jnp.array([material_names[name] for name in names])
882
+ if self.assume_quads and len(names) == self.num_quads:
883
+ face_materials = jnp.repeat(face_materials, 2)
884
+ return self.set_face_materials(face_materials)
885
+
886
+ material_names = material_names | dict.fromkeys(names)
887
+ material_names = {name: i for i, name in enumerate(material_names)}
888
+
889
+ face_materials = jnp.array([material_names[name] for name in names])
890
+ if self.assume_quads and len(names) == self.num_quads:
891
+ face_materials = jnp.repeat(face_materials, 2)
892
+ mesh = replace(self, material_names=tuple(material_names))
893
+ return mesh.set_face_materials(face_materials)
894
+
895
+ def set_face_materials(
896
+ self, materials: Int[ArrayLike, " "] | Int[ArrayLike, "#num_triangles"]
897
+ ) -> Self:
898
+ """
899
+ Return a copy of this mesh, with new face materials.
900
+
901
+ Args:
902
+ materials: The material indices.
903
+ If one material is provided, it will be applied to all triangles.
904
+
905
+ No check is performed to verify that material indices are actually
906
+ in bounds of :attr:`material_names`.
907
+
908
+ Returns:
909
+ A new mesh with updated face materials.
910
+ """
911
+ face_materials = jnp.broadcast_to(
912
+ jnp.asarray(materials),
913
+ self.num_triangles,
914
+ )
915
+ return eqx.tree_at(
916
+ lambda m: m.face_materials,
917
+ self,
918
+ face_materials,
919
+ is_leaf=lambda x: x is None,
920
+ )
921
+
652
922
  @overload
653
923
  @classmethod
654
924
  def plane(
@@ -22,6 +22,8 @@ SIONNA_SCENES_FOLDER = Path(__file__).parent / "scenes"
22
22
 
23
23
  def download_sionna_scenes(
24
24
  branch_or_tag: str = "main",
25
+ repo: str = "NVlabs/sionna-rt",
26
+ scenes_folder: str = "src/sionna/rt/scenes/",
25
27
  *,
26
28
  folder: str | Path = SIONNA_SCENES_FOLDER,
27
29
  cached: bool = True,
@@ -44,6 +46,11 @@ def download_sionna_scenes(
44
46
 
45
47
  Args:
46
48
  branch_or_tag: The branch or tag version of the Sionna repository.
49
+ repo: The repository ``{owner}/{name}`` on GitHub from which to download the scenes.
50
+
51
+ E.g., you can change this if you want to use a fork instead.
52
+ scenes_folder: The folder where the scenes are stored in the
53
+ repository.
47
54
  folder: Where to extract the scene files, i.e., the content
48
55
  of ``sionna/rt/scenes/``.
49
56
  cached: Whether to avoid downloading again if the target folder
@@ -66,7 +73,7 @@ def download_sionna_scenes(
66
73
 
67
74
  folder.rmdir()
68
75
 
69
- url = f"https://codeload.github.com/NVlabs/sionna/tar.gz/{branch_or_tag}"
76
+ url = f"https://codeload.github.com/{repo}/tar.gz/{branch_or_tag}"
70
77
 
71
78
  response = requests.get(url, stream=True, timeout=timeout)
72
79
 
@@ -75,8 +82,8 @@ def download_sionna_scenes(
75
82
 
76
83
  def members(tar: tarfile.TarFile) -> Iterator[tarfile.TarInfo]:
77
84
  for member in tar.getmembers():
78
- if (index := member.path.find("sionna/rt/scenes/")) >= 0:
79
- member.path = member.path[index + 17 :]
85
+ if (index := member.path.find(scenes_folder)) >= 0:
86
+ member.path = member.path[index + len(scenes_folder) :]
80
87
  yield member
81
88
 
82
89
  with (
@@ -181,6 +188,20 @@ def main() -> None: # pragma: no cover
181
188
  nargs="?",
182
189
  help="branch or tag version of the Sionna repository.",
183
190
  )
191
+ parser.add_argument(
192
+ "-r",
193
+ "--repo",
194
+ type=str,
195
+ default="NVlabs/sionna-rt",
196
+ help="the repository '{owner}/{name}' on GitHub from which to download the scenes.",
197
+ )
198
+ parser.add_argument(
199
+ "-s",
200
+ "--scenes-folder",
201
+ type=Path,
202
+ default="src/sionna/rt/scenes",
203
+ help="the folder where the scenes are stored in the repository.",
204
+ )
184
205
  parser.add_argument(
185
206
  "--folder",
186
207
  type=Path,
@@ -189,6 +189,9 @@ def _compute_paths(
189
189
  axis=-1
190
190
  ) # Any path segment being too small
191
191
 
192
+ # TODO: check if we should invalidate non-finite paths
193
+ # is_finite = jnp.isfinite(full_paths).all(axis=(-1, -2))
194
+
192
195
  mask = inside_triangles & valid_reflections & ~blocked & ~too_small
193
196
 
194
197
  return full_paths, mask
File without changes
File without changes
File without changes
File without changes
File without changes