Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow serializing and deserializing named astropy units #2475

Merged
merged 5 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions glue/core/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@
import numpy as np
from matplotlib.colors import Colormap
from matplotlib import cm
import astropy.units as u
from astropy.units import UnitBase, Unit
from astropy.wcs import WCS
import shapely

Expand Down Expand Up @@ -621,6 +623,23 @@
return slice(rec['start'], rec['stop'], rec['step'])


@saver(UnitBase)
def _save_unit_base(unit, context):
unit_str = unit.to_string()
# Check that unit can be parsed back with default enabled systems
try:
with u.set_enabled_units([u.si, u.cgs, u.astrophys]):
_ = u.Unit(unit_str)
except ValueError:
raise GlueSerializeError(f"Serializing units of '{unit}' is not yet supported")

Check warning on line 634 in glue/core/state.py

View check run for this annotation

Codecov / codecov/patch

glue/core/state.py#L633-L634

Added lines #L633 - L634 were not covered by tests
return dict(unit_base=unit_str)


@loader(UnitBase)
def _load_unit_base(rec, context):
return Unit(rec["unit_base"])


@saver(WCS)
def _save_wcs(wcs, context):
return dict(header=wcs.to_header_string())
Expand Down
28 changes: 28 additions & 0 deletions glue/core/tests/test_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,34 @@ def test_datetime_component():
assert isinstance(c2.data[0], np.datetime64)


@requires_astropy
def test_astropy_units():
import astropy.units as u
unit = u.m
unit2 = clone(unit)
assert unit2 is unit
astrofrog marked this conversation as resolved.
Show resolved Hide resolved

unit = u.km
unit2 = clone(unit)
assert unit2 is unit


@requires_astropy
def test_astropy_compound_units():
import astropy.units as u
unit = u.m / u.s
unit2 = clone(unit)
assert unit2 == unit

unit = u.W / u.m**2 / u.nm
unit2 = clone(unit)
assert unit2 == unit

unit = u.km
unit2 = clone(unit)
assert unit2 is unit


class DummyClass(object):
pass

Expand Down