Skip to content

Commit 31a48a5

Browse files
Making lint, style changes with some migration fixes
1 parent 58a92c3 commit 31a48a5

File tree

64 files changed

+616
-853
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

64 files changed

+616
-853
lines changed

docs/lowercase_filter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
# copyright notice, and modified files need to carry a notice indicating
1111
# that they have been altered from the originals.
1212

13-
""" Implements a Lower Case Filter for Sphinx spelling """
13+
"""Implements a Lower Case Filter for Sphinx spelling"""
1414

1515
from enchant import tokenize
1616

qiskit_machine_learning/algorithm_job.py

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,7 @@ def submit(self) -> None:
2929
"""
3030
Submit the job for execution.
3131
32-
For V1 primitives, Qiskit ``PrimitiveJob`` subclassed JobV1 and defined ``submit()``.
33-
``PrimitiveJob`` was updated for V2 primitives, no longer subclasses ``JobV1``, and
34-
now has a private ``_submit()`` method, with ``submit()`` being deprecated as of
35-
Qiskit version 0.46. This maintains the ``submit()`` for ``AlgorithmJob`` here as
36-
it's called in many places for such a job. An alternative could be to make
37-
0.46 the required minimum version and alter all algorithm's call sites to use
38-
``_submit()`` and make this an empty class again as it once was. For now this
39-
way maintains compatibility with the current min version of 0.44.
32+
Since the library has been migrated to Qiskit v2.1, it is no longer necessary to
33+
keep the :meth:``JobV1.submit()`` for the exception handling.
4034
"""
41-
# TODO: Considering changing this in the future - see above docstring.
42-
try:
43-
super()._submit()
44-
except AttributeError:
45-
super().submit() # pylint: disable=no-member
35+
super()._submit()

qiskit_machine_learning/algorithms/classifiers/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010
# copyright notice, and modified files need to carry a notice indicating
1111
# that they have been altered from the originals.
1212

13-
""" Classifiers Package """
13+
"""Classifiers Package"""
1414

1515
from .neural_network_classifier import NeuralNetworkClassifier
16-
from .qsvc import QSVC
1716
from .pegasos_qsvc import PegasosQSVC
17+
from .qsvc import QSVC
1818
from .vqc import VQC
1919

2020
__all__ = ["NeuralNetworkClassifier", "QSVC", "PegasosQSVC", "VQC"]

qiskit_machine_learning/algorithms/classifiers/vqc.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,21 @@
1212
"""An implementation of variational quantum classifier."""
1313

1414
from __future__ import annotations
15+
1516
from typing import Callable
1617

1718
import numpy as np
18-
1919
from qiskit import QuantumCircuit
20-
from qiskit.primitives import BaseSamplerV2 # change: BaseSampler is migrated to BaseSamplerV2
20+
from qiskit.primitives import BaseSamplerV2
2121
from qiskit.transpiler.passmanager import BasePassManager
2222

2323
from ...neural_networks import SamplerQNN
24-
from ...optimizers import Optimizer, OptimizerResult, Minimizer
24+
from ...optimizers import Minimizer, Optimizer, OptimizerResult
2525
from ...utils import derive_num_qubits_feature_map_ansatz
2626
from ...utils.loss_functions import Loss
27-
2827
from .neural_network_classifier import NeuralNetworkClassifier
2928

29+
3030
class VQC(NeuralNetworkClassifier):
3131
r"""A convenient Variational Quantum Classifier implementation.
3232
@@ -57,7 +57,7 @@ def __init__(
5757
initial_point: np.ndarray | None = None,
5858
callback: Callable[[np.ndarray, float], None] | None = None,
5959
*,
60-
sampler: BaseSamplerV2 | None = None, # change: BaseSampler is migrated to BaseSamplerV2
60+
sampler: BaseSamplerV2 | None = None, # change: BaseSampler is migrated to BaseSamplerV2
6161
interpret: Callable[[int], int | tuple[int, ...]] | None = None,
6262
output_shape: int | None = None,
6363
pass_manager: BasePassManager | None = None,
@@ -107,7 +107,7 @@ def __init__(
107107
"""
108108

109109
num_qubits, feature_map, ansatz = derive_num_qubits_feature_map_ansatz(
110-
num_qubits, feature_map, ansatz, use_methods=True
110+
num_qubits, feature_map, ansatz
111111
)
112112

113113
if output_shape is None:
@@ -197,4 +197,4 @@ def _get_interpret(self, num_classes: int):
197197
def parity(x: int, num_classes: int = num_classes) -> int:
198198
return x % num_classes
199199

200-
return parity
200+
return parity

qiskit_machine_learning/algorithms/inference/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
# copyright notice, and modified files need to carry a notice indicating
1111
# that they have been altered from the originals.
1212

13-
""" Inference Package """
13+
"""Inference Package"""
1414

1515

1616
from .qbayesian import QBayesian

