mirror of https://github.com/Qiskit/qiskit.git
Remove consider-using-f-string lint rule and updates (#12423)
* remove consider-using-f-string lint rule and updates * reverting a latex update * f-string update based on review * Update qiskit/circuit/library/hamiltonian_gate.py Co-authored-by: Matthew Treinish <mtreinish@kortar.org> * Update qiskit/circuit/tools/pi_check.py Co-authored-by: Matthew Treinish <mtreinish@kortar.org> * Update qiskit/circuit/tools/pi_check.py Co-authored-by: Matthew Treinish <mtreinish@kortar.org> * updates after merge * Update qiskit/providers/models/backendproperties.py Co-authored-by: Julien Gacon <gaconju@gmail.com> * Update qiskit/synthesis/linear/cnot_synth.py Co-authored-by: Julien Gacon <gaconju@gmail.com> * updates from PR * latex fixes --------- Co-authored-by: Matthew Treinish <mtreinish@kortar.org> Co-authored-by: Julien Gacon <gaconju@gmail.com>
This commit is contained in:
parent
d4e795b431
commit
53667d167e
|
@ -218,7 +218,6 @@ disable = [
|
|||
# TODO(#9614): these were added in modern Pylint. Decide if we want to enable them. If so,
|
||||
# remove from here and fix the issues. Else, move it above this section and add a comment
|
||||
# with the rationale
|
||||
"consider-using-f-string",
|
||||
"no-member", # for dynamically created members
|
||||
"not-context-manager",
|
||||
"unnecessary-lambda-assignment", # do not want to implement
|
||||
|
|
|
@ -153,9 +153,9 @@ def _assemble_circuit(
|
|||
conditional_reg_idx = memory_slots + max_conditional_idx
|
||||
conversion_bfunc = QasmQobjInstruction(
|
||||
name="bfunc",
|
||||
mask="0x%X" % mask,
|
||||
mask="0x%X" % mask, # pylint: disable=consider-using-f-string
|
||||
relation="==",
|
||||
val="0x%X" % val,
|
||||
val="0x%X" % val, # pylint: disable=consider-using-f-string
|
||||
register=conditional_reg_idx,
|
||||
)
|
||||
instructions.append(conversion_bfunc)
|
||||
|
|
|
@ -152,7 +152,7 @@ def _assemble_experiments(
|
|||
# TODO: add other experimental header items (see circuit assembler)
|
||||
qobj_experiment_header = qobj.QobjExperimentHeader(
|
||||
memory_slots=max_memory_slot + 1, # Memory slots are 0 indexed
|
||||
name=sched.name or "Experiment-%d" % idx,
|
||||
name=sched.name or f"Experiment-{idx}",
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
|
@ -306,18 +306,11 @@ def _validate_meas_map(
|
|||
common_next = next_inst_qubits.intersection(meas_set)
|
||||
if common_instr_qubits and common_next:
|
||||
raise QiskitError(
|
||||
"Qubits {} and {} are in the same measurement grouping: {}. "
|
||||
f"Qubits {common_instr_qubits} and {common_next} are in the same measurement "
|
||||
f"grouping: {meas_map}. "
|
||||
"They must either be acquired at the same time, or disjointly"
|
||||
". Instead, they were acquired at times: {}-{} and "
|
||||
"{}-{}".format(
|
||||
common_instr_qubits,
|
||||
common_next,
|
||||
meas_map,
|
||||
inst[0][0],
|
||||
inst_end_time,
|
||||
next_inst_time,
|
||||
next_inst_time + next_inst[0][1],
|
||||
)
|
||||
f". Instead, they were acquired at times: {inst[0][0]}-{inst_end_time} and "
|
||||
f"{next_inst_time}-{next_inst_time + next_inst[0][1]}"
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -109,7 +109,7 @@ def _qobj_to_circuit_cals(qobj, pulse_lib):
|
|||
config = (tuple(gate["qubits"]), tuple(gate["params"]))
|
||||
cal = {
|
||||
config: pulse.Schedule(
|
||||
name="{} {} {}".format(gate["name"], str(gate["params"]), str(gate["qubits"]))
|
||||
name=f"{gate['name']} {str(gate['params'])} {str(gate['qubits'])}"
|
||||
)
|
||||
}
|
||||
for instruction in gate["instructions"]:
|
||||
|
|
|
@ -116,7 +116,7 @@ class BooleanExpression(ClassicalElement):
|
|||
|
||||
expr_obj = cls.__new__(cls)
|
||||
if not isfile(filename):
|
||||
raise FileNotFoundError("The file %s does not exists." % filename)
|
||||
raise FileNotFoundError(f"The file {filename} does not exists.")
|
||||
expr_obj._tweedledum_bool_expression = BoolFunction.from_dimacs_file(filename)
|
||||
|
||||
num_qubits = (
|
||||
|
|
|
@ -83,7 +83,7 @@ class ClassicalFunctionVisitor(ast.NodeVisitor):
|
|||
"""Uses ClassicalFunctionVisitor.bitops to extend self._network"""
|
||||
bitop = ClassicalFunctionVisitor.bitops.get(type(op))
|
||||
if not bitop:
|
||||
raise ClassicalFunctionParseError("Unknown binop.op %s" % op)
|
||||
raise ClassicalFunctionParseError(f"Unknown binop.op {op}")
|
||||
binop = getattr(self._network, bitop)
|
||||
|
||||
left_type, left_signal = values[0]
|
||||
|
@ -112,19 +112,19 @@ class ClassicalFunctionVisitor(ast.NodeVisitor):
|
|||
operand_type, operand_signal = self.visit(node.operand)
|
||||
if operand_type != "Int1":
|
||||
raise ClassicalFunctionCompilerTypeError(
|
||||
"UntaryOp.op %s only support operation on Int1s for now" % node.op
|
||||
f"UntaryOp.op {node.op} only support operation on Int1s for now"
|
||||
)
|
||||
bitop = ClassicalFunctionVisitor.bitops.get(type(node.op))
|
||||
if not bitop:
|
||||
raise ClassicalFunctionCompilerTypeError(
|
||||
"UntaryOp.op %s does not operate with Int1 type " % node.op
|
||||
f"UntaryOp.op {node.op} does not operate with Int1 type "
|
||||
)
|
||||
return "Int1", getattr(self._network, bitop)(operand_signal)
|
||||
|
||||
def visit_Name(self, node):
|
||||
"""Reduce variable names."""
|
||||
if node.id not in self.scopes[-1]:
|
||||
raise ClassicalFunctionParseError("out of scope: %s" % node.id)
|
||||
raise ClassicalFunctionParseError(f"out of scope: {node.id}")
|
||||
return self.scopes[-1][node.id]
|
||||
|
||||
def generic_visit(self, node):
|
||||
|
@ -143,7 +143,7 @@ class ClassicalFunctionVisitor(ast.NodeVisitor):
|
|||
),
|
||||
):
|
||||
return super().generic_visit(node)
|
||||
raise ClassicalFunctionParseError("Unknown node: %s" % type(node))
|
||||
raise ClassicalFunctionParseError(f"Unknown node: {type(node)}")
|
||||
|
||||
def extend_scope(self, args_node: _ast.arguments) -> None:
|
||||
"""Add the arguments to the scope"""
|
||||
|
|
|
@ -47,7 +47,7 @@ def _convert_tweedledum_operator(op):
|
|||
if op.kind() == "py_operator":
|
||||
return op.py_op()
|
||||
else:
|
||||
raise RuntimeError("Unrecognized operator: %s" % op.kind())
|
||||
raise RuntimeError(f"Unrecognized operator: {op.kind()}")
|
||||
|
||||
# TODO: need to deal with cbits too!
|
||||
if op.num_controls() > 0:
|
||||
|
|
|
@ -43,7 +43,7 @@ class Clbit(Bit):
|
|||
super().__init__(register, index)
|
||||
else:
|
||||
raise CircuitError(
|
||||
"Clbit needs a ClassicalRegister and %s was provided" % type(register).__name__
|
||||
f"Clbit needs a ClassicalRegister and {type(register).__name__} was provided"
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ class Delay(Instruction):
|
|||
unit: the unit of the duration. Must be ``"dt"`` or an SI-prefixed seconds unit.
|
||||
"""
|
||||
if unit not in {"s", "ms", "us", "ns", "ps", "dt"}:
|
||||
raise CircuitError("Unknown unit %s is specified." % unit)
|
||||
raise CircuitError(f"Unknown unit {unit} is specified.")
|
||||
|
||||
super().__init__("delay", 1, 0, params=[duration], unit=unit)
|
||||
|
||||
|
|
|
@ -35,8 +35,8 @@ def duration_in_dt(duration_in_sec: float, dt_in_sec: float) -> int:
|
|||
rounding_error = abs(duration_in_sec - res * dt_in_sec)
|
||||
if rounding_error > 1e-15:
|
||||
warnings.warn(
|
||||
"Duration is rounded to %d [dt] = %e [s] from %e [s]"
|
||||
% (res, res * dt_in_sec, duration_in_sec),
|
||||
f"Duration is rounded to {res:d} [dt] = {res * dt_in_sec:e} [s] "
|
||||
f"from {duration_in_sec:e} [s]",
|
||||
UserWarning,
|
||||
)
|
||||
return res
|
||||
|
|
|
@ -249,7 +249,7 @@ class EquivalenceLibrary:
|
|||
)
|
||||
node_map[decomp_basis] = decomp_basis_node
|
||||
|
||||
label = "{}\n{}".format(str(params), str(decomp) if num_qubits <= 5 else "...")
|
||||
label = f"{str(params)}\n{str(decomp) if num_qubits <= 5 else '...'}"
|
||||
graph.add_edge(
|
||||
node_map[basis],
|
||||
node_map[decomp_basis],
|
||||
|
@ -273,8 +273,8 @@ def _raise_if_param_mismatch(gate_params, circuit_parameters):
|
|||
if set(gate_parameters) != circuit_parameters:
|
||||
raise CircuitError(
|
||||
"Cannot add equivalence between circuit and gate "
|
||||
"of different parameters. Gate params: {}. "
|
||||
"Circuit params: {}.".format(gate_parameters, circuit_parameters)
|
||||
f"of different parameters. Gate params: {gate_parameters}. "
|
||||
f"Circuit params: {circuit_parameters}."
|
||||
)
|
||||
|
||||
|
||||
|
@ -282,10 +282,8 @@ def _raise_if_shape_mismatch(gate, circuit):
|
|||
if gate.num_qubits != circuit.num_qubits or gate.num_clbits != circuit.num_clbits:
|
||||
raise CircuitError(
|
||||
"Cannot add equivalence between circuit and gate "
|
||||
"of different shapes. Gate: {} qubits and {} clbits. "
|
||||
"Circuit: {} qubits and {} clbits.".format(
|
||||
gate.num_qubits, gate.num_clbits, circuit.num_qubits, circuit.num_clbits
|
||||
)
|
||||
f"of different shapes. Gate: {gate.num_qubits} qubits and {gate.num_clbits} clbits. "
|
||||
f"Circuit: {circuit.num_qubits} qubits and {circuit.num_clbits} clbits."
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -177,7 +177,7 @@ class Gate(Instruction):
|
|||
for arg in zip(*qargs):
|
||||
yield list(arg), []
|
||||
else:
|
||||
raise CircuitError("Not sure how to combine these qubit arguments:\n %s\n" % qargs)
|
||||
raise CircuitError(f"Not sure how to combine these qubit arguments:\n {qargs}\n")
|
||||
|
||||
def broadcast_arguments(self, qargs: list, cargs: list) -> Iterable[tuple[list, list]]:
|
||||
"""Validation and handling of the arguments and its relationship.
|
||||
|
@ -236,7 +236,7 @@ class Gate(Instruction):
|
|||
elif len(qargs) >= 3:
|
||||
return Gate._broadcast_3_or_more_args(qargs)
|
||||
else:
|
||||
raise CircuitError("This gate cannot handle %i arguments" % len(qargs))
|
||||
raise CircuitError(f"This gate cannot handle {len(qargs)} arguments")
|
||||
|
||||
def validate_parameter(self, parameter):
|
||||
"""Gate parameters should be int, float, or ParameterExpression"""
|
||||
|
|
|
@ -81,7 +81,7 @@ class Instruction(Operation):
|
|||
raise CircuitError("num_qubits and num_clbits must be integer.")
|
||||
if num_qubits < 0 or num_clbits < 0:
|
||||
raise CircuitError(
|
||||
"bad instruction dimensions: %d qubits, %d clbits." % num_qubits, num_clbits
|
||||
f"bad instruction dimensions: {num_qubits} qubits, {num_clbits} clbits."
|
||||
)
|
||||
self._name = name
|
||||
self._num_qubits = num_qubits
|
||||
|
@ -222,8 +222,9 @@ class Instruction(Operation):
|
|||
str: A representation of the Instruction instance with the name,
|
||||
number of qubits, classical bits and params( if any )
|
||||
"""
|
||||
return "Instruction(name='{}', num_qubits={}, num_clbits={}, params={})".format(
|
||||
self.name, self.num_qubits, self.num_clbits, self.params
|
||||
return (
|
||||
f"Instruction(name='{self.name}', num_qubits={self.num_qubits}, "
|
||||
f"num_clbits={self.num_clbits}, params={self.params})"
|
||||
)
|
||||
|
||||
def soft_compare(self, other: "Instruction") -> bool:
|
||||
|
@ -456,7 +457,7 @@ class Instruction(Operation):
|
|||
return AnnotatedOperation(self, InverseModifier())
|
||||
|
||||
if self.definition is None:
|
||||
raise CircuitError("inverse() not implemented for %s." % self.name)
|
||||
raise CircuitError(f"inverse() not implemented for {self.name}.")
|
||||
|
||||
from qiskit.circuit import Gate # pylint: disable=cyclic-import
|
||||
|
||||
|
|
|
@ -153,7 +153,7 @@ class LinearPauliRotations(FunctionalPauliRotations):
|
|||
if raise_on_failure:
|
||||
raise CircuitError(
|
||||
"Not enough qubits in the circuit, need at least "
|
||||
"{}.".format(self.num_state_qubits + 1)
|
||||
f"{self.num_state_qubits + 1}."
|
||||
)
|
||||
|
||||
return valid
|
||||
|
|
|
@ -122,7 +122,7 @@ class PiecewiseChebyshev(BlueprintCircuit):
|
|||
if raise_on_failure:
|
||||
raise CircuitError(
|
||||
"Not enough qubits in the circuit, need at least "
|
||||
"{}.".format(self.num_state_qubits + 1)
|
||||
f"{self.num_state_qubits + 1}."
|
||||
)
|
||||
|
||||
return valid
|
||||
|
|
|
@ -202,7 +202,7 @@ class PiecewiseLinearPauliRotations(FunctionalPauliRotations):
|
|||
if raise_on_failure:
|
||||
raise CircuitError(
|
||||
"Not enough qubits in the circuit, need at least "
|
||||
"{}.".format(self.num_state_qubits + 1)
|
||||
f"{self.num_state_qubits + 1}."
|
||||
)
|
||||
|
||||
if len(self.breakpoints) != len(self.slopes) or len(self.breakpoints) != len(self.offsets):
|
||||
|
|
|
@ -237,7 +237,7 @@ class PiecewisePolynomialPauliRotations(FunctionalPauliRotations):
|
|||
if raise_on_failure:
|
||||
raise CircuitError(
|
||||
"Not enough qubits in the circuit, need at least "
|
||||
"{}.".format(self.num_state_qubits + 1)
|
||||
f"{self.num_state_qubits + 1}."
|
||||
)
|
||||
|
||||
if len(self.breakpoints) != len(self.coeffs) + 1:
|
||||
|
|
|
@ -248,7 +248,7 @@ class PolynomialPauliRotations(FunctionalPauliRotations):
|
|||
if raise_on_failure:
|
||||
raise CircuitError(
|
||||
"Not enough qubits in the circuit, need at least "
|
||||
"{}.".format(self.num_state_qubits + 1)
|
||||
f"{self.num_state_qubits + 1}."
|
||||
)
|
||||
|
||||
return valid
|
||||
|
|
|
@ -154,8 +154,8 @@ class StatePreparation(Gate):
|
|||
# Raise if number of bits is greater than num_qubits
|
||||
if len(intstr) > self.num_qubits:
|
||||
raise QiskitError(
|
||||
"StatePreparation integer has %s bits, but this exceeds the"
|
||||
" number of qubits in the circuit, %s." % (len(intstr), self.num_qubits)
|
||||
f"StatePreparation integer has {len(intstr)} bits, but this exceeds the"
|
||||
f" number of qubits in the circuit, {self.num_qubits}."
|
||||
)
|
||||
|
||||
for qubit, bit in enumerate(intstr):
|
||||
|
@ -212,9 +212,9 @@ class StatePreparation(Gate):
|
|||
|
||||
if self.num_qubits != len(flat_qargs):
|
||||
raise QiskitError(
|
||||
"StatePreparation parameter vector has %d elements, therefore expects %s "
|
||||
"qubits. However, %s were provided."
|
||||
% (2**self.num_qubits, self.num_qubits, len(flat_qargs))
|
||||
f"StatePreparation parameter vector has {2**self.num_qubits}"
|
||||
f" elements, therefore expects {self.num_qubits} "
|
||||
f"qubits. However, {len(flat_qargs)} were provided."
|
||||
)
|
||||
yield flat_qargs, []
|
||||
|
||||
|
@ -226,8 +226,8 @@ class StatePreparation(Gate):
|
|||
if parameter in ["0", "1", "+", "-", "l", "r"]:
|
||||
return parameter
|
||||
raise CircuitError(
|
||||
"invalid param label {} for instruction {}. Label should be "
|
||||
"0, 1, +, -, l, or r ".format(type(parameter), self.name)
|
||||
f"invalid param label {type(parameter)} for instruction {self.name}. Label should be "
|
||||
"0, 1, +, -, l, or r "
|
||||
)
|
||||
|
||||
# StatePreparation instruction parameter can be int, float, and complex.
|
||||
|
|
|
@ -74,7 +74,7 @@ class GraphState(QuantumCircuit):
|
|||
raise CircuitError("The adjacency matrix must be symmetric.")
|
||||
|
||||
num_qubits = len(adjacency_matrix)
|
||||
circuit = QuantumCircuit(num_qubits, name="graph: %s" % (adjacency_matrix))
|
||||
circuit = QuantumCircuit(num_qubits, name=f"graph: {adjacency_matrix}")
|
||||
|
||||
circuit.h(range(num_qubits))
|
||||
for i in range(num_qubits):
|
||||
|
|
|
@ -103,8 +103,7 @@ class HamiltonianGate(Gate):
|
|||
time = float(self.params[1])
|
||||
except TypeError as ex:
|
||||
raise TypeError(
|
||||
"Unable to generate Unitary matrix for "
|
||||
"unbound t parameter {}".format(self.params[1])
|
||||
f"Unable to generate Unitary matrix for unbound t parameter {self.params[1]}"
|
||||
) from ex
|
||||
arr = scipy.linalg.expm(-1j * self.params[0] * time)
|
||||
dtype = complex if dtype is None else dtype
|
||||
|
|
|
@ -82,7 +82,7 @@ class HiddenLinearFunction(QuantumCircuit):
|
|||
raise CircuitError("The adjacency matrix must be symmetric.")
|
||||
|
||||
num_qubits = len(adjacency_matrix)
|
||||
circuit = QuantumCircuit(num_qubits, name="hlf: %s" % adjacency_matrix)
|
||||
circuit = QuantumCircuit(num_qubits, name=f"hlf: {adjacency_matrix}")
|
||||
|
||||
circuit.h(range(num_qubits))
|
||||
for i in range(num_qubits):
|
||||
|
|
|
@ -441,9 +441,8 @@ class NLocal(BlueprintCircuit):
|
|||
):
|
||||
raise ValueError(
|
||||
"The length of ordered parameters must be equal to the number of "
|
||||
"settable parameters in the circuit ({}), but is {}".format(
|
||||
self.num_parameters_settable, len(parameters)
|
||||
)
|
||||
f"settable parameters in the circuit ({self.num_parameters_settable}),"
|
||||
f" but is {len(parameters)}"
|
||||
)
|
||||
self._ordered_parameters = parameters
|
||||
self._invalidate()
|
||||
|
|
|
@ -97,20 +97,18 @@ class QAOAAnsatz(EvolvedOperatorAnsatz):
|
|||
valid = False
|
||||
if raise_on_failure:
|
||||
raise ValueError(
|
||||
"The number of qubits of the initial state {} does not match "
|
||||
"the number of qubits of the cost operator {}".format(
|
||||
self.initial_state.num_qubits, self.num_qubits
|
||||
)
|
||||
f"The number of qubits of the initial state {self.initial_state.num_qubits}"
|
||||
" does not match "
|
||||
f"the number of qubits of the cost operator {self.num_qubits}"
|
||||
)
|
||||
|
||||
if self.mixer_operator is not None and self.mixer_operator.num_qubits != self.num_qubits:
|
||||
valid = False
|
||||
if raise_on_failure:
|
||||
raise ValueError(
|
||||
"The number of qubits of the mixer {} does not match "
|
||||
"the number of qubits of the cost operator {}".format(
|
||||
self.mixer_operator.num_qubits, self.num_qubits
|
||||
)
|
||||
f"The number of qubits of the mixer {self.mixer_operator.num_qubits}"
|
||||
f" does not match "
|
||||
f"the number of qubits of the cost operator {self.num_qubits}"
|
||||
)
|
||||
|
||||
return valid
|
||||
|
|
|
@ -112,8 +112,6 @@ def _check_unitary(circuit):
|
|||
for instruction in circuit.data:
|
||||
if not isinstance(instruction.operation, (Gate, Barrier)):
|
||||
raise CircuitError(
|
||||
(
|
||||
"One or more instructions cannot be converted to"
|
||||
' a gate. "{}" is not a gate instruction'
|
||||
).format(instruction.operation.name)
|
||||
"One or more instructions cannot be converted to"
|
||||
f' a gate. "{instruction.operation.name}" is not a gate instruction'
|
||||
)
|
||||
|
|
|
@ -344,7 +344,7 @@ def _generate_gray_code(num_bits):
|
|||
result = [0]
|
||||
for i in range(num_bits):
|
||||
result += [x + 2**i for x in reversed(result)]
|
||||
return [format(x, "0%sb" % num_bits) for x in result]
|
||||
return [format(x, f"0{num_bits}b") for x in result]
|
||||
|
||||
|
||||
def _gray_code_chain(q, num_ctrl_qubits, gate):
|
||||
|
|
|
@ -109,8 +109,8 @@ class Parameter(ParameterExpression):
|
|||
if allow_unknown_parameters:
|
||||
return self
|
||||
raise CircuitError(
|
||||
"Cannot bind Parameters ({}) not present in "
|
||||
"expression.".format([str(p) for p in parameter_map])
|
||||
f"Cannot bind Parameters ({[str(p) for p in parameter_map]}) not present in "
|
||||
"expression."
|
||||
)
|
||||
|
||||
@property
|
||||
|
|
|
@ -140,7 +140,7 @@ class ParameterExpression:
|
|||
raise ZeroDivisionError(
|
||||
"Binding provided for expression "
|
||||
"results in division by zero "
|
||||
"(Expression: {}, Bindings: {}).".format(self, parameter_values)
|
||||
f"(Expression: {self}, Bindings: {parameter_values})."
|
||||
)
|
||||
|
||||
return ParameterExpression(free_parameter_symbols, bound_symbol_expr)
|
||||
|
@ -199,8 +199,8 @@ class ParameterExpression:
|
|||
unknown_parameters = parameters - self.parameters
|
||||
if unknown_parameters:
|
||||
raise CircuitError(
|
||||
"Cannot bind Parameters ({}) not present in "
|
||||
"expression.".format([str(p) for p in unknown_parameters])
|
||||
f"Cannot bind Parameters ({[str(p) for p in unknown_parameters]}) not present in "
|
||||
"expression."
|
||||
)
|
||||
|
||||
def _raise_if_passed_nan(self, parameter_values):
|
||||
|
@ -404,8 +404,8 @@ class ParameterExpression:
|
|||
except (TypeError, RuntimeError) as exc:
|
||||
if self.parameters:
|
||||
raise TypeError(
|
||||
"ParameterExpression with unbound parameters ({}) "
|
||||
"cannot be cast to a complex.".format(self.parameters)
|
||||
f"ParameterExpression with unbound parameters ({self.parameters}) "
|
||||
"cannot be cast to a complex."
|
||||
) from None
|
||||
raise TypeError("could not cast expression to complex") from exc
|
||||
|
||||
|
@ -416,8 +416,8 @@ class ParameterExpression:
|
|||
except (TypeError, RuntimeError) as exc:
|
||||
if self.parameters:
|
||||
raise TypeError(
|
||||
"ParameterExpression with unbound parameters ({}) "
|
||||
"cannot be cast to a float.".format(self.parameters)
|
||||
f"ParameterExpression with unbound parameters ({self.parameters}) "
|
||||
"cannot be cast to a float."
|
||||
) from None
|
||||
# In symengine, if an expression was complex at any time, its type is likely to have
|
||||
# stayed "complex" even when the imaginary part symbolically (i.e. exactly)
|
||||
|
@ -436,8 +436,8 @@ class ParameterExpression:
|
|||
except RuntimeError as exc:
|
||||
if self.parameters:
|
||||
raise TypeError(
|
||||
"ParameterExpression with unbound parameters ({}) "
|
||||
"cannot be cast to an int.".format(self.parameters)
|
||||
f"ParameterExpression with unbound parameters ({self.parameters}) "
|
||||
"cannot be cast to an int."
|
||||
) from None
|
||||
raise TypeError("could not cast expression to int") from exc
|
||||
|
||||
|
|
|
@ -1067,8 +1067,9 @@ class QuantumCircuit:
|
|||
|
||||
if not valid_reg_size:
|
||||
raise CircuitError(
|
||||
"Circuit args must be Registers or integers. (%s '%s' was "
|
||||
"provided)" % ([type(reg).__name__ for reg in regs], regs)
|
||||
"Circuit args must be Registers or integers. ("
|
||||
f"{[type(reg).__name__ for reg in regs]} '{regs}' was "
|
||||
"provided)"
|
||||
)
|
||||
|
||||
regs = tuple(int(reg) for reg in regs) # cast to int
|
||||
|
@ -1659,7 +1660,7 @@ class QuantumCircuit:
|
|||
raise CircuitError(
|
||||
"Cannot raise a parameterized circuit to a non-positive power "
|
||||
"or matrix-power, please bind the free parameters: "
|
||||
"{}".format(self.parameters)
|
||||
f"{self.parameters}"
|
||||
)
|
||||
|
||||
try:
|
||||
|
@ -2957,14 +2958,14 @@ class QuantumCircuit:
|
|||
raise CircuitError(
|
||||
"QuantumCircuit parameters can be Registers or Integers."
|
||||
" If Integers, up to 2 arguments. QuantumCircuit was called"
|
||||
" with %s." % (regs,)
|
||||
f" with {(regs,)}."
|
||||
)
|
||||
|
||||
for register in regs:
|
||||
if isinstance(register, Register) and any(
|
||||
register.name == reg.name for reg in self.qregs + self.cregs
|
||||
):
|
||||
raise CircuitError('register name "%s" already exists' % register.name)
|
||||
raise CircuitError(f'register name "{register.name}" already exists')
|
||||
|
||||
if isinstance(register, AncillaRegister):
|
||||
for bit in register:
|
||||
|
@ -3020,7 +3021,7 @@ class QuantumCircuit:
|
|||
else:
|
||||
raise CircuitError(
|
||||
"Expected an instance of Qubit, Clbit, or "
|
||||
"AncillaQubit, but was passed {}".format(bit)
|
||||
f"AncillaQubit, but was passed {bit}"
|
||||
)
|
||||
|
||||
def find_bit(self, bit: Bit) -> BitLocations:
|
||||
|
|
|
@ -43,7 +43,7 @@ class Qubit(Bit):
|
|||
super().__init__(register, index)
|
||||
else:
|
||||
raise CircuitError(
|
||||
"Qubit needs a QuantumRegister and %s was provided" % type(register).__name__
|
||||
f"Qubit needs a QuantumRegister and {type(register).__name__} was provided"
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -67,7 +67,7 @@ class Register:
|
|||
if (size, bits) == (None, None) or (size is not None and bits is not None):
|
||||
raise CircuitError(
|
||||
"Exactly one of the size or bits arguments can be "
|
||||
"provided. Provided size=%s bits=%s." % (size, bits)
|
||||
f"provided. Provided size={size} bits={bits}."
|
||||
)
|
||||
|
||||
# validate (or cast) size
|
||||
|
@ -81,20 +81,18 @@ class Register:
|
|||
|
||||
if not valid_size:
|
||||
raise CircuitError(
|
||||
"Register size must be an integer. (%s '%s' was provided)"
|
||||
% (type(size).__name__, size)
|
||||
f"Register size must be an integer. ({type(size).__name__} '{size}' was provided)"
|
||||
)
|
||||
size = int(size) # cast to int
|
||||
|
||||
if size < 0:
|
||||
raise CircuitError(
|
||||
"Register size must be non-negative (%s '%s' was provided)"
|
||||
% (type(size).__name__, size)
|
||||
f"Register size must be non-negative ({type(size).__name__} '{size}' was provided)"
|
||||
)
|
||||
|
||||
# validate (or cast) name
|
||||
if name is None:
|
||||
name = "%s%i" % (self.prefix, next(self.instances_counter))
|
||||
name = f"{self.prefix}{next(self.instances_counter)}"
|
||||
else:
|
||||
try:
|
||||
name = str(name)
|
||||
|
@ -108,7 +106,7 @@ class Register:
|
|||
self._size = size
|
||||
|
||||
self._hash = hash((type(self), self._name, self._size))
|
||||
self._repr = "%s(%d, '%s')" % (self.__class__.__qualname__, self.size, self.name)
|
||||
self._repr = f"{self.__class__.__qualname__}({self.size}, '{self.name}')"
|
||||
if bits is not None:
|
||||
# check duplicated bits
|
||||
if self._size != len(set(bits)):
|
||||
|
|
|
@ -104,9 +104,9 @@ def pi_check(inpt, eps=1e-9, output="text", ndigits=None):
|
|||
if power[0].shape[0]:
|
||||
if output == "qasm":
|
||||
if ndigits is None:
|
||||
str_out = "{}".format(single_inpt)
|
||||
str_out = str(single_inpt)
|
||||
else:
|
||||
str_out = "{:.{}g}".format(single_inpt, ndigits)
|
||||
str_out = f"{single_inpt:.{ndigits}g}"
|
||||
elif output == "latex":
|
||||
str_out = f"{neg_str}{pi}^{power[0][0] + 2}"
|
||||
elif output == "mpl":
|
||||
|
@ -119,9 +119,9 @@ def pi_check(inpt, eps=1e-9, output="text", ndigits=None):
|
|||
# multiple or power of pi, since no fractions will exceed MAX_FRAC * pi
|
||||
if abs(single_inpt) >= (MAX_FRAC * np.pi):
|
||||
if ndigits is None:
|
||||
str_out = "{}".format(single_inpt)
|
||||
str_out = str(single_inpt)
|
||||
else:
|
||||
str_out = "{:.{}g}".format(single_inpt, ndigits)
|
||||
str_out = f"{single_inpt:.{ndigits}g}"
|
||||
return str_out
|
||||
|
||||
# Fourth check is for fractions for 1*pi in the numer and any
|
||||
|
|
|
@ -34,7 +34,7 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
def _log_assembly_time(start_time, end_time):
|
||||
log_msg = "Total Assembly Time - %.5f (ms)" % ((end_time - start_time) * 1000)
|
||||
log_msg = f"Total Assembly Time - {((end_time - start_time) * 1000):.5f} (ms)"
|
||||
logger.info(log_msg)
|
||||
|
||||
|
||||
|
@ -311,8 +311,8 @@ def _parse_common_args(
|
|||
raise QiskitError("Argument 'shots' should be of type 'int'")
|
||||
elif max_shots and max_shots < shots:
|
||||
raise QiskitError(
|
||||
"Number of shots specified: %s exceeds max_shots property of the "
|
||||
"backend: %s." % (shots, max_shots)
|
||||
f"Number of shots specified: {max_shots} exceeds max_shots property of the "
|
||||
f"backend: {max_shots}."
|
||||
)
|
||||
|
||||
dynamic_reprate_enabled = getattr(backend_config, "dynamic_reprate_enabled", False)
|
||||
|
@ -397,9 +397,8 @@ def _check_lo_freqs(
|
|||
raise QiskitError(f"Each element of {lo_type} LO range must be a 2d list.")
|
||||
if freq < freq_range[0] or freq > freq_range[1]:
|
||||
raise QiskitError(
|
||||
"Qubit {} {} LO frequency is {}. The range is [{}, {}].".format(
|
||||
i, lo_type, freq, freq_range[0], freq_range[1]
|
||||
)
|
||||
f"Qubit {i} {lo_type} LO frequency is {freq}. "
|
||||
f"The range is [{freq_range[0]}, {freq_range[1]}]."
|
||||
)
|
||||
|
||||
|
||||
|
@ -429,9 +428,8 @@ def _parse_pulse_args(
|
|||
|
||||
if meas_level not in getattr(backend_config, "meas_levels", [MeasLevel.CLASSIFIED]):
|
||||
raise QiskitError(
|
||||
("meas_level = {} not supported for backend {}, only {} is supported").format(
|
||||
meas_level, backend_config.backend_name, backend_config.meas_levels
|
||||
)
|
||||
f"meas_level = {meas_level} not supported for backend "
|
||||
f"{backend_config.backend_name}, only {backend_config.meas_levels} is supported"
|
||||
)
|
||||
|
||||
meas_map = meas_map or getattr(backend_config, "meas_map", None)
|
||||
|
@ -522,14 +520,12 @@ def _parse_rep_delay(
|
|||
if rep_delay_range is not None and isinstance(rep_delay_range, list):
|
||||
if len(rep_delay_range) != 2:
|
||||
raise QiskitError(
|
||||
"Backend rep_delay_range {} must be a list with two entries.".format(
|
||||
rep_delay_range
|
||||
)
|
||||
f"Backend rep_delay_range {rep_delay_range} must be a list with two entries."
|
||||
)
|
||||
if not rep_delay_range[0] <= rep_delay <= rep_delay_range[1]:
|
||||
raise QiskitError(
|
||||
"Supplied rep delay {} not in the supported "
|
||||
"backend range {}".format(rep_delay, rep_delay_range)
|
||||
f"Supplied rep delay {rep_delay} not in the supported "
|
||||
f"backend range {rep_delay_range}"
|
||||
)
|
||||
rep_delay = rep_delay * 1e6 # convert sec to μs
|
||||
|
||||
|
|
|
@ -31,7 +31,7 @@ logger = logging.getLogger(__name__)
|
|||
|
||||
|
||||
def _log_schedule_time(start_time, end_time):
|
||||
log_msg = "Total Scheduling Time - %.5f (ms)" % ((end_time - start_time) * 1000)
|
||||
log_msg = f"Total Scheduling Time - {((end_time - start_time) * 1000):.5f} (ms)"
|
||||
logger.info(log_msg)
|
||||
|
||||
|
||||
|
|
|
@ -405,7 +405,7 @@ def _check_circuits_coupling_map(circuits, cmap, backend):
|
|||
|
||||
|
||||
def _log_transpile_time(start_time, end_time):
|
||||
log_msg = "Total Transpile Time - %.5f (ms)" % ((end_time - start_time) * 1000)
|
||||
log_msg = f"Total Transpile Time - {((end_time - start_time) * 1000):.5f} (ms)"
|
||||
logger.info(log_msg)
|
||||
|
||||
|
||||
|
@ -476,7 +476,7 @@ def _parse_output_name(output_name, circuits):
|
|||
else:
|
||||
raise TranspilerError(
|
||||
"The parameter output_name should be a string or a"
|
||||
"list of strings: %s was used." % type(output_name)
|
||||
f"list of strings: {type(output_name)} was used."
|
||||
)
|
||||
else:
|
||||
return [circuit.name for circuit in circuits]
|
||||
|
|
|
@ -64,10 +64,8 @@ def circuit_to_gate(circuit, parameter_map=None, equivalence_library=None, label
|
|||
for instruction in circuit.data:
|
||||
if not _check_is_gate(instruction.operation):
|
||||
raise QiskitError(
|
||||
(
|
||||
"One or more instructions cannot be converted to"
|
||||
' a gate. "{}" is not a gate instruction'
|
||||
).format(instruction.operation.name)
|
||||
"One or more instructions cannot be converted to"
|
||||
f' a gate. "{instruction.operation.name}" is not a gate instruction'
|
||||
)
|
||||
|
||||
if parameter_map is None:
|
||||
|
@ -77,10 +75,8 @@ def circuit_to_gate(circuit, parameter_map=None, equivalence_library=None, label
|
|||
|
||||
if parameter_dict.keys() != circuit.parameters:
|
||||
raise QiskitError(
|
||||
(
|
||||
"parameter_map should map all circuit parameters. "
|
||||
"Circuit parameters: {}, parameter_map: {}"
|
||||
).format(circuit.parameters, parameter_dict)
|
||||
"parameter_map should map all circuit parameters. "
|
||||
f"Circuit parameters: {circuit.parameters}, parameter_map: {parameter_dict}"
|
||||
)
|
||||
|
||||
gate = Gate(
|
||||
|
|
|
@ -89,10 +89,8 @@ def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None
|
|||
|
||||
if parameter_dict.keys() != circuit.parameters:
|
||||
raise QiskitError(
|
||||
(
|
||||
"parameter_map should map all circuit parameters. "
|
||||
"Circuit parameters: {}, parameter_map: {}"
|
||||
).format(circuit.parameters, parameter_dict)
|
||||
"parameter_map should map all circuit parameters. "
|
||||
f"Circuit parameters: {circuit.parameters}, parameter_map: {parameter_dict}"
|
||||
)
|
||||
|
||||
out_instruction = Instruction(
|
||||
|
|
|
@ -271,7 +271,7 @@ class DAGCircuit:
|
|||
|
||||
duplicate_qubits = set(self.qubits).intersection(qubits)
|
||||
if duplicate_qubits:
|
||||
raise DAGCircuitError("duplicate qubits %s" % duplicate_qubits)
|
||||
raise DAGCircuitError(f"duplicate qubits {duplicate_qubits}")
|
||||
|
||||
for qubit in qubits:
|
||||
self.qubits.append(qubit)
|
||||
|
@ -285,7 +285,7 @@ class DAGCircuit:
|
|||
|
||||
duplicate_clbits = set(self.clbits).intersection(clbits)
|
||||
if duplicate_clbits:
|
||||
raise DAGCircuitError("duplicate clbits %s" % duplicate_clbits)
|
||||
raise DAGCircuitError(f"duplicate clbits {duplicate_clbits}")
|
||||
|
||||
for clbit in clbits:
|
||||
self.clbits.append(clbit)
|
||||
|
@ -297,7 +297,7 @@ class DAGCircuit:
|
|||
if not isinstance(qreg, QuantumRegister):
|
||||
raise DAGCircuitError("not a QuantumRegister instance.")
|
||||
if qreg.name in self.qregs:
|
||||
raise DAGCircuitError("duplicate register %s" % qreg.name)
|
||||
raise DAGCircuitError(f"duplicate register {qreg.name}")
|
||||
self.qregs[qreg.name] = qreg
|
||||
existing_qubits = set(self.qubits)
|
||||
for j in range(qreg.size):
|
||||
|
@ -315,7 +315,7 @@ class DAGCircuit:
|
|||
if not isinstance(creg, ClassicalRegister):
|
||||
raise DAGCircuitError("not a ClassicalRegister instance.")
|
||||
if creg.name in self.cregs:
|
||||
raise DAGCircuitError("duplicate register %s" % creg.name)
|
||||
raise DAGCircuitError(f"duplicate register {creg.name}")
|
||||
self.cregs[creg.name] = creg
|
||||
existing_clbits = set(self.clbits)
|
||||
for j in range(creg.size):
|
||||
|
@ -451,17 +451,17 @@ class DAGCircuit:
|
|||
"""
|
||||
if any(not isinstance(clbit, Clbit) for clbit in clbits):
|
||||
raise DAGCircuitError(
|
||||
"clbits not of type Clbit: %s" % [b for b in clbits if not isinstance(b, Clbit)]
|
||||
f"clbits not of type Clbit: {[b for b in clbits if not isinstance(b, Clbit)]}"
|
||||
)
|
||||
|
||||
clbits = set(clbits)
|
||||
unknown_clbits = clbits.difference(self.clbits)
|
||||
if unknown_clbits:
|
||||
raise DAGCircuitError("clbits not in circuit: %s" % unknown_clbits)
|
||||
raise DAGCircuitError(f"clbits not in circuit: {unknown_clbits}")
|
||||
|
||||
busy_clbits = {bit for bit in clbits if not self._is_wire_idle(bit)}
|
||||
if busy_clbits:
|
||||
raise DAGCircuitError("clbits not idle: %s" % busy_clbits)
|
||||
raise DAGCircuitError(f"clbits not idle: {busy_clbits}")
|
||||
|
||||
# remove any references to bits
|
||||
cregs_to_remove = {creg for creg in self.cregs.values() if not clbits.isdisjoint(creg)}
|
||||
|
@ -487,13 +487,13 @@ class DAGCircuit:
|
|||
"""
|
||||
if any(not isinstance(creg, ClassicalRegister) for creg in cregs):
|
||||
raise DAGCircuitError(
|
||||
"cregs not of type ClassicalRegister: %s"
|
||||
% [r for r in cregs if not isinstance(r, ClassicalRegister)]
|
||||
"cregs not of type ClassicalRegister: "
|
||||
f"{[r for r in cregs if not isinstance(r, ClassicalRegister)]}"
|
||||
)
|
||||
|
||||
unknown_cregs = set(cregs).difference(self.cregs.values())
|
||||
if unknown_cregs:
|
||||
raise DAGCircuitError("cregs not in circuit: %s" % unknown_cregs)
|
||||
raise DAGCircuitError(f"cregs not in circuit: {unknown_cregs}")
|
||||
|
||||
for creg in cregs:
|
||||
del self.cregs[creg.name]
|
||||
|
@ -517,17 +517,17 @@ class DAGCircuit:
|
|||
"""
|
||||
if any(not isinstance(qubit, Qubit) for qubit in qubits):
|
||||
raise DAGCircuitError(
|
||||
"qubits not of type Qubit: %s" % [b for b in qubits if not isinstance(b, Qubit)]
|
||||
f"qubits not of type Qubit: {[b for b in qubits if not isinstance(b, Qubit)]}"
|
||||
)
|
||||
|
||||
qubits = set(qubits)
|
||||
unknown_qubits = qubits.difference(self.qubits)
|
||||
if unknown_qubits:
|
||||
raise DAGCircuitError("qubits not in circuit: %s" % unknown_qubits)
|
||||
raise DAGCircuitError(f"qubits not in circuit: {unknown_qubits}")
|
||||
|
||||
busy_qubits = {bit for bit in qubits if not self._is_wire_idle(bit)}
|
||||
if busy_qubits:
|
||||
raise DAGCircuitError("qubits not idle: %s" % busy_qubits)
|
||||
raise DAGCircuitError(f"qubits not idle: {busy_qubits}")
|
||||
|
||||
# remove any references to bits
|
||||
qregs_to_remove = {qreg for qreg in self.qregs.values() if not qubits.isdisjoint(qreg)}
|
||||
|
@ -553,13 +553,13 @@ class DAGCircuit:
|
|||
"""
|
||||
if any(not isinstance(qreg, QuantumRegister) for qreg in qregs):
|
||||
raise DAGCircuitError(
|
||||
"qregs not of type QuantumRegister: %s"
|
||||
% [r for r in qregs if not isinstance(r, QuantumRegister)]
|
||||
f"qregs not of type QuantumRegister: "
|
||||
f"{[r for r in qregs if not isinstance(r, QuantumRegister)]}"
|
||||
)
|
||||
|
||||
unknown_qregs = set(qregs).difference(self.qregs.values())
|
||||
if unknown_qregs:
|
||||
raise DAGCircuitError("qregs not in circuit: %s" % unknown_qregs)
|
||||
raise DAGCircuitError(f"qregs not in circuit: {unknown_qregs}")
|
||||
|
||||
for qreg in qregs:
|
||||
del self.qregs[qreg.name]
|
||||
|
@ -581,13 +581,13 @@ class DAGCircuit:
|
|||
DAGCircuitError: the wire is not in the circuit.
|
||||
"""
|
||||
if wire not in self._wires:
|
||||
raise DAGCircuitError("wire %s not in circuit" % wire)
|
||||
raise DAGCircuitError(f"wire {wire} not in circuit")
|
||||
|
||||
try:
|
||||
child = next(self.successors(self.input_map[wire]))
|
||||
except StopIteration as e:
|
||||
raise DAGCircuitError(
|
||||
"Invalid dagcircuit input node %s has no output" % self.input_map[wire]
|
||||
f"Invalid dagcircuit input node {self.input_map[wire]} has no output"
|
||||
) from e
|
||||
return child is self.output_map[wire]
|
||||
|
||||
|
@ -950,12 +950,11 @@ class DAGCircuit:
|
|||
# the mapped wire should already exist
|
||||
if m_wire not in dag.output_map:
|
||||
raise DAGCircuitError(
|
||||
"wire %s[%d] not in self" % (m_wire.register.name, m_wire.index)
|
||||
f"wire {m_wire.register.name}[{m_wire.index}] not in self"
|
||||
)
|
||||
if nd.wire not in other._wires:
|
||||
raise DAGCircuitError(
|
||||
"inconsistent wire type for %s[%d] in other"
|
||||
% (nd.register.name, nd.wire.index)
|
||||
f"inconsistent wire type for {nd.register.name}[{nd.wire.index}] in other"
|
||||
)
|
||||
# If it's a Var wire, we already checked that it exists in the destination.
|
||||
elif isinstance(nd, DAGOutNode):
|
||||
|
@ -974,7 +973,7 @@ class DAGCircuit:
|
|||
op.target = variable_mapper.map_target(op.target)
|
||||
dag.apply_operation_back(op, m_qargs, m_cargs, check=False)
|
||||
else:
|
||||
raise DAGCircuitError("bad node type %s" % type(nd))
|
||||
raise DAGCircuitError(f"bad node type {type(nd)}")
|
||||
|
||||
if not inplace:
|
||||
return dag
|
||||
|
@ -1632,10 +1631,10 @@ class DAGCircuit:
|
|||
|
||||
if node.op.num_qubits != op.num_qubits or node.op.num_clbits != op.num_clbits:
|
||||
raise DAGCircuitError(
|
||||
"Cannot replace node of width ({} qubits, {} clbits) with "
|
||||
"operation of mismatched width ({} qubits, {} clbits).".format(
|
||||
node.op.num_qubits, node.op.num_clbits, op.num_qubits, op.num_clbits
|
||||
)
|
||||
f"Cannot replace node of width ({node.op.num_qubits} qubits, "
|
||||
f"{node.op.num_clbits} clbits) with "
|
||||
f"operation of mismatched width ({op.num_qubits} qubits, "
|
||||
f"{op.num_clbits} clbits)."
|
||||
)
|
||||
|
||||
# This might include wires that are inherent to the node, like in its `condition` or
|
||||
|
@ -1953,8 +1952,8 @@ class DAGCircuit:
|
|||
"""
|
||||
if not isinstance(node, DAGOpNode):
|
||||
raise DAGCircuitError(
|
||||
'The method remove_op_node only works on DAGOpNodes. A "%s" '
|
||||
"node type was wrongly provided." % type(node)
|
||||
f'The method remove_op_node only works on DAGOpNodes. A "{type(node)}" '
|
||||
"node type was wrongly provided."
|
||||
)
|
||||
|
||||
self._multi_graph.remove_node_retain_edges(
|
||||
|
@ -2182,7 +2181,7 @@ class DAGCircuit:
|
|||
current_node = self.input_map.get(wire, None)
|
||||
|
||||
if not current_node:
|
||||
raise DAGCircuitError("The given wire %s is not present in the circuit" % str(wire))
|
||||
raise DAGCircuitError(f"The given wire {str(wire)} is not present in the circuit")
|
||||
|
||||
more_nodes = True
|
||||
while more_nodes:
|
||||
|
|
|
@ -187,7 +187,7 @@ class DAGDependency:
|
|||
|
||||
duplicate_qubits = set(self.qubits).intersection(qubits)
|
||||
if duplicate_qubits:
|
||||
raise DAGDependencyError("duplicate qubits %s" % duplicate_qubits)
|
||||
raise DAGDependencyError(f"duplicate qubits {duplicate_qubits}")
|
||||
|
||||
self.qubits.extend(qubits)
|
||||
|
||||
|
@ -198,7 +198,7 @@ class DAGDependency:
|
|||
|
||||
duplicate_clbits = set(self.clbits).intersection(clbits)
|
||||
if duplicate_clbits:
|
||||
raise DAGDependencyError("duplicate clbits %s" % duplicate_clbits)
|
||||
raise DAGDependencyError(f"duplicate clbits {duplicate_clbits}")
|
||||
|
||||
self.clbits.extend(clbits)
|
||||
|
||||
|
@ -207,7 +207,7 @@ class DAGDependency:
|
|||
if not isinstance(qreg, QuantumRegister):
|
||||
raise DAGDependencyError("not a QuantumRegister instance.")
|
||||
if qreg.name in self.qregs:
|
||||
raise DAGDependencyError("duplicate register %s" % qreg.name)
|
||||
raise DAGDependencyError(f"duplicate register {qreg.name}")
|
||||
self.qregs[qreg.name] = qreg
|
||||
existing_qubits = set(self.qubits)
|
||||
for j in range(qreg.size):
|
||||
|
@ -219,7 +219,7 @@ class DAGDependency:
|
|||
if not isinstance(creg, ClassicalRegister):
|
||||
raise DAGDependencyError("not a ClassicalRegister instance.")
|
||||
if creg.name in self.cregs:
|
||||
raise DAGDependencyError("duplicate register %s" % creg.name)
|
||||
raise DAGDependencyError(f"duplicate register {creg.name}")
|
||||
self.cregs[creg.name] = creg
|
||||
existing_clbits = set(self.clbits)
|
||||
for j in range(creg.size):
|
||||
|
|
|
@ -247,7 +247,7 @@ class _DAGDependencyV2:
|
|||
|
||||
duplicate_qubits = set(self.qubits).intersection(qubits)
|
||||
if duplicate_qubits:
|
||||
raise DAGDependencyError("duplicate qubits %s" % duplicate_qubits)
|
||||
raise DAGDependencyError(f"duplicate qubits {duplicate_qubits}")
|
||||
|
||||
for qubit in qubits:
|
||||
self.qubits.append(qubit)
|
||||
|
@ -260,7 +260,7 @@ class _DAGDependencyV2:
|
|||
|
||||
duplicate_clbits = set(self.clbits).intersection(clbits)
|
||||
if duplicate_clbits:
|
||||
raise DAGDependencyError("duplicate clbits %s" % duplicate_clbits)
|
||||
raise DAGDependencyError(f"duplicate clbits {duplicate_clbits}")
|
||||
|
||||
for clbit in clbits:
|
||||
self.clbits.append(clbit)
|
||||
|
@ -271,7 +271,7 @@ class _DAGDependencyV2:
|
|||
if not isinstance(qreg, QuantumRegister):
|
||||
raise DAGDependencyError("not a QuantumRegister instance.")
|
||||
if qreg.name in self.qregs:
|
||||
raise DAGDependencyError("duplicate register %s" % qreg.name)
|
||||
raise DAGDependencyError(f"duplicate register {qreg.name}")
|
||||
self.qregs[qreg.name] = qreg
|
||||
existing_qubits = set(self.qubits)
|
||||
for j in range(qreg.size):
|
||||
|
@ -288,7 +288,7 @@ class _DAGDependencyV2:
|
|||
if not isinstance(creg, ClassicalRegister):
|
||||
raise DAGDependencyError("not a ClassicalRegister instance.")
|
||||
if creg.name in self.cregs:
|
||||
raise DAGDependencyError("duplicate register %s" % creg.name)
|
||||
raise DAGDependencyError(f"duplicate register {creg.name}")
|
||||
self.cregs[creg.name] = creg
|
||||
existing_clbits = set(self.clbits)
|
||||
for j in range(creg.size):
|
||||
|
|
|
@ -83,7 +83,7 @@ class DAGDepNode:
|
|||
def op(self):
|
||||
"""Returns the Instruction object corresponding to the op for the node, else None"""
|
||||
if not self.type or self.type != "op":
|
||||
raise QiskitError("The node %s is not an op node" % (str(self)))
|
||||
raise QiskitError(f"The node {str(self)} is not an op node")
|
||||
return self._op
|
||||
|
||||
@op.setter
|
||||
|
|
|
@ -84,7 +84,7 @@ class DoWhileController(BaseController):
|
|||
return
|
||||
# Remove stored tasks from the completed task collection for next loop
|
||||
state.workflow_status.completed_passes.difference_update(self.tasks)
|
||||
raise PassManagerError("Maximum iteration reached. max_iteration=%i" % max_iteration)
|
||||
raise PassManagerError(f"Maximum iteration reached. max_iteration={max_iteration}")
|
||||
|
||||
|
||||
class ConditionalController(BaseController):
|
||||
|
|
|
@ -130,7 +130,7 @@ class BasePassManager(ABC):
|
|||
return new_passmanager
|
||||
except PassManagerError as ex:
|
||||
raise TypeError(
|
||||
"unsupported operand type + for %s and %s" % (self.__class__, other.__class__)
|
||||
f"unsupported operand type + for {self.__class__} and {other.__class__}"
|
||||
) from ex
|
||||
|
||||
@abstractmethod
|
||||
|
|
|
@ -95,7 +95,7 @@ class BackendV1(Backend, ABC):
|
|||
if fields:
|
||||
for field in fields:
|
||||
if field not in self._options.data:
|
||||
raise AttributeError("Options field %s is not valid for this backend" % field)
|
||||
raise AttributeError(f"Options field {field} is not valid for this backend")
|
||||
self._options.update_config(**fields)
|
||||
|
||||
@classmethod
|
||||
|
@ -129,7 +129,7 @@ class BackendV1(Backend, ABC):
|
|||
"""
|
||||
for field in fields:
|
||||
if not hasattr(self._options, field):
|
||||
raise AttributeError("Options field %s is not valid for this backend" % field)
|
||||
raise AttributeError(f"Options field {field} is not valid for this backend")
|
||||
self._options.update_options(**fields)
|
||||
|
||||
def configuration(self):
|
||||
|
@ -352,7 +352,7 @@ class BackendV2(Backend, ABC):
|
|||
if fields:
|
||||
for field in fields:
|
||||
if field not in self._options.data:
|
||||
raise AttributeError("Options field %s is not valid for this backend" % field)
|
||||
raise AttributeError(f"Options field {field} is not valid for this backend")
|
||||
self._options.update_config(**fields)
|
||||
self.name = name
|
||||
"""Name of the backend."""
|
||||
|
@ -598,7 +598,7 @@ class BackendV2(Backend, ABC):
|
|||
"""
|
||||
for field in fields:
|
||||
if not hasattr(self._options, field):
|
||||
raise AttributeError("Options field %s is not valid for this backend" % field)
|
||||
raise AttributeError(f"Options field {field} is not valid for this backend")
|
||||
self._options.update_options(**fields)
|
||||
|
||||
@property
|
||||
|
|
|
@ -66,7 +66,7 @@ def single_gate_matrix(gate: str, params: list[float] | None = None) -> np.ndarr
|
|||
if gate in SINGLE_QUBIT_GATES:
|
||||
gc = SINGLE_QUBIT_GATES[gate]
|
||||
else:
|
||||
raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate)
|
||||
raise QiskitError(f"Gate is not a valid basis gate for this simulator: {gate}")
|
||||
|
||||
return gc(*params).to_matrix()
|
||||
|
||||
|
|
|
@ -208,7 +208,7 @@ class BasicSimulator(BackendV2):
|
|||
target.add_instruction(UnitaryGate, name="unitary")
|
||||
else:
|
||||
raise BasicProviderError(
|
||||
"Gate is not a valid basis gate for this simulator: %s" % name
|
||||
f"Gate is not a valid basis gate for this simulator: {name}"
|
||||
)
|
||||
return target
|
||||
|
||||
|
@ -531,7 +531,7 @@ class BasicSimulator(BackendV2):
|
|||
for key, value in backend_options.items():
|
||||
if not hasattr(self.options, key):
|
||||
warnings.warn(
|
||||
"Option %s is not used by this backend" % key, UserWarning, stacklevel=2
|
||||
f"Option {key} is not used by this backend", UserWarning, stacklevel=2
|
||||
)
|
||||
else:
|
||||
out_options[key] = value
|
||||
|
|
|
@ -143,8 +143,8 @@ class FakeBackend(BackendV1):
|
|||
pulse_job = False
|
||||
if pulse_job is None:
|
||||
raise QiskitError(
|
||||
"Invalid input object %s, must be either a "
|
||||
"QuantumCircuit, Schedule, or a list of either" % circuits
|
||||
f"Invalid input object {circuits}, must be either a "
|
||||
"QuantumCircuit, Schedule, or a list of either"
|
||||
)
|
||||
if pulse_job:
|
||||
raise QiskitError("Pulse simulation is currently not supported for fake backends.")
|
||||
|
|
|
@ -496,8 +496,8 @@ class GenericBackendV2(BackendV2):
|
|||
pulse_job = False
|
||||
if pulse_job is None: # submitted job is invalid
|
||||
raise QiskitError(
|
||||
"Invalid input object %s, must be either a "
|
||||
"QuantumCircuit, Schedule, or a list of either" % circuits
|
||||
f"Invalid input object {circuits}, must be either a "
|
||||
"QuantumCircuit, Schedule, or a list of either"
|
||||
)
|
||||
if pulse_job: # pulse job
|
||||
raise QiskitError("Pulse simulation is currently not supported for V2 backends.")
|
||||
|
|
|
@ -404,9 +404,9 @@ class BackendProperties:
|
|||
if name is not None:
|
||||
result = result[name]
|
||||
except KeyError as ex:
|
||||
formatted_name = "y '" + name + "'" if name else "ies"
|
||||
raise BackendPropertyError(
|
||||
"Couldn't find the propert{name} for qubit "
|
||||
"{qubit}.".format(name="y '" + name + "'" if name else "ies", qubit=qubit)
|
||||
f"Couldn't find the propert{formatted_name} for qubit {qubit}."
|
||||
) from ex
|
||||
return result
|
||||
|
||||
|
|
|
@ -296,9 +296,4 @@ class PulseDefaults:
|
|||
meas_freqs = [freq / 1e9 for freq in self.meas_freq_est]
|
||||
qfreq = f"Qubit Frequencies [GHz]\n{qubit_freqs}"
|
||||
mfreq = f"Measurement Frequencies [GHz]\n{meas_freqs} "
|
||||
return "<{name}({insts}{qfreq}\n{mfreq})>".format(
|
||||
name=self.__class__.__name__,
|
||||
insts=str(self.instruction_schedule_map),
|
||||
qfreq=qfreq,
|
||||
mfreq=mfreq,
|
||||
)
|
||||
return f"<{self.__class__.__name__}({str(self.instruction_schedule_map)}{qfreq}\n{mfreq})>"
|
||||
|
|
|
@ -170,7 +170,7 @@ class Options(Mapping):
|
|||
|
||||
def __repr__(self):
|
||||
items = (f"{k}={v!r}" for k, v in self._fields.items())
|
||||
return "{}({})".format(type(self).__name__, ", ".join(items))
|
||||
return f"{type(self).__name__}({', '.join(items)})"
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(self, Options) and isinstance(other, Options):
|
||||
|
@ -211,7 +211,7 @@ class Options(Mapping):
|
|||
"""
|
||||
|
||||
if field not in self._fields:
|
||||
raise KeyError("Field '%s' is not present in this options object" % field)
|
||||
raise KeyError(f"Field '{field}' is not present in this options object")
|
||||
if isinstance(validator_value, tuple):
|
||||
if len(validator_value) != 2:
|
||||
raise ValueError(
|
||||
|
|
|
@ -55,11 +55,9 @@ class Kernel:
|
|||
self.params = params
|
||||
|
||||
def __repr__(self):
|
||||
return "{}({}{})".format(
|
||||
self.__class__.__name__,
|
||||
"'" + self.name + "', " or "",
|
||||
", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items()),
|
||||
)
|
||||
name_repr = "'" + self.name + "', "
|
||||
params_repr = ", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items())
|
||||
return f"{self.__class__.__name__}({name_repr}{params_repr})"
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Kernel):
|
||||
|
@ -83,11 +81,9 @@ class Discriminator:
|
|||
self.params = params
|
||||
|
||||
def __repr__(self):
|
||||
return "{}({}{})".format(
|
||||
self.__class__.__name__,
|
||||
"'" + self.name + "', " or "",
|
||||
", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items()),
|
||||
)
|
||||
name_repr = "'" + self.name + "', " or ""
|
||||
params_repr = ", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items())
|
||||
return f"{self.__class__.__name__}({name_repr}{params_repr})"
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Discriminator):
|
||||
|
@ -184,7 +180,7 @@ class LoConfig:
|
|||
self.check_lo(channel, freq)
|
||||
self._m_lo_freq[channel] = freq
|
||||
else:
|
||||
raise PulseError("Specified channel %s cannot be configured." % channel.name)
|
||||
raise PulseError(f"Specified channel {channel.name} cannot be configured.")
|
||||
|
||||
def add_lo_range(
|
||||
self, channel: DriveChannel | MeasureChannel, lo_range: LoRange | tuple[int, int]
|
||||
|
@ -236,7 +232,7 @@ class LoConfig:
|
|||
if channel in self.meas_los:
|
||||
return self.meas_los[channel]
|
||||
|
||||
raise PulseError("Channel %s is not configured" % channel)
|
||||
raise PulseError(f"Channel {channel} is not configured")
|
||||
|
||||
@property
|
||||
def qubit_los(self) -> dict[DriveChannel, float]:
|
||||
|
|
|
@ -169,10 +169,8 @@ class InstructionScheduleMap:
|
|||
if not self.has(instruction, _to_tuple(qubits)):
|
||||
if instruction in self._map:
|
||||
raise PulseError(
|
||||
"Operation '{inst}' exists, but is only defined for qubits "
|
||||
"{qubits}.".format(
|
||||
inst=instruction, qubits=self.qubits_with_instruction(instruction)
|
||||
)
|
||||
f"Operation '{instruction}' exists, but is only defined for qubits "
|
||||
f"{self.qubits_with_instruction(instruction)}."
|
||||
)
|
||||
raise PulseError(f"Operation '{instruction}' is not defined for this system.")
|
||||
|
||||
|
|
|
@ -138,12 +138,11 @@ class Acquire(Instruction):
|
|||
return isinstance(self.duration, ParameterExpression) or super().is_parameterized()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{}({}{}{}{}{}{})".format(
|
||||
self.__class__.__name__,
|
||||
self.duration,
|
||||
", " + str(self.channel),
|
||||
", " + str(self.mem_slot) if self.mem_slot else "",
|
||||
", " + str(self.reg_slot) if self.reg_slot else "",
|
||||
", " + str(self.kernel) if self.kernel else "",
|
||||
", " + str(self.discriminator) if self.discriminator else "",
|
||||
mem_slot_repr = str(self.mem_slot) if self.mem_slot else ""
|
||||
reg_slot_repr = str(self.reg_slot) if self.reg_slot else ""
|
||||
kernel_repr = str(self.kernel) if self.kernel else ""
|
||||
discriminator_repr = str(self.discriminator) if self.discriminator else ""
|
||||
return (
|
||||
f"{self.__class__.__name__}({self.duration}, {str(self.channel)}, "
|
||||
f"{mem_slot_repr}, {reg_slot_repr}, {kernel_repr}, {discriminator_repr})"
|
||||
)
|
||||
|
|
|
@ -264,6 +264,5 @@ class Instruction(ABC):
|
|||
|
||||
def __repr__(self) -> str:
|
||||
operands = ", ".join(str(op) for op in self.operands)
|
||||
return "{}({}{})".format(
|
||||
self.__class__.__name__, operands, f", name='{self.name}'" if self.name else ""
|
||||
)
|
||||
name_repr = f", name='{self.name}'" if self.name else ""
|
||||
return f"{self.__class__.__name__}({operands}{name_repr})"
|
||||
|
|
|
@ -182,9 +182,9 @@ def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Ca
|
|||
header, body = wrapped_docstring.split("\n", 1)
|
||||
body = textwrap.indent(body, " ")
|
||||
wrapped_docstring = header + body
|
||||
updated_ds = """
|
||||
Discretized continuous pulse function: `{continuous_name}` using
|
||||
sampler: `{sampler_name}`.
|
||||
updated_ds = f"""
|
||||
Discretized continuous pulse function: `{discretized_pulse.__name__}` using
|
||||
sampler: `{sampler_inst.__name__}`.
|
||||
|
||||
The first argument (time) of the continuous pulse function has been replaced with
|
||||
a discretized `duration` of type (int).
|
||||
|
@ -198,12 +198,8 @@ def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Ca
|
|||
|
||||
Sampled continuous function:
|
||||
|
||||
{continuous_doc}
|
||||
""".format(
|
||||
continuous_name=discretized_pulse.__name__,
|
||||
sampler_name=sampler_inst.__name__,
|
||||
continuous_doc=wrapped_docstring,
|
||||
)
|
||||
{wrapped_docstring}
|
||||
"""
|
||||
|
||||
discretized_pulse.__doc__ = updated_ds
|
||||
return discretized_pulse
|
||||
|
|
|
@ -570,11 +570,8 @@ class SymbolicPulse(Pulse):
|
|||
|
||||
def __repr__(self) -> str:
|
||||
param_repr = ", ".join(f"{p}={v}" for p, v in self.parameters.items())
|
||||
return "{}({}{})".format(
|
||||
self._pulse_type,
|
||||
param_repr,
|
||||
f", name='{self.name}'" if self.name is not None else "",
|
||||
)
|
||||
name_repr = f", name='{self.name}'" if self.name is not None else ""
|
||||
return f"{self._pulse_type}({param_repr}{name_repr})"
|
||||
|
||||
__hash__ = None
|
||||
|
||||
|
|
|
@ -130,8 +130,5 @@ class Waveform(Pulse):
|
|||
opt = np.get_printoptions()
|
||||
np.set_printoptions(threshold=50)
|
||||
np.set_printoptions(**opt)
|
||||
return "{}({}{})".format(
|
||||
self.__class__.__name__,
|
||||
repr(self.samples),
|
||||
f", name='{self.name}'" if self.name is not None else "",
|
||||
)
|
||||
name_repr = f", name='{self.name}'" if self.name is not None else ""
|
||||
return f"{self.__class__.__name__}({repr(self.samples)}{name_repr})"
|
||||
|
|
|
@ -135,10 +135,10 @@ def _measure_v1(
|
|||
default_sched = inst_map.get(measure_name, measure_group_qubits)
|
||||
except exceptions.PulseError as ex:
|
||||
raise exceptions.PulseError(
|
||||
"We could not find a default measurement schedule called '{}'. "
|
||||
f"We could not find a default measurement schedule called '{measure_name}'. "
|
||||
"Please provide another name using the 'measure_name' keyword "
|
||||
"argument. For assistance, the instructions which are defined are: "
|
||||
"{}".format(measure_name, inst_map.instructions)
|
||||
f"{inst_map.instructions}"
|
||||
) from ex
|
||||
for time, inst in default_sched.instructions:
|
||||
if inst.channel.index not in qubits:
|
||||
|
@ -203,10 +203,10 @@ def _measure_v2(
|
|||
schedule += _schedule_remapping_memory_slot(default_sched, qubit_mem_slots)
|
||||
except KeyError as ex:
|
||||
raise exceptions.PulseError(
|
||||
"We could not find a default measurement schedule called '{}'. "
|
||||
f"We could not find a default measurement schedule called '{measure_name}'. "
|
||||
"Please provide another name using the 'measure_name' keyword "
|
||||
"argument. For assistance, the instructions which are defined are: "
|
||||
"{}".format(measure_name, target.instructions)
|
||||
f"{target.instructions}"
|
||||
) from ex
|
||||
return schedule
|
||||
|
||||
|
|
|
@ -124,13 +124,11 @@ class PulseExpression(ast.NodeTransformer):
|
|||
self._locals_dict[key] = val
|
||||
else:
|
||||
raise PulseError(
|
||||
"%s got multiple values for argument '%s'"
|
||||
% (self.__class__.__name__, key)
|
||||
f"{self.__class__.__name__} got multiple values for argument '{key}'"
|
||||
)
|
||||
else:
|
||||
raise PulseError(
|
||||
"%s got an unexpected keyword argument '%s'"
|
||||
% (self.__class__.__name__, key)
|
||||
f"{self.__class__.__name__} got an unexpected keyword argument '{key}'"
|
||||
)
|
||||
|
||||
expr = self.visit(self._tree)
|
||||
|
@ -139,7 +137,7 @@ class PulseExpression(ast.NodeTransformer):
|
|||
if self._partial_binding:
|
||||
return PulseExpression(expr, self._partial_binding)
|
||||
else:
|
||||
raise PulseError("Parameters %s are not all bound." % self.params)
|
||||
raise PulseError(f"Parameters {self.params} are not all bound.")
|
||||
return expr.body.value
|
||||
|
||||
@staticmethod
|
||||
|
@ -160,7 +158,7 @@ class PulseExpression(ast.NodeTransformer):
|
|||
for op_type, op_func in opr_dict.items():
|
||||
if isinstance(opr, op_type):
|
||||
return op_func(*args)
|
||||
raise PulseError("Operator %s is not supported." % opr.__class__.__name__)
|
||||
raise PulseError(f"Operator {opr.__class__.__name__} is not supported.")
|
||||
|
||||
def visit_Expression(self, node: ast.Expression) -> ast.Expression:
|
||||
"""Evaluate children nodes of expression.
|
||||
|
@ -273,7 +271,7 @@ class PulseExpression(ast.NodeTransformer):
|
|||
node.args = [self.visit(arg) for arg in node.args]
|
||||
if all(isinstance(arg, ast.Constant) for arg in node.args):
|
||||
if node.func.id not in self._math_ops:
|
||||
raise PulseError("Function %s is not supported." % node.func.id)
|
||||
raise PulseError(f"Function {node.func.id} is not supported.")
|
||||
_args = [arg.value for arg in node.args]
|
||||
_val = self._math_ops[node.func.id](*_args)
|
||||
if not _val.imag:
|
||||
|
@ -283,7 +281,7 @@ class PulseExpression(ast.NodeTransformer):
|
|||
return node
|
||||
|
||||
def generic_visit(self, node):
|
||||
raise PulseError("Unsupported node: %s" % node.__class__.__name__)
|
||||
raise PulseError(f"Unsupported node: {node.__class__.__name__}")
|
||||
|
||||
|
||||
def parse_string_expr(source: str, partial_binding: bool = False) -> PulseExpression:
|
||||
|
|
|
@ -553,17 +553,10 @@ class Schedule:
|
|||
self._timeslots[channel].insert(index, interval)
|
||||
except PulseError as ex:
|
||||
raise PulseError(
|
||||
"Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at "
|
||||
"time {time} because its instruction on channel {ch} scheduled from time "
|
||||
"{t0} to {tf} overlaps with an existing instruction."
|
||||
"".format(
|
||||
new=schedule.name or "",
|
||||
old=self.name or "",
|
||||
time=time,
|
||||
ch=channel,
|
||||
t0=interval[0],
|
||||
tf=interval[1],
|
||||
)
|
||||
f"Schedule(name='{schedule.name or ''}') cannot be inserted into "
|
||||
f"Schedule(name='{self.name or ''}') at "
|
||||
f"time {time} because its instruction on channel {channel} scheduled from time "
|
||||
f"{interval[0]} to {interval[1]} overlaps with an existing instruction."
|
||||
) from ex
|
||||
|
||||
_check_nonnegative_timeslot(self._timeslots)
|
||||
|
@ -598,10 +591,8 @@ class Schedule:
|
|||
continue
|
||||
|
||||
raise PulseError(
|
||||
"Cannot find interval ({t0}, {tf}) to remove from "
|
||||
"channel {ch} in Schedule(name='{name}').".format(
|
||||
ch=channel, t0=interval[0], tf=interval[1], name=schedule.name
|
||||
)
|
||||
f"Cannot find interval ({interval[0]}, {interval[1]}) to remove from "
|
||||
f"channel {channel} in Schedule(name='{schedule.name}')."
|
||||
)
|
||||
|
||||
if not channel_timeslots:
|
||||
|
@ -1615,8 +1606,9 @@ class ScheduleBlock:
|
|||
blocks = ", ".join([repr(instr) for instr in self.blocks[:50]])
|
||||
if len(self.blocks) > 25:
|
||||
blocks += ", ..."
|
||||
return '{}({}, name="{}", transform={})'.format(
|
||||
self.__class__.__name__, blocks, name, repr(self.alignment_context)
|
||||
return (
|
||||
f'{self.__class__.__name__}({blocks}, name="{name}",'
|
||||
f" transform={repr(self.alignment_context)})"
|
||||
)
|
||||
|
||||
def __add__(self, other: "BlockComponent") -> "ScheduleBlock":
|
||||
|
|
|
@ -398,9 +398,7 @@ class AlignFunc(AlignmentKind):
|
|||
_t_center = self.duration * self.func(ind + 1)
|
||||
_t0 = int(_t_center - 0.5 * child.duration)
|
||||
if _t0 < 0 or _t0 > self.duration:
|
||||
raise PulseError(
|
||||
"Invalid schedule position t=%d is specified at index=%d" % (_t0, ind)
|
||||
)
|
||||
raise PulseError(f"Invalid schedule position t={_t0} is specified at index={ind}")
|
||||
aligned.insert(_t0, child, inplace=True)
|
||||
|
||||
return aligned
|
||||
|
|
|
@ -108,10 +108,9 @@ def instruction_duration_validation(duration: int):
|
|||
"""
|
||||
if isinstance(duration, ParameterExpression):
|
||||
raise UnassignedDurationError(
|
||||
"Instruction duration {} is not assigned. "
|
||||
f"Instruction duration {repr(duration)} is not assigned. "
|
||||
"Please bind all durations to an integer value before playing in the Schedule, "
|
||||
"or use ScheduleBlock to align instructions with unassigned duration."
|
||||
"".format(repr(duration))
|
||||
)
|
||||
|
||||
if not isinstance(duration, (int, np.integer)) or duration < 0:
|
||||
|
|
|
@ -157,7 +157,7 @@ def dumps(circuit: QuantumCircuit, /) -> str:
|
|||
_make_unique(_escape_name(reg.name, "reg_"), register_escaped_names)
|
||||
] = reg
|
||||
bit_labels: dict[Qubit | Clbit, str] = {
|
||||
bit: "%s[%d]" % (name, idx)
|
||||
bit: f"{name}[{idx}]"
|
||||
for name, register in register_escaped_names.items()
|
||||
for (idx, bit) in enumerate(register)
|
||||
}
|
||||
|
@ -244,18 +244,14 @@ def _instruction_call_site(operation):
|
|||
else:
|
||||
qasm2_call = operation.name
|
||||
if operation.params:
|
||||
qasm2_call = "{}({})".format(
|
||||
qasm2_call,
|
||||
",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]),
|
||||
)
|
||||
params = ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params])
|
||||
qasm2_call = f"{qasm2_call}({params})"
|
||||
if operation.condition is not None:
|
||||
if not isinstance(operation.condition[0], ClassicalRegister):
|
||||
raise QASM2ExportError(
|
||||
"OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'"
|
||||
)
|
||||
qasm2_call = (
|
||||
"if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call
|
||||
)
|
||||
qasm2_call = f"if({operation.condition[0].name}=={operation.condition[1]:d}) " + qasm2_call
|
||||
return qasm2_call
|
||||
|
||||
|
||||
|
|
|
@ -621,7 +621,7 @@ class QobjToInstructionConverter:
|
|||
elif prefix == channels.ControlChannel.prefix:
|
||||
return channels.ControlChannel(index)
|
||||
|
||||
raise QiskitError("Channel %s is not valid" % channel)
|
||||
raise QiskitError(f"Channel {channel} is not valid")
|
||||
|
||||
@staticmethod
|
||||
def disassemble_value(value_expr: Union[float, str]) -> Union[float, ParameterExpression]:
|
||||
|
@ -827,9 +827,7 @@ class QobjToInstructionConverter:
|
|||
pulse_name = instruction.label
|
||||
except AttributeError:
|
||||
sorted_params = sorted(instruction.parameters.items(), key=lambda x: x[0])
|
||||
base_str = "{pulse}_{params}".format(
|
||||
pulse=instruction.pulse_shape, params=str(sorted_params)
|
||||
)
|
||||
base_str = f"{instruction.pulse_shape}_{str(sorted_params)}"
|
||||
short_pulse_id = hashlib.md5(base_str.encode("utf-8")).hexdigest()[:4]
|
||||
pulse_name = f"{instruction.pulse_shape}_{short_pulse_id}"
|
||||
params = dict(instruction.parameters)
|
||||
|
|
|
@ -209,8 +209,8 @@ class PulseQobjInstruction:
|
|||
return out
|
||||
|
||||
def __str__(self):
|
||||
out = "Instruction: %s\n" % self.name
|
||||
out += "\t\tt0: %s\n" % self.t0
|
||||
out = f"Instruction: {self.name}\n"
|
||||
out += f"\t\tt0: {self.t0}\n"
|
||||
for attr in self._COMMON_ATTRS:
|
||||
if hasattr(self, attr):
|
||||
out += f"\t\t{attr}: {getattr(self, attr)}\n"
|
||||
|
@ -434,10 +434,10 @@ class PulseQobjExperiment:
|
|||
header = pprint.pformat(self.header.to_dict() or {})
|
||||
else:
|
||||
header = "{}"
|
||||
out += "Header:\n%s\n" % header
|
||||
out += "Config:\n%s\n\n" % config
|
||||
out += f"Header:\n{header}\n"
|
||||
out += f"Config:\n{config}\n\n"
|
||||
for instruction in self.instructions:
|
||||
out += "\t%s\n" % instruction
|
||||
out += f"\t{instruction}\n"
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
|
@ -567,23 +567,20 @@ class PulseQobj:
|
|||
def __repr__(self):
|
||||
experiments_str = [repr(x) for x in self.experiments]
|
||||
experiments_repr = "[" + ", ".join(experiments_str) + "]"
|
||||
out = "PulseQobj(qobj_id='{}', config={}, experiments={}, header={})".format(
|
||||
self.qobj_id,
|
||||
repr(self.config),
|
||||
experiments_repr,
|
||||
repr(self.header),
|
||||
return (
|
||||
f"PulseQobj(qobj_id='{self.qobj_id}', config={repr(self.config)}, "
|
||||
f"experiments={experiments_repr}, header={repr(self.header)})"
|
||||
)
|
||||
return out
|
||||
|
||||
def __str__(self):
|
||||
out = "Pulse Qobj: %s:\n" % self.qobj_id
|
||||
out = f"Pulse Qobj: {self.qobj_id}:\n"
|
||||
config = pprint.pformat(self.config.to_dict())
|
||||
out += "Config: %s\n" % str(config)
|
||||
out += f"Config: {str(config)}\n"
|
||||
header = pprint.pformat(self.header.to_dict())
|
||||
out += "Header: %s\n" % str(header)
|
||||
out += f"Header: {str(header)}\n"
|
||||
out += "Experiments:\n"
|
||||
for experiment in self.experiments:
|
||||
out += "%s" % str(experiment)
|
||||
out += str(experiment)
|
||||
return out
|
||||
|
||||
def to_dict(self):
|
||||
|
|
|
@ -131,7 +131,7 @@ class QasmQobjInstruction:
|
|||
return out_dict
|
||||
|
||||
def __repr__(self):
|
||||
out = "QasmQobjInstruction(name='%s'" % self.name
|
||||
out = f"QasmQobjInstruction(name='{self.name}'"
|
||||
for attr in [
|
||||
"params",
|
||||
"qubits",
|
||||
|
@ -155,7 +155,7 @@ class QasmQobjInstruction:
|
|||
return out
|
||||
|
||||
def __str__(self):
|
||||
out = "Instruction: %s\n" % self.name
|
||||
out = f"Instruction: {self.name}\n"
|
||||
for attr in [
|
||||
"params",
|
||||
"qubits",
|
||||
|
@ -215,21 +215,19 @@ class QasmQobjExperiment:
|
|||
def __repr__(self):
|
||||
instructions_str = [repr(x) for x in self.instructions]
|
||||
instructions_repr = "[" + ", ".join(instructions_str) + "]"
|
||||
out = "QasmQobjExperiment(config={}, header={}, instructions={})".format(
|
||||
repr(self.config),
|
||||
repr(self.header),
|
||||
instructions_repr,
|
||||
return (
|
||||
f"QasmQobjExperiment(config={repr(self.config)}, header={repr(self.header)},"
|
||||
f" instructions={instructions_repr})"
|
||||
)
|
||||
return out
|
||||
|
||||
def __str__(self):
|
||||
out = "\nOpenQASM2 Experiment:\n"
|
||||
config = pprint.pformat(self.config.to_dict())
|
||||
header = pprint.pformat(self.header.to_dict())
|
||||
out += "Header:\n%s\n" % header
|
||||
out += "Config:\n%s\n\n" % config
|
||||
out += f"Header:\n{header}\n"
|
||||
out += f"Config:\n{config}\n\n"
|
||||
for instruction in self.instructions:
|
||||
out += "\t%s\n" % instruction
|
||||
out += f"\t{instruction}\n"
|
||||
return out
|
||||
|
||||
def to_dict(self):
|
||||
|
@ -568,23 +566,20 @@ class QasmQobj:
|
|||
def __repr__(self):
|
||||
experiments_str = [repr(x) for x in self.experiments]
|
||||
experiments_repr = "[" + ", ".join(experiments_str) + "]"
|
||||
out = "QasmQobj(qobj_id='{}', config={}, experiments={}, header={})".format(
|
||||
self.qobj_id,
|
||||
repr(self.config),
|
||||
experiments_repr,
|
||||
repr(self.header),
|
||||
return (
|
||||
f"QasmQobj(qobj_id='{self.qobj_id}', config={repr(self.config)},"
|
||||
f" experiments={experiments_repr}, header={repr(self.header)})"
|
||||
)
|
||||
return out
|
||||
|
||||
def __str__(self):
|
||||
out = "QASM Qobj: %s:\n" % self.qobj_id
|
||||
out = f"QASM Qobj: {self.qobj_id}:\n"
|
||||
config = pprint.pformat(self.config.to_dict())
|
||||
out += "Config: %s\n" % str(config)
|
||||
out += f"Config: {str(config)}\n"
|
||||
header = pprint.pformat(self.header.to_dict())
|
||||
out += "Header: %s\n" % str(header)
|
||||
out += f"Header: {str(header)}\n"
|
||||
out += "Experiments:\n"
|
||||
for experiment in self.experiments:
|
||||
out += "%s" % str(experiment)
|
||||
out += str(experiment)
|
||||
return out
|
||||
|
||||
def to_dict(self):
|
||||
|
|
|
@ -128,7 +128,7 @@ def _read_registers_v4(file_obj, num_registers):
|
|||
)
|
||||
)
|
||||
name = file_obj.read(data.name_size).decode("utf8")
|
||||
REGISTER_ARRAY_PACK = "!%sq" % data.size
|
||||
REGISTER_ARRAY_PACK = f"!{data.size}q"
|
||||
bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK))
|
||||
bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw))
|
||||
if data.type.decode("utf8") == "q":
|
||||
|
@ -148,7 +148,7 @@ def _read_registers(file_obj, num_registers):
|
|||
)
|
||||
)
|
||||
name = file_obj.read(data.name_size).decode("utf8")
|
||||
REGISTER_ARRAY_PACK = "!%sI" % data.size
|
||||
REGISTER_ARRAY_PACK = f"!{data.size}I"
|
||||
bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK))
|
||||
bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw))
|
||||
if data.type.decode("utf8") == "q":
|
||||
|
@ -352,7 +352,7 @@ def _read_instruction(
|
|||
elif gate_name == "Clifford":
|
||||
gate_class = Clifford
|
||||
else:
|
||||
raise AttributeError("Invalid instruction type: %s" % gate_name)
|
||||
raise AttributeError(f"Invalid instruction type: {gate_name}")
|
||||
|
||||
if instruction.label_size <= 0:
|
||||
label = None
|
||||
|
@ -507,7 +507,7 @@ def _parse_custom_operation(
|
|||
if type_key == type_keys.CircuitInstruction.PAULI_EVOL_GATE:
|
||||
return definition
|
||||
|
||||
raise ValueError("Invalid custom instruction type '%s'" % type_str)
|
||||
raise ValueError(f"Invalid custom instruction type '{type_str}'")
|
||||
|
||||
|
||||
def _read_pauli_evolution_gate(file_obj, version, vectors):
|
||||
|
@ -1031,7 +1031,7 @@ def _write_registers(file_obj, in_circ_regs, full_bits):
|
|||
)
|
||||
)
|
||||
file_obj.write(reg_name)
|
||||
REGISTER_ARRAY_PACK = "!%sq" % reg.size
|
||||
REGISTER_ARRAY_PACK = f"!{reg.size}q"
|
||||
bit_indices = []
|
||||
for bit in reg:
|
||||
bit_indices.append(bitmap.get(bit, -1))
|
||||
|
|
|
@ -277,7 +277,7 @@ def _read_parameter_expression(file_obj):
|
|||
elif elem_key == type_keys.Value.PARAMETER_EXPRESSION:
|
||||
value = common.data_from_binary(binary_data, _read_parameter_expression)
|
||||
else:
|
||||
raise exceptions.QpyError("Invalid parameter expression map type: %s" % elem_key)
|
||||
raise exceptions.QpyError(f"Invalid parameter expression map type: {elem_key}")
|
||||
symbol_map[symbol] = value
|
||||
|
||||
return ParameterExpression(symbol_map, expr_)
|
||||
|
@ -311,7 +311,7 @@ def _read_parameter_expression_v3(file_obj, vectors, use_symengine):
|
|||
elif symbol_key == type_keys.Value.PARAMETER_VECTOR:
|
||||
symbol = _read_parameter_vec(file_obj, vectors)
|
||||
else:
|
||||
raise exceptions.QpyError("Invalid parameter expression map type: %s" % symbol_key)
|
||||
raise exceptions.QpyError(f"Invalid parameter expression map type: {symbol_key}")
|
||||
|
||||
elem_key = type_keys.Value(elem_data.type)
|
||||
binary_data = file_obj.read(elem_data.size)
|
||||
|
@ -331,7 +331,7 @@ def _read_parameter_expression_v3(file_obj, vectors, use_symengine):
|
|||
use_symengine=use_symengine,
|
||||
)
|
||||
else:
|
||||
raise exceptions.QpyError("Invalid parameter expression map type: %s" % elem_key)
|
||||
raise exceptions.QpyError(f"Invalid parameter expression map type: {elem_key}")
|
||||
symbol_map[symbol] = value
|
||||
|
||||
return ParameterExpression(symbol_map, expr_)
|
||||
|
|
|
@ -304,10 +304,11 @@ def load(
|
|||
):
|
||||
warnings.warn(
|
||||
"The qiskit version used to generate the provided QPY "
|
||||
"file, %s, is newer than the current qiskit version %s. "
|
||||
f"file, {'.'.join([str(x) for x in qiskit_version])}, "
|
||||
f"is newer than the current qiskit version {__version__}. "
|
||||
"This may result in an error if the QPY file uses "
|
||||
"instructions not present in this current qiskit "
|
||||
"version" % (".".join([str(x) for x in qiskit_version]), __version__)
|
||||
"version"
|
||||
)
|
||||
|
||||
if data.qpy_version < 5:
|
||||
|
|
|
@ -66,12 +66,9 @@ class QuantumChannel(LinearOp):
|
|||
def __repr__(self):
|
||||
prefix = f"{self._channel_rep}("
|
||||
pad = len(prefix) * " "
|
||||
return "{}{},\n{}input_dims={}, output_dims={})".format(
|
||||
prefix,
|
||||
np.array2string(np.asarray(self.data), separator=", ", prefix=prefix),
|
||||
pad,
|
||||
self.input_dims(),
|
||||
self.output_dims(),
|
||||
return (
|
||||
f"{prefix}{np.array2string(np.asarray(self.data), separator=', ', prefix=prefix)}"
|
||||
f",\n{pad}input_dims={self.input_dims()}, output_dims={self.output_dims()})"
|
||||
)
|
||||
|
||||
def __eq__(self, other: Self):
|
||||
|
|
|
@ -355,8 +355,8 @@ class SuperOp(QuantumChannel):
|
|||
raise QiskitError(f"Cannot apply Instruction: {obj.name}")
|
||||
if not isinstance(obj.definition, QuantumCircuit):
|
||||
raise QiskitError(
|
||||
"{} instruction definition is {}; "
|
||||
"expected QuantumCircuit".format(obj.name, type(obj.definition))
|
||||
f"{obj.name} instruction definition is {type(obj.definition)}; "
|
||||
"expected QuantumCircuit"
|
||||
)
|
||||
qubit_indices = {bit: idx for idx, bit in enumerate(obj.definition.qubits)}
|
||||
for instruction in obj.definition.data:
|
||||
|
|
|
@ -92,9 +92,7 @@ def _append_circuit(elem, circuit, qargs=None):
|
|||
raise QiskitError(f"Cannot apply Instruction: {gate.name}")
|
||||
if not isinstance(gate.definition, QuantumCircuit):
|
||||
raise QiskitError(
|
||||
"{} instruction definition is {}; expected QuantumCircuit".format(
|
||||
gate.name, type(gate.definition)
|
||||
)
|
||||
f"{gate.name} instruction definition is {type(gate.definition)}; expected QuantumCircuit"
|
||||
)
|
||||
|
||||
flat_instr = gate.definition
|
||||
|
|
|
@ -93,7 +93,7 @@ def process_fidelity(
|
|||
if channel.dim != target.dim:
|
||||
raise QiskitError(
|
||||
"Input quantum channel and target unitary must have the same "
|
||||
"dimensions ({} != {}).".format(channel.dim, target.dim)
|
||||
f"dimensions ({channel.dim} != {target.dim})."
|
||||
)
|
||||
|
||||
# Validate complete-positivity and trace-preserving
|
||||
|
|
|
@ -193,7 +193,7 @@ class OpShape:
|
|||
if raise_exception:
|
||||
raise QiskitError(
|
||||
"Output dimensions do not match matrix shape "
|
||||
"({} != {})".format(reduce(mul, self._dims_l), shape[0])
|
||||
f"({reduce(mul, self._dims_l)} != {shape[0]})"
|
||||
)
|
||||
return False
|
||||
elif shape[0] != 2**self._num_qargs_l:
|
||||
|
@ -207,7 +207,7 @@ class OpShape:
|
|||
if raise_exception:
|
||||
raise QiskitError(
|
||||
"Input dimensions do not match matrix shape "
|
||||
"({} != {})".format(reduce(mul, self._dims_r), shape[1])
|
||||
f"({reduce(mul, self._dims_r)} != {shape[1]})"
|
||||
)
|
||||
return False
|
||||
elif shape[1] != 2**self._num_qargs_r:
|
||||
|
@ -430,7 +430,7 @@ class OpShape:
|
|||
if self._num_qargs_r != other._num_qargs_l or self._dims_r != other._dims_l:
|
||||
raise QiskitError(
|
||||
"Left and right compose dimensions don't match "
|
||||
"({} != {})".format(self.dims_r(), other.dims_l())
|
||||
f"({self.dims_r()} != {other.dims_l()})"
|
||||
)
|
||||
ret._dims_l = self._dims_l
|
||||
ret._dims_r = other._dims_r
|
||||
|
@ -440,7 +440,7 @@ class OpShape:
|
|||
if self._num_qargs_l != other._num_qargs_r or self._dims_l != other._dims_r:
|
||||
raise QiskitError(
|
||||
"Left and right compose dimensions don't match "
|
||||
"({} != {})".format(self.dims_l(), other.dims_r())
|
||||
f"({self.dims_l()} != {other.dims_r()})"
|
||||
)
|
||||
ret._dims_l = other._dims_l
|
||||
ret._dims_r = self._dims_r
|
||||
|
@ -453,15 +453,13 @@ class OpShape:
|
|||
ret._num_qargs_l = self._num_qargs_l
|
||||
if len(qargs) != other._num_qargs_l:
|
||||
raise QiskitError(
|
||||
"Number of qargs does not match ({} != {})".format(
|
||||
len(qargs), other._num_qargs_l
|
||||
)
|
||||
f"Number of qargs does not match ({len(qargs)} != {other._num_qargs_l})"
|
||||
)
|
||||
if self._dims_r or other._dims_r:
|
||||
if self.dims_r(qargs) != other.dims_l():
|
||||
raise QiskitError(
|
||||
"Subsystem dimension do not match on specified qargs "
|
||||
"{} != {}".format(self.dims_r(qargs), other.dims_l())
|
||||
f"{self.dims_r(qargs)} != {other.dims_l()}"
|
||||
)
|
||||
dims_r = list(self.dims_r())
|
||||
for i, dim in zip(qargs, other.dims_r()):
|
||||
|
@ -475,15 +473,13 @@ class OpShape:
|
|||
ret._num_qargs_r = self._num_qargs_r
|
||||
if len(qargs) != other._num_qargs_r:
|
||||
raise QiskitError(
|
||||
"Number of qargs does not match ({} != {})".format(
|
||||
len(qargs), other._num_qargs_r
|
||||
)
|
||||
f"Number of qargs does not match ({len(qargs)} != {other._num_qargs_r})"
|
||||
)
|
||||
if self._dims_l or other._dims_l:
|
||||
if self.dims_l(qargs) != other.dims_r():
|
||||
raise QiskitError(
|
||||
"Subsystem dimension do not match on specified qargs "
|
||||
"{} != {}".format(self.dims_l(qargs), other.dims_r())
|
||||
f"{self.dims_l(qargs)} != {other.dims_r()}"
|
||||
)
|
||||
dims_l = list(self.dims_l())
|
||||
for i, dim in zip(qargs, other.dims_l()):
|
||||
|
@ -508,26 +504,22 @@ class OpShape:
|
|||
if self.dims_l(qargs) != other.dims_l():
|
||||
raise QiskitError(
|
||||
"Cannot add shapes width different left "
|
||||
"dimension on specified qargs {} != {}".format(
|
||||
self.dims_l(qargs), other.dims_l()
|
||||
)
|
||||
f"dimension on specified qargs {self.dims_l(qargs)} != {other.dims_l()}"
|
||||
)
|
||||
if self.dims_r(qargs) != other.dims_r():
|
||||
raise QiskitError(
|
||||
"Cannot add shapes width different total right "
|
||||
"dimension on specified qargs{} != {}".format(
|
||||
self.dims_r(qargs), other.dims_r()
|
||||
)
|
||||
f"dimension on specified qargs{self.dims_r(qargs)} != {other.dims_r()}"
|
||||
)
|
||||
elif self != other:
|
||||
if self._dim_l != other._dim_l:
|
||||
raise QiskitError(
|
||||
"Cannot add shapes width different total left "
|
||||
"dimension {} != {}".format(self._dim_l, other._dim_l)
|
||||
f"dimension {self._dim_l} != {other._dim_l}"
|
||||
)
|
||||
if self._dim_r != other._dim_r:
|
||||
raise QiskitError(
|
||||
"Cannot add shapes width different total right "
|
||||
"dimension {} != {}".format(self._dim_r, other._dim_r)
|
||||
f"dimension {self._dim_r} != {other._dim_r}"
|
||||
)
|
||||
return self
|
||||
|
|
|
@ -128,12 +128,9 @@ class Operator(LinearOp):
|
|||
def __repr__(self):
|
||||
prefix = "Operator("
|
||||
pad = len(prefix) * " "
|
||||
return "{}{},\n{}input_dims={}, output_dims={})".format(
|
||||
prefix,
|
||||
np.array2string(self.data, separator=", ", prefix=prefix),
|
||||
pad,
|
||||
self.input_dims(),
|
||||
self.output_dims(),
|
||||
return (
|
||||
f"{prefix}{np.array2string(self.data, separator=', ', prefix=prefix)},\n"
|
||||
f"{pad}input_dims={self.input_dims()}, output_dims={self.output_dims()})"
|
||||
)
|
||||
|
||||
def __eq__(self, other):
|
||||
|
@ -763,10 +760,8 @@ class Operator(LinearOp):
|
|||
raise QiskitError(f"Cannot apply Operation: {obj.name}")
|
||||
if not isinstance(obj.definition, QuantumCircuit):
|
||||
raise QiskitError(
|
||||
'Operation "{}" '
|
||||
"definition is {} but expected QuantumCircuit.".format(
|
||||
obj.name, type(obj.definition)
|
||||
)
|
||||
f'Operation "{obj.name}" '
|
||||
f"definition is {type(obj.definition)} but expected QuantumCircuit."
|
||||
)
|
||||
if obj.definition.global_phase:
|
||||
dimension = 2**obj.num_qubits
|
||||
|
|
|
@ -22,6 +22,7 @@ RTOL_DEFAULT = 1e-5
|
|||
|
||||
|
||||
def matrix_equal(mat1, mat2, ignore_phase=False, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT, props=None):
|
||||
# pylint: disable-next=consider-using-f-string
|
||||
"""Test if two arrays are equal.
|
||||
|
||||
The final comparison is implemented using Numpy.allclose. See its
|
||||
|
|
|
@ -215,12 +215,12 @@ class BasePauli(BaseOperator, AdjointMixin, MultiplyMixin):
|
|||
if qargs is not None and len(qargs) != other.num_qubits:
|
||||
raise QiskitError(
|
||||
"Number of qubits of other Pauli does not match number of "
|
||||
"qargs ({} != {}).".format(other.num_qubits, len(qargs))
|
||||
f"qargs ({other.num_qubits} != {len(qargs)})."
|
||||
)
|
||||
if qargs is None and self.num_qubits != other.num_qubits:
|
||||
raise QiskitError(
|
||||
"Number of qubits of other Pauli does not match the current "
|
||||
"Pauli ({} != {}).".format(other.num_qubits, self.num_qubits)
|
||||
f"Pauli ({other.num_qubits} != {self.num_qubits})."
|
||||
)
|
||||
if qargs is not None:
|
||||
inds = list(qargs)
|
||||
|
@ -262,15 +262,12 @@ class BasePauli(BaseOperator, AdjointMixin, MultiplyMixin):
|
|||
# Check dimension
|
||||
if qargs is not None and len(qargs) != other.num_qubits:
|
||||
raise QiskitError(
|
||||
"Incorrect number of qubits for Clifford circuit ({} != {}).".format(
|
||||
other.num_qubits, len(qargs)
|
||||
)
|
||||
f"Incorrect number of qubits for Clifford circuit ({other.num_qubits} != {len(qargs)})."
|
||||
)
|
||||
if qargs is None and self.num_qubits != other.num_qubits:
|
||||
raise QiskitError(
|
||||
"Incorrect number of qubits for Clifford circuit ({} != {}).".format(
|
||||
other.num_qubits, self.num_qubits
|
||||
)
|
||||
f"Incorrect number of qubits for Clifford circuit "
|
||||
f"({other.num_qubits} != {self.num_qubits})."
|
||||
)
|
||||
|
||||
# Evolve via Pauli
|
||||
|
@ -571,9 +568,8 @@ class BasePauli(BaseOperator, AdjointMixin, MultiplyMixin):
|
|||
raise QiskitError(f"Cannot apply Instruction: {gate.name}")
|
||||
if not isinstance(gate.definition, QuantumCircuit):
|
||||
raise QiskitError(
|
||||
"{} instruction definition is {}; expected QuantumCircuit".format(
|
||||
gate.name, type(gate.definition)
|
||||
)
|
||||
f"{gate.name} instruction definition is {type(gate.definition)};"
|
||||
f" expected QuantumCircuit"
|
||||
)
|
||||
|
||||
circuit = gate.definition
|
||||
|
|
|
@ -344,7 +344,7 @@ class Pauli(BasePauli):
|
|||
if max(qubits) > self.num_qubits - 1:
|
||||
raise QiskitError(
|
||||
"Qubit index is larger than the number of qubits "
|
||||
"({}>{}).".format(max(qubits), self.num_qubits - 1)
|
||||
f"({max(qubits)}>{self.num_qubits - 1})."
|
||||
)
|
||||
if len(qubits) == self.num_qubits:
|
||||
raise QiskitError("Cannot delete all qubits of Pauli")
|
||||
|
@ -379,12 +379,12 @@ class Pauli(BasePauli):
|
|||
if len(qubits) != value.num_qubits:
|
||||
raise QiskitError(
|
||||
"Number of indices does not match number of qubits for "
|
||||
"the inserted Pauli ({}!={})".format(len(qubits), value.num_qubits)
|
||||
f"the inserted Pauli ({len(qubits)}!={value.num_qubits})"
|
||||
)
|
||||
if max(qubits) > ret.num_qubits - 1:
|
||||
raise QiskitError(
|
||||
"Index is too larger for combined Pauli number of qubits "
|
||||
"({}>{}).".format(max(qubits), ret.num_qubits - 1)
|
||||
f"({max(qubits)}>{ret.num_qubits - 1})."
|
||||
)
|
||||
# Qubit positions for original op
|
||||
self_qubits = [i for i in range(ret.num_qubits) if i not in qubits]
|
||||
|
|
|
@ -382,8 +382,8 @@ class PauliList(BasePauli, LinearMixin, GroupMixin):
|
|||
if not qubit:
|
||||
if max(ind) >= len(self):
|
||||
raise QiskitError(
|
||||
"Indices {} are not all less than the size"
|
||||
" of the PauliList ({})".format(ind, len(self))
|
||||
f"Indices {ind} are not all less than the size"
|
||||
f" of the PauliList ({len(self)})"
|
||||
)
|
||||
z = np.delete(self._z, ind, axis=0)
|
||||
x = np.delete(self._x, ind, axis=0)
|
||||
|
@ -394,8 +394,8 @@ class PauliList(BasePauli, LinearMixin, GroupMixin):
|
|||
# Column (qubit) deletion
|
||||
if max(ind) >= self.num_qubits:
|
||||
raise QiskitError(
|
||||
"Indices {} are not all less than the number of"
|
||||
" qubits in the PauliList ({})".format(ind, self.num_qubits)
|
||||
f"Indices {ind} are not all less than the number of"
|
||||
f" qubits in the PauliList ({self.num_qubits})"
|
||||
)
|
||||
z = np.delete(self._z, ind, axis=1)
|
||||
x = np.delete(self._x, ind, axis=1)
|
||||
|
@ -432,8 +432,7 @@ class PauliList(BasePauli, LinearMixin, GroupMixin):
|
|||
if not qubit:
|
||||
if ind > size:
|
||||
raise QiskitError(
|
||||
"Index {} is larger than the number of rows in the"
|
||||
" PauliList ({}).".format(ind, size)
|
||||
f"Index {ind} is larger than the number of rows in the" f" PauliList ({size})."
|
||||
)
|
||||
base_z = np.insert(self._z, ind, value._z, axis=0)
|
||||
base_x = np.insert(self._x, ind, value._x, axis=0)
|
||||
|
@ -443,8 +442,8 @@ class PauliList(BasePauli, LinearMixin, GroupMixin):
|
|||
# Column insertion
|
||||
if ind > self.num_qubits:
|
||||
raise QiskitError(
|
||||
"Index {} is greater than number of qubits"
|
||||
" in the PauliList ({})".format(ind, self.num_qubits)
|
||||
f"Index {ind} is greater than number of qubits"
|
||||
f" in the PauliList ({self.num_qubits})"
|
||||
)
|
||||
if len(value) == 1:
|
||||
# Pad blocks to correct size
|
||||
|
@ -461,7 +460,7 @@ class PauliList(BasePauli, LinearMixin, GroupMixin):
|
|||
raise QiskitError(
|
||||
"Input PauliList must have a single row, or"
|
||||
" the same number of rows as the Pauli Table"
|
||||
" ({}).".format(size)
|
||||
f" ({size})."
|
||||
)
|
||||
# Build new array by blocks
|
||||
z = np.hstack([self.z[:, :ind], value_z, self.z[:, ind:]])
|
||||
|
|
|
@ -172,7 +172,7 @@ class SparsePauliOp(LinearOp):
|
|||
if self._coeffs.shape != (self._pauli_list.size,):
|
||||
raise QiskitError(
|
||||
"coeff vector is incorrect shape for number"
|
||||
" of Paulis {} != {}".format(self._coeffs.shape, self._pauli_list.size)
|
||||
f" of Paulis {self._coeffs.shape} != {self._pauli_list.size}"
|
||||
)
|
||||
# Initialize LinearOp
|
||||
super().__init__(num_qubits=self._pauli_list.num_qubits)
|
||||
|
@ -186,11 +186,9 @@ class SparsePauliOp(LinearOp):
|
|||
def __repr__(self):
|
||||
prefix = "SparsePauliOp("
|
||||
pad = len(prefix) * " "
|
||||
return "{}{},\n{}coeffs={})".format(
|
||||
prefix,
|
||||
self.paulis.to_labels(),
|
||||
pad,
|
||||
np.array2string(self.coeffs, separator=", "),
|
||||
return (
|
||||
f"{prefix}{self.paulis.to_labels()},\n{pad}"
|
||||
f"coeffs={np.array2string(self.coeffs, separator=', ')})"
|
||||
)
|
||||
|
||||
def __eq__(self, other):
|
||||
|
|
|
@ -123,11 +123,9 @@ class DensityMatrix(QuantumState, TolerancesMixin):
|
|||
def __repr__(self):
|
||||
prefix = "DensityMatrix("
|
||||
pad = len(prefix) * " "
|
||||
return "{}{},\n{}dims={})".format(
|
||||
prefix,
|
||||
np.array2string(self._data, separator=", ", prefix=prefix),
|
||||
pad,
|
||||
self._op_shape.dims_l(),
|
||||
return (
|
||||
f"{prefix}{np.array2string(self._data, separator=', ', prefix=prefix)},\n"
|
||||
f"{pad}dims={self._op_shape.dims_l()})"
|
||||
)
|
||||
|
||||
@property
|
||||
|
@ -771,9 +769,8 @@ class DensityMatrix(QuantumState, TolerancesMixin):
|
|||
raise QiskitError(f"Cannot apply Instruction: {other.name}")
|
||||
if not isinstance(other.definition, QuantumCircuit):
|
||||
raise QiskitError(
|
||||
"{} instruction definition is {}; expected QuantumCircuit".format(
|
||||
other.name, type(other.definition)
|
||||
)
|
||||
f"{other.name} instruction definition is {type(other.definition)};"
|
||||
f" expected QuantumCircuit"
|
||||
)
|
||||
qubit_indices = {bit: idx for idx, bit in enumerate(other.definition.qubits)}
|
||||
for instruction in other.definition:
|
||||
|
|
|
@ -117,11 +117,9 @@ class Statevector(QuantumState, TolerancesMixin):
|
|||
def __repr__(self):
|
||||
prefix = "Statevector("
|
||||
pad = len(prefix) * " "
|
||||
return "{}{},\n{}dims={})".format(
|
||||
prefix,
|
||||
np.array2string(self._data, separator=", ", prefix=prefix),
|
||||
pad,
|
||||
self._op_shape.dims_l(),
|
||||
return (
|
||||
f"{prefix}{np.array2string(self._data, separator=', ', prefix=prefix)},\n{pad}"
|
||||
f"dims={self._op_shape.dims_l()})"
|
||||
)
|
||||
|
||||
@property
|
||||
|
@ -940,9 +938,7 @@ class Statevector(QuantumState, TolerancesMixin):
|
|||
raise QiskitError(f"Cannot apply Instruction: {obj.name}")
|
||||
if not isinstance(obj.definition, QuantumCircuit):
|
||||
raise QiskitError(
|
||||
"{} instruction definition is {}; expected QuantumCircuit".format(
|
||||
obj.name, type(obj.definition)
|
||||
)
|
||||
f"{obj.name} instruction definition is {type(obj.definition)}; expected QuantumCircuit"
|
||||
)
|
||||
|
||||
if obj.definition.global_phase:
|
||||
|
|
|
@ -130,7 +130,7 @@ class Counts(dict):
|
|||
max_values_counts = [x[0] for x in self.items() if x[1] == max_value]
|
||||
if len(max_values_counts) != 1:
|
||||
raise exceptions.QiskitError(
|
||||
"Multiple values have the same maximum counts: %s" % ",".join(max_values_counts)
|
||||
f"Multiple values have the same maximum counts: {','.join(max_values_counts)}"
|
||||
)
|
||||
return max_values_counts[0]
|
||||
|
||||
|
|
|
@ -54,8 +54,8 @@ class CorrelatedReadoutMitigator(BaseReadoutMitigator):
|
|||
else:
|
||||
if len(qubits) != matrix_qubits_num:
|
||||
raise QiskitError(
|
||||
"The number of given qubits ({}) is different than the number of "
|
||||
"qubits inferred from the matrices ({})".format(len(qubits), matrix_qubits_num)
|
||||
f"The number of given qubits ({len(qubits)}) is different than the number of "
|
||||
f"qubits inferred from the matrices ({matrix_qubits_num})"
|
||||
)
|
||||
self._qubits = qubits
|
||||
self._num_qubits = len(self._qubits)
|
||||
|
|
|
@ -68,8 +68,8 @@ class LocalReadoutMitigator(BaseReadoutMitigator):
|
|||
else:
|
||||
if len(qubits) != len(assignment_matrices):
|
||||
raise QiskitError(
|
||||
"The number of given qubits ({}) is different than the number of qubits "
|
||||
"inferred from the matrices ({})".format(len(qubits), len(assignment_matrices))
|
||||
f"The number of given qubits ({len(qubits)}) is different than the number of qubits "
|
||||
f"inferred from the matrices ({len(assignment_matrices)})"
|
||||
)
|
||||
self._qubits = qubits
|
||||
self._num_qubits = len(self._qubits)
|
||||
|
|
|
@ -120,9 +120,7 @@ def marganalize_counts(
|
|||
clbits_len = len(clbits) if not clbits is None else 0
|
||||
if clbits_len not in (0, qubits_len):
|
||||
raise QiskitError(
|
||||
"Num qubits ({}) does not match number of clbits ({}).".format(
|
||||
qubits_len, clbits_len
|
||||
)
|
||||
f"Num qubits ({qubits_len}) does not match number of clbits ({clbits_len})."
|
||||
)
|
||||
counts = marginal_counts(counts, clbits)
|
||||
if clbits is None and qubits is not None:
|
||||
|
|
|
@ -66,8 +66,7 @@ class ExperimentResultData:
|
|||
string_list = []
|
||||
for field in self._data_attributes:
|
||||
string_list.append(f"{field}={getattr(self, field)}")
|
||||
out = "ExperimentResultData(%s)" % ", ".join(string_list)
|
||||
return out
|
||||
return f"ExperimentResultData({', '.join(string_list)})"
|
||||
|
||||
def to_dict(self):
|
||||
"""Return a dictionary format representation of the ExperimentResultData
|
||||
|
@ -157,23 +156,21 @@ class ExperimentResult:
|
|||
self._metadata.update(kwargs)
|
||||
|
||||
def __repr__(self):
|
||||
out = "ExperimentResult(shots={}, success={}, meas_level={}, data={}".format(
|
||||
self.shots,
|
||||
self.success,
|
||||
self.meas_level,
|
||||
self.data,
|
||||
out = (
|
||||
f"ExperimentResult(shots={self.shots}, success={self.success},"
|
||||
f" meas_level={self.meas_level}, data={self.data}"
|
||||
)
|
||||
if hasattr(self, "header"):
|
||||
out += ", header=%s" % self.header
|
||||
out += f", header={self.header}"
|
||||
if hasattr(self, "status"):
|
||||
out += ", status=%s" % self.status
|
||||
out += f", status={self.status}"
|
||||
if hasattr(self, "seed"):
|
||||
out += ", seed=%s" % self.seed
|
||||
out += f", seed={self.seed}"
|
||||
if hasattr(self, "meas_return"):
|
||||
out += ", meas_return=%s" % self.meas_return
|
||||
out += f", meas_return={self.meas_return}"
|
||||
for key, value in self._metadata.items():
|
||||
if isinstance(value, str):
|
||||
value_str = "'%s'" % value
|
||||
value_str = f"'{value}'"
|
||||
else:
|
||||
value_str = repr(value)
|
||||
out += f", {key}={value_str}"
|
||||
|
|
|
@ -69,21 +69,14 @@ class Result:
|
|||
|
||||
def __repr__(self):
|
||||
out = (
|
||||
"Result(backend_name='%s', backend_version='%s', qobj_id='%s', "
|
||||
"job_id='%s', success=%s, results=%s"
|
||||
% (
|
||||
self.backend_name,
|
||||
self.backend_version,
|
||||
self.qobj_id,
|
||||
self.job_id,
|
||||
self.success,
|
||||
self.results,
|
||||
)
|
||||
f"Result(backend_name='{self.backend_name}', backend_version='{self.backend_version}',"
|
||||
f" qobj_id='{self.qobj_id}', job_id='{self.job_id}', success={self.success},"
|
||||
f" results={self.results}"
|
||||
)
|
||||
out += f", date={self.date}, status={self.status}, header={self.header}"
|
||||
for key, value in self._metadata.items():
|
||||
if isinstance(value, str):
|
||||
value_str = "'%s'" % value
|
||||
value_str = f"'{value}'"
|
||||
else:
|
||||
value_str = repr(value)
|
||||
out += f", {key}={value_str}"
|
||||
|
@ -236,10 +229,10 @@ class Result:
|
|||
|
||||
except KeyError as ex:
|
||||
raise QiskitError(
|
||||
'No memory for experiment "{}". '
|
||||
f'No memory for experiment "{repr(experiment)}". '
|
||||
"Please verify that you either ran a measurement level 2 job "
|
||||
'with the memory flag set, eg., "memory=True", '
|
||||
"or a measurement level 0/1 job.".format(repr(experiment))
|
||||
"or a measurement level 0/1 job."
|
||||
) from ex
|
||||
|
||||
def get_counts(self, experiment=None):
|
||||
|
@ -377,14 +370,14 @@ class Result:
|
|||
]
|
||||
|
||||
if len(exp) == 0:
|
||||
raise QiskitError('Data for experiment "%s" could not be found.' % key)
|
||||
raise QiskitError(f'Data for experiment "{key}" could not be found.')
|
||||
if len(exp) == 1:
|
||||
exp = exp[0]
|
||||
else:
|
||||
warnings.warn(
|
||||
'Result object contained multiple results matching name "%s", '
|
||||
f'Result object contained multiple results matching name "{key}", '
|
||||
"only first match will be returned. Use an integer index to "
|
||||
"retrieve results for all entries." % key
|
||||
"retrieve results for all entries."
|
||||
)
|
||||
exp = exp[0]
|
||||
|
||||
|
|
|
@ -145,9 +145,9 @@ def lower_gates(
|
|||
elif isinstance(instruction.operation, Measure):
|
||||
if len(inst_qubits) != 1 and len(instruction.clbits) != 1:
|
||||
raise QiskitError(
|
||||
"Qubit '{}' or classical bit '{}' errored because the "
|
||||
f"Qubit '{inst_qubits}' or classical bit '{instruction.clbits}' errored because the "
|
||||
"circuit Measure instruction only takes one of "
|
||||
"each.".format(inst_qubits, instruction.clbits)
|
||||
"each."
|
||||
)
|
||||
qubit_mem_slots[inst_qubits[0]] = clbit_indices[instruction.clbits[0]]
|
||||
else:
|
||||
|
|
|
@ -53,8 +53,7 @@ def synth_cnot_count_full_pmh(
|
|||
"""
|
||||
if not isinstance(state, (list, np.ndarray)):
|
||||
raise QiskitError(
|
||||
"state should be of type list or numpy.ndarray, "
|
||||
"but was of the type {}".format(type(state))
|
||||
f"state should be of type list or numpy.ndarray, but was of the type {type(state)}"
|
||||
)
|
||||
state = np.array(state)
|
||||
# Synthesize lower triangular part
|
||||
|
|
|
@ -116,7 +116,7 @@ def decompose_two_qubit_product_gate(special_unitary_matrix: np.ndarray):
|
|||
if deviation > 1.0e-13:
|
||||
raise QiskitError(
|
||||
"decompose_two_qubit_product_gate: decomposition failed: "
|
||||
"deviation too large: {}".format(deviation)
|
||||
f"deviation too large: {deviation}"
|
||||
)
|
||||
|
||||
return L, R, phase
|
||||
|
|
|
@ -101,7 +101,7 @@ class CouplingMap:
|
|||
raise CouplingError("Physical qubits should be integers.")
|
||||
if physical_qubit in self.physical_qubits:
|
||||
raise CouplingError(
|
||||
"The physical qubit %s is already in the coupling graph" % physical_qubit
|
||||
f"The physical qubit {physical_qubit} is already in the coupling graph"
|
||||
)
|
||||
self.graph.add_node(physical_qubit)
|
||||
self._dist_matrix = None # invalidate
|
||||
|
@ -188,9 +188,9 @@ class CouplingMap:
|
|||
CouplingError: if the qubits do not exist in the CouplingMap
|
||||
"""
|
||||
if physical_qubit1 >= self.size():
|
||||
raise CouplingError("%s not in coupling graph" % physical_qubit1)
|
||||
raise CouplingError(f"{physical_qubit1} not in coupling graph")
|
||||
if physical_qubit2 >= self.size():
|
||||
raise CouplingError("%s not in coupling graph" % physical_qubit2)
|
||||
raise CouplingError(f"{physical_qubit2} not in coupling graph")
|
||||
self.compute_distance_matrix()
|
||||
res = self._dist_matrix[physical_qubit1, physical_qubit2]
|
||||
if res == math.inf:
|
||||
|
|
|
@ -98,8 +98,8 @@ class Layout:
|
|||
virtual = value1
|
||||
else:
|
||||
raise LayoutError(
|
||||
"The map (%s -> %s) has to be a (Bit -> integer)"
|
||||
" or the other way around." % (type(value1), type(value2))
|
||||
f"The map ({type(value1)} -> {type(value2)}) has to be a (Bit -> integer)"
|
||||
" or the other way around."
|
||||
)
|
||||
return virtual, physical
|
||||
|
||||
|
@ -137,7 +137,7 @@ class Layout:
|
|||
else:
|
||||
raise LayoutError(
|
||||
"The key to remove should be of the form"
|
||||
" Qubit or integer) and %s was provided" % (type(key),)
|
||||
f" Qubit or integer) and {type(key)} was provided"
|
||||
)
|
||||
|
||||
def __len__(self):
|
||||
|
|
|
@ -302,9 +302,7 @@ class BasisTranslator(TransformationPass):
|
|||
if len(node.op.params) != len(target_params):
|
||||
raise TranspilerError(
|
||||
"Translation num_params not equal to op num_params."
|
||||
"Op: {} {} Translation: {}\n{}".format(
|
||||
node.op.params, node.op.name, target_params, target_dag
|
||||
)
|
||||
f"Op: {node.op.params} {node.op.name} Translation: {target_params}\n{target_dag}"
|
||||
)
|
||||
if node.op.params:
|
||||
parameter_map = dict(zip(target_params, node.op.params))
|
||||
|
|
|
@ -78,7 +78,7 @@ class Unroll3qOrMore(TransformationPass):
|
|||
continue
|
||||
raise QiskitError(
|
||||
"Cannot unroll all 3q or more gates. "
|
||||
"No rule to expand instruction %s." % node.op.name
|
||||
f"No rule to expand instruction {node.op.name}."
|
||||
)
|
||||
decomposition = circuit_to_dag(node.op.definition, copy_operations=False)
|
||||
decomposition = self.run(decomposition) # recursively unroll
|
||||
|
|
|
@ -95,9 +95,9 @@ class UnrollCustomDefinitions(TransformationPass):
|
|||
if unrolled is None:
|
||||
# opaque node
|
||||
raise QiskitError(
|
||||
"Cannot unroll the circuit to the given basis, %s. "
|
||||
"Instruction %s not found in equivalence library "
|
||||
"and no rule found to expand." % (str(self._basis_gates), node.op.name)
|
||||
f"Cannot unroll the circuit to the given basis, {str(self._basis_gates)}. "
|
||||
f"Instruction {node.op.name} not found in equivalence library "
|
||||
"and no rule found to expand."
|
||||
)
|
||||
|
||||
decomposition = circuit_to_dag(unrolled, copy_operations=False)
|
||||
|
|
|
@ -204,7 +204,7 @@ class RZXCalibrationBuilder(CalibrationBuilder):
|
|||
if cal_type in [CRCalType.ECR_CX_FORWARD, CRCalType.ECR_FORWARD]:
|
||||
xgate = self._inst_map.get("x", qubits[0])
|
||||
with builder.build(
|
||||
default_alignment="sequential", name="rzx(%.3f)" % theta
|
||||
default_alignment="sequential", name=f"rzx({theta:.3f})"
|
||||
) as rzx_theta_native:
|
||||
for cr_tone, comp_tone in zip(cr_tones, comp_tones):
|
||||
with builder.align_left():
|
||||
|
@ -230,7 +230,7 @@ class RZXCalibrationBuilder(CalibrationBuilder):
|
|||
builder.call(szt, name="szt")
|
||||
|
||||
with builder.build(
|
||||
default_alignment="sequential", name="rzx(%.3f)" % theta
|
||||
default_alignment="sequential", name=f"rzx({theta:.3f})"
|
||||
) as rzx_theta_flip:
|
||||
builder.call(hadamard, name="hadamard")
|
||||
for cr_tone, comp_tone in zip(cr_tones, comp_tones):
|
||||
|
@ -297,7 +297,7 @@ class RZXCalibrationBuilderNoEcho(RZXCalibrationBuilder):
|
|||
|
||||
# RZXCalibrationNoEcho only good for forward CR direction
|
||||
if cal_type in [CRCalType.ECR_CX_FORWARD, CRCalType.ECR_FORWARD]:
|
||||
with builder.build(default_alignment="left", name="rzx(%.3f)" % theta) as rzx_theta:
|
||||
with builder.build(default_alignment="left", name=f"rzx({theta:.3f})") as rzx_theta:
|
||||
stretched_dur = self.rescale_cr_inst(cr_tones[0], 2 * theta)
|
||||
self.rescale_cr_inst(comp_tones[0], 2 * theta)
|
||||
# Placeholder to make pulse gate work
|
||||
|
|
|
@ -53,8 +53,8 @@ class InverseCancellation(TransformationPass):
|
|||
)
|
||||
else:
|
||||
raise TranspilerError(
|
||||
"InverseCancellation pass does not take input type {}. Input must be"
|
||||
" a Gate.".format(type(gates))
|
||||
f"InverseCancellation pass does not take input type {type(gates)}. Input must be"
|
||||
" a Gate."
|
||||
)
|
||||
|
||||
self.self_inverse_gates = []
|
||||
|
|
|
@ -308,7 +308,7 @@ class Optimize1qGates(TransformationPass):
|
|||
if "u3" in self.basis:
|
||||
new_op = U3Gate(*right_parameters)
|
||||
else:
|
||||
raise TranspilerError("It was not possible to use the basis %s" % self.basis)
|
||||
raise TranspilerError(f"It was not possible to use the basis {self.basis}")
|
||||
|
||||
dag.global_phase += right_global_phase
|
||||
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue