Skip to content

ordito.cholesky

Sparse Cholesky factorization of symmetric positive-(semi-)definite operators, solved on the device.

sparse_cholesky orders the operator by nested dissection, factors it level by level on the device and returns a SparseCholesky whose solve is a fixed sequence of matrix-vector products, recorded once and replayed. Where a Krylov solver's cost grows with the operator's condition number and with the distance information must travel across the mesh, a factorization's does not: one factor serves every later right-hand side and every operator of the same sparsity (refactor).

Every solve is refined against the operator itself until its residual passes the requested test, unless the caller asks for one solve against the factor alone. A solution spanning hundreds of orders of magnitude -- the heat method's diffusions -- can be solved componentwise, each entry to its own size, which no iteration controlled by a residual norm achieves: on an M-matrix the factor and both triangular solves add terms of one sign, so no entry is formed by cancellation.

A component of the operator's graph whose rows all sum to zero (a Laplacian's constant null space) is solved up to that constant, which is then set to the initial guess's mean: the answer conjugate gradient gives from the same guess on a consistent right-hand side.

Notes

The ordering is geometric nested dissection when vertex coordinates are given and the same bisection over breadth-first distances from three mutually far vertices otherwise. Rows of 1 024 entries or more (a fan's hub) take no part in the bisection and are eliminated last, so a vertex whose neighbours span the mesh does not turn every separator into half of them. The numeric factorization is multifrontal (Liu 1992); each supernode stores the inverse of its diagonal block and the product of that inverse with its off-diagonal rows, so both triangular solves are level-scheduled products with no substitution inside a level (the partitioned inverse of Alvarado, Pothen and Schreiber 1993). Every partial sum lands in its own slot and is reduced in a fixed order, so solves are reproducible on both devices.

Classes:

Name Description
NotPositiveDefiniteError

The operator met a pivot that is not positive: it is not definite, at least in float64.

SparseCholesky

A sparse Cholesky factorization on the device.

Functions:

Name Description
sparse_cholesky

Sparse Cholesky factorization of a symmetric positive-(semi-)definite float64 operator.

held_nbytes

Device memory several factorizations hold together, in bytes: a shared analysis counted once.

factorization_nbytes

Peak device memory sparse_cholesky would take, in bytes.

CHOLESKY_LEAF_ROWS module-attribute

CHOLESKY_LEAF_ROWS = 32

CHOLESKY_TOP_ROWS module-attribute

CHOLESKY_TOP_ROWS = 512

CHOLESKY_REFINE_ROUNDS module-attribute

CHOLESKY_REFINE_ROUNDS = 12

NotPositiveDefiniteError

Bases: ValueError

The operator met a pivot that is not positive: it is not definite, at least in float64.

Raised by sparse_cholesky and SparseCholesky.refactor; a ValueError, so a caller catching that sees it too. Distinct from the operator being too large to factor, which an iteration may still solve: a symmetric operator this cannot factor either way round is past what conjugate gradient converges on as well.

Examples:

A cotangent Laplacian is negative semi-definite, so factoring it as given fails:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
L = od.laplacian.cotmatrix(vertices, faces, dtype=wp.float64)
try:
    od.cholesky.sparse_cholesky(L)
    outcome = "factored"
except od.cholesky.NotPositiveDefiniteError:
    outcome = "not positive definite"
print(outcome)  # not positive definite

SparseCholesky

SparseCholesky(
    plan: _Plan,
    matrix: BsrMatrix[float64],
    *,
    negated: bool,
)

A sparse Cholesky factorization on the device.

Built by sparse_cholesky.

Attributes:

Name Type Description
n int

Rows of the factored operator.

device Device

Device the factor lives on.

nbytes int

Device memory the factorization holds, in bytes: its analysis (shared with every factorization with_operator builds from it; held_nbytes counts it once), its factor, the scratch of every right-hand-side count solved so far, and the storage a repeated refactor keeps. Building also takes a transient arena, not held, which CHOLESKY_MEMORY_BUDGET counts.

negated bool

Whether -matrix was factored (a negative semi-definite operator).

expandable bool

Whether the analysis was built for with_expanded_operator to derive from (sparse_cholesky(expandable=True)).

records_at_once bool

Whether a solve records its refinement graph on its first run (a factorization solved many times), rather than on its second against the same operator storage (the default: a one-shot solve then runs its rounds directly and records nothing).

Examples:

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
system = od.heat.heat_operators(vertices, faces)[0]  # M - t L, float64
factor = od.cholesky.sparse_cholesky(system, vertices)
print(factor.n, factor.negated, factor.nbytes > 0)  # 162 False True

Factor matrix (or its negation) over plan's structure.

Methods:

Name Description
refactor

Factor a new operator of the same sparsity pattern in place.

with_operator

Factor another operator of this one's sparsity pattern, sharing this analysis.

with_expanded_operator

Factor an operator over this pattern's 2 x 2 block expansion, deriving its analysis.

solve

Solve the factored system for one or several right-hand sides, refined in float64.

Source code in ordito/cholesky.py
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
def __init__(self, plan: _Plan, matrix: odt.BsrMatrix[wp.float64], *, negated: bool) -> None:
    """Factor ``matrix`` (or its negation) over ``plan``'s structure."""
    self.negated = negated
    self.expandable = plan.granularity == 2
    self.records_at_once = False
    self.n = plan.n
    self.device = plan.device
    self.nbytes = plan.nbytes + _numeric_nbytes(plan.n, plan.block_entries)
    self._plan = plan
    self._numeric = _numeric(plan)
    self._solves: dict[int, _Solve] = {}
    self._matrix = matrix
    # A caller that refactors repeatedly gets stable storage: the operator copied into arrays
    # this factorization owns, the fronts arena kept, and the numeric factorization recorded
    # once and replayed, as the refined solve then is too (``_Solve.run`` replays for one
    # operator storage). Built on the first ``refactor`` after construction.
    self._stable: odt.BsrMatrix[wp.float64] | None = None
    self._fronts: wp.array[wp.float64] | None = None
    self._factor_graph: Any = None
    # Whether the numeric factor is one ``solve`` may use: false from a ``refactor`` that
    # raised until one that succeeds.
    self._valid = False
    self._constructing = True
    self.refactor(matrix)
    self._constructing = False

negated instance-attribute

negated = negated

expandable instance-attribute

expandable = plan.granularity == 2

records_at_once instance-attribute

records_at_once = False

n instance-attribute

n = plan.n

device instance-attribute

device = plan.device

nbytes instance-attribute

nbytes = plan.nbytes + _numeric_nbytes(
    plan.n, plan.block_entries
)

refactor

refactor(matrix: BsrMatrix[float64]) -> None

Factor a new operator of the same sparsity pattern in place.

If the new operator is not positive definite, the factorization holds no usable factor afterwards: solve raises until a later refactor succeeds.

Parameters:

Name Type Description Default
matrix BsrMatrix[float64]

(n, n) symmetric float64 operator whose stored pattern is the one this factorization was built for (the same row offsets and column indices). Only its shape and its storage's sizes are checked; another pattern of as many stored entries is not detected and factors a wrong operator.

required

Raises:

Type Description
ValueError

If matrix is not (n, n) scalar float64, or stores fewer entries than the pattern this factorization was built for.

NotPositiveDefiniteError

If the operator is not positive definite on its non-singular components (a pivot that is not positive).

RuntimeError

If matrix is not on this factorization's device.

Examples:

The heat system at another diffusion time has the same pattern, so the analysis is reused:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
factor = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces, t=0.01)[0])
factor.refactor(od.heat.heat_operators(vertices, faces, t=0.1)[0])
mass = od.laplacian.mass_matrix_entries(vertices, faces, dtype=wp.float64)
solution = wp.zeros_like(mass)
factor.solve(mass, solution)  # (M - t L) 1 = M 1
print(f"{solution.numpy().min():.6f} {solution.numpy().max():.6f}")  # 1.000000 1.000000
Source code in ordito/cholesky.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def refactor(self, matrix: odt.BsrMatrix[wp.float64]) -> None:
    """
    Factor a new operator of the same sparsity pattern in place.

    If the new operator is not positive definite, the factorization holds no usable factor
    afterwards: [`solve`][ordito.cholesky.SparseCholesky.solve] raises until a later
    ``refactor`` succeeds.

    Parameters
    ----------
    matrix
        ``(n, n)`` symmetric ``float64`` operator whose stored pattern is the one this
        factorization was built for (the same row offsets and column indices). Only its
        shape and its storage's sizes are checked; another pattern of as many stored entries
        is not detected and factors a wrong operator.

    Raises
    ------
    ValueError
        If ``matrix`` is not ``(n, n)`` scalar ``float64``, or stores fewer entries than the
        pattern this factorization was built for.
    NotPositiveDefiniteError
        If the operator is not positive definite on its non-singular components (a pivot that
        is not positive).
    RuntimeError
        If ``matrix`` is not on this factorization's device.

    Examples
    --------
    The heat system at another diffusion time has the same pattern, so the analysis is reused:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    factor = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces, t=0.01)[0])
    factor.refactor(od.heat.heat_operators(vertices, faces, t=0.1)[0])
    mass = od.laplacian.mass_matrix_entries(vertices, faces, dtype=wp.float64)
    solution = wp.zeros_like(mass)
    factor.solve(mass, solution)  # (M - t L) 1 = M 1
    print(f"{solution.numpy().min():.6f} {solution.numpy().max():.6f}")  # 1.000000 1.000000
    ```
    """
    require_same_device(matrix=matrix, factor=self)
    self._require_pattern(matrix, "refactor")
    plan = self._plan
    sign = -1.0 if self.negated else 1.0
    # The factor is overwritten from here on: unusable until the pivots are read back good.
    self._valid = False
    if self._constructing:
        _factor(plan, matrix, self._numeric, sign)
    else:
        matrix = self._stable_copy(matrix)
        fronts = self._fronts
        if fronts is None:
            fronts = self._fronts = _launch.empty(
                plan.front_entries, dtype=wp.float64, device=self.device
            )
            self.nbytes += 8 * plan.front_entries
        device = wp.get_device(self.device)
        if device.is_cuda:
            if self._factor_graph is None:
                with scoped_capture(device) as capture:
                    _factor(plan, matrix, self._numeric, sign, fronts)
                self._factor_graph = capture.graph
            wp.capture_launch(self._factor_graph)
        else:
            _factor(plan, matrix, self._numeric, sign, fronts)
    # Read back: a bad pivot raises, and whether any component is singular decides whether
    # the solves project a null space at all -- both in one read.
    bad_pivot, singular = read_values(self._numeric.status, 0, 2)
    if bad_pivot != 0:
        raise NotPositiveDefiniteError("sparse_cholesky: the operator is not positive definite")
    self._numeric.any_singular = singular != 0
    self._matrix = matrix
    for solve in self._solves.values():
        solve.matrix = matrix
    self._valid = True

