From afdb69289136cdf3d65e7d030781f617435c3699 Mon Sep 17 00:00:00 2001 From: Douglas Wilson Date: Tue, 22 Aug 2023 08:46:10 +0100 Subject: [PATCH] TKET-3469 Allow setting of RNG seed --- .../qulacs/backends/qulacs_backend.py | 20 +++++++++++++++---- tests/test_qulacs_backend.py | 4 ++-- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/pytket/extensions/qulacs/backends/qulacs_backend.py b/pytket/extensions/qulacs/backends/qulacs_backend.py index 859383e..0c1ca41 100644 --- a/pytket/extensions/qulacs/backends/qulacs_backend.py +++ b/pytket/extensions/qulacs/backends/qulacs_backend.py @@ -17,6 +17,7 @@ from typing import List, Optional, Sequence, Union from logging import warning +from random import Random from uuid import uuid4 import numpy as np from sympy import Expr # type: ignore @@ -104,8 +105,9 @@ class QulacsBackend(Backend): *_1Q_GATES, OpType.Barrier, } + _seed = None - def __init__(self) -> None: + def __init__(self, seed: Optional[int] = None) -> None: super().__init__() self._backend_info = BackendInfo( type(self).__name__, @@ -116,6 +118,8 @@ def __init__(self) -> None: ) self._sim = QuantumState + if seed: + self._seed = Random(seed) @property def _result_id_type(self) -> _ResultIdTuple: @@ -205,7 +209,7 @@ def process_circuits( else: bits, choose_indices = zip(*bits2index) - samples = qulacs_state.sampling(n_shots_circ) + samples = self._sample_quantum_state(qulacs_state, n_shots_circ) shots = OutcomeArray.from_ints(samples, circuit.n_qubits) shots = shots.choose_indices(choose_indices) try: @@ -228,6 +232,14 @@ def process_circuits( del qulacs_circ return handle_list + def _sample_quantum_state( + self, quantum_state: QuantumState, n_shots: int + ) -> List[int]: + if self._seed: + return quantum_state.sampling(n_shots, self._seed.randint(0, 2**32 - 1)) + else: + return quantum_state.sampling(n_shots) + def circuit_status(self, handle: ResultHandle) -> CircuitStatus: if handle in self._cache: return CircuitStatus(StatusEnum.COMPLETED) @@ -286,7 +298,7 @@ class QulacsGPUBackend(QulacsBackend): Backend for running simulations on the Qulacs GPU simulator """ - def __init__(self) -> None: - super().__init__() + def __init__(self, **kwargs) -> None: + super().__init__(**kwargs) self._backend_info.name = type(self).__name__ self._sim = QuantumStateGpu diff --git a/tests/test_qulacs_backend.py b/tests/test_qulacs_backend.py index 8e251ff..02bded2 100644 --- a/tests/test_qulacs_backend.py +++ b/tests/test_qulacs_backend.py @@ -26,12 +26,12 @@ from pytket.utils.operators import QubitPauliOperator from pytket.extensions.qulacs import QulacsBackend -backends = [QulacsBackend()] +backends = [QulacsBackend(), QulacsBackend(seed=-1)] try: from pytket.extensions.qulacs import QulacsGPUBackend - backends.append(QulacsGPUBackend()) + backends.append([QulacsGPUBackend(), QulacsGPUBackend(seed=1)]) except ImportError: warnings.warn("local settings failed to import QulacsGPUBackend", ImportWarning)