]> gitweb.michael.orlitzky.com - sage.d.git/blob - mjo/eja/eja_algebra.py
eja: reimplement multiplication_table() without member variables.
[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 SETUP::
9
10 sage: from mjo.eja.eja_algebra import random_eja
11
12 EXAMPLES::
13
14 sage: random_eja()
15 Euclidean Jordan algebra of dimension...
16
17 """
18
19 from itertools import repeat
20
21 from sage.algebras.quatalg.quaternion_algebra import QuaternionAlgebra
22 from sage.categories.magmatic_algebras import MagmaticAlgebras
23 from sage.combinat.free_module import CombinatorialFreeModule
24 from sage.matrix.constructor import matrix
25 from sage.matrix.matrix_space import MatrixSpace
26 from sage.misc.cachefunc import cached_method
27 from sage.misc.table import table
28 from sage.modules.free_module import FreeModule, VectorSpace
29 from sage.rings.all import (ZZ, QQ, AA, QQbar, RR, RLF, CLF,
30 PolynomialRing,
31 QuadraticField)
32 from mjo.eja.eja_element import FiniteDimensionalEuclideanJordanAlgebraElement
33 from mjo.eja.eja_operator import FiniteDimensionalEuclideanJordanAlgebraOperator
34 from mjo.eja.eja_utils import _mat2vec
35
36 class FiniteDimensionalEuclideanJordanAlgebra(CombinatorialFreeModule):
37 r"""
38 The lowest-level class for representing a Euclidean Jordan algebra.
39 """
40 def _coerce_map_from_base_ring(self):
41 """
42 Disable the map from the base ring into the algebra.
43
44 Performing a nonsense conversion like this automatically
45 is counterpedagogical. The fallback is to try the usual
46 element constructor, which should also fail.
47
48 SETUP::
49
50 sage: from mjo.eja.eja_algebra import random_eja
51
52 TESTS::
53
54 sage: set_random_seed()
55 sage: J = random_eja()
56 sage: J(1)
57 Traceback (most recent call last):
58 ...
59 ValueError: not an element of this algebra
60
61 """
62 return None
63
64 def __init__(self,
65 field,
66 multiplication_table,
67 inner_product_table,
68 prefix='e',
69 category=None,
70 matrix_basis=None,
71 check_field=True,
72 check_axioms=True):
73 """
74 INPUT:
75
76 * field -- the scalar field for this algebra (must be real)
77
78 * multiplication_table -- the multiplication table for this
79 algebra's implicit basis. Only the lower-triangular portion
80 of the table is used, since the multiplication is assumed
81 to be commutative.
82
83 SETUP::
84
85 sage: from mjo.eja.eja_algebra import (
86 ....: FiniteDimensionalEuclideanJordanAlgebra,
87 ....: JordanSpinEJA,
88 ....: random_eja)
89
90 EXAMPLES:
91
92 By definition, Jordan multiplication commutes::
93
94 sage: set_random_seed()
95 sage: J = random_eja()
96 sage: x,y = J.random_elements(2)
97 sage: x*y == y*x
98 True
99
100 An error is raised if the Jordan product is not commutative::
101
102 sage: JP = ((1,2),(0,0))
103 sage: IP = ((1,0),(0,1))
104 sage: FiniteDimensionalEuclideanJordanAlgebra(QQ,JP,IP)
105 Traceback (most recent call last):
106 ...
107 ValueError: Jordan product is not commutative
108
109 An error is raised if the inner-product is not commutative::
110
111 sage: JP = ((1,0),(0,1))
112 sage: IP = ((1,2),(0,0))
113 sage: FiniteDimensionalEuclideanJordanAlgebra(QQ,JP,IP)
114 Traceback (most recent call last):
115 ...
116 ValueError: inner-product is not commutative
117
118 TESTS:
119
120 The ``field`` we're given must be real with ``check_field=True``::
121
122 sage: JordanSpinEJA(2, field=QQbar)
123 Traceback (most recent call last):
124 ...
125 ValueError: scalar field is not real
126 sage: JordanSpinEJA(2, field=QQbar, check_field=False)
127 Euclidean Jordan algebra of dimension 2 over Algebraic Field
128
129 The multiplication table must be square with ``check_axioms=True``::
130
131 sage: FiniteDimensionalEuclideanJordanAlgebra(QQ,((),()),((1,),))
132 Traceback (most recent call last):
133 ...
134 ValueError: multiplication table is not square
135
136 The multiplication and inner-product tables must be the same
137 size (and in particular, the inner-product table must also be
138 square) with ``check_axioms=True``::
139
140 sage: FiniteDimensionalEuclideanJordanAlgebra(QQ,((1,),),(()))
141 Traceback (most recent call last):
142 ...
143 ValueError: multiplication and inner-product tables are
144 different sizes
145 sage: FiniteDimensionalEuclideanJordanAlgebra(QQ,((1,),),((1,2),))
146 Traceback (most recent call last):
147 ...
148 ValueError: multiplication and inner-product tables are
149 different sizes
150
151 """
152 if check_field:
153 if not field.is_subring(RR):
154 # Note: this does return true for the real algebraic
155 # field, the rationals, and any quadratic field where
156 # we've specified a real embedding.
157 raise ValueError("scalar field is not real")
158
159
160 # The multiplication and inner-product tables should be square
161 # if the user wants us to verify them. And we verify them as
162 # soon as possible, because we want to exploit their symmetry.
163 n = len(multiplication_table)
164 if check_axioms:
165 if not all( len(l) == n for l in multiplication_table ):
166 raise ValueError("multiplication table is not square")
167
168 # If the multiplication table is square, we can check if
169 # the inner-product table is square by comparing it to the
170 # multiplication table's dimensions.
171 msg = "multiplication and inner-product tables are different sizes"
172 if not len(inner_product_table) == n:
173 raise ValueError(msg)
174
175 if not all( len(l) == n for l in inner_product_table ):
176 raise ValueError(msg)
177
178 # Check commutativity of the Jordan product (symmetry of
179 # the multiplication table) and the commutativity of the
180 # inner-product (symmetry of the inner-product table)
181 # first if we're going to check them at all.. This has to
182 # be done before we define product_on_basis(), because
183 # that method assumes that self._multiplication_table is
184 # symmetric. And it has to be done before we build
185 # self._inner_product_matrix, because the process used to
186 # construct it assumes symmetry as well.
187 if not all( multiplication_table[j][i]
188 == multiplication_table[i][j]
189 for i in range(n)
190 for j in range(i+1) ):
191 raise ValueError("Jordan product is not commutative")
192
193 if not all( inner_product_table[j][i]
194 == inner_product_table[i][j]
195 for i in range(n)
196 for j in range(i+1) ):
197 raise ValueError("inner-product is not commutative")
198
199 self._matrix_basis = matrix_basis
200
201 if category is None:
202 category = MagmaticAlgebras(field).FiniteDimensional()
203 category = category.WithBasis().Unital()
204
205 fda = super(FiniteDimensionalEuclideanJordanAlgebra, self)
206 fda.__init__(field,
207 range(n),
208 prefix=prefix,
209 category=category)
210 self.print_options(bracket='')
211
212 # The multiplication table we're given is necessarily in terms
213 # of vectors, because we don't have an algebra yet for
214 # anything to be an element of. However, it's faster in the
215 # long run to have the multiplication table be in terms of
216 # algebra elements. We do this after calling the superclass
217 # constructor so that from_vector() knows what to do.
218 #
219 # Note: we take advantage of symmetry here, and only store
220 # the lower-triangular portion of the table.
221 self._multiplication_table = [ [ self.vector_space().zero()
222 for j in range(i+1) ]
223 for i in range(n) ]
224
225 for i in range(n):
226 for j in range(i+1):
227 elt = self.from_vector(multiplication_table[i][j])
228 self._multiplication_table[i][j] = elt
229
230 self._multiplication_table = tuple(map(tuple, self._multiplication_table))
231
232 # Save our inner product as a matrix, since the efficiency of
233 # matrix multiplication will usually outweigh the fact that we
234 # have to store a redundant upper- or lower-triangular part.
235 # Pre-cache the fact that these are Hermitian (real symmetric,
236 # in fact) in case some e.g. matrix multiplication routine can
237 # take advantage of it.
238 ip_matrix_constructor = lambda i,j: inner_product_table[i][j] if j <= i else inner_product_table[j][i]
239 self._inner_product_matrix = matrix(field, n, ip_matrix_constructor)
240 self._inner_product_matrix._cache = {'hermitian': True}
241 self._inner_product_matrix.set_immutable()
242
243 if check_axioms:
244 if not self._is_jordanian():
245 raise ValueError("Jordan identity does not hold")
246 if not self._inner_product_is_associative():
247 raise ValueError("inner product is not associative")
248
249 def _element_constructor_(self, elt):
250 """
251 Construct an element of this algebra from its vector or matrix
252 representation.
253
254 This gets called only after the parent element _call_ method
255 fails to find a coercion for the argument.
256
257 SETUP::
258
259 sage: from mjo.eja.eja_algebra import (JordanSpinEJA,
260 ....: HadamardEJA,
261 ....: RealSymmetricEJA)
262
263 EXAMPLES:
264
265 The identity in `S^n` is converted to the identity in the EJA::
266
267 sage: J = RealSymmetricEJA(3)
268 sage: I = matrix.identity(QQ,3)
269 sage: J(I) == J.one()
270 True
271
272 This skew-symmetric matrix can't be represented in the EJA::
273
274 sage: J = RealSymmetricEJA(3)
275 sage: A = matrix(QQ,3, lambda i,j: i-j)
276 sage: J(A)
277 Traceback (most recent call last):
278 ...
279 ValueError: not an element of this algebra
280
281 TESTS:
282
283 Ensure that we can convert any element of the two non-matrix
284 simple algebras (whose matrix representations are columns)
285 back and forth faithfully::
286
287 sage: set_random_seed()
288 sage: J = HadamardEJA.random_instance()
289 sage: x = J.random_element()
290 sage: J(x.to_vector().column()) == x
291 True
292 sage: J = JordanSpinEJA.random_instance()
293 sage: x = J.random_element()
294 sage: J(x.to_vector().column()) == x
295 True
296
297 """
298 msg = "not an element of this algebra"
299 if elt == 0:
300 # The superclass implementation of random_element()
301 # needs to be able to coerce "0" into the algebra.
302 return self.zero()
303 elif elt in self.base_ring():
304 # Ensure that no base ring -> algebra coercion is performed
305 # by this method. There's some stupidity in sage that would
306 # otherwise propagate to this method; for example, sage thinks
307 # that the integer 3 belongs to the space of 2-by-2 matrices.
308 raise ValueError(msg)
309
310 if elt not in self.matrix_space():
311 raise ValueError(msg)
312
313 # Thanks for nothing! Matrix spaces aren't vector spaces in
314 # Sage, so we have to figure out its matrix-basis coordinates
315 # ourselves. We use the basis space's ring instead of the
316 # element's ring because the basis space might be an algebraic
317 # closure whereas the base ring of the 3-by-3 identity matrix
318 # could be QQ instead of QQbar.
319 #
320 # We pass check=False because the matrix basis is "guaranteed"
321 # to be linearly independent... right? Ha ha.
322 V = VectorSpace(self.base_ring(), elt.nrows()*elt.ncols())
323 W = V.span_of_basis( (_mat2vec(s) for s in self.matrix_basis()),
324 check=False)
325
326 try:
327 coords = W.coordinate_vector(_mat2vec(elt))
328 except ArithmeticError: # vector is not in free module
329 raise ValueError(msg)
330
331 return self.from_vector(coords)
332
333 def _repr_(self):
334 """
335 Return a string representation of ``self``.
336
337 SETUP::
338
339 sage: from mjo.eja.eja_algebra import JordanSpinEJA
340
341 TESTS:
342
343 Ensure that it says what we think it says::
344
345 sage: JordanSpinEJA(2, field=AA)
346 Euclidean Jordan algebra of dimension 2 over Algebraic Real Field
347 sage: JordanSpinEJA(3, field=RDF)
348 Euclidean Jordan algebra of dimension 3 over Real Double Field
349
350 """
351 fmt = "Euclidean Jordan algebra of dimension {} over {}"
352 return fmt.format(self.dimension(), self.base_ring())
353
354 def product_on_basis(self, i, j):
355 # We only stored the lower-triangular portion of the
356 # multiplication table.
357 if j <= i:
358 return self._multiplication_table[i][j]
359 else:
360 return self._multiplication_table[j][i]
361
362 def _is_commutative(self):
363 r"""
364 Whether or not this algebra's multiplication table is commutative.
365
366 This method should of course always return ``True``, unless
367 this algebra was constructed with ``check_axioms=False`` and
368 passed an invalid multiplication table.
369 """
370 return all( self.product_on_basis(i,j) == self.product_on_basis(i,j)
371 for i in range(self.dimension())
372 for j in range(self.dimension()) )
373
374 def _is_jordanian(self):
375 r"""
376 Whether or not this algebra's multiplication table respects the
377 Jordan identity `(x^{2})(xy) = x(x^{2}y)`.
378
379 We only check one arrangement of `x` and `y`, so for a
380 ``True`` result to be truly true, you should also check
381 :meth:`_is_commutative`. This method should of course always
382 return ``True``, unless this algebra was constructed with
383 ``check_axioms=False`` and passed an invalid multiplication table.
384 """
385 return all( (self.monomial(i)**2)*(self.monomial(i)*self.monomial(j))
386 ==
387 (self.monomial(i))*((self.monomial(i)**2)*self.monomial(j))
388 for i in range(self.dimension())
389 for j in range(self.dimension()) )
390
391 def _inner_product_is_associative(self):
392 r"""
393 Return whether or not this algebra's inner product `B` is
394 associative; that is, whether or not `B(xy,z) = B(x,yz)`.
395
396 This method should of course always return ``True``, unless
397 this algebra was constructed with ``check_axioms=False`` and
398 passed an invalid multiplication table.
399 """
400
401 # Used to check whether or not something is zero in an inexact
402 # ring. This number is sufficient to allow the construction of
403 # QuaternionHermitianEJA(2, field=RDF) with check_axioms=True.
404 epsilon = 1e-16
405
406 for i in range(self.dimension()):
407 for j in range(self.dimension()):
408 for k in range(self.dimension()):
409 x = self.monomial(i)
410 y = self.monomial(j)
411 z = self.monomial(k)
412 diff = (x*y).inner_product(z) - x.inner_product(y*z)
413
414 if self.base_ring().is_exact():
415 if diff != 0:
416 return False
417 else:
418 if diff.abs() > epsilon:
419 return False
420
421 return True
422
423 @cached_method
424 def characteristic_polynomial_of(self):
425 """
426 Return the algebra's "characteristic polynomial of" function,
427 which is itself a multivariate polynomial that, when evaluated
428 at the coordinates of some algebra element, returns that
429 element's characteristic polynomial.
430
431 The resulting polynomial has `n+1` variables, where `n` is the
432 dimension of this algebra. The first `n` variables correspond to
433 the coordinates of an algebra element: when evaluated at the
434 coordinates of an algebra element with respect to a certain
435 basis, the result is a univariate polynomial (in the one
436 remaining variable ``t``), namely the characteristic polynomial
437 of that element.
438
439 SETUP::
440
441 sage: from mjo.eja.eja_algebra import JordanSpinEJA, TrivialEJA
442
443 EXAMPLES:
444
445 The characteristic polynomial in the spin algebra is given in
446 Alizadeh, Example 11.11::
447
448 sage: J = JordanSpinEJA(3)
449 sage: p = J.characteristic_polynomial_of(); p
450 X1^2 - X2^2 - X3^2 + (-2*t)*X1 + t^2
451 sage: xvec = J.one().to_vector()
452 sage: p(*xvec)
453 t^2 - 2*t + 1
454
455 By definition, the characteristic polynomial is a monic
456 degree-zero polynomial in a rank-zero algebra. Note that
457 Cayley-Hamilton is indeed satisfied since the polynomial
458 ``1`` evaluates to the identity element of the algebra on
459 any argument::
460
461 sage: J = TrivialEJA()
462 sage: J.characteristic_polynomial_of()
463 1
464
465 """
466 r = self.rank()
467 n = self.dimension()
468
469 # The list of coefficient polynomials a_0, a_1, a_2, ..., a_(r-1).
470 a = self._charpoly_coefficients()
471
472 # We go to a bit of trouble here to reorder the
473 # indeterminates, so that it's easier to evaluate the
474 # characteristic polynomial at x's coordinates and get back
475 # something in terms of t, which is what we want.
476 S = PolynomialRing(self.base_ring(),'t')
477 t = S.gen(0)
478 if r > 0:
479 R = a[0].parent()
480 S = PolynomialRing(S, R.variable_names())
481 t = S(t)
482
483 return (t**r + sum( a[k]*(t**k) for k in range(r) ))
484
485 def coordinate_polynomial_ring(self):
486 r"""
487 The multivariate polynomial ring in which this algebra's
488 :meth:`characteristic_polynomial_of` lives.
489
490 SETUP::
491
492 sage: from mjo.eja.eja_algebra import (HadamardEJA,
493 ....: RealSymmetricEJA)
494
495 EXAMPLES::
496
497 sage: J = HadamardEJA(2)
498 sage: J.coordinate_polynomial_ring()
499 Multivariate Polynomial Ring in X1, X2...
500 sage: J = RealSymmetricEJA(3,field=QQ,orthonormalize=False)
501 sage: J.coordinate_polynomial_ring()
502 Multivariate Polynomial Ring in X1, X2, X3, X4, X5, X6...
503
504 """
505 var_names = tuple( "X%d" % z for z in range(1, self.dimension()+1) )
506 return PolynomialRing(self.base_ring(), var_names)
507
508 def inner_product(self, x, y):
509 """
510 The inner product associated with this Euclidean Jordan algebra.
511
512 Defaults to the trace inner product, but can be overridden by
513 subclasses if they are sure that the necessary properties are
514 satisfied.
515
516 SETUP::
517
518 sage: from mjo.eja.eja_algebra import (random_eja,
519 ....: HadamardEJA,
520 ....: BilinearFormEJA)
521
522 EXAMPLES:
523
524 Our inner product is "associative," which means the following for
525 a symmetric bilinear form::
526
527 sage: set_random_seed()
528 sage: J = random_eja()
529 sage: x,y,z = J.random_elements(3)
530 sage: (x*y).inner_product(z) == y.inner_product(x*z)
531 True
532
533 TESTS:
534
535 Ensure that this is the usual inner product for the algebras
536 over `R^n`::
537
538 sage: set_random_seed()
539 sage: J = HadamardEJA.random_instance()
540 sage: x,y = J.random_elements(2)
541 sage: actual = x.inner_product(y)
542 sage: expected = x.to_vector().inner_product(y.to_vector())
543 sage: actual == expected
544 True
545
546 Ensure that this is one-half of the trace inner-product in a
547 BilinearFormEJA that isn't just the reals (when ``n`` isn't
548 one). This is in Faraut and Koranyi, and also my "On the
549 symmetry..." paper::
550
551 sage: set_random_seed()
552 sage: J = BilinearFormEJA.random_instance()
553 sage: n = J.dimension()
554 sage: x = J.random_element()
555 sage: y = J.random_element()
556 sage: (n == 1) or (x.inner_product(y) == (x*y).trace()/2)
557 True
558 """
559 B = self._inner_product_matrix
560 return (B*x.to_vector()).inner_product(y.to_vector())
561
562
563 def is_trivial(self):
564 """
565 Return whether or not this algebra is trivial.
566
567 A trivial algebra contains only the zero element.
568
569 SETUP::
570
571 sage: from mjo.eja.eja_algebra import (ComplexHermitianEJA,
572 ....: TrivialEJA)
573
574 EXAMPLES::
575
576 sage: J = ComplexHermitianEJA(3)
577 sage: J.is_trivial()
578 False
579
580 ::
581
582 sage: J = TrivialEJA()
583 sage: J.is_trivial()
584 True
585
586 """
587 return self.dimension() == 0
588
589
590 def multiplication_table(self):
591 """
592 Return a visual representation of this algebra's multiplication
593 table (on basis elements).
594
595 SETUP::
596
597 sage: from mjo.eja.eja_algebra import JordanSpinEJA
598
599 EXAMPLES::
600
601 sage: J = JordanSpinEJA(4)
602 sage: J.multiplication_table()
603 +----++----+----+----+----+
604 | * || e0 | e1 | e2 | e3 |
605 +====++====+====+====+====+
606 | e0 || e0 | e1 | e2 | e3 |
607 +----++----+----+----+----+
608 | e1 || e1 | e0 | 0 | 0 |
609 +----++----+----+----+----+
610 | e2 || e2 | 0 | e0 | 0 |
611 +----++----+----+----+----+
612 | e3 || e3 | 0 | 0 | e0 |
613 +----++----+----+----+----+
614
615 """
616 n = self.dimension()
617 # Prepend the header row.
618 M = [["*"] + list(self.gens())]
619
620 # And to each subsequent row, prepend an entry that belongs to
621 # the left-side "header column."
622 M += [ [self.monomial(i)] + [ self.product_on_basis(i,j)
623 for j in range(n) ]
624 for i in range(n) ]
625
626 return table(M, header_row=True, header_column=True, frame=True)
627
628
629 def matrix_basis(self):
630 """
631 Return an (often more natural) representation of this algebras
632 basis as an ordered tuple of matrices.
633
634 Every finite-dimensional Euclidean Jordan Algebra is a, up to
635 Jordan isomorphism, a direct sum of five simple
636 algebras---four of which comprise Hermitian matrices. And the
637 last type of algebra can of course be thought of as `n`-by-`1`
638 column matrices (ambiguusly called column vectors) to avoid
639 special cases. As a result, matrices (and column vectors) are
640 a natural representation format for Euclidean Jordan algebra
641 elements.
642
643 But, when we construct an algebra from a basis of matrices,
644 those matrix representations are lost in favor of coordinate
645 vectors *with respect to* that basis. We could eventually
646 convert back if we tried hard enough, but having the original
647 representations handy is valuable enough that we simply store
648 them and return them from this method.
649
650 Why implement this for non-matrix algebras? Avoiding special
651 cases for the :class:`BilinearFormEJA` pays with simplicity in
652 its own right. But mainly, we would like to be able to assume
653 that elements of a :class:`DirectSumEJA` can be displayed
654 nicely, without having to have special classes for direct sums
655 one of whose components was a matrix algebra.
656
657 SETUP::
658
659 sage: from mjo.eja.eja_algebra import (JordanSpinEJA,
660 ....: RealSymmetricEJA)
661
662 EXAMPLES::
663
664 sage: J = RealSymmetricEJA(2)
665 sage: J.basis()
666 Finite family {0: e0, 1: e1, 2: e2}
667 sage: J.matrix_basis()
668 (
669 [1 0] [ 0 0.7071067811865475?] [0 0]
670 [0 0], [0.7071067811865475? 0], [0 1]
671 )
672
673 ::
674
675 sage: J = JordanSpinEJA(2)
676 sage: J.basis()
677 Finite family {0: e0, 1: e1}
678 sage: J.matrix_basis()
679 (
680 [1] [0]
681 [0], [1]
682 )
683 """
684 if self._matrix_basis is None:
685 M = self.matrix_space()
686 return tuple( M(b.to_vector()) for b in self.basis() )
687 else:
688 return self._matrix_basis
689
690
691 def matrix_space(self):
692 """
693 Return the matrix space in which this algebra's elements live, if
694 we think of them as matrices (including column vectors of the
695 appropriate size).
696
697 Generally this will be an `n`-by-`1` column-vector space,
698 except when the algebra is trivial. There it's `n`-by-`n`
699 (where `n` is zero), to ensure that two elements of the matrix
700 space (empty matrices) can be multiplied.
701
702 Matrix algebras override this with something more useful.
703 """
704 if self.is_trivial():
705 return MatrixSpace(self.base_ring(), 0)
706 elif self._matrix_basis is None or len(self._matrix_basis) == 0:
707 return MatrixSpace(self.base_ring(), self.dimension(), 1)
708 else:
709 return self._matrix_basis[0].matrix_space()
710
711
712 @cached_method
713 def one(self):
714 """
715 Return the unit element of this algebra.
716
717 SETUP::
718
719 sage: from mjo.eja.eja_algebra import (HadamardEJA,
720 ....: random_eja)
721
722 EXAMPLES::
723
724 sage: J = HadamardEJA(5)
725 sage: J.one()
726 e0 + e1 + e2 + e3 + e4
727
728 TESTS:
729
730 The identity element acts like the identity::
731
732 sage: set_random_seed()
733 sage: J = random_eja()
734 sage: x = J.random_element()
735 sage: J.one()*x == x and x*J.one() == x
736 True
737
738 The matrix of the unit element's operator is the identity::
739
740 sage: set_random_seed()
741 sage: J = random_eja()
742 sage: actual = J.one().operator().matrix()
743 sage: expected = matrix.identity(J.base_ring(), J.dimension())
744 sage: actual == expected
745 True
746
747 Ensure that the cached unit element (often precomputed by
748 hand) agrees with the computed one::
749
750 sage: set_random_seed()
751 sage: J = random_eja()
752 sage: cached = J.one()
753 sage: J.one.clear_cache()
754 sage: J.one() == cached
755 True
756
757 """
758 # We can brute-force compute the matrices of the operators
759 # that correspond to the basis elements of this algebra.
760 # If some linear combination of those basis elements is the
761 # algebra identity, then the same linear combination of
762 # their matrices has to be the identity matrix.
763 #
764 # Of course, matrices aren't vectors in sage, so we have to
765 # appeal to the "long vectors" isometry.
766 oper_vecs = [ _mat2vec(g.operator().matrix()) for g in self.gens() ]
767
768 # Now we use basic linear algebra to find the coefficients,
769 # of the matrices-as-vectors-linear-combination, which should
770 # work for the original algebra basis too.
771 A = matrix(self.base_ring(), oper_vecs)
772
773 # We used the isometry on the left-hand side already, but we
774 # still need to do it for the right-hand side. Recall that we
775 # wanted something that summed to the identity matrix.
776 b = _mat2vec( matrix.identity(self.base_ring(), self.dimension()) )
777
778 # Now if there's an identity element in the algebra, this
779 # should work. We solve on the left to avoid having to
780 # transpose the matrix "A".
781 return self.from_vector(A.solve_left(b))
782
783
784 def peirce_decomposition(self, c):
785 """
786 The Peirce decomposition of this algebra relative to the
787 idempotent ``c``.
788
789 In the future, this can be extended to a complete system of
790 orthogonal idempotents.
791
792 INPUT:
793
794 - ``c`` -- an idempotent of this algebra.
795
796 OUTPUT:
797
798 A triple (J0, J5, J1) containing two subalgebras and one subspace
799 of this algebra,
800
801 - ``J0`` -- the algebra on the eigenspace of ``c.operator()``
802 corresponding to the eigenvalue zero.
803
804 - ``J5`` -- the eigenspace (NOT a subalgebra) of ``c.operator()``
805 corresponding to the eigenvalue one-half.
806
807 - ``J1`` -- the algebra on the eigenspace of ``c.operator()``
808 corresponding to the eigenvalue one.
809
810 These are the only possible eigenspaces for that operator, and this
811 algebra is a direct sum of them. The spaces ``J0`` and ``J1`` are
812 orthogonal, and are subalgebras of this algebra with the appropriate
813 restrictions.
814
815 SETUP::
816
817 sage: from mjo.eja.eja_algebra import random_eja, RealSymmetricEJA
818
819 EXAMPLES:
820
821 The canonical example comes from the symmetric matrices, which
822 decompose into diagonal and off-diagonal parts::
823
824 sage: J = RealSymmetricEJA(3)
825 sage: C = matrix(QQ, [ [1,0,0],
826 ....: [0,1,0],
827 ....: [0,0,0] ])
828 sage: c = J(C)
829 sage: J0,J5,J1 = J.peirce_decomposition(c)
830 sage: J0
831 Euclidean Jordan algebra of dimension 1...
832 sage: J5
833 Vector space of degree 6 and dimension 2...
834 sage: J1
835 Euclidean Jordan algebra of dimension 3...
836 sage: J0.one().to_matrix()
837 [0 0 0]
838 [0 0 0]
839 [0 0 1]
840 sage: orig_df = AA.options.display_format
841 sage: AA.options.display_format = 'radical'
842 sage: J.from_vector(J5.basis()[0]).to_matrix()
843 [ 0 0 1/2*sqrt(2)]
844 [ 0 0 0]
845 [1/2*sqrt(2) 0 0]
846 sage: J.from_vector(J5.basis()[1]).to_matrix()
847 [ 0 0 0]
848 [ 0 0 1/2*sqrt(2)]
849 [ 0 1/2*sqrt(2) 0]
850 sage: AA.options.display_format = orig_df
851 sage: J1.one().to_matrix()
852 [1 0 0]
853 [0 1 0]
854 [0 0 0]
855
856 TESTS:
857
858 Every algebra decomposes trivially with respect to its identity
859 element::
860
861 sage: set_random_seed()
862 sage: J = random_eja()
863 sage: J0,J5,J1 = J.peirce_decomposition(J.one())
864 sage: J0.dimension() == 0 and J5.dimension() == 0
865 True
866 sage: J1.superalgebra() == J and J1.dimension() == J.dimension()
867 True
868
869 The decomposition is into eigenspaces, and its components are
870 therefore necessarily orthogonal. Moreover, the identity
871 elements in the two subalgebras are the projections onto their
872 respective subspaces of the superalgebra's identity element::
873
874 sage: set_random_seed()
875 sage: J = random_eja()
876 sage: x = J.random_element()
877 sage: if not J.is_trivial():
878 ....: while x.is_nilpotent():
879 ....: x = J.random_element()
880 sage: c = x.subalgebra_idempotent()
881 sage: J0,J5,J1 = J.peirce_decomposition(c)
882 sage: ipsum = 0
883 sage: for (w,y,z) in zip(J0.basis(), J5.basis(), J1.basis()):
884 ....: w = w.superalgebra_element()
885 ....: y = J.from_vector(y)
886 ....: z = z.superalgebra_element()
887 ....: ipsum += w.inner_product(y).abs()
888 ....: ipsum += w.inner_product(z).abs()
889 ....: ipsum += y.inner_product(z).abs()
890 sage: ipsum
891 0
892 sage: J1(c) == J1.one()
893 True
894 sage: J0(J.one() - c) == J0.one()
895 True
896
897 """
898 if not c.is_idempotent():
899 raise ValueError("element is not idempotent: %s" % c)
900
901 from mjo.eja.eja_subalgebra import FiniteDimensionalEuclideanJordanSubalgebra
902
903 # Default these to what they should be if they turn out to be
904 # trivial, because eigenspaces_left() won't return eigenvalues
905 # corresponding to trivial spaces (e.g. it returns only the
906 # eigenspace corresponding to lambda=1 if you take the
907 # decomposition relative to the identity element).
908 trivial = FiniteDimensionalEuclideanJordanSubalgebra(self, ())
909 J0 = trivial # eigenvalue zero
910 J5 = VectorSpace(self.base_ring(), 0) # eigenvalue one-half
911 J1 = trivial # eigenvalue one
912
913 for (eigval, eigspace) in c.operator().matrix().right_eigenspaces():
914 if eigval == ~(self.base_ring()(2)):
915 J5 = eigspace
916 else:
917 gens = tuple( self.from_vector(b) for b in eigspace.basis() )
918 subalg = FiniteDimensionalEuclideanJordanSubalgebra(self,
919 gens,
920 check_axioms=False)
921 if eigval == 0:
922 J0 = subalg
923 elif eigval == 1:
924 J1 = subalg
925 else:
926 raise ValueError("unexpected eigenvalue: %s" % eigval)
927
928 return (J0, J5, J1)
929
930
931 def random_element(self, thorough=False):
932 r"""
933 Return a random element of this algebra.
934
935 Our algebra superclass method only returns a linear
936 combination of at most two basis elements. We instead
937 want the vector space "random element" method that
938 returns a more diverse selection.
939
940 INPUT:
941
942 - ``thorough`` -- (boolean; default False) whether or not we
943 should generate irrational coefficients for the random
944 element when our base ring is irrational; this slows the
945 algebra operations to a crawl, but any truly random method
946 should include them
947
948 """
949 # For a general base ring... maybe we can trust this to do the
950 # right thing? Unlikely, but.
951 V = self.vector_space()
952 v = V.random_element()
953
954 if self.base_ring() is AA:
955 # The "random element" method of the algebraic reals is
956 # stupid at the moment, and only returns integers between
957 # -2 and 2, inclusive:
958 #
959 # https://trac.sagemath.org/ticket/30875
960 #
961 # Instead, we implement our own "random vector" method,
962 # and then coerce that into the algebra. We use the vector
963 # space degree here instead of the dimension because a
964 # subalgebra could (for example) be spanned by only two
965 # vectors, each with five coordinates. We need to
966 # generate all five coordinates.
967 if thorough:
968 v *= QQbar.random_element().real()
969 else:
970 v *= QQ.random_element()
971
972 return self.from_vector(V.coordinate_vector(v))
973
974 def random_elements(self, count, thorough=False):
975 """
976 Return ``count`` random elements as a tuple.
977
978 INPUT:
979
980 - ``thorough`` -- (boolean; default False) whether or not we
981 should generate irrational coefficients for the random
982 elements when our base ring is irrational; this slows the
983 algebra operations to a crawl, but any truly random method
984 should include them
985
986 SETUP::
987
988 sage: from mjo.eja.eja_algebra import JordanSpinEJA
989
990 EXAMPLES::
991
992 sage: J = JordanSpinEJA(3)
993 sage: x,y,z = J.random_elements(3)
994 sage: all( [ x in J, y in J, z in J ])
995 True
996 sage: len( J.random_elements(10) ) == 10
997 True
998
999 """
1000 return tuple( self.random_element(thorough)
1001 for idx in range(count) )
1002
1003
1004 @cached_method
1005 def _charpoly_coefficients(self):
1006 r"""
1007 The `r` polynomial coefficients of the "characteristic polynomial
1008 of" function.
1009 """
1010 n = self.dimension()
1011 R = self.coordinate_polynomial_ring()
1012 vars = R.gens()
1013 F = R.fraction_field()
1014
1015 def L_x_i_j(i,j):
1016 # From a result in my book, these are the entries of the
1017 # basis representation of L_x.
1018 return sum( vars[k]*self.monomial(k).operator().matrix()[i,j]
1019 for k in range(n) )
1020
1021 L_x = matrix(F, n, n, L_x_i_j)
1022
1023 r = None
1024 if self.rank.is_in_cache():
1025 r = self.rank()
1026 # There's no need to pad the system with redundant
1027 # columns if we *know* they'll be redundant.
1028 n = r
1029
1030 # Compute an extra power in case the rank is equal to
1031 # the dimension (otherwise, we would stop at x^(r-1)).
1032 x_powers = [ (L_x**k)*self.one().to_vector()
1033 for k in range(n+1) ]
1034 A = matrix.column(F, x_powers[:n])
1035 AE = A.extended_echelon_form()
1036 E = AE[:,n:]
1037 A_rref = AE[:,:n]
1038 if r is None:
1039 r = A_rref.rank()
1040 b = x_powers[r]
1041
1042 # The theory says that only the first "r" coefficients are
1043 # nonzero, and they actually live in the original polynomial
1044 # ring and not the fraction field. We negate them because
1045 # in the actual characteristic polynomial, they get moved
1046 # to the other side where x^r lives.
1047 return -A_rref.solve_right(E*b).change_ring(R)[:r]
1048
1049 @cached_method
1050 def rank(self):
1051 r"""
1052 Return the rank of this EJA.
1053
1054 This is a cached method because we know the rank a priori for
1055 all of the algebras we can construct. Thus we can avoid the
1056 expensive ``_charpoly_coefficients()`` call unless we truly
1057 need to compute the whole characteristic polynomial.
1058
1059 SETUP::
1060
1061 sage: from mjo.eja.eja_algebra import (HadamardEJA,
1062 ....: JordanSpinEJA,
1063 ....: RealSymmetricEJA,
1064 ....: ComplexHermitianEJA,
1065 ....: QuaternionHermitianEJA,
1066 ....: random_eja)
1067
1068 EXAMPLES:
1069
1070 The rank of the Jordan spin algebra is always two::
1071
1072 sage: JordanSpinEJA(2).rank()
1073 2
1074 sage: JordanSpinEJA(3).rank()
1075 2
1076 sage: JordanSpinEJA(4).rank()
1077 2
1078
1079 The rank of the `n`-by-`n` Hermitian real, complex, or
1080 quaternion matrices is `n`::
1081
1082 sage: RealSymmetricEJA(4).rank()
1083 4
1084 sage: ComplexHermitianEJA(3).rank()
1085 3
1086 sage: QuaternionHermitianEJA(2).rank()
1087 2
1088
1089 TESTS:
1090
1091 Ensure that every EJA that we know how to construct has a
1092 positive integer rank, unless the algebra is trivial in
1093 which case its rank will be zero::
1094
1095 sage: set_random_seed()
1096 sage: J = random_eja()
1097 sage: r = J.rank()
1098 sage: r in ZZ
1099 True
1100 sage: r > 0 or (r == 0 and J.is_trivial())
1101 True
1102
1103 Ensure that computing the rank actually works, since the ranks
1104 of all simple algebras are known and will be cached by default::
1105
1106 sage: set_random_seed() # long time
1107 sage: J = random_eja() # long time
1108 sage: caches = J.rank() # long time
1109 sage: J.rank.clear_cache() # long time
1110 sage: J.rank() == cached # long time
1111 True
1112
1113 """
1114 return len(self._charpoly_coefficients())
1115
1116
1117 def vector_space(self):
1118 """
1119 Return the vector space that underlies this algebra.
1120
1121 SETUP::
1122
1123 sage: from mjo.eja.eja_algebra import RealSymmetricEJA
1124
1125 EXAMPLES::
1126
1127 sage: J = RealSymmetricEJA(2)
1128 sage: J.vector_space()
1129 Vector space of dimension 3 over...
1130
1131 """
1132 return self.zero().to_vector().parent().ambient_vector_space()
1133
1134
1135 Element = FiniteDimensionalEuclideanJordanAlgebraElement
1136
1137 class RationalBasisEuclideanJordanAlgebra(FiniteDimensionalEuclideanJordanAlgebra):
1138 r"""
1139 New class for algebras whose supplied basis elements have all rational entries.
1140
1141 SETUP::
1142
1143 sage: from mjo.eja.eja_algebra import BilinearFormEJA
1144
1145 EXAMPLES:
1146
1147 The supplied basis is orthonormalized by default::
1148
1149 sage: B = matrix(QQ, [[1, 0, 0], [0, 25, -32], [0, -32, 41]])
1150 sage: J = BilinearFormEJA(B)
1151 sage: J.matrix_basis()
1152 (
1153 [1] [ 0] [ 0]
1154 [0] [1/5] [32/5]
1155 [0], [ 0], [ 5]
1156 )
1157
1158 """
1159 def __init__(self,
1160 basis,
1161 jordan_product,
1162 inner_product,
1163 field=AA,
1164 orthonormalize=True,
1165 prefix='e',
1166 category=None,
1167 check_field=True,
1168 check_axioms=True):
1169
1170 if check_field:
1171 # Abuse the check_field parameter to check that the entries of
1172 # out basis (in ambient coordinates) are in the field QQ.
1173 if not all( all(b_i in QQ for b_i in b.list()) for b in basis ):
1174 raise TypeError("basis not rational")
1175
1176 # Temporary(?) hack to ensure that the matrix and vector bases
1177 # are over the same ring.
1178 basis = tuple( b.change_ring(field) for b in basis )
1179
1180 n = len(basis)
1181 vector_basis = basis
1182
1183 from sage.structure.element import is_Matrix
1184 basis_is_matrices = False
1185
1186 degree = 0
1187 if n > 0:
1188 if is_Matrix(basis[0]):
1189 basis_is_matrices = True
1190 from mjo.eja.eja_utils import _vec2mat
1191 vector_basis = tuple( map(_mat2vec,basis) )
1192 degree = basis[0].nrows()**2
1193 else:
1194 degree = basis[0].degree()
1195
1196 V = VectorSpace(field, degree)
1197
1198 # Save a copy of an algebra with the original, rational basis
1199 # and over QQ where computations are fast.
1200 self._rational_algebra = None
1201
1202 if field is not QQ:
1203 # There's no point in constructing the extra algebra if this
1204 # one is already rational.
1205 #
1206 # Note: the same Jordan and inner-products work here,
1207 # because they are necessarily defined with respect to
1208 # ambient coordinates and not any particular basis.
1209 self._rational_algebra = RationalBasisEuclideanJordanAlgebra(
1210 basis,
1211 jordan_product,
1212 inner_product,
1213 field=QQ,
1214 orthonormalize=False,
1215 prefix=prefix,
1216 category=category,
1217 check_field=False,
1218 check_axioms=False)
1219
1220 if orthonormalize:
1221 # Compute the deorthonormalized tables before we orthonormalize
1222 # the given basis. The "check" parameter here guarantees that
1223 # the basis is linearly-independent.
1224 W = V.span_of_basis( vector_basis, check=check_axioms)
1225
1226 # Note: the Jordan and inner-products are defined in terms
1227 # of the ambient basis. It's important that their arguments
1228 # are in ambient coordinates as well.
1229 for i in range(n):
1230 for j in range(i+1):
1231 # given basis w.r.t. ambient coords
1232 q_i = vector_basis[i]
1233 q_j = vector_basis[j]
1234
1235 if basis_is_matrices:
1236 q_i = _vec2mat(q_i)
1237 q_j = _vec2mat(q_j)
1238
1239 elt = jordan_product(q_i, q_j)
1240 ip = inner_product(q_i, q_j)
1241
1242 if basis_is_matrices:
1243 # do another mat2vec because the multiplication
1244 # table is in terms of vectors
1245 elt = _mat2vec(elt)
1246
1247 # We overwrite the name "vector_basis" in a second, but never modify it
1248 # in place, to this effectively makes a copy of it.
1249 deortho_vector_basis = vector_basis
1250 self._deortho_matrix = None
1251
1252 if orthonormalize:
1253 from mjo.eja.eja_utils import gram_schmidt
1254 if basis_is_matrices:
1255 vector_ip = lambda x,y: inner_product(_vec2mat(x), _vec2mat(y))
1256 vector_basis = gram_schmidt(vector_basis, vector_ip)
1257 else:
1258 vector_basis = gram_schmidt(vector_basis, inner_product)
1259
1260 # Normalize the "matrix" basis, too!
1261 basis = vector_basis
1262
1263 if basis_is_matrices:
1264 basis = tuple( map(_vec2mat,basis) )
1265
1266 W = V.span_of_basis( vector_basis, check=check_axioms)
1267
1268 # Now "W" is the vector space of our algebra coordinates. The
1269 # variables "X1", "X2",... refer to the entries of vectors in
1270 # W. Thus to convert back and forth between the orthonormal
1271 # coordinates and the given ones, we need to stick the original
1272 # basis in W.
1273 U = V.span_of_basis( deortho_vector_basis, check=check_axioms)
1274 self._deortho_matrix = matrix( U.coordinate_vector(q)
1275 for q in vector_basis )
1276
1277 # If the superclass constructor is going to verify the
1278 # symmetry of this table, it has better at least be
1279 # square...
1280 if check_axioms:
1281 mult_table = [ [0 for j in range(n)] for i in range(n) ]
1282 ip_table = [ [0 for j in range(n)] for i in range(n) ]
1283 else:
1284 mult_table = [ [0 for j in range(i+1)] for i in range(n) ]
1285 ip_table = [ [0 for j in range(i+1)] for i in range(n) ]
1286
1287 # Note: the Jordan and inner-products are defined in terms
1288 # of the ambient basis. It's important that their arguments
1289 # are in ambient coordinates as well.
1290 for i in range(n):
1291 for j in range(i+1):
1292 # ortho basis w.r.t. ambient coords
1293 q_i = vector_basis[i]
1294 q_j = vector_basis[j]
1295
1296 if basis_is_matrices:
1297 q_i = _vec2mat(q_i)
1298 q_j = _vec2mat(q_j)
1299
1300 elt = jordan_product(q_i, q_j)
1301 ip = inner_product(q_i, q_j)
1302
1303 if basis_is_matrices:
1304 # do another mat2vec because the multiplication
1305 # table is in terms of vectors
1306 elt = _mat2vec(elt)
1307
1308 elt = W.coordinate_vector(elt)
1309 mult_table[i][j] = elt
1310 ip_table[i][j] = ip
1311 if check_axioms:
1312 # The tables are square if we're verifying that they
1313 # are commutative.
1314 mult_table[j][i] = elt
1315 ip_table[j][i] = ip
1316
1317 if basis_is_matrices:
1318 for m in basis:
1319 m.set_immutable()
1320 else:
1321 basis = tuple( x.column() for x in basis )
1322
1323 super().__init__(field,
1324 mult_table,
1325 ip_table,
1326 prefix,
1327 category,
1328 basis, # matrix basis
1329 check_field,
1330 check_axioms)
1331
1332 @cached_method
1333 def _charpoly_coefficients(self):
1334 r"""
1335 SETUP::
1336
1337 sage: from mjo.eja.eja_algebra import (BilinearFormEJA,
1338 ....: JordanSpinEJA)
1339
1340 EXAMPLES:
1341
1342 The base ring of the resulting polynomial coefficients is what
1343 it should be, and not the rationals (unless the algebra was
1344 already over the rationals)::
1345
1346 sage: J = JordanSpinEJA(3)
1347 sage: J._charpoly_coefficients()
1348 (X1^2 - X2^2 - X3^2, -2*X1)
1349 sage: a0 = J._charpoly_coefficients()[0]
1350 sage: J.base_ring()
1351 Algebraic Real Field
1352 sage: a0.base_ring()
1353 Algebraic Real Field
1354
1355 """
1356 if self._rational_algebra is None:
1357 # There's no need to construct *another* algebra over the
1358 # rationals if this one is already over the
1359 # rationals. Likewise, if we never orthonormalized our
1360 # basis, we might as well just use the given one.
1361 superclass = super(RationalBasisEuclideanJordanAlgebra, self)
1362 return superclass._charpoly_coefficients()
1363
1364 # Do the computation over the rationals. The answer will be
1365 # the same, because all we've done is a change of basis.
1366 # Then, change back from QQ to our real base ring
1367 a = ( a_i.change_ring(self.base_ring())
1368 for a_i in self._rational_algebra._charpoly_coefficients() )
1369
1370 # Now convert the coordinate variables back to the
1371 # deorthonormalized ones.
1372 R = self.coordinate_polynomial_ring()
1373 from sage.modules.free_module_element import vector
1374 X = vector(R, R.gens())
1375 BX = self._deortho_matrix*X
1376
1377 subs_dict = { X[i]: BX[i] for i in range(len(X)) }
1378 return tuple( a_i.subs(subs_dict) for a_i in a )
1379
1380 class ConcreteEuclideanJordanAlgebra(RationalBasisEuclideanJordanAlgebra):
1381 r"""
1382 A class for the Euclidean Jordan algebras that we know by name.
1383
1384 These are the Jordan algebras whose basis, multiplication table,
1385 rank, and so on are known a priori. More to the point, they are
1386 the Euclidean Jordan algebras for which we are able to conjure up
1387 a "random instance."
1388
1389 SETUP::
1390
1391 sage: from mjo.eja.eja_algebra import ConcreteEuclideanJordanAlgebra
1392
1393 TESTS:
1394
1395 Our basis is normalized with respect to the algebra's inner
1396 product, unless we specify otherwise::
1397
1398 sage: set_random_seed()
1399 sage: J = ConcreteEuclideanJordanAlgebra.random_instance()
1400 sage: all( b.norm() == 1 for b in J.gens() )
1401 True
1402
1403 Since our basis is orthonormal with respect to the algebra's inner
1404 product, and since we know that this algebra is an EJA, any
1405 left-multiplication operator's matrix will be symmetric because
1406 natural->EJA basis representation is an isometry and within the
1407 EJA the operator is self-adjoint by the Jordan axiom::
1408
1409 sage: set_random_seed()
1410 sage: J = ConcreteEuclideanJordanAlgebra.random_instance()
1411 sage: x = J.random_element()
1412 sage: x.operator().is_self_adjoint()
1413 True
1414 """
1415
1416 @staticmethod
1417 def _max_random_instance_size():
1418 """
1419 Return an integer "size" that is an upper bound on the size of
1420 this algebra when it is used in a random test
1421 case. Unfortunately, the term "size" is ambiguous -- when
1422 dealing with `R^n` under either the Hadamard or Jordan spin
1423 product, the "size" refers to the dimension `n`. When dealing
1424 with a matrix algebra (real symmetric or complex/quaternion
1425 Hermitian), it refers to the size of the matrix, which is far
1426 less than the dimension of the underlying vector space.
1427
1428 This method must be implemented in each subclass.
1429 """
1430 raise NotImplementedError
1431
1432 @classmethod
1433 def random_instance(cls, *args, **kwargs):
1434 """
1435 Return a random instance of this type of algebra.
1436
1437 This method should be implemented in each subclass.
1438 """
1439 from sage.misc.prandom import choice
1440 eja_class = choice(cls.__subclasses__())
1441
1442 # These all bubble up to the RationalBasisEuclideanJordanAlgebra
1443 # superclass constructor, so any (kw)args valid there are also
1444 # valid here.
1445 return eja_class.random_instance(*args, **kwargs)
1446
1447
1448 class MatrixEuclideanJordanAlgebra:
1449 @staticmethod
1450 def dimension_over_reals():
1451 r"""
1452 The dimension of this matrix's base ring over the reals.
1453
1454 The reals are dimension one over themselves, obviously; that's
1455 just `\mathbb{R}^{1}`. Likewise, the complex numbers `a + bi`
1456 have dimension two. Finally, the quaternions have dimension
1457 four over the reals.
1458
1459 This is used to determine the size of the matrix returned from
1460 :meth:`real_embed`, among other things.
1461 """
1462 raise NotImplementedError
1463
1464 @classmethod
1465 def real_embed(cls,M):
1466 """
1467 Embed the matrix ``M`` into a space of real matrices.
1468
1469 The matrix ``M`` can have entries in any field at the moment:
1470 the real numbers, complex numbers, or quaternions. And although
1471 they are not a field, we can probably support octonions at some
1472 point, too. This function returns a real matrix that "acts like"
1473 the original with respect to matrix multiplication; i.e.
1474
1475 real_embed(M*N) = real_embed(M)*real_embed(N)
1476
1477 """
1478 if M.ncols() != M.nrows():
1479 raise ValueError("the matrix 'M' must be square")
1480 return M
1481
1482
1483 @classmethod
1484 def real_unembed(cls,M):
1485 """
1486 The inverse of :meth:`real_embed`.
1487 """
1488 if M.ncols() != M.nrows():
1489 raise ValueError("the matrix 'M' must be square")
1490 if not ZZ(M.nrows()).mod(cls.dimension_over_reals()).is_zero():
1491 raise ValueError("the matrix 'M' must be a real embedding")
1492 return M
1493
1494 @staticmethod
1495 def jordan_product(X,Y):
1496 return (X*Y + Y*X)/2
1497
1498 @classmethod
1499 def trace_inner_product(cls,X,Y):
1500 r"""
1501 Compute the trace inner-product of two real-embeddings.
1502
1503 SETUP::
1504
1505 sage: from mjo.eja.eja_algebra import (RealSymmetricEJA,
1506 ....: ComplexHermitianEJA,
1507 ....: QuaternionHermitianEJA)
1508
1509 EXAMPLES::
1510
1511 This gives the same answer as it would if we computed the trace
1512 from the unembedded (original) matrices::
1513
1514 sage: set_random_seed()
1515 sage: J = RealSymmetricEJA.random_instance()
1516 sage: x,y = J.random_elements(2)
1517 sage: Xe = x.to_matrix()
1518 sage: Ye = y.to_matrix()
1519 sage: X = J.real_unembed(Xe)
1520 sage: Y = J.real_unembed(Ye)
1521 sage: expected = (X*Y).trace()
1522 sage: actual = J.trace_inner_product(Xe,Ye)
1523 sage: actual == expected
1524 True
1525
1526 ::
1527
1528 sage: set_random_seed()
1529 sage: J = ComplexHermitianEJA.random_instance()
1530 sage: x,y = J.random_elements(2)
1531 sage: Xe = x.to_matrix()
1532 sage: Ye = y.to_matrix()
1533 sage: X = J.real_unembed(Xe)
1534 sage: Y = J.real_unembed(Ye)
1535 sage: expected = (X*Y).trace().real()
1536 sage: actual = J.trace_inner_product(Xe,Ye)
1537 sage: actual == expected
1538 True
1539
1540 ::
1541
1542 sage: set_random_seed()
1543 sage: J = QuaternionHermitianEJA.random_instance()
1544 sage: x,y = J.random_elements(2)
1545 sage: Xe = x.to_matrix()
1546 sage: Ye = y.to_matrix()
1547 sage: X = J.real_unembed(Xe)
1548 sage: Y = J.real_unembed(Ye)
1549 sage: expected = (X*Y).trace().coefficient_tuple()[0]
1550 sage: actual = J.trace_inner_product(Xe,Ye)
1551 sage: actual == expected
1552 True
1553
1554 """
1555 Xu = cls.real_unembed(X)
1556 Yu = cls.real_unembed(Y)
1557 tr = (Xu*Yu).trace()
1558
1559 try:
1560 # Works in QQ, AA, RDF, et cetera.
1561 return tr.real()
1562 except AttributeError:
1563 # A quaternion doesn't have a real() method, but does
1564 # have coefficient_tuple() method that returns the
1565 # coefficients of 1, i, j, and k -- in that order.
1566 return tr.coefficient_tuple()[0]
1567
1568
1569 class RealMatrixEuclideanJordanAlgebra(MatrixEuclideanJordanAlgebra):
1570 @staticmethod
1571 def dimension_over_reals():
1572 return 1
1573
1574
1575 class RealSymmetricEJA(ConcreteEuclideanJordanAlgebra,
1576 RealMatrixEuclideanJordanAlgebra):
1577 """
1578 The rank-n simple EJA consisting of real symmetric n-by-n
1579 matrices, the usual symmetric Jordan product, and the trace inner
1580 product. It has dimension `(n^2 + n)/2` over the reals.
1581
1582 SETUP::
1583
1584 sage: from mjo.eja.eja_algebra import RealSymmetricEJA
1585
1586 EXAMPLES::
1587
1588 sage: J = RealSymmetricEJA(2)
1589 sage: e0, e1, e2 = J.gens()
1590 sage: e0*e0
1591 e0
1592 sage: e1*e1
1593 1/2*e0 + 1/2*e2
1594 sage: e2*e2
1595 e2
1596
1597 In theory, our "field" can be any subfield of the reals::
1598
1599 sage: RealSymmetricEJA(2, field=RDF)
1600 Euclidean Jordan algebra of dimension 3 over Real Double Field
1601 sage: RealSymmetricEJA(2, field=RR)
1602 Euclidean Jordan algebra of dimension 3 over Real Field with
1603 53 bits of precision
1604
1605 TESTS:
1606
1607 The dimension of this algebra is `(n^2 + n) / 2`::
1608
1609 sage: set_random_seed()
1610 sage: n_max = RealSymmetricEJA._max_random_instance_size()
1611 sage: n = ZZ.random_element(1, n_max)
1612 sage: J = RealSymmetricEJA(n)
1613 sage: J.dimension() == (n^2 + n)/2
1614 True
1615
1616 The Jordan multiplication is what we think it is::
1617
1618 sage: set_random_seed()
1619 sage: J = RealSymmetricEJA.random_instance()
1620 sage: x,y = J.random_elements(2)
1621 sage: actual = (x*y).to_matrix()
1622 sage: X = x.to_matrix()
1623 sage: Y = y.to_matrix()
1624 sage: expected = (X*Y + Y*X)/2
1625 sage: actual == expected
1626 True
1627 sage: J(expected) == x*y
1628 True
1629
1630 We can change the generator prefix::
1631
1632 sage: RealSymmetricEJA(3, prefix='q').gens()
1633 (q0, q1, q2, q3, q4, q5)
1634
1635 We can construct the (trivial) algebra of rank zero::
1636
1637 sage: RealSymmetricEJA(0)
1638 Euclidean Jordan algebra of dimension 0 over Algebraic Real Field
1639
1640 """
1641 @classmethod
1642 def _denormalized_basis(cls, n):
1643 """
1644 Return a basis for the space of real symmetric n-by-n matrices.
1645
1646 SETUP::
1647
1648 sage: from mjo.eja.eja_algebra import RealSymmetricEJA
1649
1650 TESTS::
1651
1652 sage: set_random_seed()
1653 sage: n = ZZ.random_element(1,5)
1654 sage: B = RealSymmetricEJA._denormalized_basis(n)
1655 sage: all( M.is_symmetric() for M in B)
1656 True
1657
1658 """
1659 # The basis of symmetric matrices, as matrices, in their R^(n-by-n)
1660 # coordinates.
1661 S = []
1662 for i in range(n):
1663 for j in range(i+1):
1664 Eij = matrix(ZZ, n, lambda k,l: k==i and l==j)
1665 if i == j:
1666 Sij = Eij
1667 else:
1668 Sij = Eij + Eij.transpose()
1669 S.append(Sij)
1670 return tuple(S)
1671
1672
1673 @staticmethod
1674 def _max_random_instance_size():
1675 return 4 # Dimension 10
1676
1677 @classmethod
1678 def random_instance(cls, **kwargs):
1679 """
1680 Return a random instance of this type of algebra.
1681 """
1682 n = ZZ.random_element(cls._max_random_instance_size() + 1)
1683 return cls(n, **kwargs)
1684
1685 def __init__(self, n, **kwargs):
1686 # We know this is a valid EJA, but will double-check
1687 # if the user passes check_axioms=True.
1688 if "check_axioms" not in kwargs: kwargs["check_axioms"] = False
1689
1690 super(RealSymmetricEJA, self).__init__(self._denormalized_basis(n),
1691 self.jordan_product,
1692 self.trace_inner_product,
1693 **kwargs)
1694
1695 # TODO: this could be factored out somehow, but is left here
1696 # because the MatrixEuclideanJordanAlgebra is not presently
1697 # a subclass of the FDEJA class that defines rank() and one().
1698 self.rank.set_cache(n)
1699 idV = matrix.identity(ZZ, self.dimension_over_reals()*n)
1700 self.one.set_cache(self(idV))
1701
1702
1703
1704 class ComplexMatrixEuclideanJordanAlgebra(MatrixEuclideanJordanAlgebra):
1705 @staticmethod
1706 def dimension_over_reals():
1707 return 2
1708
1709 @classmethod
1710 def real_embed(cls,M):
1711 """
1712 Embed the n-by-n complex matrix ``M`` into the space of real
1713 matrices of size 2n-by-2n via the map the sends each entry `z = a +
1714 bi` to the block matrix ``[[a,b],[-b,a]]``.
1715
1716 SETUP::
1717
1718 sage: from mjo.eja.eja_algebra import \
1719 ....: ComplexMatrixEuclideanJordanAlgebra
1720
1721 EXAMPLES::
1722
1723 sage: F = QuadraticField(-1, 'I')
1724 sage: x1 = F(4 - 2*i)
1725 sage: x2 = F(1 + 2*i)
1726 sage: x3 = F(-i)
1727 sage: x4 = F(6)
1728 sage: M = matrix(F,2,[[x1,x2],[x3,x4]])
1729 sage: ComplexMatrixEuclideanJordanAlgebra.real_embed(M)
1730 [ 4 -2| 1 2]
1731 [ 2 4|-2 1]
1732 [-----+-----]
1733 [ 0 -1| 6 0]
1734 [ 1 0| 0 6]
1735
1736 TESTS:
1737
1738 Embedding is a homomorphism (isomorphism, in fact)::
1739
1740 sage: set_random_seed()
1741 sage: n = ZZ.random_element(3)
1742 sage: F = QuadraticField(-1, 'I')
1743 sage: X = random_matrix(F, n)
1744 sage: Y = random_matrix(F, n)
1745 sage: Xe = ComplexMatrixEuclideanJordanAlgebra.real_embed(X)
1746 sage: Ye = ComplexMatrixEuclideanJordanAlgebra.real_embed(Y)
1747 sage: XYe = ComplexMatrixEuclideanJordanAlgebra.real_embed(X*Y)
1748 sage: Xe*Ye == XYe
1749 True
1750
1751 """
1752 super(ComplexMatrixEuclideanJordanAlgebra,cls).real_embed(M)
1753 n = M.nrows()
1754
1755 # We don't need any adjoined elements...
1756 field = M.base_ring().base_ring()
1757
1758 blocks = []
1759 for z in M.list():
1760 a = z.list()[0] # real part, I guess
1761 b = z.list()[1] # imag part, I guess
1762 blocks.append(matrix(field, 2, [[a,b],[-b,a]]))
1763
1764 return matrix.block(field, n, blocks)
1765
1766
1767 @classmethod
1768 def real_unembed(cls,M):
1769 """
1770 The inverse of _embed_complex_matrix().
1771
1772 SETUP::
1773
1774 sage: from mjo.eja.eja_algebra import \
1775 ....: ComplexMatrixEuclideanJordanAlgebra
1776
1777 EXAMPLES::
1778
1779 sage: A = matrix(QQ,[ [ 1, 2, 3, 4],
1780 ....: [-2, 1, -4, 3],
1781 ....: [ 9, 10, 11, 12],
1782 ....: [-10, 9, -12, 11] ])
1783 sage: ComplexMatrixEuclideanJordanAlgebra.real_unembed(A)
1784 [ 2*I + 1 4*I + 3]
1785 [ 10*I + 9 12*I + 11]
1786
1787 TESTS:
1788
1789 Unembedding is the inverse of embedding::
1790
1791 sage: set_random_seed()
1792 sage: F = QuadraticField(-1, 'I')
1793 sage: M = random_matrix(F, 3)
1794 sage: Me = ComplexMatrixEuclideanJordanAlgebra.real_embed(M)
1795 sage: ComplexMatrixEuclideanJordanAlgebra.real_unembed(Me) == M
1796 True
1797
1798 """
1799 super(ComplexMatrixEuclideanJordanAlgebra,cls).real_unembed(M)
1800 n = ZZ(M.nrows())
1801 d = cls.dimension_over_reals()
1802
1803 # If "M" was normalized, its base ring might have roots
1804 # adjoined and they can stick around after unembedding.
1805 field = M.base_ring()
1806 R = PolynomialRing(field, 'z')
1807 z = R.gen()
1808
1809 # Sage doesn't know how to adjoin the complex "i" (the root of
1810 # x^2 + 1) to a field in a general way. Here, we just enumerate
1811 # all of the cases that I have cared to support so far.
1812 if field is AA:
1813 # Sage doesn't know how to embed AA into QQbar, i.e. how
1814 # to adjoin sqrt(-1) to AA.
1815 F = QQbar
1816 elif not field.is_exact():
1817 # RDF or RR
1818 F = field.complex_field()
1819 else:
1820 # Works for QQ and... maybe some other fields.
1821 F = field.extension(z**2 + 1, 'I', embedding=CLF(-1).sqrt())
1822 i = F.gen()
1823
1824 # Go top-left to bottom-right (reading order), converting every
1825 # 2-by-2 block we see to a single complex element.
1826 elements = []
1827 for k in range(n/d):
1828 for j in range(n/d):
1829 submat = M[d*k:d*k+d,d*j:d*j+d]
1830 if submat[0,0] != submat[1,1]:
1831 raise ValueError('bad on-diagonal submatrix')
1832 if submat[0,1] != -submat[1,0]:
1833 raise ValueError('bad off-diagonal submatrix')
1834 z = submat[0,0] + submat[0,1]*i
1835 elements.append(z)
1836
1837 return matrix(F, n/d, elements)
1838
1839
1840 class ComplexHermitianEJA(ConcreteEuclideanJordanAlgebra,
1841 ComplexMatrixEuclideanJordanAlgebra):
1842 """
1843 The rank-n simple EJA consisting of complex Hermitian n-by-n
1844 matrices over the real numbers, the usual symmetric Jordan product,
1845 and the real-part-of-trace inner product. It has dimension `n^2` over
1846 the reals.
1847
1848 SETUP::
1849
1850 sage: from mjo.eja.eja_algebra import ComplexHermitianEJA
1851
1852 EXAMPLES:
1853
1854 In theory, our "field" can be any subfield of the reals::
1855
1856 sage: ComplexHermitianEJA(2, field=RDF)
1857 Euclidean Jordan algebra of dimension 4 over Real Double Field
1858 sage: ComplexHermitianEJA(2, field=RR)
1859 Euclidean Jordan algebra of dimension 4 over Real Field with
1860 53 bits of precision
1861
1862 TESTS:
1863
1864 The dimension of this algebra is `n^2`::
1865
1866 sage: set_random_seed()
1867 sage: n_max = ComplexHermitianEJA._max_random_instance_size()
1868 sage: n = ZZ.random_element(1, n_max)
1869 sage: J = ComplexHermitianEJA(n)
1870 sage: J.dimension() == n^2
1871 True
1872
1873 The Jordan multiplication is what we think it is::
1874
1875 sage: set_random_seed()
1876 sage: J = ComplexHermitianEJA.random_instance()
1877 sage: x,y = J.random_elements(2)
1878 sage: actual = (x*y).to_matrix()
1879 sage: X = x.to_matrix()
1880 sage: Y = y.to_matrix()
1881 sage: expected = (X*Y + Y*X)/2
1882 sage: actual == expected
1883 True
1884 sage: J(expected) == x*y
1885 True
1886
1887 We can change the generator prefix::
1888
1889 sage: ComplexHermitianEJA(2, prefix='z').gens()
1890 (z0, z1, z2, z3)
1891
1892 We can construct the (trivial) algebra of rank zero::
1893
1894 sage: ComplexHermitianEJA(0)
1895 Euclidean Jordan algebra of dimension 0 over Algebraic Real Field
1896
1897 """
1898
1899 @classmethod
1900 def _denormalized_basis(cls, n):
1901 """
1902 Returns a basis for the space of complex Hermitian n-by-n matrices.
1903
1904 Why do we embed these? Basically, because all of numerical linear
1905 algebra assumes that you're working with vectors consisting of `n`
1906 entries from a field and scalars from the same field. There's no way
1907 to tell SageMath that (for example) the vectors contain complex
1908 numbers, while the scalar field is real.
1909
1910 SETUP::
1911
1912 sage: from mjo.eja.eja_algebra import ComplexHermitianEJA
1913
1914 TESTS::
1915
1916 sage: set_random_seed()
1917 sage: n = ZZ.random_element(1,5)
1918 sage: field = QuadraticField(2, 'sqrt2')
1919 sage: B = ComplexHermitianEJA._denormalized_basis(n)
1920 sage: all( M.is_symmetric() for M in B)
1921 True
1922
1923 """
1924 field = ZZ
1925 R = PolynomialRing(field, 'z')
1926 z = R.gen()
1927 F = field.extension(z**2 + 1, 'I')
1928 I = F.gen(1)
1929
1930 # This is like the symmetric case, but we need to be careful:
1931 #
1932 # * We want conjugate-symmetry, not just symmetry.
1933 # * The diagonal will (as a result) be real.
1934 #
1935 S = []
1936 for i in range(n):
1937 for j in range(i+1):
1938 Eij = matrix(F, n, lambda k,l: k==i and l==j)
1939 if i == j:
1940 Sij = cls.real_embed(Eij)
1941 S.append(Sij)
1942 else:
1943 # The second one has a minus because it's conjugated.
1944 Sij_real = cls.real_embed(Eij + Eij.transpose())
1945 S.append(Sij_real)
1946 Sij_imag = cls.real_embed(I*Eij - I*Eij.transpose())
1947 S.append(Sij_imag)
1948
1949 # Since we embedded these, we can drop back to the "field" that we
1950 # started with instead of the complex extension "F".
1951 return tuple( s.change_ring(field) for s in S )
1952
1953
1954 def __init__(self, n, **kwargs):
1955 # We know this is a valid EJA, but will double-check
1956 # if the user passes check_axioms=True.
1957 if "check_axioms" not in kwargs: kwargs["check_axioms"] = False
1958
1959 super(ComplexHermitianEJA, self).__init__(self._denormalized_basis(n),
1960 self.jordan_product,
1961 self.trace_inner_product,
1962 **kwargs)
1963 # TODO: this could be factored out somehow, but is left here
1964 # because the MatrixEuclideanJordanAlgebra is not presently
1965 # a subclass of the FDEJA class that defines rank() and one().
1966 self.rank.set_cache(n)
1967 idV = matrix.identity(ZZ, self.dimension_over_reals()*n)
1968 self.one.set_cache(self(idV))
1969
1970 @staticmethod
1971 def _max_random_instance_size():
1972 return 3 # Dimension 9
1973
1974 @classmethod
1975 def random_instance(cls, **kwargs):
1976 """
1977 Return a random instance of this type of algebra.
1978 """
1979 n = ZZ.random_element(cls._max_random_instance_size() + 1)
1980 return cls(n, **kwargs)
1981
1982 class QuaternionMatrixEuclideanJordanAlgebra(MatrixEuclideanJordanAlgebra):
1983 @staticmethod
1984 def dimension_over_reals():
1985 return 4
1986
1987 @classmethod
1988 def real_embed(cls,M):
1989 """
1990 Embed the n-by-n quaternion matrix ``M`` into the space of real
1991 matrices of size 4n-by-4n by first sending each quaternion entry `z
1992 = a + bi + cj + dk` to the block-complex matrix ``[[a + bi,
1993 c+di],[-c + di, a-bi]]`, and then embedding those into a real
1994 matrix.
1995
1996 SETUP::
1997
1998 sage: from mjo.eja.eja_algebra import \
1999 ....: QuaternionMatrixEuclideanJordanAlgebra
2000
2001 EXAMPLES::
2002
2003 sage: Q = QuaternionAlgebra(QQ,-1,-1)
2004 sage: i,j,k = Q.gens()
2005 sage: x = 1 + 2*i + 3*j + 4*k
2006 sage: M = matrix(Q, 1, [[x]])
2007 sage: QuaternionMatrixEuclideanJordanAlgebra.real_embed(M)
2008 [ 1 2 3 4]
2009 [-2 1 -4 3]
2010 [-3 4 1 -2]
2011 [-4 -3 2 1]
2012
2013 Embedding is a homomorphism (isomorphism, in fact)::
2014
2015 sage: set_random_seed()
2016 sage: n = ZZ.random_element(2)
2017 sage: Q = QuaternionAlgebra(QQ,-1,-1)
2018 sage: X = random_matrix(Q, n)
2019 sage: Y = random_matrix(Q, n)
2020 sage: Xe = QuaternionMatrixEuclideanJordanAlgebra.real_embed(X)
2021 sage: Ye = QuaternionMatrixEuclideanJordanAlgebra.real_embed(Y)
2022 sage: XYe = QuaternionMatrixEuclideanJordanAlgebra.real_embed(X*Y)
2023 sage: Xe*Ye == XYe
2024 True
2025
2026 """
2027 super(QuaternionMatrixEuclideanJordanAlgebra,cls).real_embed(M)
2028 quaternions = M.base_ring()
2029 n = M.nrows()
2030
2031 F = QuadraticField(-1, 'I')
2032 i = F.gen()
2033
2034 blocks = []
2035 for z in M.list():
2036 t = z.coefficient_tuple()
2037 a = t[0]
2038 b = t[1]
2039 c = t[2]
2040 d = t[3]
2041 cplxM = matrix(F, 2, [[ a + b*i, c + d*i],
2042 [-c + d*i, a - b*i]])
2043 realM = ComplexMatrixEuclideanJordanAlgebra.real_embed(cplxM)
2044 blocks.append(realM)
2045
2046 # We should have real entries by now, so use the realest field
2047 # we've got for the return value.
2048 return matrix.block(quaternions.base_ring(), n, blocks)
2049
2050
2051
2052 @classmethod
2053 def real_unembed(cls,M):
2054 """
2055 The inverse of _embed_quaternion_matrix().
2056
2057 SETUP::
2058
2059 sage: from mjo.eja.eja_algebra import \
2060 ....: QuaternionMatrixEuclideanJordanAlgebra
2061
2062 EXAMPLES::
2063
2064 sage: M = matrix(QQ, [[ 1, 2, 3, 4],
2065 ....: [-2, 1, -4, 3],
2066 ....: [-3, 4, 1, -2],
2067 ....: [-4, -3, 2, 1]])
2068 sage: QuaternionMatrixEuclideanJordanAlgebra.real_unembed(M)
2069 [1 + 2*i + 3*j + 4*k]
2070
2071 TESTS:
2072
2073 Unembedding is the inverse of embedding::
2074
2075 sage: set_random_seed()
2076 sage: Q = QuaternionAlgebra(QQ, -1, -1)
2077 sage: M = random_matrix(Q, 3)
2078 sage: Me = QuaternionMatrixEuclideanJordanAlgebra.real_embed(M)
2079 sage: QuaternionMatrixEuclideanJordanAlgebra.real_unembed(Me) == M
2080 True
2081
2082 """
2083 super(QuaternionMatrixEuclideanJordanAlgebra,cls).real_unembed(M)
2084 n = ZZ(M.nrows())
2085 d = cls.dimension_over_reals()
2086
2087 # Use the base ring of the matrix to ensure that its entries can be
2088 # multiplied by elements of the quaternion algebra.
2089 field = M.base_ring()
2090 Q = QuaternionAlgebra(field,-1,-1)
2091 i,j,k = Q.gens()
2092
2093 # Go top-left to bottom-right (reading order), converting every
2094 # 4-by-4 block we see to a 2-by-2 complex block, to a 1-by-1
2095 # quaternion block.
2096 elements = []
2097 for l in range(n/d):
2098 for m in range(n/d):
2099 submat = ComplexMatrixEuclideanJordanAlgebra.real_unembed(
2100 M[d*l:d*l+d,d*m:d*m+d] )
2101 if submat[0,0] != submat[1,1].conjugate():
2102 raise ValueError('bad on-diagonal submatrix')
2103 if submat[0,1] != -submat[1,0].conjugate():
2104 raise ValueError('bad off-diagonal submatrix')
2105 z = submat[0,0].real()
2106 z += submat[0,0].imag()*i
2107 z += submat[0,1].real()*j
2108 z += submat[0,1].imag()*k
2109 elements.append(z)
2110
2111 return matrix(Q, n/d, elements)
2112
2113
2114 class QuaternionHermitianEJA(ConcreteEuclideanJordanAlgebra,
2115 QuaternionMatrixEuclideanJordanAlgebra):
2116 r"""
2117 The rank-n simple EJA consisting of self-adjoint n-by-n quaternion
2118 matrices, the usual symmetric Jordan product, and the
2119 real-part-of-trace inner product. It has dimension `2n^2 - n` over
2120 the reals.
2121
2122 SETUP::
2123
2124 sage: from mjo.eja.eja_algebra import QuaternionHermitianEJA
2125
2126 EXAMPLES:
2127
2128 In theory, our "field" can be any subfield of the reals::
2129
2130 sage: QuaternionHermitianEJA(2, field=RDF)
2131 Euclidean Jordan algebra of dimension 6 over Real Double Field
2132 sage: QuaternionHermitianEJA(2, field=RR)
2133 Euclidean Jordan algebra of dimension 6 over Real Field with
2134 53 bits of precision
2135
2136 TESTS:
2137
2138 The dimension of this algebra is `2*n^2 - n`::
2139
2140 sage: set_random_seed()
2141 sage: n_max = QuaternionHermitianEJA._max_random_instance_size()
2142 sage: n = ZZ.random_element(1, n_max)
2143 sage: J = QuaternionHermitianEJA(n)
2144 sage: J.dimension() == 2*(n^2) - n
2145 True
2146
2147 The Jordan multiplication is what we think it is::
2148
2149 sage: set_random_seed()
2150 sage: J = QuaternionHermitianEJA.random_instance()
2151 sage: x,y = J.random_elements(2)
2152 sage: actual = (x*y).to_matrix()
2153 sage: X = x.to_matrix()
2154 sage: Y = y.to_matrix()
2155 sage: expected = (X*Y + Y*X)/2
2156 sage: actual == expected
2157 True
2158 sage: J(expected) == x*y
2159 True
2160
2161 We can change the generator prefix::
2162
2163 sage: QuaternionHermitianEJA(2, prefix='a').gens()
2164 (a0, a1, a2, a3, a4, a5)
2165
2166 We can construct the (trivial) algebra of rank zero::
2167
2168 sage: QuaternionHermitianEJA(0)
2169 Euclidean Jordan algebra of dimension 0 over Algebraic Real Field
2170
2171 """
2172 @classmethod
2173 def _denormalized_basis(cls, n):
2174 """
2175 Returns a basis for the space of quaternion Hermitian n-by-n matrices.
2176
2177 Why do we embed these? Basically, because all of numerical
2178 linear algebra assumes that you're working with vectors consisting
2179 of `n` entries from a field and scalars from the same field. There's
2180 no way to tell SageMath that (for example) the vectors contain
2181 complex numbers, while the scalar field is real.
2182
2183 SETUP::
2184
2185 sage: from mjo.eja.eja_algebra import QuaternionHermitianEJA
2186
2187 TESTS::
2188
2189 sage: set_random_seed()
2190 sage: n = ZZ.random_element(1,5)
2191 sage: B = QuaternionHermitianEJA._denormalized_basis(n)
2192 sage: all( M.is_symmetric() for M in B )
2193 True
2194
2195 """
2196 field = ZZ
2197 Q = QuaternionAlgebra(QQ,-1,-1)
2198 I,J,K = Q.gens()
2199
2200 # This is like the symmetric case, but we need to be careful:
2201 #
2202 # * We want conjugate-symmetry, not just symmetry.
2203 # * The diagonal will (as a result) be real.
2204 #
2205 S = []
2206 for i in range(n):
2207 for j in range(i+1):
2208 Eij = matrix(Q, n, lambda k,l: k==i and l==j)
2209 if i == j:
2210 Sij = cls.real_embed(Eij)
2211 S.append(Sij)
2212 else:
2213 # The second, third, and fourth ones have a minus
2214 # because they're conjugated.
2215 Sij_real = cls.real_embed(Eij + Eij.transpose())
2216 S.append(Sij_real)
2217 Sij_I = cls.real_embed(I*Eij - I*Eij.transpose())
2218 S.append(Sij_I)
2219 Sij_J = cls.real_embed(J*Eij - J*Eij.transpose())
2220 S.append(Sij_J)
2221 Sij_K = cls.real_embed(K*Eij - K*Eij.transpose())
2222 S.append(Sij_K)
2223
2224 # Since we embedded these, we can drop back to the "field" that we
2225 # started with instead of the quaternion algebra "Q".
2226 return tuple( s.change_ring(field) for s in S )
2227
2228
2229 def __init__(self, n, **kwargs):
2230 # We know this is a valid EJA, but will double-check
2231 # if the user passes check_axioms=True.
2232 if "check_axioms" not in kwargs: kwargs["check_axioms"] = False
2233
2234 super(QuaternionHermitianEJA, self).__init__(self._denormalized_basis(n),
2235 self.jordan_product,
2236 self.trace_inner_product,
2237 **kwargs)
2238 # TODO: this could be factored out somehow, but is left here
2239 # because the MatrixEuclideanJordanAlgebra is not presently
2240 # a subclass of the FDEJA class that defines rank() and one().
2241 self.rank.set_cache(n)
2242 idV = matrix.identity(ZZ, self.dimension_over_reals()*n)
2243 self.one.set_cache(self(idV))
2244
2245
2246 @staticmethod
2247 def _max_random_instance_size():
2248 r"""
2249 The maximum rank of a random QuaternionHermitianEJA.
2250 """
2251 return 2 # Dimension 6
2252
2253 @classmethod
2254 def random_instance(cls, **kwargs):
2255 """
2256 Return a random instance of this type of algebra.
2257 """
2258 n = ZZ.random_element(cls._max_random_instance_size() + 1)
2259 return cls(n, **kwargs)
2260
2261
2262 class HadamardEJA(ConcreteEuclideanJordanAlgebra):
2263 """
2264 Return the Euclidean Jordan Algebra corresponding to the set
2265 `R^n` under the Hadamard product.
2266
2267 Note: this is nothing more than the Cartesian product of ``n``
2268 copies of the spin algebra. Once Cartesian product algebras
2269 are implemented, this can go.
2270
2271 SETUP::
2272
2273 sage: from mjo.eja.eja_algebra import HadamardEJA
2274
2275 EXAMPLES:
2276
2277 This multiplication table can be verified by hand::
2278
2279 sage: J = HadamardEJA(3)
2280 sage: e0,e1,e2 = J.gens()
2281 sage: e0*e0
2282 e0
2283 sage: e0*e1
2284 0
2285 sage: e0*e2
2286 0
2287 sage: e1*e1
2288 e1
2289 sage: e1*e2
2290 0
2291 sage: e2*e2
2292 e2
2293
2294 TESTS:
2295
2296 We can change the generator prefix::
2297
2298 sage: HadamardEJA(3, prefix='r').gens()
2299 (r0, r1, r2)
2300
2301 """
2302 def __init__(self, n, **kwargs):
2303 def jordan_product(x,y):
2304 P = x.parent()
2305 return P(tuple( xi*yi for (xi,yi) in zip(x,y) ))
2306 def inner_product(x,y):
2307 return x.inner_product(y)
2308
2309 # New defaults for keyword arguments. Don't orthonormalize
2310 # because our basis is already orthonormal with respect to our
2311 # inner-product. Don't check the axioms, because we know this
2312 # is a valid EJA... but do double-check if the user passes
2313 # check_axioms=True. Note: we DON'T override the "check_field"
2314 # default here, because the user can pass in a field!
2315 if "orthonormalize" not in kwargs: kwargs["orthonormalize"] = False
2316 if "check_axioms" not in kwargs: kwargs["check_axioms"] = False
2317
2318
2319 standard_basis = FreeModule(ZZ, n).basis()
2320 super(HadamardEJA, self).__init__(standard_basis,
2321 jordan_product,
2322 inner_product,
2323 **kwargs)
2324 self.rank.set_cache(n)
2325
2326 if n == 0:
2327 self.one.set_cache( self.zero() )
2328 else:
2329 self.one.set_cache( sum(self.gens()) )
2330
2331 @staticmethod
2332 def _max_random_instance_size():
2333 r"""
2334 The maximum dimension of a random HadamardEJA.
2335 """
2336 return 5
2337
2338 @classmethod
2339 def random_instance(cls, **kwargs):
2340 """
2341 Return a random instance of this type of algebra.
2342 """
2343 n = ZZ.random_element(cls._max_random_instance_size() + 1)
2344 return cls(n, **kwargs)
2345
2346
2347 class BilinearFormEJA(ConcreteEuclideanJordanAlgebra):
2348 r"""
2349 The rank-2 simple EJA consisting of real vectors ``x=(x0, x_bar)``
2350 with the half-trace inner product and jordan product ``x*y =
2351 (<Bx,y>,y_bar>, x0*y_bar + y0*x_bar)`` where `B = 1 \times B22` is
2352 a symmetric positive-definite "bilinear form" matrix. Its
2353 dimension is the size of `B`, and it has rank two in dimensions
2354 larger than two. It reduces to the ``JordanSpinEJA`` when `B` is
2355 the identity matrix of order ``n``.
2356
2357 We insist that the one-by-one upper-left identity block of `B` be
2358 passed in as well so that we can be passed a matrix of size zero
2359 to construct a trivial algebra.
2360
2361 SETUP::
2362
2363 sage: from mjo.eja.eja_algebra import (BilinearFormEJA,
2364 ....: JordanSpinEJA)
2365
2366 EXAMPLES:
2367
2368 When no bilinear form is specified, the identity matrix is used,
2369 and the resulting algebra is the Jordan spin algebra::
2370
2371 sage: B = matrix.identity(AA,3)
2372 sage: J0 = BilinearFormEJA(B)
2373 sage: J1 = JordanSpinEJA(3)
2374 sage: J0.multiplication_table() == J0.multiplication_table()
2375 True
2376
2377 An error is raised if the matrix `B` does not correspond to a
2378 positive-definite bilinear form::
2379
2380 sage: B = matrix.random(QQ,2,3)
2381 sage: J = BilinearFormEJA(B)
2382 Traceback (most recent call last):
2383 ...
2384 ValueError: bilinear form is not positive-definite
2385 sage: B = matrix.zero(QQ,3)
2386 sage: J = BilinearFormEJA(B)
2387 Traceback (most recent call last):
2388 ...
2389 ValueError: bilinear form is not positive-definite
2390
2391 TESTS:
2392
2393 We can create a zero-dimensional algebra::
2394
2395 sage: B = matrix.identity(AA,0)
2396 sage: J = BilinearFormEJA(B)
2397 sage: J.basis()
2398 Finite family {}
2399
2400 We can check the multiplication condition given in the Jordan, von
2401 Neumann, and Wigner paper (and also discussed on my "On the
2402 symmetry..." paper). Note that this relies heavily on the standard
2403 choice of basis, as does anything utilizing the bilinear form
2404 matrix. We opt not to orthonormalize the basis, because if we
2405 did, we would have to normalize the `s_{i}` in a similar manner::
2406
2407 sage: set_random_seed()
2408 sage: n = ZZ.random_element(5)
2409 sage: M = matrix.random(QQ, max(0,n-1), algorithm='unimodular')
2410 sage: B11 = matrix.identity(QQ,1)
2411 sage: B22 = M.transpose()*M
2412 sage: B = block_matrix(2,2,[ [B11,0 ],
2413 ....: [0, B22 ] ])
2414 sage: J = BilinearFormEJA(B, orthonormalize=False)
2415 sage: eis = VectorSpace(M.base_ring(), M.ncols()).basis()
2416 sage: V = J.vector_space()
2417 sage: sis = [ J( V([0] + (M.inverse()*ei).list()).column() )
2418 ....: for ei in eis ]
2419 sage: actual = [ sis[i]*sis[j]
2420 ....: for i in range(n-1)
2421 ....: for j in range(n-1) ]
2422 sage: expected = [ J.one() if i == j else J.zero()
2423 ....: for i in range(n-1)
2424 ....: for j in range(n-1) ]
2425 sage: actual == expected
2426 True
2427 """
2428 def __init__(self, B, **kwargs):
2429 if not B.is_positive_definite():
2430 raise ValueError("bilinear form is not positive-definite")
2431
2432 def inner_product(x,y):
2433 return (B*x).inner_product(y)
2434
2435 def jordan_product(x,y):
2436 P = x.parent()
2437 x0 = x[0]
2438 xbar = x[1:]
2439 y0 = y[0]
2440 ybar = y[1:]
2441 z0 = inner_product(x,y)
2442 zbar = y0*xbar + x0*ybar
2443 return P((z0,) + tuple(zbar))
2444
2445 # We know this is a valid EJA, but will double-check
2446 # if the user passes check_axioms=True.
2447 if "check_axioms" not in kwargs: kwargs["check_axioms"] = False
2448
2449 n = B.nrows()
2450 standard_basis = FreeModule(ZZ, n).basis()
2451 super(BilinearFormEJA, self).__init__(standard_basis,
2452 jordan_product,
2453 inner_product,
2454 **kwargs)
2455
2456 # The rank of this algebra is two, unless we're in a
2457 # one-dimensional ambient space (because the rank is bounded
2458 # by the ambient dimension).
2459 self.rank.set_cache(min(n,2))
2460
2461 if n == 0:
2462 self.one.set_cache( self.zero() )
2463 else:
2464 self.one.set_cache( self.monomial(0) )
2465
2466 @staticmethod
2467 def _max_random_instance_size():
2468 r"""
2469 The maximum dimension of a random BilinearFormEJA.
2470 """
2471 return 5
2472
2473 @classmethod
2474 def random_instance(cls, **kwargs):
2475 """
2476 Return a random instance of this algebra.
2477 """
2478 n = ZZ.random_element(cls._max_random_instance_size() + 1)
2479 if n.is_zero():
2480 B = matrix.identity(ZZ, n)
2481 return cls(B, **kwargs)
2482
2483 B11 = matrix.identity(ZZ, 1)
2484 M = matrix.random(ZZ, n-1)
2485 I = matrix.identity(ZZ, n-1)
2486 alpha = ZZ.zero()
2487 while alpha.is_zero():
2488 alpha = ZZ.random_element().abs()
2489 B22 = M.transpose()*M + alpha*I
2490
2491 from sage.matrix.special import block_matrix
2492 B = block_matrix(2,2, [ [B11, ZZ(0) ],
2493 [ZZ(0), B22 ] ])
2494
2495 return cls(B, **kwargs)
2496
2497
2498 class JordanSpinEJA(BilinearFormEJA):
2499 """
2500 The rank-2 simple EJA consisting of real vectors ``x=(x0, x_bar)``
2501 with the usual inner product and jordan product ``x*y =
2502 (<x,y>, x0*y_bar + y0*x_bar)``. It has dimension `n` over
2503 the reals.
2504
2505 SETUP::
2506
2507 sage: from mjo.eja.eja_algebra import JordanSpinEJA
2508
2509 EXAMPLES:
2510
2511 This multiplication table can be verified by hand::
2512
2513 sage: J = JordanSpinEJA(4)
2514 sage: e0,e1,e2,e3 = J.gens()
2515 sage: e0*e0
2516 e0
2517 sage: e0*e1
2518 e1
2519 sage: e0*e2
2520 e2
2521 sage: e0*e3
2522 e3
2523 sage: e1*e2
2524 0
2525 sage: e1*e3
2526 0
2527 sage: e2*e3
2528 0
2529
2530 We can change the generator prefix::
2531
2532 sage: JordanSpinEJA(2, prefix='B').gens()
2533 (B0, B1)
2534
2535 TESTS:
2536
2537 Ensure that we have the usual inner product on `R^n`::
2538
2539 sage: set_random_seed()
2540 sage: J = JordanSpinEJA.random_instance()
2541 sage: x,y = J.random_elements(2)
2542 sage: actual = x.inner_product(y)
2543 sage: expected = x.to_vector().inner_product(y.to_vector())
2544 sage: actual == expected
2545 True
2546
2547 """
2548 def __init__(self, n, **kwargs):
2549 # This is a special case of the BilinearFormEJA with the
2550 # identity matrix as its bilinear form.
2551 B = matrix.identity(ZZ, n)
2552
2553 # Don't orthonormalize because our basis is already
2554 # orthonormal with respect to our inner-product.
2555 if "orthonormalize" not in kwargs: kwargs["orthonormalize"] = False
2556
2557 # But also don't pass check_field=False here, because the user
2558 # can pass in a field!
2559 super(JordanSpinEJA, self).__init__(B, **kwargs)
2560
2561 @staticmethod
2562 def _max_random_instance_size():
2563 r"""
2564 The maximum dimension of a random JordanSpinEJA.
2565 """
2566 return 5
2567
2568 @classmethod
2569 def random_instance(cls, **kwargs):
2570 """
2571 Return a random instance of this type of algebra.
2572
2573 Needed here to override the implementation for ``BilinearFormEJA``.
2574 """
2575 n = ZZ.random_element(cls._max_random_instance_size() + 1)
2576 return cls(n, **kwargs)
2577
2578
2579 class TrivialEJA(ConcreteEuclideanJordanAlgebra):
2580 """
2581 The trivial Euclidean Jordan algebra consisting of only a zero element.
2582
2583 SETUP::
2584
2585 sage: from mjo.eja.eja_algebra import TrivialEJA
2586
2587 EXAMPLES::
2588
2589 sage: J = TrivialEJA()
2590 sage: J.dimension()
2591 0
2592 sage: J.zero()
2593 0
2594 sage: J.one()
2595 0
2596 sage: 7*J.one()*12*J.one()
2597 0
2598 sage: J.one().inner_product(J.one())
2599 0
2600 sage: J.one().norm()
2601 0
2602 sage: J.one().subalgebra_generated_by()
2603 Euclidean Jordan algebra of dimension 0 over Algebraic Real Field
2604 sage: J.rank()
2605 0
2606
2607 """
2608 def __init__(self, **kwargs):
2609 jordan_product = lambda x,y: x
2610 inner_product = lambda x,y: 0
2611 basis = ()
2612
2613 # New defaults for keyword arguments
2614 if "orthonormalize" not in kwargs: kwargs["orthonormalize"] = False
2615 if "check_axioms" not in kwargs: kwargs["check_axioms"] = False
2616
2617 super(TrivialEJA, self).__init__(basis,
2618 jordan_product,
2619 inner_product,
2620 **kwargs)
2621 # The rank is zero using my definition, namely the dimension of the
2622 # largest subalgebra generated by any element.
2623 self.rank.set_cache(0)
2624 self.one.set_cache( self.zero() )
2625
2626 @classmethod
2627 def random_instance(cls, **kwargs):
2628 # We don't take a "size" argument so the superclass method is
2629 # inappropriate for us.
2630 return cls(**kwargs)
2631
2632 class DirectSumEJA(FiniteDimensionalEuclideanJordanAlgebra):
2633 r"""
2634 The external (orthogonal) direct sum of two other Euclidean Jordan
2635 algebras. Essentially the Cartesian product of its two factors.
2636 Every Euclidean Jordan algebra decomposes into an orthogonal
2637 direct sum of simple Euclidean Jordan algebras, so no generality
2638 is lost by providing only this construction.
2639
2640 SETUP::
2641
2642 sage: from mjo.eja.eja_algebra import (random_eja,
2643 ....: HadamardEJA,
2644 ....: RealSymmetricEJA,
2645 ....: DirectSumEJA)
2646
2647 EXAMPLES::
2648
2649 sage: J1 = HadamardEJA(2)
2650 sage: J2 = RealSymmetricEJA(3)
2651 sage: J = DirectSumEJA(J1,J2)
2652 sage: J.dimension()
2653 8
2654 sage: J.rank()
2655 5
2656
2657 TESTS:
2658
2659 The external direct sum construction is only valid when the two factors
2660 have the same base ring; an error is raised otherwise::
2661
2662 sage: set_random_seed()
2663 sage: J1 = random_eja(field=AA)
2664 sage: J2 = random_eja(field=QQ,orthonormalize=False)
2665 sage: J = DirectSumEJA(J1,J2)
2666 Traceback (most recent call last):
2667 ...
2668 ValueError: algebras must share the same base field
2669
2670 """
2671 def __init__(self, J1, J2, **kwargs):
2672 if J1.base_ring() != J2.base_ring():
2673 raise ValueError("algebras must share the same base field")
2674 field = J1.base_ring()
2675
2676 self._factors = (J1, J2)
2677 n1 = J1.dimension()
2678 n2 = J2.dimension()
2679 n = n1+n2
2680 V = VectorSpace(field, n)
2681 mult_table = [ [ V.zero() for j in range(i+1) ]
2682 for i in range(n) ]
2683 for i in range(n1):
2684 for j in range(i+1):
2685 p = (J1.monomial(i)*J1.monomial(j)).to_vector()
2686 mult_table[i][j] = V(p.list() + [field.zero()]*n2)
2687
2688 for i in range(n2):
2689 for j in range(i+1):
2690 p = (J2.monomial(i)*J2.monomial(j)).to_vector()
2691 mult_table[n1+i][n1+j] = V([field.zero()]*n1 + p.list())
2692
2693 # TODO: build the IP table here from the two constituent IP
2694 # matrices (it'll be block diagonal, I think).
2695 ip_table = [ [ field.zero() for j in range(i+1) ]
2696 for i in range(n) ]
2697 super(DirectSumEJA, self).__init__(field,
2698 mult_table,
2699 ip_table,
2700 check_axioms=False,
2701 **kwargs)
2702 self.rank.set_cache(J1.rank() + J2.rank())
2703
2704
2705 def factors(self):
2706 r"""
2707 Return the pair of this algebra's factors.
2708
2709 SETUP::
2710
2711 sage: from mjo.eja.eja_algebra import (HadamardEJA,
2712 ....: JordanSpinEJA,
2713 ....: DirectSumEJA)
2714
2715 EXAMPLES::
2716
2717 sage: J1 = HadamardEJA(2, field=QQ)
2718 sage: J2 = JordanSpinEJA(3, field=QQ)
2719 sage: J = DirectSumEJA(J1,J2)
2720 sage: J.factors()
2721 (Euclidean Jordan algebra of dimension 2 over Rational Field,
2722 Euclidean Jordan algebra of dimension 3 over Rational Field)
2723
2724 """
2725 return self._factors
2726
2727 def projections(self):
2728 r"""
2729 Return a pair of projections onto this algebra's factors.
2730
2731 SETUP::
2732
2733 sage: from mjo.eja.eja_algebra import (JordanSpinEJA,
2734 ....: ComplexHermitianEJA,
2735 ....: DirectSumEJA)
2736
2737 EXAMPLES::
2738
2739 sage: J1 = JordanSpinEJA(2)
2740 sage: J2 = ComplexHermitianEJA(2)
2741 sage: J = DirectSumEJA(J1,J2)
2742 sage: (pi_left, pi_right) = J.projections()
2743 sage: J.one().to_vector()
2744 (1, 0, 1, 0, 0, 1)
2745 sage: pi_left(J.one()).to_vector()
2746 (1, 0)
2747 sage: pi_right(J.one()).to_vector()
2748 (1, 0, 0, 1)
2749
2750 """
2751 (J1,J2) = self.factors()
2752 m = J1.dimension()
2753 n = J2.dimension()
2754 V_basis = self.vector_space().basis()
2755 # Need to specify the dimensions explicitly so that we don't
2756 # wind up with a zero-by-zero matrix when we want e.g. a
2757 # zero-by-two matrix (important for composing things).
2758 P1 = matrix(self.base_ring(), m, m+n, V_basis[:m])
2759 P2 = matrix(self.base_ring(), n, m+n, V_basis[m:])
2760 pi_left = FiniteDimensionalEuclideanJordanAlgebraOperator(self,J1,P1)
2761 pi_right = FiniteDimensionalEuclideanJordanAlgebraOperator(self,J2,P2)
2762 return (pi_left, pi_right)
2763
2764 def inclusions(self):
2765 r"""
2766 Return the pair of inclusion maps from our factors into us.
2767
2768 SETUP::
2769
2770 sage: from mjo.eja.eja_algebra import (random_eja,
2771 ....: JordanSpinEJA,
2772 ....: RealSymmetricEJA,
2773 ....: DirectSumEJA)
2774
2775 EXAMPLES::
2776
2777 sage: J1 = JordanSpinEJA(3)
2778 sage: J2 = RealSymmetricEJA(2)
2779 sage: J = DirectSumEJA(J1,J2)
2780 sage: (iota_left, iota_right) = J.inclusions()
2781 sage: iota_left(J1.zero()) == J.zero()
2782 True
2783 sage: iota_right(J2.zero()) == J.zero()
2784 True
2785 sage: J1.one().to_vector()
2786 (1, 0, 0)
2787 sage: iota_left(J1.one()).to_vector()
2788 (1, 0, 0, 0, 0, 0)
2789 sage: J2.one().to_vector()
2790 (1, 0, 1)
2791 sage: iota_right(J2.one()).to_vector()
2792 (0, 0, 0, 1, 0, 1)
2793 sage: J.one().to_vector()
2794 (1, 0, 0, 1, 0, 1)
2795
2796 TESTS:
2797
2798 Composing a projection with the corresponding inclusion should
2799 produce the identity map, and mismatching them should produce
2800 the zero map::
2801
2802 sage: set_random_seed()
2803 sage: J1 = random_eja()
2804 sage: J2 = random_eja()
2805 sage: J = DirectSumEJA(J1,J2)
2806 sage: (iota_left, iota_right) = J.inclusions()
2807 sage: (pi_left, pi_right) = J.projections()
2808 sage: pi_left*iota_left == J1.one().operator()
2809 True
2810 sage: pi_right*iota_right == J2.one().operator()
2811 True
2812 sage: (pi_left*iota_right).is_zero()
2813 True
2814 sage: (pi_right*iota_left).is_zero()
2815 True
2816
2817 """
2818 (J1,J2) = self.factors()
2819 m = J1.dimension()
2820 n = J2.dimension()
2821 V_basis = self.vector_space().basis()
2822 # Need to specify the dimensions explicitly so that we don't
2823 # wind up with a zero-by-zero matrix when we want e.g. a
2824 # two-by-zero matrix (important for composing things).
2825 I1 = matrix.column(self.base_ring(), m, m+n, V_basis[:m])
2826 I2 = matrix.column(self.base_ring(), n, m+n, V_basis[m:])
2827 iota_left = FiniteDimensionalEuclideanJordanAlgebraOperator(J1,self,I1)
2828 iota_right = FiniteDimensionalEuclideanJordanAlgebraOperator(J2,self,I2)
2829 return (iota_left, iota_right)
2830
2831 def inner_product(self, x, y):
2832 r"""
2833 The standard Cartesian inner-product.
2834
2835 We project ``x`` and ``y`` onto our factors, and add up the
2836 inner-products from the subalgebras.
2837
2838 SETUP::
2839
2840
2841 sage: from mjo.eja.eja_algebra import (HadamardEJA,
2842 ....: QuaternionHermitianEJA,
2843 ....: DirectSumEJA)
2844
2845 EXAMPLE::
2846
2847 sage: J1 = HadamardEJA(3,field=QQ)
2848 sage: J2 = QuaternionHermitianEJA(2,field=QQ,orthonormalize=False)
2849 sage: J = DirectSumEJA(J1,J2)
2850 sage: x1 = J1.one()
2851 sage: x2 = x1
2852 sage: y1 = J2.one()
2853 sage: y2 = y1
2854 sage: x1.inner_product(x2)
2855 3
2856 sage: y1.inner_product(y2)
2857 2
2858 sage: J.one().inner_product(J.one())
2859 5
2860
2861 """
2862 (pi_left, pi_right) = self.projections()
2863 x1 = pi_left(x)
2864 x2 = pi_right(x)
2865 y1 = pi_left(y)
2866 y2 = pi_right(y)
2867
2868 return (x1.inner_product(y1) + x2.inner_product(y2))
2869
2870
2871
2872 random_eja = ConcreteEuclideanJordanAlgebra.random_instance