differt 0.3.1__tar.gz → 0.4.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.3.1 → differt-0.4.1}/PKG-INFO +3 -3
  2. {differt-0.3.1 → differt-0.4.1}/README.md +1 -1
  3. {differt-0.3.1 → differt-0.4.1}/pyproject.toml +1 -1
  4. {differt-0.3.1 → differt-0.4.1}/src/differt/em/_antenna.py +1 -1
  5. {differt-0.3.1 → differt-0.4.1}/src/differt/em/_utd.py +1 -1
  6. {differt-0.3.1 → differt-0.4.1}/src/differt/geometry/_triangle_mesh.py +66 -24
  7. {differt-0.3.1 → differt-0.4.1}/src/differt/plotting/_core.py +18 -6
  8. {differt-0.3.1 → differt-0.4.1}/src/differt/plugins/deepmimo.py +1 -1
  9. {differt-0.3.1 → differt-0.4.1}/src/differt/rt/_fermat.py +57 -78
  10. {differt-0.3.1 → differt-0.4.1}/src/differt/rt/_image_method.py +80 -80
  11. {differt-0.3.1 → differt-0.4.1}/src/differt/rt/_utils.py +289 -110
  12. {differt-0.3.1 → differt-0.4.1}/src/differt/scene/_triangle_scene.py +35 -31
  13. {differt-0.3.1 → differt-0.4.1}/.gitignore +0 -0
  14. {differt-0.3.1 → differt-0.4.1}/LICENSE.md +0 -0
  15. {differt-0.3.1 → differt-0.4.1}/src/differt/__init__.py +0 -0
  16. {differt-0.3.1 → differt-0.4.1}/src/differt/_version.py +0 -0
  17. {differt-0.3.1 → differt-0.4.1}/src/differt/em/__init__.py +0 -0
  18. {differt-0.3.1 → differt-0.4.1}/src/differt/em/_constants.py +0 -0
  19. {differt-0.3.1 → differt-0.4.1}/src/differt/em/_fresnel.py +0 -0
  20. {differt-0.3.1 → differt-0.4.1}/src/differt/em/_interaction_type.py +0 -0
  21. {differt-0.3.1 → differt-0.4.1}/src/differt/em/_material.py +0 -0
  22. {differt-0.3.1 → differt-0.4.1}/src/differt/em/_utils.py +0 -0
  23. {differt-0.3.1 → differt-0.4.1}/src/differt/geometry/__init__.py +0 -0
  24. {differt-0.3.1 → differt-0.4.1}/src/differt/geometry/_paths.py +0 -0
  25. {differt-0.3.1 → differt-0.4.1}/src/differt/geometry/_utils.py +0 -0
  26. {differt-0.3.1 → differt-0.4.1}/src/differt/plotting/__init__.py +0 -0
  27. {differt-0.3.1 → differt-0.4.1}/src/differt/plotting/_utils.py +0 -0
  28. {differt-0.3.1 → differt-0.4.1}/src/differt/plugins/__init__.py +0 -0
  29. {differt-0.3.1 → differt-0.4.1}/src/differt/plugins/_deepmimo_types.py +0 -0
  30. {differt-0.3.1 → differt-0.4.1}/src/differt/py.typed +0 -0
  31. {differt-0.3.1 → differt-0.4.1}/src/differt/rt/__init__.py +0 -0
  32. {differt-0.3.1 → differt-0.4.1}/src/differt/scene/__init__.py +0 -0
  33. {differt-0.3.1 → differt-0.4.1}/src/differt/scene/_sionna.py +0 -0
  34. {differt-0.3.1 → differt-0.4.1}/src/differt/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: DiffeRT
3
- Version: 0.3.1
3
+ Version: 0.4.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.3.1
24
+ Requires-Dist: differt-core==0.4.1
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.3.1}
143
+ version = {v0.4.1}
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.3.1}
86
+ version = {v0.4.1}
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.3.1",
19
+ "differt-core==0.4.1",
20
20
  "equinox>=0.12.2",
21
21
  "filelock>=3.15.4",
