Skip to content

Commit 2140f7c

Browse files
author
Sourcery AI
committed
'Refactored by Sourcery'
1 parent c83f562 commit 2140f7c

33 files changed

+280
-522
lines changed

src/obstools/airmass.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,14 @@ def refractive_index(h_gp):
4141
delta = 2.93e-4
4242
rho = atmosphere(h_gp)
4343

44-
n = 1. + delta * (rho / RHO0)
45-
return n
44+
return 1. + delta * (rho / RHO0)
4645

4746

4847
class Atmopshere(object):
4948
pass
5049

5150

52-
def atmosphere(H_gp): # class StandardAtmosphere
51+
def atmosphere(H_gp): # class StandardAtmosphere
5352
"""
5453
US Standard Atmosphere, 1976
5554
As published by NOAA, NASA, and USAF
@@ -69,13 +68,16 @@ def atmosphere(H_gp): # class StandardAtmosphere
6968
if isinstance(H_gp, (float, int)):
7069
H_gp = np.array([H_gp])
7170

72-
regions = [(0. <= H_gp) & (H_gp <= 11e3),
73-
(11e3 < H_gp) & (H_gp <= 20e3),
74-
(20e3 < H_gp) & (H_gp <= 32e3),
75-
(32e3 < H_gp) & (H_gp <= 47e3),
76-
(47e3 < H_gp) & (H_gp <= 51e3),
77-
(51e3 < H_gp) & (H_gp <= 71e3),
78-
(71e3 < H_gp) & (H_gp <= 84852.)]
71+
regions = [
72+
(H_gp >= 0.0) & (H_gp <= 11e3),
73+
(H_gp > 11e3) & (H_gp <= 20e3),
74+
(H_gp > 20e3) & (H_gp <= 32e3),
75+
(H_gp > 32e3) & (H_gp <= 47e3),
76+
(H_gp > 47e3) & (H_gp <= 51e3),
77+
(H_gp > 51e3) & (H_gp <= 71e3),
78+
(H_gp > 71e3) & (H_gp <= 84852.0),
79+
]
80+
7981

8082
expressions = [lambda x: RHO0 * (1. - x / 44330.94) ** 4.25587615,
8183
lambda x: RHO0 * 0.29707755 * np.exp((11e3 - x) / 6341.62),
@@ -362,8 +364,7 @@ def delM(z, h):
362364

363365
cos_delphi = (4 * (rhm * np.cos(im)) ** 2 - (delh * np.sin(im)) ** 2) / (
364366
4 * (rhm * np.cos(im)) ** 2 + (delh * np.sin(im)) ** 2)
365-
dM = rho * np.sqrt(rh * rh + rhp * rhp - 2 * rh * rhp * cos_delphi)
366-
return dM
367+
return rho * np.sqrt(rh * rh + rhp * rhp - 2 * rh * rhp * cos_delphi)
367368

368369
H = np.arange(0., Hmax, delh)
369370
X = np.empty(Z.shape)

src/obstools/aps/ApertureCollections.py

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ def __init__(self, widths=None, heights=None, angles=None, **kws):
356356

357357
def __str__(self):
358358
# FIXME: better repr with widths, heights, angles
359-
return '%s of shape %s' % (self.__class__.__name__, self.shape)
359+
return f'{self.__class__.__name__} of shape {self.shape}'
360360

361361
# def __repr__(self):
362362
# return str(self)
@@ -518,26 +518,19 @@ def append(self, aps=None, **props):
518518
print('#' * 300)
519519
return
520520

521-
if not self.size:
522-
concatenate = lambda o, a: a
523-
# if the Collection was initialized as empty, set the new properties as current
524-
else:
525-
concatenate = props.concatenate
526-
521+
concatenate = props.concatenate if self.size else (lambda o, a: a)
527522
# embed()
528523
oprops = self._properties._original
529524
# Find which properties differ and update those
530525
for key, val in props.items():
531-
if (not key in oprops) \
532-
or (not np.array_equal(oprops[key], props[
533-
key])): # `np.array_equal` here flags the empty properties as being unequal to the new ones, whereas `np.all` evaluates as True under the same conditions
526+
if key not in oprops or not np.array_equal(oprops[key], props[key]): # `np.array_equal` here flags the empty properties as being unequal to the new ones, whereas `np.all` evaluates as True under the same conditions
534527
new = concatenate(self[key], val)
535528

536529
# print( '8'*88 )
537530
# print('APPEND', key, self[key], val )
538531
# print( 'NEW:', new )
539532

540-
setter = getattr(self, 'set_%s' % key)
533+
setter = getattr(self, f'set_{key}')
541534
setter(new)
542535

543536
# print( )
@@ -581,8 +574,7 @@ def area(self, idx=...):
581574
def area_between(self, idxs):
582575
"""return the area enclosed between the two apertures given by idxs"""
583576
A = np.array(self.area(idxs), ndmin=2)
584-
area = np.abs(np.subtract(*A.T))
585-
return area
577+
return np.abs(np.subtract(*A.T))
586578

587579
def center_proximity(self, position, idx=...):
588580
"""
@@ -645,7 +637,7 @@ def edge_proximity(self, position, idx=...):
645637
# ==============================================================================================
646638
# TODO: maybe maxe this a propetry??
647639
def add_to_axes(self, ax=None):
648-
if not self in ax.collections:
640+
if self not in ax.collections:
649641
# print( 'Adding collection to axis' )
650642

