Skip to content

Commit

Permalink
deprecate backend.run(validate=True) and clean codes in AerBackend
Browse files Browse the repository at this point in the history
  • Loading branch information
hhorii committed Mar 1, 2023
1 parent a68df4c commit 2b1c077
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 27 deletions.
18 changes: 7 additions & 11 deletions qiskit_aer/backends/aer_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,8 +393,8 @@ def assemble_circuit(circuit: QuantumCircuit):
global_phase=global_phase,
)

if hasattr(circuit, "metadata") and circuit.metadata:
header.metadata = copy(circuit.metadata)
if circuit.metadata is not None:
header.metadata = circuit.metadata

qubit_indices = {qubit: idx for idx, qubit in enumerate(circuit.qubits)}
clbit_indices = {clbit: idx for idx, clbit in enumerate(circuit.clbits)}
Expand Down Expand Up @@ -455,8 +455,6 @@ def _assemble_op(aer_circ, inst, qubit_indices, clbit_indices, is_conditional, c
'sx', 'sxdg', 't', 'tdg', 'u', 'x', 'y', 'z', 'u1', 'u2', 'u3',
'cu', 'cu1', 'cu2', 'cu3'}:
aer_circ.gate(name, qubits, params, [], conditional_reg, label if label else name)
elif name == 'pauli':
aer_circ.gate(name, qubits, [], params, conditional_reg, label if label else name)
elif name == 'measure':
if is_conditional:
aer_circ.measure(qubits, clbits, clbits)
Expand All @@ -468,6 +466,8 @@ def _assemble_op(aer_circ, inst, qubit_indices, clbit_indices, is_conditional, c
aer_circ.diagonal(qubits, params, label if label else 'diagonal')
elif name == 'unitary':
aer_circ.unitary(qubits, params[0], conditional_reg, label if label else 'unitary')
elif name == 'pauli':
aer_circ.gate(name, qubits, [], params, conditional_reg, label if label else name)
elif name == 'initialize':
aer_circ.initialize(qubits, params)
elif name == 'roerror':
Expand All @@ -476,12 +476,12 @@ def _assemble_op(aer_circ, inst, qubit_indices, clbit_indices, is_conditional, c
aer_circ.multiplexer(qubits, params, conditional_reg, label if label else name)
elif name == 'kraus':
aer_circ.kraus(qubits, params, conditional_reg)
elif name in ('save_statevector', 'save_statevector_dict', 'save_clifford',
elif name in {'save_statevector', 'save_statevector_dict', 'save_clifford',
'save_probabilities', 'save_probabilities_dict', 'save_matrix_product_state',
'save_unitary', 'save_superop', 'save_density_matrix', 'save_state',
'save_stabilizer'):
'save_stabilizer'}:
aer_circ.save_state(qubits, name, operation._subtype, label if label else name)
elif name in ('save_amplitudes', 'save_amplitudes_sq'):
elif name in {'save_amplitudes', 'save_amplitudes_sq'}:
aer_circ.save_amplitudes(qubits, name, params, operation._subtype,
label if label else name)
elif name in ('save_expval', 'save_expval_var'):
Expand Down Expand Up @@ -549,8 +549,4 @@ def assemble_circuits(
# Generate AerCircuit from the input circuit
aer_qc_list = assemble_circuits(circuits=[qc])
"""
# generate aer circuits
# TODO parallel_map will improve performance for multi circuit assembly.
# However, it calls pickling AerCircuit in Linux environment. Until AerCircuit
# supports pickle, circuits are assembleed sequentially in a single thread
return [assemble_circuit(circuit) for circuit in circuits]
8 changes: 7 additions & 1 deletion qiskit_aer/backends/aerbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ def run(self,
for key, value in circuits.config.__dict__.items():
if key not in run_options and value is not None:
run_options[key] = value
if 'parameter_binds' in run_options:
parameter_binds = run_options.pop('parameter_binds')
return self._run_qobj(circuits, validate, parameter_binds, **run_options)

only_circuits = True
Expand All @@ -200,10 +202,14 @@ def run(self,
only_pulse &= isinstance(circ, (ScheduleBlock, Schedule))

if only_circuits and not only_pulse:
if validate:
raise TypeError("bad input to run() function;"
"`validation` argument is only effective for input qobj")

executor = run_options.get('executor', None)
if executor is None and 'executor' in self.options.__dict__:
executor = self.options.__dict__.get('executor', None)
if executor or validate:
if executor:
# This path remains for DASK execution to split a qobj insttance
# into sub-qobj instances. This will be replaced with _run_circuits path
# in the near releases
Expand Down
4 changes: 0 additions & 4 deletions qiskit_aer/backends/wrappers/aer_controller_binding.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,6 @@ void bind_aer_controller(MODULE m) {
aer_config.def_readwrite("method", &Config::method);
aer_config.def_readwrite("device", &Config::device);
aer_config.def_readwrite("precision", &Config::precision);
// executor=None,
// max_job_size=None,
// max_shot_size=None,
aer_config.def_readwrite("enable_truncation", &Config::enable_truncation);
aer_config.def_readwrite("zero_threshold", &Config::zero_threshold);
aer_config.def_readwrite("validation_threshold", &Config::validation_threshold);
Expand Down Expand Up @@ -134,7 +131,6 @@ void bind_aer_controller(MODULE m) {
aer_config.def_property("memory",
[](const Config &config) { return config.memory.val;},
[](Config &config, bool val) { config.memory.value(val);});
// noise_model=None,
aer_config.def_property("seed_simulator",
[](const Config &config) { return config.seed_simulator.val;},
[](Config &config, int_t val) { config.seed_simulator.value(val);});
Expand Down
2 changes: 0 additions & 2 deletions src/transpile/fusion.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -379,8 +379,6 @@ void NQubitFusion<N>::set_config(const Config &config) {
#elif N == 5
if (config._fusion_enable_n_qubits_5.has_value()) active = config._fusion_enable_n_qubits_5.value();
#endif
// if (JSON::check_key(activate_prop_name, config))
// JSON::get_value(active, activate_prop_name, config);
}

template<size_t N>
Expand Down
5 changes: 2 additions & 3 deletions test/terra/backends/aer_simulator/test_auto_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,14 +222,13 @@ def test_auto_method_partial_result_a_single_invalid_circuit(self):
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc_2 = QuantumVolume(5)
qc_2 = QuantumCircuit(50)
qc_2.h(range(50))
qc_2.measure_all()
circuits.append(qc_2)
circuits.append(qc)
backend = self.backend()
shots = 100
result = backend.run(circuits, shots=shots).result()
result = backend.run(circuits, shots=shots, method='statevector').result()
self.assertEqual(result.status, 'PARTIAL COMPLETED')
self.assertTrue(hasattr(result.results[1].data, 'counts'))
self.assertFalse(hasattr(result.results[0].data, 'counts'))
11 changes: 5 additions & 6 deletions test/terra/backends/aer_simulator/test_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from ddt import ddt
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit import CircuitInstruction
from qiskit.circuit.library import Measure
from test.terra.reference import ref_algorithms

from test.terra.backends.simulator_test_case import (
Expand All @@ -42,7 +41,7 @@ def test_quantum_register_circuit(self, method, device):
circuit.cx(qubits[0], qubits[2])

for q, c in zip(qubits, clbits):
circuit.append(CircuitInstruction(Measure(), [q], [c]))
circuit.measure(q, c)

backend = self.backend(
method=method,
Expand Down Expand Up @@ -72,7 +71,7 @@ def test_qubits_circuit(self, method, device):
circuit.cx(qubits[0], qubits[2])

for q, c in zip(qubits, clbits):
circuit.append(CircuitInstruction(Measure(), [q], [c]))
circuit.measure(q, c)

backend = self.backend(
method=method,
Expand Down Expand Up @@ -105,7 +104,7 @@ def test_qubits_quantum_register_circuit(self, method, device):

for qubits, clbits in zip([qubits0, qubits1], [clbits1, clbits2]):
for q, c in zip(qubits, clbits):
circuit.append(CircuitInstruction(Measure(), [q], [c]))
circuit.measure(q, c)

backend = self.backend(
method=method,
Expand Down Expand Up @@ -136,8 +135,8 @@ def test_qubits_quantum_register_circuit(self, method, device):

for qubits, clbits in zip([qubits0, qubits1, qubits2], [clbits1, clbits2, clbits3]):
for q, c in zip(qubits, clbits):
circuit.append(CircuitInstruction(Measure(), [q], [c]))

circuit.measure(q, c)
backend = self.backend(
method=method,
device=device,
Expand Down
51 changes: 51 additions & 0 deletions test/terra/backends/test_parameterized_qobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,57 @@ def parameterized_qobj(
parameterizations=params)
return qobj

def test_parameterized_qobj_qasm_save_expval(self):
"""Test parameterized qobj with Expectation Value snapshot and qasm simulator."""
shots = 1000
labels = save_expval_labels() * 3
counts_targets = save_expval_counts(shots) * 3
value_targets = save_expval_pre_meas_values() * 3

backend = AerSimulator()
qobj = self.parameterized_qobj(backend=backend,
shots=1000,
measure=True,
snapshot=True)
self.assertIn('parameterizations', qobj.to_dict()['config'])
with self.assertWarns(DeprecationWarning):
job = backend.run(qobj, **self.BACKEND_OPTS)
result = job.result()
success = getattr(result, 'success', False)
num_circs = len(result.to_dict()['results'])
self.assertTrue(success)
self.compare_counts(result,
range(num_circs),
counts_targets,
delta=0.1 * shots)
# Check snapshots
for j, target in enumerate(value_targets):
data = result.data(j)
for label in labels:
self.assertAlmostEqual(
data[label], target[label], delta=1e-7)

def test_parameterized_qobj_statevector(self):
"""Test parameterized qobj with Expectation Value snapshot and qasm simulator."""
statevec_targets = save_expval_final_statevecs() * 3

backend = AerSimulator(method="statevector")
qobj = self.parameterized_qobj(
backend=backend, measure=False, snapshot=False, save_state=True,
)
self.assertIn('parameterizations', qobj.to_dict()['config'])
with self.assertWarns(DeprecationWarning):
job = backend.run(qobj, **self.BACKEND_OPTS)
result = job.result()
success = getattr(result, 'success', False)
num_circs = len(result.to_dict()['results'])
self.assertTrue(success)

for j in range(num_circs):
statevector = result.get_statevector(j)
np.testing.assert_array_almost_equal(
statevector, statevec_targets[j].data, decimal=7)

def test_run_path(self):
"""Test parameterized circuit path via backed.run()"""
shots = 1000
Expand Down

0 comments on commit 2b1c077

Please sign in to comment.