From d29577ea305da611d9ed7058fc5271714527196e Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Tue, 8 Aug 2023 13:00:31 -0400 Subject: [PATCH 01/15] Keep resets at beginning of circuits --- qiskit/transpiler/preset_passmanagers/level1.py | 4 ++-- qiskit/transpiler/preset_passmanagers/level2.py | 4 ++-- qiskit/transpiler/preset_passmanagers/level3.py | 4 ++-- test/python/compiler/test_transpiler.py | 7 ++++--- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/qiskit/transpiler/preset_passmanagers/level1.py b/qiskit/transpiler/preset_passmanagers/level1.py index c56cd820262c..1f6972d0ac3d 100644 --- a/qiskit/transpiler/preset_passmanagers/level1.py +++ b/qiskit/transpiler/preset_passmanagers/level1.py @@ -232,10 +232,10 @@ def _swap_mapped(property_set): target is not None and target.get_non_global_operation_names(strict_direction=True) ): pre_optimization = common.generate_pre_op_passmanager( - target, coupling_map, remove_reset_in_zero=True + target, coupling_map, remove_reset_in_zero=False ) else: - pre_optimization = common.generate_pre_op_passmanager(remove_reset_in_zero=True) + pre_optimization = common.generate_pre_op_passmanager(remove_reset_in_zero=False) if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] diff --git a/qiskit/transpiler/preset_passmanagers/level2.py b/qiskit/transpiler/preset_passmanagers/level2.py index 62880e3eeec9..de17840c499e 100644 --- a/qiskit/transpiler/preset_passmanagers/level2.py +++ b/qiskit/transpiler/preset_passmanagers/level2.py @@ -220,9 +220,9 @@ def _swap_mapped(property_set): if (coupling_map and not coupling_map.is_symmetric) or ( target is not None and target.get_non_global_operation_names(strict_direction=True) ): - pre_optimization = common.generate_pre_op_passmanager(target, coupling_map, True) + pre_optimization = common.generate_pre_op_passmanager(target, coupling_map, False) else: - pre_optimization = common.generate_pre_op_passmanager(remove_reset_in_zero=True) + pre_optimization = common.generate_pre_op_passmanager(remove_reset_in_zero=False) if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] diff --git a/qiskit/transpiler/preset_passmanagers/level3.py b/qiskit/transpiler/preset_passmanagers/level3.py index 81ca9af75eee..9635d978fe0f 100644 --- a/qiskit/transpiler/preset_passmanagers/level3.py +++ b/qiskit/transpiler/preset_passmanagers/level3.py @@ -272,7 +272,7 @@ def _unroll_condition(property_set): if (coupling_map and not coupling_map.is_symmetric) or ( target is not None and target.get_non_global_operation_names(strict_direction=True) ): - pre_optimization = common.generate_pre_op_passmanager(target, coupling_map, True) + pre_optimization = common.generate_pre_op_passmanager(target, coupling_map, False) _direction = [ pass_ for x in common.generate_pre_op_passmanager(target, coupling_map).passes() @@ -284,7 +284,7 @@ def _unroll_condition(property_set): do_while=_opt_control, ) else: - pre_optimization = common.generate_pre_op_passmanager(remove_reset_in_zero=True) + pre_optimization = common.generate_pre_op_passmanager(remove_reset_in_zero=False) optimization.append( _opt + _unroll_if_out_of_basis + _minimum_point_check, do_while=_opt_control ) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 307e90d914c4..d041711a3639 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -802,14 +802,15 @@ def test_move_measurements(self): ) self.assertTrue(is_last_measure) - def test_initialize_reset_should_be_removed(self): - """The reset in front of initializer should be removed when zero state""" + def test_initialize_reset_is_not_removed(self): + """The reset in front of initializer should NOT be removed at beginning""" qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]]) qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]]) expected = QuantumCircuit(qr) + expected.reset(qr[0]) expected.append(U3Gate(np.pi / 2, 0, 0), [qr[0]]) expected.reset(qr[0]) expected.append(U3Gate(np.pi / 2, -np.pi, 0), [qr[0]]) @@ -828,7 +829,7 @@ def test_initialize_FakeMelbourne(self): out_dag = circuit_to_dag(out) reset_nodes = out_dag.named_nodes("reset") - self.assertEqual(reset_nodes, []) + self.assertEqual(len(reset_nodes), 3) def test_non_standard_basis(self): """Test a transpilation with a non-standard basis""" From ea7c1e683bf3b703208e349b32f33af8f9960806 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Tue, 8 Aug 2023 13:10:26 -0400 Subject: [PATCH 02/15] Add reno and black --- qiskit/algorithms/algorithm_result.py | 1 - .../eigen_solvers/numpy_eigen_solver.py | 2 -- qiskit/algorithms/eigen_solvers/vqd.py | 10 +++---- .../eigensolvers/numpy_eigensolver.py | 2 -- qiskit/algorithms/gradients/reverse/bind.py | 1 + .../algorithms/minimum_eigen_solvers/vqe.py | 7 +++-- .../minimum_eigensolvers/sampling_vqe.py | 7 +++-- qiskit/algorithms/optimizers/adam_amsgrad.py | 1 - qiskit/algorithms/optimizers/aqgd.py | 2 +- .../algorithms/optimizers/gradient_descent.py | 1 - qiskit/algorithms/optimizers/gsls.py | 1 - qiskit/algorithms/optimizers/nft.py | 1 - qiskit/algorithms/optimizers/umda.py | 1 - .../hamiltonian_phase_estimation.py | 1 - qiskit/algorithms/phase_estimators/ipe.py | 1 - .../state_fidelities/base_state_fidelity.py | 7 ++--- .../time_evolvers/classical_methods/evolve.py | 1 - .../solvers/ode/abstract_ode_function.py | 1 - .../real_mc_lachlan_principle.py | 1 - .../variational_principle.py | 1 - qiskit/assembler/assemble_schedules.py | 1 - qiskit/circuit/controlflow/while_loop.py | 1 - .../library/arithmetic/integer_comparator.py | 2 -- qiskit/circuit/library/n_local/n_local.py | 14 +++++++-- qiskit/compiler/assembler.py | 1 - qiskit/dagcircuit/dagcircuit.py | 1 - qiskit/dagcircuit/dagdepnode.py | 1 - .../quantum_initializer/isometry.py | 4 +-- .../quantum_initializer/uc_pauli_rot.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 2 -- .../expectations/expectation_factory.py | 1 - .../gradients/circuit_gradients/lin_comb.py | 1 - .../gradients/circuit_qfis/lin_comb_full.py | 2 -- .../gradients/circuit_qfis/overlap_diag.py | 2 -- qiskit/opflow/gradients/gradient.py | 1 - qiskit/opflow/gradients/hessian.py | 1 - qiskit/opflow/gradients/qfi_base.py | 1 - qiskit/opflow/list_ops/composed_op.py | 1 - qiskit/opflow/list_ops/list_op.py | 1 - qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/primitive_ops/circuit_op.py | 1 - qiskit/opflow/primitive_ops/matrix_op.py | 1 - qiskit/opflow/primitive_ops/pauli_op.py | 4 --- qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 -- .../primitive_ops/tapered_pauli_sum_op.py | 1 - qiskit/opflow/state_fns/circuit_state_fn.py | 2 +- qiskit/primitives/backend_estimator.py | 2 -- qiskit/primitives/backend_sampler.py | 1 - .../utils/configurable_backend.py | 6 ++-- qiskit/pulse/library/symbolic_pulses.py | 1 - qiskit/pulse/macros.py | 1 - qiskit/pulse/schedule.py | 1 - qiskit/quantum_info/synthesis/qsd.py | 2 +- .../synthesis/xx_decompose/circuits.py | 1 - .../clifford/clifford_decompose_bm.py | 1 - .../clifford/clifford_decompose_greedy.py | 1 - qiskit/tools/jupyter/backend_monitor.py | 1 - qiskit/tools/jupyter/watcher_monitor.py | 1 - qiskit/transpiler/instruction_durations.py | 1 - .../passes/basis/basis_translator.py | 3 -- .../optimization/commutation_analysis.py | 4 +-- .../echo_rzx_weyl_decomposition.py | 1 - .../template_matching/backward_match.py | 9 ------ .../template_matching/forward_match.py | 5 ---- .../template_matching/template_matching.py | 1 - .../template_substitution.py | 3 -- .../passes/routing/algorithms/bip_model.py | 30 +++++++++---------- .../transpiler/passes/routing/bip_mapping.py | 2 +- .../commuting_2q_gate_router.py | 1 - .../pauli_2q_evolution_commutation.py | 1 - .../swap_strategy.py | 1 - .../scheduling/alignments/reschedule.py | 1 - .../synthesis/solovay_kitaev_synthesis.py | 1 - .../passes/synthesis/unitary_synthesis.py | 1 - .../barrier_before_final_measurements.py | 1 - .../passes/utils/merge_adjacent_barriers.py | 3 -- .../transpiler/preset_passmanagers/level1.py | 1 + .../transpiler/preset_passmanagers/level2.py | 1 + .../transpiler/preset_passmanagers/level3.py | 1 + qiskit/transpiler/synthesis/aqc/aqc_plugin.py | 1 - qiskit/utils/mitigation/_filters.py | 5 ---- qiskit/utils/mitigation/circuits.py | 2 -- qiskit/utils/mitigation/fitters.py | 2 -- qiskit/utils/run_circuits.py | 1 - qiskit/visualization/bloch.py | 2 -- qiskit/visualization/circuit/matplotlib.py | 1 - qiskit/visualization/circuit/text.py | 1 - qiskit/visualization/gate_map.py | 1 - .../pass_manager_visualization.py | 1 - qiskit/visualization/pulse_v2/core.py | 1 - .../keep-initial-resets-a5f75cb16c8edb57.yaml | 6 ++++ .../minimum_eigensolvers/test_vqe.py | 1 + .../algorithms/test_aux_ops_evaluator.py | 1 - .../test_measure_error_mitigation.py | 1 - .../python/algorithms/test_phase_estimator.py | 1 - test/python/algorithms/test_qaoa.py | 1 - .../circuit/library/test_linear_function.py | 1 - test/python/circuit/test_gate_definitions.py | 1 + test/python/circuit/test_random_circuit.py | 2 +- test/python/opflow/test_gradients.py | 2 -- test/python/opflow/test_matrix_expectation.py | 1 - .../python/opflow/test_state_op_meas_evals.py | 1 - .../primitives/test_backend_estimator.py | 2 -- .../python/primitives/test_backend_sampler.py | 2 -- .../quantum_info/states/test_densitymatrix.py | 12 -------- .../quantum_info/states/test_statevector.py | 12 -------- .../aqc/fast_gradient/test_layer1q.py | 2 -- .../aqc/fast_gradient/test_layer2q.py | 2 -- .../aqc/fast_gradient/test_utils.py | 1 - .../test_echo_rzx_weyl_decomposition.py | 1 - test/python/utils/mitigation/test_meas.py | 1 - 111 files changed, 64 insertions(+), 202 deletions(-) create mode 100644 releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml diff --git a/qiskit/algorithms/algorithm_result.py b/qiskit/algorithms/algorithm_result.py index 0804303a4ef6..a19b4dbff956 100644 --- a/qiskit/algorithms/algorithm_result.py +++ b/qiskit/algorithms/algorithm_result.py @@ -31,7 +31,6 @@ def __str__(self) -> str: and not inspect.isfunction(value) and hasattr(self, name) ): - result[name] = value return pprint.pformat(result, indent=4) diff --git a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py index 6b0536330441..94196da139a9 100644 --- a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py @@ -176,7 +176,6 @@ def _get_energies( def _eval_aux_operators( aux_operators: ListOrDict[OperatorBase], wavefn, threshold: float = 1e-12 ) -> ListOrDict[tuple[complex, complex]]: - values: ListOrDict[tuple[complex, complex]] # As a list, aux_operators can contain None operators for which None values are returned. @@ -241,7 +240,6 @@ def compute_eigenvalues( # if a filter is set, loop over the given values and only keep if self._filter_criterion: - eigvecs = [] eigvals = [] aux_ops = [] diff --git a/qiskit/algorithms/eigen_solvers/vqd.py b/qiskit/algorithms/eigen_solvers/vqd.py index 72e3dd306647..1478c23f6ec9 100644 --- a/qiskit/algorithms/eigen_solvers/vqd.py +++ b/qiskit/algorithms/eigen_solvers/vqd.py @@ -572,7 +572,6 @@ def compute_eigenvalues( aux_values = [] for step in range(1, self.k + 1): - self._eval_count = 0 energy_evaluation, expectation = self.get_energy_evaluation( step, operator, return_expectation=True, prev_states=result.optimal_parameters @@ -627,7 +626,6 @@ def compute_eigenvalues( aux_values.append(aux_value) if step == 1: - logger.info( "Ground state optimization complete in %s seconds.\n" "Found opt_params %s in %s evals", @@ -666,9 +664,10 @@ def get_energy_evaluation( operator: OperatorBase, return_expectation: bool = False, prev_states: list[np.ndarray] | None = None, - ) -> Callable[[np.ndarray], float | list[float]] | tuple[ - Callable[[np.ndarray], float | list[float]], ExpectationBase - ]: + ) -> ( + Callable[[np.ndarray], float | list[float]] + | tuple[Callable[[np.ndarray], float | list[float]], ExpectationBase] + ): """Returns a function handle to evaluates the energy at given parameters for the ansatz. This return value is the objective function to be passed to the optimizer for evaluation. @@ -714,7 +713,6 @@ def get_energy_evaluation( ) for state in range(step - 1): - prev_circ = self.ansatz.bind_parameters(prev_states[state]) overlap_op.append(~CircuitStateFn(prev_circ) @ CircuitStateFn(self.ansatz)) diff --git a/qiskit/algorithms/eigensolvers/numpy_eigensolver.py b/qiskit/algorithms/eigensolvers/numpy_eigensolver.py index 954292ecc5d0..457fe3fdbdad 100644 --- a/qiskit/algorithms/eigensolvers/numpy_eigensolver.py +++ b/qiskit/algorithms/eigensolvers/numpy_eigensolver.py @@ -172,7 +172,6 @@ def _eval_aux_operators( wavefn: np.ndarray, threshold: float = 1e-12, ) -> ListOrDict[tuple[complex, complex]]: - values: ListOrDict[tuple[complex, complex]] # As a list, aux_operators can contain None operators for which None values are returned. @@ -232,7 +231,6 @@ def compute_eigenvalues( operator: BaseOperator | PauliSumOp, aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, ) -> NumPyEigensolverResult: - super().compute_eigenvalues(operator, aux_operators) if operator.num_qubits is None or operator.num_qubits < 1: diff --git a/qiskit/algorithms/gradients/reverse/bind.py b/qiskit/algorithms/gradients/reverse/bind.py index 5380090b7425..bc745eb99573 100644 --- a/qiskit/algorithms/gradients/reverse/bind.py +++ b/qiskit/algorithms/gradients/reverse/bind.py @@ -17,6 +17,7 @@ from qiskit.circuit import QuantumCircuit, Parameter + # pylint: disable=inconsistent-return-statements def bind( circuits: QuantumCircuit | Iterable[QuantumCircuit], diff --git a/qiskit/algorithms/minimum_eigen_solvers/vqe.py b/qiskit/algorithms/minimum_eigen_solvers/vqe.py index bf9304e4d6b7..f34359699a64 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/vqe.py +++ b/qiskit/algorithms/minimum_eigen_solvers/vqe.py @@ -582,9 +582,10 @@ def get_energy_evaluation( self, operator: OperatorBase, return_expectation: bool = False, - ) -> Callable[[np.ndarray], float | list[float]] | tuple[ - Callable[[np.ndarray], float | list[float]], ExpectationBase - ]: + ) -> ( + Callable[[np.ndarray], float | list[float]] + | tuple[Callable[[np.ndarray], float | list[float]], ExpectationBase] + ): """Returns a function handle to evaluates the energy at given parameters for the ansatz. This is the objective function to be passed to the optimizer that is used for evaluation. diff --git a/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py b/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py index 2fb60355b2a5..9a8ee66c381f 100644 --- a/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py +++ b/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py @@ -258,9 +258,10 @@ def _get_evaluate_energy( operator: BaseOperator | PauliSumOp, ansatz: QuantumCircuit, return_best_measurement: bool = False, - ) -> Callable[[np.ndarray], np.ndarray | float] | tuple[ - Callable[[np.ndarray], np.ndarray | float], dict[str, Any] - ]: + ) -> ( + Callable[[np.ndarray], np.ndarray | float] + | tuple[Callable[[np.ndarray], np.ndarray | float], dict[str, Any]] + ): """Returns a function handle to evaluate the energy at given parameters. This is the objective function to be passed to the optimizer that is used for evaluation. diff --git a/qiskit/algorithms/optimizers/adam_amsgrad.py b/qiskit/algorithms/optimizers/adam_amsgrad.py index 422aa17a5f01..326887ae0c9c 100644 --- a/qiskit/algorithms/optimizers/adam_amsgrad.py +++ b/qiskit/algorithms/optimizers/adam_amsgrad.py @@ -113,7 +113,6 @@ def __init__( self._v_eff = np.zeros(1) if self._snapshot_dir: - with open(os.path.join(self._snapshot_dir, "adam_params.csv"), mode="w") as csv_file: if self._amsgrad: fieldnames = ["v", "v_eff", "m", "t"] diff --git a/qiskit/algorithms/optimizers/aqgd.py b/qiskit/algorithms/optimizers/aqgd.py index bedc52301f34..9464f040b55d 100644 --- a/qiskit/algorithms/optimizers/aqgd.py +++ b/qiskit/algorithms/optimizers/aqgd.py @@ -314,7 +314,7 @@ def minimize( epoch = 0 converged = False - for (eta, mom_coeff) in zip(self._eta, self._momenta_coeff): + for eta, mom_coeff in zip(self._eta, self._momenta_coeff): logger.info("Epoch: %4d | Stepsize: %6.4f | Momentum: %6.4f", epoch, eta, mom_coeff) sum_max_iters = sum(self._maxiter[0 : epoch + 1]) diff --git a/qiskit/algorithms/optimizers/gradient_descent.py b/qiskit/algorithms/optimizers/gradient_descent.py index 03911c21c012..a2d3e228cadd 100644 --- a/qiskit/algorithms/optimizers/gradient_descent.py +++ b/qiskit/algorithms/optimizers/gradient_descent.py @@ -365,7 +365,6 @@ def start( jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> None: - self.state = GradientDescentState( fun=fun, jac=jac, diff --git a/qiskit/algorithms/optimizers/gsls.py b/qiskit/algorithms/optimizers/gsls.py index 6c1446f879cb..31714a5396c4 100644 --- a/qiskit/algorithms/optimizers/gsls.py +++ b/qiskit/algorithms/optimizers/gsls.py @@ -179,7 +179,6 @@ def ls_optimize( x_value = obj_fun(x) n_evals += 1 while iter_count < self._options["maxiter"] and n_evals < self._options["max_eval"]: - # Determine set of sample points directions, sample_set_x = self.sample_set(n, x, var_lb, var_ub, sample_set_size) diff --git a/qiskit/algorithms/optimizers/nft.py b/qiskit/algorithms/optimizers/nft.py index 2a7503137daf..872dc0e86bd3 100644 --- a/qiskit/algorithms/optimizers/nft.py +++ b/qiskit/algorithms/optimizers/nft.py @@ -120,7 +120,6 @@ def nakanishi_fujii_todo( funcalls = 0 while True: - idx = niter % x0.size if reset_interval > 0: diff --git a/qiskit/algorithms/optimizers/umda.py b/qiskit/algorithms/optimizers/umda.py index dd8739c2fac1..f0b6e628ee9d 100644 --- a/qiskit/algorithms/optimizers/umda.py +++ b/qiskit/algorithms/optimizers/umda.py @@ -213,7 +213,6 @@ def minimize( jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> OptimizerResult: - not_better_count = 0 result = OptimizerResult() diff --git a/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py b/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py index 87907c39e304..5bf1a4fe6715 100644 --- a/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py +++ b/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py @@ -140,7 +140,6 @@ def _get_unitary( """ if self._phase_estimation._sampler is not None: - evo = PauliEvolutionGate(hamiltonian, -pe_scale.scale, synthesis=evolution) unitary = QuantumCircuit(evo.num_qubits) unitary.append(evo, unitary.qubits) diff --git a/qiskit/algorithms/phase_estimators/ipe.py b/qiskit/algorithms/phase_estimators/ipe.py index e8e583027a92..69d09f42910a 100644 --- a/qiskit/algorithms/phase_estimators/ipe.py +++ b/qiskit/algorithms/phase_estimators/ipe.py @@ -140,7 +140,6 @@ def _estimate_phase_iteratively(self, unitary, state_preparation): omega_coef /= 2 if self._sampler is not None: - qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True ) diff --git a/qiskit/algorithms/state_fidelities/base_state_fidelity.py b/qiskit/algorithms/state_fidelities/base_state_fidelity.py index 9395889bc5da..5a821a956de3 100644 --- a/qiskit/algorithms/state_fidelities/base_state_fidelity.py +++ b/qiskit/algorithms/state_fidelities/base_state_fidelity.py @@ -42,7 +42,6 @@ class BaseStateFidelity(ABC): """ def __init__(self) -> None: - # use cache for preventing unnecessary circuit compositions self._circuit_cache: Mapping[tuple[int, int], QuantumCircuit] = {} @@ -81,7 +80,6 @@ def _preprocess_values( ) return [[]] else: - # Support ndarray if isinstance(values, np.ndarray): values = values.tolist() @@ -168,8 +166,7 @@ def _construct_circuits( ) circuits = [] - for (circuit_1, circuit_2) in zip(circuits_1, circuits_2): - + for circuit_1, circuit_2 in zip(circuits_1, circuits_2): # TODO: improve caching, what if the circuit is modified without changing the id? circuit = self._circuit_cache.get((id(circuit_1), id(circuit_2))) @@ -226,7 +223,7 @@ def _construct_value_list( elif len(values_1[0]) == 0: values = list(values_2) else: - for (val_1, val_2) in zip(values_1, values_2): + for val_1, val_2 in zip(values_1, values_2): values.append(val_1 + val_2) return values diff --git a/qiskit/algorithms/time_evolvers/classical_methods/evolve.py b/qiskit/algorithms/time_evolvers/classical_methods/evolve.py index 18c679a03c8f..5280c24ef7da 100644 --- a/qiskit/algorithms/time_evolvers/classical_methods/evolve.py +++ b/qiskit/algorithms/time_evolvers/classical_methods/evolve.py @@ -97,7 +97,6 @@ def _evaluate_aux_ops( def _operator_to_matrix(operator: BaseOperator | PauliSumOp): - if isinstance(operator, PauliSumOp): op_matrix = operator.to_spmatrix() else: diff --git a/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py b/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py index b94ded552a81..58eb1221ac79 100644 --- a/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py +++ b/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py @@ -30,7 +30,6 @@ def __init__( param_dict: Mapping[Parameter, float], t_param: Parameter | None = None, ) -> None: - self._varqte_linear_solver = varqte_linear_solver self._param_dict = param_dict self._t_param = t_param diff --git a/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py b/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py index d7a946b8ab70..89bb4a5ef604 100644 --- a/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py +++ b/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py @@ -150,7 +150,6 @@ def _construct_modified_hamiltonian(hamiltonian: BaseOperator, energy: float) -> @staticmethod def _validate_grad_settings(gradient): - if gradient is not None: if not hasattr(gradient, "_derivative_type"): raise ValueError( diff --git a/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py b/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py index be16849155c4..33128b7221ca 100644 --- a/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py +++ b/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py @@ -70,7 +70,6 @@ def metric_tensor( try: metric_tensor = self.qgt.run([ansatz], [param_values], [None]).result().qgts[0] except Exception as exc: - raise AlgorithmError("The QFI primitive job failed!") from exc return metric_tensor diff --git a/qiskit/assembler/assemble_schedules.py b/qiskit/assembler/assemble_schedules.py index 6ddf4c140d56..af6b2537a2ea 100644 --- a/qiskit/assembler/assemble_schedules.py +++ b/qiskit/assembler/assemble_schedules.py @@ -222,7 +222,6 @@ def _assemble_instructions( acquire_instruction_map = defaultdict(list) for time, instruction in sched.instructions: - if isinstance(instruction, instructions.Play): if isinstance(instruction.pulse, (library.ParametricPulse, library.SymbolicPulse)): is_backend_supported = True diff --git a/qiskit/circuit/controlflow/while_loop.py b/qiskit/circuit/controlflow/while_loop.py index 98fefa3ce8c2..d2c9c5739136 100644 --- a/qiskit/circuit/controlflow/while_loop.py +++ b/qiskit/circuit/controlflow/while_loop.py @@ -142,7 +142,6 @@ def __init__( *, label: str | None = None, ): - self._circuit = circuit self._condition = validate_condition(condition) self._label = label diff --git a/qiskit/circuit/library/arithmetic/integer_comparator.py b/qiskit/circuit/library/arithmetic/integer_comparator.py index 699e8c221ff3..c1ced2693ab5 100644 --- a/qiskit/circuit/library/arithmetic/integer_comparator.py +++ b/qiskit/circuit/library/arithmetic/integer_comparator.py @@ -198,7 +198,6 @@ def _build(self) -> None: circuit.x(q_compare) # condition never satisfied for values larger than or equal to 2^n elif self.value < pow(2, self.num_state_qubits): - if self.num_state_qubits > 1: twos = self._get_twos_complement() for i in range(self.num_state_qubits): @@ -239,7 +238,6 @@ def _build(self) -> None: else: circuit.ccx(qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]) else: - # num_state_qubits == 1 and value == 1: circuit.cx(qr_state[0], q_compare) diff --git a/qiskit/circuit/library/n_local/n_local.py b/qiskit/circuit/library/n_local/n_local.py index aca3ea65bb3b..f6134bba7766 100644 --- a/qiskit/circuit/library/n_local/n_local.py +++ b/qiskit/circuit/library/n_local/n_local.py @@ -285,9 +285,17 @@ def entanglement_blocks( @property def entanglement( self, - ) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[ - list[list[int]] - ] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]: + ) -> ( + str + | list[str] + | list[list[str]] + | list[int] + | list[list[int]] + | list[list[list[int]]] + | list[list[list[list[int]]]] + | Callable[[int], str] + | Callable[[int], list[list[int]]] + ): """Get the entanglement strategy. Returns: diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 5a9e15c33f0e..941d5f439db5 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -556,7 +556,6 @@ def _expand_parameters(circuits, run_config): parameter_binds = run_config.parameter_binds if parameter_binds and any(parameter_binds) or any(circuit.parameters for circuit in circuits): - # Unroll params here in order to handle ParamVects all_bind_parameters = [ QuantumCircuit()._unroll_param_dict(bind).keys() for bind in parameter_binds diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py index 012b43db66ee..b643c27bbda8 100644 --- a/qiskit/dagcircuit/dagcircuit.py +++ b/qiskit/dagcircuit/dagcircuit.py @@ -1777,7 +1777,6 @@ def layers(self): return for graph_layer in graph_layers: - # Get the op nodes from the layer, removing any input and output nodes. op_nodes = [node for node in graph_layer if isinstance(node, DAGOpNode)] diff --git a/qiskit/dagcircuit/dagdepnode.py b/qiskit/dagcircuit/dagdepnode.py index 0ac7be65f103..8fdc82735129 100644 --- a/qiskit/dagcircuit/dagdepnode.py +++ b/qiskit/dagcircuit/dagdepnode.py @@ -59,7 +59,6 @@ def __init__( cindices=None, nid=-1, ): - self.type = type self._op = op self.name = name diff --git a/qiskit/extensions/quantum_initializer/isometry.py b/qiskit/extensions/quantum_initializer/isometry.py index 611413e9f56f..2270a5e487f6 100644 --- a/qiskit/extensions/quantum_initializer/isometry.py +++ b/qiskit/extensions/quantum_initializer/isometry.py @@ -103,7 +103,6 @@ def __init__(self, isometry, num_ancillas_zero, num_ancillas_dirty, epsilon=_EPS super().__init__("isometry", num_qubits, 0, [isometry]) def _define(self): - # TODO The inverse().inverse() is because there is code to uncompute (_gates_to_uncompute) # an isometry, but not for generating its decomposition. It would be cheaper to do the # later here instead. @@ -292,7 +291,6 @@ def _append_mcg_up_to_diagonal(self, circ, q, gate, control_labels, target_label return mcg_up_to_diag._get_diagonal() def _define_qubit_role(self, q): - n = int(np.log2(self.iso_data.shape[0])) m = int(np.log2(self.iso_data.shape[1])) @@ -502,7 +500,7 @@ def _get_binary_rep_as_list(n, num_digits): def _merge_UCGate_and_diag(single_qubit_gates, diag): - for (i, gate) in enumerate(single_qubit_gates): + for i, gate in enumerate(single_qubit_gates): single_qubit_gates[i] = np.array([[diag[2 * i], 0.0], [0.0, diag[2 * i + 1]]]).dot(gate) return single_qubit_gates diff --git a/qiskit/extensions/quantum_initializer/uc_pauli_rot.py b/qiskit/extensions/quantum_initializer/uc_pauli_rot.py index 87a1b1fd3642..ecb60351ed64 100644 --- a/qiskit/extensions/quantum_initializer/uc_pauli_rot.py +++ b/qiskit/extensions/quantum_initializer/uc_pauli_rot.py @@ -102,7 +102,7 @@ def _dec_ucrot(self): angles = self.params.copy() UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False) # Now, it is easy to place the C-NOT gates to get back the full decomposition. - for (i, angle) in enumerate(angles): + for i, angle in enumerate(angles): if self.rot_axes == "X": if np.abs(angle) > _EPS: circuit.rx(angle, q_target) diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index e8e5938617e7..9abf101bb8bb 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -420,13 +420,11 @@ def resolve_param(inst_param): def _prepare_parameterized_run_config( self, param_bindings: List[Dict[Parameter, float]] ) -> List[Any]: - self.quantum_instance._run_config.parameterizations = [] if self._transpiled_circ_templates is None or len(self._transpiled_circ_templates) != len( self._transpiled_circ_cache ): - # temporally resolve parameters of self._transpiled_circ_cache # They will be overridden in Aer from the next iterations self._transpiled_circ_templates = [ diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 58a72ed6daca..92e73a70de7b 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -71,7 +71,6 @@ def build( # pylint: disable=cyclic-import primitives = operator.primitive_strings() if primitives in ({"Pauli"}, {"SparsePauliOp"}): - if backend_to_check is None: # If user has Aer but didn't specify a backend, use the Aer fast expectation if optionals.HAS_AER: diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 361d13112e85..421b3a84b800 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -212,7 +212,6 @@ def _prepare_operator( isinstance(params, list) and all(isinstance(param, ParameterExpression) for param in params) ): - return self._gradient_states( state_op, meas_op=(2 * meas), diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 71f4eea3d8c2..34a52d18981c 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -149,7 +149,6 @@ def convert( break for grad_coeff_i, grad_gate_i in zip(grad_coeffs_i, grad_gates_i): - # Get the gates of the quantum state which are parameterized by param_j param_gates_j = state_qc._parameter_table[param_j] for gate_j, idx_j in param_gates_j: @@ -163,7 +162,6 @@ def convert( break for grad_coeff_j, grad_gate_j in zip(grad_coeffs_j, grad_gates_j): - grad_coeff_ij = np.conj(grad_coeff_i) * grad_coeff_j qfi_circuit = LinComb.apply_grad_gate( state_qc, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 3f630fe304b9..abb1e5bd05cf 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -208,7 +208,6 @@ def apply_node_op(node, dag, back=True): # without becoming the descendant of a parameterized gate, # then do it. if not any(ledger[x] for x in indices): - apply_node_op(next_node, layer) next_layer.remove_op_node(next_node) @@ -250,7 +249,6 @@ def _get_generators(params, circuit): for param in params: if param in param_value.parameters: - if isinstance(instr, RYGate): generator = Y elif isinstance(instr, RZGate): diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index f9762da93e41..87e750a882e9 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -171,7 +171,6 @@ def is_coeff_c_abs(coeff, c): # circuits were applied. Additionally, all coefficients within ComposedOps were collected # and moved out front. if isinstance(operator, ComposedOp): - # Gradient of an expectation value if not is_coeff_c_abs(operator._coeff, 1.0): raise OpflowError( diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 3ec39f5674ca..04c4e4977141 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -191,7 +191,6 @@ def is_coeff_c(coeff, c): # circuits were applied. Additionally, all coefficients within ComposedOps were collected # and moved out front. if isinstance(operator, ComposedOp): - if not is_coeff_c(operator.coeff, 1.0): raise OpflowError( "Operator pre-processing failed. Coefficients were not properly " diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index b09f9170dbad..f8147280b0a5 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -20,7 +20,6 @@ class QFIBase(DerivativeBase): - r"""Deprecated: Base class for Quantum Fisher Information (QFI). Compute the Quantum Fisher Information (QFI) given a pure, parameterized quantum state. diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index d47a81fbd796..1ef9f2db1d1f 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -111,7 +111,6 @@ def adjoint(self) -> "ComposedOp": def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: - new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(ComposedOp, new_self) diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index abf2d2326d0c..9d655da80237 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -335,7 +335,6 @@ def permute(self, permutation: List[int]) -> "OperatorBase": def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: - new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(ListOp, new_self) diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index 7c1e031d8620..949ffad4f6c7 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -396,7 +396,7 @@ def _unroll_param_dict( """Unrolls the ParameterVectors in a param_dict into separate Parameters, and unrolls parameterization value lists into separate param_dicts without list nesting.""" unrolled_value_dict = {} - for (param, value) in value_dict.items(): + for param, value in value_dict.items(): if isinstance(param, ParameterExpression): unrolled_value_dict[param] = value if isinstance(param, ParameterVector) and isinstance(value, (list, np.ndarray)): diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 1a6104a4cac3..b026f405fbd8 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -121,7 +121,6 @@ def tensor(self, other: OperatorBase) -> Union["CircuitOp", TensoredOp]: def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: - new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(CircuitOp, new_self) diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index be8c8ac90eec..66f62348e1bc 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -131,7 +131,6 @@ def tensor(self, other: OperatorBase) -> Union["MatrixOp", TensoredOp]: def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: - new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(MatrixOp, new_self) diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 623608754671..bea3c2c9c960 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -153,7 +153,6 @@ def permute(self, permutation: List[int]) -> "PauliOp": def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: - new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(PauliOp, new_self) @@ -233,7 +232,6 @@ def eval( ) else: - if self.num_qubits != front.num_qubits: raise ValueError( "eval does not support operands with differing numbers of qubits, " @@ -241,7 +239,6 @@ def eval( ) if isinstance(front, DictStateFn): - new_dict: Dict[str, complex] = {} corrected_x_bits = self.primitive.x[::-1] corrected_z_bits = self.primitive.z[::-1] @@ -320,7 +317,6 @@ def exp_i(self) -> OperatorBase: return EvolvedOp(self) def to_circuit(self) -> QuantumCircuit: - pauli = self.primitive.to_label()[-self.num_qubits :] phase = self.primitive.phase diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index b1bb9b7242a9..a41b17eb0ad8 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -231,7 +231,6 @@ def compose( permutation: Optional[List[int]] = None, front: bool = False, ) -> OperatorBase: - new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(PauliSumOp, new_self) @@ -318,7 +317,6 @@ def eval( ) else: - if self.num_qubits != front.num_qubits: raise ValueError( "eval does not support operands with differing numbers of qubits, " diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index 9411afc71f26..b509a210cc28 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -273,7 +273,6 @@ def find_Z2_symmetries(cls, operator: PauliSumOp) -> "Z2Symmetries": symm_shape = stacked_symmetries.shape for row in range(symm_shape[0]): - pauli_symmetries.append( Pauli( ( diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index 3f23f89a1cee..7ae96434bd22 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -102,7 +102,7 @@ def from_dict(density_dict: dict) -> "CircuitStateFn": for bstr, prob in density_dict.items(): qc = QuantumCircuit(len(bstr)) # NOTE: Reversing endianness!! - for (index, bit) in enumerate(reversed(bstr)): + for index, bit in enumerate(reversed(bstr)): if bit == "1": qc.x(index) sf_circuit = CircuitStateFn(qc, coeff=prob) diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index 40c77f9e9a6b..7dbc4e92862d 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -231,7 +231,6 @@ def _call( parameter_values: Sequence[Sequence[float]], **run_options, ) -> EstimatorResult: - # Transpile self._grouping = list(zip(circuits, observables)) transpiled_circuits = self.transpiled_circuits @@ -361,7 +360,6 @@ def _postprocessing( shots_list = [] for i, j in zip(accum, accum[1:]): - combined_expval = 0.0 combined_var = 0.0 diff --git a/qiskit/primitives/backend_sampler.py b/qiskit/primitives/backend_sampler.py index 6d7f16173980..41df0edd7e2c 100644 --- a/qiskit/primitives/backend_sampler.py +++ b/qiskit/primitives/backend_sampler.py @@ -134,7 +134,6 @@ def _call( parameter_values: Sequence[Sequence[float]], **run_options, ) -> SamplerResult: - # This line does the actual transpilation transpiled_circuits = self.transpiled_circuits bound_circuits = [ diff --git a/qiskit/providers/fake_provider/utils/configurable_backend.py b/qiskit/providers/fake_provider/utils/configurable_backend.py index a3dd72eed97a..03c00bf3384b 100644 --- a/qiskit/providers/fake_provider/utils/configurable_backend.py +++ b/qiskit/providers/fake_provider/utils/configurable_backend.py @@ -155,7 +155,7 @@ def _build_props(self) -> BackendProperties: qubits = [] gates = [] - for (qubit_t1, qubit_t2, freq, read_err) in zip( + for qubit_t1, qubit_t2, freq, read_err in zip( self.qubit_t1, self.qubit_t2, self.qubit_frequency, self.qubit_readout_error ): qubits.append( @@ -184,7 +184,7 @@ def _build_props(self) -> BackendProperties: ) ) elif gate == "cx": - for (qubit1, qubit2) in list(itertools.combinations(range(self.n_qubits), 2)): + for qubit1, qubit2 in list(itertools.combinations(range(self.n_qubits), 2)): gates.append( Gate( gate=gate, @@ -212,7 +212,7 @@ def _build_conf(self) -> PulseBackendConfiguration: ",".join([f"_SUM[i,0,{self.n_qubits}", "omegad{i}*X{i}||D{i}]"]), ] variables = [] - for (qubit1, qubit2) in self.coupling_map: + for qubit1, qubit2 in self.coupling_map: h_str += [ "jq{q1}q{q2}*Sp{q1}*Sm{q2}".format(q1=qubit1, q2=qubit2), "jq{q1}q{q2}*Sm{q1}*Sp{q2}".format(q1=qubit1, q2=qubit2), diff --git a/qiskit/pulse/library/symbolic_pulses.py b/qiskit/pulse/library/symbolic_pulses.py index 8c90777eae01..256729db1bc4 100644 --- a/qiskit/pulse/library/symbolic_pulses.py +++ b/qiskit/pulse/library/symbolic_pulses.py @@ -544,7 +544,6 @@ def parameters(self) -> Dict[str, Any]: return params def __eq__(self, other: "SymbolicPulse") -> bool: - if not isinstance(other, SymbolicPulse): return NotImplemented diff --git a/qiskit/pulse/macros.py b/qiskit/pulse/macros.py index f45d94bbeb98..5530e0baddc9 100644 --- a/qiskit/pulse/macros.py +++ b/qiskit/pulse/macros.py @@ -64,7 +64,6 @@ def measure( # backend is V2. if isinstance(backend, BackendV2): - return _measure_v2( qubits=qubits, target=backend.target, diff --git a/qiskit/pulse/schedule.py b/qiskit/pulse/schedule.py index 6643a03d1a31..fac36891b56b 100644 --- a/qiskit/pulse/schedule.py +++ b/qiskit/pulse/schedule.py @@ -580,7 +580,6 @@ def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: - if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") diff --git a/qiskit/quantum_info/synthesis/qsd.py b/qiskit/quantum_info/synthesis/qsd.py index b2f00a56045d..cd33a5058086 100644 --- a/qiskit/quantum_info/synthesis/qsd.py +++ b/qiskit/quantum_info/synthesis/qsd.py @@ -214,7 +214,7 @@ def _get_ucry_cz(nqubits, angles): else: angles = angles.copy() UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False) - for (i, angle) in enumerate(angles): + for i, angle in enumerate(angles): if np.abs(angle) > _EPS: qc.ry(angle, q_target) if not i == len(angles) - 1: diff --git a/qiskit/quantum_info/synthesis/xx_decompose/circuits.py b/qiskit/quantum_info/synthesis/xx_decompose/circuits.py index c0f2671f42f9..e7218fe20188 100644 --- a/qiskit/quantum_info/synthesis/xx_decompose/circuits.py +++ b/qiskit/quantum_info/synthesis/xx_decompose/circuits.py @@ -169,7 +169,6 @@ def xx_circuit_step(source, strength, target, embodiment): # check for overlap, back out permutation source_shared, target_shared = None, None for i, j in [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]: - if ( abs(np.mod(abs(shifted_source_coord[i] - target[j]), np.pi)) < EPSILON or abs(np.mod(abs(shifted_source_coord[i] - target[j]), np.pi) - np.pi) diff --git a/qiskit/synthesis/clifford/clifford_decompose_bm.py b/qiskit/synthesis/clifford/clifford_decompose_bm.py index 5c4c3bcee5a3..40efa424da34 100644 --- a/qiskit/synthesis/clifford/clifford_decompose_bm.py +++ b/qiskit/synthesis/clifford/clifford_decompose_bm.py @@ -155,7 +155,6 @@ def _reduce_cost(clifford, inv_circuit, cost): for qubit0 in range(num_qubits): for qubit1 in range(qubit0 + 1, num_qubits): for n0, n1 in product(range(3), repeat=2): - # Apply a 2-qubit block reduced = clifford.copy() for qubit, n in [(qubit0, n0), (qubit1, n1)]: diff --git a/qiskit/synthesis/clifford/clifford_decompose_greedy.py b/qiskit/synthesis/clifford/clifford_decompose_greedy.py index b0d7f60c4736..ba14285b1848 100644 --- a/qiskit/synthesis/clifford/clifford_decompose_greedy.py +++ b/qiskit/synthesis/clifford/clifford_decompose_greedy.py @@ -219,7 +219,6 @@ def _calc_decoupling(pauli_x, pauli_z, qubit_list, min_qubit, num_qubits, cliff) # Reduce the pair of Paulis to a representative in the equivalence class # ['XZ', 'XX', 'XI', 'IZ', 'II'] by adding single-qubit gates for qubit in qubit_list: - typeq = _from_pair_paulis_to_type(pauli_x, pauli_z, qubit) if typeq in [ diff --git a/qiskit/tools/jupyter/backend_monitor.py b/qiskit/tools/jupyter/backend_monitor.py index ecb401521caf..5d5321c906c0 100644 --- a/qiskit/tools/jupyter/backend_monitor.py +++ b/qiskit/tools/jupyter/backend_monitor.py @@ -480,7 +480,6 @@ def job_history(backend): def _build_job_history(tabs, backend): - past_year_date = datetime.datetime.now() - datetime.timedelta(days=365) date_filter = {"creationDate": {"gt": past_year_date.isoformat()}} jobs = backend.jobs(limit=None, db_filter=date_filter) diff --git a/qiskit/tools/jupyter/watcher_monitor.py b/qiskit/tools/jupyter/watcher_monitor.py index 7d12dfc9bd03..51a4637aea3f 100644 --- a/qiskit/tools/jupyter/watcher_monitor.py +++ b/qiskit/tools/jupyter/watcher_monitor.py @@ -51,7 +51,6 @@ def _job_checker(job, status, watcher): if status.name == "QUEUED": queue_pos = job.queue_position() if queue_pos != prev_queue_pos: - update_info = (job.job_id(), status.name, queue_pos, status.value) watcher.update_single_job(update_info) diff --git a/qiskit/transpiler/instruction_durations.py b/qiskit/transpiler/instruction_durations.py index d1611840a040..ed261b53ef78 100644 --- a/qiskit/transpiler/instruction_durations.py +++ b/qiskit/transpiler/instruction_durations.py @@ -130,7 +130,6 @@ def update(self, inst_durations: "InstructionDurationsType" | None, dt: float = ) else: for i, items in enumerate(inst_durations): - if not isinstance(items[-1], str): items = (*items, "dt") # set default unit diff --git a/qiskit/transpiler/passes/basis/basis_translator.py b/qiskit/transpiler/passes/basis/basis_translator.py index 5383f940c255..19043fedc49c 100644 --- a/qiskit/transpiler/passes/basis/basis_translator.py +++ b/qiskit/transpiler/passes/basis/basis_translator.py @@ -587,7 +587,6 @@ def _compose_transforms(basis_transforms, source_basis, source_dag): ] if doomed_nodes and logger.isEnabledFor(logging.DEBUG): - logger.debug( "Updating transform for mapped instr %s %s from \n%s", mapped_instr_name, @@ -596,7 +595,6 @@ def _compose_transforms(basis_transforms, source_basis, source_dag): ) for node in doomed_nodes: - replacement = equiv.assign_parameters( dict(zip_longest(equiv_params, node.op.params)) ) @@ -606,7 +604,6 @@ def _compose_transforms(basis_transforms, source_basis, source_dag): dag.substitute_node_with_dag(node, replacement_dag) if doomed_nodes and logger.isEnabledFor(logging.DEBUG): - logger.debug( "Updated transform for mapped instr %s %s to\n%s", mapped_instr_name, diff --git a/qiskit/transpiler/passes/optimization/commutation_analysis.py b/qiskit/transpiler/passes/optimization/commutation_analysis.py index b35a88a23dff..2234fbf169dd 100644 --- a/qiskit/transpiler/passes/optimization/commutation_analysis.py +++ b/qiskit/transpiler/passes/optimization/commutation_analysis.py @@ -55,14 +55,12 @@ def run(self, dag): # Add edges to the dictionary for each qubit for node in dag.topological_op_nodes(): - for (_, _, edge_wire) in dag.edges(node): + for _, _, edge_wire in dag.edges(node): self.property_set["commutation_set"][(node, edge_wire)] = -1 # Construct the commutation set for wire in dag.wires: - for current_gate in dag.nodes_on_wire(wire): - current_comm_set = self.property_set["commutation_set"][wire] if not current_comm_set: current_comm_set.append([current_gate]) diff --git a/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py b/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py index 5f4be27d220e..17eb0f9da7d9 100644 --- a/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py +++ b/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py @@ -136,7 +136,6 @@ def run(self, dag: DAGCircuit): decomposer = TwoQubitControlledUDecomposer(RZXGate) for node in dag.two_qubit_ops(): - unitary = Operator(node.op).data dag_weyl = circuit_to_dag(decomposer(unitary)) dag.substitute_node_with_dag(node, dag_weyl) diff --git a/qiskit/transpiler/passes/optimization/template_matching/backward_match.py b/qiskit/transpiler/passes/optimization/template_matching/backward_match.py index a4b11a33de2d..920f2b80a065 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/backward_match.py +++ b/qiskit/transpiler/passes/optimization/template_matching/backward_match.py @@ -256,7 +256,6 @@ def _is_same_q_conf(self, node_circuit, node_template, qarg_circuit): """ # If the gate is controlled, then the control qubits have to be compared as sets. if isinstance(node_circuit.op, ControlledGate): - c_template = node_template.op.num_ctrl_qubits if c_template == 1: @@ -267,7 +266,6 @@ def _is_same_q_conf(self, node_circuit, node_template, qarg_circuit): control_qubits_circuit = qarg_circuit[:c_template] if set(control_qubits_circuit) == set(control_qubits_template): - target_qubits_template = node_template.qindices[c_template::] target_qubits_circuit = qarg_circuit[c_template::] @@ -424,7 +422,6 @@ def run_backward_match(self): # While the scenario stack is not empty. while self.matching_list.matching_scenarios_list: - # If parameters are given, the heuristics is applied. if self.heuristics_backward_param: self._backward_heuristics( @@ -490,7 +487,6 @@ def run_backward_match(self): # Loop over the template candidates. for template_id in candidates_indices: - node_template = self.template_dag_dep.get_node(template_id) qarg2 = self.template_dag_dep.get_node(template_id).qindices @@ -509,7 +505,6 @@ def run_backward_match(self): and self._is_same_c_conf(node_circuit, node_template, carg1) and self._is_same_op(node_circuit, node_template) ): - # If there is a match the attributes are copied. circuit_matched_match = circuit_matched.copy() circuit_blocked_match = circuit_blocked.copy() @@ -625,7 +620,6 @@ def run_backward_match(self): # Third option: if blocking the succesors breaks a match, we consider # also the possibility to block all predecessors (push the gate to the left). if broken_matches and all(global_broken): - circuit_matched_block_p = circuit_matched.copy() circuit_blocked_block_p = circuit_blocked.copy() @@ -651,7 +645,6 @@ def run_backward_match(self): # If there is no match then there are three options. if not global_match: - circuit_blocked[circuit_id] = True following_matches = [] @@ -666,7 +659,6 @@ def run_backward_match(self): predecessors = self.circuit_dag_dep.get_node(circuit_id).predecessors if not predecessors or not following_matches: - matching_scenario = MatchingScenarios( circuit_matched, circuit_blocked, @@ -678,7 +670,6 @@ def run_backward_match(self): self.matching_list.append_scenario(matching_scenario) else: - circuit_matched_nomatch = circuit_matched.copy() circuit_blocked_nomatch = circuit_blocked.copy() diff --git a/qiskit/transpiler/passes/optimization/template_matching/forward_match.py b/qiskit/transpiler/passes/optimization/template_matching/forward_match.py index 6c5380539701..d3a8ef589d5e 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/forward_match.py +++ b/qiskit/transpiler/passes/optimization/template_matching/forward_match.py @@ -268,7 +268,6 @@ def _is_same_q_conf(self, node_circuit, node_template): """ if isinstance(node_circuit.op, ControlledGate): - c_template = node_template.op.num_ctrl_qubits if c_template == 1: @@ -279,7 +278,6 @@ def _is_same_q_conf(self, node_circuit, node_template): control_qubits_circuit = self.qarg_indices[:c_template] if set(control_qubits_circuit) == set(control_qubits_template): - target_qubits_template = node_template.qindices[c_template::] target_qubits_circuit = self.qarg_indices[c_template::] @@ -347,7 +345,6 @@ def run_forward_match(self): # While the list of matched nodes is not empty while self.matched_nodes_list: - # Return first element of the matched_nodes_list and removes it from the list v_first = self._get_node_forward(0) self._remove_node_forward(0) @@ -386,7 +383,6 @@ def run_forward_match(self): # For loop over the candidates (template) to find a match. for i in self.candidates: - # Break the for loop if a match is found. if match: break @@ -411,7 +407,6 @@ def run_forward_match(self): and self._is_same_c_conf(node_circuit, node_template) and self._is_same_op(node_circuit, node_template) ): - v[1].matchedwith = [i] self.template_dag_dep.get_node(i).matchedwith = [label] diff --git a/qiskit/transpiler/passes/optimization/template_matching/template_matching.py b/qiskit/transpiler/passes/optimization/template_matching/template_matching.py index 29b65f8e7380..62410ada7893 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/template_matching.py +++ b/qiskit/transpiler/passes/optimization/template_matching/template_matching.py @@ -256,7 +256,6 @@ def run_template_matching(self): if self.circuit_dag_dep.get_node(circuit_index).op.soft_compare( self.template_dag_dep.get_node(template_index).op ): - qarg_c = self.circuit_dag_dep.get_node(circuit_index).qindices carg_c = self.circuit_dag_dep.get_node(circuit_index).cindices diff --git a/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py b/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py index 5e020fd03a30..f6f1bfdc8739 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py +++ b/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py @@ -253,7 +253,6 @@ def _permutation(self): index = self.substitution_list.index(scenario) for scenario_b in self.substitution_list[index::]: if set(scenario_b.circuit_config) & predecessors: - index1 = self.substitution_list.index(scenario) index2 = self.substitution_list.index(scenario_b) @@ -306,7 +305,6 @@ def _substitution(self): """ while self.match_stack: - # Get the first match scenario of the list current = self.match_stack.pop(0) @@ -386,7 +384,6 @@ def run_dag_opt(self): if self.substitution_list: # Loop over the different matches. for group in self.substitution_list: - circuit_sub = group.circuit_config template_inverse = group.template_config diff --git a/qiskit/transpiler/passes/routing/algorithms/bip_model.py b/qiskit/transpiler/passes/routing/algorithms/bip_model.py index 972cf8242918..8deedd11a17d 100644 --- a/qiskit/transpiler/passes/routing/algorithms/bip_model.py +++ b/qiskit/transpiler/passes/routing/algorithms/bip_model.py @@ -211,8 +211,8 @@ def create_cpx_problem( # Add y variables y = {} for t in range(self.depth): - for ((p, q), _) in self.gates[t]: - for (i, j) in self._arcs: + for (p, q), _ in self.gates[t]: + for i, j in self._arcs: y[t, p, q, i, j] = mdl.binary_var(name=f"y_{t}_{p}_{q}_{i}_{j}") # Add x variables x = {} @@ -239,15 +239,15 @@ def create_cpx_problem( ) # Each gate must be implemented for t in range(self.depth): - for ((p, q), _) in self.gates[t]: + for (p, q), _ in self.gates[t]: mdl.add_constraint( sum(y[t, p, q, i, j] for (i, j) in self._arcs) == 1, ctname=f"implement_gate_{p}_{q}_at_{t}", ) # Gate can be implemented iff both of its qubits are located at the associated nodes for t in range(self.depth - 1): - for ((p, q), _) in self.gates[t]: - for (i, j) in self._arcs: + for (p, q), _ in self.gates[t]: + for i, j in self._arcs: # Apply McCormick to y[t, p, q, i, j] == w[t, p, i] * w[t, q, j] mdl.add_constraint( y[t, p, q, i, j] >= w[t, p, i] + w[t, q, j] - 1, @@ -264,8 +264,8 @@ def create_cpx_problem( ctname=f"McCormickUB2_{p}_{q}_{i}_{j}_at_{t}", ) # For last time step, use regular McCormick - for ((p, q), _) in self.gates[self.depth - 1]: - for (i, j) in self._arcs: + for (p, q), _ in self.gates[self.depth - 1]: + for i, j in self._arcs: # Apply McCormick to y[self.depth - 1, p, q, i, j] # == w[self.depth - 1, p, i] * w[self.depth - 1, q, j] mdl.add_constraint( @@ -302,18 +302,18 @@ def create_cpx_problem( ) # If a gate is implemented, involved qubits cannot swap with other positions for t in range(self.depth - 1): - for ((p, q), _) in self.gates[t]: - for (i, j) in self._arcs: + for (p, q), _ in self.gates[t]: + for i, j in self._arcs: mdl.add_constraint( x[t, p, i, j] == x[t, q, j, i], ctname=f"swap_{p}_{q}_{i}_{j}_at_{t}" ) # Qubit not in gates can flip with their neighbors for t in range(self.depth - 1): q_no_gate = list(range(self.num_vqubits)) - for ((p, q), _) in self.gates[t]: + for (p, q), _ in self.gates[t]: q_no_gate.remove(p) q_no_gate.remove(q) - for (i, j) in self._arcs: + for i, j in self._arcs: mdl.add_constraint( sum(x[t, q, i, j] for q in q_no_gate) == sum(x[t, p, j, i] for p in q_no_gate), ctname=f"swap_no_gate_{i}_{j}_at_{t}", @@ -356,7 +356,7 @@ def create_cpx_problem( objexr = sum(z[t] for t in range(self.depth) if self._is_dummy_step(t)) for t in range(self.depth - 1): for q in range(self.num_vqubits): - for (i, j) in self._arcs: + for i, j in self._arcs: objexr += 0.01 * x[t, q, i, j] mdl.minimize(objexr) elif objective in ("gate_error", "balanced"): @@ -364,7 +364,7 @@ def create_cpx_problem( objexr = 0 for t in range(self.depth - 1): for (p, q), node in self.gates[t]: - for (i, j) in self._arcs: + for i, j in self._arcs: # We pay the cost for gate implementation. pbest_fid = -np.log(self._max_expected_fidelity(node, i, j)) objexr += y[t, p, q, i, j] * pbest_fid @@ -381,7 +381,7 @@ def create_cpx_problem( objexr += x[t, q, i, j] * -3 / 2 * np.log(self._cx_fidelity(i, j)) # Cost for the last layer (x variables are not defined for depth-1) for (p, q), node in self.gates[self.depth - 1]: - for (i, j) in self._arcs: + for i, j in self._arcs: pbest_fid = -np.log(self._max_expected_fidelity(node, i, j)) objexr += y[self.depth - 1, p, q, i, j] * pbest_fid if objective == "balanced": @@ -488,7 +488,7 @@ def get_swaps(self, t: int) -> list: List of swaps (pairs of physical qubits (integers)) """ swaps = [] - for (i, j) in self._arcs: + for i, j in self._arcs: if i >= j: continue for q in range(self.num_vqubits): diff --git a/qiskit/transpiler/passes/routing/bip_mapping.py b/qiskit/transpiler/passes/routing/bip_mapping.py index a658c1c98eaa..a94c05236822 100644 --- a/qiskit/transpiler/passes/routing/bip_mapping.py +++ b/qiskit/transpiler/passes/routing/bip_mapping.py @@ -217,7 +217,7 @@ def run(self, dag): from_steps = max(interval * (su4dep - 1), 0) to_steps = min(interval * su4dep, model.depth - 1) for t in range(from_steps, to_steps): # pylint: disable=invalid-name - for (i, j) in model.get_swaps(t): + for i, j in model.get_swaps(t): mapped_dag.apply_operation_back( op=SwapGate(), qargs=[canonical_qreg[i], canonical_qreg[j]], diff --git a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py index 60b5cf9e3ad3..a2cf7630e3db 100644 --- a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py +++ b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py @@ -169,7 +169,6 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: for node in dag.topological_op_nodes(): if isinstance(node.op, Commuting2qBlock): - # Check that the swap strategy creates enough connectivity for the node. self._check_edges(dag, node, swap_strategy) diff --git a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py index 8b92c5cdaf53..eb86d36febb6 100644 --- a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py +++ b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py @@ -130,7 +130,6 @@ def _decompose_to_2q(self, dag: DAGCircuit, op: PauliEvolutionGate) -> DAGCircui } for edge, (pauli, coeff) in required_paulis.items(): - qubits = [dag.qubits[edge[0]], dag.qubits[edge[1]]] simple_pauli = Pauli(pauli.to_label().replace("I", "")) diff --git a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py index 72b62dc49a81..d32da751b2ac 100644 --- a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py +++ b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py @@ -180,7 +180,6 @@ def distance_matrix(self) -> np.ndarray: for i in range(len(self._swap_layers) + 1): for j, k in self.swapped_coupling_map(i).get_edges(): - # This if ensures that the smallest distance is used. if self._distance_matrix[j, k] == -1: self._distance_matrix[j, k] = i diff --git a/qiskit/transpiler/passes/scheduling/alignments/reschedule.py b/qiskit/transpiler/passes/scheduling/alignments/reschedule.py index b53d0f864cef..08020b8f8691 100644 --- a/qiskit/transpiler/passes/scheduling/alignments/reschedule.py +++ b/qiskit/transpiler/passes/scheduling/alignments/reschedule.py @@ -225,7 +225,6 @@ def run(self, dag: DAGCircuit): node_start_time = self.property_set["node_start_time"] for node in dag.topological_op_nodes(): - start_time = node_start_time.get(node) if start_time is None: diff --git a/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py b/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py index dbc60999fc35..634520610438 100644 --- a/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py +++ b/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py @@ -263,7 +263,6 @@ def supports_coupling_map(self): return False def run(self, unitary, **options): - # Runtime imports to avoid the overhead of these imports for # plugin discovery and only use them if the plugin is run/used config = options.get("config") or {} diff --git a/qiskit/transpiler/passes/synthesis/unitary_synthesis.py b/qiskit/transpiler/passes/synthesis/unitary_synthesis.py index 67176ddf374e..8c1fc473bf6a 100644 --- a/qiskit/transpiler/passes/synthesis/unitary_synthesis.py +++ b/qiskit/transpiler/passes/synthesis/unitary_synthesis.py @@ -76,7 +76,6 @@ def _choose_euler_basis(basis_gates): basis_set = set(basis_gates or []) for basis, gates in one_qubit_decompose.ONE_QUBIT_EULER_BASIS_GATES.items(): - if set(gates).issubset(basis_set): return basis diff --git a/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py b/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py index e510ddc87aeb..919d2cfa0424 100644 --- a/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py +++ b/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py @@ -36,7 +36,6 @@ def run(self, dag): is_final_op = True for _, child_successors in dag.bfs_successors(candidate_node): - if any( isinstance(suc, DAGOpNode) and suc.name not in final_op_types for suc in child_successors diff --git a/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py b/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py index f77870047c9d..ef78900179d8 100644 --- a/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py +++ b/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py @@ -113,10 +113,8 @@ def _collect_potential_merges(dag, barriers): barrier_to_add = Barrier(len(current_qubits)) for next_barrier in barriers[1:]: - # Ensure barriers are adjacent before checking if they are mergeable. if dag._multi_graph.has_edge(end_of_barrier._node_id, next_barrier._node_id): - # Remove all barriers that have already been included in this new barrier from the # set of ancestors/descendants as they will be removed from the new DAG when it is # created. @@ -133,7 +131,6 @@ def _collect_potential_merges(dag, barriers): and current_ancestors.isdisjoint(next_descendants) and current_descendants.isdisjoint(next_ancestors) ): - # can be merged current_ancestors = current_ancestors | next_ancestors current_descendants = current_descendants | next_descendants diff --git a/qiskit/transpiler/preset_passmanagers/level1.py b/qiskit/transpiler/preset_passmanagers/level1.py index 1f6972d0ac3d..a5fe9065d62e 100644 --- a/qiskit/transpiler/preset_passmanagers/level1.py +++ b/qiskit/transpiler/preset_passmanagers/level1.py @@ -239,6 +239,7 @@ def _swap_mapped(property_set): if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] + # Build nested Flow controllers def _unroll_condition(property_set): return not property_set["all_gates_in_basis"] diff --git a/qiskit/transpiler/preset_passmanagers/level2.py b/qiskit/transpiler/preset_passmanagers/level2.py index de17840c499e..1c3ddc515951 100644 --- a/qiskit/transpiler/preset_passmanagers/level2.py +++ b/qiskit/transpiler/preset_passmanagers/level2.py @@ -226,6 +226,7 @@ def _swap_mapped(property_set): if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] + # Build nested Flow controllers def _unroll_condition(property_set): return not property_set["all_gates_in_basis"] diff --git a/qiskit/transpiler/preset_passmanagers/level3.py b/qiskit/transpiler/preset_passmanagers/level3.py index 9635d978fe0f..1038ffca3002 100644 --- a/qiskit/transpiler/preset_passmanagers/level3.py +++ b/qiskit/transpiler/preset_passmanagers/level3.py @@ -258,6 +258,7 @@ def _swap_mapped(property_set): if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] + # Build nested Flow controllers def _unroll_condition(property_set): return not property_set["all_gates_in_basis"] diff --git a/qiskit/transpiler/synthesis/aqc/aqc_plugin.py b/qiskit/transpiler/synthesis/aqc/aqc_plugin.py index 0138d8e7b97a..4ea8da597cf5 100644 --- a/qiskit/transpiler/synthesis/aqc/aqc_plugin.py +++ b/qiskit/transpiler/synthesis/aqc/aqc_plugin.py @@ -101,7 +101,6 @@ def supports_coupling_map(self): return False def run(self, unitary, **options): - # Runtime imports to avoid the overhead of these imports for # plugin discovery and only use them if the plugin is run/used from qiskit.algorithms.optimizers import L_BFGS_B diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 5d566f625116..485be032941c 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -149,7 +149,6 @@ def apply(self, raw_data, method="least_squares"): ) elif isinstance(raw_data, qiskit.result.result.Result): - # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) @@ -173,7 +172,6 @@ def apply(self, raw_data, method="least_squares"): # Apply the correction for data_idx, _ in enumerate(raw_data2): - if method == "pseudo_inverse": raw_data2[data_idx] = np.dot(pinv_cal_mat, raw_data2[data_idx]) @@ -279,7 +277,6 @@ def substate_labels_list(self, new_substate_labels_list): # get the indices in the calibration matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): - self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)}) @property @@ -382,7 +379,6 @@ def apply( raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): - # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) @@ -413,7 +409,6 @@ def apply( # Apply the correction for data_idx, _ in enumerate(raw_data2): - if method == "pseudo_inverse": for pinv_cal_mat, pos_qubits, indices in zip( pinv_cal_matrices, self._mit_pattern, self._indices_list diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index 2fdeaa6372a6..6ccad17a6c99 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -224,7 +224,6 @@ def tensored_meas_cal( end_index = nqubits for qubit_list, list_size in zip(mit_pattern, qubits_list_sizes): - start_index = end_index - list_size substate = basis_state[start_index:end_index] @@ -239,7 +238,6 @@ def tensored_meas_cal( # add measurements end_index = nqubits for qubit_list, list_size in zip(mit_pattern, qubits_list_sizes): - for qind in range(list_size): qc_circuit.measure(qr[qubit_list[qind]], cr[nqubits - (end_index - qind)]) diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index 65357d5dc5b5..2c92dc3c99f3 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -181,7 +181,6 @@ def subset_fitter(self, qubit_sublist): # do a partial trace for i in range(len(new_state_labels)): for j in range(len(new_state_labels)): - for q_q_i_map in q_q_mapping[i]: for q_q_j_map in q_q_mapping[j]: new_cal_matrix[i, j] += self.cal_matrix[q_q_i_map, q_q_j_map] @@ -421,7 +420,6 @@ def _build_calibration_matrices(self): for measured_state, counts in state_cnts.items(): end_index = self.nqubits for cal_ind, cal_mat in enumerate(self._cal_matrices): - start_index = end_index - self._qubit_list_sizes[cal_ind] substate_index = self._indices_list[cal_ind][state[start_index:end_index]] diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index 9714234ca694..6265365403d9 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -344,7 +344,6 @@ def _safe_submit_circuits( pip_install="pip install qiskit-ibmq-provider", ) from ex1 if isinstance(ex, IBMQBackendJobLimitError): - oldest_running = backend.jobs( limit=1, descending=False, status=["QUEUED", "VALIDATING", "RUNNING"] ) diff --git a/qiskit/visualization/bloch.py b/qiskit/visualization/bloch.py index 778e4a013546..4e956814c46e 100644 --- a/qiskit/visualization/bloch.py +++ b/qiskit/visualization/bloch.py @@ -154,7 +154,6 @@ class Bloch: def __init__( self, fig=None, axes=None, view=None, figsize=None, background=False, font_size=20 ): - # Figure and axes self._ext_fig = False if fig is not None: @@ -587,7 +586,6 @@ def plot_vectors(self): """Plot vector""" # -X and Y data are switched for plotting purposes for k in range(len(self.vectors)): - xs3d = self.vectors[k][1] * np.array([0, 1]) ys3d = -self.vectors[k][0] * np.array([0, 1]) zs3d = self.vectors[k][2] * np.array([0, 1]) diff --git a/qiskit/visualization/circuit/matplotlib.py b/qiskit/visualization/circuit/matplotlib.py index fb61c7cf6d3b..25b29835ed3a 100644 --- a/qiskit/visualization/circuit/matplotlib.py +++ b/qiskit/visualization/circuit/matplotlib.py @@ -593,7 +593,6 @@ def _set_bit_reg_info(self, wire_map, qubits_dict, clbits_dict, glob_data): idx = 0 pos = y_off = -len(self._qubits) + 1 for ii, wire in enumerate(wire_map): - # if it's a creg, register is the key and just load the index if isinstance(wire, ClassicalRegister): # If wire came from ControlFlowOp and not in clbits, don't draw it diff --git a/qiskit/visualization/circuit/text.py b/qiskit/visualization/circuit/text.py index 0185723fc8c6..ab5ac76f5e23 100644 --- a/qiskit/visualization/circuit/text.py +++ b/qiskit/visualization/circuit/text.py @@ -1477,7 +1477,6 @@ def connect_with(self, wire_char): """ for label, affected_bits in self.connections: - if not affected_bits: continue diff --git a/qiskit/visualization/gate_map.py b/qiskit/visualization/gate_map.py index 86a3fbe9f858..a9d919d0d931 100644 --- a/qiskit/visualization/gate_map.py +++ b/qiskit/visualization/gate_map.py @@ -1411,7 +1411,6 @@ def plot_error_map(backend, figsize=(12, 9), show_title=True, qubit_coordinates= directed = False line_colors = [] if cmap: - # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) diff --git a/qiskit/visualization/pass_manager_visualization.py b/qiskit/visualization/pass_manager_visualization.py index 6765c199e7c5..1caa7fd7e9d8 100644 --- a/qiskit/visualization/pass_manager_visualization.py +++ b/qiskit/visualization/pass_manager_visualization.py @@ -200,7 +200,6 @@ def draw_subgraph(controller_group, component_id, style, prev_node, idx): component_id += 1 for pass_ in controller_group["passes"]: - # label is the name of the pass node = pydot.Node( str(component_id), diff --git a/qiskit/visualization/pulse_v2/core.py b/qiskit/visualization/pulse_v2/core.py index 42cfa224c5d4..eecbf09d800d 100644 --- a/qiskit/visualization/pulse_v2/core.py +++ b/qiskit/visualization/pulse_v2/core.py @@ -290,7 +290,6 @@ def _schedule_loader(self, program: pulse.Schedule | pulse.ScheduleBlock): for name, chans in mapper( channels=program.channels, formatter=self.formatter, device=self.device ): - chart = Chart(parent=self, name=name) # add standard pulse instructions diff --git a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml new file mode 100644 index 000000000000..a0026456e9f1 --- /dev/null +++ b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Disables the use of `RemoveResetInZeroState` in the preset passmanagers. + This better aligns circuits to the notion of arbitrary initital states + unless explicilty set to zeros with resets. diff --git a/test/python/algorithms/minimum_eigensolvers/test_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_vqe.py index 4e61aa89f704..ddef131ba922 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_vqe.py @@ -43,6 +43,7 @@ from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals + # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" diff --git a/test/python/algorithms/test_aux_ops_evaluator.py b/test/python/algorithms/test_aux_ops_evaluator.py index 11e4c8e76fc5..3ba5e6cdc4eb 100644 --- a/test/python/algorithms/test_aux_ops_evaluator.py +++ b/test/python/algorithms/test_aux_ops_evaluator.py @@ -86,7 +86,6 @@ def _run_test( observables: ListOrDict[OperatorBase], quantum_instance: Union[QuantumInstance, Backend], ): - with self.assertWarns(DeprecationWarning): result = eval_observables( quantum_instance, quantum_state, observables, expectation, self.threshold diff --git a/test/python/algorithms/test_measure_error_mitigation.py b/test/python/algorithms/test_measure_error_mitigation.py index a252ab08af7d..5347ca81b371 100644 --- a/test/python/algorithms/test_measure_error_mitigation.py +++ b/test/python/algorithms/test_measure_error_mitigation.py @@ -242,7 +242,6 @@ def test_measurement_error_mitigation_qaoa(self): ) with self.assertWarns(DeprecationWarning): - qaoa = QAOA( optimizer=COBYLA(maxiter=3), quantum_instance=quantum_instance, diff --git a/test/python/algorithms/test_phase_estimator.py b/test/python/algorithms/test_phase_estimator.py index 9040bc1d6912..cc6833d17142 100644 --- a/test/python/algorithms/test_phase_estimator.py +++ b/test/python/algorithms/test_phase_estimator.py @@ -368,7 +368,6 @@ def one_phase( qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): - if phase_estimator == IterativePhaseEstimation: p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi) elif phase_estimator == PhaseEstimation: diff --git a/test/python/algorithms/test_qaoa.py b/test/python/algorithms/test_qaoa.py index 7c743af7e263..b50fd2d247a8 100644 --- a/test/python/algorithms/test_qaoa.py +++ b/test/python/algorithms/test_qaoa.py @@ -282,7 +282,6 @@ def test_qaoa_initial_state(self, w, init_state): self.assertEqual(len(zero_circuits), len(custom_circuits)) for zero_circ, custom_circ in zip(zero_circuits, custom_circuits): - z_length = len(zero_circ.data) c_length = len(custom_circ.data) diff --git a/test/python/circuit/library/test_linear_function.py b/test/python/circuit/library/test_linear_function.py index 4209d1a4e4a0..d2eb6c38338f 100644 --- a/test/python/circuit/library/test_linear_function.py +++ b/test/python/circuit/library/test_linear_function.py @@ -39,7 +39,6 @@ def random_linear_circuit( clifford=False, recursion_depth=0, ): - """Generate a pseudo random linear circuit.""" if num_qubits == 0: diff --git a/test/python/circuit/test_gate_definitions.py b/test/python/circuit/test_gate_definitions.py index 0c41189fc954..6a5742b770d2 100644 --- a/test/python/circuit/test_gate_definitions.py +++ b/test/python/circuit/test_gate_definitions.py @@ -285,6 +285,7 @@ class TestGateEquivalenceEqual(QiskitTestCase): "_U0Gate", "_DefinedGate", } + # Amazingly, Python's scoping rules for class bodies means that this is the closest we can get # to a "natural" comprehension or functional iterable definition: # https://docs.python.org/3/reference/executionmodel.html#resolution-of-names diff --git a/test/python/circuit/test_random_circuit.py b/test/python/circuit/test_random_circuit.py index d318c9c58578..dcdbec5a9de3 100644 --- a/test/python/circuit/test_random_circuit.py +++ b/test/python/circuit/test_random_circuit.py @@ -63,7 +63,7 @@ def test_large_conditional(self): conditions = (getattr(instruction.operation, "condition", None) for instruction in circ) conditions = [x for x in conditions if x is not None] self.assertNotEqual(conditions, []) - for (register, value) in conditions: + for register, value in conditions: self.assertIsInstance(register, (ClassicalRegister, Clbit)) # Condition values always have to be Python bigints (of which `bool` is a subclass), not # any of Numpy's fixed-width types, for example. diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 07ada8e56ef9..4720b3b23d39 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -1098,7 +1098,6 @@ def test_gradient_wrapper(self, backend_type): operator=op, bind_params=params, backend=q_instance ) else: - with self.assertWarns(DeprecationWarning): prob_grad = Gradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance @@ -1516,7 +1515,6 @@ def test_aux_meas_op(self, aux_meas_op): ] for backend_type in ["qasm_simulator", "statevector_simulator"]: - for j, value_dict in enumerate(value_dicts): with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index 10448c3a64e1..5706a547666e 100644 --- a/test/python/opflow/test_matrix_expectation.py +++ b/test/python/opflow/test_matrix_expectation.py @@ -86,7 +86,6 @@ def test_pauli_expect_op_vector(self): converted_meas = self.expect.convert(~StateFn(paulis_op)) with self.assertWarns(DeprecationWarning): - plus_mean = converted_meas @ Plus np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) sampled_plus = self.sampler.convert(plus_mean) diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index e6d23390ea78..067eb2035311 100644 --- a/test/python/opflow/test_state_op_meas_evals.py +++ b/test/python/opflow/test_state_op_meas_evals.py @@ -176,7 +176,6 @@ def test_circuit_sampler_caching(self, caching): circuit.ry(x, 0) with self.assertWarns(DeprecationWarning): - expr1 = ~StateFn(H) @ StateFn(circuit) expr2 = ~StateFn(X) @ StateFn(circuit) sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector"), caching=caching) diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index df9387ee070b..d8850c602273 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -333,7 +333,6 @@ def test_bound_pass_manager(self): op = SparsePauliOp.from_list([("II", 1)]) with self.subTest("Test single circuit"): - dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: @@ -343,7 +342,6 @@ def test_bound_pass_manager(self): self.assertEqual(mock_pass.call_count, 1) with self.subTest("Test circuit batch"): - dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index 86dc709f8983..3c56ea2bfd80 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -387,7 +387,6 @@ def test_bound_pass_manager(self): """Test bound pass manager.""" with self.subTest("Test single circuit"): - dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: @@ -397,7 +396,6 @@ def test_bound_pass_manager(self): self.assertEqual(mock_pass.call_count, 1) with self.subTest("Test circuit batch"): - dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: diff --git a/test/python/quantum_info/states/test_densitymatrix.py b/test/python/quantum_info/states/test_densitymatrix.py index 3185758cb469..7377f4859f10 100644 --- a/test/python/quantum_info/states/test_densitymatrix.py +++ b/test/python/quantum_info/states/test_densitymatrix.py @@ -620,7 +620,6 @@ def test_sample_counts_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -628,7 +627,6 @@ def test_sample_counts_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -636,7 +634,6 @@ def test_sample_counts_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -657,7 +654,6 @@ def test_sample_counts_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -665,7 +661,6 @@ def test_sample_counts_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -673,7 +668,6 @@ def test_sample_counts_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -764,7 +758,6 @@ def test_sample_memory_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -773,7 +766,6 @@ def test_sample_memory_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -782,7 +774,6 @@ def test_sample_memory_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -803,7 +794,6 @@ def test_sample_memory_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -812,7 +802,6 @@ def test_sample_memory_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -821,7 +810,6 @@ def test_sample_memory_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) diff --git a/test/python/quantum_info/states/test_statevector.py b/test/python/quantum_info/states/test_statevector.py index a7228d6bf5d2..fde32c744fb1 100644 --- a/test/python/quantum_info/states/test_statevector.py +++ b/test/python/quantum_info/states/test_statevector.py @@ -675,7 +675,6 @@ def test_sample_counts_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -683,7 +682,6 @@ def test_sample_counts_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -691,7 +689,6 @@ def test_sample_counts_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -709,7 +706,6 @@ def test_sample_counts_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -717,7 +713,6 @@ def test_sample_counts_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -725,7 +720,6 @@ def test_sample_counts_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -814,7 +808,6 @@ def test_sample_memory_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -823,7 +816,6 @@ def test_sample_memory_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -832,7 +824,6 @@ def test_sample_memory_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -850,7 +841,6 @@ def test_sample_memory_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -859,7 +849,6 @@ def test_sample_memory_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -868,7 +857,6 @@ def test_sample_memory_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: - with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) diff --git a/test/python/transpiler/aqc/fast_gradient/test_layer1q.py b/test/python/transpiler/aqc/fast_gradient/test_layer1q.py index c3a211293cd3..a55a3961410c 100644 --- a/test/python/transpiler/aqc/fast_gradient/test_layer1q.py +++ b/test/python/transpiler/aqc/fast_gradient/test_layer1q.py @@ -45,7 +45,6 @@ def test_layer1q_matrix(self): eps = 100.0 * np.finfo(float).eps max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): - dim = 2**n iden = tut.eye_int(n) for k in range(n): @@ -92,7 +91,6 @@ def test_pmatrix_class(self): mat_kind = "complex" max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): - dim = 2**n tmp1 = np.ndarray((dim, dim), dtype=np.cfloat) tmp2 = tmp1.copy() diff --git a/test/python/transpiler/aqc/fast_gradient/test_layer2q.py b/test/python/transpiler/aqc/fast_gradient/test_layer2q.py index a4795f57be92..1ba05fdb1f91 100644 --- a/test/python/transpiler/aqc/fast_gradient/test_layer2q.py +++ b/test/python/transpiler/aqc/fast_gradient/test_layer2q.py @@ -45,7 +45,6 @@ def test_layer2q_matrix(self): _eps = 100.0 * np.finfo(float).eps max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): - dim = 2**n iden = tut.eye_int(n) for j in range(n): @@ -95,7 +94,6 @@ def test_pmatrix_class(self): mat_kind = "complex" max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): - dim = 2**n tmp1 = np.ndarray((dim, dim), dtype=np.cfloat) tmp2 = tmp1.copy() diff --git a/test/python/transpiler/aqc/fast_gradient/test_utils.py b/test/python/transpiler/aqc/fast_gradient/test_utils.py index d120fcac7ce4..75492bbe6532 100644 --- a/test/python/transpiler/aqc/fast_gradient/test_utils.py +++ b/test/python/transpiler/aqc/fast_gradient/test_utils.py @@ -109,7 +109,6 @@ def _permutation_and_matrix(size: int) -> (np.ndarray, np.ndarray, np.ndarray, n return perm, inv_perm, p_mat, q_mat for n in range(1, self.max_nqubits_perms + 1): - dim = 2**n for _ in range(100): perm1, inv_perm1, p1_mat, q1_mat = _permutation_and_matrix(dim) diff --git a/test/python/transpiler/test_echo_rzx_weyl_decomposition.py b/test/python/transpiler/test_echo_rzx_weyl_decomposition.py index 54f630d4ed24..d87d10ea1a6d 100644 --- a/test/python/transpiler/test_echo_rzx_weyl_decomposition.py +++ b/test/python/transpiler/test_echo_rzx_weyl_decomposition.py @@ -162,7 +162,6 @@ def test_weyl_decomposition_gate_angles(self): circuits = [circuit_rxx, circuit_ryy, circuit_rzz] for circuit in circuits: - unitary_circuit = qi.Operator(circuit).data dag = circuit_to_dag(circuit) diff --git a/test/python/utils/mitigation/test_meas.py b/test/python/utils/mitigation/test_meas.py index a5105b5ba4d5..a2c480519570 100644 --- a/test/python/utils/mitigation/test_meas.py +++ b/test/python/utils/mitigation/test_meas.py @@ -274,7 +274,6 @@ def test_ideal_meas_cal(self): """Test ideal execution, without noise.""" for nq in self.nq_list: for pattern_type in range(1, 2**nq): - # Generate the quantum register according to the pattern qubits, weight = self.choose_calibration(nq, pattern_type) From 4c1117702d9544cf1613ee191b9e8adf5d905671 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:15:44 -0400 Subject: [PATCH 03/15] Revert "Add reno and black" This reverts commit ea7c1e683bf3b703208e349b32f33af8f9960806. --- qiskit/algorithms/algorithm_result.py | 1 + .../eigen_solvers/numpy_eigen_solver.py | 2 ++ qiskit/algorithms/eigen_solvers/vqd.py | 10 ++++--- .../eigensolvers/numpy_eigensolver.py | 2 ++ qiskit/algorithms/gradients/reverse/bind.py | 1 - .../algorithms/minimum_eigen_solvers/vqe.py | 7 ++--- .../minimum_eigensolvers/sampling_vqe.py | 7 ++--- qiskit/algorithms/optimizers/adam_amsgrad.py | 1 + qiskit/algorithms/optimizers/aqgd.py | 2 +- .../algorithms/optimizers/gradient_descent.py | 1 + qiskit/algorithms/optimizers/gsls.py | 1 + qiskit/algorithms/optimizers/nft.py | 1 + qiskit/algorithms/optimizers/umda.py | 1 + .../hamiltonian_phase_estimation.py | 1 + qiskit/algorithms/phase_estimators/ipe.py | 1 + .../state_fidelities/base_state_fidelity.py | 7 +++-- .../time_evolvers/classical_methods/evolve.py | 1 + .../solvers/ode/abstract_ode_function.py | 1 + .../real_mc_lachlan_principle.py | 1 + .../variational_principle.py | 1 + qiskit/assembler/assemble_schedules.py | 1 + qiskit/circuit/controlflow/while_loop.py | 1 + .../library/arithmetic/integer_comparator.py | 2 ++ qiskit/circuit/library/n_local/n_local.py | 14 ++------- qiskit/compiler/assembler.py | 1 + qiskit/dagcircuit/dagcircuit.py | 1 + qiskit/dagcircuit/dagdepnode.py | 1 + .../quantum_initializer/isometry.py | 4 ++- .../quantum_initializer/uc_pauli_rot.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 2 ++ .../expectations/expectation_factory.py | 1 + .../gradients/circuit_gradients/lin_comb.py | 1 + .../gradients/circuit_qfis/lin_comb_full.py | 2 ++ .../gradients/circuit_qfis/overlap_diag.py | 2 ++ qiskit/opflow/gradients/gradient.py | 1 + qiskit/opflow/gradients/hessian.py | 1 + qiskit/opflow/gradients/qfi_base.py | 1 + qiskit/opflow/list_ops/composed_op.py | 1 + qiskit/opflow/list_ops/list_op.py | 1 + qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/primitive_ops/circuit_op.py | 1 + qiskit/opflow/primitive_ops/matrix_op.py | 1 + qiskit/opflow/primitive_ops/pauli_op.py | 4 +++ qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 ++ .../primitive_ops/tapered_pauli_sum_op.py | 1 + qiskit/opflow/state_fns/circuit_state_fn.py | 2 +- qiskit/primitives/backend_estimator.py | 2 ++ qiskit/primitives/backend_sampler.py | 1 + .../utils/configurable_backend.py | 6 ++-- qiskit/pulse/library/symbolic_pulses.py | 1 + qiskit/pulse/macros.py | 1 + qiskit/pulse/schedule.py | 1 + qiskit/quantum_info/synthesis/qsd.py | 2 +- .../synthesis/xx_decompose/circuits.py | 1 + .../clifford/clifford_decompose_bm.py | 1 + .../clifford/clifford_decompose_greedy.py | 1 + qiskit/tools/jupyter/backend_monitor.py | 1 + qiskit/tools/jupyter/watcher_monitor.py | 1 + qiskit/transpiler/instruction_durations.py | 1 + .../passes/basis/basis_translator.py | 3 ++ .../optimization/commutation_analysis.py | 4 ++- .../echo_rzx_weyl_decomposition.py | 1 + .../template_matching/backward_match.py | 9 ++++++ .../template_matching/forward_match.py | 5 ++++ .../template_matching/template_matching.py | 1 + .../template_substitution.py | 3 ++ .../passes/routing/algorithms/bip_model.py | 30 +++++++++---------- .../transpiler/passes/routing/bip_mapping.py | 2 +- .../commuting_2q_gate_router.py | 1 + .../pauli_2q_evolution_commutation.py | 1 + .../swap_strategy.py | 1 + .../scheduling/alignments/reschedule.py | 1 + .../synthesis/solovay_kitaev_synthesis.py | 1 + .../passes/synthesis/unitary_synthesis.py | 1 + .../barrier_before_final_measurements.py | 1 + .../passes/utils/merge_adjacent_barriers.py | 3 ++ .../transpiler/preset_passmanagers/level1.py | 1 - .../transpiler/preset_passmanagers/level2.py | 1 - .../transpiler/preset_passmanagers/level3.py | 1 - qiskit/transpiler/synthesis/aqc/aqc_plugin.py | 1 + qiskit/utils/mitigation/_filters.py | 5 ++++ qiskit/utils/mitigation/circuits.py | 2 ++ qiskit/utils/mitigation/fitters.py | 2 ++ qiskit/utils/run_circuits.py | 1 + qiskit/visualization/bloch.py | 2 ++ qiskit/visualization/circuit/matplotlib.py | 1 + qiskit/visualization/circuit/text.py | 1 + qiskit/visualization/gate_map.py | 1 + .../pass_manager_visualization.py | 1 + qiskit/visualization/pulse_v2/core.py | 1 + .../keep-initial-resets-a5f75cb16c8edb57.yaml | 6 ---- .../minimum_eigensolvers/test_vqe.py | 1 - .../algorithms/test_aux_ops_evaluator.py | 1 + .../test_measure_error_mitigation.py | 1 + .../python/algorithms/test_phase_estimator.py | 1 + test/python/algorithms/test_qaoa.py | 1 + .../circuit/library/test_linear_function.py | 1 + test/python/circuit/test_gate_definitions.py | 1 - test/python/circuit/test_random_circuit.py | 2 +- test/python/opflow/test_gradients.py | 2 ++ test/python/opflow/test_matrix_expectation.py | 1 + .../python/opflow/test_state_op_meas_evals.py | 1 + .../primitives/test_backend_estimator.py | 2 ++ .../python/primitives/test_backend_sampler.py | 2 ++ .../quantum_info/states/test_densitymatrix.py | 12 ++++++++ .../quantum_info/states/test_statevector.py | 12 ++++++++ .../aqc/fast_gradient/test_layer1q.py | 2 ++ .../aqc/fast_gradient/test_layer2q.py | 2 ++ .../aqc/fast_gradient/test_utils.py | 1 + .../test_echo_rzx_weyl_decomposition.py | 1 + test/python/utils/mitigation/test_meas.py | 1 + 111 files changed, 202 insertions(+), 64 deletions(-) delete mode 100644 releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml diff --git a/qiskit/algorithms/algorithm_result.py b/qiskit/algorithms/algorithm_result.py index a19b4dbff956..0804303a4ef6 100644 --- a/qiskit/algorithms/algorithm_result.py +++ b/qiskit/algorithms/algorithm_result.py @@ -31,6 +31,7 @@ def __str__(self) -> str: and not inspect.isfunction(value) and hasattr(self, name) ): + result[name] = value return pprint.pformat(result, indent=4) diff --git a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py index 94196da139a9..6b0536330441 100644 --- a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py @@ -176,6 +176,7 @@ def _get_energies( def _eval_aux_operators( aux_operators: ListOrDict[OperatorBase], wavefn, threshold: float = 1e-12 ) -> ListOrDict[tuple[complex, complex]]: + values: ListOrDict[tuple[complex, complex]] # As a list, aux_operators can contain None operators for which None values are returned. @@ -240,6 +241,7 @@ def compute_eigenvalues( # if a filter is set, loop over the given values and only keep if self._filter_criterion: + eigvecs = [] eigvals = [] aux_ops = [] diff --git a/qiskit/algorithms/eigen_solvers/vqd.py b/qiskit/algorithms/eigen_solvers/vqd.py index 1478c23f6ec9..72e3dd306647 100644 --- a/qiskit/algorithms/eigen_solvers/vqd.py +++ b/qiskit/algorithms/eigen_solvers/vqd.py @@ -572,6 +572,7 @@ def compute_eigenvalues( aux_values = [] for step in range(1, self.k + 1): + self._eval_count = 0 energy_evaluation, expectation = self.get_energy_evaluation( step, operator, return_expectation=True, prev_states=result.optimal_parameters @@ -626,6 +627,7 @@ def compute_eigenvalues( aux_values.append(aux_value) if step == 1: + logger.info( "Ground state optimization complete in %s seconds.\n" "Found opt_params %s in %s evals", @@ -664,10 +666,9 @@ def get_energy_evaluation( operator: OperatorBase, return_expectation: bool = False, prev_states: list[np.ndarray] | None = None, - ) -> ( - Callable[[np.ndarray], float | list[float]] - | tuple[Callable[[np.ndarray], float | list[float]], ExpectationBase] - ): + ) -> Callable[[np.ndarray], float | list[float]] | tuple[ + Callable[[np.ndarray], float | list[float]], ExpectationBase + ]: """Returns a function handle to evaluates the energy at given parameters for the ansatz. This return value is the objective function to be passed to the optimizer for evaluation. @@ -713,6 +714,7 @@ def get_energy_evaluation( ) for state in range(step - 1): + prev_circ = self.ansatz.bind_parameters(prev_states[state]) overlap_op.append(~CircuitStateFn(prev_circ) @ CircuitStateFn(self.ansatz)) diff --git a/qiskit/algorithms/eigensolvers/numpy_eigensolver.py b/qiskit/algorithms/eigensolvers/numpy_eigensolver.py index 457fe3fdbdad..954292ecc5d0 100644 --- a/qiskit/algorithms/eigensolvers/numpy_eigensolver.py +++ b/qiskit/algorithms/eigensolvers/numpy_eigensolver.py @@ -172,6 +172,7 @@ def _eval_aux_operators( wavefn: np.ndarray, threshold: float = 1e-12, ) -> ListOrDict[tuple[complex, complex]]: + values: ListOrDict[tuple[complex, complex]] # As a list, aux_operators can contain None operators for which None values are returned. @@ -231,6 +232,7 @@ def compute_eigenvalues( operator: BaseOperator | PauliSumOp, aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, ) -> NumPyEigensolverResult: + super().compute_eigenvalues(operator, aux_operators) if operator.num_qubits is None or operator.num_qubits < 1: diff --git a/qiskit/algorithms/gradients/reverse/bind.py b/qiskit/algorithms/gradients/reverse/bind.py index bc745eb99573..5380090b7425 100644 --- a/qiskit/algorithms/gradients/reverse/bind.py +++ b/qiskit/algorithms/gradients/reverse/bind.py @@ -17,7 +17,6 @@ from qiskit.circuit import QuantumCircuit, Parameter - # pylint: disable=inconsistent-return-statements def bind( circuits: QuantumCircuit | Iterable[QuantumCircuit], diff --git a/qiskit/algorithms/minimum_eigen_solvers/vqe.py b/qiskit/algorithms/minimum_eigen_solvers/vqe.py index f34359699a64..bf9304e4d6b7 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/vqe.py +++ b/qiskit/algorithms/minimum_eigen_solvers/vqe.py @@ -582,10 +582,9 @@ def get_energy_evaluation( self, operator: OperatorBase, return_expectation: bool = False, - ) -> ( - Callable[[np.ndarray], float | list[float]] - | tuple[Callable[[np.ndarray], float | list[float]], ExpectationBase] - ): + ) -> Callable[[np.ndarray], float | list[float]] | tuple[ + Callable[[np.ndarray], float | list[float]], ExpectationBase + ]: """Returns a function handle to evaluates the energy at given parameters for the ansatz. This is the objective function to be passed to the optimizer that is used for evaluation. diff --git a/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py b/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py index 9a8ee66c381f..2fb60355b2a5 100644 --- a/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py +++ b/qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py @@ -258,10 +258,9 @@ def _get_evaluate_energy( operator: BaseOperator | PauliSumOp, ansatz: QuantumCircuit, return_best_measurement: bool = False, - ) -> ( - Callable[[np.ndarray], np.ndarray | float] - | tuple[Callable[[np.ndarray], np.ndarray | float], dict[str, Any]] - ): + ) -> Callable[[np.ndarray], np.ndarray | float] | tuple[ + Callable[[np.ndarray], np.ndarray | float], dict[str, Any] + ]: """Returns a function handle to evaluate the energy at given parameters. This is the objective function to be passed to the optimizer that is used for evaluation. diff --git a/qiskit/algorithms/optimizers/adam_amsgrad.py b/qiskit/algorithms/optimizers/adam_amsgrad.py index 326887ae0c9c..422aa17a5f01 100644 --- a/qiskit/algorithms/optimizers/adam_amsgrad.py +++ b/qiskit/algorithms/optimizers/adam_amsgrad.py @@ -113,6 +113,7 @@ def __init__( self._v_eff = np.zeros(1) if self._snapshot_dir: + with open(os.path.join(self._snapshot_dir, "adam_params.csv"), mode="w") as csv_file: if self._amsgrad: fieldnames = ["v", "v_eff", "m", "t"] diff --git a/qiskit/algorithms/optimizers/aqgd.py b/qiskit/algorithms/optimizers/aqgd.py index 9464f040b55d..bedc52301f34 100644 --- a/qiskit/algorithms/optimizers/aqgd.py +++ b/qiskit/algorithms/optimizers/aqgd.py @@ -314,7 +314,7 @@ def minimize( epoch = 0 converged = False - for eta, mom_coeff in zip(self._eta, self._momenta_coeff): + for (eta, mom_coeff) in zip(self._eta, self._momenta_coeff): logger.info("Epoch: %4d | Stepsize: %6.4f | Momentum: %6.4f", epoch, eta, mom_coeff) sum_max_iters = sum(self._maxiter[0 : epoch + 1]) diff --git a/qiskit/algorithms/optimizers/gradient_descent.py b/qiskit/algorithms/optimizers/gradient_descent.py index a2d3e228cadd..03911c21c012 100644 --- a/qiskit/algorithms/optimizers/gradient_descent.py +++ b/qiskit/algorithms/optimizers/gradient_descent.py @@ -365,6 +365,7 @@ def start( jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> None: + self.state = GradientDescentState( fun=fun, jac=jac, diff --git a/qiskit/algorithms/optimizers/gsls.py b/qiskit/algorithms/optimizers/gsls.py index 31714a5396c4..6c1446f879cb 100644 --- a/qiskit/algorithms/optimizers/gsls.py +++ b/qiskit/algorithms/optimizers/gsls.py @@ -179,6 +179,7 @@ def ls_optimize( x_value = obj_fun(x) n_evals += 1 while iter_count < self._options["maxiter"] and n_evals < self._options["max_eval"]: + # Determine set of sample points directions, sample_set_x = self.sample_set(n, x, var_lb, var_ub, sample_set_size) diff --git a/qiskit/algorithms/optimizers/nft.py b/qiskit/algorithms/optimizers/nft.py index 872dc0e86bd3..2a7503137daf 100644 --- a/qiskit/algorithms/optimizers/nft.py +++ b/qiskit/algorithms/optimizers/nft.py @@ -120,6 +120,7 @@ def nakanishi_fujii_todo( funcalls = 0 while True: + idx = niter % x0.size if reset_interval > 0: diff --git a/qiskit/algorithms/optimizers/umda.py b/qiskit/algorithms/optimizers/umda.py index f0b6e628ee9d..dd8739c2fac1 100644 --- a/qiskit/algorithms/optimizers/umda.py +++ b/qiskit/algorithms/optimizers/umda.py @@ -213,6 +213,7 @@ def minimize( jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> OptimizerResult: + not_better_count = 0 result = OptimizerResult() diff --git a/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py b/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py index 5bf1a4fe6715..87907c39e304 100644 --- a/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py +++ b/qiskit/algorithms/phase_estimators/hamiltonian_phase_estimation.py @@ -140,6 +140,7 @@ def _get_unitary( """ if self._phase_estimation._sampler is not None: + evo = PauliEvolutionGate(hamiltonian, -pe_scale.scale, synthesis=evolution) unitary = QuantumCircuit(evo.num_qubits) unitary.append(evo, unitary.qubits) diff --git a/qiskit/algorithms/phase_estimators/ipe.py b/qiskit/algorithms/phase_estimators/ipe.py index 69d09f42910a..e8e583027a92 100644 --- a/qiskit/algorithms/phase_estimators/ipe.py +++ b/qiskit/algorithms/phase_estimators/ipe.py @@ -140,6 +140,7 @@ def _estimate_phase_iteratively(self, unitary, state_preparation): omega_coef /= 2 if self._sampler is not None: + qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True ) diff --git a/qiskit/algorithms/state_fidelities/base_state_fidelity.py b/qiskit/algorithms/state_fidelities/base_state_fidelity.py index 5a821a956de3..9395889bc5da 100644 --- a/qiskit/algorithms/state_fidelities/base_state_fidelity.py +++ b/qiskit/algorithms/state_fidelities/base_state_fidelity.py @@ -42,6 +42,7 @@ class BaseStateFidelity(ABC): """ def __init__(self) -> None: + # use cache for preventing unnecessary circuit compositions self._circuit_cache: Mapping[tuple[int, int], QuantumCircuit] = {} @@ -80,6 +81,7 @@ def _preprocess_values( ) return [[]] else: + # Support ndarray if isinstance(values, np.ndarray): values = values.tolist() @@ -166,7 +168,8 @@ def _construct_circuits( ) circuits = [] - for circuit_1, circuit_2 in zip(circuits_1, circuits_2): + for (circuit_1, circuit_2) in zip(circuits_1, circuits_2): + # TODO: improve caching, what if the circuit is modified without changing the id? circuit = self._circuit_cache.get((id(circuit_1), id(circuit_2))) @@ -223,7 +226,7 @@ def _construct_value_list( elif len(values_1[0]) == 0: values = list(values_2) else: - for val_1, val_2 in zip(values_1, values_2): + for (val_1, val_2) in zip(values_1, values_2): values.append(val_1 + val_2) return values diff --git a/qiskit/algorithms/time_evolvers/classical_methods/evolve.py b/qiskit/algorithms/time_evolvers/classical_methods/evolve.py index 5280c24ef7da..18c679a03c8f 100644 --- a/qiskit/algorithms/time_evolvers/classical_methods/evolve.py +++ b/qiskit/algorithms/time_evolvers/classical_methods/evolve.py @@ -97,6 +97,7 @@ def _evaluate_aux_ops( def _operator_to_matrix(operator: BaseOperator | PauliSumOp): + if isinstance(operator, PauliSumOp): op_matrix = operator.to_spmatrix() else: diff --git a/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py b/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py index 58eb1221ac79..b94ded552a81 100644 --- a/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py +++ b/qiskit/algorithms/time_evolvers/variational/solvers/ode/abstract_ode_function.py @@ -30,6 +30,7 @@ def __init__( param_dict: Mapping[Parameter, float], t_param: Parameter | None = None, ) -> None: + self._varqte_linear_solver = varqte_linear_solver self._param_dict = param_dict self._t_param = t_param diff --git a/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py b/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py index 89bb4a5ef604..d7a946b8ab70 100644 --- a/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py +++ b/qiskit/algorithms/time_evolvers/variational/variational_principles/real_mc_lachlan_principle.py @@ -150,6 +150,7 @@ def _construct_modified_hamiltonian(hamiltonian: BaseOperator, energy: float) -> @staticmethod def _validate_grad_settings(gradient): + if gradient is not None: if not hasattr(gradient, "_derivative_type"): raise ValueError( diff --git a/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py b/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py index 33128b7221ca..be16849155c4 100644 --- a/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py +++ b/qiskit/algorithms/time_evolvers/variational/variational_principles/variational_principle.py @@ -70,6 +70,7 @@ def metric_tensor( try: metric_tensor = self.qgt.run([ansatz], [param_values], [None]).result().qgts[0] except Exception as exc: + raise AlgorithmError("The QFI primitive job failed!") from exc return metric_tensor diff --git a/qiskit/assembler/assemble_schedules.py b/qiskit/assembler/assemble_schedules.py index af6b2537a2ea..6ddf4c140d56 100644 --- a/qiskit/assembler/assemble_schedules.py +++ b/qiskit/assembler/assemble_schedules.py @@ -222,6 +222,7 @@ def _assemble_instructions( acquire_instruction_map = defaultdict(list) for time, instruction in sched.instructions: + if isinstance(instruction, instructions.Play): if isinstance(instruction.pulse, (library.ParametricPulse, library.SymbolicPulse)): is_backend_supported = True diff --git a/qiskit/circuit/controlflow/while_loop.py b/qiskit/circuit/controlflow/while_loop.py index d2c9c5739136..98fefa3ce8c2 100644 --- a/qiskit/circuit/controlflow/while_loop.py +++ b/qiskit/circuit/controlflow/while_loop.py @@ -142,6 +142,7 @@ def __init__( *, label: str | None = None, ): + self._circuit = circuit self._condition = validate_condition(condition) self._label = label diff --git a/qiskit/circuit/library/arithmetic/integer_comparator.py b/qiskit/circuit/library/arithmetic/integer_comparator.py index c1ced2693ab5..699e8c221ff3 100644 --- a/qiskit/circuit/library/arithmetic/integer_comparator.py +++ b/qiskit/circuit/library/arithmetic/integer_comparator.py @@ -198,6 +198,7 @@ def _build(self) -> None: circuit.x(q_compare) # condition never satisfied for values larger than or equal to 2^n elif self.value < pow(2, self.num_state_qubits): + if self.num_state_qubits > 1: twos = self._get_twos_complement() for i in range(self.num_state_qubits): @@ -238,6 +239,7 @@ def _build(self) -> None: else: circuit.ccx(qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]) else: + # num_state_qubits == 1 and value == 1: circuit.cx(qr_state[0], q_compare) diff --git a/qiskit/circuit/library/n_local/n_local.py b/qiskit/circuit/library/n_local/n_local.py index f6134bba7766..aca3ea65bb3b 100644 --- a/qiskit/circuit/library/n_local/n_local.py +++ b/qiskit/circuit/library/n_local/n_local.py @@ -285,17 +285,9 @@ def entanglement_blocks( @property def entanglement( self, - ) -> ( - str - | list[str] - | list[list[str]] - | list[int] - | list[list[int]] - | list[list[list[int]]] - | list[list[list[list[int]]]] - | Callable[[int], str] - | Callable[[int], list[list[int]]] - ): + ) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[ + list[list[int]] + ] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]: """Get the entanglement strategy. Returns: diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 941d5f439db5..5a9e15c33f0e 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -556,6 +556,7 @@ def _expand_parameters(circuits, run_config): parameter_binds = run_config.parameter_binds if parameter_binds and any(parameter_binds) or any(circuit.parameters for circuit in circuits): + # Unroll params here in order to handle ParamVects all_bind_parameters = [ QuantumCircuit()._unroll_param_dict(bind).keys() for bind in parameter_binds diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py index b643c27bbda8..012b43db66ee 100644 --- a/qiskit/dagcircuit/dagcircuit.py +++ b/qiskit/dagcircuit/dagcircuit.py @@ -1777,6 +1777,7 @@ def layers(self): return for graph_layer in graph_layers: + # Get the op nodes from the layer, removing any input and output nodes. op_nodes = [node for node in graph_layer if isinstance(node, DAGOpNode)] diff --git a/qiskit/dagcircuit/dagdepnode.py b/qiskit/dagcircuit/dagdepnode.py index 8fdc82735129..0ac7be65f103 100644 --- a/qiskit/dagcircuit/dagdepnode.py +++ b/qiskit/dagcircuit/dagdepnode.py @@ -59,6 +59,7 @@ def __init__( cindices=None, nid=-1, ): + self.type = type self._op = op self.name = name diff --git a/qiskit/extensions/quantum_initializer/isometry.py b/qiskit/extensions/quantum_initializer/isometry.py index 2270a5e487f6..611413e9f56f 100644 --- a/qiskit/extensions/quantum_initializer/isometry.py +++ b/qiskit/extensions/quantum_initializer/isometry.py @@ -103,6 +103,7 @@ def __init__(self, isometry, num_ancillas_zero, num_ancillas_dirty, epsilon=_EPS super().__init__("isometry", num_qubits, 0, [isometry]) def _define(self): + # TODO The inverse().inverse() is because there is code to uncompute (_gates_to_uncompute) # an isometry, but not for generating its decomposition. It would be cheaper to do the # later here instead. @@ -291,6 +292,7 @@ def _append_mcg_up_to_diagonal(self, circ, q, gate, control_labels, target_label return mcg_up_to_diag._get_diagonal() def _define_qubit_role(self, q): + n = int(np.log2(self.iso_data.shape[0])) m = int(np.log2(self.iso_data.shape[1])) @@ -500,7 +502,7 @@ def _get_binary_rep_as_list(n, num_digits): def _merge_UCGate_and_diag(single_qubit_gates, diag): - for i, gate in enumerate(single_qubit_gates): + for (i, gate) in enumerate(single_qubit_gates): single_qubit_gates[i] = np.array([[diag[2 * i], 0.0], [0.0, diag[2 * i + 1]]]).dot(gate) return single_qubit_gates diff --git a/qiskit/extensions/quantum_initializer/uc_pauli_rot.py b/qiskit/extensions/quantum_initializer/uc_pauli_rot.py index ecb60351ed64..87a1b1fd3642 100644 --- a/qiskit/extensions/quantum_initializer/uc_pauli_rot.py +++ b/qiskit/extensions/quantum_initializer/uc_pauli_rot.py @@ -102,7 +102,7 @@ def _dec_ucrot(self): angles = self.params.copy() UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False) # Now, it is easy to place the C-NOT gates to get back the full decomposition. - for i, angle in enumerate(angles): + for (i, angle) in enumerate(angles): if self.rot_axes == "X": if np.abs(angle) > _EPS: circuit.rx(angle, q_target) diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index 9abf101bb8bb..e8e5938617e7 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -420,11 +420,13 @@ def resolve_param(inst_param): def _prepare_parameterized_run_config( self, param_bindings: List[Dict[Parameter, float]] ) -> List[Any]: + self.quantum_instance._run_config.parameterizations = [] if self._transpiled_circ_templates is None or len(self._transpiled_circ_templates) != len( self._transpiled_circ_cache ): + # temporally resolve parameters of self._transpiled_circ_cache # They will be overridden in Aer from the next iterations self._transpiled_circ_templates = [ diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 92e73a70de7b..58a72ed6daca 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -71,6 +71,7 @@ def build( # pylint: disable=cyclic-import primitives = operator.primitive_strings() if primitives in ({"Pauli"}, {"SparsePauliOp"}): + if backend_to_check is None: # If user has Aer but didn't specify a backend, use the Aer fast expectation if optionals.HAS_AER: diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 421b3a84b800..361d13112e85 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -212,6 +212,7 @@ def _prepare_operator( isinstance(params, list) and all(isinstance(param, ParameterExpression) for param in params) ): + return self._gradient_states( state_op, meas_op=(2 * meas), diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 34a52d18981c..71f4eea3d8c2 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -149,6 +149,7 @@ def convert( break for grad_coeff_i, grad_gate_i in zip(grad_coeffs_i, grad_gates_i): + # Get the gates of the quantum state which are parameterized by param_j param_gates_j = state_qc._parameter_table[param_j] for gate_j, idx_j in param_gates_j: @@ -162,6 +163,7 @@ def convert( break for grad_coeff_j, grad_gate_j in zip(grad_coeffs_j, grad_gates_j): + grad_coeff_ij = np.conj(grad_coeff_i) * grad_coeff_j qfi_circuit = LinComb.apply_grad_gate( state_qc, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index abb1e5bd05cf..3f630fe304b9 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -208,6 +208,7 @@ def apply_node_op(node, dag, back=True): # without becoming the descendant of a parameterized gate, # then do it. if not any(ledger[x] for x in indices): + apply_node_op(next_node, layer) next_layer.remove_op_node(next_node) @@ -249,6 +250,7 @@ def _get_generators(params, circuit): for param in params: if param in param_value.parameters: + if isinstance(instr, RYGate): generator = Y elif isinstance(instr, RZGate): diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index 87e750a882e9..f9762da93e41 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -171,6 +171,7 @@ def is_coeff_c_abs(coeff, c): # circuits were applied. Additionally, all coefficients within ComposedOps were collected # and moved out front. if isinstance(operator, ComposedOp): + # Gradient of an expectation value if not is_coeff_c_abs(operator._coeff, 1.0): raise OpflowError( diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 04c4e4977141..3ec39f5674ca 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -191,6 +191,7 @@ def is_coeff_c(coeff, c): # circuits were applied. Additionally, all coefficients within ComposedOps were collected # and moved out front. if isinstance(operator, ComposedOp): + if not is_coeff_c(operator.coeff, 1.0): raise OpflowError( "Operator pre-processing failed. Coefficients were not properly " diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index f8147280b0a5..b09f9170dbad 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -20,6 +20,7 @@ class QFIBase(DerivativeBase): + r"""Deprecated: Base class for Quantum Fisher Information (QFI). Compute the Quantum Fisher Information (QFI) given a pure, parameterized quantum state. diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index 1ef9f2db1d1f..d47a81fbd796 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -111,6 +111,7 @@ def adjoint(self) -> "ComposedOp": def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: + new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(ComposedOp, new_self) diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index 9d655da80237..abf2d2326d0c 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -335,6 +335,7 @@ def permute(self, permutation: List[int]) -> "OperatorBase": def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: + new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(ListOp, new_self) diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index 949ffad4f6c7..7c1e031d8620 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -396,7 +396,7 @@ def _unroll_param_dict( """Unrolls the ParameterVectors in a param_dict into separate Parameters, and unrolls parameterization value lists into separate param_dicts without list nesting.""" unrolled_value_dict = {} - for param, value in value_dict.items(): + for (param, value) in value_dict.items(): if isinstance(param, ParameterExpression): unrolled_value_dict[param] = value if isinstance(param, ParameterVector) and isinstance(value, (list, np.ndarray)): diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index b026f405fbd8..1a6104a4cac3 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -121,6 +121,7 @@ def tensor(self, other: OperatorBase) -> Union["CircuitOp", TensoredOp]: def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: + new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(CircuitOp, new_self) diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index 66f62348e1bc..be8c8ac90eec 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -131,6 +131,7 @@ def tensor(self, other: OperatorBase) -> Union["MatrixOp", TensoredOp]: def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: + new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(MatrixOp, new_self) diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index bea3c2c9c960..623608754671 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -153,6 +153,7 @@ def permute(self, permutation: List[int]) -> "PauliOp": def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: + new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(PauliOp, new_self) @@ -232,6 +233,7 @@ def eval( ) else: + if self.num_qubits != front.num_qubits: raise ValueError( "eval does not support operands with differing numbers of qubits, " @@ -239,6 +241,7 @@ def eval( ) if isinstance(front, DictStateFn): + new_dict: Dict[str, complex] = {} corrected_x_bits = self.primitive.x[::-1] corrected_z_bits = self.primitive.z[::-1] @@ -317,6 +320,7 @@ def exp_i(self) -> OperatorBase: return EvolvedOp(self) def to_circuit(self) -> QuantumCircuit: + pauli = self.primitive.to_label()[-self.num_qubits :] phase = self.primitive.phase diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index a41b17eb0ad8..b1bb9b7242a9 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -231,6 +231,7 @@ def compose( permutation: Optional[List[int]] = None, front: bool = False, ) -> OperatorBase: + new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(PauliSumOp, new_self) @@ -317,6 +318,7 @@ def eval( ) else: + if self.num_qubits != front.num_qubits: raise ValueError( "eval does not support operands with differing numbers of qubits, " diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index b509a210cc28..9411afc71f26 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -273,6 +273,7 @@ def find_Z2_symmetries(cls, operator: PauliSumOp) -> "Z2Symmetries": symm_shape = stacked_symmetries.shape for row in range(symm_shape[0]): + pauli_symmetries.append( Pauli( ( diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index 7ae96434bd22..3f23f89a1cee 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -102,7 +102,7 @@ def from_dict(density_dict: dict) -> "CircuitStateFn": for bstr, prob in density_dict.items(): qc = QuantumCircuit(len(bstr)) # NOTE: Reversing endianness!! - for index, bit in enumerate(reversed(bstr)): + for (index, bit) in enumerate(reversed(bstr)): if bit == "1": qc.x(index) sf_circuit = CircuitStateFn(qc, coeff=prob) diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index 7dbc4e92862d..40c77f9e9a6b 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -231,6 +231,7 @@ def _call( parameter_values: Sequence[Sequence[float]], **run_options, ) -> EstimatorResult: + # Transpile self._grouping = list(zip(circuits, observables)) transpiled_circuits = self.transpiled_circuits @@ -360,6 +361,7 @@ def _postprocessing( shots_list = [] for i, j in zip(accum, accum[1:]): + combined_expval = 0.0 combined_var = 0.0 diff --git a/qiskit/primitives/backend_sampler.py b/qiskit/primitives/backend_sampler.py index 41df0edd7e2c..6d7f16173980 100644 --- a/qiskit/primitives/backend_sampler.py +++ b/qiskit/primitives/backend_sampler.py @@ -134,6 +134,7 @@ def _call( parameter_values: Sequence[Sequence[float]], **run_options, ) -> SamplerResult: + # This line does the actual transpilation transpiled_circuits = self.transpiled_circuits bound_circuits = [ diff --git a/qiskit/providers/fake_provider/utils/configurable_backend.py b/qiskit/providers/fake_provider/utils/configurable_backend.py index 03c00bf3384b..a3dd72eed97a 100644 --- a/qiskit/providers/fake_provider/utils/configurable_backend.py +++ b/qiskit/providers/fake_provider/utils/configurable_backend.py @@ -155,7 +155,7 @@ def _build_props(self) -> BackendProperties: qubits = [] gates = [] - for qubit_t1, qubit_t2, freq, read_err in zip( + for (qubit_t1, qubit_t2, freq, read_err) in zip( self.qubit_t1, self.qubit_t2, self.qubit_frequency, self.qubit_readout_error ): qubits.append( @@ -184,7 +184,7 @@ def _build_props(self) -> BackendProperties: ) ) elif gate == "cx": - for qubit1, qubit2 in list(itertools.combinations(range(self.n_qubits), 2)): + for (qubit1, qubit2) in list(itertools.combinations(range(self.n_qubits), 2)): gates.append( Gate( gate=gate, @@ -212,7 +212,7 @@ def _build_conf(self) -> PulseBackendConfiguration: ",".join([f"_SUM[i,0,{self.n_qubits}", "omegad{i}*X{i}||D{i}]"]), ] variables = [] - for qubit1, qubit2 in self.coupling_map: + for (qubit1, qubit2) in self.coupling_map: h_str += [ "jq{q1}q{q2}*Sp{q1}*Sm{q2}".format(q1=qubit1, q2=qubit2), "jq{q1}q{q2}*Sm{q1}*Sp{q2}".format(q1=qubit1, q2=qubit2), diff --git a/qiskit/pulse/library/symbolic_pulses.py b/qiskit/pulse/library/symbolic_pulses.py index 256729db1bc4..8c90777eae01 100644 --- a/qiskit/pulse/library/symbolic_pulses.py +++ b/qiskit/pulse/library/symbolic_pulses.py @@ -544,6 +544,7 @@ def parameters(self) -> Dict[str, Any]: return params def __eq__(self, other: "SymbolicPulse") -> bool: + if not isinstance(other, SymbolicPulse): return NotImplemented diff --git a/qiskit/pulse/macros.py b/qiskit/pulse/macros.py index 5530e0baddc9..f45d94bbeb98 100644 --- a/qiskit/pulse/macros.py +++ b/qiskit/pulse/macros.py @@ -64,6 +64,7 @@ def measure( # backend is V2. if isinstance(backend, BackendV2): + return _measure_v2( qubits=qubits, target=backend.target, diff --git a/qiskit/pulse/schedule.py b/qiskit/pulse/schedule.py index fac36891b56b..6643a03d1a31 100644 --- a/qiskit/pulse/schedule.py +++ b/qiskit/pulse/schedule.py @@ -580,6 +580,7 @@ def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: + if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") diff --git a/qiskit/quantum_info/synthesis/qsd.py b/qiskit/quantum_info/synthesis/qsd.py index cd33a5058086..b2f00a56045d 100644 --- a/qiskit/quantum_info/synthesis/qsd.py +++ b/qiskit/quantum_info/synthesis/qsd.py @@ -214,7 +214,7 @@ def _get_ucry_cz(nqubits, angles): else: angles = angles.copy() UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False) - for i, angle in enumerate(angles): + for (i, angle) in enumerate(angles): if np.abs(angle) > _EPS: qc.ry(angle, q_target) if not i == len(angles) - 1: diff --git a/qiskit/quantum_info/synthesis/xx_decompose/circuits.py b/qiskit/quantum_info/synthesis/xx_decompose/circuits.py index e7218fe20188..c0f2671f42f9 100644 --- a/qiskit/quantum_info/synthesis/xx_decompose/circuits.py +++ b/qiskit/quantum_info/synthesis/xx_decompose/circuits.py @@ -169,6 +169,7 @@ def xx_circuit_step(source, strength, target, embodiment): # check for overlap, back out permutation source_shared, target_shared = None, None for i, j in [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]: + if ( abs(np.mod(abs(shifted_source_coord[i] - target[j]), np.pi)) < EPSILON or abs(np.mod(abs(shifted_source_coord[i] - target[j]), np.pi) - np.pi) diff --git a/qiskit/synthesis/clifford/clifford_decompose_bm.py b/qiskit/synthesis/clifford/clifford_decompose_bm.py index 40efa424da34..5c4c3bcee5a3 100644 --- a/qiskit/synthesis/clifford/clifford_decompose_bm.py +++ b/qiskit/synthesis/clifford/clifford_decompose_bm.py @@ -155,6 +155,7 @@ def _reduce_cost(clifford, inv_circuit, cost): for qubit0 in range(num_qubits): for qubit1 in range(qubit0 + 1, num_qubits): for n0, n1 in product(range(3), repeat=2): + # Apply a 2-qubit block reduced = clifford.copy() for qubit, n in [(qubit0, n0), (qubit1, n1)]: diff --git a/qiskit/synthesis/clifford/clifford_decompose_greedy.py b/qiskit/synthesis/clifford/clifford_decompose_greedy.py index ba14285b1848..b0d7f60c4736 100644 --- a/qiskit/synthesis/clifford/clifford_decompose_greedy.py +++ b/qiskit/synthesis/clifford/clifford_decompose_greedy.py @@ -219,6 +219,7 @@ def _calc_decoupling(pauli_x, pauli_z, qubit_list, min_qubit, num_qubits, cliff) # Reduce the pair of Paulis to a representative in the equivalence class # ['XZ', 'XX', 'XI', 'IZ', 'II'] by adding single-qubit gates for qubit in qubit_list: + typeq = _from_pair_paulis_to_type(pauli_x, pauli_z, qubit) if typeq in [ diff --git a/qiskit/tools/jupyter/backend_monitor.py b/qiskit/tools/jupyter/backend_monitor.py index 5d5321c906c0..ecb401521caf 100644 --- a/qiskit/tools/jupyter/backend_monitor.py +++ b/qiskit/tools/jupyter/backend_monitor.py @@ -480,6 +480,7 @@ def job_history(backend): def _build_job_history(tabs, backend): + past_year_date = datetime.datetime.now() - datetime.timedelta(days=365) date_filter = {"creationDate": {"gt": past_year_date.isoformat()}} jobs = backend.jobs(limit=None, db_filter=date_filter) diff --git a/qiskit/tools/jupyter/watcher_monitor.py b/qiskit/tools/jupyter/watcher_monitor.py index 51a4637aea3f..7d12dfc9bd03 100644 --- a/qiskit/tools/jupyter/watcher_monitor.py +++ b/qiskit/tools/jupyter/watcher_monitor.py @@ -51,6 +51,7 @@ def _job_checker(job, status, watcher): if status.name == "QUEUED": queue_pos = job.queue_position() if queue_pos != prev_queue_pos: + update_info = (job.job_id(), status.name, queue_pos, status.value) watcher.update_single_job(update_info) diff --git a/qiskit/transpiler/instruction_durations.py b/qiskit/transpiler/instruction_durations.py index ed261b53ef78..d1611840a040 100644 --- a/qiskit/transpiler/instruction_durations.py +++ b/qiskit/transpiler/instruction_durations.py @@ -130,6 +130,7 @@ def update(self, inst_durations: "InstructionDurationsType" | None, dt: float = ) else: for i, items in enumerate(inst_durations): + if not isinstance(items[-1], str): items = (*items, "dt") # set default unit diff --git a/qiskit/transpiler/passes/basis/basis_translator.py b/qiskit/transpiler/passes/basis/basis_translator.py index 19043fedc49c..5383f940c255 100644 --- a/qiskit/transpiler/passes/basis/basis_translator.py +++ b/qiskit/transpiler/passes/basis/basis_translator.py @@ -587,6 +587,7 @@ def _compose_transforms(basis_transforms, source_basis, source_dag): ] if doomed_nodes and logger.isEnabledFor(logging.DEBUG): + logger.debug( "Updating transform for mapped instr %s %s from \n%s", mapped_instr_name, @@ -595,6 +596,7 @@ def _compose_transforms(basis_transforms, source_basis, source_dag): ) for node in doomed_nodes: + replacement = equiv.assign_parameters( dict(zip_longest(equiv_params, node.op.params)) ) @@ -604,6 +606,7 @@ def _compose_transforms(basis_transforms, source_basis, source_dag): dag.substitute_node_with_dag(node, replacement_dag) if doomed_nodes and logger.isEnabledFor(logging.DEBUG): + logger.debug( "Updated transform for mapped instr %s %s to\n%s", mapped_instr_name, diff --git a/qiskit/transpiler/passes/optimization/commutation_analysis.py b/qiskit/transpiler/passes/optimization/commutation_analysis.py index 2234fbf169dd..b35a88a23dff 100644 --- a/qiskit/transpiler/passes/optimization/commutation_analysis.py +++ b/qiskit/transpiler/passes/optimization/commutation_analysis.py @@ -55,12 +55,14 @@ def run(self, dag): # Add edges to the dictionary for each qubit for node in dag.topological_op_nodes(): - for _, _, edge_wire in dag.edges(node): + for (_, _, edge_wire) in dag.edges(node): self.property_set["commutation_set"][(node, edge_wire)] = -1 # Construct the commutation set for wire in dag.wires: + for current_gate in dag.nodes_on_wire(wire): + current_comm_set = self.property_set["commutation_set"][wire] if not current_comm_set: current_comm_set.append([current_gate]) diff --git a/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py b/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py index 17eb0f9da7d9..5f4be27d220e 100644 --- a/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py +++ b/qiskit/transpiler/passes/optimization/echo_rzx_weyl_decomposition.py @@ -136,6 +136,7 @@ def run(self, dag: DAGCircuit): decomposer = TwoQubitControlledUDecomposer(RZXGate) for node in dag.two_qubit_ops(): + unitary = Operator(node.op).data dag_weyl = circuit_to_dag(decomposer(unitary)) dag.substitute_node_with_dag(node, dag_weyl) diff --git a/qiskit/transpiler/passes/optimization/template_matching/backward_match.py b/qiskit/transpiler/passes/optimization/template_matching/backward_match.py index 920f2b80a065..a4b11a33de2d 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/backward_match.py +++ b/qiskit/transpiler/passes/optimization/template_matching/backward_match.py @@ -256,6 +256,7 @@ def _is_same_q_conf(self, node_circuit, node_template, qarg_circuit): """ # If the gate is controlled, then the control qubits have to be compared as sets. if isinstance(node_circuit.op, ControlledGate): + c_template = node_template.op.num_ctrl_qubits if c_template == 1: @@ -266,6 +267,7 @@ def _is_same_q_conf(self, node_circuit, node_template, qarg_circuit): control_qubits_circuit = qarg_circuit[:c_template] if set(control_qubits_circuit) == set(control_qubits_template): + target_qubits_template = node_template.qindices[c_template::] target_qubits_circuit = qarg_circuit[c_template::] @@ -422,6 +424,7 @@ def run_backward_match(self): # While the scenario stack is not empty. while self.matching_list.matching_scenarios_list: + # If parameters are given, the heuristics is applied. if self.heuristics_backward_param: self._backward_heuristics( @@ -487,6 +490,7 @@ def run_backward_match(self): # Loop over the template candidates. for template_id in candidates_indices: + node_template = self.template_dag_dep.get_node(template_id) qarg2 = self.template_dag_dep.get_node(template_id).qindices @@ -505,6 +509,7 @@ def run_backward_match(self): and self._is_same_c_conf(node_circuit, node_template, carg1) and self._is_same_op(node_circuit, node_template) ): + # If there is a match the attributes are copied. circuit_matched_match = circuit_matched.copy() circuit_blocked_match = circuit_blocked.copy() @@ -620,6 +625,7 @@ def run_backward_match(self): # Third option: if blocking the succesors breaks a match, we consider # also the possibility to block all predecessors (push the gate to the left). if broken_matches and all(global_broken): + circuit_matched_block_p = circuit_matched.copy() circuit_blocked_block_p = circuit_blocked.copy() @@ -645,6 +651,7 @@ def run_backward_match(self): # If there is no match then there are three options. if not global_match: + circuit_blocked[circuit_id] = True following_matches = [] @@ -659,6 +666,7 @@ def run_backward_match(self): predecessors = self.circuit_dag_dep.get_node(circuit_id).predecessors if not predecessors or not following_matches: + matching_scenario = MatchingScenarios( circuit_matched, circuit_blocked, @@ -670,6 +678,7 @@ def run_backward_match(self): self.matching_list.append_scenario(matching_scenario) else: + circuit_matched_nomatch = circuit_matched.copy() circuit_blocked_nomatch = circuit_blocked.copy() diff --git a/qiskit/transpiler/passes/optimization/template_matching/forward_match.py b/qiskit/transpiler/passes/optimization/template_matching/forward_match.py index d3a8ef589d5e..6c5380539701 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/forward_match.py +++ b/qiskit/transpiler/passes/optimization/template_matching/forward_match.py @@ -268,6 +268,7 @@ def _is_same_q_conf(self, node_circuit, node_template): """ if isinstance(node_circuit.op, ControlledGate): + c_template = node_template.op.num_ctrl_qubits if c_template == 1: @@ -278,6 +279,7 @@ def _is_same_q_conf(self, node_circuit, node_template): control_qubits_circuit = self.qarg_indices[:c_template] if set(control_qubits_circuit) == set(control_qubits_template): + target_qubits_template = node_template.qindices[c_template::] target_qubits_circuit = self.qarg_indices[c_template::] @@ -345,6 +347,7 @@ def run_forward_match(self): # While the list of matched nodes is not empty while self.matched_nodes_list: + # Return first element of the matched_nodes_list and removes it from the list v_first = self._get_node_forward(0) self._remove_node_forward(0) @@ -383,6 +386,7 @@ def run_forward_match(self): # For loop over the candidates (template) to find a match. for i in self.candidates: + # Break the for loop if a match is found. if match: break @@ -407,6 +411,7 @@ def run_forward_match(self): and self._is_same_c_conf(node_circuit, node_template) and self._is_same_op(node_circuit, node_template) ): + v[1].matchedwith = [i] self.template_dag_dep.get_node(i).matchedwith = [label] diff --git a/qiskit/transpiler/passes/optimization/template_matching/template_matching.py b/qiskit/transpiler/passes/optimization/template_matching/template_matching.py index 62410ada7893..29b65f8e7380 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/template_matching.py +++ b/qiskit/transpiler/passes/optimization/template_matching/template_matching.py @@ -256,6 +256,7 @@ def run_template_matching(self): if self.circuit_dag_dep.get_node(circuit_index).op.soft_compare( self.template_dag_dep.get_node(template_index).op ): + qarg_c = self.circuit_dag_dep.get_node(circuit_index).qindices carg_c = self.circuit_dag_dep.get_node(circuit_index).cindices diff --git a/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py b/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py index f6f1bfdc8739..5e020fd03a30 100644 --- a/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py +++ b/qiskit/transpiler/passes/optimization/template_matching/template_substitution.py @@ -253,6 +253,7 @@ def _permutation(self): index = self.substitution_list.index(scenario) for scenario_b in self.substitution_list[index::]: if set(scenario_b.circuit_config) & predecessors: + index1 = self.substitution_list.index(scenario) index2 = self.substitution_list.index(scenario_b) @@ -305,6 +306,7 @@ def _substitution(self): """ while self.match_stack: + # Get the first match scenario of the list current = self.match_stack.pop(0) @@ -384,6 +386,7 @@ def run_dag_opt(self): if self.substitution_list: # Loop over the different matches. for group in self.substitution_list: + circuit_sub = group.circuit_config template_inverse = group.template_config diff --git a/qiskit/transpiler/passes/routing/algorithms/bip_model.py b/qiskit/transpiler/passes/routing/algorithms/bip_model.py index 8deedd11a17d..972cf8242918 100644 --- a/qiskit/transpiler/passes/routing/algorithms/bip_model.py +++ b/qiskit/transpiler/passes/routing/algorithms/bip_model.py @@ -211,8 +211,8 @@ def create_cpx_problem( # Add y variables y = {} for t in range(self.depth): - for (p, q), _ in self.gates[t]: - for i, j in self._arcs: + for ((p, q), _) in self.gates[t]: + for (i, j) in self._arcs: y[t, p, q, i, j] = mdl.binary_var(name=f"y_{t}_{p}_{q}_{i}_{j}") # Add x variables x = {} @@ -239,15 +239,15 @@ def create_cpx_problem( ) # Each gate must be implemented for t in range(self.depth): - for (p, q), _ in self.gates[t]: + for ((p, q), _) in self.gates[t]: mdl.add_constraint( sum(y[t, p, q, i, j] for (i, j) in self._arcs) == 1, ctname=f"implement_gate_{p}_{q}_at_{t}", ) # Gate can be implemented iff both of its qubits are located at the associated nodes for t in range(self.depth - 1): - for (p, q), _ in self.gates[t]: - for i, j in self._arcs: + for ((p, q), _) in self.gates[t]: + for (i, j) in self._arcs: # Apply McCormick to y[t, p, q, i, j] == w[t, p, i] * w[t, q, j] mdl.add_constraint( y[t, p, q, i, j] >= w[t, p, i] + w[t, q, j] - 1, @@ -264,8 +264,8 @@ def create_cpx_problem( ctname=f"McCormickUB2_{p}_{q}_{i}_{j}_at_{t}", ) # For last time step, use regular McCormick - for (p, q), _ in self.gates[self.depth - 1]: - for i, j in self._arcs: + for ((p, q), _) in self.gates[self.depth - 1]: + for (i, j) in self._arcs: # Apply McCormick to y[self.depth - 1, p, q, i, j] # == w[self.depth - 1, p, i] * w[self.depth - 1, q, j] mdl.add_constraint( @@ -302,18 +302,18 @@ def create_cpx_problem( ) # If a gate is implemented, involved qubits cannot swap with other positions for t in range(self.depth - 1): - for (p, q), _ in self.gates[t]: - for i, j in self._arcs: + for ((p, q), _) in self.gates[t]: + for (i, j) in self._arcs: mdl.add_constraint( x[t, p, i, j] == x[t, q, j, i], ctname=f"swap_{p}_{q}_{i}_{j}_at_{t}" ) # Qubit not in gates can flip with their neighbors for t in range(self.depth - 1): q_no_gate = list(range(self.num_vqubits)) - for (p, q), _ in self.gates[t]: + for ((p, q), _) in self.gates[t]: q_no_gate.remove(p) q_no_gate.remove(q) - for i, j in self._arcs: + for (i, j) in self._arcs: mdl.add_constraint( sum(x[t, q, i, j] for q in q_no_gate) == sum(x[t, p, j, i] for p in q_no_gate), ctname=f"swap_no_gate_{i}_{j}_at_{t}", @@ -356,7 +356,7 @@ def create_cpx_problem( objexr = sum(z[t] for t in range(self.depth) if self._is_dummy_step(t)) for t in range(self.depth - 1): for q in range(self.num_vqubits): - for i, j in self._arcs: + for (i, j) in self._arcs: objexr += 0.01 * x[t, q, i, j] mdl.minimize(objexr) elif objective in ("gate_error", "balanced"): @@ -364,7 +364,7 @@ def create_cpx_problem( objexr = 0 for t in range(self.depth - 1): for (p, q), node in self.gates[t]: - for i, j in self._arcs: + for (i, j) in self._arcs: # We pay the cost for gate implementation. pbest_fid = -np.log(self._max_expected_fidelity(node, i, j)) objexr += y[t, p, q, i, j] * pbest_fid @@ -381,7 +381,7 @@ def create_cpx_problem( objexr += x[t, q, i, j] * -3 / 2 * np.log(self._cx_fidelity(i, j)) # Cost for the last layer (x variables are not defined for depth-1) for (p, q), node in self.gates[self.depth - 1]: - for i, j in self._arcs: + for (i, j) in self._arcs: pbest_fid = -np.log(self._max_expected_fidelity(node, i, j)) objexr += y[self.depth - 1, p, q, i, j] * pbest_fid if objective == "balanced": @@ -488,7 +488,7 @@ def get_swaps(self, t: int) -> list: List of swaps (pairs of physical qubits (integers)) """ swaps = [] - for i, j in self._arcs: + for (i, j) in self._arcs: if i >= j: continue for q in range(self.num_vqubits): diff --git a/qiskit/transpiler/passes/routing/bip_mapping.py b/qiskit/transpiler/passes/routing/bip_mapping.py index a94c05236822..a658c1c98eaa 100644 --- a/qiskit/transpiler/passes/routing/bip_mapping.py +++ b/qiskit/transpiler/passes/routing/bip_mapping.py @@ -217,7 +217,7 @@ def run(self, dag): from_steps = max(interval * (su4dep - 1), 0) to_steps = min(interval * su4dep, model.depth - 1) for t in range(from_steps, to_steps): # pylint: disable=invalid-name - for i, j in model.get_swaps(t): + for (i, j) in model.get_swaps(t): mapped_dag.apply_operation_back( op=SwapGate(), qargs=[canonical_qreg[i], canonical_qreg[j]], diff --git a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py index a2cf7630e3db..60b5cf9e3ad3 100644 --- a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py +++ b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/commuting_2q_gate_router.py @@ -169,6 +169,7 @@ def run(self, dag: DAGCircuit) -> DAGCircuit: for node in dag.topological_op_nodes(): if isinstance(node.op, Commuting2qBlock): + # Check that the swap strategy creates enough connectivity for the node. self._check_edges(dag, node, swap_strategy) diff --git a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py index eb86d36febb6..8b92c5cdaf53 100644 --- a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py +++ b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/pauli_2q_evolution_commutation.py @@ -130,6 +130,7 @@ def _decompose_to_2q(self, dag: DAGCircuit, op: PauliEvolutionGate) -> DAGCircui } for edge, (pauli, coeff) in required_paulis.items(): + qubits = [dag.qubits[edge[0]], dag.qubits[edge[1]]] simple_pauli = Pauli(pauli.to_label().replace("I", "")) diff --git a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py index d32da751b2ac..72b62dc49a81 100644 --- a/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py +++ b/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py @@ -180,6 +180,7 @@ def distance_matrix(self) -> np.ndarray: for i in range(len(self._swap_layers) + 1): for j, k in self.swapped_coupling_map(i).get_edges(): + # This if ensures that the smallest distance is used. if self._distance_matrix[j, k] == -1: self._distance_matrix[j, k] = i diff --git a/qiskit/transpiler/passes/scheduling/alignments/reschedule.py b/qiskit/transpiler/passes/scheduling/alignments/reschedule.py index 08020b8f8691..b53d0f864cef 100644 --- a/qiskit/transpiler/passes/scheduling/alignments/reschedule.py +++ b/qiskit/transpiler/passes/scheduling/alignments/reschedule.py @@ -225,6 +225,7 @@ def run(self, dag: DAGCircuit): node_start_time = self.property_set["node_start_time"] for node in dag.topological_op_nodes(): + start_time = node_start_time.get(node) if start_time is None: diff --git a/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py b/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py index 634520610438..dbc60999fc35 100644 --- a/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py +++ b/qiskit/transpiler/passes/synthesis/solovay_kitaev_synthesis.py @@ -263,6 +263,7 @@ def supports_coupling_map(self): return False def run(self, unitary, **options): + # Runtime imports to avoid the overhead of these imports for # plugin discovery and only use them if the plugin is run/used config = options.get("config") or {} diff --git a/qiskit/transpiler/passes/synthesis/unitary_synthesis.py b/qiskit/transpiler/passes/synthesis/unitary_synthesis.py index 8c1fc473bf6a..67176ddf374e 100644 --- a/qiskit/transpiler/passes/synthesis/unitary_synthesis.py +++ b/qiskit/transpiler/passes/synthesis/unitary_synthesis.py @@ -76,6 +76,7 @@ def _choose_euler_basis(basis_gates): basis_set = set(basis_gates or []) for basis, gates in one_qubit_decompose.ONE_QUBIT_EULER_BASIS_GATES.items(): + if set(gates).issubset(basis_set): return basis diff --git a/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py b/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py index 919d2cfa0424..e510ddc87aeb 100644 --- a/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py +++ b/qiskit/transpiler/passes/utils/barrier_before_final_measurements.py @@ -36,6 +36,7 @@ def run(self, dag): is_final_op = True for _, child_successors in dag.bfs_successors(candidate_node): + if any( isinstance(suc, DAGOpNode) and suc.name not in final_op_types for suc in child_successors diff --git a/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py b/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py index ef78900179d8..f77870047c9d 100644 --- a/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py +++ b/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py @@ -113,8 +113,10 @@ def _collect_potential_merges(dag, barriers): barrier_to_add = Barrier(len(current_qubits)) for next_barrier in barriers[1:]: + # Ensure barriers are adjacent before checking if they are mergeable. if dag._multi_graph.has_edge(end_of_barrier._node_id, next_barrier._node_id): + # Remove all barriers that have already been included in this new barrier from the # set of ancestors/descendants as they will be removed from the new DAG when it is # created. @@ -131,6 +133,7 @@ def _collect_potential_merges(dag, barriers): and current_ancestors.isdisjoint(next_descendants) and current_descendants.isdisjoint(next_ancestors) ): + # can be merged current_ancestors = current_ancestors | next_ancestors current_descendants = current_descendants | next_descendants diff --git a/qiskit/transpiler/preset_passmanagers/level1.py b/qiskit/transpiler/preset_passmanagers/level1.py index a5fe9065d62e..1f6972d0ac3d 100644 --- a/qiskit/transpiler/preset_passmanagers/level1.py +++ b/qiskit/transpiler/preset_passmanagers/level1.py @@ -239,7 +239,6 @@ def _swap_mapped(property_set): if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] - # Build nested Flow controllers def _unroll_condition(property_set): return not property_set["all_gates_in_basis"] diff --git a/qiskit/transpiler/preset_passmanagers/level2.py b/qiskit/transpiler/preset_passmanagers/level2.py index 1c3ddc515951..de17840c499e 100644 --- a/qiskit/transpiler/preset_passmanagers/level2.py +++ b/qiskit/transpiler/preset_passmanagers/level2.py @@ -226,7 +226,6 @@ def _swap_mapped(property_set): if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] - # Build nested Flow controllers def _unroll_condition(property_set): return not property_set["all_gates_in_basis"] diff --git a/qiskit/transpiler/preset_passmanagers/level3.py b/qiskit/transpiler/preset_passmanagers/level3.py index 1038ffca3002..9635d978fe0f 100644 --- a/qiskit/transpiler/preset_passmanagers/level3.py +++ b/qiskit/transpiler/preset_passmanagers/level3.py @@ -258,7 +258,6 @@ def _swap_mapped(property_set): if optimization_method is None: optimization = PassManager() unroll = [pass_ for x in translation.passes() for pass_ in x["passes"]] - # Build nested Flow controllers def _unroll_condition(property_set): return not property_set["all_gates_in_basis"] diff --git a/qiskit/transpiler/synthesis/aqc/aqc_plugin.py b/qiskit/transpiler/synthesis/aqc/aqc_plugin.py index 4ea8da597cf5..0138d8e7b97a 100644 --- a/qiskit/transpiler/synthesis/aqc/aqc_plugin.py +++ b/qiskit/transpiler/synthesis/aqc/aqc_plugin.py @@ -101,6 +101,7 @@ def supports_coupling_map(self): return False def run(self, unitary, **options): + # Runtime imports to avoid the overhead of these imports for # plugin discovery and only use them if the plugin is run/used from qiskit.algorithms.optimizers import L_BFGS_B diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 485be032941c..5d566f625116 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -149,6 +149,7 @@ def apply(self, raw_data, method="least_squares"): ) elif isinstance(raw_data, qiskit.result.result.Result): + # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) @@ -172,6 +173,7 @@ def apply(self, raw_data, method="least_squares"): # Apply the correction for data_idx, _ in enumerate(raw_data2): + if method == "pseudo_inverse": raw_data2[data_idx] = np.dot(pinv_cal_mat, raw_data2[data_idx]) @@ -277,6 +279,7 @@ def substate_labels_list(self, new_substate_labels_list): # get the indices in the calibration matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): + self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)}) @property @@ -379,6 +382,7 @@ def apply( raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): + # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) @@ -409,6 +413,7 @@ def apply( # Apply the correction for data_idx, _ in enumerate(raw_data2): + if method == "pseudo_inverse": for pinv_cal_mat, pos_qubits, indices in zip( pinv_cal_matrices, self._mit_pattern, self._indices_list diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index 6ccad17a6c99..2fdeaa6372a6 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -224,6 +224,7 @@ def tensored_meas_cal( end_index = nqubits for qubit_list, list_size in zip(mit_pattern, qubits_list_sizes): + start_index = end_index - list_size substate = basis_state[start_index:end_index] @@ -238,6 +239,7 @@ def tensored_meas_cal( # add measurements end_index = nqubits for qubit_list, list_size in zip(mit_pattern, qubits_list_sizes): + for qind in range(list_size): qc_circuit.measure(qr[qubit_list[qind]], cr[nqubits - (end_index - qind)]) diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index 2c92dc3c99f3..65357d5dc5b5 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -181,6 +181,7 @@ def subset_fitter(self, qubit_sublist): # do a partial trace for i in range(len(new_state_labels)): for j in range(len(new_state_labels)): + for q_q_i_map in q_q_mapping[i]: for q_q_j_map in q_q_mapping[j]: new_cal_matrix[i, j] += self.cal_matrix[q_q_i_map, q_q_j_map] @@ -420,6 +421,7 @@ def _build_calibration_matrices(self): for measured_state, counts in state_cnts.items(): end_index = self.nqubits for cal_ind, cal_mat in enumerate(self._cal_matrices): + start_index = end_index - self._qubit_list_sizes[cal_ind] substate_index = self._indices_list[cal_ind][state[start_index:end_index]] diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index 6265365403d9..9714234ca694 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -344,6 +344,7 @@ def _safe_submit_circuits( pip_install="pip install qiskit-ibmq-provider", ) from ex1 if isinstance(ex, IBMQBackendJobLimitError): + oldest_running = backend.jobs( limit=1, descending=False, status=["QUEUED", "VALIDATING", "RUNNING"] ) diff --git a/qiskit/visualization/bloch.py b/qiskit/visualization/bloch.py index 4e956814c46e..778e4a013546 100644 --- a/qiskit/visualization/bloch.py +++ b/qiskit/visualization/bloch.py @@ -154,6 +154,7 @@ class Bloch: def __init__( self, fig=None, axes=None, view=None, figsize=None, background=False, font_size=20 ): + # Figure and axes self._ext_fig = False if fig is not None: @@ -586,6 +587,7 @@ def plot_vectors(self): """Plot vector""" # -X and Y data are switched for plotting purposes for k in range(len(self.vectors)): + xs3d = self.vectors[k][1] * np.array([0, 1]) ys3d = -self.vectors[k][0] * np.array([0, 1]) zs3d = self.vectors[k][2] * np.array([0, 1]) diff --git a/qiskit/visualization/circuit/matplotlib.py b/qiskit/visualization/circuit/matplotlib.py index 25b29835ed3a..fb61c7cf6d3b 100644 --- a/qiskit/visualization/circuit/matplotlib.py +++ b/qiskit/visualization/circuit/matplotlib.py @@ -593,6 +593,7 @@ def _set_bit_reg_info(self, wire_map, qubits_dict, clbits_dict, glob_data): idx = 0 pos = y_off = -len(self._qubits) + 1 for ii, wire in enumerate(wire_map): + # if it's a creg, register is the key and just load the index if isinstance(wire, ClassicalRegister): # If wire came from ControlFlowOp and not in clbits, don't draw it diff --git a/qiskit/visualization/circuit/text.py b/qiskit/visualization/circuit/text.py index ab5ac76f5e23..0185723fc8c6 100644 --- a/qiskit/visualization/circuit/text.py +++ b/qiskit/visualization/circuit/text.py @@ -1477,6 +1477,7 @@ def connect_with(self, wire_char): """ for label, affected_bits in self.connections: + if not affected_bits: continue diff --git a/qiskit/visualization/gate_map.py b/qiskit/visualization/gate_map.py index a9d919d0d931..86a3fbe9f858 100644 --- a/qiskit/visualization/gate_map.py +++ b/qiskit/visualization/gate_map.py @@ -1411,6 +1411,7 @@ def plot_error_map(backend, figsize=(12, 9), show_title=True, qubit_coordinates= directed = False line_colors = [] if cmap: + # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) diff --git a/qiskit/visualization/pass_manager_visualization.py b/qiskit/visualization/pass_manager_visualization.py index 1caa7fd7e9d8..6765c199e7c5 100644 --- a/qiskit/visualization/pass_manager_visualization.py +++ b/qiskit/visualization/pass_manager_visualization.py @@ -200,6 +200,7 @@ def draw_subgraph(controller_group, component_id, style, prev_node, idx): component_id += 1 for pass_ in controller_group["passes"]: + # label is the name of the pass node = pydot.Node( str(component_id), diff --git a/qiskit/visualization/pulse_v2/core.py b/qiskit/visualization/pulse_v2/core.py index eecbf09d800d..42cfa224c5d4 100644 --- a/qiskit/visualization/pulse_v2/core.py +++ b/qiskit/visualization/pulse_v2/core.py @@ -290,6 +290,7 @@ def _schedule_loader(self, program: pulse.Schedule | pulse.ScheduleBlock): for name, chans in mapper( channels=program.channels, formatter=self.formatter, device=self.device ): + chart = Chart(parent=self, name=name) # add standard pulse instructions diff --git a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml deleted file mode 100644 index a0026456e9f1..000000000000 --- a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml +++ /dev/null @@ -1,6 +0,0 @@ ---- -features: - - | - Disables the use of `RemoveResetInZeroState` in the preset passmanagers. - This better aligns circuits to the notion of arbitrary initital states - unless explicilty set to zeros with resets. diff --git a/test/python/algorithms/minimum_eigensolvers/test_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_vqe.py index ddef131ba922..4e61aa89f704 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_vqe.py @@ -43,7 +43,6 @@ from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals - # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" diff --git a/test/python/algorithms/test_aux_ops_evaluator.py b/test/python/algorithms/test_aux_ops_evaluator.py index 3ba5e6cdc4eb..11e4c8e76fc5 100644 --- a/test/python/algorithms/test_aux_ops_evaluator.py +++ b/test/python/algorithms/test_aux_ops_evaluator.py @@ -86,6 +86,7 @@ def _run_test( observables: ListOrDict[OperatorBase], quantum_instance: Union[QuantumInstance, Backend], ): + with self.assertWarns(DeprecationWarning): result = eval_observables( quantum_instance, quantum_state, observables, expectation, self.threshold diff --git a/test/python/algorithms/test_measure_error_mitigation.py b/test/python/algorithms/test_measure_error_mitigation.py index 5347ca81b371..a252ab08af7d 100644 --- a/test/python/algorithms/test_measure_error_mitigation.py +++ b/test/python/algorithms/test_measure_error_mitigation.py @@ -242,6 +242,7 @@ def test_measurement_error_mitigation_qaoa(self): ) with self.assertWarns(DeprecationWarning): + qaoa = QAOA( optimizer=COBYLA(maxiter=3), quantum_instance=quantum_instance, diff --git a/test/python/algorithms/test_phase_estimator.py b/test/python/algorithms/test_phase_estimator.py index cc6833d17142..9040bc1d6912 100644 --- a/test/python/algorithms/test_phase_estimator.py +++ b/test/python/algorithms/test_phase_estimator.py @@ -368,6 +368,7 @@ def one_phase( qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): + if phase_estimator == IterativePhaseEstimation: p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi) elif phase_estimator == PhaseEstimation: diff --git a/test/python/algorithms/test_qaoa.py b/test/python/algorithms/test_qaoa.py index b50fd2d247a8..7c743af7e263 100644 --- a/test/python/algorithms/test_qaoa.py +++ b/test/python/algorithms/test_qaoa.py @@ -282,6 +282,7 @@ def test_qaoa_initial_state(self, w, init_state): self.assertEqual(len(zero_circuits), len(custom_circuits)) for zero_circ, custom_circ in zip(zero_circuits, custom_circuits): + z_length = len(zero_circ.data) c_length = len(custom_circ.data) diff --git a/test/python/circuit/library/test_linear_function.py b/test/python/circuit/library/test_linear_function.py index d2eb6c38338f..4209d1a4e4a0 100644 --- a/test/python/circuit/library/test_linear_function.py +++ b/test/python/circuit/library/test_linear_function.py @@ -39,6 +39,7 @@ def random_linear_circuit( clifford=False, recursion_depth=0, ): + """Generate a pseudo random linear circuit.""" if num_qubits == 0: diff --git a/test/python/circuit/test_gate_definitions.py b/test/python/circuit/test_gate_definitions.py index 6a5742b770d2..0c41189fc954 100644 --- a/test/python/circuit/test_gate_definitions.py +++ b/test/python/circuit/test_gate_definitions.py @@ -285,7 +285,6 @@ class TestGateEquivalenceEqual(QiskitTestCase): "_U0Gate", "_DefinedGate", } - # Amazingly, Python's scoping rules for class bodies means that this is the closest we can get # to a "natural" comprehension or functional iterable definition: # https://docs.python.org/3/reference/executionmodel.html#resolution-of-names diff --git a/test/python/circuit/test_random_circuit.py b/test/python/circuit/test_random_circuit.py index dcdbec5a9de3..d318c9c58578 100644 --- a/test/python/circuit/test_random_circuit.py +++ b/test/python/circuit/test_random_circuit.py @@ -63,7 +63,7 @@ def test_large_conditional(self): conditions = (getattr(instruction.operation, "condition", None) for instruction in circ) conditions = [x for x in conditions if x is not None] self.assertNotEqual(conditions, []) - for register, value in conditions: + for (register, value) in conditions: self.assertIsInstance(register, (ClassicalRegister, Clbit)) # Condition values always have to be Python bigints (of which `bool` is a subclass), not # any of Numpy's fixed-width types, for example. diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 4720b3b23d39..07ada8e56ef9 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -1098,6 +1098,7 @@ def test_gradient_wrapper(self, backend_type): operator=op, bind_params=params, backend=q_instance ) else: + with self.assertWarns(DeprecationWarning): prob_grad = Gradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance @@ -1515,6 +1516,7 @@ def test_aux_meas_op(self, aux_meas_op): ] for backend_type in ["qasm_simulator", "statevector_simulator"]: + for j, value_dict in enumerate(value_dicts): with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index 5706a547666e..10448c3a64e1 100644 --- a/test/python/opflow/test_matrix_expectation.py +++ b/test/python/opflow/test_matrix_expectation.py @@ -86,6 +86,7 @@ def test_pauli_expect_op_vector(self): converted_meas = self.expect.convert(~StateFn(paulis_op)) with self.assertWarns(DeprecationWarning): + plus_mean = converted_meas @ Plus np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) sampled_plus = self.sampler.convert(plus_mean) diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index 067eb2035311..e6d23390ea78 100644 --- a/test/python/opflow/test_state_op_meas_evals.py +++ b/test/python/opflow/test_state_op_meas_evals.py @@ -176,6 +176,7 @@ def test_circuit_sampler_caching(self, caching): circuit.ry(x, 0) with self.assertWarns(DeprecationWarning): + expr1 = ~StateFn(H) @ StateFn(circuit) expr2 = ~StateFn(X) @ StateFn(circuit) sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector"), caching=caching) diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index d8850c602273..df9387ee070b 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -333,6 +333,7 @@ def test_bound_pass_manager(self): op = SparsePauliOp.from_list([("II", 1)]) with self.subTest("Test single circuit"): + dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: @@ -342,6 +343,7 @@ def test_bound_pass_manager(self): self.assertEqual(mock_pass.call_count, 1) with self.subTest("Test circuit batch"): + dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index 3c56ea2bfd80..86dc709f8983 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -387,6 +387,7 @@ def test_bound_pass_manager(self): """Test bound pass manager.""" with self.subTest("Test single circuit"): + dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: @@ -396,6 +397,7 @@ def test_bound_pass_manager(self): self.assertEqual(mock_pass.call_count, 1) with self.subTest("Test circuit batch"): + dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: diff --git a/test/python/quantum_info/states/test_densitymatrix.py b/test/python/quantum_info/states/test_densitymatrix.py index 7377f4859f10..3185758cb469 100644 --- a/test/python/quantum_info/states/test_densitymatrix.py +++ b/test/python/quantum_info/states/test_densitymatrix.py @@ -620,6 +620,7 @@ def test_sample_counts_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -627,6 +628,7 @@ def test_sample_counts_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -634,6 +636,7 @@ def test_sample_counts_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -654,6 +657,7 @@ def test_sample_counts_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -661,6 +665,7 @@ def test_sample_counts_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -668,6 +673,7 @@ def test_sample_counts_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -758,6 +764,7 @@ def test_sample_memory_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -766,6 +773,7 @@ def test_sample_memory_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -774,6 +782,7 @@ def test_sample_memory_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -794,6 +803,7 @@ def test_sample_memory_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -802,6 +812,7 @@ def test_sample_memory_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -810,6 +821,7 @@ def test_sample_memory_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) diff --git a/test/python/quantum_info/states/test_statevector.py b/test/python/quantum_info/states/test_statevector.py index fde32c744fb1..a7228d6bf5d2 100644 --- a/test/python/quantum_info/states/test_statevector.py +++ b/test/python/quantum_info/states/test_statevector.py @@ -675,6 +675,7 @@ def test_sample_counts_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -682,6 +683,7 @@ def test_sample_counts_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -689,6 +691,7 @@ def test_sample_counts_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -706,6 +709,7 @@ def test_sample_counts_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -713,6 +717,7 @@ def test_sample_counts_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -720,6 +725,7 @@ def test_sample_counts_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) @@ -808,6 +814,7 @@ def test_sample_memory_ghz(self): # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -816,6 +823,7 @@ def test_sample_memory_ghz(self): # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -824,6 +832,7 @@ def test_sample_memory_ghz(self): # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -841,6 +850,7 @@ def test_sample_memory_w(self): target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -849,6 +859,7 @@ def test_sample_memory_w(self): # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) @@ -857,6 +868,7 @@ def test_sample_memory_w(self): # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: + with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) diff --git a/test/python/transpiler/aqc/fast_gradient/test_layer1q.py b/test/python/transpiler/aqc/fast_gradient/test_layer1q.py index a55a3961410c..c3a211293cd3 100644 --- a/test/python/transpiler/aqc/fast_gradient/test_layer1q.py +++ b/test/python/transpiler/aqc/fast_gradient/test_layer1q.py @@ -45,6 +45,7 @@ def test_layer1q_matrix(self): eps = 100.0 * np.finfo(float).eps max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): + dim = 2**n iden = tut.eye_int(n) for k in range(n): @@ -91,6 +92,7 @@ def test_pmatrix_class(self): mat_kind = "complex" max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): + dim = 2**n tmp1 = np.ndarray((dim, dim), dtype=np.cfloat) tmp2 = tmp1.copy() diff --git a/test/python/transpiler/aqc/fast_gradient/test_layer2q.py b/test/python/transpiler/aqc/fast_gradient/test_layer2q.py index 1ba05fdb1f91..a4795f57be92 100644 --- a/test/python/transpiler/aqc/fast_gradient/test_layer2q.py +++ b/test/python/transpiler/aqc/fast_gradient/test_layer2q.py @@ -45,6 +45,7 @@ def test_layer2q_matrix(self): _eps = 100.0 * np.finfo(float).eps max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): + dim = 2**n iden = tut.eye_int(n) for j in range(n): @@ -94,6 +95,7 @@ def test_pmatrix_class(self): mat_kind = "complex" max_rel_err = 0.0 for n in range(2, self.max_num_qubits + 1): + dim = 2**n tmp1 = np.ndarray((dim, dim), dtype=np.cfloat) tmp2 = tmp1.copy() diff --git a/test/python/transpiler/aqc/fast_gradient/test_utils.py b/test/python/transpiler/aqc/fast_gradient/test_utils.py index 75492bbe6532..d120fcac7ce4 100644 --- a/test/python/transpiler/aqc/fast_gradient/test_utils.py +++ b/test/python/transpiler/aqc/fast_gradient/test_utils.py @@ -109,6 +109,7 @@ def _permutation_and_matrix(size: int) -> (np.ndarray, np.ndarray, np.ndarray, n return perm, inv_perm, p_mat, q_mat for n in range(1, self.max_nqubits_perms + 1): + dim = 2**n for _ in range(100): perm1, inv_perm1, p1_mat, q1_mat = _permutation_and_matrix(dim) diff --git a/test/python/transpiler/test_echo_rzx_weyl_decomposition.py b/test/python/transpiler/test_echo_rzx_weyl_decomposition.py index d87d10ea1a6d..54f630d4ed24 100644 --- a/test/python/transpiler/test_echo_rzx_weyl_decomposition.py +++ b/test/python/transpiler/test_echo_rzx_weyl_decomposition.py @@ -162,6 +162,7 @@ def test_weyl_decomposition_gate_angles(self): circuits = [circuit_rxx, circuit_ryy, circuit_rzz] for circuit in circuits: + unitary_circuit = qi.Operator(circuit).data dag = circuit_to_dag(circuit) diff --git a/test/python/utils/mitigation/test_meas.py b/test/python/utils/mitigation/test_meas.py index a2c480519570..a5105b5ba4d5 100644 --- a/test/python/utils/mitigation/test_meas.py +++ b/test/python/utils/mitigation/test_meas.py @@ -274,6 +274,7 @@ def test_ideal_meas_cal(self): """Test ideal execution, without noise.""" for nq in self.nq_list: for pattern_type in range(1, 2**nq): + # Generate the quantum register according to the pattern qubits, weight = self.choose_calibration(nq, pattern_type) From ef9e2d33e5cb9c6f678b7cba344a9dd0e40c9938 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:16:08 -0400 Subject: [PATCH 04/15] Add note back --- .../notes/keep-initial-resets-a5f75cb16c8edb57.yaml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml diff --git a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml new file mode 100644 index 000000000000..a0026456e9f1 --- /dev/null +++ b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Disables the use of `RemoveResetInZeroState` in the preset passmanagers. + This better aligns circuits to the notion of arbitrary initital states + unless explicilty set to zeros with resets. From ba0bf899ec52a7987e582cf9527ccc7e373e44d6 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:27:14 -0400 Subject: [PATCH 05/15] Add test over all transpile levels --- .../transpiler/preset_passmanagers/level3.py | 1 - .../python/compiler/test_transpiler_resets.py | 32 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 test/python/compiler/test_transpiler_resets.py diff --git a/qiskit/transpiler/preset_passmanagers/level3.py b/qiskit/transpiler/preset_passmanagers/level3.py index 9635d978fe0f..737e95f85048 100644 --- a/qiskit/transpiler/preset_passmanagers/level3.py +++ b/qiskit/transpiler/preset_passmanagers/level3.py @@ -211,7 +211,6 @@ def _opt_control(property_set): unitary_synthesis_plugin_config, hls_config, ) - init.append(RemoveResetInZeroState()) init.append(OptimizeSwapBeforeMeasure()) init.append(RemoveDiagonalGatesBeforeMeasure()) if coupling_map or initial_layout: diff --git a/test/python/compiler/test_transpiler_resets.py b/test/python/compiler/test_transpiler_resets.py new file mode 100644 index 000000000000..a0557f869290 --- /dev/null +++ b/test/python/compiler/test_transpiler_resets.py @@ -0,0 +1,32 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2023. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Tests for resets in the transpiler""" + +import unittest + +from qiskit.circuit import QuantumCircuit, transpile +from qiskit.test import QiskitTestCase + + +class TestResetsTranspiler(QiskitTestCase): + """Tests resets and transpilation""" + + def test_init_resets_kept_preset_passmanagers(self): + """Test initial resets kept at all preset transpilation levels""" + N = 5 + qc = QuantumCircuit(N) + qc.reset(range(N)) + + for level in range(4): + num_resets = transpile(qc, optimization_level=level).count_ops()['reset'] + self.assertEqual(num_resets, N) From 35421fe768d9ea1f9f9e39ed290eea72b396b1bd Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:28:19 -0400 Subject: [PATCH 06/15] black --- test/python/compiler/test_transpiler_resets.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/python/compiler/test_transpiler_resets.py b/test/python/compiler/test_transpiler_resets.py index a0557f869290..84bae2bdb6c1 100644 --- a/test/python/compiler/test_transpiler_resets.py +++ b/test/python/compiler/test_transpiler_resets.py @@ -14,7 +14,7 @@ import unittest -from qiskit.circuit import QuantumCircuit, transpile +from qiskit.circuit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase @@ -28,5 +28,5 @@ def test_init_resets_kept_preset_passmanagers(self): qc.reset(range(N)) for level in range(4): - num_resets = transpile(qc, optimization_level=level).count_ops()['reset'] + num_resets = transpile(qc, optimization_level=level).count_ops()["reset"] self.assertEqual(num_resets, N) From 5bc253d4a9572a4d726e35103f23bf21714fdbe2 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:29:33 -0400 Subject: [PATCH 07/15] Update releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml Co-authored-by: Julien Gacon --- .../notes/keep-initial-resets-a5f75cb16c8edb57.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml index a0026456e9f1..960722cfdc9f 100644 --- a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml +++ b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml @@ -1,6 +1,6 @@ --- features: - | - Disables the use of `RemoveResetInZeroState` in the preset passmanagers. - This better aligns circuits to the notion of arbitrary initital states - unless explicilty set to zeros with resets. + Disables the use of :class:`.RemoveResetInZeroState` in the preset passmanagers. + This better aligns circuits to the notion of arbitrary initial states + unless explicitly set to zeros with resets. From d86d77e72b2456267cce4445e5cb39e93a1a2099 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:30:25 -0400 Subject: [PATCH 08/15] fix imports --- test/python/compiler/test_transpiler_resets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/python/compiler/test_transpiler_resets.py b/test/python/compiler/test_transpiler_resets.py index 84bae2bdb6c1..aec767ab84d1 100644 --- a/test/python/compiler/test_transpiler_resets.py +++ b/test/python/compiler/test_transpiler_resets.py @@ -14,7 +14,7 @@ import unittest -from qiskit.circuit import QuantumCircuit, transpile +from qiskit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase From 11490978a2f6f3a9ba22b2faf4bc0da5840926c0 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:31:08 -0400 Subject: [PATCH 09/15] remove unused import --- test/python/compiler/test_transpiler_resets.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/python/compiler/test_transpiler_resets.py b/test/python/compiler/test_transpiler_resets.py index aec767ab84d1..8f2a9db56908 100644 --- a/test/python/compiler/test_transpiler_resets.py +++ b/test/python/compiler/test_transpiler_resets.py @@ -11,9 +11,6 @@ # that they have been altered from the originals. """Tests for resets in the transpiler""" - -import unittest - from qiskit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase From 7a6b0f5a15e13d1b49d85b75cc1d3e94e031b660 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 10:58:45 -0400 Subject: [PATCH 10/15] damn variable names --- test/python/compiler/test_transpiler_resets.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/python/compiler/test_transpiler_resets.py b/test/python/compiler/test_transpiler_resets.py index 8f2a9db56908..481bfd2bf617 100644 --- a/test/python/compiler/test_transpiler_resets.py +++ b/test/python/compiler/test_transpiler_resets.py @@ -20,10 +20,10 @@ class TestResetsTranspiler(QiskitTestCase): def test_init_resets_kept_preset_passmanagers(self): """Test initial resets kept at all preset transpilation levels""" - N = 5 - qc = QuantumCircuit(N) - qc.reset(range(N)) + num_qubits = 5 + qc = QuantumCircuit(num_qubits) + qc.reset(range(num_qubits)) for level in range(4): num_resets = transpile(qc, optimization_level=level).count_ops()["reset"] - self.assertEqual(num_resets, N) + self.assertEqual(num_resets, num_qubits) From b1ca03963aa22303becbf8a22d9bc23f2d3e2765 Mon Sep 17 00:00:00 2001 From: Paul Nation Date: Fri, 18 Aug 2023 11:18:08 -0400 Subject: [PATCH 11/15] remove unused import --- qiskit/transpiler/preset_passmanagers/level3.py | 1 - 1 file changed, 1 deletion(-) diff --git a/qiskit/transpiler/preset_passmanagers/level3.py b/qiskit/transpiler/preset_passmanagers/level3.py index d11d25494611..c1f0d34d52f6 100644 --- a/qiskit/transpiler/preset_passmanagers/level3.py +++ b/qiskit/transpiler/preset_passmanagers/level3.py @@ -30,7 +30,6 @@ from qiskit.transpiler.passes import MinimumPoint from qiskit.transpiler.passes import Depth from qiskit.transpiler.passes import Size -from qiskit.transpiler.passes import RemoveResetInZeroState from qiskit.transpiler.passes import Optimize1qGatesDecomposition from qiskit.transpiler.passes import CommutativeCancellation from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure From 584ead491fb2285085bd578012f35c255231b034 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 24 Aug 2023 11:00:50 +0200 Subject: [PATCH 12/15] conflict --- qiskit/transpiler/preset_passmanagers/builtin_plugins.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/qiskit/transpiler/preset_passmanagers/builtin_plugins.py b/qiskit/transpiler/preset_passmanagers/builtin_plugins.py index b6cf031f3f3a..28d017e91660 100644 --- a/qiskit/transpiler/preset_passmanagers/builtin_plugins.py +++ b/qiskit/transpiler/preset_passmanagers/builtin_plugins.py @@ -27,7 +27,6 @@ from qiskit.transpiler.passes import NoiseAdaptiveLayout from qiskit.transpiler.passes import CheckMap from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements -from qiskit.transpiler.passes import RemoveResetInZeroState from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure from qiskit.transpiler.passes import RemoveDiagonalGatesBeforeMeasure from qiskit.transpiler.preset_passmanagers import common @@ -81,7 +80,6 @@ def pass_manager(self, pass_manager_config, optimization_level=None) -> PassMana pass_manager_config.unitary_synthesis_plugin_config, pass_manager_config.hls_config, ) - init.append(RemoveResetInZeroState()) init.append(OptimizeSwapBeforeMeasure()) init.append(RemoveDiagonalGatesBeforeMeasure()) else: From 7abded24302f77e6f35d306bbb879c3219098f27 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 24 Aug 2023 11:22:45 +0200 Subject: [PATCH 13/15] consolidate tests --- test/python/compiler/test_transpiler.py | 24 ++++++++------- .../python/compiler/test_transpiler_resets.py | 29 ------------------- 2 files changed, 14 insertions(+), 39 deletions(-) delete mode 100644 test/python/compiler/test_transpiler_resets.py diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index d041711a3639..0be4922cb5b7 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -51,7 +51,6 @@ SXGate, U1Gate, U2Gate, - U3Gate, UGate, XGate, ) @@ -802,21 +801,26 @@ def test_move_measurements(self): ) self.assertTrue(is_last_measure) - def test_initialize_reset_is_not_removed(self): + @data(0, 1, 2, 3) + def test_init_resets_kept_preset_passmanagers(self, optimization_level): + """Test initial resets kept at all preset transpilation levels""" + num_qubits = 5 + qc = QuantumCircuit(num_qubits) + qc.reset(range(num_qubits)) + + num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"] + self.assertEqual(num_resets, num_qubits) + + @data(0, 1, 2, 3) + def test_initialize_reset_is_not_removed(self, optimization_level): """The reset in front of initializer should NOT be removed at beginning""" qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]]) qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]]) - expected = QuantumCircuit(qr) - expected.reset(qr[0]) - expected.append(U3Gate(np.pi / 2, 0, 0), [qr[0]]) - expected.reset(qr[0]) - expected.append(U3Gate(np.pi / 2, -np.pi, 0), [qr[0]]) - - after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=1) - self.assertEqual(after, expected, msg=f"after:\n{after}\nexpected:\n{expected}") + after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level) + self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.") def test_initialize_FakeMelbourne(self): """Test that the zero-state resets are remove in a device not supporting them.""" diff --git a/test/python/compiler/test_transpiler_resets.py b/test/python/compiler/test_transpiler_resets.py deleted file mode 100644 index 481bfd2bf617..000000000000 --- a/test/python/compiler/test_transpiler_resets.py +++ /dev/null @@ -1,29 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2023. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -"""Tests for resets in the transpiler""" -from qiskit import QuantumCircuit, transpile -from qiskit.test import QiskitTestCase - - -class TestResetsTranspiler(QiskitTestCase): - """Tests resets and transpilation""" - - def test_init_resets_kept_preset_passmanagers(self): - """Test initial resets kept at all preset transpilation levels""" - num_qubits = 5 - qc = QuantumCircuit(num_qubits) - qc.reset(range(num_qubits)) - - for level in range(4): - num_resets = transpile(qc, optimization_level=level).count_ops()["reset"] - self.assertEqual(num_resets, num_qubits) From 79e5b5cfdab7448332c1e1a3ef3e55737e78e1ea Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 24 Aug 2023 11:26:00 +0200 Subject: [PATCH 14/15] unrelated change From 8492811bdf1aabb701cb4168c4261e519ee8ae96 Mon Sep 17 00:00:00 2001 From: Jake Lishman Date: Thu, 24 Aug 2023 11:42:45 +0100 Subject: [PATCH 15/15] Change release note to "upgrade" Co-authored-by: Luciano Bello --- releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml index 960722cfdc9f..e0c987504dc0 100644 --- a/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml +++ b/releasenotes/notes/keep-initial-resets-a5f75cb16c8edb57.yaml @@ -1,5 +1,5 @@ --- -features: +upgrade: - | Disables the use of :class:`.RemoveResetInZeroState` in the preset passmanagers. This better aligns circuits to the notion of arbitrary initial states