]> gitweb.michael.orlitzky.com - sage.d.git/blobdiff - mjo/eja/eja_algebra.py
eja: add random_instance() method for algebras.
[sage.d.git] / mjo / eja / eja_algebra.py
index c1d66ddaaea7f01f86b4f84065cfa22eb5be1590..413128c843647e038e8869471daf29d84f1470f2 100644 (file)
@@ -5,25 +5,34 @@ are used in optimization, and have some additional nice methods beyond
 what can be supported in a general Jordan Algebra.
 """
 
-#from sage.algebras.finite_dimensional_algebras.finite_dimensional_algebra import FiniteDimensionalAlgebra
 from sage.algebras.quatalg.quaternion_algebra import QuaternionAlgebra
-from sage.categories.finite_dimensional_algebras_with_basis import FiniteDimensionalAlgebrasWithBasis
+from sage.categories.magmatic_algebras import MagmaticAlgebras
 from sage.combinat.free_module import CombinatorialFreeModule
 from sage.matrix.constructor import matrix
+from sage.matrix.matrix_space import MatrixSpace
 from sage.misc.cachefunc import cached_method
 from sage.misc.prandom import choice
-from sage.modules.free_module import VectorSpace
+from sage.misc.table import table
+from sage.modules.free_module import FreeModule, VectorSpace
 from sage.rings.integer_ring import ZZ
-from sage.rings.number_field.number_field import QuadraticField
+from sage.rings.number_field.number_field import NumberField, QuadraticField
 from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
 from sage.rings.rational_field import QQ
+from sage.rings.real_lazy import CLF, RLF
 from sage.structure.element import is_Matrix
-from sage.structure.category_object import normalize_names
 
 from mjo.eja.eja_element import FiniteDimensionalEuclideanJordanAlgebraElement
 from mjo.eja.eja_utils import _mat2vec
 
 class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
+    # This is an ugly hack needed to prevent the category framework
+    # from implementing a coercion from our base ring (e.g. the
+    # rationals) into the algebra. First of all -- such a coercion is
+    # nonsense to begin with. But more importantly, it tries to do so
+    # in the category of rings, and since our algebras aren't
+    # associative they generally won't be rings.
+    _no_generic_basering_coercion = True
+
     def __init__(self,
                  field,
                  mult_table,
@@ -50,9 +59,14 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
         """
         self._rank = rank
         self._natural_basis = natural_basis
-        self._multiplication_table = mult_table
+
+        # TODO: HACK for the charpoly.. needs redesign badly.
+        self._basis_normalizers = None
+
         if category is None:
-            category = FiniteDimensionalAlgebrasWithBasis(field).Unital()
+            category = MagmaticAlgebras(field).FiniteDimensional()
+            category = category.WithBasis().Unital()
+
         fda = super(FiniteDimensionalEuclideanJordanAlgebra, self)
         fda.__init__(field,
                      range(len(mult_table)),
@@ -60,6 +74,106 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
                      category=category)
         self.print_options(bracket='')
 
+        # The multiplication table we're given is necessarily in terms
+        # of vectors, because we don't have an algebra yet for
+        # anything to be an element of. However, it's faster in the
+        # long run to have the multiplication table be in terms of
+        # algebra elements. We do this after calling the superclass
+        # constructor so that from_vector() knows what to do.
+        self._multiplication_table = [ map(lambda x: self.from_vector(x), ls)
+                                       for ls in mult_table ]
+
+
+    def _element_constructor_(self, elt):
+        """
+        Construct an element of this algebra from its natural
+        representation.
+
+        This gets called only after the parent element _call_ method
+        fails to find a coercion for the argument.
+
+        SETUP::
+
+            sage: from mjo.eja.eja_algebra import (JordanSpinEJA,
+            ....:                                  RealCartesianProductEJA,
+            ....:                                  RealSymmetricEJA)
+
+        EXAMPLES:
+
+        The identity in `S^n` is converted to the identity in the EJA::
+
+            sage: J = RealSymmetricEJA(3)
+            sage: I = matrix.identity(QQ,3)
+            sage: J(I) == J.one()
+            True
+
+        This skew-symmetric matrix can't be represented in the EJA::
+
+            sage: J = RealSymmetricEJA(3)
+            sage: A = matrix(QQ,3, lambda i,j: i-j)
+            sage: J(A)
+            Traceback (most recent call last):
+            ...
+            ArithmeticError: vector is not in free module
+
+        TESTS:
+
+        Ensure that we can convert any element of the two non-matrix
+        simple algebras (whose natural representations are their usual
+        vector representations) back and forth faithfully::
+
+            sage: set_random_seed()
+            sage: J = RealCartesianProductEJA.random_instance()
+            sage: x = J.random_element()
+            sage: J(x.to_vector().column()) == x
+            True
+            sage: J = JordanSpinEJA.random_instance()
+            sage: x = J.random_element()
+            sage: J(x.to_vector().column()) == x
+            True
+
+        """
+        if elt == 0:
+            # The superclass implementation of random_element()
+            # needs to be able to coerce "0" into the algebra.
+            return self.zero()
+
+        natural_basis = self.natural_basis()
+        basis_space = natural_basis[0].matrix_space()
+        if elt not in basis_space:
+            raise ValueError("not a naturally-represented algebra element")
+
+        # Thanks for nothing! Matrix spaces aren't vector spaces in
+        # Sage, so we have to figure out its natural-basis coordinates
+        # ourselves. We use the basis space's ring instead of the
+        # element's ring because the basis space might be an algebraic
+        # closure whereas the base ring of the 3-by-3 identity matrix
+        # could be QQ instead of QQbar.
+        V = VectorSpace(basis_space.base_ring(), elt.nrows()*elt.ncols())
+        W = V.span_of_basis( _mat2vec(s) for s in natural_basis )
+        coords =  W.coordinate_vector(_mat2vec(elt))
+        return self.from_vector(coords)
+
+
+    @staticmethod
+    def _max_test_case_size():
+        """
+        Return an integer "size" that is an upper bound on the size of
+        this algebra when it is used in a random test
+        case. Unfortunately, the term "size" is quite vague -- when
+        dealing with `R^n` under either the Hadamard or Jordan spin
+        product, the "size" refers to the dimension `n`. When dealing
+        with a matrix algebra (real symmetric or complex/quaternion
+        Hermitian), it refers to the size of the matrix, which is
+        far less than the dimension of the underlying vector space.
+
+        We default to five in this class, which is safe in `R^n`. The
+        matrix algebra subclasses (or any class where the "size" is
+        interpreted to be far less than the dimension) should override
+        with a smaller number.
+        """
+        return 5
+
 
     def _repr_(self):
         """
@@ -74,20 +188,16 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
         Ensure that it says what we think it says::
 
             sage: JordanSpinEJA(2, field=QQ)
-            Euclidean Jordan algebra of degree 2 over Rational Field
+            Euclidean Jordan algebra of dimension 2 over Rational Field
             sage: JordanSpinEJA(3, field=RDF)
-            Euclidean Jordan algebra of degree 3 over Real Double Field
+            Euclidean Jordan algebra of dimension 3 over Real Double Field
 
         """
