Skip to content

ordito.metrics

Chamfer and Hausdorff distances between point clouds and meshes.

All metrics are fully GPU-resident: they compose the nearest-neighbor and point-to-surface primitives in proximity with the tiled reductions in reduce, and never move per-element data to the host.

Chamfer distances reduce plain Euclidean distances by default, the usual definition of the metric. squared=True squares each distance before reducing instead, which is the pytorch3d convention (pytorch3d.loss.chamfer_distance) and the one to pass when comparing against it. Hausdorff distances follow libigl's igl::hausdorff and reduce the (already Euclidean) per-element distances with a maximum, so no squaring or final square root is needed.

One place the convention does not carry over, because the two libraries answer different questions: pytorch3d.loss.point_mesh_face_distance sums point-to-triangle with face-to-point, where chamfer_points_to_mesh's backward direction is mesh-vertex to nearest query. The forward halves agree, but the whole scalars differ by construction and are not comparable.

Two families of geometry are supported and can be mixed:

  • points_to_points -- both sides are point clouds (nearest neighbor via query_nearest).
  • points_to_mesh -- a point cloud versus a triangle mesh (point-to-surface via closest_point_on_mesh one way, mesh-vertex nearest neighbor the other way).
  • mesh_to_mesh -- both sides are triangle meshes (vertex-to-surface both directions).

Functions:

Name Description
chamfer_points_to_points

Chamfer distance between two point clouds.

chamfer_points_to_mesh

Chamfer distance between a point cloud and a triangle mesh.

chamfer_mesh_to_mesh

Chamfer distance between two triangle meshes (vertex-to-surface).

chamfer_points_to_points_loss

Differentiable Chamfer loss between two point clouds.

chamfer_points_to_mesh_loss

Differentiable Chamfer loss between a point cloud and a triangle mesh.

chamfer_mesh_to_mesh_loss

Differentiable Chamfer loss between two triangle meshes (vertex-to-surface).

hausdorff_points_to_points

Hausdorff distance between two point clouds.

hausdorff_points_to_mesh

Hausdorff distance between a point cloud and a triangle mesh.

hausdorff_mesh_to_mesh

Hausdorff distance between two triangle meshes.

chamfer_points_to_points

chamfer_points_to_points(
    x: array[vec3],
    y: array[vec3],
    *,
    point_reduction: _PointReduction = ...,
    single_directional: bool = ...,
    squared: bool = ...,
) -> float
chamfer_points_to_points(
    x: array[vec3],
    y: array[vec3],
    *,
    point_reduction: None,
    single_directional: Literal[True],
    squared: bool = ...,
) -> odt.Array1dFloat32
chamfer_points_to_points(
    x: array[vec3],
    y: array[vec3],
    *,
    point_reduction: None,
    single_directional: Literal[False] = ...,
    squared: bool = ...,
) -> tuple[odt.Array1dFloat32, odt.Array1dFloat32]
chamfer_points_to_points(
    x: array[vec3],
    y: array[vec3],
    *,
    point_reduction: None,
    single_directional: bool,
    squared: bool = ...,
) -> _UnreducedChamfer
chamfer_points_to_points(
    x: array[vec3],
    y: array[vec3],
    *,
    point_reduction: _PointReduction | None = "mean",
    single_directional: bool = False,
    squared: bool = False,
) -> float | _UnreducedChamfer

Chamfer distance between two point clouds.

For each point in x the Euclidean distance to its nearest neighbor in y is accumulated (and symmetrically for y into x unless single_directional). pytorch3d.loss.chamfer_distance is this call with squared=True; its single_directional keyword maps onto this one exactly.

Parameters:

Name Type Description Default
x array[vec3]

(n,) query point cloud.

required
y array[vec3]

(m,) target point cloud.

required
point_reduction _PointReduction | None

How to reduce the per-point distances of each direction: "mean" (default), "sum", "max", or None to return the per-point distances unreduced. "max" yields a directed Hausdorff-like value.

'mean'
single_directional bool

If True, only the x -> y term is computed.

False
squared bool

Square each distance before reducing, as pytorch3d does. Off by default: the result is then in squared units, and its "mean" is not a mean distance, which is easy to misread.

False

Returns:

Type Description
float or array[float32] or tuple

The reduced Chamfer distance as a Python float when point_reduction is not None. Otherwise the per-point distances: a single (n,) array when single_directional, else an ((n,), (m,)) tuple. Empty inputs yield 0.0 (reduced) or empty arrays.

Raises:

Type Description
RuntimeError

If x and y are not all on one device.

ValueError

If point_reduction is not "mean", "sum", "max" or None.

See Also

chamfer_points_to_mesh chamfer_mesh_to_mesh query_nearest

Examples:

The x -> y distances are [0, 1] and the y -> x ones [0, 3]; the symmetric value is the sum of the two means:

import warp as wp

import ordito as od

x = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=wp.vec3)
y = wp.array([[0.0, 0.0, 0.0], [0.0, 0.0, 3.0]], dtype=wp.vec3)
print(od.metrics.chamfer_points_to_points(x, y))  # 2.0
print(od.metrics.chamfer_points_to_points(x, y, single_directional=True))  # 0.5
print(od.metrics.chamfer_points_to_points(x, y, squared=True))  # 5.0
forward, backward = od.metrics.chamfer_points_to_points(x, y, point_reduction=None)
print(forward.numpy().tolist(), backward.numpy().tolist())  # [0.0, 1.0] [0.0, 3.0]
Source code in ordito/metrics.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def chamfer_points_to_points(
    x: wp.array[wp.vec3],
    y: wp.array[wp.vec3],
    *,
    point_reduction: _PointReduction | None = "mean",
    single_directional: bool = False,
    squared: bool = False,
) -> float | _UnreducedChamfer:
    """
    Chamfer distance between two point clouds.

    For each point in ``x`` the Euclidean distance to its nearest neighbor in ``y`` is
    accumulated (and symmetrically for ``y`` into ``x`` unless ``single_directional``).
    ``pytorch3d.loss.chamfer_distance`` is this call with ``squared=True``; its
    ``single_directional`` keyword maps onto this one exactly.

    Parameters
    ----------
    x
        ``(n,)`` query point cloud.
    y
        ``(m,)`` target point cloud.
    point_reduction
        How to reduce the per-point distances of each direction:
        ``"mean"`` (default), ``"sum"``, ``"max"``, or ``None`` to return the
        per-point distances unreduced. ``"max"`` yields a directed
        Hausdorff-like value.
    single_directional
        If ``True``, only the ``x -> y`` term is computed.
    squared
        Square each distance before reducing, as ``pytorch3d`` does. Off by default: the result
        is then in squared units, and its ``"mean"`` is not a mean distance, which is easy to
        misread.

    Returns
    -------
    float or wp.array[wp.float32] or tuple
        The reduced Chamfer distance as a Python ``float`` when ``point_reduction``
        is not ``None``. Otherwise the per-point distances: a single
        ``(n,)`` array when ``single_directional``, else an ``((n,), (m,))`` tuple.
        Empty inputs yield ``0.0`` (reduced) or empty arrays.

    Raises
    ------
    RuntimeError
        If ``x`` and ``y`` are not all on one device.
    ValueError
        If ``point_reduction`` is not ``"mean"``, ``"sum"``, ``"max"`` or ``None``.

    See Also
    --------
    [`chamfer_points_to_mesh`][ordito.metrics.chamfer_points_to_mesh]
    [`chamfer_mesh_to_mesh`][ordito.metrics.chamfer_mesh_to_mesh]
    [`query_nearest`][ordito.neighbors.query_nearest]

    Examples
    --------
    The ``x -> y`` distances are ``[0, 1]`` and the ``y -> x`` ones ``[0, 3]``; the symmetric value
    is the sum of the two means:

    ```python
    import warp as wp

    import ordito as od

    x = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=wp.vec3)
    y = wp.array([[0.0, 0.0, 0.0], [0.0, 0.0, 3.0]], dtype=wp.vec3)
    print(od.metrics.chamfer_points_to_points(x, y))  # 2.0
    print(od.metrics.chamfer_points_to_points(x, y, single_directional=True))  # 0.5
    print(od.metrics.chamfer_points_to_points(x, y, squared=True))  # 5.0
    forward, backward = od.metrics.chamfer_points_to_points(x, y, point_reduction=None)
    print(forward.numpy().tolist(), backward.numpy().tolist())  # [0.0, 1.0] [0.0, 3.0]
    ```
    """
    require_same_device(x=x, y=y)
    _validate_point_reduction(point_reduction)
    distances = _distances_points_to_points(x, y, single_directional)
    if distances is None:
        return _empty_chamfer(point_reduction, single_directional, x.device)
    return _chamfer(distances, point_reduction, single_directional, squared)

