Skip to content

ordito.array

NumPy-style structural and elementwise ops on Warp arrays (ranges, gather, sort, masks).

Functions:

Name Description
arange

Evenly spaced integers over the half-open interval [start, stop) (numpy.arange).

arange_repeat

Fill out[i] = i // repeats (numpy.repeat of an index range).

sort_pair_indices

Fill [0, 1, ..., n-1, fill_value, ..., fill_value] (length 2 * n).

pack_1d_arrays

Concatenate several 1-D warp.array instances into one buffer plus per-segment offsets.

concatenate

Concatenate 1-D warp.array instances in order (numpy.concatenate).

split

Break a packed 1-D array into its per-segment arrays (numpy.split).

allclose

Test whether two arrays are element-wise equal within a tolerance (numpy.allclose).

sort_and_argsort

Ascending sort of keys together with the permutation that produced it.

sort_and_argsort_in_place

Ascending sort of keys a producer wrote into a radix sort's buffers, with its permutation.

sort_rows

Sort each row of a 2D array independently, in place, ascending.

triplet_buffers

Uninitialized (rows, cols, values) COO buffers for one csr_from_triplets build.

empty_square_bsr

Zero-nnz (n_rows, n_rows) operator, the n_faces == 0 return several assemblers share.

bsr_from_csr

Wrap compressed-row arrays that already hold a matrix's storage as a BsrMatrix, no copy.

bsr_with_values

Build a sparse matrix with matrix's sparsity pattern and the given block values.

block_diag

Stack square sparse operators into one block-diagonal float64 operator.

scalar_expansion

Return a wp.mat22d operator as the float64 CSR over its interleaved unknowns.

csr_key_buffers

Uninitialized (keys, order) buffers for one csr_from_keys.

csr_from_keys

Sort row-major entry keys and return the CSR pattern they spell, with each entry's positions.

csr_from_triplets

Assemble a sparse matrix from coordinate triplets, summing duplicates.

csr_from_coo_keys

Assemble a sparse matrix from written entry keys, summing each key's values.

csr_transpose

Transpose a sparse matrix of scalar blocks, with no host readback.

index_sparse

Build a sparse row/column incidence matrix from flat index columns.

isin

Test whether each element appears in test_elements (numpy.isin for integers).

flatnonzero

Return the indices of the non-zero entries of a 1D array (numpy.flatnonzero).

flatnonzero_in_place

Return the indices of the ones in a 0 / 1 flag buffer, scanning it in place.

compress_in_place

Return the values at the ones of a 0 / 1 flag buffer, scanning it in place.

gather

Dense copy of src gathered along its first axis by indices (numpy.take).

astype

Element-wise dtype conversion, shape and rank preserved (numpy.ndarray.astype).

copyto

Copy src into dst, converting each element to dst's dtype (numpy.copyto).

index_bound

Exclusive upper bound on an index buffer's values, as max(indices) + 1.

indices_to_mask

Boolean membership mask of length n marking each value in indices as True.

mask_to_compact_ranks

Compact index map over the True entries of a boolean mask, plus their count.

bit_ranks

Return each word's inclusive count of set bits over a uint32 bitmask.

counts_to_offsets

Total-terminated exclusive prefix sum of counts, plus their total.

remap_indices

Remap an index buffer through a lookup table, passing negative (sentinel) entries through.

trim_to_count

Trim atomic-append output buffers to the number of elements actually written.

bitcast_to_int

Reinterpret an array's underlying bits as a same-width signed integer dtype.

bitcast_from_int

Inverse of bitcast_to_int: recover the original dtype.

DType module-attribute

DType = TypeVar('DType')

SORT_ROWS_INSERTION_MAX_COLS module-attribute

SORT_ROWS_INSERTION_MAX_COLS = 8

PACK_SEGMENTS_KERNEL_FROM module-attribute

PACK_SEGMENTS_KERNEL_FROM = (
    _launch.SEGMENTS_IN_ONE_LAUNCH_FROM
)

arange

arange(
    start: int,
    stop: int | None = None,
    step: int = 1,
    *,
    device: DeviceLike,
) -> wp.array[wp.int32]

Evenly spaced integers over the half-open interval [start, stop) (numpy.arange).

Called with a varying number of positional arguments, exactly as numpy.arange: arange(stop, device=...) runs from 0, arange(start, stop, device=...) from start, and arange(start, stop, step, device=...) spaces the values by step. A step may be negative, in which case the interval runs downwards.

Parameters:

Name Type Description Default
start int

Start of the interval, included. Read as stop when stop is omitted, in which case the interval starts at 0.

required
stop int | None

End of the interval, excluded.

None
step int

Spacing between consecutive values, so out[i + 1] - out[i] == step. Must be non-zero.

1
device DeviceLike

Warp device for the result. Keyword-only, unlike the first three, so the positional arguments stay numpy.arange's; required, because nothing in this package allocates onto Warp's ambient current device.

required

Returns:

Type Description
array[int32]

(n,) values on device, n = max(0, ceil((stop - start) / step)).

Raises:

Type Description
ValueError

If step is zero, or the first or last value does not fit in int32.

Notes

There is no dtype argument, which is the one place this departs from numpy.arange's signature. Every index buffer in this package is int32, so a second width has no caller, and registering the kernel overloads for widths nothing reaches would cost compile time on every rebuild. The range check above is what stands in for choosing a wider dtype: a range that does not fit raises rather than silently wrapping.

See Also

arange_repeat The same range with each value repeated a fixed number of times. numpy.arange

Examples:

Mirrors numpy.arange, with one, two or three positional arguments:

import warp as wp

import ordito as od

device = wp.get_device()
print(od.array.arange(5, device=device).numpy().tolist())  # [0, 1, 2, 3, 4]
print(od.array.arange(2, 11, 3, device=device).numpy().tolist())  # [2, 5, 8]
print(od.array.arange(3, 0, -1, device=device).numpy().tolist())  # [3, 2, 1]
Source code in ordito/array.py
 47
 48
 49
 50
 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
