From 7f603defc67662b78666c1baabd5db14057d6490 Mon Sep 17 00:00:00 2001 From: Hiroshi Horii Date: Sat, 11 Mar 2023 15:56:58 +0900 Subject: [PATCH] reformat qiskit_aer, test, tools, and setup.py with length 100 --- pyproject.toml | 4 + qiskit_aer/aerprovider.py | 4 +- qiskit_aer/backends/aer_compiler.py | 135 ++------ qiskit_aer/backends/aer_simulator.py | 20 +- qiskit_aer/backends/aerbackend.py | 52 +-- qiskit_aer/backends/backend_utils.py | 24 +- qiskit_aer/backends/compatibility.py | 4 +- qiskit_aer/backends/pulse_simulator.py | 34 +- qiskit_aer/backends/qasm_simulator.py | 24 +- qiskit_aer/backends/statevector_simulator.py | 9 +- qiskit_aer/backends/unitary_simulator.py | 13 +- qiskit_aer/jobs/aerjob.py | 4 +- qiskit_aer/jobs/aerjobset.py | 44 +-- .../save_instructions/save_amplitudes.py | 15 +- .../library/save_instructions/save_data.py | 15 +- .../save_instructions/save_density_matrix.py | 7 +- .../save_expectation_value.py | 12 +- .../save_matrix_product_state.py | 14 +- .../save_instructions/save_probabilities.py | 14 +- .../save_instructions/save_stabilizer.py | 14 +- .../library/save_instructions/save_state.py | 8 +- .../save_instructions/save_statevector.py | 28 +- qiskit_aer/noise/device/models.py | 7 +- qiskit_aer/noise/errors/quantum_error.py | 4 +- qiskit_aer/noise/errors/readout_error.py | 34 +- qiskit_aer/noise/errors/standard_errors.py | 41 +-- qiskit_aer/noise/noise_model.py | 76 ++--- qiskit_aer/noise/passes/local_noise_pass.py | 20 +- .../noise/passes/relaxation_noise_pass.py | 4 +- qiskit_aer/primitives/estimator.py | 94 ++---- qiskit_aer/primitives/sampler.py | 12 +- .../pulse/controllers/digest_pulse_qobj.py | 53 +-- qiskit_aer/pulse/controllers/mc_controller.py | 15 +- .../pulse/controllers/pulse_controller.py | 42 +-- .../pulse/controllers/unitary_controller.py | 6 +- qiskit_aer/pulse/de/DE_Methods.py | 22 +- qiskit_aer/pulse/de/type_utils.py | 4 +- .../system_models/duffing_model_generators.py | 32 +- .../pulse/system_models/hamiltonian_model.py | 16 +- .../pulse/system_models/pulse_system_model.py | 5 +- .../operator_from_string.py | 4 +- .../operator_generators.py | 4 +- .../string_model_parser.py | 16 +- .../quantum_info/states/aer_densitymatrix.py | 24 +- qiskit_aer/quantum_info/states/aer_state.py | 28 +- .../quantum_info/states/aer_statevector.py | 36 +-- qiskit_aer/utils/noise_model_inserter.py | 8 +- qiskit_aer/utils/noise_transformation.py | 12 +- qiskit_aer/version.py | 4 +- setup.py | 26 +- test/benchmark/basic.py | 8 +- test/benchmark/circuit_library_circuits.py | 11 +- test/benchmark/noise.py | 14 +- test/benchmark/simulator_benchmark.py | 44 +-- test/benchmark/vqe_application.py | 6 +- .../backends/aer_simulator/test_algorithms.py | 16 +- .../aer_simulator/test_auto_method.py | 16 +- .../backends/aer_simulator/test_chunk.py | 28 +- .../backends/aer_simulator/test_circuit.py | 20 +- .../backends/aer_simulator/test_cliffords.py | 8 +- .../aer_simulator/test_conditional.py | 32 +- .../backends/aer_simulator/test_executors.py | 22 +- .../aer_simulator/test_from_backend.py | 16 +- .../backends/aer_simulator/test_fusion.py | 98 ++---- .../backends/aer_simulator/test_initialize.py | 7 +- .../aer_simulator/test_job_splitting.py | 5 +- .../backends/aer_simulator/test_measure.py | 31 +- .../backends/aer_simulator/test_metadata.py | 8 +- .../aer_simulator/test_multiplexer.py | 17 +- .../backends/aer_simulator/test_noise.py | 29 +- .../aer_simulator/test_non_cliffords.py | 8 +- .../backends/aer_simulator/test_options.py | 19 +- .../backends/aer_simulator/test_pauli_gate.py | 8 +- .../backends/aer_simulator/test_reset.py | 4 +- .../aer_simulator/test_save_amplitudes.py | 15 +- .../aer_simulator/test_save_density_matrix.py | 52 +-- .../aer_simulator/test_save_expval.py | 40 +-- .../test_save_matrix_product_state.py | 12 +- .../aer_simulator/test_save_probabilities.py | 20 +- .../backends/aer_simulator/test_save_state.py | 8 +- .../aer_simulator/test_save_statevector.py | 25 +- .../test_save_statevector_dict.py | 25 +- .../aer_simulator/test_save_superop.py | 4 +- .../aer_simulator/test_save_unitary.py | 4 +- .../backends/aer_simulator/test_set_state.py | 24 +- .../aer_simulator/test_standard_gates.py | 9 +- .../aer_simulator/test_thread_management.py | 76 ++--- .../backends/aer_simulator/test_truncate.py | 12 +- .../aer_simulator/test_unitary_gate.py | 8 +- .../test_wrapper_statevector_simulator.py | 12 +- .../test_wrapper_unitary_simulator.py | 12 +- test/terra/backends/pulse_sim_independent.py | 20 +- .../backends/test_config_pulse_simulator.py | 45 +-- .../terra/backends/test_parameterized_qobj.py | 76 ++--- test/terra/backends/test_pulse_simulator.py | 306 ++++-------------- test/terra/common.py | 29 +- test/terra/extensions/test_save_expval.py | 20 +- test/terra/extensions/test_wrappers.py | 6 +- .../passes/test_relaxation_noise_pass.py | 16 +- test/terra/noise/test_device_models.py | 8 +- test/terra/noise/test_noise_model.py | 40 +-- test/terra/noise/test_noise_transformation.py | 70 +--- test/terra/noise/test_quantum_error.py | 8 +- test/terra/noise/test_readout_error.py | 43 +-- test/terra/noise/test_standard_errors.py | 107 ++---- test/terra/primitives/test_estimator.py | 26 +- test/terra/primitives/test_sampler.py | 20 +- .../controllers/test_pulse_controller.py | 16 +- test/terra/pulse/de/test_de_methods.py | 4 +- test/terra/pulse/de/test_type_utils.py | 8 +- .../pulse/test_duffing_model_generators.py | 164 +++------- test/terra/pulse/test_system_models.py | 24 +- test/terra/reference/ref_2q_clifford.py | 12 +- test/terra/reference/ref_algorithms.py | 19 +- test/terra/reference/ref_diagonal_gate.py | 31 +- test/terra/reference/ref_initialize.py | 27 +- test/terra/reference/ref_measure.py | 24 +- test/terra/reference/ref_multiplexer.py | 24 +- test/terra/reference/ref_non_clifford.py | 60 +--- test/terra/reference/ref_readout_noise.py | 8 +- test/terra/reference/ref_save_expval.py | 15 +- test/terra/reference/ref_unitary_gate.py | 20 +- test/terra/states/test_aer_densitymatrix.py | 62 +--- test/terra/states/test_aer_state.py | 4 +- test/terra/states/test_aer_statevector.py | 44 +-- tools/generate_qobj.py | 4 +- tools/verify_standalone_results.py | 11 +- tools/verify_wheels.py | 48 +-- 128 files changed, 809 insertions(+), 2640 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 27df824423..46e2c752c8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,3 +32,7 @@ environment = { CMAKE_GENERATOR = "Visual Studio 16 2019"} [[tool.cibuildwheel.overrides]] select = "cp3{7,8,9,10,11}-manylinux_i686" before-all = "yum install -y wget && bash {project}/tools/install_openblas_i686.sh && bash {project}/tools/install_rust.sh" + +[tool.black] +line-length = 100 +target-version = ['py37', 'py38', 'py39', 'py310', 'py311'] diff --git a/qiskit_aer/aerprovider.py b/qiskit_aer/aerprovider.py index 4a7b50c27c..8fca28f521 100644 --- a/qiskit_aer/aerprovider.py +++ b/qiskit_aer/aerprovider.py @@ -49,9 +49,7 @@ def __init__(self): if device != "CPU": new_name = f"{name}_{device}".lower() device_name = device - backends.append( - (new_name, AerSimulator, method, device_name) - ) + backends.append((new_name, AerSimulator, method, device_name)) # Add legacy backend names backends += [ diff --git a/qiskit_aer/backends/aer_compiler.py b/qiskit_aer/backends/aer_compiler.py index 88d468e767..fdb4fd88bd 100644 --- a/qiskit_aer/backends/aer_compiler.py +++ b/qiskit_aer/backends/aer_compiler.py @@ -21,13 +21,7 @@ from qiskit.extensions import Initialize from qiskit.providers.options import Options from qiskit.pulse import Schedule, ScheduleBlock -from qiskit.circuit.controlflow import ( - WhileLoopOp, - ForLoopOp, - IfElseOp, - BreakLoopOp, - ContinueLoopOp, -) +from qiskit.circuit.controlflow import WhileLoopOp, ForLoopOp, IfElseOp, BreakLoopOp, ContinueLoopOp from qiskit.compiler import transpile from qiskit.qobj import QobjExperimentHeader from qiskit_aer.aererror import AerError @@ -76,8 +70,7 @@ def compile(self, circuits, basis_gates=None, optypes=None): circuit = self._inline_initialize(circuit, compiled_optypes[idx]) if self._is_dynamic(circuit, compiled_optypes[idx]): compiled_circ = transpile( - self._inline_circuit(circuit, None, None), - basis_gates=basis_gates, + self._inline_circuit(circuit, None, None), basis_gates=basis_gates ) compiled_circuits.append(compiled_circ) # Recompute optype for compiled circuit @@ -108,9 +101,7 @@ def _inline_initialize(self, circ, optype): for inst, qargs, cargs in circ.data: if isinstance(inst, Initialize) and not isinstance(inst.params[0], complex): # Assume that the decomposed circuit of inst.definition consists of basis gates - new_circ.compose( - inst.definition.decompose(), qargs, cargs, inplace=True - ) + new_circ.compose(inst.definition.decompose(), qargs, cargs, inplace=True) else: new_circ._append(inst, qargs, cargs) @@ -122,13 +113,7 @@ def _is_dynamic(circuit, optype=None): if not isinstance(circuit, QuantumCircuit): return False - controlflow_types = ( - WhileLoopOp, - ForLoopOp, - IfElseOp, - BreakLoopOp, - ContinueLoopOp, - ) + controlflow_types = (WhileLoopOp, ForLoopOp, IfElseOp, BreakLoopOp, ContinueLoopOp) # Check via optypes if isinstance(optype, set): @@ -171,21 +156,15 @@ def _inline_circuit(self, circ, continue_label, break_label, bit_map=None): ret.barrier() elif isinstance(instruction.operation, IfElseOp): ret.barrier() - self._inline_if_else_op( - instruction, continue_label, break_label, ret, bit_map - ) + self._inline_if_else_op(instruction, continue_label, break_label, ret, bit_map) ret.barrier() elif isinstance(instruction.operation, BreakLoopOp): ret._append( - AerJump(break_label, ret.num_qubits, ret.num_clbits), - ret.qubits, - ret.clbits, + AerJump(break_label, ret.num_qubits, ret.num_clbits), ret.qubits, ret.clbits ) elif isinstance(instruction.operation, ContinueLoopOp): ret._append( - AerJump(continue_label, ret.num_qubits, ret.num_clbits), - ret.qubits, - ret.clbits, + AerJump(continue_label, ret.num_qubits, ret.num_clbits), ret.qubits, ret.clbits ) else: ret._append(instruction) @@ -220,9 +199,7 @@ def _inline_for_loop_op(self, instruction, parent, bit_map): break_label = f"{loop_name}_end" for index in indexset: continue_label = f"{loop_name}_{index}" - inlined_body = self._inline_circuit( - body, continue_label, break_label, inner_bit_map - ) + inlined_body = self._inline_circuit(body, continue_label, break_label, inner_bit_map) if loop_parameter is not None: inlined_body = inlined_body.bind_parameters({loop_parameter: index}) parent.append(inlined_body, qargs, cargs) @@ -233,9 +210,7 @@ def _inline_for_loop_op(self, instruction, parent, bit_map): def _inline_while_loop_op(self, instruction, parent, bit_map): """inline while_loop body with jump and mark instructions""" - condition_tuple = self._convert_c_if_args( - instruction.operation.condition, bit_map - ) + condition_tuple = self._convert_c_if_args(instruction.operation.condition, bit_map) (body,) = instruction.operation.params self._last_flow_id += 1 @@ -273,31 +248,19 @@ def _inline_while_loop_op(self, instruction, parent, bit_map): ) c_if_args = self._convert_c_if_args(condition_tuple, bit_map) - parent.append( - AerMark(continue_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) + parent.append(AerMark(continue_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) parent.append( AerJump(loop_start_label, len(qargs), len(mark_cargs)).c_if(*c_if_args), qargs, mark_cargs, ) - parent.append( - AerJump(break_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) - parent.append( - AerMark(loop_start_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) + parent.append(AerJump(break_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) + parent.append(AerMark(loop_start_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) parent.append(inlined_body, qargs, cargs) - parent.append( - AerJump(continue_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) - parent.append( - AerMark(break_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) + parent.append(AerJump(continue_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) + parent.append(AerMark(break_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) - def _inline_if_else_op( - self, instruction, continue_label, break_label, parent, bit_map - ): + def _inline_if_else_op(self, instruction, continue_label, break_label, parent, bit_map): """inline true and false bodies of if_else with jump and mark instructions""" condition_tuple = instruction.operation.condition true_body, false_body = instruction.operation.params @@ -339,20 +302,12 @@ def _inline_if_else_op( } parent.append( - AerJump(if_true_label, len(qargs), len(mark_cargs)).c_if(*c_if_args), - qargs, - mark_cargs, - ) - parent.append( - AerJump(if_else_label, len(qargs), len(mark_cargs)), qargs, mark_cargs + AerJump(if_true_label, len(qargs), len(mark_cargs)).c_if(*c_if_args), qargs, mark_cargs ) + parent.append(AerJump(if_else_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) + parent.append(AerMark(if_true_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) parent.append( - AerMark(if_true_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) - parent.append( - self._inline_circuit(true_body, continue_label, break_label, true_bit_map), - qargs, - cargs, + self._inline_circuit(true_body, continue_label, break_label, true_bit_map), qargs, cargs ) if false_body: @@ -363,23 +318,15 @@ def _inline_if_else_op( zip(false_body.clbits, instruction.clbits), ) } + parent.append(AerJump(if_end_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) + parent.append(AerMark(if_else_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) parent.append( - AerJump(if_end_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) - parent.append( - AerMark(if_else_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) - parent.append( - self._inline_circuit( - false_body, continue_label, break_label, false_bit_map - ), + self._inline_circuit(false_body, continue_label, break_label, false_bit_map), qargs, cargs, ) - parent.append( - AerMark(if_end_label, len(qargs), len(mark_cargs)), qargs, mark_cargs - ) + parent.append(AerMark(if_end_label, len(qargs), len(mark_cargs)), qargs, mark_cargs) def compile_circuit(circuits, basis_gates=None, optypes=None): @@ -433,9 +380,7 @@ def assemble_circuit(circuit: QuantumCircuit): for creg in circuit.cregs: creg_sizes.append([creg.name, creg.size]) - is_conditional = any( - getattr(inst.operation, "condition", None) for inst in circuit.data - ) + is_conditional = any(getattr(inst.operation, "condition", None) for inst in circuit.data) header = QobjExperimentHeader( n_qubits=num_qubits, @@ -479,21 +424,12 @@ def assemble_circuit(circuit: QuantumCircuit): aer_circ.bfunc(f"0x{mask:X}", f"0x{val:X}", "==", conditional_reg) max_conditional_idx += 1 - _assemble_op( - aer_circ, - inst, - qubit_indices, - clbit_indices, - is_conditional, - conditional_reg, - ) + _assemble_op(aer_circ, inst, qubit_indices, clbit_indices, is_conditional, conditional_reg) return aer_circ -def _assemble_op( - aer_circ, inst, qubit_indices, clbit_indices, is_conditional, conditional_reg -): +def _assemble_op(aer_circ, inst, qubit_indices, clbit_indices, is_conditional, conditional_reg): operation = inst.operation qubits = [qubit_indices[qubit] for qubit in inst.qubits] clbits = [clbit_indices[clbit] for clbit in inst.clbits] @@ -566,9 +502,7 @@ def _assemble_op( "cu2", "cu3", }: - aer_circ.gate( - name, qubits, params, [], conditional_reg, label if label else name - ) + 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) @@ -579,13 +513,9 @@ def _assemble_op( elif name == "diagonal": 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" - ) + 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 - ) + aer_circ.gate(name, qubits, [], params, conditional_reg, label if label else name) elif name == "initialize": aer_circ.initialize(qubits, params) elif name == "roerror": @@ -609,9 +539,7 @@ def _assemble_op( }: aer_circ.save_state(qubits, name, operation._subtype, label if label else name) elif name in {"save_amplitudes", "save_amplitudes_sq"}: - aer_circ.save_amplitudes( - qubits, name, params, operation._subtype, label if label else name - ) + aer_circ.save_amplitudes(qubits, name, params, operation._subtype, label if label else name) elif name in ("save_expval", "save_expval_var"): paulis = [] coeff_reals = [] @@ -653,8 +581,7 @@ def _assemble_op( aer_circ.set_qerror_loc(qubits, label if label else name, conditional_reg) elif name in ("for_loop", "while_loop", "if_else"): raise AerError( - "control-flow instructions must be converted " - f"to jump and mark instructions: {name}" + "control-flow instructions must be converted " f"to jump and mark instructions: {name}" ) else: diff --git a/qiskit_aer/backends/aer_simulator.py b/qiskit_aer/backends/aer_simulator.py index a31755add4..db601d6546 100644 --- a/qiskit_aer/backends/aer_simulator.py +++ b/qiskit_aer/backends/aer_simulator.py @@ -641,9 +641,7 @@ class AerSimulator(AerBackend): _AVAILABLE_DEVICES = None - def __init__( - self, configuration=None, properties=None, provider=None, **backend_options - ): + def __init__(self, configuration=None, properties=None, provider=None, **backend_options): self._controller = aer_controller_execute() # Update available methods and devices for class @@ -653,26 +651,19 @@ def __init__( ) if AerSimulator._AVAILABLE_METHODS is None: AerSimulator._AVAILABLE_METHODS = available_methods( - self._controller, - AerSimulator._SIMULATION_METHODS, - AerSimulator._AVAILABLE_DEVICES, + self._controller, AerSimulator._SIMULATION_METHODS, AerSimulator._AVAILABLE_DEVICES ) # Default configuration if configuration is None: - configuration = QasmBackendConfiguration.from_dict( - AerSimulator._DEFAULT_CONFIGURATION - ) + configuration = QasmBackendConfiguration.from_dict(AerSimulator._DEFAULT_CONFIGURATION) # Cache basis gates since computing the intersection # of noise model, method, and config gates is expensive. self._cached_basis_gates = self._BASIS_GATES["automatic"] super().__init__( - configuration, - properties=properties, - provider=provider, - backend_options=backend_options, + configuration, properties=properties, provider=provider, backend_options=backend_options ) @classmethod @@ -878,8 +869,7 @@ def _validate(self, qobj): break if no_data: logger.warning( - 'No measure or save instruction in circuit "%s": ' - "results will be empty.", + 'No measure or save instruction in circuit "%s": ' "results will be empty.", experiment.header.name, ) diff --git a/qiskit_aer/backends/aerbackend.py b/qiskit_aer/backends/aerbackend.py index 2e2126c6f6..4ff9a3d6ed 100644 --- a/qiskit_aer/backends/aerbackend.py +++ b/qiskit_aer/backends/aerbackend.py @@ -43,12 +43,7 @@ class AerBackend(Backend, ABC): """Qiskit Aer Backend class.""" def __init__( - self, - configuration, - properties=None, - defaults=None, - backend_options=None, - provider=None, + self, configuration, properties=None, defaults=None, backend_options=None, provider=None ): """Aer class for backends. @@ -113,9 +108,7 @@ def _convert_circuit_binds(self, circuit, binds): def _convert_binds(self, circuits, parameter_binds): if isinstance(circuits, QuantumCircuit): if len(parameter_binds) > 1: - raise AerError( - "More than 1 parameter table provided for a single circuit" - ) + raise AerError("More than 1 parameter table provided for a single circuit") return [self._convert_circuit_binds(circuits, parameter_binds[0])] elif len(parameter_binds) != len(circuits): @@ -217,9 +210,7 @@ def run(self, circuits, validate=False, parameter_binds=None, **run_options): # 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 - return self._run_qobj( - circuits, validate, parameter_binds, **run_options - ) + return self._run_qobj(circuits, validate, parameter_binds, **run_options) else: return self._run_circuits(circuits, parameter_binds, **run_options) elif not only_circuits and only_pulse: @@ -231,17 +222,14 @@ def run(self, circuits, validate=False, parameter_binds=None, **run_options): ) else: raise TypeError( - "bad input to run() function;" - "circuits must be either circuits or schedules" + "bad input to run() function;" "circuits must be either circuits or schedules" ) def _run_circuits(self, circuits, parameter_binds, **run_options): """Run circuits by generating native circuits.""" circuits, noise_model = self._compile(circuits, **run_options) if parameter_binds: - run_options["parameterizations"] = self._convert_binds( - circuits, parameter_binds - ) + run_options["parameterizations"] = self._convert_binds(circuits, parameter_binds) config = generate_aer_config(circuits, self.options, **run_options) # Submit job @@ -288,16 +276,10 @@ def _run_qobj(self, circuits, validate=False, parameter_binds=None, **run_option # Submit job job_id = str(uuid.uuid4()) if isinstance(experiments, list): - aer_job = AerJobSet( - self, job_id, self._execute_qobj_job, experiments, executor - ) + aer_job = AerJobSet(self, job_id, self._execute_qobj_job, experiments, executor) else: aer_job = AerJob( - self, - job_id, - self._execute_qobj_job, - qobj=experiments, - executor=executor, + self, job_id, self._execute_qobj_job, qobj=experiments, executor=executor ) aer_job.submit() @@ -436,9 +418,7 @@ def _execute_qobj_job(self, qobj, job_id="", format_result=True): return self._format_results(output) return output - def _execute_circuits_job( - self, circuits, noise_model, config, job_id="", format_result=True - ): + def _execute_circuits_job(self, circuits, noise_model, config, job_id="", format_result=True): """Run a job""" # Start timer start = time.time() @@ -508,9 +488,7 @@ def _format_results(output): save_subtypes = metadata.get("result_subtypes", {}) for key, val in data.items(): if key in save_types: - data[key] = format_save_type( - val, save_types[key], save_subtypes[key] - ) + data[key] = format_save_type(val, save_types[key], save_subtypes[key]) return Result.from_dict(output) def _compile(self, circuits, **run_options): @@ -583,22 +561,16 @@ def _assemble_noise_model(self, circuits, optypes, **run_options): # This avoids unnecessarily copying the noise model for circuits # that do not contain a quantum error updated_noise = False - noise_model = run_options.get( - "noise_model", getattr(self.options, "noise_model", None) - ) + noise_model = run_options.get("noise_model", getattr(self.options, "noise_model", None)) # Add custom pass noise only to QuantumCircuit objects that contain delay # instructions since this is the only instruction handled by the noise pass # at present - if noise_model and all( - isinstance(circ, QuantumCircuit) for circ in run_circuits - ): + if noise_model and all(isinstance(circ, QuantumCircuit) for circ in run_circuits): npm = noise_model._pass_manager() if npm is not None: # Get indicies of circuits that need noise transpiling - transpile_idxs = [ - idx for idx, optype in enumerate(optypes) if Delay in optype - ] + transpile_idxs = [idx for idx, optype in enumerate(optypes) if Delay in optype] # Transpile only the required circuits transpiled_circuits = npm.run([run_circuits[i] for i in transpile_idxs]) diff --git a/qiskit_aer/backends/backend_utils.py b/qiskit_aer/backends/backend_utils.py index 72b3fbe5fc..446406c796 100644 --- a/qiskit_aer/backends/backend_utils.py +++ b/qiskit_aer/backends/backend_utils.py @@ -22,13 +22,7 @@ from qiskit.qobj import QasmQobjInstruction from qiskit.result import ProbDistribution from qiskit.quantum_info import Clifford -from .compatibility import ( - Statevector, - DensityMatrix, - StabilizerState, - Operator, - SuperOp, -) +from .compatibility import Statevector, DensityMatrix, StabilizerState, Operator, SuperOp # Available system memory SYSTEM_MEMORY_GB = local_hardware_info()["memory"] @@ -452,11 +446,7 @@ def available_methods(controller, methods, devices): for method in methods: if method not in valid_methods: qobj = assemble( - dummy_circ, - optimization_level=0, - shots=1, - method=method, - device=device, + dummy_circ, optimization_level=0, shots=1, method=method, device=device ) result = cpp_execute_qobj(controller, qobj) if result.get("success", False): @@ -473,11 +463,7 @@ def available_devices(controller, devices): valid_devices = [] for device in devices: qobj = assemble( - dummy_circ, - optimization_level=0, - shots=1, - method="statevector", - device=device, + dummy_circ, optimization_level=0, shots=1, method="statevector", device=device ) result = cpp_execute_qobj(controller, qobj) if result.get("success", False): @@ -509,9 +495,7 @@ def add_final_save_op(aer_circuits, state): for aer_circuit in aer_circuits: num_qubits = aer_circuit.num_qubits - aer_circuit.save_state( - list(range(num_qubits)), f"save_{state}", "single", state - ) + aer_circuit.save_state(list(range(num_qubits)), f"save_{state}", "single", state) return aer_circuits diff --git a/qiskit_aer/backends/compatibility.py b/qiskit_aer/backends/compatibility.py index 2f3c874631..068edda4be 100644 --- a/qiskit_aer/backends/compatibility.py +++ b/qiskit_aer/backends/compatibility.py @@ -284,6 +284,4 @@ def _add(self, other): raise NotImplementedError(f"{type(self)} does not support addition") def _multiply(self, other): - raise NotImplementedError( - f"{type(self)} does not support scalar multiplication" - ) + raise NotImplementedError(f"{type(self)} does not support scalar multiplication") diff --git a/qiskit_aer/backends/pulse_simulator.py b/qiskit_aer/backends/pulse_simulator.py index b817e2de32..4fea7f0974 100644 --- a/qiskit_aer/backends/pulse_simulator.py +++ b/qiskit_aer/backends/pulse_simulator.py @@ -157,12 +157,7 @@ class PulseSimulator(AerBackend): """ def __init__( - self, - configuration=None, - properties=None, - defaults=None, - provider=None, - **backend_options + self, configuration=None, properties=None, defaults=None, provider=None, **backend_options ): warn( "The Pulse simulator backend in Qiskit Aer is deprecated and will " @@ -182,11 +177,7 @@ def __init__( if defaults is None: defaults = PulseDefaults( - qubit_freq_est=[inf], - meas_freq_est=[inf], - buffer=0, - cmd_def=[], - pulse_library=[], + qubit_freq_est=[inf], meas_freq_est=[inf], buffer=0, cmd_def=[], pulse_library=[] ) super().__init__( @@ -201,9 +192,7 @@ def __init__( subsystem_list = backend_options.get("subsystem_list", None) if backend_options.get("system_model") is None: if hasattr(configuration, "hamiltonian"): - system_model = PulseSystemModel.from_config( - configuration, subsystem_list - ) + system_model = PulseSystemModel.from_config(configuration, subsystem_list) self._set_system_model(system_model) @classmethod @@ -266,9 +255,7 @@ def _system_model(self): def from_backend(cls, backend, **options): """Initialize simulator from backend.""" if isinstance(backend, BackendV2): - raise AerError( - "PulseSimulator.from_backend does not currently support V2 Backends." - ) + raise AerError("PulseSimulator.from_backend does not currently support V2 Backends.") configuration = copy.copy(backend.configuration()) defaults = copy.copy(backend.defaults()) properties = copy.copy(backend.properties()) @@ -283,7 +270,7 @@ def from_backend(cls, backend, **options): defaults=defaults, backend_name=backend_name, description=description, - **options + **options, ) return sim @@ -319,9 +306,7 @@ def set_option(self, key, value): if key == "hamiltonian": # if option is hamiltonian, set in configuration and reconstruct pulse system model subsystem_list = getattr(self._options.get, "subsystem_list", None) - system_model = PulseSystemModel.from_config( - self.configuration(), subsystem_list - ) + system_model = PulseSystemModel.from_config(self.configuration(), subsystem_list) super().set_option("system_model", system_model) self._set_configuration_option(key, value) return @@ -346,9 +331,7 @@ def set_option(self, key, value): def _set_system_model(self, system_model): """Set system model option""" self._set_configuration_option("dt", getattr(system_model, "dt", [])) - self._set_configuration_option( - "u_channel_lo", getattr(system_model, "u_channel_lo", []) - ) + self._set_configuration_option("u_channel_lo", getattr(system_model, "u_channel_lo", [])) super().set_option("system_model", system_model) def _validate(self, qobj): @@ -374,8 +357,7 @@ def _validate(self, qobj): if num_acquires == 0: raise AerError( - "PulseSimulator requires at least one Acquire " - "instruction per schedule." + "PulseSimulator requires at least one Acquire " "instruction per schedule." ) @staticmethod diff --git a/qiskit_aer/backends/qasm_simulator.py b/qiskit_aer/backends/qasm_simulator.py index c24120cb8c..a7978da705 100644 --- a/qiskit_aer/backends/qasm_simulator.py +++ b/qiskit_aer/backends/qasm_simulator.py @@ -432,9 +432,7 @@ class QasmSimulator(AerBackend): _AVAILABLE_DEVICES = None - def __init__( - self, configuration=None, properties=None, provider=None, **backend_options - ): + def __init__(self, configuration=None, properties=None, provider=None, **backend_options): warn( "The `QasmSimulator` backend will be deprecated in the" " future. It has been superseded by the `AerSimulator`" @@ -454,9 +452,7 @@ def __init__( # Default configuration if configuration is None: - configuration = QasmBackendConfiguration.from_dict( - QasmSimulator._DEFAULT_CONFIGURATION - ) + configuration = QasmBackendConfiguration.from_dict(QasmSimulator._DEFAULT_CONFIGURATION) else: configuration.open_pulse = False @@ -465,10 +461,7 @@ def __init__( self._cached_basis_gates = self._DEFAULT_BASIS_GATES super().__init__( - configuration, - properties=properties, - provider=provider, - backend_options=backend_options, + configuration, properties=properties, provider=provider, backend_options=backend_options ) def __repr__(self): @@ -542,9 +535,7 @@ def _default_options(cls): def from_backend(cls, backend, **options): """Initialize simulator from backend.""" if isinstance(backend, BackendV2): - raise AerError( - "QasmSimulator.from_backend does not currently support V2 Backends." - ) + raise AerError("QasmSimulator.from_backend does not currently support V2 Backends.") # pylint: disable=import-outside-toplevel # Avoid cyclic import from ..noise.noise_model import NoiseModel @@ -644,8 +635,7 @@ def _validate(self, qobj): # Print warning if clbits but no measure if no_measure: logger.warning( - 'No measurements in circuit "%s": ' - "count data will return all zeros.", + 'No measurements in circuit "%s": ' "count data will return all zeros.", experiment.header.name, ) @@ -920,9 +910,7 @@ def _custom_instructions(self): ] ) if method == "extended_stabilizer": - return sorted( - ["quantum_channel", "qerror_loc", "roerror", "save_statevector"] - ) + return sorted(["quantum_channel", "qerror_loc", "roerror", "save_statevector"]) return QasmSimulator._DEFAULT_CUSTOM_INSTR def _set_method_config(self, method=None): diff --git a/qiskit_aer/backends/statevector_simulator.py b/qiskit_aer/backends/statevector_simulator.py index 30d088a6b7..e7affcf1c7 100644 --- a/qiskit_aer/backends/statevector_simulator.py +++ b/qiskit_aer/backends/statevector_simulator.py @@ -239,9 +239,7 @@ class StatevectorSimulator(AerBackend): _AVAILABLE_DEVICES = None - def __init__( - self, configuration=None, properties=None, provider=None, **backend_options - ): + def __init__(self, configuration=None, properties=None, provider=None, **backend_options): warn( "The `StatevectorSimulator` backend will be deprecated in the" " future. It has been superseded by the `AerSimulator`" @@ -266,10 +264,7 @@ def __init__( configuration.open_pulse = False super().__init__( - configuration, - properties=properties, - provider=provider, - backend_options=backend_options, + configuration, properties=properties, provider=provider, backend_options=backend_options ) @classmethod diff --git a/qiskit_aer/backends/unitary_simulator.py b/qiskit_aer/backends/unitary_simulator.py index ec5d653d06..190a3eb508 100644 --- a/qiskit_aer/backends/unitary_simulator.py +++ b/qiskit_aer/backends/unitary_simulator.py @@ -226,9 +226,7 @@ class UnitarySimulator(AerBackend): _AVAILABLE_DEVICES = None - def __init__( - self, configuration=None, properties=None, provider=None, **backend_options - ): + def __init__(self, configuration=None, properties=None, provider=None, **backend_options): warn( "The `UnitarySimulator` backend will be deprecated in the" " future. It has been superseded by the `AerSimulator`" @@ -253,10 +251,7 @@ def __init__( configuration.open_pulse = False super().__init__( - configuration, - properties=properties, - provider=provider, - backend_options=backend_options, + configuration, properties=properties, provider=provider, backend_options=backend_options ) @classmethod @@ -299,9 +294,7 @@ def set_option(self, key, value): value, device = LEGACY_METHOD_MAP[value] self.set_option("device", device) if value != "unitary": - raise AerError( - "only the 'unitary' method is supported for the UnitarySimulator" - ) + raise AerError("only the 'unitary' method is supported for the UnitarySimulator") return super().set_option(key, value) diff --git a/qiskit_aer/jobs/aerjob.py b/qiskit_aer/jobs/aerjob.py index da1de6d60c..545fbe773e 100644 --- a/qiskit_aer/jobs/aerjob.py +++ b/qiskit_aer/jobs/aerjob.py @@ -135,9 +135,7 @@ def status(self): elif self._future.cancelled(): _status = JobStatus.CANCELLED elif self._future.done(): - _status = ( - JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR - ) + _status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR else: # Note: There is an undocumented Future state: PENDING, that seems to show up when # the job is enqueued, waiting for someone to pick it up. We need to deal with this diff --git a/qiskit_aer/jobs/aerjobset.py b/qiskit_aer/jobs/aerjobset.py index 58a0f04460..ce3d3d6229 100644 --- a/qiskit_aer/jobs/aerjobset.py +++ b/qiskit_aer/jobs/aerjobset.py @@ -79,9 +79,7 @@ def submit(self): RuntimeError: If the jobs were already submitted. """ if self._futures: - raise RuntimeError( - "The jobs for this managed job set have already been submitted." - ) + raise RuntimeError("The jobs for this managed job set have already been submitted.") self._future = True worker_id = 0 @@ -100,9 +98,7 @@ def submit(self): self._combined_result.append(_worker_id_list) @requires_submit - def status( - self, worker: Union[None, int, Iterable[int]] - ) -> Union[JobStatus, List[JobStatus]]: + def status(self, worker: Union[None, int, Iterable[int]]) -> Union[JobStatus, List[JobStatus]]: """Return the status of each job in this set. Args @@ -220,18 +216,12 @@ def _get_worker_result(self, worker: int, timeout: Optional[float] = None): result = aer_job.result(timeout=timeout) if result is None or not result.success: if result: - logger.warning( - "AerJobSet %s Error: %s", aer_job.name(), result.header - ) + logger.warning("AerJobSet %s Error: %s", aer_job.name(), result.header) else: - logger.warning( - "AerJobSet %s did not return a result", aer_job.name() - ) + logger.warning("AerJobSet %s did not return a result", aer_job.name()) except JobError: raise JobError( - "Timeout while waiting for the results of experiment {}".format( - aer_job.name() - ) + "Timeout while waiting for the results of experiment {}".format(aer_job.name()) ) if timeout: @@ -248,9 +238,7 @@ def _combine_job_results(self, result_list: List[Result]): _merge_result_list = [] for _result in result_list[1:]: - for _master_result, _sub_result in zip( - master_result.results, _result.results - ): + for _master_result, _sub_result in zip(master_result.results, _result.results): _merge_result_list.append(self._merge_exp(_master_result, _sub_result)) master_result.results = _merge_result_list return master_result @@ -278,9 +266,7 @@ def _accumulate_experiment_results(self, results: List[Result]): master_result = None for _result in each_result.results: - if not hasattr(_result.data, "counts") and not hasattr( - _result.data, "memory" - ): + if not hasattr(_result.data, "counts") and not hasattr(_result.data, "memory"): raise JobError("Results do not include counts or memory data") meta_data = getattr(_result.header, "metadata", None) if meta_data and "id" in meta_data: @@ -347,9 +333,7 @@ def _combine_results(self, results: List[Union[Result, None]] = None) -> Result: for each_result in results: if each_result is not None: - combined_result["results"].extend( - x.to_dict() for x in each_result.results - ) + combined_result["results"].extend(x.to_dict() for x in each_result.results) if self._end_time is None: self._end_time = datetime.datetime.now() @@ -370,9 +354,7 @@ def cancel(self) -> None: aer_job.cancel() @requires_submit - def job( - self, experiment: Union[str, QuantumCircuit, Schedule] - ) -> Tuple[AerJob, int]: + def job(self, experiment: Union[str, QuantumCircuit, Schedule]) -> Tuple[AerJob, int]: """Retrieve the job used to submit the specified experiment and its index. Args: @@ -393,9 +375,7 @@ def job( return self.worker_job(worker_index) @requires_submit - def worker( - self, experiment: Union[str, QuantumCircuit, Schedule] - ) -> Union[int, List[int]]: + def worker(self, experiment: Union[str, QuantumCircuit, Schedule]) -> Union[int, List[int]]: """Retrieve the index of job. Args: @@ -429,9 +409,7 @@ def worker( raise JobError("Unable to find the job for experiment {}.".format(experiment)) @requires_submit - def worker_job( - self, worker: Union[None, int, Iterable[int]] - ) -> Union[AerJob, List[AerJob]]: + def worker_job(self, worker: Union[None, int, Iterable[int]]) -> Union[AerJob, List[AerJob]]: """Retrieve the job specified with job's id Args: diff --git a/qiskit_aer/library/save_instructions/save_amplitudes.py b/qiskit_aer/library/save_instructions/save_amplitudes.py index 392a6ec277..bcc12383d1 100644 --- a/qiskit_aer/library/save_instructions/save_amplitudes.py +++ b/qiskit_aer/library/save_instructions/save_amplitudes.py @@ -22,9 +22,7 @@ class SaveAmplitudes(SaveSingleData): """Save complex statevector amplitudes.""" - def __init__( - self, num_qubits, params, label="amplitudes", pershot=False, conditional=False - ): + def __init__(self, num_qubits, params, label="amplitudes", pershot=False, conditional=False): """Instruction to save complex statevector amplitudes. Args: @@ -121,12 +119,7 @@ def save_amplitudes(self, params, label="amplitudes", pershot=False, conditional def save_amplitudes_squared( - self, - params, - label="amplitudes_squared", - unnormalized=False, - pershot=False, - conditional=False, + self, params, label="amplitudes_squared", unnormalized=False, pershot=False, conditional=False ): """Save squared statevector amplitudes (probabilities). @@ -168,9 +161,7 @@ def _format_amplitude_params(params, num_qubits=None): else: params = [int(i, 2) for i in params] if num_qubits and max(params) >= 2**num_qubits: - raise ExtensionError( - "Param values contain a state larger than the number of qubits" - ) + raise ExtensionError("Param values contain a state larger than the number of qubits") return params diff --git a/qiskit_aer/library/save_instructions/save_data.py b/qiskit_aer/library/save_instructions/save_data.py index fc3e839e81..cb86edd94e 100644 --- a/qiskit_aer/library/save_instructions/save_data.py +++ b/qiskit_aer/library/save_instructions/save_data.py @@ -24,16 +24,7 @@ class SaveData(Instruction): _directive = True _allowed_subtypes = set( - [ - "single", - "c_single", - "list", - "c_list", - "average", - "c_average", - "accum", - "c_accum", - ] + ["single", "c_single", "list", "c_list", "average", "c_average", "accum", "c_accum"] ) def __init__(self, name, num_qubits, label, subtype="single", params=None): @@ -129,9 +120,7 @@ def __init__( class SaveSingleData(SaveData): """Save non-averagable single data type.""" - def __init__( - self, name, num_qubits, label, pershot=False, conditional=False, params=None - ): + def __init__(self, name, num_qubits, label, pershot=False, conditional=False, params=None): """Create new save data instruction. Args: diff --git a/qiskit_aer/library/save_instructions/save_density_matrix.py b/qiskit_aer/library/save_instructions/save_density_matrix.py index 219562d355..4532fef2f3 100644 --- a/qiskit_aer/library/save_instructions/save_density_matrix.py +++ b/qiskit_aer/library/save_instructions/save_density_matrix.py @@ -55,12 +55,7 @@ def __init__( def save_density_matrix( - self, - qubits=None, - label="density_matrix", - unnormalized=False, - pershot=False, - conditional=False, + self, qubits=None, label="density_matrix", unnormalized=False, pershot=False, conditional=False ): """Save the current simulator quantum state as a density matrix. diff --git a/qiskit_aer/library/save_instructions/save_expectation_value.py b/qiskit_aer/library/save_instructions/save_expectation_value.py index 7c41063b8d..27bcad9da0 100644 --- a/qiskit_aer/library/save_instructions/save_expectation_value.py +++ b/qiskit_aer/library/save_instructions/save_expectation_value.py @@ -204,11 +204,7 @@ def save_expectation_value( the quantum circuit. """ instr = SaveExpectationValue( - operator, - label=label, - unnormalized=unnormalized, - pershot=pershot, - conditional=conditional, + operator, label=label, unnormalized=unnormalized, pershot=pershot, conditional=conditional ) return self.append(instr, qubits) @@ -249,11 +245,7 @@ def save_expectation_value_variance( instruction to the quantum circuit. """ instr = SaveExpectationValueVariance( - operator, - label=label, - unnormalized=unnormalized, - pershot=pershot, - conditional=conditional, + operator, label=label, unnormalized=unnormalized, pershot=pershot, conditional=conditional ) return self.append(instr, qubits) diff --git a/qiskit_aer/library/save_instructions/save_matrix_product_state.py b/qiskit_aer/library/save_instructions/save_matrix_product_state.py index 9358befe5a..31163beeb3 100644 --- a/qiskit_aer/library/save_instructions/save_matrix_product_state.py +++ b/qiskit_aer/library/save_instructions/save_matrix_product_state.py @@ -21,9 +21,7 @@ class SaveMatrixProductState(SaveSingleData): """Save matrix product state instruction""" - def __init__( - self, num_qubits, label="matrix_product_state", pershot=False, conditional=False - ): + def __init__(self, num_qubits, label="matrix_product_state", pershot=False, conditional=False): """Create new instruction to save the matrix product state. Args: @@ -41,17 +39,11 @@ def __init__( simulation. """ super().__init__( - "save_matrix_product_state", - num_qubits, - label, - pershot=pershot, - conditional=conditional, + "save_matrix_product_state", num_qubits, label, pershot=pershot, conditional=conditional ) -def save_matrix_product_state( - self, label="matrix_product_state", pershot=False, conditional=False -): +def save_matrix_product_state(self, label="matrix_product_state", pershot=False, conditional=False): """Save the current simulator quantum state as a matrix product state. Args: diff --git a/qiskit_aer/library/save_instructions/save_probabilities.py b/qiskit_aer/library/save_instructions/save_probabilities.py index 164802e4e0..cb3fcec678 100644 --- a/qiskit_aer/library/save_instructions/save_probabilities.py +++ b/qiskit_aer/library/save_instructions/save_probabilities.py @@ -89,12 +89,7 @@ def __init__( def save_probabilities( - self, - qubits=None, - label="probabilities", - unnormalized=False, - pershot=False, - conditional=False, + self, qubits=None, label="probabilities", unnormalized=False, pershot=False, conditional=False ): """Save measurement outcome probabilities vector. @@ -126,12 +121,7 @@ def save_probabilities( def save_probabilities_dict( - self, - qubits=None, - label="probabilities", - unnormalized=False, - pershot=False, - conditional=False, + self, qubits=None, label="probabilities", unnormalized=False, pershot=False, conditional=False ): """Save measurement outcome probabilities vector. diff --git a/qiskit_aer/library/save_instructions/save_stabilizer.py b/qiskit_aer/library/save_instructions/save_stabilizer.py index d21b2e61f0..9ad04e3724 100644 --- a/qiskit_aer/library/save_instructions/save_stabilizer.py +++ b/qiskit_aer/library/save_instructions/save_stabilizer.py @@ -21,9 +21,7 @@ class SaveStabilizer(SaveSingleData): """Save Stabilizer instruction""" - def __init__( - self, num_qubits, label="stabilizer", pershot=False, conditional=False - ): + def __init__(self, num_qubits, label="stabilizer", pershot=False, conditional=False): """Create new instruction to save the stabilizer simulator state as a StabilizerState. Args: @@ -42,11 +40,7 @@ def __init__( simulation. """ super().__init__( - "save_stabilizer", - num_qubits, - label, - pershot=pershot, - conditional=conditional, + "save_stabilizer", num_qubits, label, pershot=pershot, conditional=conditional ) @@ -69,9 +63,7 @@ def save_stabilizer(self, label="stabilizer", pershot=False, conditional=False): This instruction is always defined across all qubits in a circuit. """ qubits = default_qubits(self) - instr = SaveStabilizer( - len(qubits), label=label, pershot=pershot, conditional=conditional - ) + instr = SaveStabilizer(len(qubits), label=label, pershot=pershot, conditional=conditional) return self.append(instr, qubits) diff --git a/qiskit_aer/library/save_instructions/save_state.py b/qiskit_aer/library/save_instructions/save_state.py index d969c3d252..ab0d43ef4b 100644 --- a/qiskit_aer/library/save_instructions/save_state.py +++ b/qiskit_aer/library/save_instructions/save_state.py @@ -48,9 +48,7 @@ def __init__(self, num_qubits, label=None, pershot=False, conditional=False): """ if label is None: label = "_method_" - super().__init__( - "save_state", num_qubits, label, pershot=pershot, conditional=conditional - ) + super().__init__("save_state", num_qubits, label, pershot=pershot, conditional=conditional) def save_state(self, label=None, pershot=False, conditional=False): @@ -74,9 +72,7 @@ def save_state(self, label=None, pershot=False, conditional=False): This instruction is always defined across all qubits in a circuit. """ qubits = default_qubits(self) - instr = SaveState( - len(qubits), label=label, pershot=pershot, conditional=conditional - ) + instr = SaveState(len(qubits), label=label, pershot=pershot, conditional=conditional) return self.append(instr, qubits) diff --git a/qiskit_aer/library/save_instructions/save_statevector.py b/qiskit_aer/library/save_instructions/save_statevector.py index 4f5eca07db..5bb112c32d 100644 --- a/qiskit_aer/library/save_instructions/save_statevector.py +++ b/qiskit_aer/library/save_instructions/save_statevector.py @@ -21,9 +21,7 @@ class SaveStatevector(SaveSingleData): """Save statevector""" - def __init__( - self, num_qubits, label="statevector", pershot=False, conditional=False - ): + def __init__(self, num_qubits, label="statevector", pershot=False, conditional=False): """Create new instruction to save the simulator statevector. Args: @@ -42,20 +40,14 @@ def __init__( simulation. """ super().__init__( - "save_statevector", - num_qubits, - label, - pershot=pershot, - conditional=conditional, + "save_statevector", num_qubits, label, pershot=pershot, conditional=conditional ) class SaveStatevectorDict(SaveSingleData): """Save statevector as ket-form dictionary.""" - def __init__( - self, num_qubits, label="statevector_dict", pershot=False, conditional=False - ): + def __init__(self, num_qubits, label="statevector_dict", pershot=False, conditional=False): """Create new instruction to save the simulator statevector as a dict. Args: @@ -74,11 +66,7 @@ def __init__( simulation. """ super().__init__( - "save_statevector_dict", - num_qubits, - label, - pershot=pershot, - conditional=conditional, + "save_statevector_dict", num_qubits, label, pershot=pershot, conditional=conditional ) @@ -101,9 +89,7 @@ def save_statevector(self, label="statevector", pershot=False, conditional=False This instruction is always defined across all qubits in a circuit. """ qubits = default_qubits(self) - instr = SaveStatevector( - len(qubits), label=label, pershot=pershot, conditional=conditional - ) + instr = SaveStatevector(len(qubits), label=label, pershot=pershot, conditional=conditional) return self.append(instr, qubits) @@ -126,9 +112,7 @@ def save_statevector_dict(self, label="statevector", pershot=False, conditional= This instruction is always defined across all qubits in a circuit. """ qubits = default_qubits(self) - instr = SaveStatevectorDict( - len(qubits), label=label, pershot=pershot, conditional=conditional - ) + instr = SaveStatevectorDict(len(qubits), label=label, pershot=pershot, conditional=conditional) return self.append(instr, qubits) diff --git a/qiskit_aer/noise/device/models.py b/qiskit_aer/noise/device/models.py index 0751aa2756..480c571a2e 100644 --- a/qiskit_aer/noise/device/models.py +++ b/qiskit_aer/noise/device/models.py @@ -195,9 +195,7 @@ def basic_device_gate_errors( relax_time = gate_length # Override with custom value if name in custom_times: - filtered = [ - val for q, val in custom_times[name] if q is None or q == qubits - ] + filtered = [val for q, val in custom_times[name] if q is None or q == qubits] if filtered: # get first value relax_time = filtered[0] @@ -282,8 +280,7 @@ def _basic_device_target_gate_errors( def _device_depolarizing_error(qubits, error_param, relax_error=None): """Construct a depolarizing_error for device. - If un-physical parameters are supplied, they are truncated to the theoretical bound values. - """ + If un-physical parameters are supplied, they are truncated to the theoretical bound values.""" # We now deduce the depolarizing channel error parameter in the # presence of T1/T2 thermal relaxation. We assume the gate error diff --git a/qiskit_aer/noise/errors/quantum_error.py b/qiskit_aer/noise/errors/quantum_error.py index a2d66f8a74..59d65c469f 100644 --- a/qiskit_aer/noise/errors/quantum_error.py +++ b/qiskit_aer/noise/errors/quantum_error.py @@ -403,9 +403,7 @@ def expand(self, other): # Overloads def __rmul__(self, other): - raise NotImplementedError( - "'QuantumError' does not support scalar multiplication." - ) + raise NotImplementedError("'QuantumError' does not support scalar multiplication.") def __truediv__(self, other): raise NotImplementedError("'QuantumError' does not support division.") diff --git a/qiskit_aer/noise/errors/readout_error.py b/qiskit_aer/noise/errors/readout_error.py index abcee0e480..8374e6736c 100644 --- a/qiskit_aer/noise/errors/readout_error.py +++ b/qiskit_aer/noise/errors/readout_error.py @@ -74,13 +74,8 @@ def __init__(self, probabilities, atol=ATOL_DEFAULT): self._check_probabilities(probabilities, atol) self._probabilities = np.array(probabilities, dtype=float) self._number_of_qubits = int(np.log2(self._probabilities.shape[0])) - if self._probabilities.shape != ( - 2**self._number_of_qubits, - 2**self._number_of_qubits, - ): - raise NoiseError( - "Input readout error probabilities is not a 2^N by 2^N matrix." - ) + if self._probabilities.shape != (2**self._number_of_qubits, 2**self._number_of_qubits): + raise NoiseError("Input readout error probabilities is not a 2^N by 2^N matrix.") def __repr__(self): """Display ReadoutError.""" @@ -138,9 +133,7 @@ def set_atol(cls, value): if value < 0: raise NoiseError("Invalid atol ({}) must be non-negative.".format(value)) if value > cls._MAX_TOL: - raise NoiseError( - "Invalid atol ({}) must be less than {}.".format(value, cls._MAX_TOL) - ) + raise NoiseError("Invalid atol ({}) must be less than {}.".format(value, cls._MAX_TOL)) cls._ATOL_DEFAULT = value @classmethod @@ -149,9 +142,7 @@ def set_rtol(cls, value): if value < 0: raise NoiseError("Invalid rtol ({}) must be non-negative.".format(value)) if value > cls._MAX_TOL: - raise NoiseError( - "Invalid rtol ({}) must be less than {}.".format(value, cls._MAX_TOL) - ) + raise NoiseError("Invalid rtol ({}) must be less than {}.".format(value, cls._MAX_TOL)) cls._RTOL_DEFAULT = value def ideal(self): @@ -271,26 +262,21 @@ def _check_probabilities(probabilities, threshold): num_qubits = int(np.log2(num_outcomes)) if 2**num_qubits != num_outcomes: raise NoiseError( - "Invalid probabilities: length " - "{} != 2**{}".format(num_outcomes, num_qubits) + "Invalid probabilities: length " "{} != 2**{}".format(num_outcomes, num_qubits) ) if len(probabilities) != num_outcomes: raise NoiseError("Invalid probabilities.") for vec in probabilities: arr = np.array(vec) if len(arr) != num_outcomes: - raise NoiseError( - "Invalid probabilities: vectors are different lengths." - ) + raise NoiseError("Invalid probabilities: vectors are different lengths.") if abs(sum(arr) - 1) > threshold: raise NoiseError( - "Invalid probabilities: sum({})= {} " - "is not 1.".format(vec, sum(arr)) + "Invalid probabilities: sum({})= {} " "is not 1.".format(vec, sum(arr)) ) if arr[arr < 0].size > 0: raise NoiseError( - "Invalid probabilities: {} " - "contains a negative probability.".format(vec) + "Invalid probabilities: {} " "contains a negative probability.".format(vec) ) def _matmul(self, other, left_multiply=False): @@ -349,9 +335,7 @@ def __xor__(self, other): return self.tensor(other) def __rmul__(self, other): - raise NotImplementedError( - "'ReadoutError' does not support scalar multiplication." - ) + raise NotImplementedError("'ReadoutError' does not support scalar multiplication.") def __truediv__(self, other): raise NotImplementedError("'ReadoutError' does not support division.") diff --git a/qiskit_aer/noise/errors/standard_errors.py b/qiskit_aer/noise/errors/standard_errors.py index 9c64c97a95..a02a8652fd 100644 --- a/qiskit_aer/noise/errors/standard_errors.py +++ b/qiskit_aer/noise/errors/standard_errors.py @@ -88,9 +88,7 @@ def mixed_unitary_error(noise_ops): instructions_probs = [] num_qubits = int(np.log2(noise_ops[0][0].shape[0])) if noise_ops[0][0].shape != (2**num_qubits, 2**num_qubits): - raise NoiseError( - "A unitary matrix in input noise_ops is not a multi-qubit matrix." - ) + raise NoiseError("A unitary matrix in input noise_ops is not a multi-qubit matrix.") for unitary, prob in noise_ops: # Check unitary if unitary.shape != noise_ops[0][0].shape: @@ -207,9 +205,7 @@ def depolarizing_error(param, num_qubits): num_terms = 4**num_qubits max_param = num_terms / (num_terms - 1) if param < 0 or param > max_param: - raise NoiseError( - "Depolarizing parameter must be in between 0 " "and {}.".format(max_param) - ) + raise NoiseError("Depolarizing parameter must be in between 0 " "and {}.".format(max_param)) # Rescale completely depolarizing channel error probs # with the identity component removed @@ -219,10 +215,7 @@ def depolarizing_error(param, num_qubits): # Generate pauli strings. The order doesn't matter as long # as the all identity string is first. - paulis = [ - Pauli("".join(tup)) - for tup in it.product(["I", "X", "Y", "Z"], repeat=num_qubits) - ] + paulis = [Pauli("".join(tup)) for tup in it.product(["I", "X", "Y", "Z"], repeat=num_qubits)] return QuantumError(zip(paulis, probs)) @@ -290,13 +283,11 @@ def thermal_relaxation_error(t1, t2, time, excited_state_population=0): """ if excited_state_population < 0: raise NoiseError( - "Invalid excited state population " - "({} < 0).".format(excited_state_population) + "Invalid excited state population " "({} < 0).".format(excited_state_population) ) if excited_state_population > 1: raise NoiseError( - "Invalid excited state population " - "({} > 1).".format(excited_state_population) + "Invalid excited state population " "({} > 1).".format(excited_state_population) ) if time < 0: raise NoiseError("Invalid gate_time ({} < 0)".format(time)) @@ -305,9 +296,7 @@ def thermal_relaxation_error(t1, t2, time, excited_state_population=0): if t2 <= 0: raise NoiseError("Invalid T_2 relaxation time parameter: T_2 <= 0.") if t2 - 2 * t1 > 0: - raise NoiseError( - "Invalid T_2 relaxation time parameter: T_2 greater than 2 * T_1." - ) + raise NoiseError("Invalid T_2 relaxation time parameter: T_2 greater than 2 * T_1.") # T1 relaxation rate if t1 == np.inf: @@ -401,13 +390,9 @@ def phase_amplitude_damping_error( """ if param_amp < 0: - raise NoiseError( - "Invalid amplitude damping to |0> parameter " "({} < 0)".format(param_amp) - ) + raise NoiseError("Invalid amplitude damping to |0> parameter " "({} < 0)".format(param_amp)) if param_phase < 0: - raise NoiseError( - "Invalid phase damping parameter " "({} < 0)".format(param_phase) - ) + raise NoiseError("Invalid phase damping parameter " "({} < 0)".format(param_phase)) if param_phase + param_amp > 1: raise NoiseError( "Invalid amplitude and phase damping parameters " @@ -415,13 +400,11 @@ def phase_amplitude_damping_error( ) if excited_state_population < 0: raise NoiseError( - "Invalid excited state population " - "({} < 0).".format(excited_state_population) + "Invalid excited state population " "({} < 0).".format(excited_state_population) ) if excited_state_population > 1: raise NoiseError( - "Invalid excited state population " - "({} > 1).".format(excited_state_population) + "Invalid excited state population " "({} > 1).".format(excited_state_population) ) c0 = np.sqrt(1 - excited_state_population) c1 = np.sqrt(excited_state_population) @@ -439,9 +422,7 @@ def phase_amplitude_damping_error( return kraus_error(noise_ops, canonical_kraus=canonical_kraus) -def amplitude_damping_error( - param_amp, excited_state_population=0, canonical_kraus=True -): +def amplitude_damping_error(param_amp, excited_state_population=0, canonical_kraus=True): r""" Return a single-qubit generalized amplitude damping quantum error channel. diff --git a/qiskit_aer/noise/noise_model.py b/qiskit_aer/noise/noise_model.py index 914f923821..29d852dbb6 100644 --- a/qiskit_aer/noise/noise_model.py +++ b/qiskit_aer/noise/noise_model.py @@ -200,9 +200,7 @@ def __init__(self, basis_gates=None): # and identities won't be unrolled self._basis_gates = set(["id", "rz", "sx", "cx"]) else: - self._basis_gates = set( - name for name, _ in self._instruction_names_labels(basis_gates) - ) + self._basis_gates = set(name for name, _ in self._instruction_names_labels(basis_gates)) # Store gates with a noise model defined self._noise_instructions = set() # Store qubits referenced in noise model. @@ -375,9 +373,7 @@ def from_backend( target = copy.deepcopy(target) for op_name, qubits, value in gate_lengths: prop = target[op_name][qubits] - prop.duration = apply_prefix( - value, gate_length_units - ) # convert to seconds + prop.duration = apply_prefix(value, gate_length_units) # convert to seconds target.update_instruction_properties(op_name, qubits, prop) all_qubit_properties = backend.target.qubit_properties if not all_qubit_properties: @@ -393,17 +389,13 @@ def from_backend( basis_gates = configuration.basis_gates all_qubit_properties = [ QubitProperties( - t1=properties.t1(q), - t2=properties.t2(q), - frequency=properties.frequency(q), + t1=properties.t1(q), t2=properties.t2(q), frequency=properties.frequency(q) ) for q in range(configuration.num_qubits) ] dt = getattr(configuration, "dt", 0) if not properties: - raise NoiseError( - f"Qiskit backend {backend} does not have a BackendProperties" - ) + raise NoiseError(f"Qiskit backend {backend} does not have a BackendProperties") else: raise NoiseError(f"{backend} is not a Qiskit backend") @@ -416,9 +408,7 @@ def from_backend( # Add gate errors with catch_warnings(): - filterwarnings( - "ignore", category=DeprecationWarning, module="qiskit_aer.noise" - ) + filterwarnings("ignore", category=DeprecationWarning, module="qiskit_aer.noise") gate_errors = basic_device_gate_errors( properties, gate_error=gate_error, @@ -443,10 +433,7 @@ def from_backend( excited_state_populations = None try: t1s = [prop.t1 for prop in all_qubit_properties] - t2s = [ - _truncate_t2_value(prop.t1, prop.t2) - for prop in all_qubit_properties - ] + t2s = [_truncate_t2_value(prop.t1, prop.t2) for prop in all_qubit_properties] delay_pass = RelaxationNoisePass( t1s=t1s, t2s=t2s, @@ -511,8 +498,7 @@ def from_backend_properties( """ if not isinstance(backend_properties, BackendProperties): raise NoiseError( - "{} is not a Qiskit backend or" - " BackendProperties".format(backend_properties) + "{} is not a Qiskit backend or" " BackendProperties".format(backend_properties) ) basis_gates = set() for prop in backend_properties.gates: @@ -552,9 +538,7 @@ def from_backend_properties( delay_pass = RelaxationNoisePass( t1s=[backend_properties.t1(q) for q in range(num_qubits)], t2s=[ - _truncate_t2_value( - backend_properties.t1(q), backend_properties.t2(q) - ) + _truncate_t2_value(backend_properties.t1(q), backend_properties.t2(q)) for q in range(num_qubits) ], dt=dt, @@ -616,9 +600,7 @@ def __str__(self): output = "NoiseModel:" output += "\n Basis gates: {}".format(self.basis_gates) if self._noise_instructions: - output += "\n Instructions with noise: {}".format( - list(self._noise_instructions) - ) + output += "\n Instructions with noise: {}".format(list(self._noise_instructions)) if self._noise_qubits: output += "\n Qubits with noise: {}".format(list(self._noise_qubits)) if default_error_ops: @@ -669,14 +651,7 @@ def add_basis_gates(self, instructions): # If the instruction is in the default basis gates for the # AerSimulator we add it to the basis gates. if name in BASIS_GATES["automatic"]: - if name not in [ - "measure", - "reset", - "initialize", - "kraus", - "superop", - "roerror", - ]: + if name not in ["measure", "reset", "initialize", "kraus", "superop", "roerror"]: self._basis_gates.add(name) def add_all_qubit_quantum_error(self, error, instructions, warnings=True): @@ -764,9 +739,7 @@ def add_quantum_error(self, error, instructions, qubits, warnings=True): try: qubits = tuple(qubits) except TypeError as ex: - raise NoiseError( - "Qubits must be convertible to a tuple of integers" - ) from ex + raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): return @@ -849,9 +822,7 @@ def add_all_qubit_readout_error(self, error, warnings=True): # Check number of qubits is correct for standard instructions if error.number_of_qubits != 1: - raise NoiseError( - "All-qubit readout errors must defined as single-qubit errors." - ) + raise NoiseError("All-qubit readout errors must defined as single-qubit errors.") if self._default_readout_error is not None: if warnings: logger.warning( @@ -898,9 +869,7 @@ def add_readout_error(self, error, qubits, warnings=True): try: qubits = tuple(qubits) except TypeError as ex: - raise NoiseError( - "Qubits must be convertible to a tuple of integers" - ) from ex + raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): @@ -1031,8 +1000,7 @@ def inst_dic_list_to_circuit(dic_list): ) circ.append( UnitaryGate( - label=dic["name"], - data=_standard_gate_unitary(dic["name"]), + label=dic["name"], data=_standard_gate_unitary(dic["name"]) ), qargs=dic["qubits"], ) @@ -1049,9 +1017,7 @@ def inst_dic_list_to_circuit(dic_list): # Add QuantumError if error_type == "qerror": - circuits = [ - inst_dic_list_to_circuit(dics) for dics in error["instructions"] - ] + circuits = [inst_dic_list_to_circuit(dics) for dics in error["instructions"]] noise_ops = tuple(zip(circuits, error["probabilities"])) qerror = QuantumError(noise_ops) qerror._id = error.get("id", None) or qerror.id @@ -1077,9 +1043,7 @@ def inst_dic_list_to_circuit(dic_list): # Add local readout error if all_gate_qubits is not None: for gate_qubits in all_gate_qubits: - noise_model.add_readout_error( - roerror, gate_qubits, warnings=False - ) + noise_model.add_readout_error(roerror, gate_qubits, warnings=False) # Add all-qubit readout error else: noise_model.add_all_qubit_readout_error(roerror, warnings=False) @@ -1144,9 +1108,7 @@ def _readout_errors_equal(self, other): if self._default_readout_error != other._default_readout_error: return False # Check local readout errors are equal - if sorted(self._local_readout_errors.keys()) != sorted( - other._local_readout_errors.keys() - ): + if sorted(self._local_readout_errors.keys()) != sorted(other._local_readout_errors.keys()): return False for key in self._local_readout_errors: if self._local_readout_errors[key] != other._local_readout_errors[key]: @@ -1166,9 +1128,7 @@ def _all_qubit_quantum_errors_equal(self, other): def _local_quantum_errors_equal(self, other): """Check two noise models have equal local quantum errors""" - if sorted(self._local_quantum_errors.keys()) != sorted( - other._local_quantum_errors.keys() - ): + if sorted(self._local_quantum_errors.keys()) != sorted(other._local_quantum_errors.keys()): return False for key in self._local_quantum_errors: inner_dict1 = self._local_quantum_errors[key] diff --git a/qiskit_aer/noise/passes/local_noise_pass.py b/qiskit_aer/noise/passes/local_noise_pass.py index 23a59d6d81..8713ed494d 100644 --- a/qiskit_aer/noise/passes/local_noise_pass.py +++ b/qiskit_aer/noise/passes/local_noise_pass.py @@ -109,9 +109,7 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: continue if isinstance(new_op, ReadoutError): - raise TranspilerError( - "Insertions of ReadoutError is not yet supported." - ) + raise TranspilerError("Insertions of ReadoutError is not yet supported.") # Initialize new node dag new_dag = DAGCircuit() @@ -120,9 +118,7 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: # If appending re-apply original op node first if self._method == "append": - new_dag.apply_operation_back( - node.op, qargs=node.qargs, cargs=node.cargs - ) + new_dag.apply_operation_back(node.op, qargs=node.qargs, cargs=node.cargs) # If the new op is not a QuantumCircuit or Instruction, attempt # to conver to an Instruction @@ -148,20 +144,14 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: if isinstance(new_op, QuantumCircuit): # If the new op is a quantum circuit, compose its DAG with the new dag # so that it is unrolled rather than added as an opaque instruction - new_dag.compose( - circuit_to_dag(new_op), qubits=node.qargs - ) # never touch clbits + new_dag.compose(circuit_to_dag(new_op), qubits=node.qargs) # never touch clbits else: # Otherwise append the instruction returned by the function - new_dag.apply_operation_back( - new_op, qargs=node.qargs - ) # never touch cargs + new_dag.apply_operation_back(new_op, qargs=node.qargs) # never touch cargs # If prepending reapply original op node last if self._method == "prepend": - new_dag.apply_operation_back( - node.op, qargs=node.qargs, cargs=node.cargs - ) + new_dag.apply_operation_back(node.op, qargs=node.qargs, cargs=node.cargs) dag.substitute_node_with_dag(node, new_dag) diff --git a/qiskit_aer/noise/passes/relaxation_noise_pass.py b/qiskit_aer/noise/passes/relaxation_noise_pass.py index 32e5accbaf..d2bf6159bc 100644 --- a/qiskit_aer/noise/passes/relaxation_noise_pass.py +++ b/qiskit_aer/noise/passes/relaxation_noise_pass.py @@ -55,9 +55,7 @@ def __init__( else: self._p1s = np.zeros(len(t1s)) self._dt = dt - super().__init__( - self._thermal_relaxation_error, op_types=op_types, method="append" - ) + super().__init__(self._thermal_relaxation_error, op_types=op_types, method="append") def _thermal_relaxation_error(self, op: Instruction, qubits: Sequence[int]): """Return thermal relaxation error on each operand qubit""" diff --git a/qiskit_aer/primitives/estimator.py b/qiskit_aer/primitives/estimator.py index cbbc45ed3a..157f83b6b5 100644 --- a/qiskit_aer/primitives/estimator.py +++ b/qiskit_aer/primitives/estimator.py @@ -83,9 +83,7 @@ def __init__( backend_options = {} if backend_options is None else backend_options method = ( - "density_matrix" - if approximation and "noise_model" in backend_options - else "automatic" + "density_matrix" if approximation and "noise_model" in backend_options else "automatic" ) self._backend = AerSimulator(method=method) self._backend.set_options(**backend_options) @@ -144,16 +142,10 @@ def _run( observable_indices.append(index) else: observable_indices.append(len(self._observables)) - self._observable_ids[_observable_key(observable)] = len( - self._observables - ) + self._observable_ids[_observable_key(observable)] = len(self._observables) self._observables.append(observable) job = PrimitiveJob( - self._call, - circuit_indices, - observable_indices, - parameter_values, - **run_options, + self._call, circuit_indices, observable_indices, parameter_values, **run_options ) job.submit() return job @@ -165,9 +157,7 @@ def _compute(self, circuits, observables, parameter_values, run_options): # Create expectation value experiments. if key in self._cache: # Use a cache experiments_dict, obs_maps = self._cache[key] - exp_map = self._pre_process_params( - circuits, observables, parameter_values, obs_maps - ) + exp_map = self._pre_process_params(circuits, observables, parameter_values, obs_maps) experiments, parameter_binds = self._flatten(experiments_dict, exp_map) post_processings = self._create_post_processing( circuits, observables, parameter_values, obs_maps, exp_map @@ -179,9 +169,7 @@ def _compute(self, circuits, observables, parameter_values, run_options): for circ_ind, obs_ind in zip(circuits, observables): circ_obs_map[circ_ind].append(obs_ind) experiments_dict = {} - obs_maps = ( - {} - ) # circ_ind => obs_ind => term_ind (Original Pauli) => basis_ind + obs_maps = {} # circ_ind => obs_ind => term_ind (Original Pauli) => basis_ind # Group and create measurement circuit for circ_ind, obs_indices in circ_obs_map.items(): pauli_list = sum( @@ -200,13 +188,9 @@ def _compute(self, circuits, observables, parameter_values, run_options): break obs_maps[circ_ind] = obs_map bases = [_paulis2basis(pauli_list) for pauli_list in pauli_lists] - if ( - len(bases) == 1 and not bases[0].x.any() and not bases[0].z.any() - ): # identity + if len(bases) == 1 and not bases[0].x.any() and not bases[0].z.any(): # identity break - meas_circuits = [ - self._create_meas_circuit(basis, circ_ind) for basis in bases - ] + meas_circuits = [self._create_meas_circuit(basis, circ_ind) for basis in bases] circuit = ( self._circuits[circ_ind] if self._skip_transpilation @@ -215,9 +199,7 @@ def _compute(self, circuits, observables, parameter_values, run_options): experiments_dict[circ_ind] = self._combine_circs(circuit, meas_circuits) self._cache[key] = experiments_dict, obs_maps - exp_map = self._pre_process_params( - circuits, observables, parameter_values, obs_maps - ) + exp_map = self._pre_process_params(circuits, observables, parameter_values, obs_maps) # Flatten experiments, parameter_binds = self._flatten(experiments_dict, exp_map) @@ -248,12 +230,8 @@ def _compute(self, circuits, observables, parameter_values, run_options): return EstimatorResult(np.real_if_close(expectation_values), list(metadata)) def _pre_process_params(self, circuits, observables, parameter_values, obs_maps): - exp_map = defaultdict( - dict - ) # circ_ind => basis_ind => (parameter, parameter_values) - for circ_ind, obs_ind, param_val in zip( - circuits, observables, parameter_values - ): + exp_map = defaultdict(dict) # circ_ind => basis_ind => (parameter, parameter_values) + for circ_ind, obs_ind, param_val in zip(circuits, observables, parameter_values): self._validate_parameter_length(param_val, circ_ind) parameter = self._parameters[circ_ind] for basis_ind in obs_maps[circ_ind][obs_ind]: @@ -316,9 +294,7 @@ def _combine_circs(circuit: QuantumCircuit, meas_circuits: list[QuantumCircuit]) return circs @staticmethod - def _calculate_result_index( - circ_ind, obs_ind, term_ind, param_val, obs_maps, exp_map - ) -> int: + def _calculate_result_index(circ_ind, obs_ind, term_ind, param_val, obs_maps, exp_map) -> int: basis_ind = obs_maps[circ_ind][obs_ind][term_ind] result_index = 0 @@ -336,16 +312,12 @@ def _create_post_processing( self, circuits, observables, parameter_values, obs_maps, exp_map ) -> list[_PostProcessing]: post_processings = [] - for circ_ind, obs_ind, param_val in zip( - circuits, observables, parameter_values - ): + for circ_ind, obs_ind, param_val in zip(circuits, observables, parameter_values): result_indices: list[int | None] = [] paulis = [] coeffs = [] observable = self._observables[obs_ind] - for term_ind, (pauli, coeff) in enumerate( - zip(observable.paulis, observable.coeffs) - ): + for term_ind, (pauli, coeff) in enumerate(zip(observable.paulis, observable.coeffs)): # Identity if not pauli.x.any() and not pauli.z.any(): result_indices.append(None) @@ -379,9 +351,7 @@ def _compute_with_approximation( experiments, experiment_data = self._cache[key] for i, j, value in zip(circuits, observables, parameter_values): self._validate_parameter_length(value, i) - parameter_binds.append( - {k: [v] for k, v in zip(self._parameters[i], value)} - ) + parameter_binds.append({k: [v] for k, v in zip(self._parameters[i], value)}) else: self._transpile_circuits(circuits) experiments = [] @@ -399,13 +369,9 @@ def _compute_with_approximation( circuit.save_expectation_value(observable, self._layouts[i]) else: for term_ind, pauli in enumerate(observable.paulis): - circuit.save_expectation_value( - pauli, self._layouts[i], label=str(term_ind) - ) + circuit.save_expectation_value(pauli, self._layouts[i], label=str(term_ind)) experiments.append(circuit) - parameter_binds.append( - {k: [v] for k, v in zip(self._parameters[i], value)} - ) + parameter_binds.append({k: [v] for k, v in zip(self._parameters[i], value)}) self._cache[key] = (experiments, experiment_data) parameter_binds = parameter_binds if any(parameter_binds) else None result = self._backend.run( @@ -414,12 +380,9 @@ def _compute_with_approximation( # Post processing (calculate expectation values) if shots is None: - expectation_values = [ - result.data(i)["expectation_value"] for i in range(len(circuits)) - ] + expectation_values = [result.data(i)["expectation_value"] for i in range(len(circuits))] metadata = [ - {"simulator_metadata": result.results[i].metadata} - for i in range(len(experiments)) + {"simulator_metadata": result.results[i].metadata} for i in range(len(experiments)) ] else: expectation_values = [] @@ -494,10 +457,7 @@ def _expval_with_variance(counts) -> tuple[float, float]: class _PostProcessing: def __init__( - self, - result_indices: list[int], - paulis: list[PauliList], - coeffs: list[list[float]], + self, result_indices: list[int], paulis: list[PauliList], coeffs: list[list[float]] ): self._result_indices = result_indices self._paulis = paulis @@ -515,14 +475,10 @@ def run(self, results: list[ExperimentResult]) -> tuple[float, dict]: combined_expval = 0.0 combined_var = 0.0 simulator_metadata = [] - for c_i, paulis, coeffs in zip( - self._result_indices, self._paulis, self._coeffs - ): + for c_i, paulis, coeffs in zip(self._result_indices, self._paulis, self._coeffs): if c_i is None: # Observable is identity - expvals, variances = np.array([1], dtype=complex), np.array( - [0], dtype=complex - ) + expvals, variances = np.array([1], dtype=complex), np.array([0], dtype=complex) shots = 0 else: result = results[c_i] @@ -553,9 +509,7 @@ def _update_metadata(circuit: QuantumCircuit, metadata: dict) -> QuantumCircuit: return circuit -def _pauli_expval_with_variance( - counts: dict, paulis: PauliList -) -> tuple[np.ndarray, np.ndarray]: +def _pauli_expval_with_variance(counts: dict, paulis: PauliList) -> tuple[np.ndarray, np.ndarray]: # Diag indices size = len(paulis) diag_inds = _paulis2inds(paulis) @@ -578,9 +532,7 @@ def _pauli_expval_with_variance( def _paulis2inds(paulis: PauliList) -> list[int]: nonid = paulis.z | paulis.x - packed_vals = np.packbits( - nonid, axis=1, bitorder="little" - ).astype( # pylint:disable=no-member + packed_vals = np.packbits(nonid, axis=1, bitorder="little").astype( # pylint:disable=no-member object ) power_uint8 = 1 << (8 * np.arange(packed_vals.shape[1], dtype=object)) diff --git a/qiskit_aer/primitives/sampler.py b/qiskit_aer/primitives/sampler.py index d87a93b3d6..e1b75cef39 100644 --- a/qiskit_aer/primitives/sampler.py +++ b/qiskit_aer/primitives/sampler.py @@ -118,9 +118,7 @@ def _call( {f"{k:0{num_qubits}b}": v for k, v in probabilities.items()} ) quasis.append(quasi_dist) - metadata.append( - {"shots": None, "simulator_metadata": result.results[i].metadata} - ) + metadata.append({"shots": None, "simulator_metadata": result.results[i].metadata}) else: counts = result.get_counts(i) shots = sum(counts.values()) @@ -130,9 +128,7 @@ def _call( shots=shots, ) ) - metadata.append( - {"shots": shots, "simulator_metadata": result.results[i].metadata} - ) + metadata.append({"shots": shots, "simulator_metadata": result.results[i].metadata}) return SamplerResult(quasis, metadata) @@ -183,9 +179,7 @@ def _preprocess_circuit(circuit: QuantumCircuit): def _transpile(self, circuit_indices: Sequence[int], is_shots_none: bool): to_handle = [ - i - for i in set(circuit_indices) - if (i, is_shots_none) not in self._transpiled_circuits + i for i in set(circuit_indices) if (i, is_shots_none) not in self._transpiled_circuits ] if to_handle: circuits = (self._circuits[i] for i in to_handle) diff --git a/qiskit_aer/pulse/controllers/digest_pulse_qobj.py b/qiskit_aer/pulse/controllers/digest_pulse_qobj.py index 6c231c29da..ea278a2b84 100644 --- a/qiskit_aer/pulse/controllers/digest_pulse_qobj.py +++ b/qiskit_aer/pulse/controllers/digest_pulse_qobj.py @@ -90,9 +90,7 @@ def digest_pulse_qobj(qobj, channels, dt, qubit_list): # extract schedule_los if qobj_config.get("schedule_los") is not None: - for exp, schedule_lo in zip( - qobj_dict["experiments"], qobj_config["schedule_los"] - ): + for exp, schedule_lo in zip(qobj_dict["experiments"], qobj_config["schedule_los"]): if exp.get("config") is None: exp["config"] = {} @@ -126,9 +124,7 @@ def digest_pulse_qobj(qobj, channels, dt, qubit_list): # set qubit_lo_freq as given in qobj if "qubit_lo_freq" in qobj_config and qobj_config["qubit_lo_freq"] != [np.inf]: # qobj frequencies are divided by 1e9, so multiply back - digested_qobj.qubit_lo_freq = [ - freq * 1e9 for freq in qobj_config["qubit_lo_freq"] - ] + digested_qobj.qubit_lo_freq = [freq * 1e9 for freq in qobj_config["qubit_lo_freq"]] # build pulse arrays from qobj pulses, pulses_idx, pulse_dict = build_pulse_arrays( @@ -142,9 +138,7 @@ def digest_pulse_qobj(qobj, channels, dt, qubit_list): experiments = [] for exp in qobj_dict["experiments"]: - exp_struct = experiment_to_structs( - exp, channels, pulses_idx, pulse_dict, dt, qubit_list - ) + exp_struct = experiment_to_structs(exp, channels, pulses_idx, pulse_dict, dt, qubit_list) experiments.append(exp_struct) digested_qobj.experiments = experiments @@ -163,9 +157,7 @@ def _unsupported_errors(qobj_dict): """ # Warnings that don't stop execution - warning_str = ( - "{} are an untested feature, and therefore may not behave as expected." - ) + warning_str = "{} are an untested feature, and therefore may not behave as expected." if _contains_pv_instruction(qobj_dict["experiments"]): raise AerError(warning_str.format("PersistentValue instructions")) @@ -176,9 +168,7 @@ def _unsupported_errors(qobj_dict): error_str = """Schedules contain {}, are not supported by PulseSimulator.""" if _contains_frequency_instruction(qobj_dict["experiments"]): - raise AerError( - error_str.format("shift frequency and/or set frequency instructions") - ) + raise AerError(error_str.format("shift frequency and/or set frequency instructions")) required_str = "{} are required for simulation, and none were specified." if not _contains_acquire_instruction(qobj_dict["experiments"]): @@ -279,10 +269,7 @@ def build_pulse_arrays(experiments, pulse_library): for exp in experiments: for pulse in exp["instructions"]: if pulse["name"] == "pv": - if ( - pulse["val"] not in [pval[1] for pval in pv_pulses] - and pulse["val"] != 0 - ): + if pulse["val"] not in [pval[1] for pval in pv_pulses] and pulse["val"] != 0: pv_pulses.append((pulse["val"], idx)) idx += 1 total_pulse_length += 1 @@ -297,9 +284,7 @@ def build_pulse_arrays(experiments, pulse_library): for _, pulse in enumerate(pulse_library): stop = pulses_idx[ind - 1] + len(pulse["samples"]) pulses_idx[ind] = stop - oplist_to_array( - format_pulse_samples(pulse["samples"]), pulses, pulses_idx[ind - 1] - ) + oplist_to_array(format_pulse_samples(pulse["samples"]), pulses, pulses_idx[ind - 1]) ind += 1 for pv in pv_pulses: @@ -333,9 +318,7 @@ def format_pulse_samples(pulse_samples): return [[samp.real, samp.imag] for samp in new_samples] -def experiment_to_structs( - experiment, ham_chans, pulse_inds, pulse_to_int, dt, qubit_list=None -): +def experiment_to_structs(experiment, ham_chans, pulse_inds, pulse_to_int, dt, qubit_list=None): """Converts an experiment to a better formatted structure Args: @@ -387,9 +370,7 @@ def experiment_to_structs( if "ch" in inst.keys() and inst["ch"][0] in ["d", "u"]: chan_name = inst["ch"].upper() if chan_name not in ham_chans.keys(): - raise ValueError( - "Channel {} is not in Hamiltonian model".format(inst["ch"]) - ) + raise ValueError("Channel {} is not in Hamiltonian model".format(inst["ch"])) # If last pulse on channel was a PV then need to set # its final time to be start time of current pulse @@ -409,9 +390,7 @@ def experiment_to_structs( if pv[0] == inst["val"]: index = pv[1] break - structs["channels"][chan_name][0].extend( - [inst["t0"] * dt, None, index, cond] - ) + structs["channels"][chan_name][0].extend([inst["t0"] * dt, None, index, cond]) pv_needs_tf[ham_chans[chan_name]] = 1 # ShiftPhase instructions @@ -427,9 +406,7 @@ def experiment_to_structs( # SetPhase instruction elif inst["name"] == "setp": - structs["channels"][chan_name][1].extend( - [inst["t0"] * dt, inst["phase"], cond] - ) + structs["channels"][chan_name][1].extend([inst["t0"] * dt, inst["phase"], cond]) # Delay instruction elif inst["name"] == "delay": pass # nothing to be done in this case @@ -523,12 +500,8 @@ def experiment_to_structs( # Convert lists to numpy arrays for key in structs["channels"].keys(): - structs["channels"][key][0] = np.asarray( - structs["channels"][key][0], dtype=float - ) - structs["channels"][key][1] = np.asarray( - structs["channels"][key][1], dtype=float - ) + structs["channels"][key][0] = np.asarray(structs["channels"][key][0], dtype=float) + structs["channels"][key][1] = np.asarray(structs["channels"][key][1], dtype=float) structs["tlist"] = np.asarray([0] + structs["tlist"], dtype=float) diff --git a/qiskit_aer/pulse/controllers/mc_controller.py b/qiskit_aer/pulse/controllers/mc_controller.py index e53bdc1ca4..00e14d7f84 100644 --- a/qiskit_aer/pulse/controllers/mc_controller.py +++ b/qiskit_aer/pulse/controllers/mc_controller.py @@ -88,7 +88,7 @@ def run_monte_carlo_experiments(pulse_sim_desc, pulse_de_model, solver_options=N pulse_de_model, solver_options, ), - **map_kwargs + **map_kwargs, ) # exp_results is a list for each shot @@ -104,9 +104,7 @@ def run_monte_carlo_experiments(pulse_sim_desc, pulse_de_model, solver_options=N return exp_results, exp_times -def monte_carlo_evolution( - seed, exp, y0, pulse_sim_desc, pulse_de_model, solver_options=None -): +def monte_carlo_evolution(seed, exp, y0, pulse_sim_desc, pulse_de_model, solver_options=None): """Performs a single monte carlo run for the given op_system, experiment, and seed Parameters: @@ -177,10 +175,7 @@ def monte_carlo_evolution( if not ODE.successful(): raise Exception("Integration failed after adjusting step size!") norm2_guess = dznrm2(ODE.y) ** 2 - if ( - abs(rand_vals[0] - norm2_guess) - < solver_options.norm_tol * rand_vals[0] - ): + if abs(rand_vals[0] - norm2_guess) < solver_options.norm_tol * rand_vals[0]: break if norm2_guess < rand_vals[0]: @@ -222,9 +217,7 @@ def monte_carlo_evolution( current_acq = exp["acquire"][aind] qubits = current_acq[1] memory_slots = current_acq[2] - probs = occ_probabilities( - qubits, out_psi, pulse_sim_desc.measurement_ops - ) + probs = occ_probabilities(qubits, out_psi, pulse_sim_desc.measurement_ops) rand_vals = rng.rand(memory_slots.shape[0]) write_shots_memory(memory, memory_slots, probs, rand_vals) acq_idx += 1 diff --git a/qiskit_aer/pulse/controllers/pulse_controller.py b/qiskit_aer/pulse/controllers/pulse_controller.py index 0870dcd299..74b4e8ff40 100644 --- a/qiskit_aer/pulse/controllers/pulse_controller.py +++ b/qiskit_aer/pulse/controllers/pulse_controller.py @@ -108,9 +108,7 @@ def pulse_controller(qobj): # ############################### # ### Parse qobj_config settings # ############################### - digested_qobj = digest_pulse_qobj( - qobj, pulse_de_model.channels, system_model.dt, qubit_list - ) + digested_qobj = digest_pulse_qobj(qobj, pulse_de_model.channels, system_model.dt, qubit_list) # extract simulation-description level qobj content pulse_sim_desc.shots = digested_qobj.shots @@ -145,12 +143,8 @@ def pulse_controller(qobj): "so it is being automatically determined from the drift Hamiltonian." ) - pulse_de_model.freqs = system_model.calculate_channel_frequencies( - qubit_lo_freq=qubit_lo_freq - ) - pulse_de_model.calculate_channel_frequencies = ( - system_model.calculate_channel_frequencies - ) + pulse_de_model.freqs = system_model.calculate_channel_frequencies(qubit_lo_freq=qubit_lo_freq) + pulse_de_model.calculate_channel_frequencies = system_model.calculate_channel_frequencies # ############################### # ### Parse backend_options @@ -207,11 +201,7 @@ def pulse_controller(qobj): pulse_sim_desc.measurement_ops[ qubit_list.index(jj) ] = op_gen.qubit_occ_oper_dressed( - jj, - estates, - h_osc=dim_osc, - h_qub=dim_qub, - level=q_level_meas, + jj, estates, h_osc=dim_osc, h_qub=dim_qub, level=q_level_meas ) if not exp["can_sample"]: @@ -225,13 +215,9 @@ def pulse_controller(qobj): pulse_sim_desc.measurement_ops = meas_ops_reduced run_experiments = ( - run_unitary_experiments - if pulse_sim_desc.can_sample - else run_monte_carlo_experiments - ) - exp_results, exp_times = run_experiments( - pulse_sim_desc, pulse_de_model, solver_options + run_unitary_experiments if pulse_sim_desc.can_sample else run_monte_carlo_experiments ) + exp_results, exp_times = run_experiments(pulse_sim_desc, pulse_de_model, solver_options) output = { "results": format_exp_results(exp_results, exp_times, pulse_sim_desc), @@ -311,9 +297,7 @@ def format_exp_results(exp_results, exp_times, pulse_sim_desc): for mem_shot in memory: results["data"]["memory"].append([]) for mem_slot in mem_shot: - results["data"]["memory"][-1].append( - [np.real(mem_slot), np.imag(mem_slot)] - ) + results["data"]["memory"][-1].append([np.real(mem_slot), np.imag(mem_slot)]) if m_ret == "avg": results["data"]["memory"] = results["data"]["memory"][0] @@ -333,9 +317,7 @@ def _unsupported_warnings(noise_model): """ # Warnings that don't stop execution - warning_str = ( - "{} are an untested feature, and therefore may not behave as expected." - ) + warning_str = "{} are an untested feature, and therefore may not behave as expected." if noise_model is not None: warn(warning_str.format("Noise models")) @@ -452,12 +434,8 @@ def init_rhs(self, exp): # Init register register = np.ones(self.n_registers, dtype=np.uint8) - rhs_dict = setup_rhs_dict_freqs( - self._rhs_dict, exp, self.calculate_channel_frequencies - ) - ode_rhs_obj = get_ode_rhs_functor( - rhs_dict, exp, self.system, channels, register - ) + rhs_dict = setup_rhs_dict_freqs(self._rhs_dict, exp, self.calculate_channel_frequencies) + ode_rhs_obj = get_ode_rhs_functor(rhs_dict, exp, self.system, channels, register) def rhs(t, y): return ode_rhs_obj(t, y) diff --git a/qiskit_aer/pulse/controllers/unitary_controller.py b/qiskit_aer/pulse/controllers/unitary_controller.py index 002a7218e2..29a8afb8e5 100644 --- a/qiskit_aer/pulse/controllers/unitary_controller.py +++ b/qiskit_aer/pulse/controllers/unitary_controller.py @@ -110,13 +110,11 @@ def run_unitary_experiments(pulse_sim_desc, pulse_de_model, solver_options=None) pulse_de_model, solver_options, ), - **map_kwargs + **map_kwargs, ) end = time.time() exp_times = ( - np.ones(len(pulse_sim_desc.experiments)) - * (end - start) - / len(pulse_sim_desc.experiments) + np.ones(len(pulse_sim_desc.experiments)) * (end - start) / len(pulse_sim_desc.experiments) ) return exp_results, exp_times diff --git a/qiskit_aer/pulse/de/DE_Methods.py b/qiskit_aer/pulse/de/DE_Methods.py index 0489e08cc8..812cd53618 100644 --- a/qiskit_aer/pulse/de/DE_Methods.py +++ b/qiskit_aer/pulse/de/DE_Methods.py @@ -114,8 +114,8 @@ def set_y(self, new_y, reset=True): # instantiate internal StateTypeConverter based on the provided new_y and the # general type required internally by the solver type_spec = self.method_spec.get("inner_state_spec") - self._state_type_converter = ( - StateTypeConverter.from_outer_instance_inner_type_spec(new_y, type_spec) + self._state_type_converter = StateTypeConverter.from_outer_instance_inner_type_spec( + new_y, type_spec ) # set internal state @@ -143,9 +143,7 @@ def set_rhs(self, rhs=None, reset=True): rhs = {"rhs": rhs} if "rhs" not in rhs: - raise Exception( - "ODE_Method requires at minimum a specification of an rhs function." - ) + raise Exception("ODE_Method requires at minimum a specification of an rhs function.") # transform rhs function into a function that accepts/returns inner state type self.rhs = self._state_type_converter.transform_rhs_funcs(rhs) @@ -220,7 +218,7 @@ def integrate(self, tf, **kwargs): max_step=self.options.max_step, min_step=self.options.min_step, first_step=self.options.first_step, - **kwargs + **kwargs, ) # update the internal state @@ -265,9 +263,7 @@ class QiskitZVODE(ODE_Method): def __init__(self, t0=None, y0=None, rhs=None, options=None): # all de specification arguments are necessary to instantiate scipy ode object if (t0 is None) or (y0 is None) or (rhs is None): - raise Exception( - "QiskitZVODE solver requires t0, y0, and rhs at instantiation." - ) + raise Exception("QiskitZVODE solver requires t0, y0, and rhs at instantiation.") # initialize internal attribute for storing scipy ode object self._ODE = None @@ -287,8 +283,8 @@ def t(self, new_t): def set_y(self, new_y, reset=True): """Method for logic of setting internal state of solver with more control""" type_spec = self.method_spec.get("inner_state_spec") - self._state_type_converter = ( - StateTypeConverter.from_outer_instance_inner_type_spec(new_y, type_spec) + self._state_type_converter = StateTypeConverter.from_outer_instance_inner_type_spec( + new_y, type_spec ) self._y = self._state_type_converter.outer_to_inner(new_y) @@ -308,9 +304,7 @@ def set_rhs(self, rhs=None, reset=True): rhs = {"rhs": rhs} if "rhs" not in rhs: - raise Exception( - "ODE_Method requires at minimum a specification of an rhs function." - ) + raise Exception("ODE_Method requires at minimum a specification of an rhs function.") self.rhs = self._state_type_converter.transform_rhs_funcs(rhs) diff --git a/qiskit_aer/pulse/de/type_utils.py b/qiskit_aer/pulse/de/type_utils.py index 568b36794b..e445c81df1 100644 --- a/qiskit_aer/pulse/de/type_utils.py +++ b/qiskit_aer/pulse/de/type_utils.py @@ -43,9 +43,7 @@ def __init__(self, inner_type_spec, outer_type_spec=None): self.inner_type_spec = inner_type_spec - self.outer_type_spec = ( - self.inner_type_spec if outer_type_spec is None else outer_type_spec - ) + self.outer_type_spec = self.inner_type_spec if outer_type_spec is None else outer_type_spec @classmethod def from_instances(cls, inner_y, outer_y=None): diff --git a/qiskit_aer/pulse/system_models/duffing_model_generators.py b/qiskit_aer/pulse/system_models/duffing_model_generators.py index 94fa372519..fd1cc09039 100644 --- a/qiskit_aer/pulse/system_models/duffing_model_generators.py +++ b/qiskit_aer/pulse/system_models/duffing_model_generators.py @@ -148,9 +148,7 @@ def duffing_system_model( edge_strength = coupling_dict.get((edge[1], edge[0])) coupling_strengths.append(edge_strength) - coupling_symbols = _str_list_generator( - coupling_symbol + "{0}{1}", *zip(*sorted_coupling_edges) - ) + coupling_symbols = _str_list_generator(coupling_symbol + "{0}{1}", *zip(*sorted_coupling_edges)) cr_idx_dict = coupling_graph.two_way_graph_dict hamiltonian_dict = _duffing_hamiltonian_dict( @@ -234,25 +232,19 @@ def _duffing_hamiltonian_dict( """ # single oscillator terms - hamiltonian_str = _single_duffing_drift_terms( - freq_symbols, anharm_symbols, oscillators - ) + hamiltonian_str = _single_duffing_drift_terms(freq_symbols, anharm_symbols, oscillators) hamiltonian_str += _drive_terms(drive_symbols, oscillators) # exchange terms if len(ordered_coupling_edges) > 0: - hamiltonian_str += _exchange_coupling_terms( - coupling_symbols, ordered_coupling_edges - ) + hamiltonian_str += _exchange_coupling_terms(coupling_symbols, ordered_coupling_edges) # cr terms if len(cr_idx_dict) > 0: driven_system_indices = [key[0] for key in cr_idx_dict.keys()] cr_drive_symbols = [drive_symbols[idx] for idx in driven_system_indices] cr_channel_idx = cr_idx_dict.values() - hamiltonian_str += _cr_terms( - cr_drive_symbols, driven_system_indices, cr_channel_idx - ) + hamiltonian_str += _cr_terms(cr_drive_symbols, driven_system_indices, cr_channel_idx) # construct vars dictionary var_dict = {} @@ -265,9 +257,7 @@ def _duffing_hamiltonian_dict( for symbol, strength in zip(coupling_symbols, coupling_strengths): var_dict[symbol] = strength - dim_dict = { - str(oscillator): dim for oscillator, dim in zip(oscillators, oscillator_dims) - } + dim_dict = {str(oscillator): dim for oscillator, dim in zip(oscillators, oscillator_dims)} return {"h_str": hamiltonian_str, "vars": var_dict, "qub": dim_dict} @@ -311,9 +301,7 @@ def _single_duffing_drift_terms(freq_symbols, anharm_symbols, system_list): harm_terms = _str_list_generator( "np.pi*(2*{0}-{1})*O{2}", freq_symbols, anharm_symbols, system_list ) - anharm_terms = _str_list_generator( - "np.pi*{0}*O{1}*O{1}", anharm_symbols, system_list - ) + anharm_terms = _str_list_generator("np.pi*{0}*O{1}*O{1}", anharm_symbols, system_list) return harm_terms + anharm_terms @@ -360,10 +348,7 @@ def _cr_terms(drive_symbols, driven_system_indices, u_channel_indices): """ return _str_list_generator( - "2*np.pi*{0}*X{1}||U{2}", - drive_symbols, - driven_system_indices, - u_channel_indices, + "2*np.pi*{0}*X{1}||U{2}", drive_symbols, driven_system_indices, u_channel_indices ) @@ -465,8 +450,7 @@ def __init__(self, edges): # create the dictionary version self.two_way_graph_dict = { - self.sorted_two_way_graph[k]: k - for k in range(len(self.sorted_two_way_graph)) + self.sorted_two_way_graph[k]: k for k in range(len(self.sorted_two_way_graph)) } def sorted_edge_index(self, edge): diff --git a/qiskit_aer/pulse/system_models/hamiltonian_model.py b/qiskit_aer/pulse/system_models/hamiltonian_model.py index 2da28b8b34..90978b3419 100644 --- a/qiskit_aer/pulse/system_models/hamiltonian_model.py +++ b/qiskit_aer/pulse/system_models/hamiltonian_model.py @@ -101,9 +101,7 @@ def from_dict(cls, hamiltonian, subsystem_list=None): # force keys in hamiltonian['qub'] to be ints qub_dict = {int(key): val for key, val in hamiltonian["qub"].items()} - subsystem_dims = { - int(qubit): qub_dict[int(qubit)] for qubit in subsystem_list - } + subsystem_dims = {int(qubit): qub_dict[int(qubit)] for qubit in subsystem_list} else: subsystem_dims = {} @@ -140,9 +138,7 @@ def get_qubit_lo_from_drift(self): min_eval = np.min(self._evals) for q_idx in self._subsystem_dims.keys(): single_excite = _first_excited_state(q_idx, self._subsystem_dims) - dressed_eval = _eval_for_max_espace_overlap( - single_excite, self._evals, self._estates - ) + dressed_eval = _eval_for_max_espace_overlap(single_excite, self._evals, self._estates) qubit_lo_freq[q_idx] = (dressed_eval - min_eval) / (2 * np.pi) return qubit_lo_freq @@ -159,9 +155,7 @@ def _calculate_hamiltonian_channels(self): chan_idx = [i for i, letter in enumerate(ham_str) if letter in ["D", "U"]] for ch in chan_idx: if (ch + 1) == len(ham_str) or not ham_str[ch + 1].isdigit(): - raise Exception( - "Channel name must include" + "an integer labeling the qubit." - ) + raise Exception("Channel name must include" + "an integer labeling the qubit.") for kk in chan_idx: done = False offset = 0 @@ -249,9 +243,7 @@ def _hamiltonian_pre_parse_exceptions(hamiltonian): raise AerError("Hamiltonian dict requires a non-empty 'h_str' entry.") if hamiltonian.get("qub", {}) == {}: - raise AerError( - "Hamiltonian dict requires non-empty 'qub' entry with subsystem dimensions." - ) + raise AerError("Hamiltonian dict requires non-empty 'qub' entry with subsystem dimensions.") if hamiltonian.get("osc", {}) != {}: raise AerError("Oscillator-type systems are not supported.") diff --git a/qiskit_aer/pulse/system_models/pulse_system_model.py b/qiskit_aer/pulse/system_models/pulse_system_model.py index 45cdac74cd..c4741d991f 100644 --- a/qiskit_aer/pulse/system_models/pulse_system_model.py +++ b/qiskit_aer/pulse/system_models/pulse_system_model.py @@ -152,10 +152,7 @@ def from_config(cls, configuration, subsystem_list=None): u_string += str(scale) + "q" + str(q_idx) else: u_string += str(scale[0] + scale[1] * 1j) + "q" + str(q_idx) - control_channel_labels[u_idx] = { - "driven_q": drive_idx, - "freq": u_string, - } + control_channel_labels[u_idx] = {"driven_q": drive_idx, "freq": u_string} return cls( hamiltonian=hamiltonian, diff --git a/qiskit_aer/pulse/system_models/string_model_parser/operator_from_string.py b/qiskit_aer/pulse/system_models/string_model_parser/operator_from_string.py index e20dd810dd..16a8509cf3 100644 --- a/qiskit_aer/pulse/system_models/string_model_parser/operator_from_string.py +++ b/qiskit_aer/pulse/system_models/string_model_parser/operator_from_string.py @@ -43,9 +43,7 @@ def gen_oper(opname, index, h_osc, h_qub, states=None): if opname == "X": opr_tmp = op_gen.get_oper("A", dim) + op_gen.get_oper("C", dim) elif opname == "Y": - opr_tmp = -1j * op_gen.get_oper("A", dim) + 1j * op_gen.get_oper( - "C", dim - ) + opr_tmp = -1j * op_gen.get_oper("A", dim) + 1j * op_gen.get_oper("C", dim) else: opr_tmp = op_gen.get_oper("I", dim) - 2 * op_gen.get_oper("N", dim) diff --git a/qiskit_aer/pulse/system_models/string_model_parser/operator_generators.py b/qiskit_aer/pulse/system_models/string_model_parser/operator_generators.py index 33c3edf7f9..755100d146 100644 --- a/qiskit_aer/pulse/system_models/string_model_parser/operator_generators.py +++ b/qiskit_aer/pulse/system_models/string_model_parser/operator_generators.py @@ -80,9 +80,7 @@ def project(dim, states): if ket in range(dim) and bra in range(dim): return gen_operator.basis(dim, ket) * gen_operator.basis(dim, bra).adjoint() else: - raise Exception( - "States are specified on the outside of Hilbert space %s" % states - ) + raise Exception("States are specified on the outside of Hilbert space %s" % states) def tensor(list_qobj): diff --git a/qiskit_aer/pulse/system_models/string_model_parser/string_model_parser.py b/qiskit_aer/pulse/system_models/string_model_parser/string_model_parser.py index 6396b8ee08..7b3337fca1 100644 --- a/qiskit_aer/pulse/system_models/string_model_parser/string_model_parser.py +++ b/qiskit_aer/pulse/system_models/string_model_parser/string_model_parser.py @@ -107,9 +107,7 @@ def parse(self, qubit_list=None): def _expand_sum(self): """Takes a string-based Hamiltonian list and expands the _SUM action items out.""" - sum_str = re.compile( - r"_SUM\[(?P[a-z]),(?P[a-z\d{}+-]+),(?P[a-z\d{}+-]+)," - ) + sum_str = re.compile(r"_SUM\[(?P[a-z]),(?P[a-z\d{}+-]+),(?P[a-z\d{}+-]+),") brk_str = re.compile(r"]") ham_list = copy.copy(self.h_str) @@ -143,9 +141,7 @@ def _expand_sum(self): pattern = {} for p in re.finditer(r"\{(?P[a-z0-9*/+-]+)\}", trg_s): if p.group() not in pattern: - sub = parse_binop( - p.group("op_str"), operands={itr: str(kk)} - ) + sub = parse_binop(p.group("op_str"), operands={itr: str(kk)}) if sub.isdecimal(): pattern[p.group()] = sub else: @@ -153,9 +149,7 @@ def _expand_sum(self): for key, val in pattern.items(): trg_s = trg_s.replace(key, val) _temp.append( - "".join( - [ham[: p_sums[0].start()], trg_s, ham[p_brks[ii].end() :]] - ) + "".join([ham[: p_sums[0].start()], trg_s, ham[p_brks[ii].end() :]]) ) ham_list.extend(_temp) @@ -225,9 +219,7 @@ def _tokenizer(self, op_str, qubit_list=None): token_list = token_list[ii + 1 :] break else: - raise Exception( - "Invalid order of operators and coefficients in %s" % op_str - ) + raise Exception("Invalid order of operators and coefficients in %s" % op_str) return coef, token_list diff --git a/qiskit_aer/quantum_info/states/aer_densitymatrix.py b/qiskit_aer/quantum_info/states/aer_densitymatrix.py index 5a87667b62..6bc4ce45c4 100644 --- a/qiskit_aer/quantum_info/states/aer_densitymatrix.py +++ b/qiskit_aer/quantum_info/states/aer_densitymatrix.py @@ -62,9 +62,7 @@ def __init__(self, data, dims=None, **configs): method = configs["method"] raise AerError(f"Method {method} is not supported") if isinstance(data, (QuantumCircuit, Instruction)): - data, aer_state = AerDensityMatrix._from_instruction( - data, None, configs - ) + data, aer_state = AerDensityMatrix._from_instruction(data, None, configs) elif isinstance(data, list): data = self._from_1d_array(np.array(data, dtype=complex)) data, aer_state = AerDensityMatrix._from_ndarray(data, configs) @@ -96,9 +94,7 @@ def __init__(self, data, dims=None, **configs): np.asarray(data.to_matrix(), dtype=complex), configs ) else: - raise AerError( - f"Input data is not supported: type={data.__class__}, data={data}" - ) + raise AerError(f"Input data is not supported: type={data.__class__}, data={data}") self._aer_state = aer_state @@ -112,9 +108,7 @@ def seed(self, value=None): if value is None or isinstance(value, int): self._aer_state.set_seed(value) else: - raise AerError( - f"This seed is not supported: type={value.__class__}, value={value}" - ) + raise AerError(f"This seed is not supported: type={value.__class__}, value={value}") def _last_result(self): if self._result is None: @@ -260,13 +254,9 @@ def _from_instruction(inst, init_data, configs): aer_state.apply_global_phase(inst.global_phase) if isinstance(inst, QuantumCircuit): - AerStatevector._aer_evolve_circuit( - aer_state, inst, range(num_qubits), basis_gates - ) + AerStatevector._aer_evolve_circuit(aer_state, inst, range(num_qubits), basis_gates) else: - AerStatevector._aer_evolve_instruction( - aer_state, inst, range(num_qubits), basis_gates - ) + AerStatevector._aer_evolve_instruction(aer_state, inst, range(num_qubits), basis_gates) return aer_state.move_to_ndarray(), aer_state @@ -311,9 +301,7 @@ def to_statevector(self, atol=None, rtol=None): evals, evecs = np.linalg.eig(self.data) nonzero_evals = evals[abs(evals) > atol] - if len(nonzero_evals) != 1 or not np.isclose( - nonzero_evals[0], 1, atol=atol, rtol=rtol - ): + if len(nonzero_evals) != 1 or not np.isclose(nonzero_evals[0], 1, atol=atol, rtol=rtol): raise QiskitError("Density matrix is not a pure state") psi = evecs[:, np.argmax(evals)] # eigenvectors returned in columns. diff --git a/qiskit_aer/quantum_info/states/aer_state.py b/qiskit_aer/quantum_info/states/aer_state.py index ee993df844..0dd0d47fbe 100644 --- a/qiskit_aer/quantum_info/states/aer_state.py +++ b/qiskit_aer/quantum_info/states/aer_state.py @@ -100,23 +100,17 @@ def _assert_closed(self): def _allocated(self): if self._state != _STATE.INITIALIZING: - raise AerError( - "unexpected state transition: {self._state}->{_STATE.ALLOCATED}" - ) + raise AerError("unexpected state transition: {self._state}->{_STATE.ALLOCATED}") self._state = _STATE.ALLOCATED def _mapped(self): if self._state != _STATE.INITIALIZING: - raise AerError( - "unexpected state transition: {self._state}->{_STATE.MAPPED}" - ) + raise AerError("unexpected state transition: {self._state}->{_STATE.MAPPED}") self._state = _STATE.MAPPED def _released(self): if self._state != _STATE.MAPPED: - raise AerError( - "unexpected state transition: {self._state}->{_STATE.RELEASED}" - ) + raise AerError("unexpected state transition: {self._state}->{_STATE.RELEASED}") self._state = _STATE.RELEASED def _moved(self): @@ -126,9 +120,7 @@ def _moved(self): def _closed(self): if self._state not in (_STATE.MOVED, _STATE.MAPPED, _STATE.RELEASED): - raise AerError( - "unexpected state transition: {self._state}->{_STATE.CLOSED}" - ) + raise AerError("unexpected state transition: {self._state}->{_STATE.CLOSED}") self._state = _STATE.CLOSED def configure(self, key, value): @@ -180,9 +172,7 @@ def _initialize_with_ndarray(self, data, copy): elif self._method == "density_matrix": if data.shape != (len(data), len(data)): raise AerError("shape of init data must be a pair of power of two") - init = self._native_state.initialize_density_matrix( - num_of_qubits, data, copy - ) + init = self._native_state.initialize_density_matrix(num_of_qubits, data, copy) if init: if not copy: @@ -452,9 +442,7 @@ def apply_cu(self, control_qubit, target_qubit, theta, phi, lamb, gamma): self._assert_in_allocated_qubits(control_qubit) self._assert_in_allocated_qubits(target_qubit) # update state - self._native_state.apply_cu( - [control_qubit, target_qubit], theta, phi, lamb, gamma - ) + self._native_state.apply_cu([control_qubit, target_qubit], theta, phi, lamb, gamma) def apply_mcu(self, control_qubits, target_qubit, theta, phi, lamb, gamma): """apply a mcu operation.""" @@ -462,9 +450,7 @@ def apply_mcu(self, control_qubits, target_qubit, theta, phi, lamb, gamma): self._assert_in_allocated_qubits(control_qubits) self._assert_in_allocated_qubits(target_qubit) # update state - self._native_state.apply_mcu( - control_qubits + [target_qubit], theta, phi, lamb, gamma - ) + self._native_state.apply_mcu(control_qubits + [target_qubit], theta, phi, lamb, gamma) def apply_mcswap(self, control_qubits, qubit0, qubit1): """apply a mcswap operation.""" diff --git a/qiskit_aer/quantum_info/states/aer_statevector.py b/qiskit_aer/quantum_info/states/aer_statevector.py index 4a27f433fe..f5b91d322d 100644 --- a/qiskit_aer/quantum_info/states/aer_statevector.py +++ b/qiskit_aer/quantum_info/states/aer_statevector.py @@ -81,9 +81,7 @@ def __init__(self, data, dims=None, **configs): np.array(data.data, dtype=complex), configs ) else: - raise AerError( - f"Input data is not supported: type={data.__class__}, data={data}" - ) + raise AerError(f"Input data is not supported: type={data.__class__}, data={data}") self._aer_state = aer_state @@ -97,9 +95,7 @@ def seed(self, value=None): if value is None or isinstance(value, int): self._aer_state.set_seed(value) else: - raise AerError( - f"This seed is not supported: type={value.__class__}, value={value}" - ) + raise AerError(f"This seed is not supported: type={value.__class__}, value={value}") def _last_result(self): if self._result is None: @@ -192,13 +188,9 @@ def _from_instruction(inst, init_data, configs): aer_state.apply_global_phase(inst.global_phase) if isinstance(inst, QuantumCircuit): - AerStatevector._aer_evolve_circuit( - aer_state, inst, range(num_qubits), basis_gates - ) + AerStatevector._aer_evolve_circuit(aer_state, inst, range(num_qubits), basis_gates) else: - AerStatevector._aer_evolve_instruction( - aer_state, inst, range(num_qubits), basis_gates - ) + AerStatevector._aer_evolve_instruction(aer_state, inst, range(num_qubits), basis_gates) return aer_state.move_to_ndarray(), aer_state @@ -248,9 +240,7 @@ def _aer_evolve_instruction(aer_state, inst, qubits, basis_gates=None): elif inst.name == "diagonal": aer_state.apply_diagonal(qubits, inst.params) elif inst.name == "cu": - aer_state.apply_cu( - qubits[0], qubits[1], params[0], params[1], params[2], params[3] - ) + aer_state.apply_cu(qubits[0], qubits[1], params[0], params[1], params[2], params[3]) elif inst.name == "mcu": aer_state.apply_mcu( qubits[0 : len(qubits) - 1], @@ -261,17 +251,11 @@ def _aer_evolve_instruction(aer_state, inst, qubits, basis_gates=None): params[3], ) elif inst.name in "mcx": - aer_state.apply_mcx( - qubits[0 : len(qubits) - 1], qubits[len(qubits) - 1] - ) + aer_state.apply_mcx(qubits[0 : len(qubits) - 1], qubits[len(qubits) - 1]) elif inst.name in "mcy": - aer_state.apply_mcy( - qubits[0 : len(qubits) - 1], qubits[len(qubits) - 1] - ) + aer_state.apply_mcy(qubits[0 : len(qubits) - 1], qubits[len(qubits) - 1]) elif inst.name in "mcz": - aer_state.apply_mcz( - qubits[0 : len(qubits) - 1], qubits[len(qubits) - 1] - ) + aer_state.apply_mcz(qubits[0 : len(qubits) - 1], qubits[len(qubits) - 1]) elif inst.name == "id": pass else: @@ -289,9 +273,7 @@ def _aer_evolve_instruction(aer_state, inst, qubits, basis_gates=None): definition = inst.definition if definition is inst or definition is None: raise AerError("cannot decompose " + inst.name) - AerStatevector._aer_evolve_circuit( - aer_state, definition, qubits, basis_gates - ) + AerStatevector._aer_evolve_circuit(aer_state, definition, qubits, basis_gates) @classmethod def from_label(cls, label): diff --git a/qiskit_aer/utils/noise_model_inserter.py b/qiskit_aer/utils/noise_model_inserter.py index c889990d2b..f5bca2576f 100644 --- a/qiskit_aer/utils/noise_model_inserter.py +++ b/qiskit_aer/utils/noise_model_inserter.py @@ -47,12 +47,8 @@ def insert_noise(circuits, noise_model, transpile=False): ) else: transpiled_circuit = circuit - qubit_indices = { - bit: index for index, bit in enumerate(transpiled_circuit.qubits) - } - result_circuit = transpiled_circuit.copy( - name=transpiled_circuit.name + "_with_noise" - ) + qubit_indices = {bit: index for index, bit in enumerate(transpiled_circuit.qubits)} + result_circuit = transpiled_circuit.copy(name=transpiled_circuit.name + "_with_noise") result_circuit.data = [] for inst, qargs, cargs in transpiled_circuit.data: result_circuit.data.append((inst, qargs, cargs)) diff --git a/qiskit_aer/utils/noise_transformation.py b/qiskit_aer/utils/noise_transformation.py index b3cdd438cd..41d2044065 100644 --- a/qiskit_aer/utils/noise_transformation.py +++ b/qiskit_aer/utils/noise_transformation.py @@ -218,9 +218,7 @@ def approximate_quantum_error( for op in operator_list ] # preserve operator_list except NoiseError as err: - raise NoiseError( - f"Invalid type found in operator list: {operator_list}" - ) from err + raise NoiseError(f"Invalid type found in operator list: {operator_list}") from err probabilities = _transform_by_operator_list(channel_list, error)[1:] identity_prob = np.round(1 - sum(probabilities), 9) @@ -231,14 +229,10 @@ def approximate_quantum_error( noise_ops.append((operator, probability)) return QuantumError(noise_ops) - raise NoiseError( - "Quantum error approximation failed - no approximating operators detected" - ) + raise NoiseError("Quantum error approximation failed - no approximating operators detected") -def approximate_noise_model( - model, *, operator_string=None, operator_dict=None, operator_list=None -): +def approximate_noise_model(model, *, operator_string=None, operator_dict=None, operator_list=None): """ Replace all noises in a noise model with ones approximated by a mixture of operators (channels). diff --git a/qiskit_aer/version.py b/qiskit_aer/version.py index a723c4b76b..341b876974 100644 --- a/qiskit_aer/version.py +++ b/qiskit_aer/version.py @@ -68,9 +68,7 @@ def get_version_info(): full_version = VERSION if not os.path.exists( - os.path.join( - os.path.dirname(os.path.dirname(os.path.dirname(ROOT_DIR))), ".git" - ) + os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(ROOT_DIR))), ".git") ): return full_version try: diff --git a/setup.py b/setup.py index 9901c915e1..d35d076c23 100644 --- a/setup.py +++ b/setup.py @@ -10,31 +10,27 @@ from skbuild import setup -PACKAGE_NAME = os.getenv('QISKIT_AER_PACKAGE_NAME', 'qiskit-aer') +PACKAGE_NAME = os.getenv("QISKIT_AER_PACKAGE_NAME", "qiskit-aer") -extras_requirements = { - "dask": ["dask", "distributed"] -} +extras_requirements = {"dask": ["dask", "distributed"]} requirements = [ - 'qiskit-terra>=0.21.0', - 'numpy>=1.16.3', - 'scipy>=1.0', + "qiskit-terra>=0.21.0", + "numpy>=1.16.3", + "scipy>=1.0", ] -VERSION_PATH = os.path.join(os.path.dirname(__file__), - "qiskit_aer", "VERSION.txt") +VERSION_PATH = os.path.join(os.path.dirname(__file__), "qiskit_aer", "VERSION.txt") with open(VERSION_PATH, "r") as version_file: VERSION = version_file.read().strip() -README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), - 'README.md') +README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), "README.md") with open(README_PATH) as readme_file: README = readme_file.read() cmake_args = [] -is_win_32_bit = (platform.system() == 'Windows' and platform.architecture()[0] == "32bit") +is_win_32_bit = platform.system() == "Windows" and platform.architecture()[0] == "32bit" if is_win_32_bit: cmake_args.append("-DCMAKE_GENERATOR_PLATFORM=Win32") @@ -42,10 +38,10 @@ name=PACKAGE_NAME, version=VERSION, packages=setuptools.find_packages(exclude=["test*"]), - cmake_source_dir='.', + cmake_source_dir=".", description="Qiskit Aer - High performance simulators for Qiskit", long_description=README, - long_description_content_type='text/markdown', + long_description_content_type="text/markdown", url="https://github.com/Qiskit/qiskit-aer", author="AER Development Team", author_email="hello@qiskit.org", @@ -74,5 +70,5 @@ extras_require=extras_requirements, cmake_args=cmake_args, keywords="qiskit aer simulator quantum addon backend", - zip_safe=False + zip_safe=False, ) diff --git a/test/benchmark/basic.py b/test/benchmark/basic.py index f990fd3dd2..f63a28513c 100644 --- a/test/benchmark/basic.py +++ b/test/benchmark/basic.py @@ -48,9 +48,5 @@ def track_statevector_gpu(self, app, measure, measure_count, noise_name, qubit): self.RUNTIME_STATEVECTOR_GPU, app, measure, measure_count, noise_name, qubit ) - def track_matrix_product_state( - self, app, measure, measure_count, noise_name, qubit - ): - return self._run( - self.RUNTIME_MPS_CPU, app, measure, measure_count, noise_name, qubit - ) + def track_matrix_product_state(self, app, measure, measure_count, noise_name, qubit): + return self._run(self.RUNTIME_MPS_CPU, app, measure, measure_count, noise_name, qubit) diff --git a/test/benchmark/circuit_library_circuits.py b/test/benchmark/circuit_library_circuits.py index ac76ef9998..7fec4addba 100644 --- a/test/benchmark/circuit_library_circuits.py +++ b/test/benchmark/circuit_library_circuits.py @@ -51,9 +51,7 @@ def real_amplitudes(self, qubit, repeats): return self.transpile(RealAmplitudes(qubit, reps=repeats)) def real_amplitudes_linear(self, qubit, repeats): - return self.transpile( - RealAmplitudes(qubit, reps=repeats, entanglement="linear") - ) + return self.transpile(RealAmplitudes(qubit, reps=repeats, entanglement="linear")) def efficient_su2(self, qubit, repeats): return self.transpile(EfficientSU2(qubit).decompose()) @@ -65,9 +63,7 @@ def excitation_preserving(self, qubit, repeats): return self.transpile(ExcitationPreserving(qubit, reps=repeats).decompose()) def excitation_preserving_linear(self, qubit, repeats): - return self.transpile( - ExcitationPreserving(qubit, reps=repeats, entanglement="linear") - ) + return self.transpile(ExcitationPreserving(qubit, reps=repeats, entanglement="linear")) def fourier_checking(self, qubit, repeats): if qubit > 20: @@ -114,6 +110,5 @@ def phase_estimation(self, qubit, repeats): if qubit < 5: raise ValueError("qubit is too small: {0}".format(qubit)) return self._repeat( - PhaseEstimation(2, QuantumVolume(qubit - 2).decompose()).decompose(), - repeats, + PhaseEstimation(2, QuantumVolume(qubit - 2).decompose()).decompose(), repeats ) diff --git a/test/benchmark/noise.py b/test/benchmark/noise.py index 61ce411718..1789a8884c 100644 --- a/test/benchmark/noise.py +++ b/test/benchmark/noise.py @@ -50,20 +50,10 @@ def track_statevector_gpu(self, app, measure, measure_count, noise_name, qubit): def track_density_matrix(self, app, measure, measure_count, noise_name, qubit): return self._run( - self.RUNTIME_DENSITY_MATRIX_CPU, - app, - measure, - measure_count, - noise_name, - qubit, + self.RUNTIME_DENSITY_MATRIX_CPU, app, measure, measure_count, noise_name, qubit ) def track_density_matrix_gpu(self, app, measure, measure_count, noise_name, qubit): return self._run( - self.RUNTIME_DENSITY_MATRIX_GPU, - app, - measure, - measure_count, - noise_name, - qubit, + self.RUNTIME_DENSITY_MATRIX_GPU, app, measure, measure_count, noise_name, qubit ) diff --git a/test/benchmark/simulator_benchmark.py b/test/benchmark/simulator_benchmark.py index e2060803b0..c7cd605486 100644 --- a/test/benchmark/simulator_benchmark.py +++ b/test/benchmark/simulator_benchmark.py @@ -45,11 +45,7 @@ class SimulatorBenchmarkSuite(CircuitLibraryCircuits): RUNTIME_UNITARY_MATRIX_CPU, ] - RUNTIME_GPU = [ - RUNTIME_STATEVECTOR_GPU, - RUNTIME_DENSITY_MATRIX_GPU, - RUNTIME_UNITARY_MATRIX_GPU, - ] + RUNTIME_GPU = [RUNTIME_STATEVECTOR_GPU, RUNTIME_DENSITY_MATRIX_GPU, RUNTIME_UNITARY_MATRIX_GPU] DEFAULT_RUNTIME = [ RUNTIME_STATEVECTOR_CPU, @@ -102,13 +98,7 @@ def __init__( self.noise_model_names, self.qubits, ) - self.param_names = [ - "application", - "measure_method", - "measure_counts", - "noise", - "qubit", - ] + self.param_names = ["application", "measure_method", "measure_counts", "noise", "qubit"] all_simulators = [SIMULATOR] @@ -145,9 +135,7 @@ def __init__( if self.RUNTIME_MPS_CPU in runtime_names: self.simulators[self.RUNTIME_MPS_CPU] = SIMULATOR - self.backend_options_list[self.RUNTIME_MPS_CPU] = { - "method": self.RUNTIME_MPS_CPU - } + self.backend_options_list[self.RUNTIME_MPS_CPU] = {"method": self.RUNTIME_MPS_CPU} self.backend_qubits[self.RUNTIME_MPS_CPU] = self.qubits if self.RUNTIME_DENSITY_MATRIX_CPU in runtime_names: @@ -180,10 +168,7 @@ def add_expval(base, num_terms): from numpy.random import default_rng rng = default_rng(1) - paulis = [ - "".join(s) - for s in rng.choice(["I", "X", "Y", "Z"], size=(num_terms, qubit)) - ] + paulis = ["".join(s) for s in rng.choice(["I", "X", "Y", "Z"], size=(num_terms, qubit))] pauli_op = [(1 / num_terms, pauli) for pauli in paulis] circuit.snapshot_expectation_value("expval", pauli_op, range(qubit)) @@ -316,24 +301,17 @@ def _run(self, runtime, app, measure, measure_count, noise_name, qubit): qobj = self.gen_qobj(runtime, app, measure, measure_count, qubit) if qobj is None: raise ValueError( - "no qobj: measure={0}:{1}, qubit={2}".format( - measure, measure_count, qubit - ) + "no qobj: measure={0}:{1}, qubit={2}".format(measure, measure_count, qubit) ) start = time() - result = simulator.run( - qobj, noise_model=noise_model, **backend_options - ).result() + result = simulator.run(qobj, noise_model=noise_model, **backend_options).result() if result.status != "COMPLETED": try: reason = None ret_dict = result.to_dict() if "results" in ret_dict: - if ( - len(ret_dict["results"]) > 0 - and "status" in ret_dict["results"][0] - ): + if len(ret_dict["results"]) > 0 and "status" in ret_dict["results"][0]: reason = ret_dict["results"][0]["status"] if reason is None and "status" in ret_dict: reason = ret_dict["status"] @@ -348,9 +326,7 @@ def run_manual(self): import timeout_decorator @timeout_decorator.timeout(self.timeout) - def run_with_timeout( - suite, runtime, app, measure, measure_count, noise_name, qubit - ): + def run_with_timeout(suite, runtime, app, measure, measure_count, noise_name, qubit): start = time() return eval("suite.track_{0}".format(runtime))( app, measure, measure_count, noise_name, qubit @@ -361,9 +337,7 @@ def run_with_timeout( for runtime in self.runtime_names: for app in self.apps: repeats = None if app not in self.app2rep else self.app2rep[app] - app_name = ( - app if repeats is None else "{0}:{1}".format(app, repeats) - ) + app_name = app if repeats is None else "{0}:{1}".format(app, repeats) for qubit in self.qubits: for measure in self.measures: for measure_count in self.measure_counts: diff --git a/test/benchmark/vqe_application.py b/test/benchmark/vqe_application.py index 705c79a4a1..fc4e0d91f8 100644 --- a/test/benchmark/vqe_application.py +++ b/test/benchmark/vqe_application.py @@ -44,11 +44,7 @@ def _run_uccsd_vqe(self, mol_string, method, threads): ) def cb_create_solver( - num_particles, - num_orbitals, - qubit_mapping, - two_qubit_reduction, - z2_symmetries, + num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries ): initial_state = HartreeFock( num_orbitals, diff --git a/test/terra/backends/aer_simulator/test_algorithms.py b/test/terra/backends/aer_simulator/test_algorithms.py index feb917e532..4c99576f59 100644 --- a/test/terra/backends/aer_simulator/test_algorithms.py +++ b/test/terra/backends/aer_simulator/test_algorithms.py @@ -28,9 +28,7 @@ def _test_grovers(self, **options): shots = 2000 backend = self.backend(**options) - circuits = ref_algorithms.grovers_circuit( - final_measure=True, allow_sampling=True - ) + circuits = ref_algorithms.grovers_circuit(final_measure=True, allow_sampling=True) targets = ref_algorithms.grovers_counts(shots) circuits = transpile(circuits, backend) @@ -97,16 +95,12 @@ def test_teleport(self, method, device): @supported_methods(["statevector", "density_matrix"]) def test_grovers_cache_blocking(self, method, device): """Test grovers circuits execute.""" - self._test_grovers( - method=method, device=device, blocking_qubits=2, max_parallel_threads=1 - ) + self._test_grovers(method=method, device=device, blocking_qubits=2, max_parallel_threads=1) @supported_methods(["statevector", "density_matrix"]) def test_teleport_cache_blocking(self, method, device): """Test teleport circuits.""" - self._test_teleport( - method=method, device=device, blocking_qubits=2, max_parallel_threads=1 - ) + self._test_teleport(method=method, device=device, blocking_qubits=2, max_parallel_threads=1) def test_extended_stabilizer_sparse_output_probs(self): """ @@ -137,6 +131,4 @@ def test_extended_stabilizer_sparse_output_probs(self): } result = backend.run(circ, shots=shots).result() self.assertSuccess(result) - self.compare_counts( - result, [circ], [target], hex_counts=False, delta=0.1 * shots - ) + self.compare_counts(result, [circ], [target], hex_counts=False, delta=0.1 * shots) diff --git a/test/terra/backends/aer_simulator/test_auto_method.py b/test/terra/backends/aer_simulator/test_auto_method.py index 33f43d3362..70fcb0d175 100644 --- a/test/terra/backends/aer_simulator/test_auto_method.py +++ b/test/terra/backends/aer_simulator/test_auto_method.py @@ -65,9 +65,7 @@ def test_auto_method_clifford_circuits_and_reset_noise(self): noise_probs = [0.5, 0.5] error = QuantumError(zip(noise_circs, noise_probs)) noise_model = NoiseModel() - noise_model.add_all_qubit_quantum_error( - error, ["id", "x", "y", "z", "h", "s", "sdg"] - ) + noise_model.add_all_qubit_quantum_error(error, ["id", "x", "y", "z", "h", "s", "sdg"]) backend = self.backend(noise_model=noise_model) # Test circuits @@ -116,9 +114,7 @@ def test_auto_method_clifford_circuits_and_kraus_noise(self): # Noise Model error = amplitude_damping_error(0.5) noise_model = NoiseModel() - noise_model.add_all_qubit_quantum_error( - error, ["id", "x", "y", "z", "h", "s", "sdg"] - ) + noise_model.add_all_qubit_quantum_error(error, ["id", "x", "y", "z", "h", "s", "sdg"]) backend = self.backend(noise_model=noise_model) # Test circuits @@ -148,9 +144,7 @@ def test_auto_method_nonclifford_circuit_and_reset_noise(self): noise_probs = [0.5, 0.5] error = QuantumError(zip(noise_circs, noise_probs)) noise_model = NoiseModel() - noise_model.add_all_qubit_quantum_error( - error, ["id", "x", "y", "z", "h", "s", "sdg"] - ) + noise_model.add_all_qubit_quantum_error(error, ["id", "x", "y", "z", "h", "s", "sdg"]) backend = self.backend(noise_model=noise_model) # Test circuits @@ -197,9 +191,7 @@ def test_auto_method_nonclifford_circuit_and_kraus_noise(self): # Noise Model error = amplitude_damping_error(0.5) noise_model = NoiseModel() - noise_model.add_all_qubit_quantum_error( - error, ["id", "x", "y", "z", "h", "s", "sdg"] - ) + noise_model.add_all_qubit_quantum_error(error, ["id", "x", "y", "z", "h", "s", "sdg"]) backend = self.backend(noise_model=noise_model) # Test circuits diff --git a/test/terra/backends/aer_simulator/test_chunk.py b/test/terra/backends/aer_simulator/test_chunk.py index 6c69dc9f5a..ca4c20d90b 100644 --- a/test/terra/backends/aer_simulator/test_chunk.py +++ b/test/terra/backends/aer_simulator/test_chunk.py @@ -40,17 +40,13 @@ def test_chunk_QuantumVolume(self, method, device): num_qubits = 4 depth = 10 circuit = transpile( - QuantumVolume(num_qubits, depth, seed=0), - backend=backend, - optimization_level=0, + QuantumVolume(num_qubits, depth, seed=0), backend=backend, optimization_level=0 ) circuit.measure_all() result = backend.run(circuit, shots=shots, memory=True).result() counts = result.get_counts(circuit) - result_no_chunk = backend_no_chunk.run( - circuit, shots=shots, memory=True - ).result() + result_no_chunk = backend_no_chunk.run(circuit, shots=shots, memory=True).result() counts_no_chunk = result_no_chunk.get_counts(circuit) self.assertEqual(counts_no_chunk, counts) @@ -73,17 +69,13 @@ def test_chunk_QuantumVolumeWithFusion(self, method, device): num_qubits = 8 depth = 10 circuit = transpile( - QuantumVolume(num_qubits, depth, seed=0), - backend=backend, - optimization_level=0, + QuantumVolume(num_qubits, depth, seed=0), backend=backend, optimization_level=0 ) circuit.measure_all() result = backend.run(circuit, shots=shots, memory=True).result() counts = result.get_counts(circuit) - result_no_chunk = backend_no_chunk.run( - circuit, shots=shots, memory=True - ).result() + result_no_chunk = backend_no_chunk.run(circuit, shots=shots, memory=True).result() counts_no_chunk = result_no_chunk.get_counts(circuit) self.assertEqual(counts_no_chunk, counts) @@ -109,9 +101,7 @@ def test_chunk_QFT(self, method, device): result = backend.run(circuit, shots=shots, memory=True).result() counts = result.get_counts(circuit) - result_no_chunk = backend_no_chunk.run( - circuit, shots=shots, memory=True - ).result() + result_no_chunk = backend_no_chunk.run(circuit, shots=shots, memory=True).result() counts_no_chunk = result_no_chunk.get_counts(circuit) self.assertEqual(counts_no_chunk, counts) @@ -137,9 +127,7 @@ def test_chunk_QFTWithFusion(self, method, device): result = backend.run(circuit, shots=shots, memory=True).result() counts = result.get_counts(circuit) - result_no_chunk = backend_no_chunk.run( - circuit, shots=shots, memory=True - ).result() + result_no_chunk = backend_no_chunk.run(circuit, shots=shots, memory=True).result() counts_no_chunk = result_no_chunk.get_counts(circuit) self.assertEqual(counts_no_chunk, counts) @@ -171,9 +159,7 @@ def test_chunk_pauli(self, method, device): result = backend.run(circuit, shots=shots, memory=True).result() counts = result.get_counts(circuit) - result_no_chunk = backend_no_chunk.run( - circuit, shots=shots, memory=True - ).result() + result_no_chunk = backend_no_chunk.run(circuit, shots=shots, memory=True).result() counts_no_chunk = result_no_chunk.get_counts(circuit) self.assertEqual(counts_no_chunk, counts) diff --git a/test/terra/backends/aer_simulator/test_circuit.py b/test/terra/backends/aer_simulator/test_circuit.py index a40467ab21..f387e27a16 100644 --- a/test/terra/backends/aer_simulator/test_circuit.py +++ b/test/terra/backends/aer_simulator/test_circuit.py @@ -54,9 +54,7 @@ def test_quantum_register_circuit(self, method, device): shots = 1000 result = backend.run(circuit, shots=shots).result() self.assertSuccess(result) - self.compare_counts( - result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots - ) + self.compare_counts(result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots) @supported_methods( [ @@ -89,9 +87,7 @@ def test_qubits_circuit(self, method, device): shots = 1000 result = backend.run(circuit, shots=shots).result() self.assertSuccess(result) - self.compare_counts( - result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots - ) + self.compare_counts(result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots) @supported_methods( [ @@ -127,9 +123,7 @@ def test_qubits_quantum_register_circuit(self, method, device): shots = 1000 result = backend.run(circuit, shots=shots).result() self.assertSuccess(result) - self.compare_counts( - result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots - ) + self.compare_counts(result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots) qubits0 = QuantumRegister(1) clbits1 = ClassicalRegister(1) @@ -147,9 +141,7 @@ def test_qubits_quantum_register_circuit(self, method, device): circuit.cx(qubits0[0], qubits1[0]) circuit.cx(qubits1[0], qubits2[0]) - for qubits, clbits in zip( - [qubits0, qubits1, qubits2], [clbits1, clbits2, clbits3] - ): + for qubits, clbits in zip([qubits0, qubits1, qubits2], [clbits1, clbits2, clbits3]): for q, c in zip(qubits, clbits): circuit.measure(q, c) @@ -158,9 +150,7 @@ def test_qubits_quantum_register_circuit(self, method, device): shots = 1000 result = backend.run(circuit, shots=shots).result() self.assertSuccess(result) - self.compare_counts( - result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots - ) + self.compare_counts(result, [circuit], [{"0x0": 500, "0x7": 500}], delta=0.05 * shots) def test_partial_result_a_single_invalid_circuit(self): """Test a partial result is returned with a job with a valid and invalid circuit.""" diff --git a/test/terra/backends/aer_simulator/test_cliffords.py b/test/terra/backends/aer_simulator/test_cliffords.py index 9f65d59529..3c3c0af1b5 100644 --- a/test/terra/backends/aer_simulator/test_cliffords.py +++ b/test/terra/backends/aer_simulator/test_cliffords.py @@ -147,9 +147,7 @@ def test_sdg_gate_nondeterministic(self, method, device): backend = self.backend(method=method, device=device, seed_simulator=self.SEED) shots = 4000 """Test sdg-gate circuits""" - circuits = ref_1q_clifford.sdg_gate_circuits_nondeterministic( - final_measure=True - ) + circuits = ref_1q_clifford.sdg_gate_circuits_nondeterministic(final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_nondeterministic(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -224,9 +222,7 @@ def test_swap_gate_nondeterministic(self, method, device): """Test swap-gate circuits""" backend = self.backend(method=method, device=device, seed_simulator=self.SEED) shots = 4000 - circuits = ref_2q_clifford.swap_gate_circuits_nondeterministic( - final_measure=True - ) + circuits = ref_2q_clifford.swap_gate_circuits_nondeterministic(final_measure=True) targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) diff --git a/test/terra/backends/aer_simulator/test_conditional.py b/test/terra/backends/aer_simulator/test_conditional.py index cf4c63bc1c..07f1298557 100644 --- a/test/terra/backends/aer_simulator/test_conditional.py +++ b/test/terra/backends/aer_simulator/test_conditional.py @@ -77,9 +77,7 @@ def test_conditional_gates_64bit(self, method, device): ) # not using hex counts because number of leading zeros in results # doesn't seem consistent - targets = ref_conditionals.condtional_counts_nbit( - 64, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(64, cases, shots, hex_counts=False) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -97,9 +95,7 @@ def test_conditional_gates_132bit(self, method, device): circuits = ref_conditionals.conditional_circuits_nbit( 132, cases, final_measure=True, conditional_type="gate" ) - targets = ref_conditionals.condtional_counts_nbit( - 132, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(132, cases, shots, hex_counts=False) circuits = circuits[0:1] targets = targets[0:1] result = backend.run(circuits, shots=shots).result() @@ -161,9 +157,7 @@ def test_conditional_unitary_64bit(self, method, device): circuits = ref_conditionals.conditional_circuits_nbit( 64, cases, final_measure=True, conditional_type="unitary" ) - targets = ref_conditionals.condtional_counts_nbit( - 64, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(64, cases, shots, hex_counts=False) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -181,9 +175,7 @@ def test_conditional_unitary_132bit(self, method, device): circuits = ref_conditionals.conditional_circuits_nbit( 132, cases, final_measure=True, conditional_type="unitary" ) - targets = ref_conditionals.condtional_counts_nbit( - 132, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(132, cases, shots, hex_counts=False) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, hex_counts=False, delta=0) @@ -243,9 +235,7 @@ def test_conditional_kraus_64bit(self, method, device): circuits = ref_conditionals.conditional_circuits_nbit( 64, cases, final_measure=True, conditional_type="kraus" ) - targets = ref_conditionals.condtional_counts_nbit( - 64, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(64, cases, shots, hex_counts=False) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -263,9 +253,7 @@ def test_conditional_kraus_132bit(self, method, device): circuits = ref_conditionals.conditional_circuits_nbit( 132, cases, final_measure=True, conditional_type="kraus" ) - targets = ref_conditionals.condtional_counts_nbit( - 132, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(132, cases, shots, hex_counts=False) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, hex_counts=False, delta=0) @@ -319,9 +307,7 @@ def test_conditional_superop_64bit(self, method, device): circuits = ref_conditionals.conditional_circuits_nbit( 64, cases, final_measure=True, conditional_type="superop" ) - targets = ref_conditionals.condtional_counts_nbit( - 64, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(64, cases, shots, hex_counts=False) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -339,9 +325,7 @@ def test_conditional_superop_132bit(self, method, device): circuits = ref_conditionals.conditional_circuits_nbit( 132, cases, final_measure=True, conditional_type="superop" ) - targets = ref_conditionals.condtional_counts_nbit( - 132, cases, shots, hex_counts=False - ) + targets = ref_conditionals.condtional_counts_nbit(132, cases, shots, hex_counts=False) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, hex_counts=False, delta=0) diff --git a/test/terra/backends/aer_simulator/test_executors.py b/test/terra/backends/aer_simulator/test_executors.py index 3ea4411ba1..068126f4b0 100644 --- a/test/terra/backends/aer_simulator/test_executors.py +++ b/test/terra/backends/aer_simulator/test_executors.py @@ -84,9 +84,7 @@ class TestDaskExecutor(CBFixture): def setUpClass(cls): super().setUpClass() if DASK: - cls._test_executor = Client( - address=LocalCluster(n_workers=1, processes=True) - ) + cls._test_executor = Client(address=LocalCluster(n_workers=1, processes=True)) def setUp(self): super().setUp() @@ -100,19 +98,14 @@ def test_random_circuits_job(self, method, device, max_job_size): backend = self.backend(method=method, device=device, max_job_size=max_job_size) result, circuits, targets = run_random_circuits(backend, shots=shots) self.assertSuccess(result) - self.compare_counts( - result, circuits, targets, hex_counts=False, delta=0.05 * shots - ) + self.compare_counts(result, circuits, targets, hex_counts=False, delta=0.05 * shots) @supported_methods(["statevector"], [None, 1, 1, 1], [None, 100, 500, 1000]) def test_noise_circuits_job(self, method, device, max_job_size, max_shot_size): """Test random circuits with custom executor.""" shots = 4000 backend = self.backend( - method=method, - device=device, - max_job_size=max_job_size, - max_shot_size=max_shot_size, + method=method, device=device, max_job_size=max_job_size, max_shot_size=max_shot_size ) circuits = ref_kraus_noise.kraus_gate_error_circuits() @@ -152,19 +145,14 @@ def test_random_circuits_job(self, method, device, max_job_size): backend = self.backend(method=method, device=device, max_job_size=max_job_size) result, circuits, targets = run_random_circuits(backend, shots=shots) self.assertSuccess(result) - self.compare_counts( - result, circuits, targets, hex_counts=False, delta=0.05 * shots - ) + self.compare_counts(result, circuits, targets, hex_counts=False, delta=0.05 * shots) @supported_methods(["statevector"], [None, 1, 1, 1], [None, 100, 500, 1000]) def test_noise_circuits_job(self, method, device, max_job_size, max_shot_size): """Test random circuits with custom executor.""" shots = 4000 backend = self.backend( - method=method, - device=device, - max_job_size=max_job_size, - max_shot_size=max_shot_size, + method=method, device=device, max_job_size=max_job_size, max_shot_size=max_shot_size ) circuits = ref_kraus_noise.kraus_gate_error_circuits() diff --git a/test/terra/backends/aer_simulator/test_from_backend.py b/test/terra/backends/aer_simulator/test_from_backend.py index 7c07917ae7..0231f574f5 100644 --- a/test/terra/backends/aer_simulator/test_from_backend.py +++ b/test/terra/backends/aer_simulator/test_from_backend.py @@ -38,12 +38,8 @@ def test_backend_v1(self): sim_backend = AerSimulator.from_backend(backend) tqc = transpile(self.qc, backend) self.assertEqual( - backend.run(tqc, shots=1024, seed_simulator=12345678942) - .result() - .get_counts(), - sim_backend.run(tqc, shots=1024, seed_simulator=12345678942) - .result() - .get_counts(), + backend.run(tqc, shots=1024, seed_simulator=12345678942).result().get_counts(), + sim_backend.run(tqc, shots=1024, seed_simulator=12345678942).result().get_counts(), ) def test_backend_v2(self): @@ -52,11 +48,7 @@ def test_backend_v2(self): sim_backend = AerSimulator.from_backend(backend) tqc = transpile(self.qc, backend) self.assertDictAlmostEqual( - backend.run(tqc, shots=1024, seed_simulator=12345678942) - .result() - .get_counts(), - sim_backend.run(tqc, shots=1024, seed_simulator=12345678942) - .result() - .get_counts(), + backend.run(tqc, shots=1024, seed_simulator=12345678942).result().get_counts(), + sim_backend.run(tqc, shots=1024, seed_simulator=12345678942).result().get_counts(), delta=100, ) diff --git a/test/terra/backends/aer_simulator/test_fusion.py b/test/terra/backends/aer_simulator/test_fusion.py index ce8c8815fd..d2d5c42289 100644 --- a/test/terra/backends/aer_simulator/test_fusion.py +++ b/test/terra/backends/aer_simulator/test_fusion.py @@ -21,11 +21,7 @@ from qiskit.circuit.library import QuantumVolume, QFT, RealAmplitudes from qiskit.compiler import transpile from qiskit_aer.noise import NoiseModel -from qiskit_aer.noise.errors import ( - ReadoutError, - depolarizing_error, - amplitude_damping_error, -) +from qiskit_aer.noise.errors import ReadoutError, depolarizing_error, amplitude_damping_error from test.terra.backends.simulator_test_case import SimulatorTestCase, supported_methods @@ -62,9 +58,7 @@ def noise_model_depol(self): ] noise.add_all_qubit_readout_error(ReadoutError(readout)) for gate, (num_qubits, gate_error) in params.items(): - noise.add_all_qubit_quantum_error( - depolarizing_error(gate_error, num_qubits), gate - ) + noise.add_all_qubit_quantum_error(depolarizing_error(gate_error, num_qubits), gate) return noise def noise_model_kraus(self): @@ -78,14 +72,10 @@ def noise_model_kraus(self): ] noise.add_all_qubit_readout_error(ReadoutError(readout)) for gate, (num_qubits, gate_error) in params.items(): - noise.add_all_qubit_quantum_error( - amplitude_damping_error(gate_error, num_qubits), gate - ) + noise.add_all_qubit_quantum_error(amplitude_damping_error(gate_error, num_qubits), gate) return noise - def fusion_options( - self, enabled=None, threshold=None, verbose=None, parallelization=None - ): + def fusion_options(self, enabled=None, threshold=None, verbose=None, parallelization=None): """Return default backend_options dict.""" backend_options = {} if enabled is not None: @@ -116,9 +106,7 @@ def test_fusion_threshold(self, method, device): circuit.measure_all() with self.subTest(msg="at threshold"): - backend.set_options( - **self.fusion_options(enabled=True, threshold=num_qubits) - ) + backend.set_options(**self.fusion_options(enabled=True, threshold=num_qubits)) result = backend.run(circuit, shots=shots).result() self.assertSuccess(result) meta = self.fusion_metadata(result) @@ -126,9 +114,7 @@ def test_fusion_threshold(self, method, device): self.assertFalse(meta.get("applied")) with self.subTest(msg="below threshold"): - backend.set_options( - **self.fusion_options(enabled=True, threshold=num_qubits + 1) - ) + backend.set_options(**self.fusion_options(enabled=True, threshold=num_qubits + 1)) result = backend.run(circuit, shots=shots).result() self.assertSuccess(result) meta = self.fusion_metadata(result) @@ -136,9 +122,7 @@ def test_fusion_threshold(self, method, device): self.assertFalse(meta.get("applied")) with self.subTest(msg="above threshold"): - backend.set_options( - **self.fusion_options(enabled=True, threshold=num_qubits - 1) - ) + backend.set_options(**self.fusion_options(enabled=True, threshold=num_qubits - 1)) result = backend.run(circuit, shots=shots).result() self.assertSuccess(result) meta = self.fusion_metadata(result) @@ -177,14 +161,10 @@ def test_fusion_verbose(self): """Test Fusion with verbose option""" shots = 100 backend = self.backend(method="statevector") - circuit = transpile( - self.create_statevector_circuit(), backend, optimization_level=0 - ) + circuit = transpile(self.create_statevector_circuit(), backend, optimization_level=0) with self.subTest(msg="verbose enabled"): - backend.set_options( - **self.fusion_options(enabled=True, verbose=True, threshold=1) - ) + backend.set_options(**self.fusion_options(enabled=True, verbose=True, threshold=1)) result = backend.run(circuit, shots=shots).result() # Assert fusion applied succesfully self.assertSuccess(result) @@ -194,9 +174,7 @@ def test_fusion_verbose(self): self.assertIn("output_ops", meta) with self.subTest(msg="verbose disabled"): - backend.set_options( - **self.fusion_options(enabled=True, verbose=False, threshold=1) - ) + backend.set_options(**self.fusion_options(enabled=True, verbose=False, threshold=1)) result = backend.run(circuit, shots=shots).result() # Assert fusion applied succesfully self.assertSuccess(result) @@ -254,14 +232,9 @@ def test_kraus_noise_fusion(self, method, device): shots = 100 fusion_options = self.fusion_options(enabled=True, threshold=1) backend = self.backend( - method=method, - device=device, - noise_model=self.noise_model_kraus(), - **fusion_options - ) - circuit = transpile( - self.create_statevector_circuit(), backend, optimization_level=0 + method=method, device=device, noise_model=self.noise_model_kraus(), **fusion_options ) + circuit = transpile(self.create_statevector_circuit(), backend, optimization_level=0) result = backend.run(circuit, shots=shots).result() meta = self.fusion_metadata(result) if method == "density_matrix": @@ -269,9 +242,7 @@ def test_kraus_noise_fusion(self, method, device): else: target_method = "kraus" self.assertSuccess(result) - self.assertTrue( - meta.get("applied", False), msg="fusion should have been applied." - ) + self.assertTrue(meta.get("applied", False), msg="fusion should have been applied.") self.assertEqual(meta.get("method", None), target_method) @supported_methods(["statevector", "density_matrix"]) @@ -280,14 +251,9 @@ def test_non_kraus_noise_fusion(self, method, device): shots = 100 fusion_options = self.fusion_options(enabled=True, threshold=1) backend = self.backend( - method=method, - device=device, - noise_model=self.noise_model_depol(), - **fusion_options - ) - circuit = transpile( - self.create_statevector_circuit(), backend, optimization_level=0 + method=method, device=device, noise_model=self.noise_model_depol(), **fusion_options ) + circuit = transpile(self.create_statevector_circuit(), backend, optimization_level=0) result = backend.run(circuit, shots=shots).result() meta = self.fusion_metadata(result) if method == "density_matrix": @@ -295,9 +261,7 @@ def test_non_kraus_noise_fusion(self, method, device): else: target_method = "unitary" self.assertSuccess(result) - self.assertTrue( - meta.get("applied", False), msg="fusion should have been applied." - ) + self.assertTrue(meta.get("applied", False), msg="fusion should have been applied.") self.assertEqual(meta.get("method", None), target_method) def test_control_fusion(self): @@ -318,9 +282,7 @@ def test_control_fusion(self): self.assertTrue(meta.get("applied", False)) with self.subTest(msg="fusion disabled"): - backend_options = backend_options = self.fusion_options( - enabled=False, threshold=1 - ) + backend_options = backend_options = self.fusion_options(enabled=False, threshold=1) result = backend.run(circuit, shots=shots, **backend_options).result() meta = self.fusion_metadata(result) @@ -425,9 +387,7 @@ def test_fusion_qv(self): depth = 2 backend = self.backend(method="statevector") circuit = transpile( - QuantumVolume(num_qubits, depth, seed=0), - backend=backend, - optimization_level=0, + QuantumVolume(num_qubits, depth, seed=0), backend=backend, optimization_level=0 ) circuit.measure_all() @@ -487,21 +447,15 @@ def test_fusion_parallelization(self): backend = self.backend(method="statevector") circuit = transpile( - QuantumVolume(num_qubits, depth, seed=0), - backend=backend, - optimization_level=0, + QuantumVolume(num_qubits, depth, seed=0), backend=backend, optimization_level=0 ) circuit.measure_all() - options_serial = self.fusion_options( - enabled=True, threshold=1, parallelization=1 - ) + options_serial = self.fusion_options(enabled=True, threshold=1, parallelization=1) result_serial = backend.run(circuit, shots=shots, **options_serial).result() meta_serial = self.fusion_metadata(result_serial) - options_parallel = self.fusion_options( - enabled=True, threshold=1, parallelization=2 - ) + options_parallel = self.fusion_options(enabled=True, threshold=1, parallelization=2) result_parallel = backend.run(circuit, shots=shots, **options_parallel).result() meta_parallel = self.fusion_metadata(result_parallel) @@ -523,9 +477,7 @@ def test_fusion_two_qubits(self): reps = 3 backend = self.backend(method="statevector") - circuit = RealAmplitudes( - num_qubits=num_qubits, entanglement="linear", reps=reps - ) + circuit = RealAmplitudes(num_qubits=num_qubits, entanglement="linear", reps=reps) circuit.measure_all() np.random.seed(12345) @@ -533,9 +485,7 @@ def test_fusion_two_qubits(self): for param in circuit.parameters: param_binds[param] = np.random.random() - circuit = transpile( - circuit.bind_parameters(param_binds), backend, optimization_level=0 - ) + circuit = transpile(circuit.bind_parameters(param_binds), backend, optimization_level=0) backend_options = self.fusion_options(enabled=True, threshold=1) backend_options["fusion_verbose"] = True @@ -629,7 +579,7 @@ def test_parallel_fusion_diagonal(self): "fusion_enable.n_qubits": False, }, fusion_parallelization_threshold=3, - max_parallel_threads=thread + max_parallel_threads=thread, ).result() actual = result.get_statevector(0) diff --git a/test/terra/backends/aer_simulator/test_initialize.py b/test/terra/backends/aer_simulator/test_initialize.py index 693da843ad..a493c28e68 100644 --- a/test/terra/backends/aer_simulator/test_initialize.py +++ b/test/terra/backends/aer_simulator/test_initialize.py @@ -19,12 +19,7 @@ import numpy as np from test.terra.backends.simulator_test_case import SimulatorTestCase, supported_methods -SUPPORTED_METHODS = [ - "automatic", - "statevector", - "matrix_product_state", - "tensor_network", -] +SUPPORTED_METHODS = ["automatic", "statevector", "matrix_product_state", "tensor_network"] @ddt diff --git a/test/terra/backends/aer_simulator/test_job_splitting.py b/test/terra/backends/aer_simulator/test_job_splitting.py index 4e2e9be390..148a070904 100644 --- a/test/terra/backends/aer_simulator/test_job_splitting.py +++ b/test/terra/backends/aer_simulator/test_job_splitting.py @@ -80,10 +80,7 @@ def add_custom_instruction(self): def test_split(self): """Circuits split test""" backend = self.backend(max_job_size=1) - circs = [ - random_circuit(num_qubits=2, depth=4, measure=True, seed=i) - for i in range(2) - ] + circs = [random_circuit(num_qubits=2, depth=4, measure=True, seed=i) for i in range(2)] circs = transpile(circs, backend) self.split_compare(circs, backend) diff --git a/test/terra/backends/aer_simulator/test_measure.py b/test/terra/backends/aer_simulator/test_measure.py index 81f90f91f5..f3a495befd 100644 --- a/test/terra/backends/aer_simulator/test_measure.py +++ b/test/terra/backends/aer_simulator/test_measure.py @@ -155,9 +155,7 @@ def test_measure_deterministic_multi_qubit_with_sampling(self, method, device): """Test AerSimulator multi-qubit measure with deterministic counts with sampling""" backend = self.backend(method=method, device=device) shots = 100 - circuits = ref_measure.multiqubit_measure_circuits_deterministic( - allow_sampling=True - ) + circuits = ref_measure.multiqubit_measure_circuits_deterministic(allow_sampling=True) target_counts = ref_measure.multiqubit_measure_counts_deterministic(shots) target_memory = ref_measure.multiqubit_measure_memory_deterministic(shots) result = backend.run(circuits, memory=True, shots=shots).result() @@ -171,9 +169,7 @@ def test_measure_deterministic_multi_qubit_without_sampling(self, method, device """Test AerSimulator multi-qubit measure with deterministic counts without sampling""" backend = self.backend(method=method, device=device) shots = 100 - circuits = ref_measure.multiqubit_measure_circuits_deterministic( - allow_sampling=False - ) + circuits = ref_measure.multiqubit_measure_circuits_deterministic(allow_sampling=False) target_counts = ref_measure.multiqubit_measure_counts_deterministic(shots) target_memory = ref_measure.multiqubit_measure_memory_deterministic(shots) result = backend.run(circuits, memory=True, shots=shots).result() @@ -186,9 +182,7 @@ def test_measure_nondeterministic_multi_qubit_with_sampling(self, method, device """Test AerSimulator measure with non-deterministic counts""" backend = self.backend(method=method, device=device) shots = 4000 - circuits = ref_measure.multiqubit_measure_circuits_nondeterministic( - allow_sampling=True - ) + circuits = ref_measure.multiqubit_measure_circuits_nondeterministic(allow_sampling=True) targets = ref_measure.multiqubit_measure_counts_nondeterministic(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -196,9 +190,7 @@ def test_measure_nondeterministic_multi_qubit_with_sampling(self, method, device self.compare_result_metadata(result, circuits, "measure_sampling", True) @supported_methods(SUPPORTED_METHODS) - def test_measure_nondeterministic_multi_qubit_without_sampling( - self, method, device - ): + def test_measure_nondeterministic_multi_qubit_without_sampling(self, method, device): """Test AerSimulator measure with non-deterministic counts""" backend = self.backend(method=method, device=device) shots = 4000 @@ -206,9 +198,7 @@ def test_measure_nondeterministic_multi_qubit_without_sampling( if "tensor_network" in method: shots = 100 delta = 0.1 - circuits = ref_measure.multiqubit_measure_circuits_nondeterministic( - allow_sampling=False - ) + circuits = ref_measure.multiqubit_measure_circuits_nondeterministic(allow_sampling=False) targets = ref_measure.multiqubit_measure_counts_nondeterministic(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -271,9 +261,7 @@ def test_mps_measure_subset_alg_qv(self): self.assertTrue(getattr(result2, "success", "True")) self.assertDictAlmostEqual( - result1.get_counts(circuit), - result2.get_counts(circuit), - delta=0.1 * shots, + result1.get_counts(circuit), result2.get_counts(circuit), delta=0.1 * shots ) def test_mps_measure_with_limited_bond_dimension(self): @@ -285,8 +273,7 @@ def test_mps_measure_with_limited_bond_dimension(self): n = 4 for bd in [2, 4]: backend_mps = self.backend( - method="matrix_product_state", - matrix_product_state_max_bond_dimension=bd, + method="matrix_product_state", matrix_product_state_max_bond_dimension=bd ) for measured_qubits in [ [0, 1, 2, 3], @@ -305,7 +292,5 @@ def test_mps_measure_with_limited_bond_dimension(self): circuit.measure(measured_qubits, measured_qubits) res_mps = backend_mps.run(circuit, shots=shots).result().get_counts() self.assertTrue(getattr(res_mps, "success", "True")) - res_sv = ( - backend_statevector.run(circuit, shots=shots).result().get_counts() - ) + res_sv = backend_statevector.run(circuit, shots=shots).result().get_counts() self.assertDictAlmostEqual(res_mps, res_sv, delta=0.1 * shots) diff --git a/test/terra/backends/aer_simulator/test_metadata.py b/test/terra/backends/aer_simulator/test_metadata.py index bd47b84cb9..28cbab20d4 100644 --- a/test/terra/backends/aer_simulator/test_metadata.py +++ b/test/terra/backends/aer_simulator/test_metadata.py @@ -78,13 +78,7 @@ def test_three_circuit_metadata(self, method, device): self.assertEqual(circuit2.metadata, metadata2) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ] + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"] ) def test_three_parameterized_circuit_metadata(self, method, device): """Test circuits with object metadata.""" diff --git a/test/terra/backends/aer_simulator/test_multiplexer.py b/test/terra/backends/aer_simulator/test_multiplexer.py index d606cd3239..263fb7e33f 100644 --- a/test/terra/backends/aer_simulator/test_multiplexer.py +++ b/test/terra/backends/aer_simulator/test_multiplexer.py @@ -28,9 +28,7 @@ def test_multiplexer_cx_gate_deterministic(self): """Test multiplxer cx-gate circuits compiling to backend default basis_gates.""" backend = self.backend() shots = 100 - circuits = ref_multiplexer.multiplexer_cx_gate_circuits_deterministic( - final_measure=True - ) + circuits = ref_multiplexer.multiplexer_cx_gate_circuits_deterministic(final_measure=True) targets = ref_multiplexer.multiplexer_cx_gate_counts_deterministic(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -40,9 +38,7 @@ def test_multiplexer_cx_gate_nondeterministic(self): """Test multiplexer cx-gate circuits compiling to backend default basis_gates.""" backend = self.backend() shots = 4000 - circuits = ref_multiplexer.multiplexer_cx_gate_circuits_nondeterministic( - final_measure=True - ) + circuits = ref_multiplexer.multiplexer_cx_gate_circuits_nondeterministic(final_measure=True) targets = ref_multiplexer.multiplexer_cx_gate_counts_nondeterministic(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -55,9 +51,7 @@ def test_multiplexer_cxx_gate_deterministic(self): """Test multiplexer-gate gate circuits""" backend = self.backend() shots = 100 - circuits = ref_multiplexer.multiplexer_ccx_gate_circuits_deterministic( - final_measure=True - ) + circuits = ref_multiplexer.multiplexer_ccx_gate_circuits_deterministic(final_measure=True) targets = ref_multiplexer.multiplexer_ccx_gate_counts_deterministic(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) @@ -84,10 +78,7 @@ def test_multiplexer_without_control_qubits(self): result = backend.run(circuits, shots=shots).result() counts = [result.get_counts(circuit) for circuit in circuits] target_results = backend.run(target_circuits, shots=shots).result() - targets = [ - target_results.get_counts(target_circuit) - for target_circuit in target_circuits - ] + targets = [target_results.get_counts(target_circuit) for target_circuit in target_circuits] self.assertSuccess(result) for actual, target in zip(counts, targets): self.assertDictAlmostEqual(actual, target, delta=0.05 * shots) diff --git a/test/terra/backends/aer_simulator/test_noise.py b/test/terra/backends/aer_simulator/test_noise.py index 502a9201a8..9255bc8868 100644 --- a/test/terra/backends/aer_simulator/test_noise.py +++ b/test/terra/backends/aer_simulator/test_noise.py @@ -49,9 +49,7 @@ def test_empty_circuit_noise(self, method, device): backend = self.backend(method=method, device=device) noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.1, 1), ["x"]) - result = backend.run( - QuantumCircuit(), shots=1, noise_model=noise_model - ).result() + result = backend.run(QuantumCircuit(), shots=1, noise_model=noise_model).result() self.assertSuccess(result) @supported_methods(ALL_METHODS) @@ -142,13 +140,7 @@ def test_reset_gate_noise(self, method, device): self.compare_counts(result, [circuit], [target], delta=0.05 * shots) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ] + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"] ) def test_kraus_gate_noise(self, method, device): """Test simulation with Kraus gate error noise model.""" @@ -198,13 +190,7 @@ def _test_kraus_gate_noise_on_QFT(self, **options): ) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ] + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"] ) def test_kraus_gate_noise_on_QFT(self, method, device): """Test Kraus noise on a QFT circuit""" @@ -213,9 +199,7 @@ def test_kraus_gate_noise_on_QFT(self, method, device): @supported_methods(["statevector", "density_matrix"]) def test_kraus_gate_noise_on_QFT_cache_blocking(self, method, device): """Test Kraus noise on a QFT circuit with caceh blocking""" - self._test_kraus_gate_noise_on_QFT( - method=method, device=device, blocking_qubits=2 - ) + self._test_kraus_gate_noise_on_QFT(method=method, device=device, blocking_qubits=2) @supported_methods(ALL_METHODS) def test_clifford_circuit_noise(self, method, device): @@ -292,9 +276,6 @@ def test_kraus_circuit_noise(self, method, device): result = backend.run([qc0, qc1], shots=shots).result() self.assertSuccess(result) - probs = [ - {key: val / shots for key, val in result.get_counts(i).items()} - for i in range(2) - ] + probs = [{key: val / shots for key, val in result.get_counts(i).items()} for i in range(2)] self.assertDictAlmostEqual(target_probs0, probs[0], delta=0.1) self.assertDictAlmostEqual(target_probs1, probs[1], delta=0.1) diff --git a/test/terra/backends/aer_simulator/test_non_cliffords.py b/test/terra/backends/aer_simulator/test_non_cliffords.py index 62abdee751..94056b4b6a 100644 --- a/test/terra/backends/aer_simulator/test_non_cliffords.py +++ b/test/terra/backends/aer_simulator/test_non_cliffords.py @@ -82,9 +82,7 @@ def test_tdg_gate_nondeterministic_default_basis_gates(self, method, device): method=method, device=device, extended_stabilizer_metropolis_mixing_time=50 ) shots = 500 - circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic( - final_measure=True - ) + circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic(final_measure=True) circuits = transpile(circuits, backend, optimization_level=0) result = backend.run(circuits, shots=shots).result() targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) @@ -115,9 +113,7 @@ def test_ccx_gate_nondeterministic_default_basis_gates(self, method, device): method=method, device=device, extended_stabilizer_metropolis_mixing_time=100 ) shots = 500 - circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( - final_measure=True - ) + circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic(final_measure=True) circuits = transpile(circuits, backend, optimization_level=0) result = backend.run(circuits, shots=shots).result() targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) diff --git a/test/terra/backends/aer_simulator/test_options.py b/test/terra/backends/aer_simulator/test_options.py index 74d99b3d04..e82c00e2d3 100644 --- a/test/terra/backends/aer_simulator/test_options.py +++ b/test/terra/backends/aer_simulator/test_options.py @@ -144,8 +144,7 @@ def test_option_basis_gates(self, method): noise_gates = ["id", "sx", "x", "cx"] noise_model = NoiseModel(basis_gates=noise_gates) target_gates = ( - sorted(set(config.basis_gates).intersection(noise_gates)) - + config.custom_instructions + sorted(set(config.basis_gates).intersection(noise_gates)) + config.custom_instructions ) sim = self.backend(method=method, noise_model=noise_model) @@ -219,15 +218,9 @@ def test_mps_options(self): """Test MPS options""" shots = 4000 method = "matrix_product_state" - backend_swap_left = self.backend( - method=method, mps_swap_direction="mps_swap_left" - ) - backend_swap_right = self.backend( - method=method, mps_swap_direction="mps_swap_right" - ) - backend_approx = self.backend( - method=method, matrix_product_state_max_bond_dimension=8 - ) + backend_swap_left = self.backend(method=method, mps_swap_direction="mps_swap_left") + backend_swap_right = self.backend(method=method, mps_swap_direction="mps_swap_right") + backend_approx = self.backend(method=method, matrix_product_state_max_bond_dimension=8) # The test must be large enough and entangled enough so that # approximation actually truncates something n = 10 @@ -288,6 +281,4 @@ def test_statevector_memory(self): self.assertTrue( "Required memory: {}".format(2 ** (n - 20) * 16) in result.results[0].status ) - self.assertTrue( - "max memory: {}".format(max_memory_mb) in result.results[0].status - ) + self.assertTrue("max memory: {}".format(max_memory_mb) in result.results[0].status) diff --git a/test/terra/backends/aer_simulator/test_pauli_gate.py b/test/terra/backends/aer_simulator/test_pauli_gate.py index 306f63c731..d2480983ef 100644 --- a/test/terra/backends/aer_simulator/test_pauli_gate.py +++ b/test/terra/backends/aer_simulator/test_pauli_gate.py @@ -68,9 +68,7 @@ def test_pauli_gate(self, method, device, pauli): circuit.save_statevector(label=label) fidelity_fn = qi.state_fidelity - result = backend.run( - transpile(circuit, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circuit, backend, optimization_level=0), shots=1).result() # Check results success = getattr(result, "success", False) @@ -80,6 +78,4 @@ def test_pauli_gate(self, method, device, pauli): fidelity = fidelity_fn(target, data[label]) threshold = 0.9999 - self.assertGreater( - fidelity, threshold, msg="Fidelity {fidelity} not > {threshold}" - ) + self.assertGreater(fidelity, threshold, msg="Fidelity {fidelity} not > {threshold}") diff --git a/test/terra/backends/aer_simulator/test_reset.py b/test/terra/backends/aer_simulator/test_reset.py index a7cb4d0f60..746e7e3519 100644 --- a/test/terra/backends/aer_simulator/test_reset.py +++ b/test/terra/backends/aer_simulator/test_reset.py @@ -88,9 +88,7 @@ def test_reset_moving_qubits(self, method, device): backend = self.backend(method=method, device=device) # count output circuits shots = 1000 - circuits = ref_reset.reset_circuits_with_entangled_and_moving_qubits( - final_measure=True - ) + circuits = ref_reset.reset_circuits_with_entangled_and_moving_qubits(final_measure=True) targets = ref_reset.reset_counts_with_entangled_and_moving_qubits(shots) result = backend.run(circuits, shots=shots).result() self.assertSuccess(result) diff --git a/test/terra/backends/aer_simulator/test_save_amplitudes.py b/test/terra/backends/aer_simulator/test_save_amplitudes.py index 646fb1b281..dc3a38b36f 100644 --- a/test/terra/backends/aer_simulator/test_save_amplitudes.py +++ b/test/terra/backends/aer_simulator/test_save_amplitudes.py @@ -54,9 +54,7 @@ def _test_save_amplitudes(self, circuit, params, amp_squared, **options): circ.save_amplitudes(params, label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -64,21 +62,14 @@ def _test_save_amplitudes(self, circuit, params, amp_squared, **options): self.assertTrue(np.allclose(value, target)) @supported_methods( - ["automatic", "statevector", "matrix_product_state", "tensor_network"], - AMPLITUDES, + ["automatic", "statevector", "matrix_product_state", "tensor_network"], AMPLITUDES ) def test_save_amplitudes(self, method, device, params): """Test save_amplitudes instruction""" self._test_save_amplitudes(QFT(3), params, False, method=method, device=device) @supported_methods( - [ - "automatic", - "statevector", - "matrix_product_state", - "density_matrix", - "tensor_network", - ], + ["automatic", "statevector", "matrix_product_state", "density_matrix", "tensor_network"], AMPLITUDES, ) def test_save_amplitudes_squared(self, method, device, params): diff --git a/test/terra/backends/aer_simulator/test_save_density_matrix.py b/test/terra/backends/aer_simulator/test_save_density_matrix.py index 9855f4af02..5ab7518d8a 100644 --- a/test/terra/backends/aer_simulator/test_save_density_matrix.py +++ b/test/terra/backends/aer_simulator/test_save_density_matrix.py @@ -25,13 +25,7 @@ class QasmSaveDensityMatrixTests(SimulatorTestCase): """Test SaveDensityMatrix instruction.""" @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ] + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"] ) def test_save_density_matrix(self, method, device): """Test save density matrix for instruction""" @@ -52,9 +46,7 @@ def test_save_density_matrix(self, method, device): circ.save_density_matrix(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -62,13 +54,7 @@ def test_save_density_matrix(self, method, device): self.assertEqual(value, target) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ] + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"] ) def test_save_density_matrix_conditional(self, method, device): """Test conditional save density matrix instruction""" @@ -90,9 +76,7 @@ def test_save_density_matrix_conditional(self, method, device): } # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -101,13 +85,7 @@ def test_save_density_matrix_conditional(self, method, device): self.assertEqual(qi.DensityMatrix(state), target[key]) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ] + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"] ) def test_save_density_matrix_pershot(self, method, device): """Test pershot save density matrix instruction""" @@ -129,9 +107,7 @@ def test_save_density_matrix_pershot(self, method, device): # Run shots = 10 - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=shots - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -140,13 +116,7 @@ def test_save_density_matrix_pershot(self, method, device): self.assertEqual(qi.DensityMatrix(state), target) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ] + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"] ) def test_save_density_matrix_pershot_conditional(self, method, device): """Test pershot conditional save density matrix instruction""" @@ -169,9 +139,7 @@ def test_save_density_matrix_pershot_conditional(self, method, device): # Run shots = 10 - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=shots - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -202,9 +170,7 @@ def test_save_density_matrix_cache_blocking(self, method, device): circ.save_density_matrix(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) diff --git a/test/terra/backends/aer_simulator/test_save_expval.py b/test/terra/backends/aer_simulator/test_save_expval.py index 604e5f9c54..36131907f5 100644 --- a/test/terra/backends/aer_simulator/test_save_expval.py +++ b/test/terra/backends/aer_simulator/test_save_expval.py @@ -64,9 +64,7 @@ def _test_save_expval(self, circuit, oper, qubits, variance, **options): target = expval circ.save_expectation_value(oper, qubits, label=label) - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -171,13 +169,7 @@ def test_save_expval_var_stabilizer_hermitian(self, method, device, qubits): self._test_save_expval(circ, oper, qubits, True, method=method, device=device) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ], + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"], PAULI2, ) def test_save_expval_nonstabilizer_pauli(self, method, device, pauli): @@ -189,13 +181,7 @@ def test_save_expval_nonstabilizer_pauli(self, method, device, pauli): self._test_save_expval(circ, oper, qubits, False, method=method, device=device) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ], + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"], PAULI2, ) def test_save_expval_var_nonstabilizer_pauli(self, method, device, pauli): @@ -207,13 +193,7 @@ def test_save_expval_var_nonstabilizer_pauli(self, method, device, pauli): self._test_save_expval(circ, oper, qubits, True, method=method, device=device) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ], + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"], [[0, 1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1]], ) def test_save_expval_nonstabilizer_hermitian(self, method, device, qubits): @@ -224,13 +204,7 @@ def test_save_expval_nonstabilizer_hermitian(self, method, device, qubits): self._test_save_expval(circ, oper, qubits, False, method=method, device=device) @supported_methods( - [ - "automatic", - "statevector", - "density_matrix", - "matrix_product_state", - "tensor_network", - ], + ["automatic", "statevector", "density_matrix", "matrix_product_state", "tensor_network"], [[0, 1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1]], ) def test_save_expval_var_nonstabilizer_hermitian(self, method, device, qubits): @@ -281,9 +255,7 @@ def test_save_expval_stabilizer_pauli_cache_blocking(self, method, device, pauli ) @supported_methods(["statevector", "density_matrix"], PAULI2) - def test_save_expval_var_stabilizer_pauli_cache_blocking( - self, method, device, pauli - ): + def test_save_expval_var_stabilizer_pauli_cache_blocking(self, method, device, pauli): """Test Pauli expval_var for stabilizer circuit""" SEED = 5832 circ = qi.random_clifford(2, seed=SEED).to_circuit() diff --git a/test/terra/backends/aer_simulator/test_save_matrix_product_state.py b/test/terra/backends/aer_simulator/test_save_matrix_product_state.py index fa59388b3b..533c293cd8 100644 --- a/test/terra/backends/aer_simulator/test_save_matrix_product_state.py +++ b/test/terra/backends/aer_simulator/test_save_matrix_product_state.py @@ -29,15 +29,11 @@ def test_save_matrix_product_state(self, method, device): # Target mps structure target_qreg = [] - target_qreg.append( - (np.array([[1, 0]], dtype=complex), np.array([[0, 1]], dtype=complex)) - ) + target_qreg.append((np.array([[1, 0]], dtype=complex), np.array([[0, 1]], dtype=complex))) target_qreg.append( (np.array([[1], [0]], dtype=complex), np.array([[0], [1]], dtype=complex)) ) - target_qreg.append( - (np.array([[1]], dtype=complex), np.array([[0]], dtype=complex)) - ) + target_qreg.append((np.array([[1]], dtype=complex), np.array([[0]], dtype=complex))) target_lambda_reg = [] target_lambda_reg.append(np.array([1 / np.math.sqrt(2)], dtype=float)) @@ -54,9 +50,7 @@ def test_save_matrix_product_state(self, method, device): # Run shots = 10 - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=shots - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) diff --git a/test/terra/backends/aer_simulator/test_save_probabilities.py b/test/terra/backends/aer_simulator/test_save_probabilities.py index 1d12652665..4c32d6b524 100644 --- a/test/terra/backends/aer_simulator/test_save_probabilities.py +++ b/test/terra/backends/aer_simulator/test_save_probabilities.py @@ -41,9 +41,7 @@ def _test_save_probabilities(self, qubits, **options): label = "probs" circ.save_probabilities(qubits, label=label) - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -66,9 +64,7 @@ def _test_save_probabilities_dict(self, qubits, **options): # Snapshot circuit label = "probs" circ.save_probabilities_dict(qubits, label=label) - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -109,20 +105,12 @@ def test_save_probabilities_dict(self, method, device, qubits): def test_save_probabilities_cache_blocking(self, method, device, qubits): """Test save probabilities instruction""" self._test_save_probabilities( - qubits, - method=method, - device=device, - blocking_qubits=2, - max_parallel_threads=1, + qubits, method=method, device=device, blocking_qubits=2, max_parallel_threads=1 ) @supported_methods(["statevector", "density_matrix"], [[0, 1], [1, 0], [0], [1]]) def test_save_probabilities_dict_cache_blocking(self, method, device, qubits): """Test save probabilities dict instruction""" self._test_save_probabilities_dict( - qubits, - method=method, - device=device, - blocking_qubits=2, - max_parallel_threads=1, + qubits, method=method, device=device, blocking_qubits=2, max_parallel_threads=1 ) diff --git a/test/terra/backends/aer_simulator/test_save_state.py b/test/terra/backends/aer_simulator/test_save_state.py index 7620a44b1c..8c26330d8c 100644 --- a/test/terra/backends/aer_simulator/test_save_state.py +++ b/test/terra/backends/aer_simulator/test_save_state.py @@ -74,9 +74,7 @@ def test_save_state(self, method, device): circ.append(target_instr, range(num_qubits)) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -115,9 +113,7 @@ def test_save_state_cache_blocking(self, method, device): circ.append(target_instr, range(num_qubits)) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(method, simdata) diff --git a/test/terra/backends/aer_simulator/test_save_statevector.py b/test/terra/backends/aer_simulator/test_save_statevector.py index 24c45464a5..c8f374a54d 100644 --- a/test/terra/backends/aer_simulator/test_save_statevector.py +++ b/test/terra/backends/aer_simulator/test_save_statevector.py @@ -51,9 +51,7 @@ def test_save_statevector(self, method, device): circ.save_statevector(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -85,15 +83,10 @@ def test_save_statevector_conditional(self, method, device): circ.save_statevector(label=label, conditional=True) # Target statevector - target = { - "0x0": qi.Statevector([1, 0, 0, 0]), - "0x3": qi.Statevector([0, 0, 0, -1j]), - } + target = {"0x0": qi.Statevector([1, 0, 0, 0]), "0x3": qi.Statevector([0, 0, 0, -1j])} # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -130,9 +123,7 @@ def test_save_statevector_pershot(self, method, device): # Run shots = 10 - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=shots - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -172,9 +163,7 @@ def test_save_statevector_pershot_conditional(self, method, device): # Run shots = 10 - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=shots - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -206,9 +195,7 @@ def test_save_statevector_cache_blocking(self, method, device): circ.save_statevector(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) diff --git a/test/terra/backends/aer_simulator/test_save_statevector_dict.py b/test/terra/backends/aer_simulator/test_save_statevector_dict.py index debe281727..982f12e5d9 100644 --- a/test/terra/backends/aer_simulator/test_save_statevector_dict.py +++ b/test/terra/backends/aer_simulator/test_save_statevector_dict.py @@ -20,9 +20,7 @@ def statevec_as_dict(data): - return { - hex(int(key, 2)): val for key, val in qi.Statevector(data).to_dict().items() - } + return {hex(int(key, 2)): val for key, val in qi.Statevector(data).to_dict().items()} @ddt @@ -50,9 +48,7 @@ def test_save_statevector_dict(self, method, device): circ.save_statevector_dict(label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -75,15 +71,10 @@ def test_save_statevector_conditional(self, method, device): circ.save_statevector_dict(label, conditional=True) # Target statevector - target = { - "0x0": statevec_as_dict([1, 0, 0, 0]), - "0x3": statevec_as_dict([0, 0, 0, -1j]), - } + target = {"0x0": statevec_as_dict([1, 0, 0, 0]), "0x3": statevec_as_dict([0, 0, 0, -1j])} # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -113,9 +104,7 @@ def test_save_statevector_dict_pershot(self, method, device): # Run shots = 10 - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=shots - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -147,9 +136,7 @@ def test_save_statevector_dict_pershot_conditional(self, method, device): # Run shots = 10 - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=shots - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) diff --git a/test/terra/backends/aer_simulator/test_save_superop.py b/test/terra/backends/aer_simulator/test_save_superop.py index 17c9a2215c..693dd690ad 100644 --- a/test/terra/backends/aer_simulator/test_save_superop.py +++ b/test/terra/backends/aer_simulator/test_save_superop.py @@ -40,9 +40,7 @@ def test_save_superop(self, method, device): circ.save_superop(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) diff --git a/test/terra/backends/aer_simulator/test_save_unitary.py b/test/terra/backends/aer_simulator/test_save_unitary.py index 0726b26dec..947aed208b 100644 --- a/test/terra/backends/aer_simulator/test_save_unitary.py +++ b/test/terra/backends/aer_simulator/test_save_unitary.py @@ -40,9 +40,7 @@ def test_save_unitary(self, method, device): circ.save_unitary(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) diff --git a/test/terra/backends/aer_simulator/test_set_state.py b/test/terra/backends/aer_simulator/test_set_state.py index 58c385f999..fd77b825c4 100644 --- a/test/terra/backends/aer_simulator/test_set_state.py +++ b/test/terra/backends/aer_simulator/test_set_state.py @@ -39,9 +39,7 @@ def test_set_stabilizer_stabilizer_state(self, method, device, num_qubits): circ.save_stabilizer(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -63,9 +61,7 @@ def test_set_stabilizer_clifford(self, method, device, num_qubits): circ.save_clifford(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -87,9 +83,7 @@ def test_set_statevector(self, method, device, num_qubits): circ.save_statevector(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -111,9 +105,7 @@ def test_set_density_matrix(self, method, device, num_qubits): circ.save_density_matrix(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -135,9 +127,7 @@ def test_set_unitary(self, method, device, num_qubits): circ.save_unitary(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) @@ -159,9 +149,7 @@ def test_set_superop(self, method, device, num_qubits): circ.save_superop(label=label) # Run - result = backend.run( - transpile(circ, backend, optimization_level=0), shots=1 - ).result() + result = backend.run(transpile(circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) diff --git a/test/terra/backends/aer_simulator/test_standard_gates.py b/test/terra/backends/aer_simulator/test_standard_gates.py index 9ce14c4b38..51e5da6914 100644 --- a/test/terra/backends/aer_simulator/test_standard_gates.py +++ b/test/terra/backends/aer_simulator/test_standard_gates.py @@ -157,10 +157,7 @@ def _test_gate(self, gate, gates_dict, **options): gate_cls, num_angles, has_ctrl_qubits = gates_dict[gate] circuits = self.gate_circuits( - gate_cls, - num_angles=num_angles, - has_ctrl_qubits=has_ctrl_qubits, - rng=self.RNG, + gate_cls, num_angles=num_angles, has_ctrl_qubits=has_ctrl_qubits, rng=self.RNG ) label = "final" @@ -257,9 +254,7 @@ def test_nonclifford_gate_cache_blocking(self, method, device, gate): max_parallel_threads=1, ) - @supported_methods( - ["automatic", "statevector", "unitary", "tensor_network"], MC_GATES_DICT - ) + @supported_methods(["automatic", "statevector", "unitary", "tensor_network"], MC_GATES_DICT) def test_multictrl_gate(self, method, device, gate): """Test multi-controlled standard gates.""" self._test_gate(gate, MC_GATES_DICT, method=method, device=device) diff --git a/test/terra/backends/aer_simulator/test_thread_management.py b/test/terra/backends/aer_simulator/test_thread_management.py index ca80967afb..003cb92372 100644 --- a/test/terra/backends/aer_simulator/test_thread_management.py +++ b/test/terra/backends/aer_simulator/test_thread_management.py @@ -31,11 +31,7 @@ class TestThreadManagement(SimulatorTestCase): """AerSimulator thread tests.""" def backend_options_parallel( - self, - total_threads=None, - state_threads=None, - shot_threads=None, - exp_threads=None, + self, total_threads=None, state_threads=None, shot_threads=None, exp_threads=None ): """Backend options with thread manangement.""" opts = {} @@ -101,9 +97,7 @@ def test_max_memory_settings(self): result = backend.run(circuit, shots=100).result() max_mem_result = result.metadata.get("max_memory_mb") self.assertGreaterEqual( - max_mem_result, - int(system_memory / 2), - msg="Default 'max_memory_mb' is too small.", + max_mem_result, int(system_memory / 2), msg="Default 'max_memory_mb' is too small." ) self.assertLessEqual( max_mem_result, system_memory, msg="Default 'max_memory_mb' is too large." @@ -112,18 +106,14 @@ def test_max_memory_settings(self): def test_custom_memory_settings(self): """test max memory configuration""" max_mem_target = 128 - backend = self.backend( - max_memory_mb=max_mem_target, **self.backend_options_parallel() - ) + backend = self.backend(max_memory_mb=max_mem_target, **self.backend_options_parallel()) circuit = transpile(QuantumVolume(4, 1, seed=0), backend) circuit.measure_all() result = backend.run(circuit, shots=100).result() max_mem_result = result.metadata.get("max_memory_mb") self.assertEqual( - max_mem_result, - max_mem_target, - msg="Custom 'max_memory_mb' is not being set correctly.", + max_mem_result, max_mem_target, msg="Custom 'max_memory_mb' is not being set correctly." ) def available_threads(self): @@ -184,9 +174,7 @@ def test_parallel_defaults_single_meas(self): # Test single circuit, with measure in middle, no noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 - result = backend.run( - self.measure_in_middle_circuit(1), shots=10 * max_threads - ).result() + result = backend.run(self.measure_in_middle_circuit(1), shots=10 * max_threads).result() for threads in self.threads_used(result): target = { "experiments": 1, @@ -206,9 +194,7 @@ def test_parallel_defaults_multi_ideal(self): # Test multiple circuit, no noise # Parallel experiments always be 1 # parallel shots should always be 1 - result = backend.run( - max_threads * [self.dummy_circuit(1)], shots=10 * max_threads - ).result() + result = backend.run(max_threads * [self.dummy_circuit(1)], shots=10 * max_threads).result() for threads in self.threads_used(result): target = { "experiments": 1, @@ -309,9 +295,7 @@ def test_parallel_thread_assignment(self, custom_max_threads): # Test single circuit, with noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 - backend = self.backend( - noise_model=self.dummy_noise_model(), **parallel_opts - ) + backend = self.backend(noise_model=self.dummy_noise_model(), **parallel_opts) circuits = self.dummy_circuit(1) result = backend.run(circuits, shots=shots).result() for threads in self.threads_used(result): @@ -359,9 +343,7 @@ def test_parallel_thread_assignment(self, custom_max_threads): # Test multiple circuits, with noise # Parallel experiments always be greater than 1 # parallel shots should always be 1 - backend = self.backend( - noise_model=self.dummy_noise_model(), **parallel_opts - ) + backend = self.backend(noise_model=self.dummy_noise_model(), **parallel_opts) circuits = max_threads * [self.dummy_circuit(1)] result = backend.run(circuits, shots=shots).result() for threads in self.threads_used(result): @@ -419,9 +401,7 @@ def test_parallel_experiment_thread_multiple(self): # Test multiple circuit, no noise # Parallel experiments should take priority - result = backend.run( - max_threads * [self.dummy_circuit(1)], shots=10 * max_threads - ).result() + result = backend.run(max_threads * [self.dummy_circuit(1)], shots=10 * max_threads).result() for threads in self.threads_used(result): target = { "experiments": max_threads, @@ -486,7 +466,7 @@ def test_parallel_experiment_thread_mem_limit(self): backend = self.backend( method="statevector", max_memory_mb=1, - **self.backend_options_parallel(exp_threads=max_threads) + **self.backend_options_parallel(exp_threads=max_threads), ) # Test multiple circuits, with memory limitation @@ -510,15 +490,11 @@ def test_parallel_shot_thread_single_ideal(self): """Test parallel shot thread assignment""" max_threads = self.available_threads() - backend = self.backend( - **self.backend_options_parallel(shot_threads=max_threads) - ) + backend = self.backend(**self.backend_options_parallel(shot_threads=max_threads)) # Test single circuit # Parallel experiments and shots should always be 1 - result = backend.run( - max_threads * [self.dummy_circuit(1)], shots=10 * max_threads - ).result() + result = backend.run(max_threads * [self.dummy_circuit(1)], shots=10 * max_threads).result() for threads in self.threads_used(result): target = { "experiments": 1, @@ -534,15 +510,11 @@ def test_parallel_shot_thread_multi_ideal(self): """Test parallel shot thread assignment""" max_threads = self.available_threads() - backend = self.backend( - **self.backend_options_parallel(shot_threads=max_threads) - ) + backend = self.backend(**self.backend_options_parallel(shot_threads=max_threads)) # Test multiple circuit, no noise # Parallel experiments and shots should always be 1 - result = backend.run( - max_threads * [self.dummy_circuit(1)], shots=10 * max_threads - ).result() + result = backend.run(max_threads * [self.dummy_circuit(1)], shots=10 * max_threads).result() for threads in self.threads_used(result): target = { "experiments": 1, @@ -560,14 +532,12 @@ def test_parallel_shot_thread_multi_noise(self): max_threads = self.available_threads() backend = self.backend( noise_model=self.dummy_noise_model(), - **self.backend_options_parallel(shot_threads=max_threads) + **self.backend_options_parallel(shot_threads=max_threads), ) # Test multiple circuits, with noise # Parallel shots should take priority - result = backend.run( - max_threads * [self.dummy_circuit(1)], shots=10 * max_threads - ).result() + result = backend.run(max_threads * [self.dummy_circuit(1)], shots=10 * max_threads).result() for threads in self.threads_used(result): target = { "experiments": 1, @@ -585,7 +555,7 @@ def test_parallel_shot_thread_multi_meas(self): max_threads = self.available_threads() backend = self.backend( noise_model=self.dummy_noise_model(), - **self.backend_options_parallel(shot_threads=max_threads) + **self.backend_options_parallel(shot_threads=max_threads), ) # Test multiple circuit, with measure in middle, no noise @@ -633,25 +603,19 @@ def _test_qasm_explicit_parallelization(self): """test disabling parallel shots because max_parallel_shots is 1""" backend = self.backend( noise_model=self.dummy_noise_model(), - **self.backend_options_parallel(shot_threads=1, exp_threads=1) + **self.backend_options_parallel(shot_threads=1, exp_threads=1), ) # Test circuit shots = multiprocessing.cpu_count() circuit = QuantumVolume(16, 1, seed=0) circuit.measure_all() - run_opts = { - "_parallel_experiments": 2, - "_parallel_shots": 3, - "_parallel_state_update": 4, - } + run_opts = {"_parallel_experiments": 2, "_parallel_shots": 3, "_parallel_state_update": 4} result = self.backend(circuit, shots=shots, **run_opts).result() if result.metadata["omp_enabled"]: self.assertEqual( - result.metadata["parallel_experiments"], - 2, - msg="parallel_experiments should be 2", + result.metadata["parallel_experiments"], 2, msg="parallel_experiments should be 2" ) self.assertEqual( result.to_dict()["results"][0]["metadata"]["parallel_shots"], diff --git a/test/terra/backends/aer_simulator/test_truncate.py b/test/terra/backends/aer_simulator/test_truncate.py index 1cd06c72df..5963143580 100644 --- a/test/terra/backends/aer_simulator/test_truncate.py +++ b/test/terra/backends/aer_simulator/test_truncate.py @@ -61,9 +61,7 @@ def test_truncate_ideal_sparse_circuit(self): result = backend.run(circuit, shots=1).result() metadata = result.results[0].metadata - self.assertEqual( - metadata["num_qubits"], 2, msg="wrong number of truncated qubits." - ) + self.assertEqual(metadata["num_qubits"], 2, msg="wrong number of truncated qubits.") self.assertEqual( metadata["active_input_qubits"], [10, 20], msg="incorrect truncated qubits." ) @@ -84,9 +82,7 @@ def test_truncate_default(self): ] noise_model = NoiseModel.from_backend(self.device_backend()) backend = self.backend(noise_model=noise_model) - circuit = transpile( - self.create_circuit_for_truncate(), backend, coupling_map=coupling_map - ) + circuit = transpile(self.create_circuit_for_truncate(), backend, coupling_map=coupling_map) result = backend.run(circuit, shots=1).result() metadata = result.results[0].metadata @@ -120,9 +116,7 @@ def test_truncate_disable_noise(self): ] noise_model = NoiseModel.from_backend(self.device_backend()) backend = self.backend(noise_model=noise_model, enable_truncation=False) - circuit = transpile( - self.create_circuit_for_truncate(), backend, coupling_map=coupling_map - ) + circuit = transpile(self.create_circuit_for_truncate(), backend, coupling_map=coupling_map) result = backend.run(circuit, shots=100).result() metadata = result.results[0].metadata diff --git a/test/terra/backends/aer_simulator/test_unitary_gate.py b/test/terra/backends/aer_simulator/test_unitary_gate.py index 4bc6f4ee0b..9e92410ae4 100644 --- a/test/terra/backends/aer_simulator/test_unitary_gate.py +++ b/test/terra/backends/aer_simulator/test_unitary_gate.py @@ -45,9 +45,7 @@ def test_unitary_gate(self, method, device): """Test simulation with unitary gate circuit instructions.""" backend = self.backend(method=method, device=device) shots = 100 - circuits = ref_unitary_gate.unitary_gate_circuits_deterministic( - final_measure=True - ) + circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=True) targets = ref_unitary_gate.unitary_gate_counts_deterministic(shots) circuits = transpile(circuits, backend) result = backend.run(circuits, shots=shots).result() @@ -99,9 +97,7 @@ def test_diagonal_gate(self, method, device): """Test simulation with unitary gate circuit instructions.""" backend = self.backend(method=method, device=device) shots = 100 - circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic( - final_measure=True - ) + circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic(final_measure=True) targets = ref_diagonal_gate.diagonal_gate_counts_deterministic(shots) circuits = transpile(circuits, backend) result = backend.run(circuits, shots=shots).result() diff --git a/test/terra/backends/aer_simulator/test_wrapper_statevector_simulator.py b/test/terra/backends/aer_simulator/test_wrapper_statevector_simulator.py index 7f053ab090..48f6eb29ef 100644 --- a/test/terra/backends/aer_simulator/test_wrapper_statevector_simulator.py +++ b/test/terra/backends/aer_simulator/test_wrapper_statevector_simulator.py @@ -216,9 +216,7 @@ def test_conditional_unitary_132bit(self, device): def test_unitary_gate(self, device): """Test simulation with unitary gate circuit instructions.""" backend = self.backend(device=device) - circuits = ref_unitary_gate.unitary_gate_circuits_deterministic( - final_measure=False - ) + circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=False) circuits = transpile(circuits, backend, optimization_level=1) result = backend.run(circuits, shots=1).result() targets = ref_unitary_gate.unitary_gate_statevector_deterministic() @@ -229,9 +227,7 @@ def test_unitary_gate(self, device): def test_unitary_gate_circuit_run(self, device): """Test simulation with unitary gate circuit instructions.""" backend = self.backend(device=device) - circuits = ref_unitary_gate.unitary_gate_circuits_deterministic( - final_measure=False - ) + circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=False) circuits = transpile(circuits, backend, optimization_level=1) result = backend.run(circuits, shots=1).result() targets = ref_unitary_gate.unitary_gate_statevector_deterministic() @@ -242,9 +238,7 @@ def test_unitary_gate_circuit_run(self, device): def test_diagonal_gate(self, device): """Test simulation with diagonal gate circuit instructions.""" backend = self.backend(device=device) - circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic( - final_measure=False - ) + circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic(final_measure=False) circuits = transpile(circuits, backend, optimization_level=1) result = backend.run(circuits, shots=1).result() targets = ref_diagonal_gate.diagonal_gate_statevector_deterministic() diff --git a/test/terra/backends/aer_simulator/test_wrapper_unitary_simulator.py b/test/terra/backends/aer_simulator/test_wrapper_unitary_simulator.py index 98d28daf8b..c3100d45b8 100644 --- a/test/terra/backends/aer_simulator/test_wrapper_unitary_simulator.py +++ b/test/terra/backends/aer_simulator/test_wrapper_unitary_simulator.py @@ -38,9 +38,7 @@ class TestUnitarySimulator(SimulatorTestCase): def test_unitary_gate(self, device): """Test simulation with unitary gate circuit instructions.""" backend = self.backend(device=device) - circuits = ref_unitary_gate.unitary_gate_circuits_deterministic( - final_measure=False - ) + circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=False) circuits = transpile(circuits, backend, optimization_level=1) result = backend.run(circuits, shots=1).result() targets = ref_unitary_gate.unitary_gate_unitary_deterministic() @@ -51,9 +49,7 @@ def test_unitary_gate(self, device): def test_unitary_gate_circuit_run(self, device): """Test simulation with unitary gate circuit instructions.""" backend = self.backend(device=device) - circuits = ref_unitary_gate.unitary_gate_circuits_deterministic( - final_measure=False - ) + circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=False) circuits = transpile(circuits, backend, optimization_level=1) result = backend.run(circuits, shots=1).result() targets = ref_unitary_gate.unitary_gate_unitary_deterministic() @@ -64,9 +60,7 @@ def test_unitary_gate_circuit_run(self, device): def test_diagonal_gate(self, device): """Test simulation with diagonal gate circuit instructions.""" backend = self.backend(device=device) - circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic( - final_measure=False - ) + circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic(final_measure=False) circuits = transpile(circuits, backend, optimization_level=1) result = backend.run(circuits, shots=1).result() targets = ref_diagonal_gate.diagonal_gate_unitary_deterministic() diff --git a/test/terra/backends/pulse_sim_independent.py b/test/terra/backends/pulse_sim_independent.py index 31892a67a8..cca1a7b5a0 100644 --- a/test/terra/backends/pulse_sim_independent.py +++ b/test/terra/backends/pulse_sim_independent.py @@ -67,9 +67,7 @@ def generator_in_frame(drift, control_ops, chan_vals, diag_frame, t): return np.diag(U_inv) @ G @ np.diag(U) -def simulate_system( - y0, drift, control_ops, channel_freqs, channel_samples, dt, diag_frame -): +def simulate_system(y0, drift, control_ops, channel_freqs, channel_samples, dt, diag_frame): """Simulate the DE y' = G(t) @ y, where G(t) = drift + a0(t) * A0 + ... + ak(t) Ak, where control_ops = [A0, ..., Ak], and the aj(t) are the values of the signals specified by channel_freqs, channel_samples, and dt @@ -125,9 +123,7 @@ def simulate_1q_model(y0, q_freq, r, drive_freqs, drive_samples, dt): frame_op = -1j * 2 * np.pi * drive_freqs[0] * np.array([1.0, -1.0]) / 2 - return simulate_system( - y0, drift, control_ops, drive_freqs, drive_samples, dt, frame_op - ) + return simulate_system(y0, drift, control_ops, drive_freqs, drive_samples, dt, frame_op) def simulate_2q_exchange_model(y0, q_freqs, r, j, drive_freqs, drive_samples, dt): @@ -151,14 +147,10 @@ def simulate_2q_exchange_model(y0, q_freqs, r, j, drive_freqs, drive_samples, dt control_ops = -1j * 2 * np.pi * r * np.array([IX, XI]) / 2 - return simulate_system( - y0, drift, control_ops, drive_freqs, drive_samples, dt, drift_diag - ) + return simulate_system(y0, drift, control_ops, drive_freqs, drive_samples, dt, drift_diag) -def simulate_3d_oscillator_model( - y0, osc_freq, anharm, r, drive_freqs, drive_samples, dt -): +def simulate_3d_oscillator_model(y0, osc_freq, anharm, r, drive_freqs, drive_samples, dt): """Simulate a basic duffing odscillator model truncated at 3 dimensions, with H(t) = 2 pi osc_freq[0] a^\dagger a + 2 pi anharm (a^\dagger a)(a^dagger a - 1) + 2 pi r D(t) (a + a^\dagger) @@ -174,6 +166,4 @@ def simulate_3d_oscillator_model( osc_X = np.array([[0.0, 1.0, 0.0], [1.0, 0.0, np.sqrt(2)], [0.0, np.sqrt(2), 0.0]]) control_ops = -1j * np.array([2 * np.pi * r * osc_X]) - return simulate_system( - y0, drift, control_ops, drive_freqs, drive_samples, dt, drift_diag - ) + return simulate_system(y0, drift, control_ops, drive_freqs, drive_samples, dt, drift_diag) diff --git a/test/terra/backends/test_config_pulse_simulator.py b/test/terra/backends/test_config_pulse_simulator.py index 354ecdc3d2..b905ffe785 100644 --- a/test/terra/backends/test_config_pulse_simulator.py +++ b/test/terra/backends/test_config_pulse_simulator.py @@ -61,9 +61,7 @@ def test_from_backend(self): if key == "backend_name": self.assertEqual(sim_dict[key], "pulse_simulator(fake_athens)") elif key == "description": - desc = ( - "A Pulse-based simulator configured from the backend: fake_athens" - ) + desc = "A Pulse-based simulator configured from the backend: fake_athens" self.assertEqual(sim_dict[key], desc) elif key == "simulator": self.assertTrue(sim_dict[key]) @@ -83,14 +81,10 @@ def test_from_backend(self): for entry_key in entry: if entry_key == "samples": self.assertTrue( - np.array_equal( - entry[entry_key], backend_dict[key][idx][entry_key] - ) + np.array_equal(entry[entry_key], backend_dict[key][idx][entry_key]) ) else: - self.assertTrue( - entry[entry_key] == backend_dict[key][idx][entry_key] - ) + self.assertTrue(entry[entry_key] == backend_dict[key][idx][entry_key]) else: self.assertEqual(sim_dict[key], backend_dict[key]) @@ -158,9 +152,7 @@ def test_parametric_pulses_error(self): backend = PulseSimulator.from_backend(fake_backend) # reset parametric_pulses option - backend.set_option( - "parametric_pulses", fake_backend.configuration().parametric_pulses - ) + backend.set_option("parametric_pulses", fake_backend.configuration().parametric_pulses) qc = QuantumCircuit(2) qc.x(0) @@ -220,9 +212,7 @@ def test_set_system_model_from_backend(self): # check that system model properties have been imported self.assertEqual(armonk_sim.configuration().dt, system_model.dt) - self.assertEqual( - armonk_sim.configuration().u_channel_lo, system_model.u_channel_lo - ) + self.assertEqual(armonk_sim.configuration().u_channel_lo, system_model.u_channel_lo) def test_set_system_model_in_constructor(self): """Test setting system model when constructing.""" @@ -246,9 +236,7 @@ def test_set_system_model_in_constructor(self): # check that system model properties have been imported self.assertEqual(test_sim.configuration().dt, system_model.dt) - self.assertEqual( - test_sim.configuration().u_channel_lo, system_model.u_channel_lo - ) + self.assertEqual(test_sim.configuration().u_channel_lo, system_model.u_channel_lo) def test_set_system_model_after_construction(self): """Test setting the system model after construction.""" @@ -272,9 +260,7 @@ def test_set_system_model_after_construction(self): # check that system model properties have been imported self.assertEqual(test_sim._system_model, system_model) self.assertEqual(test_sim.configuration().dt, system_model.dt) - self.assertEqual( - test_sim.configuration().u_channel_lo, system_model.u_channel_lo - ) + self.assertEqual(test_sim.configuration().u_channel_lo, system_model.u_channel_lo) # next, construct a pulse simulator with a config containing a Hamiltonian and observe # warnings @@ -293,9 +279,7 @@ def test_set_system_model_after_construction(self): self.assertTrue("inconsistencies" in str(w[-1].message)) self.assertEqual(test_sim.configuration().dt, system_model.dt) - self.assertEqual( - test_sim.configuration().u_channel_lo, system_model.u_channel_lo - ) + self.assertEqual(test_sim.configuration().u_channel_lo, system_model.u_channel_lo) def test_validation_num_acquires(self): """Test that validation fails if 0 or >1 acquire is given in a schedule.""" @@ -331,10 +315,7 @@ def test_run_simulation_from_backend(self): freq_est = 4.97e9 drive_est = 6.35e7 armonk_backend.defaults().qubit_freq_est = [freq_est] - armonk_backend.configuration().hamiltonian["h_str"] = [ - "wq0*0.5*(I0-Z0)", - "omegad0*X0||D0", - ] + armonk_backend.configuration().hamiltonian["h_str"] = ["wq0*0.5*(I0-Z0)", "omegad0*X0||D0"] armonk_backend.configuration().hamiltonian["vars"] = { "wq0": 2 * np.pi * freq_est, "omegad0": drive_est, @@ -380,10 +361,7 @@ def _system_model_1Q(self, omega_0=5.0, r=0.02): dt = 1.0 return PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) def _1Q_schedule(self, total_samples=100, amp=1.0, num_acquires=1): @@ -402,8 +380,7 @@ def _1Q_schedule(self, total_samples=100, amp=1.0, num_acquires=1): schedule |= Play(Waveform(amp * np.ones(total_samples)), DriveChannel(0)) for _ in range(num_acquires): schedule |= ( - Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) - << schedule.duration + Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << schedule.duration ) return schedule diff --git a/test/terra/backends/test_parameterized_qobj.py b/test/terra/backends/test_parameterized_qobj.py index 8913806f95..3af19f304d 100644 --- a/test/terra/backends/test_parameterized_qobj.py +++ b/test/terra/backends/test_parameterized_qobj.py @@ -69,9 +69,7 @@ def parameterized_qobj( for circuit in circuits: circuit.save_statevector(pershot=pershot) params = [param1, [], [], [], param2] - qobj = assemble( - circuits, backend=backend, shots=shots, parameterizations=params - ) + qobj = assemble(circuits, backend=backend, shots=shots, parameterizations=params) return qobj def test_parameterized_qobj_qasm_save_expval(self): @@ -82,9 +80,7 @@ def test_parameterized_qobj_qasm_save_expval(self): value_targets = save_expval_pre_meas_values() * 3 backend = AerSimulator() - qobj = self.parameterized_qobj( - backend=backend, shots=1000, measure=True, snapshot=True - ) + 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) @@ -92,9 +88,7 @@ def test_parameterized_qobj_qasm_save_expval(self): 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 - ) + 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) @@ -136,9 +130,7 @@ def test_run_path(self): circuit.cx(0, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] - res = backend.run( - circuit, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run(circuit, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() self.assertEqual(counts, [{"00": shots}, {"11": shots}, {"00": shots}]) @@ -156,9 +148,7 @@ def test_run_path_already_bound_parameter_expression(self): circuit.cx(0, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] - res = backend.run( - circuit, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run(circuit, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() self.assertEqual(counts, [{"00": shots}, {"11": shots}, {"00": shots}]) @@ -188,9 +178,7 @@ def test_run_path_with_expressions(self): circuit.rz(theta_squared, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] - res = backend.run( - circuit, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run(circuit, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() self.assertEqual(counts, [{"00": shots}, {"11": shots}, {"00": shots}]) @@ -207,9 +195,7 @@ def test_run_path_with_expressions_multiple_params_per_instruction(self): circuit.u(theta, theta_squared, theta, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] - res = backend.run( - circuit, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run(circuit, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() self.assertEqual(counts, [{"00": shots}, {"01": shots}, {"00": shots}]) @@ -227,9 +213,7 @@ def test_run_path_with_more_params_than_expressions(self): circuit.ry(phi, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi], phi: [0, 1, pi]}] - res = backend.run( - circuit, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run(circuit, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() for index, expected in enumerate( [{"00": shots}, {"01": 0.25 * shots, "11": 0.75 * shots}, {"10": shots}] @@ -246,9 +230,7 @@ def test_run_path_multiple_circuits(self): circuit.cx(0, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] * 3 - res = backend.run( - [circuit] * 3, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run([circuit] * 3, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() self.assertEqual(counts, [{"00": shots}, {"11": shots}, {"00": shots}] * 3) @@ -300,9 +282,7 @@ def test_run_path_with_expressions_multiple_circuits(self): circuit.rz(theta_squared, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] * 3 - res = backend.run( - [circuit] * 3, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run([circuit] * 3, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() self.assertEqual(counts, [{"00": shots}, {"11": shots}, {"00": shots}] * 3) @@ -319,9 +299,7 @@ def test_run_path_with_expressions_multiple_params_per_instruction(self): circuit.u(theta, theta_squared, theta, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] * 3 - res = backend.run( - [circuit] * 3, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run([circuit] * 3, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() self.assertEqual(counts, [{"00": shots}, {"01": shots}, {"00": shots}] * 3) @@ -339,9 +317,7 @@ def test_run_path_with_more_params_than_expressions_multiple_circuits(self): circuit.ry(phi, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi], phi: [0, 1, pi]}] * 3 - res = backend.run( - [circuit] * 3, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run([circuit] * 3, shots=shots, parameter_binds=parameter_binds).result() counts = res.get_counts() for index, expected in enumerate( [{"00": shots}, {"01": 0.25 * shots, "11": 0.75 * shots}, {"10": shots}] * 3 @@ -359,9 +335,7 @@ def test_run_path_multiple_circuits_mismatch_length(self): circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] with self.assertRaises(AerError): - backend.run( - [circuit] * 3, shots=shots, parameter_binds=[parameter_binds] - ).result() + backend.run([circuit] * 3, shots=shots, parameter_binds=[parameter_binds]).result() def test_run_path_with_truncation(self): """Test parameterized circuits with truncation""" @@ -376,16 +350,12 @@ def test_run_path_with_truncation(self): circuit.ry(theta, q) circuit.cx(0, 1) circuit.cx(1, 2) - circuit.append( - SaveStatevector(3, label="sv", pershot=False, conditional=False), range(3) - ) + circuit.append(SaveStatevector(3, label="sv", pershot=False, conditional=False), range(3)) param_map = {theta: [0.1 * i for i in range(3)]} param_sets = [{theta: 0.1 * i} for i in range(3)] - resolved_circuits = [ - circuit.bind_parameters(param_set) for param_set in param_sets - ] + resolved_circuits = [circuit.bind_parameters(param_set) for param_set in param_sets] result = backend.run(circuit, parameter_binds=[param_map]).result() self.assertSuccess(result) @@ -397,9 +367,7 @@ def test_run_path_with_truncation(self): metadata = actual_result.metadata self.assertEqual(metadata["active_input_qubits"], [q for q in range(3)]) for i in range(3): - self.assertEqual( - result.data(i)["sv"], result_without_parameters.data(i)["sv"] - ) + self.assertEqual(result.data(i)["sv"], result_without_parameters.data(i)["sv"]) def test_different_seed(self): """Test parameterized circuits have different seeds""" @@ -411,9 +379,7 @@ def test_different_seed(self): circuit.cx(0, 1) circuit.measure_all() parameter_binds = [{theta: [0, pi, 2 * pi]}] - res = backend.run( - circuit, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run(circuit, shots=shots, parameter_binds=parameter_binds).result() seed_simulator_list = [result.seed_simulator for result in res.results] self.assertEqual(len(seed_simulator_list), len(np.unique(seed_simulator_list))) @@ -423,9 +389,7 @@ def test_different_seed(self): parameter_binds=parameter_binds, seed_simulator=seed_simulator_list[0], ).result() - self.assertEqual( - seed_simulator_list, [result.seed_simulator for result in res2.results] - ) + self.assertEqual(seed_simulator_list, [result.seed_simulator for result in res2.results]) def test_run_empty(self): """Test parameterized circuit with empty dict path via backed.run()""" @@ -438,9 +402,7 @@ def test_run_empty(self): circuit.measure_all() parameter_binds = [{}] with self.assertRaises(AerError): - res = backend.run( - circuit, shots=shots, parameter_binds=parameter_binds - ).result() + res = backend.run(circuit, shots=shots, parameter_binds=parameter_binds).result() if __name__ == "__main__": diff --git a/test/terra/backends/test_pulse_simulator.py b/test/terra/backends/test_pulse_simulator.py index 0596184ab0..cedb30d18f 100644 --- a/test/terra/backends/test_pulse_simulator.py +++ b/test/terra/backends/test_pulse_simulator.py @@ -80,9 +80,7 @@ def test_circuit_conversion(self): qc.measure_all() tqc = transpile(qc, pulse_sim) result = pulse_sim.run(tqc, shots=1024).result() - self.assertDictAlmostEqual( - result.get_counts(0), {"0": 512, "1": 512}, delta=128 - ) + self.assertDictAlmostEqual(result.get_counts(0), {"0": 512, "1": 512}, delta=128) def test_multiple_circuit_conversion(self): with self.assertWarns(DeprecationWarning): @@ -97,9 +95,7 @@ def test_multiple_circuit_conversion(self): counts = result.get_counts() self.assertEqual(5, len(counts)) for i in range(5): - self.assertDictAlmostEqual( - result.get_counts(i), {"0": 512, "1": 512}, delta=128 - ) + self.assertDictAlmostEqual(result.get_counts(i), {"0": 512, "1": 512}, delta=128) # --------------------------------------------------------------------- # Test single qubit gates @@ -124,11 +120,7 @@ def test_x_gate(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_d], - shots=256, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_d], shots=256 ) # set up constant pulse for doing a pi pulse sched = self._1Q_constant_sched(total_samples) @@ -141,9 +133,7 @@ def test_x_gate(self): indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, 1.0) # approximate analytic solution - phases = np.exp( - -1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2 - ) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2) approx_yf = phases * np.array([0.0, -1j]) # test final state @@ -176,11 +166,7 @@ def test_x_gate_rwa(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_d], - shots=1, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_d], shots=1 ) # set up constant pulse for doing a pi pulse sched = self._1Q_constant_sched(total_samples) @@ -213,11 +199,7 @@ def test_x_half_gate(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_d], - shots=256, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_d], shots=256 ) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) @@ -230,9 +212,7 @@ def test_x_half_gate(self): indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), samples, 1.0) # approximate analytic solution - phases = np.exp( - -1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2 - ) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2) approx_yf = phases * (expm(-1j * (np.pi / 4) * self.X) @ y0) # test final state @@ -264,11 +244,7 @@ def test_y_half_gate(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_d], - shots=256, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_d], shots=256 ) # set up constant pulse for doing a pi pulse sched = self._1Q_constant_sched(total_samples, amp=1j) @@ -281,9 +257,7 @@ def test_y_half_gate(self): indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), samples, 1.0) # approximate analytic solution - phases = np.exp( - -1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2 - ) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2) approx_yf = phases * (expm(-1j * (np.pi / 4) * self.Y) @ y0) # test final state @@ -319,11 +293,7 @@ def test_1Q_noise(self): system_model=self._system_model_1Q(omega_0, r), noise_model=noise_model ) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_d], - shots=10, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_d], shots=10 ) # set up constant pulse for doing a pi pulse @@ -356,18 +326,12 @@ def test_unitary_parallel(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_d], - shots=256, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_d], shots=256 ) # set up constant pulse for doing a pi pulse schedule = self._1Q_constant_sched(total_samples) - result = pulse_sim.run( - [schedule, schedule], initial_state=y0, seed=seed - ).result() + result = pulse_sim.run([schedule, schedule], initial_state=y0, seed=seed).result() # test results, checking both runs in parallel counts = result.get_counts() @@ -399,9 +363,7 @@ def scale_test(scale): # set up simulator system_model = self._system_model_1Q(omega_0, r) with self.assertWarns(DeprecationWarning): - pulse_sim = PulseSimulator( - system_model=self._system_model_1Q(omega_0, r) - ) + pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) pulse_sim.set_options(dt=scale) pulse_sim.set_options( meas_level=2, @@ -420,20 +382,14 @@ def scale_test(scale): # set up and run independent simulation samples = np.ones((total_samples, 1)) - indep_yf = simulate_1q_model( - y0, omega_0, r, np.array([omega_0]), samples, scale - ) + indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, scale) # approximate analytic solution - phases = np.exp( - -1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2 - ) + phases = np.exp(-1j * 2 * np.pi * omega_0 * total_samples * np.array([1.0, -1.0]) / 2) approx_yf = phases * np.array([0.0, -1j]) # test final state - self.assertGreaterEqual( - state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5 - ) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5) self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) counts = result.get_counts() @@ -476,9 +432,7 @@ def test_arbitrary_constant_drive(self): shots=1, ) - schedule = self._1Q_constant_sched( - total_samples, amp=np.exp(-1j * phase_vals[i]) - ) + schedule = self._1Q_constant_sched(total_samples, amp=np.exp(-1j * phase_vals[i])) result = pulse_sim.run(schedule, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() @@ -491,13 +445,7 @@ def test_arbitrary_constant_drive(self): # approximate analytic solution phases = np.exp( - -1j - * 2 - * np.pi - * omega_d_vals[i] - * total_samples - * np.array([1.0, -1.0]) - / 2 + -1j * 2 * np.pi * omega_d_vals[i] * total_samples * np.array([1.0, -1.0]) / 2 ) detuning = omega_0 - omega_d_vals[i] amp = np.exp(-1j * phase_vals[i]) @@ -512,9 +460,7 @@ def test_arbitrary_constant_drive(self): approx_yf = phases * (expm(-1j * rwa_ham * total_samples) @ y0) # test final state - self.assertGreaterEqual( - state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5 - ) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5) self.assertGreaterEqual(state_fidelity(pulse_sim_yf, approx_yf), 0.99) def test_3d_oscillator(self): @@ -533,11 +479,7 @@ def test_3d_oscillator(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=system_model) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[freq], - shots=1, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[freq], shots=1 ) schedule = self._1Q_constant_sched(total_samples) @@ -547,9 +489,7 @@ def test_3d_oscillator(self): # set up and run independent simulation y0 = np.array([1.0, 0.0, 0.0]) samples = np.ones((total_samples, 1)) - indep_yf = simulate_3d_oscillator_model( - y0, freq, anharm, r, np.array([freq]), samples, 1.0 - ) + indep_yf = simulate_3d_oscillator_model(y0, freq, anharm, r, np.array([freq]), samples, 1.0) # test final state self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5) @@ -562,11 +502,7 @@ def test_3d_oscillator(self): system_model = self._system_model_3d_oscillator(freq, anharm, r) pulse_sim.set_options(system_model=system_model) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[freq], - shots=1, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[freq], shots=1 ) schedule = self._1Q_constant_sched(total_samples) @@ -574,9 +510,7 @@ def test_3d_oscillator(self): pulse_sim_yf = result.get_statevector() samples = np.ones((total_samples, 1)) - indep_yf = simulate_3d_oscillator_model( - y0, freq, anharm, r, np.array([freq]), samples, 1.0 - ) + indep_yf = simulate_3d_oscillator_model(y0, freq, anharm, r, np.array([freq]), samples, 1.0) # test final state self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - 10**-5) @@ -640,9 +574,7 @@ def test_subsystem_restriction(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=system_model) - schedule = self._3Q_constant_sched( - total_samples, u_idx=0, subsystem_list=subsystem_list - ) + schedule = self._3Q_constant_sched(total_samples, u_idx=0, subsystem_list=subsystem_list) result = pulse_sim.run( [schedule], @@ -683,9 +615,7 @@ def test_subsystem_restriction(self): y0 = np.kron(np.array([1.0, 0.0]), np.array([0.0, 1.0])) pulse_sim.set_options(system_model=system_model) - schedule = self._3Q_constant_sched( - total_samples, u_idx=1, subsystem_list=subsystem_list - ) + schedule = self._3Q_constant_sched(total_samples, u_idx=1, subsystem_list=subsystem_list) result = pulse_sim.run( [schedule], meas_level=2, @@ -732,21 +662,14 @@ def test_simulation_without_variables(self): dt = 1.0 system_model = PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator( system_model=system_model, initial_state=np.array([1.0, 0.0]), seed=9000 ) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[1.0], - shots=256, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[1.0], shots=256 ) # set up schedule and qobj @@ -780,15 +703,9 @@ def test_meas_level_1(self): y0 = np.array([1.0, 0.0]) with self.assertWarns(DeprecationWarning): - pulse_sim = PulseSimulator( - system_model=system_model, initial_state=y0, seed=9000 - ) + pulse_sim = PulseSimulator(system_model=system_model, initial_state=y0, seed=9000) pulse_sim.set_options( - meas_level=1, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[1.0], - shots=shots, + meas_level=1, meas_return="single", meas_map=[[0]], qubit_lo_freq=[1.0], shots=shots ) result = pulse_sim.run(schedule).result() pulse_sim_yf = result.get_statevector() @@ -839,11 +756,7 @@ def test_gaussian_drive(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=self._system_model_1Q(omega_0, r)) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_d], - shots=1, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_d], shots=1 ) for gauss_sigma in gauss_sigmas: @@ -855,22 +768,16 @@ def test_gaussian_drive(self): # construct schedule schedule = Schedule() schedule |= Play(drive_pulse, DriveChannel(0)) - schedule |= ( - Acquire(1, AcquireChannel(0), MemorySlot(0)) << schedule.duration - ) + schedule |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << schedule.duration result = pulse_sim.run(schedule, initial_state=y0, seed=seed).result() pulse_sim_yf = result.get_statevector() # run independent simulation - yf = simulate_1q_model( - y0, omega_0, r, np.array([omega_d]), gaussian_samples, 1.0 - ) + yf = simulate_1q_model(y0, omega_0, r, np.array([omega_d]), gaussian_samples, 1.0) # Check fidelity of statevectors - self.assertGreaterEqual( - state_fidelity(pulse_sim_yf, yf), 1 - (10**-5) - ) + self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) def test_2Q_exchange(self): r"""Test a more complicated 2q simulation""" @@ -901,10 +808,7 @@ def test_2Q_exchange(self): dt = 1.0 system_model = PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) # try some random schedule @@ -913,26 +817,14 @@ def test_2Q_exchange(self): schedule += Play(drive_pulse, DriveChannel(0)) schedule |= Play(drive_pulse, DriveChannel(1)) << 2 * total_samples - schedule |= ( - Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) - << 3 * total_samples - ) - schedule |= ( - Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) - << 3 * total_samples - ) + schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << 3 * total_samples + schedule |= Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) << 3 * total_samples y0 = np.array([1.0, 0.0, 0.0, 0.0]) with self.assertWarns(DeprecationWarning): - pulse_sim = PulseSimulator( - system_model=system_model, initial_state=y0, seed=9000 - ) + pulse_sim = PulseSimulator(system_model=system_model, initial_state=y0, seed=9000) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=q_freqs, - shots=1000, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=q_freqs, shots=1000 ) result = pulse_sim.run(schedule).result() pulse_sim_yf = result.get_statevector() @@ -962,10 +854,7 @@ def test_delay_instruction(self): dt = 1.0 system_model = PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) # construct a schedule that should result in a unitary -Z if delays are correctly handled @@ -985,8 +874,7 @@ def test_delay_instruction(self): # Result of schedule should be the unitary -1j*Z, so check rotation of an X eigenstate with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator( - system_model=system_model, - initial_state=np.array([1.0, 1.0]) / np.sqrt(2), + system_model=system_model, initial_state=np.array([1.0, 1.0]) / np.sqrt(2) ) pulse_sim.set_options( meas_return="single", meas_map=[[0]], qubit_lo_freq=[0.0, 0.0], shots=1 @@ -997,9 +885,7 @@ def test_delay_instruction(self): statevector = results.get_statevector() expected_vector = np.array([-1j, 1j]) / np.sqrt(2) - self.assertGreaterEqual( - state_fidelity(statevector, expected_vector), 1 - (10**-5) - ) + self.assertGreaterEqual(state_fidelity(statevector, expected_vector), 1 - (10**-5)) # verify validity of simulation when no delays included sched = Schedule() @@ -1013,14 +899,10 @@ def test_delay_instruction(self): results = pulse_sim.run(sched).result() statevector = results.get_statevector() - U = expm(1j * np.pi * self.Y / 4) @ expm( - -1j * np.pi * (self.Y / 4 + self.X / 2) - ) + U = expm(1j * np.pi * self.Y / 4) @ expm(-1j * np.pi * (self.Y / 4 + self.X / 2)) expected_vector = U @ np.array([1.0, 1.0]) / np.sqrt(2) - self.assertGreaterEqual( - state_fidelity(statevector, expected_vector), 1 - (10**-5) - ) + self.assertGreaterEqual(state_fidelity(statevector, expected_vector), 1 - (10**-5)) def test_shift_phase(self): """Test ShiftPhase command.""" @@ -1051,11 +933,7 @@ def test_shift_phase(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=system_model, initial_state=y0) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_0], - shots=1, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_0], shots=1 ) results = pulse_sim.run(sched).result() pulse_sim_yf = results.get_statevector() @@ -1119,11 +997,7 @@ def test_set_phase(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=system_model, initial_state=y0) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_0], - shots=1, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_0], shots=1 ) results = pulse_sim.run(sched).result() pulse_sim_yf = results.get_statevector() @@ -1158,11 +1032,7 @@ def test_set_phase_rwa(self): with self.assertWarns(DeprecationWarning): pulse_sim = PulseSimulator(system_model=system_model, initial_state=y0) pulse_sim.set_options( - meas_level=2, - meas_return="single", - meas_map=[[0]], - qubit_lo_freq=[omega_0], - shots=1, + meas_level=2, meas_return="single", meas_map=[[0]], qubit_lo_freq=[omega_0], shots=1 ) results = pulse_sim.run(sched).result() pulse_sim_yf = results.get_statevector() @@ -1194,10 +1064,7 @@ def test_frequency_error(self): schedule |= Play(drive_pulse, DriveChannel(0)) schedule += ShiftFrequency(5.0, DriveChannel(0)) schedule += Play(drive_pulse, DriveChannel(0)) - schedule += ( - Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) - << schedule.duration - ) + schedule += Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << schedule.duration with self.assertRaises(AerError): res = pulse_sim.run(schedule).result() @@ -1208,10 +1075,7 @@ def test_frequency_error(self): schedule |= Play(drive_pulse, DriveChannel(0)) schedule += SetFrequency(5.0, DriveChannel(0)) schedule += Play(drive_pulse, DriveChannel(0)) - schedule += ( - Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) - << schedule.duration - ) + schedule += Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << schedule.duration with self.assertRaises(AerError): res = pulse_sim.run(schedule).result() @@ -1281,27 +1145,16 @@ def test_3_level_measurement(self): dt = 1.0 system_model = PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) schedule = Schedule() - schedule |= ( - Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) - << 3 * total_samples - ) - schedule |= ( - Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) - << 3 * total_samples - ) + schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << 3 * total_samples + schedule |= Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) << 3 * total_samples y0 = np.array([1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) / np.sqrt(2) with self.assertWarns(DeprecationWarning): - pulse_sim = PulseSimulator( - system_model=system_model, initial_state=y0, seed=50 - ) + pulse_sim = PulseSimulator(system_model=system_model, initial_state=y0, seed=50) pulse_sim.set_options( meas_level=2, meas_return="single", @@ -1337,10 +1190,7 @@ def _system_model_1Q(self, omega_0, r): dt = 1.0 return PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) def _1Q_constant_sched(self, total_samples, amp=1.0): @@ -1358,10 +1208,7 @@ def _1Q_constant_sched(self, total_samples, amp=1.0): drive_pulse = Waveform(amp * np.ones(total_samples)) schedule = Schedule() schedule |= Play(drive_pulse, DriveChannel(0)) - schedule |= ( - Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) - << schedule.duration - ) + schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << schedule.duration return schedule @@ -1388,10 +1235,7 @@ def _system_model_2Q(self, j): dt = 1.0 return PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) def _2Q_constant_sched(self, total_samples, amp=1.0, u_idx=0): @@ -1410,12 +1254,8 @@ def _2Q_constant_sched(self, total_samples, amp=1.0, u_idx=0): drive_pulse = Waveform(amp * np.ones(total_samples)) schedule = Schedule() schedule |= Play(drive_pulse, ControlChannel(u_idx)) - schedule |= ( - Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << total_samples - ) - schedule |= ( - Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) << total_samples - ) + schedule |= Acquire(total_samples, AcquireChannel(0), MemorySlot(0)) << total_samples + schedule |= Acquire(total_samples, AcquireChannel(1), MemorySlot(1)) << total_samples return schedule @@ -1432,30 +1272,20 @@ def _system_model_3Q(self, j, subsystem_list=[0, 2]): """ hamiltonian = {} - hamiltonian["h_str"] = [ - "2*np.pi*j*0.25*(Z0*X2)||U0", - "2*np.pi*j*0.25*(Z1*X2)||U1", - ] + hamiltonian["h_str"] = ["2*np.pi*j*0.25*(Z0*X2)||U0", "2*np.pi*j*0.25*(Z1*X2)||U1"] hamiltonian["vars"] = {"j": j} hamiltonian["qub"] = {"0": 2, "1": 2, "2": 2} - ham_model = HamiltonianModel.from_dict( - hamiltonian, subsystem_list=subsystem_list - ) + ham_model = HamiltonianModel.from_dict(hamiltonian, subsystem_list=subsystem_list) # set the U0 to have frequency of drive channel 0 u_channel_lo = [[UchannelLO(0, 1.0 + 0.0j)], [UchannelLO(0, 1.0 + 0.0j)]] dt = 1.0 return PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) - def _3Q_constant_sched( - self, total_samples, amp=1.0, u_idx=0, subsystem_list=[0, 2] - ): + def _3Q_constant_sched(self, total_samples, amp=1.0, u_idx=0, subsystem_list=[0, 2]): """Creates a runnable schedule for the 3Q system after the system is restricted to 2 qubits. @@ -1475,8 +1305,7 @@ def _3Q_constant_sched( schedule |= Play(drive_pulse, ControlChannel(u_idx)) for idx in subsystem_list: schedule |= ( - Acquire(total_samples, AcquireChannel(idx), MemorySlot(idx)) - << total_samples + Acquire(total_samples, AcquireChannel(idx), MemorySlot(idx)) << total_samples ) return schedule @@ -1493,11 +1322,7 @@ def _system_model_3d_oscillator(self, freq, anharm, r): PulseSystemModel: model for oscillator system """ hamiltonian = {} - hamiltonian["h_str"] = [ - "np.pi*(2*v-alpha)*O0", - "np.pi*alpha*O0*O0", - "2*np.pi*r*X0||D0", - ] + hamiltonian["h_str"] = ["np.pi*(2*v-alpha)*O0", "np.pi*alpha*O0*O0", "2*np.pi*r*X0||D0"] hamiltonian["vars"] = {"v": freq, "alpha": anharm, "r": r} hamiltonian["qub"] = {"0": 3} ham_model = HamiltonianModel.from_dict(hamiltonian) @@ -1507,10 +1332,7 @@ def _system_model_3d_oscillator(self, freq, anharm, r): dt = 1.0 return PulseSystemModel( - hamiltonian=ham_model, - u_channel_lo=u_channel_lo, - subsystem_list=subsystem_list, - dt=dt, + hamiltonian=ham_model, u_channel_lo=u_channel_lo, subsystem_list=subsystem_list, dt=dt ) diff --git a/test/terra/common.py b/test/terra/common.py index 2b5c03a577..8ce447f970 100644 --- a/test/terra/common.py +++ b/test/terra/common.py @@ -65,9 +65,8 @@ def setUpClass(cls): # is set. if os.getenv("LOG_LEVEL"): # Set up formatter. - log_fmt = ( - "{}.%(funcName)s:%(levelname)s:%(asctime)s:" - " %(message)s".format(cls.__name__) + log_fmt = "{}.%(funcName)s:%(levelname)s:%(asctime)s:" " %(message)s".format( + cls.__name__ ) formatter = logging.Formatter(log_fmt) @@ -111,9 +110,7 @@ def assertNotSuccess(self, result): self.assertFalse(success, msg=msg) @staticmethod - def gate_circuits( - gate_cls, num_angles=0, has_ctrl_qubits=False, rng=None, basis_states=None - ): + def gate_circuits(gate_cls, num_angles=0, has_ctrl_qubits=False, rng=None, basis_states=None): """ Construct circuits from a gate class. Example of basis_states: ['010, '100']. @@ -134,9 +131,7 @@ def gate_circuits( gate = gate_cls(*params) if basis_states is None: - basis_states = [ - bin(i)[2:].zfill(gate.num_qubits) for i in range(1 << gate.num_qubits) - ] + basis_states = [bin(i)[2:].zfill(gate.num_qubits) for i in range(1 << gate.num_qubits)] circs = [] qubit_permutation = list(rng.permutation(gate.num_qubits)) @@ -188,17 +183,11 @@ def compare_statevector( with self.subTest(msg=test_msg): msg = " {} != {}".format(output, target) delta = matrix_equal( - output.data, - target.data, - ignore_phase=ignore_phase, - atol=atol, - rtol=rtol, + output.data, target.data, ignore_phase=ignore_phase, atol=atol, rtol=rtol ) self.assertTrue(delta, msg=msg) - def compare_unitary( - self, result, circuits, targets, ignore_phase=False, atol=1e-8, rtol=1e-5 - ): + def compare_unitary(self, result, circuits, targets, ignore_phase=False, atol=1e-8, rtol=1e-5): """Compare final unitary matrices to targets.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case @@ -208,11 +197,7 @@ def compare_unitary( with self.subTest(msg=test_msg): msg = test_msg + " {} != {}".format(output.data, target.data) delta = matrix_equal( - output.data, - target.data, - ignore_phase=ignore_phase, - atol=atol, - rtol=rtol, + output.data, target.data, ignore_phase=ignore_phase, atol=atol, rtol=rtol ) self.assertTrue(delta, msg=msg) diff --git a/test/terra/extensions/test_save_expval.py b/test/terra/extensions/test_save_expval.py index fb006b1f7b..76ab55f899 100644 --- a/test/terra/extensions/test_save_expval.py +++ b/test/terra/extensions/test_save_expval.py @@ -59,9 +59,7 @@ def test_unnorm_kwarg(self): def test_unnorm_cond_kwarg(self): """Test unnormalized, conditonal kwargs""" key = "test_key" - instr = SaveExpectationValue( - Pauli("X"), key, conditional=True, unnormalized=True - ) + instr = SaveExpectationValue(Pauli("X"), key, conditional=True, unnormalized=True) self.assertEqual(instr.name, "save_expval") self.assertEqual(instr._label, key) self.assertEqual(instr._subtype, "c_accum") @@ -88,16 +86,12 @@ class TestSaveExpectationValueVariance(QiskitAerTestCase): def test_invalid_key_raises(self): """Test save instruction key is str""" - self.assertRaises( - ExtensionError, lambda: SaveExpectationValueVariance(Pauli("Z"), 1) - ) + self.assertRaises(ExtensionError, lambda: SaveExpectationValueVariance(Pauli("Z"), 1)) def test_nonhermitian_raises(self): """Test non-Hermitian op raises exception.""" op = [[0, 1j], [1j, 0]] - self.assertRaises( - ExtensionError, lambda: SaveExpectationValueVariance(op, "expval") - ) + self.assertRaises(ExtensionError, lambda: SaveExpectationValueVariance(op, "expval")) def test_default_kwarg(self): """Test default kwargs""" @@ -126,9 +120,7 @@ def test_unnorm_kwarg(self): def test_unnorm_cond_kwarg(self): """Test unnormalized, conditonal kwargs""" key = "test_key" - instr = SaveExpectationValueVariance( - Pauli("X"), key, conditional=True, unnormalized=True - ) + instr = SaveExpectationValueVariance(Pauli("X"), key, conditional=True, unnormalized=True) self.assertEqual(instr.name, "save_expval_var") self.assertEqual(instr._label, key) self.assertEqual(instr._subtype, "c_accum") @@ -144,9 +136,7 @@ def test_pershot_kwarg(self): def test_pershot_cond_kwarg(self): """Test pershot, conditonal kwargs""" key = "test_key" - instr = SaveExpectationValueVariance( - Pauli("X"), key, conditional=True, pershot=True - ) + instr = SaveExpectationValueVariance(Pauli("X"), key, conditional=True, pershot=True) self.assertEqual(instr.name, "save_expval_var") self.assertEqual(instr._label, key) self.assertEqual(instr._subtype, "c_list") diff --git a/test/terra/extensions/test_wrappers.py b/test/terra/extensions/test_wrappers.py index 2f68179f76..cc7e62b50a 100644 --- a/test/terra/extensions/test_wrappers.py +++ b/test/terra/extensions/test_wrappers.py @@ -44,11 +44,7 @@ def _create_qobj(self, backend, noise_model=None): circuit = QuantumCircuit(num_qubits) circuit.x(list(range(num_qubits))) circuit = transpile(circuit, backend) - opts = { - "max_parallel_threads": 1, - "library_dir": LIBRARY_DIR, - "noise_model": noise_model, - } + opts = {"max_parallel_threads": 1, "library_dir": LIBRARY_DIR, "noise_model": noise_model} qobj = backend._assemble(circuit, **opts) return qobj diff --git a/test/terra/noise/passes/test_relaxation_noise_pass.py b/test/terra/noise/passes/test_relaxation_noise_pass.py index 1acd5f8cc5..4ca2502336 100644 --- a/test/terra/noise/passes/test_relaxation_noise_pass.py +++ b/test/terra/noise/passes/test_relaxation_noise_pass.py @@ -67,9 +67,7 @@ def test_default_with_scheduled_circuit(self): qc.measure([0, 1], [0, 1]) durations = [("h", None, 10), ("cx", None, 50), ("measure", None, 200)] - sched_circ = transpile( - qc, scheduling_method="alap", instruction_durations=durations - ) + sched_circ = transpile(qc, scheduling_method="alap", instruction_durations=durations) noise_pass = RelaxationNoisePass(t1s=[0.10, 0.11], t2s=[0.20, 0.21], dt=0.01) noisy_circ = noise_pass(sched_circ) @@ -90,9 +88,7 @@ def test_default_with_non_scheduled_circuit(self): def test_raise_if_supplied_invalid_ops(self): with self.assertRaises(TranspilerError): - RelaxationNoisePass( - t1s=[1], t2s=[1], dt=1, op_types="delay" - ) # str is invalid + RelaxationNoisePass(t1s=[1], t2s=[1], dt=1, op_types="delay") # str is invalid def test_ops_types(self): """Test adding noises only to delays in a scheduled circuit.""" @@ -106,9 +102,7 @@ def test_ops_types(self): qc.measure([0, 1], [0, 1]) durations = [("h", None, 10), ("cx", None, 50), ("measure", None, 200)] - sched_circ = transpile( - qc, scheduling_method="alap", instruction_durations=durations - ) + sched_circ = transpile(qc, scheduling_method="alap", instruction_durations=durations) noise_pass = RelaxationNoisePass(t1s=t1s, t2s=t2s, dt=dt, op_types=Delay) noisy_circ = noise_pass(sched_circ) @@ -116,9 +110,7 @@ def test_ops_types(self): expected = QuantumCircuit(2, 2) expected.h(0) expected.delay(10, 1) - expected.append( - thermal_relaxation_error(t1s[1], t2s[1], 10 * dt).to_instruction(), [1] - ) + expected.append(thermal_relaxation_error(t1s[1], t2s[1], 10 * dt).to_instruction(), [1]) expected.cx(0, 1) expected.measure([0, 1], [0, 1]) diff --git a/test/terra/noise/test_device_models.py b/test/terra/noise/test_device_models.py index 6c1535e8e3..7b82553bf7 100644 --- a/test/terra/noise/test_device_models.py +++ b/test/terra/noise/test_device_models.py @@ -35,14 +35,10 @@ def test_basic_device_gate_errors_from_target(self): def test_basic_device_gate_errors_from_target_and_properties(self): """Test if the device same gate errors are produced both from target and properties""" - errors_from_properties = basic_device_gate_errors( - properties=FakeNairobi().properties() - ) + errors_from_properties = basic_device_gate_errors(properties=FakeNairobi().properties()) errors_from_target = basic_device_gate_errors(target=FakeNairobiV2().target) self.assertEqual(len(errors_from_properties), len(errors_from_target)) - for err_properties, err_target in zip( - errors_from_properties, errors_from_target - ): + for err_properties, err_target in zip(errors_from_properties, errors_from_target): name1, qargs1, err1 = err_properties name2, qargs2, err2 = err_target self.assertEqual(name1, name2) diff --git a/test/terra/noise/test_noise_model.py b/test/terra/noise/test_noise_model.py index be2da00733..5e70e3f389 100644 --- a/test/terra/noise/test_noise_model.py +++ b/test/terra/noise/test_noise_model.py @@ -69,9 +69,7 @@ def test_amplitude_damping_error(self): noise_model.add_all_qubit_quantum_error(error, "id") # Execute target = {"0x0": 3 * shots / 4, "0x1": shots / 4} - circuit = transpile( - circuit, basis_gates=noise_model.basis_gates, optimization_level=0 - ) + circuit = transpile(circuit, basis_gates=noise_model.basis_gates, optimization_level=0) result = backend.run(circuit, shots=shots, noise_model=noise_model).result() self.assertSuccess(result) self.compare_counts(result, [circuit], [target], delta=0.05 * shots) @@ -262,11 +260,7 @@ def test_noise_model_from_lagos_v2(self): def test_noise_model_from_invalid_t2_backend(self): """Test if silently truncate invalid T2 values when creating a noise model from backend""" - from qiskit.providers.models.backendproperties import ( - BackendProperties, - Gate, - Nduv, - ) + from qiskit.providers.models.backendproperties import BackendProperties, Gate, Nduv import datetime t1_ns, invalid_t2_ns = 75_1000, 200_1000 @@ -284,21 +278,9 @@ def __init__(self): basis_gates=["u3"], qubits=[ [ - Nduv( - date=mock_time, name="T1", unit="µs", value=t1_ns / 1000 - ), - Nduv( - date=mock_time, - name="T2", - unit="µs", - value=invalid_t2_ns / 1000, - ), - Nduv( - date=mock_time, - name="frequency", - unit="MHz", - value=frequency, - ), + Nduv(date=mock_time, name="T1", unit="µs", value=t1_ns / 1000), + Nduv(date=mock_time, name="T2", unit="µs", value=invalid_t2_ns / 1000), + Nduv(date=mock_time, name="frequency", unit="MHz", value=frequency), ], ], gates=[ @@ -307,17 +289,9 @@ def __init__(self): name="u3_0", qubits=[0], parameters=[ + Nduv(date=mock_time, name="gate_error", unit="", value=0.001), Nduv( - date=mock_time, - name="gate_error", - unit="", - value=0.001, - ), - Nduv( - date=mock_time, - name="gate_length", - unit="ns", - value=u3_time_ns, + date=mock_time, name="gate_length", unit="ns", value=u3_time_ns ), ], ), diff --git a/test/terra/noise/test_noise_transformation.py b/test/terra/noise/test_noise_transformation.py index 8b81bd820c..656db8f718 100644 --- a/test/terra/noise/test_noise_transformation.py +++ b/test/terra/noise/test_noise_transformation.py @@ -45,13 +45,7 @@ class TestNoiseTransformer(QiskitAerTestCase): def setUp(self): super().setUp() - self.ops = { - "X": XGate(), - "Y": YGate(), - "Z": ZGate(), - "H": HGate(), - "S": SGate(), - } + self.ops = {"X": XGate(), "Y": YGate(), "Z": ZGate(), "H": HGate(), "S": SGate()} def assertNoiseModelsAlmostEqual(self, lhs, rhs, places=3): self.assertNoiseDictsAlmostEqual( @@ -74,12 +68,8 @@ def assertNoiseModelsAlmostEqual(self, lhs, rhs, places=3): def assertNoiseDictsAlmostEqual(self, lhs, rhs, places=3): keys = set(lhs.keys()).union(set(rhs.keys())) for key in keys: - self.assertTrue( - key in lhs.keys(), msg="Key {} is missing from lhs".format(key) - ) - self.assertTrue( - key in rhs.keys(), msg="Key {} is missing from rhs".format(key) - ) + self.assertTrue(key in lhs.keys(), msg="Key {} is missing from lhs".format(key)) + self.assertTrue(key in rhs.keys(), msg="Key {} is missing from rhs".format(key)) if isinstance(lhs[key], dict): self.assertNoiseDictsAlmostEqual(lhs[key], rhs[key], places=places) else: @@ -96,17 +86,13 @@ def assertDictAlmostEqual(self, lhs, rhs, places=None): self.assertAlmostEqual( lhs.get(key), rhs.get(key), - msg="Not almost equal for key {}: {} !~ {}".format( - key, lhs.get(key), rhs.get(key) - ), + msg="Not almost equal for key {}: {} !~ {}".format(key, lhs.get(key), rhs.get(key)), places=places, ) def assertListAlmostEqual(self, lhs, rhs, places=None): self.assertEqual( - len(lhs), - len(rhs), - msg="List lengths differ: {} != {}".format(len(lhs), len(rhs)), + len(lhs), len(rhs), msg="List lengths differ: {} != {}".format(len(lhs), len(rhs)) ) for i in range(len(lhs)): if isinstance(lhs[i], numpy.ndarray) and isinstance(rhs[i], numpy.ndarray): @@ -115,9 +101,7 @@ def assertListAlmostEqual(self, lhs, rhs, places=None): self.assertAlmostEqual(lhs[i], rhs[i], places=places) def assertMatricesAlmostEqual(self, lhs, rhs, places=None): - self.assertEqual( - lhs.shape, rhs.shape, "Marix shapes differ: {} vs {}".format(lhs, rhs) - ) + self.assertEqual(lhs.shape, rhs.shape, "Marix shapes differ: {} vs {}".format(lhs, rhs)) n, m = lhs.shape for x in range(n): for y in range(m): @@ -136,12 +120,8 @@ def test_transformation_by_pauli(self): p = 0.22 theta = numpy.pi / 5 E0 = numpy.sqrt(1 - p) * numpy.array(numpy.eye(2)) - E1 = numpy.sqrt(p) * ( - numpy.cos(theta) * numpy.array(X) + numpy.sin(theta) * numpy.array(Y) - ) - results = approximate_quantum_error( - Kraus([E0, E1]), operator_dict={"X": X, "Y": Y, "Z": Z} - ) + E1 = numpy.sqrt(p) * (numpy.cos(theta) * numpy.array(X) + numpy.sin(theta) * numpy.array(Y)) + results = approximate_quantum_error(Kraus([E0, E1]), operator_dict={"X": X, "Y": Y, "Z": Z}) expected_results = pauli_error( [ ("X", p * numpy.cos(theta) * numpy.cos(theta)), @@ -182,22 +162,14 @@ def test_transform(self): p = 0.34 theta = numpy.pi / 7 E0 = numpy.sqrt(1 - p) * numpy.array(numpy.eye(2)) - E1 = numpy.sqrt(p) * ( - numpy.cos(theta) * numpy.array(X) + numpy.sin(theta) * numpy.array(Y) - ) + E1 = numpy.sqrt(p) * (numpy.cos(theta) * numpy.array(X) + numpy.sin(theta) * numpy.array(Y)) results_dict = approximate_quantum_error( Kraus([E0, E1]), operator_dict={"X": X, "Y": Y, "Z": Z} ) - results_string = approximate_quantum_error( - Kraus([E0, E1]), operator_string="pauli" - ) - results_list = approximate_quantum_error( - Kraus([E0, E1]), operator_list=[X, Y, Z] - ) - results_tuple = approximate_quantum_error( - Kraus([E0, E1]), operator_list=(X, Y, Z) - ) + results_string = approximate_quantum_error(Kraus([E0, E1]), operator_string="pauli") + results_list = approximate_quantum_error(Kraus([E0, E1]), operator_list=[X, Y, Z]) + results_tuple = approximate_quantum_error(Kraus([E0, E1]), operator_list=(X, Y, Z)) self.assertErrorsAlmostEqual(results_dict, results_string) self.assertErrorsAlmostEqual(results_string, results_list) @@ -260,16 +232,10 @@ def test_reset_2_qubit(self): error_2 = QuantumError([([(Kraus([A0, A1]), [1]), (IGate(), [0])], 1)]) expected_results_1 = QuantumError( - [ - ([(IGate(), [0]), (IGate(), [1])], 1 - p), - ([(Reset(), [0]), (IGate(), [1])], p), - ] + [([(IGate(), [0]), (IGate(), [1])], 1 - p), ([(Reset(), [0]), (IGate(), [1])], p)] ) expected_results_2 = QuantumError( - [ - ([(IGate(), [1]), (IGate(), [0])], 1 - p), - ([(Reset(), [1]), (IGate(), [0])], p), - ] + [([(IGate(), [1]), (IGate(), [0])], 1 - p), ([(Reset(), [1]), (IGate(), [0])], p)] ) results_1 = approximate_quantum_error(error_1, operator_string="reset") @@ -282,9 +248,7 @@ def test_clifford(self): x_p = 0.1 y_p = 0.2 z_p = 0.3 - error = pauli_error( - [("X", x_p), ("Y", y_p), ("Z", z_p), ("I", 1 - (x_p + y_p + z_p))] - ) + error = pauli_error([("X", x_p), ("Y", y_p), ("Z", z_p), ("I", 1 - (x_p + y_p + z_p))]) results = approximate_quantum_error(error, operator_string="clifford") self.assertErrorsAlmostEqual(error, results, places=1) @@ -292,9 +256,7 @@ def test_errors(self): gamma = 0.23 error = amplitude_damping_error(gamma) # kraus error is legit, transform_channel_operators are not - with self.assertRaisesRegex( - TypeError, "takes 1 positional argument but 2 were given" - ): + with self.assertRaisesRegex(TypeError, "takes 1 positional argument but 2 were given"): approximate_quantum_error(error, 7) with self.assertRaises(NoiseError): approximate_quantum_error(error, operator_string="seven") diff --git a/test/terra/noise/test_quantum_error.py b/test/terra/noise/test_quantum_error.py index f189119595..79cc49bb18 100644 --- a/test/terra/noise/test_quantum_error.py +++ b/test/terra/noise/test_quantum_error.py @@ -75,9 +75,7 @@ def test_init_with_instructions(self): mixed_gates = QuantumError([((IGate(), [0]), 0.6), ((XGate(), [1]), 0.4)]) self.assertEqual(mixed_gates.size, 2) - mixed_ops = QuantumError( - [(IGate(), 0.7), (Pauli("Z"), 0.3)] # Gate - ) # Operator + mixed_ops = QuantumError([(IGate(), 0.7), (Pauli("Z"), 0.3)]) # Gate # Operator self.assertEqual(mixed_ops.size, 2) mixed_ops = QuantumError( [(IGate(), 0.7), ((Reset(), [1]), 0.3)] # Instruction @@ -90,9 +88,7 @@ def test_raise_if_invalid_op_type_for_init(self): QuantumError(Measure()) # instruction with clbits with self.assertRaises(NoiseError): - QuantumError( - [Reset(), XGate()] - ) # list of instructions expecting default qubits + QuantumError([Reset(), XGate()]) # list of instructions expecting default qubits with self.assertRaises(NoiseError): QuantumError([(Reset(), [0]), XGate()]) # partially supplied diff --git a/test/terra/noise/test_readout_error.py b/test/terra/noise/test_readout_error.py index 4029dc6f1c..4afa26959f 100644 --- a/test/terra/noise/test_readout_error.py +++ b/test/terra/noise/test_readout_error.py @@ -73,11 +73,7 @@ def test_1qubit(self): # Test circuit: ideal outcome "11" probs = [[1, 0], [0, 1]] - roerror_dict = { - "type": "roerror", - "operations": ["measure"], - "probabilities": probs, - } + roerror_dict = {"type": "roerror", "operations": ["measure"], "probabilities": probs} roerror = ReadoutError(probs) self.assertEqual(roerror.number_of_qubits, 1) self.assertEqual(roerror.probabilities.tolist(), probs) @@ -86,17 +82,8 @@ def test_1qubit(self): def test_2qubit(self): """Test 2-qubit readout error""" # Test circuit: ideal outcome "11" - probs = [ - [0.7, 0.2, 0.1, 0], - [0, 0.9, 0.1, 0], - [0, 0, 1, 0], - [0.1, 0.1, 0.2, 0.6], - ] - roerror_dict = { - "type": "roerror", - "operations": ["measure"], - "probabilities": probs, - } + probs = [[0.7, 0.2, 0.1, 0], [0, 0.9, 0.1, 0], [0, 0, 1, 0], [0.1, 0.1, 0.2, 0.6]] + roerror_dict = {"type": "roerror", "operations": ["measure"], "probabilities": probs} roerror = ReadoutError(probs) self.assertEqual(roerror.number_of_qubits, 2) self.assertEqual(roerror.probabilities.tolist(), probs) @@ -107,11 +94,7 @@ def test_tensor(self): probs0 = [[0.9, 0.1], [0.4, 0.6]] probs1 = [[0.5, 0.5], [0.2, 0.8]] probs = np.kron(probs0, probs1).tolist() - error_dict = { - "type": "roerror", - "operations": ["measure"], - "probabilities": probs, - } + error_dict = {"type": "roerror", "operations": ["measure"], "probabilities": probs} error0 = ReadoutError(probs0) error1 = ReadoutError(probs1) error = error0.tensor(error1) @@ -125,11 +108,7 @@ def test_expand(self): probs0 = [[0.9, 0.1], [0.4, 0.6]] probs1 = [[0.5, 0.5], [0.2, 0.8]] probs = np.kron(probs0, probs1).tolist() - error_dict = { - "type": "roerror", - "operations": ["measure"], - "probabilities": probs, - } + error_dict = {"type": "roerror", "operations": ["measure"], "probabilities": probs} error0 = ReadoutError(probs0) error1 = ReadoutError(probs1) error = error1.expand(error0) @@ -143,11 +122,7 @@ def test_compose(self): probs0 = [[0.9, 0.1], [0.4, 0.6]] probs1 = [[0.5, 0.5], [0.2, 0.8]] probs = np.dot(probs1, probs0).tolist() - error_dict = { - "type": "roerror", - "operations": ["measure"], - "probabilities": probs, - } + error_dict = {"type": "roerror", "operations": ["measure"], "probabilities": probs} error0 = ReadoutError(probs0) error1 = ReadoutError(probs1) # compose method @@ -166,11 +141,7 @@ def test_dot_front(self): probs0 = [[0.9, 0.1], [0.4, 0.6]] probs1 = [[0.5, 0.5], [0.2, 0.8]] probs = np.dot(probs1, probs0).tolist() - error_dict = { - "type": "roerror", - "operations": ["measure"], - "probabilities": probs, - } + error_dict = {"type": "roerror", "operations": ["measure"], "probabilities": probs} error0 = ReadoutError(probs0) error1 = ReadoutError(probs1) # dot method diff --git a/test/terra/noise/test_standard_errors.py b/test/terra/noise/test_standard_errors.py index c52949ccf4..686f41e3ff 100644 --- a/test/terra/noise/test_standard_errors.py +++ b/test/terra/noise/test_standard_errors.py @@ -74,9 +74,7 @@ def test_mixed_unitary_error(self): """Test construction of mixed unitary error""" unitaries = [np.diag([1, -1]), np.eye(2)] probs = [0.3, 0.7] - error = mixed_unitary_error( - [(unitaries[0], probs[0]), (unitaries[1], probs[1])] - ) + error = mixed_unitary_error([(unitaries[0], probs[0]), (unitaries[1], probs[1])]) for i in [0, 1]: op, p = error.error_term(i) self.assertEqual(p, probs[i]) @@ -100,16 +98,12 @@ def test_pauli_error_1q_gate_from_string(self): probs = [0.4, 0.3, 0.2, 0.1] actual = pauli_error(zip(paulis, probs)) - expected = QuantumError( - [(IGate(), 0.4), (XGate(), 0.3), (YGate(), 0.2), (ZGate(), 0.1)] - ) + expected = QuantumError([(IGate(), 0.4), (XGate(), 0.3), (YGate(), 0.2), (ZGate(), 0.1)]) for i in range(actual.size): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_pauli_error_1q_gate_from_pauli(self): """Test single-qubit pauli error as gate qobj from Pauli obj""" @@ -117,16 +111,12 @@ def test_pauli_error_1q_gate_from_pauli(self): probs = [0.4, 0.3, 0.2, 0.1] actual = pauli_error(zip(paulis, probs)) - expected = QuantumError( - [(IGate(), 0.4), (XGate(), 0.3), (YGate(), 0.2), (ZGate(), 0.1)] - ) + expected = QuantumError([(IGate(), 0.4), (XGate(), 0.3), (YGate(), 0.2), (ZGate(), 0.1)]) for i in range(actual.size): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_pauli_error_2q_gate_from_string(self): """Test two-qubit pauli error as gate qobj from string label""" @@ -141,9 +131,7 @@ def test_pauli_error_2q_gate_from_string(self): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_pauli_error_2q_gate_from_pauli(self): """Test two-qubit pauli error as gate qobj from Pauli obj""" @@ -158,9 +146,7 @@ def test_pauli_error_2q_gate_from_pauli(self): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_depolarizing_error_ideal(self): """Test depolarizing error with p=0 (ideal) as gate qobj""" @@ -192,9 +178,7 @@ def test_depolarizing_error_1q_gate(self): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_depolarizing_error_2q_gate(self): """Test 2-qubit depolarizing error as gate qobj""" @@ -225,9 +209,7 @@ def test_depolarizing_error_2q_gate(self): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_amplitude_damping_error_raises_invalid_amp_param(self): """Test phase and amplitude damping error raises for invalid amp_param""" @@ -261,9 +243,7 @@ def test_phase_amplitude_damping_error_noncanonical(self): circ, p = error.error_term(0) self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertEqual( - len(circ[0][0].params), 6, msg="Incorrect number of kraus matrices" - ) + self.assertEqual(len(circ[0][0].params), 6, msg="Incorrect number of kraus matrices") def test_phase_amplitude_damping_error_canonical(self): """Test phase maplitude damping channel has correct number of ops""" @@ -271,70 +251,50 @@ def test_phase_amplitude_damping_error_canonical(self): circ, p = error.error_term(0) self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertEqual( - len(circ[0][0].params), 4, msg="Incorrect number of kraus matrices" - ) + self.assertEqual(len(circ[0][0].params), 4, msg="Incorrect number of kraus matrices") def test_amplitude_damping_error_ideal_canonical(self): """Test amplitude damping error with param=0 and canonical kraus""" - error = amplitude_damping_error( - 0, excited_state_population=0.5, canonical_kraus=True - ) + error = amplitude_damping_error(0, excited_state_population=0.5, canonical_kraus=True) circ, p = error.error_term(0) self.assertEqual(p, 1, msg="ideal probability") self.assertTrue(error.ideal(), msg="ideal circuit") def test_amplitude_damping_error_full_0state_canonical(self): """Test amplitude damping error with param=1 and canonical kraus""" - error = amplitude_damping_error( - 1, excited_state_population=0, canonical_kraus=True - ) + error = amplitude_damping_error(1, excited_state_population=0, canonical_kraus=True) targets = [np.diag([1, 0]), np.array([[0, 1], [0, 0]])] circ, p = error.error_term(0) self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertTrue( - np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices" - ) + self.assertTrue(np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices") def test_amplitude_damping_error_full_1state_canonical(self): """Test amplitude damping error with param=1 and canonical kraus""" - error = amplitude_damping_error( - 1, excited_state_population=1, canonical_kraus=True - ) + error = amplitude_damping_error(1, excited_state_population=1, canonical_kraus=True) targets = [np.array([[0, 0], [1, 0]]), np.diag([0, 1])] circ, p = error.error_term(0) self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertTrue( - np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices" - ) + self.assertTrue(np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices") def test_amplitude_damping_error_full_0state_noncanonical(self): """Test amplitude damping error with param=1 and canonical kraus""" - error = amplitude_damping_error( - 1, excited_state_population=0, canonical_kraus=False - ) + error = amplitude_damping_error(1, excited_state_population=0, canonical_kraus=False) targets = [np.diag([1, 0]), np.array([[0, 1], [0, 0]])] circ, p = error.error_term(0) self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertTrue( - np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices" - ) + self.assertTrue(np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices") def test_amplitude_damping_error_full_1state_noncanonical(self): """Test amplitude damping error with param=1 and canonical kraus""" - error = amplitude_damping_error( - 1, excited_state_population=1, canonical_kraus=False - ) + error = amplitude_damping_error(1, excited_state_population=1, canonical_kraus=False) targets = [np.diag([0, 1]), np.array([[0, 0], [1, 0]])] circ, p = error.error_term(0) self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertTrue( - np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices" - ) + self.assertTrue(np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices") def test_phase_damping_error_ideal(self): """Test phase damping error with param=0 (ideal)""" @@ -350,9 +310,7 @@ def test_phase_damping_error_full_canonical(self): targets = [np.diag([1, 0]), np.diag([0, 1])] self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertTrue( - np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices" - ) + self.assertTrue(np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices") def test_phase_damping_error_full_noncanonical(self): """Test phase damping error with param=1 and non-canonical kraus""" @@ -361,9 +319,7 @@ def test_phase_damping_error_full_noncanonical(self): targets = [np.diag([1, 0]), np.diag([0, 1])] self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertTrue( - np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices" - ) + self.assertTrue(np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices") def test_phase_damping_error_canonical(self): """Test phase damping error with canonical kraus""" @@ -378,8 +334,7 @@ def test_phase_damping_error_canonical(self): self.assertEqual(circ[0][1], [circ.qubits[0]]) for actual, expected in zip(circ[0][0].params, targets): self.assertTrue( - np.allclose(actual / actual[0][0], expected), - msg="Incorrect kraus matrix", + np.allclose(actual / actual[0][0], expected), msg="Incorrect kraus matrix" ) def test_phase_damping_error_noncanonical(self): @@ -393,9 +348,7 @@ def test_phase_damping_error_noncanonical(self): ] self.assertEqual(p, 1, msg="Kraus probability") self.assertEqual(circ[0][1], [circ.qubits[0]]) - self.assertTrue( - np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices" - ) + self.assertTrue(np.allclose(circ[0][0].params, targets), msg="Incorrect kraus matrices") def test_thermal_relaxation_error_raises_invalid_t2(self): """Test raises error for invalid t2 parameters""" @@ -444,9 +397,7 @@ def test_thermal_relaxation_error_t1_equal_t2_0state(self): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_thermal_relaxation_error_t1_equal_t2_1state(self): """Test qobj instructions return for t1=t2""" @@ -461,9 +412,7 @@ def test_thermal_relaxation_error_t1_equal_t2_1state(self): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_thermal_relaxation_error_gate(self): """Test qobj instructions return for t2 < t1""" @@ -485,9 +434,7 @@ def test_thermal_relaxation_error_gate(self): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") - self.assertAlmostEqual( - prob, expected_prob, msg=f"Incorrect {i}-th probability" - ) + self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability") def test_thermal_relaxation_error_kraus(self): """Test non-kraus instructions return for t2 < t1""" diff --git a/test/terra/primitives/test_estimator.py b/test/terra/primitives/test_estimator.py index a78c75febc..d0b97a1688 100644 --- a/test/terra/primitives/test_estimator.py +++ b/test/terra/primitives/test_estimator.py @@ -95,11 +95,7 @@ def test_evaluate(self, abelian_grouping): """test for evaluate""" est = Estimator(abelian_grouping=abelian_grouping) result = est.run( - self.ansatz, - self.observable, - parameter_values=[[0, 1, 1, 2, 3, 5]], - seed=15, - shots=8192, + self.ansatz, self.observable, parameter_values=[[0, 1, 1, 2, 3, 5]], seed=15, shots=8192 ).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [self.expval], rtol=0.02) @@ -115,9 +111,7 @@ def test_evaluate_multi_params(self, abelian_grouping): seed=15, ).result() self.assertIsInstance(result, EstimatorResult) - np.testing.assert_allclose( - result.values, [self.expval, self.expval_rev], rtol=0.02 - ) + np.testing.assert_allclose(result.values, [self.expval, self.expval_rev], rtol=0.02) @data(True, False) def test_evaluate_no_params(self, abelian_grouping): @@ -250,9 +244,7 @@ def test_numpy_params(self, abelian_grouping): np.testing.assert_allclose(result.values, target.values) with self.subTest("list of ndarray"): - result = estimator.run( - [qc] * k, [op] * k, params_list_array, seed=15 - ).result() + result = estimator.run([qc] * k, [op] * k, params_list_array, seed=15).result() self.assertEqual(len(result.metadata), k) np.testing.assert_allclose(result.values, target.values) @@ -263,11 +255,7 @@ def test_with_shots_option_with_approximation(self, abelian_grouping): # The purpose of this test is to make sure the results remain the same. est = Estimator(approximation=True, abelian_grouping=abelian_grouping) result = est.run( - self.ansatz, - self.observable, - parameter_values=[[0, 1, 1, 2, 3, 5]], - shots=1024, - seed=15, + self.ansatz, self.observable, parameter_values=[[0, 1, 1, 2, 3, 5]], shots=1024, seed=15 ).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.3088991960117797]) @@ -276,11 +264,7 @@ def test_with_shots_option_without_approximation(self): """test with shots option.""" est = Estimator(approximation=False, abelian_grouping=False) result = est.run( - self.ansatz, - self.observable, - parameter_values=[[0, 1, 1, 2, 3, 5]], - shots=1024, - seed=15, + self.ansatz, self.observable, parameter_values=[[0, 1, 1, 2, 3, 5]], shots=1024, seed=15 ).result() self.assertIsInstance(result, EstimatorResult) np.testing.assert_allclose(result.values, [-1.2895828299114598]) diff --git a/test/terra/primitives/test_sampler.py b/test/terra/primitives/test_sampler.py index b334855700..e19b7f8fd8 100644 --- a/test/terra/primitives/test_sampler.py +++ b/test/terra/primitives/test_sampler.py @@ -111,9 +111,7 @@ def test_sampler_param_order(self): qc.measure(2, 2) sampler = Sampler(backend_options={"seed_simulator": 15}) - result = sampler.run( - [qc] * 4, [[0, 0], [0, 0], [np.pi / 2, 0], [0, np.pi / 2]] - ).result() + result = sampler.run([qc] * 4, [[0, 0], [0, 0], [np.pi / 2, 0], [0, np.pi / 2]]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) @@ -124,14 +122,10 @@ def test_sampler_param_order(self): self.assertDictAlmostEqual(result.quasi_dists[1], {4: 1}) # qc({x: pi/2, y: 0}) - self.assertDictAlmostEqual( - result.quasi_dists[2], {4: 0.4990234375, 5: 0.5009765625} - ) + self.assertDictAlmostEqual(result.quasi_dists[2], {4: 0.4990234375, 5: 0.5009765625}) # qc({x: 0, y: pi/2}) - self.assertDictAlmostEqual( - result.quasi_dists[3], {4: 0.4814453125, 6: 0.5185546875} - ) + self.assertDictAlmostEqual(result.quasi_dists[3], {4: 0.4814453125, 6: 0.5185546875}) def test_sampler_reverse_meas_order(self): """test for sampler with reverse measurement order""" @@ -160,14 +154,10 @@ def test_sampler_reverse_meas_order(self): self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}) # qc({x: pi/2, y: 0}) - self.assertDictAlmostEqual( - result.quasi_dists[2], {1: 0.4990234375, 5: 0.5009765625} - ) + self.assertDictAlmostEqual(result.quasi_dists[2], {1: 0.4990234375, 5: 0.5009765625}) # qc({x: 0, y: pi/2}) - self.assertDictAlmostEqual( - result.quasi_dists[3], {1: 0.4814453125, 3: 0.5185546875} - ) + self.assertDictAlmostEqual(result.quasi_dists[3], {1: 0.4814453125, 3: 0.5185546875}) def test_1qubit(self): """test for 1-qubit cases""" diff --git a/test/terra/pulse/controllers/test_pulse_controller.py b/test/terra/pulse/controllers/test_pulse_controller.py index 3569108a7b..161bb469e9 100644 --- a/test/terra/pulse/controllers/test_pulse_controller.py +++ b/test/terra/pulse/controllers/test_pulse_controller.py @@ -42,27 +42,19 @@ def test_without_override(self): self.default_dict, {}, self.calculate_channel_frequencies ) - self.assertAlmostEqual( - np.array(output_dict["freqs"]), np.array(self.default_dict["freqs"]) - ) + self.assertAlmostEqual(np.array(output_dict["freqs"]), np.array(self.default_dict["freqs"])) output_dict = setup_rhs_dict_freqs( - self.default_dict, - {"qubit_lo_freq": None}, - self.calculate_channel_frequencies, + self.default_dict, {"qubit_lo_freq": None}, self.calculate_channel_frequencies ) - self.assertAlmostEqual( - np.array(output_dict["freqs"]), np.array(self.default_dict["freqs"]) - ) + self.assertAlmostEqual(np.array(output_dict["freqs"]), np.array(self.default_dict["freqs"])) def test_with_override(self): """Test overriding of default values with qubit_lo_freq in exp.""" output_dict = setup_rhs_dict_freqs( - self.default_dict, - {"qubit_lo_freq": [5, 11]}, - self.calculate_channel_frequencies, + self.default_dict, {"qubit_lo_freq": [5, 11]}, self.calculate_channel_frequencies ) self.assertAlmostEqual(np.array(output_dict["freqs"]), np.array([5, -6, 11])) diff --git a/test/terra/pulse/de/test_de_methods.py b/test/terra/pulse/de/test_de_methods.py index fcf24b8828..a5cc9b0926 100644 --- a/test/terra/pulse/de/test_de_methods.py +++ b/test/terra/pulse/de/test_de_methods.py @@ -81,9 +81,7 @@ def test_QiskitZVODE_options_and_defaults(self): def test_QiskitZVODE_instantiation_error(self): """Test option handling for QiskitZVODE solver.""" - expected_message = ( - "QiskitZVODE solver requires t0, y0, and rhs at instantiation." - ) + expected_message = "QiskitZVODE solver requires t0, y0, and rhs at instantiation." options = DE_Options(method="zvode-adams") try: diff --git a/test/terra/pulse/de/test_type_utils.py b/test/terra/pulse/de/test_type_utils.py index eba6b77b01..0092df5e25 100644 --- a/test/terra/pulse/de/test_type_utils.py +++ b/test/terra/pulse/de/test_type_utils.py @@ -91,9 +91,7 @@ def test_from_outer_instance_inner_type_spec(self): inner_type_spec = {"type": "array", "ndim": 1} outer_y = np.array([[1, 2], [3, 4]]) - converter = StateTypeConverter.from_outer_instance_inner_type_spec( - outer_y, inner_type_spec - ) + converter = StateTypeConverter.from_outer_instance_inner_type_spec(outer_y, inner_type_spec) self.assertEqual(converter.inner_type_spec, {"type": "array", "shape": (4,)}) self.assertEqual(converter.outer_type_spec, {"type": "array", "shape": (2, 2)}) @@ -102,9 +100,7 @@ def test_from_outer_instance_inner_type_spec(self): inner_type_spec = {"type": "array"} outer_y = np.array([[1, 2], [3, 4]]) - converter = StateTypeConverter.from_outer_instance_inner_type_spec( - outer_y, inner_type_spec - ) + converter = StateTypeConverter.from_outer_instance_inner_type_spec(outer_y, inner_type_spec) self.assertEqual(converter.inner_type_spec, {"type": "array", "shape": (2, 2)}) self.assertEqual(converter.outer_type_spec, {"type": "array", "shape": (2, 2)}) diff --git a/test/terra/pulse/test_duffing_model_generators.py b/test/terra/pulse/test_duffing_model_generators.py index 03666d4a1f..760d6d30d9 100644 --- a/test/terra/pulse/test_duffing_model_generators.py +++ b/test/terra/pulse/test_duffing_model_generators.py @@ -19,9 +19,7 @@ from qiskit_aer.pulse.system_models.pulse_system_model import PulseSystemModel from qiskit_aer.pulse.system_models.hamiltonian_model import HamiltonianModel from qiskit_aer.pulse.system_models import duffing_model_generators as model_gen -from qiskit_aer.pulse.system_models.string_model_parser.operator_generators import ( - get_oper, -) +from qiskit_aer.pulse.system_models.string_model_parser.operator_generators import get_oper from qiskit.providers.models.backendconfiguration import UchannelLO from qiskit.quantum_info.operators.operator import Operator @@ -40,16 +38,9 @@ def test_duffing_system_model1(self): dt = 1.3 system_model = model_gen.duffing_system_model( - dim_oscillators, - oscillator_freqs, - anharm_freqs, - drive_strengths, - coupling_dict, - dt, + dim_oscillators, oscillator_freqs, anharm_freqs, drive_strengths, coupling_dict, dt ) - cr_idx_dict = { - label: idx for idx, label in enumerate(system_model.control_channel_labels) - } + cr_idx_dict = {label: idx for idx, label in enumerate(system_model.control_channel_labels)} # check basic parameters self.assertEqual(system_model.subsystem_list, [0, 1]) @@ -61,16 +52,13 @@ def test_duffing_system_model1(self): # check u_channel_lo is correct self.assertEqual( - system_model.u_channel_lo, - [[UchannelLO(1, 1.0 + 0.0j)], [UchannelLO(0, 1.0 + 0.0j)]], + system_model.u_channel_lo, [[UchannelLO(1, 1.0 + 0.0j)], [UchannelLO(0, 1.0 + 0.0j)]] ) # check consistency of system_model.u_channel_lo with cr_idx_dict # this should in principle be redundant with the above two checks for q_pair, idx in cr_idx_dict.items(): - self.assertEqual( - system_model.u_channel_lo[idx], [UchannelLO(q_pair[1], 1.0 + 0.0j)] - ) + self.assertEqual(system_model.u_channel_lo[idx], [UchannelLO(q_pair[1], 1.0 + 0.0j)]) # check correct hamiltonian ham_model = system_model.hamiltonian @@ -96,9 +84,9 @@ def test_duffing_system_model1(self): OO1 = O1 & O1 X0 = self._operator_array_from_str(2, ["I", "X"]) X1 = self._operator_array_from_str(2, ["X", "I"]) - exchange = self._operator_array_from_str( - 2, ["Sm", "Sp"] - ) + self._operator_array_from_str(2, ["Sp", "Sm"]) + exchange = self._operator_array_from_str(2, ["Sm", "Sp"]) + self._operator_array_from_str( + 2, ["Sp", "Sm"] + ) expected_terms = [ ("np.pi*(2*v0-alpha0)", O0), ("np.pi*(2*v1-alpha1)", O1), @@ -137,16 +125,9 @@ def test_duffing_system_model2(self): dt = 1.3 system_model = model_gen.duffing_system_model( - dim_oscillators, - oscillator_freqs, - anharm_freqs, - drive_strengths, - coupling_dict, - dt, + dim_oscillators, oscillator_freqs, anharm_freqs, drive_strengths, coupling_dict, dt ) - cr_idx_dict = { - label: idx for idx, label in enumerate(system_model.control_channel_labels) - } + cr_idx_dict = {label: idx for idx, label in enumerate(system_model.control_channel_labels)} # check basic parameters self.assertEqual(system_model.subsystem_list, [0, 1, 2]) @@ -170,9 +151,7 @@ def test_duffing_system_model2(self): # check consistency of system_model.u_channel_lo with cr_idx_dict # this should in principle be redundant with the above two checks for q_pair, idx in cr_idx_dict.items(): - self.assertEqual( - system_model.u_channel_lo[idx], [UchannelLO(q_pair[1], 1.0 + 0.0j)] - ) + self.assertEqual(system_model.u_channel_lo[idx], [UchannelLO(q_pair[1], 1.0 + 0.0j)]) # check correct hamiltonian ham_model = system_model.hamiltonian @@ -204,15 +183,15 @@ def test_duffing_system_model2(self): OO0 = O0 & O0 OO1 = O1 & O1 OO2 = O2 & O2 - X0 = self._operator_array_from_str( - 3, ["I", "I", "A"] - ) + self._operator_array_from_str(3, ["I", "I", "C"]) - X1 = self._operator_array_from_str( - 3, ["I", "A", "I"] - ) + self._operator_array_from_str(3, ["I", "C", "I"]) - X2 = self._operator_array_from_str( - 3, ["A", "I", "I"] - ) + self._operator_array_from_str(3, ["C", "I", "I"]) + X0 = self._operator_array_from_str(3, ["I", "I", "A"]) + self._operator_array_from_str( + 3, ["I", "I", "C"] + ) + X1 = self._operator_array_from_str(3, ["I", "A", "I"]) + self._operator_array_from_str( + 3, ["I", "C", "I"] + ) + X2 = self._operator_array_from_str(3, ["A", "I", "I"]) + self._operator_array_from_str( + 3, ["C", "I", "I"] + ) exchange01 = self._operator_array_from_str( 3, ["I", "Sm", "Sp"] ) + self._operator_array_from_str(3, ["I", "Sp", "Sm"]) @@ -259,26 +238,13 @@ def test_duffing_system_model3(self): oscillator_freqs = [5.0, 5.1, 5.2, 5.3] anharm_freqs = [-0.33, -0.33, -0.32, -0.31] drive_strengths = [1.1, 1.2, 1.3, 1.4] - coupling_dict = { - (0, 2): 0.03, - (1, 0): 0.02, - (0, 3): 0.14, - (3, 1): 0.18, - (1, 2): 0.33, - } + coupling_dict = {(0, 2): 0.03, (1, 0): 0.02, (0, 3): 0.14, (3, 1): 0.18, (1, 2): 0.33} dt = 1.3 system_model = model_gen.duffing_system_model( - dim_oscillators, - oscillator_freqs, - anharm_freqs, - drive_strengths, - coupling_dict, - dt, + dim_oscillators, oscillator_freqs, anharm_freqs, drive_strengths, coupling_dict, dt ) - cr_idx_dict = { - label: idx for idx, label in enumerate(system_model.control_channel_labels) - } + cr_idx_dict = {label: idx for idx, label in enumerate(system_model.control_channel_labels)} # check basic parameters self.assertEqual(system_model.subsystem_list, [0, 1, 2, 3]) @@ -322,9 +288,7 @@ def test_duffing_system_model3(self): # check consistency of system_model.u_channel_lo with cr_idx_dict # this should in principle be redundant with the above two checks for q_pair, idx in cr_idx_dict.items(): - self.assertEqual( - system_model.u_channel_lo[idx], [UchannelLO(q_pair[1], 1.0 + 0.0j)] - ) + self.assertEqual(system_model.u_channel_lo[idx], [UchannelLO(q_pair[1], 1.0 + 0.0j)]) # check correct hamiltonian ham_model = system_model.hamiltonian @@ -351,22 +315,7 @@ def test_duffing_system_model3(self): self.assertEqual(ham_model._subsystem_dims, {0: 2, 1: 2, 2: 2, 3: 2}) self._compare_str_lists( list(ham_model._channels), - [ - "D0", - "D1", - "D3", - "D4", - "U0", - "U1", - "U2", - "U3", - "U4", - "U5", - "U6", - "U7", - "U8", - "U9", - ], + ["D0", "D1", "D3", "D4", "U0", "U1", "U2", "U3", "U4", "U5", "U6", "U7", "U8", "U9"], ) # check that Hamiltonian terms have been imported correctly @@ -380,18 +329,18 @@ def test_duffing_system_model3(self): OO1 = O1 & O1 OO2 = O2 & O2 OO3 = O3 & O3 - X0 = self._operator_array_from_str( - 2, ["I", "I", "I", "A"] - ) + self._operator_array_from_str(2, ["I", "I", "I", "C"]) - X1 = self._operator_array_from_str( - 2, ["I", "I", "A", "I"] - ) + self._operator_array_from_str(2, ["I", "I", "C", "I"]) - X2 = self._operator_array_from_str( - 2, ["I", "A", "I", "I"] - ) + self._operator_array_from_str(2, ["I", "C", "I", "I"]) - X3 = self._operator_array_from_str( - 2, ["A", "I", "I", "I"] - ) + self._operator_array_from_str(2, ["C", "I", "I", "I"]) + X0 = self._operator_array_from_str(2, ["I", "I", "I", "A"]) + self._operator_array_from_str( + 2, ["I", "I", "I", "C"] + ) + X1 = self._operator_array_from_str(2, ["I", "I", "A", "I"]) + self._operator_array_from_str( + 2, ["I", "I", "C", "I"] + ) + X2 = self._operator_array_from_str(2, ["I", "A", "I", "I"]) + self._operator_array_from_str( + 2, ["I", "C", "I", "I"] + ) + X3 = self._operator_array_from_str(2, ["A", "I", "I", "I"]) + self._operator_array_from_str( + 2, ["C", "I", "I", "I"] + ) exchange01 = self._operator_array_from_str( 2, ["I", "I", "Sm", "Sp"] ) + self._operator_array_from_str(2, ["I", "I", "Sp", "Sm"]) @@ -584,12 +533,7 @@ def test_calculate_channel_frequencies(self): dt = 1.3 system_model = model_gen.duffing_system_model( - dim_oscillators, - oscillator_freqs, - anharm_freqs, - drive_strengths, - coupling_dict, - dt, + dim_oscillators, oscillator_freqs, anharm_freqs, drive_strengths, coupling_dict, dt ) channel_freqs = system_model.calculate_channel_frequencies([5.0, 5.1]) @@ -629,22 +573,14 @@ def test_single_term_generators(self): ) self.assertEqual( model_gen._single_duffing_drift_terms( - freq_symbols=["v0", "v1"], - anharm_symbols=["a0", "a1"], - system_list=[2, 3], + freq_symbols=["v0", "v1"], anharm_symbols=["a0", "a1"], system_list=[2, 3] ), - [ - "np.pi*(2*v0-a0)*O2", - "np.pi*(2*v1-a1)*O3", - "np.pi*a0*O2*O2", - "np.pi*a1*O3*O3", - ], + ["np.pi*(2*v0-a0)*O2", "np.pi*(2*v1-a1)*O3", "np.pi*a0*O2*O2", "np.pi*a1*O3*O3"], ) # drive terms self.assertEqual( - model_gen._drive_terms(drive_symbols="r", system_list=0), - ["2*np.pi*r*X0||D0"], + model_gen._drive_terms(drive_symbols="r", system_list=0), ["2*np.pi*r*X0||D0"] ) self.assertEqual( model_gen._drive_terms(drive_symbols=["r0", "r1"], system_list=[1, 2]), @@ -666,16 +602,12 @@ def test_single_term_generators(self): driven_indices = 0 u_channel_indices = [1] expected = ["2*np.pi*r*X0||U1"] - self.assertEqual( - model_gen._cr_terms(symbols, driven_indices, u_channel_indices), expected - ) + self.assertEqual(model_gen._cr_terms(symbols, driven_indices, u_channel_indices), expected) symbols = ["r", "s"] driven_indices = [0, 3] u_channel_indices = [1, 1] expected = ["2*np.pi*r*X0||U1", "2*np.pi*s*X3||U1"] - self.assertEqual( - model_gen._cr_terms(symbols, driven_indices, u_channel_indices), expected - ) + self.assertEqual(model_gen._cr_terms(symbols, driven_indices, u_channel_indices), expected) def test_str_list_generator(self): """Test _str_list_generator""" @@ -684,15 +616,12 @@ def test_str_list_generator(self): template = "First: {0}" self.assertEqual(model_gen._str_list_generator(template, "a"), ["First: a"]) self.assertEqual( - model_gen._str_list_generator(template, ["a1", "a2"]), - ["First: a1", "First: a2"], + model_gen._str_list_generator(template, ["a1", "a2"]), ["First: a1", "First: a2"] ) # test multiple arguments template = "First: {0}, Second: {1}" - self.assertEqual( - model_gen._str_list_generator(template, "a", "b"), ["First: a, Second: b"] - ) + self.assertEqual(model_gen._str_list_generator(template, "a", "b"), ["First: a, Second: b"]) self.assertEqual( model_gen._str_list_generator(template, ["a1", "a2"], ["b1", "b2"]), ["First: a1, Second: b1", "First: a2, Second: b2"], @@ -715,8 +644,7 @@ def test_CouplingGraph(self): self.assertEqual(len(coupling_graph.graph), 3) self.assertEqual(coupling_graph.sorted_graph, [(0, 1), (1, 2), (2, 3)]) self.assertEqual( - coupling_graph.sorted_two_way_graph, - [(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2)], + coupling_graph.sorted_two_way_graph, [(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2)] ) self.assertEqual( coupling_graph.two_way_graph_dict, diff --git a/test/terra/pulse/test_system_models.py b/test/terra/pulse/test_system_models.py index ad0118aed0..c48b309b4c 100644 --- a/test/terra/pulse/test_system_models.py +++ b/test/terra/pulse/test_system_models.py @@ -33,13 +33,9 @@ def setUp(self): self._default_qubit_lo_freq = [4.9, 5.0] self._u_channel_lo = [] self._u_channel_lo.append([UchannelLO(0, 1.0 + 0.0j)]) - self._u_channel_lo.append( - [UchannelLO(0, -1.0 + 0.0j), UchannelLO(1, 1.0 + 0.0j)] - ) + self._u_channel_lo.append([UchannelLO(0, -1.0 + 0.0j), UchannelLO(1, 1.0 + 0.0j)]) - def _simple_system_model( - self, v0=5.0, v1=5.1, j=0.01, r=0.02, alpha0=-0.33, alpha1=-0.33 - ): + def _simple_system_model(self, v0=5.0, v1=5.1, j=0.01, r=0.02, alpha0=-0.33, alpha1=-0.33): hamiltonian = {} hamiltonian["h_str"] = [ "np.pi*(2*v0-alpha0)*O0", @@ -146,9 +142,7 @@ def test_qubit_lo_from_configurable_backend(self): test_model = PulseSystemModel.from_backend(backend) qubit_lo_from_hamiltonian = test_model.hamiltonian.get_qubit_lo_from_drift() freqs = test_model.calculate_channel_frequencies(qubit_lo_from_hamiltonian) - expected = getattr(backend.configuration(), "hamiltonian")["vars"]["wq0"] / ( - 2 * np.pi - ) + expected = getattr(backend.configuration(), "hamiltonian")["vars"]["wq0"] / (2 * np.pi) self.assertAlmostEqual(freqs["D0"], expected, places=5) def _compute_u_lo_freqs(self, qubit_lo_freq): @@ -220,9 +214,7 @@ def test_subsystem_list_from_dict(self): self.assertEqual(len(channel_labels0), 2) qubit_lo_freq0 = ham_model0.get_qubit_lo_from_drift() - expected_freq0 = np.array( - [(np.pi * (2 * v0 - alpha0) + np.pi * alpha0) / (2 * np.pi)] - ) + expected_freq0 = np.array([(np.pi * (2 * v0 - alpha0) + np.pi * alpha0) / (2 * np.pi)]) self.assertAlmostEqual(norm(qubit_lo_freq0 - expected_freq0), 0) # restrict to qubit 1 and verify some properties @@ -243,9 +235,7 @@ def test_subsystem_list_from_dict(self): self.assertEqual(len(channel_labels1), 2) qubit_lo_freq1 = ham_model1.get_qubit_lo_from_drift() - expected_freq1 = np.array( - [0, (np.pi * (2 * v1 - alpha1) + np.pi * alpha1) / (2 * np.pi)] - ) + expected_freq1 = np.array([0, (np.pi * (2 * v1 - alpha1) + np.pi * alpha1) / (2 * np.pi)]) self.assertAlmostEqual(norm(qubit_lo_freq1 - expected_freq1), 0) def test_eigen_sorting(self): @@ -316,9 +306,7 @@ def test_empty_hamiltonian_string_exception(self): def test_empty_qub_exception(self): """Test exception raising for empty qub""" - message = ( - "Hamiltonian dict requires non-empty 'qub' entry with subsystem dimensions." - ) + message = "Hamiltonian dict requires non-empty 'qub' entry with subsystem dimensions." ham_dict = {"h_str": "X0"} self.assert_hamiltonian_parse_exception(ham_dict, message) diff --git a/test/terra/reference/ref_2q_clifford.py b/test/terra/reference/ref_2q_clifford.py index 0911bfb2bb..f6903dba7d 100644 --- a/test/terra/reference/ref_2q_clifford.py +++ b/test/terra/reference/ref_2q_clifford.py @@ -259,13 +259,11 @@ def cx_gate_unitary_nondeterministic(): targets = [] # CX01.(I^H), Bell state targets.append( - np.array([[1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1], [1, -1, 0, 0]]) - / np.sqrt(2) + np.array([[1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1], [1, -1, 0, 0]]) / np.sqrt(2) ) # CX10.(I^H), Bell state targets.append( - np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, -1], [1, 0, -1, 0]]) - / np.sqrt(2) + np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, -1], [1, 0, -1, 0]]) / np.sqrt(2) ) return targets @@ -470,13 +468,11 @@ def cz_gate_unitary_nondeterministic(): targets = [] # (I^H).CZ.(H^H) = CX10.(H^I), Bell state targets.append( - np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, -1], [1, 0, -1, 0]]) - / np.sqrt(2) + np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, -1], [1, 0, -1, 0]]) / np.sqrt(2) ) # (H^I).CZ.(H^H) = CX01.(I^H), Bell state targets.append( - np.array([[1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1], [1, -1, 0, 0]]) - / np.sqrt(2) + np.array([[1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1], [1, -1, 0, 0]]) / np.sqrt(2) ) return targets diff --git a/test/terra/reference/ref_algorithms.py b/test/terra/reference/ref_algorithms.py index 1113db85d4..385c81f5f0 100644 --- a/test/terra/reference/ref_algorithms.py +++ b/test/terra/reference/ref_algorithms.py @@ -77,14 +77,10 @@ def grovers_counts(shots, hex_counts=True): targets = [] if hex_counts: # 6-qubit grovers - targets.append( - {"0x0": 5 * shots / 8, "0x1": shots / 8, "0x2": shots / 8, "0x3": shots / 8} - ) + targets.append({"0x0": 5 * shots / 8, "0x1": shots / 8, "0x2": shots / 8, "0x3": shots / 8}) else: # 6-qubit grovers - targets.append( - {"00": 5 * shots / 8, "01": shots / 8, "10": shots / 8, "11": shots / 8} - ) + targets.append({"00": 5 * shots / 8, "01": shots / 8, "10": shots / 8, "11": shots / 8}) return targets @@ -122,17 +118,10 @@ def teleport_counts(shots, hex_counts=True): targets = [] if hex_counts: # Classical 3-qubit teleport - targets.append( - {"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4} - ) + targets.append({"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4}) else: # Classical 3-qubit teleport targets.append( - { - "0 0 0": shots / 4, - "0 0 1": shots / 4, - "0 1 0": shots / 4, - "0 1 1": shots / 4, - } + {"0 0 0": shots / 4, "0 0 1": shots / 4, "0 1 0": shots / 4, "0 1 1": shots / 4} ) return targets diff --git a/test/terra/reference/ref_diagonal_gate.py b/test/terra/reference/ref_diagonal_gate.py index 9c9eab1fdb..72f506b9c1 100644 --- a/test/terra/reference/ref_diagonal_gate.py +++ b/test/terra/reference/ref_diagonal_gate.py @@ -38,12 +38,7 @@ def diagonal_gate_circuits_deterministic(final_measure=True): # 4 x Swap |00> <--> |10> states arg = [1, -1] for qubit in [0, 1]: - for diag in [ - arg, - np.array(arg), - np.array(arg, dtype=float), - np.array(arg, dtype=complex), - ]: + for diag in [arg, np.array(arg), np.array(arg, dtype=float), np.array(arg, dtype=complex)]: circuit = QuantumCircuit(*regs) circuit.h(qubit) circuit.diagonal(list(diag), [qubit]) @@ -55,12 +50,7 @@ def diagonal_gate_circuits_deterministic(final_measure=True): # 4 x Swap |00> <--> |11> states arg = [1, -1, -1, 1] - for diag in [ - arg, - np.array(arg), - np.array(arg, dtype=float), - np.array(arg, dtype=complex), - ]: + for diag in [arg, np.array(arg), np.array(arg, dtype=float), np.array(arg, dtype=complex)]: circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.diagonal(list(diag), qr) @@ -71,9 +61,7 @@ def diagonal_gate_circuits_deterministic(final_measure=True): circuits.append(circuit) # CS01.XX, exp(-1j * np.pi/k)|11> state - for diag in [ - np.array([1, 1, 1, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000] - ]: + for diag in [np.array([1, 1, 1, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000]]: circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.diagonal(list(diag), qr) @@ -119,9 +107,7 @@ def diagonal_gate_statevector_deterministic(): # Swap |00> <--> |11> states targets += 4 * [np.array([0, 0, 0, 1])] # CS01.XX, exp(-1j * np.pi/k)|11> state - targets += [ - np.array([0, 0, 0, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000] - ] + targets += [np.array([0, 0, 0, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000]] return targets @@ -137,14 +123,7 @@ def diagonal_gate_unitary_deterministic(): targets += 4 * [np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])] # CS01.XX, 1j|11> state targets += [ - np.array( - [ - [0, 0, 0, 1], - [0, 0, 1, 0], - [0, 1, 0, 0], - [np.exp(-1j * np.pi / k), 0, 0, 0], - ] - ) + np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [np.exp(-1j * np.pi / k), 0, 0, 0]]) for k in [10, 100, 1000, 10000] ] return targets diff --git a/test/terra/reference/ref_initialize.py b/test/terra/reference/ref_initialize.py index fd72192f3b..15e6df0f75 100644 --- a/test/terra/reference/ref_initialize.py +++ b/test/terra/reference/ref_initialize.py @@ -131,8 +131,7 @@ def initialize_circuits_1(final_measure=True): circuit.h(qr[1]) circuit.h(qr[2]) circuit.initialize( - [0, 1, 0, 0, 0, -1, 0, 0] / sqrt(2), - [qr[qubit_i], qr[qubit_j], qr[qubit_k]], + [0, 1, 0, 0, 0, -1, 0, 0] / sqrt(2), [qr[qubit_i], qr[qubit_j], qr[qubit_k]] ) if final_measure: @@ -148,17 +147,11 @@ def initialize_counts_1(shots, hex_counts=True): targets = [] if hex_counts: # Initialize 0 to |1> from |+++> - targets.append( - {"0x1": shots / 4, "0x3": shots / 4, "0x5": shots / 4, "0x7": shots / 4} - ) + targets.append({"0x1": shots / 4, "0x3": shots / 4, "0x5": shots / 4, "0x7": shots / 4}) # Initialize 1 to |1> from |+++> - targets.append( - {"0x2": shots / 4, "0x3": shots / 4, "0x6": shots / 4, "0x7": shots / 4} - ) + targets.append({"0x2": shots / 4, "0x3": shots / 4, "0x6": shots / 4, "0x7": shots / 4}) # Initialize 2 to |1> from |+++> - targets.append( - {"0x4": shots / 4, "0x5": shots / 4, "0x6": shots / 4, "0x7": shots / 4} - ) + targets.append({"0x4": shots / 4, "0x5": shots / 4, "0x6": shots / 4, "0x7": shots / 4}) # Initialize 0,1 to |01> from |+++> targets.append({"0x1": shots / 2, "0x5": shots / 2}) # Initialize 0,2 to |01> from |+++> @@ -185,17 +178,11 @@ def initialize_counts_1(shots, hex_counts=True): targets.append({"0x4": shots / 2, "0x5": shots / 2}) else: # Initialize 0 to |1> from |+++> - targets.append( - {"001": shots / 4, "011": shots / 4, "101": shots / 4, "111": shots / 4} - ) + targets.append({"001": shots / 4, "011": shots / 4, "101": shots / 4, "111": shots / 4}) # Initialize 1 to |1> from |+++> - targets.append( - {"010": shots / 4, "011": shots / 4, "110": shots / 4, "111": shots / 4} - ) + targets.append({"010": shots / 4, "011": shots / 4, "110": shots / 4, "111": shots / 4}) # Initialize 2 to |1> from |+++> - targets.append( - {"100": shots / 4, "101": shots / 4, "110": shots / 4, "111": shots / 4} - ) + targets.append({"100": shots / 4, "101": shots / 4, "110": shots / 4, "111": shots / 4}) # Initialize 0,1 to |01> from |+++> targets.append({"001": shots / 2, "101": shots / 2}) # Initialize 0,2 to |01> from |+++> diff --git a/test/terra/reference/ref_measure.py b/test/terra/reference/ref_measure.py index e7106108a6..8db104dfd2 100644 --- a/test/terra/reference/ref_measure.py +++ b/test/terra/reference/ref_measure.py @@ -199,14 +199,10 @@ def measure_counts_nondeterministic(shots, hex_counts=True): targets = [] if hex_counts: # Measure |++> state - targets.append( - {"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4} - ) + targets.append({"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4}) else: # Measure |++> state - targets.append( - {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4} - ) + targets.append({"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4}) return targets @@ -377,20 +373,12 @@ def multiqubit_measure_counts_nondeterministic(shots, hex_counts=True): targets = [] if hex_counts: # 2-qubit measure |++> - targets.append( - {"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4} - ) + targets.append({"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4}) # 3-qubit measure |0++> - targets.append( - {"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4} - ) + targets.append({"0x0": shots / 4, "0x1": shots / 4, "0x2": shots / 4, "0x3": shots / 4}) else: # 2-qubit measure |++> - targets.append( - {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4} - ) + targets.append({"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4}) # 3-qubit measure |0++> - targets.append( - {"000": shots / 4, "001": shots / 4, "010": shots / 4, "011": shots / 4} - ) + targets.append({"000": shots / 4, "001": shots / 4, "010": shots / 4, "011": shots / 4}) return targets diff --git a/test/terra/reference/ref_multiplexer.py b/test/terra/reference/ref_multiplexer.py index 4d92161fe7..028cdf78ae 100644 --- a/test/terra/reference/ref_multiplexer.py +++ b/test/terra/reference/ref_multiplexer.py @@ -182,9 +182,7 @@ def multiplexer_ccx_gate_circuits_deterministic(final_measure=True): # CCX(0,1,2) circuit = QuantumCircuit(*regs) - circuit.append( - multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[0], qr[1]] - ) + circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[0], qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) @@ -196,9 +194,7 @@ def multiplexer_ccx_gate_circuits_deterministic(final_measure=True): circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) - circuit.append( - multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[0], qr[1]] - ) + circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[0], qr[1]]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) @@ -210,9 +206,7 @@ def multiplexer_ccx_gate_circuits_deterministic(final_measure=True): # CCX(2,1,0) circuit = QuantumCircuit(*regs) - circuit.append( - multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[2], qr[1]] - ) + circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[2], qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) @@ -224,9 +218,7 @@ def multiplexer_ccx_gate_circuits_deterministic(final_measure=True): circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) - circuit.append( - multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[2], qr[1]] - ) + circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[2], qr[1]]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) @@ -258,9 +250,7 @@ def multiplexer_ccx_gate_circuits_nondeterministic(final_measure=True): circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) - circuit.append( - multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[0], qr[1]] - ) + circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[0], qr[1]]) circuit.barrier(qr) circuit.x(qr[1]) if final_measure: @@ -274,9 +264,7 @@ def multiplexer_ccx_gate_circuits_nondeterministic(final_measure=True): circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) - circuit.append( - multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[2], qr[1]] - ) + circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[2], qr[1]]) circuit.barrier(qr) circuit.x(qr[2]) if final_measure: diff --git a/test/terra/reference/ref_non_clifford.py b/test/terra/reference/ref_non_clifford.py index ef31b24416..0828e510e0 100644 --- a/test/terra/reference/ref_non_clifford.py +++ b/test/terra/reference/ref_non_clifford.py @@ -172,13 +172,9 @@ def t_gate_unitary_nondeterministic(): """T-gate circuits reference unitaries.""" targets = [] # T.H - targets.append( - np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 + 0.5j, -0.5 - 0.5j]]) - ) + targets.append(np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 + 0.5j, -0.5 - 0.5j]])) # X.T.H - targets.append( - np.array([[0.5 + 0.5j, -0.5 - 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]]) - ) + targets.append(np.array([[0.5 + 0.5j, -0.5 - 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]])) # H.T.T.H = H.S.H targets.append(np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]]) / 2) return targets @@ -345,13 +341,9 @@ def tdg_gate_unitary_nondeterministic(): """Tdg-gate circuits reference unitaries.""" targets = [] # Tdg.H - targets.append( - np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 - 0.5j, -0.5 + 0.5j]]) - ) + targets.append(np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 - 0.5j, -0.5 + 0.5j]])) # X.Tdg.H - targets.append( - np.array([[0.5 - 0.5j, -0.5 + 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]]) - ) + targets.append(np.array([[0.5 - 0.5j, -0.5 + 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]])) # H.Tdg.Tdg.H = H.Sdg.H targets.append(np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]]) / 2) return targets @@ -1459,10 +1451,7 @@ def cu1_gate_counts_nondeterministic(shots, hex_counts=True): targets.append({"0x0": shots}) # H^X.CU1(pi/4,0,1).H^X targets.append( - { - "0x0": shots * (0.25 * (2 + np.sqrt(2))), - "0x2": shots * (0.25 * (2 - np.sqrt(2))), - } + {"0x0": shots * (0.25 * (2 + np.sqrt(2))), "0x2": shots * (0.25 * (2 - np.sqrt(2)))} ) # H^X.CU1(pi/2,0,1).H^X targets.append({"0x0": shots * 0.5, "0x2": shots * 0.5}) @@ -1472,21 +1461,11 @@ def cu1_gate_counts_nondeterministic(shots, hex_counts=True): targets.append({"0x0": shots}) # H^H.CU1(pi/2,0,1).H^H targets.append( - { - "0x0": shots * 0.625, - "0x1": shots * 0.125, - "0x2": shots * 0.125, - "0x3": shots * 0.125, - } + {"0x0": shots * 0.625, "0x1": shots * 0.125, "0x2": shots * 0.125, "0x3": shots * 0.125} ) # H^H.CU1(pi,0,1).H^H targets.append( - { - "0x0": shots * 0.25, - "0x1": shots * 0.25, - "0x2": shots * 0.25, - "0x3": shots * 0.25, - } + {"0x0": shots * 0.25, "0x1": shots * 0.25, "0x2": shots * 0.25, "0x3": shots * 0.25} ) else: # H^X.CU1(0,0,1).H^X @@ -1503,21 +1482,11 @@ def cu1_gate_counts_nondeterministic(shots, hex_counts=True): targets.append({"00": shots}) # H^H.CU1(pi/2,0,1).H^H targets.append( - { - "00": shots * 0.5125, - "01": shots * 0.125, - "10": shots * 0.125, - "11": shots * 0.125, - } + {"00": shots * 0.5125, "01": shots * 0.125, "10": shots * 0.125, "11": shots * 0.125} ) # H^H.CU1(pi,0,1).H^H targets.append( - { - "00": shots * 0.25, - "01": shots * 0.25, - "10": shots * 0.25, - "11": shots * 0.25, - } + {"00": shots * 0.25, "01": shots * 0.25, "10": shots * 0.25, "11": shots * 0.25} ) return targets @@ -1597,13 +1566,10 @@ def cu1_gate_unitary_nondeterministic(): # H^H.CU1(pi/2,0,1).H^H targets.append( (0.75 + 0.25j) * np.eye(4) - + (0.25 - 0.25j) - * np.array([[0, 1, 1, -1], [1, 0, -1, 1], [1, -1, 0, 1], [-1, 1, 1, 0]]) + + (0.25 - 0.25j) * np.array([[0, 1, 1, -1], [1, 0, -1, 1], [1, -1, 0, 1], [-1, 1, 1, 0]]) ) # H^H.CU1(pi,0,1).H^H - targets.append( - 0.5 * np.array([[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]]) - ) + targets.append(0.5 * np.array([[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]])) return targets @@ -1706,9 +1672,7 @@ def cu3_gate_unitary_deterministic(): ) # I^X.CRX(pi).I^X - targets.append( - np.array([[0, 0, -1j, 0], [0, 1, 0, 0], [-1j, 0, 0, 0], [0, 0, 0, 1]]) - ) + targets.append(np.array([[0, 0, -1j, 0], [0, 1, 0, 0], [-1j, 0, 0, 0], [0, 0, 0, 1]])) # I^X.CRY(pi).I^X targets.append(np.array([[0, 0, -1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) diff --git a/test/terra/reference/ref_readout_noise.py b/test/terra/reference/ref_readout_noise.py index f3f2745152..e5f47a1f08 100644 --- a/test/terra/reference/ref_readout_noise.py +++ b/test/terra/reference/ref_readout_noise.py @@ -114,12 +114,8 @@ def readout_error_counts(shots, hex_counts=True): # 1-qubit readout error on qubit 1 p00 = 0.5 * (ROERROR_1Q[0][0] ** 2 + ROERROR_1Q[1][0] ** 2) - p01 = 0.5 * ( - ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1] - ) - p10 = 0.5 * ( - ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1] - ) + p01 = 0.5 * (ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1]) + p10 = 0.5 * (ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1]) p11 = 0.5 * (ROERROR_1Q[0][1] ** 2 + ROERROR_1Q[1][1] ** 2) counts = [p00 * shots, p01 * shots, p10 * shots, p11 * shots] counts_lists.append(counts) diff --git a/test/terra/reference/ref_save_expval.py b/test/terra/reference/ref_save_expval.py index e38ac24087..d272d51ca4 100644 --- a/test/terra/reference/ref_save_expval.py +++ b/test/terra/reference/ref_save_expval.py @@ -217,14 +217,10 @@ def save_expval_final_statevecs(): statevec = Statevector.from_label("+1") statevecs.append(statevec) # State |00> + |11> - statevec = (Statevector.from_label("00") + Statevector.from_label("11")) / np.sqrt( - 2 - ) + statevec = (Statevector.from_label("00") + Statevector.from_label("11")) / np.sqrt(2) statevecs.append(statevec) # State |10> -i|01> - statevec = ( - Statevector.from_label("10") - 1j * Statevector.from_label("01") - ) / np.sqrt(2) + statevec = (Statevector.from_label("10") - 1j * Statevector.from_label("01")) / np.sqrt(2) statevecs.append(statevec) return statevecs @@ -254,9 +250,7 @@ def save_expval_post_meas_values(): if not np.isclose(vec.data.dot(statevec.data), 0): # If outcome is non-zero compute expectation value # with post-selected outcome state - inner_dict[hex(int(j, 2))] = vec.data.conj().dot( - vec.evolve(mat, qubits).data - ) + inner_dict[hex(int(j, 2))] = vec.data.conj().dot(vec.evolve(mat, qubits).data) values[label] = inner_dict targets.append(values) return targets @@ -365,8 +359,7 @@ def save_expval_circuit_parameterized( ] ).tolist() parameterizations = [ - [list(index), params] - for (index, params) in zip(plus_one_params.keys(), param_mat) + [list(index), params] for (index, params) in zip(plus_one_params.keys(), param_mat) ] return circuit, parameterizations diff --git a/test/terra/reference/ref_unitary_gate.py b/test/terra/reference/ref_unitary_gate.py index 58a5bbc662..5692ac7921 100644 --- a/test/terra/reference/ref_unitary_gate.py +++ b/test/terra/reference/ref_unitary_gate.py @@ -33,9 +33,7 @@ def unitary_gate_circuits_deterministic(final_measure=True): else: regs = (qr,) y_mat = np.array([[0, -1j], [1j, 0]], dtype=complex) - cx_mat = np.array( - [[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex - ) + cx_mat = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex) # CX01, |00> state circuit = QuantumCircuit(*regs) @@ -149,21 +147,13 @@ def unitary_gate_unitary_deterministic(): # CX10, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])) # CX01.(Y^I), |10> state - targets.append( - np.array([[0, 0, -1j, 0], [0, 1j, 0, 0], [1j, 0, 0, 0], [0, 0, 0, -1j]]) - ) + targets.append(np.array([[0, 0, -1j, 0], [0, 1j, 0, 0], [1j, 0, 0, 0], [0, 0, 0, -1j]])) # CX10.(I^Y), |01> state - targets.append( - np.array([[0, -1j, 0, 0], [1j, 0, 0, 0], [0, 0, 1j, 0], [0, 0, 0, -1j]]) - ) + targets.append(np.array([[0, -1j, 0, 0], [1j, 0, 0, 0], [0, 0, 1j, 0], [0, 0, 0, -1j]])) # CX01.(I^Y), |11> state - targets.append( - np.array([[0, -1j, 0, 0], [0, 0, 1j, 0], [0, 0, 0, -1j], [1j, 0, 0, 0]]) - ) + targets.append(np.array([[0, -1j, 0, 0], [0, 0, 1j, 0], [0, 0, 0, -1j], [1j, 0, 0, 0]])) # CX10.(Y^I), |11> state - targets.append( - np.array([[0, 0, -1j, 0], [0, 0, 0, -1j], [0, 1j, 0, 0], [1j, 0, 0, 0]]) - ) + targets.append(np.array([[0, 0, -1j, 0], [0, 0, 0, -1j], [0, 1j, 0, 0], [1j, 0, 0, 0]])) return targets diff --git a/test/terra/states/test_aer_densitymatrix.py b/test/terra/states/test_aer_densitymatrix.py index 9436357c1d..61aacb20cc 100644 --- a/test/terra/states/test_aer_densitymatrix.py +++ b/test/terra/states/test_aer_densitymatrix.py @@ -21,11 +21,7 @@ from qiskit.exceptions import QiskitError from qiskit.circuit import QuantumCircuit, QuantumRegister -from qiskit.quantum_info.random import ( - random_unitary, - random_density_matrix, - random_pauli, -) +from qiskit.quantum_info.random import random_unitary, random_density_matrix, random_pauli from qiskit.quantum_info.states import DensityMatrix, Statevector from qiskit.circuit.library import QuantumVolume from qiskit.quantum_info import Kraus @@ -497,23 +493,17 @@ def test_evolve_subsystem(self): # Test evolve on 1-qubit op = op0 op_full = Operator(np.eye(4)).tensor(op) - target = AerDensityMatrix( - np.dot(op_full.data, rho).dot(op_full.adjoint().data) - ) + target = AerDensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0]), target) # Evolve on qubit 1 op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2)) - target = AerDensityMatrix( - np.dot(op_full.data, rho).dot(op_full.adjoint().data) - ) + target = AerDensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[1]), target) # Evolve on qubit 2 op_full = op.tensor(np.eye(4)) - target = AerDensityMatrix( - np.dot(op_full.data, rho).dot(op_full.adjoint().data) - ) + target = AerDensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2]), target) # Test evolve on 2-qubits @@ -521,16 +511,12 @@ def test_evolve_subsystem(self): # Evolve on qubits [0, 2] op_full = op1.tensor(np.eye(2)).tensor(op0) - target = AerDensityMatrix( - np.dot(op_full.data, rho).dot(op_full.adjoint().data) - ) + target = AerDensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 2]), target) # Evolve on qubits [2, 0] op_full = op0.tensor(np.eye(2)).tensor(op1) - target = AerDensityMatrix( - np.dot(op_full.data, rho).dot(op_full.adjoint().data) - ) + target = AerDensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 0]), target) # Test evolve on 3-qubits @@ -538,16 +524,12 @@ def test_evolve_subsystem(self): # Evolve on qubits [0, 1, 2] op_full = op - target = AerDensityMatrix( - np.dot(op_full.data, rho).dot(op_full.adjoint().data) - ) + target = AerDensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target) # Evolve on qubits [2, 1, 0] op_full = op0.tensor(op1).tensor(op2) - target = AerDensityMatrix( - np.dot(op_full.data, rho).dot(op_full.adjoint().data) - ) + target = AerDensityMatrix(np.dot(op_full.data, rho).dot(op_full.adjoint().data)) self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target) # omit test_evolve_qudit_subsystems since qudit is currently not supported @@ -715,9 +697,7 @@ def test_probabilities_product(self): def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" - psi = ( - AerStatevector.from_label("000") + AerStatevector.from_label("111") - ) / np.sqrt(2) + psi = (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) state = AerDensityMatrix(psi) # 3-qubit qargs @@ -807,9 +787,7 @@ def test_probabilities_dict_product(self): def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" - psi = ( - AerStatevector.from_label("000") + AerStatevector.from_label("111") - ) / np.sqrt(2) + psi = (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) state = AerDensityMatrix(psi) # 3-qubit qargs @@ -871,8 +849,7 @@ def test_sample_counts_ghz(self): shots = 5000 threshold = 0.02 * shots state = AerDensityMatrix( - (AerStatevector.from_label("000") + AerStatevector.from_label("111")) - / np.sqrt(2) + (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) ) state.seed(100) @@ -938,8 +915,7 @@ def test_sample_memory_ghz(self): shots = 2000 state = AerDensityMatrix( - (AerStatevector.from_label("000") + AerStatevector.from_label("111")) - / np.sqrt(2) + (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) ) state.seed(100) @@ -1115,9 +1091,7 @@ def test_from_int(self): self.assertEqual(target, value) with self.subTest(msg="from_int(15, (4, 4))"): - target = AerDensityMatrix( - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(4, 4) - ) + target = AerDensityMatrix([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(4, 4)) value = AerDensityMatrix.from_int(15, (4, 4)) self.assertEqual(target, value) @@ -1339,15 +1313,7 @@ def test_drawings(self): dm = AerDensityMatrix.from_instruction(qc1) with self.subTest(msg="str(density_matrix)"): str(dm) - for drawtype in [ - "repr", - "text", - "latex", - "latex_source", - "qsphere", - "hinton", - "bloch", - ]: + for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): dm.draw(drawtype) diff --git a/test/terra/states/test_aer_state.py b/test/terra/states/test_aer_state.py index 368b0100ed..501a538281 100644 --- a/test/terra/states/test_aer_state.py +++ b/test/terra/states/test_aer_state.py @@ -288,9 +288,7 @@ def test_initialize_density_matrix_with_non_contiguous_ndarray(self): self.assertIsNot(sv1, sv2) self.assertEqual(len(sv1), len(sv2)) - self.assertEqual( - sv1[len(sv1) - 1, len(sv1) - 1], sv2[len(sv2) - 1, len(sv2) - 1] - ) + self.assertEqual(sv1[len(sv1) - 1, len(sv1) - 1], sv2[len(sv2) - 1, len(sv2) - 1]) def test_appply_unitary(self): """Test applying a unitary matrix""" diff --git a/test/terra/states/test_aer_statevector.py b/test/terra/states/test_aer_statevector.py index 5245781066..4de8c9af2e 100644 --- a/test/terra/states/test_aer_statevector.py +++ b/test/terra/states/test_aer_statevector.py @@ -32,10 +32,7 @@ from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.operators.predicates import matrix_equal -from qiskit.visualization.state_visualization import ( - numbers_to_latex_terms, - state_to_latex, -) +from qiskit.visualization.state_visualization import numbers_to_latex_terms, state_to_latex from qiskit.circuit.library import QFT, HGate from test.terra import common @@ -359,9 +356,7 @@ def test_initialize_with_non_contiguous_ndarray(self): vec = u[0, :] state = AerStatevector(vec) - self.assertTrue( - np.allclose(state, vec, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT) - ) + self.assertTrue(np.allclose(state, vec, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT)) def test_initialize_with_terra_statevector(self): """Test Statevector initialization""" @@ -415,9 +410,7 @@ def test_init_circuit(self): self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) - self.assertTrue( - all(state.data == np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex)) - ) + self.assertTrue(all(state.data == np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex))) self.assertEqual(state.num_qubits, 3) def test_init_array_except(self): @@ -797,9 +790,7 @@ def test_probabilities_product(self): def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" - state = ( - AerStatevector.from_label("000") + AerStatevector.from_label("111") - ) / np.sqrt(2) + state = (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) @@ -887,9 +878,7 @@ def test_probabilities_dict_product(self): def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" - state = ( - AerStatevector.from_label("000") + AerStatevector.from_label("111") - ) / np.sqrt(2) + state = (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = {"000": 0.5, "111": 0.5} @@ -948,9 +937,7 @@ def test_sample_counts_ghz(self): shots = 2000 threshold = 0.02 * shots - state = ( - AerStatevector.from_label("000") + AerStatevector.from_label("111") - ) / np.sqrt(2) + state = (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs @@ -1009,9 +996,7 @@ def test_sample_memory_ghz(self): """Test sample_memory method for GHZ state""" shots = 5000 - state = ( - AerStatevector.from_label("000") + AerStatevector.from_label("111") - ) / np.sqrt(2) + state = (AerStatevector.from_label("000") + AerStatevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs @@ -1364,15 +1349,7 @@ def test_drawings(self): sv = AerStatevector.from_instruction(qc1) with self.subTest(msg="str(statevector)"): str(sv) - for drawtype in [ - "repr", - "text", - "latex", - "latex_source", - "qsphere", - "hinton", - "bloch", - ]: + for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): sv.draw(drawtype) with self.subTest(msg=" draw('latex', convention='vector')"): @@ -1410,10 +1387,7 @@ def test_number_to_latex_terms(self): ([1e-16 + 1j], ["i"]), ([-1 + 1e-16 * 1j], ["-"]), ([-1, -1 - 1j], ["-", "+(-1 - i)"]), - ( - [np.sqrt(2) / 2, np.sqrt(2) / 2], - ["\\frac{\\sqrt{2}}{2}", "+\\frac{\\sqrt{2}}{2}"], - ), + ([np.sqrt(2) / 2, np.sqrt(2) / 2], ["\\frac{\\sqrt{2}}{2}", "+\\frac{\\sqrt{2}}{2}"]), ([1 + np.sqrt(2)], ["(1 + \\sqrt{2})"]), ] with self.assertWarns(DeprecationWarning): diff --git a/tools/generate_qobj.py b/tools/generate_qobj.py index 62689453e1..23b0c4ac26 100755 --- a/tools/generate_qobj.py +++ b/tools/generate_qobj.py @@ -69,9 +69,7 @@ def grovers_circuit(final_measure=True, allow_sampling=True): shots = 4000 circuits = grovers_circuit(final_measure=True, allow_sampling=True) if os.getenv("USE_MPI", False): - qobj = assemble( - transpile(circuits), shots=shots, blocking_enable=True, blocking_qubits=2 - ) + qobj = assemble(transpile(circuits), shots=shots, blocking_enable=True, blocking_qubits=2) else: qobj = assemble(transpile(circuits), shots=shots) with open("qobj.json", "wt") as fp: diff --git a/tools/verify_standalone_results.py b/tools/verify_standalone_results.py index a3c3153686..f17e2eef2c 100644 --- a/tools/verify_standalone_results.py +++ b/tools/verify_standalone_results.py @@ -12,9 +12,7 @@ from qiskit.result import Result -def assertDictAlmostEqual( - dict1, dict2, delta=None, msg=None, places=None, default_value=0 -): +def assertDictAlmostEqual(dict1, dict2, delta=None, msg=None, places=None, default_value=0): """Assert two dictionaries with numeric values are almost equal. Fail if the two dictionaries are unequal as determined by @@ -113,11 +111,6 @@ def compare_counts(result, target, delta=0): if os.getenv("USE_MPI", False): assert result.metadata["num_mpi_processes"] > 1 shots = result.results[0].shots - targets = { - "0x0": 5 * shots / 8, - "0x1": shots / 8, - "0x2": shots / 8, - "0x3": shots / 8, - } + targets = {"0x0": 5 * shots / 8, "0x1": shots / 8, "0x2": shots / 8, "0x3": shots / 8} compare_counts(result, targets, delta=0.05 * shots) print("Input result JSON is valid!") diff --git a/tools/verify_wheels.py b/tools/verify_wheels.py index 5be9fc05dd..f1228372de 100644 --- a/tools/verify_wheels.py +++ b/tools/verify_wheels.py @@ -16,15 +16,7 @@ from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit_aer.pulse.system_models.duffing_model_generators import duffing_system_model -from qiskit.pulse import ( - Schedule, - Play, - Acquire, - Waveform, - DriveChannel, - AcquireChannel, - MemorySlot, -) +from qiskit.pulse import Schedule, Play, Acquire, Waveform, DriveChannel, AcquireChannel, MemorySlot from qiskit_aer import AerSimulator from qiskit_aer import QasmSimulator @@ -61,12 +53,7 @@ def assertAlmostEqual(first, second, places=None, msg=None, delta=None): if diff <= delta: return - standardMsg = "%s != %s within %s delta (%s difference)" % ( - first, - second, - delta, - diff, - ) + standardMsg = "%s != %s within %s delta (%s difference)" % (first, second, delta, diff) else: if places is None: places = 7 @@ -74,12 +61,7 @@ def assertAlmostEqual(first, second, places=None, msg=None, delta=None): if round(diff, places) == 0: return - standardMsg = "%s != %s within %r places (%s difference)" % ( - first, - second, - places, - diff, - ) + standardMsg = "%s != %s within %r places (%s difference)" % (first, second, places, diff) raise Exception(standardMsg) @@ -133,9 +115,7 @@ def grovers_circuit(final_measure=True, allow_sampling=True): return circuits -def assertDictAlmostEqual( - dict1, dict2, delta=None, msg=None, places=None, default_value=0 -): +def assertDictAlmostEqual(dict1, dict2, delta=None, msg=None, places=None, default_value=0): """Assert two dictionaries with numeric values are almost equal. Fail if the two dictionaries are unequal as determined by @@ -360,9 +340,7 @@ def cx_gate_unitary_deterministic(): return targets -def compare_statevector( - result, circuits, targets, ignore_phase=False, atol=1e-8, rtol=1e-5 -): +def compare_statevector(result, circuits, targets, ignore_phase=False, atol=1e-8, rtol=1e-5): """Compare final statevectors to targets.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case @@ -373,15 +351,11 @@ def compare_statevector( ) if equiv: return - msg = "Circuit ({}/{}): {} != {}".format( - pos + 1, len(circuits), output.data, target.data - ) + msg = "Circuit ({}/{}): {} != {}".format(pos + 1, len(circuits), output.data, target.data) raise Exception(msg) -def compare_unitary( - result, circuits, targets, ignore_phase=False, atol=1e-8, rtol=1e-5 -): +def compare_unitary(result, circuits, targets, ignore_phase=False, atol=1e-8, rtol=1e-5): """Compare final unitary matrices to targets.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case @@ -392,9 +366,7 @@ def compare_unitary( ) if equiv: return - msg = "Circuit ({}/{}): {} != {}".format( - pos + 1, len(circuits), output.data, target.data - ) + msg = "Circuit ({}/{}): {} != {}".format(pos + 1, len(circuits), output.data, target.data) raise Exception(msg) @@ -426,9 +398,7 @@ def model_and_pi_schedule(): # Run Aer simulator shots = 4000 circuits = grovers_circuit(final_measure=True, allow_sampling=True) - targets = [ - {"0x0": 5 * shots / 8, "0x1": shots / 8, "0x2": shots / 8, "0x3": shots / 8} - ] + targets = [{"0x0": 5 * shots / 8, "0x1": shots / 8, "0x2": shots / 8, "0x3": shots / 8}] simulator = AerSimulator() result = simulator.run(transpile(circuits, simulator), shots=shots).result() assert result.status == "COMPLETED"