differt 0.1.2__tar.gz → 0.3.0__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 (36) hide show
  1. {differt-0.1.2 → differt-0.3.0}/PKG-INFO +3 -3
  2. {differt-0.1.2 → differt-0.3.0}/README.md +1 -1
  3. {differt-0.1.2 → differt-0.3.0}/pyproject.toml +1 -1
  4. differt-0.3.0/src/differt/__init__.py +8 -0
  5. differt-0.3.0/src/differt/_version.py +6 -0
  6. {differt-0.1.2 → differt-0.3.0}/src/differt/geometry/_triangle_mesh.py +154 -19
  7. {differt-0.1.2 → differt-0.3.0}/src/differt/geometry/_utils.py +65 -18
  8. {differt-0.1.2 → differt-0.3.0}/src/differt/plotting/_core.py +2 -2
  9. {differt-0.1.2 → differt-0.3.0}/src/differt/plugins/_deepmimo_types.py +4 -1
  10. {differt-0.1.2 → differt-0.3.0}/src/differt/plugins/deepmimo.py +1 -1
  11. {differt-0.1.2 → differt-0.3.0}/src/differt/rt/_fermat.py +8 -8
  12. {differt-0.1.2 → differt-0.3.0}/src/differt/rt/_image_method.py +4 -4
  13. {differt-0.1.2 → differt-0.3.0}/src/differt/rt/_utils.py +54 -8
  14. {differt-0.1.2 → differt-0.3.0}/src/differt/scene/_triangle_scene.py +20 -5
  15. {differt-0.1.2 → differt-0.3.0}/src/differt/utils.py +1 -132
  16. differt-0.1.2/src/differt/__init__.py +0 -6
  17. differt-0.1.2/src/differt/_version.py +0 -6
  18. {differt-0.1.2 → differt-0.3.0}/.gitignore +0 -0
  19. {differt-0.1.2 → differt-0.3.0}/LICENSE.md +0 -0
  20. {differt-0.1.2 → differt-0.3.0}/src/differt/em/__init__.py +0 -0
  21. {differt-0.1.2 → differt-0.3.0}/src/differt/em/_antenna.py +0 -0
  22. {differt-0.1.2 → differt-0.3.0}/src/differt/em/_constants.py +0 -0
  23. {differt-0.1.2 → differt-0.3.0}/src/differt/em/_fresnel.py +0 -0
  24. {differt-0.1.2 → differt-0.3.0}/src/differt/em/_interaction_type.py +0 -0
  25. {differt-0.1.2 → differt-0.3.0}/src/differt/em/_material.py +0 -0
  26. {differt-0.1.2 → differt-0.3.0}/src/differt/em/_utd.py +0 -0
  27. {differt-0.1.2 → differt-0.3.0}/src/differt/em/_utils.py +0 -0
  28. {differt-0.1.2 → differt-0.3.0}/src/differt/geometry/__init__.py +0 -0
  29. {differt-0.1.2 → differt-0.3.0}/src/differt/geometry/_paths.py +0 -0
  30. {differt-0.1.2 → differt-0.3.0}/src/differt/plotting/__init__.py +0 -0
  31. {differt-0.1.2 → differt-0.3.0}/src/differt/plotting/_utils.py +0 -0
  32. {differt-0.1.2 → differt-0.3.0}/src/differt/plugins/__init__.py +0 -0
  33. {differt-0.1.2 → differt-0.3.0}/src/differt/py.typed +0 -0
  34. {differt-0.1.2 → differt-0.3.0}/src/differt/rt/__init__.py +0 -0
  35. {differt-0.1.2 → differt-0.3.0}/src/differt/scene/__init__.py +0 -0
  36. {differt-0.1.2 → differt-0.3.0}/src/differt/scene/_sionna.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: DiffeRT
3
- Version: 0.1.2
3
+ Version: 0.3.0
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.1.2
24
+ Requires-Dist: differt-core==0.3.0
25
25
  Requires-Dist: equinox>=0.12.2
26
26
  Requires-Dist: filelock>=3.15.4
27
27
  Requires-Dist: jax>=0.4.32
@@ -140,7 +140,7 @@ If you use this software, please cite it as:
140
140
  author = {Eertmans, Jérome},
141
141
  url = {https://github.com/jeertmans/DiffeRT},
142
142
  license = {MIT},
143
- version = {v0.1.2}
143
+ version = {v0.3.0}
144
144
  }
145
145
  ```
146
146
 
@@ -83,7 +83,7 @@ If you use this software, please cite it as:
83
83
  author = {Eertmans, Jérome},
84
84
  url = {https://github.com/jeertmans/DiffeRT},
85
85
  license = {MIT},
86
- version = {v0.1.2}
86
+ version = {v0.3.0}
87
87
  }
88
88
  ```
89
89
 
@@ -16,7 +16,7 @@ classifiers = [
16
16
  ]
