Skip to content

Commit

Permalink
Autofix precommits
Browse files Browse the repository at this point in the history
  • Loading branch information
CyclingNinja committed Oct 23, 2024
1 parent 9dc0eb3 commit 4d8bfb6
Show file tree
Hide file tree
Showing 16 changed files with 134 additions and 144 deletions.
4 changes: 4 additions & 0 deletions .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ extend-ignore = [
"docs/*.py" = [
"INP001", # Implicit-namespace-package. The examples are not a package.
]
"examples/*.py" = [
"T201",
# We need print in our examples
]
"__init__.py" = ["E402", "F401", "F403"]
"test_*.py" = ["B011", "D", "E402", "PGH001", "S101"]

Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
]

# Add any paths that contain templates here, relative to this directory.
# templates_path = ["_templates"] # NOQA: ERA001
# templates_path = ["_templates"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
Expand Down Expand Up @@ -116,7 +116,7 @@
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ["_static"] # NOQA: ERA001
# html_static_path = ["_static"]

# By default, when rendering docstrings for classes, sphinx.ext.autodoc will
# make docs with the class-level docstring and the class-method docstrings,
Expand Down
2 changes: 1 addition & 1 deletion examples/creating_even_spaced_wavelength_visualisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
# `sequence=True` causes a sequence of maps to be returned, one for each image file.
sequence_of_maps = sunpy.map.Map(aia_files, sequence=True)
# Sort the maps in the sequence in order of wavelength.
sequence_of_maps.maps = list(sorted(sequence_of_maps.maps, key=lambda m: m.wavelength))
sequence_of_maps.maps = sorted(sequence_of_maps.maps, key=lambda m: m.wavelength)

