This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
multi_polynomial.pyx
2017 lines (1653 loc) · 68.3 KB
/
multi_polynomial.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"""
Base class for elements of multivariate polynomial rings
"""
#*****************************************************************************
# 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/
#*****************************************************************************
from __future__ import print_function
from sage.rings.integer cimport Integer
from sage.rings.integer_ring import ZZ
from sage.structure.element cimport coercion_model
from sage.misc.derivative import multi_derivative
from sage.rings.infinity import infinity
from sage.structure.element cimport Element
from sage.misc.all import prod
def is_MPolynomial(x):
return isinstance(x, MPolynomial)
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.categories.map cimport Map
from sage.categories.morphism cimport Morphism
from sage.modules.free_module_element import vector
from sage.rings.rational_field import QQ
from sage.arith.misc import gcd
from sage.rings.complex_interval_field import ComplexIntervalField
from sage.rings.real_mpfr import RealField_class,RealField
cdef class MPolynomial(CommutativeRingElement):
####################
# Some standard conversions
####################
def __int__(self):
"""
TESTS::
sage: type(RR['x,y'])
<class 'sage.rings.polynomial.multi_polynomial_ring.MPolynomialRing_polydict_domain_with_category'>
sage: type(RR['x, y'](0))
<class 'sage.rings.polynomial.multi_polynomial_element.MPolynomial_polydict'>
sage: int(RR['x,y'](0)) # indirect doctest
0
sage: int(RR['x,y'](10))
10
sage: int(RR['x,y'].gen())
Traceback (most recent call last):
...
TypeError...
"""
if self.degree() <= 0:
return int(self.constant_coefficient())
else:
raise TypeError
def __long__(self):
"""
TESTS::
sage: long(RR['x,y'](0)) # indirect doctest
0L
"""
if self.degree() <= 0:
return long(self.constant_coefficient())
else:
raise TypeError
def __float__(self):
"""
TESTS::
sage: float(RR['x,y'](0)) # indirect doctest
0.0
"""
if self.degree() <= 0:
return float(self.constant_coefficient())
else:
raise TypeError
def _mpfr_(self, R):
"""
TESTS::
sage: RR(RR['x,y'](0)) # indirect doctest
0.000000000000000
"""
if self.degree() <= 0:
return R(self.constant_coefficient())
else:
raise TypeError
def _complex_mpfr_field_(self, R):
"""
TESTS::
sage: CC(RR['x,y'](0)) # indirect doctest
0.000000000000000
"""
if self.degree() <= 0:
return R(self.constant_coefficient())
else:
raise TypeError
def _complex_double_(self, R):
"""
TESTS::
sage: CDF(RR['x,y'](0)) # indirect doctest
0.0
"""
if self.degree() <= 0:
return R(self.constant_coefficient())
else:
raise TypeError
def _real_double_(self, R):
"""
TESTS::
sage: RR(RR['x,y'](0)) # indirect doctest
0.000000000000000
"""
if self.degree() <= 0:
return R(self.constant_coefficient())
else:
raise TypeError
def _rational_(self):
"""
TESTS::
sage: QQ(RR['x,y'](0)) # indirect doctest
0
sage: QQ(RR['x,y'](0.5)) # indirect doctest
Traceback (most recent call last):
...
TypeError...
"""
if self.degree() <= 0:
from sage.rings.rational import Rational
return Rational(repr(self))
else:
raise TypeError
def _integer_(self, ZZ=None):
"""
TESTS::
sage: ZZ(RR['x,y'](0)) # indirect doctest
0
sage: ZZ(RR['x,y'](0.0))
0
sage: ZZ(RR['x,y'](0.5))
Traceback (most recent call last):
...
TypeError...
"""
if self.degree() <= 0:
from sage.rings.integer import Integer
return Integer(repr(self))
else:
raise TypeError
def _symbolic_(self, R):
"""
EXAMPLES::
sage: R.<x,y> = QQ[]
sage: f = x^3 + y
sage: g = f._symbolic_(SR); g
x^3 + y
sage: g(x=2,y=2)
10
sage: g = SR(f)
sage: g(x=2,y=2)
10
"""
d = dict([(repr(g), R.var(g)) for g in self.parent().gens()])
return self.subs(**d)
def _polynomial_(self, R):
var = R.variable_name()
if var in self._parent.variable_names():
return R(self.polynomial(self._parent(var)))
else:
return R([self])
def coefficients(self):
"""
Return the nonzero coefficients of this polynomial in a list.
The returned list is decreasingly ordered by the term ordering
of ``self.parent()``, i.e. the list of coefficients matches the list
of monomials returned by
:meth:`sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular.monomials`.
EXAMPLES::
sage: R.<x,y,z> = PolynomialRing(QQ,3,order='degrevlex')
sage: f=23*x^6*y^7 + x^3*y+6*x^7*z
sage: f.coefficients()
[23, 6, 1]
sage: R.<x,y,z> = PolynomialRing(QQ,3,order='lex')
sage: f=23*x^6*y^7 + x^3*y+6*x^7*z
sage: f.coefficients()
[6, 23, 1]
Test the same stuff with base ring `\ZZ` -- different implementation::
sage: R.<x,y,z> = PolynomialRing(ZZ,3,order='degrevlex')
sage: f=23*x^6*y^7 + x^3*y+6*x^7*z
sage: f.coefficients()
[23, 6, 1]
sage: R.<x,y,z> = PolynomialRing(ZZ,3,order='lex')
sage: f=23*x^6*y^7 + x^3*y+6*x^7*z
sage: f.coefficients()
[6, 23, 1]
AUTHOR:
- Didier Deshommes
"""
degs = self.exponents()
d = self.dict()
return [ d[i] for i in degs ]
def truncate(self, var, n):
"""
Returns a new multivariate polynomial obtained from self by
deleting all terms that involve the given variable to a power
at least n.
"""
cdef int ind
R = self.parent()
G = R.gens()
Z = list(G)
try:
ind = Z.index(var)
except ValueError:
raise ValueError("var must be one of the generators of the parent polynomial ring.")
d = self.dict()
return R(dict([(k, c) for k, c in d.iteritems() if k[ind] < n]))
def _fast_float_(self, *vars):
"""
Returns a quickly-evaluating function on floats.
EXAMPLES::
sage: K.<x,y,z> = QQ[]
sage: f = (x+2*y+3*z^2)^2 + 42
sage: f(1, 10, 100)
901260483
sage: ff = f._fast_float_()
sage: ff(0, 0, 1)
51.0
sage: ff(0, 1, 0)
46.0
sage: ff(1, 10, 100)
901260483.0
sage: ff_swapped = f._fast_float_('z', 'y', 'x')
sage: ff_swapped(100, 10, 1)
901260483.0
sage: ff_extra = f._fast_float_('x', 'A', 'y', 'B', 'z', 'C')
sage: ff_extra(1, 7, 10, 13, 100, 19)
901260483.0
Currently, we use a fairly unoptimized method that evaluates one
monomial at a time, with no sharing of repeated computations and
with useless additions of 0 and multiplications by 1::
sage: list(ff)
['push 0.0', 'push 12.0', 'load 1', 'load 2', 'dup', 'mul', 'mul', 'mul', 'add', 'push 4.0', 'load 0', 'load 1', 'mul', 'mul', 'add', 'push 42.0', 'add', 'push 1.0', 'load 0', 'dup', 'mul', 'mul', 'add', 'push 9.0', 'load 2', 'dup', 'mul', 'dup', 'mul', 'mul', 'add', 'push 6.0', 'load 0', 'load 2', 'dup', 'mul', 'mul', 'mul', 'add', 'push 4.0', 'load 1', 'dup', 'mul', 'mul', 'add']
TESTS::
sage: from sage.ext.fast_eval import fast_float
sage: list(fast_float(K(0), old=True))
['push 0.0']
sage: list(fast_float(K(17), old=True))
['push 0.0', 'push 17.0', 'add']
sage: list(fast_float(y, old=True))
['push 0.0', 'push 1.0', 'load 1', 'mul', 'add']
"""
from sage.ext.fast_eval import fast_float_arg, fast_float_constant
my_vars = self.parent().variable_names()
vars = list(vars)
if len(vars) == 0:
indices = range(len(my_vars))
else:
indices = [vars.index(v) for v in my_vars]
x = [fast_float_arg(i) for i in indices]
n = len(x)
expr = fast_float_constant(0)
for (m,c) in self.dict().iteritems():
monom = prod([ x[i]**m[i] for i in range(n) if m[i] != 0], fast_float_constant(c))
expr = expr + monom
return expr
def _fast_callable_(self, etb):
"""
Given an ExpressionTreeBuilder, return an Expression representing
this value.
EXAMPLES::
sage: from sage.ext.fast_callable import ExpressionTreeBuilder
sage: etb = ExpressionTreeBuilder(vars=['x','y','z'])
sage: K.<x,y,z> = QQ[]
sage: v = K.random_element(degree=3, terms=4); v
-6/5*x*y*z + 2*y*z^2 - x
sage: v._fast_callable_(etb)
add(add(add(0, mul(-6/5, mul(mul(ipow(v_0, 1), ipow(v_1, 1)), ipow(v_2, 1)))), mul(2, mul(ipow(v_1, 1), ipow(v_2, 2)))), mul(-1, ipow(v_0, 1)))
TESTS::
sage: v = K(0)
sage: vf = fast_callable(v)
sage: type(v(0r, 0r, 0r))
<type 'sage.rings.rational.Rational'>
sage: type(vf(0r, 0r, 0r))
<type 'sage.rings.rational.Rational'>
sage: K.<x,y,z> = QQ[]
sage: from sage.ext.fast_eval import fast_float
sage: fast_float(K(0)).op_list()
[('load_const', 0.0), 'return']
sage: fast_float(K(17)).op_list()
[('load_const', 0.0), ('load_const', 17.0), 'add', 'return']
sage: fast_float(y).op_list()
[('load_const', 0.0), ('load_const', 1.0), ('load_arg', 1), ('ipow', 1), 'mul', 'add', 'return']
"""
my_vars = self.parent().variable_names()
x = [etb.var(v) for v in my_vars]
n = len(x)
expr = etb.constant(self.base_ring()(0))
for (m, c) in self.dict().iteritems():
monom = prod([ x[i]**m[i] for i in range(n) if m[i] != 0],
etb.constant(c))
expr = expr + monom
return expr
def derivative(self, *args):
r"""
The formal derivative of this polynomial, with respect to
variables supplied in args.
Multiple variables and iteration counts may be supplied; see
documentation for the global derivative() function for more details.
.. seealso:: :meth:`._derivative`
EXAMPLES:
Polynomials implemented via Singular::
sage: R.<x, y> = PolynomialRing(FiniteField(5))
sage: f = x^3*y^5 + x^7*y
sage: type(f)
<type 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular'>
sage: f.derivative(x)
2*x^6*y - 2*x^2*y^5
sage: f.derivative(y)
x^7
Generic multivariate polynomials::
sage: R.<t> = PowerSeriesRing(QQ)
sage: S.<x, y> = PolynomialRing(R)
sage: f = (t^2 + O(t^3))*x^2*y^3 + (37*t^4 + O(t^5))*x^3
sage: type(f)
<class 'sage.rings.polynomial.multi_polynomial_element.MPolynomial_polydict'>
sage: f.derivative(x) # with respect to x
(2*t^2 + O(t^3))*x*y^3 + (111*t^4 + O(t^5))*x^2
sage: f.derivative(y) # with respect to y
(3*t^2 + O(t^3))*x^2*y^2
sage: f.derivative(t) # with respect to t (recurses into base ring)
(2*t + O(t^2))*x^2*y^3 + (148*t^3 + O(t^4))*x^3
sage: f.derivative(x, y) # with respect to x and then y
(6*t^2 + O(t^3))*x*y^2
sage: f.derivative(y, 3) # with respect to y three times
(6*t^2 + O(t^3))*x^2
sage: f.derivative() # can't figure out the variable
Traceback (most recent call last):
...
ValueError: must specify which variable to differentiate with respect to
Polynomials over the symbolic ring (just for fun....)::
sage: x = var("x")
sage: S.<u, v> = PolynomialRing(SR)
sage: f = u*v*x
sage: f.derivative(x) == u*v
True
sage: f.derivative(u) == v*x
True
"""
return multi_derivative(self, args)
def polynomial(self, var):
"""
Let var be one of the variables of the parent of self. This
returns self viewed as a univariate polynomial in var over the
polynomial ring generated by all the other variables of the parent.
EXAMPLES::
sage: R.<x,w,z> = QQ[]
sage: f = x^3 + 3*w*x + w^5 + (17*w^3)*x + z^5
sage: f.polynomial(x)
x^3 + (17*w^3 + 3*w)*x + w^5 + z^5
sage: parent(f.polynomial(x))
Univariate Polynomial Ring in x over Multivariate Polynomial Ring in w, z over Rational Field
sage: f.polynomial(w)
w^5 + 17*x*w^3 + 3*x*w + z^5 + x^3
sage: f.polynomial(z)
z^5 + w^5 + 17*x*w^3 + x^3 + 3*x*w
sage: R.<x,w,z,k> = ZZ[]
sage: f = x^3 + 3*w*x + w^5 + (17*w^3)*x + z^5 +x*w*z*k + 5
sage: f.polynomial(x)
x^3 + (17*w^3 + w*z*k + 3*w)*x + w^5 + z^5 + 5
sage: f.polynomial(w)
w^5 + 17*x*w^3 + (x*z*k + 3*x)*w + z^5 + x^3 + 5
sage: f.polynomial(z)
z^5 + x*w*k*z + w^5 + 17*x*w^3 + x^3 + 3*x*w + 5
sage: f.polynomial(k)
x*w*z*k + w^5 + z^5 + 17*x*w^3 + x^3 + 3*x*w + 5
sage: R.<x,y>=GF(5)[]
sage: f=x^2+x+y
sage: f.polynomial(x)
x^2 + x + y
sage: f.polynomial(y)
y + x^2 + x
"""
cdef int ind
R = self.parent()
G = R.gens()
Z = list(G)
try:
ind = Z.index(var)
except ValueError:
raise ValueError("var must be one of the generators of the parent polynomial ring.")
if R.ngens() <= 1:
return self.univariate_polynomial()
other_vars = Z
del other_vars[ind]
# Make polynomial ring over all variables except var.
S = R.base_ring()[tuple(other_vars)]
ring = S[var]
if not self:
return ring(0)
d = self.degree(var)
B = ring.base_ring()
w = dict([(remove_from_tuple(e, ind), val) for e, val in self.dict().iteritems() if not e[ind]])
v = [B(w)] # coefficients that don't involve var
z = var
for i in range(1,d+1):
c = self.coefficient(z).dict()
w = dict([(remove_from_tuple(e, ind), val) for e, val in c.iteritems()])
v.append(B(w))
z *= var
return ring(v)
def _mpoly_dict_recursive(self, vars=None, base_ring=None):
"""
Return a dict of coefficient entries suitable for construction of a MPolynomial_polydict
with the given variables.
EXAMPLES::
sage: R = Integers(10)['x,y,z']['t,s']
sage: t,s = R.gens()
sage: x,y,z = R.base_ring().gens()
sage: (x+y+2*z*s+3*t)._mpoly_dict_recursive(['z','t','s'])
{(0, 0, 0): x + y, (0, 1, 0): 3, (1, 0, 1): 2}
TESTS::
sage: R = Qp(7)['x,y,z,t,p']; S = ZZ['x,z,t']['p']
sage: R(S.0)
p
sage: R = QQ['x,y,z,t,p']; S = ZZ['x']['y,z,t']['p']
sage: z = S.base_ring().gen(1)
sage: R(z)
z
sage: R = QQ['x,y,z,t,p']; S = ZZ['x']['y,z,t']['p']
sage: z = S.base_ring().gen(1); p = S.0; x = S.base_ring().base_ring().gen()
sage: R(z+p)
z + p
sage: R = Qp(7)['x,y,z,p']; S = ZZ['x']['y,z,t']['p'] # shouldn't work, but should throw a better error
sage: R(S.0)
p
See :trac:`2601`::
sage: R.<a,b,c> = PolynomialRing(QQ, 3)
sage: a._mpoly_dict_recursive(['c', 'b', 'a'])
{(0, 0, 1): 1}
sage: testR.<a,b,c> = PolynomialRing(QQ,3)
sage: id_ringA = ideal([a^2-b,b^2-c,c^2-a])
sage: id_ringB = ideal(id_ringA.gens()).change_ring(PolynomialRing(QQ,'c,b,a'))
"""
from polydict import ETuple
if not self:
return {}
if vars is None:
vars = self.parent().variable_names_recursive()
vars = list(vars)
my_vars = self.parent().variable_names()
if vars == list(my_vars):
return self.dict()
elif not my_vars[-1] in vars:
x = base_ring(self) if base_ring is not None else self
const_ix = ETuple((0,)*len(vars))
return { const_ix: x }
elif not set(my_vars).issubset(set(vars)):
# we need to split it up
return self.polynomial(self.parent().gen(len(my_vars)-1))._mpoly_dict_recursive(vars, base_ring)
else:
D = {}
m = min([vars.index(z) for z in my_vars])
prev_vars = vars[:m]
var_range = range(len(my_vars))
if len(prev_vars) > 0:
mapping = [vars.index(v) - len(prev_vars) for v in my_vars]
tmp = [0] * (len(vars) - len(prev_vars))
try:
for ix,a in self.dict().iteritems():
for k in var_range:
tmp[mapping[k]] = ix[k]
postfix = ETuple(tmp)
mpoly = a._mpoly_dict_recursive(prev_vars, base_ring)
for prefix,b in mpoly.iteritems():
D[prefix+postfix] = b
return D
except AttributeError:
pass
if base_ring is self.base_ring():
base_ring = None
mapping = [vars.index(v) for v in my_vars]
tmp = [0] * len(vars)
for ix,a in self.dict().iteritems():
for k in var_range:
tmp[mapping[k]] = ix[k]
if base_ring is not None:
a = base_ring(a)
D[ETuple(tmp)] = a
return D
cdef long _hash_c(self) except -1:
"""
This hash incorporates the variable name in an effort to respect the obvious inclusions
into multi-variable polynomial rings.
The tuple algorithm is borrowed from http://effbot.org/zone/python-hash.htm.
EXAMPLES::
sage: T.<y>=QQ[]
sage: R.<x>=ZZ[]
sage: S.<x,y>=ZZ[]
sage: hash(S.0)==hash(R.0) # respect inclusions into mpoly rings (with matching base rings)
True
sage: hash(S.1)==hash(T.0) # respect inclusions into mpoly rings (with unmatched base rings)
True
sage: hash(S(12))==hash(12) # respect inclusions of the integers into an mpoly ring
True
sage: # the point is to make for more flexible dictionary look ups
sage: d={S.0:12}
sage: d[R.0]
12
sage: # or, more to the point, make subs in fraction field elements work
sage: f=x/y
sage: f.subs({x:1})
1/y
TESTS:
Verify that :trac:`16251` has been resolved, i.e., polynomials with
unhashable coefficients are unhashable::
sage: K.<a> = Qq(9)
sage: R.<t,s> = K[]
sage: hash(t)
Traceback (most recent call last):
...
TypeError: unhashable type: 'sage.rings.padics.qadic_flint_CR.qAdicCappedRelativeElement'
"""
cdef long result = 0 # store it in a c-int and just let the overflowing additions wrap
cdef long result_mon
var_name_hash = [hash(v) for v in self._parent.variable_names()]
cdef long c_hash
for m,c in self.dict().iteritems():
# I'm assuming (incorrectly) that hashes of zero indicate that the element is 0.
# This assumption is not true, but I think it is true enough for the purposes and it
# it allows us to write fast code that omits terms with 0 coefficients. This is
# important if we want to maintain the '==' relationship with sparse polys.
c_hash = hash(c)
if c_hash != 0: # this is always going to be true, because we are sparse (correct?)
# Hash (self[i], gen_a, exp_a, gen_b, exp_b, gen_c, exp_c, ...) as a tuple according to the algorithm.
# I omit gen,exp pairs where the exponent is zero.
result_mon = c_hash
for p in m.nonzero_positions():
result_mon = (1000003 * result_mon) ^ var_name_hash[p]
result_mon = (1000003 * result_mon) ^ m[p]
result += result_mon
if result == -1:
return -2
return result
# you may have to replicate this boilerplate code in derived classes if you override
# __richcmp__. The python documentation at http://docs.python.org/api/type-structs.html
# explains how __richcmp__, __hash__, and __cmp__ are tied together.
def __hash__(self):
return self._hash_c()
def args(self):
r"""
Returns the named of the arguments of self, in the
order they are accepted from call.
EXAMPLES::
sage: R.<x,y> = ZZ[]
sage: x.args()
(x, y)
"""
return self._parent.gens()
def homogenize(self, var='h'):
r"""
Return the homogenization of this polynomial.
The polynomial itself is returned if it is homogeneous already.
Otherwise, the monomials are multiplied with the smallest powers of
``var`` such that they all have the same total degree.
INPUT:
- ``var`` -- a variable in the polynomial ring (as a string, an element of
the ring, or a zero-based index in the list of variables) or a name
for a new variable (default: ``'h'``)
OUTPUT:
If ``var`` specifies a variable in the polynomial ring, then a
homogeneous element in that ring is returned. Otherwise, a homogeneous
element is returned in a polynomial ring with an extra last variable
``var``.
EXAMPLES::
sage: R.<x,y> = QQ[]
sage: f = x^2 + y + 1 + 5*x*y^10
sage: f.homogenize()
5*x*y^10 + x^2*h^9 + y*h^10 + h^11
The parameter ``var`` can be used to specify the name of the variable::
sage: g = f.homogenize('z'); g
5*x*y^10 + x^2*z^9 + y*z^10 + z^11
sage: g.parent()
Multivariate Polynomial Ring in x, y, z over Rational Field
However, if the polynomial is homogeneous already, then that parameter
is ignored and no extra variable is added to the polynomial ring::
sage: f = x^2 + y^2
sage: g = f.homogenize('z'); g
x^2 + y^2
sage: g.parent()
Multivariate Polynomial Ring in x, y over Rational Field
If you want the ring of the result to be independent of whether the
polynomial is homogenized, you can use ``var`` to use an existing
variable to homogenize::
sage: R.<x,y,z> = QQ[]
sage: f = x^2 + y^2
sage: g = f.homogenize(z); g
x^2 + y^2
sage: g.parent()
Multivariate Polynomial Ring in x, y, z over Rational Field
sage: f = x^2 - y
sage: g = f.homogenize(z); g
x^2 - y*z
sage: g.parent()
Multivariate Polynomial Ring in x, y, z over Rational Field
The parameter ``var`` can also be given as a zero-based index in the
list of variables::
sage: g = f.homogenize(2); g
x^2 - y*z
If the variable specified by ``var`` is not present in the polynomial,
then setting it to 1 yields the original polynomial::
sage: g(x,y,1)
x^2 - y
If it is present already, this might not be the case::
sage: g = f.homogenize(x); g
x^2 - x*y
sage: g(1,y,z)
-y + 1
In particular, this can be surprising in positive characteristic::
sage: R.<x,y> = GF(2)[]
sage: f = x + 1
sage: f.homogenize(x)
0
TESTS::
sage: R = PolynomialRing(QQ, 'x', 5)
sage: p = R.random_element()
sage: q1 = p.homogenize()
sage: q2 = p.homogenize()
sage: q1.parent() is q2.parent()
True
"""
P = self.parent()
if self.is_homogeneous():
return self
if isinstance(var, basestring):
V = list(P.variable_names())
try:
i = V.index(var)
return self._homogenize(i)
except ValueError:
P = PolynomialRing(P.base_ring(), len(V)+1, V + [var], order=P.term_order())
return P(self)._homogenize(len(V))
elif isinstance(var, MPolynomial) and \
((<MPolynomial>var)._parent is P or (<MPolynomial>var)._parent == P):
V = list(P.gens())
try:
i = V.index(var)
return self._homogenize(i)
except ValueError:
P = P.change_ring(names=P.variable_names() + [str(var)])
return P(self)._homogenize(len(V))
elif isinstance(var, int) or isinstance(var, Integer):
if 0 <= var < P.ngens():
return self._homogenize(var)
else:
raise TypeError("Variable index %d must be < parent(self).ngens()." % var)
else:
raise TypeError("Parameter var must be either a variable, a string or an integer.")
def is_homogeneous(self):
r"""
Return ``True`` if self is a homogeneous polynomial.
TESTS::
sage: from sage.rings.polynomial.multi_polynomial import MPolynomial
sage: P.<x, y> = PolynomialRing(QQ, 2)
sage: MPolynomial.is_homogeneous(x+y)
True
sage: MPolynomial.is_homogeneous(P(0))
True
sage: MPolynomial.is_homogeneous(x+y^2)
False
sage: MPolynomial.is_homogeneous(x^2 + y^2)
True
sage: MPolynomial.is_homogeneous(x^2 + y^2*x)
False
sage: MPolynomial.is_homogeneous(x^2*y + y^2*x)
True
.. note::
This is a generic implementation which is likely overridden by
subclasses.
"""
M = self.monomials()
if M==[]:
return True
d = M.pop().degree()
for m in M:
if m.degree() != d:
return False
else:
return True
cpdef _mod_(self, other):
"""
EXAMPLES::
sage: R.<x,y> = PolynomialRing(QQ)
sage: f = (x^2*y + 2*x - 3)
sage: g = (x + 1)*f
sage: g % f
0
sage: (g+1) % f
1
sage: M = x*y
sage: N = x^2*y^3
sage: M.divides(N)
True
"""
q,r = self.quo_rem(other)
return r
def change_ring(self, R):
"""
Return a copy of this polynomial but with coefficients in ``R``,
if at all possible.
INPUT:
- ``R`` -- a ring or morphism.
EXAMPLES::
sage: R.<x,y> = QQ[]
sage: f = x^3 + 3/5*y + 1
sage: f.change_ring(GF(7))
x^3 + 2*y + 1
::
sage: R.<x,y> = GF(9,'a')[]
sage: (x+2*y).change_ring(GF(3))
x - y
::
sage: K.<z> = CyclotomicField(3)
sage: R.<x,y> = K[]
sage: f = x^2 + z*y
sage: f.change_ring(K.embeddings(CC)[1])
x^2 + (-0.500000000000000 + 0.866025403784439*I)*y
"""
if isinstance(R, Morphism):
#if we're given a hom of the base ring extend to a poly hom
if R.domain() == self.base_ring():
R = self.parent().hom(R, self.parent().change_ring(R.codomain()))
return R(self)
else:
return self.parent().change_ring(R)(self)
def _magma_init_(self, magma):
"""
Returns a Magma string representation of self valid in the
given magma session.
EXAMPLES::
sage: k.<b> = GF(25); R.<x,y> = k[]
sage: f = y*x^2*b + x*(b+1) + 1
sage: magma = Magma() # so var names same below
sage: magma(f) # optional - magma
b*x^2*y + b^22*x + 1
sage: f._magma_init_(magma) # optional - magma
'_sage_[...]!((_sage_[...]!(_sage_[...]))*_sage_[...]^2*_sage_[...]+(_sage_[...]!(_sage_[...] + 1))*_sage_[...]+(_sage_[...]!(1))*1)'
A more complicated nested example::
sage: R.<x,y> = QQ[]; S.<z,w> = R[]; f = (2/3)*x^3*z + w^2 + 5
sage: f._magma_init_(magma) # optional - magma
'_sage_[...]!((_sage_[...]!((1/1)*1))*_sage_[...]^2+(_sage_[...]!((2/3)*_sage_[...]^3))*_sage_[...]+(_sage_[...]!((5/1)*1))*1)'
sage: magma(f) # optional - magma
w^2 + 2/3*x^3*z + 5
"""
R = magma(self.parent())
g = R.gen_names()
v = []
for m, c in zip(self.monomials(), self.coefficients()):
v.append('(%s)*%s'%( c._magma_init_(magma),
m._repr_with_changed_varnames(g)))
if len(v) == 0:
s = '0'
else:
s = '+'.join(v)
return '%s!(%s)'%(R.name(), s)
def gradient(self):
r"""
Return a list of partial derivatives of this polynomial,
ordered by the variables of ``self.parent()``.
EXAMPLES::
sage: P.<x,y,z> = PolynomialRing(ZZ,3)
sage: f = x*y + 1
sage: f.gradient()
[y, x, 0]
"""
return [ self.derivative(var) for var in self.parent().gens() ]
def jacobian_ideal(self):
r"""
Return the Jacobian ideal of the polynomial self.
EXAMPLES::
sage: R.<x,y,z> = QQ[]
sage: f = x^3 + y^3 + z^3
sage: f.jacobian_ideal()
Ideal (3*x^2, 3*y^2, 3*z^2) of Multivariate Polynomial Ring in x, y, z over Rational Field
"""
return self.parent().ideal(self.gradient())
def newton_polytope(self):
"""
Return the Newton polytope of this polynomial.
EXAMPLES::
sage: R.<x,y> = QQ[]
sage: f = 1 + x*y + x^3 + y^3
sage: P = f.newton_polytope()
sage: P
A 2-dimensional polyhedron in ZZ^2 defined as the convex hull of 3 vertices
sage: P.is_simple()
True
TESTS::
sage: R.<x,y> = QQ[]
sage: R(0).newton_polytope()
The empty polyhedron in ZZ^0
sage: R(1).newton_polytope()
A 0-dimensional polyhedron in ZZ^2 defined as the convex hull of 1 vertex
sage: R(x^2+y^2).newton_polytope().integral_points()
((0, 2), (1, 1), (2, 0))
"""
from sage.geometry.polyhedron.constructor import Polyhedron
e = self.exponents()
P = Polyhedron(vertices = e, base_ring=ZZ)
return P
def __iter__(self):
"""
Facilitates iterating over the monomials of self,
returning tuples of the form ``(coeff, mon)`` for each
non-zero monomial.
.. note::
This function creates the entire list upfront because Cython
doesn't (yet) support iterators.
EXAMPLES::
sage: P.<x,y,z> = PolynomialRing(QQ,3)
sage: f = 3*x^3*y + 16*x + 7
sage: [(c,m) for c,m in f]
[(3, x^3*y), (16, x), (7, 1)]
sage: f = P.random_element(12,14)
sage: sum(c*m for c,m in f) == f
True
"""
L = zip(self.coefficients(), self.monomials())
return iter(L)
def content(self):
"""
Returns the content of this polynomial. Here, we define content as
the gcd of the coefficients in the base ring.
EXAMPLES::
sage: R.<x,y> = ZZ[]
sage: f = 4*x+6*y
sage: f.content()
2