chamfer_points_to_mesh

chamfer_points_to_mesh(
    points: array[vec3],
    vertices: array[vec3],
    faces: array[int32],
    *,
    point_reduction: _PointReduction = ...,
    single_directional: bool = ...,
    squared: bool = ...,
    mesh: Mesh | None = ...,
) -> float
chamfer_points_to_mesh(
    points: array[vec3],
    vertices: array[vec3],
    faces: array[int32],
    *,
    point_reduction: None,
    single_directional: Literal[True],
    squared: bool = ...,
    mesh: Mesh | None = ...,
) -> odt.Array1dFloat32
chamfer_points_to_mesh(
    points: array[vec3],
    vertices: array[vec3],
    faces: array[int32],
    *,
    point_reduction: None,
    single_directional: Literal[False] = ...,
    squared: bool = ...,
    mesh: Mesh | None = ...,
) -> tuple[odt.Array1dFloat32, odt.Array1dFloat32]
chamfer_points_to_mesh(
    points: array[vec3],
    vertices: array[vec3],
    faces: array[int32],
    *,
    point_reduction: None,
    single_directional: bool,
    squared: bool = ...,
    mesh: Mesh | None = ...,
) -> _UnreducedChamfer
chamfer_points_to_mesh(
    points: array[vec3],
    vertices: array[vec3],
    faces: array[int32],
    *,
    point_reduction: _PointReduction | None = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh: Mesh | None = None,
) -> float | _UnreducedChamfer

Chamfer distance between a point cloud and a triangle mesh.

The forward term is the distance from each point to the mesh surface (exact, via closest_point_on_mesh); the backward term is the distance from each mesh vertex to its nearest point in the cloud.

Parameters:

Name Type Description Default
points array[vec3]

(n,) query point cloud.

required
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index array.

required
point_reduction _PointReduction | None

"mean" (default), "sum", "max", or None. See chamfer_points_to_points.

'mean'
single_directional bool

If True, only the points -> mesh surface term is computed.

False
squared bool

Square each distance before reducing, as pytorch3d does. Off by default: the result is then in squared units, and its "mean" is not a mean distance, which is easy to misread.

False
mesh Mesh | None

A wp.Mesh already built over vertices and faces, to spare the BVH build each call otherwise pays (worth it when one mesh is measured repeatedly). Not checked against vertices / faces: the answer is for the geometry mesh holds. Trimesh.warp_mesh is the cached one to pass.

None

Returns:

Type Description
float or array[float32] or tuple

Same layout as chamfer_points_to_points. The forward array is (n,) and the backward array (n_vertices,), except when points, vertices or faces is empty -- a mesh with no faces counts as empty here even when vertices is not, since there is no surface for the forward term to measure against -- in which case both arrays are length 0, matching chamfer_points_to_points's own convention.

Raises:

Type Description
RuntimeError

If points, vertices, faces and mesh are not all on one device.

ValueError

If point_reduction is not "mean", "sum", "max" or None.

See Also

chamfer_points_to_points chamfer_mesh_to_mesh closest_point_on_mesh

Examples:

