nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: rigetticomputing/pyquil
Pull request #287 (2018-02-02 17:15:43)

Remove dangling input from commuting_set method
Removes number of qubits input for the `commuting_set` method in
pyquil.paulis


Patch:
diff --git a/pyquil/paulis.py b/pyquil/paulis.py
index c1efd58..4990b0f 100644
--- a/pyquil/paulis.py
+++ b/pyquil/paulis.py
@@ -617,7 +617,7 @@ def check_commutation(pauli_list, pauli_two):
     return True
 
 
-def commuting_sets(pauli_terms, nqubits):
+def commuting_sets(pauli_terms):
     """Gather the Pauli terms of pauli_terms variable into commuting sets
 
     Uses algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011)


Test patch:
diff --git a/pyquil/tests/test_paulis.py b/pyquil/tests/test_paulis.py
index 3d3e6d6..c5c3e35 100644
--- a/pyquil/tests/test_paulis.py
+++ b/pyquil/tests/test_paulis.py
@@ -467,7 +467,7 @@ def test_commuting_sets():
     term2 = PauliTerm("Y", 0) * PauliTerm("Y", 1)
     term3 = PauliTerm("Y", 0) * PauliTerm("Z", 2)
     pauli_sum = term1 + term2 + term3
-    commuting_sets(pauli_sum, 3)
+    commuting_sets(pauli_sum)
 
 
 def test_paulisum_iteration():
Repository: rigetticomputing/pyquil
Pull request #288 (2018-02-02 20:55:55)

Function to return wavefunction probabilities as an array

stevenheidel: It'd be cool if you changed Wavefunction.zeros to also return a numpy array
mpharrigan: done

Patch:
diff --git a/pyquil/wavefunction.py b/pyquil/wavefunction.py
index 064c1e8..3b06c0f 100644
--- a/pyquil/wavefunction.py
+++ b/pyquil/wavefunction.py
@@ -33,7 +33,7 @@ class Wavefunction(object):
         if len(amplitude_vector) == 0 or len(amplitude_vector) & (len(amplitude_vector) - 1) != 0:
             raise TypeError("Amplitude vector must have a length that is a power of two")
 
-        self.amplitudes = amplitude_vector
+        self.amplitudes = np.asarray(amplitude_vector)
         self.classical_memory = classical_memory
 
     @staticmethod
@@ -50,9 +50,9 @@ class Wavefunction(object):
         :return: A Wavefunction in the ground state
         :rtype: Wavefunction
         """
-        container = [0] * (2**qubit_num)
-        container[0] = 1.0
-        return Wavefunction(container)
+        amplitude_vector = np.zeros(2**qubit_num)
+        amplitude_vector[0] = 1.0
+        return Wavefunction(amplitude_vector)
 
     @staticmethod
     def from_bit_packed_string(coef_string, classical_addresses):
@@ -101,6 +101,10 @@ class Wavefunction(object):
     def __str__(self):
         return self.pretty_print(decimal_digits=10)
 
+    def probabilities(self):
+        """Returns an array of probabilities in lexicographical order"""
+        return np.abs(self.amplitudes) ** 2
+
     def get_outcome_probs(self):
         """
         Parses a wavefunction (array of complex amplitudes) and returns a dictionary of


Test patch:
diff --git a/pyquil/tests/test_wavefunction.py b/pyquil/tests/test_wavefunction.py
index 77ab9be..64f7ec2 100644
--- a/pyquil/tests/test_wavefunction.py
+++ b/pyquil/tests/test_wavefunction.py
@@ -1,5 +1,6 @@
 import pytest
 import numpy as np
+import itertools
 
 from pyquil.wavefunction import get_bitstring_from_index, Wavefunction, _round_to_next_multiple, _octet_bits
 
@@ -56,3 +57,13 @@ def test_octet_bits():
     assert [0, 1, 0, 0, 0, 0, 0, 0] == _octet_bits(0b10)
     assert [1, 0, 1, 0, 0, 0, 0, 0] == _octet_bits(0b101)
     assert [1, 1, 1, 1, 1, 1, 1, 1] == _octet_bits(0b11111111)
+
+
+def test_probabilities(wvf):
+    n_qubits = 2
+    bitstrings = [list(x) for x in itertools.product((0, 1), repeat=n_qubits)]
+    prob_keys = [''.join(str(b) for b in bs) for bs in bitstrings]
+    prob_dict = wvf.get_outcome_probs()
+    probs1 = np.array([prob_dict[x] for x in prob_keys])
+    probs2 = wvf.probabilities()
+    np.testing.assert_array_equal(probs1, probs2)
Repository: rigetticomputing/pyquil
Pull request #301 (2018-02-08 18:10:04)

Sample from wavefunction
Also ensure normalization and fix tests that weren't normalized


Patch:
diff --git a/pyquil/wavefunction.py b/pyquil/wavefunction.py
index 3b06c0f..f28149e 100644
--- a/pyquil/wavefunction.py
+++ b/pyquil/wavefunction.py
@@ -3,6 +3,7 @@ Module containing the Wavefunction object and methods for working with wavefunct
 """
 import struct
 import warnings
