internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: PennyLaneAI/pennylane

Issue:
Improve the check for whether _heisenberg_rep() is implemented
Having to construct parameters to be able to call self._heisenberg_rep() and then actually construcitng the rep is not a very elegant way of checking whether a heisenberg rep is in principle supported. Can one not do something like `Operation._heisenberg_rep == type(self)._heisenberg_rep` to test whether the method was overwritten?

This litte example suggests this should be possible:
```
class A:
    def m():
        return 'a'

    def check_if_m_overwritten(self):
        return A.m == type(self).m

class B(A):
    pass

class C(A):
    def m():
        return 'b'


b = B()
c = C()

print(b.check_if_m_overwritten())
print(c.check_if_m_overwritten())
```
Output:
```
True
False
```

_Originally posted by @cgogolin in https://github.com/XanaduAI/pennylane/pull/149_


Discussion:
I will do that tomorrow

Resolving patch:
diff --git a/pennylane/operation.py b/pennylane/operation.py
--- a/pennylane/operation.py
+++ b/pennylane/operation.py
@@ -548,19 +548,12 @@ def supports_analytic(self):
     @classproperty
     def supports_heisenberg(self):
         """Returns True if the CV Operation has
-        a defined :meth:`~.CV._heisenberg_rep` static method, indicating
+        a overwritten the :meth:`~.CV._heisenberg_rep` static method
+        defined in :class:`CV`, thereby indicating
         that analytic differentiation is supported if this operation
-        succeeds a gate to be differentiated analytically.
+        succeeds the gate to be differentiated analytically.
         """
-        n = self.num_params
-        if self.par_domain == 'A':
-            pars = [np.eye(2)] * n
-        elif self.par_domain == 'N':
-            pars = [0] * n
-        else:
-            pars = [0.0] * n
-        return self._heisenberg_rep(pars) is not None
-
+        return CV._heisenberg_rep != self._heisenberg_rep
 
 class CVOperation(CV, Operation):
     """Base class for continuous-variable quantum operations."""


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
scipy import bug
#### Issue description
When calling `pennylane.ops.cv.Rotation._heisenberg_rep([phi])` if one does not explicitly import the block_diag function via `from scipy.linalg import block_diag` there is an error.

```pennylane/pennylane/ops/cv.py", line 109, in _rotation
    return sp.linalg.block_diag(1, temp) # pylint: disable=no-member
AttributeError: module 'scipy' has no attribute 'linalg'
````

This is not a bug in scipy as it is a design choice not to import top level components such as `linalg` as they are not sub-modules but directories. Read this [discussion](https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/mMiv9QslB4E).

I encountered this when I wrote an independent test for the ops #99 

#### System information

* **Operating system:**
  MacOS 10.14.3 

* **PennyLane version:**
  master

* **Python version:**
Python 3.7.2 (default, Dec 29 2018, 00:00:04)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin


* **NumPy and SciPy versions:**
  NumPy 1.15.0
  Scipy 1.2.1

* **Installation method:**

  Installed using  `python setup.py develop`on latest master.



Discussion:
Very good catch, this should be changed to `from scipy.linalg import block_diag` wherever it occurs.

Interestingly enough, I have noticed that some Python/SciPy installations allow this, and others do not, and I have not been able to figure out what the deciding factor is. For example, it imports fine on my development system, and on our continuous integration services.
Okay. I will try to figure out where such imports are and make a PR

Resolving patch:
diff --git a/pennylane/ops/cv.py b/pennylane/ops/cv.py
--- a/pennylane/ops/cv.py
+++ b/pennylane/ops/cv.py
@@ -78,7 +78,7 @@
 ~~~~~~~~~~~~
 """
 import numpy as np
-import scipy as sp
+from scipy.linalg import block_diag
 
 from pennylane.operation import CVOperation
 
@@ -106,7 +106,7 @@ def _rotation(phi, bare=False):
     temp = np.array([[c, -s], [s, c]])
     if bare:
         return temp
-    return sp.linalg.block_diag(1, temp) # pylint: disable=no-member
+    return block_diag(1, temp) # pylint: disable=no-member
 
 
 class Rotation(CVOperation):


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
Bug: QubitStateVector function for qubit state preparation 
Hi,
There is some bug or inconsistency in this function. see the file jupyter notebook attached.  
```Python
dev2 = qml.device('default.qubit', wires=2)

@qml.qnode(dev2)
def make_State2(s=None):
    qml.QubitStateVector(s, wires=[0,1])
    return qml.expval.PauliZ(0),qml.expval.PauliZ(1)