-        # TODO: change this to say "dimension" and fix all the tests.
-        fmt = "Euclidean Jordan algebra of degree {} over {}"
+        fmt = "Euclidean Jordan algebra of dimension {} over {}"
         return fmt.format(self.dimension(), self.base_ring())
 
     def product_on_basis(self, i, j):
-        ei = self.basis()[i]
-        ej = self.basis()[j]
-        Lei = self._multiplication_table[i]
-        return self.from_vector(Lei*ej.to_vector())
+        return self._multiplication_table[i][j]
 
     def _a_regular_element(self):
         """
@@ -126,12 +236,18 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
         determinant).
         """
         z = self._a_regular_element()
-        V = self.vector_space()
-        V1 = V.span_of_basis( (z**k).to_vector() for k in range(self.rank()) )
+        # Don't use the parent vector space directly here in case this
+        # happens to be a subalgebra. In that case, we would be e.g.
+        # two-dimensional but span_of_basis() would expect three
+        # coordinates.
+        V = VectorSpace(self.base_ring(), self.vector_space().dimension())
+        basis = [ (z**k).to_vector() for k in range(self.rank()) ]
+        V1 = V.span_of_basis( basis )
         b =  (V1.basis() + V1.complement().basis())
         return V.span_of_basis(b)
 
 
+
     @cached_method
     def _charpoly_coeff(self, i):
         """
@@ -142,6 +258,19 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
         store the trace/determinant (a_{r-1} and a_{0} respectively)
         separate from the entire characteristic polynomial.
         """
+        if self._basis_normalizers is not None:
+             # Must be a matrix class?
+             # WARNING/TODO: this whole mess is mis-designed.
+             n = self.natural_basis_space().nrows()
+             field = self.base_ring().base_ring() # yeeeeaaaahhh
+             J = self.__class__(n, field, False)
+             (_,x,_,_) = J._charpoly_matrix_system()
+             p = J._charpoly_coeff(i)
+             # p might be missing some vars, have to substitute "optionally"
+             pairs = zip(x.base_ring().gens(), self._basis_normalizers)
+             substitutions = { v: v*c for (v,c) in pairs }
+             return p.subs(substitutions)
+
         (A_of_x, x, xr, detA) = self._charpoly_matrix_system()
         R = A_of_x.base_ring()
         if i >= self.rank():
@@ -178,15 +307,40 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
         r = self.rank()
         n = self.dimension()
 
-        # Construct a new algebra over a multivariate polynomial ring...
+        # Turn my vector space into a module so that "vectors" can
+        # have multivatiate polynomial entries.
         names = tuple('X' + str(i) for i in range(1,n+1))
         R = PolynomialRing(self.base_ring(), names)
-        J = FiniteDimensionalEuclideanJordanAlgebra(
-              R,
-              tuple(self._multiplication_table),
-              r)
 
-        idmat = matrix.identity(J.base_ring(), n)
+        # Using change_ring() on the parent's vector space doesn't work
+        # here because, in a subalgebra, that vector space has a basis
+        # and change_ring() tries to bring the basis along with it. And
+        # that doesn't work unless the new ring is a PID, which it usually
+        # won't be.
+        V = FreeModule(R,n)
+
+        # Now let x = (X1,X2,...,Xn) be the vector whose entries are
+        # indeterminates...
+        x = V(names)
+
+        # And figure out the "left multiplication by x" matrix in
+        # that setting.
+        lmbx_cols = []
+        monomial_matrices = [ self.monomial(i).operator().matrix()
+                              for i in range(n) ] # don't recompute these!
+        for k in range(n):
+            ek = self.monomial(k).to_vector()
+            lmbx_cols.append(
+              sum( x[i]*(monomial_matrices[i]*ek)
+                   for i in range(n) ) )
+        Lx = matrix.column(R, lmbx_cols)
+
+        # Now we can compute powers of x "symbolically"
+        x_powers = [self.one().to_vector(), x]
+        for d in range(2, r+1):
+            x_powers.append( Lx*(x_powers[-1]) )
+
+        idmat = matrix.identity(R, n)
 
         W = self._charpoly_basis_space()
         W = W.change_ring(R.fraction_field())
@@ -206,18 +360,10 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
         # We want the middle equivalent thing in our matrix, but use
         # the first equivalent thing instead so that we can pass in
         # standard coordinates.
