Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py +1 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py +1102 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py +2563 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_factorials.py +650 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_numbers.py +852 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_beta_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_bsplines.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_delta_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_gamma_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_hyper.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_tensor_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_zeta_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py +59 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/commutator.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/constants.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/gate.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/identitysearch.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixcache.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/operatorordering.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/operatorset.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/pauli.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/piab.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/qapply.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/qubit.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/sho1d.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/shor.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/spin.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/state.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/trace.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py +149 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/boson.py +259 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py +341 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/cg.py +754 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py +370 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py +488 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py +239 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/constants.py +59 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py +97 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/density.py +319 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/fermion.py +179 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/gate.py +1305 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/grover.py +345 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py +653 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py +853 -0
- env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py +137 -0
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# Stub __init__.py for sympy.functions.combinatorial
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py
ADDED
@@ -0,0 +1,1102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from functools import reduce
|
3 |
+
|
4 |
+
from sympy.core import S, sympify, Dummy, Mod
|
5 |
+
from sympy.core.cache import cacheit
|
6 |
+
from sympy.core.function import Function, ArgumentIndexError, PoleError
|
7 |
+
from sympy.core.logic import fuzzy_and
|
8 |
+
from sympy.core.numbers import Integer, pi, I
|
9 |
+
from sympy.core.relational import Eq
|
10 |
+
from sympy.external.gmpy import HAS_GMPY, gmpy
|
11 |
+
from sympy.ntheory import sieve
|
12 |
+
from sympy.polys.polytools import Poly
|
13 |
+
|
14 |
+
from math import factorial as _factorial, prod, sqrt as _sqrt
|
15 |
+
|
16 |
+
class CombinatorialFunction(Function):
|
17 |
+
"""Base class for combinatorial functions. """
|
18 |
+
|
19 |
+
def _eval_simplify(self, **kwargs):
|
20 |
+
from sympy.simplify.combsimp import combsimp
|
21 |
+
# combinatorial function with non-integer arguments is
|
22 |
+
# automatically passed to gammasimp
|
23 |
+
expr = combsimp(self)
|
24 |
+
measure = kwargs['measure']
|
25 |
+
if measure(expr) <= kwargs['ratio']*measure(self):
|
26 |
+
return expr
|
27 |
+
return self
|
28 |
+
|
29 |
+
|
30 |
+
###############################################################################
|
31 |
+
######################## FACTORIAL and MULTI-FACTORIAL ########################
|
32 |
+
###############################################################################
|
33 |
+
|
34 |
+
|
35 |
+
class factorial(CombinatorialFunction):
|
36 |
+
r"""Implementation of factorial function over nonnegative integers.
|
37 |
+
By convention (consistent with the gamma function and the binomial
|
38 |
+
coefficients), factorial of a negative integer is complex infinity.
|
39 |
+
|
40 |
+
The factorial is very important in combinatorics where it gives
|
41 |
+
the number of ways in which `n` objects can be permuted. It also
|
42 |
+
arises in calculus, probability, number theory, etc.
|
43 |
+
|
44 |
+
There is strict relation of factorial with gamma function. In
|
45 |
+
fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this
|
46 |
+
kind is very useful in case of combinatorial simplification.
|
47 |
+
|
48 |
+
Computation of the factorial is done using two algorithms. For
|
49 |
+
small arguments a precomputed look up table is used. However for bigger
|
50 |
+
input algorithm Prime-Swing is used. It is the fastest algorithm
|
51 |
+
known and computes `n!` via prime factorization of special class
|
52 |
+
of numbers, called here the 'Swing Numbers'.
|
53 |
+
|
54 |
+
Examples
|
55 |
+
========
|
56 |
+
|
57 |
+
>>> from sympy import Symbol, factorial, S
|
58 |
+
>>> n = Symbol('n', integer=True)
|
59 |
+
|
60 |
+
>>> factorial(0)
|
61 |
+
1
|
62 |
+
|
63 |
+
>>> factorial(7)
|
64 |
+
5040
|
65 |
+
|
66 |
+
>>> factorial(-2)
|
67 |
+
zoo
|
68 |
+
|
69 |
+
>>> factorial(n)
|
70 |
+
factorial(n)
|
71 |
+
|
72 |
+
>>> factorial(2*n)
|
73 |
+
factorial(2*n)
|
74 |
+
|
75 |
+
>>> factorial(S(1)/2)
|
76 |
+
factorial(1/2)
|
77 |
+
|
78 |
+
See Also
|
79 |
+
========
|
80 |
+
|
81 |
+
factorial2, RisingFactorial, FallingFactorial
|
82 |
+
"""
|
83 |
+
|
84 |
+
def fdiff(self, argindex=1):
|
85 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
86 |
+
if argindex == 1:
|
87 |
+
return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1)
|
88 |
+
else:
|
89 |
+
raise ArgumentIndexError(self, argindex)
|
90 |
+
|
91 |
+
_small_swing = [
|
92 |
+
1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395,
|
93 |
+
12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075,
|
94 |
+
35102025, 5014575, 145422675, 9694845, 300540195, 300540195
|
95 |
+
]
|
96 |
+
|
97 |
+
_small_factorials: list[int] = []
|
98 |
+
|
99 |
+
@classmethod
|
100 |
+
def _swing(cls, n):
|
101 |
+
if n < 33:
|
102 |
+
return cls._small_swing[n]
|
103 |
+
else:
|
104 |
+
N, primes = int(_sqrt(n)), []
|
105 |
+
|
106 |
+
for prime in sieve.primerange(3, N + 1):
|
107 |
+
p, q = 1, n
|
108 |
+
|
109 |
+
while True:
|
110 |
+
q //= prime
|
111 |
+
|
112 |
+
if q > 0:
|
113 |
+
if q & 1 == 1:
|
114 |
+
p *= prime
|
115 |
+
else:
|
116 |
+
break
|
117 |
+
|
118 |
+
if p > 1:
|
119 |
+
primes.append(p)
|
120 |
+
|
121 |
+
for prime in sieve.primerange(N + 1, n//3 + 1):
|
122 |
+
if (n // prime) & 1 == 1:
|
123 |
+
primes.append(prime)
|
124 |
+
|
125 |
+
L_product = prod(sieve.primerange(n//2 + 1, n + 1))
|
126 |
+
R_product = prod(primes)
|
127 |
+
|
128 |
+
return L_product*R_product
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def _recursive(cls, n):
|
132 |
+
if n < 2:
|
133 |
+
return 1
|
134 |
+
else:
|
135 |
+
return (cls._recursive(n//2)**2)*cls._swing(n)
|
136 |
+
|
137 |
+
@classmethod
|
138 |
+
def eval(cls, n):
|
139 |
+
n = sympify(n)
|
140 |
+
|
141 |
+
if n.is_Number:
|
142 |
+
if n.is_zero:
|
143 |
+
return S.One
|
144 |
+
elif n is S.Infinity:
|
145 |
+
return S.Infinity
|
146 |
+
elif n.is_Integer:
|
147 |
+
if n.is_negative:
|
148 |
+
return S.ComplexInfinity
|
149 |
+
else:
|
150 |
+
n = n.p
|
151 |
+
|
152 |
+
if n < 20:
|
153 |
+
if not cls._small_factorials:
|
154 |
+
result = 1
|
155 |
+
for i in range(1, 20):
|
156 |
+
result *= i
|
157 |
+
cls._small_factorials.append(result)
|
158 |
+
result = cls._small_factorials[n-1]
|
159 |
+
|
160 |
+
# GMPY factorial is faster, use it when available
|
161 |
+
elif HAS_GMPY:
|
162 |
+
result = gmpy.fac(n)
|
163 |
+
|
164 |
+
else:
|
165 |
+
bits = bin(n).count('1')
|
166 |
+
result = cls._recursive(n)*2**(n - bits)
|
167 |
+
|
168 |
+
return Integer(result)
|
169 |
+
|
170 |
+
def _facmod(self, n, q):
|
171 |
+
res, N = 1, int(_sqrt(n))
|
172 |
+
|
173 |
+
# Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ...
|
174 |
+
# for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m,
|
175 |
+
# occur consecutively and are grouped together in pw[m] for
|
176 |
+
# simultaneous exponentiation at a later stage
|
177 |
+
pw = [1]*N
|
178 |
+
|
179 |
+
m = 2 # to initialize the if condition below
|
180 |
+
for prime in sieve.primerange(2, n + 1):
|
181 |
+
if m > 1:
|
182 |
+
m, y = 0, n // prime
|
183 |
+
while y:
|
184 |
+
m += y
|
185 |
+
y //= prime
|
186 |
+
if m < N:
|
187 |
+
pw[m] = pw[m]*prime % q
|
188 |
+
else:
|
189 |
+
res = res*pow(prime, m, q) % q
|
190 |
+
|
191 |
+
for ex, bs in enumerate(pw):
|
192 |
+
if ex == 0 or bs == 1:
|
193 |
+
continue
|
194 |
+
if bs == 0:
|
195 |
+
return 0
|
196 |
+
res = res*pow(bs, ex, q) % q
|
197 |
+
|
198 |
+
return res
|
199 |
+
|
200 |
+
def _eval_Mod(self, q):
|
201 |
+
n = self.args[0]
|
202 |
+
if n.is_integer and n.is_nonnegative and q.is_integer:
|
203 |
+
aq = abs(q)
|
204 |
+
d = aq - n
|
205 |
+
if d.is_nonpositive:
|
206 |
+
return S.Zero
|
207 |
+
else:
|
208 |
+
isprime = aq.is_prime
|
209 |
+
if d == 1:
|
210 |
+
# Apply Wilson's theorem (if a natural number n > 1
|
211 |
+
# is a prime number, then (n-1)! = -1 mod n) and
|
212 |
+
# its inverse (if n > 4 is a composite number, then
|
213 |
+
# (n-1)! = 0 mod n)
|
214 |
+
if isprime:
|
215 |
+
return -1 % q
|
216 |
+
elif isprime is False and (aq - 6).is_nonnegative:
|
217 |
+
return S.Zero
|
218 |
+
elif n.is_Integer and q.is_Integer:
|
219 |
+
n, d, aq = map(int, (n, d, aq))
|
220 |
+
if isprime and (d - 1 < n):
|
221 |
+
fc = self._facmod(d - 1, aq)
|
222 |
+
fc = pow(fc, aq - 2, aq)
|
223 |
+
if d%2:
|
224 |
+
fc = -fc
|
225 |
+
else:
|
226 |
+
fc = self._facmod(n, aq)
|
227 |
+
|
228 |
+
return fc % q
|
229 |
+
|
230 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
231 |
+
from sympy.functions.special.gamma_functions import gamma
|
232 |
+
return gamma(n + 1)
|
233 |
+
|
234 |
+
def _eval_rewrite_as_Product(self, n, **kwargs):
|
235 |
+
from sympy.concrete.products import Product
|
236 |
+
if n.is_nonnegative and n.is_integer:
|
237 |
+
i = Dummy('i', integer=True)
|
238 |
+
return Product(i, (i, 1, n))
|
239 |
+
|
240 |
+
def _eval_is_integer(self):
|
241 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
242 |
+
return True
|
243 |
+
|
244 |
+
def _eval_is_positive(self):
|
245 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
246 |
+
return True
|
247 |
+
|
248 |
+
def _eval_is_even(self):
|
249 |
+
x = self.args[0]
|
250 |
+
if x.is_integer and x.is_nonnegative:
|
251 |
+
return (x - 2).is_nonnegative
|
252 |
+
|
253 |
+
def _eval_is_composite(self):
|
254 |
+
x = self.args[0]
|
255 |
+
if x.is_integer and x.is_nonnegative:
|
256 |
+
return (x - 3).is_nonnegative
|
257 |
+
|
258 |
+
def _eval_is_real(self):
|
259 |
+
x = self.args[0]
|
260 |
+
if x.is_nonnegative or x.is_noninteger:
|
261 |
+
return True
|
262 |
+
|
263 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
264 |
+
arg = self.args[0].as_leading_term(x)
|
265 |
+
arg0 = arg.subs(x, 0)
|
266 |
+
if arg0.is_zero:
|
267 |
+
return S.One
|
268 |
+
elif not arg0.is_infinite:
|
269 |
+
return self.func(arg)
|
270 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
271 |
+
|
272 |
+
class MultiFactorial(CombinatorialFunction):
|
273 |
+
pass
|
274 |
+
|
275 |
+
|
276 |
+
class subfactorial(CombinatorialFunction):
|
277 |
+
r"""The subfactorial counts the derangements of $n$ items and is
|
278 |
+
defined for non-negative integers as:
|
279 |
+
|
280 |
+
.. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\
|
281 |
+
(n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases}
|
282 |
+
|
283 |
+
It can also be written as ``int(round(n!/exp(1)))`` but the
|
284 |
+
recursive definition with caching is implemented for this function.
|
285 |
+
|
286 |
+
An interesting analytic expression is the following [2]_
|
287 |
+
|
288 |
+
.. math:: !x = \Gamma(x + 1, -1)/e
|
289 |
+
|
290 |
+
which is valid for non-negative integers `x`. The above formula
|
291 |
+
is not very useful in case of non-integers. `\Gamma(x + 1, -1)` is
|
292 |
+
single-valued only for integral arguments `x`, elsewhere on the positive
|
293 |
+
real axis it has an infinite number of branches none of which are real.
|
294 |
+
|
295 |
+
References
|
296 |
+
==========
|
297 |
+
|
298 |
+
.. [1] https://en.wikipedia.org/wiki/Subfactorial
|
299 |
+
.. [2] https://mathworld.wolfram.com/Subfactorial.html
|
300 |
+
|
301 |
+
Examples
|
302 |
+
========
|
303 |
+
|
304 |
+
>>> from sympy import subfactorial
|
305 |
+
>>> from sympy.abc import n
|
306 |
+
>>> subfactorial(n + 1)
|
307 |
+
subfactorial(n + 1)
|
308 |
+
>>> subfactorial(5)
|
309 |
+
44
|
310 |
+
|
311 |
+
See Also
|
312 |
+
========
|
313 |
+
|
314 |
+
factorial, uppergamma,
|
315 |
+
sympy.utilities.iterables.generate_derangements
|
316 |
+
"""
|
317 |
+
|
318 |
+
@classmethod
|
319 |
+
@cacheit
|
320 |
+
def _eval(self, n):
|
321 |
+
if not n:
|
322 |
+
return S.One
|
323 |
+
elif n == 1:
|
324 |
+
return S.Zero
|
325 |
+
else:
|
326 |
+
z1, z2 = 1, 0
|
327 |
+
for i in range(2, n + 1):
|
328 |
+
z1, z2 = z2, (i - 1)*(z2 + z1)
|
329 |
+
return z2
|
330 |
+
|
331 |
+
@classmethod
|
332 |
+
def eval(cls, arg):
|
333 |
+
if arg.is_Number:
|
334 |
+
if arg.is_Integer and arg.is_nonnegative:
|
335 |
+
return cls._eval(arg)
|
336 |
+
elif arg is S.NaN:
|
337 |
+
return S.NaN
|
338 |
+
elif arg is S.Infinity:
|
339 |
+
return S.Infinity
|
340 |
+
|
341 |
+
def _eval_is_even(self):
|
342 |
+
if self.args[0].is_odd and self.args[0].is_nonnegative:
|
343 |
+
return True
|
344 |
+
|
345 |
+
def _eval_is_integer(self):
|
346 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
347 |
+
return True
|
348 |
+
|
349 |
+
def _eval_rewrite_as_factorial(self, arg, **kwargs):
|
350 |
+
from sympy.concrete.summations import summation
|
351 |
+
i = Dummy('i')
|
352 |
+
f = S.NegativeOne**i / factorial(i)
|
353 |
+
return factorial(arg) * summation(f, (i, 0, arg))
|
354 |
+
|
355 |
+
def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs):
|
356 |
+
from sympy.functions.elementary.exponential import exp
|
357 |
+
from sympy.functions.special.gamma_functions import (gamma, lowergamma)
|
358 |
+
return (S.NegativeOne**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1)
|
359 |
+
+ gamma(arg + 1))*exp(-1)
|
360 |
+
|
361 |
+
def _eval_rewrite_as_uppergamma(self, arg, **kwargs):
|
362 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
363 |
+
return uppergamma(arg + 1, -1)/S.Exp1
|
364 |
+
|
365 |
+
def _eval_is_nonnegative(self):
|
366 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
367 |
+
return True
|
368 |
+
|
369 |
+
def _eval_is_odd(self):
|
370 |
+
if self.args[0].is_even and self.args[0].is_nonnegative:
|
371 |
+
return True
|
372 |
+
|
373 |
+
|
374 |
+
class factorial2(CombinatorialFunction):
|
375 |
+
r"""The double factorial `n!!`, not to be confused with `(n!)!`
|
376 |
+
|
377 |
+
The double factorial is defined for nonnegative integers and for odd
|
378 |
+
negative integers as:
|
379 |
+
|
380 |
+
.. math:: n!! = \begin{cases} 1 & n = 0 \\
|
381 |
+
n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\
|
382 |
+
n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\
|
383 |
+
(n+2)!!/(n+2) & n\ \text{negative odd} \end{cases}
|
384 |
+
|
385 |
+
References
|
386 |
+
==========
|
387 |
+
|
388 |
+
.. [1] https://en.wikipedia.org/wiki/Double_factorial
|
389 |
+
|
390 |
+
Examples
|
391 |
+
========
|
392 |
+
|
393 |
+
>>> from sympy import factorial2, var
|
394 |
+
>>> n = var('n')
|
395 |
+
>>> n
|
396 |
+
n
|
397 |
+
>>> factorial2(n + 1)
|
398 |
+
factorial2(n + 1)
|
399 |
+
>>> factorial2(5)
|
400 |
+
15
|
401 |
+
>>> factorial2(-1)
|
402 |
+
1
|
403 |
+
>>> factorial2(-5)
|
404 |
+
1/3
|
405 |
+
|
406 |
+
See Also
|
407 |
+
========
|
408 |
+
|
409 |
+
factorial, RisingFactorial, FallingFactorial
|
410 |
+
"""
|
411 |
+
|
412 |
+
@classmethod
|
413 |
+
def eval(cls, arg):
|
414 |
+
# TODO: extend this to complex numbers?
|
415 |
+
|
416 |
+
if arg.is_Number:
|
417 |
+
if not arg.is_Integer:
|
418 |
+
raise ValueError("argument must be nonnegative integer "
|
419 |
+
"or negative odd integer")
|
420 |
+
|
421 |
+
# This implementation is faster than the recursive one
|
422 |
+
# It also avoids "maximum recursion depth exceeded" runtime error
|
423 |
+
if arg.is_nonnegative:
|
424 |
+
if arg.is_even:
|
425 |
+
k = arg / 2
|
426 |
+
return 2**k * factorial(k)
|
427 |
+
return factorial(arg) / factorial2(arg - 1)
|
428 |
+
|
429 |
+
|
430 |
+
if arg.is_odd:
|
431 |
+
return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg)
|
432 |
+
raise ValueError("argument must be nonnegative integer "
|
433 |
+
"or negative odd integer")
|
434 |
+
|
435 |
+
|
436 |
+
def _eval_is_even(self):
|
437 |
+
# Double factorial is even for every positive even input
|
438 |
+
n = self.args[0]
|
439 |
+
if n.is_integer:
|
440 |
+
if n.is_odd:
|
441 |
+
return False
|
442 |
+
if n.is_even:
|
443 |
+
if n.is_positive:
|
444 |
+
return True
|
445 |
+
if n.is_zero:
|
446 |
+
return False
|
447 |
+
|
448 |
+
def _eval_is_integer(self):
|
449 |
+
# Double factorial is an integer for every nonnegative input, and for
|
450 |
+
# -1 and -3
|
451 |
+
n = self.args[0]
|
452 |
+
if n.is_integer:
|
453 |
+
if (n + 1).is_nonnegative:
|
454 |
+
return True
|
455 |
+
if n.is_odd:
|
456 |
+
return (n + 3).is_nonnegative
|
457 |
+
|
458 |
+
def _eval_is_odd(self):
|
459 |
+
# Double factorial is odd for every odd input not smaller than -3, and
|
460 |
+
# for 0
|
461 |
+
n = self.args[0]
|
462 |
+
if n.is_odd:
|
463 |
+
return (n + 3).is_nonnegative
|
464 |
+
if n.is_even:
|
465 |
+
if n.is_positive:
|
466 |
+
return False
|
467 |
+
if n.is_zero:
|
468 |
+
return True
|
469 |
+
|
470 |
+
def _eval_is_positive(self):
|
471 |
+
# Double factorial is positive for every nonnegative input, and for
|
472 |
+
# every odd negative input which is of the form -1-4k for an
|
473 |
+
# nonnegative integer k
|
474 |
+
n = self.args[0]
|
475 |
+
if n.is_integer:
|
476 |
+
if (n + 1).is_nonnegative:
|
477 |
+
return True
|
478 |
+
if n.is_odd:
|
479 |
+
return ((n + 1) / 2).is_even
|
480 |
+
|
481 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
482 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
483 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
484 |
+
from sympy.functions.special.gamma_functions import gamma
|
485 |
+
return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)),
|
486 |
+
(sqrt(2/pi), Eq(Mod(n, 2), 1)))
|
487 |
+
|
488 |
+
|
489 |
+
###############################################################################
|
490 |
+
######################## RISING and FALLING FACTORIALS ########################
|
491 |
+
###############################################################################
|
492 |
+
|
493 |
+
|
494 |
+
class RisingFactorial(CombinatorialFunction):
|
495 |
+
r"""
|
496 |
+
Rising factorial (also called Pochhammer symbol [1]_) is a double valued
|
497 |
+
function arising in concrete mathematics, hypergeometric functions
|
498 |
+
and series expansions. It is defined by:
|
499 |
+
|
500 |
+
.. math:: \texttt{rf(y, k)} = (x)^k = x \cdot (x+1) \cdots (x+k-1)
|
501 |
+
|
502 |
+
where `x` can be arbitrary expression and `k` is an integer. For
|
503 |
+
more information check "Concrete mathematics" by Graham, pp. 66
|
504 |
+
or visit https://mathworld.wolfram.com/RisingFactorial.html page.
|
505 |
+
|
506 |
+
When `x` is a `~.Poly` instance of degree $\ge 1$ with a single variable,
|
507 |
+
`(x)^k = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the
|
508 |
+
variable of `x`. This is as described in [2]_.
|
509 |
+
|
510 |
+
Examples
|
511 |
+
========
|
512 |
+
|
513 |
+
>>> from sympy import rf, Poly
|
514 |
+
>>> from sympy.abc import x
|
515 |
+
>>> rf(x, 0)
|
516 |
+
1
|
517 |
+
>>> rf(1, 5)
|
518 |
+
120
|
519 |
+
>>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x)
|
520 |
+
True
|
521 |
+
>>> rf(Poly(x**3, x), 2)
|
522 |
+
Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ')
|
523 |
+
|
524 |
+
Rewriting is complicated unless the relationship between
|
525 |
+
the arguments is known, but rising factorial can
|
526 |
+
be rewritten in terms of gamma, factorial, binomial,
|
527 |
+
and falling factorial.
|
528 |
+
|
529 |
+
>>> from sympy import Symbol, factorial, ff, binomial, gamma
|
530 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
531 |
+
>>> R = rf(n, n + 2)
|
532 |
+
>>> for i in (rf, ff, factorial, binomial, gamma):
|
533 |
+
... R.rewrite(i)
|
534 |
+
...
|
535 |
+
RisingFactorial(n, n + 2)
|
536 |
+
FallingFactorial(2*n + 1, n + 2)
|
537 |
+
factorial(2*n + 1)/factorial(n - 1)
|
538 |
+
binomial(2*n + 1, n + 2)*factorial(n + 2)
|
539 |
+
gamma(2*n + 2)/gamma(n)
|
540 |
+
|
541 |
+
See Also
|
542 |
+
========
|
543 |
+
|
544 |
+
factorial, factorial2, FallingFactorial
|
545 |
+
|
546 |
+
References
|
547 |
+
==========
|
548 |
+
|
549 |
+
.. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol
|
550 |
+
.. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
|
551 |
+
Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
|
552 |
+
1995.
|
553 |
+
|
554 |
+
"""
|
555 |
+
|
556 |
+
@classmethod
|
557 |
+
def eval(cls, x, k):
|
558 |
+
x = sympify(x)
|
559 |
+
k = sympify(k)
|
560 |
+
|
561 |
+
if x is S.NaN or k is S.NaN:
|
562 |
+
return S.NaN
|
563 |
+
elif x is S.One:
|
564 |
+
return factorial(k)
|
565 |
+
elif k.is_Integer:
|
566 |
+
if k.is_zero:
|
567 |
+
return S.One
|
568 |
+
else:
|
569 |
+
if k.is_positive:
|
570 |
+
if x is S.Infinity:
|
571 |
+
return S.Infinity
|
572 |
+
elif x is S.NegativeInfinity:
|
573 |
+
if k.is_odd:
|
574 |
+
return S.NegativeInfinity
|
575 |
+
else:
|
576 |
+
return S.Infinity
|
577 |
+
else:
|
578 |
+
if isinstance(x, Poly):
|
579 |
+
gens = x.gens
|
580 |
+
if len(gens)!= 1:
|
581 |
+
raise ValueError("rf only defined for "
|
582 |
+
"polynomials on one generator")
|
583 |
+
else:
|
584 |
+
return reduce(lambda r, i:
|
585 |
+
r*(x.shift(i)),
|
586 |
+
range(int(k)), 1)
|
587 |
+
else:
|
588 |
+
return reduce(lambda r, i: r*(x + i),
|
589 |
+
range(int(k)), 1)
|
590 |
+
|
591 |
+
else:
|
592 |
+
if x is S.Infinity:
|
593 |
+
return S.Infinity
|
594 |
+
elif x is S.NegativeInfinity:
|
595 |
+
return S.Infinity
|
596 |
+
else:
|
597 |
+
if isinstance(x, Poly):
|
598 |
+
gens = x.gens
|
599 |
+
if len(gens)!= 1:
|
600 |
+
raise ValueError("rf only defined for "
|
601 |
+
"polynomials on one generator")
|
602 |
+
else:
|
603 |
+
return 1/reduce(lambda r, i:
|
604 |
+
r*(x.shift(-i)),
|
605 |
+
range(1, abs(int(k)) + 1), 1)
|
606 |
+
else:
|
607 |
+
return 1/reduce(lambda r, i:
|
608 |
+
r*(x - i),
|
609 |
+
range(1, abs(int(k)) + 1), 1)
|
610 |
+
|
611 |
+
if k.is_integer == False:
|
612 |
+
if x.is_integer and x.is_negative:
|
613 |
+
return S.Zero
|
614 |
+
|
615 |
+
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
|
616 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
617 |
+
from sympy.functions.special.gamma_functions import gamma
|
618 |
+
if not piecewise:
|
619 |
+
if (x <= 0) == True:
|
620 |
+
return S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1)
|
621 |
+
return gamma(x + k) / gamma(x)
|
622 |
+
return Piecewise(
|
623 |
+
(gamma(x + k) / gamma(x), x > 0),
|
624 |
+
(S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1), True))
|
625 |
+
|
626 |
+
def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs):
|
627 |
+
return FallingFactorial(x + k - 1, k)
|
628 |
+
|
629 |
+
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
|
630 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
631 |
+
if x.is_integer and k.is_integer:
|
632 |
+
return Piecewise(
|
633 |
+
(factorial(k + x - 1)/factorial(x - 1), x > 0),
|
634 |
+
(S.NegativeOne**k*factorial(-x)/factorial(-k - x), True))
|
635 |
+
|
636 |
+
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
|
637 |
+
if k.is_integer:
|
638 |
+
return factorial(k) * binomial(x + k - 1, k)
|
639 |
+
|
640 |
+
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
|
641 |
+
from sympy.functions.special.gamma_functions import gamma
|
642 |
+
if limitvar:
|
643 |
+
k_lim = k.subs(limitvar, S.Infinity)
|
644 |
+
if k_lim is S.Infinity:
|
645 |
+
return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x))
|
646 |
+
elif k_lim is S.NegativeInfinity:
|
647 |
+
return (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True))
|
648 |
+
return self.rewrite(gamma).rewrite('tractable', deep=True)
|
649 |
+
|
650 |
+
def _eval_is_integer(self):
|
651 |
+
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
|
652 |
+
self.args[1].is_nonnegative))
|
653 |
+
|
654 |
+
|
655 |
+
class FallingFactorial(CombinatorialFunction):
|
656 |
+
r"""
|
657 |
+
Falling factorial (related to rising factorial) is a double valued
|
658 |
+
function arising in concrete mathematics, hypergeometric functions
|
659 |
+
and series expansions. It is defined by
|
660 |
+
|
661 |
+
.. math:: \texttt{ff(x, k)} = (x)_k = x \cdot (x-1) \cdots (x-k+1)
|
662 |
+
|
663 |
+
where `x` can be arbitrary expression and `k` is an integer. For
|
664 |
+
more information check "Concrete mathematics" by Graham, pp. 66
|
665 |
+
or [1]_.
|
666 |
+
|
667 |
+
When `x` is a `~.Poly` instance of degree $\ge 1$ with single variable,
|
668 |
+
`(x)_k = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the
|
669 |
+
variable of `x`. This is as described in
|
670 |
+
|
671 |
+
>>> from sympy import ff, Poly, Symbol
|
672 |
+
>>> from sympy.abc import x
|
673 |
+
>>> n = Symbol('n', integer=True)
|
674 |
+
|
675 |
+
>>> ff(x, 0)
|
676 |
+
1
|
677 |
+
>>> ff(5, 5)
|
678 |
+
120
|
679 |
+
>>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
|
680 |
+
True
|
681 |
+
>>> ff(Poly(x**2, x), 2)
|
682 |
+
Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ')
|
683 |
+
>>> ff(n, n)
|
684 |
+
factorial(n)
|
685 |
+
|
686 |
+
Rewriting is complicated unless the relationship between
|
687 |
+
the arguments is known, but falling factorial can
|
688 |
+
be rewritten in terms of gamma, factorial and binomial
|
689 |
+
and rising factorial.
|
690 |
+
|
691 |
+
>>> from sympy import factorial, rf, gamma, binomial, Symbol
|
692 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
693 |
+
>>> F = ff(n, n - 2)
|
694 |
+
>>> for i in (rf, ff, factorial, binomial, gamma):
|
695 |
+
... F.rewrite(i)
|
696 |
+
...
|
697 |
+
RisingFactorial(3, n - 2)
|
698 |
+
FallingFactorial(n, n - 2)
|
699 |
+
factorial(n)/2
|
700 |
+
binomial(n, n - 2)*factorial(n - 2)
|
701 |
+
gamma(n + 1)/2
|
702 |
+
|
703 |
+
See Also
|
704 |
+
========
|
705 |
+
|
706 |
+
factorial, factorial2, RisingFactorial
|
707 |
+
|
708 |
+
References
|
709 |
+
==========
|
710 |
+
|
711 |
+
.. [1] https://mathworld.wolfram.com/FallingFactorial.html
|
712 |
+
.. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
|
713 |
+
Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
|
714 |
+
1995.
|
715 |
+
|
716 |
+
"""
|
717 |
+
|
718 |
+
@classmethod
|
719 |
+
def eval(cls, x, k):
|
720 |
+
x = sympify(x)
|
721 |
+
k = sympify(k)
|
722 |
+
|
723 |
+
if x is S.NaN or k is S.NaN:
|
724 |
+
return S.NaN
|
725 |
+
elif k.is_integer and x == k:
|
726 |
+
return factorial(x)
|
727 |
+
elif k.is_Integer:
|
728 |
+
if k.is_zero:
|
729 |
+
return S.One
|
730 |
+
else:
|
731 |
+
if k.is_positive:
|
732 |
+
if x is S.Infinity:
|
733 |
+
return S.Infinity
|
734 |
+
elif x is S.NegativeInfinity:
|
735 |
+
if k.is_odd:
|
736 |
+
return S.NegativeInfinity
|
737 |
+
else:
|
738 |
+
return S.Infinity
|
739 |
+
else:
|
740 |
+
if isinstance(x, Poly):
|
741 |
+
gens = x.gens
|
742 |
+
if len(gens)!= 1:
|
743 |
+
raise ValueError("ff only defined for "
|
744 |
+
"polynomials on one generator")
|
745 |
+
else:
|
746 |
+
return reduce(lambda r, i:
|
747 |
+
r*(x.shift(-i)),
|
748 |
+
range(int(k)), 1)
|
749 |
+
else:
|
750 |
+
return reduce(lambda r, i: r*(x - i),
|
751 |
+
range(int(k)), 1)
|
752 |
+
else:
|
753 |
+
if x is S.Infinity:
|
754 |
+
return S.Infinity
|
755 |
+
elif x is S.NegativeInfinity:
|
756 |
+
return S.Infinity
|
757 |
+
else:
|
758 |
+
if isinstance(x, Poly):
|
759 |
+
gens = x.gens
|
760 |
+
if len(gens)!= 1:
|
761 |
+
raise ValueError("rf only defined for "
|
762 |
+
"polynomials on one generator")
|
763 |
+
else:
|
764 |
+
return 1/reduce(lambda r, i:
|
765 |
+
r*(x.shift(i)),
|
766 |
+
range(1, abs(int(k)) + 1), 1)
|
767 |
+
else:
|
768 |
+
return 1/reduce(lambda r, i: r*(x + i),
|
769 |
+
range(1, abs(int(k)) + 1), 1)
|
770 |
+
|
771 |
+
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
|
772 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
773 |
+
from sympy.functions.special.gamma_functions import gamma
|
774 |
+
if not piecewise:
|
775 |
+
if (x < 0) == True:
|
776 |
+
return S.NegativeOne**k*gamma(k - x) / gamma(-x)
|
777 |
+
return gamma(x + 1) / gamma(x - k + 1)
|
778 |
+
return Piecewise(
|
779 |
+
(gamma(x + 1) / gamma(x - k + 1), x >= 0),
|
780 |
+
(S.NegativeOne**k*gamma(k - x) / gamma(-x), True))
|
781 |
+
|
782 |
+
def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs):
|
783 |
+
return rf(x - k + 1, k)
|
784 |
+
|
785 |
+
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
|
786 |
+
if k.is_integer:
|
787 |
+
return factorial(k) * binomial(x, k)
|
788 |
+
|
789 |
+
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
|
790 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
791 |
+
if x.is_integer and k.is_integer:
|
792 |
+
return Piecewise(
|
793 |
+
(factorial(x)/factorial(-k + x), x >= 0),
|
794 |
+
(S.NegativeOne**k*factorial(k - x - 1)/factorial(-x - 1), True))
|
795 |
+
|
796 |
+
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
|
797 |
+
from sympy.functions.special.gamma_functions import gamma
|
798 |
+
if limitvar:
|
799 |
+
k_lim = k.subs(limitvar, S.Infinity)
|
800 |
+
if k_lim is S.Infinity:
|
801 |
+
return (S.NegativeOne**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x))
|
802 |
+
elif k_lim is S.NegativeInfinity:
|
803 |
+
return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True))
|
804 |
+
return self.rewrite(gamma).rewrite('tractable', deep=True)
|
805 |
+
|
806 |
+
def _eval_is_integer(self):
|
807 |
+
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
|
808 |
+
self.args[1].is_nonnegative))
|
809 |
+
|
810 |
+
|
811 |
+
rf = RisingFactorial
|
812 |
+
ff = FallingFactorial
|
813 |
+
|
814 |
+
###############################################################################
|
815 |
+
########################### BINOMIAL COEFFICIENTS #############################
|
816 |
+
###############################################################################
|
817 |
+
|
818 |
+
|
819 |
+
class binomial(CombinatorialFunction):
|
820 |
+
r"""Implementation of the binomial coefficient. It can be defined
|
821 |
+
in two ways depending on its desired interpretation:
|
822 |
+
|
823 |
+
.. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\
|
824 |
+
\binom{n}{k} = \frac{(n)_k}{k!}
|
825 |
+
|
826 |
+
First, in a strict combinatorial sense it defines the
|
827 |
+
number of ways we can choose `k` elements from a set of
|
828 |
+
`n` elements. In this case both arguments are nonnegative
|
829 |
+
integers and binomial is computed using an efficient
|
830 |
+
algorithm based on prime factorization.
|
831 |
+
|
832 |
+
The other definition is generalization for arbitrary `n`,
|
833 |
+
however `k` must also be nonnegative. This case is very
|
834 |
+
useful when evaluating summations.
|
835 |
+
|
836 |
+
For the sake of convenience, for negative integer `k` this function
|
837 |
+
will return zero no matter the other argument.
|
838 |
+
|
839 |
+
To expand the binomial when `n` is a symbol, use either
|
840 |
+
``expand_func()`` or ``expand(func=True)``. The former will keep
|
841 |
+
the polynomial in factored form while the latter will expand the
|
842 |
+
polynomial itself. See examples for details.
|
843 |
+
|
844 |
+
Examples
|
845 |
+
========
|
846 |
+
|
847 |
+
>>> from sympy import Symbol, Rational, binomial, expand_func
|
848 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
849 |
+
|
850 |
+
>>> binomial(15, 8)
|
851 |
+
6435
|
852 |
+
|
853 |
+
>>> binomial(n, -1)
|
854 |
+
0
|
855 |
+
|
856 |
+
Rows of Pascal's triangle can be generated with the binomial function:
|
857 |
+
|
858 |
+
>>> for N in range(8):
|
859 |
+
... print([binomial(N, i) for i in range(N + 1)])
|
860 |
+
...
|
861 |
+
[1]
|
862 |
+
[1, 1]
|
863 |
+
[1, 2, 1]
|
864 |
+
[1, 3, 3, 1]
|
865 |
+
[1, 4, 6, 4, 1]
|
866 |
+
[1, 5, 10, 10, 5, 1]
|
867 |
+
[1, 6, 15, 20, 15, 6, 1]
|
868 |
+
[1, 7, 21, 35, 35, 21, 7, 1]
|
869 |
+
|
870 |
+
As can a given diagonal, e.g. the 4th diagonal:
|
871 |
+
|
872 |
+
>>> N = -4
|
873 |
+
>>> [binomial(N, i) for i in range(1 - N)]
|
874 |
+
[1, -4, 10, -20, 35]
|
875 |
+
|
876 |
+
>>> binomial(Rational(5, 4), 3)
|
877 |
+
-5/128
|
878 |
+
>>> binomial(Rational(-5, 4), 3)
|
879 |
+
-195/128
|
880 |
+
|
881 |
+
>>> binomial(n, 3)
|
882 |
+
binomial(n, 3)
|
883 |
+
|
884 |
+
>>> binomial(n, 3).expand(func=True)
|
885 |
+
n**3/6 - n**2/2 + n/3
|
886 |
+
|
887 |
+
>>> expand_func(binomial(n, 3))
|
888 |
+
n*(n - 2)*(n - 1)/6
|
889 |
+
|
890 |
+
References
|
891 |
+
==========
|
892 |
+
|
893 |
+
.. [1] https://www.johndcook.com/blog/binomial_coefficients/
|
894 |
+
|
895 |
+
"""
|
896 |
+
|
897 |
+
def fdiff(self, argindex=1):
|
898 |
+
from sympy.functions.special.gamma_functions import polygamma
|
899 |
+
if argindex == 1:
|
900 |
+
# https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/
|
901 |
+
n, k = self.args
|
902 |
+
return binomial(n, k)*(polygamma(0, n + 1) - \
|
903 |
+
polygamma(0, n - k + 1))
|
904 |
+
elif argindex == 2:
|
905 |
+
# https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/
|
906 |
+
n, k = self.args
|
907 |
+
return binomial(n, k)*(polygamma(0, n - k + 1) - \
|
908 |
+
polygamma(0, k + 1))
|
909 |
+
else:
|
910 |
+
raise ArgumentIndexError(self, argindex)
|
911 |
+
|
912 |
+
@classmethod
|
913 |
+
def _eval(self, n, k):
|
914 |
+
# n.is_Number and k.is_Integer and k != 1 and n != k
|
915 |
+
|
916 |
+
if k.is_Integer:
|
917 |
+
if n.is_Integer and n >= 0:
|
918 |
+
n, k = int(n), int(k)
|
919 |
+
|
920 |
+
if k > n:
|
921 |
+
return S.Zero
|
922 |
+
elif k > n // 2:
|
923 |
+
k = n - k
|
924 |
+
|
925 |
+
if HAS_GMPY:
|
926 |
+
return Integer(gmpy.bincoef(n, k))
|
927 |
+
|
928 |
+
d, result = n - k, 1
|
929 |
+
for i in range(1, k + 1):
|
930 |
+
d += 1
|
931 |
+
result = result * d // i
|
932 |
+
return Integer(result)
|
933 |
+
else:
|
934 |
+
d, result = n - k, 1
|
935 |
+
for i in range(1, k + 1):
|
936 |
+
d += 1
|
937 |
+
result *= d
|
938 |
+
return result / _factorial(k)
|
939 |
+
|
940 |
+
@classmethod
|
941 |
+
def eval(cls, n, k):
|
942 |
+
n, k = map(sympify, (n, k))
|
943 |
+
d = n - k
|
944 |
+
n_nonneg, n_isint = n.is_nonnegative, n.is_integer
|
945 |
+
if k.is_zero or ((n_nonneg or n_isint is False)
|
946 |
+
and d.is_zero):
|
947 |
+
return S.One
|
948 |
+
if (k - 1).is_zero or ((n_nonneg or n_isint is False)
|
949 |
+
and (d - 1).is_zero):
|
950 |
+
return n
|
951 |
+
if k.is_integer:
|
952 |
+
if k.is_negative or (n_nonneg and n_isint and d.is_negative):
|
953 |
+
return S.Zero
|
954 |
+
elif n.is_number:
|
955 |
+
res = cls._eval(n, k)
|
956 |
+
return res.expand(basic=True) if res else res
|
957 |
+
elif n_nonneg is False and n_isint:
|
958 |
+
# a special case when binomial evaluates to complex infinity
|
959 |
+
return S.ComplexInfinity
|
960 |
+
elif k.is_number:
|
961 |
+
from sympy.functions.special.gamma_functions import gamma
|
962 |
+
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
963 |
+
|
964 |
+
def _eval_Mod(self, q):
|
965 |
+
n, k = self.args
|
966 |
+
|
967 |
+
if any(x.is_integer is False for x in (n, k, q)):
|
968 |
+
raise ValueError("Integers expected for binomial Mod")
|
969 |
+
|
970 |
+
if all(x.is_Integer for x in (n, k, q)):
|
971 |
+
n, k = map(int, (n, k))
|
972 |
+
aq, res = abs(q), 1
|
973 |
+
|
974 |
+
# handle negative integers k or n
|
975 |
+
if k < 0:
|
976 |
+
return S.Zero
|
977 |
+
if n < 0:
|
978 |
+
n = -n + k - 1
|
979 |
+
res = -1 if k%2 else 1
|
980 |
+
|
981 |
+
# non negative integers k and n
|
982 |
+
if k > n:
|
983 |
+
return S.Zero
|
984 |
+
|
985 |
+
isprime = aq.is_prime
|
986 |
+
aq = int(aq)
|
987 |
+
if isprime:
|
988 |
+
if aq < n:
|
989 |
+
# use Lucas Theorem
|
990 |
+
N, K = n, k
|
991 |
+
while N or K:
|
992 |
+
res = res*binomial(N % aq, K % aq) % aq
|
993 |
+
N, K = N // aq, K // aq
|
994 |
+
|
995 |
+
else:
|
996 |
+
# use Factorial Modulo
|
997 |
+
d = n - k
|
998 |
+
if k > d:
|
999 |
+
k, d = d, k
|
1000 |
+
kf = 1
|
1001 |
+
for i in range(2, k + 1):
|
1002 |
+
kf = kf*i % aq
|
1003 |
+
df = kf
|
1004 |
+
for i in range(k + 1, d + 1):
|
1005 |
+
df = df*i % aq
|
1006 |
+
res *= df
|
1007 |
+
for i in range(d + 1, n + 1):
|
1008 |
+
res = res*i % aq
|
1009 |
+
|
1010 |
+
res *= pow(kf*df % aq, aq - 2, aq)
|
1011 |
+
res %= aq
|
1012 |
+
|
1013 |
+
else:
|
1014 |
+
# Binomial Factorization is performed by calculating the
|
1015 |
+
# exponents of primes <= n in `n! /(k! (n - k)!)`,
|
1016 |
+
# for non-negative integers n and k. As the exponent of
|
1017 |
+
# prime in n! is e_p(n) = [n/p] + [n/p**2] + ...
|
1018 |
+
# the exponent of prime in binomial(n, k) would be
|
1019 |
+
# e_p(n) - e_p(k) - e_p(n - k)
|
1020 |
+
M = int(_sqrt(n))
|
1021 |
+
for prime in sieve.primerange(2, n + 1):
|
1022 |
+
if prime > n - k:
|
1023 |
+
res = res*prime % aq
|
1024 |
+
elif prime > n // 2:
|
1025 |
+
continue
|
1026 |
+
elif prime > M:
|
1027 |
+
if n % prime < k % prime:
|
1028 |
+
res = res*prime % aq
|
1029 |
+
else:
|
1030 |
+
N, K = n, k
|
1031 |
+
exp = a = 0
|
1032 |
+
|
1033 |
+
while N > 0:
|
1034 |
+
a = int((N % prime) < (K % prime + a))
|
1035 |
+
N, K = N // prime, K // prime
|
1036 |
+
exp += a
|
1037 |
+
|
1038 |
+
if exp > 0:
|
1039 |
+
res *= pow(prime, exp, aq)
|
1040 |
+
res %= aq
|
1041 |
+
|
1042 |
+
return S(res % q)
|
1043 |
+
|
1044 |
+
def _eval_expand_func(self, **hints):
|
1045 |
+
"""
|
1046 |
+
Function to expand binomial(n, k) when m is positive integer
|
1047 |
+
Also,
|
1048 |
+
n is self.args[0] and k is self.args[1] while using binomial(n, k)
|
1049 |
+
"""
|
1050 |
+
n = self.args[0]
|
1051 |
+
if n.is_Number:
|
1052 |
+
return binomial(*self.args)
|
1053 |
+
|
1054 |
+
k = self.args[1]
|
1055 |
+
if (n-k).is_Integer:
|
1056 |
+
k = n - k
|
1057 |
+
|
1058 |
+
if k.is_Integer:
|
1059 |
+
if k.is_zero:
|
1060 |
+
return S.One
|
1061 |
+
elif k.is_negative:
|
1062 |
+
return S.Zero
|
1063 |
+
else:
|
1064 |
+
n, result = self.args[0], 1
|
1065 |
+
for i in range(1, k + 1):
|
1066 |
+
result *= n - k + i
|
1067 |
+
return result / _factorial(k)
|
1068 |
+
else:
|
1069 |
+
return binomial(*self.args)
|
1070 |
+
|
1071 |
+
def _eval_rewrite_as_factorial(self, n, k, **kwargs):
|
1072 |
+
return factorial(n)/(factorial(k)*factorial(n - k))
|
1073 |
+
|
1074 |
+
def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs):
|
1075 |
+
from sympy.functions.special.gamma_functions import gamma
|
1076 |
+
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
1077 |
+
|
1078 |
+
def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs):
|
1079 |
+
return self._eval_rewrite_as_gamma(n, k).rewrite('tractable')
|
1080 |
+
|
1081 |
+
def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs):
|
1082 |
+
if k.is_integer:
|
1083 |
+
return ff(n, k) / factorial(k)
|
1084 |
+
|
1085 |
+
def _eval_is_integer(self):
|
1086 |
+
n, k = self.args
|
1087 |
+
if n.is_integer and k.is_integer:
|
1088 |
+
return True
|
1089 |
+
elif k.is_integer is False:
|
1090 |
+
return False
|
1091 |
+
|
1092 |
+
def _eval_is_nonnegative(self):
|
1093 |
+
n, k = self.args
|
1094 |
+
if n.is_integer and k.is_integer:
|
1095 |
+
if n.is_nonnegative or k.is_negative or k.is_even:
|
1096 |
+
return True
|
1097 |
+
elif k.is_even is False:
|
1098 |
+
return False
|
1099 |
+
|
1100 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1101 |
+
from sympy.functions.special.gamma_functions import gamma
|
1102 |
+
return self.rewrite(gamma)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py
ADDED
@@ -0,0 +1,2563 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module implements some special functions that commonly appear in
|
3 |
+
combinatorial contexts (e.g. in power series); in particular,
|
4 |
+
sequences of rational numbers such as Bernoulli and Fibonacci numbers.
|
5 |
+
|
6 |
+
Factorials, binomial coefficients and related functions are located in
|
7 |
+
the separate 'factorials' module.
|
8 |
+
"""
|
9 |
+
from math import prod
|
10 |
+
from collections import defaultdict
|
11 |
+
from typing import Tuple as tTuple
|
12 |
+
|
13 |
+
from sympy.core import S, Symbol, Add, Dummy
|
14 |
+
from sympy.core.cache import cacheit
|
15 |
+
from sympy.core.expr import Expr
|
16 |
+
from sympy.core.function import ArgumentIndexError, Function, expand_mul
|
17 |
+
from sympy.core.logic import fuzzy_not
|
18 |
+
from sympy.core.mul import Mul
|
19 |
+
from sympy.core.numbers import E, I, pi, oo, Rational, Integer
|
20 |
+
from sympy.core.relational import Eq, is_le, is_gt
|
21 |
+
from sympy.external.gmpy import SYMPY_INTS
|
22 |
+
from sympy.functions.combinatorial.factorials import (binomial,
|
23 |
+
factorial, subfactorial)
|
24 |
+
from sympy.functions.elementary.exponential import log
|
25 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
26 |
+
from sympy.ntheory.primetest import isprime, is_square
|
27 |
+
from sympy.polys.appellseqs import bernoulli_poly, euler_poly, genocchi_poly
|
28 |
+
from sympy.utilities.enumerative import MultisetPartitionTraverser
|
29 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
30 |
+
from sympy.utilities.iterables import multiset, multiset_derangements, iterable
|
31 |
+
from sympy.utilities.memoization import recurrence_memo
|
32 |
+
from sympy.utilities.misc import as_int
|
33 |
+
|
34 |
+
from mpmath import mp, workprec
|
35 |
+
from mpmath.libmp import ifib as _ifib
|
36 |
+
|
37 |
+
|
38 |
+
def _product(a, b):
|
39 |
+
return prod(range(a, b + 1))
|
40 |
+
|
41 |
+
|
42 |
+
# Dummy symbol used for computing polynomial sequences
|
43 |
+
_sym = Symbol('x')
|
44 |
+
|
45 |
+
|
46 |
+
#----------------------------------------------------------------------------#
|
47 |
+
# #
|
48 |
+
# Carmichael numbers #
|
49 |
+
# #
|
50 |
+
#----------------------------------------------------------------------------#
|
51 |
+
|
52 |
+
def _divides(p, n):
|
53 |
+
return n % p == 0
|
54 |
+
|
55 |
+
class carmichael(Function):
|
56 |
+
r"""
|
57 |
+
Carmichael Numbers:
|
58 |
+
|
59 |
+
Certain cryptographic algorithms make use of big prime numbers.
|
60 |
+
However, checking whether a big number is prime is not so easy.
|
61 |
+
Randomized prime number checking tests exist that offer a high degree of
|
62 |
+
confidence of accurate determination at low cost, such as the Fermat test.
|
63 |
+
|
64 |
+
Let 'a' be a random number between $2$ and $n - 1$, where $n$ is the
|
65 |
+
number whose primality we are testing. Then, $n$ is probably prime if it
|
66 |
+
satisfies the modular arithmetic congruence relation:
|
67 |
+
|
68 |
+
.. math :: a^{n-1} = 1 \pmod{n}
|
69 |
+
|
70 |
+
(where mod refers to the modulo operation)
|
71 |
+
|
72 |
+
If a number passes the Fermat test several times, then it is prime with a
|
73 |
+
high probability.
|
74 |
+
|
75 |
+
Unfortunately, certain composite numbers (non-primes) still pass the Fermat
|
76 |
+
test with every number smaller than themselves.
|
77 |
+
These numbers are called Carmichael numbers.
|
78 |
+
|
79 |
+
A Carmichael number will pass a Fermat primality test to every base $b$
|
80 |
+
relatively prime to the number, even though it is not actually prime.
|
81 |
+
This makes tests based on Fermat's Little Theorem less effective than
|
82 |
+
strong probable prime tests such as the Baillie-PSW primality test and
|
83 |
+
the Miller-Rabin primality test.
|
84 |
+
|
85 |
+
Examples
|
86 |
+
========
|
87 |
+
|
88 |
+
>>> from sympy import carmichael
|
89 |
+
>>> carmichael.find_first_n_carmichaels(5)
|
90 |
+
[561, 1105, 1729, 2465, 2821]
|
91 |
+
>>> carmichael.find_carmichael_numbers_in_range(0, 562)
|
92 |
+
[561]
|
93 |
+
>>> carmichael.find_carmichael_numbers_in_range(0,1000)
|
94 |
+
[561]
|
95 |
+
>>> carmichael.find_carmichael_numbers_in_range(0,2000)
|
96 |
+
[561, 1105, 1729]
|
97 |
+
|
98 |
+
References
|
99 |
+
==========
|
100 |
+
|
101 |
+
.. [1] https://en.wikipedia.org/wiki/Carmichael_number
|
102 |
+
.. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
|
103 |
+
.. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
|
104 |
+
"""
|
105 |
+
|
106 |
+
@staticmethod
|
107 |
+
def is_perfect_square(n):
|
108 |
+
sympy_deprecation_warning(
|
109 |
+
"""
|
110 |
+
is_perfect_square is just a wrapper around sympy.ntheory.primetest.is_square
|
111 |
+
so use that directly instead.
|
112 |
+
""",
|
113 |
+
deprecated_since_version="1.11",
|
114 |
+
active_deprecations_target='deprecated-carmichael-static-methods',
|
115 |
+
)
|
116 |
+
return is_square(n)
|
117 |
+
|
118 |
+
@staticmethod
|
119 |
+
def divides(p, n):
|
120 |
+
sympy_deprecation_warning(
|
121 |
+
"""
|
122 |
+
divides can be replaced by directly testing n % p == 0.
|
123 |
+
""",
|
124 |
+
deprecated_since_version="1.11",
|
125 |
+
active_deprecations_target='deprecated-carmichael-static-methods',
|
126 |
+
)
|
127 |
+
return n % p == 0
|
128 |
+
|
129 |
+
@staticmethod
|
130 |
+
def is_prime(n):
|
131 |
+
sympy_deprecation_warning(
|
132 |
+
"""
|
133 |
+
is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that
|
134 |
+
directly instead.
|
135 |
+
""",
|
136 |
+
deprecated_since_version="1.11",
|
137 |
+
active_deprecations_target='deprecated-carmichael-static-methods',
|
138 |
+
)
|
139 |
+
return isprime(n)
|
140 |
+
|
141 |
+
@staticmethod
|
142 |
+
def is_carmichael(n):
|
143 |
+
if n >= 0:
|
144 |
+
if (n == 1) or isprime(n) or (n % 2 == 0):
|
145 |
+
return False
|
146 |
+
|
147 |
+
divisors = [1, n]
|
148 |
+
|
149 |
+
# get divisors
|
150 |
+
divisors.extend([i for i in range(3, n // 2 + 1, 2) if n % i == 0])
|
151 |
+
|
152 |
+
for i in divisors:
|
153 |
+
if is_square(i) and i != 1:
|
154 |
+
return False
|
155 |
+
if isprime(i):
|
156 |
+
if not _divides(i - 1, n - 1):
|
157 |
+
return False
|
158 |
+
|
159 |
+
return True
|
160 |
+
|
161 |
+
else:
|
162 |
+
raise ValueError('The provided number must be greater than or equal to 0')
|
163 |
+
|
164 |
+
@staticmethod
|
165 |
+
def find_carmichael_numbers_in_range(x, y):
|
166 |
+
if 0 <= x <= y:
|
167 |
+
if x % 2 == 0:
|
168 |
+
return [i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)]
|
169 |
+
else:
|
170 |
+
return [i for i in range(x, y, 2) if carmichael.is_carmichael(i)]
|
171 |
+
|
172 |
+
else:
|
173 |
+
raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
|
174 |
+
|
175 |
+
@staticmethod
|
176 |
+
def find_first_n_carmichaels(n):
|
177 |
+
i = 1
|
178 |
+
carmichaels = []
|
179 |
+
|
180 |
+
while len(carmichaels) < n:
|
181 |
+
if carmichael.is_carmichael(i):
|
182 |
+
carmichaels.append(i)
|
183 |
+
i += 2
|
184 |
+
|
185 |
+
return carmichaels
|
186 |
+
|
187 |
+
|
188 |
+
#----------------------------------------------------------------------------#
|
189 |
+
# #
|
190 |
+
# Fibonacci numbers #
|
191 |
+
# #
|
192 |
+
#----------------------------------------------------------------------------#
|
193 |
+
|
194 |
+
|
195 |
+
class fibonacci(Function):
|
196 |
+
r"""
|
197 |
+
Fibonacci numbers / Fibonacci polynomials
|
198 |
+
|
199 |
+
The Fibonacci numbers are the integer sequence defined by the
|
200 |
+
initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence
|
201 |
+
relation `F_n = F_{n-1} + F_{n-2}`. This definition
|
202 |
+
extended to arbitrary real and complex arguments using
|
203 |
+
the formula
|
204 |
+
|
205 |
+
.. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}
|
206 |
+
|
207 |
+
The Fibonacci polynomials are defined by `F_1(x) = 1`,
|
208 |
+
`F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
|
209 |
+
For all positive integers `n`, `F_n(1) = F_n`.
|
210 |
+
|
211 |
+
* ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
|
212 |
+
* ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`
|
213 |
+
|
214 |
+
Examples
|
215 |
+
========
|
216 |
+
|
217 |
+
>>> from sympy import fibonacci, Symbol
|
218 |
+
|
219 |
+
>>> [fibonacci(x) for x in range(11)]
|
220 |
+
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
221 |
+
>>> fibonacci(5, Symbol('t'))
|
222 |
+
t**4 + 3*t**2 + 1
|
223 |
+
|
224 |
+
See Also
|
225 |
+
========
|
226 |
+
|
227 |
+
bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci
|
228 |
+
|
229 |
+
References
|
230 |
+
==========
|
231 |
+
|
232 |
+
.. [1] https://en.wikipedia.org/wiki/Fibonacci_number
|
233 |
+
.. [2] https://mathworld.wolfram.com/FibonacciNumber.html
|
234 |
+
|
235 |
+
"""
|
236 |
+
|
237 |
+
@staticmethod
|
238 |
+
def _fib(n):
|
239 |
+
return _ifib(n)
|
240 |
+
|
241 |
+
@staticmethod
|
242 |
+
@recurrence_memo([None, S.One, _sym])
|
243 |
+
def _fibpoly(n, prev):
|
244 |
+
return (prev[-2] + _sym*prev[-1]).expand()
|
245 |
+
|
246 |
+
@classmethod
|
247 |
+
def eval(cls, n, sym=None):
|
248 |
+
if n is S.Infinity:
|
249 |
+
return S.Infinity
|
250 |
+
|
251 |
+
if n.is_Integer:
|
252 |
+
if sym is None:
|
253 |
+
n = int(n)
|
254 |
+
if n < 0:
|
255 |
+
return S.NegativeOne**(n + 1) * fibonacci(-n)
|
256 |
+
else:
|
257 |
+
return Integer(cls._fib(n))
|
258 |
+
else:
|
259 |
+
if n < 1:
|
260 |
+
raise ValueError("Fibonacci polynomials are defined "
|
261 |
+
"only for positive integer indices.")
|
262 |
+
return cls._fibpoly(n).subs(_sym, sym)
|
263 |
+
|
264 |
+
def _eval_rewrite_as_sqrt(self, n, **kwargs):
|
265 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
266 |
+
return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
|
267 |
+
|
268 |
+
def _eval_rewrite_as_GoldenRatio(self,n, **kwargs):
|
269 |
+
return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1)
|
270 |
+
|
271 |
+
|
272 |
+
#----------------------------------------------------------------------------#
|
273 |
+
# #
|
274 |
+
# Lucas numbers #
|
275 |
+
# #
|
276 |
+
#----------------------------------------------------------------------------#
|
277 |
+
|
278 |
+
|
279 |
+
class lucas(Function):
|
280 |
+
"""
|
281 |
+
Lucas numbers
|
282 |
+
|
283 |
+
Lucas numbers satisfy a recurrence relation similar to that of
|
284 |
+
the Fibonacci sequence, in which each term is the sum of the
|
285 |
+
preceding two. They are generated by choosing the initial
|
286 |
+
values `L_0 = 2` and `L_1 = 1`.
|
287 |
+
|
288 |
+
* ``lucas(n)`` gives the `n^{th}` Lucas number
|
289 |
+
|
290 |
+
Examples
|
291 |
+
========
|
292 |
+
|
293 |
+
>>> from sympy import lucas
|
294 |
+
|
295 |
+
>>> [lucas(x) for x in range(11)]
|
296 |
+
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
|
297 |
+
|
298 |
+
See Also
|
299 |
+
========
|
300 |
+
|
301 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci
|
302 |
+
|
303 |
+
References
|
304 |
+
==========
|
305 |
+
|
306 |
+
.. [1] https://en.wikipedia.org/wiki/Lucas_number
|
307 |
+
.. [2] https://mathworld.wolfram.com/LucasNumber.html
|
308 |
+
|
309 |
+
"""
|
310 |
+
|
311 |
+
@classmethod
|
312 |
+
def eval(cls, n):
|
313 |
+
if n is S.Infinity:
|
314 |
+
return S.Infinity
|
315 |
+
|
316 |
+
if n.is_Integer:
|
317 |
+
return fibonacci(n + 1) + fibonacci(n - 1)
|
318 |
+
|
319 |
+
def _eval_rewrite_as_sqrt(self, n, **kwargs):
|
320 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
321 |
+
return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n)
|
322 |
+
|
323 |
+
|
324 |
+
#----------------------------------------------------------------------------#
|
325 |
+
# #
|
326 |
+
# Tribonacci numbers #
|
327 |
+
# #
|
328 |
+
#----------------------------------------------------------------------------#
|
329 |
+
|
330 |
+
|
331 |
+
class tribonacci(Function):
|
332 |
+
r"""
|
333 |
+
Tribonacci numbers / Tribonacci polynomials
|
334 |
+
|
335 |
+
The Tribonacci numbers are the integer sequence defined by the
|
336 |
+
initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
|
337 |
+
recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.
|
338 |
+
|
339 |
+
The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
|
340 |
+
`T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
|
341 |
+
for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`.
|
342 |
+
|
343 |
+
* ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
|
344 |
+
* ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`
|
345 |
+
|
346 |
+
Examples
|
347 |
+
========
|
348 |
+
|
349 |
+
>>> from sympy import tribonacci, Symbol
|
350 |
+
|
351 |
+
>>> [tribonacci(x) for x in range(11)]
|
352 |
+
[0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
|
353 |
+
>>> tribonacci(5, Symbol('t'))
|
354 |
+
t**8 + 3*t**5 + 3*t**2
|
355 |
+
|
356 |
+
See Also
|
357 |
+
========
|
358 |
+
|
359 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition
|
360 |
+
|
361 |
+
References
|
362 |
+
==========
|
363 |
+
|
364 |
+
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
|
365 |
+
.. [2] https://mathworld.wolfram.com/TribonacciNumber.html
|
366 |
+
.. [3] https://oeis.org/A000073
|
367 |
+
|
368 |
+
"""
|
369 |
+
|
370 |
+
@staticmethod
|
371 |
+
@recurrence_memo([S.Zero, S.One, S.One])
|
372 |
+
def _trib(n, prev):
|
373 |
+
return (prev[-3] + prev[-2] + prev[-1])
|
374 |
+
|
375 |
+
@staticmethod
|
376 |
+
@recurrence_memo([S.Zero, S.One, _sym**2])
|
377 |
+
def _tribpoly(n, prev):
|
378 |
+
return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand()
|
379 |
+
|
380 |
+
@classmethod
|
381 |
+
def eval(cls, n, sym=None):
|
382 |
+
if n is S.Infinity:
|
383 |
+
return S.Infinity
|
384 |
+
|
385 |
+
if n.is_Integer:
|
386 |
+
n = int(n)
|
387 |
+
if n < 0:
|
388 |
+
raise ValueError("Tribonacci polynomials are defined "
|
389 |
+
"only for non-negative integer indices.")
|
390 |
+
if sym is None:
|
391 |
+
return Integer(cls._trib(n))
|
392 |
+
else:
|
393 |
+
return cls._tribpoly(n).subs(_sym, sym)
|
394 |
+
|
395 |
+
def _eval_rewrite_as_sqrt(self, n, **kwargs):
|
396 |
+
from sympy.functions.elementary.miscellaneous import cbrt, sqrt
|
397 |
+
w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
|
398 |
+
a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
|
399 |
+
b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
|
400 |
+
c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
|
401 |
+
Tn = (a**(n + 1)/((a - b)*(a - c))
|
402 |
+
+ b**(n + 1)/((b - a)*(b - c))
|
403 |
+
+ c**(n + 1)/((c - a)*(c - b)))
|
404 |
+
return Tn
|
405 |
+
|
406 |
+
def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs):
|
407 |
+
from sympy.functions.elementary.integers import floor
|
408 |
+
from sympy.functions.elementary.miscellaneous import cbrt, sqrt
|
409 |
+
b = cbrt(586 + 102*sqrt(33))
|
410 |
+
Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4)
|
411 |
+
return floor(Tn + S.Half)
|
412 |
+
|
413 |
+
|
414 |
+
#----------------------------------------------------------------------------#
|
415 |
+
# #
|
416 |
+
# Bernoulli numbers #
|
417 |
+
# #
|
418 |
+
#----------------------------------------------------------------------------#
|
419 |
+
|
420 |
+
|
421 |
+
class bernoulli(Function):
|
422 |
+
r"""
|
423 |
+
Bernoulli numbers / Bernoulli polynomials / Bernoulli function
|
424 |
+
|
425 |
+
The Bernoulli numbers are a sequence of rational numbers
|
426 |
+
defined by `B_0 = 1` and the recursive relation (`n > 0`):
|
427 |
+
|
428 |
+
.. math :: n+1 = \sum_{k=0}^n \binom{n+1}{k} B_k
|
429 |
+
|
430 |
+
They are also commonly defined by their exponential generating
|
431 |
+
function, which is `\frac{x}{1 - e^{-x}}`. For odd indices > 1,
|
432 |
+
the Bernoulli numbers are zero.
|
433 |
+
|
434 |
+
The Bernoulli polynomials satisfy the analogous formula:
|
435 |
+
|
436 |
+
.. math :: B_n(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} B_k x^{n-k}
|
437 |
+
|
438 |
+
Bernoulli numbers and Bernoulli polynomials are related as
|
439 |
+
`B_n(1) = B_n`.
|
440 |
+
|
441 |
+
The generalized Bernoulli function `\operatorname{B}(s, a)`
|
442 |
+
is defined for any complex `s` and `a`, except where `a` is a
|
443 |
+
nonpositive integer and `s` is not a nonnegative integer. It is
|
444 |
+
an entire function of `s` for fixed `a`, related to the Hurwitz
|
445 |
+
zeta function by
|
446 |
+
|
447 |
+
.. math:: \operatorname{B}(s, a) = \begin{cases}
|
448 |
+
-s \zeta(1-s, a) & s \ne 0 \\ 1 & s = 0 \end{cases}
|
449 |
+
|
450 |
+
When `s` is a nonnegative integer this function reduces to the
|
451 |
+
Bernoulli polynomials: `\operatorname{B}(n, x) = B_n(x)`. When
|
452 |
+
`a` is omitted it is assumed to be 1, yielding the (ordinary)
|
453 |
+
Bernoulli function which interpolates the Bernoulli numbers and is
|
454 |
+
related to the Riemann zeta function.
|
455 |
+
|
456 |
+
We compute Bernoulli numbers using Ramanujan's formula:
|
457 |
+
|
458 |
+
.. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}
|
459 |
+
|
460 |
+
where:
|
461 |
+
|
462 |
+
.. math :: A(n) = \begin{cases} \frac{n+3}{3} &
|
463 |
+
n \equiv 0\ \text{or}\ 2 \pmod{6} \\
|
464 |
+
-\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}
|
465 |
+
|
466 |
+
and:
|
467 |
+
|
468 |
+
.. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}
|
469 |
+
|
470 |
+
This formula is similar to the sum given in the definition, but
|
471 |
+
cuts `\frac{2}{3}` of the terms. For Bernoulli polynomials, we use
|
472 |
+
Appell sequences.
|
473 |
+
|
474 |
+
For `n` a nonnegative integer and `s`, `a`, `x` arbitrary complex numbers,
|
475 |
+
|
476 |
+
* ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
|
477 |
+
* ``bernoulli(s)`` gives the Bernoulli function `\operatorname{B}(s)`
|
478 |
+
* ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
|
479 |
+
* ``bernoulli(s, a)`` gives the generalized Bernoulli function
|
480 |
+
`\operatorname{B}(s, a)`
|
481 |
+
|
482 |
+
.. versionchanged:: 1.12
|
483 |
+
``bernoulli(1)`` gives `+\frac{1}{2}` instead of `-\frac{1}{2}`.
|
484 |
+
This choice of value confers several theoretical advantages [5]_,
|
485 |
+
including the extension to complex parameters described above
|
486 |
+
which this function now implements. The previous behavior, defined
|
487 |
+
only for nonnegative integers `n`, can be obtained with
|
488 |
+
``(-1)**n*bernoulli(n)``.
|
489 |
+
|
490 |
+
Examples
|
491 |
+
========
|
492 |
+
|
493 |
+
>>> from sympy import bernoulli
|
494 |
+
>>> from sympy.abc import x
|
495 |
+
>>> [bernoulli(n) for n in range(11)]
|
496 |
+
[1, 1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
|
497 |
+
>>> bernoulli(1000001)
|
498 |
+
0
|
499 |
+
>>> bernoulli(3, x)
|
500 |
+
x**3 - 3*x**2/2 + x/2
|
501 |
+
|
502 |
+
See Also
|
503 |
+
========
|
504 |
+
|
505 |
+
andre, bell, catalan, euler, fibonacci, harmonic, lucas, genocchi,
|
506 |
+
partition, tribonacci, sympy.polys.appellseqs.bernoulli_poly
|
507 |
+
|
508 |
+
References
|
509 |
+
==========
|
510 |
+
|
511 |
+
.. [1] https://en.wikipedia.org/wiki/Bernoulli_number
|
512 |
+
.. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
|
513 |
+
.. [3] https://mathworld.wolfram.com/BernoulliNumber.html
|
514 |
+
.. [4] https://mathworld.wolfram.com/BernoulliPolynomial.html
|
515 |
+
.. [5] Peter Luschny, "The Bernoulli Manifesto",
|
516 |
+
https://luschny.de/math/zeta/The-Bernoulli-Manifesto.html
|
517 |
+
.. [6] Peter Luschny, "An introduction to the Bernoulli function",
|
518 |
+
https://arxiv.org/abs/2009.06743
|
519 |
+
|
520 |
+
"""
|
521 |
+
|
522 |
+
args: tTuple[Integer]
|
523 |
+
|
524 |
+
# Calculates B_n for positive even n
|
525 |
+
@staticmethod
|
526 |
+
def _calc_bernoulli(n):
|
527 |
+
s = 0
|
528 |
+
a = int(binomial(n + 3, n - 6))
|
529 |
+
for j in range(1, n//6 + 1):
|
530 |
+
s += a * bernoulli(n - 6*j)
|
531 |
+
# Avoid computing each binomial coefficient from scratch
|
532 |
+
a *= _product(n - 6 - 6*j + 1, n - 6*j)
|
533 |
+
a //= _product(6*j + 4, 6*j + 9)
|
534 |
+
if n % 6 == 4:
|
535 |
+
s = -Rational(n + 3, 6) - s
|
536 |
+
else:
|
537 |
+
s = Rational(n + 3, 3) - s
|
538 |
+
return s / binomial(n + 3, n)
|
539 |
+
|
540 |
+
# We implement a specialized memoization scheme to handle each
|
541 |
+
# case modulo 6 separately
|
542 |
+
_cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)}
|
543 |
+
_highest = {0: 0, 2: 2, 4: 4}
|
544 |
+
|
545 |
+
@classmethod
|
546 |
+
def eval(cls, n, x=None):
|
547 |
+
if x is S.One:
|
548 |
+
return cls(n)
|
549 |
+
elif n.is_zero:
|
550 |
+
return S.One
|
551 |
+
elif n.is_integer is False or n.is_nonnegative is False:
|
552 |
+
if x is not None and x.is_Integer and x.is_nonpositive:
|
553 |
+
return S.NaN
|
554 |
+
return
|
555 |
+
# Bernoulli numbers
|
556 |
+
elif x is None:
|
557 |
+
if n is S.One:
|
558 |
+
return S.Half
|
559 |
+
elif n.is_odd and (n-1).is_positive:
|
560 |
+
return S.Zero
|
561 |
+
elif n.is_Number:
|
562 |
+
n = int(n)
|
563 |
+
# Use mpmath for enormous Bernoulli numbers
|
564 |
+
if n > 500:
|
565 |
+
p, q = mp.bernfrac(n)
|
566 |
+
return Rational(int(p), int(q))
|
567 |
+
case = n % 6
|
568 |
+
highest_cached = cls._highest[case]
|
569 |
+
if n <= highest_cached:
|
570 |
+
return cls._cache[n]
|
571 |
+
# To avoid excessive recursion when, say, bernoulli(1000) is
|
572 |
+
# requested, calculate and cache the entire sequence ... B_988,
|
573 |
+
# B_994, B_1000 in increasing order
|
574 |
+
for i in range(highest_cached + 6, n + 6, 6):
|
575 |
+
b = cls._calc_bernoulli(i)
|
576 |
+
cls._cache[i] = b
|
577 |
+
cls._highest[case] = i
|
578 |
+
return b
|
579 |
+
# Bernoulli polynomials
|
580 |
+
elif n.is_Number:
|
581 |
+
return bernoulli_poly(n, x)
|
582 |
+
|
583 |
+
def _eval_rewrite_as_zeta(self, n, x=1, **kwargs):
|
584 |
+
from sympy.functions.special.zeta_functions import zeta
|
585 |
+
return Piecewise((1, Eq(n, 0)), (-n * zeta(1-n, x), True))
|
586 |
+
|
587 |
+
def _eval_evalf(self, prec):
|
588 |
+
if not all(x.is_number for x in self.args):
|
589 |
+
return
|
590 |
+
n = self.args[0]._to_mpmath(prec)
|
591 |
+
x = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
|
592 |
+
with workprec(prec):
|
593 |
+
if n == 0:
|
594 |
+
res = mp.mpf(1)
|
595 |
+
elif n == 1:
|
596 |
+
res = x - mp.mpf(0.5)
|
597 |
+
elif mp.isint(n) and n >= 0:
|
598 |
+
res = mp.bernoulli(n) if x == 1 else mp.bernpoly(n, x)
|
599 |
+
else:
|
600 |
+
res = -n * mp.zeta(1-n, x)
|
601 |
+
return Expr._from_mpmath(res, prec)
|
602 |
+
|
603 |
+
|
604 |
+
#----------------------------------------------------------------------------#
|
605 |
+
# #
|
606 |
+
# Bell numbers #
|
607 |
+
# #
|
608 |
+
#----------------------------------------------------------------------------#
|
609 |
+
|
610 |
+
|
611 |
+
class bell(Function):
|
612 |
+
r"""
|
613 |
+
Bell numbers / Bell polynomials
|
614 |
+
|
615 |
+
The Bell numbers satisfy `B_0 = 1` and
|
616 |
+
|
617 |
+
.. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.
|
618 |
+
|
619 |
+
They are also given by:
|
620 |
+
|
621 |
+
.. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
|
622 |
+
|
623 |
+
The Bell polynomials are given by `B_0(x) = 1` and
|
624 |
+
|
625 |
+
.. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).
|
626 |
+
|
627 |
+
The second kind of Bell polynomials (are sometimes called "partial" Bell
|
628 |
+
polynomials or incomplete Bell polynomials) are defined as
|
629 |
+
|
630 |
+
.. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
|
631 |
+
\sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
|
632 |
+
\frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
|
633 |
+
\left(\frac{x_1}{1!} \right)^{j_1}
|
634 |
+
\left(\frac{x_2}{2!} \right)^{j_2} \dotsb
|
635 |
+
\left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
|
636 |
+
|
637 |
+
* ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
|
638 |
+
* ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
|
639 |
+
* ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
|
640 |
+
`B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
|
641 |
+
|
642 |
+
Notes
|
643 |
+
=====
|
644 |
+
|
645 |
+
Not to be confused with Bernoulli numbers and Bernoulli polynomials,
|
646 |
+
which use the same notation.
|
647 |
+
|
648 |
+
Examples
|
649 |
+
========
|
650 |
+
|
651 |
+
>>> from sympy import bell, Symbol, symbols
|
652 |
+
|
653 |
+
>>> [bell(n) for n in range(11)]
|
654 |
+
[1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
|
655 |
+
>>> bell(30)
|
656 |
+
846749014511809332450147
|
657 |
+
>>> bell(4, Symbol('t'))
|
658 |
+
t**4 + 6*t**3 + 7*t**2 + t
|
659 |
+
>>> bell(6, 2, symbols('x:6')[1:])
|
660 |
+
6*x1*x5 + 15*x2*x4 + 10*x3**2
|
661 |
+
|
662 |
+
See Also
|
663 |
+
========
|
664 |
+
|
665 |
+
bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
|
666 |
+
|
667 |
+
References
|
668 |
+
==========
|
669 |
+
|
670 |
+
.. [1] https://en.wikipedia.org/wiki/Bell_number
|
671 |
+
.. [2] https://mathworld.wolfram.com/BellNumber.html
|
672 |
+
.. [3] https://mathworld.wolfram.com/BellPolynomial.html
|
673 |
+
|
674 |
+
"""
|
675 |
+
|
676 |
+
@staticmethod
|
677 |
+
@recurrence_memo([1, 1])
|
678 |
+
def _bell(n, prev):
|
679 |
+
s = 1
|
680 |
+
a = 1
|
681 |
+
for k in range(1, n):
|
682 |
+
a = a * (n - k) // k
|
683 |
+
s += a * prev[k]
|
684 |
+
return s
|
685 |
+
|
686 |
+
@staticmethod
|
687 |
+
@recurrence_memo([S.One, _sym])
|
688 |
+
def _bell_poly(n, prev):
|
689 |
+
s = 1
|
690 |
+
a = 1
|
691 |
+
for k in range(2, n + 1):
|
692 |
+
a = a * (n - k + 1) // (k - 1)
|
693 |
+
s += a * prev[k - 1]
|
694 |
+
return expand_mul(_sym * s)
|
695 |
+
|
696 |
+
@staticmethod
|
697 |
+
def _bell_incomplete_poly(n, k, symbols):
|
698 |
+
r"""
|
699 |
+
The second kind of Bell polynomials (incomplete Bell polynomials).
|
700 |
+
|
701 |
+
Calculated by recurrence formula:
|
702 |
+
|
703 |
+
.. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
|
704 |
+
\sum_{m=1}^{n-k+1}
|
705 |
+
\x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})
|
706 |
+
|
707 |
+
where
|
708 |
+
`B_{0,0} = 1;`
|
709 |
+
`B_{n,0} = 0; for n \ge 1`
|
710 |
+
`B_{0,k} = 0; for k \ge 1`
|
711 |
+
|
712 |
+
"""
|
713 |
+
if (n == 0) and (k == 0):
|
714 |
+
return S.One
|
715 |
+
elif (n == 0) or (k == 0):
|
716 |
+
return S.Zero
|
717 |
+
s = S.Zero
|
718 |
+
a = S.One
|
719 |
+
for m in range(1, n - k + 2):
|
720 |
+
s += a * bell._bell_incomplete_poly(
|
721 |
+
n - m, k - 1, symbols) * symbols[m - 1]
|
722 |
+
a = a * (n - m) / m
|
723 |
+
return expand_mul(s)
|
724 |
+
|
725 |
+
@classmethod
|
726 |
+
def eval(cls, n, k_sym=None, symbols=None):
|
727 |
+
if n is S.Infinity:
|
728 |
+
if k_sym is None:
|
729 |
+
return S.Infinity
|
730 |
+
else:
|
731 |
+
raise ValueError("Bell polynomial is not defined")
|
732 |
+
|
733 |
+
if n.is_negative or n.is_integer is False:
|
734 |
+
raise ValueError("a non-negative integer expected")
|
735 |
+
|
736 |
+
if n.is_Integer and n.is_nonnegative:
|
737 |
+
if k_sym is None:
|
738 |
+
return Integer(cls._bell(int(n)))
|
739 |
+
elif symbols is None:
|
740 |
+
return cls._bell_poly(int(n)).subs(_sym, k_sym)
|
741 |
+
else:
|
742 |
+
r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
|
743 |
+
return r
|
744 |
+
|
745 |
+
def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs):
|
746 |
+
from sympy.concrete.summations import Sum
|
747 |
+
if (k_sym is not None) or (symbols is not None):
|
748 |
+
return self
|
749 |
+
|
750 |
+
# Dobinski's formula
|
751 |
+
if not n.is_nonnegative:
|
752 |
+
return self
|
753 |
+
k = Dummy('k', integer=True, nonnegative=True)
|
754 |
+
return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity))
|
755 |
+
|
756 |
+
|
757 |
+
#----------------------------------------------------------------------------#
|
758 |
+
# #
|
759 |
+
# Harmonic numbers #
|
760 |
+
# #
|
761 |
+
#----------------------------------------------------------------------------#
|
762 |
+
|
763 |
+
|
764 |
+
class harmonic(Function):
|
765 |
+
r"""
|
766 |
+
Harmonic numbers
|
767 |
+
|
768 |
+
The nth harmonic number is given by `\operatorname{H}_{n} =
|
769 |
+
1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
|
770 |
+
|
771 |
+
More generally:
|
772 |
+
|
773 |
+
.. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
|
774 |
+
|
775 |
+
As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
|
776 |
+
the Riemann zeta function.
|
777 |
+
|
778 |
+
* ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`
|
779 |
+
|
780 |
+
* ``harmonic(n, m)`` gives the nth generalized harmonic number
|
781 |
+
of order `m`, `\operatorname{H}_{n,m}`, where
|
782 |
+
``harmonic(n) == harmonic(n, 1)``
|
783 |
+
|
784 |
+
This function can be extended to complex `n` and `m` where `n` is not a
|
785 |
+
negative integer or `m` is a nonpositive integer as
|
786 |
+
|
787 |
+
.. math:: \operatorname{H}_{n,m} = \begin{cases} \zeta(m) - \zeta(m, n+1)
|
788 |
+
& m \ne 1 \\ \psi(n+1) + \gamma & m = 1 \end{cases}
|
789 |
+
|
790 |
+
Examples
|
791 |
+
========
|
792 |
+
|
793 |
+
>>> from sympy import harmonic, oo
|
794 |
+
|
795 |
+
>>> [harmonic(n) for n in range(6)]
|
796 |
+
[0, 1, 3/2, 11/6, 25/12, 137/60]
|
797 |
+
>>> [harmonic(n, 2) for n in range(6)]
|
798 |
+
[0, 1, 5/4, 49/36, 205/144, 5269/3600]
|
799 |
+
>>> harmonic(oo, 2)
|
800 |
+
pi**2/6
|
801 |
+
|
802 |
+
>>> from sympy import Symbol, Sum
|
803 |
+
>>> n = Symbol("n")
|
804 |
+
|
805 |
+
>>> harmonic(n).rewrite(Sum)
|
806 |
+
Sum(1/_k, (_k, 1, n))
|
807 |
+
|
808 |
+
We can evaluate harmonic numbers for all integral and positive
|
809 |
+
rational arguments:
|
810 |
+
|
811 |
+
>>> from sympy import S, expand_func, simplify
|
812 |
+
>>> harmonic(8)
|
813 |
+
761/280
|
814 |
+
>>> harmonic(11)
|
815 |
+
83711/27720
|
816 |
+
|
817 |
+
>>> H = harmonic(1/S(3))
|
818 |
+
>>> H
|
819 |
+
harmonic(1/3)
|
820 |
+
>>> He = expand_func(H)
|
821 |
+
>>> He
|
822 |
+
-log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
|
823 |
+
+ 3*Sum(1/(3*_k + 1), (_k, 0, 0))
|
824 |
+
>>> He.doit()
|
825 |
+
-log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
|
826 |
+
>>> H = harmonic(25/S(7))
|
827 |
+
>>> He = simplify(expand_func(H).doit())
|
828 |
+
>>> He
|
829 |
+
log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900
|
830 |
+
>>> He.n(40)
|
831 |
+
1.983697455232980674869851942390639915940
|
832 |
+
>>> harmonic(25/S(7)).n(40)
|
833 |
+
1.983697455232980674869851942390639915940
|
834 |
+
|
835 |
+
We can rewrite harmonic numbers in terms of polygamma functions:
|
836 |
+
|
837 |
+
>>> from sympy import digamma, polygamma
|
838 |
+
>>> m = Symbol("m", integer=True, positive=True)
|
839 |
+
|
840 |
+
>>> harmonic(n).rewrite(digamma)
|
841 |
+
polygamma(0, n + 1) + EulerGamma
|
842 |
+
|
843 |
+
>>> harmonic(n).rewrite(polygamma)
|
844 |
+
polygamma(0, n + 1) + EulerGamma
|
845 |
+
|
846 |
+
>>> harmonic(n,3).rewrite(polygamma)
|
847 |
+
polygamma(2, n + 1)/2 + zeta(3)
|
848 |
+
|
849 |
+
>>> simplify(harmonic(n,m).rewrite(polygamma))
|
850 |
+
Piecewise((polygamma(0, n + 1) + EulerGamma, Eq(m, 1)),
|
851 |
+
(-(-1)**m*polygamma(m - 1, n + 1)/factorial(m - 1) + zeta(m), True))
|
852 |
+
|
853 |
+
Integer offsets in the argument can be pulled out:
|
854 |
+
|
855 |
+
>>> from sympy import expand_func
|
856 |
+
|
857 |
+
>>> expand_func(harmonic(n+4))
|
858 |
+
harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
|
859 |
+
|
860 |
+
>>> expand_func(harmonic(n-4))
|
861 |
+
harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
|
862 |
+
|
863 |
+
Some limits can be computed as well:
|
864 |
+
|
865 |
+
>>> from sympy import limit, oo
|
866 |
+
|
867 |
+
>>> limit(harmonic(n), n, oo)
|
868 |
+
oo
|
869 |
+
|
870 |
+
>>> limit(harmonic(n, 2), n, oo)
|
871 |
+
pi**2/6
|
872 |
+
|
873 |
+
>>> limit(harmonic(n, 3), n, oo)
|
874 |
+
zeta(3)
|
875 |
+
|
876 |
+
For `m > 1`, `H_{n,m}` tends to `\zeta(m)` in the limit of infinite `n`:
|
877 |
+
|
878 |
+
>>> m = Symbol("m", positive=True)
|
879 |
+
>>> limit(harmonic(n, m+1), n, oo)
|
880 |
+
zeta(m + 1)
|
881 |
+
|
882 |
+
See Also
|
883 |
+
========
|
884 |
+
|
885 |
+
bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci
|
886 |
+
|
887 |
+
References
|
888 |
+
==========
|
889 |
+
|
890 |
+
.. [1] https://en.wikipedia.org/wiki/Harmonic_number
|
891 |
+
.. [2] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
|
892 |
+
.. [3] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/
|
893 |
+
|
894 |
+
"""
|
895 |
+
|
896 |
+
@classmethod
|
897 |
+
def eval(cls, n, m=None):
|
898 |
+
from sympy.functions.special.zeta_functions import zeta
|
899 |
+
if m is S.One:
|
900 |
+
return cls(n)
|
901 |
+
if m is None:
|
902 |
+
m = S.One
|
903 |
+
if n.is_zero:
|
904 |
+
return S.Zero
|
905 |
+
elif m.is_zero:
|
906 |
+
return n
|
907 |
+
elif n is S.Infinity:
|
908 |
+
if m.is_negative:
|
909 |
+
return S.NaN
|
910 |
+
elif is_le(m, S.One):
|
911 |
+
return S.Infinity
|
912 |
+
elif is_gt(m, S.One):
|
913 |
+
return zeta(m)
|
914 |
+
elif m.is_Integer and m.is_nonpositive:
|
915 |
+
return (bernoulli(1-m, n+1) - bernoulli(1-m)) / (1-m)
|
916 |
+
elif n.is_Integer:
|
917 |
+
if n.is_negative and (m.is_integer is False or m.is_nonpositive is False):
|
918 |
+
return S.ComplexInfinity if m is S.One else S.NaN
|
919 |
+
if n.is_nonnegative:
|
920 |
+
return Add(*(k**(-m) for k in range(1, int(n)+1)))
|
921 |
+
|
922 |
+
def _eval_rewrite_as_polygamma(self, n, m=S.One, **kwargs):
|
923 |
+
from sympy.functions.special.gamma_functions import gamma, polygamma
|
924 |
+
if m.is_integer and m.is_positive:
|
925 |
+
return Piecewise((polygamma(0, n+1) + S.EulerGamma, Eq(m, 1)),
|
926 |
+
(S.NegativeOne**m * (polygamma(m-1, 1) - polygamma(m-1, n+1)) /
|
927 |
+
gamma(m), True))
|
928 |
+
|
929 |
+
def _eval_rewrite_as_digamma(self, n, m=1, **kwargs):
|
930 |
+
from sympy.functions.special.gamma_functions import polygamma
|
931 |
+
return self.rewrite(polygamma)
|
932 |
+
|
933 |
+
def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs):
|
934 |
+
from sympy.functions.special.gamma_functions import polygamma
|
935 |
+
return self.rewrite(polygamma)
|
936 |
+
|
937 |
+
def _eval_rewrite_as_Sum(self, n, m=None, **kwargs):
|
938 |
+
from sympy.concrete.summations import Sum
|
939 |
+
k = Dummy("k", integer=True)
|
940 |
+
if m is None:
|
941 |
+
m = S.One
|
942 |
+
return Sum(k**(-m), (k, 1, n))
|
943 |
+
|
944 |
+
def _eval_rewrite_as_zeta(self, n, m=S.One, **kwargs):
|
945 |
+
from sympy.functions.special.zeta_functions import zeta
|
946 |
+
from sympy.functions.special.gamma_functions import digamma
|
947 |
+
return Piecewise((digamma(n + 1) + S.EulerGamma, Eq(m, 1)),
|
948 |
+
(zeta(m) - zeta(m, n+1), True))
|
949 |
+
|
950 |
+
def _eval_expand_func(self, **hints):
|
951 |
+
from sympy.concrete.summations import Sum
|
952 |
+
n = self.args[0]
|
953 |
+
m = self.args[1] if len(self.args) == 2 else 1
|
954 |
+
|
955 |
+
if m == S.One:
|
956 |
+
if n.is_Add:
|
957 |
+
off = n.args[0]
|
958 |
+
nnew = n - off
|
959 |
+
if off.is_Integer and off.is_positive:
|
960 |
+
result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)]
|
961 |
+
return Add(*result)
|
962 |
+
elif off.is_Integer and off.is_negative:
|
963 |
+
result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)]
|
964 |
+
return Add(*result)
|
965 |
+
|
966 |
+
if n.is_Rational:
|
967 |
+
# Expansions for harmonic numbers at general rational arguments (u + p/q)
|
968 |
+
# Split n as u + p/q with p < q
|
969 |
+
p, q = n.as_numer_denom()
|
970 |
+
u = p // q
|
971 |
+
p = p - u * q
|
972 |
+
if u.is_nonnegative and p.is_positive and q.is_positive and p < q:
|
973 |
+
from sympy.functions.elementary.exponential import log
|
974 |
+
from sympy.functions.elementary.integers import floor
|
975 |
+
from sympy.functions.elementary.trigonometric import sin, cos, cot
|
976 |
+
k = Dummy("k")
|
977 |
+
t1 = q * Sum(1 / (q * k + p), (k, 0, u))
|
978 |
+
t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) *
|
979 |
+
log(sin((pi * k) / S(q))),
|
980 |
+
(k, 1, floor((q - 1) / S(2))))
|
981 |
+
t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q)
|
982 |
+
return t1 + t2 - t3
|
983 |
+
|
984 |
+
return self
|
985 |
+
|
986 |
+
def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs):
|
987 |
+
from sympy.functions.special.zeta_functions import zeta
|
988 |
+
from sympy.functions.special.gamma_functions import polygamma
|
989 |
+
pg = self.rewrite(polygamma)
|
990 |
+
if not isinstance(pg, harmonic):
|
991 |
+
return pg.rewrite("tractable", deep=True)
|
992 |
+
arg = m - S.One
|
993 |
+
if arg.is_nonzero:
|
994 |
+
return (zeta(m) - zeta(m, n+1)).rewrite("tractable", deep=True)
|
995 |
+
|
996 |
+
def _eval_evalf(self, prec):
|
997 |
+
if not all(x.is_number for x in self.args):
|
998 |
+
return
|
999 |
+
n = self.args[0]._to_mpmath(prec)
|
1000 |
+
m = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
|
1001 |
+
if mp.isint(n) and n < 0:
|
1002 |
+
return S.NaN
|
1003 |
+
with workprec(prec):
|
1004 |
+
if m == 1:
|
1005 |
+
res = mp.harmonic(n)
|
1006 |
+
else:
|
1007 |
+
res = mp.zeta(m) - mp.zeta(m, n+1)
|
1008 |
+
return Expr._from_mpmath(res, prec)
|
1009 |
+
|
1010 |
+
def fdiff(self, argindex=1):
|
1011 |
+
from sympy.functions.special.zeta_functions import zeta
|
1012 |
+
if len(self.args) == 2:
|
1013 |
+
n, m = self.args
|
1014 |
+
else:
|
1015 |
+
n, m = self.args + (1,)
|
1016 |
+
if argindex == 1:
|
1017 |
+
return m * zeta(m+1, n+1)
|
1018 |
+
else:
|
1019 |
+
raise ArgumentIndexError
|
1020 |
+
|
1021 |
+
|
1022 |
+
#----------------------------------------------------------------------------#
|
1023 |
+
# #
|
1024 |
+
# Euler numbers #
|
1025 |
+
# #
|
1026 |
+
#----------------------------------------------------------------------------#
|
1027 |
+
|
1028 |
+
|
1029 |
+
class euler(Function):
|
1030 |
+
r"""
|
1031 |
+
Euler numbers / Euler polynomials / Euler function
|
1032 |
+
|
1033 |
+
The Euler numbers are given by:
|
1034 |
+
|
1035 |
+
.. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
|
1036 |
+
\frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}
|
1037 |
+
|
1038 |
+
.. math:: E_{2n+1} = 0
|
1039 |
+
|
1040 |
+
Euler numbers and Euler polynomials are related by
|
1041 |
+
|
1042 |
+
.. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).
|
1043 |
+
|
1044 |
+
We compute symbolic Euler polynomials using Appell sequences,
|
1045 |
+
but numerical evaluation of the Euler polynomial is computed
|
1046 |
+
more efficiently (and more accurately) using the mpmath library.
|
1047 |
+
|
1048 |
+
The Euler polynomials are special cases of the generalized Euler function,
|
1049 |
+
related to the Genocchi function as
|
1050 |
+
|
1051 |
+
.. math:: \operatorname{E}(s, a) = -\frac{\operatorname{G}(s+1, a)}{s+1}
|
1052 |
+
|
1053 |
+
with the limit of `\psi\left(\frac{a+1}{2}\right) - \psi\left(\frac{a}{2}\right)`
|
1054 |
+
being taken when `s = -1`. The (ordinary) Euler function interpolating
|
1055 |
+
the Euler numbers is then obtained as
|
1056 |
+
`\operatorname{E}(s) = 2^s \operatorname{E}\left(s, \frac{1}{2}\right)`.
|
1057 |
+
|
1058 |
+
* ``euler(n)`` gives the nth Euler number `E_n`.
|
1059 |
+
* ``euler(s)`` gives the Euler function `\operatorname{E}(s)`.
|
1060 |
+
* ``euler(n, x)`` gives the nth Euler polynomial `E_n(x)`.
|
1061 |
+
* ``euler(s, a)`` gives the generalized Euler function `\operatorname{E}(s, a)`.
|
1062 |
+
|
1063 |
+
Examples
|
1064 |
+
========
|
1065 |
+
|
1066 |
+
>>> from sympy import euler, Symbol, S
|
1067 |
+
>>> [euler(n) for n in range(10)]
|
1068 |
+
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
|
1069 |
+
>>> [2**n*euler(n,1) for n in range(10)]
|
1070 |
+
[1, 1, 0, -2, 0, 16, 0, -272, 0, 7936]
|
1071 |
+
>>> n = Symbol("n")
|
1072 |
+
>>> euler(n + 2*n)
|
1073 |
+
euler(3*n)
|
1074 |
+
|
1075 |
+
>>> x = Symbol("x")
|
1076 |
+
>>> euler(n, x)
|
1077 |
+
euler(n, x)
|
1078 |
+
|
1079 |
+
>>> euler(0, x)
|
1080 |
+
1
|
1081 |
+
>>> euler(1, x)
|
1082 |
+
x - 1/2
|
1083 |
+
>>> euler(2, x)
|
1084 |
+
x**2 - x
|
1085 |
+
>>> euler(3, x)
|
1086 |
+
x**3 - 3*x**2/2 + 1/4
|
1087 |
+
>>> euler(4, x)
|
1088 |
+
x**4 - 2*x**3 + x
|
1089 |
+
|
1090 |
+
>>> euler(12, S.Half)
|
1091 |
+
2702765/4096
|
1092 |
+
>>> euler(12)
|
1093 |
+
2702765
|
1094 |
+
|
1095 |
+
See Also
|
1096 |
+
========
|
1097 |
+
|
1098 |
+
andre, bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi,
|
1099 |
+
partition, tribonacci, sympy.polys.appellseqs.euler_poly
|
1100 |
+
|
1101 |
+
References
|
1102 |
+
==========
|
1103 |
+
|
1104 |
+
.. [1] https://en.wikipedia.org/wiki/Euler_numbers
|
1105 |
+
.. [2] https://mathworld.wolfram.com/EulerNumber.html
|
1106 |
+
.. [3] https://en.wikipedia.org/wiki/Alternating_permutation
|
1107 |
+
.. [4] https://mathworld.wolfram.com/AlternatingPermutation.html
|
1108 |
+
|
1109 |
+
"""
|
1110 |
+
|
1111 |
+
@classmethod
|
1112 |
+
def eval(cls, n, x=None):
|
1113 |
+
if n.is_zero:
|
1114 |
+
return S.One
|
1115 |
+
elif n is S.NegativeOne:
|
1116 |
+
if x is None:
|
1117 |
+
return S.Pi/2
|
1118 |
+
from sympy.functions.special.gamma_functions import digamma
|
1119 |
+
return digamma((x+1)/2) - digamma(x/2)
|
1120 |
+
elif n.is_integer is False or n.is_nonnegative is False:
|
1121 |
+
return
|
1122 |
+
# Euler numbers
|
1123 |
+
elif x is None:
|
1124 |
+
if n.is_odd and n.is_positive:
|
1125 |
+
return S.Zero
|
1126 |
+
elif n.is_Number:
|
1127 |
+
from mpmath import mp
|
1128 |
+
n = n._to_mpmath(mp.prec)
|
1129 |
+
res = mp.eulernum(n, exact=True)
|
1130 |
+
return Integer(res)
|
1131 |
+
# Euler polynomials
|
1132 |
+
elif n.is_Number:
|
1133 |
+
return euler_poly(n, x)
|
1134 |
+
|
1135 |
+
def _eval_rewrite_as_Sum(self, n, x=None, **kwargs):
|
1136 |
+
from sympy.concrete.summations import Sum
|
1137 |
+
if x is None and n.is_even:
|
1138 |
+
k = Dummy("k", integer=True)
|
1139 |
+
j = Dummy("j", integer=True)
|
1140 |
+
n = n / 2
|
1141 |
+
Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j *
|
1142 |
+
(k - 2*j)**(2*n + 1)) /
|
1143 |
+
(2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1)))
|
1144 |
+
return Em
|
1145 |
+
if x:
|
1146 |
+
k = Dummy("k", integer=True)
|
1147 |
+
return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n))
|
1148 |
+
|
1149 |
+
def _eval_rewrite_as_genocchi(self, n, x=None, **kwargs):
|
1150 |
+
if x is None:
|
1151 |
+
return Piecewise((S.Pi/2, Eq(n, -1)),
|
1152 |
+
(-2**n * genocchi(n+1, S.Half) / (n+1), True))
|
1153 |
+
from sympy.functions.special.gamma_functions import digamma
|
1154 |
+
return Piecewise((digamma((x+1)/2) - digamma(x/2), Eq(n, -1)),
|
1155 |
+
(-genocchi(n+1, x) / (n+1), True))
|
1156 |
+
|
1157 |
+
def _eval_evalf(self, prec):
|
1158 |
+
if not all(i.is_number for i in self.args):
|
1159 |
+
return
|
1160 |
+
from mpmath import mp
|
1161 |
+
m, x = (self.args[0], None) if len(self.args) == 1 else self.args
|
1162 |
+
m = m._to_mpmath(prec)
|
1163 |
+
if x is not None:
|
1164 |
+
x = x._to_mpmath(prec)
|
1165 |
+
with workprec(prec):
|
1166 |
+
if mp.isint(m) and m >= 0:
|
1167 |
+
res = mp.eulernum(m) if x is None else mp.eulerpoly(m, x)
|
1168 |
+
else:
|
1169 |
+
if m == -1:
|
1170 |
+
res = mp.pi if x is None else mp.digamma((x+1)/2) - mp.digamma(x/2)
|
1171 |
+
else:
|
1172 |
+
y = 0.5 if x is None else x
|
1173 |
+
res = 2 * (mp.zeta(-m, y) - 2**(m+1) * mp.zeta(-m, (y+1)/2))
|
1174 |
+
if x is None:
|
1175 |
+
res *= 2**m
|
1176 |
+
return Expr._from_mpmath(res, prec)
|
1177 |
+
|
1178 |
+
|
1179 |
+
#----------------------------------------------------------------------------#
|
1180 |
+
# #
|
1181 |
+
# Catalan numbers #
|
1182 |
+
# #
|
1183 |
+
#----------------------------------------------------------------------------#
|
1184 |
+
|
1185 |
+
|
1186 |
+
class catalan(Function):
|
1187 |
+
r"""
|
1188 |
+
Catalan numbers
|
1189 |
+
|
1190 |
+
The `n^{th}` catalan number is given by:
|
1191 |
+
|
1192 |
+
.. math :: C_n = \frac{1}{n+1} \binom{2n}{n}
|
1193 |
+
|
1194 |
+
* ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`
|
1195 |
+
|
1196 |
+
Examples
|
1197 |
+
========
|
1198 |
+
|
1199 |
+
>>> from sympy import (Symbol, binomial, gamma, hyper,
|
1200 |
+
... catalan, diff, combsimp, Rational, I)
|
1201 |
+
|
1202 |
+
>>> [catalan(i) for i in range(1,10)]
|
1203 |
+
[1, 2, 5, 14, 42, 132, 429, 1430, 4862]
|
1204 |
+
|
1205 |
+
>>> n = Symbol("n", integer=True)
|
1206 |
+
|
1207 |
+
>>> catalan(n)
|
1208 |
+
catalan(n)
|
1209 |
+
|
1210 |
+
Catalan numbers can be transformed into several other, identical
|
1211 |
+
expressions involving other mathematical functions
|
1212 |
+
|
1213 |
+
>>> catalan(n).rewrite(binomial)
|
1214 |
+
binomial(2*n, n)/(n + 1)
|
1215 |
+
|
1216 |
+
>>> catalan(n).rewrite(gamma)
|
1217 |
+
4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))
|
1218 |
+
|
1219 |
+
>>> catalan(n).rewrite(hyper)
|
1220 |
+
hyper((1 - n, -n), (2,), 1)
|
1221 |
+
|
1222 |
+
For some non-integer values of n we can get closed form
|
1223 |
+
expressions by rewriting in terms of gamma functions:
|
1224 |
+
|
1225 |
+
>>> catalan(Rational(1, 2)).rewrite(gamma)
|
1226 |
+
8/(3*pi)
|
1227 |
+
|
1228 |
+
We can differentiate the Catalan numbers C(n) interpreted as a
|
1229 |
+
continuous real function in n:
|
1230 |
+
|
1231 |
+
>>> diff(catalan(n), n)
|
1232 |
+
(polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)
|
1233 |
+
|
1234 |
+
As a more advanced example consider the following ratio
|
1235 |
+
between consecutive numbers:
|
1236 |
+
|
1237 |
+
>>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
|
1238 |
+
2*(2*n + 1)/(n + 2)
|
1239 |
+
|
1240 |
+
The Catalan numbers can be generalized to complex numbers:
|
1241 |
+
|
1242 |
+
>>> catalan(I).rewrite(gamma)
|
1243 |
+
4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))
|
1244 |
+
|
1245 |
+
and evaluated with arbitrary precision:
|
1246 |
+
|
1247 |
+
>>> catalan(I).evalf(20)
|
1248 |
+
0.39764993382373624267 - 0.020884341620842555705*I
|
1249 |
+
|
1250 |
+
See Also
|
1251 |
+
========
|
1252 |
+
|
1253 |
+
andre, bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi,
|
1254 |
+
partition, tribonacci, sympy.functions.combinatorial.factorials.binomial
|
1255 |
+
|
1256 |
+
References
|
1257 |
+
==========
|
1258 |
+
|
1259 |
+
.. [1] https://en.wikipedia.org/wiki/Catalan_number
|
1260 |
+
.. [2] https://mathworld.wolfram.com/CatalanNumber.html
|
1261 |
+
.. [3] https://functions.wolfram.com/GammaBetaErf/CatalanNumber/
|
1262 |
+
.. [4] http://geometer.org/mathcircles/catalan.pdf
|
1263 |
+
|
1264 |
+
"""
|
1265 |
+
|
1266 |
+
@classmethod
|
1267 |
+
def eval(cls, n):
|
1268 |
+
from sympy.functions.special.gamma_functions import gamma
|
1269 |
+
if (n.is_Integer and n.is_nonnegative) or \
|
1270 |
+
(n.is_noninteger and n.is_negative):
|
1271 |
+
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
|
1272 |
+
|
1273 |
+
if (n.is_integer and n.is_negative):
|
1274 |
+
if (n + 1).is_negative:
|
1275 |
+
return S.Zero
|
1276 |
+
if (n + 1).is_zero:
|
1277 |
+
return Rational(-1, 2)
|
1278 |
+
|
1279 |
+
def fdiff(self, argindex=1):
|
1280 |
+
from sympy.functions.elementary.exponential import log
|
1281 |
+
from sympy.functions.special.gamma_functions import polygamma
|
1282 |
+
n = self.args[0]
|
1283 |
+
return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4))
|
1284 |
+
|
1285 |
+
def _eval_rewrite_as_binomial(self, n, **kwargs):
|
1286 |
+
return binomial(2*n, n)/(n + 1)
|
1287 |
+
|
1288 |
+
def _eval_rewrite_as_factorial(self, n, **kwargs):
|
1289 |
+
return factorial(2*n) / (factorial(n+1) * factorial(n))
|
1290 |
+
|
1291 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
1292 |
+
from sympy.functions.special.gamma_functions import gamma
|
1293 |
+
# The gamma function allows to generalize Catalan numbers to complex n
|
1294 |
+
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
|
1295 |
+
|
1296 |
+
def _eval_rewrite_as_hyper(self, n, **kwargs):
|
1297 |
+
from sympy.functions.special.hyper import hyper
|
1298 |
+
return hyper([1 - n, -n], [2], 1)
|
1299 |
+
|
1300 |
+
def _eval_rewrite_as_Product(self, n, **kwargs):
|
1301 |
+
from sympy.concrete.products import Product
|
1302 |
+
if not (n.is_integer and n.is_nonnegative):
|
1303 |
+
return self
|
1304 |
+
k = Dummy('k', integer=True, positive=True)
|
1305 |
+
return Product((n + k) / k, (k, 2, n))
|
1306 |
+
|
1307 |
+
def _eval_is_integer(self):
|
1308 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
1309 |
+
return True
|
1310 |
+
|
1311 |
+
def _eval_is_positive(self):
|
1312 |
+
if self.args[0].is_nonnegative:
|
1313 |
+
return True
|
1314 |
+
|
1315 |
+
def _eval_is_composite(self):
|
1316 |
+
if self.args[0].is_integer and (self.args[0] - 3).is_positive:
|
1317 |
+
return True
|
1318 |
+
|
1319 |
+
def _eval_evalf(self, prec):
|
1320 |
+
from sympy.functions.special.gamma_functions import gamma
|
1321 |
+
if self.args[0].is_number:
|
1322 |
+
return self.rewrite(gamma)._eval_evalf(prec)
|
1323 |
+
|
1324 |
+
|
1325 |
+
#----------------------------------------------------------------------------#
|
1326 |
+
# #
|
1327 |
+
# Genocchi numbers #
|
1328 |
+
# #
|
1329 |
+
#----------------------------------------------------------------------------#
|
1330 |
+
|
1331 |
+
|
1332 |
+
class genocchi(Function):
|
1333 |
+
r"""
|
1334 |
+
Genocchi numbers / Genocchi polynomials / Genocchi function
|
1335 |
+
|
1336 |
+
The Genocchi numbers are a sequence of integers `G_n` that satisfy the
|
1337 |
+
relation:
|
1338 |
+
|
1339 |
+
.. math:: \frac{-2t}{1 + e^{-t}} = \sum_{n=0}^\infty \frac{G_n t^n}{n!}
|
1340 |
+
|
1341 |
+
They are related to the Bernoulli numbers by
|
1342 |
+
|
1343 |
+
.. math:: G_n = 2 (1 - 2^n) B_n
|
1344 |
+
|
1345 |
+
and generalize like the Bernoulli numbers to the Genocchi polynomials and
|
1346 |
+
function as
|
1347 |
+
|
1348 |
+
.. math:: \operatorname{G}(s, a) = 2 \left(\operatorname{B}(s, a) -
|
1349 |
+
2^s \operatorname{B}\left(s, \frac{a+1}{2}\right)\right)
|
1350 |
+
|
1351 |
+
.. versionchanged:: 1.12
|
1352 |
+
``genocchi(1)`` gives `-1` instead of `1`.
|
1353 |
+
|
1354 |
+
Examples
|
1355 |
+
========
|
1356 |
+
|
1357 |
+
>>> from sympy import genocchi, Symbol
|
1358 |
+
>>> [genocchi(n) for n in range(9)]
|
1359 |
+
[0, -1, -1, 0, 1, 0, -3, 0, 17]
|
1360 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
1361 |
+
>>> genocchi(2*n + 1)
|
1362 |
+
0
|
1363 |
+
>>> x = Symbol('x')
|
1364 |
+
>>> genocchi(4, x)
|
1365 |
+
-4*x**3 + 6*x**2 - 1
|
1366 |
+
|
1367 |
+
See Also
|
1368 |
+
========
|
1369 |
+
|
1370 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
|
1371 |
+
sympy.polys.appellseqs.genocchi_poly
|
1372 |
+
|
1373 |
+
References
|
1374 |
+
==========
|
1375 |
+
|
1376 |
+
.. [1] https://en.wikipedia.org/wiki/Genocchi_number
|
1377 |
+
.. [2] https://mathworld.wolfram.com/GenocchiNumber.html
|
1378 |
+
.. [3] Peter Luschny, "An introduction to the Bernoulli function",
|
1379 |
+
https://arxiv.org/abs/2009.06743
|
1380 |
+
|
1381 |
+
"""
|
1382 |
+
|
1383 |
+
@classmethod
|
1384 |
+
def eval(cls, n, x=None):
|
1385 |
+
if x is S.One:
|
1386 |
+
return cls(n)
|
1387 |
+
elif n.is_integer is False or n.is_nonnegative is False:
|
1388 |
+
return
|
1389 |
+
# Genocchi numbers
|
1390 |
+
elif x is None:
|
1391 |
+
if n.is_odd and (n-1).is_positive:
|
1392 |
+
return S.Zero
|
1393 |
+
elif n.is_Number:
|
1394 |
+
return 2 * (1-S(2)**n) * bernoulli(n)
|
1395 |
+
# Genocchi polynomials
|
1396 |
+
elif n.is_Number:
|
1397 |
+
return genocchi_poly(n, x)
|
1398 |
+
|
1399 |
+
def _eval_rewrite_as_bernoulli(self, n, x=1, **kwargs):
|
1400 |
+
if x == 1 and n.is_integer and n.is_nonnegative:
|
1401 |
+
return 2 * (1-S(2)**n) * bernoulli(n)
|
1402 |
+
return 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
|
1403 |
+
|
1404 |
+
def _eval_rewrite_as_dirichlet_eta(self, n, x=1, **kwargs):
|
1405 |
+
from sympy.functions.special.zeta_functions import dirichlet_eta
|
1406 |
+
return -2*n * dirichlet_eta(1-n, x)
|
1407 |
+
|
1408 |
+
def _eval_is_integer(self):
|
1409 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1410 |
+
return
|
1411 |
+
n = self.args[0]
|
1412 |
+
if n.is_integer and n.is_nonnegative:
|
1413 |
+
return True
|
1414 |
+
|
1415 |
+
def _eval_is_negative(self):
|
1416 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1417 |
+
return
|
1418 |
+
n = self.args[0]
|
1419 |
+
if n.is_integer and n.is_nonnegative:
|
1420 |
+
if n.is_odd:
|
1421 |
+
return fuzzy_not((n-1).is_positive)
|
1422 |
+
return (n/2).is_odd
|
1423 |
+
|
1424 |
+
def _eval_is_positive(self):
|
1425 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1426 |
+
return
|
1427 |
+
n = self.args[0]
|
1428 |
+
if n.is_integer and n.is_nonnegative:
|
1429 |
+
if n.is_zero or n.is_odd:
|
1430 |
+
return False
|
1431 |
+
return (n/2).is_even
|
1432 |
+
|
1433 |
+
def _eval_is_even(self):
|
1434 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1435 |
+
return
|
1436 |
+
n = self.args[0]
|
1437 |
+
if n.is_integer and n.is_nonnegative:
|
1438 |
+
if n.is_even:
|
1439 |
+
return n.is_zero
|
1440 |
+
return (n-1).is_positive
|
1441 |
+
|
1442 |
+
def _eval_is_odd(self):
|
1443 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1444 |
+
return
|
1445 |
+
n = self.args[0]
|
1446 |
+
if n.is_integer and n.is_nonnegative:
|
1447 |
+
if n.is_even:
|
1448 |
+
return fuzzy_not(n.is_zero)
|
1449 |
+
return fuzzy_not((n-1).is_positive)
|
1450 |
+
|
1451 |
+
def _eval_is_prime(self):
|
1452 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1453 |
+
return
|
1454 |
+
n = self.args[0]
|
1455 |
+
# only G_6 = -3 and G_8 = 17 are prime,
|
1456 |
+
# but SymPy does not consider negatives as prime
|
1457 |
+
# so only n=8 is tested
|
1458 |
+
return (n-8).is_zero
|
1459 |
+
|
1460 |
+
def _eval_evalf(self, prec):
|
1461 |
+
if all(i.is_number for i in self.args):
|
1462 |
+
return self.rewrite(bernoulli)._eval_evalf(prec)
|
1463 |
+
|
1464 |
+
|
1465 |
+
#----------------------------------------------------------------------------#
|
1466 |
+
# #
|
1467 |
+
# Andre numbers #
|
1468 |
+
# #
|
1469 |
+
#----------------------------------------------------------------------------#
|
1470 |
+
|
1471 |
+
|
1472 |
+
class andre(Function):
|
1473 |
+
r"""
|
1474 |
+
Andre numbers / Andre function
|
1475 |
+
|
1476 |
+
The Andre number `\mathcal{A}_n` is Luschny's name for half the number of
|
1477 |
+
*alternating permutations* on `n` elements, where a permutation is alternating
|
1478 |
+
if adjacent elements alternately compare "greater" and "smaller" going from
|
1479 |
+
left to right. For example, `2 < 3 > 1 < 4` is an alternating permutation.
|
1480 |
+
|
1481 |
+
This sequence is A000111 in the OEIS, which assigns the names *up/down numbers*
|
1482 |
+
and *Euler zigzag numbers*. It satisfies a recurrence relation similar to that
|
1483 |
+
for the Catalan numbers, with `\mathcal{A}_0 = 1` and
|
1484 |
+
|
1485 |
+
.. math:: 2 \mathcal{A}_{n+1} = \sum_{k=0}^n \binom{n}{k} \mathcal{A}_k \mathcal{A}_{n-k}
|
1486 |
+
|
1487 |
+
The Bernoulli and Euler numbers are signed transformations of the odd- and
|
1488 |
+
even-indexed elements of this sequence respectively:
|
1489 |
+
|
1490 |
+
.. math :: \operatorname{B}_{2k} = \frac{2k \mathcal{A}_{2k-1}}{(-4)^k - (-16)^k}
|
1491 |
+
|
1492 |
+
.. math :: \operatorname{E}_{2k} = (-1)^k \mathcal{A}_{2k}
|
1493 |
+
|
1494 |
+
Like the Bernoulli and Euler numbers, the Andre numbers are interpolated by the
|
1495 |
+
entire Andre function:
|
1496 |
+
|
1497 |
+
.. math :: \mathcal{A}(s) = (-i)^{s+1} \operatorname{Li}_{-s}(i) +
|
1498 |
+
i^{s+1} \operatorname{Li}_{-s}(-i) = \\ \frac{2 \Gamma(s+1)}{(2\pi)^{s+1}}
|
1499 |
+
(\zeta(s+1, 1/4) - \zeta(s+1, 3/4) \cos{\pi s})
|
1500 |
+
|
1501 |
+
Examples
|
1502 |
+
========
|
1503 |
+
|
1504 |
+
>>> from sympy import andre, euler, bernoulli
|
1505 |
+
>>> [andre(n) for n in range(11)]
|
1506 |
+
[1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
|
1507 |
+
>>> [(-1)**k * andre(2*k) for k in range(7)]
|
1508 |
+
[1, -1, 5, -61, 1385, -50521, 2702765]
|
1509 |
+
>>> [euler(2*k) for k in range(7)]
|
1510 |
+
[1, -1, 5, -61, 1385, -50521, 2702765]
|
1511 |
+
>>> [andre(2*k-1) * (2*k) / ((-4)**k - (-16)**k) for k in range(1, 8)]
|
1512 |
+
[1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
|
1513 |
+
>>> [bernoulli(2*k) for k in range(1, 8)]
|
1514 |
+
[1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
|
1515 |
+
|
1516 |
+
See Also
|
1517 |
+
========
|
1518 |
+
|
1519 |
+
bernoulli, catalan, euler, sympy.polys.appellseqs.andre_poly
|
1520 |
+
|
1521 |
+
References
|
1522 |
+
==========
|
1523 |
+
|
1524 |
+
.. [1] https://en.wikipedia.org/wiki/Alternating_permutation
|
1525 |
+
.. [2] https://mathworld.wolfram.com/EulerZigzagNumber.html
|
1526 |
+
.. [3] Peter Luschny, "An introduction to the Bernoulli function",
|
1527 |
+
https://arxiv.org/abs/2009.06743
|
1528 |
+
"""
|
1529 |
+
|
1530 |
+
@classmethod
|
1531 |
+
def eval(cls, n):
|
1532 |
+
if n is S.NaN:
|
1533 |
+
return S.NaN
|
1534 |
+
elif n is S.Infinity:
|
1535 |
+
return S.Infinity
|
1536 |
+
if n.is_zero:
|
1537 |
+
return S.One
|
1538 |
+
elif n == -1:
|
1539 |
+
return -log(2)
|
1540 |
+
elif n == -2:
|
1541 |
+
return -2*S.Catalan
|
1542 |
+
elif n.is_Integer:
|
1543 |
+
if n.is_nonnegative and n.is_even:
|
1544 |
+
return abs(euler(n))
|
1545 |
+
elif n.is_odd:
|
1546 |
+
from sympy.functions.special.zeta_functions import zeta
|
1547 |
+
m = -n-1
|
1548 |
+
return I**m * Rational(1-2**m, 4**m) * zeta(-n)
|
1549 |
+
|
1550 |
+
def _eval_rewrite_as_zeta(self, s, **kwargs):
|
1551 |
+
from sympy.functions.elementary.trigonometric import cos
|
1552 |
+
from sympy.functions.special.gamma_functions import gamma
|
1553 |
+
from sympy.functions.special.zeta_functions import zeta
|
1554 |
+
return 2 * gamma(s+1) / (2*pi)**(s+1) * \
|
1555 |
+
(zeta(s+1, S.One/4) - cos(pi*s) * zeta(s+1, S(3)/4))
|
1556 |
+
|
1557 |
+
def _eval_rewrite_as_polylog(self, s, **kwargs):
|
1558 |
+
from sympy.functions.special.zeta_functions import polylog
|
1559 |
+
return (-I)**(s+1) * polylog(-s, I) + I**(s+1) * polylog(-s, -I)
|
1560 |
+
|
1561 |
+
def _eval_is_integer(self):
|
1562 |
+
n = self.args[0]
|
1563 |
+
if n.is_integer and n.is_nonnegative:
|
1564 |
+
return True
|
1565 |
+
|
1566 |
+
def _eval_is_positive(self):
|
1567 |
+
if self.args[0].is_nonnegative:
|
1568 |
+
return True
|
1569 |
+
|
1570 |
+
def _eval_evalf(self, prec):
|
1571 |
+
if not self.args[0].is_number:
|
1572 |
+
return
|
1573 |
+
s = self.args[0]._to_mpmath(prec+12)
|
1574 |
+
with workprec(prec+12):
|
1575 |
+
sp, cp = mp.sinpi(s/2), mp.cospi(s/2)
|
1576 |
+
res = 2*mp.dirichlet(-s, (-sp, cp, sp, -cp))
|
1577 |
+
return Expr._from_mpmath(res, prec)
|
1578 |
+
|
1579 |
+
|
1580 |
+
#----------------------------------------------------------------------------#
|
1581 |
+
# #
|
1582 |
+
# Partition numbers #
|
1583 |
+
# #
|
1584 |
+
#----------------------------------------------------------------------------#
|
1585 |
+
|
1586 |
+
_npartition = [1, 1]
|
1587 |
+
class partition(Function):
|
1588 |
+
r"""
|
1589 |
+
Partition numbers
|
1590 |
+
|
1591 |
+
The Partition numbers are a sequence of integers `p_n` that represent the
|
1592 |
+
number of distinct ways of representing `n` as a sum of natural numbers
|
1593 |
+
(with order irrelevant). The generating function for `p_n` is given by:
|
1594 |
+
|
1595 |
+
.. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}
|
1596 |
+
|
1597 |
+
Examples
|
1598 |
+
========
|
1599 |
+
|
1600 |
+
>>> from sympy import partition, Symbol
|
1601 |
+
>>> [partition(n) for n in range(9)]
|
1602 |
+
[1, 1, 2, 3, 5, 7, 11, 15, 22]
|
1603 |
+
>>> n = Symbol('n', integer=True, negative=True)
|
1604 |
+
>>> partition(n)
|
1605 |
+
0
|
1606 |
+
|
1607 |
+
See Also
|
1608 |
+
========
|
1609 |
+
|
1610 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci
|
1611 |
+
|
1612 |
+
References
|
1613 |
+
==========
|
1614 |
+
|
1615 |
+
.. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
|
1616 |
+
.. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem
|
1617 |
+
|
1618 |
+
"""
|
1619 |
+
|
1620 |
+
@staticmethod
|
1621 |
+
def _partition(n):
|
1622 |
+
L = len(_npartition)
|
1623 |
+
if n < L:
|
1624 |
+
return _npartition[n]
|
1625 |
+
# lengthen cache
|
1626 |
+
for _n in range(L, n + 1):
|
1627 |
+
v, p, i = 0, 0, 0
|
1628 |
+
while 1:
|
1629 |
+
s = 0
|
1630 |
+
p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ...
|
1631 |
+
if _n >= p:
|
1632 |
+
s += _npartition[_n - p]
|
1633 |
+
i += 1
|
1634 |
+
gp = p + i # gp = generalized pentagonal: 2, 7, 15, ...
|
1635 |
+
if _n >= gp:
|
1636 |
+
s += _npartition[_n - gp]
|
1637 |
+
if s == 0:
|
1638 |
+
break
|
1639 |
+
else:
|
1640 |
+
v += s if i%2 == 1 else -s
|
1641 |
+
_npartition.append(v)
|
1642 |
+
return v
|
1643 |
+
|
1644 |
+
@classmethod
|
1645 |
+
def eval(cls, n):
|
1646 |
+
is_int = n.is_integer
|
1647 |
+
if is_int == False:
|
1648 |
+
raise ValueError("Partition numbers are defined only for "
|
1649 |
+
"integers")
|
1650 |
+
elif is_int:
|
1651 |
+
if n.is_negative:
|
1652 |
+
return S.Zero
|
1653 |
+
|
1654 |
+
if n.is_zero or (n - 1).is_zero:
|
1655 |
+
return S.One
|
1656 |
+
|
1657 |
+
if n.is_Integer:
|
1658 |
+
return Integer(cls._partition(n))
|
1659 |
+
|
1660 |
+
|
1661 |
+
def _eval_is_integer(self):
|
1662 |
+
if self.args[0].is_integer:
|
1663 |
+
return True
|
1664 |
+
|
1665 |
+
def _eval_is_negative(self):
|
1666 |
+
if self.args[0].is_integer:
|
1667 |
+
return False
|
1668 |
+
|
1669 |
+
def _eval_is_positive(self):
|
1670 |
+
n = self.args[0]
|
1671 |
+
if n.is_nonnegative and n.is_integer:
|
1672 |
+
return True
|
1673 |
+
|
1674 |
+
|
1675 |
+
#######################################################################
|
1676 |
+
###
|
1677 |
+
### Functions for enumerating partitions, permutations and combinations
|
1678 |
+
###
|
1679 |
+
#######################################################################
|
1680 |
+
|
1681 |
+
|
1682 |
+
class _MultisetHistogram(tuple):
|
1683 |
+
pass
|
1684 |
+
|
1685 |
+
|
1686 |
+
_N = -1
|
1687 |
+
_ITEMS = -2
|
1688 |
+
_M = slice(None, _ITEMS)
|
1689 |
+
|
1690 |
+
|
1691 |
+
def _multiset_histogram(n):
|
1692 |
+
"""Return tuple used in permutation and combination counting. Input
|
1693 |
+
is a dictionary giving items with counts as values or a sequence of
|
1694 |
+
items (which need not be sorted).
|
1695 |
+
|
1696 |
+
The data is stored in a class deriving from tuple so it is easily
|
1697 |
+
recognized and so it can be converted easily to a list.
|
1698 |
+
"""
|
1699 |
+
if isinstance(n, dict): # item: count
|
1700 |
+
if not all(isinstance(v, int) and v >= 0 for v in n.values()):
|
1701 |
+
raise ValueError
|
1702 |
+
tot = sum(n.values())
|
1703 |
+
items = sum(1 for k in n if n[k] > 0)
|
1704 |
+
return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot])
|
1705 |
+
else:
|
1706 |
+
n = list(n)
|
1707 |
+
s = set(n)
|
1708 |
+
lens = len(s)
|
1709 |
+
lenn = len(n)
|
1710 |
+
if lens == lenn:
|
1711 |
+
n = [1]*lenn + [lenn, lenn]
|
1712 |
+
return _MultisetHistogram(n)
|
1713 |
+
m = dict(zip(s, range(lens)))
|
1714 |
+
d = dict(zip(range(lens), (0,)*lens))
|
1715 |
+
for i in n:
|
1716 |
+
d[m[i]] += 1
|
1717 |
+
return _multiset_histogram(d)
|
1718 |
+
|
1719 |
+
|
1720 |
+
def nP(n, k=None, replacement=False):
|
1721 |
+
"""Return the number of permutations of ``n`` items taken ``k`` at a time.
|
1722 |
+
|
1723 |
+
Possible values for ``n``:
|
1724 |
+
|
1725 |
+
integer - set of length ``n``
|
1726 |
+
|
1727 |
+
sequence - converted to a multiset internally
|
1728 |
+
|
1729 |
+
multiset - {element: multiplicity}
|
1730 |
+
|
1731 |
+
If ``k`` is None then the total of all permutations of length 0
|
1732 |
+
through the number of items represented by ``n`` will be returned.
|
1733 |
+
|
1734 |
+
If ``replacement`` is True then a given item can appear more than once
|
1735 |
+
in the ``k`` items. (For example, for 'ab' permutations of 2 would
|
1736 |
+
include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
|
1737 |
+
``n`` is ignored when ``replacement`` is True but the total number
|
1738 |
+
of elements is considered since no element can appear more times than
|
1739 |
+
the number of elements in ``n``.
|
1740 |
+
|
1741 |
+
Examples
|
1742 |
+
========
|
1743 |
+
|
1744 |
+
>>> from sympy.functions.combinatorial.numbers import nP
|
1745 |
+
>>> from sympy.utilities.iterables import multiset_permutations, multiset
|
1746 |
+
>>> nP(3, 2)
|
1747 |
+
6
|
1748 |
+
>>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
|
1749 |
+
True
|
1750 |
+
>>> nP('aab', 2)
|
1751 |
+
3
|
1752 |
+
>>> nP([1, 2, 2], 2)
|
1753 |
+
3
|
1754 |
+
>>> [nP(3, i) for i in range(4)]
|
1755 |
+
[1, 3, 6, 6]
|
1756 |
+
>>> nP(3) == sum(_)
|
1757 |
+
True
|
1758 |
+
|
1759 |
+
When ``replacement`` is True, each item can have multiplicity
|
1760 |
+
equal to the length represented by ``n``:
|
1761 |
+
|
1762 |
+
>>> nP('aabc', replacement=True)
|
1763 |
+
121
|
1764 |
+
>>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
|
1765 |
+
[1, 3, 9, 27, 81]
|
1766 |
+
>>> sum(_)
|
1767 |
+
121
|
1768 |
+
|
1769 |
+
See Also
|
1770 |
+
========
|
1771 |
+
sympy.utilities.iterables.multiset_permutations
|
1772 |
+
|
1773 |
+
References
|
1774 |
+
==========
|
1775 |
+
|
1776 |
+
.. [1] https://en.wikipedia.org/wiki/Permutation
|
1777 |
+
|
1778 |
+
"""
|
1779 |
+
try:
|
1780 |
+
n = as_int(n)
|
1781 |
+
except ValueError:
|
1782 |
+
return Integer(_nP(_multiset_histogram(n), k, replacement))
|
1783 |
+
return Integer(_nP(n, k, replacement))
|
1784 |
+
|
1785 |
+
|
1786 |
+
@cacheit
|
1787 |
+
def _nP(n, k=None, replacement=False):
|
1788 |
+
|
1789 |
+
if k == 0:
|
1790 |
+
return 1
|
1791 |
+
if isinstance(n, SYMPY_INTS): # n different items
|
1792 |
+
# assert n >= 0
|
1793 |
+
if k is None:
|
1794 |
+
return sum(_nP(n, i, replacement) for i in range(n + 1))
|
1795 |
+
elif replacement:
|
1796 |
+
return n**k
|
1797 |
+
elif k > n:
|
1798 |
+
return 0
|
1799 |
+
elif k == n:
|
1800 |
+
return factorial(k)
|
1801 |
+
elif k == 1:
|
1802 |
+
return n
|
1803 |
+
else:
|
1804 |
+
# assert k >= 0
|
1805 |
+
return _product(n - k + 1, n)
|
1806 |
+
elif isinstance(n, _MultisetHistogram):
|
1807 |
+
if k is None:
|
1808 |
+
return sum(_nP(n, i, replacement) for i in range(n[_N] + 1))
|
1809 |
+
elif replacement:
|
1810 |
+
return n[_ITEMS]**k
|
1811 |
+
elif k == n[_N]:
|
1812 |
+
return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1])
|
1813 |
+
elif k > n[_N]:
|
1814 |
+
return 0
|
1815 |
+
elif k == 1:
|
1816 |
+
return n[_ITEMS]
|
1817 |
+
else:
|
1818 |
+
# assert k >= 0
|
1819 |
+
tot = 0
|
1820 |
+
n = list(n)
|
1821 |
+
for i in range(len(n[_M])):
|
1822 |
+
if not n[i]:
|
1823 |
+
continue
|
1824 |
+
n[_N] -= 1
|
1825 |
+
if n[i] == 1:
|
1826 |
+
n[i] = 0
|
1827 |
+
n[_ITEMS] -= 1
|
1828 |
+
tot += _nP(_MultisetHistogram(n), k - 1)
|
1829 |
+
n[_ITEMS] += 1
|
1830 |
+
n[i] = 1
|
1831 |
+
else:
|
1832 |
+
n[i] -= 1
|
1833 |
+
tot += _nP(_MultisetHistogram(n), k - 1)
|
1834 |
+
n[i] += 1
|
1835 |
+
n[_N] += 1
|
1836 |
+
return tot
|
1837 |
+
|
1838 |
+
|
1839 |
+
@cacheit
|
1840 |
+
def _AOP_product(n):
|
1841 |
+
"""for n = (m1, m2, .., mk) return the coefficients of the polynomial,
|
1842 |
+
prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
|
1843 |
+
of the product of AOPs (all-one polynomials) or order given in n. The
|
1844 |
+
resulting coefficient corresponding to x**r is the number of r-length
|
1845 |
+
combinations of sum(n) elements with multiplicities given in n.
|
1846 |
+
The coefficients are given as a default dictionary (so if a query is made
|
1847 |
+
for a key that is not present, 0 will be returned).
|
1848 |
+
|
1849 |
+
Examples
|
1850 |
+
========
|
1851 |
+
|
1852 |
+
>>> from sympy.functions.combinatorial.numbers import _AOP_product
|
1853 |
+
>>> from sympy.abc import x
|
1854 |
+
>>> n = (2, 2, 3) # e.g. aabbccc
|
1855 |
+
>>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
|
1856 |
+
>>> c = _AOP_product(n); dict(c)
|
1857 |
+
{0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
|
1858 |
+
>>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
|
1859 |
+
True
|
1860 |
+
|
1861 |
+
The generating poly used here is the same as that listed in
|
1862 |
+
https://tinyurl.com/cep849r, but in a refactored form.
|
1863 |
+
|
1864 |
+
"""
|
1865 |
+
|
1866 |
+
n = list(n)
|
1867 |
+
ord = sum(n)
|
1868 |
+
need = (ord + 2)//2
|
1869 |
+
rv = [1]*(n.pop() + 1)
|
1870 |
+
rv.extend((0,) * (need - len(rv)))
|
1871 |
+
rv = rv[:need]
|
1872 |
+
while n:
|
1873 |
+
ni = n.pop()
|
1874 |
+
N = ni + 1
|
1875 |
+
was = rv[:]
|
1876 |
+
for i in range(1, min(N, len(rv))):
|
1877 |
+
rv[i] += rv[i - 1]
|
1878 |
+
for i in range(N, need):
|
1879 |
+
rv[i] += rv[i - 1] - was[i - N]
|
1880 |
+
rev = list(reversed(rv))
|
1881 |
+
if ord % 2:
|
1882 |
+
rv = rv + rev
|
1883 |
+
else:
|
1884 |
+
rv[-1:] = rev
|
1885 |
+
d = defaultdict(int)
|
1886 |
+
for i, r in enumerate(rv):
|
1887 |
+
d[i] = r
|
1888 |
+
return d
|
1889 |
+
|
1890 |
+
|
1891 |
+
def nC(n, k=None, replacement=False):
|
1892 |
+
"""Return the number of combinations of ``n`` items taken ``k`` at a time.
|
1893 |
+
|
1894 |
+
Possible values for ``n``:
|
1895 |
+
|
1896 |
+
integer - set of length ``n``
|
1897 |
+
|
1898 |
+
sequence - converted to a multiset internally
|
1899 |
+
|
1900 |
+
multiset - {element: multiplicity}
|
1901 |
+
|
1902 |
+
If ``k`` is None then the total of all combinations of length 0
|
1903 |
+
through the number of items represented in ``n`` will be returned.
|
1904 |
+
|
1905 |
+
If ``replacement`` is True then a given item can appear more than once
|
1906 |
+
in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
|
1907 |
+
'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
|
1908 |
+
``replacement`` is True but the total number of elements is considered
|
1909 |
+
since no element can appear more times than the number of elements in
|
1910 |
+
``n``.
|
1911 |
+
|
1912 |
+
Examples
|
1913 |
+
========
|
1914 |
+
|
1915 |
+
>>> from sympy.functions.combinatorial.numbers import nC
|
1916 |
+
>>> from sympy.utilities.iterables import multiset_combinations
|
1917 |
+
>>> nC(3, 2)
|
1918 |
+
3
|
1919 |
+
>>> nC('abc', 2)
|
1920 |
+
3
|
1921 |
+
>>> nC('aab', 2)
|
1922 |
+
2
|
1923 |
+
|
1924 |
+
When ``replacement`` is True, each item can have multiplicity
|
1925 |
+
equal to the length represented by ``n``:
|
1926 |
+
|
1927 |
+
>>> nC('aabc', replacement=True)
|
1928 |
+
35
|
1929 |
+
>>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
|
1930 |
+
[1, 3, 6, 10, 15]
|
1931 |
+
>>> sum(_)
|
1932 |
+
35
|
1933 |
+
|
1934 |
+
If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
|
1935 |
+
then the total of all combinations of length 0 through ``k`` is the
|
1936 |
+
product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
|
1937 |
+
of each item is 1 (i.e., k unique items) then there are 2**k
|
1938 |
+
combinations. For example, if there are 4 unique items, the total number
|
1939 |
+
of combinations is 16:
|
1940 |
+
|
1941 |
+
>>> sum(nC(4, i) for i in range(5))
|
1942 |
+
16
|
1943 |
+
|
1944 |
+
See Also
|
1945 |
+
========
|
1946 |
+
|
1947 |
+
sympy.utilities.iterables.multiset_combinations
|
1948 |
+
|
1949 |
+
References
|
1950 |
+
==========
|
1951 |
+
|
1952 |
+
.. [1] https://en.wikipedia.org/wiki/Combination
|
1953 |
+
.. [2] https://tinyurl.com/cep849r
|
1954 |
+
|
1955 |
+
"""
|
1956 |
+
|
1957 |
+
if isinstance(n, SYMPY_INTS):
|
1958 |
+
if k is None:
|
1959 |
+
if not replacement:
|
1960 |
+
return 2**n
|
1961 |
+
return sum(nC(n, i, replacement) for i in range(n + 1))
|
1962 |
+
if k < 0:
|
1963 |
+
raise ValueError("k cannot be negative")
|
1964 |
+
if replacement:
|
1965 |
+
return binomial(n + k - 1, k)
|
1966 |
+
return binomial(n, k)
|
1967 |
+
if isinstance(n, _MultisetHistogram):
|
1968 |
+
N = n[_N]
|
1969 |
+
if k is None:
|
1970 |
+
if not replacement:
|
1971 |
+
return prod(m + 1 for m in n[_M])
|
1972 |
+
return sum(nC(n, i, replacement) for i in range(N + 1))
|
1973 |
+
elif replacement:
|
1974 |
+
return nC(n[_ITEMS], k, replacement)
|
1975 |
+
# assert k >= 0
|
1976 |
+
elif k in (1, N - 1):
|
1977 |
+
return n[_ITEMS]
|
1978 |
+
elif k in (0, N):
|
1979 |
+
return 1
|
1980 |
+
return _AOP_product(tuple(n[_M]))[k]
|
1981 |
+
else:
|
1982 |
+
return nC(_multiset_histogram(n), k, replacement)
|
1983 |
+
|
1984 |
+
|
1985 |
+
def _eval_stirling1(n, k):
|
1986 |
+
if n == k == 0:
|
1987 |
+
return S.One
|
1988 |
+
if 0 in (n, k):
|
1989 |
+
return S.Zero
|
1990 |
+
|
1991 |
+
# some special values
|
1992 |
+
if n == k:
|
1993 |
+
return S.One
|
1994 |
+
elif k == n - 1:
|
1995 |
+
return binomial(n, 2)
|
1996 |
+
elif k == n - 2:
|
1997 |
+
return (3*n - 1)*binomial(n, 3)/4
|
1998 |
+
elif k == n - 3:
|
1999 |
+
return binomial(n, 2)*binomial(n, 4)
|
2000 |
+
|
2001 |
+
return _stirling1(n, k)
|
2002 |
+
|
2003 |
+
|
2004 |
+
@cacheit
|
2005 |
+
def _stirling1(n, k):
|
2006 |
+
row = [0, 1]+[0]*(k-1) # for n = 1
|
2007 |
+
for i in range(2, n+1):
|
2008 |
+
for j in range(min(k,i), 0, -1):
|
2009 |
+
row[j] = (i-1) * row[j] + row[j-1]
|
2010 |
+
return Integer(row[k])
|
2011 |
+
|
2012 |
+
|
2013 |
+
def _eval_stirling2(n, k):
|
2014 |
+
if n == k == 0:
|
2015 |
+
return S.One
|
2016 |
+
if 0 in (n, k):
|
2017 |
+
return S.Zero
|
2018 |
+
|
2019 |
+
# some special values
|
2020 |
+
if n == k:
|
2021 |
+
return S.One
|
2022 |
+
elif k == n - 1:
|
2023 |
+
return binomial(n, 2)
|
2024 |
+
elif k == 1:
|
2025 |
+
return S.One
|
2026 |
+
elif k == 2:
|
2027 |
+
return Integer(2**(n - 1) - 1)
|
2028 |
+
|
2029 |
+
return _stirling2(n, k)
|
2030 |
+
|
2031 |
+
|
2032 |
+
@cacheit
|
2033 |
+
def _stirling2(n, k):
|
2034 |
+
row = [0, 1]+[0]*(k-1) # for n = 1
|
2035 |
+
for i in range(2, n+1):
|
2036 |
+
for j in range(min(k,i), 0, -1):
|
2037 |
+
row[j] = j * row[j] + row[j-1]
|
2038 |
+
return Integer(row[k])
|
2039 |
+
|
2040 |
+
|
2041 |
+
def stirling(n, k, d=None, kind=2, signed=False):
|
2042 |
+
r"""Return Stirling number $S(n, k)$ of the first or second (default) kind.
|
2043 |
+
|
2044 |
+
The sum of all Stirling numbers of the second kind for $k = 1$
|
2045 |
+
through $n$ is ``bell(n)``. The recurrence relationship for these numbers
|
2046 |
+
is:
|
2047 |
+
|
2048 |
+
.. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;
|
2049 |
+
|
2050 |
+
.. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}
|
2051 |
+
|
2052 |
+
where $j$ is:
|
2053 |
+
$n$ for Stirling numbers of the first kind,
|
2054 |
+
$-n$ for signed Stirling numbers of the first kind,
|
2055 |
+
$k$ for Stirling numbers of the second kind.
|
2056 |
+
|
2057 |
+
The first kind of Stirling number counts the number of permutations of
|
2058 |
+
``n`` distinct items that have ``k`` cycles; the second kind counts the
|
2059 |
+
ways in which ``n`` distinct items can be partitioned into ``k`` parts.
|
2060 |
+
If ``d`` is given, the "reduced Stirling number of the second kind" is
|
2061 |
+
returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
|
2062 |
+
(This counts the ways to partition $n$ consecutive integers into $k$
|
2063 |
+
groups with no pairwise difference less than $d$. See example below.)
|
2064 |
+
|
2065 |
+
To obtain the signed Stirling numbers of the first kind, use keyword
|
2066 |
+
``signed=True``. Using this keyword automatically sets ``kind`` to 1.
|
2067 |
+
|
2068 |
+
Examples
|
2069 |
+
========
|
2070 |
+
|
2071 |
+
>>> from sympy.functions.combinatorial.numbers import stirling, bell
|
2072 |
+
>>> from sympy.combinatorics import Permutation
|
2073 |
+
>>> from sympy.utilities.iterables import multiset_partitions, permutations
|
2074 |
+
|
2075 |
+
First kind (unsigned by default):
|
2076 |
+
|
2077 |
+
>>> [stirling(6, i, kind=1) for i in range(7)]
|
2078 |
+
[0, 120, 274, 225, 85, 15, 1]
|
2079 |
+
>>> perms = list(permutations(range(4)))
|
2080 |
+
>>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
|
2081 |
+
[0, 6, 11, 6, 1]
|
2082 |
+
>>> [stirling(4, i, kind=1) for i in range(5)]
|
2083 |
+
[0, 6, 11, 6, 1]
|
2084 |
+
|
2085 |
+
First kind (signed):
|
2086 |
+
|
2087 |
+
>>> [stirling(4, i, signed=True) for i in range(5)]
|
2088 |
+
[0, -6, 11, -6, 1]
|
2089 |
+
|
2090 |
+
Second kind:
|
2091 |
+
|
2092 |
+
>>> [stirling(10, i) for i in range(12)]
|
2093 |
+
[0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
|
2094 |
+
>>> sum(_) == bell(10)
|
2095 |
+
True
|
2096 |
+
>>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
|
2097 |
+
True
|
2098 |
+
|
2099 |
+
Reduced second kind:
|
2100 |
+
|
2101 |
+
>>> from sympy import subsets, oo
|
2102 |
+
>>> def delta(p):
|
2103 |
+
... if len(p) == 1:
|
2104 |
+
... return oo
|
2105 |
+
... return min(abs(i[0] - i[1]) for i in subsets(p, 2))
|
2106 |
+
>>> parts = multiset_partitions(range(5), 3)
|
2107 |
+
>>> d = 2
|
2108 |
+
>>> sum(1 for p in parts if all(delta(i) >= d for i in p))
|
2109 |
+
7
|
2110 |
+
>>> stirling(5, 3, 2)
|
2111 |
+
7
|
2112 |
+
|
2113 |
+
See Also
|
2114 |
+
========
|
2115 |
+
sympy.utilities.iterables.multiset_partitions
|
2116 |
+
|
2117 |
+
|
2118 |
+
References
|
2119 |
+
==========
|
2120 |
+
|
2121 |
+
.. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
|
2122 |
+
.. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
|
2123 |
+
|
2124 |
+
"""
|
2125 |
+
# TODO: make this a class like bell()
|
2126 |
+
|
2127 |
+
n = as_int(n)
|
2128 |
+
k = as_int(k)
|
2129 |
+
if n < 0:
|
2130 |
+
raise ValueError('n must be nonnegative')
|
2131 |
+
if k > n:
|
2132 |
+
return S.Zero
|
2133 |
+
if d:
|
2134 |
+
# assert k >= d
|
2135 |
+
# kind is ignored -- only kind=2 is supported
|
2136 |
+
return _eval_stirling2(n - d + 1, k - d + 1)
|
2137 |
+
elif signed:
|
2138 |
+
# kind is ignored -- only kind=1 is supported
|
2139 |
+
return S.NegativeOne**(n - k)*_eval_stirling1(n, k)
|
2140 |
+
|
2141 |
+
if kind == 1:
|
2142 |
+
return _eval_stirling1(n, k)
|
2143 |
+
elif kind == 2:
|
2144 |
+
return _eval_stirling2(n, k)
|
2145 |
+
else:
|
2146 |
+
raise ValueError('kind must be 1 or 2, not %s' % k)
|
2147 |
+
|
2148 |
+
|
2149 |
+
@cacheit
|
2150 |
+
def _nT(n, k):
|
2151 |
+
"""Return the partitions of ``n`` items into ``k`` parts. This
|
2152 |
+
is used by ``nT`` for the case when ``n`` is an integer."""
|
2153 |
+
# really quick exits
|
2154 |
+
if k > n or k < 0:
|
2155 |
+
return 0
|
2156 |
+
if k in (1, n):
|
2157 |
+
return 1
|
2158 |
+
if k == 0:
|
2159 |
+
return 0
|
2160 |
+
# exits that could be done below but this is quicker
|
2161 |
+
if k == 2:
|
2162 |
+
return n//2
|
2163 |
+
d = n - k
|
2164 |
+
if d <= 3:
|
2165 |
+
return d
|
2166 |
+
# quick exit
|
2167 |
+
if 3*k >= n: # or, equivalently, 2*k >= d
|
2168 |
+
# all the information needed in this case
|
2169 |
+
# will be in the cache needed to calculate
|
2170 |
+
# partition(d), so...
|
2171 |
+
# update cache
|
2172 |
+
tot = partition._partition(d)
|
2173 |
+
# and correct for values not needed
|
2174 |
+
if d - k > 0:
|
2175 |
+
tot -= sum(_npartition[:d - k])
|
2176 |
+
return tot
|
2177 |
+
# regular exit
|
2178 |
+
# nT(n, k) = Sum(nT(n - k, m), (m, 1, k));
|
2179 |
+
# calculate needed nT(i, j) values
|
2180 |
+
p = [1]*d
|
2181 |
+
for i in range(2, k + 1):
|
2182 |
+
for m in range(i + 1, d):
|
2183 |
+
p[m] += p[m - i]
|
2184 |
+
d -= 1
|
2185 |
+
# if p[0] were appended to the end of p then the last
|
2186 |
+
# k values of p are the nT(n, j) values for 0 < j < k in reverse
|
2187 |
+
# order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of
|
2188 |
+
# putting the 1 from p[0] there, however, it is simply added to
|
2189 |
+
# the sum below which is valid for 1 < k <= n//2
|
2190 |
+
return (1 + sum(p[1 - k:]))
|
2191 |
+
|
2192 |
+
|
2193 |
+
def nT(n, k=None):
|
2194 |
+
"""Return the number of ``k``-sized partitions of ``n`` items.
|
2195 |
+
|
2196 |
+
Possible values for ``n``:
|
2197 |
+
|
2198 |
+
integer - ``n`` identical items
|
2199 |
+
|
2200 |
+
sequence - converted to a multiset internally
|
2201 |
+
|
2202 |
+
multiset - {element: multiplicity}
|
2203 |
+
|
2204 |
+
Note: the convention for ``nT`` is different than that of ``nC`` and
|
2205 |
+
``nP`` in that
|
2206 |
+
here an integer indicates ``n`` *identical* items instead of a set of
|
2207 |
+
length ``n``; this is in keeping with the ``partitions`` function which
|
2208 |
+
treats its integer-``n`` input like a list of ``n`` 1s. One can use
|
2209 |
+
``range(n)`` for ``n`` to indicate ``n`` distinct items.
|
2210 |
+
|
2211 |
+
If ``k`` is None then the total number of ways to partition the elements
|
2212 |
+
represented in ``n`` will be returned.
|
2213 |
+
|
2214 |
+
Examples
|
2215 |
+
========
|
2216 |
+
|
2217 |
+
>>> from sympy.functions.combinatorial.numbers import nT
|
2218 |
+
|
2219 |
+
Partitions of the given multiset:
|
2220 |
+
|
2221 |
+
>>> [nT('aabbc', i) for i in range(1, 7)]
|
2222 |
+
[1, 8, 11, 5, 1, 0]
|
2223 |
+
>>> nT('aabbc') == sum(_)
|
2224 |
+
True
|
2225 |
+
|
2226 |
+
>>> [nT("mississippi", i) for i in range(1, 12)]
|
2227 |
+
[1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]
|
2228 |
+
|
2229 |
+
Partitions when all items are identical:
|
2230 |
+
|
2231 |
+
>>> [nT(5, i) for i in range(1, 6)]
|
2232 |
+
[1, 2, 2, 1, 1]
|
2233 |
+
>>> nT('1'*5) == sum(_)
|
2234 |
+
True
|
2235 |
+
|
2236 |
+
When all items are different:
|
2237 |
+
|
2238 |
+
>>> [nT(range(5), i) for i in range(1, 6)]
|
2239 |
+
[1, 15, 25, 10, 1]
|
2240 |
+
>>> nT(range(5)) == sum(_)
|
2241 |
+
True
|
2242 |
+
|
2243 |
+
Partitions of an integer expressed as a sum of positive integers:
|
2244 |
+
|
2245 |
+
>>> from sympy import partition
|
2246 |
+
>>> partition(4)
|
2247 |
+
5
|
2248 |
+
>>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
|
2249 |
+
5
|
2250 |
+
>>> nT('1'*4)
|
2251 |
+
5
|
2252 |
+
|
2253 |
+
See Also
|
2254 |
+
========
|
2255 |
+
sympy.utilities.iterables.partitions
|
2256 |
+
sympy.utilities.iterables.multiset_partitions
|
2257 |
+
sympy.functions.combinatorial.numbers.partition
|
2258 |
+
|
2259 |
+
References
|
2260 |
+
==========
|
2261 |
+
|
2262 |
+
.. [1] https://web.archive.org/web/20210507012732/https://teaching.csse.uwa.edu.au/units/CITS7209/partition.pdf
|
2263 |
+
|
2264 |
+
"""
|
2265 |
+
|
2266 |
+
if isinstance(n, SYMPY_INTS):
|
2267 |
+
# n identical items
|
2268 |
+
if k is None:
|
2269 |
+
return partition(n)
|
2270 |
+
if isinstance(k, SYMPY_INTS):
|
2271 |
+
n = as_int(n)
|
2272 |
+
k = as_int(k)
|
2273 |
+
return Integer(_nT(n, k))
|
2274 |
+
if not isinstance(n, _MultisetHistogram):
|
2275 |
+
try:
|
2276 |
+
# if n contains hashable items there is some
|
2277 |
+
# quick handling that can be done
|
2278 |
+
u = len(set(n))
|
2279 |
+
if u <= 1:
|
2280 |
+
return nT(len(n), k)
|
2281 |
+
elif u == len(n):
|
2282 |
+
n = range(u)
|
2283 |
+
raise TypeError
|
2284 |
+
except TypeError:
|
2285 |
+
n = _multiset_histogram(n)
|
2286 |
+
N = n[_N]
|
2287 |
+
if k is None and N == 1:
|
2288 |
+
return 1
|
2289 |
+
if k in (1, N):
|
2290 |
+
return 1
|
2291 |
+
if k == 2 or N == 2 and k is None:
|
2292 |
+
m, r = divmod(N, 2)
|
2293 |
+
rv = sum(nC(n, i) for i in range(1, m + 1))
|
2294 |
+
if not r:
|
2295 |
+
rv -= nC(n, m)//2
|
2296 |
+
if k is None:
|
2297 |
+
rv += 1 # for k == 1
|
2298 |
+
return rv
|
2299 |
+
if N == n[_ITEMS]:
|
2300 |
+
# all distinct
|
2301 |
+
if k is None:
|
2302 |
+
return bell(N)
|
2303 |
+
return stirling(N, k)
|
2304 |
+
m = MultisetPartitionTraverser()
|
2305 |
+
if k is None:
|
2306 |
+
return m.count_partitions(n[_M])
|
2307 |
+
# MultisetPartitionTraverser does not have a range-limited count
|
2308 |
+
# method, so need to enumerate and count
|
2309 |
+
tot = 0
|
2310 |
+
for discard in m.enum_range(n[_M], k-1, k):
|
2311 |
+
tot += 1
|
2312 |
+
return tot
|
2313 |
+
|
2314 |
+
|
2315 |
+
#-----------------------------------------------------------------------------#
|
2316 |
+
# #
|
2317 |
+
# Motzkin numbers #
|
2318 |
+
# #
|
2319 |
+
#-----------------------------------------------------------------------------#
|
2320 |
+
|
2321 |
+
|
2322 |
+
class motzkin(Function):
|
2323 |
+
"""
|
2324 |
+
The nth Motzkin number is the number
|
2325 |
+
of ways of drawing non-intersecting chords
|
2326 |
+
between n points on a circle (not necessarily touching
|
2327 |
+
every point by a chord). The Motzkin numbers are named
|
2328 |
+
after Theodore Motzkin and have diverse applications
|
2329 |
+
in geometry, combinatorics and number theory.
|
2330 |
+
|
2331 |
+
Motzkin numbers are the integer sequence defined by the
|
2332 |
+
initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
|
2333 |
+
`M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`.
|
2334 |
+
|
2335 |
+
|
2336 |
+
Examples
|
2337 |
+
========
|
2338 |
+
|
2339 |
+
>>> from sympy import motzkin
|
2340 |
+
|
2341 |
+
>>> motzkin.is_motzkin(5)
|
2342 |
+
False
|
2343 |
+
>>> motzkin.find_motzkin_numbers_in_range(2,300)
|
2344 |
+
[2, 4, 9, 21, 51, 127]
|
2345 |
+
>>> motzkin.find_motzkin_numbers_in_range(2,900)
|
2346 |
+
[2, 4, 9, 21, 51, 127, 323, 835]
|
2347 |
+
>>> motzkin.find_first_n_motzkins(10)
|
2348 |
+
[1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
|
2349 |
+
|
2350 |
+
|
2351 |
+
References
|
2352 |
+
==========
|
2353 |
+
|
2354 |
+
.. [1] https://en.wikipedia.org/wiki/Motzkin_number
|
2355 |
+
.. [2] https://mathworld.wolfram.com/MotzkinNumber.html
|
2356 |
+
|
2357 |
+
"""
|
2358 |
+
|
2359 |
+
@staticmethod
|
2360 |
+
def is_motzkin(n):
|
2361 |
+
try:
|
2362 |
+
n = as_int(n)
|
2363 |
+
except ValueError:
|
2364 |
+
return False
|
2365 |
+
if n > 0:
|
2366 |
+
if n in (1, 2):
|
2367 |
+
return True
|
2368 |
+
|
2369 |
+
tn1 = 1
|
2370 |
+
tn = 2
|
2371 |
+
i = 3
|
2372 |
+
while tn < n:
|
2373 |
+
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
|
2374 |
+
i += 1
|
2375 |
+
tn1 = tn
|
2376 |
+
tn = a
|
2377 |
+
|
2378 |
+
if tn == n:
|
2379 |
+
return True
|
2380 |
+
else:
|
2381 |
+
return False
|
2382 |
+
|
2383 |
+
else:
|
2384 |
+
return False
|
2385 |
+
|
2386 |
+
@staticmethod
|
2387 |
+
def find_motzkin_numbers_in_range(x, y):
|
2388 |
+
if 0 <= x <= y:
|
2389 |
+
motzkins = []
|
2390 |
+
if x <= 1 <= y:
|
2391 |
+
motzkins.append(1)
|
2392 |
+
tn1 = 1
|
2393 |
+
tn = 2
|
2394 |
+
i = 3
|
2395 |
+
while tn <= y:
|
2396 |
+
if tn >= x:
|
2397 |
+
motzkins.append(tn)
|
2398 |
+
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
|
2399 |
+
i += 1
|
2400 |
+
tn1 = tn
|
2401 |
+
tn = int(a)
|
2402 |
+
|
2403 |
+
return motzkins
|
2404 |
+
|
2405 |
+
else:
|
2406 |
+
raise ValueError('The provided range is not valid. This condition should satisfy x <= y')
|
2407 |
+
|
2408 |
+
@staticmethod
|
2409 |
+
def find_first_n_motzkins(n):
|
2410 |
+
try:
|
2411 |
+
n = as_int(n)
|
2412 |
+
except ValueError:
|
2413 |
+
raise ValueError('The provided number must be a positive integer')
|
2414 |
+
if n < 0:
|
2415 |
+
raise ValueError('The provided number must be a positive integer')
|
2416 |
+
motzkins = [1]
|
2417 |
+
if n >= 1:
|
2418 |
+
motzkins.append(1)
|
2419 |
+
tn1 = 1
|
2420 |
+
tn = 2
|
2421 |
+
i = 3
|
2422 |
+
while i <= n:
|
2423 |
+
motzkins.append(tn)
|
2424 |
+
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
|
2425 |
+
i += 1
|
2426 |
+
tn1 = tn
|
2427 |
+
tn = int(a)
|
2428 |
+
|
2429 |
+
return motzkins
|
2430 |
+
|
2431 |
+
@staticmethod
|
2432 |
+
@recurrence_memo([S.One, S.One])
|
2433 |
+
def _motzkin(n, prev):
|
2434 |
+
return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2)
|
2435 |
+
|
2436 |
+
@classmethod
|
2437 |
+
def eval(cls, n):
|
2438 |
+
try:
|
2439 |
+
n = as_int(n)
|
2440 |
+
except ValueError:
|
2441 |
+
raise ValueError('The provided number must be a positive integer')
|
2442 |
+
if n < 0:
|
2443 |
+
raise ValueError('The provided number must be a positive integer')
|
2444 |
+
return Integer(cls._motzkin(n - 1))
|
2445 |
+
|
2446 |
+
|
2447 |
+
def nD(i=None, brute=None, *, n=None, m=None):
|
2448 |
+
"""return the number of derangements for: ``n`` unique items, ``i``
|
2449 |
+
items (as a sequence or multiset), or multiplicities, ``m`` given
|
2450 |
+
as a sequence or multiset.
|
2451 |
+
|
2452 |
+
Examples
|
2453 |
+
========
|
2454 |
+
|
2455 |
+
>>> from sympy.utilities.iterables import generate_derangements as enum
|
2456 |
+
>>> from sympy.functions.combinatorial.numbers import nD
|
2457 |
+
|
2458 |
+
A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``:
|
2459 |
+
|
2460 |
+
>>> set([''.join(i) for i in enum('abc')])
|
2461 |
+
{'bca', 'cab'}
|
2462 |
+
>>> nD('abc')
|
2463 |
+
2
|
2464 |
+
|
2465 |
+
Input as iterable or dictionary (multiset form) is accepted:
|
2466 |
+
|
2467 |
+
>>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3})
|
2468 |
+
|
2469 |
+
By default, a brute-force enumeration and count of multiset permutations
|
2470 |
+
is only done if there are fewer than 9 elements. There may be cases when
|
2471 |
+
there is high multiplicity with few unique elements that will benefit
|
2472 |
+
from a brute-force enumeration, too. For this reason, the `brute`
|
2473 |
+
keyword (default None) is provided. When False, the brute-force
|
2474 |
+
enumeration will never be used. When True, it will always be used.
|
2475 |
+
|
2476 |
+
>>> nD('1111222233', brute=True)
|
2477 |
+
44
|
2478 |
+
|
2479 |
+
For convenience, one may specify ``n`` distinct items using the
|
2480 |
+
``n`` keyword:
|
2481 |
+
|
2482 |
+
>>> assert nD(n=3) == nD('abc') == 2
|
2483 |
+
|
2484 |
+
Since the number of derangments depends on the multiplicity of the
|
2485 |
+
elements and not the elements themselves, it may be more convenient
|
2486 |
+
to give a list or multiset of multiplicities using keyword ``m``:
|
2487 |
+
|
2488 |
+
>>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2
|
2489 |
+
|
2490 |
+
"""
|
2491 |
+
from sympy.integrals.integrals import integrate
|
2492 |
+
from sympy.functions.special.polynomials import laguerre
|
2493 |
+
from sympy.abc import x
|
2494 |
+
def ok(x):
|
2495 |
+
if not isinstance(x, SYMPY_INTS):
|
2496 |
+
raise TypeError('expecting integer values')
|
2497 |
+
if x < 0:
|
2498 |
+
raise ValueError('value must not be negative')
|
2499 |
+
return True
|
2500 |
+
|
2501 |
+
if (i, n, m).count(None) != 2:
|
2502 |
+
raise ValueError('enter only 1 of i, n, or m')
|
2503 |
+
if i is not None:
|
2504 |
+
if isinstance(i, SYMPY_INTS):
|
2505 |
+
raise TypeError('items must be a list or dictionary')
|
2506 |
+
if not i:
|
2507 |
+
return S.Zero
|
2508 |
+
if type(i) is not dict:
|
2509 |
+
s = list(i)
|
2510 |
+
ms = multiset(s)
|
2511 |
+
elif type(i) is dict:
|
2512 |
+
all(ok(_) for _ in i.values())
|
2513 |
+
ms = {k: v for k, v in i.items() if v}
|
2514 |
+
s = None
|
2515 |
+
if not ms:
|
2516 |
+
return S.Zero
|
2517 |
+
N = sum(ms.values())
|
2518 |
+
counts = multiset(ms.values())
|
2519 |
+
nkey = len(ms)
|
2520 |
+
elif n is not None:
|
2521 |
+
ok(n)
|
2522 |
+
if not n:
|
2523 |
+
return S.Zero
|
2524 |
+
return subfactorial(n)
|
2525 |
+
elif m is not None:
|
2526 |
+
if isinstance(m, dict):
|
2527 |
+
all(ok(i) and ok(j) for i, j in m.items())
|
2528 |
+
counts = {k: v for k, v in m.items() if k*v}
|
2529 |
+
elif iterable(m) or isinstance(m, str):
|
2530 |
+
m = list(m)
|
2531 |
+
all(ok(i) for i in m)
|
2532 |
+
counts = multiset([i for i in m if i])
|
2533 |
+
else:
|
2534 |
+
raise TypeError('expecting iterable')
|
2535 |
+
if not counts:
|
2536 |
+
return S.Zero
|
2537 |
+
N = sum(k*v for k, v in counts.items())
|
2538 |
+
nkey = sum(counts.values())
|
2539 |
+
s = None
|
2540 |
+
big = int(max(counts))
|
2541 |
+
if big == 1: # no repetition
|
2542 |
+
return subfactorial(nkey)
|
2543 |
+
nval = len(counts)
|
2544 |
+
if big*2 > N:
|
2545 |
+
return S.Zero
|
2546 |
+
if big*2 == N:
|
2547 |
+
if nkey == 2 and nval == 1:
|
2548 |
+
return S.One # aaabbb
|
2549 |
+
if nkey - 1 == big: # one element repeated
|
2550 |
+
return factorial(big) # e.g. abc part of abcddd
|
2551 |
+
if N < 9 and brute is None or brute:
|
2552 |
+
# for all possibilities, this was found to be faster
|
2553 |
+
if s is None:
|
2554 |
+
s = []
|
2555 |
+
i = 0
|
2556 |
+
for m, v in counts.items():
|
2557 |
+
for j in range(v):
|
2558 |
+
s.extend([i]*m)
|
2559 |
+
i += 1
|
2560 |
+
return Integer(sum(1 for i in multiset_derangements(s)))
|
2561 |
+
from sympy.functions.elementary.exponential import exp
|
2562 |
+
return Integer(abs(integrate(exp(-x)*Mul(*[
|
2563 |
+
laguerre(i, x)**m for i, m in counts.items()]), (x, 0, oo))))
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (200 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc
ADDED
Binary file (22 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc
ADDED
Binary file (35.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_factorials.py
ADDED
@@ -0,0 +1,650 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.products import Product
|
2 |
+
from sympy.core.function import expand_func
|
3 |
+
from sympy.core.mod import Mod
|
4 |
+
from sympy.core.mul import Mul
|
5 |
+
from sympy.core import EulerGamma
|
6 |
+
from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
|
7 |
+
from sympy.core.relational import Eq
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import (Dummy, Symbol, symbols)
|
10 |
+
from sympy.functions.combinatorial.factorials import (ff, rf, binomial, factorial, factorial2)
|
11 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
12 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
13 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
14 |
+
from sympy.polys.polytools import Poly
|
15 |
+
from sympy.series.order import O
|
16 |
+
from sympy.simplify.simplify import simplify
|
17 |
+
from sympy.core.expr import unchanged
|
18 |
+
from sympy.core.function import ArgumentIndexError
|
19 |
+
from sympy.functions.combinatorial.factorials import subfactorial
|
20 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
21 |
+
from sympy.testing.pytest import XFAIL, raises, slow
|
22 |
+
|
23 |
+
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
|
24 |
+
|
25 |
+
def test_rf_eval_apply():
|
26 |
+
x, y = symbols('x,y')
|
27 |
+
n, k = symbols('n k', integer=True)
|
28 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
29 |
+
|
30 |
+
assert rf(nan, y) is nan
|
31 |
+
assert rf(x, nan) is nan
|
32 |
+
|
33 |
+
assert unchanged(rf, x, y)
|
34 |
+
|
35 |
+
assert rf(oo, 0) == 1
|
36 |
+
assert rf(-oo, 0) == 1
|
37 |
+
|
38 |
+
assert rf(oo, 6) is oo
|
39 |
+
assert rf(-oo, 7) is -oo
|
40 |
+
assert rf(-oo, 6) is oo
|
41 |
+
|
42 |
+
assert rf(oo, -6) is oo
|
43 |
+
assert rf(-oo, -7) is oo
|
44 |
+
|
45 |
+
assert rf(-1, pi) == 0
|
46 |
+
assert rf(-5, 1 + I) == 0
|
47 |
+
|
48 |
+
assert unchanged(rf, -3, k)
|
49 |
+
assert unchanged(rf, x, Symbol('k', integer=False))
|
50 |
+
assert rf(-3, Symbol('k', integer=False)) == 0
|
51 |
+
assert rf(Symbol('x', negative=True, integer=True), Symbol('k', integer=False)) == 0
|
52 |
+
|
53 |
+
assert rf(x, 0) == 1
|
54 |
+
assert rf(x, 1) == x
|
55 |
+
assert rf(x, 2) == x*(x + 1)
|
56 |
+
assert rf(x, 3) == x*(x + 1)*(x + 2)
|
57 |
+
assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4)
|
58 |
+
|
59 |
+
assert rf(x, -1) == 1/(x - 1)
|
60 |
+
assert rf(x, -2) == 1/((x - 1)*(x - 2))
|
61 |
+
assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3))
|
62 |
+
|
63 |
+
assert rf(1, 100) == factorial(100)
|
64 |
+
|
65 |
+
assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1)
|
66 |
+
assert isinstance(rf(x**2 + 3*x, 2), Mul)
|
67 |
+
assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2))
|
68 |
+
|
69 |
+
assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x)
|
70 |
+
assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly)
|
71 |
+
raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2))
|
72 |
+
assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20)
|
73 |
+
raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2))
|
74 |
+
|
75 |
+
assert rf(x, m).is_integer is None
|
76 |
+
assert rf(n, k).is_integer is None
|
77 |
+
assert rf(n, m).is_integer is True
|
78 |
+
assert rf(n, k + pi).is_integer is False
|
79 |
+
assert rf(n, m + pi).is_integer is False
|
80 |
+
assert rf(pi, m).is_integer is False
|
81 |
+
|
82 |
+
def check(x, k, o, n):
|
83 |
+
a, b = Dummy(), Dummy()
|
84 |
+
r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
|
85 |
+
for i in range(-5,5):
|
86 |
+
for j in range(-5,5):
|
87 |
+
assert o(i, j) == r(i, j), (o, n, i, j)
|
88 |
+
check(x, k, rf, ff)
|
89 |
+
check(x, k, rf, binomial)
|
90 |
+
check(n, k, rf, factorial)
|
91 |
+
check(x, y, rf, factorial)
|
92 |
+
check(x, y, rf, binomial)
|
93 |
+
|
94 |
+
assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
|
95 |
+
assert rf(x, k).rewrite(gamma) == Piecewise(
|
96 |
+
(gamma(k + x)/gamma(x), x > 0),
|
97 |
+
((-1)**k*gamma(1 - x)/gamma(-k - x + 1), True))
|
98 |
+
assert rf(5, k).rewrite(gamma) == gamma(k + 5)/24
|
99 |
+
assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k)
|
100 |
+
assert rf(n, k).rewrite(factorial) == Piecewise(
|
101 |
+
(factorial(k + n - 1)/factorial(n - 1), n > 0),
|
102 |
+
((-1)**k*factorial(-n)/factorial(-k - n), True))
|
103 |
+
assert rf(5, k).rewrite(factorial) == factorial(k + 4)/24
|
104 |
+
assert rf(x, y).rewrite(factorial) == rf(x, y)
|
105 |
+
assert rf(x, y).rewrite(binomial) == rf(x, y)
|
106 |
+
|
107 |
+
import random
|
108 |
+
from mpmath import rf as mpmath_rf
|
109 |
+
for i in range(100):
|
110 |
+
x = -500 + 500 * random.random()
|
111 |
+
k = -500 + 500 * random.random()
|
112 |
+
assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15))
|
113 |
+
|
114 |
+
|
115 |
+
def test_ff_eval_apply():
|
116 |
+
x, y = symbols('x,y')
|
117 |
+
n, k = symbols('n k', integer=True)
|
118 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
119 |
+
|
120 |
+
assert ff(nan, y) is nan
|
121 |
+
assert ff(x, nan) is nan
|
122 |
+
|
123 |
+
assert unchanged(ff, x, y)
|
124 |
+
|
125 |
+
assert ff(oo, 0) == 1
|
126 |
+
assert ff(-oo, 0) == 1
|
127 |
+
|
128 |
+
assert ff(oo, 6) is oo
|
129 |
+
assert ff(-oo, 7) is -oo
|
130 |
+
assert ff(-oo, 6) is oo
|
131 |
+
|
132 |
+
assert ff(oo, -6) is oo
|
133 |
+
assert ff(-oo, -7) is oo
|
134 |
+
|
135 |
+
assert ff(x, 0) == 1
|
136 |
+
assert ff(x, 1) == x
|
137 |
+
assert ff(x, 2) == x*(x - 1)
|
138 |
+
assert ff(x, 3) == x*(x - 1)*(x - 2)
|
139 |
+
assert ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
|
140 |
+
|
141 |
+
assert ff(x, -1) == 1/(x + 1)
|
142 |
+
assert ff(x, -2) == 1/((x + 1)*(x + 2))
|
143 |
+
assert ff(x, -3) == 1/((x + 1)*(x + 2)*(x + 3))
|
144 |
+
|
145 |
+
assert ff(100, 100) == factorial(100)
|
146 |
+
|
147 |
+
assert ff(2*x**2 - 5*x, 2) == (2*x**2 - 5*x)*(2*x**2 - 5*x - 1)
|
148 |
+
assert isinstance(ff(2*x**2 - 5*x, 2), Mul)
|
149 |
+
assert ff(x**2 + 3*x, -2) == 1/((x**2 + 3*x + 1)*(x**2 + 3*x + 2))
|
150 |
+
|
151 |
+
assert ff(Poly(2*x**2 - 5*x, x), 2) == Poly(4*x**4 - 28*x**3 + 59*x**2 - 35*x, x)
|
152 |
+
assert isinstance(ff(Poly(2*x**2 - 5*x, x), 2), Poly)
|
153 |
+
raises(ValueError, lambda: ff(Poly(2*x**2 - 5*x, x, y), 2))
|
154 |
+
assert ff(Poly(x**2 + 3*x, x), -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40)
|
155 |
+
raises(ValueError, lambda: ff(Poly(x**2 + 3*x, x, y), -2))
|
156 |
+
|
157 |
+
|
158 |
+
assert ff(x, m).is_integer is None
|
159 |
+
assert ff(n, k).is_integer is None
|
160 |
+
assert ff(n, m).is_integer is True
|
161 |
+
assert ff(n, k + pi).is_integer is False
|
162 |
+
assert ff(n, m + pi).is_integer is False
|
163 |
+
assert ff(pi, m).is_integer is False
|
164 |
+
|
165 |
+
assert isinstance(ff(x, x), ff)
|
166 |
+
assert ff(n, n) == factorial(n)
|
167 |
+
|
168 |
+
def check(x, k, o, n):
|
169 |
+
a, b = Dummy(), Dummy()
|
170 |
+
r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
|
171 |
+
for i in range(-5,5):
|
172 |
+
for j in range(-5,5):
|
173 |
+
assert o(i, j) == r(i, j), (o, n)
|
174 |
+
check(x, k, ff, rf)
|
175 |
+
check(x, k, ff, gamma)
|
176 |
+
check(n, k, ff, factorial)
|
177 |
+
check(x, k, ff, binomial)
|
178 |
+
check(x, y, ff, factorial)
|
179 |
+
check(x, y, ff, binomial)
|
180 |
+
|
181 |
+
assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
|
182 |
+
assert ff(x, k).rewrite(gamma) == Piecewise(
|
183 |
+
(gamma(x + 1)/gamma(-k + x + 1), x >= 0),
|
184 |
+
((-1)**k*gamma(k - x)/gamma(-x), True))
|
185 |
+
assert ff(5, k).rewrite(gamma) == 120/gamma(6 - k)
|
186 |
+
assert ff(n, k).rewrite(factorial) == Piecewise(
|
187 |
+
(factorial(n)/factorial(-k + n), n >= 0),
|
188 |
+
((-1)**k*factorial(k - n - 1)/factorial(-n - 1), True))
|
189 |
+
assert ff(5, k).rewrite(factorial) == 120/factorial(5 - k)
|
190 |
+
assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
|
191 |
+
assert ff(x, y).rewrite(factorial) == ff(x, y)
|
192 |
+
assert ff(x, y).rewrite(binomial) == ff(x, y)
|
193 |
+
|
194 |
+
import random
|
195 |
+
from mpmath import ff as mpmath_ff
|
196 |
+
for i in range(100):
|
197 |
+
x = -500 + 500 * random.random()
|
198 |
+
k = -500 + 500 * random.random()
|
199 |
+
a = mpmath_ff(x, k)
|
200 |
+
b = ff(x, k)
|
201 |
+
assert (abs(a - b) < abs(a) * 10**(-15))
|
202 |
+
|
203 |
+
|
204 |
+
def test_rf_ff_eval_hiprec():
|
205 |
+
maple = Float('6.9109401292234329956525265438452')
|
206 |
+
us = ff(18, Rational(2, 3)).evalf(32)
|
207 |
+
assert abs(us - maple)/us < 1e-31
|
208 |
+
|
209 |
+
maple = Float('6.8261540131125511557924466355367')
|
210 |
+
us = rf(18, Rational(2, 3)).evalf(32)
|
211 |
+
assert abs(us - maple)/us < 1e-31
|
212 |
+
|
213 |
+
maple = Float('34.007346127440197150854651814225')
|
214 |
+
us = rf(Float('4.4', 32), Float('2.2', 32));
|
215 |
+
assert abs(us - maple)/us < 1e-31
|
216 |
+
|
217 |
+
|
218 |
+
def test_rf_lambdify_mpmath():
|
219 |
+
from sympy.utilities.lambdify import lambdify
|
220 |
+
x, y = symbols('x,y')
|
221 |
+
f = lambdify((x,y), rf(x, y), 'mpmath')
|
222 |
+
maple = Float('34.007346127440197')
|
223 |
+
us = f(4.4, 2.2)
|
224 |
+
assert abs(us - maple)/us < 1e-15
|
225 |
+
|
226 |
+
|
227 |
+
def test_factorial():
|
228 |
+
x = Symbol('x')
|
229 |
+
n = Symbol('n', integer=True)
|
230 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
231 |
+
r = Symbol('r', integer=False)
|
232 |
+
s = Symbol('s', integer=False, negative=True)
|
233 |
+
t = Symbol('t', nonnegative=True)
|
234 |
+
u = Symbol('u', noninteger=True)
|
235 |
+
|
236 |
+
assert factorial(-2) is zoo
|
237 |
+
assert factorial(0) == 1
|
238 |
+
assert factorial(7) == 5040
|
239 |
+
assert factorial(19) == 121645100408832000
|
240 |
+
assert factorial(31) == 8222838654177922817725562880000000
|
241 |
+
assert factorial(n).func == factorial
|
242 |
+
assert factorial(2*n).func == factorial
|
243 |
+
|
244 |
+
assert factorial(x).is_integer is None
|
245 |
+
assert factorial(n).is_integer is None
|
246 |
+
assert factorial(k).is_integer
|
247 |
+
assert factorial(r).is_integer is None
|
248 |
+
|
249 |
+
assert factorial(n).is_positive is None
|
250 |
+
assert factorial(k).is_positive
|
251 |
+
|
252 |
+
assert factorial(x).is_real is None
|
253 |
+
assert factorial(n).is_real is None
|
254 |
+
assert factorial(k).is_real is True
|
255 |
+
assert factorial(r).is_real is None
|
256 |
+
assert factorial(s).is_real is True
|
257 |
+
assert factorial(t).is_real is True
|
258 |
+
assert factorial(u).is_real is True
|
259 |
+
|
260 |
+
assert factorial(x).is_composite is None
|
261 |
+
assert factorial(n).is_composite is None
|
262 |
+
assert factorial(k).is_composite is None
|
263 |
+
assert factorial(k + 3).is_composite is True
|
264 |
+
assert factorial(r).is_composite is None
|
265 |
+
assert factorial(s).is_composite is None
|
266 |
+
assert factorial(t).is_composite is None
|
267 |
+
assert factorial(u).is_composite is None
|
268 |
+
|
269 |
+
assert factorial(oo) is oo
|
270 |
+
|
271 |
+
|
272 |
+
def test_factorial_Mod():
|
273 |
+
pr = Symbol('pr', prime=True)
|
274 |
+
p, q = 10**9 + 9, 10**9 + 33 # prime modulo
|
275 |
+
r, s = 10**7 + 5, 33333333 # composite modulo
|
276 |
+
assert Mod(factorial(pr - 1), pr) == pr - 1
|
277 |
+
assert Mod(factorial(pr - 1), -pr) == -1
|
278 |
+
assert Mod(factorial(r - 1, evaluate=False), r) == 0
|
279 |
+
assert Mod(factorial(s - 1, evaluate=False), s) == 0
|
280 |
+
assert Mod(factorial(p - 1, evaluate=False), p) == p - 1
|
281 |
+
assert Mod(factorial(q - 1, evaluate=False), q) == q - 1
|
282 |
+
assert Mod(factorial(p - 50, evaluate=False), p) == 854928834
|
283 |
+
assert Mod(factorial(q - 1800, evaluate=False), q) == 905504050
|
284 |
+
assert Mod(factorial(153, evaluate=False), r) == Mod(factorial(153), r)
|
285 |
+
assert Mod(factorial(255, evaluate=False), s) == Mod(factorial(255), s)
|
286 |
+
assert Mod(factorial(4, evaluate=False), 3) == S.Zero
|
287 |
+
assert Mod(factorial(5, evaluate=False), 6) == S.Zero
|
288 |
+
|
289 |
+
|
290 |
+
def test_factorial_diff():
|
291 |
+
n = Symbol('n', integer=True)
|
292 |
+
|
293 |
+
assert factorial(n).diff(n) == \
|
294 |
+
gamma(1 + n)*polygamma(0, 1 + n)
|
295 |
+
assert factorial(n**2).diff(n) == \
|
296 |
+
2*n*gamma(1 + n**2)*polygamma(0, 1 + n**2)
|
297 |
+
raises(ArgumentIndexError, lambda: factorial(n**2).fdiff(2))
|
298 |
+
|
299 |
+
|
300 |
+
def test_factorial_series():
|
301 |
+
n = Symbol('n', integer=True)
|
302 |
+
|
303 |
+
assert factorial(n).series(n, 0, 3) == \
|
304 |
+
1 - n*EulerGamma + n**2*(EulerGamma**2/2 + pi**2/12) + O(n**3)
|
305 |
+
|
306 |
+
|
307 |
+
def test_factorial_rewrite():
|
308 |
+
n = Symbol('n', integer=True)
|
309 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
310 |
+
|
311 |
+
assert factorial(n).rewrite(gamma) == gamma(n + 1)
|
312 |
+
_i = Dummy('i')
|
313 |
+
assert factorial(k).rewrite(Product).dummy_eq(Product(_i, (_i, 1, k)))
|
314 |
+
assert factorial(n).rewrite(Product) == factorial(n)
|
315 |
+
|
316 |
+
|
317 |
+
def test_factorial2():
|
318 |
+
n = Symbol('n', integer=True)
|
319 |
+
|
320 |
+
assert factorial2(-1) == 1
|
321 |
+
assert factorial2(0) == 1
|
322 |
+
assert factorial2(7) == 105
|
323 |
+
assert factorial2(8) == 384
|
324 |
+
|
325 |
+
# The following is exhaustive
|
326 |
+
tt = Symbol('tt', integer=True, nonnegative=True)
|
327 |
+
tte = Symbol('tte', even=True, nonnegative=True)
|
328 |
+
tpe = Symbol('tpe', even=True, positive=True)
|
329 |
+
tto = Symbol('tto', odd=True, nonnegative=True)
|
330 |
+
tf = Symbol('tf', integer=True, nonnegative=False)
|
331 |
+
tfe = Symbol('tfe', even=True, nonnegative=False)
|
332 |
+
tfo = Symbol('tfo', odd=True, nonnegative=False)
|
333 |
+
ft = Symbol('ft', integer=False, nonnegative=True)
|
334 |
+
ff = Symbol('ff', integer=False, nonnegative=False)
|
335 |
+
fn = Symbol('fn', integer=False)
|
336 |
+
nt = Symbol('nt', nonnegative=True)
|
337 |
+
nf = Symbol('nf', nonnegative=False)
|
338 |
+
nn = Symbol('nn')
|
339 |
+
z = Symbol('z', zero=True)
|
340 |
+
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
|
341 |
+
raises(ValueError, lambda: factorial2(oo))
|
342 |
+
raises(ValueError, lambda: factorial2(Rational(5, 2)))
|
343 |
+
raises(ValueError, lambda: factorial2(-4))
|
344 |
+
assert factorial2(n).is_integer is None
|
345 |
+
assert factorial2(tt - 1).is_integer
|
346 |
+
assert factorial2(tte - 1).is_integer
|
347 |
+
assert factorial2(tpe - 3).is_integer
|
348 |
+
assert factorial2(tto - 4).is_integer
|
349 |
+
assert factorial2(tto - 2).is_integer
|
350 |
+
assert factorial2(tf).is_integer is None
|
351 |
+
assert factorial2(tfe).is_integer is None
|
352 |
+
assert factorial2(tfo).is_integer is None
|
353 |
+
assert factorial2(ft).is_integer is None
|
354 |
+
assert factorial2(ff).is_integer is None
|
355 |
+
assert factorial2(fn).is_integer is None
|
356 |
+
assert factorial2(nt).is_integer is None
|
357 |
+
assert factorial2(nf).is_integer is None
|
358 |
+
assert factorial2(nn).is_integer is None
|
359 |
+
|
360 |
+
assert factorial2(n).is_positive is None
|
361 |
+
assert factorial2(tt - 1).is_positive is True
|
362 |
+
assert factorial2(tte - 1).is_positive is True
|
363 |
+
assert factorial2(tpe - 3).is_positive is True
|
364 |
+
assert factorial2(tpe - 1).is_positive is True
|
365 |
+
assert factorial2(tto - 2).is_positive is True
|
366 |
+
assert factorial2(tto - 1).is_positive is True
|
367 |
+
assert factorial2(tf).is_positive is None
|
368 |
+
assert factorial2(tfe).is_positive is None
|
369 |
+
assert factorial2(tfo).is_positive is None
|
370 |
+
assert factorial2(ft).is_positive is None
|
371 |
+
assert factorial2(ff).is_positive is None
|
372 |
+
assert factorial2(fn).is_positive is None
|
373 |
+
assert factorial2(nt).is_positive is None
|
374 |
+
assert factorial2(nf).is_positive is None
|
375 |
+
assert factorial2(nn).is_positive is None
|
376 |
+
|
377 |
+
assert factorial2(tt).is_even is None
|
378 |
+
assert factorial2(tt).is_odd is None
|
379 |
+
assert factorial2(tte).is_even is None
|
380 |
+
assert factorial2(tte).is_odd is None
|
381 |
+
assert factorial2(tte + 2).is_even is True
|
382 |
+
assert factorial2(tpe).is_even is True
|
383 |
+
assert factorial2(tpe).is_odd is False
|
384 |
+
assert factorial2(tto).is_odd is True
|
385 |
+
assert factorial2(tf).is_even is None
|
386 |
+
assert factorial2(tf).is_odd is None
|
387 |
+
assert factorial2(tfe).is_even is None
|
388 |
+
assert factorial2(tfe).is_odd is None
|
389 |
+
assert factorial2(tfo).is_even is False
|
390 |
+
assert factorial2(tfo).is_odd is None
|
391 |
+
assert factorial2(z).is_even is False
|
392 |
+
assert factorial2(z).is_odd is True
|
393 |
+
|
394 |
+
|
395 |
+
def test_factorial2_rewrite():
|
396 |
+
n = Symbol('n', integer=True)
|
397 |
+
assert factorial2(n).rewrite(gamma) == \
|
398 |
+
2**(n/2)*Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2)/sqrt(pi), Eq(Mod(n, 2), 1)))*gamma(n/2 + 1)
|
399 |
+
assert factorial2(2*n).rewrite(gamma) == 2**n*gamma(n + 1)
|
400 |
+
assert factorial2(2*n + 1).rewrite(gamma) == \
|
401 |
+
sqrt(2)*2**(n + S.Half)*gamma(n + Rational(3, 2))/sqrt(pi)
|
402 |
+
|
403 |
+
|
404 |
+
def test_binomial():
|
405 |
+
x = Symbol('x')
|
406 |
+
n = Symbol('n', integer=True)
|
407 |
+
nz = Symbol('nz', integer=True, nonzero=True)
|
408 |
+
k = Symbol('k', integer=True)
|
409 |
+
kp = Symbol('kp', integer=True, positive=True)
|
410 |
+
kn = Symbol('kn', integer=True, negative=True)
|
411 |
+
u = Symbol('u', negative=True)
|
412 |
+
v = Symbol('v', nonnegative=True)
|
413 |
+
p = Symbol('p', positive=True)
|
414 |
+
z = Symbol('z', zero=True)
|
415 |
+
nt = Symbol('nt', integer=False)
|
416 |
+
kt = Symbol('kt', integer=False)
|
417 |
+
a = Symbol('a', integer=True, nonnegative=True)
|
418 |
+
b = Symbol('b', integer=True, nonnegative=True)
|
419 |
+
|
420 |
+
assert binomial(0, 0) == 1
|
421 |
+
assert binomial(1, 1) == 1
|
422 |
+
assert binomial(10, 10) == 1
|
423 |
+
assert binomial(n, z) == 1
|
424 |
+
assert binomial(1, 2) == 0
|
425 |
+
assert binomial(-1, 2) == 1
|
426 |
+
assert binomial(1, -1) == 0
|
427 |
+
assert binomial(-1, 1) == -1
|
428 |
+
assert binomial(-1, -1) == 0
|
429 |
+
assert binomial(S.Half, S.Half) == 1
|
430 |
+
assert binomial(-10, 1) == -10
|
431 |
+
assert binomial(-10, 7) == -11440
|
432 |
+
assert binomial(n, -1) == 0 # holds for all integers (negative, zero, positive)
|
433 |
+
assert binomial(kp, -1) == 0
|
434 |
+
assert binomial(nz, 0) == 1
|
435 |
+
assert expand_func(binomial(n, 1)) == n
|
436 |
+
assert expand_func(binomial(n, 2)) == n*(n - 1)/2
|
437 |
+
assert expand_func(binomial(n, n - 2)) == n*(n - 1)/2
|
438 |
+
assert expand_func(binomial(n, n - 1)) == n
|
439 |
+
assert binomial(n, 3).func == binomial
|
440 |
+
assert binomial(n, 3).expand(func=True) == n**3/6 - n**2/2 + n/3
|
441 |
+
assert expand_func(binomial(n, 3)) == n*(n - 2)*(n - 1)/6
|
442 |
+
assert binomial(n, n).func == binomial # e.g. (-1, -1) == 0, (2, 2) == 1
|
443 |
+
assert binomial(n, n + 1).func == binomial # e.g. (-1, 0) == 1
|
444 |
+
assert binomial(kp, kp + 1) == 0
|
445 |
+
assert binomial(kn, kn) == 0 # issue #14529
|
446 |
+
assert binomial(n, u).func == binomial
|
447 |
+
assert binomial(kp, u).func == binomial
|
448 |
+
assert binomial(n, p).func == binomial
|
449 |
+
assert binomial(n, k).func == binomial
|
450 |
+
assert binomial(n, n + p).func == binomial
|
451 |
+
assert binomial(kp, kp + p).func == binomial
|
452 |
+
|
453 |
+
assert expand_func(binomial(n, n - 3)) == n*(n - 2)*(n - 1)/6
|
454 |
+
|
455 |
+
assert binomial(n, k).is_integer
|
456 |
+
assert binomial(nt, k).is_integer is None
|
457 |
+
assert binomial(x, nt).is_integer is False
|
458 |
+
|
459 |
+
assert binomial(gamma(25), 6) == 79232165267303928292058750056084441948572511312165380965440075720159859792344339983120618959044048198214221915637090855535036339620413440000
|
460 |
+
assert binomial(1324, 47) == 906266255662694632984994480774946083064699457235920708992926525848438478406790323869952
|
461 |
+
assert binomial(1735, 43) == 190910140420204130794758005450919715396159959034348676124678207874195064798202216379800
|
462 |
+
assert binomial(2512, 53) == 213894469313832631145798303740098720367984955243020898718979538096223399813295457822575338958939834177325304000
|
463 |
+
assert binomial(3383, 52) == 27922807788818096863529701501764372757272890613101645521813434902890007725667814813832027795881839396839287659777235
|
464 |
+
assert binomial(4321, 51) == 124595639629264868916081001263541480185227731958274383287107643816863897851139048158022599533438936036467601690983780576
|
465 |
+
|
466 |
+
assert binomial(a, b).is_nonnegative is True
|
467 |
+
assert binomial(-1, 2, evaluate=False).is_nonnegative is True
|
468 |
+
assert binomial(10, 5, evaluate=False).is_nonnegative is True
|
469 |
+
assert binomial(10, -3, evaluate=False).is_nonnegative is True
|
470 |
+
assert binomial(-10, -3, evaluate=False).is_nonnegative is True
|
471 |
+
assert binomial(-10, 2, evaluate=False).is_nonnegative is True
|
472 |
+
assert binomial(-10, 1, evaluate=False).is_nonnegative is False
|
473 |
+
assert binomial(-10, 7, evaluate=False).is_nonnegative is False
|
474 |
+
|
475 |
+
# issue #14625
|
476 |
+
for _ in (pi, -pi, nt, v, a):
|
477 |
+
assert binomial(_, _) == 1
|
478 |
+
assert binomial(_, _ - 1) == _
|
479 |
+
assert isinstance(binomial(u, u), binomial)
|
480 |
+
assert isinstance(binomial(u, u - 1), binomial)
|
481 |
+
assert isinstance(binomial(x, x), binomial)
|
482 |
+
assert isinstance(binomial(x, x - 1), binomial)
|
483 |
+
|
484 |
+
#issue #18802
|
485 |
+
assert expand_func(binomial(x + 1, x)) == x + 1
|
486 |
+
assert expand_func(binomial(x, x - 1)) == x
|
487 |
+
assert expand_func(binomial(x + 1, x - 1)) == x*(x + 1)/2
|
488 |
+
assert expand_func(binomial(x**2 + 1, x**2)) == x**2 + 1
|
489 |
+
|
490 |
+
# issue #13980 and #13981
|
491 |
+
assert binomial(-7, -5) == 0
|
492 |
+
assert binomial(-23, -12) == 0
|
493 |
+
assert binomial(Rational(13, 2), -10) == 0
|
494 |
+
assert binomial(-49, -51) == 0
|
495 |
+
|
496 |
+
assert binomial(19, Rational(-7, 2)) == S(-68719476736)/(911337863661225*pi)
|
497 |
+
assert binomial(0, Rational(3, 2)) == S(-2)/(3*pi)
|
498 |
+
assert binomial(-3, Rational(-7, 2)) is zoo
|
499 |
+
assert binomial(kn, kt) is zoo
|
500 |
+
|
501 |
+
assert binomial(nt, kt).func == binomial
|
502 |
+
assert binomial(nt, Rational(15, 6)) == 8*gamma(nt + 1)/(15*sqrt(pi)*gamma(nt - Rational(3, 2)))
|
503 |
+
assert binomial(Rational(20, 3), Rational(-10, 8)) == gamma(Rational(23, 3))/(gamma(Rational(-1, 4))*gamma(Rational(107, 12)))
|
504 |
+
assert binomial(Rational(19, 2), Rational(-7, 2)) == Rational(-1615, 8388608)
|
505 |
+
assert binomial(Rational(-13, 5), Rational(-7, 8)) == gamma(Rational(-8, 5))/(gamma(Rational(-29, 40))*gamma(Rational(1, 8)))
|
506 |
+
assert binomial(Rational(-19, 8), Rational(-13, 5)) == gamma(Rational(-11, 8))/(gamma(Rational(-8, 5))*gamma(Rational(49, 40)))
|
507 |
+
|
508 |
+
# binomial for complexes
|
509 |
+
assert binomial(I, Rational(-89, 8)) == gamma(1 + I)/(gamma(Rational(-81, 8))*gamma(Rational(97, 8) + I))
|
510 |
+
assert binomial(I, 2*I) == gamma(1 + I)/(gamma(1 - I)*gamma(1 + 2*I))
|
511 |
+
assert binomial(-7, I) is zoo
|
512 |
+
assert binomial(Rational(-7, 6), I) == gamma(Rational(-1, 6))/(gamma(Rational(-1, 6) - I)*gamma(1 + I))
|
513 |
+
assert binomial((1+2*I), (1+3*I)) == gamma(2 + 2*I)/(gamma(1 - I)*gamma(2 + 3*I))
|
514 |
+
assert binomial(I, 5) == Rational(1, 3) - I/S(12)
|
515 |
+
assert binomial((2*I + 3), 7) == -13*I/S(63)
|
516 |
+
assert isinstance(binomial(I, n), binomial)
|
517 |
+
assert expand_func(binomial(3, 2, evaluate=False)) == 3
|
518 |
+
assert expand_func(binomial(n, 0, evaluate=False)) == 1
|
519 |
+
assert expand_func(binomial(n, -2, evaluate=False)) == 0
|
520 |
+
assert expand_func(binomial(n, k)) == binomial(n, k)
|
521 |
+
|
522 |
+
|
523 |
+
def test_binomial_Mod():
|
524 |
+
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
|
525 |
+
r = 10**7 + 5 # composite modulo
|
526 |
+
|
527 |
+
# A few tests to get coverage
|
528 |
+
# Lucas Theorem
|
529 |
+
assert Mod(binomial(156675, 4433, evaluate=False), p) == Mod(binomial(156675, 4433), p)
|
530 |
+
|
531 |
+
# factorial Mod
|
532 |
+
assert Mod(binomial(1234, 432, evaluate=False), q) == Mod(binomial(1234, 432), q)
|
533 |
+
|
534 |
+
# binomial factorize
|
535 |
+
assert Mod(binomial(253, 113, evaluate=False), r) == Mod(binomial(253, 113), r)
|
536 |
+
|
537 |
+
|
538 |
+
@slow
|
539 |
+
def test_binomial_Mod_slow():
|
540 |
+
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
|
541 |
+
r, s = 10**7 + 5, 33333333 # composite modulo
|
542 |
+
|
543 |
+
n, k, m = symbols('n k m')
|
544 |
+
assert (binomial(n, k) % q).subs({n: s, k: p}) == Mod(binomial(s, p), q)
|
545 |
+
assert (binomial(n, k) % m).subs({n: 8, k: 5, m: 13}) == 4
|
546 |
+
assert (binomial(9, k) % 7).subs(k, 2) == 1
|
547 |
+
|
548 |
+
# Lucas Theorem
|
549 |
+
assert Mod(binomial(123456, 43253, evaluate=False), p) == Mod(binomial(123456, 43253), p)
|
550 |
+
assert Mod(binomial(-178911, 237, evaluate=False), p) == Mod(-binomial(178911 + 237 - 1, 237), p)
|
551 |
+
assert Mod(binomial(-178911, 238, evaluate=False), p) == Mod(binomial(178911 + 238 - 1, 238), p)
|
552 |
+
|
553 |
+
# factorial Mod
|
554 |
+
assert Mod(binomial(9734, 451, evaluate=False), q) == Mod(binomial(9734, 451), q)
|
555 |
+
assert Mod(binomial(-10733, 4459, evaluate=False), q) == Mod(binomial(-10733, 4459), q)
|
556 |
+
assert Mod(binomial(-15733, 4458, evaluate=False), q) == Mod(binomial(-15733, 4458), q)
|
557 |
+
assert Mod(binomial(23, -38, evaluate=False), q) is S.Zero
|
558 |
+
assert Mod(binomial(23, 38, evaluate=False), q) is S.Zero
|
559 |
+
|
560 |
+
# binomial factorize
|
561 |
+
assert Mod(binomial(753, 119, evaluate=False), r) == Mod(binomial(753, 119), r)
|
562 |
+
assert Mod(binomial(3781, 948, evaluate=False), s) == Mod(binomial(3781, 948), s)
|
563 |
+
assert Mod(binomial(25773, 1793, evaluate=False), s) == Mod(binomial(25773, 1793), s)
|
564 |
+
assert Mod(binomial(-753, 118, evaluate=False), r) == Mod(binomial(-753, 118), r)
|
565 |
+
assert Mod(binomial(-25773, 1793, evaluate=False), s) == Mod(binomial(-25773, 1793), s)
|
566 |
+
|
567 |
+
|
568 |
+
def test_binomial_diff():
|
569 |
+
n = Symbol('n', integer=True)
|
570 |
+
k = Symbol('k', integer=True)
|
571 |
+
|
572 |
+
assert binomial(n, k).diff(n) == \
|
573 |
+
(-polygamma(0, 1 + n - k) + polygamma(0, 1 + n))*binomial(n, k)
|
574 |
+
assert binomial(n**2, k**3).diff(n) == \
|
575 |
+
2*n*(-polygamma(
|
576 |
+
0, 1 + n**2 - k**3) + polygamma(0, 1 + n**2))*binomial(n**2, k**3)
|
577 |
+
|
578 |
+
assert binomial(n, k).diff(k) == \
|
579 |
+
(-polygamma(0, 1 + k) + polygamma(0, 1 + n - k))*binomial(n, k)
|
580 |
+
assert binomial(n**2, k**3).diff(k) == \
|
581 |
+
3*k**2*(-polygamma(
|
582 |
+
0, 1 + k**3) + polygamma(0, 1 + n**2 - k**3))*binomial(n**2, k**3)
|
583 |
+
raises(ArgumentIndexError, lambda: binomial(n, k).fdiff(3))
|
584 |
+
|
585 |
+
|
586 |
+
def test_binomial_rewrite():
|
587 |
+
n = Symbol('n', integer=True)
|
588 |
+
k = Symbol('k', integer=True)
|
589 |
+
x = Symbol('x')
|
590 |
+
|
591 |
+
assert binomial(n, k).rewrite(
|
592 |
+
factorial) == factorial(n)/(factorial(k)*factorial(n - k))
|
593 |
+
assert binomial(
|
594 |
+
n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
595 |
+
assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
|
596 |
+
assert binomial(n, x).rewrite(ff) == binomial(n, x)
|
597 |
+
|
598 |
+
|
599 |
+
@XFAIL
|
600 |
+
def test_factorial_simplify_fail():
|
601 |
+
# simplify(factorial(x + 1).diff(x) - ((x + 1)*factorial(x)).diff(x))) == 0
|
602 |
+
from sympy.abc import x
|
603 |
+
assert simplify(x*polygamma(0, x + 1) - x*polygamma(0, x + 2) +
|
604 |
+
polygamma(0, x + 1) - polygamma(0, x + 2) + 1) == 0
|
605 |
+
|
606 |
+
|
607 |
+
def test_subfactorial():
|
608 |
+
assert all(subfactorial(i) == ans for i, ans in enumerate(
|
609 |
+
[1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496]))
|
610 |
+
assert subfactorial(oo) is oo
|
611 |
+
assert subfactorial(nan) is nan
|
612 |
+
assert subfactorial(23) == 9510425471055777937262
|
613 |
+
assert unchanged(subfactorial, 2.2)
|
614 |
+
|
615 |
+
x = Symbol('x')
|
616 |
+
assert subfactorial(x).rewrite(uppergamma) == uppergamma(x + 1, -1)/S.Exp1
|
617 |
+
|
618 |
+
tt = Symbol('tt', integer=True, nonnegative=True)
|
619 |
+
tf = Symbol('tf', integer=True, nonnegative=False)
|
620 |
+
tn = Symbol('tf', integer=True)
|
621 |
+
ft = Symbol('ft', integer=False, nonnegative=True)
|
622 |
+
ff = Symbol('ff', integer=False, nonnegative=False)
|
623 |
+
fn = Symbol('ff', integer=False)
|
624 |
+
nt = Symbol('nt', nonnegative=True)
|
625 |
+
nf = Symbol('nf', nonnegative=False)
|
626 |
+
nn = Symbol('nf')
|
627 |
+
te = Symbol('te', even=True, nonnegative=True)
|
628 |
+
to = Symbol('to', odd=True, nonnegative=True)
|
629 |
+
assert subfactorial(tt).is_integer
|
630 |
+
assert subfactorial(tf).is_integer is None
|
631 |
+
assert subfactorial(tn).is_integer is None
|
632 |
+
assert subfactorial(ft).is_integer is None
|
633 |
+
assert subfactorial(ff).is_integer is None
|
634 |
+
assert subfactorial(fn).is_integer is None
|
635 |
+
assert subfactorial(nt).is_integer is None
|
636 |
+
assert subfactorial(nf).is_integer is None
|
637 |
+
assert subfactorial(nn).is_integer is None
|
638 |
+
assert subfactorial(tt).is_nonnegative
|
639 |
+
assert subfactorial(tf).is_nonnegative is None
|
640 |
+
assert subfactorial(tn).is_nonnegative is None
|
641 |
+
assert subfactorial(ft).is_nonnegative is None
|
642 |
+
assert subfactorial(ff).is_nonnegative is None
|
643 |
+
assert subfactorial(fn).is_nonnegative is None
|
644 |
+
assert subfactorial(nt).is_nonnegative is None
|
645 |
+
assert subfactorial(nf).is_nonnegative is None
|
646 |
+
assert subfactorial(nn).is_nonnegative is None
|
647 |
+
assert subfactorial(tt).is_even is None
|
648 |
+
assert subfactorial(tt).is_odd is None
|
649 |
+
assert subfactorial(te).is_odd is True
|
650 |
+
assert subfactorial(to).is_even is True
|
env-llmeval/lib/python3.10/site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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import string
|
2 |
+
|
3 |
+
from sympy.concrete.products import Product
|
4 |
+
from sympy.concrete.summations import Sum
|
5 |
+
from sympy.core.function import (diff, expand_func)
|
6 |
+
from sympy.core import (EulerGamma, TribonacciConstant)
|
7 |
+
from sympy.core.numbers import (Float, I, Rational, oo, pi)
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import (Dummy, Symbol, symbols)
|
10 |
+
from sympy.functions.combinatorial.numbers import carmichael
|
11 |
+
from sympy.functions.elementary.complexes import (im, re)
|
12 |
+
from sympy.functions.elementary.integers import floor
|
13 |
+
from sympy.polys.polytools import cancel
|
14 |
+
from sympy.series.limits import limit, Limit
|
15 |
+
from sympy.series.order import O
|
16 |
+
from sympy.functions import (
|
17 |
+
bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan,
|
18 |
+
genocchi, andre, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma,
|
19 |
+
trigamma, polygamma, factorial, sin, cos, cot, polylog, zeta, dirichlet_eta)
|
20 |
+
from sympy.functions.combinatorial.numbers import _nT
|
21 |
+
|
22 |
+
from sympy.core.expr import unchanged
|
23 |
+
from sympy.core.numbers import GoldenRatio, Integer
|
24 |
+
|
25 |
+
from sympy.testing.pytest import raises, nocache_fail, warns_deprecated_sympy
|
26 |
+
from sympy.abc import x
|
27 |
+
|
28 |
+
|
29 |
+
def test_carmichael():
|
30 |
+
assert carmichael.find_carmichael_numbers_in_range(0, 561) == []
|
31 |
+
assert carmichael.find_carmichael_numbers_in_range(561, 562) == [561]
|
32 |
+
assert carmichael.find_carmichael_numbers_in_range(561, 1105) == carmichael.find_carmichael_numbers_in_range(561,
|
33 |
+
562)
|
34 |
+
assert carmichael.find_first_n_carmichaels(5) == [561, 1105, 1729, 2465, 2821]
|
35 |
+
raises(ValueError, lambda: carmichael.is_carmichael(-2))
|
36 |
+
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(-2, 2))
|
37 |
+
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(22, 2))
|
38 |
+
with warns_deprecated_sympy():
|
39 |
+
assert carmichael.is_prime(2821) == False
|
40 |
+
|
41 |
+
|
42 |
+
def test_bernoulli():
|
43 |
+
assert bernoulli(0) == 1
|
44 |
+
assert bernoulli(1) == Rational(1, 2)
|
45 |
+
assert bernoulli(2) == Rational(1, 6)
|
46 |
+
assert bernoulli(3) == 0
|
47 |
+
assert bernoulli(4) == Rational(-1, 30)
|
48 |
+
assert bernoulli(5) == 0
|
49 |
+
assert bernoulli(6) == Rational(1, 42)
|
50 |
+
assert bernoulli(7) == 0
|
51 |
+
assert bernoulli(8) == Rational(-1, 30)
|
52 |
+
assert bernoulli(10) == Rational(5, 66)
|
53 |
+
assert bernoulli(1000001) == 0
|
54 |
+
|
55 |
+
assert bernoulli(0, x) == 1
|
56 |
+
assert bernoulli(1, x) == x - S.Half
|
57 |
+
assert bernoulli(2, x) == x**2 - x + Rational(1, 6)
|
58 |
+
assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2
|
59 |
+
|
60 |
+
# Should be fast; computed with mpmath
|
61 |
+
b = bernoulli(1000)
|
62 |
+
assert b.p % 10**10 == 7950421099
|
63 |
+
assert b.q == 342999030
|
64 |
+
|
65 |
+
b = bernoulli(10**6, evaluate=False).evalf()
|
66 |
+
assert str(b) == '-2.23799235765713e+4767529'
|
67 |
+
|
68 |
+
# Issue #8527
|
69 |
+
l = Symbol('l', integer=True)
|
70 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
71 |
+
n = Symbol('n', integer=True, positive=True)
|
72 |
+
assert isinstance(bernoulli(2 * l + 1), bernoulli)
|
73 |
+
assert isinstance(bernoulli(2 * m + 1), bernoulli)
|
74 |
+
assert bernoulli(2 * n + 1) == 0
|
75 |
+
|
76 |
+
assert bernoulli(x, 1) == bernoulli(x)
|
77 |
+
|
78 |
+
assert str(bernoulli(0.0, 2.3).evalf(n=10)) == '1.000000000'
|
79 |
+
assert str(bernoulli(1.0).evalf(n=10)) == '0.5000000000'
|
80 |
+
assert str(bernoulli(1.2).evalf(n=10)) == '0.4195995367'
|
81 |
+
assert str(bernoulli(1.2, 0.8).evalf(n=10)) == '0.2144830348'
|
82 |
+
assert str(bernoulli(1.2, -0.8).evalf(n=10)) == '-1.158865646 - 0.6745558744*I'
|
83 |
+
assert str(bernoulli(3.0, 1j).evalf(n=10)) == '1.5 - 0.5*I'
|
84 |
+
assert str(bernoulli(I).evalf(n=10)) == '0.9268485643 - 0.5821580598*I'
|
85 |
+
assert str(bernoulli(I, I).evalf(n=10)) == '0.1267792071 + 0.01947413152*I'
|
86 |
+
assert bernoulli(x).evalf() == bernoulli(x)
|
87 |
+
|
88 |
+
|
89 |
+
def test_bernoulli_rewrite():
|
90 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
91 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
92 |
+
|
93 |
+
assert bernoulli(-1).rewrite(zeta) == pi**2/6
|
94 |
+
assert bernoulli(-2).rewrite(zeta) == 2*zeta(3)
|
95 |
+
assert not bernoulli(n, -3).rewrite(zeta).has(harmonic)
|
96 |
+
assert bernoulli(-4, x).rewrite(zeta) == 4*zeta(5, x)
|
97 |
+
assert isinstance(bernoulli(n, x).rewrite(zeta), Piecewise)
|
98 |
+
assert bernoulli(n+1, x).rewrite(zeta) == -(n+1) * zeta(-n, x)
|
99 |
+
|
100 |
+
|
101 |
+
def test_fibonacci():
|
102 |
+
assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3]
|
103 |
+
assert fibonacci(100) == 354224848179261915075
|
104 |
+
assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7]
|
105 |
+
assert lucas(100) == 792070839848372253127
|
106 |
+
|
107 |
+
assert fibonacci(1, x) == 1
|
108 |
+
assert fibonacci(2, x) == x
|
109 |
+
assert fibonacci(3, x) == x**2 + 1
|
110 |
+
assert fibonacci(4, x) == x**3 + 2*x
|
111 |
+
|
112 |
+
# issue #8800
|
113 |
+
n = Dummy('n')
|
114 |
+
assert fibonacci(n).limit(n, S.Infinity) is S.Infinity
|
115 |
+
assert lucas(n).limit(n, S.Infinity) is S.Infinity
|
116 |
+
|
117 |
+
assert fibonacci(n).rewrite(sqrt) == \
|
118 |
+
2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
|
119 |
+
assert fibonacci(n).rewrite(sqrt).subs(n, 10).expand() == fibonacci(10)
|
120 |
+
assert fibonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
|
121 |
+
Float(fibonacci(10))
|
122 |
+
assert lucas(n).rewrite(sqrt) == \
|
123 |
+
(fibonacci(n-1).rewrite(sqrt) + fibonacci(n+1).rewrite(sqrt)).simplify()
|
124 |
+
assert lucas(n).rewrite(sqrt).subs(n, 10).expand() == lucas(10)
|
125 |
+
raises(ValueError, lambda: fibonacci(-3, x))
|
126 |
+
|
127 |
+
|
128 |
+
def test_tribonacci():
|
129 |
+
assert [tribonacci(n) for n in range(8)] == [0, 1, 1, 2, 4, 7, 13, 24]
|
130 |
+
assert tribonacci(100) == 98079530178586034536500564
|
131 |
+
|
132 |
+
assert tribonacci(0, x) == 0
|
133 |
+
assert tribonacci(1, x) == 1
|
134 |
+
assert tribonacci(2, x) == x**2
|
135 |
+
assert tribonacci(3, x) == x**4 + x
|
136 |
+
assert tribonacci(4, x) == x**6 + 2*x**3 + 1
|
137 |
+
assert tribonacci(5, x) == x**8 + 3*x**5 + 3*x**2
|
138 |
+
|
139 |
+
n = Dummy('n')
|
140 |
+
assert tribonacci(n).limit(n, S.Infinity) is S.Infinity
|
141 |
+
|
142 |
+
w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
|
143 |
+
a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
|
144 |
+
b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
|
145 |
+
c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
|
146 |
+
assert tribonacci(n).rewrite(sqrt) == \
|
147 |
+
(a**(n + 1)/((a - b)*(a - c))
|
148 |
+
+ b**(n + 1)/((b - a)*(b - c))
|
149 |
+
+ c**(n + 1)/((c - a)*(c - b)))
|
150 |
+
assert tribonacci(n).rewrite(sqrt).subs(n, 4).simplify() == tribonacci(4)
|
151 |
+
assert tribonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
|
152 |
+
Float(tribonacci(10))
|
153 |
+
assert tribonacci(n).rewrite(TribonacciConstant) == floor(
|
154 |
+
3*TribonacciConstant**n*(102*sqrt(33) + 586)**Rational(1, 3)/
|
155 |
+
(-2*(102*sqrt(33) + 586)**Rational(1, 3) + 4 + (102*sqrt(33)
|
156 |
+
+ 586)**Rational(2, 3)) + S.Half)
|
157 |
+
raises(ValueError, lambda: tribonacci(-1, x))
|
158 |
+
|
159 |
+
|
160 |
+
@nocache_fail
|
161 |
+
def test_bell():
|
162 |
+
assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877]
|
163 |
+
|
164 |
+
assert bell(0, x) == 1
|
165 |
+
assert bell(1, x) == x
|
166 |
+
assert bell(2, x) == x**2 + x
|
167 |
+
assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x
|
168 |
+
assert bell(oo) is S.Infinity
|
169 |
+
raises(ValueError, lambda: bell(oo, x))
|
170 |
+
|
171 |
+
raises(ValueError, lambda: bell(-1))
|
172 |
+
raises(ValueError, lambda: bell(S.Half))
|
173 |
+
|
174 |
+
X = symbols('x:6')
|
175 |
+
# X = (x0, x1, .. x5)
|
176 |
+
# at the same time: X[1] = x1, X[2] = x2 for standard readablity.
|
177 |
+
# but we must supply zero-based indexed object X[1:] = (x1, .. x5)
|
178 |
+
|
179 |
+
assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2
|
180 |
+
assert bell(
|
181 |
+
6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3
|
182 |
+
|
183 |
+
X = (1, 10, 100, 1000, 10000)
|
184 |
+
assert bell(6, 2, X) == (6 + 15 + 10)*10000
|
185 |
+
|
186 |
+
X = (1, 2, 3, 3, 5)
|
187 |
+
assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2
|
188 |
+
|
189 |
+
X = (1, 2, 3, 5)
|
190 |
+
assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3
|
191 |
+
|
192 |
+
# Dobinski's formula
|
193 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
194 |
+
# For large numbers, this is too slow
|
195 |
+
# For nonintegers, there are significant precision errors
|
196 |
+
for i in [0, 2, 3, 7, 13, 42, 55]:
|
197 |
+
# Running without the cache this is either very slow or goes into an
|
198 |
+
# infinite loop.
|
199 |
+
assert bell(i).evalf() == bell(n).rewrite(Sum).evalf(subs={n: i})
|
200 |
+
|
201 |
+
m = Symbol("m")
|
202 |
+
assert bell(m).rewrite(Sum) == bell(m)
|
203 |
+
assert bell(n, m).rewrite(Sum) == bell(n, m)
|
204 |
+
# issue 9184
|
205 |
+
n = Dummy('n')
|
206 |
+
assert bell(n).limit(n, S.Infinity) is S.Infinity
|
207 |
+
|
208 |
+
|
209 |
+
def test_harmonic():
|
210 |
+
n = Symbol("n")
|
211 |
+
m = Symbol("m")
|
212 |
+
|
213 |
+
assert harmonic(n, 0) == n
|
214 |
+
assert harmonic(n).evalf() == harmonic(n)
|
215 |
+
assert harmonic(n, 1) == harmonic(n)
|
216 |
+
assert harmonic(1, n) == 1
|
217 |
+
|
218 |
+
assert harmonic(0, 1) == 0
|
219 |
+
assert harmonic(1, 1) == 1
|
220 |
+
assert harmonic(2, 1) == Rational(3, 2)
|
221 |
+
assert harmonic(3, 1) == Rational(11, 6)
|
222 |
+
assert harmonic(4, 1) == Rational(25, 12)
|
223 |
+
assert harmonic(0, 2) == 0
|
224 |
+
assert harmonic(1, 2) == 1
|
225 |
+
assert harmonic(2, 2) == Rational(5, 4)
|
226 |
+
assert harmonic(3, 2) == Rational(49, 36)
|
227 |
+
assert harmonic(4, 2) == Rational(205, 144)
|
228 |
+
assert harmonic(0, 3) == 0
|
229 |
+
assert harmonic(1, 3) == 1
|
230 |
+
assert harmonic(2, 3) == Rational(9, 8)
|
231 |
+
assert harmonic(3, 3) == Rational(251, 216)
|
232 |
+
assert harmonic(4, 3) == Rational(2035, 1728)
|
233 |
+
|
234 |
+
assert harmonic(oo, -1) is S.NaN
|
235 |
+
assert harmonic(oo, 0) is oo
|
236 |
+
assert harmonic(oo, S.Half) is oo
|
237 |
+
assert harmonic(oo, 1) is oo
|
238 |
+
assert harmonic(oo, 2) == (pi**2)/6
|
239 |
+
assert harmonic(oo, 3) == zeta(3)
|
240 |
+
assert harmonic(oo, Dummy(negative=True)) is S.NaN
|
241 |
+
ip = Dummy(integer=True, positive=True)
|
242 |
+
if (1/ip <= 1) is True: #---------------------------------+
|
243 |
+
assert None, 'delete this if-block and the next line' #|
|
244 |
+
ip = Dummy(even=True, positive=True) #--------------------+
|
245 |
+
assert harmonic(oo, 1/ip) is oo
|
246 |
+
assert harmonic(oo, 1 + ip) is zeta(1 + ip)
|
247 |
+
|
248 |
+
assert harmonic(0, m) == 0
|
249 |
+
assert harmonic(-1, -1) == 0
|
250 |
+
assert harmonic(-1, 0) == -1
|
251 |
+
assert harmonic(-1, 1) is S.ComplexInfinity
|
252 |
+
assert harmonic(-1, 2) is S.NaN
|
253 |
+
assert harmonic(-3, -2) == -5
|
254 |
+
assert harmonic(-3, -3) == 9
|
255 |
+
|
256 |
+
|
257 |
+
def test_harmonic_rational():
|
258 |
+
ne = S(6)
|
259 |
+
no = S(5)
|
260 |
+
pe = S(8)
|
261 |
+
po = S(9)
|
262 |
+
qe = S(10)
|
263 |
+
qo = S(13)
|
264 |
+
|
265 |
+
Heee = harmonic(ne + pe/qe)
|
266 |
+
Aeee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
267 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
268 |
+
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(13944145, 4720968))
|
269 |
+
|
270 |
+
Heeo = harmonic(ne + pe/qo)
|
271 |
+
Aeeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
|
272 |
+
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
|
273 |
+
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2 - 2*log(sin(pi/13))*cos(pi*Rational(3, 13))
|
274 |
+
+ Rational(2422020029, 702257080))
|
275 |
+
|
276 |
+
Heoe = harmonic(ne + po/qe)
|
277 |
+
Aeoe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
|
278 |
+
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
279 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
280 |
+
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
|
281 |
+
+ Rational(11818877030, 4286604231) + pi*sqrt(2*sqrt(5) + 5)/2)
|
282 |
+
|
283 |
+
Heoo = harmonic(ne + po/qo)
|
284 |
+
Aeoo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
|
285 |
+
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
|
286 |
+
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
|
287 |
+
- 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(3, 13)) + Rational(11669332571, 3628714320))
|
288 |
+
|
289 |
+
Hoee = harmonic(no + pe/qe)
|
290 |
+
Aoee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
291 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
292 |
+
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(779405, 277704))
|
293 |
+
|
294 |
+
Hoeo = harmonic(no + pe/qo)
|
295 |
+
Aoeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
|
296 |
+
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
|
297 |
+
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2
|
298 |
+
- 2*log(sin(pi/13))*cos(pi*Rational(3, 13)) + Rational(53857323, 16331560))
|
299 |
+
|
300 |
+
Hooe = harmonic(no + po/qe)
|
301 |
+
Aooe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
|
302 |
+
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
303 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
304 |
+
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
|
305 |
+
+ Rational(486853480, 186374097) + pi*sqrt(2*sqrt(5) + 5)/2)
|
306 |
+
|
307 |
+
Hooo = harmonic(no + po/qo)
|
308 |
+
Aooo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
|
309 |
+
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
|
310 |
+
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
|
311 |
+
- 2*log(sin(pi*Rational(2, 13)))*cos(3*pi/13) + Rational(383693479, 125128080))
|
312 |
+
|
313 |
+
H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo]
|
314 |
+
A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo]
|
315 |
+
for h, a in zip(H, A):
|
316 |
+
e = expand_func(h).doit()
|
317 |
+
assert cancel(e/a) == 1
|
318 |
+
assert abs(h.n() - a.n()) < 1e-12
|
319 |
+
|
320 |
+
|
321 |
+
def test_harmonic_evalf():
|
322 |
+
assert str(harmonic(1.5).evalf(n=10)) == '1.280372306'
|
323 |
+
assert str(harmonic(1.5, 2).evalf(n=10)) == '1.154576311' # issue 7443
|
324 |
+
assert str(harmonic(4.0, -3).evalf(n=10)) == '100.0000000'
|
325 |
+
assert str(harmonic(7.0, 1.0).evalf(n=10)) == '2.592857143'
|
326 |
+
assert str(harmonic(1, pi).evalf(n=10)) == '1.000000000'
|
327 |
+
assert str(harmonic(2, pi).evalf(n=10)) == '1.113314732'
|
328 |
+
assert str(harmonic(1000.0, pi).evalf(n=10)) == '1.176241563'
|
329 |
+
assert str(harmonic(I).evalf(n=10)) == '0.6718659855 + 1.076674047*I'
|
330 |
+
assert str(harmonic(I, I).evalf(n=10)) == '-0.3970915266 + 1.9629689*I'
|
331 |
+
|
332 |
+
assert harmonic(-1.0, 1).evalf() is S.NaN
|
333 |
+
assert harmonic(-2.0, 2.0).evalf() is S.NaN
|
334 |
+
|
335 |
+
def test_harmonic_rewrite():
|
336 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
337 |
+
n = Symbol("n")
|
338 |
+
m = Symbol("m", integer=True, positive=True)
|
339 |
+
x1 = Symbol("x1", positive=True)
|
340 |
+
x2 = Symbol("x2", negative=True)
|
341 |
+
|
342 |
+
assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma
|
343 |
+
assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma
|
344 |
+
assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma
|
345 |
+
|
346 |
+
assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2
|
347 |
+
assert isinstance(harmonic(n,m).rewrite(polygamma), Piecewise)
|
348 |
+
|
349 |
+
assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
|
350 |
+
assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
|
351 |
+
|
352 |
+
assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma)
|
353 |
+
assert harmonic(n, x1).rewrite("tractable") == harmonic(n, x1)
|
354 |
+
assert harmonic(n, x1 + 1).rewrite("tractable") == zeta(x1 + 1) - zeta(x1 + 1, n + 1)
|
355 |
+
assert harmonic(n, x2).rewrite("tractable") == zeta(x2) - zeta(x2, n + 1)
|
356 |
+
|
357 |
+
_k = Dummy("k")
|
358 |
+
assert harmonic(n).rewrite(Sum).dummy_eq(Sum(1/_k, (_k, 1, n)))
|
359 |
+
assert harmonic(n, m).rewrite(Sum).dummy_eq(Sum(_k**(-m), (_k, 1, n)))
|
360 |
+
|
361 |
+
|
362 |
+
def test_harmonic_calculus():
|
363 |
+
y = Symbol("y", positive=True)
|
364 |
+
z = Symbol("z", negative=True)
|
365 |
+
assert harmonic(x, 1).limit(x, 0) == 0
|
366 |
+
assert harmonic(x, y).limit(x, 0) == 0
|
367 |
+
assert harmonic(x, 1).series(x, y, 2) == \
|
368 |
+
harmonic(y) + (x - y)*zeta(2, y + 1) + O((x - y)**2, (x, y))
|
369 |
+
assert limit(harmonic(x, y), x, oo) == harmonic(oo, y)
|
370 |
+
assert limit(harmonic(x, y + 1), x, oo) == zeta(y + 1)
|
371 |
+
assert limit(harmonic(x, y - 1), x, oo) == harmonic(oo, y - 1)
|
372 |
+
assert limit(harmonic(x, z), x, oo) == Limit(harmonic(x, z), x, oo, dir='-')
|
373 |
+
assert limit(harmonic(x, z + 1), x, oo) == oo
|
374 |
+
assert limit(harmonic(x, z + 2), x, oo) == harmonic(oo, z + 2)
|
375 |
+
assert limit(harmonic(x, z - 1), x, oo) == Limit(harmonic(x, z - 1), x, oo, dir='-')
|
376 |
+
|
377 |
+
|
378 |
+
def test_euler():
|
379 |
+
assert euler(0) == 1
|
380 |
+
assert euler(1) == 0
|
381 |
+
assert euler(2) == -1
|
382 |
+
assert euler(3) == 0
|
383 |
+
assert euler(4) == 5
|
384 |
+
assert euler(6) == -61
|
385 |
+
assert euler(8) == 1385
|
386 |
+
|
387 |
+
assert euler(20, evaluate=False) != 370371188237525
|
388 |
+
|
389 |
+
n = Symbol('n', integer=True)
|
390 |
+
assert euler(n) != -1
|
391 |
+
assert euler(n).subs(n, 2) == -1
|
392 |
+
|
393 |
+
assert euler(-1) == S.Pi / 2
|
394 |
+
assert euler(-1, 1) == 2*log(2)
|
395 |
+
assert euler(-2).evalf() == (2*S.Catalan).evalf()
|
396 |
+
assert euler(-3).evalf() == (S.Pi**3 / 16).evalf()
|
397 |
+
assert str(euler(2.3).evalf(n=10)) == '-1.052850274'
|
398 |
+
assert str(euler(1.2, 3.4).evalf(n=10)) == '3.575613489'
|
399 |
+
assert str(euler(I).evalf(n=10)) == '1.248446443 - 0.7675445124*I'
|
400 |
+
assert str(euler(I, I).evalf(n=10)) == '0.04812930469 + 0.01052411008*I'
|
401 |
+
|
402 |
+
assert euler(20).evalf() == 370371188237525.0
|
403 |
+
assert euler(20, evaluate=False).evalf() == 370371188237525.0
|
404 |
+
|
405 |
+
assert euler(n).rewrite(Sum) == euler(n)
|
406 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
407 |
+
assert euler(2*n + 1).rewrite(Sum) == 0
|
408 |
+
_j = Dummy('j')
|
409 |
+
_k = Dummy('k')
|
410 |
+
assert euler(2*n).rewrite(Sum).dummy_eq(
|
411 |
+
I*Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)*
|
412 |
+
binomial(_k, _j)/_k, (_j, 0, _k), (_k, 1, 2*n + 1)))
|
413 |
+
|
414 |
+
|
415 |
+
def test_euler_odd():
|
416 |
+
n = Symbol('n', odd=True, positive=True)
|
417 |
+
assert euler(n) == 0
|
418 |
+
n = Symbol('n', odd=True)
|
419 |
+
assert euler(n) != 0
|
420 |
+
|
421 |
+
|
422 |
+
def test_euler_polynomials():
|
423 |
+
assert euler(0, x) == 1
|
424 |
+
assert euler(1, x) == x - S.Half
|
425 |
+
assert euler(2, x) == x**2 - x
|
426 |
+
assert euler(3, x) == x**3 - (3*x**2)/2 + Rational(1, 4)
|
427 |
+
m = Symbol('m')
|
428 |
+
assert isinstance(euler(m, x), euler)
|
429 |
+
from sympy.core.numbers import Float
|
430 |
+
A = Float('-0.46237208575048694923364757452876131e8') # from Maple
|
431 |
+
B = euler(19, S.Pi).evalf(32)
|
432 |
+
assert abs((A - B)/A) < 1e-31
|
433 |
+
|
434 |
+
|
435 |
+
def test_euler_polynomial_rewrite():
|
436 |
+
m = Symbol('m')
|
437 |
+
A = euler(m, x).rewrite('Sum');
|
438 |
+
assert A.subs({m:3, x:5}).doit() == euler(3, 5)
|
439 |
+
|
440 |
+
|
441 |
+
def test_catalan():
|
442 |
+
n = Symbol('n', integer=True)
|
443 |
+
m = Symbol('m', integer=True, positive=True)
|
444 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
445 |
+
p = Symbol('p', nonnegative=True)
|
446 |
+
|
447 |
+
catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
|
448 |
+
for i, c in enumerate(catalans):
|
449 |
+
assert catalan(i) == c
|
450 |
+
assert catalan(n).rewrite(factorial).subs(n, i) == c
|
451 |
+
assert catalan(n).rewrite(Product).subs(n, i).doit() == c
|
452 |
+
|
453 |
+
assert unchanged(catalan, x)
|
454 |
+
assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
|
455 |
+
assert catalan(S.Half).rewrite(gamma) == 8/(3*pi)
|
456 |
+
assert catalan(S.Half).rewrite(factorial).rewrite(gamma) ==\
|
457 |
+
8 / (3 * pi)
|
458 |
+
assert catalan(3*x).rewrite(gamma) == 4**(
|
459 |
+
3*x)*gamma(3*x + S.Half)/(sqrt(pi)*gamma(3*x + 2))
|
460 |
+
assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)
|
461 |
+
|
462 |
+
assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
|
463 |
+
* factorial(n))
|
464 |
+
assert isinstance(catalan(n).rewrite(Product), catalan)
|
465 |
+
assert isinstance(catalan(m).rewrite(Product), Product)
|
466 |
+
|
467 |
+
assert diff(catalan(x), x) == (polygamma(
|
468 |
+
0, x + S.Half) - polygamma(0, x + 2) + log(4))*catalan(x)
|
469 |
+
|
470 |
+
assert catalan(x).evalf() == catalan(x)
|
471 |
+
c = catalan(S.Half).evalf()
|
472 |
+
assert str(c) == '0.848826363156775'
|
473 |
+
c = catalan(I).evalf(3)
|
474 |
+
assert str((re(c), im(c))) == '(0.398, -0.0209)'
|
475 |
+
|
476 |
+
# Assumptions
|
477 |
+
assert catalan(p).is_positive is True
|
478 |
+
assert catalan(k).is_integer is True
|
479 |
+
assert catalan(m+3).is_composite is True
|
480 |
+
|
481 |
+
|
482 |
+
def test_genocchi():
|
483 |
+
genocchis = [0, -1, -1, 0, 1, 0, -3, 0, 17]
|
484 |
+
for n, g in enumerate(genocchis):
|
485 |
+
assert genocchi(n) == g
|
486 |
+
|
487 |
+
m = Symbol('m', integer=True)
|
488 |
+
n = Symbol('n', integer=True, positive=True)
|
489 |
+
assert unchanged(genocchi, m)
|
490 |
+
assert genocchi(2*n + 1) == 0
|
491 |
+
gn = 2 * (1 - 2**n) * bernoulli(n)
|
492 |
+
assert genocchi(n).rewrite(bernoulli).factor() == gn.factor()
|
493 |
+
gnx = 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
|
494 |
+
assert genocchi(n, x).rewrite(bernoulli).factor() == gnx.factor()
|
495 |
+
assert genocchi(2 * n).is_odd
|
496 |
+
assert genocchi(2 * n).is_even is False
|
497 |
+
assert genocchi(2 * n + 1).is_even
|
498 |
+
assert genocchi(n).is_integer
|
499 |
+
assert genocchi(4 * n).is_positive
|
500 |
+
# these are the only 2 prime Genocchi numbers
|
501 |
+
assert genocchi(6, evaluate=False).is_prime == S(-3).is_prime
|
502 |
+
assert genocchi(8, evaluate=False).is_prime
|
503 |
+
assert genocchi(4 * n + 2).is_negative
|
504 |
+
assert genocchi(4 * n + 1).is_negative is False
|
505 |
+
assert genocchi(4 * n - 2).is_negative
|
506 |
+
|
507 |
+
g0 = genocchi(0, evaluate=False)
|
508 |
+
assert g0.is_positive is False
|
509 |
+
assert g0.is_negative is False
|
510 |
+
assert g0.is_even is True
|
511 |
+
assert g0.is_odd is False
|
512 |
+
|
513 |
+
assert genocchi(0, x) == 0
|
514 |
+
assert genocchi(1, x) == -1
|
515 |
+
assert genocchi(2, x) == 1 - 2*x
|
516 |
+
assert genocchi(3, x) == 3*x - 3*x**2
|
517 |
+
assert genocchi(4, x) == -1 + 6*x**2 - 4*x**3
|
518 |
+
y = Symbol("y")
|
519 |
+
assert genocchi(5, (x+y)**100) == -5*(x+y)**400 + 10*(x+y)**300 - 5*(x+y)**100
|
520 |
+
|
521 |
+
assert str(genocchi(5.0, 4.0).evalf(n=10)) == '-660.0000000'
|
522 |
+
assert str(genocchi(Rational(5, 4)).evalf(n=10)) == '-1.104286457'
|
523 |
+
assert str(genocchi(-2).evalf(n=10)) == '3.606170709'
|
524 |
+
assert str(genocchi(1.3, 3.7).evalf(n=10)) == '-1.847375373'
|
525 |
+
assert str(genocchi(I, 1.0).evalf(n=10)) == '-0.3161917278 - 1.45311955*I'
|
526 |
+
|
527 |
+
n = Symbol('n')
|
528 |
+
assert genocchi(n, x).rewrite(dirichlet_eta) == -2*n * dirichlet_eta(1-n, x)
|
529 |
+
|
530 |
+
|
531 |
+
def test_andre():
|
532 |
+
nums = [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
|
533 |
+
for n, a in enumerate(nums):
|
534 |
+
assert andre(n) == a
|
535 |
+
assert andre(S.Infinity) == S.Infinity
|
536 |
+
assert andre(-1) == -log(2)
|
537 |
+
assert andre(-2) == -2*S.Catalan
|
538 |
+
assert andre(-3) == 3*zeta(3)/16
|
539 |
+
assert andre(-5) == -15*zeta(5)/256
|
540 |
+
# In fact andre(-2*n) is related to the Dirichlet *beta* function
|
541 |
+
# at 2*n, but SymPy doesn't implement that (or general L-functions)
|
542 |
+
assert unchanged(andre, -4)
|
543 |
+
|
544 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
545 |
+
assert unchanged(andre, n)
|
546 |
+
assert andre(n).is_integer is True
|
547 |
+
assert andre(n).is_positive is True
|
548 |
+
|
549 |
+
assert str(andre(10, evaluate=False).evalf(n=10)) == '50521.00000'
|
550 |
+
assert str(andre(-1, evaluate=False).evalf(n=10)) == '-0.6931471806'
|
551 |
+
assert str(andre(-2, evaluate=False).evalf(n=10)) == '-1.831931188'
|
552 |
+
assert str(andre(-4, evaluate=False).evalf(n=10)) == '1.977889103'
|
553 |
+
assert str(andre(I, evaluate=False).evalf(n=10)) == '2.378417833 + 0.6343322845*I'
|
554 |
+
|
555 |
+
assert andre(x).rewrite(polylog) == \
|
556 |
+
(-I)**(x+1) * polylog(-x, I) + I**(x+1) * polylog(-x, -I)
|
557 |
+
assert andre(x).rewrite(zeta) == \
|
558 |
+
2 * gamma(x+1) / (2*pi)**(x+1) * \
|
559 |
+
(zeta(x+1, Rational(1,4)) - cos(pi*x) * zeta(x+1, Rational(3,4)))
|
560 |
+
|
561 |
+
|
562 |
+
@nocache_fail
|
563 |
+
def test_partition():
|
564 |
+
partition_nums = [1, 1, 2, 3, 5, 7, 11, 15, 22]
|
565 |
+
for n, p in enumerate(partition_nums):
|
566 |
+
assert partition(n) == p
|
567 |
+
|
568 |
+
x = Symbol('x')
|
569 |
+
y = Symbol('y', real=True)
|
570 |
+
m = Symbol('m', integer=True)
|
571 |
+
n = Symbol('n', integer=True, negative=True)
|
572 |
+
p = Symbol('p', integer=True, nonnegative=True)
|
573 |
+
assert partition(m).is_integer
|
574 |
+
assert not partition(m).is_negative
|
575 |
+
assert partition(m).is_nonnegative
|
576 |
+
assert partition(n).is_zero
|
577 |
+
assert partition(p).is_positive
|
578 |
+
assert partition(x).subs(x, 7) == 15
|
579 |
+
assert partition(y).subs(y, 8) == 22
|
580 |
+
raises(ValueError, lambda: partition(Rational(5, 4)))
|
581 |
+
|
582 |
+
|
583 |
+
def test__nT():
|
584 |
+
assert [_nT(i, j) for i in range(5) for j in range(i + 2)] == [
|
585 |
+
1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 2, 1, 1, 0]
|
586 |
+
check = [_nT(10, i) for i in range(11)]
|
587 |
+
assert check == [0, 1, 5, 8, 9, 7, 5, 3, 2, 1, 1]
|
588 |
+
assert all(type(i) is int for i in check)
|
589 |
+
assert _nT(10, 5) == 7
|
590 |
+
assert _nT(100, 98) == 2
|
591 |
+
assert _nT(100, 100) == 1
|
592 |
+
assert _nT(10, 3) == 8
|
593 |
+
|
594 |
+
|
595 |
+
def test_nC_nP_nT():
|
596 |
+
from sympy.utilities.iterables import (
|
597 |
+
multiset_permutations, multiset_combinations, multiset_partitions,
|
598 |
+
partitions, subsets, permutations)
|
599 |
+
from sympy.functions.combinatorial.numbers import (
|
600 |
+
nP, nC, nT, stirling, _stirling1, _stirling2, _multiset_histogram, _AOP_product)
|
601 |
+
|
602 |
+
from sympy.combinatorics.permutations import Permutation
|
603 |
+
from sympy.core.random import choice
|
604 |
+
|
605 |
+
c = string.ascii_lowercase
|
606 |
+
for i in range(100):
|
607 |
+
s = ''.join(choice(c) for i in range(7))
|
608 |
+
u = len(s) == len(set(s))
|
609 |
+
try:
|
610 |
+
tot = 0
|
611 |
+
for i in range(8):
|
612 |
+
check = nP(s, i)
|
613 |
+
tot += check
|
614 |
+
assert len(list(multiset_permutations(s, i))) == check
|
615 |
+
if u:
|
616 |
+
assert nP(len(s), i) == check
|
617 |
+
assert nP(s) == tot
|
618 |
+
except AssertionError:
|
619 |
+
print(s, i, 'failed perm test')
|
620 |
+
raise ValueError()
|
621 |
+
|
622 |
+
for i in range(100):
|
623 |
+
s = ''.join(choice(c) for i in range(7))
|
624 |
+
u = len(s) == len(set(s))
|
625 |
+
try:
|
626 |
+
tot = 0
|
627 |
+
for i in range(8):
|
628 |
+
check = nC(s, i)
|
629 |
+
tot += check
|
630 |
+
assert len(list(multiset_combinations(s, i))) == check
|
631 |
+
if u:
|
632 |
+
assert nC(len(s), i) == check
|
633 |
+
assert nC(s) == tot
|
634 |
+
if u:
|
635 |
+
assert nC(len(s)) == tot
|
636 |
+
except AssertionError:
|
637 |
+
print(s, i, 'failed combo test')
|
638 |
+
raise ValueError()
|
639 |
+
|
640 |
+
for i in range(1, 10):
|
641 |
+
tot = 0
|
642 |
+
for j in range(1, i + 2):
|
643 |
+
check = nT(i, j)
|
644 |
+
assert check.is_Integer
|
645 |
+
tot += check
|
646 |
+
assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check
|
647 |
+
assert nT(i) == tot
|
648 |
+
|
649 |
+
for i in range(1, 10):
|
650 |
+
tot = 0
|
651 |
+
for j in range(1, i + 2):
|
652 |
+
check = nT(range(i), j)
|
653 |
+
tot += check
|
654 |
+
assert len(list(multiset_partitions(list(range(i)), j))) == check
|
655 |
+
assert nT(range(i)) == tot
|
656 |
+
|
657 |
+
for i in range(100):
|
658 |
+
s = ''.join(choice(c) for i in range(7))
|
659 |
+
u = len(s) == len(set(s))
|
660 |
+
try:
|
661 |
+
tot = 0
|
662 |
+
for i in range(1, 8):
|
663 |
+
check = nT(s, i)
|
664 |
+
tot += check
|
665 |
+
assert len(list(multiset_partitions(s, i))) == check
|
666 |
+
if u:
|
667 |
+
assert nT(range(len(s)), i) == check
|
668 |
+
if u:
|
669 |
+
assert nT(range(len(s))) == tot
|
670 |
+
assert nT(s) == tot
|
671 |
+
except AssertionError:
|
672 |
+
print(s, i, 'failed partition test')
|
673 |
+
raise ValueError()
|
674 |
+
|
675 |
+
# tests for Stirling numbers of the first kind that are not tested in the
|
676 |
+
# above
|
677 |
+
assert [stirling(9, i, kind=1) for i in range(11)] == [
|
678 |
+
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0]
|
679 |
+
perms = list(permutations(range(4)))
|
680 |
+
assert [sum(1 for p in perms if Permutation(p).cycles == i)
|
681 |
+
for i in range(5)] == [0, 6, 11, 6, 1] == [
|
682 |
+
stirling(4, i, kind=1) for i in range(5)]
|
683 |
+
# http://oeis.org/A008275
|
684 |
+
assert [stirling(n, k, signed=1)
|
685 |
+
for n in range(10) for k in range(1, n + 1)] == [
|
686 |
+
1, -1,
|
687 |
+
1, 2, -3,
|
688 |
+
1, -6, 11, -6,
|
689 |
+
1, 24, -50, 35, -10,
|
690 |
+
1, -120, 274, -225, 85, -15,
|
691 |
+
1, 720, -1764, 1624, -735, 175, -21,
|
692 |
+
1, -5040, 13068, -13132, 6769, -1960, 322, -28,
|
693 |
+
1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1]
|
694 |
+
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
|
695 |
+
assert [stirling(n, k, kind=1)
|
696 |
+
for n in range(10) for k in range(n+1)] == [
|
697 |
+
1,
|
698 |
+
0, 1,
|
699 |
+
0, 1, 1,
|
700 |
+
0, 2, 3, 1,
|
701 |
+
0, 6, 11, 6, 1,
|
702 |
+
0, 24, 50, 35, 10, 1,
|
703 |
+
0, 120, 274, 225, 85, 15, 1,
|
704 |
+
0, 720, 1764, 1624, 735, 175, 21, 1,
|
705 |
+
0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1,
|
706 |
+
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1]
|
707 |
+
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
|
708 |
+
assert [stirling(n, k, kind=2)
|
709 |
+
for n in range(10) for k in range(n+1)] == [
|
710 |
+
1,
|
711 |
+
0, 1,
|
712 |
+
0, 1, 1,
|
713 |
+
0, 1, 3, 1,
|
714 |
+
0, 1, 7, 6, 1,
|
715 |
+
0, 1, 15, 25, 10, 1,
|
716 |
+
0, 1, 31, 90, 65, 15, 1,
|
717 |
+
0, 1, 63, 301, 350, 140, 21, 1,
|
718 |
+
0, 1, 127, 966, 1701, 1050, 266, 28, 1,
|
719 |
+
0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1]
|
720 |
+
assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0
|
721 |
+
raises(ValueError, lambda: stirling(-2, 2))
|
722 |
+
|
723 |
+
# Assertion that the return type is SymPy Integer.
|
724 |
+
assert isinstance(_stirling1(6, 3), Integer)
|
725 |
+
assert isinstance(_stirling2(6, 3), Integer)
|
726 |
+
|
727 |
+
def delta(p):
|
728 |
+
if len(p) == 1:
|
729 |
+
return oo
|
730 |
+
return min(abs(i[0] - i[1]) for i in subsets(p, 2))
|
731 |
+
parts = multiset_partitions(range(5), 3)
|
732 |
+
d = 2
|
733 |
+
assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) ==
|
734 |
+
stirling(5, 3, d=d) == 7)
|
735 |
+
|
736 |
+
# other coverage tests
|
737 |
+
assert nC('abb', 2) == nC('aab', 2) == 2
|
738 |
+
assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27
|
739 |
+
assert nP(3, 4) == 0
|
740 |
+
assert nP('aabc', 5) == 0
|
741 |
+
assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \
|
742 |
+
len(list(multiset_combinations('aabbccdd', 2))) == 10
|
743 |
+
assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24
|
744 |
+
assert nC(list('abcdd'), 4) == 4
|
745 |
+
assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5
|
746 |
+
assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7
|
747 |
+
assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa
|
748 |
+
assert dict(_AOP_product((4,1,1,1))) == {
|
749 |
+
0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1}
|
750 |
+
# the following was the first t that showed a problem in a previous form of
|
751 |
+
# the function, so it's not as random as it may appear
|
752 |
+
t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4)
|
753 |
+
assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000
|
754 |
+
raises(ValueError, lambda: _multiset_histogram({1:'a'}))
|
755 |
+
|
756 |
+
|
757 |
+
def test_PR_14617():
|
758 |
+
from sympy.functions.combinatorial.numbers import nT
|
759 |
+
for n in (0, []):
|
760 |
+
for k in (-1, 0, 1):
|
761 |
+
if k == 0:
|
762 |
+
assert nT(n, k) == 1
|
763 |
+
else:
|
764 |
+
assert nT(n, k) == 0
|
765 |
+
|
766 |
+
|
767 |
+
def test_issue_8496():
|
768 |
+
n = Symbol("n")
|
769 |
+
k = Symbol("k")
|
770 |
+
|
771 |
+
raises(TypeError, lambda: catalan(n, k))
|
772 |
+
|
773 |
+
|
774 |
+
def test_issue_8601():
|
775 |
+
n = Symbol('n', integer=True, negative=True)
|
776 |
+
|
777 |
+
assert catalan(n - 1) is S.Zero
|
778 |
+
assert catalan(Rational(-1, 2)) is S.ComplexInfinity
|
779 |
+
assert catalan(-S.One) == Rational(-1, 2)
|
780 |
+
c1 = catalan(-5.6).evalf()
|
781 |
+
assert str(c1) == '6.93334070531408e-5'
|
782 |
+
c2 = catalan(-35.4).evalf()
|
783 |
+
assert str(c2) == '-4.14189164517449e-24'
|
784 |
+
|
785 |
+
|
786 |
+
def test_motzkin():
|
787 |
+
assert motzkin.is_motzkin(4) == True
|
788 |
+
assert motzkin.is_motzkin(9) == True
|
789 |
+
assert motzkin.is_motzkin(10) == False
|
790 |
+
assert motzkin.find_motzkin_numbers_in_range(10,200) == [21, 51, 127]
|
791 |
+
assert motzkin.find_motzkin_numbers_in_range(10,400) == [21, 51, 127, 323]
|
792 |
+
assert motzkin.find_motzkin_numbers_in_range(10,1600) == [21, 51, 127, 323, 835]
|
793 |
+
assert motzkin.find_first_n_motzkins(5) == [1, 1, 2, 4, 9]
|
794 |
+
assert motzkin.find_first_n_motzkins(7) == [1, 1, 2, 4, 9, 21, 51]
|
795 |
+
assert motzkin.find_first_n_motzkins(10) == [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
|
796 |
+
raises(ValueError, lambda: motzkin.eval(77.58))
|
797 |
+
raises(ValueError, lambda: motzkin.eval(-8))
|
798 |
+
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(-2,7))
|
799 |
+
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(13,7))
|
800 |
+
raises(ValueError, lambda: motzkin.find_first_n_motzkins(112.8))
|
801 |
+
|
802 |
+
|
803 |
+
def test_nD_derangements():
|
804 |
+
from sympy.utilities.iterables import (partitions, multiset,
|
805 |
+
multiset_derangements, multiset_permutations)
|
806 |
+
from sympy.functions.combinatorial.numbers import nD
|
807 |
+
|
808 |
+
got = []
|
809 |
+
for i in partitions(8, k=4):
|
810 |
+
s = []
|
811 |
+
it = 0
|
812 |
+
for k, v in i.items():
|
813 |
+
for i in range(v):
|
814 |
+
s.extend([it]*k)
|
815 |
+
it += 1
|
816 |
+
ms = multiset(s)
|
817 |
+
c1 = sum(1 for i in multiset_permutations(s) if
|
818 |
+
all(i != j for i, j in zip(i, s)))
|
819 |
+
assert c1 == nD(ms) == nD(ms, 0) == nD(ms, 1)
|
820 |
+
v = [tuple(i) for i in multiset_derangements(s)]
|
821 |
+
c2 = len(v)
|
822 |
+
assert c2 == len(set(v))
|
823 |
+
assert c1 == c2
|
824 |
+
got.append(c1)
|
825 |
+
assert got == [1, 4, 6, 12, 24, 24, 61, 126, 315, 780, 297, 772,
|
826 |
+
2033, 5430, 14833]
|
827 |
+
|
828 |
+
assert nD('1112233456', brute=True) == nD('1112233456') == 16356
|
829 |
+
assert nD('') == nD([]) == nD({}) == 0
|
830 |
+
assert nD({1: 0}) == 0
|
831 |
+
raises(ValueError, lambda: nD({1: -1}))
|
832 |
+
assert nD('112') == 0
|
833 |
+
assert nD(i='112') == 0
|
834 |
+
assert [nD(n=i) for i in range(6)] == [0, 0, 1, 2, 9, 44]
|
835 |
+
assert nD((i for i in range(4))) == nD('0123') == 9
|
836 |
+
assert nD(m=(i for i in range(4))) == 3
|
837 |
+
assert nD(m={0: 1, 1: 1, 2: 1, 3: 1}) == 3
|
838 |
+
assert nD(m=[0, 1, 2, 3]) == 3
|
839 |
+
raises(TypeError, lambda: nD(m=0))
|
840 |
+
raises(TypeError, lambda: nD(-1))
|
841 |
+
assert nD({-1: 1, -2: 1}) == 1
|
842 |
+
assert nD(m={0: 3}) == 0
|
843 |
+
raises(ValueError, lambda: nD(i='123', n=3))
|
844 |
+
raises(ValueError, lambda: nD(i='123', m=(1,2)))
|
845 |
+
raises(ValueError, lambda: nD(n=0, m=(1,2)))
|
846 |
+
raises(ValueError, lambda: nD({1: -1}))
|
847 |
+
raises(ValueError, lambda: nD(m={-1: 1, 2: 1}))
|
848 |
+
raises(ValueError, lambda: nD(m={1: -1, 2: 1}))
|
849 |
+
raises(ValueError, lambda: nD(m=[-1, 2]))
|
850 |
+
raises(TypeError, lambda: nD({1: x}))
|
851 |
+
raises(TypeError, lambda: nD(m={1: x}))
|
852 |
+
raises(TypeError, lambda: nD(m={x: 1}))
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (199 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_beta_functions.cpython-310.pyc
ADDED
Binary file (3.85 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_bsplines.cpython-310.pyc
ADDED
Binary file (6.63 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_delta_functions.cpython-310.pyc
ADDED
Binary file (5.96 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_gamma_functions.cpython-310.pyc
ADDED
Binary file (24.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_hyper.cpython-310.pyc
ADDED
Binary file (15.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_tensor_functions.cpython-310.pyc
ADDED
Binary file (4.58 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/functions/special/tests/__pycache__/test_zeta_functions.cpython-310.pyc
ADDED
Binary file (10.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Names exposed by 'from sympy.physics.quantum import *'
|
2 |
+
|
3 |
+
__all__ = [
|
4 |
+
'AntiCommutator',
|
5 |
+
|
6 |
+
'qapply',
|
7 |
+
|
8 |
+
'Commutator',
|
9 |
+
|
10 |
+
'Dagger',
|
11 |
+
|
12 |
+
'HilbertSpaceError', 'HilbertSpace', 'TensorProductHilbertSpace',
|
13 |
+
'TensorPowerHilbertSpace', 'DirectSumHilbertSpace', 'ComplexSpace', 'L2',
|
14 |
+
'FockSpace',
|
15 |
+
|
16 |
+
'InnerProduct',
|
17 |
+
|
18 |
+
'Operator', 'HermitianOperator', 'UnitaryOperator', 'IdentityOperator',
|
19 |
+
'OuterProduct', 'DifferentialOperator',
|
20 |
+
|
21 |
+
'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result',
|
22 |
+
'get_basis', 'enumerate_states',
|
23 |
+
|
24 |
+
'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState',
|
25 |
+
'TimeDepBra', 'TimeDepKet', 'OrthogonalKet', 'OrthogonalBra',
|
26 |
+
'OrthogonalState', 'Wavefunction',
|
27 |
+
|
28 |
+
'TensorProduct', 'tensor_product_simp',
|
29 |
+
|
30 |
+
'hbar', 'HBar',
|
31 |
+
|
32 |
+
]
|
33 |
+
from .anticommutator import AntiCommutator
|
34 |
+
|
35 |
+
from .qapply import qapply
|
36 |
+
|
37 |
+
from .commutator import Commutator
|
38 |
+
|
39 |
+
from .dagger import Dagger
|
40 |
+
|
41 |
+
from .hilbert import (HilbertSpaceError, HilbertSpace,
|
42 |
+
TensorProductHilbertSpace, TensorPowerHilbertSpace,
|
43 |
+
DirectSumHilbertSpace, ComplexSpace, L2, FockSpace)
|
44 |
+
|
45 |
+
from .innerproduct import InnerProduct
|
46 |
+
|
47 |
+
from .operator import (Operator, HermitianOperator, UnitaryOperator,
|
48 |
+
IdentityOperator, OuterProduct, DifferentialOperator)
|
49 |
+
|
50 |
+
from .represent import (represent, rep_innerproduct, rep_expectation,
|
51 |
+
integrate_result, get_basis, enumerate_states)
|
52 |
+
|
53 |
+
from .state import (KetBase, BraBase, StateBase, State, Ket, Bra,
|
54 |
+
TimeDepState, TimeDepBra, TimeDepKet, OrthogonalKet,
|
55 |
+
OrthogonalBra, OrthogonalState, Wavefunction)
|
56 |
+
|
57 |
+
from .tensorproduct import TensorProduct, tensor_product_simp
|
58 |
+
|
59 |
+
from .constants import hbar, HBar
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/commutator.cpython-310.pyc
ADDED
Binary file (6.29 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/constants.cpython-310.pyc
ADDED
Binary file (1.78 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/gate.cpython-310.pyc
ADDED
Binary file (34.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/identitysearch.cpython-310.pyc
ADDED
Binary file (21.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixcache.cpython-310.pyc
ADDED
Binary file (3.73 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/operatorordering.cpython-310.pyc
ADDED
Binary file (7.18 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/operatorset.cpython-310.pyc
ADDED
Binary file (7.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/pauli.cpython-310.pyc
ADDED
Binary file (18.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/piab.cpython-310.pyc
ADDED
Binary file (3.17 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/qapply.cpython-310.pyc
ADDED
Binary file (5.03 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/qubit.cpython-310.pyc
ADDED
Binary file (22.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/sho1d.cpython-310.pyc
ADDED
Binary file (22 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/shor.cpython-310.pyc
ADDED
Binary file (5.41 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/spin.cpython-310.pyc
ADDED
Binary file (72.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/state.cpython-310.pyc
ADDED
Binary file (30.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/trace.cpython-310.pyc
ADDED
Binary file (5.94 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""The anti-commutator: ``{A,B} = A*B + B*A``."""
|
2 |
+
|
3 |
+
from sympy.core.expr import Expr
|
4 |
+
from sympy.core.mul import Mul
|
5 |
+
from sympy.core.numbers import Integer
|
6 |
+
from sympy.core.singleton import S
|
7 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
8 |
+
|
9 |
+
from sympy.physics.quantum.operator import Operator
|
10 |
+
from sympy.physics.quantum.dagger import Dagger
|
11 |
+
|
12 |
+
__all__ = [
|
13 |
+
'AntiCommutator'
|
14 |
+
]
|
15 |
+
|
16 |
+
#-----------------------------------------------------------------------------
|
17 |
+
# Anti-commutator
|
18 |
+
#-----------------------------------------------------------------------------
|
19 |
+
|
20 |
+
|
21 |
+
class AntiCommutator(Expr):
|
22 |
+
"""The standard anticommutator, in an unevaluated state.
|
23 |
+
|
24 |
+
Explanation
|
25 |
+
===========
|
26 |
+
|
27 |
+
Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``.
|
28 |
+
This class returns the anticommutator in an unevaluated form. To evaluate
|
29 |
+
the anticommutator, use the ``.doit()`` method.
|
30 |
+
|
31 |
+
Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The
|
32 |
+
arguments of the anticommutator are put into canonical order using
|
33 |
+
``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``.
|
34 |
+
|
35 |
+
Parameters
|
36 |
+
==========
|
37 |
+
|
38 |
+
A : Expr
|
39 |
+
The first argument of the anticommutator {A,B}.
|
40 |
+
B : Expr
|
41 |
+
The second argument of the anticommutator {A,B}.
|
42 |
+
|
43 |
+
Examples
|
44 |
+
========
|
45 |
+
|
46 |
+
>>> from sympy import symbols
|
47 |
+
>>> from sympy.physics.quantum import AntiCommutator
|
48 |
+
>>> from sympy.physics.quantum import Operator, Dagger
|
49 |
+
>>> x, y = symbols('x,y')
|
50 |
+
>>> A = Operator('A')
|
51 |
+
>>> B = Operator('B')
|
52 |
+
|
53 |
+
Create an anticommutator and use ``doit()`` to multiply them out.
|
54 |
+
|
55 |
+
>>> ac = AntiCommutator(A,B); ac
|
56 |
+
{A,B}
|
57 |
+
>>> ac.doit()
|
58 |
+
A*B + B*A
|
59 |
+
|
60 |
+
The commutator orders it arguments in canonical order:
|
61 |
+
|
62 |
+
>>> ac = AntiCommutator(B,A); ac
|
63 |
+
{A,B}
|
64 |
+
|
65 |
+
Commutative constants are factored out:
|
66 |
+
|
67 |
+
>>> AntiCommutator(3*x*A,x*y*B)
|
68 |
+
3*x**2*y*{A,B}
|
69 |
+
|
70 |
+
Adjoint operations applied to the anticommutator are properly applied to
|
71 |
+
the arguments:
|
72 |
+
|
73 |
+
>>> Dagger(AntiCommutator(A,B))
|
74 |
+
{Dagger(A),Dagger(B)}
|
75 |
+
|
76 |
+
References
|
77 |
+
==========
|
78 |
+
|
79 |
+
.. [1] https://en.wikipedia.org/wiki/Commutator
|
80 |
+
"""
|
81 |
+
is_commutative = False
|
82 |
+
|
83 |
+
def __new__(cls, A, B):
|
84 |
+
r = cls.eval(A, B)
|
85 |
+
if r is not None:
|
86 |
+
return r
|
87 |
+
obj = Expr.__new__(cls, A, B)
|
88 |
+
return obj
|
89 |
+
|
90 |
+
@classmethod
|
91 |
+
def eval(cls, a, b):
|
92 |
+
if not (a and b):
|
93 |
+
return S.Zero
|
94 |
+
if a == b:
|
95 |
+
return Integer(2)*a**2
|
96 |
+
if a.is_commutative or b.is_commutative:
|
97 |
+
return Integer(2)*a*b
|
98 |
+
|
99 |
+
# [xA,yB] -> xy*[A,B]
|
100 |
+
ca, nca = a.args_cnc()
|
101 |
+
cb, ncb = b.args_cnc()
|
102 |
+
c_part = ca + cb
|
103 |
+
if c_part:
|
104 |
+
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
|
105 |
+
|
106 |
+
# Canonical ordering of arguments
|
107 |
+
#The Commutator [A,B] is on canonical form if A < B.
|
108 |
+
if a.compare(b) == 1:
|
109 |
+
return cls(b, a)
|
110 |
+
|
111 |
+
def doit(self, **hints):
|
112 |
+
""" Evaluate anticommutator """
|
113 |
+
A = self.args[0]
|
114 |
+
B = self.args[1]
|
115 |
+
if isinstance(A, Operator) and isinstance(B, Operator):
|
116 |
+
try:
|
117 |
+
comm = A._eval_anticommutator(B, **hints)
|
118 |
+
except NotImplementedError:
|
119 |
+
try:
|
120 |
+
comm = B._eval_anticommutator(A, **hints)
|
121 |
+
except NotImplementedError:
|
122 |
+
comm = None
|
123 |
+
if comm is not None:
|
124 |
+
return comm.doit(**hints)
|
125 |
+
return (A*B + B*A).doit(**hints)
|
126 |
+
|
127 |
+
def _eval_adjoint(self):
|
128 |
+
return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1]))
|
129 |
+
|
130 |
+
def _sympyrepr(self, printer, *args):
|
131 |
+
return "%s(%s,%s)" % (
|
132 |
+
self.__class__.__name__, printer._print(
|
133 |
+
self.args[0]), printer._print(self.args[1])
|
134 |
+
)
|
135 |
+
|
136 |
+
def _sympystr(self, printer, *args):
|
137 |
+
return "{%s,%s}" % (
|
138 |
+
printer._print(self.args[0]), printer._print(self.args[1]))
|
139 |
+
|
140 |
+
def _pretty(self, printer, *args):
|
141 |
+
pform = printer._print(self.args[0], *args)
|
142 |
+
pform = prettyForm(*pform.right(prettyForm(',')))
|
143 |
+
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
|
144 |
+
pform = prettyForm(*pform.parens(left='{', right='}'))
|
145 |
+
return pform
|
146 |
+
|
147 |
+
def _latex(self, printer, *args):
|
148 |
+
return "\\left\\{%s,%s\\right\\}" % tuple([
|
149 |
+
printer._print(arg, *args) for arg in self.args])
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/boson.py
ADDED
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Bosonic quantum operators."""
|
2 |
+
|
3 |
+
from sympy.core.mul import Mul
|
4 |
+
from sympy.core.numbers import Integer
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.functions.elementary.complexes import conjugate
|
7 |
+
from sympy.functions.elementary.exponential import exp
|
8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
9 |
+
from sympy.physics.quantum import Operator
|
10 |
+
from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator
|
11 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
12 |
+
|
13 |
+
|
14 |
+
__all__ = [
|
15 |
+
'BosonOp',
|
16 |
+
'BosonFockKet',
|
17 |
+
'BosonFockBra',
|
18 |
+
'BosonCoherentKet',
|
19 |
+
'BosonCoherentBra'
|
20 |
+
]
|
21 |
+
|
22 |
+
|
23 |
+
class BosonOp(Operator):
|
24 |
+
"""A bosonic operator that satisfies [a, Dagger(a)] == 1.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
==========
|
28 |
+
|
29 |
+
name : str
|
30 |
+
A string that labels the bosonic mode.
|
31 |
+
|
32 |
+
annihilation : bool
|
33 |
+
A bool that indicates if the bosonic operator is an annihilation (True,
|
34 |
+
default value) or creation operator (False)
|
35 |
+
|
36 |
+
Examples
|
37 |
+
========
|
38 |
+
|
39 |
+
>>> from sympy.physics.quantum import Dagger, Commutator
|
40 |
+
>>> from sympy.physics.quantum.boson import BosonOp
|
41 |
+
>>> a = BosonOp("a")
|
42 |
+
>>> Commutator(a, Dagger(a)).doit()
|
43 |
+
1
|
44 |
+
"""
|
45 |
+
|
46 |
+
@property
|
47 |
+
def name(self):
|
48 |
+
return self.args[0]
|
49 |
+
|
50 |
+
@property
|
51 |
+
def is_annihilation(self):
|
52 |
+
return bool(self.args[1])
|
53 |
+
|
54 |
+
@classmethod
|
55 |
+
def default_args(self):
|
56 |
+
return ("a", True)
|
57 |
+
|
58 |
+
def __new__(cls, *args, **hints):
|
59 |
+
if not len(args) in [1, 2]:
|
60 |
+
raise ValueError('1 or 2 parameters expected, got %s' % args)
|
61 |
+
|
62 |
+
if len(args) == 1:
|
63 |
+
args = (args[0], S.One)
|
64 |
+
|
65 |
+
if len(args) == 2:
|
66 |
+
args = (args[0], Integer(args[1]))
|
67 |
+
|
68 |
+
return Operator.__new__(cls, *args)
|
69 |
+
|
70 |
+
def _eval_commutator_BosonOp(self, other, **hints):
|
71 |
+
if self.name == other.name:
|
72 |
+
# [a^\dagger, a] = -1
|
73 |
+
if not self.is_annihilation and other.is_annihilation:
|
74 |
+
return S.NegativeOne
|
75 |
+
|
76 |
+
elif 'independent' in hints and hints['independent']:
|
77 |
+
# [a, b] = 0
|
78 |
+
return S.Zero
|
79 |
+
|
80 |
+
return None
|
81 |
+
|
82 |
+
def _eval_commutator_FermionOp(self, other, **hints):
|
83 |
+
return S.Zero
|
84 |
+
|
85 |
+
def _eval_anticommutator_BosonOp(self, other, **hints):
|
86 |
+
if 'independent' in hints and hints['independent']:
|
87 |
+
# {a, b} = 2 * a * b, because [a, b] = 0
|
88 |
+
return 2 * self * other
|
89 |
+
|
90 |
+
return None
|
91 |
+
|
92 |
+
def _eval_adjoint(self):
|
93 |
+
return BosonOp(str(self.name), not self.is_annihilation)
|
94 |
+
|
95 |
+
def __mul__(self, other):
|
96 |
+
|
97 |
+
if other == IdentityOperator(2):
|
98 |
+
return self
|
99 |
+
|
100 |
+
if isinstance(other, Mul):
|
101 |
+
args1 = tuple(arg for arg in other.args if arg.is_commutative)
|
102 |
+
args2 = tuple(arg for arg in other.args if not arg.is_commutative)
|
103 |
+
x = self
|
104 |
+
for y in args2:
|
105 |
+
x = x * y
|
106 |
+
return Mul(*args1) * x
|
107 |
+
|
108 |
+
return Mul(self, other)
|
109 |
+
|
110 |
+
def _print_contents_latex(self, printer, *args):
|
111 |
+
if self.is_annihilation:
|
112 |
+
return r'{%s}' % str(self.name)
|
113 |
+
else:
|
114 |
+
return r'{{%s}^\dagger}' % str(self.name)
|
115 |
+
|
116 |
+
def _print_contents(self, printer, *args):
|
117 |
+
if self.is_annihilation:
|
118 |
+
return r'%s' % str(self.name)
|
119 |
+
else:
|
120 |
+
return r'Dagger(%s)' % str(self.name)
|
121 |
+
|
122 |
+
def _print_contents_pretty(self, printer, *args):
|
123 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
124 |
+
pform = printer._print(self.args[0], *args)
|
125 |
+
if self.is_annihilation:
|
126 |
+
return pform
|
127 |
+
else:
|
128 |
+
return pform**prettyForm('\N{DAGGER}')
|
129 |
+
|
130 |
+
|
131 |
+
class BosonFockKet(Ket):
|
132 |
+
"""Fock state ket for a bosonic mode.
|
133 |
+
|
134 |
+
Parameters
|
135 |
+
==========
|
136 |
+
|
137 |
+
n : Number
|
138 |
+
The Fock state number.
|
139 |
+
|
140 |
+
"""
|
141 |
+
|
142 |
+
def __new__(cls, n):
|
143 |
+
return Ket.__new__(cls, n)
|
144 |
+
|
145 |
+
@property
|
146 |
+
def n(self):
|
147 |
+
return self.label[0]
|
148 |
+
|
149 |
+
@classmethod
|
150 |
+
def dual_class(self):
|
151 |
+
return BosonFockBra
|
152 |
+
|
153 |
+
@classmethod
|
154 |
+
def _eval_hilbert_space(cls, label):
|
155 |
+
return FockSpace()
|
156 |
+
|
157 |
+
def _eval_innerproduct_BosonFockBra(self, bra, **hints):
|
158 |
+
return KroneckerDelta(self.n, bra.n)
|
159 |
+
|
160 |
+
def _apply_from_right_to_BosonOp(self, op, **options):
|
161 |
+
if op.is_annihilation:
|
162 |
+
return sqrt(self.n) * BosonFockKet(self.n - 1)
|
163 |
+
else:
|
164 |
+
return sqrt(self.n + 1) * BosonFockKet(self.n + 1)
|
165 |
+
|
166 |
+
|
167 |
+
class BosonFockBra(Bra):
|
168 |
+
"""Fock state bra for a bosonic mode.
|
169 |
+
|
170 |
+
Parameters
|
171 |
+
==========
|
172 |
+
|
173 |
+
n : Number
|
174 |
+
The Fock state number.
|
175 |
+
|
176 |
+
"""
|
177 |
+
|
178 |
+
def __new__(cls, n):
|
179 |
+
return Bra.__new__(cls, n)
|
180 |
+
|
181 |
+
@property
|
182 |
+
def n(self):
|
183 |
+
return self.label[0]
|
184 |
+
|
185 |
+
@classmethod
|
186 |
+
def dual_class(self):
|
187 |
+
return BosonFockKet
|
188 |
+
|
189 |
+
@classmethod
|
190 |
+
def _eval_hilbert_space(cls, label):
|
191 |
+
return FockSpace()
|
192 |
+
|
193 |
+
|
194 |
+
class BosonCoherentKet(Ket):
|
195 |
+
"""Coherent state ket for a bosonic mode.
|
196 |
+
|
197 |
+
Parameters
|
198 |
+
==========
|
199 |
+
|
200 |
+
alpha : Number, Symbol
|
201 |
+
The complex amplitude of the coherent state.
|
202 |
+
|
203 |
+
"""
|
204 |
+
|
205 |
+
def __new__(cls, alpha):
|
206 |
+
return Ket.__new__(cls, alpha)
|
207 |
+
|
208 |
+
@property
|
209 |
+
def alpha(self):
|
210 |
+
return self.label[0]
|
211 |
+
|
212 |
+
@classmethod
|
213 |
+
def dual_class(self):
|
214 |
+
return BosonCoherentBra
|
215 |
+
|
216 |
+
@classmethod
|
217 |
+
def _eval_hilbert_space(cls, label):
|
218 |
+
return HilbertSpace()
|
219 |
+
|
220 |
+
def _eval_innerproduct_BosonCoherentBra(self, bra, **hints):
|
221 |
+
if self.alpha == bra.alpha:
|
222 |
+
return S.One
|
223 |
+
else:
|
224 |
+
return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2)
|
225 |
+
|
226 |
+
def _apply_from_right_to_BosonOp(self, op, **options):
|
227 |
+
if op.is_annihilation:
|
228 |
+
return self.alpha * self
|
229 |
+
else:
|
230 |
+
return None
|
231 |
+
|
232 |
+
|
233 |
+
class BosonCoherentBra(Bra):
|
234 |
+
"""Coherent state bra for a bosonic mode.
|
235 |
+
|
236 |
+
Parameters
|
237 |
+
==========
|
238 |
+
|
239 |
+
alpha : Number, Symbol
|
240 |
+
The complex amplitude of the coherent state.
|
241 |
+
|
242 |
+
"""
|
243 |
+
|
244 |
+
def __new__(cls, alpha):
|
245 |
+
return Bra.__new__(cls, alpha)
|
246 |
+
|
247 |
+
@property
|
248 |
+
def alpha(self):
|
249 |
+
return self.label[0]
|
250 |
+
|
251 |
+
@classmethod
|
252 |
+
def dual_class(self):
|
253 |
+
return BosonCoherentKet
|
254 |
+
|
255 |
+
def _apply_operator_BosonOp(self, op, **options):
|
256 |
+
if not op.is_annihilation:
|
257 |
+
return self.alpha * self
|
258 |
+
else:
|
259 |
+
return None
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py
ADDED
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Operators and states for 1D cartesian position and momentum.
|
2 |
+
|
3 |
+
TODO:
|
4 |
+
|
5 |
+
* Add 3D classes to mappings in operatorset.py
|
6 |
+
|
7 |
+
"""
|
8 |
+
|
9 |
+
from sympy.core.numbers import (I, pi)
|
10 |
+
from sympy.core.singleton import S
|
11 |
+
from sympy.functions.elementary.exponential import exp
|
12 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
13 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
14 |
+
from sympy.sets.sets import Interval
|
15 |
+
|
16 |
+
from sympy.physics.quantum.constants import hbar
|
17 |
+
from sympy.physics.quantum.hilbert import L2
|
18 |
+
from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator
|
19 |
+
from sympy.physics.quantum.state import Ket, Bra, State
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
'XOp',
|
23 |
+
'YOp',
|
24 |
+
'ZOp',
|
25 |
+
'PxOp',
|
26 |
+
'X',
|
27 |
+
'Y',
|
28 |
+
'Z',
|
29 |
+
'Px',
|
30 |
+
'XKet',
|
31 |
+
'XBra',
|
32 |
+
'PxKet',
|
33 |
+
'PxBra',
|
34 |
+
'PositionState3D',
|
35 |
+
'PositionKet3D',
|
36 |
+
'PositionBra3D'
|
37 |
+
]
|
38 |
+
|
39 |
+
#-------------------------------------------------------------------------
|
40 |
+
# Position operators
|
41 |
+
#-------------------------------------------------------------------------
|
42 |
+
|
43 |
+
|
44 |
+
class XOp(HermitianOperator):
|
45 |
+
"""1D cartesian position operator."""
|
46 |
+
|
47 |
+
@classmethod
|
48 |
+
def default_args(self):
|
49 |
+
return ("X",)
|
50 |
+
|
51 |
+
@classmethod
|
52 |
+
def _eval_hilbert_space(self, args):
|
53 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
54 |
+
|
55 |
+
def _eval_commutator_PxOp(self, other):
|
56 |
+
return I*hbar
|
57 |
+
|
58 |
+
def _apply_operator_XKet(self, ket, **options):
|
59 |
+
return ket.position*ket
|
60 |
+
|
61 |
+
def _apply_operator_PositionKet3D(self, ket, **options):
|
62 |
+
return ket.position_x*ket
|
63 |
+
|
64 |
+
def _represent_PxKet(self, basis, *, index=1, **options):
|
65 |
+
states = basis._enumerate_state(2, start_index=index)
|
66 |
+
coord1 = states[0].momentum
|
67 |
+
coord2 = states[1].momentum
|
68 |
+
d = DifferentialOperator(coord1)
|
69 |
+
delta = DiracDelta(coord1 - coord2)
|
70 |
+
|
71 |
+
return I*hbar*(d*delta)
|
72 |
+
|
73 |
+
|
74 |
+
class YOp(HermitianOperator):
|
75 |
+
""" Y cartesian coordinate operator (for 2D or 3D systems) """
|
76 |
+
|
77 |
+
@classmethod
|
78 |
+
def default_args(self):
|
79 |
+
return ("Y",)
|
80 |
+
|
81 |
+
@classmethod
|
82 |
+
def _eval_hilbert_space(self, args):
|
83 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
84 |
+
|
85 |
+
def _apply_operator_PositionKet3D(self, ket, **options):
|
86 |
+
return ket.position_y*ket
|
87 |
+
|
88 |
+
|
89 |
+
class ZOp(HermitianOperator):
|
90 |
+
""" Z cartesian coordinate operator (for 3D systems) """
|
91 |
+
|
92 |
+
@classmethod
|
93 |
+
def default_args(self):
|
94 |
+
return ("Z",)
|
95 |
+
|
96 |
+
@classmethod
|
97 |
+
def _eval_hilbert_space(self, args):
|
98 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
99 |
+
|
100 |
+
def _apply_operator_PositionKet3D(self, ket, **options):
|
101 |
+
return ket.position_z*ket
|
102 |
+
|
103 |
+
#-------------------------------------------------------------------------
|
104 |
+
# Momentum operators
|
105 |
+
#-------------------------------------------------------------------------
|
106 |
+
|
107 |
+
|
108 |
+
class PxOp(HermitianOperator):
|
109 |
+
"""1D cartesian momentum operator."""
|
110 |
+
|
111 |
+
@classmethod
|
112 |
+
def default_args(self):
|
113 |
+
return ("Px",)
|
114 |
+
|
115 |
+
@classmethod
|
116 |
+
def _eval_hilbert_space(self, args):
|
117 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
118 |
+
|
119 |
+
def _apply_operator_PxKet(self, ket, **options):
|
120 |
+
return ket.momentum*ket
|
121 |
+
|
122 |
+
def _represent_XKet(self, basis, *, index=1, **options):
|
123 |
+
states = basis._enumerate_state(2, start_index=index)
|
124 |
+
coord1 = states[0].position
|
125 |
+
coord2 = states[1].position
|
126 |
+
d = DifferentialOperator(coord1)
|
127 |
+
delta = DiracDelta(coord1 - coord2)
|
128 |
+
|
129 |
+
return -I*hbar*(d*delta)
|
130 |
+
|
131 |
+
X = XOp('X')
|
132 |
+
Y = YOp('Y')
|
133 |
+
Z = ZOp('Z')
|
134 |
+
Px = PxOp('Px')
|
135 |
+
|
136 |
+
#-------------------------------------------------------------------------
|
137 |
+
# Position eigenstates
|
138 |
+
#-------------------------------------------------------------------------
|
139 |
+
|
140 |
+
|
141 |
+
class XKet(Ket):
|
142 |
+
"""1D cartesian position eigenket."""
|
143 |
+
|
144 |
+
@classmethod
|
145 |
+
def _operators_to_state(self, op, **options):
|
146 |
+
return self.__new__(self, *_lowercase_labels(op), **options)
|
147 |
+
|
148 |
+
def _state_to_operators(self, op_class, **options):
|
149 |
+
return op_class.__new__(op_class,
|
150 |
+
*_uppercase_labels(self), **options)
|
151 |
+
|
152 |
+
@classmethod
|
153 |
+
def default_args(self):
|
154 |
+
return ("x",)
|
155 |
+
|
156 |
+
@classmethod
|
157 |
+
def dual_class(self):
|
158 |
+
return XBra
|
159 |
+
|
160 |
+
@property
|
161 |
+
def position(self):
|
162 |
+
"""The position of the state."""
|
163 |
+
return self.label[0]
|
164 |
+
|
165 |
+
def _enumerate_state(self, num_states, **options):
|
166 |
+
return _enumerate_continuous_1D(self, num_states, **options)
|
167 |
+
|
168 |
+
def _eval_innerproduct_XBra(self, bra, **hints):
|
169 |
+
return DiracDelta(self.position - bra.position)
|
170 |
+
|
171 |
+
def _eval_innerproduct_PxBra(self, bra, **hints):
|
172 |
+
return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar)
|
173 |
+
|
174 |
+
|
175 |
+
class XBra(Bra):
|
176 |
+
"""1D cartesian position eigenbra."""
|
177 |
+
|
178 |
+
@classmethod
|
179 |
+
def default_args(self):
|
180 |
+
return ("x",)
|
181 |
+
|
182 |
+
@classmethod
|
183 |
+
def dual_class(self):
|
184 |
+
return XKet
|
185 |
+
|
186 |
+
@property
|
187 |
+
def position(self):
|
188 |
+
"""The position of the state."""
|
189 |
+
return self.label[0]
|
190 |
+
|
191 |
+
|
192 |
+
class PositionState3D(State):
|
193 |
+
""" Base class for 3D cartesian position eigenstates """
|
194 |
+
|
195 |
+
@classmethod
|
196 |
+
def _operators_to_state(self, op, **options):
|
197 |
+
return self.__new__(self, *_lowercase_labels(op), **options)
|
198 |
+
|
199 |
+
def _state_to_operators(self, op_class, **options):
|
200 |
+
return op_class.__new__(op_class,
|
201 |
+
*_uppercase_labels(self), **options)
|
202 |
+
|
203 |
+
@classmethod
|
204 |
+
def default_args(self):
|
205 |
+
return ("x", "y", "z")
|
206 |
+
|
207 |
+
@property
|
208 |
+
def position_x(self):
|
209 |
+
""" The x coordinate of the state """
|
210 |
+
return self.label[0]
|
211 |
+
|
212 |
+
@property
|
213 |
+
def position_y(self):
|
214 |
+
""" The y coordinate of the state """
|
215 |
+
return self.label[1]
|
216 |
+
|
217 |
+
@property
|
218 |
+
def position_z(self):
|
219 |
+
""" The z coordinate of the state """
|
220 |
+
return self.label[2]
|
221 |
+
|
222 |
+
|
223 |
+
class PositionKet3D(Ket, PositionState3D):
|
224 |
+
""" 3D cartesian position eigenket """
|
225 |
+
|
226 |
+
def _eval_innerproduct_PositionBra3D(self, bra, **options):
|
227 |
+
x_diff = self.position_x - bra.position_x
|
228 |
+
y_diff = self.position_y - bra.position_y
|
229 |
+
z_diff = self.position_z - bra.position_z
|
230 |
+
|
231 |
+
return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff)
|
232 |
+
|
233 |
+
@classmethod
|
234 |
+
def dual_class(self):
|
235 |
+
return PositionBra3D
|
236 |
+
|
237 |
+
|
238 |
+
# XXX: The type:ignore here is because mypy gives Definition of
|
239 |
+
# "_state_to_operators" in base class "PositionState3D" is incompatible with
|
240 |
+
# definition in base class "BraBase"
|
241 |
+
class PositionBra3D(Bra, PositionState3D): # type: ignore
|
242 |
+
""" 3D cartesian position eigenbra """
|
243 |
+
|
244 |
+
@classmethod
|
245 |
+
def dual_class(self):
|
246 |
+
return PositionKet3D
|
247 |
+
|
248 |
+
#-------------------------------------------------------------------------
|
249 |
+
# Momentum eigenstates
|
250 |
+
#-------------------------------------------------------------------------
|
251 |
+
|
252 |
+
|
253 |
+
class PxKet(Ket):
|
254 |
+
"""1D cartesian momentum eigenket."""
|
255 |
+
|
256 |
+
@classmethod
|
257 |
+
def _operators_to_state(self, op, **options):
|
258 |
+
return self.__new__(self, *_lowercase_labels(op), **options)
|
259 |
+
|
260 |
+
def _state_to_operators(self, op_class, **options):
|
261 |
+
return op_class.__new__(op_class,
|
262 |
+
*_uppercase_labels(self), **options)
|
263 |
+
|
264 |
+
@classmethod
|
265 |
+
def default_args(self):
|
266 |
+
return ("px",)
|
267 |
+
|
268 |
+
@classmethod
|
269 |
+
def dual_class(self):
|
270 |
+
return PxBra
|
271 |
+
|
272 |
+
@property
|
273 |
+
def momentum(self):
|
274 |
+
"""The momentum of the state."""
|
275 |
+
return self.label[0]
|
276 |
+
|
277 |
+
def _enumerate_state(self, *args, **options):
|
278 |
+
return _enumerate_continuous_1D(self, *args, **options)
|
279 |
+
|
280 |
+
def _eval_innerproduct_XBra(self, bra, **hints):
|
281 |
+
return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar)
|
282 |
+
|
283 |
+
def _eval_innerproduct_PxBra(self, bra, **hints):
|
284 |
+
return DiracDelta(self.momentum - bra.momentum)
|
285 |
+
|
286 |
+
|
287 |
+
class PxBra(Bra):
|
288 |
+
"""1D cartesian momentum eigenbra."""
|
289 |
+
|
290 |
+
@classmethod
|
291 |
+
def default_args(self):
|
292 |
+
return ("px",)
|
293 |
+
|
294 |
+
@classmethod
|
295 |
+
def dual_class(self):
|
296 |
+
return PxKet
|
297 |
+
|
298 |
+
@property
|
299 |
+
def momentum(self):
|
300 |
+
"""The momentum of the state."""
|
301 |
+
return self.label[0]
|
302 |
+
|
303 |
+
#-------------------------------------------------------------------------
|
304 |
+
# Global helper functions
|
305 |
+
#-------------------------------------------------------------------------
|
306 |
+
|
307 |
+
|
308 |
+
def _enumerate_continuous_1D(*args, **options):
|
309 |
+
state = args[0]
|
310 |
+
num_states = args[1]
|
311 |
+
state_class = state.__class__
|
312 |
+
index_list = options.pop('index_list', [])
|
313 |
+
|
314 |
+
if len(index_list) == 0:
|
315 |
+
start_index = options.pop('start_index', 1)
|
316 |
+
index_list = list(range(start_index, start_index + num_states))
|
317 |
+
|
318 |
+
enum_states = [0 for i in range(len(index_list))]
|
319 |
+
|
320 |
+
for i, ind in enumerate(index_list):
|
321 |
+
label = state.args[0]
|
322 |
+
enum_states[i] = state_class(str(label) + "_" + str(ind), **options)
|
323 |
+
|
324 |
+
return enum_states
|
325 |
+
|
326 |
+
|
327 |
+
def _lowercase_labels(ops):
|
328 |
+
if not isinstance(ops, set):
|
329 |
+
ops = [ops]
|
330 |
+
|
331 |
+
return [str(arg.label[0]).lower() for arg in ops]
|
332 |
+
|
333 |
+
|
334 |
+
def _uppercase_labels(ops):
|
335 |
+
if not isinstance(ops, set):
|
336 |
+
ops = [ops]
|
337 |
+
|
338 |
+
new_args = [str(arg.label[0])[0].upper() +
|
339 |
+
str(arg.label[0])[1:] for arg in ops]
|
340 |
+
|
341 |
+
return new_args
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/cg.py
ADDED
@@ -0,0 +1,754 @@
|
|
|
|
|
|
|
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+
# -Implement new simplifications
|
5 |
+
"""Clebsch-Gordon Coefficients."""
|
6 |
+
|
7 |
+
from sympy.concrete.summations import Sum
|
8 |
+
from sympy.core.add import Add
|
9 |
+
from sympy.core.expr import Expr
|
10 |
+
from sympy.core.function import expand
|
11 |
+
from sympy.core.mul import Mul
|
12 |
+
from sympy.core.power import Pow
|
13 |
+
from sympy.core.relational import Eq
|
14 |
+
from sympy.core.singleton import S
|
15 |
+
from sympy.core.symbol import (Wild, symbols)
|
16 |
+
from sympy.core.sympify import sympify
|
17 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
18 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
19 |
+
from sympy.printing.pretty.stringpict import prettyForm, stringPict
|
20 |
+
|
21 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
22 |
+
from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
|
23 |
+
from sympy.printing.precedence import PRECEDENCE
|
24 |
+
|
25 |
+
__all__ = [
|
26 |
+
'CG',
|
27 |
+
'Wigner3j',
|
28 |
+
'Wigner6j',
|
29 |
+
'Wigner9j',
|
30 |
+
'cg_simp'
|
31 |
+
]
|
32 |
+
|
33 |
+
#-----------------------------------------------------------------------------
|
34 |
+
# CG Coefficients
|
35 |
+
#-----------------------------------------------------------------------------
|
36 |
+
|
37 |
+
|
38 |
+
class Wigner3j(Expr):
|
39 |
+
"""Class for the Wigner-3j symbols.
|
40 |
+
|
41 |
+
Explanation
|
42 |
+
===========
|
43 |
+
|
44 |
+
Wigner 3j-symbols are coefficients determined by the coupling of
|
45 |
+
two angular momenta. When created, they are expressed as symbolic
|
46 |
+
quantities that, for numerical parameters, can be evaluated using the
|
47 |
+
``.doit()`` method [1]_.
|
48 |
+
|
49 |
+
Parameters
|
50 |
+
==========
|
51 |
+
|
52 |
+
j1, m1, j2, m2, j3, m3 : Number, Symbol
|
53 |
+
Terms determining the angular momentum of coupled angular momentum
|
54 |
+
systems.
|
55 |
+
|
56 |
+
Examples
|
57 |
+
========
|
58 |
+
|
59 |
+
Declare a Wigner-3j coefficient and calculate its value
|
60 |
+
|
61 |
+
>>> from sympy.physics.quantum.cg import Wigner3j
|
62 |
+
>>> w3j = Wigner3j(6,0,4,0,2,0)
|
63 |
+
>>> w3j
|
64 |
+
Wigner3j(6, 0, 4, 0, 2, 0)
|
65 |
+
>>> w3j.doit()
|
66 |
+
sqrt(715)/143
|
67 |
+
|
68 |
+
See Also
|
69 |
+
========
|
70 |
+
|
71 |
+
CG: Clebsch-Gordan coefficients
|
72 |
+
|
73 |
+
References
|
74 |
+
==========
|
75 |
+
|
76 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
77 |
+
"""
|
78 |
+
|
79 |
+
is_commutative = True
|
80 |
+
|
81 |
+
def __new__(cls, j1, m1, j2, m2, j3, m3):
|
82 |
+
args = map(sympify, (j1, m1, j2, m2, j3, m3))
|
83 |
+
return Expr.__new__(cls, *args)
|
84 |
+
|
85 |
+
@property
|
86 |
+
def j1(self):
|
87 |
+
return self.args[0]
|
88 |
+
|
89 |
+
@property
|
90 |
+
def m1(self):
|
91 |
+
return self.args[1]
|
92 |
+
|
93 |
+
@property
|
94 |
+
def j2(self):
|
95 |
+
return self.args[2]
|
96 |
+
|
97 |
+
@property
|
98 |
+
def m2(self):
|
99 |
+
return self.args[3]
|
100 |
+
|
101 |
+
@property
|
102 |
+
def j3(self):
|
103 |
+
return self.args[4]
|
104 |
+
|
105 |
+
@property
|
106 |
+
def m3(self):
|
107 |
+
return self.args[5]
|
108 |
+
|
109 |
+
@property
|
110 |
+
def is_symbolic(self):
|
111 |
+
return not all(arg.is_number for arg in self.args)
|
112 |
+
|
113 |
+
# This is modified from the _print_Matrix method
|
114 |
+
def _pretty(self, printer, *args):
|
115 |
+
m = ((printer._print(self.j1), printer._print(self.m1)),
|
116 |
+
(printer._print(self.j2), printer._print(self.m2)),
|
117 |
+
(printer._print(self.j3), printer._print(self.m3)))
|
118 |
+
hsep = 2
|
119 |
+
vsep = 1
|
120 |
+
maxw = [-1]*3
|
121 |
+
for j in range(3):
|
122 |
+
maxw[j] = max([ m[j][i].width() for i in range(2) ])
|
123 |
+
D = None
|
124 |
+
for i in range(2):
|
125 |
+
D_row = None
|
126 |
+
for j in range(3):
|
127 |
+
s = m[j][i]
|
128 |
+
wdelta = maxw[j] - s.width()
|
129 |
+
wleft = wdelta //2
|
130 |
+
wright = wdelta - wleft
|
131 |
+
|
132 |
+
s = prettyForm(*s.right(' '*wright))
|
133 |
+
s = prettyForm(*s.left(' '*wleft))
|
134 |
+
|
135 |
+
if D_row is None:
|
136 |
+
D_row = s
|
137 |
+
continue
|
138 |
+
D_row = prettyForm(*D_row.right(' '*hsep))
|
139 |
+
D_row = prettyForm(*D_row.right(s))
|
140 |
+
if D is None:
|
141 |
+
D = D_row
|
142 |
+
continue
|
143 |
+
for _ in range(vsep):
|
144 |
+
D = prettyForm(*D.below(' '))
|
145 |
+
D = prettyForm(*D.below(D_row))
|
146 |
+
D = prettyForm(*D.parens())
|
147 |
+
return D
|
148 |
+
|
149 |
+
def _latex(self, printer, *args):
|
150 |
+
label = map(printer._print, (self.j1, self.j2, self.j3,
|
151 |
+
self.m1, self.m2, self.m3))
|
152 |
+
return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
|
153 |
+
tuple(label)
|
154 |
+
|
155 |
+
def doit(self, **hints):
|
156 |
+
if self.is_symbolic:
|
157 |
+
raise ValueError("Coefficients must be numerical")
|
158 |
+
return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
|
159 |
+
|
160 |
+
|
161 |
+
class CG(Wigner3j):
|
162 |
+
r"""Class for Clebsch-Gordan coefficient.
|
163 |
+
|
164 |
+
Explanation
|
165 |
+
===========
|
166 |
+
|
167 |
+
Clebsch-Gordan coefficients describe the angular momentum coupling between
|
168 |
+
two systems. The coefficients give the expansion of a coupled total angular
|
169 |
+
momentum state and an uncoupled tensor product state. The Clebsch-Gordan
|
170 |
+
coefficients are defined as [1]_:
|
171 |
+
|
172 |
+
.. math ::
|
173 |
+
C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
|
174 |
+
|
175 |
+
Parameters
|
176 |
+
==========
|
177 |
+
|
178 |
+
j1, m1, j2, m2 : Number, Symbol
|
179 |
+
Angular momenta of states 1 and 2.
|
180 |
+
|
181 |
+
j3, m3: Number, Symbol
|
182 |
+
Total angular momentum of the coupled system.
|
183 |
+
|
184 |
+
Examples
|
185 |
+
========
|
186 |
+
|
187 |
+
Define a Clebsch-Gordan coefficient and evaluate its value
|
188 |
+
|
189 |
+
>>> from sympy.physics.quantum.cg import CG
|
190 |
+
>>> from sympy import S
|
191 |
+
>>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
|
192 |
+
>>> cg
|
193 |
+
CG(3/2, 3/2, 1/2, -1/2, 1, 1)
|
194 |
+
>>> cg.doit()
|
195 |
+
sqrt(3)/2
|
196 |
+
>>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
|
197 |
+
sqrt(2)/2
|
198 |
+
|
199 |
+
|
200 |
+
Compare [2]_.
|
201 |
+
|
202 |
+
See Also
|
203 |
+
========
|
204 |
+
|
205 |
+
Wigner3j: Wigner-3j symbols
|
206 |
+
|
207 |
+
References
|
208 |
+
==========
|
209 |
+
|
210 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
211 |
+
.. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
|
212 |
+
<https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_
|
213 |
+
in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
|
214 |
+
2020, 083C01 (2020).
|
215 |
+
"""
|
216 |
+
precedence = PRECEDENCE["Pow"] - 1
|
217 |
+
|
218 |
+
def doit(self, **hints):
|
219 |
+
if self.is_symbolic:
|
220 |
+
raise ValueError("Coefficients must be numerical")
|
221 |
+
return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
|
222 |
+
|
223 |
+
def _pretty(self, printer, *args):
|
224 |
+
bot = printer._print_seq(
|
225 |
+
(self.j1, self.m1, self.j2, self.m2), delimiter=',')
|
226 |
+
top = printer._print_seq((self.j3, self.m3), delimiter=',')
|
227 |
+
|
228 |
+
pad = max(top.width(), bot.width())
|
229 |
+
bot = prettyForm(*bot.left(' '))
|
230 |
+
top = prettyForm(*top.left(' '))
|
231 |
+
|
232 |
+
if not pad == bot.width():
|
233 |
+
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
|
234 |
+
if not pad == top.width():
|
235 |
+
top = prettyForm(*top.right(' '*(pad - top.width())))
|
236 |
+
s = stringPict('C' + ' '*pad)
|
237 |
+
s = prettyForm(*s.below(bot))
|
238 |
+
s = prettyForm(*s.above(top))
|
239 |
+
return s
|
240 |
+
|
241 |
+
def _latex(self, printer, *args):
|
242 |
+
label = map(printer._print, (self.j3, self.m3, self.j1,
|
243 |
+
self.m1, self.j2, self.m2))
|
244 |
+
return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
|
245 |
+
|
246 |
+
|
247 |
+
class Wigner6j(Expr):
|
248 |
+
"""Class for the Wigner-6j symbols
|
249 |
+
|
250 |
+
See Also
|
251 |
+
========
|
252 |
+
|
253 |
+
Wigner3j: Wigner-3j symbols
|
254 |
+
|
255 |
+
"""
|
256 |
+
def __new__(cls, j1, j2, j12, j3, j, j23):
|
257 |
+
args = map(sympify, (j1, j2, j12, j3, j, j23))
|
258 |
+
return Expr.__new__(cls, *args)
|
259 |
+
|
260 |
+
@property
|
261 |
+
def j1(self):
|
262 |
+
return self.args[0]
|
263 |
+
|
264 |
+
@property
|
265 |
+
def j2(self):
|
266 |
+
return self.args[1]
|
267 |
+
|
268 |
+
@property
|
269 |
+
def j12(self):
|
270 |
+
return self.args[2]
|
271 |
+
|
272 |
+
@property
|
273 |
+
def j3(self):
|
274 |
+
return self.args[3]
|
275 |
+
|
276 |
+
@property
|
277 |
+
def j(self):
|
278 |
+
return self.args[4]
|
279 |
+
|
280 |
+
@property
|
281 |
+
def j23(self):
|
282 |
+
return self.args[5]
|
283 |
+
|
284 |
+
@property
|
285 |
+
def is_symbolic(self):
|
286 |
+
return not all(arg.is_number for arg in self.args)
|
287 |
+
|
288 |
+
# This is modified from the _print_Matrix method
|
289 |
+
def _pretty(self, printer, *args):
|
290 |
+
m = ((printer._print(self.j1), printer._print(self.j3)),
|
291 |
+
(printer._print(self.j2), printer._print(self.j)),
|
292 |
+
(printer._print(self.j12), printer._print(self.j23)))
|
293 |
+
hsep = 2
|
294 |
+
vsep = 1
|
295 |
+
maxw = [-1]*3
|
296 |
+
for j in range(3):
|
297 |
+
maxw[j] = max([ m[j][i].width() for i in range(2) ])
|
298 |
+
D = None
|
299 |
+
for i in range(2):
|
300 |
+
D_row = None
|
301 |
+
for j in range(3):
|
302 |
+
s = m[j][i]
|
303 |
+
wdelta = maxw[j] - s.width()
|
304 |
+
wleft = wdelta //2
|
305 |
+
wright = wdelta - wleft
|
306 |
+
|
307 |
+
s = prettyForm(*s.right(' '*wright))
|
308 |
+
s = prettyForm(*s.left(' '*wleft))
|
309 |
+
|
310 |
+
if D_row is None:
|
311 |
+
D_row = s
|
312 |
+
continue
|
313 |
+
D_row = prettyForm(*D_row.right(' '*hsep))
|
314 |
+
D_row = prettyForm(*D_row.right(s))
|
315 |
+
if D is None:
|
316 |
+
D = D_row
|
317 |
+
continue
|
318 |
+
for _ in range(vsep):
|
319 |
+
D = prettyForm(*D.below(' '))
|
320 |
+
D = prettyForm(*D.below(D_row))
|
321 |
+
D = prettyForm(*D.parens(left='{', right='}'))
|
322 |
+
return D
|
323 |
+
|
324 |
+
def _latex(self, printer, *args):
|
325 |
+
label = map(printer._print, (self.j1, self.j2, self.j12,
|
326 |
+
self.j3, self.j, self.j23))
|
327 |
+
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
|
328 |
+
tuple(label)
|
329 |
+
|
330 |
+
def doit(self, **hints):
|
331 |
+
if self.is_symbolic:
|
332 |
+
raise ValueError("Coefficients must be numerical")
|
333 |
+
return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
|
334 |
+
|
335 |
+
|
336 |
+
class Wigner9j(Expr):
|
337 |
+
"""Class for the Wigner-9j symbols
|
338 |
+
|
339 |
+
See Also
|
340 |
+
========
|
341 |
+
|
342 |
+
Wigner3j: Wigner-3j symbols
|
343 |
+
|
344 |
+
"""
|
345 |
+
def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
|
346 |
+
args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
|
347 |
+
return Expr.__new__(cls, *args)
|
348 |
+
|
349 |
+
@property
|
350 |
+
def j1(self):
|
351 |
+
return self.args[0]
|
352 |
+
|
353 |
+
@property
|
354 |
+
def j2(self):
|
355 |
+
return self.args[1]
|
356 |
+
|
357 |
+
@property
|
358 |
+
def j12(self):
|
359 |
+
return self.args[2]
|
360 |
+
|
361 |
+
@property
|
362 |
+
def j3(self):
|
363 |
+
return self.args[3]
|
364 |
+
|
365 |
+
@property
|
366 |
+
def j4(self):
|
367 |
+
return self.args[4]
|
368 |
+
|
369 |
+
@property
|
370 |
+
def j34(self):
|
371 |
+
return self.args[5]
|
372 |
+
|
373 |
+
@property
|
374 |
+
def j13(self):
|
375 |
+
return self.args[6]
|
376 |
+
|
377 |
+
@property
|
378 |
+
def j24(self):
|
379 |
+
return self.args[7]
|
380 |
+
|
381 |
+
@property
|
382 |
+
def j(self):
|
383 |
+
return self.args[8]
|
384 |
+
|
385 |
+
@property
|
386 |
+
def is_symbolic(self):
|
387 |
+
return not all(arg.is_number for arg in self.args)
|
388 |
+
|
389 |
+
# This is modified from the _print_Matrix method
|
390 |
+
def _pretty(self, printer, *args):
|
391 |
+
m = (
|
392 |
+
(printer._print(
|
393 |
+
self.j1), printer._print(self.j3), printer._print(self.j13)),
|
394 |
+
(printer._print(
|
395 |
+
self.j2), printer._print(self.j4), printer._print(self.j24)),
|
396 |
+
(printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
|
397 |
+
hsep = 2
|
398 |
+
vsep = 1
|
399 |
+
maxw = [-1]*3
|
400 |
+
for j in range(3):
|
401 |
+
maxw[j] = max([ m[j][i].width() for i in range(3) ])
|
402 |
+
D = None
|
403 |
+
for i in range(3):
|
404 |
+
D_row = None
|
405 |
+
for j in range(3):
|
406 |
+
s = m[j][i]
|
407 |
+
wdelta = maxw[j] - s.width()
|
408 |
+
wleft = wdelta //2
|
409 |
+
wright = wdelta - wleft
|
410 |
+
|
411 |
+
s = prettyForm(*s.right(' '*wright))
|
412 |
+
s = prettyForm(*s.left(' '*wleft))
|
413 |
+
|
414 |
+
if D_row is None:
|
415 |
+
D_row = s
|
416 |
+
continue
|
417 |
+
D_row = prettyForm(*D_row.right(' '*hsep))
|
418 |
+
D_row = prettyForm(*D_row.right(s))
|
419 |
+
if D is None:
|
420 |
+
D = D_row
|
421 |
+
continue
|
422 |
+
for _ in range(vsep):
|
423 |
+
D = prettyForm(*D.below(' '))
|
424 |
+
D = prettyForm(*D.below(D_row))
|
425 |
+
D = prettyForm(*D.parens(left='{', right='}'))
|
426 |
+
return D
|
427 |
+
|
428 |
+
def _latex(self, printer, *args):
|
429 |
+
label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
|
430 |
+
self.j4, self.j34, self.j13, self.j24, self.j))
|
431 |
+
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
|
432 |
+
tuple(label)
|
433 |
+
|
434 |
+
def doit(self, **hints):
|
435 |
+
if self.is_symbolic:
|
436 |
+
raise ValueError("Coefficients must be numerical")
|
437 |
+
return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
|
438 |
+
|
439 |
+
|
440 |
+
def cg_simp(e):
|
441 |
+
"""Simplify and combine CG coefficients.
|
442 |
+
|
443 |
+
Explanation
|
444 |
+
===========
|
445 |
+
|
446 |
+
This function uses various symmetry and properties of sums and
|
447 |
+
products of Clebsch-Gordan coefficients to simplify statements
|
448 |
+
involving these terms [1]_.
|
449 |
+
|
450 |
+
Examples
|
451 |
+
========
|
452 |
+
|
453 |
+
Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
|
454 |
+
2*a+1
|
455 |
+
|
456 |
+
>>> from sympy.physics.quantum.cg import CG, cg_simp
|
457 |
+
>>> a = CG(1,1,0,0,1,1)
|
458 |
+
>>> b = CG(1,0,0,0,1,0)
|
459 |
+
>>> c = CG(1,-1,0,0,1,-1)
|
460 |
+
>>> cg_simp(a+b+c)
|
461 |
+
3
|
462 |
+
|
463 |
+
See Also
|
464 |
+
========
|
465 |
+
|
466 |
+
CG: Clebsh-Gordan coefficients
|
467 |
+
|
468 |
+
References
|
469 |
+
==========
|
470 |
+
|
471 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
472 |
+
"""
|
473 |
+
if isinstance(e, Add):
|
474 |
+
return _cg_simp_add(e)
|
475 |
+
elif isinstance(e, Sum):
|
476 |
+
return _cg_simp_sum(e)
|
477 |
+
elif isinstance(e, Mul):
|
478 |
+
return Mul(*[cg_simp(arg) for arg in e.args])
|
479 |
+
elif isinstance(e, Pow):
|
480 |
+
return Pow(cg_simp(e.base), e.exp)
|
481 |
+
else:
|
482 |
+
return e
|
483 |
+
|
484 |
+
|
485 |
+
def _cg_simp_add(e):
|
486 |
+
#TODO: Improve simplification method
|
487 |
+
"""Takes a sum of terms involving Clebsch-Gordan coefficients and
|
488 |
+
simplifies the terms.
|
489 |
+
|
490 |
+
Explanation
|
491 |
+
===========
|
492 |
+
|
493 |
+
First, we create two lists, cg_part, which is all the terms involving CG
|
494 |
+
coefficients, and other_part, which is all other terms. The cg_part list
|
495 |
+
is then passed to the simplification methods, which return the new cg_part
|
496 |
+
and any additional terms that are added to other_part
|
497 |
+
"""
|
498 |
+
cg_part = []
|
499 |
+
other_part = []
|
500 |
+
|
501 |
+
e = expand(e)
|
502 |
+
for arg in e.args:
|
503 |
+
if arg.has(CG):
|
504 |
+
if isinstance(arg, Sum):
|
505 |
+
other_part.append(_cg_simp_sum(arg))
|
506 |
+
elif isinstance(arg, Mul):
|
507 |
+
terms = 1
|
508 |
+
for term in arg.args:
|
509 |
+
if isinstance(term, Sum):
|
510 |
+
terms *= _cg_simp_sum(term)
|
511 |
+
else:
|
512 |
+
terms *= term
|
513 |
+
if terms.has(CG):
|
514 |
+
cg_part.append(terms)
|
515 |
+
else:
|
516 |
+
other_part.append(terms)
|
517 |
+
else:
|
518 |
+
cg_part.append(arg)
|
519 |
+
else:
|
520 |
+
other_part.append(arg)
|
521 |
+
|
522 |
+
cg_part, other = _check_varsh_871_1(cg_part)
|
523 |
+
other_part.append(other)
|
524 |
+
cg_part, other = _check_varsh_871_2(cg_part)
|
525 |
+
other_part.append(other)
|
526 |
+
cg_part, other = _check_varsh_872_9(cg_part)
|
527 |
+
other_part.append(other)
|
528 |
+
return Add(*cg_part) + Add(*other_part)
|
529 |
+
|
530 |
+
|
531 |
+
def _check_varsh_871_1(term_list):
|
532 |
+
# Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
|
533 |
+
a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
|
534 |
+
expr = lt*CG(a, alpha, b, 0, a, alpha)
|
535 |
+
simp = (2*a + 1)*KroneckerDelta(b, 0)
|
536 |
+
sign = lt/abs(lt)
|
537 |
+
build_expr = 2*a + 1
|
538 |
+
index_expr = a + alpha
|
539 |
+
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
|
540 |
+
|
541 |
+
|
542 |
+
def _check_varsh_871_2(term_list):
|
543 |
+
# Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
|
544 |
+
a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
|
545 |
+
expr = lt*CG(a, alpha, a, -alpha, c, 0)
|
546 |
+
simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
|
547 |
+
sign = (-1)**(a - alpha)*lt/abs(lt)
|
548 |
+
build_expr = 2*a + 1
|
549 |
+
index_expr = a + alpha
|
550 |
+
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
|
551 |
+
|
552 |
+
|
553 |
+
def _check_varsh_872_9(term_list):
|
554 |
+
# Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
|
555 |
+
a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
|
556 |
+
'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
|
557 |
+
# Case alpha==alphap, beta==betap
|
558 |
+
|
559 |
+
# For numerical alpha,beta
|
560 |
+
expr = lt*CG(a, alpha, b, beta, c, gamma)**2
|
561 |
+
simp = S.One
|
562 |
+
sign = lt/abs(lt)
|
563 |
+
x = abs(a - b)
|
564 |
+
y = abs(alpha + beta)
|
565 |
+
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
|
566 |
+
index_expr = a + b - c
|
567 |
+
term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
|
568 |
+
|
569 |
+
# For symbolic alpha,beta
|
570 |
+
x = abs(a - b)
|
571 |
+
y = a + b
|
572 |
+
build_expr = (y + 1 - x)*(x + y + 1)
|
573 |
+
index_expr = (c - x)*(x + c) + c + gamma
|
574 |
+
term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
|
575 |
+
|
576 |
+
# Case alpha!=alphap or beta!=betap
|
577 |
+
# Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
|
578 |
+
# For numerical alpha,alphap,beta,betap
|
579 |
+
expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
|
580 |
+
simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
|
581 |
+
sign = S.One
|
582 |
+
x = abs(a - b)
|
583 |
+
y = abs(alpha + beta)
|
584 |
+
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
|
585 |
+
index_expr = a + b - c
|
586 |
+
term_list, other3 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
|
587 |
+
|
588 |
+
# For symbolic alpha,alphap,beta,betap
|
589 |
+
x = abs(a - b)
|
590 |
+
y = a + b
|
591 |
+
build_expr = (y + 1 - x)*(x + y + 1)
|
592 |
+
index_expr = (c - x)*(x + c) + c + gamma
|
593 |
+
term_list, other4 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
|
594 |
+
|
595 |
+
return term_list, other1 + other2 + other4
|
596 |
+
|
597 |
+
|
598 |
+
def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
|
599 |
+
""" Checks for simplifications that can be made, returning a tuple of the
|
600 |
+
simplified list of terms and any terms generated by simplification.
|
601 |
+
|
602 |
+
Parameters
|
603 |
+
==========
|
604 |
+
|
605 |
+
expr: expression
|
606 |
+
The expression with Wild terms that will be matched to the terms in
|
607 |
+
the sum
|
608 |
+
|
609 |
+
simp: expression
|
610 |
+
The expression with Wild terms that is substituted in place of the CG
|
611 |
+
terms in the case of simplification
|
612 |
+
|
613 |
+
sign: expression
|
614 |
+
The expression with Wild terms denoting the sign that is on expr that
|
615 |
+
must match
|
616 |
+
|
617 |
+
lt: expression
|
618 |
+
The expression with Wild terms that gives the leading term of the
|
619 |
+
matched expr
|
620 |
+
|
621 |
+
term_list: list
|
622 |
+
A list of all of the terms is the sum to be simplified
|
623 |
+
|
624 |
+
variables: list
|
625 |
+
A list of all the variables that appears in expr
|
626 |
+
|
627 |
+
dep_variables: list
|
628 |
+
A list of the variables that must match for all the terms in the sum,
|
629 |
+
i.e. the dependent variables
|
630 |
+
|
631 |
+
build_index_expr: expression
|
632 |
+
Expression with Wild terms giving the number of elements in cg_index
|
633 |
+
|
634 |
+
index_expr: expression
|
635 |
+
Expression with Wild terms giving the index terms have when storing
|
636 |
+
them to cg_index
|
637 |
+
|
638 |
+
"""
|
639 |
+
other_part = 0
|
640 |
+
i = 0
|
641 |
+
while i < len(term_list):
|
642 |
+
sub_1 = _check_cg(term_list[i], expr, len(variables))
|
643 |
+
if sub_1 is None:
|
644 |
+
i += 1
|
645 |
+
continue
|
646 |
+
if not build_index_expr.subs(sub_1).is_number:
|
647 |
+
i += 1
|
648 |
+
continue
|
649 |
+
sub_dep = [(x, sub_1[x]) for x in dep_variables]
|
650 |
+
cg_index = [None]*build_index_expr.subs(sub_1)
|
651 |
+
for j in range(i, len(term_list)):
|
652 |
+
sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
|
653 |
+
if sub_2 is None:
|
654 |
+
continue
|
655 |
+
if not index_expr.subs(sub_dep).subs(sub_2).is_number:
|
656 |
+
continue
|
657 |
+
cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
|
658 |
+
if not any(i is None for i in cg_index):
|
659 |
+
min_lt = min(*[ abs(term[2]) for term in cg_index ])
|
660 |
+
indices = [ term[0] for term in cg_index]
|
661 |
+
indices.sort()
|
662 |
+
indices.reverse()
|
663 |
+
[ term_list.pop(j) for j in indices ]
|
664 |
+
for term in cg_index:
|
665 |
+
if abs(term[2]) > min_lt:
|
666 |
+
term_list.append( (term[2] - min_lt*term[3])*term[1] )
|
667 |
+
other_part += min_lt*(sign*simp).subs(sub_1)
|
668 |
+
else:
|
669 |
+
i += 1
|
670 |
+
return term_list, other_part
|
671 |
+
|
672 |
+
|
673 |
+
def _check_cg(cg_term, expr, length, sign=None):
|
674 |
+
"""Checks whether a term matches the given expression"""
|
675 |
+
# TODO: Check for symmetries
|
676 |
+
matches = cg_term.match(expr)
|
677 |
+
if matches is None:
|
678 |
+
return
|
679 |
+
if sign is not None:
|
680 |
+
if not isinstance(sign, tuple):
|
681 |
+
raise TypeError('sign must be a tuple')
|
682 |
+
if not sign[0] == (sign[1]).subs(matches):
|
683 |
+
return
|
684 |
+
if len(matches) == length:
|
685 |
+
return matches
|
686 |
+
|
687 |
+
|
688 |
+
def _cg_simp_sum(e):
|
689 |
+
e = _check_varsh_sum_871_1(e)
|
690 |
+
e = _check_varsh_sum_871_2(e)
|
691 |
+
e = _check_varsh_sum_872_4(e)
|
692 |
+
return e
|
693 |
+
|
694 |
+
|
695 |
+
def _check_varsh_sum_871_1(e):
|
696 |
+
a = Wild('a')
|
697 |
+
alpha = symbols('alpha')
|
698 |
+
b = Wild('b')
|
699 |
+
match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
|
700 |
+
if match is not None and len(match) == 2:
|
701 |
+
return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
|
702 |
+
return e
|
703 |
+
|
704 |
+
|
705 |
+
def _check_varsh_sum_871_2(e):
|
706 |
+
a = Wild('a')
|
707 |
+
alpha = symbols('alpha')
|
708 |
+
c = Wild('c')
|
709 |
+
match = e.match(
|
710 |
+
Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
|
711 |
+
if match is not None and len(match) == 2:
|
712 |
+
return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
|
713 |
+
return e
|
714 |
+
|
715 |
+
|
716 |
+
def _check_varsh_sum_872_4(e):
|
717 |
+
alpha = symbols('alpha')
|
718 |
+
beta = symbols('beta')
|
719 |
+
a = Wild('a')
|
720 |
+
b = Wild('b')
|
721 |
+
c = Wild('c')
|
722 |
+
cp = Wild('cp')
|
723 |
+
gamma = Wild('gamma')
|
724 |
+
gammap = Wild('gammap')
|
725 |
+
cg1 = CG(a, alpha, b, beta, c, gamma)
|
726 |
+
cg2 = CG(a, alpha, b, beta, cp, gammap)
|
727 |
+
match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
|
728 |
+
if match1 is not None and len(match1) == 6:
|
729 |
+
return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
|
730 |
+
match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
|
731 |
+
if match2 is not None and len(match2) == 4:
|
732 |
+
return S.One
|
733 |
+
return e
|
734 |
+
|
735 |
+
|
736 |
+
def _cg_list(term):
|
737 |
+
if isinstance(term, CG):
|
738 |
+
return (term,), 1, 1
|
739 |
+
cg = []
|
740 |
+
coeff = 1
|
741 |
+
if not isinstance(term, (Mul, Pow)):
|
742 |
+
raise NotImplementedError('term must be CG, Add, Mul or Pow')
|
743 |
+
if isinstance(term, Pow) and term.exp.is_number:
|
744 |
+
if term.exp.is_number:
|
745 |
+
[ cg.append(term.base) for _ in range(term.exp) ]
|
746 |
+
else:
|
747 |
+
return (term,), 1, 1
|
748 |
+
if isinstance(term, Mul):
|
749 |
+
for arg in term.args:
|
750 |
+
if isinstance(arg, CG):
|
751 |
+
cg.append(arg)
|
752 |
+
else:
|
753 |
+
coeff *= arg
|
754 |
+
return cg, coeff, coeff/abs(coeff)
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py
ADDED
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Matplotlib based plotting of quantum circuits.
|
2 |
+
|
3 |
+
Todo:
|
4 |
+
|
5 |
+
* Optimize printing of large circuits.
|
6 |
+
* Get this to work with single gates.
|
7 |
+
* Do a better job checking the form of circuits to make sure it is a Mul of
|
8 |
+
Gates.
|
9 |
+
* Get multi-target gates plotting.
|
10 |
+
* Get initial and final states to plot.
|
11 |
+
* Get measurements to plot. Might need to rethink measurement as a gate
|
12 |
+
issue.
|
13 |
+
* Get scale and figsize to be handled in a better way.
|
14 |
+
* Write some tests/examples!
|
15 |
+
"""
|
16 |
+
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
from sympy.core.mul import Mul
|
20 |
+
from sympy.external import import_module
|
21 |
+
from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS
|
22 |
+
|
23 |
+
|
24 |
+
__all__ = [
|
25 |
+
'CircuitPlot',
|
26 |
+
'circuit_plot',
|
27 |
+
'labeller',
|
28 |
+
'Mz',
|
29 |
+
'Mx',
|
30 |
+
'CreateOneQubitGate',
|
31 |
+
'CreateCGate',
|
32 |
+
]
|
33 |
+
|
34 |
+
np = import_module('numpy')
|
35 |
+
matplotlib = import_module(
|
36 |
+
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
|
37 |
+
catch=(RuntimeError,)) # This is raised in environments that have no display.
|
38 |
+
|
39 |
+
if np and matplotlib:
|
40 |
+
pyplot = matplotlib.pyplot
|
41 |
+
Line2D = matplotlib.lines.Line2D
|
42 |
+
Circle = matplotlib.patches.Circle
|
43 |
+
|
44 |
+
#from matplotlib import rc
|
45 |
+
#rc('text',usetex=True)
|
46 |
+
|
47 |
+
class CircuitPlot:
|
48 |
+
"""A class for managing a circuit plot."""
|
49 |
+
|
50 |
+
scale = 1.0
|
51 |
+
fontsize = 20.0
|
52 |
+
linewidth = 1.0
|
53 |
+
control_radius = 0.05
|
54 |
+
not_radius = 0.15
|
55 |
+
swap_delta = 0.05
|
56 |
+
labels: list[str] = []
|
57 |
+
inits: dict[str, str] = {}
|
58 |
+
label_buffer = 0.5
|
59 |
+
|
60 |
+
def __init__(self, c, nqubits, **kwargs):
|
61 |
+
if not np or not matplotlib:
|
62 |
+
raise ImportError('numpy or matplotlib not available.')
|
63 |
+
self.circuit = c
|
64 |
+
self.ngates = len(self.circuit.args)
|
65 |
+
self.nqubits = nqubits
|
66 |
+
self.update(kwargs)
|
67 |
+
self._create_grid()
|
68 |
+
self._create_figure()
|
69 |
+
self._plot_wires()
|
70 |
+
self._plot_gates()
|
71 |
+
self._finish()
|
72 |
+
|
73 |
+
def update(self, kwargs):
|
74 |
+
"""Load the kwargs into the instance dict."""
|
75 |
+
self.__dict__.update(kwargs)
|
76 |
+
|
77 |
+
def _create_grid(self):
|
78 |
+
"""Create the grid of wires."""
|
79 |
+
scale = self.scale
|
80 |
+
wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float)
|
81 |
+
gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float)
|
82 |
+
self._wire_grid = wire_grid
|
83 |
+
self._gate_grid = gate_grid
|
84 |
+
|
85 |
+
def _create_figure(self):
|
86 |
+
"""Create the main matplotlib figure."""
|
87 |
+
self._figure = pyplot.figure(
|
88 |
+
figsize=(self.ngates*self.scale, self.nqubits*self.scale),
|
89 |
+
facecolor='w',
|
90 |
+
edgecolor='w'
|
91 |
+
)
|
92 |
+
ax = self._figure.add_subplot(
|
93 |
+
1, 1, 1,
|
94 |
+
frameon=True
|
95 |
+
)
|
96 |
+
ax.set_axis_off()
|
97 |
+
offset = 0.5*self.scale
|
98 |
+
ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset)
|
99 |
+
ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset)
|
100 |
+
ax.set_aspect('equal')
|
101 |
+
self._axes = ax
|
102 |
+
|
103 |
+
def _plot_wires(self):
|
104 |
+
"""Plot the wires of the circuit diagram."""
|
105 |
+
xstart = self._gate_grid[0]
|
106 |
+
xstop = self._gate_grid[-1]
|
107 |
+
xdata = (xstart - self.scale, xstop + self.scale)
|
108 |
+
for i in range(self.nqubits):
|
109 |
+
ydata = (self._wire_grid[i], self._wire_grid[i])
|
110 |
+
line = Line2D(
|
111 |
+
xdata, ydata,
|
112 |
+
color='k',
|
113 |
+
lw=self.linewidth
|
114 |
+
)
|
115 |
+
self._axes.add_line(line)
|
116 |
+
if self.labels:
|
117 |
+
init_label_buffer = 0
|
118 |
+
if self.inits.get(self.labels[i]): init_label_buffer = 0.25
|
119 |
+
self._axes.text(
|
120 |
+
xdata[0]-self.label_buffer-init_label_buffer,ydata[0],
|
121 |
+
render_label(self.labels[i],self.inits),
|
122 |
+
size=self.fontsize,
|
123 |
+
color='k',ha='center',va='center')
|
124 |
+
self._plot_measured_wires()
|
125 |
+
|
126 |
+
def _plot_measured_wires(self):
|
127 |
+
ismeasured = self._measurements()
|
128 |
+
xstop = self._gate_grid[-1]
|
129 |
+
dy = 0.04 # amount to shift wires when doubled
|
130 |
+
# Plot doubled wires after they are measured
|
131 |
+
for im in ismeasured:
|
132 |
+
xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale)
|
133 |
+
ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy)
|
134 |
+
line = Line2D(
|
135 |
+
xdata, ydata,
|
136 |
+
color='k',
|
137 |
+
lw=self.linewidth
|
138 |
+
)
|
139 |
+
self._axes.add_line(line)
|
140 |
+
# Also double any controlled lines off these wires
|
141 |
+
for i,g in enumerate(self._gates()):
|
142 |
+
if isinstance(g, (CGate, CGateS)):
|
143 |
+
wires = g.controls + g.targets
|
144 |
+
for wire in wires:
|
145 |
+
if wire in ismeasured and \
|
146 |
+
self._gate_grid[i] > self._gate_grid[ismeasured[wire]]:
|
147 |
+
ydata = min(wires), max(wires)
|
148 |
+
xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy
|
149 |
+
line = Line2D(
|
150 |
+
xdata, ydata,
|
151 |
+
color='k',
|
152 |
+
lw=self.linewidth
|
153 |
+
)
|
154 |
+
self._axes.add_line(line)
|
155 |
+
def _gates(self):
|
156 |
+
"""Create a list of all gates in the circuit plot."""
|
157 |
+
gates = []
|
158 |
+
if isinstance(self.circuit, Mul):
|
159 |
+
for g in reversed(self.circuit.args):
|
160 |
+
if isinstance(g, Gate):
|
161 |
+
gates.append(g)
|
162 |
+
elif isinstance(self.circuit, Gate):
|
163 |
+
gates.append(self.circuit)
|
164 |
+
return gates
|
165 |
+
|
166 |
+
def _plot_gates(self):
|
167 |
+
"""Iterate through the gates and plot each of them."""
|
168 |
+
for i, gate in enumerate(self._gates()):
|
169 |
+
gate.plot_gate(self, i)
|
170 |
+
|
171 |
+
def _measurements(self):
|
172 |
+
"""Return a dict ``{i:j}`` where i is the index of the wire that has
|
173 |
+
been measured, and j is the gate where the wire is measured.
|
174 |
+
"""
|
175 |
+
ismeasured = {}
|
176 |
+
for i,g in enumerate(self._gates()):
|
177 |
+
if getattr(g,'measurement',False):
|
178 |
+
for target in g.targets:
|
179 |
+
if target in ismeasured:
|
180 |
+
if ismeasured[target] > i:
|
181 |
+
ismeasured[target] = i
|
182 |
+
else:
|
183 |
+
ismeasured[target] = i
|
184 |
+
return ismeasured
|
185 |
+
|
186 |
+
def _finish(self):
|
187 |
+
# Disable clipping to make panning work well for large circuits.
|
188 |
+
for o in self._figure.findobj():
|
189 |
+
o.set_clip_on(False)
|
190 |
+
|
191 |
+
def one_qubit_box(self, t, gate_idx, wire_idx):
|
192 |
+
"""Draw a box for a single qubit gate."""
|
193 |
+
x = self._gate_grid[gate_idx]
|
194 |
+
y = self._wire_grid[wire_idx]
|
195 |
+
self._axes.text(
|
196 |
+
x, y, t,
|
197 |
+
color='k',
|
198 |
+
ha='center',
|
199 |
+
va='center',
|
200 |
+
bbox={"ec": 'k', "fc": 'w', "fill": True, "lw": self.linewidth},
|
201 |
+
size=self.fontsize
|
202 |
+
)
|
203 |
+
|
204 |
+
def two_qubit_box(self, t, gate_idx, wire_idx):
|
205 |
+
"""Draw a box for a two qubit gate. Does not work yet.
|
206 |
+
"""
|
207 |
+
# x = self._gate_grid[gate_idx]
|
208 |
+
# y = self._wire_grid[wire_idx]+0.5
|
209 |
+
print(self._gate_grid)
|
210 |
+
print(self._wire_grid)
|
211 |
+
# unused:
|
212 |
+
# obj = self._axes.text(
|
213 |
+
# x, y, t,
|
214 |
+
# color='k',
|
215 |
+
# ha='center',
|
216 |
+
# va='center',
|
217 |
+
# bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
|
218 |
+
# size=self.fontsize
|
219 |
+
# )
|
220 |
+
|
221 |
+
def control_line(self, gate_idx, min_wire, max_wire):
|
222 |
+
"""Draw a vertical control line."""
|
223 |
+
xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx])
|
224 |
+
ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire])
|
225 |
+
line = Line2D(
|
226 |
+
xdata, ydata,
|
227 |
+
color='k',
|
228 |
+
lw=self.linewidth
|
229 |
+
)
|
230 |
+
self._axes.add_line(line)
|
231 |
+
|
232 |
+
def control_point(self, gate_idx, wire_idx):
|
233 |
+
"""Draw a control point."""
|
234 |
+
x = self._gate_grid[gate_idx]
|
235 |
+
y = self._wire_grid[wire_idx]
|
236 |
+
radius = self.control_radius
|
237 |
+
c = Circle(
|
238 |
+
(x, y),
|
239 |
+
radius*self.scale,
|
240 |
+
ec='k',
|
241 |
+
fc='k',
|
242 |
+
fill=True,
|
243 |
+
lw=self.linewidth
|
244 |
+
)
|
245 |
+
self._axes.add_patch(c)
|
246 |
+
|
247 |
+
def not_point(self, gate_idx, wire_idx):
|
248 |
+
"""Draw a NOT gates as the circle with plus in the middle."""
|
249 |
+
x = self._gate_grid[gate_idx]
|
250 |
+
y = self._wire_grid[wire_idx]
|
251 |
+
radius = self.not_radius
|
252 |
+
c = Circle(
|
253 |
+
(x, y),
|
254 |
+
radius,
|
255 |
+
ec='k',
|
256 |
+
fc='w',
|
257 |
+
fill=False,
|
258 |
+
lw=self.linewidth
|
259 |
+
)
|
260 |
+
self._axes.add_patch(c)
|
261 |
+
l = Line2D(
|
262 |
+
(x, x), (y - radius, y + radius),
|
263 |
+
color='k',
|
264 |
+
lw=self.linewidth
|
265 |
+
)
|
266 |
+
self._axes.add_line(l)
|
267 |
+
|
268 |
+
def swap_point(self, gate_idx, wire_idx):
|
269 |
+
"""Draw a swap point as a cross."""
|
270 |
+
x = self._gate_grid[gate_idx]
|
271 |
+
y = self._wire_grid[wire_idx]
|
272 |
+
d = self.swap_delta
|
273 |
+
l1 = Line2D(
|
274 |
+
(x - d, x + d),
|
275 |
+
(y - d, y + d),
|
276 |
+
color='k',
|
277 |
+
lw=self.linewidth
|
278 |
+
)
|
279 |
+
l2 = Line2D(
|
280 |
+
(x - d, x + d),
|
281 |
+
(y + d, y - d),
|
282 |
+
color='k',
|
283 |
+
lw=self.linewidth
|
284 |
+
)
|
285 |
+
self._axes.add_line(l1)
|
286 |
+
self._axes.add_line(l2)
|
287 |
+
|
288 |
+
def circuit_plot(c, nqubits, **kwargs):
|
289 |
+
"""Draw the circuit diagram for the circuit with nqubits.
|
290 |
+
|
291 |
+
Parameters
|
292 |
+
==========
|
293 |
+
|
294 |
+
c : circuit
|
295 |
+
The circuit to plot. Should be a product of Gate instances.
|
296 |
+
nqubits : int
|
297 |
+
The number of qubits to include in the circuit. Must be at least
|
298 |
+
as big as the largest ``min_qubits`` of the gates.
|
299 |
+
"""
|
300 |
+
return CircuitPlot(c, nqubits, **kwargs)
|
301 |
+
|
302 |
+
def render_label(label, inits={}):
|
303 |
+
"""Slightly more flexible way to render labels.
|
304 |
+
|
305 |
+
>>> from sympy.physics.quantum.circuitplot import render_label
|
306 |
+
>>> render_label('q0')
|
307 |
+
'$\\\\left|q0\\\\right\\\\rangle$'
|
308 |
+
>>> render_label('q0', {'q0':'0'})
|
309 |
+
'$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$'
|
310 |
+
"""
|
311 |
+
init = inits.get(label)
|
312 |
+
if init:
|
313 |
+
return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init)
|
314 |
+
return r'$\left|%s\right\rangle$' % label
|
315 |
+
|
316 |
+
def labeller(n, symbol='q'):
|
317 |
+
"""Autogenerate labels for wires of quantum circuits.
|
318 |
+
|
319 |
+
Parameters
|
320 |
+
==========
|
321 |
+
|
322 |
+
n : int
|
323 |
+
number of qubits in the circuit.
|
324 |
+
symbol : string
|
325 |
+
A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
|
326 |
+
|
327 |
+
>>> from sympy.physics.quantum.circuitplot import labeller
|
328 |
+
>>> labeller(2)
|
329 |
+
['q_1', 'q_0']
|
330 |
+
>>> labeller(3,'j')
|
331 |
+
['j_2', 'j_1', 'j_0']
|
332 |
+
"""
|
333 |
+
return ['%s_%d' % (symbol,n-i-1) for i in range(n)]
|
334 |
+
|
335 |
+
class Mz(OneQubitGate):
|
336 |
+
"""Mock-up of a z measurement gate.
|
337 |
+
|
338 |
+
This is in circuitplot rather than gate.py because it's not a real
|
339 |
+
gate, it just draws one.
|
340 |
+
"""
|
341 |
+
measurement = True
|
342 |
+
gate_name='Mz'
|
343 |
+
gate_name_latex='M_z'
|
344 |
+
|
345 |
+
class Mx(OneQubitGate):
|
346 |
+
"""Mock-up of an x measurement gate.
|
347 |
+
|
348 |
+
This is in circuitplot rather than gate.py because it's not a real
|
349 |
+
gate, it just draws one.
|
350 |
+
"""
|
351 |
+
measurement = True
|
352 |
+
gate_name='Mx'
|
353 |
+
gate_name_latex='M_x'
|
354 |
+
|
355 |
+
class CreateOneQubitGate(type):
|
356 |
+
def __new__(mcl, name, latexname=None):
|
357 |
+
if not latexname:
|
358 |
+
latexname = name
|
359 |
+
return type(name + "Gate", (OneQubitGate,),
|
360 |
+
{'gate_name': name, 'gate_name_latex': latexname})
|
361 |
+
|
362 |
+
def CreateCGate(name, latexname=None):
|
363 |
+
"""Use a lexical closure to make a controlled gate.
|
364 |
+
"""
|
365 |
+
if not latexname:
|
366 |
+
latexname = name
|
367 |
+
onequbitgate = CreateOneQubitGate(name, latexname)
|
368 |
+
def ControlledGate(ctrls,target):
|
369 |
+
return CGate(tuple(ctrls),onequbitgate(target))
|
370 |
+
return ControlledGate
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py
ADDED
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Primitive circuit operations on quantum circuits."""
|
2 |
+
|
3 |
+
from functools import reduce
|
4 |
+
|
5 |
+
from sympy.core.sorting import default_sort_key
|
6 |
+
from sympy.core.containers import Tuple
|
7 |
+
from sympy.core.mul import Mul
|
8 |
+
from sympy.core.symbol import Symbol
|
9 |
+
from sympy.core.sympify import sympify
|
10 |
+
from sympy.utilities import numbered_symbols
|
11 |
+
from sympy.physics.quantum.gate import Gate
|
12 |
+
|
13 |
+
__all__ = [
|
14 |
+
'kmp_table',
|
15 |
+
'find_subcircuit',
|
16 |
+
'replace_subcircuit',
|
17 |
+
'convert_to_symbolic_indices',
|
18 |
+
'convert_to_real_indices',
|
19 |
+
'random_reduce',
|
20 |
+
'random_insert'
|
21 |
+
]
|
22 |
+
|
23 |
+
|
24 |
+
def kmp_table(word):
|
25 |
+
"""Build the 'partial match' table of the Knuth-Morris-Pratt algorithm.
|
26 |
+
|
27 |
+
Note: This is applicable to strings or
|
28 |
+
quantum circuits represented as tuples.
|
29 |
+
"""
|
30 |
+
|
31 |
+
# Current position in subcircuit
|
32 |
+
pos = 2
|
33 |
+
# Beginning position of candidate substring that
|
34 |
+
# may reappear later in word
|
35 |
+
cnd = 0
|
36 |
+
# The 'partial match' table that helps one determine
|
37 |
+
# the next location to start substring search
|
38 |
+
table = []
|
39 |
+
table.append(-1)
|
40 |
+
table.append(0)
|
41 |
+
|
42 |
+
while pos < len(word):
|
43 |
+
if word[pos - 1] == word[cnd]:
|
44 |
+
cnd = cnd + 1
|
45 |
+
table.append(cnd)
|
46 |
+
pos = pos + 1
|
47 |
+
elif cnd > 0:
|
48 |
+
cnd = table[cnd]
|
49 |
+
else:
|
50 |
+
table.append(0)
|
51 |
+
pos = pos + 1
|
52 |
+
|
53 |
+
return table
|
54 |
+
|
55 |
+
|
56 |
+
def find_subcircuit(circuit, subcircuit, start=0, end=0):
|
57 |
+
"""Finds the subcircuit in circuit, if it exists.
|
58 |
+
|
59 |
+
Explanation
|
60 |
+
===========
|
61 |
+
|
62 |
+
If the subcircuit exists, the index of the start of
|
63 |
+
the subcircuit in circuit is returned; otherwise,
|
64 |
+
-1 is returned. The algorithm that is implemented
|
65 |
+
is the Knuth-Morris-Pratt algorithm.
|
66 |
+
|
67 |
+
Parameters
|
68 |
+
==========
|
69 |
+
|
70 |
+
circuit : tuple, Gate or Mul
|
71 |
+
A tuple of Gates or Mul representing a quantum circuit
|
72 |
+
subcircuit : tuple, Gate or Mul
|
73 |
+
A tuple of Gates or Mul to find in circuit
|
74 |
+
start : int
|
75 |
+
The location to start looking for subcircuit.
|
76 |
+
If start is the same or past end, -1 is returned.
|
77 |
+
end : int
|
78 |
+
The last place to look for a subcircuit. If end
|
79 |
+
is less than 1 (one), then the length of circuit
|
80 |
+
is taken to be end.
|
81 |
+
|
82 |
+
Examples
|
83 |
+
========
|
84 |
+
|
85 |
+
Find the first instance of a subcircuit:
|
86 |
+
|
87 |
+
>>> from sympy.physics.quantum.circuitutils import find_subcircuit
|
88 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z, H
|
89 |
+
>>> circuit = X(0)*Z(0)*Y(0)*H(0)
|
90 |
+
>>> subcircuit = Z(0)*Y(0)
|
91 |
+
>>> find_subcircuit(circuit, subcircuit)
|
92 |
+
1
|
93 |
+
|
94 |
+
Find the first instance starting at a specific position:
|
95 |
+
|
96 |
+
>>> find_subcircuit(circuit, subcircuit, start=1)
|
97 |
+
1
|
98 |
+
|
99 |
+
>>> find_subcircuit(circuit, subcircuit, start=2)
|
100 |
+
-1
|
101 |
+
|
102 |
+
>>> circuit = circuit*subcircuit
|
103 |
+
>>> find_subcircuit(circuit, subcircuit, start=2)
|
104 |
+
4
|
105 |
+
|
106 |
+
Find the subcircuit within some interval:
|
107 |
+
|
108 |
+
>>> find_subcircuit(circuit, subcircuit, start=2, end=2)
|
109 |
+
-1
|
110 |
+
"""
|
111 |
+
|
112 |
+
if isinstance(circuit, Mul):
|
113 |
+
circuit = circuit.args
|
114 |
+
|
115 |
+
if isinstance(subcircuit, Mul):
|
116 |
+
subcircuit = subcircuit.args
|
117 |
+
|
118 |
+
if len(subcircuit) == 0 or len(subcircuit) > len(circuit):
|
119 |
+
return -1
|
120 |
+
|
121 |
+
if end < 1:
|
122 |
+
end = len(circuit)
|
123 |
+
|
124 |
+
# Location in circuit
|
125 |
+
pos = start
|
126 |
+
# Location in the subcircuit
|
127 |
+
index = 0
|
128 |
+
# 'Partial match' table
|
129 |
+
table = kmp_table(subcircuit)
|
130 |
+
|
131 |
+
while (pos + index) < end:
|
132 |
+
if subcircuit[index] == circuit[pos + index]:
|
133 |
+
index = index + 1
|
134 |
+
else:
|
135 |
+
pos = pos + index - table[index]
|
136 |
+
index = table[index] if table[index] > -1 else 0
|
137 |
+
|
138 |
+
if index == len(subcircuit):
|
139 |
+
return pos
|
140 |
+
|
141 |
+
return -1
|
142 |
+
|
143 |
+
|
144 |
+
def replace_subcircuit(circuit, subcircuit, replace=None, pos=0):
|
145 |
+
"""Replaces a subcircuit with another subcircuit in circuit,
|
146 |
+
if it exists.
|
147 |
+
|
148 |
+
Explanation
|
149 |
+
===========
|
150 |
+
|
151 |
+
If multiple instances of subcircuit exists, the first instance is
|
152 |
+
replaced. The position to being searching from (if different from
|
153 |
+
0) may be optionally given. If subcircuit cannot be found, circuit
|
154 |
+
is returned.
|
155 |
+
|
156 |
+
Parameters
|
157 |
+
==========
|
158 |
+
|
159 |
+
circuit : tuple, Gate or Mul
|
160 |
+
A quantum circuit.
|
161 |
+
subcircuit : tuple, Gate or Mul
|
162 |
+
The circuit to be replaced.
|
163 |
+
replace : tuple, Gate or Mul
|
164 |
+
The replacement circuit.
|
165 |
+
pos : int
|
166 |
+
The location to start search and replace
|
167 |
+
subcircuit, if it exists. This may be used
|
168 |
+
if it is known beforehand that multiple
|
169 |
+
instances exist, and it is desirable to
|
170 |
+
replace a specific instance. If a negative number
|
171 |
+
is given, pos will be defaulted to 0.
|
172 |
+
|
173 |
+
Examples
|
174 |
+
========
|
175 |
+
|
176 |
+
Find and remove the subcircuit:
|
177 |
+
|
178 |
+
>>> from sympy.physics.quantum.circuitutils import replace_subcircuit
|
179 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z, H
|
180 |
+
>>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
|
181 |
+
>>> subcircuit = Z(0)*Y(0)
|
182 |
+
>>> replace_subcircuit(circuit, subcircuit)
|
183 |
+
(X(0), H(0), X(0), H(0), Y(0))
|
184 |
+
|
185 |
+
Remove the subcircuit given a starting search point:
|
186 |
+
|
187 |
+
>>> replace_subcircuit(circuit, subcircuit, pos=1)
|
188 |
+
(X(0), H(0), X(0), H(0), Y(0))
|
189 |
+
|
190 |
+
>>> replace_subcircuit(circuit, subcircuit, pos=2)
|
191 |
+
(X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))
|
192 |
+
|
193 |
+
Replace the subcircuit:
|
194 |
+
|
195 |
+
>>> replacement = H(0)*Z(0)
|
196 |
+
>>> replace_subcircuit(circuit, subcircuit, replace=replacement)
|
197 |
+
(X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
|
198 |
+
"""
|
199 |
+
|
200 |
+
if pos < 0:
|
201 |
+
pos = 0
|
202 |
+
|
203 |
+
if isinstance(circuit, Mul):
|
204 |
+
circuit = circuit.args
|
205 |
+
|
206 |
+
if isinstance(subcircuit, Mul):
|
207 |
+
subcircuit = subcircuit.args
|
208 |
+
|
209 |
+
if isinstance(replace, Mul):
|
210 |
+
replace = replace.args
|
211 |
+
elif replace is None:
|
212 |
+
replace = ()
|
213 |
+
|
214 |
+
# Look for the subcircuit starting at pos
|
215 |
+
loc = find_subcircuit(circuit, subcircuit, start=pos)
|
216 |
+
|
217 |
+
# If subcircuit was found
|
218 |
+
if loc > -1:
|
219 |
+
# Get the gates to the left of subcircuit
|
220 |
+
left = circuit[0:loc]
|
221 |
+
# Get the gates to the right of subcircuit
|
222 |
+
right = circuit[loc + len(subcircuit):len(circuit)]
|
223 |
+
# Recombine the left and right side gates into a circuit
|
224 |
+
circuit = left + replace + right
|
225 |
+
|
226 |
+
return circuit
|
227 |
+
|
228 |
+
|
229 |
+
def _sympify_qubit_map(mapping):
|
230 |
+
new_map = {}
|
231 |
+
for key in mapping:
|
232 |
+
new_map[key] = sympify(mapping[key])
|
233 |
+
return new_map
|
234 |
+
|
235 |
+
|
236 |
+
def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None):
|
237 |
+
"""Returns the circuit with symbolic indices and the
|
238 |
+
dictionary mapping symbolic indices to real indices.
|
239 |
+
|
240 |
+
The mapping is 1 to 1 and onto (bijective).
|
241 |
+
|
242 |
+
Parameters
|
243 |
+
==========
|
244 |
+
|
245 |
+
seq : tuple, Gate/Integer/tuple or Mul
|
246 |
+
A tuple of Gate, Integer, or tuple objects, or a Mul
|
247 |
+
start : Symbol
|
248 |
+
An optional starting symbolic index
|
249 |
+
gen : object
|
250 |
+
An optional numbered symbol generator
|
251 |
+
qubit_map : dict
|
252 |
+
An existing mapping of symbolic indices to real indices
|
253 |
+
|
254 |
+
All symbolic indices have the format 'i#', where # is
|
255 |
+
some number >= 0.
|
256 |
+
"""
|
257 |
+
|
258 |
+
if isinstance(seq, Mul):
|
259 |
+
seq = seq.args
|
260 |
+
|
261 |
+
# A numbered symbol generator
|
262 |
+
index_gen = numbered_symbols(prefix='i', start=-1)
|
263 |
+
cur_ndx = next(index_gen)
|
264 |
+
|
265 |
+
# keys are symbolic indices; values are real indices
|
266 |
+
ndx_map = {}
|
267 |
+
|
268 |
+
def create_inverse_map(symb_to_real_map):
|
269 |
+
rev_items = lambda item: (item[1], item[0])
|
270 |
+
return dict(map(rev_items, symb_to_real_map.items()))
|
271 |
+
|
272 |
+
if start is not None:
|
273 |
+
if not isinstance(start, Symbol):
|
274 |
+
msg = 'Expected Symbol for starting index, got %r.' % start
|
275 |
+
raise TypeError(msg)
|
276 |
+
cur_ndx = start
|
277 |
+
|
278 |
+
if gen is not None:
|
279 |
+
if not isinstance(gen, numbered_symbols().__class__):
|
280 |
+
msg = 'Expected a generator, got %r.' % gen
|
281 |
+
raise TypeError(msg)
|
282 |
+
index_gen = gen
|
283 |
+
|
284 |
+
if qubit_map is not None:
|
285 |
+
if not isinstance(qubit_map, dict):
|
286 |
+
msg = ('Expected dict for existing map, got ' +
|
287 |
+
'%r.' % qubit_map)
|
288 |
+
raise TypeError(msg)
|
289 |
+
ndx_map = qubit_map
|
290 |
+
|
291 |
+
ndx_map = _sympify_qubit_map(ndx_map)
|
292 |
+
# keys are real indices; keys are symbolic indices
|
293 |
+
inv_map = create_inverse_map(ndx_map)
|
294 |
+
|
295 |
+
sym_seq = ()
|
296 |
+
for item in seq:
|
297 |
+
# Nested items, so recurse
|
298 |
+
if isinstance(item, Gate):
|
299 |
+
result = convert_to_symbolic_indices(item.args,
|
300 |
+
qubit_map=ndx_map,
|
301 |
+
start=cur_ndx,
|
302 |
+
gen=index_gen)
|
303 |
+
sym_item, new_map, cur_ndx, index_gen = result
|
304 |
+
ndx_map.update(new_map)
|
305 |
+
inv_map = create_inverse_map(ndx_map)
|
306 |
+
|
307 |
+
elif isinstance(item, (tuple, Tuple)):
|
308 |
+
result = convert_to_symbolic_indices(item,
|
309 |
+
qubit_map=ndx_map,
|
310 |
+
start=cur_ndx,
|
311 |
+
gen=index_gen)
|
312 |
+
sym_item, new_map, cur_ndx, index_gen = result
|
313 |
+
ndx_map.update(new_map)
|
314 |
+
inv_map = create_inverse_map(ndx_map)
|
315 |
+
|
316 |
+
elif item in inv_map:
|
317 |
+
sym_item = inv_map[item]
|
318 |
+
|
319 |
+
else:
|
320 |
+
cur_ndx = next(gen)
|
321 |
+
ndx_map[cur_ndx] = item
|
322 |
+
inv_map[item] = cur_ndx
|
323 |
+
sym_item = cur_ndx
|
324 |
+
|
325 |
+
if isinstance(item, Gate):
|
326 |
+
sym_item = item.__class__(*sym_item)
|
327 |
+
|
328 |
+
sym_seq = sym_seq + (sym_item,)
|
329 |
+
|
330 |
+
return sym_seq, ndx_map, cur_ndx, index_gen
|
331 |
+
|
332 |
+
|
333 |
+
def convert_to_real_indices(seq, qubit_map):
|
334 |
+
"""Returns the circuit with real indices.
|
335 |
+
|
336 |
+
Parameters
|
337 |
+
==========
|
338 |
+
|
339 |
+
seq : tuple, Gate/Integer/tuple or Mul
|
340 |
+
A tuple of Gate, Integer, or tuple objects or a Mul
|
341 |
+
qubit_map : dict
|
342 |
+
A dictionary mapping symbolic indices to real indices.
|
343 |
+
|
344 |
+
Examples
|
345 |
+
========
|
346 |
+
|
347 |
+
Change the symbolic indices to real integers:
|
348 |
+
|
349 |
+
>>> from sympy import symbols
|
350 |
+
>>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
|
351 |
+
>>> from sympy.physics.quantum.gate import X, Y, H
|
352 |
+
>>> i0, i1 = symbols('i:2')
|
353 |
+
>>> index_map = {i0 : 0, i1 : 1}
|
354 |
+
>>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
|
355 |
+
(X(0), Y(1), H(0), X(1))
|
356 |
+
"""
|
357 |
+
|
358 |
+
if isinstance(seq, Mul):
|
359 |
+
seq = seq.args
|
360 |
+
|
361 |
+
if not isinstance(qubit_map, dict):
|
362 |
+
msg = 'Expected dict for qubit_map, got %r.' % qubit_map
|
363 |
+
raise TypeError(msg)
|
364 |
+
|
365 |
+
qubit_map = _sympify_qubit_map(qubit_map)
|
366 |
+
real_seq = ()
|
367 |
+
for item in seq:
|
368 |
+
# Nested items, so recurse
|
369 |
+
if isinstance(item, Gate):
|
370 |
+
real_item = convert_to_real_indices(item.args, qubit_map)
|
371 |
+
|
372 |
+
elif isinstance(item, (tuple, Tuple)):
|
373 |
+
real_item = convert_to_real_indices(item, qubit_map)
|
374 |
+
|
375 |
+
else:
|
376 |
+
real_item = qubit_map[item]
|
377 |
+
|
378 |
+
if isinstance(item, Gate):
|
379 |
+
real_item = item.__class__(*real_item)
|
380 |
+
|
381 |
+
real_seq = real_seq + (real_item,)
|
382 |
+
|
383 |
+
return real_seq
|
384 |
+
|
385 |
+
|
386 |
+
def random_reduce(circuit, gate_ids, seed=None):
|
387 |
+
"""Shorten the length of a quantum circuit.
|
388 |
+
|
389 |
+
Explanation
|
390 |
+
===========
|
391 |
+
|
392 |
+
random_reduce looks for circuit identities in circuit, randomly chooses
|
393 |
+
one to remove, and returns a shorter yet equivalent circuit. If no
|
394 |
+
identities are found, the same circuit is returned.
|
395 |
+
|
396 |
+
Parameters
|
397 |
+
==========
|
398 |
+
|
399 |
+
circuit : Gate tuple of Mul
|
400 |
+
A tuple of Gates representing a quantum circuit
|
401 |
+
gate_ids : list, GateIdentity
|
402 |
+
List of gate identities to find in circuit
|
403 |
+
seed : int or list
|
404 |
+
seed used for _randrange; to override the random selection, provide a
|
405 |
+
list of integers: the elements of gate_ids will be tested in the order
|
406 |
+
given by the list
|
407 |
+
|
408 |
+
"""
|
409 |
+
from sympy.core.random import _randrange
|
410 |
+
|
411 |
+
if not gate_ids:
|
412 |
+
return circuit
|
413 |
+
|
414 |
+
if isinstance(circuit, Mul):
|
415 |
+
circuit = circuit.args
|
416 |
+
|
417 |
+
ids = flatten_ids(gate_ids)
|
418 |
+
|
419 |
+
# Create the random integer generator with the seed
|
420 |
+
randrange = _randrange(seed)
|
421 |
+
|
422 |
+
# Look for an identity in the circuit
|
423 |
+
while ids:
|
424 |
+
i = randrange(len(ids))
|
425 |
+
id = ids.pop(i)
|
426 |
+
if find_subcircuit(circuit, id) != -1:
|
427 |
+
break
|
428 |
+
else:
|
429 |
+
# no identity was found
|
430 |
+
return circuit
|
431 |
+
|
432 |
+
# return circuit with the identity removed
|
433 |
+
return replace_subcircuit(circuit, id)
|
434 |
+
|
435 |
+
|
436 |
+
def random_insert(circuit, choices, seed=None):
|
437 |
+
"""Insert a circuit into another quantum circuit.
|
438 |
+
|
439 |
+
Explanation
|
440 |
+
===========
|
441 |
+
|
442 |
+
random_insert randomly chooses a location in the circuit to insert
|
443 |
+
a randomly selected circuit from amongst the given choices.
|
444 |
+
|
445 |
+
Parameters
|
446 |
+
==========
|
447 |
+
|
448 |
+
circuit : Gate tuple or Mul
|
449 |
+
A tuple or Mul of Gates representing a quantum circuit
|
450 |
+
choices : list
|
451 |
+
Set of circuit choices
|
452 |
+
seed : int or list
|
453 |
+
seed used for _randrange; to override the random selections, give
|
454 |
+
a list two integers, [i, j] where i is the circuit location where
|
455 |
+
choice[j] will be inserted.
|
456 |
+
|
457 |
+
Notes
|
458 |
+
=====
|
459 |
+
|
460 |
+
Indices for insertion should be [0, n] if n is the length of the
|
461 |
+
circuit.
|
462 |
+
"""
|
463 |
+
from sympy.core.random import _randrange
|
464 |
+
|
465 |
+
if not choices:
|
466 |
+
return circuit
|
467 |
+
|
468 |
+
if isinstance(circuit, Mul):
|
469 |
+
circuit = circuit.args
|
470 |
+
|
471 |
+
# get the location in the circuit and the element to insert from choices
|
472 |
+
randrange = _randrange(seed)
|
473 |
+
loc = randrange(len(circuit) + 1)
|
474 |
+
choice = choices[randrange(len(choices))]
|
475 |
+
|
476 |
+
circuit = list(circuit)
|
477 |
+
circuit[loc: loc] = choice
|
478 |
+
return tuple(circuit)
|
479 |
+
|
480 |
+
# Flatten the GateIdentity objects (with gate rules) into one single list
|
481 |
+
|
482 |
+
|
483 |
+
def flatten_ids(ids):
|
484 |
+
collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids,
|
485 |
+
key=default_sort_key)
|
486 |
+
ids = reduce(collapse, ids, [])
|
487 |
+
ids.sort(key=default_sort_key)
|
488 |
+
return ids
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""The commutator: [A,B] = A*B - B*A."""
|
2 |
+
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.expr import Expr
|
5 |
+
from sympy.core.mul import Mul
|
6 |
+
from sympy.core.power import Pow
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
9 |
+
|
10 |
+
from sympy.physics.quantum.dagger import Dagger
|
11 |
+
from sympy.physics.quantum.operator import Operator
|
12 |
+
|
13 |
+
|
14 |
+
__all__ = [
|
15 |
+
'Commutator'
|
16 |
+
]
|
17 |
+
|
18 |
+
#-----------------------------------------------------------------------------
|
19 |
+
# Commutator
|
20 |
+
#-----------------------------------------------------------------------------
|
21 |
+
|
22 |
+
|
23 |
+
class Commutator(Expr):
|
24 |
+
"""The standard commutator, in an unevaluated state.
|
25 |
+
|
26 |
+
Explanation
|
27 |
+
===========
|
28 |
+
|
29 |
+
Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
|
30 |
+
class returns the commutator in an unevaluated form. To evaluate the
|
31 |
+
commutator, use the ``.doit()`` method.
|
32 |
+
|
33 |
+
Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
|
34 |
+
arguments of the commutator are put into canonical order using ``__cmp__``.
|
35 |
+
If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
|
36 |
+
|
37 |
+
Parameters
|
38 |
+
==========
|
39 |
+
|
40 |
+
A : Expr
|
41 |
+
The first argument of the commutator [A,B].
|
42 |
+
B : Expr
|
43 |
+
The second argument of the commutator [A,B].
|
44 |
+
|
45 |
+
Examples
|
46 |
+
========
|
47 |
+
|
48 |
+
>>> from sympy.physics.quantum import Commutator, Dagger, Operator
|
49 |
+
>>> from sympy.abc import x, y
|
50 |
+
>>> A = Operator('A')
|
51 |
+
>>> B = Operator('B')
|
52 |
+
>>> C = Operator('C')
|
53 |
+
|
54 |
+
Create a commutator and use ``.doit()`` to evaluate it:
|
55 |
+
|
56 |
+
>>> comm = Commutator(A, B)
|
57 |
+
>>> comm
|
58 |
+
[A,B]
|
59 |
+
>>> comm.doit()
|
60 |
+
A*B - B*A
|
61 |
+
|
62 |
+
The commutator orders it arguments in canonical order:
|
63 |
+
|
64 |
+
>>> comm = Commutator(B, A); comm
|
65 |
+
-[A,B]
|
66 |
+
|
67 |
+
Commutative constants are factored out:
|
68 |
+
|
69 |
+
>>> Commutator(3*x*A, x*y*B)
|
70 |
+
3*x**2*y*[A,B]
|
71 |
+
|
72 |
+
Using ``.expand(commutator=True)``, the standard commutator expansion rules
|
73 |
+
can be applied:
|
74 |
+
|
75 |
+
>>> Commutator(A+B, C).expand(commutator=True)
|
76 |
+
[A,C] + [B,C]
|
77 |
+
>>> Commutator(A, B+C).expand(commutator=True)
|
78 |
+
[A,B] + [A,C]
|
79 |
+
>>> Commutator(A*B, C).expand(commutator=True)
|
80 |
+
[A,C]*B + A*[B,C]
|
81 |
+
>>> Commutator(A, B*C).expand(commutator=True)
|
82 |
+
[A,B]*C + B*[A,C]
|
83 |
+
|
84 |
+
Adjoint operations applied to the commutator are properly applied to the
|
85 |
+
arguments:
|
86 |
+
|
87 |
+
>>> Dagger(Commutator(A, B))
|
88 |
+
-[Dagger(A),Dagger(B)]
|
89 |
+
|
90 |
+
References
|
91 |
+
==========
|
92 |
+
|
93 |
+
.. [1] https://en.wikipedia.org/wiki/Commutator
|
94 |
+
"""
|
95 |
+
is_commutative = False
|
96 |
+
|
97 |
+
def __new__(cls, A, B):
|
98 |
+
r = cls.eval(A, B)
|
99 |
+
if r is not None:
|
100 |
+
return r
|
101 |
+
obj = Expr.__new__(cls, A, B)
|
102 |
+
return obj
|
103 |
+
|
104 |
+
@classmethod
|
105 |
+
def eval(cls, a, b):
|
106 |
+
if not (a and b):
|
107 |
+
return S.Zero
|
108 |
+
if a == b:
|
109 |
+
return S.Zero
|
110 |
+
if a.is_commutative or b.is_commutative:
|
111 |
+
return S.Zero
|
112 |
+
|
113 |
+
# [xA,yB] -> xy*[A,B]
|
114 |
+
ca, nca = a.args_cnc()
|
115 |
+
cb, ncb = b.args_cnc()
|
116 |
+
c_part = ca + cb
|
117 |
+
if c_part:
|
118 |
+
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
|
119 |
+
|
120 |
+
# Canonical ordering of arguments
|
121 |
+
# The Commutator [A, B] is in canonical form if A < B.
|
122 |
+
if a.compare(b) == 1:
|
123 |
+
return S.NegativeOne*cls(b, a)
|
124 |
+
|
125 |
+
def _expand_pow(self, A, B, sign):
|
126 |
+
exp = A.exp
|
127 |
+
if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
|
128 |
+
# nothing to do
|
129 |
+
return self
|
130 |
+
base = A.base
|
131 |
+
if exp.is_negative:
|
132 |
+
base = A.base**-1
|
133 |
+
exp = -exp
|
134 |
+
comm = Commutator(base, B).expand(commutator=True)
|
135 |
+
|
136 |
+
result = base**(exp - 1) * comm
|
137 |
+
for i in range(1, exp):
|
138 |
+
result += base**(exp - 1 - i) * comm * base**i
|
139 |
+
return sign*result.expand()
|
140 |
+
|
141 |
+
def _eval_expand_commutator(self, **hints):
|
142 |
+
A = self.args[0]
|
143 |
+
B = self.args[1]
|
144 |
+
|
145 |
+
if isinstance(A, Add):
|
146 |
+
# [A + B, C] -> [A, C] + [B, C]
|
147 |
+
sargs = []
|
148 |
+
for term in A.args:
|
149 |
+
comm = Commutator(term, B)
|
150 |
+
if isinstance(comm, Commutator):
|
151 |
+
comm = comm._eval_expand_commutator()
|
152 |
+
sargs.append(comm)
|
153 |
+
return Add(*sargs)
|
154 |
+
elif isinstance(B, Add):
|
155 |
+
# [A, B + C] -> [A, B] + [A, C]
|
156 |
+
sargs = []
|
157 |
+
for term in B.args:
|
158 |
+
comm = Commutator(A, term)
|
159 |
+
if isinstance(comm, Commutator):
|
160 |
+
comm = comm._eval_expand_commutator()
|
161 |
+
sargs.append(comm)
|
162 |
+
return Add(*sargs)
|
163 |
+
elif isinstance(A, Mul):
|
164 |
+
# [A*B, C] -> A*[B, C] + [A, C]*B
|
165 |
+
a = A.args[0]
|
166 |
+
b = Mul(*A.args[1:])
|
167 |
+
c = B
|
168 |
+
comm1 = Commutator(b, c)
|
169 |
+
comm2 = Commutator(a, c)
|
170 |
+
if isinstance(comm1, Commutator):
|
171 |
+
comm1 = comm1._eval_expand_commutator()
|
172 |
+
if isinstance(comm2, Commutator):
|
173 |
+
comm2 = comm2._eval_expand_commutator()
|
174 |
+
first = Mul(a, comm1)
|
175 |
+
second = Mul(comm2, b)
|
176 |
+
return Add(first, second)
|
177 |
+
elif isinstance(B, Mul):
|
178 |
+
# [A, B*C] -> [A, B]*C + B*[A, C]
|
179 |
+
a = A
|
180 |
+
b = B.args[0]
|
181 |
+
c = Mul(*B.args[1:])
|
182 |
+
comm1 = Commutator(a, b)
|
183 |
+
comm2 = Commutator(a, c)
|
184 |
+
if isinstance(comm1, Commutator):
|
185 |
+
comm1 = comm1._eval_expand_commutator()
|
186 |
+
if isinstance(comm2, Commutator):
|
187 |
+
comm2 = comm2._eval_expand_commutator()
|
188 |
+
first = Mul(comm1, c)
|
189 |
+
second = Mul(b, comm2)
|
190 |
+
return Add(first, second)
|
191 |
+
elif isinstance(A, Pow):
|
192 |
+
# [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
|
193 |
+
return self._expand_pow(A, B, 1)
|
194 |
+
elif isinstance(B, Pow):
|
195 |
+
# [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
|
196 |
+
return self._expand_pow(B, A, -1)
|
197 |
+
|
198 |
+
# No changes, so return self
|
199 |
+
return self
|
200 |
+
|
201 |
+
def doit(self, **hints):
|
202 |
+
""" Evaluate commutator """
|
203 |
+
A = self.args[0]
|
204 |
+
B = self.args[1]
|
205 |
+
if isinstance(A, Operator) and isinstance(B, Operator):
|
206 |
+
try:
|
207 |
+
comm = A._eval_commutator(B, **hints)
|
208 |
+
except NotImplementedError:
|
209 |
+
try:
|
210 |
+
comm = -1*B._eval_commutator(A, **hints)
|
211 |
+
except NotImplementedError:
|
212 |
+
comm = None
|
213 |
+
if comm is not None:
|
214 |
+
return comm.doit(**hints)
|
215 |
+
return (A*B - B*A).doit(**hints)
|
216 |
+
|
217 |
+
def _eval_adjoint(self):
|
218 |
+
return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
|
219 |
+
|
220 |
+
def _sympyrepr(self, printer, *args):
|
221 |
+
return "%s(%s,%s)" % (
|
222 |
+
self.__class__.__name__, printer._print(
|
223 |
+
self.args[0]), printer._print(self.args[1])
|
224 |
+
)
|
225 |
+
|
226 |
+
def _sympystr(self, printer, *args):
|
227 |
+
return "[%s,%s]" % (
|
228 |
+
printer._print(self.args[0]), printer._print(self.args[1]))
|
229 |
+
|
230 |
+
def _pretty(self, printer, *args):
|
231 |
+
pform = printer._print(self.args[0], *args)
|
232 |
+
pform = prettyForm(*pform.right(prettyForm(',')))
|
233 |
+
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
|
234 |
+
pform = prettyForm(*pform.parens(left='[', right=']'))
|
235 |
+
return pform
|
236 |
+
|
237 |
+
def _latex(self, printer, *args):
|
238 |
+
return "\\left[%s,%s\\right]" % tuple([
|
239 |
+
printer._print(arg, *args) for arg in self.args])
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/constants.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Constants (like hbar) related to quantum mechanics."""
|
2 |
+
|
3 |
+
from sympy.core.numbers import NumberSymbol
|
4 |
+
from sympy.core.singleton import Singleton
|
5 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
6 |
+
import mpmath.libmp as mlib
|
7 |
+
|
8 |
+
#-----------------------------------------------------------------------------
|
9 |
+
# Constants
|
10 |
+
#-----------------------------------------------------------------------------
|
11 |
+
|
12 |
+
__all__ = [
|
13 |
+
'hbar',
|
14 |
+
'HBar',
|
15 |
+
]
|
16 |
+
|
17 |
+
|
18 |
+
class HBar(NumberSymbol, metaclass=Singleton):
|
19 |
+
"""Reduced Plank's constant in numerical and symbolic form [1]_.
|
20 |
+
|
21 |
+
Examples
|
22 |
+
========
|
23 |
+
|
24 |
+
>>> from sympy.physics.quantum.constants import hbar
|
25 |
+
>>> hbar.evalf()
|
26 |
+
1.05457162000000e-34
|
27 |
+
|
28 |
+
References
|
29 |
+
==========
|
30 |
+
|
31 |
+
.. [1] https://en.wikipedia.org/wiki/Planck_constant
|
32 |
+
"""
|
33 |
+
|
34 |
+
is_real = True
|
35 |
+
is_positive = True
|
36 |
+
is_negative = False
|
37 |
+
is_irrational = True
|
38 |
+
|
39 |
+
__slots__ = ()
|
40 |
+
|
41 |
+
def _as_mpf_val(self, prec):
|
42 |
+
return mlib.from_float(1.05457162e-34, prec)
|
43 |
+
|
44 |
+
def _sympyrepr(self, printer, *args):
|
45 |
+
return 'HBar()'
|
46 |
+
|
47 |
+
def _sympystr(self, printer, *args):
|
48 |
+
return 'hbar'
|
49 |
+
|
50 |
+
def _pretty(self, printer, *args):
|
51 |
+
if printer._use_unicode:
|
52 |
+
return prettyForm('\N{PLANCK CONSTANT OVER TWO PI}')
|
53 |
+
return prettyForm('hbar')
|
54 |
+
|
55 |
+
def _latex(self, printer, *args):
|
56 |
+
return r'\hbar'
|
57 |
+
|
58 |
+
# Create an instance for everyone to use.
|
59 |
+
hbar = HBar()
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Hermitian conjugation."""
|
2 |
+
|
3 |
+
from sympy.core import Expr, Mul
|
4 |
+
from sympy.functions.elementary.complexes import adjoint
|
5 |
+
|
6 |
+
__all__ = [
|
7 |
+
'Dagger'
|
8 |
+
]
|
9 |
+
|
10 |
+
|
11 |
+
class Dagger(adjoint):
|
12 |
+
"""General Hermitian conjugate operation.
|
13 |
+
|
14 |
+
Explanation
|
15 |
+
===========
|
16 |
+
|
17 |
+
Take the Hermetian conjugate of an argument [1]_. For matrices this
|
18 |
+
operation is equivalent to transpose and complex conjugate [2]_.
|
19 |
+
|
20 |
+
Parameters
|
21 |
+
==========
|
22 |
+
|
23 |
+
arg : Expr
|
24 |
+
The SymPy expression that we want to take the dagger of.
|
25 |
+
|
26 |
+
Examples
|
27 |
+
========
|
28 |
+
|
29 |
+
Daggering various quantum objects:
|
30 |
+
|
31 |
+
>>> from sympy.physics.quantum.dagger import Dagger
|
32 |
+
>>> from sympy.physics.quantum.state import Ket, Bra
|
33 |
+
>>> from sympy.physics.quantum.operator import Operator
|
34 |
+
>>> Dagger(Ket('psi'))
|
35 |
+
<psi|
|
36 |
+
>>> Dagger(Bra('phi'))
|
37 |
+
|phi>
|
38 |
+
>>> Dagger(Operator('A'))
|
39 |
+
Dagger(A)
|
40 |
+
|
41 |
+
Inner and outer products::
|
42 |
+
|
43 |
+
>>> from sympy.physics.quantum import InnerProduct, OuterProduct
|
44 |
+
>>> Dagger(InnerProduct(Bra('a'), Ket('b')))
|
45 |
+
<b|a>
|
46 |
+
>>> Dagger(OuterProduct(Ket('a'), Bra('b')))
|
47 |
+
|b><a|
|
48 |
+
|
49 |
+
Powers, sums and products::
|
50 |
+
|
51 |
+
>>> A = Operator('A')
|
52 |
+
>>> B = Operator('B')
|
53 |
+
>>> Dagger(A*B)
|
54 |
+
Dagger(B)*Dagger(A)
|
55 |
+
>>> Dagger(A+B)
|
56 |
+
Dagger(A) + Dagger(B)
|
57 |
+
>>> Dagger(A**2)
|
58 |
+
Dagger(A)**2
|
59 |
+
|
60 |
+
Dagger also seamlessly handles complex numbers and matrices::
|
61 |
+
|
62 |
+
>>> from sympy import Matrix, I
|
63 |
+
>>> m = Matrix([[1,I],[2,I]])
|
64 |
+
>>> m
|
65 |
+
Matrix([
|
66 |
+
[1, I],
|
67 |
+
[2, I]])
|
68 |
+
>>> Dagger(m)
|
69 |
+
Matrix([
|
70 |
+
[ 1, 2],
|
71 |
+
[-I, -I]])
|
72 |
+
|
73 |
+
References
|
74 |
+
==========
|
75 |
+
|
76 |
+
.. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
|
77 |
+
.. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
|
78 |
+
"""
|
79 |
+
|
80 |
+
def __new__(cls, arg):
|
81 |
+
if hasattr(arg, 'adjoint'):
|
82 |
+
obj = arg.adjoint()
|
83 |
+
elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'):
|
84 |
+
obj = arg.conjugate().transpose()
|
85 |
+
if obj is not None:
|
86 |
+
return obj
|
87 |
+
return Expr.__new__(cls, arg)
|
88 |
+
|
89 |
+
def __mul__(self, other):
|
90 |
+
from sympy.physics.quantum import IdentityOperator
|
91 |
+
if isinstance(other, IdentityOperator):
|
92 |
+
return self
|
93 |
+
|
94 |
+
return Mul(self, other)
|
95 |
+
|
96 |
+
adjoint.__name__ = "Dagger"
|
97 |
+
adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/density.py
ADDED
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import product
|
2 |
+
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.containers import Tuple
|
5 |
+
from sympy.core.function import expand
|
6 |
+
from sympy.core.mul import Mul
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.functions.elementary.exponential import log
|
9 |
+
from sympy.matrices.dense import MutableDenseMatrix as Matrix
|
10 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
11 |
+
from sympy.physics.quantum.dagger import Dagger
|
12 |
+
from sympy.physics.quantum.operator import HermitianOperator
|
13 |
+
from sympy.physics.quantum.represent import represent
|
14 |
+
from sympy.physics.quantum.matrixutils import numpy_ndarray, scipy_sparse_matrix, to_numpy
|
15 |
+
from sympy.physics.quantum.tensorproduct import TensorProduct, tensor_product_simp
|
16 |
+
from sympy.physics.quantum.trace import Tr
|
17 |
+
|
18 |
+
|
19 |
+
class Density(HermitianOperator):
|
20 |
+
"""Density operator for representing mixed states.
|
21 |
+
|
22 |
+
TODO: Density operator support for Qubits
|
23 |
+
|
24 |
+
Parameters
|
25 |
+
==========
|
26 |
+
|
27 |
+
values : tuples/lists
|
28 |
+
Each tuple/list should be of form (state, prob) or [state,prob]
|
29 |
+
|
30 |
+
Examples
|
31 |
+
========
|
32 |
+
|
33 |
+
Create a density operator with 2 states represented by Kets.
|
34 |
+
|
35 |
+
>>> from sympy.physics.quantum.state import Ket
|
36 |
+
>>> from sympy.physics.quantum.density import Density
|
37 |
+
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
|
38 |
+
>>> d
|
39 |
+
Density((|0>, 0.5),(|1>, 0.5))
|
40 |
+
|
41 |
+
"""
|
42 |
+
@classmethod
|
43 |
+
def _eval_args(cls, args):
|
44 |
+
# call this to qsympify the args
|
45 |
+
args = super()._eval_args(args)
|
46 |
+
|
47 |
+
for arg in args:
|
48 |
+
# Check if arg is a tuple
|
49 |
+
if not (isinstance(arg, Tuple) and len(arg) == 2):
|
50 |
+
raise ValueError("Each argument should be of form [state,prob]"
|
51 |
+
" or ( state, prob )")
|
52 |
+
|
53 |
+
return args
|
54 |
+
|
55 |
+
def states(self):
|
56 |
+
"""Return list of all states.
|
57 |
+
|
58 |
+
Examples
|
59 |
+
========
|
60 |
+
|
61 |
+
>>> from sympy.physics.quantum.state import Ket
|
62 |
+
>>> from sympy.physics.quantum.density import Density
|
63 |
+
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
|
64 |
+
>>> d.states()
|
65 |
+
(|0>, |1>)
|
66 |
+
|
67 |
+
"""
|
68 |
+
return Tuple(*[arg[0] for arg in self.args])
|
69 |
+
|
70 |
+
def probs(self):
|
71 |
+
"""Return list of all probabilities.
|
72 |
+
|
73 |
+
Examples
|
74 |
+
========
|
75 |
+
|
76 |
+
>>> from sympy.physics.quantum.state import Ket
|
77 |
+
>>> from sympy.physics.quantum.density import Density
|
78 |
+
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
|
79 |
+
>>> d.probs()
|
80 |
+
(0.5, 0.5)
|
81 |
+
|
82 |
+
"""
|
83 |
+
return Tuple(*[arg[1] for arg in self.args])
|
84 |
+
|
85 |
+
def get_state(self, index):
|
86 |
+
"""Return specific state by index.
|
87 |
+
|
88 |
+
Parameters
|
89 |
+
==========
|
90 |
+
|
91 |
+
index : index of state to be returned
|
92 |
+
|
93 |
+
Examples
|
94 |
+
========
|
95 |
+
|
96 |
+
>>> from sympy.physics.quantum.state import Ket
|
97 |
+
>>> from sympy.physics.quantum.density import Density
|
98 |
+
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
|
99 |
+
>>> d.states()[1]
|
100 |
+
|1>
|
101 |
+
|
102 |
+
"""
|
103 |
+
state = self.args[index][0]
|
104 |
+
return state
|
105 |
+
|
106 |
+
def get_prob(self, index):
|
107 |
+
"""Return probability of specific state by index.
|
108 |
+
|
109 |
+
Parameters
|
110 |
+
===========
|
111 |
+
|
112 |
+
index : index of states whose probability is returned.
|
113 |
+
|
114 |
+
Examples
|
115 |
+
========
|
116 |
+
|
117 |
+
>>> from sympy.physics.quantum.state import Ket
|
118 |
+
>>> from sympy.physics.quantum.density import Density
|
119 |
+
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
|
120 |
+
>>> d.probs()[1]
|
121 |
+
0.500000000000000
|
122 |
+
|
123 |
+
"""
|
124 |
+
prob = self.args[index][1]
|
125 |
+
return prob
|
126 |
+
|
127 |
+
def apply_op(self, op):
|
128 |
+
"""op will operate on each individual state.
|
129 |
+
|
130 |
+
Parameters
|
131 |
+
==========
|
132 |
+
|
133 |
+
op : Operator
|
134 |
+
|
135 |
+
Examples
|
136 |
+
========
|
137 |
+
|
138 |
+
>>> from sympy.physics.quantum.state import Ket
|
139 |
+
>>> from sympy.physics.quantum.density import Density
|
140 |
+
>>> from sympy.physics.quantum.operator import Operator
|
141 |
+
>>> A = Operator('A')
|
142 |
+
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
|
143 |
+
>>> d.apply_op(A)
|
144 |
+
Density((A*|0>, 0.5),(A*|1>, 0.5))
|
145 |
+
|
146 |
+
"""
|
147 |
+
new_args = [(op*state, prob) for (state, prob) in self.args]
|
148 |
+
return Density(*new_args)
|
149 |
+
|
150 |
+
def doit(self, **hints):
|
151 |
+
"""Expand the density operator into an outer product format.
|
152 |
+
|
153 |
+
Examples
|
154 |
+
========
|
155 |
+
|
156 |
+
>>> from sympy.physics.quantum.state import Ket
|
157 |
+
>>> from sympy.physics.quantum.density import Density
|
158 |
+
>>> from sympy.physics.quantum.operator import Operator
|
159 |
+
>>> A = Operator('A')
|
160 |
+
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
|
161 |
+
>>> d.doit()
|
162 |
+
0.5*|0><0| + 0.5*|1><1|
|
163 |
+
|
164 |
+
"""
|
165 |
+
|
166 |
+
terms = []
|
167 |
+
for (state, prob) in self.args:
|
168 |
+
state = state.expand() # needed to break up (a+b)*c
|
169 |
+
if (isinstance(state, Add)):
|
170 |
+
for arg in product(state.args, repeat=2):
|
171 |
+
terms.append(prob*self._generate_outer_prod(arg[0],
|
172 |
+
arg[1]))
|
173 |
+
else:
|
174 |
+
terms.append(prob*self._generate_outer_prod(state, state))
|
175 |
+
|
176 |
+
return Add(*terms)
|
177 |
+
|
178 |
+
def _generate_outer_prod(self, arg1, arg2):
|
179 |
+
c_part1, nc_part1 = arg1.args_cnc()
|
180 |
+
c_part2, nc_part2 = arg2.args_cnc()
|
181 |
+
|
182 |
+
if (len(nc_part1) == 0 or len(nc_part2) == 0):
|
183 |
+
raise ValueError('Atleast one-pair of'
|
184 |
+
' Non-commutative instance required'
|
185 |
+
' for outer product.')
|
186 |
+
|
187 |
+
# Muls of Tensor Products should be expanded
|
188 |
+
# before this function is called
|
189 |
+
if (isinstance(nc_part1[0], TensorProduct) and len(nc_part1) == 1
|
190 |
+
and len(nc_part2) == 1):
|
191 |
+
op = tensor_product_simp(nc_part1[0]*Dagger(nc_part2[0]))
|
192 |
+
else:
|
193 |
+
op = Mul(*nc_part1)*Dagger(Mul(*nc_part2))
|
194 |
+
|
195 |
+
return Mul(*c_part1)*Mul(*c_part2) * op
|
196 |
+
|
197 |
+
def _represent(self, **options):
|
198 |
+
return represent(self.doit(), **options)
|
199 |
+
|
200 |
+
def _print_operator_name_latex(self, printer, *args):
|
201 |
+
return r'\rho'
|
202 |
+
|
203 |
+
def _print_operator_name_pretty(self, printer, *args):
|
204 |
+
return prettyForm('\N{GREEK SMALL LETTER RHO}')
|
205 |
+
|
206 |
+
def _eval_trace(self, **kwargs):
|
207 |
+
indices = kwargs.get('indices', [])
|
208 |
+
return Tr(self.doit(), indices).doit()
|
209 |
+
|
210 |
+
def entropy(self):
|
211 |
+
""" Compute the entropy of a density matrix.
|
212 |
+
|
213 |
+
Refer to density.entropy() method for examples.
|
214 |
+
"""
|
215 |
+
return entropy(self)
|
216 |
+
|
217 |
+
|
218 |
+
def entropy(density):
|
219 |
+
"""Compute the entropy of a matrix/density object.
|
220 |
+
|
221 |
+
This computes -Tr(density*ln(density)) using the eigenvalue decomposition
|
222 |
+
of density, which is given as either a Density instance or a matrix
|
223 |
+
(numpy.ndarray, sympy.Matrix or scipy.sparse).
|
224 |
+
|
225 |
+
Parameters
|
226 |
+
==========
|
227 |
+
|
228 |
+
density : density matrix of type Density, SymPy matrix,
|
229 |
+
scipy.sparse or numpy.ndarray
|
230 |
+
|
231 |
+
Examples
|
232 |
+
========
|
233 |
+
|
234 |
+
>>> from sympy.physics.quantum.density import Density, entropy
|
235 |
+
>>> from sympy.physics.quantum.spin import JzKet
|
236 |
+
>>> from sympy import S
|
237 |
+
>>> up = JzKet(S(1)/2,S(1)/2)
|
238 |
+
>>> down = JzKet(S(1)/2,-S(1)/2)
|
239 |
+
>>> d = Density((up,S(1)/2),(down,S(1)/2))
|
240 |
+
>>> entropy(d)
|
241 |
+
log(2)/2
|
242 |
+
|
243 |
+
"""
|
244 |
+
if isinstance(density, Density):
|
245 |
+
density = represent(density) # represent in Matrix
|
246 |
+
|
247 |
+
if isinstance(density, scipy_sparse_matrix):
|
248 |
+
density = to_numpy(density)
|
249 |
+
|
250 |
+
if isinstance(density, Matrix):
|
251 |
+
eigvals = density.eigenvals().keys()
|
252 |
+
return expand(-sum(e*log(e) for e in eigvals))
|
253 |
+
elif isinstance(density, numpy_ndarray):
|
254 |
+
import numpy as np
|
255 |
+
eigvals = np.linalg.eigvals(density)
|
256 |
+
return -np.sum(eigvals*np.log(eigvals))
|
257 |
+
else:
|
258 |
+
raise ValueError(
|
259 |
+
"numpy.ndarray, scipy.sparse or SymPy matrix expected")
|
260 |
+
|
261 |
+
|
262 |
+
def fidelity(state1, state2):
|
263 |
+
""" Computes the fidelity [1]_ between two quantum states
|
264 |
+
|
265 |
+
The arguments provided to this function should be a square matrix or a
|
266 |
+
Density object. If it is a square matrix, it is assumed to be diagonalizable.
|
267 |
+
|
268 |
+
Parameters
|
269 |
+
==========
|
270 |
+
|
271 |
+
state1, state2 : a density matrix or Matrix
|
272 |
+
|
273 |
+
|
274 |
+
Examples
|
275 |
+
========
|
276 |
+
|
277 |
+
>>> from sympy import S, sqrt
|
278 |
+
>>> from sympy.physics.quantum.dagger import Dagger
|
279 |
+
>>> from sympy.physics.quantum.spin import JzKet
|
280 |
+
>>> from sympy.physics.quantum.density import fidelity
|
281 |
+
>>> from sympy.physics.quantum.represent import represent
|
282 |
+
>>>
|
283 |
+
>>> up = JzKet(S(1)/2,S(1)/2)
|
284 |
+
>>> down = JzKet(S(1)/2,-S(1)/2)
|
285 |
+
>>> amp = 1/sqrt(2)
|
286 |
+
>>> updown = (amp*up) + (amp*down)
|
287 |
+
>>>
|
288 |
+
>>> # represent turns Kets into matrices
|
289 |
+
>>> up_dm = represent(up*Dagger(up))
|
290 |
+
>>> down_dm = represent(down*Dagger(down))
|
291 |
+
>>> updown_dm = represent(updown*Dagger(updown))
|
292 |
+
>>>
|
293 |
+
>>> fidelity(up_dm, up_dm)
|
294 |
+
1
|
295 |
+
>>> fidelity(up_dm, down_dm) #orthogonal states
|
296 |
+
0
|
297 |
+
>>> fidelity(up_dm, updown_dm).evalf().round(3)
|
298 |
+
0.707
|
299 |
+
|
300 |
+
References
|
301 |
+
==========
|
302 |
+
|
303 |
+
.. [1] https://en.wikipedia.org/wiki/Fidelity_of_quantum_states
|
304 |
+
|
305 |
+
"""
|
306 |
+
state1 = represent(state1) if isinstance(state1, Density) else state1
|
307 |
+
state2 = represent(state2) if isinstance(state2, Density) else state2
|
308 |
+
|
309 |
+
if not isinstance(state1, Matrix) or not isinstance(state2, Matrix):
|
310 |
+
raise ValueError("state1 and state2 must be of type Density or Matrix "
|
311 |
+
"received type=%s for state1 and type=%s for state2" %
|
312 |
+
(type(state1), type(state2)))
|
313 |
+
|
314 |
+
if state1.shape != state2.shape and state1.is_square:
|
315 |
+
raise ValueError("The dimensions of both args should be equal and the "
|
316 |
+
"matrix obtained should be a square matrix")
|
317 |
+
|
318 |
+
sqrt_state1 = state1**S.Half
|
319 |
+
return Tr((sqrt_state1*state2*sqrt_state1)**S.Half).doit()
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/fermion.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Fermionic quantum operators."""
|
2 |
+
|
3 |
+
from sympy.core.numbers import Integer
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.physics.quantum import Operator
|
6 |
+
from sympy.physics.quantum import HilbertSpace, Ket, Bra
|
7 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
8 |
+
|
9 |
+
|
10 |
+
__all__ = [
|
11 |
+
'FermionOp',
|
12 |
+
'FermionFockKet',
|
13 |
+
'FermionFockBra'
|
14 |
+
]
|
15 |
+
|
16 |
+
|
17 |
+
class FermionOp(Operator):
|
18 |
+
"""A fermionic operator that satisfies {c, Dagger(c)} == 1.
|
19 |
+
|
20 |
+
Parameters
|
21 |
+
==========
|
22 |
+
|
23 |
+
name : str
|
24 |
+
A string that labels the fermionic mode.
|
25 |
+
|
26 |
+
annihilation : bool
|
27 |
+
A bool that indicates if the fermionic operator is an annihilation
|
28 |
+
(True, default value) or creation operator (False)
|
29 |
+
|
30 |
+
Examples
|
31 |
+
========
|
32 |
+
|
33 |
+
>>> from sympy.physics.quantum import Dagger, AntiCommutator
|
34 |
+
>>> from sympy.physics.quantum.fermion import FermionOp
|
35 |
+
>>> c = FermionOp("c")
|
36 |
+
>>> AntiCommutator(c, Dagger(c)).doit()
|
37 |
+
1
|
38 |
+
"""
|
39 |
+
@property
|
40 |
+
def name(self):
|
41 |
+
return self.args[0]
|
42 |
+
|
43 |
+
@property
|
44 |
+
def is_annihilation(self):
|
45 |
+
return bool(self.args[1])
|
46 |
+
|
47 |
+
@classmethod
|
48 |
+
def default_args(self):
|
49 |
+
return ("c", True)
|
50 |
+
|
51 |
+
def __new__(cls, *args, **hints):
|
52 |
+
if not len(args) in [1, 2]:
|
53 |
+
raise ValueError('1 or 2 parameters expected, got %s' % args)
|
54 |
+
|
55 |
+
if len(args) == 1:
|
56 |
+
args = (args[0], S.One)
|
57 |
+
|
58 |
+
if len(args) == 2:
|
59 |
+
args = (args[0], Integer(args[1]))
|
60 |
+
|
61 |
+
return Operator.__new__(cls, *args)
|
62 |
+
|
63 |
+
def _eval_commutator_FermionOp(self, other, **hints):
|
64 |
+
if 'independent' in hints and hints['independent']:
|
65 |
+
# [c, d] = 0
|
66 |
+
return S.Zero
|
67 |
+
|
68 |
+
return None
|
69 |
+
|
70 |
+
def _eval_anticommutator_FermionOp(self, other, **hints):
|
71 |
+
if self.name == other.name:
|
72 |
+
# {a^\dagger, a} = 1
|
73 |
+
if not self.is_annihilation and other.is_annihilation:
|
74 |
+
return S.One
|
75 |
+
|
76 |
+
elif 'independent' in hints and hints['independent']:
|
77 |
+
# {c, d} = 2 * c * d, because [c, d] = 0 for independent operators
|
78 |
+
return 2 * self * other
|
79 |
+
|
80 |
+
return None
|
81 |
+
|
82 |
+
def _eval_anticommutator_BosonOp(self, other, **hints):
|
83 |
+
# because fermions and bosons commute
|
84 |
+
return 2 * self * other
|
85 |
+
|
86 |
+
def _eval_commutator_BosonOp(self, other, **hints):
|
87 |
+
return S.Zero
|
88 |
+
|
89 |
+
def _eval_adjoint(self):
|
90 |
+
return FermionOp(str(self.name), not self.is_annihilation)
|
91 |
+
|
92 |
+
def _print_contents_latex(self, printer, *args):
|
93 |
+
if self.is_annihilation:
|
94 |
+
return r'{%s}' % str(self.name)
|
95 |
+
else:
|
96 |
+
return r'{{%s}^\dagger}' % str(self.name)
|
97 |
+
|
98 |
+
def _print_contents(self, printer, *args):
|
99 |
+
if self.is_annihilation:
|
100 |
+
return r'%s' % str(self.name)
|
101 |
+
else:
|
102 |
+
return r'Dagger(%s)' % str(self.name)
|
103 |
+
|
104 |
+
def _print_contents_pretty(self, printer, *args):
|
105 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
106 |
+
pform = printer._print(self.args[0], *args)
|
107 |
+
if self.is_annihilation:
|
108 |
+
return pform
|
109 |
+
else:
|
110 |
+
return pform**prettyForm('\N{DAGGER}')
|
111 |
+
|
112 |
+
|
113 |
+
class FermionFockKet(Ket):
|
114 |
+
"""Fock state ket for a fermionic mode.
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
==========
|
118 |
+
|
119 |
+
n : Number
|
120 |
+
The Fock state number.
|
121 |
+
|
122 |
+
"""
|
123 |
+
|
124 |
+
def __new__(cls, n):
|
125 |
+
if n not in (0, 1):
|
126 |
+
raise ValueError("n must be 0 or 1")
|
127 |
+
return Ket.__new__(cls, n)
|
128 |
+
|
129 |
+
@property
|
130 |
+
def n(self):
|
131 |
+
return self.label[0]
|
132 |
+
|
133 |
+
@classmethod
|
134 |
+
def dual_class(self):
|
135 |
+
return FermionFockBra
|
136 |
+
|
137 |
+
@classmethod
|
138 |
+
def _eval_hilbert_space(cls, label):
|
139 |
+
return HilbertSpace()
|
140 |
+
|
141 |
+
def _eval_innerproduct_FermionFockBra(self, bra, **hints):
|
142 |
+
return KroneckerDelta(self.n, bra.n)
|
143 |
+
|
144 |
+
def _apply_from_right_to_FermionOp(self, op, **options):
|
145 |
+
if op.is_annihilation:
|
146 |
+
if self.n == 1:
|
147 |
+
return FermionFockKet(0)
|
148 |
+
else:
|
149 |
+
return S.Zero
|
150 |
+
else:
|
151 |
+
if self.n == 0:
|
152 |
+
return FermionFockKet(1)
|
153 |
+
else:
|
154 |
+
return S.Zero
|
155 |
+
|
156 |
+
|
157 |
+
class FermionFockBra(Bra):
|
158 |
+
"""Fock state bra for a fermionic mode.
|
159 |
+
|
160 |
+
Parameters
|
161 |
+
==========
|
162 |
+
|
163 |
+
n : Number
|
164 |
+
The Fock state number.
|
165 |
+
|
166 |
+
"""
|
167 |
+
|
168 |
+
def __new__(cls, n):
|
169 |
+
if n not in (0, 1):
|
170 |
+
raise ValueError("n must be 0 or 1")
|
171 |
+
return Bra.__new__(cls, n)
|
172 |
+
|
173 |
+
@property
|
174 |
+
def n(self):
|
175 |
+
return self.label[0]
|
176 |
+
|
177 |
+
@classmethod
|
178 |
+
def dual_class(self):
|
179 |
+
return FermionFockKet
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/gate.py
ADDED
@@ -0,0 +1,1305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""An implementation of gates that act on qubits.
|
2 |
+
|
3 |
+
Gates are unitary operators that act on the space of qubits.
|
4 |
+
|
5 |
+
Medium Term Todo:
|
6 |
+
|
7 |
+
* Optimize Gate._apply_operators_Qubit to remove the creation of many
|
8 |
+
intermediate Qubit objects.
|
9 |
+
* Add commutation relationships to all operators and use this in gate_sort.
|
10 |
+
* Fix gate_sort and gate_simp.
|
11 |
+
* Get multi-target UGates plotting properly.
|
12 |
+
* Get UGate to work with either sympy/numpy matrices and output either
|
13 |
+
format. This should also use the matrix slots.
|
14 |
+
"""
|
15 |
+
|
16 |
+
from itertools import chain
|
17 |
+
import random
|
18 |
+
|
19 |
+
from sympy.core.add import Add
|
20 |
+
from sympy.core.containers import Tuple
|
21 |
+
from sympy.core.mul import Mul
|
22 |
+
from sympy.core.numbers import (I, Integer)
|
23 |
+
from sympy.core.power import Pow
|
24 |
+
from sympy.core.numbers import Number
|
25 |
+
from sympy.core.singleton import S as _S
|
26 |
+
from sympy.core.sorting import default_sort_key
|
27 |
+
from sympy.core.sympify import _sympify
|
28 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
29 |
+
from sympy.printing.pretty.stringpict import prettyForm, stringPict
|
30 |
+
|
31 |
+
from sympy.physics.quantum.anticommutator import AntiCommutator
|
32 |
+
from sympy.physics.quantum.commutator import Commutator
|
33 |
+
from sympy.physics.quantum.qexpr import QuantumError
|
34 |
+
from sympy.physics.quantum.hilbert import ComplexSpace
|
35 |
+
from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
|
36 |
+
HermitianOperator)
|
37 |
+
from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
|
38 |
+
from sympy.physics.quantum.matrixcache import matrix_cache
|
39 |
+
|
40 |
+
from sympy.matrices.matrices import MatrixBase
|
41 |
+
|
42 |
+
from sympy.utilities.iterables import is_sequence
|
43 |
+
|
44 |
+
__all__ = [
|
45 |
+
'Gate',
|
46 |
+
'CGate',
|
47 |
+
'UGate',
|
48 |
+
'OneQubitGate',
|
49 |
+
'TwoQubitGate',
|
50 |
+
'IdentityGate',
|
51 |
+
'HadamardGate',
|
52 |
+
'XGate',
|
53 |
+
'YGate',
|
54 |
+
'ZGate',
|
55 |
+
'TGate',
|
56 |
+
'PhaseGate',
|
57 |
+
'SwapGate',
|
58 |
+
'CNotGate',
|
59 |
+
# Aliased gate names
|
60 |
+
'CNOT',
|
61 |
+
'SWAP',
|
62 |
+
'H',
|
63 |
+
'X',
|
64 |
+
'Y',
|
65 |
+
'Z',
|
66 |
+
'T',
|
67 |
+
'S',
|
68 |
+
'Phase',
|
69 |
+
'normalized',
|
70 |
+
'gate_sort',
|
71 |
+
'gate_simp',
|
72 |
+
'random_circuit',
|
73 |
+
'CPHASE',
|
74 |
+
'CGateS',
|
75 |
+
]
|
76 |
+
|
77 |
+
#-----------------------------------------------------------------------------
|
78 |
+
# Gate Super-Classes
|
79 |
+
#-----------------------------------------------------------------------------
|
80 |
+
|
81 |
+
_normalized = True
|
82 |
+
|
83 |
+
|
84 |
+
def _max(*args, **kwargs):
|
85 |
+
if "key" not in kwargs:
|
86 |
+
kwargs["key"] = default_sort_key
|
87 |
+
return max(*args, **kwargs)
|
88 |
+
|
89 |
+
|
90 |
+
def _min(*args, **kwargs):
|
91 |
+
if "key" not in kwargs:
|
92 |
+
kwargs["key"] = default_sort_key
|
93 |
+
return min(*args, **kwargs)
|
94 |
+
|
95 |
+
|
96 |
+
def normalized(normalize):
|
97 |
+
r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.
|
98 |
+
|
99 |
+
This is a global setting that can be used to simplify the look of various
|
100 |
+
expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.
|
101 |
+
|
102 |
+
Parameters
|
103 |
+
----------
|
104 |
+
normalize : bool
|
105 |
+
Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
|
106 |
+
When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
|
107 |
+
Hadamard gate will not have this factor.
|
108 |
+
"""
|
109 |
+
global _normalized
|
110 |
+
_normalized = normalize
|
111 |
+
|
112 |
+
|
113 |
+
def _validate_targets_controls(tandc):
|
114 |
+
tandc = list(tandc)
|
115 |
+
# Check for integers
|
116 |
+
for bit in tandc:
|
117 |
+
if not bit.is_Integer and not bit.is_Symbol:
|
118 |
+
raise TypeError('Integer expected, got: %r' % tandc[bit])
|
119 |
+
# Detect duplicates
|
120 |
+
if len(set(tandc)) != len(tandc):
|
121 |
+
raise QuantumError(
|
122 |
+
'Target/control qubits in a gate cannot be duplicated'
|
123 |
+
)
|
124 |
+
|
125 |
+
|
126 |
+
class Gate(UnitaryOperator):
|
127 |
+
"""Non-controlled unitary gate operator that acts on qubits.
|
128 |
+
|
129 |
+
This is a general abstract gate that needs to be subclassed to do anything
|
130 |
+
useful.
|
131 |
+
|
132 |
+
Parameters
|
133 |
+
----------
|
134 |
+
label : tuple, int
|
135 |
+
A list of the target qubits (as ints) that the gate will apply to.
|
136 |
+
|
137 |
+
Examples
|
138 |
+
========
|
139 |
+
|
140 |
+
|
141 |
+
"""
|
142 |
+
|
143 |
+
_label_separator = ','
|
144 |
+
|
145 |
+
gate_name = 'G'
|
146 |
+
gate_name_latex = 'G'
|
147 |
+
|
148 |
+
#-------------------------------------------------------------------------
|
149 |
+
# Initialization/creation
|
150 |
+
#-------------------------------------------------------------------------
|
151 |
+
|
152 |
+
@classmethod
|
153 |
+
def _eval_args(cls, args):
|
154 |
+
args = Tuple(*UnitaryOperator._eval_args(args))
|
155 |
+
_validate_targets_controls(args)
|
156 |
+
return args
|
157 |
+
|
158 |
+
@classmethod
|
159 |
+
def _eval_hilbert_space(cls, args):
|
160 |
+
"""This returns the smallest possible Hilbert space."""
|
161 |
+
return ComplexSpace(2)**(_max(args) + 1)
|
162 |
+
|
163 |
+
#-------------------------------------------------------------------------
|
164 |
+
# Properties
|
165 |
+
#-------------------------------------------------------------------------
|
166 |
+
|
167 |
+
@property
|
168 |
+
def nqubits(self):
|
169 |
+
"""The total number of qubits this gate acts on.
|
170 |
+
|
171 |
+
For controlled gate subclasses this includes both target and control
|
172 |
+
qubits, so that, for examples the CNOT gate acts on 2 qubits.
|
173 |
+
"""
|
174 |
+
return len(self.targets)
|
175 |
+
|
176 |
+
@property
|
177 |
+
def min_qubits(self):
|
178 |
+
"""The minimum number of qubits this gate needs to act on."""
|
179 |
+
return _max(self.targets) + 1
|
180 |
+
|
181 |
+
@property
|
182 |
+
def targets(self):
|
183 |
+
"""A tuple of target qubits."""
|
184 |
+
return self.label
|
185 |
+
|
186 |
+
@property
|
187 |
+
def gate_name_plot(self):
|
188 |
+
return r'$%s$' % self.gate_name_latex
|
189 |
+
|
190 |
+
#-------------------------------------------------------------------------
|
191 |
+
# Gate methods
|
192 |
+
#-------------------------------------------------------------------------
|
193 |
+
|
194 |
+
def get_target_matrix(self, format='sympy'):
|
195 |
+
"""The matrix representation of the target part of the gate.
|
196 |
+
|
197 |
+
Parameters
|
198 |
+
----------
|
199 |
+
format : str
|
200 |
+
The format string ('sympy','numpy', etc.)
|
201 |
+
"""
|
202 |
+
raise NotImplementedError(
|
203 |
+
'get_target_matrix is not implemented in Gate.')
|
204 |
+
|
205 |
+
#-------------------------------------------------------------------------
|
206 |
+
# Apply
|
207 |
+
#-------------------------------------------------------------------------
|
208 |
+
|
209 |
+
def _apply_operator_IntQubit(self, qubits, **options):
|
210 |
+
"""Redirect an apply from IntQubit to Qubit"""
|
211 |
+
return self._apply_operator_Qubit(qubits, **options)
|
212 |
+
|
213 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
214 |
+
"""Apply this gate to a Qubit."""
|
215 |
+
|
216 |
+
# Check number of qubits this gate acts on.
|
217 |
+
if qubits.nqubits < self.min_qubits:
|
218 |
+
raise QuantumError(
|
219 |
+
'Gate needs a minimum of %r qubits to act on, got: %r' %
|
220 |
+
(self.min_qubits, qubits.nqubits)
|
221 |
+
)
|
222 |
+
|
223 |
+
# If the controls are not met, just return
|
224 |
+
if isinstance(self, CGate):
|
225 |
+
if not self.eval_controls(qubits):
|
226 |
+
return qubits
|
227 |
+
|
228 |
+
targets = self.targets
|
229 |
+
target_matrix = self.get_target_matrix(format='sympy')
|
230 |
+
|
231 |
+
# Find which column of the target matrix this applies to.
|
232 |
+
column_index = 0
|
233 |
+
n = 1
|
234 |
+
for target in targets:
|
235 |
+
column_index += n*qubits[target]
|
236 |
+
n = n << 1
|
237 |
+
column = target_matrix[:, int(column_index)]
|
238 |
+
|
239 |
+
# Now apply each column element to the qubit.
|
240 |
+
result = 0
|
241 |
+
for index in range(column.rows):
|
242 |
+
# TODO: This can be optimized to reduce the number of Qubit
|
243 |
+
# creations. We should simply manipulate the raw list of qubit
|
244 |
+
# values and then build the new Qubit object once.
|
245 |
+
# Make a copy of the incoming qubits.
|
246 |
+
new_qubit = qubits.__class__(*qubits.args)
|
247 |
+
# Flip the bits that need to be flipped.
|
248 |
+
for bit, target in enumerate(targets):
|
249 |
+
if new_qubit[target] != (index >> bit) & 1:
|
250 |
+
new_qubit = new_qubit.flip(target)
|
251 |
+
# The value in that row and column times the flipped-bit qubit
|
252 |
+
# is the result for that part.
|
253 |
+
result += column[index]*new_qubit
|
254 |
+
return result
|
255 |
+
|
256 |
+
#-------------------------------------------------------------------------
|
257 |
+
# Represent
|
258 |
+
#-------------------------------------------------------------------------
|
259 |
+
|
260 |
+
def _represent_default_basis(self, **options):
|
261 |
+
return self._represent_ZGate(None, **options)
|
262 |
+
|
263 |
+
def _represent_ZGate(self, basis, **options):
|
264 |
+
format = options.get('format', 'sympy')
|
265 |
+
nqubits = options.get('nqubits', 0)
|
266 |
+
if nqubits == 0:
|
267 |
+
raise QuantumError(
|
268 |
+
'The number of qubits must be given as nqubits.')
|
269 |
+
|
270 |
+
# Make sure we have enough qubits for the gate.
|
271 |
+
if nqubits < self.min_qubits:
|
272 |
+
raise QuantumError(
|
273 |
+
'The number of qubits %r is too small for the gate.' % nqubits
|
274 |
+
)
|
275 |
+
|
276 |
+
target_matrix = self.get_target_matrix(format)
|
277 |
+
targets = self.targets
|
278 |
+
if isinstance(self, CGate):
|
279 |
+
controls = self.controls
|
280 |
+
else:
|
281 |
+
controls = []
|
282 |
+
m = represent_zbasis(
|
283 |
+
controls, targets, target_matrix, nqubits, format
|
284 |
+
)
|
285 |
+
return m
|
286 |
+
|
287 |
+
#-------------------------------------------------------------------------
|
288 |
+
# Print methods
|
289 |
+
#-------------------------------------------------------------------------
|
290 |
+
|
291 |
+
def _sympystr(self, printer, *args):
|
292 |
+
label = self._print_label(printer, *args)
|
293 |
+
return '%s(%s)' % (self.gate_name, label)
|
294 |
+
|
295 |
+
def _pretty(self, printer, *args):
|
296 |
+
a = stringPict(self.gate_name)
|
297 |
+
b = self._print_label_pretty(printer, *args)
|
298 |
+
return self._print_subscript_pretty(a, b)
|
299 |
+
|
300 |
+
def _latex(self, printer, *args):
|
301 |
+
label = self._print_label(printer, *args)
|
302 |
+
return '%s_{%s}' % (self.gate_name_latex, label)
|
303 |
+
|
304 |
+
def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
|
305 |
+
raise NotImplementedError('plot_gate is not implemented.')
|
306 |
+
|
307 |
+
|
308 |
+
class CGate(Gate):
|
309 |
+
"""A general unitary gate with control qubits.
|
310 |
+
|
311 |
+
A general control gate applies a target gate to a set of targets if all
|
312 |
+
of the control qubits have a particular values (set by
|
313 |
+
``CGate.control_value``).
|
314 |
+
|
315 |
+
Parameters
|
316 |
+
----------
|
317 |
+
label : tuple
|
318 |
+
The label in this case has the form (controls, gate), where controls
|
319 |
+
is a tuple/list of control qubits (as ints) and gate is a ``Gate``
|
320 |
+
instance that is the target operator.
|
321 |
+
|
322 |
+
Examples
|
323 |
+
========
|
324 |
+
|
325 |
+
"""
|
326 |
+
|
327 |
+
gate_name = 'C'
|
328 |
+
gate_name_latex = 'C'
|
329 |
+
|
330 |
+
# The values this class controls for.
|
331 |
+
control_value = _S.One
|
332 |
+
|
333 |
+
simplify_cgate = False
|
334 |
+
|
335 |
+
#-------------------------------------------------------------------------
|
336 |
+
# Initialization
|
337 |
+
#-------------------------------------------------------------------------
|
338 |
+
|
339 |
+
@classmethod
|
340 |
+
def _eval_args(cls, args):
|
341 |
+
# _eval_args has the right logic for the controls argument.
|
342 |
+
controls = args[0]
|
343 |
+
gate = args[1]
|
344 |
+
if not is_sequence(controls):
|
345 |
+
controls = (controls,)
|
346 |
+
controls = UnitaryOperator._eval_args(controls)
|
347 |
+
_validate_targets_controls(chain(controls, gate.targets))
|
348 |
+
return (Tuple(*controls), gate)
|
349 |
+
|
350 |
+
@classmethod
|
351 |
+
def _eval_hilbert_space(cls, args):
|
352 |
+
"""This returns the smallest possible Hilbert space."""
|
353 |
+
return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
|
354 |
+
|
355 |
+
#-------------------------------------------------------------------------
|
356 |
+
# Properties
|
357 |
+
#-------------------------------------------------------------------------
|
358 |
+
|
359 |
+
@property
|
360 |
+
def nqubits(self):
|
361 |
+
"""The total number of qubits this gate acts on.
|
362 |
+
|
363 |
+
For controlled gate subclasses this includes both target and control
|
364 |
+
qubits, so that, for examples the CNOT gate acts on 2 qubits.
|
365 |
+
"""
|
366 |
+
return len(self.targets) + len(self.controls)
|
367 |
+
|
368 |
+
@property
|
369 |
+
def min_qubits(self):
|
370 |
+
"""The minimum number of qubits this gate needs to act on."""
|
371 |
+
return _max(_max(self.controls), _max(self.targets)) + 1
|
372 |
+
|
373 |
+
@property
|
374 |
+
def targets(self):
|
375 |
+
"""A tuple of target qubits."""
|
376 |
+
return self.gate.targets
|
377 |
+
|
378 |
+
@property
|
379 |
+
def controls(self):
|
380 |
+
"""A tuple of control qubits."""
|
381 |
+
return tuple(self.label[0])
|
382 |
+
|
383 |
+
@property
|
384 |
+
def gate(self):
|
385 |
+
"""The non-controlled gate that will be applied to the targets."""
|
386 |
+
return self.label[1]
|
387 |
+
|
388 |
+
#-------------------------------------------------------------------------
|
389 |
+
# Gate methods
|
390 |
+
#-------------------------------------------------------------------------
|
391 |
+
|
392 |
+
def get_target_matrix(self, format='sympy'):
|
393 |
+
return self.gate.get_target_matrix(format)
|
394 |
+
|
395 |
+
def eval_controls(self, qubit):
|
396 |
+
"""Return True/False to indicate if the controls are satisfied."""
|
397 |
+
return all(qubit[bit] == self.control_value for bit in self.controls)
|
398 |
+
|
399 |
+
def decompose(self, **options):
|
400 |
+
"""Decompose the controlled gate into CNOT and single qubits gates."""
|
401 |
+
if len(self.controls) == 1:
|
402 |
+
c = self.controls[0]
|
403 |
+
t = self.gate.targets[0]
|
404 |
+
if isinstance(self.gate, YGate):
|
405 |
+
g1 = PhaseGate(t)
|
406 |
+
g2 = CNotGate(c, t)
|
407 |
+
g3 = PhaseGate(t)
|
408 |
+
g4 = ZGate(t)
|
409 |
+
return g1*g2*g3*g4
|
410 |
+
if isinstance(self.gate, ZGate):
|
411 |
+
g1 = HadamardGate(t)
|
412 |
+
g2 = CNotGate(c, t)
|
413 |
+
g3 = HadamardGate(t)
|
414 |
+
return g1*g2*g3
|
415 |
+
else:
|
416 |
+
return self
|
417 |
+
|
418 |
+
#-------------------------------------------------------------------------
|
419 |
+
# Print methods
|
420 |
+
#-------------------------------------------------------------------------
|
421 |
+
|
422 |
+
def _print_label(self, printer, *args):
|
423 |
+
controls = self._print_sequence(self.controls, ',', printer, *args)
|
424 |
+
gate = printer._print(self.gate, *args)
|
425 |
+
return '(%s),%s' % (controls, gate)
|
426 |
+
|
427 |
+
def _pretty(self, printer, *args):
|
428 |
+
controls = self._print_sequence_pretty(
|
429 |
+
self.controls, ',', printer, *args)
|
430 |
+
gate = printer._print(self.gate)
|
431 |
+
gate_name = stringPict(self.gate_name)
|
432 |
+
first = self._print_subscript_pretty(gate_name, controls)
|
433 |
+
gate = self._print_parens_pretty(gate)
|
434 |
+
final = prettyForm(*first.right(gate))
|
435 |
+
return final
|
436 |
+
|
437 |
+
def _latex(self, printer, *args):
|
438 |
+
controls = self._print_sequence(self.controls, ',', printer, *args)
|
439 |
+
gate = printer._print(self.gate, *args)
|
440 |
+
return r'%s_{%s}{\left(%s\right)}' % \
|
441 |
+
(self.gate_name_latex, controls, gate)
|
442 |
+
|
443 |
+
def plot_gate(self, circ_plot, gate_idx):
|
444 |
+
"""
|
445 |
+
Plot the controlled gate. If *simplify_cgate* is true, simplify
|
446 |
+
C-X and C-Z gates into their more familiar forms.
|
447 |
+
"""
|
448 |
+
min_wire = int(_min(chain(self.controls, self.targets)))
|
449 |
+
max_wire = int(_max(chain(self.controls, self.targets)))
|
450 |
+
circ_plot.control_line(gate_idx, min_wire, max_wire)
|
451 |
+
for c in self.controls:
|
452 |
+
circ_plot.control_point(gate_idx, int(c))
|
453 |
+
if self.simplify_cgate:
|
454 |
+
if self.gate.gate_name == 'X':
|
455 |
+
self.gate.plot_gate_plus(circ_plot, gate_idx)
|
456 |
+
elif self.gate.gate_name == 'Z':
|
457 |
+
circ_plot.control_point(gate_idx, self.targets[0])
|
458 |
+
else:
|
459 |
+
self.gate.plot_gate(circ_plot, gate_idx)
|
460 |
+
else:
|
461 |
+
self.gate.plot_gate(circ_plot, gate_idx)
|
462 |
+
|
463 |
+
#-------------------------------------------------------------------------
|
464 |
+
# Miscellaneous
|
465 |
+
#-------------------------------------------------------------------------
|
466 |
+
|
467 |
+
def _eval_dagger(self):
|
468 |
+
if isinstance(self.gate, HermitianOperator):
|
469 |
+
return self
|
470 |
+
else:
|
471 |
+
return Gate._eval_dagger(self)
|
472 |
+
|
473 |
+
def _eval_inverse(self):
|
474 |
+
if isinstance(self.gate, HermitianOperator):
|
475 |
+
return self
|
476 |
+
else:
|
477 |
+
return Gate._eval_inverse(self)
|
478 |
+
|
479 |
+
def _eval_power(self, exp):
|
480 |
+
if isinstance(self.gate, HermitianOperator):
|
481 |
+
if exp == -1:
|
482 |
+
return Gate._eval_power(self, exp)
|
483 |
+
elif abs(exp) % 2 == 0:
|
484 |
+
return self*(Gate._eval_inverse(self))
|
485 |
+
else:
|
486 |
+
return self
|
487 |
+
else:
|
488 |
+
return Gate._eval_power(self, exp)
|
489 |
+
|
490 |
+
class CGateS(CGate):
|
491 |
+
"""Version of CGate that allows gate simplifications.
|
492 |
+
I.e. cnot looks like an oplus, cphase has dots, etc.
|
493 |
+
"""
|
494 |
+
simplify_cgate=True
|
495 |
+
|
496 |
+
|
497 |
+
class UGate(Gate):
|
498 |
+
"""General gate specified by a set of targets and a target matrix.
|
499 |
+
|
500 |
+
Parameters
|
501 |
+
----------
|
502 |
+
label : tuple
|
503 |
+
A tuple of the form (targets, U), where targets is a tuple of the
|
504 |
+
target qubits and U is a unitary matrix with dimension of
|
505 |
+
len(targets).
|
506 |
+
"""
|
507 |
+
gate_name = 'U'
|
508 |
+
gate_name_latex = 'U'
|
509 |
+
|
510 |
+
#-------------------------------------------------------------------------
|
511 |
+
# Initialization
|
512 |
+
#-------------------------------------------------------------------------
|
513 |
+
|
514 |
+
@classmethod
|
515 |
+
def _eval_args(cls, args):
|
516 |
+
targets = args[0]
|
517 |
+
if not is_sequence(targets):
|
518 |
+
targets = (targets,)
|
519 |
+
targets = Gate._eval_args(targets)
|
520 |
+
_validate_targets_controls(targets)
|
521 |
+
mat = args[1]
|
522 |
+
if not isinstance(mat, MatrixBase):
|
523 |
+
raise TypeError('Matrix expected, got: %r' % mat)
|
524 |
+
#make sure this matrix is of a Basic type
|
525 |
+
mat = _sympify(mat)
|
526 |
+
dim = 2**len(targets)
|
527 |
+
if not all(dim == shape for shape in mat.shape):
|
528 |
+
raise IndexError(
|
529 |
+
'Number of targets must match the matrix size: %r %r' %
|
530 |
+
(targets, mat)
|
531 |
+
)
|
532 |
+
return (targets, mat)
|
533 |
+
|
534 |
+
@classmethod
|
535 |
+
def _eval_hilbert_space(cls, args):
|
536 |
+
"""This returns the smallest possible Hilbert space."""
|
537 |
+
return ComplexSpace(2)**(_max(args[0]) + 1)
|
538 |
+
|
539 |
+
#-------------------------------------------------------------------------
|
540 |
+
# Properties
|
541 |
+
#-------------------------------------------------------------------------
|
542 |
+
|
543 |
+
@property
|
544 |
+
def targets(self):
|
545 |
+
"""A tuple of target qubits."""
|
546 |
+
return tuple(self.label[0])
|
547 |
+
|
548 |
+
#-------------------------------------------------------------------------
|
549 |
+
# Gate methods
|
550 |
+
#-------------------------------------------------------------------------
|
551 |
+
|
552 |
+
def get_target_matrix(self, format='sympy'):
|
553 |
+
"""The matrix rep. of the target part of the gate.
|
554 |
+
|
555 |
+
Parameters
|
556 |
+
----------
|
557 |
+
format : str
|
558 |
+
The format string ('sympy','numpy', etc.)
|
559 |
+
"""
|
560 |
+
return self.label[1]
|
561 |
+
|
562 |
+
#-------------------------------------------------------------------------
|
563 |
+
# Print methods
|
564 |
+
#-------------------------------------------------------------------------
|
565 |
+
def _pretty(self, printer, *args):
|
566 |
+
targets = self._print_sequence_pretty(
|
567 |
+
self.targets, ',', printer, *args)
|
568 |
+
gate_name = stringPict(self.gate_name)
|
569 |
+
return self._print_subscript_pretty(gate_name, targets)
|
570 |
+
|
571 |
+
def _latex(self, printer, *args):
|
572 |
+
targets = self._print_sequence(self.targets, ',', printer, *args)
|
573 |
+
return r'%s_{%s}' % (self.gate_name_latex, targets)
|
574 |
+
|
575 |
+
def plot_gate(self, circ_plot, gate_idx):
|
576 |
+
circ_plot.one_qubit_box(
|
577 |
+
self.gate_name_plot,
|
578 |
+
gate_idx, int(self.targets[0])
|
579 |
+
)
|
580 |
+
|
581 |
+
|
582 |
+
class OneQubitGate(Gate):
|
583 |
+
"""A single qubit unitary gate base class."""
|
584 |
+
|
585 |
+
nqubits = _S.One
|
586 |
+
|
587 |
+
def plot_gate(self, circ_plot, gate_idx):
|
588 |
+
circ_plot.one_qubit_box(
|
589 |
+
self.gate_name_plot,
|
590 |
+
gate_idx, int(self.targets[0])
|
591 |
+
)
|
592 |
+
|
593 |
+
def _eval_commutator(self, other, **hints):
|
594 |
+
if isinstance(other, OneQubitGate):
|
595 |
+
if self.targets != other.targets or self.__class__ == other.__class__:
|
596 |
+
return _S.Zero
|
597 |
+
return Operator._eval_commutator(self, other, **hints)
|
598 |
+
|
599 |
+
def _eval_anticommutator(self, other, **hints):
|
600 |
+
if isinstance(other, OneQubitGate):
|
601 |
+
if self.targets != other.targets or self.__class__ == other.__class__:
|
602 |
+
return Integer(2)*self*other
|
603 |
+
return Operator._eval_anticommutator(self, other, **hints)
|
604 |
+
|
605 |
+
|
606 |
+
class TwoQubitGate(Gate):
|
607 |
+
"""A two qubit unitary gate base class."""
|
608 |
+
|
609 |
+
nqubits = Integer(2)
|
610 |
+
|
611 |
+
#-----------------------------------------------------------------------------
|
612 |
+
# Single Qubit Gates
|
613 |
+
#-----------------------------------------------------------------------------
|
614 |
+
|
615 |
+
|
616 |
+
class IdentityGate(OneQubitGate):
|
617 |
+
"""The single qubit identity gate.
|
618 |
+
|
619 |
+
Parameters
|
620 |
+
----------
|
621 |
+
target : int
|
622 |
+
The target qubit this gate will apply to.
|
623 |
+
|
624 |
+
Examples
|
625 |
+
========
|
626 |
+
|
627 |
+
"""
|
628 |
+
gate_name = '1'
|
629 |
+
gate_name_latex = '1'
|
630 |
+
|
631 |
+
# Short cut version of gate._apply_operator_Qubit
|
632 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
633 |
+
# Check number of qubits this gate acts on (see gate._apply_operator_Qubit)
|
634 |
+
if qubits.nqubits < self.min_qubits:
|
635 |
+
raise QuantumError(
|
636 |
+
'Gate needs a minimum of %r qubits to act on, got: %r' %
|
637 |
+
(self.min_qubits, qubits.nqubits)
|
638 |
+
)
|
639 |
+
return qubits # no computation required for IdentityGate
|
640 |
+
|
641 |
+
def get_target_matrix(self, format='sympy'):
|
642 |
+
return matrix_cache.get_matrix('eye2', format)
|
643 |
+
|
644 |
+
def _eval_commutator(self, other, **hints):
|
645 |
+
return _S.Zero
|
646 |
+
|
647 |
+
def _eval_anticommutator(self, other, **hints):
|
648 |
+
return Integer(2)*other
|
649 |
+
|
650 |
+
|
651 |
+
class HadamardGate(HermitianOperator, OneQubitGate):
|
652 |
+
"""The single qubit Hadamard gate.
|
653 |
+
|
654 |
+
Parameters
|
655 |
+
----------
|
656 |
+
target : int
|
657 |
+
The target qubit this gate will apply to.
|
658 |
+
|
659 |
+
Examples
|
660 |
+
========
|
661 |
+
|
662 |
+
>>> from sympy import sqrt
|
663 |
+
>>> from sympy.physics.quantum.qubit import Qubit
|
664 |
+
>>> from sympy.physics.quantum.gate import HadamardGate
|
665 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
666 |
+
>>> qapply(HadamardGate(0)*Qubit('1'))
|
667 |
+
sqrt(2)*|0>/2 - sqrt(2)*|1>/2
|
668 |
+
>>> # Hadamard on bell state, applied on 2 qubits.
|
669 |
+
>>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
|
670 |
+
>>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
|
671 |
+
sqrt(2)*|00>/2 + sqrt(2)*|11>/2
|
672 |
+
|
673 |
+
"""
|
674 |
+
gate_name = 'H'
|
675 |
+
gate_name_latex = 'H'
|
676 |
+
|
677 |
+
def get_target_matrix(self, format='sympy'):
|
678 |
+
if _normalized:
|
679 |
+
return matrix_cache.get_matrix('H', format)
|
680 |
+
else:
|
681 |
+
return matrix_cache.get_matrix('Hsqrt2', format)
|
682 |
+
|
683 |
+
def _eval_commutator_XGate(self, other, **hints):
|
684 |
+
return I*sqrt(2)*YGate(self.targets[0])
|
685 |
+
|
686 |
+
def _eval_commutator_YGate(self, other, **hints):
|
687 |
+
return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
|
688 |
+
|
689 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
690 |
+
return -I*sqrt(2)*YGate(self.targets[0])
|
691 |
+
|
692 |
+
def _eval_anticommutator_XGate(self, other, **hints):
|
693 |
+
return sqrt(2)*IdentityGate(self.targets[0])
|
694 |
+
|
695 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
696 |
+
return _S.Zero
|
697 |
+
|
698 |
+
def _eval_anticommutator_ZGate(self, other, **hints):
|
699 |
+
return sqrt(2)*IdentityGate(self.targets[0])
|
700 |
+
|
701 |
+
|
702 |
+
class XGate(HermitianOperator, OneQubitGate):
|
703 |
+
"""The single qubit X, or NOT, gate.
|
704 |
+
|
705 |
+
Parameters
|
706 |
+
----------
|
707 |
+
target : int
|
708 |
+
The target qubit this gate will apply to.
|
709 |
+
|
710 |
+
Examples
|
711 |
+
========
|
712 |
+
|
713 |
+
"""
|
714 |
+
gate_name = 'X'
|
715 |
+
gate_name_latex = 'X'
|
716 |
+
|
717 |
+
def get_target_matrix(self, format='sympy'):
|
718 |
+
return matrix_cache.get_matrix('X', format)
|
719 |
+
|
720 |
+
def plot_gate(self, circ_plot, gate_idx):
|
721 |
+
OneQubitGate.plot_gate(self,circ_plot,gate_idx)
|
722 |
+
|
723 |
+
def plot_gate_plus(self, circ_plot, gate_idx):
|
724 |
+
circ_plot.not_point(
|
725 |
+
gate_idx, int(self.label[0])
|
726 |
+
)
|
727 |
+
|
728 |
+
def _eval_commutator_YGate(self, other, **hints):
|
729 |
+
return Integer(2)*I*ZGate(self.targets[0])
|
730 |
+
|
731 |
+
def _eval_anticommutator_XGate(self, other, **hints):
|
732 |
+
return Integer(2)*IdentityGate(self.targets[0])
|
733 |
+
|
734 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
735 |
+
return _S.Zero
|
736 |
+
|
737 |
+
def _eval_anticommutator_ZGate(self, other, **hints):
|
738 |
+
return _S.Zero
|
739 |
+
|
740 |
+
|
741 |
+
class YGate(HermitianOperator, OneQubitGate):
|
742 |
+
"""The single qubit Y gate.
|
743 |
+
|
744 |
+
Parameters
|
745 |
+
----------
|
746 |
+
target : int
|
747 |
+
The target qubit this gate will apply to.
|
748 |
+
|
749 |
+
Examples
|
750 |
+
========
|
751 |
+
|
752 |
+
"""
|
753 |
+
gate_name = 'Y'
|
754 |
+
gate_name_latex = 'Y'
|
755 |
+
|
756 |
+
def get_target_matrix(self, format='sympy'):
|
757 |
+
return matrix_cache.get_matrix('Y', format)
|
758 |
+
|
759 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
760 |
+
return Integer(2)*I*XGate(self.targets[0])
|
761 |
+
|
762 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
763 |
+
return Integer(2)*IdentityGate(self.targets[0])
|
764 |
+
|
765 |
+
def _eval_anticommutator_ZGate(self, other, **hints):
|
766 |
+
return _S.Zero
|
767 |
+
|
768 |
+
|
769 |
+
class ZGate(HermitianOperator, OneQubitGate):
|
770 |
+
"""The single qubit Z gate.
|
771 |
+
|
772 |
+
Parameters
|
773 |
+
----------
|
774 |
+
target : int
|
775 |
+
The target qubit this gate will apply to.
|
776 |
+
|
777 |
+
Examples
|
778 |
+
========
|
779 |
+
|
780 |
+
"""
|
781 |
+
gate_name = 'Z'
|
782 |
+
gate_name_latex = 'Z'
|
783 |
+
|
784 |
+
def get_target_matrix(self, format='sympy'):
|
785 |
+
return matrix_cache.get_matrix('Z', format)
|
786 |
+
|
787 |
+
def _eval_commutator_XGate(self, other, **hints):
|
788 |
+
return Integer(2)*I*YGate(self.targets[0])
|
789 |
+
|
790 |
+
def _eval_anticommutator_YGate(self, other, **hints):
|
791 |
+
return _S.Zero
|
792 |
+
|
793 |
+
|
794 |
+
class PhaseGate(OneQubitGate):
|
795 |
+
"""The single qubit phase, or S, gate.
|
796 |
+
|
797 |
+
This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
|
798 |
+
does nothing if the state is ``|0>``.
|
799 |
+
|
800 |
+
Parameters
|
801 |
+
----------
|
802 |
+
target : int
|
803 |
+
The target qubit this gate will apply to.
|
804 |
+
|
805 |
+
Examples
|
806 |
+
========
|
807 |
+
|
808 |
+
"""
|
809 |
+
gate_name = 'S'
|
810 |
+
gate_name_latex = 'S'
|
811 |
+
|
812 |
+
def get_target_matrix(self, format='sympy'):
|
813 |
+
return matrix_cache.get_matrix('S', format)
|
814 |
+
|
815 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
816 |
+
return _S.Zero
|
817 |
+
|
818 |
+
def _eval_commutator_TGate(self, other, **hints):
|
819 |
+
return _S.Zero
|
820 |
+
|
821 |
+
|
822 |
+
class TGate(OneQubitGate):
|
823 |
+
"""The single qubit pi/8 gate.
|
824 |
+
|
825 |
+
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
|
826 |
+
does nothing if the state is ``|0>``.
|
827 |
+
|
828 |
+
Parameters
|
829 |
+
----------
|
830 |
+
target : int
|
831 |
+
The target qubit this gate will apply to.
|
832 |
+
|
833 |
+
Examples
|
834 |
+
========
|
835 |
+
|
836 |
+
"""
|
837 |
+
gate_name = 'T'
|
838 |
+
gate_name_latex = 'T'
|
839 |
+
|
840 |
+
def get_target_matrix(self, format='sympy'):
|
841 |
+
return matrix_cache.get_matrix('T', format)
|
842 |
+
|
843 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
844 |
+
return _S.Zero
|
845 |
+
|
846 |
+
def _eval_commutator_PhaseGate(self, other, **hints):
|
847 |
+
return _S.Zero
|
848 |
+
|
849 |
+
|
850 |
+
# Aliases for gate names.
|
851 |
+
H = HadamardGate
|
852 |
+
X = XGate
|
853 |
+
Y = YGate
|
854 |
+
Z = ZGate
|
855 |
+
T = TGate
|
856 |
+
Phase = S = PhaseGate
|
857 |
+
|
858 |
+
|
859 |
+
#-----------------------------------------------------------------------------
|
860 |
+
# 2 Qubit Gates
|
861 |
+
#-----------------------------------------------------------------------------
|
862 |
+
|
863 |
+
|
864 |
+
class CNotGate(HermitianOperator, CGate, TwoQubitGate):
|
865 |
+
"""Two qubit controlled-NOT.
|
866 |
+
|
867 |
+
This gate performs the NOT or X gate on the target qubit if the control
|
868 |
+
qubits all have the value 1.
|
869 |
+
|
870 |
+
Parameters
|
871 |
+
----------
|
872 |
+
label : tuple
|
873 |
+
A tuple of the form (control, target).
|
874 |
+
|
875 |
+
Examples
|
876 |
+
========
|
877 |
+
|
878 |
+
>>> from sympy.physics.quantum.gate import CNOT
|
879 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
880 |
+
>>> from sympy.physics.quantum.qubit import Qubit
|
881 |
+
>>> c = CNOT(1,0)
|
882 |
+
>>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
|
883 |
+
|11>
|
884 |
+
|
885 |
+
"""
|
886 |
+
gate_name = 'CNOT'
|
887 |
+
gate_name_latex = r'\text{CNOT}'
|
888 |
+
simplify_cgate = True
|
889 |
+
|
890 |
+
#-------------------------------------------------------------------------
|
891 |
+
# Initialization
|
892 |
+
#-------------------------------------------------------------------------
|
893 |
+
|
894 |
+
@classmethod
|
895 |
+
def _eval_args(cls, args):
|
896 |
+
args = Gate._eval_args(args)
|
897 |
+
return args
|
898 |
+
|
899 |
+
@classmethod
|
900 |
+
def _eval_hilbert_space(cls, args):
|
901 |
+
"""This returns the smallest possible Hilbert space."""
|
902 |
+
return ComplexSpace(2)**(_max(args) + 1)
|
903 |
+
|
904 |
+
#-------------------------------------------------------------------------
|
905 |
+
# Properties
|
906 |
+
#-------------------------------------------------------------------------
|
907 |
+
|
908 |
+
@property
|
909 |
+
def min_qubits(self):
|
910 |
+
"""The minimum number of qubits this gate needs to act on."""
|
911 |
+
return _max(self.label) + 1
|
912 |
+
|
913 |
+
@property
|
914 |
+
def targets(self):
|
915 |
+
"""A tuple of target qubits."""
|
916 |
+
return (self.label[1],)
|
917 |
+
|
918 |
+
@property
|
919 |
+
def controls(self):
|
920 |
+
"""A tuple of control qubits."""
|
921 |
+
return (self.label[0],)
|
922 |
+
|
923 |
+
@property
|
924 |
+
def gate(self):
|
925 |
+
"""The non-controlled gate that will be applied to the targets."""
|
926 |
+
return XGate(self.label[1])
|
927 |
+
|
928 |
+
#-------------------------------------------------------------------------
|
929 |
+
# Properties
|
930 |
+
#-------------------------------------------------------------------------
|
931 |
+
|
932 |
+
# The default printing of Gate works better than those of CGate, so we
|
933 |
+
# go around the overridden methods in CGate.
|
934 |
+
|
935 |
+
def _print_label(self, printer, *args):
|
936 |
+
return Gate._print_label(self, printer, *args)
|
937 |
+
|
938 |
+
def _pretty(self, printer, *args):
|
939 |
+
return Gate._pretty(self, printer, *args)
|
940 |
+
|
941 |
+
def _latex(self, printer, *args):
|
942 |
+
return Gate._latex(self, printer, *args)
|
943 |
+
|
944 |
+
#-------------------------------------------------------------------------
|
945 |
+
# Commutator/AntiCommutator
|
946 |
+
#-------------------------------------------------------------------------
|
947 |
+
|
948 |
+
def _eval_commutator_ZGate(self, other, **hints):
|
949 |
+
"""[CNOT(i, j), Z(i)] == 0."""
|
950 |
+
if self.controls[0] == other.targets[0]:
|
951 |
+
return _S.Zero
|
952 |
+
else:
|
953 |
+
raise NotImplementedError('Commutator not implemented: %r' % other)
|
954 |
+
|
955 |
+
def _eval_commutator_TGate(self, other, **hints):
|
956 |
+
"""[CNOT(i, j), T(i)] == 0."""
|
957 |
+
return self._eval_commutator_ZGate(other, **hints)
|
958 |
+
|
959 |
+
def _eval_commutator_PhaseGate(self, other, **hints):
|
960 |
+
"""[CNOT(i, j), S(i)] == 0."""
|
961 |
+
return self._eval_commutator_ZGate(other, **hints)
|
962 |
+
|
963 |
+
def _eval_commutator_XGate(self, other, **hints):
|
964 |
+
"""[CNOT(i, j), X(j)] == 0."""
|
965 |
+
if self.targets[0] == other.targets[0]:
|
966 |
+
return _S.Zero
|
967 |
+
else:
|
968 |
+
raise NotImplementedError('Commutator not implemented: %r' % other)
|
969 |
+
|
970 |
+
def _eval_commutator_CNotGate(self, other, **hints):
|
971 |
+
"""[CNOT(i, j), CNOT(i,k)] == 0."""
|
972 |
+
if self.controls[0] == other.controls[0]:
|
973 |
+
return _S.Zero
|
974 |
+
else:
|
975 |
+
raise NotImplementedError('Commutator not implemented: %r' % other)
|
976 |
+
|
977 |
+
|
978 |
+
class SwapGate(TwoQubitGate):
|
979 |
+
"""Two qubit SWAP gate.
|
980 |
+
|
981 |
+
This gate swap the values of the two qubits.
|
982 |
+
|
983 |
+
Parameters
|
984 |
+
----------
|
985 |
+
label : tuple
|
986 |
+
A tuple of the form (target1, target2).
|
987 |
+
|
988 |
+
Examples
|
989 |
+
========
|
990 |
+
|
991 |
+
"""
|
992 |
+
gate_name = 'SWAP'
|
993 |
+
gate_name_latex = r'\text{SWAP}'
|
994 |
+
|
995 |
+
def get_target_matrix(self, format='sympy'):
|
996 |
+
return matrix_cache.get_matrix('SWAP', format)
|
997 |
+
|
998 |
+
def decompose(self, **options):
|
999 |
+
"""Decompose the SWAP gate into CNOT gates."""
|
1000 |
+
i, j = self.targets[0], self.targets[1]
|
1001 |
+
g1 = CNotGate(i, j)
|
1002 |
+
g2 = CNotGate(j, i)
|
1003 |
+
return g1*g2*g1
|
1004 |
+
|
1005 |
+
def plot_gate(self, circ_plot, gate_idx):
|
1006 |
+
min_wire = int(_min(self.targets))
|
1007 |
+
max_wire = int(_max(self.targets))
|
1008 |
+
circ_plot.control_line(gate_idx, min_wire, max_wire)
|
1009 |
+
circ_plot.swap_point(gate_idx, min_wire)
|
1010 |
+
circ_plot.swap_point(gate_idx, max_wire)
|
1011 |
+
|
1012 |
+
def _represent_ZGate(self, basis, **options):
|
1013 |
+
"""Represent the SWAP gate in the computational basis.
|
1014 |
+
|
1015 |
+
The following representation is used to compute this:
|
1016 |
+
|
1017 |
+
SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
|
1018 |
+
"""
|
1019 |
+
format = options.get('format', 'sympy')
|
1020 |
+
targets = [int(t) for t in self.targets]
|
1021 |
+
min_target = _min(targets)
|
1022 |
+
max_target = _max(targets)
|
1023 |
+
nqubits = options.get('nqubits', self.min_qubits)
|
1024 |
+
|
1025 |
+
op01 = matrix_cache.get_matrix('op01', format)
|
1026 |
+
op10 = matrix_cache.get_matrix('op10', format)
|
1027 |
+
op11 = matrix_cache.get_matrix('op11', format)
|
1028 |
+
op00 = matrix_cache.get_matrix('op00', format)
|
1029 |
+
eye2 = matrix_cache.get_matrix('eye2', format)
|
1030 |
+
|
1031 |
+
result = None
|
1032 |
+
for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
|
1033 |
+
product = nqubits*[eye2]
|
1034 |
+
product[nqubits - min_target - 1] = i
|
1035 |
+
product[nqubits - max_target - 1] = j
|
1036 |
+
new_result = matrix_tensor_product(*product)
|
1037 |
+
if result is None:
|
1038 |
+
result = new_result
|
1039 |
+
else:
|
1040 |
+
result = result + new_result
|
1041 |
+
|
1042 |
+
return result
|
1043 |
+
|
1044 |
+
|
1045 |
+
# Aliases for gate names.
|
1046 |
+
CNOT = CNotGate
|
1047 |
+
SWAP = SwapGate
|
1048 |
+
def CPHASE(a,b): return CGateS((a,),Z(b))
|
1049 |
+
|
1050 |
+
|
1051 |
+
#-----------------------------------------------------------------------------
|
1052 |
+
# Represent
|
1053 |
+
#-----------------------------------------------------------------------------
|
1054 |
+
|
1055 |
+
|
1056 |
+
def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
|
1057 |
+
"""Represent a gate with controls, targets and target_matrix.
|
1058 |
+
|
1059 |
+
This function does the low-level work of representing gates as matrices
|
1060 |
+
in the standard computational basis (ZGate). Currently, we support two
|
1061 |
+
main cases:
|
1062 |
+
|
1063 |
+
1. One target qubit and no control qubits.
|
1064 |
+
2. One target qubits and multiple control qubits.
|
1065 |
+
|
1066 |
+
For the base of multiple controls, we use the following expression [1]:
|
1067 |
+
|
1068 |
+
1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
|
1069 |
+
|
1070 |
+
Parameters
|
1071 |
+
----------
|
1072 |
+
controls : list, tuple
|
1073 |
+
A sequence of control qubits.
|
1074 |
+
targets : list, tuple
|
1075 |
+
A sequence of target qubits.
|
1076 |
+
target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
|
1077 |
+
The matrix form of the transformation to be performed on the target
|
1078 |
+
qubits. The format of this matrix must match that passed into
|
1079 |
+
the `format` argument.
|
1080 |
+
nqubits : int
|
1081 |
+
The total number of qubits used for the representation.
|
1082 |
+
format : str
|
1083 |
+
The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
|
1084 |
+
|
1085 |
+
Examples
|
1086 |
+
========
|
1087 |
+
|
1088 |
+
References
|
1089 |
+
----------
|
1090 |
+
[1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
|
1091 |
+
"""
|
1092 |
+
controls = [int(x) for x in controls]
|
1093 |
+
targets = [int(x) for x in targets]
|
1094 |
+
nqubits = int(nqubits)
|
1095 |
+
|
1096 |
+
# This checks for the format as well.
|
1097 |
+
op11 = matrix_cache.get_matrix('op11', format)
|
1098 |
+
eye2 = matrix_cache.get_matrix('eye2', format)
|
1099 |
+
|
1100 |
+
# Plain single qubit case
|
1101 |
+
if len(controls) == 0 and len(targets) == 1:
|
1102 |
+
product = []
|
1103 |
+
bit = targets[0]
|
1104 |
+
# Fill product with [I1,Gate,I2] such that the unitaries,
|
1105 |
+
# I, cause the gate to be applied to the correct Qubit
|
1106 |
+
if bit != nqubits - 1:
|
1107 |
+
product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
|
1108 |
+
product.append(target_matrix)
|
1109 |
+
if bit != 0:
|
1110 |
+
product.append(matrix_eye(2**bit, format=format))
|
1111 |
+
return matrix_tensor_product(*product)
|
1112 |
+
|
1113 |
+
# Single target, multiple controls.
|
1114 |
+
elif len(targets) == 1 and len(controls) >= 1:
|
1115 |
+
target = targets[0]
|
1116 |
+
|
1117 |
+
# Build the non-trivial part.
|
1118 |
+
product2 = []
|
1119 |
+
for i in range(nqubits):
|
1120 |
+
product2.append(matrix_eye(2, format=format))
|
1121 |
+
for control in controls:
|
1122 |
+
product2[nqubits - 1 - control] = op11
|
1123 |
+
product2[nqubits - 1 - target] = target_matrix - eye2
|
1124 |
+
|
1125 |
+
return matrix_eye(2**nqubits, format=format) + \
|
1126 |
+
matrix_tensor_product(*product2)
|
1127 |
+
|
1128 |
+
# Multi-target, multi-control is not yet implemented.
|
1129 |
+
else:
|
1130 |
+
raise NotImplementedError(
|
1131 |
+
'The representation of multi-target, multi-control gates '
|
1132 |
+
'is not implemented.'
|
1133 |
+
)
|
1134 |
+
|
1135 |
+
|
1136 |
+
#-----------------------------------------------------------------------------
|
1137 |
+
# Gate manipulation functions.
|
1138 |
+
#-----------------------------------------------------------------------------
|
1139 |
+
|
1140 |
+
|
1141 |
+
def gate_simp(circuit):
|
1142 |
+
"""Simplifies gates symbolically
|
1143 |
+
|
1144 |
+
It first sorts gates using gate_sort. It then applies basic
|
1145 |
+
simplification rules to the circuit, e.g., XGate**2 = Identity
|
1146 |
+
"""
|
1147 |
+
|
1148 |
+
# Bubble sort out gates that commute.
|
1149 |
+
circuit = gate_sort(circuit)
|
1150 |
+
|
1151 |
+
# Do simplifications by subing a simplification into the first element
|
1152 |
+
# which can be simplified. We recursively call gate_simp with new circuit
|
1153 |
+
# as input more simplifications exist.
|
1154 |
+
if isinstance(circuit, Add):
|
1155 |
+
return sum(gate_simp(t) for t in circuit.args)
|
1156 |
+
elif isinstance(circuit, Mul):
|
1157 |
+
circuit_args = circuit.args
|
1158 |
+
elif isinstance(circuit, Pow):
|
1159 |
+
b, e = circuit.as_base_exp()
|
1160 |
+
circuit_args = (gate_simp(b)**e,)
|
1161 |
+
else:
|
1162 |
+
return circuit
|
1163 |
+
|
1164 |
+
# Iterate through each element in circuit, simplify if possible.
|
1165 |
+
for i in range(len(circuit_args)):
|
1166 |
+
# H,X,Y or Z squared is 1.
|
1167 |
+
# T**2 = S, S**2 = Z
|
1168 |
+
if isinstance(circuit_args[i], Pow):
|
1169 |
+
if isinstance(circuit_args[i].base,
|
1170 |
+
(HadamardGate, XGate, YGate, ZGate)) \
|
1171 |
+
and isinstance(circuit_args[i].exp, Number):
|
1172 |
+
# Build a new circuit taking replacing the
|
1173 |
+
# H,X,Y,Z squared with one.
|
1174 |
+
newargs = (circuit_args[:i] +
|
1175 |
+
(circuit_args[i].base**(circuit_args[i].exp % 2),) +
|
1176 |
+
circuit_args[i + 1:])
|
1177 |
+
# Recursively simplify the new circuit.
|
1178 |
+
circuit = gate_simp(Mul(*newargs))
|
1179 |
+
break
|
1180 |
+
elif isinstance(circuit_args[i].base, PhaseGate):
|
1181 |
+
# Build a new circuit taking old circuit but splicing
|
1182 |
+
# in simplification.
|
1183 |
+
newargs = circuit_args[:i]
|
1184 |
+
# Replace PhaseGate**2 with ZGate.
|
1185 |
+
newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
|
1186 |
+
(Integer(circuit_args[i].exp/2)), circuit_args[i].base**
|
1187 |
+
(circuit_args[i].exp % 2))
|
1188 |
+
# Append the last elements.
|
1189 |
+
newargs = newargs + circuit_args[i + 1:]
|
1190 |
+
# Recursively simplify the new circuit.
|
1191 |
+
circuit = gate_simp(Mul(*newargs))
|
1192 |
+
break
|
1193 |
+
elif isinstance(circuit_args[i].base, TGate):
|
1194 |
+
# Build a new circuit taking all the old elements.
|
1195 |
+
newargs = circuit_args[:i]
|
1196 |
+
|
1197 |
+
# Put an Phasegate in place of any TGate**2.
|
1198 |
+
newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
|
1199 |
+
Integer(circuit_args[i].exp/2), circuit_args[i].base**
|
1200 |
+
(circuit_args[i].exp % 2))
|
1201 |
+
|
1202 |
+
# Append the last elements.
|
1203 |
+
newargs = newargs + circuit_args[i + 1:]
|
1204 |
+
# Recursively simplify the new circuit.
|
1205 |
+
circuit = gate_simp(Mul(*newargs))
|
1206 |
+
break
|
1207 |
+
return circuit
|
1208 |
+
|
1209 |
+
|
1210 |
+
def gate_sort(circuit):
|
1211 |
+
"""Sorts the gates while keeping track of commutation relations
|
1212 |
+
|
1213 |
+
This function uses a bubble sort to rearrange the order of gate
|
1214 |
+
application. Keeps track of Quantum computations special commutation
|
1215 |
+
relations (e.g. things that apply to the same Qubit do not commute with
|
1216 |
+
each other)
|
1217 |
+
|
1218 |
+
circuit is the Mul of gates that are to be sorted.
|
1219 |
+
"""
|
1220 |
+
# Make sure we have an Add or Mul.
|
1221 |
+
if isinstance(circuit, Add):
|
1222 |
+
return sum(gate_sort(t) for t in circuit.args)
|
1223 |
+
if isinstance(circuit, Pow):
|
1224 |
+
return gate_sort(circuit.base)**circuit.exp
|
1225 |
+
elif isinstance(circuit, Gate):
|
1226 |
+
return circuit
|
1227 |
+
if not isinstance(circuit, Mul):
|
1228 |
+
return circuit
|
1229 |
+
|
1230 |
+
changes = True
|
1231 |
+
while changes:
|
1232 |
+
changes = False
|
1233 |
+
circ_array = circuit.args
|
1234 |
+
for i in range(len(circ_array) - 1):
|
1235 |
+
# Go through each element and switch ones that are in wrong order
|
1236 |
+
if isinstance(circ_array[i], (Gate, Pow)) and \
|
1237 |
+
isinstance(circ_array[i + 1], (Gate, Pow)):
|
1238 |
+
# If we have a Pow object, look at only the base
|
1239 |
+
first_base, first_exp = circ_array[i].as_base_exp()
|
1240 |
+
second_base, second_exp = circ_array[i + 1].as_base_exp()
|
1241 |
+
|
1242 |
+
# Use SymPy's hash based sorting. This is not mathematical
|
1243 |
+
# sorting, but is rather based on comparing hashes of objects.
|
1244 |
+
# See Basic.compare for details.
|
1245 |
+
if first_base.compare(second_base) > 0:
|
1246 |
+
if Commutator(first_base, second_base).doit() == 0:
|
1247 |
+
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
|
1248 |
+
(circuit.args[i],) + circuit.args[i + 2:])
|
1249 |
+
circuit = Mul(*new_args)
|
1250 |
+
changes = True
|
1251 |
+
break
|
1252 |
+
if AntiCommutator(first_base, second_base).doit() == 0:
|
1253 |
+
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
|
1254 |
+
(circuit.args[i],) + circuit.args[i + 2:])
|
1255 |
+
sign = _S.NegativeOne**(first_exp*second_exp)
|
1256 |
+
circuit = sign*Mul(*new_args)
|
1257 |
+
changes = True
|
1258 |
+
break
|
1259 |
+
return circuit
|
1260 |
+
|
1261 |
+
|
1262 |
+
#-----------------------------------------------------------------------------
|
1263 |
+
# Utility functions
|
1264 |
+
#-----------------------------------------------------------------------------
|
1265 |
+
|
1266 |
+
|
1267 |
+
def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
|
1268 |
+
"""Return a random circuit of ngates and nqubits.
|
1269 |
+
|
1270 |
+
This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
|
1271 |
+
gates.
|
1272 |
+
|
1273 |
+
Parameters
|
1274 |
+
----------
|
1275 |
+
ngates : int
|
1276 |
+
The number of gates in the circuit.
|
1277 |
+
nqubits : int
|
1278 |
+
The number of qubits in the circuit.
|
1279 |
+
gate_space : tuple
|
1280 |
+
A tuple of the gate classes that will be used in the circuit.
|
1281 |
+
Repeating gate classes multiple times in this tuple will increase
|
1282 |
+
the frequency they appear in the random circuit.
|
1283 |
+
"""
|
1284 |
+
qubit_space = range(nqubits)
|
1285 |
+
result = []
|
1286 |
+
for i in range(ngates):
|
1287 |
+
g = random.choice(gate_space)
|
1288 |
+
if g == CNotGate or g == SwapGate:
|
1289 |
+
qubits = random.sample(qubit_space, 2)
|
1290 |
+
g = g(*qubits)
|
1291 |
+
else:
|
1292 |
+
qubit = random.choice(qubit_space)
|
1293 |
+
g = g(qubit)
|
1294 |
+
result.append(g)
|
1295 |
+
return Mul(*result)
|
1296 |
+
|
1297 |
+
|
1298 |
+
def zx_basis_transform(self, format='sympy'):
|
1299 |
+
"""Transformation matrix from Z to X basis."""
|
1300 |
+
return matrix_cache.get_matrix('ZX', format)
|
1301 |
+
|
1302 |
+
|
1303 |
+
def zy_basis_transform(self, format='sympy'):
|
1304 |
+
"""Transformation matrix from Z to Y basis."""
|
1305 |
+
return matrix_cache.get_matrix('ZY', format)
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/grover.py
ADDED
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Grover's algorithm and helper functions.
|
2 |
+
|
3 |
+
Todo:
|
4 |
+
|
5 |
+
* W gate construction (or perhaps -W gate based on Mermin's book)
|
6 |
+
* Generalize the algorithm for an unknown function that returns 1 on multiple
|
7 |
+
qubit states, not just one.
|
8 |
+
* Implement _represent_ZGate in OracleGate
|
9 |
+
"""
|
10 |
+
|
11 |
+
from sympy.core.numbers import pi
|
12 |
+
from sympy.core.sympify import sympify
|
13 |
+
from sympy.core.basic import Atom
|
14 |
+
from sympy.functions.elementary.integers import floor
|
15 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
16 |
+
from sympy.matrices.dense import eye
|
17 |
+
from sympy.core.numbers import NegativeOne
|
18 |
+
from sympy.physics.quantum.qapply import qapply
|
19 |
+
from sympy.physics.quantum.qexpr import QuantumError
|
20 |
+
from sympy.physics.quantum.hilbert import ComplexSpace
|
21 |
+
from sympy.physics.quantum.operator import UnitaryOperator
|
22 |
+
from sympy.physics.quantum.gate import Gate
|
23 |
+
from sympy.physics.quantum.qubit import IntQubit
|
24 |
+
|
25 |
+
__all__ = [
|
26 |
+
'OracleGate',
|
27 |
+
'WGate',
|
28 |
+
'superposition_basis',
|
29 |
+
'grover_iteration',
|
30 |
+
'apply_grover'
|
31 |
+
]
|
32 |
+
|
33 |
+
|
34 |
+
def superposition_basis(nqubits):
|
35 |
+
"""Creates an equal superposition of the computational basis.
|
36 |
+
|
37 |
+
Parameters
|
38 |
+
==========
|
39 |
+
|
40 |
+
nqubits : int
|
41 |
+
The number of qubits.
|
42 |
+
|
43 |
+
Returns
|
44 |
+
=======
|
45 |
+
|
46 |
+
state : Qubit
|
47 |
+
An equal superposition of the computational basis with nqubits.
|
48 |
+
|
49 |
+
Examples
|
50 |
+
========
|
51 |
+
|
52 |
+
Create an equal superposition of 2 qubits::
|
53 |
+
|
54 |
+
>>> from sympy.physics.quantum.grover import superposition_basis
|
55 |
+
>>> superposition_basis(2)
|
56 |
+
|0>/2 + |1>/2 + |2>/2 + |3>/2
|
57 |
+
"""
|
58 |
+
|
59 |
+
amp = 1/sqrt(2**nqubits)
|
60 |
+
return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)])
|
61 |
+
|
62 |
+
class OracleGateFunction(Atom):
|
63 |
+
"""Wrapper for python functions used in `OracleGate`s"""
|
64 |
+
|
65 |
+
def __new__(cls, function):
|
66 |
+
if not callable(function):
|
67 |
+
raise TypeError('Callable expected, got: %r' % function)
|
68 |
+
obj = Atom.__new__(cls)
|
69 |
+
obj.function = function
|
70 |
+
return obj
|
71 |
+
|
72 |
+
def _hashable_content(self):
|
73 |
+
return type(self), self.function
|
74 |
+
|
75 |
+
def __call__(self, *args):
|
76 |
+
return self.function(*args)
|
77 |
+
|
78 |
+
|
79 |
+
class OracleGate(Gate):
|
80 |
+
"""A black box gate.
|
81 |
+
|
82 |
+
The gate marks the desired qubits of an unknown function by flipping
|
83 |
+
the sign of the qubits. The unknown function returns true when it
|
84 |
+
finds its desired qubits and false otherwise.
|
85 |
+
|
86 |
+
Parameters
|
87 |
+
==========
|
88 |
+
|
89 |
+
qubits : int
|
90 |
+
Number of qubits.
|
91 |
+
|
92 |
+
oracle : callable
|
93 |
+
A callable function that returns a boolean on a computational basis.
|
94 |
+
|
95 |
+
Examples
|
96 |
+
========
|
97 |
+
|
98 |
+
Apply an Oracle gate that flips the sign of ``|2>`` on different qubits::
|
99 |
+
|
100 |
+
>>> from sympy.physics.quantum.qubit import IntQubit
|
101 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
102 |
+
>>> from sympy.physics.quantum.grover import OracleGate
|
103 |
+
>>> f = lambda qubits: qubits == IntQubit(2)
|
104 |
+
>>> v = OracleGate(2, f)
|
105 |
+
>>> qapply(v*IntQubit(2))
|
106 |
+
-|2>
|
107 |
+
>>> qapply(v*IntQubit(3))
|
108 |
+
|3>
|
109 |
+
"""
|
110 |
+
|
111 |
+
gate_name = 'V'
|
112 |
+
gate_name_latex = 'V'
|
113 |
+
|
114 |
+
#-------------------------------------------------------------------------
|
115 |
+
# Initialization/creation
|
116 |
+
#-------------------------------------------------------------------------
|
117 |
+
|
118 |
+
@classmethod
|
119 |
+
def _eval_args(cls, args):
|
120 |
+
if len(args) != 2:
|
121 |
+
raise QuantumError(
|
122 |
+
'Insufficient/excessive arguments to Oracle. Please ' +
|
123 |
+
'supply the number of qubits and an unknown function.'
|
124 |
+
)
|
125 |
+
sub_args = (args[0],)
|
126 |
+
sub_args = UnitaryOperator._eval_args(sub_args)
|
127 |
+
if not sub_args[0].is_Integer:
|
128 |
+
raise TypeError('Integer expected, got: %r' % sub_args[0])
|
129 |
+
|
130 |
+
function = args[1]
|
131 |
+
if not isinstance(function, OracleGateFunction):
|
132 |
+
function = OracleGateFunction(function)
|
133 |
+
|
134 |
+
return (sub_args[0], function)
|
135 |
+
|
136 |
+
@classmethod
|
137 |
+
def _eval_hilbert_space(cls, args):
|
138 |
+
"""This returns the smallest possible Hilbert space."""
|
139 |
+
return ComplexSpace(2)**args[0]
|
140 |
+
|
141 |
+
#-------------------------------------------------------------------------
|
142 |
+
# Properties
|
143 |
+
#-------------------------------------------------------------------------
|
144 |
+
|
145 |
+
@property
|
146 |
+
def search_function(self):
|
147 |
+
"""The unknown function that helps find the sought after qubits."""
|
148 |
+
return self.label[1]
|
149 |
+
|
150 |
+
@property
|
151 |
+
def targets(self):
|
152 |
+
"""A tuple of target qubits."""
|
153 |
+
return sympify(tuple(range(self.args[0])))
|
154 |
+
|
155 |
+
#-------------------------------------------------------------------------
|
156 |
+
# Apply
|
157 |
+
#-------------------------------------------------------------------------
|
158 |
+
|
159 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
160 |
+
"""Apply this operator to a Qubit subclass.
|
161 |
+
|
162 |
+
Parameters
|
163 |
+
==========
|
164 |
+
|
165 |
+
qubits : Qubit
|
166 |
+
The qubit subclass to apply this operator to.
|
167 |
+
|
168 |
+
Returns
|
169 |
+
=======
|
170 |
+
|
171 |
+
state : Expr
|
172 |
+
The resulting quantum state.
|
173 |
+
"""
|
174 |
+
if qubits.nqubits != self.nqubits:
|
175 |
+
raise QuantumError(
|
176 |
+
'OracleGate operates on %r qubits, got: %r'
|
177 |
+
% (self.nqubits, qubits.nqubits)
|
178 |
+
)
|
179 |
+
# If function returns 1 on qubits
|
180 |
+
# return the negative of the qubits (flip the sign)
|
181 |
+
if self.search_function(qubits):
|
182 |
+
return -qubits
|
183 |
+
else:
|
184 |
+
return qubits
|
185 |
+
|
186 |
+
#-------------------------------------------------------------------------
|
187 |
+
# Represent
|
188 |
+
#-------------------------------------------------------------------------
|
189 |
+
|
190 |
+
def _represent_ZGate(self, basis, **options):
|
191 |
+
"""
|
192 |
+
Represent the OracleGate in the computational basis.
|
193 |
+
"""
|
194 |
+
nbasis = 2**self.nqubits # compute it only once
|
195 |
+
matrixOracle = eye(nbasis)
|
196 |
+
# Flip the sign given the output of the oracle function
|
197 |
+
for i in range(nbasis):
|
198 |
+
if self.search_function(IntQubit(i, nqubits=self.nqubits)):
|
199 |
+
matrixOracle[i, i] = NegativeOne()
|
200 |
+
return matrixOracle
|
201 |
+
|
202 |
+
|
203 |
+
class WGate(Gate):
|
204 |
+
"""General n qubit W Gate in Grover's algorithm.
|
205 |
+
|
206 |
+
The gate performs the operation ``2|phi><phi| - 1`` on some qubits.
|
207 |
+
``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)``
|
208 |
+
|
209 |
+
Parameters
|
210 |
+
==========
|
211 |
+
|
212 |
+
nqubits : int
|
213 |
+
The number of qubits to operate on
|
214 |
+
|
215 |
+
"""
|
216 |
+
|
217 |
+
gate_name = 'W'
|
218 |
+
gate_name_latex = 'W'
|
219 |
+
|
220 |
+
@classmethod
|
221 |
+
def _eval_args(cls, args):
|
222 |
+
if len(args) != 1:
|
223 |
+
raise QuantumError(
|
224 |
+
'Insufficient/excessive arguments to W gate. Please ' +
|
225 |
+
'supply the number of qubits to operate on.'
|
226 |
+
)
|
227 |
+
args = UnitaryOperator._eval_args(args)
|
228 |
+
if not args[0].is_Integer:
|
229 |
+
raise TypeError('Integer expected, got: %r' % args[0])
|
230 |
+
return args
|
231 |
+
|
232 |
+
#-------------------------------------------------------------------------
|
233 |
+
# Properties
|
234 |
+
#-------------------------------------------------------------------------
|
235 |
+
|
236 |
+
@property
|
237 |
+
def targets(self):
|
238 |
+
return sympify(tuple(reversed(range(self.args[0]))))
|
239 |
+
|
240 |
+
#-------------------------------------------------------------------------
|
241 |
+
# Apply
|
242 |
+
#-------------------------------------------------------------------------
|
243 |
+
|
244 |
+
def _apply_operator_Qubit(self, qubits, **options):
|
245 |
+
"""
|
246 |
+
qubits: a set of qubits (Qubit)
|
247 |
+
Returns: quantum object (quantum expression - QExpr)
|
248 |
+
"""
|
249 |
+
if qubits.nqubits != self.nqubits:
|
250 |
+
raise QuantumError(
|
251 |
+
'WGate operates on %r qubits, got: %r'
|
252 |
+
% (self.nqubits, qubits.nqubits)
|
253 |
+
)
|
254 |
+
|
255 |
+
# See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result
|
256 |
+
# Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis
|
257 |
+
# state and phi is the superposition of basis states (see function
|
258 |
+
# create_computational_basis above)
|
259 |
+
basis_states = superposition_basis(self.nqubits)
|
260 |
+
change_to_basis = (2/sqrt(2**self.nqubits))*basis_states
|
261 |
+
return change_to_basis - qubits
|
262 |
+
|
263 |
+
|
264 |
+
def grover_iteration(qstate, oracle):
|
265 |
+
"""Applies one application of the Oracle and W Gate, WV.
|
266 |
+
|
267 |
+
Parameters
|
268 |
+
==========
|
269 |
+
|
270 |
+
qstate : Qubit
|
271 |
+
A superposition of qubits.
|
272 |
+
oracle : OracleGate
|
273 |
+
The black box operator that flips the sign of the desired basis qubits.
|
274 |
+
|
275 |
+
Returns
|
276 |
+
=======
|
277 |
+
|
278 |
+
Qubit : The qubits after applying the Oracle and W gate.
|
279 |
+
|
280 |
+
Examples
|
281 |
+
========
|
282 |
+
|
283 |
+
Perform one iteration of grover's algorithm to see a phase change::
|
284 |
+
|
285 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
286 |
+
>>> from sympy.physics.quantum.qubit import IntQubit
|
287 |
+
>>> from sympy.physics.quantum.grover import OracleGate
|
288 |
+
>>> from sympy.physics.quantum.grover import superposition_basis
|
289 |
+
>>> from sympy.physics.quantum.grover import grover_iteration
|
290 |
+
>>> numqubits = 2
|
291 |
+
>>> basis_states = superposition_basis(numqubits)
|
292 |
+
>>> f = lambda qubits: qubits == IntQubit(2)
|
293 |
+
>>> v = OracleGate(numqubits, f)
|
294 |
+
>>> qapply(grover_iteration(basis_states, v))
|
295 |
+
|2>
|
296 |
+
|
297 |
+
"""
|
298 |
+
wgate = WGate(oracle.nqubits)
|
299 |
+
return wgate*oracle*qstate
|
300 |
+
|
301 |
+
|
302 |
+
def apply_grover(oracle, nqubits, iterations=None):
|
303 |
+
"""Applies grover's algorithm.
|
304 |
+
|
305 |
+
Parameters
|
306 |
+
==========
|
307 |
+
|
308 |
+
oracle : callable
|
309 |
+
The unknown callable function that returns true when applied to the
|
310 |
+
desired qubits and false otherwise.
|
311 |
+
|
312 |
+
Returns
|
313 |
+
=======
|
314 |
+
|
315 |
+
state : Expr
|
316 |
+
The resulting state after Grover's algorithm has been iterated.
|
317 |
+
|
318 |
+
Examples
|
319 |
+
========
|
320 |
+
|
321 |
+
Apply grover's algorithm to an even superposition of 2 qubits::
|
322 |
+
|
323 |
+
>>> from sympy.physics.quantum.qapply import qapply
|
324 |
+
>>> from sympy.physics.quantum.qubit import IntQubit
|
325 |
+
>>> from sympy.physics.quantum.grover import apply_grover
|
326 |
+
>>> f = lambda qubits: qubits == IntQubit(2)
|
327 |
+
>>> qapply(apply_grover(f, 2))
|
328 |
+
|2>
|
329 |
+
|
330 |
+
"""
|
331 |
+
if nqubits <= 0:
|
332 |
+
raise QuantumError(
|
333 |
+
'Grover\'s algorithm needs nqubits > 0, received %r qubits'
|
334 |
+
% nqubits
|
335 |
+
)
|
336 |
+
if iterations is None:
|
337 |
+
iterations = floor(sqrt(2**nqubits)*(pi/4))
|
338 |
+
|
339 |
+
v = OracleGate(nqubits, oracle)
|
340 |
+
iterated = superposition_basis(nqubits)
|
341 |
+
for iter in range(iterations):
|
342 |
+
iterated = grover_iteration(iterated, v)
|
343 |
+
iterated = qapply(iterated)
|
344 |
+
|
345 |
+
return iterated
|
env-llmeval/lib/python3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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Hilbert spaces for quantum mechanics.
|
2 |
+
|
3 |
+
Authors:
|
4 |
+
* Brian Granger
|
5 |
+
* Matt Curry
|
6 |
+
"""
|
7 |
+
|
8 |
+
from functools import reduce
|
9 |
+
|
10 |
+
from sympy.core.basic import Basic
|
11 |
+
from sympy.core.singleton import S
|
12 |
+
from sympy.core.sympify import sympify
|
13 |
+
from sympy.sets.sets import Interval
|
14 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
15 |
+
from sympy.physics.quantum.qexpr import QuantumError
|
16 |
+
|
17 |
+
|
18 |
+
__all__ = [
|
19 |
+
'HilbertSpaceError',
|
20 |
+
'HilbertSpace',
|
21 |
+
'TensorProductHilbertSpace',
|
22 |
+
'TensorPowerHilbertSpace',
|
23 |
+
'DirectSumHilbertSpace',
|
24 |
+
'ComplexSpace',
|
25 |
+
'L2',
|
26 |
+
'FockSpace'
|
27 |
+
]
|
28 |
+
|
29 |
+
#-----------------------------------------------------------------------------
|
30 |
+
# Main objects
|
31 |
+
#-----------------------------------------------------------------------------
|
32 |
+
|
33 |
+
|
34 |
+
class HilbertSpaceError(QuantumError):
|
35 |
+
pass
|
36 |
+
|
37 |
+
#-----------------------------------------------------------------------------
|
38 |
+
# Main objects
|
39 |
+
#-----------------------------------------------------------------------------
|
40 |
+
|
41 |
+
|
42 |
+
class HilbertSpace(Basic):
|
43 |
+
"""An abstract Hilbert space for quantum mechanics.
|
44 |
+
|
45 |
+
In short, a Hilbert space is an abstract vector space that is complete
|
46 |
+
with inner products defined [1]_.
|
47 |
+
|
48 |
+
Examples
|
49 |
+
========
|
50 |
+
|
51 |
+
>>> from sympy.physics.quantum.hilbert import HilbertSpace
|
52 |
+
>>> hs = HilbertSpace()
|
53 |
+
>>> hs
|
54 |
+
H
|
55 |
+
|
56 |
+
References
|
57 |
+
==========
|
58 |
+
|
59 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space
|
60 |
+
"""
|
61 |
+
|
62 |
+
def __new__(cls):
|
63 |
+
obj = Basic.__new__(cls)
|
64 |
+
return obj
|
65 |
+
|
66 |
+
@property
|
67 |
+
def dimension(self):
|
68 |
+
"""Return the Hilbert dimension of the space."""
|
69 |
+
raise NotImplementedError('This Hilbert space has no dimension.')
|
70 |
+
|
71 |
+
def __add__(self, other):
|
72 |
+
return DirectSumHilbertSpace(self, other)
|
73 |
+
|
74 |
+
def __radd__(self, other):
|
75 |
+
return DirectSumHilbertSpace(other, self)
|
76 |
+
|
77 |
+
def __mul__(self, other):
|
78 |
+
return TensorProductHilbertSpace(self, other)
|
79 |
+
|
80 |
+
def __rmul__(self, other):
|
81 |
+
return TensorProductHilbertSpace(other, self)
|
82 |
+
|
83 |
+
def __pow__(self, other, mod=None):
|
84 |
+
if mod is not None:
|
85 |
+
raise ValueError('The third argument to __pow__ is not supported \
|
86 |
+
for Hilbert spaces.')
|
87 |
+
return TensorPowerHilbertSpace(self, other)
|
88 |
+
|
89 |
+
def __contains__(self, other):
|
90 |
+
"""Is the operator or state in this Hilbert space.
|
91 |
+
|
92 |
+
This is checked by comparing the classes of the Hilbert spaces, not
|
93 |
+
the instances. This is to allow Hilbert Spaces with symbolic
|
94 |
+
dimensions.
|
95 |
+
"""
|
96 |
+
if other.hilbert_space.__class__ == self.__class__:
|
97 |
+
return True
|
98 |
+
else:
|
99 |
+
return False
|
100 |
+
|
101 |
+
def _sympystr(self, printer, *args):
|
102 |
+
return 'H'
|
103 |
+
|
104 |
+
def _pretty(self, printer, *args):
|
105 |
+
ustr = '\N{LATIN CAPITAL LETTER H}'
|
106 |
+
return prettyForm(ustr)
|
107 |
+
|
108 |
+
def _latex(self, printer, *args):
|
109 |
+
return r'\mathcal{H}'
|
110 |
+
|
111 |
+
|
112 |
+
class ComplexSpace(HilbertSpace):
|
113 |
+
"""Finite dimensional Hilbert space of complex vectors.
|
114 |
+
|
115 |
+
The elements of this Hilbert space are n-dimensional complex valued
|
116 |
+
vectors with the usual inner product that takes the complex conjugate
|
117 |
+
of the vector on the right.
|
118 |
+
|
119 |
+
A classic example of this type of Hilbert space is spin-1/2, which is
|
120 |
+
``ComplexSpace(2)``. Generalizing to spin-s, the space is
|
121 |
+
``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the
|
122 |
+
direct product space ``ComplexSpace(2)**N``.
|
123 |
+
|
124 |
+
Examples
|
125 |
+
========
|
126 |
+
|
127 |
+
>>> from sympy import symbols
|
128 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace
|
129 |
+
>>> c1 = ComplexSpace(2)
|
130 |
+
>>> c1
|
131 |
+
C(2)
|
132 |
+
>>> c1.dimension
|
133 |
+
2
|
134 |
+
|
135 |
+
>>> n = symbols('n')
|
136 |
+
>>> c2 = ComplexSpace(n)
|
137 |
+
>>> c2
|
138 |
+
C(n)
|
139 |
+
>>> c2.dimension
|
140 |
+
n
|
141 |
+
|
142 |
+
"""
|
143 |
+
|
144 |
+
def __new__(cls, dimension):
|
145 |
+
dimension = sympify(dimension)
|
146 |
+
r = cls.eval(dimension)
|
147 |
+
if isinstance(r, Basic):
|
148 |
+
return r
|
149 |
+
obj = Basic.__new__(cls, dimension)
|
150 |
+
return obj
|
151 |
+
|
152 |
+
@classmethod
|
153 |
+
def eval(cls, dimension):
|
154 |
+
if len(dimension.atoms()) == 1:
|
155 |
+
if not (dimension.is_Integer and dimension > 0 or dimension is S.Infinity
|
156 |
+
or dimension.is_Symbol):
|
157 |
+
raise TypeError('The dimension of a ComplexSpace can only'
|
158 |
+
'be a positive integer, oo, or a Symbol: %r'
|
159 |
+
% dimension)
|
160 |
+
else:
|
161 |
+
for dim in dimension.atoms():
|
162 |
+
if not (dim.is_Integer or dim is S.Infinity or dim.is_Symbol):
|
163 |
+
raise TypeError('The dimension of a ComplexSpace can only'
|
164 |
+
' contain integers, oo, or a Symbol: %r'
|
165 |
+
% dim)
|
166 |
+
|
167 |
+
@property
|
168 |
+
def dimension(self):
|
169 |
+
return self.args[0]
|
170 |
+
|
171 |
+
def _sympyrepr(self, printer, *args):
|
172 |
+
return "%s(%s)" % (self.__class__.__name__,
|
173 |
+
printer._print(self.dimension, *args))
|
174 |
+
|
175 |
+
def _sympystr(self, printer, *args):
|
176 |
+
return "C(%s)" % printer._print(self.dimension, *args)
|
177 |
+
|
178 |
+
def _pretty(self, printer, *args):
|
179 |
+
ustr = '\N{LATIN CAPITAL LETTER C}'
|
180 |
+
pform_exp = printer._print(self.dimension, *args)
|
181 |
+
pform_base = prettyForm(ustr)
|
182 |
+
return pform_base**pform_exp
|
183 |
+
|
184 |
+
def _latex(self, printer, *args):
|
185 |
+
return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
|
186 |
+
|
187 |
+
|
188 |
+
class L2(HilbertSpace):
|
189 |
+
"""The Hilbert space of square integrable functions on an interval.
|
190 |
+
|
191 |
+
An L2 object takes in a single SymPy Interval argument which represents
|
192 |
+
the interval its functions (vectors) are defined on.
|
193 |
+
|
194 |
+
Examples
|
195 |
+
========
|
196 |
+
|
197 |
+
>>> from sympy import Interval, oo
|
198 |
+
>>> from sympy.physics.quantum.hilbert import L2
|
199 |
+
>>> hs = L2(Interval(0,oo))
|
200 |
+
>>> hs
|
201 |
+
L2(Interval(0, oo))
|
202 |
+
>>> hs.dimension
|
203 |
+
oo
|
204 |
+
>>> hs.interval
|
205 |
+
Interval(0, oo)
|
206 |
+
|
207 |
+
"""
|
208 |
+
|
209 |
+
def __new__(cls, interval):
|
210 |
+
if not isinstance(interval, Interval):
|
211 |
+
raise TypeError('L2 interval must be an Interval instance: %r'
|
212 |
+
% interval)
|
213 |
+
obj = Basic.__new__(cls, interval)
|
214 |
+
return obj
|
215 |
+
|
216 |
+
@property
|
217 |
+
def dimension(self):
|
218 |
+
return S.Infinity
|
219 |
+
|
220 |
+
@property
|
221 |
+
def interval(self):
|
222 |
+
return self.args[0]
|
223 |
+
|
224 |
+
def _sympyrepr(self, printer, *args):
|
225 |
+
return "L2(%s)" % printer._print(self.interval, *args)
|
226 |
+
|
227 |
+
def _sympystr(self, printer, *args):
|
228 |
+
return "L2(%s)" % printer._print(self.interval, *args)
|
229 |
+
|
230 |
+
def _pretty(self, printer, *args):
|
231 |
+
pform_exp = prettyForm('2')
|
232 |
+
pform_base = prettyForm('L')
|
233 |
+
return pform_base**pform_exp
|
234 |
+
|
235 |
+
def _latex(self, printer, *args):
|
236 |
+
interval = printer._print(self.interval, *args)
|
237 |
+
return r'{\mathcal{L}^2}\left( %s \right)' % interval
|
238 |
+
|
239 |
+
|
240 |
+
class FockSpace(HilbertSpace):
|
241 |
+
"""The Hilbert space for second quantization.
|
242 |
+
|
243 |
+
Technically, this Hilbert space is a infinite direct sum of direct
|
244 |
+
products of single particle Hilbert spaces [1]_. This is a mess, so we have
|
245 |
+
a class to represent it directly.
|
246 |
+
|
247 |
+
Examples
|
248 |
+
========
|
249 |
+
|
250 |
+
>>> from sympy.physics.quantum.hilbert import FockSpace
|
251 |
+
>>> hs = FockSpace()
|
252 |
+
>>> hs
|
253 |
+
F
|
254 |
+
>>> hs.dimension
|
255 |
+
oo
|
256 |
+
|
257 |
+
References
|
258 |
+
==========
|
259 |
+
|
260 |
+
.. [1] https://en.wikipedia.org/wiki/Fock_space
|
261 |
+
"""
|
262 |
+
|
263 |
+
def __new__(cls):
|
264 |
+
obj = Basic.__new__(cls)
|
265 |
+
return obj
|
266 |
+
|
267 |
+
@property
|
268 |
+
def dimension(self):
|
269 |
+
return S.Infinity
|
270 |
+
|
271 |
+
def _sympyrepr(self, printer, *args):
|
272 |
+
return "FockSpace()"
|
273 |
+
|
274 |
+
def _sympystr(self, printer, *args):
|
275 |
+
return "F"
|
276 |
+
|
277 |
+
def _pretty(self, printer, *args):
|
278 |
+
ustr = '\N{LATIN CAPITAL LETTER F}'
|
279 |
+
return prettyForm(ustr)
|
280 |
+
|
281 |
+
def _latex(self, printer, *args):
|
282 |
+
return r'\mathcal{F}'
|
283 |
+
|
284 |
+
|
285 |
+
class TensorProductHilbertSpace(HilbertSpace):
|
286 |
+
"""A tensor product of Hilbert spaces [1]_.
|
287 |
+
|
288 |
+
The tensor product between Hilbert spaces is represented by the
|
289 |
+
operator ``*`` Products of the same Hilbert space will be combined into
|
290 |
+
tensor powers.
|
291 |
+
|
292 |
+
A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
|
293 |
+
``HilbertSpace`` objects as its arguments. In addition, multiplication of
|
294 |
+
``HilbertSpace`` objects will automatically return this tensor product
|
295 |
+
object.
|
296 |
+
|
297 |
+
Examples
|
298 |
+
========
|
299 |
+
|
300 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
|
301 |
+
>>> from sympy import symbols
|
302 |
+
|
303 |
+
>>> c = ComplexSpace(2)
|
304 |
+
>>> f = FockSpace()
|
305 |
+
>>> hs = c*f
|
306 |
+
>>> hs
|
307 |
+
C(2)*F
|
308 |
+
>>> hs.dimension
|
309 |
+
oo
|
310 |
+
>>> hs.spaces
|
311 |
+
(C(2), F)
|
312 |
+
|
313 |
+
>>> c1 = ComplexSpace(2)
|
314 |
+
>>> n = symbols('n')
|
315 |
+
>>> c2 = ComplexSpace(n)
|
316 |
+
>>> hs = c1*c2
|
317 |
+
>>> hs
|
318 |
+
C(2)*C(n)
|
319 |
+
>>> hs.dimension
|
320 |
+
2*n
|
321 |
+
|
322 |
+
References
|
323 |
+
==========
|
324 |
+
|
325 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
|
326 |
+
"""
|
327 |
+
|
328 |
+
def __new__(cls, *args):
|
329 |
+
r = cls.eval(args)
|
330 |
+
if isinstance(r, Basic):
|
331 |
+
return r
|
332 |
+
obj = Basic.__new__(cls, *args)
|
333 |
+
return obj
|
334 |
+
|
335 |
+
@classmethod
|
336 |
+
def eval(cls, args):
|
337 |
+
"""Evaluates the direct product."""
|
338 |
+
new_args = []
|
339 |
+
recall = False
|
340 |
+
#flatten arguments
|
341 |
+
for arg in args:
|
342 |
+
if isinstance(arg, TensorProductHilbertSpace):
|
343 |
+
new_args.extend(arg.args)
|
344 |
+
recall = True
|
345 |
+
elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
|
346 |
+
new_args.append(arg)
|
347 |
+
else:
|
348 |
+
raise TypeError('Hilbert spaces can only be multiplied by \
|
349 |
+
other Hilbert spaces: %r' % arg)
|
350 |
+
#combine like arguments into direct powers
|
351 |
+
comb_args = []
|
352 |
+
prev_arg = None
|
353 |
+
for new_arg in new_args:
|
354 |
+
if prev_arg is not None:
|
355 |
+
if isinstance(new_arg, TensorPowerHilbertSpace) and \
|
356 |
+
isinstance(prev_arg, TensorPowerHilbertSpace) and \
|
357 |
+
new_arg.base == prev_arg.base:
|
358 |
+
prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
|
359 |
+
elif isinstance(new_arg, TensorPowerHilbertSpace) and \
|
360 |
+
new_arg.base == prev_arg:
|
361 |
+
prev_arg = prev_arg**(new_arg.exp + 1)
|
362 |
+
elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
|
363 |
+
new_arg == prev_arg.base:
|
364 |
+
prev_arg = new_arg**(prev_arg.exp + 1)
|
365 |
+
elif new_arg == prev_arg:
|
366 |
+
prev_arg = new_arg**2
|
367 |
+
else:
|
368 |
+
comb_args.append(prev_arg)
|
369 |
+
prev_arg = new_arg
|
370 |
+
elif prev_arg is None:
|
371 |
+
prev_arg = new_arg
|
372 |
+
comb_args.append(prev_arg)
|
373 |
+
if recall:
|
374 |
+
return TensorProductHilbertSpace(*comb_args)
|
375 |
+
elif len(comb_args) == 1:
|
376 |
+
return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
|
377 |
+
else:
|
378 |
+
return None
|
379 |
+
|
380 |
+
@property
|
381 |
+
def dimension(self):
|
382 |
+
arg_list = [arg.dimension for arg in self.args]
|
383 |
+
if S.Infinity in arg_list:
|
384 |
+
return S.Infinity
|
385 |
+
else:
|
386 |
+
return reduce(lambda x, y: x*y, arg_list)
|
387 |
+
|
388 |
+
@property
|
389 |
+
def spaces(self):
|
390 |
+
"""A tuple of the Hilbert spaces in this tensor product."""
|
391 |
+
return self.args
|
392 |
+
|
393 |
+
def _spaces_printer(self, printer, *args):
|
394 |
+
spaces_strs = []
|
395 |
+
for arg in self.args:
|
396 |
+
s = printer._print(arg, *args)
|
397 |
+
if isinstance(arg, DirectSumHilbertSpace):
|
398 |
+
s = '(%s)' % s
|
399 |
+
spaces_strs.append(s)
|
400 |
+
return spaces_strs
|
401 |
+
|
402 |
+
def _sympyrepr(self, printer, *args):
|
403 |
+
spaces_reprs = self._spaces_printer(printer, *args)
|
404 |
+
return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
|
405 |
+
|
406 |
+
def _sympystr(self, printer, *args):
|
407 |
+
spaces_strs = self._spaces_printer(printer, *args)
|
408 |
+
return '*'.join(spaces_strs)
|
409 |
+
|
410 |
+
def _pretty(self, printer, *args):
|
411 |
+
length = len(self.args)
|
412 |
+
pform = printer._print('', *args)
|
413 |
+
for i in range(length):
|
414 |
+
next_pform = printer._print(self.args[i], *args)
|
415 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
416 |
+
TensorProductHilbertSpace)):
|
417 |
+
next_pform = prettyForm(
|
418 |
+
*next_pform.parens(left='(', right=')')
|
419 |
+
)
|
420 |
+
pform = prettyForm(*pform.right(next_pform))
|
421 |
+
if i != length - 1:
|
422 |
+
if printer._use_unicode:
|
423 |
+
pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
|
424 |
+
else:
|
425 |
+
pform = prettyForm(*pform.right(' x '))
|
426 |
+
return pform
|
427 |
+
|
428 |
+
def _latex(self, printer, *args):
|
429 |
+
length = len(self.args)
|
430 |
+
s = ''
|
431 |
+
for i in range(length):
|
432 |
+
arg_s = printer._print(self.args[i], *args)
|
433 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
434 |
+
TensorProductHilbertSpace)):
|
435 |
+
arg_s = r'\left(%s\right)' % arg_s
|
436 |
+
s = s + arg_s
|
437 |
+
if i != length - 1:
|
438 |
+
s = s + r'\otimes '
|
439 |
+
return s
|
440 |
+
|
441 |
+
|
442 |
+
class DirectSumHilbertSpace(HilbertSpace):
|
443 |
+
"""A direct sum of Hilbert spaces [1]_.
|
444 |
+
|
445 |
+
This class uses the ``+`` operator to represent direct sums between
|
446 |
+
different Hilbert spaces.
|
447 |
+
|
448 |
+
A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
|
449 |
+
``HilbertSpace`` objects as its arguments. Also, addition of
|
450 |
+
``HilbertSpace`` objects will automatically return a direct sum object.
|
451 |
+
|
452 |
+
Examples
|
453 |
+
========
|
454 |
+
|
455 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
|
456 |
+
|
457 |
+
>>> c = ComplexSpace(2)
|
458 |
+
>>> f = FockSpace()
|
459 |
+
>>> hs = c+f
|
460 |
+
>>> hs
|
461 |
+
C(2)+F
|
462 |
+
>>> hs.dimension
|
463 |
+
oo
|
464 |
+
>>> list(hs.spaces)
|
465 |
+
[C(2), F]
|
466 |
+
|
467 |
+
References
|
468 |
+
==========
|
469 |
+
|
470 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
|
471 |
+
"""
|
472 |
+
def __new__(cls, *args):
|
473 |
+
r = cls.eval(args)
|
474 |
+
if isinstance(r, Basic):
|
475 |
+
return r
|
476 |
+
obj = Basic.__new__(cls, *args)
|
477 |
+
return obj
|
478 |
+
|
479 |
+
@classmethod
|
480 |
+
def eval(cls, args):
|
481 |
+
"""Evaluates the direct product."""
|
482 |
+
new_args = []
|
483 |
+
recall = False
|
484 |
+
#flatten arguments
|
485 |
+
for arg in args:
|
486 |
+
if isinstance(arg, DirectSumHilbertSpace):
|
487 |
+
new_args.extend(arg.args)
|
488 |
+
recall = True
|
489 |
+
elif isinstance(arg, HilbertSpace):
|
490 |
+
new_args.append(arg)
|
491 |
+
else:
|
492 |
+
raise TypeError('Hilbert spaces can only be summed with other \
|
493 |
+
Hilbert spaces: %r' % arg)
|
494 |
+
if recall:
|
495 |
+
return DirectSumHilbertSpace(*new_args)
|
496 |
+
else:
|
497 |
+
return None
|
498 |
+
|
499 |
+
@property
|
500 |
+
def dimension(self):
|
501 |
+
arg_list = [arg.dimension for arg in self.args]
|
502 |
+
if S.Infinity in arg_list:
|
503 |
+
return S.Infinity
|
504 |
+
else:
|
505 |
+
return reduce(lambda x, y: x + y, arg_list)
|
506 |
+
|
507 |
+
@property
|
508 |
+
def spaces(self):
|
509 |
+
"""A tuple of the Hilbert spaces in this direct sum."""
|
510 |
+
return self.args
|
511 |
+
|
512 |
+
def _sympyrepr(self, printer, *args):
|
513 |
+
spaces_reprs = [printer._print(arg, *args) for arg in self.args]
|
514 |
+
return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
|
515 |
+
|
516 |
+
def _sympystr(self, printer, *args):
|
517 |
+
spaces_strs = [printer._print(arg, *args) for arg in self.args]
|
518 |
+
return '+'.join(spaces_strs)
|
519 |
+
|
520 |
+
def _pretty(self, printer, *args):
|
521 |
+
length = len(self.args)
|
522 |
+
pform = printer._print('', *args)
|
523 |
+
for i in range(length):
|
524 |
+
next_pform = printer._print(self.args[i], *args)
|
525 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
526 |
+
TensorProductHilbertSpace)):
|
527 |
+
next_pform = prettyForm(
|
528 |
+
*next_pform.parens(left='(', right=')')
|
529 |
+
)
|
530 |
+
pform = prettyForm(*pform.right(next_pform))
|
531 |
+
if i != length - 1:
|
532 |
+
if printer._use_unicode:
|
533 |
+
pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
|
534 |
+
else:
|
535 |
+
pform = prettyForm(*pform.right(' + '))
|
536 |
+
return pform
|
537 |
+
|
538 |
+
def _latex(self, printer, *args):
|
539 |
+
length = len(self.args)
|
540 |
+
s = ''
|
541 |
+
for i in range(length):
|
542 |
+
arg_s = printer._print(self.args[i], *args)
|
543 |
+
if isinstance(self.args[i], (DirectSumHilbertSpace,
|
544 |
+
TensorProductHilbertSpace)):
|
545 |
+
arg_s = r'\left(%s\right)' % arg_s
|
546 |
+
s = s + arg_s
|
547 |
+
if i != length - 1:
|
548 |
+
s = s + r'\oplus '
|
549 |
+
return s
|
550 |
+
|
551 |
+
|
552 |
+
class TensorPowerHilbertSpace(HilbertSpace):
|
553 |
+
"""An exponentiated Hilbert space [1]_.
|
554 |
+
|
555 |
+
Tensor powers (repeated tensor products) are represented by the
|
556 |
+
operator ``**`` Identical Hilbert spaces that are multiplied together
|
557 |
+
will be automatically combined into a single tensor power object.
|
558 |
+
|
559 |
+
Any Hilbert space, product, or sum may be raised to a tensor power. The
|
560 |
+
``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
|
561 |
+
tensor power (number).
|
562 |
+
|
563 |
+
Examples
|
564 |
+
========
|
565 |
+
|
566 |
+
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
|
567 |
+
>>> from sympy import symbols
|
568 |
+
|
569 |
+
>>> n = symbols('n')
|
570 |
+
>>> c = ComplexSpace(2)
|
571 |
+
>>> hs = c**n
|
572 |
+
>>> hs
|
573 |
+
C(2)**n
|
574 |
+
>>> hs.dimension
|
575 |
+
2**n
|
576 |
+
|
577 |
+
>>> c = ComplexSpace(2)
|
578 |
+
>>> c*c
|
579 |
+
C(2)**2
|
580 |
+
>>> f = FockSpace()
|
581 |
+
>>> c*f*f
|
582 |
+
C(2)*F**2
|
583 |
+
|
584 |
+
References
|
585 |
+
==========
|
586 |
+
|
587 |
+
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
|
588 |
+
"""
|
589 |
+
|
590 |
+
def __new__(cls, *args):
|
591 |
+
r = cls.eval(args)
|
592 |
+
if isinstance(r, Basic):
|
593 |
+
return r
|
594 |
+
return Basic.__new__(cls, *r)
|
595 |
+
|
596 |
+
@classmethod
|
597 |
+
def eval(cls, args):
|
598 |
+
new_args = args[0], sympify(args[1])
|
599 |
+
exp = new_args[1]
|
600 |
+
#simplify hs**1 -> hs
|
601 |
+
if exp is S.One:
|
602 |
+
return args[0]
|
603 |
+
#simplify hs**0 -> 1
|
604 |
+
if exp is S.Zero:
|
605 |
+
return S.One
|
606 |
+
#check (and allow) for hs**(x+42+y...) case
|
607 |
+
if len(exp.atoms()) == 1:
|
608 |
+
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
|
609 |
+
raise ValueError('Hilbert spaces can only be raised to \
|
610 |
+
positive integers or Symbols: %r' % exp)
|
611 |
+
else:
|
612 |
+
for power in exp.atoms():
|
613 |
+
if not (power.is_Integer or power.is_Symbol):
|
614 |
+
raise ValueError('Tensor powers can only contain integers \
|
615 |
+
or Symbols: %r' % power)
|
616 |
+
return new_args
|
617 |
+
|
618 |
+
@property
|
619 |
+
def base(self):
|
620 |
+
return self.args[0]
|
621 |
+
|
622 |
+
@property
|
623 |
+
def exp(self):
|
624 |
+
return self.args[1]
|
625 |
+
|
626 |
+
@property
|
627 |
+
def dimension(self):
|
628 |
+
if self.base.dimension is S.Infinity:
|
629 |
+
return S.Infinity
|
630 |
+
else:
|
631 |
+
return self.base.dimension**self.exp
|
632 |
+
|
633 |
+
def _sympyrepr(self, printer, *args):
|
634 |
+
return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
|
635 |
+
*args), printer._print(self.exp, *args))
|
636 |
+
|
637 |
+
def _sympystr(self, printer, *args):
|
638 |
+
return "%s**%s" % (printer._print(self.base, *args),
|
639 |
+
printer._print(self.exp, *args))
|
640 |
+
|
641 |
+
def _pretty(self, printer, *args):
|
642 |
+
pform_exp = printer._print(self.exp, *args)
|
643 |
+
if printer._use_unicode:
|
644 |
+
pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
|
645 |
+
else:
|
646 |
+
pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
|
647 |
+
pform_base = printer._print(self.base, *args)
|
648 |
+
return pform_base**pform_exp
|
649 |
+
|
650 |
+
def _latex(self, printer, *args):
|
651 |
+
base = printer._print(self.base, *args)
|
652 |
+
exp = printer._print(self.exp, *args)
|
653 |
+
return r'{%s}^{\otimes %s}' % (base, exp)
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py
ADDED
@@ -0,0 +1,853 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import deque
|
2 |
+
from sympy.core.random import randint
|
3 |
+
|
4 |
+
from sympy.external import import_module
|
5 |
+
from sympy.core.basic import Basic
|
6 |
+
from sympy.core.mul import Mul
|
7 |
+
from sympy.core.numbers import Number, equal_valued
|
8 |
+
from sympy.core.power import Pow
|
9 |
+
from sympy.core.singleton import S
|
10 |
+
from sympy.physics.quantum.represent import represent
|
11 |
+
from sympy.physics.quantum.dagger import Dagger
|
12 |
+
|
13 |
+
__all__ = [
|
14 |
+
# Public interfaces
|
15 |
+
'generate_gate_rules',
|
16 |
+
'generate_equivalent_ids',
|
17 |
+
'GateIdentity',
|
18 |
+
'bfs_identity_search',
|
19 |
+
'random_identity_search',
|
20 |
+
|
21 |
+
# "Private" functions
|
22 |
+
'is_scalar_sparse_matrix',
|
23 |
+
'is_scalar_nonsparse_matrix',
|
24 |
+
'is_degenerate',
|
25 |
+
'is_reducible',
|
26 |
+
]
|
27 |
+
|
28 |
+
np = import_module('numpy')
|
29 |
+
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
|
30 |
+
|
31 |
+
|
32 |
+
def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
|
33 |
+
"""Checks if a given scipy.sparse matrix is a scalar matrix.
|
34 |
+
|
35 |
+
A scalar matrix is such that B = bI, where B is the scalar
|
36 |
+
matrix, b is some scalar multiple, and I is the identity
|
37 |
+
matrix. A scalar matrix would have only the element b along
|
38 |
+
it's main diagonal and zeroes elsewhere.
|
39 |
+
|
40 |
+
Parameters
|
41 |
+
==========
|
42 |
+
|
43 |
+
circuit : Gate tuple
|
44 |
+
Sequence of quantum gates representing a quantum circuit
|
45 |
+
nqubits : int
|
46 |
+
Number of qubits in the circuit
|
47 |
+
identity_only : bool
|
48 |
+
Check for only identity matrices
|
49 |
+
eps : number
|
50 |
+
The tolerance value for zeroing out elements in the matrix.
|
51 |
+
Values in the range [-eps, +eps] will be changed to a zero.
|
52 |
+
"""
|
53 |
+
|
54 |
+
if not np or not scipy:
|
55 |
+
pass
|
56 |
+
|
57 |
+
matrix = represent(Mul(*circuit), nqubits=nqubits,
|
58 |
+
format='scipy.sparse')
|
59 |
+
|
60 |
+
# In some cases, represent returns a 1D scalar value in place
|
61 |
+
# of a multi-dimensional scalar matrix
|
62 |
+
if (isinstance(matrix, int)):
|
63 |
+
return matrix == 1 if identity_only else True
|
64 |
+
|
65 |
+
# If represent returns a matrix, check if the matrix is diagonal
|
66 |
+
# and if every item along the diagonal is the same
|
67 |
+
else:
|
68 |
+
# Due to floating pointing operations, must zero out
|
69 |
+
# elements that are "very" small in the dense matrix
|
70 |
+
# See parameter for default value.
|
71 |
+
|
72 |
+
# Get the ndarray version of the dense matrix
|
73 |
+
dense_matrix = matrix.todense().getA()
|
74 |
+
# Since complex values can't be compared, must split
|
75 |
+
# the matrix into real and imaginary components
|
76 |
+
# Find the real values in between -eps and eps
|
77 |
+
bool_real = np.logical_and(dense_matrix.real > -eps,
|
78 |
+
dense_matrix.real < eps)
|
79 |
+
# Find the imaginary values between -eps and eps
|
80 |
+
bool_imag = np.logical_and(dense_matrix.imag > -eps,
|
81 |
+
dense_matrix.imag < eps)
|
82 |
+
# Replaces values between -eps and eps with 0
|
83 |
+
corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
|
84 |
+
corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
|
85 |
+
# Convert the matrix with real values into imaginary values
|
86 |
+
corrected_imag = corrected_imag * complex(1j)
|
87 |
+
# Recombine the real and imaginary components
|
88 |
+
corrected_dense = corrected_real + corrected_imag
|
89 |
+
|
90 |
+
# Check if it's diagonal
|
91 |
+
row_indices = corrected_dense.nonzero()[0]
|
92 |
+
col_indices = corrected_dense.nonzero()[1]
|
93 |
+
# Check if the rows indices and columns indices are the same
|
94 |
+
# If they match, then matrix only contains elements along diagonal
|
95 |
+
bool_indices = row_indices == col_indices
|
96 |
+
is_diagonal = bool_indices.all()
|
97 |
+
|
98 |
+
first_element = corrected_dense[0][0]
|
99 |
+
# If the first element is a zero, then can't rescale matrix
|
100 |
+
# and definitely not diagonal
|
101 |
+
if (first_element == 0.0 + 0.0j):
|
102 |
+
return False
|
103 |
+
|
104 |
+
# The dimensions of the dense matrix should still
|
105 |
+
# be 2^nqubits if there are elements all along the
|
106 |
+
# the main diagonal
|
107 |
+
trace_of_corrected = (corrected_dense/first_element).trace()
|
108 |
+
expected_trace = pow(2, nqubits)
|
109 |
+
has_correct_trace = trace_of_corrected == expected_trace
|
110 |
+
|
111 |
+
# If only looking for identity matrices
|
112 |
+
# first element must be a 1
|
113 |
+
real_is_one = abs(first_element.real - 1.0) < eps
|
114 |
+
imag_is_zero = abs(first_element.imag) < eps
|
115 |
+
is_one = real_is_one and imag_is_zero
|
116 |
+
is_identity = is_one if identity_only else True
|
117 |
+
return bool(is_diagonal and has_correct_trace and is_identity)
|
118 |
+
|
119 |
+
|
120 |
+
def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
|
121 |
+
"""Checks if a given circuit, in matrix form, is equivalent to
|
122 |
+
a scalar value.
|
123 |
+
|
124 |
+
Parameters
|
125 |
+
==========
|
126 |
+
|
127 |
+
circuit : Gate tuple
|
128 |
+
Sequence of quantum gates representing a quantum circuit
|
129 |
+
nqubits : int
|
130 |
+
Number of qubits in the circuit
|
131 |
+
identity_only : bool
|
132 |
+
Check for only identity matrices
|
133 |
+
eps : number
|
134 |
+
This argument is ignored. It is just for signature compatibility with
|
135 |
+
is_scalar_sparse_matrix.
|
136 |
+
|
137 |
+
Note: Used in situations when is_scalar_sparse_matrix has bugs
|
138 |
+
"""
|
139 |
+
|
140 |
+
matrix = represent(Mul(*circuit), nqubits=nqubits)
|
141 |
+
|
142 |
+
# In some cases, represent returns a 1D scalar value in place
|
143 |
+
# of a multi-dimensional scalar matrix
|
144 |
+
if (isinstance(matrix, Number)):
|
145 |
+
return matrix == 1 if identity_only else True
|
146 |
+
|
147 |
+
# If represent returns a matrix, check if the matrix is diagonal
|
148 |
+
# and if every item along the diagonal is the same
|
149 |
+
else:
|
150 |
+
# Added up the diagonal elements
|
151 |
+
matrix_trace = matrix.trace()
|
152 |
+
# Divide the trace by the first element in the matrix
|
153 |
+
# if matrix is not required to be the identity matrix
|
154 |
+
adjusted_matrix_trace = (matrix_trace/matrix[0]
|
155 |
+
if not identity_only
|
156 |
+
else matrix_trace)
|
157 |
+
|
158 |
+
is_identity = equal_valued(matrix[0], 1) if identity_only else True
|
159 |
+
|
160 |
+
has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
|
161 |
+
|
162 |
+
# The matrix is scalar if it's diagonal and the adjusted trace
|
163 |
+
# value is equal to 2^nqubits
|
164 |
+
return bool(
|
165 |
+
matrix.is_diagonal() and has_correct_trace and is_identity)
|
166 |
+
|
167 |
+
if np and scipy:
|
168 |
+
is_scalar_matrix = is_scalar_sparse_matrix
|
169 |
+
else:
|
170 |
+
is_scalar_matrix = is_scalar_nonsparse_matrix
|
171 |
+
|
172 |
+
|
173 |
+
def _get_min_qubits(a_gate):
|
174 |
+
if isinstance(a_gate, Pow):
|
175 |
+
return a_gate.base.min_qubits
|
176 |
+
else:
|
177 |
+
return a_gate.min_qubits
|
178 |
+
|
179 |
+
|
180 |
+
def ll_op(left, right):
|
181 |
+
"""Perform a LL operation.
|
182 |
+
|
183 |
+
A LL operation multiplies both left and right circuits
|
184 |
+
with the dagger of the left circuit's leftmost gate, and
|
185 |
+
the dagger is multiplied on the left side of both circuits.
|
186 |
+
|
187 |
+
If a LL is possible, it returns the new gate rule as a
|
188 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
189 |
+
and RHS is the right circuit of the new rule.
|
190 |
+
If a LL is not possible, None is returned.
|
191 |
+
|
192 |
+
Parameters
|
193 |
+
==========
|
194 |
+
|
195 |
+
left : Gate tuple
|
196 |
+
The left circuit of a gate rule expression.
|
197 |
+
right : Gate tuple
|
198 |
+
The right circuit of a gate rule expression.
|
199 |
+
|
200 |
+
Examples
|
201 |
+
========
|
202 |
+
|
203 |
+
Generate a new gate rule using a LL operation:
|
204 |
+
|
205 |
+
>>> from sympy.physics.quantum.identitysearch import ll_op
|
206 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
207 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
208 |
+
>>> ll_op((x, y, z), ())
|
209 |
+
((Y(0), Z(0)), (X(0),))
|
210 |
+
|
211 |
+
>>> ll_op((y, z), (x,))
|
212 |
+
((Z(0),), (Y(0), X(0)))
|
213 |
+
"""
|
214 |
+
|
215 |
+
if (len(left) > 0):
|
216 |
+
ll_gate = left[0]
|
217 |
+
ll_gate_is_unitary = is_scalar_matrix(
|
218 |
+
(Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
|
219 |
+
|
220 |
+
if (len(left) > 0 and ll_gate_is_unitary):
|
221 |
+
# Get the new left side w/o the leftmost gate
|
222 |
+
new_left = left[1:len(left)]
|
223 |
+
# Add the leftmost gate to the left position on the right side
|
224 |
+
new_right = (Dagger(ll_gate),) + right
|
225 |
+
# Return the new gate rule
|
226 |
+
return (new_left, new_right)
|
227 |
+
|
228 |
+
return None
|
229 |
+
|
230 |
+
|
231 |
+
def lr_op(left, right):
|
232 |
+
"""Perform a LR operation.
|
233 |
+
|
234 |
+
A LR operation multiplies both left and right circuits
|
235 |
+
with the dagger of the left circuit's rightmost gate, and
|
236 |
+
the dagger is multiplied on the right side of both circuits.
|
237 |
+
|
238 |
+
If a LR is possible, it returns the new gate rule as a
|
239 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
240 |
+
and RHS is the right circuit of the new rule.
|
241 |
+
If a LR is not possible, None is returned.
|
242 |
+
|
243 |
+
Parameters
|
244 |
+
==========
|
245 |
+
|
246 |
+
left : Gate tuple
|
247 |
+
The left circuit of a gate rule expression.
|
248 |
+
right : Gate tuple
|
249 |
+
The right circuit of a gate rule expression.
|
250 |
+
|
251 |
+
Examples
|
252 |
+
========
|
253 |
+
|
254 |
+
Generate a new gate rule using a LR operation:
|
255 |
+
|
256 |
+
>>> from sympy.physics.quantum.identitysearch import lr_op
|
257 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
258 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
259 |
+
>>> lr_op((x, y, z), ())
|
260 |
+
((X(0), Y(0)), (Z(0),))
|
261 |
+
|
262 |
+
>>> lr_op((x, y), (z,))
|
263 |
+
((X(0),), (Z(0), Y(0)))
|
264 |
+
"""
|
265 |
+
|
266 |
+
if (len(left) > 0):
|
267 |
+
lr_gate = left[len(left) - 1]
|
268 |
+
lr_gate_is_unitary = is_scalar_matrix(
|
269 |
+
(Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
|
270 |
+
|
271 |
+
if (len(left) > 0 and lr_gate_is_unitary):
|
272 |
+
# Get the new left side w/o the rightmost gate
|
273 |
+
new_left = left[0:len(left) - 1]
|
274 |
+
# Add the rightmost gate to the right position on the right side
|
275 |
+
new_right = right + (Dagger(lr_gate),)
|
276 |
+
# Return the new gate rule
|
277 |
+
return (new_left, new_right)
|
278 |
+
|
279 |
+
return None
|
280 |
+
|
281 |
+
|
282 |
+
def rl_op(left, right):
|
283 |
+
"""Perform a RL operation.
|
284 |
+
|
285 |
+
A RL operation multiplies both left and right circuits
|
286 |
+
with the dagger of the right circuit's leftmost gate, and
|
287 |
+
the dagger is multiplied on the left side of both circuits.
|
288 |
+
|
289 |
+
If a RL is possible, it returns the new gate rule as a
|
290 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
291 |
+
and RHS is the right circuit of the new rule.
|
292 |
+
If a RL is not possible, None is returned.
|
293 |
+
|
294 |
+
Parameters
|
295 |
+
==========
|
296 |
+
|
297 |
+
left : Gate tuple
|
298 |
+
The left circuit of a gate rule expression.
|
299 |
+
right : Gate tuple
|
300 |
+
The right circuit of a gate rule expression.
|
301 |
+
|
302 |
+
Examples
|
303 |
+
========
|
304 |
+
|
305 |
+
Generate a new gate rule using a RL operation:
|
306 |
+
|
307 |
+
>>> from sympy.physics.quantum.identitysearch import rl_op
|
308 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
309 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
310 |
+
>>> rl_op((x,), (y, z))
|
311 |
+
((Y(0), X(0)), (Z(0),))
|
312 |
+
|
313 |
+
>>> rl_op((x, y), (z,))
|
314 |
+
((Z(0), X(0), Y(0)), ())
|
315 |
+
"""
|
316 |
+
|
317 |
+
if (len(right) > 0):
|
318 |
+
rl_gate = right[0]
|
319 |
+
rl_gate_is_unitary = is_scalar_matrix(
|
320 |
+
(Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
|
321 |
+
|
322 |
+
if (len(right) > 0 and rl_gate_is_unitary):
|
323 |
+
# Get the new right side w/o the leftmost gate
|
324 |
+
new_right = right[1:len(right)]
|
325 |
+
# Add the leftmost gate to the left position on the left side
|
326 |
+
new_left = (Dagger(rl_gate),) + left
|
327 |
+
# Return the new gate rule
|
328 |
+
return (new_left, new_right)
|
329 |
+
|
330 |
+
return None
|
331 |
+
|
332 |
+
|
333 |
+
def rr_op(left, right):
|
334 |
+
"""Perform a RR operation.
|
335 |
+
|
336 |
+
A RR operation multiplies both left and right circuits
|
337 |
+
with the dagger of the right circuit's rightmost gate, and
|
338 |
+
the dagger is multiplied on the right side of both circuits.
|
339 |
+
|
340 |
+
If a RR is possible, it returns the new gate rule as a
|
341 |
+
2-tuple (LHS, RHS), where LHS is the left circuit and
|
342 |
+
and RHS is the right circuit of the new rule.
|
343 |
+
If a RR is not possible, None is returned.
|
344 |
+
|
345 |
+
Parameters
|
346 |
+
==========
|
347 |
+
|
348 |
+
left : Gate tuple
|
349 |
+
The left circuit of a gate rule expression.
|
350 |
+
right : Gate tuple
|
351 |
+
The right circuit of a gate rule expression.
|
352 |
+
|
353 |
+
Examples
|
354 |
+
========
|
355 |
+
|
356 |
+
Generate a new gate rule using a RR operation:
|
357 |
+
|
358 |
+
>>> from sympy.physics.quantum.identitysearch import rr_op
|
359 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
360 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
361 |
+
>>> rr_op((x, y), (z,))
|
362 |
+
((X(0), Y(0), Z(0)), ())
|
363 |
+
|
364 |
+
>>> rr_op((x,), (y, z))
|
365 |
+
((X(0), Z(0)), (Y(0),))
|
366 |
+
"""
|
367 |
+
|
368 |
+
if (len(right) > 0):
|
369 |
+
rr_gate = right[len(right) - 1]
|
370 |
+
rr_gate_is_unitary = is_scalar_matrix(
|
371 |
+
(Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
|
372 |
+
|
373 |
+
if (len(right) > 0 and rr_gate_is_unitary):
|
374 |
+
# Get the new right side w/o the rightmost gate
|
375 |
+
new_right = right[0:len(right) - 1]
|
376 |
+
# Add the rightmost gate to the right position on the right side
|
377 |
+
new_left = left + (Dagger(rr_gate),)
|
378 |
+
# Return the new gate rule
|
379 |
+
return (new_left, new_right)
|
380 |
+
|
381 |
+
return None
|
382 |
+
|
383 |
+
|
384 |
+
def generate_gate_rules(gate_seq, return_as_muls=False):
|
385 |
+
"""Returns a set of gate rules. Each gate rules is represented
|
386 |
+
as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary
|
387 |
+
scalar value.
|
388 |
+
|
389 |
+
This function uses the four operations (LL, LR, RL, RR)
|
390 |
+
to generate the gate rules.
|
391 |
+
|
392 |
+
A gate rule is an expression such as ABC = D or AB = CD, where
|
393 |
+
A, B, C, and D are gates. Each value on either side of the
|
394 |
+
equal sign represents a circuit. The four operations allow
|
395 |
+
one to find a set of equivalent circuits from a gate identity.
|
396 |
+
The letters denoting the operation tell the user what
|
397 |
+
activities to perform on each expression. The first letter
|
398 |
+
indicates which side of the equal sign to focus on. The
|
399 |
+
second letter indicates which gate to focus on given the
|
400 |
+
side. Once this information is determined, the inverse
|
401 |
+
of the gate is multiplied on both circuits to create a new
|
402 |
+
gate rule.
|
403 |
+
|
404 |
+
For example, given the identity, ABCD = 1, a LL operation
|
405 |
+
means look at the left value and multiply both left sides by the
|
406 |
+
inverse of the leftmost gate A. If A is Hermitian, the inverse
|
407 |
+
of A is still A. The resulting new rule is BCD = A.
|
408 |
+
|
409 |
+
The following is a summary of the four operations. Assume
|
410 |
+
that in the examples, all gates are Hermitian.
|
411 |
+
|
412 |
+
LL : left circuit, left multiply
|
413 |
+
ABCD = E -> AABCD = AE -> BCD = AE
|
414 |
+
LR : left circuit, right multiply
|
415 |
+
ABCD = E -> ABCDD = ED -> ABC = ED
|
416 |
+
RL : right circuit, left multiply
|
417 |
+
ABC = ED -> EABC = EED -> EABC = D
|
418 |
+
RR : right circuit, right multiply
|
419 |
+
AB = CD -> ABD = CDD -> ABD = C
|
420 |
+
|
421 |
+
The number of gate rules generated is n*(n+1), where n
|
422 |
+
is the number of gates in the sequence (unproven).
|
423 |
+
|
424 |
+
Parameters
|
425 |
+
==========
|
426 |
+
|
427 |
+
gate_seq : Gate tuple, Mul, or Number
|
428 |
+
A variable length tuple or Mul of Gates whose product is equal to
|
429 |
+
a scalar matrix
|
430 |
+
return_as_muls : bool
|
431 |
+
True to return a set of Muls; False to return a set of tuples
|
432 |
+
|
433 |
+
Examples
|
434 |
+
========
|
435 |
+
|
436 |
+
Find the gate rules of the current circuit using tuples:
|
437 |
+
|
438 |
+
>>> from sympy.physics.quantum.identitysearch import generate_gate_rules
|
439 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
440 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
441 |
+
>>> generate_gate_rules((x, x))
|
442 |
+
{((X(0),), (X(0),)), ((X(0), X(0)), ())}
|
443 |
+
|
444 |
+
>>> generate_gate_rules((x, y, z))
|
445 |
+
{((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
|
446 |
+
((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
|
447 |
+
((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
|
448 |
+
((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
|
449 |
+
((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
|
450 |
+
((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
|
451 |
+
|
452 |
+
Find the gate rules of the current circuit using Muls:
|
453 |
+
|
454 |
+
>>> generate_gate_rules(x*x, return_as_muls=True)
|
455 |
+
{(1, 1)}
|
456 |
+
|
457 |
+
>>> generate_gate_rules(x*y*z, return_as_muls=True)
|
458 |
+
{(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
|
459 |
+
(1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
|
460 |
+
(Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
|
461 |
+
(X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
|
462 |
+
(Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
|
463 |
+
(Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
|
464 |
+
"""
|
465 |
+
|
466 |
+
if isinstance(gate_seq, Number):
|
467 |
+
if return_as_muls:
|
468 |
+
return {(S.One, S.One)}
|
469 |
+
else:
|
470 |
+
return {((), ())}
|
471 |
+
|
472 |
+
elif isinstance(gate_seq, Mul):
|
473 |
+
gate_seq = gate_seq.args
|
474 |
+
|
475 |
+
# Each item in queue is a 3-tuple:
|
476 |
+
# i) first item is the left side of an equality
|
477 |
+
# ii) second item is the right side of an equality
|
478 |
+
# iii) third item is the number of operations performed
|
479 |
+
# The argument, gate_seq, will start on the left side, and
|
480 |
+
# the right side will be empty, implying the presence of an
|
481 |
+
# identity.
|
482 |
+
queue = deque()
|
483 |
+
# A set of gate rules
|
484 |
+
rules = set()
|
485 |
+
# Maximum number of operations to perform
|
486 |
+
max_ops = len(gate_seq)
|
487 |
+
|
488 |
+
def process_new_rule(new_rule, ops):
|
489 |
+
if new_rule is not None:
|
490 |
+
new_left, new_right = new_rule
|
491 |
+
|
492 |
+
if new_rule not in rules and (new_right, new_left) not in rules:
|
493 |
+
rules.add(new_rule)
|
494 |
+
# If haven't reached the max limit on operations
|
495 |
+
if ops + 1 < max_ops:
|
496 |
+
queue.append(new_rule + (ops + 1,))
|
497 |
+
|
498 |
+
queue.append((gate_seq, (), 0))
|
499 |
+
rules.add((gate_seq, ()))
|
500 |
+
|
501 |
+
while len(queue) > 0:
|
502 |
+
left, right, ops = queue.popleft()
|
503 |
+
|
504 |
+
# Do a LL
|
505 |
+
new_rule = ll_op(left, right)
|
506 |
+
process_new_rule(new_rule, ops)
|
507 |
+
# Do a LR
|
508 |
+
new_rule = lr_op(left, right)
|
509 |
+
process_new_rule(new_rule, ops)
|
510 |
+
# Do a RL
|
511 |
+
new_rule = rl_op(left, right)
|
512 |
+
process_new_rule(new_rule, ops)
|
513 |
+
# Do a RR
|
514 |
+
new_rule = rr_op(left, right)
|
515 |
+
process_new_rule(new_rule, ops)
|
516 |
+
|
517 |
+
if return_as_muls:
|
518 |
+
# Convert each rule as tuples into a rule as muls
|
519 |
+
mul_rules = set()
|
520 |
+
for rule in rules:
|
521 |
+
left, right = rule
|
522 |
+
mul_rules.add((Mul(*left), Mul(*right)))
|
523 |
+
|
524 |
+
rules = mul_rules
|
525 |
+
|
526 |
+
return rules
|
527 |
+
|
528 |
+
|
529 |
+
def generate_equivalent_ids(gate_seq, return_as_muls=False):
|
530 |
+
"""Returns a set of equivalent gate identities.
|
531 |
+
|
532 |
+
A gate identity is a quantum circuit such that the product
|
533 |
+
of the gates in the circuit is equal to a scalar value.
|
534 |
+
For example, XYZ = i, where X, Y, Z are the Pauli gates and
|
535 |
+
i is the imaginary value, is considered a gate identity.
|
536 |
+
|
537 |
+
This function uses the four operations (LL, LR, RL, RR)
|
538 |
+
to generate the gate rules and, subsequently, to locate equivalent
|
539 |
+
gate identities.
|
540 |
+
|
541 |
+
Note that all equivalent identities are reachable in n operations
|
542 |
+
from the starting gate identity, where n is the number of gates
|
543 |
+
in the sequence.
|
544 |
+
|
545 |
+
The max number of gate identities is 2n, where n is the number
|
546 |
+
of gates in the sequence (unproven).
|
547 |
+
|
548 |
+
Parameters
|
549 |
+
==========
|
550 |
+
|
551 |
+
gate_seq : Gate tuple, Mul, or Number
|
552 |
+
A variable length tuple or Mul of Gates whose product is equal to
|
553 |
+
a scalar matrix.
|
554 |
+
return_as_muls: bool
|
555 |
+
True to return as Muls; False to return as tuples
|
556 |
+
|
557 |
+
Examples
|
558 |
+
========
|
559 |
+
|
560 |
+
Find equivalent gate identities from the current circuit with tuples:
|
561 |
+
|
562 |
+
>>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
|
563 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
564 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
565 |
+
>>> generate_equivalent_ids((x, x))
|
566 |
+
{(X(0), X(0))}
|
567 |
+
|
568 |
+
>>> generate_equivalent_ids((x, y, z))
|
569 |
+
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
|
570 |
+
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
|
571 |
+
|
572 |
+
Find equivalent gate identities from the current circuit with Muls:
|
573 |
+
|
574 |
+
>>> generate_equivalent_ids(x*x, return_as_muls=True)
|
575 |
+
{1}
|
576 |
+
|
577 |
+
>>> generate_equivalent_ids(x*y*z, return_as_muls=True)
|
578 |
+
{X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
|
579 |
+
Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
|
580 |
+
"""
|
581 |
+
|
582 |
+
if isinstance(gate_seq, Number):
|
583 |
+
return {S.One}
|
584 |
+
elif isinstance(gate_seq, Mul):
|
585 |
+
gate_seq = gate_seq.args
|
586 |
+
|
587 |
+
# Filter through the gate rules and keep the rules
|
588 |
+
# with an empty tuple either on the left or right side
|
589 |
+
|
590 |
+
# A set of equivalent gate identities
|
591 |
+
eq_ids = set()
|
592 |
+
|
593 |
+
gate_rules = generate_gate_rules(gate_seq)
|
594 |
+
for rule in gate_rules:
|
595 |
+
l, r = rule
|
596 |
+
if l == ():
|
597 |
+
eq_ids.add(r)
|
598 |
+
elif r == ():
|
599 |
+
eq_ids.add(l)
|
600 |
+
|
601 |
+
if return_as_muls:
|
602 |
+
convert_to_mul = lambda id_seq: Mul(*id_seq)
|
603 |
+
eq_ids = set(map(convert_to_mul, eq_ids))
|
604 |
+
|
605 |
+
return eq_ids
|
606 |
+
|
607 |
+
|
608 |
+
class GateIdentity(Basic):
|
609 |
+
"""Wrapper class for circuits that reduce to a scalar value.
|
610 |
+
|
611 |
+
A gate identity is a quantum circuit such that the product
|
612 |
+
of the gates in the circuit is equal to a scalar value.
|
613 |
+
For example, XYZ = i, where X, Y, Z are the Pauli gates and
|
614 |
+
i is the imaginary value, is considered a gate identity.
|
615 |
+
|
616 |
+
Parameters
|
617 |
+
==========
|
618 |
+
|
619 |
+
args : Gate tuple
|
620 |
+
A variable length tuple of Gates that form an identity.
|
621 |
+
|
622 |
+
Examples
|
623 |
+
========
|
624 |
+
|
625 |
+
Create a GateIdentity and look at its attributes:
|
626 |
+
|
627 |
+
>>> from sympy.physics.quantum.identitysearch import GateIdentity
|
628 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
629 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
630 |
+
>>> an_identity = GateIdentity(x, y, z)
|
631 |
+
>>> an_identity.circuit
|
632 |
+
X(0)*Y(0)*Z(0)
|
633 |
+
|
634 |
+
>>> an_identity.equivalent_ids
|
635 |
+
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
|
636 |
+
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
|
637 |
+
"""
|
638 |
+
|
639 |
+
def __new__(cls, *args):
|
640 |
+
# args should be a tuple - a variable length argument list
|
641 |
+
obj = Basic.__new__(cls, *args)
|
642 |
+
obj._circuit = Mul(*args)
|
643 |
+
obj._rules = generate_gate_rules(args)
|
644 |
+
obj._eq_ids = generate_equivalent_ids(args)
|
645 |
+
|
646 |
+
return obj
|
647 |
+
|
648 |
+
@property
|
649 |
+
def circuit(self):
|
650 |
+
return self._circuit
|
651 |
+
|
652 |
+
@property
|
653 |
+
def gate_rules(self):
|
654 |
+
return self._rules
|
655 |
+
|
656 |
+
@property
|
657 |
+
def equivalent_ids(self):
|
658 |
+
return self._eq_ids
|
659 |
+
|
660 |
+
@property
|
661 |
+
def sequence(self):
|
662 |
+
return self.args
|
663 |
+
|
664 |
+
def __str__(self):
|
665 |
+
"""Returns the string of gates in a tuple."""
|
666 |
+
return str(self.circuit)
|
667 |
+
|
668 |
+
|
669 |
+
def is_degenerate(identity_set, gate_identity):
|
670 |
+
"""Checks if a gate identity is a permutation of another identity.
|
671 |
+
|
672 |
+
Parameters
|
673 |
+
==========
|
674 |
+
|
675 |
+
identity_set : set
|
676 |
+
A Python set with GateIdentity objects.
|
677 |
+
gate_identity : GateIdentity
|
678 |
+
The GateIdentity to check for existence in the set.
|
679 |
+
|
680 |
+
Examples
|
681 |
+
========
|
682 |
+
|
683 |
+
Check if the identity is a permutation of another identity:
|
684 |
+
|
685 |
+
>>> from sympy.physics.quantum.identitysearch import (
|
686 |
+
... GateIdentity, is_degenerate)
|
687 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
688 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
689 |
+
>>> an_identity = GateIdentity(x, y, z)
|
690 |
+
>>> id_set = {an_identity}
|
691 |
+
>>> another_id = (y, z, x)
|
692 |
+
>>> is_degenerate(id_set, another_id)
|
693 |
+
True
|
694 |
+
|
695 |
+
>>> another_id = (x, x)
|
696 |
+
>>> is_degenerate(id_set, another_id)
|
697 |
+
False
|
698 |
+
"""
|
699 |
+
|
700 |
+
# For now, just iteratively go through the set and check if the current
|
701 |
+
# gate_identity is a permutation of an identity in the set
|
702 |
+
for an_id in identity_set:
|
703 |
+
if (gate_identity in an_id.equivalent_ids):
|
704 |
+
return True
|
705 |
+
return False
|
706 |
+
|
707 |
+
|
708 |
+
def is_reducible(circuit, nqubits, begin, end):
|
709 |
+
"""Determines if a circuit is reducible by checking
|
710 |
+
if its subcircuits are scalar values.
|
711 |
+
|
712 |
+
Parameters
|
713 |
+
==========
|
714 |
+
|
715 |
+
circuit : Gate tuple
|
716 |
+
A tuple of Gates representing a circuit. The circuit to check
|
717 |
+
if a gate identity is contained in a subcircuit.
|
718 |
+
nqubits : int
|
719 |
+
The number of qubits the circuit operates on.
|
720 |
+
begin : int
|
721 |
+
The leftmost gate in the circuit to include in a subcircuit.
|
722 |
+
end : int
|
723 |
+
The rightmost gate in the circuit to include in a subcircuit.
|
724 |
+
|
725 |
+
Examples
|
726 |
+
========
|
727 |
+
|
728 |
+
Check if the circuit can be reduced:
|
729 |
+
|
730 |
+
>>> from sympy.physics.quantum.identitysearch import is_reducible
|
731 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
732 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
733 |
+
>>> is_reducible((x, y, z), 1, 0, 3)
|
734 |
+
True
|
735 |
+
|
736 |
+
Check if an interval in the circuit can be reduced:
|
737 |
+
|
738 |
+
>>> is_reducible((x, y, z), 1, 1, 3)
|
739 |
+
False
|
740 |
+
|
741 |
+
>>> is_reducible((x, y, y), 1, 1, 3)
|
742 |
+
True
|
743 |
+
"""
|
744 |
+
|
745 |
+
current_circuit = ()
|
746 |
+
# Start from the gate at "end" and go down to almost the gate at "begin"
|
747 |
+
for ndx in reversed(range(begin, end)):
|
748 |
+
next_gate = circuit[ndx]
|
749 |
+
current_circuit = (next_gate,) + current_circuit
|
750 |
+
|
751 |
+
# If a circuit as a matrix is equivalent to a scalar value
|
752 |
+
if (is_scalar_matrix(current_circuit, nqubits, False)):
|
753 |
+
return True
|
754 |
+
|
755 |
+
return False
|
756 |
+
|
757 |
+
|
758 |
+
def bfs_identity_search(gate_list, nqubits, max_depth=None,
|
759 |
+
identity_only=False):
|
760 |
+
"""Constructs a set of gate identities from the list of possible gates.
|
761 |
+
|
762 |
+
Performs a breadth first search over the space of gate identities.
|
763 |
+
This allows the finding of the shortest gate identities first.
|
764 |
+
|
765 |
+
Parameters
|
766 |
+
==========
|
767 |
+
|
768 |
+
gate_list : list, Gate
|
769 |
+
A list of Gates from which to search for gate identities.
|
770 |
+
nqubits : int
|
771 |
+
The number of qubits the quantum circuit operates on.
|
772 |
+
max_depth : int
|
773 |
+
The longest quantum circuit to construct from gate_list.
|
774 |
+
identity_only : bool
|
775 |
+
True to search for gate identities that reduce to identity;
|
776 |
+
False to search for gate identities that reduce to a scalar.
|
777 |
+
|
778 |
+
Examples
|
779 |
+
========
|
780 |
+
|
781 |
+
Find a list of gate identities:
|
782 |
+
|
783 |
+
>>> from sympy.physics.quantum.identitysearch import bfs_identity_search
|
784 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z
|
785 |
+
>>> x = X(0); y = Y(0); z = Z(0)
|
786 |
+
>>> bfs_identity_search([x], 1, max_depth=2)
|
787 |
+
{GateIdentity(X(0), X(0))}
|
788 |
+
|
789 |
+
>>> bfs_identity_search([x, y, z], 1)
|
790 |
+
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
|
791 |
+
GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
|
792 |
+
|
793 |
+
Find a list of identities that only equal to 1:
|
794 |
+
|
795 |
+
>>> bfs_identity_search([x, y, z], 1, identity_only=True)
|
796 |
+
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
|
797 |
+
GateIdentity(Z(0), Z(0))}
|
798 |
+
"""
|
799 |
+
|
800 |
+
if max_depth is None or max_depth <= 0:
|
801 |
+
max_depth = len(gate_list)
|
802 |
+
|
803 |
+
id_only = identity_only
|
804 |
+
|
805 |
+
# Start with an empty sequence (implicitly contains an IdentityGate)
|
806 |
+
queue = deque([()])
|
807 |
+
|
808 |
+
# Create an empty set of gate identities
|
809 |
+
ids = set()
|
810 |
+
|
811 |
+
# Begin searching for gate identities in given space.
|
812 |
+
while (len(queue) > 0):
|
813 |
+
current_circuit = queue.popleft()
|
814 |
+
|
815 |
+
for next_gate in gate_list:
|
816 |
+
new_circuit = current_circuit + (next_gate,)
|
817 |
+
|
818 |
+
# Determines if a (strict) subcircuit is a scalar matrix
|
819 |
+
circuit_reducible = is_reducible(new_circuit, nqubits,
|
820 |
+
1, len(new_circuit))
|
821 |
+
|
822 |
+
# In many cases when the matrix is a scalar value,
|
823 |
+
# the evaluated matrix will actually be an integer
|
824 |
+
if (is_scalar_matrix(new_circuit, nqubits, id_only) and
|
825 |
+
not is_degenerate(ids, new_circuit) and
|
826 |
+
not circuit_reducible):
|
827 |
+
ids.add(GateIdentity(*new_circuit))
|
828 |
+
|
829 |
+
elif (len(new_circuit) < max_depth and
|
830 |
+
not circuit_reducible):
|
831 |
+
queue.append(new_circuit)
|
832 |
+
|
833 |
+
return ids
|
834 |
+
|
835 |
+
|
836 |
+
def random_identity_search(gate_list, numgates, nqubits):
|
837 |
+
"""Randomly selects numgates from gate_list and checks if it is
|
838 |
+
a gate identity.
|
839 |
+
|
840 |
+
If the circuit is a gate identity, the circuit is returned;
|
841 |
+
Otherwise, None is returned.
|
842 |
+
"""
|
843 |
+
|
844 |
+
gate_size = len(gate_list)
|
845 |
+
circuit = ()
|
846 |
+
|
847 |
+
for i in range(numgates):
|
848 |
+
next_gate = gate_list[randint(0, gate_size - 1)]
|
849 |
+
circuit = circuit + (next_gate,)
|
850 |
+
|
851 |
+
is_scalar = is_scalar_matrix(circuit, nqubits, False)
|
852 |
+
|
853 |
+
return circuit if is_scalar else None
|
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Symbolic inner product."""
|
2 |
+
|
3 |
+
from sympy.core.expr import Expr
|
4 |
+
from sympy.functions.elementary.complexes import conjugate
|
5 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
6 |
+
from sympy.physics.quantum.dagger import Dagger
|
7 |
+
from sympy.physics.quantum.state import KetBase, BraBase
|
8 |
+
|
9 |
+
__all__ = [
|
10 |
+
'InnerProduct'
|
11 |
+
]
|
12 |
+
|
13 |
+
|
14 |
+
# InnerProduct is not an QExpr because it is really just a regular commutative
|
15 |
+
# number. We have gone back and forth about this, but we gain a lot by having
|
16 |
+
# it subclass Expr. The main challenges were getting Dagger to work
|
17 |
+
# (we use _eval_conjugate) and represent (we can use atoms and subs). Having
|
18 |
+
# it be an Expr, mean that there are no commutative QExpr subclasses,
|
19 |
+
# which simplifies the design of everything.
|
20 |
+
|
21 |
+
class InnerProduct(Expr):
|
22 |
+
"""An unevaluated inner product between a Bra and a Ket [1].
|
23 |
+
|
24 |
+
Parameters
|
25 |
+
==========
|
26 |
+
|
27 |
+
bra : BraBase or subclass
|
28 |
+
The bra on the left side of the inner product.
|
29 |
+
ket : KetBase or subclass
|
30 |
+
The ket on the right side of the inner product.
|
31 |
+
|
32 |
+
Examples
|
33 |
+
========
|
34 |
+
|
35 |
+
Create an InnerProduct and check its properties:
|
36 |
+
|
37 |
+
>>> from sympy.physics.quantum import Bra, Ket
|
38 |
+
>>> b = Bra('b')
|
39 |
+
>>> k = Ket('k')
|
40 |
+
>>> ip = b*k
|
41 |
+
>>> ip
|
42 |
+
<b|k>
|
43 |
+
>>> ip.bra
|
44 |
+
<b|
|
45 |
+
>>> ip.ket
|
46 |
+
|k>
|
47 |
+
|
48 |
+
In simple products of kets and bras inner products will be automatically
|
49 |
+
identified and created::
|
50 |
+
|
51 |
+
>>> b*k
|
52 |
+
<b|k>
|
53 |
+
|
54 |
+
But in more complex expressions, there is ambiguity in whether inner or
|
55 |
+
outer products should be created::
|
56 |
+
|
57 |
+
>>> k*b*k*b
|
58 |
+
|k><b|*|k>*<b|
|
59 |
+
|
60 |
+
A user can force the creation of a inner products in a complex expression
|
61 |
+
by using parentheses to group the bra and ket::
|
62 |
+
|
63 |
+
>>> k*(b*k)*b
|
64 |
+
<b|k>*|k>*<b|
|
65 |
+
|
66 |
+
Notice how the inner product <b|k> moved to the left of the expression
|
67 |
+
because inner products are commutative complex numbers.
|
68 |
+
|
69 |
+
References
|
70 |
+
==========
|
71 |
+
|
72 |
+
.. [1] https://en.wikipedia.org/wiki/Inner_product
|
73 |
+
"""
|
74 |
+
is_complex = True
|
75 |
+
|
76 |
+
def __new__(cls, bra, ket):
|
77 |
+
if not isinstance(ket, KetBase):
|
78 |
+
raise TypeError('KetBase subclass expected, got: %r' % ket)
|
79 |
+
if not isinstance(bra, BraBase):
|
80 |
+
raise TypeError('BraBase subclass expected, got: %r' % ket)
|
81 |
+
obj = Expr.__new__(cls, bra, ket)
|
82 |
+
return obj
|
83 |
+
|
84 |
+
@property
|
85 |
+
def bra(self):
|
86 |
+
return self.args[0]
|
87 |
+
|
88 |
+
@property
|
89 |
+
def ket(self):
|
90 |
+
return self.args[1]
|
91 |
+
|
92 |
+
def _eval_conjugate(self):
|
93 |
+
return InnerProduct(Dagger(self.ket), Dagger(self.bra))
|
94 |
+
|
95 |
+
def _sympyrepr(self, printer, *args):
|
96 |
+
return '%s(%s,%s)' % (self.__class__.__name__,
|
97 |
+
printer._print(self.bra, *args), printer._print(self.ket, *args))
|
98 |
+
|
99 |
+
def _sympystr(self, printer, *args):
|
100 |
+
sbra = printer._print(self.bra)
|
101 |
+
sket = printer._print(self.ket)
|
102 |
+
return '%s|%s' % (sbra[:-1], sket[1:])
|
103 |
+
|
104 |
+
def _pretty(self, printer, *args):
|
105 |
+
# Print state contents
|
106 |
+
bra = self.bra._print_contents_pretty(printer, *args)
|
107 |
+
ket = self.ket._print_contents_pretty(printer, *args)
|
108 |
+
# Print brackets
|
109 |
+
height = max(bra.height(), ket.height())
|
110 |
+
use_unicode = printer._use_unicode
|
111 |
+
lbracket, _ = self.bra._pretty_brackets(height, use_unicode)
|
112 |
+
cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode)
|
113 |
+
# Build innerproduct
|
114 |
+
pform = prettyForm(*bra.left(lbracket))
|
115 |
+
pform = prettyForm(*pform.right(cbracket))
|
116 |
+
pform = prettyForm(*pform.right(ket))
|
117 |
+
pform = prettyForm(*pform.right(rbracket))
|
118 |
+
return pform
|
119 |
+
|
120 |
+
def _latex(self, printer, *args):
|
121 |
+
bra_label = self.bra._print_contents_latex(printer, *args)
|
122 |
+
ket = printer._print(self.ket, *args)
|
123 |
+
return r'\left\langle %s \right. %s' % (bra_label, ket)
|
124 |
+
|
125 |
+
def doit(self, **hints):
|
126 |
+
try:
|
127 |
+
r = self.ket._eval_innerproduct(self.bra, **hints)
|
128 |
+
except NotImplementedError:
|
129 |
+
try:
|
130 |
+
r = conjugate(
|
131 |
+
self.bra.dual._eval_innerproduct(self.ket.dual, **hints)
|
132 |
+
)
|
133 |
+
except NotImplementedError:
|
134 |
+
r = None
|
135 |
+
if r is not None:
|
136 |
+
return r
|
137 |
+
return self
|