Skip to content

ordito.parametrization

Flatten a mesh into the plane: harmonic, Tutte, ARAP, SLIM and LSCM parametrizations.

Seven maps, differing in what they hold fixed and what they minimize. The first three pin the boundary and solve for the interior: harmonic minimizes Dirichlet energy with cotangent weights, tutte is the same solve with uniform weights (guaranteeing an injective map for a convex boundary), and arap alternates local rotation fits with a global solve to trade conformality for low area distortion. slim frees the boundary and refines a start toward the least symmetric Dirichlet distortion, never inverting a face the start had the right way round and not squashed flat. lscm instead pins only two vertices and lets the boundary find its own shape, minimizing conformal rather than Dirichlet energy. low_distortion_parametrization pins nothing and needs no start: a free-boundary chart of low ARAP distortion in the mesh's own units for an open surface of any topology, converged on a coarse mesh; arap_parametrization is the same chart refined from a harmonic, Tutte or LSCM map of a surface with a boundary. slim_parametrization unwraps in one call to the least symmetric Dirichlet distortion, from the free chart or a harmonic, Tutte or LSCM start.

map_vertices_to_circle supplies the boundary condition the fixed-boundary three need, and face_flipped_indices is the diagnostic that says whether a result is actually injective. All but the two low-distortion charts port the corresponding igl:: routines.

The fixed-vertex maps (harmonic, tutte, lscm) take the mesh as an ordito.mesh.Trimesh or as its vertices and faces. Their solves iterate, verified, and fall back to a sparse Cholesky factorization where the iteration fails; given a Trimesh, a factorization is kept on it (Trimesh.fixed_vertex_solver), and one built ahead with FixedVertexSolver.factor -- or by a call with solver="direct" -- turns every later call fixing the same vertices into a factored solve with no iteration.

Classes:

Name Description
FixedVertexSolver

Factorizations of the fixed-vertex maps' systems on one mesh, kept by the mesh.

Functions:

Name Description
face_flipped_mask

Per-face flag: whether a triangle is inverted (negative 2D signed area) in the parametrization.

face_flipped_indices

Return the indices of triangles inverted (negative 2D signed area) in the parametrization.

map_vertices_to_circle

Map an ordered boundary loop onto the unit circle by arc length.

harmonic

Harmonic parametrization with fixed boundary.

tutte

Tutte embedding with fixed boundary (uniform-Laplacian parametrization).

arap

As-rigid-as-possible (ARAP) parametrization with fixed vertices.

slim

Free-boundary chart of least symmetric Dirichlet distortion, refined from a start (SLIM).

low_distortion_parametrization

Free-boundary chart of low ARAP distortion in the mesh's own units, for any topology.

arap_parametrization

Free-boundary chart of low ARAP distortion, from a harmonic, Tutte or LSCM start.

slim_parametrization

Free-boundary chart of least symmetric Dirichlet distortion, from a start it builds (SLIM).

lscm

Constrained least-squares conformal map.

FixedVertexSolver

FixedVertexSolver(mesh: Trimesh)

Factorizations of the fixed-vertex maps' systems on one mesh, kept by the mesh.

What Trimesh.fixed_vertex_solver returns, and what harmonic, tutte and lscm consult when given a Trimesh. Each map solves the system its operator reduces to once the fixed vertices are eliminated, and that system depends on which vertices are fixed -- not on the values they are fixed to -- so one factorization per (method, k) serves every later call that fixes the same vertices: such a call runs no iteration, only the factorization's solve.

A factorization is kept here when factor builds it ahead of the calls, when a call asks for one (solver="direct"), or when a call built one anyway: the iteration's result failed its verification (see min_quad_with_fixed), or the system is factored from the start -- at k >= 3, for a k == 2 harmonic / tutte system or an lscm one on a mesh of 4 000 vertices or more, and on the CPU device for a k == 1 one on a mesh of 5 000 or more. A call fixing other vertices than the kept factorization's solves as if none were kept, and replaces it with its own when it builds one. A system factored from the start that cannot be factored (over CHOLESKY_MEMORY_BUDGET, or not definite) is remembered as such until release, and later "auto" calls iterate without attempting it again.

Notes

A kept factorization holds device memory of the order of its system's fill-in for as long as this solver lives -- the mesh's lifetime -- reported by nbytes and returned by release or Trimesh.release_factorizations. The solver refers to its mesh weakly and is unusable once the mesh is gone.

See Also

Trimesh.fixed_vertex_solver MinQuadWithFixedData

Examples:

Factor once for a boundary, then every harmonic map of that mesh fixing it is a direct solve:

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
mesh = od.mesh.Trimesh(vertices, faces)
boundary = od.boundary.longest_boundary_loop(vertices, faces)
solver = mesh.fixed_vertex_solver()
print(solver.factor("harmonic", boundary))  # True
circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
uv = od.parametrization.harmonic(mesh, boundary_indices=boundary, boundary_uv=circle)
print(uv.shape, solver.nbytes > 0)  # (217,) True
solver.release()
print(solver.nbytes)  # 0

Bind a solver to mesh; nothing is assembled until a factorization is asked for.

Methods:

Name Description
release

Drop every kept factorization, and forget which systems could not be factored.

factor

Factor method's system with fixed_indices fixed, for every later call fixing them.

solve

Solve method's reduced system: by the kept factorization if it fixes fixed_mask.

Source code in ordito/parametrization.py
2663
2664
2665
2666
2667
2668
2669
2670
def __init__(self, mesh: Trimesh) -> None:
    """Bind a solver to ``mesh``; nothing is assembled until a factorization is asked for."""
    self._mesh = weakref.ref(mesh)
    self._systems: dict[tuple[str, int], twl.MinQuadWithFixedData] = {}
    # The ``(method, k)`` whose system ``"auto"`` factored at once (``_factors_at_once``) and
    # the factorization refused -- over the memory budget, or not definite. Its later calls
    # iterate without paying for the refused attempt's analysis again; ``release`` forgets it.
    self._refused: set[tuple[str, int]] = set()

nbytes property

nbytes: int

Device memory this solver's kept factorizations hold, in bytes.

release

release() -> None

Drop every kept factorization, and forget which systems could not be factored.

Source code in ordito/parametrization.py
2677
2678
2679
2680
2681
2682
def release(self) -> None:
    """Drop every kept factorization, and forget which systems could not be factored."""
    for system in self._systems.values():
        system.release()
    self._systems.clear()
    self._refused.clear()

factor

factor(
    method: str, fixed_indices: array[int32], *, k: int = 1
) -> bool

Factor method's system with fixed_indices fixed, for every later call fixing them.

Parameters:

Name Type Description Default
method str

"harmonic", "tutte" or "lscm": the map the factorization serves.

required
fixed_indices array[int32]

(n_fixed,) the vertices the calls fix: boundary_indices of harmonic / tutte, pinned_indices of lscm. Only the set matters, not the order.

required
k int

The harmonic power the calls pass (1 for "lscm").

1

Returns:

Type Description
bool

Whether the calls will run no iteration: False when the system cannot be factored (over CHOLESKY_MEMORY_BUDGET, or not definite in float64), and they keep iterating.

Raises:

Type Description
ValueError

If method is not one of the three, if k < 1, if k != 1 for "lscm", or if fixed_indices repeats a vertex or holds one outside [0, n_vertices).

RuntimeError

If fixed_indices is not on the mesh's device.

Examples:

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
mesh = od.mesh.Trimesh(vertices, faces)
boundary = od.boundary.longest_boundary_loop(vertices, faces)
print(mesh.fixed_vertex_solver().factor("tutte", boundary, k=2))  # True
Source code in ordito/parametrization.py
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
def factor(self, method: str, fixed_indices: wp.array[wp.int32], *, k: int = 1) -> bool:
    """
    Factor ``method``'s system with ``fixed_indices`` fixed, for every later call fixing them.

    Parameters
    ----------
    method
        ``"harmonic"``, ``"tutte"`` or ``"lscm"``: the map the factorization serves.
    fixed_indices
        ``(n_fixed,)`` the vertices the calls fix: ``boundary_indices`` of
        [`harmonic`][ordito.parametrization.harmonic] / [`tutte`][ordito.parametrization.tutte],
        ``pinned_indices`` of [`lscm`][ordito.parametrization.lscm]. Only the set matters,
        not the order.
    k
        The harmonic power the calls pass (``1`` for ``"lscm"``).

    Returns
    -------
    bool
        Whether the calls will run no iteration: ``False`` when the system cannot be factored
        (over [`CHOLESKY_MEMORY_BUDGET`][ordito.cholesky.CHOLESKY_MEMORY_BUDGET], or not
        definite in ``float64``), and they keep iterating.

    Raises
    ------
    ValueError
        If ``method`` is not one of the three, if ``k < 1``, if ``k != 1`` for ``"lscm"``, or
        if ``fixed_indices`` repeats a vertex or holds one outside ``[0, n_vertices)``.
    RuntimeError
        If ``fixed_indices`` is not on the mesh's device.

    Examples
    --------
    ```python
    import ordito as od

    vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
    mesh = od.mesh.Trimesh(vertices, faces)
    boundary = od.boundary.longest_boundary_loop(vertices, faces)
    print(mesh.fixed_vertex_solver().factor("tutte", boundary, k=2))  # True
    ```
    """
    _require_fixed_vertex_method(method, k, "FixedVertexSolver.factor")
    mesh = self._bound_mesh()
    require_same_device(vertices=mesh.vertices, fixed_indices=fixed_indices)
    n_vertices = mesh.n_vertices
    if n_vertices == 0:
        return True
    n_fixed = fixed_indices.size
    # The values are scattered into a buffer the factorization never reads.
    no_uv = _launch.empty(n_fixed, dtype=wp.vec2, device=mesh.device)
    if method == "lscm":
        fixed_mask, _ = _pin_stacked(n_vertices, fixed_indices, no_uv, mesh.device)
        n_fixed *= 2
    else:
        fixed_mask, _ = _scatter_constraints(n_vertices, fixed_indices, no_uv, mesh.device)
    system, _ = _fixed_vertex_system(mesh, method, k, fixed_mask, n_fixed, factor=True)
    if system.factored:
        self._keep(method, k, system)
    return system.factored or system.n_free == 0

solve

solve(
    method: str,
    fixed_mask: array[bool],
    fixed_values: Array2dFloat64,
    *,
    k: int = 1,
    solver: Literal["auto", "direct"] = "auto",
) -> tuple[odt.Array2dFloat, wp.array[wp.int32]]

Solve method's reduced system: by the kept factorization if it fixes fixed_mask.

Otherwise the system is assembled and solved verified, as min_quad_with_fixed solves it, and a factorization that solve builds is kept here, replacing the one (method, k) held.

Parameters:

Name Type Description Default
method str

"harmonic", "tutte" or "lscm".

required
fixed_mask array[bool]

(n_dofs,) the fixed degrees of freedom: (n_vertices,) for harmonic / tutte, (2 * n_vertices,) (u then v) for lscm.

required
fixed_values Array2dFloat64

(n_columns, n_dofs) prescribed values; only the fixed entries are read.

required
k int

The harmonic power (1 for "lscm").

1
solver Literal['auto', 'direct']

"auto" iterates, verified, and factors only when the check fails -- or at once at k >= 3, for k == 2 and "lscm" on a mesh of 4 000 vertices or more, and on the CPU device for k == 1 on one of 5 000 or more, unless that system was already refused; "direct" factors at once. A factorization either builds is kept.

'auto'

Returns:

Name Type Description
solution Array2dFloat

(n_columns, n_free) values of the free degrees of freedom.

free_map array[int32]

(n_dofs,) compact index of each free degree of freedom.

Raises:

Type Description
ValueError

If method is not one of the three, if k < 1, if k != 1 for "lscm", or if solver is not "auto" or "direct".

RuntimeError

If fixed_mask and fixed_values are not on the mesh's device.

Warns:

Type Description
UserWarning

When no verified solution is reached (see min_quad_with_fixed).

Examples:

The harmonic system with the boundary of a flat grid fixed to its x coordinates: the free values are the interior x coordinates:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(5, 5))
mesh = od.mesh.Trimesh(vertices, faces)
boundary = od.boundary.longest_boundary_loop(vertices, faces).numpy()
mask = np.zeros(vertices.shape[0], dtype=bool)
mask[boundary] = True
x = vertices.numpy()[:, 0].astype(np.float64)
solution, free_map = mesh.fixed_vertex_solver().solve(
    "harmonic", wp.array(mask, dtype=wp.bool), wp.array(x[None, :], dtype=wp.float64)
)
print(solution.shape)  # (1, 9)
print(np.allclose(solution.numpy()[0], x[~mask]))  # True
Source code in ordito/parametrization.py
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
def solve(
    self,
    method: str,
    fixed_mask: wp.array[wp.bool],
    fixed_values: odt.Array2dFloat64,
    *,
    k: int = 1,
    solver: Literal["auto", "direct"] = "auto",
) -> tuple[odt.Array2dFloat, wp.array[wp.int32]]:
    """
    Solve ``method``'s reduced system: by the kept factorization if it fixes ``fixed_mask``.

    Otherwise the system is assembled and solved verified, as
    [`min_quad_with_fixed`][ordito.linalg.min_quad_with_fixed] solves it, and a factorization
    that solve builds is kept here, replacing the one ``(method, k)`` held.

    Parameters
    ----------
    method
        ``"harmonic"``, ``"tutte"`` or ``"lscm"``.
    fixed_mask
        ``(n_dofs,)`` the fixed degrees of freedom: ``(n_vertices,)`` for ``harmonic`` /
        ``tutte``, ``(2 * n_vertices,)`` (``u`` then ``v``) for ``lscm``.
    fixed_values
        ``(n_columns, n_dofs)`` prescribed values; only the fixed entries are read.
    k
        The harmonic power (``1`` for ``"lscm"``).
    solver
        ``"auto"`` iterates, verified, and factors only when the check fails -- or at once at
        ``k >= 3``, for ``k == 2`` and ``"lscm"`` on a mesh of 4 000 vertices or more, and on
        the CPU device for ``k == 1`` on one of 5 000 or more, unless that system was already
        refused; ``"direct"`` factors at once. A factorization
        either builds is kept.

    Returns
    -------
    solution : odt.Array2dFloat
        ``(n_columns, n_free)`` values of the free degrees of freedom.
    free_map : wp.array[wp.int32]
        ``(n_dofs,)`` compact index of each free degree of freedom.

    Raises
    ------
    ValueError
        If ``method`` is not one of the three, if ``k < 1``, if ``k != 1`` for ``"lscm"``, or
        if ``solver`` is not ``"auto"`` or ``"direct"``.
    RuntimeError
        If ``fixed_mask`` and ``fixed_values`` are not on the mesh's device.

    Warns
    -----
    UserWarning
        When no verified solution is reached (see
        [`min_quad_with_fixed`][ordito.linalg.min_quad_with_fixed]).

    Examples
    --------
    The harmonic system with the boundary of a flat grid fixed to its ``x`` coordinates: the
    free values are the interior ``x`` coordinates:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(5, 5))
    mesh = od.mesh.Trimesh(vertices, faces)
    boundary = od.boundary.longest_boundary_loop(vertices, faces).numpy()
    mask = np.zeros(vertices.shape[0], dtype=bool)
    mask[boundary] = True
    x = vertices.numpy()[:, 0].astype(np.float64)
    solution, free_map = mesh.fixed_vertex_solver().solve(
        "harmonic", wp.array(mask, dtype=wp.bool), wp.array(x[None, :], dtype=wp.float64)
    )
    print(solution.shape)  # (1, 9)
    print(np.allclose(solution.numpy()[0], x[~mask]))  # True
    ```
    """
    _require_fixed_vertex_method(method, k, "FixedVertexSolver.solve")
    return self._solve(method, fixed_mask, fixed_values, k, solver, None)