-        x = J.from_vector(W(R.gens()))
-
-        # Handle the zeroth power separately, because computing
-        # the unit element in J is mathematically suspect.
-        x0 = W.coordinate_vector(self.one().to_vector())
-        l1  = [ x0.column() ]
-        l1 += [ W.coordinate_vector((x**k).to_vector()).column()
-                for k in range(1,r) ]
-        l2 = [idmat.column(k-1).column() for k in range(r+1, n+1)]
-        A_of_x = matrix.block(R, 1, n, (l1 + l2))
-        xr = W.coordinate_vector((x**r).to_vector())
-        return (A_of_x, x, xr, A_of_x.det())
+        x_powers = [ W.coordinate_vector(xp) for xp in x_powers ]
+        l2 = [idmat.column(k-1) for k in range(r+1, n+1)]
+        A_of_x = matrix.column(R, n, (x_powers[:r] + l2))
+        return (A_of_x, x, x_powers[r], A_of_x.det())
 
 
     @cached_method
@@ -307,9 +453,66 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
             True
 
         """
-        if (not x in self) or (not y in self):
-            raise TypeError("arguments must live in this algebra")
-        return x.trace_inner_product(y)
+        X = x.natural_representation()
+        Y = y.natural_representation()
+        return self.natural_inner_product(X,Y)
+
+
+    def is_trivial(self):
+        """
+        Return whether or not this algebra is trivial.
+
+        A trivial algebra contains only the zero element.
+
+        SETUP::
+
+            sage: from mjo.eja.eja_algebra import ComplexHermitianEJA
+
+        EXAMPLES::
+
+            sage: J = ComplexHermitianEJA(3)
+            sage: J.is_trivial()
+            False
+            sage: A = J.zero().subalgebra_generated_by()
+            sage: A.is_trivial()
+            True
+
+        """
+        return self.dimension() == 0
+
+
+    def multiplication_table(self):
+        """
+        Return a visual representation of this algebra's multiplication
+        table (on basis elements).
+
+        SETUP::
+
+            sage: from mjo.eja.eja_algebra import JordanSpinEJA
+
+        EXAMPLES::
+
+            sage: J = JordanSpinEJA(4)
+            sage: J.multiplication_table()
+            +----++----+----+----+----+
+            | *  || e0 | e1 | e2 | e3 |
+            +====++====+====+====+====+
+            | e0 || e0 | e1 | e2 | e3 |
+            +----++----+----+----+----+
+            | e1 || e1 | e0 | 0  | 0  |
+            +----++----+----+----+----+
+            | e2 || e2 | 0  | e0 | 0  |
+            +----++----+----+----+----+
+            | e3 || e3 | 0  | 0  | e0 |
+            +----++----+----+----+----+
+
+        """
+        M = list(self._multiplication_table) # copy
+        for i in range(len(M)):
+            # M had better be "square"
+            M[i] = [self.monomial(i)] + M[i]
+        M = [["*"] + list(self.gens())] + M
+        return table(M, header_row=True, header_column=True, frame=True)
 
 
     def natural_basis(self):
@@ -337,8 +540,8 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
             Finite family {0: e0, 1: e1, 2: e2}
             sage: J.natural_basis()
             (
-            [1 0]  [0 1]  [0 0]
-            [0 0], [1 0], [0 1]
+            [1 0]  [        0 1/2*sqrt2]  [0 0]
+            [0 0], [1/2*sqrt2         0], [0 1]
             )
 
         ::
@@ -354,11 +557,37 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
 
         """
         if self._natural_basis is None:
-            return tuple( b.to_vector().column() for b in self.basis() )
+            M = self.natural_basis_space()
+            return tuple( M(b.to_vector()) for b in self.basis() )
         else:
             return self._natural_basis
 
 
+    def natural_basis_space(self):
+        """
+        Return the matrix space in which this algebra's natural basis
+        elements live.
+        """
+        if self._natural_basis is None or len(self._natural_basis) == 0:
+            return MatrixSpace(self.base_ring(), self.dimension(), 1)
+        else:
+            return self._natural_basis[0].matrix_space()
+
+
+    @staticmethod
+    def natural_inner_product(X,Y):
+        """
+        Compute the inner product of two naturally-represented elements.
+
+        For example in the real symmetric matrix EJA, this will compute
+        the trace inner-product of two n-by-n symmetric matrices. The
+        default should work for the real cartesian product EJA, the
+        Jordan spin EJA, and the real symmetric matrices. The others
+        will have to be overridden.
+        """
+        return (X.conjugate_transpose()*Y).trace()
+
+
     @cached_method
     def one(self):
         """
@@ -375,7 +604,7 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
             sage: J.one()
             e0 + e1 + e2 + e3 + e4
 
-        TESTS::
+        TESTS:
 
         The identity element acts like the identity::
 
@@ -420,6 +649,37 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
         return self.linear_combination(zip(self.gens(), coeffs))
 
 
+    def random_element(self):
+        # Temporary workaround for https://trac.sagemath.org/ticket/28327
+        if self.is_trivial():
+            return self.zero()
+        else:
+            s = super(FiniteDimensionalEuclideanJordanAlgebra, self)
+            return s.random_element()
+
+
+    @classmethod
+    def random_instance(cls, field=QQ, **kwargs):
+        """
+        Return a random instance of this type of algebra.
+
+        In subclasses for algebras that we know how to construct, this
+        is a shortcut for constructing test cases and examples.
+        """
+        if cls is FiniteDimensionalEuclideanJordanAlgebra:
+            # Red flag! But in theory we could do this I guess. The
+            # only finite-dimensional exceptional EJA is the
+            # octononions. So, we could just create an EJA from an
+            # associative matrix algebra (generated by a subset of
+            # elements) with the symmetric product. Or, we could punt
+            # to random_eja() here, override it in our subclasses, and
+            # not worry about it.
+            raise NotImplementedError
+
+        n = ZZ.random_element(1, cls._max_test_case_size())
+        return cls(n, field, **kwargs)
+
+
     def rank(self):
         """
         Return the rank of this EJA.
