Skip to content

Commit

Permalink
Merge pull request #150 from mcflugen/mcflugen/absolute-import-utils
Browse files Browse the repository at this point in the history
Absolute import of the deltametrics.utils module
  • Loading branch information
mcflugen authored Dec 4, 2024
2 parents 929eddb + e474e18 commit f8cc545
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 97 deletions.
18 changes: 9 additions & 9 deletions deltametrics/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import abc
import warnings

from . import utils
from deltametrics.utils import is_ndarray_or_xarray
from . import cube
from . import plan
from . import plot
Expand Down Expand Up @@ -62,11 +62,11 @@ def __init__(self, mask_type, *args, **kwargs):
elif (len(args) >= 1) and issubclass(type(args[0]), BaseMask):
self._input_flag = "mask"
self._set_shape_mask(args[0].mask)
elif utils.is_ndarray_or_xarray(args[0]):
elif is_ndarray_or_xarray(args[0]):
# check that all arguments are xarray or numpy arrays
self._input_flag = "array"
for i in range(len(args)):
if not utils.is_ndarray_or_xarray(args[i]):
if not is_ndarray_or_xarray(args[i]):
raise TypeError(
"First input to mask instantiation was an array "
"but then a later argument was not an array. "
Expand Down Expand Up @@ -736,7 +736,7 @@ def _compute_mask(self, *args, **kwargs):
if isinstance(args[0], LandMask):
lm_array = args[0]._mask.values
fm_array = args[1]._mask.values
elif utils.is_ndarray_or_xarray(args[0]):
elif is_ndarray_or_xarray(args[0]):
lm_array = args[0].values
fm_array = args[1].values
else:
Expand Down Expand Up @@ -958,7 +958,7 @@ def _compute_mask(self, *args, **kwargs):
if isinstance(args[0], LandMask):
lm_array = args[0]._mask
below_array = 1 - args[1]._mask # go from elevation mask
elif utils.is_ndarray_or_xarray(args[0]):
elif is_ndarray_or_xarray(args[0]):
lm_array = args[0]
below_array = args[1]
else:
Expand Down Expand Up @@ -1198,7 +1198,7 @@ def _compute_mask(self, *args, **kwargs):
if len(args) == 1:
if isinstance(args[0], plan.BasePlanform):
composite_array = args[0].composite_array
elif utils.is_ndarray_or_xarray(args[0]):
elif is_ndarray_or_xarray(args[0]):
composite_array = args[0]
else:
raise TypeError
Expand Down Expand Up @@ -1509,7 +1509,7 @@ def _compute_MPM_mask(self, *args, **kwargs):
elif len(args) == 2:
if isinstance(args[0], plan.MorphologicalPlanform):
_mean_image = args[0]._mean_image
elif utils.is_ndarray_or_xarray(args[1]):
elif is_ndarray_or_xarray(args[1]):
_mean_image = args[1]
else:
raise ValueError
Expand Down Expand Up @@ -1798,7 +1798,7 @@ def _compute_mask(self, *args, **kwargs):
if isinstance(args[0], LandMask):
lm_array = args[0]._mask.astype(float)
wm_array = args[1]._mask.astype(float)
elif utils.is_ndarray_or_xarray(args[0]):
elif is_ndarray_or_xarray(args[0]):
lm_array = args[0].astype(float)
wm_array = args[1].astype(float)
else:
Expand Down Expand Up @@ -2648,7 +2648,7 @@ def __init__(self, *args, background_value=0, elevation_tolerance=0.1, **kwargs)
raise ValueError("Invalid _input_flag. Did you modify this attribute?")

# process background_value into an array
if utils.is_ndarray_or_xarray(background_value):
if is_ndarray_or_xarray(background_value):
background_array = np.array(background_value) # strip xarray
else:
background_array = np.ones(self._shape) * background_value
Expand Down
17 changes: 9 additions & 8 deletions deltametrics/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
from . import cube
from . import section as dm_section
from . import plot
from . import utils
from deltametrics.utils import _points_in_polygon
from deltametrics.utils import is_ndarray_or_xarray


class BasePlanform(abc.ABC):
Expand Down Expand Up @@ -707,7 +708,7 @@ def __init__(self, *args, **kwargs):
raise ValueError("Expected 1 input, got %s." % str(len(args)))

# process the argument to the omask needed for Shaw OAM
if utils.is_ndarray_or_xarray(args[0]):
if is_ndarray_or_xarray(args[0]):
_arr = args[0]
# check that is boolean or integer binary
if _arr.dtype == bool:
Expand Down Expand Up @@ -1002,7 +1003,7 @@ def __init__(self, *args, **kwargs):
# assign first argument to attribute of self
if issubclass(type(args[0]), mask.BaseMask):
self._elevation_mask = args[0]._mask
elif utils.is_ndarray_or_xarray(args[0]):
elif is_ndarray_or_xarray(args[0]):
self._elevation_mask = args[0]
else:
raise TypeError("Type of first argument is unrecognized or unsupported")
Expand Down Expand Up @@ -1869,7 +1870,7 @@ def shaw_opening_angle_method(
## Make sea points
# identify set of points in both the convex hull polygon and
# defined as points_to_test and put these binary points into seamap
sea_points_in_hull_bool = utils._points_in_polygon(
sea_points_in_hull_bool = _points_in_polygon(
all_sea_points, test_set_points[hull.vertices]
)
sea_points_in_hull_bool = sea_points_in_hull_bool.astype(bool)
Expand Down Expand Up @@ -2003,7 +2004,7 @@ def morphological_closing_method(elevationmask, biggestdisk=None):
# coerce input image into 2-d ndarray
if isinstance(elevationmask, mask.BaseMask):
emsk = np.array(elevationmask.mask)
elif utils.is_ndarray_or_xarray(elevationmask):
elif is_ndarray_or_xarray(elevationmask):
emsk = np.array(elevationmask)
else:
raise TypeError(
Expand Down Expand Up @@ -2113,7 +2114,7 @@ def compute_channel_width(channelmask, section=None, return_widths=False):
# todo...

# coerce the channel mask to just the raw mask values
if utils.is_ndarray_or_xarray(channelmask):
if is_ndarray_or_xarray(channelmask):
if isinstance(channelmask, xr.core.dataarray.DataArray):
_dx = float(
channelmask[channelmask.dims[0]][1]
Expand Down Expand Up @@ -2245,7 +2246,7 @@ def compute_channel_depth(
# check that the section trace is a valid shape
# todo...

if utils.is_ndarray_or_xarray(channelmask):
if is_ndarray_or_xarray(channelmask):
pass
elif isinstance(channelmask, mask.ChannelMask):
channelmask = np.array(channelmask.mask)
Expand Down Expand Up @@ -2367,7 +2368,7 @@ def compute_surface_deposit_time(data, surface_idx=-1, **kwargs):
if isinstance(data, cube.DataCube):
etas = data["eta"][:surface_idx, :, :]
etas = np.array(etas) # strip xarray for input to helper
elif utils.is_ndarray_or_xarray(data):
elif is_ndarray_or_xarray(data):
etas = np.array(data[:surface_idx, :, :])
else:
# implement other options...
Expand Down
4 changes: 2 additions & 2 deletions deltametrics/sample_data/sample_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
import pooch

from .. import cube
from .. import utils
from deltametrics.utils import _get_version


# deltametrics version
__version__ = utils._get_version()
__version__ = _get_version()

# enusre DeprecationWarning is shown
warnings.simplefilter("default")
Expand Down
26 changes: 16 additions & 10 deletions deltametrics/section.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@
from . import plot
from . import mask
from . import plan
from . import utils
from deltametrics.utils import NoStratigraphyError
from deltametrics.utils import circle_to_cells
from deltametrics.utils import coordinates_to_segments
from deltametrics.utils import guess_land_width_from_land
from deltametrics.utils import is_ndarray_or_xarray
from deltametrics.utils import line_to_cells
from deltametrics.utils import segments_to_cells


@xr.register_dataarray_accessor("strat")
Expand Down Expand Up @@ -113,7 +119,7 @@ def _check_knows_stratigraphy(self):
Raises if does not know stratigraphy.
"""
if not self._knows_stratigraphy:
raise utils.NoStratigraphyError(obj=self)
raise NoStratigraphyError(obj=self)
return self._knows_stratigraphy

def as_preserved(self):
Expand Down Expand Up @@ -233,7 +239,7 @@ def connect(self, InputInstance, name=None):
self._underlying_dim1_coords = _mask_xarray[_mask_xarray.dims[0]]
self._underlying_dim2_coords = _mask_xarray[_mask_xarray.dims[1]]
self._z = None
elif utils.is_ndarray_or_xarray(InputInstance):
elif is_ndarray_or_xarray(InputInstance):
self._underlying = InputInstance
self._underlying_type = "array"
self._variables = None
Expand Down Expand Up @@ -404,7 +410,7 @@ def strat_attr(self):
if self._underlying._knows_stratigraphy:
return self._underlying.strat_attr
else:
raise utils.NoStratigraphyError(obj=self, var="strat_attr")
raise NoStratigraphyError(obj=self, var="strat_attr")

def __getitem__(self, var):
"""Get a slice of the section.
Expand Down Expand Up @@ -872,8 +878,8 @@ def _compute_section_coords(self):

# convert the points into segments into lists of cells
# input to utils needs to be xy cartesian order
_segs = utils.coordinates_to_segments(np.fliplr(_path))
_cell = utils.segments_to_cells(_segs)
_segs = coordinates_to_segments(np.fliplr(_path))
_cell = segments_to_cells(_segs)

# determine only unique coordinates along the path
def unsorted_unique(array):
Expand Down Expand Up @@ -1592,7 +1598,7 @@ def _compute_section_coords(self):
"This is unlikely to work for data not generated from pyDeltaRCM."
)
land_width = np.minimum(
utils.guess_land_width_from_land(
guess_land_width_from_land(
self._underlying["eta"][-1, :, 0]
),
5,
Expand All @@ -1617,7 +1623,7 @@ def _compute_section_coords(self):

# use the utility to compute the cells *in order*
origin_idx_rev = tuple(reversed(self._origin_idx)) # input must be x,y
xy = utils.circle_to_cells(origin_idx_rev, self._radius_idx)
xy = circle_to_cells(origin_idx_rev, self._radius_idx)

# store
self._dim1_idx = xy[1]
Expand Down Expand Up @@ -1841,7 +1847,7 @@ def _compute_section_coords(self):
"This is unlikely to work for data not generated from pyDeltaRCM."
)
land_width = np.minimum(
utils.guess_land_width_from_land(
guess_land_width_from_land(
self._underlying["eta"][-1, :, 0]
),
5,
Expand Down Expand Up @@ -1932,7 +1938,7 @@ def _compute_section_coords(self):

# note that origin idx and end point are in x-y cartesian convention!
origin_idx_rev = tuple(reversed(self._origin_idx)) # input must be x,y
x, y = utils.line_to_cells(origin_idx_rev, end_point)
x, y = line_to_cells(origin_idx_rev, end_point)

# validate and clean the xy array
yvalid = np.logical_and(y >= 0, y <= (_L - 1))
Expand Down
8 changes: 4 additions & 4 deletions tests/test_cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from deltametrics import plot
from deltametrics import section
from deltametrics import plan
from deltametrics import utils
from deltametrics.utils import NoStratigraphyError
from deltametrics.sample_data import _get_golf_path, _get_rcm8_path, _get_landsat_path


Expand Down Expand Up @@ -157,7 +157,7 @@ def test_nostratigraphy_default_attribute_derived_variable(self):
golf = cube.DataCube(golf_path)
golf.register_section("testsection", section.StrikeSection(distance_idx=10))
assert golf._knows_stratigraphy is False
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
golf.sections["testsection"]["velocity"].strat.as_stratigraphy()

def test_fixeddatacube_init_varset(self):
Expand Down Expand Up @@ -224,9 +224,9 @@ def test_section_no_stratigraphy(self):
sc = section.StrikeSection(self.fixeddatacube, distance_idx=10)
_ = sc["velocity"][:, 1]
assert not hasattr(sc, "strat_attr")
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
_ = sc.strat_attr
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
_ = sc["velocity"].strat.as_preserved()

def test_show_section_mocked_BaseSection_show(self):
Expand Down
14 changes: 7 additions & 7 deletions tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from deltametrics import plot
from deltametrics import cube
from deltametrics import section
from deltametrics import utils
from deltametrics.utils import NoStratigraphyError
from deltametrics.sample_data import _get_golf_path


Expand Down Expand Up @@ -416,12 +416,12 @@ def test_dsv_nostrat_get_display_arrays_spacetime(self):
assert np.all(_data == self.dsv_nostrat)

def test_dsv_nostrat_get_display_arrays_preserved(self):
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
plot.get_display_arrays(self.dsv_nostrat,
data='preserved')

def test_dsv_nostrat_get_display_arrays_stratigraphy(self):
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
plot.get_display_arrays(self.dsv_nostrat,
data='stratigraphy')

Expand Down Expand Up @@ -506,12 +506,12 @@ def test_dsv_nostrat_get_display_lines_spacetime(self):
assert _segments.shape[1:] == (2, 2)

def test_dsv_nostrat_get_display_lines_preserved(self):
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
plot.get_display_lines(self.dsv_nostrat,
data='preserved')

def test_dsv_nostrat_get_display_lines_stratigraphy(self):
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
plot.get_display_lines(self.dsv_nostrat,
data='stratigraphy')

Expand Down Expand Up @@ -582,11 +582,11 @@ def test_dsv_nostrat_get_display_limits_spacetime(self):
assert len(_lims) == 4

def test_dsv_nostrat_get_display_limits_preserved(self):
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
plot.get_display_limits(self.dsv_nostrat, data='preserved')

def test_dsv_nostrat_get_display_limits_stratigraphy(self):
with pytest.raises(utils.NoStratigraphyError):
with pytest.raises(NoStratigraphyError):
plot.get_display_limits(self.dsv_nostrat, data='stratigraphy')

def test_dsv_get_display_limits_spacetime(self):
Expand Down
Loading

0 comments on commit f8cc545

Please sign in to comment.