Skip to content

Commit

Permalink
Run latest Black version (#676)
Browse files Browse the repository at this point in the history
* run latest black

* update dev_requirements

* downgrade black

* back to latest black

* update and pin doc requirements

* update req

* bumpy req

* remove tf in docs

* revert req

* fix

* revert tf-backend in docs

* fix codefactor issues
  • Loading branch information
thisac committed Feb 2, 2022
1 parent 5b0ea3a commit 529e97e
Show file tree
Hide file tree
Showing 42 changed files with 203 additions and 207 deletions.
2 changes: 1 addition & 1 deletion dev_requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ pytest-cov>=2.11.1
pytest-mock>=3.5.1
pytest-randomly>=3.5.0
typing-extensions==3.7.4
black>=19.3b0
black>=22.1.0
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"sphinx.ext.intersphinx",
"sphinx_automodapi.automodapi",
'sphinx_copybutton',
"m2r"
"m2r2"
]


Expand Down
25 changes: 13 additions & 12 deletions doc/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
docutils==0.16
appdirs
ipykernel
appdirs==1.4.4
black==19.10b0
ipykernel==6.7.0
sphinx==2.2.2
m2r
m2r2==0.3.1
numba==0.53.1
networkx>=2.0
numpy>=1.19.2
plotly
quantum-blackbird
scipy>=1.0.0
sklearn
networkx==2.6.3
numpy==1.19.2
plotly==4.4.1
quantum-blackbird==0.4.0
scipy==1.7.1
scikit-learn==1.0.2
sphinx-autodoc-typehints==1.10.3
sphinx-copybutton
sphinx-copybutton==0.4.0
sphinx-automodapi==0.13
sphinxcontrib-bibtex==0.4.2
tensorflow==2.6.1
thewalrus>=0.17.0
toml
thewalrus==0.18.0
toml==0.10.2
mistune==0.8.4
2 changes: 1 addition & 1 deletion strawberryfields/apps/points.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def rbf_kernel(R: np.ndarray, sigma: float) -> np.ndarray:
Returns:
K (array): the RBF kernel matrix
"""
return np.exp(-((scipy.spatial.distance.cdist(R, R)) ** 2) / 2 / sigma ** 2)
return np.exp(-((scipy.spatial.distance.cdist(R, R)) ** 2) / 2 / sigma**2)


def sample(K: np.ndarray, n_mean: float, n_samples: int) -> list:
Expand Down
6 changes: 3 additions & 3 deletions strawberryfields/apps/qchem/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ def duschinsky(
"""
U = Lf.T @ Li

d = Lf.T * m ** 0.5 @ (ri - rf)
d = Lf.T * m**0.5 @ (ri - rf)

l0_inv = np.diag((h / (wf * 100.0 * c)) ** (-0.5) * 2.0 * pi) / 1.0e10 * m_u ** 0.5
l0_inv = np.diag((h / (wf * 100.0 * c)) ** (-0.5) * 2.0 * pi) / 1.0e10 * m_u**0.5

delta = np.array(d @ l0_inv)

Expand Down Expand Up @@ -141,7 +141,7 @@ def read_gamess(file) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
tuple[array, array, array, array]: atomic coordinates, atomic masses, normal mode
frequencies, normal modes
"""
with open(file, "r") as f:
with open(file, "r", encoding="utf-8") as f:

r = []
m = []
Expand Down
2 changes: 1 addition & 1 deletion strawberryfields/apps/qchem/vibronic.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def gbs_params(
else:
t = np.zeros(len(w))

U2, s, U1 = np.linalg.svd(np.diag(wp ** 0.5) @ Ud @ np.diag(w ** -0.5))
U2, s, U1 = np.linalg.svd(np.diag(wp**0.5) @ Ud @ np.diag(w**-0.5))
alpha = delta / np.sqrt(2)

return t, U1, np.log(s), U2, alpha
Expand Down
26 changes: 13 additions & 13 deletions strawberryfields/backends/bosonicbackend/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ def prepare_cat(self, a, theta, p, representation, ampl_cutoff, D):
return weights, means, covs

# Normalization factor
norm = 1 / (2 * (1 + np.exp(-2 * a ** 2) * np.cos(phi)))
norm = 1 / (2 * (1 + np.exp(-2 * a**2) * np.cos(phi)))
hbar = self.circuit.hbar

if representation == "complex":
Expand Down Expand Up @@ -469,16 +469,16 @@ def prepare_cat_real_rep(self, a, theta, p, ampl_cutoff, D):

# Normalization factor
phi = np.pi * p
norm = 1 / (2 * (1 + np.exp(-2 * a ** 2) * np.cos(phi)))
norm = 1 / (2 * (1 + np.exp(-2 * a**2) * np.cos(phi)))
hbar = self.circuit.hbar

# Defining useful constants
E = np.pi ** 2 * D * hbar / (16 * a ** 2)
E = np.pi**2 * D * hbar / (16 * a**2)
v = hbar / 2
num_mean = 8 * a * np.sqrt(hbar) / (np.pi * D * np.sqrt(2))
denom_mean = 16 * a ** 2 / (np.pi ** 2 * D) + 2
coef_sigma = np.pi ** 2 * hbar / (8 * a ** 2 * (E + v))
prefac = np.sqrt(np.pi * hbar) * np.exp(0.25 * np.pi ** 2 * D) / (4 * a) / (np.sqrt(E + v))
denom_mean = 16 * a**2 / (np.pi**2 * D) + 2
coef_sigma = np.pi**2 * hbar / (8 * a**2 * (E + v))
prefac = np.sqrt(np.pi * hbar) * np.exp(0.25 * np.pi**2 * D) / (4 * a) / (np.sqrt(E + v))
z_max = int(
np.ceil(
2
Expand All @@ -499,8 +499,8 @@ def prepare_cat_real_rep(self, a, theta, p, ampl_cutoff, D):
even_phases = (-1) ** ((term_inds % 4) // 2)
odd_phases = (-1) ** (1 + ((term_inds + 2) % 4) // 2)
weights = np.cos(phi) * even_terms * even_phases * np.exp(
-0.5 * coef_sigma * p_means ** 2
) - np.sin(phi) * odd_terms * odd_phases * np.exp(-0.5 * coef_sigma * p_means ** 2)
-0.5 * coef_sigma * p_means**2
) - np.sin(phi) * odd_terms * odd_phases * np.exp(-0.5 * coef_sigma * p_means**2)
weights *= prefac
weights_real = np.ones(2, dtype=float)
weights = norm * np.concatenate((weights_real, weights))
Expand Down Expand Up @@ -610,7 +610,7 @@ def coeff(peak_loc):
prefactor = np.exp(
-np.pi
* 0.25
* (l ** 2 + m ** 2)
* (l**2 + m**2)
* (1 - np.exp(-2 * epsilon))
/ (1 + np.exp(-2 * epsilon))
)
Expand Down Expand Up @@ -683,7 +683,7 @@ def prepare_fock(self, n, r=0.05):
Raises:
ValueError: if :math:`1/r^2` is less than :math:`n`
"""
if 1 / r ** 2 < n:
if 1 / r**2 < n:
raise ValueError(f"The parameter 1 / r ** 2={1 / r ** 2} is smaller than n={n}")
# A simple function to calculate the parity
parity = lambda n: 1 if n % 2 == 0 else -1
Expand All @@ -694,14 +694,14 @@ def prepare_fock(self, n, r=0.05):
0.5
* self.circuit.hbar
* np.identity(2)
* (1 + (n - j) * r ** 2)
/ (1 - (n - j) * r ** 2)
* (1 + (n - j) * r**2)
/ (1 - (n - j) * r**2)
for j in range(n + 1)
]
)
weights = np.array(
[
(1 - n * (r ** 2)) / (1 - (n - j) * (r ** 2)) * comb(n, j) * parity(j)
(1 - n * (r**2)) / (1 - (n - j) * (r**2)) * comb(n, j) * parity(j)
for j in range(n + 1)
],
dtype=complex,
Expand Down
12 changes: 6 additions & 6 deletions strawberryfields/backends/bosonicbackend/bosoniccircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def w_shape(num_modes, num_gauss):
Returns:
int: number of weights for all Gaussian peaks in phase space
"""
return num_gauss ** num_modes
return num_gauss**num_modes


def m_shape(num_modes, num_gauss):
Expand All @@ -46,7 +46,7 @@ def m_shape(num_modes, num_gauss):
Returns:
tuple: (number of weights, number of quadratures)
"""
return (num_gauss ** num_modes, 2 * num_modes)
return (num_gauss**num_modes, 2 * num_modes)


def c_shape(num_modes, num_gauss):
Expand All @@ -60,7 +60,7 @@ def c_shape(num_modes, num_gauss):
tuple: (number of weights, number of quadratures, number of quadratures)
"""
num_quad = 2 * num_modes
return (num_gauss ** num_modes, num_quad, num_quad)
return (num_gauss**num_modes, num_quad, num_quad)


def to_xp(num_modes):
Expand Down Expand Up @@ -233,7 +233,7 @@ def reset(self, num_subsystems=None, num_weights=1):
self.from_xp = from_xp(self.nlen)

self.weights = np.ones(w_shape(self.nlen, num_weights), dtype=complex)
self.weights = self.weights / (num_weights ** self.nlen)
self.weights = self.weights / (num_weights**self.nlen)

self.means = np.zeros(m_shape(self.nlen, num_weights), dtype=complex)
id_covs = [np.identity(2 * self.nlen, dtype=complex) for i in range(len(self.weights))]
Expand Down Expand Up @@ -876,7 +876,7 @@ def homodyne(self, mode, shots=1, eps=0.0002):
Returns:
array: homodyne outcome
"""
covmat = self.hbar * np.diag(np.array([eps ** 2, 1.0 / eps ** 2])) / 2
covmat = self.hbar * np.diag(np.array([eps**2, 1.0 / eps**2])) / 2
return self.measure_dyne(covmat, [mode], shots=shots)

def heterodyne(self, mode, shots=1):
Expand Down Expand Up @@ -957,7 +957,7 @@ def post_select_homodyne(self, mode, val, eps=0.0002, phi=0):
if self.active[mode] is None:
raise ValueError("Cannot apply homodyne measurement, mode does not exist.")
self.phase_shift(phi, mode)
covmat = self.hbar * np.diag(np.array([eps ** 2, 1.0 / eps ** 2])) / 2
covmat = self.hbar * np.diag(np.array([eps**2, 1.0 / eps**2])) / 2
indices = [mode]
vals = np.array([val, 0])
self.post_select_generaldyne(covmat, indices, vals)
Expand Down
11 changes: 6 additions & 5 deletions strawberryfields/backends/fockbackend/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def apply_gate_BLAS(self, mat, modes, **kwargs):
n = kwargs.get("n", self._num_modes)

size = len(modes)
dim = self._trunc ** size
dim = self._trunc**size
stshape = [self._trunc for i in range(size)]

# Apply the following matrix transposition:
Expand Down Expand Up @@ -416,10 +416,11 @@ def prepare_multimode(self, state, modes):
n_modes = len(modes)
pure_shape = tuple([self._trunc] * n_modes)
mixed_shape = tuple([self._trunc] * (2 * n_modes))
pure_shape_as_vector = tuple([self._trunc ** n_modes])
mixed_shape_as_matrix = tuple([self._trunc ** n_modes] * 2)
pure_shape_as_vector = tuple([self._trunc**n_modes])
mixed_shape_as_matrix = tuple([self._trunc**n_modes] * 2)

# Do consistency checks
# pylint: disable=consider-using-in
if self._checks:
if (
state.shape != pure_shape
Expand Down Expand Up @@ -745,12 +746,12 @@ def measure_homodyne(self, phi, mode, select=None, **kwargs):
q_tensor, Hvals = ops.hermiteVals(q_mag, num_bins, m_omega_over_hbar, self._trunc)
H_matrix = np.zeros((self._trunc, self._trunc, num_bins))
for n, m in product(range(self._trunc), repeat=2):
H_matrix[n][m] = 1 / sqrt(2 ** n * bang(n) * 2 ** m * bang(m)) * Hvals[n] * Hvals[m]
H_matrix[n][m] = 1 / sqrt(2**n * bang(n) * 2**m * bang(m)) * Hvals[n] * Hvals[m]
H_terms = np.expand_dims(reduced, -1) * np.expand_dims(H_matrix, 0)
rho_dist = (
np.sum(H_terms, axis=(1, 2))
* (m_omega_over_hbar / pi) ** 0.5
* np.exp(-m_omega_over_hbar * q_tensor ** 2)
* np.exp(-m_omega_over_hbar * q_tensor**2)
* (q_tensor[1] - q_tensor[0])
) # Delta_q for normalization (only works if the bins are equally spaced)

Expand Down
10 changes: 5 additions & 5 deletions strawberryfields/backends/fockbackend/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def abssqr(z):
r"""
Given :math:`z` returns :math:`|z|^2`.
"""
return z.real ** 2 + z.imag ** 2
return z.real**2 + z.imag**2


def dagger(mat):
Expand Down Expand Up @@ -277,7 +277,7 @@ def kerr(kappa, trunc):
The Kerr interaction :math:`K(\kappa)`.
"""
n = np.arange(trunc)
ret = np.diag(np.exp(1j * kappa * n ** 2))
ret = np.diag(np.exp(1j * kappa * n**2))
return ret


Expand Down Expand Up @@ -397,7 +397,7 @@ def coherentState(r, phi, trunc):

def entry(n):
"""coherent summation term"""
return alpha ** n / sqrt(fac(n))
return alpha**n / sqrt(fac(n))

return exp(-abssqr(alpha) / 2) * array([entry(n) for n in range(trunc)])

Expand All @@ -410,7 +410,7 @@ def squeezedState(r, theta, trunc):

def entry(n):
"""squeezed summation term"""
return (sqrt(fac(2 * n)) / (2 ** n * fac(n))) * (-exp(1j * theta) * tanh(r)) ** n
return (sqrt(fac(2 * n)) / (2**n * fac(n))) * (-exp(1j * theta) * tanh(r)) ** n

vec = array([entry(n // 2) if n % 2 == 0 else 0.0 + 0.0j for n in range(trunc)])
return sqrt(1 / cosh(r)) * vec
Expand Down Expand Up @@ -455,7 +455,7 @@ def thermalState(nbar, trunc):
st = fockState(0, trunc)
state = np.outer(st, st.conjugate())
else:
coeff = np.array([nbar ** n / (nbar + 1) ** (n + 1) for n in range(trunc)])
coeff = np.array([nbar**n / (nbar + 1) ** (n + 1) for n in range(trunc)])
state = np.diag(coeff)

return state
Expand Down
44 changes: 19 additions & 25 deletions strawberryfields/backends/gaussianbackend/gaussiancircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,20 +365,17 @@ def qmat(self, modes=None):
rows = np.reshape(modes, [-1, 1])
cols = np.reshape(modes, [1, -1])

sigmaq = (
np.concatenate(
(
np.concatenate(
(self.nmat[rows, cols], np.conjugate(self.mmat[rows, cols])), axis=1
),
np.concatenate(
(self.mmat[rows, cols], np.conjugate(self.nmat[rows, cols])), axis=1
),
sigmaq = np.concatenate(
(
np.concatenate(
(self.nmat[rows, cols], np.conjugate(self.mmat[rows, cols])), axis=1
),
axis=0,
)
+ np.identity(2 * len(modes))
)
np.concatenate(
(self.mmat[rows, cols], np.conjugate(self.nmat[rows, cols])), axis=1
),
),
axis=0,
) + np.identity(2 * len(modes))
return sigmaq

def fidelity_coherent(self, alpha, modes=None):
Expand Down Expand Up @@ -406,16 +403,13 @@ def fidelity_vacuum(self, modes=None):
def Amat(self):
"""Constructs the A matrix from Hamilton's paper"""
######### this needs to be conjugated
sigmaq = (
np.concatenate(
(
np.concatenate((np.transpose(self.nmat), self.mmat), axis=1),
np.concatenate((np.transpose(np.conjugate(self.mmat)), self.nmat), axis=1),
),
axis=0,
)
+ np.identity(2 * self.nlen)
)
sigmaq = np.concatenate(
(
np.concatenate((np.transpose(self.nmat), self.mmat), axis=1),
np.concatenate((np.transpose(np.conjugate(self.mmat)), self.nmat), axis=1),
),
axis=0,
) + np.identity(2 * self.nlen)
return np.dot(Xmat(self.nlen), np.identity(2 * self.nlen) - np.linalg.inv(sigmaq))

def loss(self, T, k):
Expand Down Expand Up @@ -489,7 +483,7 @@ def measure_dyne(self, covmat, indices, shots=1):
def homodyne(self, n, shots=1, eps=0.0002):
"""Performs a homodyne measurement by calling measure dyne an giving it the
covariance matrix of a squeezed state whose x quadrature has variance eps**2"""
covmat = np.diag(np.array([eps ** 2, 1.0 / eps ** 2]))
covmat = np.diag(np.array([eps**2, 1.0 / eps**2]))
res = self.measure_dyne(covmat, [n], shots=shots)

return res
Expand All @@ -498,7 +492,7 @@ def post_select_homodyne(self, n, val, eps=0.0002):
"""Performs a homodyne measurement but postelecting on the value vals for mode n"""
if self.active[n] is None:
raise ValueError("Cannot apply homodyne measurement, mode does not exist")
covmat = np.diag(np.array([eps ** 2, 1.0 / eps ** 2]))
covmat = np.diag(np.array([eps**2, 1.0 / eps**2]))
indices = [n]
expind = np.concatenate((2 * np.array(indices), 2 * np.array(indices) + 1))
mp = self.scovmat()
Expand Down

0 comments on commit 529e97e

Please sign in to comment.