qiboteam / qibo

A full-stack framework for quantum computing.
https://qibo.science
Apache License 2.0
294 stars 60 forks source link

Add `Phase-RX` gate + `qasm_label` for `GPI`, `GPI2`, and `MS` gates #1326

Closed mho291 closed 4 months ago

mho291 commented 6 months ago

Checklist:

mho291 commented 5 months ago

Hi @BrunoLiegiBastonLiegi , so sorry to trouble you.

I've added a new gate called Phase RX gate inside qibo/gates/gates.py with its pytest function in qibo/tests/test_gates_gates.py but am encountering some errors.

In qibo/gates/gates.py, I have this:

class PRx(ParametrizedGate):
    """Phase Rx gate.

    Corresponds to the following unitary matrix

        .. math::
            \\begin{pmatrix}
                \\cos{(\\theta / 2)} & -i e^{-i \\phi} \\sin{(\\theta / 2)} \\
                -i e^{i \\phi} \\sin{(\\theta / 2)} & \\cos{(\\theta / 2)}
            \\end{pmatrix}

    Args:
        theta (float): The first angle of the gate in radians or expression representation.
        phi (float): The second angle of the gate in radians or expression representation.
    """ 

    def __init__(self, q, theta, phi, trainable=True):
        super().__init__(trainable)
        self.name = "prx"
        self.draw_label = "prx"
        self.target_qubits = (q,)
        self.unitary = True

        if theta is None:
            raise_error(
                ValueError,
                f"Theta is not defined.",
            )
        if phi is None:
            raise_error(
                ValueError,
                f"Phi is not defined.",
            )

        self.parameter_names = ["theta", "phi"]
        self.theta = theta
        self.phi = phi
        self.nparams = 2

        self.init_args = [q]
        self.init_kwargs = {
            "theta": theta,
            "phi": phi,
            "trainable": trainable,
        }

    @property
    def qasm_label(self):
        return "prx"

    def _dagger(self) -> "Gate":
        theta = -self.theta
        phi = self.phi
        return self.__class__(
            self.target_qubits[0], theta, phi
        )  # pylint: disable=E1130

and inside qibo/tests/test_gates_gates.py I have added this function to test:

def test_prx(backend):
    phi = 0.24
    theta = 0.52
    final_state = apply_gates(
        backend, [gates.H(0), gates.PRx(0, theta=theta, phi=phi)], nqubits=1
    )
    cos = np.cos(theta / 2)
    sin = np.sin(theta / 2)
    exponent1 = -1.0j * np.exp(-1.0j * phi)
    exponent2 = -1.0j * np.exp(1.0j * phi)
    gate = np.array([[cos, exponent1 * sin], [exponent2 * sin, cos]])
    target_state = gate.dot(np.ones(2)) / np.sqrt(2.0)
    backend.assert_allclose(final_state, target_state)
    assert gates.PRx(0, phi=phi, theta=theta).qasm_label == "prx"
    assert not gates.PRx(0, phi=phi, theta=theta).clifford
    assert gates.PRx(0, phi=phi, theta=theta).unitary

I have also added the matrix form of the Phase RX gate inside qibo/backends/npmatrices.py:

def PRx(self, theta, phi):
        cos = self.np.cos(theta / 2)
        sin = self.np.sin(theta / 2)
        exponent1 = -1.0j * self.np.exp(-1.0j * phi)
        exponent2 = -1.0j * self.np.exp(1.0j * phi)
        return self._cast(
            [[cos, exponent1 * sin], [exponent2 * sin, cos]], dtype=self.dtype
        )

However, I'm encountering some errors when running pytests on my local laptop. This is the failure message:

=========== FAILURES ===========
_____________ test_prx[numpy] _____________

backend = numpy

    def test_prx(backend):
        phi = 0.24
        theta = 0.52
        final_state = apply_gates(
>           backend, [gates.H(0), gates.PRx(0, theta=theta, phi=phi)], nqubits=1
        )
E       AttributeError: module 'qibo.gates' has no attribute 'PRx'

test_gates_gates.py:1068: AttributeError

I've tried to resolve it as best as I can to no avail. Could I ask for help / advice on how to get this to work? Thank you!

BrunoLiegiBastonLiegi commented 5 months ago

Hi, no worries. I don't see the same error in tests here, it seems to find the gate here. How did you install qibo? Because if you install with pip install qibo it will install the latest release, try with pip install -e . that install your local branch with your changes (or alternatively with poetry install).

mho291 commented 5 months ago

Thank you @BrunoLiegiBastonLiegi , all I needed to do was poetry install. Tests are passed. Now there's an error with tensorflow: ___ test_prx[tensorflow] ___. This is under Tests / build (macos-latest, 3.10) / build (push). Could I trouble you for some assistance? So sorry!

BrunoLiegiBastonLiegi commented 5 months ago

Sorry for the delay, many tests from the quantum_info module and the CliffordBackend are failing actually. Which test are you referring to in particular?

mho291 commented 5 months ago

Sorry for the delay, many tests from the quantum_info module and the CliffordBackend are failing actually. Which test are you referring to in particular?

There seems to be an issue with the tensorflow test:

FAILED tests/test_gates_gates.py::test_prx[tensorflow] - tensorflow.python.framework.errors_impl.InvalidArgumentError: cannot compute Pack as input #1(zero-based) was expected to be a double tensor but is a complex128 tensor [Op:Pack] name: 0

Any idea how to resolve this? Thanks!

renatomello commented 5 months ago

@mho291 Dom you have a reference for this gate?

mho291 commented 4 months ago

@mho291 Dom you have a reference for this gate?

Here! https://amazon-braket-sdk-python.readthedocs.io/en/latest/_apidoc/braket.circuits.gate.html#braket.circuits.gate.Gate.PRx

The Phase RX gate is a native gate for the IQM Garnet chip.

renatomello commented 4 months ago

@mho291 @BrunoLiegiBastonLiegi problem is solved. The issue was that tensorflow is not very fond of arrays with elements of different dtypes. Adding a + 0j to the matrix elements that are real fixed it.

I also added the API reference and a decomposition in terms of gates.RY and gates.RZ

codecov[bot] commented 4 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 99.82%. Comparing base (363a6e5) to head (a756eea). Report is 211 commits behind head on master.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #1326 +/- ## ======================================= Coverage 99.82% 99.82% ======================================= Files 72 72 Lines 10560 10601 +41 ======================================= + Hits 10541 10582 +41 Misses 19 19 ``` | [Flag](https://app.codecov.io/gh/qiboteam/qibo/pull/1326/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=qiboteam) | Coverage Δ | | |---|---|---| | [unittests](https://app.codecov.io/gh/qiboteam/qibo/pull/1326/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=qiboteam) | `99.82% <100.00%> (+<0.01%)` | :arrow_up: | Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=qiboteam#carryforward-flags-in-the-pull-request-comment) to find out more.

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.