|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
""" |
|
utils.algorithm_globals |
|
======================= |
|
Common (global) properties used across qiskit_algorithms. |
|
|
|
.. currentmodule:: qiskit_algorithms.utils.algorithm_globals |
|
|
|
Includes: |
|
|
|
* Random number generator and random seed. |
|
|
|
Algorithms can use the generator for random values, as needed, and it |
|
can be seeded here for reproducible results when using such an algorithm. |
|
This is often important, for example in unit tests, where the same |
|
outcome is desired each time (reproducible) and not have it be variable |
|
due to randomness. |
|
|
|
Attributes: |
|
random_seed (int | None): Random generator seed (read/write). |
|
random (np.random.Generator): Random generator (read-only) |
|
""" |
|
|
|
from __future__ import annotations |
|
|
|
import warnings |
|
|
|
import numpy as np |
|
|
|
|
|
class QiskitAlgorithmGlobals: |
|
"""Global properties for algorithms.""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self) -> None: |
|
self._random_seed: int | None = None |
|
self._random: np.random.Generator | None = None |
|
|
|
@property |
|
def random_seed(self) -> int | None: |
|
"""Random seed property (getter/setter).""" |
|
try: |
|
from qiskit.utils import algorithm_globals as qiskit_globals |
|
|
|
return qiskit_globals.random_seed |
|
|
|
except ImportError: |
|
return self._random_seed |
|
|
|
@random_seed.setter |
|
def random_seed(self, seed: int | None) -> None: |
|
"""Set the random generator seed. |
|
|
|
Args: |
|
seed: If ``None`` then internally a random value is used as a seed |
|
""" |
|
try: |
|
from qiskit.utils import algorithm_globals as qiskit_globals |
|
|
|
qiskit_globals.random_seed = seed |
|
|
|
|
|
self._random_seed = seed |
|
|
|
except ImportError: |
|
self._random_seed = seed |
|
self._random = None |
|
|
|
@property |
|
def random(self) -> np.random.Generator: |
|
"""Return a numpy np.random.Generator (default_rng) using random_seed.""" |
|
try: |
|
from qiskit.utils import algorithm_globals as qiskit_globals |
|
|
|
if self._random_seed != qiskit_globals.random_seed: |
|
|
|
|
|
|
|
warnings.warn( |
|
"Using random that is seeded via qiskit.utils algorithm_globals is deprecated " |
|
"since version 0.2.0. Instead set random_seed directly to " |
|
"qiskit_algorithms.utils algorithm_globals.", |
|
category=DeprecationWarning, |
|
stacklevel=2, |
|
) |
|
|
|
return qiskit_globals.random |
|
|
|
except ImportError: |
|
if self._random is None: |
|
self._random = np.random.default_rng(self._random_seed) |
|
return self._random |
|
|
|
|
|
|
|
algorithm_globals = QiskitAlgorithmGlobals() |
|
|