with_operator

with_operator(
    matrix: BsrMatrix[float64],
    *,
    negated: bool | None = None,
) -> SparseCholesky

Factor another operator of this one's sparsity pattern, sharing this analysis.

Only the numeric factorization is paid: the ordering and every structure map are this factorization's, held by both. The two factorizations are independent otherwise.

Parameters:

Name Type Description Default
matrix BsrMatrix[float64]

(n, n) symmetric float64 operator stored over the pattern this factorization was built for (the same row offsets and column indices; checked as refactor checks it).

required
negated bool | None

As sparse_cholesky takes it: None factors whichever sign is positive definite.

None

Returns:

Type Description
SparseCholesky

The new factorization.

Raises:

Type Description
ValueError

If matrix is not (n, n) scalar float64, or stores fewer entries than the pattern this factorization was built for.

NotPositiveDefiniteError

If the operator (with negated=None: either sign of it) is not positive definite.

RuntimeError

If matrix is not on this factorization's device.

Examples:

Two diffusion times, one analysis, two independent factorizations:

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
short = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces, t=0.01)[0])
long = short.with_operator(od.heat.heat_operators(vertices, faces, t=0.1)[0])
print(long is short, long.n)  # False 162
Source code in ordito/cholesky.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def with_operator(
    self, matrix: odt.BsrMatrix[wp.float64], *, negated: bool | None = None
) -> SparseCholesky:
    """
    Factor another operator of this one's sparsity pattern, sharing this analysis.

    Only the numeric factorization is paid: the ordering and every structure map are this
    factorization's, held by both. The two factorizations are independent otherwise.

    Parameters
    ----------
    matrix
        ``(n, n)`` symmetric ``float64`` operator stored over the pattern this factorization
        was built for (the same row offsets and column indices; checked as
        [`refactor`][ordito.cholesky.SparseCholesky.refactor] checks it).
    negated
        As [`sparse_cholesky`][ordito.cholesky.sparse_cholesky] takes it: ``None`` factors
        whichever sign is positive definite.

    Returns
    -------
    SparseCholesky
        The new factorization.

    Raises
    ------
    ValueError
        If ``matrix`` is not ``(n, n)`` scalar ``float64``, or stores fewer entries than the
        pattern this factorization was built for.
    NotPositiveDefiniteError
        If the operator (with ``negated=None``: either sign of it) is not positive definite.
    RuntimeError
        If ``matrix`` is not on this factorization's device.

    Examples
    --------
    Two diffusion times, one analysis, two independent factorizations:

    ```python
    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    short = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces, t=0.01)[0])
    long = short.with_operator(od.heat.heat_operators(vertices, faces, t=0.1)[0])
    print(long is short, long.n)  # False 162
    ```
    """
    require_same_device(matrix=matrix, factor=self)
    self._require_pattern(matrix, "with_operator")
    return _factored(self._plan, matrix, negated, analysed=False)

