Skip to content

panchi.algorithms

from panchi.algorithms import ref, rref, lu, qr_decomposition, svd
from panchi.algorithms import RowSwap, RowScale, RowAdd
from panchi.algorithms import Reduction, LUDecomposition, QRDecomposition
from panchi.algorithms import InverseResult, Solution, EigenResult, QREigenResult
from panchi.algorithms import SVDResult, JacobiSweep, JacobiRotation
from panchi.algorithms import inverse, solve, determinant
from panchi.algorithms import cofactor_expansion, determinant_by_reduction, adjugate, cramer
from panchi.algorithms import eigen, characteristic_polynomial, eigen_qr
from panchi.algorithms import rank, nullity, is_invertible, is_symmetric
from panchi.algorithms import span, standard_basis, column_space, row_space, null_space
from panchi.algorithms import dot, cross, orthogonal_complement
from panchi.algorithms import gram_schmidt, vector_projection

Row operations

panchi.algorithms.RowSwap

Bases: RowOperation

Elementary row operation: swap two rows.

Represents the operation R_a <-> R_b. The corresponding elementary matrix is the identity matrix with rows a and b exchanged.

Applying this operation twice returns the original matrix.

Parameters:

Name Type Description Default
row_a int

Index of the first row to swap (0-based).

required
row_b int

Index of the second row to swap (0-based).

required

Examples:

>>> m = Matrix([[1, 2], [3, 4], [5, 6]])
>>> op = RowSwap(0, 2)
>>> print(op.apply(m))
[[5, 6],
 [3, 4],
 [1, 2]]
>>> v = Vector([1, 2, 3])
>>> print(op.apply(v))
[3, 2, 1]
>>> print(op.elementary_matrix(3))
[[0, 0, 1],
 [0, 1, 0],
 [1, 0, 0]]
>>> print(op)
R0 <-> R2
>>> repr(op)
'RowSwap(row_a=0, row_b=2)'
Source code in panchi/algorithms/row_operations.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
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
class RowSwap(RowOperation):
    """
    Elementary row operation: swap two rows.

    Represents the operation R_a <-> R_b. The corresponding elementary
    matrix is the identity matrix with rows a and b exchanged.

    Applying this operation twice returns the original matrix.

    Parameters
    ----------
    row_a : int
        Index of the first row to swap (0-based).
    row_b : int
        Index of the second row to swap (0-based).

    Examples
    --------
    >>> m = Matrix([[1, 2], [3, 4], [5, 6]])
    >>> op = RowSwap(0, 2)
    >>> print(op.apply(m))
    [[5, 6],
     [3, 4],
     [1, 2]]
    >>> v = Vector([1, 2, 3])
    >>> print(op.apply(v))
    [3, 2, 1]
    >>> print(op.elementary_matrix(3))
    [[0, 0, 1],
     [0, 1, 0],
     [1, 0, 0]]
    >>> print(op)
    R0 <-> R2
    >>> repr(op)
    'RowSwap(row_a=0, row_b=2)'
    """

    def __init__(self, row_a: int, row_b: int) -> None:
        self.a = row_a
        self.b = row_b
        self._validate_index_type(self.a, "row_a")
        self._validate_index_type(self.b, "row_b")

    def _validate_indices(self, n: int) -> None:
        self._validate_in_range(self.a, n)
        self._validate_in_range(self.b, n)

    def elementary_matrix(self, n: int) -> Matrix:
        """
        Return the n×n elementary matrix for this row swap.

        Constructed by swapping rows a and b in the n×n identity matrix.
        This matrix has determinant -1, reflecting that row swaps reverse
        the orientation of the row space.

        Parameters
        ----------
        n : int
            Size of the elementary matrix. Must be at least 1, and large
            enough so that both row indices are in range.

        Returns
        -------
        Matrix
            An n×n matrix identical to the identity except that rows a
            and b are exchanged.

        Raises
        ------
        TypeError
            If n is not an integer.
        ValueError
            If n < 2 or either row index is out of range for n.

        Examples
        --------
        >>> op = RowSwap(0, 1)
        >>> print(op.elementary_matrix(3))
        [[0, 1, 0],
         [1, 0, 0],
         [0, 0, 1]]
        """
        self._validate_n(n)
        self._validate_indices(n)

        grid: Matrix = identity(n)
        row_a: list[Scalar] = grid[self.a].copy()
        row_b: list[Scalar] = grid[self.b].copy()
        grid[self.a] = row_b
        grid[self.b] = row_a

        return grid

    def _apply_vector(self, vector: Vector) -> Vector:
        result = vector.copy()
        result[self.a], result[self.b] = vector[self.b], vector[self.a]
        return result

    def inverse(self) -> RowSwap:
        """
        Return the inverse of this row swap.

        A row swap is its own inverse: swapping the same two rows a second
        time restores the original matrix.

        Returns
        -------
        RowSwap
            A new RowSwap with the same row indices.

        Examples
        --------
        >>> op = RowSwap(0, 2)
        >>> op.inverse()
        RowSwap(row_a=0, row_b=2)
        """
        return RowSwap(self.a, self.b)

    def __str__(self) -> str:
        return f"R{self.a} <-> R{self.b}"

    def __repr__(self) -> str:
        return f"RowSwap(row_a={self.a}, row_b={self.b})"

    def _latex(self) -> str:
        return f"R_{{{self.a}}} \\leftrightarrow R_{{{self.b}}}"

apply(target)

apply(target: Matrix) -> Matrix
apply(target: Vector) -> Vector

Apply this operation to a matrix or vector, returning the result.

Does not modify the input. When applied to a Matrix, the result satisfies:

apply(M) == elementary_matrix(M.rows) @ M

When applied to a Vector, the operation acts on the vector's components using the same row indices, treating the vector as a single-column matrix.

Parameters:

Name Type Description Default
target Matrix | Vector

The matrix or vector to operate on.

required

Returns:

Type Description
Matrix | Vector

A new Matrix or Vector with the operation applied. The return type matches the input type.

Raises:

Type Description
TypeError

If target is not a Matrix or Vector instance.

ValueError

If the operation's row indices are out of range for this target.

Examples:

>>> m = Matrix([[1, 2], [3, 4], [5, 6]])
>>> print(RowSwap(0, 2).apply(m))
[[5, 6],
 [3, 4],
 [1, 2]]
>>> print(RowAdd(target=1, source=0, scalar=-3).apply(Vector([2, 6])))
[2, 0]
Source code in panchi/algorithms/row_operations.py
43
44
45
46
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
def apply(self, target: Matrix | Vector) -> Matrix | Vector:
    """
    Apply this operation to a matrix or vector, returning the result.

    Does not modify the input. When applied to a Matrix, the result
    satisfies:

        apply(M) == elementary_matrix(M.rows) @ M

    When applied to a Vector, the operation acts on the vector's
    components using the same row indices, treating the vector as a
    single-column matrix.

    Parameters
    ----------
    target : Matrix | Vector
        The matrix or vector to operate on.

    Returns
    -------
    Matrix | Vector
        A new Matrix or Vector with the operation applied. The return
        type matches the input type.

    Raises
    ------
    TypeError
        If target is not a Matrix or Vector instance.
    ValueError
        If the operation's row indices are out of range for this target.

    Examples
    --------
    >>> m = Matrix([[1, 2], [3, 4], [5, 6]])
    >>> print(RowSwap(0, 2).apply(m))
    [[5, 6],
     [3, 4],
     [1, 2]]
    >>> print(RowAdd(target=1, source=0, scalar=-3).apply(Vector([2, 6])))
    [2, 0]
    """
    self._validate_target(target)
    n = target.dims if isinstance(target, Vector) else target.rows
    self._validate_indices(n)

    if isinstance(target, Vector):
        return self._apply_vector(target)

    return self.elementary_matrix(n) @ target

elementary_matrix(n)

Return the n×n elementary matrix for this row swap.

Constructed by swapping rows a and b in the n×n identity matrix. This matrix has determinant -1, reflecting that row swaps reverse the orientation of the row space.

Parameters:

Name Type Description Default
n int

Size of the elementary matrix. Must be at least 1, and large enough so that both row indices are in range.

required

Returns:

Type Description
Matrix

An n×n matrix identical to the identity except that rows a and b are exchanged.

Raises:

Type Description
TypeError

If n is not an integer.

ValueError

If n < 2 or either row index is out of range for n.

Examples:

>>> op = RowSwap(0, 1)
>>> print(op.elementary_matrix(3))
[[0, 1, 0],
 [1, 0, 0],
 [0, 0, 1]]
Source code in panchi/algorithms/row_operations.py
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
def elementary_matrix(self, n: int) -> Matrix:
    """
    Return the n×n elementary matrix for this row swap.

    Constructed by swapping rows a and b in the n×n identity matrix.
    This matrix has determinant -1, reflecting that row swaps reverse
    the orientation of the row space.

    Parameters
    ----------
    n : int
        Size of the elementary matrix. Must be at least 1, and large
        enough so that both row indices are in range.

    Returns
    -------
    Matrix
        An n×n matrix identical to the identity except that rows a
        and b are exchanged.

    Raises
    ------
    TypeError
        If n is not an integer.
    ValueError
        If n < 2 or either row index is out of range for n.

    Examples
    --------
    >>> op = RowSwap(0, 1)
    >>> print(op.elementary_matrix(3))
    [[0, 1, 0],
     [1, 0, 0],
     [0, 0, 1]]
    """
    self._validate_n(n)
    self._validate_indices(n)

    grid: Matrix = identity(n)
    row_a: list[Scalar] = grid[self.a].copy()
    row_b: list[Scalar] = grid[self.b].copy()
    grid[self.a] = row_b
    grid[self.b] = row_a

    return grid

inverse()

Return the inverse of this row swap.

A row swap is its own inverse: swapping the same two rows a second time restores the original matrix.

Returns:

Type Description
RowSwap

A new RowSwap with the same row indices.

Examples:

>>> op = RowSwap(0, 2)
>>> op.inverse()
RowSwap(row_a=0, row_b=2)
Source code in panchi/algorithms/row_operations.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def inverse(self) -> RowSwap:
    """
    Return the inverse of this row swap.

    A row swap is its own inverse: swapping the same two rows a second
    time restores the original matrix.

    Returns
    -------
    RowSwap
        A new RowSwap with the same row indices.

    Examples
    --------
    >>> op = RowSwap(0, 2)
    >>> op.inverse()
    RowSwap(row_a=0, row_b=2)
    """
    return RowSwap(self.a, self.b)

panchi.algorithms.RowScale

Bases: RowOperation

Elementary row operation: multiply a row by a non-zero scalar.

Represents the operation R_i -> scalar * R_i. The corresponding elementary matrix is the identity matrix with the diagonal entry at position [i, i] replaced by scalar.

Scaling a row by scalar multiplies the determinant of the matrix by scalar. To invert this operation, scale by 1 / scalar.

Parameters:

Name Type Description Default
row int

Index of the row to scale (0-based).

required
scalar int | float | Fraction

The non-zero value to multiply the row by.

required

Examples:

>>> m = Matrix([[1, 2], [3, 4]])
>>> op = RowScale(1, 3)
>>> print(op.apply(m))
[[1, 2],
 [9, 12]]
>>> v = Vector([1, 2])
>>> print(op.apply(v))
[1, 6]
>>> print(op.elementary_matrix(2))
[[1, 0],
 [0, 3]]
>>> print(op)
R1 -> 3 * R1
>>> repr(op)
'RowScale(row=1, scalar=3)'
Source code in panchi/algorithms/row_operations.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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
class RowScale(RowOperation):
    """
    Elementary row operation: multiply a row by a non-zero scalar.

    Represents the operation R_i -> scalar * R_i. The corresponding
    elementary matrix is the identity matrix with the diagonal entry
    at position [i, i] replaced by scalar.

    Scaling a row by scalar multiplies the determinant of the matrix
    by scalar. To invert this operation, scale by 1 / scalar.

    Parameters
    ----------
    row : int
        Index of the row to scale (0-based).
    scalar : int | float | Fraction
        The non-zero value to multiply the row by.

    Examples
    --------
    >>> m = Matrix([[1, 2], [3, 4]])
    >>> op = RowScale(1, 3)
    >>> print(op.apply(m))
    [[1, 2],
     [9, 12]]
    >>> v = Vector([1, 2])
    >>> print(op.apply(v))
    [1, 6]
    >>> print(op.elementary_matrix(2))
    [[1, 0],
     [0, 3]]
    >>> print(op)
    R1 -> 3 * R1
    >>> repr(op)
    'RowScale(row=1, scalar=3)'
    """

    def __init__(self, row: int, scalar: Scalar) -> None:
        self.row = row
        self.scalar = scalar
        self._validate_index_type(self.row)
        self._validate_scalar_type(self.scalar)
        if self.scalar == 0:
            raise ValueError(
                "Scalar must be non-zero. Scaling a row by zero would make "
                "the matrix singular and the operation non-invertible."
            )

    def _validate_indices(self, n: int) -> None:
        self._validate_in_range(self.row, n)

    def elementary_matrix(self, n: int) -> Matrix:
        """
        Return the n×n elementary matrix for this row scale.

        Constructed from the identity matrix with the diagonal entry at
        position [row, row] replaced by scalar.

        Parameters
        ----------
        n : int
            Size of the elementary matrix. Must be at least 1, and large
            enough so that the row index is in range.

        Returns
        -------
        Matrix
            An n×n matrix identical to the identity except that entry
            [row, row] equals scalar.

        Raises
        ------
        TypeError
            If n is not an integer.
        ValueError
            If n < 2 or the row index is out of range.

        Examples
        --------
        >>> op = RowScale(0, 5)
        >>> print(op.elementary_matrix(3))
        [[5, 0, 0],
         [0, 1, 0],
         [0, 0, 1]]
        """
        self._validate_n(n)
        self._validate_indices(n)

        grid: Matrix = identity(n)
        grid[self.row, self.row] = self.scalar

        return grid

    def _apply_vector(self, vector: Vector) -> Vector:
        result = vector.copy()
        result[self.row] = vector[self.row] * self.scalar
        return result

    def inverse(self) -> RowScale:
        """
        Return the inverse of this row scale.

        The inverse scales the same row by 1 / scalar, which restores
        the original values.

        Returns
        -------
        RowScale
            A new RowScale on the same row with scalar 1 / self.scalar.

        Examples
        --------
        >>> op = RowScale(1, 3)
        >>> op.inverse()
        RowScale(row=1, scalar=0.3333333333333333)
        """
        return RowScale(self.row, 1 / self.scalar)

    def __str__(self) -> str:
        return f"R{self.row} -> {self.scalar} * R{self.row}"

    def __repr__(self) -> str:
        return f"RowScale(row={self.row}, scalar={self.scalar})"

    def _latex(self) -> str:
        return (
            f"R_{{{self.row}}} \\to {scalar_to_latex(self.scalar)}\\,R_{{{self.row}}}"
        )

apply(target)

apply(target: Matrix) -> Matrix
apply(target: Vector) -> Vector

Apply this operation to a matrix or vector, returning the result.

Does not modify the input. When applied to a Matrix, the result satisfies:

apply(M) == elementary_matrix(M.rows) @ M

When applied to a Vector, the operation acts on the vector's components using the same row indices, treating the vector as a single-column matrix.

Parameters:

Name Type Description Default
target Matrix | Vector

The matrix or vector to operate on.

required

Returns:

Type Description
Matrix | Vector

A new Matrix or Vector with the operation applied. The return type matches the input type.

Raises:

Type Description
TypeError

If target is not a Matrix or Vector instance.

ValueError

If the operation's row indices are out of range for this target.

Examples:

>>> m = Matrix([[1, 2], [3, 4], [5, 6]])
>>> print(RowSwap(0, 2).apply(m))
[[5, 6],
 [3, 4],
 [1, 2]]
>>> print(RowAdd(target=1, source=0, scalar=-3).apply(Vector([2, 6])))
[2, 0]
Source code in panchi/algorithms/row_operations.py
43
44
45
46
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
def apply(self, target: Matrix | Vector) -> Matrix | Vector:
    """
    Apply this operation to a matrix or vector, returning the result.

    Does not modify the input. When applied to a Matrix, the result
    satisfies:

        apply(M) == elementary_matrix(M.rows) @ M

    When applied to a Vector, the operation acts on the vector's
    components using the same row indices, treating the vector as a
    single-column matrix.

    Parameters
    ----------
    target : Matrix | Vector
        The matrix or vector to operate on.

    Returns
    -------
    Matrix | Vector
        A new Matrix or Vector with the operation applied. The return
        type matches the input type.

    Raises
    ------
    TypeError
        If target is not a Matrix or Vector instance.
    ValueError
        If the operation's row indices are out of range for this target.

    Examples
    --------
    >>> m = Matrix([[1, 2], [3, 4], [5, 6]])
    >>> print(RowSwap(0, 2).apply(m))
    [[5, 6],
     [3, 4],
     [1, 2]]
    >>> print(RowAdd(target=1, source=0, scalar=-3).apply(Vector([2, 6])))
    [2, 0]
    """
    self._validate_target(target)
    n = target.dims if isinstance(target, Vector) else target.rows
    self._validate_indices(n)

    if isinstance(target, Vector):
        return self._apply_vector(target)

    return self.elementary_matrix(n) @ target

elementary_matrix(n)

Return the n×n elementary matrix for this row scale.

Constructed from the identity matrix with the diagonal entry at position [row, row] replaced by scalar.

Parameters:

Name Type Description Default
n int

Size of the elementary matrix. Must be at least 1, and large enough so that the row index is in range.

required

Returns:

Type Description
Matrix

An n×n matrix identical to the identity except that entry [row, row] equals scalar.

Raises:

Type Description
TypeError

If n is not an integer.

ValueError

If n < 2 or the row index is out of range.

Examples:

>>> op = RowScale(0, 5)
>>> print(op.elementary_matrix(3))
[[5, 0, 0],
 [0, 1, 0],
 [0, 0, 1]]
Source code in panchi/algorithms/row_operations.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def elementary_matrix(self, n: int) -> Matrix:
    """
    Return the n×n elementary matrix for this row scale.

    Constructed from the identity matrix with the diagonal entry at
    position [row, row] replaced by scalar.

    Parameters
    ----------
    n : int
        Size of the elementary matrix. Must be at least 1, and large
        enough so that the row index is in range.

    Returns
    -------
    Matrix
        An n×n matrix identical to the identity except that entry
        [row, row] equals scalar.

    Raises
    ------
    TypeError
        If n is not an integer.
    ValueError
        If n < 2 or the row index is out of range.

    Examples
    --------
    >>> op = RowScale(0, 5)
    >>> print(op.elementary_matrix(3))
    [[5, 0, 0],
     [0, 1, 0],
     [0, 0, 1]]
    """
    self._validate_n(n)
    self._validate_indices(n)

    grid: Matrix = identity(n)
    grid[self.row, self.row] = self.scalar

    return grid

inverse()

Return the inverse of this row scale.

The inverse scales the same row by 1 / scalar, which restores the original values.

Returns:

Type Description
RowScale

A new RowScale on the same row with scalar 1 / self.scalar.

Examples:

>>> op = RowScale(1, 3)
>>> op.inverse()
RowScale(row=1, scalar=0.3333333333333333)
Source code in panchi/algorithms/row_operations.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def inverse(self) -> RowScale:
    """
    Return the inverse of this row scale.

    The inverse scales the same row by 1 / scalar, which restores
    the original values.

    Returns
    -------
    RowScale
        A new RowScale on the same row with scalar 1 / self.scalar.

    Examples
    --------
    >>> op = RowScale(1, 3)
    >>> op.inverse()
    RowScale(row=1, scalar=0.3333333333333333)
    """
    return RowScale(self.row, 1 / self.scalar)

panchi.algorithms.RowAdd

Bases: RowOperation

Elementary row operation: add a scalar multiple of one row to another.

Represents the operation R_target -> R_target + scalar * R_source. The corresponding elementary matrix is the identity with scalar placed at position [target, source].

This is the core operation of Gaussian elimination. When scalar is chosen to eliminate an entry, the result is a zero in position [target, source_col] of the transformed matrix.

The inverse of this operation is RowAdd(target, source, -scalar).

Parameters:

Name Type Description Default
target int

Index of the row being modified (0-based).

required
source int

Index of the row being added (0-based). Must differ from target.

required
scalar int | float | Fraction

The value to multiply the source row by before adding.

required

Examples:

>>> m = Matrix([[1, 2], [3, 4]])
>>> op = RowAdd(target=1, source=0, scalar=-3)
>>> print(op.apply(m))
[[1,  2],
 [0, -2]]
>>> v = Vector([1, 2])
>>> print(op.apply(v))
[1, -1]
>>> print(op.elementary_matrix(2))
[[1,  0],
 [-3, 1]]
>>> print(op)
R1 -> R1 + (-3) * R0
>>> repr(op)
'RowAdd(target=1, source=0, scalar=-3)'
Source code in panchi/algorithms/row_operations.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
class RowAdd(RowOperation):
    """
    Elementary row operation: add a scalar multiple of one row to another.

    Represents the operation R_target -> R_target + scalar * R_source.
    The corresponding elementary matrix is the identity with scalar placed
    at position [target, source].

    This is the core operation of Gaussian elimination. When scalar is
    chosen to eliminate an entry, the result is a zero in position
    [target, source_col] of the transformed matrix.

    The inverse of this operation is RowAdd(target, source, -scalar).

    Parameters
    ----------
    target : int
        Index of the row being modified (0-based).
    source : int
        Index of the row being added (0-based). Must differ from target.
    scalar : int | float | Fraction
        The value to multiply the source row by before adding.

    Examples
    --------
    >>> m = Matrix([[1, 2], [3, 4]])
    >>> op = RowAdd(target=1, source=0, scalar=-3)
    >>> print(op.apply(m))
    [[1,  2],
     [0, -2]]
    >>> v = Vector([1, 2])
    >>> print(op.apply(v))
    [1, -1]
    >>> print(op.elementary_matrix(2))
    [[1,  0],
     [-3, 1]]
    >>> print(op)
    R1 -> R1 + (-3) * R0
    >>> repr(op)
    'RowAdd(target=1, source=0, scalar=-3)'
    """

    def __init__(self, target: int, source: int, scalar: Scalar) -> None:
        self.target = target
        self.source = source
        self.scalar = scalar
        self._validate_index_type(self.target, "target")
        self._validate_index_type(self.source, "source")
        self._validate_scalar_type(self.scalar)

    def _validate_indices(self, n: int) -> None:
        self._validate_in_range(self.target, n, "Target row")
        self._validate_in_range(self.source, n, "Source row")

        if self.target == self.source:
            raise ValueError(
                f"Target and source rows must be different. Both are row {self.target}. "
                f"To scale a row, use RowScale instead."
            )

    def elementary_matrix(self, n: int) -> Matrix:
        """
        Return the n×n elementary matrix for this row addition.

        Constructed from the identity matrix with scalar placed at position
        [target, source]. This encodes the fact that left-multiplying by E
        replaces row target with row target plus scalar times row source.

        Parameters
        ----------
        n : int
            Size of the elementary matrix. Must be at least 1 and large
            enough so that both row indices are in range.

        Returns
        -------
        Matrix
            An n×n matrix identical to the identity except that entry
            [target, source] equals scalar.

        Raises
        ------
        TypeError
            If n is not an integer.
        ValueError
            If n < 2, indices are out of range, or target equals source.

        Examples
        --------
        >>> op = RowAdd(target=2, source=0, scalar=4)
        >>> print(op.elementary_matrix(3))
        [[1, 0, 0],
         [0, 1, 0],
         [4, 0, 1]]
        """
        self._validate_n(n)
        self._validate_indices(n)

        grid: Matrix = identity(n)
        grid[self.target, self.source] = self.scalar

        return grid

    def _apply_vector(self, vector: Vector) -> Vector:
        result = vector.copy()
        result[self.target] = vector[self.target] + self.scalar * vector[self.source]
        return result

    def inverse(self) -> RowAdd:
        """
        Return the inverse of this row addition.

        The inverse subtracts the same scalar multiple of the source row
        from the target row, which restores the original values.

        Returns
        -------
        RowAdd
            A new RowAdd with the same rows and negated scalar.

        Examples
        --------
        >>> op = RowAdd(target=1, source=0, scalar=-3)
        >>> op.inverse()
        RowAdd(target=1, source=0, scalar=3)
        """
        return RowAdd(self.target, self.source, -self.scalar)

    def __str__(self) -> str:
        return f"R{self.target} -> R{self.target} + ({self.scalar}) * R{self.source}"

    def __repr__(self) -> str:
        return (
            f"RowAdd(target={self.target}, source={self.source}, scalar={self.scalar})"
        )

    def _latex(self) -> str:
        return (
            f"R_{{{self.target}}} \\to R_{{{self.target}}} "
            f"+ ({scalar_to_latex(self.scalar)})\\,R_{{{self.source}}}"
        )

apply(target)

apply(target: Matrix) -> Matrix
apply(target: Vector) -> Vector

Apply this operation to a matrix or vector, returning the result.

Does not modify the input. When applied to a Matrix, the result satisfies:

apply(M) == elementary_matrix(M.rows) @ M

When applied to a Vector, the operation acts on the vector's components using the same row indices, treating the vector as a single-column matrix.

Parameters:

Name Type Description Default
target Matrix | Vector

The matrix or vector to operate on.

required

Returns:

Type Description
Matrix | Vector

A new Matrix or Vector with the operation applied. The return type matches the input type.

Raises:

Type Description
TypeError

If target is not a Matrix or Vector instance.

ValueError

If the operation's row indices are out of range for this target.

Examples:

>>> m = Matrix([[1, 2], [3, 4], [5, 6]])
>>> print(RowSwap(0, 2).apply(m))
[[5, 6],
 [3, 4],
 [1, 2]]
>>> print(RowAdd(target=1, source=0, scalar=-3).apply(Vector([2, 6])))
[2, 0]
Source code in panchi/algorithms/row_operations.py
43
44
45
46
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
def apply(self, target: Matrix | Vector) -> Matrix | Vector:
    """
    Apply this operation to a matrix or vector, returning the result.

    Does not modify the input. When applied to a Matrix, the result
    satisfies:

        apply(M) == elementary_matrix(M.rows) @ M

    When applied to a Vector, the operation acts on the vector's
    components using the same row indices, treating the vector as a
    single-column matrix.

    Parameters
    ----------
    target : Matrix | Vector
        The matrix or vector to operate on.

    Returns
    -------
    Matrix | Vector
        A new Matrix or Vector with the operation applied. The return
        type matches the input type.

    Raises
    ------
    TypeError
        If target is not a Matrix or Vector instance.
    ValueError
        If the operation's row indices are out of range for this target.

    Examples
    --------
    >>> m = Matrix([[1, 2], [3, 4], [5, 6]])
    >>> print(RowSwap(0, 2).apply(m))
    [[5, 6],
     [3, 4],
     [1, 2]]
    >>> print(RowAdd(target=1, source=0, scalar=-3).apply(Vector([2, 6])))
    [2, 0]
    """
    self._validate_target(target)
    n = target.dims if isinstance(target, Vector) else target.rows
    self._validate_indices(n)

    if isinstance(target, Vector):
        return self._apply_vector(target)

    return self.elementary_matrix(n) @ target

elementary_matrix(n)

Return the n×n elementary matrix for this row addition.