651643
# necessary for apertures to map correctly to data positions
@@ -888,10 +880,7 @@ def __init__(self, apertures, ax, **kws):
888880
# @expose.args( pre='='*100, post='?'*100 )
889881
def make_segments(self, radii):
890882

891-
if radii.size:
892-
return [list(zip((r, r), (0, 1))) for r in radii]
893-
else:
894-
return []
883+
return [list(zip((r, r), (0, 1))) for r in radii] if radii.size else []
895884

896885
def update_from(self, aps):
897886

@@ -1113,12 +1102,7 @@ def append(self, aps=None, **props):
11131102
# can all be changed at a specific index.
11141103

11151104
# FIXME: SMELLY CODE!!!!!!!!!!!!
1116-
if not self.size:
1117-
concatenate = lambda o, a: a
1118-
# HACK! if the Collection was initialized as empty, set the new properties as current
1119-
else:
1120-
concatenate = PropertyManager.concatenate
1121-
1105+
concatenate = PropertyManager.concatenate if self.size else (lambda o, a: a)
11221106
# for key in self._properties.__broadcast__:
11231107
for key, val in props.items():
11241108

@@ -1134,7 +1118,7 @@ def append(self, aps=None, **props):
11341118
print(e)
11351119
embed()
11361120

1137-
setter = getattr(self, 'set_%s' % key)
1121+
setter = getattr(self, f'set_{key}')
11381122

11391123
print()
11401124
# try:
@@ -1148,7 +1132,7 @@ def within_allowed_range(self, r):
11481132
def resize(self, relative_motion, idx=..., ):
11491133
print('RESIZING!', relative_motion, self.radii, idx)
11501134

1151-
if not relative_motion is None:
1135+
if relative_motion is not None:
11521136
rnew = self.radii
11531137
rnew[idx] += relative_motion
11541138
if not self.within_allowed_range(rnew):

src/obstools/ephemeris.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -153,12 +153,11 @@ def rephase(phase, offset, *data):
153153
phase %= 1
154154
if data is None:
155155
return phase
156-
else:
157-
data = np.array(cosort(phase, *data))
156+
data = np.array(cosort(phase, *data))
158157

159-
phase = data[0]
160-
data = data[1:]
161-
return phase, data
158+
phase = data[0]
159+
data = data[1:]
160+
return phase, data
162161

163162

164163
def phase_splitter(ph, *data, **kws):

src/obstools/image/calibration.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ def __init__(self, name):
1515
self.name = f'_{name}'
1616

1717
def __get__(self, instance, owner):
18-
if instance is None:
19-
return self
20-
return getattr(instance, self.name)
18+
return self if instance is None else getattr(instance, self.name)
2119

2220
def __set__(self, instance, value):
2321
if value is keep:

