differt 0.0.21__tar.gz → 0.0.22__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 (27) hide show
  1. {differt-0.0.21 → differt-0.0.22}/PKG-INFO +2 -2
  2. {differt-0.0.21 → differt-0.0.22}/pyproject.toml +1 -1
  3. {differt-0.0.21 → differt-0.0.22}/src/differt/geometry/paths.py +25 -26
  4. {differt-0.0.21 → differt-0.0.22}/src/differt/geometry/triangle_mesh.py +197 -34
  5. {differt-0.0.21 → differt-0.0.22}/src/differt/geometry/utils.py +52 -18
  6. {differt-0.0.21 → differt-0.0.22}/src/differt/plotting/__init__.py +6 -6
  7. {differt-0.0.21 → differt-0.0.22}/src/differt/plotting/_core.py +267 -86
  8. {differt-0.0.21 → differt-0.0.22}/src/differt/plotting/_utils.py +2 -2
  9. {differt-0.0.21 → differt-0.0.22}/src/differt/rt/utils.py +4 -4
  10. {differt-0.0.21 → differt-0.0.22}/src/differt/scene/triangle_scene.py +145 -18
  11. {differt-0.0.21 → differt-0.0.22}/src/differt/utils.py +25 -7
  12. {differt-0.0.21 → differt-0.0.22}/.gitignore +0 -0
  13. {differt-0.0.21 → differt-0.0.22}/LICENSE.md +0 -0
  14. {differt-0.0.21 → differt-0.0.22}/README.md +0 -0
  15. {differt-0.0.21 → differt-0.0.22}/src/differt/__init__.py +0 -0
  16. {differt-0.0.21 → differt-0.0.22}/src/differt/em/__init__.py +0 -0
  17. {differt-0.0.21 → differt-0.0.22}/src/differt/em/constants.py +0 -0
  18. {differt-0.0.21 → differt-0.0.22}/src/differt/em/special.py +0 -0
  19. {differt-0.0.21 → differt-0.0.22}/src/differt/em/utd.py +0 -0
  20. {differt-0.0.21 → differt-0.0.22}/src/differt/em/utils.py +0 -0
  21. {differt-0.0.21 → differt-0.0.22}/src/differt/geometry/__init__.py +0 -0
  22. {differt-0.0.21 → differt-0.0.22}/src/differt/rt/__init__.py +0 -0
  23. {differt-0.0.21 → differt-0.0.22}/src/differt/rt/fermat.py +0 -0
  24. {differt-0.0.21 → differt-0.0.22}/src/differt/rt/image_method.py +0 -0
  25. {differt-0.0.21 → differt-0.0.22}/src/differt/scene/__init__.py +0 -0
  26. {differt-0.0.21 → differt-0.0.22}/src/differt/scene/sionna.py +0 -0
  27. {differt-0.0.21 → differt-0.0.22}/src/differt/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: DiffeRT
3
- Version: 0.0.21
3
+ Version: 0.0.22
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: Topic :: Scientific/Engineering
21
21
  Requires-Python: >=3.10
22
22
  Requires-Dist: beartype>=0.17.2
23
23
  Requires-Dist: chex>=0.1.86
