internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: quantumlib/Cirq

Issue:
Broken Hadamard gate decomposition
Steps to reproduce:

```
In [1]: import cirq                                                                                                                                                            

In [2]: q = cirq.NamedQubit('q')                                                                                                                                               

In [3]: cirq.Circuit.from_ops(cirq.decompose([cirq.H(q)]))._unitary_()                                                                                                         
Out[3]: 
array([[ 0.5+0.5j,  0.5+0.5j],
       [ 0.5+0.5j, -0.5-0.5j]])

In [4]: cirq.Circuit.from_ops([cirq.H(q)])._unitary_()                                                                                                                         
Out[4]: 
array([[ 0.70710678+0.j,  0.70710678+0.j],
       [ 0.70710678+0.j, -0.70710678+0.j]])
```

Note that exponentiating the gate to a power different from 1.0 makes this work, suggesting a special casing of a decomposition is the culprit.

This affects other gates whose decomposition includes Hadamards (e.g. iSwaps). 

There is a unit test that compares the unitary given by the gate and by its decomposition, but the assert it uses makes the comparison merely up to global phase. I think this is incorrect. Consider two qubits q0 and q1 and a circuit that applies U0 to q0 and U1 to q1. Suppose that the decomposition of U0 yields a unitary that is consistent with U0 merely up to global phase. What happens we you replace U0 with its decomposition? Well, this alters the *relative* phase between q0 and q1 producing observable effect.


Discussion:

Resolving patch:
diff --git a/cirq/ops/common_gates.py b/cirq/ops/common_gates.py
--- a/cirq/ops/common_gates.py
+++ b/cirq/ops/common_gates.py
@@ -518,7 +518,8 @@ def _decompose_(self, qubits):
         q = qubits[0]
 
         if self._exponent == 1:
-            yield Y(q)**0.5, X(q)
+            yield cirq.Y(q)**0.5
+            yield cirq.XPowGate(global_shift=-0.25).on(q)
             return
 
         yield Y(q)**0.25


Test patch:
diff --git a/cirq/testing/consistent_decomposition.py b/cirq/testing/consistent_decomposition.py
--- a/cirq/testing/consistent_decomposition.py
+++ b/cirq/testing/consistent_decomposition.py
@@ -14,8 +14,9 @@
 
 from typing import Any
 
+import numpy as np
+
 from cirq import protocols, ops, line, circuits
-from cirq.testing import lin_alg_utils
 
 
 def assert_decompose_is_consistent_with_unitary(val: Any):
@@ -36,6 +37,4 @@ def assert_decompose_is_consistent_with_unitary(val: Any):
     actual = circuits.Circuit.from_ops(dec).to_unitary_matrix(
         qubit_order=qubits)
 
-    lin_alg_utils.assert_allclose_up_to_global_phase(actual,
-                                                     expected,
-                                                     atol=1e-8)
+    assert np.allclose(actual, expected, atol=1e-8)
Repository: quantumlib/Cirq

Issue:
Make the table in cirq.SimulationTrialResult's doc string render as a table on readthedocs



Discussion:

Resolving patch:
diff --git a/cirq/sim/simulator.py b/cirq/sim/simulator.py
--- a/cirq/sim/simulator.py
+++ b/cirq/sim/simulator.py
@@ -209,17 +209,18 @@ class SimulationTrialResult:
                  qubit ordering: [QubitA, QubitB, QubitC]
             Then the returned vector will have indices mapped to qubit basis
             states like the following table
