Skip to content

Commit

Permalink
Add reno and black
Browse files Browse the repository at this point in the history
  • Loading branch information
nonhermitian committed Aug 8, 2023
1 parent d29577e commit ea7c1e6
Show file tree
Hide file tree
Showing 111 changed files with 64 additions and 202 deletions.
1 change: 0 additions & 1 deletion qiskit/algorithms/algorithm_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ def __str__(self) -> str:
and not inspect.isfunction(value)
and hasattr(self, name)
):

result[name] = value

return pprint.pformat(result, indent=4)
Expand Down
2 changes: 0 additions & 2 deletions qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,6 @@ def _get_energies(
def _eval_aux_operators(
aux_operators: ListOrDict[OperatorBase], wavefn, threshold: float = 1e-12
) -> ListOrDict[tuple[complex, complex]]:

values: ListOrDict[tuple[complex, complex]]

# As a list, aux_operators can contain None operators for which None values are returned.
Expand Down Expand Up @@ -241,7 +240,6 @@ def compute_eigenvalues(

# if a filter is set, loop over the given values and only keep
if self._filter_criterion:

eigvecs = []
eigvals = []
aux_ops = []
Expand Down
10 changes: 4 additions & 6 deletions qiskit/algorithms/eigen_solvers/vqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,6 @@ def compute_eigenvalues(
aux_values = []

for step in range(1, self.k + 1):

self._eval_count = 0
energy_evaluation, expectation = self.get_energy_evaluation(
step, operator, return_expectation=True, prev_states=result.optimal_parameters
Expand Down Expand Up @@ -627,7 +626,6 @@ def compute_eigenvalues(
aux_values.append(aux_value)

if step == 1:

logger.info(
"Ground state optimization complete in %s seconds.\n"
"Found opt_params %s in %s evals",
Expand Down Expand Up @@ -666,9 +664,10 @@ def get_energy_evaluation(
operator: OperatorBase,
return_expectation: bool = False,
prev_states: list[np.ndarray] | None = None,
) -> Callable[[np.ndarray], float | list[float]] | tuple[
Callable[[np.ndarray], float | list[float]], ExpectationBase
]:
) -> (
Callable[[np.ndarray], float | list[float]]
| tuple[Callable[[np.ndarray], float | list[float]], ExpectationBase]
):
"""Returns a function handle to evaluates the energy at given parameters for the ansatz.
This return value is the objective function to be passed to the optimizer for evaluation.
Expand Down Expand Up @@ -714,7 +713,6 @@ def get_energy_evaluation(
)

for state in range(step - 1):

prev_circ = self.ansatz.bind_parameters(prev_states[state])
overlap_op.append(~CircuitStateFn(prev_circ) @ CircuitStateFn(self.ansatz))

Expand Down
2 changes: 0 additions & 2 deletions qiskit/algorithms/eigensolvers/numpy_eigensolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,6 @@ def _eval_aux_operators(
wavefn: np.ndarray,
threshold: float = 1e-12,
) -> ListOrDict[tuple[complex, complex]]:

values: ListOrDict[tuple[complex, complex]]

# As a list, aux_operators can contain None operators for which None values are returned.
Expand Down Expand Up @@ -232,7 +231,6 @@ def compute_eigenvalues(
operator: BaseOperator | PauliSumOp,
aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None,
) -> NumPyEigensolverResult:

super().compute_eigenvalues(operator, aux_operators)

if operator.num_qubits is None or operator.num_qubits < 1:
Expand Down
1 change: 1 addition & 0 deletions qiskit/algorithms/gradients/reverse/bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from qiskit.circuit import QuantumCircuit, Parameter


# pylint: disable=inconsistent-return-statements
def bind(
circuits: QuantumCircuit | Iterable[QuantumCircuit],
Expand Down
7 changes: 4 additions & 3 deletions qiskit/algorithms/minimum_eigen_solvers/vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,9 +582,10 @@ def get_energy_evaluation(
self,
operator: OperatorBase,
return_expectation: bool = False,
) -> Callable[[np.ndarray], float | list[float]] | tuple[
Callable[[np.ndarray], float | list[float]], ExpectationBase
]:
) -> (
Callable[[np.ndarray], float | list[float]]
| tuple[Callable[[np.ndarray], float | list[float]], ExpectationBase]
):
"""Returns a function handle to evaluates the energy at given parameters for the ansatz.
This is the objective function to be passed to the optimizer that is used for evaluation.
Expand Down
7 changes: 4 additions & 3 deletions qiskit/algorithms/minimum_eigensolvers/sampling_vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,9 +258,10 @@ def _get_evaluate_energy(
operator: BaseOperator | PauliSumOp,
ansatz: QuantumCircuit,
return_best_measurement: bool = False,
) -> Callable[[np.ndarray], np.ndarray | float] | tuple[
Callable[[np.ndarray], np.ndarray | float], dict[str, Any]
]:
) -> (
Callable[[np.ndarray], np.ndarray | float]
| tuple[Callable[[np.ndarray], np.ndarray | float], dict[str, Any]]
):
"""Returns a function handle to evaluate the energy at given parameters.
This is the objective function to be passed to the optimizer that is used for evaluation.
Expand Down
1 change: 0 additions & 1 deletion qiskit/algorithms/optimizers/adam_amsgrad.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ def __init__(
self._v_eff = np.zeros(1)

if self._snapshot_dir:

with open(os.path.join(self._snapshot_dir, "adam_params.csv"), mode="w") as csv_file:
if self._amsgrad:
fieldnames = ["v", "v_eff", "m", "t"]
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/optimizers/aqgd.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ def minimize(

epoch = 0
converged = False
for (eta, mom_coeff) in zip(self._eta, self._momenta_coeff):
for eta, mom_coeff in zip(self._eta, self._momenta_coeff):
logger.info("Epoch: %4d | Stepsize: %6.4f | Momentum: %6.4f", epoch, eta, mom_coeff)

sum_max_iters = sum(self._maxiter[0 : epoch + 1])
Expand Down
1 change: 0 additions & 1 deletion qiskit/algorithms/optimizers/gradient_descent.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,6 @@ def start(
jac: Callable[[POINT], POINT] | None = None,
bounds: list[tuple[float, float]] | None = None,
) -> None:

self.state = GradientDescentState(
fun=fun,
jac=jac,
Expand Down
1 change: 0 additions & 1 deletion qiskit/algorithms/optimizers/gsls.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ def ls_optimize(
x_value = obj_fun(x)
n_evals += 1
while iter_count < self._options["maxiter"] and n_evals < self._options["max_eval"]:

# Determine set of sample points
directions, sample_set_x = self.sample_set(n, x, var_lb, var_ub, sample_set_size)

Expand Down
1 change: 0 additions & 1 deletion qiskit/algorithms/optimizers/nft.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,6 @@ def nakanishi_fujii_todo(
funcalls = 0

while True:

idx = niter % x0.size

if reset_interval > 0:
Expand Down
1 change: 0 additions & 1 deletion qiskit/algorithms/optimizers/umda.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,6 @@ def minimize(
jac: Callable[[POINT], POINT] | None = None,
bounds: list[tuple[float, float]] | None = None,
) -> OptimizerResult:

not_better_count = 0
result = OptimizerResult()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ def _get_unitary(
"""

if self._phase_estimation._sampler is not None:

evo = PauliEvolutionGate(hamiltonian, -pe_scale.scale, synthesis=evolution)
unitary = QuantumCircuit(evo.num_qubits)
unitary.append(evo, unitary.qubits)
Expand Down
1 change: 0 additions & 1 deletion qiskit/algorithms/phase_estimators/ipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ def _estimate_phase_iteratively(self, unitary, state_preparation):
omega_coef /= 2

if self._sampler is not None:

qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True
)
Expand Down
7 changes: 2 additions & 5 deletions qiskit/algorithms/state_fidelities/base_state_fidelity.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ class BaseStateFidelity(ABC):
"""

def __init__(self) -> None:

# use cache for preventing unnecessary circuit compositions
self._circuit_cache: Mapping[tuple[int, int], QuantumCircuit] = {}

Expand Down Expand Up @@ -81,7 +80,6 @@ def _preprocess_values(
)
return [[]]
else:

# Support ndarray
if isinstance(values, np.ndarray):
values = values.tolist()
Expand Down Expand Up @@ -168,8 +166,7 @@ def _construct_circuits(
)

circuits = []
for (circuit_1, circuit_2) in zip(circuits_1, circuits_2):

for circuit_1, circuit_2 in zip(circuits_1, circuits_2):
# TODO: improve caching, what if the circuit is modified without changing the id?
circuit = self._circuit_cache.get((id(circuit_1), id(circuit_2)))

Expand Down Expand Up @@ -226,7 +223,7 @@ def _construct_value_list(
elif len(values_1[0]) == 0:
values = list(values_2)
else:
for (val_1, val_2) in zip(values_1, values_2):
for val_1, val_2 in zip(values_1, values_2):
values.append(val_1 + val_2)

return values
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@ def _evaluate_aux_ops(


def _operator_to_matrix(operator: BaseOperator | PauliSumOp):

if isinstance(operator, PauliSumOp):
op_matrix = operator.to_spmatrix()
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ def __init__(
param_dict: Mapping[Parameter, float],
t_param: Parameter | None = None,
) -> None:

self._varqte_linear_solver = varqte_linear_solver
self._param_dict = param_dict
self._t_param = t_param
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ def _construct_modified_hamiltonian(hamiltonian: BaseOperator, energy: float) ->

@staticmethod
def _validate_grad_settings(gradient):

if gradient is not None:
if not hasattr(gradient, "_derivative_type"):
raise ValueError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ def metric_tensor(
try:
metric_tensor = self.qgt.run([ansatz], [param_values], [None]).result().qgts[0]
except Exception as exc:

raise AlgorithmError("The QFI primitive job failed!") from exc
return metric_tensor

Expand Down
1 change: 0 additions & 1 deletion qiskit/assembler/assemble_schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,6 @@ def _assemble_instructions(

acquire_instruction_map = defaultdict(list)
for time, instruction in sched.instructions:

if isinstance(instruction, instructions.Play):
if isinstance(instruction.pulse, (library.ParametricPulse, library.SymbolicPulse)):
is_backend_supported = True
Expand Down
1 change: 0 additions & 1 deletion qiskit/circuit/controlflow/while_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,6 @@ def __init__(
*,
label: str | None = None,
):

self._circuit = circuit
self._condition = validate_condition(condition)
self._label = label
Expand Down
2 changes: 0 additions & 2 deletions qiskit/circuit/library/arithmetic/integer_comparator.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,6 @@ def _build(self) -> None:
circuit.x(q_compare)
# condition never satisfied for values larger than or equal to 2^n
elif self.value < pow(2, self.num_state_qubits):

if self.num_state_qubits > 1:
twos = self._get_twos_complement()
for i in range(self.num_state_qubits):
Expand Down Expand Up @@ -239,7 +238,6 @@ def _build(self) -> None:
else:
circuit.ccx(qr_state[i], qr_ancilla[i - 1], qr_ancilla[i])
else:

# num_state_qubits == 1 and value == 1:
circuit.cx(qr_state[0], q_compare)

Expand Down
14 changes: 11 additions & 3 deletions qiskit/circuit/library/n_local/n_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,9 +285,17 @@ def entanglement_blocks(
@property
def entanglement(
self,
) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[
list[list[int]]
] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]:
) -> (
str
| list[str]
| list[list[str]]
| list[int]
| list[list[int]]
| list[list[list[int]]]
| list[list[list[list[int]]]]
| Callable[[int], str]
| Callable[[int], list[list[int]]]
):
"""Get the entanglement strategy.
Returns:
Expand Down
1 change: 0 additions & 1 deletion qiskit/compiler/assembler.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,6 @@ def _expand_parameters(circuits, run_config):
parameter_binds = run_config.parameter_binds

if parameter_binds and any(parameter_binds) or any(circuit.parameters for circuit in circuits):

# Unroll params here in order to handle ParamVects
all_bind_parameters = [
QuantumCircuit()._unroll_param_dict(bind).keys() for bind in parameter_binds
Expand Down
1 change: 0 additions & 1 deletion qiskit/dagcircuit/dagcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1777,7 +1777,6 @@ def layers(self):
return

for graph_layer in graph_layers:

# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in graph_layer if isinstance(node, DAGOpNode)]

Expand Down
1 change: 0 additions & 1 deletion qiskit/dagcircuit/dagdepnode.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ def __init__(
cindices=None,
nid=-1,
):

self.type = type
self._op = op
self.name = name
Expand Down
4 changes: 1 addition & 3 deletions qiskit/extensions/quantum_initializer/isometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ def __init__(self, isometry, num_ancillas_zero, num_ancillas_dirty, epsilon=_EPS
super().__init__("isometry", num_qubits, 0, [isometry])

def _define(self):

# TODO The inverse().inverse() is because there is code to uncompute (_gates_to_uncompute)
# an isometry, but not for generating its decomposition. It would be cheaper to do the
# later here instead.
Expand Down Expand Up @@ -292,7 +291,6 @@ def _append_mcg_up_to_diagonal(self, circ, q, gate, control_labels, target_label
return mcg_up_to_diag._get_diagonal()

def _define_qubit_role(self, q):

n = int(np.log2(self.iso_data.shape[0]))
m = int(np.log2(self.iso_data.shape[1]))

Expand Down Expand Up @@ -502,7 +500,7 @@ def _get_binary_rep_as_list(n, num_digits):


def _merge_UCGate_and_diag(single_qubit_gates, diag):
for (i, gate) in enumerate(single_qubit_gates):
for i, gate in enumerate(single_qubit_gates):
single_qubit_gates[i] = np.array([[diag[2 * i], 0.0], [0.0, diag[2 * i + 1]]]).dot(gate)
return single_qubit_gates

Expand Down
2 changes: 1 addition & 1 deletion qiskit/extensions/quantum_initializer/uc_pauli_rot.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def _dec_ucrot(self):
angles = self.params.copy()
UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False)
# Now, it is easy to place the C-NOT gates to get back the full decomposition.
for (i, angle) in enumerate(angles):
for i, angle in enumerate(angles):
if self.rot_axes == "X":
if np.abs(angle) > _EPS:
circuit.rx(angle, q_target)
Expand Down
2 changes: 0 additions & 2 deletions qiskit/opflow/converters/circuit_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,13 +420,11 @@ def resolve_param(inst_param):
def _prepare_parameterized_run_config(
self, param_bindings: List[Dict[Parameter, float]]
) -> List[Any]:

self.quantum_instance._run_config.parameterizations = []

if self._transpiled_circ_templates is None or len(self._transpiled_circ_templates) != len(
self._transpiled_circ_cache
):

# temporally resolve parameters of self._transpiled_circ_cache
# They will be overridden in Aer from the next iterations
self._transpiled_circ_templates = [
Expand Down
1 change: 0 additions & 1 deletion qiskit/opflow/expectations/expectation_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ def build(
# pylint: disable=cyclic-import
primitives = operator.primitive_strings()
if primitives in ({"Pauli"}, {"SparsePauliOp"}):

if backend_to_check is None:
# If user has Aer but didn't specify a backend, use the Aer fast expectation
if optionals.HAS_AER:
Expand Down
1 change: 0 additions & 1 deletion qiskit/opflow/gradients/circuit_gradients/lin_comb.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,6 @@ def _prepare_operator(
isinstance(params, list)
and all(isinstance(param, ParameterExpression) for param in params)
):

return self._gradient_states(
state_op,
meas_op=(2 * meas),
Expand Down
Loading

0 comments on commit ea7c1e6

Please sign in to comment.