• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

qiskit-community / qiskit-optimization / 17087002402

18 Aug 2025 11:51PM UTC coverage: 91.999% (-0.02%) from 92.014%
17087002402

push

github

web-flow
Show warning of algorithm_globals (#679)

0 of 3 new or added lines in 1 file covered. (0.0%)

6048 of 6574 relevant lines covered (92.0%)

0.92 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.24
/qiskit_optimization/utils/algorithm_globals.py
1
# This code is part of a Qiskit project.
2
#
3
# (C) Copyright IBM 2019, 2025.
4
#
5
# This code is licensed under the Apache License, Version 2.0. You may
6
# obtain a copy of this license in the LICENSE.txt file in the root directory
7
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
#
9
# Any modifications or derivative works of this code must retain this
10
# copyright notice, and modified files need to carry a notice indicating
11
# that they have been altered from the originals.
12

13
"""Global properties for algorithms"""
14

15
from __future__ import annotations
1✔
16

17
import warnings
1✔
18

19
import numpy as np
1✔
20

21

22
class QiskitAlgorithmGlobals:
1✔
23
    """
24
    Common (global) properties used across qiskit_optimization.
25

26
    Includes:
27

28
    * Random number generator and random seed.
29

30
        Algorithms can use the generator for random values, as needed, and it
31
        can be seeded here for reproducible results when using such an algorithm.
32
        This is often important, for example in unit tests, where the same
33
        outcome is desired each time (reproducible) and not have it be variable
34
        due to randomness.
35

36
    Attributes:
37
        random_seed (int | None): Random generator seed (read/write).
38
        random (np.random.Generator): Random generator (read-only)
39
    """
40

41
    # The code is done to work even after some future removal of algorithm_globals
42
    # from Qiskit (qiskit.utils). All that is needed in the future, after that, if
43
    # this is updated, is just the logic in the except blocks.
44
    #
45
    # If the Qiskit Algorithms version exists this acts a redirect to that (it delegates the
46
    # calls off to it). In the future when that does not exist this has similar code
47
    # in the except blocks here, as noted above, that will take over. By delegating
48
    # to the Qiskit Algorithms instance it means that any existing code that uses that continues
49
    # to work. Logic here in qiskit_optimization though uses this instance and the
50
    # random check here has logic to warn if the seed here is not the same as the Qiskit Algorithms
51
    # version so we can detect direct usage of the Qiskit Algorithms version and alert the user to
52
    # change their code to use this. So simply changing from:
53
    #     from qiskit_algorithms.utils import algorithm_globals
54
    # to
55
    #     from qiskit_optimization.utils import algorithm_globals
56

57
    def __init__(self) -> None:
1✔
58
        self._random_seed: int | None = None
1✔
59
        self._random: np.random.Generator | None = None
1✔
60

61
    @property
1✔
62
    def random_seed(self) -> int | None:
1✔
63
        """Random seed property (getter/setter)."""
64
        try:
1✔
65
            with warnings.catch_warnings():
1✔
66
                warnings.simplefilter("ignore", category=DeprecationWarning)
1✔
67

68
                from qiskit_algorithms.utils import algorithm_globals as qiskit_globals
1✔
69

70
                return qiskit_globals.random_seed
1✔
71

72
        except ImportError:
1✔
73
            return self._random_seed
1✔
74

75
    @random_seed.setter
1✔
76
    def random_seed(self, seed: int | None) -> None:
1✔
77
        """Set the random generator seed.
78

79
        Args:
80
            seed: If ``None`` then internally a random value is used as a seed
81
        """
82
        try:
1✔
83
            with warnings.catch_warnings():
1✔
84
                warnings.simplefilter("ignore", category=DeprecationWarning)
1✔
85

86
                from qiskit_algorithms.utils import algorithm_globals as qiskit_globals
1✔
87

88
                qiskit_globals.random_seed = seed
×
89
                # Mirror the seed here when set via this random_seed. If the seed is
90
                # set on the qiskit.utils instance then we can detect it's different
91
                self._random_seed = seed
1✔
92

93
        except ImportError:
1✔
94
            self._random_seed = seed
1✔
95
            self._random = None
1✔
96

97
    @property
1✔
98
    def random(self) -> np.random.Generator:
1✔
99
        """Return a numpy np.random.Generator (default_rng) using random_seed."""
100
        try:
1✔
101
            with warnings.catch_warnings():
1✔
102
                warnings.simplefilter("ignore", category=DeprecationWarning)
1✔
103

104
                from qiskit_algorithms.utils import algorithm_globals as qiskit_globals
1✔
105

NEW
106
            if self._random_seed != qiskit_globals.random_seed:
×
107
                # If the seeds are different - likely this local is None and the qiskit.utils
108
                # algorithms global was seeded directly then we will warn to use this here as
109
                # the Qiskit version is planned to be removed in a future version of Qiskit.
NEW
110
                warnings.warn(
×
111
                    "Using random that is seeded via qiskit_algorithms.utils.algorithm_globals "
112
                    "is deprecated since version 0.7.0. Instead set random_seed directly to "
113
                    "qiskit_optimization.utils.algorithm_globals.",
114
                    category=DeprecationWarning,
115
                    stacklevel=2,
116
                )
117

NEW
118
            return qiskit_globals.random
×
119

120
        except ImportError:
1✔
121
            if self._random is None:
1✔
122
                self._random = np.random.default_rng(self._random_seed)
1✔
123
            return self._random
1✔
124

125

126
# Global instance to be used as the entry point for globals.
127
algorithm_globals = QiskitAlgorithmGlobals()
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc