Skip to content

Commit 3397b36

Browse files
committed
Add support for masked quantities
Fixes #202.
1 parent 6826f49 commit 3397b36

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

CHANGES.rst

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
0.8.0 (unreleased)
2+
------------------
3+
4+
- Add support for masked quantities [#749]
5+
16
0.7.0 (2024-11-13)
27
------------------
38

asdf_astropy/converters/unit/quantity.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1+
import numpy as np
12
from asdf.extension import Converter
23
from asdf.tags.core.ndarray import NDArrayType
4+
from astropy.units import Quantity
5+
from astropy.utils.masked import Masked
6+
7+
MaskedQuantity = Masked(Quantity)
38

49

510
class QuantityConverter(Converter):
@@ -9,11 +14,12 @@ class QuantityConverter(Converter):
914
# The Distance class has no tag of its own, so we
1015
# just serialize it as a quantity.
1116
"astropy.coordinates.distances.Distance",
17+
MaskedQuantity,
1218
)
1319

1420
def to_yaml_tree(self, obj, tag, ctx):
1521
node = {
16-
"value": obj.value,
22+
"value": np.ma.asarray(obj.value) if isinstance(obj, MaskedQuantity) else obj.value,
1723
"unit": obj.unit,
1824
}
1925

@@ -39,4 +45,6 @@ def from_yaml_tree(self, node, tag, ctx):
3945
value = value._make_array()
4046
dtype = value.dtype
4147

42-
return Quantity(value, unit=node["unit"], copy=copy, dtype=dtype)
48+
class_ = MaskedQuantity if isinstance(value, np.ma.MaskedArray) else Quantity
49+
50+
return class_(value, unit=node["unit"], copy=copy, dtype=dtype)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import asdf
2+
from astropy import units as u
3+
from astropy.utils.masked import Masked
4+
5+
MaskedQuantity = Masked(u.Quantity)
6+
7+
8+
def test_masked_quantity(tmp_path):
9+
file_path = tmp_path / "test.asdf"
10+
with asdf.AsdfFile() as af:
11+
af["quantity"] = Masked([1, 2, 3], [False, False, True]) * u.yottamole
12+
af.write_to(file_path)
13+
14+
with asdf.open(file_path) as af:
15+
assert isinstance(af["quantity"], MaskedQuantity)

0 commit comments

Comments
 (0)