Skip to content

ordito.homology

Homology generators: the loops that make a surface's topology, found by tree-cotree.

On a closed genus-g surface there are 2 * g independent loops that cannot be contracted to a point — two per handle, going around it and through it. They are what a cutting tool needs (cut along them and the surface opens into a disk), and what tells a parametrizer where its seams have to go.

The construction is Erickson & Whittlesey's tree-cotree decomposition, and it is a counting argument as much as an algorithm: take a spanning tree of the vertex graph, then a spanning tree of the dual graph that avoids the primal tree's edges, and every remaining edge closes exactly one independent loop. Euler's formula fixes how many are left: E - (V - 1) - (F - 1) = 2 - chi, which is 2 * g.

Unlike the rest of this package there is no reference implementation to compare against — potpourri3d does not expose geometry-central's homology code — so the tests check structural invariants instead: the loop count against euler_characteristic, and that every loop is a closed walk along real mesh edges that visits no vertex twice.

Functions:

Name Description
homology_generators

Non-contractible loops of the surface, as ordered vertex-index cycles.

homology_generators_with_offsets

Non-contractible loops of the surface, packed: every loop's vertices, then their offsets.

homology_generators

homology_generators(
    vertices: array[vec3],
    faces: array[int32],
    *,
    root: int | None = None,
    copy: bool = False,
    unique_edges: Array2dInt32 | None = None,
    edge_map: array[int32] | None = None,
) -> list[wp.array[wp.int32]]

Non-contractible loops of the surface, as ordered vertex-index cycles.

Returns 2 * g loops for a closed genus-g surface and none for a sphere. Each loop is a closed walk along mesh edges: consecutive entries share an edge, and so do the last and first (the start vertex is not repeated, matching boundary_loops).

The loops are a basis, not canonical: any generating set is as valid as any other. This one is the greedy system of loops through the root in the hop metric (Erickson and Whittlesey, Greedy optimal homotopy and homology generators, SODA 2005): the primal tree is a breadth-first tree from root, and the dual forest is a maximum spanning tree under the length of each edge's loop through the root, so each generator is the shortest loop through the root independent of the ones before it. A handle near the root therefore shows up as its own short loop rather than as part of a combination; one far from it can still be represented only through longer loops, so which loops come out depends on where the root is. The loops are as jagged as the tree, which is what shorten_loop is for. The basis is reproducible, and the same on every device: the primal tree resolves competing claims by lowest vertex index and the dual forest breaks equal loop lengths by lowest edge index, so neither depends on the order the threads ran in.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions. Only the count is used.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Must be a closed, connected, edge-manifold surface: the counting argument this rests on assumes it.

required
root int | None

Vertex the loops are based at, or None for a referenced vertex the connectivity fixes (the same one on every call and device). Must be a referenced vertex.

None
copy bool

Return independent buffers instead of views into one packed allocation.

False
unique_edges Array2dInt32 | None

(n_edges, 2) and (3 * n_faces,) optional precomputed edge numbering from edges_unique — pass both or neither — to spare the sort that otherwise builds it. Trimesh.edges_unique and Trimesh.edges_unique_inverse are the cached ones to pass.

None
edge_map Array2dInt32 | None

(n_edges, 2) and (3 * n_faces,) optional precomputed edge numbering from edges_unique — pass both or neither — to spare the sort that otherwise builds it. Trimesh.edges_unique and Trimesh.edges_unique_inverse are the cached ones to pass.

None

Returns:

Type Description
list[array[int32]]

One array of vertex indices per generator, on faces.device. Empty for a sphere, and for a mesh with no faces.

Raises:

Type Description
ValueError

If the mesh has a boundary, since a surface with boundary has a different homology basis (every boundary loop contributes one, and the tree-cotree count no longer applies), or if its referenced vertices are not all in one connected component, since the count is then a sum over components that a single pair of spanning trees does not produce, if root is not a referenced vertex, or if only one of unique_edges and edge_map is passed.

RuntimeError

If vertices, faces, unique_edges and edge_map are not all on one device.

See Also

homology_generators_with_offsets The same loops, packed into one buffer with their offsets. shorten_loop Shortens these loops within their homotopy class, keeping them on mesh edges. euler_characteristic Fixes how many loops there are: 2 * g == 2 - chi. boundary_loops