Constructed from the identity matrix with scalar placed at position [target, source]. This encodes the fact that left-multiplying by E replaces row target with row target plus scalar times row source.

Parameters:

Name Type Description Default
n int

Size of the elementary matrix. Must be at least 1 and large enough so that both row indices are in range.

required

Returns:

Type Description
Matrix

An n×n matrix identical to the identity except that entry [target, source] equals scalar.

Raises:

Type Description
TypeError

If n is not an integer.

ValueError

If n < 2, indices are out of range, or target equals source.

Examples:

>>> op = RowAdd(target=2, source=0, scalar=4)
>>> print(op.elementary_matrix(3))
[[1, 0, 0],
 [0, 1, 0],
 [4, 0, 1]]
Source code in panchi/algorithms/row_operations.py
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
def elementary_matrix(self, n: int) -> Matrix:
    """
    Return the n×n elementary matrix for this row addition.

    Constructed from the identity matrix with scalar placed at position
    [target, source]. This encodes the fact that left-multiplying by E
    replaces row target with row target plus scalar times row source.

    Parameters
    ----------
    n : int
        Size of the elementary matrix. Must be at least 1 and large
        enough so that both row indices are in range.

    Returns
    -------
    Matrix
        An n×n matrix identical to the identity except that entry
        [target, source] equals scalar.

    Raises
    ------
    TypeError
        If n is not an integer.
    ValueError
        If n < 2, indices are out of range, or target equals source.

    Examples
    --------
    >>> op = RowAdd(target=2, source=0, scalar=4)
    >>> print(op.elementary_matrix(3))
    [[1, 0, 0],
     [0, 1, 0],
     [4, 0, 1]]
    """
    self._validate_n(n)
    self._validate_indices(n)

    grid: Matrix = identity(n)
    grid[self.target, self.source] = self.scalar

    return grid

inverse()

Return the inverse of this row addition.

The inverse subtracts the same scalar multiple of the source row from the target row, which restores the original values.

Returns:

Type Description
RowAdd

A new RowAdd with the same rows and negated scalar.

Examples:

>>> op = RowAdd(target=1, source=0, scalar=-3)
>>> op.inverse()
RowAdd(target=1, source=0, scalar=3)
Source code in panchi/algorithms/row_operations.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
def inverse(self) -> RowAdd:
    """
    Return the inverse of this row addition.

    The inverse subtracts the same scalar multiple of the source row
    from the target row, which restores the original values.

    Returns
    -------
    RowAdd
        A new RowAdd with the same rows and negated scalar.

    Examples
    --------
    >>> op = RowAdd(target=1, source=0, scalar=-3)
    >>> op.inverse()
    RowAdd(target=1, source=0, scalar=3)
    """
    return RowAdd(self.target, self.source, -self.scalar)

Reductions

panchi.algorithms.ref(matrix, tolerance=0.0)

Reduce a matrix to row echelon form using Gaussian elimination.

Applies a sequence of elementary row operations to produce an upper triangular form where each pivot is to the right of the pivot in the row above it, and all entries below each pivot are zero. The pivot values are not normalised to 1.

Parameters:

Name Type Description Default
matrix Matrix

The matrix to reduce. Not modified by this function.

required
tolerance float

Column entries with magnitude at or below this value are treated as zero when selecting pivots, so a column with only near-zero entries becomes a free (non-pivot) column. The default of 0.0 means exact comparison and reproduces the standard exact reduction. A positive tolerance is useful for floating-point matrices that are only approximately rank-deficient (e.g. A - λI for an estimated λ).

0.0

Returns:

Type Description
Reduction

A Reduction object containing the original matrix, the REF result, the ordered list of row operations applied, the pivot positions as (row, col) tuples, and the form label 'REF'.

Examples:

>>> m = Matrix([[1, 2, 3], [2, 5, 7], [0, 1, 2]])
>>> reduction = ref(m)
>>> print(reduction.result)
[[1, 2, 3],
 [0, 1, 1],
 [0, 0, 1]]
>>> reduction.rank
3
>>> reduction.pivots
[(0, 0), (1, 1), (2, 2)]
Source code in panchi/algorithms/reductions.py
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
def ref(matrix: Matrix, tolerance: float = 0.0) -> Reduction:
    """
    Reduce a matrix to row echelon form using Gaussian elimination.

    Applies a sequence of elementary row operations to produce an upper
    triangular form where each pivot is to the right of the pivot in the
    row above it, and all entries below each pivot are zero. The pivot
    values are not normalised to 1.

    Parameters
    ----------
    matrix : Matrix
        The matrix to reduce. Not modified by this function.
    tolerance : float, optional
        Column entries with magnitude at or below this value are treated as
        zero when selecting pivots, so a column with only near-zero entries
        becomes a free (non-pivot) column. The default of 0.0 means exact
        comparison and reproduces the standard exact reduction. A positive
        tolerance is useful for floating-point matrices that are only
        approximately rank-deficient (e.g. A - λI for an estimated λ).

    Returns
    -------
    Reduction
        A Reduction object containing the original matrix, the REF result,
        the ordered list of row operations applied, the pivot positions as
        (row, col) tuples, and the form label 'REF'.

    Examples
    --------
    >>> m = Matrix([[1, 2, 3], [2, 5, 7], [0, 1, 2]])
    >>> reduction = ref(m)
    >>> print(reduction.result)
    [[1, 2, 3],
     [0, 1, 1],
     [0, 0, 1]]
    >>> reduction.rank
    3
    >>> reduction.pivots
    [(0, 0), (1, 1), (2, 2)]
    """
    result = matrix.copy()
    operations = []
    pivots = []
    i = 0
    for j in range(matrix.cols):
        if i >= matrix.rows:
            break
        result, swap_operations = _swap_pivot(i, j, result, tolerance)
        operations += swap_operations
        if abs(result[i][j]) <= tolerance:
            continue

        result, addition_operations = _add_below_pivot(i, j, result, tolerance)
        operations += addition_operations
        pivots.append((i, j))
        i += 1

    return Reduction(matrix, result, operations, pivots, "REF")

panchi.algorithms.rref(matrix, tolerance=0.0)

Reduce a matrix to reduced row echelon form using Gauss-Jordan elimination.

First reduces to REF via Gaussian elimination, then applies back-substitution to clear all entries above each pivot and scales each pivot row so that the pivot value equals 1. The result is unique for any given matrix.

Parameters:

Name Type Description Default
matrix Matrix

The matrix to reduce. Not modified by this function.

required
tolerance float

Entries with magnitude at or below this value are treated as zero when selecting pivots. The default of 0.0 means exact comparison. See ref() for when a positive tolerance is useful.

0.0

Returns:

Type Description
Reduction

A Reduction object containing the original matrix, the RREF result, the complete ordered list of row operations applied (including those from the initial REF step), the pivot positions as (row, col) tuples, and the form label 'RREF'.

Examples:

>>> m = Matrix([[1, 2, 3], [2, 5, 7], [0, 1, 2]])
>>> reduction = rref(m)
>>> print(reduction.result)
[[1, 0, 0],
 [0, 1, 0],
 [0, 0, 1]]
>>> reduction.rank
3
>>> reduction.nullity
0
Source code in panchi/algorithms/reductions.py
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
def rref(matrix: Matrix, tolerance: float = 0.0) -> Reduction:
    """
    Reduce a matrix to reduced row echelon form using Gauss-Jordan elimination.

    First reduces to REF via Gaussian elimination, then applies back-substitution
    to clear all entries above each pivot and scales each pivot row so that the
    pivot value equals 1. The result is unique for any given matrix.

    Parameters
    ----------
    matrix : Matrix
        The matrix to reduce. Not modified by this function.
    tolerance : float, optional
        Entries with magnitude at or below this value are treated as zero when
        selecting pivots. The default of 0.0 means exact comparison. See ref()
        for when a positive tolerance is useful.

    Returns
    -------
    Reduction
        A Reduction object containing the original matrix, the RREF result,
        the complete ordered list of row operations applied (including those
        from the initial REF step), the pivot positions as (row, col) tuples,
        and the form label 'RREF'.

    Examples
    --------
    >>> m = Matrix([[1, 2, 3], [2, 5, 7], [0, 1, 2]])
    >>> reduction = rref(m)
    >>> print(reduction.result)
    [[1, 0, 0],
     [0, 1, 0],
     [0, 0, 1]]
    >>> reduction.rank
    3
    >>> reduction.nullity
    0
    """
    gaussian_step = ref(matrix, tolerance)
    result = gaussian_step.result
    operations = gaussian_step.steps
    pivots = gaussian_step.pivots
    for i, j in pivots:
        result, scale_operations = _scale_pivot(i, j, result)
        operations += scale_operations
        result, addition_operations = _add_above_pivot(i, j, result, tolerance)
        operations += addition_operations

    return Reduction(matrix, result, operations, pivots, "RREF")

Decompositions

panchi.algorithms.lu(matrix)

Compute the LU decomposition of a square matrix, swapping rows as needed.

Factors the matrix into a lower triangular matrix L, an upper triangular matrix U, and a permutation matrix P such that P @ matrix == L @ U.

A row swap happens only when the current pivot is zero, using the first row below with a non-zero entry in the pivot column. This is not partial pivoting: a small non-zero pivot is kept. The swaps are recorded in P so the factorisation relationship holds exactly.

L is lower triangular with ones on the diagonal. Its off-diagonal entries are the elimination multipliers used during Gaussian elimination. U is the row echelon form of P @ matrix.

Parameters:

Name Type Description Default
matrix Matrix

The square matrix to decompose.

required

Returns:

Type Description
LUDecomposition

A result object containing the original matrix, L, U, P, and the ordered list of row operations applied during elimination.

Examples:

>>> A = Matrix([[2, 1], [4, 3]])
>>> decomp = lu(A)
>>> decomp.permutation @ A == decomp.lower @ decomp.upper
True
>>> print(decomp.lower)
[[1, 0],
 [2.0, 1]]
>>> print(decomp.upper)
[[2, 1],
 [0.0, 1.0]]
Source code in panchi/algorithms/decompositions.py
 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
def lu(matrix: Matrix) -> LUDecomposition:
    """
    Compute the LU decomposition of a square matrix, swapping rows as needed.

    Factors the matrix into a lower triangular matrix L, an upper triangular
    matrix U, and a permutation matrix P such that P @ matrix == L @ U.

    A row swap happens only when the current pivot is zero, using the first
    row below with a non-zero entry in the pivot column. This is not partial
    pivoting: a small non-zero pivot is kept. The swaps are recorded in P so
    the factorisation relationship holds exactly.

    L is lower triangular with ones on the diagonal. Its off-diagonal
    entries are the elimination multipliers used during Gaussian elimination.
    U is the row echelon form of P @ matrix.

    Parameters
    ----------
    matrix : Matrix
        The square matrix to decompose.

    Returns
    -------
    LUDecomposition
        A result object containing the original matrix, L, U, P, and the
        ordered list of row operations applied during elimination.

    Examples
    --------
    >>> A = Matrix([[2, 1], [4, 3]])
    >>> decomp = lu(A)
    >>> decomp.permutation @ A == decomp.lower @ decomp.upper
    True
    >>> print(decomp.lower)
    [[1, 0],
     [2.0, 1]]
    >>> print(decomp.upper)
    [[2, 1],
     [0.0, 1.0]]
    """
    matrix_ref = ref(matrix)
    n = matrix.rows
    steps = matrix_ref.steps
    l = _calculate_l(n, steps)
    u = matrix_ref.result
    p = _calculate_p(n, steps)
    return LUDecomposition(matrix, l, u, p, steps)

panchi.algorithms.qr_decomposition(matrix)

Compute the (thin) QR decomposition of a matrix.

Factors the matrix into a matrix Q with orthonormal columns and an upper triangular matrix R such that matrix == Q @ R. Q is built by applying Gram-Schmidt to the columns of the matrix, and R is recovered as Q.T @ matrix.

This is the reduced ("thin") QR decomposition and assumes the columns of the matrix are linearly independent. Dependent columns produce a zero orthogonal vector during Gram-Schmidt, which cannot be normalized and raises ZeroDivisionError.

Parameters:

Name Type Description Default
matrix Matrix

The matrix to decompose. Its columns are expected to be linearly independent.

required

Returns:

Type Description
QRDecomposition

A result object containing the original matrix, Q, R, and the ordered list of Gram-Schmidt steps used to build Q.

Raises:

Type Description
ZeroDivisionError

If the columns of the matrix are linearly dependent.

Examples:

>>> A = Matrix([[1, 0], [0, 1]])
>>> decomp = qr_decomposition(A)
>>> decomp.q @ decomp.r == A
True
Source code in panchi/algorithms/decompositions.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def qr_decomposition(matrix: Matrix) -> QRDecomposition:
    """
    Compute the (thin) QR decomposition of a matrix.

    Factors the matrix into a matrix Q with orthonormal columns and an
    upper triangular matrix R such that matrix == Q @ R. Q is built by
    applying Gram-Schmidt to the columns of the matrix, and R is recovered
    as Q.T @ matrix.

    This is the reduced ("thin") QR decomposition and assumes the columns
    of the matrix are linearly independent. Dependent columns produce a zero
    orthogonal vector during Gram-Schmidt, which cannot be normalized and
    raises ZeroDivisionError.

    Parameters
    ----------
    matrix : Matrix
        The matrix to decompose. Its columns are expected to be linearly
        independent.

    Returns
    -------
    QRDecomposition
        A result object containing the original matrix, Q, R, and the
        ordered list of Gram-Schmidt steps used to build Q.

    Raises
    ------
    ZeroDivisionError
        If the columns of the matrix are linearly dependent.

    Examples
    --------
    >>> A = Matrix([[1, 0], [0, 1]])
    >>> decomp = qr_decomposition(A)
    >>> decomp.q @ decomp.r == A
    True
    """
    steps = _gram_schmidt_steps(matrix.col_vectors)
    orthonormal_vectors = [step.orthonormal for step in steps]
    q = vector_column_matrix(orthonormal_vectors)
    r = q.T @ matrix
    return QRDecomposition(matrix, q, r, steps)

panchi.algorithms.svd(matrix, *, tolerance=1e-15, max_sweeps=60, record='sweeps')

Compute the (thin) singular value decomposition A = U Σ Vᵀ.

Uses one-sided Jacobi: pairs of columns of A are rotated until every pair is orthogonal. The rotations, collected into V, give A V = W with orthogonal columns wᵢ. Each singular value is σᵢ = ‖wᵢ‖ and each left singular vector is uᵢ = wᵢ / σᵢ. For a wide matrix (m < n) the algorithm runs on Aᵀ and swaps U and V.

With k = min(m, n), U is m×k with orthonormal columns, Σ is the k×k diagonal matrix of singular values in descending order, and V is n×k with orthonormal columns. The first entry of each column of V with absolute value above 1e-12 is positive. Columns of U for zero singular values are completed so that Uᵀ U = I always holds.

Parameters:

Name Type Description Default
matrix Matrix

The matrix to decompose. Entries are converted with float().

required
tolerance float

A column pair is rotated while |cos(angle between columns)| exceeds this value. Also sets the numerical rank threshold. Defaults to 1e-15.

1e-15
max_sweeps int

The maximum number of sweeps over all column pairs. Defaults to 60.

60
record str

How much history to keep in steps: "none", "sweeps" (one summary per sweep, the default) or "rotations" (every rotation, plus the working matrix after each sweep).

'sweeps'

Returns:

Type Description
SVDResult

The factors U, σ, V, the sweep history and helpers for rank-k approximation. If the sweeps do not converge, converged is False and the best factors found are returned.

Raises:

Type Description
TypeError

If matrix is not a Matrix, or an entry cannot be converted to float.

ValueError

If an entry is NaN or infinite, record is not a valid level, max_sweeps < 1, or tolerance <= 0.

See Also

qr_decomposition : Factor a matrix into orthonormal Q and triangular R. eigen_qr : Numerical eigenvalues via the QR algorithm.

Examples:

>>> result = svd(Matrix([[1, 1], [1, 1]]))
>>> [round(value, 10) for value in result.sigma]
[2.0, 0.0]
>>> result.rank
1
>>> product = result.u @ result.s @ result.vt
>>> [[round(x, 10) for x in row] for row in product.to_list()]
[[1.0, 1.0], [1.0, 1.0]]
Source code in panchi/algorithms/decompositions.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def svd(
    matrix: Matrix,
    *,
    tolerance: float = 1e-15,
    max_sweeps: int = 60,
    record: str = "sweeps",
) -> SVDResult:
    """
    Compute the (thin) singular value decomposition A = U Σ Vᵀ.

    Uses one-sided Jacobi: pairs of columns of A are rotated until every
    pair is orthogonal. The rotations, collected into V, give A V = W with
    orthogonal columns wᵢ. Each singular value is σᵢ = ‖wᵢ‖ and each left
    singular vector is uᵢ = wᵢ / σᵢ. For a wide matrix (m < n) the algorithm
    runs on Aᵀ and swaps U and V.

    With k = min(m, n), U is m×k with orthonormal columns, Σ is the k×k
    diagonal matrix of singular values in descending order, and V is n×k
    with orthonormal columns. The first entry of each column of V with
    absolute value above 1e-12 is positive. Columns of U for zero singular
    values are completed so that Uᵀ U = I always holds.

    Parameters
    ----------
    matrix : Matrix
        The matrix to decompose. Entries are converted with float().
    tolerance : float, optional
        A column pair is rotated while |cos(angle between columns)| exceeds
        this value. Also sets the numerical rank threshold. Defaults to 1e-15.
    max_sweeps : int, optional
        The maximum number of sweeps over all column pairs. Defaults to 60.
    record : str, optional
        How much history to keep in ``steps``: "none", "sweeps" (one summary
        per sweep, the default) or "rotations" (every rotation, plus the
        working matrix after each sweep).

    Returns
    -------
    SVDResult
        The factors U, σ, V, the sweep history and helpers for rank-k
        approximation. If the sweeps do not converge, ``converged`` is False
        and the best factors found are returned.

    Raises
    ------
    TypeError
        If matrix is not a Matrix, or an entry cannot be converted to float.
    ValueError
        If an entry is NaN or infinite, record is not a valid level,
        max_sweeps < 1, or tolerance <= 0.

    See Also
    --------
    qr_decomposition : Factor a matrix into orthonormal Q and triangular R.
    eigen_qr : Numerical eigenvalues via the QR algorithm.

    Examples
    --------
    >>> result = svd(Matrix([[1, 1], [1, 1]]))
    >>> [round(value, 10) for value in result.sigma]
    [2.0, 0.0]
    >>> result.rank
    1
    >>> product = result.u @ result.s @ result.vt
    >>> [[round(x, 10) for x in row] for row in product.to_list()]
    [[1.0, 1.0], [1.0, 1.0]]
    """
    if not isinstance(matrix, Matrix):
        raise TypeError(f"svd() requires a Matrix. Got {type(matrix).__name__}.")
    if record not in _RECORD_LEVELS:
        raise ValueError(
            f"record must be one of {', '.join(repr(r) for r in _RECORD_LEVELS)}. "
            f"Got {record!r}."
        )
    if isinstance(max_sweeps, bool) or not isinstance(max_sweeps, int):
        raise TypeError(f"max_sweeps must be an int. Got {type(max_sweeps).__name__}.")
    if max_sweeps < 1:
        raise ValueError(f"max_sweeps must be at least 1. Got {max_sweeps}.")
    if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):
        raise TypeError(f"tolerance must be a number. Got {type(tolerance).__name__}.")
    if not tolerance > 0:
        raise ValueError(f"tolerance must be positive. Got {tolerance}.")

    columns = _float_columns(matrix)
    transposed = matrix.rows < matrix.cols
    if transposed:
        columns = [list(row) for row in zip(*columns, strict=True)]

    work, v_columns, sweeps, converged, steps = _one_sided_jacobi(
        columns, tolerance, max_sweeps, record
    )

    norms = [math.sqrt(sum(x * x for x in column)) for column in work]
    order = sorted(range(len(work)), key=lambda j: norms[j], reverse=True)
    sigma = [norms[j] for j in order]
    rows = len(work[0])
    threshold = tolerance * sigma[0] * max(matrix.rows, matrix.cols)

    u_columns: list[list[float]] = []
    for position, j in enumerate(order):
        if sigma[position] > threshold:
            u_columns.append([x / sigma[position] for x in work[j]])
    u_columns += _complete_orthonormal(u_columns, rows, len(order) - len(u_columns))
    v_sorted = [v_columns[j] for j in order]

    if transposed:
        u_columns, v_sorted = v_sorted, u_columns

    for position, v_column in enumerate(v_sorted):
        leading = next((x for x in v_column if abs(x) > 1e-12), 0.0)
        if leading < 0:
            v_sorted[position] = [-x for x in v_column]
            u_columns[position] = [-x for x in u_columns[position]]

    u = _columns_to_matrix(u_columns)
    v = _columns_to_matrix(v_sorted)
    return SVDResult(matrix, u, sigma, v, sweeps, converged, steps, tolerance)

Eigenvalues

panchi.algorithms.eigen

characteristic_polynomial(matrix)

Compute the characteristic polynomial det(A - λI) exactly.

Uses the formulas taught for small matrices, written in terms of the trace and determinant:

  • 2×2: λ² - tr(A)·λ + det(A)
  • 3×3: -λ³ + tr(A)·λ² - (sum of principal 2×2 minors)·λ + det(A)

The principal 2×2 minors are the determinants left after deleting row i and column i, for each i.

Parameters:

Name Type Description Default
matrix Matrix

A 1×1, 2×2 or 3×3 matrix with int or Fraction entries.

required

Returns:

Type Description
Polynomial

The characteristic polynomial in λ. Its leading coefficient is (-1)ⁿ, so it is λ² + … for a 2×2 matrix and -λ³ + … for a 3×3.

Raises:

Type Description
TypeError

If matrix is not a Matrix, or has float or irrational entries.

ValueError

If matrix is not square or is larger than 3×3.

Examples:

>>> print(characteristic_polynomial(Matrix([[2, 1], [1, 2]])))
λ² - 4λ + 3
>>> print(characteristic_polynomial(Matrix([[2, 0, 0], [0, 3, 4], [0, 4, 9]])))
-λ³ + 14λ² - 35λ + 22
Source code in panchi/algorithms/eigen.py
 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
def characteristic_polynomial(matrix: Matrix) -> Polynomial:
    """
    Compute the characteristic polynomial det(A - λI) exactly.

    Uses the formulas taught for small matrices, written in terms of the
    trace and determinant:

    - 2×2: λ² - tr(A)·λ + det(A)
    - 3×3: -λ³ + tr(A)·λ² - (sum of principal 2×2 minors)·λ + det(A)

    The principal 2×2 minors are the determinants left after deleting row
    i and column i, for each i.

    Parameters
    ----------
    matrix : Matrix
        A 1×1, 2×2 or 3×3 matrix with int or Fraction entries.

    Returns
    -------
    Polynomial
        The characteristic polynomial in λ. Its leading coefficient is
        (-1)ⁿ, so it is λ² + … for a 2×2 matrix and -λ³ + … for a 3×3.

    Raises
    ------
    TypeError
        If matrix is not a Matrix, or has float or irrational entries.
    ValueError
        If matrix is not square or is larger than 3×3.

    Examples
    --------
    >>> print(characteristic_polynomial(Matrix([[2, 1], [1, 2]])))
    λ² - 4λ + 3
    >>> print(characteristic_polynomial(Matrix([[2, 0, 0], [0, 3, 4], [0, 4, 9]])))
    -λ³ + 14λ² - 35λ + 22
    """
    _validate_exact_small_square(matrix, "Characteristic polynomial")
    n = matrix.rows
    if n == 1:
        return Polynomial([matrix[0][0], -1])
    if n == 2:
        return Polynomial([determinant(matrix), -matrix.trace, 1])
    return Polynomial(
        [determinant(matrix), -_principal_minor_sum(matrix), matrix.trace, -1]
    )

eigen(matrix)

Compute the exact eigenvalues and eigenvectors of a 2×2 or 3×3 matrix.

Follows the method used by hand:

  1. Form the characteristic polynomial det(A - λI).
  2. Solve it exactly. Rational roots are found with the rational root theorem and divided out, and any quadratic left over is solved with the quadratic formula.
  3. For each eigenvalue λ, the eigenspace is the null space of A - λI, found by row reduction.

Answers are exact: irrational eigenvalues such as (1 + √5)/2 and complex ones such as 1 - 2i are QuadraticNumbers, and the eigenvectors are scaled so they contain no fractions.

Parameters:

Name Type Description Default
matrix Matrix

A 1×1, 2×2 or 3×3 matrix with int or Fraction entries.

required

Returns:

Type Description
EigenResult

The characteristic polynomial, the distinct eigenvalues with their algebraic multiplicities, and the eigenspaces.

Raises:

Type Description
TypeError

If matrix is not a Matrix, or has float or irrational entries.

ValueError

If matrix is not square, is larger than 3×3, or is a 3×3 matrix whose characteristic polynomial has no rational root (its eigenvalues then involve cube roots and cannot be written exactly as a + b√d).

See Also

eigen_qr : Numerical eigenvalues via the QR algorithm, for any size.

Examples:

>>> result = eigen(Matrix([[2, 1], [1, 2]]))
>>> result.eigenvalues
[1, 3]
>>> [str(v) for v in eigen(Matrix([[0, -1], [1, 0]])).eigenvalues]
['-i', 'i']
Source code in panchi/algorithms/eigen.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def eigen(matrix: Matrix) -> EigenResult:
    """
    Compute the exact eigenvalues and eigenvectors of a 2×2 or 3×3 matrix.

    Follows the method used by hand:

    1. Form the characteristic polynomial det(A - λI).
    2. Solve it exactly. Rational roots are found with the rational root
       theorem and divided out, and any quadratic left over is solved with
       the quadratic formula.
    3. For each eigenvalue λ, the eigenspace is the null space of A - λI,
       found by row reduction.

    Answers are exact: irrational eigenvalues such as (1 + √5)/2 and
    complex ones such as 1 - 2i are QuadraticNumbers, and the eigenvectors
    are scaled so they contain no fractions.

    Parameters
    ----------
    matrix : Matrix
        A 1×1, 2×2 or 3×3 matrix with int or Fraction entries.

    Returns
    -------
    EigenResult
        The characteristic polynomial, the distinct eigenvalues with their
        algebraic multiplicities, and the eigenspaces.

    Raises
    ------
    TypeError
        If matrix is not a Matrix, or has float or irrational entries.
    ValueError
        If matrix is not square, is larger than 3×3, or is a 3×3 matrix
        whose characteristic polynomial has no rational root (its
        eigenvalues then involve cube roots and cannot be written exactly
        as a + b√d).

    See Also
    --------
    eigen_qr : Numerical eigenvalues via the QR algorithm, for any size.

    Examples
    --------
    >>> result = eigen(Matrix([[2, 1], [1, 2]]))
    >>> result.eigenvalues
    [1, 3]
    >>> [str(v) for v in eigen(Matrix([[0, -1], [1, 0]])).eigenvalues]
    ['-i', 'i']
    """
    polynomial = characteristic_polynomial(matrix)
    try:
        roots = exact_roots(polynomial)
    except ValueError as error:
        raise ValueError(
            f"{error} Use eigen_qr() to approximate these eigenvalues numerically."
        ) from None

    n = matrix.rows
    exact = exact_matrix(matrix.to_list())
    eigenvalues = []
    multiplicities = []
    eigenspaces = []
    for value, multiplicity in roots:
        space = null_space(exact - value * identity(n))
        eigenvalues.append(value)
        multiplicities.append(multiplicity)
        eigenspaces.append(VectorSpace([_clear_denominators(v) for v in space]))
    return EigenResult(matrix, polynomial, eigenvalues, multiplicities, eigenspaces)

