Skip to content

Added V2 and ISA support #197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 92 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
92 commits
Select commit Hold shift + click to select a range
634dc69
Added TODO
tnemoz Aug 7, 2024
ecee0c6
Started to adapt to V2 primitives
tnemoz Aug 7, 2024
529c5da
Modified phase estimators to work with V2 primitives and ISA circuits
tnemoz Aug 9, 2024
e390037
Merge branch 'main' into main
woodsp-ibm Aug 9, 2024
da40425
Changed PassManager to more generic transpiler
tnemoz Aug 12, 2024
d83408c
Changed custom types to support Python 3.8
tnemoz Aug 12, 2024
0e6e6f0
Added transpiler to .pylintdict
tnemoz Aug 12, 2024
0e8ac74
Adapted Grover to V2 primitives
tnemoz Aug 12, 2024
3d79bb5
Changed custom types using __future__ annotations
tnemoz Aug 16, 2024
eae6cff
Adapated VQD to V2 primitives
tnemoz Aug 16, 2024
df69ea7
Adapted tests for Grover
tnemoz Aug 16, 2024
111188b
Fixed styling
tnemoz Aug 16, 2024
4b46931
Merge branch 'main' into main
tnemoz Aug 24, 2024
c03c3a1
Merge branch 'min_eigen' into dev
Aug 25, 2024
93af774
removed useless comments in vqe and changed SamplingVQE to match v2 p…
Aug 26, 2024
63332e9
changed AdaptVQE
Aug 26, 2024
1b58074
changed diagonal_estimators from v1 to v2 primitives
Aug 26, 2024
b48c66d
updated TODO
Aug 30, 2024
1cd76ff
changed qaoa to match v2 and isa
Aug 30, 2024
4f734d9
modified all associated tests for min_eigen classes
Aug 30, 2024
d7b671f
changed todo
Aug 30, 2024
d2bc2db
ComputeUncompute done
tnemoz Sep 2, 2024
cae37b2
QNSPSA done
tnemoz Sep 2, 2024
84128a8
Restored SPSA test to previous values
tnemoz Sep 10, 2024
b3c32a3
Refactored test for transpilers, make linter happy, test_vqd not passing
tnemoz Sep 10, 2024
dc075d0
Updated TODO
tnemoz Sep 10, 2024
0790c53
PVQD done
tnemoz Sep 10, 2024
7ff3ab6
Slight modifications of VQD, still isn't working
tnemoz Sep 18, 2024
bf6a931
Adapted PVQD to EstimatorV2
tnemoz Aug 16, 2024
dea4bd0
Adapted Trotter QRTE to EstimatorV2
tnemoz Aug 16, 2024
8d9a54c
Trotter QRTE
tnemoz Sep 18, 2024
8c87b8d
Time evolvers
tnemoz Dec 5, 2024
e3150cf
Merge branch 'main' into main
tnemoz Dec 5, 2024
3fcc265
Fixed linting and VQD test
tnemoz Dec 5, 2024
a1171dc
Updated TODO
tnemoz Dec 5, 2024
82f7ced
Merge branch 'main' into main
woodsp-ibm May 29, 2025
d45c9ad
started mlae.py, not finished
Aug 30, 2024
cefd334
finished mlae file
Oct 9, 2024
4b95ced
updated todo andneed to continue fae and addtranspilation to mlae and…
Oct 9, 2024
9eab51a
modified gradient base
Mar 14, 2025
3af5a57
started changes into gradients
Mar 29, 2025
fb4dcc6
finished finite-diff gradient
Mar 29, 2025
950b24e
Updated gradients test
tnemoz Mar 29, 2025
6fbd45e
updated reverse gradients
Mar 29, 2025
af1c097
updated lin_comb files, missing transpilation added to the TODO list …
Mar 29, 2025
c5a46b3
updated spsa estimator gradient
Mar 29, 2025
b4fcadb
finished spsa sampler
Mar 30, 2025
8fa65ce
finished lin comb
Mar 30, 2025
004e28c
started changes for tests
Mar 30, 2025
48e63f9
Amplitude estimators, tests failing but no errors
tnemoz Mar 29, 2025
b63a36e
Almost done, weird bug on transpiler test on mlae
tnemoz Mar 30, 2025
4299816
Amplitude estimatorsd done
tnemoz Apr 26, 2025
2c21f99
Updated TODO
tnemoz Apr 29, 2025
73fbb5d
Estimator gradients working
tnemoz Apr 29, 2025
2e78525
QGT working
tnemoz Apr 30, 2025
ee0597e
QFI working
tnemoz May 1, 2025
0610b7c
Sampler gradients working
tnemoz May 5, 2025
c9f823d
Started working on _DiagonalEstimator
tnemoz May 6, 2025
188c5ae
Continued working on _DiagonalEstimator
tnemoz May 6, 2025
dd53643
Continued working on _DiagonalEstimator #2, _call method todo
tnemoz May 12, 2025
d0e7203
Continued working on _DiagonalEstimator #3, test sampling_vqe todo
tnemoz May 13, 2025
cf84ba6
_DiagonalEstimator supposedly done, test with QNSPSA fails for now
tnemoz May 26, 2025
25f1c55
_DiagonalEstimator done
tnemoz May 27, 2025
941043b
SamplingVQE done
tnemoz May 27, 2025
207f365
Working QAOA
tnemoz May 27, 2025
822e204
Removed TODO and added more shots for the QAOA test
tnemoz May 27, 2025
757a277
Changed initial point in QAOA test to be able to seed
tnemoz May 27, 2025
6f39d76
Updated VQE tutorials
tnemoz May 29, 2025
fb47a1b
VQE working
tnemoz May 29, 2025
8c402ad
Most tutorials updated. QAOA to be checked, tweedldum to be removed f…
tnemoz Jun 2, 2025
bf2d326
Replaced test for transpiler
tnemoz Jun 2, 2025
aff31d8
Added pVQD to docs
tnemoz Jun 2, 2025
4ff895f
All tests passing
tnemoz Jun 2, 2025
75cc776
Removed aliases
tnemoz Jun 2, 2025
64b8352
Fixed time evolvers
tnemoz Jun 6, 2025
303bcb4
Added future imports annotations for Python 3.9
tnemoz Jun 6, 2025
47c22fb
Added copyrights
tnemoz Jun 6, 2025
d89db0b
Linting done, spelling to fix
tnemoz Jun 6, 2025
6d8a705
Spell checked
tnemoz Jun 6, 2025
e6db4f2
Rollback RealAmplitudes and EfficientSU2
tnemoz Jun 6, 2025
9ab842c
Additional copyrights and linting
tnemoz Jun 6, 2025
fb9c417
Removed strict=True in zip
tnemoz Jun 6, 2025
fc17c5d
Lowered precision of VQD test
tnemoz Jun 6, 2025
ba0c35d
Correct wrong import and line too long
tnemoz Jun 6, 2025
e33745b
Added tweedledum to dictionnary and added missing copyright
tnemoz Jun 6, 2025
515bc54
Corrected spelling in optional
tnemoz Jun 9, 2025
bceaf06
Seeded StatevectorSampler in gradients test
tnemoz Jun 9, 2025
924d2f3
black formatting
tnemoz Jun 9, 2025
f4dd0e6
Added _circuit_key
tnemoz Jun 9, 2025
3ec9df7
lback formatting circuit_key
tnemoz Jun 9, 2025
8d83580
Accessed _op_start_times private attribute
tnemoz Jun 9, 2025
077052d
Removed last instance of Estimator and changed ClassicalRegister impo…
tnemoz Jun 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions qiskit_algorithms/custom_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Types used by the qiskit-algorithms package."""

from typing import Any, List, Protocol, Union

from qiskit import QuantumCircuit

_Circuits = Union[List[QuantumCircuit], QuantumCircuit]
Copy link
Member

@woodsp-ibm woodsp-ibm Aug 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use list in 3.8 - which arguably is better and what we have tried to do elsewhere. You do need to add a future import to have that work from __future__ import annotations. You can see examples in this repo e.g. in this file which does that and uses it https://github.com/qiskit-community/qiskit-algorithms/blob/main/qiskit_algorithms/time_evolvers/pvqd/pvqd_result.py Though I am not sure here with custom types defs though as I see Union and elsewhere we try and use the | nowadays instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I initially went for

_Circuits = list[QuantumCircuit] | QuantumCircuit

but then make lint complained with:

************* Module qiskit_algorithms.custom_types
qiskit_algorithms/custom_types.py:21:12: E1131: unsupported operand type(s) for | (unsupported-binary-operation)

which is why I went for Union instead of |. Or is there a workaround I don't know of?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That future import is needed for | as well - but if you had that import then as I mentioned I was not not sure here as I recall having issues when defining types before using these newer aspects where we had to have them defined with the former Typing constructs. If you search in this repo you will find just a few Union hits where they are pretty much limited to being used in type defines like this - I also see List being used in the ones here so it may well be the same issue with that. I commented mostly as a saw the commit that changed things to fix it for lint in 3.8 from list to List that was all the change I did not see a from future import being removed which is needed to type things this newer way in 3.8.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One further comment around 3.8. Qiskit has already deprecated support for Python 3.8 and support will be removed in 1.3.0 which is due in Nov. Python 3.8 EOL is Oct this year so among the changes here it could be a choice to drop 3.8 support too along with these changes. To drop this would evidently also include dropping it from CI tests etc and bumping things to run at 3.9 min.

In talking about versions I will note 3.13 is planned to be available beginning of Oct. There is an issue on Qiskit Qiskit/qiskit#12903 to support this so again depending on timeline.... but hopefully that's just adding it as supported and to CI to test when dependencies are there and it just works!



class Transpiler(Protocol):
"""A Generic type to represent a transpiler."""

def run(self, circuits: _Circuits, **options: Any) -> _Circuits:
"""Transpile a circuit or a list of quantum circuits."""
pass
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2020, 2023.
# (C) Copyright IBM 2020, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -14,16 +14,16 @@

from __future__ import annotations


from qiskit import QuantumCircuit
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.primitives import BaseSampler
from qiskit.primitives import BaseSamplerV2
from qiskit.quantum_info import SparsePauliOp, Statevector, Pauli
from qiskit.synthesis import EvolutionSynthesis

from .phase_estimation import PhaseEstimation
from .hamiltonian_phase_estimation_result import HamiltonianPhaseEstimationResult
from .phase_estimation import PhaseEstimation
from .phase_estimation_scale import PhaseEstimationScale
from ..custom_types import Transpiler


class HamiltonianPhaseEstimation:
Expand Down Expand Up @@ -83,17 +83,22 @@ class HamiltonianPhaseEstimation:
def __init__(
self,
num_evaluation_qubits: int,
sampler: BaseSampler | None = None,
sampler: BaseSamplerV2 | None = None,
transpiler: Transpiler | None = None,
) -> None:
r"""
Args:
num_evaluation_qubits: The number of qubits used in estimating the phase. The phase will
be estimated as a binary string with this many bits.
sampler: The sampler primitive on which the circuit will be sampled.
transpiler: An optional object with a `run` method allowing to transpile the circuits
that are produced within this algorithm. If set to `None`, these won't be
transpiled.
"""
self._phase_estimation = PhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits,
sampler=sampler,
transpiler=transpiler,
)

def _get_scale(self, hamiltonian, bound=None) -> PhaseEstimationScale:
Expand Down
22 changes: 18 additions & 4 deletions qiskit_algorithms/phase_estimators/ipe.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2021, 2023.
# (C) Copyright IBM 2021, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -19,12 +19,13 @@

from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.primitives import BaseSampler
from qiskit.primitives import BaseSamplerV2

from qiskit_algorithms.exceptions import AlgorithmError

from .phase_estimator import PhaseEstimator
from .phase_estimator import PhaseEstimatorResult
from ..custom_types import Transpiler


class IterativePhaseEstimation(PhaseEstimator):
Expand All @@ -40,12 +41,16 @@ class IterativePhaseEstimation(PhaseEstimator):
def __init__(
self,
num_iterations: int,
sampler: BaseSampler | None = None,
sampler: BaseSamplerV2 | None = None,
transpiler: Transpiler | None = None,
) -> None:
r"""
Args:
num_iterations: The number of iterations (rounds) of the phase estimation to run.
sampler: The sampler primitive on which the circuit will be sampled.
transpiler: An optional object with a `run` method allowing to transpile the circuits
that are produced within this algorithm. If set to `None`, these won't be
transpiled.

Raises:
ValueError: if num_iterations is not greater than zero.
Expand All @@ -58,6 +63,7 @@ def __init__(
raise ValueError("`num_iterations` must be greater than zero.")
self._num_iterations = num_iterations
self._sampler = sampler
self._pass_manager = transpiler

def construct_circuit(
self,
Expand Down Expand Up @@ -125,9 +131,17 @@ def _estimate_phase_iteratively(self, unitary, state_preparation):
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True
)

if self._pass_manager is not None:
qc = self._pass_manager.run(qc)

try:
sampler_job = self._sampler.run([qc])
result = sampler_job.result().quasi_dists[0]
result = sampler_job.result()[0].data.c
result = {
label: value / result.num_shots
for label, value in result.get_int_counts().items()
}
except Exception as exc:
raise AlgorithmError("The primitive job failed!") from exc
x = 1 if result.get(1, 0) > result.get(0, 0) else 0
Expand Down
25 changes: 18 additions & 7 deletions qiskit_algorithms/phase_estimators/phase_estimation.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2020, 2023.
# (C) Copyright IBM 2020, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -20,13 +20,14 @@
from qiskit import circuit
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.primitives import BaseSampler
from qiskit.primitives import BaseSamplerV2
from qiskit.result import Result

from qiskit_algorithms.exceptions import AlgorithmError

from .phase_estimation_result import PhaseEstimationResult, _sort_phases
from .phase_estimator import PhaseEstimator
from ..custom_types import Transpiler


class PhaseEstimation(PhaseEstimator):
Expand Down Expand Up @@ -82,13 +83,17 @@ class PhaseEstimation(PhaseEstimator):
def __init__(
self,
num_evaluation_qubits: int,
sampler: BaseSampler | None = None,
sampler: BaseSamplerV2 | None = None,
transpiler: Transpiler | None = None,
) -> None:
r"""
Args:
num_evaluation_qubits: The number of qubits used in estimating the phase. The phase will
be estimated as a binary string with this many bits.
sampler: The sampler primitive on which the circuit will be sampled.
transpiler: An optional object with a `run` method allowing to transpile the circuits
that are produced within this algorithm. If set to `None`, these won't be
transpiled.

Raises:
AlgorithmError: If a sampler is not provided
Expand All @@ -101,6 +106,7 @@ def __init__(
self._num_evaluation_qubits = num_evaluation_qubits

self._sampler = sampler
self._pass_manager = transpiler

def construct_circuit(
self, unitary: QuantumCircuit, state_preparation: QuantumCircuit | None = None
Expand Down Expand Up @@ -189,18 +195,23 @@ def estimate_from_pe_circuit(self, pe_circuit: QuantumCircuit) -> PhaseEstimatio
AlgorithmError: Primitive job failed.
"""

if self._pass_manager is not None:
pe_circuit = self._pass_manager.run(pe_circuit)

self._add_measurement_if_required(pe_circuit)

try:
circuit_job = self._sampler.run([pe_circuit])
circuit_result = circuit_job.result()
except Exception as exc:
raise AlgorithmError("The primitive job failed!") from exc
phases = circuit_result.quasi_dists[0]
phases = circuit_result[0].data.meas.get_counts()
# Ensure we still return the measurement strings in sorted order, which SamplerV2 doesn't
# guarantee
measurement_labels = sorted(phases.keys())
phases_bitstrings = {}
for key, phase in phases.items():
bitstring_key = self._get_reversed_bitstring(self._num_evaluation_qubits, key)
phases_bitstrings[bitstring_key] = phase
for key in measurement_labels:
phases_bitstrings[key[::-1]] = phases[key] / circuit_result[0].data.meas.num_shots
phases = phases_bitstrings

return PhaseEstimationResult(
Expand Down
6 changes: 1 addition & 5 deletions qiskit_algorithms/phase_estimators/phase_estimator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2020, 2023.
# (C) Copyright IBM 2020, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand Down Expand Up @@ -38,10 +38,6 @@ def estimate(
"""Estimate the phase."""
raise NotImplementedError

@staticmethod
def _get_reversed_bitstring(length: int, number: int) -> str:
return f"{number:b}".zfill(length)[::-1]


class PhaseEstimatorResult(AlgorithmResult):
"""Phase Estimator Result."""
Expand Down
Loading
Loading