A point 1.0 outside a unit cube and one at its centre, 0.5 from every face. The backward term adds the mean distance from the cube's corners to the cloud, sqrt(3) / 2:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
points = wp.array([[1.5, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=wp.vec3)
forward = od.metrics.chamfer_points_to_mesh(points, vertices, faces, single_directional=True)
print(forward)  # 0.75
print(f"{od.metrics.chamfer_points_to_mesh(points, vertices, faces):.4f}")  # 1.6160
Source code in ordito/metrics.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def chamfer_points_to_mesh(
    points: wp.array[wp.vec3],
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    point_reduction: _PointReduction | None = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh: wp.Mesh | None = None,
) -> float | _UnreducedChamfer:
    """
    Chamfer distance between a point cloud and a triangle mesh.

    The forward term is the distance from each point to the mesh surface
    (exact, via [`closest_point_on_mesh`][ordito.proximity.closest_point_on_mesh]);
    the backward term is the distance from each mesh vertex to its nearest
    point in the cloud.

    Parameters
    ----------
    points
        ``(n,)`` query point cloud.
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index array.
    point_reduction
        ``"mean"`` (default), ``"sum"``, ``"max"``, or ``None``. See
        [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points].
    single_directional
        If ``True``, only the ``points -> mesh surface`` term is computed.
    squared
        Square each distance before reducing, as ``pytorch3d`` does. Off by default: the result
        is then in squared units, and its ``"mean"`` is not a mean distance, which is easy to
        misread.
    mesh
        A ``wp.Mesh`` already built over ``vertices`` and ``faces``, to spare the BVH build each
        call otherwise pays (worth it when one mesh is measured repeatedly). Not checked against
        ``vertices`` / ``faces``: the answer is for the geometry ``mesh`` holds.
        [`Trimesh.warp_mesh`][ordito.mesh.Trimesh.warp_mesh] is the cached one to pass.

    Returns
    -------
    float or wp.array[wp.float32] or tuple
        Same layout as [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points].
        The forward array is ``(n,)`` and the backward array ``(n_vertices,)``, except when
        ``points``, ``vertices`` or ``faces`` is empty -- a mesh with no faces counts as empty here
        even when ``vertices`` is not, since there is no surface for the forward term to measure
        against -- in which case both arrays are length 0, matching
        [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points]'s own convention.

    Raises
    ------
    RuntimeError
        If ``points``, ``vertices``, ``faces`` and ``mesh`` are not all on one device.
    ValueError
        If ``point_reduction`` is not ``"mean"``, ``"sum"``, ``"max"`` or ``None``.

    See Also
    --------
    [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points]
    [`chamfer_mesh_to_mesh`][ordito.metrics.chamfer_mesh_to_mesh]
    [`closest_point_on_mesh`][ordito.proximity.closest_point_on_mesh]

    Examples
    --------
    A point ``1.0`` outside a unit cube and one at its centre, ``0.5`` from every face. The backward
    term adds the mean distance from the cube's corners to the cloud, ``sqrt(3) / 2``:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    points = wp.array([[1.5, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=wp.vec3)
    forward = od.metrics.chamfer_points_to_mesh(points, vertices, faces, single_directional=True)
    print(forward)  # 0.75
    print(f"{od.metrics.chamfer_points_to_mesh(points, vertices, faces):.4f}")  # 1.6160
    ```
    """
    require_same_device(points=points, vertices=vertices, faces=faces, mesh=mesh)
    _validate_point_reduction(point_reduction)
    distances = _distances_points_to_mesh(points, vertices, faces, single_directional, mesh)
    if distances is None:
        return _empty_chamfer(point_reduction, single_directional, points.device)
    return _chamfer(distances, point_reduction, single_directional, squared)

chamfer_mesh_to_mesh

chamfer_mesh_to_mesh(
    vertices_a: array[vec3],
    faces_a: array[int32],
    vertices_b: array[vec3],
    faces_b: array[int32],
    *,
    point_reduction: _PointReduction = ...,
    single_directional: bool = ...,
    squared: bool = ...,
    mesh_a: Mesh | None = ...,
    mesh_b: Mesh | None = ...,
) -> float
chamfer_mesh_to_mesh(
    vertices_a: array[vec3],
    faces_a: array[int32],
    vertices_b: array[vec3],
    faces_b: array[int32],
    *,
    point_reduction: None,
    single_directional: Literal[True],
    squared: bool = ...,
    mesh_a: Mesh | None = ...,
    mesh_b: Mesh | None = ...,
) -> odt.Array1dFloat32
chamfer_mesh_to_mesh(
    vertices_a: array[vec3],
    faces_a: array[int32],
    vertices_b: array[vec3],
    faces_b: array[int32],
    *,
    point_reduction: None,
    single_directional: Literal[False] = ...,
    squared: bool = ...,
    mesh_a: Mesh | None = ...,
    mesh_b: Mesh | None = ...,
) -> tuple[odt.Array1dFloat32, odt.Array1dFloat32]
chamfer_mesh_to_mesh(
    vertices_a: array[vec3],
    faces_a: array[int32],
    vertices_b: array[vec3],
    faces_b: array[int32],
    *,
    point_reduction: None,
    single_directional: bool,
    squared: bool = ...,
    mesh_a: Mesh | None = ...,
    mesh_b: Mesh | None = ...,
) -> _UnreducedChamfer
chamfer_mesh_to_mesh(
    vertices_a: array[vec3],
    faces_a: array[int32],
    vertices_b: array[vec3],
    faces_b: array[int32],
    *,
    point_reduction: _PointReduction | None = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh_a: Mesh | None = None,
    mesh_b: Mesh | None = None,
) -> float | _UnreducedChamfer

Chamfer distance between two triangle meshes (vertex-to-surface).

The forward term is the distance from each vertex of mesh A to the surface of mesh B; the backward term is the reverse. This mirrors the vertex-based approach of libigl while accumulating (mean/sum) instead of maximizing.

Parameters:

Name Type Description Default
vertices_a array[vec3]

(n_vertices_a,) vertices and (3 * n_faces_a,) flat faces of mesh A.

required
faces_a array[vec3]

(n_vertices_a,) vertices and (3 * n_faces_a,) flat faces of mesh A.

required
vertices_b array[vec3]

(n_vertices_b,) vertices and (3 * n_faces_b,) flat faces of mesh B.

required
faces_b array[vec3]

(n_vertices_b,) vertices and (3 * n_faces_b,) flat faces of mesh B.

required
point_reduction _PointReduction | None

"mean" (default), "sum", "max", or None. See chamfer_points_to_points.

'mean'
single_directional bool

If True, only the A -> surface(B) term is computed.

False
squared bool

Square each distance before reducing, as pytorch3d does. Off by default: the result is then in squared units, and its "mean" is not a mean distance, which is easy to misread.

False
mesh_a Mesh | None

wp.Mesh objects already built over mesh A and mesh B, to spare the BVH build each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly). Not checked against the arrays: the answer is for the geometry each holds. Trimesh.warp_mesh is the cached one to pass.

None
mesh_b Mesh | None

wp.Mesh objects already built over mesh A and mesh B, to spare the BVH build each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly). Not checked against the arrays: the answer is for the geometry each holds. Trimesh.warp_mesh is the cached one to pass.

None

Returns:

Type Description
float or array[float32] or tuple

Same layout as chamfer_points_to_points. The forward array is (n_vertices_a,) and the backward array (n_vertices_b,), except when any of vertices_a, faces_a, vertices_b or faces_b is empty -- a mesh with no faces counts as empty here even when its vertices are not -- in which case both arrays are length 0.

Raises:

Type Description
RuntimeError

If vertices_a, faces_a, vertices_b, faces_b, mesh_a and mesh_b are not all on one device.

ValueError

If point_reduction is not "mean", "sum", "max" or None.

See Also

chamfer_points_to_points chamfer_points_to_mesh hausdorff_mesh_to_mesh

Examples:

A unit cube inside a cube of side 2: each inner corner is 0.5 from the outer surface, each outer corner sqrt(3) / 2 from the inner one:

import ordito as od