eigen_qr(matrix, max_iterations=1000, tolerance=1e-12)

Compute the eigenvalues of a square matrix using the QR algorithm.

Starting from the original matrix, repeatedly computes a QR decomposition and reassembles the matrix as R @ Q. For matrices with real eigenvalues this sequence converges to an upper triangular matrix whose diagonal entries are the eigenvalues.

The iteration stops once the strictly-below-diagonal entries sum to less than tolerance (recorded as converged), or once max_iterations is reached (recorded as not converged). Eigenvalues are the diagonal of the final iterate. Eigenvectors are computed separately and are only populated when the iteration converges.

Only real eigenvalues are supported. Matrices with complex eigenvalues or eigenvalues of equal magnitude may fail to converge, in which case the returned result has converged set to False and no eigenvectors.

Parameters:

Name Type Description Default
matrix Matrix

The square matrix whose eigenvalues will be computed.

required
max_iterations int

The maximum number of QR iterations to perform. Defaults to 1000.

1000
tolerance float

The convergence threshold on the below-diagonal mass. Defaults to 1e-12.

1e-12

Returns:

Type Description
QREigenResult

A result object containing the eigenvalues, eigenvectors, the number of iterations performed, whether the iteration converged, and the final (near) upper-triangular matrix.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance.

ValueError

If matrix is not square.

See Also

svd : Singular values via one-sided Jacobi, reliable for rank-deficient matrices.

Examples:

>>> result = eigen_qr(Matrix([[2, 1], [1, 2]]))
>>> sorted(round(v, 6) for v in result.eigenvalues)
[1.0, 3.0]
Source code in panchi/algorithms/eigen.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def eigen_qr(
    matrix: Matrix,
    max_iterations: int = 1000,
    tolerance: float = 1e-12,
) -> QREigenResult:
    """
    Compute the eigenvalues of a square matrix using the QR algorithm.

    Starting from the original matrix, repeatedly computes a QR
    decomposition and reassembles the matrix as R @ Q. For matrices with
    real eigenvalues this sequence converges to an upper triangular matrix
    whose diagonal entries are the eigenvalues.

    The iteration stops once the strictly-below-diagonal entries sum to less
    than ``tolerance`` (recorded as converged), or once ``max_iterations`` is
    reached (recorded as not converged). Eigenvalues are the diagonal of the
    final iterate. Eigenvectors are computed separately and are only
    populated when the iteration converges.

    Only real eigenvalues are supported. Matrices with complex eigenvalues
    or eigenvalues of equal magnitude may fail to converge, in which case the
    returned result has ``converged`` set to False and no eigenvectors.

    Parameters
    ----------
    matrix : Matrix
        The square matrix whose eigenvalues will be computed.
    max_iterations : int, optional
        The maximum number of QR iterations to perform. Defaults to 1000.
    tolerance : float, optional
        The convergence threshold on the below-diagonal mass. Defaults to
        1e-12.

    Returns
    -------
    QREigenResult
        A result object containing the eigenvalues, eigenvectors, the number
        of iterations performed, whether the iteration converged, and the
        final (near) upper-triangular matrix.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance.
    ValueError
        If matrix is not square.

    See Also
    --------
    svd : Singular values via one-sided Jacobi, reliable for rank-deficient
        matrices.

    Examples
    --------
    >>> result = eigen_qr(Matrix([[2, 1], [1, 2]]))
    >>> sorted(round(v, 6) for v in result.eigenvalues)
    [1.0, 3.0]
    """
    _require_square_matrix(matrix, "eigenvalues")

    n = matrix.rows
    current = matrix
    converged = False
    iterations = 0
    for iterations in range(1, max_iterations + 1):
        if _below_diagonal_mass(current) < tolerance:
            converged = True
            iterations -= 1
            break
        try:
            decomposition = qr_decomposition(current)
        except ZeroDivisionError:
            # A singular iterate cannot be orthonormalized by Gram-Schmidt;
            # treat this as failure to converge rather than crashing.
            break
        current = decomposition.r @ decomposition.q

    eigenvalues = [current[i][i] for i in range(n)]
    eigenvectors: list[Vector] = []
    if converged:
        for eigenvalue in eigenvalues:
            vector = _eigenvector(matrix, eigenvalue, n)
            if vector is not None:
                eigenvectors.append(vector)
    return QREigenResult(
        matrix, eigenvalues, eigenvectors, iterations, converged, current
    )

panchi.algorithms.characteristic_polynomial(matrix)

Compute the characteristic polynomial det(A - λI) exactly.

Uses the formulas taught for small matrices, written in terms of the trace and determinant:

  • 2×2: λ² - tr(A)·λ + det(A)
  • 3×3: -λ³ + tr(A)·λ² - (sum of principal 2×2 minors)·λ + det(A)

The principal 2×2 minors are the determinants left after deleting row i and column i, for each i.

Parameters:

Name Type Description Default
matrix Matrix

A 1×1, 2×2 or 3×3 matrix with int or Fraction entries.

required

Returns:

Type Description
Polynomial

The characteristic polynomial in λ. Its leading coefficient is (-1)ⁿ, so it is λ² + … for a 2×2 matrix and -λ³ + … for a 3×3.

Raises:

Type Description
TypeError

If matrix is not a Matrix, or has float or irrational entries.

ValueError

If matrix is not square or is larger than 3×3.

Examples:

>>> print(characteristic_polynomial(Matrix([[2, 1], [1, 2]])))
λ² - 4λ + 3
>>> print(characteristic_polynomial(Matrix([[2, 0, 0], [0, 3, 4], [0, 4, 9]])))
-λ³ + 14λ² - 35λ + 22
Source code in panchi/algorithms/eigen.py
 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
def characteristic_polynomial(matrix: Matrix) -> Polynomial:
    """
    Compute the characteristic polynomial det(A - λI) exactly.

    Uses the formulas taught for small matrices, written in terms of the
    trace and determinant:

    - 2×2: λ² - tr(A)·λ + det(A)
    - 3×3: -λ³ + tr(A)·λ² - (sum of principal 2×2 minors)·λ + det(A)

    The principal 2×2 minors are the determinants left after deleting row
    i and column i, for each i.

    Parameters
    ----------
    matrix : Matrix
        A 1×1, 2×2 or 3×3 matrix with int or Fraction entries.

    Returns
    -------
    Polynomial
        The characteristic polynomial in λ. Its leading coefficient is
        (-1)ⁿ, so it is λ² + … for a 2×2 matrix and -λ³ + … for a 3×3.

    Raises
    ------
    TypeError
        If matrix is not a Matrix, or has float or irrational entries.
    ValueError
        If matrix is not square or is larger than 3×3.

    Examples
    --------
    >>> print(characteristic_polynomial(Matrix([[2, 1], [1, 2]])))
    λ² - 4λ + 3
    >>> print(characteristic_polynomial(Matrix([[2, 0, 0], [0, 3, 4], [0, 4, 9]])))
    -λ³ + 14λ² - 35λ + 22
    """
    _validate_exact_small_square(matrix, "Characteristic polynomial")
    n = matrix.rows
    if n == 1:
        return Polynomial([matrix[0][0], -1])
    if n == 2:
        return Polynomial([determinant(matrix), -matrix.trace, 1])
    return Polynomial(
        [determinant(matrix), -_principal_minor_sum(matrix), matrix.trace, -1]
    )

panchi.algorithms.eigen_qr(matrix, max_iterations=1000, tolerance=1e-12)

Compute the eigenvalues of a square matrix using the QR algorithm.

Starting from the original matrix, repeatedly computes a QR decomposition and reassembles the matrix as R @ Q. For matrices with real eigenvalues this sequence converges to an upper triangular matrix whose diagonal entries are the eigenvalues.

The iteration stops once the strictly-below-diagonal entries sum to less than tolerance (recorded as converged), or once max_iterations is reached (recorded as not converged). Eigenvalues are the diagonal of the final iterate. Eigenvectors are computed separately and are only populated when the iteration converges.

Only real eigenvalues are supported. Matrices with complex eigenvalues or eigenvalues of equal magnitude may fail to converge, in which case the returned result has converged set to False and no eigenvectors.

Parameters:

Name Type Description Default
matrix Matrix

The square matrix whose eigenvalues will be computed.

required
max_iterations int

The maximum number of QR iterations to perform. Defaults to 1000.

1000
tolerance float

The convergence threshold on the below-diagonal mass. Defaults to 1e-12.

1e-12

Returns:

Type Description
QREigenResult

A result object containing the eigenvalues, eigenvectors, the number of iterations performed, whether the iteration converged, and the final (near) upper-triangular matrix.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance.

ValueError

If matrix is not square.

See Also

svd : Singular values via one-sided Jacobi, reliable for rank-deficient matrices.

Examples:

>>> result = eigen_qr(Matrix([[2, 1], [1, 2]]))
>>> sorted(round(v, 6) for v in result.eigenvalues)
[1.0, 3.0]
Source code in panchi/algorithms/eigen.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def eigen_qr(
    matrix: Matrix,
    max_iterations: int = 1000,
    tolerance: float = 1e-12,
) -> QREigenResult:
    """
    Compute the eigenvalues of a square matrix using the QR algorithm.

    Starting from the original matrix, repeatedly computes a QR
    decomposition and reassembles the matrix as R @ Q. For matrices with
    real eigenvalues this sequence converges to an upper triangular matrix
    whose diagonal entries are the eigenvalues.

    The iteration stops once the strictly-below-diagonal entries sum to less
    than ``tolerance`` (recorded as converged), or once ``max_iterations`` is
    reached (recorded as not converged). Eigenvalues are the diagonal of the
    final iterate. Eigenvectors are computed separately and are only
    populated when the iteration converges.

    Only real eigenvalues are supported. Matrices with complex eigenvalues
    or eigenvalues of equal magnitude may fail to converge, in which case the
    returned result has ``converged`` set to False and no eigenvectors.

    Parameters
    ----------
    matrix : Matrix
        The square matrix whose eigenvalues will be computed.
    max_iterations : int, optional
        The maximum number of QR iterations to perform. Defaults to 1000.
    tolerance : float, optional
        The convergence threshold on the below-diagonal mass. Defaults to
        1e-12.

    Returns
    -------
    QREigenResult
        A result object containing the eigenvalues, eigenvectors, the number
        of iterations performed, whether the iteration converged, and the
        final (near) upper-triangular matrix.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance.
    ValueError
        If matrix is not square.

    See Also
    --------
    svd : Singular values via one-sided Jacobi, reliable for rank-deficient
        matrices.

    Examples
    --------
    >>> result = eigen_qr(Matrix([[2, 1], [1, 2]]))
    >>> sorted(round(v, 6) for v in result.eigenvalues)
    [1.0, 3.0]
    """
    _require_square_matrix(matrix, "eigenvalues")

    n = matrix.rows
    current = matrix
    converged = False
    iterations = 0
    for iterations in range(1, max_iterations + 1):
        if _below_diagonal_mass(current) < tolerance:
            converged = True
            iterations -= 1
            break
        try:
            decomposition = qr_decomposition(current)
        except ZeroDivisionError:
            # A singular iterate cannot be orthonormalized by Gram-Schmidt;
            # treat this as failure to converge rather than crashing.
            break
        current = decomposition.r @ decomposition.q

    eigenvalues = [current[i][i] for i in range(n)]
    eigenvectors: list[Vector] = []
    if converged:
        for eigenvalue in eigenvalues:
            vector = _eigenvector(matrix, eigenvalue, n)
            if vector is not None:
                eigenvectors.append(vector)
    return QREigenResult(
        matrix, eigenvalues, eigenvectors, iterations, converged, current
    )

Solvers

panchi.algorithms.inverse(matrix)

Compute the inverse of a square, invertible matrix.

Reduces the matrix to RREF using Gauss-Jordan elimination and replays the recorded row operations on the identity matrix to construct A⁻¹. The matrix must be square and have full rank; otherwise it is singular and no inverse exists.

Parameters:

Name Type Description Default
matrix Matrix

The matrix to invert. Must be square and have full rank.

required

Returns:

Type Description
InverseResult

An object containing the original matrix, the computed inverse, and the sequence of row operations used.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance.

ValueError

If matrix is not square, or if matrix is singular (rank < n).

Examples:

>>> m = Matrix([[1, 2], [3, 4]])
>>> result = inverse(m)
>>> print(result.inverse)
[[-2.0, 1.0],
 [1.5, -0.5]]
Source code in panchi/algorithms/matrix_operations.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def inverse(matrix: Matrix) -> InverseResult:
    """
    Compute the inverse of a square, invertible matrix.

    Reduces the matrix to RREF using Gauss-Jordan elimination and replays
    the recorded row operations on the identity matrix to construct A⁻¹.
    The matrix must be square and have full rank; otherwise it is singular
    and no inverse exists.

    Parameters
    ----------
    matrix : Matrix
        The matrix to invert. Must be square and have full rank.

    Returns
    -------
    InverseResult
        An object containing the original matrix, the computed inverse, and
        the sequence of row operations used.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance.
    ValueError
        If matrix is not square, or if matrix is singular (rank < n).

    Examples
    --------
    >>> m = Matrix([[1, 2], [3, 4]])
    >>> result = inverse(m)
    >>> print(result.inverse)
    [[-2.0, 1.0],
     [1.5, -0.5]]
    """
    _require_square_matrix(matrix, "inverse")
    n = matrix.rows
    matrix_rref = rref(matrix)
    if matrix_rref.rank != n:
        raise ValueError(
            f"Cannot compute the inverse of a singular matrix. "
            f"Your matrix has rank {matrix_rref.rank}, but must have rank {n}. "
            f"Only matrices with full rank are invertible."
        )
    steps = matrix_rref.steps
    inv = _calculate_inverse(n, steps)
    return InverseResult(matrix, inv, steps)

panchi.algorithms.solve(A, b, tolerance=0.0)

Solve the linear system Ax = b.

Reduces A to RREF and applies the same row operations to b. The system's status is determined by inspecting the reduced forms: an inconsistent row (zero row in A with a non-zero corresponding entry in b) means no solution exists; fewer pivots than variables means infinitely many solutions exist; otherwise a unique solution is extracted from the pivot rows of the transformed b.

Parameters:

Name Type Description Default
A Matrix

The coefficient matrix in the system Ax = b.

required
b Vector

The right-hand side vector in the system Ax = b.

required
tolerance float

Pivot and right-hand-side magnitudes at or below this value are treated as zero during reduction. The default of 0.0 performs an exact solve. A small positive tolerance lets the solver treat a matrix that is only approximately rank-deficient as singular, which is how eigenvectors are recovered as the null space of A - λI for a floating-point eigenvalue estimate λ.

0.0

Returns:

Type Description
Solution

An object containing the original matrix and vector, the status ('unique', 'infinite', or 'inconsistent'), the solution vector if unique, and the row operations applied.

Raises:

Type Description
TypeError

If A is not a Matrix instance, or b is not a Vector instance.

ValueError

If the number of rows in A does not match the length of b.

Examples:

>>> A = Matrix([[2, 1], [5, 3]])
>>> b = Vector([1, 2])
>>> result = solve(A, b)
>>> result.status
'unique'
>>> result.solution
[1.0, -1.0]
Source code in panchi/algorithms/matrix_operations.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
def solve(A: Matrix, b: Vector, tolerance: float = 0.0) -> Solution:
    """
    Solve the linear system Ax = b.

    Reduces A to RREF and applies the same row operations to b. The
    system's status is determined by inspecting the reduced forms: an
    inconsistent row (zero row in A with a non-zero corresponding entry
    in b) means no solution exists; fewer pivots than variables means
    infinitely many solutions exist; otherwise a unique solution is
    extracted from the pivot rows of the transformed b.

    Parameters
    ----------
    A : Matrix
        The coefficient matrix in the system Ax = b.
    b : Vector
        The right-hand side vector in the system Ax = b.
    tolerance : float, optional
        Pivot and right-hand-side magnitudes at or below this value are
        treated as zero during reduction. The default of 0.0 performs an
        exact solve. A small positive tolerance lets the solver treat a
        matrix that is only approximately rank-deficient as singular, which
        is how eigenvectors are recovered as the null space of A - λI for a
        floating-point eigenvalue estimate λ.

    Returns
    -------
    Solution
        An object containing the original matrix and vector, the status
        ('unique', 'infinite', or 'inconsistent'), the solution vector
        if unique, and the row operations applied.

    Raises
    ------
    TypeError
        If A is not a Matrix instance, or b is not a Vector instance.
    ValueError
        If the number of rows in A does not match the length of b.

    Examples
    --------
    >>> A = Matrix([[2, 1], [5, 3]])
    >>> b = Vector([1, 2])
    >>> result = solve(A, b)
    >>> result.status
    'unique'
    >>> result.solution
    [1.0, -1.0]
    """
    if not isinstance(A, Matrix):
        raise TypeError(
            f"Expected a Matrix for A, but got {type(A).__name__}. "
            f"Solve is only defined for Matrix objects."
        )
    if not isinstance(b, Vector):
        raise TypeError(
            f"Expected a Vector for b, but got {type(b).__name__}. "
            f"Solve is only defined for Vector objects."
        )
    if A.rows != b.dims:
        raise ValueError(
            f"The number of rows in A must match the length of b. "
            f"A has {A.rows} rows but b has {b.dims} entries."
        )

    matrix_rref = rref(A, tolerance)
    steps = matrix_rref.steps

    applied_b = b
    for step in steps:
        applied_b = step.apply(applied_b)

    if _inconsistent_rows(matrix_rref, applied_b, tolerance):
        return Solution(A, b, "inconsistent", None, steps)

    if matrix_rref.nullity > 0:
        n = A.cols
        pivot_map = {col: row for row, col in matrix_rref.pivots}
        null_vectors = _null_space_basis(matrix_rref)

        particular_components: list[Scalar] = [0] * n
        for pc, pr in pivot_map.items():
            particular_components[pc] = applied_b[pr]
        particular = Vector(particular_components)

        null_space = VectorSpace(null_vectors)
        return Solution(A, b, "infinite", None, steps, particular, null_space)

    pivot_row_indices = [
        row for row, _ in sorted(matrix_rref.pivots, key=lambda p: p[1])
    ]
    solution = Vector([applied_b[row] for row in pivot_row_indices])
    return Solution(A, b, "unique", solution, steps)

panchi.algorithms.determinant(matrix)

Compute the determinant of a square matrix using cofactor expansion.

The determinant is a scalar that encodes properties of the matrix, including whether it is invertible (det ≠ 0) and how it scales areas or volumes under transformation. Only defined for square matrices.

Computed by expanding along the first row: for each entry in the first row, multiply it by its cofactor (the signed determinant of the submatrix formed by removing that entry's row and column), then sum the results. This preserves exact int/Fraction arithmetic, at the cost of O(n!) work; determinant_by_reduction is exact too and takes O(n³).

Parameters:

Name Type Description Default
matrix Matrix

The matrix whose determinant will be computed. Must be square.

required

Returns:

Type Description
int | float | Fraction

The determinant of the matrix.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance.

ValueError

If matrix is not square.

Examples:

>>> determinant(Matrix([[1, 2], [3, 4]]))
-2
>>> determinant(Matrix([[6]]))
6
See Also

determinant_by_reduction : Exact determinant via row reduction, with steps. cofactor_expansion : This expansion with every term shown.

Source code in panchi/algorithms/matrix_operations.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def determinant(matrix: Matrix) -> Scalar:
    """
    Compute the determinant of a square matrix using cofactor expansion.

    The determinant is a scalar that encodes properties of the matrix,
    including whether it is invertible (det ≠ 0) and how it scales areas or
    volumes under transformation. Only defined for square matrices.

    Computed by expanding along the first row: for each entry in the first
    row, multiply it by its cofactor (the signed determinant of the submatrix
    formed by removing that entry's row and column), then sum the results.
    This preserves exact ``int``/``Fraction`` arithmetic, at the cost of
    O(n!) work; ``determinant_by_reduction`` is exact too and takes O(n³).

    Parameters
    ----------
    matrix : Matrix
        The matrix whose determinant will be computed. Must be square.

    Returns
    -------
    int | float | Fraction
        The determinant of the matrix.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance.
    ValueError
        If matrix is not square.

    Examples
    --------
    >>> determinant(Matrix([[1, 2], [3, 4]]))
    -2
    >>> determinant(Matrix([[6]]))
    6

    See Also
    --------
    determinant_by_reduction : Exact determinant via row reduction, with steps.
    cofactor_expansion : This expansion with every term shown.
    """
    _require_square_matrix(matrix, "determinant")

    if matrix.rows == 1:
        return matrix[0][0]

    if matrix.rows == 2:
        return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0])

    det = 0
    for j in range(matrix.cols):
        entry = matrix[0][j]
        if entry != 0:
            sign = (-1) ** j
            det += sign * entry * determinant(_submatrix(matrix, 0, j))

    return det

Deprecated in 3.1.0, removed in 4.0

Use determinant, or determinant_by_reduction for an exact result with steps.

panchi.algorithms.determinant_lu(matrix)

Compute the determinant of a square matrix using LU decomposition.

Deprecated since 3.1.0. Use determinant or the exact determinant_by_reduction instead. Removed in 4.0.

Factors the matrix into P, L, and U with row swaps, then multiplies the main diagonal entries of U by the parity of the permutation. Each row swap in P contributes a factor of -1 to the determinant, so the sign is adjusted by counting the number of swaps performed during factorization.

Parameters:

Name Type Description Default
matrix Matrix

The matrix whose determinant will be computed. Must be square.

required

Returns:

Type Description
float

The determinant of the matrix.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance.

ValueError

If matrix is not square.

Examples:

>>> determinant_lu(Matrix([[1, 2], [3, 4]]))
-2.0
>>> determinant_lu(Matrix([[0, 1], [1, 2]]))
-1.0
See Also

determinant : Determinant via cofactor expansion.

Source code in panchi/algorithms/matrix_operations.py
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
def determinant_lu(matrix: Matrix) -> float:
    """
    Compute the determinant of a square matrix using LU decomposition.

    Deprecated since 3.1.0. Use ``determinant`` or the exact
    ``determinant_by_reduction`` instead. Removed in 4.0.

    Factors the matrix into P, L, and U with row swaps, then
    multiplies the main diagonal entries of U by the parity of the
    permutation. Each row swap in P contributes a factor of -1 to the
    determinant, so the sign is adjusted by counting the number of swaps
    performed during factorization.

    Parameters
    ----------
    matrix : Matrix
        The matrix whose determinant will be computed. Must be square.

    Returns
    -------
    float
        The determinant of the matrix.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance.
    ValueError
        If matrix is not square.

    Examples
    --------
    >>> determinant_lu(Matrix([[1, 2], [3, 4]]))
    -2.0
    >>> determinant_lu(Matrix([[0, 1], [1, 2]]))
    -1.0

    See Also
    --------
    determinant : Determinant via cofactor expansion.
    """
    warn_deprecated(
        "determinant_lu", "determinant() or determinant_by_reduction() (exact)"
    )
    _require_square_matrix(matrix, "determinant")
    matrix_lu = lu(matrix)
    parity = _swap_parity(matrix_lu.steps)
    upper_diagonal_product = _main_diagonal_product(matrix_lu.upper)
    return parity * upper_diagonal_product

Determinants step by step

panchi.algorithms.cofactor_expansion(matrix, along='row', index=0)

Compute the determinant by cofactor expansion, keeping every term.

Expands along one row or column: each entry a_ij is multiplied by its cofactor (-1)^(i+j) · det(M_ij), where M_ij is the matrix left after deleting row i and column j, and the terms are summed. Choosing a row or column with many zeros makes the hand computation shortest; the result is the same whichever line is chosen.

Parameters:

Name Type Description Default
matrix Matrix

The square matrix to expand. Must be at least 2×2.

required
along str

"row" (default) or "column".

'row'
index int

Which row or column to expand along (0-based). Defaults to 0.

0

Returns:

Type Description
CofactorExpansion

Every term of the expansion and the determinant.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance, or index is not an integer.

ValueError

If matrix is not square or is 1×1, along is not "row" or "column", or index is out of range.

Examples:

>>> A = Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 4]])
>>> cofactor_expansion(A).determinant
18
>>> cofactor_expansion(A, along="column", index=2).determinant
18
Source code in panchi/algorithms/matrix_operations.py
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def cofactor_expansion(
    matrix: Matrix, along: str = "row", index: int = 0
) -> CofactorExpansion:
    """
    Compute the determinant by cofactor expansion, keeping every term.

    Expands along one row or column: each entry a_ij is multiplied by its
    cofactor (-1)^(i+j) · det(M_ij), where M_ij is the matrix left after
    deleting row i and column j, and the terms are summed. Choosing a row or
    column with many zeros makes the hand computation shortest; the result
    is the same whichever line is chosen.

    Parameters
    ----------
    matrix : Matrix
        The square matrix to expand. Must be at least 2×2.
    along : str, optional
        "row" (default) or "column".
    index : int, optional
        Which row or column to expand along (0-based). Defaults to 0.

    Returns
    -------
    CofactorExpansion
        Every term of the expansion and the determinant.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance, or index is not an integer.
    ValueError
        If matrix is not square or is 1×1, along is not "row" or "column",
        or index is out of range.

    Examples
    --------
    >>> A = Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 4]])
    >>> cofactor_expansion(A).determinant
    18
    >>> cofactor_expansion(A, along="column", index=2).determinant
    18
    """
    _require_square_matrix(matrix, "cofactor expansion")
    n = matrix.rows
    if n < 2:
        raise ValueError(
            "Cofactor expansion needs at least a 2×2 matrix. "
            "The determinant of a 1×1 matrix is its only entry."
        )
    if along not in ("row", "column"):
        raise ValueError(f"along must be 'row' or 'column'. Got {along!r}.")
    if not isinstance(index, int):
        raise TypeError(f"index must be an integer. Got {type(index).__name__}.")
    if not (0 <= index < n):
        raise ValueError(
            f"{along.capitalize()} index {index} is out of range for a "
            f"{n}×{n} matrix. Valid indices are 0 to {n - 1}."
        )

    terms = []
    for k in range(n):
        i, j = (index, k) if along == "row" else (k, index)
        minor = _submatrix(matrix, i, j)
        terms.append(CofactorTerm(i, j, matrix[i][j], minor, determinant(minor)))
    return CofactorExpansion(matrix, along, index, terms)

panchi.algorithms.determinant_by_reduction(matrix)

Compute the determinant exactly by reducing to row echelon form.

Reduces the matrix with ref(), which uses only row swaps and row additions. Row additions leave the determinant unchanged and each swap flips its sign, so det(A) = (-1)^swaps times the product of the diagonal of the echelon form. This takes O(n³) work instead of the O(n!) of cofactor expansion and stays exact for int and Fraction entries.

Parameters:

Name Type Description Default
matrix Matrix

The square matrix whose determinant will be computed.

required

Returns:

Type Description
DeterminantReduction

The reduction, the number of swaps, and the determinant.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance.

ValueError

If matrix is not square.

Examples:

>>> determinant_by_reduction(Matrix([[0, 2], [3, 4]])).determinant
-6
Source code in panchi/algorithms/matrix_operations.py
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
def determinant_by_reduction(matrix: Matrix) -> DeterminantReduction:
    """
    Compute the determinant exactly by reducing to row echelon form.

    Reduces the matrix with ref(), which uses only row swaps and row
    additions. Row additions leave the determinant unchanged and each swap
    flips its sign, so det(A) = (-1)^swaps times the product of the
    diagonal of the echelon form. This takes O(n³) work instead of the O(n!)
    of cofactor expansion and stays exact for int and Fraction entries.

    Parameters
    ----------
    matrix : Matrix
        The square matrix whose determinant will be computed.

    Returns
    -------
    DeterminantReduction
        The reduction, the number of swaps, and the determinant.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance.
    ValueError
        If matrix is not square.

    Examples
    --------
    >>> determinant_by_reduction(Matrix([[0, 2], [3, 4]])).determinant
    -6
    """
    _require_square_matrix(matrix, "determinant")
    reduction = ref(matrix)
    swaps = sum(1 for step in reduction.steps if isinstance(step, RowSwap))
    return DeterminantReduction(matrix, reduction, swaps)

panchi.algorithms.adjugate(matrix)

Return the adjugate (classical adjoint) of a square matrix.

The adjugate is the transpose of the cofactor matrix, whose entry (i, j) is (-1)^(i+j) · det(M_ij). It satisfies A @ adj(A) == det(A) · I, so when det(A) ≠ 0 the inverse is adj(A) / det(A).

Parameters:

Name Type Description Default
matrix Matrix

The square matrix.

required

Returns:

Type Description
Matrix

The adjugate, with the same shape as matrix.

Raises:

Type Description
TypeError

If matrix is not a Matrix instance.

ValueError

If matrix is not square.

Examples:

>>> print(adjugate(Matrix([[1, 2], [3, 4]])))
[[4, -2],
 [-3, 1]]
Source code in panchi/algorithms/matrix_operations.py
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
def adjugate(matrix: Matrix) -> Matrix:
    """
    Return the adjugate (classical adjoint) of a square matrix.

    The adjugate is the transpose of the cofactor matrix, whose entry (i, j)
    is (-1)^(i+j) · det(M_ij). It satisfies A @ adj(A) == det(A) · I, so
    when det(A) ≠ 0 the inverse is adj(A) / det(A).

    Parameters
    ----------
    matrix : Matrix
        The square matrix.

    Returns
    -------
    Matrix
        The adjugate, with the same shape as matrix.

    Raises
    ------
    TypeError
        If matrix is not a Matrix instance.
    ValueError
        If matrix is not square.

    Examples
    --------
    >>> print(adjugate(Matrix([[1, 2], [3, 4]])))
    [[4, -2],
     [-3, 1]]
    """
    _require_square_matrix(matrix, "adjugate")
    n = matrix.rows
    if n == 1:
        return Matrix([[1]])
    cofactors = [
        [(-1) ** (i + j) * determinant(_submatrix(matrix, i, j)) for j in range(n)]
        for i in range(n)
    ]
    return Matrix(cofactors).T

panchi.algorithms.cramer(A, b)

Solve a square system Ax = b with Cramer's rule.

Each unknown is x_i = det(A_i) / det(A), where A_i is A with column i replaced by b. Only works when det(A) ≠ 0, i.e. when the system has a unique solution.

Parameters:

Name Type Description Default
A Matrix

The square coefficient matrix.

required
b Vector

The right-hand side, with one component per row of A.

required

Returns:

Type Description
CramerResult

The replaced matrices, their determinants, and the solution.

Raises:

Type Description
TypeError

If A is not a Matrix or b is not a Vector.

ValueError

If A is not square, b has the wrong dimension, or det(A) is zero.

Examples:

>>> cramer(Matrix([[2, 1], [1, 3]]), Vector([3, 5])).solution
[0.8, 1.4]
Source code in panchi/algorithms/matrix_operations.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
def cramer(A: Matrix, b: Vector) -> CramerResult:
    """
    Solve a square system Ax = b with Cramer's rule.

    Each unknown is x_i = det(A_i) / det(A), where A_i is A with column i
    replaced by b. Only works when det(A) ≠ 0, i.e. when the system has a
    unique solution.

    Parameters
    ----------
    A : Matrix
        The square coefficient matrix.
    b : Vector
        The right-hand side, with one component per row of A.

    Returns
    -------
    CramerResult
        The replaced matrices, their determinants, and the solution.

    Raises
    ------
    TypeError
        If A is not a Matrix or b is not a Vector.
    ValueError
        If A is not square, b has the wrong dimension, or det(A) is zero.

    Examples
    --------
    >>> cramer(Matrix([[2, 1], [1, 3]]), Vector([3, 5])).solution
    [0.8, 1.4]
    """
    _require_square_matrix(A, "Cramer's rule solution")
    if not isinstance(b, Vector):
        raise TypeError(f"Expected b to be a Vector, but got {type(b).__name__}.")
    n = A.rows
    if b.dims != n:
        raise ValueError(
            f"b must have one component per row of A. "
            f"A has {n} rows but b has {b.dims} components."
        )

    det = determinant(A)
    if det == 0:
        raise ValueError(
            "Cramer's rule needs det(A) ≠ 0, but det(A) = 0. The system has "
            "either no solution or infinitely many; use solve() instead."
        )

    replaced = [
        Matrix([[b[i] if j == col else A[i][j] for j in range(n)] for i in range(n)])
        for col in range(n)
    ]
    replaced_determinants = [determinant(m) for m in replaced]
    solution = Vector([value / det for value in replaced_determinants])
    return CramerResult(A, b, det, replaced, replaced_determinants, solution)

Matrix properties

panchi.algorithms.rank(obj)

Return the rank of a matrix or vector space.

Rank is fundamentally a matrix property: the number of linearly independent rows (equivalently, columns) of a matrix, computed as the number of pivots in its reduced row echelon form. A VectorSpace's rank is defined as the rank of the matrix whose rows are its spanning vectors — so the same function answers both, and rank(m) == rank(VectorSpace(m.col_vectors)).

Parameters:

Name Type Description Default
obj Matrix or VectorSpace

The matrix, or the vector space whose generators to rank.

required

Returns:

Type Description
int

The number of linearly independent rows/vectors.

Examples:

>>> rank(Matrix([[1, 2], [2, 4]]))
1
>>> rank(VectorSpace([Vector([1, 0]), Vector([0, 1]), Vector([1, 1])]))
2
Source code in panchi/algorithms/matrix_operations.py
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
def rank(obj: Matrix | VectorSpace) -> int:
    """
    Return the rank of a matrix or vector space.

    Rank is fundamentally a matrix property: the number of linearly
    independent rows (equivalently, columns) of a matrix, computed as the
    number of pivots in its reduced row echelon form. A ``VectorSpace``'s
    rank is *defined* as the rank of the matrix whose rows are its spanning
    vectors — so the same function answers both, and
    ``rank(m) == rank(VectorSpace(m.col_vectors))``.

    Parameters
    ----------
    obj : Matrix or VectorSpace
        The matrix, or the vector space whose generators to rank.

    Returns
    -------
    int
        The number of linearly independent rows/vectors.

    Examples
    --------
    >>> rank(Matrix([[1, 2], [2, 4]]))
    1
    >>> rank(VectorSpace([Vector([1, 0]), Vector([0, 1]), Vector([1, 1])]))
    2
    """
    if isinstance(obj, VectorSpace):
        matrix = Matrix([v.to_list() for v in obj.data])
    else:
        matrix = obj
    return ref(matrix).rank

panchi.algorithms.nullity(matrix)

Return the nullity of a matrix — the dimension of its null space.

By the rank–nullity theorem, rank(matrix) + nullity(matrix) equals the number of columns of the matrix.

Parameters:

Name Type Description Default
matrix Matrix

The matrix whose nullity to compute.

required

Returns:

Type Description
int

The dimension of the null space (number of free columns).

Examples:

>>> nullity(Matrix([[1, 2, 3], [4, 5, 6]]))
1
Source code in panchi/algorithms/matrix_operations.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def nullity(matrix: Matrix) -> int:
    """
    Return the nullity of a matrix — the dimension of its null space.

    By the rank–nullity theorem, ``rank(matrix) + nullity(matrix)`` equals
    the number of columns of the matrix.

    Parameters
    ----------
    matrix : Matrix
        The matrix whose nullity to compute.

    Returns
    -------
    int
        The dimension of the null space (number of free columns).

    Examples
    --------
    >>> nullity(Matrix([[1, 2, 3], [4, 5, 6]]))
    1
    """
    return ref(matrix).nullity

panchi.algorithms.is_invertible(matrix)

Return True if the matrix is square and invertible (full rank).

A matrix is invertible exactly when it is square and its rank equals its number of rows (equivalently, its determinant is non-zero). This uses the rank via RREF rather than the O(n!) cofactor determinant.

Parameters:

Name Type Description Default
matrix Matrix

The matrix to test.

required

Returns:

Type Description
bool

True if the matrix is square and full rank, False otherwise.

Examples:

>>> is_invertible(Matrix([[1, 2], [3, 4]]))
True
>>> is_invertible(Matrix([[1, 2], [2, 4]]))
False
Source code in panchi/algorithms/matrix_operations.py
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
def is_invertible(matrix: Matrix) -> bool:
    """
    Return True if the matrix is square and invertible (full rank).

    A matrix is invertible exactly when it is square and its rank equals its
    number of rows (equivalently, its determinant is non-zero). This uses the
    rank via RREF rather than the O(n!) cofactor determinant.

    Parameters
    ----------
    matrix : Matrix
        The matrix to test.

    Returns
    -------
    bool
        True if the matrix is square and full rank, False otherwise.

    Examples
    --------
    >>> is_invertible(Matrix([[1, 2], [3, 4]]))
    True
    >>> is_invertible(Matrix([[1, 2], [2, 4]]))
    False
    """
    return matrix.is_square and rank(matrix) == matrix.rows

panchi.algorithms.is_symmetric(matrix)

Return True if the matrix equals its own transpose.

Only square matrices can be symmetric. A symmetric matrix satisfies A == Aᵀ entrywise.

Parameters:

Name Type Description Default
matrix Matrix

The matrix to test.

required

Returns:

Type Description
bool

True if the matrix is square and equal to its transpose.

Examples:

>>> is_symmetric(Matrix([[1, 2], [2, 1]]))
True
>>> is_symmetric(Matrix([[1, 2], [3, 4]]))
False
Source code in panchi/algorithms/matrix_operations.py
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
def is_symmetric(matrix: Matrix) -> bool:
    """
    Return True if the matrix equals its own transpose.

    Only square matrices can be symmetric. A symmetric matrix satisfies
    ``A == Aᵀ`` entrywise.

    Parameters
    ----------
    matrix : Matrix
        The matrix to test.

    Returns
    -------
    bool
        True if the matrix is square and equal to its transpose.

    Examples
    --------
    >>> is_symmetric(Matrix([[1, 2], [2, 1]]))
    True
    >>> is_symmetric(Matrix([[1, 2], [3, 4]]))
    False
    """
    return matrix.is_square and matrix == matrix.transpose()

Vector space operations

panchi.algorithms.basis(space)

Return a basis for the span of the vectors in a space.

Computes a maximal linearly independent subset of the spanning set by reducing the matrix whose columns are the vectors to row echelon form. Each pivot column corresponds to a vector that is linearly independent of all preceding pivot vectors, so the original vectors at those column indices form a basis.

The result is cached on the space and reused while the spanning set is unchanged. The cache key is the current value of every spanning vector, so any mutation — through VectorSpace.__setitem__ or direct edits to data — invalidates it automatically. A new list is returned on every call, so mutating the result never corrupts the cache.

Parameters:

Name Type Description Default
space VectorSpace

The space whose basis to compute.

required

Returns:

Type Description
list[Vector]

A list of vectors from the original spanning set that form a basis. The order follows the original input order.

Examples:

>>> v1 = Vector([1, 2, 3])
>>> v2 = Vector([4, 5, 6])
>>> v3 = Vector([7, 8, 9])  # linearly dependent on v1 and v2
>>> vs = VectorSpace([v1, v2, v3])
>>> len(basis(vs))
2
Source code in panchi/algorithms/vector_space_operations.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def basis(space: VectorSpace) -> list[Vector]:
    """
    Return a basis for the span of the vectors in a space.

    Computes a maximal linearly independent subset of the spanning set by
    reducing the matrix whose columns are the vectors to row echelon form.
    Each pivot column corresponds to a vector that is linearly independent
    of all preceding pivot vectors, so the original vectors at those column
    indices form a basis.

    The result is cached on the space and reused while the spanning set is
    unchanged. The cache key is the current value of every spanning vector,
    so any mutation — through ``VectorSpace.__setitem__`` or direct edits to
    ``data`` — invalidates it automatically. A new list is returned on every
    call, so mutating the result never corrupts the cache.

    Parameters
    ----------
    space : VectorSpace
        The space whose basis to compute.

    Returns
    -------
    list[Vector]
        A list of vectors from the original spanning set that form a basis.
        The order follows the original input order.

    Examples
    --------
    >>> v1 = Vector([1, 2, 3])
    >>> v2 = Vector([4, 5, 6])
    >>> v3 = Vector([7, 8, 9])  # linearly dependent on v1 and v2
    >>> vs = VectorSpace([v1, v2, v3])
    >>> len(basis(vs))
    2
    """
    return space._cached_basis(_pivot_vectors)

panchi.algorithms.is_full_rank(space)

Return True if a space spans its entire ambient space.

A space is full rank when its rank equals the ambient dimension — i.e. when the basis vectors span all of R^n.

Parameters:

Name Type Description Default
space VectorSpace

The space to test.

required

Returns:

Type Description
bool

True if rank(space) == space.ambient_dims, False otherwise.

Examples:

>>> is_full_rank(VectorSpace([Vector([1, 0]), Vector([0, 1])]))
True
>>> is_full_rank(VectorSpace([Vector([1, 0, 0]), Vector([0, 1, 0])]))
False
Source code in panchi/algorithms/vector_space_operations.py
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
def is_full_rank(space: VectorSpace) -> bool:
    """
    Return True if a space spans its entire ambient space.

    A space is full rank when its rank equals the ambient dimension — i.e.
    when the basis vectors span all of R^n.

    Parameters
    ----------
    space : VectorSpace
        The space to test.

    Returns
    -------
    bool
        True if ``rank(space) == space.ambient_dims``, False otherwise.

    Examples
    --------
    >>> is_full_rank(VectorSpace([Vector([1, 0]), Vector([0, 1])]))
    True
    >>> is_full_rank(VectorSpace([Vector([1, 0, 0]), Vector([0, 1, 0])]))
    False
    """
    return rank(space) == space.ambient_dims

panchi.algorithms.contains(space, v)

Return True if vector v lies in a space.

Checks membership by attempting to solve the linear system Bx = v, where B is the matrix whose columns are the basis vectors. The vector v is in the span if and only if the system is consistent.

Parameters:

Name Type Description Default
space VectorSpace

The space to test membership against.

required
v Vector

The vector to test for membership.

required

Returns:

Type Description
bool

True if v is in the span of the space, False otherwise.

Raises:

Type Description
TypeError

If v is not a Vector.

ValueError

If v has a different number of components than the vectors in the space.

Examples:

>>> vs = VectorSpace([Vector([1, 0]), Vector([0, 1])])
>>> contains(vs, Vector([3, 4]))
True
>>> vs2 = VectorSpace([Vector([1, 0, 0]), Vector([0, 1, 0])])
>>> contains(vs2, Vector([0, 0, 1]))
False
Source code in panchi/algorithms/vector_space_operations.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def contains(space: VectorSpace, v: Vector) -> bool:
    """
    Return True if vector v lies in a space.

    Checks membership by attempting to solve the linear system ``Bx = v``,
    where B is the matrix whose columns are the basis vectors. The vector v
    is in the span if and only if the system is consistent.

    Parameters
    ----------
    space : VectorSpace
        The space to test membership against.
    v : Vector
        The vector to test for membership.

    Returns
    -------
    bool
        True if v is in the span of the space, False otherwise.

    Raises
    ------
    TypeError
        If v is not a Vector.
    ValueError
        If v has a different number of components than the vectors in the
        space.

    Examples
    --------
    >>> vs = VectorSpace([Vector([1, 0]), Vector([0, 1])])
    >>> contains(vs, Vector([3, 4]))
    True
    >>> vs2 = VectorSpace([Vector([1, 0, 0]), Vector([0, 1, 0])])
    >>> contains(vs2, Vector([0, 0, 1]))
    False
    """
    if not isinstance(v, Vector):
        raise TypeError(f"contains() requires a Vector. Got {type(v).__name__}.")

    if v.dims != space.ambient_dims:
        raise ValueError(
            f"Vector has {v.dims} component(s), but this space lives in "
            f"R^{space.ambient_dims}. Dimensions must match."
        )

    b = basis(space)
    if not b:
        return all(component == 0 for component in v)

    basis_matrix = vector_column_matrix(b)
    return solve(basis_matrix, v).status != "inconsistent"

panchi.algorithms.same_subspace(a, b)

Check if two spaces span the same subspace.

Two subspaces are equal if and only if they have the same rank and every basis vector of one is contained in the other. This is a mathematical comparison — unlike VectorSpace.__eq__, which checks whether the generating sets contain the same vectors, this determines whether the two spaces cover the same region of R^n.

Parameters:

Name Type Description Default
a VectorSpace

The first space.

required
b VectorSpace

The second space.

required

Returns:

Type Description
bool

True if both spaces span the same subspace, False otherwise.

Raises:

Type Description
TypeError

If b is not a VectorSpace.

ValueError

If the two spaces live in different ambient dimensions.

Examples:

>>> v1, v2 = Vector([1, 0]), Vector([0, 1])
>>> a = VectorSpace([v1, v2])
>>> b = VectorSpace([v1, v1 + v2])
>>> same_subspace(a, b)
True
>>> a == b
False
Source code in panchi/algorithms/vector_space_operations.py
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
def same_subspace(a: VectorSpace, b: VectorSpace) -> bool:
    """
    Check if two spaces span the same subspace.

    Two subspaces are equal if and only if they have the same rank and every
    basis vector of one is contained in the other. This is a mathematical
    comparison — unlike ``VectorSpace.__eq__``, which checks whether the
    generating sets contain the same vectors, this determines whether the two
    spaces cover the same region of R^n.

    Parameters
    ----------
    a : VectorSpace
        The first space.
    b : VectorSpace
        The second space.

    Returns
    -------
    bool
        True if both spaces span the same subspace, False otherwise.

    Raises
    ------
    TypeError
        If b is not a VectorSpace.
    ValueError
        If the two spaces live in different ambient dimensions.

    Examples
    --------
    >>> v1, v2 = Vector([1, 0]), Vector([0, 1])
    >>> a = VectorSpace([v1, v2])
    >>> b = VectorSpace([v1, v1 + v2])
    >>> same_subspace(a, b)
    True
    >>> a == b
    False
    """
    if not isinstance(b, VectorSpace):
        raise TypeError(
            f"same_subspace() requires a VectorSpace. Got {type(b).__name__}."
        )

    if a.ambient_dims != b.ambient_dims:
        raise ValueError(
            f"Cannot compare subspaces of different ambient dimensions. "
            f"The first lives in R^{a.ambient_dims}, "
            f"but the second lives in R^{b.ambient_dims}."
        )

    if rank(a) != rank(b):
        return False

    return all(contains(b, v) for v in basis(a))

panchi.algorithms.orthogonal_complement(space)

Compute the orthogonal complement of a vector space.

The orthogonal complement of a subspace W of R^n is the set of all vectors in R^n that are orthogonal to every vector in W. It is exactly the null space of the matrix whose rows are the basis vectors of W.

Parameters:

Name Type Description Default
space VectorSpace

The subspace whose orthogonal complement is to be computed.

required

Returns:

Type Description
VectorSpace

A VectorSpace representing the orthogonal complement. If the input space spans all of R^n, returns a VectorSpace containing only the zero vector (rank 0).

Raises:

Type Description
TypeError

If space is not a VectorSpace.

Examples:

>>> v1 = Vector([1, 0, 0])
>>> v2 = Vector([0, 1, 0])
>>> vs = VectorSpace([v1, v2])
>>> comp = orthogonal_complement(vs)
>>> rank(comp)
1
>>> basis(comp)[0]
Vector([0, 0, 1])
Source code in panchi/algorithms/vector_space_operations.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def orthogonal_complement(space: VectorSpace) -> VectorSpace:
    """
    Compute the orthogonal complement of a vector space.

    The orthogonal complement of a subspace W of R^n is the set of all
    vectors in R^n that are orthogonal to every vector in W. It is exactly
    the null space of the matrix whose rows are the basis vectors of W.

    Parameters
    ----------
    space : VectorSpace
        The subspace whose orthogonal complement is to be computed.

    Returns
    -------
    VectorSpace
        A VectorSpace representing the orthogonal complement. If the input
        space spans all of R^n, returns a VectorSpace containing only the
        zero vector (rank 0).

    Raises
    ------
    TypeError
        If space is not a VectorSpace.

    Examples
    --------
    >>> v1 = Vector([1, 0, 0])
    >>> v2 = Vector([0, 1, 0])
    >>> vs = VectorSpace([v1, v2])
    >>> comp = orthogonal_complement(vs)
    >>> rank(comp)
    1
    >>> basis(comp)[0]
    Vector([0, 0, 1])
    """
    if not isinstance(space, VectorSpace):
        raise TypeError(
            f"orthogonal_complement() requires a VectorSpace. "
            f"Got {type(space).__name__}."
        )

    basis_vectors = basis(space)
    if not basis_vectors:
        return standard_basis(space.ambient_dims)

    row_matrix = Matrix([v.to_list() for v in basis_vectors])
    return null_space(row_matrix)

panchi.algorithms.gram_schmidt(vectors, normalize=True)

Orthogonalize (and optionally normalize) a list of vectors using the Gram-Schmidt process.

Given a list of linearly independent vectors, produces an orthogonal list spanning the same subspace: each output vector is orthogonal to all the others. Each input vector has its components along the previously produced directions removed. By default, each remainder is then normalized to unit length, giving an orthonormal list. With normalize = False, the unnormalized orthogonal remainders are returned as is, which keeps exact inputs exact.

Parameters:

Name Type Description Default
vectors list[Vector]

The vectors to orthogonalize. Must be non-empty; the vectors are expected to be linearly independent.

required
normalize bool

Whether to return vectors normalized to unit length

True

Returns:

Type Description
list[Vector]

An orthonormal list of vectors spanning the same subspace, in the same order as the inputs.

Raises:

Type Description
ValueError

If vectors is empty.

ZeroDivisionError

If the vectors are linearly dependent (a vector reduces to the zero vector and cannot be normalized).

Examples:

>>> a = Vector([1, 1, 0])
>>> b = Vector([1, 0, 1])
>>> q = gram_schmidt([a, b])
>>> round(dot(q[0], q[1]), 10)
0.0
>>> round(q[0].magnitude, 10)
1.0
>>> a = Vector([3, 6, 0])
>>> b = Vector([1, 2, 2,])
>>> g = gram_schmidt([a, b], normalize=False)
>>> round(dot(p[0], p[1]), 10)
0.0
>>> round(p[1].magnitude, 10)
2.0
Source code in panchi/algorithms/vector_operations.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def gram_schmidt(vectors: list[Vector], normalize: bool = True) -> list[Vector]:
    """
    Orthogonalize (and optionally normalize) a list of vectors using the
    Gram-Schmidt process.

    Given a list of linearly independent vectors, produces an orthogonal
    list spanning the same subspace: each output vector is orthogonal to
    all the others. Each input vector has its components along the
    previously produced directions removed. By default, each remainder is
    then normalized to unit length, giving an orthonormal list. With
    normalize = False, the unnormalized orthogonal remainders are returned
    as is, which keeps exact inputs exact.

    Parameters
    ----------
    vectors : list[Vector]
        The vectors to orthogonalize. Must be non-empty; the vectors are
        expected to be linearly independent.
    normalize: bool, optional
        Whether to return vectors normalized to unit length

    Returns
    -------
    list[Vector]
        An orthonormal list of vectors spanning the same subspace, in the
        same order as the inputs.

    Raises
    ------
    ValueError
        If vectors is empty.
    ZeroDivisionError
        If the vectors are linearly dependent (a vector reduces to the zero
        vector and cannot be normalized).

    Examples
    --------
    >>> a = Vector([1, 1, 0])
    >>> b = Vector([1, 0, 1])
    >>> q = gram_schmidt([a, b])
    >>> round(dot(q[0], q[1]), 10)
    0.0
    >>> round(q[0].magnitude, 10)
    1.0

    >>> a = Vector([3, 6, 0])
    >>> b = Vector([1, 2, 2,])
    >>> g = gram_schmidt([a, b], normalize=False)
    >>> round(dot(p[0], p[1]), 10)
    0.0
    >>> round(p[1].magnitude, 10)
    2.0
    """
    if normalize:
        return [step.orthonormal for step in _gram_schmidt_steps(vectors)]
    else:
        return [step.orthogonal for step in _gram_schmidt_steps(vectors)]

panchi.algorithms.vector_projection(projected_vector, axis_vector)

Project one vector orthogonally onto the line spanned by another.

The projection of v onto a is the component of v that lies along a, computed as (v . a) / (a . a) * a. It is the closest point to v on the line through the origin in the direction of a.

Parameters:

Name Type Description Default
projected_vector Vector

The vector being projected (v).

required
axis_vector Vector

The vector defining the direction to project onto (a). Must be non-zero.

required

Returns:

Type Description
Vector

The projection of projected_vector onto axis_vector.

Raises:

Type Description
ValueError

If the vectors have different dimensions.

ZeroDivisionError

If axis_vector is the zero vector.

Examples:

>>> v = Vector([2, 3])
>>> a = Vector([1, 0])
>>> print(vector_projection(v, a))
[2.0, 0.0]
Source code in panchi/algorithms/vector_operations.py
 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
def vector_projection(projected_vector: Vector, axis_vector: Vector) -> Vector:
    """
    Project one vector orthogonally onto the line spanned by another.

    The projection of v onto a is the component of v that lies along a,
    computed as (v . a) / (a . a) * a. It is the closest point to v on the
    line through the origin in the direction of a.

    Parameters
    ----------
    projected_vector : Vector
        The vector being projected (v).
    axis_vector : Vector
        The vector defining the direction to project onto (a). Must be
        non-zero.

    Returns
    -------
    Vector
        The projection of projected_vector onto axis_vector.

    Raises
    ------
    ValueError
        If the vectors have different dimensions.
    ZeroDivisionError
        If axis_vector is the zero vector.

    Examples
    --------
    >>> v = Vector([2, 3])
    >>> a = Vector([1, 0])
    >>> print(vector_projection(v, a))
    [2.0, 0.0]
    """
    scalar_projection = dot(projected_vector, axis_vector) / dot(
        axis_vector, axis_vector
    )
    return scalar_projection * axis_vector

Subspace factories

panchi.algorithms.span(vectors)

Construct the vector space spanned by a list of vectors.

A readable alias for VectorSpace(vectors) — the span is the set of all linear combinations of the given vectors.

Parameters:

Name Type Description Default
vectors list[Vector]

The spanning vectors.

required

Returns:

