]> gitweb.michael.orlitzky.com - sage.d.git/blobdiff - mjo/ldlt.py
mjo/ldlt.py: add fast block-LDLT-based is_positive_semidefinite().
[sage.d.git] / mjo / ldlt.py
index 45615288085764c5bf59b3241343da030c948b6e..1c2663ea3d574360059b07d22f9af8163ebdc2e7 100644 (file)
@@ -25,187 +25,49 @@ def is_positive_semidefinite_naive(A):
         return True # vacuously
     return A.is_hermitian() and all( v >= 0 for v in A.eigenvalues() )
 
-def ldlt_naive(A):
-    r"""
-    Perform a pivoted `LDL^{T}` factorization of the Hermitian
-    positive-semidefinite matrix `A`.
-
-    This is a naive, recursive implementation that is inefficient due
-    to Python's lack of tail-call optimization. The pivot strategy is
-    to choose the largest diagonal entry of the matrix at each step,
-    and to permute it into the top-left position. Ultimately this
-    results in a factorization `A = PLDL^{T}P^{T}`, where `P` is a
-    permutation matrix, `L` is unit-lower-triangular, and `D` is
-    diagonal decreasing from top-left to bottom-right.
-
-    ALGORITHM:
-
-    The algorithm is based on the discussion in Golub and Van Loan, but with
-    some "typos" fixed.
 
-    OUTPUT:
-
-    A triple `(P,L,D)` such that `A = PLDL^{T}P^{T}` and where,
-
-      * `P` is a permutaiton matrix
-      * `L` is unit lower-triangular
-      * `D` is a diagonal matrix whose entries are decreasing from top-left
-        to bottom-right
+def is_positive_semidefinite(A):
+    r"""
+    A fast positive-semidefinite check based on the block-LDLT
+    factorization.
 
     SETUP::
 
-        sage: from mjo.ldlt import ldlt_naive, is_positive_semidefinite_naive
+        sage: from mjo.ldlt import (is_positive_semidefinite,
+        ....:                       is_positive_semidefinite_naive)
 
-    EXAMPLES:
+    TESTS:
 
-    All three factors should be the identity when the original matrix is::
+    Check that the naive and fast answers are the same, in general::
 
-        sage: I = matrix.identity(QQ,4)
-        sage: P,L,D = ldlt_naive(I)
-        sage: P == I and L == I and D == I
+        sage: set_random_seed()
+        sage: F = NumberField(x^2 + 1, 'I')
+        sage: from sage.misc.prandom import choice
+        sage: ring = choice([ZZ,QQ,F])
+        sage: A = matrix.random(ring, 10)
+        sage: is_positive_semidefinite(A) == is_positive_semidefinite_naive(A)
         True
 
-    TESTS:
-
-    Ensure that a "random" positive-semidefinite matrix is factored correctly::
+    Check that the naive and fast answers are the same for a Hermitian
+    matrix::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(5)
-        sage: A = matrix.random(QQ, n)
-        sage: A = A*A.transpose()
-        sage: is_positive_semidefinite_naive(A)
+        sage: F = NumberField(x^2 + 1, 'I')
+        sage: from sage.misc.prandom import choice
+        sage: ring = choice([ZZ,QQ,F])
+        sage: A = matrix.random(ring, 10); A = A + A.conjugate_transpose()
+        sage: is_positive_semidefinite(A) == is_positive_semidefinite_naive(A)
         True
-        sage: P,L,D = ldlt_naive(A)
-        sage: A == P*L*D*L.transpose()*P.transpose()
-        True
-
-    """
-    n = A.nrows()
-
-    # Use the fraction field of the given matrix so that division will work
-    # when (for example) our matrix consists of integer entries.
-    ring = A.base_ring().fraction_field()
-
-    if n == 0 or n == 1:
-        # We can get n == 0 if someone feeds us a trivial matrix.
-        P = matrix.identity(ring, n)
-        L = matrix.identity(ring, n)
-        D = A
-        return (P,L,D)
-
-    A1 = A.change_ring(ring)
-    diags = A1.diagonal()
-    s = diags.index(max(diags))
-    P1 = copy(A1.matrix_space().identity_matrix())
-    P1.swap_rows(0,s)
-    A1 = P1.T * A1 * P1
-    alpha1 = A1[0,0]
-
-    # Golub and Van Loan mention in passing what to do here. This is
-    # only sensible if the matrix is positive-semidefinite, because we
-    # are assuming that we can set everything else to zero as soon as
-    # we hit the first on-diagonal zero.
-    if alpha1 == 0:
-        P = A1.matrix_space().identity_matrix()
-        L = P
-        D = A1.matrix_space().zero()
-        return (P,L,D)
-
-    v1 = A1[1:n,0]
-    A2 = A1[1:,1:]
-
-    P2, L2, D2 = ldlt_naive(A2 - (v1*v1.transpose())/alpha1)
-
-    P1 = P1*block_matrix(2,2, [[ZZ(1), ZZ(0)],
-                               [0*v1,  P2]])
-    L1 = block_matrix(2,2, [[ZZ(1),                    ZZ(0)],
-                            [P2.transpose()*v1/alpha1, L2]])
-    D1 = block_matrix(2,2, [[alpha1, ZZ(0)],
-                            [0*v1,   D2]])
-
-    return (P1,L1,D1)
-
-
-
-def ldlt_fast(A):
-    r"""
-    Perform a fast, pivoted `LDL^{T}` factorization of the Hermitian
-    positive-semidefinite matrix `A`.
 