with_expanded_operator

with_expanded_operator(
    matrix: BsrMatrix[float64],
    *,
    negated: bool | None = None,
) -> SparseCholesky

Factor an operator over this pattern's 2 x 2 block expansion, deriving its analysis.

matrix is a wp.mat22d operator stored over this factorization's pattern, as scalar_expansion presents it: unknown i becomes unknowns 2 * i and 2 * i + 1. Those two are eliminated one after the other where i was, so the expansion's analysis is this one's with every supernode and every row of its structure doubled: no ordering or symbolic analysis of its own is run. The new factorization holds its own analysis, and is independent of this one otherwise. Its supernodes are twice this one's: as fine as an analysis of the expansion's own when this one was built expandable (see sparse_cholesky), coarser, with more fill, otherwise.

Parameters:

Name Type Description Default
matrix BsrMatrix[float64]

(2 * n, 2 * n) symmetric float64 operator stored over the 2 x 2 block expansion of the pattern this factorization was built for. Only its shape and its storage's sizes are checked, as refactor checks them.

required
negated bool | None

As sparse_cholesky takes it: None factors whichever sign is positive definite.

None

Returns:

Type Description
SparseCholesky

The factorization of matrix.

Raises:

Type Description
ValueError

If matrix is not (2 * n, 2 * n) scalar float64, stores fewer entries than the expanded pattern, or the factorization's peak device memory would exceed CHOLESKY_MEMORY_BUDGET.