def arange(
    start: int, stop: int | None = None, step: int = 1, *, device: wp.DeviceLike
) -> wp.array[wp.int32]:
    """
    Evenly spaced integers over the half-open interval ``[start, stop)`` (``numpy.arange``).

    Called with a varying number of positional arguments, exactly as [`numpy.arange`][]:
    ``arange(stop, device=...)`` runs from ``0``, ``arange(start, stop, device=...)`` from
    ``start``, and ``arange(start, stop, step, device=...)`` spaces the values by ``step``. A
    ``step`` may be negative, in which case the interval runs downwards.

    Parameters
    ----------
    start
        Start of the interval, included. Read as ``stop`` when ``stop`` is omitted, in which case
        the interval starts at ``0``.
    stop
        End of the interval, excluded.
    step
        Spacing between consecutive values, so ``out[i + 1] - out[i] == step``. Must be non-zero.
    device
        Warp device for the result. Keyword-only, unlike the first three, so the positional
        arguments stay [`numpy.arange`][]'s; required, because nothing in this package allocates
        onto Warp's ambient current device.

    Returns
    -------
    wp.array[wp.int32]
        ``(n,)`` values on ``device``, ``n = max(0, ceil((stop - start) / step))``.

    Raises
    ------
    ValueError
        If ``step`` is zero, or the first or last value does not fit in ``int32``.

    Notes
    -----
    There is no ``dtype`` argument, which is the one place this departs from [`numpy.arange`][]'s
    signature. Every index buffer in this package is ``int32``, so a second width has no caller,
    and registering the kernel overloads for widths nothing reaches would cost compile time on
    every rebuild. The range check above is what stands in for choosing a wider dtype: a range
    that does not fit raises rather than silently wrapping.

    See Also
    --------
    [`arange_repeat`][ordito.array.arange_repeat]
        The same range with each value repeated a fixed number of times.
    [`numpy.arange`][]

    Examples
    --------
    Mirrors [`numpy.arange`][], with one, two or three positional arguments:

    ```python
    import warp as wp

    import ordito as od

    device = wp.get_device()
    print(od.array.arange(5, device=device).numpy().tolist())  # [0, 1, 2, 3, 4]
    print(od.array.arange(2, 11, 3, device=device).numpy().tolist())  # [2, 5, 8]
    print(od.array.arange(3, 0, -1, device=device).numpy().tolist())  # [3, 2, 1]
    ```
    """
    if stop is None:
        start, stop = 0, start
    if step == 0:
        raise ValueError("step must be non-zero")
    # ``ceil((stop - start) / step)`` in integers, correct for either sign of ``step``: Python's
    # ``//`` floors, so negating both sides of the division ceils.
    n = max(0, -((start - stop) // step))
    if n > 0:
        _check_int32_fits(start, "start")
        _check_int32_fits(start + (n - 1) * step, "stop")
    out = _launch.empty(n, dtype=wp.int32, device=device)
    if n == 0:
        return out
    if start == 0 and step == 1:
        _launch.launch(kernel_array.ARANGE[wp.int32], dim=n, inputs=[out], device=device)
    else:
        _launch.launch(
            kernel_array.ARANGE_AFFINE[wp.int32],
            dim=n,
            inputs=[wp.int32(start), wp.int32(step), out],
            device=device,
        )
    return out

arange_repeat

arange_repeat(
    count: int, repeats: int, device: DeviceLike
) -> wp.array[wp.int32]

Fill out[i] = i // repeats (numpy.repeat of an index range).

Parameters:

Name Type Description Default
count int

Number of elements; must be non-negative.

required
repeats int

How many consecutive entries share an index; must be positive.

required
device DeviceLike

Warp device for the result.

required

Returns:

Type Description
array[int32]

(count,) array on device.

Raises:

Type Description
ValueError

If count is negative, repeats is not positive, or the largest value does not fit in int32.

See Also

arange The range this repeats, and whose Notes explain why neither takes a dtype. numpy.repeat

Examples:

The first count entries of numpy.repeat(numpy.arange(n), repeats):

import warp as wp

import ordito as od

indices = od.array.arange_repeat(7, 3, wp.get_device())
print(indices.numpy().tolist())  # [0, 0, 0, 1, 1, 1, 2]
Source code in ordito/array.py
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 arange_repeat(count: int, repeats: int, device: wp.DeviceLike) -> wp.array[wp.int32]:
    """
    Fill ``out[i] = i // repeats`` (``numpy.repeat`` of an index range).

    Parameters
    ----------
    count
        Number of elements; must be non-negative.
    repeats
        How many consecutive entries share an index; must be positive.
    device
        Warp device for the result.

    Returns
    -------
    wp.array[wp.int32]
        ``(count,)`` array on ``device``.

    Raises
    ------
    ValueError
        If ``count`` is negative, ``repeats`` is not positive, or the largest value does not fit
        in ``int32``.

    See Also
    --------
    [`arange`][ordito.array.arange]
        The range this repeats, and whose ``Notes`` explain why neither takes a ``dtype``.
    [`numpy.repeat`][]

    Examples
    --------
    The first ``count`` entries of ``numpy.repeat(numpy.arange(n), repeats)``:

    ```python
    import warp as wp

    import ordito as od

    indices = od.array.arange_repeat(7, 3, wp.get_device())
    print(indices.numpy().tolist())  # [0, 0, 0, 1, 1, 1, 2]
    ```
    """
    if count < 0:
        raise ValueError(f"count must be non-negative, got {count}")
    if repeats <= 0:
        raise ValueError(f"repeats must be positive, got {repeats}")
    if count > 0:
        _check_int32_fits((count - 1) // repeats, "count // repeats")
    out = _launch.empty(count, dtype=wp.int32, device=device)
    if count > 0:
        _launch.launch(
            kernel_array.ARANGE_REPEAT[wp.int32],
            dim=count,
            inputs=[wp.int32(repeats), out],
            device=device,
        )
    return out

sort_pair_indices

sort_pair_indices(
    n: int, fill_value: int, device: DeviceLike
) -> wp.array[wp.int32]

Fill [0, 1, ..., n-1, fill_value, ..., fill_value] (length 2 * n).

The payload buffer warp.utils.radix_sort_pairs wants: the first half seeded with the identity permutation, the second half (its scratch) filled with a padding value.

Parameters:

Name Type Description Default
n int

Number of real entries; the result has length 2 * n.

required
fill_value int

Padding written into the upper half.

required
device DeviceLike

Warp device for the result.

required

Returns:

Type Description
array[int32]

(2 * n,) array on device.

Raises:

Type Description
ValueError

If n is negative, or n - 1 / fill_value does not fit in int32.

See Also

sort_and_argsort arange Whose Notes explain why neither takes a dtype.

Examples:

import warp as wp

import ordito as od

payload = od.array.sort_pair_indices(3, -1, wp.get_device())
print(payload.numpy().tolist())  # [0, 1, 2, -1, -1, -1]
Source code in ordito/array.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
def sort_pair_indices(n: int, fill_value: int, device: wp.DeviceLike) -> wp.array[wp.int32]:
    """
    Fill ``[0, 1, ..., n-1, fill_value, ..., fill_value]`` (length ``2 * n``).

    The payload buffer ``warp.utils.radix_sort_pairs`` wants: the first half seeded with the
    identity permutation, the second half (its scratch) filled with a padding value.

    Parameters
    ----------
    n
        Number of real entries; the result has length ``2 * n``.
    fill_value
        Padding written into the upper half.
    device
        Warp device for the result.

    Returns
    -------
    wp.array[wp.int32]
        ``(2 * n,)`` array on ``device``.

    Raises
    ------
    ValueError
        If ``n`` is negative, or ``n - 1`` / ``fill_value`` does not fit in ``int32``.

    See Also
    --------
    [`sort_and_argsort`][ordito.array.sort_and_argsort]
    [`arange`][ordito.array.arange]
        Whose ``Notes`` explain why neither takes a ``dtype``.

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

    import ordito as od

    payload = od.array.sort_pair_indices(3, -1, wp.get_device())
    print(payload.numpy().tolist())  # [0, 1, 2, -1, -1, -1]
    ```
    """
    if n < 0:
        raise ValueError(f"n must be non-negative, got {n}")
    if n > 0:
        _check_int32_fits(n - 1, "n")
    _check_int32_fits(fill_value, "fill_value")
    out = _launch.empty(2 * n, dtype=wp.int32, device=device)
    if n > 0:
        _launch.launch(
            kernel_array.SORT_PAIR_INDICES[wp.int32],
            dim=2 * n,
            inputs=[wp.int32(n), wp.int32(fill_value), out],
            device=device,
        )
    return out

pack_1d_arrays

pack_1d_arrays(
    arrays: Sequence[array[DType]], *, copy: bool = True
) -> tuple[wp.array[DType], wp.array[wp.int32]]

Concatenate several 1-D warp.array instances into one buffer plus per-segment offsets.

Segment i occupies flat[offsets[i] : offsets[i + 1]]. This is the usual packed representation for variable-length per-item lists on the device (no nested arrays).

The packed pair is spelled values first, then total-terminated offsets

This function is where the package's convention is stated, because it is the primitive the others are built on: a packed buffer and its offsets are returned, and accepted, values first, and the offsets are the n + 1 total-terminated CSR form (scipy's indptr): item i is values[offsets[i] : offsets[i + 1]], offsets[0] == 0, offsets[n] == values.shape[0], and a size is the difference of two neighbouring entries -- there is no separate sizes array. An empty packed result has offsets == [0]. Every public function that hands back such a pair -- boundary_loops_with_offsets, successor_cycles, query_ball_with_offsets, geodesic_ball, vertex_face_adjacency, vertex_one_rings and the ordito.geodesic_walk tracers among them -- and every function that takes one (split, submeshes_from_face_groups) uses the same order and form. Both halves are wp.int32 in the common case, so a transposed unpack type-checks, runs, and indexes garbage; there is nothing but the convention to lean on. Where a third array rides along it is a per-item one and goes last, as in (ring_halfedges, offsets, is_boundary).

Parameters:

Name Type Description Default
arrays Sequence[array[DType]]

Non-empty sequence of 1-D arrays sharing the same dtype and device.

required
copy bool

Keep False for a read-only result. arrays that are already consecutive non-empty views of one buffer -- what split returns with copy=False -- are then handed back as that buffer's span instead of being copied into a new one, so the split round trip costs nothing at all. The default copies, so writing into flat is safe; with copy=False such a write reaches the segments.

True

Returns:

Type Description
flat

(sum(a.size for a in arrays),) array, same dtype and device as the inputs.

offsets

(len(arrays) + 1,) total-terminated offsets, same device as the inputs: offsets[0] == 0 and offsets[-1] == flat.size.

Raises:

Type Description
ValueError

If arrays is empty, any input is not rank-1, or their dtype differs.

RuntimeError

If the segments are not all on one device.

See Also

split The inverse: recovers the per-segment arrays from (flat, offsets). concatenate

Examples:

Three segments of lengths 2, 1 and 3 pack into six values and four offsets:

import warp as wp

import ordito as od

segments = [
    wp.array([1, 2], dtype=wp.int32),
    wp.array([3], dtype=wp.int32),
    wp.array([4, 5, 6], dtype=wp.int32),
]
flat, offsets = od.array.pack_1d_arrays(segments)
print(flat.numpy().tolist())  # [1, 2, 3, 4, 5, 6]
print(offsets.numpy().tolist())  # [0, 2, 3, 6]
Source code in ordito/array.py
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
def pack_1d_arrays(
    arrays: Sequence[wp.array[DType]], *, copy: bool = True
) -> tuple[wp.array[DType], wp.array[wp.int32]]:
    """
    Concatenate several 1-D ``warp.array`` instances into one buffer plus per-segment offsets.

    Segment ``i`` occupies ``flat[offsets[i] : offsets[i + 1]]``. This is the usual packed
    representation for variable-length per-item lists on the device (no nested arrays).

    !!! note "The packed pair is spelled values first, then total-terminated offsets"
        This function is where the package's convention is stated, because it is the primitive the
        others are built on: **a packed buffer and its offsets are returned, and accepted, values
        first, and the offsets are the ``n + 1`` total-terminated CSR form** (``scipy``'s
        ``indptr``): item ``i`` is ``values[offsets[i] : offsets[i + 1]]``, ``offsets[0] == 0``,
        ``offsets[n] == values.shape[0]``, and a size is the difference of two neighbouring
        entries -- there is no separate sizes array. An empty packed result has ``offsets == [0]``.
        Every public function that hands back such a pair --
        [`boundary_loops_with_offsets`][ordito.boundary.boundary_loops_with_offsets],
        [`successor_cycles`][ordito.graph.successor_cycles],
        [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets],
        [`geodesic_ball`][ordito.neighbors.geodesic_ball],
        [`vertex_face_adjacency`][ordito.adjacency.vertex_face_adjacency],
        [`vertex_one_rings`][ordito.halfedge.vertex_one_rings] and the
        [`ordito.geodesic_walk`][ordito.geodesic_walk] tracers among them -- and every function
        that *takes* one ([`split`][ordito.array.split],
        [`submeshes_from_face_groups`][ordito.selection.submeshes_from_face_groups]) uses the same
        order and form. Both halves are ``wp.int32`` in the common case, so a transposed unpack
        type-checks, runs, and indexes garbage; there is nothing but the convention to lean on.
        Where a third array rides along it is a *per-item* one and goes last, as in
        ``(ring_halfedges, offsets, is_boundary)``.

    Parameters
    ----------
    arrays
        Non-empty sequence of 1-D arrays sharing the same ``dtype`` and ``device``.
    copy
        Keep ``False`` for a read-only result. ``arrays`` that are already consecutive non-empty
        views of one buffer -- what [`split`][ordito.array.split] returns with ``copy=False`` --
        are then handed back as that buffer's span instead of being copied into a new one, so the
        ``split`` round trip costs nothing at all. The default copies, so writing into ``flat`` is
        safe; with ``copy=False`` such a write reaches the segments.

    Returns
    -------
    flat
        ``(sum(a.size for a in arrays),)`` array, same ``dtype`` and ``device`` as the inputs.
    offsets
        ``(len(arrays) + 1,)`` total-terminated offsets, same ``device`` as the inputs:
        ``offsets[0] == 0`` and ``offsets[-1] == flat.size``.

    Raises
    ------
    ValueError
        If ``arrays`` is empty, any input is not rank-1, or their ``dtype`` differs.
    RuntimeError
        If the segments are not all on one device.

    See Also
    --------
    [`split`][ordito.array.split]
        The inverse: recovers the per-segment arrays from ``(flat, offsets)``.
    [`concatenate`][ordito.array.concatenate]

    Examples
    --------
    Three segments of lengths 2, 1 and 3 pack into six values and four offsets:

    ```python
    import warp as wp

    import ordito as od

    segments = [
        wp.array([1, 2], dtype=wp.int32),
        wp.array([3], dtype=wp.int32),
        wp.array([4, 5, 6], dtype=wp.int32),
    ]
    flat, offsets = od.array.pack_1d_arrays(segments)
    print(flat.numpy().tolist())  # [1, 2, 3, 4, 5, 6]
    print(offsets.numpy().tolist())  # [0, 2, 3, 6]
    ```
    """
    flat, offsets = _pack_segments(arrays, caller="pack_1d_arrays", copy=copy)
    return flat, _launch.array([*offsets, flat.size], dtype=wp.int32, device=flat.device)

concatenate

concatenate(
    arrays: Sequence[array[DType]], *, copy: bool = True
) -> wp.array[DType]

Concatenate 1-D warp.array instances in order (numpy.concatenate).

Parameters:

Name Type Description Default
arrays Sequence[array[DType]]

Non-empty sequence of rank-1 arrays sharing the same dtype and device. Empty segments are allowed.

required
copy bool

Keep False for a read-only result, which then costs nothing when the segments already tile one buffer -- see pack_1d_arrays.

True

Returns:

Type Description
array

(sum(a.size for a in arrays),) contiguous array on the input device. When arrays has a single element, that array is returned without copying whatever copy says, since there is nothing to concatenate it with.

Raises:

Type Description
ValueError

If arrays is empty, any input is not rank-1, or their dtype differs.

RuntimeError

If the segments are not all on one device.

See Also

pack_1d_arrays concatenate The mesh-level operation of the same name, which joins (vertices, faces) pairs and reindexes as it goes. Both names are required: this one mirrors numpy.concatenate, that one trimesh.util.concatenate. numpy.concatenate

Examples:

Mirrors numpy.concatenate for rank-1 arrays:

import warp as wp

import ordito as od

first = wp.array([1.0, 2.0], dtype=wp.float32)
second = wp.array([3.0], dtype=wp.float32)
print(od.array.concatenate([first, second]).numpy().tolist())  # [1.0, 2.0, 3.0]
Source code in ordito/array.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
def concatenate(arrays: Sequence[wp.array[DType]], *, copy: bool = True) -> wp.array[DType]:
    """
    Concatenate 1-D ``warp.array`` instances in order (``numpy.concatenate``).

    Parameters
    ----------
    arrays
        Non-empty sequence of rank-1 arrays sharing the same ``dtype`` and ``device``.
        Empty segments are allowed.
    copy
        Keep ``False`` for a read-only result, which then costs nothing when the segments already
        tile one buffer -- see [`pack_1d_arrays`][ordito.array.pack_1d_arrays].

    Returns
    -------
    wp.array
        ``(sum(a.size for a in arrays),)`` contiguous array on the input device. When ``arrays`` has
        a single element, that array is returned without copying whatever ``copy`` says, since there
        is nothing to concatenate it with.

    Raises
    ------
    ValueError
        If ``arrays`` is empty, any input is not rank-1, or their ``dtype`` differs.
    RuntimeError
        If the segments are not all on one device.

    See Also
    --------
    [`pack_1d_arrays`][ordito.array.pack_1d_arrays]
    [`concatenate`][ordito.combine.concatenate]
        The mesh-level operation of the same name, which joins ``(vertices, faces)`` pairs and
        reindexes as it goes. Both names are required: this one mirrors
        [`numpy.concatenate`][], that one [`trimesh.util.concatenate`][].
    [`numpy.concatenate`][]

    Examples
    --------
    Mirrors [`numpy.concatenate`][] for rank-1 arrays:

    ```python
    import warp as wp

    import ordito as od

    first = wp.array([1.0, 2.0], dtype=wp.float32)
    second = wp.array([3.0], dtype=wp.float32)
    print(od.array.concatenate([first, second]).numpy().tolist())  # [1.0, 2.0, 3.0]
    ```
    """
    if len(arrays) == 0:
        raise ValueError("arrays must be non-empty")
    if len(arrays) == 1:
        arr = arrays[0]
        if int(arr.ndim) != 1:
            raise ValueError(f"concatenate requires rank-1 arrays, got ndim={arr.ndim}")
        return arr
    return _pack_segments(arrays, caller="concatenate", copy=copy)[0]

split

split(
    array: array[DType],
    offsets: array[int32] | Sequence[int],
    *,
    copy: bool = False,
    row_size: int = 1,
) -> list[wp.array[DType]]

Break a packed 1-D array into its per-segment arrays (numpy.split).

The inverse of pack_1d_arrays: segment i is array[offsets[i] : offsets[i + 1]]. One host readback of offsets (none when they are passed as a host sequence), then zero copies by default -- the segments are views into array, which they keep alive.

Parameters:

Name Type Description Default
array array[DType]

(row_size * offsets[-1],) array to split, any dtype.

required
offsets array[int32] | Sequence[int]

(n_segments + 1,) total-terminated wp.int32 offsets: offsets[0] == 0, non-decreasing, and offsets[-1] equal to array's row count -- exactly what pack_1d_arrays and counts_to_offsets return. [0] describes no segments. A host sequence of ints with the same contents is accepted too, for a caller that already holds the bounds.

required
copy bool

When True, return independent copies, each in its own allocation, instead of views.

False
row_size int

Number of elements each offset counts. With row_size=3 the offsets index the rows of a flat (3 * n_faces,) face buffer, and segment i is array[3 * offsets[i] : 3 * offsets[i + 1]] -- the form split_with_offsets returns its face offsets in.

1

Returns:

Type Description
list[array]

One array per segment, on array.device, in segment order. Empty list when offsets == [0].

Raises:

Type Description
ValueError

If array or offsets is not rank-1, row_size is not positive or does not divide array's length, offsets is empty, or offsets is not a non-decreasing sequence from 0 to array's row count -- which is what an unterminated, length-n_segments offsets array fails.

RuntimeError

If array and offsets are not all on one device.

See Also

pack_1d_arrays The inverse: packs per-segment arrays into one buffer plus these offsets. split The mesh-level operation of the same name, which separates a mesh into connected components. Both names are required: this one mirrors numpy.split, that one trimesh.Trimesh.split. numpy.split

Examples:

Unlike numpy.split, the bounds are total-terminated offsets rather than split points:

import warp as wp

import ordito as od

values = wp.array([1, 2, 3, 4, 5, 6], dtype=wp.int32)
offsets = wp.array([0, 2, 3, 6], dtype=wp.int32)
segments = od.array.split(values, offsets)
print([segment.numpy().tolist() for segment in segments])  # [[1, 2], [3], [4, 5, 6]]
Source code in ordito/array.py
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
def split(
    array: wp.array[DType],
    offsets: wp.array[wp.int32] | Sequence[int],
    *,
    copy: bool = False,
    row_size: int = 1,
) -> list[wp.array[DType]]:
    """
    Break a packed 1-D array into its per-segment arrays (``numpy.split``).

    The inverse of [`pack_1d_arrays`][ordito.array.pack_1d_arrays]: segment ``i`` is
    ``array[offsets[i] : offsets[i + 1]]``. One host readback of ``offsets`` (none when they are
    passed as a host sequence), then zero copies by default -- the segments are views into
    ``array``, which they keep alive.

    Parameters
    ----------
    array
        ``(row_size * offsets[-1],)`` array to split, any ``dtype``.
    offsets
        ``(n_segments + 1,)`` total-terminated ``wp.int32`` offsets: ``offsets[0] == 0``,
        non-decreasing, and ``offsets[-1]`` equal to ``array``'s row count -- exactly what
        [`pack_1d_arrays`][ordito.array.pack_1d_arrays] and
        [`counts_to_offsets`][ordito.array.counts_to_offsets] return. ``[0]`` describes no
        segments. A host sequence of ints with the same contents is accepted too, for a caller
        that already holds the bounds.
    copy
        When ``True``, return independent copies, each in its own allocation, instead of views.
    row_size
        Number of elements each offset counts. With ``row_size=3`` the offsets index the rows of a
        flat ``(3 * n_faces,)`` face buffer, and segment ``i`` is
        ``array[3 * offsets[i] : 3 * offsets[i + 1]]`` -- the form
        [`split_with_offsets`][ordito.combine.split_with_offsets] returns its face offsets in.

    Returns
    -------
    list[wp.array]
        One array per segment, on ``array.device``, in segment order. Empty list when
        ``offsets == [0]``.

    Raises
    ------
    ValueError
        If ``array`` or ``offsets`` is not rank-1, ``row_size`` is not positive or does not divide
        ``array``'s length, ``offsets`` is empty, or ``offsets`` is not a non-decreasing sequence
        from ``0`` to ``array``'s row count -- which is what an unterminated, length-``n_segments``
        offsets array fails.
    RuntimeError
        If ``array`` and ``offsets`` are not all on one device.

    See Also
    --------
    [`pack_1d_arrays`][ordito.array.pack_1d_arrays]
        The inverse: packs per-segment arrays into one buffer plus these offsets.
    [`split`][ordito.combine.split]
        The mesh-level operation of the same name, which separates a mesh into connected
        components. Both names are required: this one mirrors [`numpy.split`][], that one
        ``trimesh.Trimesh.split``.
    [`numpy.split`][]

    Examples
    --------
    Unlike [`numpy.split`][], the bounds are total-terminated offsets rather than split points:

    ```python
    import warp as wp

    import ordito as od

    values = wp.array([1, 2, 3, 4, 5, 6], dtype=wp.int32)
    offsets = wp.array([0, 2, 3, 6], dtype=wp.int32)
    segments = od.array.split(values, offsets)
    print([segment.numpy().tolist() for segment in segments])  # [[1, 2], [3], [4, 5, 6]]
    ```
    """
    on_device = isinstance(offsets, wp.array)
    # Host bounds carry no device, and walking them for one costs a call per bound.
    require_same_device(array=array, offsets=offsets if on_device else None)
    if int(array.ndim) != 1:
        raise ValueError(f"split requires a rank-1 array, got ndim={array.ndim}")
    offsets_ndim = int(offsets.ndim) if on_device else np.ndim(offsets)
    if offsets_ndim != 1:
        raise ValueError(f"split requires rank-1 offsets, got ndim={offsets_ndim}")
    n = array.size
    if row_size < 1 or n % row_size != 0:
        raise ValueError(
            f"row_size must be positive and divide the array length {n}, got {row_size}"
        )
    n_offsets = offsets.size if on_device else len(offsets)
    if n_offsets == 0:
        raise ValueError("split requires total-terminated offsets of length n_segments + 1, got []")
    if n_offsets == 1 and n == 0:
        # No segments over an empty array: the only valid entry is the ``0`` both ends must be.
        return []

    # The one readback, unless the caller already holds the bounds on the host. ``.numpy()`` of a
    # CPU array is a view, so the bounds are built in a fresh buffer rather than in place.
    bounds_np = np.array(read_array(offsets) if on_device else offsets, dtype=np.int64)
    n_rows = n // row_size
    if bounds_np[0] != 0 or bounds_np[-1] != n_rows or bool((bounds_np[1:] < bounds_np[:-1]).any()):
        raise ValueError(
            f"offsets must be total-terminated: start at 0, be non-decreasing and end at the row "
            f"count {n_rows}, got {bounds_np.tolist()}"
        )
    if bounds_np.size == 1:
        return []
    if row_size != 1:
        bounds_np *= row_size
    bounds = bounds_np.tolist()
    return _copy_segments(array, bounds) if copy else _segment_views(array, bounds)

allclose

allclose(
    a: array[Float] | array[vec3],
    b: array[Float] | array[vec3],
    *,
    rtol: float = ALLCLOSE_RTOL,
    atol: float = ALLCLOSE_ATOL,
) -> bool

Test whether two arrays are element-wise equal within a tolerance (numpy.allclose).

Reduces |a - b| <= atol + rtol * |b| (element-wise, and component-wise for wp.vec3) to a single Python bool on-device, without copying either array to the host. Matches the asymmetric numpy.allclose / torch.allclose tolerance convention.

Parameters:

Name Type Description Default
a array[Float] | array[vec3]

(n,) array of any float dtype (float16 / float32 / float64) or of wp.vec3, on the target device.

required
b array[Float] | array[vec3]

(n,) array of the same dtype as a.

required
rtol float

Relative tolerance. Defaults to 1e-05. Converted to a's precision.

ALLCLOSE_RTOL
atol float

Absolute tolerance. Defaults to 1e-08. Converted to a's precision, so a float16 comparison cannot resolve a tolerance below its own epsilon.

ALLCLOSE_ATOL

Returns:

Type Description
bool

True when every element (every component, for wp.vec3) is within tolerance. True for empty inputs, following the numpy.allclose convention.

Raises:

Type Description
ValueError

If a and b have different lengths or dtypes.

RuntimeError

If a and b are not all on one device.

Examples:

Mirrors numpy.allclose with its default tolerances:

import warp as wp

import ordito as od

a = wp.array([1.0, 2.0, 3.0], dtype=wp.float32)
print(od.array.allclose(a, wp.array([1.0, 2.0, 3.000001], dtype=wp.float32)))  # True
print(od.array.allclose(a, wp.array([1.0, 2.0, 3.1], dtype=wp.float32)))  # False
Source code in ordito/array.py
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
def allclose(
    a: wp.array[wp.Float] | wp.array[wp.vec3],
    b: wp.array[wp.Float] | wp.array[wp.vec3],
    *,
    rtol: float = ALLCLOSE_RTOL,
    atol: float = ALLCLOSE_ATOL,
) -> bool:
    """
    Test whether two arrays are element-wise equal within a tolerance (``numpy.allclose``).

    Reduces ``|a - b| <= atol + rtol * |b|`` (element-wise, and component-wise for ``wp.vec3``)
    to a single Python ``bool`` on-device, without copying either array to the host. Matches the
    asymmetric ``numpy.allclose`` / ``torch.allclose`` tolerance convention.

    Parameters
    ----------
    a
        ``(n,)`` array of any float dtype (``float16`` / ``float32`` / ``float64``) or of
        ``wp.vec3``, on the target device.
    b
        ``(n,)`` array of the same dtype as ``a``.
    rtol
        Relative tolerance. Defaults to ``1e-05``. Converted to ``a``'s precision.
    atol
        Absolute tolerance. Defaults to ``1e-08``. Converted to ``a``'s precision, so a
        ``float16`` comparison cannot resolve a tolerance below its own epsilon.

    Returns
    -------
    bool
        ``True`` when every element (every component, for ``wp.vec3``) is within tolerance.
        ``True`` for empty inputs, following the ``numpy.allclose`` convention.

    Raises
    ------
    ValueError
        If ``a`` and ``b`` have different lengths or dtypes.
    RuntimeError
        If ``a`` and ``b`` are not all on one device.

    Examples
    --------
    Mirrors [`numpy.allclose`][] with its default tolerances:

    ```python
    import warp as wp

    import ordito as od

    a = wp.array([1.0, 2.0, 3.0], dtype=wp.float32)
    print(od.array.allclose(a, wp.array([1.0, 2.0, 3.000001], dtype=wp.float32)))  # True
    print(od.array.allclose(a, wp.array([1.0, 2.0, 3.1], dtype=wp.float32)))  # False
    ```
    """
    require_same_device(a=a, b=b)
    if a.dtype != b.dtype:
        raise ValueError(f"allclose requires matching dtypes, got {a.dtype} and {b.dtype}")
    n = a.size
    if n != b.size:
        raise ValueError(f"allclose requires equal lengths, got {n} and {b.size}")
    if n == 0:
        return True

    # The predicate folds into its own reduction: one launch and one four-byte accumulator, rather
    # than a ``wp.map`` into an ``(n,)`` mask and a whole ``reduce.all`` over it. See
    # ``kernels/reduce.ALLCLOSE_1D_TILED``, including why it is a table of concrete kernels.
    tolerance = wp.float32 if a.dtype == wp.vec3 else a.dtype
    flag = _launch.ones(1, dtype=wp.int32, device=a.device)
    _launch.launch_tiled(
        kernel_reduce.ALLCLOSE_1D_TILED[a.dtype],
        dim=kernel_reduce.blocks_1d(n),
        inputs=[a, b, tolerance(rtol), tolerance(atol)],
        outputs=[flag],
        block_dim=TILE_1D,
        device=a.device,
    )
    return bool(int(read_scalar(flag, 0)) != 0)

sort_and_argsort

sort_and_argsort(
    keys: _SortableArrayT, *, end_bit: int | None = None
) -> tuple[_SortableArrayT, wp.array[wp.int32]]

Ascending sort of keys together with the permutation that produced it.

Both halves of numpy.sort and numpy.argsort at once: a radix sort produces the ordered keys as a side effect of computing the order, so returning only one of the two would throw work away. sorted_keys[i] == keys[order[i]].

Wraps warp.utils.radix_sort_pairs, which needs double-width scratch for both the keys and the payload; this allocates that scratch, seeds the payload with 0..n-1 and hands back length-n views of the sorted prefixes.

Parameters:

Name Type Description Default
keys _SortableArrayT

(n,) sort keys (any radix-sortable scalar dtype; see sortable_dtype for which those are).

required
end_bit int | None

Exclusive upper bound on the key bits the radix sort orders, for integer keys known to be non-negative and below 2**end_bit (a face id below n_faces needs (n_faces - 1).bit_length() bits). None sorts the whole key width.

None

Returns:

Name Type Description
sorted_keys array

(n,) view of the ascending keys.

order array[int32]

(n,) view of the original index of each sorted key.

Notes

Both results are views into the scratch buffers, kept alive by the returned arrays. Clone them if they must outlive the caller's frame alongside another sort.

The sort is stable: equal keys keep their input order, so order is ascending within each run of duplicate keys. warp.utils.radix_sort_pairs documents this ("the sort is stable and operates in linear time"), it is inherent to its LSD radix passes, and it is verified on both devices against numpy.argsort(kind="stable"). Callers may rely on it -- split_with_offsets does, to keep faces ascending within each component.

See Also

sort_and_argsort_in_place The same sort over buffers a producer kernel has already written. sort_rows sortable_dtype

Examples:

numpy.sort and numpy.argsort(kind="stable") in one call; the two equal keys keep their input order:

import warp as wp

import ordito as od

keys = wp.array([3, 1, 2, 1], dtype=wp.int32)
sorted_keys, order = od.array.sort_and_argsort(keys)
print(sorted_keys.numpy().tolist())  # [1, 1, 2, 3]
print(order.numpy().tolist())  # [1, 3, 2, 0]
Source code in ordito/array.py
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
def sort_and_argsort(
    keys: _SortableArrayT, *, end_bit: int | None = None
) -> tuple[_SortableArrayT, wp.array[wp.int32]]:
    """
    Ascending sort of ``keys`` together with the permutation that produced it.

    Both halves of ``numpy.sort`` and ``numpy.argsort`` at once: a radix sort produces the ordered
    keys as a side effect of computing the order, so returning only one of the two would throw work
    away. ``sorted_keys[i] == keys[order[i]]``.

    Wraps ``warp.utils.radix_sort_pairs``, which needs double-width scratch for both the keys and
    the payload; this allocates that scratch, seeds the payload with ``0..n-1`` and hands back
    length-``n`` views of the sorted prefixes.

    Parameters
    ----------
    keys
        ``(n,)`` sort keys (any radix-sortable scalar dtype; see
        [`sortable_dtype`][ordito.typing.sortable_dtype] for which those are).
    end_bit
        Exclusive upper bound on the key bits the radix sort orders, for integer keys known to be
        non-negative and below ``2**end_bit`` (a face id below ``n_faces`` needs
        ``(n_faces - 1).bit_length()`` bits). ``None`` sorts the whole key width.

    Returns
    -------
    sorted_keys : wp.array
        ``(n,)`` view of the ascending keys.
    order : wp.array[wp.int32]
        ``(n,)`` view of the original index of each sorted key.

    Notes
    -----
    Both results are **views** into the scratch buffers, kept alive by the returned arrays. Clone
    them if they must outlive the caller's frame alongside another sort.

    The sort is **stable**: equal keys keep their input order, so ``order`` is ascending within
    each run of duplicate keys. ``warp.utils.radix_sort_pairs`` documents this ("the sort is
    stable and operates in linear time"), it is inherent to its LSD radix passes, and it is
    verified on both devices against ``numpy.argsort(kind="stable")``. Callers may rely on it --
    [`split_with_offsets`][ordito.combine.split_with_offsets] does, to keep faces ascending within
    each component.

    See Also
    --------
    [`sort_and_argsort_in_place`][ordito.array.sort_and_argsort_in_place]
        The same sort over buffers a producer kernel has already written.
    [`sort_rows`][ordito.array.sort_rows]
    [`sortable_dtype`][ordito.typing.sortable_dtype]

    Examples
    --------
    [`numpy.sort`][] and ``numpy.argsort(kind="stable")`` in one call; the two equal keys keep
    their input order:

    ```python
    import warp as wp

    import ordito as od

    keys = wp.array([3, 1, 2, 1], dtype=wp.int32)
    sorted_keys, order = od.array.sort_and_argsort(keys)
    print(sorted_keys.numpy().tolist())  # [1, 1, 2, 3]
    print(order.numpy().tolist())  # [1, 3, 2, 0]
    ```
    """
    device = keys.device
    n = keys.size
    if n == 0:
        return keys, _launch.empty(0, dtype=wp.int32, device=device)
    keys_buffer, order_buffer = _launch.sort_buffers(n, keys.dtype, device)
    # The keys and the identity payload into the sort's leading halves in one launch.
    _launch.launch(
        kernel_array.KEYS_AND_IDENTITY[keys.dtype],
        dim=n,
        inputs=[keys, keys_buffer, order_buffer],
        device=device,
    )
    sorted_keys, order = sort_and_argsort_in_place(keys_buffer, order_buffer, end_bit=end_bit)
    return cast(_SortableArrayT, sorted_keys), order

sort_and_argsort_in_place

sort_and_argsort_in_place(
    keys_buffer: _SortableArrayT,
    order_buffer: array[int32],
    *,
    end_bit: int | None = None,
) -> tuple[_SortableArrayT, wp.array[wp.int32]]

Ascending sort of keys a producer wrote into a radix sort's buffers, with its permutation.

sort_and_argsort for a caller whose own kernel computes the keys: it writes them, and the identity permutation, straight into the leading halves of the double-width buffers warp.utils.radix_sort_pairs sorts in, so the keys are never copied into the sort's buffer. Allocate both buffers with wp.empty-style storage: the upper halves are the sort's scratch and need no initial value.

Parameters:

Name Type Description Default
keys_buffer _SortableArrayT

(2 * n,) buffer whose first n entries are the sort keys (any dtype Warp's radix sort orders: int32, uint32, int64, uint64, float32, float64). Sorted in place.

required
order_buffer array[int32]

(2 * n,) int32 buffer whose first n entries are the payload the sort carries, usually 0, 1, ..., n - 1. Permuted in place.

required
end_bit int | None

Exclusive upper bound on the key bits the radix sort orders, for integer keys known to be non-negative and below 2**end_bit. None sorts the whole key width.

None

Returns:

Name Type Description
sorted_keys array

(n,) view of the ascending keys: the leading half of keys_buffer.

order array[int32]

(n,) view of the payload in sorted order: the leading half of order_buffer.

Raises:

Type Description
ValueError

If the buffers are not both rank-1 of one even length.

RuntimeError

If keys_buffer and order_buffer are not on one device.

Notes

Stable, like sort_and_argsort: equal keys keep their payload order.

See Also

sort_and_argsort The same sort of an existing key array.

Examples:

import warp as wp

import ordito as od

keys_buffer = wp.array([3, 1, 2, 1, 0, 0, 0, 0], dtype=wp.int32)
order_buffer = wp.array([0, 1, 2, 3, 0, 0, 0, 0], dtype=wp.int32)
sorted_keys, order = od.array.sort_and_argsort_in_place(keys_buffer, order_buffer)
print(sorted_keys.numpy().tolist())  # [1, 1, 2, 3]
print(order.numpy().tolist())  # [1, 3, 2, 0]
Source code in ordito/array.py
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
def sort_and_argsort_in_place(
    keys_buffer: _SortableArrayT, order_buffer: wp.array[wp.int32], *, end_bit: int | None = None
) -> tuple[_SortableArrayT, wp.array[wp.int32]]:
    """
    Ascending sort of keys a producer wrote into a radix sort's buffers, with its permutation.

    [`sort_and_argsort`][ordito.array.sort_and_argsort] for a caller whose own kernel computes the
    keys: it writes them, and the identity permutation, straight into the leading halves of the
    double-width buffers ``warp.utils.radix_sort_pairs`` sorts in, so the keys are never copied
    into the sort's buffer. Allocate both buffers with ``wp.empty``-style storage: the upper halves
    are the sort's scratch and need no initial value.

    Parameters
    ----------
    keys_buffer
        ``(2 * n,)`` buffer whose first ``n`` entries are the sort keys (any dtype Warp's radix
        sort orders: ``int32``, ``uint32``, ``int64``, ``uint64``, ``float32``, ``float64``).
        Sorted in place.
    order_buffer
        ``(2 * n,)`` ``int32`` buffer whose first ``n`` entries are the payload the sort carries,
        usually ``0, 1, ..., n - 1``. Permuted in place.
    end_bit
        Exclusive upper bound on the key bits the radix sort orders, for integer keys known to be
        non-negative and below ``2**end_bit``. ``None`` sorts the whole key width.

    Returns
    -------
    sorted_keys : wp.array
        ``(n,)`` view of the ascending keys: the leading half of ``keys_buffer``.
    order : wp.array[wp.int32]
        ``(n,)`` view of the payload in sorted order: the leading half of ``order_buffer``.

    Raises
    ------
    ValueError
        If the buffers are not both rank-1 of one even length.
    RuntimeError
        If ``keys_buffer`` and ``order_buffer`` are not on one device.

    Notes
    -----
    Stable, like [`sort_and_argsort`][ordito.array.sort_and_argsort]: equal keys keep their payload
    order.

    See Also
    --------
    [`sort_and_argsort`][ordito.array.sort_and_argsort]
        The same sort of an existing key array.

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

    import ordito as od

    keys_buffer = wp.array([3, 1, 2, 1, 0, 0, 0, 0], dtype=wp.int32)
    order_buffer = wp.array([0, 1, 2, 3, 0, 0, 0, 0], dtype=wp.int32)
    sorted_keys, order = od.array.sort_and_argsort_in_place(keys_buffer, order_buffer)
    print(sorted_keys.numpy().tolist())  # [1, 1, 2, 3]
    print(order.numpy().tolist())  # [1, 3, 2, 0]
    ```
    """
    require_same_device(keys_buffer=keys_buffer, order_buffer=order_buffer)
    n2 = keys_buffer.size
    if (
        int(keys_buffer.ndim) != 1
        or int(order_buffer.ndim) != 1
        or n2 % 2
        or order_buffer.size != n2
    ):
        raise ValueError(
            "sort_and_argsort_in_place requires rank-1 key and order buffers of one even length, "
            f"got {tuple(keys_buffer.shape)} and {tuple(order_buffer.shape)}"
        )
    n = n2 // 2
    if n == 0:
        return keys_buffer, order_buffer
    _launch.radix_sort_pairs(keys_buffer, order_buffer, count=n, end_bit=end_bit)
    return _launch.view(keys_buffer, 0, n), _launch.view(order_buffer, 0, n)

sort_rows

sort_rows(data: Array2dInt32 | Array2dFloat32) -> None

Sort each row of a 2D array independently, in place, ascending.

Each row is treated as its own radix-sort segment, so rows are reordered internally but their relative row order is unaffected.

Parameters:

Name Type Description Default
data Array2dInt32 | Array2dFloat32

(n, w) int32 or float32 device array sorted in place, row by row.

required

Raises:

Type Description
TypeError

If data is not int32 or float32.

Notes

Rows no wider than SORT_ROWS_INSERTION_MAX_COLS are sorted by a per-row insertion sort (one thread per row); wider rows fall back to a segmented radix sort. The narrow path is not a micro-optimization: segmented_sort_pairs pays a fixed cost per segment, which for rows this narrow dominates the comparison work by orders of magnitude.

The dtype restriction comes from that fallback -- warp.utils.segmented_sort_pairs takes int32 or float32 keys and nothing else -- and it is checked up front rather than left to whichever path a row width happens to select, so the accepted dtypes do not depend on w.

Examples:

numpy.sort(rows, axis=1), in place:

import warp as wp

import ordito as od

rows = wp.array([[3, 1, 2], [9, 7, 8]], dtype=wp.int32)
od.array.sort_rows(rows)
print(rows.numpy().tolist())  # [[1, 2, 3], [7, 8, 9]]
Source code in ordito/array.py
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
def sort_rows(data: odt.Array2dInt32 | odt.Array2dFloat32) -> None:
    """
    Sort each row of a 2D array independently, in place, ascending.

    Each row is treated as its own radix-sort segment, so rows are reordered internally
    but their relative row order is unaffected.

    Parameters
    ----------
    data
        ``(n, w)`` ``int32`` or ``float32`` device array sorted in place, row by row.

    Raises
    ------
    TypeError
        If ``data`` is not ``int32`` or ``float32``.

    Notes
    -----
    Rows no wider than ``SORT_ROWS_INSERTION_MAX_COLS`` are sorted by a per-row insertion sort (one
    thread per row); wider rows fall back to a segmented radix sort. The narrow path is not a
    micro-optimization: ``segmented_sort_pairs`` pays a fixed cost per *segment*, which for rows
    this narrow dominates the comparison work by orders of magnitude.

    The dtype restriction comes from that fallback -- ``warp.utils.segmented_sort_pairs`` takes
    ``int32`` or ``float32`` keys and nothing else -- and it is checked up front rather than left
    to whichever path a row width happens to select, so the accepted dtypes do not depend on ``w``.

    Examples
    --------
    ``numpy.sort(rows, axis=1)``, in place:

    ```python
    import warp as wp

    import ordito as od

    rows = wp.array([[3, 1, 2], [9, 7, 8]], dtype=wp.int32)
    od.array.sort_rows(rows)
    print(rows.numpy().tolist())  # [[1, 2, 3], [7, 8, 9]]
    ```
    """
    # The narrow path's margin, for whoever considers deleting it: a fixed per-segment cost in
    # ``segmented_sort_pairs`` dominates the comparison work for rows this narrow, where a plain
    # compare-and-swap needs none of it.
    #
    # The dtype guard is here rather than at the wide branch because without it the two paths
    # disagree: the insertion kernel is generic, so without it a ``float64`` table sorts silently
    # at ``w <= SORT_ROWS_INSERTION_MAX_COLS`` and raises ``RuntimeError: Unsupported data type:
    # float64`` from inside Warp one column later. Support that turns on the row width is worse
    # than no support.
    if data.dtype not in (wp.int32, wp.float32):
        raise TypeError(f"sort_rows requires an int32 or float32 array, got {data.dtype}")
    n = data.size
    n_rows, n_cols = int(data.shape[0]), int(data.shape[1])
    if n_rows == 0 or n_cols < 2:
        return
    if n_cols <= SORT_ROWS_INSERTION_MAX_COLS:
        _launch.launch(
            kernel_array.SORT_ROWS_INSERTION[data.dtype],
            dim=n_rows,
            inputs=[data],
            device=data.device,
        )
        return

    # ``data.dtype`` is a union, so the buffer reads as an array of the union; Warp's stub wants one
    # dtype per array, which the guard above already established.
    data_buffer = cast(
        "wp.array[wp.int32] | wp.array[wp.float32]",
        _launch.empty(n * 2, dtype=data.dtype, device=data.device),
    )
    _launch.copy(data_buffer, data, count=n)
    # The payload is never read: only the keys come back. Its lower half needs no identity and its
    # upper half is sort scratch.
    indices_buffer = _launch.empty(2 * n, dtype=wp.int32, device=data.device)
    segment_start_indices = arange(0, (n // n_cols + 1) * n_cols, n_cols, device=data.device)
    wp.utils.segmented_sort_pairs(
        data_buffer, indices_buffer, n, segment_start_indices=segment_start_indices
    )
    _launch.copy(data, data_buffer, count=n)

triplet_buffers

triplet_buffers(
    n_triplets: int, dtype: type[Block], device: DeviceLike
) -> tuple[
    wp.array[wp.int32],
    wp.array[wp.int32],
    wp.array[odt.Block],
]

Uninitialized (rows, cols, values) COO buffers for one csr_from_triplets build.

Parameters:

Name Type Description Default
n_triplets int

Length of each of the three buffers: the number of (row, col, value) entries the writing kernel will emit, counting duplicates, since csr_from_triplets sums entries that land on the same position.

required
dtype type[Block]

Element type of the value buffer. A scalar (wp.float32 / wp.float64) for a 1x1-block matrix, or a matrix type (wp.mat22d) for a block matrix.

required
device DeviceLike

Warp device for all three buffers.

required

Returns:

Type Description
(rows, cols, values)

(n_triplets,) each, on device; values takes dtype. All three are uninitialized -- the caller's kernel is expected to write every entry.

Notes

wp.empty rather than wp.zeros deliberately: a triplet writer fills all three buffers, so zeroing them first would be three wasted launches. A kernel that emits fewer than n_triplets entries must therefore write an explicit structural zero (typically a self-entry) or point the slot outside the matrix, where the build drops it; every operator build in this package keeps numerical zeros -- see the note on index_sparse, the one caller that prunes.

See Also

index_sparse

Examples:

Fill the three buffers, then assemble them; the two (0, 0) triplets sum:

import warp as wp

import ordito as od

rows, cols, values = od.array.triplet_buffers(3, wp.float32, wp.get_device())
wp.copy(rows, wp.array([0, 1, 0], dtype=wp.int32))
wp.copy(cols, wp.array([0, 1, 0], dtype=wp.int32))
wp.copy(values, wp.array([1.0, 3.0, 1.0], dtype=wp.float32))
matrix = od.array.csr_from_triplets(2, 2, rows, cols, values)
print(matrix.nnz_sync())  # 2
print(matrix.values.numpy()[:2].tolist())  # [2.0, 3.0]
Source code in ordito/array.py
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
def triplet_buffers(
    n_triplets: int, dtype: type[odt.Block], device: wp.DeviceLike
) -> tuple[wp.array[wp.int32], wp.array[wp.int32], wp.array[odt.Block]]:
    """
    Uninitialized ``(rows, cols, values)`` COO buffers for one ``csr_from_triplets`` build.

    Parameters
    ----------
    n_triplets
        Length of each of the three buffers: the number of ``(row, col, value)`` entries the
        writing kernel will emit, counting duplicates, since
        [`csr_from_triplets`][ordito.array.csr_from_triplets]
        sums entries that land on the same position.
    dtype
        Element type of the value buffer. A scalar (``wp.float32`` / ``wp.float64``) for a
        1x1-block matrix, or a matrix type (``wp.mat22d``) for a block matrix.
    device
        Warp device for all three buffers.

    Returns
    -------
    rows, cols, values
        ``(n_triplets,)`` each, on ``device``; ``values`` takes ``dtype``. All three are
        **uninitialized** -- the caller's kernel is expected to write every entry.

    Notes
    -----
    ``wp.empty`` rather than ``wp.zeros`` deliberately: a triplet writer fills all three buffers,
    so zeroing them first would be three wasted launches. A kernel that emits *fewer* than
    ``n_triplets`` entries must therefore write an explicit structural zero (typically a
    self-entry) or point the slot outside the matrix, where the build drops it; every operator
    build in this package keeps numerical zeros -- see the note on
    [`index_sparse`][ordito.array.index_sparse], the one caller that prunes.

    See Also
    --------
    [`index_sparse`][ordito.array.index_sparse]

    Examples
    --------
    Fill the three buffers, then assemble them; the two ``(0, 0)`` triplets sum:

    ```python
    import warp as wp

    import ordito as od

    rows, cols, values = od.array.triplet_buffers(3, wp.float32, wp.get_device())
    wp.copy(rows, wp.array([0, 1, 0], dtype=wp.int32))
    wp.copy(cols, wp.array([0, 1, 0], dtype=wp.int32))
    wp.copy(values, wp.array([1.0, 3.0, 1.0], dtype=wp.float32))
    matrix = od.array.csr_from_triplets(2, 2, rows, cols, values)
    print(matrix.nnz_sync())  # 2
    print(matrix.values.numpy()[:2].tolist())  # [2.0, 3.0]
    ```
    """
    rows = _launch.empty(n_triplets, dtype=wp.int32, device=device)
    cols = _launch.empty(n_triplets, dtype=wp.int32, device=device)
    values = _launch.empty(n_triplets, dtype=dtype, device=device)
    return rows, cols, values

empty_square_bsr

empty_square_bsr(
    n_rows: int, dtype: type[Block], device: DeviceLike
) -> odt.BsrMatrix[odt.Block]

Zero-nnz (n_rows, n_rows) operator, the n_faces == 0 return several assemblers share.

A square BSR matrix with no faces to assemble from is still a valid, correctly-shaped operator -- just an empty one -- so laplacian.cotmatrix, laplacian.connection_laplacian, laplacian.graph_laplacian and energies's assembly wrappers all construct this exact matrix for their empty-mesh early return.

Parameters:

Name Type Description Default
n_rows int

Row and column count of the square matrix.

required
dtype type[Block]

Element type of the (empty) value buffer -- a scalar for a 1x1-block matrix, or a matrix type (e.g. wp.mat22d) for a block matrix.

required
device DeviceLike

Warp device for the matrix.

required

Returns:

Type Description
BsrMatrix

(n_rows, n_rows) square matrix with zero stored entries, on device.

See Also

bsr_from_csr

Examples:

import warp as wp

import ordito as od

matrix = od.array.empty_square_bsr(4, wp.float32, wp.get_device())
print(matrix.shape)  # (4, 4)
print(matrix.nnz)  # 0
Source code in ordito/array.py
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
def empty_square_bsr(
    n_rows: int, dtype: type[odt.Block], device: wp.DeviceLike
) -> odt.BsrMatrix[odt.Block]:
    """
    Zero-nnz ``(n_rows, n_rows)`` operator, the ``n_faces == 0`` return several assemblers share.

    A square BSR matrix with no faces to assemble from is still a valid, correctly-shaped
    operator -- just an empty one -- so [`laplacian.cotmatrix`][ordito.laplacian.cotmatrix],
    [`laplacian.connection_laplacian`][ordito.laplacian.connection_laplacian],
    [`laplacian.graph_laplacian`][ordito.laplacian.graph_laplacian] and
    [`energies`][ordito.energies]'s assembly wrappers all construct this exact matrix for their
    empty-mesh early return.

    Parameters
    ----------
    n_rows
        Row and column count of the square matrix.
    dtype
        Element type of the (empty) value buffer -- a scalar for a 1x1-block matrix, or a matrix
        type (e.g. ``wp.mat22d``) for a block matrix.
    device
        Warp device for the matrix.

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n_rows, n_rows)`` square matrix with zero stored entries, on ``device``.

    See Also
    --------
    [`bsr_from_csr`][ordito.array.bsr_from_csr]

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

    import ordito as od

    matrix = od.array.empty_square_bsr(4, wp.float32, wp.get_device())
    print(matrix.shape)  # (4, 4)
    print(matrix.nnz)  # 0
    ```
    """
    return bsr_from_csr(
        n_rows,
        n_rows,
        _launch.zeros(n_rows + 1, dtype=wp.int32, device=device),
        _launch.empty(0, dtype=wp.int32, device=device),
        _launch.empty(0, dtype=dtype, device=device),
        nnz=0,
    )

bsr_from_csr

bsr_from_csr(
    n_rows: int,
    n_cols: int,
    offsets: array[int32],
    columns: array[int32],
    values: array[Block, Any],
    *,
    nnz: int | None = None,
) -> odt.BsrMatrix[odt.Block]

Wrap compressed-row arrays that already hold a matrix's storage as a BsrMatrix, no copy.

values' dtype is the block type: a scalar for a 1x1-block (CSR) matrix, or a matrix type such as wp.mat22d. Row i's entries are columns[offsets[i] : offsets[i + 1]], and every warp.sparse operation expects them sorted by column with no duplicates.

Parameters:

Name Type Description Default
n_rows int

Block row and column counts.

required
n_cols int

Block row and column counts.

required
offsets array[int32]

(n_rows + 1,) row offsets, total-terminated (offsets[-1] is the stored entry count).

required
columns array[int32]

(n_capacity,) each, one element per stored entry, n_capacity >= offsets[-1]. A longer buffer is a capacity, as warp.sparse itself allocates.

required
values array[int32]

(n_capacity,) each, one element per stored entry, n_capacity >= offsets[-1]. A longer buffer is a capacity, as warp.sparse itself allocates.

required
nnz int | None

The stored entry count, when the host knows it. None records the buffers' length as an upper bound and starts the asynchronous copy of offsets[-1] that BsrMatrix.nnz_sync() then completes -- the state warp.sparse.bsr_from_triplets leaves, with no host synchronization here.

None

Returns:

Type Description
BsrMatrix

(n_rows, n_cols) compact matrix holding exactly these arrays.

Raises:

Type Description
ValueError

If offsets is not n_rows + 1 long, or columns and values differ in length.

See Also

csr_from_keys csr_from_triplets

Examples:

The matrix [[1, 0], [2, 3]] from its compressed rows, applied to [1, 1]:

import warp as wp
import warp.sparse as wps

import ordito as od

offsets = wp.array([0, 1, 3], dtype=wp.int32)
columns = wp.array([0, 0, 1], dtype=wp.int32)
values = wp.array([1.0, 2.0, 3.0], dtype=wp.float32)
matrix = od.array.bsr_from_csr(2, 2, offsets, columns, values, nnz=3)
print(matrix.shape)  # (2, 2)
ones = wp.ones(2, dtype=wp.float32)
print(wps.bsr_mv(matrix, ones).numpy().tolist())  # [1.0, 5.0]
Source code in ordito/array.py
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
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
def bsr_from_csr(
    n_rows: int,
    n_cols: int,
    offsets: wp.array[wp.int32],
    columns: wp.array[wp.int32],
    values: wp.array[odt.Block, Any],
    *,
    nnz: int | None = None,
) -> odt.BsrMatrix[odt.Block]:
    """
    Wrap compressed-row arrays that already hold a matrix's storage as a ``BsrMatrix``, no copy.

    ``values``' dtype is the block type: a scalar for a 1x1-block (CSR) matrix, or a matrix type
    such as ``wp.mat22d``. Row ``i``'s entries are ``columns[offsets[i] : offsets[i + 1]]``, and
    every ``warp.sparse`` operation expects them sorted by column with no duplicates.

    Parameters
    ----------
    n_rows, n_cols
        Block row and column counts.
    offsets
        ``(n_rows + 1,)`` row offsets, total-terminated (``offsets[-1]`` is the stored entry
        count).
    columns, values
        ``(n_capacity,)`` each, one element per stored entry, ``n_capacity >= offsets[-1]``. A
        longer buffer is a capacity, as ``warp.sparse`` itself allocates.
    nnz
        The stored entry count, when the host knows it. ``None`` records the buffers' length as an
        upper bound and starts the asynchronous copy of ``offsets[-1]`` that
        ``BsrMatrix.nnz_sync()`` then completes -- the state ``warp.sparse.bsr_from_triplets``
        leaves, with no host synchronization here.

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n_rows, n_cols)`` compact matrix holding exactly these arrays.

    Raises
    ------
    ValueError
        If ``offsets`` is not ``n_rows + 1`` long, or ``columns`` and ``values`` differ in length.

    See Also
    --------
    [`csr_from_keys`][ordito.array.csr_from_keys]
    [`csr_from_triplets`][ordito.array.csr_from_triplets]

    Examples
    --------
    The matrix ``[[1, 0], [2, 3]]`` from its compressed rows, applied to ``[1, 1]``:

    ```python
    import warp as wp
    import warp.sparse as wps

    import ordito as od

    offsets = wp.array([0, 1, 3], dtype=wp.int32)
    columns = wp.array([0, 0, 1], dtype=wp.int32)
    values = wp.array([1.0, 2.0, 3.0], dtype=wp.float32)
    matrix = od.array.bsr_from_csr(2, 2, offsets, columns, values, nnz=3)
    print(matrix.shape)  # (2, 2)
    ones = wp.ones(2, dtype=wp.float32)
    print(wps.bsr_mv(matrix, ones).numpy().tolist())  # [1.0, 5.0]
    ```
    """
    if offsets.size != n_rows + 1:
        raise ValueError(f"offsets must have n_rows + 1 = {n_rows + 1} entries, got {offsets.size}")
    if columns.size != int(values.shape[0]):
        raise ValueError(
            f"columns and values must have one element per entry, got {columns.size} and "
            f"{values.shape[0]}"
        )
    matrix = odt.bsr_matrix_t(values.dtype)()
    matrix.nrow = n_rows
    matrix.ncol = n_cols
    matrix.offsets = offsets
    matrix.columns = columns
    matrix.values = values
    matrix.row_counts = None
    if nnz is None:
        matrix.notify_nnz_changed(nnz_capacity=columns.size)
    else:
        matrix.notify_nnz_changed(nnz=nnz)
    return matrix

bsr_with_values

bsr_with_values(
    matrix: SparseMatrix, values: array[Block, Any]
) -> odt.BsrMatrix[odt.Block]

Build a sparse matrix with matrix's sparsity pattern and the given block values.

The pattern is shared, not copied: the result holds matrix's offsets, columns and row_counts arrays, and matrix itself is not referenced. It is how a system whose pattern is known to equal an existing operator's -- a mass-plus-stiffness system over a Laplacian that already stores every diagonal -- is built without merging two patterns.

Parameters:

Name Type Description Default
matrix SparseMatrix

(n_rows, n_cols) operator, in blocks, whose pattern the result takes. Rewriting that pattern in place afterwards rewrites the result's too.

required
values array[Block, Any]

(matrix.values.shape[0],) one block per storage slot of matrix, laid out as matrix.values is; its dtype is the result's block type. A matrix assembled from keys can hold more slots than stored entries (its nnz): the entries come first, in columns order, and the slots past them are carried along but never read.

required

Returns:

Type Description
BsrMatrix

(n_rows, n_cols) blocks, as matrix, with matrix's stored entry count.

Raises:

Type Description
ValueError

If values does not hold one block per storage slot of matrix (matrix.values.shape[0]).

RuntimeError

If matrix and values are not on one device.

See Also

bsr_from_csr block_diag

Examples:

All-one values on a cotangent Laplacian's pattern: each row then sums to its stored count, a vertex's degree plus its diagonal (5 or 6 neighbours on an icosphere). values is sized like L.values, which here holds more slots than L's 1122 stored entries:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
L = od.laplacian.cotmatrix(vertices, faces)
print(L.nnz_sync(), L.values.shape[0])  # 1122 2082
ones = wp.full(L.values.shape[0], 1.0, dtype=wp.float32)
counts = od.array.bsr_with_values(L, ones)
print(counts.offsets is L.offsets)  # True
row_sums = (counts @ wp.full(counts.shape[0], 1.0, dtype=wp.float32)).numpy()
print(row_sums.min(), row_sums.max())  # 6.0 7.0
Source code in ordito/array.py
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
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
def bsr_with_values(
    matrix: odt.SparseMatrix, values: wp.array[odt.Block, Any]
) -> odt.BsrMatrix[odt.Block]:
    """
    Build a sparse matrix with ``matrix``'s sparsity pattern and the given block values.

    The pattern is **shared**, not copied: the result holds ``matrix``'s ``offsets``, ``columns``
    and ``row_counts`` arrays, and ``matrix`` itself is not referenced. It is how a system whose
    pattern is known to equal an existing operator's -- a mass-plus-stiffness system over a
    Laplacian that already stores every diagonal -- is built without merging two patterns.

    Parameters
    ----------
    matrix
        ``(n_rows, n_cols)`` operator, in blocks, whose pattern the result takes. Rewriting that
        pattern in place afterwards rewrites the result's too.
    values
        ``(matrix.values.shape[0],)`` one block per storage slot of ``matrix``, laid out as
        ``matrix.values`` is; its dtype is the result's block type. A matrix assembled from keys
        can hold more slots than stored entries (its ``nnz``): the entries come first, in
        ``columns`` order, and the slots past them are carried along but never read.

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n_rows, n_cols)`` blocks, as ``matrix``, with ``matrix``'s stored entry count.

    Raises
    ------
    ValueError
        If ``values`` does not hold one block per storage slot of ``matrix``
        (``matrix.values.shape[0]``).
    RuntimeError
        If ``matrix`` and ``values`` are not on one device.

    See Also
    --------
    [`bsr_from_csr`][ordito.array.bsr_from_csr]
    [`block_diag`][ordito.array.block_diag]

    Examples
    --------
    All-one values on a cotangent Laplacian's pattern: each row then sums to its stored count, a
    vertex's degree plus its diagonal (5 or 6 neighbours on an icosphere). ``values`` is sized
    like ``L.values``, which here holds more slots than ``L``'s 1122 stored entries:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    L = od.laplacian.cotmatrix(vertices, faces)
    print(L.nnz_sync(), L.values.shape[0])  # 1122 2082
    ones = wp.full(L.values.shape[0], 1.0, dtype=wp.float32)
    counts = od.array.bsr_with_values(L, ones)
    print(counts.offsets is L.offsets)  # True
    row_sums = (counts @ wp.full(counts.shape[0], 1.0, dtype=wp.float32)).numpy()
    print(row_sums.min(), row_sums.max())  # 6.0 7.0
    ```
    """
    require_same_device(matrix=matrix, values=values)
    if values.shape[0] != matrix.values.size:
        raise ValueError(
            f"values must hold one block per storage slot of matrix.values "
            f"({matrix.values.shape[0]}), got {values.shape[0]}"
        )
    result = odt.bsr_matrix_t(values.dtype)()
    result.nrow = int(matrix.nrow)
    result.ncol = int(matrix.ncol)
    result.offsets = matrix.offsets
    result.columns = matrix.columns
    result.values = values
    result.row_counts = matrix.row_counts
    result.notify_nnz_changed(nnz=int(matrix.nnz))
    return result

block_diag

block_diag(
    matrices: Sequence[SparseMatrix],
) -> odt.BsrMatrix[wp.float64]

Stack square sparse operators into one block-diagonal float64 operator.

The operator scipy.sparse.block_diag builds. Its use here is to solve several independent systems as one: a single conjugate-gradient iteration over the stack advances every block at once, in the launches of one solve rather than several, and stops when the slowest block does. A wp.mat22d operator enters as its scalar expansion over interleaved unknowns -- the memory of a wp.vec2d array viewed as float64 -- so a tangent-field system and scalar systems stack together.

The result is kept per set of operators: a later call with the same operators, over the same storage, returns the same matrix, so a solve against it replays its recorded loop (see solve_spd). The stack is a copy, so values rewritten in place in one of matrices afterwards do not reach it.

Parameters:

Name Type Description Default
matrices Sequence[SparseMatrix]

One or more square operators, float64 or wp.mat22d blocks, on one device.

required

Returns:

Type Description
BsrMatrix

(n, n) operator whose row count n is the sum of the blocks' scalar row counts, in the order given.

Raises:

Type Description
ValueError

If matrices is empty, or holds an operator that is not square or has another block type.

RuntimeError

If matrices are not all on one device.

See Also

solve_spd_settled replicated_operator

Examples:

import ordito as od

sphere_vertices, sphere_faces = od.creation.icosphere(subdivisions=1)
box_vertices, box_faces = od.creation.box()
sphere_system = od.heat.heat_operators(sphere_vertices, sphere_faces)[0]
box_system = od.heat.heat_operators(box_vertices, box_faces)[0]
stacked = od.array.block_diag([sphere_system, box_system])
print(sphere_system.shape, box_system.shape, stacked.shape)  # (42, 42) (8, 8) (50, 50)
Source code in ordito/array.py
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
def block_diag(matrices: Sequence[odt.SparseMatrix]) -> odt.BsrMatrix[wp.float64]:
    """
    Stack square sparse operators into one block-diagonal ``float64`` operator.

    The operator ``scipy.sparse.block_diag`` builds. Its use here is to solve several independent
    systems as one: a single conjugate-gradient iteration over the stack advances every block at
    once, in the launches of one solve rather than several, and stops when the slowest block does.
    A ``wp.mat22d`` operator enters as its scalar expansion over interleaved unknowns -- the memory
    of a ``wp.vec2d`` array viewed as ``float64`` -- so a tangent-field system and scalar systems
    stack together.

    The result is **kept per set of operators**: a later call with the same operators, over the
    same storage, returns the same matrix, so a solve against it replays its recorded loop (see
    [`solve_spd`][ordito.linalg.solve_spd]). The stack is a copy, so values rewritten in place
    in one of ``matrices`` afterwards do not reach it.

    Parameters
    ----------
    matrices
        One or more square operators, ``float64`` or ``wp.mat22d`` blocks, on one device.

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n, n)`` operator whose row count ``n`` is the sum of the blocks' scalar row counts, in
        the order given.

    Raises
    ------
    ValueError
        If ``matrices`` is empty, or holds an operator that is not square or has another block type.
    RuntimeError
        If ``matrices`` are not all on one device.

    See Also
    --------
    [`solve_spd_settled`][ordito.linalg.solve_spd_settled]
    [`replicated_operator`][ordito.linalg.replicated_operator]

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

    sphere_vertices, sphere_faces = od.creation.icosphere(subdivisions=1)
    box_vertices, box_faces = od.creation.box()
    sphere_system = od.heat.heat_operators(sphere_vertices, sphere_faces)[0]
    box_system = od.heat.heat_operators(box_vertices, box_faces)[0]
    stacked = od.array.block_diag([sphere_system, box_system])
    print(sphere_system.shape, box_system.shape, stacked.shape)  # (42, 42) (8, 8) (50, 50)
    ```
    """
    require_same_device(matrices=list(matrices))
    if len(matrices) == 0:
        raise ValueError("block_diag needs at least one operator")
    for matrix in matrices:
        if matrix.values.dtype not in (wp.float64, wp.mat22d) or matrix.nrow != matrix.ncol:
            raise ValueError(
                "block_diag stacks square float64 or wp.mat22d operators, got a "
                f"{matrix.nrow} x {matrix.ncol} operator of {matrix.values.dtype}"
            )
    identity = tuple(
        i
        for matrix in matrices
        for i in (id(matrix.offsets), id(matrix.columns), id(matrix.values))
    )
    entries = _BLOCK_DIAG_CACHE.setdefault(matrices[0], {})
    cached = entries.get(identity)
    if cached is not None:
        return cached[1]
    blocks = [
        scalar_expansion(matrix) if matrix.values.dtype == wp.mat22d else matrix
        for matrix in matrices
    ]
    device = blocks[0].device
    n_rows = sum(int(block.nrow) for block in blocks)
    capacity = sum(block.values.size for block in blocks)
    # The descriptor table filled as host records and uploaded as words, so Warp never rebuilds the
    # struct's record layout to convert a list of instances.
    records = _launch.struct_records(kernel_array.CsrBlock, len(blocks))
    for name in ("offsets", "columns", "values"):
        field = records[name]
        arrays = [getattr(block, name) for block in blocks]
        field["data"] = [int(arr.ptr) for arr in arrays]
        field["shape"][:, 0] = [int(arr.shape[0]) for arr in arrays]
        field["strides"][:, 0] = [int(arr.strides[0]) for arr in arrays]
        field["ndim"] = 1
    records["n_rows"] = [int(block.nrow) for block in blocks]
    offsets = _launch.empty(n_rows + 1, dtype=wp.int32, device=device)
    columns = _launch.empty(capacity, dtype=wp.int32, device=device)
    values = _launch.empty(capacity, dtype=wp.float64, device=device)
    if n_rows == 0:
        _launch.zero_(offsets)
    else:
        _launch.launch(
            kernel_array.stack_block_diagonal,
            dim=n_rows,
            inputs=[_launch.struct_array(records, kernel_array.CsrBlock, device)],
            outputs=[offsets, columns, values],
            device=device,
        )
    # A capacity, as the blocks' own counts are: the offsets bound every row.
    stacked = bsr_from_csr(n_rows, n_rows, offsets, columns, values, nnz=capacity)
    # The entry holds every block's arrays, so the identities in its key cannot be reused.
    held = tuple((matrix.offsets, matrix.columns, matrix.values) for matrix in matrices)
    entries[identity] = (held, stacked)
    return stacked

scalar_expansion

scalar_expansion(
    matrix: SparseMatrix,
) -> odt.BsrMatrix[wp.float64]

Return a wp.mat22d operator as the float64 CSR over its interleaved unknowns.

Unknown i of the block operator becomes unknowns 2 * i and 2 * i + 1, so a wp.vec2d right-hand side or solution is the same bytes as the float64 vector this matrix acts on. The scalar operator is the one scipy.sparse.bsr_matrix(...).tocsr() builds.

The storage is allocated once per operator and its values are rewritten on every call, so values changed in place are what the returned matrix holds, and repeated calls return the same matrix object (a solver state kept for it is reused). An operator whose arrays are replaced is expanded into new storage.

Parameters:

Name Type Description Default
matrix SparseMatrix

(n, n) block sparse operator with wp.mat22d blocks.

required

Returns:

Type Description
BsrMatrix[float64]

(2 * n, 2 * n) scalar sparse operator. It aliases storage the next call on the same operator overwrites.

Raises:

Type Description
ValueError

If matrix does not have wp.mat22d blocks.

See Also

block_diag : Stacks expanded operators with scalar ones.

Examples:

import warp as wp

import ordito as od

offsets = wp.array([0, 1], dtype=wp.int32)
columns = wp.array([0], dtype=wp.int32)
values = wp.array([wp.mat22d(2.0, 1.0, 1.0, 3.0)], dtype=wp.mat22d)
matrix = od.array.bsr_from_csr(1, 1, offsets, columns, values)
scalar = od.array.scalar_expansion(matrix)
print(scalar.shape)  # (2, 2)
print(scalar.values.numpy().tolist())  # [2.0, 1.0, 1.0, 3.0]
Source code in ordito/array.py
1554
1555
1556
1557
1558
1559
1560
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
def scalar_expansion(matrix: odt.SparseMatrix) -> odt.BsrMatrix[wp.float64]:
    """
    Return a ``wp.mat22d`` operator as the ``float64`` CSR over its interleaved unknowns.

    Unknown ``i`` of the block operator becomes unknowns ``2 * i`` and ``2 * i + 1``, so a
    ``wp.vec2d`` right-hand side or solution is the same bytes as the ``float64`` vector this
    matrix acts on. The scalar operator is the one ``scipy.sparse.bsr_matrix(...).tocsr()``
    builds.

    The storage is allocated once per operator and its values are rewritten on every call, so
    values changed in place are what the returned matrix holds, and repeated calls return the
    same matrix object (a solver state kept for it is reused). An operator whose arrays are
    replaced is expanded into new storage.

    Parameters
    ----------
    matrix
        ``(n, n)`` block sparse operator with ``wp.mat22d`` blocks.

    Returns
    -------
    odt.BsrMatrix[wp.float64]
        ``(2 * n, 2 * n)`` scalar sparse operator. It aliases storage the next call on the same
        operator overwrites.

    Raises
    ------
    ValueError
        If ``matrix`` does not have ``wp.mat22d`` blocks.

    See Also
    --------
    [`block_diag`][ordito.array.block_diag] : Stacks expanded operators with scalar ones.

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

    import ordito as od

    offsets = wp.array([0, 1], dtype=wp.int32)
    columns = wp.array([0], dtype=wp.int32)
    values = wp.array([wp.mat22d(2.0, 1.0, 1.0, 3.0)], dtype=wp.mat22d)
    matrix = od.array.bsr_from_csr(1, 1, offsets, columns, values)
    scalar = od.array.scalar_expansion(matrix)
    print(scalar.shape)  # (2, 2)
    print(scalar.values.numpy().tolist())  # [2.0, 1.0, 1.0, 3.0]
    ```
    """
    if matrix.values.dtype != wp.mat22d:
        raise ValueError(
            f"scalar_expansion expands wp.mat22d operators, got blocks of {matrix.values.dtype}"
        )
    identity = (id(matrix.offsets), id(matrix.columns), id(matrix.values))
    device = matrix.device
    n_rows = int(matrix.nrow)
    cached = _EXPANSION_CACHE.get(matrix)
    if cached is not None and cached[0][0] == identity:
        expanded = cached[1]
    else:
        # Sized off the ``values`` capacity rather than ``nnz``: the row offsets alone bound every
        # row, so a stale capacity's tail is allocated and never read.
        capacity = 4 * matrix.values.size
        offsets = _launch.empty(2 * n_rows + 1, dtype=wp.int32, device=device)
        if n_rows == 0:
            _launch.zero_(offsets)
        expanded = bsr_from_csr(
            2 * n_rows,
            2 * int(matrix.ncol),
            offsets,
            _launch.empty(capacity, dtype=wp.int32, device=device),
            _launch.empty(capacity, dtype=wp.float64, device=device),
            nnz=4 * int(matrix.nnz),
        )
        # The entry holds the block arrays, so the identities in its key cannot be reused.
        _EXPANSION_CACHE[matrix] = (
            (identity, (matrix.offsets, matrix.columns, matrix.values)),
            expanded,
        )
    if n_rows > 0:
        _launch.launch(
            kernel_array.expand_block_csr_2x2,
            dim=n_rows,
            inputs=[matrix.offsets, matrix.columns, matrix.values],
            outputs=[expanded.offsets, expanded.columns, expanded.values],
            device=device,
        )
    return expanded

csr_key_buffers

csr_key_buffers(
    count: int, device: DeviceLike
) -> tuple[wp.array[wp.uint64], wp.array[wp.int32]]

Uninitialized (keys, order) buffers for one csr_from_keys.

Both are 2 * count long because warp.utils.radix_sort_pairs sorts in place with its upper halves as scratch; a producer writes entry i's key into keys[i] and its payload (usually i itself, or anything that locates the entry's value) into order[i], for i < count, and never touches the upper halves.

Parameters:

Name Type Description Default
count int

The number of keys the producer writes, counting duplicates.

required
device DeviceLike

Warp device for both buffers.

required

Returns:

Type Description
(keys, order)

(2 * count,) each.

See Also

csr_from_keys

Examples:

import warp as wp

import ordito as od

keys, order = od.array.csr_key_buffers(3, wp.get_device())
print(keys.shape, order.shape)  # (6,) (6,)
Source code in ordito/array.py
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
1682
1683
1684
def csr_key_buffers(
    count: int, device: wp.DeviceLike
) -> tuple[wp.array[wp.uint64], wp.array[wp.int32]]:
    """
    Uninitialized ``(keys, order)`` buffers for one [`csr_from_keys`][ordito.array.csr_from_keys].

    Both are ``2 * count`` long because ``warp.utils.radix_sort_pairs`` sorts in place with its
    upper halves as scratch; a producer writes entry ``i``'s key into ``keys[i]`` and its payload
    (usually ``i`` itself, or anything that locates the entry's value) into ``order[i]``, for
    ``i < count``, and never touches the upper halves.

    Parameters
    ----------
    count
        The number of keys the producer writes, counting duplicates.
    device
        Warp device for both buffers.

    Returns
    -------
    keys, order
        ``(2 * count,)`` each.

    See Also
    --------
    [`csr_from_keys`][ordito.array.csr_from_keys]

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

    import ordito as od

    keys, order = od.array.csr_key_buffers(3, wp.get_device())
    print(keys.shape, order.shape)  # (6,) (6,)
    ```
    """
    keys, order = _launch.sort_buffers(count, wp.uint64, device)
    return keys, order

csr_from_keys

csr_from_keys(
    keys: array[uint64],
    order: array[int32],
    count: int,
    n_rows: int,
    n_cols: int,
) -> tuple[
    wp.array[wp.int32],
    wp.array[wp.int32],
    wp.array[wp.int32],
]

Sort row-major entry keys and return the CSR pattern they spell, with each entry's positions.

A producer writes count keys row * n_cols + col -- kernels/array.csr_key, which maps an index outside the matrix to the sentinel n_rows * n_cols -- with a payload each, into csr_key_buffers. This sorts them in place (stably, and only over the bits n_rows * n_cols needs), keeps each run of equal in-range keys as one entry and drops the sentinels. Entry e's contributors are the payloads order[starts[e] : starts[e + 1]], in the order the producer wrote them, so a value kernel can form the entry's value deterministically. Nothing is read back to the host.

Parameters:

Name Type Description Default
keys array[uint64]

(2 * count,) sort buffers, holding the keys and payloads in their first halves. Both are sorted in place, and both upper halves are overwritten.

required
order array[uint64]

(2 * count,) sort buffers, holding the keys and payloads in their first halves. Both are sorted in place, and both upper halves are overwritten.

required
count int

The number of keys written.

required
n_rows int

The matrix shape the keys encode.

required
n_cols int

The matrix shape the keys encode.

required

Returns:

Type Description
offsets

(n_rows + 1,) row bounds, total-terminated.

columns

(count,) sorted column index of each entry, per row, of which the first offsets[-1] are written.

starts

(count + 1,) sorted positions: entry e's first sorted position is starts[e] and starts[offsets[-1]] closes the last. A view of keys' upper half.

See Also

csr_from_triplets bsr_from_csr

Examples:

Four keys of a 2 x 3 matrix: (0, 1) twice, (1, 2) once, and the sentinel 6, which is dropped. Entry 0 collects payloads 0 and 2:

import warp as wp

import ordito as od

keys, order = od.array.csr_key_buffers(4, wp.get_device())
wp.copy(keys, wp.array([1, 5, 1, 6], dtype=wp.uint64))
wp.copy(order, wp.array([0, 1, 2, 3], dtype=wp.int32))
offsets, columns, starts = od.array.csr_from_keys(keys, order, 4, 2, 3)
print(offsets.numpy().tolist())  # [0, 1, 2]
print(columns.numpy()[:2].tolist())  # [1, 2]
print(starts.numpy()[:3].tolist())  # [0, 2, 3]
print(order.numpy()[:3].tolist())  # [0, 2, 1]
Source code in ordito/array.py
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
def csr_from_keys(
    keys: wp.array[wp.uint64], order: wp.array[wp.int32], count: int, n_rows: int, n_cols: int
) -> tuple[wp.array[wp.int32], wp.array[wp.int32], wp.array[wp.int32]]:
    """
    Sort row-major entry keys and return the CSR pattern they spell, with each entry's positions.

    A producer writes ``count`` keys ``row * n_cols + col`` -- ``kernels/array.csr_key``, which
    maps an index outside the matrix to the sentinel ``n_rows * n_cols`` -- with a payload each,
    into [`csr_key_buffers`][ordito.array.csr_key_buffers]. This sorts them in place (stably, and
    only over the bits ``n_rows * n_cols`` needs), keeps each run of equal in-range keys as one
    entry and drops the sentinels. Entry ``e``'s contributors are the payloads
    ``order[starts[e] : starts[e + 1]]``, in the order the producer wrote them, so a value kernel
    can form the entry's value deterministically. Nothing is read back to the host.

    Parameters
    ----------
    keys, order
        ``(2 * count,)`` sort buffers, holding the keys and payloads in their first halves. Both
        are sorted in place, and both upper halves are overwritten.
    count
        The number of keys written.
    n_rows, n_cols
        The matrix shape the keys encode.

    Returns
    -------
    offsets
        ``(n_rows + 1,)`` row bounds, total-terminated.
    columns
        ``(count,)`` sorted column index of each entry, per row, of which the first
        ``offsets[-1]`` are written.
    starts
        ``(count + 1,)`` sorted positions: entry ``e``'s first sorted position is ``starts[e]`` and
        ``starts[offsets[-1]]`` closes the last. A view of ``keys``' upper half.

    See Also
    --------
    [`csr_from_triplets`][ordito.array.csr_from_triplets]
    [`bsr_from_csr`][ordito.array.bsr_from_csr]

    Examples
    --------
    Four keys of a 2 x 3 matrix: ``(0, 1)`` twice, ``(1, 2)`` once, and the sentinel ``6``, which
    is dropped. Entry 0 collects payloads 0 and 2:

    ```python
    import warp as wp

    import ordito as od

    keys, order = od.array.csr_key_buffers(4, wp.get_device())
    wp.copy(keys, wp.array([1, 5, 1, 6], dtype=wp.uint64))
    wp.copy(order, wp.array([0, 1, 2, 3], dtype=wp.int32))
    offsets, columns, starts = od.array.csr_from_keys(keys, order, 4, 2, 3)
    print(offsets.numpy().tolist())  # [0, 1, 2]
    print(columns.numpy()[:2].tolist())  # [1, 2]
    print(starts.numpy()[:3].tolist())  # [0, 2, 3]
    print(order.numpy()[:3].tolist())  # [0, 2, 1]
    ```
    """
    device = keys.device
    if count == 0:
        return (
            _launch.zeros(n_rows + 1, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.zeros(1, dtype=wp.int32, device=device),
        )
    # Every bound is written by ``csr_from_runs``, the empty matrix's too.
    offsets = _launch.empty(n_rows + 1, dtype=wp.int32, device=device)
    columns = _launch.empty(count, dtype=wp.int32, device=device)
    sentinel = n_rows * n_cols
    _launch.radix_sort_pairs(keys, order, count=count, end_bit=_launch.key_bits(sentinel + 1))
    # The entries' sorted positions live in the key buffer's upper half, sort scratch too: its
    # ``count`` 8-byte slots hold ``count + 1`` 4-byte ones. ``keys`` and ``order`` are one
    # allocation, which every caller holds while it reads ``starts`` beside ``order``, so the alias
    # costs no memory and saves an allocation.
    starts = _launch.alias(keys, wp.int32, 8 * count, count + 1)
    # The run flags and their scan live in the payload buffer's upper half, which is sort scratch.
    inclusive = _launch.view(order, count, 2 * count)
    if wp.get_device(device).is_cpu:
        # The CPU runs a launch's threads in turn: one thread flags, counts and places every
        # position, the same writes in the same order as the three passes below.
        _launch.launch(
            kernel_array.csr_from_sorted_keys_serial,
            dim=1,
            inputs=[
                keys,
                wp.uint64(sentinel),
                wp.int32(n_rows),
                wp.uint64(n_cols),
                inclusive,
                offsets,
                columns,
                starts,
            ],
            device=device,
        )
        return offsets, columns, starts
    _launch.launch(
        kernel_array.csr_run_flags,
        dim=count,
        inputs=[keys, wp.uint64(sentinel), inclusive],
        device=device,
    )
    _launch.array_scan(inclusive, out_array=inclusive, inclusive=True)
    _launch.launch(
        kernel_array.csr_from_runs,
        dim=count,
        inputs=[
            keys,
            inclusive,
            wp.uint64(sentinel),
            wp.int32(n_rows),
            wp.uint64(n_cols),
            offsets,
            columns,
            starts,
        ],
        device=device,
    )
    return offsets, columns, starts

csr_from_triplets

csr_from_triplets(
    n_rows: int,
    n_cols: int,
    rows: ArrayNdInt32,
    cols: ArrayNdInt32,
    values: array[Block, Any],
    *,
    prune_numerical_zeros: bool = False,
) -> odt.BsrMatrix[odt.Block]

Assemble a sparse matrix from coordinate triplets, summing duplicates.

The replacement for warp.sparse.bsr_from_triplets over 1x1 or matrix blocks: a triplet whose row or column is outside the matrix is dropped, duplicates are summed in the triplets' own order, and nothing is read back. It sorts a key over only the bits the shape needs and allocates a fraction of bsr_from_triplets' scratch. Assemblers whose sparsity follows from the mesh write their keys directly with csr_from_keys and never materialize the triplets at all.

Parameters:

Name Type Description Default
n_rows int

Matrix shape in blocks.

required
n_cols int

Matrix shape in blocks.

required
rows ArrayNdInt32

(n_triplets,) wp.int32 block coordinates, one per triplet.

required
cols ArrayNdInt32

(n_triplets,) wp.int32 block coordinates, one per triplet.

required
values array[Block, Any]

(n_triplets,) blocks, one per triplet; its dtype is the matrix's block type (wp.float32, wp.float64, wp.int32 or wp.mat22d).

required
prune_numerical_zeros bool

Drop every entry whose summed value is exactly zero -- including one whose triplets cancel. bsr_from_triplets instead drops zero-valued triplets before summing and keeps an entry that sums to zero, so the two differ only in stored zeros.

False

Returns:

Type Description
BsrMatrix

(n_rows, n_cols) assembled matrix. Its nnz is the triplet count as an upper bound until nnz_sync(), exactly as after bsr_from_triplets.

Raises:

Type Description
ValueError

If rows, cols and values differ in length.

RuntimeError

If they are not all on one device.

KeyError

If values' dtype is not one of the four supported block types.

See Also

csr_from_keys triplet_buffers

Examples:

The matrix [[2, 0], [2, 3]], whose (0, 0) entry is given as two triplets:

import warp as wp

import ordito as od

rows = wp.array([0, 1, 0, 1], dtype=wp.int32)
cols = wp.array([0, 1, 0, 0], dtype=wp.int32)
values = wp.array([1.0, 3.0, 1.0, 2.0], dtype=wp.float32)
matrix = od.array.csr_from_triplets(2, 2, rows, cols, values)
print(matrix.nnz_sync())  # 3
print(matrix.offsets.numpy().tolist())  # [0, 1, 3]
print(matrix.columns.numpy()[:3].tolist())  # [0, 0, 1]
print(matrix.values.numpy()[:3].tolist())  # [2.0, 2.0, 3.0]
Source code in ordito/array.py
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
def csr_from_triplets(
    n_rows: int,
    n_cols: int,
    rows: odt.ArrayNdInt32,
    cols: odt.ArrayNdInt32,
    values: wp.array[odt.Block, Any],
    *,
    prune_numerical_zeros: bool = False,
) -> odt.BsrMatrix[odt.Block]:
    """
    Assemble a sparse matrix from coordinate triplets, summing duplicates.

    The replacement for ``warp.sparse.bsr_from_triplets`` over 1x1 or matrix blocks: a triplet
    whose row or column is outside the matrix is dropped, duplicates are summed in the triplets'
    own order, and nothing is read back. It sorts a key over only the bits the shape needs and
    allocates a fraction of ``bsr_from_triplets``' scratch. Assemblers whose sparsity follows from
    the mesh write their keys directly with [`csr_from_keys`][ordito.array.csr_from_keys] and
    never materialize the triplets at all.

    Parameters
    ----------
    n_rows, n_cols
        Matrix shape in blocks.
    rows, cols
        ``(n_triplets,)`` ``wp.int32`` block coordinates, one per triplet.
    values
        ``(n_triplets,)`` blocks, one per triplet; its dtype is the matrix's block type
        (``wp.float32``, ``wp.float64``, ``wp.int32`` or ``wp.mat22d``).
    prune_numerical_zeros
        Drop every entry whose *summed* value is exactly zero -- including one whose triplets
        cancel. ``bsr_from_triplets`` instead drops zero-valued triplets before summing and keeps
        an entry that sums to zero, so the two differ only in stored zeros.

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n_rows, n_cols)`` assembled matrix. Its ``nnz`` is the triplet count as an upper
        bound until ``nnz_sync()``, exactly as after ``bsr_from_triplets``.

    Raises
    ------
    ValueError
        If ``rows``, ``cols`` and ``values`` differ in length.
    RuntimeError
        If they are not all on one device.
    KeyError
        If ``values``' dtype is not one of the four supported block types.

    See Also
    --------
    [`csr_from_keys`][ordito.array.csr_from_keys]
    [`triplet_buffers`][ordito.array.triplet_buffers]

    Examples
    --------
    The matrix ``[[2, 0], [2, 3]]``, whose ``(0, 0)`` entry is given as two triplets:

    ```python
    import warp as wp

    import ordito as od

    rows = wp.array([0, 1, 0, 1], dtype=wp.int32)
    cols = wp.array([0, 1, 0, 0], dtype=wp.int32)
    values = wp.array([1.0, 3.0, 1.0, 2.0], dtype=wp.float32)
    matrix = od.array.csr_from_triplets(2, 2, rows, cols, values)
    print(matrix.nnz_sync())  # 3
    print(matrix.offsets.numpy().tolist())  # [0, 1, 3]
    print(matrix.columns.numpy()[:3].tolist())  # [0, 0, 1]
    print(matrix.values.numpy()[:3].tolist())  # [2.0, 2.0, 3.0]
    ```
    """
    require_same_device(rows=rows, cols=cols, values=values)
    count = rows.size
    if cols.size != count or int(values.shape[0]) != count:
        raise ValueError(
            f"rows, cols and values must have equal length, got {count}, {cols.size} and "
            f"{values.shape[0]}"
        )
    device = rows.device
    if count == 0:
        return bsr_from_csr(
            n_rows,
            n_cols,
            _launch.zeros(n_rows + 1, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=values.dtype, device=device),
        )
    keys, order = csr_key_buffers(count, device)
    if prune_numerical_zeros:
        # Zero-valued triplets are never sorted: they cannot change a sum, so this only saves work.
        _launch.launch(
            kernel_array.COO_KEYS_NONZERO[values.dtype],
            dim=count,
            inputs=[
                rows,
                cols,
                values,
                wp.int32(n_rows),
                wp.int32(n_cols),
                values.dtype(),
                keys,
                order,
            ],
            device=device,
        )
    else:
        _launch.launch(
            kernel_array.coo_keys,
            dim=count,
            inputs=[rows, cols, wp.int32(n_rows), wp.int32(n_cols), keys, order],
            device=device,
        )
    return _csr_from_coo_keys(
        n_rows, n_cols, keys, order, values, prune_numerical_zeros=prune_numerical_zeros
    )

csr_from_coo_keys

csr_from_coo_keys(
    n_rows: int,
    n_cols: int,
    keys: array[uint64],
    order: array[int32],
    values: array[Block, Any],
    *,
    prune_numerical_zeros: bool = False,
) -> odt.BsrMatrix[odt.Block]

Assemble a sparse matrix from written entry keys, summing each key's values.

csr_from_triplets for a producer that writes the keys itself: slot i < n_triplets of csr_key_buffers holds kernels/array.csr_key(row, col, n_rows, n_cols) and an index into values, so no rows / cols buffers are written only to be packed. Duplicates are summed in slot order and an out-of-range entry (the sentinel key) is dropped, exactly as there.

Parameters:

Name Type Description Default
n_rows int

Matrix shape in blocks.

required
n_cols int

Matrix shape in blocks.

required
keys array[uint64]

(2 * n_triplets,) sort buffers holding the keys and the value indices in their first halves. Both are sorted in place, and order's upper half is overwritten.

required
order array[uint64]

(2 * n_triplets,) sort buffers holding the keys and the value indices in their first halves. Both are sorted in place, and order's upper half is overwritten.

required
values array[Block, Any]

(n_triplets,) blocks the payloads index (wp.float32, wp.float64, wp.int32 or wp.mat22d).

required
prune_numerical_zeros bool

Drop every entry whose summed value is exactly zero, as csr_from_triplets does. That build also gives each zero-valued triplet the sentinel key before sorting, which changes no sum; a producer writing its own keys may do the same (kernels/array.csr_key_nonzero).

False

Returns:

Type Description
BsrMatrix

(n_rows, n_cols) assembled matrix. Its nnz is n_triplets as an upper bound until nnz_sync(), as after csr_from_triplets.

Raises:

Type Description
ValueError

If keys or order is not 2 * n_triplets long.

See Also

csr_from_triplets csr_from_keys The pattern alone, for a producer forming its values per entry.

Examples:

The matrix [[2, 0], [0, 3]], its (0, 0) entry written as two keys:

import warp as wp

import ordito as od

keys, order = od.array.csr_key_buffers(3, wp.get_device())
wp.copy(keys, wp.array([0, 3, 0], dtype=wp.uint64))
wp.copy(order, wp.array([0, 1, 2], dtype=wp.int32))
values = wp.array([1.0, 3.0, 1.0], dtype=wp.float32)
matrix = od.array.csr_from_coo_keys(2, 2, keys, order, values)
print(matrix.offsets.numpy().tolist())  # [0, 1, 2]
print(matrix.values.numpy()[:2].tolist())  # [2.0, 3.0]
Source code in ordito/array.py
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
def csr_from_coo_keys(
    n_rows: int,
    n_cols: int,
    keys: wp.array[wp.uint64],
    order: wp.array[wp.int32],
    values: wp.array[odt.Block, Any],
    *,
    prune_numerical_zeros: bool = False,
) -> odt.BsrMatrix[odt.Block]:
    """
    Assemble a sparse matrix from written entry keys, summing each key's ``values``.

    [`csr_from_triplets`][ordito.array.csr_from_triplets] for a producer that writes the keys
    itself: slot ``i < n_triplets`` of [`csr_key_buffers`][ordito.array.csr_key_buffers] holds
    ``kernels/array.csr_key(row, col, n_rows, n_cols)`` and an index into ``values``, so no
    ``rows`` / ``cols`` buffers are written only to be packed. Duplicates are summed in slot order
    and an out-of-range entry (the sentinel key) is dropped, exactly as there.

    Parameters
    ----------
    n_rows, n_cols
        Matrix shape in blocks.
    keys, order
        ``(2 * n_triplets,)`` sort buffers holding the keys and the value indices in their first
        halves. Both are sorted in place, and ``order``'s upper half is overwritten.
    values
        ``(n_triplets,)`` blocks the payloads index (``wp.float32``, ``wp.float64``, ``wp.int32``
        or ``wp.mat22d``).
    prune_numerical_zeros
        Drop every entry whose *summed* value is exactly zero, as
        [`csr_from_triplets`][ordito.array.csr_from_triplets] does. That build also gives each
        zero-valued triplet the sentinel key before sorting, which changes no sum; a producer
        writing its own keys may do the same (``kernels/array.csr_key_nonzero``).

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n_rows, n_cols)`` assembled matrix. Its ``nnz`` is ``n_triplets`` as an upper bound
        until ``nnz_sync()``, as after [`csr_from_triplets`][ordito.array.csr_from_triplets].

    Raises
    ------
    ValueError
        If ``keys`` or ``order`` is not ``2 * n_triplets`` long.

    See Also
    --------
    [`csr_from_triplets`][ordito.array.csr_from_triplets]
    [`csr_from_keys`][ordito.array.csr_from_keys]
        The pattern alone, for a producer forming its values per entry.

    Examples
    --------
    The matrix ``[[2, 0], [0, 3]]``, its ``(0, 0)`` entry written as two keys:

    ```python
    import warp as wp

    import ordito as od

    keys, order = od.array.csr_key_buffers(3, wp.get_device())
    wp.copy(keys, wp.array([0, 3, 0], dtype=wp.uint64))
    wp.copy(order, wp.array([0, 1, 2], dtype=wp.int32))
    values = wp.array([1.0, 3.0, 1.0], dtype=wp.float32)
    matrix = od.array.csr_from_coo_keys(2, 2, keys, order, values)
    print(matrix.offsets.numpy().tolist())  # [0, 1, 2]
    print(matrix.values.numpy()[:2].tolist())  # [2.0, 3.0]
    ```
    """
    count = int(values.shape[0])
    if keys.size != 2 * count or order.size != 2 * count:
        raise ValueError(
            f"keys and order must have length {2 * count}, got {keys.size} and {order.size}"
        )
    if count == 0:
        device = keys.device
        return bsr_from_csr(
            n_rows,
            n_cols,
            _launch.zeros(n_rows + 1, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=values.dtype, device=device),
        )
    return _csr_from_coo_keys(
        n_rows, n_cols, keys, order, values, prune_numerical_zeros=prune_numerical_zeros
    )

csr_transpose

csr_transpose(
    matrix: BsrMatrix[Block],
) -> odt.BsrMatrix[odt.Block]

Transpose a sparse matrix of scalar blocks, with no host readback.

The entries keep their values bit for bit and every row of the result is sorted by column, as warp.sparse.bsr_transposed returns them; this sorts one key per entry over only the bits the shape needs instead.

Parameters:

Name Type Description Default
matrix BsrMatrix[Block]

(n_rows, n_cols) compact matrix of wp.float32, wp.float64 or wp.int32 entries. Its nnz may be a capacity (the stored entries are offsets[-1]).

required

Returns:

Type Description
BsrMatrix

(n_cols, n_rows) transpose, its nnz the same count matrix.nnz records.

Raises:

Type Description
ValueError

If matrix has blocks larger than 1x1.

See Also

csr_from_triplets

Examples:

The transpose of [[1, 0], [2, 3]] is [[1, 2], [0, 3]]:

import warp as wp

import ordito as od

rows = wp.array([0, 1, 1], dtype=wp.int32)
cols = wp.array([0, 0, 1], dtype=wp.int32)
values = wp.array([1.0, 2.0, 3.0], dtype=wp.float32)
transpose = od.array.csr_transpose(od.array.csr_from_triplets(2, 2, rows, cols, values))
print(transpose.offsets.numpy().tolist())  # [0, 2, 3]
print(transpose.columns.numpy()[:3].tolist())  # [0, 1, 1]
print(transpose.values.numpy()[:3].tolist())  # [1.0, 2.0, 3.0]
Source code in ordito/array.py
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
def csr_transpose(matrix: odt.BsrMatrix[odt.Block]) -> odt.BsrMatrix[odt.Block]:
    """
    Transpose a sparse matrix of scalar blocks, with no host readback.

    The entries keep their values bit for bit and every row of the result is sorted by column, as
    ``warp.sparse.bsr_transposed`` returns them; this sorts one key per entry over only the bits
    the shape needs instead.

    Parameters
    ----------
    matrix
        ``(n_rows, n_cols)`` compact matrix of ``wp.float32``, ``wp.float64`` or ``wp.int32``
        entries. Its ``nnz`` may be a capacity (the stored entries are ``offsets[-1]``).

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n_cols, n_rows)`` transpose, its ``nnz`` the same count ``matrix.nnz`` records.

    Raises
    ------
    ValueError
        If ``matrix`` has blocks larger than 1x1.

    See Also
    --------
    [`csr_from_triplets`][ordito.array.csr_from_triplets]

    Examples
    --------
    The transpose of ``[[1, 0], [2, 3]]`` is ``[[1, 2], [0, 3]]``:

    ```python
    import warp as wp

    import ordito as od

    rows = wp.array([0, 1, 1], dtype=wp.int32)
    cols = wp.array([0, 0, 1], dtype=wp.int32)
    values = wp.array([1.0, 2.0, 3.0], dtype=wp.float32)
    transpose = od.array.csr_transpose(od.array.csr_from_triplets(2, 2, rows, cols, values))
    print(transpose.offsets.numpy().tolist())  # [0, 2, 3]
    print(transpose.columns.numpy()[:3].tolist())  # [0, 1, 1]
    print(transpose.values.numpy()[:3].tolist())  # [1.0, 2.0, 3.0]
    ```
    """
    if matrix.block_shape != (1, 1):
        raise ValueError(f"csr_transpose takes 1x1 blocks, got {matrix.block_shape}")
    n_rows = int(matrix.nrow)
    n_cols = int(matrix.ncol)
    count = int(matrix.nnz)
    device = matrix.values.device
    if count == 0:
        return bsr_from_csr(
            n_cols,
            n_rows,
            _launch.zeros(n_cols + 1, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=matrix.values.dtype, device=device),
            nnz=0,
        )
    # The entries run row-major, so the transpose's columns (the rows) are in slot order: the
    # keys' column field is padded and the sort orders the row bits alone.
    key_cols = _column_ordered_key_cols(n_rows)
    keys, order = csr_key_buffers(count, device)
    _launch.launch(
        kernel_array.csr_transposed_keys,
        dim=n_rows + 1,
        inputs=[
            matrix.offsets,
            matrix.columns,
            wp.int32(n_rows),
            wp.int32(n_cols),
            wp.int32(n_rows if key_cols is None else key_cols),
            keys,
            order,
        ],
        device=device,
    )
    # Every key is distinct, so each run is one entry and its "sum" is its own value.
    return _csr_from_coo_keys(
        n_cols, n_rows, keys, order, odt.as_dense(matrix.values[:count]), key_cols=key_cols
    )

index_sparse

index_sparse(
    n_rows: int,
    indices: Array2dInt32,
    data: array[Scalar] | None = None,
    dtype: type[Scalar] | None = None,
    *,
    prune_numerical_zeros: bool = True,
) -> odt.BsrMatrix[wp.Scalar]

Build a sparse row/column incidence matrix from flat index columns.

This mirrors trimesh.geometry.index_sparse, but returns a warp.sparse.BsrMatrix in 1x1 BSR (CSR) form instead of scipy.sparse.coo_matrix.

Parameters:

Name Type Description Default
n_rows int

Number of matrix rows (e.g. vertex count). Matrix shape is (n_rows, len(indices)).

required
indices Array2dInt32

(m, d) index rows — typically mesh.faces with three vertex indices per face.

required
data array[Scalar] | None

(m * d,) optional values. If omitted, wp.ones is used; see dtype.

None
dtype type[Scalar] | None

Scalar type for wp.ones when data is None (defaults to wp.float32 if dtype is None). When data and dtype are provided, the values of the matrix are cast to dtype.

None
prune_numerical_zeros bool

Forwarded to csr_from_triplets.

True

Returns:

Type Description
BsrMatrix

(n_rows, len(indices)) sparse matrix with 1x1 blocks.

Raises:

Type Description
ValueError

If data is given and its size differs from indices.size.

RuntimeError

If indices and data are not all on one device.

Examples:

The vertex-face incidence of two triangles; multiplying by ones counts each vertex's faces:

import warp as wp
import warp.sparse as wps

import ordito as od

faces = wp.array([[0, 1, 2], [2, 1, 3]], dtype=wp.int32)
incidence = od.array.index_sparse(4, faces)
print(incidence.shape)  # (4, 2)
ones = wp.ones(2, dtype=wp.float32)
print(wps.bsr_mv(incidence, ones).numpy().tolist())  # [1.0, 2.0, 2.0, 1.0]
Source code in ordito/array.py
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
def index_sparse(
    n_rows: int,
    indices: odt.Array2dInt32,
    data: wp.array[wp.Scalar] | None = None,
    dtype: type[wp.Scalar] | None = None,
    *,
    prune_numerical_zeros: bool = True,
) -> odt.BsrMatrix[wp.Scalar]:
    """
    Build a sparse row/column incidence matrix from flat index columns.

    This mirrors ``trimesh.geometry.index_sparse``, but returns a ``warp.sparse.BsrMatrix``
    in 1x1 BSR (CSR) form instead of ``scipy.sparse.coo_matrix``.

    Parameters
    ----------
    n_rows
        Number of matrix rows (e.g. vertex count). Matrix shape is ``(n_rows, len(indices))``.
    indices
        ``(m, d)`` index rows — typically ``mesh.faces`` with three vertex indices per face.
    data
        ``(m * d,)`` optional values. If omitted, ``wp.ones`` is used; see ``dtype``.
    dtype
        Scalar type for ``wp.ones`` when ``data`` is ``None`` (defaults to ``wp.float32`` if
        ``dtype`` is ``None``). When ``data`` and ``dtype`` are provided, the values of the
        matrix are cast to ``dtype``.
    prune_numerical_zeros
        Forwarded to [`csr_from_triplets`][ordito.array.csr_from_triplets].

    Returns
    -------
    warp.sparse.BsrMatrix
        ``(n_rows, len(indices))`` sparse matrix with 1x1 blocks.

    Raises
    ------
    ValueError
        If ``data`` is given and its size differs from ``indices.size``.
    RuntimeError
        If ``indices`` and ``data`` are not all on one device.

    Examples
    --------
    The vertex-face incidence of two triangles; multiplying by ones counts each vertex's faces:

    ```python
    import warp as wp
    import warp.sparse as wps

    import ordito as od

    faces = wp.array([[0, 1, 2], [2, 1, 3]], dtype=wp.int32)
    incidence = od.array.index_sparse(4, faces)
    print(incidence.shape)  # (4, 2)
    ones = wp.ones(2, dtype=wp.float32)
    print(wps.bsr_mv(incidence, ones).numpy().tolist())  # [1.0, 2.0, 2.0, 1.0]
    ```
    """
    require_same_device(indices=indices, data=data)
    prune_numerical_zeros = prune_numerical_zeros and data is not None
    if data is None:
        data = cast(
            "wp.array[wp.Scalar]",
            _launch.ones(
                indices.size,
                dtype=dtype if dtype is not None else wp.float32,
                device=indices.device,
            ),
        )
    else:
        if data.size != indices.size:
            raise ValueError(
                f"data must have the same size as indices, got {data.size} and {indices.size}"
            )
        if dtype is not None and data.dtype != dtype:
            data = astype(data, dtype)

    n_cols, n_repeats = indices.shape
    count = indices.size
    device = indices.device
    if count == 0:
        return bsr_from_csr(
            n_rows,
            n_cols,
            _launch.zeros(n_rows + 1, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=data.dtype, device=device),
        )
    # The triplets' keys straight from the index rows: a zero-valued triplet adds nothing to its
    # entry's sum, so pruning on the sums needs no keys of its own.
    # The index rows run in column order, so the keys' column field is padded and the sort
    # orders the row bits alone.
    key_cols = _column_ordered_key_cols(n_cols)
    keys, order = csr_key_buffers(count, device)
    _launch.launch(
        kernel_array.index_sparse_keys,
        dim=count,
        inputs=[
            indices.flatten(),
            wp.int32(n_repeats),
            wp.int32(n_rows),
            wp.int32(n_cols if key_cols is None else key_cols),
        ],
        outputs=[keys, order],
        device=device,
    )
    return _csr_from_coo_keys(
        n_rows,
        n_cols,
        keys,
        order,
        data,
        prune_numerical_zeros=prune_numerical_zeros,
        key_cols=key_cols,
    )

isin

isin(
    elements: ArrayNd,
    test_elements: array[Int],
    *,
    max_index: int | None = None,
) -> wp.array[wp.bool]

Test whether each element appears in test_elements (numpy.isin for integers).

Works for every Warp integer dtype -- int8 through int64, uint8 through uint64 -- and for negative values. Both arrays must share one dtype.

Two strategies, chosen by the value span max - min + 1 taken over both inputs together. When the span is modest relative to len(test_elements), membership is a boolean lookup table indexed by value - min (fast for dense mesh indices). Otherwise test_elements is sorted and each query is a binary search, which keeps memory bounded when the values are sparse in their dtype.

Parameters:

Name Type Description Default
elements ArrayNd

Integer array of any rank on the target device. Membership is a per-element predicate, so the array is flattened, tested, and the result reshaped back; nothing in the two strategies looks at the shape.

required
test_elements array[Int]

(n_test,) values to test membership against, of the same dtype as elements.

required
max_index int | None

Optional exclusive upper bound on the values of both arrays, which must then be non-negative -- the same escape hatch, and the same shape of it, as hash_indices_rows' max_index. Supplying it pins the strategy to the direct-index table and skips the two ordito.reduce.minmax reductions that would otherwise infer the span, and with them two host readbacks that serialise the device pipeline. Must be positive. Pass it wherever the bound is structural, as it is for any buffer of mesh vertex indices.

None

Returns:

Type Description
array[bool]

elements.shape membership mask. All False when either input is empty.

Raises:

Type Description
TypeError

If either array is not an integer dtype, or the two dtypes differ.

ValueError

If max_index is not positive.

Warnings

A max_index smaller than the true maximum is a wrong answer, not a raise: a value at or above it reads as absent, however far above it lies and on either side of the comparison. Unlike hash_indices_rows' bound it is at least memory-safe, because the table lookup range-guards each slot.

See Also

indices_to_mask sortable_dtype numpy.isin

Notes

Dtypes narrower than four bytes are widened to int32 / uint32 (the sortable_dtype rule) before either strategy runs: Warp's radix sort does not accept them, and neither does the tiled min/max reduction the span needs.

There is no assume_unique, and its absence is deliberate rather than an omission: numpy.isin gains from one because the sort path behind it calls numpy.unique on both arrays first, and neither strategy here dedups anything -- the table is an idempotent scatter and the binary search is over the sorted keys as given, so duplicates on either side are already free. What the two strategies do pay for is inferring the value span, which is why the guarantee this takes is a bound rather than a uniqueness claim.

Without max_index: two host readbacks, one min/max reduction per input, which is what selects the strategy and anchors the table.

Examples:

Mirrors numpy.isin, negative values included:

import warp as wp

import ordito as od

elements = wp.array([0, 3, 5, 7, -2], dtype=wp.int32)
test_elements = wp.array([7, 0, -2], dtype=wp.int32)
mask = od.array.isin(elements, test_elements)
print(mask.numpy().tolist())  # [True, False, False, True, True]
Source code in ordito/array.py
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
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
def isin(
    elements: odt.ArrayNd, test_elements: wp.array[wp.Int], *, max_index: int | None = None
) -> wp.array[wp.bool]:
    """
    Test whether each element appears in ``test_elements`` (``numpy.isin`` for integers).

    Works for every Warp integer dtype -- ``int8`` through ``int64``, ``uint8`` through ``uint64``
    -- and for negative values. Both arrays must share one dtype.

    Two strategies, chosen by the value **span** ``max - min + 1`` taken over both inputs together.
    When the span is modest relative to ``len(test_elements)``, membership is a boolean lookup table
    indexed by ``value - min`` (fast for dense mesh indices). Otherwise ``test_elements`` is sorted
    and each query is a binary search, which keeps memory bounded when the values are sparse in
    their dtype.

    Parameters
    ----------
    elements
        Integer array of **any rank** on the target device. Membership is a per-element predicate,
        so the array is flattened, tested, and the result reshaped back; nothing in the two
        strategies looks at the shape.
    test_elements
        ``(n_test,)`` values to test membership against, of the same dtype as ``elements``.
    max_index
        Optional exclusive upper bound on the values of **both** arrays, which must then be
        non-negative -- the same escape hatch, and the same shape of it, as
        [`hash_indices_rows`][ordito.grouping.hash_indices_rows]' ``max_index``. Supplying it
        pins the strategy to the direct-index table and skips the two ``ordito.reduce.minmax``
        reductions that would otherwise infer the span, and with them two host readbacks that
        serialise the device pipeline. Must be positive. Pass it wherever the bound is structural,
        as it is for any buffer of mesh vertex indices.

    Returns
    -------
    wp.array[wp.bool]
        ``elements.shape`` membership mask. All ``False`` when either input is empty.

    Raises
    ------
    TypeError
        If either array is not an integer dtype, or the two dtypes differ.
    ValueError
        If ``max_index`` is not positive.

    Warnings
    --------
    A ``max_index`` smaller than the true maximum is a wrong answer, not a raise: a value at or
    above it reads as absent, however far above it lies and on either side of the comparison.
    Unlike [`hash_indices_rows`][ordito.grouping.hash_indices_rows]' bound it is at least
    memory-safe, because the table lookup range-guards each slot.

    See Also
    --------
    [`indices_to_mask`][ordito.array.indices_to_mask]
    [`sortable_dtype`][ordito.typing.sortable_dtype]
    [`numpy.isin`][]

    Notes
    -----
    Dtypes narrower than four bytes are widened to ``int32`` / ``uint32`` (the
    [`sortable_dtype`][ordito.typing.sortable_dtype] rule) before either strategy runs: Warp's
    radix sort does not accept them, and neither does the tiled min/max reduction the span needs.

    There is no ``assume_unique``, and its absence is deliberate rather than an omission:
    [`numpy.isin`][] gains from one because the sort path behind it calls [`numpy.unique`][] on both
    arrays first, and neither strategy here dedups anything -- the table is an idempotent scatter
    and the binary search is over the sorted keys as given, so duplicates on either side are already
    free. What the two strategies *do* pay for is inferring the value span, which is why the
    guarantee this takes is a bound rather than a uniqueness claim.

    Without ``max_index``: two host readbacks, one min/max reduction per input, which is what
    selects the strategy and anchors the table.

    Examples
    --------
    Mirrors [`numpy.isin`][], negative values included:

    ```python
    import warp as wp

    import ordito as od

    elements = wp.array([0, 3, 5, 7, -2], dtype=wp.int32)
    test_elements = wp.array([7, 0, -2], dtype=wp.int32)
    mask = od.array.isin(elements, test_elements)
    print(mask.numpy().tolist())  # [True, False, False, True, True]
    ```
    """
    device = elements.device
    dtype = elements.dtype
    if dtype != test_elements.dtype:
        raise TypeError(
            f"isin requires one dtype for both arrays, got {dtype} and {test_elements.dtype}"
        )
    if not wp.types.type_is_int(dtype) or dtype == wp.bool:
        raise TypeError(f"isin requires an integer dtype, got {dtype}")

    if max_index is not None and max_index <= 0:
        raise ValueError(f"max_index must be positive, got {max_index}")

    k = test_elements.size
    if k == 0 or int(elements.size) == 0:
        return _launch.zeros(elements.shape, dtype=wp.bool, device=device)

    is_flat = int(elements.ndim) == 1
    # Either input may be widened below, to a dtype chosen at runtime.
    elements_flat: odt.ArrayNd = elements if is_flat else elements.flatten()
    tests: odt.ArrayNd = test_elements
    # Widen sub-32-bit dtypes once, up front: neither ``reduce.minmax`` nor the radix sort accepts
    # them, and a widened span cannot overflow the type it is measured in (int8's span reaches 256).
    if wp.types.type_size_in_bytes(dtype) < 4:
        wide = odt.sortable_dtype(dtype)
        elements_flat = astype(elements_flat, wide)
        tests = astype(tests, wide)

    if max_index is not None:
        # A supplied bound is the whole point of the keyword: it is what the two reductions below
        # would have inferred, so it also settles the strategy -- a caller who knows the values are
        # dense mesh indices is describing exactly the table's best case, and honouring a
        # ``_ISIN_MASK_SIZE_FACTOR`` test here would spend the readback to reach the same branch.
        return _reshaped(_isin_lookup_mask(elements_flat, tests, max_index, 0), elements)

    # One ``(min, max)`` accumulator over both inputs, for a single readback: on CUDA one launch
    # over their concatenation; on the CPU the tiled kernel once per input, folding into what the
    # buffer holds, since its ``tile_load`` vectorizes where a lane-strided loop does not.
    reduce_dtype = elements_flat.dtype
    bounds = _launch.pattern(
        [odt.dtype_max(reduce_dtype), odt.dtype_min(reduce_dtype)],
        dtype=reduce_dtype,
        device=device,
    )
    if wp.get_device(device).is_cuda:
        _launch.launch_tiled(
            kernel_reduce.MINMAX_PAIR_1D[reduce_dtype],
            dim=[kernel_reduce.blocks_1d(elements_flat.size + tests.size)],
            inputs=[elements_flat, tests],
            outputs=[bounds],
            block_dim=TILE_1D,
            device=device,
        )
    else:
        for values in (elements_flat, tests):
            _launch.launch_tiled(
                kernel_reduce.MINMAX1D_TILED[reduce_dtype],
                dim=[kernel_reduce.blocks_1d(values.size)],
                inputs=[values, bounds],
                block_dim=TILE_1D,
                device=device,
            )
    offset, high = (int(bound) for bound in read_values(bounds, 0, 2))
    span = high - offset + 1
    if span <= _ISIN_MASK_SIZE_FACTOR * k:
        out_flat = _isin_lookup_mask(elements_flat, tests, span, offset)
    else:
        out_flat = _isin_lookup_sorted(elements_flat, tests)

    return _reshaped(out_flat, elements)

flatnonzero

flatnonzero(
    values: array[bool] | array[Scalar],
) -> wp.array[wp.int32]

Return the indices of the non-zero entries of a 1D array (numpy.flatnonzero).

Takes a boolean mask, which is the common case, or any scalar array — every non-zero value selects its index, exactly as numpy.flatnonzero does, so -2 and 3 both count and only 0 does not.

Parameters:

Name Type Description Default
values array[bool] | array[Scalar]

(n,) wp.bool mask, or a wp.int32 / float / other scalar array, on the target device.

required

Returns:

Type Description
array[int32]

(n_nonzero,) selected indices on values.device, ascending, n_nonzero the number of non-zero entries. Empty when nothing is non-zero.

Raises:

Type Description
ValueError

If values is not rank-1.

See Also

indices_to_mask mask_to_compact_ranks numpy.flatnonzero

Examples:

Mirrors numpy.flatnonzero, for a mask or any scalar array:

import warp as wp

import ordito as od

mask = wp.array([False, True, True, False], dtype=wp.bool)
print(od.array.flatnonzero(mask).numpy().tolist())  # [1, 2]
values = wp.array([0, 2, 0, -1, 5], dtype=wp.int32)
print(od.array.flatnonzero(values).numpy().tolist())  # [1, 3, 4]
Source code in ordito/array.py
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
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
def flatnonzero(values: wp.array[wp.bool] | wp.array[wp.Scalar]) -> wp.array[wp.int32]:
    """
    Return the indices of the non-zero entries of a 1D array (``numpy.flatnonzero``).

    Takes a boolean mask, which is the common case, or any scalar array — every non-zero value
    selects its index, exactly as ``numpy.flatnonzero`` does, so ``-2`` and ``3`` both count and
    only ``0`` does not.

    Parameters
    ----------
    values
        ``(n,)`` ``wp.bool`` mask, or a ``wp.int32`` / float / other scalar array, on the target
        device.

    Returns
    -------
    wp.array[wp.int32]
        ``(n_nonzero,)`` selected indices on ``values.device``, ascending, ``n_nonzero`` the
        number of non-zero entries. Empty when nothing is non-zero.

    Raises
    ------
    ValueError
        If ``values`` is not rank-1.

    See Also
    --------
    [`indices_to_mask`][ordito.array.indices_to_mask]
    [`mask_to_compact_ranks`][ordito.array.mask_to_compact_ranks]
    [`numpy.flatnonzero`][]

    Examples
    --------
    Mirrors [`numpy.flatnonzero`][], for a mask or any scalar array:

    ```python
    import warp as wp

    import ordito as od

    mask = wp.array([False, True, True, False], dtype=wp.bool)
    print(od.array.flatnonzero(mask).numpy().tolist())  # [1, 2]
    values = wp.array([0, 2, 0, -1, 5], dtype=wp.int32)
    print(od.array.flatnonzero(values).numpy().tolist())  # [1, 3, 4]
    ```
    """
    if int(values.ndim) != 1:
        raise ValueError(f"flatnonzero requires a 1D array, got ndim={values.ndim}")

    device = values.device
    n = values.size
    if n == 0:
        return _launch.empty(0, dtype=wp.int32, device=device)

    if values.dtype == wp.bool and wp.get_device(device).is_cuda and n >= _FLATNONZERO_BITS_FROM:
        return _flatnonzero_bits(cast("wp.array[wp.bool]", values))
    # One buffer for the flags and their scan: the flags are written into it and scanned in place.
    inclusive = _launch.empty(n, dtype=wp.int32, device=device)
    if values.dtype == wp.bool:
        # A mask needs its own kernel: ``wp.Scalar`` does not instantiate for ``wp.bool``, so
        # ``nonzero_flag`` cannot serve one. For every other dtype the plain cast that kernel
        # replaces would copy the *values*, and the scan below would then sum them instead of
        # counting them.
        _launch.launch(kernel_array.bool_flags, dim=n, inputs=[values, inclusive], device=device)
    else:
        _launch.map(kernel_array.nonzero_flag, values, out=inclusive)

    return flatnonzero_in_place(inclusive)

flatnonzero_in_place

flatnonzero_in_place(
    flags: array[int32],
) -> wp.array[wp.int32]

Return the indices of the ones in a 0 / 1 flag buffer, scanning it in place.

flatnonzero for a caller whose own kernel writes the flags: the flags go straight into the buffer the scan runs in, so no mask sits between the kernel and the scan. The buffer is consumed -- it holds the flags' inclusive scan on return.

Parameters:

Name Type Description Default
flags array[int32]

(n,) int32 buffer of 0 / 1 flags. Overwritten with its inclusive scan.

required

Returns:

Type Description
array[int32]

(n_selected,) ascending indices of the 1 entries on flags.device, n_selected their count. Empty when none is set.

See Also

flatnonzero The same indices of an existing mask or scalar array.

Examples:

import warp as wp

import ordito as od

flags = wp.array([0, 1, 1, 0, 1], dtype=wp.int32)
print(od.array.flatnonzero_in_place(flags).numpy().tolist())  # [1, 2, 4]
print(flags.numpy().tolist())  # [0, 1, 2, 2, 3]
Source code in ordito/array.py
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
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
def flatnonzero_in_place(flags: wp.array[wp.int32]) -> wp.array[wp.int32]:
    """
    Return the indices of the ones in a ``0`` / ``1`` flag buffer, scanning it in place.

    [`flatnonzero`][ordito.array.flatnonzero] for a caller whose own kernel writes the flags: the
    flags go straight into the buffer the scan runs in, so no mask sits between the kernel and the
    scan. The buffer is consumed -- it holds the flags' inclusive scan on return.

    Parameters
    ----------
    flags
        ``(n,)`` ``int32`` buffer of ``0`` / ``1`` flags. Overwritten with its inclusive scan.

    Returns
    -------
    wp.array[wp.int32]
        ``(n_selected,)`` ascending indices of the ``1`` entries on ``flags.device``,
        ``n_selected`` their count. Empty when none is set.

    See Also
    --------
    [`flatnonzero`][ordito.array.flatnonzero]
        The same indices of an existing mask or scalar array.

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

    import ordito as od

    flags = wp.array([0, 1, 1, 0, 1], dtype=wp.int32)
    print(od.array.flatnonzero_in_place(flags).numpy().tolist())  # [1, 2, 4]
    print(flags.numpy().tolist())  # [0, 1, 2, 2, 3]
    ```
    """
    device = flags.device
    n_out = _scan_selection(flags)
    out_indices = _launch.empty(n_out, dtype=wp.int32, device=device)
    if n_out > 0:
        _launch.launch(
            kernel_scatter.scatter_index_where_scanned,
            dim=flags.size,
            inputs=[flags, out_indices],
            device=device,
        )
    return out_indices

compress_in_place

compress_in_place(
    flags: array[int32], values: array[vec3]
) -> wp.array[wp.vec3]

Return the values at the ones of a 0 / 1 flag buffer, scanning it in place.

numpy.compress(flags, values) for a caller whose own kernel writes the flags: the flatnonzero_in_place counterpart that writes each selected value to its compact slot, so no index buffer is built and gathered back. The buffer is consumed -- it holds the flags' inclusive scan on return.

Parameters:

Name Type Description Default
flags array[int32]

(n,) int32 buffer of 0 / 1 flags. Overwritten with its inclusive scan.

required
values array[vec3]

(n,) values on flags.device.

required

Returns:

Type Description
array[vec3]

(n_selected,) the selected values, in ascending index order.

See Also

flatnonzero_in_place The indices of the ones instead of the values there.

Examples:

import warp as wp

import ordito as od

flags = wp.array([0, 1, 0, 1], dtype=wp.int32)
values = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]],
                  dtype=wp.vec3)
print(od.array.compress_in_place(flags, values).numpy()[:, 0].tolist())  # [1.0, 3.0]
Source code in ordito/array.py
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
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
def compress_in_place(flags: wp.array[wp.int32], values: wp.array[wp.vec3]) -> wp.array[wp.vec3]:
    """
    Return the values at the ones of a ``0`` / ``1`` flag buffer, scanning it in place.

    ``numpy.compress(flags, values)`` for a caller whose own kernel writes the flags: the
    [`flatnonzero_in_place`][ordito.array.flatnonzero_in_place] counterpart that writes each
    selected value to its compact slot, so no index buffer is built and gathered back. The buffer
    is consumed -- it holds the flags' inclusive scan on return.

    Parameters
    ----------
    flags
        ``(n,)`` ``int32`` buffer of ``0`` / ``1`` flags. Overwritten with its inclusive scan.
    values
        ``(n,)`` values on ``flags.device``.

    Returns
    -------
    wp.array[wp.vec3]
        ``(n_selected,)`` the selected values, in ascending index order.

    See Also
    --------
    [`flatnonzero_in_place`][ordito.array.flatnonzero_in_place]
        The indices of the ones instead of the values there.

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

    import ordito as od

    flags = wp.array([0, 1, 0, 1], dtype=wp.int32)
    values = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]],
                      dtype=wp.vec3)
    print(od.array.compress_in_place(flags, values).numpy()[:, 0].tolist())  # [1.0, 3.0]
    ```
    """
    device = flags.device
    n_out = _scan_selection(flags)
    out_values = _launch.empty(n_out, dtype=wp.vec3, device=device)
    if n_out > 0:
        _launch.launch(
            kernel_scatter.scatter_value_where_scanned,
            dim=flags.size,
            inputs=[flags, values, out_values],
            device=device,
        )
    return out_values

gather

gather(
    src: array[DType] | ArrayNd,
    indices: array[int32],
    *,
    out: array[DType] | ArrayNd | None = None,
) -> wp.array[DType] | odt.ArrayNd

Dense copy of src gathered along its first axis by indices (numpy.take).

Warp's src[indices] fancy indexing yields a warp.indexedarray view; this materializes a contiguous warp.array (performing the copy) so callers get a real array supporting .reshape and a stable return type. Works for rank-1 sources (src[indices]) and rank-2 row gather (src[indices, :]), with any scalar or vector dtype.

Only the first axis is indexable, which is what every caller in this package needs. To take a column, materialize it with wp.clone(src[:, k]) — a column view is strided, and Warp's fancy indexing silently ignores the stride of an index array.

Parameters:

Name Type Description Default
src array[DType] | ArrayNd

(n,) or (n, m) wp.array on the target device.

required
indices array[int32]

(k,) indices into the first axis of src. Must be contiguous; see the warning above.

required
out array[DType] | ArrayNd | None

(k, *src.shape[1:]) contiguous buffer of src's dtype on src.device to write the gathered copy into, or None to allocate one.

None

Returns:

Type Description
array

(len(indices), *src.shape[1:]) contiguous gathered copy on src.device, with the same dtype as src: out when given. Empty along the first axis when indices is empty.

Raises:

Type Description
RuntimeError

If src, indices and out are not all on one device.

ValueError

If out does not have the gathered copy's shape and dtype.

See Also

index_sparse remap_indices The sentinel-preserving variant for index buffers that may carry -1 entries.

Examples:

numpy.take(src, indices, axis=0), for values and for rows:

import warp as wp

import ordito as od

indices = wp.array([3, 0, 3], dtype=wp.int32)
values = wp.array([10, 20, 30, 40], dtype=wp.int32)
print(od.array.gather(values, indices).numpy().tolist())  # [40, 10, 40]
rows = wp.array([[0, 1], [2, 3], [4, 5], [6, 7]], dtype=wp.int32)
print(od.array.gather(rows, indices).numpy().tolist())  # [[6, 7], [0, 1], [6, 7]]
Source code in ordito/array.py
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
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
def gather(
    src: wp.array[DType] | odt.ArrayNd,
    indices: wp.array[wp.int32],
    *,
    out: wp.array[DType] | odt.ArrayNd | None = None,
) -> wp.array[DType] | odt.ArrayNd:
    """
    Dense copy of ``src`` gathered along its first axis by ``indices`` (``numpy.take``).

    Warp's ``src[indices]`` fancy indexing yields a ``warp.indexedarray`` view; this
    materializes a contiguous ``warp.array`` (performing the copy) so callers get a real
    array supporting ``.reshape`` and a stable return type. Works for rank-1 sources
    (``src[indices]``) and rank-2 row gather (``src[indices, :]``), with any scalar or vector
    ``dtype``.

    Only the first axis is indexable, which is what every caller in this package needs. To take a
    *column*, materialize it with ``wp.clone(src[:, k])`` — a column view is strided, and Warp's
    fancy indexing silently ignores the stride of an index array.

    Parameters
    ----------
    src
        ``(n,)`` or ``(n, m)`` ``wp.array`` on the target device.
    indices
        ``(k,)`` indices into the first axis of ``src``. **Must be contiguous**;
        see the warning above.
    out
        ``(k, *src.shape[1:])`` contiguous buffer of ``src``'s dtype on ``src.device`` to write the
        gathered copy into, or ``None`` to allocate one.

    Returns
    -------
    wp.array
        ``(len(indices), *src.shape[1:])`` contiguous gathered copy on ``src.device``, with the
        same ``dtype`` as ``src``: ``out`` when given. Empty along the first axis when
        ``indices`` is empty.

    Raises
    ------
    RuntimeError
        If ``src``, ``indices`` and ``out`` are not all on one device.
    ValueError
        If ``out`` does not have the gathered copy's shape and dtype.

    See Also
    --------
    [`index_sparse`][ordito.array.index_sparse]
    [`remap_indices`][ordito.array.remap_indices]
        The sentinel-preserving variant for index buffers that may carry ``-1`` entries.

    Examples
    --------
    ``numpy.take(src, indices, axis=0)``, for values and for rows:

    ```python
    import warp as wp

    import ordito as od

    indices = wp.array([3, 0, 3], dtype=wp.int32)
    values = wp.array([10, 20, 30, 40], dtype=wp.int32)
    print(od.array.gather(values, indices).numpy().tolist())  # [40, 10, 40]
    rows = wp.array([[0, 1], [2, 3], [4, 5], [6, 7]], dtype=wp.int32)
    print(od.array.gather(rows, indices).numpy().tolist())  # [[6, 7], [0, 1], [6, 7]]
    ```
    """
    require_same_device(src=src, indices=indices, out=out)
    k = indices.size
    out_shape = (k, *(int(dim) for dim in src.shape[1:]))
    if out is None:
        out = _launch.empty(out_shape, dtype=src.dtype, device=src.device)
    elif tuple(int(dim) for dim in out.shape) != out_shape or out.dtype != src.dtype:
        raise ValueError(
            f"out must be a {out_shape} array of {src.dtype}, got {tuple(out.shape)} of {out.dtype}"
        )
    if k == 0:
        return out
    element_words = _words_per_element(src.dtype)
    row_words = element_words * math.prod(out_shape[1:])
    if (
        row_words
        and wp.get_device(src.device).is_cuda
        and src.is_contiguous
        and indices.is_contiguous
        and max(int(src.shape[0]), k) * row_words < 1 << 31
    ):
        # One word kernel for every dtype and rank on CUDA (``kernels/array.gather_words``).
        _launch.launch(
            kernel_array.gather_words,
            dim=k * row_words,
            inputs=[_as_words(src, element_words), indices, row_words],
            outputs=[_as_words(out, element_words)],
            device=src.device,
        )
    else:
        _launch.copy(out, src[indices])
    return out

astype

astype(
    values: ArrayNd, dtype: type[DType]
) -> wp.array[DType, Any]

Element-wise dtype conversion, shape and rank preserved (numpy.ndarray.astype).

The Python-scope counterpart of wp.cast, which exists only inside a kernel. Allocates a buffer of values' shape on values' device and fills it with copyto.

Parameters:

Name Type Description Default
values ArrayNd

(n,) or (n, m) Warp array of any scalar or vector dtype.

required
dtype type[DType]

Target dtype, of the same element shape as values.dtype.

required

Returns:

Type Description
array

values.shape new array on values' device, with element type dtype.

Raises:

Type Description
ValueError

If values is rank-2 and not contiguous, since the rank-2 path flattens.

Notes

The output keeps values' shape, so this is not a reinterpretation that changes rank: an (n, 3) float32 read as (n,) wp.vec3 is a different operation, a view of a contiguous table, as hash_rows and mean_vertex_normals do.

See Also

copyto The same conversion into a buffer the caller already holds. bitcast_to_int Reinterpret the bits rather than convert the value.

Examples:

Mirrors numpy.ndarray.astype; a float converts to an integer by truncation toward zero:

import warp as wp

import ordito as od

values = wp.array([1.5, -2.5, 3.0], dtype=wp.float32)
print(od.array.astype(values, wp.int32).numpy().tolist())  # [1, -2, 3]
Source code in ordito/array.py
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
def astype(values: odt.ArrayNd, dtype: type[DType]) -> wp.array[DType, Any]:
    """
    Element-wise dtype conversion, shape and rank preserved (``numpy.ndarray.astype``).

    The Python-scope counterpart of ``wp.cast``, which exists only inside a kernel. Allocates a
    buffer of ``values``' shape on ``values``' device and fills it with
    [`copyto`][ordito.array.copyto].

    Parameters
    ----------
    values
        ``(n,)`` or ``(n, m)`` Warp array of any scalar or vector dtype.
    dtype
        Target dtype, of the same element shape as ``values.dtype``.

    Returns
    -------
    wp.array
        ``values.shape`` new array on ``values``' device, with element type ``dtype``.

    Raises
    ------
    ValueError
        If ``values`` is rank-2 and not contiguous, since the rank-2 path flattens.

    Notes
    -----
    The output keeps ``values``' shape, so this is not a reinterpretation that changes rank: an
    ``(n, 3)`` ``float32`` read as ``(n,)`` ``wp.vec3`` is a different operation, a ``view`` of a
    contiguous table, as [`hash_rows`][ordito.grouping.hash_rows] and
    [`mean_vertex_normals`][ordito.normals.mean_vertex_normals] do.

    See Also
    --------
    [`copyto`][ordito.array.copyto]
        The same conversion into a buffer the caller already holds.
    [`bitcast_to_int`][ordito.array.bitcast_to_int]
        Reinterpret the *bits* rather than convert the value.

    Examples
    --------
    Mirrors ``numpy.ndarray.astype``; a float converts to an integer by truncation toward zero:

    ```python
    import warp as wp

    import ordito as od

    values = wp.array([1.5, -2.5, 3.0], dtype=wp.float32)
    print(od.array.astype(values, wp.int32).numpy().tolist())  # [1, -2, 3]
    ```
    """
    out = _launch.empty(values.shape, dtype=dtype, device=values.device)
    copyto(out, values)
    return out

copyto

copyto(dst: ArrayNd, src: ArrayNd) -> None

Copy src into dst, converting each element to dst's dtype (numpy.copyto).

A matching dtype is a plain copy. Otherwise every element is converted as wp.cast would at kernel scope, through a concrete kernel built once per dtype pair -- never through warp.utils.array_cast, whose generic kernel rebuilds Warp's whole utility module the first time it meets each new pair.

Parameters:

Name Type Description Default
dst ArrayNd

src.shape destination, on src.device, of any scalar or vector dtype whose element shape matches src.dtype's. A slice view writes into its parent.

required
src ArrayNd

(n,) or (n, m) source array.

required

Raises:

Type Description
RuntimeError

If dst and src are on different devices.

ValueError

If the shapes differ, or if the dtypes differ and either array is rank-2 and not contiguous, since the rank-2 conversion flattens.

See Also

astype The same conversion into a new array.

Examples:

Mirrors numpy.copyto, converting float64 into an int32 buffer:

import warp as wp

import ordito as od

destination = wp.zeros(3, dtype=wp.int32)
od.array.copyto(destination, wp.array([1.9, 2.0, -0.5], dtype=wp.float64))
print(destination.numpy().tolist())  # [1, 2, 0]
Source code in ordito/array.py
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
def copyto(dst: odt.ArrayNd, src: odt.ArrayNd) -> None:
    """
    Copy ``src`` into ``dst``, converting each element to ``dst``'s dtype (``numpy.copyto``).

    A matching dtype is a plain copy. Otherwise every element is converted as ``wp.cast`` would at
    kernel scope, through a concrete kernel built once per dtype pair -- never through
    ``warp.utils.array_cast``, whose generic kernel rebuilds Warp's whole utility module the first
    time it meets each new pair.

    Parameters
    ----------
    dst
        ``src.shape`` destination, on ``src.device``, of any scalar or vector dtype whose element
        shape matches ``src.dtype``'s. A slice view writes into its parent.
    src
        ``(n,)`` or ``(n, m)`` source array.

    Raises
    ------
    RuntimeError
        If ``dst`` and ``src`` are on different devices.
    ValueError
        If the shapes differ, or if the dtypes differ and either array is rank-2 and not
        contiguous, since the rank-2 conversion flattens.

    See Also
    --------
    [`astype`][ordito.array.astype]
        The same conversion into a new array.

    Examples
    --------
    Mirrors [`numpy.copyto`][], converting ``float64`` into an ``int32`` buffer:

    ```python
    import warp as wp

    import ordito as od

    destination = wp.zeros(3, dtype=wp.int32)
    od.array.copyto(destination, wp.array([1.9, 2.0, -0.5], dtype=wp.float64))
    print(destination.numpy().tolist())  # [1, 2, 0]
    ```
    """
    require_same_device(dst=dst, src=src)
    if tuple(dst.shape) != tuple(src.shape):
        raise ValueError(f"copyto needs matching shapes, got {dst.shape} and {src.shape}")
    if src.size == 0:
        return
    if dst.dtype == src.dtype:
        _launch.copy(dst, src)
        return
    source, target = src, dst
    if int(src.ndim) != 1:
        if not (src.is_contiguous and dst.is_contiguous):
            raise ValueError("copyto requires contiguous arrays to convert rank-2 input")
        source, target = src.flatten(), dst.flatten()
    kernel = kernel_array.cast_kernel(src.dtype, dst.dtype)
    _launch.launch(kernel, dim=source.size, inputs=[source, target], device=src.device)

index_bound

index_bound(
    indices: ArrayNdInt,
    *,
    require_non_negative: bool = False,
) -> int

Exclusive upper bound on an index buffer's values, as max(indices) + 1.

For a face or edge buffer this is the vertex count, and it follows libigl's F.maxCoeff() + 1 convention: one past the largest referenced index, so a mesh with trailing unreferenced vertices reports fewer than it has. Accepts any wp.int32 index buffer of any shape -- a length-3 * n_faces flat triangle buffer, an (n, 2) edge array -- and reads only the 4-byte maximum back to the host.

Named for the index buffer rather than for vertices because that is all it sees: it is index arithmetic, and nothing about it is geometric. Named a bound rather than a size because that is what a consumer wants it for -- to allocate a table the indices address, or to hand hash_indices_rows its radix -- and because a mesh with trailing unreferenced vertices has more of them than this reports.

Parameters:

Name Type Description Default
indices ArrayNdInt

A wp.int32 index buffer of any shape (e.g. a flat faces array or a (n, 2) edge array).

required
require_non_negative bool

Raise if any index is negative. Free: the minimum comes out of the same reduction, the same buffer and the same host readback as the maximum, so asking for both costs what asking for one does. It exists because the pairing it replaces is not free -- a caller that takes this bound and then hands it to hash_indices_rows with validate=True reduces the same array a second time to re-check a bound derived from it, where only the negative half of that check can ever fire. Pass this instead and the packing's validate=False.

False

Returns:

Type Description
int

max(indices) + 1, or 0 when indices is empty.

Raises:

Type Description
ValueError

If require_non_negative is set and any index is negative.

Examples:

A cube's faces reference all eight corners, so the bound is the vertex count:

import ordito as od

vertices, faces = od.creation.box()
print(od.array.index_bound(faces, require_non_negative=True))  # 8
Source code in ordito/array.py
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
def index_bound(indices: odt.ArrayNdInt, *, require_non_negative: bool = False) -> int:
    """
    Exclusive upper bound on an index buffer's values, as ``max(indices) + 1``.

    For a face or edge buffer this is the vertex count, and it follows libigl's
    ``F.maxCoeff() + 1`` convention: one past the largest referenced index, so a mesh with trailing
    unreferenced vertices reports fewer than it has. Accepts any ``wp.int32`` index buffer of any
    shape -- a length-``3 * n_faces`` flat triangle buffer, an ``(n, 2)`` edge array -- and reads
    only the 4-byte maximum back to the host.

    Named for the index buffer rather than for vertices because that is all it sees: it is
    index arithmetic, and nothing about it is geometric. Named a *bound* rather than a size
    because that is what a consumer wants it for -- to allocate a table the indices address, or to
    hand [`hash_indices_rows`][ordito.grouping.hash_indices_rows] its radix -- and because a mesh
    with trailing unreferenced vertices has more of them than this reports.

    Parameters
    ----------
    indices
        A ``wp.int32`` index buffer of any shape (e.g. a flat ``faces`` array or a ``(n, 2)``
        edge array).
    require_non_negative
        Raise if any index is negative. Free: the minimum comes out of the same reduction, the
        same buffer and the same host readback as the maximum, so asking for both costs what
        asking for one does. It exists because the pairing it replaces is not free -- a caller
        that takes this bound and then hands it to
        [`hash_indices_rows`][ordito.grouping.hash_indices_rows] with ``validate=True`` reduces
        the same array a second time to re-check a bound derived from it, where only the negative
        half of that check can ever fire. Pass this instead and the packing's ``validate=False``.

    Returns
    -------
    int
        ``max(indices) + 1``, or ``0`` when ``indices`` is empty.

    Raises
    ------
    ValueError
        If ``require_non_negative`` is set and any index is negative.

    Examples
    --------
    A cube's faces reference all eight corners, so the bound is the vertex count:

    ```python
    import ordito as od

    vertices, faces = od.creation.box()
    print(od.array.index_bound(faces, require_non_negative=True))  # 8
    ```
    """
    if int(indices.size) == 0:
        return 0
    # Device-side extrema: only the two clamped ends cross to the host, not the whole buffer.
    low, high = index_extrema(indices)
    if require_non_negative:
        return checked_index_bound(low, high, "indices")
    if low < 0 and high == 0:
        # The maximum clamped at zero: every index may be negative, so measure it.
        return int(od.reduce.max(indices)) + 1
    return high + 1

indices_to_mask

indices_to_mask(
    indices: array[int32],
    n: int,
    *,
    device: DeviceLike = None,
) -> wp.array[wp.bool]

Boolean membership mask of length n marking each value in indices as True.

Wraps the mark_membership_mask scatter kernel: every indices[i] sets out_mask[indices[i]] = True. The inverse of flatnonzero.

Parameters:

Name Type Description Default
indices array[int32]

(k,) values in [0, n) to mark. May be empty.

required
n int

Length of the returned mask.

required
device DeviceLike

Target Warp device. Defaults to indices.device.

None

Returns:

Type Description
array[bool]

(n,) mask, all False except at positions named by indices.

See Also

flatnonzero isin

Examples:

import warp as wp

import ordito as od

indices = wp.array([3, 1], dtype=wp.int32)
mask = od.array.indices_to_mask(indices, 5)
print(mask.numpy().tolist())  # [False, True, False, True, False]
print(od.array.flatnonzero(mask).numpy().tolist())  # [1, 3]
Source code in ordito/array.py
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
def indices_to_mask(
    indices: wp.array[wp.int32], n: int, *, device: wp.DeviceLike = None
) -> wp.array[wp.bool]:
    """
    Boolean membership mask of length ``n`` marking each value in ``indices`` as ``True``.

    Wraps the ``mark_membership_mask`` scatter kernel: every ``indices[i]`` sets
    ``out_mask[indices[i]] = True``. The inverse of [`flatnonzero`][ordito.array.flatnonzero].

    Parameters
    ----------
    indices
        ``(k,)`` values in ``[0, n)`` to mark. May be empty.
    n
        Length of the returned mask.
    device
        Target Warp device. Defaults to ``indices.device``.

    Returns
    -------
    wp.array[wp.bool]
        ``(n,)`` mask, all ``False`` except at positions named by ``indices``.

    See Also
    --------
    [`flatnonzero`][ordito.array.flatnonzero]
    [`isin`][ordito.array.isin]

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

    import ordito as od

    indices = wp.array([3, 1], dtype=wp.int32)
    mask = od.array.indices_to_mask(indices, 5)
    print(mask.numpy().tolist())  # [False, True, False, True, False]
    print(od.array.flatnonzero(mask).numpy().tolist())  # [1, 3]
    ```
    """
    device = device if device is not None else indices.device
    mask = _launch.zeros(n, dtype=wp.bool, device=device)
    k = indices.size
    if k > 0:
        _launch.launch(
            kernel_scatter.mark_membership_mask, dim=k, inputs=[indices, mask], device=device
        )
    return mask

mask_to_compact_ranks

mask_to_compact_ranks(
    mask: array[bool], *, invert: bool = False
) -> tuple[wp.array[wp.int32], int]

Compact index map over the True entries of a boolean mask, plus their count.

Not flatnonzero, though the two come from the same scan: flatnonzero returns which elements are selected (length count, values are positions into mask), while this returns where each element lands in the compacted numbering (length n, values are compact ranks). Renumbering consumers — the free/fixed degree-of-freedom partitions in ordito.smoothing and ordito.linalg — need this full-length scatter-side form, which flatnonzero cannot provide without an extra pass.

Parameters:

Name Type Description Default
mask array[bool]

(n,) mask.

required
invert bool

When True, map the False entries instead. Useful for a free/fixed degree-of-freedom partition, where the mask marks the constrained entries and the compact map is wanted over the unconstrained complement (see free_partition).

False

Returns:

Name Type Description
compact_ranks array[int32]

(n,) ranks on mask.device: an exclusive scan of the (optionally inverted) mask, so index_map[i] is the compact 0-based rank of element i among the selected entries at or before it (meaningful only where element i is itself selected).

count int

Total number of selected entries in mask.

Examples:

The selected entries 0, 2 and 3 are renumbered 0, 1 and 2; with invert=True the unselected entries 1 and 4 are renumbered 0 and 1:

import warp as wp

import ordito as od

mask = wp.array([True, False, True, True, False], dtype=wp.bool)
ranks, count = od.array.mask_to_compact_ranks(mask)
print(ranks.numpy().tolist(), count)  # [0, 1, 1, 2, 3] 3
ranks, count = od.array.mask_to_compact_ranks(mask, invert=True)
print(ranks.numpy().tolist(), count)  # [0, 0, 1, 1, 1] 2
Source code in ordito/array.py
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
def mask_to_compact_ranks(
    mask: wp.array[wp.bool], *, invert: bool = False
) -> tuple[wp.array[wp.int32], int]:
    """
    Compact index map over the ``True`` entries of a boolean mask, plus their count.

    Not [`flatnonzero`][ordito.array.flatnonzero], though the two come from the same scan:
    ``flatnonzero`` returns *which* elements are selected (length ``count``, values are positions
    into ``mask``), while this returns *where each element lands* in the compacted numbering
    (length ``n``, values are compact ranks). Renumbering consumers — the free/fixed
    degree-of-freedom partitions in [`ordito.smoothing`][ordito.smoothing] and
    [`ordito.linalg`][ordito.linalg] — need this full-length scatter-side form, which
    ``flatnonzero`` cannot provide without an extra pass.

    Parameters
    ----------
    mask
        ``(n,)`` mask.
    invert
        When ``True``, map the ``False`` entries instead. Useful for a free/fixed degree-of-freedom
        partition, where the mask marks the *constrained* entries and the compact map is wanted over
        the unconstrained complement (see [`free_partition`][ordito.linalg.free_partition]).

    Returns
    -------
    compact_ranks : wp.array[wp.int32]
        ``(n,)`` ranks on ``mask.device``: an exclusive scan of the (optionally inverted) mask,
        so ``index_map[i]`` is the compact 0-based rank of element ``i`` among the selected
        entries at or before it (meaningful only where element ``i`` is itself selected).
    count : int
        Total number of selected entries in ``mask``.

    Examples
    --------
    The selected entries 0, 2 and 3 are renumbered 0, 1 and 2; with ``invert=True`` the
    unselected entries 1 and 4 are renumbered 0 and 1:

    ```python
    import warp as wp

    import ordito as od

    mask = wp.array([True, False, True, True, False], dtype=wp.bool)
    ranks, count = od.array.mask_to_compact_ranks(mask)
    print(ranks.numpy().tolist(), count)  # [0, 1, 1, 2, 3] 3
    ranks, count = od.array.mask_to_compact_ranks(mask, invert=True)
    print(ranks.numpy().tolist(), count)  # [0, 0, 1, 1, 1] 2
    ```
    """
    device = mask.device
    n = mask.size
    if n == 0:
        return _launch.zeros(0, dtype=wp.int32, device=device), 0
    # The flags are written straight into the tail of the ``n + 1`` offsets buffer, with its
    # leading zero, and scanned there in place, so the separate flag buffer ``counts_to_offsets``
    # would take them from is never allocated. Declined (2026-11-13, CUDA, interleaved in one
    # process): ``flatnonzero``'s counted ballot bits and a rank pass a position
    # (``kernels/array.bit_slot``) in place of the scan of ``n`` flags, 1.5-1.6x up to 2.6 M
    # entries, 1.12-1.28x at 8-16 M, 0.69-0.72x from 32 M, where the flags leave L2. Every caller
    # ranks a vertex mask (``linalg.free_partition``, smoothing), under that size on ``lucy``.
    buffer = _launch.empty(n + 1, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_array.mask_rank_flags, dim=n, inputs=[mask, bool(invert), buffer], device=device
    )
    flags = _launch.view(buffer, 1, n + 1)
    return _launch.view(buffer, 0, n), _scan_into_tail(buffer, flags, flags)

bit_ranks

bit_ranks(
    words: array[uint32], *, out: array[int32] | None = None
) -> wp.array[wp.int32]

Return each word's inclusive count of set bits over a uint32 bitmask.

The rank table of a bitmask stored 32 flags to a word: ranks[w] is the number of set bits in words[0 : w + 1], so the last entry is the population, the set bits before position p are ranks[p >> 5] less the set bits of word p >> 5 at or past p (kernels/array.bit_rank), and the k-th set bit lies in the first word whose rank passes k (kernels/array.nth_bit_position). A flag a position stored this way and ranked takes a 32nd of an int32 flag's memory and scan.

Parameters:

Name Type Description Default
words array[uint32]

(n_words,) bitmask, bit p & 31 of word p >> 5 the flag of position p.

required
out array[int32] | None

(n_words,) buffer on words.device to write the ranks into, or None to allocate one.

None

Returns:

Type Description
array[int32]

(n_words,) inclusive running count of the words' set bits, on words.device: out when given.

Raises:

Type Description
RuntimeError

If words and out are on different devices.

ValueError

If out does not hold one entry per word.

See Also

mask_to_compact_ranks flatnonzero

Examples:

Three set bits in the first word, none in the second, one in the third:

import warp as wp

import ordito as od

words = wp.array([0b1011, 0, 0b100], dtype=wp.uint32)
print(od.array.bit_ranks(words).numpy().tolist())  # [3, 3, 4]
Source code in ordito/array.py
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
def bit_ranks(
    words: wp.array[wp.uint32], *, out: wp.array[wp.int32] | None = None
) -> wp.array[wp.int32]:
    """
    Return each word's inclusive count of set bits over a ``uint32`` bitmask.

    The rank table of a bitmask stored 32 flags to a word: ``ranks[w]`` is the number of set bits
    in ``words[0 : w + 1]``, so the last entry is the population, the set bits before position
    ``p`` are ``ranks[p >> 5]`` less the set bits of word ``p >> 5`` at or past ``p``
    (``kernels/array.bit_rank``), and the ``k``-th set bit lies in the first word whose rank
    passes ``k`` (``kernels/array.nth_bit_position``). A flag a position stored this way and
    ranked takes a 32nd of an ``int32`` flag's memory and scan.

    Parameters
    ----------
    words
        ``(n_words,)`` bitmask, bit ``p & 31`` of word ``p >> 5`` the flag of position ``p``.
    out
        ``(n_words,)`` buffer on ``words.device`` to write the ranks into, or ``None`` to allocate
        one.

    Returns
    -------
    wp.array[wp.int32]
        ``(n_words,)`` inclusive running count of the words' set bits, on ``words.device``:
        ``out`` when given.

    Raises
    ------
    RuntimeError
        If ``words`` and ``out`` are on different devices.
    ValueError
        If ``out`` does not hold one entry per word.

    See Also
    --------
    [`mask_to_compact_ranks`][ordito.array.mask_to_compact_ranks]
    [`flatnonzero`][ordito.array.flatnonzero]

    Examples
    --------
    Three set bits in the first word, none in the second, one in the third:

    ```python
    import warp as wp

    import ordito as od

    words = wp.array([0b1011, 0, 0b100], dtype=wp.uint32)
    print(od.array.bit_ranks(words).numpy().tolist())  # [3, 3, 4]
    ```
    """
    require_same_device(words=words, out=out)
    if out is None:
        ranks = _launch.empty(words.size, dtype=wp.int32, device=words.device)
    elif out.size != words.size:
        raise ValueError(f"out must hold {words.size} ranks, one per word, got {out.size}")
    else:
        ranks = out
    if words.size == 0:
        return ranks
    _launch.map(kernel_array.popcount32, words, out=ranks)
    _launch.array_scan(ranks, out_array=ranks, inclusive=True)
    return ranks

counts_to_offsets

counts_to_offsets(
    counts: array[int32],
) -> tuple[wp.array[wp.int32], int]

Total-terminated exclusive prefix sum of counts, plus their total.

The CSR-building step that turns per-element counts into row starts. Done in one scan pass and one 4-byte host read: the scan runs inclusive into the tail of an n + 1 buffer whose leading zero is already in place, which makes the first n entries the exclusive sum and the last entry the total. The obvious spelling -- one exclusive scan for the offsets and a second inclusive scan (or a reduce.sum) for the total -- costs a second full pass over counts, and reading the total as inclusive.numpy()[-1] copies the whole array to the host to look at one element of it.

Parameters:

Name Type Description Default
counts array[int32]

(n,) per-element counts.

required

Returns:

Name Type Description
offsets array[int32]

(n + 1,) total-terminated offsets (the package's one convention, stated at pack_1d_arrays): element i owns [offsets[i], offsets[i + 1]) and offsets[n] == total. [0] when counts is empty.

total int

Sum of counts, read back so a caller sizing an output needs no second device access.

Notes

This is for callers that want total, which it reads back unconditionally, and a host readback serialises the device pipeline. A caller that only needs the offsets and already knows its buffer size should keep the open-coded wp.zeros(n + 1) plus a scan into [1:], as halfedge.vertex_one_rings and adjacency.vertex_face_adjacency do: both size their payload from 3 * n_faces and would gain a synchronization they currently do not have.

See Also

flatnonzero mask_to_compact_ranks

Examples:

Element 1 owns no entries, so its range [2, 2) is empty:

import warp as wp

import ordito as od

offsets, total = od.array.counts_to_offsets(wp.array([2, 0, 3], dtype=wp.int32))
print(offsets.numpy().tolist(), total)  # [0, 2, 2, 5] 5
Source code in ordito/array.py
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
def counts_to_offsets(counts: wp.array[wp.int32]) -> tuple[wp.array[wp.int32], int]:
    """
    Total-terminated exclusive prefix sum of ``counts``, plus their total.

    The CSR-building step that turns per-element counts into row starts. Done in **one** scan pass
    and one 4-byte host read: the scan runs *inclusive* into the tail of an ``n + 1`` buffer whose
    leading zero is already in place, which makes the first ``n`` entries the exclusive sum and the
    last entry the total. The obvious spelling -- one exclusive scan for the offsets and a second
    inclusive scan (or a ``reduce.sum``) for the total -- costs a second full pass over ``counts``,
    and reading the total as ``inclusive.numpy()[-1]`` copies the whole array to the host to look at
    one element of it.

    Parameters
    ----------
    counts
        ``(n,)`` per-element counts.

    Returns
    -------
    offsets : wp.array[wp.int32]
        ``(n + 1,)`` total-terminated offsets (the package's one convention, stated at
        [`pack_1d_arrays`][ordito.array.pack_1d_arrays]): element ``i`` owns
        ``[offsets[i], offsets[i + 1])`` and ``offsets[n] == total``. ``[0]`` when ``counts`` is
        empty.
    total : int
        Sum of ``counts``, read back so a caller sizing an output needs no second device access.

    Notes
    -----
    **This is for callers that want ``total``**, which it reads back unconditionally, and a host
    readback serialises the device pipeline. A caller that only needs the offsets and already knows
    its buffer size should keep the open-coded ``wp.zeros(n + 1)`` plus a scan into ``[1:]``, as
    ``halfedge.vertex_one_rings`` and ``adjacency.vertex_face_adjacency`` do: both size their
    payload from ``3 * n_faces`` and would gain a synchronization they currently do not have.

    See Also
    --------
    [`flatnonzero`][ordito.array.flatnonzero]
    [`mask_to_compact_ranks`][ordito.array.mask_to_compact_ranks]

    Examples
    --------
    Element 1 owns no entries, so its range ``[2, 2)`` is empty:

    ```python
    import warp as wp

    import ordito as od

    offsets, total = od.array.counts_to_offsets(wp.array([2, 0, 3], dtype=wp.int32))
    print(offsets.numpy().tolist(), total)  # [0, 2, 2, 5] 5
    ```
    """
    # The unconditional readback of ``total`` is a host synchronization -- which is why the Notes
    # section advises open-coding the scan when only the offsets are wanted.
    n = counts.size
    device = counts.device
    if n == 0:
        return _launch.zeros(1, dtype=wp.int32, device=device), 0
    # The leading zero is the first exclusive offset; the inclusive scan fills the rest, so
    # ``buffer[n]`` is the total and ``buffer[:n]`` the exclusive offsets. A long buffer zeroes
    # that one slot rather than all of them.
    if n >= (_HEAD_ZERO_FROM_CUDA if wp.get_device(device).is_cuda else _HEAD_ZERO_FROM_CPU):
        buffer = _launch.empty(n + 1, dtype=wp.int32, device=device)
        _launch.zero_(_launch.view(buffer, 0, 1))
    else:
        buffer = _launch.zeros(n + 1, dtype=wp.int32, device=device)
    return buffer, _scan_into_tail(buffer, counts, _launch.view(buffer, 1, n + 1))

remap_indices

remap_indices(
    indices: array[int32], remap: array[int32]
) -> wp.array[wp.int32]

Remap an index buffer through a lookup table, passing negative (sentinel) entries through.

Not a plain gather: the -1 slots that mark padded or removed entries in an index buffer must survive the remap unchanged, where a gather would read out of bounds on them. ordito.repair relies on this — its functions preserve -1 face sentinels through vertex renumbering (see remove_unreferenced_vertices).

Parameters:

Name Type Description Default
indices array[int32]

(n,) indices into remap (e.g. a flat face buffer). Negative entries are passed through unchanged.

required
remap array[int32]

(n_table,) lookup table (e.g. old-to-new vertex index map).

required

Returns:

Type Description
array[int32]

(n,) array on indices.device with out[i] = remap[indices[i]] for non-negative indices[i], and out[i] = indices[i] otherwise.

Raises:

Type Description
RuntimeError

If indices and remap are not all on one device.

See Also

gather The sentinel-free form: a dense first-axis gather for index buffers known to be in range.

Examples:

import warp as wp

import ordito as od

indices = wp.array([2, -1, 0], dtype=wp.int32)
remap = wp.array([10, 11, 12], dtype=wp.int32)
print(od.array.remap_indices(indices, remap).numpy().tolist())  # [12, -1, 10]
Source code in ordito/array.py
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
def remap_indices(indices: wp.array[wp.int32], remap: wp.array[wp.int32]) -> wp.array[wp.int32]:
    """
    Remap an index buffer through a lookup table, passing negative (sentinel) entries through.

    Not a plain [`gather`][ordito.array.gather]: the ``-1`` slots that mark padded or removed
    entries in an index buffer must survive the remap unchanged, where a gather would read out of
    bounds on them. [`ordito.repair`][ordito.repair] relies on this — its functions preserve
    ``-1`` face sentinels through vertex renumbering (see ``remove_unreferenced_vertices``).

    Parameters
    ----------
    indices
        ``(n,)`` indices into ``remap`` (e.g. a flat face buffer). Negative entries are passed
        through unchanged.
    remap
        ``(n_table,)`` lookup table (e.g. old-to-new vertex index map).

    Returns
    -------
    wp.array[wp.int32]
        ``(n,)`` array on ``indices.device`` with ``out[i] = remap[indices[i]]``
        for non-negative ``indices[i]``, and ``out[i] = indices[i]`` otherwise.

    Raises
    ------
    RuntimeError
        If ``indices`` and ``remap`` are not all on one device.

    See Also
    --------
    [`gather`][ordito.array.gather]
        The sentinel-free form: a dense first-axis gather for index buffers known to be in range.

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

    import ordito as od

    indices = wp.array([2, -1, 0], dtype=wp.int32)
    remap = wp.array([10, 11, 12], dtype=wp.int32)
    print(od.array.remap_indices(indices, remap).numpy().tolist())  # [12, -1, 10]
    ```
    """
    require_same_device(indices=indices, remap=remap)
    n = indices.size
    device = indices.device
    if n == 0:
        return _launch.empty(0, dtype=wp.int32, device=device)
    out = _launch.empty(n, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_array.gather_1d_skip_negative, dim=n, inputs=[indices, remap, out], device=device
    )
    return out

trim_to_count

trim_to_count(
    counter: array[int32], *buffers: array[DType, Any]
) -> tuple[int, list[wp.array[DType, Any]]]

Trim atomic-append output buffers to the number of elements actually written.

A kernel that emits an unpredictable number of results cannot size its output ahead of time. The usual pattern is to over-allocate the output buffers to a safe upper bound and have each thread claim its slots with wp.atomic_add on a shared length-1 counter, writing into buffer[slot]. After the launch, only the first n_out slots hold valid data and the tail is uninitialized, but n_out is known only on the device.

This finalizes that pattern: it reads the counter back to the host once, then copies the valid prefix buffer[:n_out] of each over-allocated buffer into a freshly allocated, exact-size array. Pass every buffer filled by the same counter in one call so they are all trimmed to a consistent length.

Parameters:

Name Type Description Default
counter array[int32]

(1,) array holding the final atomic-append count on the target device.

required
*buffers array[DType, Any]

Over-allocated output buffers to trim, all indexed along their first axis by the same counter. Any rank and dtype; trailing dimensions are preserved.

()

Returns:

Name Type Description
n_out int

The counter value: the number of valid leading elements in each buffer.

trimmed list[array]

One contiguous (n_out, *buffer.shape[1:]) copy per input buffer, in order, each on its buffer's device.

Examples:

A kernel appended two results into buffers sized for four:

import warp as wp

import ordito as od

counter = wp.array([2], dtype=wp.int32)
values = wp.array([7, 9, 0, 0], dtype=wp.int32)
points = wp.zeros(4, dtype=wp.vec3)
n_out, (values, points) = od.array.trim_to_count(counter, values, points)
print(n_out, values.numpy().tolist(), points.shape)  # 2 [7, 9] (2,)
Source code in ordito/array.py
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
def trim_to_count(
    counter: wp.array[wp.int32], *buffers: wp.array[DType, Any]
) -> tuple[int, list[wp.array[DType, Any]]]:
    """
    Trim atomic-append output buffers to the number of elements actually written.

    A kernel that emits an unpredictable number of results cannot size its output ahead of
    time. The usual pattern is to over-allocate the output buffers to a safe upper bound and
    have each thread claim its slots with ``wp.atomic_add`` on a shared length-1 ``counter``,
    writing into ``buffer[slot]``. After the launch, only the first ``n_out`` slots hold valid
    data and the tail is uninitialized, but ``n_out`` is known only on the device.

    This finalizes that pattern: it reads the counter back to the host once, then copies the
    valid prefix ``buffer[:n_out]`` of each over-allocated buffer into a freshly allocated,
    exact-size array. Pass every buffer filled by the same counter in one call so they are all
    trimmed to a consistent length.

    Parameters
    ----------
    counter
        ``(1,)`` array holding the final atomic-append count on the target device.
    *buffers
        Over-allocated output buffers to trim, all indexed along their first axis by the same
        counter. Any rank and ``dtype``; trailing dimensions are preserved.

    Returns
    -------
    n_out : int
        The counter value: the number of valid leading elements in each buffer.
    trimmed : list[wp.array]
        One contiguous ``(n_out, *buffer.shape[1:])`` copy per input buffer, in order, each on
        its buffer's device.

    Examples
    --------
    A kernel appended two results into buffers sized for four:

    ```python
    import warp as wp

    import ordito as od

    counter = wp.array([2], dtype=wp.int32)
    values = wp.array([7, 9, 0, 0], dtype=wp.int32)
    points = wp.zeros(4, dtype=wp.vec3)
    n_out, (values, points) = od.array.trim_to_count(counter, values, points)
    print(n_out, values.numpy().tolist(), points.shape)  # 2 [7, 9] (2,)
    ```
    """
    n_out = int(read_scalar(counter, 0))
    trimmed = []
    for buffer in buffers:
        out_shape = (n_out, *(int(dim) for dim in buffer.shape[1:]))
        out = _launch.empty(out_shape, dtype=buffer.dtype, device=buffer.device)
        if n_out > 0:
            # A contiguous buffer's rows are its leading elements, copied with no view built.
            if buffer.is_contiguous:
                _launch.copy(out, buffer, count=int(out.size))
            else:
                _launch.copy(out, buffer[:n_out])
        trimmed.append(out)
    return n_out, trimmed

bitcast_to_int

bitcast_to_int(
    data: array[Scalar], count: int | None = None
) -> wp.array[wp.int32] | wp.array[wp.int64]

Reinterpret an array's underlying bits as a same-width signed integer dtype.

32-bit-or-narrower dtypes (wp.int32, wp.uint32, wp.float32, and narrower) are reinterpreted as wp.int32; wider dtypes (wp.int64, wp.uint64, wp.float64) as wp.int64. Narrower-than-32-bit floating point values are first upcast to wp.float32 (a numeric cast, not a bit reinterpretation) so every dtype narrower than 32 bits shares one wp.int32 key space. Used by the hashing/uniqueness machinery (unique_1d) to give arbitrary scalar dtypes a common sortable, hashable integer key.

Parameters:

Name Type Description Default
data array[Scalar]

(n,) wp.array of any scalar dtype.

required
count int | None

Output length. Defaults to data.shape[0]. When greater than the input length, the tail is left uninitialized (over-allocation for in-place radix-sort scratch).

None

Returns:

Type Description
array[int32] | array[int64]

(count,) bit-reinterpreted (or, for sub-32-bit floats, upcast-then-reinterpreted) copy on data.device.

See Also

bitcast_from_int

Examples:

The IEEE-754 bits of 1.0 and -0.0 as int32; float64 would give int64:

import warp as wp

import ordito as od

bits = od.array.bitcast_to_int(wp.array([1.0, -0.0], dtype=wp.float32))
print(bits.dtype is wp.int32, bits.numpy().tolist())  # True [1065353216, -2147483648]
Source code in ordito/array.py
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
def bitcast_to_int(
    data: wp.array[wp.Scalar], count: int | None = None
) -> wp.array[wp.int32] | wp.array[wp.int64]:
    """
    Reinterpret an array's underlying bits as a same-width signed integer dtype.

    32-bit-or-narrower dtypes (``wp.int32``, ``wp.uint32``, ``wp.float32``, and narrower) are
    reinterpreted as ``wp.int32``; wider dtypes (``wp.int64``, ``wp.uint64``, ``wp.float64``) as
    ``wp.int64``. Narrower-than-32-bit floating point values are first upcast to ``wp.float32``
    (a numeric cast, not a bit reinterpretation) so every dtype narrower than 32 bits shares one
    ``wp.int32`` key space. Used by the hashing/uniqueness machinery
    ([`unique_1d`][ordito.grouping.unique_1d]) to give arbitrary scalar dtypes a common sortable,
    hashable integer key.

    Parameters
    ----------
    data
        ``(n,)`` ``wp.array`` of any scalar dtype.
    count
        Output length. Defaults to ``data.shape[0]``. When greater than the input length, the
        tail is left uninitialized (over-allocation for in-place radix-sort scratch).

    Returns
    -------
    wp.array[wp.int32] | wp.array[wp.int64]
        ``(count,)`` bit-reinterpreted (or, for sub-32-bit floats, upcast-then-reinterpreted)
        copy on ``data.device``.

    See Also
    --------
    [`bitcast_from_int`][ordito.array.bitcast_from_int]

    Examples
    --------
    The IEEE-754 bits of ``1.0`` and ``-0.0`` as ``int32``; ``float64`` would give ``int64``:

    ```python
    import warp as wp

    import ordito as od

    bits = od.array.bitcast_to_int(wp.array([1.0, -0.0], dtype=wp.float32))
    print(bits.dtype is wp.int32, bits.numpy().tolist())  # True [1065353216, -2147483648]
    ```
    """
    n_bits = wp.types.type_size_in_bytes(data.dtype) * 8
    n = data.size
    # ``is None``, not ``or``: zero is a legitimate length and ``or`` would read it as "not passed"
    # and hand back the whole buffer -- an ``n``-element array of stale bits where the caller asked
    # for an empty one. The signature already spells the distinction; only this line lost it.
    count = n if count is None else count
    copy_count = min(n, count)
    target = wp.int64 if n_bits > 32 else wp.int32

    # ``count=0`` reaches ``wp.copy`` as *"copy the whole source"* -- a documented
    # back-compatibility rule in Warp 1.19 (``if count == 0: count = src.size``), so the zero that
    # means "nothing" and the zero that means "everything" are the same argument. Into a length-0
    # destination that is not even a clean refusal: it raises ``TypeError: unsupported operand
    # type(s) for +: 'NoneType' and 'int'`` from inside the copy. Returning the empty allocation
    # here is both the right answer and the only way to state it (a zero-length slice for the
    # ``copyto`` paths below would raise too).
    if copy_count == 0:
        return cast(
            "wp.array[wp.int32] | wp.array[wp.int64]",
            _launch.empty(count, dtype=target, device=data.device),
        )

    if n_bits > 32:
        reinterpreted = _launch.empty(count, dtype=wp.int64, device=data.device)
        _launch.copy(reinterpreted, data, count=copy_count)
        return reinterpreted

    reinterpreted = _launch.empty(count, dtype=wp.int32, device=data.device)
    if wp.types.type_is_float(data.dtype):
        src = data
        if n_bits < 32:
            src = _launch.empty(copy_count, dtype=wp.float32, device=data.device)
            copyto(src, odt.as_dense(data[:copy_count]))
        _launch.copy(reinterpreted, src, count=copy_count)
    else:
        copyto(odt.as_dense(reinterpreted[:copy_count]), odt.as_dense(data[:copy_count]))
    return reinterpreted

bitcast_from_int

bitcast_from_int(
    data: array[int32] | array[int64],
    dtype: type[Scalar],
    count: int | None = None,
) -> wp.array[wp.Scalar]

Inverse of bitcast_to_int: recover the original dtype.

Reinterprets (same-width) or upcasts-then-reinterprets (narrower target) the bits produced by bitcast_to_int back into dtype.

Parameters:

Name Type Description Default
data array[int32] | array[int64]

(n,) wp.array[wp.int32] or wp.array[wp.int64], typically the output of bitcast_to_int.

required
dtype type[Scalar]

Target scalar dtype to reinterpret data as.

required
count int | None

Output length. Defaults to data.shape[0]. When greater than the input length, the tail is left uninitialized.

None

Returns:

Type Description
array[Scalar]

(count,) array of dtype dtype on data.device.

See Also

bitcast_to_int

Examples:

The round trip restores the values bit for bit, the sign of -0.0 included:

import warp as wp

import ordito as od

bits = od.array.bitcast_to_int(wp.array([1.0, -0.0], dtype=wp.float32))
print(od.array.bitcast_from_int(bits, wp.float32).numpy().tolist())  # [1.0, -0.0]
Source code in ordito/array.py
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
def bitcast_from_int(
    data: wp.array[wp.int32] | wp.array[wp.int64], dtype: type[wp.Scalar], count: int | None = None
) -> wp.array[wp.Scalar]:
    """
    Inverse of [`bitcast_to_int`][ordito.array.bitcast_to_int]: recover the original dtype.

    Reinterprets (same-width) or upcasts-then-reinterprets (narrower target) the bits produced
    by ``bitcast_to_int`` back into ``dtype``.

    Parameters
    ----------
    data
        ``(n,)`` ``wp.array[wp.int32]`` or ``wp.array[wp.int64]``, typically the output of
        [`bitcast_to_int`][ordito.array.bitcast_to_int].
    dtype
        Target scalar dtype to reinterpret ``data`` as.
    count
        Output length. Defaults to ``data.shape[0]``. When greater than the input length, the
        tail is left uninitialized.

    Returns
    -------
    wp.array[wp.Scalar]
        ``(count,)`` array of dtype ``dtype`` on ``data.device``.

    See Also
    --------
    [`bitcast_to_int`][ordito.array.bitcast_to_int]

    Examples
    --------
    The round trip restores the values bit for bit, the sign of ``-0.0`` included:

    ```python
    import warp as wp

    import ordito as od

    bits = od.array.bitcast_to_int(wp.array([1.0, -0.0], dtype=wp.float32))
    print(od.array.bitcast_from_int(bits, wp.float32).numpy().tolist())  # [1.0, -0.0]
    ```
    """
    n_bits = wp.types.type_size_in_bytes(data.dtype) * 8
    n_target_bits = wp.types.type_size_in_bytes(dtype) * 8
    n = data.size
    # ``is None`` rather than ``or``, and the zero-length short circuit, both for the reasons
    # recorded at ``bitcast_to_int``: Warp reads ``count=0`` as "copy everything".
    count = n if count is None else count
    copy_count = min(n, count)
    if copy_count == 0:
        return _launch.empty(count, dtype=dtype, device=data.device)

    if n_bits == n_target_bits:
        reinterpreted = _launch.empty(count, dtype=dtype, device=data.device)
        _launch.copy(reinterpreted, data, count=copy_count)
        return reinterpreted

    if wp.types.type_is_float(dtype) and n_bits > n_target_bits:
        wide_dtype = getattr(wp, f"float{n_bits}")
        wide = _launch.empty(count, dtype=wide_dtype, device=data.device)
        _launch.copy(wide, data, count=copy_count)
        reinterpreted_casted = _launch.empty(count, dtype=dtype, device=data.device)
        copyto(odt.as_dense(reinterpreted_casted[:copy_count]), odt.as_dense(wide[:copy_count]))
    else:
        reinterpreted_casted = _launch.empty(count, dtype=dtype, device=data.device)
        copyto(odt.as_dense(reinterpreted_casted[:copy_count]), odt.as_dense(data[:copy_count]))
    return reinterpreted_casted