24
- Requires-Dist: differt-core==0.0.21
24
+ Requires-Dist: differt-core==0.0.22
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
  dependencies = [
17
17
  "beartype>=0.17.2",
18
18
  "chex>=0.1.86",
19
- "differt-core==0.0.21",
19
+ "differt-core==0.0.22",
20
20
  "equinox>=0.11.5",
21
21
  "filelock>=3.15.4",
22
22
  "jax>=0.4.32",
@@ -7,11 +7,10 @@ from typing import Any
7
7
  import equinox as eqx
8
8
  import jax
9
9
  import jax.numpy as jnp
10
- import numpy as np
11
10
  from beartype import beartype as typechecker
12
11
  from jaxtyping import Array, ArrayLike, Bool, Float, Int, Shaped, jaxtyped
13
12
 
14
- from differt.plotting import draw_paths
13
+ from differt.plotting import PlotOutput, draw_paths
15
14
 
16
15
  if sys.version_info >= (3, 11):
17
16
  from typing import Self
@@ -21,7 +20,7 @@ else:
21
20
 
22
21
  @jax.jit
23
22
  @jaxtyped(typechecker=typechecker)
24
- def _cluster_ids(array: Shaped[Array, "batch n"]) -> Int[Array, " batch"]:
23
+ def _cell_ids(array: Shaped[Array, "batch n"]) -> Int[Array, " batch"]:
25
24
  @jaxtyped(typechecker=typechecker)
26
25
  def scan_fun(
27
26
  indices: Int[Array, " batch"],
@@ -41,15 +40,15 @@ def _cluster_ids(array: Shaped[Array, "batch n"]) -> Int[Array, " batch"]:
41
40
 
42
41
  @jax.jit
43
42
  @jaxtyped(typechecker=typechecker)
44
- def merge_cluster_ids(
45
- cluster_ids_a: Int[Array, " *batch"],
46
- cluster_ids_b: Int[Array, " *batch"],
43
+ def merge_cell_ids(
44
+ cell_ids_a: Int[Array, " *batch"],
45
+ cell_ids_b: Int[Array, " *batch"],
47
46
  ) -> Int[Array, " *batch"]:
48
47
  """
49
- Merge two arrays of cluster indices as returned by :meth:`Paths.multipath_clusters`.
48
+ Merge two arrays of cell indices as returned by :meth:`Paths.multipath_cells`.
50
49
 
51
- Let the returned array be ``cluster_ids``,
52
- then ``cluster_ids[i] == cluster_ids[j]`` for all ``i``,
50
+ Let the returned array be ``cell_ids``,
51
+ then ``cell_ids[i] == cell_ids[j]`` for all ``i``,
53
52
  ``j`` indices if
54
53
  ``(groups_a[i], groups_b[i]) == (groups_a[j], groups_b[j])``,
55
54
  granted that arrays have been reshaped to uni-dimensional
@@ -61,15 +60,15 @@ def merge_cluster_ids(
61
60
  do with the ones used in individual arrays.
62
61
 
63
62
  Args:
64
- cluster_ids_a: The first array of cluster indices.
65
- cluster_ids_b: The second array of cluster indices.
63
+ cell_ids_a: The first array of cell indices.
64
+ cell_ids_b: The second array of cell indices.
66
65
 
67
66
  Returns:
68
67
  The new array group indices.
69
68
  """
70
- batch = cluster_ids_a.shape
71
- return _cluster_ids(
72
- jnp.stack((cluster_ids_a, cluster_ids_b), axis=-1).reshape(-1, 2),
69
+ batch = cell_ids_a.shape
70
+ return _cell_ids(
71
+ jnp.stack((cell_ids_a, cell_ids_b), axis=-1).reshape(-1, 2),
73
72
  ).reshape(batch)
74
73
 
75
74
 
@@ -134,7 +133,7 @@ class Paths(eqx.Module):
134
133
  @property
135
134
  @jax.jit
136
135
  @jaxtyped(typechecker=typechecker)
137
- def num_valid_paths(self) -> Int[ArrayLike, ""]:
136
+ def num_valid_paths(self) -> Int[ArrayLike, " "]:
138
137
  """The number of paths kept by :attr:`mask`.
139
138
 
140
139
  If :attr:`mask` is not :data:`None`, then the output value can be traced by JAX.
@@ -176,15 +175,15 @@ class Paths(eqx.Module):
176
175
 
177
176
  @eqx.filter_jit
178
177
  @jaxtyped(typechecker=typechecker)
179
- def multipath_clusters(
178
+ def multipath_cells(
180
179
  self,
181
180
  axis: int = -1,
182
181
  ) -> Int[Array, " *partial_batch"]:
183
182
  """
184
- Return an array of same multipath cluster indices.
183
+ Return an array of same multipath cell indices.
185
184
 
186
- Let the returned array be ``cluster_ids``,
187
- then ``cluster_ids[i] == cluster_ids[j]`` for all ``i``,
185
+ Let the returned array be ``cell_ids``,
186
+ then ``cell_ids[i] == cell_ids[j]`` for all ``i``,
188
187
  ``j`` indices if ``self.mask[i, :] == self.mask[j, :]``,
189
188
  granted that each array has been reshaped to a two-dimensional
190
189
  array and that ``axis`` is the last dimension. Of course, this
@@ -210,7 +209,7 @@ class Paths(eqx.Module):
210
209
 
211
210
  By default, the last axis is used to match the
212
211
  ``num_path_candidates`` axis as returned by
213
- :meth:`TriangleScene.compute_paths<differt.scene.triangle_scene.TriangleScene.compute_paths`.
212
+ :meth:`TriangleScene.compute_paths<differt.scene.triangle_scene.TriangleScene.compute_paths>`.
214
213
 
215
214
  Returns:
216
215
  The array of group indices.
@@ -219,13 +218,13 @@ class Paths(eqx.Module):
219
218
  ValueError: If :attr:`mask` is None.
220
219
  """
221
220
  if self.mask is None:
222
- msg = "Cannot create multiplath clusters from non-existing mask!"
221
+ msg = "Cannot create multiplath cells from non-existing mask!"
223
222
  raise ValueError(msg)
224
223
 
225
224
  mask = jnp.moveaxis(self.mask, axis, -1)
226
225
  *partial_batch, last_axis = mask.shape
227
226
 
228
- return _cluster_ids(mask.reshape(-1, last_axis)).reshape(partial_batch)
227
+ return _cell_ids(mask.reshape(-1, last_axis)).reshape(partial_batch)
229
228
 
230
229
  @jax.jit
231
230
  @jaxtyped(typechecker=typechecker)
@@ -237,7 +236,7 @@ class Paths(eqx.Module):
237
236
  undergo the same types of interactions.
238
237
 
239
238
  Internally, it uses the same logic as
240
- :meth:`multipath_clusters`, but applied to object indices
239
+ :meth:`multipath_cells`, but applied to object indices
241
240
  rather than on mask.
242
241
 
243
242
  Returns:
@@ -278,7 +277,7 @@ class Paths(eqx.Module):
278
277
  *batch, path_length = self.objects.shape
279
278
 
280
279
  objects = self.objects.reshape((-1, path_length))
281
- return _cluster_ids(objects).reshape(batch)
280
+ return _cell_ids(objects).reshape(batch)
282
281
 
283
282
  def __iter__(self) -> Iterator[Self]:
284
283
  """Return an iterator over masked paths.
@@ -311,7 +310,7 @@ class Paths(eqx.Module):
311
310
  """
312
311
  return jnp.sum(fun(self.vertices), where=self.mask)
313
312
 
314
- def plot(self, **kwargs: Any) -> Any:
313
+ def plot(self, **kwargs: Any) -> PlotOutput:
315
314
  """
316
315
  Plot the (masked) paths on a 3D scene.
317
316
 
@@ -322,4 +321,4 @@ class Paths(eqx.Module):
322
321
  Returns:
323
322
  The resulting plot output.
324
323
  """
325
- return draw_paths(np.asarray(self.masked_vertices), **kwargs)
324
+ return draw_paths(self.masked_vertices, **kwargs)
@@ -2,17 +2,16 @@
2
2
  # ruff: noqa: ERA001
3
3
 
4
4
  import sys
5
- from typing import Any
5
+ from typing import Any, Literal, overload
6
6
 
7
7
  import equinox as eqx
8
8
  import jax
9
9
  import jax.numpy as jnp
10
- import numpy as np
11
10
  from beartype import beartype as typechecker
12
11
  from jaxtyping import Array, ArrayLike, Bool, Float, Int, PRNGKeyArray, jaxtyped
13
12
 
14
13
  import differt_core.geometry.triangle_mesh
15
- from differt.plotting import draw_mesh
14
+ from differt.plotting import PlotOutput, draw_mesh
16
15
 
17
16
  from .utils import normalize, orthogonal_basis, rotation_matrix_along_axis
18
17
 
@@ -105,7 +104,7 @@ class TriangleMesh(eqx.Module):
105
104
  """The array of face materials.
106
105
 
107
106
  The array contains the material indices,
108
- with a special placeholder value of :data:`-1`.
107
+ with a special placeholder value of ``-1``.
109
108
  The obtain the name of the material, see :attr:`material_names`.
110
109
  This attribute is :data:`None` if all face materials are unset.
111
110
  """
@@ -137,7 +136,7 @@ class TriangleMesh(eqx.Module):
137
136
  @jaxtyped(
138
137
  typechecker=None
139
138
  ) # typing.Self is (currently) not compatible with jaxtyping and beartype
140
- def __getitem__(self, key: slice | Int[ArrayLike, "*batch"]) -> Self:
139
+ def __getitem__(self, key: slice | Int[ArrayLike, " n"]) -> Self:
141
140
  """Return a copy of this mesh, taking only specific triangles.
142
141
 
143
142
  Warning:
@@ -188,19 +187,42 @@ class TriangleMesh(eqx.Module):
188
187
 
189
188
  return self.triangles.shape[0] // 2
190
189
 
190
+ @property
191
+ def num_objects(self) -> int:
192
+ """The number of objects.
193
+
194
+ This is a convenient alias to :attr:`num_quads` :attr:`assume_quads` is :data:`True`
195
+ else :attr:`num_triangles`.
196
+ """
197
+ return self.num_quads if self.assume_quads else self.num_triangles
198
+
191
199
  @property
192
200
  @jax.jit
193
201
  @jaxtyped(typechecker=typechecker)
194
202
  def triangle_vertices(self) -> Float[Array, "{self.num_triangles} 3 3"]:
195
- """The array of indexed triangle vertices.
196
-
197
- TODO: improve description.
198
- """
203
+ """The array of indexed triangle vertices."""
199
204
  if self.triangles.size == 0:
200
205
  return jnp.empty_like(self.vertices, shape=(0, 3, 3))
201
206
 
202
207
  return jnp.take(self.vertices, self.triangles, axis=0)
203
208
 
209
+ def set_assume_quads(self, flag: bool = True) -> Self:
210
+ """
211
+ Return a copy of this mesh with :attr:`assume_quads` set to ``flag``.
212
+
213
+ Unlike with using :func:`equinox.tree_at`, this function will also
214
+ perform runtime checks.
215
+
216
+ Args:
217
+ flag: The new flag value.
218
+
219
+ Returns:
220
+ A new mesh.
221
+ """
222
+ mesh = eqx.tree_at(lambda m: m.assume_quads, self, flag)
223
+ mesh.__check_init__()
224
+ return mesh
225
+
204
226
  @classmethod
205
227
  def from_core(
206
228
  cls, core_mesh: differt_core.geometry.triangle_mesh.TriangleMesh
@@ -254,6 +276,66 @@ class TriangleMesh(eqx.Module):
254
276
  (jnp.min(vertices, axis=0), jnp.max(vertices, axis=0)),
255
277
  )
256
278
 
279
+ @eqx.filter_jit
280
+ @jaxtyped(
281
+ typechecker=None
282
+ ) # typing.Self is (currently) not compatible with jaxtyping and beartype
283
+ def rotate(self, rotation_matrix: Float[Array, "3 3"]) -> Self:
284
+ """
285
+ Return a new mesh by applying a rotation matrix to all triangle coordinates.
286
+
287
+ Args:
288
+ rotation_matrix: The rotation matrix.
289
+
290
+ Returns:
291
+ The new rotated mesh.
292
+ """
293
+ return eqx.tree_at(
294
+ lambda m: m.vertices,
295
+ self,
296
+ (rotation_matrix @ self.vertices.T).T,
297
+ )
298
+
299
+ @eqx.filter_jit
300
+ @jaxtyped(
301
+ typechecker=None
302
+ ) # typing.Self is (currently) not compatible with jaxtyping and beartype
303
+ def scale(self, scale_factor: Float[ArrayLike, " "]) -> Self:
304
+ """
305
+ Return a new mesh by applying a scale factor to all triangle coordinates.
306
+
307
+ Args:
308
+ scale_factor: The scate factor.
309
+
310
+ Returns:
311
+ The new scaled mesh.
312
+ """
313
+ return eqx.tree_at(
314
+ lambda m: m.vertices,
315
+ self,
316
+ self.vertices * scale_factor,
317
+ )
318
+
319
+ @eqx.filter_jit
320
+ @jaxtyped(
321
+ typechecker=None
322
+ ) # typing.Self is (currently) not compatible with jaxtyping and beartype
323
+ def translate(self, translation: Float[Array, "3"]) -> Self:
324
+ """
325
+ Return a new mesh by applying a translation to all triangle coordinates.
326
+
327
+ Args:
328
+ translation: The translation vector.
329
+
330
+ Returns:
331
+ The new translated mesh.
332
+ """
333
+ return eqx.tree_at(
334
+ lambda m: m.vertices,
335
+ self,
336
+ self.vertices + translation,
337
+ )
338
+
257
339
  @classmethod
258
340
  def empty(cls) -> Self:
259
341
  """
@@ -290,14 +372,42 @@ class TriangleMesh(eqx.Module):
290
372
  is_leaf=lambda x: x is None,
291
373
  )
292
374
 
375
+ @overload
376
+ @classmethod
377
+ def plane(
378
+ cls,
379
+ vertex_a: Float[Array, "3"],
380
+ vertex_b: Float[Array, "3"],
381
+ vertex_c: Float[Array, "3"],
382
+ *,
383
+ normal: Literal[None] = None,
384
+ side_length: Float[ArrayLike, " "] = 1.0,
385
+ rotate: Float[ArrayLike, " "] | None = None,
386
+ ) -> Self: ...
387
+
388
+ @overload
389
+ @classmethod
390
+ def plane(
391
+ cls,
392
+ vertex_a: Float[Array, "3"],
393
+ vertex_b: Literal[None] = None,
394
+ vertex_c: Literal[None] = None,
395
+ *,
396
+ normal: Float[Array, "3"],
397
+ side_length: Float[ArrayLike, " "] = 1.0,
398
+ rotate: Float[ArrayLike, " "] | None = None,
399
+ ) -> Self: ...
400
+
293
401
  @classmethod
294
402
  @jaxtyped(
295
403
  typechecker=None
296
404
  ) # typing.Self is (currently) not compatible with jaxtyping and beartype
297
405
  def plane(
298
406
  cls,
299
- vertex: Float[Array, "3"],
300
- *other_vertices: Float[Array, "3"],
407
+ vertex_a: Float[Array, "3"],
408
+ vertex_b: Float[Array, "3"] | None = None,
409
+ vertex_c: Float[Array, "3"] | None = None,
410
+ *,
301
411
  normal: Float[Array, "3"] | None = None,
302
412
  side_length: Float[ArrayLike, " "] = 1.0,
303
413
  rotate: Float[ArrayLike, " "] | None = None,
@@ -306,10 +416,13 @@ class TriangleMesh(eqx.Module):
306
416
  Create an plane mesh, made of two triangles.
307
417
 
308
418
  Args:
309
- vertex: The center of the plane.
310
- other_vertices: Two other vertices that define the plane.
419
+ vertex_a: The center of the plane.
420
+ vertex_b: Any second vertex on the plane.
421
+
422
+ This and ``vertex_c``, or ``normal`` is required.
423
+ vertex_c: Any third vertex on the plane.
311
424
 
312
- This or ``normal`` is required.
425
+ This and ``vertex_b``, or ``normal`` is required.
313
426
  normal: The plane normal.
314
427
 
315
428
  Must be of unit length.
@@ -322,23 +435,22 @@ class TriangleMesh(eqx.Module):
322
435
  A new plane mesh.
323
436
 
324
437
  Raises:
325
- ValueError: If neither ``other_vertices`` nor ``normal`` has been provided,
438
+ ValueError: If neither ``vertex_b`` and ``vertex_c``, nor ``normal`` have been provided,
326
439
  or if both have been provided simultaneously.
327
440
  """
328
- if (other_vertices == ()) == (normal is None):
329
- msg = "You must specify one of 'other_vertices' or 'normal', not both."
441
+ if (vertex_b is None) != (vertex_c is None):
442
+ msg = "You must specify either of both of 'vertex_b' and 'vertex_c', or none."
330
443
  raise ValueError(msg)
331
- if other_vertices:
332
- if len(other_vertices) != 2: # noqa: PLR2004
333
- msg = (
334
- "You must provide exactly 3 vertices to create a new plane, "
335
- f"but you provided {len(other_vertices) + 1}."
336
- )
337
- raise ValueError(msg)
338
- u = other_vertices[0] - vertex
339
- v = other_vertices[1] - vertex
444
+
445
+ if (vertex_b is None) == (normal is None):
446
+ msg = "You must specify one of ('vertex_b', 'vertex_c') or 'normal', not both."
447
+ raise ValueError(msg)
448
+
449
+ if vertex_b is not None:
450
+ u = vertex_b - vertex_a
451
+ v = vertex_c - vertex_a
340
452
  w = jnp.cross(u, v)
341
- (normal, _) = normalize(w)
453
+ normal = normalize(w)[0]
342
454
 
343
455
  u, v = orthogonal_basis(
344
456
  normal, # type: ignore[reportArgumentType]
@@ -353,7 +465,7 @@ class TriangleMesh(eqx.Module):
353
465
  rotation_matrix = rotation_matrix_along_axis(rotate, normal)
354
466
  vertices = (rotation_matrix @ vertices.T).T
355
467
 
356
- vertices += vertex
468
+ vertices += vertex_a
357
469
 
358
470
  triangles = jnp.array([[0, 1, 2], [0, 2, 3]], dtype=int)
359
471
  return cls(vertices=vertices, triangles=triangles)
@@ -397,7 +509,7 @@ class TriangleMesh(eqx.Module):
397
509
  core_mesh = differt_core.geometry.triangle_mesh.TriangleMesh.load_ply(file)
398
510
  return cls.from_core(core_mesh)
399
511
 
400
- def plot(self, **kwargs: Any) -> Any:
512
+ def plot(self, **kwargs: Any) -> PlotOutput:
401
513
  """
402
514
  Plot this mesh on a 3D scene.
403
515
 
@@ -409,11 +521,11 @@ class TriangleMesh(eqx.Module):
409
521
  The resulting plot output.
410
522
  """
411
523
  if "face_colors" not in kwargs and self.face_colors is not None:
412
- kwargs["face_colors"] = np.asarray(self.face_colors)
524
+ kwargs["face_colors"] = self.face_colors
413
525
 
414
526
  return draw_mesh(
415
- vertices=np.asarray(self.vertices),
416
- triangles=np.asarray(self.triangles),
527
+ vertices=self.vertices,
528
+ triangles=self.triangles,
417
529
  **kwargs,
418
530
  )
419
531
 
@@ -425,15 +537,28 @@ class TriangleMesh(eqx.Module):
425
537
  self,
426
538
  size: int,
427
539
  replace: bool = False,
540
+ preserve: bool = False,
428
541
  *,
429
542
  key: PRNGKeyArray,
430
543
  ) -> Self:
431
544
  """
432
545
  Generate a new mesh by randomly sampling triangles from this geometry.
433
546
 
547
+ Warning:
548
+ If :attr:`assume_quads` is :data:`True`, then quadrilaterals are
549
+ sampled.
550
+
434
551
  Args:
435
552
  size: The size of the sample, i.e., the number of triangles.
436
553
  replace: Whether to sample with or without replacement.
554
+ preserve: Whether to preserve :attr:`object_bounds`, otherwise
555
+ it is discarded.
556
+
557
+ Object bounds are re-generated by sorting the randomly generated samples,
558
+ which takes additional time.
559
+
560
+ Setting this to :data:`True` has no effect if :attr:`object_bounds`
561
+ is :data:`None`.
437
562
  key: The :func:`jax.random.key` to be used.
438
563
 
439
564
  Returns:
@@ -441,8 +566,46 @@ class TriangleMesh(eqx.Module):
441
566
  """
442
567
  indices = jax.random.choice(
443
568
  key,
444
- self.num_triangles,
569
+ self.num_objects,
445
570
  shape=(size,),
446
571
  replace=replace,
447
572
  )
448
- return self[indices]
573
+
574
+ if self.assume_quads:
575
+ indices *= 2
576
+
577
+ if preserve and self.object_bounds is not None:
578
+ indices = jnp.sort(indices)
579
+ object_bounds = jnp.stack(
580
+ (
581
+ jnp.searchsorted(indices, self.object_bounds[:, 0]),
582
+ jnp.searchsorted(indices, self.object_bounds[:, 1]),
583
+ ),
584
+ axis=-1,
585
+ )
586
+ else:
587
+ object_bounds = None
588
+
589
+ if self.assume_quads:
590
+ indices = jnp.stack((indices, indices + 1), axis=-1).reshape(-1)
591
+
592
+ return eqx.tree_at(
593
+ lambda m: (
594
+ m.vertices,
595
+ m.triangles,
596
+ m.face_colors,
597
+ m.face_materials,
598
+ m.object_bounds,
599
+ ),
600
+ self,
601
+ (
602
+ self.vertices,
603
+ self.triangles[indices, :],
604
+ self.face_colors[indices, :] if self.face_colors is not None else None,
605
+ self.face_materials[indices]
606
+ if self.face_materials is not None
607
+ else None,
608
+ object_bounds,
609
+ ),
610
+ is_leaf=lambda x: x is None,
611
+ )
@@ -1,5 +1,7 @@
1
1
  """Utilities for working with 3D geometries."""
2
2
 
3
+ from typing import Literal, overload
4
+
3
5
  import equinox as eqx
4
6
  import jax
5
7
  import jax.numpy as jnp
@@ -26,11 +28,41 @@ def pairwise_cross(
26
28
  return jnp.cross(u[:, None, :], v[None, :, :])
27
29
 
28
30
 
29
- @jax.jit
31
+ @overload
32
+ def normalize(
33
+ vector: Float[Array, "*batch 3"],
34
+ keepdims: Literal[False] = False,
35
+ ) -> tuple[Float[Array, "*batch 3"], Float[Array, " *batch"]]: ...
36
+
37
+
38
+ @overload
39
+ def normalize(
40
+ vector: Float[Array, "*batch 3"],
41
+ keepdims: Literal[True],
42
+ ) -> tuple[Float[Array, "*batch 3"], Float[Array, " *batch 1"]]: ...
43
+
44
+
45
+ # Workaround currently needed,
46
+ # see: https://github.com/microsoft/pyright/issues/9149
47
+ @overload
48
+ def normalize(
49
+ vector: Float[Array, "*batch 3"],
50
+ keepdims: bool,
51
+ ) -> (
52
+ tuple[Float[Array, "*batch 3"], Float[Array, " *batch"]]
53
+ | tuple[Float[Array, "*batch 3"], Float[Array, " *batch 1"]]
54
+ ): ...
55
+
56
+
57
+ @eqx.filter_jit
30
58
  @jaxtyped(typechecker=typechecker)
31
59
  def normalize(
32
60
  vector: Float[Array, "*batch 3"],
33
- ) -> tuple[Float[Array, "*batch 3"], Float[Array, " *batch"]]:
61
+ keepdims: bool = False,
62
+ ) -> (
63
+ tuple[Float[Array, "*batch 3"], Float[Array, " *batch"]]
64
+ | tuple[Float[Array, "*batch 3"], Float[Array, " *batch 1"]]
65
+ ):
34
66
  """
35
67
  Normalize vectors and also return their length.
36
68
 
@@ -39,6 +71,8 @@ def normalize(
39
71
 
40
72
  Args:
41
73
  vector: An array of vectors.
74
+ keepdims: If set to :data:`True`, the array of lengths
75
+ will have the same number of dimensions are the input.
42
76
 
43
77
  Returns:
44
78
  The normalized vector and their length.
@@ -62,7 +96,7 @@ def normalize(
62
96
  length: Array = jnp.linalg.norm(vector, axis=-1, keepdims=True)
63
97
  length = jnp.where(length == 0.0, jnp.ones_like(length), length)
64
98
 
65
- return vector / length, jnp.squeeze(length, axis=-1)
99
+ return vector / length, (length if keepdims else jnp.squeeze(length, axis=-1))
66
100
 
67
101
 
68
102
  @eqx.filter_jit
@@ -351,7 +385,7 @@ def fibonacci_lattice(
351
385
  ... )
352
386
  >>> from differt.plotting import draw_markers
353
387
  >>>
354
- >>> xyz = np.asarray(fibonacci_lattice(100))
388
+ >>> xyz = fibonacci_lattice(100)
355
389
  >>> fig = draw_markers(xyz, marker={"color": xyz[:, 0]}, backend="plotly")
356
390
  >>> fig # doctest: +SKIP
357
391
  """
@@ -405,19 +439,19 @@ def assemble_paths(
405
439
 
406
440
  @jax.jit
407
441
  @jaxtyped(typechecker=typechecker)
408
- def min_distance_between_clusters(
409
- cluster_vertices: Float[Array, "*batch 3"],
410
- cluster_ids: Int[Array, "*batch"],
442
+ def min_distance_between_cells(
443
+ cell_vertices: Float[Array, "*batch 3"],
444
+ cell_ids: Int[Array, "*batch"],
411
445
  ) -> Float[Array, "*batch"]:
412
446
  """
413
- Compute the minimal (Euclidean) distance between vertices in different clusters.
447
+ Compute the minimal (Euclidean) distance between vertices in different cells.
414
448
 
415
449
  For every vertex, the minimum distance to another vertex that is not is the same
416
- cluster is computed.
450
+ cell is computed.
417
451
 
418
452
  Args:
419
- cluster_vertices: The array of vertex coordinates.
420
- cluster_ids: The array of corresponding cluster indices.
453
+ cell_vertices: The array of vertex coordinates.
454
+ cell_ids: The array of corresponding cell indices.
421
455
 
422
456
  Returns:
423
457
  The array of minimal distances.
@@ -425,16 +459,16 @@ def min_distance_between_clusters(
425
459
 
426
460
  @jaxtyped(typechecker=typechecker)
427
461
  def scan_fun(
428
- _: None, vertex_and_cluster_id: tuple[Float[Array, "3"], Int[Array, " "]]
462
+ _: None, vertex_and_cell_id: tuple[Float[Array, "3"], Int[Array, " "]]
429
463
  ) -> tuple[None, Float[Array, " "]]:
430
- vertex, cluster_id = vertex_and_cluster_id
464
+ vertex, cell_id = vertex_and_cell_id
431
465
  min_dist = jnp.min(
432
466
  jnp.linalg.norm(
433
- cluster_vertices - vertex,
467
+ cell_vertices - vertex,
434
468
  axis=-1,
435
469
  ),
436
470
  initial=jnp.inf,
437
- where=(cluster_id != cluster_ids),
471
+ where=(cell_id != cell_ids),
438
472
  )
439
473
  return None, min_dist
440
474
 
@@ -442,7 +476,7 @@ def min_distance_between_clusters(
442
476
  scan_fun,
443
477
  init=None,
444
478
  xs=(
445
- cluster_vertices.reshape(-1, 3),
446
- cluster_ids.reshape(-1),
479
+ cell_vertices.reshape(-1, 3),
480
+ cell_ids.reshape(-1),
447
481
  ),
448
- )[1].reshape(cluster_ids.shape)
482
+ )[1].reshape(cell_ids.shape)