17
17
  dependencies = [
18
18
  "chex>=0.1.86",
19
- "differt-core==0.1.2",
19
+ "differt-core==0.3.0",
20
20
  "equinox>=0.12.2",
21
21
  "filelock>=3.15.4",
22
22
  "jax>=0.4.32", # TODO: fixme, issue with pmap
@@ -0,0 +1,8 @@
1
+ """Differentiable Ray Tracing Toolbox for Radio Propagation."""
2
+
3
+ from ._version import __version__, __version_info__
4
+
5
+ __all__ = (
6
+ "__version__",
7
+ "__version_info__",
8
+ )
@@ -0,0 +1,6 @@
1
+ from differt_core import ( # Re-export version from core module
2
+ __version__,
3
+ __version_info__,
4
+ )
5
+
6
+ __all__ = ("__version__", "__version_info__")
@@ -235,6 +235,20 @@ class TriangleMesh(eqx.Module):
235
235
  :attr:`num_triangles` is even, but each two consecutive
236
236
  triangles are assumed to represent a quadrilateral surface.
237
237
  """
238
+ mask: Bool[Array, " num_triangles"] | None = eqx.field(
239
+ converter=lambda x: jnp.asarray(x) if x is not None else None, default=None
240
+ )
241
+ """An optional mask to indicate which triangles are active.
242
+
243
+ Using a mask allows to represent multiple sub-meshes of a single mesh, without changing
244
+ the memory allocated to each sub-mesh. Masks can be conveniently created using the
245
+ :meth:`sample` method by passing ``by_masking=True``.
246
+
247
+ .. important::
248
+
249
+ Unless specified, the transformation or selection operations, like :meth:`rotate`,
250
+ will not take the mask into account, and will apply to all triangles.
251
+ """
238
252
 
239
253
  def __check_init__(self) -> None: # noqa: PLW3201
240
254
  if self.assume_quads and (self.triangles.shape[0] % 2) != 0:
@@ -265,6 +279,7 @@ class TriangleMesh(eqx.Module):
265
279
  m.face_colors,
266
280
  m.face_materials,
267
281
  m.object_bounds,
282
+ m.mask,
268
283
  ),
269
284
  self,
270
285
  (
@@ -273,6 +288,7 @@ class TriangleMesh(eqx.Module):
273
288
  self.face_colors[key, :] if self.face_colors is not None else None,
274
289
  self.face_materials[key] if self.face_materials is not None else None,
275
290
  None,
291
+ self.mask[key] if self.mask is not None else None,
276
292
  ),
277
293
  is_leaf=lambda x: x is None,
278
294
  )
@@ -297,6 +313,7 @@ class TriangleMesh(eqx.Module):
297
313
  m.face_colors,
298
314
  m.face_materials,
299
315
  m.object_bounds,
316
+ m.mask,
300
317
  ),
301
318
  self,
302
319
  (
@@ -309,6 +326,7 @@ class TriangleMesh(eqx.Module):
309
326
  if self.face_materials is not None
310
327
  else None,
311
328
  jnp.array([[0, stop - start]]),
329
+ self.mask[start:stop] if self.mask is not None else None,
312
330
  ),
313
331
  is_leaf=lambda x: x is None,
314
332
  )
@@ -441,12 +459,22 @@ class TriangleMesh(eqx.Module):
441
459
 
442
460
  @property
443
461
  def bounding_box(self) -> Float[Array, "2 3"]:
444
- """The bounding box (min. and max. coordinates)."""
462
+ """The bounding box (min. and max. coordinates).
463
+
464
+ .. important::
465
+
466
+ Setting :attr:`mask` will have an effect on the bounding box,
467
+ as the bounding box is computed only for the active triangles.
468
+ """
445
469
  # Using self.triangle_vertices is important because, e.g., as a result of using
446
470
  # __getitem__, some vertices in 'self.vertices' may no longer be used by this mesh.
447
471
  vertices = self.triangle_vertices.reshape(-1, 3)
472
+ where = jnp.repeat(self.mask, 3)[:, None] if self.mask is not None else None
448
473
  return jnp.vstack(
449
- (jnp.min(vertices, axis=0), jnp.max(vertices, axis=0)),
474
+ (
475
+ jnp.min(vertices, axis=0, initial=+jnp.inf, where=where),
476
+ jnp.max(vertices, axis=0, initial=-jnp.inf, where=where),
477
+ ),
450
478
  )
451
479
 
452
480
  @property
@@ -539,6 +567,43 @@ class TriangleMesh(eqx.Module):
539
567
  """
540
568
  return _TriangleMeshVerticesUpdateHelper(self)
541
569
 
570
+ def masked(self) -> Self:
571
+ """Return a pruned copy of this object that only keeps masked (i.e., active) triangles.
572
+
573
+ .. important::
574
+ This method does not preserve the :attr:`object_bounds` attribute.
575
+
576
+ Returns:
577
+ A new paths instance with flattened batch dimensions and only valid paths.
578
+ """
579
+ if self.mask is None:
580
+ return jax.tree.map(lambda m: m, self)
581
+
582
+ return eqx.tree_at(
583
+ lambda m: (
584
+ m.vertices,
585
+ m.triangles,
586
+ m.face_colors,
587
+ m.face_materials,
588
+ m.object_bounds,
589
+ m.mask,
590
+ ),
591
+ self,
592
+ (
593
+ self.vertices,
594
+ self.triangles[self.mask, :],
595
+ self.face_colors[self.mask, :]
596
+ if self.face_colors is not None
597
+ else None,
598
+ self.face_materials[self.mask]
599
+ if self.face_materials is not None
600
+ else None,
601
+ None,
602
+ None,
603
+ ),
604
+ is_leaf=lambda x: x is None,
605
+ )
606
+
542
607
  def rotate(self, rotation_matrix: Float[ArrayLike, "3 3"]) -> Self:
543
608
  """
544
609
  Return a new mesh by applying a rotation matrix to all triangle coordinates.
@@ -597,7 +662,7 @@ class TriangleMesh(eqx.Module):
597
662
  """
598
663
  return cls(vertices=jnp.empty((0, 3)), triangles=jnp.empty((0, 3), dtype=int))
599
664
 
600
- def append(self, other: "TriangleMesh") -> Self:
665
+ def append(self, other: "TriangleMesh") -> Self: # noqa: C901, PLR0912
601
666
  """
602
667
  Return a new mesh by appending another mesh to this one.
603
668
 
@@ -620,6 +685,8 @@ class TriangleMesh(eqx.Module):
620
685
  * The material names are merged, keeping only unique names;
621
686
  * The object bounds are concatenated only if both meshes have them set,
622
687
  otherwise, the object bounds are set to :data:`None`;
688
+ * The masks are concatenated if present in both meshes. If one mesh has a mask while the other does not,
689
+ then the mesh with no mask will have its mask set to all triangles being active (i.e., :data:`True`).
623
690
  * The :attr:`assume_quads` flag is set to :data:`True` if both meshes have it set to :data:`True`.
624
691
 
625
692
  Two important exceptions are:
@@ -734,6 +801,25 @@ class TriangleMesh(eqx.Module):
734
801
  if (self.object_bounds is not None and other.object_bounds is not None)
735
802
  else None
736
803
  )
804
+
805
+ if self.mask is not None and other.mask is not None:
806
+ mask = jnp.concatenate((self.mask, other.mask), axis=0)
807
+ elif self.mask is not None:
808
+ mask = jnp.concatenate(
809
+ (self.mask, jnp.ones_like(self.mask, shape=(other.num_triangles,))),
810
+ axis=0,
811
+ )
812
+ elif other.mask is not None:
813
+ mask = jnp.concatenate(
814
+ (
815
+ jnp.ones_like(other.mask, shape=(self.num_triangles,)),
816
+ other.mask,
817
+ ),
818
+ axis=0,
819
+ )
820
+ else:
821
+ mask = None
822
+
737
823
  assume_quads = self.assume_quads and other.assume_quads
738
824
  mesh = replace(self, material_names=material_names, assume_quads=assume_quads)
739
825
  return eqx.tree_at(
@@ -743,9 +829,10 @@ class TriangleMesh(eqx.Module):
743
829
  m.face_colors,
744
830
  m.face_materials,
745
831
  m.object_bounds,
832
+ m.mask,
746
833
  ),
747
834
  mesh,
748
- (vertices, triangles, face_colors, face_materials, object_bounds),
835
+ (vertices, triangles, face_colors, face_materials, object_bounds, mask),
749
836
  is_leaf=lambda x: x is None,
750
837
  )
751
838
 
@@ -761,6 +848,7 @@ class TriangleMesh(eqx.Module):
761
848
  Returns:
762
849
  A new mesh with duplicate vertices removed.
763
850
  """
851
+ # TODO: handle mask
764
852
  vertices, unique_inverse = jnp.unique(
765
853
  self.vertices, axis=0, return_inverse=True
766
854
  )
@@ -817,6 +905,7 @@ class TriangleMesh(eqx.Module):
817
905
  >>> fig = sorted_mesh.plot(opacity=0.5, backend="plotly")
818
906
  >>> fig # doctest: +SKIP
819
907
  """
908
+ # TODO: handle mask
820
909
  indices = jnp.lexsort(self.vertices.T[::-1])
821
910
  vertices = self.vertices[indices]
822
911
  triangles = jnp.argsort(indices)[self.triangles]
@@ -1383,8 +1472,9 @@ class TriangleMesh(eqx.Module):
1383
1472
  ... )
1384
1473
  >>> fig # doctest: +SKIP
1385
1474
  """
1386
- if "face_colors" not in kwargs and self.face_colors is not None:
1387
- kwargs["face_colors"] = self.face_colors
1475
+ mesh = self.masked()
1476
+ if "face_colors" not in kwargs and mesh.face_colors is not None:
1477
+ kwargs["face_colors"] = mesh.face_colors
1388
1478
 
1389
1479
  normals_kwargs = {} if normals_kwargs is None else normals_kwargs
1390
1480
  triangle_edges_kwargs = (
@@ -1396,26 +1486,26 @@ class TriangleMesh(eqx.Module):
1396
1486
 
1397
1487
  with reuse(pass_all_kwargs=False, **kwargs) as result:
1398
1488
  draw_mesh(
1399
- vertices=self.vertices,
1400
- triangles=self.triangles,
1489
+ vertices=mesh.vertices,
1490
+ triangles=mesh.triangles,
1401
1491
  **kwargs,
1402
1492
  )
1403
1493
 
1404
1494
  if show_normals:
1405
1495
  draw_rays(
1406
- self.triangle_vertices.mean(axis=-2),
1407
- self.normals,
1496
+ mesh.triangle_vertices.mean(axis=-2),
1497
+ mesh.normals,
1408
1498
  **normals_kwargs,
1409
1499
  )
1410
1500
 
1411
1501
  if show_triangle_edges:
1412
1502
  draw_paths(
1413
- self.triangle_edges,
1503
+ mesh.triangle_edges,
1414
1504
  **triangle_edges_kwargs,
1415
1505
  )
1416
1506
  if show_diffraction_edges:
1417
1507
  draw_paths(
1418
- self.diffraction_edges,
1508
+ mesh.diffraction_edges,
1419
1509
  **diffraction_edges_kwargs,
1420
1510
  )
1421
1511
 
@@ -1423,10 +1513,11 @@ class TriangleMesh(eqx.Module):
1423
1513
 
1424
1514
  def sample(
1425
1515
  self,
1426
- size: int,
1516
+ size: int | Float[ArrayLike, " "],
1427
1517
  replace: bool = False,
1428
1518
  preserve: bool = False,
1429
1519
  *,
1520
+ by_masking: bool = False,
1430
1521
  key: PRNGKeyArray,
1431
1522
  ) -> Self:
1432
1523
  """
@@ -1438,7 +1529,13 @@ class TriangleMesh(eqx.Module):
1438
1529
 
1439
1530
  Args:
1440
1531
  size: The size of the sample, i.e., the number of triangles.
1532
+
1533
+ If a floating point number is provided, it is interpreted as a fill factor,
1534
+ i.e., the fraction of triangles to sample from the mesh. This is only supported
1535
+ if ``by_masking`` is set to :data:`True`.
1441
1536
  replace: Whether to sample with or without replacement.
1537
+
1538
+ Cannot be used with ``by_masking`` set to :data:`True`.
1442
1539
  preserve: Whether to preserve :attr:`object_bounds`, otherwise
1443
1540
  it is discarded.
1444
1541
 
@@ -1447,17 +1544,53 @@ class TriangleMesh(eqx.Module):
1447
1544
 
1448
1545
  Setting this to :data:`True` has no effect if :attr:`object_bounds`
1449
1546
  is :data:`None`.
1547
+
1548
+ Cannot be used with ``by_masking`` set to :data:`True`.
1549
+ by_masking: Whether to sample by masking the triangles.
1550
+ If :data:`True`, then the :attr:`mask` attribute set (ignoring any existing mask).
1450
1551
  key: The :func:`jax.random.key` to be used.
1451
1552
 
1452
1553
  Returns:
1453
1554
  A new random mesh.
1555
+
1556
+ Raises:
1557
+ TypeError: If ``by_masking`` is :data:`False` and ``size`` is not an integer.
1558
+ ValueError: If ``by_masking`` is :data:`True` and ``replace`` or ``preserve`` are set to :data:`True`.
1454
1559
  """
1455
- indices = jax.random.choice(
1456
- key,
1457
- self.num_objects,
1458
- shape=(size,),
1459
- replace=replace,
1460
- )
1560
+ if by_masking:
1561
+ if replace:
1562
+ msg = "Cannot sample with replacement when 'by_masking' is True."
1563
+ raise ValueError(msg)
1564
+ if preserve:
1565
+ msg = "Cannot preserve 'object_bounds' when 'by_masking' is True."
1566
+ raise ValueError(msg)
1567
+ if isinstance(size, int):
1568
+ mask = jnp.zeros(self.num_objects, dtype=bool)
1569
+ mask = mask.at[:size].set(True)
1570
+ mask = jax.random.permutation(key, mask)
1571
+ else:
1572
+ mask = jax.random.uniform(key, (self.num_objects,)) <= size
1573
+
1574
+ if self.assume_quads:
1575
+ mask = jnp.repeat(mask, 2)
1576
+
1577
+ return eqx.tree_at(
1578
+ lambda m: (m.object_bounds, m.mask),
1579
+ self,
1580
+ (None, mask),
1581
+ is_leaf=lambda x: x is None,
1582
+ )
1583
+
1584
+ if isinstance(size, int):
1585
+ indices = jax.random.choice(
1586
+ key,
1587
+ self.num_objects,
1588
+ shape=(size,),
1589
+ replace=replace,
1590
+ )
1591
+ else:
1592
+ msg = "'size' must be an integer when 'by_masking' is False."
1593
+ raise TypeError(msg)
1461
1594
 
1462
1595
  if self.assume_quads:
1463
1596
  indices *= 2
@@ -1484,6 +1617,7 @@ class TriangleMesh(eqx.Module):
1484
1617
  m.face_colors,
1485
1618
  m.face_materials,
1486
1619
  m.object_bounds,
1620
+ m.mask,
1487
1621
  ),
1488
1622
  self,
1489
1623
  (
@@ -1494,6 +1628,7 @@ class TriangleMesh(eqx.Module):
1494
1628
  if self.face_materials is not None
1495
1629
  else None,
1496
1630
  object_bounds,
1631
+ self.mask[indices] if self.mask is not None else None,
1497
1632
  ),
1498
1633
  is_leaf=lambda x: x is None,
1499
1634
  )
