This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
/
multi_polynomial_libsingular.pyx
5862 lines (4694 loc) · 184 KB
/
multi_polynomial_libsingular.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
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Multivariate Polynomials via libSINGULAR
This module implements specialized and optimized implementations for
multivariate polynomials over many coefficient rings, via a shared library
interface to SINGULAR. In particular, the following coefficient rings are
supported by this implementation:
- the rational numbers `\QQ`,
- the ring of integers `\ZZ`,
- `\ZZ/n\ZZ` for any integer `n`,
- finite fields `\GF{p^n}` for `p` prime and `n > 0`,
- and absolute number fields `\QQ(a)`.
EXAMPLES:
We show how to construct various multivariate polynomial rings::
sage: P.<x,y,z> = QQ[]
sage: P
Multivariate Polynomial Ring in x, y, z over Rational Field
sage: f = 27/113 * x^2 + y*z + 1/2; f
27/113*x^2 + y*z + 1/2
sage: P.term_order()
Degree reverse lexicographic term order
sage: P = PolynomialRing(GF(127),3,names='abc', order='lex')
sage: P
Multivariate Polynomial Ring in a, b, c over Finite Field of size 127
sage: a,b,c = P.gens()
sage: f = 57 * a^2*b + 43 * c + 1; f
57*a^2*b + 43*c + 1
sage: P.term_order()
Lexicographic term order
sage: z = QQ['z'].0
sage: K.<s> = NumberField(z^2 - 2)
sage: P.<x,y> = PolynomialRing(K, 2)
sage: 1/2*s*x^2 + 3/4*s
(1/2*s)*x^2 + (3/4*s)
sage: P.<x,y,z> = ZZ[]; P
Multivariate Polynomial Ring in x, y, z over Integer Ring
sage: P.<x,y,z> = Zmod(2^10)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 1024
sage: P.<x,y,z> = Zmod(3^10)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 59049
sage: P.<x,y,z> = Zmod(2^100)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 1267650600228229401496703205376
sage: P.<x,y,z> = Zmod(2521352)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 2521352
sage: type(P)
<class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomialRing_libsingular'>
sage: P.<x,y,z> = Zmod(25213521351515232)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 25213521351515232
sage: type(P)
<class 'sage.rings.polynomial.multi_polynomial_ring.MPolynomialRing_polydict_with_category'>
We construct the Frobenius morphism on `\GF{5}[x,y,z]` over `\GF{5}`::
sage: R.<x,y,z> = PolynomialRing(GF(5), 3)
sage: frob = R.hom([x^5, y^5, z^5])
sage: frob(x^2 + 2*y - z^4)
-z^20 + x^10 + 2*y^5
sage: frob((x + 2*y)^3)
x^15 + x^10*y^5 + 2*x^5*y^10 - 2*y^15
sage: (x^5 + 2*y^5)^3
x^15 + x^10*y^5 + 2*x^5*y^10 - 2*y^15
We make a polynomial ring in one variable over a polynomial ring in
two variables::
sage: R.<x, y> = PolynomialRing(QQ, 2)
sage: S.<t> = PowerSeriesRing(R)
sage: t*(x+y)
(x + y)*t
TESTS::
sage: P.<x,y,z> = QQ[]
sage: loads(dumps(P)) == P
True
sage: loads(dumps(x)) == x
True
sage: P.<x,y,z> = GF(2^8,'a')[]
sage: loads(dumps(P)) == P
True
sage: loads(dumps(x)) == x
True
sage: P.<x,y,z> = GF(127)[]
sage: loads(dumps(P)) == P
True
sage: loads(dumps(x)) == x
True
sage: P.<x,y,z> = GF(127)[]
sage: loads(dumps(P)) == P
True
sage: loads(dumps(x)) == x
True
sage: Rt.<t> = PolynomialRing(QQ, implementation="singular")
sage: p = 1+t
sage: R.<u,v> = PolynomialRing(QQ, 2)
sage: p(u/v)
(u + v)/v
Check if :trac:`6160` is fixed::
sage: x=var('x')
sage: K.<j> = NumberField(x-1728)
sage: R.<b,c> = K[]
sage: b-j*c
b - 1728*c
.. TODO::
Implement Real, Complex coefficient rings via libSINGULAR
AUTHORS:
- Martin Albrecht (2007-01): initial implementation
- Joel Mohler (2008-01): misc improvements, polishing
- Martin Albrecht (2008-08): added `\QQ(a)` and `\ZZ` support
- Simon King (2009-04): improved coercion
- Martin Albrecht (2009-05): added `\ZZ/n\ZZ` support, refactoring
- Martin Albrecht (2009-06): refactored the code to allow better
re-use
- Simon King (2011-03): use a faster way of conversion from the base
ring.
- Volker Braun (2011-06): major cleanup, refcount singular rings, bugfixes.
"""
#*****************************************************************************
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
# The Singular API is as follows:
#
# pXXX does assume the currRing to be set
# p_XXX does not.
#
# However, sometimes there are bugs, i.e. you call p_XXX and it
# crashes unless currRing is set.
#
# Notable exceptions:
# * pNext and pIter don't need currRing
# * p_Normalize apparently needs currRing
from cpython.object cimport Py_NE
from cysignals.memory cimport sig_malloc, sig_free
from cysignals.signals cimport sig_on, sig_off
from sage.cpython.string cimport char_to_str, str_to_bytes
# singular types
from sage.libs.singular.decl cimport (ring, poly, ideal, intvec, number,
currRing, n_unknown, n_Z, n_Zn, n_Znm, n_Z2m, sBucket, sBucketCreate,
sBucketDestroy, sBucket_Merge_m, sBucketClearMerge, sBucketDeleteAndDestroy)
# singular functions
from sage.libs.singular.decl cimport (
errorreported,
n_IsUnit, n_Invers, n_GetChar,
p_ISet, rChangeCurrRing, p_Copy, p_Init, p_SetCoeff, p_Setm, p_SetExp, p_Add_q,
p_NSet, p_GetCoeff, p_Delete, p_GetExp, pNext, rRingVar, omAlloc0, omStrDup,
omFree, p_Divide, p_SetCoeff0, n_Init, p_DivisibleBy, pLcm, p_LmDivisibleBy,
pMDivide, p_MDivide, p_IsConstant, p_ExpVectorEqual, p_String, p_LmInit, n_Copy,
p_IsUnit, p_IsOne, p_Series, p_Head, idInit, fast_map_common_subexp, id_Delete,
p_IsHomogeneous, p_Homogen, p_Totaldegree,pLDeg1_Totaldegree, singclap_pdivide, singclap_factorize,
idLift, IDELEMS, On, Off, SW_USE_CHINREM_GCD, SW_USE_EZGCD,
p_LmIsConstant, pTakeOutComp1, singclap_gcd, pp_Mult_qq, p_GetMaxExp,
pLength, kNF, p_Neg, p_Minus_mm_Mult_qq, p_Plus_mm_Mult_qq,
pDiff, singclap_resultant, p_Normalize,
prCopyR, prCopyR_NoSort)
# singular conversion routines
from sage.libs.singular.singular cimport si2sa, sa2si, overflow_check
# singular poly arith
from sage.libs.singular.polynomial cimport (
singular_polynomial_call, singular_polynomial_cmp, singular_polynomial_add,
singular_polynomial_sub, singular_polynomial_neg, singular_polynomial_rmul,
singular_polynomial_mul, singular_polynomial_div_coeff, singular_polynomial_pow,
singular_polynomial_str, singular_polynomial_latex,
singular_polynomial_str_with_changed_varnames, singular_polynomial_deg,
singular_polynomial_length_bounded, singular_polynomial_subst )
# singular rings
from sage.libs.singular.ring cimport singular_ring_new, singular_ring_reference, singular_ring_delete
# polynomial imports
from sage.rings.polynomial.multi_polynomial_ring import MPolynomialRing_polydict, MPolynomialRing_polydict_domain
from sage.rings.polynomial.multi_polynomial_element import MPolynomial_polydict
from sage.rings.polynomial.multi_polynomial_ideal import MPolynomialIdeal
from sage.rings.polynomial.polydict cimport ETuple
from sage.rings.polynomial.polynomial_ring import is_PolynomialRing
# base ring imports
import sage.rings.abc
from sage.rings.finite_rings.finite_field_prime_modn import FiniteField_prime_modn
from sage.rings.rational cimport Rational
from sage.rings.rational_field import QQ
import sage.rings.abc
from sage.rings.integer_ring import is_IntegerRing, ZZ
from sage.rings.integer cimport Integer
from sage.rings.integer import GCD_list
from sage.rings.number_field.number_field_base cimport NumberField
from sage.rings.number_field.order import is_NumberFieldOrder
from sage.categories.number_fields import NumberFields
from sage.structure.element import coerce_binop
from sage.structure.parent cimport Parent
from sage.structure.category_object cimport CategoryObject
from sage.structure.coerce cimport coercion_model
from sage.structure.element cimport Element, CommutativeRingElement
from sage.structure.richcmp cimport rich_to_bool, richcmp
from sage.structure.factorization import Factorization
from sage.structure.sequence import Sequence
from sage.rings.fraction_field import FractionField
from sage.rings.all import RealField
import sage.interfaces.abc
from sage.misc.misc_c import prod as mul
from sage.misc.sage_eval import sage_eval
import sage.rings.polynomial.polynomial_singular_interface
cimport cypari2.gen
from . import polynomial_element
permstore=[]
cdef class MPolynomialRing_libsingular(MPolynomialRing_base):
def __cinit__(self):
"""
The Cython constructor.
EXAMPLES::
sage: from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular
sage: MPolynomialRing_libsingular(QQ, 3, ('x', 'y', 'z'), TermOrder('degrevlex', 3))
Multivariate Polynomial Ring in x, y, z over Rational Field
sage: type(_)
<class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomialRing_libsingular'>
sage: P.<x,y,z> = QQ[]; P
Multivariate Polynomial Ring in x, y, z over Rational Field
sage: type(P)
<class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomialRing_libsingular'>
"""
self._ring = NULL
def __init__(self, base_ring, n, names, order='degrevlex'):
"""
Construct a multivariate polynomial ring subject to the
following conditions:
INPUT:
- ``base_ring`` - base ring (must be either GF(q), ZZ, ZZ/nZZ,
QQ or absolute number field)
- ``n`` - number of variables (must be at least 1)
- ``names`` - names of ring variables, may be string of list/tuple
- ``order`` - term order (default: ``degrevlex``)
EXAMPLES::
sage: P.<x,y,z> = QQ[]
sage: P
Multivariate Polynomial Ring in x, y, z over Rational Field
sage: f = 27/113 * x^2 + y*z + 1/2; f
27/113*x^2 + y*z + 1/2
sage: P.term_order()
Degree reverse lexicographic term order
sage: P = PolynomialRing(GF(127),3,names='abc', order='lex')
sage: P
Multivariate Polynomial Ring in a, b, c over Finite Field of size 127
sage: a,b,c = P.gens()
sage: f = 57 * a^2*b + 43 * c + 1; f
57*a^2*b + 43*c + 1
sage: P.term_order()
Lexicographic term order
sage: z = QQ['z'].0
sage: K.<s> = NumberField(z^2 - 2)
sage: P.<x,y> = PolynomialRing(K, 2)
sage: 1/2*s*x^2 + 3/4*s
(1/2*s)*x^2 + (3/4*s)
sage: P.<x,y,z> = ZZ[]; P
Multivariate Polynomial Ring in x, y, z over Integer Ring
sage: P.<x,y,z> = Zmod(2^10)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 1024
sage: P.<x,y,z> = Zmod(3^10)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 59049
sage: P.<x,y,z> = Zmod(2^100)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 1267650600228229401496703205376
sage: P.<x,y,z> = Zmod(2521352)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 2521352
sage: type(P)
<class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomialRing_libsingular'>
sage: P.<x,y,z> = Zmod(25213521351515232)[]; P
Multivariate Polynomial Ring in x, y, z over Ring of integers modulo 25213521351515232
sage: type(P)
<class 'sage.rings.polynomial.multi_polynomial_ring.MPolynomialRing_polydict_with_category'>
sage: P.<x,y,z> = PolynomialRing(Integers(2^32),order='lex')
sage: P(2^32-1)
4294967295
TESTS:
Make sure that a faster coercion map from the base ring is used;
see :trac:`9944`::
sage: R.<x,y> = PolynomialRing(ZZ)
sage: R.coerce_map_from(R.base_ring())
Polynomial base injection morphism:
From: Integer Ring
To: Multivariate Polynomial Ring in x, y over Integer Ring
Check some invalid input::
sage: from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular
sage: MPolynomialRing_libsingular(Zmod(1), 1, ["x"], "lex")
Traceback (most recent call last):
...
NotImplementedError: polynomials over Ring of integers modulo 1 are not supported in Singular
sage: MPolynomialRing_libsingular(SR, 1, ["x"], "lex")
Traceback (most recent call last):
...
NotImplementedError: polynomials over Symbolic Ring are not supported in Singular
sage: MPolynomialRing_libsingular(QQ, 0, [], "lex")
Traceback (most recent call last):
...
NotImplementedError: polynomials in 0 variables are not supported in Singular
sage: MPolynomialRing_libsingular(QQ, -1, [], "lex")
Traceback (most recent call last):
...
NotImplementedError: polynomials in -1 variables are not supported in Singular
"""
self.__ngens = n
self._ring = singular_ring_new(base_ring, n, names, order)
self._zero_element = new_MP(self, NULL)
cdef MPolynomial_libsingular one = new_MP(self, p_ISet(1, self._ring))
self._one_element = one
self._one_element_poly = one._poly
MPolynomialRing_base.__init__(self, base_ring, n, names, order)
self._has_singular = True
#permanently store a reference to this ring until deallocation works reliably
permstore.append(self)
def __dealloc__(self):
r"""
Deallocate the ring without changing ``currRing``
TESTS:
This example caused a segmentation fault with a previous version
of this method::
sage: import gc
sage: from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular
sage: R1 = MPolynomialRing_libsingular(GF(5), 2, ('x', 'y'), TermOrder('degrevlex', 2))
sage: R2 = MPolynomialRing_libsingular(GF(11), 2, ('x', 'y'), TermOrder('degrevlex', 2))
sage: R3 = MPolynomialRing_libsingular(GF(13), 2, ('x', 'y'), TermOrder('degrevlex', 2))
sage: _ = gc.collect()
sage: foo = R1.gen(0)
sage: del foo
sage: del R1
sage: _ = gc.collect()
sage: del R2
sage: _ = gc.collect()
sage: del R3
sage: _ = gc.collect()
"""
if self._ring != NULL: # the constructor did not raise an exception
singular_ring_delete(self._ring)
def __copy__(self):
"""
Copy ``self``.
The ring is unique and immutable, so we do not copy.
TESTS::
sage: import gc
sage: from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular
sage: from sage.libs.singular.ring import ring_refcount_dict
sage: gc.collect() # random output
sage: n = len(ring_refcount_dict)
sage: R = MPolynomialRing_libsingular(GF(547), 2, ('x', 'y'), TermOrder('degrevlex', 2))
sage: len(ring_refcount_dict) == n + 1
True
sage: Q = copy(R) # indirect doctest
sage: p = R.gen(0) ^2+R.gen(1)^2
sage: q = copy(p)
sage: del R
sage: del Q
sage: del p
sage: del q
sage: gc.collect() # random output
sage: len(ring_refcount_dict) == n
False
"""
return self
def __deepcopy__(self, memo):
"""
Deep copy ``self``.
The ring should be immutable, so we do not copy.
TESTS::
sage: R.<x,y> = GF(547)[]
sage: R is deepcopy(R) # indirect doctest
True
"""
memo[id(self)] = self
return self
cpdef _coerce_map_from_(self, other):
"""
Return True if and only if there exists a coercion map from
``other`` to ``self``.
TESTS::
sage: R.<x,y> = QQ[]
sage: type(R)
<class 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomialRing_libsingular'>
sage: R.has_coerce_map_from(ZZ['t'])
False
sage: R.coerce_map_from(ZZ['x'])
Coercion map:
From: Univariate Polynomial Ring in x over Integer Ring
To: Multivariate Polynomial Ring in x, y over Rational Field
"""
base_ring = self.base_ring()
if other is base_ring:
# Because this parent class is a Cython class, the method
# UnitalAlgebras.ParentMethods.__init_extra__(), which normally
# registers the coercion map from the base ring, is called only
# when inheriting from this class in Python (cf. Trac #26958).
return self._coerce_map_from_base_ring()
f = self._coerce_map_via([base_ring], other)
if f is not None:
return f
if isinstance(other, MPolynomialRing_libsingular):
if self is other:
return True
n = other.ngens()
if(other.base_ring is base_ring and self.ngens() >= n and
self.variable_names()[:n] == other.variable_names()):
return True
elif base_ring.has_coerce_map_from(other._mpoly_base_ring(self.variable_names())):
return True
elif isinstance(other, MPolynomialRing_polydict):
if self == other:
return True
elif other.ngens() == 0:
return True
elif base_ring.has_coerce_map_from(other._mpoly_base_ring(self.variable_names())):
return True
elif is_PolynomialRing(other):
if base_ring.has_coerce_map_from(other._mpoly_base_ring(self.variable_names())):
return True
Element = MPolynomial_libsingular
def _element_constructor_(self, element, check=True):
"""
Construct a new element in this polynomial ring by converting
``element`` into ``self`` if possible.
INPUT:
- ``element`` -- several types are supported, see below
EXAMPLES::
sage: P.<x,y,z> = QQ[]
We can coerce elements of self to self::
sage: P.coerce(x*y + 1/2)
x*y + 1/2
We can coerce elements for a ring with the same algebraic properties::
sage: from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular
sage: R.<x,y,z> = MPolynomialRing_libsingular(QQ,3)
sage: P == R
True
sage: P is R
False
sage: P.coerce(x*y + 1)
x*y + 1
We can coerce base ring elements::
sage: P.coerce(3/2)
3/2
and all kinds of integers::
sage: P.coerce(ZZ(1))
1
sage: P.coerce(int(1))
1
sage: k.<a> = GF(2^8)
sage: P.<x,y> = PolynomialRing(k,2)
sage: P.coerce(a)
a
sage: z = QQ['z'].0
sage: K.<s> = NumberField(z^2 - 2)
sage: P.<x,y> = PolynomialRing(K, 2)
sage: P.coerce(1/2*s)
(1/2*s)
TESTS::
sage: P.<x,y> = PolynomialRing(GF(127))
sage: P("111111111111111111111111111111111111111111111111111111111")
21
sage: P.<x,y> = PolynomialRing(QQ)
sage: P("111111111111111111111111111111111111111111111111111111111")
111111111111111111111111111111111111111111111111111111111
sage: P("31367566080")
31367566080
Check if :trac:`7582` is fixed::
sage: R.<x,y,z> = PolynomialRing(CyclotomicField(2),3)
sage: R.coerce(1)
1
Check if :trac:`6160` is fixed::
sage: x=var('x')
sage: K.<j> = NumberField(x-1728)
sage: R.<b,c> = K[]
sage: R.coerce(1)
1
Check if coercion from zero variable polynomial rings work
(:trac:`7951`)::
sage: P = PolynomialRing(QQ,0,'')
sage: R.<x,y> = QQ[]
sage: P(5)*x
5*x
sage: P = PolynomialRing(ZZ,0,'')
sage: R.<x,y> = GF(127)[]
sage: R.coerce(P(5))
5
Conversion from strings::
sage: P.<x,y,z> = QQ[]
sage: P('x+y + 1/4')
x + y + 1/4
Coercion from SINGULAR elements::
sage: P._singular_()
polynomial ring, over a field, global ordering
// coefficients: QQ
// number of vars : 3
// block 1 : ordering dp
// : names x y z
// block 2 : ordering C
sage: P._singular_().set_ring()
sage: P(singular('x + 3/4'))
x + 3/4
Coercion from symbolic variables::
sage: R = QQ['x,y,z']
sage: var('x')
x
sage: R(x)
x
Coercion from 'similar' rings, which maps by index::
sage: P.<x,y,z> = QQ[]
sage: R.<a,b,c> = ZZ[]
sage: P(a)
x
::
sage: P.<x,y> = QQ[]
sage: R.<a,b,c> = QQ[]
sage: R(x)
a
Coercion from PARI objects::
sage: P.<x,y,z> = QQ[]
sage: P(pari('x^2 + y'))
x^2 + y
sage: P(pari('x*y'))
x*y
Coercion from boolean polynomials, also by index::
sage: B.<x,y,z> = BooleanPolynomialRing(3)
sage: P.<x,y,z> = QQ[]
sage: P(B.gen(0))
x
If everything else fails, we try to convert to the base ring::
sage: R.<x,y,z> = GF(3)[]
sage: R(1/2)
-1
Finally, conversions from other polynomial rings which are not
coercions are provided. Variables are mapped as follows. Say,
we are mapping an element from `P` to `Q` (this ring). If the
variables of `P` are a subset of `Q`, we perform a name
preserving conversion::
sage: P.<y_2, y_1, z_3, z_2, z_1> = GF(3)[]
sage: Q = GF(3)['y_4', 'y_3', 'y_2', 'y_1', 'z_5', 'z_4', 'z_3', 'z_2', 'z_1']
sage: Q(y_1*z_2^2*z_1)
y_1*z_2^2*z_1
Otherwise, if `P` has less than or equal the number of
variables as `Q`, we perform a conversion by index::
sage: P.<a,b,c> = GF(2)[]
sage: Q = GF(2)['c','b','d','e']
sage: f = Q.convert_map_from(P)
sage: f(a), f(b), f(c)
(c, b, d)
::
sage: P.<a,b,c> = GF(2)[]
sage: Q = GF(2)['c','b','d']
sage: f = Q.convert_map_from(P)
sage: f(a),f(b),f(c)
(c, b, d)
In all other cases, we fail::
sage: P.<a,b,c,f> = GF(2)[]
sage: Q = GF(2)['c','d','e']
sage: f = Q.convert_map_from(P)
sage: f(a)
Traceback (most recent call last):
...
TypeError: Could not find a mapping of the passed element to this ring.
Coerce in a polydict where a coefficient reduces to 0 but isn't 0. ::
sage: R.<x,y> = QQ[]; S.<xx,yy> = GF(5)[]; S( (5*x*y + x + 17*y)._mpoly_dict_recursive() )
xx + 2*yy
Coerce in a polynomial one of whose coefficients reduces to 0. ::
sage: R.<x,y> = QQ[]; S.<xx,yy> = GF(5)[]; S(5*x*y + x + 17*y)
xx + 2*yy
Some other examples that illustrate the same coercion idea::
sage: R.<x,y> = ZZ[]
sage: S.<xx,yy> = GF(25,'a')[]
sage: S(5*x*y + x + 17*y)
xx + 2*yy
sage: S.<xx,yy> = Integers(5)[]
sage: S(5*x*y + x + 17*y)
xx + 2*yy
See :trac:`5292`::
sage: R.<x> = QQ[]; S.<q,t> = QQ[]; F = FractionField(S)
sage: x in S
False
sage: x in F
False
Check if :trac:`8228` is fixed::
sage: P.<x,y> = Zmod(10)[]; P(0)
0
sage: P.<x,y> = Zmod(2^10)[]; P(0)
0
And :trac:`7597` is fixed if this does not segfault::
sage: F2 = GF(2)
sage: F.<x> = GF(2^8)
sage: R4.<a,b> = PolynomialRing(F)
sage: R.<u,v> = PolynomialRing(F2)
sage: P = a
sage: (P(0,0).polynomial()[0])*u
0
sage: P(a,b)
a
Check that :trac:`15746` is fixed::
sage: R.<x,y> = GF(7)[]
sage: R(2^31)
2
Check that :trac:`17964` is fixed::
sage: K.<a> = QuadraticField(17)
sage: Q.<x,y> = K[]
sage: f = (-3*a)*y + (5*a)
sage: p = K.primes_above(5)[0]
sage: R = K.residue_field(p)
sage: S = R['x','y']
sage: S(f)
(2*abar)*y
Check that creating element from strings works for transcendental extensions::
sage: T.<c,d> = QQ[]
sage: F = FractionField(T)
sage: R.<x,y,z> = F[]
sage: R('d*z+x^2*y')
x^2*y + d*z
"""
cdef poly *_p
cdef poly *mon
cdef poly *El_poly
cdef ring *_ring = self._ring
cdef ring *El_ring
cdef MPolynomial_libsingular Element
cdef MPolynomialRing_libsingular El_parent
cdef int i, j
cdef int e
cdef list ind_map = []
cdef sBucket *bucket
if _ring != currRing: rChangeCurrRing(_ring)
base_ring = self._base
if isinstance(element, MPolynomial_libsingular):
Element = <MPolynomial_libsingular>element
El_parent = Element._parent
if El_parent is self:
return element
El_poly = Element._poly
El_ring = Element._parent_ring
El_base = El_parent._base
El_n = El_parent.ngens()
if (base_ring is El_base and self.ngens() >= El_n
and self.variable_names()[:El_n] == El_parent.variable_names()):
if self.term_order() == El_parent.term_order():
_p = prCopyR_NoSort(El_poly, El_ring, _ring)
else:
_p = prCopyR(El_poly, El_ring, _ring)
return new_MP(self, _p)
variable_names_t = self.variable_names()
if base_ring.has_coerce_map_from(El_parent._mpoly_base_ring(variable_names_t)):
return self(element._mpoly_dict_recursive(variable_names_t, base_ring))
else:
variable_names_s = El_parent.variable_names()
if set(variable_names_s).issubset(variable_names_t):
for v in variable_names_s:
ind_map.append(variable_names_t.index(v)+1)
else:
ind_map = [i+1 for i in range(_ring.N)]
if El_n <= self.ngens():
# Map the variables by indices
_p = p_ISet(0, _ring)
#this loop needs improvement
while El_poly:
c = si2sa(p_GetCoeff(El_poly, El_ring), El_ring, El_base)
if check:
try:
c = base_ring(c)
except TypeError:
p_Delete(&_p, _ring)
raise
if c:
mon = p_Init(_ring)
p_SetCoeff(mon, sa2si(c, _ring), _ring)
for j from 1 <= j <= El_ring.N:
e = p_GetExp(El_poly, j, El_ring)
if e:
p_SetExp(mon, ind_map[j-1], e, _ring)
p_Setm(mon, _ring)
_p = p_Add_q(_p, mon, _ring)
El_poly = pNext(El_poly)
return new_MP(self, _p)
elif isinstance(element, MPolynomial_polydict):
if element.parent() == self:
bucket = sBucketCreate(_ring)
try:
for (m,c) in element.element().dict().iteritems():
mon = p_Init(_ring)
p_SetCoeff(mon, sa2si(c, _ring), _ring)
for pos in m.nonzero_positions():
overflow_check(m[pos], _ring)
p_SetExp(mon, pos+1, m[pos], _ring)
p_Setm(mon, _ring)
#we can use "_m" because we're merging a monomial and
#"Merge" because this monomial is different from the rest
sBucket_Merge_m(bucket, mon)
e=0
#we can use "Merge" because the monomials are distinct
sBucketClearMerge(bucket, &_p, &e)
sBucketDestroy(&bucket)
except Exception:
sBucketDeleteAndDestroy(&bucket)
raise
return new_MP(self, _p)
elif element.parent().ngens() == 0:
# zero variable polynomials
_p = p_NSet(sa2si(base_ring(element[tuple()]), _ring),
_ring)
return new_MP(self, _p)
elif base_ring.has_coerce_map_from(element.parent()._mpoly_base_ring(self.variable_names())):
return self(element._mpoly_dict_recursive(self.variable_names(), base_ring))
else:
variable_names_s = element.parent().variable_names()
variable_names_t = self.variable_names()
if set(variable_names_s).issubset(variable_names_t):
for v in variable_names_s:
ind_map.append(variable_names_t.index(v)+1)
else:
ind_map = [i+1 for i in range(_ring.N)]
if element.parent().ngens() <= self.ngens():
bucket = sBucketCreate(_ring)
try:
for (m,c) in element.element().dict().iteritems():
if check:
c = base_ring(c)
if not c:
continue
mon = p_Init(_ring)
p_SetCoeff(mon, sa2si(c , _ring), _ring)
for pos in m.nonzero_positions():
overflow_check(m[pos], _ring)
p_SetExp(mon, ind_map[pos], m[pos], _ring)
p_Setm(mon, _ring)
sBucket_Merge_m(bucket, mon)
e=0
sBucketClearMerge(bucket, &_p, &e)
sBucketDestroy(&bucket)
except TypeError:
sBucketDeleteAndDestroy(&bucket)
raise
return new_MP(self, _p)
elif isinstance(element, polynomial_element.Polynomial):
if base_ring.has_coerce_map_from(element.parent()._mpoly_base_ring(self.variable_names())):
return self(element._mpoly_dict_recursive(self.variable_names(), base_ring))
elif isinstance(element, dict):
if not element:
_p = p_ISet(0, _ring)
else:
bucket = sBucketCreate(_ring)
try:
for (m,c) in element.iteritems():
if check:
c = base_ring(c)
if not c:
continue
mon = p_Init(_ring)
p_SetCoeff(mon, sa2si(c , _ring), _ring)
if len(m) != self.ngens():
raise TypeError("tuple key must have same length as ngens")
for pos from 0 <= pos < len(m):
if m[pos]:
overflow_check(m[pos], _ring)
p_SetExp(mon, pos+1, m[pos], _ring)
p_Setm(mon, _ring)
sBucket_Merge_m(bucket, mon)
e=0
sBucketClearMerge(bucket, &_p, &e)
sBucketDestroy(&bucket)
except TypeError:
sBucketDeleteAndDestroy(&bucket)
raise
return new_MP(self, _p)
from sage.rings.polynomial.pbori.pbori import BooleanPolynomial
if isinstance(element, BooleanPolynomial):
if element.constant():
if element:
return self._one_element
else:
return self._zero_element
variable_names_s = set(element.parent().variable_names())
variable_names_t = self.variable_names()
if variable_names_s.issubset(variable_names_t):
return eval(str(element),self.gens_dict(copy=False))
elif element.parent().ngens() <= self.ngens():
Q = element.parent()
gens_map = dict(zip(Q.variable_names(),self.gens()[:Q.ngens()]))
return eval(str(element),gens_map)
if isinstance(element, (sage.interfaces.abc.SingularElement, cypari2.gen.Gen)):
element = str(element)
elif isinstance(element, sage.interfaces.abc.Macaulay2Element):
element = element.external_string()
if isinstance(element, str):
# let python do the parsing
d = self.gens_dict()
if self.base_ring().gen() != 1:
if hasattr(self.base_ring(), 'gens'):
for gen in self.base_ring().gens():
d[str(gen)] = gen
else:
d[str(self.base_ring().gen())] = self.base_ring_gen()
try:
if '/' in element:
element = sage_eval(element,d)
else:
element = element.replace("^","**")
element = eval(element, d, {})
except (SyntaxError, NameError):
raise TypeError("Could not find a mapping of the passed element to this ring.")
# we need to do this, to make sure that we actually get an
# element in self.
return self.coerce(element)
if hasattr(element,'_polynomial_'): # symbolic.expression.Expression
return element._polynomial_(self)