Examples:

A torus has genus 1, so two loops: one around the tube and one around the hole. A sphere has none:

import ordito as od

vertices, faces = od.creation.torus(1.0, 0.3, major_sections=16, minor_sections=8)
loops = od.homology.homology_generators(vertices, faces)
print(len(loops))  # 2
print(sorted(loop.size for loop in loops))  # [8, 16]

vertices, faces = od.creation.icosphere(subdivisions=2)
print(len(od.homology.homology_generators(vertices, faces)))  # 0
Source code in ordito/homology.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
def homology_generators(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    root: int | None = None,
    copy: bool = False,
    unique_edges: odt.Array2dInt32 | None = None,
    edge_map: wp.array[wp.int32] | None = None,
) -> list[wp.array[wp.int32]]:
    """
    Non-contractible loops of the surface, as ordered vertex-index cycles.

    Returns ``2 * g`` loops for a closed genus-``g`` surface and none for a sphere. Each loop is a
    closed walk along mesh edges: consecutive entries share an edge, and so do the last and first
    (the start vertex is not repeated, matching
    [`boundary_loops`][ordito.boundary.boundary_loops]).

    The loops are a *basis*, not canonical: any generating set is as valid as any other. This one
    is the **greedy system of loops through the root** in the hop metric (Erickson and Whittlesey,
    *Greedy optimal homotopy and homology generators*, SODA 2005): the primal tree is a
    breadth-first tree from ``root``, and the dual forest is a maximum spanning tree under the
    length of each edge's loop through the root, so each generator is the shortest loop through the
    root independent of the ones before it. A handle near the root therefore shows up as its own
    short loop rather than as part of a combination; one far from it can still be represented only
    through longer loops, so which loops come out depends on where the root is. The loops are as
    jagged as the tree, which is what [`shorten_loop`][ordito.geodesic_walk.shorten_loop] is for.
    The basis is **reproducible**, and the same on every device: the primal tree resolves competing
    claims by lowest vertex index and the dual forest breaks equal loop lengths by lowest edge
    index, so neither depends on the order the threads ran in.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions. Only the count is used.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Must be a closed, connected,
        edge-manifold surface: the counting argument this rests on assumes it.
    root
        Vertex the loops are based at, or ``None`` for a referenced vertex the connectivity fixes
        (the same one on every call and device). Must be a referenced vertex.
    copy
        Return independent buffers instead of views into one packed allocation.
    unique_edges, edge_map
        ``(n_edges, 2)`` and ``(3 * n_faces,)`` optional precomputed edge numbering from
        [`edges_unique`][ordito.edges.edges_unique] — pass both or neither — to spare the sort
        that otherwise builds it. [`Trimesh.edges_unique`][ordito.mesh.Trimesh.edges_unique] and
        [`Trimesh.edges_unique_inverse`][ordito.mesh.Trimesh.edges_unique_inverse] are the cached
        ones to pass.

    Returns
    -------
    list[wp.array[wp.int32]]
        One array of vertex indices per generator, on ``faces.device``. Empty for a
        sphere, and for a mesh with no faces.

    Raises
    ------
    ValueError
        If the mesh has a boundary, since a surface with boundary has a different homology basis
        (every boundary loop contributes one, and the tree-cotree count no longer applies), or if
        its referenced vertices are not all in one connected component, since the count is then a
        sum over components that a single pair of spanning trees does not produce, if ``root``
        is not a referenced vertex, or if only one of ``unique_edges`` and ``edge_map`` is passed.
    RuntimeError
        If ``vertices``, ``faces``, ``unique_edges`` and ``edge_map`` are not all on one device.

    See Also
    --------
    [`homology_generators_with_offsets`][ordito.homology.homology_generators_with_offsets]
        The same loops, packed into one buffer with their offsets.
    [`shorten_loop`][ordito.geodesic_walk.shorten_loop]
        Shortens these loops within their homotopy class, keeping them on mesh edges.
    [`euler_characteristic`][ordito.measures.euler_characteristic]
        Fixes how many loops there are: ``2 * g == 2 - chi``.
    [`boundary_loops`][ordito.boundary.boundary_loops]

    Examples
    --------
    A torus has genus 1, so two loops: one around the tube and one around the hole. A sphere has
    none:

    ```python
    import ordito as od

    vertices, faces = od.creation.torus(1.0, 0.3, major_sections=16, minor_sections=8)
    loops = od.homology.homology_generators(vertices, faces)
    print(len(loops))  # 2
    print(sorted(loop.size for loop in loops))  # [8, 16]

    vertices, faces = od.creation.icosphere(subdivisions=2)
    print(len(od.homology.homology_generators(vertices, faces)))  # 0
    ```
    """
    loops, offsets = homology_generators_with_offsets(
        vertices, faces, root=root, unique_edges=unique_edges, edge_map=edge_map
    )
    return od.array.split(loops, offsets, copy=copy)