Type Description
VectorSpace

The space these vectors span.

Examples:

>>> span([Vector([1, 0]), Vector([0, 1])])
VectorSpace(ambient=2, generators=2)
Source code in panchi/algorithms/vector_space_operations.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def span(vectors: list[Vector]) -> VectorSpace:
    """
    Construct the vector space spanned by a list of vectors.

    A readable alias for ``VectorSpace(vectors)`` — the span is the set of all
    linear combinations of the given vectors.

    Parameters
    ----------
    vectors : list[Vector]
        The spanning vectors.

    Returns
    -------
    VectorSpace
        The space these vectors span.

    Examples
    --------
    >>> span([Vector([1, 0]), Vector([0, 1])])
    VectorSpace(ambient=2, generators=2)
    """
    return VectorSpace(vectors)

panchi.algorithms.standard_basis(n)

Construct the standard basis of R^n as a vector space.

The standard basis is {e_1, ..., e_n}, where e_i has a 1 in position i and 0 elsewhere. The resulting space is all of R^n.

Parameters:

Name Type Description Default
n int

The dimension of the ambient space.

required

Returns:

Type Description
VectorSpace

The full space R^n, spanned by the standard basis vectors.

Examples:

>>> rank(standard_basis(3))
3
Source code in panchi/algorithms/vector_space_operations.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def standard_basis(n: int) -> VectorSpace:
    """
    Construct the standard basis of R^n as a vector space.

    The standard basis is ``{e_1, ..., e_n}``, where ``e_i`` has a 1 in
    position i and 0 elsewhere. The resulting space is all of R^n.

    Parameters
    ----------
    n : int
        The dimension of the ambient space.

    Returns
    -------
    VectorSpace
        The full space R^n, spanned by the standard basis vectors.

    Examples
    --------
    >>> rank(standard_basis(3))
    3
    """
    return VectorSpace([unit_vector(n, i) for i in range(n)])

panchi.algorithms.column_space(matrix)

Construct the column space of a matrix.

The column space is the span of the matrix's columns — the set of all vectors reachable as matrix @ x. Its dimension equals rank(matrix).

Parameters:

Name Type Description Default
matrix Matrix

The matrix whose column space to build.

required

Returns:

Type Description
VectorSpace

The span of the matrix's columns.

Examples:

>>> A = Matrix([[1, 2], [3, 6]])
>>> rank(column_space(A))
1
Source code in panchi/algorithms/vector_space_operations.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
def column_space(matrix: Matrix) -> VectorSpace:
    """
    Construct the column space of a matrix.

    The column space is the span of the matrix's columns — the set of all
    vectors reachable as ``matrix @ x``. Its dimension equals ``rank(matrix)``.

    Parameters
    ----------
    matrix : Matrix
        The matrix whose column space to build.

    Returns
    -------
    VectorSpace
        The span of the matrix's columns.

    Examples
    --------
    >>> A = Matrix([[1, 2], [3, 6]])
    >>> rank(column_space(A))
    1
    """
    return VectorSpace(matrix.col_vectors)

panchi.algorithms.row_space(matrix)

Construct the row space of a matrix.

The row space is the span of the matrix's rows, equivalently the column space of its transpose. Its dimension equals rank(matrix).

Parameters:

Name Type Description Default
matrix Matrix

The matrix whose row space to build.

required

Returns:

Type Description
VectorSpace

The span of the matrix's rows.

Examples:

>>> A = Matrix([[1, 2], [3, 6]])
>>> rank(row_space(A))
1
Source code in panchi/algorithms/vector_space_operations.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def row_space(matrix: Matrix) -> VectorSpace:
    """
    Construct the row space of a matrix.

    The row space is the span of the matrix's rows, equivalently the column
    space of its transpose. Its dimension equals ``rank(matrix)``.

    Parameters
    ----------
    matrix : Matrix
        The matrix whose row space to build.

    Returns
    -------
    VectorSpace
        The span of the matrix's rows.

    Examples
    --------
    >>> A = Matrix([[1, 2], [3, 6]])
    >>> rank(row_space(A))
    1
    """
    return column_space(matrix.transpose())

panchi.algorithms.null_space(matrix)

Construct the null space (kernel) of a matrix.

The null space is the set of all vectors x with matrix @ x == 0. Its basis is extracted parametrically from the reduced row echelon form: one basis vector per free column. When the matrix has full column rank the null space is trivial and is represented by the zero vector (rank 0).

Parameters:

Name Type Description Default
matrix Matrix

The matrix whose null space to build.

required

Returns:

Type Description
VectorSpace

The kernel of the matrix. rank(null_space(A)) == nullity(A).

Examples:

>>> A = Matrix([[1, 1], [1, 1]])
>>> rank(null_space(A))
1
Source code in panchi/algorithms/vector_space_operations.py
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
def null_space(matrix: Matrix) -> VectorSpace:
    """
    Construct the null space (kernel) of a matrix.

    The null space is the set of all vectors x with ``matrix @ x == 0``. Its
    basis is extracted parametrically from the reduced row echelon form: one
    basis vector per free column. When the matrix has full column rank the
    null space is trivial and is represented by the zero vector (rank 0).

    Parameters
    ----------
    matrix : Matrix
        The matrix whose null space to build.

    Returns
    -------
    VectorSpace
        The kernel of the matrix. ``rank(null_space(A)) == nullity(A)``.

    Examples
    --------
    >>> A = Matrix([[1, 1], [1, 1]])
    >>> rank(null_space(A))
    1
    """
    null_vectors = _null_space_basis(rref(matrix))
    if not null_vectors:
        return VectorSpace([zero_vector(matrix.cols)])
    return VectorSpace(null_vectors)

Result types

panchi.algorithms.Reduction

The result of a row reduction performed on a matrix.

Stores the original matrix, the reduced form, every row operation applied as an ordered sequence of RowOperation objects, the pivot positions, and whether the result is in REF or RREF.

Parameters:

Name Type Description Default
original Matrix

The matrix before any row operations were applied.

required
result Matrix

The matrix after all row operations have been applied.

required
steps list[RowOperation]

The ordered sequence of elementary row operations that transforms original into result.

required
pivots list[tuple[int, int]]

The (row, col) positions of each pivot, in order of discovery.

required
form str

Either 'REF' or 'RREF', indicating which reduced form was computed.

required

Examples:

>>> A = Matrix([[1, 2], [3, 4]])
>>> reduction = ref(A)
>>> reduction.rank
2
>>> reduction.nullity
0
Source code in panchi/algorithms/results.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
class Reduction:
    """
    The result of a row reduction performed on a matrix.

    Stores the original matrix, the reduced form, every row operation
    applied as an ordered sequence of RowOperation objects, the pivot
    positions, and whether the result is in REF or RREF.

    Parameters
    ----------
    original : Matrix
        The matrix before any row operations were applied.
    result : Matrix
        The matrix after all row operations have been applied.
    steps : list[RowOperation]
        The ordered sequence of elementary row operations that transforms
        original into result.
    pivots : list[tuple[int, int]]
        The (row, col) positions of each pivot, in order of discovery.
    form : str
        Either 'REF' or 'RREF', indicating which reduced form was computed.

    Examples
    --------
    >>> A = Matrix([[1, 2], [3, 4]])
    >>> reduction = ref(A)
    >>> reduction.rank
    2
    >>> reduction.nullity
    0
    """

    def __init__(
        self,
        original: Matrix,
        result: Matrix,
        steps: list[RowOperation],
        pivots: list[tuple[int, int]],
        form: str,
    ) -> None:
        self.original = original
        self.result = result
        self.steps = steps
        self.pivots = pivots
        self.form = form

    @property
    def rank(self) -> int:
        """
        The rank of the matrix, equal to the number of pivot positions.

        Returns
        -------
        int
            Number of pivot positions found during reduction.
        """
        return len(self.pivots)

    @property
    def nullity(self) -> int:
        """
        The nullity of the matrix, equal to columns minus rank.

        By the rank-nullity theorem, rank + nullity equals the number
        of columns of the original matrix.

        Returns
        -------
        int
            Dimension of the null space.
        """
        return self.original.cols - self.rank

    def __str__(self) -> str:
        """
        Return a step-by-step walkthrough of the reduction.

        Shows the operation label and resulting matrix state after each
        step, followed by a summary of pivot positions, rank, and nullity.

        Returns
        -------
        str
            Human-readable reduction walkthrough.

        Examples
        --------
        >>> print(ref(Matrix([[1, 2], [3, 4]])))
        REF of 2×2 matrix — 1 steps, rank 2

        Step 1: R1 -> R1 + (-3.0) * R0
        [[1, 2],
         [0, -2.0]]
        ...
        """
        header: str = (
            f"{self.form} of {self.original.rows}×{self.original.cols} matrix"
            f" — {len(self.steps)} steps, rank {self.rank}\n"
        )

        current: Matrix = self.original.copy()
        steps_str: str = ""
        for i, step in enumerate(self.steps):
            current = step.apply(current)
            steps_str += f"\nStep {i + 1}: {step}\n{current}\n"

        footer: str = (
            f"\nResult:\n{self.result}\n"
            f"\nPivots: {self.pivots}\n"
            f"Rank: {self.rank}  |  Nullity: {self.nullity}"
        )

        return header + steps_str + footer

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this Reduction.

        Returns
        -------
        str
            Compact representation showing form, shape, rank, nullity,
            pivot positions, number of steps, and the result matrix.

        Examples
        --------
        >>> ref(Matrix([[1, 2], [3, 4]]))
        Reduction(form=REF, shape=2×2, rank=2, nullity=0, pivots=[(0, 0), (1, 1)], steps=1)
        [[1, 2],
         [0, -2.0]]
        """
        summary: str = (
            f"Reduction("
            f"form={self.form}, "
            f"shape={self.original.rows}×{self.original.cols}, "
            f"rank={self.rank}, "
            f"nullity={self.nullity}, "
            f"pivots={self.pivots}, "
            f"steps={len(self.steps)})"
        )

        return f"{summary}\n{self.result}"

    def _repr_latex_(self) -> str:
        """Render the reduction as a stacked LaTeX arrow sequence."""
        current = self.original.copy()
        lines = [f"& {matrix_to_latex(current)}"]
        for step in self.steps:
            current = step.apply(current)
            lines.append(
                f"&\\xrightarrow{{{step._latex()}}} {matrix_to_latex(current)}"
            )
        return aligned_to_latex(lines)

nullity property

The nullity of the matrix, equal to columns minus rank.

By the rank-nullity theorem, rank + nullity equals the number of columns of the original matrix.

Returns:

Type Description
int

Dimension of the null space.

rank property

The rank of the matrix, equal to the number of pivot positions.

Returns:

Type Description
int

Number of pivot positions found during reduction.

__repr__()

Return a concise data inspection string for this Reduction.

Returns:

Type Description
str

Compact representation showing form, shape, rank, nullity, pivot positions, number of steps, and the result matrix.

Examples:

>>> ref(Matrix([[1, 2], [3, 4]]))
Reduction(form=REF, shape=2×2, rank=2, nullity=0, pivots=[(0, 0), (1, 1)], steps=1)
[[1, 2],
 [0, -2.0]]
Source code in panchi/algorithms/results.py
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
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this Reduction.

    Returns
    -------
    str
        Compact representation showing form, shape, rank, nullity,
        pivot positions, number of steps, and the result matrix.

    Examples
    --------
    >>> ref(Matrix([[1, 2], [3, 4]]))
    Reduction(form=REF, shape=2×2, rank=2, nullity=0, pivots=[(0, 0), (1, 1)], steps=1)
    [[1, 2],
     [0, -2.0]]
    """
    summary: str = (
        f"Reduction("
        f"form={self.form}, "
        f"shape={self.original.rows}×{self.original.cols}, "
        f"rank={self.rank}, "
        f"nullity={self.nullity}, "
        f"pivots={self.pivots}, "
        f"steps={len(self.steps)})"
    )

    return f"{summary}\n{self.result}"

__str__()

Return a step-by-step walkthrough of the reduction.

Shows the operation label and resulting matrix state after each step, followed by a summary of pivot positions, rank, and nullity.

Returns:

Type Description
str

Human-readable reduction walkthrough.

Examples:

>>> print(ref(Matrix([[1, 2], [3, 4]])))
REF of 2×2 matrix — 1 steps, rank 2

Step 1: R1 -> R1 + (-3.0) * R0 [[1, 2], [0, -2.0]] ...

Source code in panchi/algorithms/results.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __str__(self) -> str:
    """
    Return a step-by-step walkthrough of the reduction.

    Shows the operation label and resulting matrix state after each
    step, followed by a summary of pivot positions, rank, and nullity.

    Returns
    -------
    str
        Human-readable reduction walkthrough.

    Examples
    --------
    >>> print(ref(Matrix([[1, 2], [3, 4]])))
    REF of 2×2 matrix — 1 steps, rank 2

    Step 1: R1 -> R1 + (-3.0) * R0
    [[1, 2],
     [0, -2.0]]
    ...
    """
    header: str = (
        f"{self.form} of {self.original.rows}×{self.original.cols} matrix"
        f" — {len(self.steps)} steps, rank {self.rank}\n"
    )

    current: Matrix = self.original.copy()
    steps_str: str = ""
    for i, step in enumerate(self.steps):
        current = step.apply(current)
        steps_str += f"\nStep {i + 1}: {step}\n{current}\n"

    footer: str = (
        f"\nResult:\n{self.result}\n"
        f"\nPivots: {self.pivots}\n"
        f"Rank: {self.rank}  |  Nullity: {self.nullity}"
    )

    return header + steps_str + footer

panchi.algorithms.LUDecomposition

The result of an LU decomposition with row swaps.

Stores the original matrix, the lower triangular matrix L, the upper triangular matrix U, and the permutation matrix P encoding any row swaps applied during elimination. The decomposition satisfies P @ original == L @ U.

A row swap happens only when the current pivot is zero. The swaps are recorded in P so that the factorisation relationship is exact.

Parameters:

Name Type Description Default
original Matrix

The square matrix that was decomposed.

required
lower Matrix

The lower triangular matrix L with ones on the diagonal.

required
upper Matrix

The upper triangular matrix U produced by Gaussian elimination on P @ original.

required
permutation Matrix

The permutation matrix P encoding all row swaps performed, satisfying P @ original == L @ U.

required
steps list[RowOperation]

The ordered sequence of row operations applied to P @ original to produce U.

required

Examples:

>>> A = Matrix([[2, 1], [4, 3]])
>>> decomp = lu(A)
>>> decomp.lower @ decomp.upper == decomp.permutation @ A
True
Source code in panchi/algorithms/results.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
class LUDecomposition:
    """
    The result of an LU decomposition with row swaps.

    Stores the original matrix, the lower triangular matrix L, the upper
    triangular matrix U, and the permutation matrix P encoding any row
    swaps applied during elimination. The decomposition satisfies
    P @ original == L @ U.

    A row swap happens only when the current pivot is zero. The swaps are
    recorded in P so that the factorisation relationship is exact.

    Parameters
    ----------
    original : Matrix
        The square matrix that was decomposed.
    lower : Matrix
        The lower triangular matrix L with ones on the diagonal.
    upper : Matrix
        The upper triangular matrix U produced by Gaussian elimination
        on P @ original.
    permutation : Matrix
        The permutation matrix P encoding all row swaps performed,
        satisfying P @ original == L @ U.
    steps : list[RowOperation]
        The ordered sequence of row operations applied to P @ original
        to produce U.

    Examples
    --------
    >>> A = Matrix([[2, 1], [4, 3]])
    >>> decomp = lu(A)
    >>> decomp.lower @ decomp.upper == decomp.permutation @ A
    True
    """

    def __init__(
        self,
        original: Matrix,
        lower: Matrix,
        upper: Matrix,
        permutation: Matrix,
        steps: list[RowOperation],
    ) -> None:
        self.original = original
        self.lower = lower
        self.upper = upper
        self.permutation = permutation
        self.steps = steps

    def __str__(self) -> str:
        """
        Return a readable summary of the LU decomposition.

        Shows P, L, and U individually and states the factorisation
        relationship P @ A = L @ U.

        Returns
        -------
        str
            Human-readable decomposition summary.

        Examples
        --------
        >>> print(lu(Matrix([[2, 1], [4, 3]])))
        LU decomposition of 2×2 matrix — 1 steps

        P @ A = L @ U

        P:
        [[1, 0],
         [0, 1]]

        A:
        [[2, 1],
         [4, 3]]

        L:
        [[1, 0],
         [2.0, 1]]

        U:
        [[2, 1],
         [0.0, 1.0]]
        """
        header: str = (
            f"LU decomposition of "
            f"{self.original.rows}×{self.original.cols} matrix"
            f" — {len(self.steps)} steps\n"
        )

        body: str = (
            f"\nP @ A = L @ U\n"
            f"\nP:\n{self.permutation}\n"
            f"\nA:\n{self.original}\n"
            f"\nL:\n{self.lower}\n"
            f"\nU:\n{self.upper}"
        )

        return header + body

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this LUDecomposition.

        Returns
        -------
        str
            Compact representation showing shape and number of steps.

        Examples
        --------
        >>> lu(Matrix([[2, 1], [4, 3]]))
        LUDecomposition(shape=2×2, steps=1)
        """
        return (
            f"LUDecomposition("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"steps={len(self.steps)})"
        )

    def _repr_latex_(self) -> str:
        """Render the factorization ``A = LU`` (or ``PA = LU`` when pivoted)."""
        n = self.permutation.rows
        is_identity = all(
            self.permutation[i, j] == (1 if i == j else 0)
            for i in range(n)
            for j in range(n)
        )
        rhs = f"{matrix_to_latex(self.lower)}\\,{matrix_to_latex(self.upper)}"
        if is_identity:
            return f"$${matrix_to_latex(self.original)} = {rhs}$$"
        return (
            f"$$P\\,{matrix_to_latex(self.original)} = {rhs}, \\quad "
            f"P = {matrix_to_latex(self.permutation)}$$"
        )

__repr__()

Return a concise data inspection string for this LUDecomposition.

Returns:

Type Description
str

Compact representation showing shape and number of steps.

Examples:

>>> lu(Matrix([[2, 1], [4, 3]]))
LUDecomposition(shape=2×2, steps=1)
Source code in panchi/algorithms/results.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this LUDecomposition.

    Returns
    -------
    str
        Compact representation showing shape and number of steps.

    Examples
    --------
    >>> lu(Matrix([[2, 1], [4, 3]]))
    LUDecomposition(shape=2×2, steps=1)
    """
    return (
        f"LUDecomposition("
        f"shape={self.original.rows}×{self.original.cols}, "
        f"steps={len(self.steps)})"
    )

__str__()

Return a readable summary of the LU decomposition.

Shows P, L, and U individually and states the factorisation relationship P @ A = L @ U.

Returns:

Type Description
str

Human-readable decomposition summary.

Examples:

>>> print(lu(Matrix([[2, 1], [4, 3]])))
LU decomposition of 2×2 matrix — 1 steps

P @ A = L @ U

P: [[1, 0], [0, 1]]

A: [[2, 1], [4, 3]]

L: [[1, 0], [2.0, 1]]

U: [[2, 1], [0.0, 1.0]]

Source code in panchi/algorithms/results.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def __str__(self) -> str:
    """
    Return a readable summary of the LU decomposition.

    Shows P, L, and U individually and states the factorisation
    relationship P @ A = L @ U.

    Returns
    -------
    str
        Human-readable decomposition summary.

    Examples
    --------
    >>> print(lu(Matrix([[2, 1], [4, 3]])))
    LU decomposition of 2×2 matrix — 1 steps

    P @ A = L @ U

    P:
    [[1, 0],
     [0, 1]]

    A:
    [[2, 1],
     [4, 3]]

    L:
    [[1, 0],
     [2.0, 1]]

    U:
    [[2, 1],
     [0.0, 1.0]]
    """
    header: str = (
        f"LU decomposition of "
        f"{self.original.rows}×{self.original.cols} matrix"
        f" — {len(self.steps)} steps\n"
    )

    body: str = (
        f"\nP @ A = L @ U\n"
        f"\nP:\n{self.permutation}\n"
        f"\nA:\n{self.original}\n"
        f"\nL:\n{self.lower}\n"
        f"\nU:\n{self.upper}"
    )

    return header + body

panchi.algorithms.QRDecomposition

The result of a (thin) QR decomposition via Gram-Schmidt.

Stores the original matrix, the matrix Q with orthonormal columns, the upper triangular matrix R, and the ordered list of Gram-Schmidt steps used to build Q. The decomposition satisfies original == Q @ R.

Q is formed by orthonormalizing the columns of the original matrix, so its columns are an orthonormal basis for the column space. R = Qᵀ @ A is upper triangular and its diagonal entries record how much of each column survived orthogonalization. The recorded steps expose the column-by-column derivation of Q, mirroring how a Reduction exposes its row operations.

Parameters:

Name Type Description Default
original Matrix

The matrix that was decomposed, with linearly independent columns.

required
q Matrix

The matrix with orthonormal columns.

required
r Matrix

The upper triangular matrix satisfying original == q @ r.

required
steps list[GramSchmidtStep]

The ordered Gram-Schmidt steps, one per column, used to build Q.

required

Examples:

>>> A = Matrix([[1, 0], [0, 1]])
>>> decomp = qr_decomposition(A)
>>> decomp.q @ decomp.r == A
True
Source code in panchi/algorithms/results.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
class QRDecomposition:
    """
    The result of a (thin) QR decomposition via Gram-Schmidt.

    Stores the original matrix, the matrix Q with orthonormal columns, the
    upper triangular matrix R, and the ordered list of Gram-Schmidt steps
    used to build Q. The decomposition satisfies original == Q @ R.

    Q is formed by orthonormalizing the columns of the original matrix, so
    its columns are an orthonormal basis for the column space. R = Qᵀ @ A is
    upper triangular and its diagonal entries record how much of each column
    survived orthogonalization. The recorded steps expose the column-by-column
    derivation of Q, mirroring how a Reduction exposes its row operations.

    Parameters
    ----------
    original : Matrix
        The matrix that was decomposed, with linearly independent columns.
    q : Matrix
        The matrix with orthonormal columns.
    r : Matrix
        The upper triangular matrix satisfying original == q @ r.
    steps : list[GramSchmidtStep]
        The ordered Gram-Schmidt steps, one per column, used to build Q.

    Examples
    --------
    >>> A = Matrix([[1, 0], [0, 1]])
    >>> decomp = qr_decomposition(A)
    >>> decomp.q @ decomp.r == A
    True
    """

    def __init__(
        self,
        original: Matrix,
        q: Matrix,
        r: Matrix,
        steps: list,
    ) -> None:
        self.original = original
        self.q = q
        self.r = r
        self.steps = steps

    def __str__(self) -> str:
        """
        Return a readable summary of the QR decomposition.

        Shows the column-by-column Gram-Schmidt walkthrough, then Q and R
        individually, and states the factorisation relationship A = Q @ R.

        Returns
        -------
        str
            Human-readable decomposition summary.
        """
        header: str = (
            f"QR decomposition of "
            f"{self.original.rows}×{self.original.cols} matrix"
            f" — {len(self.steps)} steps\n"
        )

        steps_str: str = ""
        for step in self.steps:
            steps_str += f"\n{step}\n"

        body: str = (
            f"\nA = Q @ R\n"
            f"\nA:\n{self.original}\n"
            f"\nQ:\n{self.q}\n"
            f"\nR:\n{self.r}"
        )

        return header + steps_str + body

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this QRDecomposition.

        Returns
        -------
        str
            Compact representation showing shape and number of steps.

        Examples
        --------
        >>> qr_decomposition(Matrix([[1, 0], [0, 1]]))
        QRDecomposition(shape=2×2, steps=2)
        """
        return (
            f"QRDecomposition("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"steps={len(self.steps)})"
        )

    def _repr_latex_(self) -> str:
        """Render the factorization ``A = QR`` in LaTeX."""
        return (
            f"$${matrix_to_latex(self.original)} = "
            f"{matrix_to_latex(self.q)}\\,{matrix_to_latex(self.r)}$$"
        )

__repr__()

Return a concise data inspection string for this QRDecomposition.

Returns:

Type Description
str

Compact representation showing shape and number of steps.

Examples:

>>> qr_decomposition(Matrix([[1, 0], [0, 1]]))
QRDecomposition(shape=2×2, steps=2)
Source code in panchi/algorithms/results.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this QRDecomposition.

    Returns
    -------
    str
        Compact representation showing shape and number of steps.

    Examples
    --------
    >>> qr_decomposition(Matrix([[1, 0], [0, 1]]))
    QRDecomposition(shape=2×2, steps=2)
    """
    return (
        f"QRDecomposition("
        f"shape={self.original.rows}×{self.original.cols}, "
        f"steps={len(self.steps)})"
    )

__str__()

Return a readable summary of the QR decomposition.

Shows the column-by-column Gram-Schmidt walkthrough, then Q and R individually, and states the factorisation relationship A = Q @ R.

Returns:

Type Description
str

Human-readable decomposition summary.

Source code in panchi/algorithms/results.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
def __str__(self) -> str:
    """
    Return a readable summary of the QR decomposition.

    Shows the column-by-column Gram-Schmidt walkthrough, then Q and R
    individually, and states the factorisation relationship A = Q @ R.

    Returns
    -------
    str
        Human-readable decomposition summary.
    """
    header: str = (
        f"QR decomposition of "
        f"{self.original.rows}×{self.original.cols} matrix"
        f" — {len(self.steps)} steps\n"
    )

    steps_str: str = ""
    for step in self.steps:
        steps_str += f"\n{step}\n"

    body: str = (
        f"\nA = Q @ R\n"
        f"\nA:\n{self.original}\n"
        f"\nQ:\n{self.q}\n"
        f"\nR:\n{self.r}"
    )

    return header + steps_str + body

panchi.algorithms.InverseResult

The result of a matrix inversion via Gauss-Jordan elimination.

Stores the original matrix, its inverse, and the row operations applied during reduction of the augmented matrix [A | I]. The inverse satisfies original @ inverse == identity(n) == inverse @ original.

Parameters:

Name Type Description Default
original Matrix

The square invertible matrix that was inverted.

required
inverse Matrix

The inverse of the original matrix.

required
steps list[RowOperation]

The ordered sequence of row operations applied to the augmented matrix [A | I] to produce [I | A⁻¹].

required

Examples:

>>> A = Matrix([[1, 2], [3, 4]])
>>> result = inverse(A)
>>> result.original @ result.inverse == identity(2)
True
Source code in panchi/algorithms/results.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
class InverseResult:
    """
    The result of a matrix inversion via Gauss-Jordan elimination.

    Stores the original matrix, its inverse, and the row operations applied
    during reduction of the augmented matrix [A | I]. The inverse satisfies
    original @ inverse == identity(n) == inverse @ original.

    Parameters
    ----------
    original : Matrix
        The square invertible matrix that was inverted.
    inverse : Matrix
        The inverse of the original matrix.
    steps : list[RowOperation]
        The ordered sequence of row operations applied to the augmented
        matrix [A | I] to produce [I | A⁻¹].

    Examples
    --------
    >>> A = Matrix([[1, 2], [3, 4]])
    >>> result = inverse(A)
    >>> result.original @ result.inverse == identity(2)
    True
    """

    def __init__(
        self,
        original: Matrix,
        inverse: Matrix,
        steps: list[RowOperation],
    ) -> None:
        self.original = original
        self.inverse = inverse
        self.steps = steps

    def __str__(self) -> str:
        """
        Return a readable summary of the inversion.

        Shows the number of steps taken and the computed inverse matrix.

        Returns
        -------
        str
            Human-readable inversion summary.

        Examples
        --------
        >>> print(inverse(Matrix([[1, 2], [3, 4]])))
        Inverse of 2×2 matrix — 6 steps

        Inverse:
        [[-2.0, 1.0],
         [1.5, -0.5]]
        """
        header: str = (
            f"Inverse of {self.original.rows}×{self.original.cols} matrix"
            f" — {len(self.steps)} steps\n"
        )

        return header + f"\nInverse:\n{self.inverse}"

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this InverseResult.

        Returns
        -------
        str
            Compact representation showing shape, number of steps,
            and the inverse matrix.

        Examples
        --------
        >>> inverse(Matrix([[1, 2], [3, 4]]))
        InverseResult(shape=2×2, steps=6)
        [[-2.0, 1.0],
         [1.5, -0.5]]
        """
        summary: str = (
            f"InverseResult("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"steps={len(self.steps)})"
        )

        return f"{summary}\n{self.inverse}"

    def _repr_latex_(self) -> str:
        """Render ``A^{-1} = ...`` in LaTeX."""
        return (
            f"$${matrix_to_latex(self.original)}^{{-1}} = "
            f"{matrix_to_latex(self.inverse)}$$"
        )

__repr__()

Return a concise data inspection string for this InverseResult.

Returns:

Type Description
str

Compact representation showing shape, number of steps, and the inverse matrix.

Examples:

>>> inverse(Matrix([[1, 2], [3, 4]]))
InverseResult(shape=2×2, steps=6)
[[-2.0, 1.0],
 [1.5, -0.5]]
Source code in panchi/algorithms/results.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this InverseResult.

    Returns
    -------
    str
        Compact representation showing shape, number of steps,
        and the inverse matrix.

    Examples
    --------
    >>> inverse(Matrix([[1, 2], [3, 4]]))
    InverseResult(shape=2×2, steps=6)
    [[-2.0, 1.0],
     [1.5, -0.5]]
    """
    summary: str = (
        f"InverseResult("
        f"shape={self.original.rows}×{self.original.cols}, "
        f"steps={len(self.steps)})"
    )

    return f"{summary}\n{self.inverse}"

__str__()

Return a readable summary of the inversion.

Shows the number of steps taken and the computed inverse matrix.

Returns:

Type Description
str

Human-readable inversion summary.

Examples:

>>> print(inverse(Matrix([[1, 2], [3, 4]])))
Inverse of 2×2 matrix — 6 steps

Inverse: [[-2.0, 1.0], [1.5, -0.5]]

Source code in panchi/algorithms/results.py
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
def __str__(self) -> str:
    """
    Return a readable summary of the inversion.

    Shows the number of steps taken and the computed inverse matrix.

    Returns
    -------
    str
        Human-readable inversion summary.

    Examples
    --------
    >>> print(inverse(Matrix([[1, 2], [3, 4]])))
    Inverse of 2×2 matrix — 6 steps

    Inverse:
    [[-2.0, 1.0],
     [1.5, -0.5]]
    """
    header: str = (
        f"Inverse of {self.original.rows}×{self.original.cols} matrix"
        f" — {len(self.steps)} steps\n"
    )

    return header + f"\nInverse:\n{self.inverse}"

panchi.algorithms.CofactorExpansion

The determinant of a square matrix computed by cofactor expansion.

Expanding along row i gives det(A) = Σ_j (-1)^(i+j) · a_ij · det(M_ij), and along column j gives det(A) = Σ_i (-1)^(i+j) · a_ij · det(M_ij). Every term is kept, including those whose entry is zero, so the derivation can be read off directly.

Parameters:

Name Type Description Default
original Matrix

The square matrix whose determinant was computed.

required
along str

"row" or "column".

required
index int

The row or column expanded along (0-based).

required
terms list[CofactorTerm]

One term per entry of that row or column, in order.

required

Examples:

>>> result = cofactor_expansion(Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 4]]))
>>> result.determinant
18
>>> [term.value for term in result.terms]
[22, -4, 0]
Source code in panchi/algorithms/results.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class CofactorExpansion:
    """
    The determinant of a square matrix computed by cofactor expansion.

    Expanding along row i gives det(A) = Σ_j (-1)^(i+j) · a_ij · det(M_ij),
    and along column j gives det(A) = Σ_i (-1)^(i+j) · a_ij · det(M_ij). Every
    term is kept, including those whose entry is zero, so the derivation can
    be read off directly.

    Parameters
    ----------
    original : Matrix
        The square matrix whose determinant was computed.
    along : str
        "row" or "column".
    index : int
        The row or column expanded along (0-based).
    terms : list[CofactorTerm]
        One term per entry of that row or column, in order.

    Examples
    --------
    >>> result = cofactor_expansion(Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 4]]))
    >>> result.determinant
    18
    >>> [term.value for term in result.terms]
    [22, -4, 0]
    """

    def __init__(
        self,
        original: Matrix,
        along: str,
        index: int,
        terms: list[CofactorTerm],
    ) -> None:
        self.original = original
        self.along = along
        self.index = index
        self.terms = terms

    @property
    def determinant(self) -> Scalar:
        """det(A), the sum of every term."""
        return sum(term.value for term in self.terms)

    def __str__(self) -> str:
        """
        Return the expansion written out term by term.

        Examples
        --------
        >>> print(cofactor_expansion(Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 4]])))
        Cofactor expansion of 3×3 matrix along row 0
          (+1) · 2 · 11 = 22
          (-1) · 1 · 4 = -4
          (+1) · 0 · 1 = 0
        det(A) = 18
        """
        lines = [
            f"Cofactor expansion of {self.original.rows}×{self.original.cols} "
            f"matrix along {self.along} {self.index}"
        ]
        for term in self.terms:
            lines.append(
                f"  ({term.sign:+d}) · {_factor(term.entry)} · "
                f"{_factor(term.minor_determinant)} = {term.value}"
            )
        lines.append(f"det(A) = {self.determinant}")
        return "\n".join(lines)

    def __repr__(self) -> str:
        return (
            f"CofactorExpansion("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"along={self.along} {self.index}, "
            f"determinant={self.determinant})"
        )

    def _repr_latex_(self) -> str:
        """Render the expansion with each minor drawn as a determinant."""
        expanded = " + ".join(
            f"({term.sign:+d})\\,({scalar_to_latex(term.entry)})"
            f"{matrix_to_latex(term.minor, 'vmatrix')}"
            for term in self.terms
        )
        evaluated = " + ".join(
            f"({term.sign:+d})({scalar_to_latex(term.entry)})"
            f"({scalar_to_latex(term.minor_determinant)})"
            for term in self.terms
        )
        return aligned_to_latex(
            [
                f"{matrix_to_latex(self.original, 'vmatrix')} &= {expanded}",
                f"&= {evaluated}",
                f"&= {scalar_to_latex(self.determinant)}",
            ]
        )

determinant property

det(A), the sum of every term.

__str__()

Return the expansion written out term by term.

Examples:

>>> print(cofactor_expansion(Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 4]])))
Cofactor expansion of 3×3 matrix along row 0
  (+1) · 2 · 11 = 22
  (-1) · 1 · 4 = -4
  (+1) · 0 · 1 = 0
det(A) = 18
Source code in panchi/algorithms/results.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
def __str__(self) -> str:
    """
    Return the expansion written out term by term.

    Examples
    --------
    >>> print(cofactor_expansion(Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 4]])))
    Cofactor expansion of 3×3 matrix along row 0
      (+1) · 2 · 11 = 22
      (-1) · 1 · 4 = -4
      (+1) · 0 · 1 = 0
    det(A) = 18
    """
    lines = [
        f"Cofactor expansion of {self.original.rows}×{self.original.cols} "
        f"matrix along {self.along} {self.index}"
    ]
    for term in self.terms:
        lines.append(
            f"  ({term.sign:+d}) · {_factor(term.entry)} · "
            f"{_factor(term.minor_determinant)} = {term.value}"
        )
    lines.append(f"det(A) = {self.determinant}")
    return "\n".join(lines)

panchi.algorithms.CofactorTerm

One term of a cofactor expansion: (-1)^(i+j) · a_ij · det(M_ij).

Parameters:

Name Type Description Default
row int

The row index i of the entry (0-based).

required
col int

The column index j of the entry (0-based).

required
entry Scalar

The entry a_ij.

required
minor Matrix

M_ij, the matrix left after deleting row i and column j.

required
minor_determinant Scalar

det(M_ij).

required
Source code in panchi/algorithms/results.py
525
526
527
528
529
530
531
532
533
534
535
536
537
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
class CofactorTerm:
    """
    One term of a cofactor expansion: (-1)^(i+j) · a_ij · det(M_ij).

    Parameters
    ----------
    row : int
        The row index i of the entry (0-based).
    col : int
        The column index j of the entry (0-based).
    entry : Scalar
        The entry a_ij.
    minor : Matrix
        M_ij, the matrix left after deleting row i and column j.
    minor_determinant : Scalar
        det(M_ij).
    """

    def __init__(
        self,
        row: int,
        col: int,
        entry: Scalar,
        minor: Matrix,
        minor_determinant: Scalar,
    ) -> None:
        self.row = row
        self.col = col
        self.entry = entry
        self.minor = minor
        self.minor_determinant = minor_determinant

    @property
    def sign(self) -> int:
        """The checkerboard sign (-1)^(i+j)."""
        return (-1) ** (self.row + self.col)

    @property
    def cofactor(self) -> Scalar:
        """The cofactor C_ij = (-1)^(i+j) · det(M_ij)."""
        return self.sign * self.minor_determinant

    @property
    def value(self) -> Scalar:
        """This term's contribution to the determinant, a_ij · C_ij."""
        return self.entry * self.cofactor

    def __repr__(self) -> str:
        return (
            f"CofactorTerm(row={self.row}, col={self.col}, entry={self.entry}, "
            f"minor_determinant={self.minor_determinant})"
        )

cofactor property

The cofactor C_ij = (-1)^(i+j) · det(M_ij).

sign property

The checkerboard sign (-1)^(i+j).

value property

This term's contribution to the determinant, a_ij · C_ij.

panchi.algorithms.DeterminantReduction

The determinant of a square matrix computed by row reduction.

Reduces A to a row echelon form U using only row swaps and row additions. Adding a multiple of one row to another leaves the determinant unchanged and each swap flips its sign, so det(A) = (-1)^swaps · det(U), and det(U) is the product of its diagonal because U is upper triangular.

Parameters:

Name Type Description Default
original Matrix

The square matrix whose determinant was computed.

required
reduction Reduction

The REF reduction of original, with every step applied.

required
swaps int

The number of row swaps among the reduction steps.

required

Examples:

>>> result = determinant_by_reduction(Matrix([[0, 2], [3, 4]]))
>>> result.swaps, result.diagonal, result.determinant
(1, [3, 2], -6)
Source code in panchi/algorithms/results.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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
class DeterminantReduction:
    """
    The determinant of a square matrix computed by row reduction.

    Reduces A to a row echelon form U using only row swaps and row
    additions. Adding a multiple of one row to another leaves the
    determinant unchanged and each swap flips its sign, so
    det(A) = (-1)^swaps · det(U), and det(U) is the product of its diagonal
    because U is upper triangular.

    Parameters
    ----------
    original : Matrix
        The square matrix whose determinant was computed.
    reduction : Reduction
        The REF reduction of original, with every step applied.
    swaps : int
        The number of row swaps among the reduction steps.

    Examples
    --------
    >>> result = determinant_by_reduction(Matrix([[0, 2], [3, 4]]))
    >>> result.swaps, result.diagonal, result.determinant
    (1, [3, 2], -6)
    """

    def __init__(self, original: Matrix, reduction: Reduction, swaps: int) -> None:
        self.original = original
        self.reduction = reduction
        self.swaps = swaps

    @property
    def diagonal(self) -> list[Scalar]:
        """The diagonal entries of the row echelon form U."""
        return [self.reduction.result[i][i] for i in range(self.original.rows)]

    @property
    def determinant(self) -> Scalar:
        """det(A) = (-1)^swaps · (product of the diagonal of U)."""
        product = 1
        for value in self.diagonal:
            product *= value
        return (-1) ** self.swaps * product

    def __str__(self) -> str:
        """
        Return the reduction summary and the final product.

        Examples
        --------
        >>> print(determinant_by_reduction(Matrix([[0, 2], [3, 4]])))
        Determinant of 2×2 matrix by row reduction — 1 step, 1 row swap
        U =
        [[3, 4],
         [0, 2]]
        det(A) = (-1)^1 · 3 · 2 = -6
        """
        product = " · ".join(_factor(value) for value in self.diagonal)
        steps = len(self.reduction.steps)
        return (
            f"Determinant of {self.original.rows}×{self.original.cols} matrix "
            f"by row reduction — {steps} step{'' if steps == 1 else 's'}, "
            f"{self.swaps} row swap{'' if self.swaps == 1 else 's'}\n"
            f"U =\n{self.reduction.result}\n"
            f"det(A) = (-1)^{self.swaps} · {product} = {self.determinant}"
        )

    def __repr__(self) -> str:
        return (
            f"DeterminantReduction("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"swaps={self.swaps}, "
            f"determinant={self.determinant})"
        )

    def _repr_latex_(self) -> str:
        """Render det(A) = (-1)^s det(U) = (-1)^s · d1 · d2 ... = det."""
        product = "".join(f"({scalar_to_latex(value)})" for value in self.diagonal)
        return aligned_to_latex(
            [
                f"{matrix_to_latex(self.original, 'vmatrix')} "
                f"&= (-1)^{{{self.swaps}}}"
                f"{matrix_to_latex(self.reduction.result, 'vmatrix')}",
                f"&= (-1)^{{{self.swaps}}}{product}",
                f"&= {scalar_to_latex(self.determinant)}",
            ]
        )

determinant property

det(A) = (-1)^swaps · (product of the diagonal of U).

diagonal property

The diagonal entries of the row echelon form U.

__str__()

Return the reduction summary and the final product.

Examples:

>>> print(determinant_by_reduction(Matrix([[0, 2], [3, 4]])))
Determinant of 2×2 matrix by row reduction — 1 step, 1 row swap
U =
[[3, 4],
 [0, 2]]
det(A) = (-1)^1 · 3 · 2 = -6
Source code in panchi/algorithms/results.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
def __str__(self) -> str:
    """
    Return the reduction summary and the final product.

    Examples
    --------
    >>> print(determinant_by_reduction(Matrix([[0, 2], [3, 4]])))
    Determinant of 2×2 matrix by row reduction — 1 step, 1 row swap
    U =
    [[3, 4],
     [0, 2]]
    det(A) = (-1)^1 · 3 · 2 = -6
    """
    product = " · ".join(_factor(value) for value in self.diagonal)
    steps = len(self.reduction.steps)
    return (
        f"Determinant of {self.original.rows}×{self.original.cols} matrix "
        f"by row reduction — {steps} step{'' if steps == 1 else 's'}, "
        f"{self.swaps} row swap{'' if self.swaps == 1 else 's'}\n"
        f"U =\n{self.reduction.result}\n"
        f"det(A) = (-1)^{self.swaps} · {product} = {self.determinant}"
    )

panchi.algorithms.CramerResult

The solution of a square system Ax = b by Cramer's rule.

Each unknown is x_i = det(A_i) / det(A), where A_i is A with column i replaced by b. Only defined when det(A) ≠ 0.

Parameters:

Name Type Description Default
original Matrix

The square coefficient matrix A.

required
b Vector

The right-hand side vector.

required
determinant Scalar

det(A), which is non-zero.

required
replaced list[Matrix]

The matrices A_0, A_1, ..., each with one column replaced by b.

required
replaced_determinants list[Scalar]

det(A_i) for each replaced matrix, in order.

required
solution Vector

The unique solution x.

required

Examples:

>>> result = cramer(Matrix([[2, 1], [1, 3]]), Vector([3, 5]))
>>> result.replaced_determinants
[4, 7]
>>> result.solution
[0.8, 1.4]
Source code in panchi/algorithms/results.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
class CramerResult:
    """
    The solution of a square system Ax = b by Cramer's rule.

    Each unknown is x_i = det(A_i) / det(A), where A_i is A with column i
    replaced by b. Only defined when det(A) ≠ 0.

    Parameters
    ----------
    original : Matrix
        The square coefficient matrix A.
    b : Vector
        The right-hand side vector.
    determinant : Scalar
        det(A), which is non-zero.
    replaced : list[Matrix]
        The matrices A_0, A_1, ..., each with one column replaced by b.
    replaced_determinants : list[Scalar]
        det(A_i) for each replaced matrix, in order.
    solution : Vector
        The unique solution x.

    Examples
    --------
    >>> result = cramer(Matrix([[2, 1], [1, 3]]), Vector([3, 5]))
    >>> result.replaced_determinants
    [4, 7]
    >>> result.solution
    [0.8, 1.4]
    """

    def __init__(
        self,
        original: Matrix,
        b: Vector,
        determinant: Scalar,
        replaced: list[Matrix],
        replaced_determinants: list[Scalar],
        solution: Vector,
    ) -> None:
        self.original = original
        self.b = b
        self.determinant = determinant
        self.replaced = replaced
        self.replaced_determinants = replaced_determinants
        self.solution = solution

    def __str__(self) -> str:
        """
        Return each x_i = det(A_i) / det(A) and the solution.

        Examples
        --------
        >>> print(cramer(Matrix([[2, 1], [1, 3]]), Vector([3, 5])))
        Cramer's rule for 2×2 system, det(A) = 5
          x0 = det(A0) / det(A) = 4 / 5 = 0.8
          x1 = det(A1) / det(A) = 7 / 5 = 1.4
        x = [0.8, 1.4]
        """
        lines = [
            f"Cramer's rule for {self.original.rows}×{self.original.cols} system, "
            f"det(A) = {self.determinant}"
        ]
        for i, (value, x) in enumerate(
            zip(self.replaced_determinants, self.solution, strict=True)
        ):
            lines.append(
                f"  x{i} = det(A{i}) / det(A) = {value} / {self.determinant} = {x}"
            )
        lines.append(f"x = {self.solution}")
        return "\n".join(lines)

    def __repr__(self) -> str:
        return (
            f"CramerResult("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"solution={self.solution})"
        )

    def _repr_latex_(self) -> str:
        """Render x_i = |A_i| / |A| = value for every unknown."""
        denominator = matrix_to_latex(self.original, "vmatrix")
        lines = [
            f"x_{{{i}}} &= \\frac{{{matrix_to_latex(matrix, 'vmatrix')}}}"
            f"{{{denominator}}} = "
            f"\\frac{{{scalar_to_latex(value)}}}{{{scalar_to_latex(self.determinant)}}}"
            f" = {scalar_to_latex(x)}"
            for i, (matrix, value, x) in enumerate(
                zip(
                    self.replaced,
                    self.replaced_determinants,
                    self.solution,
                    strict=True,
                )
            )
        ]
        return aligned_to_latex(lines)

__str__()

Return each x_i = det(A_i) / det(A) and the solution.

Examples:

>>> print(cramer(Matrix([[2, 1], [1, 3]]), Vector([3, 5])))
Cramer's rule for 2×2 system, det(A) = 5
  x0 = det(A0) / det(A) = 4 / 5 = 0.8
  x1 = det(A1) / det(A) = 7 / 5 = 1.4
x = [0.8, 1.4]
Source code in panchi/algorithms/results.py
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
def __str__(self) -> str:
    """
    Return each x_i = det(A_i) / det(A) and the solution.

    Examples
    --------
    >>> print(cramer(Matrix([[2, 1], [1, 3]]), Vector([3, 5])))
    Cramer's rule for 2×2 system, det(A) = 5
      x0 = det(A0) / det(A) = 4 / 5 = 0.8
      x1 = det(A1) / det(A) = 7 / 5 = 1.4
    x = [0.8, 1.4]
    """
    lines = [
        f"Cramer's rule for {self.original.rows}×{self.original.cols} system, "
        f"det(A) = {self.determinant}"
    ]
    for i, (value, x) in enumerate(
        zip(self.replaced_determinants, self.solution, strict=True)
    ):
        lines.append(
            f"  x{i} = det(A{i}) / det(A) = {value} / {self.determinant} = {x}"
        )
    lines.append(f"x = {self.solution}")
    return "\n".join(lines)

panchi.algorithms.Solution

The result of solving a linear system Ax = b.

Stores the coefficient matrix A, the right-hand side vector b, the solution status, the solution vector x if a unique solution exists, and the row operations applied during reduction of the augmented matrix [A | b].

The three possible statuses reflect the three fundamentally different outcomes a linear system can have:

  • 'unique': exactly one solution exists, stored in solution.
  • 'infinite': infinitely many solutions exist (underdetermined system).
  • 'inconsistent': no solution exists (the system is contradictory).

Parameters:

Name Type Description Default
original Matrix

The coefficient matrix A.

required
target Vector

The right-hand side vector b.

required
status str

One of 'unique', 'infinite', or 'inconsistent'.

required
solution Vector or None

The unique solution vector x satisfying A @ x == b, or None if the system does not have a unique solution.

required
steps list[RowOperation]

The ordered sequence of row operations applied to the augmented matrix [A | b] during reduction.

required
particular Vector or None

A particular solution for infinite-solution systems. None for unique or inconsistent systems.

None
null_space VectorSpace or None

A basis for the null space of A for infinite-solution systems. None for unique or inconsistent systems.

None

Examples:

>>> A = Matrix([[1, 2], [3, 4]])
>>> b = Vector([5, 6])
>>> result = solve(A, b)
>>> result.status
'unique'
>>> A @ result.solution == b
True
Source code in panchi/algorithms/results.py
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
class Solution:
    """
    The result of solving a linear system Ax = b.

    Stores the coefficient matrix A, the right-hand side vector b, the
    solution status, the solution vector x if a unique solution exists,
    and the row operations applied during reduction of the augmented
    matrix [A | b].

    The three possible statuses reflect the three fundamentally different
    outcomes a linear system can have:

    - 'unique': exactly one solution exists, stored in solution.
    - 'infinite': infinitely many solutions exist (underdetermined system).
    - 'inconsistent': no solution exists (the system is contradictory).

    Parameters
    ----------
    original : Matrix
        The coefficient matrix A.
    target : Vector
        The right-hand side vector b.
    status : str
        One of 'unique', 'infinite', or 'inconsistent'.
    solution : Vector or None
        The unique solution vector x satisfying A @ x == b, or None if
        the system does not have a unique solution.
    steps : list[RowOperation]
        The ordered sequence of row operations applied to the augmented
        matrix [A | b] during reduction.
    particular : Vector or None
        A particular solution for infinite-solution systems. None for
        unique or inconsistent systems.
    null_space : VectorSpace or None
        A basis for the null space of A for infinite-solution systems.
        None for unique or inconsistent systems.

    Examples
    --------
    >>> A = Matrix([[1, 2], [3, 4]])
    >>> b = Vector([5, 6])
    >>> result = solve(A, b)
    >>> result.status
    'unique'
    >>> A @ result.solution == b
    True
    """

    def __init__(
        self,
        original: Matrix,
        target: Vector,
        status: str,
        solution: Vector | None,
        steps: list[RowOperation],
        particular: Vector | None = None,
        null_space: VectorSpace | None = None,
    ) -> None:
        self.original = original
        self.target = target
        self.status = status
        self.solution = solution
        self.steps = steps
        self.particular = particular
        self.null_space = null_space

    def __str__(self) -> str:
        """
        Return a readable summary of the solution.

        Shows the system dimensions, the status, and the solution vector
        if one exists.

        Returns
        -------
        str
            Human-readable solution summary.

        Examples
        --------
        >>> print(solve(Matrix([[1, 2], [3, 4]]), Vector([5, 6])))
        Solution to 2×2 system — unique

        x = [-4.0, 4.5]
        """
        header: str = (
            f"Solution to "
            f"{self.original.rows}×{self.original.cols} system"
            f" — {self.status}\n"
        )

        if self.solution is not None:
            return header + f"\nx = {self.solution}"

        if self.particular is not None and self.null_space is not None:
            return header + "\n" + self._general_solution(latex=False)

        return header

    def _general_solution(self, latex: bool) -> str:
        basis = list(self.null_space)
        n = len(basis)

        if n == 1:
            params = ["t"]
        elif n == 2:
            params = ["s", "t"]
        else:
            params = [f"t_{{{i + 1}}}" if latex else f"t{i + 1}" for i in range(n)]

        render = vector_to_latex if latex else str
        times = "\\," if latex else "·"
        parts = []
        if any(x != 0 for x in self.particular):
            parts.append(render(self.particular))
        for param, vec in zip(params, basis, strict=False):
            parts.append(f"{param}{times}{render(vec)}")

        return "x = " + " + ".join(parts)

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this Solution.

        Returns
        -------
        str
            Compact representation showing shape, status, and solution.

        Examples
        --------
        >>> solve(Matrix([[1, 2], [3, 4]]), Vector([5, 6]))
        Solution(shape=2×2, status=unique, solution=[-4.0, 4.5])
        """
        return (
            f"Solution("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"status={self.status}, "
            f"solution={self.solution})"
        )

    def _repr_latex_(self) -> str:
        """Render the solution (unique vector or general solution) in LaTeX."""
        if self.solution is not None:
            return f"$x = {vector_to_latex(self.solution)}$"
        if self.particular is not None and self.null_space is not None:
            return f"$${self._general_solution(latex=True)}$$"
        return "$\\text{No solution (inconsistent system).}$"

__repr__()

Return a concise data inspection string for this Solution.

Returns:

Type Description
str

Compact representation showing shape, status, and solution.

Examples:

>>> solve(Matrix([[1, 2], [3, 4]]), Vector([5, 6]))
Solution(shape=2×2, status=unique, solution=[-4.0, 4.5])
Source code in panchi/algorithms/results.py
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this Solution.

    Returns
    -------
    str
        Compact representation showing shape, status, and solution.

    Examples
    --------
    >>> solve(Matrix([[1, 2], [3, 4]]), Vector([5, 6]))
    Solution(shape=2×2, status=unique, solution=[-4.0, 4.5])
    """
    return (
        f"Solution("
        f"shape={self.original.rows}×{self.original.cols}, "
        f"status={self.status}, "
        f"solution={self.solution})"
    )

__str__()

Return a readable summary of the solution.

Shows the system dimensions, the status, and the solution vector if one exists.

Returns:

Type Description
str

Human-readable solution summary.

Examples:

>>> print(solve(Matrix([[1, 2], [3, 4]]), Vector([5, 6])))
Solution to 2×2 system — unique

x = [-4.0, 4.5]

Source code in panchi/algorithms/results.py
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
def __str__(self) -> str:
    """
    Return a readable summary of the solution.

    Shows the system dimensions, the status, and the solution vector
    if one exists.

    Returns
    -------
    str
        Human-readable solution summary.

    Examples
    --------
    >>> print(solve(Matrix([[1, 2], [3, 4]]), Vector([5, 6])))
    Solution to 2×2 system — unique

    x = [-4.0, 4.5]
    """
    header: str = (
        f"Solution to "
        f"{self.original.rows}×{self.original.cols} system"
        f" — {self.status}\n"
    )

    if self.solution is not None:
        return header + f"\nx = {self.solution}"

    if self.particular is not None and self.null_space is not None:
        return header + "\n" + self._general_solution(latex=False)

    return header