vertices_a, faces_a = od.creation.box()
vertices_b, faces_b = od.creation.box(extents=(2.0, 2.0, 2.0))
forward = od.metrics.chamfer_mesh_to_mesh(
    vertices_a, faces_a, vertices_b, faces_b, single_directional=True
)
print(forward)  # 0.5
symmetric = od.metrics.chamfer_mesh_to_mesh(vertices_a, faces_a, vertices_b, faces_b)
print(f"{symmetric:.4f}")  # 1.3660
Source code in ordito/metrics.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def chamfer_mesh_to_mesh(
    vertices_a: wp.array[wp.vec3],
    faces_a: wp.array[wp.int32],
    vertices_b: wp.array[wp.vec3],
    faces_b: wp.array[wp.int32],
    *,
    point_reduction: _PointReduction | None = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh_a: wp.Mesh | None = None,
    mesh_b: wp.Mesh | None = None,
) -> float | _UnreducedChamfer:
    """
    Chamfer distance between two triangle meshes (vertex-to-surface).

    The forward term is the distance from each vertex of mesh ``A`` to the
    surface of mesh ``B``; the backward term is the reverse. This mirrors the
    vertex-based approach of libigl while accumulating (mean/sum) instead of maximizing.

    Parameters
    ----------
    vertices_a, faces_a
        ``(n_vertices_a,)`` vertices and ``(3 * n_faces_a,)`` flat faces of mesh ``A``.
    vertices_b, faces_b
        ``(n_vertices_b,)`` vertices and ``(3 * n_faces_b,)`` flat faces of mesh ``B``.
    point_reduction
        ``"mean"`` (default), ``"sum"``, ``"max"``, or ``None``. See
        [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points].
    single_directional
        If ``True``, only the ``A -> surface(B)`` term is computed.
    squared
        Square each distance before reducing, as ``pytorch3d`` does. Off by default: the result
        is then in squared units, and its ``"mean"`` is not a mean distance, which is easy to
        misread.
    mesh_a, mesh_b
        ``wp.Mesh`` objects already built over mesh ``A`` and mesh ``B``, to spare the BVH build
        each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly).
        Not checked against the arrays: the answer is for the geometry each holds.
        [`Trimesh.warp_mesh`][ordito.mesh.Trimesh.warp_mesh] is the cached one to pass.

    Returns
    -------
    float or wp.array[wp.float32] or tuple
        Same layout as [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points].
        The forward array is ``(n_vertices_a,)`` and the backward array ``(n_vertices_b,)``, except
        when any of ``vertices_a``, ``faces_a``, ``vertices_b`` or ``faces_b`` is empty -- a mesh
        with no faces counts as empty here even when its vertices are not -- in which case both
        arrays are length 0.

    Raises
    ------
    RuntimeError
        If ``vertices_a``, ``faces_a``, ``vertices_b``, ``faces_b``, ``mesh_a`` and ``mesh_b``
        are not all on one device.
    ValueError
        If ``point_reduction`` is not ``"mean"``, ``"sum"``, ``"max"`` or ``None``.

    See Also
    --------
    [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points]
    [`chamfer_points_to_mesh`][ordito.metrics.chamfer_points_to_mesh]
    [`hausdorff_mesh_to_mesh`][ordito.metrics.hausdorff_mesh_to_mesh]

    Examples
    --------
    A unit cube inside a cube of side 2: each inner corner is ``0.5`` from the outer surface, each
    outer corner ``sqrt(3) / 2`` from the inner one:

    ```python
    import ordito as od

    vertices_a, faces_a = od.creation.box()
    vertices_b, faces_b = od.creation.box(extents=(2.0, 2.0, 2.0))
    forward = od.metrics.chamfer_mesh_to_mesh(
        vertices_a, faces_a, vertices_b, faces_b, single_directional=True
    )
    print(forward)  # 0.5
    symmetric = od.metrics.chamfer_mesh_to_mesh(vertices_a, faces_a, vertices_b, faces_b)
    print(f"{symmetric:.4f}")  # 1.3660
    ```
    """
    require_same_device(
        vertices_a=vertices_a,
        faces_a=faces_a,
        vertices_b=vertices_b,
        faces_b=faces_b,
        mesh_a=mesh_a,
        mesh_b=mesh_b,
    )
    _validate_point_reduction(point_reduction)
    distances = _distances_mesh_to_mesh(
        vertices_a, faces_a, vertices_b, faces_b, single_directional, mesh_a, mesh_b
    )
    if distances is None:
        return _empty_chamfer(point_reduction, single_directional, vertices_a.device)
    return _chamfer(distances, point_reduction, single_directional, squared)

chamfer_points_to_points_loss

chamfer_points_to_points_loss(
    x: array[vec3],
    y: array[vec3],
    *,
    tape: Tape | None = None,
    point_reduction: _DiffReduction = "mean",
    single_directional: bool = False,
    squared: bool = False,
) -> wp.array[wp.float32]

Differentiable Chamfer loss between two point clouds.

Squared-distance analogue of chamfer_points_to_points that returns a length-1 wp.float32 device array instead of a host float, so the loss can be back-propagated to x and y through a caller-owned wp.Tape.

The nearest-neighbor assignment (via query_nearest) is computed outside tape and held constant during the backward pass, matching pytorch3d's chamfer_distance gradient.

Parameters:

Name Type Description Default
x array[vec3]

(n,) query point cloud. Set requires_grad=True for gradients.

required
y array[vec3]

(m,) target point cloud. Set requires_grad=True for gradients.

required
tape Tape | None

Caller-owned wp.Tape into which the differentiable kernels are recorded. When None the loss is still computed but no operations are taped (no gradient).

None
point_reduction _DiffReduction

"mean" (default) or "sum"; reduces the per-point distances of each direction. "max" and None are not supported (see chamfer_points_to_points).

'mean'
single_directional bool

If True, only the x -> y term is accumulated.

False
squared bool

Square each distance before reducing, as pytorch3d does. Off by default: the result is then in squared units, and its "mean" is not a mean distance, which is easy to misread.

False

Returns:

Type Description
array[float32]

(1,) device array holding the Chamfer loss (requires_grad=True). Empty inputs yield a length-1 zero array.

Raises:

Type Description
RuntimeError

If x and y are not all on one device.

ValueError

If point_reduction is not "mean" or "sum".

See Also

chamfer_points_to_points chamfer_points_to_mesh_loss chamfer_mesh_to_mesh_loss

Examples:

The point (1, 0, 0) is 1 from its nearest neighbour at the origin, so the mean loss is 0.5 and its gradient pushes it towards the origin with weight 1 / 2:

import warp as wp

import ordito as od

x = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=wp.vec3, requires_grad=True)
y = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 2.0]], dtype=wp.vec3)
tape = wp.Tape()
loss = od.metrics.chamfer_points_to_points_loss(x, y, tape=tape, single_directional=True)
tape.backward(loss=loss)
print(loss.numpy())  # [0.5]
print(x.grad.numpy()[1])  # [0.5 0.  0. ]
Source code in ordito/metrics.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def chamfer_points_to_points_loss(
    x: wp.array[wp.vec3],
    y: wp.array[wp.vec3],
    *,
    tape: wp.Tape | None = None,
    point_reduction: _DiffReduction = "mean",
    single_directional: bool = False,
    squared: bool = False,
) -> wp.array[wp.float32]:
    """
    Differentiable Chamfer loss between two point clouds.

    Squared-distance analogue of
    [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points] that returns
    a length-1 ``wp.float32`` device array instead of a host ``float``, so the loss can be
    back-propagated to ``x`` and ``y`` through a caller-owned ``wp.Tape``.

    The nearest-neighbor assignment (via
    [`query_nearest`][ordito.neighbors.query_nearest]) is computed
    outside ``tape`` and held constant during the backward pass, matching pytorch3d's
    ``chamfer_distance`` gradient.

    Parameters
    ----------
    x
        ``(n,)`` query point cloud. Set ``requires_grad=True`` for gradients.
    y
        ``(m,)`` target point cloud. Set ``requires_grad=True`` for gradients.
    tape
        Caller-owned ``wp.Tape`` into which the differentiable kernels are recorded. When
        ``None`` the loss is still computed but no operations are taped (no gradient).
    point_reduction
        ``"mean"`` (default) or ``"sum"``; reduces the per-point distances of each
        direction. ``"max"`` and ``None`` are not supported (see
        [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points]).
    single_directional
        If ``True``, only the ``x -> y`` term is accumulated.
    squared
        Square each distance before reducing, as ``pytorch3d`` does. Off by default: the result
        is then in squared units, and its ``"mean"`` is not a mean distance, which is easy to
        misread.

    Returns
    -------
    wp.array[wp.float32]
        ``(1,)`` device array holding the Chamfer loss (``requires_grad=True``). Empty
        inputs yield a length-1 zero array.

    Raises
    ------
    RuntimeError
        If ``x`` and ``y`` are not all on one device.
    ValueError
        If ``point_reduction`` is not ``"mean"`` or ``"sum"``.

    See Also
    --------
    [`chamfer_points_to_points`][ordito.metrics.chamfer_points_to_points]
    [`chamfer_points_to_mesh_loss`][ordito.metrics.chamfer_points_to_mesh_loss]
    [`chamfer_mesh_to_mesh_loss`][ordito.metrics.chamfer_mesh_to_mesh_loss]

    Examples
    --------
    The point ``(1, 0, 0)`` is 1 from its nearest neighbour at the origin, so the mean loss is
    ``0.5`` and its gradient pushes it towards the origin with weight ``1 / 2``:

    ```python
    import warp as wp

    import ordito as od

    x = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=wp.vec3, requires_grad=True)
    y = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 2.0]], dtype=wp.vec3)
    tape = wp.Tape()
    loss = od.metrics.chamfer_points_to_points_loss(x, y, tape=tape, single_directional=True)
    tape.backward(loss=loss)
    print(loss.numpy())  # [0.5]
    print(x.grad.numpy()[1])  # [0.5 0.  0. ]
    ```
    """
    require_same_device(x=x, y=y)
    _validate_diff_reduction(point_reduction)
    device = x.device
    n = x.size
    m = y.size
    loss = _zero_loss(device)
    if n == 0 or m == 0:
        return loss

    # Non-differentiable nearest-neighbor indices (computed outside the tape). The backward search
    # is chosen from the forward one's own distances -- see `_backward_nearest`.
    nearest_xy, distance_xy = _nearest(y, x)
    terms: list[_ChamferTerm] = [_NnTerm(x, y, nearest_xy, _reduction_scale(point_reduction, n))]
    if not single_directional:
        nearest_yx = _backward_nearest(x, y, distance_xy, nearest_xy)[0][0]
        terms.append(_NnTerm(y, x, nearest_yx, _reduction_scale(point_reduction, m)))

    _accumulate_chamfer_terms(tape, terms, loss, squared=squared)
    return loss

