forked from flintlib/python-flint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfmpq_mat.pyx
455 lines (405 loc) · 14.8 KB
/
fmpq_mat.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
from flint.flint_base.flint_base cimport flint_mat
from flint.utils.typecheck cimport typecheck
cdef any_as_fmpq_mat(obj):
if typecheck(obj, fmpq_mat):
return obj
if typecheck(obj, fmpz_mat):
return fmpq_mat(obj)
return NotImplemented
cdef class fmpq_mat(flint_mat):
"""
Represents a dense matrix over the rational numbers.
>>> A = fmpq_mat(3,3,[1,3,5,2,4,6,fmpq(2,3),2,4])
>>> A.inv()
[-3, 3/2, 3/2]
[ 3, -1/2, -3]
[-1, 0, 3/2]
>>> A.inv() * A
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
"""
cdef fmpq_mat_t val
def __cinit__(self):
fmpq_mat_init(self.val, 0, 0)
def __dealloc__(self):
fmpq_mat_clear(self.val)
@cython.embedsignature(False)
def __init__(self, *args):
cdef long m, n, i, j
if len(args) == 1:
val = args[0]
if typecheck(val, fmpq_mat):
fmpq_mat_init(self.val, fmpq_mat_nrows((<fmpq_mat>val).val),
fmpq_mat_ncols((<fmpq_mat>val).val))
fmpq_mat_set(self.val, (<fmpq_mat>val).val)
elif typecheck(val, fmpz_mat):
fmpq_mat_init(self.val, fmpz_mat_nrows((<fmpz_mat>val).val),
fmpz_mat_ncols((<fmpz_mat>val).val))
fmpq_mat_set_fmpz_mat(self.val, (<fmpz_mat>val).val)
elif isinstance(val, (list, tuple)):
m = len(val)
n = 0
if m != 0:
if not isinstance(val[0], (list, tuple)):
raise TypeError("single input to fmpq_mat must be a list of lists")
n = len(val[0])
for i from 1 <= i < m:
if len(val[i]) != n:
raise ValueError("input rows have different lengths")
fmpq_mat_init(self.val, m, n)
for i from 0 <= i < m:
row = val[i]
for j from 0 <= j < n:
x = fmpq(row[j])
fmpq_set(fmpq_mat_entry(self.val, i, j), (<fmpq>x).val)
else:
raise TypeError("cannot create fmpq_mat from input of type %s" % type(val))
elif len(args) == 2:
m, n = args
fmpq_mat_init(self.val, m, n)
elif len(args) == 3:
m, n, entries = args
fmpq_mat_init(self.val, m, n)
entries = list(entries)
if len(entries) != m*n:
raise ValueError("list of entries has the wrong length")
for i from 0 <= i < m:
for j from 0 <= j < n:
# XXX: slow
x = fmpq(entries[i*n + j])
fmpq_set(fmpq_mat_entry(self.val, i, j), (<fmpq>x).val)
else:
raise ValueError("fmpq_mat: expected 1-3 arguments")
def __nonzero__(self):
return not fmpq_mat_is_zero(self.val)
def __richcmp__(s, t, int op):
cdef bint r
if op != 2 and op != 3:
raise TypeError("matrices cannot be ordered")
s = any_as_fmpq_mat(s)
if t is NotImplemented:
return s
t = any_as_fmpq_mat(t)
if t is NotImplemented:
return t
r = fmpq_mat_equal((<fmpq_mat>s).val, (<fmpq_mat>t).val)
if op == 3:
r = not r
return r
cpdef long nrows(self):
return fmpq_mat_nrows(self.val)
cpdef long ncols(self):
return fmpq_mat_ncols(self.val)
def __getitem__(self, index):
cdef long i, j
cdef fmpq x
i, j = index
if i < 0 or i >= self.nrows() or j < 0 or j >= self.ncols():
raise ValueError("index %i,%i exceeds matrix dimensions" % (i, j))
x = fmpq.__new__(fmpq)
fmpq_set(x.val, fmpq_mat_entry(self.val, i, j))
return x
def __setitem__(self, index, value):
cdef long i, j
i, j = index
if i < 0 or i >= self.nrows() or j < 0 or j >= self.ncols():
raise ValueError("index %i,%i exceeds matrix dimensions" % (i, j))
c = fmpq(value) # XXX
fmpq_set(fmpq_mat_entry(self.val, i, j), (<fmpq>c).val)
def det(self):
"""
Returns the determinant of *self* as an *fmpq*.
>>> (fmpq_mat(2,2,[1,2,3,4]) / 5).det()
-2/25
"""
cdef fmpq d
if not fmpq_mat_is_square(self.val):
raise ValueError("matrix must be square")
d = fmpq.__new__(fmpq)
fmpq_mat_det(d.val, self.val)
return d
def __pos__(self):
return self
def __neg__(self):
cdef fmpq_mat t = fmpq_mat(self)
fmpq_mat_neg(t.val, t.val) # XXX
return t
def __add__(s, t):
cdef fmpq_mat u
cdef fmpq_mat_struct *sval
cdef fmpq_mat_struct *tval
t = any_as_fmpq_mat(t)
if t is NotImplemented:
return t
sval = &(<fmpq_mat>s).val[0]
tval = &(<fmpq_mat>t).val[0]
if (fmpq_mat_nrows(sval) != fmpq_mat_nrows(tval) or
fmpq_mat_ncols(sval) != fmpq_mat_ncols(tval)):
raise ValueError("incompatible shapes for matrix addition")
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows(sval), fmpq_mat_ncols(sval))
fmpq_mat_add(u.val, sval, tval)
return u
def __sub__(s, t):
cdef fmpq_mat u
cdef fmpq_mat_struct *sval
cdef fmpq_mat_struct *tval
t = any_as_fmpq_mat(t)
if t is NotImplemented:
return t
sval = &(<fmpq_mat>s).val[0]
tval = &(<fmpq_mat>t).val[0]
if (fmpq_mat_nrows(sval) != fmpq_mat_nrows(tval) or
fmpq_mat_ncols(sval) != fmpq_mat_ncols(tval)):
raise ValueError("incompatible shapes for matrix subtraction")
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows(sval), fmpq_mat_ncols(sval))
fmpq_mat_sub(u.val, sval, tval)
return u
cdef __mul_fmpz(self, fmpz c):
cdef fmpq_mat u
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows(self.val), fmpq_mat_ncols(self.val))
fmpq_mat_scalar_mul_fmpz(u.val, self.val, c.val)
return u
cdef __mul_fmpq(self, fmpq c):
cdef fmpq_mat u
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows(self.val), fmpq_mat_ncols(self.val))
fmpq_mat_scalar_mul_fmpz(u.val, self.val, fmpq_numref(c.val))
fmpq_mat_scalar_div_fmpz(u.val, u.val, fmpq_denref(c.val))
return u
cdef __mul_fmpq_mat(self, fmpq_mat other):
cdef fmpq_mat u
if self.ncols() != other.nrows():
raise ValueError("incompatible shapes for matrix multiplication")
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows(self.val), fmpq_mat_ncols(other.val))
fmpq_mat_mul(u.val, self.val, other.val)
return u
cdef __mul_fmpz_mat(self, fmpz_mat other):
cdef fmpq_mat u
if self.ncols() != other.nrows():
raise ValueError("incompatible shapes for matrix multiplication")
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows(self.val), fmpz_mat_ncols(other.val))
fmpq_mat_mul_fmpz_mat(u.val, self.val, other.val)
return u
cdef __mul_r_fmpz_mat(self, fmpz_mat other):
cdef fmpq_mat u
if self.nrows() != other.ncols():
raise ValueError("incompatible shapes for matrix multiplication")
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpz_mat_nrows(other.val), fmpq_mat_ncols(self.val))
fmpq_mat_mul_r_fmpz_mat(u.val, other.val, self.val)
return u
def __mul__(s, t):
cdef fmpz_mat u
if typecheck(t, fmpq_mat):
return (<fmpq_mat>s).__mul_fmpq_mat(t)
elif typecheck(t, fmpz_mat):
return (<fmpq_mat>s).__mul_fmpz_mat(t)
else:
c = any_as_fmpz(t)
if c is not NotImplemented:
return (<fmpq_mat>s).__mul_fmpz(c)
c = any_as_fmpq(t)
if c is not NotImplemented:
return (<fmpq_mat>s).__mul_fmpq(c)
return NotImplemented
def __rmul__(s, t):
cdef fmpz_mat u
if typecheck(t, fmpz_mat):
return (<fmpq_mat>s).__mul_r_fmpz_mat(t)
else:
c = any_as_fmpz(t)
if c is not NotImplemented:
return (<fmpq_mat>s).__mul_fmpz(c)
c = any_as_fmpq(t)
if c is not NotImplemented:
return (<fmpq_mat>s).__mul_fmpq(c)
return NotImplemented
@staticmethod
def _div_(fmpq_mat s, t):
t = any_as_fmpq(t)
if t is NotImplemented:
return t
return s * (1 / t)
def __truediv__(s, t):
return fmpq_mat._div_(s, t)
def __div__(s, t):
return fmpq_mat._div_(s, t)
def inv(self):
"""
Returns the inverse matrix of *self*.
>>> (fmpq_mat([[1,2],[3,4]]) / 5).inv()
[ -10, 5]
[15/2, -5/2]
>>> (fmpq_mat([[1,2],[3,6]]) / 5).inv()
Traceback (most recent call last):
...
ZeroDivisionError: matrix is singular
"""
cdef fmpq_mat u
if not fmpq_mat_is_square(self.val):
raise ValueError("matrix must be square")
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows(self.val), fmpq_mat_ncols(self.val))
if not fmpq_mat_inv(u.val, self.val):
raise ZeroDivisionError("matrix is singular")
return u
def transpose(self):
"""
Returns the transpose of *self*.
>>> fmpq_mat(2,3,range(6)).transpose()
[0, 3]
[1, 4]
[2, 5]
"""
cdef fmpq_mat u
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_ncols(self.val), fmpq_mat_nrows(self.val))
fmpq_mat_transpose(u.val, self.val)
return u
def solve(self, other, algorithm=None):
"""
Given matrices *A* and *B* represented by *self* and *other*,
returns an *fmpq_mat* *X* such that `AX = B`, assuming that
*A* is square and invertible.
Algorithm can *None* for a default choice, or "fflu" or "dixon"
(faster for large matrices).
>>> A = fmpq_mat(2, 2, [1,4,8,3])
>>> B = fmpq_mat(2, 3, range(6))
>>> X = A.solve(B)
>>> X
[12/29, 13/29, 14/29]
[-3/29, 4/29, 11/29]
>>> A*X == B
True
>>> A.solve(B, algorithm='dixon') == X
True
>>> fmpq_mat(2, 2, [1,0,2,0]).solve(B)
Traceback (most recent call last):
...
ZeroDivisionError: singular matrix in solve()
>>> A.solve(fmpq_mat(1, 2, [2,3]))
Traceback (most recent call last):
...
ValueError: need a square system and compatible right hand side
"""
cdef fmpq_mat u
cdef int result
t = any_as_fmpq_mat(other)
if t is NotImplemented:
raise TypeError("cannot convert input to fmpq_mat")
if (fmpq_mat_nrows(self.val) != fmpq_mat_ncols(self.val) or
fmpq_mat_nrows(self.val) != fmpq_mat_nrows((<fmpq_mat>t).val)):
raise ValueError("need a square system and compatible right hand side")
u = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init(u.val, fmpq_mat_nrows((<fmpq_mat>t).val),
fmpq_mat_ncols((<fmpq_mat>t).val))
if algorithm is None:
if fmpq_mat_nrows(self.val) < 25:
result = fmpq_mat_solve_fraction_free(u.val, self.val, (<fmpq_mat>t).val)
else:
result = fmpq_mat_solve_dixon(u.val, self.val, (<fmpq_mat>t).val)
elif algorithm == "fflu":
result = fmpq_mat_solve_fraction_free(u.val, self.val, (<fmpq_mat>t).val)
elif algorithm == "dixon":
result = fmpq_mat_solve_dixon(u.val, self.val, (<fmpq_mat>t).val)
else:
raise ValueError("unknown algorithm")
if not result:
raise ZeroDivisionError("singular matrix in solve()")
return u
def rref(self, inplace=False):
"""
Computes the reduced row echelon form (rref) of *self*,
either returning a new copy or modifying self in-place.
Returns (*rref*, *rank*).
>>> A = fmpq_mat(3,3,range(9))
>>> A.rref()
([1, 0, -1]
[0, 1, 2]
[0, 0, 0], 2)
>>> A.rref(inplace=True)
([1, 0, -1]
[0, 1, 2]
[0, 0, 0], 2)
>>> A
[1, 0, -1]
[0, 1, 2]
[0, 0, 0]
"""
if inplace:
res = self
else:
res = fmpq_mat.__new__(fmpq_mat)
fmpq_mat_init((<fmpq_mat>res).val, fmpq_mat_nrows(self.val), fmpq_mat_ncols(self.val))
rank = fmpq_mat_rref((<fmpq_mat>res).val, self.val)
return res, rank
@classmethod
def hilbert(cls, long n, long m):
"""
Returns the *n* by *m* truncated Hilbert matrix.
>>> fmpq_mat.hilbert(2,3)
[ 1, 1/2, 1/3]
[1/2, 1/3, 1/4]
"""
cdef fmpq_mat u
u = fmpq_mat(n, m)
fmpq_mat_hilbert_matrix(u.val)
return u
def numer_denom(self):
"""
Returns (*A*, *d*) where *A* is an *fmpz_mat* and *d* is an
*fmpz* representing the minimal denominator such that
*A* times *d* equals *self*.
>>> A, d = fmpq_mat.hilbert(3,3).numer_denom()
>>> A
[60, 30, 20]
[30, 20, 15]
[20, 15, 12]
>>> d
60
"""
cdef fmpz_mat num
cdef fmpz_den
num = fmpz_mat(self.nrows(), self.ncols())
den = fmpz()
fmpq_mat_get_fmpz_mat_matwise(num.val, den.val, self.val)
return num, den
def charpoly(self):
cdef fmpq_poly u
u = fmpq_poly.__new__(fmpq_poly)
fmpq_poly_init(u.val)
fmpq_mat_charpoly(u.val, self.val)
return u
def minpoly(self):
cdef fmpq_poly u
u = fmpq_poly.__new__(fmpq_poly)
fmpq_poly_init(u.val)
fmpq_mat_minpoly(u.val, self.val)
return u
def __pow__(self, n, z):
cdef fmpq_mat v
assert z is None
n = int(n)
if n == 0:
r, c = self.nrows(), self.ncols()
assert r == c
v = fmpq_mat(r, c)
fmpq_mat_one(v.val)
return v
if n == 1:
return self
if n == 2:
return self * self
if n < 0:
return self.inv() ** (-n)
v = self ** (n // 2)
v = v * v
if n % 2:
v *= self
return v