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

Add a trait for astropy quantities #2524

Merged
merged 6 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions docs/changes/2524.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add an ``AstroQuantity`` trait which can hold any ``astropy.units.Quantity``.
41 changes: 41 additions & 0 deletions src/ctapipe/core/tests/test_traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from ctapipe.core import Component
from ctapipe.core.traits import (
AstroQuantity,
AstroTime,
List,
Path,
Expand Down Expand Up @@ -278,6 +279,46 @@ class NoNone(Component):
c.time = None


def test_quantity():
import astropy.units as u

class SomeComponentWithQuantityTrait(Component):
quantity = AstroQuantity()

c = SomeComponentWithQuantityTrait()
c.quantity = -1.754 * u.m / (u.s * u.deg)
assert isinstance(c.quantity, u.Quantity)
assert c.quantity.value == -1.754
assert c.quantity.unit == u.Unit("m / (deg s)")

c.quantity = "1337 erg / centimeter**2 second"
assert isinstance(c.quantity, u.Quantity)
assert c.quantity.value == 1337
assert c.quantity.unit == u.Unit("erg / (s cm2)")

with pytest.raises(TraitError):
c.quantity = "No quantity"

# Try misspelled/ non-existent unit
with pytest.raises(TraitError):
c.quantity = "5 meters"


def test_quantity_none():
class AllowNone(Component):
quantity = AstroQuantity(default_value=None, allow_none=True)

c = AllowNone()
assert c.quantity is None

class NoNone(Component):
quantity = AstroQuantity(default_value="5 meter", allow_none=False)

c = NoNone()
with pytest.raises(TraitError):
c.quantity = None


def test_component_name():
from ctapipe.core.traits import ComponentName, ComponentNameList

Expand Down
23 changes: 22 additions & 1 deletion src/ctapipe/core/traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pathlib
from urllib.parse import urlparse

import astropy.units as u
import traitlets
import traitlets.config
from astropy.time import Time
Expand All @@ -17,6 +18,7 @@

__all__ = [
# Implemented here
"AstroQuantity",
"AstroTime",
"BoolTelescopeParameter",
"IntTelescopeParameter",
Expand Down Expand Up @@ -72,8 +74,27 @@
flag = traitlets.config.boolean_flag


class AstroQuantity(TraitType):
"""A trait containing an ``astropy.units`` quantity."""

def info(self):
info = "An ``astropy.units.Quantity`` instance"
if self.allow_none:
info += "or None"

Check warning on line 83 in src/ctapipe/core/traits.py

View check run for this annotation

Codecov / codecov/patch

src/ctapipe/core/traits.py#L83

Added line #L83 was not covered by tests
return info

def validate(self, obj, value):
try:
quantity = u.Quantity(value)
return quantity
except TypeError:
return self.error(obj, value)
except ValueError:
return self.error(obj, value)


class AstroTime(TraitType):
"""A trait representing a point in Time, as understood by `astropy.time`"""
"""A trait representing a point in Time, as understood by ``astropy.time``."""

def validate(self, obj, value):
"""try to parse and return an ISO time string"""
Expand Down