22
22
  "jax>=0.4.32", # TODO: fixme, issue with pmap
@@ -645,7 +645,7 @@ class RadiationPattern(BaseAntenna):
645
645
 
646
646
  r = self.center + distance * jnp.stack((x, y, z), axis=-1)
647
647
 
648
- s = self.poynting_vector(r) # type: ignore[reportAttributeAccessIssue]
648
+ s = self.poynting_vector(r)
649
649
 
650
650
  p = jnp.linalg.norm(s, axis=-1, keepdims=True)
651
651
 
@@ -75,7 +75,7 @@ def L_i(
75
75
 
76
76
 
77
77
  @eqx.filter_jit
78
- def L_i( # noqa: PLR0917
78
+ def L_i(
79
79
  s_d: Float[Array, " *#batch"],
80
80
  sin_2_beta_0: Float[Array, " *#batch"],
81
81
  rho_1_i: Float[Array, " *#batch"] | None = None,
@@ -213,7 +213,7 @@ class TriangleMesh(eqx.Module):
213
213
  converter=tuple, default_factory=tuple, static=True
214
214
  )
215
215
  """The list of material names (must be unique)."""
216
- object_bounds: Int[Array, "num_objects 2"] | None = eqx.field(
216
+ object_bounds: Int[Array, "num_primitives 2"] | None = eqx.field(
217
217
  converter=lambda x: jnp.asarray(x) if x is not None else None, default=None
218
218
  )
219
219
  """The array of object indices.
@@ -248,6 +248,11 @@ class TriangleMesh(eqx.Module):
248
248
 
249
249
  Unless specified, the transformation or selection operations, like :meth:`rotate`,
250
250
  will not take the mask into account, and will apply to all triangles.
251
+
252
+ .. important::
253
+
254
+ When :attr:`assume_quads` is :data:`True`, a quad is considered active if both triangles
255
+ that form the quad are active.
251
256
  """
252
257
 
253
258
  def __check_init__(self) -> None: # noqa: PLW3201
@@ -350,10 +355,10 @@ class TriangleMesh(eqx.Module):
350
355
  return self.triangles.shape[0] // 2
351
356
 
352
357
  @property
353
- def num_objects(self) -> int:
354
- """The number of objects.
358
+ def num_primitives(self) -> int:
359
+ """The number of primitives.
355
360
 
356
- This is a convenient alias to :attr:`num_quads` :attr:`assume_quads` is :data:`True`
361
+ This is a convenient alias to :attr:`num_quads` if :attr:`assume_quads` is :data:`True`
357
362
  else :attr:`num_triangles`.
358
363
  """
359
364
  return self.num_quads if self.assume_quads else self.num_triangles
@@ -662,7 +667,7 @@ class TriangleMesh(eqx.Module):
662
667
  """
663
668
  return cls(vertices=jnp.empty((0, 3)), triangles=jnp.empty((0, 3), dtype=int))
664
669
 
665
- def append(self, other: "TriangleMesh") -> Self: # noqa: C901, PLR0912
670
+ def append(self, other: "TriangleMesh") -> Self:
666
671
  """
667
672
  Return a new mesh by appending another mesh to this one.
668
673
 
@@ -1061,7 +1066,7 @@ class TriangleMesh(eqx.Module):
1061
1066
  )
1062
1067
  elif self.assume_quads:
1063
1068
  quad_colors = jax.random.uniform(key, (self.num_quads, 3))
1064
- repeats = jnp.full(self.num_objects, 2)
1069
+ repeats = jnp.full(self.num_primitives, 2)
1065
1070
  colors = jnp.repeat(
1066
1071
  quad_colors, repeats, axis=0, total_repeat_length=self.num_triangles
1067
1072
  )
@@ -1095,11 +1100,11 @@ class TriangleMesh(eqx.Module):
1095
1100
  A new mesh with updated face materials.
1096
1101
 
1097
1102
  Raises:
1098
- 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`).
1103
+ ValueError: If the number of names is not 1, :attr:`num_triangles`, or :attr:`num_primitives` (if :attr:`assume_quads` is set to :data:`True`).
1099
1104
  """
1100
- if len(names) not in {1, self.num_triangles, self.num_objects}:
1105
+ if len(names) not in {1, self.num_triangles, self.num_primitives}:
1101
1106
  if self.assume_quads:
1102
- msg = f"Expected either 1, {self.num_triangles}, or {self.num_objects} names, got {len(names)}."
1107
+ msg = f"Expected either 1, {self.num_triangles}, or {self.num_primitives} names, got {len(names)}."
1103
1108
  else:
1104
1109
  msg = f"Expected either 1, or {self.num_triangles} names, got {len(names)}."
1105
1110
  raise ValueError(msg)
@@ -1518,20 +1523,23 @@ class TriangleMesh(eqx.Module):
1518
1523
  preserve: bool = False,
1519
1524
  *,
1520
1525
  by_masking: bool = False,
1526
+ sample_objects: bool = False,
1521
1527
  key: PRNGKeyArray,
1522
1528
  ) -> Self:
1523
1529
  """
1524
- Generate a new mesh by randomly sampling triangles from this geometry.
1530
+ Generate a new mesh by randomly sampling primitives from this geometry.
1525
1531
 
1526
- Warning:
1527
- If :attr:`assume_quads` is :data:`True`, then quadrilaterals are
1528
- sampled.
1532
+ Important:
1533
+ If ``by_masking`` is set to :data:`True`, then this function is compatible
1534
+ with :func:`jax.jit`. Conversely, if ``by_masking`` is set to :data:`False`,
1535
+ then this function is **not** compatible with :func:`jax.jit`,
1536
+ as the size of the output mesh is not known at compile time.
1529
1537
 
1530
1538
  Args:
1531
- size: The size of the sample, i.e., the number of triangles.
1539
+ size: The size of the sample, i.e., the number of primitives (or objects, if ``sample_objects`` is :data:`True`).
1532
1540
 
1533
1541
  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
1542
+ i.e., the fraction of primitives to sample from the mesh. This is only supported
1535
1543
  if ``by_masking`` is set to :data:`True`.
1536
1544
  replace: Whether to sample with or without replacement.
1537
1545
 
@@ -1546,8 +1554,11 @@ class TriangleMesh(eqx.Module):
1546
1554
  is :data:`None`.
1547
1555
 
1548
1556
  Cannot be used with ``by_masking`` set to :data:`True`.
1549
- by_masking: Whether to sample by masking the triangles.
1557
+ by_masking: Whether to sample by masking the primitives.
1550
1558
  If :data:`True`, then the :attr:`mask` attribute set (ignoring any existing mask).
1559
+ sample_objects: Whether to sample by objects, i.e., sampling whole objects at once.
1560
+ The value of ``size`` is interpreted as the number of objects to sample,
1561
+ or the fill factor of objects to sample.
1551
1562
  key: The :func:`jax.random.key` to be used.
1552
1563
 
1553
1564
  Returns:
@@ -1556,35 +1567,56 @@ class TriangleMesh(eqx.Module):
1556
1567
  Raises:
1557
1568
  TypeError: If ``by_masking`` is :data:`False` and ``size`` is not an integer.
1558
1569
  ValueError: If ``by_masking`` is :data:`True` and ``replace`` or ``preserve`` are set to :data:`True`.
1570
+ ValueError: If ``sample_objects`` is :data:`True` and :attr:`object_bounds` is :data:`None`.
1559
1571
  """
1572
+ if sample_objects:
1573
+ if self.object_bounds is None:
1574
+ msg = "Cannot sample by objects when 'object_bounds' is None."
1575
+ raise ValueError(msg)
1576
+ num = self.object_bounds.shape[0]
1577
+ else:
1578
+ num = self.num_primitives
1560
1579
  if by_masking:
1561
1580
  if replace:
1562
1581
  msg = "Cannot sample with replacement when 'by_masking' is True."
1563
1582
  raise ValueError(msg)
1564
- if preserve:
1565
- msg = "Cannot preserve 'object_bounds' when 'by_masking' is True."
1583
+ if preserve and not sample_objects:
1584
+ msg = "Cannot preserve 'object_bounds' when 'by_masking' is True and 'sample_objects' is False."
1566
1585
  raise ValueError(msg)
1567
1586
  if isinstance(size, int):
1568
- mask = jnp.zeros(self.num_objects, dtype=bool)
1587
+ mask = jnp.zeros(num, dtype=bool)
1569
1588
  mask = mask.at[:size].set(True)
1570
1589
  mask = jax.random.permutation(key, mask)
1571
1590
  else:
1572
- mask = jax.random.uniform(key, (self.num_objects,)) <= size
1573
-
1574
- if self.assume_quads:
1591
+ mask = jax.random.uniform(key, (num,)) <= size
1592
+
1593
+ if sample_objects:
1594
+ indices = jnp.arange(self.num_triangles)
1595
+ indices_inside_bounds = (
1596
+ self.object_bounds[:, 0] <= indices[:, None] # type: ignore[reportOptionalSubscript]
1597
+ ) & (indices[:, None] < self.object_bounds[:, 1]) # type: ignore[reportOptionalSubscript]
1598
+ triangle_indices = indices_inside_bounds.argmax(
1599
+ axis=1
1600
+ ) # Exactly one bound should be true for each triangle
1601
+ mask = jnp.take(
1602
+ mask,
1603
+ triangle_indices,
1604
+ indices_are_sorted=True, # Object bounds are sorted
1605
+ )
1606
+ elif self.assume_quads:
1575
1607
  mask = jnp.repeat(mask, 2)
1576
1608
 
1577
1609
  return eqx.tree_at(
1578
1610
  lambda m: (m.object_bounds, m.mask),
1579
1611
  self,
1580
- (None, mask),
1612
+ (self.object_bounds if preserve else None, mask),
1581
1613
  is_leaf=lambda x: x is None,
1582
1614
  )
1583
1615
 
1584
1616
  if isinstance(size, int):
1585
1617
  indices = jax.random.choice(
1586
1618
  key,
1587
- self.num_objects,
1619
+ num,
1588
1620
  shape=(size,),
1589
1621
  replace=replace,
1590
1622
  )
@@ -1592,6 +1624,11 @@ class TriangleMesh(eqx.Module):
1592
1624
  msg = "'size' must be an integer when 'by_masking' is False."
1593
1625
  raise TypeError(msg)
1594
1626
 
1627
+ if sample_objects:
1628
+ indices = jnp.concatenate([
1629
+ jnp.arange(self.object_bounds[i, 0], self.object_bounds[i, 1]) # type: ignore[reportOptionalSubscript]
1630
+ for i in indices
1631
+ ])
1595
1632
  if self.assume_quads:
1596
1633
  indices *= 2
1597
1634
 
@@ -1604,6 +1641,11 @@ class TriangleMesh(eqx.Module):
1604
1641
  ),
1605
1642
  axis=-1,
1606
1643
  )
