10 Hash of a sequence, that *depends* on the order of elements.
12 # make this more robust:
15 m
= hash(m
+ 1001 ^
hash(x
))
20 def __new__(cls
, type, args
):
21 obj
= object.__new
__(cls
)
23 obj
._args
= tuple(args
)
31 if self
.mhash
is None:
32 h
= hash_seq(self
.args
)
42 def as_coeff_rest(self
):
43 return (Integer(1), self
)
45 def as_base_exp(self
):
46 return (self
, Integer(1))
70 return Mul((x
, Pow((y
, Integer(-1)))))
73 return Mul((y
, Pow((x
, Integer(-1)))))
82 return Mul((Integer(-1), x
))
88 return not self
.__eq
__(x
)
92 if o
.type == self
.type:
93 return self
.args
== o
.args
101 obj
= Basic
.__new
__(cls
, INTEGER
, [])
106 if self
.mhash
is None:
115 if o
.type == INTEGER
:
123 def __add__(self
, o
):
125 if o
.type == INTEGER
:
126 return Integer(self
.i
+o
.i
)
127 return Basic
.__add
__(self
, o
)
129 def __mul__(self
, o
):
131 if o
.type == INTEGER
:
132 return Integer(self
.i
*o
.i
)
133 return Basic
.__mul
__(self
, o
)
138 def __new__(cls
, name
):
139 obj
= Basic
.__new
__(cls
, SYMBOL
, [])
144 if self
.mhash
is None:
154 return self
.name
== o
.name
163 def __new__(cls
, args
, canonicalize
=True):
164 if canonicalize
== False:
165 obj
= Basic
.__new
__(cls
, ADD
, args
)
168 args
= [sympify(x
) for x
in args
]
169 return Add
.canonicalize(args
)
172 def canonicalize(cls
, args
):
175 from csympy
import HashTable
181 if a
.type == INTEGER
:
185 if b
.type == INTEGER
:
188 coeff
, key
= b
.as_coeff_rest()
194 coeff
, key
= a
.as_coeff_rest()
202 for a
, b
in d
.iteritems():
203 args
.append(Mul((a
, b
)))
209 return Add(args
, False)
211 def freeze_args(self
):
212 #print "add is freezing"
213 if self
._args
_set
is None:
214 self
._args
_set
= frozenset(self
.args
)
222 return self
._args
_set
== o
._args
_set
227 s
= str(self
.args
[0])
228 if self
.args
[0].type == ADD
:
230 for x
in self
.args
[1:]:
231 s
= "%s + %s" % (s
, str(x
))
237 if self
.mhash
is None:
238 # XXX: it is surprising, but this is *not* faster:
240 #h = hash(self._args_set)
243 a
= list(self
.args
[:])
253 for term
in self
.args
:
254 r
.append( term
.expand() )
259 def __new__(cls
, args
, canonicalize
=True):
260 if canonicalize
== False:
261 obj
= Basic
.__new
__(cls
, MUL
, args
)
264 args
= [sympify(x
) for x
in args
]
265 return Mul
.canonicalize(args
)
268 def canonicalize(cls
, args
):
271 from csympy
import HashTable
275 if len(args
) == 2 and args
[0].type == MUL
and args
[1].type == INTEGER
:
278 assert b
.type == INTEGER
283 if a
.args
[0].type == INTEGER
:
285 args
= (b
,) + a
.args
[1:]
287 args
= (b
*a
.args
[0],) + a
.args
[1:]
290 return Mul(args
, False)
294 if a
.type == INTEGER
:
298 if b
.type == INTEGER
:
301 key
, coeff
= b
.as_base_exp()
307 key
, coeff
= a
.as_base_exp()
312 if num
.i
== 0 or len(d
)==0:
315 for a
, b
in d
.iteritems():
316 args
.append(Pow((a
, b
)))
322 return Mul(args
, False)
325 if self
.mhash
is None:
326 # in contrast to Add, here it is faster:
328 h
= hash(self
._args
_set
)
330 #a = list(self.args[:])
338 def freeze_args(self
):
339 #print "mul is freezing"
340 if self
._args
_set
is None:
341 self
._args
_set
= frozenset(self
.args
)
349 return self
._args
_set
== o
._args
_set
354 def as_coeff_rest(self
):
355 if self
.args
[0].type == INTEGER
:
356 return self
.as_two_terms()
357 return (Integer(1), self
)
359 def as_two_terms(self
):
366 return (a0
, Mul(args
[1:], False))
370 s
= str(self
.args
[0])
371 if self
.args
[0].type in [ADD
, MUL
]:
373 for x
in self
.args
[1:]:
374 if x
.type in [ADD
, MUL
]:
375 s
= "%s * (%s)" % (s
, str(x
))
377 s
= "%s*%s" % (s
, str(x
))
381 def expand_two(self
, a
, b
):
383 Both a and b are assumed to be expanded.
385 if a
.type == ADD
and b
.type == ADD
:
404 a
, b
= self
.as_two_terms()
405 r
= Mul
.expand_two(a
, b
)
409 return Mul
.expand_two(a
, b
)
415 def __new__(cls
, args
, canonicalize
=True, do_sympify
=True):
416 if canonicalize
== False:
417 obj
= Basic
.__new
__(cls
, POW
, args
)
420 args
= [sympify(x
) for x
in args
]
421 return Pow
.canonicalize(args
)
424 def canonicalize(cls
, args
):
426 if base
.type == INTEGER
:
431 if exp
.type == INTEGER
:
437 return Pow((base
.args
[0], base
.args
[1]*exp
))
438 return Pow(args
, False)
441 s
= str(self
.args
[0])
442 if self
.args
[0].type == ADD
:
444 if self
.args
[1].type == ADD
:
445 s
= "%s^(%s)" % (s
, str(self
.args
[1]))
447 s
= "%s^%s" % (s
, str(self
.args
[1]))
450 def as_base_exp(self
):
454 base
, exp
= self
.args
455 if base
.type == ADD
and exp
.type == INTEGER
:
459 d
= multinomial_coefficients(m
, n
)
462 for powers
, coeff
in d
.iteritems():
467 for x
, p
in zip(base
.args
, powers
):
472 tt
= Pow((x
, Integer(p
)), do_sympify
=False)
486 if isinstance(x
, int):
492 Create a symbolic variable with the name *s*.
495 s -- a string, either a single variable name, or
496 a space separated list of variable names, or
497 a list of variable names.
499 NOTE: The new variable is both returned and automatically injected into
500 the parent's *global* namespace. It's recommended not to use "var" in
501 library code, it is better to use symbols() instead.
504 We define some symbolic variables:
507 >>> var('n xx yy zz')
515 frame
= inspect
.currentframe().f_back
518 if not isinstance(s
, list):
519 s
= re
.split('\s|,', s
)
528 frame
.f_globals
[t
] = sym
532 if len(res
) == 0: # var('')
534 elif len(res
) == 1: # var('x')
536 # otherwise var('a b ...')
540 # we should explicitly break cyclic dependencies as stated in inspect
544 def binomial_coefficients(n
):
545 """Return a dictionary containing pairs {(k1,k2) : C_kn} where
546 C_kn are binomial coefficients and n=k1+k2."""
547 d
= {(0, n
):1, (n
, 0):1}
549 for k
in xrange(1, n
//2+1):
551 d
[k
, n
-k
] = d
[n
-k
, k
] = a
554 def binomial_coefficients_list(n
):
555 """ Return a list of binomial coefficients as rows of the Pascal's
560 for k
in xrange(1, n
//2+1):
565 def multinomial_coefficients(m
, n
, _tuple
=tuple, _zip
=zip):
566 """Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
567 where ``C_kn`` are multinomial coefficients such that
572 >>> print multinomial_coefficients(2,5)
573 {(3, 2): 10, (1, 4): 5, (2, 3): 10, (5, 0): 1, (0, 5): 1, (4, 1): 5}
575 The algorithm is based on the following result:
577 Consider a polynomial and it's ``m``-th exponent::
579 P(x) = sum_{i=0}^m p_i x^k
580 P(x)^n = sum_{k=0}^{m n} a(n,k) x^k
582 The coefficients ``a(n,k)`` can be computed using the
583 J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical
584 Algorithms, The art of Computer Programming v.2, Addison
585 Wesley, Reading, 1981;]::
587 a(n,k) = 1/(k p_0) sum_{i=1}^m p_i ((n+1)i-k) a(n,k-i),
589 where ``a(n,0) = p_0^n``.
593 return binomial_coefficients(n
)
594 symbols
= [(0,)*i
+ (1,) + (0,)*(m
-i
-1) for i
in range(m
)]
596 p0
= [_tuple(aa
-bb
for aa
,bb
in _zip(s
,s0
)) for s
in symbols
]
597 r
= {_tuple(aa
*n
for aa
in s0
):1}
600 l
= [0] * (n
*(m
-1)+1)
602 for k
in xrange(1, n
*(m
-1)+1):
605 for i
in xrange(1, min(m
,k
+1)):
610 for t2
, c2
in l
[k
-i
]:
611 tt
= _tuple([aa
+bb
for aa
,bb
in _zip(t2
,t
)])
622 r1
= [(t
, c
//k
) for (t
, c
) in d
.iteritems()]