Skip to content

Commit 2d2a249

Browse files
edoaltamuraFrancescaSchiavOkuyanBogadeclanmillarwoodsp-ibm
authored
Support for V2 primitives (#843)
* Update README.md * Generalize the Einstein summation signature * Add reno * Update Copyright * Rename and add test * Update Copyright * Add docstring for `test_get_einsum_signature` * Correct spelling * Disable spellcheck for comments * Add `docstring` in pylint dict * Delete example in docstring * Add Einstein in pylint dict * Add full use case in einsum dict * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (2/2) * Update RuntimeError msg * Update RuntimeError msg - line too long * Trigger CI * Merge algos, globals.random to fix * Fixed `algorithms_globals` * Import /tests and run CI locally * Fix copyrights and some spellings * Ignore mypy in 8 instances * Merge spell dicts * Black reformatting * Black reformatting * Add reno * Lint sanitize * Pylint * Pylint * Pylint * Pylint * Fix relative imports in tutorials * Fix relative imports in tutorials * Remove algorithms from Jupyter magic methods * Temporarily disable "Run stable tutorials" tests * Change the docstrings with imports from qiskit_algorithms * Styling * Update qiskit_machine_learning/optimizers/gradient_descent.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Add more tests for utils * Add more tests for optimizers: adam, bobyqa, gsls and imfil * Fix random seed for volatile optimizers * Fix random seed for volatile optimizers * Add more tests * Pylint dict * Activate scikit-quant-0.8.2 * Remove scikit-quant methods * Remove scikit-quant methods (2) * Edit the release notes and Qiskit version 1+ * Edit the release notes and Qiskit version 1+ * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Apply line breaks * Restructure line breaks * Added support for SamplerV2 primitives (#49) * Migrating `qiskit_algorithms` (#817) * Update README.md * Generalize the Einstein summation signature * Add reno * Update Copyright * Rename and add test * Update Copyright * Add docstring for `test_get_einsum_signature` * Correct spelling * Disable spellcheck for comments * Add `docstring` in pylint dict * Delete example in docstring * Add Einstein in pylint dict * Add full use case in einsum dict * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (2/2) * Update RuntimeError msg * Update RuntimeError msg - line too long * Trigger CI * Merge algos, globals.random to fix * Fixed `algorithms_globals` * Import /tests and run CI locally * Fix copyrights and some spellings * Ignore mypy in 8 instances * Merge spell dicts * Black reformatting * Black reformatting * Add reno * Lint sanitize * Pylint * Pylint * Pylint * Pylint * Fix relative imports in tutorials * Fix relative imports in tutorials * Remove algorithms from Jupyter magic methods * Temporarily disable "Run stable tutorials" tests * Change the docstrings with imports from qiskit_algorithms * Styling * Update qiskit_machine_learning/optimizers/gradient_descent.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Add more tests for utils * Add more tests for optimizers: adam, bobyqa, gsls and imfil * Fix random seed for volatile optimizers * Fix random seed for volatile optimizers * Add more tests * Pylint dict * Activate scikit-quant-0.8.2 * Remove scikit-quant methods * Remove scikit-quant methods (2) * Edit the release notes and Qiskit version 1+ * Edit the release notes and Qiskit version 1+ * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Apply line breaks * Restructure line breaks --------- Co-authored-by: FrancescaSchiav <FrancescaSchiav@users.noreply.github.com> Co-authored-by: M. Emre Sahin <40424147+OkuyanBoga@users.noreply.github.com> Co-authored-by: Declan Millar <declan.millar@ibm.com> * Revamp readme pt2 (#822) * Restructure README.md --------- Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> * V2 Primitive Support for SamplerQNN and Gradients * Update base_sampler_gradient.py * Update qiskit_machine_learning/gradients/param_shift/param_shift_sampler_gradient.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/gradients/spsa/spsa_sampler_gradient.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/gradients/spsa/spsa_sampler_gradient.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/sampler_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/sampler_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/sampler_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/sampler_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/sampler_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/sampler_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Fix lint errors due to Pylint 3.3.0 update in CI (#833) * disable=too-many-positional-arguments * Transfer pylint rc to toml * Transfer pylint rc to toml * Minor fixes * Remove Python 3.8 from CI (#824) (#826) * Remove Python 3.8 in CI (#824) * Correct `tmp` dirs (#818) * Correct unit py version (#818) * Add reno (#818) * Finalze removal of py38 (#818) * Spelling * Remove duplicate tmp folder * Updated the release note * Bump min pyversion in toml * Remove ipython constraints * Update reno * Updated test for test_sampler_qnn * Fix: output_shape * Adding optimisation level to TestSamplerQNN SamplerV2 option * Correcting the PUB prep for SamplerV2 by changing max iterator from n to len(job_param_values). Added a load of print statements to investigate behaviour when self._output_shape = (2, 3) - a tuple as this was failing tests due to a comparison in line 166. This has lead me to think that the way we are calculating QuasiDistribution is wrong as we need to know which real qubits the virtual qubits have been transpiled too to calculate the correct dist for SamplerV2. Following this up with IBM runtime. * Update sampler_qnn.py for correcting tuple output_shape when interpret is provided. * Adding ISA capabilities to gradients * Fix output shape and its default for V2 * Implement SamplerV2 for bayesian inference * Implement SamplerV2 for bayesian inference * Adding ISA capabilities to SamplerQNN and ParamShiftSamplerGradient * Removing unused backend * Removing failed merge conflicts * Removing residual merge conflicts * added SamplerV2 support for ComputeUncompute * Removing multiple tranpilations within same test * Formatting * Linting * Adding measure_all to setUp * removing default pm --------- Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> Co-authored-by: FrancescaSchiav <FrancescaSchiav@users.noreply.github.com> Co-authored-by: Declan Millar <declan.millar@ibm.com> Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> Co-authored-by: oscar-wallis <oscar.wallis@outlook.com> * Added support for EstimatorV2 primitives (#48) * Migrating `qiskit_algorithms` (#817) * Update README.md * Generalize the Einstein summation signature * Add reno * Update Copyright * Rename and add test * Update Copyright * Add docstring for `test_get_einsum_signature` * Correct spelling * Disable spellcheck for comments * Add `docstring` in pylint dict * Delete example in docstring * Add Einstein in pylint dict * Add full use case in einsum dict * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (2/2) * Update RuntimeError msg * Update RuntimeError msg - line too long * Trigger CI * Merge algos, globals.random to fix * Fixed `algorithms_globals` * Import /tests and run CI locally * Fix copyrights and some spellings * Ignore mypy in 8 instances * Merge spell dicts * Black reformatting * Black reformatting * Add reno * Lint sanitize * Pylint * Pylint * Pylint * Pylint * Fix relative imports in tutorials * Fix relative imports in tutorials * Remove algorithms from Jupyter magic methods * Temporarily disable "Run stable tutorials" tests * Change the docstrings with imports from qiskit_algorithms * Styling * Update qiskit_machine_learning/optimizers/gradient_descent.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Add more tests for utils * Add more tests for optimizers: adam, bobyqa, gsls and imfil * Fix random seed for volatile optimizers * Fix random seed for volatile optimizers * Add more tests * Pylint dict * Activate scikit-quant-0.8.2 * Remove scikit-quant methods * Remove scikit-quant methods (2) * Edit the release notes and Qiskit version 1+ * Edit the release notes and Qiskit version 1+ * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Apply line breaks * Restructure line breaks --------- Co-authored-by: FrancescaSchiav <FrancescaSchiav@users.noreply.github.com> Co-authored-by: M. Emre Sahin <40424147+OkuyanBoga@users.noreply.github.com> Co-authored-by: Declan Millar <declan.millar@ibm.com> * Revamp readme pt2 (#822) * Restructure README.md --------- Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> * Added support for EstimatorV2 primitives * Update qiskit_machine_learning/neural_networks/estimator_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/estimator_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/estimator_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/estimator_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/gradients/param_shift/param_shift_estimator_gradient.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/gradients/spsa/spsa_estimator_gradient.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/gradients/param_shift/param_shift_estimator_gradient.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/estimator_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/neural_networks/estimator_qnn.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Update qiskit_machine_learning/gradients/param_shift/param_shift_estimator_gradient.py Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> * Fix lint errors due to Pylint 3.3.0 update in CI (#833) * disable=too-many-positional-arguments * Transfer pylint rc to toml * Transfer pylint rc to toml * Cleaner statements * Remove Python 3.8 from CI (#824) (#826) * Remove Python 3.8 in CI (#824) * Correct `tmp` dirs (#818) * Correct unit py version (#818) * Add reno (#818) * Finalze removal of py38 (#818) * Spelling * Remove duplicate tmp folder * Updated the release note * Bump min pyversion in toml * Remove ipython constraints * Update reno * Added unit tests for estimatorqnnV2 and minor fixes * Make black * Make lint and changes to V1/2 choice logics * Update requirements * Add default precision * Update estimator tests * Change num qubits in backend * Allow for num_qubits=None * Fix shape in parameter shift * Fix shape in parameter shift * Fix shape observables * Fix shape observables * Change default precision to match base estimator * Fix remaining shape issues * Estimator seed has no effect in local testing * fix argnames and supress error tolerance for test_estimator_qnn_v2 * Added pass manager the gradients. * quick bugfix for isa_circuits * Updating PUBs for estimatorqnn, updating test_estimator_qnn_v2 for ISA circs and relaxing tolerances * Lint and formatting * Tranpiling observables for isa g circs * fixing apply_layout --------- Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> Co-authored-by: FrancescaSchiav <FrancescaSchiav@users.noreply.github.com> Co-authored-by: Declan Millar <declan.millar@ibm.com> Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> Co-authored-by: oscar-wallis <oscar.wallis@outlook.com> * Pulled changes from main * Quick fix * bugfix for V1 * formatting * Prep-ing for 0.8 (#53) * Migrating `qiskit_algorithms` (#817) * Update README.md * Generalize the Einstein summation signature * Add reno * Update Copyright * Rename and add test * Update Copyright * Add docstring for `test_get_einsum_signature` * Correct spelling * Disable spellcheck for comments * Add `docstring` in pylint dict * Delete example in docstring * Add Einstein in pylint dict * Add full use case in einsum dict * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Spelling and type ignore * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (1/2) * Remove for loop in einsum function and remove Literal arguments (2/2) * Update RuntimeError msg * Update RuntimeError msg - line too long * Trigger CI * Merge algos, globals.random to fix * Fixed `algorithms_globals` * Import /tests and run CI locally * Fix copyrights and some spellings * Ignore mypy in 8 instances * Merge spell dicts * Black reformatting * Black reformatting * Add reno * Lint sanitize * Pylint * Pylint * Pylint * Pylint * Fix relative imports in tutorials * Fix relative imports in tutorials * Remove algorithms from Jupyter magic methods * Temporarily disable "Run stable tutorials" tests * Change the docstrings with imports from qiskit_algorithms * Styling * Update qiskit_machine_learning/optimizers/gradient_descent.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py Co-authored-by: Declan Millar <declan.millar@ibm.com> * Add more tests for utils * Add more tests for optimizers: adam, bobyqa, gsls and imfil * Fix random seed for volatile optimizers * Fix random seed for volatile optimizers * Add more tests * Pylint dict * Activate scikit-quant-0.8.2 * Remove scikit-quant methods * Remove scikit-quant methods (2) * Edit the release notes and Qiskit version 1+ * Edit the release notes and Qiskit version 1+ * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Add Qiskit 1.0 upgrade in reno * Apply line breaks * Restructure line breaks --------- Co-authored-by: FrancescaSchiav <FrancescaSchiav@users.noreply.github.com> Co-authored-by: M. Emre Sahin <40424147+OkuyanBoga@users.noreply.github.com> Co-authored-by: Declan Millar <declan.millar@ibm.com> * Revamp readme pt2 (#822) * Restructure README.md --------- Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> * Fix lint errors due to Pylint 3.3.0 update in CI (#833) * disable=too-many-positional-arguments * Transfer pylint rc to toml * Transfer pylint rc to toml * Remove Python 3.8 from CI (#824) (#826) * Remove Python 3.8 in CI (#824) * Correct `tmp` dirs (#818) * Correct unit py version (#818) * Add reno (#818) * Finalze removal of py38 (#818) * Spelling * Remove duplicate tmp folder * Updated the release note * Bump min pyversion in toml * Remove ipython constraints * Update reno * Reestablish latest Pytorch and Numpy (#818) (#827) * Reestablish latest Pytorch and Numpy (#818) * Keep pinned Numpy * Keep pinned Numpy * Fix numpy min version * Fix RawFeatureVector for failing test case (#838) * Alter RawFeatureVector normalization * Alter RawFeatureVector normalization * Release nbconvert constraints (#842) * Remove redundant MacOS 14 image in CI (#841) * Remove redundant MacOS 14 image * Update with macos-latest-large * Revert "Update with macos-latest-large" This reverts commit 14f945e. * Update with macos-latest-large * Update v2 (#54) * bugfix for V1 * formatting --------- Co-authored-by: oscar-wallis <oscar.wallis@outlook.com> --------- Co-authored-by: Edoardo Altamura <38359901+edoaltamura@users.noreply.github.com> Co-authored-by: FrancescaSchiav <FrancescaSchiav@users.noreply.github.com> Co-authored-by: M. Emre Sahin <40424147+OkuyanBoga@users.noreply.github.com> Co-authored-by: Declan Millar <declan.millar@ibm.com> Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> * Update test_qbayesian * Bugfixing the test_gradient * Fixing an Options error with sampler_gradient * Linting and formatting * Add reno * Fix dict typing definition * Fix mypy * Issue deprecation warnings * Update skip test message * Update deprecation warning for qbayesian.py * Update deprecation warning for qbayesian.py * Add headers in deprecation.py * Add headers in deprecation.py * Add headers in deprecation.py * Correct spelling * Add spelling `msg` --------- Co-authored-by: FrancescaSchiav <FrancescaSchiav@users.noreply.github.com> Co-authored-by: M. Emre Sahin <40424147+OkuyanBoga@users.noreply.github.com> Co-authored-by: Declan Millar <declan.millar@ibm.com> Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> Co-authored-by: oscar-wallis <oscar.wallis@outlook.com> Co-authored-by: Emre <mustafaemresahin@outlook.com> Co-authored-by: Oscar <108736468+oscar-wallis@users.noreply.github.com>
1 parent fe7ea66 commit 2d2a249

21 files changed

+1581
-168
lines changed

.github/workflows/main.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,4 +312,4 @@ jobs:
312312
env:
313313
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
314314
run: coveralls --service=github
315-
shell: bash
315+
shell: bash

.pylintdict

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ monte
312312
mosca
313313
mpl
314314
mprev
315+
msg
315316
multiclass
316317
multinomial
317318
multioutput
@@ -501,6 +502,7 @@ sparsearray
501502
spedalieri
502503
spsa
503504
sqrt
505+
stacklevel
504506
statefn
505507
statevector
506508
statevectors

qiskit_machine_learning/algorithms/inference/qbayesian.py

Lines changed: 56 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,17 @@
1515

1616
import copy
1717
from typing import Tuple, Dict, Set, List
18+
1819
from qiskit import QuantumCircuit, ClassicalRegister
1920
from qiskit.quantum_info import Statevector
20-
from qiskit.circuit.library import GroverOperator
21-
from qiskit.primitives import BaseSampler, Sampler
2221
from qiskit.circuit import Qubit
22+
from qiskit.circuit.library import GroverOperator
23+
from qiskit.primitives import BaseSampler, Sampler, BaseSamplerV2, BaseSamplerV1
24+
from qiskit.transpiler.passmanager import BasePassManager
25+
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
26+
from qiskit.providers.fake_provider import GenericBackendV2
27+
28+
from ...utils.deprecation import issue_deprecation_msg
2329

2430

2531
class QBayesian:
@@ -62,7 +68,8 @@ def __init__(
6268
*,
6369
limit: int = 10,
6470
threshold: float = 0.9,
65-
sampler: BaseSampler | None = None,
71+
sampler: BaseSampler | BaseSamplerV2 | None = None,
72+
pass_manager: BasePassManager | None = None,
6673
):
6774
"""
6875
Args:
@@ -83,15 +90,30 @@ def __init__(
8390
# Test valid input
8491
for qrg in circuit.qregs:
8592
if qrg.size > 1:
86-
raise ValueError("Every register needs to be mapped to exactly one unique qubit")
93+
raise ValueError("Every register needs to be mapped to exactly one unique qubit.")
94+
8795
# Initialize parameter
8896
self._circ = circuit
8997
self._limit = limit
9098
self._threshold = threshold
9199
if sampler is None:
92100
sampler = Sampler()
101+
102+
if isinstance(sampler, BaseSamplerV1):
103+
issue_deprecation_msg(
104+
msg="V1 Primitives are deprecated",
105+
version="0.8.0",
106+
remedy="Use V2 primitives for continued compatibility and support.",
107+
period="4 months",
108+
)
109+
93110
self._sampler = sampler
94111

112+
if pass_manager is None:
113+
_backend = GenericBackendV2(num_qubits=max(circuit.num_qubits, 2))
114+
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=_backend)
115+
self._pass_manager = pass_manager
116+
95117
# Label of register mapped to its qubit
96118
self._label2qubit = {qrg.name: qrg[0] for qrg in self._circ.qregs}
97119
# Label of register mapped to its qubit index bottom up in significance
@@ -139,11 +161,34 @@ def _get_grover_op(self, evidence: Dict[str, int]) -> GroverOperator:
139161

140162
def _run_circuit(self, circuit: QuantumCircuit) -> Dict[str, float]:
141163
"""Run the quantum circuit with the sampler."""
142-
# Sample from circuit
143-
job = self._sampler.run(circuit)
144-
result = job.result()
145-
# Get the counts of quantum state results
146-
counts = result.quasi_dists[0].nearest_probability_distribution().binary_probabilities()
164+
counts = {}
165+
166+
if isinstance(self._sampler, BaseSampler):
167+
# Sample from circuit
168+
job = self._sampler.run(circuit)
169+
result = job.result()
170+
171+
# Get the counts of quantum state results
172+
counts = result.quasi_dists[0].nearest_probability_distribution().binary_probabilities()
173+
174+
elif isinstance(self._sampler, BaseSamplerV2):
175+
176+
# Sample from circuit
177+
circuit_isa = self._pass_manager.run(circuit)
178+
job = self._sampler.run([circuit_isa])
179+
result = job.result()
180+
181+
bit_array = list(result[0].data.values())[0]
182+
bitstring_counts = bit_array.get_counts()
183+
184+
# Normalize the counts to probabilities
185+
total_shots = result[0].metadata["shots"]
186+
counts = {k: v / total_shots for k, v in bitstring_counts.items()}
187+
188+
# Convert to quasi-probabilities
189+
# counts = QuasiDistribution(probabilities)
190+
# counts = {k: v for k, v in counts.items()}
191+
147192
return counts
148193

149194
def __power_grover(
@@ -360,12 +405,12 @@ def limit(self, limit: int):
360405
self._limit = limit
361406

362407
@property
363-
def sampler(self) -> BaseSampler:
408+
def sampler(self) -> BaseSampler | BaseSamplerV2:
364409
"""Returns the sampler primitive used to compute the samples."""
365410
return self._sampler
366411

367412
@sampler.setter
368-
def sampler(self, sampler: BaseSampler):
413+
def sampler(self, sampler: BaseSampler | BaseSamplerV2):
369414
"""Set the sampler primitive used to compute the samples."""
370415
self._sampler = sampler
371416

qiskit_machine_learning/gradients/base/base_estimator_gradient.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,13 @@
2323
import numpy as np
2424

2525
from qiskit.circuit import Parameter, ParameterExpression, QuantumCircuit
26-
from qiskit.primitives import BaseEstimator
26+
from qiskit.primitives import BaseEstimator, BaseEstimatorV1
27+
from qiskit.primitives.base import BaseEstimatorV2
2728
from qiskit.primitives.utils import _circuit_key
2829
from qiskit.providers import Options
2930
from qiskit.quantum_info.operators.base_operator import BaseOperator
3031
from qiskit.transpiler.passes import TranslateParameterizedGates
32+
from qiskit.transpiler.passmanager import BasePassManager
3133

3234
from .estimator_gradient_result import EstimatorGradientResult
3335
from ..utils import (
@@ -37,7 +39,7 @@
3739
_make_gradient_parameters,
3840
_make_gradient_parameter_values,
3941
)
40-
42+
from ...utils.deprecation import issue_deprecation_msg
4143
from ...algorithm_job import AlgorithmJob
4244

4345

@@ -46,13 +48,15 @@ class BaseEstimatorGradient(ABC):
4648

4749
def __init__(
4850
self,
49-
estimator: BaseEstimator,
51+
estimator: BaseEstimator | BaseEstimatorV2,
5052
options: Options | None = None,
5153
derivative_type: DerivativeType = DerivativeType.REAL,
54+
pass_manager: BasePassManager | None = None,
5255
):
5356
r"""
5457
Args:
5558
estimator: The estimator used to compute the gradients.
59+
pass_manager: pass manager for isa_circuit transpilation.
5660
options: Primitive backend runtime options used for circuit execution.
5761
The order of priority is: options in ``run`` method > gradient's
5862
default options > primitive's default setting.
@@ -68,7 +72,15 @@ def __init__(
6872
gradient and this type is the only supported type for function-level schemes like
6973
finite difference.
7074
"""
75+
if isinstance(estimator, BaseEstimatorV1):
76+
issue_deprecation_msg(
77+
msg="V1 Primitives are deprecated",
78+
version="0.8.0",
79+
remedy="Use V2 primitives for continued compatibility and support.",
80+
period="4 months",
81+
)
7182
self._estimator: BaseEstimator = estimator
83+
self._pass_manager = pass_manager
7284
self._default_options = Options()
7385
if options is not None:
7486
self._default_options.update_options(**options)
@@ -92,7 +104,7 @@ def run(
92104
self,
93105
circuits: Sequence[QuantumCircuit],
94106
observables: Sequence[BaseOperator],
95-
parameter_values: Sequence[Sequence[float]],
107+
parameter_values: Sequence[Sequence[float]] | np.ndarray,
96108
parameters: Sequence[Sequence[Parameter] | None] | None = None,
97109
**options,
98110
) -> AlgorithmJob:
@@ -157,7 +169,7 @@ def _run(
157169
self,
158170
circuits: Sequence[QuantumCircuit],
159171
observables: Sequence[BaseOperator],
160-
parameter_values: Sequence[Sequence[float]],
172+
parameter_values: Sequence[Sequence[float]] | np.ndarray,
161173
parameters: Sequence[Sequence[Parameter]],
162174
**options,
163175
) -> EstimatorGradientResult:
@@ -167,7 +179,7 @@ def _run(
167179
def _preprocess(
168180
self,
169181
circuits: Sequence[QuantumCircuit],
170-
parameter_values: Sequence[Sequence[float]],
182+
parameter_values: Sequence[Sequence[float]] | np.ndarray,
171183
parameters: Sequence[Sequence[Parameter]],
172184
supported_gates: Sequence[str],
173185
) -> tuple[Sequence[QuantumCircuit], Sequence[Sequence[float]], Sequence[Sequence[Parameter]]]:
@@ -209,7 +221,7 @@ def _postprocess(
209221
self,
210222
results: EstimatorGradientResult,
211223
circuits: Sequence[QuantumCircuit],
212-
parameter_values: Sequence[Sequence[float]],
224+
parameter_values: Sequence[Sequence[float]] | np.ndarray,
213225
parameters: Sequence[Sequence[Parameter]],
214226
) -> EstimatorGradientResult:
215227
"""Postprocess the gradients. This method computes the gradient of the original circuits
@@ -269,7 +281,7 @@ def _postprocess(
269281
def _validate_arguments(
270282
circuits: Sequence[QuantumCircuit],
271283
observables: Sequence[BaseOperator],
272-
parameter_values: Sequence[Sequence[float]],
284+
parameter_values: Sequence[Sequence[float]] | np.ndarray,
273285
parameters: Sequence[Sequence[Parameter]],
274286
) -> None:
275287
"""Validate the arguments of the ``run`` method.

qiskit_machine_learning/gradients/base/base_sampler_gradient.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,11 @@
2222
from copy import copy
2323

2424
from qiskit.circuit import Parameter, ParameterExpression, QuantumCircuit
25-
from qiskit.primitives import BaseSampler
25+
from qiskit.primitives import BaseSampler, BaseSamplerV1
2626
from qiskit.primitives.utils import _circuit_key
2727
from qiskit.providers import Options
2828
from qiskit.transpiler.passes import TranslateParameterizedGates
29+
from qiskit.transpiler.passmanager import BasePassManager
2930

3031
from .sampler_gradient_result import SamplerGradientResult
3132
from ..utils import (
@@ -34,14 +35,20 @@
3435
_make_gradient_parameters,
3536
_make_gradient_parameter_values,
3637
)
37-
38+
from ...utils.deprecation import issue_deprecation_msg
3839
from ...algorithm_job import AlgorithmJob
3940

4041

4142
class BaseSamplerGradient(ABC):
4243
"""Base class for a ``SamplerGradient`` to compute the gradients of the sampling probability."""
4344

44-
def __init__(self, sampler: BaseSampler, options: Options | None = None):
45+
def __init__(
46+
self,
47+
sampler: BaseSampler,
48+
options: Options | None = None,
49+
len_quasi_dist: int | None = None,
50+
pass_manager: BasePassManager | None = None,
51+
):
4552
"""
4653
Args:
4754
sampler: The sampler used to compute the gradients.
@@ -50,7 +57,16 @@ def __init__(self, sampler: BaseSampler, options: Options | None = None):
5057
default options > primitive's default setting.
5158
Higher priority setting overrides lower priority setting
5259
"""
60+
if isinstance(sampler, BaseSamplerV1):
61+
issue_deprecation_msg(
62+
msg="V1 Primitives are deprecated",
63+
version="0.8.0",
64+
remedy="Use V2 primitives for continued compatibility and support.",
65+
period="4 months",
66+
)
5367
self._sampler: BaseSampler = sampler
68+
self._pass_manager = pass_manager
69+
self._len_quasi_dist = len_quasi_dist
5470
self._default_options = Options()
5571
if options is not None:
5672
self._default_options.update_options(**options)

qiskit_machine_learning/gradients/lin_comb/lin_comb_estimator_gradient.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def _run(
9898
self,
9999
circuits: Sequence[QuantumCircuit],
100100
observables: Sequence[BaseOperator],
101-
parameter_values: Sequence[Sequence[float]],
101+
parameter_values: Sequence[Sequence[float]] | np.ndarray,
102102
parameters: Sequence[Sequence[Parameter]],
103103
**options,
104104
) -> EstimatorGradientResult:

0 commit comments

Comments
 (0)