face_flipped_mask

face_flipped_mask(
    vertices: array[vec2], faces: array[int32]
) -> wp.array[wp.bool]

Per-face flag: whether a triangle is inverted (negative 2D signed area) in the parametrization.

For each triangle the 2D signed area of its three UV vertices is computed; a face is flagged True when that area is strictly negative, i.e. the triangle has folded over (flipped orientation) in the 2D domain. Mirrors libigl's flipped_triangles per-triangle test (determinant of the homogeneous 3 x 3 vertex matrix < 0). Degenerate (zero-area) triangles are not flagged, matching the strict < 0 comparison. face_flipped_indices is the index form of this mask.

Parameters:

Name Type Description Default
vertices array[vec2]

(n_vertices,) 2D vertex positions (the parametrization / UV coordinates).

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required

Returns:

Type Description
array[bool]

(n_faces,) flipped-triangle mask on vertices.device. Empty for an empty mesh.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

See Also

face_flipped_indices face_flip_mask

Notes

Equivalent to the per-triangle predicate behind libigl flipped_triangles: the 2D cross product (v1 - v0) x (v2 - v0) equals det([[x0, x1, x2], [y0, y1, y2], [1, 1, 1]]), so a True entry corresponds exactly to a triangle libigl would list as flipped.

This is a different flip from face_flip_mask, which is about the 3D winding: this mask flags a triangle whose UV image has folded over, a property of the parametrization that says nothing about the surface, while that one flags a triangle whose index order must be reversed to agree with its patch. A mesh can be consistently wound and still have flipped UVs, and vice versa.

Examples:

Two triangles sharing an edge, the second wound clockwise in the plane:

import warp as wp

import ordito as od

uv = wp.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=wp.vec2)
faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
print(od.parametrization.face_flipped_mask(uv, faces).numpy())  # [False  True]
Source code in ordito/parametrization.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
def face_flipped_mask(vertices: wp.array[wp.vec2], faces: wp.array[wp.int32]) -> wp.array[wp.bool]:
    """
    Per-face flag: whether a triangle is inverted (negative 2D signed area) in the parametrization.

    For each triangle the 2D signed area of its three UV vertices is computed; a face is flagged
    ``True`` when that area is strictly negative, i.e. the triangle has folded over (flipped
    orientation) in the 2D domain. Mirrors libigl's ``flipped_triangles`` per-triangle test
    (determinant of the homogeneous ``3 x 3`` vertex matrix ``< 0``). Degenerate (zero-area)
    triangles are **not** flagged, matching the strict ``< 0`` comparison.
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices] is the index form of
    this mask.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` 2D vertex positions (the parametrization / UV coordinates).
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.

    Returns
    -------
    wp.array[wp.bool]
        ``(n_faces,)`` flipped-triangle mask on ``vertices.device``. Empty for an empty mesh.

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

    See Also
    --------
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices]
    [`face_flip_mask`][ordito.validation.face_flip_mask]

    Notes
    -----
    Equivalent to the per-triangle predicate behind libigl ``flipped_triangles``: the 2D cross
    product ``(v1 - v0) x (v2 - v0)`` equals ``det([[x0, x1, x2], [y0, y1, y2], [1, 1, 1]])``, so a
    ``True`` entry corresponds exactly to a triangle libigl would list as flipped.

    This is a different flip from
    [`face_flip_mask`][ordito.validation.face_flip_mask], which is about the *3D winding*: this
    mask flags a triangle whose UV image has folded over, a property of the parametrization that
    says nothing about the surface, while that one flags a triangle whose index order must be
    reversed to agree with its patch. A mesh can be consistently wound and still have flipped UVs,
    and vice versa.

    Examples
    --------
    Two triangles sharing an edge, the second wound clockwise in the plane:

    ```python
    import warp as wp

    import ordito as od

    uv = wp.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=wp.vec2)
    faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
    print(od.parametrization.face_flipped_mask(uv, faces).numpy())  # [False  True]
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    device = vertices.device
    n_faces = faces.size // 3
    if n_faces == 0:
        return _launch.empty(0, dtype=wp.bool, device=device)

    out_mask = _launch.empty(n_faces, dtype=wp.bool, device=device)
    _launch.launch(
        kernel_parametrization.face_flipped_mask,
        dim=n_faces,
        inputs=[vertices, faces, out_mask],
        device=device,
    )
    return out_mask

face_flipped_indices

face_flipped_indices(
    vertices: array[vec2], faces: array[int32]
) -> wp.array[wp.int32]

Return the indices of triangles inverted (negative 2D signed area) in the parametrization.

Convenience wrapper returning flatnonzero of face_flipped_mask: the indices into faces of triangles whose 2D signed area is strictly negative (folded over in the UV domain). Matches libigl's flipped_triangles, which returns the same list of flipped-triangle indices.

Parameters:

Name Type Description Default
vertices array[vec2]

(n_vertices,) 2D vertex positions (the parametrization / UV coordinates).

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required

Returns:

Type Description
array[int32]

(m,) ascending face indices of the m flipped triangles on vertices.device. Empty when no triangle is flipped.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

See Also

face_flipped_mask flatnonzero

Examples:

import warp as wp

import ordito as od

uv = wp.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=wp.vec2)
faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
print(od.parametrization.face_flipped_indices(uv, faces).numpy())  # [1]
Source code in ordito/parametrization.py
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def face_flipped_indices(
    vertices: wp.array[wp.vec2], faces: wp.array[wp.int32]
) -> wp.array[wp.int32]:
    """
    Return the indices of triangles inverted (negative 2D signed area) in the parametrization.

    Convenience wrapper returning ``flatnonzero`` of
    [`face_flipped_mask`][ordito.parametrization.face_flipped_mask]: the indices into ``faces``
    of triangles whose 2D signed area is strictly negative (folded over in the UV domain). Matches
    libigl's ``flipped_triangles``, which returns the same list of flipped-triangle indices.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` 2D vertex positions (the parametrization / UV coordinates).
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.

    Returns
    -------
    wp.array[wp.int32]
        ``(m,)`` ascending face indices of the ``m`` flipped triangles on ``vertices.device``.
        Empty when no
        triangle is flipped.

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

    See Also
    --------
    [`face_flipped_mask`][ordito.parametrization.face_flipped_mask]
    [`flatnonzero`][ordito.array.flatnonzero]

    Examples
    --------
    ```python
    import warp as wp

    import ordito as od

    uv = wp.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=wp.vec2)
    faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
    print(od.parametrization.face_flipped_indices(uv, faces).numpy())  # [1]
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    device = vertices.device
    n_faces = faces.size // 3
    if n_faces == 0:
        return _launch.empty(0, dtype=wp.int32, device=device)
    # ``flatnonzero`` of the mask, with the flags written straight into the buffer they are scanned
    # in: no bool mask between them.
    inclusive = _launch.empty(n_faces, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_parametrization.face_flipped_flags,
        dim=n_faces,
        inputs=[vertices, faces, inclusive],
        device=device,
    )
    return od.array.flatnonzero_in_place(inclusive)

map_vertices_to_circle

map_vertices_to_circle(
    vertices: array[vec3], boundary: array[int32]
) -> wp.array[wp.vec2]

Map an ordered boundary loop onto the unit circle by arc length.

Places boundary vertex i at angle 2*pi * len[i] / total, where len[i] is the cumulative edge length from boundary[0] to boundary[i] along the loop and total is the full perimeter (closing over the wrap edge). The result is in loop order: row i is the position of boundary[i]. Feed it as boundary_uv to tutte or harmonic for a disk parametrization.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
boundary array[int32]

(n_boundary,) ordered boundary-loop vertex indices, e.g. from longest_boundary_loop.

required

Returns:

Type Description
array[vec2]

(n_boundary,) unit-circle positions on vertices.device, aligned with boundary.

Raises:

Type Description
RuntimeError

If vertices and boundary are not all on one device.

Notes

The name and the arc-length placement follow igl::map_vertices_to_circle.

See Also

longest_boundary_loop tutte harmonic

Examples:

The boundary of a 3 x 3 grid, eight vertices at equal spacing, lands at multiples of 45°:

import numpy as np

import ordito as od

vertices, faces = od.creation.grid(count=(3, 3))
boundary = od.boundary.longest_boundary_loop(vertices, faces)
circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
print(circle.shape)  # (8,)
print(np.allclose(np.linalg.norm(circle.numpy(), axis=1), 1.0))  # True
print(circle.numpy()[1].round(4))  # [0.7071 0.7071]
Source code in ordito/parametrization.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
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
def map_vertices_to_circle(
    vertices: wp.array[wp.vec3], boundary: wp.array[wp.int32]
) -> wp.array[wp.vec2]:
    """
    Map an ordered boundary loop onto the unit circle by arc length.

    Places boundary vertex ``i`` at angle ``2*pi * len[i] / total``, where ``len[i]`` is the
    cumulative edge length from ``boundary[0]`` to ``boundary[i]`` along the loop and ``total`` is
    the full perimeter (closing over the wrap edge). The result is in loop order: row ``i`` is the
    position of ``boundary[i]``. Feed it as ``boundary_uv`` to
    [`tutte`][ordito.parametrization.tutte] or [`harmonic`][ordito.parametrization.harmonic] for a
    disk parametrization.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    boundary
        ``(n_boundary,)`` ordered boundary-loop vertex indices, e.g. from
        [`longest_boundary_loop`][ordito.boundary.longest_boundary_loop].

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_boundary,)`` unit-circle positions on ``vertices.device``, aligned with ``boundary``.

    Raises
    ------
    RuntimeError
        If ``vertices`` and ``boundary`` are not all on one device.

    Notes
    -----
    The name and the arc-length placement follow ``igl::map_vertices_to_circle``.

    See Also
    --------
    [`longest_boundary_loop`][ordito.boundary.longest_boundary_loop]
    [`tutte`][ordito.parametrization.tutte]
    [`harmonic`][ordito.parametrization.harmonic]

    Examples
    --------
    The boundary of a 3 x 3 grid, eight vertices at equal spacing, lands at multiples of 45°:

    ```python
    import numpy as np

    import ordito as od

    vertices, faces = od.creation.grid(count=(3, 3))
    boundary = od.boundary.longest_boundary_loop(vertices, faces)
    circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
    print(circle.shape)  # (8,)
    print(np.allclose(np.linalg.norm(circle.numpy(), axis=1), 1.0))  # True
    print(circle.numpy()[1].round(4))  # [0.7071 0.7071]
    ```
    """
    require_same_device(vertices=vertices, boundary=boundary)
    device = vertices.device
    n_boundary = boundary.size
    out_uv = _launch.empty(n_boundary, dtype=wp.vec2, device=device)
    if n_boundary == 0:
        return out_uv

    if n_boundary <= _CIRCLE_ONE_BLOCK_VERTICES or not wp.get_device(device).is_cuda:
        _launch.launch_tiled(
            kernel_parametrization.circle_positions_block,
            dim=1,
            inputs=[boundary, vertices, out_uv],
            device=device,
        )
        return out_uv
    segment_lengths = _launch.empty(n_boundary, dtype=wp.float32, device=device)
    _launch.launch(
        kernel_parametrization.boundary_edge_lengths,
        dim=n_boundary,
        inputs=[boundary, vertices, segment_lengths],
        device=device,
    )
    # Scanned in place: the lengths are read only through their running sum.
    _launch.array_scan(segment_lengths, out_array=segment_lengths, inclusive=True)
    _launch.launch(
        kernel_parametrization.circle_positions,
        dim=n_boundary,
        inputs=[boundary, vertices, segment_lengths, out_uv],
        device=device,
    )
    return out_uv

harmonic

harmonic(
    mesh: Trimesh,
    boundary_indices: array[int32],
    boundary_uv: array[vec2],
    /,
    *,
    k: int = 1,
    solver: Literal["auto", "direct"] = "auto",
    nonnegative_weights: bool = False,
) -> wp.array[wp.vec2]
harmonic(
    vertices: array[vec3],
    faces: array[int32],
    boundary_indices: array[int32],
    boundary_uv: array[vec2],
    /,
    k: int = 1,
    *,
    solver: Literal["auto", "direct"] = "auto",
    nonnegative_weights: bool = False,
) -> wp.array[wp.vec2]
harmonic(
    mesh: Trimesh | array[vec3] | None = None,
    faces: array[int32] | None = None,
    boundary_indices: array[int32]
    | array[vec2]
    | None = None,
    boundary_uv: array[vec2] | None = None,
    k: int = 1,
    *,
    vertices: array[vec3] | None = None,
    solver: Literal["auto", "direct"] = "auto",
    nonnegative_weights: bool = False,
) -> wp.array[wp.vec2]

Harmonic parametrization with fixed boundary.

Minimizes the k-harmonic energy built from the cotangent Laplacian cotmatrix subject to the boundary vertices being pinned to boundary_uv. For k == 1 this is the harmonic map (each interior UV is the cotangent-weighted average of its neighbors); k == 2 is the biharmonic map, and so on. The interior system is iterated, verified, or factored, as solver and Notes say.

Parameters:

Name Type Description Default
mesh Trimesh | array[vec3] | None

The mesh, as an ordito.mesh.Trimesh; or, in its place, vertices and faces.

None
vertices array[vec3] | None

(n_vertices,) mesh vertex positions.

None
faces array[int32] | None

(3 * n_faces,) triangle index buffer.

None
boundary_indices array[int32] | array[vec2] | None

(n_boundary,) indices of the fixed (constrained) vertices.

None
boundary_uv array[vec2] | None

(n_boundary,) target UV positions for boundary_indices, in the same order (e.g. from map_vertices_to_circle).

None
k int

Harmonic power (>= 1). k > 1 additionally uses the barycentric lumped mass matrix mass_matrix_entries. The operator is assembled in float64 (built native, never recast) so the ill-conditioned k > 1 solve is accurate.

1
solver Literal['auto', 'direct']

"auto" (default) factors the system at once at k >= 3, where the iteration does not converge, at k == 2 on a mesh of 4 000 vertices or more, and on the CPU device at k == 1 on one of 5 000 or more, where a factorization costs less than the iteration; otherwise it solves by conjugate gradient, verified, and factors the system only when the iteration's result fails the check. "direct" factors it at once (a sparse Cholesky); given a Trimesh, the factorization is kept on it, so every later call fixing the same vertices -- whatever their values -- is a factored solve with no iteration. Pays from about the second such call; a one-shot call is usually faster under "auto".

'auto'
nonnegative_weights bool

Build the Laplacian from cotangent weights clamped at zero (cotmatrix's nonnegative_weights). At k == 1 each free vertex is then a convex combination of its neighbors, so with the boundary on a convex polygon the map is an embedding (Tutte's and Floater's theorem) whatever the mesh's obtuse angles, where the signed weights can fold triangles; the map is no longer exactly harmonic. A Trimesh keeps this system's factorization apart from the signed one's.

False

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device.

Raises:

Type Description
ValueError

If k < 1, if there are interior vertices but boundary_indices is empty (the Dirichlet system would be singular), if boundary_indices and boundary_uv have different lengths, if boundary_indices repeats a vertex or holds one outside [0, n_vertices), or if solver is not "auto" or "direct".

RuntimeError

If vertices, faces, boundary_indices and boundary_uv are not all on one device.

Warns:

Type Description
UserWarning

When no verified solution is reached (see min_quad_with_fixed): the interior system cannot be factored -- too large, or not definite in float64, which a high k on a strongly graded mesh reaches -- and conjugate gradient does not converge.

See Also

tutte k_harmonic The operator this minimizes, as opposed to this map -- the two are the only two "harmonic" names in the package and they are not interchangeable. cotmatrix map_vertices_to_circle

Notes

Matches igl::harmonic at k == 1. Above, igl's default mass matrix is the Voronoi one where this uses the barycentric lumped mass; igl::harmonic given a barycentric massmatrix is the same map.

Each k is solved its own way, since raising the operator to the k-th power raises its condition number to it. k == 1 runs conjugate gradient under the Jacobi-Chebyshev polynomial (chebyshev_preconditioner), k == 2 under the square of that Laplacian's polynomial (squared_laplacian_preconditioner) -- on a mesh of fewer than 4 000 vertices; from 4 000 the k == 2 system is factored at once, as k >= 3 is below, its iteration growing faster with the mesh than the factorization. Both results are verified -- converged within CG_FACTOR_AFTER_POLYNOMIAL_ROUNDS rounds, with a componentwise backward error under VERIFIED_BACKWARD_ERROR -- and a result that is not is replaced by a sparse_cholesky solve: on a strongly graded mesh the k == 2 system's condition number nears the reciprocal of float64's precision, where no iteration converges. k >= 3 is factored from the start, the iteration (under the multigrid preconditioner multigrid_preconditioner) taken only when the system cannot be factored; a Trimesh remembers that refusal, so its later calls iterate without attempting the factorization again. Given a Trimesh, a factorization built here is kept on it, and one prepared with FixedVertexSolver.factor serves every later call fixing the same vertices -- whatever their values -- with no iteration; the vertices, faces form drops it, and says so at INFO.

On such an ill-conditioned system the answer itself is determined only to the system's own precision: direct solvers under different orderings agree to about a percent of the UV range there, as this one does with them.

Examples:

A disk-topology cap mapped onto the unit disk, with no flipped triangle:

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
boundary = od.boundary.longest_boundary_loop(vertices, faces)
circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
uv = od.parametrization.harmonic(
    vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
)
print(uv.shape)  # (217,)
print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)

On a flat grid pinned to its own boundary positions, the harmonic map interpolates them linearly, so it reproduces the grid:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(8, 8))
boundary = od.boundary.longest_boundary_loop(vertices, faces)
boundary_uv = wp.array(vertices.numpy()[boundary.numpy(), :2], dtype=wp.vec2)
uv = od.parametrization.harmonic(
    vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=boundary_uv
)
print(np.allclose(uv.numpy(), vertices.numpy()[:, :2], atol=1e-5))  # True
Source code in ordito/parametrization.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def harmonic(
    mesh: Trimesh | wp.array[wp.vec3] | None = None,
    faces: wp.array[wp.int32] | None = None,
    boundary_indices: wp.array[wp.int32] | wp.array[wp.vec2] | None = None,
    boundary_uv: wp.array[wp.vec2] | None = None,
    k: int = 1,
    *,
    vertices: wp.array[wp.vec3] | None = None,
    solver: Literal["auto", "direct"] = "auto",
    nonnegative_weights: bool = False,
) -> wp.array[wp.vec2]:
    """
    Harmonic parametrization with fixed boundary.

    Minimizes the ``k``-harmonic energy built from the cotangent Laplacian
    [`cotmatrix`][ordito.laplacian.cotmatrix] subject to the boundary vertices being pinned to
    ``boundary_uv``. For ``k == 1`` this is the harmonic map (each interior UV is the
    cotangent-weighted average of its neighbors); ``k == 2`` is the biharmonic map, and so on. The
    interior system is iterated, verified, or factored, as ``solver`` and Notes say.

    Parameters
    ----------
    mesh
        The mesh, as an [`ordito.mesh.Trimesh`][ordito.mesh.Trimesh]; or, in its place,
        ``vertices`` and ``faces``.
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer.
    boundary_indices
        ``(n_boundary,)`` indices of the fixed (constrained) vertices.
    boundary_uv
        ``(n_boundary,)`` target UV positions for ``boundary_indices``, in the same order (e.g. from
        [`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle]).
    k
        Harmonic power (``>= 1``). ``k > 1`` additionally uses the barycentric lumped mass matrix
        [`mass_matrix_entries`][ordito.laplacian.mass_matrix_entries]. The operator is assembled in
        float64 (built native, never recast) so the ill-conditioned ``k > 1`` solve is accurate.
    solver
        ``"auto"`` (default) factors the system at once at ``k >= 3``, where the iteration does not
        converge, at ``k == 2`` on a mesh of 4 000 vertices or more, and on the CPU device at
        ``k == 1`` on one of 5 000 or more, where a factorization costs less than the iteration;
        otherwise it solves by conjugate gradient, verified, and factors the system only when the
        iteration's result fails the check. ``"direct"`` factors it at once (a sparse Cholesky);
        given a `Trimesh`, the factorization is kept on it, so every later call fixing the same
        vertices -- whatever their values -- is a factored solve with no iteration. Pays from about
        the second such call; a one-shot call is usually faster under ``"auto"``.
    nonnegative_weights
        Build the Laplacian from cotangent weights clamped at zero
        ([`cotmatrix`][ordito.laplacian.cotmatrix]'s ``nonnegative_weights``). At ``k == 1`` each
        free vertex is then a convex combination of its neighbors, so with the boundary on a
        convex polygon the map is an embedding (Tutte's and Floater's theorem) whatever the mesh's
        obtuse angles, where the signed weights can fold triangles; the map is no longer exactly
        harmonic. A `Trimesh` keeps this system's factorization apart from the signed one's.

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``.

    Raises
    ------
    ValueError
        If ``k < 1``, if there are interior vertices but ``boundary_indices`` is empty (the
        Dirichlet system would be singular), if ``boundary_indices`` and ``boundary_uv`` have
        different lengths, if ``boundary_indices`` repeats a vertex or holds one outside
        ``[0, n_vertices)``, or if ``solver`` is not ``"auto"`` or ``"direct"``.
    RuntimeError
        If ``vertices``, ``faces``, ``boundary_indices`` and ``boundary_uv`` are not all on one
        device.

    Warns
    -----
    UserWarning
        When no verified solution is reached (see
        [`min_quad_with_fixed`][ordito.linalg.min_quad_with_fixed]): the interior system cannot be
        factored -- too large, or not definite in ``float64``, which a high ``k`` on a strongly
        graded mesh reaches -- and conjugate gradient does not converge.

    See Also
    --------
    [`tutte`][ordito.parametrization.tutte]
    [`k_harmonic`][ordito.energies.k_harmonic]
        The *operator* this minimizes, as opposed to this *map* -- the two are the only two
        "harmonic" names in the package and they are not interchangeable.
    [`cotmatrix`][ordito.laplacian.cotmatrix]
    [`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle]

    Notes
    -----
    Matches ``igl::harmonic`` at ``k == 1``. Above, igl's default mass matrix is the Voronoi one
    where this uses the barycentric lumped mass; ``igl::harmonic`` given a barycentric
    ``massmatrix`` is the same map.

    Each ``k`` is solved its own way, since raising the operator to the ``k``-th power raises its
    condition number to it. ``k == 1`` runs conjugate gradient under the Jacobi-Chebyshev polynomial
    ([`chebyshev_preconditioner`][ordito.linalg.chebyshev_preconditioner]), ``k == 2`` under the
    square of that Laplacian's polynomial
    ([`squared_laplacian_preconditioner`][ordito.linalg.squared_laplacian_preconditioner]) -- on a
    mesh of fewer than 4 000 vertices; from 4 000 the ``k == 2`` system is factored at once, as
    ``k >= 3`` is below, its iteration growing faster with the mesh than the factorization. Both
    results are verified -- converged within
    [`CG_FACTOR_AFTER_POLYNOMIAL_ROUNDS`][ordito.linalg.CG_FACTOR_AFTER_POLYNOMIAL_ROUNDS] rounds,
    with a componentwise
    backward error under
    [`VERIFIED_BACKWARD_ERROR`][ordito.linalg.VERIFIED_BACKWARD_ERROR] -- and a result that is not
    is replaced by a [`sparse_cholesky`][ordito.cholesky.sparse_cholesky] solve: on a strongly
    graded mesh the ``k == 2`` system's condition number nears the reciprocal of ``float64``'s
    precision, where no iteration converges. ``k >= 3`` is factored from the start, the iteration
    (under the multigrid preconditioner
    [`multigrid_preconditioner`][ordito.linalg.multigrid_preconditioner]) taken only when the
    system cannot be factored; a `Trimesh` remembers that refusal, so its later calls iterate
    without attempting the factorization again. Given a `Trimesh`, a factorization built here is
    kept on it, and one prepared with
    [`FixedVertexSolver.factor`][ordito.parametrization.FixedVertexSolver.factor] serves every
    later call fixing the same vertices -- whatever their values -- with no iteration; the
    ``vertices, faces`` form drops it, and says so at ``INFO``.

    On such an ill-conditioned system the answer itself is determined only to the system's own
    precision: direct solvers under different orderings agree to about a percent of the UV range
    there, as this one does with them.

    Examples
    --------
    A disk-topology cap mapped onto the unit disk, with no flipped triangle:

    ```python
    import ordito as od

    vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
    boundary = od.boundary.longest_boundary_loop(vertices, faces)
    circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
    uv = od.parametrization.harmonic(
        vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
    )
    print(uv.shape)  # (217,)
    print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
    ```

    On a flat grid pinned to its own boundary positions, the harmonic map interpolates them
    linearly, so it reproduces the grid:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(8, 8))
    boundary = od.boundary.longest_boundary_loop(vertices, faces)
    boundary_uv = wp.array(vertices.numpy()[boundary.numpy(), :2], dtype=wp.vec2)
    uv = od.parametrization.harmonic(
        vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=boundary_uv
    )
    print(np.allclose(uv.numpy(), vertices.numpy()[:, :2], atol=1e-5))  # True
    ```
    """
    bound, owned, arguments = mesh_arguments(
        "harmonic", mesh, vertices, faces, (boundary_indices, boundary_uv, k), 2
    )
    return _fixed_boundary_map(
        bound,
        owned,
        _HARMONIC_NONNEGATIVE if nonnegative_weights else "harmonic",
        cast("wp.array[wp.int32]", arguments[0]),
        cast("wp.array[wp.vec2]", arguments[1]),
        cast("int", arguments[2]),
        solver,
    )

tutte

tutte(
    mesh: Trimesh,
    boundary_indices: array[int32],
    boundary_uv: array[vec2],
    /,
    *,
    k: int = 1,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]
tutte(
    vertices: array[vec3],
    faces: array[int32],
    boundary_indices: array[int32],
    boundary_uv: array[vec2],
    /,
    k: int = 1,
    *,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]
tutte(
    mesh: Trimesh | array[vec3] | None = None,
    faces: array[int32] | None = None,
    boundary_indices: array[int32]
    | array[vec2]
    | None = None,
    boundary_uv: array[vec2] | None = None,
    k: int = 1,
    *,
    vertices: array[vec3] | None = None,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]

Tutte embedding with fixed boundary (uniform-Laplacian parametrization).

Identical to harmonic except the operator is the combinatorial graph_laplacian instead of the cotangent one — for k == 1 that Laplacian is the only difference. Because the uniform Laplacian's free-free block is a diagonally dominant M-matrix, the Tutte embedding of a mesh with a convex boundary is guaranteed bijective (fold-free), unlike the harmonic/conformal maps. For k > 1 the mass matrix is the identity (matching libigl's speye graph-Laplacian variant). Solved, and its factorizations kept, as harmonic is (see its Notes).

Parameters:

Name Type Description Default
mesh Trimesh | array[vec3] | None

The mesh, as an ordito.mesh.Trimesh; or, in its place, vertices and faces.

None
vertices array[vec3] | None

(n_vertices,) mesh vertex positions.

None
faces array[int32] | None

(3 * n_faces,) triangle index buffer.

None
boundary_indices array[int32] | array[vec2] | None

(n_boundary,) indices of the fixed (constrained) vertices.

None
boundary_uv array[vec2] | None

(n_boundary,) target UV positions for boundary_indices, in the same order (e.g. a convex loop from map_vertices_to_circle).

None
k int

Laplacian power (>= 1). k == 1 is the classic Tutte embedding.

1
solver Literal['auto', 'direct']

"auto" (default) or "direct", as for harmonic.

'auto'

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device.

Raises:

Type Description
ValueError

If k < 1, if there are interior vertices but boundary_indices is empty, if boundary_indices and boundary_uv have different lengths, if boundary_indices repeats a vertex or holds one outside [0, n_vertices), or if solver is not "auto" or "direct".

RuntimeError

If vertices, faces, boundary_indices and boundary_uv are not all on one device.

See Also

harmonic graph_laplacian map_vertices_to_circle

Examples:

Even a cap curved almost into a sphere embeds without a fold onto the convex unit disk:

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=2.5, subdivisions=3)
boundary = od.boundary.longest_boundary_loop(vertices, faces)
circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
uv = od.parametrization.tutte(
    vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
)
print(uv.shape)  # (217,)
print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
Source code in ordito/parametrization.py
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def tutte(
    mesh: Trimesh | wp.array[wp.vec3] | None = None,
    faces: wp.array[wp.int32] | None = None,
    boundary_indices: wp.array[wp.int32] | wp.array[wp.vec2] | None = None,
    boundary_uv: wp.array[wp.vec2] | None = None,
    k: int = 1,
    *,
    vertices: wp.array[wp.vec3] | None = None,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]:
    """
    Tutte embedding with fixed boundary (uniform-Laplacian parametrization).

    Identical to [`harmonic`][ordito.parametrization.harmonic] except the operator is the
    combinatorial [`graph_laplacian`][ordito.laplacian.graph_laplacian] instead of the
    cotangent one — for ``k == 1`` that Laplacian is the *only* difference. Because the uniform
    Laplacian's free-free block is a diagonally dominant M-matrix, the Tutte embedding of a mesh
    with a convex boundary is guaranteed bijective (fold-free), unlike the harmonic/conformal maps.
    For ``k > 1`` the mass matrix is the identity (matching libigl's ``speye`` graph-Laplacian
    variant). Solved, and its factorizations kept, as [`harmonic`][ordito.parametrization.harmonic]
    is (see its Notes).

    Parameters
    ----------
    mesh
        The mesh, as an [`ordito.mesh.Trimesh`][ordito.mesh.Trimesh]; or, in its place,
        ``vertices`` and ``faces``.
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer.
    boundary_indices
        ``(n_boundary,)`` indices of the fixed (constrained) vertices.
    boundary_uv
        ``(n_boundary,)`` target UV positions for ``boundary_indices``, in the same order (e.g. a
        convex loop from
        [`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle]).
    k
        Laplacian power (``>= 1``). ``k == 1`` is the classic Tutte embedding.
    solver
        ``"auto"`` (default) or ``"direct"``, as for
        [`harmonic`][ordito.parametrization.harmonic].

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``.

    Raises
    ------
    ValueError
        If ``k < 1``, if there are interior vertices but ``boundary_indices`` is empty, if
        ``boundary_indices`` and ``boundary_uv`` have different lengths, if ``boundary_indices``
        repeats a vertex or holds one outside ``[0, n_vertices)``, or if ``solver`` is not
        ``"auto"`` or ``"direct"``.
    RuntimeError
        If ``vertices``, ``faces``, ``boundary_indices`` and ``boundary_uv`` are not all on one
        device.

    See Also
    --------
    [`harmonic`][ordito.parametrization.harmonic]
    [`graph_laplacian`][ordito.laplacian.graph_laplacian]
    [`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle]

    Examples
    --------
    Even a cap curved almost into a sphere embeds without a fold onto the convex unit disk:

    ```python
    import ordito as od

    vertices, faces = od.creation.sphere_cap(angle=2.5, subdivisions=3)
    boundary = od.boundary.longest_boundary_loop(vertices, faces)
    circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
    uv = od.parametrization.tutte(
        vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
    )
    print(uv.shape)  # (217,)
    print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
    ```
    """
    bound, owned, arguments = mesh_arguments(
        "tutte", mesh, vertices, faces, (boundary_indices, boundary_uv, k), 2
    )
    return _fixed_boundary_map(
        bound,
        owned,
        "tutte",
        cast("wp.array[wp.int32]", arguments[0]),
        cast("wp.array[wp.vec2]", arguments[1]),
        cast("int", arguments[2]),
        solver,
    )

arap

arap(
    vertices: array[vec3],
    faces: array[int32],
    fixed_indices: array[int32],
    fixed_uv: array[vec2],
    uv_init: array[vec2],
    max_iterations: int = 10,
    tolerance: float = 1e-07,
    *,
    pattern: MeshOperatorPattern | None = None,
) -> wp.array[wp.vec2]

As-rigid-as-possible (ARAP) parametrization with fixed vertices.

Minimizes the ARAP energy of the 2D parametrization by local/global alternation, starting from uv_init and keeping fixed_indices pinned to fixed_uv at every iteration. The local step fits, per triangle, the closest rotation between the isometrically flattened rest triangle and its current UV image (closed-form 2D polar decomposition, reflections forbidden); the global step solves the cotangent-Laplacian Poisson system (-L)_uu U_u = (K R)_u - (-L)_ub bc for each UV column with conjugate gradient, or by a factorization of it once those solves prove long (see Notes).

A good uv_init matters: ARAP is non-convex, so feed a fold-free initial map such as harmonic or tutte, with the boundary placed by map_vertices_to_circle. Inspect the result for inverted triangles with face_flipped_indices.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer.

required
fixed_indices array[int32]

(n_fixed,) indices of the pinned (constrained) vertices — libigl's b. At least one is required whenever the mesh has interior vertices (the ARAP global system is otherwise a singular, translation-invariant Poisson problem). Pinning the whole boundary loop reproduces the classic fixed-boundary ARAP disk parametrization.

required
fixed_uv array[vec2]

(n_fixed,) target UV positions for fixed_indices, in the same order — libigl's bc.

required
uv_init array[vec2]

(n_vertices,) initial UV coordinates (the warm start). Never mutated; the interior values seed the first local step and the conjugate-gradient warm start, and the pinned rows are overwritten with fixed_uv before the first iteration.

required
max_iterations int

Number of local/global iterations (>= 1). libigl defaults to 10.

10
tolerance float

Relative residual tolerance of each global step's solve (> 0). Looser than the 1e-8 of the single-solve maps: each solve is an inner step of a truncated outer iteration, and solving past that iteration's own error changes nothing.

1e-07
pattern MeshOperatorPattern | None

A "cotmatrix" mesh_operator_pattern of faces (Trimesh.mesh_operator_pattern), which spares the cotangent assembly its sort.

None

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device. Empty for an empty mesh. Rows at fixed_indices equal fixed_uv exactly.

Raises:

Type Description
ValueError

If max_iterations < 1, if tolerance <= 0, if there are interior vertices but fixed_indices is empty, if fixed_indices and fixed_uv have different lengths, if fixed_indices repeats a vertex or holds one outside [0, n_vertices), or if pattern was built for another operator or vertex count.

RuntimeError

If vertices, faces, fixed_indices, fixed_uv, uv_init and pattern are not all on one device.

See Also

harmonic tutte map_vertices_to_circle face_flipped_indices low_distortion_parametrization The same energy with no pins and no start.

Notes

Uses the elements ARAP energy (one rotation per triangle), libigl's default for the flat dim = 2 case, with unclamped half-cotangent weights as libigl's. Each face's rotation is the proper rotation nearest its Jacobian -- the rotation igl::fit_rotations_planar fits to the weighted edge covariance -- and the right-hand side is gathered per vertex, the same vector as libigl's rotated rest edges. The local step shares its code with low_distortion_parametrization. Everything between iterations is float64.

The global step's operator is the same at every iteration. When the second iteration's solve shows the solves are long -- a graded mesh, or a long schedule on a large one -- the remaining iterations solve by a sparse_cholesky factorization of it, refined to tolerance, held until the call returns: device memory of the order of the operator's fill-in, within CHOLESKY_MEMORY_BUDGET. An operator that cannot be factored keeps iterating.

Examples:

Started from a Tutte embedding, the result stays flip-free and keeps the pinned boundary exactly:

import numpy as np

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
boundary = od.boundary.longest_boundary_loop(vertices, faces)
circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
uv_init = od.parametrization.tutte(
    vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
)
uv = od.parametrization.arap(vertices, faces, boundary, circle, uv_init)
print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
print(np.array_equal(uv.numpy()[boundary.numpy()], circle.numpy()))  # True
Source code in ordito/parametrization.py
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
749
750
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
875
876
877
878
879
880
881
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
937
938
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
def arap(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    fixed_indices: wp.array[wp.int32],
    fixed_uv: wp.array[wp.vec2],
    uv_init: wp.array[wp.vec2],
    max_iterations: int = 10,
    tolerance: float = 1e-7,
    *,
    pattern: od.laplacian.MeshOperatorPattern | None = None,
) -> wp.array[wp.vec2]:
    """
    As-rigid-as-possible (ARAP) parametrization with fixed vertices.

    Minimizes the ARAP energy of the 2D parametrization by local/global alternation, starting from
    ``uv_init`` and keeping ``fixed_indices`` pinned to ``fixed_uv`` at every iteration. The local
    step fits, per triangle, the closest rotation between the isometrically flattened rest triangle
    and its current UV image (closed-form 2D polar decomposition, reflections forbidden); the global
    step solves the cotangent-Laplacian Poisson system ``(-L)_uu U_u = (K R)_u - (-L)_ub bc`` for
    each UV column with conjugate gradient, or by a factorization of it once those solves prove
    long (see Notes).

    A good ``uv_init`` matters: ARAP is non-convex, so feed a fold-free initial map such as
    [`harmonic`][ordito.parametrization.harmonic] or [`tutte`][ordito.parametrization.tutte], with
    the boundary placed by
    [`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle]. Inspect the result
    for inverted triangles with
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices].

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer.
    fixed_indices
        ``(n_fixed,)`` indices of the pinned (constrained) vertices — libigl's ``b``. At least one
        is required whenever the mesh has interior vertices (the ARAP global system is otherwise a
        singular, translation-invariant Poisson problem). Pinning the whole boundary loop reproduces
        the classic fixed-boundary ARAP disk parametrization.
    fixed_uv
        ``(n_fixed,)`` target UV positions for ``fixed_indices``, in the same order — libigl's
        ``bc``.
    uv_init
        ``(n_vertices,)`` initial UV coordinates (the warm start). Never mutated; the interior
        values seed the first local step and the conjugate-gradient warm start, and the pinned rows
        are overwritten with ``fixed_uv`` before the first iteration.
    max_iterations
        Number of local/global iterations (``>= 1``). libigl defaults to ``10``.
    tolerance
        Relative residual tolerance of each global step's solve (``> 0``). Looser than the
        ``1e-8`` of the single-solve maps: each solve is an inner step of a truncated outer
        iteration, and solving past that iteration's own error changes nothing.
    pattern
        A ``"cotmatrix"`` [`mesh_operator_pattern`][ordito.laplacian.mesh_operator_pattern] of
        ``faces`` ([`Trimesh.mesh_operator_pattern`][ordito.mesh.Trimesh.mesh_operator_pattern]),
        which spares the cotangent assembly its sort.

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``. Empty for an empty mesh. Rows at
        ``fixed_indices`` equal ``fixed_uv`` exactly.

    Raises
    ------
    ValueError
        If ``max_iterations < 1``, if ``tolerance <= 0``, if there are interior vertices but
        ``fixed_indices`` is empty, if ``fixed_indices`` and ``fixed_uv`` have different lengths,
        if ``fixed_indices`` repeats a vertex or holds one outside ``[0, n_vertices)``, or if
        ``pattern`` was built for another operator or vertex count.
    RuntimeError
        If ``vertices``, ``faces``, ``fixed_indices``, ``fixed_uv``, ``uv_init`` and ``pattern``
        are not all on one device.

    See Also
    --------
    [`harmonic`][ordito.parametrization.harmonic]
    [`tutte`][ordito.parametrization.tutte]
    [`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle]
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices]
    [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization]
        The same energy with no pins and no start.

    Notes
    -----
    Uses the *elements* ARAP energy (one rotation per triangle), libigl's default for the flat
    ``dim = 2`` case, with unclamped half-cotangent weights as libigl's. Each face's rotation is the
    proper rotation nearest its Jacobian -- the rotation ``igl::fit_rotations_planar`` fits to the
    weighted edge covariance -- and the right-hand side is gathered per vertex, the same vector as
    libigl's rotated rest edges. The local step shares its code with
    [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization].
    Everything between iterations is ``float64``.

    The global step's operator is the same at every iteration. When the second iteration's solve
    shows the solves are long -- a graded mesh, or a long schedule on a large one -- the remaining
    iterations solve by a [`sparse_cholesky`][ordito.cholesky.sparse_cholesky] factorization of it,
    refined to ``tolerance``, held until the call returns: device memory of the order of the
    operator's fill-in, within [`CHOLESKY_MEMORY_BUDGET`][ordito.cholesky.CHOLESKY_MEMORY_BUDGET].
    An operator that cannot be factored keeps iterating.

    Examples
    --------
    Started from a Tutte embedding, the result stays flip-free and keeps the pinned boundary
    exactly:

    ```python
    import numpy as np

    import ordito as od

    vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
    boundary = od.boundary.longest_boundary_loop(vertices, faces)
    circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
    uv_init = od.parametrization.tutte(
        vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
    )
    uv = od.parametrization.arap(vertices, faces, boundary, circle, uv_init)
    print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
    print(np.array_equal(uv.numpy()[boundary.numpy()], circle.numpy()))  # True
    ```
    """
    require_same_device(
        vertices=vertices,
        faces=faces,
        fixed_indices=fixed_indices,
        fixed_uv=fixed_uv,
        uv_init=uv_init,
        pattern=None if pattern is None else pattern.offsets,
    )
    if max_iterations < 1:
        raise ValueError(f"arap max_iterations must be >= 1, got {max_iterations}.")
    if tolerance <= 0.0:
        raise ValueError(f"arap tolerance must be > 0, got {tolerance}.")
    device = vertices.device
    n_vertices = vertices.size
    if n_vertices == 0:
        return _launch.empty(0, dtype=wp.vec2, device=device)

    # Interior vertices with nothing pinned leave the ARAP global system translation-invariant
    # (singular) -- and since n_vertices > 0, an empty ``fixed_indices`` always means at least one
    # interior vertex exists. Checked before the cotangent/Laplacian build below (mirroring
    # harmonic / tutte), so a rejected call doesn't pay for the assembly first.
    _require_fixed_vertices(
        fixed_indices.size,
        n_vertices,
        1,
        "arap requires at least one fixed vertex when the mesh has interior vertices; the ARAP "
        "global system is otherwise singular (translation invariant).",
    )
    n_faces = faces.size // 3

    laplacian = cotmatrix(vertices, faces, dtype=wp.float64, pattern=pattern)

    # Partition vertices into pinned (fixed) and interior (free), and extract the global-step
    # operator with it: the interior block of Q = -L and the constant boundary term -(-L)_ub bc.
    # ``fixed_values`` is the (2, n_vertices) prescribed-UV buffer (row 0 = u, row 1 = v) shared
    # with the assembly / scatter kernels; ``interior_map`` compacts free vertices into the reduced
    # system.
    # ``future work``: libigl also supports rotation groups ``G`` (shared rotations across grouped
    # faces, replacing the per-face fit with a group-summed covariance) and ``with_dynamics`` (a
    # mass-matrix + timestep term added to Q and the right-hand side); both are out of scope here.
    fixed_mask, fixed_values = _scatter_constraints(n_vertices, fixed_indices, fixed_uv, device)
    fixed_values_2d = odt.as_array2d(fixed_values, wp.float64)
    q_uu, rhs_const, interior_map, n_interior = twl.partitioned_interior_system(
        laplacian, fixed_mask, fixed_values_2d, scale=-1.0
    )
    # The scatter skips an out-of-range index and a repeated one marks its vertex once, so either
    # leaves fewer vertices fixed than ``fixed_indices`` lists: the free count just read shows it.
    if n_vertices - n_interior != fixed_indices.size:
        raise ValueError(
            "arap: fixed_indices must be distinct vertex indices in [0, n_vertices); they fix "
            f"{n_vertices - n_interior} vertices where {fixed_indices.size} were given"
        )

    out_uv = _launch.empty(n_vertices, dtype=wp.vec2, device=device)
    if n_interior == 0:
        # Every vertex pinned: the prescribed positions are the whole answer, and the loop's
        # setup would serve no solve.
        empty_sol = _launch.zeros((2, 0), dtype=wp.float64, device=device)
        _launch.launch(
            kernel_parametrization.scatter_solution,
            dim=n_vertices,
            inputs=[fixed_mask, interior_map, empty_sol, fixed_values_2d, out_uv],
            device=device,
        )
        return out_uv

    # The loop's buffers, none allocated inside it: each face's gradients and area, the
    # warm-started solution per column ``sol`` (seeded from ``uv_init``'s free rows by the same
    # launch) and the global step's right-hand side ``b``, the last two in one allocation.
    vertex_faces, offsets = od.adjacency.vertex_face_adjacency(faces, n_vertices=n_vertices)
    gradients = odt.empty_2d((n_faces, 3), wp.vec2d, device=device)
    areas = _launch.empty(n_faces, dtype=wp.float64, device=device)
    solve_buffers = _launch.empty(4 * n_interior, dtype=wp.float64, device=device)
    sol = odt.as_array2d(
        _launch.view(solve_buffers, 0, 2 * n_interior).reshape((2, n_interior)), wp.float64
    )
    b = odt.as_array2d(
        _launch.view(solve_buffers, 2 * n_interior, 4 * n_interior).reshape((2, n_interior)),
        wp.float64,
    )
    _launch.launch(
        kernel_parametrization.arap_setup,
        dim=max(n_faces, n_vertices),
        inputs=[vertices, faces, fixed_mask, interior_map, uv_init],
        outputs=[gradients, areas, sol],
        device=device,
    )

    # One batched CG state for both UV columns, reading ``b`` and warm-started from ``sol``. The
    # global steps are short warm-started Jacobi-Chebyshev solves of an operator rebuilt per call,
    # so it factors only once they are found long (``_ARAP_FACTOR_FROM_ROUNDS_CUDA`` / ``_CPU``).
    solver = twl.spd_column_solver(
        q_uu, b, sol, tol=tolerance, maxiter=10 * n_interior, preconditioner="chebyshev",
        factorize=False,
    )  # fmt: skip

    held = None
    for iteration in range(max_iterations):
        # The local step and the global step's right-hand side at each free vertex.
        _launch.launch(
            kernel_parametrization.arap_rhs,
            dim=n_vertices,
            inputs=[faces, vertex_faces, offsets, gradients, areas, fixed_values_2d, fixed_mask,
                    interior_map, sol, rhs_const],
            outputs=[b],
            device=device,
        )  # fmt: skip
        # Both UV columns in one batched symmetric-PD solve, warm-started from the previous ``sol``;
        # by a factorization of the operator once the iteration is found long.
        if held is not None:
            held.solve(b, sol, tol=tolerance)
            continue
        rounds, _, _ = solver()
        if iteration == 1 and iteration + 1 < max_iterations:
            # The second solve's round count, read once a call: it predicts the later solves'
            # length (the first, from ``uv_init``, does not: a harmonic start's first solve can be
            # long and every later one short), which decides whether a factorization pays.
            remaining = max_iterations - iteration - 1
            if _round_count(rounds) * remaining >= (
                _ARAP_FACTOR_FROM_ROUNDS_CUDA
                if wp.get_device(device).is_cuda
                else _ARAP_FACTOR_FROM_ROUNDS_CPU
            ):
                held = _arap_factorization(q_uu, vertices, fixed_mask, interior_map)
    if held is not None:
        held.release()
    # The full UV field, the pinned rows at their constraints.
    _launch.launch(
        kernel_parametrization.scatter_solution,
        dim=n_vertices,
        inputs=[fixed_mask, interior_map, sol, fixed_values_2d, out_uv],
        device=device,
    )
    return out_uv

slim

slim(
    vertices: array[vec3],
    faces: array[int32],
    uv_init: array[vec2],
    *,
    max_iterations: int = 100,
    tolerance: float = 0.001,
) -> wp.array[wp.vec2]

Free-boundary chart of least symmetric Dirichlet distortion, refined from a start (SLIM).

Minimizes sum_f A_f (s1^2 + s2^2 + s1^-2 + s2^-2) over the chart, s1 and s2 each face's singular values, by scalable locally injective maps: each iteration solves the energy's reweighted ARAP proxy, whose gradient at the current chart is the energy's own, and moves along that step only as far as no face inverts and the energy does not rise. The energy grows without bound as a face collapses, so it trades stretch against compression evenly and never folds a face the start had the right way round (and not squashed flat, below). No vertex is pinned and the boundary is free; the chart keeps the start's position and rotation up to the drift of its optimization.

The start must be a chart of the mesh in its own units (a free chart such as low_distortion_parametrization, or a disk map such as tutte scaled to the surface's area): the energy is not scale-invariant, and its minimum is an isometry wherever one exists. A start winding clockwise on the whole is refined mirrored and returned with its winding. A face inverted in the start, as a surface with a handle forces somewhere, is held by the ARAP term 4 A_f |J_f - R_f|^2 instead, which has no barrier and may right it; so is a face the start squashes by more than a thousandfold, which the barrier, held at the edge of float64, would freeze.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Faces of no area are ignored.

required
uv_init array[vec2]

(n_vertices,) start chart in the mesh's units. Never mutated.

required
max_iterations int

Iteration budget. 0 returns the start.

100
tolerance float

The iterations stop once eight of them lower the energy above its rest value by less than this fraction of it.

0.001

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device. A vertex no face uses keeps its start. Empty for an empty mesh.

Raises:

Type Description
ValueError

If vertices is not wp.vec3, faces not wp.int32 with a multiple of three entries or uv_init not wp.vec2 with one entry per vertex, if max_iterations is negative or tolerance negative or not finite, or if the factorization of the proxy would exceed CHOLESKY_MEMORY_BUDGET.

RuntimeError

If vertices, faces and uv_init are not on one device.

See Also

low_distortion_parametrization A start for any topology. arap The pinned ARAP map. face_flipped_indices

Notes

Ports igl::slim with SYMMETRIC_DIRICHLET and no constraints, which converges to the same chart from a fold-free start. Each proxy is a wp.mat22d operator over the vertices, factored by sparse_cholesky (device memory of the order of its fill-in, held until the call returns); it is refactored every eight iterations and the iterations between solve against the held factor with the current gradient, which the line search keeps descending; libigl refactors every iteration. The proxy's weights are capped where a face nears collapse, and its gradient with them, which bounds the operator's conditioning and keeps a nearly collapsed face of the start (as a Tutte map of a surface with a handle has) from cutting every step to nothing; the energy and the barrier stay exact.

The iteration runs in float64. Under is_deterministic the chart repeats bit for bit; otherwise its last bits can move between calls on the CUDA device.

Examples:

A cap started from a Tutte disk scaled to its area relaxes toward an isometry and stays fold-free:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=1.4, subdivisions=4)
corners = faces.numpy().reshape(-1, 3)
surface = float(od.triangles.face_normals_and_areas(vertices, faces)[1].numpy().sum())


def chart_area(uv: np.ndarray) -> float:
    e1 = uv[corners[:, 1]] - uv[corners[:, 0]]
    e2 = uv[corners[:, 2]] - uv[corners[:, 0]]
    return float(np.abs(e1[:, 0] * e2[:, 1] - e1[:, 1] * e2[:, 0]).sum() / 2)


boundary = od.boundary.longest_boundary_loop(vertices, faces)
circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
disk = od.parametrization.tutte(
    vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
).numpy()
start = wp.array(disk * np.sqrt(surface / chart_area(disk)), dtype=wp.vec2)
uv = od.parametrization.slim(vertices, faces, start)
print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
print(f"{chart_area(uv.numpy()) / surface:.2f}")  # 1.01
Source code in ordito/parametrization.py
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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
def slim(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    uv_init: wp.array[wp.vec2],
    *,
    max_iterations: int = 100,
    tolerance: float = 1e-3,
) -> wp.array[wp.vec2]:
    """
    Free-boundary chart of least symmetric Dirichlet distortion, refined from a start (SLIM).

    Minimizes ``sum_f A_f (s1^2 + s2^2 + s1^-2 + s2^-2)`` over the chart, ``s1`` and ``s2`` each
    face's singular values, by scalable locally injective maps: each iteration solves the
    energy's reweighted ARAP proxy, whose gradient at the current chart is the energy's own, and
    moves along that step only as far as no face inverts and the energy does not rise. The energy
    grows without bound as a face collapses, so it trades stretch against compression evenly and
    never folds a face the start had the right way round (and not squashed flat, below). No vertex
    is pinned and the boundary is
    free; the chart keeps the start's position and rotation up to the drift of its optimization.

    The start must be a chart of the mesh in its own units (a free chart such as
    [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization], or a
    disk map such as [`tutte`][ordito.parametrization.tutte] scaled to the surface's area): the
    energy is not scale-invariant, and its minimum is an isometry wherever one exists. A start
    winding clockwise on the whole is refined mirrored and returned with its winding. A face
    inverted in the start, as a surface with a handle forces somewhere, is held by the ARAP term
    ``4 A_f |J_f - R_f|^2`` instead, which has no barrier and may right it; so is a face the start
    squashes by more than a thousandfold, which the barrier, held at the edge of ``float64``,
    would freeze.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Faces of no area are ignored.
    uv_init
        ``(n_vertices,)`` start chart in the mesh's units. Never mutated.
    max_iterations
        Iteration budget. ``0`` returns the start.
    tolerance
        The iterations stop once eight of them lower the energy above its rest value by less than
        this fraction of it.

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``. A vertex no face uses keeps its
        start. Empty for an empty mesh.

    Raises
    ------
    ValueError
        If ``vertices`` is not ``wp.vec3``, ``faces`` not ``wp.int32`` with a multiple of three
        entries or ``uv_init`` not ``wp.vec2`` with one entry per vertex, if ``max_iterations`` is
        negative or ``tolerance`` negative or not finite, or if the factorization of the proxy
        would exceed [`CHOLESKY_MEMORY_BUDGET`][ordito.cholesky.CHOLESKY_MEMORY_BUDGET].
    RuntimeError
        If ``vertices``, ``faces`` and ``uv_init`` are not on one device.

    See Also
    --------
    [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization]
        A start for any topology.
    [`arap`][ordito.parametrization.arap]
        The pinned ARAP map.
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices]

    Notes
    -----
    Ports ``igl::slim`` with ``SYMMETRIC_DIRICHLET`` and no constraints, which converges to the
    same chart from a fold-free start. Each proxy is a ``wp.mat22d`` operator over the vertices,
    factored by [`sparse_cholesky`][ordito.cholesky.sparse_cholesky] (device memory of the order of
    its fill-in, held until the call returns); it is refactored every eight iterations and the
    iterations between solve against the held factor with the current gradient, which the line
    search keeps descending; libigl refactors every iteration. The proxy's weights are capped
    where a face nears collapse, and its gradient with them, which bounds the operator's
    conditioning and keeps a nearly collapsed face of the start (as a Tutte map of a surface with
    a handle has) from cutting every step to nothing; the energy and the barrier stay exact.

    The iteration runs in ``float64``. Under [`is_deterministic`][ordito.config.is_deterministic]
    the chart repeats bit for bit; otherwise its last bits can move between calls on the CUDA
    device.

    Examples
    --------
    A cap started from a Tutte disk scaled to its area relaxes toward an isometry and stays
    fold-free:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.sphere_cap(angle=1.4, subdivisions=4)
    corners = faces.numpy().reshape(-1, 3)
    surface = float(od.triangles.face_normals_and_areas(vertices, faces)[1].numpy().sum())


    def chart_area(uv: np.ndarray) -> float:
        e1 = uv[corners[:, 1]] - uv[corners[:, 0]]
        e2 = uv[corners[:, 2]] - uv[corners[:, 0]]
        return float(np.abs(e1[:, 0] * e2[:, 1] - e1[:, 1] * e2[:, 0]).sum() / 2)


    boundary = od.boundary.longest_boundary_loop(vertices, faces)
    circle = od.parametrization.map_vertices_to_circle(vertices, boundary)
    disk = od.parametrization.tutte(
        vertices=vertices, faces=faces, boundary_indices=boundary, boundary_uv=circle
    ).numpy()
    start = wp.array(disk * np.sqrt(surface / chart_area(disk)), dtype=wp.vec2)
    uv = od.parametrization.slim(vertices, faces, start)
    print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
    print(f"{chart_area(uv.numpy()) / surface:.2f}")  # 1.01
    ```
    """
    require_same_device(vertices=vertices, faces=faces, uv_init=uv_init)
    if (
        vertices.dtype is not wp.vec3
        or faces.dtype is not wp.int32
        or faces.size % 3 != 0
        or uv_init.dtype is not wp.vec2
        or uv_init.size != vertices.size
    ):
        raise ValueError(
            "slim takes wp.vec3 vertices, a flat wp.int32 faces buffer of 3 * n_faces entries and "
            f"a wp.vec2 uv_init of one entry per vertex, got {vertices.size} "
            f"{vertices.dtype.__name__} vertices, {faces.size} {faces.dtype.__name__} faces and "
            f"{uv_init.size} {uv_init.dtype.__name__} uv_init"
        )
    if max_iterations < 0:
        raise ValueError(f"slim max_iterations must be >= 0, got {max_iterations}")
    if not (math.isfinite(tolerance) and tolerance >= 0.0):
        raise ValueError(f"slim tolerance must be finite and >= 0, got {tolerance}")
    device = vertices.device
    n_vertices = vertices.size
    n_faces = faces.size // 3
    out_uv = _launch.empty(n_vertices, dtype=wp.vec2, device=device)
    if n_vertices == 0:
        return out_uv
    if max_iterations == 0 or n_faces == 0:
        wp.copy(out_uv, uv_init)
        return out_uv

    gradients, areas, pattern, held = _slim_system(vertices, faces)
    offsets, columns, starts, order, anchor = pattern
    n_keys = _TWO_LEVEL_FACE_KEYS * n_faces + n_vertices
    analysis: od.cholesky.SparseCholesky | None = held
    face_blocks = kernel_reduce.blocks_1d(n_faces)
    start_areas, _ = _launch.block_partials(face_blocks, 1, wp.vec3d, device)
    _launch.launch_tiled(
        kernel_parametrization.start_chart_areas,
        dim=face_blocks,
        inputs=[vertices, faces, uv_init],
        outputs=[start_areas],
        block_dim=TILE_1D,
        device=device,
    )
    chart = _launch.empty(n_vertices, dtype=wp.vec2d, device=device)
    inverted = _launch.empty(n_faces, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_parametrization.slim_start,
        dim=max(n_vertices, n_faces),
        inputs=[uv_init, faces, gradients, areas, start_areas],
        outputs=[chart, inverted],
        device=device,
    )

    # The loop's buffers, none allocated inside it: the face terms, the proxy's blocks over the
    # stiffness pattern, the step and its right-hand side, and a slot (or partials buffer) per
    # iteration for the step bound, the trial energies, the accepted step and its energy.
    vertex_faces, vertex_offsets = od.adjacency.vertex_face_adjacency(faces, n_vertices=n_vertices)
    metric = _launch.empty(n_faces, dtype=wp.mat22d, device=device)
    force = _launch.empty(n_faces, dtype=wp.mat22d, device=device)
    blocks = od.array.bsr_from_csr(
        n_vertices,
        n_vertices,
        offsets,
        columns,
        _launch.empty(n_keys, dtype=wp.mat22d, device=device),
    )
    rhs = _launch.empty(n_vertices, dtype=wp.vec2d, device=device)
    step = _launch.empty(n_vertices, dtype=wp.vec2d, device=device)
    rhs_flat = rhs.view(wp.float64).flatten()
    step_flat = step.view(wp.float64).flatten()
    bounds = _launch.full(
        max_iterations, float(kernel_parametrization.SLIM_NO_BOUND), dtype=wp.float64, device=device
    )
    steps = _launch.zeros(3 * max_iterations, dtype=wp.float64, device=device)
    accepted, energies = (
        _launch.view(steps, 0, max_iterations),
        _launch.view(steps, max_iterations, 3 * max_iterations),
    )
    # The step bound and the trial energies fold a face a lane where the device allows.
    trial_width, trial_blocks = kernel_reduce.spanned_blocks_1d(n_faces, device)
    partial_size = _launch.block_partials_size(trial_blocks, 1)
    partials = _launch.zeros(
        partial_size * max_iterations,
        dtype=kernel_parametrization.slim_trials_vector,
        device=device,
    )
    factorization: od.cholesky.SparseCholesky | None = None
    for iteration in range(max_iterations):
        _launch.launch(
            kernel_parametrization.slim_face_terms,
            dim=n_faces,
            inputs=[chart, faces, gradients, areas, inverted],
            outputs=[metric, force],
            device=device,
        )
        if iteration % _SLIM_REFACTOR_EVERY == 0:
            _launch.launch(
                kernel_parametrization.slim_block_values,
                dim=n_keys,
                inputs=[offsets, starts, order, gradients, metric, anchor, wp.int32(n_vertices)],
                outputs=[blocks.values],
                device=device,
            )
            expanded = od.array.scalar_expansion(blocks)
            if factorization is None:
                assert analysis is not None
                factorization = analysis.with_expanded_operator(expanded)
                # The scalar analysis has served: the proxy's factorization holds its own.
                analysis = None
                # Every iteration solves into the same two buffers: recorded once, replayed.
                factorization.records_at_once = True
            else:
                factorization.refactor(expanded)
        assert factorization is not None
        _launch.launch(
            kernel_parametrization.slim_rhs,
            dim=n_vertices,
            inputs=[faces, vertex_faces, vertex_offsets, gradients, force],
            outputs=[rhs],
            device=device,
        )
        # The held factor's direction is all a step needs: the line search below decides how far
        # to move, so refining it against the proxy would buy nothing.
        factorization.solve(rhs_flat, step_flat, refine=False)
        _launch.launch_tiled(
            kernel_parametrization.slim_step_bound,
            dim=trial_blocks,
            inputs=[chart, step, faces, gradients, inverted, iteration, trial_width],
            outputs=[bounds],
            block_dim=TILE_1D,
            device=device,
        )
        trial_partials = _launch.view(
            partials, iteration * partial_size, (iteration + 1) * partial_size
        )
        _launch.launch_tiled(
            kernel_parametrization.slim_trial_energies,
            dim=trial_blocks,
            inputs=[chart, step, faces, gradients, areas, inverted, bounds, iteration, trial_width],
            outputs=[trial_partials],
            block_dim=TILE_1D,
            device=device,
        )
        _launch.launch(
            kernel_parametrization.slim_accept,
            dim=1,
            inputs=[trial_partials, bounds, wp.int32(iteration)],
            outputs=[accepted, energies],
            device=device,
        )
        _launch.launch(
            kernel_parametrization.slim_advance,
            dim=n_vertices,
            inputs=[step, accepted, wp.int32(iteration), chart],
            device=device,
        )
        if (iteration + 1) % _SLIM_REFACTOR_EVERY == 0 and iteration + 1 < max_iterations:
            # Read back: whether the period's iterations still lowered the energy decides whether
            # to issue more (read where the next refactor reads its pivots anyway).
            first = 2 * (iteration + 1 - _SLIM_REFACTOR_EVERY)
            period = read_values(energies, first, 2 * _SLIM_REFACTOR_EVERY)
            if float(period[0]) - float(period[-1]) <= tolerance * float(period[-1]):
                break
    _launch.launch(
        kernel_parametrization.slim_uv,
        dim=n_vertices,
        inputs=[chart, start_areas],
        outputs=[out_uv],
        device=device,
    )
    return out_uv

low_distortion_parametrization

low_distortion_parametrization(
    vertices: array[vec3],
    faces: array[int32],
    *,
    coarse_cell: float | None = None,
    normal: vec3 | None = None,
    iterations: int = 150,
    smoothing_passes: int = 3,
    smoothing_steps: int = 8,
    single_level_vertices: int = 6000,
) -> wp.array[wp.vec2]

Free-boundary chart of low ARAP distortion in the mesh's own units, for any topology.

Flattens an open surface -- with handles, several boundary loops, several components -- into a near-isometric chart with a free boundary: no vertex is pinned, no boundary shape is imposed and no initial map is needed. It minimizes the element ARAP energy sum_f A_f |J_f - R_f|^2 (one proper rotation per face) in two levels, because a chart's large-scale layout needs dozens of local/global iterations while depending only on the coarse shape:

  1. The vertices are clustered on a grid of cells of side coarse_cell. The clusters' means, joined by every face whose corners fall in three distinct clusters, form a coarse mesh. Each coarse face is wound as the fine face that spans it, so a flat sheet's coarse mesh is flat.
  2. ARAP is iterated on the coarse mesh from its projection onto the plane of normal. Each global step is proximal, (K + epsilon I) U = B + epsilon U_prev, with epsilon a millionth of the mean stiffness diagonal: it removes the translations of every piece the clustering disconnects and keeps each where it started, and changes nothing at convergence. The system is factored once.
  3. Each vertex takes its cluster's UV plus its offset from the cluster's mean, carried by the cluster's area-weighted mean Jacobian; a cluster no coarse face touches borrows the nearest covered cluster's.
  4. smoothing_passes ARAP passes on the full mesh repair the fine detail, each global step cut short after smoothing_steps Jacobi-preconditioned conjugate-gradient steps from the current chart. The full mesh's system is applied face by face, never assembled.

A mesh of at most single_level_vertices vertices, or one whose clustering leaves fewer than 16 coarse faces or more clusters than half its vertices, is iterated directly as in step 2, from its own projection. arap_parametrization starts from a harmonic, Tutte or LSCM map instead.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Faces of no area are ignored.

required
coarse_cell float | None

Side of the grid cells the vertices are clustered on, in the mesh's units: a few times the mesh's edge length, and smaller than the gaps between sheets that must not be welded together (two sheets closer than a cell share clusters, which folds the chart there). None takes five times the mean edge length (mean_edge_length). The iterations also stop once one moves no vertex by more than a thousandth of it.

None
normal vec3 | None

Normal of the plane the start is projected onto (any length but zero). None takes the plane fitted to the longest boundary loop, the rim a scan crop or a disk is viewed through, or the vertices' best-fit plane on a mesh with no boundary.

None
iterations int

ARAP iteration budget on the coarse mesh (or on the mesh itself when it is iterated directly). 0 keeps the projection.

150
smoothing_passes int

ARAP passes on the full mesh after the coarse level.

3
smoothing_steps int

Conjugate-gradient steps of each smoothing pass.

8
single_level_vertices int

A mesh of at most this many vertices is iterated directly, without a coarse level.

6000

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device, in the mesh's units, with the faces mostly counter-clockwise; the rotation is unspecified. A vertex no face uses follows its cluster, or keeps its projection when the mesh is iterated directly. Empty for an empty mesh.

Raises:

Type Description
ValueError

If vertices is not wp.vec3 or faces not wp.int32 with a multiple of three entries, if coarse_cell is given and not a positive finite number, if normal is zero or not finite, if iterations, smoothing_passes, smoothing_steps or single_level_vertices is negative, if a vertex coordinate is not finite, if no face has a positive area, or if coarse_cell is so small against the mesh that the grid's cells or clusters cannot be numbered.

RuntimeError

If vertices and faces are not on one device.

See Also

arap_parametrization arap The pinned, warm-started ARAP map. lscm A free-boundary conformal map. face_flipped_indices

Notes

The chart approximates a converged full-resolution element ARAP: within a few points of its mean distortion. It is not guaranteed free of inverted faces, and where the grid welds sheets that pass closer than a cell, or squashes a handle, it leaves more of them than a full-resolution solve would.

The coarse level's sums and its solve run in float64. Under is_deterministic the chart repeats bit for bit; otherwise its last bits can move between calls on the CUDA device.

Examples:

A flat sheet has an exact answer, an isometry, which the chart reproduces:

import numpy as np

import ordito as od

vertices, faces = od.creation.grid(count=(41, 41))
uv = od.parametrization.low_distortion_parametrization(vertices, faces)
corners_np = vertices.numpy()[faces.numpy().reshape(-1, 3)]
corners_uv = uv.numpy()[faces.numpy().reshape(-1, 3)]
lengths_np = np.linalg.norm(corners_np - np.roll(corners_np, 1, axis=1), axis=2)
lengths_uv = np.linalg.norm(corners_uv - np.roll(corners_uv, 1, axis=1), axis=2)
print(uv.shape)  # (1681,)
print(np.allclose(lengths_uv, lengths_np, atol=1e-5))  # True
print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
Source code in ordito/parametrization.py
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
def low_distortion_parametrization(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    coarse_cell: float | None = None,
    normal: wp.vec3 | None = None,
    iterations: int = 150,
    smoothing_passes: int = 3,
    smoothing_steps: int = 8,
    single_level_vertices: int = 6_000,
) -> wp.array[wp.vec2]:
    """
    Free-boundary chart of low ARAP distortion in the mesh's own units, for any topology.

    Flattens an open surface -- with handles, several boundary loops, several components -- into a
    near-isometric chart with a free boundary: no vertex is pinned, no boundary shape is imposed
    and no initial map is needed. It minimizes the element ARAP energy ``sum_f A_f |J_f - R_f|^2``
    (one proper rotation per face) in two levels, because a chart's large-scale layout needs dozens
    of local/global iterations while depending only on the coarse shape:

    1. The vertices are clustered on a grid of cells of side ``coarse_cell``. The clusters' means,
       joined by every face whose corners fall in three distinct clusters, form a coarse mesh. Each
       coarse face is wound as the fine face that spans it, so a flat sheet's coarse mesh is flat.
    2. ARAP is iterated on the coarse mesh from its projection onto the plane of ``normal``. Each
       global step is proximal, ``(K + epsilon I) U = B + epsilon U_prev``, with ``epsilon`` a
       millionth of the mean stiffness diagonal: it removes the translations of every piece the
       clustering disconnects and keeps each where it started, and changes nothing at
       convergence. The system is factored once.
    3. Each vertex takes its cluster's UV plus its offset from the cluster's mean, carried by the
       cluster's area-weighted mean Jacobian; a cluster no coarse face touches borrows the nearest
       covered cluster's.
    4. ``smoothing_passes`` ARAP passes on the full mesh repair the fine detail, each global step
       cut short after ``smoothing_steps`` Jacobi-preconditioned conjugate-gradient steps from the
       current chart. The full mesh's system is applied face by face, never assembled.

    A mesh of at most ``single_level_vertices`` vertices, or one whose clustering leaves fewer
    than 16 coarse faces or more clusters than half its vertices, is iterated directly as in
    step 2, from its own projection.
    [`arap_parametrization`][ordito.parametrization.arap_parametrization] starts from a harmonic,
    Tutte or LSCM map instead.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Faces of no area are ignored.
    coarse_cell
        Side of the grid cells the vertices are clustered on, in the mesh's units: a few times
        the mesh's edge length, and smaller than the gaps between sheets that must not be welded
        together (two sheets closer than a cell share clusters, which folds the chart there).
        ``None`` takes five times the mean edge length
        ([`mean_edge_length`][ordito.edges.mean_edge_length]). The iterations also stop once one
        moves no vertex by more than a thousandth of it.
    normal
        Normal of the plane the start is projected onto (any length but zero). ``None`` takes the
        plane fitted to the longest boundary loop, the rim a scan crop or a disk is viewed through,
        or the vertices' best-fit plane on a mesh with no boundary.
    iterations
        ARAP iteration budget on the coarse mesh (or on the mesh itself when it is iterated
        directly). ``0`` keeps the projection.
    smoothing_passes
        ARAP passes on the full mesh after the coarse level.
    smoothing_steps
        Conjugate-gradient steps of each smoothing pass.
    single_level_vertices
        A mesh of at most this many vertices is iterated directly, without a coarse level.

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``, in the mesh's units, with the
        faces mostly counter-clockwise; the rotation is unspecified. A vertex no face uses follows
        its cluster, or keeps its projection when the mesh is iterated directly. Empty for an
        empty mesh.

    Raises
    ------
    ValueError
        If ``vertices`` is not ``wp.vec3`` or ``faces`` not ``wp.int32`` with a multiple of three
        entries, if ``coarse_cell`` is given and not a positive finite number, if ``normal`` is
        zero or not finite, if ``iterations``, ``smoothing_passes``, ``smoothing_steps`` or
        ``single_level_vertices`` is negative, if a vertex coordinate is not finite, if no face has
        a positive area, or if ``coarse_cell`` is so small against the mesh that the grid's cells
        or clusters cannot be numbered.
    RuntimeError
        If ``vertices`` and ``faces`` are not on one device.

    See Also
    --------
    [`arap_parametrization`][ordito.parametrization.arap_parametrization]
    [`arap`][ordito.parametrization.arap]
        The pinned, warm-started ARAP map.
    [`lscm`][ordito.parametrization.lscm]
        A free-boundary conformal map.
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices]

    Notes
    -----
    The chart approximates a converged full-resolution element ARAP: within a few points of its
    mean distortion. It is not guaranteed free of inverted faces, and where the grid welds sheets
    that pass closer than a cell, or squashes a handle, it leaves more of them than a
    full-resolution solve would.

    The coarse level's sums and its solve run in ``float64``. Under
    [`is_deterministic`][ordito.config.is_deterministic] the chart repeats bit for bit; otherwise
    its last bits can move between calls on the CUDA device.

    Examples
    --------
    A flat sheet has an exact answer, an isometry, which the chart reproduces:

    ```python
    import numpy as np

    import ordito as od

    vertices, faces = od.creation.grid(count=(41, 41))
    uv = od.parametrization.low_distortion_parametrization(vertices, faces)
    corners_np = vertices.numpy()[faces.numpy().reshape(-1, 3)]
    corners_uv = uv.numpy()[faces.numpy().reshape(-1, 3)]
    lengths_np = np.linalg.norm(corners_np - np.roll(corners_np, 1, axis=1), axis=2)
    lengths_uv = np.linalg.norm(corners_uv - np.roll(corners_uv, 1, axis=1), axis=2)
    print(uv.shape)  # (1681,)
    print(np.allclose(lengths_uv, lengths_np, atol=1e-5))  # True
    print(od.parametrization.face_flipped_indices(uv, faces).shape)  # (0,)
    ```
    """
    name = "low_distortion_parametrization"
    bounds = _low_distortion_bounds(
        name,
        vertices,
        faces,
        (
            ("iterations", iterations),
            ("smoothing_passes", smoothing_passes),
            ("smoothing_steps", smoothing_steps),
            ("single_level_vertices", single_level_vertices),
        ),
    )
    if coarse_cell is not None and not (math.isfinite(coarse_cell) and coarse_cell > 0.0):
        raise ValueError(f"{name} coarse_cell must be positive and finite, got {coarse_cell}")
    if normal is not None:
        length = math.sqrt(sum(float(c) ** 2 for c in normal))
        if not (math.isfinite(length) and length > 0.0):
            raise ValueError(f"{name} normal must be non-zero and finite, got {normal}")
    if bounds is None:
        return _launch.empty(0, dtype=wp.vec2, device=vertices.device)
    low, high = bounds
    if coarse_cell is None:
        coarse_cell = _DEFAULT_CELL_EDGES * od.edges.mean_edge_length(vertices, faces)
    plane_normal = _projection_normal(vertices, faces, normal)

    settled = _TWO_LEVEL_SETTLED * coarse_cell
    chart = None
    if vertices.size > single_level_vertices:
        chart = _two_level_chart(
            vertices,
            faces,
            low,
            high,
            coarse_cell,
            plane_normal,
            iterations,
            settled,
            smoothing_passes,
            smoothing_steps,
        )
    if chart is None:
        vertex_faces, offsets = od.adjacency.vertex_face_adjacency(faces, n_vertices=vertices.size)
        chart = _proximal_arap(
            od.array.astype(vertices, wp.vec3d),
            vertices,
            faces,
            vertex_faces,
            offsets,
            iterations,
            settled,
            normal=plane_normal,
        )
    return _chart_uv(chart)

arap_parametrization

arap_parametrization(
    vertices: array[vec3],
    faces: array[int32],
    *,
    init: Literal["harmonic", "tutte", "lscm"] = "harmonic",
    iterations: int = 150,
) -> wp.array[wp.vec2]

Free-boundary chart of low ARAP distortion, from a harmonic, Tutte or LSCM start.

The counterpart of low_distortion_parametrization started from a classic map: the same pin-free element ARAP energy sum_f A_f |J_f - R_f|^2 and free boundary, started from a map of the whole mesh instead of a coarse level, and iterated on the mesh itself, each global step a factored solve, until an iteration moves no vertex by more than 5e-3 mean edge lengths. A start's distortion is large-scale, which only whole solves repair.

The start is harmonic or tutte with the longest boundary loop placed on a circle by map_vertices_to_circle and any other loop free, or lscm with two vertices half that loop apart pinned; it is scaled to the mesh's area and mirrored if its faces wind clockwise on the whole, since ARAP fits proper rotations and cannot unmirror it. The same starts as slim_parametrization's.

The mesh needs one connected component with a boundary loop, but need not be a disk. On a surface with a handle or several holes the start inverts some faces (a handle forces it), and ARAP, which has no barrier against folding, may keep some of them inverted; check with face_flipped_indices.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer of one connected surface with at least one boundary loop. Faces of no area are ignored.

required
init Literal['harmonic', 'tutte', 'lscm']

The start: "harmonic" (default), "tutte" or "lscm".

'harmonic'
iterations int

ARAP iteration budget. 0 keeps the scaled start.

150

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device, in the mesh's units, with the faces mostly counter-clockwise; the rotation is unspecified. Empty for an empty mesh.

Raises:

Type Description
ValueError

If vertices is not wp.vec3 or faces not wp.int32 with a multiple of three entries, if init is not one of the three, if iterations is negative, if a vertex coordinate is not finite, if no face has a positive area, or if the mesh has no boundary loop or more than one connected component.

RuntimeError

If vertices and faces are not on one device.

See Also

low_distortion_parametrization The same energy from a coarse level, closed meshes included. slim_parametrization The least symmetric Dirichlet distortion from the same starts. arap The pinned, warm-started ARAP map.

Notes

The factored iterations' sums and solves run in float64. Under is_deterministic the chart repeats bit for bit; otherwise its last bits can move between calls on the CUDA device.

Examples:

A curved cap from each start, its edges kept at the surface's mean length:

import numpy as np

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
corners = faces.numpy().reshape(-1, 3)


def mean_edge(points: np.ndarray) -> str:
    triangles = points[corners]
    lengths = np.linalg.norm(triangles - np.roll(triangles, 1, axis=1), axis=2)
    return f"{lengths.mean():.3f}"


charts = [
    od.parametrization.arap_parametrization(vertices, faces, init=init)
    for init in ("harmonic", "tutte", "lscm")
]
print(mean_edge(vertices.numpy()))  # 0.134
print([mean_edge(uv.numpy()) for uv in charts])  # ['0.134', '0.134', '0.134']
print(od.parametrization.face_flipped_indices(charts[0], faces).shape)  # (0,)
Source code in ordito/parametrization.py
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
def arap_parametrization(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    init: Literal["harmonic", "tutte", "lscm"] = "harmonic",
    iterations: int = 150,
) -> wp.array[wp.vec2]:
    """
    Free-boundary chart of low ARAP distortion, from a harmonic, Tutte or LSCM start.

    The counterpart of
    [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization]
    started from a classic map: the same pin-free element ARAP energy ``sum_f A_f |J_f - R_f|^2``
    and free boundary, started from a map of the whole mesh instead of a coarse level, and iterated
    on the mesh itself, each global step a factored solve, until an iteration moves no vertex by
    more than ``5e-3`` mean edge lengths. A start's distortion is large-scale, which only whole
    solves repair.

    The start is [`harmonic`][ordito.parametrization.harmonic] or
    [`tutte`][ordito.parametrization.tutte] with the longest boundary loop placed on a circle by
    [`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle] and any other loop
    free, or [`lscm`][ordito.parametrization.lscm] with two vertices half that loop apart pinned;
    it is scaled to the mesh's area and mirrored if its faces wind clockwise on the whole, since
    ARAP fits proper rotations and cannot unmirror it. The same starts as
    [`slim_parametrization`][ordito.parametrization.slim_parametrization]'s.

    The mesh needs one connected component with a boundary loop, but need not be a disk. On a
    surface with a handle or several holes the start inverts some faces (a handle forces it), and
    ARAP, which has no barrier against folding, may keep some of them inverted; check with
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices].

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer of one connected surface with at least one
        boundary loop. Faces of no area are ignored.
    init
        The start: ``"harmonic"`` (default), ``"tutte"`` or ``"lscm"``.
    iterations
        ARAP iteration budget. ``0`` keeps the scaled start.

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``, in the mesh's units, with the
        faces mostly counter-clockwise; the rotation is unspecified. Empty for an empty mesh.

    Raises
    ------
    ValueError
        If ``vertices`` is not ``wp.vec3`` or ``faces`` not ``wp.int32`` with a multiple of three
        entries, if ``init`` is not one of the three, if ``iterations`` is negative, if a vertex
        coordinate is not finite, if no face has a positive area, or if the mesh has no boundary
        loop or more than one connected component.
    RuntimeError
        If ``vertices`` and ``faces`` are not on one device.

    See Also
    --------
    [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization]
        The same energy from a coarse level, closed meshes included.
    [`slim_parametrization`][ordito.parametrization.slim_parametrization]
        The least symmetric Dirichlet distortion from the same starts.
    [`arap`][ordito.parametrization.arap]
        The pinned, warm-started ARAP map.

    Notes
    -----
    The factored iterations' sums and solves run in ``float64``. Under
    [`is_deterministic`][ordito.config.is_deterministic] the chart repeats bit for bit; otherwise
    its last bits can move between calls on the CUDA device.

    Examples
    --------
    A curved cap from each start, its edges kept at the surface's mean length:

    ```python
    import numpy as np

    import ordito as od

    vertices, faces = od.creation.sphere_cap(angle=1.0, subdivisions=3)
    corners = faces.numpy().reshape(-1, 3)


    def mean_edge(points: np.ndarray) -> str:
        triangles = points[corners]
        lengths = np.linalg.norm(triangles - np.roll(triangles, 1, axis=1), axis=2)
        return f"{lengths.mean():.3f}"


    charts = [
        od.parametrization.arap_parametrization(vertices, faces, init=init)
        for init in ("harmonic", "tutte", "lscm")
    ]
    print(mean_edge(vertices.numpy()))  # 0.134
    print([mean_edge(uv.numpy()) for uv in charts])  # ['0.134', '0.134', '0.134']
    print(od.parametrization.face_flipped_indices(charts[0], faces).shape)  # (0,)
    ```
    """
    name = "arap_parametrization"
    bounds = _low_distortion_bounds(name, vertices, faces, (("iterations", iterations),))
    if init not in _MAP_STARTS:
        raise ValueError(f"{name} init must be one of {_MAP_STARTS}, got {init!r}")
    if bounds is None:
        return _launch.empty(0, dtype=wp.vec2, device=vertices.device)
    settled = _TWO_LEVEL_SETTLED * _DEFAULT_CELL_EDGES * od.edges.mean_edge_length(vertices, faces)
    vertex_faces, offsets = od.adjacency.vertex_face_adjacency(faces, n_vertices=vertices.size)
    chart = _proximal_arap(
        od.array.astype(vertices, wp.vec3d),
        vertices,
        faces,
        vertex_faces,
        offsets,
        iterations,
        settled,
        start=_start_chart(name, vertices, faces, init),
    )
    return _chart_uv(chart)

slim_parametrization

slim_parametrization(
    vertices: array[vec3],
    faces: array[int32],
    *,
    init: Literal["free", "harmonic", "tutte", "lscm"]
    | None = None,
    max_iterations: int = 100,
    tolerance: float = 0.001,
) -> wp.array[wp.vec2]

Free-boundary chart of least symmetric Dirichlet distortion, from a start it builds (SLIM).

The whole unwrap in one call: a start, then slim from it to the least sum_f A_f (s1^2 + s2^2 + s1^-2 + s2^-2), with a free boundary and no pins. The start is

each of the last three scaled to the mesh's area and mirrored if it winds clockwise, as arap_parametrization builds them. A start may invert or squash flat some faces (a handle forces some): slim holds those by an unbarriered ARAP term and keeps every other face upright. Every start reaches about the same distortion; they differ in time and in the layout of a long surface, which a Tutte or LSCM start unbends more than the free chart does.

A face the start has the right way round and not squashed flat never inverts. A Tutte map of a disk inverts none (its boundary is convex), so on a disk the default start is Tutte, and the chart folds no face unless the start squashed one a thousandfold.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Faces of no area are ignored.

required
init Literal['free', 'harmonic', 'tutte', 'lscm'] | None

The start: "free", "harmonic", "tutte" or "lscm". None takes "tutte" for a disk (one connected component with one boundary loop and Euler characteristic 1) and "free" otherwise.

None
max_iterations int

Forwarded to slim. max_iterations=0 returns the start.

100
tolerance int

Forwarded to slim. max_iterations=0 returns the start.

100

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device, in the mesh's units, with the faces mostly counter-clockwise; the rotation is unspecified. Empty for an empty mesh.

Raises:

Type Description
ValueError

If vertices is not wp.vec3 or faces not wp.int32 with a multiple of three entries, if init is not one of the four, if max_iterations is negative or tolerance negative or not finite, if a vertex coordinate is not finite, if no face has a positive area, if init is "harmonic", "tutte" or "lscm" and the mesh has no boundary loop or more than one connected component, or if the factorization of the proxy would exceed CHOLESKY_MEMORY_BUDGET.

RuntimeError

If vertices and faces are not on one device.

See Also

slim The iteration, from a start of the caller's. low_distortion_parametrization arap_parametrization The ARAP charts.

Notes

Under is_deterministic the chart repeats bit for bit; otherwise its last bits can move between calls on the CUDA device.

Examples:

Every start of a cap lands on the same fold-free chart:

import numpy as np

import ordito as od

vertices, faces = od.creation.sphere_cap(angle=1.4, subdivisions=4)
corners = faces.numpy().reshape(-1, 3)


def mean_edge(points: np.ndarray) -> str:
    triangles = points[corners]
    lengths = np.linalg.norm(triangles - np.roll(triangles, 1, axis=1), axis=2)
    return f"{lengths.mean():.3f}"


charts = [
    od.parametrization.slim_parametrization(vertices, faces, init=init)
    for init in ("free", "harmonic", "tutte", "lscm")
]
print(mean_edge(vertices.numpy()))  # 0.091
print([mean_edge(uv.numpy()) for uv in charts])  # ['0.091', '0.091', '0.091', '0.091']
flipped = [od.parametrization.face_flipped_indices(uv, faces).size for uv in charts]
print(flipped)  # [0, 0, 0, 0]
Source code in ordito/parametrization.py
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
def slim_parametrization(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    init: Literal["free", "harmonic", "tutte", "lscm"] | None = None,
    max_iterations: int = 100,
    tolerance: float = 1e-3,
) -> wp.array[wp.vec2]:
    """
    Free-boundary chart of least symmetric Dirichlet distortion, from a start it builds (SLIM).

    The whole unwrap in one call: a start, then [`slim`][ordito.parametrization.slim] from it to
    the least ``sum_f A_f (s1^2 + s2^2 + s1^-2 + s2^-2)``, with a free boundary and no pins. The
    start is

    - ``"free"``: the ARAP chart of
      [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization],
      for any topology, closed meshes included, and already near the answer;
    - ``"harmonic"`` or ``"tutte"``: the [`harmonic`][ordito.parametrization.harmonic] or
      [`tutte`][ordito.parametrization.tutte] map with the longest boundary loop on a circle
      ([`map_vertices_to_circle`][ordito.parametrization.map_vertices_to_circle]), any other
      loop free;
    - ``"lscm"``: [`lscm`][ordito.parametrization.lscm] with two vertices half the longest loop
      apart pinned;

    each of the last three scaled to the mesh's area and mirrored if it winds clockwise, as
    [`arap_parametrization`][ordito.parametrization.arap_parametrization] builds them. A start
    may invert or squash flat some faces (a handle forces some): ``slim`` holds those by an
    unbarriered ARAP term and keeps every other face upright. Every start
    reaches about the same distortion; they differ in time and in the layout of a long surface,
    which a Tutte or LSCM start unbends more than the free chart does.

    A face the start has the right way round and not squashed flat never inverts. A Tutte map of a
    disk inverts none (its boundary is convex), so on a disk the default start is Tutte, and the
    chart folds no face unless the start squashed one a thousandfold.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Faces of no area are ignored.
    init
        The start: ``"free"``, ``"harmonic"``, ``"tutte"`` or ``"lscm"``. ``None`` takes
        ``"tutte"`` for a disk (one connected component with one boundary loop and Euler
        characteristic 1) and ``"free"`` otherwise.
    max_iterations, tolerance
        Forwarded to [`slim`][ordito.parametrization.slim]. ``max_iterations=0`` returns the
        start.

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``, in the mesh's units, with the
        faces mostly counter-clockwise; the rotation is unspecified. Empty for an empty mesh.

    Raises
    ------
    ValueError
        If ``vertices`` is not ``wp.vec3`` or ``faces`` not ``wp.int32`` with a multiple of three
        entries, if ``init`` is not one of the four, if ``max_iterations`` is negative or
        ``tolerance`` negative or not finite, if a vertex coordinate is not finite, if no face has a
        positive area, if ``init`` is ``"harmonic"``, ``"tutte"`` or ``"lscm"`` and the mesh has no
        boundary loop or more than one connected component, or if the factorization of the proxy
        would exceed
        [`CHOLESKY_MEMORY_BUDGET`][ordito.cholesky.CHOLESKY_MEMORY_BUDGET].
    RuntimeError
        If ``vertices`` and ``faces`` are not on one device.

    See Also
    --------
    [`slim`][ordito.parametrization.slim]
        The iteration, from a start of the caller's.
    [`low_distortion_parametrization`][ordito.parametrization.low_distortion_parametrization]
    [`arap_parametrization`][ordito.parametrization.arap_parametrization]
        The ARAP charts.

    Notes
    -----
    Under [`is_deterministic`][ordito.config.is_deterministic] the chart repeats bit for bit;
    otherwise its last bits can move between calls on the CUDA device.

    Examples
    --------
    Every start of a cap lands on the same fold-free chart:

    ```python
    import numpy as np

    import ordito as od

    vertices, faces = od.creation.sphere_cap(angle=1.4, subdivisions=4)
    corners = faces.numpy().reshape(-1, 3)


    def mean_edge(points: np.ndarray) -> str:
        triangles = points[corners]
        lengths = np.linalg.norm(triangles - np.roll(triangles, 1, axis=1), axis=2)
        return f"{lengths.mean():.3f}"


    charts = [
        od.parametrization.slim_parametrization(vertices, faces, init=init)
        for init in ("free", "harmonic", "tutte", "lscm")
    ]
    print(mean_edge(vertices.numpy()))  # 0.091
    print([mean_edge(uv.numpy()) for uv in charts])  # ['0.091', '0.091', '0.091', '0.091']
    flipped = [od.parametrization.face_flipped_indices(uv, faces).size for uv in charts]
    print(flipped)  # [0, 0, 0, 0]
    ```
    """
    name = "slim_parametrization"
    bounds = _low_distortion_bounds(name, vertices, faces, (("max_iterations", max_iterations),))
    if init is not None and init not in _SLIM_STARTS:
        raise ValueError(f"{name} init must be one of {_SLIM_STARTS}, got {init!r}")
    if not (math.isfinite(tolerance) and tolerance >= 0.0):
        raise ValueError(f"{name} tolerance must be finite and >= 0, got {tolerance}")
    if bounds is None:
        return _launch.empty(0, dtype=wp.vec2, device=vertices.device)
    loop = None
    if init is None:
        loop, _ = _disk_loop(vertices, faces)
        init = "free" if loop is None else "tutte"
    if init == "free":
        start = low_distortion_parametrization(vertices, faces)
    else:
        start = _chart_uv(_start_chart(name, vertices, faces, init, loop=loop))
    return slim(vertices, faces, start, max_iterations=max_iterations, tolerance=tolerance)

lscm

lscm(
    mesh: Trimesh,
    pinned_indices: array[int32],
    pinned_uv: array[vec2],
    /,
    *,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]
lscm(
    vertices: array[vec3],
    faces: array[int32],
    pinned_indices: array[int32],
    pinned_uv: array[vec2],
    /,
    *,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]
lscm(
    mesh: Trimesh | array[vec3] | None = None,
    faces: array[int32] | None = None,
    pinned_indices: array[int32]
    | array[vec2]
    | None = None,
    pinned_uv: array[vec2] | None = None,
    *,
    vertices: array[vec3] | None = None,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]

Constrained least-squares conformal map.

Computes the conformal (angle-preserving) parametrization that minimizes the LSCM (Levy) conformal energy subject to a set of pinned vertices, by solving a single quadratic program over the stacked [u; v] vector of 2 * n_vertices unknowns with the LSCM Hessian lscm_hessian as the operator. Unlike harmonic / tutte (which pin the whole boundary and solve two independent columns), LSCM couples u and v through the boundary vector-area term, so it needs only a few pins — typically two — to fix the remaining similarity-transform (rotation + scale + translation) degree of freedom.

On a mesh of fewer than 4 000 vertices the interior system is solved with conjugate gradient, verified as min_quad_with_fixed verifies it, with a sparse Cholesky factorization taking over a solve that does not converge within its budget; from 4 000 vertices it is factored at once, since with only a few pins its iteration grows faster with the mesh than the factorization does. Closed meshes are valid input: the boundary vector-area matrix is then zero and the Hessian reduces to -repdiag(L, 2). Given a Trimesh, a factorization is kept on it; one prepared with FixedVertexSolver.factor ("lscm", the pinned indices) answers every later call pinning the same vertices with no iteration.

Parameters:

Name Type Description Default
mesh Trimesh | array[vec3] | None

The mesh, as an ordito.mesh.Trimesh; or, in its place, vertices and faces.

None
vertices array[vec3] | None

(n_vertices,) mesh vertex positions.

None
faces array[int32] | None

(3 * n_faces,) triangle index buffer.

None
pinned_indices array[int32] | array[vec2] | None

(n_pinned,) indices of the pinned (constrained) vertices — igl's b. At least two are required (unless the mesh has fewer than two vertices) to remove the conformal map's similarity-transform null space.

None
pinned_uv array[vec2] | None

(n_pinned,) target UV positions for pinned_indices, in the same order (igl's bc).

None
solver Literal['auto', 'direct']

"auto" (default) solves by conjugate gradient, verified, and factors the system only when the iteration's result fails the check -- or at once on a mesh of 4 000 vertices or more, where a factorization costs less than the iteration. "direct" factors it at once (a sparse Cholesky); given a Trimesh, the factorization is kept on it, so every later call fixing the same vertices -- whatever their values -- is a factored solve with no iteration. Pays from about the second such call on a smaller mesh.

'auto'

Returns:

Type Description
array[vec2]

(n_vertices,) UV coordinates on vertices.device. Empty for an empty mesh.

Raises:

Type Description
ValueError

If fewer than two vertices are pinned (and the mesh has at least two vertices), if pinned_indices and pinned_uv have different lengths, if pinned_indices repeats a vertex or holds one outside [0, n_vertices), or if solver is not "auto" or "direct".

RuntimeError

If vertices, faces, pinned_indices and pinned_uv are not all on one device.

Warns:

Type Description
UserWarning

When no verified solution is reached (see min_quad_with_fixed).

See Also

lscm_hessian vector_area_matrix harmonic face_flipped_indices

Notes

The unknowns are stacked [u; v] (all u DOFs then all v DOFs), matching igl's lscm: pin i fixes DOF i (u) and DOF i + n_vertices (v). The returned Q of igl.lscm equals -repdiag(L, 2) - 2 A exactly (see lscm_hessian).

Examples:

A flat grid with two opposite corners pinned where they are: the identity map is conformal, so LSCM recovers it:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(6, 6))
pinned = wp.array([0, 35], dtype=wp.int32)
pinned_uv = wp.array(vertices.numpy()[[0, 35], :2], dtype=wp.vec2)
uv = od.parametrization.lscm(
    vertices=vertices, faces=faces, pinned_indices=pinned, pinned_uv=pinned_uv
)
print(uv.shape)  # (36,)
print(np.allclose(uv.numpy(), vertices.numpy()[:, :2], atol=1e-5))  # True
Source code in ordito/parametrization.py
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
def lscm(
    mesh: Trimesh | wp.array[wp.vec3] | None = None,
    faces: wp.array[wp.int32] | None = None,
    pinned_indices: wp.array[wp.int32] | wp.array[wp.vec2] | None = None,
    pinned_uv: wp.array[wp.vec2] | None = None,
    *,
    vertices: wp.array[wp.vec3] | None = None,
    solver: Literal["auto", "direct"] = "auto",
) -> wp.array[wp.vec2]:
    """
    Constrained least-squares conformal map.

    Computes the conformal (angle-preserving) parametrization that minimizes the LSCM (Levy)
    conformal energy subject to a set of pinned vertices, by solving a single quadratic program
    over the stacked ``[u; v]`` vector of ``2 * n_vertices`` unknowns with the LSCM Hessian
    [`lscm_hessian`][ordito.energies.lscm_hessian] as the operator. Unlike
    [`harmonic`][ordito.parametrization.harmonic] / [`tutte`][ordito.parametrization.tutte] (which
    pin the whole boundary and solve two independent columns), LSCM couples ``u`` and ``v`` through
    the boundary vector-area term, so it needs only a few pins — typically **two** — to fix the
    remaining similarity-transform (rotation + scale + translation) degree of freedom.

    On a mesh of fewer than 4 000 vertices the interior system is solved with conjugate gradient,
    verified as [`min_quad_with_fixed`][ordito.linalg.min_quad_with_fixed] verifies it, with a
    sparse Cholesky factorization taking over a solve that does not converge within its budget;
    from 4 000 vertices it is factored at once, since with only a few pins its iteration grows
    faster with the mesh than the factorization does. Closed meshes are
    valid input: the boundary vector-area matrix is then zero and the Hessian reduces to
    ``-repdiag(L, 2)``. Given a `Trimesh`,
    a factorization is kept on it; one prepared with
    [`FixedVertexSolver.factor`][ordito.parametrization.FixedVertexSolver.factor] (``"lscm"``, the
    pinned indices) answers every later call pinning the same vertices with no iteration.

    Parameters
    ----------
    mesh
        The mesh, as an [`ordito.mesh.Trimesh`][ordito.mesh.Trimesh]; or, in its place,
        ``vertices`` and ``faces``.
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer.
    pinned_indices
        ``(n_pinned,)`` indices of the pinned (constrained) vertices — igl's ``b``. At least two are
        required (unless the mesh has fewer than two vertices) to remove the conformal map's
        similarity-transform null space.
    pinned_uv
        ``(n_pinned,)`` target UV positions for ``pinned_indices``, in the same order (igl's
        ``bc``).
    solver
        ``"auto"`` (default) solves by conjugate gradient, verified, and factors the system only
        when the iteration's result fails the check -- or at once on a mesh of 4 000 vertices or
        more, where a factorization costs less than the iteration. ``"direct"`` factors it at once
        (a sparse Cholesky); given a `Trimesh`, the factorization is kept on it, so every later
        call fixing the same vertices -- whatever their values -- is a factored solve with no
        iteration. Pays from about the second such call on a smaller mesh.

    Returns
    -------
    wp.array[wp.vec2]
        ``(n_vertices,)`` UV coordinates on ``vertices.device``. Empty for an empty mesh.

    Raises
    ------
    ValueError
        If fewer than two vertices are pinned (and the mesh has at least two vertices), if
        ``pinned_indices`` and ``pinned_uv`` have different lengths, if ``pinned_indices`` repeats
        a vertex or holds one outside ``[0, n_vertices)``, or if ``solver`` is not ``"auto"`` or
        ``"direct"``.
    RuntimeError
        If ``vertices``, ``faces``, ``pinned_indices`` and ``pinned_uv`` are not all on one device.

    Warns
    -----
    UserWarning
        When no verified solution is reached (see
        [`min_quad_with_fixed`][ordito.linalg.min_quad_with_fixed]).

    See Also
    --------
    [`lscm_hessian`][ordito.energies.lscm_hessian]
    [`vector_area_matrix`][ordito.energies.vector_area_matrix]
    [`harmonic`][ordito.parametrization.harmonic]
    [`face_flipped_indices`][ordito.parametrization.face_flipped_indices]

    Notes
    -----
    The unknowns are stacked ``[u; v]`` (all ``u`` DOFs then all ``v`` DOFs), matching igl's
    ``lscm``: pin ``i`` fixes DOF ``i`` (``u``) and DOF ``i + n_vertices`` (``v``). The returned
    ``Q`` of ``igl.lscm`` equals ``-repdiag(L, 2) - 2 A`` exactly (see
    [`lscm_hessian`][ordito.energies.lscm_hessian]).

    Examples
    --------
    A flat grid with two opposite corners pinned where they are: the identity map is conformal, so
    LSCM recovers it:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(6, 6))
    pinned = wp.array([0, 35], dtype=wp.int32)
    pinned_uv = wp.array(vertices.numpy()[[0, 35], :2], dtype=wp.vec2)
    uv = od.parametrization.lscm(
        vertices=vertices, faces=faces, pinned_indices=pinned, pinned_uv=pinned_uv
    )
    print(uv.shape)  # (36,)
    print(np.allclose(uv.numpy(), vertices.numpy()[:, :2], atol=1e-5))  # True
    ```
    """
    bound, owned, arguments = mesh_arguments(
        "lscm", mesh, vertices, faces, (pinned_indices, pinned_uv), 2
    )
    pinned_indices = cast("wp.array[wp.int32]", arguments[0])
    pinned_uv = cast("wp.array[wp.vec2]", arguments[1])
    _require_solver_name(solver, "lscm")
    require_same_device(
        vertices=bound.vertices,
        faces=bound.faces,
        pinned_indices=pinned_indices,
        pinned_uv=pinned_uv,
    )
    device = bound.device
    n = bound.n_vertices
    if n == 0:
        return _launch.empty(0, dtype=wp.vec2, device=device)

    n_pinned = pinned_indices.size
    _require_fixed_vertices(
        n_pinned,
        n,
        2,
        "lscm requires at least two pinned vertices to remove the conformal map's "
        f"similarity-transform null space; got {n_pinned}.",
    )
    fixed_mask, fixed_values = _pin_stacked(n, pinned_indices, pinned_uv, device)
    sol, free_map = _solve_fixed_vertices(
        bound,
        owned,
        "lscm",
        1,
        fixed_mask,
        odt.as_array2d(fixed_values, wp.float64),
        solver,
        2 * n_pinned,
    )
    out_uv = _launch.empty(n, dtype=wp.vec2, device=device)
    _launch.launch(
        kernel_parametrization.scatter_solution_stacked,
        dim=n,
        inputs=[fixed_mask, free_map, sol[0], fixed_values[0], out_uv],
        device=device,
    )
    return out_uv