Skip to content

Commit

Permalink
Bump black version and relax constraint (Qiskit#7615)
Browse files Browse the repository at this point in the history
This commit bumps the black version we pin to the latest release,
22.1.0. This release is also the first release not marked as beta and
with that black has introduced a stability policy where no formatting
changes will be introduced on a major version release (which is the
year). [1] With this new policy in place we no longer need to pin to a
single version and can instead constrain the requirement to just the
major version without worrying about a new release breaking ci or local
development. This commit does that and sets the black version
requirement to be any 22.x.y release so that we'll continue to get
bugfixes moving forward without having to manually bump a pinned version.

[1] https://black.readthedocs.io/en/latest/the_black_code_style/index.html#stability-policy
  • Loading branch information
mtreinish authored Feb 3, 2022
1 parent b059762 commit 8b672eb
Show file tree
Hide file tree
Showing 22 changed files with 52 additions and 52 deletions.
6 changes: 3 additions & 3 deletions qiskit/algorithms/amplitude_amplifiers/grover.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def __init__(

if growth_rate is not None:
# yield iterations ** 1, iterations ** 2, etc. and casts to int
self._iterations = map(lambda x: int(growth_rate ** x), itertools.count(1))
self._iterations = map(lambda x: int(growth_rate**x), itertools.count(1))
elif isinstance(iterations, int):
self._iterations = [iterations]
else:
Expand Down Expand Up @@ -195,7 +195,7 @@ def amplify(self, amplification_problem: AmplificationProblem) -> "GroverResult"
max_power = np.inf # no cap on the power
iterator = iter(self._iterations)
else:
max_iterations = max(10, 2 ** amplification_problem.oracle.num_qubits)
max_iterations = max(10, 2**amplification_problem.oracle.num_qubits)
max_power = np.ceil(
2 ** (len(amplification_problem.grover_operator.reflection_qubits) / 2)
)
Expand Down Expand Up @@ -292,7 +292,7 @@ def optimal_num_iterations(num_solutions: int, num_qubits: int) -> int:
Returns:
The optimal number of iterations for Grover's algorithm to succeed.
"""
amplitude = np.sqrt(num_solutions / 2 ** num_qubits)
amplitude = np.sqrt(num_solutions / 2**num_qubits)
return round(np.arccos(amplitude) / (2 * np.arcsin(amplitude)))

def construct_circuit(
Expand Down
12 changes: 6 additions & 6 deletions qiskit/algorithms/amplitude_estimators/ae.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def __init__(

# get parameters
self._m = num_eval_qubits # pylint: disable=invalid-name
self._M = 2 ** num_eval_qubits # pylint: disable=invalid-name
self._M = 2**num_eval_qubits # pylint: disable=invalid-name

self._iqft = iqft
self._pec = phase_estimation_circuit
Expand Down Expand Up @@ -194,7 +194,7 @@ def _evaluate_statevector_results(self, statevector):
if y >= int(self._M / 2):
y = self._M - y
# due to the finite accuracy of the sine, we round the result to 7 decimals
a = np.round(np.power(np.sin(y * np.pi / 2 ** self._m), 2), decimals=7)
a = np.round(np.power(np.sin(y * np.pi / 2**self._m), 2), decimals=7)
samples[a] = samples.get(a, 0) + probability

return samples, measurements
Expand All @@ -209,7 +209,7 @@ def _evaluate_count_results(self, counts):
y = int(state.replace(" ", "")[: self._m][::-1], 2)
probability = count / shots
measurements[y] = probability
a = np.round(np.power(np.sin(y * np.pi / 2 ** self._m), 2), decimals=7)
a = np.round(np.power(np.sin(y * np.pi / 2**self._m), 2), decimals=7)
samples[a] = samples.get(a, 0.0) + probability

return samples, measurements
Expand All @@ -229,7 +229,7 @@ def compute_mle(
The MLE for the provided result object.
"""
m = result.num_evaluation_qubits
M = 2 ** m # pylint: disable=invalid-name
M = 2**m # pylint: disable=invalid-name
qae = result.estimation

# likelihood function
Expand Down Expand Up @@ -481,7 +481,7 @@ def _compute_fisher_information(result: AmplitudeEstimationResult, observed: boo
fisher_information = None
mlv = result.mle # MLE in [0,1]
m = result.num_evaluation_qubits
M = 2 ** m # pylint: disable=invalid-name
M = 2**m # pylint: disable=invalid-name

if observed:
a_i = np.asarray(list(result.samples.keys()))
Expand Down Expand Up @@ -535,7 +535,7 @@ def _likelihood_ratio_confint(result: AmplitudeEstimationResult, alpha: float) -
# Compute the two intervals in which we the look for values above
# the likelihood ratio: the two bubbles next to the QAE estimate
m = result.num_evaluation_qubits
M = 2 ** m # pylint: disable=invalid-name
M = 2**m # pylint: disable=invalid-name
qae = result.estimation

y = int(np.round(M * np.arcsin(np.sqrt(qae)) / np.pi))
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/amplitude_estimators/ae_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def _derivative_beta(x, p):

def _pdf_a_single_angle(x, p, m, pi_delta):
"""Helper function for `pdf_a`."""
M = 2 ** m
M = 2**m

d = pi_delta(x, p)
res = np.sin(M * d) ** 2 / (M * np.sin(d)) ** 2 if d != 0 else 1
Expand Down Expand Up @@ -226,7 +226,7 @@ def derivative_log_pdf_a(x, p, m):
Returns:
float: d/dp log(PDF(x|p))
"""
M = 2 ** m
M = 2**m

if x not in [0, 1]:
num_p1 = 0
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/amplitude_estimators/fae.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def cos_estimate(power, shots):

if 2 ** (j + 1) * theta_ci[1] >= 3 * np.pi / 8 and j < self._maxiter:
j_0 = j
v = 2 ** j * np.sum(theta_ci)
v = 2**j * np.sum(theta_ci)
first_stage = False
else:
cos = cos_estimate(2 ** (j - 1), self._shots[1])
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/amplitude_estimators/mlae.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def __init__(
if evaluation_schedule < 0:
raise ValueError("The evaluation schedule cannot be < 0.")

self._evaluation_schedule = [0] + [2 ** j for j in range(evaluation_schedule)]
self._evaluation_schedule = [0] + [2**j for j in range(evaluation_schedule)]
else:
if any(value < 0 for value in evaluation_schedule):
raise ValueError("The elements of the evaluation schedule cannot be < 0.")
Expand Down Expand Up @@ -445,7 +445,7 @@ def _compute_fisher_information(
d_loglik += (2 * m_k + 1) * (h_k / tan + (shots_k - h_k) * tan)

d_loglik /= np.sqrt(a * (1 - a))
fisher_information = d_loglik ** 2 / len(all_hits)
fisher_information = d_loglik**2 / len(all_hits)

else:
fisher_information = sum(
Expand Down
8 changes: 4 additions & 4 deletions qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ def supports_aux_operators(cls) -> bool:

def _check_set_k(self, operator: OperatorBase) -> None:
if operator is not None:
if self._in_k > 2 ** operator.num_qubits:
self._k = 2 ** operator.num_qubits
if self._in_k > 2**operator.num_qubits:
self._k = 2**operator.num_qubits
logger.debug(
"WARNING: Asked for %s eigenvalues but max possible is %s.", self._in_k, self._k
)
Expand All @@ -123,7 +123,7 @@ def _solve(self, operator: OperatorBase) -> None:
for i, idx in enumerate(indices):
eigvec[idx, i] = 1.0
else:
if self._k >= 2 ** operator.num_qubits - 1:
if self._k >= 2**operator.num_qubits - 1:
logger.debug("SciPy doesn't support to get all eigenvalues, using NumPy instead.")
if operator.is_hermitian():
eigval, eigvec = np.linalg.eigh(operator.to_matrix())
Expand Down Expand Up @@ -221,7 +221,7 @@ def compute_eigenvalues(
k_orig = self._k
if self._filter_criterion:
# need to consider all elements if a filter is set
self._k = 2 ** operator.num_qubits
self._k = 2**operator.num_qubits

self._ret = EigensolverResult()
self._solve(operator)
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/factorizers/shor.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def factor(
counts = {}
for i, v in enumerate(up_qreg_density_mat_diag):
if not v == 0:
counts[bin(int(i))[2:].zfill(2 * n)] = v ** 2
counts[bin(int(i))[2:].zfill(2 * n)] = v**2
else:
circuit = self.construct_circuit(N=N, a=a, measurement=True)
counts = self._quantum_instance.execute(circuit).get_counts(circuit)
Expand Down
12 changes: 6 additions & 6 deletions qiskit/algorithms/linear_solvers/hhl.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def _get_delta(self, n_l: int, lambda_min: float, lambda_max: float) -> float:
The value of the scaling factor.
"""
formatstr = "#0" + str(n_l + 2) + "b"
lambda_min_tilde = np.abs(lambda_min * (2 ** n_l - 1) / lambda_max)
lambda_min_tilde = np.abs(lambda_min * (2**n_l - 1) / lambda_max)
# floating point precision can cause problems
if np.abs(lambda_min_tilde - 1) < 1e-7:
lambda_min_tilde = 1
Expand Down Expand Up @@ -356,7 +356,7 @@ def construct_circuit(
raise ValueError("Input matrix dimension must be 2^n!")
if not np.allclose(matrix, matrix.conj().T):
raise ValueError("Input matrix must be hermitian!")
if matrix.shape[0] != 2 ** vector_circuit.num_qubits:
if matrix.shape[0] != 2**vector_circuit.num_qubits:
raise ValueError(
"Input vector dimension does not match input "
"matrix dimension! Vector dimension: "
Expand Down Expand Up @@ -392,11 +392,11 @@ def construct_circuit(
# the most to the solution of the system. -1 to take into account the sign qubit
delta = self._get_delta(nl - neg_vals, lambda_min, lambda_max)
# Update evolution time
matrix_circuit.evolution_time = 2 * np.pi * delta / lambda_min / (2 ** neg_vals)
matrix_circuit.evolution_time = 2 * np.pi * delta / lambda_min / (2**neg_vals)
# Update the scaling of the solution
self.scaling = lambda_min
else:
delta = 1 / (2 ** nl)
delta = 1 / (2**nl)
print("The solution will be calculated up to a scaling factor.")

if self._exact_reciprocal:
Expand All @@ -405,7 +405,7 @@ def construct_circuit(
na = matrix_circuit.num_ancillas
else:
# Calculate breakpoints for the reciprocal approximation
num_values = 2 ** nl
num_values = 2**nl
constant = delta
a = int(round(num_values ** (2 / 3)))

Expand All @@ -432,7 +432,7 @@ def construct_circuit(
breakpoints = []
for i in range(0, num_intervals):
# Add the breakpoint to the list
breakpoints.append(a * (5 ** i))
breakpoints.append(a * (5**i))

# Define the right breakpoint of the interval
if i == num_intervals - 1:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,13 @@ def matrix(self) -> np.ndarray:
matrix = diags(
[self.off_diag, self.main_diag, self.off_diag],
[-1, 0, 1],
shape=(2 ** self.num_state_qubits, 2 ** self.num_state_qubits),
shape=(2**self.num_state_qubits, 2**self.num_state_qubits),
).toarray()
return matrix

def eigs_bounds(self) -> Tuple[float, float]:
"""Return lower and upper bounds on the eigenvalues of the matrix."""
n_b = 2 ** self.num_state_qubits
n_b = 2**self.num_state_qubits
# Calculate the eigenvalues according to the formula for Toeplitz matrices
eig_1 = np.abs(self.main_diag - 2 * self.off_diag * np.cos(n_b * np.pi / (n_b + 1)))
eig_2 = np.abs(self.main_diag - 2 * self.off_diag * np.cos(np.pi / (n_b + 1)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def post_processing(
else:
raise ValueError("Solution probability must be given as a single value.")

return np.real(np.sqrt(solution / (2 ** num_qubits)) / scaling)
return np.real(np.sqrt(solution / (2**num_qubits)) / scaling)

def evaluate_classically(self, solution: Union[np.array, QuantumCircuit]) -> float:
"""Evaluates the given observable on the solution to the linear system.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ def post_processing(
# Calculate the value from the off-diagonal elements
off_val = 0
for i in range(1, len(solution), 2):
off_val += (solution[i] - solution[i + 1]) / (scaling ** 2)
main_val = solution[0] / (scaling ** 2)
off_val += (solution[i] - solution[i + 1]) / (scaling**2)
main_val = solution[0] / (scaling**2)
return np.real(self._main_diag * main_val + self._off_diag * off_val)

def evaluate_classically(self, solution: Union[np.array, QuantumCircuit]) -> float:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/optimizers/adam_amsgrad.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def minimize(
self._t += 1
self._m = self._beta_1 * self._m + (1 - self._beta_1) * derivative
self._v = self._beta_2 * self._v + (1 - self._beta_2) * derivative * derivative
lr_eff = self._lr * np.sqrt(1 - self._beta_2 ** self._t) / (1 - self._beta_1 ** self._t)
lr_eff = self._lr * np.sqrt(1 - self._beta_2**self._t) / (1 - self._beta_1**self._t)
if not self._amsgrad:
params_new = params - lr_eff * self._m.flatten() / (
np.sqrt(self._v.flatten()) + self._noise_factor
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/optimizers/qnspsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def _point_sample(self, loss, x, eps, delta1, delta2):
# compute the preconditioner point estimate
diff = fidelity_values[2] - fidelity_values[0]
diff -= fidelity_values[3] - fidelity_values[1]
diff /= 2 * eps ** 2
diff /= 2 * eps**2

rank_one = np.outer(delta1, delta2)
# -0.5 factor comes from the fact that we need -0.5 * fidelity
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/optimizers/spsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ def calibrate(
avg_magnitudes /= steps

if modelspace:
a = target_magnitude / (avg_magnitudes ** 2)
a = target_magnitude / (avg_magnitudes**2)
else:
a = target_magnitude / avg_magnitudes

Expand Down Expand Up @@ -430,7 +430,7 @@ def _point_sample(self, loss, x, eps, delta1, delta2):
hessian_sample = None
if self.second_order:
diff = (values[2] - plus) - (values[3] - minus)
diff /= 2 * eps ** 2
diff /= 2 * eps**2

rank_one = np.outer(delta1, delta2)
hessian_sample = diff * (rank_one + rank_one.T) / 2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def _bit_string_to_phase(binary_string: str) -> float:
A phase scaled to :math:`[0,1)`.
"""
n_qubits = len(binary_string)
return int(binary_string, 2) / (2 ** n_qubits)
return int(binary_string, 2) / (2**n_qubits)


def _sort_phases(phases: Dict) -> Dict:
Expand Down
2 changes: 1 addition & 1 deletion test/python/algorithms/optimizers/test_gradient_descent.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def learning_rate():
def powerlaw():
n = 0
while True:
yield constant_coeff * (n ** power)
yield constant_coeff * (n**power)
n += 1

return powerlaw()
Expand Down
2 changes: 1 addition & 1 deletion test/python/algorithms/optimizers/test_optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ def test_spsa_custom_iterators(self):
def powerlaw():
n = 0
while True:
yield rate ** n
yield rate**n
n += 1

def steps():
Expand Down
2 changes: 1 addition & 1 deletion test/python/algorithms/optimizers/test_spsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def test_recalibrate_at_optimize(self):
"""Test SPSA calibrates anew upon each optimization run, if no autocalibration is set."""

def objective(x):
return -(x ** 2)
return -(x**2)

spsa = SPSA(maxiter=1)
_ = spsa.optimize(1, objective, initial_point=np.array([0.5]))
Expand Down
12 changes: 6 additions & 6 deletions test/python/algorithms/test_amplitude_estimators.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ def __init__(self, num_qubits):
self.h(qr_state)

# apply the sine/cosine term
self.ry(2 * 1 / 2 / 2 ** num_qubits, qr_objective[0])
self.ry(2 * 1 / 2 / 2**num_qubits, qr_objective[0])
for i, qubit in enumerate(qr_state):
self.cry(2 * 2 ** i / 2 ** num_qubits, qubit, qr_objective[0])
self.cry(2 * 2**i / 2**num_qubits, qubit, qr_objective[0])


@ddt
Expand Down Expand Up @@ -197,7 +197,7 @@ def test_qae_circuit(self, efficient_circuit):
if efficient_circuit:
qae.grover_operator = BernoulliGrover(prob)
for power in range(m):
circuit.cry(2 * 2 ** power * angle, qr_eval[power], qr_objective[0])
circuit.cry(2 * 2**power * angle, qr_eval[power], qr_objective[0])
else:
oracle = QuantumCircuit(1)
oracle.z(0)
Expand All @@ -207,7 +207,7 @@ def test_qae_circuit(self, efficient_circuit):
grover_op = GroverOperator(oracle, state_preparation)
for power in range(m):
circuit.compose(
grover_op.power(2 ** power).control(),
grover_op.power(2**power).control(),
qubits=[qr_eval[power], qr_objective[0]],
inplace=True,
)
Expand Down Expand Up @@ -286,15 +286,15 @@ def test_mlae_circuits(self, efficient_circuit):
# Q^(2^j) operator
if efficient_circuit:
qae.grover_operator = BernoulliGrover(prob)
circuit.ry(2 * 2 ** power * angle, q_objective[0])
circuit.ry(2 * 2**power * angle, q_objective[0])

else:
oracle = QuantumCircuit(1)
oracle.z(0)
state_preparation = QuantumCircuit(1)
state_preparation.ry(angle, 0)
grover_op = GroverOperator(oracle, state_preparation)
for _ in range(2 ** power):
for _ in range(2**power):
circuit.compose(grover_op, inplace=True)
circuits += [circuit]

Expand Down
6 changes: 3 additions & 3 deletions test/python/algorithms/test_grover.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def zero():
n = 5
problem = AmplificationProblem(Statevector.from_label("1" * n), is_good_state=["1" * n])
result = grover.amplify(problem)
self.assertEqual(len(result.iterations), 2 ** n)
self.assertEqual(len(result.iterations), 2**n)

def test_max_power(self):
"""Test the iteration stops when the maximum power is reached."""
Expand Down Expand Up @@ -209,8 +209,8 @@ def test_run_custom_grover_operator(self):
def test_optimal_num_iterations(self):
"""Test optimal_num_iterations"""
num_qubits = 7
for num_solutions in range(1, 2 ** num_qubits):
amplitude = np.sqrt(num_solutions / 2 ** num_qubits)
for num_solutions in range(1, 2**num_qubits):
amplitude = np.sqrt(num_solutions / 2**num_qubits)
expected = round(np.arccos(amplitude) / (2 * np.arcsin(amplitude)))
actual = Grover.optimal_num_iterations(num_solutions, num_qubits)
self.assertEqual(actual, expected)
Expand Down
Loading

0 comments on commit 8b672eb

Please sign in to comment.