Skip to content

Commit

Permalink
support coercing iterables with nonuniform dimensionally equivalent u…
Browse files Browse the repository at this point in the history
…nits to a single unyt_array
  • Loading branch information
ngoldbaum committed Nov 18, 2021
1 parent 413d06c commit 2754c9d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
8 changes: 7 additions & 1 deletion unyt/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,13 @@ def _coerce_iterable_units(input_object, registry=None):
if any([isinstance(o, unyt_array) for o in input_object]):
ff = getattr(input_object[0], "units", NULL_UNIT)
if any([ff != getattr(_, "units", NULL_UNIT) for _ in input_object]):
raise IterableUnitCoercionError(input_object)
ret = []
for datum in input_object:
try:
ret.append(datum.in_units(ff.units))
except UnitConversionError:
raise IterableUnitCoercionError(str(input_object))
return unyt_array(np.array(ret), ff, registry=registry)
# This will create a copy of the data in the iterable.
return unyt_array(np.array(input_object), ff, registry=registry)
return np.asarray(input_object)
Expand Down
14 changes: 9 additions & 5 deletions unyt/tests/test_unyt_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2161,17 +2161,21 @@ def test_ones_and_zeros_like():


def test_coerce_iterable():
from unyt import cm, km
from unyt import cm, m, g

a = unyt_array([1, 2, 3], "cm")
b = [1 * cm, 2 * km, 3 * cm]
b = [1 * cm, 2 * m, 3 * cm]
c = [1 * g, 2 * m, 3 * cm]

assert_equal(a + b, unyt_array([2, 202, 6], 'cm'))
assert_equal(b + a, unyt_array([2, 202, 6], 'cm'))
with pytest.raises(IterableUnitCoercionError):
a + b
a + c
with pytest.raises(IterableUnitCoercionError):
b + a
c + a
assert_equal(unyt_array(b), unyt_array([1, 200, 3], 'cm'))
with pytest.raises(IterableUnitCoercionError):
unyt_array(b)
unyt_array(c)


def test_bypass_validation():
Expand Down

0 comments on commit 2754c9d

Please sign in to comment.