@@ -492,7 +752,7 @@ class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
 
             sage: J = RealSymmetricEJA(2)
             sage: J.vector_space()
-            Vector space of dimension 3 over Rational Field
+            Vector space of dimension 3 over...
 
         """
         return self.zero().to_vector().parent().ambient_vector_space()
@@ -533,21 +793,56 @@ class RealCartesianProductEJA(FiniteDimensionalEuclideanJordanAlgebra):
         sage: e2*e2
         e2
 
+    TESTS:
+
+    We can change the generator prefix::
+
+        sage: RealCartesianProductEJA(3, prefix='r').gens()
+        (r0, r1, r2)
+
+    Our inner product satisfies the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: J = RealCartesianProductEJA.random_instance()
+        sage: x = J.random_element()
+        sage: y = J.random_element()
+        sage: z = J.random_element()
+        sage: (x*y).inner_product(z) == y.inner_product(x*z)
+        True
+
     """
-    def __init__(self, n, field=QQ):
-        # The superclass constructor takes a list of matrices, the ith
-        # representing right multiplication by the ith basis element
-        # in the vector space. So if e_1 = (1,0,0), then right
-        # (Hadamard) multiplication of x by e_1 picks out the first
-        # component of x; and likewise for the ith basis element e_i.
-        Qs = [ matrix(field, n, n, lambda k,j: 1*(k == j == i))
-               for i in xrange(n) ]
+    def __init__(self, n, field=QQ, **kwargs):
+        V = VectorSpace(field, n)
+        mult_table = [ [ V.gen(i)*(i == j) for j in range(n) ]
+                       for i in range(n) ]
 
         fdeja = super(RealCartesianProductEJA, self)
-        return fdeja.__init__(field, Qs, rank=n)
+        return fdeja.__init__(field, mult_table, rank=n, **kwargs)
 
     def inner_product(self, x, y):
-        return _usual_ip(x,y)
+        """
+        Faster to reimplement than to use natural representations.
+
+        SETUP::
+
+            sage: from mjo.eja.eja_algebra import RealCartesianProductEJA
+
+        TESTS:
+
+        Ensure that this is the usual inner product for the algebras
+        over `R^n`::
+
+            sage: set_random_seed()
+            sage: J = RealCartesianProductEJA.random_instance()
+            sage: x = J.random_element()
+            sage: y = J.random_element()
+            sage: X = x.natural_representation()
+            sage: Y = y.natural_representation()
+            sage: x.inner_product(y) == J.natural_inner_product(X,Y)
+            True
+
+        """
+        return x.to_vector().inner_product(y.to_vector())
 
 
 def random_eja():
@@ -583,27 +878,34 @@ def random_eja():
     TESTS::
 
         sage: random_eja()
-        Euclidean Jordan algebra of degree...
+        Euclidean Jordan algebra of dimension...
 
     """
+    classname = choice([RealCartesianProductEJA,
+                        JordanSpinEJA,
+                        RealSymmetricEJA,
+                        ComplexHermitianEJA,
+                        QuaternionHermitianEJA])
+    return classname.random_instance()
 
-    # The max_n component lets us choose different upper bounds on the
-    # value "n" that gets passed to the constructor. This is needed
-    # because e.g. R^{10} is reasonable to test, while the Hermitian
-    # 10-by-10 quaternion matrices are not.
-    (constructor, max_n) = choice([(RealCartesianProductEJA, 6),
-                                   (JordanSpinEJA, 6),
-                                   (RealSymmetricEJA, 5),
-                                   (ComplexHermitianEJA, 4),
-                                   (QuaternionHermitianEJA, 3)])
-    n = ZZ.random_element(1, max_n)
-    return constructor(n, field=QQ)
 
 
-
-def _real_symmetric_basis(n, field=QQ):
+def _real_symmetric_basis(n, field):
     """
     Return a basis for the space of real symmetric n-by-n matrices.
+
+    SETUP::
+
+        sage: from mjo.eja.eja_algebra import _real_symmetric_basis
+
+    TESTS::
+
+        sage: set_random_seed()
+        sage: n = ZZ.random_element(1,5)
+        sage: B = _real_symmetric_basis(n, QQ)
+        sage: all( M.is_symmetric() for M in  B)
+        True
+
     """
     # The basis of symmetric matrices, as matrices, in their R^(n-by-n)
     # coordinates.
@@ -614,16 +916,21 @@ def _real_symmetric_basis(n, field=QQ):
             if i == j:
                 Sij = Eij
             else:
-                # Beware, orthogonal but not normalized!
                 Sij = Eij + Eij.transpose()
             S.append(Sij)
     return tuple(S)
 
 
-def _complex_hermitian_basis(n, field=QQ):
+def _complex_hermitian_basis(n, field):
     """
     Returns a basis for the space of complex Hermitian n-by-n matrices.
 
+    Why do we embed these? Basically, because all of numerical linear
+    algebra assumes that you're working with vectors consisting of `n`
+    entries from a field and scalars from the same field. There's no way
+    to tell SageMath that (for example) the vectors contain complex
+    numbers, while the scalar field is real.
+
     SETUP::
 
         sage: from mjo.eja.eja_algebra import _complex_hermitian_basis
@@ -632,11 +939,15 @@ def _complex_hermitian_basis(n, field=QQ):
 
         sage: set_random_seed()
         sage: n = ZZ.random_element(1,5)
-        sage: all( M.is_symmetric() for M in _complex_hermitian_basis(n) )
+        sage: field = QuadraticField(2, 'sqrt2')
+        sage: B = _complex_hermitian_basis(n, field)
+        sage: all( M.is_symmetric() for M in  B)
         True
 
     """
-    F = QuadraticField(-1, 'I')
+    R = PolynomialRing(field, 'z')
+    z = R.gen()
+    F = NumberField(z**2 + 1, 'I', embedding=CLF(-1).sqrt())
     I = F.gen()
 
     # This is like the symmetric case, but we need to be careful:
@@ -647,24 +958,33 @@ def _complex_hermitian_basis(n, field=QQ):
     S = []
     for i in xrange(n):
         for j in xrange(i+1):
-            Eij = matrix(field, n, lambda k,l: k==i and l==j)
+            Eij = matrix(F, n, lambda k,l: k==i and l==j)
             if i == j:
                 Sij = _embed_complex_matrix(Eij)
                 S.append(Sij)
             else:
-                # Beware, orthogonal but not normalized! The second one
-                # has a minus because it's conjugated.
+                # The second one has a minus because it's conjugated.
                 Sij_real = _embed_complex_matrix(Eij + Eij.transpose())
                 S.append(Sij_real)
                 Sij_imag = _embed_complex_matrix(I*Eij - I*Eij.transpose())
                 S.append(Sij_imag)
-    return tuple(S)
+
+    # Since we embedded these, we can drop back to the "field" that we
+    # started with instead of the complex extension "F".
+    return tuple( s.change_ring(field) for s in S )
 
 
-def _quaternion_hermitian_basis(n, field=QQ):
+
+def _quaternion_hermitian_basis(n, field):
     """
     Returns a basis for the space of quaternion Hermitian n-by-n matrices.
 
+    Why do we embed these? Basically, because all of numerical linear
+    algebra assumes that you're working with vectors consisting of `n`
+    entries from a field and scalars from the same field. There's no way
+    to tell SageMath that (for example) the vectors contain complex
+    numbers, while the scalar field is real.
+
     SETUP::
 
         sage: from mjo.eja.eja_algebra import _quaternion_hermitian_basis
@@ -673,7 +993,8 @@ def _quaternion_hermitian_basis(n, field=QQ):
 
         sage: set_random_seed()
         sage: n = ZZ.random_element(1,5)
-        sage: all( M.is_symmetric() for M in _quaternion_hermitian_basis(n) )
+        sage: B = _quaternion_hermitian_basis(n, QQ)
+        sage: all( M.is_symmetric() for M in B )
         True
 
     """
@@ -715,10 +1036,7 @@ def _multiplication_table_from_matrix_basis(basis):
     multiplication on the right is matrix multiplication. Given a basis
     for the underlying matrix space, this function returns a
     multiplication table (obtained by looping through the basis
-    elements) for an algebra of those matrices. A reordered copy
-    of the basis is also returned to work around the fact that
-    the ``span()`` in this function will change the order of the basis
-    from what we think it is, to... something else.
+    elements) for an algebra of those matrices.
     """
     # In S^2, for example, we nominally have four coordinates even
     # though the space is of dimension three only. The vector space V
@@ -730,20 +1048,14 @@ def _multiplication_table_from_matrix_basis(basis):
 
     V = VectorSpace(field, dimension**2)
     W = V.span_of_basis( _mat2vec(s) for s in basis )
+    n = len(basis)
+    mult_table = [[W.zero() for j in range(n)] for i in range(n)]
+    for i in range(n):
+        for j in range(n):
+            mat_entry = (basis[i]*basis[j] + basis[j]*basis[i])/2
+            mult_table[i][j] = W.coordinate_vector(_mat2vec(mat_entry))
 
-    Qs = []
-    for s in basis:
-        # Brute force the multiplication-by-s matrix by looping
-        # through all elements of the basis and doing the computation
-        # to find out what the corresponding row should be.
-        Q_cols = []
-        for t in basis:
-            this_col = _mat2vec((s*t + t*s)/2)
-            Q_cols.append(W.coordinates(this_col))
-        Q = matrix.column(field, W.dimension(), Q_cols)
-        Qs.append(Q)
-
-    return Qs
+    return mult_table
 
 
 def _embed_complex_matrix(M):
@@ -754,11 +1066,12 @@ def _embed_complex_matrix(M):
 
     SETUP::
 
-        sage: from mjo.eja.eja_algebra import _embed_complex_matrix
+        sage: from mjo.eja.eja_algebra import (_embed_complex_matrix,
+        ....:                                  ComplexHermitianEJA)
 
     EXAMPLES::
 
-        sage: F = QuadraticField(-1,'i')
+        sage: F = QuadraticField(-1, 'i')
         sage: x1 = F(4 - 2*i)
         sage: x2 = F(1 + 2*i)
         sage: x3 = F(-i)
@@ -776,7 +1089,8 @@ def _embed_complex_matrix(M):
     Embedding is a homomorphism (isomorphism, in fact)::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(5)
+        sage: n_max = ComplexHermitianEJA._max_test_case_size()
+        sage: n = ZZ.random_element(n_max)
         sage: F = QuadraticField(-1, 'i')
         sage: X = random_matrix(F, n)
         sage: Y = random_matrix(F, n)
@@ -792,8 +1106,8 @@ def _embed_complex_matrix(M):
     field = M.base_ring()
     blocks = []
     for z in M.list():
-        a = z.real()
-        b = z.imag()
+        a = z.vector()[0] # real part, I guess
+        b = z.vector()[1] # imag part, I guess
         blocks.append(matrix(field, 2, [[a,b],[-b,a]]))
 
     # We can drop the imaginaries here.
@@ -836,7 +1150,10 @@ def _unembed_complex_matrix(M):
     if not n.mod(2).is_zero():
         raise ValueError("the matrix 'M' must be a complex embedding")
 
-    F = QuadraticField(-1, 'i')
+    field = M.base_ring() # This should already have sqrt2
+    R = PolynomialRing(field, 'z')
+    z = R.gen()
+    F = NumberField(z**2 + 1,'i', embedding=CLF(-1).sqrt())
     i = F.gen()
 
     # Go top-left to bottom-right (reading order), converting every
@@ -865,7 +1182,8 @@ def _embed_quaternion_matrix(M):
 
     SETUP::
 
-        sage: from mjo.eja.eja_algebra import _embed_quaternion_matrix
+        sage: from mjo.eja.eja_algebra import (_embed_quaternion_matrix,
+        ....:                                  QuaternionHermitianEJA)
 
     EXAMPLES::
 
@@ -882,7 +1200,8 @@ def _embed_quaternion_matrix(M):
     Embedding is a homomorphism (isomorphism, in fact)::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(5)
+        sage: n_max = QuaternionHermitianEJA._max_test_case_size()
+        sage: n = ZZ.random_element(n_max)
         sage: Q = QuaternionAlgebra(QQ,-1,-1)
         sage: X = random_matrix(Q, n)
         sage: Y = random_matrix(Q, n)
@@ -951,7 +1270,10 @@ def _unembed_quaternion_matrix(M):
     if not n.mod(4).is_zero():
         raise ValueError("the matrix 'M' must be a complex embedding")
 
-    Q = QuaternionAlgebra(QQ,-1,-1)
+    # Use the base ring of the matrix to ensure that its entries can be
+    # multiplied by elements of the quaternion algebra.
+    field = M.base_ring()
+    Q = QuaternionAlgebra(field,-1,-1)
     i,j,k = Q.gens()
 
     # Go top-left to bottom-right (reading order), converting every
@@ -965,17 +1287,15 @@ def _unembed_quaternion_matrix(M):
                 raise ValueError('bad on-diagonal submatrix')
             if submat[0,1] != -submat[1,0].conjugate():
                 raise ValueError('bad off-diagonal submatrix')
-            z  = submat[0,0].real() + submat[0,0].imag()*i
-            z += submat[0,1].real()*j + submat[0,1].imag()*k
+            z  = submat[0,0].vector()[0]   # real part
+            z += submat[0,0].vector()[1]*i # imag part
+            z += submat[0,1].vector()[0]*j # real part
+            z += submat[0,1].vector()[1]*k # imag part
             elements.append(z)
 
     return matrix(Q, n/4, elements)
 
 
-# The usual inner product on R^n.
-def _usual_ip(x,y):
-    return x.to_vector().inner_product(y.to_vector())
-
 # The inner product used for the real symmetric simple EJA.
 # We keep it as a separate function because e.g. the complex
 # algebra uses the same inner product, except divided by 2.
@@ -1002,7 +1322,7 @@ class RealSymmetricEJA(FiniteDimensionalEuclideanJordanAlgebra):
         sage: e0*e0
         e0
         sage: e1*e1
-        e0 + e2
+        1/2*e0 + 1/2*e2
         sage: e2*e2
         e2
 
@@ -1011,7 +1331,8 @@ class RealSymmetricEJA(FiniteDimensionalEuclideanJordanAlgebra):
     The dimension of this algebra is `(n^2 + n) / 2`::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(1,5)
+        sage: n_max = RealSymmetricEJA._max_test_case_size()
+        sage: n = ZZ.random_element(1, n_max)
         sage: J = RealSymmetricEJA(n)
         sage: J.dimension() == (n^2 + n)/2
         True
@@ -1019,8 +1340,7 @@ class RealSymmetricEJA(FiniteDimensionalEuclideanJordanAlgebra):
     The Jordan multiplication is what we think it is::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(1,5)
-        sage: J = RealSymmetricEJA(n)
+        sage: J = RealSymmetricEJA.random_instance()
         sage: x = J.random_element()
         sage: y = J.random_element()
         sage: actual = (x*y).natural_representation()
@@ -1032,19 +1352,70 @@ class RealSymmetricEJA(FiniteDimensionalEuclideanJordanAlgebra):
         sage: J(expected) == x*y
         True
 
+    We can change the generator prefix::
+
+        sage: RealSymmetricEJA(3, prefix='q').gens()
+        (q0, q1, q2, q3, q4, q5)
+
+    Our inner product satisfies the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: J = RealSymmetricEJA.random_instance()
+        sage: x = J.random_element()
+        sage: y = J.random_element()
+        sage: z = J.random_element()
+        sage: (x*y).inner_product(z) == y.inner_product(x*z)
+        True
+
+    Our natural basis is normalized with respect to the natural inner
+    product unless we specify otherwise::
+
+        sage: set_random_seed()
+        sage: J = RealSymmetricEJA.random_instance()
+        sage: all( b.norm() == 1 for b in J.gens() )
+        True
+
+    Since our natural basis is normalized with respect to the natural
+    inner product, and since we know that this algebra is an EJA, any
+    left-multiplication operator's matrix will be symmetric because
+    natural->EJA basis representation is an isometry and within the EJA
+    the operator is self-adjoint by the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: x = RealSymmetricEJA.random_instance().random_element()
+        sage: x.operator().matrix().is_symmetric()
+        True
+
     """
-    def __init__(self, n, field=QQ):
-        S = _real_symmetric_basis(n, field=field)
+    def __init__(self, n, field=QQ, normalize_basis=True, **kwargs):
+        S = _real_symmetric_basis(n, field)
+
+        if n > 1 and normalize_basis:
+            # We'll need sqrt(2) to normalize the basis, and this
+            # winds up in the multiplication table, so the whole
+            # algebra needs to be over the field extension.
+            R = PolynomialRing(field, 'z')
+            z = R.gen()
+            p = z**2 - 2
+            if p.is_irreducible():
+                field = NumberField(p, 'sqrt2', embedding=RLF(2).sqrt())
+                S = [ s.change_ring(field) for s in S ]
+            self._basis_normalizers = tuple(
+                ~(self.natural_inner_product(s,s).sqrt()) for s in S )
+            S = tuple( s*c for (s,c) in zip(S,self._basis_normalizers) )
+
         Qs = _multiplication_table_from_matrix_basis(S)
 
         fdeja = super(RealSymmetricEJA, self)
         return fdeja.__init__(field,
                               Qs,
                               rank=n,
-                              natural_basis=S)
+                              natural_basis=S,
+                              **kwargs)
 
-    def inner_product(self, x, y):
-        return _matrix_ip(x,y)
+    @staticmethod
+    def _max_test_case_size():
+        return 5
 
 
 class ComplexHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
@@ -1063,7 +1434,8 @@ class ComplexHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
     The dimension of this algebra is `n^2`::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(1,5)
+        sage: n_max = ComplexHermitianEJA._max_test_case_size()
+        sage: n = ZZ.random_element(1, n_max)
         sage: J = ComplexHermitianEJA(n)
         sage: J.dimension() == n^2
         True
@@ -1071,8 +1443,7 @@ class ComplexHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
     The Jordan multiplication is what we think it is::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(1,5)
-        sage: J = ComplexHermitianEJA(n)
+        sage: J = ComplexHermitianEJA.random_instance()
         sage: x = J.random_element()
         sage: y = J.random_element()
         sage: actual = (x*y).natural_representation()
@@ -1084,27 +1455,79 @@ class ComplexHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
         sage: J(expected) == x*y
         True
 
+    We can change the generator prefix::
+
+        sage: ComplexHermitianEJA(2, prefix='z').gens()
+        (z0, z1, z2, z3)
+
+    Our inner product satisfies the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: J = ComplexHermitianEJA.random_instance()
+        sage: x = J.random_element()
+        sage: y = J.random_element()
+        sage: z = J.random_element()
+        sage: (x*y).inner_product(z) == y.inner_product(x*z)
+        True
+
+    Our natural basis is normalized with respect to the natural inner
+    product unless we specify otherwise::
+
+        sage: set_random_seed()
+        sage: J = ComplexHermitianEJA.random_instance()
+        sage: all( b.norm() == 1 for b in J.gens() )
+        True
+
+    Since our natural basis is normalized with respect to the natural
+    inner product, and since we know that this algebra is an EJA, any
+    left-multiplication operator's matrix will be symmetric because
+    natural->EJA basis representation is an isometry and within the EJA
+    the operator is self-adjoint by the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: x = ComplexHermitianEJA.random_instance().random_element()
+        sage: x.operator().matrix().is_symmetric()
+        True
+
     """
-    def __init__(self, n, field=QQ):
-        S = _complex_hermitian_basis(n)
+    def __init__(self, n, field=QQ, normalize_basis=True, **kwargs):
+        S = _complex_hermitian_basis(n, field)
+
+        if n > 1 and normalize_basis:
+            # We'll need sqrt(2) to normalize the basis, and this
+            # winds up in the multiplication table, so the whole
+            # algebra needs to be over the field extension.
+            R = PolynomialRing(field, 'z')
+            z = R.gen()
+            p = z**2 - 2
+            if p.is_irreducible():
+                field = NumberField(p, 'sqrt2', embedding=RLF(2).sqrt())
+                S = [ s.change_ring(field) for s in S ]
+            self._basis_normalizers = tuple(
+                ~(self.natural_inner_product(s,s).sqrt()) for s in S )
+            S = tuple( s*c for (s,c) in zip(S,self._basis_normalizers) )
+
         Qs = _multiplication_table_from_matrix_basis(S)
 
         fdeja = super(ComplexHermitianEJA, self)
         return fdeja.__init__(field,
                               Qs,
                               rank=n,
-                              natural_basis=S)
+                              natural_basis=S,
+                              **kwargs)
 
 
-    def inner_product(self, x, y):
-        # Since a+bi on the diagonal is represented as
-        #
-        #   a + bi  = [  a  b  ]
-        #             [ -b  a  ],
-        #
-        # we'll double-count the "a" entries if we take the trace of
-        # the embedding.
-        return _matrix_ip(x,y)/2
+    @staticmethod
+    def _max_test_case_size():
+        return 4
+
+    @staticmethod
+    def natural_inner_product(X,Y):
+        Xu = _unembed_complex_matrix(X)
+        Yu = _unembed_complex_matrix(Y)
+        # The trace need not be real; consider Xu = (i*I) and Yu = I.
+        return ((Xu*Yu).trace()).vector()[0] # real part, I guess
+
 
 
 class QuaternionHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
@@ -1120,10 +1543,11 @@ class QuaternionHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
 
     TESTS:
 
-    The dimension of this algebra is `n^2`::
+    The dimension of this algebra is `2*n^2 - n`::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(1,5)
+        sage: n_max = QuaternionHermitianEJA._max_test_case_size()
+        sage: n = ZZ.random_element(1, n_max)
         sage: J = QuaternionHermitianEJA(n)
         sage: J.dimension() == 2*(n^2) - n
         True
@@ -1131,8 +1555,7 @@ class QuaternionHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
     The Jordan multiplication is what we think it is::
 
         sage: set_random_seed()
-        sage: n = ZZ.random_element(1,5)
-        sage: J = QuaternionHermitianEJA(n)
+        sage: J = QuaternionHermitianEJA.random_instance()
         sage: x = J.random_element()
         sage: y = J.random_element()
         sage: actual = (x*y).natural_representation()
@@ -1144,28 +1567,81 @@ class QuaternionHermitianEJA(FiniteDimensionalEuclideanJordanAlgebra):
         sage: J(expected) == x*y
         True
 
+    We can change the generator prefix::
+
+        sage: QuaternionHermitianEJA(2, prefix='a').gens()
+        (a0, a1, a2, a3, a4, a5)
+
+    Our inner product satisfies the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: J = QuaternionHermitianEJA.random_instance()
+        sage: x = J.random_element()
+        sage: y = J.random_element()
+        sage: z = J.random_element()
+        sage: (x*y).inner_product(z) == y.inner_product(x*z)
+        True
+
+    Our natural basis is normalized with respect to the natural inner
+    product unless we specify otherwise::
+
+        sage: set_random_seed()
+        sage: J = QuaternionHermitianEJA.random_instance()
+        sage: all( b.norm() == 1 for b in J.gens() )
+        True
+
+    Since our natural basis is normalized with respect to the natural
+    inner product, and since we know that this algebra is an EJA, any
+    left-multiplication operator's matrix will be symmetric because
+    natural->EJA basis representation is an isometry and within the EJA
+    the operator is self-adjoint by the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: x = QuaternionHermitianEJA.random_instance().random_element()
+        sage: x.operator().matrix().is_symmetric()
+        True
+
     """
-    def __init__(self, n, field=QQ):
-        S = _quaternion_hermitian_basis(n)
+    def __init__(self, n, field=QQ, normalize_basis=True, **kwargs):
+        S = _quaternion_hermitian_basis(n, field)
+
+        if n > 1 and normalize_basis:
+            # We'll need sqrt(2) to normalize the basis, and this
+            # winds up in the multiplication table, so the whole
+            # algebra needs to be over the field extension.
+            R = PolynomialRing(field, 'z')
+            z = R.gen()
+            p = z**2 - 2
+            if p.is_irreducible():
+                field = NumberField(p, 'sqrt2', embedding=RLF(2).sqrt())
+                S = [ s.change_ring(field) for s in S ]
+            self._basis_normalizers = tuple(
+                ~(self.natural_inner_product(s,s).sqrt()) for s in S )
+            S = tuple( s*c for (s,c) in zip(S,self._basis_normalizers) )
+
         Qs = _multiplication_table_from_matrix_basis(S)
 
         fdeja = super(QuaternionHermitianEJA, self)
         return fdeja.__init__(field,
                               Qs,
                               rank=n,
-                              natural_basis=S)
+                              natural_basis=S,
+                              **kwargs)
+
+    @staticmethod
+    def _max_test_case_size():
+        return 3
+
+    @staticmethod
+    def natural_inner_product(X,Y):
+        Xu = _unembed_quaternion_matrix(X)
+        Yu = _unembed_quaternion_matrix(Y)
+        # The trace need not be real; consider Xu = (i*I) and Yu = I.
+        # The result will be a quaternion algebra element, which doesn't
+        # have a "vector" method, but does have coefficient_tuple() method
+        # that returns the coefficients of 1, i, j, and k -- in that order.
+        return ((Xu*Yu).trace()).coefficient_tuple()[0]
 
-    def inner_product(self, x, y):
-        # Since a+bi+cj+dk on the diagonal is represented as
-        #
-        #   a + bi +cj + dk = [  a  b  c  d]
-        #                     [ -b  a -d  c]
-        #                     [ -c  d  a -b]
-        #                     [ -d -c  b  a],
-        #
-        # we'll quadruple-count the "a" entries if we take the trace of
-        # the embedding.
-        return _matrix_ip(x,y)/4
 
 
 class JordanSpinEJA(FiniteDimensionalEuclideanJordanAlgebra):
@@ -1200,26 +1676,66 @@ class JordanSpinEJA(FiniteDimensionalEuclideanJordanAlgebra):
         sage: e2*e3
         0
 
+    We can change the generator prefix::
+
+        sage: JordanSpinEJA(2, prefix='B').gens()
+        (B0, B1)
+
+    Our inner product satisfies the Jordan axiom::
+
+        sage: set_random_seed()
+        sage: J = JordanSpinEJA.random_instance()
+        sage: x = J.random_element()
+        sage: y = J.random_element()
+        sage: z = J.random_element()
+        sage: (x*y).inner_product(z) == y.inner_product(x*z)
+        True
+
     """
-    def __init__(self, n, field=QQ):
-        Qs = []
-        id_matrix = matrix.identity(field, n)
-        for i in xrange(n):
-            ei = id_matrix.column(i)
-            Qi = matrix.zero(field, n)
-            Qi.set_row(0, ei)
-            Qi.set_column(0, ei)
-            Qi += matrix.diagonal(n, [ei[0]]*n)
-            # The addition of the diagonal matrix adds an extra ei[0] in the
-            # upper-left corner of the matrix.
-            Qi[0,0] = Qi[0,0] * ~field(2)
-            Qs.append(Qi)
+    def __init__(self, n, field=QQ, **kwargs):
+        V = VectorSpace(field, n)
+        mult_table = [[V.zero() for j in range(n)] for i in range(n)]
+        for i in range(n):
+            for j in range(n):
+                x = V.gen(i)
+                y = V.gen(j)
+                x0 = x[0]
+                xbar = x[1:]
+                y0 = y[0]
+                ybar = y[1:]
+                # z = x*y
+                z0 = x.inner_product(y)
+                zbar = y0*xbar + x0*ybar
+                z = V([z0] + zbar.list())
+                mult_table[i][j] = z
 
         # The rank of the spin algebra is two, unless we're in a
         # one-dimensional ambient space (because the rank is bounded by
         # the ambient dimension).
         fdeja = super(JordanSpinEJA, self)
-        return fdeja.__init__(field, Qs, rank=min(n,2))
+        return fdeja.__init__(field, mult_table, rank=min(n,2), **kwargs)
 
     def inner_product(self, x, y):
-        return _usual_ip(x,y)
+        """
+        Faster to reimplement than to use natural representations.
+
+        SETUP::
+
+            sage: from mjo.eja.eja_algebra import JordanSpinEJA
+
+        TESTS:
+
+        Ensure that this is the usual inner product for the algebras
+        over `R^n`::
+
+            sage: set_random_seed()
+            sage: J = JordanSpinEJA.random_instance()
+            sage: x = J.random_element()
+            sage: y = J.random_element()
+            sage: X = x.natural_representation()
+            sage: Y = y.natural_representation()
+            sage: x.inner_product(y) == J.natural_inner_product(X,Y)
+            True
+
+        """
+        return x.to_vector().inner_product(y.to_vector())