qciconnect-applib 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- qciconnect/applib/__init__.py +4 -0
- qciconnect/applib/algorithm/__init__.py +26 -0
- qciconnect/applib/algorithm/imaginary_time_evolution.py +54 -0
- qciconnect/applib/algorithm/imaginary_time_evolution_params.py +30 -0
- qciconnect/applib/algorithm/optimizer/__init__.py +1 -0
- qciconnect/applib/algorithm/optimizer/scipy_optimizer.py +66 -0
- qciconnect/applib/algorithm/quench.py +35 -0
- qciconnect/applib/algorithm/quench_params.py +25 -0
- qciconnect/applib/algorithm/time_evolution.py +52 -0
- qciconnect/applib/algorithm/time_evolution_params.py +44 -0
- qciconnect/applib/algorithm/vqe.py +113 -0
- qciconnect/applib/algorithm/vqe_params.py +38 -0
- qciconnect/applib/app/__init__.py +19 -0
- qciconnect/applib/app/schemas/alf.schema.json +417 -0
- qciconnect/applib/app/schemas/runner.schema.json +28 -0
- qciconnect/applib/app/time_evolution/Dockerfile +14 -0
- qciconnect/applib/app/time_evolution/README.md +59 -0
- qciconnect/applib/app/time_evolution/__init__.py +3 -0
- qciconnect/applib/app/time_evolution/app_config.json +46 -0
- qciconnect/applib/app/time_evolution/main.py +40 -0
- qciconnect/applib/app/time_evolution/parse_input.py +79 -0
- qciconnect/applib/app/time_evolution/preview_media/time_evolution_plot.svg +1174 -0
- qciconnect/applib/app/time_evolution/thumbnail.svg +311 -0
- qciconnect/applib/app/time_evolution/write_output.py +105 -0
- qciconnect/applib/circuit/__init__.py +3 -0
- qciconnect/applib/circuit/builder/__init__.py +11 -0
- qciconnect/applib/circuit/builder/efficient_su2_ansatz_builder.py +37 -0
- qciconnect/applib/circuit/builder/imaginary_trotter_builder.py +101 -0
- qciconnect/applib/circuit/builder/imaginary_trotter_step_builder.py +95 -0
- qciconnect/applib/circuit/builder/qsp_circuit.py +48 -0
- qciconnect/applib/circuit/builder/trotter_builder.py +142 -0
- qciconnect/applib/circuit/builder/trotter_step_builder.py +35 -0
- qciconnect/applib/circuit/efficient_su2.py +19 -0
- qciconnect/applib/mitigation/__init__.py +12 -0
- qciconnect/applib/mitigation/noise_amplifier.py +43 -0
- qciconnect/applib/mitigation/postselection_sampler.py +29 -0
- qciconnect/applib/mitigation/twirled_readout_sampler.py +49 -0
- qciconnect/applib/mitigation/unitary_folding.py +73 -0
- qciconnect/applib/mitigation/zne_estimator.py +79 -0
- qciconnect/applib/problem/__init__.py +6 -0
- qciconnect/applib/problem/problem_input/__init__.py +4 -0
- qciconnect/applib/problem/problem_input/fermi_hubbard_hamiltonians.py +10 -0
- qciconnect/applib/problem/problem_input/tfi_hamiltonians.py +46 -0
- qciconnect/applib/problem/time_evolution_problem.py +12 -0
- qciconnect_applib-0.2.0.dist-info/METADATA +58 -0
- qciconnect_applib-0.2.0.dist-info/RECORD +47 -0
- qciconnect_applib-0.2.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""AppLib provides implementations of algorithms, containing the quantum algorithmic business logic.
|
|
2
|
+
|
|
3
|
+
The algorithms within AppLib serve as examples
|
|
4
|
+
for QCI Connect app developers for implementing their own quantum applications.
|
|
5
|
+
To also enable web demonstrations, see :ref:`section-app`.
|
|
6
|
+
|
|
7
|
+
Algorithms map a :class:`ProblemInput` to a :class:`Result` and use a :class:`Runner` instance
|
|
8
|
+
for handling quantum jobs.
|
|
9
|
+
They are used the following way:
|
|
10
|
+
|
|
11
|
+
.. code-block:: python
|
|
12
|
+
|
|
13
|
+
algorithm = MyAlgorithm(algorithm_parameters, runner)
|
|
14
|
+
result = algorithm(problem_input)
|
|
15
|
+
|
|
16
|
+
For tutorials and details on how to implement algorithms, refer to the ALF documentation.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from .imaginary_time_evolution import ImaginaryTimeEvolution
|
|
20
|
+
from .imaginary_time_evolution_params import ImaginaryTimeEvolutionParams
|
|
21
|
+
from .quench import Quench
|
|
22
|
+
from .quench_params import QuenchParams
|
|
23
|
+
from .time_evolution import TimeEvolution
|
|
24
|
+
from .time_evolution_params import TimeEvolutionParams
|
|
25
|
+
from .vqe import VQE
|
|
26
|
+
from .vqe_params import VqeParams
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from copy import deepcopy
|
|
2
|
+
|
|
3
|
+
from qciconnect.alf.algorithm import Algorithm
|
|
4
|
+
from qciconnect.alf.base import MeasurementBasis
|
|
5
|
+
from qciconnect.alf.execution import Runner
|
|
6
|
+
from qciconnect.alf.problem.problem_input import Hamiltonian
|
|
7
|
+
from qciconnect.alf.problem.result import TimeEvolvedExpectationValueResult
|
|
8
|
+
|
|
9
|
+
from qciconnect.applib.mitigation import PostselectionSampler
|
|
10
|
+
|
|
11
|
+
from .imaginary_time_evolution_params import ImaginaryTimeEvolutionParams
|
|
12
|
+
from .time_evolution import TimeEvolution
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ImaginaryTimeEvolution(Algorithm[ImaginaryTimeEvolutionParams]):
|
|
16
|
+
r"""Performs (probabilistic) imaginary time evolution of Observable expectation values.
|
|
17
|
+
|
|
18
|
+
The algorithm attempts to bring the state of the quantum register closer
|
|
19
|
+
to the ground state of the ``Hamiltonian`` that is handed in the ``__call__``.
|
|
20
|
+
The circuit uses an additional flag qubit.
|
|
21
|
+
For each time step,
|
|
22
|
+
the energy reduction succeeded if after applying the circuit and measuring the flag qubit,
|
|
23
|
+
the value of the flag qubit is 0.
|
|
24
|
+
|
|
25
|
+
The convergence speed is increased by choosing a big ``timestep``,
|
|
26
|
+
but this decreases the success probability.
|
|
27
|
+
|
|
28
|
+
For each observable :math:`O` and every entry ``n_step`` in ``sample_points``,
|
|
29
|
+
the expectation value :math:`\langle O\rangle`
|
|
30
|
+
is computed at every time ``[time_grid[idx] for idx in sample_points]``.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, params: ImaginaryTimeEvolutionParams, runner: Runner):
|
|
34
|
+
"""Initialize ``ImaginaryTimeEvolution`` algorithm."""
|
|
35
|
+
adapted_runner = deepcopy(runner)
|
|
36
|
+
filter_flag_qubit_0 = PostselectionSampler({0: 0})
|
|
37
|
+
adapted_runner.add_sampler_layer(filter_flag_qubit_0)
|
|
38
|
+
super().__init__(params, adapted_runner)
|
|
39
|
+
|
|
40
|
+
if self.params.bases is not None:
|
|
41
|
+
meas_bases_with_ancilla = [MeasurementBasis('Z'+str(basis))
|
|
42
|
+
for basis in self.params.bases]
|
|
43
|
+
self.params.bases = meas_bases_with_ancilla
|
|
44
|
+
observables_with_ancilla = [observable >> 1 for observable in self.params.observables]
|
|
45
|
+
self.params.observables = observables_with_ancilla
|
|
46
|
+
|
|
47
|
+
def run_core(self, problem_input: Hamiltonian) -> TimeEvolvedExpectationValueResult:
|
|
48
|
+
"""Run the core logic of the imaginary time evolution.
|
|
49
|
+
|
|
50
|
+
:param problem_input: Hamiltonian of the time-evolved system.
|
|
51
|
+
:return: ``TimeEvolvedExpectationValueResult``.
|
|
52
|
+
"""
|
|
53
|
+
time_evolution_algo = TimeEvolution(self.params, self.runner)
|
|
54
|
+
return time_evolution_algo.run_core(problem_input)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Parameter classes for the variational Quantum Eigensolver Algorithm."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
from qciconnect.alf.circuit.builder import TimeEvolutionBuilder
|
|
6
|
+
|
|
7
|
+
from qciconnect.applib.circuit.builder import ImaginaryTrotterBuilder
|
|
8
|
+
|
|
9
|
+
from .time_evolution_params import TimeEvolutionParams
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class ImaginaryTimeEvolutionParams(TimeEvolutionParams):
|
|
14
|
+
r"""Parameters to configure the ``TimeEvolution`` algorithm.
|
|
15
|
+
|
|
16
|
+
:param observables: List of ``Observable``\\ s whose time evolution is computed.
|
|
17
|
+
:param time_evolution_circuit_builder: ``TimeEvolutionBuilder`` to define the time evolution
|
|
18
|
+
Defaults to :class:`ImaginaryTrotterBuilder`.
|
|
19
|
+
:param single_step_builder: ``TimeStepBuilder`` to apply for time evolution
|
|
20
|
+
:param bases: list of ``MeasurementBasis`` to use.
|
|
21
|
+
:param time_grid: list of times at which to evaluate ``system`` Hamiltonian to perform
|
|
22
|
+
the Imaginary Time Evolution.
|
|
23
|
+
:param sample_points: optional list of indices in ``time_grid`` at which to sample.
|
|
24
|
+
:param state_preparation: ``Circuit`` to apply before time evolution.
|
|
25
|
+
:param n_shots: number of shots for each sample.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
# overwrite only default value of time_evolution_builder; recycle rest from TimeEvolutionParams
|
|
29
|
+
time_evolution_builder: TimeEvolutionBuilder = field(
|
|
30
|
+
default_factory = lambda: ImaginaryTrotterBuilder())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .scipy_optimizer import ScipyOptimizer, ScipyOptimizerParams
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Scipy Optimizer interface."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from qciconnect.alf.algorithm.optimizer import Optimizer
|
|
9
|
+
from qciconnect.alf.base import ClassParams
|
|
10
|
+
from qciconnect.alf.problem.result import OptimizationResult
|
|
11
|
+
from scipy.optimize import minimize
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class ScipyOptimizerParams(ClassParams):
|
|
16
|
+
"""Parameters to configure ``ScipyOptimizer``.
|
|
17
|
+
|
|
18
|
+
:param method: name of optimizer that is used.
|
|
19
|
+
:param options: keyword arguments to pass to `scipy.optimize.minimize` and the method."
|
|
20
|
+
Default value sets parameter step size ``eps`` to 1e-2 because the scipy default
|
|
21
|
+
value is too small and typically overshadowed by shot noise.
|
|
22
|
+
"""
|
|
23
|
+
method: str = "bfgs"
|
|
24
|
+
options: dict[str, Any] = field(default_factory = lambda: {"eps": 1e-2})
|
|
25
|
+
|
|
26
|
+
class ScipyOptimizer(Optimizer[ScipyOptimizerParams]):
|
|
27
|
+
"""Scipy Optimizer interface."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, params: ScipyOptimizerParams | None = None):
|
|
30
|
+
"""Initialize object. If ``params`` is ``None``, use default values of parameters."""
|
|
31
|
+
if params is None:
|
|
32
|
+
params = ScipyOptimizerParams()
|
|
33
|
+
super().__init__(params)
|
|
34
|
+
|
|
35
|
+
def __call__(self, cost_function, init_params) -> OptimizationResult:
|
|
36
|
+
"""Optimize ``cost_function`` starting at ``init_params``.
|
|
37
|
+
|
|
38
|
+
:param cost_function: cost function which is to be minimized.
|
|
39
|
+
:param init_params: initial parameter values for the variational circuit.
|
|
40
|
+
|
|
41
|
+
:return: ``OptimizationResult`` containing the found cost and circuit parameters.
|
|
42
|
+
"""
|
|
43
|
+
minimize_options, solver_options = self._select_options(self.params.options)
|
|
44
|
+
|
|
45
|
+
x0 = np.array(init_params)
|
|
46
|
+
res = minimize(cost_function, x0, method = self.params.method,
|
|
47
|
+
options = solver_options, **minimize_options)
|
|
48
|
+
optimal_params = res.x.tolist()
|
|
49
|
+
optimal_cost = res.fun
|
|
50
|
+
return OptimizationResult(cost=optimal_cost, params=optimal_params)
|
|
51
|
+
|
|
52
|
+
def _select_options(self, options: dict) -> tuple[dict, dict]:
|
|
53
|
+
"""Split options into kwargs for `minimize` and remaining options to pass to the method.
|
|
54
|
+
|
|
55
|
+
This checks against the signature of `scipy.optimize.minimize` and puts any option
|
|
56
|
+
that does not fit into this signature into `solver_options`.
|
|
57
|
+
Note that `scipy` prints a warning if an invalid option is passed to the solver,
|
|
58
|
+
but henceforth simply ignores that option.
|
|
59
|
+
|
|
60
|
+
:param options: `dict` containing the options passed to `ScipyOptimizer`.
|
|
61
|
+
:return: tuple containing options for `minimize` as first and remaining options as second.
|
|
62
|
+
"""
|
|
63
|
+
minimize_args = inspect.signature(minimize).parameters.keys()
|
|
64
|
+
minimize_options = {k: v for k, v in options.items() if k in minimize_args}
|
|
65
|
+
solver_options = {k: v for k, v in options.items() if k not in minimize_args}
|
|
66
|
+
return minimize_options, solver_options
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from qciconnect.alf.algorithm import Algorithm
|
|
2
|
+
from qciconnect.alf.problem.problem_input import Hamiltonian
|
|
3
|
+
from qciconnect.alf.problem.result import TimeEvolvedExpectationValueResult
|
|
4
|
+
|
|
5
|
+
from .quench_params import QuenchParams
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Quench(Algorithm[QuenchParams]):
|
|
9
|
+
"""Time evolve ``Observable`` ``ExpectationValue``'s for a quenched eigenstate.
|
|
10
|
+
|
|
11
|
+
First prepares an eigenstate of the system ``Hamiltonian``.
|
|
12
|
+
Then performs the time evolution for a different (quenched) ``Hamiltonian``.
|
|
13
|
+
|
|
14
|
+
For each step, an algorithm can be provided, such as
|
|
15
|
+
the ``VQE`` to prepare the ground state in the first step and
|
|
16
|
+
a Trotter time evolution for the second step.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def run_core(self, problem_input: Hamiltonian) -> TimeEvolvedExpectationValueResult:
|
|
20
|
+
"""Run the core logic of the ``Quench`` algorithm.
|
|
21
|
+
|
|
22
|
+
First, ``state_finder_algorithm`` is applied with respect to the ``unquenched_system``.
|
|
23
|
+
Then, ``time_evolver_algorithm`` evolves the resulting state
|
|
24
|
+
with respect to ``problem_input``.
|
|
25
|
+
|
|
26
|
+
:param problem_input: quenched ``Hamiltonian`` used for time evolution.
|
|
27
|
+
:return: ``TimeEvolvedExpectationValueResult`` object.
|
|
28
|
+
"""
|
|
29
|
+
optim_results = self.params.state_finder_algorithm(self.params.unquenched_system)
|
|
30
|
+
init_state_preparation = optim_results.circuit
|
|
31
|
+
|
|
32
|
+
self.params.time_evolver_algorithm.params.state_preparation = init_state_preparation
|
|
33
|
+
time_evolution_result = self.params.time_evolver_algorithm(problem_input)
|
|
34
|
+
|
|
35
|
+
return time_evolution_result
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Parameter classes for the variational Quantum Eigensolver Algorithm."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
from qciconnect.alf.algorithm import Algorithm
|
|
6
|
+
from qciconnect.alf.base import ClassParams
|
|
7
|
+
from qciconnect.alf.problem.problem_input import Hamiltonian
|
|
8
|
+
|
|
9
|
+
from .time_evolution import TimeEvolution
|
|
10
|
+
from .vqe import VQE
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class QuenchParams(ClassParams):
|
|
15
|
+
r"""Parameters to configure the ``Quench`` algorithm.
|
|
16
|
+
|
|
17
|
+
:param unquenched_system: unquenched ``Hamiltonian`` used to find initial state.
|
|
18
|
+
:param state_finder_algorithm: ``Algorithm`` to find specific system state.
|
|
19
|
+
:param state_finder_args: arguments to initialize ``state_finder_algorithm``.
|
|
20
|
+
:param time_evolver_algorithm: ``Algorithm`` to time evolve the state.
|
|
21
|
+
:param time_evolver_args: arguments to initialize ``time_evolver``.
|
|
22
|
+
"""
|
|
23
|
+
unquenched_system: Hamiltonian
|
|
24
|
+
state_finder_algorithm: Algorithm = field(default_factory = lambda: VQE())
|
|
25
|
+
time_evolver_algorithm: Algorithm = field(default_factory = lambda: TimeEvolution())
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Standard time evolution algorithm."""
|
|
2
|
+
from qciconnect.alf.algorithm import Algorithm, AlgorithmStatistics
|
|
3
|
+
from qciconnect.alf.execution import EstimationJob
|
|
4
|
+
from qciconnect.alf.problem.problem_input import Hamiltonian, TimeDependentHamiltonian
|
|
5
|
+
from qciconnect.alf.problem.result import TimeEvolvedExpectationValueResult
|
|
6
|
+
|
|
7
|
+
from .time_evolution_params import TimeEvolutionParams
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TimeEvolution(Algorithm[TimeEvolutionParams]):
|
|
11
|
+
r"""Performs time evolution of Observables for a Hamiltonian using a chosen TimeStepBuilder.
|
|
12
|
+
|
|
13
|
+
The time evolution evaluates the Hamiltonian stored in ``system``
|
|
14
|
+
at the time points defined in ``time_grid``.
|
|
15
|
+
The expectation values :math:`\langle O_i\rangle` of the ``observables`` :math:`O_i`
|
|
16
|
+
can be measured at any of those times.
|
|
17
|
+
|
|
18
|
+
If ``sample_points`` is ``None`` a measurement is performed for every time in ``time_grid``.
|
|
19
|
+
Otherwise, the entries of ``sample_points`` are used as the indices of ``time_grid``
|
|
20
|
+
for which measurements are performed.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def run_core(self, problem_input: Hamiltonian | TimeDependentHamiltonian) \
|
|
24
|
+
-> TimeEvolvedExpectationValueResult:
|
|
25
|
+
"""Run the core logic of the time evolution.
|
|
26
|
+
|
|
27
|
+
:param problem_input: Hamiltonian of the time-evolved system.
|
|
28
|
+
:return: ``TimeEvolvedExpectationValueResult`` containing the measured expectation values.
|
|
29
|
+
"""
|
|
30
|
+
circuits = self.params.time_evolution_builder(problem_input,
|
|
31
|
+
self.params.time_grid,
|
|
32
|
+
self.params.sample_points,
|
|
33
|
+
self.params.state_preparation,
|
|
34
|
+
self.params.single_step_builder)
|
|
35
|
+
|
|
36
|
+
job_ids = [f"time_evolution_step_{t_step}" for t_step in self.params.sample_points]
|
|
37
|
+
|
|
38
|
+
jobs = [
|
|
39
|
+
EstimationJob(job_id, circuit, self.params.observables,
|
|
40
|
+
self.params.n_shots, self.params.bases) \
|
|
41
|
+
for job_id, circuit in zip(job_ids, circuits, strict=True)
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
estimations = self.runner.estimate(jobs)
|
|
45
|
+
return TimeEvolvedExpectationValueResult(
|
|
46
|
+
algorithm_statistics = AlgorithmStatistics(),
|
|
47
|
+
times = [self.params.time_grid[step] for step in self.params.sample_points],
|
|
48
|
+
observable_data = [
|
|
49
|
+
[obs_val.value for obs_val in exp_val] for exp_val in estimations.values()
|
|
50
|
+
]
|
|
51
|
+
)
|
|
52
|
+
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Parameter classes for the variational Quantum Eigensolver Algorithm."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from qciconnect.alf.base import ClassParams, MeasurementBasis
|
|
7
|
+
from qciconnect.alf.circuit import Circuit
|
|
8
|
+
from qciconnect.alf.circuit.builder import TimeEvolutionBuilder, TimeStepBuilder
|
|
9
|
+
from qciconnect.alf.execution import Observable
|
|
10
|
+
|
|
11
|
+
from qciconnect.applib.circuit.builder import TrotterBuilder, TrotterStepBuilder
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class TimeEvolutionParams(ClassParams):
|
|
16
|
+
r"""Parameters to configure the ``TimeEvolution`` algorithm.
|
|
17
|
+
|
|
18
|
+
:param observables: list of ``Observable``\\ s whose time evolution is computed.
|
|
19
|
+
:param time_evolution_circuit_builder: ``TimeEvolutionBuilder`` to define the time evolution
|
|
20
|
+
:param single_step_builder: ``TimeStepBuilder`` to apply for time evolution.
|
|
21
|
+
Default is ``TrotterStepBuilder``.
|
|
22
|
+
:param time_evolution_circuit_builder: ``TimeEvolutionBuilder`` to define the time evolution
|
|
23
|
+
:param bases: list of ``MeasurementBasis`` to use.
|
|
24
|
+
:param time_grid: list of times at which to evaluate ``system`` Hamiltonian to perform
|
|
25
|
+
the time evolution.
|
|
26
|
+
:param sample_points: optional list of indices in ``time_grid`` at which to sample.
|
|
27
|
+
:param state_preparation: ``Circuit`` to apply before time evolution.
|
|
28
|
+
:param n_shots: number of shots for each sample.
|
|
29
|
+
"""
|
|
30
|
+
time_grid: list[float]
|
|
31
|
+
observables: list[Observable]
|
|
32
|
+
bases: list[MeasurementBasis] | None = None
|
|
33
|
+
sample_points: list[int] | Literal["all"] = "all"
|
|
34
|
+
state_preparation: Circuit | None = None
|
|
35
|
+
n_shots: list[int] | int = 1000
|
|
36
|
+
single_step_builder: TimeStepBuilder = field(
|
|
37
|
+
default_factory = lambda: TrotterStepBuilder())
|
|
38
|
+
time_evolution_builder: TimeEvolutionBuilder = field(
|
|
39
|
+
default_factory = lambda: TrotterBuilder())
|
|
40
|
+
|
|
41
|
+
def __post_init__(self):
|
|
42
|
+
"""Choose correct ``sample_points`` if ``sample_points==all``."""
|
|
43
|
+
if self.sample_points == "all":
|
|
44
|
+
self.sample_points = list(range(len(self.time_grid)))
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Variational Quantum Eigensolver Algorithm."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from math import pi
|
|
5
|
+
from random import random
|
|
6
|
+
|
|
7
|
+
from qciconnect.alf.algorithm import Algorithm, AlgorithmStatistics
|
|
8
|
+
from qciconnect.alf.base import MeasurementBasis
|
|
9
|
+
from qciconnect.alf.circuit import Circuit, VariationalCircuit
|
|
10
|
+
from qciconnect.alf.execution import EstimationJob, Observable
|
|
11
|
+
from qciconnect.alf.problem.problem_input import Hamiltonian
|
|
12
|
+
from qciconnect.alf.problem.result import CircuitOptimizationResult
|
|
13
|
+
|
|
14
|
+
from .vqe_params import VqeParams
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class VqeAlgoStats(AlgorithmStatistics):
|
|
19
|
+
"""Statistics that are captured whenever the ``VQE`` algorithm runs."""
|
|
20
|
+
cost_history: list[float] = field(default_factory = list)
|
|
21
|
+
params_history: list[list] = field(default_factory = list)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class VQE(Algorithm[VqeParams]):
|
|
25
|
+
"""Variational Quantum Eigensolver to find ground state (energy).
|
|
26
|
+
|
|
27
|
+
The Variational Quantum Eigensolver is an algorithm composed of a quantum circuit
|
|
28
|
+
that prepares a parametrized state and a classical optimizer that iteratively
|
|
29
|
+
adjusts the circuit parameters. It evaluates the expectation value of an Hamiltonian
|
|
30
|
+
to minimize the energy of the quantum system.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def run_core(self, hamiltonian: Hamiltonian) -> CircuitOptimizationResult:
|
|
34
|
+
"""Run the core logic of the VQE.
|
|
35
|
+
|
|
36
|
+
Attempt to minimize the expectation value of the ``Hamiltonian``.
|
|
37
|
+
|
|
38
|
+
:param hamiltonian: ``Hamiltonian`` whose expectation value should be minimized.
|
|
39
|
+
:return: ``CircuitOptimizationResult``, where the returned optimized circuit is given \
|
|
40
|
+
by just the variational circuit without state_preparation.
|
|
41
|
+
"""
|
|
42
|
+
circuit_ansatz = self._init_circuit_ansatz(hamiltonian)
|
|
43
|
+
state_preparation = self._init_state_preparation(circuit_ansatz)
|
|
44
|
+
|
|
45
|
+
vqe_stats = VqeAlgoStats()
|
|
46
|
+
|
|
47
|
+
def cost(params):
|
|
48
|
+
circuit = state_preparation + circuit_ansatz.dispatch(params)
|
|
49
|
+
cost = self._energy_cost(hamiltonian, circuit, self.params.bases, self.params.nshots)
|
|
50
|
+
vqe_stats.params_history.append(params.tolist())
|
|
51
|
+
vqe_stats.cost_history.append(cost)
|
|
52
|
+
return cost
|
|
53
|
+
|
|
54
|
+
optimization_result = self.params.optimizer(cost, self._initial_parameters(circuit_ansatz))
|
|
55
|
+
best_cost = optimization_result.cost
|
|
56
|
+
best_params = optimization_result.params
|
|
57
|
+
best_circuit = circuit_ansatz.dispatch(best_params)
|
|
58
|
+
|
|
59
|
+
return CircuitOptimizationResult[VqeAlgoStats](cost = best_cost,
|
|
60
|
+
params = best_params,
|
|
61
|
+
circuit = best_circuit,
|
|
62
|
+
algorithm_statistics = vqe_stats)
|
|
63
|
+
|
|
64
|
+
def _initial_parameters(self, circuit_ansatz: VariationalCircuit):
|
|
65
|
+
"""Prepare initial parameters with which to dispatch the ``VariationalCircuit``.
|
|
66
|
+
|
|
67
|
+
:param circuit_ansatz: Variational circuit ansatz depending on a set of parameters.
|
|
68
|
+
"""
|
|
69
|
+
init_params = self.params.init_params
|
|
70
|
+
if type(init_params) is str and init_params == "zero":
|
|
71
|
+
return [0.] * circuit_ansatz.num_parameters
|
|
72
|
+
if type(init_params) is str and init_params == "random":
|
|
73
|
+
return [random() * 0.1*pi for _ in range(circuit_ansatz.num_parameters)]
|
|
74
|
+
return init_params
|
|
75
|
+
|
|
76
|
+
def _init_circuit_ansatz(self, hamiltonian: Hamiltonian) -> VariationalCircuit:
|
|
77
|
+
"""Return circuit ansatz for given ``hamiltonian``."""
|
|
78
|
+
param_circuit_ansatz = self.params.circuit_ansatz
|
|
79
|
+
if isinstance(param_circuit_ansatz, VariationalCircuit):
|
|
80
|
+
circuit_ansatz = param_circuit_ansatz
|
|
81
|
+
else:
|
|
82
|
+
circuit_ansatz = param_circuit_ansatz(hamiltonian)
|
|
83
|
+
return circuit_ansatz
|
|
84
|
+
|
|
85
|
+
def _init_state_preparation(self, circuit_ansatz: VariationalCircuit) -> Circuit:
|
|
86
|
+
"""Return state preparation circuit for given ``circuit_ansatz``."""
|
|
87
|
+
if isinstance(self.params.state_preparation, Circuit):
|
|
88
|
+
preparation_circuit = self.params.state_preparation
|
|
89
|
+
else:
|
|
90
|
+
n_qubits = circuit_ansatz.width
|
|
91
|
+
preparation_circuit = Circuit("I", n_qubits)
|
|
92
|
+
return preparation_circuit
|
|
93
|
+
|
|
94
|
+
def _energy_cost(self, hamiltonian:Hamiltonian, circuit: Circuit,
|
|
95
|
+
bases: list[MeasurementBasis] | None = None,
|
|
96
|
+
nshots: list[int] | int = 1000) -> float:
|
|
97
|
+
"""Internal method to compute energy expectation value.
|
|
98
|
+
|
|
99
|
+
:param hamiltonian: ``Hamiltonian`` whose expectation value should be minimized.
|
|
100
|
+
:param circuit: parametrized ``VariationalCircuit`` to use for estimation.
|
|
101
|
+
:param bases: list of ``MeasurementBasis`` to use.
|
|
102
|
+
:param nshots: number of shots for each sample.
|
|
103
|
+
|
|
104
|
+
:return: ``CircuitOptimizationResult`` object.
|
|
105
|
+
"""
|
|
106
|
+
# TODO: smarter way of allowing Hamiltonians to be used as observables
|
|
107
|
+
pauli_superposition = hamiltonian.paulis
|
|
108
|
+
hamiltonian_observable = Observable(pauli_superposition.coefficients,
|
|
109
|
+
pauli_superposition.pauli_strings)
|
|
110
|
+
|
|
111
|
+
job = EstimationJob("vqe_cost", circuit, [hamiltonian_observable], nshots, bases)
|
|
112
|
+
expec = self.runner.estimate([job])
|
|
113
|
+
return expec["vqe_cost"][0].value.real
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Parameter classes for the variational Quantum Eigensolver Algorithm."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from qciconnect.alf.algorithm.optimizer import Optimizer
|
|
7
|
+
from qciconnect.alf.base import ClassParams, MeasurementBasis
|
|
8
|
+
from qciconnect.alf.circuit import Circuit, VariationalCircuit
|
|
9
|
+
from qciconnect.alf.circuit.builder import AnsatzBuilder
|
|
10
|
+
|
|
11
|
+
from qciconnect.applib.algorithm.optimizer import ScipyOptimizer
|
|
12
|
+
from qciconnect.applib.circuit.builder import (
|
|
13
|
+
EfficientSu2AnsatzBuilder,
|
|
14
|
+
EfficientSu2AnsatzBuilderParams,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class VqeParams(ClassParams):
|
|
20
|
+
"""Parameters to configure the ``VQE`` algorithm.
|
|
21
|
+
|
|
22
|
+
:param bases: list of ``MeasurementBasis`` to use. Default is ``None``.
|
|
23
|
+
:param circuit_ansatz: ``VariationalCircuit`` to use for optimizing state.
|
|
24
|
+
Default is ``EfficientSu2AnsatzBuilder``.
|
|
25
|
+
:param init_params: initial parameter values to use in the ansatz.
|
|
26
|
+
Default is ``zero``.
|
|
27
|
+
:param optimizer: classical ``Optimizer`` to find best ``circuit_ansatz`` parameters.
|
|
28
|
+
Default is ``ScipyOptimizer``.
|
|
29
|
+
:param state_preparation: ``Circuit`` to apply before time evolution. Default is ``None``.
|
|
30
|
+
:param nshots: number of shots for each sample. Default is 1000.
|
|
31
|
+
"""
|
|
32
|
+
bases: list[MeasurementBasis] | None = None
|
|
33
|
+
circuit_ansatz: VariationalCircuit | AnsatzBuilder = field(
|
|
34
|
+
default_factory = lambda: EfficientSu2AnsatzBuilder(EfficientSu2AnsatzBuilderParams()))
|
|
35
|
+
init_params: list[float] | Literal["zero", "random"] = "zero"
|
|
36
|
+
optimizer: Optimizer = field(default_factory = lambda: ScipyOptimizer())
|
|
37
|
+
state_preparation: Circuit | None = None
|
|
38
|
+
nshots: int = 1000
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""AppLib provides implementations of applications and their underlying algorithms.
|
|
2
|
+
|
|
3
|
+
The applications within AppLib serve as examples
|
|
4
|
+
for QCI Connect app developers for implementing their own quantum applications.
|
|
5
|
+
|
|
6
|
+
The actual quantum algorithmic business logic of applications
|
|
7
|
+
is usually implemented in an :class:`Algorithm` subclass, see :ref:`section-algorithm`.
|
|
8
|
+
If you are developing software that uses QCI Connect,
|
|
9
|
+
implementing an :class:`Algorithm` subclass is already enough to allow your users to
|
|
10
|
+
run your own quantum algorithms on QCI Connect after installing your package.
|
|
11
|
+
|
|
12
|
+
On top of this, the application is necessary to enable web demonstrations on the QCI Connect webpage
|
|
13
|
+
and defines the workflow when an user starts the app on the webpage.
|
|
14
|
+
This includes metadata for how it is visualized,
|
|
15
|
+
which documentation information is shown,
|
|
16
|
+
and which parameters can be selected by the user.
|
|
17
|
+
This can also entail further logic,
|
|
18
|
+
such as choosing a suitable algorithm for the problem definition.
|
|
19
|
+
"""
|