Skip to content

Commit

Permalink
add get_sample_count and tests (#228)
Browse files Browse the repository at this point in the history
  • Loading branch information
d-chambers authored Aug 24, 2023
1 parent fe5ae1d commit e2cc416
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
20 changes: 20 additions & 0 deletions dascore/core/coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,26 @@ def update(self, **kwargs):
out = out.convert_units(units)
return out

def get_sample_count(self, value) -> int:
"""
Return the number of samples represented by a value.
This is calculated by dividing the value by dt and rounding up.
Therefore, the output will always be greater or equal to 1.
Parameters
----------
value
The value (supports units).
"""
if not self.evenly_sampled:
msg = "Coordinate is not evenly sampled, cant get sample count."
raise CoordError(msg)
compat_val = self._get_compatible_value(value, relative=True)
duration = compat_val - self.min()
samples = int(np.ceil(duration / self.step))
return samples


class CoordRange(BaseCoord):
"""
Expand Down
28 changes: 28 additions & 0 deletions tests/test_core/test_coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,34 @@ def test_time_delta(self, evenly_sampled_time_delta_coord):
assert out.dtype == coord.dtype


class TestGetSampleCount:
"""Tests for getting the number of samples from a coordinate."""

def test_uneven_raises(self, monotonic_float_coord):
"""Unevenly sampled counts should raise."""
msg = "Coordinate is not evenly sampled"
with pytest.raises(CoordError, match=msg):
monotonic_float_coord.get_sample_count(10)

def test_dt_lt_step(self, evenly_sampled_coord):
"""Ensure sample count is 1 when value < dt"""
dt = evenly_sampled_coord.step * 0.1
out = evenly_sampled_coord.get_sample_count(dt)
assert out == 1

def test_datetime(self, evenly_sampled_date_coord):
"""Ensure evenly sampled date coords work."""
dt = evenly_sampled_date_coord.step
out = evenly_sampled_date_coord.get_sample_count(12 * dt)
assert out == 12

def test_timedelta(self, evenly_sampled_time_delta_coord):
"""Ensure timedelta works."""
dt = evenly_sampled_time_delta_coord.step
out = evenly_sampled_time_delta_coord.get_sample_count(12 * dt)
assert out == 12


class TestIssues:
"""Tests for special issues related to coords."""

Expand Down

0 comments on commit e2cc416

Please sign in to comment.