Skip to content

Commit

Permalink
Update outdate numpy
Browse files Browse the repository at this point in the history
Update np.random.rand to np.random.Generate
per NPY002
  • Loading branch information
CyclingNinja committed Oct 24, 2024
1 parent 93a34cf commit 4965cba
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 41 deletions.
4 changes: 3 additions & 1 deletion .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ select = [
"PD",
"PLC",
"PLE",
"TRY",
"FLY",
"NPY",
"PERF",
Expand All @@ -40,9 +39,12 @@ extend-ignore = [
"PIE808", # Disallow passing 0 as the first argument to range
# upgrades
"UP038", # Use | in isinstance - not compatible with models and is slower
# numpy
"NPY002", # TODO: migrate from np.random.rand to np.random.Generator
# pytest (PT)
"PT001", # Always use pytest.fixture()
"PT004", # Fixtures which don't return anything should have leading _
"PT011", # except(ValueRaises) is too broad
"PT023", # Always use () on pytest decorators
# flake8-use-pathlib
"PTH123", # open() should be replaced by Path.open()
Expand Down
4 changes: 2 additions & 2 deletions ndcube/_dev/scm_version.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Try to use setuptools_scm to get the current version; this is only used
# in development installations from the git repository.
import os.path
import Path

try:
from setuptools_scm import get_version

version = get_version(root=os.path.join('..', '..'), relative_to=__file__)
version = get_version(root=Path('../..'), relative_to=__file__)
except ImportError:
raise
except Exception as e:
Expand Down
6 changes: 2 additions & 4 deletions ndcube/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,7 @@ def ndcube_2d_ln_lt_uncert(wcs_2d_lt_ln):
shape = (10, 12)
data_cube = data_nd(shape)
uncertainty = astropy.nddata.StdDevUncertainty(data_cube * 0.1)
cube = NDCube(data_cube, wcs=wcs_2d_lt_ln, uncertainty=uncertainty)
return cube
return NDCube(data_cube, wcs=wcs_2d_lt_ln, uncertainty=uncertainty)


@pytest.fixture
Expand All @@ -493,8 +492,7 @@ def ndcube_2d_ln_lt_mask_uncert(wcs_2d_lt_ln):
mask[2, 0] = True
mask[3, 3] = True
mask[4:6, :4] = True
cube = NDCube(data_cube, wcs=wcs_2d_lt_ln, uncertainty=uncertainty, mask=mask)
return cube
return NDCube(data_cube, wcs=wcs_2d_lt_ln, uncertainty=uncertainty, mask=mask)


@pytest.fixture
Expand Down
12 changes: 6 additions & 6 deletions ndcube/extra_coords/extra_coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ def __init__(self, ndcube=None):

# Lookup tables is a list of (pixel_dim, LookupTableCoord) to allow for
# one pixel dimension having more than one lookup coord.
self._lookup_tables = list()
self._dropped_tables = list()
self._lookup_tables = []
self._dropped_tables = []

# We need a reference to the parent NDCube
self._ndcube = ndcube
Expand Down Expand Up @@ -243,7 +243,7 @@ def _name_lut_map(self):
def keys(self):
# docstring in ABC
if not self.wcs:
return tuple()
return ()

return tuple(self.wcs.world_axis_names) if self.wcs.world_axis_names else None

Expand All @@ -256,7 +256,7 @@ def mapping(self):
# If mapping is not set but lookup_tables is empty then the extra
# coords is empty, so there is no mapping.
if not self._lookup_tables:
return tuple()
return ()

# The mapping is from the array index (position in the list) to the
# pixel dimensions (numbers in the list)
Expand Down Expand Up @@ -292,7 +292,7 @@ def wcs(self):
if not self._lookup_tables:
return None

tcoords = set(lt[1] for lt in self._lookup_tables)
tcoords = {lt[1] for lt in self._lookup_tables}
# created a sorted list of unique items
_tmp = set() # a temporary set
tcoords = [x[1] for x in self._lookup_tables if x[1] not in _tmp and _tmp.add(x[1]) is None]
Expand Down Expand Up @@ -424,7 +424,7 @@ def dropped_world_dimensions(self):

return mtc.dropped_world_dimensions

return dict()
return {}

def resample(self, factor, offset=0, ndcube=None, **kwargs):
"""
Expand Down
62 changes: 37 additions & 25 deletions ndcube/extra_coords/table_coord.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@
except ImportError:
pass

__all__ = ['TimeTableCoordinate', 'SkyCoordTableCoordinate', 'QuantityTableCoordinate', "BaseTableCoordinate", "MultipleTableCoordinate"]
__all__ = ['TimeTableCoordinate',
'SkyCoordTableCoordinate',
'QuantityTableCoordinate',
'BaseTableCoordinate',
'MultipleTableCoordinate']


class Length1Tabular(_Tabular):
Expand Down Expand Up @@ -115,10 +119,10 @@ def _generate_generic_frame(naxes, unit, names=None, physical_types=None):
if isinstance(unit, (u.Unit, u.IrreducibleUnit, u.CompositeUnit)):
unit = tuple([unit] * naxes)

if all([u.m.is_equivalent(un) for un in unit]):
if all(u.m.is_equivalent(un) for un in unit):
axes_type = "SPATIAL"

if all([u.pix.is_equivalent(un) for un in unit]):
if all(u.pix.is_equivalent(un) for un in unit):
name = "PixelFrame"
axes_type = "PIXEL"

Expand All @@ -136,7 +140,7 @@ def _generate_tabular(lookup_table, interpolation='linear', points_unit=u.pix, *
raise TypeError("lookup_table must be a Quantity.") # pragma: no cover

ndim = lookup_table.ndim
TabularND = tabular_model(ndim, name=f"Tabular{ndim}D")
tabular_nd = tabular_model(ndim, name=f"Tabular{ndim}D")

# The integer location is at the centre of the pixel.
points = [(np.arange(size) - 0) * points_unit for size in lookup_table.shape]
Expand All @@ -151,7 +155,7 @@ def _generate_tabular(lookup_table, interpolation='linear', points_unit=u.pix, *
if len(lookup_table) == 1:
t = Length1Tabular(points, lookup_table, **kwargs)
else:
t = TabularND(points, lookup_table, **kwargs)
t = tabular_nd(points, lookup_table, **kwargs)

# TODO: Remove this when there is a new gWCS release
# Work around https://github.com/spacetelescope/gwcs/pull/331
Expand Down Expand Up @@ -202,7 +206,7 @@ def __init__(self, *tables, mesh=False, names=None, physical_types=None):
self.names = names if not isinstance(names, str) else [names]
self.physical_types = physical_types if not isinstance(physical_types, str) else [physical_types]
self._dropped_world_dimensions = defaultdict(list)
self._dropped_world_dimensions["world_axis_object_classes"] = dict()
self._dropped_world_dimensions["world_axis_object_classes"] = {}

@abc.abstractmethod
def __getitem__(self, item):
Expand All @@ -224,8 +228,8 @@ def __str__(self):
header = f"{self.__class__.__name__} {self.names or ''} {self.physical_types or '[None]'}:"
content = str(self.table).lstrip('(').rstrip(',)')
if len(header) + len(content) >= np.get_printoptions()['linewidth']:
return '\n'.join((header, content))
return ' '.join((header, content))
return f'\n {header} \n {content}'
return f' {header}{content} '

def __repr__(self):
return f"{object.__repr__(self)}\n{self}"
Expand Down Expand Up @@ -301,9 +305,9 @@ class QuantityTableCoordinate(BaseTableCoordinate):
"""

def __init__(self, *tables, names=None, physical_types=None):
if not all([isinstance(t, u.Quantity) for t in tables]):
if not all(isinstance(t, u.Quantity) for t in tables):
raise TypeError("All tables must be astropy Quantity objects")
if not all([t.unit.is_equivalent(tables[0].unit) for t in tables]):
if not all(t.unit.is_equivalent(tables[0].unit) for t in tables):
raise u.UnitsError("All tables must have equivalent units.")
ndim = len(tables)
dims = np.array([t.ndim for t in tables])
Expand Down Expand Up @@ -348,7 +352,9 @@ def _slice_table(self, i, table, item, new_components, whole_slice):
dwd["world_axis_physical_types"].append(self.frame.axis_physical_types[i])
dwd["world_axis_units"].append(table.unit.to_string())
dwd["world_axis_object_components"].append((f"quantity{i}", 0, "value"))
dwd["world_axis_object_classes"].update({f"quantity{i}": (u.Quantity, tuple(), {"unit", table.unit.to_string()})})
dwd["world_axis_object_classes"].update({f"quantity{i}": (u.Quantity,
(),
{"unit", table.unit.to_string()})})
return

new_components["tables"].append(table[item])
Expand Down Expand Up @@ -381,7 +387,7 @@ def n_inputs(self):
return len(self.table)

def is_scalar(self):
return all(t.shape == tuple() for t in self.table)
return all(t.shape == () for t in self.table)

@property
def frame(self):
Expand Down Expand Up @@ -515,7 +521,7 @@ def n_inputs(self):
return len(self.table.data.components)

def is_scalar(self):
return self.table.shape == tuple()
return self.table.shape == ()

@staticmethod
def combine_slices(slice1, slice2):
Expand All @@ -539,7 +545,7 @@ def __getitem__(self, item):
names=self.names,
physical_types=self.physical_types)
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]):
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,
Expand All @@ -556,7 +562,7 @@ def frame(self):
sc = self.table
components = tuple(getattr(sc.data, comp) for comp in sc.data.components)
ref_frame = sc.frame.replicate_without_data()
units = list(c.unit for c in components)
units = [c.unit for c in components]

