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