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

qiskit-community / qiskit-optimization / 16848186457

09 Aug 2025 10:02AM UTC coverage: 91.98% (-0.2%) from 92.15%
16848186457

Pull #672

github

web-flow
Merge 37150d858 into c0dfe67d9
Pull Request #672: (WIP) Add V2 Primitives Support and Qiskit 2.0

199 of 222 new or added lines in 22 files covered. (89.64%)

49 existing lines in 8 files now uncovered.

5987 of 6509 relevant lines covered (91.98%)

0.92 hits per line

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

92.68
/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
"""
14
utils.algorithm_globals
15
=======================
16
Common (global) properties used across qiskit_optimization.
17

18
.. currentmodule:: qiskit_optimization.utils.algorithm_globals
19

20
Includes:
21

22
  * Random number generator and random seed.
23

24
    Algorithms can use the generator for random values, as needed, and it
25
    can be seeded here for reproducible results when using such an algorithm.
26
    This is often important, for example in unit tests, where the same
27
    outcome is desired each time (reproducible) and not have it be variable
28
    due to randomness.
29

30
Attributes:
31
    random_seed (int | None): Random generator seed (read/write).
32
    random (np.random.Generator): Random generator (read-only)
33
"""
34

35
from __future__ import annotations
1✔
36

37
import warnings
1✔
38

39
import numpy as np
1✔
40

41

42
class QiskitAlgorithmGlobals:
1✔
43
    """Global properties for algorithms."""
44

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

61
    def __init__(self) -> None:
1✔
62
        self._random_seed: int | None = None
1✔
63
        self._random: np.random.Generator | None = None
1✔
64

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

72
                from qiskit.utils import algorithm_globals as qiskit_globals
1✔
73

74
                return qiskit_globals.random_seed
1✔
75

76
        except ImportError:
1✔
77
            return self._random_seed
1✔
78

79
    @random_seed.setter
1✔
80
    def random_seed(self, seed: int | None) -> None:
1✔
81
        """Set the random generator seed.
82

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

90
                from qiskit.utils import algorithm_globals as qiskit_globals
1✔
91

UNCOV
92
                qiskit_globals.random_seed = seed
×
93
                # Mirror the seed here when set via this random_seed. If the seed is
94
                # set on the qiskit.utils instance then we can detect it's different
95
                self._random_seed = seed
1✔
96

97
        except ImportError:
1✔
98
            self._random_seed = seed
1✔
99
            self._random = None
1✔
100

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

108
                from qiskit.utils import algorithm_globals as qiskit_globals
1✔
109

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

122
                return qiskit_globals.random
1✔
123

124
        except ImportError:
1✔
125
            if self._random is None:
1✔
126
                self._random = np.random.default_rng(self._random_seed)
1✔
127
            return self._random
1✔
128

129

130
# Global instance to be used as the entry point for globals.
131
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