NotPositiveDefiniteError

If the operator (with negated=None: either sign of it) is not positive definite.

RuntimeError

If matrix is not on this factorization's device.

Examples:

The vector heat system is stored over the scalar heat system's pattern, by blocks:

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
vector_system, scalar_operators = od.heat.vector_heat_operators(vertices, faces)[:2]
heat = od.cholesky.sparse_cholesky(scalar_operators[0], vertices, expandable=True)
tangent = heat.with_expanded_operator(od.array.scalar_expansion(vector_system))
print(heat.n, tangent.n)  # 162 324
Source code in ordito/cholesky.py
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def with_expanded_operator(
    self, matrix: odt.BsrMatrix[wp.float64], *, negated: bool | None = None
) -> SparseCholesky:
    """
    Factor an operator over this pattern's 2 x 2 block expansion, deriving its analysis.

    ``matrix`` is a ``wp.mat22d`` operator stored over this factorization's pattern, as
    [`scalar_expansion`][ordito.array.scalar_expansion] presents it: unknown ``i`` becomes
    unknowns ``2 * i`` and ``2 * i + 1``. Those two are eliminated one after the other where
    ``i`` was, so the expansion's analysis is this one's with every supernode and every row of
    its structure doubled: no ordering or symbolic analysis of its own is run. The new
    factorization holds its own analysis, and is independent of this one otherwise. Its
    supernodes are twice this one's: as fine as an analysis of the expansion's own when this
    one was built ``expandable`` (see [`sparse_cholesky`][ordito.cholesky.sparse_cholesky]),
    coarser, with more fill, otherwise.

    Parameters
    ----------
    matrix
        ``(2 * n, 2 * n)`` symmetric ``float64`` operator stored over the 2 x 2 block
        expansion of the pattern this factorization was built for. Only its shape and its
        storage's sizes are checked, as
        [`refactor`][ordito.cholesky.SparseCholesky.refactor] checks them.
    negated
        As [`sparse_cholesky`][ordito.cholesky.sparse_cholesky] takes it: ``None`` factors
        whichever sign is positive definite.

    Returns
    -------
    SparseCholesky
        The factorization of ``matrix``.

    Raises
    ------
    ValueError
        If ``matrix`` is not ``(2 * n, 2 * n)`` scalar ``float64``, stores fewer entries than
        the expanded pattern, or the factorization's peak device memory would exceed
        [`CHOLESKY_MEMORY_BUDGET`][ordito.cholesky.CHOLESKY_MEMORY_BUDGET].
    NotPositiveDefiniteError
        If the operator (with ``negated=None``: either sign of it) is not positive definite.
    RuntimeError
        If ``matrix`` is not on this factorization's device.

    Examples
    --------
    The vector heat system is stored over the scalar heat system's pattern, by blocks:

    ```python
    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    vector_system, scalar_operators = od.heat.vector_heat_operators(vertices, faces)[:2]
    heat = od.cholesky.sparse_cholesky(scalar_operators[0], vertices, expandable=True)
    tangent = heat.with_expanded_operator(od.array.scalar_expansion(vector_system))
    print(heat.n, tangent.n)  # 162 324
    ```
    """
    require_same_device(matrix=matrix, factor=self)
    self._require_pattern(matrix, "with_expanded_operator", expanded=True)
    plan = _analyse(matrix, None, None, expanding=self._plan)
    assert isinstance(plan, _Plan)
    return _factored(plan, matrix, negated, analysed=True)

solve

solve(
    rhs: ArrayNd,
    solution: ArrayNd,
    *,
    tol: float = 1e-12,
    componentwise: bool = False,
    refine: bool = True,
) -> None

Solve the factored system for one or several right-hand sides, refined in float64.

Parameters:

Name Type Description Default
rhs ArrayNd

(n,) right-hand side, or (n_columns, n) float64 columns solved together.

required
solution ArrayNd

Same shape as rhs: the initial guess, overwritten with the answer. Refinement starts from it, so a guess that already passes tol costs one residual and no triangular solve; on a singular component it supplies the constant (see the module notes). Ignored with refine=False, which starts from zero.

