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