#############################################################################
# Using an `astropy.units.Quantity` of the wavelengths of the images, we can construct
Expand Down
9 changes: 4 additions & 5 deletions ndcube/extra_coords/extra_coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,8 @@ def add(self, name, array_dimension, lookup_table, physical_types=None, **kwargs
self._lookup_tables.append((array_dimension, coord))

# Sort the LUTs so that the mapping and the wcs are ordered in pixel dim order
self._lookup_tables = list(sorted(self._lookup_tables,
key=lambda x: x[0] if isinstance(x[0], Integral) else x[0][0]))
self._lookup_tables = sorted(self._lookup_tables,
key=lambda x: x[0] if isinstance(x[0], Integral) else x[0][0])

@property
def _name_lut_map(self):
Expand Down Expand Up @@ -323,8 +323,7 @@ def is_empty(self):
# docstring in ABC
if not self._wcs and not self._lookup_tables:
return True
else:
return False
return False

def _getitem_string(self, item):
"""
Expand Down Expand Up @@ -402,7 +401,7 @@ def __getitem__(self, item):
if self._wcs:
return self._getitem_wcs(item)

elif self._lookup_tables:
if self._lookup_tables:
return self._getitem_lookup_tables(item)

# If we get here this object is empty, so just return an empty extra coords
Expand Down
53 changes: 24 additions & 29 deletions ndcube/extra_coords/table_coord.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,7 @@ def __str__(self):
content = str(self.table).lstrip('(').rstrip(',)')
if len(header) + len(content) >= np.get_printoptions()['linewidth']:
return '\n'.join((header, content))
else:
return ' '.join((header, content))
return ' '.join((header, content))

Check warning on line 228 in ndcube/extra_coords/table_coord.py

View check run for this annotation

Codecov / codecov/patch

ndcube/extra_coords/table_coord.py#L228

Added line #L228 was not covered by tests

def __repr__(self):
return f"{object.__repr__(self)}\n{self}"
Expand Down Expand Up @@ -539,16 +538,15 @@ def __getitem__(self, item):
mesh=False,
names=self.names,
physical_types=self.physical_types)
else:
self._slice = [self.combine_slices(a, b) for a, b in zip(sane_item, self._slice)]
if all([isinstance(s, Integral) for s in self._slice]):
# Here we rebuild the SkyCoord with the slice applied to the individual components.
new_sc = SkyCoord(self.table.realize_frame(type(self.table.data)(*self._sliced_components)))
return type(self)(new_sc,
mesh=False,
names=self.names,
physical_types=self.physical_types)
return self
self._slice = [self.combine_slices(a, b) for a, b in zip(sane_item, self._slice)]
if all([isinstance(s, Integral) for s in self._slice]):
# Here we rebuild the SkyCoord with the slice applied to the individual components.
new_sc = SkyCoord(self.table.realize_frame(type(self.table.data)(*self._sliced_components)))
return type(self)(new_sc,
mesh=False,
names=self.names,
physical_types=self.physical_types)
return self

@property
def frame(self):
Expand Down Expand Up @@ -590,8 +588,7 @@ def ndim(self):
"""
if self.mesh:
return len(self.table.data.components)
else:
return self.table.ndim
return self.table.ndim

@property
def shape(self):
Expand All @@ -605,8 +602,7 @@ def shape(self):
"""
if self.mesh:
return tuple(list(self.table.shape) * self.ndim)
else:
return self.table.shape
return self.table.shape

def interpolate(self, *new_array_grids, mesh_output=None, **kwargs):
"""
Expand Down Expand Up @@ -892,19 +888,18 @@ def frame(self):
"""
if len(self._table_coords) == 1:
return self._table_coords[0].frame
else:
frames = [t.frame for t in self._table_coords]

# We now have to set the axes_order of all the frames so that we
# have one consistent WCS with the correct number of pixel
# dimensions.
ind = 0
for f in frames:
new_ind = ind + f.naxes
f._axes_order = tuple(range(ind, new_ind))
ind = new_ind

return cf.CompositeFrame(frames)
frames = [t.frame for t in self._table_coords]

# We now have to set the axes_order of all the frames so that we
# have one consistent WCS with the correct number of pixel
# dimensions.
ind = 0
for f in frames:
new_ind = ind + f.naxes
f._axes_order = tuple(range(ind, new_ind))
ind = new_ind

return cf.CompositeFrame(frames)

@property
def dropped_world_dimensions(self):
Expand Down
4 changes: 2 additions & 2 deletions ndcube/global_coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def __len__(self):

def __str__(self):
classname = self.__class__.__name__
elements = [f"{name} {[ptype]}:\n{repr(coord)}" for (name, coord), ptype in
elements = [f"{name} {[ptype]}:\n{coord!r}" for (name, coord), ptype in

Check warning on line 235 in ndcube/global_coords.py

View check run for this annotation

Codecov / codecov/patch

ndcube/global_coords.py#L235

Added line #L235 was not covered by tests
zip(self.items(), self.physical_types.values())]
length = len(classname) + 2 * len(elements) + sum(len(e) for e in elements)
if length > np.get_printoptions()['linewidth']:
Expand All @@ -243,4 +243,4 @@ def __str__(self):
return f"{classname}({joiner.join(elements)})"

def __repr__(self):
return f"{object.__repr__(self)}\n{str(self)}"
return f"{object.__repr__(self)}\n{self!s}"

Check warning on line 246 in ndcube/global_coords.py

View check run for this annotation

Codecov / codecov/patch

ndcube/global_coords.py#L246

Added line #L246 was not covered by tests
67 changes: 33 additions & 34 deletions ndcube/ndcollection.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def __str__(self):
Aligned physical types: {self.aligned_axis_physical_types}"""))

def __repr__(self):
return f"{object.__repr__(self)}\n{str(self)}"
return f"{object.__repr__(self)}\n{self!s}"

Check warning on line 95 in ndcube/ndcollection.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcollection.py#L95

Added line #L95 was not covered by tests

@property
def aligned_dimensions(self):
Expand Down Expand Up @@ -137,40 +137,39 @@ def __getitem__(self, item):
return super().__getitem__(item)

# If item is not a single string...
# If item is a sequence, ensure strings and numeric items are not mixed.
item_is_strings = False
if isinstance(item, collections.abc.Sequence):
item_strings = [isinstance(item_, str) for item_ in item]
item_is_strings = all(item_strings)
# Ensure strings are not mixed with slices.
if (not item_is_strings) and (not all(np.invert(item_strings))):
raise TypeError("Cannot mix keys and non-keys when indexing instance.")