-    This function is much faster than ``ldlt_naive`` because the
-    tail-recursion has been unrolled into a loop.
     """
-    n = A.nrows()
-    ring = A.base_ring().fraction_field()
-
-    A = A.change_ring(ring)
-
-    # Don't try to store the results in the lower-left-hand corner of
-    # "A" itself; there lies madness.
-    L = copy(A.matrix_space().identity_matrix())
-    D = copy(A.matrix_space().zero())
-
-    # Keep track of the permutations in a vector rather than in a
-    # matrix, for efficiency.
-    p = list(range(n))
-
-    for k in range(n):
-        # We need to loop once for every diagonal entry in the
-        # matrix. So, as many times as it has rows/columns. At each
-        # step, we obtain the permutation needed to put things in the
-        # right place, then the "next" entry (alpha) of D, and finally
-        # another column of L.
-        diags = A.diagonal()[k:n]
-        alpha = max(diags)
-
-        # We're working *within* the matrix ``A``, so every index is
-        # offset by k. For example: after the second step, we should
-        # only be looking at the lower 3-by-3 block of a 5-by-5 matrix.
-        s = k + diags.index(alpha)
-
-        # Move the largest diagonal element up into the top-left corner
-        # of the block we're working on (the one starting from index k,k).
-        # Presumably this is faster than hitting the thing with a
-        # permutation matrix.
-        A.swap_columns(k,s)
-        A.swap_rows(k,s)
-
-        # Have to do L, too, to keep track of the "P2.T" (which is 1 x
-        # P3.T which is 1 x P4 T)... in the recursive
-        # algorithm. There, we compute P2^T from the bottom up. Here,
-        # we apply the permutations one at a time, essentially
-        # building them top-down (but just applying them instead of
-        # building them.
-        L.swap_columns(k,s)
-        L.swap_rows(k,s)
-
-        # Update the permutation "matrix" with the next swap.
-        p_k = p[k]
-        p[k] = p[s]
-        p[s] = p_k
-
-        # Now the largest diagonal is in the top-left corner of
-        # the block below and to the right of index k,k....
-        # Note: same as ``pivot``.
-        D[k,k] = alpha
-
-        # When alpha is zero, we can just leave the rest of the D/L entries
-        # zero... which is exactly how they start out.
-        if alpha != 0:
-            # Update the "next" block of A that we'll work on during
-            # the following iteration. I think it's faster to get the
-            # entries of a row than a column here?
-            for i in range(n-k-1):
-                for j in range(i+1):
-                    A[k+1+i,k+1+j] = A[k+1+i,k+1+j] - A[k,k+1+i]*A[k,k+1+j]/alpha
-                    A[k+1+j,k+1+i] = A[k+1+i,k+1+j] # keep it symmetric!
-
-            # Store the "new" (kth) column of L.
-            for i in range(n-k-1):
-                # Set the lower-left "half" from the upper-right "half"...
-                L[k+i+1,k] = A[k,k+1+i]/alpha
-
-    I = A.matrix_space().identity_matrix()
-    P = matrix.column( I.row(p[j]) for j in range(n) )
-
-    return P,L,D
+    if not A.is_hermitian():
+        return False
+    _,_,d = A._block_ldlt()
+    for d_i in d:
+        if d_i.nrows() == 1:
+            if d_i < 0:
+                return False
+        else:
+            # A 2x2 block indicates that it's indefinite
+            return False
+    return True