homology_generators_with_offsets

homology_generators_with_offsets(
    vertices: array[vec3],
    faces: array[int32],
    *,
    root: int | None = None,
    unique_edges: Array2dInt32 | None = None,
    edge_map: array[int32] | None = None,
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]

Non-contractible loops of the surface, packed: every loop's vertices, then their offsets.

The packed form of homology_generators: the same basis in the same order, concatenated into one buffer with no per-loop Python object.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions. Only the count is used.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Must be a closed, connected, edge-manifold surface: the counting argument this rests on assumes it.

required
root int | None

Vertex the loops are based at, or None for a referenced vertex the connectivity fixes (the same one on every call and device). Must be a referenced vertex.

None
unique_edges Array2dInt32 | None

(n_edges, 2) and (3 * n_faces,) optional precomputed edge numbering from edges_unique — pass both or neither — to spare the sort that otherwise builds it. Trimesh.edges_unique and Trimesh.edges_unique_inverse are the cached ones to pass.

None
edge_map Array2dInt32 | None

(n_edges, 2) and (3 * n_faces,) optional precomputed edge numbering from edges_unique — pass both or neither — to spare the sort that otherwise builds it. Trimesh.edges_unique and Trimesh.edges_unique_inverse are the cached ones to pass.

None

Returns:

Name Type Description
loops array[int32]

(m,) every generator's vertex-index cycle, loop after loop, m == offsets[-1], on faces.device.

offsets array[int32]

(2 * g + 1,) total-terminated offsets, g the genus: loop i is loops[offsets[i] : offsets[i + 1]], and [0] for a sphere or a mesh with no faces.

Raises:

Type Description
ValueError

If the mesh has a boundary, its referenced vertices are not all in one connected component, root is not a referenced vertex, or only one of unique_edges and edge_map is passed (see homology_generators).

RuntimeError

If vertices, faces, unique_edges and edge_map are not all on one device.

See Also

homology_generators The same loops, one array each. shorten_loop_with_offsets Shortens them in the packed form.

Examples:

import ordito as od

