]> gitweb.michael.orlitzky.com - sage.d.git/blob - mjo/eja/eja_utils.py
eja: add a WIP gram-schmidt for EJA elements.
[sage.d.git] / mjo / eja / eja_utils.py
1 from sage.modules.free_module_element import vector
2 from sage.rings.number_field.number_field import NumberField
3 from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
4 from sage.rings.real_lazy import RLF
5
6 def _mat2vec(m):
7 return vector(m.base_ring(), m.list())
8
9 def gram_schmidt(v):
10 """
11 Perform Gram-Schmidt on the list ``v`` which are assumed to be
12 vectors over the same base ring. Returns a list of orthonormalized
13 vectors over the smallest extention ring containing the necessary
14 roots.
15
16 SETUP::
17
18 sage: from mjo.eja.eja_utils import gram_schmidt
19
20 EXAMPLES::
21
22 sage: v1 = vector(QQ,(1,2,3))
23 sage: v2 = vector(QQ,(1,-1,6))
24 sage: v3 = vector(QQ,(2,1,-1))
25 sage: v = [v1,v2,v3]
26 sage: u = gram_schmidt(v)
27 sage: [ u_i.inner_product(u_i).sqrt() == 1 for u_i in u ]
28 True
29 sage: u[0].inner_product(u[1]) == 0
30 True
31 sage: u[0].inner_product(u[2]) == 0
32 True
33 sage: u[1].inner_product(u[2]) == 0
34 True
35
36 TESTS:
37
38 Ensure that zero vectors don't get in the way::
39
40 sage: v1 = vector(QQ,(1,2,3))
41 sage: v2 = vector(QQ,(1,-1,6))
42 sage: v3 = vector(QQ,(0,0,0))
43 sage: v = [v1,v2,v3]
44 sage: len(gram_schmidt(v)) == 2
45 True
46
47 """
48 def proj(x,y):
49 return (y.inner_product(x)/x.inner_product(x))*x
50
51 v = list(v) # make a copy, don't clobber the input
52
53 # Drop all zero vectors before we start.
54 v = [ v_i for v_i in v if not v_i.is_zero() ]
55
56 if len(v) == 0:
57 # cool
58 return v
59
60 R = v[0].base_ring()
61
62 # First orthogonalize...
63 for i in xrange(1,len(v)):
64 # Earlier vectors can be made into zero so we have to ignore them.
65 v[i] -= sum( proj(v[j],v[i]) for j in range(i) if not v[j].is_zero() )
66
67 # And now drop all zero vectors again if they were "orthogonalized out."
68 v = [ v_i for v_i in v if not v_i.is_zero() ]
69
70 # Now pretend to normalize, building a new ring R that contains
71 # all of the necessary square roots.
72 norms_squared = [0]*len(v)
73
74 for i in xrange(len(v)):
75 norms_squared[i] = v[i].inner_product(v[i])
76 ns = [norms_squared[i].numerator(), norms_squared[i].denominator()]
77
78 # Do the numerator and denominator separately so that we
79 # adjoin e.g. sqrt(2) and sqrt(3) instead of sqrt(2/3).
80 for j in xrange(len(ns)):
81 PR = PolynomialRing(R, 'z')
82 z = PR.gen()
83 p = z**2 - ns[j]
84 if p.is_irreducible():
85 R = NumberField(p,
86 'sqrt' + str(ns[j]),
87 embedding=RLF(ns[j]).sqrt())
88
89 # When we're done, we have to change every element's ring to the
90 # extension that we wound up with, and then normalize it (which
91 # should work, since "R" contains its norm now).
92 for i in xrange(len(v)):
93 v[i] = v[i].change_ring(R) / R(norms_squared[i]).sqrt()
94
95 return v