Пример #1
0
    def test_integration_file(self, tmpdir, monkeypatch, capsys):
        """Tests that a blackbird script was loaded and samples were written to
        the specified output file using the run_blackbird_script function."""

        filepath = tmpdir.join("test_script.xbb")

        with open(filepath, "w") as f:
            f.write(TEST_SCRIPT)

        mocked_args = MockArgs()
        mocked_args.input = filepath

        out_filepath = tmpdir.join("test_script.xbb")
        mocked_args.output = out_filepath

        with monkeypatch.context() as m:
            m.setattr(cli, "RemoteEngine", MockRemoteEngineIntegration)
            cli.run_blackbird_script(mocked_args)

        with open(filepath, "r") as f:
            results_from_file = f.read()

        out, _ = capsys.readouterr()
        assert out == "Executing program on remote hardware...\n"
        assert results_from_file == str(Result(test_samples).samples)
Пример #2
0
 def test_state_print(self, capfd):
     """Test that printing a result object with a state provides the correct output."""
     result = Result(np.array([[1, 2], [3, 4], [5, 6]]), is_stateful=True)
     print(result)
     out, err = capfd.readouterr()
     assert "modes=2" in out
     assert "shots=3" in out
     assert "contains state=True" in out
Пример #3
0
    def test_stateless_result_raises_on_state_access(self):
        """Tests that `result.state` raises an error for a stateless result.
        """
        result = Result([[1, 2], [3, 4]], is_stateful=False)

        with pytest.raises(
                AttributeError,
                match="The state is undefined for a stateless computation."):
            result.state
Пример #4
0
 def test_tdm_print(self, stateful, capfd):
     """Test that printing a result object with TDM samples provides the correct output."""
     samples = np.ones((2, 3, 4))
     result = Result(samples, is_stateful=stateful)
     print(result)
     out, err = capfd.readouterr()
     assert "spatial_modes=3" in out
     assert "shots=2" in out
     assert "timebins=4" in out
     assert f"contains state={stateful}" in out
Пример #5
0
 def test_unkown_shape_print(self, stateful, capfd):
     """Test that printing a result object with samples with an unknown shape
     provides the correct output."""
     samples = np.ones((2, 3, 4, 5))
     result = Result(samples, is_stateful=stateful)
     print(result)
     out, err = capfd.readouterr()
     assert "modes" not in out
     assert "shots" not in out
     assert "timebins" not in out
     assert f"contains state={stateful}" in out
def job_to_complete(connection, monkeypatch):
    """Mocks a remote job that is completed after a certain number of requests."""
    monkeypatch.setattr(
        Connection,
        "create_job",
        mock_return(Job(id_="123", status=JobStatus.OPEN, connection=connection)),
    )
    server = MockServer()
    monkeypatch.setattr(Connection, "get_job_status", server.get_job_status)
    monkeypatch.setattr(
        Connection,
        "get_job_result",
        mock_return(Result(np.array([[1, 2], [3, 4]]), is_stateful=False)),
    )
Пример #7
0
    def test_integration_std_out(self, tmpdir, monkeypatch, capsys):
        """Tests that a blackbird script was loaded and samples were written to
        the standard output using the run_blackbird_script function."""

        filepath = tmpdir.join("test_script.xbb")

        with open(filepath, "w") as f:
            f.write(TEST_SCRIPT)

        mocked_args = MockArgs()
        mocked_args.input = filepath

        with monkeypatch.context() as m:
            m.setattr(cli, "RemoteEngine", MockRemoteEngineIntegration)
            cli.run_blackbird_script(mocked_args)

        out, err = capsys.readouterr()

        execution_message = "Executing program on remote hardware...\n"

        outputs = execution_message + str(Result(test_samples).samples)
        assert outputs == out
Пример #8
0
 def run(*args, **kwargs):
     return Result(MOCK_SAMPLES)
Пример #9
0
    def _run(self, program, *, args, compile_options, **kwargs):
        """Execute the given programs by sending them to the backend.

        If multiple Programs are given they will be executed sequentially as
        parts of a single computation.
        For each :class:`.Program` instance given as input, the following happens:

        * The Program instance is compiled for the target backend.
        * The compiled program is executed on the backend.
        * The measurement results of each subsystem (if any) are stored in the :class:`.RegRef`
          instances of the corresponding Program, as well as in :attr:`~BaseEngine.samples`.
        * The compiled program is appended to :attr:`~BaseEngine.run_progs`.

        Finally, the result of the computation is returned.

        Args:
            program (Program, Sequence[Program]): quantum programs to run
            args (Dict[str, Any]): values for the free parameters in the program(s) (if any)
            compile_options (Dict[str, Any]): keyword arguments for :meth:`.Program.compile`

        The ``kwargs`` keyword arguments are passed to the backend API calls via :meth:`Operation.apply`.

        Returns:
            Result: results of the computation
        """

        if not isinstance(program, collections.abc.Sequence):
            program = [program]

        kwargs.setdefault("shots", 1)
        # NOTE: by putting ``shots`` into keyword arguments, it allows for the
        # signatures of methods in Operations to remain cleaner, since only
        # Measurements need to know about shots

        prev = self.run_progs[-1] if self.run_progs else None  # previous program segment
        for p in program:
            if prev is None:
                # initialize the backend
                self._init_backend(p.init_num_subsystems)
            else:
                # there was a previous program segment
                if not p.can_follow(prev):
                    raise RuntimeError(
                        "Register mismatch: program {}, '{}'.".format(len(self.run_progs), p.name)
                    )

                # Copy the latest measured values in the RegRefs of p.
                # We cannot copy from prev directly because it could be used in more than one
                # engine.
                for k, v in enumerate(self.samples):
                    p.reg_refs[k].val = v

            # bind free parameters to their values
            p.bind_params(args)

            # compile the program for the correct backend
            target = self.backend.compiler
            if target is not None:
                p = p.compile(compiler=target, **compile_options)
            p.lock()

            _, self.samples, self.all_samples = self._run_program(p, **kwargs)
            self.run_progs.append(p)

            prev = p

        return Result(self.samples, all_samples=self.all_samples)
Пример #10
0
 def run(self, program):
     if program:
         return Result(test_samples)