forked from sympy/sympy
/
basic.py
2332 lines (1841 loc) · 67.6 KB
/
basic.py
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
"""Base class for all objects in sympy"""
import sympy.mpmath as mpmath
from assumptions import AssumeMeths, make__get_assumption
from sympify import _sympify, _sympifyit, sympify, SympifyError
from cache import cacheit, Memoizer, MemoizerArg
# from numbers import Number, Integer, Rational, Real /cyclic/
# from interval import Interval /cyclic/
# from symbol import Symbol, Wild, Temporary /cyclic/
# from add import Add /cyclic/
# from mul import Mul /cyclic/
# from power import Pow /cyclic/
# from function import Derivative, FunctionClass /cyclic/
# from relational import Equality, Unequality, Inequality, StrictInequality /cyclic/
# from sympy.functions.elementary.complexes import abs as abs_ /cyclic/
# from sympy.printing import StrPrinter
# used for canonical ordering of symbolic sequences
# via __cmp__ method:
# FIXME this is *so* irrelevant and outdated!
ordering_of_classes = [
# singleton numbers
'Zero', 'One','Half','Infinity','NaN','NegativeOne','NegativeInfinity',
# numbers
'Integer','Rational','Real',
# singleton symbols
'Exp1','Pi','ImaginaryUnit',
# symbols
'Symbol','Wild','Temporary',
# Functions that should come before Pow/Add/Mul
'ApplyConjugate', 'ApplyAbs',
# arithmetic operations
'Pow', 'Mul', 'Add',
# function values
'Apply',
'ApplyExp','ApplyLog',
'ApplySin','ApplyCos','ApplyTan','ApplyCot',
'ApplyASin','ApplyACos','ApplyATan','ApplyACot',
'ApplySinh','ApplyCosh','ApplyTanh','ApplyCoth',
'ApplyASinh','ApplyACosh','ApplyATanh','ApplyACoth',
'ApplyRisingFactorial','ApplyFallingFactorial',
'ApplyFactorial','ApplyBinomial',
'ApplyFloor', 'ApplyCeiling',
'ApplyRe','ApplyIm', 'ApplyArg',
'ApplySqrt','ApplySign',
'ApplyMrvLog',
'ApplyGamma','ApplyLowerGamma','ApplyUpperGamma','ApplyPolyGamma',
'ApplyErf',
'ApplyChebyshev','ApplyChebyshev2',
'Derivative','Integral',
# defined singleton functions
'Abs','Sign','Sqrt',
'Floor', 'Ceiling',
'Re', 'Im', 'Arg',
'Conjugate',
'Exp','Log','MrvLog',
'Sin','Cos','Tan','Cot','ASin','ACos','ATan','ACot',
'Sinh','Cosh','Tanh','Coth','ASinh','ACosh','ATanh','ACoth',
'RisingFactorial','FallingFactorial',
'Factorial','Binomial',
'Gamma','LowerGamma','UpperGamma','PolyGamma',
'Erf',
# special polynomials
'Chebyshev','Chebyshev2',
# undefined functions
'Function','WildFunction',
# anonymous functions
'Lambda',
# operators
'FDerivative','FApply',
# composition of functions
'FPow', 'Composition',
# Landau O symbol
'Order',
# relational operations
'Equality', 'Unequality', 'StrictInequality', 'Inequality',
]
class BasicType(type):
pass
class BasicMeta(BasicType):
classnamespace = {}
singleton = {}
def __init__(cls, *args, **kws):
n = cls.__name__
c = BasicMeta.classnamespace.get(n)
BasicMeta.classnamespace[n] = cls
super(BasicMeta, cls).__init__(cls)
# --- assumptions ---
# initialize default_assumptions dictionary
default_assumptions = {}
for k,v in cls.__dict__.iteritems():
if not k.startswith('is_'):
continue
# this is not an assumption (e.g. is_Integer)
if k[3:] not in AssumeMeths._assume_defined:
continue
k = k[3:]
if isinstance(v,(bool,int,long,type(None))):
if v is not None:
v = bool(v)
default_assumptions[k] = v
#print ' %r <-- %s' % (k,v)
# XXX maybe we should try to keep ._default_premises out of class ?
# XXX __slots__ in class ?
cls._default_premises = default_assumptions
for base in cls.__bases__:
try:
base_premises = base._default_premises
except AttributeError:
continue # no ._default_premises is ok
for k,v in base_premises.iteritems():
# if an assumption is already present in child, we should ignore base
# e.g. Integer.is_integer=T, but Rational.is_integer=F (for speed)
if k in default_assumptions:
continue
default_assumptions[k] = v
# deduce all consequences from default assumptions -- make it complete
xass = AssumeMeths._assume_rules.deduce_all_facts(default_assumptions)
# and store completed set into cls -- this way we'll avoid rededucing
# extensions of class default assumptions each time on instance
# creation -- we keep it prededuced already.
cls.default_assumptions = xass
#print '\t(%2i) %s' % (len(default_assumptions), default_assumptions)
#print '\t(%2i) %s' % (len(xass), xass)
# let's store new derived assumptions back into class.
# this will result in faster access to this attributes.
#
# Timings
# -------
#
# a = Integer(5)
# %timeit a.is_zero -> 20 us (without this optimization)
# %timeit a.is_zero -> 2 us (with this optimization)
#
#
# BTW: it is very important to study the lessons learned here --
# we could drop Basic.__getattr__ completely (!)
#
# %timeit x.is_Add -> 2090 ns (Basic.__getattr__ present)
# %timeit x.is_Add -> 825 ns (Basic.__getattr__ absent)
#
# so we may want to override all assumptions is_<xxx> methods and
# remove Basic.__getattr__
# first we need to collect derived premises
derived_premises = {}
for k,v in xass.iteritems():
if k not in default_assumptions:
derived_premises[k] = v
cls._derived_premises = derived_premises
for k,v in xass.iteritems():
assert v == cls.__dict__.get('is_'+k, v), (cls,k,v)
# NOTE: this way Integer.is_even = False (inherited from Rational)
# NOTE: the next code blocks add 'protection-properties' to overcome this
setattr(cls, 'is_'+k, v)
# protection e.g. for Initeger.is_even=F <- (Rational.is_integer=F)
for base in cls.__bases__:
try:
base_derived_premises = base._derived_premises
except AttributeError:
continue # no ._derived_premises is ok
for k,v in base_derived_premises.iteritems():
if not cls.__dict__.has_key('is_'+k):
#print '%s -- overriding: %s' % (cls.__name__, k)
is_k = make__get_assumption(cls.__name__, k)
setattr(cls, 'is_'+k, property(is_k))
def __cmp__(cls, other):
try:
other = sympify(other)
except ValueError:
#if we cannot sympify it, other is definitely not equal to cls
return -1
n1 = cls.__name__
n2 = other.__name__
c = cmp(n1,n2)
if not c: return 0
UNKNOWN = len(ordering_of_classes)+1
try:
i1 = ordering_of_classes.index(n1)
except ValueError:
#print 'Add',n1,'to basic.ordering_of_classes list'
#return c
i1 = UNKNOWN
try:
i2 = ordering_of_classes.index(n2)
except ValueError:
#print 'Add',n2,'to basic.ordering_of_classes list'
#return c
i2 = UNKNOWN
if i1 == UNKNOWN and i2 == UNKNOWN:
return c
return cmp(i1,i2)
def __lt__(cls, other):
if cls.__cmp__(other)==-1:
return True
return False
def __gt__(cls, other):
if cls.__cmp__(other)==1:
return True
return False
class Basic(AssumeMeths):
"""
Base class for all objects in sympy.
Conventions:
1)
When you want to access parameters of some instance, always use .args:
Example:
>>> from sympy import symbols, cot
>>> x, y = symbols('xy')
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
2) Never use internal methods or variables (the ones prefixed with "_").
Example:
>>> cot(x)._args #don't use this, use cot(x).args instead
(x,)
"""
__metaclass__ = BasicMeta
__slots__ = ['_mhash', # hash value
'_args', # arguments
'_assume_type_keys', # assumptions typeinfo keys
]
# To be overridden with True in the appropriate subclasses
is_Atom = False
is_Symbol = False
is_Function = False
is_Add = False
is_Mul = False
is_Pow = False
is_Number = False
is_Real = False
is_Rational = False
is_Integer = False
is_NumberSymbol = False
is_Order = False
is_Derivative = False
def __new__(cls, *args, **assumptions):
obj = object.__new__(cls)
# FIXME we are slowed a *lot* by Add/Mul passing is_commutative as the
# only assumption.
#
# .is_commutative is not an assumption -- it's like typeinfo!!!
# we should remove it.
# initially assumptions are shared between instances and class
obj._assumptions = cls.default_assumptions
obj._a_inprogress = []
# NOTE this could be made lazy -- probably not all instances will need
# fully derived assumptions?
if assumptions:
obj._learn_new_facts(assumptions)
# ^
# FIXME this is slow | another NOTE: speeding this up is *not*
# | | important. say for %timeit x+y most of
# .------' | the time is spent elsewhere
# | |
# | XXX _learn_new_facts could be asked about what *new* facts have
# v XXX been learned -- we'll need this to append to _hashable_content
basek = set(cls.default_assumptions.keys())
k2 = set(obj._assumptions.keys())
newk = k2.difference(basek)
obj._assume_type_keys = frozenset(newk)
else:
obj._assume_type_keys = None
obj._mhash = None # will be set by __hash__ method.
obj._args = args # all items in args must be Basic objects
return obj
# XXX better name?
@property
def assumptions0(self):
"""return object `type` assumptions
For example:
Symbol('x', real=True)
Symbol('x', integer=True)
are different objects, and besides Python type (Symbol), initial
assumptions, are too forming their typeinfo.
"""
cls = type(self)
A = self._assumptions
# assumptions shared:
if A is cls.default_assumptions or (self._assume_type_keys is None):
assumptions0 = {}
else:
assumptions0 = dict( (k, A[k]) for k in self._assume_type_keys )
return assumptions0
def new(self, *args):
"""create new 'similar' object
this is conceptually equivalent to:
type(self) (*args)
but takes type assumptions into account.
see: assumptions0
"""
obj = type(self) (*args, **self.assumptions0)
return obj
# NOTE NOTE NOTE
# --------------
#
# new-style classes + __getattr__ is *very* slow!
# def __getattr__(self, name):
# raise 'no way, *all* attribute access will be 2.5x slower'
# here is what we do instead:
for k in AssumeMeths._assume_defined:
exec "is_%s = property(make__get_assumption('Basic', '%s'))" % (k,k)
# NB: there is no need in protective __setattr__
def __hash__(self):
# hash cannot be cached using cache_it because infinite recurrence
# occurs as hash is needed for setting cache dictionary keys
h = self._mhash
if h is None:
h = (type(self).__name__,) + self._hashable_content()
if self._assume_type_keys is not None:
a = []
kv= self._assumptions
for k in sorted(self._assume_type_keys):
a.append( (k, kv[k]) )
h = hash( h + tuple(a) )
else:
h = hash( h )
self._mhash = h
return h
else:
return h
def _hashable_content(self):
# If class defines additional attributes, like name in Symbol,
# then this method should be updated accordingly to return
# relevant attributes as tuple.
return self._args
def __nonzero__(self):
"""Tests if 'self' is an instance of Zero class.
This should be understand as an idiom:
[1] bool(x) <=> bool(x is not S.Zero)
[2] bool(not x) <=> bool(x is S.Zero)
Allowing definition of __nonzero__ method is important in
algorithms where uniform handling of int, long values and
and sympy expressions is required.
>>> from sympy import *
>>> x,y = symbols('xy')
>>> bool(0)
False
>>> bool(1)
True
>>> bool(S.Zero)
False
>>> bool(S.One)
True
>>> bool(x*y)
True
>>> bool(x + y)
True
"""
return self is not S.Zero
def compare(self, other):
"""
Return -1,0,1 if the object is smaller, equal, or greater than other
(not always in mathematical sense).
If the object is of different type from other then their classes
are ordered according to sorted_classes list.
"""
# all redefinitions of __cmp__ method should start with the
# following three lines:
if self is other: return 0
c = cmp(self.__class__, other.__class__)
if c: return c
#
st = self._hashable_content()
ot = other._hashable_content()
c = cmp(len(st),len(ot))
if c: return c
for l,r in zip(st,ot):
if isinstance(l, Basic):
c = l.compare(r)
else:
c = cmp(l, r)
if c: return c
return 0
@staticmethod
def _compare_pretty(a, b):
from sympy.series.order import Order
if isinstance(a, Order) and not isinstance(b, Order):
return 1
if not isinstance(a, Order) and isinstance(b, Order):
return -1
# FIXME this produces wrong ordering for 1 and 0
# e.g. the ordering will be 1 0 2 3 4 ...
# because 1 = x^0, but 0 2 3 4 ... = x^1
p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3")
r_a = a.match(p1 * p2**p3)
r_b = b.match(p1 * p2**p3)
if r_a is not None and r_b is not None:
c = Basic.compare(r_a[p3], r_b[p3])
if c!=0:
return c
return Basic.compare(a,b)
@staticmethod
def compare_pretty(a, b):
"""
Is a>b in the sense of ordering in printing?
yes ..... return 1
no ...... return -1
equal ... return 0
Strategy:
It uses Basic.compare as a fallback, but improves it in many cases,
like x**3, x**4, O(x**3) etc. In those simple cases, it just parses the
expression and returns the "sane" ordering such as:
1 < x < x**2 < x**3 < O(x**4) etc.
"""
try:
a = _sympify(a)
except SympifyError:
pass
try:
b = _sympify(b)
except SympifyError:
pass
# both objects are non-SymPy
if (not isinstance(a, Basic)) and (not isinstance(b, Basic)):
return cmp(a,b)
if not isinstance(a, Basic):
return -1 # other < sympy
if not isinstance(b, Basic):
return +1 # sympy > other
# now both objects are from SymPy, so we can proceed to usual comparison
return Basic._compare_pretty(a, b)
def __eq__(self, other):
"""a == b -> Compare two symbolic trees and see whether they are equal
this is the same as:
a.compare(b) == 0
but faster
"""
if type(self) is not type(other):
try:
other = _sympify(other)
except SympifyError:
return False # sympy != other
if type(self) is not type(other):
return False
# type(self) == type(other)
st = self._hashable_content()
ot = other._hashable_content()
return (st == ot)
def __ne__(self, other):
"""a != b -> Compare two symbolic trees and see whether they are different
this is the same as:
a.compare(b) != 0
but faster
"""
if type(self) is not type(other):
try:
other = _sympify(other)
except SympifyError:
return True # sympy != other
if type(self) is not type(other):
return True
# type(self) == type(other)
st = self._hashable_content()
ot = other._hashable_content()
return (st != ot)
# TODO all comparison methods should return True/False directly (?)
# see #153
#
# OTOH Py3k says
#
# Comparisons other than == and != between disparate types will raise an
# exception unless explicitly supported by the type
#
# references:
#
# http://www.python.org/dev/peps/pep-0207/
# http://www.python.org/dev/peps/pep-3100/#id18
# http://mail.python.org/pipermail/python-dev/2004-June/045111.html
@_sympifyit('other', False) # sympy > other
def __lt__(self, other):
#return sympify(other) > self
return StrictInequality(self, other)
@_sympifyit('other', True) # sympy > other
def __gt__(self, other):
return StrictInequality(other, self)
#return sympify(other) < self
@_sympifyit('other', False) # sympy > other
def __le__(self, other):
return Inequality(self, other)
@_sympifyit('other', True) # sympy > other
def __ge__(self, other):
return sympify(other) <= self
# ***************
# * Arithmetics *
# ***************
def __pos__(self):
return self
def __neg__(self):
return Mul(S.NegativeOne, self)
def __abs__(self):
return abs_(self)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
return Add(self, other)
@_sympifyit('other', NotImplemented)
def __radd__(self, other):
return Add(other, self)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
return Add(self, -other)
@_sympifyit('other', NotImplemented)
def __rsub__(self, other):
return Add(other, -self)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
return Mul(self, other)
@_sympifyit('other', NotImplemented)
def __rmul__(self, other):
return Mul(other, self)
@_sympifyit('other', NotImplemented)
def __pow__(self, other):
return Pow(self, other)
@_sympifyit('other', NotImplemented)
def __rpow__(self, other):
return Pow(other, self)
@_sympifyit('other', NotImplemented)
def __div__(self, other):
return Mul(self, Pow(other, S.NegativeOne))
@_sympifyit('other', NotImplemented)
def __rdiv__(self, other):
return Mul(other, Pow(self, S.NegativeOne))
__truediv__ = __div__
__rtruediv__ = __rdiv__
def __repr__(self):
return StrPrinter.doprint(self)
def __str__(self):
return StrPrinter.doprint(self)
def atoms(self, *types):
"""Returns the atoms that form the current object.
An atom is the smallest piece in which we can divide an
expression.
Examples:
>>> from sympy import *
>>> x,y = symbols('xy')
>>> sorted((x+y**2 + 2*x*y).atoms())
[2, x, y]
You can also filter the results by a given type(s) of object:
>>> sorted((x+y+2+y**2*sin(x)).atoms(Symbol))
[x, y]
>>> sorted((x+y+2+y**3*sin(x)).atoms(Number))
[2, 3]
>>> sorted((x+y+2+y**2*sin(x)).atoms(Symbol, Number))
[2, x, y]
Or by a type of on object in an impliciy way:
>>> sorted((x+y+2+y**2*sin(x)).atoms(x))
[x, y]
"""
def _atoms(expr, typ):
"""Helper function for recursively denesting atoms"""
if isinstance(expr, Basic):
if expr.is_Atom and len(typ) == 0: # if we haven't specified types
return [expr]
else:
try:
if isinstance(expr, typ): return [expr]
except TypeError:
#if type is in implicit form
if isinstance(expr, tuple(map(type, typ))): return [expr]
result = []
#search for a suitable iterator
if isinstance(expr, Basic):
iter = expr.iter_basic_args()
elif isinstance(expr, (tuple, list)):
iter = expr.__iter__()
else:
iter = []
for obj in iter:
result.extend(_atoms(obj, typ))
return result
return set(_atoms(self, typ=types))
def is_hypergeometric(self, k):
from sympy.simplify import hypersimp
return hypersimp(self, k) is not None
@property
def is_number(self):
"""Returns True if 'self' is a number.
>>> from sympy import *
>>> x,y = symbols('xy')
>>> x.is_number
False
>>> (2*x).is_number
False
>>> (2 + log(2)).is_number
True
"""
for obj in self.iter_basic_args():
if not obj.is_number:
return False
else:
return True
@property
def func(self):
"""
The top-level function in an expression.
The following should hold for all objects::
>> x == x.func(*x.args)
"""
return self.__class__
@property
def args(self):
"""Returns a tuple of arguments of 'self'.
Example:
>>> from sympy import symbols, cot
>>> x, y = symbols('xy')
>>> cot(x).args
(x,)
>>> cot(x).args[0]
x
>>> (x*y).args
(x, y)
>>> (x*y).args[1]
y
Note for developers: Never use self._args, always use self.args.
Only when you are creating your own new function, use _args
in the __new__. Don't override .args() from Basic (so that it's
easy to change the interface in the future if needed).
"""
return self._args[:]
def iter_basic_args(self):
"""Iterates arguments of 'self' with are Basic instances. """
return iter(self.args)
def is_fraction(self, *syms):
p, q = self.as_numer_denom()
if p.is_polynomial(*syms):
if q.is_polynomial(*syms):
return True
return False
def _eval_is_polynomial(self, syms):
return
def is_polynomial(self, *syms):
if syms:
syms = map(sympify, syms)
else:
syms = list(self.atoms(Symbol))
if not syms: # constant polynomial
return True
else:
return self._eval_is_polynomial(syms)
def as_poly(self, *symbols, **flags):
"""Converts 'self' to a polynomial or returns None.
When constructing a polynomial an exception will be raised in
case the input expression is not convertible to a polynomial.
There are situations when it is easier (simpler or prettier)
to receive None on failure.
If no symbols were given and 'self' isn't already a polynomial
then all available symbols will be collected and used to form
a new polynomial.
>>> from sympy import *
>>> x,y = symbols('xy')
>>> print (x**2 + x*y).as_poly()
Poly(x**2 + x*y, x, y)
>>> print (x**2 + x*y).as_poly(x, y)
Poly(x**2 + x*y, x, y)
>>> print (x**2 + sin(y)).as_poly(x, y)
None
"""
from sympy.polys import Poly, PolynomialError
try:
if not symbols:
if isinstance(self, Poly):
return self
else:
symbols = sorted(self.atoms(Symbol))
return Poly(self, *symbols, **flags)
except PolynomialError:
return None
def as_basic(self):
"""Converts polynomial to a valid sympy expression.
>>> from sympy import *
>>> x,y = symbols('xy')
>>> p = (x**2 + x*y).as_poly(x, y)
>>> p.as_basic()
x*y + x**2
>>> f = sin(x)
>>> f.as_basic()
sin(x)
"""
return self
def subs(self, *args):
"""
Substitutes an expression.
Calls either _subs_old_new, _subs_dict or _subs_list depending
if you give it two arguments (old, new), a dictionary or a list.
Examples:
>>> from sympy import *
>>> x,y = symbols('xy')
>>> (1+x*y).subs(x, pi)
1 + pi*y
>>> (1+x*y).subs({x:pi, y:2})
1 + 2*pi
>>> (1+x*y).subs([(x,pi), (y,2)])
1 + 2*pi
"""
if len(args) == 1:
sequence = args[0]
if isinstance(sequence, dict):
return self._subs_dict(sequence)
elif isinstance(sequence, (list, tuple)):
return self._subs_list(sequence)
else:
raise TypeError("Not an iterable container")
elif len(args) == 2:
old, new = args
return self._subs_old_new(old, new)
else:
raise Exception("subs accept either 1 or 2 arguments")
@cacheit
def _subs_old_new(self, old, new):
"""Substitutes an expression old -> new."""
old = sympify(old)
new = sympify(new)
return self._eval_subs(old, new)
def _eval_subs(self, old, new):
if self==old:
return new
return self
def _subs_list(self, sequence):
"""
Performs an order sensitive substitution from the
input sequence list.
Examples:
>>> from sympy import *
>>> x, y = symbols('xy')
>>> (x+y)._subs_list( [(x, 3), (y, x**2)] )
3 + x**2
>>> (x+y)._subs_list( [(y, x**2), (x, 3) ] )
12
"""
if not isinstance(sequence, (list, tuple)):
raise TypeError("Not an iterable container")
result = self
for old, new in sequence:
result = result.subs(old, new)
return result
def _subs_dict(self, sequence):
"""Performs sequential substitution.
Given a collection of key, value pairs, which correspond to
old and new expressions respectively, substitute all given
pairs handling properly all overlapping keys (according to
'in' relation).
We have to use naive O(n**2) sorting algorithm, as 'in'
gives only partial order and all asymptotically faster
fail (depending on the initial order).
>>> from sympy import *
>>> x, y = symbols('xy')
>>> a,b,c,d,e = symbols('abcde')
>>> A = (sqrt(sin(2*x)), a)
>>> B = (sin(2*x), b)
>>> C = (cos(2*x), c)
>>> D = (x, d)
>>> E = (exp(x), e)
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
>>> expr._subs_dict([A,B,C,D,E])
b + a*c*sin(d*e)
"""
if isinstance(sequence, dict):
sequence = sequence.items()
elif not isinstance(sequence, (list, tuple)):
raise TypeError("Not an iterable container")
subst = []