chamfer_points_to_mesh_loss

chamfer_points_to_mesh_loss(
    points: array[vec3],
    vertices: array[vec3],
    faces: array[int32],
    *,
    tape: Tape | None = None,
    point_reduction: _DiffReduction = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh: Mesh | None = None,
) -> wp.array[wp.float32]

Differentiable Chamfer loss between a point cloud and a triangle mesh.

Squared-distance analogue of chamfer_points_to_mesh. The forward term is the exact point-to-surface distance (closest triangle held constant during backprop); the backward term is the distance from each mesh vertex to its nearest point in the cloud. Gradients flow to points and vertices.

Parameters:

Name Type Description Default
points array[vec3]

(n,) query point cloud.

required
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index array.

required
tape Tape | None

Caller-owned wp.Tape for the backward pass, or None to skip taping.

None
point_reduction _DiffReduction

"mean" (default) or "sum".

'mean'
single_directional bool

If True, only the points -> mesh surface term is accumulated.

False
squared bool

Square each distance before reducing, as pytorch3d does. Off by default: the result is then in squared units, and its "mean" is not a mean distance, which is easy to misread.

False
mesh Mesh | None

A wp.Mesh already built over vertices and faces, to spare the BVH build each call otherwise pays (worth it when one mesh is measured repeatedly). Not checked against vertices / faces: the answer is for the geometry mesh holds. Trimesh.warp_mesh is the cached one to pass.

None

Returns:

Type Description
array[float32]

(1,) device array holding the Chamfer loss (requires_grad=True).

Raises:

Type Description
RuntimeError

If points, vertices, faces and mesh are not all on one device.

ValueError

If point_reduction is not "mean" or "sum".

See Also

chamfer_points_to_mesh chamfer_points_to_points_loss chamfer_mesh_to_mesh_loss

Examples:

A point 1.0 outside the x = 0.5 face of a unit cube; the gradient of its distance points away from the face:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
points = wp.array([[1.5, 0.1, 0.2]], dtype=wp.vec3, requires_grad=True)
tape = wp.Tape()
loss = od.metrics.chamfer_points_to_mesh_loss(
    points, vertices, faces, tape=tape, single_directional=True
)
tape.backward(loss=loss)
print(loss.numpy())  # [1.]
print(points.grad.numpy()[0])  # [1. 0. 0.]
Source code in ordito/metrics.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
def chamfer_points_to_mesh_loss(
    points: wp.array[wp.vec3],
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    tape: wp.Tape | None = None,
    point_reduction: _DiffReduction = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh: wp.Mesh | None = None,
) -> wp.array[wp.float32]:
    """
    Differentiable Chamfer loss between a point cloud and a triangle mesh.

    Squared-distance analogue of
    [`chamfer_points_to_mesh`][ordito.metrics.chamfer_points_to_mesh]. The forward term
    is the exact point-to-surface distance (closest triangle held constant during
    backprop); the backward term is the distance from each mesh vertex to its
    nearest point in the cloud. Gradients flow to ``points`` **and** ``vertices``.

    Parameters
    ----------
    points
        ``(n,)`` query point cloud.
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index array.
    tape
        Caller-owned ``wp.Tape`` for the backward pass, or ``None`` to skip taping.
    point_reduction
        ``"mean"`` (default) or ``"sum"``.
    single_directional
        If ``True``, only the ``points -> mesh surface`` term is accumulated.
    squared
        Square each distance before reducing, as ``pytorch3d`` does. Off by default: the result
        is then in squared units, and its ``"mean"`` is not a mean distance, which is easy to
        misread.
    mesh
        A ``wp.Mesh`` already built over ``vertices`` and ``faces``, to spare the BVH build each
        call otherwise pays (worth it when one mesh is measured repeatedly). Not checked against
        ``vertices`` / ``faces``: the answer is for the geometry ``mesh`` holds.
        [`Trimesh.warp_mesh`][ordito.mesh.Trimesh.warp_mesh] is the cached one to pass.

    Returns
    -------
    wp.array[wp.float32]
        ``(1,)`` device array holding the Chamfer loss (``requires_grad=True``).

    Raises
    ------
    RuntimeError
        If ``points``, ``vertices``, ``faces`` and ``mesh`` are not all on one device.
    ValueError
        If ``point_reduction`` is not ``"mean"`` or ``"sum"``.

    See Also
    --------
    [`chamfer_points_to_mesh`][ordito.metrics.chamfer_points_to_mesh]
    [`chamfer_points_to_points_loss`][ordito.metrics.chamfer_points_to_points_loss]
    [`chamfer_mesh_to_mesh_loss`][ordito.metrics.chamfer_mesh_to_mesh_loss]

    Examples
    --------
    A point ``1.0`` outside the ``x = 0.5`` face of a unit cube; the gradient of its distance points
    away from the face:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    points = wp.array([[1.5, 0.1, 0.2]], dtype=wp.vec3, requires_grad=True)
    tape = wp.Tape()
    loss = od.metrics.chamfer_points_to_mesh_loss(
        points, vertices, faces, tape=tape, single_directional=True
    )
    tape.backward(loss=loss)
    print(loss.numpy())  # [1.]
    print(points.grad.numpy()[0])  # [1. 0. 0.]
    ```
    """
    require_same_device(points=points, vertices=vertices, faces=faces, mesh=mesh)
    _validate_diff_reduction(point_reduction)
    device = points.device
    n = points.size
    v = vertices.size
    n_faces = faces.size // 3
    loss = _zero_loss(device)
    if n == 0 or v == 0 or n_faces == 0:
        return loss

    # Non-differentiable closest-face and nearest-neighbor assignment (outside the tape). The
    # backward search is chosen from the forward one's own distances -- see `_backward_nearest`.
    distance_forward, face_id = _closest_on_mesh(points, vertices, faces, mesh)
    terms: list[_ChamferTerm] = [
        _SurfaceTerm(points, vertices, faces, face_id, _reduction_scale(point_reduction, n))
    ]
    if not single_directional:
        nearest_vp = _backward_nearest(points, vertices, distance_forward, face_id, faces)[0][0]
        terms.append(_NnTerm(vertices, points, nearest_vp, _reduction_scale(point_reduction, v)))

    _accumulate_chamfer_terms(tape, terms, loss, squared=squared)
    return loss

