Skip to content

Commit

Permalink
Merge pull request #206 from CSSFrancis/apply_black
Browse files Browse the repository at this point in the history
Black:  Applied black formatting
  • Loading branch information
hakonanes committed Apr 14, 2024
2 parents 80473c8 + 2201fd3 commit df42e4e
Show file tree
Hide file tree
Showing 22 changed files with 67 additions and 73 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ Added
- Explicit support for Python 3.11.
- Added Pre-Commit for code formatting.


Changed
-------
- Documentation theme from Furo to the PyData-Sphinx-Theme.
- Ran ``black`` formatting to update the code style.

Deprecated
----------
Expand Down
6 changes: 3 additions & 3 deletions diffsims/generators/diffraction_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ def calculate_ed_data(
r_spot = np.sqrt(np.sum(np.square(cartesian_coordinates[:, :2]), axis=1))
z_spot = cartesian_coordinates[:, 2]

z_sphere = -np.sqrt(r_sphere ** 2 - r_spot ** 2) + r_sphere
z_sphere = -np.sqrt(r_sphere**2 - r_spot**2) + r_sphere
excitation_error = z_sphere - z_spot

# determine the pre-selection reflections
Expand All @@ -270,8 +270,8 @@ def calculate_ed_data(
P_z = r_sphere * np.cos(np.deg2rad(self.precession_angle))
P_t = r_sphere * np.sin(np.deg2rad(self.precession_angle))
# the extremes of the ewald sphere
z_surf_up = P_z - np.sqrt(r_sphere ** 2 - (r_spot + P_t) ** 2)
z_surf_do = P_z - np.sqrt(r_sphere ** 2 - (r_spot - P_t) ** 2)
z_surf_up = P_z - np.sqrt(r_sphere**2 - (r_spot + P_t) ** 2)
z_surf_do = P_z - np.sqrt(r_sphere**2 - (r_spot - P_t) ** 2)
intersection = (z_spot - max_excitation_error <= z_surf_up) & (
z_spot + max_excitation_error >= z_surf_do
)
Expand Down
2 changes: 1 addition & 1 deletion diffsims/release_info.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name = "diffsims"
version = "0.5.2"
version = "0.6.dev0"
author = "Duncan Johnstone, Phillip Crout"
copyright = "Copyright 2017-2023, The diffsims developers"
# Initial committer first, then listed by line additions
Expand Down
2 changes: 1 addition & 1 deletion diffsims/sims/diffraction_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def _get_transformed_coordinates(
y = coords_transformed[:, 1]
mirrored_factor = -1 if mirrored else 1
theta = mirrored_factor * np.arctan2(y, x) + np.deg2rad(angle)
rd = np.sqrt(x ** 2 + y ** 2)
rd = np.sqrt(x**2 + y**2)
coords_transformed[:, 0] = rd * np.cos(theta) + cx
coords_transformed[:, 1] = rd * np.sin(theta) + cy
return coords_transformed
Expand Down
5 changes: 2 additions & 3 deletions diffsims/tests/generators/test_diffraction_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ def probe(x, out=None, scale=None):
v = v * abs(x[1].reshape(1, -1, 1)) < 6
return v + 0 * x[2].reshape(1, 1, -1)


@pytest.mark.parametrize("model", [binary, linear, atanc, sin2c, lorentzian])
def test_shape_factor_precession(model):
excitation = np.array([-0.1, 0.1])
Expand All @@ -111,11 +112,10 @@ def test_shape_factor_precession(model):
def test_linear_shape_factor():
excitation = np.array([-2, -1, -0.5, 0, 0.5, 1, 2])
totest = linear(excitation, 1)
np.testing.assert_allclose(totest, np.array([0,0,0.5,1,0.5,0,0]))
np.testing.assert_allclose(totest, np.array([0, 0, 0.5, 1, 0.5, 0, 0]))
np.testing.assert_allclose(linear(0.5, 1), 0.5)



@pytest.mark.parametrize(
"model, expected",
[("linear", linear), ("lorentzian", lorentzian), (binary, binary)],
Expand Down Expand Up @@ -202,7 +202,6 @@ def test_shape_factor_strings(self, diffraction_calculator, local_structure):
_ = diffraction_calculator.calculate_ed_data(local_structure, 2)

def test_shape_factor_custom(self, diffraction_calculator, local_structure):

t1 = diffraction_calculator.calculate_ed_data(
local_structure, 2, max_excitation_error=0.02
)
Expand Down
2 changes: 1 addition & 1 deletion diffsims/tests/generators/test_rotation_list_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def test_get_beam_directions_grid(crystal_system, mesh):
("orthorhombic", 1657),
("monoclinic", 6441),
("triclinic", 12698),
]
],
)
def test_get_beam_directions_grid_size(crystal_system, desired_size):
grid = get_beam_directions_grid(crystal_system, 2)
Expand Down
4 changes: 2 additions & 2 deletions diffsims/tests/generators/test_zap_map_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def test_rotation_to_static_y_axis(self, sample_system):
assert np.allclose(r_to_y, (180, 90, -180))

def test_rotations_to_static_yz(self, sample_system):
""" We rotate from z towards y, and compare the results to geometry"""
"""We rotate from z towards y, and compare the results to geometry"""
r_to_yz = get_rotation_from_z_to_direction(sample_system, [0, 1, 1])
tan_angle = np.tan(np.deg2rad(r_to_yz[1]))
tan_lattice = sample_system.lattice.b / sample_system.lattice.c
Expand All @@ -70,7 +70,7 @@ def test_zap_map_all_systems(default_structure, default_simulator, system):

@pytest.mark.parametrize("density", ["3", "7"])
def test_zap_map_density_changes(default_structure, default_simulator, density):
""" Checks density arguments are passed correctly """
"""Checks density arguments are passed correctly"""
z_dict = generate_zap_map(default_structure, default_simulator, density=density)
if density == "3":
assert str(len(z_dict.keys())) == "3"
Expand Down
20 changes: 10 additions & 10 deletions diffsims/tests/patterns/test_detector_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ def test_constrain_to_dynamic_range(pattern):


class TestReturnsareCopies:
""" We want pattern to remain untouched by the noise addition """
"""We want pattern to remain untouched by the noise addition"""

def test_copy_shot_and_point_spread(self, pattern):
""" Also covers shot/point independantly """
"""Also covers shot/point independantly"""
z = add_shot_and_point_spread(pattern, 2, shot_noise=True)
assert not np.may_share_memory(pattern, z)

Expand Down Expand Up @@ -82,13 +82,13 @@ def test_add_shot_and_point_spread(self, pattern):

class TestShotNoise:
def test_seed_duplicates(self, pattern):
""" Same seed should imply same result """
"""Same seed should imply same result"""
z1 = add_shot_noise(pattern, seed=7)
z2 = add_shot_noise(pattern, seed=7)
assert np.allclose(z1, z2)

def test_seed_unduplicates(self, pattern):
""" Different seeds should (almost always) give different results"""
"""Different seeds should (almost always) give different results"""
z1 = add_shot_noise(pattern, seed=7)
z2 = add_shot_noise(pattern, seed=312)
z3 = add_shot_noise(pattern, seed=None)
Expand All @@ -98,15 +98,15 @@ def test_seed_unduplicates(self, pattern):

class TestGaussianNoise:
def test_seed_duplicates(self, pattern):
""" Same seed should imply same result """
"""Same seed should imply same result"""
z1 = add_gaussian_noise(pattern, sigma=3, seed=7)
z2 = add_gaussian_noise(pattern, sigma=3, seed=7)
assert np.allclose(z1, z2)


class TestDeadPixel:
def test_seed_duplicates(self, pattern):
""" Same seed should imply same result """
"""Same seed should imply same result"""
pattern = pattern + 1 # so that we can detect dead pixels
z1 = add_dead_pixels(pattern, n=6, seed=7)
z2 = add_dead_pixels(pattern, n=6, seed=7)
Expand All @@ -131,26 +131,26 @@ def test_bad_kwarg_choices_b(self, pattern):

class TestDetectorGainOffset:
def test_gain_scalar(self, pattern):
""" Tests scalar gains are invertible """
"""Tests scalar gains are invertible"""
g1 = add_linear_detector_gain(pattern, 1.1)
g2 = add_linear_detector_gain(g1, 1 / 1.1)
assert np.allclose(pattern, g2)

def test_gain_array(self, pattern):
""" Test array gain are invertible """
"""Test array gain are invertible"""
pattern = pattern + 1 # avoids problems inverting zeroes
g1 = add_linear_detector_gain(pattern, pattern)
g2 = add_linear_detector_gain(g1, np.divide(1, pattern))
assert np.allclose(pattern, g2)

def test_offset_scalar(self, pattern):
""" Test postive scalar offsets are invertible """
"""Test postive scalar offsets are invertible"""
g1 = add_detector_offset(pattern, 3)
g2 = add_detector_offset(g1, -3)
assert np.allclose(pattern, g2)

def test_offset_array(self, pattern):
""" Test postive array offsets are invertible """
"""Test postive array offsets are invertible"""
g1 = add_detector_offset(pattern, pattern)
g2 = add_detector_offset(g1, -pattern)
assert np.allclose(pattern, g2)
5 changes: 3 additions & 2 deletions diffsims/tests/sims/test_diffraction_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
import pytest

from diffsims.sims.diffraction_simulation import (
DiffractionSimulation, ProfileSimulation
DiffractionSimulation,
ProfileSimulation,
)


Expand Down Expand Up @@ -104,7 +105,7 @@ def test_failed_initialization(self):
with pytest.raises(ValueError, match="Coordinate"):
DiffractionSimulation(
np.array([[0, 0, 0], [1, 2, 3], [3, 4, 5]], dtype=float),
indices=np.array([1, 2, 3])
indices=np.array([1, 2, 3]),
)

def test_init(self, diffraction_simulation):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def test_grid2sphere(shape, rad):
x = [np.linspace(-1, 1, s) if s > 1 else np.array([0]) for s in shape]
X = to_mesh(x)
Y = to_mesh((x[0], x[1], np.array([0]))).reshape(-1, 3)
w = 1 / (1 + (Y ** 2).sum(-1) / rad ** 2)
w = 1 / (1 + (Y**2).sum(-1) / rad**2)
Y *= w[..., None]
Y[:, 2] = rad * (1 - w)
Y = Y.reshape(shape[0], shape[1], 3)
Expand Down
2 changes: 1 addition & 1 deletion diffsims/tests/utils/test_kinematic_simulation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def test_grid2sphere(shape, rad):
x = [np.linspace(-1, 1, s) if s > 1 else np.array([0]) for s in shape]
X = to_mesh(x)
Y = to_mesh((x[0], x[1], np.array([0]))).reshape(-1, 3)
w = 1 / (1 + (Y ** 2).sum(-1) / rad ** 2)
w = 1 / (1 + (Y**2).sum(-1) / rad**2)
Y *= w[..., None]
Y[:, 2] = rad * (1 - w)
Y = Y.reshape(shape[0], shape[1], 3)
Expand Down
10 changes: 5 additions & 5 deletions diffsims/tests/utils/test_mask_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,22 @@ def test_create_mask():

def test_invert_mask():
mask = mu.create_mask((20, 10))
initial = mask[0,0]
initial = mask[0, 0]
mu.invert_mask(mask)
assert initial != mask[0,0]
assert initial != mask[0, 0]


def test_add_polygon():
mask = mu.create_mask((20, 10))
coords = np.array([[5, 5],[15, 5],[10,10]])
coords = np.array([[5, 5], [15, 5], [10, 10]])
mu.add_polygon_to_mask(mask, coords)


def test_add_circles_to_mask():
mask = mu.create_mask((20, 10))
coords = np.array([[5, 5],[15, 5],[10,10]])
coords = np.array([[5, 5], [15, 5], [10, 10]])
mu.add_circles_to_mask(mask, coords, 3)


def test_add_circle_to_mask():
mask = mu.create_mask((20, 10))
Expand Down
2 changes: 1 addition & 1 deletion diffsims/tests/utils/test_sim_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def test_uvtw_to_uvw(uvtw, uvw):
class TestHolzCalibration:
def test_get_holz_angle(self):
wavelength = 2.51 / 1000
lattice_parameter = 0.3905 * 2 ** 0.5
lattice_parameter = 0.3905 * 2**0.5
angle = get_holz_angle(wavelength, lattice_parameter)
assert np.isclose(angle, 0.095378, rtol=1e-4)

Expand Down
2 changes: 1 addition & 1 deletion diffsims/utils/atomic_diffraction_generator_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def grid2sphere(arr, x, dx, C):
y = to_mesh((x[0], x[1], array([0])), dx).reshape(-1, 3)

if C is not None: # project on line to centre
w = 1 / (1 + (y ** 2).sum(-1) / C ** 2)
w = 1 / (1 + (y**2).sum(-1) / C**2)
y *= w[:, None]
if dx is None:
y[:, 2] = C * (1 - w)
Expand Down
8 changes: 3 additions & 5 deletions diffsims/utils/discretise_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,6 @@ def __FT3D_av_cpu(x0, x1, x2, loc, a, b, d, B, precomp, h, out): # pragma: no c

@cuda.jit
def __density3D_pw_gpu(x0, x1, x2, xmin, loc, sublist, r, a, d, B, precomp, h, out):

i0, i1, i2 = cuda.grid(3)
if i0 >= x0.size or i1 >= x1.size or i2 >= x2.size:
return
Expand Down Expand Up @@ -544,7 +543,6 @@ def __density3D_pw_gpu(x0, x1, x2, xmin, loc, sublist, r, a, d, B, precomp, h, o

@cuda.jit
def __density3D_av_gpu(x0, x1, x2, xmin, loc, sublist, r, a, d, B, precomp, h, out):

i0, i1, i2 = cuda.grid(3)
if i0 >= x0.size or i1 >= x1.size or i2 >= x2.size:
return
Expand Down Expand Up @@ -641,14 +639,14 @@ def _precomp_atom(a, b, d, pw, ZERO, dtype=FTYPE):
if pw:
n_zeros = sum(1 for D in d if D == 0)
f = lambda x: sum(
a[i] * c_exp(-b[i] * x ** 2) * (pi / b[i]) ** (n_zeros / 2)
a[i] * c_exp(-b[i] * x**2) * (pi / b[i]) ** (n_zeros / 2)
for i in range(a.size)
)
Rmax = 0.1
while f(Rmax) >= ZERO * f(0):
Rmax *= 1.1
h = max(Rmax / 500, max(d) / 10)
pms = array([Rmax ** 2, 1 / h], dtype=dtype)
pms = array([Rmax**2, 1 / h], dtype=dtype)
precomp = array([f(x) for x in arange(0, Rmax + 2 * h, h)], dtype=dtype)

else:
Expand All @@ -662,7 +660,7 @@ def f(i, j, x):
A
* (c_erf(B * (x + d[j] / 2)) - c_erf(B * (x - d[j] / 2)))
/ (2 * d[j] * B)
* pi ** 0.5
* pi**0.5
)

h = [D / 10 for D in d]
Expand Down
1 change: 0 additions & 1 deletion diffsims/utils/fourier_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,6 @@ def plan_ifft(
)
return plan, plan.input_array


except ImportError:
# Only scipy has a next_fast_len, usually numpy is a little faster
# (note they are not identical)
Expand Down
2 changes: 1 addition & 1 deletion diffsims/utils/kinematic_simulation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def grid2sphere(arr, x, dx, C):
y = to_mesh((x[0], x[1], array([0])), dx).reshape(-1, 3)

if C is not None: # project on line to centre
w = 1 / (1 + (y ** 2).sum(-1) / C ** 2)
w = 1 / (1 + (y**2).sum(-1) / C**2)
y *= w[:, None]
if dx is None:
y[:, 2] = C * (1 - w)
Expand Down
14 changes: 8 additions & 6 deletions diffsims/utils/mask_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def add_polygon_to_mask(mask, coords, fill=False):
the mask is adjusted inplace
"""
coords = np.array(coords)
coords = np.ravel(coords, order='C').tolist()
coords = np.ravel(coords, order="C").tolist()
tempmask = Image.fromarray(mask)
draw = ImageDraw.Draw(tempmask)
draw.polygon(coords, fill=fill)
Expand Down Expand Up @@ -82,7 +82,7 @@ def add_circles_to_mask(mask, coords, r, fill=False):
the mask is adjusted inplace
"""
coords = np.array(coords)
r = r*np.ones(coords.shape[0])
r = r * np.ones(coords.shape[0])
for i, j in zip(coords, r):
add_circle_to_mask(mask, i[0], i[1], j, fill=fill)

Expand Down Expand Up @@ -112,7 +112,7 @@ def add_circle_to_mask(mask, x, y, r, fill=False):
xx = np.arange(mask.shape[1])
yy = np.arange(mask.shape[0])
X, Y = np.meshgrid(xx, yy)
condition = ((X - x)**2 + (Y - y)**2 < r**2)
condition = (X - x) ** 2 + (Y - y) ** 2 < r**2
mask[condition] = fill


Expand Down Expand Up @@ -147,7 +147,9 @@ def add_annulus_to_mask(mask, r1, r2, x=None, y=None, fill=False):
xx = np.arange(mask.shape[1])
yy = np.arange(mask.shape[0])
X, Y = np.meshgrid(xx, yy)
condition = ((X - x)**2 + (Y - y)**2 > r1**2) & ((X - x)**2 + (Y - y)**2 < r2**2)
condition = ((X - x) ** 2 + (Y - y) ** 2 > r1**2) & (
(X - x) ** 2 + (Y - y) ** 2 < r2**2
)
mask[condition] = fill


Expand Down Expand Up @@ -181,10 +183,10 @@ def add_band_to_mask(mask, x, y, theta, width, fill=False):
theta_r = np.deg2rad(theta)
a = np.sin(theta_r)
b = -np.cos(theta_r)
c = -(a*x+b*y)
c = -(a * x + b * y)
denom = np.sqrt(a**2 + b**2)
xx = np.arange(mask.shape[1])
yy = np.arange(mask.shape[0])
X, Y = np.meshgrid(xx, yy)
condition = np.abs(a*X+b*Y+c)/denom < width/2
condition = np.abs(a * X + b * Y + c) / denom < width / 2
mask[condition] = fill
Loading

0 comments on commit df42e4e

Please sign in to comment.