| 1 |
from asdf.extension import Converter |
| 2 |
from asdf.tags.core.ndarray import NDArrayType |
| 3 |
|
| 4 |
|
| 5 |
class QuantityConverter(Converter): |
| 6 |
tags = ("tag:stsci.edu:asdf/unit/quantity-*",) |
| 7 |
types = ( |
| 8 |
"astropy.units.quantity.Quantity", |
| 9 |
# The Distance class has no tag of its own, so we |
| 10 |
# just serialize it as a quantity. |
| 11 |
"astropy.coordinates.distances.Distance", |
| 12 |
"astropy.utils.masked.core.MaskedQuantity", |
| 13 |
) |
| 14 |
|
| 15 |
def to_yaml_tree(self, obj, tag, ctx): |
| 16 |
import numpy as np |
| 17 |
from astropy.utils.masked import Masked |
| 18 |
|
| 19 |
node = { |
| 20 |
"value": np.ma.asarray(obj.value) if isinstance(obj, Masked) else obj.value, |
| 21 |
"unit": obj.unit, |
| 22 |
} |
| 23 |
|
| 24 |
if obj.isscalar: |
| 25 |
node["datatype"] = obj.dtype.name |
| 26 |
|
| 27 |
return node |
| 28 |
|
| 29 |
def from_yaml_tree(self, node, tag, ctx): |
| 30 |
# numpy 2.0 changed behavior for copy where an error is produced |
| 31 |
# if False and a copy is required (previously there was no error) |
| 32 |
# astropy 6.1 changed Quantity in a similar way |
| 33 |
import numpy as np |
| 34 |
from astropy.units import Quantity |
| 35 |
|
| 36 |
copy = None if np.lib.NumpyVersion(np.__version__) >= "2.0.0b1" else False |
| 37 |
|
| 38 |
value = node["value"] |
| 39 |
dtype = node.get("datatype", None) |
| 40 |
if isinstance(value, NDArrayType): |
| 41 |
# TODO: Why doesn't NDArrayType work? This needs some research |
| 42 |
# and documentation. |
| 43 |
value = value._make_array() |
| 44 |
dtype = value.dtype |
| 45 |
|
| 46 |
if isinstance(value, np.ma.MaskedArray): |
| 47 |
from astropy.utils import minversion |
| 48 |
from astropy.utils.masked import Masked |
| 49 |
|
| 50 |
if not minversion("astropy", "7.1.dev"): # ASTROPY_GE_7_1 |
| 51 |
msg = "MaskedQuantity support requires astropy 7.1 or later" |
| 52 |
raise NotImplementedError(msg) |
| 53 |
class_ = Masked(Quantity) |
| 54 |
else: |
| 55 |
class_ = Quantity |
| 56 |
|
| 57 |
return class_(value, unit=node["unit"], copy=copy, dtype=dtype) |