panchi.algorithms.EigenResult

The exact eigenvalues and eigenspaces of a 2×2 or 3×3 matrix.

Built the way eigenvalues are found by hand: the characteristic polynomial det(A - λI) is computed exactly, its roots are the eigenvalues, and each eigenspace is the null space of A - λI. Every value is exact: rational eigenvalues are ints or Fractions, and irrational or complex ones are QuadraticNumbers such as (1 + √5)/2 or 1 - 2i.

Parameters:

Name Type Description Default
original Matrix

The square matrix whose eigenvalues were computed.

required
characteristic_polynomial Polynomial

The polynomial det(A - λI), written in powers of λ.

required
eigenvalues list[Scalar]

The distinct eigenvalues: real ones in increasing order, then complex ones.

required
algebraic_multiplicities list[int]

How many times each eigenvalue is a root of the characteristic polynomial, paired by index with eigenvalues.

required
eigenspaces list[VectorSpace]

The eigenspace of each eigenvalue, paired by index with eigenvalues. Each is spanned by a basis of eigenvectors scaled to avoid fractions.

required

Examples:

>>> result = eigen(Matrix([[2, 1], [1, 2]]))
>>> result.eigenvalues
[1, 3]
>>> print(result.characteristic_polynomial)
λ² - 4λ + 3
Source code in panchi/algorithms/results.py
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
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
1352
1353
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
class EigenResult:
    """
    The exact eigenvalues and eigenspaces of a 2×2 or 3×3 matrix.

    Built the way eigenvalues are found by hand: the characteristic
    polynomial det(A - λI) is computed exactly, its roots are the
    eigenvalues, and each eigenspace is the null space of A - λI. Every
    value is exact: rational eigenvalues are ints or Fractions, and
    irrational or complex ones are QuadraticNumbers such as (1 + √5)/2 or
    1 - 2i.

    Parameters
    ----------
    original : Matrix
        The square matrix whose eigenvalues were computed.
    characteristic_polynomial : Polynomial
        The polynomial det(A - λI), written in powers of λ.
    eigenvalues : list[Scalar]
        The distinct eigenvalues: real ones in increasing order, then
        complex ones.
    algebraic_multiplicities : list[int]
        How many times each eigenvalue is a root of the characteristic
        polynomial, paired by index with eigenvalues.
    eigenspaces : list[VectorSpace]
        The eigenspace of each eigenvalue, paired by index with
        eigenvalues. Each is spanned by a basis of eigenvectors scaled to
        avoid fractions.

    Examples
    --------
    >>> result = eigen(Matrix([[2, 1], [1, 2]]))
    >>> result.eigenvalues
    [1, 3]
    >>> print(result.characteristic_polynomial)
    λ² - 4λ + 3
    """

    def __init__(
        self,
        original: Matrix,
        characteristic_polynomial: Polynomial,
        eigenvalues: list[Scalar],
        algebraic_multiplicities: list[int],
        eigenspaces: list[VectorSpace],
    ) -> None:
        self.original = original
        self.characteristic_polynomial = characteristic_polynomial
        self.eigenvalues = eigenvalues
        self.algebraic_multiplicities = algebraic_multiplicities
        self.eigenspaces = eigenspaces

    @property
    def geometric_multiplicities(self) -> list[int]:
        """
        The dimension of each eigenspace, paired by index with eigenvalues.

        The geometric multiplicity is never larger than the algebraic one.
        When it is smaller for some eigenvalue, the matrix is defective.
        """
        return [len(space) for space in self.eigenspaces]

    @property
    def is_diagonalizable(self) -> bool:
        """
        Whether the matrix can be written as P D P⁻¹ with D diagonal.

        True exactly when every eigenvalue's geometric multiplicity equals
        its algebraic multiplicity, so that the eigenvectors form a basis.
        Complex eigenvalues count: a rotation is diagonalizable over ℂ.
        """
        return self.geometric_multiplicities == self.algebraic_multiplicities

    @property
    def has_complex_eigenvalues(self) -> bool:
        """Whether any eigenvalue has a non-zero imaginary part."""
        return any(
            isinstance(value, QuadraticNumber) and not value.is_real
            for value in self.eigenvalues
        )

    @property
    def pairs(self) -> list[tuple[Scalar, Vector]]:
        """
        Every (eigenvalue, eigenvector) pair from the eigenspace bases.

        An eigenvalue with a two-dimensional eigenspace contributes two
        pairs, one for each basis vector.
        """
        return [
            (value, vector)
            for value, space in zip(self.eigenvalues, self.eigenspaces, strict=True)
            for vector in space
        ]

    def diagonalization(self) -> tuple[Matrix, Matrix]:
        """
        Return P and D with A = P D P⁻¹.

        The columns of P are the eigenvectors and D holds the matching
        eigenvalues on its diagonal, in the same order.

        Returns
        -------
        tuple[Matrix, Matrix]
            The eigenvector matrix P and the diagonal matrix D.

        Raises
        ------
        ValueError
            If the matrix is defective (not diagonalizable).

        Examples
        --------
        >>> p, d = eigen(Matrix([[2, 1], [1, 2]])).diagonalization()
        >>> print(d)
        [[1, 0],
         [0, 3]]
        """
        if not self.is_diagonalizable:
            shortfalls = [
                f"λ = {value} appears {alg} times but has only {geo} "
                f"independent eigenvector{'s' if geo != 1 else ''}"
                for value, alg, geo in zip(
                    self.eigenvalues,
                    self.algebraic_multiplicities,
                    self.geometric_multiplicities,
                    strict=True,
                )
                if alg != geo
            ]
            raise ValueError(
                "This matrix is not diagonalizable: "
                + "; ".join(shortfalls)
                + ". There are not enough independent eigenvectors to build "
                "an invertible P."
            )
        pairs = self.pairs
        p = vector_column_matrix([vector for _, vector in pairs])
        d = diagonal([value for value, _ in pairs])
        return p, d

    def _factored(self, latex: bool) -> str:
        variable = "\\lambda" if latex else self.characteristic_polynomial.variable
        sign = "-" if self.characteristic_polynomial.leading_coefficient < 0 else ""
        return sign + "".join(
            _power(_linear_factor(value, variable, latex), count, latex)
            for value, count in zip(
                self.eigenvalues, self.algebraic_multiplicities, strict=True
            )
        )

    def __str__(self) -> str:
        """
        Return the full by-hand derivation of the eigenvalues.

        Shows the characteristic polynomial and its factored form, then
        each eigenvalue with its multiplicities and eigenspace basis, and
        finally whether the matrix is diagonalizable.
        """
        n = self.original.rows
        lines = [
            f"Eigenvalues of {n}×{n} matrix",
            f"det(A - λI) = {self.characteristic_polynomial} = {self._factored(False)}",
            "",
        ]
        for value, alg, geo, space in zip(
            self.eigenvalues,
            self.algebraic_multiplicities,
            self.geometric_multiplicities,
            self.eigenspaces,
            strict=True,
        ):
            lines.append(
                f"λ = {value}  (algebraic multiplicity {alg}, "
                f"geometric multiplicity {geo})"
            )
            lines.extend(f"  v = {vector}" for vector in space)
        lines.append("")
        if self.is_diagonalizable:
            lines.append("Diagonalizable: yes")
        else:
            lines.append("Diagonalizable: no (not enough independent eigenvectors)")
        return "\n".join(lines)

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this EigenResult.

        Examples
        --------
        >>> eigen(Matrix([[2, 1], [1, 2]]))
        EigenResult(shape=2×2, eigenvalues=[1, 3], diagonalizable=True)
        """
        values = ", ".join(str(v) for v in self.eigenvalues)
        return (
            f"EigenResult(shape={self.original.rows}×{self.original.cols}, "
            f"eigenvalues=[{values}], diagonalizable={self.is_diagonalizable})"
        )

    def _repr_latex_(self) -> str:
        """Render the characteristic polynomial and eigenspaces in LaTeX."""
        lines = [
            f"\\det(A - \\lambda I) &= {self.characteristic_polynomial._latex()} "
            f"= {self._factored(True)}"
        ]
        for i, (value, space) in enumerate(
            zip(self.eigenvalues, self.eigenspaces, strict=True)
        ):
            lines.append(
                f"\\lambda_{{{i + 1}}} &= {scalar_to_latex(value)}, "
                f"\\quad E_{{\\lambda_{{{i + 1}}}}} = {span_to_latex(space)}"
            )
        return aligned_to_latex(lines)

geometric_multiplicities property

The dimension of each eigenspace, paired by index with eigenvalues.

The geometric multiplicity is never larger than the algebraic one. When it is smaller for some eigenvalue, the matrix is defective.

has_complex_eigenvalues property

Whether any eigenvalue has a non-zero imaginary part.

is_diagonalizable property

Whether the matrix can be written as P D P⁻¹ with D diagonal.

True exactly when every eigenvalue's geometric multiplicity equals its algebraic multiplicity, so that the eigenvectors form a basis. Complex eigenvalues count: a rotation is diagonalizable over ℂ.

pairs property

Every (eigenvalue, eigenvector) pair from the eigenspace bases.

An eigenvalue with a two-dimensional eigenspace contributes two pairs, one for each basis vector.

__repr__()

Return a concise data inspection string for this EigenResult.

Examples:

>>> eigen(Matrix([[2, 1], [1, 2]]))
EigenResult(shape=2×2, eigenvalues=[1, 3], diagonalizable=True)
Source code in panchi/algorithms/results.py
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this EigenResult.

    Examples
    --------
    >>> eigen(Matrix([[2, 1], [1, 2]]))
    EigenResult(shape=2×2, eigenvalues=[1, 3], diagonalizable=True)
    """
    values = ", ".join(str(v) for v in self.eigenvalues)
    return (
        f"EigenResult(shape={self.original.rows}×{self.original.cols}, "
        f"eigenvalues=[{values}], diagonalizable={self.is_diagonalizable})"
    )

__str__()

Return the full by-hand derivation of the eigenvalues.

Shows the characteristic polynomial and its factored form, then each eigenvalue with its multiplicities and eigenspace basis, and finally whether the matrix is diagonalizable.

Source code in panchi/algorithms/results.py
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
def __str__(self) -> str:
    """
    Return the full by-hand derivation of the eigenvalues.

    Shows the characteristic polynomial and its factored form, then
    each eigenvalue with its multiplicities and eigenspace basis, and
    finally whether the matrix is diagonalizable.
    """
    n = self.original.rows
    lines = [
        f"Eigenvalues of {n}×{n} matrix",
        f"det(A - λI) = {self.characteristic_polynomial} = {self._factored(False)}",
        "",
    ]
    for value, alg, geo, space in zip(
        self.eigenvalues,
        self.algebraic_multiplicities,
        self.geometric_multiplicities,
        self.eigenspaces,
        strict=True,
    ):
        lines.append(
            f"λ = {value}  (algebraic multiplicity {alg}, "
            f"geometric multiplicity {geo})"
        )
        lines.extend(f"  v = {vector}" for vector in space)
    lines.append("")
    if self.is_diagonalizable:
        lines.append("Diagonalizable: yes")
    else:
        lines.append("Diagonalizable: no (not enough independent eigenvectors)")
    return "\n".join(lines)

diagonalization()

Return P and D with A = P D P⁻¹.

The columns of P are the eigenvectors and D holds the matching eigenvalues on its diagonal, in the same order.

Returns:

Type Description
tuple[Matrix, Matrix]

The eigenvector matrix P and the diagonal matrix D.

Raises:

Type Description
ValueError

If the matrix is defective (not diagonalizable).

Examples:

>>> p, d = eigen(Matrix([[2, 1], [1, 2]])).diagonalization()
>>> print(d)
[[1, 0],
 [0, 3]]
Source code in panchi/algorithms/results.py
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
def diagonalization(self) -> tuple[Matrix, Matrix]:
    """
    Return P and D with A = P D P⁻¹.

    The columns of P are the eigenvectors and D holds the matching
    eigenvalues on its diagonal, in the same order.

    Returns
    -------
    tuple[Matrix, Matrix]
        The eigenvector matrix P and the diagonal matrix D.

    Raises
    ------
    ValueError
        If the matrix is defective (not diagonalizable).

    Examples
    --------
    >>> p, d = eigen(Matrix([[2, 1], [1, 2]])).diagonalization()
    >>> print(d)
    [[1, 0],
     [0, 3]]
    """
    if not self.is_diagonalizable:
        shortfalls = [
            f"λ = {value} appears {alg} times but has only {geo} "
            f"independent eigenvector{'s' if geo != 1 else ''}"
            for value, alg, geo in zip(
                self.eigenvalues,
                self.algebraic_multiplicities,
                self.geometric_multiplicities,
                strict=True,
            )
            if alg != geo
        ]
        raise ValueError(
            "This matrix is not diagonalizable: "
            + "; ".join(shortfalls)
            + ". There are not enough independent eigenvectors to build "
            "an invertible P."
        )
    pairs = self.pairs
    p = vector_column_matrix([vector for _, vector in pairs])
    d = diagonal([value for value, _ in pairs])
    return p, d

panchi.algorithms.QREigenResult

The result of an eigenvalue computation via the QR algorithm.

Stores the original matrix, the computed eigenvalues, the corresponding eigenvectors, and metadata about the iterative process: how many iterations were run, whether the iteration converged, and the final (near) upper-triangular matrix the QR algorithm produced.

Eigenvalues are read off the diagonal of the QR iterate, and each eigenvector is paired with the eigenvalue at the same index. The values are numerical approximations, not exact or symbolic results.

Only real eigenvalues are supported. Matrices with complex eigenvalues (or eigenvalues of equal magnitude) may not converge; in that case converged is False and eigenvectors is empty.

Parameters:

Name Type Description Default
original Matrix

The square matrix whose spectrum was computed.

required
eigenvalues list[float]

The computed eigenvalues, in the order they appear on the diagonal of the final iterate.

required
eigenvectors list[Vector]

The eigenvectors, paired by index with eigenvalues. Empty when the iteration did not converge.

required
iterations int

The number of QR iterations performed.

required
converged bool

Whether the below-diagonal mass fell below the tolerance before the iteration limit was reached.

required
triangular Matrix

The final (near) upper-triangular matrix produced by the iteration.

required

Examples:

>>> result = eigen_qr(Matrix([[2, 1], [1, 2]]))
>>> sorted(round(v, 6) for v in result.eigenvalues)
[1.0, 3.0]
Source code in panchi/algorithms/results.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
class QREigenResult:
    """
    The result of an eigenvalue computation via the QR algorithm.

    Stores the original matrix, the computed eigenvalues, the corresponding
    eigenvectors, and metadata about the iterative process: how many
    iterations were run, whether the iteration converged, and the final
    (near) upper-triangular matrix the QR algorithm produced.

    Eigenvalues are read off the diagonal of the QR iterate, and each
    eigenvector is paired with the eigenvalue at the same index. The values
    are numerical approximations, not exact or symbolic results.

    Only real eigenvalues are supported. Matrices with complex eigenvalues
    (or eigenvalues of equal magnitude) may not converge; in that case
    ``converged`` is False and ``eigenvectors`` is empty.

    Parameters
    ----------
    original : Matrix
        The square matrix whose spectrum was computed.
    eigenvalues : list[float]
        The computed eigenvalues, in the order they appear on the diagonal
        of the final iterate.
    eigenvectors : list[Vector]
        The eigenvectors, paired by index with eigenvalues. Empty when the
        iteration did not converge.
    iterations : int
        The number of QR iterations performed.
    converged : bool
        Whether the below-diagonal mass fell below the tolerance before the
        iteration limit was reached.
    triangular : Matrix
        The final (near) upper-triangular matrix produced by the iteration.

    Examples
    --------
    >>> result = eigen_qr(Matrix([[2, 1], [1, 2]]))
    >>> sorted(round(v, 6) for v in result.eigenvalues)
    [1.0, 3.0]
    """

    def __init__(
        self,
        original: Matrix,
        eigenvalues: list[float],
        eigenvectors: list[Vector],
        iterations: int,
        converged: bool,
        triangular: Matrix,
    ) -> None:
        self.original = original
        self.eigenvalues = eigenvalues
        self.eigenvectors = eigenvectors
        self.iterations = iterations
        self.converged = converged
        self.triangular = triangular

    @property
    def pairs(self) -> list[tuple[float, Vector]]:
        """
        The eigenvalue/eigenvector pairs, zipped by index.

        Returns
        -------
        list[tuple[float, Vector]]
            One (eigenvalue, eigenvector) tuple per computed eigenvector.
            Empty when no eigenvectors were computed.
        """
        return list(zip(self.eigenvalues, self.eigenvectors, strict=False))

    def __str__(self) -> str:
        """
        Return a readable summary of the eigenvalue computation.

        Shows the iteration count and convergence status, then each
        eigenvalue together with its eigenvector when available.

        Returns
        -------
        str
            Human-readable eigendecomposition summary.
        """
        header: str = (
            f"Eigendecomposition of "
            f"{self.original.rows}×{self.original.cols} matrix"
            f" — {self.iterations} iterations (converged: {self.converged})\n"
        )

        if self.eigenvectors:
            body = "\n" + "\n".join(
                f"λ = {value}\n  v = {vector}" for value, vector in self.pairs
            )
        else:
            body = "\nEigenvalues: " + ", ".join(str(v) for v in self.eigenvalues)

        return header + body

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this QREigenResult.

        Returns
        -------
        str
            Compact representation showing shape, iteration count, and
            convergence status.

        Examples
        --------
        >>> eigen_qr(Matrix([[2, 1], [1, 2]]))
        QREigenResult(shape=2×2, iterations=..., converged=True)
        """
        return (
            f"QREigenResult("
            f"shape={self.original.rows}×{self.original.cols}, "
            f"iterations={self.iterations}, "
            f"converged={self.converged})"
        )

    def _repr_latex_(self) -> str:
        """Render the eigenvalue/eigenvector pairs in LaTeX."""
        values = ",\\; ".join(scalar_to_latex(round(v, 6)) for v in self.eigenvalues)
        if not self.eigenvectors:
            body = f"\\lambda \\in \\left\\{{ {values} \\right\\}}"
            if not self.converged:
                body = "\\text{did not converge; } " + body
            return f"${body}$"
        lines = []
        for i, (value, vector) in enumerate(self.pairs):
            lines.append(
                f"\\lambda_{{{i + 1}}} = {scalar_to_latex(round(value, 6))}, "
                f"\\quad v_{{{i + 1}}} = {vector_to_latex(vector)}"
            )
        return aligned_to_latex(lines)

pairs property

The eigenvalue/eigenvector pairs, zipped by index.

Returns:

Type Description
list[tuple[float, Vector]]

One (eigenvalue, eigenvector) tuple per computed eigenvector. Empty when no eigenvectors were computed.

__repr__()

Return a concise data inspection string for this QREigenResult.

Returns:

Type Description
str

Compact representation showing shape, iteration count, and convergence status.

Examples:

>>> eigen_qr(Matrix([[2, 1], [1, 2]]))
QREigenResult(shape=2×2, iterations=..., converged=True)
Source code in panchi/algorithms/results.py
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this QREigenResult.

    Returns
    -------
    str
        Compact representation showing shape, iteration count, and
        convergence status.

    Examples
    --------
    >>> eigen_qr(Matrix([[2, 1], [1, 2]]))
    QREigenResult(shape=2×2, iterations=..., converged=True)
    """
    return (
        f"QREigenResult("
        f"shape={self.original.rows}×{self.original.cols}, "
        f"iterations={self.iterations}, "
        f"converged={self.converged})"
    )

__str__()

Return a readable summary of the eigenvalue computation.

Shows the iteration count and convergence status, then each eigenvalue together with its eigenvector when available.

Returns:

Type Description
str

Human-readable eigendecomposition summary.

Source code in panchi/algorithms/results.py
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
def __str__(self) -> str:
    """
    Return a readable summary of the eigenvalue computation.

    Shows the iteration count and convergence status, then each
    eigenvalue together with its eigenvector when available.

    Returns
    -------
    str
        Human-readable eigendecomposition summary.
    """
    header: str = (
        f"Eigendecomposition of "
        f"{self.original.rows}×{self.original.cols} matrix"
        f" — {self.iterations} iterations (converged: {self.converged})\n"
    )

    if self.eigenvectors:
        body = "\n" + "\n".join(
            f"λ = {value}\n  v = {vector}" for value, vector in self.pairs
        )
    else:
        body = "\nEigenvalues: " + ", ".join(str(v) for v in self.eigenvalues)

    return header + body

panchi.algorithms.SVDResult

The result of a (thin) singular value decomposition.

Stores the original m×n matrix A and the factors U (m×k, orthonormal columns), Σ (k×k diagonal) and V (n×k, orthonormal columns), with k = min(m, n), so that A = U Σ Vᵀ. The singular values are sorted in descending order. The Jacobi sweeps used to compute the factors are kept in steps.

The helpers approximation, error, energy, storage and compression_ratio describe the best rank-k approximation A_k = σ₀u₀v₀ᵀ + ... + σ_{k-1}u_{k-1}v_{k-1}ᵀ, which is how SVD is used for compression.

Parameters:

Name Type Description Default
original Matrix

The matrix that was decomposed.

required
u Matrix

The m×k matrix of left singular vectors.

required
sigma list[float]

The k singular values, in descending order.

required
v Matrix

The n×k matrix of right singular vectors.

required
sweeps int

The number of Jacobi sweeps performed.

required
converged bool

Whether the last sweep made no rotations.

required
steps list[JacobiSweep]

The recorded sweeps.

required
tolerance float

The tolerance used for convergence and for the numerical rank.

required

Examples:

>>> result = svd(Matrix([[3, 0], [0, 4]]))
>>> result.sigma
[4.0, 3.0]
>>> result.rank
2
Source code in panchi/algorithms/results.py
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
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
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
1926
1927
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
class SVDResult:
    """
    The result of a (thin) singular value decomposition.

    Stores the original m×n matrix A and the factors U (m×k, orthonormal
    columns), Σ (k×k diagonal) and V (n×k, orthonormal columns), with
    k = min(m, n), so that A = U Σ Vᵀ. The singular values are sorted in
    descending order. The Jacobi sweeps used to compute the factors are
    kept in ``steps``.

    The helpers ``approximation``, ``error``, ``energy``, ``storage`` and
    ``compression_ratio`` describe the best rank-k approximation
    A_k = σ₀u₀v₀ᵀ + ... + σ_{k-1}u_{k-1}v_{k-1}ᵀ, which is how SVD is used
    for compression.

    Parameters
    ----------
    original : Matrix
        The matrix that was decomposed.
    u : Matrix
        The m×k matrix of left singular vectors.
    sigma : list[float]
        The k singular values, in descending order.
    v : Matrix
        The n×k matrix of right singular vectors.
    sweeps : int
        The number of Jacobi sweeps performed.
    converged : bool
        Whether the last sweep made no rotations.
    steps : list[JacobiSweep]
        The recorded sweeps.
    tolerance : float
        The tolerance used for convergence and for the numerical rank.

    Examples
    --------
    >>> result = svd(Matrix([[3, 0], [0, 4]]))
    >>> result.sigma
    [4.0, 3.0]
    >>> result.rank
    2
    """

    def __init__(
        self,
        original: Matrix,
        u: Matrix,
        sigma: list[float],
        v: Matrix,
        sweeps: int,
        converged: bool,
        steps: list[JacobiSweep],
        tolerance: float,
    ) -> None:
        self.original = original
        self.u = u
        self.sigma = sigma
        self.s = Matrix(
            [
                [value if i == j else 0.0 for j in range(len(sigma))]
                for i, value in enumerate(sigma)
            ]
        )
        self.v = v
        self.sweeps = sweeps
        self.converged = converged
        self.steps = steps
        self.tolerance = tolerance

    @property
    def vt(self) -> Matrix:
        """
        The transpose of V, the k×n matrix whose rows are the vᵢ.

        Returns
        -------
        Matrix
            Vᵀ.
        """
        return self.v.T

    @property
    def rank(self) -> int:
        """
        The numerical rank: the number of σ above tolerance · σ₀ · max(m, n).

        Returns
        -------
        int
            The number of singular values treated as nonzero.

        Examples
        --------
        >>> svd(Matrix([[1, 1], [1, 1]])).rank
        1
        """
        if not self.sigma or self.sigma[0] == 0:
            return 0
        threshold = (
            self.tolerance * self.sigma[0] * max(self.original.rows, self.original.cols)
        )
        return sum(1 for value in self.sigma if value > threshold)

    @property
    def pairs(self) -> list[tuple[float, Vector, Vector]]:
        """
        The singular triples (σᵢ, uᵢ, vᵢ), in descending order of σ.

        Returns
        -------
        list[tuple[float, Vector, Vector]]
            One tuple per singular value.
        """
        u_columns = self.u.col_vectors
        v_columns = self.v.col_vectors
        return [
            (self.sigma[i], u_columns[i], v_columns[i]) for i in range(len(self.sigma))
        ]

    def _check_rank(self, k: int) -> None:
        if isinstance(k, bool) or not isinstance(k, int):
            raise TypeError(f"k must be an int. Got {type(k).__name__}.")
        if not 0 <= k <= len(self.sigma):
            raise ValueError(
                f"k must satisfy 0 <= k <= {len(self.sigma)} "
                f"(the number of singular values). Got {k}."
            )

    def component(self, i: int) -> Matrix:
        """
        Return the rank-1 component σᵢ uᵢ vᵢᵀ.

        Parameters
        ----------
        i : int
            The 0-based index of the singular value.

        Returns
        -------
        Matrix
            The m×n matrix σᵢ uᵢ vᵢᵀ.

        Raises
        ------
        TypeError
            If i is not an int.
        ValueError
            If i is not in 0 <= i < k.

        Examples
        --------
        >>> result = svd(Matrix([[3, 0], [0, 4]]))
        >>> print(result.component(0))
        [[0.0, 0.0],
         [0.0, 4.0]]
        """
        if isinstance(i, bool) or not isinstance(i, int):
            raise TypeError(f"i must be an int. Got {type(i).__name__}.")
        if not 0 <= i < len(self.sigma):
            raise ValueError(
                f"i must satisfy 0 <= i < {len(self.sigma)} "
                f"(the number of singular values). Got {i}."
            )
        sigma = self.sigma[i]
        u_column = [float(row[i]) for row in self.u.to_list()]
        v_column = [float(row[i]) for row in self.v.to_list()]
        return Matrix([[sigma * a * b for b in v_column] for a in u_column])

    def approximation(self, k: int) -> Matrix:
        """
        Return the best rank-k approximation A_k = Σ_{i<k} σᵢ uᵢ vᵢᵀ.

        Parameters
        ----------
        k : int
            The number of singular values to keep, 0 <= k <= len(sigma).

        Returns
        -------
        Matrix
            The m×n matrix A_k. For k = 0 this is the zero matrix.

        Raises
        ------
        TypeError
            If k is not an int.
        ValueError
            If k is out of range.

        Examples
        --------
        >>> result = svd(Matrix([[3, 0], [0, 4]]))
        >>> print(result.approximation(1))
        [[0.0, 0.0],
         [0.0, 4.0]]
        """
        self._check_rank(k)
        u = self.u.to_list()
        v = self.v.to_list()
        return Matrix(
            [
                [
                    sum(
                        (
                            self.sigma[i] * float(u[row][i]) * float(v[col][i])
                            for i in range(k)
                        ),
                        0.0,
                    )
                    for col in range(self.original.cols)
                ]
                for row in range(self.original.rows)
            ]
        )

    def error(self, k: int) -> float:
        """
        Return ‖A − A_k‖_F, computed as √(Σ_{i>=k} σᵢ²).

        Parameters
        ----------
        k : int
            The number of singular values kept, 0 <= k <= len(sigma).

        Returns
        -------
        float
            The Frobenius norm of the approximation error.

        Examples
        --------
        >>> svd(Matrix([[3, 0], [0, 4]])).error(1)
        3.0
        """
        self._check_rank(k)
        return math.sqrt(sum(value * value for value in self.sigma[k:]))

    def relative_error(self, k: int) -> float:
        """
        Return ‖A − A_k‖_F / ‖A‖_F.

        Parameters
        ----------
        k : int
            The number of singular values kept, 0 <= k <= len(sigma).

        Returns
        -------
        float
            The relative error, or 0.0 when A is the zero matrix.

        Examples
        --------
        >>> svd(Matrix([[3, 0], [0, 4]])).relative_error(1)
        0.6
        """
        self._check_rank(k)
        total = self.error(0)
        if total == 0:
            return 0.0
        return self.error(k) / total

    def energy(self, k: int) -> float:
        """
        Return the fraction of Σσᵢ² captured by the first k singular values.

        Parameters
        ----------
        k : int
            The number of singular values kept, 0 <= k <= len(sigma).

        Returns
        -------
        float
            Σ_{i<k} σᵢ² / Σ σᵢ², or 1.0 when every σ is zero.

        Examples
        --------
        >>> svd(Matrix([[3, 0], [0, 4]])).energy(1)
        0.64
        """
        self._check_rank(k)
        total = sum(value * value for value in self.sigma)
        if total == 0:
            return 1.0
        return sum(value * value for value in self.sigma[:k]) / total

    def storage(self, k: int) -> int:
        """
        Return the number of values needed to store A_k: k · (m + n + 1).

        Parameters
        ----------
        k : int
            The number of singular values kept, 0 <= k <= len(sigma).

        Returns
        -------
        int
            The count of stored numbers (k columns of U, k of V, k σ values).

        Examples
        --------
        >>> svd(Matrix([[3, 0], [0, 4]])).storage(1)
        5
        """
        self._check_rank(k)
        return k * (self.original.rows + self.original.cols + 1)

    def compression_ratio(self, k: int) -> float:
        """
        Return storage(k) / (m · n), the cost of A_k relative to A itself.

        Parameters
        ----------
        k : int
            The number of singular values kept, 0 <= k <= len(sigma).

        Returns
        -------
        float
            Values below 1 mean A_k is cheaper to store than A.

        Examples
        --------
        >>> svd(Matrix([[3, 0], [0, 4]])).compression_ratio(1)
        1.25
        """
        self._check_rank(k)
        return self.storage(k) / (self.original.rows * self.original.cols)

    def rank_for_energy(self, fraction: float) -> int:
        """
        Return the smallest k with energy(k) >= fraction.

        Parameters
        ----------
        fraction : float
            The target energy, 0 <= fraction <= 1.

        Returns
        -------
        int
            The smallest number of singular values reaching the target.

        Raises
        ------
        TypeError
            If fraction is not a number.
        ValueError
            If fraction is not in [0, 1].

        Examples
        --------
        >>> svd(Matrix([[3, 0], [0, 4]])).rank_for_energy(0.5)
        1
        """
        if isinstance(fraction, bool) or not isinstance(fraction, (int, float)):
            raise TypeError(
                f"fraction must be a number. Got {type(fraction).__name__}."
            )
        if not 0 <= fraction <= 1:
            raise ValueError(
                f"fraction must satisfy 0 <= fraction <= 1. Got {fraction}."
            )
        for k in range(len(self.sigma) + 1):
            if self.energy(k) >= fraction:
                return k
        return len(self.sigma)

    def __str__(self) -> str:
        """
        Return a readable summary of the singular value decomposition.

        Shows the Jacobi sweeps (every rotation for record="rotations" on
        small matrices), then σ, U, Σ and Vᵀ, and states A = U Σ Vᵀ.

        Returns
        -------
        str
            Human-readable decomposition summary.
        """
        rows = self.original.rows
        cols = self.original.cols
        sweep_word = "sweep" if self.sweeps == 1 else "sweeps"
        status = "converged" if self.converged else "not converged"
        header = f"SVD of {rows}×{cols} matrix — {self.sweeps} {sweep_word}, {status}\n"

        detailed = min(rows, cols) <= 4 and any(
            step.matrix is not None for step in self.steps
        )
        steps_str = ""
        for step in self.steps:
            steps_str += f"\n{step}"
            if detailed:
                for rotation in step.rotations:
                    steps_str += f"\n  {rotation}"
                if step.matrix is not None:
                    steps_str += f"\n{step.matrix}\n"
        if steps_str:
            steps_str += "\n"

        values = ", ".join(f"{value:.6g}" for value in self.sigma)
        body = (
            f"\nσ = [{values}]\n"
            f"\nA = U Σ Vᵀ\n"
            f"\nU:\n{self.u}\n"
            f"\nΣ:\n{self.s}\n"
            f"\nVᵀ:\n{self.vt}"
        )
        return header + steps_str + body

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this SVDResult.

        Returns
        -------
        str
            Compact representation showing shape, rank, sweeps and convergence.

        Examples
        --------
        >>> svd(Matrix([[3, 0], [0, 4]]))
        SVDResult(shape=2×2, rank=2, sweeps=1, converged=True)
        """
        return (
            f"SVDResult(shape={self.original.rows}×{self.original.cols}, "
            f"rank={self.rank}, sweeps={self.sweeps}, converged={self.converged})"
        )

    def _repr_latex_(self) -> str:
        """Render the factorization ``A = U Σ Vᵀ`` in LaTeX."""
        return (
            f"$${matrix_to_latex(self.original)} = "
            f"{matrix_to_latex(self.u)}\\,{matrix_to_latex(self.s)}\\,"
            f"{matrix_to_latex(self.vt)}$$"
        )

pairs property

The singular triples (σᵢ, uᵢ, vᵢ), in descending order of σ.

Returns:

Type Description
list[tuple[float, Vector, Vector]]

One tuple per singular value.

rank property

The numerical rank: the number of σ above tolerance · σ₀ · max(m, n).

Returns:

Type Description
int

The number of singular values treated as nonzero.

Examples:

>>> svd(Matrix([[1, 1], [1, 1]])).rank
1

vt property

The transpose of V, the k×n matrix whose rows are the vᵢ.

Returns:

Type Description
Matrix

Vᵀ.

__repr__()

Return a concise data inspection string for this SVDResult.

Returns:

Type Description
str

Compact representation showing shape, rank, sweeps and convergence.

Examples:

>>> svd(Matrix([[3, 0], [0, 4]]))
SVDResult(shape=2×2, rank=2, sweeps=1, converged=True)
Source code in panchi/algorithms/results.py
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this SVDResult.

    Returns
    -------
    str
        Compact representation showing shape, rank, sweeps and convergence.

    Examples
    --------
    >>> svd(Matrix([[3, 0], [0, 4]]))
    SVDResult(shape=2×2, rank=2, sweeps=1, converged=True)
    """
    return (
        f"SVDResult(shape={self.original.rows}×{self.original.cols}, "
        f"rank={self.rank}, sweeps={self.sweeps}, converged={self.converged})"
    )

__str__()

Return a readable summary of the singular value decomposition.

Shows the Jacobi sweeps (every rotation for record="rotations" on small matrices), then σ, U, Σ and Vᵀ, and states A = U Σ Vᵀ.

Returns:

Type Description
str

Human-readable decomposition summary.

Source code in panchi/algorithms/results.py
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
def __str__(self) -> str:
    """
    Return a readable summary of the singular value decomposition.

    Shows the Jacobi sweeps (every rotation for record="rotations" on
    small matrices), then σ, U, Σ and Vᵀ, and states A = U Σ Vᵀ.

    Returns
    -------
    str
        Human-readable decomposition summary.
    """
    rows = self.original.rows
    cols = self.original.cols
    sweep_word = "sweep" if self.sweeps == 1 else "sweeps"
    status = "converged" if self.converged else "not converged"
    header = f"SVD of {rows}×{cols} matrix — {self.sweeps} {sweep_word}, {status}\n"

    detailed = min(rows, cols) <= 4 and any(
        step.matrix is not None for step in self.steps
    )
    steps_str = ""
    for step in self.steps:
        steps_str += f"\n{step}"
        if detailed:
            for rotation in step.rotations:
                steps_str += f"\n  {rotation}"
            if step.matrix is not None:
                steps_str += f"\n{step.matrix}\n"
    if steps_str:
        steps_str += "\n"

    values = ", ".join(f"{value:.6g}" for value in self.sigma)
    body = (
        f"\nσ = [{values}]\n"
        f"\nA = U Σ Vᵀ\n"
        f"\nU:\n{self.u}\n"
        f"\nΣ:\n{self.s}\n"
        f"\nVᵀ:\n{self.vt}"
    )
    return header + steps_str + body

approximation(k)

Return the best rank-k approximation A_k = Σ_{i<k} σᵢ uᵢ vᵢᵀ.

Parameters:

Name Type Description Default
k int

The number of singular values to keep, 0 <= k <= len(sigma).

required

Returns:

Type Description
Matrix

The m×n matrix A_k. For k = 0 this is the zero matrix.

Raises:

Type Description
TypeError

If k is not an int.

ValueError

If k is out of range.

Examples:

>>> result = svd(Matrix([[3, 0], [0, 4]]))
>>> print(result.approximation(1))
[[0.0, 0.0],
 [0.0, 4.0]]
Source code in panchi/algorithms/results.py
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
def approximation(self, k: int) -> Matrix:
    """
    Return the best rank-k approximation A_k = Σ_{i<k} σᵢ uᵢ vᵢᵀ.

    Parameters
    ----------
    k : int
        The number of singular values to keep, 0 <= k <= len(sigma).

    Returns
    -------
    Matrix
        The m×n matrix A_k. For k = 0 this is the zero matrix.

    Raises
    ------
    TypeError
        If k is not an int.
    ValueError
        If k is out of range.

    Examples
    --------
    >>> result = svd(Matrix([[3, 0], [0, 4]]))
    >>> print(result.approximation(1))
    [[0.0, 0.0],
     [0.0, 4.0]]
    """
    self._check_rank(k)
    u = self.u.to_list()
    v = self.v.to_list()
    return Matrix(
        [
            [
                sum(
                    (
                        self.sigma[i] * float(u[row][i]) * float(v[col][i])
                        for i in range(k)
                    ),
                    0.0,
                )
                for col in range(self.original.cols)
            ]
            for row in range(self.original.rows)
        ]
    )

component(i)

Return the rank-1 component σᵢ uᵢ vᵢᵀ.

Parameters:

Name Type Description Default
i int

The 0-based index of the singular value.

required

Returns:

Type Description
Matrix

The m×n matrix σᵢ uᵢ vᵢᵀ.

Raises:

Type Description
TypeError

If i is not an int.

ValueError

If i is not in 0 <= i < k.

Examples:

>>> result = svd(Matrix([[3, 0], [0, 4]]))
>>> print(result.component(0))
[[0.0, 0.0],
 [0.0, 4.0]]
Source code in panchi/algorithms/results.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
def component(self, i: int) -> Matrix:
    """
    Return the rank-1 component σᵢ uᵢ vᵢᵀ.

    Parameters
    ----------
    i : int
        The 0-based index of the singular value.

    Returns
    -------
    Matrix
        The m×n matrix σᵢ uᵢ vᵢᵀ.

    Raises
    ------
    TypeError
        If i is not an int.
    ValueError
        If i is not in 0 <= i < k.

    Examples
    --------
    >>> result = svd(Matrix([[3, 0], [0, 4]]))
    >>> print(result.component(0))
    [[0.0, 0.0],
     [0.0, 4.0]]
    """
    if isinstance(i, bool) or not isinstance(i, int):
        raise TypeError(f"i must be an int. Got {type(i).__name__}.")
    if not 0 <= i < len(self.sigma):
        raise ValueError(
            f"i must satisfy 0 <= i < {len(self.sigma)} "
            f"(the number of singular values). Got {i}."
        )
    sigma = self.sigma[i]
    u_column = [float(row[i]) for row in self.u.to_list()]
    v_column = [float(row[i]) for row in self.v.to_list()]
    return Matrix([[sigma * a * b for b in v_column] for a in u_column])

compression_ratio(k)

Return storage(k) / (m · n), the cost of A_k relative to A itself.

Parameters:

Name Type Description Default
k int

The number of singular values kept, 0 <= k <= len(sigma).

required

Returns:

Type Description
float

Values below 1 mean A_k is cheaper to store than A.

Examples:

>>> svd(Matrix([[3, 0], [0, 4]])).compression_ratio(1)
1.25
Source code in panchi/algorithms/results.py
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
def compression_ratio(self, k: int) -> float:
    """
    Return storage(k) / (m · n), the cost of A_k relative to A itself.

    Parameters
    ----------
    k : int
        The number of singular values kept, 0 <= k <= len(sigma).

    Returns
    -------
    float
        Values below 1 mean A_k is cheaper to store than A.

    Examples
    --------
    >>> svd(Matrix([[3, 0], [0, 4]])).compression_ratio(1)
    1.25
    """
    self._check_rank(k)
    return self.storage(k) / (self.original.rows * self.original.cols)

energy(k)

Return the fraction of Σσᵢ² captured by the first k singular values.

Parameters:

Name Type Description Default
k int

The number of singular values kept, 0 <= k <= len(sigma).

required

Returns:

Type Description
float

Σ_{i<k} σᵢ² / Σ σᵢ², or 1.0 when every σ is zero.

Examples:

>>> svd(Matrix([[3, 0], [0, 4]])).energy(1)
0.64
Source code in panchi/algorithms/results.py
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
def energy(self, k: int) -> float:
    """
    Return the fraction of Σσᵢ² captured by the first k singular values.

    Parameters
    ----------
    k : int
        The number of singular values kept, 0 <= k <= len(sigma).

    Returns
    -------
    float
        Σ_{i<k} σᵢ² / Σ σᵢ², or 1.0 when every σ is zero.

    Examples
    --------
    >>> svd(Matrix([[3, 0], [0, 4]])).energy(1)
    0.64
    """
    self._check_rank(k)
    total = sum(value * value for value in self.sigma)
    if total == 0:
        return 1.0
    return sum(value * value for value in self.sigma[:k]) / total

error(k)

Return ‖A − A_k‖F, computed as √(Σ{i>=k} σᵢ²).

Parameters:

Name Type Description Default
k int

The number of singular values kept, 0 <= k <= len(sigma).

required

Returns:

Type Description
float

The Frobenius norm of the approximation error.

Examples:

>>> svd(Matrix([[3, 0], [0, 4]])).error(1)
3.0
Source code in panchi/algorithms/results.py
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
def error(self, k: int) -> float:
    """
    Return ‖A − A_k‖_F, computed as √(Σ_{i>=k} σᵢ²).

    Parameters
    ----------
    k : int
        The number of singular values kept, 0 <= k <= len(sigma).

    Returns
    -------
    float
        The Frobenius norm of the approximation error.

    Examples
    --------
    >>> svd(Matrix([[3, 0], [0, 4]])).error(1)
    3.0
    """
    self._check_rank(k)
    return math.sqrt(sum(value * value for value in self.sigma[k:]))

rank_for_energy(fraction)

Return the smallest k with energy(k) >= fraction.

Parameters:

Name Type Description Default
fraction float

The target energy, 0 <= fraction <= 1.

required

Returns:

Type Description
int

The smallest number of singular values reaching the target.

Raises:

Type Description
TypeError

If fraction is not a number.

ValueError

If fraction is not in [0, 1].

Examples:

>>> svd(Matrix([[3, 0], [0, 4]])).rank_for_energy(0.5)
1
Source code in panchi/algorithms/results.py
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
1926
1927
def rank_for_energy(self, fraction: float) -> int:
    """
    Return the smallest k with energy(k) >= fraction.

    Parameters
    ----------
    fraction : float
        The target energy, 0 <= fraction <= 1.

    Returns
    -------
    int
        The smallest number of singular values reaching the target.

    Raises
    ------
    TypeError
        If fraction is not a number.
    ValueError
        If fraction is not in [0, 1].

    Examples
    --------
    >>> svd(Matrix([[3, 0], [0, 4]])).rank_for_energy(0.5)
    1
    """
    if isinstance(fraction, bool) or not isinstance(fraction, (int, float)):
        raise TypeError(
            f"fraction must be a number. Got {type(fraction).__name__}."
        )
    if not 0 <= fraction <= 1:
        raise ValueError(
            f"fraction must satisfy 0 <= fraction <= 1. Got {fraction}."
        )
    for k in range(len(self.sigma) + 1):
        if self.energy(k) >= fraction:
            return k
    return len(self.sigma)

relative_error(k)

Return ‖A − A_k‖_F / ‖A‖_F.

Parameters:

Name Type Description Default
k int

The number of singular values kept, 0 <= k <= len(sigma).

required

Returns:

Type Description
float

The relative error, or 0.0 when A is the zero matrix.

Examples:

>>> svd(Matrix([[3, 0], [0, 4]])).relative_error(1)
0.6
Source code in panchi/algorithms/results.py
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
def relative_error(self, k: int) -> float:
    """
    Return ‖A − A_k‖_F / ‖A‖_F.

    Parameters
    ----------
    k : int
        The number of singular values kept, 0 <= k <= len(sigma).

    Returns
    -------
    float
        The relative error, or 0.0 when A is the zero matrix.

    Examples
    --------
    >>> svd(Matrix([[3, 0], [0, 4]])).relative_error(1)
    0.6
    """
    self._check_rank(k)
    total = self.error(0)
    if total == 0:
        return 0.0
    return self.error(k) / total

storage(k)

Return the number of values needed to store A_k: k · (m + n + 1).

Parameters:

Name Type Description Default
k int

The number of singular values kept, 0 <= k <= len(sigma).

required

Returns:

Type Description
int

The count of stored numbers (k columns of U, k of V, k σ values).

Examples:

>>> svd(Matrix([[3, 0], [0, 4]])).storage(1)
5
Source code in panchi/algorithms/results.py
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
def storage(self, k: int) -> int:
    """
    Return the number of values needed to store A_k: k · (m + n + 1).

    Parameters
    ----------
    k : int
        The number of singular values kept, 0 <= k <= len(sigma).

    Returns
    -------
    int
        The count of stored numbers (k columns of U, k of V, k σ values).

    Examples
    --------
    >>> svd(Matrix([[3, 0], [0, 4]])).storage(1)
    5
    """
    self._check_rank(k)
    return k * (self.original.rows + self.original.cols + 1)

panchi.algorithms.JacobiSweep

One full sweep of one-sided Jacobi over every column pair.

A sweep visits each pair (p, q) with p < q once. It records how many pairs were rotated and the largest |cos(angle between columns)| seen, which measures how far the columns were from orthogonal. A sweep with zero rotations means the algorithm has converged.

Parameters:

Name Type Description Default
index int

The 1-based index of the sweep.

required
rotation_count int

The number of rotations applied in this sweep.

required
max_off float

The largest |γ| / √(αβ) seen in this sweep, or 0.0 if none.

required
rotations list[JacobiRotation]

Every rotation applied, when recorded with record="rotations". Empty otherwise.

required
matrix Matrix | None

The working matrix after this sweep, when recorded with record="rotations". None otherwise.

required

Examples:

>>> result = svd(Matrix([[1, 1], [1, 1]]))
>>> print(result.steps[0])
Sweep 1: 1 rotation, max |cos(angle between columns)| = 1.0e+00
Source code in panchi/algorithms/results.py
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
class JacobiSweep:
    """
    One full sweep of one-sided Jacobi over every column pair.

    A sweep visits each pair (p, q) with p < q once. It records how many
    pairs were rotated and the largest |cos(angle between columns)| seen,
    which measures how far the columns were from orthogonal. A sweep with
    zero rotations means the algorithm has converged.

    Parameters
    ----------
    index : int
        The 1-based index of the sweep.
    rotation_count : int
        The number of rotations applied in this sweep.
    max_off : float
        The largest |γ| / √(αβ) seen in this sweep, or 0.0 if none.
    rotations : list[JacobiRotation]
        Every rotation applied, when recorded with record="rotations".
        Empty otherwise.
    matrix : Matrix | None
        The working matrix after this sweep, when recorded with
        record="rotations". None otherwise.

    Examples
    --------
    >>> result = svd(Matrix([[1, 1], [1, 1]]))
    >>> print(result.steps[0])
    Sweep 1: 1 rotation, max |cos(angle between columns)| = 1.0e+00
    """

    def __init__(
        self,
        index: int,
        rotation_count: int,
        max_off: float,
        rotations: list[JacobiRotation],
        matrix: Matrix | None,
    ) -> None:
        self.index = index
        self.rotation_count = rotation_count
        self.max_off = max_off
        self.rotations = rotations
        self.matrix = matrix

    def __str__(self) -> str:
        """
        Return a one-line summary of the sweep.

        Returns
        -------
        str
            The sweep index, rotation count and largest off-orthogonality.
        """
        return (
            f"Sweep {self.index}: {self.rotation_count} "
            f"rotation{'' if self.rotation_count == 1 else 's'}, "
            f"max |cos(angle between columns)| = {self.max_off:.1e}"
        )

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this JacobiSweep.

        Returns
        -------
        str
            Compact representation showing the index, count and max_off.
        """
        return (
            f"JacobiSweep(index={self.index}, "
            f"rotation_count={self.rotation_count}, max_off={self.max_off:.1e})"
        )

__repr__()

Return a concise data inspection string for this JacobiSweep.

Returns:

Type Description
str

Compact representation showing the index, count and max_off.

Source code in panchi/algorithms/results.py
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this JacobiSweep.

    Returns
    -------
    str
        Compact representation showing the index, count and max_off.
    """
    return (
        f"JacobiSweep(index={self.index}, "
        f"rotation_count={self.rotation_count}, max_off={self.max_off:.1e})"
    )

__str__()

Return a one-line summary of the sweep.

Returns:

Type Description
str

The sweep index, rotation count and largest off-orthogonality.

Source code in panchi/algorithms/results.py
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
def __str__(self) -> str:
    """
    Return a one-line summary of the sweep.

    Returns
    -------
    str
        The sweep index, rotation count and largest off-orthogonality.
    """
    return (
        f"Sweep {self.index}: {self.rotation_count} "
        f"rotation{'' if self.rotation_count == 1 else 's'}, "
        f"max |cos(angle between columns)| = {self.max_off:.1e}"
    )

panchi.algorithms.JacobiRotation

One plane rotation applied during a one-sided Jacobi sweep.

The rotation mixes columns p and q of the working matrix so that they become orthogonal. Before the rotation, alpha and beta are the squared lengths of the two columns and gamma is their dot product. The rotation replaces a_p with cos·a_p − sin·a_q and a_q with sin·a_p + cos·a_q.

Parameters:

Name Type Description Default
sweep int

The 1-based index of the sweep this rotation belongs to.

required
p int

The index of the first column, with p < q.

required
q int

The index of the second column.

required
cos float

The cosine of the rotation angle.

required
sin float

The sine of the rotation angle.

required
t float

The tangent of the rotation angle.

required
alpha float

The squared length of column p before the rotation.

required
beta float

The squared length of column q before the rotation.

required
gamma float

The dot product of columns p and q before the rotation.

required

Examples:

>>> result = svd(Matrix([[1, 1], [1, 1]]), record="rotations")
>>> rotation = result.steps[0].rotations[0]
>>> rotation.p, rotation.q
(0, 1)
Source code in panchi/algorithms/results.py
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
class JacobiRotation:
    """
    One plane rotation applied during a one-sided Jacobi sweep.

    The rotation mixes columns p and q of the working matrix so that they
    become orthogonal. Before the rotation, alpha and beta are the squared
    lengths of the two columns and gamma is their dot product. The rotation
    replaces a_p with cos·a_p − sin·a_q and a_q with sin·a_p + cos·a_q.

    Parameters
    ----------
    sweep : int
        The 1-based index of the sweep this rotation belongs to.
    p : int
        The index of the first column, with p < q.
    q : int
        The index of the second column.
    cos : float
        The cosine of the rotation angle.
    sin : float
        The sine of the rotation angle.
    t : float
        The tangent of the rotation angle.
    alpha : float
        The squared length of column p before the rotation.
    beta : float
        The squared length of column q before the rotation.
    gamma : float
        The dot product of columns p and q before the rotation.

    Examples
    --------
    >>> result = svd(Matrix([[1, 1], [1, 1]]), record="rotations")
    >>> rotation = result.steps[0].rotations[0]
    >>> rotation.p, rotation.q
    (0, 1)
    """

    def __init__(
        self,
        sweep: int,
        p: int,
        q: int,
        cos: float,
        sin: float,
        t: float,
        alpha: float,
        beta: float,
        gamma: float,
    ) -> None:
        self.sweep = sweep
        self.p = p
        self.q = q
        self.cos = cos
        self.sin = sin
        self.t = t
        self.alpha = alpha
        self.beta = beta
        self.gamma = gamma

    def __str__(self) -> str:
        """
        Return a readable description of the rotation.

        Returns
        -------
        str
            The rotated column pair, the column statistics and the angle.
        """
        return (
            f"rotate columns {self.p} and {self.q}: "
            f"‖a_p‖² = {self.alpha:.4g}, ‖a_q‖² = {self.beta:.4g}, "
            f"a_p·a_q = {self.gamma:.4g} → cos = {self.cos:.6f}, "
            f"sin = {self.sin:.6f}"
        )

    def __repr__(self) -> str:
        """
        Return a concise data inspection string for this JacobiRotation.

        Returns
        -------
        str
            Compact representation showing the sweep, the pair and the angle.
        """
        return (
            f"JacobiRotation(sweep={self.sweep}, p={self.p}, q={self.q}, "
            f"cos={self.cos:.6g}, sin={self.sin:.6g})"
        )

__repr__()

Return a concise data inspection string for this JacobiRotation.

Returns:

Type Description
str

Compact representation showing the sweep, the pair and the angle.

Source code in panchi/algorithms/results.py
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
def __repr__(self) -> str:
    """
    Return a concise data inspection string for this JacobiRotation.

    Returns
    -------
    str
        Compact representation showing the sweep, the pair and the angle.
    """
    return (
        f"JacobiRotation(sweep={self.sweep}, p={self.p}, q={self.q}, "
        f"cos={self.cos:.6g}, sin={self.sin:.6g})"
    )

__str__()

Return a readable description of the rotation.

Returns:

Type Description
str

The rotated column pair, the column statistics and the angle.

Source code in panchi/algorithms/results.py
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
def __str__(self) -> str:
    """
    Return a readable description of the rotation.

    Returns
    -------
    str
        The rotated column pair, the column statistics and the angle.
    """
    return (
        f"rotate columns {self.p} and {self.q}: "
        f"‖a_p‖² = {self.alpha:.4g}, ‖a_q‖² = {self.beta:.4g}, "
        f"a_p·a_q = {self.gamma:.4g} → cos = {self.cos:.6f}, "
        f"sin = {self.sin:.6f}"
    )