@@ -1,5 +1,5 @@
1
1
  from functools import partial
2
- from typing import Literal, overload
2
+ from typing import Literal, no_type_check, overload
3
3
 
4
4
  import jax
5
5
  import jax.numpy as jnp
@@ -468,30 +468,77 @@ def fibonacci_lattice(
468
468
  return spherical_to_cartesian(pa).astype(dtype)
469
469
 
470
470
 
471
+ @overload
472
+ def assemble_paths(
473
+ from_vertices: Float[ArrayLike, "*#batch 3"],
474
+ intermediate_vertices: Float[ArrayLike, "*#batch num_inter_vertices 3"],
475
+ to_vertices: Float[ArrayLike, "*#batch 3"],
476
+ ) -> Float[Array, "*batch num_inter_vertices+2 3"]: ...
477
+
478
+
479
+ @overload
480
+ def assemble_paths(
481
+ from_vertices: Float[ArrayLike, "*#batch 3"],
482
+ intermediate_vertices: Float[ArrayLike, "*#batch 3"],
483
+ to_vertices: None = None,
484
+ ) -> Float[Array, "*batch 2 3"]: ...
485
+
486
+
487
+ # NOTE: Jaxtyping does not match the correct shape for `intermediate_vertices` and will match
488
+ # `Float[ArrayLike, "*#batch 3"]` instead of `Float[ArrayLike, "*#batch num_inter_vertices 3"]`.
489
+ # This is why we use `no_type_check` here.
490
+ # TODO: fix this.
491
+ @no_type_check
471
492
  def assemble_paths(
472
- *path_segments: Float[ArrayLike, "*#batch _num_vertices 3"],
473
- ) -> Float[Array, "*#batch path_length 3"]:
493
+ from_vertices: Float[ArrayLike, "*#batch 3"],
494
+ intermediate_vertices: Float[ArrayLike, "*#batch num_inter_vertices 3"]
495
+ | Float[ArrayLike, "*#batch 3"],
496
+ to_vertices: Float[ArrayLike, "*#batch 3"] | None = None,
497
+ ) -> Float[Array, "*batch num_inter_vertices+2 3"] | Float[Array, "*batch 2 3"]:
474
498
  """
475
- Assemble paths by concatenating path vertices along the second to last axis.
499
+ Assemble paths vertices by concatenating start-, intermediate, and end-vertices.
476
500
 
477
501
  Arrays broadcasting is automatically performed, and the total
478
- path length is simply is sum of all the number of vertices.
502
+ number of vertices per path is simply ``num_inter_vertices+2``.
479
503
 
480
504
  Args:
481
- path_segments: The path segments to assemble together.
482
-
483
- Usually, this will be a 3-tuple of transmitter positions,
484
- interaction points, and receiver positions.
505
+ from_vertices: The starting vertices of the paths.
506
+ intermediate_vertices: The intermediate vertices of the paths.
507
+ If ``to_vertices`` is not provided, then this argument is interpreted
508
+ as the end vertices of the paths.
509
+ to_vertices: The ending vertices of the paths.
485
510
 
486
511
  Returns:
487
- The assembled paths.
512
+ The assembled path vertices.
488
513
  """