vertices, faces = od.creation.torus(1.0, 0.3, major_sections=16, minor_sections=8)
loops, offsets = od.homology.homology_generators_with_offsets(vertices, faces)
print(offsets.numpy().tolist())  # [0, 8, 24]
print(loops.shape)  # (24,)
Source code in ordito/homology.py
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
258
259
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
349
350
351
352
353
354
355
356
357
358
def homology_generators_with_offsets(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    root: int | None = None,
    unique_edges: odt.Array2dInt32 | None = None,
    edge_map: wp.array[wp.int32] | None = None,
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]:
    """
    Non-contractible loops of the surface, packed: every loop's vertices, then their offsets.

    The packed form of [`homology_generators`][ordito.homology.homology_generators]: the same
    basis in the same order, concatenated into one buffer with no per-loop Python object.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions. Only the count is used.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Must be a closed, connected,
        edge-manifold surface: the counting argument this rests on assumes it.
    root
        Vertex the loops are based at, or ``None`` for a referenced vertex the connectivity fixes
        (the same one on every call and device). Must be a referenced vertex.
    unique_edges, edge_map
        ``(n_edges, 2)`` and ``(3 * n_faces,)`` optional precomputed edge numbering from
        [`edges_unique`][ordito.edges.edges_unique] — pass both or neither — to spare the sort
        that otherwise builds it. [`Trimesh.edges_unique`][ordito.mesh.Trimesh.edges_unique] and
        [`Trimesh.edges_unique_inverse`][ordito.mesh.Trimesh.edges_unique_inverse] are the cached
        ones to pass.

    Returns
    -------
    loops : wp.array[wp.int32]
        ``(m,)`` every generator's vertex-index cycle, loop after loop, ``m == offsets[-1]``, on
        ``faces.device``.
    offsets : wp.array[wp.int32]
        ``(2 * g + 1,)`` total-terminated offsets, ``g`` the genus: loop ``i`` is
        ``loops[offsets[i] : offsets[i + 1]]``, and ``[0]`` for a sphere or a mesh with no faces.

    Raises
    ------
    ValueError
        If the mesh has a boundary, its referenced vertices are not all in one connected
        component, ``root`` is not a referenced vertex, or only one of ``unique_edges`` and
        ``edge_map`` is passed (see [`homology_generators`][ordito.homology.homology_generators]).
    RuntimeError
        If ``vertices``, ``faces``, ``unique_edges`` and ``edge_map`` are not all on one device.

    See Also
    --------
    [`homology_generators`][ordito.homology.homology_generators]
        The same loops, one array each.
    [`shorten_loop_with_offsets`][ordito.geodesic_walk.shorten_loop_with_offsets]
        Shortens them in the packed form.

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

    vertices, faces = od.creation.torus(1.0, 0.3, major_sections=16, minor_sections=8)
    loops, offsets = od.homology.homology_generators_with_offsets(vertices, faces)
    print(offsets.numpy().tolist())  # [0, 8, 24]
    print(loops.shape)  # (24,)
    ```
    """
    require_same_device(
        vertices=vertices, faces=faces, unique_edges=unique_edges, edge_map=edge_map
    )
    device = faces.device
    n_vertices = vertices.size
    n_faces = faces.size // 3
    if root is not None and not 0 <= root < n_vertices:
        raise ValueError(f"root must index a vertex in [0, {n_vertices}), got {root}")
    if (unique_edges is None) != (edge_map is None):
        raise ValueError("pass unique_edges and edge_map together, or neither.")
    if n_vertices == 0 or n_faces == 0:
        return _launch.empty_packed(wp.int32, device)

    # One grouping of the edge rows answers everything: ``inverse`` maps each face corner to its
    # unique edge, and one scatter over it fills both the per-edge face count and the two incident
    # faces. That is the whole dual graph, indexed by unique edge — which is why nothing here needs
    # to locate a shared edge's row afterwards.
    if unique_edges is None or edge_map is None:
        unique_edges, inverse = od.edges.edges_unique(faces, n_vertices=n_vertices, validate=False)
    else:
        inverse = edge_map
    n_edges = int(unique_edges.shape[0])
    if n_edges == 0:
        # A face carries three edges, so no edges means no faces: vacuously closed, nothing to span
        # and nothing left over.
        return _launch.empty_packed(wp.int32, device)
    # Every ``int32`` table the decomposition works in dies with the call, so they are carved from
    # one allocation: the incidence below, the dual forest's labels and roots, the primal tree's
    # parents and depths (and on the CPU its traversal's queue), the loops' apexes, and last the
    # loops' ``(1, length)`` counts, the guards' count slots and the per-edge face count, adjacent
    # so that one memset clears the slots with the face count and one read takes the slots with
    # the counts' scanned total.
    serial = wp.get_device(device).is_cpu
    count_slots = kernel_homology.COUNT_SIZE
    edge_faces_flat, labels, roots, tree, apex, trace_and_counts = _launch.carve(
        wp.int32,
        [
            2 * n_edges,
            n_faces,
            n_faces,
            (3 if serial else 2) * n_vertices,
            n_edges,
            3 * n_edges + count_slots,
        ],
        device,
    )
    loop_counts = _launch.view(trace_and_counts, 0, 2 * n_edges)
    counts = _launch.view(trace_and_counts, 2 * n_edges, 2 * n_edges + count_slots)
    edge_face_count = _launch.view(
        trace_and_counts, 2 * n_edges + count_slots, 3 * n_edges + count_slots
    )
    _launch.zero_(_launch.view(trace_and_counts, 2 * n_edges, 3 * n_edges + count_slots))
    edge_faces = odt.as_array2d(edge_faces_flat.reshape((n_edges, 2)), wp.int32)
    _launch.launch(
        kernel_scatter.scatter_edge_incidence,
        dim=inverse.size,
        inputs=[inverse, edge_face_count, edge_faces],
        device=device,
    )

    # The vertex graph the primal tree spans. Unsorted rows, which the level loop cannot see: it
    # resolves competing claims by lowest vertex index, not by column position.
    neighbors, offsets = od.graph.edges_to_neighbor_lists(n_vertices, unique_edges, validate=False)
    # Every small ``int32`` buffer the decomposition needs, uploaded at once holding its initial
    # values: the primal level loop's state, the dual forest's merge flag and a caller's root. The
    # level loop's condition starts true because ``wp.capture_while`` reads it before the first
    # round; it claims level 1 first and nothing is claimed yet.
    small = _launch.array([1, 1, 0, 0, 0 if root is None else root], dtype=wp.int32, device=device)
    parents, distances = _primal_spanning_tree(
        offsets,
        neighbors,
        odt.as_dense(unique_edges[0] if root is None else small[_FOREST_MERGED.stop :]),
        odt.as_dense(small[_PRIMAL_STATE]),
        labels,
        tree,
    )

    # Both preconditions are counting questions, answered on the device into ``counts`` and read
    # back with the generators' total, after the dual forest: a guard that raises does not need to
    # raise early, and reading it here would leave the device idle while the host records the
    # forest's loop. The interior-edge count rides in the candidate mask below, which already tests
    # ``edge_face_count == 2``, so neither guard costs a pass of its own.
    #
    # A generator is an edge in neither tree. ``candidate`` starts as the edges the cotree is
    # allowed to cross -- interior, reached by the primal tree and not claimed by it -- and the
    # forest pass removes the ones it took, so the leftovers need no predicate of their own. The
    # reach test only matters on the raising path, where it keeps the tracer off the vertices the
    # tree never reached.
    candidate = _launch.empty(n_edges, dtype=wp.bool, device=device)
    vertex_blocks = kernel_reduce.blocks_1d(n_vertices)
    _launch.launch_tiled(
        kernel_homology.guards_and_dual_candidates,
        # The vertex fold at the reduce module's chunk width, then one *tile* per edge block: the
        # candidate mask writes an entry per edge as well as folding a count, so its per-edge
        # dimension has to stay in the grid.
        dim=vertex_blocks + (n_edges + TILE_1D - 1) // TILE_1D,
        inputs=[
            offsets,
            distances,
            wp.int32(vertex_blocks),
            unique_edges,
            edge_face_count,
            parents,
        ],
        outputs=[candidate, counts],
        block_dim=TILE_1D,
        device=device,
    )
    _remove_dual_spanning_forest(
        candidate,
        edge_faces,
        unique_edges,
        distances,
        labels,
        roots,
        odt.as_dense(small[_FOREST_MERGED]),
    )
    pairs = _launch.view_as(loop_counts, wp.vec2i)
    _size_generator_loops(candidate, unique_edges, parents, distances, apex, pairs)

    # The counts' scanned total and the three guard slots after it, in one read: it sizes both
    # outputs and decides the guards.
    n_generators, n_packed, n_interior, n_reached, n_referenced = (
        int(value) for value in read_values(trace_and_counts, 2 * n_edges - 2, 2 + count_slots)
    )
    if n_interior * 2 != 3 * n_faces:
        raise ValueError(
            "homology_generators requires a closed surface: this mesh has "
            f"{3 * n_faces - 2 * n_interior} boundary edge(s)."
        )
    if root is not None and n_reached == 1:
        raise ValueError(f"root {root} is not referenced by any face")
    if n_reached != n_referenced:
        raise ValueError(
            "homology_generators requires a connected surface: the traversal reached "
            f"{n_reached} of {n_referenced} referenced vertices."
        )
    if n_generators == 0:
        return _launch.empty_packed(wp.int32, device)
    return _write_generator_loops(
        candidate, unique_edges, parents, apex, pairs, n_generators, n_packed
    )