]> gitweb.michael.orlitzky.com - sage.d.git/blobdiff - mjo/eja/eja_utils.py
eja: add a deep change_ring() utility function.
[sage.d.git] / mjo / eja / eja_utils.py
index b6e0c7d38eaf1d9114973bba4f5ad0674cb8a8a2..81b5634bc921736b0d007f3df04013d0dc6df265 100644 (file)
@@ -2,6 +2,130 @@ from sage.functions.other import sqrt
 from sage.matrix.constructor import matrix
 from sage.modules.free_module_element import vector
 
+def _change_ring(x, R):
+    r"""
+    Change the ring of a vector, matrix, or a cartesian product of
+    those things.
+
+    SETUP::
+
+        sage: from mjo.eja.eja_utils import _change_ring
+
+    EXAMPLES::
+
+        sage: v = vector(QQ, (1,2,3))
+        sage: m = matrix(QQ, [[1,2],[3,4]])
+        sage: _change_ring(v, RDF)
+        (1.0, 2.0, 3.0)
+        sage: _change_ring(m, RDF)
+        [1.0 2.0]
+        [3.0 4.0]
+        sage: _change_ring((v,m), RDF)
+        (
+                         [1.0 2.0]
+        (1.0, 2.0, 3.0), [3.0 4.0]
+        )
+        sage: V1 = cartesian_product([v.parent(), v.parent()])
+        sage: V = cartesian_product([v.parent(), V1])
+        sage: V((v, (v, v)))
+        ((1, 2, 3), ((1, 2, 3), (1, 2, 3)))
+        sage: _change_ring(V((v, (v, v))), RDF)
+        ((1.0, 2.0, 3.0), ((1.0, 2.0, 3.0), (1.0, 2.0, 3.0)))
+
+    """
+    try:
+        return x.change_ring(R)
+    except AttributeError:
+        try:
+            from sage.categories.sets_cat import cartesian_product
+            if hasattr(x, 'element_class'):
+                # x is a parent and we're in a recursive call.
+                return cartesian_product( [_change_ring(x_i, R)
+                                           for x_i in x.cartesian_factors()] )
+            else:
+                # x is an element, and we want to change the ring
+                # of its parent.
+                P = x.parent()
+                Q = cartesian_product( [_change_ring(P_i, R)
+                                        for P_i in P.cartesian_factors()] )
+                return Q(x)
+        except AttributeError:
+            # No parent for x
+            return x.__class__( _change_ring(x_i, R) for x_i in x )
+
+def _scale(x, alpha):
+    r"""
+    Scale the vector, matrix, or cartesian-product-of-those-things
+    ``x`` by ``alpha``.
+
+    This works around the inability to scale certain elements of
+    Cartesian product spaces, as reported in
+
+      https://trac.sagemath.org/ticket/31435
+
+    ..WARNING:
+
+        This will do the wrong thing if you feed it a tuple or list.
+
+    SETUP::
+
+        sage: from mjo.eja.eja_utils import _scale
+
+    EXAMPLES::
+
+        sage: v = vector(QQ, (1,2,3))
+        sage: _scale(v,2)
+        (2, 4, 6)
+        sage: m = matrix(QQ, [[1,2],[3,4]])
+        sage: M = cartesian_product([m.parent(), m.parent()])
+        sage: _scale(M((m,m)), 2)
+        ([2 4]
+        [6 8], [2 4]
+        [6 8])
+
+    """
+    if hasattr(x, 'cartesian_factors'):
+        P = x.parent()
+        return P(tuple( _scale(x_i, alpha)
+                        for x_i in x.cartesian_factors() ))
+    else:
+        return x*alpha
+
+
+def _all2list(x):
+    r"""
+    Flatten a vector, matrix, or cartesian product of those things
+    into a long list.
+
+    EXAMPLES::
+
+        sage: from mjo.eja.eja_utils import _all2list
+        sage: V1 = VectorSpace(QQ,2)
+        sage: V2 = MatrixSpace(QQ,2)
+        sage: x1 = V1([1,1])
+        sage: x2 = V1([1,-1])
+        sage: y1 = V2.one()
+        sage: y2 = V2([0,1,1,0])
+        sage: _all2list((x1,y1))
+        [1, 1, 1, 0, 0, 1]
+        sage: _all2list((x2,y2))
+        [1, -1, 0, 1, 1, 0]
+        sage: M = cartesian_product([V1,V2])
+        sage: _all2list(M((x1,y1)))
+        [1, 1, 1, 0, 0, 1]
+        sage: _all2list(M((x2,y2)))
+        [1, -1, 0, 1, 1, 0]
+
+    """
+    if hasattr(x, 'list'):
+        # Easy case...
+        return x.list()
+    else:
+        # But what if it's a tuple or something else? This has to
+        # handle cartesian products of cartesian products, too; that's
+        # why it's recursive.
+        return sum( map(_all2list,x), [] )
+
 def _mat2vec(m):
         return vector(m.base_ring(), m.list())
 