1644
+ # Some object may not have any triangles left after sampling,
1645
+ # so we remove them.
1646
+ object_bounds = object_bounds.compress(
1647
+ object_bounds[:, 0] < object_bounds[:, 1], axis=0
1648
+ )
1607
1649
  else:
1608
1650
  object_bounds = None
1609
1651
 
@@ -99,10 +99,14 @@ def _(
99
99
 
100
100
  canvas, view = process_vispy_kwargs(kwargs)
101
101
 
102
+ if vertices.size == 0 or triangles.size == 0: # type: ignore[reportAttributeAccessIssue] # pragma: no cover
103
+ return canvas
104
+
102
105
  kwargs.setdefault("shading", "flat")
103
106
 
104
107
  vertices = np.asarray(vertices)
105
108
  triangles = np.asarray(triangles)
109
+
106
110
  view.add(Mesh(vertices=vertices, faces=triangles, **kwargs))
107
111
  view.camera.set_range()
108
112
 
@@ -202,6 +206,9 @@ def _(
202
206
 
203
207
  canvas, view = process_vispy_kwargs(kwargs)
204
208
 
209
+ if paths.size == 0: # type: ignore[reportAttributeAccessIssue] # pragma: no cover
210
+ return canvas
211
+
205
212
  kwargs.setdefault("width", 3.0)
206
213
  kwargs.setdefault("marker_size", 0.0)
207
214
  paths = np.asarray(paths)
@@ -211,7 +218,6 @@ def _(
211
218
  connect[path_length - 1 :: path_length] = False
212
219
 
213
220
  view.add(LinePlot(data=paths, connect=connect, **kwargs)) # type: ignore[reportArgumentType]
214
-
215
221
  view.camera.set_range()
216
222
 
217
223
  return canvas
@@ -353,6 +359,9 @@ def _(
353
359
 
354
360
  canvas, view = process_vispy_kwargs(kwargs)
355
361
 
362
+ if ray_origins.size == 0 or ray_directions.size == 0: # type: ignore[reportAttributeAccessIssue] # pragma: no cover
363
+ return canvas
364
+
356
365
  kwargs.setdefault("width", 3.0)
357
366
  kwargs.setdefault("arrow_size", 6.0)
358
367
 
@@ -370,7 +379,6 @@ def _(
370
379
  arrows = np.concatenate((body_ends, arrows_center), axis=-1)
371
380
 
372
381
  view.add(Arrow(pos=pos, connect=connect, arrows=arrows, **kwargs)) # type: ignore[reportArgumentType]
373
-
374
382
  view.camera.set_range()
375
383
 
376
384
  return canvas
@@ -512,6 +520,10 @@ def _(
512
520
  from vispy.scene.visuals import Markers, Text # noqa: PLC0415
513
521
 
514
522
  canvas, view = process_vispy_kwargs(kwargs)
523
+
524
+ if markers.size == 0: # type: ignore[reportAttributeAccessIssue] # pragma: no cover
525
+ return canvas
526
+
515
527
  kwargs.setdefault("size", 1)
516
528
  kwargs.setdefault("edge_width_rel", 0.05)
517
529
  kwargs.setdefault("scaling", "scene")
@@ -734,7 +746,7 @@ def _(
734
746
 
735
747
 
736
748
  @dispatch
737
- def draw_contour( # noqa: PLR0917
749
+ def draw_contour(
738
750
  data: Real[ArrayLike, "rows cols"],
739
751
  x: Real[ArrayLike, " cols"] | Real[ArrayLike, "rows cols 3"] | None = None,
740
752
  y: Real[ArrayLike, " rows"] | Real[ArrayLike, "rows cols 3"] | None = None,
@@ -796,7 +808,7 @@ def draw_contour( # noqa: PLR0917
796
808
 
797
809
 
798
810
  @draw_contour.register("vispy")
799
- def _( # noqa: PLR0917
811
+ def _(
800
812
  data: Real[ArrayLike, "rows cols"],
801
813
  x: Real[ArrayLike, " cols"] | Real[ArrayLike, "rows cols"] | None = None,
802
814
  y: Real[ArrayLike, " rows"] | Real[ArrayLike, "rows cols"] | None = None,
@@ -861,7 +873,7 @@ def _( # noqa: PLR0917
861
873
 
862
874
 
863
875
  @draw_contour.register("matplotlib")
864
- def _( # noqa: PLR0917
876
+ def _(
865
877
  data: Real[ArrayLike, "rows cols"],
866
878
  x: Real[ArrayLike, " cols"] | Real[ArrayLike, "rows cols"] | None = None,
867
879
  y: Real[ArrayLike, " rows"] | Real[ArrayLike, "rows cols"] | None = None,
@@ -891,7 +903,7 @@ def _( # noqa: PLR0917
891
903
 
892
904
 
893
905
  @draw_contour.register("plotly")
894
- def _( # noqa: PLR0917
906
+ def _(
895
907
  data: Real[ArrayLike, "rows cols"],
896
908
  x: Real[ArrayLike, " cols"] | Real[ArrayLike, "rows cols"] | None = None,
897
909
  y: Real[ArrayLike, " rows"] | Real[ArrayLike, "rows cols"] | None = None,
@@ -271,7 +271,7 @@ class DeepMIMO(eqx.Module, Generic[ArrayType]):
271
271
  return output
272
272
 
273
273
 
274
- def export( # noqa: PLR0915
274
+ def export(
275
275
  *,
276
276
  paths: Paths | Iterable[Paths],
277
277
  scene: TriangleScene,
@@ -1,4 +1,3 @@
1
- from functools import partial
2
1
  from typing import Any, no_type_check
3
2
 
4
3
  import chex
@@ -11,7 +10,6 @@ from jaxtyping import Array, ArrayLike, Float
11
10
  from differt.geometry import orthogonal_basis
12
11
 
13
12
 
14
- @partial(jax.jit, inline=True)
15
13
  def _param_to_xyz(
16
14
  p: Float[Array, "*batch num_object_x_num_dims"],
17
15
  o: Float[Array, "*#batch num_objects 3"],
@@ -22,7 +20,6 @@ def _param_to_xyz(
22
20
  return o + jnp.sum(p * v, axis=-2)
23
21
 
24
22
 
25
- @partial(jax.jit, inline=True)
26
23
  def _loss(
27
24
  p: Float[Array, "*batch num_object_x_num_dims"],
28
25
  from_: Float[Array, "*#batch 3"],
@@ -45,6 +42,47 @@ def _loss(
45
42
  )
46
43
 
47
44
 
45
+ def _fermat_path_on_linear_objects(
46
+ from_vertex: Float[Array, "3"],
47
+ to_vertex: Float[Array, "3"],
48
+ object_origins: Float[Array, "num_objects 3"],
49
+ object_vectors: Float[Array, "num_objects num_dims 3"],
50
+ steps: int,
51
+ optimizer: optax.GradientTransformationExtraArgs,
52
+ ) -> Float[Array, "num_objects 3"]:
53
+ dtype = jnp.result_type(from_vertex, to_vertex, object_origins, object_vectors)
54
+ x_0 = jnp.zeros(object_vectors.shape[0] * object_vectors.shape[1], dtype=dtype)
55
+ opt_state = optimizer.init(x_0)
56
+ value_and_grad = optax.value_and_grad_from_state(_loss)
57
+
58
+ @no_type_check
59
+ def update(
60
+ state: tuple[Float[Array, " num_unknowns"], Any],
61
+ _: None,
62
+ ) -> tuple[tuple[Float[Array, " num_unknowns"], Any], float | Float[Array, " "]]:
63
+ x, opt_state = state
64
+ loss_value, grad = value_and_grad(
65
+ x, from_vertex, to_vertex, object_origins, object_vectors, state=opt_state
66
+ )
67
+ updates, opt_state = optimizer.update(
68
+ grad,
69
+ opt_state,
70
+ x,
71
+ value=loss_value,
72
+ grad=grad,
73
+ value_fn=_loss,
74
+ from_=from_vertex,
75
+ to=to_vertex,
76
+ o=object_origins,
77
+ v=object_vectors,
78
+ )
79
+ x = optax.apply_updates(x, updates)
80
+ return (x, opt_state), loss_value
81
+
82
+ (x, _), _ = jax.lax.scan(update, (x_0, opt_state), length=steps)
83
+ return _param_to_xyz(x, object_origins, object_vectors)
84
+
85
+
48
86
  @eqx.filter_jit
49
87
  def fermat_path_on_linear_objects(
50
88
  from_vertices: Float[ArrayLike, "*#batch 3"],
@@ -176,90 +214,31 @@ def fermat_path_on_linear_objects(
176
214
  object_origins = jnp.asarray(object_origins)
177
215
  object_vectors = jnp.asarray(object_vectors)
178
216
 
179
- batch = jnp.broadcast_shapes(
180
- from_vertices.shape[:-1],
181
- to_vertices.shape[:-1],
182
- object_origins.shape[:-2],
183
- object_vectors.shape[:-3],
184
- )
185
-
186
- num_objects = object_origins.shape[-2]
187
-
188
- if num_objects == 0:
217
+ if (num_objects := object_origins.shape[-2]) == 0 or (
218
+ object_vectors.shape[-2] == 0
219
+ ):
189
220
  # If there are no objects, return empty paths.
190
- dtype = jnp.result_type(
191
- from_vertices, to_vertices, object_origins, object_vectors
221
+ # If there are no dimensions, return origins.
222
+ batch = jnp.broadcast_shapes(
223
+ from_vertices.shape[:-1],
224
+ to_vertices.shape[:-1],
225
+ object_origins.shape[:-2],
226
+ object_vectors.shape[:-3],
192
227
  )
193
- return jnp.empty((*batch, 0, 3), dtype=dtype)
194
-
195
- num_dims = object_vectors.shape[-2]
196
-
197
- if num_dims == 0:
198
- # If there are no dimension, return origins.
199
228
  dtype = jnp.result_type(
200
229
  from_vertices, to_vertices, object_origins, object_vectors
201
230
  )
231
+ if num_objects == 0:
232
+ return jnp.empty((*batch, 0, 3), dtype=dtype)
202
233
  return jnp.broadcast_to(object_origins, (*batch, num_objects, 3)).astype(dtype)
203
234
 
204
- num_unknowns = num_objects * num_dims
205
-
206
- objective = _loss
207
-
208
235
  optimizer = optimizer if optimizer is not None else optax.lbfgs()
209
236
 
210
- def minimize(
211
- x_0: Float[Array, " num_unknowns"],
212
- from_: Float[Array, "3"],
213
- to: Float[Array, "3"],
214
- o: Float[Array, "num_objects 3"],
215
- v: Float[Array, "num_objects num_dims 3"],
216
- ) -> Float[Array, "num_objects 3"]:
217
- opt_state = optimizer.init(x_0)
218
-
219
- value_and_grad = optax.value_and_grad_from_state(objective)
220
-
221
- @no_type_check
222
- def update(
223
- state: tuple[Float[Array, "*batch num_unknowns"], Any],
224
- _: None,
225
- ) -> tuple[
226
- tuple[Float[Array, "*batch num_unknowns"], Any], float | Float[Array, " "]
227
- ]:
228
- x, opt_state = state
229
- loss_value, grad = value_and_grad(x, from_, to, o, v, state=opt_state)
230
- updates, opt_state = optimizer.update(
231
- grad,
232
- opt_state,
233
- x,
234
- value=loss_value,
235
- grad=grad,
236
- value_fn=objective,
237
- from_=from_,
238
- to=to,
239
- o=o,
240
- v=v,
241
- )
242
- x = optax.apply_updates(x, updates)
243
- return (x, opt_state), loss_value
244
-
245
- (x, _), _ = jax.lax.scan(update, (x_0, opt_state), length=steps)
246
- return _param_to_xyz(x, o, v)
247
-
248
- x_0 = jnp.zeros((*batch, num_unknowns))
249
-
250
- for i in reversed(range(len(batch))):
251
- minimize = jax.vmap(
252
- minimize,
253
- in_axes=(
254
- 0,
255
- 0 if from_vertices.ndim > i + 1 else None,
256
- 0 if to_vertices.ndim > i + 1 else None,
257
- 0 if object_origins.ndim > i + 2 else None,
258
- 0 if object_vectors.ndim > i + 3 else None,
259
- ),
260
- )
261
-
262
- return minimize(x_0, from_vertices, to_vertices, object_origins, object_vectors)
237
+ return jnp.vectorize(
238
+ _fermat_path_on_linear_objects,
239
+ excluded={4, 5},
240
+ signature="(3),(3),(n,3),(n,d,3)->(n,3)",
241
+ )(from_vertices, to_vertices, object_origins, object_vectors, steps, optimizer)
263
242
 
264
243
 
265
244
  @eqx.filter_jit