489
- # TODO: simplify this function to only take start / mid / end points
490
- arrays = [jnp.asarray(path_segment) for path_segment in path_segments]
491
- batch = jnp.broadcast_shapes(*(arr.shape[:-2] for arr in arrays))
514
+ from_vertices = jnp.asarray(from_vertices)
515
+ intermediate_vertices = jnp.asarray(intermediate_vertices)
516
+ if to_vertices is None:
517
+ batch = jnp.broadcast_shapes(
518
+ from_vertices.shape[:-1], intermediate_vertices.shape[:-1]
519
+ )
520
+ return jnp.concatenate(
521
+ (
522
+ jnp.broadcast_to(from_vertices[..., None, :], (*batch, 1, 3)),
523
+ jnp.broadcast_to(intermediate_vertices[..., None, :], (*batch, 1, 3)),
524
+ ),
525
+ axis=-2,
526
+ )
527
+ to_vertices = jnp.asarray(to_vertices)
528
+ batch = jnp.broadcast_shapes(
529
+ from_vertices.shape[:-1],
530
+ intermediate_vertices.shape[:-2],
531
+ to_vertices.shape[:-1],
532
+ )
492
533
 
493
534
  return jnp.concatenate(
494
- tuple(jnp.broadcast_to(arr, (*batch, *arr.shape[-2:])) for arr in arrays),
535
+ (
536
+ jnp.broadcast_to(from_vertices[..., None, :], (*batch, 1, 3)),
537
+ jnp.broadcast_to(
538
+ intermediate_vertices, (*batch, *intermediate_vertices.shape[-2:])
539
+ ),
540
+ jnp.broadcast_to(to_vertices[..., None, :], (*batch, 1, 3)),
541
+ ),
495
542
  axis=-2,
496
543
  )
497
544
 
@@ -785,12 +832,12 @@ def cartesian_to_spherical(
785
832
  xyz: Float[ArrayLike, "*batch 3"],
786
833
  ) -> Float[Array, "*batch 3"]:
787
834
  """
788
- Transform cartesian coordinates to spherical coordinates.
835
+ Transform Cartesian coordinates to spherical coordinates.
789
836
 
790
837
  See :ref:`conventions` for details.
791
838
 
792
839
  Args:
793
- xyz: The array of cartesian coordinates.
840
+ xyz: The array of Cartesian coordinates.
794
841
 
795
842
  Returns:
796
843
  The array of corresponding spherical coordinates.
@@ -813,7 +860,7 @@ def spherical_to_cartesian(
813
860
  rpa: Float[ArrayLike, "*batch 3"] | Float[ArrayLike, "*batch 2"],
814
861
  ) -> Float[Array, "*batch 3"]:
815
862
  """