qiskit_machine_learning/algorithms/inference/qbayesian.py

Lines changed: 27 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,19 @@
1414
from __future__ import annotations
1515

1616
import copy
17-
from typing import Tuple, Dict, Set, List
17+
from typing import Dict, List, Set, Tuple
1818

19-
from qiskit import QuantumCircuit, ClassicalRegister
20-
from qiskit.quantum_info import Statevector
19+
from qiskit import ClassicalRegister, QuantumCircuit
2120
from qiskit.circuit import Qubit
2221
from qiskit.circuit.library import grover_operator
23-
from qiskit.primitives import BaseSamplerV2, StatevectorSampler # change: BaseSampler and Sampler are replaced by BaseSamplerV2 and StatevectorSampler
24-
from qiskit.transpiler.passmanager import BasePassManager
22+
from qiskit.primitives import (
23+
BaseSamplerV2,
24+
StatevectorSampler,
25+
)
26+
from qiskit.quantum_info import Statevector
2527
from qiskit.result import QuasiDistribution
28+
from qiskit.transpiler.passmanager import BasePassManager
2629

27-
from ...utils.deprecation import issue_deprecation_msg
2830

2931
class QBayesian:
3032
r"""
@@ -66,7 +68,7 @@ def __init__(
6668
*,
6769
limit: int = 10,
6870
threshold: float = 0.9,
69-
sampler: BaseSamplerV2 | None = None, # change: BaseSampler is replaced by BaseSamplerV2
71+
sampler: BaseSamplerV2 | None = None,
7072
pass_manager: BasePassManager | None = None,
7173
):
7274
"""
@@ -95,15 +97,7 @@ def __init__(
9597
self._limit = limit
9698
self._threshold = threshold
9799
if sampler is None:
98-
sampler = StatevectorSampler() # change: Sampler is replaced by StatevectorSampler
99-
100-
if isinstance(sampler, BaseSamplerV2): # change: BaseSamplerV1 is replaced by BaseSamplerV2
101-
issue_deprecation_msg(
102-
msg="V1 Primitives are deprecated",
103-
version="0.8.0",
104-
remedy="Use V2 primitives for continued compatibility and support.",
105-
period="4 months",
106-
)
100+
sampler = StatevectorSampler()
107101

108102
self._sampler = sampler
109103

@@ -166,34 +160,22 @@ def _run_circuit(self, circuit: QuantumCircuit) -> Dict[str, float]:
166160
"""Run the quantum circuit with the sampler."""
167161
counts = {}
168162

169-
if isinstance(self._sampler, BaseSamplerV2): # change: BaseSampler is replaced by BaseSamplerV2
170-
# Sample from circuit
171-
job = self._sampler.run(circuit)
172-
result = job.result()
163+
# Sample from circuit
164+
if self._pass_manager is not None:
165+
circuit = self._pass_manager.run(circuit)
166+
job = self._sampler.run([circuit])
167+
result = job.result()
173168

174-
# Get the counts of quantum state results
175-
counts = result.quasi_dists[0].nearest_probability_distribution().binary_probabilities()
169+
bit_array = list(result[0].data.values())[0]
170+
bitstring_counts = bit_array.get_counts()
176171

177-
elif isinstance(self._sampler, BaseSamplerV2): # change: BaseSamplerV2 is replaced by BaseSamplerV2
178-
# Sample from circuit
179-
if self._pass_manager is not None:
180-
circuit = self._pass_manager.run(circuit)
181-
job = self._sampler.run([circuit])
182-
result = job.result()
183-
184-
bit_array = list(result[0].data.values())[0]
185-
bitstring_counts = bit_array.get_counts()
186-
187-
# Normalize the counts to probabilities
188-
total_shots = sum(bitstring_counts.values())
189-
probabilities = {k: v / total_shots for k, v in bitstring_counts.items()}
190-
# Convert to quasi-probabilities
191-
quasi_dist = QuasiDistribution(probabilities)
192-
binary_prob = quasi_dist.nearest_probability_distribution().binary_probabilities()
193-
counts = {k: v for k, v in binary_prob.items() if int(k) < 2**self.num_virtual_qubits}
194-
195-
# counts = QuasiDistribution(probabilities)
196-
# counts = {k: v for k, v in counts.items()}
172+
# Normalize the counts to probabilities
173+
total_shots = sum(bitstring_counts.values())
174+
probabilities = {k: v / total_shots for k, v in bitstring_counts.items()}
175+
# Convert to quasi-probabilities
176+
quasi_dist = QuasiDistribution(probabilities)
177+
binary_prob = quasi_dist.nearest_probability_distribution().binary_probabilities()
178+
counts = {k: v for k, v in binary_prob.items() if int(k) < 2**self.num_virtual_qubits}
197179

198180
return counts
199181

@@ -411,12 +393,12 @@ def limit(self, limit: int):
411393
self._limit = limit
412394

413395
@property
414-
def sampler(self) -> BaseSamplerV2: # change: BaseSampler is replaced by BaseSamplerV2
396+
def sampler(self) -> BaseSamplerV2:
415397
"""Returns the sampler primitive used to compute the samples."""
416398
return self._sampler
417399

418400
@sampler.setter
419-
def sampler(self, sampler: BaseSamplerV2): # change: BaseSampler is replaced by BaseSamplerV2
401+
def sampler(self, sampler: BaseSamplerV2):
420402
"""Set the sampler primitive used to compute the samples."""
421403
self._sampler = sampler
422404

@@ -428,4 +410,4 @@ def threshold(self) -> float:
428410
@threshold.setter
429411
def threshold(self, threshold: float):
430412
"""Set the threshold to accept the evidence."""
431-
self._threshold = threshold
413+
self._threshold = threshold

qiskit_machine_learning/algorithms/regressors/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
# copyright notice, and modified files need to carry a notice indicating
1111
# that they have been altered from the originals.
1212

13-
""" Regressors Package"""
13+
"""Regressors Package"""
1414

15-
from .qsvr import QSVR
1615
from .neural_network_regressor import NeuralNetworkRegressor
16+
from .qsvr import QSVR
1717
from .vqr import VQR
1818

1919
__all__ = ["QSVR", "VQR", "NeuralNetworkRegressor"]

qiskit_machine_learning/algorithms/regressors/vqr.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,16 @@
1616

1717
import numpy as np
1818
from qiskit import QuantumCircuit
19-
from qiskit.primitives import BaseEstimatorV2 # change: BaseEstimator is migrated to BaseEstimatorV2
19+
from qiskit.primitives import BaseEstimatorV2
2020
from qiskit.quantum_info.operators.base_operator import BaseOperator
2121
from qiskit.transpiler.passmanager import BasePassManager
2222

23-
from .neural_network_regressor import NeuralNetworkRegressor
2423
from ...neural_networks import EstimatorQNN
25-
from ...optimizers import Optimizer, Minimizer
24+
from ...optimizers import Minimizer, Optimizer
2625
from ...utils import derive_num_qubits_feature_map_ansatz
2726
from ...utils.loss_functions import Loss
27+
from .neural_network_regressor import NeuralNetworkRegressor
28+
2829

2930
class VQR(NeuralNetworkRegressor):
3031
"""A convenient Variational Quantum Regressor implementation."""
@@ -42,7 +43,7 @@ def __init__(
4243
initial_point: np.ndarray | None = None,
4344
callback: Callable[[np.ndarray, float], None] | None = None,
4445
*,
45-
estimator: BaseEstimatorV2 | None = None, # change: BaseEstimator is migrated to BaseEstimatorV2
46+
estimator: BaseEstimatorV2 | None = None,
4647
pass_manager: BasePassManager | None = None,
4748
) -> None:
4849
r"""
@@ -93,7 +94,7 @@ def __init__(
9394
self._estimator = estimator
9495

9596
num_qubits, feature_map, ansatz = derive_num_qubits_feature_map_ansatz(
96-
num_qubits, feature_map, ansatz, use_methods=True
97+
num_qubits, feature_map, ansatz
9798
)
9899

99100
# construct circuit
@@ -144,4 +145,4 @@ def ansatz(self) -> QuantumCircuit:
144145
@property
145146
def num_qubits(self) -> int:
146147
"""Returns the number of qubits used by ansatz and feature map."""
147-
return self._num_qubits
148+
return self._num_qubits

qiskit_machine_learning/circuit/library/qnn_circuit.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@
1212

1313
"""The QNN circuit."""
1414
from __future__ import annotations
15+
1516
from typing import List
1617

17-
from qiskit.circuit import QuantumRegister, QuantumCircuit
18-
from qiskit.circuit.parametertable import ParameterView
18+
from qiskit.circuit import QuantumCircuit, QuantumRegister
1919
from qiskit.circuit.library import BlueprintCircuit
20+
from qiskit.circuit.parametertable import ParameterView
2021

2122
from qiskit_machine_learning import QiskitMachineLearningError
2223

@@ -119,7 +120,7 @@ def qnn_circuit(
119120
"""
120121
# Check if circuit is constructed with valid configuration and set properties accordingly.
121122
num_qubits, feature_map, ansatz = derive_num_qubits_feature_map_ansatz(
122-
num_qubits, feature_map, ansatz, use_methods=True
123+
num_qubits, feature_map, ansatz
123124
)
124125
qc = QuantumCircuit(num_qubits)
125126
qc.compose(feature_map, inplace=True)

qiskit_machine_learning/exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
# copyright notice, and modified files need to carry a notice indicating
1111
# that they have been altered from the originals.
1212

13-
""" Machine Learning Exception """
13+
"""Machine Learning Exception"""
1414

1515
from qiskit.exceptions import QiskitError
1616

0 commit comments

Comments
 (0)