state = np.array([1+0.j, 0.j, 0.j, 0-1.j])*np.sqrt(2)
print(state)
make_State2(s=state)
```
output look like this for the function call:
```Python
array([2., 2.])
```
Checking the state using
```python
dev2._state
```
gives the putput:
```python
array([1.41421356, 0.        , 0.        , 0.        ])
```

Q: Is the dev2._state function only showing the real part of the wavefunction.

Q. The expectation values are not correct. The normalization factor of the input state is throwing it off.

[test-QubitStateVector Function.pdf](https://github.com/XanaduAI/pennylane/files/3214078/test-QubitStateVector.Function.pdf)



Discussion:
Thanks @AroosaIjaz, definitely looks like a bug. We'll get on it and try to fix

Resolving patch:
diff --git a/pennylane/plugins/default_qubit.py b/pennylane/plugins/default_qubit.py
--- a/pennylane/plugins/default_qubit.py
+++ b/pennylane/plugins/default_qubit.py
@@ -294,7 +294,7 @@ def pre_apply(self):
 
     def apply(self, operation, wires, par):
         if operation == 'QubitStateVector':
-            state = np.asarray(par[0], dtype=np.float64)
+            state = np.asarray(par[0], dtype=np.complex128)
             if state.ndim == 1 and state.shape[0] == 2**self.num_wires:
                 self._state = state
             else:


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
Missing plot lines in VQE tutorial 
#### Issue description

The second and third plots in the VQE tutorial do not show the plot line of the gradient descent. The legends are shown, however. 

Is this problem coming from making this file a "run" file? 

https://pennylane.readthedocs.io/en/latest/tutorials/pennylane_run_variational_quantum_eigensolver.html#vqe

* *Expected behavior:*

The plots should show the gradient descent on top of the optimization landscape. 




Discussion:
@AroosaIjaz, does the example produce the correct plot when run manually? i.e.,
```console
python examples/pennylane_run_variational_quantum_eigensolver.py
```

Yes the bug is also in the .py file...The line is somehow obscured by the contour plot. When you add a much larger offset to the z-values you suddenly see the lines.

Resolving patch:
diff --git a/examples/pennylane_run_variational_quantum_eigensolver.py b/examples/pennylane_run_variational_quantum_eigensolver.py
--- a/examples/pennylane_run_variational_quantum_eigensolver.py
+++ b/examples/pennylane_run_variational_quantum_eigensolver.py
@@ -172,12 +172,13 @@ def cost(var):
 Y = np.linspace(-3, 3, 20)
 xx, yy = np.meshgrid(X, Y)
 Z = np.array([[cost([x, y]) for x in X] for y in Y]).reshape(len(Y), len(X))
+
 surf = ax.plot_surface(xx, yy, Z, cmap=cm.coolwarm, antialiased=False)
 
 path_z = [cost(var) + 1e-8 for var in var_gd]
 path_x = [v[0] for v in var_gd]
 path_y = [v[1] for v in var_gd]
-ax.plot(path_x, path_y, path_z, c="green", marker=".", label="graddesc")
+ax.plot(path_x, path_y, path_z, c="green", marker=".", label="graddesc", zorder=10)
 
 ax.set_xlabel("v1")
 ax.set_ylabel("v2")
@@ -254,7 +255,7 @@ def cost(var):
 path_z = [cost(var) + 1e-8 for var in var_gd]
 path_x = [v[0] for v in var_gd]
 path_y = [v[1] for v in var_gd]
-ax.plot(path_x, path_y, path_z, c="pink", marker=".", label="graddesc")
+ax.plot(path_x, path_y, path_z, c="pink", marker=".", label="graddesc", zorder=10)
 
 ax.set_xlabel("v1")
 ax.set_ylabel("v2")


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
Investigate alternate matrix pseudo-inverse functions
The QGT optimizer makes use of the matrix pseudo-inverse, via the `scipy.linalg.pinv` function. However, there are several alternative functions we could also use:

* https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinv.html
* https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinv2.html
* https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinvh.html

In the case of commuting generators, the block diag metric tensor will be symmetric, so `pinvh`  might be more efficient/stable. This is something worth investigating.



Discussion:

Resolving patch:
diff --git a/pennylane/optimize/qng.py b/pennylane/optimize/qng.py
--- a/pennylane/optimize/qng.py
+++ b/pennylane/optimize/qng.py
@@ -126,7 +126,7 @@ def step(self, qnode, x, recompute_tensor=True):
         if recompute_tensor or self.metric_tensor is None:
             # pseudo-inverse metric tensor
             metric_tensor = qnode.metric_tensor(x, diag_approx=self.diag_approx)
-            self.metric_tensor_inv = linalg.pinv(metric_tensor)
+            self.metric_tensor_inv = linalg.pinvh(metric_tensor)
 
         g = self.compute_grad(qnode, x)
         x_out = self.apply_grad(g, x)


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
__str__ and __repr__ incorrect in Device class
* *Expected behavior:* ``__str__`` and ``__repr__`` should produce useful strings

* *Actual behavior:* They produce strings where most entries are blank:
```
>>> dev = qml.device('default.qubit', 4)
>>> print(dev.__str__())
Default qubit PennyLane plugin
Name: 
API version: 
Plugin version: 
Author: 
>>>print(dev.__repr__())
pennylane.plugins.default_qubit.
Instance: 