chamfer_mesh_to_mesh_loss

chamfer_mesh_to_mesh_loss(
    vertices_a: array[vec3],
    faces_a: array[int32],
    vertices_b: array[vec3],
    faces_b: array[int32],
    *,
    tape: Tape | None = None,
    point_reduction: _DiffReduction = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh_a: Mesh | None = None,
    mesh_b: Mesh | None = None,
) -> wp.array[wp.float32]

Differentiable Chamfer loss between two triangle meshes (vertex-to-surface).

Squared-distance analogue of chamfer_mesh_to_mesh. The forward term is the distance from each vertex of mesh A to the surface of mesh B (with the closest triangle held constant during backprop); the backward term is the reverse. Gradients flow to both meshes' vertices.

Parameters:

Name Type Description Default
vertices_a array[vec3]

(n_vertices_a,) vertices and (3 * n_faces_a,) flat faces of mesh A.

required
faces_a array[vec3]

(n_vertices_a,) vertices and (3 * n_faces_a,) flat faces of mesh A.

required
vertices_b array[vec3]

(n_vertices_b,) vertices and (3 * n_faces_b,) flat faces of mesh B.

required
faces_b array[vec3]

(n_vertices_b,) vertices and (3 * n_faces_b,) flat faces of mesh B.

required
tape Tape | None

Caller-owned wp.Tape for the backward pass, or None to skip taping.

None
point_reduction _DiffReduction

"mean" (default) or "sum".

'mean'
single_directional bool

If True, only the A -> surface(B) term is accumulated.

False
squared bool

Square each distance before reducing, as pytorch3d does. Off by default: the result is then in squared units, and its "mean" is not a mean distance, which is easy to misread.

False
mesh_a Mesh | None

wp.Mesh objects already built over mesh A and mesh B, to spare the BVH build each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly). Not checked against the arrays: the answer is for the geometry each holds. Trimesh.warp_mesh is the cached one to pass.

None
mesh_b Mesh | None

wp.Mesh objects already built over mesh A and mesh B, to spare the BVH build each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly). Not checked against the arrays: the answer is for the geometry each holds. Trimesh.warp_mesh is the cached one to pass.

None

Returns:

Type Description
array[float32]

(1,) device array holding the Chamfer loss (requires_grad=True).

Raises:

Type Description
RuntimeError

If vertices_a, faces_a, vertices_b, faces_b, mesh_a and mesh_b are not all on one device.

ValueError

If point_reduction is not "mean" or "sum".

See Also

chamfer_mesh_to_mesh chamfer_points_to_points_loss chamfer_points_to_mesh_loss

Examples:

A unit cube under a slab whose bottom face is the plane z = 1: the cube's top corners are 0.5 from it and the bottom ones 1.5, a mean of 1, and every corner is pulled up with weight 1 / 8:

import warp as wp

import ordito as od

vertices_a, faces_a = od.creation.box()
vertices_b, faces_b = od.creation.box(bounds=[[-2.0, -2.0, 1.0], [2.0, 2.0, 2.0]])
vertices_a.requires_grad = True
tape = wp.Tape()
loss = od.metrics.chamfer_mesh_to_mesh_loss(
    vertices_a, faces_a, vertices_b, faces_b, tape=tape, single_directional=True
)
tape.backward(loss=loss)
print(loss.numpy())  # [1.]
print(set(vertices_a.grad.numpy()[:, 2].tolist()))  # {-0.125}
Source code in ordito/metrics.py
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
def chamfer_mesh_to_mesh_loss(
    vertices_a: wp.array[wp.vec3],
    faces_a: wp.array[wp.int32],
    vertices_b: wp.array[wp.vec3],
    faces_b: wp.array[wp.int32],
    *,
    tape: wp.Tape | None = None,
    point_reduction: _DiffReduction = "mean",
    single_directional: bool = False,
    squared: bool = False,
    mesh_a: wp.Mesh | None = None,
    mesh_b: wp.Mesh | None = None,
) -> wp.array[wp.float32]:
    """
    Differentiable Chamfer loss between two triangle meshes (vertex-to-surface).

    Squared-distance analogue of
    [`chamfer_mesh_to_mesh`][ordito.metrics.chamfer_mesh_to_mesh]. The forward term is
    the distance from each vertex of mesh ``A`` to the surface of mesh ``B`` (with
    the closest triangle held constant during backprop); the backward term is the reverse.
    Gradients flow to both meshes' vertices.

    Parameters
    ----------
    vertices_a, faces_a
        ``(n_vertices_a,)`` vertices and ``(3 * n_faces_a,)`` flat faces of mesh ``A``.
    vertices_b, faces_b
        ``(n_vertices_b,)`` vertices and ``(3 * n_faces_b,)`` flat faces of mesh ``B``.
    tape
        Caller-owned ``wp.Tape`` for the backward pass, or ``None`` to skip taping.
    point_reduction
        ``"mean"`` (default) or ``"sum"``.
    single_directional
        If ``True``, only the ``A -> surface(B)`` term is accumulated.
    squared
        Square each distance before reducing, as ``pytorch3d`` does. Off by default: the result
        is then in squared units, and its ``"mean"`` is not a mean distance, which is easy to
        misread.
    mesh_a, mesh_b
        ``wp.Mesh`` objects already built over mesh ``A`` and mesh ``B``, to spare the BVH build
        each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly).
        Not checked against the arrays: the answer is for the geometry each holds.
        [`Trimesh.warp_mesh`][ordito.mesh.Trimesh.warp_mesh] is the cached one to pass.

    Returns
    -------
    wp.array[wp.float32]
        ``(1,)`` device array holding the Chamfer loss (``requires_grad=True``).

    Raises
    ------
    RuntimeError
        If ``vertices_a``, ``faces_a``, ``vertices_b``, ``faces_b``, ``mesh_a`` and ``mesh_b``
        are not all on one device.
    ValueError
        If ``point_reduction`` is not ``"mean"`` or ``"sum"``.

    See Also
    --------
    [`chamfer_mesh_to_mesh`][ordito.metrics.chamfer_mesh_to_mesh]
    [`chamfer_points_to_points_loss`][ordito.metrics.chamfer_points_to_points_loss]
    [`chamfer_points_to_mesh_loss`][ordito.metrics.chamfer_points_to_mesh_loss]

    Examples
    --------
    A unit cube under a slab whose bottom face is the plane ``z = 1``: the cube's top corners are
    ``0.5`` from it and the bottom ones ``1.5``, a mean of 1, and every corner is pulled up with
    weight ``1 / 8``:

    ```python
    import warp as wp

    import ordito as od

    vertices_a, faces_a = od.creation.box()
    vertices_b, faces_b = od.creation.box(bounds=[[-2.0, -2.0, 1.0], [2.0, 2.0, 2.0]])
    vertices_a.requires_grad = True
    tape = wp.Tape()
    loss = od.metrics.chamfer_mesh_to_mesh_loss(
        vertices_a, faces_a, vertices_b, faces_b, tape=tape, single_directional=True
    )
    tape.backward(loss=loss)
    print(loss.numpy())  # [1.]
    print(set(vertices_a.grad.numpy()[:, 2].tolist()))  # {-0.125}
    ```
    """
    require_same_device(
        vertices_a=vertices_a,
        faces_a=faces_a,
        vertices_b=vertices_b,
        faces_b=faces_b,
        mesh_a=mesh_a,
        mesh_b=mesh_b,
    )
    _validate_diff_reduction(point_reduction)
    device = vertices_a.device
    va = vertices_a.size
    vb = vertices_b.size
    n_faces_a = faces_a.size // 3
    n_faces_b = faces_b.size // 3
    loss = _zero_loss(device)
    if va == 0 or vb == 0 or n_faces_a == 0 or n_faces_b == 0:
        return loss

    # Non-differentiable closest-face assignment for each direction (outside the tape).
    _distances, face_ids = _closest_both_ways(
        vertices_a, faces_a, vertices_b, faces_b, single_directional, mesh_a, mesh_b
    )
    face_id_ab = odt.as_dense(face_ids[:va])
    terms: list[_ChamferTerm] = [
        _SurfaceTerm(
            vertices_a, vertices_b, faces_b, face_id_ab, _reduction_scale(point_reduction, va)
        )
    ]
    if not single_directional:
        face_id_ba = odt.as_dense(face_ids[va:])
        terms.append(
            _SurfaceTerm(
                vertices_b, vertices_a, faces_a, face_id_ba, _reduction_scale(point_reduction, vb)
            )
        )

    _accumulate_chamfer_terms(tape, terms, loss, squared=squared)
    return loss

