We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Override of PhasedXPowGate causes determinant of gate to jump discontinuously
```
>>> np.linalg.det(cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1.01, exponent=0.5)))
0.9999999999999998j
>>> np.linalg.det(cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1., exponent=0.5)))
-0.9999999999999998j
>>> np.linalg.det(cirq.unitary(cirq.PhasedXPowGate(phase_exponent=0.99, exponent=0.5)))
0.9999999999999998j
```
and the gates also change badly
```
>>> cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1.01, exponent=0.5))
array([[ 0.5       +0.5j       , -0.4840479 +0.51545866j],
       [-0.51545866+0.4840479j ,  0.5       +0.5j       ]])
>>> cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1, exponent=0.5))
array([[0.5-0.5j, 0.5+0.5j],
       [0.5+0.5j, 0.5-0.5j]])
>>> cirq.unitary(cirq.PhasedXPowGate(phase_exponent=0.99, exponent=0.5))
array([[ 0.5       +0.5j       , -0.51545866+0.4840479j ],
       [-0.4840479 +0.51545866j,  0.5       +0.5j       ]])
```

These discontinuous jumps are likely coming from the __new__ override code.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `cirq/ops/phased_x_gate.py`
Content:
```
1 # Copyright 2018 The Cirq Developers
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     https://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """An `XPowGate` conjugated by `ZPowGate`s."""
16 from typing import Union, Sequence, Tuple, Optional, cast
17 
18 import math
19 import numpy as np
20 import sympy
21 
22 import cirq
23 from cirq import value, protocols
24 from cirq._compat import proper_repr
25 from cirq.ops import gate_features, raw_types, op_tree
26 from cirq.type_workarounds import NotImplementedType
27 
28 @value.value_equality
29 class PhasedXPowGate(gate_features.SingleQubitGate):
30     """A gate equivalent to the circuit ───Z^-p───X^t───Z^p───."""
31 
32     def __new__(cls,
33                 *,
34                 phase_exponent: Union[float, sympy.Symbol],
35                 exponent: Union[float, sympy.Symbol] = 1.0,
36                 global_shift: float = 0.0):
37         """Substitutes a raw X or raw Y if possible.
38 
39         Args:
40             phase_exponent: The exponent on the Z gates conjugating the X gate.
41             exponent: The exponent on the X gate conjugated by Zs.
42             global_shift: How much to shift the operation's eigenvalues at
43                 exponent=1.
44         """
45         p = value.canonicalize_half_turns(phase_exponent)
46         if p == 0:
47             return cirq.ops.common_gates.XPowGate(
48                 exponent=exponent,
49                 global_shift=global_shift)
50         if p == 0.5:
51             return cirq.ops.common_gates.YPowGate(
52                 exponent=exponent,
53                 global_shift=global_shift)
54         if p == 1 and not isinstance(exponent, sympy.Symbol):
55             return cirq.ops.common_gates.XPowGate(
56                 exponent=-exponent,
57                 global_shift=global_shift)
58         if p == -0.5 and not isinstance(exponent, sympy.Symbol):
59             return cirq.ops.common_gates.YPowGate(
60                 exponent=-exponent,
61                 global_shift=global_shift)
62         return super().__new__(cls)
63 
64     def __init__(self,
65                  *,
66                  phase_exponent: Union[float, sympy.Symbol],
67                  exponent: Union[float, sympy.Symbol] = 1.0,
68                  global_shift: float = 0.0) -> None:
69         """
70         Args:
71             phase_exponent: The exponent on the Z gates conjugating the X gate.
72             exponent: The exponent on the X gate conjugated by Zs.
73             global_shift: How much to shift the operation's eigenvalues at
74                 exponent=1.
75         """
76         self._phase_exponent = value.canonicalize_half_turns(phase_exponent)
77         self._exponent = exponent
78         self._global_shift = global_shift
79 
80     def _qasm_(self,
81                args: protocols.QasmArgs,
82                qubits: Tuple[raw_types.Qid, ...]) -> Optional[str]:
83         if cirq.is_parameterized(self):
84             return None
85 
86         args.validate_version('2.0')
87 
88         e = cast(float, value.canonicalize_half_turns(self._exponent))
89         p = cast(float, self.phase_exponent)
90         epsilon = 10**-args.precision
91 
92         if abs(e + 0.5) <= epsilon:
93             return args.format('u2({0:half_turns}, {1:half_turns}) {2};\n',
94                                p + 0.5, -p - 0.5, qubits[0])
95 
96         if abs(e - 0.5) <= epsilon:
97             return args.format('u2({0:half_turns}, {1:half_turns}) {2};\n',
98                                p - 0.5, -p + 0.5, qubits[0])
99 
100         return args.format(
101             'u3({0:half_turns}, {1:half_turns}, {2:half_turns}) {3};\n',
102             -e, p + 0.5, -p - 0.5, qubits[0])
103 
104     def _decompose_(self, qubits: Sequence[raw_types.Qid]
105                           ) -> op_tree.OP_TREE:
106         assert len(qubits) == 1
107         q = qubits[0]
108         z = cirq.Z(q)**self._phase_exponent
109         x = cirq.X(q)**self._exponent
110         if protocols.is_parameterized(z):
111             return NotImplemented
112         return z**-1, x, z
113 
114     @property
115     def exponent(self) -> Union[float, sympy.Symbol]:
116         """The exponent on the central X gate conjugated by the Z gates."""
117         return self._exponent
118 
119     @property
120     def phase_exponent(self) -> Union[float, sympy.Symbol]:
121         """The exponent on the Z gates conjugating the X gate."""
122         return self._phase_exponent
123 
124     def __pow__(self, exponent: Union[float, sympy.Symbol]) -> 'PhasedXPowGate':
125         new_exponent = protocols.mul(self._exponent, exponent, NotImplemented)
126         if new_exponent is NotImplemented:
127             return NotImplemented
128         return PhasedXPowGate(phase_exponent=self._phase_exponent,
129                               exponent=new_exponent,
130                               global_shift=self._global_shift)
131 
132     def _trace_distance_bound_(self):
133         """See `cirq.SupportsTraceDistanceBound`."""
134         return protocols.trace_distance_bound(cirq.X**self._exponent)
135 
136     def _unitary_(self) -> Union[np.ndarray, NotImplementedType]:
137         """See `cirq.SupportsUnitary`."""
138         if self._is_parameterized_():
139             return NotImplemented
140         z = protocols.unitary(cirq.Z**self._phase_exponent)
141         x = protocols.unitary(cirq.X**self._exponent)
142         p = np.exp(1j * np.pi * self._global_shift * self._exponent)
143         return np.dot(np.dot(z, x), np.conj(z)) * p
144 
145     def _pauli_expansion_(self) -> value.LinearDict[str]:
146         if self._is_parameterized_():
147             return NotImplemented
148         phase_angle = np.pi * self._phase_exponent / 2
149         angle = np.pi * self._exponent / 2
150         phase = 1j**(2 * self._exponent * (self._global_shift + 0.5))
151         return value.LinearDict({
152             'I': phase * np.cos(angle),
153             'X': -1j * phase * np.sin(angle) * np.cos(2 * phase_angle),
154             'Y': -1j * phase * np.sin(angle) * np.sin(2 * phase_angle),
155         })
156 
157     def _is_parameterized_(self) -> bool:
158         """See `cirq.SupportsParameterization`."""
159         return (protocols.is_parameterized(self._exponent) or
160                 protocols.is_parameterized(self._phase_exponent))
161 
162     def _resolve_parameters_(self, param_resolver) -> 'PhasedXPowGate':
163         """See `cirq.SupportsParameterization`."""
164         return PhasedXPowGate(
165             phase_exponent=param_resolver.value_of(self._phase_exponent),
166             exponent=param_resolver.value_of(self._exponent),
167             global_shift=self._global_shift)
168 
169     def _phase_by_(self, phase_turns, qubit_index):
170         """See `cirq.SupportsPhase`."""
171         assert qubit_index == 0
172         return PhasedXPowGate(
173             exponent=self._exponent,
174             phase_exponent=self._phase_exponent + phase_turns * 2,
175             global_shift=self._global_shift)
176 
177     def _circuit_diagram_info_(self, args: protocols.CircuitDiagramInfoArgs
178                                ) -> protocols.CircuitDiagramInfo:
179         """See `cirq.SupportsCircuitDiagramInfo`."""
180 
181         if (isinstance(self.phase_exponent, sympy.Symbol) or
182                 args.precision is None):
183             s = 'PhasedX({})'.format(self.phase_exponent)
184         else:
185             s = 'PhasedX({{:.{}}})'.format(args.precision).format(
186                 self.phase_exponent)
187         return protocols.CircuitDiagramInfo(
188             wire_symbols=(s,),
189             exponent=value.canonicalize_half_turns(self._exponent))
190 
191     def __str__(self):
192         info = protocols.circuit_diagram_info(self)
193         if info.exponent == 1:
194             return info.wire_symbols[0]
195         return '{}^{}'.format(info.wire_symbols[0], info.exponent)
196 
197     def __repr__(self):
198         args = ['phase_exponent={}'.format(proper_repr(self.phase_exponent))]
199         if self.exponent != 1:
200             args.append('exponent={}'.format(proper_repr(self.exponent)))
201         if self._global_shift != 0:
202             args.append('global_shift={!r}'.format(self._global_shift))
203         return 'cirq.PhasedXPowGate({})'.format(', '.join(args))
204 
205     def _period(self):
206         exponents = [self._global_shift, 1 + self._global_shift]
207         real_periods = [abs(2/e) for e in exponents if e != 0]
208         int_periods = [int(np.round(e)) for e in real_periods]
209         if any(i != r for i, r in zip(real_periods, int_periods)):
210             return None
211         if len(int_periods) == 1:
212             return int_periods[0]
213         return int_periods[0] * int_periods[1] / math.gcd(*int_periods)
214 
215     @property
216     def _canonical_exponent(self):
217         period = self._period()
218         if not period or isinstance(self._exponent, sympy.Symbol):
219             return self._exponent
220         else:
221             return self._exponent % period
222 
223     def _value_equality_values_(self):
224         return self.phase_exponent, self._canonical_exponent, self._global_shift
225
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/cirq/ops/phased_x_gate.py b/cirq/ops/phased_x_gate.py
--- a/cirq/ops/phased_x_gate.py
+++ b/cirq/ops/phased_x_gate.py
@@ -48,17 +48,8 @@
                 exponent=exponent,
                 global_shift=global_shift)
         if p == 0.5:
-            return cirq.ops.common_gates.YPowGate(
-                exponent=exponent,
-                global_shift=global_shift)
-        if p == 1 and not isinstance(exponent, sympy.Symbol):
-            return cirq.ops.common_gates.XPowGate(
-                exponent=-exponent,
-                global_shift=global_shift)
-        if p == -0.5 and not isinstance(exponent, sympy.Symbol):
-            return cirq.ops.common_gates.YPowGate(
-                exponent=-exponent,
-                global_shift=global_shift)
+            return cirq.ops.common_gates.YPowGate(exponent=exponent,
+                                                  global_shift=global_shift)
         return super().__new__(cls)
 
     def __init__(self,

{"golden_diff": "diff --git a/cirq/ops/phased_x_gate.py b/cirq/ops/phased_x_gate.py\n--- a/cirq/ops/phased_x_gate.py\n+++ b/cirq/ops/phased_x_gate.py\n@@ -48,17 +48,8 @@\n                 exponent=exponent,\n                 global_shift=global_shift)\n         if p == 0.5:\n-            return cirq.ops.common_gates.YPowGate(\n-                exponent=exponent,\n-                global_shift=global_shift)\n-        if p == 1 and not isinstance(exponent, sympy.Symbol):\n-            return cirq.ops.common_gates.XPowGate(\n-                exponent=-exponent,\n-                global_shift=global_shift)\n-        if p == -0.5 and not isinstance(exponent, sympy.Symbol):\n-            return cirq.ops.common_gates.YPowGate(\n-                exponent=-exponent,\n-                global_shift=global_shift)\n+            return cirq.ops.common_gates.YPowGate(exponent=exponent,\n+                                                  global_shift=global_shift)\n         return super().__new__(cls)\n \n     def __init__(self,\n", "issue": "Override of PhasedXPowGate causes determinant of gate to jump discontinuously\n```\r\n>>> np.linalg.det(cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1.01, exponent=0.5)))\r\n0.9999999999999998j\r\n>>> np.linalg.det(cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1., exponent=0.5)))\r\n-0.9999999999999998j\r\n>>> np.linalg.det(cirq.unitary(cirq.PhasedXPowGate(phase_exponent=0.99, exponent=0.5)))\r\n0.9999999999999998j\r\n```\r\nand the gates also change badly\r\n```\r\n>>> cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1.01, exponent=0.5))\r\narray([[ 0.5       +0.5j       , -0.4840479 +0.51545866j],\r\n       [-0.51545866+0.4840479j ,  0.5       +0.5j       ]])\r\n>>> cirq.unitary(cirq.PhasedXPowGate(phase_exponent=1, exponent=0.5))\r\narray([[0.5-0.5j, 0.5+0.5j],\r\n       [0.5+0.5j, 0.5-0.5j]])\r\n>>> cirq.unitary(cirq.PhasedXPowGate(phase_exponent=0.99, exponent=0.5))\r\narray([[ 0.5       +0.5j       , -0.51545866+0.4840479j ],\r\n       [-0.4840479 +0.51545866j,  0.5       +0.5j       ]])\r\n```\r\n\r\nThese discontinuous jumps are likely coming from the __new__ override code.\r\n\n", "before_files": [{"content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"An `XPowGate` conjugated by `ZPowGate`s.\"\"\"\nfrom typing import Union, Sequence, Tuple, Optional, cast\n\nimport math\nimport numpy as np\nimport sympy\n\nimport cirq\nfrom cirq import value, protocols\nfrom cirq._compat import proper_repr\nfrom cirq.ops import gate_features, raw_types, op_tree\nfrom cirq.type_workarounds import NotImplementedType\n\n@value.value_equality\nclass PhasedXPowGate(gate_features.SingleQubitGate):\n    \"\"\"A gate equivalent to the circuit \u2500\u2500\u2500Z^-p\u2500\u2500\u2500X^t\u2500\u2500\u2500Z^p\u2500\u2500\u2500.\"\"\"\n\n    def __new__(cls,\n                *,\n                phase_exponent: Union[float, sympy.Symbol],\n                exponent: Union[float, sympy.Symbol] = 1.0,\n                global_shift: float = 0.0):\n        \"\"\"Substitutes a raw X or raw Y if possible.\n\n        Args:\n            phase_exponent: The exponent on the Z gates conjugating the X gate.\n            exponent: The exponent on the X gate conjugated by Zs.\n            global_shift: How much to shift the operation's eigenvalues at\n                exponent=1.\n        \"\"\"\n        p = value.canonicalize_half_turns(phase_exponent)\n        if p == 0:\n            return cirq.ops.common_gates.XPowGate(\n                exponent=exponent,\n                global_shift=global_shift)\n        if p == 0.5:\n            return cirq.ops.common_gates.YPowGate(\n                exponent=exponent,\n                global_shift=global_shift)\n        if p == 1 and not isinstance(exponent, sympy.Symbol):\n            return cirq.ops.common_gates.XPowGate(\n                exponent=-exponent,\n                global_shift=global_shift)\n        if p == -0.5 and not isinstance(exponent, sympy.Symbol):\n            return cirq.ops.common_gates.YPowGate(\n                exponent=-exponent,\n                global_shift=global_shift)\n        return super().__new__(cls)\n\n    def __init__(self,\n                 *,\n                 phase_exponent: Union[float, sympy.Symbol],\n                 exponent: Union[float, sympy.Symbol] = 1.0,\n                 global_shift: float = 0.0) -> None:\n        \"\"\"\n        Args:\n            phase_exponent: The exponent on the Z gates conjugating the X gate.\n            exponent: The exponent on the X gate conjugated by Zs.\n            global_shift: How much to shift the operation's eigenvalues at\n                exponent=1.\n        \"\"\"\n        self._phase_exponent = value.canonicalize_half_turns(phase_exponent)\n        self._exponent = exponent\n        self._global_shift = global_shift\n\n    def _qasm_(self,\n               args: protocols.QasmArgs,\n               qubits: Tuple[raw_types.Qid, ...]) -> Optional[str]:\n        if cirq.is_parameterized(self):\n            return None\n\n        args.validate_version('2.0')\n\n        e = cast(float, value.canonicalize_half_turns(self._exponent))\n        p = cast(float, self.phase_exponent)\n        epsilon = 10**-args.precision\n\n        if abs(e + 0.5) <= epsilon:\n            return args.format('u2({0:half_turns}, {1:half_turns}) {2};\\n',\n                               p + 0.5, -p - 0.5, qubits[0])\n\n        if abs(e - 0.5) <= epsilon:\n            return args.format('u2({0:half_turns}, {1:half_turns}) {2};\\n',\n                               p - 0.5, -p + 0.5, qubits[0])\n\n        return args.format(\n            'u3({0:half_turns}, {1:half_turns}, {2:half_turns}) {3};\\n',\n            -e, p + 0.5, -p - 0.5, qubits[0])\n\n    def _decompose_(self, qubits: Sequence[raw_types.Qid]\n                          ) -> op_tree.OP_TREE:\n        assert len(qubits) == 1\n        q = qubits[0]\n        z = cirq.Z(q)**self._phase_exponent\n        x = cirq.X(q)**self._exponent\n        if protocols.is_parameterized(z):\n            return NotImplemented\n        return z**-1, x, z\n\n    @property\n    def exponent(self) -> Union[float, sympy.Symbol]:\n        \"\"\"The exponent on the central X gate conjugated by the Z gates.\"\"\"\n        return self._exponent\n\n    @property\n    def phase_exponent(self) -> Union[float, sympy.Symbol]:\n        \"\"\"The exponent on the Z gates conjugating the X gate.\"\"\"\n        return self._phase_exponent\n\n    def __pow__(self, exponent: Union[float, sympy.Symbol]) -> 'PhasedXPowGate':\n        new_exponent = protocols.mul(self._exponent, exponent, NotImplemented)\n        if new_exponent is NotImplemented:\n            return NotImplemented\n        return PhasedXPowGate(phase_exponent=self._phase_exponent,\n                              exponent=new_exponent,\n                              global_shift=self._global_shift)\n\n    def _trace_distance_bound_(self):\n        \"\"\"See `cirq.SupportsTraceDistanceBound`.\"\"\"\n        return protocols.trace_distance_bound(cirq.X**self._exponent)\n\n    def _unitary_(self) -> Union[np.ndarray, NotImplementedType]:\n        \"\"\"See `cirq.SupportsUnitary`.\"\"\"\n        if self._is_parameterized_():\n            return NotImplemented\n        z = protocols.unitary(cirq.Z**self._phase_exponent)\n        x = protocols.unitary(cirq.X**self._exponent)\n        p = np.exp(1j * np.pi * self._global_shift * self._exponent)\n        return np.dot(np.dot(z, x), np.conj(z)) * p\n\n    def _pauli_expansion_(self) -> value.LinearDict[str]:\n        if self._is_parameterized_():\n            return NotImplemented\n        phase_angle = np.pi * self._phase_exponent / 2\n        angle = np.pi * self._exponent / 2\n        phase = 1j**(2 * self._exponent * (self._global_shift + 0.5))\n        return value.LinearDict({\n            'I': phase * np.cos(angle),\n            'X': -1j * phase * np.sin(angle) * np.cos(2 * phase_angle),\n            'Y': -1j * phase * np.sin(angle) * np.sin(2 * phase_angle),\n        })\n\n    def _is_parameterized_(self) -> bool:\n        \"\"\"See `cirq.SupportsParameterization`.\"\"\"\n        return (protocols.is_parameterized(self._exponent) or\n                protocols.is_parameterized(self._phase_exponent))\n\n    def _resolve_parameters_(self, param_resolver) -> 'PhasedXPowGate':\n        \"\"\"See `cirq.SupportsParameterization`.\"\"\"\n        return PhasedXPowGate(\n            phase_exponent=param_resolver.value_of(self._phase_exponent),\n            exponent=param_resolver.value_of(self._exponent),\n            global_shift=self._global_shift)\n\n    def _phase_by_(self, phase_turns, qubit_index):\n        \"\"\"See `cirq.SupportsPhase`.\"\"\"\n        assert qubit_index == 0\n        return PhasedXPowGate(\n            exponent=self._exponent,\n            phase_exponent=self._phase_exponent + phase_turns * 2,\n            global_shift=self._global_shift)\n\n    def _circuit_diagram_info_(self, args: protocols.CircuitDiagramInfoArgs\n                               ) -> protocols.CircuitDiagramInfo:\n        \"\"\"See `cirq.SupportsCircuitDiagramInfo`.\"\"\"\n\n        if (isinstance(self.phase_exponent, sympy.Symbol) or\n                args.precision is None):\n            s = 'PhasedX({})'.format(self.phase_exponent)\n        else:\n            s = 'PhasedX({{:.{}}})'.format(args.precision).format(\n                self.phase_exponent)\n        return protocols.CircuitDiagramInfo(\n            wire_symbols=(s,),\n            exponent=value.canonicalize_half_turns(self._exponent))\n\n    def __str__(self):\n        info = protocols.circuit_diagram_info(self)\n        if info.exponent == 1:\n            return info.wire_symbols[0]\n        return '{}^{}'.format(info.wire_symbols[0], info.exponent)\n\n    def __repr__(self):\n        args = ['phase_exponent={}'.format(proper_repr(self.phase_exponent))]\n        if self.exponent != 1:\n            args.append('exponent={}'.format(proper_repr(self.exponent)))\n        if self._global_shift != 0:\n            args.append('global_shift={!r}'.format(self._global_shift))\n        return 'cirq.PhasedXPowGate({})'.format(', '.join(args))\n\n    def _period(self):\n        exponents = [self._global_shift, 1 + self._global_shift]\n        real_periods = [abs(2/e) for e in exponents if e != 0]\n        int_periods = [int(np.round(e)) for e in real_periods]\n        if any(i != r for i, r in zip(real_periods, int_periods)):\n            return None\n        if len(int_periods) == 1:\n            return int_periods[0]\n        return int_periods[0] * int_periods[1] / math.gcd(*int_periods)\n\n    @property\n    def _canonical_exponent(self):\n        period = self._period()\n        if not period or isinstance(self._exponent, sympy.Symbol):\n            return self._exponent\n        else:\n            return self._exponent % period\n\n    def _value_equality_values_(self):\n        return self.phase_exponent, self._canonical_exponent, self._global_shift\n", "path": "cirq/ops/phased_x_gate.py"}], "after_files": [{"content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"An `XPowGate` conjugated by `ZPowGate`s.\"\"\"\nfrom typing import Union, Sequence, Tuple, Optional, cast\n\nimport math\nimport numpy as np\nimport sympy\n\nimport cirq\nfrom cirq import value, protocols\nfrom cirq._compat import proper_repr\nfrom cirq.ops import gate_features, raw_types, op_tree\nfrom cirq.type_workarounds import NotImplementedType\n\n@value.value_equality\nclass PhasedXPowGate(gate_features.SingleQubitGate):\n    \"\"\"A gate equivalent to the circuit \u2500\u2500\u2500Z^-p\u2500\u2500\u2500X^t\u2500\u2500\u2500Z^p\u2500\u2500\u2500.\"\"\"\n\n    def __new__(cls,\n                *,\n                phase_exponent: Union[float, sympy.Symbol],\n                exponent: Union[float, sympy.Symbol] = 1.0,\n                global_shift: float = 0.0):\n        \"\"\"Substitutes a raw X or raw Y if possible.\n\n        Args:\n            phase_exponent: The exponent on the Z gates conjugating the X gate.\n            exponent: The exponent on the X gate conjugated by Zs.\n            global_shift: How much to shift the operation's eigenvalues at\n                exponent=1.\n        \"\"\"\n        p = value.canonicalize_half_turns(phase_exponent)\n        if p == 0:\n            return cirq.ops.common_gates.XPowGate(\n                exponent=exponent,\n                global_shift=global_shift)\n        if p == 0.5:\n            return cirq.ops.common_gates.YPowGate(exponent=exponent,\n                                                  global_shift=global_shift)\n        return super().__new__(cls)\n\n    def __init__(self,\n                 *,\n                 phase_exponent: Union[float, sympy.Symbol],\n                 exponent: Union[float, sympy.Symbol] = 1.0,\n                 global_shift: float = 0.0) -> None:\n        \"\"\"\n        Args:\n            phase_exponent: The exponent on the Z gates conjugating the X gate.\n            exponent: The exponent on the X gate conjugated by Zs.\n            global_shift: How much to shift the operation's eigenvalues at\n                exponent=1.\n        \"\"\"\n        self._phase_exponent = value.canonicalize_half_turns(phase_exponent)\n        self._exponent = exponent\n        self._global_shift = global_shift\n\n    def _qasm_(self,\n               args: protocols.QasmArgs,\n               qubits: Tuple[raw_types.Qid, ...]) -> Optional[str]:\n        if cirq.is_parameterized(self):\n            return None\n\n        args.validate_version('2.0')\n\n        e = cast(float, value.canonicalize_half_turns(self._exponent))\n        p = cast(float, self.phase_exponent)\n        epsilon = 10**-args.precision\n\n        if abs(e + 0.5) <= epsilon:\n            return args.format('u2({0:half_turns}, {1:half_turns}) {2};\\n',\n                               p + 0.5, -p - 0.5, qubits[0])\n\n        if abs(e - 0.5) <= epsilon:\n            return args.format('u2({0:half_turns}, {1:half_turns}) {2};\\n',\n                               p - 0.5, -p + 0.5, qubits[0])\n\n        return args.format(\n            'u3({0:half_turns}, {1:half_turns}, {2:half_turns}) {3};\\n',\n            -e, p + 0.5, -p - 0.5, qubits[0])\n\n    def _decompose_(self, qubits: Sequence[raw_types.Qid]\n                          ) -> op_tree.OP_TREE:\n        assert len(qubits) == 1\n        q = qubits[0]\n        z = cirq.Z(q)**self._phase_exponent\n        x = cirq.X(q)**self._exponent\n        if protocols.is_parameterized(z):\n            return NotImplemented\n        return z**-1, x, z\n\n    @property\n    def exponent(self) -> Union[float, sympy.Symbol]:\n        \"\"\"The exponent on the central X gate conjugated by the Z gates.\"\"\"\n        return self._exponent\n\n    @property\n    def phase_exponent(self) -> Union[float, sympy.Symbol]:\n        \"\"\"The exponent on the Z gates conjugating the X gate.\"\"\"\n        return self._phase_exponent\n\n    def __pow__(self, exponent: Union[float, sympy.Symbol]) -> 'PhasedXPowGate':\n        new_exponent = protocols.mul(self._exponent, exponent, NotImplemented)\n        if new_exponent is NotImplemented:\n            return NotImplemented\n        return PhasedXPowGate(phase_exponent=self._phase_exponent,\n                              exponent=new_exponent,\n                              global_shift=self._global_shift)\n\n    def _trace_distance_bound_(self):\n        \"\"\"See `cirq.SupportsTraceDistanceBound`.\"\"\"\n        return protocols.trace_distance_bound(cirq.X**self._exponent)\n\n    def _unitary_(self) -> Union[np.ndarray, NotImplementedType]:\n        \"\"\"See `cirq.SupportsUnitary`.\"\"\"\n        if self._is_parameterized_():\n            return NotImplemented\n        z = protocols.unitary(cirq.Z**self._phase_exponent)\n        x = protocols.unitary(cirq.X**self._exponent)\n        p = np.exp(1j * np.pi * self._global_shift * self._exponent)\n        return np.dot(np.dot(z, x), np.conj(z)) * p\n\n    def _pauli_expansion_(self) -> value.LinearDict[str]:\n        if self._is_parameterized_():\n            return NotImplemented\n        phase_angle = np.pi * self._phase_exponent / 2\n        angle = np.pi * self._exponent / 2\n        phase = 1j**(2 * self._exponent * (self._global_shift + 0.5))\n        return value.LinearDict({\n            'I': phase * np.cos(angle),\n            'X': -1j * phase * np.sin(angle) * np.cos(2 * phase_angle),\n            'Y': -1j * phase * np.sin(angle) * np.sin(2 * phase_angle),\n        })\n\n    def _is_parameterized_(self) -> bool:\n        \"\"\"See `cirq.SupportsParameterization`.\"\"\"\n        return (protocols.is_parameterized(self._exponent) or\n                protocols.is_parameterized(self._phase_exponent))\n\n    def _resolve_parameters_(self, param_resolver) -> 'PhasedXPowGate':\n        \"\"\"See `cirq.SupportsParameterization`.\"\"\"\n        return PhasedXPowGate(\n            phase_exponent=param_resolver.value_of(self._phase_exponent),\n            exponent=param_resolver.value_of(self._exponent),\n            global_shift=self._global_shift)\n\n    def _phase_by_(self, phase_turns, qubit_index):\n        \"\"\"See `cirq.SupportsPhase`.\"\"\"\n        assert qubit_index == 0\n        return PhasedXPowGate(\n            exponent=self._exponent,\n            phase_exponent=self._phase_exponent + phase_turns * 2,\n            global_shift=self._global_shift)\n\n    def _circuit_diagram_info_(self, args: protocols.CircuitDiagramInfoArgs\n                               ) -> protocols.CircuitDiagramInfo:\n        \"\"\"See `cirq.SupportsCircuitDiagramInfo`.\"\"\"\n\n        if (isinstance(self.phase_exponent, sympy.Symbol) or\n                args.precision is None):\n            s = 'PhasedX({})'.format(self.phase_exponent)\n        else:\n            s = 'PhasedX({{:.{}}})'.format(args.precision).format(\n                self.phase_exponent)\n        return protocols.CircuitDiagramInfo(\n            wire_symbols=(s,),\n            exponent=value.canonicalize_half_turns(self._exponent))\n\n    def __str__(self):\n        info = protocols.circuit_diagram_info(self)\n        if info.exponent == 1:\n            return info.wire_symbols[0]\n        return '{}^{}'.format(info.wire_symbols[0], info.exponent)\n\n    def __repr__(self):\n        args = ['phase_exponent={}'.format(proper_repr(self.phase_exponent))]\n        if self.exponent != 1:\n            args.append('exponent={}'.format(proper_repr(self.exponent)))\n        if self._global_shift != 0:\n            args.append('global_shift={!r}'.format(self._global_shift))\n        return 'cirq.PhasedXPowGate({})'.format(', '.join(args))\n\n    def _period(self):\n        exponents = [self._global_shift, 1 + self._global_shift]\n        real_periods = [abs(2/e) for e in exponents if e != 0]\n        int_periods = [int(np.round(e)) for e in real_periods]\n        if any(i != r for i, r in zip(real_periods, int_periods)):\n            return None\n        if len(int_periods) == 1:\n            return int_periods[0]\n        return int_periods[0] * int_periods[1] / math.gcd(*int_periods)\n\n    @property\n    def _canonical_exponent(self):\n        period = self._period()\n        if not period or isinstance(self._exponent, sympy.Symbol):\n            return self._exponent\n        else:\n            return self._exponent % period\n\n    def _value_equality_values_(self):\n        return self.phase_exponent, self._canonical_exponent, self._global_shift\n", "path": "cirq/ops/phased_x_gate.py"}]}