required
tol float

Refinement stops once every row's residual passes the backward-error test |b - A x|_i <= tol * max(s_i, max_j |b_j|), with s_i = (|A| |x| + |b|)_i the row's Oettli-Prager scale and max_j |b_j| the column's largest right-hand-side entry -- or, with componentwise, |b - A x|_i <= tol * s_i. A row dropped to pin a singular component is exempt; a residual that is not a number never passes. At most CHOLESKY_REFINE_ROUNDS refinement solves run: a solution still failing the test then is returned as it stands, without a warning.

1e-12
componentwise bool

Refine every entry to its own size: for solutions spanning many orders of magnitude.

False
refine bool

False solves once against the factor alone, from a zero guess, with no residual test (tol and componentwise are then not read): the refined solve's first round, for a caller whose own iteration absorbs the factor's rounding, such as a descent that only needs a direction. On a singular component the constant is then zero's.

True

Raises:

Type Description
ValueError

If rhs or solution is not float64 of a matching shape.

RuntimeError

If rhs and solution are not on this factorization's device, or the last refactor raised, leaving no factor.

Examples:

Two right-hand sides solved together: (M - t L) c = c M 1 for a constant c:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
factor = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces)[0], vertices)
mass = od.laplacian.mass_matrix_entries(vertices, faces, dtype=wp.float64).numpy()
rhs = wp.array(np.stack([mass, 2.0 * mass]), dtype=wp.float64)
solution = wp.zeros_like(rhs)
factor.solve(rhs, solution)
print(solution.numpy().mean(axis=1).round(6))  # [1. 2.]
Source code in ordito/cholesky.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def solve(
    self,
    rhs: odt.ArrayNd,
    solution: odt.ArrayNd,
    *,
    tol: float = 1e-12,
    componentwise: bool = False,
    refine: bool = True,
) -> None:
    """
    Solve the factored system for one or several right-hand sides, refined in ``float64``.

    Parameters
    ----------
    rhs
        ``(n,)`` right-hand side, or ``(n_columns, n)`` ``float64`` columns solved together.
    solution
        Same shape as ``rhs``: the initial guess, overwritten with the answer. Refinement
        starts from it, so a guess that already passes ``tol`` costs one residual and no
        triangular solve; on a singular component it supplies the constant (see the module
        notes). Ignored with ``refine=False``, which starts from zero.
    tol
        Refinement stops once every row's residual passes the backward-error test
        ``|b - A x|_i <= tol * max(s_i, max_j |b_j|)``, with ``s_i = (|A| |x| + |b|)_i`` the
        row's Oettli-Prager scale and ``max_j |b_j|`` the column's largest right-hand-side
        entry -- or, with ``componentwise``, ``|b - A x|_i <= tol * s_i``. A row dropped to
        pin a singular component is exempt; a residual that is not a number never passes.
        At most [`CHOLESKY_REFINE_ROUNDS`][ordito.cholesky.CHOLESKY_REFINE_ROUNDS]
        refinement solves run: a solution still failing the test then is returned as it
        stands, without a warning.
    componentwise
        Refine every entry to its own size: for solutions spanning many orders of magnitude.
    refine
        ``False`` solves once against the factor alone, from a zero guess, with no residual
        test (``tol`` and ``componentwise`` are then not read): the refined solve's first
        round, for a caller whose own iteration absorbs the factor's rounding, such as a
        descent that only needs a direction. On a singular component the constant is then
        zero's.

    Raises
    ------
    ValueError
        If ``rhs`` or ``solution`` is not ``float64`` of a matching shape.
    RuntimeError
        If ``rhs`` and ``solution`` are not on this factorization's device, or the last
        [`refactor`][ordito.cholesky.SparseCholesky.refactor] raised, leaving no factor.

    Examples
    --------
    Two right-hand sides solved together: ``(M - t L) c = c M 1`` for a constant ``c``:

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

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    factor = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces)[0], vertices)
    mass = od.laplacian.mass_matrix_entries(vertices, faces, dtype=wp.float64).numpy()
    rhs = wp.array(np.stack([mass, 2.0 * mass]), dtype=wp.float64)
    solution = wp.zeros_like(rhs)
    factor.solve(rhs, solution)
    print(solution.numpy().mean(axis=1).round(6))  # [1. 2.]
    ```
    """
    require_same_device(rhs=rhs, solution=solution, factor=self)
    if not self._valid:
        raise RuntimeError(
            "SparseCholesky.solve: the last refactor failed and left no factor; refactor "
            "with a positive definite operator first"
        )
    if rhs.dtype != wp.float64 or solution.dtype != wp.float64 or rhs.shape != solution.shape:
        raise ValueError("SparseCholesky.solve takes float64 rhs and solution of one shape")
    n_columns = 1 if rhs.ndim == 1 else int(rhs.shape[0])
    if int(rhs.shape[-1]) != self.n:
        raise ValueError(
            f"SparseCholesky.solve: rhs has {rhs.shape[-1]} rows, expected {self.n}"
        )
    if self.n == 0 or n_columns == 0:
        return
    key = (n_columns, float(tol), bool(componentwise), bool(refine))
    solve = self._solves.get(n_columns)
    if solve is None or solve.key != key:
        plan = self._plan
        solve_nbytes = _solve_nbytes(
            n_columns,
            plan.n,
            plan.n_forward_parts,
            plan.n_backward_parts,
            plan.n_pairs,
            plan.chunk_bound,
            plan.n_components,
        )
        if solve is not None:
            self.nbytes -= solve_nbytes
        solve = _Solve(
            self._plan,
            self._numeric,
            self._matrix,
            n_columns,
            float(tol),
            bool(componentwise),
            -1.0 if self.negated else 1.0,
            refine=bool(refine),
        )
        self._solves[n_columns] = solve
        self.nbytes += solve_nbytes
    solve.run(rhs.flatten(), solution.flatten(), self.records_at_once)

