GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Numerics/python/pynumerics/src/pynumerics/linalg.py at main · USACE-RMC/Numerics Expand file tree/ Copy pathlinalg.pyMore file actions 1408 lines (1126 loc) · 43.4 KB / Copy pathlinalg.pyFile metadata and controls1408 lines (1126 loc) · 43.4 KB 1 2 3 4 5 6 7 8 9 10 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 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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 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 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 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 """Matrices, vectors and decompositions from ``Numerics.Mathematics.LinearAlgebra``. :class:`Matrix` and :class:`Vector` hold a .NET ``Matrix`` or ``Vector`` (``.net``) and expose its members; matrix-valued results stay in .NET as new wrappers, and ``numpy.asarray`` copies the values out. The decompositions (:class:`CholeskyDecomposition`, :class:`LUDecomposition`, :class:`QRDecomposition`, :class:`SingularValueDecomposition` and :class:`EigenValueDecomposition`) take any 2-D array or a :class:`Matrix` and return their factors and solutions as NumPy arrays. :func:`regularize` and :func:`make_symmetric_positive_definite` wrap ``MatrixRegularization``. Every array crosses in one bulk copy each way, bit for bit. """ from __future__ import annotations from collections.abc import Callable, Sequence from typing import Any import numpy as np from pynumerics._util import cached_overload, net_enum, overload from pynumerics.callbacks import scalar_function from pynumerics.enums import NetEnum from pynumerics.errors import translate_public from pynumerics.marshal import ( _construct, _linear_algebra, _numerics_matrix, _numerics_vector, to_net_doubles, to_net_matrix, to_numpy_doubles, to_numpy_matrix, ) def _numpy_matrix(net: Any) -> np.ndarray: """Copy a .NET ``Matrix`` into a new 2-D float64 array.""" return to_numpy_matrix(net.Array) def _numpy_vector(net: Any) -> np.ndarray: """Copy a .NET ``Vector`` into a new 1-D float64 array.""" return to_numpy_doubles(net.Array) def _is_matrix_operand(values: Any) -> bool: """Return whether an operand is a :class:`Matrix` or a 2-D array (otherwise a vector).""" return isinstance(values, Matrix) or (not isinstance(values, Vector) and np.ndim(values) == 2) def _solve(net: Any, b: Any, *extra: float) -> np.ndarray: """Call ``Solve`` with a vector or a matrix right-hand side and copy the solution out.""" if _is_matrix_operand(b): return _numpy_matrix(net.Solve(_numerics_matrix(b, unwrap=True), *extra)) return _numpy_vector(net.Solve(_numerics_vector(b, unwrap=True), *extra)) class DecompositionMethod(NetEnum): """Matrix decomposition choices (``Numerics.Mathematics.LinearAlgebra.DecompositionMethod``).""" CHOLESKY = "Cholesky" SINGULAR_VALUE = "SingularValue" class EigenSolverMethod(NetEnum): """Symmetric eigen-decomposition algorithms (``Numerics.Mathematics.LinearAlgebra.EigenSolverMethod``).""" JACOBI = "Jacobi" QL = "QL" class Matrix: """A dense matrix of doubles (``Numerics.Mathematics.LinearAlgebra.Matrix``). Parameters ---------- values : array_like or int or Vector A 2-D array; a 1-D array or a :class:`Vector` (a single column); or the number of rows of a zero matrix (square unless ``columns`` is given). With ``by_column``, a sequence of 1-D arrays. columns : int, optional The number of columns of a zero matrix. by_column : bool, optional Build from a sequence of 1-D arrays, as columns (True) or rows (False). Attributes ---------- net : Numerics.Mathematics.LinearAlgebra.Matrix The wrapped .NET matrix. """ def __init__(self, values: Any, columns: int | None = None, *, by_column: bool | None = None) -> None: la = _linear_algebra() if isinstance(values, Vector): self.net = la.Matrix(values.net) elif isinstance(values, (int, np.integer)) and not isinstance(values, bool): self.net = la.Matrix(int(values)) if columns is None else la.Matrix(int(values), int(columns)) elif by_column is not None: import System # noqa: PLC0415 - started by _linear_algebra() from System.Collections.Generic import List # noqa: PLC0415 arrays = List[System.Array[System.Double]]() for item in values: arrays.Add(to_net_doubles(item)) self.net = la.Matrix(arrays, bool(by_column)) elif np.ndim(values) == 1: self.net = la.Matrix(to_net_doubles(values)) else: self.net = _construct("Matrix", to_net_matrix(values)) @classmethod def from_net(cls, net: Any) -> Matrix: """Wrap an existing .NET matrix without copying it. Parameters ---------- net : Numerics.Mathematics.LinearAlgebra.Matrix The .NET matrix. Returns ------- Matrix The wrapper. """ matrix = cls.__new__(cls) matrix.net = net return matrix @classmethod def from_xml(cls, xml: str) -> Matrix: """Read a matrix written by :meth:`to_xml` (the ``Matrix(XElement)`` constructor). Parameters ---------- xml : str The ``<Matrix>`` element text. Returns ------- Matrix The matrix. """ from System.Xml.Linq import XElement # noqa: PLC0415 _linear_algebra() return cls.from_net(_linear_algebra().Matrix(XElement.Parse(str(xml)))) def __array__(self, dtype: Any = None, copy: Any = None) -> np.ndarray: values = _numpy_matrix(self.net) return values if dtype is None else values.astype(dtype) def __getitem__(self, index: tuple[int, int]) -> float: row, column = index return float(self.net[int(row), int(column)]) def __setitem__(self, index: tuple[int, int], value: float) -> None: row, column = index self.net[int(row), int(column)] = float(value) def __repr__(self) -> str: return f"Matrix({self.to_array()!r})" @property def number_of_rows(self) -> int: """The number of rows (``NumberOfRows``).""" return int(self.net.NumberOfRows) @property def number_of_columns(self) -> int: """The number of columns (``NumberOfColumns``).""" return int(self.net.NumberOfColumns) @property def shape(self) -> tuple[int, int]: """``(number_of_rows, number_of_columns)``.""" return self.number_of_rows, self.number_of_columns @property def header(self) -> list[str] | None: """The column header text (``Header``).""" header = self.net.Header return None if header is None else [str(h) for h in header] @header.setter def header(self, value: Sequence[str] | None) -> None: import System # noqa: PLC0415 - the matrix exists, so the runtime is running self.net.Header = None if value is None else System.Array[System.String]([str(v) for v in value]) @property def is_symmetric(self) -> bool: """Whether every pair agrees to 1e-12 times the largest magnitude (``IsSymmetric``).""" return bool(self.net.IsSymmetric) @property def is_square(self) -> bool: """Whether the matrix is square (``IsSquare``).""" return bool(self.net.IsSquare) @property def array(self) -> np.ndarray: """A copy of the underlying ``double[,]`` (``Array``).""" return _numpy_matrix(self.net) def to_array(self) -> np.ndarray: """Return the values as a new 2-D array (``ToArray``). Returns ------- numpy.ndarray The values. """ return to_numpy_matrix(self.net.ToArray()) def to_xml(self) -> str: """Return the matrix as XML text (``ToXElement``). Returns ------- str The ``<Matrix>`` element, values written with round-trip precision. """ return str(self.net.ToXElement().ToString()) def clone(self) -> Matrix: """Return a copy (``Clone``). Returns ------- Matrix The copy. """ return Matrix.from_net(self.net.Clone()) def row(self, index: int) -> np.ndarray: """Return a copy of a row (``Row``). Parameters ---------- index : int The zero-based row index. Returns ------- numpy.ndarray The row. """ return to_numpy_doubles(self.net.Row(int(index))) def column(self, index: int) -> np.ndarray: """Return a copy of a column (``Column``). Parameters ---------- index : int The zero-based column index. Returns ------- numpy.ndarray The column. """ return to_numpy_doubles(self.net.Column(int(index))) def diagonal(self) -> np.ndarray: """Return the min(rows, columns) diagonal elements (``Diagonal()``). Returns ------- numpy.ndarray The diagonal. """ return to_numpy_doubles(self.net.Diagonal()) @staticmethod def diagonal_matrix(values: Any) -> Matrix: """Return a diagonal matrix (the static ``Matrix.Diagonal``). Parameters ---------- values : Matrix or Vector or array_like A square matrix (its diagonal is kept) or a 1-D array of diagonal entries. Returns ------- Matrix The diagonal matrix. """ la = _linear_algebra() if _is_matrix_operand(values): return Matrix.from_net(la.Matrix.Diagonal.Overloads[la.Matrix](_numerics_matrix(values, unwrap=True))) return Matrix.from_net(la.Matrix.Diagonal.Overloads[la.Vector](_numerics_vector(values, unwrap=True))) def upper_triangle(self) -> Matrix: """Return the upper triangle, with zeros below the diagonal (``UpperTriangle``). Returns ------- Matrix The upper-triangular matrix. """ return Matrix.from_net(self.net.UpperTriangle()) def lower_triangle(self) -> Matrix: """Return the lower triangle, with zeros above the diagonal (``LowerTriangle``). Returns ------- Matrix The lower-triangular matrix. """ return Matrix.from_net(self.net.LowerTriangle()) def determinant(self) -> float: """Return the determinant, by LU decomposition (``Determinant``). Returns ------- float The determinant det(A). """ return float(self.net.Determinant()) def inverse(self) -> Matrix: """Return the inverse, by LU decomposition (``Inverse``). Returns ------- Matrix A^-1. """ return Matrix.from_net(self.net.Inverse()) def transpose(self) -> Matrix: """Return the transpose (``Transpose``). Returns ------- Matrix A^T. """ return Matrix.from_net(self.net.Transpose()) def trace(self) -> float: """Return the sum of the diagonal (``Trace``). Returns ------- float The trace tr(A). """ return float(self.net.Trace()) @staticmethod def identity(size: int) -> Matrix: """Return the identity matrix (``Identity``). Parameters ---------- size : int The number of rows and columns. Returns ------- Matrix I. """ return Matrix.from_net(_linear_algebra().Matrix.Identity(int(size))) @staticmethod def outer(x: Any, y: Any) -> Matrix: """Return the outer product x y^T (``Outer``). Parameters ---------- x, y : Vector or array_like 1-D operands. Returns ------- Matrix The ``len(x)`` by ``len(y)`` product. """ return Matrix.from_net(_linear_algebra().Matrix.Outer(_numerics_vector(x, unwrap=True), _numerics_vector(y, unwrap=True))) def column_means(self) -> np.ndarray: """Return the mean of each column (``ColumnMeans``). Returns ------- numpy.ndarray One mean per column. """ return _numpy_vector(self.net.ColumnMeans()) def apply(self, func: Callable[[float], float] | str) -> None: """Replace every element ``a`` by ``func(a)`` in place (``Apply``). Parameters ---------- func : callable or str A Python callable (one crossing per element) or C# lambda source compiled with Roslyn (no crossing per element), as :func:`pynumerics.callbacks.scalar_function` accepts. """ self.net.Apply(scalar_function(func)) def sqrt(self) -> None: """Take the square root of every element in place (``Sqrt``).""" self.net.Sqrt() def sqr(self) -> None: """Square every element in place (``Sqr``).""" self.net.Sqr() def log(self) -> None: """Take the natural logarithm of every element in place (``Log``).""" self.net.Log() def exp(self) -> None: """Exponentiate every element in place (``Exp``).""" self.net.Exp() def sum(self) -> float: """Return the sum of every element (``Sum``). Returns ------- float The sum. """ return float(self.net.Sum()) def multiply(self, other: Any) -> Matrix | Vector: """Return the product with a matrix, a vector or a scalar (``Multiply``). Parameters ---------- other : Matrix or Vector or array_like or float A matrix (or 2-D array), a vector (or 1-D array) or a scalar. Returns ------- Matrix or Vector A B or A s (a :class:`Matrix`), or A x (a :class:`Vector`). """ if _is_matrix_operand(other): member = cached_overload("Matrix.Multiply(Matrix)", lambda: _linear_algebra().Matrix.Multiply.Overloads[_linear_algebra().Matrix]) return Matrix.from_net(member(self.net, _numerics_matrix(other, unwrap=True))) if isinstance(other, Vector) or np.ndim(other) == 1: member = cached_overload("Matrix.Multiply(Vector)", lambda: _linear_algebra().Matrix.Multiply.Overloads[_linear_algebra().Vector]) return Vector.from_net(member(self.net, _numerics_vector(other, unwrap=True))) return Matrix.from_net(overload(self.net.Multiply, "Double")(float(other))) def transpose_multiply(self, other: Any) -> Matrix: """Return A^T B without forming the transpose (``TransposeMultiply``). Parameters ---------- other : Matrix or array_like B, with as many rows as this matrix. Returns ------- Matrix A^T B; exactly symmetric when B is A. """ return Matrix.from_net(self.net.TransposeMultiply(_numerics_matrix(other, unwrap=True))) def divide(self, scalar: float) -> Matrix: """Return the matrix divided by a scalar (``Divide``). Parameters ---------- scalar : float The divisor. Returns ------- Matrix A / s. """ return Matrix.from_net(self.net.Divide(float(scalar))) def add(self, other: Any) -> Matrix: """Return the elementwise sum (``Add``). Parameters ---------- other : Matrix or array_like A matrix of the same shape. Returns ------- Matrix A + B. """ return Matrix.from_net(self.net.Add(_numerics_matrix(other, unwrap=True))) def subtract(self, other: Any) -> Matrix: """Return the elementwise difference (``Subtract``). Parameters ---------- other : Matrix or array_like A matrix of the same shape. Returns ------- Matrix A - B. """ return Matrix.from_net(self.net.Subtract(_numerics_matrix(other, unwrap=True))) class Vector: """A dense vector of doubles (``Numerics.Mathematics.LinearAlgebra.Vector``). Parameters ---------- values : array_like or int The 1-D values, or the length of a new vector. fill : float, optional The value of every element of a new vector of length ``values``; None gives zeros. Attributes ---------- net : Numerics.Mathematics.LinearAlgebra.Vector The wrapped .NET vector. """ def __init__(self, values: Any, fill: float | None = None) -> None: la = _linear_algebra() if isinstance(values, (int, np.integer)) and not isinstance(values, bool): self.net = la.Vector(int(values)) if fill is None else la.Vector(int(values), float(fill)) else: self.net = _construct("Vector", to_net_doubles(values)) @classmethod def from_net(cls, net: Any) -> Vector: """Wrap an existing .NET vector without copying it. Parameters ---------- net : Numerics.Mathematics.LinearAlgebra.Vector The .NET vector. Returns ------- Vector The wrapper. """ vector = cls.__new__(cls) vector.net = net return vector def __array__(self, dtype: Any = None, copy: Any = None) -> np.ndarray: values = _numpy_vector(self.net) return values if dtype is None else values.astype(dtype) def __len__(self) -> int: return int(self.net.Length) def __getitem__(self, index: int) -> float: return float(self.net[int(index)]) def __setitem__(self, index: int, value: float) -> None: self.net[int(index)] = float(value) def __repr__(self) -> str: return f"Vector({self.to_array()!r})" @property def length(self) -> int: """The number of elements (``Length``).""" return int(self.net.Length) @property def header(self) -> str | None: """The header text (``Header``).""" header = self.net.Header return None if header is None else str(header) @header.setter def header(self, value: str | None) -> None: self.net.Header = None if value is None else str(value) @property def array(self) -> np.ndarray: """A copy of the underlying ``double[]`` (``Array``).""" return _numpy_vector(self.net) def to_array(self) -> np.ndarray: """Return the values as a new 1-D array (``ToArray``). Returns ------- numpy.ndarray The values. """ return to_numpy_doubles(self.net.ToArray()) def to_list(self) -> list[float]: """Return the values as a Python list (``ToList``). Returns ------- list of float The values. """ return to_numpy_doubles(self.net.ToList()).tolist() def clone(self) -> Vector: """Return a copy (``Clone``). Returns ------- Vector The copy. """ return Vector.from_net(self.net.Clone()) def clear(self) -> None: """Set every element to zero in place (``Clear``).""" self.net.Clear() def copy_from(self, other: Any) -> None: """Overwrite the elements with those of another vector of the same length (``CopyFrom``). Parameters ---------- other : Vector or array_like The source. """ self.net.CopyFrom(_numerics_vector(other, unwrap=True)) def sum(self) -> float: """Return the sum of the elements (``Sum``). Returns ------- float The sum. """ return float(self.net.Sum()) def norm(self) -> float: """Return the Euclidean norm (``Norm``). Returns ------- float ||v||. """ return float(self.net.Norm()) def norm_squared(self) -> float: """Return the squared Euclidean norm (``NormSquared``). Returns ------- float ||v||**2. """ return float(self.net.NormSquared()) @staticmethod def distance(a: Any, b: Any) -> float: """Return the Euclidean distance ||a - b|| (``Distance``). Parameters ---------- a, b : Vector or array_like Equal-length vectors. Returns ------- float The distance. """ return float(_linear_algebra().Vector.Distance(_numerics_vector(a, unwrap=True), _numerics_vector(b, unwrap=True))) @staticmethod def dot_product(a: Any, b: Any) -> float: """Return the dot product a . b (``DotProduct``). Parameters ---------- a, b : Vector or array_like Equal-length vectors. Returns ------- float The dot product. """ return float(_linear_algebra().Vector.DotProduct(_numerics_vector(a, unwrap=True), _numerics_vector(b, unwrap=True))) @staticmethod def project(a: Any, b: Any) -> Vector: """Return the projection of a onto b, (a . b / b . b) b (``Project``). Parameters ---------- a, b : Vector or array_like Equal-length vectors. Returns ------- Vector The projection. """ return Vector.from_net(_linear_algebra().Vector.Project(_numerics_vector(a, unwrap=True), _numerics_vector(b, unwrap=True))) def add(self, other: Any) -> Vector: """Return the elementwise sum (``Add``). Parameters ---------- other : Vector or array_like An equal-length vector. Returns ------- Vector The sum v + w. """ if isinstance(other, Vector): return Vector.from_net(self.net.Add.Overloads[_linear_algebra().Vector](other.net)) return Vector.from_net(overload(self.net.Add, "Double[]")(to_net_doubles(other))) def subtract(self, other: Any) -> Vector: """Return the elementwise difference (``Subtract``). Parameters ---------- other : Vector or array_like An equal-length vector. Returns ------- Vector The difference v - w. """ if isinstance(other, Vector): return Vector.from_net(self.net.Subtract.Overloads[_linear_algebra().Vector](other.net)) return Vector.from_net(overload(self.net.Subtract, "Double[]")(to_net_doubles(other))) def multiply(self, other: Any) -> Vector: """Return a matrix times this vector, the elementwise product, or the scaled vector (``Multiply``). Parameters ---------- other : Matrix or Vector or array_like or float A matrix M (or 2-D array) whose column count is the vector length, for M v; a vector (or 1-D array) for the elementwise product; or a scalar. Returns ------- Vector The product. """ la = _linear_algebra() if _is_matrix_operand(other): return Vector.from_net(self.net.Multiply.Overloads[la.Matrix](_numerics_matrix(other, unwrap=True))) if isinstance(other, Vector): return Vector.from_net(self.net.Multiply.Overloads[la.Vector](other.net)) if np.ndim(other) == 1: return Vector.from_net(overload(self.net.Multiply, "Double[]")(to_net_doubles(other))) return Vector.from_net(overload(self.net.Multiply, "Double")(float(other))) def divide(self, scalar: float) -> Vector: """Return the vector divided by a scalar (``Divide``). Parameters ---------- scalar : float The divisor. Returns ------- Vector The quotient v / s. """ return Vector.from_net(self.net.Divide(float(scalar))) class CholeskyDecomposition: """The Cholesky factorization A = L L^T of a symmetric positive-definite matrix (``CholeskyDecomposition``). Only the upper triangle and the diagonal of A are read. A pivot is rejected when it is at or below ``relative_tolerance`` times the corresponding diagonal entry. Parameters ---------- matrix : Matrix or array_like The symmetric positive-definite matrix. relative_tolerance : float, optional The scale-relative pivot tolerance in [0, 1); None uses :meth:`default_relative_tolerance` of the dimension. Attributes ---------- net : Numerics.Mathematics.LinearAlgebra.CholeskyDecomposition The wrapped .NET decomposition. Raises ------ RuntimeError If the matrix is not positive definite (raised by Numerics). ValueError If the matrix is not square or the tolerance is outside [0, 1) (raised by Numerics). """ def __init__(self, matrix: Any, relative_tolerance: float | None = None) -> None: la = _linear_algebra() self.net = (la.CholeskyDecomposition(_numerics_matrix(matrix, unwrap=True)) if relative_tolerance is None else la.CholeskyDecomposition(_numerics_matrix(matrix, unwrap=True), float(relative_tolerance))) @classmethod def try_decompose(cls, matrix: Any, minimum_relative_jitter: float | None = None, maximum_relative_jitter: float | None = None) -> tuple[bool, CholeskyDecomposition | None, float]: """Factor A, retrying on A + jitter I with an escalating jitter (``TryCholesky``). The jitters are s * minimum * 10**k up to s * maximum, with s the mean diagonal of A (or 1); the defaults are the Numerics ones, 1e-10 and 1e-2. Parameters ---------- matrix : Matrix or array_like The symmetric matrix. minimum_relative_jitter, maximum_relative_jitter : float, optional The jitter range relative to s; give both or neither. Returns ------- success : bool Whether A or a jittered A was factored. decomposition : CholeskyDecomposition or None The factorization of A + jitter I on success. jitter : float The absolute jitter added: 0 when A factors as given, NaN on failure. """ member = _linear_algebra().CholeskyDecomposition.TryCholesky if minimum_relative_jitter is None and maximum_relative_jitter is None: ok, net, jitter = member(_numerics_matrix(matrix, unwrap=True), None, 0.0) else: ok, net, jitter = member(_numerics_matrix(matrix, unwrap=True), float(minimum_relative_jitter), float(maximum_relative_jitter), None, 0.0) if not ok: return False, None, float(jitter) decomposition = cls.__new__(cls) decomposition.net = net return True, decomposition, float(jitter) @staticmethod def default_relative_tolerance(dimension: int) -> float: """Return the default pivot tolerance for a dimension (``DefaultRelativeTolerance``). Parameters ---------- dimension : int The matrix order n. Returns ------- float The tolerance (2 n eps). """ return float(_linear_algebra().CholeskyDecomposition.DefaultRelativeTolerance(int(dimension))) @property def relative_tolerance(self) -> float: """The pivot tolerance used (``RelativeTolerance``).""" return float(self.net.RelativeTolerance) @property def l(self) -> np.ndarray: # noqa: E743 - the factor's conventional name """The lower-triangular factor L (``L``).""" return _numpy_matrix(self.net.L) @property def a(self) -> np.ndarray: """The decomposed matrix (``A``; A + jitter I after :meth:`try_decompose`).""" return _numpy_matrix(self.net.A) @property def is_positive_definite(self) -> bool: """Whether the factorization succeeded (``IsPositiveDefinite``).""" return bool(self.net.IsPositiveDefinite) def solve(self, b: Any) -> np.ndarray: """Solve A x = b (``Solve``). Parameters ---------- b : Vector or array_like The right-hand side. Returns ------- numpy.ndarray The solution x. """ return _numpy_vector(self.net.Solve(_numerics_vector(b, unwrap=True))) def forward(self, b: Any) -> np.ndarray: """Solve L y = b by forward substitution (``Forward``). Parameters ---------- b : Vector or array_like The right-hand side. Returns ------- numpy.ndarray The solution y. """ return _numpy_vector(self.net.Forward(_numerics_vector(b, unwrap=True))) def backward(self, y: Any) -> np.ndarray: """Solve L^T x = y by back substitution (``Backward``). Parameters ---------- y : Vector or array_like The right-hand side. Returns ------- numpy.ndarray The solution x. """ return _numpy_vector(self.net.Backward(_numerics_vector(y, unwrap=True))) def inverse(self) -> np.ndarray: """Return A^-1 from the factor (``InverseA``). Returns ------- numpy.ndarray The inverse. """ return _numpy_matrix(self.net.InverseA()) def determinant(self) -> float: """Return det(A) from the factor (``Determinant``). Returns ------- float The determinant. """ return float(self.net.Determinant()) def log_determinant(self) -> float: """Return ln det(A) = 2 sum ln L[i, i] (``LogDeterminant``). Returns ------- float The log determinant. """ return float(self.net.LogDeterminant()) class LUDecomposition: """The LU decomposition with partial pivoting of a square matrix (``LUDecomposition``). Parameters ---------- matrix : Matrix or array_like The square matrix; it is copied, not modified. Attributes ---------- net : Numerics.Mathematics.LinearAlgebra.LUDecomposition The wrapped .NET decomposition. Raises ------ ValueError If the matrix is not square (raised by Numerics). """ def __init__(self, matrix: Any) -> None: self.net = _linear_algebra().LUDecomposition(_numerics_matrix(matrix, unwrap=True)) @property def lu(self) -> np.ndarray: """The packed factors of the row-permuted matrix (``LU``; unit diagonal of L implied).""" return _numpy_matrix(self.net.LU) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |