]> gitweb.michael.orlitzky.com - sage.d.git/blob - mjo/eja/eja_algebra.py
eja: add the RealMatrixEuclideanJordanAlgebra class.
[sage.d.git] / mjo / eja / eja_algebra.py
1 """
2 Euclidean Jordan Algebras. These are formally-real Jordan Algebras;
3 specifically those where u^2 + v^2 = 0 implies that u = v = 0. They
4 are used in optimization, and have some additional nice methods beyond
5 what can be supported in a general Jordan Algebra.
6 """
7
8 from itertools import repeat
9
10 from sage.algebras.quatalg.quaternion_algebra import QuaternionAlgebra
11 from sage.categories.magmatic_algebras import MagmaticAlgebras
12 from sage.combinat.free_module import CombinatorialFreeModule
13 from sage.matrix.constructor import matrix
14 from sage.matrix.matrix_space import MatrixSpace
15 from sage.misc.cachefunc import cached_method
16 from sage.misc.prandom import choice
17 from sage.misc.table import table
18 from sage.modules.free_module import FreeModule, VectorSpace
19 from sage.rings.integer_ring import ZZ
20 from sage.rings.number_field.number_field import NumberField, QuadraticField
21 from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
22 from sage.rings.rational_field import QQ
23 from sage.rings.real_lazy import CLF, RLF
24 from sage.structure.element import is_Matrix
25
26 from mjo.eja.eja_element import FiniteDimensionalEuclideanJordanAlgebraElement
27 from mjo.eja.eja_utils import _mat2vec
28
29 class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
30 # This is an ugly hack needed to prevent the category framework
31 # from implementing a coercion from our base ring (e.g. the
32 # rationals) into the algebra. First of all -- such a coercion is
33 # nonsense to begin with. But more importantly, it tries to do so
34 # in the category of rings, and since our algebras aren't
35 # associative they generally won't be rings.
36 _no_generic_basering_coercion = True
37
38 def __init__(self,
39 field,
40 mult_table,
41 rank,
42 prefix='e',
43 category=None,
44 natural_basis=None):
45 """
46 SETUP::
47
48 sage: from mjo.eja.eja_algebra import random_eja
49
50 EXAMPLES:
51
52 By definition, Jordan multiplication commutes::
53
54 sage: set_random_seed()
55 sage: J = random_eja()
56 sage: x,y = J.random_elements(2)
57 sage: x*y == y*x
58 True
59
60 """
61 self._rank = rank
62 self._natural_basis = natural_basis
63
64 # TODO: HACK for the charpoly.. needs redesign badly.
65 self._basis_normalizers = None
66
67 if category is None:
68 category = MagmaticAlgebras(field).FiniteDimensional()
69 category = category.WithBasis().Unital()
70
71 fda = super(FiniteDimensionalEuclideanJordanAlgebra, self)
72 fda.__init__(field,
73 range(len(mult_table)),
74 prefix=prefix,
75 category=category)
76 self.print_options(bracket='')
77
78 # The multiplication table we're given is necessarily in terms
79 # of vectors, because we don't have an algebra yet for
80 # anything to be an element of. However, it's faster in the
81 # long run to have the multiplication table be in terms of
82 # algebra elements. We do this after calling the superclass
83 # constructor so that from_vector() knows what to do.
84 self._multiplication_table = [ map(lambda x: self.from_vector(x), ls)
85 for ls in mult_table ]
86
87
88 def _element_constructor_(self, elt):
89 """
90 Construct an element of this algebra from its natural
91 representation.
92
93 This gets called only after the parent element _call_ method
94 fails to find a coercion for the argument.
95
96 SETUP::
97
98 sage: from mjo.eja.eja_algebra import (JordanSpinEJA,
99 ....: RealCartesianProductEJA,
100 ....: RealSymmetricEJA)
101
102 EXAMPLES:
103
104 The identity in `S^n` is converted to the identity in the EJA::
105
106 sage: J = RealSymmetricEJA(3)
107 sage: I = matrix.identity(QQ,3)
108 sage: J(I) == J.one()
109 True
110
111 This skew-symmetric matrix can't be represented in the EJA::
112
113 sage: J = RealSymmetricEJA(3)
114 sage: A = matrix(QQ,3, lambda i,j: i-j)
115 sage: J(A)
116 Traceback (most recent call last):
117 ...
118 ArithmeticError: vector is not in free module
119
120 TESTS:
121
122 Ensure that we can convert any element of the two non-matrix
123 simple algebras (whose natural representations are their usual
124 vector representations) back and forth faithfully::
125
126 sage: set_random_seed()
127 sage: J = RealCartesianProductEJA.random_instance()
128 sage: x = J.random_element()
129 sage: J(x.to_vector().column()) == x
130 True
131 sage: J = JordanSpinEJA.random_instance()
132 sage: x = J.random_element()
133 sage: J(x.to_vector().column()) == x
134 True
135
136 """
137 if elt == 0:
138 # The superclass implementation of random_element()
139 # needs to be able to coerce "0" into the algebra.
140 return self.zero()
141
142 natural_basis = self.natural_basis()
143 basis_space = natural_basis[0].matrix_space()
144 if elt not in basis_space:
145 raise ValueError("not a naturally-represented algebra element")
146
147 # Thanks for nothing! Matrix spaces aren't vector spaces in
148 # Sage, so we have to figure out its natural-basis coordinates
149 # ourselves. We use the basis space's ring instead of the
150 # element's ring because the basis space might be an algebraic
151 # closure whereas the base ring of the 3-by-3 identity matrix
152 # could be QQ instead of QQbar.
153 V = VectorSpace(basis_space.base_ring(), elt.nrows()*elt.ncols())
154 W = V.span_of_basis( _mat2vec(s) for s in natural_basis )
155 coords = W.coordinate_vector(_mat2vec(elt))
156 return self.from_vector(coords)
157
158
159 @staticmethod
160 def _max_test_case_size():
161 """
162 Return an integer "size" that is an upper bound on the size of
163 this algebra when it is used in a random test
164 case. Unfortunately, the term "size" is quite vague -- when
165 dealing with `R^n` under either the Hadamard or Jordan spin
166 product, the "size" refers to the dimension `n`. When dealing
167 with a matrix algebra (real symmetric or complex/quaternion
168 Hermitian), it refers to the size of the matrix, which is
169 far less than the dimension of the underlying vector space.
170
171 We default to five in this class, which is safe in `R^n`. The
172 matrix algebra subclasses (or any class where the "size" is
173 interpreted to be far less than the dimension) should override
174 with a smaller number.
175 """
176 return 5
177
178
179 def _repr_(self):
180 """
181 Return a string representation of ``self``.
182
183 SETUP::
184
185 sage: from mjo.eja.eja_algebra import JordanSpinEJA
186
187 TESTS:
188
189 Ensure that it says what we think it says::
190
191 sage: JordanSpinEJA(2, field=QQ)
192 Euclidean Jordan algebra of dimension 2 over Rational Field
193 sage: JordanSpinEJA(3, field=RDF)
194 Euclidean Jordan algebra of dimension 3 over Real Double Field
195
196 """
197 fmt = "Euclidean Jordan algebra of dimension {} over {}"
198 return fmt.format(self.dimension(), self.base_ring())
199
200 def product_on_basis(self, i, j):
201 return self._multiplication_table[i][j]
202
203 def _a_regular_element(self):
204 """
205 Guess a regular element. Needed to compute the basis for our
206 characteristic polynomial coefficients.
207
208 SETUP::
209
210 sage: from mjo.eja.eja_algebra import random_eja
211
212 TESTS:
213
214 Ensure that this hacky method succeeds for every algebra that we
215 know how to construct::
216
217 sage: set_random_seed()
218 sage: J = random_eja()
219 sage: J._a_regular_element().is_regular()
220 True
221
222 """
223 gs = self.gens()
224 z = self.sum( (i+1)*gs[i] for i in range(len(gs)) )
225 if not z.is_regular():
226 raise ValueError("don't know a regular element")
227 return z
228
229
230 @cached_method
231 def _charpoly_basis_space(self):
232 """
233 Return the vector space spanned by the basis used in our
234 characteristic polynomial coefficients. This is used not only to
235 compute those coefficients, but also any time we need to
236 evaluate the coefficients (like when we compute the trace or
237 determinant).
238 """
239 z = self._a_regular_element()
240 # Don't use the parent vector space directly here in case this
241 # happens to be a subalgebra. In that case, we would be e.g.
242 # two-dimensional but span_of_basis() would expect three
243 # coordinates.
244 V = VectorSpace(self.base_ring(), self.vector_space().dimension())
245 basis = [ (z**k).to_vector() for k in range(self.rank()) ]
246 V1 = V.span_of_basis( basis )
247 b = (V1.basis() + V1.complement().basis())
248 return V.span_of_basis(b)
249
250
251
252 @cached_method
253 def _charpoly_coeff(self, i):
254 """
255 Return the coefficient polynomial "a_{i}" of this algebra's
256 general characteristic polynomial.
257
258 Having this be a separate cached method lets us compute and
259 store the trace/determinant (a_{r-1} and a_{0} respectively)
260 separate from the entire characteristic polynomial.
261 """
262 if self._basis_normalizers is not None:
263 # Must be a matrix class?
264 # WARNING/TODO: this whole mess is mis-designed.
265 n = self.natural_basis_space().nrows()
266 field = self.base_ring().base_ring() # yeeeeaaaahhh
267 J = self.__class__(n, field, False)
268 (_,x,_,_) = J._charpoly_matrix_system()
269 p = J._charpoly_coeff(i)
270 # p might be missing some vars, have to substitute "optionally"
271 pairs = zip(x.base_ring().gens(), self._basis_normalizers)
272 substitutions = { v: v*c for (v,c) in pairs }
273 return p.subs(substitutions)
274
275 (A_of_x, x, xr, detA) = self._charpoly_matrix_system()
276 R = A_of_x.base_ring()
277 if i >= self.rank():
278 # Guaranteed by theory
279 return R.zero()
280
281 # Danger: the in-place modification is done for performance
282 # reasons (reconstructing a matrix with huge polynomial
283 # entries is slow), but I don't know how cached_method works,
284 # so it's highly possible that we're modifying some global
285 # list variable by reference, here. In other words, you
286 # probably shouldn't call this method twice on the same
287 # algebra, at the same time, in two threads
288 Ai_orig = A_of_x.column(i)
289 A_of_x.set_column(i,xr)
290 numerator = A_of_x.det()
291 A_of_x.set_column(i,Ai_orig)
292
293 # We're relying on the theory here to ensure that each a_i is
294 # indeed back in R, and the added negative signs are to make
295 # the whole charpoly expression sum to zero.
296 return R(-numerator/detA)
297
298
299 @cached_method
300 def _charpoly_matrix_system(self):
301 """
302 Compute the matrix whose entries A_ij are polynomials in
303 X1,...,XN, the vector ``x`` of variables X1,...,XN, the vector
304 corresponding to `x^r` and the determinent of the matrix A =
305 [A_ij]. In other words, all of the fixed (cachable) data needed
306 to compute the coefficients of the characteristic polynomial.
307 """
308 r = self.rank()
309 n = self.dimension()
310
311 # Turn my vector space into a module so that "vectors" can
312 # have multivatiate polynomial entries.
313 names = tuple('X' + str(i) for i in range(1,n+1))
314 R = PolynomialRing(self.base_ring(), names)
315
316 # Using change_ring() on the parent's vector space doesn't work
317 # here because, in a subalgebra, that vector space has a basis
318 # and change_ring() tries to bring the basis along with it. And
319 # that doesn't work unless the new ring is a PID, which it usually
320 # won't be.
321 V = FreeModule(R,n)
322
323 # Now let x = (X1,X2,...,Xn) be the vector whose entries are
324 # indeterminates...
325 x = V(names)
326
327 # And figure out the "left multiplication by x" matrix in
328 # that setting.
329 lmbx_cols = []
330 monomial_matrices = [ self.monomial(i).operator().matrix()
331 for i in range(n) ] # don't recompute these!
332 for k in range(n):
333 ek = self.monomial(k).to_vector()
334 lmbx_cols.append(
335 sum( x[i]*(monomial_matrices[i]*ek)
336 for i in range(n) ) )
337 Lx = matrix.column(R, lmbx_cols)
338
339 # Now we can compute powers of x "symbolically"
340 x_powers = [self.one().to_vector(), x]
341 for d in range(2, r+1):
342 x_powers.append( Lx*(x_powers[-1]) )
343
344 idmat = matrix.identity(R, n)
345
346 W = self._charpoly_basis_space()
347 W = W.change_ring(R.fraction_field())
348
349 # Starting with the standard coordinates x = (X1,X2,...,Xn)
350 # and then converting the entries to W-coordinates allows us
351 # to pass in the standard coordinates to the charpoly and get
352 # back the right answer. Specifically, with x = (X1,X2,...,Xn),
353 # we have
354 #
355 # W.coordinates(x^2) eval'd at (standard z-coords)
356 # =
357 # W-coords of (z^2)
358 # =
359 # W-coords of (standard coords of x^2 eval'd at std-coords of z)
360 #
361 # We want the middle equivalent thing in our matrix, but use
362 # the first equivalent thing instead so that we can pass in
363 # standard coordinates.
364 x_powers = [ W.coordinate_vector(xp) for xp in x_powers ]
365 l2 = [idmat.column(k-1) for k in range(r+1, n+1)]
366 A_of_x = matrix.column(R, n, (x_powers[:r] + l2))
367 return (A_of_x, x, x_powers[r], A_of_x.det())
368
369
370 @cached_method
371 def characteristic_polynomial(self):
372 """
373 Return a characteristic polynomial that works for all elements
374 of this algebra.
375
376 The resulting polynomial has `n+1` variables, where `n` is the
377 dimension of this algebra. The first `n` variables correspond to
378 the coordinates of an algebra element: when evaluated at the
379 coordinates of an algebra element with respect to a certain
380 basis, the result is a univariate polynomial (in the one
381 remaining variable ``t``), namely the characteristic polynomial
382 of that element.
383
384 SETUP::
385
386 sage: from mjo.eja.eja_algebra import JordanSpinEJA
387
388 EXAMPLES:
389
390 The characteristic polynomial in the spin algebra is given in
391 Alizadeh, Example 11.11::
392
393 sage: J = JordanSpinEJA(3)
394 sage: p = J.characteristic_polynomial(); p
395 X1^2 - X2^2 - X3^2 + (-2*t)*X1 + t^2
396 sage: xvec = J.one().to_vector()
397 sage: p(*xvec)
398 t^2 - 2*t + 1
399
400 """
401 r = self.rank()
402 n = self.dimension()
403
404 # The list of coefficient polynomials a_1, a_2, ..., a_n.
405 a = [ self._charpoly_coeff(i) for i in range(n) ]
406
407 # We go to a bit of trouble here to reorder the
408 # indeterminates, so that it's easier to evaluate the
409 # characteristic polynomial at x's coordinates and get back
410 # something in terms of t, which is what we want.
411 R = a[0].parent()
412 S = PolynomialRing(self.base_ring(),'t')
413 t = S.gen(0)
414 S = PolynomialRing(S, R.variable_names())
415 t = S(t)
416
417 # Note: all entries past the rth should be zero. The
418 # coefficient of the highest power (x^r) is 1, but it doesn't
419 # appear in the solution vector which contains coefficients
420 # for the other powers (to make them sum to x^r).
421 if (r < n):
422 a[r] = 1 # corresponds to x^r
423 else:
424 # When the rank is equal to the dimension, trying to
425 # assign a[r] goes out-of-bounds.
426 a.append(1) # corresponds to x^r
427
428 return sum( a[k]*(t**k) for k in range(len(a)) )
429
430
431 def inner_product(self, x, y):
432 """
433 The inner product associated with this Euclidean Jordan algebra.
434
435 Defaults to the trace inner product, but can be overridden by
436 subclasses if they are sure that the necessary properties are
437 satisfied.
438
439 SETUP::
440
441 sage: from mjo.eja.eja_algebra import random_eja
442
443 EXAMPLES:
444
445 Our inner product satisfies the Jordan axiom, which is also
446 referred to as "associativity" for a symmetric bilinear form::
447
448 sage: set_random_seed()
449 sage: J = random_eja()
450 sage: x,y,z = J.random_elements(3)
451 sage: (x*y).inner_product(z) == y.inner_product(x*z)
452 True
453
454 """
455 X = x.natural_representation()
456 Y = y.natural_representation()
457 return self.natural_inner_product(X,Y)
458
459
460 def is_trivial(self):
461 """
462 Return whether or not this algebra is trivial.
463
464 A trivial algebra contains only the zero element.
465
466 SETUP::
467
468 sage: from mjo.eja.eja_algebra import ComplexHermitianEJA
469
470 EXAMPLES::
471
472 sage: J = ComplexHermitianEJA(3)
473 sage: J.is_trivial()
474 False
475 sage: A = J.zero().subalgebra_generated_by()
476 sage: A.is_trivial()
477 True
478
479 """
480 return self.dimension() == 0
481
482
483 def multiplication_table(self):
484 """
485 Return a visual representation of this algebra's multiplication
486 table (on basis elements).
487
488 SETUP::
489
490 sage: from mjo.eja.eja_algebra import JordanSpinEJA
491
492 EXAMPLES::
493
494 sage: J = JordanSpinEJA(4)
495 sage: J.multiplication_table()
496 +----++----+----+----+----+
497 | * || e0 | e1 | e2 | e3 |
498 +====++====+====+====+====+
499 | e0 || e0 | e1 | e2 | e3 |
500 +----++----+----+----+----+
501 | e1 || e1 | e0 | 0 | 0 |
502 +----++----+----+----+----+
503 | e2 || e2 | 0 | e0 | 0 |
504 +----++----+----+----+----+
505 | e3 || e3 | 0 | 0 | e0 |
506 +----++----+----+----+----+
507
508 """
509 M = list(self._multiplication_table) # copy
510 for i in range(len(M)):
511 # M had better be "square"
512 M[i] = [self.monomial(i)] + M[i]
513 M = [["*"] + list(self.gens())] + M
514 return table(M, header_row=True, header_column=True, frame=True)
515
516
517 def natural_basis(self):
518 """
519 Return a more-natural representation of this algebra's basis.
520
521 Every finite-dimensional Euclidean Jordan Algebra is a direct
522 sum of five simple algebras, four of which comprise Hermitian
523 matrices. This method returns the original "natural" basis
524 for our underlying vector space. (Typically, the natural basis
525 is used to construct the multiplication table in the first place.)
526
527 Note that this will always return a matrix. The standard basis
528 in `R^n` will be returned as `n`-by-`1` column matrices.
529
530 SETUP::
531
532 sage: from mjo.eja.eja_algebra import (JordanSpinEJA,
533 ....: RealSymmetricEJA)
534
535 EXAMPLES::
536
537 sage: J = RealSymmetricEJA(2)
538 sage: J.basis()
539 Finite family {0: e0, 1: e1, 2: e2}
540 sage: J.natural_basis()
541 (
542 [1 0] [ 0 1/2*sqrt2] [0 0]
543 [0 0], [1/2*sqrt2 0], [0 1]
544 )
545
546 ::
547
548 sage: J = JordanSpinEJA(2)
549 sage: J.basis()
550 Finite family {0: e0, 1: e1}
551 sage: J.natural_basis()
552 (
553 [1] [0]
554 [0], [1]
555 )
556
557 """
558 if self._natural_basis is None:
559 M = self.natural_basis_space()
560 return tuple( M(b.to_vector()) for b in self.basis() )
561 else:
562 return self._natural_basis
563
564
565 def natural_basis_space(self):
566 """
567 Return the matrix space in which this algebra's natural basis
568 elements live.
569 """
570 if self._natural_basis is None or len(self._natural_basis) == 0:
571 return MatrixSpace(self.base_ring(), self.dimension(), 1)
572 else:
573 return self._natural_basis[0].matrix_space()
574
575
576 @staticmethod
577 def natural_inner_product(X,Y):
578 """
579 Compute the inner product of two naturally-represented elements.
580
581 For example in the real symmetric matrix EJA, this will compute
582 the trace inner-product of two n-by-n symmetric matrices. The
583 default should work for the real cartesian product EJA, the
584 Jordan spin EJA, and the real symmetric matrices. The others
585 will have to be overridden.
586 """
587 return (X.conjugate_transpose()*Y).trace()
588
589
590 @cached_method
591 def one(self):
592 """
593 Return the unit element of this algebra.
594
595 SETUP::
596
597 sage: from mjo.eja.eja_algebra import (RealCartesianProductEJA,
598 ....: random_eja)
599
600 EXAMPLES::
601
602 sage: J = RealCartesianProductEJA(5)
603 sage: J.one()
604 e0 + e1 + e2 + e3 + e4
605
606 TESTS:
607
608 The identity element acts like the identity::
609
610 sage: set_random_seed()
611 sage: J = random_eja()
612 sage: x = J.random_element()
613 sage: J.one()*x == x and x*J.one() == x
614 True
615
616 The matrix of the unit element's operator is the identity::
617
618 sage: set_random_seed()
619 sage: J = random_eja()
620 sage: actual = J.one().operator().matrix()
621 sage: expected = matrix.identity(J.base_ring(), J.dimension())
622 sage: actual == expected
623 True
624
625 """
626 # We can brute-force compute the matrices of the operators
627 # that correspond to the basis elements of this algebra.
628 # If some linear combination of those basis elements is the
629 # algebra identity, then the same linear combination of
630 # their matrices has to be the identity matrix.
631 #
632 # Of course, matrices aren't vectors in sage, so we have to
633 # appeal to the "long vectors" isometry.
634 oper_vecs = [ _mat2vec(g.operator().matrix()) for g in self.gens() ]
635
636 # Now we use basis linear algebra to find the coefficients,
637 # of the matrices-as-vectors-linear-combination, which should
638 # work for the original algebra basis too.
639 A = matrix.column(self.base_ring(), oper_vecs)
640
641 # We used the isometry on the left-hand side already, but we
642 # still need to do it for the right-hand side. Recall that we
643 # wanted something that summed to the identity matrix.
644 b = _mat2vec( matrix.identity(self.base_ring(), self.dimension()) )
645
646 # Now if there's an identity element in the algebra, this should work.
647 coeffs = A.solve_right(b)
648 return self.linear_combination(zip(self.gens(), coeffs))
649
650
651 def random_element(self):
652 # Temporary workaround for https://trac.sagemath.org/ticket/28327
653 if self.is_trivial():
654 return self.zero()
655 else:
656 s = super(FiniteDimensionalEuclideanJordanAlgebra, self)
657 return s.random_element()
658
659 def random_elements(self, count):
660 """
661 Return ``count`` random elements as a tuple.
662
663 SETUP::
664
665 sage: from mjo.eja.eja_algebra import JordanSpinEJA
666
667 EXAMPLES::
668
669 sage: J = JordanSpinEJA(3)
670 sage: x,y,z = J.random_elements(3)
671 sage: all( [ x in J, y in J, z in J ])
672 True
673 sage: len( J.random_elements(10) ) == 10
674 True
675
676 """
677 return tuple( self.random_element() for idx in xrange(count) )
678
679 @classmethod
680 def random_instance(cls, field=QQ, **kwargs):
681 """
682 Return a random instance of this type of algebra.
683
684 In subclasses for algebras that we know how to construct, this
685 is a shortcut for constructing test cases and examples.
686 """
687 if cls is FiniteDimensionalEuclideanJordanAlgebra:
688 # Red flag! But in theory we could do this I guess. The
689 # only finite-dimensional exceptional EJA is the
690 # octononions. So, we could just create an EJA from an
691 # associative matrix algebra (generated by a subset of
692 # elements) with the symmetric product. Or, we could punt
693 # to random_eja() here, override it in our subclasses, and
694 # not worry about it.
695 raise NotImplementedError
696
697 n = ZZ.random_element(1, cls._max_test_case_size())
698 return cls(n, field, **kwargs)
699
700
701 def rank(self):
702 """
703 Return the rank of this EJA.
704
705 ALGORITHM:
706
707 The author knows of no algorithm to compute the rank of an EJA
708 where only the multiplication table is known. In lieu of one, we
709 require the rank to be specified when the algebra is created,
710 and simply pass along that number here.
711
712 SETUP::
713
714 sage: from mjo.eja.eja_algebra import (JordanSpinEJA,
715 ....: RealSymmetricEJA,
716 ....: ComplexHermitianEJA,
717 ....: QuaternionHermitianEJA,
718 ....: random_eja)
719
720 EXAMPLES:
721
722 The rank of the Jordan spin algebra is always two::
723
724 sage: JordanSpinEJA(2).rank()
725 2
726 sage: JordanSpinEJA(3).rank()
727 2
728 sage: JordanSpinEJA(4).rank()
729 2
730
731 The rank of the `n`-by-`n` Hermitian real, complex, or
732 quaternion matrices is `n`::
733
734 sage: RealSymmetricEJA(4).rank()
735 4
736 sage: ComplexHermitianEJA(3).rank()
737 3
738 sage: QuaternionHermitianEJA(2).rank()
739 2
740
741 TESTS:
742
743 Ensure that every EJA that we know how to construct has a
744 positive integer rank::
745
746 sage: set_random_seed()
747 sage: r = random_eja().rank()
748 sage: r in ZZ and r > 0
749 True
750
751 """
752 return self._rank
753
754
755 def vector_space(self):
756 """
757 Return the vector space that underlies this algebra.
758
759 SETUP::
760
761 sage: from mjo.eja.eja_algebra import RealSymmetricEJA
762
763 EXAMPLES::
764
765 sage: J = RealSymmetricEJA(2)
766 sage: J.vector_space()
767 Vector space of dimension 3 over...
768
769 """
770 return self.zero().to_vector().parent().ambient_vector_space()
771
772
773 Element = FiniteDimensionalEuclideanJordanAlgebraElement
774
775
776 class RealCartesianProductEJA(FiniteDimensionalEuclideanJordanAlgebra):
777 """
778 Return the Euclidean Jordan Algebra corresponding to the set
779 `R^n` under the Hadamard product.
780
781 Note: this is nothing more than the Cartesian product of ``n``
782 copies of the spin algebra. Once Cartesian product algebras
783 are implemented, this can go.
784
785 SETUP::
786
787 sage: from mjo.eja.eja_algebra import RealCartesianProductEJA
788
789 EXAMPLES:
790
791 This multiplication table can be verified by hand::
792
793 sage: J = RealCartesianProductEJA(3)
794 sage: e0,e1,e2 = J.gens()
795 sage: e0*e0
796 e0
797 sage: e0*e1
798 0
799 sage: e0*e2
800 0
801 sage: e1*e1
802 e1
803 sage: e1*e2
804 0
805 sage: e2*e2
806 e2
807
808 TESTS:
809
810 We can change the generator prefix::
811
812 sage: RealCartesianProductEJA(3, prefix='r').gens()
813 (r0, r1, r2)
814
815 """
816 def __init__(self, n, field=QQ, **kwargs):
817 V = VectorSpace(field, n)
818 mult_table = [ [ V.gen(i)*(i == j) for j in range(n) ]
819 for i in range(n) ]
820
821 fdeja = super(RealCartesianProductEJA, self)
822 return fdeja.__init__(field, mult_table, rank=n, **kwargs)
823
824 def inner_product(self, x, y):
825 """
826 Faster to reimplement than to use natural representations.
827
828 SETUP::
829
830 sage: from mjo.eja.eja_algebra import RealCartesianProductEJA
831
832 TESTS:
833
834 Ensure that this is the usual inner product for the algebras
835 over `R^n`::
836
837 sage: set_random_seed()
838 sage: J = RealCartesianProductEJA.random_instance()
839 sage: x,y = J.random_elements(2)
840 sage: X = x.natural_representation()
841 sage: Y = y.natural_representation()
842 sage: x.inner_product(y) == J.natural_inner_product(X,Y)
843 True
844
845 """
846 return x.to_vector().inner_product(y.to_vector())
847
848
849 def random_eja():
850 """
851 Return a "random" finite-dimensional Euclidean Jordan Algebra.
852
853 ALGORITHM:
854
855 For now, we choose a random natural number ``n`` (greater than zero)
856 and then give you back one of the following:
857
858 * The cartesian product of the rational numbers ``n`` times; this is
859 ``QQ^n`` with the Hadamard product.
860
861 * The Jordan spin algebra on ``QQ^n``.
862
863 * The ``n``-by-``n`` rational symmetric matrices with the symmetric
864 product.
865
866 * The ``n``-by-``n`` complex-rational Hermitian matrices embedded
867 in the space of ``2n``-by-``2n`` real symmetric matrices.
868
869 * The ``n``-by-``n`` quaternion-rational Hermitian matrices embedded
870 in the space of ``4n``-by-``4n`` real symmetric matrices.
871
872 Later this might be extended to return Cartesian products of the
873 EJAs above.
874
875 SETUP::
876
877 sage: from mjo.eja.eja_algebra import random_eja
878
879 TESTS::
880
881 sage: random_eja()
882 Euclidean Jordan algebra of dimension...
883
884 """
885 classname = choice([RealCartesianProductEJA,
886 JordanSpinEJA,
887 RealSymmetricEJA,
888 ComplexHermitianEJA,
889 QuaternionHermitianEJA])
890 return classname.random_instance()
891
892
893
894
895
896
897 class MatrixEuclideanJordanAlgebra(FiniteDimensionalEuclideanJordanAlgebra):
898 @staticmethod
899 def _max_test_case_size():
900 # Play it safe, since this will be squared and the underlying
901 # field can have dimension 4 (quaternions) too.
902 return 3
903
904 @classmethod
905 def _denormalized_basis(cls, n, field):
906 raise NotImplementedError
907
908 def __init__(self, n, field=QQ, normalize_basis=True, **kwargs):
909 S = self._denormalized_basis(n, field)
910
911 if n > 1 and normalize_basis:
912 # We'll need sqrt(2) to normalize the basis, and this
913 # winds up in the multiplication table, so the whole
914 # algebra needs to be over the field extension.
915 R = PolynomialRing(field, 'z')
916 z = R.gen()
917 p = z**2 - 2
918 if p.is_irreducible():
919 field = NumberField(p, 'sqrt2', embedding=RLF(2).sqrt())
920 S = [ s.change_ring(field) for s in S ]
921 self._basis_normalizers = tuple(
922 ~(self.natural_inner_product(s,s).sqrt()) for s in S )
923 S = tuple( s*c for (s,c) in zip(S,self._basis_normalizers) )
924
925 Qs = self.multiplication_table_from_matrix_basis(S)
926
927 fdeja = super(MatrixEuclideanJordanAlgebra, self)
928 return fdeja.__init__(field,
929 Qs,
930 rank=n,
931 natural_basis=S,
932 **kwargs)
933
934
935 @staticmethod
936 def multiplication_table_from_matrix_basis(basis):
937 """
938 At least three of the five simple Euclidean Jordan algebras have the
939 symmetric multiplication (A,B) |-> (AB + BA)/2, where the
940 multiplication on the right is matrix multiplication. Given a basis
941 for the underlying matrix space, this function returns a
942 multiplication table (obtained by looping through the basis
943 elements) for an algebra of those matrices.
944 """
945 # In S^2, for example, we nominally have four coordinates even
946 # though the space is of dimension three only. The vector space V
947 # is supposed to hold the entire long vector, and the subspace W
948 # of V will be spanned by the vectors that arise from symmetric
949 # matrices. Thus for S^2, dim(V) == 4 and dim(W) == 3.
950 field = basis[0].base_ring()
951 dimension = basis[0].nrows()
952
953 V = VectorSpace(field, dimension**2)
954 W = V.span_of_basis( _mat2vec(s) for s in basis )
955 n = len(basis)
956 mult_table = [[W.zero() for j in range(n)] for i in range(n)]
957 for i in range(n):
958 for j in range(n):
959 mat_entry = (basis[i]*basis[j] + basis[j]*basis[i])/2
960 mult_table[i][j] = W.coordinate_vector(_mat2vec(mat_entry))
961
962 return mult_table
963
964
965 @staticmethod
966 def real_embed(M):
967 """
968 Embed the matrix ``M`` into a space of real matrices.
969
970 The matrix ``M`` can have entries in any field at the moment:
971 the real numbers, complex numbers, or quaternions. And although
972 they are not a field, we can probably support octonions at some
973 point, too. This function returns a real matrix that "acts like"
974 the original with respect to matrix multiplication; i.e.
975
976 real_embed(M*N) = real_embed(M)*real_embed(N)
977
978 """
979 raise NotImplementedError
980
981
982 @staticmethod
983 def real_unembed(M):
984 """
985 The inverse of :meth:`real_embed`.
986 """
987 raise NotImplementedError
988
989
990 @classmethod
991 def natural_inner_product(cls,X,Y):
992 Xu = cls.real_unembed(X)
993 Yu = cls.real_unembed(Y)
994 tr = (Xu*Yu).trace()
995 if tr in RLF:
996 # It's real already.
997 return tr
998
999 # Otherwise, try the thing that works for complex numbers; and
1000 # if that doesn't work, the thing that works for quaternions.
1001 try:
1002 return tr.vector()[0] # real part, imag part is index 1
1003 except AttributeError:
1004 # A quaternions doesn't have a vector() method, but does
1005 # have coefficient_tuple() method that returns the
1006 # coefficients of 1, i, j, and k -- in that order.
1007 return tr.coefficient_tuple()[0]
1008
1009
1010 class RealMatrixEuclideanJordanAlgebra(MatrixEuclideanJordanAlgebra):
1011 @staticmethod
1012 def real_embed(M):
1013 """
1014 Embed the matrix ``M`` into a space of real matrices.
1015
1016 The matrix ``M`` can have entries in any field at the moment:
1017 the real numbers, complex numbers, or quaternions. And although
1018 they are not a field, we can probably support octonions at some
1019 point, too. This function returns a real matrix that "acts like"
1020 the original with respect to matrix multiplication; i.e.
1021
1022 real_embed(M*N) = real_embed(M)*real_embed(N)
1023
1024 """
1025 return M
1026
1027
1028 @staticmethod
1029 def real_unembed(M):
1030 """
1031 The inverse of :meth:`real_embed`.
1032 """
1033 return M
1034
1035
1036 class RealSymmetricEJA(RealMatrixEuclideanJordanAlgebra):
1037 """
1038 The rank-n simple EJA consisting of real symmetric n-by-n
1039 matrices, the usual symmetric Jordan product, and the trace inner
1040 product. It has dimension `(n^2 + n)/2` over the reals.
1041
1042 SETUP::
1043
1044 sage: from mjo.eja.eja_algebra import RealSymmetricEJA
1045
1046 EXAMPLES::
1047
1048 sage: J = RealSymmetricEJA(2)
1049 sage: e0, e1, e2 = J.gens()
1050 sage: e0*e0
1051 e0
1052 sage: e1*e1
1053 1/2*e0 + 1/2*e2
1054 sage: e2*e2
1055 e2
1056
1057 TESTS:
1058
1059 The dimension of this algebra is `(n^2 + n) / 2`::
1060
1061 sage: set_random_seed()
1062 sage: n_max = RealSymmetricEJA._max_test_case_size()
1063 sage: n = ZZ.random_element(1, n_max)
1064 sage: J = RealSymmetricEJA(n)
1065 sage: J.dimension() == (n^2 + n)/2
1066 True
1067
1068 The Jordan multiplication is what we think it is::
1069
1070 sage: set_random_seed()
1071 sage: J = RealSymmetricEJA.random_instance()
1072 sage: x,y = J.random_elements(2)
1073 sage: actual = (x*y).natural_representation()
1074 sage: X = x.natural_representation()
1075 sage: Y = y.natural_representation()
1076 sage: expected = (X*Y + Y*X)/2
1077 sage: actual == expected
1078 True
1079 sage: J(expected) == x*y
1080 True
1081
1082 We can change the generator prefix::
1083
1084 sage: RealSymmetricEJA(3, prefix='q').gens()
1085 (q0, q1, q2, q3, q4, q5)
1086
1087 Our natural basis is normalized with respect to the natural inner
1088 product unless we specify otherwise::
1089
1090 sage: set_random_seed()
1091 sage: J = RealSymmetricEJA.random_instance()
1092 sage: all( b.norm() == 1 for b in J.gens() )
1093 True
1094
1095 Since our natural basis is normalized with respect to the natural
1096 inner product, and since we know that this algebra is an EJA, any
1097 left-multiplication operator's matrix will be symmetric because
1098 natural->EJA basis representation is an isometry and within the EJA
1099 the operator is self-adjoint by the Jordan axiom::
1100
1101 sage: set_random_seed()
1102 sage: x = RealSymmetricEJA.random_instance().random_element()
1103 sage: x.operator().matrix().is_symmetric()
1104 True
1105
1106 """
1107 @classmethod
1108 def _denormalized_basis(cls, n, field):
1109 """
1110 Return a basis for the space of real symmetric n-by-n matrices.
1111
1112 SETUP::
1113
1114 sage: from mjo.eja.eja_algebra import RealSymmetricEJA
1115
1116 TESTS::
1117
1118 sage: set_random_seed()
1119 sage: n = ZZ.random_element(1,5)
1120 sage: B = RealSymmetricEJA._denormalized_basis(n,QQ)
1121 sage: all( M.is_symmetric() for M in B)
1122 True
1123
1124 """
1125 # The basis of symmetric matrices, as matrices, in their R^(n-by-n)
1126 # coordinates.
1127 S = []
1128 for i in xrange(n):
1129 for j in xrange(i+1):
1130 Eij = matrix(field, n, lambda k,l: k==i and l==j)
1131 if i == j:
1132 Sij = Eij
1133 else:
1134 Sij = Eij + Eij.transpose()
1135 S.append(Sij)
1136 return tuple(S)
1137
1138
1139 @staticmethod
1140 def _max_test_case_size():
1141 return 5 # Dimension 10
1142
1143
1144
1145 class ComplexMatrixEuclideanJordanAlgebra(MatrixEuclideanJordanAlgebra):
1146 @staticmethod
1147 def real_embed(M):
1148 """
1149 Embed the n-by-n complex matrix ``M`` into the space of real
1150 matrices of size 2n-by-2n via the map the sends each entry `z = a +
1151 bi` to the block matrix ``[[a,b],[-b,a]]``.
1152
1153 SETUP::
1154
1155 sage: from mjo.eja.eja_algebra import \
1156 ....: ComplexMatrixEuclideanJordanAlgebra
1157
1158 EXAMPLES::
1159
1160 sage: F = QuadraticField(-1, 'i')
1161 sage: x1 = F(4 - 2*i)
1162 sage: x2 = F(1 + 2*i)
1163 sage: x3 = F(-i)
1164 sage: x4 = F(6)
1165 sage: M = matrix(F,2,[[x1,x2],[x3,x4]])
1166 sage: ComplexMatrixEuclideanJordanAlgebra.real_embed(M)
1167 [ 4 -2| 1 2]
1168 [ 2 4|-2 1]
1169 [-----+-----]
1170 [ 0 -1| 6 0]
1171 [ 1 0| 0 6]
1172
1173 TESTS:
1174
1175 Embedding is a homomorphism (isomorphism, in fact)::
1176
1177 sage: set_random_seed()
1178 sage: n_max = ComplexMatrixEuclideanJordanAlgebra._max_test_case_size()
1179 sage: n = ZZ.random_element(n_max)
1180 sage: F = QuadraticField(-1, 'i')
1181 sage: X = random_matrix(F, n)
1182 sage: Y = random_matrix(F, n)
1183 sage: Xe = ComplexMatrixEuclideanJordanAlgebra.real_embed(X)
1184 sage: Ye = ComplexMatrixEuclideanJordanAlgebra.real_embed(Y)
1185 sage: XYe = ComplexMatrixEuclideanJordanAlgebra.real_embed(X*Y)
1186 sage: Xe*Ye == XYe
1187 True
1188
1189 """
1190 n = M.nrows()
1191 if M.ncols() != n:
1192 raise ValueError("the matrix 'M' must be square")
1193 field = M.base_ring()
1194 blocks = []
1195 for z in M.list():
1196 a = z.vector()[0] # real part, I guess
1197 b = z.vector()[1] # imag part, I guess
1198 blocks.append(matrix(field, 2, [[a,b],[-b,a]]))
1199
1200 # We can drop the imaginaries here.
1201 return matrix.block(field.base_ring(), n, blocks)
1202
1203
1204 @staticmethod
1205 def real_unembed(M):
1206 """
1207 The inverse of _embed_complex_matrix().
1208
1209 SETUP::
1210
1211 sage: from mjo.eja.eja_algebra import \
1212 ....: ComplexMatrixEuclideanJordanAlgebra
1213
1214 EXAMPLES::
1215
1216 sage: A = matrix(QQ,[ [ 1, 2, 3, 4],
1217 ....: [-2, 1, -4, 3],
1218 ....: [ 9, 10, 11, 12],
1219 ....: [-10, 9, -12, 11] ])
1220 sage: ComplexMatrixEuclideanJordanAlgebra.real_unembed(A)
1221 [ 2*i + 1 4*i + 3]
1222 [ 10*i + 9 12*i + 11]
1223
1224 TESTS:
1225
1226 Unembedding is the inverse of embedding::
1227
1228 sage: set_random_seed()
1229 sage: F = QuadraticField(-1, 'i')
1230 sage: M = random_matrix(F, 3)
1231 sage: Me = ComplexMatrixEuclideanJordanAlgebra.real_embed(M)
1232 sage: ComplexMatrixEuclideanJordanAlgebra.real_unembed(Me) == M
1233 True
1234
1235 """
1236 n = ZZ(M.nrows())
1237 if M.ncols() != n:
1238 raise ValueError("the matrix 'M' must be square")
1239 if not n.mod(2).is_zero():
1240 raise ValueError("the matrix 'M' must be a complex embedding")
1241
1242 field = M.base_ring() # This should already have sqrt2
1243 R = PolynomialRing(field, 'z')
1244 z = R.gen()
1245 F = NumberField(z**2 + 1,'i', embedding=CLF(-1).sqrt())
1246 i = F.gen()
1247
1248 # Go top-left to bottom-right (reading order), converting every
1249 # 2-by-2 block we see to a single complex element.
1250 elements = []
1251 for k in xrange(n/2):
1252 for j in xrange(n/2):
1253 submat = M[2*k:2*k+2,2*j:2*j+2]
1254 if submat[0,0] != submat[1,1]:
1255 raise ValueError('bad on-diagonal submatrix')
1256 if submat[0,1] != -submat[1,0]:
1257 raise ValueError('bad off-diagonal submatrix')
1258 z = submat[0,0] + submat[0,1]*i
1259 elements.append(z)
1260
1261 return matrix(F, n/2, elements)
1262
1263
1264 class ComplexHermitianEJA(ComplexMatrixEuclideanJordanAlgebra):
1265 """
1266 The rank-n simple EJA consisting of complex Hermitian n-by-n
1267 matrices over the real numbers, the usual symmetric Jordan product,
1268 and the real-part-of-trace inner product. It has dimension `n^2` over
1269 the reals.
1270
1271 SETUP::
1272
1273 sage: from mjo.eja.eja_algebra import ComplexHermitianEJA
1274
1275 TESTS:
1276
1277 The dimension of this algebra is `n^2`::
1278
1279 sage: set_random_seed()
1280 sage: n_max = ComplexHermitianEJA._max_test_case_size()
1281 sage: n = ZZ.random_element(1, n_max)
1282 sage: J = ComplexHermitianEJA(n)
1283 sage: J.dimension() == n^2
1284 True
1285
1286 The Jordan multiplication is what we think it is::
1287
1288 sage: set_random_seed()
1289 sage: J = ComplexHermitianEJA.random_instance()
1290 sage: x,y = J.random_elements(2)
1291 sage: actual = (x*y).natural_representation()
1292 sage: X = x.natural_representation()
1293 sage: Y = y.natural_representation()
1294 sage: expected = (X*Y + Y*X)/2
1295 sage: actual == expected
1296 True
1297 sage: J(expected) == x*y
1298 True
1299
1300 We can change the generator prefix::
1301
1302 sage: ComplexHermitianEJA(2, prefix='z').gens()
1303 (z0, z1, z2, z3)
1304
1305 Our natural basis is normalized with respect to the natural inner
1306 product unless we specify otherwise::
1307
1308 sage: set_random_seed()
1309 sage: J = ComplexHermitianEJA.random_instance()
1310 sage: all( b.norm() == 1 for b in J.gens() )
1311 True
1312
1313 Since our natural basis is normalized with respect to the natural
1314 inner product, and since we know that this algebra is an EJA, any
1315 left-multiplication operator's matrix will be symmetric because
1316 natural->EJA basis representation is an isometry and within the EJA
1317 the operator is self-adjoint by the Jordan axiom::
1318
1319 sage: set_random_seed()
1320 sage: x = ComplexHermitianEJA.random_instance().random_element()
1321 sage: x.operator().matrix().is_symmetric()
1322 True
1323
1324 """
1325 @classmethod
1326 def _denormalized_basis(cls, n, field):
1327 """
1328 Returns a basis for the space of complex Hermitian n-by-n matrices.
1329
1330 Why do we embed these? Basically, because all of numerical linear
1331 algebra assumes that you're working with vectors consisting of `n`
1332 entries from a field and scalars from the same field. There's no way
1333 to tell SageMath that (for example) the vectors contain complex
1334 numbers, while the scalar field is real.
1335
1336 SETUP::
1337
1338 sage: from mjo.eja.eja_algebra import ComplexHermitianEJA
1339
1340 TESTS::
1341
1342 sage: set_random_seed()
1343 sage: n = ZZ.random_element(1,5)
1344 sage: field = QuadraticField(2, 'sqrt2')
1345 sage: B = ComplexHermitianEJA._denormalized_basis(n, field)
1346 sage: all( M.is_symmetric() for M in B)
1347 True
1348
1349 """
1350 R = PolynomialRing(field, 'z')
1351 z = R.gen()
1352 F = NumberField(z**2 + 1, 'I', embedding=CLF(-1).sqrt())
1353 I = F.gen()
1354
1355 # This is like the symmetric case, but we need to be careful:
1356 #
1357 # * We want conjugate-symmetry, not just symmetry.
1358 # * The diagonal will (as a result) be real.
1359 #
1360 S = []
1361 for i in xrange(n):
1362 for j in xrange(i+1):
1363 Eij = matrix(F, n, lambda k,l: k==i and l==j)
1364 if i == j:
1365 Sij = cls.real_embed(Eij)
1366 S.append(Sij)
1367 else:
1368 # The second one has a minus because it's conjugated.
1369 Sij_real = cls.real_embed(Eij + Eij.transpose())
1370 S.append(Sij_real)
1371 Sij_imag = cls.real_embed(I*Eij - I*Eij.transpose())
1372 S.append(Sij_imag)
1373
1374 # Since we embedded these, we can drop back to the "field" that we
1375 # started with instead of the complex extension "F".
1376 return tuple( s.change_ring(field) for s in S )
1377
1378
1379
1380 class QuaternionMatrixEuclideanJordanAlgebra(MatrixEuclideanJordanAlgebra):
1381 @staticmethod
1382 def real_embed(M):
1383 """
1384 Embed the n-by-n quaternion matrix ``M`` into the space of real
1385 matrices of size 4n-by-4n by first sending each quaternion entry `z
1386 = a + bi + cj + dk` to the block-complex matrix ``[[a + bi,
1387 c+di],[-c + di, a-bi]]`, and then embedding those into a real
1388 matrix.
1389
1390 SETUP::
1391
1392 sage: from mjo.eja.eja_algebra import \
1393 ....: QuaternionMatrixEuclideanJordanAlgebra
1394
1395 EXAMPLES::
1396
1397 sage: Q = QuaternionAlgebra(QQ,-1,-1)
1398 sage: i,j,k = Q.gens()
1399 sage: x = 1 + 2*i + 3*j + 4*k
1400 sage: M = matrix(Q, 1, [[x]])
1401 sage: QuaternionMatrixEuclideanJordanAlgebra.real_embed(M)
1402 [ 1 2 3 4]
1403 [-2 1 -4 3]
1404 [-3 4 1 -2]
1405 [-4 -3 2 1]
1406
1407 Embedding is a homomorphism (isomorphism, in fact)::
1408
1409 sage: set_random_seed()
1410 sage: n_max = QuaternionMatrixEuclideanJordanAlgebra._max_test_case_size()
1411 sage: n = ZZ.random_element(n_max)
1412 sage: Q = QuaternionAlgebra(QQ,-1,-1)
1413 sage: X = random_matrix(Q, n)
1414 sage: Y = random_matrix(Q, n)
1415 sage: Xe = QuaternionMatrixEuclideanJordanAlgebra.real_embed(X)
1416 sage: Ye = QuaternionMatrixEuclideanJordanAlgebra.real_embed(Y)
1417 sage: XYe = QuaternionMatrixEuclideanJordanAlgebra.real_embed(X*Y)
1418 sage: Xe*Ye == XYe
1419 True
1420
1421 """
1422 quaternions = M.base_ring()
1423 n = M.nrows()
1424 if M.ncols() != n:
1425 raise ValueError("the matrix 'M' must be square")
1426
1427 F = QuadraticField(-1, 'i')
1428 i = F.gen()
1429
1430 blocks = []
1431 for z in M.list():
1432 t = z.coefficient_tuple()
1433 a = t[0]
1434 b = t[1]
1435 c = t[2]
1436 d = t[3]
1437 cplxM = matrix(F, 2, [[ a + b*i, c + d*i],
1438 [-c + d*i, a - b*i]])
1439 realM = ComplexMatrixEuclideanJordanAlgebra.real_embed(cplxM)
1440 blocks.append(realM)
1441
1442 # We should have real entries by now, so use the realest field
1443 # we've got for the return value.
1444 return matrix.block(quaternions.base_ring(), n, blocks)
1445
1446
1447
1448 @staticmethod
1449 def real_unembed(M):
1450 """
1451 The inverse of _embed_quaternion_matrix().
1452
1453 SETUP::
1454
1455 sage: from mjo.eja.eja_algebra import \
1456 ....: QuaternionMatrixEuclideanJordanAlgebra
1457
1458 EXAMPLES::
1459
1460 sage: M = matrix(QQ, [[ 1, 2, 3, 4],
1461 ....: [-2, 1, -4, 3],
1462 ....: [-3, 4, 1, -2],
1463 ....: [-4, -3, 2, 1]])
1464 sage: QuaternionMatrixEuclideanJordanAlgebra.real_unembed(M)
1465 [1 + 2*i + 3*j + 4*k]
1466
1467 TESTS:
1468
1469 Unembedding is the inverse of embedding::
1470
1471 sage: set_random_seed()
1472 sage: Q = QuaternionAlgebra(QQ, -1, -1)
1473 sage: M = random_matrix(Q, 3)
1474 sage: Me = QuaternionMatrixEuclideanJordanAlgebra.real_embed(M)
1475 sage: QuaternionMatrixEuclideanJordanAlgebra.real_unembed(Me) == M
1476 True
1477
1478 """
1479 n = ZZ(M.nrows())
1480 if M.ncols() != n:
1481 raise ValueError("the matrix 'M' must be square")
1482 if not n.mod(4).is_zero():
1483 raise ValueError("the matrix 'M' must be a complex embedding")
1484
1485 # Use the base ring of the matrix to ensure that its entries can be
1486 # multiplied by elements of the quaternion algebra.
1487 field = M.base_ring()
1488 Q = QuaternionAlgebra(field,-1,-1)
1489 i,j,k = Q.gens()
1490
1491 # Go top-left to bottom-right (reading order), converting every
1492 # 4-by-4 block we see to a 2-by-2 complex block, to a 1-by-1
1493 # quaternion block.
1494 elements = []
1495 for l in xrange(n/4):
1496 for m in xrange(n/4):
1497 submat = ComplexMatrixEuclideanJordanAlgebra.real_unembed(
1498 M[4*l:4*l+4,4*m:4*m+4] )
1499 if submat[0,0] != submat[1,1].conjugate():
1500 raise ValueError('bad on-diagonal submatrix')
1501 if submat[0,1] != -submat[1,0].conjugate():
1502 raise ValueError('bad off-diagonal submatrix')
1503 z = submat[0,0].vector()[0] # real part
1504 z += submat[0,0].vector()[1]*i # imag part
1505 z += submat[0,1].vector()[0]*j # real part
1506 z += submat[0,1].vector()[1]*k # imag part
1507 elements.append(z)
1508
1509 return matrix(Q, n/4, elements)
1510
1511
1512
1513 class QuaternionHermitianEJA(QuaternionMatrixEuclideanJordanAlgebra):
1514 """
1515 The rank-n simple EJA consisting of self-adjoint n-by-n quaternion
1516 matrices, the usual symmetric Jordan product, and the
1517 real-part-of-trace inner product. It has dimension `2n^2 - n` over
1518 the reals.
1519
1520 SETUP::
1521
1522 sage: from mjo.eja.eja_algebra import QuaternionHermitianEJA
1523
1524 TESTS:
1525
1526 The dimension of this algebra is `2*n^2 - n`::
1527
1528 sage: set_random_seed()
1529 sage: n_max = QuaternionHermitianEJA._max_test_case_size()
1530 sage: n = ZZ.random_element(1, n_max)
1531 sage: J = QuaternionHermitianEJA(n)
1532 sage: J.dimension() == 2*(n^2) - n
1533 True
1534
1535 The Jordan multiplication is what we think it is::
1536
1537 sage: set_random_seed()
1538 sage: J = QuaternionHermitianEJA.random_instance()
1539 sage: x,y = J.random_elements(2)
1540 sage: actual = (x*y).natural_representation()
1541 sage: X = x.natural_representation()
1542 sage: Y = y.natural_representation()
1543 sage: expected = (X*Y + Y*X)/2
1544 sage: actual == expected
1545 True
1546 sage: J(expected) == x*y
1547 True
1548
1549 We can change the generator prefix::
1550
1551 sage: QuaternionHermitianEJA(2, prefix='a').gens()
1552 (a0, a1, a2, a3, a4, a5)
1553
1554 Our natural basis is normalized with respect to the natural inner
1555 product unless we specify otherwise::
1556
1557 sage: set_random_seed()
1558 sage: J = QuaternionHermitianEJA.random_instance()
1559 sage: all( b.norm() == 1 for b in J.gens() )
1560 True
1561
1562 Since our natural basis is normalized with respect to the natural
1563 inner product, and since we know that this algebra is an EJA, any
1564 left-multiplication operator's matrix will be symmetric because
1565 natural->EJA basis representation is an isometry and within the EJA
1566 the operator is self-adjoint by the Jordan axiom::
1567
1568 sage: set_random_seed()
1569 sage: x = QuaternionHermitianEJA.random_instance().random_element()
1570 sage: x.operator().matrix().is_symmetric()
1571 True
1572
1573 """
1574 @classmethod
1575 def _denormalized_basis(cls, n, field):
1576 """
1577 Returns a basis for the space of quaternion Hermitian n-by-n matrices.
1578
1579 Why do we embed these? Basically, because all of numerical
1580 linear algebra assumes that you're working with vectors consisting
1581 of `n` entries from a field and scalars from the same field. There's
1582 no way to tell SageMath that (for example) the vectors contain
1583 complex numbers, while the scalar field is real.
1584
1585 SETUP::
1586
1587 sage: from mjo.eja.eja_algebra import QuaternionHermitianEJA
1588
1589 TESTS::
1590
1591 sage: set_random_seed()
1592 sage: n = ZZ.random_element(1,5)
1593 sage: B = QuaternionHermitianEJA._denormalized_basis(n,QQ)
1594 sage: all( M.is_symmetric() for M in B )
1595 True
1596
1597 """
1598 Q = QuaternionAlgebra(QQ,-1,-1)
1599 I,J,K = Q.gens()
1600
1601 # This is like the symmetric case, but we need to be careful:
1602 #
1603 # * We want conjugate-symmetry, not just symmetry.
1604 # * The diagonal will (as a result) be real.
1605 #
1606 S = []
1607 for i in xrange(n):
1608 for j in xrange(i+1):
1609 Eij = matrix(Q, n, lambda k,l: k==i and l==j)
1610 if i == j:
1611 Sij = cls.real_embed(Eij)
1612 S.append(Sij)
1613 else:
1614 # The second, third, and fourth ones have a minus
1615 # because they're conjugated.
1616 Sij_real = cls.real_embed(Eij + Eij.transpose())
1617 S.append(Sij_real)
1618 Sij_I = cls.real_embed(I*Eij - I*Eij.transpose())
1619 S.append(Sij_I)
1620 Sij_J = cls.real_embed(J*Eij - J*Eij.transpose())
1621 S.append(Sij_J)
1622 Sij_K = cls.real_embed(K*Eij - K*Eij.transpose())
1623 S.append(Sij_K)
1624 return tuple(S)
1625
1626
1627
1628 class JordanSpinEJA(FiniteDimensionalEuclideanJordanAlgebra):
1629 """
1630 The rank-2 simple EJA consisting of real vectors ``x=(x0, x_bar)``
1631 with the usual inner product and jordan product ``x*y =
1632 (<x_bar,y_bar>, x0*y_bar + y0*x_bar)``. It has dimension `n` over
1633 the reals.
1634
1635 SETUP::
1636
1637 sage: from mjo.eja.eja_algebra import JordanSpinEJA
1638
1639 EXAMPLES:
1640
1641 This multiplication table can be verified by hand::
1642
1643 sage: J = JordanSpinEJA(4)
1644 sage: e0,e1,e2,e3 = J.gens()
1645 sage: e0*e0
1646 e0
1647 sage: e0*e1
1648 e1
1649 sage: e0*e2
1650 e2
1651 sage: e0*e3
1652 e3
1653 sage: e1*e2
1654 0
1655 sage: e1*e3
1656 0
1657 sage: e2*e3
1658 0
1659
1660 We can change the generator prefix::
1661
1662 sage: JordanSpinEJA(2, prefix='B').gens()
1663 (B0, B1)
1664
1665 """
1666 def __init__(self, n, field=QQ, **kwargs):
1667 V = VectorSpace(field, n)
1668 mult_table = [[V.zero() for j in range(n)] for i in range(n)]
1669 for i in range(n):
1670 for j in range(n):
1671 x = V.gen(i)
1672 y = V.gen(j)
1673 x0 = x[0]
1674 xbar = x[1:]
1675 y0 = y[0]
1676 ybar = y[1:]
1677 # z = x*y
1678 z0 = x.inner_product(y)
1679 zbar = y0*xbar + x0*ybar
1680 z = V([z0] + zbar.list())
1681 mult_table[i][j] = z
1682
1683 # The rank of the spin algebra is two, unless we're in a
1684 # one-dimensional ambient space (because the rank is bounded by
1685 # the ambient dimension).
1686 fdeja = super(JordanSpinEJA, self)
1687 return fdeja.__init__(field, mult_table, rank=min(n,2), **kwargs)
1688
1689 def inner_product(self, x, y):
1690 """
1691 Faster to reimplement than to use natural representations.
1692
1693 SETUP::
1694
1695 sage: from mjo.eja.eja_algebra import JordanSpinEJA
1696
1697 TESTS:
1698
1699 Ensure that this is the usual inner product for the algebras
1700 over `R^n`::
1701
1702 sage: set_random_seed()
1703 sage: J = JordanSpinEJA.random_instance()
1704 sage: x,y = J.random_elements(2)
1705 sage: X = x.natural_representation()
1706 sage: Y = y.natural_representation()
1707 sage: x.inner_product(y) == J.natural_inner_product(X,Y)
1708 True
1709
1710 """
1711 return x.to_vector().inner_product(y.to_vector())