816
- Transform spherical coordinates to cartisian coordinates.
863
+ Transform spherical coordinates to Cartesian coordinates.
817
864
 
818
865
  See :ref:`conventions` for details.
819
866
 
@@ -823,7 +870,7 @@ def spherical_to_cartesian(
823
870
  If the radial component is missing, a radius of 1 is assumed.
824
871
 
825
872
  Returns:
826
- The array of corresponding cartesian coordinates.
873
+ The array of corresponding Cartesian coordinates.
827
874
 
828
875
  .. seealso::
829
876
 
@@ -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) # type: ignore[reportArgumentType]
547
+ ax.scatter(xs, ys, zs=zs, **kwargs)
548
548
 
549
549
  return fig
550
550
 
@@ -770,7 +770,7 @@ def draw_contour( # noqa: PLR0917
770
770
 
771
771
  Warning:
772
772
  VisPy does not support filling the contour.
773
- Plotly does not support 3D contours, and will draw the coontour on
773
+ Plotly does not support 3D contours, and will draw the contour on
774
774
  a 2D figure instead.
775
775
 
776
776
  Examples:
@@ -6,4 +6,7 @@ import numpy as np
6
6
  from jaxtyping import Array
7
7
 
8
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)
9
+ ArrayType = TypeVar(
10
+ "ArrayType",
11
+ bound=Array | np.ndarray, # type: ignore[reportMissingTypeArgument]
12
+ )
@@ -171,7 +171,7 @@ class DeepMIMO(eqx.Module, Generic[ArrayType]):
171
171
  """
172
172
  return jax.tree.map(jnp.asarray, self)
173
173
 
174
- def numpy(self) -> "DeepMIMO[np.ndarray]":
174
+ def numpy(self) -> "DeepMIMO[np.ndarray]": # type: ignore[reportMissingTypeArgument]
175
175
  """
176
176
  Return a copy of this class with arrays converted to NumPy arrays.
177
177
 
