diff --git a/pyproject.toml b/pyproject.toml index c13486c21bb3..149d6c0f2d47 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -221,7 +221,6 @@ disable = [ "consider-using-f-string", "no-member", # for dynamically created members "not-context-manager", - "possibly-used-before-assignment", "unnecessary-lambda-assignment", # do not want to implement "unspecified-encoding", # do not want to implement ] diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index b91ea7068be1..8446c870b1fd 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -65,6 +65,8 @@ def _run_circuits( max_circuits = getattr(backend.configuration(), "max_experiments", None) elif isinstance(backend, BackendV2): max_circuits = backend.max_circuits + else: + raise RuntimeError("Backend version not supported") if max_circuits: jobs = [ backend.run(circuits[pos : pos + max_circuits], **run_options) diff --git a/qiskit/pulse/macros.py b/qiskit/pulse/macros.py index 1995d6d20c40..88414cfc7e9b 100644 --- a/qiskit/pulse/macros.py +++ b/qiskit/pulse/macros.py @@ -124,8 +124,13 @@ def _measure_v1( for qubit in qubits: measure_groups.add(tuple(meas_map[qubit])) for measure_group_qubits in measure_groups: - if qubit_mem_slots is not None: - unused_mem_slots = set(measure_group_qubits) - set(qubit_mem_slots.values()) + + unused_mem_slots = ( + set() + if qubit_mem_slots is None + else set(measure_group_qubits) - set(qubit_mem_slots.values()) + ) + try: default_sched = inst_map.get(measure_name, measure_group_qubits) except exceptions.PulseError as ex: diff --git a/qiskit/qpy/binary_io/circuits.py b/qiskit/qpy/binary_io/circuits.py index 25103e7b4c27..db53defbcfa7 100644 --- a/qiskit/qpy/binary_io/circuits.py +++ b/qiskit/qpy/binary_io/circuits.py @@ -446,6 +446,7 @@ def _parse_custom_operation( ) = custom_operations[gate_name] else: type_str, num_qubits, num_clbits, definition = custom_operations[gate_name] + base_gate_raw = ctrl_state = num_ctrl_qubits = None # Strip the trailing "_{uuid}" from the gate name if the version >=11 if version >= 11: gate_name = "_".join(gate_name.split("_")[:-1]) diff --git a/qiskit/quantum_info/operators/operator.py b/qiskit/quantum_info/operators/operator.py index 41eac3563576..016e337f082c 100644 --- a/qiskit/quantum_info/operators/operator.py +++ b/qiskit/quantum_info/operators/operator.py @@ -414,6 +414,8 @@ def from_circuit( from qiskit.synthesis.permutation.permutation_utils import _inverse_pattern + op = Operator(circuit) + if initial_layout is not None: input_qubits = [None] * len(layout.input_qubit_mapping) for q, p in layout.input_qubit_mapping.items(): @@ -421,22 +423,18 @@ def from_circuit( initial_permutation = initial_layout.to_permutation(input_qubits) initial_permutation_inverse = _inverse_pattern(initial_permutation) + op = op.apply_permutation(initial_permutation, True) - if final_layout is not None: + if final_layout is not None: + final_permutation = final_layout.to_permutation(circuit.qubits) + final_permutation_inverse = _inverse_pattern(final_permutation) + op = op.apply_permutation(final_permutation_inverse, False) + op = op.apply_permutation(initial_permutation_inverse, False) + elif final_layout is not None: final_permutation = final_layout.to_permutation(circuit.qubits) final_permutation_inverse = _inverse_pattern(final_permutation) - - op = Operator(circuit) - - if initial_layout: - op = op.apply_permutation(initial_permutation, True) - - if final_layout: op = op.apply_permutation(final_permutation_inverse, False) - if initial_layout: - op = op.apply_permutation(initial_permutation_inverse, False) - return op def is_unitary(self, atol=None, rtol=None): diff --git a/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py b/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py index f8d25a6e8daa..6204189be443 100644 --- a/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +++ b/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py @@ -135,19 +135,19 @@ def __init__( pauli_list = PauliList(data.copy() if copy and hasattr(data, "copy") else data) - if isinstance(coeffs, np.ndarray): - dtype = object if coeffs.dtype == object else complex - elif coeffs is not None: - if not isinstance(coeffs, (np.ndarray, Sequence)): - coeffs = [coeffs] - if any(isinstance(coeff, ParameterExpression) for coeff in coeffs): - dtype = object - else: - dtype = complex - if coeffs is None: coeffs = np.ones(pauli_list.size, dtype=complex) else: + if isinstance(coeffs, np.ndarray): + dtype = object if coeffs.dtype == object else complex + else: + if not isinstance(coeffs, Sequence): + coeffs = [coeffs] + if any(isinstance(coeff, ParameterExpression) for coeff in coeffs): + dtype = object + else: + dtype = complex + coeffs_asarray = np.asarray(coeffs, dtype=dtype) coeffs = ( coeffs_asarray.copy() diff --git a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py index 2a95f540f886..a54e4bfcb001 100644 --- a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py +++ b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py @@ -60,9 +60,9 @@ def run(self, dag): if self._basis_gates is None and self._target is None: return dag + device_insts = {"measure", "reset", "barrier", "snapshot", "delay", "store"} if self._target is None: - basic_insts = {"measure", "reset", "barrier", "snapshot", "delay", "store"} - device_insts = basic_insts | set(self._basis_gates) + device_insts |= set(self._basis_gates) for node in dag.op_nodes(): if isinstance(node.op, ControlFlowOp): @@ -77,14 +77,14 @@ def run(self, dag): controlled_gate_open_ctrl = isinstance(node.op, ControlledGate) and node.op._open_ctrl if not controlled_gate_open_ctrl: - inst_supported = ( - self._target.instruction_supported( + if self._target is not None: + inst_supported = self._target.instruction_supported( operation_name=node.op.name, qargs=tuple(dag.find_bit(x).index for x in node.qargs), ) - if self._target is not None - else node.name in device_insts - ) + else: + inst_supported = node.name in device_insts + if inst_supported or self._equiv_lib.has_entry(node.op): continue try: diff --git a/qiskit/transpiler/passes/optimization/commutative_cancellation.py b/qiskit/transpiler/passes/optimization/commutative_cancellation.py index 396186fa95cc..68d40f3650a2 100644 --- a/qiskit/transpiler/passes/optimization/commutative_cancellation.py +++ b/qiskit/transpiler/passes/optimization/commutative_cancellation.py @@ -16,7 +16,6 @@ import numpy as np from qiskit.circuit.quantumregister import QuantumRegister -from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passes.optimization.commutation_analysis import CommutationAnalysis @@ -72,9 +71,6 @@ def run(self, dag): Returns: DAGCircuit: the optimized DAG. - - Raises: - TranspilerError: when the 1-qubit rotation gates are not found """ var_z_gate = None z_var_gates = [gate for gate in dag.count_ops().keys() if gate in self._var_z_map] @@ -146,7 +142,7 @@ def run(self, dag): or len(current_node.qargs) != 1 or current_node.qargs[0] != run_qarg ): - raise TranspilerError("internal error") + raise RuntimeError("internal error") if current_node.name in ["p", "u1", "rz", "rx"]: current_angle = float(current_node.op.params[0]) @@ -156,6 +152,10 @@ def run(self, dag): current_angle = np.pi / 4 elif current_node.name == "s": current_angle = np.pi / 2 + else: + raise RuntimeError( + f"Angle for operation {current_node.name } is not defined" + ) # Compose gates total_angle = current_angle + total_angle @@ -167,6 +167,8 @@ def run(self, dag): new_op = var_z_gate(total_angle) elif cancel_set_key[0] == "x_rotation": new_op = RXGate(total_angle) + else: + raise RuntimeError("impossible case") new_op_phase = 0 if np.mod(total_angle, (2 * np.pi)) > _CUTOFF_PRECISION: diff --git a/qiskit/visualization/circuit/matplotlib.py b/qiskit/visualization/circuit/matplotlib.py index b4252065006c..0076073fb8e4 100644 --- a/qiskit/visualization/circuit/matplotlib.py +++ b/qiskit/visualization/circuit/matplotlib.py @@ -1584,6 +1584,8 @@ def _flow_op_gate(self, node, node_data, glob_data): flow_text = " For" elif isinstance(node.op, SwitchCaseOp): flow_text = "Switch" + else: + flow_text = node.op.name # Some spacers. op_spacer moves 'Switch' back a bit for alignment, # expr_spacer moves the expr over to line up with 'Switch' and diff --git a/test/benchmarks/randomized_benchmarking.py b/test/benchmarks/randomized_benchmarking.py index f3c3d18e9f96..9847c928ad71 100644 --- a/test/benchmarks/randomized_benchmarking.py +++ b/test/benchmarks/randomized_benchmarking.py @@ -105,6 +105,7 @@ def clifford_2_qubit_circuit(num): qc = QuantumCircuit(2) if vals[0] == 0 or vals[0] == 3: (form, i0, i1, j0, j1, p0, p1) = vals + k0, k1 = (None, None) else: (form, i0, i1, j0, j1, k0, k1, p0, p1) = vals if i0 == 1: diff --git a/test/benchmarks/utils.py b/test/benchmarks/utils.py index d932e8d6a0c5..bbd7d0a9af85 100644 --- a/test/benchmarks/utils.py +++ b/test/benchmarks/utils.py @@ -126,6 +126,8 @@ def random_circuit( operation = rng.choice(two_q_ops) elif num_operands == 3: operation = rng.choice(three_q_ops) + else: + raise RuntimeError("not supported number of operands") if operation in one_param: num_angles = 1 elif operation in two_param: diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index 7cdc4ed56ab6..c86deee42876 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -1091,7 +1091,7 @@ def test_decompose_propagates_bound_parameters(self, target_type, parameter_type if target_type == "gate": inst = qc.to_gate() - elif target_type == "instruction": + else: # target_type == "instruction": inst = qc.to_instruction() qc2 = QuantumCircuit(1) @@ -1132,7 +1132,7 @@ def test_decompose_propagates_deeply_bound_parameters(self, target_type, paramet if target_type == "gate": inst = qc1.to_gate() - elif target_type == "instruction": + else: # target_type == "instruction": inst = qc1.to_instruction() qc2 = QuantumCircuit(1) @@ -1188,7 +1188,7 @@ def test_executing_parameterized_instruction_bound_early(self, target_type): if target_type == "gate": sub_inst = sub_qc.to_gate() - elif target_type == "instruction": + else: # target_type == "instruction": sub_inst = sub_qc.to_instruction() unbound_qc = QuantumCircuit(2, 1) @@ -1405,6 +1405,7 @@ def _paramvec_names(prefix, length): @ddt class TestParameterExpressions(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Test expressions of Parameters.""" # supported operations dictionary operation : accuracy (0=exact match) diff --git a/test/python/classical_function_compiler/test_boolean_expression.py b/test/python/classical_function_compiler/test_boolean_expression.py index afdc91fdd04f..40a01b154c63 100644 --- a/test/python/classical_function_compiler/test_boolean_expression.py +++ b/test/python/classical_function_compiler/test_boolean_expression.py @@ -28,6 +28,7 @@ @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") @ddt class TestBooleanExpression(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Test boolean expression.""" @data( diff --git a/test/python/classical_function_compiler/test_classical_function.py b/test/python/classical_function_compiler/test_classical_function.py index d4a0bf66d493..e385745952e9 100644 --- a/test/python/classical_function_compiler/test_classical_function.py +++ b/test/python/classical_function_compiler/test_classical_function.py @@ -26,6 +26,7 @@ @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestOracleDecomposition(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Tests ClassicalFunction.decomposition.""" def test_grover_oracle(self): diff --git a/test/python/classical_function_compiler/test_parse.py b/test/python/classical_function_compiler/test_parse.py index 15862ca71b3a..9da93873c700 100644 --- a/test/python/classical_function_compiler/test_parse.py +++ b/test/python/classical_function_compiler/test_parse.py @@ -25,6 +25,7 @@ @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestParseFail(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Tests bad_examples with the classicalfunction parser.""" def assertExceptionMessage(self, context, message): diff --git a/test/python/classical_function_compiler/test_simulate.py b/test/python/classical_function_compiler/test_simulate.py index 65399de82d08..f7c6ef3dd165 100644 --- a/test/python/classical_function_compiler/test_simulate.py +++ b/test/python/classical_function_compiler/test_simulate.py @@ -26,6 +26,7 @@ @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") @ddt class TestSimulate(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Tests LogicNetwork.simulate method""" @data(*utils.example_list()) diff --git a/test/python/classical_function_compiler/test_synthesis.py b/test/python/classical_function_compiler/test_synthesis.py index 3b8890d986ce..1d44b58882f8 100644 --- a/test/python/classical_function_compiler/test_synthesis.py +++ b/test/python/classical_function_compiler/test_synthesis.py @@ -26,6 +26,7 @@ @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestSynthesis(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Tests ClassicalFunction.synth method.""" def test_grover_oracle(self): diff --git a/test/python/classical_function_compiler/test_tweedledum2qiskit.py b/test/python/classical_function_compiler/test_tweedledum2qiskit.py index 32bd9485fdc2..ff9b73a5b551 100644 --- a/test/python/classical_function_compiler/test_tweedledum2qiskit.py +++ b/test/python/classical_function_compiler/test_tweedledum2qiskit.py @@ -29,6 +29,7 @@ @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestTweedledum2Qiskit(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Tests qiskit.transpiler.classicalfunction.utils.tweedledum2qiskit function.""" def test_x(self): diff --git a/test/python/classical_function_compiler/test_typecheck.py b/test/python/classical_function_compiler/test_typecheck.py index 36b64ce4fd4d..ffe57cc3d4b3 100644 --- a/test/python/classical_function_compiler/test_typecheck.py +++ b/test/python/classical_function_compiler/test_typecheck.py @@ -25,6 +25,7 @@ @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestTypeCheck(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Tests classicalfunction compiler type checker (good examples).""" def test_id(self): @@ -74,6 +75,7 @@ def test_bool_or(self): @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestTypeCheckFail(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Tests classicalfunction compiler type checker (bad examples).""" def assertExceptionMessage(self, context, message): diff --git a/test/python/visualization/test_circuit_drawer.py b/test/python/visualization/test_circuit_drawer.py index f02f1ad11431..e6b430c4ee82 100644 --- a/test/python/visualization/test_circuit_drawer.py +++ b/test/python/visualization/test_circuit_drawer.py @@ -55,6 +55,7 @@ def test_default_output(self): @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_mpl_config_with_path(self): + # pylint: disable=possibly-used-before-assignment # It's too easy to get too nested in a test with many context managers. tempdir = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with self.addCleanup(tempdir.cleanup) @@ -128,6 +129,7 @@ def test_latex_unsupported_image_format_error_message(self): @_latex_drawer_condition def test_latex_output_file_correct_format(self): + # pylint: disable=possibly-used-before-assignment with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() filename = "file.gif" diff --git a/test/python/visualization/test_circuit_text_drawer.py b/test/python/visualization/test_circuit_text_drawer.py index 3f018c085109..2a0a61c7904b 100644 --- a/test/python/visualization/test_circuit_text_drawer.py +++ b/test/python/visualization/test_circuit_text_drawer.py @@ -185,6 +185,7 @@ def test_text_no_pager(self): class TestTextDrawerGatesInCircuit(QiskitTestCase): + # pylint: disable=possibly-used-before-assignment """Gate by gate checks in different settings.""" def test_text_measure_cregbundle(self): diff --git a/test/python/visualization/test_gate_map.py b/test/python/visualization/test_gate_map.py index dd3a479ba65d..bf9b1ca80d79 100644 --- a/test/python/visualization/test_gate_map.py +++ b/test/python/visualization/test_gate_map.py @@ -45,6 +45,7 @@ @unittest.skipUnless(optionals.HAS_PIL, "PIL not available") @unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available") class TestGateMap(QiskitVisualizationTestCase): + # pylint: disable=possibly-used-before-assignment """visual tests for plot_gate_map""" backends = [Fake5QV1(), Fake20QV1(), Fake7QPulseV1()] diff --git a/test/python/visualization/test_plot_histogram.py b/test/python/visualization/test_plot_histogram.py index 7c530851326d..2668f3ff679d 100644 --- a/test/python/visualization/test_plot_histogram.py +++ b/test/python/visualization/test_plot_histogram.py @@ -28,6 +28,7 @@ @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.") class TestPlotHistogram(QiskitVisualizationTestCase): + # pylint: disable=possibly-used-before-assignment """Qiskit plot_histogram tests.""" def test_different_counts_lengths(self): diff --git a/tools/build_standard_commutations.py b/tools/build_standard_commutations.py index 72798f0eb4be..56c452b11ce0 100644 --- a/tools/build_standard_commutations.py +++ b/tools/build_standard_commutations.py @@ -102,12 +102,12 @@ def _generate_commutation_dict(considered_gates: List[Gate] = None) -> dict: commutation_relation = cc.commute( op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits=4 ) + + gate_pair_commutation[relative_placement] = commutation_relation else: pass # TODO - gate_pair_commutation[relative_placement] = commutation_relation - commutations[gate0.name, gate1.name] = gate_pair_commutation return commutations