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
796 lines (624 loc) · 23.7 KB
/
flint_base.pyx
File metadata and controls
796 lines (624 loc) · 23.7 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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
from flint.utils.flint_exceptions import IncompatibleContextError
from flint.types.fmpz cimport fmpz, any_as_fmpz
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, other):
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 create_context_key(cls, slong nvars=1, ordering=Ordering.lex, names: Optional[str] = "x", nametup: Optional[tuple] = None):
"""
Create a key for the context cache via the number of variables, the ordering, and
either a variable name string, or a tuple of variable names.
"""
# 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 its 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`")
return key
@classmethod
def get_context(cls, *args, **kwargs):
"""
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`.
"""
key = cls.create_context_key(*args, **kwargs)
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()
)
def any_as_scalar(self, other):
raise NotImplementedError("abstract method")
def scalar_as_mpoly(self, other):
raise NotImplementedError("abstract method")
def compatible_context_check(self, other):
if not typecheck(other, type(self)):
raise TypeError(f"type {type(other)} is not {type(self)}")
elif other is not self:
raise IncompatibleContextError(f"{other} is not {self}")
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 _division_check(self, other):
if not other:
raise ZeroDivisionError("nmod_mpoly division by zero")
def _add_scalar_(self, other):
return NotImplemented
def _add_mpoly_(self, other):
return NotImplemented
def _iadd_scalar_(self, other):
return NotImplemented
def _iadd_mpoly_(self, other):
return NotImplemented
def _sub_scalar_(self, other):
return NotImplemented
def _sub_mpoly_(self, other):
return NotImplemented
def _isub_scalar_(self, other):
return NotImplemented
def _isub_mpoly_(self, other):
return NotImplemented
def _mul_scalar_(self, other):
return NotImplemented
def _imul_mpoly_(self, other):
return NotImplemented
def _imul_scalar_(self, other):
return NotImplemented
def _mul_mpoly_(self, other):
return NotImplemented
def _pow_(self, other):
return NotImplemented
def _divmod_mpoly_(self, other):
return NotImplemented
def _floordiv_mpoly_(self, other):
return NotImplemented
def _truediv_mpoly_(self, other):
return NotImplemented
def __add__(self, other):
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
return self._add_mpoly_(other)
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
return self._add_scalar_(other)
def __radd__(self, other):
return self.__add__(other)
def iadd(self, other):
"""
In-place addition, mutates self.
>>> from flint import Ordering, fmpz_mpoly_ctx
>>> ctx = fmpz_mpoly_ctx.get_context(2, Ordering.lex, 'x')
>>> f = ctx.from_dict({(1, 0): 2, (0, 1): 3, (1, 1): 4})
>>> f
4*x0*x1 + 2*x0 + 3*x1
>>> f.iadd(5)
>>> f
4*x0*x1 + 2*x0 + 3*x1 + 5
"""
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
self._iadd_mpoly_(other)
return
other_scalar = self.context().any_as_scalar(other)
if other_scalar is NotImplemented:
raise NotImplementedError(f"cannot add {type(self)} and {type(other)}")
self._iadd_scalar_(other_scalar)
def __sub__(self, other):
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
return self._sub_mpoly_(other)
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
return self._sub_scalar_(other)
def __rsub__(self, other):
return -self.__sub__(other)
def isub(self, other):
"""
In-place subtraction, mutates self.
>>> from flint import Ordering, fmpz_mpoly_ctx
>>> ctx = fmpz_mpoly_ctx.get_context(2, Ordering.lex, 'x')
>>> f = ctx.from_dict({(1, 0): 2, (0, 1): 3, (1, 1): 4})
>>> f
4*x0*x1 + 2*x0 + 3*x1
>>> f.isub(5)
>>> f
4*x0*x1 + 2*x0 + 3*x1 - 5
"""
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
self._isub_mpoly_(other)
return
other_scalar = self.context().any_as_scalar(other)
if other_scalar is NotImplemented:
raise NotImplementedError(f"cannot subtract {type(self)} and {type(other)}")
self._isub_scalar_(other_scalar)
def __mul__(self, other):
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
return self._mul_mpoly_(other)
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
return self._mul_scalar_(other)
def __rmul__(self, other):
return self.__mul__(other)
def imul(self, other):
"""
In-place multiplication, mutates self.
>>> from flint import Ordering, fmpz_mpoly_ctx
>>> ctx = fmpz_mpoly_ctx.get_context(2, Ordering.lex, 'x')
>>> f = ctx.from_dict({(1, 0): 2, (0, 1): 3, (1, 1): 4})
>>> f
4*x0*x1 + 2*x0 + 3*x1
>>> f.imul(2)
>>> f
8*x0*x1 + 4*x0 + 6*x1
"""
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
self._imul_mpoly_(other)
return
other_scalar = self.context().any_as_scalar(other)
if other_scalar is NotImplemented:
raise NotImplementedError(f"cannot multiply {type(self)} and {type(other)}")
self._imul_scalar_(other_scalar)
def __pow__(self, other, modulus):
if modulus is not None:
raise NotImplementedError("cannot specify modulus outside of the context")
elif typecheck(other, fmpz):
return self._pow_(other)
other = any_as_fmpz(other)
if other is NotImplemented:
return NotImplemented
elif other < 0:
raise ValueError("cannot raise to a negative power")
return self._pow_(other)
def __divmod__(self, other):
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
self._division_check(other)
return self._divmod_mpoly_(other)
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
self._division_check(other)
return self._divmod_mpoly_(other)
def __rdivmod__(self, other):
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
other._division_check(self)
return other._divmod_mpoly_(self)
def __truediv__(self, other):
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
self._division_check(other)
return self._truediv_mpoly_(other)
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
self._division_check(other)
return self._truediv_mpoly_(other)
def __rtruediv__(self, other):
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
other._division_check(self)
return other._truediv_mpoly_(self)
def __floordiv__(self, other):
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
self._division_check(other)
return self._floordiv_mpoly_(other)
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
self._division_check(other)
return self._floordiv_mpoly_(other)
def __rfloordiv__(self, other):
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
other._division_check(self)
return other._floordiv_mpoly_(self)
def __mod__(self, other):
if typecheck(other, type(self)):
self.context().compatible_context_check(other.context())
self._division_check(other)
return self._mod_mpoly_(other)
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
self._division_check(other)
return self._mod_mpoly_(other)
def __rmod__(self, other):
other = self.context().any_as_scalar(other)
if other is NotImplemented:
return NotImplemented
other = self.context().scalar_as_mpoly(other)
other._division_check(self)
return other._mod_mpoly_(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)