Check warning on line 147 in ndcube/ndcollection.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcollection.py#L147

Added line #L147 was not covered by tests

# If sequence is all strings, extract the cubes corresponding to the string keys.
if item_is_strings:
new_data = [self[_item] for _item in item]
new_keys = item
new_aligned_axes = tuple([self.aligned_axes[item_] for item_ in item])

# Else, the item is assumed to be a typical slicing item.
# Slice each cube in collection using information in this item.
# However, this can only be done if there are aligned axes.
else:
# If item is a sequence, ensure strings and numeric items are not mixed.
item_is_strings = False
if isinstance(item, collections.abc.Sequence):
item_strings = [isinstance(item_, str) for item_ in item]
item_is_strings = all(item_strings)
# Ensure strings are not mixed with slices.
if (not item_is_strings) and (not all(np.invert(item_strings))):
raise TypeError("Cannot mix keys and non-keys when indexing instance.")

# If sequence is all strings, extract the cubes corresponding to the string keys.
if item_is_strings:
new_data = [self[_item] for _item in item]
new_keys = item
new_aligned_axes = tuple([self.aligned_axes[item_] for item_ in item])

# Else, the item is assumed to be a typical slicing item.
# Slice each cube in collection using information in this item.
# However, this can only be done if there are aligned axes.
else:
if self.aligned_axes is None:
raise IndexError("Cannot slice unless collection has aligned axes.")
# Derive item to be applied to each cube in collection and
# whether any aligned axes are dropped by the slicing.
collection_items, new_aligned_axes = self._generate_collection_getitems(item)
# Apply those slice items to each cube in collection.
new_data = [self[key][tuple(cube_item)]
for key, cube_item in zip(self, collection_items)]
# Since item is not strings, no cube in collection is dropped.
# Therefore the collection keys remain unchanged.
new_keys = list(self.keys())

return self.__class__(list(zip(new_keys, new_data)), aligned_axes=new_aligned_axes,
meta=self.meta, sanitize_inputs=False)
if self.aligned_axes is None:
raise IndexError("Cannot slice unless collection has aligned axes.")

Check warning on line 160 in ndcube/ndcollection.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcollection.py#L160

Added line #L160 was not covered by tests
# Derive item to be applied to each cube in collection and
# whether any aligned axes are dropped by the slicing.
collection_items, new_aligned_axes = self._generate_collection_getitems(item)
# Apply those slice items to each cube in collection.
new_data = [self[key][tuple(cube_item)]
for key, cube_item in zip(self, collection_items)]
# Since item is not strings, no cube in collection is dropped.
# Therefore the collection keys remain unchanged.
new_keys = list(self.keys())

return self.__class__(list(zip(new_keys, new_data)), aligned_axes=new_aligned_axes,
meta=self.meta, sanitize_inputs=False)

def _generate_collection_getitems(self, item):
# There are 3 supported cases of the slice item: int, slice, tuple of ints and/or slices.
Expand Down
63 changes: 30 additions & 33 deletions ndcube/ndcube.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ def __set_name__(self, owner, name):

def __get__(self, obj, objtype=None):
if obj is None:
return
return None

Check warning on line 312 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L312

Added line #L312 was not covered by tests

