Skip to content

Commit

Permalink
TKET-3469 Allow setting of RNG seed
Browse files Browse the repository at this point in the history
  • Loading branch information
doug-q committed Aug 22, 2023
1 parent d86c7c2 commit afdb692
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
20 changes: 16 additions & 4 deletions pytket/extensions/qulacs/backends/qulacs_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__,
Expand All @@ -116,6 +118,8 @@ def __init__(self) -> None:
)

self._sim = QuantumState
if seed:
self._seed = Random(seed)

@property
def _result_id_type(self) -> _ResultIdTuple:
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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
4 changes: 2 additions & 2 deletions tests/test_qulacs_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit afdb692

Please sign in to comment.