@@ -78,6 +202,28 @@ def gram_schmidt(v, inner_product=None):
         [0 0], [1/2*sqrt(2)           0], [0 1]
         ]
 
+    It even works on Cartesian product spaces whose factors are vector
+    or matrix spaces::
+
+        sage: V1 = VectorSpace(AA,2)
+        sage: V2 = MatrixSpace(AA,2)
+        sage: M = cartesian_product([V1,V2])
+        sage: x1 = V1([1,1])
+        sage: x2 = V1([1,-1])
+        sage: y1 = V2.one()
+        sage: y2 = V2([0,1,1,0])
+        sage: z1 = M((x1,y1))
+        sage: z2 = M((x2,y2))
+        sage: def ip(a,b):
+        ....:     return a[0].inner_product(b[0]) + (a[1]*b[1]).trace()
+        sage: U = gram_schmidt([z1,z2], inner_product=ip)
+        sage: ip(U[0],U[1])
+        0
+        sage: ip(U[0],U[0])
+        1
+        sage: ip(U[1],U[1])
+        1
+
     TESTS:
 
     Ensure that zero vectors don't get in the way::
@@ -88,15 +234,11 @@ def gram_schmidt(v, inner_product=None):
         sage: v = [v1,v2,v3]
         sage: len(gram_schmidt(v)) == 2
         True
-
     """
     if inner_product is None:
         inner_product = lambda x,y: x.inner_product(y)
     norm = lambda x: inner_product(x,x).sqrt()
 
-    def proj(x,y):
-        return (inner_product(x,y)/inner_product(x,x))*x
-
     v = list(v) # make a copy, don't clobber the input
 
     # Drop all zero vectors before we start.
@@ -108,10 +250,24 @@ def gram_schmidt(v, inner_product=None):
 
     R = v[0].base_ring()
 
+    # Our "zero" needs to belong to the right space for sum() to work.
+    zero = v[0].parent().zero()
+
+    sc = lambda x,a: a*x
+    if hasattr(v[0], 'cartesian_factors'):
+        # Only use the slow implementation if necessary.
+        sc = _scale
+
+    def proj(x,y):
+        return sc(x, (inner_product(x,y)/inner_product(x,x)))
+
     # First orthogonalize...
     for i in range(1,len(v)):
         # Earlier vectors can be made into zero so we have to ignore them.
-        v[i] -= sum( proj(v[j],v[i]) for j in range(i) if not v[j].is_zero() )
+        v[i] -= sum( (proj(v[j],v[i])
+                      for j in range(i)
+                      if not v[j].is_zero() ),
+                     zero )
 
     # And now drop all zero vectors again if they were "orthogonalized out."
     v = [ v_i for v_i in v if not v_i.is_zero() ]
@@ -120,6 +276,6 @@ def gram_schmidt(v, inner_product=None):
     # them here because then our subalgebra would have a bigger field
     # than the superalgebra.
     for i in range(len(v)):
-        v[i] = v[i] / norm(v[i])
+        v[i] = sc(v[i], ~norm(v[i]))
 
     return v