sparse_cholesky

sparse_cholesky(
    matrix: BsrMatrix[float64],
    coordinates: array[vec3] | None = None,
    *,
    negated: bool | None = False,
    expandable: bool = False,
) -> SparseCholesky

Sparse Cholesky factorization of a symmetric positive-(semi-)definite float64 operator.

Orders the operator by nested dissection, factors it on the device and returns the factorization, whose solve answers any later right-hand side in a fixed number of device passes. The ordering and the symbolic analysis run on the device too, reading back a few small counts per level of the dissection. The analysis belongs to the returned factorization: refactor reuses it for another operator of the same pattern, and nothing is kept across calls.

Parameters:

Name Type Description Default
matrix BsrMatrix[float64]

(n, n) symmetric scalar float64 operator, positive definite apart from components whose rows all sum to zero (solved up to a constant, see the module notes). Its stored pattern must be symmetric too: where (i, j) is stored, so is (j, i).

required
coordinates array[vec3] | None

(n,) positions of the rows, for a geometric ordering: a mesh's vertices for a vertex operator. When None, the ordering is computed from the pattern alone.

None
negated bool | None

Factor -matrix instead, for a negative (semi-)definite operator such as cotmatrix; solves still answer matrix x = rhs. When None, factor whichever of matrix and -matrix is positive definite, over one analysis: the sign of the leading diagonal is tried first.

False
expandable bool

Order with leaves and merged tops of half CHOLESKY_LEAF_ROWS and CHOLESKY_TOP_ROWS rows, for a factorization whose with_expanded_operator will derive a 2 x 2 block expansion's analysis: doubled, its supernodes are then as fine as an ordering of the expansion's own rows.

False

Returns:

Type Description
SparseCholesky

The factorization, on matrix.device.

Raises:

Type Description
ValueError

If matrix is not square scalar float64, its stored pattern is not symmetric, coordinates does not have n rows, or the factorization's peak device memory would exceed CHOLESKY_MEMORY_BUDGET.

NotPositiveDefiniteError

If the operator is not positive definite (with negated=None: neither sign is).

RuntimeError

If matrix and coordinates are not on one device.

See Also

SparseCholesky solve_spd

Examples:

The heat method's system M - t L maps the constant 1 to the lumped masses, since every row of L sums to zero; solving against the masses recovers it:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
system = od.heat.heat_operators(vertices, faces)[0]  # M - t L, float64
factor = od.cholesky.sparse_cholesky(system, vertices)
mass = od.laplacian.mass_matrix_entries(vertices, faces, dtype=wp.float64)
solution = wp.zeros_like(mass)
factor.solve(mass, solution)
print(f"{solution.numpy().min():.6f} {solution.numpy().max():.6f}")  # 1.000000 1.000000

