| 1 |
import warnings |
| 2 |
|
| 3 |
from asdf.extension import Converter |
| 4 |
|
| 5 |
|
| 6 |
class UnitConverter(Converter): |
| 7 |
tags = ( |
| 8 |
"tag:stsci.edu:asdf/unit/unit-*", |
| 9 |
"tag:astropy.org:astropy/units/unit-*", |
| 10 |
) |
| 11 |
types = ( |
| 12 |
"astropy.units.core.CompositeUnit", |
| 13 |
"astropy.units.core.IrreducibleUnit", |
| 14 |
"astropy.units.core.NamedUnit", |
| 15 |
"astropy.units.core.PrefixUnit", |
| 16 |
"astropy.units.core.Unit", |
| 17 |
"astropy.units.core.UnitBase", |
| 18 |
"astropy.units.core.UnrecognizedUnit", |
| 19 |
"astropy.units.function.mixin.IrreducibleFunctionUnit", |
| 20 |
"astropy.units.function.mixin.RegularFunctionUnit", |
| 21 |
) |
| 22 |
|
| 23 |
def select_tag(self, obj, tags, ctx): |
| 24 |
from astropy.units import UnitsError, UnitsWarning |
| 25 |
|
| 26 |
with warnings.catch_warnings(): |
| 27 |
warnings.simplefilter("ignore", category=UnitsWarning) |
| 28 |
|
| 29 |
try: |
| 30 |
obj.to_string(format="vounit") |
| 31 |
except (UnitsError, ValueError): |
| 32 |
return next(t for t in tags if "astropy.org" in t) |
| 33 |
|
| 34 |
return next(t for t in tags if "stsci.edu" in t) |
| 35 |
|
| 36 |
def to_yaml_tree(self, obj, tag, ctx): |
| 37 |
from astropy.units import UnitsWarning |
| 38 |
|
| 39 |
if "stsci.edu" in tag: |
| 40 |
with warnings.catch_warnings(): |
| 41 |
# astropy emits "deprecated" warnings when there is no plan |
| 42 |
# to remove these units so we just ignore them here |
| 43 |
warnings.simplefilter("ignore", category=UnitsWarning) |
| 44 |
return obj.to_string(format="vounit") |
| 45 |
|
| 46 |
return obj.to_string() |
| 47 |
|
| 48 |
def from_yaml_tree(self, node, tag, ctx): |
| 49 |
from astropy.units import Unit |
| 50 |
|
| 51 |
kwargs = {"parse_strict": "silent"} |
| 52 |
if "stsci.edu" in tag: |
| 53 |
kwargs["format"] = "vounit" |
| 54 |
|
| 55 |
from astropy.units import UnitsWarning |
| 56 |
|
| 57 |
with warnings.catch_warnings(): |
| 58 |
# astropy emits "deprecated" warnings when there is no plan |
| 59 |
# to remove these units so we just ignore them here |
| 60 |
warnings.simplefilter("ignore", category=UnitsWarning) |
| 61 |
|
| 62 |
return Unit(node, **kwargs) |