```

* *Reproduces how often:* on every device that inherits from the base class without overwriting these methods


Discussion:
This is an embarrassing bug, looks like the `{}` were never placed in the format string!

```python
def __repr__(self):
    """String representation."""
    return "{}.\nInstance: ".format(self.__module__, self.__class__.__name__, self.name)

def __str__(self):
    """Verbose string representation."""
    return "{}\nName: \nAPI version: \nPlugin version: \nAuthor: ".format(
        self.name, self.pennylane_requires, self.version, self.author
    )
```

Resolving patch:
diff --git a/pennylane/_device.py b/pennylane/_device.py
--- a/pennylane/_device.py
+++ b/pennylane/_device.py
@@ -62,12 +62,20 @@ def __init__(self, wires=1, shots=1000):
 
     def __repr__(self):
         """String representation."""
-        return "{}.\nInstance: ".format(self.__module__, self.__class__.__name__, self.name)
+        return "<{} device (wires={}, shots={}) at {}>".format(
+            self.__class__.__name__, self.num_wires, self.shots, hex(id(self))
+        )
 
     def __str__(self):
         """Verbose string representation."""
-        return "{}\nName: \nAPI version: \nPlugin version: \nAuthor: ".format(
-            self.name, self.pennylane_requires, self.version, self.author
+        return "{}\nShort name: {}\nPackage: {}\nPlugin version: {}\nAuthor: {}\nWires: {}\nShots: {}".format(
+            self.name,
+            self.short_name,
+            self.__module__.split(".")[0],
+            self.version,
+            self.author,
+            self.num_wires,
+            self.shots,
         )
 
     @property


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
outdated link in web documentation
#### Issue description

Description of the issue - 
outdated link in this webpage
https://pennylane.readthedocs.io/en/stable/development/guide/adr.html

quote: If you are unsure if a change requires an ADR proposal or not, please open a [GitHub issue](https://github.com/XanaduAI/pennylane/issue)

* *Expected behavior:* (What you expect to happen)
[GitHub issue] (https://github.com/PennyLaneAI/pennylane/issues)
* *Actual behavior:* (What actually happens)
[GitHub issue] (https://github.com/XanaduAI/pennylane/issue)



Discussion:
Thanks @WeileiZeng for catching this! `XanaduAI/pennylane` was the original location of the repository, so should redirect automatically to `PennyLaneAI/pennylane` 🙂 However, we should continue to make sure all links are updated.
the redirection doesn't work for issue page
Ah, then it should definitely be fixed ASAP. Thanks for letting us know!

Resolving patch:
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -334,11 +334,11 @@ def __getattr__(cls, name):
     "table_header_border": "#19b37b",
     "download_button": "#19b37b",
     # gallery options
-    # "github_repo": "XanaduAI/PennyLane",
+    # "github_repo": "PennyLaneAI/pennylane",
     # "gallery_dirs": "tutorials",
 }
 
-edit_on_github_project = 'XanaduAI/pennylane'
+edit_on_github_project = 'PennyLaneAI/pennylane'
 edit_on_github_branch = 'master/doc'
 
 # -- Options for HTMLHelp output ------------------------------------------
diff --git a/pennylane/__init__.py b/pennylane/__init__.py
--- a/pennylane/__init__.py
+++ b/pennylane/__init__.py
@@ -105,11 +105,11 @@ def device(name, *args, **kwargs):
     * :mod:`'default.gaussian' <pennylane.devices.default_gaussian>`: a simple simulator
       of Gaussian states and operations on continuous-variable circuit architectures.
 
-    * :mod:`'default.qubit.tf' <pennylane.devices.default_qubit.tf>`: a state simulator
+    * :mod:`'default.qubit.tf' <pennylane.devices.default_qubit_tf>`: a state simulator
       of qubit-based quantum circuit architectures written in TensorFlow, which allows
       automatic differentiation through the simulation.
 
-    * :mod:`'default.qubit.autograd' <pennylane.devices.default_qubit.autograd>`: a state simulator
+    * :mod:`'default.qubit.autograd' <pennylane.devices.default_qubit_autograd>`: a state simulator
       of qubit-based quantum circuit architectures which allows
       automatic differentiation through the simulation via python's autograd library.
 


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
Inverses in default_qubit
Several operations have hard coded implementations instead of simply using their unitary matrix.  These are specified at [default_qubit.py Line 130](https://github.com/PennyLaneAI/pennylane/blob/9bbf560e830f951eaa421c2de20549b9d9e7af6c/pennylane/devices/default_qubit.py#L130) such as `"PauliX"` or `"CNOT"`.  

These hard-coded functions like  [`dev._apply_phase`](https://github.com/PennyLaneAI/pennylane/blob/9bbf560e830f951eaa421c2de20549b9d9e7af6c/pennylane/devices/default_qubit.py#L328) can take in a boolean for the keyword `inverse` and apply the inverse operation instead.

**BUT** [`dev._apply_operation`](https://github.com/PennyLaneAI/pennylane/blob/9bbf560e830f951eaa421c2de20549b9d9e7af6c/pennylane/devices/default_qubit.py#L163) always sends inverse operations to the more general path using `dev._get_unitary_matrix` followed by something like `dev._apply_unitary`.

This happens because inverse operations have `.inv` appended to their name.  Thus the new name is no longer in the `dev._apply_ops` dictionary.

This can easily be fixed by changing `operation.name` to `operation.base_name` at [Line 179](https://github.com/PennyLaneAI/pennylane/blob/9bbf560e830f951eaa421c2de20549b9d9e7af6c/pennylane/devices/default_qubit.py#L179) and [Line 181](https://github.com/PennyLaneAI/pennylane/blob/9bbf560e830f951eaa421c2de20549b9d9e7af6c/pennylane/devices/default_qubit.py#L181)



Discussion:

Resolving patch:
diff --git a/pennylane/devices/default_qubit.py b/pennylane/devices/default_qubit.py
--- a/pennylane/devices/default_qubit.py
+++ b/pennylane/devices/default_qubit.py
@@ -182,9 +182,9 @@ def _apply_operation(self, operation):
             self._apply_basis_state(operation.parameters[0], wires)
             return
 
-        if operation.name in self._apply_ops:
+        if operation.base_name in self._apply_ops:
             axes = self.wires.indices(wires)
-            self._state = self._apply_ops[operation.name](
+            self._state = self._apply_ops[operation.base_name](
                 self._state, axes, inverse=operation.inverse
             )
             return


Test patch:
Repository: PennyLaneAI/pennylane

Issue:
Please expose device._shot_vector via public property
This is a features request: Please expose the shot vector via some public and documented property of the device. Thank you!

This is inspired by me needing to predict the output shape of certain QNodes and in case of a non trivial shot vector and all observables being owned by an `expval` the shape is 
```
(sum([shot_tuple.copies for shot_tuple in self.device._shot_vector]), len(self.measurements))
```
(where self is a tape).


Discussion:
Thanks @cvjjm!

> This is inspired by me needing to predict the output shape of certain QNodes and in case of a non trivial shot vector and all observables being owned by an expval the shape is

We should also update the `tape` logic to better predict the output shape.
> This is inspired by me needing to predict the output shape

Are you doing something with JAX? I'd be interested in hearing more about it.

Resolving patch:
diff --git a/pennylane/_device.py b/pennylane/_device.py
--- a/pennylane/_device.py
+++ b/pennylane/_device.py
@@ -264,6 +264,33 @@ def shots(self, shots):
                 "Shots must be a single non-negative integer or a sequence of non-negative integers."
             )
 
+    @property
+    def shot_vector(self):
+        """list[.ShotTuple[int, int]]: Returns the shot vector, a sparse
+        representation of the shot sequence used by the device
+        when evaluating QNodes.
+
+        **Example**
+
+        >>> dev = qml.device("default.qubit", wires=2, shots=[3, 1, 2, 2, 2, 2, 6, 1, 1, 5, 12, 10, 10])
+        >>> dev.shots
+        57
+        >>> dev.shot_vector
+        [ShotTuple(shots=3, copies=1),
+         ShotTuple(shots=1, copies=1),
+         ShotTuple(shots=2, copies=4),
+         ShotTuple(shots=6, copies=1),
+         ShotTuple(shots=1, copies=2),
+         ShotTuple(shots=5, copies=1),
+         ShotTuple(shots=12, copies=1),
+         ShotTuple(shots=10, copies=2)]
+
+        The sparse representation of the shot
+        sequence is returned, where tuples indicate the number of times a shot
+        integer is repeated.
+        """
+        return self._shot_vector
+
     def define_wire_map(self, wires):
         """Create the map from user-provided wire labels to the wire labels used by the device.
 


Test patch:
diff --git a/tests/test_device.py b/tests/test_device.py
--- a/tests/test_device.py
+++ b/tests/test_device.py
@@ -164,6 +164,19 @@ def get_device(wires=1):
 
         yield get_device
 
+def test_shot_vector_property():
+    dev = qml.device("default.qubit", wires=1, shots=[1, 3, 3, 4, 4, 4, 3])
+    shot_vector = dev.shot_vector
+    assert len(shot_vector) == 4
+    assert shot_vector[0].shots == 1
+    assert shot_vector[0].copies == 1
+    assert shot_vector[1].shots == 3
+    assert shot_vector[1].copies == 2
+    assert shot_vector[2].shots == 4
+    assert shot_vector[2].copies == 3
+    assert shot_vector[3].shots == 3
+    assert shot_vector[3].copies == 1
+
 
 class TestDeviceSupportedLogic:
     """Test the logic associated with the supported operations and observables"""
Repository: PennyLaneAI/pennylane

Issue:
[unitaryhack] Define decomposition for `qml.SWAP`
*This issue has been tagged for contributions during [unitaryHACK](https://unitaryfund.github.io/unitaryhack/participating-projects.html)*

Each PennyLane operation defines a decomposition. The decomposition of an operation is an ordered list of other operations. Applying this list of operations evolves quantum states the same way as applying the operation itself does. In most cases, this list includes elementary gates that are often supported by most quantum devices.

We would like to add the decomposition of the `qml.SWAP` operation by:
1. Defining the decomposition method for [the `qml.SWAP` operation](https://github.com/PennyLaneAI/pennylane/blob/1930230dde60112ad90af0951fa9295d374e1adf/pennylane/ops/qubit.py#L528) that has the following signature:
```python
    @staticmethod
    def decomposition(wires):
