differt 0.0.20__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.20 → differt-0.0.22}/PKG-INFO +9 -4
  2. {differt-0.0.20 → differt-0.0.22}/pyproject.toml +1 -1
  3. {differt-0.0.20 → differt-0.0.22}/src/differt/geometry/paths.py +26 -27
  4. {differt-0.0.20 → differt-0.0.22}/src/differt/geometry/triangle_mesh.py +226 -35
  5. {differt-0.0.20 → differt-0.0.22}/src/differt/geometry/utils.py +52 -18
  6. {differt-0.0.20 → differt-0.0.22}/src/differt/plotting/__init__.py +6 -6
  7. {differt-0.0.20 → differt-0.0.22}/src/differt/plotting/_core.py +269 -84
  8. {differt-0.0.20 → differt-0.0.22}/src/differt/plotting/_utils.py +11 -5
  9. {differt-0.0.20 → differt-0.0.22}/src/differt/rt/image_method.py +5 -2
  10. {differt-0.0.20 → differt-0.0.22}/src/differt/rt/utils.py +19 -9
  11. {differt-0.0.20 → differt-0.0.22}/src/differt/scene/triangle_scene.py +263 -41
  12. {differt-0.0.20 → differt-0.0.22}/src/differt/utils.py +42 -19
  13. {differt-0.0.20 → differt-0.0.22}/.gitignore +0 -0
  14. {differt-0.0.20 → differt-0.0.22}/LICENSE.md +0 -0
  15. {differt-0.0.20 → differt-0.0.22}/README.md +0 -0
  16. {differt-0.0.20 → differt-0.0.22}/src/differt/__init__.py +0 -0
  17. {differt-0.0.20 → differt-0.0.22}/src/differt/em/__init__.py +0 -0
  18. {differt-0.0.20 → differt-0.0.22}/src/differt/em/constants.py +0 -0
  19. {differt-0.0.20 → differt-0.0.22}/src/differt/em/special.py +0 -0
  20. {differt-0.0.20 → differt-0.0.22}/src/differt/em/utd.py +0 -0
  21. {differt-0.0.20 → differt-0.0.22}/src/differt/em/utils.py +0 -0
  22. {differt-0.0.20 → differt-0.0.22}/src/differt/geometry/__init__.py +0 -0
  23. {differt-0.0.20 → differt-0.0.22}/src/differt/rt/__init__.py +0 -0
  24. {differt-0.0.20 → differt-0.0.22}/src/differt/rt/fermat.py +0 -0
  25. {differt-0.0.20 → differt-0.0.22}/src/differt/scene/__init__.py +0 -0
  26. {differt-0.0.20 → differt-0.0.22}/src/differt/scene/sionna.py +0 -0
  27. {differt-0.0.20 → 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.20
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.20
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
@@ -180,12 +180,17 @@ or benchmark it:
180
180
  pytest --benchmark-enable differt/tests/benchmarks
181
181
  ```
182
182
 
183
+ ## Citing
184
+
185
+ If you use this software, please cite it as
186
+ [detailed here](https://differt.readthedocs.io/latest/citing.html).
187
+
183
188
  [pypi-version-badge]: https://img.shields.io/pypi/v/DiffeRT?label=DiffeRT&color=blueviolet
184
189
  [pypi-version-url]: https://pypi.org/project/DiffeRT/
185
190
  [pypi-python-version-badge]: https://img.shields.io/pypi/pyversions/DiffeRT?color=orange
186
191
  [documentation-badge]: https://readthedocs.org/projects/differt/badge/?version=latest
187
192
  [documentation-url]: https://differt.readthedocs.io/latest/?badge=latest
188
- [doi-badge]: https://zenodo.org/badge/DOI/10.5281/zenodo.11386432.svg
189
- [doi-url]: https://doi.org/10.5281/zenodo.11386432
193
+ [doi-badge]: https://zenodo.org/badge/DOI/10.5281/zenodo.13895021.svg
194
+ [doi-url]: https://doi.org/10.5281/zenodo.13895021
190
195
  [codecov-badge]: https://codecov.io/gh/jeertmans/DiffeRT/branch/main/graph/badge.svg?token=v63alnTWzu
191
196
  [codecov-url]: https://codecov.io/gh/jeertmans/DiffeRT
@@ -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.20",
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:
@@ -251,7 +250,7 @@ class Paths(eqx.Module):
251
250
 
252
251
  >>> from differt.geometry.paths import Paths
253
252
  >>>
254
- >>> key = jax.random.PRNGKey(1234)
253
+ >>> key = jax.random.key(1234)
255
254
  >>> key_v, key_o = jax.random.split(key, 2)
256
255
  >>> *batch, path_length = (2, 6, 3)
257
256
  >>> vertices = jax.random.uniform(key_v, (*batch, path_length, 3))
@@ -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
  """
@@ -121,11 +120,23 @@ class TriangleMesh(eqx.Module):
121
120
  If the present mesh contains multiple objects, usually as a result of appending
122
121
  multiple meshes together, this array contain start end end indices for each sub mesh.
123
122
  """
123
+ assume_quads: bool = eqx.field(default=False)
124
+ """Flag indicating whether triangles can be paired into quadrilaterals.
125
+
126
+ Setting this to :data:`True` will not check anything, except that
127
+ :attr:`num_triangles` should is even, but each two consecutive
128
+ triangles are assumed to represent a quadrilateral surface.
129
+ """
130
+
131
+ def __check_init__(self) -> None: # noqa: D105,PLW3201
132
+ if self.assume_quads and (self.triangles.shape[0] % 2) != 0:
133
+ msg = "You cannot set 'assume_quads' to 'True' if the number of triangles is not even!"
134
+ raise ValueError(msg)
124
135
 
125
136
  @jaxtyped(
126
137
  typechecker=None
127
138
  ) # typing.Self is (currently) not compatible with jaxtyping and beartype
128
- def __getitem__(self, key: slice | Int[ArrayLike, "*batch"]) -> Self:
139
+ def __getitem__(self, key: slice | Int[ArrayLike, " n"]) -> Self:
129
140
  """Return a copy of this mesh, taking only specific triangles.
130
141
 
131
142
  Warning:
@@ -163,16 +174,55 @@ class TriangleMesh(eqx.Module):
163
174
  """The number of triangles."""
164
175
  return self.triangles.shape[0]
165
176
 
177
+ @property
178
+ def num_quads(self) -> int:
179
+ """The number of quadrilaterals.
180
+
181
+ Raises:
182
+ ValueError: If :attr:`assume_quads` is :data:`False`.
183
+ """
184
+ if not self.assume_quads:
185
+ msg = "Cannot access the number of quadrilaterals if 'assume_quads' is set to 'False'."
186
+ raise ValueError(msg)
187
+
188
+ return self.triangles.shape[0] // 2
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
+
166
199
  @property
167
200
  @jax.jit
168
201
  @jaxtyped(typechecker=typechecker)
169
202
  def triangle_vertices(self) -> Float[Array, "{self.num_triangles} 3 3"]:
170
- """The array of indexed triangle vertices.
203
+ """The array of indexed triangle vertices."""
204
+ if self.triangles.size == 0:
205
+ return jnp.empty_like(self.vertices, shape=(0, 3, 3))
171
206
 
172
- TODO: improve description.
173
- """
174
207
  return jnp.take(self.vertices, self.triangles, axis=0)
175
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
+
176
226
  @classmethod
177
227
  def from_core(
178
228
  cls, core_mesh: differt_core.geometry.triangle_mesh.TriangleMesh
@@ -226,6 +276,66 @@ class TriangleMesh(eqx.Module):
226
276
  (jnp.min(vertices, axis=0), jnp.max(vertices, axis=0)),
227
277
  )
228
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
+
229
339
  @classmethod
230
340
  def empty(cls) -> Self:
231
341
  """
@@ -262,14 +372,42 @@ class TriangleMesh(eqx.Module):
262
372
  is_leaf=lambda x: x is None,
263
373
  )
264
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
+
265
401
  @classmethod
266
402
  @jaxtyped(
267
403
  typechecker=None
268
404
  ) # typing.Self is (currently) not compatible with jaxtyping and beartype
269
405
  def plane(
270
406
  cls,
271
- vertex: Float[Array, "3"],
272
- *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
+ *,
273
411
  normal: Float[Array, "3"] | None = None,
274
412
  side_length: Float[ArrayLike, " "] = 1.0,
275
413
  rotate: Float[ArrayLike, " "] | None = None,
@@ -278,10 +416,13 @@ class TriangleMesh(eqx.Module):
278
416
  Create an plane mesh, made of two triangles.
279
417
 
280
418
  Args:
281
- vertex: The center of the plane.
282
- 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.
283
424
 
284
- This or ``normal`` is required.
425
+ This and ``vertex_b``, or ``normal`` is required.
285
426
  normal: The plane normal.
286
427
 
287
428
  Must be of unit length.
@@ -294,23 +435,22 @@ class TriangleMesh(eqx.Module):
294
435
  A new plane mesh.
295
436
 
296
437
  Raises:
297
- ValueError: If one of two ``other_vertices`` or ``normal``
298
- were not provided.
438
+ ValueError: If neither ``vertex_b`` and ``vertex_c``, nor ``normal`` have been provided,
439
+ or if both have been provided simultaneously.
299
440
  """
300
- if (other_vertices == ()) == (normal is None):
301
- 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."
443
+ raise ValueError(msg)
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."
302
447
  raise ValueError(msg)
303
- if other_vertices:
304
- if len(other_vertices) != 2: # noqa: PLR2004
305
- msg = (
306
- "You must provide exactly 3 vertices to create a new plane, "
307
- f"but you provided {len(other_vertices) + 1}."
308
- )
309
- raise ValueError(msg)
310
- u = other_vertices[0] - vertex
311
- v = other_vertices[1] - vertex
448
+
449
+ if vertex_b is not None:
450
+ u = vertex_b - vertex_a
451
+ v = vertex_c - vertex_a
312
452
  w = jnp.cross(u, v)
313
- (normal, _) = normalize(w)
453
+ normal = normalize(w)[0]
314
454
 
315
455
  u, v = orthogonal_basis(
316
456
  normal, # type: ignore[reportArgumentType]
@@ -325,7 +465,7 @@ class TriangleMesh(eqx.Module):
325
465
  rotation_matrix = rotation_matrix_along_axis(rotate, normal)
326
466
  vertices = (rotation_matrix @ vertices.T).T
327
467
 
328
- vertices += vertex
468
+ vertices += vertex_a
329
469
 
330
470
  triangles = jnp.array([[0, 1, 2], [0, 2, 3]], dtype=int)
331
471
  return cls(vertices=vertices, triangles=triangles)
@@ -369,7 +509,7 @@ class TriangleMesh(eqx.Module):
369
509
  core_mesh = differt_core.geometry.triangle_mesh.TriangleMesh.load_ply(file)
370
510
  return cls.from_core(core_mesh)
371
511
 
372
- def plot(self, **kwargs: Any) -> Any:
512
+ def plot(self, **kwargs: Any) -> PlotOutput:
373
513
  """
374
514
  Plot this mesh on a 3D scene.
375
515
 
@@ -381,11 +521,11 @@ class TriangleMesh(eqx.Module):
381
521
  The resulting plot output.
382
522
  """
383
523
  if "face_colors" not in kwargs and self.face_colors is not None:
384
- kwargs["face_colors"] = np.asarray(self.face_colors)
524
+ kwargs["face_colors"] = self.face_colors
385
525
 
386
526
  return draw_mesh(
387
- vertices=np.asarray(self.vertices),
388
- triangles=np.asarray(self.triangles),
527
+ vertices=self.vertices,
528
+ triangles=self.triangles,
389
529
  **kwargs,
390
530
  )
391
531
 
@@ -397,24 +537,75 @@ class TriangleMesh(eqx.Module):
397
537
  self,
398
538
  size: int,
399
539
  replace: bool = False,
540
+ preserve: bool = False,
400
541
  *,
401
542
  key: PRNGKeyArray,
402
543
  ) -> Self:
403
544
  """
404
545
  Generate a new mesh by randomly sampling triangles from this geometry.
405
546
 
547
+ Warning:
548
+ If :attr:`assume_quads` is :data:`True`, then quadrilaterals are
549
+ sampled.
550
+
406
551
  Args:
407
552
  size: The size of the sample, i.e., the number of triangles.
408
553
  replace: Whether to sample with or without replacement.
409
- key: The :func:`jax.random.PRNGKey` to be used.
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`.
562
+ key: The :func:`jax.random.key` to be used.
410
563
 
411
564
  Returns:
412
565
  A new random mesh.
413
566
  """
414
567
  indices = jax.random.choice(
415
568
  key,
416
- self.num_triangles,
569
+ self.num_objects,
417
570
  shape=(size,),
418
571
  replace=replace,
419
572
  )
420
- 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
+ )