if getattr(obj, self._attribute_name, None) is None and self._default_type is not None:
self.__set__(obj, self._default_type)
Expand Down Expand Up @@ -580,24 +580,23 @@ def _get_crop_item(self, *points, wcs=None, keepdims=False):
# Quit out early if we are no-op
if no_op:
return tuple([slice(None)] * wcs.pixel_n_dim)
else:
comp = [c[0] for c in wcs.world_axis_object_components]
# Trim to unique component names - `np.unique(..., return_index=True)
# keeps sorting alphabetically, set() seems just nondeterministic.
for k, c in enumerate(comp):
if comp.count(c) > 1:
comp.pop(k)
classes = [wcs.world_axis_object_classes[c][0] for c in comp]
for i, point in enumerate(points):
if len(point) != len(comp):
raise ValueError(f"{len(point)} components in point {i} do not match "
f"WCS with {len(comp)} components.")
for j, value in enumerate(point):
if not (value is None or isinstance(value, classes[j])):
raise TypeError(f"{type(value)} of component {j} in point {i} is "
f"incompatible with WCS component {comp[j]} "
f"{classes[j]}.")
return utils.cube.get_crop_item_from_points(points, wcs, False, keepdims=keepdims)
comp = [c[0] for c in wcs.world_axis_object_components]

Check warning on line 583 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L583

Added line #L583 was not covered by tests
# Trim to unique component names - `np.unique(..., return_index=True)
# keeps sorting alphabetically, set() seems just nondeterministic.
for k, c in enumerate(comp):
if comp.count(c) > 1:
comp.pop(k)
classes = [wcs.world_axis_object_classes[c][0] for c in comp]
for i, point in enumerate(points):
if len(point) != len(comp):
raise ValueError(f"{len(point)} components in point {i} do not match "
f"WCS with {len(comp)} components.")
for j, value in enumerate(point):
if not (value is None or isinstance(value, classes[j])):
raise TypeError(f"{type(value)} of component {j} in point {i} is "
f"incompatible with WCS component {comp[j]} "
f"{classes[j]}.")
return utils.cube.get_crop_item_from_points(points, wcs, False, keepdims=keepdims)

def crop_by_values(self, *points, units=None, wcs=None, keepdims=False):
# The docstring is defined in NDCubeABC
Expand Down Expand Up @@ -651,7 +650,7 @@ def __str__(self):
Data Type: {self.data.dtype}""")

def __repr__(self):
return f"{object.__repr__(self)}\n{str(self)}"
return f"{object.__repr__(self)}\n{self!s}"

def explode_along_axis(self, axis):
"""
Expand Down Expand Up @@ -866,14 +865,13 @@ class NDCube(NDCubeBase):
def _as_mpl_axes(self):
if hasattr(self.plotter, "_as_mpl_axes"):
return self.plotter._as_mpl_axes()
else:
warn_user(f"The current plotter {self.plotter} does not have a '_as_mpl_axes' method. "
"The default MatplotlibPlotter._as_mpl_axes method will be used instead.")
warn_user(f"The current plotter {self.plotter} does not have a '_as_mpl_axes' method. "
"The default MatplotlibPlotter._as_mpl_axes method will be used instead.")

Check warning on line 869 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L869

Added line #L869 was not covered by tests

from ndcube.visualization.mpl_plotter import MatplotlibPlotter
from ndcube.visualization.mpl_plotter import MatplotlibPlotter

plotter = MatplotlibPlotter(self)
return plotter._as_mpl_axes()
plotter = MatplotlibPlotter(self)
return plotter._as_mpl_axes()

Check warning on line 874 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L874

Added line #L874 was not covered by tests

def plot(self, *args, **kwargs):
"""
Expand Down Expand Up @@ -1268,11 +1266,10 @@ def _create_masked_array_for_rebinning(data, mask, operation_ignores_mask):
m = None if (mask is None or mask is False or operation_ignores_mask) else mask
if m is None:
return data, m
for array_type, masked_type in ARRAY_MASK_MAP.items():
if isinstance(data, array_type):
break
else:
for array_type, masked_type in ARRAY_MASK_MAP.items():
if isinstance(data, array_type):
break
else:
masked_type = np.ma.masked_array
warn_user("data and mask arrays of different or unrecognized types. Casting them into a numpy masked array.")
return masked_type(data, m), m
masked_type = np.ma.masked_array
warn_user("data and mask arrays of different or unrecognized types. Casting them into a numpy masked array.")
return masked_type(data, m), m

Check warning on line 1275 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L1274-L1275

Added lines #L1274 - L1275 were not covered by tests
Loading

0 comments on commit 4d8bfb6

Please sign in to comment.