src/obstools/image/mosaic.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def plot_transformed_image(ax, image, fov=None, p=(0, 0, 0), frame=True,
8787

8888
frame_kws = dict(fc='none', lw=0.5, ec='0.5', alpha=kws.get('alpha'))
8989
if isinstance(frame, dict):
90-
frame_kws.update(frame)
90+
frame_kws |= frame
9191

9292
ax.add_patch(
9393
Rectangle(xy - half_pixel_size, *fov[::-1], np.degrees(theta),
@@ -256,7 +256,7 @@ def plot_image(self, image=None, fov=None, p=(0, 0, 0), name=None,
256256

257257
#
258258
# if not isinstance(image, SkyImage):
259-
if not image.__class__.__name__ == 'SkyImage':
259+
if image.__class__.__name__ != 'SkyImage':
260260
image = SkyImage(image, fov)
261261

262262
#
@@ -373,7 +373,7 @@ def mark_target(self, xy, name, colour='forestgreen', arrow_size=10,
373373
def label_image(self, name='', p=(0, 0, 0), fov=(0, 0), **kws):
374374
# default args for init
375375
_kws = {}
376-
_kws.update(self.label_props)
376+
_kws |= self.label_props
377377
_kws.update(kws)
378378
return self.ax.text(*ulc(p, fov), name,
379379
rotation=np.degrees(p[-1]),

src/obstools/image/registration.py

Lines changed: 16 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -298,10 +298,7 @@ def _checks(self, p, xy=None, *args, **kws):
298298
return self._check_params(p), self._check_grid(xy)
299299

300300
def _check_params(self, p):
301-
if (p is None) or (p == ()):
302-
# default parameter values for evaluation
303-
return np.zeros(self.dof)
304-
return p
301+
return np.zeros(self.dof) if (p is None) or (p == ()) else p
305302

306303
def _check_grid(self, grid):
307304
#
@@ -373,9 +370,8 @@ def plot(self, grid=100, show_xy=True, show_peak=True, **kws):
373370
grid = duplicate_if_scalar(grid, self.n_dims, raises=False)
374371
if grid.size == self.n_dims:
375372
grid = self._auto_grid(grid)
376-
else:
377-
if (grid.ndim != 3) or (grid.shape[-1] != self.n_dims):
378-
raise ValueError('Invalid grid')
373+
elif (grid.ndim != 3) or (grid.shape[-1] != self.n_dims):
374+
raise ValueError('Invalid grid')
379375

380376
# compute model values
381377
z = self((), grid)
@@ -691,15 +687,13 @@ def display_multitab(images, fovs, params, coords):
691687
import more_itertools as mit
692688

693689
ui = MplMultiTab()
694-
for i, (image, fov, p, yx) in enumerate(zip(images, fovs, params, coords)):
690+
for image, fov, p, yx in zip(images, fovs, params, coords):
695691
xy = yx[:, ::-1] # roto_translate_yx(yx, np.r_[-p[:2], 0])[:, ::-1]
696692
ex = mit.interleave((0, 0), fov)
697693
im = ImageDisplay(image, extent=list(ex))
698694
im.ax.plot(*xy.T, 'kx', ms=5)
699695
ui.add_tab(im.figure)
700696
plt.close(im.figure)
701-
# if i == 1:
702-
# break
703697
return ui
704698

705699

@@ -1102,20 +1096,18 @@ def _measure_positions_offsets(xy, centres, d_cut=None):
11021096
out_new = (d > d_cut)
11031097
out_new = np.ma.getdata(out_new) | np.ma.getmask(out_new)
11041098

1105-
changed = (outliers != out_new).any()
1106-
if changed:
1107-
out = out_new
1108-
xym[out] = np.ma.masked
1109-
n_out = out.sum()
1099+
if not (changed := (outliers != out_new).any()):
1100+
break
11101101

1111-
if n_out / n_points > 0.5:
1112-
raise Exception('Too many outliers!!')
1102+
out = out_new
1103+
xym[out] = np.ma.masked
1104+
n_out = out.sum()
11131105

1114-
logger.info('Ignoring %i/%i (%.1f%%) values with |δr| > %.3f',
1115-
n_out, n_points, (n_out / n_points) * 100, d_cut)
1116-
else:
1117-
break
1106+
if n_out / n_points > 0.5:
1107+
raise Exception('Too many outliers!!')
11181108

1109+
logger.info('Ignoring %i/%i (%.1f%%) values with |δr| > %.3f',
1110+
n_out, n_points, (n_out / n_points) * 100, d_cut)
11191111
return centres, xy_shifted.std(0), xy_offsets.squeeze(), outliers
11201112

11211113

@@ -1385,7 +1377,7 @@ def plot(self, ax=None, p=(0, 0, 0), scale='fov', frame=True, **kws):
13851377
frame_kws = dict(fc='none', lw=1, ec='0.5',
13861378
alpha=kws.get('alpha'))
13871379
if isinstance(frame, dict):
1388-
frame_kws.update(frame)
1380+
frame_kws |= frame
13891381

13901382
*xy, theta = p
13911383
frame = Rectangle(np.subtract(xy, half_pixel_size), *urc,
@@ -1652,11 +1644,7 @@ def from_images(cls, images, fovs, angles=(), ridx=None, plot=False,
16521644
# message
16531645
cls.logger.info('Aligning %i images on image %i', n, ridx)
16541646

1655-
if len(angles):
1656-
angles = np.array(angles) - angles[ridx] # relative angles
1657-
else:
1658-
angles = np.zeros(n)
1659-
1647+
angles = np.array(angles) - angles[ridx] if len(angles) else np.zeros(n)
16601648
reg = cls(**find_kws)
16611649
for i in indices:
16621650
reg(images[i], fovs[i], angles[i], plot=plot)
@@ -2566,8 +2554,7 @@ def mosaic(self, names=(), **kws):
25662554
def get_rotation(self):
25672555
# transform pixel to ICRS coordinate
25682556
h = self.hdu[0].header
2569-
theta = np.pi / 2 - np.arctan(-h['CD1_1'] / h['CD1_2'])
2570-
return theta
2557+
return np.pi / 2 - np.arctan(-h['CD1_1'] / h['CD1_2'])
25712558

25722559
# todo: def proper_motion_correction(self, coords):
25732560

0 commit comments

Comments
 (0)