```
Other operations in the `pennylane/ops/qubit.py` file can serve as an example for defining this method (e.g., [see `qml.Hadamard`](https://github.com/PennyLaneAI/pennylane/blob/1930230dde60112ad90af0951fa9295d374e1adf/pennylane/ops/qubit.py#L87)).
2. Including a test case for the decomposition of `qml.SWAP` in the `tests/ops/test_qubit_ops.py` file to verify its correctness.


Discussion:

Resolving patch:
diff --git a/pennylane/ops/qubit.py b/pennylane/ops/qubit.py
--- a/pennylane/ops/qubit.py
+++ b/pennylane/ops/qubit.py
@@ -526,6 +526,15 @@ class SWAP(Operation):
     def _matrix(cls, *params):
         return cls.matrix
 
+    @staticmethod
+    def decomposition(wires):
+        decomp_ops = [
+            qml.CNOT(wires=[wires[0], wires[1]]),
+            qml.CNOT(wires=[wires[1], wires[0]]),
+            qml.CNOT(wires=[wires[0], wires[1]]),
+        ]
+        return decomp_ops
+
     def adjoint(self):
         return SWAP(wires=self.wires)
 


Test patch:
diff --git a/tests/ops/test_qubit_ops.py b/tests/ops/test_qubit_ops.py
--- a/tests/ops/test_qubit_ops.py
+++ b/tests/ops/test_qubit_ops.py
@@ -923,6 +923,22 @@ def test_iswap_eigenval(self):
         res = op.eigvals
         assert np.allclose(res, exp)
 
+    def test_swap_decomposition(self):
+        """Tests the swap operator produces the correct output"""
+        opr = qml.SWAP(wires=[0, 1])
+        decomp = opr.decomposition([0, 1])
+
+        mat = []
+        for op in reversed(decomp):
+            if isinstance(op, qml.CNOT) and op.wires.tolist() == [0, 1]:
+                mat.append(CNOT)
+            elif isinstance(op, qml.CNOT) and op.wires.tolist() == [1, 0]:
+                mat.append(np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]))
+
+        decomposed_matrix = np.linalg.multi_dot(mat)
+
+        assert np.allclose(decomposed_matrix, opr.matrix)
+
     @pytest.mark.parametrize("phi", [-0.1, 0.2, 0.5])
     def test_controlled_phase_shift_matrix_and_eigvals(self, phi):
         """Tests that the ControlledPhaseShift operation calculates the correct matrix and