Skip to content
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

fix: do not allow to pass A&B custom options to backend.run() #56

Merged
merged 2 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
32 changes: 27 additions & 5 deletions qiskit_alice_bob_provider/local/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from qiskit_aer.backends.aerbackend import AerBackend

from ..processor.description import ProcessorDescription
from ..processor.utils import get_init_params
from .job import ProcessorSimulationJob
from .quantum_errors import build_quantum_error_passes
from .readout_errors import build_readout_noise_model
Expand Down Expand Up @@ -73,12 +74,13 @@ def __init__(

Args:
processor (ProcessorDescription): the description of the quantum
processor to simulate
processor to simulate
execution_backend (AerBackend, optional): the Qiskit simulator used
in the background for simulation. Defaults to AerSimulator().
in the background for simulation. Defaults to AerSimulator().
name (Optional[str], optional): an optional name for the backend.
"""
super().__init__(name=name, backend_version=1)
self._processor = processor
self._target = processor_to_target(processor)
self._execution_backend = execution_backend
self._execution_backend.set_option('n_qubits', self._target.num_qubits)
Expand Down Expand Up @@ -141,11 +143,31 @@ def run(

Args:
run_input (Union[QuantumCircuit, List[QuantumCircuit]]): one or
multiple circuits to simulate.
multiple circuits to simulate.
**options: additional arguments are interpreted as options for
the underlying execution backend, usually an instance of
AerSimulator.
the underlying execution backend, usually an instance of
AerSimulator.

Returns:
ProcessorSimulationJob: A wrapper of a submitted asynchronous
AerJob

Raises:
ValueError: if a custom A&B option is passed to backend.run()
"""
if options:
# Check that the options passed are not custom A&B options of the
# processor because they will be ignored in this function.
processor_params = get_init_params(self._processor.__class__)
for option in options:
if option not in processor_params:
continue
raise ValueError(
f'The Alice & Bob custom option {option} is not allowed '
'for backend.run() with local provider. '
'You should pass it to get_backend() instead.'
)

if isinstance(run_input, QuantumCircuit):
circuits = [run_input]
else:
Expand Down
8 changes: 8 additions & 0 deletions qiskit_alice_bob_provider/processor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
# limitations under the License.
##############################################################################

from inspect import signature
from itertools import product
from typing import Dict, List, Union

import numpy as np
from typing_extensions import Type


def pauli_errors_to_chi(pauli_errors: Dict[str, float]) -> np.ndarray:
Expand Down Expand Up @@ -220,3 +222,9 @@ def tensor_errors(
for (a_pauli, a_prob), (b_pauli, b_prob) in product(a.items(), b.items()):
output[b_pauli + a_pauli] = a_prob * b_prob
return output


def get_init_params(cls: Type) -> List[str]:
"""Get the names of the parameters of a class's __init__ method"""
init_signature = signature(cls.__init__)
return list(init_signature.parameters.keys())[1:] # Skip 'self'
22 changes: 22 additions & 0 deletions tests/local/test_backend.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from typing import List

import numpy as np
import pytest
from qiskit import QuantumCircuit, transpile
from qiskit.circuit.library import Initialize

from qiskit_alice_bob_provider.local.backend import ProcessorSimulator
from qiskit_alice_bob_provider.processor.logical_cat import LogicalCatProcessor
from qiskit_alice_bob_provider.processor.physical_cat import (
PhysicalCatProcessor,
)
Expand Down Expand Up @@ -43,6 +45,26 @@ def test_set_execution_backend_options() -> None:
assert sum(backend.run(transpiled).result().get_counts().values()) == 7


def test_run_override_nbar_error() -> None:
"""
Test that passing average_nb_photons option to backend.run() is not allowed
"""
circ = QuantumCircuit(1, 1)
backend = ProcessorSimulator(PhysicalCatProcessor())
transpiled = transpile(circ, backend)
with pytest.raises(ValueError):
_ = backend.run(transpiled, shots=100, average_nb_photons=4)
with pytest.raises(ValueError):
_ = backend.run(transpiled, shots=100, kappa_1=4)

backend = ProcessorSimulator(LogicalCatProcessor())
transpiled = transpile(circ, backend)
with pytest.raises(ValueError):
_ = backend.run(transpiled, shots=100, average_nb_photons=4)
with pytest.raises(ValueError):
_ = backend.run(transpiled, shots=100, kappa_1=4)


def test_translation_plugin() -> None:
backend = ProcessorSimulator(SimpleProcessor(1))

Expand Down
Loading