hausdorff_points_to_points

hausdorff_points_to_points(
    x: array[vec3],
    y: array[vec3],
    *,
    single_directional: bool = False,
) -> float

Hausdorff distance between two point clouds.

The directed distance d(x, y) = max_i min_j ||x_i - y_j|| is computed (and symmetrized with d(y, x) unless single_directional). Equivalent to symmetrizing scipy.spatial.distance.directed_hausdorff.

Parameters:

Name Type Description Default
x array[vec3]

(n,) query point cloud.

required
y array[vec3]

(m,) target point cloud.

required
single_directional bool

If True, return only the directed distance d(x, y).

False

Returns:

Type Description
float

The (symmetric or directed) Hausdorff distance. 0.0 for empty inputs.

Raises:

Type Description
RuntimeError

If x and y are not all on one device.

See Also

hausdorff_points_to_mesh hausdorff_mesh_to_mesh scipy.spatial.distance.directed_hausdorff

Examples:

Every point of x is within 1 of y, but (3, 0, 0) is 2 from x:

import warp as wp

import ordito as od

x = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=wp.vec3)
y = wp.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0]], dtype=wp.vec3)
print(od.metrics.hausdorff_points_to_points(x, y))  # 2.0
print(od.metrics.hausdorff_points_to_points(x, y, single_directional=True))  # 1.0
Source code in ordito/metrics.py
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
def hausdorff_points_to_points(
    x: wp.array[wp.vec3], y: wp.array[wp.vec3], *, single_directional: bool = False
) -> float:
    """
    Hausdorff distance between two point clouds.

    The directed distance ``d(x, y) = max_i min_j ||x_i - y_j||`` is computed (and
    symmetrized with ``d(y, x)`` unless ``single_directional``). Equivalent to
    symmetrizing [`scipy.spatial.distance.directed_hausdorff`][].

    Parameters
    ----------
    x
        ``(n,)`` query point cloud.
    y
        ``(m,)`` target point cloud.
    single_directional
        If ``True``, return only the directed distance ``d(x, y)``.

    Returns
    -------
    float
        The (symmetric or directed) Hausdorff distance. ``0.0`` for empty inputs.

    Raises
    ------
    RuntimeError
        If ``x`` and ``y`` are not all on one device.

    See Also
    --------
    [`hausdorff_points_to_mesh`][ordito.metrics.hausdorff_points_to_mesh]
    [`hausdorff_mesh_to_mesh`][ordito.metrics.hausdorff_mesh_to_mesh]
    [`scipy.spatial.distance.directed_hausdorff`][]

    Examples
    --------
    Every point of ``x`` is within 1 of ``y``, but ``(3, 0, 0)`` is 2 from ``x``:

    ```python
    import warp as wp

    import ordito as od

    x = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=wp.vec3)
    y = wp.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0]], dtype=wp.vec3)
    print(od.metrics.hausdorff_points_to_points(x, y))  # 2.0
    print(od.metrics.hausdorff_points_to_points(x, y, single_directional=True))  # 1.0
    ```
    """
    require_same_device(x=x, y=y)
    distances = _distances_points_to_points(x, y, single_directional)
    if distances is None:
        return 0.0
    return _hausdorff(distances, single_directional)

hausdorff_points_to_mesh

hausdorff_points_to_mesh(
    points: array[vec3],
    vertices: array[vec3],
    faces: array[int32],
    *,
    single_directional: bool = False,
    mesh: Mesh | None = None,
) -> float

Hausdorff distance between a point cloud and a triangle mesh.

The forward distance is the maximum over points of the distance to the mesh surface; the backward distance is the maximum over mesh vertices of the distance to the nearest point in the cloud.

Parameters:

Name Type Description Default
points array[vec3]

(n,) query point cloud.

required
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index array.

required
single_directional bool

If True, return only the directed points -> mesh surface distance.

False
mesh Mesh | None

A wp.Mesh already built over vertices and faces, to spare the BVH build each call otherwise pays (worth it when one mesh is measured repeatedly). Not checked against vertices / faces: the answer is for the geometry mesh holds. Trimesh.warp_mesh is the cached one to pass.

None

Returns:

Type Description
float

The (symmetric or directed) Hausdorff distance. 0.0 for empty inputs.

Raises:

Type Description
RuntimeError

If points, vertices, faces and mesh are not all on one device.

See Also

hausdorff_points_to_points hausdorff_mesh_to_mesh

Examples:

