forked from sympy/sympy
/
exprtools.py
383 lines (281 loc) · 9.65 KB
/
exprtools.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
"""Tools for manipulating of large commutative expressions. """
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.basic import Basic
from sympy.core.sympify import sympify
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.coreerrors import NonCommutativeExpression
from sympy.core.containers import Tuple
def decompose_power(expr):
"""
Decompose power into symbolic base and integer exponent.
**Example**
>>> from sympy.core.exprtools import decompose_power
>>> from sympy.abc import x, y
>>> decompose_power(x)
(x, 1)
>>> decompose_power(x**2)
(x, 2)
>>> decompose_power(x**(2*y))
(x**y, 2)
>>> decompose_power(x**(2*y/3))
(x**(y/3), 2)
"""
base, exp = expr.as_base_exp()
if exp.is_Number:
if exp.is_Rational:
if not exp.is_Integer:
base = Pow(base, Rational(1, exp.q))
exp = exp.p
else:
base, exp = expr, 1
else:
exp, tail = exp.as_coeff_mul()
if exp.is_Rational:
if not exp.is_Integer:
tail += (Rational(1, exp.q),)
base, exp = Pow(base, Mul(*tail)), exp.p
else:
base, exp = expr, 1
return base, exp
class Factors(object):
"""Efficient representation of ``f_1*f_2*...*f_n``. """
__slots__ = ['factors', 'gens']
def __init__(self, factors=None):
if factors is None:
factors = {}
self.factors = factors
self.gens = frozenset(factors.keys())
def __hash__(self):
return hash((tuple(self.factors), self.gens))
def __repr__(self):
return "Factors(%s)" % self.factors
def as_expr(self):
return Mul(*[ factor**exp for factor, exp in self.factors.iteritems() ])
def normal(self, other):
self_factors = dict(self.factors)
other_factors = dict(other.factors)
for factor, self_exp in self.factors.iteritems():
try:
other_exp = other.factors[factor]
except KeyError:
continue
exp = self_exp - other_exp
if not exp:
del self_factors[factor]
del other_factors[factor]
else:
if exp > 0:
self_factors[factor] = exp
del other_factors[factor]
else:
del self_factors[factor]
other_factors[factor] = -exp
return Factors(self_factors), Factors(other_factors)
def mul(self, other):
factors = dict(self.factors)
for factor, exp in other.factors.iteritems():
if factor in factors:
exp = factors[factor] + exp
if not exp:
del factors[factor]
continue
factors[factor] = exp
return Factors(factors)
def div(self, other):
quo, rem = dict(self.factors), {}
for factor, exp in other.factors.iteritems():
if factor in quo:
exp = quo[factor] - exp
if exp <= 0:
del quo[factor]
if exp >= 0:
if exp:
quo[factor] = exp
continue
exp = -exp
rem[factor] = exp
return Factors(quo), Factors(rem)
def quo(self, other):
return self.div(other)[0]
def rem(self, other):
return self.div(other)[1]
def pow(self, other):
if type(other) is int and other >= 0:
factors = {}
if other:
for factor, exp in self.factors.iteritems():
factors[factor] = exp*other
return Factors(factors)
else:
raise ValueError("expected non-negative integer, got %s" % other)
def gcd(self, other):
factors = {}
for factor, exp in self.factors.iteritems():
if factor in other.factors:
exp = min(exp, other.factors[factor])
factors[factor] = exp
return Factors(factors)
def lcm(self, other):
factors = dict(self.factors)
for factor, exp in other.factors.iteritems():
if factor in factors:
exp = max(exp, factors[factor])
factors[factor] = exp
return Factors(factors)
def __mul__(self, other):
if isinstance(other, Factors):
return self.mul(other)
else:
return NotImplemented
def __divmod__(self, other):
if isinstance(other, Factors):
return self.div(other)
else:
return NotImplemented
def __div__(self, other):
if isinstance(other, Factors):
return self.quo(other)
else:
return NotImplemented
__truediv__ = __div__
def __mod__(self, other):
if isinstance(other, Factors):
return self.rem(other)
else:
return NotImplemented
def __pow__(self, other):
if type(other) is int:
return self.pow(other)
else:
return NotImplemented
def __eq__(self, other):
return self.factors == other.factors
def __ne__(self, other):
return not self.__eq__(other)
class Term(object):
"""Efficient representation of ``coeff*(numer/denom)``. """
__slots__ = ['coeff', 'numer', 'denom']
def __init__(self, term, numer=None, denom=None):
if numer is None and denom is None:
if not term.is_commutative:
raise NonCommutativeExpression('commutative expression expected')
coeff, factors = term.as_coeff_mul()
numer, denom = {}, {}
for factor in factors:
base, exp = decompose_power(factor)
if base.is_Add:
cont, base = base.primitive()
coeff *= cont**exp
if exp > 0:
numer[base] = exp
else:
denom[base] = -exp
numer = Factors(numer)
denom = Factors(denom)
else:
coeff = term
if numer is None:
numer = Factors()
if denom is None:
denom = Factors()
self.coeff = coeff
self.numer = numer
self.denom = denom
def __hash__(self):
return hash((self.coeff, self.numer, self.denom))
def __repr__(self):
return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom)
def as_expr(self):
return self.coeff*(self.numer.as_expr()/self.denom.as_expr())
def mul(self, other):
coeff = self.coeff*other.coeff
numer = self.numer.mul(other.numer)
denom = self.denom.mul(other.denom)
numer, denom = numer.normal(denom)
return Term(coeff, numer, denom)
def inv(self):
return Term(1/self.coeff, self.denom, self.numer)
def quo(self, other):
return self.mul(other.inv())
def pow(self, other):
if other < 0:
return self.inv().pow(-other)
else:
return Term(self.coeff ** other,
self.numer.pow(other),
self.denom.pow(other))
def gcd(self, other):
return Term(self.coeff.gcd(other.coeff),
self.numer.gcd(other.numer),
self.denom.gcd(other.denom))
def lcm(self, other):
return Term(self.coeff.lcm(other.coeff),
self.numer.lcm(other.numer),
self.denom.lcm(other.denom))
def __mul__(self, other):
if isinstance(other, Term):
return self.mul(other)
else:
return NotImplemented
def __div__(self, other):
if isinstance(other, Term):
return self.quo(other)
else:
return NotImplemented
__truediv__ = __div__
def __pow__(self, other):
if type(other) is int:
return self.pow(other)
else:
return NotImplemented
def __eq__(self, other):
return (self.coeff == other.coeff and
self.numer == other.numer and
self.denom == other.denom)
def __ne__(self, other):
return not self.__eq__(other)
def _gcd_terms(terms):
"""Helper function for :func:`gcd_terms`. """
if isinstance(terms, Basic) and not isinstance(terms, Tuple):
terms = Add.make_args(terms)
if len(terms) <= 1:
if not terms:
return S.Zero, S.Zero, S.One
else:
return terms[0], S.One, S.One
terms = map(Term, terms)
cont = terms[0]
for term in terms[1:]:
cont = cont.gcd(term)
for i, term in enumerate(terms):
terms[i] = term.quo(cont)
denom = terms[0].denom
for term in terms[1:]:
denom = denom.lcm(term.denom)
numers = []
for term in terms:
numer = term.numer.mul(denom.quo(term.denom))
numers.append(term.coeff*numer.as_expr())
cont = cont.as_expr()
numer = Add(*numers)
denom = denom.as_expr()
if numer.is_Add:
_cont, numer = numer.primitive()
cont *= _cont
return cont, numer, denom
def gcd_terms(terms):
"""
Compute the GCD of ``terms`` and put them together.
**Example**
>>> from sympy.core import gcd_terms
>>> from sympy.abc import x, y
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
y*(x + 1)*(x + y + 1)
"""
from sympy.polys.polytools import _keep_coeff
cont, numer, denom = _gcd_terms(sympify(terms))
coeff, factors = cont.as_coeff_Mul()
return _keep_coeff(coeff, factors*numer/denom)