# Licensed under a 3-clause BSD style license - see LICENSE.rst
# Dependencies
from collections import defaultdict
from contextlib import contextmanager
from contextvars import ContextVar
import numpy as np
# Project
from astropy import units as u
from astropy.time import Time
from astropy.utils import ShapedLikeNDArray
from .earth import EarthLocation
from .representation import BaseDifferential, CartesianRepresentation
__all__ = [
"Attribute",
"CartesianRepresentationAttribute",
"CoordinateAttribute",
"DifferentialAttribute",
"EarthLocationAttribute",
"QuantityAttribute",
"TimeAttribute",
"impose_frame_attributes",
]
_imposed_attributes: ContextVar[defaultdict | None] = ContextVar(
"_imposed_attributes", default=None
)
def _get_imposed_attributes():
"""A helper function so that we don't have a mutable default in ContextVar."""
return _imposed_attributes.get() or {}
[docs]
@contextmanager
def impose_frame_attributes(**kwargs):
"""
Assume a value of one or more frame attributes.
Parameters
----------
kwargs
This function accepts any keyword arguments and will override
any frame attribute with a name matching that of the keyword
name.
Examples
--------
>>> import astropy.units as u
>>> from astropy.coordinates import EarthLocation, SkyCoord
>>> from astropy.coordinates.attributes import impose_frame_attributes
>>> location = EarthLocation(-5466045*u.m, -2404388*u.m, 2242133*u.m)
Say you have two coordinates that represent points in images which are very close in time but not exactly the same:
>>> coord1 = SkyCoord(10, 20, unit=u.deg, obstime="2026-01-01T00:00:00", location=location, frame="altaz")
>>> coord2 = SkyCoord(10, 20, unit=u.deg, obstime="2026-01-01T00:01:00", location=location, frame="altaz")
If you transform these to other frames, they will give slightly different results:
>>> coord1.transform_to("icrs")
<SkyCoord (ICRS): (ra, dec) in deg
(36.10412254, 80.47633131)>
>>> coord2.transform_to("icrs")
<SkyCoord (ICRS): (ra, dec) in deg
(36.35158456, 80.47671193)>
If however, you are happy to ignore this small change in observer
location, and you want to avoid more complex transformations or
other effects through the transform graph, you can do this:
>>> with impose_frame_attributes(obstime="2026-01-01T00:00:00"):
... coord2.transform_to("icrs")
<SkyCoord (ICRS): (ra, dec) in deg
(36.10412254, 80.47633131)>
Another example is computing the separation between two `~.HCRS` frames with slightly different obstimes.
>>> import astropy.units as u
>>> from astropy.coordinates import SkyCoord
>>> coord1 = SkyCoord(10*u.deg, 20*u.deg, frame='hcrs', obstime='2026-01-01 00:00:00')
>>> coord2 = SkyCoord(20*u.deg, 30*u.deg, frame='hcrs', obstime='2026-01-01 00:00:00.001')
When you try and compute the separation an error is raised because of the origin shift.
>>> print(coord1.separation(coord2)) # doctest: +SKIP
...
astropy.units.errors.UnitsError: The input HCRS coordinates do not have length units. This probably means you created coordinates with lat/lon but no distance. Heliocentric<->ICRS transforms cannot function in this case because there is an origin shift.
However, using this context manager:
>>> with impose_frame_attributes(obstime=coord1.obstime):
... print(coord1.separation(coord2))
13d28m54.20360928s
Both of these examples are trivial when constructing coordinates
like this, but when operating on a large number of coordinates
read from a file or with coordinate transforms in packages such as
``reproject``, it becomes harder to make these changes manually.
"""
# Get the current imposed attributes
current_attrs = _get_imposed_attributes()
# Build the new set, overriding current with kwargs
new_attrs = {**current_attrs, **kwargs}
# Set the new imposed attrs, but make sure it's still a defaultdict
token = _imposed_attributes.set(defaultdict(lambda: None, new_attrs))
try:
yield
finally:
# Reset to previous value using token
_imposed_attributes.reset(token)
[docs]
class Attribute:
"""A non-mutable data descriptor to hold a frame attribute.
This class must be used to define frame attributes (e.g. ``equinox`` or
``obstime``) that are included in a frame class definition.
Examples
--------
The `~astropy.coordinates.FK4` class uses the following class attributes::
class FK4(BaseCoordinateFrame):
equinox = TimeAttribute(default=_EQUINOX_B1950)
obstime = TimeAttribute(default=None,
secondary_attribute='equinox')
This means that ``equinox`` and ``obstime`` are available to be set as
keyword arguments when creating an ``FK4`` class instance and are then
accessible as instance attributes. The instance value for the attribute
must be stored in ``'_' + <attribute_name>`` by the frame ``__init__``
method.
Note in this example that ``equinox`` and ``obstime`` are time attributes
and use the ``TimeAttributeFrame`` class. This subclass overrides the
``convert_input`` method to validate and convert inputs into a ``Time``
object.
Parameters
----------
default : object
Default value for the attribute if not provided
secondary_attribute : str
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
doc : str
Description of the frame attribute for help and documentation.
Information on the default value will be appended to this description.
"""
name = "<unbound>"
def __init__(
self, default=None, secondary_attribute="", *, doc="A frame attribute"
):
self.default = default
self.secondary_attribute = secondary_attribute
super().__init__()
# Replace the class docstring with the custom docstring
self.__doc__ = doc
# Add information on the default value
if self.default is not None:
self.__doc__ += f"\n\nDefault: {self.default}"
elif self.secondary_attribute != "":
self.__doc__ += (
f"\n\nDefault: taken from `{self.secondary_attribute}` frame attribute"
)
else:
self.__doc__ += "\n\nNo default value"
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, frame_cls=None):
if instance is None:
# Return the descriptor instance to enable the retrieval of the docstring
return self
if (imposed_value := _get_imposed_attributes().get(self.name)) is not None:
out = imposed_value
else:
out = getattr(instance, "_" + self.name, self.default)
if out is None:
out = getattr(instance, self.secondary_attribute, self.default)
out, converted = self.convert_input(out)
if instance is not None:
# None if instance (frame) has no data!
instance_shape = getattr(instance, "shape", None)
if instance_shape is not None and (
getattr(out, "shape", ()) and out.shape != instance_shape
):
# If the shapes do not match, try broadcasting.
try:
if isinstance(out, ShapedLikeNDArray):
out = out._apply(
np.broadcast_to, shape=instance_shape, subok=True
)
else:
out = np.broadcast_to(out, instance_shape, subok=True)
except ValueError:
# raise more informative exception.
raise ValueError(
f"attribute {self.name} should be scalar or have shape"
f" {instance_shape}, but it has shape {out.shape} and could not"
" be broadcast."
)
converted = True
if converted and not imposed_value:
setattr(instance, "_" + self.name, out)
return out
def __set__(self, instance, val):
raise AttributeError("Cannot set frame attribute")
[docs]
class TimeAttribute(Attribute):
"""
Frame attribute descriptor for quantities that are Time objects.
See the `~astropy.coordinates.Attribute` API doc for further
information.
Parameters
----------
default : object
Default value for the attribute if not provided
secondary_attribute : str
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
doc : str
Description of the frame attribute for help and documentation
"""
[docs]
class CartesianRepresentationAttribute(Attribute):
"""
A frame attribute that is a CartesianRepresentation with specified units.
Parameters
----------
default : object
Default value for the attribute if not provided
secondary_attribute : str
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
unit : unit-like or None
Name of a unit that the input will be converted into. If None, no
unit-checking or conversion is performed
doc : str
Description of the frame attribute for help and documentation
"""
def __init__(self, default=None, secondary_attribute="", unit=None, **kwargs):
super().__init__(default, secondary_attribute, **kwargs)
self.unit = unit
[docs]
class QuantityAttribute(Attribute):
"""
A frame attribute that is a quantity with specified units and shape
(optionally).
Can be `None`, which should be used for special cases in associated
frame transformations like "this quantity should be ignored" or similar.
Parameters
----------
default : number or `~astropy.units.Quantity` or None, optional
Default value for the attribute if the user does not supply one. If a
Quantity, it must be consistent with ``unit``, or if a value, ``unit``
cannot be None.
secondary_attribute : str, optional
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
unit : unit-like or None, optional
Name of a unit that the input will be converted into. If None, no
unit-checking or conversion is performed
shape : tuple or None, optional
If given, specifies the shape the attribute must be
doc : str
Description of the frame attribute for help and documentation
"""
def __init__(
self, default=None, secondary_attribute="", unit=None, shape=None, **kwargs
):
if default is None and unit is None:
raise ValueError(
"Either a default quantity value must be provided, or a unit must "
"be provided to define a QuantityAttribute."
)
if default is not None and unit is None:
unit = default.unit
self.unit = unit
self.shape = shape
default = self.convert_input(default)[0]
super().__init__(default, secondary_attribute, **kwargs)
[docs]
class EarthLocationAttribute(Attribute):
"""
A frame attribute that can act as a `~astropy.coordinates.EarthLocation`.
It can be created as anything that can be transformed to the
`~astropy.coordinates.ITRS` frame, but always presents as an `EarthLocation`
when accessed after creation.
Parameters
----------
default : object
Default value for the attribute if not provided
secondary_attribute : str
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
doc : str
Description of the frame attribute for help and documentation
"""
[docs]
class CoordinateAttribute(Attribute):
"""
A frame attribute which is a coordinate object. It can be given as a
`~astropy.coordinates.SkyCoord` or a low-level frame instance. If a
low-level frame instance is provided, it will always be upgraded to be a
`~astropy.coordinates.SkyCoord` to ensure consistent transformation
behavior. The coordinate object will always be returned as a low-level
frame instance when accessed.
Parameters
----------
frame : `~astropy.coordinates.BaseCoordinateFrame` class
The type of frame this attribute can be
default : object
Default value for the attribute if not provided
secondary_attribute : str
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
doc : str
Description of the frame attribute for help and documentation
"""
def __init__(self, frame, default=None, secondary_attribute="", **kwargs):
self._frame = frame
super().__init__(default, secondary_attribute, **kwargs)
[docs]
class DifferentialAttribute(Attribute):
"""A frame attribute which is a differential instance.
The optional ``allowed_classes`` argument allows specifying a restricted
set of valid differential classes to check the input against. Otherwise,
any `~astropy.coordinates.BaseDifferential` subclass instance is valid.
Parameters
----------
default : object
Default value for the attribute if not provided
allowed_classes : tuple, optional
A list of allowed differential classes for this attribute to have.
secondary_attribute : str
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
doc : str
Description of the frame attribute for help and documentation
"""
def __init__(
self, default=None, allowed_classes=None, secondary_attribute="", **kwargs
):
if allowed_classes is not None:
self.allowed_classes = tuple(allowed_classes)
else:
self.allowed_classes = BaseDifferential
super().__init__(default, secondary_attribute, **kwargs)