A point 1.0 outside a unit cube and one at its centre. The farthest cube corner from the cloud is sqrt(3) / 2 from the centre point, so the symmetric value is still 1:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
points = wp.array([[1.5, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=wp.vec3)
directed = od.metrics.hausdorff_points_to_mesh(points, vertices, faces, single_directional=True)
print(directed)  # 1.0
print(f"{od.metrics.hausdorff_points_to_mesh(points, vertices, faces):.4f}")  # 1.0000
Source code in ordito/metrics.py
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
def hausdorff_points_to_mesh(
    points: wp.array[wp.vec3],
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    single_directional: bool = False,
    mesh: wp.Mesh | None = None,
) -> float:
    """
    Hausdorff distance between a point cloud and a triangle mesh.

    The forward distance is the maximum over points of the distance to the mesh
    surface; the backward distance is the maximum over mesh vertices of the distance
    to the nearest point in the cloud.

    Parameters
    ----------
    points
        ``(n,)`` query point cloud.
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index array.
    single_directional
        If ``True``, return only the directed ``points -> mesh surface`` distance.
    mesh
        A ``wp.Mesh`` already built over ``vertices`` and ``faces``, to spare the BVH build each
        call otherwise pays (worth it when one mesh is measured repeatedly). Not checked against
        ``vertices`` / ``faces``: the answer is for the geometry ``mesh`` holds.
        [`Trimesh.warp_mesh`][ordito.mesh.Trimesh.warp_mesh] is the cached one to pass.

    Returns
    -------
    float
        The (symmetric or directed) Hausdorff distance. ``0.0`` for empty inputs.

    Raises
    ------
    RuntimeError
        If ``points``, ``vertices``, ``faces`` and ``mesh`` are not all on one device.

    See Also
    --------
    [`hausdorff_points_to_points`][ordito.metrics.hausdorff_points_to_points]
    [`hausdorff_mesh_to_mesh`][ordito.metrics.hausdorff_mesh_to_mesh]

    Examples
    --------
    A point ``1.0`` outside a unit cube and one at its centre. The farthest cube corner from the
    cloud is ``sqrt(3) / 2`` from the centre point, so the symmetric value is still 1:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    points = wp.array([[1.5, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=wp.vec3)
    directed = od.metrics.hausdorff_points_to_mesh(points, vertices, faces, single_directional=True)
    print(directed)  # 1.0
    print(f"{od.metrics.hausdorff_points_to_mesh(points, vertices, faces):.4f}")  # 1.0000
    ```
    """
    require_same_device(points=points, vertices=vertices, faces=faces, mesh=mesh)
    distances = _distances_points_to_mesh(points, vertices, faces, single_directional, mesh)
    if distances is None:
        return 0.0
    return _hausdorff(distances, single_directional)

hausdorff_mesh_to_mesh

hausdorff_mesh_to_mesh(
    vertices_a: array[vec3],
    faces_a: array[int32],
    vertices_b: array[vec3],
    faces_b: array[int32],
    *,
    single_directional: bool = False,
    mesh_a: Mesh | None = None,
    mesh_b: Mesh | None = None,
) -> float

Hausdorff distance between two triangle meshes.

Direct port of libigl's igl::hausdorff (vertex-based overload): the distance from every vertex of one mesh to the surface of the other is computed in both directions and the overall maximum is returned. This equals sqrt(max(d_ba, d_ab)) in libigl, where d_* are squared distances.

Parameters:

Name Type Description Default
vertices_a array[vec3]

(n_vertices_a,) vertices and (3 * n_faces_a,) flat faces of mesh A.

required
faces_a array[vec3]

(n_vertices_a,) vertices and (3 * n_faces_a,) flat faces of mesh A.

required
vertices_b array[vec3]

(n_vertices_b,) vertices and (3 * n_faces_b,) flat faces of mesh B.

required
faces_b array[vec3]

(n_vertices_b,) vertices and (3 * n_faces_b,) flat faces of mesh B.

required
single_directional bool

If True, return only the directed A -> surface(B) distance.

False
mesh_a Mesh | None

wp.Mesh objects already built over mesh A and mesh B, to spare the BVH build each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly). Not checked against the arrays: the answer is for the geometry each holds. Trimesh.warp_mesh is the cached one to pass.

None
mesh_b Mesh | None

wp.Mesh objects already built over mesh A and mesh B, to spare the BVH build each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly). Not checked against the arrays: the answer is for the geometry each holds. Trimesh.warp_mesh is the cached one to pass.

None

Returns:

Type Description
float

The (symmetric or directed) Hausdorff distance. 0.0 for empty inputs.

Raises:

Type Description
RuntimeError

If vertices_a, faces_a, vertices_b, faces_b, mesh_a and mesh_b are not all on one device.

See Also

chamfer_mesh_to_mesh hausdorff_points_to_mesh

Examples:

A unit cube inside a cube of side 2: the inner corners are 0.5 from the outer surface, the outer corners sqrt(3) / 2 from the inner one:

import ordito as od

vertices_a, faces_a = od.creation.box()
vertices_b, faces_b = od.creation.box(extents=(2.0, 2.0, 2.0))
directed = od.metrics.hausdorff_mesh_to_mesh(
    vertices_a, faces_a, vertices_b, faces_b, single_directional=True
)
print(directed)  # 0.5
symmetric = od.metrics.hausdorff_mesh_to_mesh(vertices_a, faces_a, vertices_b, faces_b)
print(f"{symmetric:.4f}")  # 0.8660
Source code in ordito/metrics.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def hausdorff_mesh_to_mesh(
    vertices_a: wp.array[wp.vec3],
    faces_a: wp.array[wp.int32],
    vertices_b: wp.array[wp.vec3],
    faces_b: wp.array[wp.int32],
    *,
    single_directional: bool = False,
    mesh_a: wp.Mesh | None = None,
    mesh_b: wp.Mesh | None = None,
) -> float:
    """
    Hausdorff distance between two triangle meshes.

    Direct port of libigl's ``igl::hausdorff`` (vertex-based overload): the distance
    from every vertex of one mesh to the surface of the other is computed in both
    directions and the overall maximum is returned. This equals
    ``sqrt(max(d_ba, d_ab))`` in libigl, where ``d_*`` are squared distances.

    Parameters
    ----------
    vertices_a, faces_a
        ``(n_vertices_a,)`` vertices and ``(3 * n_faces_a,)`` flat faces of mesh ``A``.
    vertices_b, faces_b
        ``(n_vertices_b,)`` vertices and ``(3 * n_faces_b,)`` flat faces of mesh ``B``.
    single_directional
        If ``True``, return only the directed ``A -> surface(B)`` distance.
    mesh_a, mesh_b
        ``wp.Mesh`` objects already built over mesh ``A`` and mesh ``B``, to spare the BVH build
        each call otherwise pays per mesh queried (worth it when a mesh is measured repeatedly).
        Not checked against the arrays: the answer is for the geometry each holds.
        [`Trimesh.warp_mesh`][ordito.mesh.Trimesh.warp_mesh] is the cached one to pass.

    Returns
    -------
    float
        The (symmetric or directed) Hausdorff distance. ``0.0`` for empty inputs.

    Raises
    ------
    RuntimeError
        If ``vertices_a``, ``faces_a``, ``vertices_b``, ``faces_b``, ``mesh_a`` and ``mesh_b``
        are not all on one device.

    See Also
    --------
    [`chamfer_mesh_to_mesh`][ordito.metrics.chamfer_mesh_to_mesh]
    [`hausdorff_points_to_mesh`][ordito.metrics.hausdorff_points_to_mesh]

    Examples
    --------
    A unit cube inside a cube of side 2: the inner corners are ``0.5`` from the outer surface, the
    outer corners ``sqrt(3) / 2`` from the inner one:

    ```python
    import ordito as od

    vertices_a, faces_a = od.creation.box()
    vertices_b, faces_b = od.creation.box(extents=(2.0, 2.0, 2.0))
    directed = od.metrics.hausdorff_mesh_to_mesh(
        vertices_a, faces_a, vertices_b, faces_b, single_directional=True
    )
    print(directed)  # 0.5
    symmetric = od.metrics.hausdorff_mesh_to_mesh(vertices_a, faces_a, vertices_b, faces_b)
    print(f"{symmetric:.4f}")  # 0.8660
    ```
    """
    require_same_device(
        vertices_a=vertices_a,
        faces_a=faces_a,
        vertices_b=vertices_b,
        faces_b=faces_b,
        mesh_a=mesh_a,
        mesh_b=mesh_b,
    )
    distances = _distances_mesh_to_mesh(
        vertices_a, faces_a, vertices_b, faces_b, single_directional, mesh_a, mesh_b
    )
    if distances is None:
        return 0.0
    return _hausdorff(distances, single_directional)