Ejemplo n.º 1
0
    def test_identity_mixed(self, dev, monkeypatch, tmpdir, test_result):
        """Test computing that computing the expectation value of a tape with
        observables of identity and PauliZ and a tape where only the identity
        of observable returns the correct list of results."""
        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs:
                test_result,  # The exact results are not considered in the test
            )

            dev = qml.device(dev, wires=2)

            with qml.tape.QuantumTape() as tape1:
                qml.expval(qml.Identity(wires=[0]))
                qml.expval(qml.PauliZ(wires=[1]))

            with qml.tape.QuantumTape() as tape2:
                qml.expval(qml.Identity(wires=[0]))

            res = dev.batch_execute([tape1, tape2])

            assert np.allclose(res[0], np.array([1, test_batch_res0]))
            assert np.allclose(res[1], np.array([1]))
Ejemplo n.º 2
0
    def test_got_resources(self, resources, monkeypatch):
        """Test that the resource details defined when the device was created
        are passed to generate the workflow."""
        dev = qml.device("orquestra.qiskit", wires=2, resources=resources)
        recorder = []
        mock_res_dict = {"First": {"expval": {"list": [123456789]}}}

        with monkeypatch.context() as m:

            # Record the resources that were passed
            get_resources_passed = lambda *args, **kwargs: recorder.append(
                kwargs.get("resources", False))
            m.setattr(pennylane_orquestra.orquestra_device,
                      "gen_expval_workflow", get_resources_passed)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs: mock_res_dict,
            )

            @qml.qnode(dev)
            def circuit():
                qml.PauliX(0)
                return qml.expval(qml.PauliZ(0))

            assert circuit() == 123456789

            # Check that the resorces were passed correctly
            assert len(recorder) == 1
            assert recorder[0] == resources
Ejemplo n.º 3
0
    def test_operator_with_invalid_wire(self, monkeypatch, test_batch_result):
        """Test that a device with custom wire labels raises an error when an
        invalid wire is used in the operator definition.

        This test is meant to check that the internal wire mappings do not
        introduce false positive behaviour when using custom wire labels.
        """
        dev = QeQiskitDevice(wires=["a", "b", "c"],
                             shots=1000,
                             backend="qasm_simulator",
                             analytic=False)

        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs: test_batch_result,
            )

            @qml.qnode(dev)
            def circuit():
                return qml.expval(qml.PauliZ(0))

            with pytest.raises(
                    qml.qnodes.base.QuantumFunctionError,
                    match="Operation PauliZ applied to invalid wire",
            ):
                circuit()
Ejemplo n.º 4
0
    def test_identity_mixed(self, dev, monkeypatch, tmpdir, test_result):
        """Test computing that computing the expectation value of the identity
        and PauliZ returns an array of results."""
        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs:
                test_result,  # The exact results are not considered in the test
            )

            dev = qml.device(dev, wires=2)

            @qml.qnode(dev)
            def circuit():
                qml.PauliX(0)
                return qml.expval(qml.Identity(0)), qml.expval(qml.PauliZ(1))

            res = circuit()
            assert np.allclose(res, np.array([1, test_batch_res0]))
Ejemplo n.º 5
0
    def test_timeout(self, timeout, tmpdir, monkeypatch):
        """Test the option for keeping/deleting the workflow file."""

        file_name = "test_workflow.yaml"
        dev = qml.device("orquestra.forest", wires=3, timeout=timeout)
        mock_res_dict = {"First": {"expval": {"list": [123456789]}}}

        test_uuid = "1234"
        assert dev._timeout == timeout
        assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}.yaml"))
        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)
            m.setattr(pennylane_orquestra.cli_actions, "workflow_results",
                      lambda *args: "Test res")

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())

            # Disable random uuid generation
            m.setattr(uuid, "uuid4", lambda *args: test_uuid)

            @qml.qnode(dev)
            def circuit():
                qml.PauliX(0)
                return qml.expval(qml.PauliZ(0))

            start = time.time()
            with pytest.raises(TimeoutError,
                               match="The workflow results for workflow"):
                circuit()
            end = time.time()
            assert end - start >= timeout
    def test_serialize_circuit_rotations_tape(self, monkeypatch, tmpdir,
                                              test_batch_result):
        """Test that a circuit that is serialized correctly with rotations for
        a remote hardware backend"""
        dev = QeQiskitDevice(wires=1, shots=1000, backend="qasm_simulator")

        circuit_history = []

        with qml.tape.QuantumTape() as tape1:
            qml.Hadamard(wires=[0])
            qml.expval(qml.Hadamard(0))

        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "gen_expval_workflow",
                lambda component, backend_specs, circuits, operators, **kwargs:
                circuit_history.extend(circuits),
            )

            # Disable submitting to Orquestra by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs:
                test_batch_result,  # The exact results are not considered in the test
            )

            dev.execute(tape1)

        expected = 'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[1];\ncreg c[1];\nh q[0];\nry(-0.7853981633974483) q[0];\n'
        assert circuit_history[0] == expected
Ejemplo n.º 7
0
    def test_submit_raises_no_success(self, monkeypatch):
        """Test that the qe_submit method raises an error if a success
        message was not received."""

        no_success_msg = "Not a success message."
        with monkeypatch.context() as m:
            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen",
                      lambda *args, **kwargs: MockPopen(no_success_msg))

            with pytest.raises(ValueError, match=no_success_msg):
                qe_submit("some_filename")
Ejemplo n.º 8
0
    def test_batch_exec(self, keep, tmpdir, monkeypatch, test_batch_result):
        """Test that the batch_execute method returns the desired result and
        that the result preserves the order in which circuits were
        submitted."""
        qml.enable_tape()

        dev = qml.device("orquestra.forest", wires=3, keep_files=keep)

        with qml.tape.QuantumTape() as tape1:
            qml.expval(qml.PauliZ(wires=[0]))

        with qml.tape.QuantumTape() as tape2:
            qml.RX(0.432, wires=0)
            qml.RY(0.543, wires=0)
            qml.expval(qml.PauliZ(wires=[0]))

        with qml.tape.QuantumTape() as tape3:
            qml.RX(0.432, wires=0)
            qml.expval(qml.PauliZ(wires=[0]))

        circuits = [tape1, tape2, tape3]

        test_uuid = "1234"
        assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}-0.yaml"))

        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs: test_batch_result,
            )

            # Disable random uuid generation
            m.setattr(uuid, "uuid4", lambda *args: test_uuid)

            res = dev.batch_execute(circuits)

            # Correct order of results is expected
            assert np.allclose(res[0], test_batch_res0)
            assert np.allclose(res[1], test_batch_res1)
            assert np.allclose(res[2], test_batch_res2)
            file_kept = os.path.exists(
                tmpdir.join(f"expval-{test_uuid}-0.yaml"))

            assert file_kept if keep else not file_kept

        qml.disable_tape()
Ejemplo n.º 9
0
    def test_submit_raises_unexpected_resp(self, monkeypatch, response):
        """Test that the qe_submit method raises an error if the workflow id
        could not be obtained."""

        unexp_resp_msg = "Received an unexpected response after submitting workflow."
        with monkeypatch.context() as m:
            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen",
                      lambda *args, **kwargs: MockPopen(response))
            m.setattr(os, "remove", lambda *args, **kwargs: None)

            with pytest.raises(ValueError, match=unexp_resp_msg):
                qe_submit("some_filename")
Ejemplo n.º 10
0
    def test_identity_multiple_tape(self, dev, tmpdir, monkeypatch):
        """Test computing the expectation value of the identity for multiple
        return values."""
        qml.enable_tape()

        dev = qml.device(dev, wires=2, keep_files=False)

        with qml.tape.QuantumTape() as tape1:
            qml.RX(0.133, wires=0)
            qml.expval(qml.Identity(wires=[0]))

        with qml.tape.QuantumTape() as tape2:
            qml.RX(0.432, wires=0)
            qml.expval(qml.Identity(wires=[0]))
            qml.expval(qml.Identity(wires=[1]))

        circuits = [tape1, tape2]

        test_uuid = "1234"
        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs: None,
            )

            # Disable random uuid generation
            m.setattr(uuid, "uuid4", lambda *args: test_uuid)

            res = dev.batch_execute(circuits)

            # No workflow files were created because we only computed with
            # identities
            assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}.yaml"))
            assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}.yaml"))

            expected = [
                np.ones(1),
                np.ones(2),
            ]

            for r, e in zip(res, expected):
                assert np.allclose(r, e)

        qml.disable_tape()