A cotangent Laplacian is negative semi-definite: negated=None finds the sign, and the singular constant component is solved up to a constant:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(6, 6))
L = od.laplacian.cotmatrix(vertices, faces, dtype=wp.float64)
factor = od.cholesky.sparse_cholesky(L, vertices, negated=None)
print(factor.negated)  # True
x = wp.array(vertices.numpy()[:, 0], dtype=wp.float64)
solution = wp.zeros_like(x)
factor.solve(L @ x, solution)
print(np.ptp(solution.numpy() - x.numpy()) < 1e-9)  # True
Source code in ordito/cholesky.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def sparse_cholesky(
    matrix: odt.BsrMatrix[wp.float64],
    coordinates: wp.array[wp.vec3] | None = None,
    *,
    negated: bool | None = False,
    expandable: bool = False,
) -> SparseCholesky:
    """
    Sparse Cholesky factorization of a symmetric positive-(semi-)definite ``float64`` operator.

    Orders the operator by nested dissection, factors it on the device and returns the
    factorization, whose [`solve`][ordito.cholesky.SparseCholesky.solve] answers any later
    right-hand side in a fixed number of device passes. The ordering and the symbolic analysis run
    on the device too, reading back a few small counts per level of the dissection. The analysis
    belongs to the returned factorization: [`refactor`][ordito.cholesky.SparseCholesky.refactor]
    reuses it for another operator of the same pattern, and nothing is kept across calls.

    Parameters
    ----------
    matrix
        ``(n, n)`` symmetric scalar ``float64`` operator, positive definite apart from components
        whose rows all sum to zero (solved up to a constant, see the module notes). Its stored
        pattern must be symmetric too: where ``(i, j)`` is stored, so is ``(j, i)``.
    coordinates
        ``(n,)`` positions of the rows, for a geometric ordering: a mesh's vertices for a vertex
        operator. When ``None``, the ordering is computed from the pattern alone.
    negated
        Factor ``-matrix`` instead, for a negative (semi-)definite operator such as
        [`cotmatrix`][ordito.laplacian.cotmatrix]; solves still answer ``matrix x = rhs``. When
        ``None``, factor whichever of ``matrix`` and ``-matrix`` is positive definite, over one
        analysis: the sign of the leading diagonal is tried first.
    expandable
        Order with leaves and merged tops of half
        [`CHOLESKY_LEAF_ROWS`][ordito.cholesky.CHOLESKY_LEAF_ROWS] and
        [`CHOLESKY_TOP_ROWS`][ordito.cholesky.CHOLESKY_TOP_ROWS] rows, for a factorization whose
        [`with_expanded_operator`][ordito.cholesky.SparseCholesky.with_expanded_operator] will
        derive a 2 x 2 block expansion's analysis: doubled, its supernodes are then as fine as an
        ordering of the expansion's own rows.

    Returns
    -------
    SparseCholesky
        The factorization, on ``matrix.device``.

    Raises
    ------
    ValueError
        If ``matrix`` is not square scalar ``float64``, its stored pattern is not symmetric,
        ``coordinates`` does not have ``n`` rows, or the factorization's peak device memory would
        exceed [`CHOLESKY_MEMORY_BUDGET`][ordito.cholesky.CHOLESKY_MEMORY_BUDGET].
    NotPositiveDefiniteError
        If the operator is not positive definite (with ``negated=None``: neither sign is).
    RuntimeError
        If ``matrix`` and ``coordinates`` are not on one device.

    See Also
    --------
    [`SparseCholesky`][ordito.cholesky.SparseCholesky]
    [`solve_spd`][ordito.linalg.solve_spd]

    Examples
    --------
    The heat method's system ``M - t L`` maps the constant ``1`` to the lumped masses, since every
    row of ``L`` sums to zero; solving against the masses recovers it:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    system = od.heat.heat_operators(vertices, faces)[0]  # M - t L, float64
    factor = od.cholesky.sparse_cholesky(system, vertices)
    mass = od.laplacian.mass_matrix_entries(vertices, faces, dtype=wp.float64)
    solution = wp.zeros_like(mass)
    factor.solve(mass, solution)
    print(f"{solution.numpy().min():.6f} {solution.numpy().max():.6f}")  # 1.000000 1.000000
    ```

    A cotangent Laplacian is negative semi-definite: ``negated=None`` finds the sign, and the
    singular constant component is solved up to a constant:

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

    import ordito as od

    vertices, faces = od.creation.grid(count=(6, 6))
    L = od.laplacian.cotmatrix(vertices, faces, dtype=wp.float64)
    factor = od.cholesky.sparse_cholesky(L, vertices, negated=None)
    print(factor.negated)  # True
    x = wp.array(vertices.numpy()[:, 0], dtype=wp.float64)
    solution = wp.zeros_like(x)
    factor.solve(L @ x, solution)
    print(np.ptp(solution.numpy() - x.numpy()) < 1e-9)  # True
    ```
    """
    require_same_device(matrix=matrix, coordinates=coordinates)
    granularity = 2 if expandable else 1
    plan = _plan_cholesky(matrix, coordinates, granularity=granularity)
    return _factored(plan, matrix, negated, analysed=True)

held_nbytes

held_nbytes(
    factorizations: Iterable[SparseCholesky],
) -> int

Device memory several factorizations hold together, in bytes: a shared analysis counted once.

Each factorization's nbytes counts its analysis, which every factorization built from it by with_operator holds too; summing nbytes counts that analysis once a factorization.

Parameters:

Name Type Description Default
factorizations Iterable[SparseCholesky]

The factorizations, each counted once however often it appears.

required

Returns:

Type Description
int

The bytes of every distinct allocation the factorizations hold.

