applied-ai-018 commited on
Commit
0c03f3b
·
verified ·
1 Parent(s): 6e3e29d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py +59 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/__init__.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitplot.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitutils.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/fermion.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/qubit.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py +149 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py +370 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py +280 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/piab.py +72 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/qasm.py +224 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/represent.py +574 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py +423 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_boson.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cartesian.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cg.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitplot.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_dagger.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_density.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_grover.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_hilbert.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_matrixutils.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorset.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_pauli.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_piab.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc +0 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qapply.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qft.cpython-310.pyc +0 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qubit.cpython-310.pyc +0 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc +0 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_sho1d.cpython-310.pyc +0 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_shor.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_state.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_tensorproduct.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_anticommutator.py +56 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py +50 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py +104 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py +178 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitplot.py +69 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitutils.py +402 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_commutator.py +81 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py +13 -0
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc ADDED
Binary file (2.66 kB). View file
 
llmeval-env/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
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitplot.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitutils.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/fermion.cpython-310.pyc ADDED
Binary file (5.75 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/qubit.cpython-310.pyc ADDED
Binary file (22.5 kB). View file
 
llmeval-env/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])
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ A module for mapping operators to their corresponding eigenstates
2
+ and vice versa
3
+
4
+ It contains a global dictionary with eigenstate-operator pairings.
5
+ If a new state-operator pair is created, this dictionary should be
6
+ updated as well.
7
+
8
+ It also contains functions operators_to_state and state_to_operators
9
+ for mapping between the two. These can handle both classes and
10
+ instances of operators and states. See the individual function
11
+ descriptions for details.
12
+
13
+ TODO List:
14
+ - Update the dictionary with a complete list of state-operator pairs
15
+ """
16
+
17
+ from sympy.physics.quantum.cartesian import (XOp, YOp, ZOp, XKet, PxOp, PxKet,
18
+ PositionKet3D)
19
+ from sympy.physics.quantum.operator import Operator
20
+ from sympy.physics.quantum.state import StateBase, BraBase, Ket
21
+ from sympy.physics.quantum.spin import (JxOp, JyOp, JzOp, J2Op, JxKet, JyKet,
22
+ JzKet)
23
+
24
+ __all__ = [
25
+ 'operators_to_state',
26
+ 'state_to_operators'
27
+ ]
28
+
29
+ #state_mapping stores the mappings between states and their associated
30
+ #operators or tuples of operators. This should be updated when new
31
+ #classes are written! Entries are of the form PxKet : PxOp or
32
+ #something like 3DKet : (ROp, ThetaOp, PhiOp)
33
+
34
+ #frozenset is used so that the reverse mapping can be made
35
+ #(regular sets are not hashable because they are mutable
36
+ state_mapping = { JxKet: frozenset((J2Op, JxOp)),
37
+ JyKet: frozenset((J2Op, JyOp)),
38
+ JzKet: frozenset((J2Op, JzOp)),
39
+ Ket: Operator,
40
+ PositionKet3D: frozenset((XOp, YOp, ZOp)),
41
+ PxKet: PxOp,
42
+ XKet: XOp }
43
+
44
+ op_mapping = {v: k for k, v in state_mapping.items()}
45
+
46
+
47
+ def operators_to_state(operators, **options):
48
+ """ Returns the eigenstate of the given operator or set of operators
49
+
50
+ A global function for mapping operator classes to their associated
51
+ states. It takes either an Operator or a set of operators and
52
+ returns the state associated with these.
53
+
54
+ This function can handle both instances of a given operator or
55
+ just the class itself (i.e. both XOp() and XOp)
56
+
57
+ There are multiple use cases to consider:
58
+
59
+ 1) A class or set of classes is passed: First, we try to
60
+ instantiate default instances for these operators. If this fails,
61
+ then the class is simply returned. If we succeed in instantiating
62
+ default instances, then we try to call state._operators_to_state
63
+ on the operator instances. If this fails, the class is returned.
64
+ Otherwise, the instance returned by _operators_to_state is returned.
65
+
66
+ 2) An instance or set of instances is passed: In this case,
67
+ state._operators_to_state is called on the instances passed. If
68
+ this fails, a state class is returned. If the method returns an
69
+ instance, that instance is returned.
70
+
71
+ In both cases, if the operator class or set does not exist in the
72
+ state_mapping dictionary, None is returned.
73
+
74
+ Parameters
75
+ ==========
76
+
77
+ arg: Operator or set
78
+ The class or instance of the operator or set of operators
79
+ to be mapped to a state
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy.physics.quantum.cartesian import XOp, PxOp
85
+ >>> from sympy.physics.quantum.operatorset import operators_to_state
86
+ >>> from sympy.physics.quantum.operator import Operator
87
+ >>> operators_to_state(XOp)
88
+ |x>
89
+ >>> operators_to_state(XOp())
90
+ |x>
91
+ >>> operators_to_state(PxOp)
92
+ |px>
93
+ >>> operators_to_state(PxOp())
94
+ |px>
95
+ >>> operators_to_state(Operator)
96
+ |psi>
97
+ >>> operators_to_state(Operator())
98
+ |psi>
99
+ """
100
+
101
+ if not (isinstance(operators, Operator)
102
+ or isinstance(operators, set) or issubclass(operators, Operator)):
103
+ raise NotImplementedError("Argument is not an Operator or a set!")
104
+
105
+ if isinstance(operators, set):
106
+ for s in operators:
107
+ if not (isinstance(s, Operator)
108
+ or issubclass(s, Operator)):
109
+ raise NotImplementedError("Set is not all Operators!")
110
+
111
+ ops = frozenset(operators)
112
+
113
+ if ops in op_mapping: # ops is a list of classes in this case
114
+ #Try to get an object from default instances of the
115
+ #operators...if this fails, return the class
116
+ try:
117
+ op_instances = [op() for op in ops]
118
+ ret = _get_state(op_mapping[ops], set(op_instances), **options)
119
+ except NotImplementedError:
120
+ ret = op_mapping[ops]
121
+
122
+ return ret
123
+ else:
124
+ tmp = [type(o) for o in ops]
125
+ classes = frozenset(tmp)
126
+
127
+ if classes in op_mapping:
128
+ ret = _get_state(op_mapping[classes], ops, **options)
129
+ else:
130
+ ret = None
131
+
132
+ return ret
133
+ else:
134
+ if operators in op_mapping:
135
+ try:
136
+ op_instance = operators()
137
+ ret = _get_state(op_mapping[operators], op_instance, **options)
138
+ except NotImplementedError:
139
+ ret = op_mapping[operators]
140
+
141
+ return ret
142
+ elif type(operators) in op_mapping:
143
+ return _get_state(op_mapping[type(operators)], operators, **options)
144
+ else:
145
+ return None
146
+
147
+
148
+ def state_to_operators(state, **options):
149
+ """ Returns the operator or set of operators corresponding to the
150
+ given eigenstate
151
+
152
+ A global function for mapping state classes to their associated
153
+ operators or sets of operators. It takes either a state class
154
+ or instance.
155
+
156
+ This function can handle both instances of a given state or just
157
+ the class itself (i.e. both XKet() and XKet)
158
+
159
+ There are multiple use cases to consider:
160
+
161
+ 1) A state class is passed: In this case, we first try
162
+ instantiating a default instance of the class. If this succeeds,
163
+ then we try to call state._state_to_operators on that instance.
164
+ If the creation of the default instance or if the calling of
165
+ _state_to_operators fails, then either an operator class or set of
166
+ operator classes is returned. Otherwise, the appropriate
167
+ operator instances are returned.
168
+
169
+ 2) A state instance is returned: Here, state._state_to_operators
170
+ is called for the instance. If this fails, then a class or set of
171
+ operator classes is returned. Otherwise, the instances are returned.
172
+
173
+ In either case, if the state's class does not exist in
174
+ state_mapping, None is returned.
175
+
176
+ Parameters
177
+ ==========
178
+
179
+ arg: StateBase class or instance (or subclasses)
180
+ The class or instance of the state to be mapped to an
181
+ operator or set of operators
182
+
183
+ Examples
184
+ ========
185
+
186
+ >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra
187
+ >>> from sympy.physics.quantum.operatorset import state_to_operators
188
+ >>> from sympy.physics.quantum.state import Ket, Bra
189
+ >>> state_to_operators(XKet)
190
+ X
191
+ >>> state_to_operators(XKet())
192
+ X
193
+ >>> state_to_operators(PxKet)
194
+ Px
195
+ >>> state_to_operators(PxKet())
196
+ Px
197
+ >>> state_to_operators(PxBra)
198
+ Px
199
+ >>> state_to_operators(XBra)
200
+ X
201
+ >>> state_to_operators(Ket)
202
+ O
203
+ >>> state_to_operators(Bra)
204
+ O
205
+ """
206
+
207
+ if not (isinstance(state, StateBase) or issubclass(state, StateBase)):
208
+ raise NotImplementedError("Argument is not a state!")
209
+
210
+ if state in state_mapping: # state is a class
211
+ state_inst = _make_default(state)
212
+ try:
213
+ ret = _get_ops(state_inst,
214
+ _make_set(state_mapping[state]), **options)
215
+ except (NotImplementedError, TypeError):
216
+ ret = state_mapping[state]
217
+ elif type(state) in state_mapping:
218
+ ret = _get_ops(state,
219
+ _make_set(state_mapping[type(state)]), **options)
220
+ elif isinstance(state, BraBase) and state.dual_class() in state_mapping:
221
+ ret = _get_ops(state,
222
+ _make_set(state_mapping[state.dual_class()]))
223
+ elif issubclass(state, BraBase) and state.dual_class() in state_mapping:
224
+ state_inst = _make_default(state)
225
+ try:
226
+ ret = _get_ops(state_inst,
227
+ _make_set(state_mapping[state.dual_class()]))
228
+ except (NotImplementedError, TypeError):
229
+ ret = state_mapping[state.dual_class()]
230
+ else:
231
+ ret = None
232
+
233
+ return _make_set(ret)
234
+
235
+
236
+ def _make_default(expr):
237
+ # XXX: Catching TypeError like this is a bad way of distinguishing between
238
+ # classes and instances. The logic using this function should be rewritten
239
+ # somehow.
240
+ try:
241
+ ret = expr()
242
+ except TypeError:
243
+ ret = expr
244
+
245
+ return ret
246
+
247
+
248
+ def _get_state(state_class, ops, **options):
249
+ # Try to get a state instance from the operator INSTANCES.
250
+ # If this fails, get the class
251
+ try:
252
+ ret = state_class._operators_to_state(ops, **options)
253
+ except NotImplementedError:
254
+ ret = _make_default(state_class)
255
+
256
+ return ret
257
+
258
+
259
+ def _get_ops(state_inst, op_classes, **options):
260
+ # Try to get operator instances from the state INSTANCE.
261
+ # If this fails, just return the classes
262
+ try:
263
+ ret = state_inst._state_to_operators(op_classes, **options)
264
+ except NotImplementedError:
265
+ if isinstance(op_classes, (set, tuple, frozenset)):
266
+ ret = tuple(_make_default(x) for x in op_classes)
267
+ else:
268
+ ret = _make_default(op_classes)
269
+
270
+ if isinstance(ret, set) and len(ret) == 1:
271
+ return ret[0]
272
+
273
+ return ret
274
+
275
+
276
+ def _make_set(ops):
277
+ if isinstance(ops, (tuple, list, frozenset)):
278
+ return set(ops)
279
+ else:
280
+ return ops
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/piab.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """1D quantum particle in a box."""
2
+
3
+ from sympy.core.numbers import pi
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.trigonometric import sin
8
+ from sympy.sets.sets import Interval
9
+
10
+ from sympy.physics.quantum.operator import HermitianOperator
11
+ from sympy.physics.quantum.state import Ket, Bra
12
+ from sympy.physics.quantum.constants import hbar
13
+ from sympy.functions.special.tensor_functions import KroneckerDelta
14
+ from sympy.physics.quantum.hilbert import L2
15
+
16
+ m = Symbol('m')
17
+ L = Symbol('L')
18
+
19
+
20
+ __all__ = [
21
+ 'PIABHamiltonian',
22
+ 'PIABKet',
23
+ 'PIABBra'
24
+ ]
25
+
26
+
27
+ class PIABHamiltonian(HermitianOperator):
28
+ """Particle in a box Hamiltonian operator."""
29
+
30
+ @classmethod
31
+ def _eval_hilbert_space(cls, label):
32
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
33
+
34
+ def _apply_operator_PIABKet(self, ket, **options):
35
+ n = ket.label[0]
36
+ return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket
37
+
38
+
39
+ class PIABKet(Ket):
40
+ """Particle in a box eigenket."""
41
+
42
+ @classmethod
43
+ def _eval_hilbert_space(cls, args):
44
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
45
+
46
+ @classmethod
47
+ def dual_class(self):
48
+ return PIABBra
49
+
50
+ def _represent_default_basis(self, **options):
51
+ return self._represent_XOp(None, **options)
52
+
53
+ def _represent_XOp(self, basis, **options):
54
+ x = Symbol('x')
55
+ n = Symbol('n')
56
+ subs_info = options.get('subs', {})
57
+ return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info)
58
+
59
+ def _eval_innerproduct_PIABBra(self, bra):
60
+ return KroneckerDelta(bra.label[0], self.label[0])
61
+
62
+
63
+ class PIABBra(Bra):
64
+ """Particle in a box eigenbra."""
65
+
66
+ @classmethod
67
+ def _eval_hilbert_space(cls, label):
68
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
69
+
70
+ @classmethod
71
+ def dual_class(self):
72
+ return PIABKet
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/qasm.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ qasm.py - Functions to parse a set of qasm commands into a SymPy Circuit.
4
+
5
+ Examples taken from Chuang's page: https://web.archive.org/web/20220120121541/https://www.media.mit.edu/quanta/qasm2circ/
6
+
7
+ The code returns a circuit and an associated list of labels.
8
+
9
+ >>> from sympy.physics.quantum.qasm import Qasm
10
+ >>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
11
+ >>> q.get_circuit()
12
+ CNOT(1,0)*H(1)
13
+
14
+ >>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
15
+ >>> q.get_circuit()
16
+ CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
17
+ """
18
+
19
+ __all__ = [
20
+ 'Qasm',
21
+ ]
22
+
23
+ from math import prod
24
+
25
+ from sympy.physics.quantum.gate import H, CNOT, X, Z, CGate, CGateS, SWAP, S, T,CPHASE
26
+ from sympy.physics.quantum.circuitplot import Mz
27
+
28
+ def read_qasm(lines):
29
+ return Qasm(*lines.splitlines())
30
+
31
+ def read_qasm_file(filename):
32
+ return Qasm(*open(filename).readlines())
33
+
34
+ def flip_index(i, n):
35
+ """Reorder qubit indices from largest to smallest.
36
+
37
+ >>> from sympy.physics.quantum.qasm import flip_index
38
+ >>> flip_index(0, 2)
39
+ 1
40
+ >>> flip_index(1, 2)
41
+ 0
42
+ """
43
+ return n-i-1
44
+
45
+ def trim(line):
46
+ """Remove everything following comment # characters in line.
47
+
48
+ >>> from sympy.physics.quantum.qasm import trim
49
+ >>> trim('nothing happens here')
50
+ 'nothing happens here'
51
+ >>> trim('something #happens here')
52
+ 'something '
53
+ """
54
+ if '#' not in line:
55
+ return line
56
+ return line.split('#')[0]
57
+
58
+ def get_index(target, labels):
59
+ """Get qubit labels from the rest of the line,and return indices
60
+
61
+ >>> from sympy.physics.quantum.qasm import get_index
62
+ >>> get_index('q0', ['q0', 'q1'])
63
+ 1
64
+ >>> get_index('q1', ['q0', 'q1'])
65
+ 0
66
+ """
67
+ nq = len(labels)
68
+ return flip_index(labels.index(target), nq)
69
+
70
+ def get_indices(targets, labels):
71
+ return [get_index(t, labels) for t in targets]
72
+
73
+ def nonblank(args):
74
+ for line in args:
75
+ line = trim(line)
76
+ if line.isspace():
77
+ continue
78
+ yield line
79
+ return
80
+
81
+ def fullsplit(line):
82
+ words = line.split()
83
+ rest = ' '.join(words[1:])
84
+ return fixcommand(words[0]), [s.strip() for s in rest.split(',')]
85
+
86
+ def fixcommand(c):
87
+ """Fix Qasm command names.
88
+
89
+ Remove all of forbidden characters from command c, and
90
+ replace 'def' with 'qdef'.
91
+ """
92
+ forbidden_characters = ['-']
93
+ c = c.lower()
94
+ for char in forbidden_characters:
95
+ c = c.replace(char, '')
96
+ if c == 'def':
97
+ return 'qdef'
98
+ return c
99
+
100
+ def stripquotes(s):
101
+ """Replace explicit quotes in a string.
102
+
103
+ >>> from sympy.physics.quantum.qasm import stripquotes
104
+ >>> stripquotes("'S'") == 'S'
105
+ True
106
+ >>> stripquotes('"S"') == 'S'
107
+ True
108
+ >>> stripquotes('S') == 'S'
109
+ True
110
+ """
111
+ s = s.replace('"', '') # Remove second set of quotes?
112
+ s = s.replace("'", '')
113
+ return s
114
+
115
+ class Qasm:
116
+ """Class to form objects from Qasm lines
117
+
118
+ >>> from sympy.physics.quantum.qasm import Qasm
119
+ >>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
120
+ >>> q.get_circuit()
121
+ CNOT(1,0)*H(1)
122
+ >>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
123
+ >>> q.get_circuit()
124
+ CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
125
+ """
126
+ def __init__(self, *args, **kwargs):
127
+ self.defs = {}
128
+ self.circuit = []
129
+ self.labels = []
130
+ self.inits = {}
131
+ self.add(*args)
132
+ self.kwargs = kwargs
133
+
134
+ def add(self, *lines):
135
+ for line in nonblank(lines):
136
+ command, rest = fullsplit(line)
137
+ if self.defs.get(command): #defs come first, since you can override built-in
138
+ function = self.defs.get(command)
139
+ indices = self.indices(rest)
140
+ if len(indices) == 1:
141
+ self.circuit.append(function(indices[0]))
142
+ else:
143
+ self.circuit.append(function(indices[:-1], indices[-1]))
144
+ elif hasattr(self, command):
145
+ function = getattr(self, command)
146
+ function(*rest)
147
+ else:
148
+ print("Function %s not defined. Skipping" % command)
149
+
150
+ def get_circuit(self):
151
+ return prod(reversed(self.circuit))
152
+
153
+ def get_labels(self):
154
+ return list(reversed(self.labels))
155
+
156
+ def plot(self):
157
+ from sympy.physics.quantum.circuitplot import CircuitPlot
158
+ circuit, labels = self.get_circuit(), self.get_labels()
159
+ CircuitPlot(circuit, len(labels), labels=labels, inits=self.inits)
160
+
161
+ def qubit(self, arg, init=None):
162
+ self.labels.append(arg)
163
+ if init: self.inits[arg] = init
164
+
165
+ def indices(self, args):
166
+ return get_indices(args, self.labels)
167
+
168
+ def index(self, arg):
169
+ return get_index(arg, self.labels)
170
+
171
+ def nop(self, *args):
172
+ pass
173
+
174
+ def x(self, arg):
175
+ self.circuit.append(X(self.index(arg)))
176
+
177
+ def z(self, arg):
178
+ self.circuit.append(Z(self.index(arg)))
179
+
180
+ def h(self, arg):
181
+ self.circuit.append(H(self.index(arg)))
182
+
183
+ def s(self, arg):
184
+ self.circuit.append(S(self.index(arg)))
185
+
186
+ def t(self, arg):
187
+ self.circuit.append(T(self.index(arg)))
188
+
189
+ def measure(self, arg):
190
+ self.circuit.append(Mz(self.index(arg)))
191
+
192
+ def cnot(self, a1, a2):
193
+ self.circuit.append(CNOT(*self.indices([a1, a2])))
194
+
195
+ def swap(self, a1, a2):
196
+ self.circuit.append(SWAP(*self.indices([a1, a2])))
197
+
198
+ def cphase(self, a1, a2):
199
+ self.circuit.append(CPHASE(*self.indices([a1, a2])))
200
+
201
+ def toffoli(self, a1, a2, a3):
202
+ i1, i2, i3 = self.indices([a1, a2, a3])
203
+ self.circuit.append(CGateS((i1, i2), X(i3)))
204
+
205
+ def cx(self, a1, a2):
206
+ fi, fj = self.indices([a1, a2])
207
+ self.circuit.append(CGate(fi, X(fj)))
208
+
209
+ def cz(self, a1, a2):
210
+ fi, fj = self.indices([a1, a2])
211
+ self.circuit.append(CGate(fi, Z(fj)))
212
+
213
+ def defbox(self, *args):
214
+ print("defbox not supported yet. Skipping: ", args)
215
+
216
+ def qdef(self, name, ncontrols, symbol):
217
+ from sympy.physics.quantum.circuitplot import CreateOneQubitGate, CreateCGate
218
+ ncontrols = int(ncontrols)
219
+ command = fixcommand(name)
220
+ symbol = stripquotes(symbol)
221
+ if ncontrols > 0:
222
+ self.defs[command] = CreateCGate(symbol)
223
+ else:
224
+ self.defs[command] = CreateOneQubitGate(symbol)
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/represent.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic for representing operators in state in various bases.
2
+
3
+ TODO:
4
+
5
+ * Get represent working with continuous hilbert spaces.
6
+ * Document default basis functionality.
7
+ """
8
+
9
+ from sympy.core.add import Add
10
+ from sympy.core.expr import Expr
11
+ from sympy.core.mul import Mul
12
+ from sympy.core.numbers import I
13
+ from sympy.core.power import Pow
14
+ from sympy.integrals.integrals import integrate
15
+ from sympy.physics.quantum.dagger import Dagger
16
+ from sympy.physics.quantum.commutator import Commutator
17
+ from sympy.physics.quantum.anticommutator import AntiCommutator
18
+ from sympy.physics.quantum.innerproduct import InnerProduct
19
+ from sympy.physics.quantum.qexpr import QExpr
20
+ from sympy.physics.quantum.tensorproduct import TensorProduct
21
+ from sympy.physics.quantum.matrixutils import flatten_scalar
22
+ from sympy.physics.quantum.state import KetBase, BraBase, StateBase
23
+ from sympy.physics.quantum.operator import Operator, OuterProduct
24
+ from sympy.physics.quantum.qapply import qapply
25
+ from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators
26
+
27
+ __all__ = [
28
+ 'represent',
29
+ 'rep_innerproduct',
30
+ 'rep_expectation',
31
+ 'integrate_result',
32
+ 'get_basis',
33
+ 'enumerate_states'
34
+ ]
35
+
36
+ #-----------------------------------------------------------------------------
37
+ # Represent
38
+ #-----------------------------------------------------------------------------
39
+
40
+
41
+ def _sympy_to_scalar(e):
42
+ """Convert from a SymPy scalar to a Python scalar."""
43
+ if isinstance(e, Expr):
44
+ if e.is_Integer:
45
+ return int(e)
46
+ elif e.is_Float:
47
+ return float(e)
48
+ elif e.is_Rational:
49
+ return float(e)
50
+ elif e.is_Number or e.is_NumberSymbol or e == I:
51
+ return complex(e)
52
+ raise TypeError('Expected number, got: %r' % e)
53
+
54
+
55
+ def represent(expr, **options):
56
+ """Represent the quantum expression in the given basis.
57
+
58
+ In quantum mechanics abstract states and operators can be represented in
59
+ various basis sets. Under this operation the follow transforms happen:
60
+
61
+ * Ket -> column vector or function
62
+ * Bra -> row vector of function
63
+ * Operator -> matrix or differential operator
64
+
65
+ This function is the top-level interface for this action.
66
+
67
+ This function walks the SymPy expression tree looking for ``QExpr``
68
+ instances that have a ``_represent`` method. This method is then called
69
+ and the object is replaced by the representation returned by this method.
70
+ By default, the ``_represent`` method will dispatch to other methods
71
+ that handle the representation logic for a particular basis set. The
72
+ naming convention for these methods is the following::
73
+
74
+ def _represent_FooBasis(self, e, basis, **options)
75
+
76
+ This function will have the logic for representing instances of its class
77
+ in the basis set having a class named ``FooBasis``.
78
+
79
+ Parameters
80
+ ==========
81
+
82
+ expr : Expr
83
+ The expression to represent.
84
+ basis : Operator, basis set
85
+ An object that contains the information about the basis set. If an
86
+ operator is used, the basis is assumed to be the orthonormal
87
+ eigenvectors of that operator. In general though, the basis argument
88
+ can be any object that contains the basis set information.
89
+ options : dict
90
+ Key/value pairs of options that are passed to the underlying method
91
+ that finds the representation. These options can be used to
92
+ control how the representation is done. For example, this is where
93
+ the size of the basis set would be set.
94
+
95
+ Returns
96
+ =======
97
+
98
+ e : Expr
99
+ The SymPy expression of the represented quantum expression.
100
+
101
+ Examples
102
+ ========
103
+
104
+ Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator
105
+ and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp``
106
+ method, the ket can be represented in the z-spin basis.
107
+
108
+ >>> from sympy.physics.quantum import Operator, represent, Ket
109
+ >>> from sympy import Matrix
110
+
111
+ >>> class SzUpKet(Ket):
112
+ ... def _represent_SzOp(self, basis, **options):
113
+ ... return Matrix([1,0])
114
+ ...
115
+ >>> class SzOp(Operator):
116
+ ... pass
117
+ ...
118
+ >>> sz = SzOp('Sz')
119
+ >>> up = SzUpKet('up')
120
+ >>> represent(up, basis=sz)
121
+ Matrix([
122
+ [1],
123
+ [0]])
124
+
125
+ Here we see an example of representations in a continuous
126
+ basis. We see that the result of representing various combinations
127
+ of cartesian position operators and kets give us continuous
128
+ expressions involving DiracDelta functions.
129
+
130
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra
131
+ >>> X = XOp()
132
+ >>> x = XKet()
133
+ >>> y = XBra('y')
134
+ >>> represent(X*x)
135
+ x*DiracDelta(x - x_2)
136
+ >>> represent(X*x*y)
137
+ x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
138
+
139
+ """
140
+
141
+ format = options.get('format', 'sympy')
142
+ if format == 'numpy':
143
+ import numpy as np
144
+ if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct):
145
+ options['replace_none'] = False
146
+ temp_basis = get_basis(expr, **options)
147
+ if temp_basis is not None:
148
+ options['basis'] = temp_basis
149
+ try:
150
+ return expr._represent(**options)
151
+ except NotImplementedError as strerr:
152
+ #If no _represent_FOO method exists, map to the
153
+ #appropriate basis state and try
154
+ #the other methods of representation
155
+ options['replace_none'] = True
156
+
157
+ if isinstance(expr, (KetBase, BraBase)):
158
+ try:
159
+ return rep_innerproduct(expr, **options)
160
+ except NotImplementedError:
161
+ raise NotImplementedError(strerr)
162
+ elif isinstance(expr, Operator):
163
+ try:
164
+ return rep_expectation(expr, **options)
165
+ except NotImplementedError:
166
+ raise NotImplementedError(strerr)
167
+ else:
168
+ raise NotImplementedError(strerr)
169
+ elif isinstance(expr, Add):
170
+ result = represent(expr.args[0], **options)
171
+ for args in expr.args[1:]:
172
+ # scipy.sparse doesn't support += so we use plain = here.
173
+ result = result + represent(args, **options)
174
+ return result
175
+ elif isinstance(expr, Pow):
176
+ base, exp = expr.as_base_exp()
177
+ if format in ('numpy', 'scipy.sparse'):
178
+ exp = _sympy_to_scalar(exp)
179
+ base = represent(base, **options)
180
+ # scipy.sparse doesn't support negative exponents
181
+ # and warns when inverting a matrix in csr format.
182
+ if format == 'scipy.sparse' and exp < 0:
183
+ from scipy.sparse.linalg import inv
184
+ exp = - exp
185
+ base = inv(base.tocsc()).tocsr()
186
+ if format == 'numpy':
187
+ return np.linalg.matrix_power(base, exp)
188
+ return base ** exp
189
+ elif isinstance(expr, TensorProduct):
190
+ new_args = [represent(arg, **options) for arg in expr.args]
191
+ return TensorProduct(*new_args)
192
+ elif isinstance(expr, Dagger):
193
+ return Dagger(represent(expr.args[0], **options))
194
+ elif isinstance(expr, Commutator):
195
+ A = expr.args[0]
196
+ B = expr.args[1]
197
+ return represent(Mul(A, B) - Mul(B, A), **options)
198
+ elif isinstance(expr, AntiCommutator):
199
+ A = expr.args[0]
200
+ B = expr.args[1]
201
+ return represent(Mul(A, B) + Mul(B, A), **options)
202
+ elif isinstance(expr, InnerProduct):
203
+ return represent(Mul(expr.bra, expr.ket), **options)
204
+ elif not isinstance(expr, (Mul, OuterProduct)):
205
+ # For numpy and scipy.sparse, we can only handle numerical prefactors.
206
+ if format in ('numpy', 'scipy.sparse'):
207
+ return _sympy_to_scalar(expr)
208
+ return expr
209
+
210
+ if not isinstance(expr, (Mul, OuterProduct)):
211
+ raise TypeError('Mul expected, got: %r' % expr)
212
+
213
+ if "index" in options:
214
+ options["index"] += 1
215
+ else:
216
+ options["index"] = 1
217
+
218
+ if "unities" not in options:
219
+ options["unities"] = []
220
+
221
+ result = represent(expr.args[-1], **options)
222
+ last_arg = expr.args[-1]
223
+
224
+ for arg in reversed(expr.args[:-1]):
225
+ if isinstance(last_arg, Operator):
226
+ options["index"] += 1
227
+ options["unities"].append(options["index"])
228
+ elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase):
229
+ options["index"] += 1
230
+ elif isinstance(last_arg, KetBase) and isinstance(arg, Operator):
231
+ options["unities"].append(options["index"])
232
+ elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase):
233
+ options["unities"].append(options["index"])
234
+
235
+ next_arg = represent(arg, **options)
236
+ if format == 'numpy' and isinstance(next_arg, np.ndarray):
237
+ # Must use np.matmult to "matrix multiply" two np.ndarray
238
+ result = np.matmul(next_arg, result)
239
+ else:
240
+ result = next_arg*result
241
+ last_arg = arg
242
+
243
+ # All three matrix formats create 1 by 1 matrices when inner products of
244
+ # vectors are taken. In these cases, we simply return a scalar.
245
+ result = flatten_scalar(result)
246
+
247
+ result = integrate_result(expr, result, **options)
248
+
249
+ return result
250
+
251
+
252
+ def rep_innerproduct(expr, **options):
253
+ """
254
+ Returns an innerproduct like representation (e.g. ``<x'|x>``) for the
255
+ given state.
256
+
257
+ Attempts to calculate inner product with a bra from the specified
258
+ basis. Should only be passed an instance of KetBase or BraBase
259
+
260
+ Parameters
261
+ ==========
262
+
263
+ expr : KetBase or BraBase
264
+ The expression to be represented
265
+
266
+ Examples
267
+ ========
268
+
269
+ >>> from sympy.physics.quantum.represent import rep_innerproduct
270
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
271
+ >>> rep_innerproduct(XKet())
272
+ DiracDelta(x - x_1)
273
+ >>> rep_innerproduct(XKet(), basis=PxOp())
274
+ sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi))
275
+ >>> rep_innerproduct(PxKet(), basis=XOp())
276
+ sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi))
277
+
278
+ """
279
+
280
+ if not isinstance(expr, (KetBase, BraBase)):
281
+ raise TypeError("expr passed is not a Bra or Ket")
282
+
283
+ basis = get_basis(expr, **options)
284
+
285
+ if not isinstance(basis, StateBase):
286
+ raise NotImplementedError("Can't form this representation!")
287
+
288
+ if "index" not in options:
289
+ options["index"] = 1
290
+
291
+ basis_kets = enumerate_states(basis, options["index"], 2)
292
+
293
+ if isinstance(expr, BraBase):
294
+ bra = expr
295
+ ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0])
296
+ else:
297
+ bra = (basis_kets[1].dual if basis_kets[0]
298
+ == expr else basis_kets[0].dual)
299
+ ket = expr
300
+
301
+ prod = InnerProduct(bra, ket)
302
+ result = prod.doit()
303
+
304
+ format = options.get('format', 'sympy')
305
+ return expr._format_represent(result, format)
306
+
307
+
308
+ def rep_expectation(expr, **options):
309
+ """
310
+ Returns an ``<x'|A|x>`` type representation for the given operator.
311
+
312
+ Parameters
313
+ ==========
314
+
315
+ expr : Operator
316
+ Operator to be represented in the specified basis
317
+
318
+ Examples
319
+ ========
320
+
321
+ >>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet
322
+ >>> from sympy.physics.quantum.represent import rep_expectation
323
+ >>> rep_expectation(XOp())
324
+ x_1*DiracDelta(x_1 - x_2)
325
+ >>> rep_expectation(XOp(), basis=PxOp())
326
+ <px_2|*X*|px_1>
327
+ >>> rep_expectation(XOp(), basis=PxKet())
328
+ <px_2|*X*|px_1>
329
+
330
+ """
331
+
332
+ if "index" not in options:
333
+ options["index"] = 1
334
+
335
+ if not isinstance(expr, Operator):
336
+ raise TypeError("The passed expression is not an operator")
337
+
338
+ basis_state = get_basis(expr, **options)
339
+
340
+ if basis_state is None or not isinstance(basis_state, StateBase):
341
+ raise NotImplementedError("Could not get basis kets for this operator")
342
+
343
+ basis_kets = enumerate_states(basis_state, options["index"], 2)
344
+
345
+ bra = basis_kets[1].dual
346
+ ket = basis_kets[0]
347
+
348
+ return qapply(bra*expr*ket)
349
+
350
+
351
+ def integrate_result(orig_expr, result, **options):
352
+ """
353
+ Returns the result of integrating over any unities ``(|x><x|)`` in
354
+ the given expression. Intended for integrating over the result of
355
+ representations in continuous bases.
356
+
357
+ This function integrates over any unities that may have been
358
+ inserted into the quantum expression and returns the result.
359
+ It uses the interval of the Hilbert space of the basis state
360
+ passed to it in order to figure out the limits of integration.
361
+ The unities option must be
362
+ specified for this to work.
363
+
364
+ Note: This is mostly used internally by represent(). Examples are
365
+ given merely to show the use cases.
366
+
367
+ Parameters
368
+ ==========
369
+
370
+ orig_expr : quantum expression
371
+ The original expression which was to be represented
372
+
373
+ result: Expr
374
+ The resulting representation that we wish to integrate over
375
+
376
+ Examples
377
+ ========
378
+
379
+ >>> from sympy import symbols, DiracDelta
380
+ >>> from sympy.physics.quantum.represent import integrate_result
381
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet
382
+ >>> x_ket = XKet()
383
+ >>> X_op = XOp()
384
+ >>> x, x_1, x_2 = symbols('x, x_1, x_2')
385
+ >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2))
386
+ x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2)
387
+ >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2),
388
+ ... unities=[1])
389
+ x*DiracDelta(x - x_2)
390
+
391
+ """
392
+ if not isinstance(result, Expr):
393
+ return result
394
+
395
+ options['replace_none'] = True
396
+ if "basis" not in options:
397
+ arg = orig_expr.args[-1]
398
+ options["basis"] = get_basis(arg, **options)
399
+ elif not isinstance(options["basis"], StateBase):
400
+ options["basis"] = get_basis(orig_expr, **options)
401
+
402
+ basis = options.pop("basis", None)
403
+
404
+ if basis is None:
405
+ return result
406
+
407
+ unities = options.pop("unities", [])
408
+
409
+ if len(unities) == 0:
410
+ return result
411
+
412
+ kets = enumerate_states(basis, unities)
413
+ coords = [k.label[0] for k in kets]
414
+
415
+ for coord in coords:
416
+ if coord in result.free_symbols:
417
+ #TODO: Add support for sets of operators
418
+ basis_op = state_to_operators(basis)
419
+ start = basis_op.hilbert_space.interval.start
420
+ end = basis_op.hilbert_space.interval.end
421
+ result = integrate(result, (coord, start, end))
422
+
423
+ return result
424
+
425
+
426
+ def get_basis(expr, *, basis=None, replace_none=True, **options):
427
+ """
428
+ Returns a basis state instance corresponding to the basis specified in
429
+ options=s. If no basis is specified, the function tries to form a default
430
+ basis state of the given expression.
431
+
432
+ There are three behaviors:
433
+
434
+ 1. The basis specified in options is already an instance of StateBase. If
435
+ this is the case, it is simply returned. If the class is specified but
436
+ not an instance, a default instance is returned.
437
+
438
+ 2. The basis specified is an operator or set of operators. If this
439
+ is the case, the operator_to_state mapping method is used.
440
+
441
+ 3. No basis is specified. If expr is a state, then a default instance of
442
+ its class is returned. If expr is an operator, then it is mapped to the
443
+ corresponding state. If it is neither, then we cannot obtain the basis
444
+ state.
445
+
446
+ If the basis cannot be mapped, then it is not changed.
447
+
448
+ This will be called from within represent, and represent will
449
+ only pass QExpr's.
450
+
451
+ TODO (?): Support for Muls and other types of expressions?
452
+
453
+ Parameters
454
+ ==========
455
+
456
+ expr : Operator or StateBase
457
+ Expression whose basis is sought
458
+
459
+ Examples
460
+ ========
461
+
462
+ >>> from sympy.physics.quantum.represent import get_basis
463
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
464
+ >>> x = XKet()
465
+ >>> X = XOp()
466
+ >>> get_basis(x)
467
+ |x>
468
+ >>> get_basis(X)
469
+ |x>
470
+ >>> get_basis(x, basis=PxOp())
471
+ |px>
472
+ >>> get_basis(x, basis=PxKet)
473
+ |px>
474
+
475
+ """
476
+
477
+ if basis is None and not replace_none:
478
+ return None
479
+
480
+ if basis is None:
481
+ if isinstance(expr, KetBase):
482
+ return _make_default(expr.__class__)
483
+ elif isinstance(expr, BraBase):
484
+ return _make_default(expr.dual_class())
485
+ elif isinstance(expr, Operator):
486
+ state_inst = operators_to_state(expr)
487
+ return (state_inst if state_inst is not None else None)
488
+ else:
489
+ return None
490
+ elif (isinstance(basis, Operator) or
491
+ (not isinstance(basis, StateBase) and issubclass(basis, Operator))):
492
+ state = operators_to_state(basis)
493
+ if state is None:
494
+ return None
495
+ elif isinstance(state, StateBase):
496
+ return state
497
+ else:
498
+ return _make_default(state)
499
+ elif isinstance(basis, StateBase):
500
+ return basis
501
+ elif issubclass(basis, StateBase):
502
+ return _make_default(basis)
503
+ else:
504
+ return None
505
+
506
+
507
+ def _make_default(expr):
508
+ # XXX: Catching TypeError like this is a bad way of distinguishing
509
+ # instances from classes. The logic using this function should be
510
+ # rewritten somehow.
511
+ try:
512
+ expr = expr()
513
+ except TypeError:
514
+ return expr
515
+
516
+ return expr
517
+
518
+
519
+ def enumerate_states(*args, **options):
520
+ """
521
+ Returns instances of the given state with dummy indices appended
522
+
523
+ Operates in two different modes:
524
+
525
+ 1. Two arguments are passed to it. The first is the base state which is to
526
+ be indexed, and the second argument is a list of indices to append.
527
+
528
+ 2. Three arguments are passed. The first is again the base state to be
529
+ indexed. The second is the start index for counting. The final argument
530
+ is the number of kets you wish to receive.
531
+
532
+ Tries to call state._enumerate_state. If this fails, returns an empty list
533
+
534
+ Parameters
535
+ ==========
536
+
537
+ args : list
538
+ See list of operation modes above for explanation
539
+
540
+ Examples
541
+ ========
542
+
543
+ >>> from sympy.physics.quantum.cartesian import XBra, XKet
544
+ >>> from sympy.physics.quantum.represent import enumerate_states
545
+ >>> test = XKet('foo')
546
+ >>> enumerate_states(test, 1, 3)
547
+ [|foo_1>, |foo_2>, |foo_3>]
548
+ >>> test2 = XBra('bar')
549
+ >>> enumerate_states(test2, [4, 5, 10])
550
+ [<bar_4|, <bar_5|, <bar_10|]
551
+
552
+ """
553
+
554
+ state = args[0]
555
+
556
+ if len(args) not in (2, 3):
557
+ raise NotImplementedError("Wrong number of arguments!")
558
+
559
+ if not isinstance(state, StateBase):
560
+ raise TypeError("First argument is not a state!")
561
+
562
+ if len(args) == 3:
563
+ num_states = args[2]
564
+ options['start_index'] = args[1]
565
+ else:
566
+ num_states = len(args[1])
567
+ options['index_list'] = args[1]
568
+
569
+ try:
570
+ ret = state._enumerate_state(num_states, **options)
571
+ except NotImplementedError:
572
+ ret = []
573
+
574
+ return ret
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract tensor product."""
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.sympify import sympify
8
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix
9
+ from sympy.printing.pretty.stringpict import prettyForm
10
+
11
+ from sympy.physics.quantum.qexpr import QuantumError
12
+ from sympy.physics.quantum.dagger import Dagger
13
+ from sympy.physics.quantum.commutator import Commutator
14
+ from sympy.physics.quantum.anticommutator import AntiCommutator
15
+ from sympy.physics.quantum.state import Ket, Bra
16
+ from sympy.physics.quantum.matrixutils import (
17
+ numpy_ndarray,
18
+ scipy_sparse_matrix,
19
+ matrix_tensor_product
20
+ )
21
+ from sympy.physics.quantum.trace import Tr
22
+
23
+
24
+ __all__ = [
25
+ 'TensorProduct',
26
+ 'tensor_product_simp'
27
+ ]
28
+
29
+ #-----------------------------------------------------------------------------
30
+ # Tensor product
31
+ #-----------------------------------------------------------------------------
32
+
33
+ _combined_printing = False
34
+
35
+
36
+ def combined_tensor_printing(combined):
37
+ """Set flag controlling whether tensor products of states should be
38
+ printed as a combined bra/ket or as an explicit tensor product of different
39
+ bra/kets. This is a global setting for all TensorProduct class instances.
40
+
41
+ Parameters
42
+ ----------
43
+ combine : bool
44
+ When true, tensor product states are combined into one ket/bra, and
45
+ when false explicit tensor product notation is used between each
46
+ ket/bra.
47
+ """
48
+ global _combined_printing
49
+ _combined_printing = combined
50
+
51
+
52
+ class TensorProduct(Expr):
53
+ """The tensor product of two or more arguments.
54
+
55
+ For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker
56
+ or tensor product matrix. For other objects a symbolic ``TensorProduct``
57
+ instance is returned. The tensor product is a non-commutative
58
+ multiplication that is used primarily with operators and states in quantum
59
+ mechanics.
60
+
61
+ Currently, the tensor product distinguishes between commutative and
62
+ non-commutative arguments. Commutative arguments are assumed to be scalars
63
+ and are pulled out in front of the ``TensorProduct``. Non-commutative
64
+ arguments remain in the resulting ``TensorProduct``.
65
+
66
+ Parameters
67
+ ==========
68
+
69
+ args : tuple
70
+ A sequence of the objects to take the tensor product of.
71
+
72
+ Examples
73
+ ========
74
+
75
+ Start with a simple tensor product of SymPy matrices::
76
+
77
+ >>> from sympy import Matrix
78
+ >>> from sympy.physics.quantum import TensorProduct
79
+
80
+ >>> m1 = Matrix([[1,2],[3,4]])
81
+ >>> m2 = Matrix([[1,0],[0,1]])
82
+ >>> TensorProduct(m1, m2)
83
+ Matrix([
84
+ [1, 0, 2, 0],
85
+ [0, 1, 0, 2],
86
+ [3, 0, 4, 0],
87
+ [0, 3, 0, 4]])
88
+ >>> TensorProduct(m2, m1)
89
+ Matrix([
90
+ [1, 2, 0, 0],
91
+ [3, 4, 0, 0],
92
+ [0, 0, 1, 2],
93
+ [0, 0, 3, 4]])
94
+
95
+ We can also construct tensor products of non-commutative symbols:
96
+
97
+ >>> from sympy import Symbol
98
+ >>> A = Symbol('A',commutative=False)
99
+ >>> B = Symbol('B',commutative=False)
100
+ >>> tp = TensorProduct(A, B)
101
+ >>> tp
102
+ AxB
103
+
104
+ We can take the dagger of a tensor product (note the order does NOT reverse
105
+ like the dagger of a normal product):
106
+
107
+ >>> from sympy.physics.quantum import Dagger
108
+ >>> Dagger(tp)
109
+ Dagger(A)xDagger(B)
110
+
111
+ Expand can be used to distribute a tensor product across addition:
112
+
113
+ >>> C = Symbol('C',commutative=False)
114
+ >>> tp = TensorProduct(A+B,C)
115
+ >>> tp
116
+ (A + B)xC
117
+ >>> tp.expand(tensorproduct=True)
118
+ AxC + BxC
119
+ """
120
+ is_commutative = False
121
+
122
+ def __new__(cls, *args):
123
+ if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)):
124
+ return matrix_tensor_product(*args)
125
+ c_part, new_args = cls.flatten(sympify(args))
126
+ c_part = Mul(*c_part)
127
+ if len(new_args) == 0:
128
+ return c_part
129
+ elif len(new_args) == 1:
130
+ return c_part * new_args[0]
131
+ else:
132
+ tp = Expr.__new__(cls, *new_args)
133
+ return c_part * tp
134
+
135
+ @classmethod
136
+ def flatten(cls, args):
137
+ # TODO: disallow nested TensorProducts.
138
+ c_part = []
139
+ nc_parts = []
140
+ for arg in args:
141
+ cp, ncp = arg.args_cnc()
142
+ c_part.extend(list(cp))
143
+ nc_parts.append(Mul._from_args(ncp))
144
+ return c_part, nc_parts
145
+
146
+ def _eval_adjoint(self):
147
+ return TensorProduct(*[Dagger(i) for i in self.args])
148
+
149
+ def _eval_rewrite(self, rule, args, **hints):
150
+ return TensorProduct(*args).expand(tensorproduct=True)
151
+
152
+ def _sympystr(self, printer, *args):
153
+ length = len(self.args)
154
+ s = ''
155
+ for i in range(length):
156
+ if isinstance(self.args[i], (Add, Pow, Mul)):
157
+ s = s + '('
158
+ s = s + printer._print(self.args[i])
159
+ if isinstance(self.args[i], (Add, Pow, Mul)):
160
+ s = s + ')'
161
+ if i != length - 1:
162
+ s = s + 'x'
163
+ return s
164
+
165
+ def _pretty(self, printer, *args):
166
+
167
+ if (_combined_printing and
168
+ (all(isinstance(arg, Ket) for arg in self.args) or
169
+ all(isinstance(arg, Bra) for arg in self.args))):
170
+
171
+ length = len(self.args)
172
+ pform = printer._print('', *args)
173
+ for i in range(length):
174
+ next_pform = printer._print('', *args)
175
+ length_i = len(self.args[i].args)
176
+ for j in range(length_i):
177
+ part_pform = printer._print(self.args[i].args[j], *args)
178
+ next_pform = prettyForm(*next_pform.right(part_pform))
179
+ if j != length_i - 1:
180
+ next_pform = prettyForm(*next_pform.right(', '))
181
+
182
+ if len(self.args[i].args) > 1:
183
+ next_pform = prettyForm(
184
+ *next_pform.parens(left='{', right='}'))
185
+ pform = prettyForm(*pform.right(next_pform))
186
+ if i != length - 1:
187
+ pform = prettyForm(*pform.right(',' + ' '))
188
+
189
+ pform = prettyForm(*pform.left(self.args[0].lbracket))
190
+ pform = prettyForm(*pform.right(self.args[0].rbracket))
191
+ return pform
192
+
193
+ length = len(self.args)
194
+ pform = printer._print('', *args)
195
+ for i in range(length):
196
+ next_pform = printer._print(self.args[i], *args)
197
+ if isinstance(self.args[i], (Add, Mul)):
198
+ next_pform = prettyForm(
199
+ *next_pform.parens(left='(', right=')')
200
+ )
201
+ pform = prettyForm(*pform.right(next_pform))
202
+ if i != length - 1:
203
+ if printer._use_unicode:
204
+ pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
205
+ else:
206
+ pform = prettyForm(*pform.right('x' + ' '))
207
+ return pform
208
+
209
+ def _latex(self, printer, *args):
210
+
211
+ if (_combined_printing and
212
+ (all(isinstance(arg, Ket) for arg in self.args) or
213
+ all(isinstance(arg, Bra) for arg in self.args))):
214
+
215
+ def _label_wrap(label, nlabels):
216
+ return label if nlabels == 1 else r"\left\{%s\right\}" % label
217
+
218
+ s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args),
219
+ len(arg.args)) for arg in self.args])
220
+
221
+ return r"{%s%s%s}" % (self.args[0].lbracket_latex, s,
222
+ self.args[0].rbracket_latex)
223
+
224
+ length = len(self.args)
225
+ s = ''
226
+ for i in range(length):
227
+ if isinstance(self.args[i], (Add, Mul)):
228
+ s = s + '\\left('
229
+ # The extra {} brackets are needed to get matplotlib's latex
230
+ # rendered to render this properly.
231
+ s = s + '{' + printer._print(self.args[i], *args) + '}'
232
+ if isinstance(self.args[i], (Add, Mul)):
233
+ s = s + '\\right)'
234
+ if i != length - 1:
235
+ s = s + '\\otimes '
236
+ return s
237
+
238
+ def doit(self, **hints):
239
+ return TensorProduct(*[item.doit(**hints) for item in self.args])
240
+
241
+ def _eval_expand_tensorproduct(self, **hints):
242
+ """Distribute TensorProducts across addition."""
243
+ args = self.args
244
+ add_args = []
245
+ for i in range(len(args)):
246
+ if isinstance(args[i], Add):
247
+ for aa in args[i].args:
248
+ tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:])
249
+ c_part, nc_part = tp.args_cnc()
250
+ # Check for TensorProduct object: is the one object in nc_part, if any:
251
+ # (Note: any other object type to be expanded must be added here)
252
+ if len(nc_part) == 1 and isinstance(nc_part[0], TensorProduct):
253
+ nc_part = (nc_part[0]._eval_expand_tensorproduct(), )
254
+ add_args.append(Mul(*c_part)*Mul(*nc_part))
255
+ break
256
+
257
+ if add_args:
258
+ return Add(*add_args)
259
+ else:
260
+ return self
261
+
262
+ def _eval_trace(self, **kwargs):
263
+ indices = kwargs.get('indices', None)
264
+ exp = tensor_product_simp(self)
265
+
266
+ if indices is None or len(indices) == 0:
267
+ return Mul(*[Tr(arg).doit() for arg in exp.args])
268
+ else:
269
+ return Mul(*[Tr(value).doit() if idx in indices else value
270
+ for idx, value in enumerate(exp.args)])
271
+
272
+
273
+ def tensor_product_simp_Mul(e):
274
+ """Simplify a Mul with TensorProducts.
275
+
276
+ Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s
277
+ to a ``TensorProduct`` of ``Muls``. It currently only works for relatively
278
+ simple cases where the initial ``Mul`` only has scalars and raw
279
+ ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of
280
+ ``TensorProduct``s.
281
+
282
+ Parameters
283
+ ==========
284
+
285
+ e : Expr
286
+ A ``Mul`` of ``TensorProduct``s to be simplified.
287
+
288
+ Returns
289
+ =======
290
+
291
+ e : Expr
292
+ A ``TensorProduct`` of ``Mul``s.
293
+
294
+ Examples
295
+ ========
296
+
297
+ This is an example of the type of simplification that this function
298
+ performs::
299
+
300
+ >>> from sympy.physics.quantum.tensorproduct import \
301
+ tensor_product_simp_Mul, TensorProduct
302
+ >>> from sympy import Symbol
303
+ >>> A = Symbol('A',commutative=False)
304
+ >>> B = Symbol('B',commutative=False)
305
+ >>> C = Symbol('C',commutative=False)
306
+ >>> D = Symbol('D',commutative=False)
307
+ >>> e = TensorProduct(A,B)*TensorProduct(C,D)
308
+ >>> e
309
+ AxB*CxD
310
+ >>> tensor_product_simp_Mul(e)
311
+ (A*C)x(B*D)
312
+
313
+ """
314
+ # TODO: This won't work with Muls that have other composites of
315
+ # TensorProducts, like an Add, Commutator, etc.
316
+ # TODO: This only works for the equivalent of single Qbit gates.
317
+ if not isinstance(e, Mul):
318
+ return e
319
+ c_part, nc_part = e.args_cnc()
320
+ n_nc = len(nc_part)
321
+ if n_nc == 0:
322
+ return e
323
+ elif n_nc == 1:
324
+ if isinstance(nc_part[0], Pow):
325
+ return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0])
326
+ return e
327
+ elif e.has(TensorProduct):
328
+ current = nc_part[0]
329
+ if not isinstance(current, TensorProduct):
330
+ if isinstance(current, Pow):
331
+ if isinstance(current.base, TensorProduct):
332
+ current = tensor_product_simp_Pow(current)
333
+ else:
334
+ raise TypeError('TensorProduct expected, got: %r' % current)
335
+ n_terms = len(current.args)
336
+ new_args = list(current.args)
337
+ for next in nc_part[1:]:
338
+ # TODO: check the hilbert spaces of next and current here.
339
+ if isinstance(next, TensorProduct):
340
+ if n_terms != len(next.args):
341
+ raise QuantumError(
342
+ 'TensorProducts of different lengths: %r and %r' %
343
+ (current, next)
344
+ )
345
+ for i in range(len(new_args)):
346
+ new_args[i] = new_args[i] * next.args[i]
347
+ else:
348
+ if isinstance(next, Pow):
349
+ if isinstance(next.base, TensorProduct):
350
+ new_tp = tensor_product_simp_Pow(next)
351
+ for i in range(len(new_args)):
352
+ new_args[i] = new_args[i] * new_tp.args[i]
353
+ else:
354
+ raise TypeError('TensorProduct expected, got: %r' % next)
355
+ else:
356
+ raise TypeError('TensorProduct expected, got: %r' % next)
357
+ current = next
358
+ return Mul(*c_part) * TensorProduct(*new_args)
359
+ elif e.has(Pow):
360
+ new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ]
361
+ return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args))
362
+ else:
363
+ return e
364
+
365
+ def tensor_product_simp_Pow(e):
366
+ """Evaluates ``Pow`` expressions whose base is ``TensorProduct``"""
367
+ if not isinstance(e, Pow):
368
+ return e
369
+
370
+ if isinstance(e.base, TensorProduct):
371
+ return TensorProduct(*[ b**e.exp for b in e.base.args])
372
+ else:
373
+ return e
374
+
375
+ def tensor_product_simp(e, **hints):
376
+ """Try to simplify and combine TensorProducts.
377
+
378
+ In general this will try to pull expressions inside of ``TensorProducts``.
379
+ It currently only works for relatively simple cases where the products have
380
+ only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
381
+ of ``TensorProducts``. It is best to see what it does by showing examples.
382
+
383
+ Examples
384
+ ========
385
+
386
+ >>> from sympy.physics.quantum import tensor_product_simp
387
+ >>> from sympy.physics.quantum import TensorProduct
388
+ >>> from sympy import Symbol
389
+ >>> A = Symbol('A',commutative=False)
390
+ >>> B = Symbol('B',commutative=False)
391
+ >>> C = Symbol('C',commutative=False)
392
+ >>> D = Symbol('D',commutative=False)
393
+
394
+ First see what happens to products of tensor products:
395
+
396
+ >>> e = TensorProduct(A,B)*TensorProduct(C,D)
397
+ >>> e
398
+ AxB*CxD
399
+ >>> tensor_product_simp(e)
400
+ (A*C)x(B*D)
401
+
402
+ This is the core logic of this function, and it works inside, powers, sums,
403
+ commutators and anticommutators as well:
404
+
405
+ >>> tensor_product_simp(e**2)
406
+ (A*C)x(B*D)**2
407
+
408
+ """
409
+ if isinstance(e, Add):
410
+ return Add(*[tensor_product_simp(arg) for arg in e.args])
411
+ elif isinstance(e, Pow):
412
+ if isinstance(e.base, TensorProduct):
413
+ return tensor_product_simp_Pow(e)
414
+ else:
415
+ return tensor_product_simp(e.base) ** e.exp
416
+ elif isinstance(e, Mul):
417
+ return tensor_product_simp_Mul(e)
418
+ elif isinstance(e, Commutator):
419
+ return Commutator(*[tensor_product_simp(arg) for arg in e.args])
420
+ elif isinstance(e, AntiCommutator):
421
+ return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])
422
+ else:
423
+ return e
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (200 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc ADDED
Binary file (2.36 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_boson.cpython-310.pyc ADDED
Binary file (1.71 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cartesian.cpython-310.pyc ADDED
Binary file (3.91 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cg.cpython-310.pyc ADDED
Binary file (7.04 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitplot.cpython-310.pyc ADDED
Binary file (2.81 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc ADDED
Binary file (3.46 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_dagger.cpython-310.pyc ADDED
Binary file (2.94 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_density.cpython-310.pyc ADDED
Binary file (8.47 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_grover.cpython-310.pyc ADDED
Binary file (3.46 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_hilbert.cpython-310.pyc ADDED
Binary file (2.94 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_matrixutils.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorset.cpython-310.pyc ADDED
Binary file (2.52 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_pauli.cpython-310.pyc ADDED
Binary file (5.32 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_piab.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qapply.cpython-310.pyc ADDED
Binary file (6.36 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qft.cpython-310.pyc ADDED
Binary file (2.57 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qubit.cpython-310.pyc ADDED
Binary file (7.99 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc ADDED
Binary file (6.09 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_sho1d.cpython-310.pyc ADDED
Binary file (4.98 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_shor.cpython-310.pyc ADDED
Binary file (1.04 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc ADDED
Binary file (200 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_state.cpython-310.pyc ADDED
Binary file (7.26 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_tensorproduct.cpython-310.pyc ADDED
Binary file (4.42 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_anticommutator.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Integer
2
+ from sympy.core.symbol import symbols
3
+
4
+ from sympy.physics.quantum.dagger import Dagger
5
+ from sympy.physics.quantum.anticommutator import AntiCommutator as AComm
6
+ from sympy.physics.quantum.operator import Operator
7
+
8
+
9
+ a, b, c = symbols('a,b,c')
10
+ A, B, C, D = symbols('A,B,C,D', commutative=False)
11
+
12
+
13
+ def test_anticommutator():
14
+ ac = AComm(A, B)
15
+ assert isinstance(ac, AComm)
16
+ assert ac.is_commutative is False
17
+ assert ac.subs(A, C) == AComm(C, B)
18
+
19
+
20
+ def test_commutator_identities():
21
+ assert AComm(a*A, b*B) == a*b*AComm(A, B)
22
+ assert AComm(A, A) == 2*A**2
23
+ assert AComm(A, B) == AComm(B, A)
24
+ assert AComm(a, b) == 2*a*b
25
+ assert AComm(A, B).doit() == A*B + B*A
26
+
27
+
28
+ def test_anticommutator_dagger():
29
+ assert Dagger(AComm(A, B)) == AComm(Dagger(A), Dagger(B))
30
+
31
+
32
+ class Foo(Operator):
33
+
34
+ def _eval_anticommutator_Bar(self, bar):
35
+ return Integer(0)
36
+
37
+
38
+ class Bar(Operator):
39
+ pass
40
+
41
+
42
+ class Tam(Operator):
43
+
44
+ def _eval_anticommutator_Foo(self, foo):
45
+ return Integer(1)
46
+
47
+
48
+ def test_eval_commutator():
49
+ F = Foo('F')
50
+ B = Bar('B')
51
+ T = Tam('T')
52
+ assert AComm(F, B).doit() == 0
53
+ assert AComm(B, F).doit() == 0
54
+ assert AComm(F, T).doit() == 1
55
+ assert AComm(T, F).doit() == 1
56
+ assert AComm(B, T).doit() == B*T + T*B
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.core.numbers import Rational
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.physics.quantum import Dagger, Commutator, qapply
7
+ from sympy.physics.quantum.boson import BosonOp
8
+ from sympy.physics.quantum.boson import (
9
+ BosonFockKet, BosonFockBra, BosonCoherentKet, BosonCoherentBra)
10
+
11
+
12
+ def test_bosonoperator():
13
+ a = BosonOp('a')
14
+ b = BosonOp('b')
15
+
16
+ assert isinstance(a, BosonOp)
17
+ assert isinstance(Dagger(a), BosonOp)
18
+
19
+ assert a.is_annihilation
20
+ assert not Dagger(a).is_annihilation
21
+
22
+ assert BosonOp("a") == BosonOp("a", True)
23
+ assert BosonOp("a") != BosonOp("c")
24
+ assert BosonOp("a", True) != BosonOp("a", False)
25
+
26
+ assert Commutator(a, Dagger(a)).doit() == 1
27
+
28
+ assert Commutator(a, Dagger(b)).doit() == a * Dagger(b) - Dagger(b) * a
29
+
30
+ assert Dagger(exp(a)) == exp(Dagger(a))
31
+
32
+
33
+ def test_boson_states():
34
+ a = BosonOp("a")
35
+
36
+ # Fock states
37
+ n = 3
38
+ assert (BosonFockBra(0) * BosonFockKet(1)).doit() == 0
39
+ assert (BosonFockBra(1) * BosonFockKet(1)).doit() == 1
40
+ assert qapply(BosonFockBra(n) * Dagger(a)**n * BosonFockKet(0)) \
41
+ == sqrt(prod(range(1, n+1)))
42
+
43
+ # Coherent states
44
+ alpha1, alpha2 = 1.2, 4.3
45
+ assert (BosonCoherentBra(alpha1) * BosonCoherentKet(alpha1)).doit() == 1
46
+ assert (BosonCoherentBra(alpha2) * BosonCoherentKet(alpha2)).doit() == 1
47
+ assert abs((BosonCoherentBra(alpha1) * BosonCoherentKet(alpha2)).doit() -
48
+ exp((alpha1 - alpha2) ** 2 * Rational(-1, 2))) < 1e-12
49
+ assert qapply(a * BosonCoherentKet(alpha1)) == \
50
+ alpha1 * BosonCoherentKet(alpha1)
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for cartesian.py"""
2
+
3
+ from sympy.core.numbers import (I, pi)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import symbols
6
+ from sympy.functions.elementary.exponential import exp
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.functions.special.delta_functions import DiracDelta
9
+ from sympy.sets.sets import Interval
10
+
11
+ from sympy.physics.quantum import qapply, represent, L2, Dagger
12
+ from sympy.physics.quantum import Commutator, hbar
13
+ from sympy.physics.quantum.cartesian import (
14
+ XOp, YOp, ZOp, PxOp, X, Y, Z, Px, XKet, XBra, PxKet, PxBra,
15
+ PositionKet3D, PositionBra3D
16
+ )
17
+ from sympy.physics.quantum.operator import DifferentialOperator
18
+
19
+ x, y, z, x_1, x_2, x_3, y_1, z_1 = symbols('x,y,z,x_1,x_2,x_3,y_1,z_1')
20
+ px, py, px_1, px_2 = symbols('px py px_1 px_2')
21
+
22
+
23
+ def test_x():
24
+ assert X.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
25
+ assert Commutator(X, Px).doit() == I*hbar
26
+ assert qapply(X*XKet(x)) == x*XKet(x)
27
+ assert XKet(x).dual_class() == XBra
28
+ assert XBra(x).dual_class() == XKet
29
+ assert (Dagger(XKet(y))*XKet(x)).doit() == DiracDelta(x - y)
30
+ assert (PxBra(px)*XKet(x)).doit() == \
31
+ exp(-I*x*px/hbar)/sqrt(2*pi*hbar)
32
+ assert represent(XKet(x)) == DiracDelta(x - x_1)
33
+ assert represent(XBra(x)) == DiracDelta(-x + x_1)
34
+ assert XBra(x).position == x
35
+ assert represent(XOp()*XKet()) == x*DiracDelta(x - x_2)
36
+ assert represent(XOp()*XKet()*XBra('y')) == \
37
+ x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
38
+ assert represent(XBra("y")*XKet()) == DiracDelta(x - y)
39
+ assert represent(
40
+ XKet()*XBra()) == DiracDelta(x - x_2) * DiracDelta(x_1 - x)
41
+
42
+ rep_p = represent(XOp(), basis=PxOp)
43
+ assert rep_p == hbar*I*DiracDelta(px_1 - px_2)*DifferentialOperator(px_1)
44
+ assert rep_p == represent(XOp(), basis=PxOp())
45
+ assert rep_p == represent(XOp(), basis=PxKet)
46
+ assert rep_p == represent(XOp(), basis=PxKet())
47
+
48
+ assert represent(XOp()*PxKet(), basis=PxKet) == \
49
+ hbar*I*DiracDelta(px - px_2)*DifferentialOperator(px)
50
+
51
+
52
+ def test_p():
53
+ assert Px.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
54
+ assert qapply(Px*PxKet(px)) == px*PxKet(px)
55
+ assert PxKet(px).dual_class() == PxBra
56
+ assert PxBra(x).dual_class() == PxKet
57
+ assert (Dagger(PxKet(py))*PxKet(px)).doit() == DiracDelta(px - py)
58
+ assert (XBra(x)*PxKet(px)).doit() == \
59
+ exp(I*x*px/hbar)/sqrt(2*pi*hbar)
60
+ assert represent(PxKet(px)) == DiracDelta(px - px_1)
61
+
62
+ rep_x = represent(PxOp(), basis=XOp)
63
+ assert rep_x == -hbar*I*DiracDelta(x_1 - x_2)*DifferentialOperator(x_1)
64
+ assert rep_x == represent(PxOp(), basis=XOp())
65
+ assert rep_x == represent(PxOp(), basis=XKet)
66
+ assert rep_x == represent(PxOp(), basis=XKet())
67
+
68
+ assert represent(PxOp()*XKet(), basis=XKet) == \
69
+ -hbar*I*DiracDelta(x - x_2)*DifferentialOperator(x)
70
+ assert represent(XBra("y")*PxOp()*XKet(), basis=XKet) == \
71
+ -hbar*I*DiracDelta(x - y)*DifferentialOperator(x)
72
+
73
+
74
+ def test_3dpos():
75
+ assert Y.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
76
+ assert Z.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
77
+
78
+ test_ket = PositionKet3D(x, y, z)
79
+ assert qapply(X*test_ket) == x*test_ket
80
+ assert qapply(Y*test_ket) == y*test_ket
81
+ assert qapply(Z*test_ket) == z*test_ket
82
+ assert qapply(X*Y*test_ket) == x*y*test_ket
83
+ assert qapply(X*Y*Z*test_ket) == x*y*z*test_ket
84
+ assert qapply(Y*Z*test_ket) == y*z*test_ket
85
+
86
+ assert PositionKet3D() == test_ket
87
+ assert YOp() == Y
88
+ assert ZOp() == Z
89
+
90
+ assert PositionKet3D.dual_class() == PositionBra3D
91
+ assert PositionBra3D.dual_class() == PositionKet3D
92
+
93
+ other_ket = PositionKet3D(x_1, y_1, z_1)
94
+ assert (Dagger(other_ket)*test_ket).doit() == \
95
+ DiracDelta(x - x_1)*DiracDelta(y - y_1)*DiracDelta(z - z_1)
96
+
97
+ assert test_ket.position_x == x
98
+ assert test_ket.position_y == y
99
+ assert test_ket.position_z == z
100
+ assert other_ket.position_x == x_1
101
+ assert other_ket.position_y == y_1
102
+ assert other_ket.position_z == z_1
103
+
104
+ # TODO: Add tests for representations
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.numbers import Rational
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import symbols
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.physics.quantum.cg import Wigner3j, Wigner6j, Wigner9j, CG, cg_simp
7
+ from sympy.functions.special.tensor_functions import KroneckerDelta
8
+
9
+
10
+ def test_cg_simp_add():
11
+ j, m1, m1p, m2, m2p = symbols('j m1 m1p m2 m2p')
12
+ # Test Varshalovich 8.7.1 Eq 1
13
+ a = CG(S.Half, S.Half, 0, 0, S.Half, S.Half)
14
+ b = CG(S.Half, Rational(-1, 2), 0, 0, S.Half, Rational(-1, 2))
15
+ c = CG(1, 1, 0, 0, 1, 1)
16
+ d = CG(1, 0, 0, 0, 1, 0)
17
+ e = CG(1, -1, 0, 0, 1, -1)
18
+ assert cg_simp(a + b) == 2
19
+ assert cg_simp(c + d + e) == 3
20
+ assert cg_simp(a + b + c + d + e) == 5
21
+ assert cg_simp(a + b + c) == 2 + c
22
+ assert cg_simp(2*a + b) == 2 + a
23
+ assert cg_simp(2*c + d + e) == 3 + c
24
+ assert cg_simp(5*a + 5*b) == 10
25
+ assert cg_simp(5*c + 5*d + 5*e) == 15
26
+ assert cg_simp(-a - b) == -2
27
+ assert cg_simp(-c - d - e) == -3
28
+ assert cg_simp(-6*a - 6*b) == -12
29
+ assert cg_simp(-4*c - 4*d - 4*e) == -12
30
+ a = CG(S.Half, S.Half, j, 0, S.Half, S.Half)
31
+ b = CG(S.Half, Rational(-1, 2), j, 0, S.Half, Rational(-1, 2))
32
+ c = CG(1, 1, j, 0, 1, 1)
33
+ d = CG(1, 0, j, 0, 1, 0)
34
+ e = CG(1, -1, j, 0, 1, -1)
35
+ assert cg_simp(a + b) == 2*KroneckerDelta(j, 0)
36
+ assert cg_simp(c + d + e) == 3*KroneckerDelta(j, 0)
37
+ assert cg_simp(a + b + c + d + e) == 5*KroneckerDelta(j, 0)
38
+ assert cg_simp(a + b + c) == 2*KroneckerDelta(j, 0) + c
39
+ assert cg_simp(2*a + b) == 2*KroneckerDelta(j, 0) + a
40
+ assert cg_simp(2*c + d + e) == 3*KroneckerDelta(j, 0) + c
41
+ assert cg_simp(5*a + 5*b) == 10*KroneckerDelta(j, 0)
42
+ assert cg_simp(5*c + 5*d + 5*e) == 15*KroneckerDelta(j, 0)
43
+ assert cg_simp(-a - b) == -2*KroneckerDelta(j, 0)
44
+ assert cg_simp(-c - d - e) == -3*KroneckerDelta(j, 0)
45
+ assert cg_simp(-6*a - 6*b) == -12*KroneckerDelta(j, 0)
46
+ assert cg_simp(-4*c - 4*d - 4*e) == -12*KroneckerDelta(j, 0)
47
+ # Test Varshalovich 8.7.1 Eq 2
48
+ a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)
49
+ b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
50
+ c = CG(1, 1, 1, -1, 0, 0)
51
+ d = CG(1, 0, 1, 0, 0, 0)
52
+ e = CG(1, -1, 1, 1, 0, 0)
53
+ assert cg_simp(a - b) == sqrt(2)
54
+ assert cg_simp(c - d + e) == sqrt(3)
55
+ assert cg_simp(a - b + c - d + e) == sqrt(2) + sqrt(3)
56
+ assert cg_simp(a - b + c) == sqrt(2) + c
57
+ assert cg_simp(2*a - b) == sqrt(2) + a
58
+ assert cg_simp(2*c - d + e) == sqrt(3) + c
59
+ assert cg_simp(5*a - 5*b) == 5*sqrt(2)
60
+ assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)
61
+ assert cg_simp(-a + b) == -sqrt(2)
62
+ assert cg_simp(-c + d - e) == -sqrt(3)
63
+ assert cg_simp(-6*a + 6*b) == -6*sqrt(2)
64
+ assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)
65
+ a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), j, 0)
66
+ b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, j, 0)
67
+ c = CG(1, 1, 1, -1, j, 0)
68
+ d = CG(1, 0, 1, 0, j, 0)
69
+ e = CG(1, -1, 1, 1, j, 0)
70
+ assert cg_simp(a - b) == sqrt(2)*KroneckerDelta(j, 0)
71
+ assert cg_simp(c - d + e) == sqrt(3)*KroneckerDelta(j, 0)
72
+ assert cg_simp(a - b + c - d + e) == sqrt(
73
+ 2)*KroneckerDelta(j, 0) + sqrt(3)*KroneckerDelta(j, 0)
74
+ assert cg_simp(a - b + c) == sqrt(2)*KroneckerDelta(j, 0) + c
75
+ assert cg_simp(2*a - b) == sqrt(2)*KroneckerDelta(j, 0) + a
76
+ assert cg_simp(2*c - d + e) == sqrt(3)*KroneckerDelta(j, 0) + c
77
+ assert cg_simp(5*a - 5*b) == 5*sqrt(2)*KroneckerDelta(j, 0)
78
+ assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)*KroneckerDelta(j, 0)
79
+ assert cg_simp(-a + b) == -sqrt(2)*KroneckerDelta(j, 0)
80
+ assert cg_simp(-c + d - e) == -sqrt(3)*KroneckerDelta(j, 0)
81
+ assert cg_simp(-6*a + 6*b) == -6*sqrt(2)*KroneckerDelta(j, 0)
82
+ assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)*KroneckerDelta(j, 0)
83
+ # Test Varshalovich 8.7.2 Eq 9
84
+ # alpha=alphap,beta=betap case
85
+ # numerical
86
+ a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0)**2
87
+ b = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)**2
88
+ c = CG(1, 0, 1, 1, 1, 1)**2
89
+ d = CG(1, 0, 1, 1, 2, 1)**2
90
+ assert cg_simp(a + b) == 1
91
+ assert cg_simp(c + d) == 1
92
+ assert cg_simp(a + b + c + d) == 2
93
+ assert cg_simp(4*a + 4*b) == 4
94
+ assert cg_simp(4*c + 4*d) == 4
95
+ assert cg_simp(5*a + 3*b) == 3 + 2*a
96
+ assert cg_simp(5*c + 3*d) == 3 + 2*c
97
+ assert cg_simp(-a - b) == -1
98
+ assert cg_simp(-c - d) == -1
99
+ # symbolic
100
+ a = CG(S.Half, m1, S.Half, m2, 1, 1)**2
101
+ b = CG(S.Half, m1, S.Half, m2, 1, 0)**2
102
+ c = CG(S.Half, m1, S.Half, m2, 1, -1)**2
103
+ d = CG(S.Half, m1, S.Half, m2, 0, 0)**2
104
+ assert cg_simp(a + b + c + d) == 1
105
+ assert cg_simp(4*a + 4*b + 4*c + 4*d) == 4
106
+ assert cg_simp(3*a + 5*b + 3*c + 4*d) == 3 + 2*b + d
107
+ assert cg_simp(-a - b - c - d) == -1
108
+ a = CG(1, m1, 1, m2, 2, 2)**2
109
+ b = CG(1, m1, 1, m2, 2, 1)**2
110
+ c = CG(1, m1, 1, m2, 2, 0)**2
111
+ d = CG(1, m1, 1, m2, 2, -1)**2
112
+ e = CG(1, m1, 1, m2, 2, -2)**2
113
+ f = CG(1, m1, 1, m2, 1, 1)**2
114
+ g = CG(1, m1, 1, m2, 1, 0)**2
115
+ h = CG(1, m1, 1, m2, 1, -1)**2
116
+ i = CG(1, m1, 1, m2, 0, 0)**2
117
+ assert cg_simp(a + b + c + d + e + f + g + h + i) == 1
118
+ assert cg_simp(4*(a + b + c + d + e + f + g + h + i)) == 4
119
+ assert cg_simp(a + b + 2*c + d + 4*e + f + g + h + i) == 1 + c + 3*e
120
+ assert cg_simp(-a - b - c - d - e - f - g - h - i) == -1
121
+ # alpha!=alphap or beta!=betap case
122
+ # numerical
123
+ a = CG(S.Half, S(
124
+ 1)/2, S.Half, Rational(-1, 2), 1, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 1, 0)
125
+ b = CG(S.Half, S(
126
+ 1)/2, S.Half, Rational(-1, 2), 0, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
127
+ c = CG(1, 1, 1, 0, 2, 1)*CG(1, 0, 1, 1, 2, 1)
128
+ d = CG(1, 1, 1, 0, 1, 1)*CG(1, 0, 1, 1, 1, 1)
129
+ assert cg_simp(a + b) == 0
130
+ assert cg_simp(c + d) == 0
131
+ # symbolic
132
+ a = CG(S.Half, m1, S.Half, m2, 1, 1)*CG(S.Half, m1p, S.Half, m2p, 1, 1)
133
+ b = CG(S.Half, m1, S.Half, m2, 1, 0)*CG(S.Half, m1p, S.Half, m2p, 1, 0)
134
+ c = CG(S.Half, m1, S.Half, m2, 1, -1)*CG(S.Half, m1p, S.Half, m2p, 1, -1)
135
+ d = CG(S.Half, m1, S.Half, m2, 0, 0)*CG(S.Half, m1p, S.Half, m2p, 0, 0)
136
+ assert cg_simp(a + b + c + d) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
137
+ a = CG(1, m1, 1, m2, 2, 2)*CG(1, m1p, 1, m2p, 2, 2)
138
+ b = CG(1, m1, 1, m2, 2, 1)*CG(1, m1p, 1, m2p, 2, 1)
139
+ c = CG(1, m1, 1, m2, 2, 0)*CG(1, m1p, 1, m2p, 2, 0)
140
+ d = CG(1, m1, 1, m2, 2, -1)*CG(1, m1p, 1, m2p, 2, -1)
141
+ e = CG(1, m1, 1, m2, 2, -2)*CG(1, m1p, 1, m2p, 2, -2)
142
+ f = CG(1, m1, 1, m2, 1, 1)*CG(1, m1p, 1, m2p, 1, 1)
143
+ g = CG(1, m1, 1, m2, 1, 0)*CG(1, m1p, 1, m2p, 1, 0)
144
+ h = CG(1, m1, 1, m2, 1, -1)*CG(1, m1p, 1, m2p, 1, -1)
145
+ i = CG(1, m1, 1, m2, 0, 0)*CG(1, m1p, 1, m2p, 0, 0)
146
+ assert cg_simp(
147
+ a + b + c + d + e + f + g + h + i) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
148
+
149
+
150
+ def test_cg_simp_sum():
151
+ x, a, b, c, cp, alpha, beta, gamma, gammap = symbols(
152
+ 'x a b c cp alpha beta gamma gammap')
153
+ # Varshalovich 8.7.1 Eq 1
154
+ assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)
155
+ )) == x*(2*a + 1)*KroneckerDelta(b, 0)
156
+ assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)) + CG(1, 0, 1, 0, 1, 0)) == x*(2*a + 1)*KroneckerDelta(b, 0) + CG(1, 0, 1, 0, 1, 0)
157
+ assert cg_simp(2 * Sum(CG(1, alpha, 0, 0, 1, alpha), (alpha, -1, 1))) == 6
158
+ # Varshalovich 8.7.1 Eq 2
159
+ assert cg_simp(x*Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c,
160
+ 0), (alpha, -a, a))) == x*sqrt(2*a + 1)*KroneckerDelta(c, 0)
161
+ assert cg_simp(3*Sum((-1)**(2 - alpha) * CG(
162
+ 2, alpha, 2, -alpha, 0, 0), (alpha, -2, 2))) == 3*sqrt(5)
163
+ # Varshalovich 8.7.2 Eq 4
164
+ assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)
165
+ assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, c, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(gamma, gammap)
166
+ assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gamma), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)
167
+ assert cg_simp(Sum(CG(
168
+ a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) == 1
169
+ assert cg_simp(Sum(CG(2, alpha, 1, beta, 2, gamma)*CG(2, alpha, 1, beta, 2, gammap), (alpha, -2, 2), (beta, -1, 1))) == KroneckerDelta(gamma, gammap)
170
+
171
+
172
+ def test_doit():
173
+ assert Wigner3j(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0).doit() == -sqrt(2)/2
174
+ assert Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105
175
+ assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105
176
+ assert Wigner9j(
177
+ 2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0).doit() == sqrt(2)/12
178
+ assert CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0).doit() == sqrt(2)/2
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitplot.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.quantum.circuitplot import labeller, render_label, Mz, CreateOneQubitGate,\
2
+ CreateCGate
3
+ from sympy.physics.quantum.gate import CNOT, H, SWAP, CGate, S, T
4
+ from sympy.external import import_module
5
+ from sympy.testing.pytest import skip
6
+
7
+ mpl = import_module('matplotlib')
8
+
9
+ def test_render_label():
10
+ assert render_label('q0') == r'$\left|q0\right\rangle$'
11
+ assert render_label('q0', {'q0': '0'}) == r'$\left|q0\right\rangle=\left|0\right\rangle$'
12
+
13
+ def test_Mz():
14
+ assert str(Mz(0)) == 'Mz(0)'
15
+
16
+ def test_create1():
17
+ Qgate = CreateOneQubitGate('Q')
18
+ assert str(Qgate(0)) == 'Q(0)'
19
+
20
+ def test_createc():
21
+ Qgate = CreateCGate('Q')
22
+ assert str(Qgate([1],0)) == 'C((1),Q(0))'
23
+
24
+ def test_labeller():
25
+ """Test the labeller utility"""
26
+ assert labeller(2) == ['q_1', 'q_0']
27
+ assert labeller(3,'j') == ['j_2', 'j_1', 'j_0']
28
+
29
+ def test_cnot():
30
+ """Test a simple cnot circuit. Right now this only makes sure the code doesn't
31
+ raise an exception, and some simple properties
32
+ """
33
+ if not mpl:
34
+ skip("matplotlib not installed")
35
+ else:
36
+ from sympy.physics.quantum.circuitplot import CircuitPlot
37
+
38
+ c = CircuitPlot(CNOT(1,0),2,labels=labeller(2))
39
+ assert c.ngates == 2
40
+ assert c.nqubits == 2
41
+ assert c.labels == ['q_1', 'q_0']
42
+
43
+ c = CircuitPlot(CNOT(1,0),2)
44
+ assert c.ngates == 2
45
+ assert c.nqubits == 2
46
+ assert c.labels == []
47
+
48
+ def test_ex1():
49
+ if not mpl:
50
+ skip("matplotlib not installed")
51
+ else:
52
+ from sympy.physics.quantum.circuitplot import CircuitPlot
53
+
54
+ c = CircuitPlot(CNOT(1,0)*H(1),2,labels=labeller(2))
55
+ assert c.ngates == 2
56
+ assert c.nqubits == 2
57
+ assert c.labels == ['q_1', 'q_0']
58
+
59
+ def test_ex4():
60
+ if not mpl:
61
+ skip("matplotlib not installed")
62
+ else:
63
+ from sympy.physics.quantum.circuitplot import CircuitPlot
64
+
65
+ c = CircuitPlot(SWAP(0,2)*H(0)* CGate((0,),S(1)) *H(1)*CGate((0,),T(2))\
66
+ *CGate((1,),S(2))*H(2),3,labels=labeller(3,'j'))
67
+ assert c.ngates == 7
68
+ assert c.nqubits == 3
69
+ assert c.labels == ['j_2', 'j_1', 'j_0']
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitutils.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.mul import Mul
2
+ from sympy.core.numbers import Integer
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.utilities import numbered_symbols
5
+ from sympy.physics.quantum.gate import X, Y, Z, H, CNOT, CGate
6
+ from sympy.physics.quantum.identitysearch import bfs_identity_search
7
+ from sympy.physics.quantum.circuitutils import (kmp_table, find_subcircuit,
8
+ replace_subcircuit, convert_to_symbolic_indices,
9
+ convert_to_real_indices, random_reduce, random_insert,
10
+ flatten_ids)
11
+ from sympy.testing.pytest import slow
12
+
13
+
14
+ def create_gate_sequence(qubit=0):
15
+ gates = (X(qubit), Y(qubit), Z(qubit), H(qubit))
16
+ return gates
17
+
18
+
19
+ def test_kmp_table():
20
+ word = ('a', 'b', 'c', 'd', 'a', 'b', 'd')
21
+ expected_table = [-1, 0, 0, 0, 0, 1, 2]
22
+ assert expected_table == kmp_table(word)
23
+
24
+ word = ('P', 'A', 'R', 'T', 'I', 'C', 'I', 'P', 'A', 'T', 'E', ' ',
25
+ 'I', 'N', ' ', 'P', 'A', 'R', 'A', 'C', 'H', 'U', 'T', 'E')
26
+ expected_table = [-1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0,
27
+ 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0]
28
+ assert expected_table == kmp_table(word)
29
+
30
+ x = X(0)
31
+ y = Y(0)
32
+ z = Z(0)
33
+ h = H(0)
34
+ word = (x, y, y, x, z)
35
+ expected_table = [-1, 0, 0, 0, 1]
36
+ assert expected_table == kmp_table(word)
37
+
38
+ word = (x, x, y, h, z)
39
+ expected_table = [-1, 0, 1, 0, 0]
40
+ assert expected_table == kmp_table(word)
41
+
42
+
43
+ def test_find_subcircuit():
44
+ x = X(0)
45
+ y = Y(0)
46
+ z = Z(0)
47
+ h = H(0)
48
+ x1 = X(1)
49
+ y1 = Y(1)
50
+
51
+ i0 = Symbol('i0')
52
+ x_i0 = X(i0)
53
+ y_i0 = Y(i0)
54
+ z_i0 = Z(i0)
55
+ h_i0 = H(i0)
56
+
57
+ circuit = (x, y, z)
58
+
59
+ assert find_subcircuit(circuit, (x,)) == 0
60
+ assert find_subcircuit(circuit, (x1,)) == -1
61
+ assert find_subcircuit(circuit, (y,)) == 1
62
+ assert find_subcircuit(circuit, (h,)) == -1
63
+ assert find_subcircuit(circuit, Mul(x, h)) == -1
64
+ assert find_subcircuit(circuit, Mul(x, y, z)) == 0
65
+ assert find_subcircuit(circuit, Mul(y, z)) == 1
66
+ assert find_subcircuit(Mul(*circuit), (x, y, z, h)) == -1
67
+ assert find_subcircuit(Mul(*circuit), (z, y, x)) == -1
68
+ assert find_subcircuit(circuit, (x,), start=2, end=1) == -1
69
+
70
+ circuit = (x, y, x, y, z)
71
+ assert find_subcircuit(Mul(*circuit), Mul(x, y, z)) == 2
72
+ assert find_subcircuit(circuit, (x,), start=1) == 2
73
+ assert find_subcircuit(circuit, (x, y), start=1, end=2) == -1
74
+ assert find_subcircuit(Mul(*circuit), (x, y), start=1, end=3) == -1
75
+ assert find_subcircuit(circuit, (x, y), start=1, end=4) == 2
76
+ assert find_subcircuit(circuit, (x, y), start=2, end=4) == 2
77
+
78
+ circuit = (x, y, z, x1, x, y, z, h, x, y, x1,
79
+ x, y, z, h, y1, h)
80
+ assert find_subcircuit(circuit, (x, y, z, h, y1)) == 11
81
+
82
+ circuit = (x, y, x_i0, y_i0, z_i0, z)
83
+ assert find_subcircuit(circuit, (x_i0, y_i0, z_i0)) == 2
84
+
85
+ circuit = (x_i0, y_i0, z_i0, x_i0, y_i0, h_i0)
86
+ subcircuit = (x_i0, y_i0, z_i0)
87
+ result = find_subcircuit(circuit, subcircuit)
88
+ assert result == 0
89
+
90
+
91
+ def test_replace_subcircuit():
92
+ x = X(0)
93
+ y = Y(0)
94
+ z = Z(0)
95
+ h = H(0)
96
+ cnot = CNOT(1, 0)
97
+ cgate_z = CGate((0,), Z(1))
98
+
99
+ # Standard cases
100
+ circuit = (z, y, x, x)
101
+ remove = (z, y, x)
102
+ assert replace_subcircuit(circuit, Mul(*remove)) == (x,)
103
+ assert replace_subcircuit(circuit, remove + (x,)) == ()
104
+ assert replace_subcircuit(circuit, remove, pos=1) == circuit
105
+ assert replace_subcircuit(circuit, remove, pos=0) == (x,)
106
+ assert replace_subcircuit(circuit, (x, x), pos=2) == (z, y)
107
+ assert replace_subcircuit(circuit, (h,)) == circuit
108
+
109
+ circuit = (x, y, x, y, z)
110
+ remove = (x, y, z)
111
+ assert replace_subcircuit(Mul(*circuit), Mul(*remove)) == (x, y)
112
+ remove = (x, y, x, y)
113
+ assert replace_subcircuit(circuit, remove) == (z,)
114
+
115
+ circuit = (x, h, cgate_z, h, cnot)
116
+ remove = (x, h, cgate_z)
117
+ assert replace_subcircuit(circuit, Mul(*remove), pos=-1) == (h, cnot)
118
+ assert replace_subcircuit(circuit, remove, pos=1) == circuit
119
+ remove = (h, h)
120
+ assert replace_subcircuit(circuit, remove) == circuit
121
+ remove = (h, cgate_z, h, cnot)
122
+ assert replace_subcircuit(circuit, remove) == (x,)
123
+
124
+ replace = (h, x)
125
+ actual = replace_subcircuit(circuit, remove,
126
+ replace=replace)
127
+ assert actual == (x, h, x)
128
+
129
+ circuit = (x, y, h, x, y, z)
130
+ remove = (x, y)
131
+ replace = (cnot, cgate_z)
132
+ actual = replace_subcircuit(circuit, remove,
133
+ replace=Mul(*replace))
134
+ assert actual == (cnot, cgate_z, h, x, y, z)
135
+
136
+ actual = replace_subcircuit(circuit, remove,
137
+ replace=replace, pos=1)
138
+ assert actual == (x, y, h, cnot, cgate_z, z)
139
+
140
+
141
+ def test_convert_to_symbolic_indices():
142
+ (x, y, z, h) = create_gate_sequence()
143
+
144
+ i0 = Symbol('i0')
145
+ exp_map = {i0: Integer(0)}
146
+ actual, act_map, sndx, gen = convert_to_symbolic_indices((x,))
147
+ assert actual == (X(i0),)
148
+ assert act_map == exp_map
149
+
150
+ expected = (X(i0), Y(i0), Z(i0), H(i0))
151
+ exp_map = {i0: Integer(0)}
152
+ actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h))
153
+ assert actual == expected
154
+ assert exp_map == act_map
155
+
156
+ (x1, y1, z1, h1) = create_gate_sequence(1)
157
+ i1 = Symbol('i1')
158
+
159
+ expected = (X(i0), Y(i0), Z(i0), H(i0))
160
+ exp_map = {i0: Integer(1)}
161
+ actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, y1, z1, h1))
162
+ assert actual == expected
163
+ assert act_map == exp_map
164
+
165
+ expected = (X(i0), Y(i0), Z(i0), H(i0), X(i1), Y(i1), Z(i1), H(i1))
166
+ exp_map = {i0: Integer(0), i1: Integer(1)}
167
+ actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h,
168
+ x1, y1, z1, h1))
169
+ assert actual == expected
170
+ assert act_map == exp_map
171
+
172
+ exp_map = {i0: Integer(1), i1: Integer(0)}
173
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x1, y1,
174
+ z1, h1, x, y, z, h))
175
+ assert actual == expected
176
+ assert act_map == exp_map
177
+
178
+ expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1), H(i0), H(i1))
179
+ exp_map = {i0: Integer(0), i1: Integer(1)}
180
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x, x1,
181
+ y, y1, z, z1, h, h1))
182
+ assert actual == expected
183
+ assert act_map == exp_map
184
+
185
+ exp_map = {i0: Integer(1), i1: Integer(0)}
186
+ actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, x, y1, y,
187
+ z1, z, h1, h))
188
+ assert actual == expected
189
+ assert act_map == exp_map
190
+
191
+ cnot_10 = CNOT(1, 0)
192
+ cnot_01 = CNOT(0, 1)
193
+ cgate_z_10 = CGate(1, Z(0))
194
+ cgate_z_01 = CGate(0, Z(1))
195
+
196
+ expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1),
197
+ H(i0), H(i1), CNOT(i1, i0), CNOT(i0, i1),
198
+ CGate(i1, Z(i0)), CGate(i0, Z(i1)))
199
+ exp_map = {i0: Integer(0), i1: Integer(1)}
200
+ args = (x, x1, y, y1, z, z1, h, h1, cnot_10, cnot_01,
201
+ cgate_z_10, cgate_z_01)
202
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
203
+ assert actual == expected
204
+ assert act_map == exp_map
205
+
206
+ args = (x1, x, y1, y, z1, z, h1, h, cnot_10, cnot_01,
207
+ cgate_z_10, cgate_z_01)
208
+ expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1),
209
+ H(i0), H(i1), CNOT(i0, i1), CNOT(i1, i0),
210
+ CGate(i0, Z(i1)), CGate(i1, Z(i0)))
211
+ exp_map = {i0: Integer(1), i1: Integer(0)}
212
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
213
+ assert actual == expected
214
+ assert act_map == exp_map
215
+
216
+ args = (cnot_10, h, cgate_z_01, h)
217
+ expected = (CNOT(i0, i1), H(i1), CGate(i1, Z(i0)), H(i1))
218
+ exp_map = {i0: Integer(1), i1: Integer(0)}
219
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
220
+ assert actual == expected
221
+ assert act_map == exp_map
222
+
223
+ args = (cnot_01, h1, cgate_z_10, h1)
224
+ exp_map = {i0: Integer(0), i1: Integer(1)}
225
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
226
+ assert actual == expected
227
+ assert act_map == exp_map
228
+
229
+ args = (cnot_10, h1, cgate_z_01, h1)
230
+ expected = (CNOT(i0, i1), H(i0), CGate(i1, Z(i0)), H(i0))
231
+ exp_map = {i0: Integer(1), i1: Integer(0)}
232
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
233
+ assert actual == expected
234
+ assert act_map == exp_map
235
+
236
+ i2 = Symbol('i2')
237
+ ccgate_z = CGate(0, CGate(1, Z(2)))
238
+ ccgate_x = CGate(1, CGate(2, X(0)))
239
+ args = (ccgate_z, ccgate_x)
240
+
241
+ expected = (CGate(i0, CGate(i1, Z(i2))), CGate(i1, CGate(i2, X(i0))))
242
+ exp_map = {i0: Integer(0), i1: Integer(1), i2: Integer(2)}
243
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
244
+ assert actual == expected
245
+ assert act_map == exp_map
246
+
247
+ ndx_map = {i0: Integer(0)}
248
+ index_gen = numbered_symbols(prefix='i', start=1)
249
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args,
250
+ qubit_map=ndx_map,
251
+ start=i0,
252
+ gen=index_gen)
253
+ assert actual == expected
254
+ assert act_map == exp_map
255
+
256
+ i3 = Symbol('i3')
257
+ cgate_x0_c321 = CGate((3, 2, 1), X(0))
258
+ exp_map = {i0: Integer(3), i1: Integer(2),
259
+ i2: Integer(1), i3: Integer(0)}
260
+ expected = (CGate((i0, i1, i2), X(i3)),)
261
+ args = (cgate_x0_c321,)
262
+ actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
263
+ assert actual == expected
264
+ assert act_map == exp_map
265
+
266
+
267
+ def test_convert_to_real_indices():
268
+ i0 = Symbol('i0')
269
+ i1 = Symbol('i1')
270
+
271
+ (x, y, z, h) = create_gate_sequence()
272
+
273
+ x_i0 = X(i0)
274
+ y_i0 = Y(i0)
275
+ z_i0 = Z(i0)
276
+
277
+ qubit_map = {i0: 0}
278
+ args = (z_i0, y_i0, x_i0)
279
+ expected = (z, y, x)
280
+ actual = convert_to_real_indices(args, qubit_map)
281
+ assert actual == expected
282
+
283
+ cnot_10 = CNOT(1, 0)
284
+ cnot_01 = CNOT(0, 1)
285
+ cgate_z_10 = CGate(1, Z(0))
286
+ cgate_z_01 = CGate(0, Z(1))
287
+
288
+ cnot_i1_i0 = CNOT(i1, i0)
289
+ cnot_i0_i1 = CNOT(i0, i1)
290
+ cgate_z_i1_i0 = CGate(i1, Z(i0))
291
+
292
+ qubit_map = {i0: 0, i1: 1}
293
+ args = (cnot_i1_i0,)
294
+ expected = (cnot_10,)
295
+ actual = convert_to_real_indices(args, qubit_map)
296
+ assert actual == expected
297
+
298
+ args = (cgate_z_i1_i0,)
299
+ expected = (cgate_z_10,)
300
+ actual = convert_to_real_indices(args, qubit_map)
301
+ assert actual == expected
302
+
303
+ args = (cnot_i0_i1,)
304
+ expected = (cnot_01,)
305
+ actual = convert_to_real_indices(args, qubit_map)
306
+ assert actual == expected
307
+
308
+ qubit_map = {i0: 1, i1: 0}
309
+ args = (cgate_z_i1_i0,)
310
+ expected = (cgate_z_01,)
311
+ actual = convert_to_real_indices(args, qubit_map)
312
+ assert actual == expected
313
+
314
+ i2 = Symbol('i2')
315
+ ccgate_z = CGate(i0, CGate(i1, Z(i2)))
316
+ ccgate_x = CGate(i1, CGate(i2, X(i0)))
317
+
318
+ qubit_map = {i0: 0, i1: 1, i2: 2}
319
+ args = (ccgate_z, ccgate_x)
320
+ expected = (CGate(0, CGate(1, Z(2))), CGate(1, CGate(2, X(0))))
321
+ actual = convert_to_real_indices(Mul(*args), qubit_map)
322
+ assert actual == expected
323
+
324
+ qubit_map = {i0: 1, i2: 0, i1: 2}
325
+ args = (ccgate_x, ccgate_z)
326
+ expected = (CGate(2, CGate(0, X(1))), CGate(1, CGate(2, Z(0))))
327
+ actual = convert_to_real_indices(args, qubit_map)
328
+ assert actual == expected
329
+
330
+
331
+ @slow
332
+ def test_random_reduce():
333
+ x = X(0)
334
+ y = Y(0)
335
+ z = Z(0)
336
+ h = H(0)
337
+ cnot = CNOT(1, 0)
338
+ cgate_z = CGate((0,), Z(1))
339
+
340
+ gate_list = [x, y, z]
341
+ ids = list(bfs_identity_search(gate_list, 1, max_depth=4))
342
+
343
+ circuit = (x, y, h, z, cnot)
344
+ assert random_reduce(circuit, []) == circuit
345
+ assert random_reduce(circuit, ids) == circuit
346
+
347
+ seq = [2, 11, 9, 3, 5]
348
+ circuit = (x, y, z, x, y, h)
349
+ assert random_reduce(circuit, ids, seed=seq) == (x, y, h)
350
+
351
+ circuit = (x, x, y, y, z, z)
352
+ assert random_reduce(circuit, ids, seed=seq) == (x, x, y, y)
353
+
354
+ seq = [14, 13, 0]
355
+ assert random_reduce(circuit, ids, seed=seq) == (y, y, z, z)
356
+
357
+ gate_list = [x, y, z, h, cnot, cgate_z]
358
+ ids = list(bfs_identity_search(gate_list, 2, max_depth=4))
359
+
360
+ seq = [25]
361
+ circuit = (x, y, z, y, h, y, h, cgate_z, h, cnot)
362
+ expected = (x, y, z, cgate_z, h, cnot)
363
+ assert random_reduce(circuit, ids, seed=seq) == expected
364
+ circuit = Mul(*circuit)
365
+ assert random_reduce(circuit, ids, seed=seq) == expected
366
+
367
+
368
+ @slow
369
+ def test_random_insert():
370
+ x = X(0)
371
+ y = Y(0)
372
+ z = Z(0)
373
+ h = H(0)
374
+ cnot = CNOT(1, 0)
375
+ cgate_z = CGate((0,), Z(1))
376
+
377
+ choices = [(x, x)]
378
+ circuit = (y, y)
379
+ loc, choice = 0, 0
380
+ actual = random_insert(circuit, choices, seed=[loc, choice])
381
+ assert actual == (x, x, y, y)
382
+
383
+ circuit = (x, y, z, h)
384
+ choices = [(h, h), (x, y, z)]
385
+ expected = (x, x, y, z, y, z, h)
386
+ loc, choice = 1, 1
387
+ actual = random_insert(circuit, choices, seed=[loc, choice])
388
+ assert actual == expected
389
+
390
+ gate_list = [x, y, z, h, cnot, cgate_z]
391
+ ids = list(bfs_identity_search(gate_list, 2, max_depth=4))
392
+
393
+ eq_ids = flatten_ids(ids)
394
+
395
+ circuit = (x, y, h, cnot, cgate_z)
396
+ expected = (x, z, x, z, x, y, h, cnot, cgate_z)
397
+ loc, choice = 1, 30
398
+ actual = random_insert(circuit, eq_ids, seed=[loc, choice])
399
+ assert actual == expected
400
+ circuit = Mul(*circuit)
401
+ actual = random_insert(circuit, eq_ids, seed=[loc, choice])
402
+ assert actual == expected
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_commutator.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Integer
2
+ from sympy.core.symbol import symbols
3
+
4
+ from sympy.physics.quantum.dagger import Dagger
5
+ from sympy.physics.quantum.commutator import Commutator as Comm
6
+ from sympy.physics.quantum.operator import Operator
7
+
8
+
9
+ a, b, c = symbols('a,b,c')
10
+ n = symbols('n', integer=True)
11
+ A, B, C, D = symbols('A,B,C,D', commutative=False)
12
+
13
+
14
+ def test_commutator():
15
+ c = Comm(A, B)
16
+ assert c.is_commutative is False
17
+ assert isinstance(c, Comm)
18
+ assert c.subs(A, C) == Comm(C, B)
19
+
20
+
21
+ def test_commutator_identities():
22
+ assert Comm(a*A, b*B) == a*b*Comm(A, B)
23
+ assert Comm(A, A) == 0
24
+ assert Comm(a, b) == 0
25
+ assert Comm(A, B) == -Comm(B, A)
26
+ assert Comm(A, B).doit() == A*B - B*A
27
+ assert Comm(A, B*C).expand(commutator=True) == Comm(A, B)*C + B*Comm(A, C)
28
+ assert Comm(A*B, C*D).expand(commutator=True) == \
29
+ A*C*Comm(B, D) + A*Comm(B, C)*D + C*Comm(A, D)*B + Comm(A, C)*D*B
30
+ assert Comm(A, B**2).expand(commutator=True) == Comm(A, B)*B + B*Comm(A, B)
31
+ assert Comm(A**2, C**2).expand(commutator=True) == \
32
+ Comm(A*B, C*D).expand(commutator=True).replace(B, A).replace(D, C) == \
33
+ A*C*Comm(A, C) + A*Comm(A, C)*C + C*Comm(A, C)*A + Comm(A, C)*C*A
34
+ assert Comm(A, C**-2).expand(commutator=True) == \
35
+ Comm(A, (1/C)*(1/D)).expand(commutator=True).replace(D, C)
36
+ assert Comm(A + B, C + D).expand(commutator=True) == \
37
+ Comm(A, C) + Comm(A, D) + Comm(B, C) + Comm(B, D)
38
+ assert Comm(A, B + C).expand(commutator=True) == Comm(A, B) + Comm(A, C)
39
+ assert Comm(A**n, B).expand(commutator=True) == Comm(A**n, B)
40
+
41
+ e = Comm(A, Comm(B, C)) + Comm(B, Comm(C, A)) + Comm(C, Comm(A, B))
42
+ assert e.doit().expand() == 0
43
+
44
+
45
+ def test_commutator_dagger():
46
+ comm = Comm(A*B, C)
47
+ assert Dagger(comm).expand(commutator=True) == \
48
+ - Comm(Dagger(B), Dagger(C))*Dagger(A) - \
49
+ Dagger(B)*Comm(Dagger(A), Dagger(C))
50
+
51
+
52
+ class Foo(Operator):
53
+
54
+ def _eval_commutator_Bar(self, bar):
55
+ return Integer(0)
56
+
57
+
58
+ class Bar(Operator):
59
+ pass
60
+
61
+
62
+ class Tam(Operator):
63
+
64
+ def _eval_commutator_Foo(self, foo):
65
+ return Integer(1)
66
+
67
+
68
+ def test_eval_commutator():
69
+ F = Foo('F')
70
+ B = Bar('B')
71
+ T = Tam('T')
72
+ assert Comm(F, B).doit() == 0
73
+ assert Comm(B, F).doit() == 0
74
+ assert Comm(F, T).doit() == -1
75
+ assert Comm(T, F).doit() == 1
76
+ assert Comm(B, T).doit() == B*T - T*B
77
+ assert Comm(F**2, B).expand(commutator=True).doit() == 0
78
+ assert Comm(F**2, T).expand(commutator=True).doit() == -2*F
79
+ assert Comm(F, T**2).expand(commutator=True).doit() == -2*T
80
+ assert Comm(T**2, F).expand(commutator=True).doit() == 2*T
81
+ assert Comm(T**2, F**3).expand(commutator=True).doit() == 2*F*T*F + 2*F**2*T + 2*T*F**2
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Float
2
+
3
+ from sympy.physics.quantum.constants import hbar
4
+
5
+
6
+ def test_hbar():
7
+ assert hbar.is_commutative is True
8
+ assert hbar.is_real is True
9
+ assert hbar.is_positive is True
10
+ assert hbar.is_negative is False
11
+ assert hbar.is_irrational is True
12
+
13
+ assert hbar.evalf() == Float(1.05457162e-34)