Ejemplo n.º 11
0
    def test_keep_workflow_file(self, keep, tmpdir, monkeypatch):
        """Test the option for keeping/deleting the workflow file."""

        file_name = "test_workflow.yaml"
        dev = qml.device("orquestra.forest", wires=3, keep_files=keep)
        mock_res_dict = {"First": {"expval": {"list": [123456789]}}}
        test_uuid = "1234"

        assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}.yaml"))
        assert not dev.filenames
        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs: mock_res_dict,
            )

            # Disable random uuid generation
            m.setattr(uuid, "uuid4", lambda *args: test_uuid)

            @qml.qnode(dev)
            def circuit():
                qml.PauliX(0)
                return qml.expval(qml.PauliZ(0))

            assert circuit() == 123456789
            file_kept = os.path.exists(tmpdir.join(f"expval-{test_uuid}.yaml"))
            assert file_kept if keep else not file_kept
            assert dev.filenames == ([f"expval-{test_uuid}.yaml"]
                                     if keep else [])
            assert dev.latest_id == "SomeWorkflowID"
Ejemplo n.º 12
0
    def test_batch_exec_multiple_workflow(self, keep, dev_name, tmpdir,
                                          monkeypatch, test_batch_result):
        """Test that the batch_execute method returns the desired result and
        that the result preserves the order in which circuits were submitted
        when batches are created in multiple workflows ."""

        qml.enable_tape()

        with qml.tape.QuantumTape() as tape1:
            qml.RX(0.133, wires=0)
            qml.CNOT(wires=[0, 1])
            qml.expval(qml.PauliZ(wires=[0]))

        with qml.tape.QuantumTape() as tape2:
            qml.RX(0.432, wires=0)
            qml.RY(0.543, wires=0)
            qml.expval(qml.PauliZ(wires=[0]))

        with qml.tape.QuantumTape() as tape3:
            qml.RX(0.432, wires=0)
            qml.expval(qml.PauliZ(wires=[0]))

        circuits = [tape1, tape2, tape3]

        # Setting batch size: allow only a single circuit for each workflow
        dev = qml.device(dev_name, wires=3, batch_size=1, keep_files=keep)

        # Check that no workflow files were created before
        test_uuid = "1234"
        assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}-0.yaml"))
        assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}-1.yaml"))
        assert not os.path.exists(tmpdir.join(f"expval-{test_uuid}-2.yaml"))

        with monkeypatch.context() as m:
            m.setattr(pennylane_orquestra.cli_actions, "user_data_dir",
                      lambda *args: tmpdir)

            # Disable submitting to the Orquestra platform by mocking Popen
            m.setattr(subprocess, "Popen", lambda *args, **kwargs: MockPopen())
            m.setattr(
                pennylane_orquestra.orquestra_device,
                "loop_until_finished",
                lambda *args, **kwargs: test_batch_result,
            )

            # Disable random uuid generation
            m.setattr(uuid, "uuid4", lambda *args: test_uuid)

            res = dev.batch_execute(circuits)

            # Correct order of results is expected
            assert np.allclose(res[0], test_batch_res0)
            assert np.allclose(res[1], test_batch_res1)
            assert np.allclose(res[2], test_batch_res2)
            file0_kept = os.path.exists(
                tmpdir.join(f"expval-{test_uuid}-0.yaml"))
            file1_kept = os.path.exists(
                tmpdir.join(f"expval-{test_uuid}-1.yaml"))
            file2_kept = os.path.exists(
                tmpdir.join(f"expval-{test_uuid}-2.yaml"))

        # Check that workflow files were either all kept or all deleted
        files_kept = file0_kept and file1_kept and file2_kept
        assert files_kept and file0_kept if keep else not files_kept

        qml.disable_tape()