+import itertools
 
 import numpy as np
 from six import integer_types
@@ -34,6 +35,11 @@ class Wavefunction(object):
             raise TypeError("Amplitude vector must have a length that is a power of two")
 
         self.amplitudes = np.asarray(amplitude_vector)
+        sumprob = np.sum(self.probabilities())
+        if not np.isclose(sumprob, 1.0):
+            raise ValueError("The wavefunction is not normalized. "
+                             "The probabilities sum to {} instead of 1".format(sumprob))
+
         self.classical_memory = classical_memory
 
     @staticmethod
@@ -183,6 +189,18 @@ class Wavefunction(object):
         plt.xticks(range(len(prob_dict)), prob_dict.keys())
         plt.show()
 
+    def sample_bitstrings(self, n_samples):
+        """
+        Sample bitstrings from the distribution defined by the wavefunction.
+
+        :param n_samples: The number of bitstrings to sample
+        :return: An array of shape (n_samples, n_qubits)
+        """
+        possible_bitstrings = np.array(list(itertools.product((0, 1), repeat=len(self))))
+        inds = np.random.choice(2 ** len(self), n_samples, p=self.probabilities())
+        bitstrings = possible_bitstrings[inds, :]
+        return bitstrings
+
 
 def get_bitstring_from_index(index, qubit_num):
     """


Test patch:
diff --git a/pyquil/tests/test_wavefunction.py b/pyquil/tests/test_wavefunction.py
index 64f7ec2..cb23252 100644
--- a/pyquil/tests/test_wavefunction.py
+++ b/pyquil/tests/test_wavefunction.py
@@ -7,7 +7,9 @@ from pyquil.wavefunction import get_bitstring_from_index, Wavefunction, _round_t
 
 @pytest.fixture()
 def wvf():
-    return Wavefunction(np.array([1.0, 1.j, 0.000005, 0.02]))
+    amps = np.array([1.0, 1.j, 0.000005, 0.02])
+    amps /= np.sqrt(np.sum(np.abs(amps)**2))
+    return Wavefunction(amps)
 
 
 def test_get_bitstring_from_index():
@@ -24,9 +26,9 @@ def test_parsers(wvf):
 
     pp_wvf = wvf.pretty_print()
     # this should round out one outcome
-    assert pp_wvf == "(1+0j)|00> + 1j|01> + (0.02+0j)|11>"
+    assert pp_wvf == "(0.71+0j)|00> + 0.71j|01> + (0.01+0j)|11>"
     pp_wvf = wvf.pretty_print(1)
-    assert pp_wvf == "(1+0j)|00> + 1j|01>"
+    assert pp_wvf == "(0.7+0j)|00> + 0.7j|01>"
 
     pp_probs = wvf.pretty_print_probabilities()
     # this should round out two outcomes
@@ -67,3 +69,11 @@ def test_probabilities(wvf):
     probs1 = np.array([prob_dict[x] for x in prob_keys])
     probs2 = wvf.probabilities()
     np.testing.assert_array_equal(probs1, probs2)
+
+    assert np.sum(probs2) == 1.0
+
+
+def test_sample(wvf):
+    bitstrings = wvf.sample_bitstrings(n_samples=100)
+    assert bitstrings.shape == (100, 2)
+    assert [0, 0] in bitstrings
Repository: rigetticomputing/pyquil
Pull request #335 (2018-02-15 23:16:26)

Bugfix/add rx pi to xhalves gates
This is necessary for running the spec-based noise model generation tool


Patch:
diff --git a/pyquil/device.py b/pyquil/device.py
index 8a2ad9b..8f56a3e 100644
--- a/pyquil/device.py
+++ b/pyquil/device.py
@@ -139,6 +139,8 @@ def gates_in_isa(isa):
                 Gate("I", [], [unpack_qubit(q.id)]),
                 Gate("RX", [np.pi / 2], [unpack_qubit(q.id)]),
                 Gate("RX", [-np.pi / 2], [unpack_qubit(q.id)]),
+                Gate("RX", [np.pi], [unpack_qubit(q.id)]),
+                Gate("RX", [-np.pi], [unpack_qubit(q.id)]),
                 Gate("RZ", [THETA], [unpack_qubit(q.id)]),
             ])
         else:  # pragma no coverage


Test patch:
diff --git a/pyquil/tests/test_device.py b/pyquil/tests/test_device.py
index 64e3b0e..c3ada22 100644
--- a/pyquil/tests/test_device.py
+++ b/pyquil/tests/test_device.py
@@ -188,7 +188,7 @@ def test_gates_in_isa(isa_dict):
     isa = ISA.from_dict(isa_dict)
     gates = gates_in_isa(isa)
     for q in [0, 1, 2]:
-        for g in [I, RX(np.pi / 2), RX(-np.pi / 2), RZ(THETA)]:
+        for g in [I, RX(np.pi / 2), RX(-np.pi / 2), RX(np.pi), RX(-np.pi), RZ(THETA)]:
             assert g(q) in gates
 
     assert CZ(0, 1) in gates
Repository: rigetticomputing/pyquil
Pull request #349 (2018-02-22 15:22:13)

Program constructor accepts generator as well as list (#265)
This commit tries to solve the issue (#265) by including an extra if condition which detects generators by type checking in the Program constructor.

stevenheidel: @sethuiyer - thanks for your contribution, this looks awesome!

Patch:
diff --git a/pyquil/quil.py b/pyquil/quil.py
index 8052ae1..e9d78f6 100644
--- a/pyquil/quil.py
+++ b/pyquil/quil.py
@@ -19,6 +19,7 @@ Module for creating and defining Quil programs.
 import warnings
 from itertools import count
 from math import pi
+import types
 
 import numpy as np
 from six import string_types
@@ -73,6 +74,7 @@ class Program(object):
             >>> p.inst(H(0)) # A single instruction
             >>> p.inst(H(0), H(1)) # Multiple instructions
             >>> p.inst([H(0), H(1)]) # A list of instructions
+            >>> p.inst(H(i) for i in range(4)) # A generator of instructions
             >>> p.inst(("H", 1)) # A tuple representing an instruction
             >>> p.inst("H 0") # A string representing an instruction
             >>> q = Program()
@@ -88,6 +90,8 @@ class Program(object):
         for instruction in instructions:
             if isinstance(instruction, list):
                 self.inst(*instruction)
+            elif isinstance(instruction, types.GeneratorType):
+                self.inst(*instruction)
             elif isinstance(instruction, tuple):
                 if len(instruction) == 0:
                     raise ValueError("tuple should have at least one element")


Test patch:
diff --git a/pyquil/tests/test_quil.py b/pyquil/tests/test_quil.py
index 05ab69d..535904a 100644
--- a/pyquil/tests/test_quil.py
+++ b/pyquil/tests/test_quil.py
@@ -133,6 +133,10 @@ def test_iteration():
     program = Program(gate_list)
     for ii, instruction in enumerate(program):
         assert instruction == gate_list[ii]
+    gate_generator = (gate_list[ii] for ii in range(3))   # https://github.com/rigetticomputing/pyquil/issues/265
+    program = Program(gate_generator)
+    for ii, instruction in enumerate(program):
+        assert instruction == gate_list[ii]
 
 
 def test_program_plus_program():
Repository: rigetticomputing/pyquil
Pull request #353 (2018-03-07 21:47:59)

Allow PauliTerm qubit indices to be numpy.int{8,16,32,64}
This fixes an annoying issue that crops up when constructing PauliTerm's with bespoke numpy integer type indices.

stevenheidel: Can't wait to drop Python 2 support

Patch:
diff --git a/pyquil/paulis.py b/pyquil/paulis.py
index 4990b0f..72286ff 100644
--- a/pyquil/paulis.py
+++ b/pyquil/paulis.py
@@ -26,7 +26,7 @@ from .gates import H, RZ, RX, CNOT, X, PHASE, STANDARD_GATES
 from numbers import Number
 from collections import Sequence
 import warnings
-from six import integer_types
+from six import integer_types as six_integer_types
 from six.moves import range
 
 PAULI_OPS = ["X", "Y", "Z", "I"]
@@ -47,6 +47,10 @@ class UnequalLengthWarning(Warning):
         super(UnequalLengthWarning, self).__init__(*args, **kwargs)
 
 
+integer_types = six_integer_types + (np.int64, np.int32, np.int16, np.int8)
+"""Explicitly include numpy integer dtypes (for python 3)."""
+
+
 class PauliTerm(object):
     """A term is a product of Pauli operators operating on different qubits.
     """


Test patch:
diff --git a/pyquil/tests/test_paulis.py b/pyquil/tests/test_paulis.py
index c5c3e35..f0c37e3 100644
--- a/pyquil/tests/test_paulis.py
+++ b/pyquil/tests/test_paulis.py
@@ -561,3 +561,10 @@ def test_from_list():
     with pytest.raises(ValueError):
         # terms are not on disjoint qubits
         pterm = PauliTerm.from_list([("X", 0), ("Y", 0)])
+
+
+def test_numpy_integer_types():
+    idx_np, = np.arange(1, dtype=np.int64)
+    assert isinstance(idx_np, np.int64)
+    # on python 3 this fails unless explicitly allowing for numpy integer types
+    PauliTerm("X", idx_np)
Repository: rigetticomputing/pyquil
Pull request #688 (2018-11-12 14:18:15)

QVM docs typo
There is a typo when .run() method is called


Patch:
diff --git a/docs/source/qvm.rst b/docs/source/qvm.rst
index 38527cf..ddf4e9e 100644
--- a/docs/source/qvm.rst
+++ b/docs/source/qvm.rst
@@ -69,7 +69,7 @@ Remember to also start up a ``quilc`` compiler server, too, with ``quilc -S``.
     p += MEASURE(1, ro[1])
     p.wrap_in_numshots_loop(5)
     executable = qc.compile(p)
-    results = qvm.run(executable)
+    results = qc.run(executable)
     print(results)
 
 The results returned are a *list of lists of integers*. In the above case, that's
diff --git a/pyquil/_parser/PyQuilListener.py b/pyquil/_parser/PyQuilListener.py
index 0c07ee2..39d5b08 100644
--- a/pyquil/_parser/PyQuilListener.py
+++ b/pyquil/_parser/PyQuilListener.py
@@ -128,11 +128,12 @@ class PyQuilListener(QuilListener):
         circuit_name = ctx.name().getText()
         variables = [variable.getText() for variable in ctx.variable()]
         qubitVariables = [qubitVariable.getText() for qubitVariable in ctx.qubitVariable()]
+        space = ' ' if qubitVariables else ''
 
         if variables:
-            raw_defcircuit = 'DEFCIRCUIT {}({}) {}:'.format(circuit_name, ', '.join(variables), ' '.join(qubitVariables))
+            raw_defcircuit = 'DEFCIRCUIT {}({}){}{}:'.format(circuit_name, ', '.join(variables), space, ' '.join(qubitVariables))
         else:
-            raw_defcircuit = 'DEFCIRCUIT {} {}:'.format(circuit_name, ' '.join(qubitVariables))
+            raw_defcircuit = 'DEFCIRCUIT {}{}{}:'.format(circuit_name, space, ' '.join(qubitVariables))
 
         raw_defcircuit += '\n    '.join([''] + [instr.out() for instr in self.result])
         self.previous_result.append(RawInstr(raw_defcircuit))


Test patch:
diff --git a/pyquil/tests/test_parser.py b/pyquil/tests/test_parser.py
index a37adaa..7994e78 100644
--- a/pyquil/tests/test_parser.py
+++ b/pyquil/tests/test_parser.py
@@ -212,8 +212,14 @@ def test_def_circuit():
 DEFCIRCUIT bell a b:
     H a
     CNOT a b
+""".strip()
+    defcircuit_no_qubits = """
+DEFCIRCUIT bell:
+    H 0
+    CNOT 0 1
 """.strip()
     parse_equals(defcircuit, RawInstr(defcircuit))
+    parse_equals(defcircuit_no_qubits, RawInstr(defcircuit_no_qubits))
 
 
 def test_parse_reset_qubit():