# TODO: Currently this limits you to 2D due to gwcs#120
return cf.CelestialFrame(reference_frame=ref_frame,
Expand Down Expand Up @@ -729,7 +735,7 @@ def n_inputs(self):
return 1 # The time table has to be one dimensional

def is_scalar(self):
return self.table.shape == tuple()
return self.table.shape == ()

@property
def frame(self):
Expand Down Expand Up @@ -807,10 +813,11 @@ class MultipleTableCoordinate(BaseTableCoordinate):
def __init__(self, *table_coordinates):
if not all(isinstance(lt, BaseTableCoordinate) and
not (isinstance(lt, MultipleTableCoordinate)) for lt in table_coordinates):
raise TypeError("All arguments must be BaseTableCoordinate instances, such as QuantityTableCoordinate, "
raise TypeError("All arguments must be BaseTableCoordinate instances, "
"such as QuantityTableCoordinate, "
"and not instances of MultipleTableCoordinate.")
self._table_coords = list(table_coordinates)
self._dropped_coords = list()
self._dropped_coords = []

def __str__(self):
classname = self.__class__.__name__
Expand Down Expand Up @@ -838,7 +845,7 @@ def __rand__(self, other):
if not isinstance(other, BaseTableCoordinate) or isinstance(other, MultipleTableCoordinate):
return NotImplemented

return type(self)(*([other] + self._table_coords))
return type(self)([other, *self._table_coords])

def __getitem__(self, item):
if isinstance(item, (slice, Integral)):
Expand Down Expand Up @@ -904,7 +911,7 @@ def frame(self):
@property
def dropped_world_dimensions(self):
dropped_world_dimensions = defaultdict(list)
dropped_world_dimensions["world_axis_object_classes"] = dict()
dropped_world_dimensions["world_axis_object_classes"] = {}

# Combine the dicts on the tables with our dict
for lutc in self._table_coords:
Expand All @@ -916,11 +923,16 @@ def dropped_world_dimensions(self):

dropped_multi_table = MultipleTableCoordinate(*self._dropped_coords)

dropped_world_dimensions["world_axis_names"] += [name or None for name in dropped_multi_table.frame.axes_names]
dropped_world_dimensions["world_axis_physical_types"] += list(dropped_multi_table.frame.axis_physical_types)
dropped_world_dimensions["world_axis_units"] += [u.to_string() for u in dropped_multi_table.frame.unit]
dropped_world_dimensions["world_axis_object_components"] += dropped_multi_table.frame._world_axis_object_components
dropped_world_dimensions["world_axis_object_classes"].update(dropped_multi_table.frame._world_axis_object_classes)
dropped_world_dimensions["world_axis_names"] += [name or None for name in
dropped_multi_table.frame.axes_names]
dropped_world_dimensions["world_axis_physical_types"] += (
list(dropped_multi_table.frame.axis_physical_types))
dropped_world_dimensions["world_axis_units"] += [u.to_string() for u in
dropped_multi_table.frame.unit]
dropped_world_dimensions["world_axis_object_components"] += \
dropped_multi_table.frame._world_axis_object_components
dropped_world_dimensions["world_axis_object_classes"].update(
dropped_multi_table.frame._world_axis_object_classes)

for dropped in self._dropped_coords:
# If the table is a tuple (QuantityTableCoordinate) then we need to
Expand Down
6 changes: 3 additions & 3 deletions ndcube/extra_coords/tests/test_extra_coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def test_empty_ec(wcs_1d_l):
# Test slice of an empty EC
assert ec[0].wcs is None

assert ec.mapping == tuple()
assert ec.mapping == ()
assert ec.wcs is None
assert ec.keys() == tuple()
assert ec.keys() == ()

ec.wcs = wcs_1d_l
assert ec.wcs is wcs_1d_l
Expand Down Expand Up @@ -299,7 +299,7 @@ def test_extra_coords_2d_quantity(quantity_2d_lut):

# Extra Coords with NDCube
def test_add_coord_after_create(time_lut):
ndc = NDCube(np.random.random((10, 10)), wcs=WCS(naxis=2))
ndc = NDCube(np.random.rand((10, 10)), wcs=WCS(naxis=2))
assert isinstance(ndc.extra_coords, ExtraCoords)
ndc.extra_coords.add("time", 0, time_lut)

Expand Down

0 comments on commit 4965cba

Please sign in to comment.