Examples:

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
short = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces, t=0.01)[0])
long = short.with_operator(od.heat.heat_operators(vertices, faces, t=0.1)[0])
together = od.cholesky.held_nbytes([short, long])
print(short.nbytes < together < short.nbytes + long.nbytes)  # True
Source code in ordito/cholesky.py
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def held_nbytes(factorizations: Iterable[SparseCholesky]) -> int:
    """
    Device memory several factorizations hold together, in bytes: a shared analysis counted once.

    Each factorization's [`nbytes`][ordito.cholesky.SparseCholesky] counts its analysis, which
    every factorization built from it by
    [`with_operator`][ordito.cholesky.SparseCholesky.with_operator] holds too; summing ``nbytes``
    counts that analysis once a factorization.

    Parameters
    ----------
    factorizations
        The factorizations, each counted once however often it appears.

    Returns
    -------
    int
        The bytes of every distinct allocation the factorizations hold.

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

    vertices, faces = od.creation.icosphere(subdivisions=2)
    short = od.cholesky.sparse_cholesky(od.heat.heat_operators(vertices, faces, t=0.01)[0])
    long = short.with_operator(od.heat.heat_operators(vertices, faces, t=0.1)[0])
    together = od.cholesky.held_nbytes([short, long])
    print(short.nbytes < together < short.nbytes + long.nbytes)  # True
    ```
    """
    analyses: dict[int, int] = {}
    own = 0
    for factor in {id(factor): factor for factor in factorizations}.values():
        # The analysis is this module's own state of a factorization.
        plan = factor._plan  # pyright: ignore[reportPrivateUsage]
        analyses[id(plan)] = plan.nbytes
        own += factor.nbytes - plan.nbytes
    return own + sum(analyses.values())

factorization_nbytes

factorization_nbytes(
    matrix: BsrMatrix[float64],
    coordinates: array[vec3] | None = None,
) -> int

Peak device memory sparse_cholesky would take, in bytes.

What the factorization holds once built plus the transient arena its first numeric factorization works in (or a first solve's scratch, when that is larger): the figure sparse_cholesky compares with CHOLESKY_MEMORY_BUDGET. Found by the ordering and the symbolic analysis alone, which stop there, so asking costs most of an analysis and no factorization, and is answered whatever the budget.

Parameters:

Name Type Description Default
matrix BsrMatrix[float64]

(n, n) symmetric scalar float64 operator, as sparse_cholesky takes it.

required
coordinates array[vec3] | None

(n,) positions of the rows for the ordering, as sparse_cholesky takes them.

None

Returns:

Type Description
int

The bytes; sparse_cholesky refuses the operator exactly when this exceeds CHOLESKY_MEMORY_BUDGET.

Raises:

Type Description
ValueError

If matrix is not square scalar float64, or coordinates does not have n rows.

RuntimeError

If matrix and coordinates are not on one device.

See Also

sparse_cholesky

Examples:

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=3)
system = od.heat.heat_operators(vertices, faces)[0]  # M - t L, float64
needed = od.cholesky.factorization_nbytes(system, vertices)
print(needed < od.cholesky.CHOLESKY_MEMORY_BUDGET)  # True
Source code in ordito/cholesky.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def factorization_nbytes(
    matrix: odt.BsrMatrix[wp.float64], coordinates: wp.array[wp.vec3] | None = None
) -> int:
    """
    Peak device memory [`sparse_cholesky`][ordito.cholesky.sparse_cholesky] would take, in bytes.

    What the factorization holds once built plus the transient arena its first numeric
    factorization works in (or a first solve's scratch, when that is larger): the figure
    ``sparse_cholesky`` compares with
    [`CHOLESKY_MEMORY_BUDGET`][ordito.cholesky.CHOLESKY_MEMORY_BUDGET]. Found by the ordering and
    the symbolic analysis alone, which stop there, so asking costs most of an analysis and no
    factorization, and is answered whatever the budget.

    Parameters
    ----------
    matrix
        ``(n, n)`` symmetric scalar ``float64`` operator, as ``sparse_cholesky`` takes it.
    coordinates
        ``(n,)`` positions of the rows for the ordering, as ``sparse_cholesky`` takes them.

    Returns
    -------
    int
        The bytes; ``sparse_cholesky`` refuses the operator exactly when this exceeds
        ``CHOLESKY_MEMORY_BUDGET``.

    Raises
    ------
    ValueError
        If ``matrix`` is not square scalar ``float64``, or ``coordinates`` does not have ``n``
        rows.
    RuntimeError
        If ``matrix`` and ``coordinates`` are not on one device.

    See Also
    --------
    [`sparse_cholesky`][ordito.cholesky.sparse_cholesky]

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

    vertices, faces = od.creation.icosphere(subdivisions=3)
    system = od.heat.heat_operators(vertices, faces)[0]  # M - t L, float64
    needed = od.cholesky.factorization_nbytes(system, vertices)
    print(needed < od.cholesky.CHOLESKY_MEMORY_BUDGET)  # True
    ```
    """
    require_same_device(matrix=matrix, coordinates=coordinates)
    return _plan_cholesky(matrix, coordinates, probe=True)