@@ -110,9 +110,9 @@ def fermat_path_on_linear_objects(
110
110
  paths = fermat_path_on_linear_objects(...)
111
111
 
112
112
  full_paths = assemble_paths(
113
- from_vertices[..., None, :],
113
+ from_vertices,
114
114
  paths,
115
- to_vertices[..., None, :],
115
+ to_vertices,
116
116
  )
117
117
 
118
118
  Examples:
@@ -156,9 +156,9 @@ def fermat_path_on_linear_objects(
156
156
  ... )
157
157
  ...
158
158
  ... full_path = assemble_paths(
159
- ... from_vertex[None, :],
159
+ ... from_vertex,
160
160
  ... path,
161
- ... to_vertex[None, :],
161
+ ... to_vertex,
162
162
  ... )
163
163
  ... draw_paths(full_path, marker={"color": "green"}, name="Final path")
164
164
  ... markers = jnp.vstack((from_vertex, to_vertex))
@@ -309,9 +309,9 @@ def fermat_path_on_planar_mirrors(
309
309
  paths = fermat_path_on_planar_mirrors(...)
310
310
 
311
311
  full_paths = assemble_paths(
312
- from_vertices[..., None, :],
312
+ from_vertices,
313
313
  paths,
314
- to_vertices[..., None, :],
314
+ to_vertices,
315
315
  )
316
316
 
317
317
  Examples:
@@ -350,9 +350,9 @@ def fermat_path_on_planar_mirrors(
350
350
  ... ).plot(color="red")
351
351
  ...
352
352
  ... full_path = assemble_paths(
353
- ... from_vertex[None, :],
353
+ ... from_vertex,
354
354
  ... path,
355
- ... to_vertex[None, :],
355
+ ... to_vertex,
356
356
  ... )
357
357
  ... draw_paths(full_path, marker={"color": "green"}, name="Final path")
358
358
  ... markers = jnp.vstack((from_vertex, to_vertex))
@@ -195,9 +195,9 @@ def image_method(
195
195
  )
196
196
 
197
197
  full_paths = assemble_paths(
198
- from_vertices[..., None, :],
198
+ from_vertices,
199
199
  paths,
200
- to_vertices[..., None, :],
200
+ to_vertices,
201
201
  )
202
202
 
203
203
  Examples:
@@ -252,9 +252,9 @@ def image_method(
252
252
  ... ).plot(color="red")
253
253
  ...
254
254
  ... full_path = assemble_paths(
255
- ... from_vertex[None, :],
255
+ ... from_vertex,
256
256
  ... path,
257
- ... to_vertex[None, :],
257
+ ... to_vertex,
258
258
  ... )
259
259
  ... draw_paths(
260
260
  ... full_path,
@@ -351,6 +351,7 @@ def rays_intersect_any_triangle(
351
351
  ray_origins: Float[ArrayLike, "*#batch 3"],
352
352
  ray_directions: Float[ArrayLike, "*#batch 3"],
353
353
  triangle_vertices: Float[ArrayLike, "*#batch num_triangles 3 3"],
354
+ active_triangles: Bool[ArrayLike, "*#batch num_triangles"] | None = None,
354
355
  *,
355
356
  hit_tol: Float[ArrayLike, " "] | None = None,
356
357
  smoothing_factor: None = None,
@@ -363,6 +364,7 @@ def rays_intersect_any_triangle(
363
364
  ray_origins: Float[ArrayLike, "*#batch 3"],
364
365
  ray_directions: Float[ArrayLike, "*#batch 3"],
365
366
  triangle_vertices: Float[ArrayLike, "*#batch num_triangles 3 3"],
367
+ active_triangles: Bool[ArrayLike, "*#batch num_triangles"] | None = None,
366
368
  *,
367
369
  hit_tol: Float[ArrayLike, " "] | None = None,
368
370
  smoothing_factor: Float[ArrayLike, " "],
@@ -375,6 +377,7 @@ def rays_intersect_any_triangle(
375
377
  ray_origins: Float[ArrayLike, "*#batch 3"],
376
378
  ray_directions: Float[ArrayLike, "*#batch 3"],
377
379
  triangle_vertices: Float[ArrayLike, "*#batch num_triangles 3 3"],
380
+ active_triangles: Bool[ArrayLike, "*#batch num_triangles"] | None = None,
378
381
  *,
379
382
  hit_tol: Float[ArrayLike, " "] | None = None,
380
383
  smoothing_factor: Float[ArrayLike, " "] | None = None,
@@ -395,6 +398,10 @@ def rays_intersect_any_triangle(
395
398
  ray_directions: An array of ray direction. The ray ends
396
399
  should be equal to ``ray_origins + ray_directions``.
397
400
  triangle_vertices: An array of triangle vertices.
401
+ active_triangles: An optional array of boolean values indicating
402
+ which triangles are active, i.e., should be considered for intersection.
403
+
404
+ If not specified, all triangles are considered active.
398
405
  hit_tol: The tolerance applied to check if a ray hits another object or not,
399
406
  before it reaches the expected position, i.e., the 'interaction' object.
400
407
 
@@ -427,6 +434,11 @@ def rays_intersect_any_triangle(
427
434
 
428
435
  # Put 'num_triangles' axis as leading axis
429
436
  triangle_vertices = jnp.moveaxis(triangle_vertices, -3, 0)
437
+ active_triangles = (
438
+ jnp.moveaxis(active_triangles, -1, 0)
439
+ if active_triangles is not None
440
+ else jnp.ones(triangle_vertices.shape[:-2], dtype=bool)
441
+ )
430
442
 
431
443
  batch = jnp.broadcast_shapes(
432
444
  ray_origins.shape[:-1],
@@ -438,8 +450,11 @@ def rays_intersect_any_triangle(
438
450
 
439
451
  def scan_fun(
440
452
  intersect: Float[Array, " *batch"],
441
- triangle_vertices: Float[Array, "*#batch 3 3"],
453
+ triangle_vertices_and_active: tuple[
454
+ Float[Array, "*#batch 3 3"], Bool[Array, "*#batch"] | None
455
+ ],
442
456
  ) -> tuple[Float[Array, " *batch"], None]:
457
+ triangle_vertices, active_triangles = triangle_vertices_and_active
443
458
  t, hit = rays_intersect_triangles(
444
459
  ray_origins,
445
460
  ray_directions,
@@ -447,6 +462,7 @@ def rays_intersect_any_triangle(
447
462
  smoothing_factor=smoothing_factor,
448
463
  **kwargs,
449
464
  )
465
+ hit *= active_triangles
450
466
  intersect = (
451
467
  intersect
452
468
  + jnp.minimum(
@@ -461,15 +477,18 @@ def rays_intersect_any_triangle(
461
477
 
462
478
  def scan_fun(
463
479
  intersect: Bool[Array, " *batch"],
464
- triangle_vertices: Float[Array, "*#batch 3 3"],
480
+ triangle_vertices_and_active: tuple[
481
+ Float[Array, "*#batch 3 3"], Bool[Array, "*#batch"] | None
482
+ ],
465
483
  ) -> tuple[Bool[Array, " *batch"], None]:
484
+ triangle_vertices, active_triangles = triangle_vertices_and_active
466
485
  t, hit = rays_intersect_triangles(
467
486
  ray_origins,
468
487
  ray_directions,
469
488
  triangle_vertices,
470
489
  **kwargs,
471
490
  )
472
- intersect |= (t < hit_threshold) & hit
491
+ intersect |= (t < hit_threshold) & hit & active_triangles
473
492
  return intersect, None
474
493
 
475
494
  init = (
@@ -481,7 +500,7 @@ def rays_intersect_any_triangle(
481
500
  return jax.lax.scan(
482
501
  scan_fun,
483
502
  init=init,
484
- xs=triangle_vertices,
503
+ xs=(triangle_vertices, active_triangles),
485
504
  )[0]
486
505
 
487
506
 
@@ -489,6 +508,7 @@ def rays_intersect_any_triangle(
489
508
  def triangles_visible_from_vertices(
490
509
  vertices: Float[ArrayLike, "*#batch 3"],
491
510
  triangle_vertices: Float[ArrayLike, "*#batch num_triangles 3 3"],
511
+ active_triangles: Bool[ArrayLike, "*#batch num_triangles"] | None = None,
492
512
  num_rays: int = int(1e6),
493
513
  **kwargs: Any,
494
514
  ) -> Bool[Array, "*batch num_triangles"]:
@@ -509,6 +529,10 @@ def triangles_visible_from_vertices(
509
529
 
510
530
  Usually, this would be an array of transmitter positions.
511
531
  triangle_vertices: An array of triangle vertices.
532
+ active_triangles: An optional array of boolean values indicating
533
+ which triangles are active, i.e., should be considered for intersection.
534
+
535
+ If not specified, all triangles are considered active.
512
536
  num_rays: The number of rays to launch.
513
537
 
514
538
  The larger, the more accurate.
@@ -561,6 +585,8 @@ def triangles_visible_from_vertices(
561
585
 
562
586
  # [2 3]
563
587
  # note: currently we don't handle batches and generate one frustum for everything
588
+ # TODO: compute frustum for each batch
589
+ # TODO: handle 'active_triangles'
564
590
  frustum = viewing_frustum(
565
591
  ray_origins,
566
592
  triangle_vertices.reshape(*triangle_vertices.shape[:-3], -1, 3),
@@ -584,7 +610,14 @@ def triangles_visible_from_vertices(
584
610
  )
585
611
  # A triangle is visible if it is the first triangle to be intersected by a ray.
586
612
  visible = visible | (
587
- t == jnp.min(t, axis=-1, keepdims=True, initial=jnp.inf, where=hit)
613
+ t
614
+ == jnp.min(
615
+ t,
616
+ axis=-1,
617
+ keepdims=True,
618
+ initial=jnp.inf,
619
+ where=(hit & active_triangles if active_triangles is not None else hit),
620
+ )
588
621
  )
589
622
 
590
623
  return visible, None
@@ -601,6 +634,7 @@ def first_triangles_hit_by_rays(
601
634
  ray_origins: Float[ArrayLike, "*#batch 3"],
602
635
  ray_directions: Float[ArrayLike, "*#batch 3"],
603
636
  triangle_vertices: Float[ArrayLike, "*#batch num_triangles 3 3"],
637
+ active_triangles: Bool[ArrayLike, "*#batch num_triangles"] | None = None,
604
638
  **kwargs: Any,
605
639
  ) -> tuple[Int[Array, " *batch"], Float[Array, " *batch"]]:
606
640
  """
@@ -615,6 +649,10 @@ def first_triangles_hit_by_rays(
615
649
  ray_directions: An array of ray direction. The ray ends
616
650
  should be equal to ``ray_origins + ray_directions``.
617
651
  triangle_vertices: An array of triangle vertices.
652
+ active_triangles: An optional array of boolean values indicating
653
+ which triangles are active, i.e., should be considered for intersection.
654
+
655
+ If not specified, all triangles are considered active.
618
656
  kwargs: Keyword arguments passed to
619
657
  :func:`rays_intersect_triangles`.
620
658
 
@@ -630,6 +668,11 @@ def first_triangles_hit_by_rays(
630
668
 
631
669
  # Put 'num_triangles' axis as leading axis
632
670
  triangle_vertices = jnp.moveaxis(triangle_vertices, -3, 0)
671
+ active_triangles = (
672
+ jnp.moveaxis(active_triangles, -1, 0)
673
+ if active_triangles is not None
674
+ else jnp.ones(triangle_vertices.shape[:-2], dtype=bool)
675
+ )
633
676
 
634
677
  batch = jnp.broadcast_shapes(
635
678
  ray_origins.shape[:-1],
@@ -639,18 +682,21 @@ def first_triangles_hit_by_rays(
639
682
 
640
683
  def scan_fun(
641
684
  carry: tuple[Int[Array, " *batch"], Float[Array, "*batch"], Int[Array, " "]],
642
- triangle_vertices: Float[Array, "*#batch 3 3"],
685
+ triangle_vertices_and_active: tuple[
686
+ Float[Array, "*#batch 3 3"], Bool[Array, "*#batch"] | None
687
+ ],
643
688
  ) -> tuple[
644
689
  tuple[Int[Array, " *batch"], Float[Array, "*batch"], Int[Array, " "]], None
645
690
  ]:
646
691
  indices, t_hit, index = carry
692
+ triangle_vertices, active_triangles = triangle_vertices_and_active
647
693
  t, hit = rays_intersect_triangles(
648
694
  ray_origins,
649
695
  ray_directions,
650
696
  triangle_vertices,
651
697
  **kwargs,
652
698
  )
653
- t = jnp.where(hit, t, jnp.full_like(t, jnp.inf))
699
+ t = jnp.where((hit & active_triangles), t, jnp.full_like(t, jnp.inf))
654
700
  indices = jnp.where(t < t_hit, index, indices)
655
701
  t_hit = jnp.minimum(t, t_hit)
656
702
  return (indices, t_hit, index + 1), None
@@ -658,5 +704,5 @@ def first_triangles_hit_by_rays(
658
704
  return jax.lax.scan(
659
705
  scan_fun,
660
706
  init=(-jnp.ones(batch, dtype=int), jnp.full(batch, jnp.inf), jnp.array(0)),
661
- xs=triangle_vertices,
707
+ xs=(triangle_vertices, active_triangles),
662
708
  )[0][:2]
@@ -85,6 +85,13 @@ def _compute_paths( # noqa: C901, PLR0915
85
85
  num_path_candidates, order, 3, 3
86
86
  ) # reshape required if mesh is empty
87
87
 
88
+ if mesh.mask is not None:
89
+ # For a ray to be active, it must hit triangles that are not masked out (i.e, inactive).
90
+ # [num_path_candidates] # noqa: ERA001
91
+ active_rays = jnp.take(mesh.mask, path_candidates, axis=0).all(axis=-1)
92
+ else:
93
+ active_rays = None
94
+
88
95
  if mesh.assume_quads:
89
96
  # [num_path_candidates order 2 3]
90
97
  quads = jnp.take(
@@ -110,7 +117,7 @@ def _compute_paths( # noqa: C901, PLR0915
110
117
  # [num_path_candidates order 3]
111
118
  mirror_normals = jnp.take(mesh.normals, path_candidates, axis=0)
112
119
 
113
- def fun(
120
+ def fun( # noqa: PLR0912
114
121
  tx_vertices: Float[Array, "num_tx_vertices 3"],
115
122
  rx_vertices: Float[Array, "num_rx_vertices 3"],
116
123
  ) -> tuple[
@@ -133,9 +140,9 @@ def _compute_paths( # noqa: C901, PLR0915
133
140
 
134
141
  # [num_tx_vertices num_rx_vertices num_path_candidates order+2 3]
135
142
  full_paths = assemble_paths(
136
- tx_vertices[:, None, None, None, :],
143
+ tx_vertices[:, None, None, :],
137
144
  paths,
138
- rx_vertices[None, :, None, None, :],
145
+ rx_vertices[None, :, None, :],
139
146
  )
140
147
 
141
148
  # 3 - Identify invalid paths
@@ -213,6 +220,7 @@ def _compute_paths( # noqa: C901, PLR0915
213
220
  ray_origins,
214
221
  ray_directions,
215
222
  mesh.triangle_vertices,
223
+ active_triangles=mesh.mask,
216
224
  epsilon=epsilon,
217
225
  hit_tol=hit_tol,
218
226
  smoothing_factor=smoothing_factor,
@@ -222,6 +230,7 @@ def _compute_paths( # noqa: C901, PLR0915
222
230
  ray_origins,
223
231
  ray_directions,
224
232
  mesh.triangle_vertices,
233
+ active_triangles=mesh.mask,
225
234
  epsilon=epsilon,
226
235
  hit_tol=hit_tol,
227
236
  ).any(axis=-1) # Reduce on 'order'
@@ -256,8 +265,12 @@ def _compute_paths( # noqa: C901, PLR0915
256
265
  ),
257
266
  axis=-1,
258
267
  ).min(axis=-1, initial=1.0)
268
+ if active_rays is not None:
269
+ confidence *= active_rays
259
270
  return full_paths, confidence
260
271
  mask = inside_triangles & valid_reflections & ~blocked & ~too_small & is_finite
272
+ if active_rays is not None:
273
+ mask &= active_rays
261
274
  return full_paths, mask
262
275
 
263
276
  if parallel:
@@ -352,6 +365,7 @@ def _compute_paths_sbr(
352
365
  )
353
366
 
354
367
  # [num_tx_vertices 2 3]
368
+ # TODO: handle mesh.mask
355
369
  frustums = jax.vmap(viewing_frustum, in_axes=(0, None))(tx_vertices, world_vertices)
356
370
 
357
371
  # [num_tx_vertices num_rays 2 3]
@@ -397,6 +411,7 @@ def _compute_paths_sbr(
397
411
  ray_origins,
398
412
  ray_directions,
399
413
  triangle_vertices,
414
+ active_triangles=mesh.mask,
400
415
  epsilon=epsilon,
401
416
  )
402
417
 
@@ -499,9 +514,9 @@ def _compute_paths_sbr(
499
514
  # 4 - Generate output paths and reshape
500
515
 
501
516
  vertices = assemble_paths(
502
- tx_vertices[:, None, None, None, :],
517
+ tx_vertices[:, None, None, :],
503
518
  vertices[:, None, ...], # We already excluded last vertex
504
- rx_vertices[None, :, None, None, :], # And replace it with receiver vertices
519
+ rx_vertices[None, :, None, :], # And replace it with receiver vertices
505
520
  )
506
521
 
507
522
  object_dtype = path_candidates.dtype
@@ -1,23 +1,15 @@
1
1
  """General purpose utilities."""
2
2
 
3
- import warnings
4
- from collections.abc import Callable
5
3
  from functools import partial
6
4
  from typing import (
7
- Any,
8
- Concatenate,
9
5
  Literal,
10
- NamedTuple,
11
- ParamSpec,
12
6
  overload,
13
7
  )
14
8
 
15
- import chex
16
9
  import equinox as eqx
17
10
  import jax
18
11
  import jax.numpy as jnp
19
- import optax
20
- from jaxtyping import Array, ArrayLike, Float, Inexact, Num, PRNGKeyArray, Shaped
12
+ from jaxtyping import Array, ArrayLike, Float, Num, PRNGKeyArray, Shaped
21
13
 
22
14
 
23
15
  @overload
@@ -138,129 +130,6 @@ def sorted_array2(array: Shaped[ArrayLike, "m n"]) -> Shaped[Array, "m n"]:
138
130
  return array[jnp.lexsort(array.T[::-1])]
139
131
 
140
132
 
141
- # Redefined here, because chex uses deprecated type hints
142
- # TODO: fixme when google/chex#361 is resolved.
143
- # TODO: changme because beartype>=0.20 complains that it cannot import ArrayTree,
144
- # and I don't see how to fix it.
145
- OptState = Any
146
- # TODO: fixme when Python >= 3.11
147
- P = ParamSpec("P")
148
-
149
-
150
- class OptimizeResult(NamedTuple):
151
- """
152
- A class to hold the result of an optimization, akin to :class:`scipy.optimize.OptimizeResult`.
153
-
154
- .. deprecated:: 0.1.2
155
- This class is deprecated and will be removed in the v0.2.0 release.
156
- See `#283 <https://github.com/jeertmans/DiffeRT/issues/283>`_ for motivation
157
- and alternatives.
158
- """
159
-
160
- x: Inexact[Array, "*batch n"]
161
- """The solution of the optimization."""
162
- fun: Inexact[Array, " *batch"]
163
- """Value of objective function at :attr:`x`."""
164
-
165
-
166
- @eqx.filter_jit
167
- def minimize(
168
- fun: Callable[Concatenate[Inexact[Array, " n"], P], Inexact[Array, " "]],
169
- x0: Inexact[ArrayLike, "*batch n"],
170
- args: tuple[Any, ...] = (),
171
- steps: int = 1000,
172
- optimizer: optax.GradientTransformation | None = None,
173
- ) -> OptimizeResult:
174
- """
175
- Minimize a scalar function of one or more variables.
176
-
177
- .. deprecated:: 0.1.2
178
- This function is deprecated and will be removed in the v0.2.0 release.
179
- See `#283 <https://github.com/jeertmans/DiffeRT/issues/283>`_ for motivation
180
- and alternatives.
181
-
182
- The minimization is achieved by computing the
183
- gradient of the objective function, and performing
184
- a fixed number of iterations (i.e., ``steps``).
185
-
186
- Args:
187
- fun: The objective function to be minimized.
188
- x0: The initial guess.
189
- args: Positional arguments passed to ``fun``.
190
-
191
- Those arguments are also expected have
192
- batch dimensions similar to ``x0``.
193
-
194
- .. note::
195
-
196
- If your function has static arguments,
197
- please wrap the function with :func:`functools.partial`:
198
-
199
- .. code-block:: python
200
-
201
- fun_p = partial(fun, static_arg=static_value)
202
-
203
- If your function has keyword-only
204
- arguments, create a wrapper function that
205
- maps positional arguments to keyword only arguments:
206
-
207
- .. code-block:: python
208
-
209
- fun_p = lambda x, kw_only_value: fun(x, kw_only_arg=kw_only_value)
210
-
211
- steps: The number of steps to perform.
212
- optimizer: The optimizer to use. If not provided,
213
- uses :func:`optax.adam` with a learning rate of ``0.1``.
214
-
215
- Returns:
216
- The optimization result.
217
- """
218
- msg = (
219
- "This function is deprecated and will be removed in the v0.2.0 release. "
220
- "See https://github.com/jeertmans/DiffeRT/issues/283 for motivation and alternatives."
221
- )
222
- warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
223
-
224
- x0 = jnp.asarray(x0)
225
- if x0.ndim > 1 and args:
226
- chex.assert_tree_has_only_ndarrays(args, exception_type=TypeError)
227
-
228
- def shape_str(arr_or_shape: Array | tuple[int, ...]) -> str:
229
- if isinstance(arr_or_shape, tuple):
230
- shape = arr_or_shape
231
- else:
232
- shape = arr_or_shape.shape
233
- return str(shape).replace(" ", "")
234
-
235
- msg = f"{shape_str(x0.shape[:-1])} is expected to be the shape prefix of all arguments, got {', '.join(shape_str(arr) for arr in args)}."
236
- chex.assert_tree_shape_prefix(
237
- args,
238
- x0.shape[:-1],
239
- exception_type=TypeError,
240
- custom_message=msg,
241
- )
242
-
243
- optimizer = optax.adam(learning_rate=0.1) if optimizer is None else optimizer
244
-
245
- f_and_df = jax.value_and_grad(fun)
246
- for _ in x0.shape[:-1]:
247
- f_and_df = jax.vmap(f_and_df)
248
-
249
- def update(
250
- state: tuple[Inexact[Array, " *batch n"], OptState],
251
- _: None,
252
- ) -> tuple[tuple[Inexact[Array, " *batch n"], OptState], Inexact[Array, " *batch"]]:
253
- x, opt_state = state
254
- loss, grads = f_and_df(x, *args)
255
- updates, opt_state = optimizer.update(grads, opt_state, x)
256
- x = optax.apply_updates(x, updates)
257
- return (x, opt_state), loss # type: ignore[reportReturnType]
258
-
259
- (x, _), losses = jax.lax.scan(update, init=(x0, optimizer.init(x0)), length=steps)
260
-
261
- return OptimizeResult(x, losses[-1])
262
-
263
-
264
133
  @partial(jax.jit, static_argnames=("shape",))
265
134
  def sample_points_in_bounding_box(
266
135
  bounding_box: Float[ArrayLike, "2 3"],
@@ -1,6 +0,0 @@
1
- """Differentiable Ray Tracing Toolbox for Radio Propagation."""
2
-
3
- from ._version import VERSION
4
-
5
- __version__ = VERSION
6
- __all__ = ("VERSION",)
@@ -1,6 +0,0 @@
1
- from differt_core import __version__ # Re-export version from code module
2
-
3
- __all__ = ("VERSION",)
4
-
5
- VERSION: str = __version__
6
- """The current version of this module."""
File without changes
File without changes
File without changes
File without changes