-                   |   | QubitA | QubitB | QubitC |
-                   +---+--------+--------+--------+
-                   | 0 |   0    |   0    |   0    |
-                   | 1 |   0    |   0    |   1    |
-                   | 2 |   0    |   1    |   0    |
-                   | 3 |   0    |   1    |   1    |
-                   | 4 |   1    |   0    |   0    |
-                   | 5 |   1    |   0    |   1    |
-                   | 6 |   1    |   1    |   0    |
-                   | 7 |   1    |   1    |   1    |
-                   +---+--------+--------+--------+
+
+                        | QubitA | QubitB | QubitC
+                    :-: | :----: | :----: | :----:
+                     0  |   0    |   0    |   0
+                     1  |   0    |   0    |   1
+                     2  |   0    |   1    |   0
+                     3  |   0    |   1    |   1
+                     4  |   1    |   0    |   0
+                     5  |   1    |   0    |   1
+                     6  |   1    |   1    |   0
+                     7  |   1    |   1    |   1
+
     """
 
     def __init__(self,


Test patch:
Repository: quantumlib/Cirq

Issue:
Circuit.insert should validate all operations before inserting any of them
Given an operation tree that contains some bad operations, the current behavior would insert some of the earlier ones until it encountered a bad one.


Discussion:
We should add a test that detects this being broken in the future. You want to do nothing when the insert will fail.
Like `Circuit.batch_insert`.

Resolving patch:
diff --git a/cirq/circuits/circuit.py b/cirq/circuits/circuit.py
--- a/cirq/circuits/circuit.py
+++ b/cirq/circuits/circuit.py
@@ -808,22 +808,27 @@ def insert(
         Raises:
             ValueError: Bad insertion strategy.
         """
-        moments_and_operations = ops.flatten_op_tree(
+        moments_and_operations = list(ops.flatten_op_tree(
             ops.transform_op_tree(moment_or_operation_tree,
                                   self._device.decompose_operation,
                                   preserve_moments=True),
-            preserve_moments=True
-        )
+            preserve_moments=True))
+
+        for moment_or_op in moments_and_operations:
+            if isinstance(moment_or_operation_tree, ops.Moment):
+                self._device.validate_moment(cast(ops.Moment, moment_or_op))
+            else:
+                self._device.validate_operation(
+                    cast(ops.Operation, moment_or_op))
+
         # limit index to 0..len(self._moments), also deal with indices smaller 0
         k = max(min(index if index >= 0 else len(self._moments) + index,
                     len(self._moments)), 0)
         for moment_or_op in moments_and_operations:
             if isinstance(moment_or_op, ops.Moment):
-                self._device.validate_moment(moment_or_op)
                 self._moments.insert(k, moment_or_op)
                 k += 1
             else:
-                self._device.validate_operation(moment_or_op)
                 p = self._pick_or_create_inserted_op_moment_index(
                     k, moment_or_op, strategy)
                 while p >= len(self._moments):


Test patch:
diff --git a/cirq/circuits/circuit_test.py b/cirq/circuits/circuit_test.py
--- a/cirq/circuits/circuit_test.py
+++ b/cirq/circuits/circuit_test.py
@@ -499,6 +499,17 @@ def test_insert_moment():
         assert c.operation_at(qubit, actual_index) == operation[0]
 
 
+def test_insert_validates_all_operations_before_inserting():
+    a, b = cirq.GridQubit(0, 0), cirq.GridQubit(1, 1)
+    c = Circuit(device=cg.Foxtail)
+    operations = [cirq.Z(a), cirq.CZ(a, b)]
+
+    with pytest.raises(ValueError, match='Non-local interaction'):
+        c.insert(0, operations)
+
+    assert len(c) == 0
+
+
 def test_insert_inline_near_start():
     a = cirq.NamedQubit('a')
     b = cirq.NamedQubit('b')
Repository: quantumlib/Cirq

Issue:
Doc string of CZPowGate: definition of g
The doc string states that the unitary matrix of `CZPowGate(exponent=t)` is:

    [[1, 0, 0, 0],
     [0, 1, 0, 0],
     [0, 0, 1, 0],
     [0, 0, 0, g]]

where `g = exp(i·π·t/2)`.


When I try `cirq.CZPowGate(exponent=1.)._unitary_()`, it gives

    array([[ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j,  0.+0.j, -1.+0.j]])

It appears that the factor g should be `g = exp(i·π·t)` instead, which seems also consistent with the circuit generated from the gate.

PS: I am on cirq v0.4.0.


Discussion:

Resolving patch:
diff --git a/cirq/ops/common_gates.py b/cirq/ops/common_gates.py
--- a/cirq/ops/common_gates.py
+++ b/cirq/ops/common_gates.py
@@ -704,7 +704,7 @@ class CZPowGate(eigen_gate.EigenGate,
 
     where:
 
-        g = exp(i·π·t/2).
+        g = exp(i·π·t).
 
     `cirq.CZ`, the controlled Z gate, is an instance of this gate at
     `exponent=1`.


Test patch:
Repository: quantumlib/Cirq

Issue:
Fix `cirq.control` documentation talking about `__control__` instead of `controlled_by`



Discussion:

Resolving patch:
diff --git a/cirq/protocols/control.py b/cirq/protocols/control.py
--- a/cirq/protocols/control.py
+++ b/cirq/protocols/control.py
@@ -35,7 +35,7 @@ def control(controllee: Union['cirq.Gate', op_tree.OP_TREE],
     """Returns a Controlled version of the given value, if defined.
 
     Controllees define how to be controlled by defining a method
-    __control__(self, control_qubits). Note that the method may return
+    controlled_by(self, control_qubits). Note that the method may return
     NotImplemented to indicate a particular controlling can't be done.
 
     Args:
@@ -46,13 +46,13 @@ def control(controllee: Union['cirq.Gate', op_tree.OP_TREE],
             fallback occurs, a TypeError is raised instead.
 
     Returns:
-        If `controllee` has a __control__ method that returns something besides
-        NotImplemented, that result is returned. For an OP_TREE, transformation
-        is applied at the leaf. Otherwise, if a default value was specified,
-        the default value is returned.
+        If `controllee` has a controlled_by method that returns something
+        besides NotImplemented, that result is returned. For an OP_TREE,
+        transformation is applied at the leaf. Otherwise, if a default value
+        was specified, the default value is returned.
 
     Raises:
-        TypeError: `controllee` doesn't have a __control__ method (or that
+        TypeError: `controllee` doesn't have a controlled_by method (or that
             method returned NotImplemented) and no `default` was specified.
     """
     if control_qubits is None:


Test patch:
diff --git a/cirq/protocols/control_test.py b/cirq/protocols/control_test.py
--- a/cirq/protocols/control_test.py
+++ b/cirq/protocols/control_test.py
@@ -43,7 +43,7 @@ def test_controlless(controllee):
     assert cirq.protocols.control(controllee, [p,q], None) is None
 
 
-def test_control_error():
+def test_controlled_by_error():
     with pytest.raises(TypeError, match="returned NotImplemented"):
         _ = cirq.protocols.control(ReturnsNotImplemented(), [p])
     with pytest.raises(TypeError, match="no controlled_by method"):
Repository: quantumlib/Cirq

Issue:
Two circuit diagram tests that rest in `contrib` are failing on Windows
See: https://travis-ci.com/quantumlib/Cirq/jobs/202641395


Discussion:

Resolving patch:
diff --git a/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py b/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py
--- a/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py
+++ b/cirq/contrib/paulistring/convert_to_pauli_string_phasors.py
@@ -40,7 +40,7 @@ class ConvertToPauliStringPhasors(PointOptimizer):
     def __init__(self,
                  ignore_failures: bool = False,
                  keep_clifford: bool = False,
-                 atol: float = 0) -> None:
+                 atol: float = 1e-14) -> None:
         """
         Args:
             ignore_failures: If set, gates that fail to convert are forwarded


Test patch:
Repository: quantumlib/Cirq

Issue:
PhasedXPowGate raised to a symbol power fails is_parameterized protocol
The following 
```
g = cirq.PhasedXPowGate(exponent=0.1, phase_exponent=0.2)
val = cirq.is_parameterized(g ** sympy.Symbol('s'))
```
has val False.  Compared with 
```
h = cirq.XPowGate(exponent=0.1)
val = cirq.is_parameterized(h ** sympy.Symbol('s'))
```
which has val True.  


Discussion:

Resolving patch:
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
@@ -156,8 +156,8 @@ def _pauli_expansion_(self) -> value.LinearDict[str]:
 
     def _is_parameterized_(self) -> bool:
         """See `cirq.SupportsParameterization`."""
-        return (isinstance(self._exponent, sympy.Symbol) or
-                isinstance(self._phase_exponent, sympy.Symbol))
+        return (protocols.is_parameterized(self._exponent) or
+                protocols.is_parameterized(self._phase_exponent))
 
     def _resolve_parameters_(self, param_resolver) -> 'PhasedXPowGate':
         """See `cirq.SupportsParameterization`."""
diff --git a/cirq/value/periodic_value.py b/cirq/value/periodic_value.py
--- a/cirq/value/periodic_value.py
+++ b/cirq/value/periodic_value.py
@@ -16,8 +16,8 @@
 
 import sympy
 
+from cirq import protocols
 from cirq._compat import proper_repr
-import cirq.protocols
 
 
 class PeriodicValue:
@@ -75,12 +75,13 @@ def _approx_eq_(self, other: Any, atol: float) -> bool:
         if high - low > self.period / 2:
             low += self.period
 
-        return cirq.protocols.approx_eq(low, high, atol=atol)
+        return protocols.approx_eq(low, high, atol=atol)
 
     def __repr__(self):
         return 'cirq.PeriodicValue({}, {})'.format(proper_repr(self.value),
                                                    proper_repr(self.period))
 
     def _is_parameterized_(self):
-        return any(isinstance(val, sympy.Basic)
-                   for val in (self.value, self.period))
+        return any(
+            protocols.is_parameterized(val)
+            for val in (self.value, self.period))


Test patch:
diff --git a/cirq/ops/phased_x_gate_test.py b/cirq/ops/phased_x_gate_test.py
--- a/cirq/ops/phased_x_gate_test.py
+++ b/cirq/ops/phased_x_gate_test.py
@@ -170,11 +170,16 @@ def test_parameterize():
     ) is NotImplemented
     assert cirq.unitary(parameterized_gate, default=None) is None
     assert cirq.is_parameterized(parameterized_gate)
+
     resolver = cirq.ParamResolver({'a': 0.1, 'b': 0.2})
     resolved_gate = cirq.resolve_parameters(parameterized_gate, resolver)
     assert resolved_gate == cirq.PhasedXPowGate(exponent=0.1,
                                                 phase_exponent=0.2)
 
+    unparameterized_gate = cirq.PhasedXPowGate(exponent=0.1, phase_exponent=0.2)
+    assert not cirq.is_parameterized(unparameterized_gate)
+    assert cirq.is_parameterized(unparameterized_gate**sympy.Symbol('a'))
+
 
 def test_trace_bound():
     assert cirq.trace_distance_bound(cirq.PhasedXPowGate(
Repository: quantumlib/Cirq

Issue:
QubitOrder.explicit fails when given an iterator
Also affects `QubitOrder.as_qubit_order()`.  I believe the issue is on line 77 of cirq/ops/qubit_order.py.

Example:
```
cirq.QubitOrder.as_qubit_order(reversed(cirq.LineQubit.range(5))).order_for(
    (cirq.LineQubit(3),))
```

The example raises `ValueError: Unexpected extra qubits: {cirq.LineQubit(3)}.` because `reversed()` is an iterator and QubitOrder tried to iterate it twice.


Discussion:

Resolving patch:
diff --git a/cirq/ops/qubit_order.py b/cirq/ops/qubit_order.py
--- a/cirq/ops/qubit_order.py
+++ b/cirq/ops/qubit_order.py
@@ -74,7 +74,7 @@ def explicit(fixed_qubits: Iterable[raw_types.Qid],
                 'Qubits appear in fixed_order twice: {}.'.format(result))
 
         def func(qubits):
-            remaining = set(qubits) - set(fixed_qubits)
+            remaining = set(qubits) - set(result)
             if not remaining:
                 return result
             if not fallback:


Test patch:
diff --git a/cirq/ops/qubit_order_test.py b/cirq/ops/qubit_order_test.py
--- a/cirq/ops/qubit_order_test.py
+++ b/cirq/ops/qubit_order_test.py
@@ -110,3 +110,13 @@ def test_qubit_order_or_list():
     ordered = cirq.QubitOrder.sorted_by(repr)
     passed_through = cirq.QubitOrder.as_qubit_order(ordered)
     assert ordered is passed_through
+
+
+def test_qubit_order_iterator():
+    generator = (q for q in cirq.LineQubit.range(5))
+    assert cirq.QubitOrder.explicit(generator).order_for(
+        (cirq.LineQubit(3),)) == tuple(cirq.LineQubit.range(5))
+
+    generator = (q for q in cirq.LineQubit.range(5))
+    assert cirq.QubitOrder.as_qubit_order(generator).order_for(
+        (cirq.LineQubit(3),)) == tuple(cirq.LineQubit.range(5))
Repository: quantumlib/Cirq

Issue:
Create nice str representation for DensityMatrixTrialResult
It has a repr, but not a good str.

Should work similar to WaveFunctionTrialResult.


Discussion:
I can take a look
Sure thing.

Resolving patch:
diff --git a/cirq/sim/density_matrix_simulator.py b/cirq/sim/density_matrix_simulator.py
--- a/cirq/sim/density_matrix_simulator.py
+++ b/cirq/sim/density_matrix_simulator.py
@@ -620,6 +620,11 @@ def _value_equality_values_(self):
                         sorted(self.measurements.items())}
         return (self.params, measurements, self._final_simulator_state)
 
+    def __str__(self):
+        samples = super().__str__()
+        return 'measurements: {}\nfinal density matrix:\n{}'.format(
+            samples, self.final_density_matrix)
+
     def __repr__(self):
         return ("cirq.DensityMatrixTrialResult(params={!r}, measurements={!r}, "
                 "final_simulator_state={!r})".format(


Test patch:
diff --git a/cirq/sim/density_matrix_simulator_test.py b/cirq/sim/density_matrix_simulator_test.py
--- a/cirq/sim/density_matrix_simulator_test.py
+++ b/cirq/sim/density_matrix_simulator_test.py
@@ -656,3 +656,17 @@ def test_works_on_pauli_string():
     np.testing.assert_allclose(result.reshape(4, 4),
                                np.diag([0, 0, 0, 1]),
                                atol=1e-8)
+
+
+def test_density_matrix_trial_result_str():
+    q0 = cirq.LineQubit(0)
+    final_simulator_state = cirq.DensityMatrixSimulatorState(
+        density_matrix=np.ones((2, 2)) * 0.5, qubit_map={q0: 0})
+    result = cirq.DensityMatrixTrialResult(
+        params=cirq.ParamResolver({}),
+        measurements={},
+        final_simulator_state=final_simulator_state)
+
+    assert str(result) == ('measurements: (no measurements)\n'
+                           'final density matrix:\n'
+                           '[[0.5 0.5]\n [0.5 0.5]]')
Repository: quantumlib/Cirq

Issue:
Split cirq packages into with/without contrib
Otherwise there's no way to easily pip install the contrib-requirements


Discussion:
setuptools has a feature for this:

setup.py:
```
...
setup(
    ...,
    extras_require = {
        'contrib': [
            '...',  # contrib-requirements
            '...',
        ]
    },
)
```

You can install it with `pip install cirq[contrib]`.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -28,6 +28,10 @@
 # Read in requirements
 requirements = open('requirements.txt').readlines()
 requirements = [r.strip() for r in requirements]
+contrib_requirements = open('cirq/contrib/contrib-requirements.txt').readlines()
+contrib_requirements = [r.strip() for r in contrib_requirements]
+dev_requirements = open('dev_tools/conf/pip-list-dev-tools.txt').readlines()
+dev_requirements = [r.strip() for r in dev_requirements]
 
 cirq_packages = ['cirq'] + [
     'cirq.' + package for package in find_packages(where='cirq')
@@ -40,6 +44,10 @@
       author_email='cirq@googlegroups.com',
       python_requires=('>=3.6.0'),
       install_requires=requirements,
+      extras_require={
+          'contrib': contrib_requirements,
+          'dev': dev_requirements,
+      },
       license='Apache 2',
       description=description,
       long_description=long_description,


Test patch:
Repository: quantumlib/Cirq

Issue:
Handedness between ISwapPowGate and FSim is different.
The ISwapPowGate and FSim gate rotate in different directions on the |01>, |10> subspace.  This feels a bit odd to me. 


Discussion:
This morning I meant to change signs of the angles in fSim only to notice that @maffoo has already done this in #1726. It seems that his PR missed ISwapPowGate. I'll send out a fix soon.
https://quantumcomputing.stackexchange.com/questions/2594/what-is-the-matrix-of-the-iswap-gate

![image](https://user-images.githubusercontent.com/79941/61984533-a98e5a00-afb9-11e9-846d-ec69ff7b3c75.png)


Changing these kinds of conventions is a silent breaking change on our users. The iswap gate has been around for several versions now; we can't just change what it means.

Personally I don't mind so much if iswap is at fsim(-90deg) instead of fsim(+90deg).

**If we want to change this convention, we first need to deprecate iswap for one version then delete it for one version then re-introduce it with the new convention.**

Resolving patch:
diff --git a/cirq/ops/fsim_gate.py b/cirq/ops/fsim_gate.py
--- a/cirq/ops/fsim_gate.py
+++ b/cirq/ops/fsim_gate.py
@@ -53,14 +53,23 @@ class FSimGate(gate_features.TwoQubitGate,
         a = cos(theta)
         b = -i·sin(theta)
         c = exp(-i·phi)
+
+    Note the difference in sign conventions between FSimGate and the
+    ISWAP and CZPowGate:
+
+        FSimGate(θ, φ) = ISWAP**(-2θ/π) CZPowGate(exponent=-φ/π)
     """
 
     def __init__(self, theta: float, phi: float):
         """
         Args:
-            theta: The strength of the XX+YY interaction, in radians.
-            phi: CPhase angle in radians. Determines how much the |11⟩ state is
-                phased.
+            theta: Swap angle on the span(|01⟩, |10⟩) subspace, in radians.
+                Determined by the strength and duration of the XX+YY
+                interaction. Note: uses opposite sign convention to the
+                iSWAP gate.
+            phi: Controlled phase angle, in radians. Determines how much the
+                |11⟩ state is phased. Note: uses opposite sign convention to
+                the CZPowGate.
         """
         self.theta = theta
         self.phi = phi


Test patch:
diff --git a/cirq/ops/fsim_gate_test.py b/cirq/ops/fsim_gate_test.py
--- a/cirq/ops/fsim_gate_test.py
+++ b/cirq/ops/fsim_gate_test.py
@@ -215,3 +215,22 @@ def test_fsim_unitary():
         ]),
         atol=1e-8,
     )
+
+
+@pytest.mark.parametrize('theta, phi', (
+    (0, 0),
+    (0.1, 0.1),
+    (-0.1, 0.1),
+    (0.1, -0.1),
+    (-0.1, -0.1),
+    (np.pi / 2, np.pi / 6),
+    (np.pi, np.pi),
+    (3.5 * np.pi, 4 * np.pi),
+))
+def test_fsim_iswap_cphase(theta, phi):
+    q0, q1 = cirq.NamedQubit('q0'), cirq.NamedQubit('q1')
+    iswap = cirq.ISWAP**(-theta * 2 / np.pi)
+    cphase = cirq.CZPowGate(exponent=-phi / np.pi)
+    iswap_cphase = cirq.Circuit.from_ops((iswap.on(q0, q1), cphase.on(q0, q1)))
+    fsim = cirq.FSimGate(theta=theta, phi=phi)
+    assert np.allclose(cirq.unitary(iswap_cphase), cirq.unitary(fsim))