forked from flintlib/python-flint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflint_base.pyx
More file actions
498 lines (397 loc) · 14.5 KB
/
flint_base.pyx
File metadata and controls
498 lines (397 loc) · 14.5 KB
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
from flint.flintlib.flint cimport (
FLINT_BITS as _FLINT_BITS,
FLINT_VERSION as _FLINT_VERSION,
__FLINT_RELEASE as _FLINT_RELEASE,
slong
)
from flint.flintlib.mpoly cimport ordering_t
from flint.flint_base.flint_context cimport thectx
from flint.flint_base.flint_base cimport Ordering
from flint.utils.typecheck cimport typecheck
cimport libc.stdlib
from typing import Optional
FLINT_BITS = _FLINT_BITS
FLINT_VERSION = _FLINT_VERSION.decode("ascii")
FLINT_RELEASE = _FLINT_RELEASE
cdef class flint_elem:
def __repr__(self):
if thectx.pretty:
return self.str()
else:
return self.repr()
def __str__(self):
return self.str()
cdef class flint_scalar(flint_elem):
# =================================================
# These are the functions a new class should define
# assumes that addition and multiplication are
# commutative
# =================================================
def is_zero(self):
return False
def _any_as_self(self):
return NotImplemented
def _neg_(self):
return NotImplemented
def _add_(self, other):
return NotImplemented
def _sub_(self, other):
return NotImplemented
def _rsub_(self, other):
return NotImplemented
def _mul_(self, other):
return NotImplemented
def _div_(self, other):
return NotImplemented
def _rdiv_(self, other):
return NotImplemented
def _floordiv_(self, other):
return NotImplemented
def _rfloordiv_(self, other):
return NotImplemented
def _invert_(self):
return NotImplemented
# =================================================
# Generic arithmetic using the above functions
# =================================================
def __pos__(self):
return self
def __neg__(self):
return self._neg_()
def __add__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._add_(other)
def __radd__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._add_(other)
def __sub__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._sub_(other)
def __rsub__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._rsub_(other)
def __mul__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._mul_(other)
def __rmul__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._mul_(other)
def __truediv__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
if other.is_zero():
raise ZeroDivisionError
return self._div_(other)
def __rtruediv__(self, other):
if self.is_zero():
raise ZeroDivisionError
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._rdiv_(other)
def __floordiv__(self, other):
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
if other.is_zero():
raise ZeroDivisionError
return self._floordiv_(other)
def __rfloordiv__(self, other):
if self.is_zero():
raise ZeroDivisionError
other = self._any_as_self(other)
if other is NotImplemented:
return NotImplemented
return self._rfloordiv_(other)
def __invert__(self):
if self.is_zero():
raise ZeroDivisionError
return self._invert_()
cdef class flint_poly(flint_elem):
"""
Base class for polynomials.
"""
def __iter__(self):
cdef long i, n
n = self.length()
for i in range(n):
yield self[i]
def coeffs(self):
"""
Returns the coefficients of ``self`` as a list
>>> from flint import fmpz_poly
>>> f = fmpz_poly([1,2,3,4,5])
>>> f.coeffs()
[1, 2, 3, 4, 5]
"""
return list(self)
def str(self, bint ascending=False, var="x", *args, **kwargs):
"""
Convert to a human-readable string (generic implementation for
all polynomial types).
If *ascending* is *True*, the monomials are output from low degree to
high, otherwise from high to low.
"""
coeffs = [c.str(*args, **kwargs) for c in self]
if not coeffs:
return "0"
s = []
coeffs = enumerate(coeffs)
if not ascending:
coeffs = reversed(list(coeffs))
for i, c in coeffs:
if c == "0":
continue
else:
if c.startswith("-") or (" " in c):
c = "(" + c + ")"
if i == 0:
s.append("%s" % c)
elif i == 1:
if c == "1":
s.append(var)
else:
s.append(f"{c}*{var}")
else:
if c == "1":
s.append(f"{var}^{i}")
else:
s.append(f"{c}*{var}^{i}")
return " + ".join(s)
def roots(self):
"""
Computes all the roots in the base ring of the polynomial.
Returns a list of all pairs (*v*, *m*) where *v* is the
integer root and *m* is the multiplicity of the root.
To compute complex roots of a polynomial, instead use
the `.complex_roots()` method, which is available on
certain polynomial rings.
>>> from flint import fmpz_poly
>>> fmpz_poly([1, 2]).roots()
[]
>>> fmpz_poly([2, 1]).roots()
[(-2, 1)]
>>> fmpz_poly([12, 7, 1]).roots()
[(-3, 1), (-4, 1)]
>>> (fmpz_poly([-5,1]) * fmpz_poly([-5,1]) * fmpz_poly([-3,1])).roots()
[(3, 1), (5, 2)]
"""
factor_fn = getattr(self, "factor", None)
if not callable(factor_fn):
raise NotImplementedError("Polynomial has no factor method, roots cannot be determined")
roots = []
factors = self.factor()
for fac, m in factors[1]:
if fac.degree() == fac[1] == 1:
v = - fac[0]
roots.append((v, m))
return roots
def complex_roots(self):
raise AttributeError("Complex roots are not supported for this polynomial")
cdef class flint_mpoly_context(flint_elem):
"""
Base class for multivariate ring contexts
"""
_ctx_cache = None
def __init__(self, int nvars, names):
if nvars < 0:
raise ValueError("cannot have a negative amount of variables")
elif len(names) != nvars:
raise ValueError("number of variables must match number of variable names")
self.py_names = tuple(name.encode("ascii") if not isinstance(name, bytes) else name for name in names)
self.c_names = <const char**> libc.stdlib.malloc(nvars * sizeof(const char *))
for i in range(nvars):
self.c_names[i] = self.py_names[i]
def __dealloc__(self):
libc.stdlib.free(self.c_names)
self.c_names = NULL
def __str__(self):
return self.__repr__()
def __repr__(self):
return f"{self.__class__.__name__}({self.nvars()}, '{repr(self.ordering())}', {self.names()})"
def name(self, long i):
if not 0 <= i < len(self.py_names):
raise IndexError("variable name index out of range")
return self.py_names[i].decode("ascii")
def names(self):
return tuple(name.decode("ascii") for name in self.py_names)
def gens(self):
return tuple(self.gen(i) for i in range(self.nvars()))
def variable_to_index(self, var: Union[int, str]):
"""Convert a variable name string or possible index to its index in the context."""
if isinstance(var, str):
try:
i = self.names().index(var)
except ValueError:
raise ValueError("variable not in context")
elif isinstance(var, int):
if not 0 <= var < self.nvars():
raise IndexError("generator index out of range")
i = var
else:
raise TypeError("invalid variable type")
return i
@staticmethod
def create_variable_names(slong nvars, names: str):
"""
Create a tuple of variable names based on the comma separated `names` string.
If `names` contains a single value, and `nvars` > 1, then the variables are numbered, e.g.
>>> flint_mpoly_context.create_variable_names(3, "x")
('x0', 'x1', 'x2')
"""
nametup = tuple(name.strip() for name in names.split(','))
if len(nametup) != nvars:
if len(nametup) == 1:
nametup = tuple(nametup[0] + str(i) for i in range(nvars))
else:
raise ValueError("number of variables does not equal number of names")
return nametup
@classmethod
def get_context(cls, slong nvars=1, ordering=Ordering.lex, names: Optional[str] = "x", nametup: Optional[tuple] = None):
"""
Retrieve a context via the number of variables, `nvars`, the ordering, `ordering`, and either a variable
name string, `names`, or a tuple of variable names, `nametup`.
"""
# A type hint of `ordering: Ordering` results in the error "TypeError: an integer is required" if a Ordering
# object is not provided. This is pretty obtuse so we check it's type ourselves
if not isinstance(ordering, Ordering):
raise TypeError(f"`ordering` ('{ordering}') is not an instance of flint.Ordering")
if nametup is not None:
key = nvars, ordering, nametup
elif nametup is None and names is not None:
key = nvars, ordering, cls.create_variable_names(nvars, names)
else:
raise ValueError("must provide either `names` or `nametup`")
ctx = cls._ctx_cache.get(key)
if ctx is None:
ctx = cls._ctx_cache.setdefault(key, cls(*key))
return ctx
@classmethod
def from_context(cls, ctx: flint_mpoly_context):
return cls.get_context(
nvars=ctx.nvars(),
ordering=ctx.ordering(),
names=None,
nametup=ctx.names()
)
cdef class flint_mpoly(flint_elem):
"""
Base class for multivariate polynomials.
"""
def leading_coefficient(self):
return self.coefficient(0)
def to_dict(self):
return {self.monomial(i): self.coefficient(i) for i in range(len(self))}
def __contains__(self, x):
"""
Returns True if `self` contains a term with exponent vector `x` and a non-zero coefficient.
>>> from flint import fmpq_mpoly_ctx, Ordering
>>> ctx = fmpq_mpoly_ctx.get_context(2, Ordering.lex, 'x')
>>> p = ctx.from_dict({(0, 1): 2, (1, 1): 3})
>>> (1, 1) in p
True
>>> (5, 1) in p
False
"""
return bool(self[x])
def __iter__(self):
return iter(self.monoms())
def __pos__(self):
return self
def terms(self):
"""
Return the exponent vectors and coefficient of each term.
>>> from flint import fmpq_mpoly_ctx, Ordering
>>> ctx = fmpq_mpoly_ctx.get_context(2, Ordering.lex, 'x')
>>> f = ctx.from_dict({(0, 0): 1, (1, 0): 2, (0, 1): 3, (1, 1): 4})
>>> list(f.terms())
[((1, 1), 4), ((1, 0), 2), ((0, 1), 3), ((0, 0), 1)]
"""
return zip(self.monoms(), self.coeffs())
cdef class flint_series(flint_elem):
"""
Base class for power series.
"""
def __iter__(self):
cdef long i, n
n = self.length()
for i in range(n):
yield self[i]
def coeffs(self):
return list(self)
cdef class flint_mat(flint_elem):
"""
Base class for matrices.
"""
def repr(self):
# XXX
return "%s(%i, %i, [%s])" % (type(self).__name__,
self.nrows(), self.ncols(), (", ".join(map(str, self.entries()))))
def str(self, *args, **kwargs):
tab = self.table()
if len(tab) == 0 or len(tab[0]) == 0:
return "[]"
tab = [[r.str(*args, **kwargs) for r in row] for row in tab]
widths = []
for i in xrange(len(tab[0])):
w = max([len(row[i]) for row in tab])
widths.append(w)
for i in xrange(len(tab)):
tab[i] = [s.rjust(widths[j]) for j, s in enumerate(tab[i])]
tab[i] = "[" + (", ".join(tab[i])) + "]"
return "\n".join(tab)
def entries(self):
cdef long i, j, m, n
m = self.nrows()
n = self.ncols()
L = [None] * (m * n)
for i from 0 <= i < m:
for j from 0 <= j < n:
L[i*n + j] = self[i, j]
return L
def __iter__(self):
cdef long i, j, m, n
m = self.nrows()
n = self.ncols()
for i from 0 <= i < m:
for j from 0 <= j < n:
yield self[i, j]
def table(self):
cdef long i, m, n
m = self.nrows()
n = self.ncols()
L = self.entries()
return [L[i*n : (i+1)*n] for i in range(m)]
# supports mpmath conversions
tolist = table
cdef ordering_t ordering_py_to_c(ordering): # Cython does not like an "Ordering" type hint here
if not isinstance(ordering, Ordering):
raise TypeError(f"`ordering` ('{ordering}') is not an instance of flint.Ordering")
if ordering == Ordering.lex:
return ordering_t.ORD_LEX
elif ordering == Ordering.deglex:
return ordering_t.ORD_DEGLEX
elif ordering == Ordering.degrevlex:
return ordering_t.ORD_DEGREVLEX
cdef ordering_c_to_py(ordering_t ordering):
if ordering == ordering_t.ORD_LEX:
return Ordering.lex
elif ordering == ordering_t.ORD_DEGLEX:
return Ordering.deglex
elif ordering == ordering_t.ORD_DEGREVLEX:
return Ordering.degrevlex
else:
raise ValueError("unimplemented term order %d" % ordering)