From 330d8c025e12a1a097a8f15a75b57b0b3c238f3f Mon Sep 17 00:00:00 2001 From: Anton Soloviev Date: Fri, 23 Oct 2026 22:12:29 -0700 Subject: [PATCH] Allow numeric bounds when clipping dimensionless quantities Fixes #108. Normalize dimensionless numeric bounds before rescaling, preserving dimensional-bound validation and output behavior. --- CHANGES.txt | 3 +++ quantities/quantity.py | 4 ++-- quantities/tests/test_methods.py | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 73e05ed..694e216 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -6,6 +6,9 @@ CHANGES Unreleased ----------- +- Allow numeric bounds when clipping dimensionless quantities (`#108 + `_). + - Correct the pond force unit to 0.00980665 N (one gram-force); it was previously 1000 times too large (`#44 `_). diff --git a/quantities/quantity.py b/quantities/quantity.py index 0cde19c..2010dbb 100644 --- a/quantities/quantity.py +++ b/quantities/quantity.py @@ -653,8 +653,8 @@ def clip(self, min=None, max=None, out=None): ) clipped = self.magnitude.clip( - min.rescale(self._dimensionality).magnitude, - max.rescale(self._dimensionality).magnitude, + Quantity(min).rescale(self._dimensionality).magnitude, + Quantity(max).rescale(self._dimensionality).magnitude, None if out is None else out.magnitude ) dim = self.dimensionality diff --git a/quantities/tests/test_methods.py b/quantities/tests/test_methods.py index 20c238c..4493fb6 100644 --- a/quantities/tests/test_methods.py +++ b/quantities/tests/test_methods.py @@ -218,6 +218,23 @@ def test_clip(self): self.assertRaises(ValueError, self.q.clip, pq.J) self.assertRaises(ValueError, self.q.clip, 1) + def test_clip_dimensionless_numeric_bounds(self): + q = [[-2., 0.5], [1.5, 3.]] * pq.dimensionless + for lower, upper in ((0, 1), (None, 1), (0, None), + (np.array([[0.], [1.]]), [1., 2.])): + with self.subTest(lower=lower, upper=upper): + expected = q.magnitude.clip(lower, upper) * pq.dimensionless + self.assertQuantityEqual(q.clip(lower, upper), expected) + self.assertQuantityEqual(np.clip(q, lower, upper), expected) + out = np.empty(q.shape) * pq.dimensionless + self.assertIs(q.clip(lower, upper, out=out), out) + self.assertQuantityEqual(out, expected) + self.assertQuantityEqual(q.clip(0, 1 * pq.dimensionless), + [[0., 0.5], [1., 1.]] * pq.dimensionless) + self.assertRaises(ValueError, q.clip, 0 * pq.m, 1) + self.assertRaises(ValueError, self.q.clip, 0, 1 * pq.m) + self.assertQuantityEqual(q, [[-2., 0.5], [1.5, 3.]] * pq.dimensionless) + def test_round(self): q = [1, 1.33, 5.67, 22] * pq.m self.methodWithOut(