coords – coordinate classes and coordinate conversions¶

Overview¶

The coords module contains classes and functions specifying locations of objects on the sky as well as coordinate converstions and distance computations, including cosmological distance and redshift calculations.

Some of the calculations involved make use of the currently selected cosmology (see astropysics.constants) and hence may not function as expected if a particularly strange cosmology is in use.

Note

Timekeeping/conversion functions are kept in astropysics.obstools, although some are crucial to coordinate systems.

Kapteyn libraries
A set of python libraries with excellent coordinate transform and other capabilities.
Meeus, Jean H. “Astronomical Algorithms” ISBN 0943396352
An authoritative reference on coordinates, ephemerides, and related transforms in astronomy.
Standards Of Fundamental Astronomy (SOFA)
The IAU reference implementations for coordinates and earth rotation.
USNO Circular 179
An excellent description of the IAU 2000 resolutions and related background for defining ICRS, CIO, and related standards.

Note

Some functionality in this module makes use of derived versions of the SOFA routines. Use of these derived works requires inclusion of the SOFA license (included in the licenses/SOFA_LICENSE file of the source distribution) and notation indicating how these routines have been modified. In all cases where SOFA-derived routines are used, the routine’s functionality is replicated exactly as the SOFA implementation (barring the possibility of typos), but adapted to the python language.

Todo

Tutorials that unify the sub-modules?

The coords module is composed of three submodules to make organization clearer. The coordsys module implements classes representing useful coordinate systems in astronomy and a framework to add additional coordinate systems as desired. It also implements standard transformations between the various celestial and terrestrial coordinates (although transformation to local horizontal coordinates is done with methods of astropysics.obstools.Site). ephems implements ephemerides for solar system objects and proper motions. Finally, funcs contains a range of utility functions including cartesian<->spherical and other canonical transforms, as well as cosmological distance calculations. The documentation for each of the sub-modules is described below.

Note

The coords module is composed of submodules that can be accessed seperately. However, they are all also included in the base module. Thus, as an example, astropysics.coords.coordsys.ICRSCoordinates and astropysics.coords.ICRSCoordinates are different names for the same class (ICRSCoordinates). The astropysics.coords.ICRSCoordinates usage is preferred as this allows the internal organization to be changed if it is deemed necessary.

coords.coordsys – coordinate systems and transforms¶

This module contains classes representing coordinates in spatial, celestial, and terrestrial coordinate systems, as well as implementations of transformations between many of the coordinate systems. There are also utility functions for easy-of-use of some of these classes.

The coordinate system framework is designed to allow users to add their own coordinate systems easily, if desired, and implement transformations between theirs and the builtin coordinate systems. This is implemented through the transformation registry static methods of the CoordinateSystem class (e.g. CoordinateSystem.registerTransform()).

Examples¶

A common task might be to convert coordinates from one standard coordinate system to another. The coords module makes this simple:

>>> from astropysics.coords import ICRSCoordinates,GalacticCoordinates
>>> gcoords = ICRSCoordinates('2h34m12.32s',12.3).convert(GalacticCoordinates)
>>> print gcoords
GalacticCoordinates: l=158.558650,b=-43.350066
>>> print '%.3f'%gcoords.l.degrees
158.559
2.767
>>> print gcoords.b.getDmsStr(canonical=True)
-43:21:00.24


Note the initial input composed of an hours,minutes,seconds string input for the RA, and a float for the dec – EquatorialCoordinate objects contain a powerful parsing system that accepts most standard astronomical representations. The resulting GalacticCoordinates object’s coordinates can then be accessed in any of the various ways supported by the AngularCoordinate object.

Warning

Errors are not currently propogated in all coordinate transforms - this will be corrected eventually, but for now you should check to make sure errors propogate for any coordinate transform you want to perform.

Built-in Transforms¶

A number of coordinate systems are provided built into astropysics. Most of these have pre-defined standard transformations. The built-in coordinate classes with defined transformation are shown in the diagram below.

A similar diagram can be generated after the user has created and registered custom coordinates and transforms:

from networkx import to_agraph,relabel_nodes,draw_networkx
from astropysics.coords import CoordinateSystem
graph = CoordinateSystem.getTransformGraph()
dotgraph = to_agraph(relabel_nodes(graph,lambda n:n.__name__))
dotgraph.graph_attr.update(dict(size='12.0, 12.0',fontsize=12))
dotgraph.write('mygraph.dot')
draw_networkx(graph)


This will save a graphviz dot file and displaying the graph with matplotlib, showing both builtin and custom-added coordinates and transforms.

Module API¶

Bases: object

A class representing an angular value.

Arithmetic operators can be applied to the coordinate, and will be applied directly to the numerical value in radians. For + and -, two angular coordinates may be used, although for -, an AngularSeparation object will be returned.

The input parser is very adaptable, and can be in any of the following forms for inpt:

• A float value

if radians is True, this will be interpreted as decimal radians, otherwise, it is in degrees.

• An AngularCoordinate object

A copy of the input object will be created.

• None

The default of 0 will be used.

• A 3-tuple

If sghms is True, the tuple will be interpreted as (hours,min,sec), otherwise, (degrees,min,sec).

• A string of the form ##.##

If radians is True, this will be cast to a float and used as decimal radians, otherwise, it is in degrees.

• A string of the form ##.##d or ##.##degrees

The numerical part will be cast to a float and used as degrees.

• A string of the form ##.##h or ##.##hours

The numerical part will be cast to a float and used as hours.

The numerical part will be cast to a float and used as radians.

• A string of the form (+/-)##h##m##.##s

The numerical parts will be treated as hours,minutes, and seconds.

• A string of the form (+/-)##d##m##.##s or (+/-)##d##’##.##”

The numerical parts will be treated as degrees,minutes, and seconds.

• A string of the form (+/-)##:##:##.## or (+/-)## ## ##.##

Sexigesimal form. If sghms is None the presence of a a + or - sign idicates that it should be interpreted as degrees, minutes, and seconds. If the sign is absent, the numerical portions will be treated as hours,min,sec. thewise, if sghms evaluates to True, the numerical parts will be treated as hours,minutes, and seconds, and if sghms evaluates to False, degrees,minutes, and seconds.

Parameters: inpt – The coordinate value – valid forms are described above. sghms (boolean) – If True, ambiguous sexigesimal inputs should be hours, minutes, and seconds instead of degrees,arcmin, and arcsec range – Sets the valid range of coordinates. Either a 2-sequence (lowerdegrees,upperdegrees) or None (for no limit) radians (boolean) – If True, ambiguous inputs are treated as radians rather than degrees.

Examples

>>> from math import pi
>>> ac = AngularCoordinate(2.5)
>>> print ac
+2d30'00.00"
>>> print AngularCoordinate(ac)
+2d30'00.00"
+180d00.00"
>>> print AngularCoordinate('1.1')
+1d6'00.00"
+63d1'31.29"
>>> print AngularCoordinate('12d25m12.5s')
+12d25'12.50"
>>> print AngularCoordinate('3:30:30',sghms=True)
+52d37'30.00"
>>> print AngularCoordinate('3:30:30',sghms=False)
+3d30'30.00"
>>> print AngularCoordinate('-3:30:30',sghms=None)
-3d30'30.00"
>>> print AngularCoordinate('+3:30:30',sghms=None)
+3d30'30.00"
>>> print AngularCoordinate('3:30:30',sghms=None)
+52d37'30.00"

d

The value of this AngularCoordinate in decimal degrees.

degminsec

The value of this AngularCoordinate as an (degrees,minutes,seconds) tuple, with degrees and minutes as integers and seconds as a float.

degrees

The value of this AngularCoordinate in decimal degrees.

dms

The value of this AngularCoordinate as an (degrees,minutes,seconds) tuple, with degrees and minutes as integers and seconds as a float.

getDmsStr(secform='%05.2f', sep=(u'xb0', "'", '"'), sign=True, canonical=False, inclzero=True)

Generates the string representation of this AngularCoordinate as degrees, arcminutes, and arcseconds.

Parameters: secform (string) – a formatter for the seconds sep (string or 3-tuple of strings) – The seperator between components - defaults to degree sign, ‘ and ” symbols. sign (boolean) – Forces sign to be present before degree component. canonical – forces [+/-]dd:mm:ss.ss , overriding other arguments inclzero (bool) – If True, a “0” is included whenever even if the degrees or minutes are 0. Otherise, the “0” and the corresponding separator are omitted from the string. String representation of this object.
getHmsStr(secform=None, sep=('h', 'm', 's'), canonical=False, inclzero=True)

gets the string representation of this AngularCoordinate as hours, minutes, and seconds

secform is the formatter for the seconds component

sep is the seperator between components - defaults to h, m, and s

canonical forces [+/-]dd:mm:ss.ss , overriding other arguments

Generates the string representation of this AngularCoordinate as hours, minutes, and seconds.

Parameters: secform (string) – a formatter for the seconds component sep (string or 3-tuple of strings) – The seperator between components - defaults to ‘h’, ‘m’, and ‘s’. canonical – forces [+/-]dd:mm:ss.ss , overriding other arguments inclzero (bool) – If True, a “0” is included whenever even if the degrees or minutes are 0. Otherise, the “0” and the corresponding separator are omitted from the string. String representation of this object.
h

The value of this AngularCoordinate in decimal hours.

hms

The value of this AngularCoordinate as an (hours,minutes,seconds) tuple, with hours and minutes as integers and seconds as a float.

hours

The value of this AngularCoordinate in decimal hours.

hrsminsec

The value of this AngularCoordinate as an (hours,minutes,seconds) tuple, with hours and minutes as integers and seconds as a float.

r

The value of this AngularCoordinate in decimal radians.

The value of this AngularCoordinate in decimal radians.

range

The acceptable range of angles for this AngularCoordinate. This can be set as a 2-sequence (lower,upper), or as a 3-sequence (lower,upper,cycle), where cycle can be :

• 0: Angle values are coerced to lie in the range (default for 2-sequence if upper-lower is 360 degrees)
• None: A ValueError will be raised if out-of-range (default for 2-sequence otherwise)
• A positive scalar: Values are coerced in a triangle wave scheme, with the scalar specifying the period. e.g. for the latitude, (-90,90,360) would give the correct behavior)
class astropysics.coords.coordsys.AngularSeparation(*args)

This class represents a separation between two angular coordinates on the unit sphere.

A constructor is available, but the most natural way to generate this object is to use the subtraction (-) operator on two AngularCoordinate objects or two LatLongCoordinates objects.

Input arguments can be either:

• AngularSeparation(AngularSeparation object)

Generates a copy of the provided object.

• AngularSeparation(sep)

Generates a separation of the provided distance with no starting point.

• AngularSeparation(start,end)

Computes the separation from the start and end objects, which must be AngularCoordinate objects.

arcmin
arcsec
projectedSeparation(zord, usez=False, **kwargs)

Computes the physical projected separation assuming a given distance.

kwargs are passed into cosmo_z_to_dist() if usez is True.

Parameters: zord (scalar number) – Redshift or distance usez (boolean) – If True, the input will be interpreted as a redshift, and kwargs will be passed into the distance calculation. The result will be in pc. Otherwise, zord will be interpreted as a distance. a float value for the separation (in pc if redshift is used)
separation3d(zord1, zord2, usez=False, **kwargs)

computes the 3d separation assuming the two points at the ends of this AngularSeparation are at the distances zord1 and zord2.

Parameters: zord1 (scalar number) – Redshift or distance for start point zord2 (scalar number) – Redshift or distance for end point usez (boolean) – If True, the inputs will be interpreted as a redshift, and kwargs will be passed into the distance calculation. The result will be in pc. Otherwise, zord will be interpreted as a distance. a float value for the separation (in pc if redshift is used)
class astropysics.coords.coordsys.CIRSCoordinates(*args, **kwargs)

Represents an object as equatorial coordinates in the Celestial Intermediate Reference System. This is the post-2000 IAU system for equatorial coordinates that seperates the coordinate system from the dynamically complicated and somewhat imprecisely-defined ideas of the equinox and ecliptic. This system’s fundamental plane is the equator of the Celestial Intermediate Pole (CIP) and the origin of RA is at the Celestial Intermediate Origin (CIO).

Changes to the epoch will result in the coordinates being updated for precession nutation. Nutation currently uses the IAU 2000B model that should be good to ~1 mas. If aberration or annual parallax corrections are necessary, convert to ICRSCoordinates, change the epoch, and then convert back to CIRSCoordinates.

To convert from these coordinates to HorizontalCoordinates appropriate for observed coordinates, site information is necessary. Hence, the transformations from equatorial to horizontal coordinates are performed by the Site class in the obstools module, and attempting to directly convert will raise an TypeError.

Input for equatorial coordinates. Can follow any of the following forms:

• EquatorialCoordinatesBase()
• EquatorialCoordinatesBase(EquatorialCoordinatesBase)
• EquatorialCoordinatesBase(‘rastr decstr’)
• EquatorialCoordinatesBase((ra,dec))
• EquatorialCoordinatesBase(ra,dec)
• EquatorialCoordinatesBase(ra,fdec,raerr,decerr)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch,distancepc)

Note that the default epoch is 2000 if not otherwise specified. To disable epoch tranformations, set the epoch to None. If scalar values are provided, they are assummed to be degrees.

dec

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

decerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

ra

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

raerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

Transforms these EquatorialCoordinates to a new epoch using the IAU 2000 precessions from Capitaine, N. et al. 2003 as written in the USNO Circular 179.

astropysics.coords.coordsys.CartesianCoordinates

alias of RectangularCoordinates

class astropysics.coords.coordsys.CoordinateSystem

Bases: object

Base class of all coordinate systems. This class also holds the static methods that manage conversion between coordinate systems.

Subclassing

• Subclasses of CoordinateSystem must override __init__() to set initial values.
• CoordinateSystem objects are intended to be quite small, so unless there is a reason to do otherwise, subclasses should have a __slots__ class attribute (it should be a sequence of all the valid attribute names for the object - see http://docs.python.org/reference/datamodel.html for an explanation of the __slots__ mechanism).
• The transweight class variable can be set to determine the weighting of this class when computing coordinate transformation pathways. Note that smaller weights are preferred paths (e.g. a larger weight is less likely to be visited). See CoordinateSystem.getTransformGraph() for more details.

Registers a new transformation type. Transformation types are used to implement particular types of transformations without repeating similar code in each of the actual transformation functions.

The transformation type function (funcorname) will be called as transfunc(trans,coords,toclass), where trans is the output of the actual registered transformation function, coords is the coordinate object that is being converted, and toclass is the target class.

Parameters: funcorname (callable or string) – The function to register as the transfromation type function. If a string, the string is taken to be the name to use for the transformation (intended for use as a function decorator). Otherwise, the transformation type name is taken from the name of the function with any intial _ removed. The function itself, to allow for use as a decorator. Note that this means that if used as a decorator inside a class, the function will be assigned as an instance method. Alternative, if funcorname is a string, a function to be called on the transformation function will be returned (see second example).

Examples:

@addTransType
def trans1(trans,coord,tocls):

def _transfunc(trans,coord,tocls):

convert(tosys)

converts the coordinate system from it’s current system to a new CoordinateSystem object.

Parameters: tosys – The new coordinate system class. Should be a subclass of CoordinateSystem . A new object of a class determined by tosys raises NotImplementedError if conversion is not present
static delTransform(fromclass, toclass)

Deletes the transformation function to go from fromclass to toclass.

static getTransform(fromclass, toclass)

Returns the transformation function to go from fromclass to toclass.

static getTransformGraph()

Returns a networkx <http://networkx.lanl.gov/> DiGraph object representing a graph of the registered coordinate systems and the transformations between them.

Raises ImportError:
If networkx is not installed.
static getTransformPath(fromsys, tosys)

Determines the transformation path from one coordinate system to another for use with convert().

Parameters: Returns: fromsys – The starting coordinate system class tosys – The target coordinate system class A list of coordinate classes with the shortest path from fromsys to tosys (including fromsys and tosys) or a callable with the transformation if a single-step direct transformation is available If no path can be found.
static listAllTransforms()

Returns a list of 2-tuples (fromclass,toclass) of all the coordinate system combinations that have registered transformation functions.

static listTransformsFrom(fromclass)

Returns a list of classes that can be transformed from the supplied class.

static listTransformsTo(toclass)

Returns a list of classes that can be transformed to the supplied class.

static registerTransform(fromclass, toclass, func=None, transtype=None, overwrite=True)

Register a function to transform coordinates from one system to another.

The transformation function is called is func(fromobject) and should return a new object of type toclass. If called with no arguments, the function should raise a NotImplementedError or behave in a manner defined in subclasses (see e.g. LatLongCoordinates). If transtype is not None, the output of the transformation function is filered through the function applied for that type using astropysics.CoordinateSystem.addTransType() .

If the transformation function func is None, the function is taken to be a decorator, and if it is a method of a subclass of CoordinateSystem, fromclass or toclass may be the string ‘self’ . In this case, the function will use the class itself as the from or to class. The function will then be treated as a static method (e.g. it should not have self as the first argument).

Parameters: fromclass (subclass of CoordinateSystem or ‘self’) – The class to transform from. toclass (subclass of CoordinateSystem or ‘self’) – The class to transform to. func (a callable or None) – the function to perform the transform or None if decorator. transtype (string or None) – A transformation type that will be used to determine how the transform is performed, or None for no transform type. (see astropysics.CoordinateSystem.addTransType() for details). overwrite (boolean) – If True, any already existing function will be silently overriden. Otherwise, a ValueError is raised.

Examples:

class MyCoordinates(CoordinateSystem):
...
class YourCoordinates(CoordinateSystem):
...
def transformer(mycooobj):
...
return yourcoordobj
CoordinateSystem.registerTransform(MyCoordinates,YourCoordinates,transformer)

class TheirCoordinates(CoordinateSystem):
@CoordinateSystem.registerTransform(MyCoordinates,'self')
@classmethod
def fromMy(cls,mycoordinates):
...
return theircoordobj

class astropysics.coords.coordsys.EclipticCoordinatesCIRS(lamb=0, beta=0, lamberr=None, betaerr=None, epoch=2000, distanceau=None)

Ecliptic Coordinates (beta, lambda) such that the fundamental plane passes through the ecliptic at the current epoch.

Note that because the concept of the ecliptic can be complicated or even ill-defined, ecliptic coordinates is astropysics are simply defined as tied to a particular set of equatorial coordinates with a given obliquity model. For EclipticCoordinatesCIRS, the equatorial coordinates are CIRSCoordinates with obliquity given by the IAU 2006 obliquity model (see obliquity())

See the associated attribute docstrings for the meaning of the inputs.

beta

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

betaerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

lamb

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

lamberr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

obliqyear = 2006
transformToEpoch(newepoch)
class astropysics.coords.coordsys.EclipticCoordinatesEquinox(lamb=0, beta=0, lamberr=None, betaerr=None, epoch=2000, distanceau=None)

Ecliptic Coordinates (beta, lambda) such that the fundamental plane passes through the ecliptic at the current epoch.

Note that because the concept of the ecliptic can be complicated or even ill-defined, ecliptic coordinates is astropysics are simply defined as tied to a particular set of equatorial coordinates with a given obliquity model. For EclipticCoordinatesEquinox, the equatorial coordinates are EquatorialCoordinatesEquinox with obliquity given by the IAU 1980 obliquity model (see obliquity())

See the associated attribute docstrings for the meaning of the inputs.

beta

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

betaerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

lamb

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

lamberr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

obliqyear = 1980
transformToEpoch(newepoch)
class astropysics.coords.coordsys.EpochalCoordinates

A base class for CoordinateSystem classes that have changeable epochs associated with them.

Subclassing

Subclasses must implement these methods:

Furthermore, subclasses should set julianepoch to determine if they are Julian or Besselian.

epoch

Epoch for this coordinate as a float.

Setting with the string ‘now’ will set the epoch to the time at the moment the command is executed.

If set, this coordinate will be transformed to the new epoch, unless the current Epoch is None, in which case the epoch will be set with no transformation. If transformation is not desired, first set the epoch to None, and then set to the new epoch.

Julian vs. Besselian is determined by the julianepoch attribute.

epochstr

A string representation of the epoch of this object with a J or B prefixed for julian or besselian epochs.

jdepoch

Julian Date of the epoch for this object.

julianepoch = True

If True, the epoch is Julian, otherwise, Besselian

mjdepoch

Modified Julian Date of the epoch for this object.

transformToEpoch(newepoch)

Subclasses should implement this method to transform their coordinates to a new epoch. At the end of this method after the necessary data transformations are performed, subclasses should call EpochalCoordinates.transformToEpoch(newepoch).

class astropysics.coords.coordsys.EpochalLatLongCoordinates(long=0, lat=0, longerr=None, laterr=None, epoch=None, distancepc=None)

A Coordinate system where the coordinates change as a function of time. The origin and orientation of some coordinate systems are tied to the motion of the Earth and Solar System and hence most be updated as time passes.

In general this only accounts for epoch-related changes in its own coordinate system. If (for example) one has a ITRSCoordinates coordinate, changing the epoch only updates for polar motion. To properly update all epoch-related such as precession/nutation and earth rotation, the coordinate should be transformed to ICRSCoordinates , update the epoch, and transform back to TIRSCoordinates .

See the associated attribute docstrings for the meaning of the inputs.

convert(tosys, optimize=False)

Converts the coordinate system from it’s current system to a new CoordinateSystem object possibly with optimizations for matrix-based transformation of LatLongCoordinates objects.

Warning

The transformation optimizations used if optimize is True are only correct if the conversion matricies are independent of the coordinate values themselves (e.g. are linear and epoch-independent). Examples that are good for optimization include FK4->FK5->ICRS (all are epoch-independent).

In the future, this system will be smarter about knowing when it is safe to optimize, but for now, only use it if you’re sure it will work correctly.

Parameters: tosys – The new coordinate system class. Should be a subclass of CoordinateSystem . optimize (bool) – If True, speed up the transformation by composing matricies where possible. If False, the standard transformation is performed. A new object of a class determined by tosys raises NotImplementedError if converters are not present
julianepoch = True
latitude

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

latitudeerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

longitude

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

longitudeerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

class astropysics.coords.coordsys.EquatorialCoordinatesBase(*args, **kwargs)

This object represents an angular location on the unit sphere, specified in right ascension and declination. Some of the subclasses are not strictly speaking equatorial, but they are close, or are tied to the equatorial position of a particular epoch.

This is a superclass for all other Equatorial Coordinate systems - particular reference systems implement the transformToEpoch() method. See the docstring for EpochalLatLongCoordinates for subclassing suggestions.

Input for equatorial coordinates. Can follow any of the following forms:

• EquatorialCoordinatesBase()
• EquatorialCoordinatesBase(EquatorialCoordinatesBase)
• EquatorialCoordinatesBase(‘rastr decstr’)
• EquatorialCoordinatesBase((ra,dec))
• EquatorialCoordinatesBase(ra,dec)
• EquatorialCoordinatesBase(ra,fdec,raerr,decerr)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch,distancepc)

Note that the default epoch is 2000 if not otherwise specified. To disable epoch tranformations, set the epoch to None. If scalar values are provided, they are assummed to be degrees.

convert(tosys, optimize=False)

Converts the coordinate system from it’s current system to a new CoordinateSystem object possibly with optimizations for matrix-based transformation of LatLongCoordinates objects.

Warning

The transformation optimizations used if optimize is True are only correct if the conversion matricies are independent of the coordinate values themselves (e.g. are linear and epoch-independent). Examples that are good for optimization include FK4->FK5->ICRS (all are epoch-independent).

In the future, this system will be smarter about knowing when it is safe to optimize, but for now, only use it if you’re sure it will work correctly.

Parameters: tosys – The new coordinate system class. Should be a subclass of CoordinateSystem . optimize (bool) – If True, speed up the transformation by composing matricies where possible. If False, the standard transformation is performed. A new object of a class determined by tosys raises NotImplementedError if converters are not present
dec

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

decerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

ra

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

raerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

class astropysics.coords.coordsys.EquatorialCoordinatesEquinox(*args, **kwargs)

Represents an object in mean geocentric apparent equatorial coordinates, using the pre-IAU2000 systems where the plane of the ecliptic is the fundamental plane and the origin is at the equinox of date (as set by epoch).

Changes to the epoch will result in the coordinates being updated for precession, but not nutation, nor annual abberation. Neither are planned by the primary author of this package, as IAU 2000 recommends using only CIO-based systems, but if someone actually wants equinox-based nutation, feel free to implement it and pass it along.

To convert from these coordinates to HorizontalCoordinates appropriate for observed coordinates, site information is necessary. Hence, the transformations from equatorial to horizontal coordinates are performed by the Site class in the astropysics.obstools module, and attempting to directly convert will raise a TypeError.

Input for equatorial coordinates. Can follow any of the following forms:

• EquatorialCoordinatesBase()
• EquatorialCoordinatesBase(EquatorialCoordinatesBase)
• EquatorialCoordinatesBase(‘rastr decstr’)
• EquatorialCoordinatesBase((ra,dec))
• EquatorialCoordinatesBase(ra,dec)
• EquatorialCoordinatesBase(ra,fdec,raerr,decerr)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch,distancepc)

Note that the default epoch is 2000 if not otherwise specified. To disable epoch tranformations, set the epoch to None. If scalar values are provided, they are assummed to be degrees.

dec

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

decerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

ra

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

raerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

Transforms these EquatorialCoordinates to a new epoch using the IAU 2000 precessions from Capitaine, N. et al. 2003 as written in the USNO Circular 179.

transweight = 1.1
class astropysics.coords.coordsys.FK4Coordinates(*args, **kwargs)

Equatorial Coordinates fixed to the FK4 reference system. Note that this implementation does not correct for the elliptic terms of aberration as of yet.

Epoch is Besselian.

Input for FK4 coordinates. Can follow any of the following forms:

• EquatorialCoordinatesBase()
• EquatorialCoordinatesBase(EquatorialCoordinatesBase)
• EquatorialCoordinatesBase(‘rastr decstr’)
• EquatorialCoordinatesBase((ra,dec))
• EquatorialCoordinatesBase(ra,dec)
• EquatorialCoordinatesBase(ra,fdec,raerr,decerr)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch,distancepc)

The epoch of FK4 coordinates defaults to B1950.

dec

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

decerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

julianepoch = False
ra

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

raerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

Transforms these EquatorialCoordinates to a new epoch. Uses the method of Newcomb (pre-IAU1976) to compute precession.

class astropysics.coords.coordsys.FK5Coordinates(*args, **kwargs)

Equatorial Coordinates fixed to the FK5 reference system.

Input for equatorial coordinates. Can follow any of the following forms:

• EquatorialCoordinatesBase()
• EquatorialCoordinatesBase(EquatorialCoordinatesBase)
• EquatorialCoordinatesBase(‘rastr decstr’)
• EquatorialCoordinatesBase((ra,dec))
• EquatorialCoordinatesBase(ra,dec)
• EquatorialCoordinatesBase(ra,fdec,raerr,decerr)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch,distancepc)

Note that the default epoch is 2000 if not otherwise specified. To disable epoch tranformations, set the epoch to None. If scalar values are provided, they are assummed to be degrees.

dec

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

decerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

ra

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

raerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

Transforms these EquatorialCoordinates to a new epoch. Uses the algorithm resolved by the IAU in 1976 as written in Meeus, as well as Lieske, J.H. 1979.

According to SOFA, this for becomes less valid at the following levels:

• 1960 CE to 2040 CE

< 0.1”

• 1640 CE to 2360 CE

< 1”

• 500 BCE to 3000 CE

< 3”

• 1200 BCE to 3900 CE

> 10”

• 4200 BCE to 5600 CE

> 100”

• 6800 BCE to 8200 CE

> 1000”

class astropysics.coords.coordsys.GCRSCoordinates(*args, **kwargs)

Geocentric Celestial Reference System equatorial coordinates. The orientation of this coordinates is fixed to the ICRS orientation, but with origin at the earth geocenter.

Warning

Abberation of starlight not yet included in transforms.

Input for equatorial coordinates. Can follow any of the following forms:

• EquatorialCoordinatesBase()
• EquatorialCoordinatesBase(EquatorialCoordinatesBase)
• EquatorialCoordinatesBase(‘rastr decstr’)
• EquatorialCoordinatesBase((ra,dec))
• EquatorialCoordinatesBase(ra,dec)
• EquatorialCoordinatesBase(ra,fdec,raerr,decerr)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch,distancepc)

Note that the default epoch is 2000 if not otherwise specified. To disable epoch tranformations, set the epoch to None. If scalar values are provided, they are assummed to be degrees.

dec

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

decerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

ra

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

raerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

Transforms from the current epoch to a new epoch by converting to ICRS and back again in the new epoch.

class astropysics.coords.coordsys.GalacticCoordinates(long=0, lat=0, longerr=None, laterr=None, epoch=None, distancepc=None)

See the associated attribute docstrings for the meaning of the inputs.

b

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

berr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

l

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

lerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

Galactic coordinates are nominally inertial, although the definition is a bit unclear in that regard.

class astropysics.coords.coordsys.HorizontalCoordinates(alt=0, az=0, alterr=None, azerr=None, distancepc=None)

This object represents an angular location on the unit sphere, with the north pole of the coordinate position fixed to the local zenith

To convert from other Coordinate types to horizontal positions, see astropysics.obstools.Site, as site information is required for these corrections

See the associated attribute docstrings for the meaning of the inputs.

alt

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

alterr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

az

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

azerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

class astropysics.coords.coordsys.ICRSCoordinates(*args, **kwargs)

Equatorial Coordinates tied to the International Celestial Reference System (ICRS). Strictly speaking this is not an Equatorial system, as it is an inertial frame that only aligns with Earth’s equator at J2000, but it is nearly an equatorial system at J2000.

Note

Technically, this is actually the Barycentric Celestial Referense System (BCRS), distringuished from ICRS by having acounted for space motion. In astropysics, instead, space motion is already accounted for by using a astropysics.coords.ephems.EphemerisObject object, which yields coordinates (often ICRSCoordinates) at the epoch of observation.

Warning

Abberation of starlight is not yet implemented in transformations to/from ICRS.

Input for equatorial coordinates. Can follow any of the following forms:

• EquatorialCoordinatesBase()
• EquatorialCoordinatesBase(EquatorialCoordinatesBase)
• EquatorialCoordinatesBase(‘rastr decstr’)
• EquatorialCoordinatesBase((ra,dec))
• EquatorialCoordinatesBase(ra,dec)
• EquatorialCoordinatesBase(ra,fdec,raerr,decerr)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch)
• EquatorialCoordinatesBase(ra,dec,raerr,decerr,epoch,distancepc)

Note that the default epoch is 2000 if not otherwise specified. To disable epoch tranformations, set the epoch to None. If scalar values are provided, they are assummed to be degrees.

dec

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

decerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

frameBiasJ2000 = matrix([[ 1.00000000e+00, -7.07827974e-08, 8.05614894e-08], [ 7.07827948e-08, 1.00000000e+00, 3.30604145e-08], [ -8.05614917e-08, -3.30604088e-08, 1.00000000e+00]])

Frame bias matrix such that vJ2000 = B*vICRS .

ra

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

raerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

ICRS is an inertial frame, so no transformation is necessary

class astropysics.coords.coordsys.ITRSCoordinates(long=0, lat=0, longerr=None, laterr=None, epoch=None, distancepc=None)

Coordinates based on the International Terrestrial Reference System. The particular implementation here assumes ITRS matches the WGS84 coordinates (used by GPS) - for astronomical purposes, this is a perfectly good assumption.

Epoch transformations in this system only adjust for polar motion - to account for earth rotation, transform back to CIRSCoordinates or EquatorialCoordinatesEquinox, change the epoch, then transfrom back to ITRSCoordinates.

Because polar motion is not fully predictable, a number of methods are available for approximating it. To choose a method, set the ITRSCoordinates.polarmotion class attribute – this will also affect all future transformations to ITRSCoordinates from other coordinate systems. The following are valid values:

• None

Assumes the pole locations are fixed to the CIP at all times, aside from the tiny effect of s’ (the TIO-CIO shift).

• A 2-tuple of callables (xp,yp)

They will be called as xp(epoch) and yp(epoch) and the result will be assumed to give the x and y coordinates of the poles in the CIP frame.

Note

The transformations from CIRS and Equinox systems to ITRS technically involve converting to TIRS (the Terrestrial Intermediate Reference System), distinguished from ITRS by no polar motion correction. While there is no class explicitly representing TIRS, ITRS with epoch set to None is equivalent to TIRS.

See the associated attribute docstrings for the meaning of the inputs.

c
convert(tosys, optimize=False)
d
latitude

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

latitudeerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

longitude

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

longitudeerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

p
polarmotion = None

Technique of computing poles (see ITRSCoordinates documentation)

transformToEpoch(newepoch)

Transforms these ITRSCoordinates to a new epoch, adjusting the coordinate values for polar motion.

class astropysics.coords.coordsys.LatLongCoordinates(long=0, lat=0, longerr=None, laterr=None, distancepc=None)

This object represents an angular location on a sphere as represented in spherical coordinates with a latitude and longitude, and optionally a distance. Subclasses specify details such as transformations or epochs.

A LatLongCoordinate system is designed to use the transformation type (see CoordinateSystem.addTransType()) ‘smatrix’. Thus, if the transformation between two LatLongCoordinate subclasses can be represented as a unitary matrix operating on position vectors on the unit sphere, the transformation function can be written as:

@CoordinateSystem.registerTransform(InLLCoords,OutLLCoords,transtype='smatrix')
def transform(incoord):
... compute the elements of a 3x3 transformation matrix...
return np.mat([[a,b,c],[d,e,f],[g,h,i]])


Subclassing

Subclasses of LatLongCoordinates can have the class attribute _longlatnames_ as a 2-tuple of strings (longname,latname), with names for the two coordinates, e.g. (‘ra’,’dec’). They can also include the _longrange_ attribute, which specifies the range of valid values for the longitude (latitude is always -90 to 90 degrees), or None to place no restriction. See CoordinateSystem for additional subclassing information.

See the associated attribute docstrings for the meaning of the inputs.

convert(tosys, optimize=False)

Converts the coordinate system from it’s current system to a new CoordinateSystem object possibly with optimizations for matrix-based transformation of LatLongCoordinates objects.

Warning

The transformation optimizations used if optimize is True are only correct if the conversion matricies are independent of the coordinate values themselves (e.g. are linear and epoch-independent). Examples that are good for optimization include FK4->FK5->ICRS (all are epoch-independent).

In the future, this system will be smarter about knowing when it is safe to optimize, but for now, only use it if you’re sure it will work correctly.

Parameters: tosys – The new coordinate system class. Should be a subclass of CoordinateSystem . optimize (bool) – If True, speed up the transformation by composing matricies where possible. If False, the standard transformation is performed. A new object of a class determined by tosys raises NotImplementedError if converters are not present
distanceau

Parallax distance to object in AU, or None to assume infinity. Set as either a float, a 2-tuple (distance,distance_error), or a no-argument callable that returns such a tuple. Getter always returns 2-tuple or None.

distancepc

Parallax distance to object in parsecs, or None to assume infinity. Set as either a float, a 2-tuple (distance,distance_error), or a no-argument callable that returns such a tuple. Getter always returns 2-tuple or None.

getCoordinateString(sep=' ', labels=False, canonical=False, hmslong=False)
lat

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

laterr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

latitude

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

latitudeerr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

long

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

longerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

longitude

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

longitudeerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

matrixRotate(matrix, apply=True, fixrange=True, unitarycheck=False)

Applies the supplied unitary rotation matrix to these coordinates.

Parameters: matrix (a 3x3 numpy.matrix) – the transformation matrix in cartesian coordinates apply (boolean) – If True, the transform will be applied inplace to the coordinates for this object fixrange (boolean) – If True the latitude is autmoatically fixed to be on (-pi/2,pi/2) and the longitude is on (0,2pi). Otherwise the raw coordinate is output. unitarycheck (boolean) – If True and the matrix is not unitary, a ValueError will be raised. Otherwise no check is performed. (lat,long) as decimal radians after the transformation matrix is applied or (lat,long,laterr,longerr) if errors are nonzero
class astropysics.coords.coordsys.RectangularCoordinates(x, y, z)

Rectangular/Cartesian Coordinates in three dimensions. Coordinates are accessed via the attributes x, y, and z.

length

The Length of this coordinate’s vector e.g. distance from the origin. If set, the direction will be preserved but the vector will be scaled to the provided value.

x

x cartesian coordinate value

y

y cartesian coordinate value

z

z cartesian coordinate value

class astropysics.coords.coordsys.RectangularGCRSCoordinates(x, y, z, epoch=None, unit='pc')

Rectangular coordinates aligned to the GCRS with origin at the Earth geocenter. The positive z-axis points to the north celestial pole and the positive x-axis points down the (0,0) point of the equatorial GCRS (and thus, also ICRS).

The coordinates at this location are actually an “Astrometric place” - the actual location relative to the geocenter. This is disctinct from GCRSCoordinates in that GCRSCoordinates includes aberration and light deflection, while RectangularGCRSCoordinates does not.

Note

Units for the coordinates are specified via the unit attribute. When converting from GCRSCoordinates, distances default to AU if less than 1000 AU, otherwise, pc. If a distance is not present, the default distance is 1 (unspecified unit).

julianepoch = True
transformToEpoch(newepoch)
unit

The unit for these coordinates. Must be ‘au’, ‘pc’, or None - setting to anything else will raise a ValueError. If not None, setting to a new unit will convert the values from AU to pc or vice versa.

class astropysics.coords.coordsys.RectangularGeocentricEclipticCoordinates(x, y, z, epoch=None)

Rectangular coordinates oriented so that the x-y plane lies in the plane of the ecliptic at the specified epoch. Distances are in AU. Origin is at the center of mass of the Earth.

Note that the epoch should not be set directly - if precession is desired desired, convert to an Ecliptic coordinate system, do the precession, and convert back.

julianepoch = True
transformToEpoch(newepoch)
class astropysics.coords.coordsys.RectangularICRSCoordinates(x, y, z, epoch=None, unit='pc')

Rectangular coordinates aligned to the ICRS with origin at the solar system barycenter. The positive z-axis points to the north celestial pole and the positive x-axis is along with the (0,0) point of the equatorial ICRS.

Note

Units for the coordinates are specified via the unit attribute. When converting from ICRSCoordinates, distances default to AU if less than 1000 AU, otherwise, pc. If a distance is not present, the default distance is 1 (unspecified unit).

julianepoch = True
transformToEpoch(newepoch)
unit

The unit for these coordinates. Must be ‘au’, ‘pc’, or None - setting to anything else will raise a ValueError. If not None, setting to a new unit will convert the values from AU to pc or vice versa.

class astropysics.coords.coordsys.SupergalacticCoordinates(long=0, lat=0, longerr=None, laterr=None, epoch=None, distancepc=None)

See the associated attribute docstrings for the meaning of the inputs.

sgb

Latitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

sgberr

Latitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

sgl

Longitude of this object as a AngularCoordinate object. May be set using any valid input form for AngularCoordinate.

sglerr

Longitude error for this object as a AngularSeparation object. May be set using any valid input form for AngularSeparation.

transformToEpoch(newepoch)

Supergalactic coordinates are nominally inertial, although the definition is a bit unclear in that regard.

astropysics.coords.coordsys.angular_string_to_dec(instr, hms=True, degrees=True)

Convinience function to convert a angular coordinate string to a decimal value.

Parameters: hms (boolean) – If True, the coordinate will be assumed to be h:m:s, otherwise d:m:s. This will be ignored if the coordinates are specified as ##h##m##s or ##d##m##s, or if the input is not in sexigesimal form. degrees (boolean) – If True, the output will be decimal degrees, otherwise radians. Decimal value in radians or degrees
astropysics.coords.coordsys.objects_to_coordinate_arrays(posobjs, coords='auto', degrees=True)

converts a sequence of position objects into an array of coordinates.

coords determines the order of the output coordinates - it can be a comma-seperated list of coordinate names or if ‘auto’, it will be ‘lat,long’ for all coordinate systems except for Equatorial, which will use ‘ra,dec’

if degrees is True, returned arrays are in degrees, otherwise radians

coords.ephems – ephemerides and proper motions¶

This module contains tools and utilities for computing ephemerides and physical locations of solar system objects, as well as proper motion calculations for extrasolar objects.

Pyephem
A Pythonic implementation of the xephem ephemerides algorithms.
Meeus, Jean H. “Astronomical Algorithms” ISBN 0943396352
An authoritative reference on coordinates, ephemerides, and related transforms in astronomy.
JPL Solar System Dynamics Group
The standard source for solar system dynamics and ephemerides. Source of DE200 and DE405 solar system models, and HORIZON ephemerides service.

Todo

Tutorials

Module API¶

class astropysics.coords.ephems.Earth

Earth position (and velocity) relative to solar system barycenter. Adapted from SOFA fits generated from DE405 solar system model. Outputs astropysics.coords.coordsys.RectangularICRSCoordinates objects.

getVelocity(jd=None, kms=True)

Computes and returns the velociy of the Earth relative to the solar system barycenter.

Params jd: Params bool kms: The julian date at which to compute the velocity, or None to use the jd attribute. If True, velocities are returned in km/s, otherwise AU/yr. vx,vy,vz in km/s if kms is True, otherwise AU/yr.
exception astropysics.coords.ephems.EphemerisAccuracyWarning

Bases: exceptions.Warning

Class for warnings due to Ephemeris accuracy issues

class astropysics.coords.ephems.EphemerisObject(name, validjdrange=None)

Bases: object

This class is the superclass of objects that change sky coordinates over time.

Subclassing

• Subclasses should implement the _getCoordObj() abstract method. This should return a astropysics.coords.coordsys.CoordinateSystem object of the coordinates for the current value of jd.
• Subclasses may implement a _jdhook() method to perform an action whenever the jd is changed. It must have a signature f(oldjd,newjd).
• Subclasses may implement the getVelocity() method to return instantaneous velocities for the coordinate at the current value of jd. If this is not implemented, calling it will raise a NotImplementedError.
Params name: Params validjdrange: The name of the object. Sets the jd range over which this method is valid as (minjd,maxjd). Trying to get something outside will result in an :exc:EphemerisAccuracyWarning warning. minjd or maxjd can be None to indicate no bound.
getVelocity()

Computes and returns the instantaneous velocity for this object at the time given by the jd attribute’s value.

Returns: Raises NotImplementedError: The current velocity of this object. The exact type is not specified, but it should be something that can be added to the coordinates that are returned when the object is called. If velocities are not implemented for this class.
jd

Julian Date at which to calculate the orbital elements. Can be set either as a scalar JD, ‘now’, datetime.datetime object or a compatible tuple.

name = ''

The name of the object.

validjdrange

The range of jds over which these ephemerides are valid. Returns a 2-tuple (minjd,maxjd), either of which can be None to indicate no bound.

class astropysics.coords.ephems.KeplerianObject(**kwargs)

An object with Keplerian orbital elements.

The following orbital elements are available for the current value of jd as read-only properties:

Keywords should be the names of orbital elements. Orbital elements can be a callable f(T) that returns the orbital element, where T is the Julian century from J2000. Otherwise, it must be a sequence giving polynomial coefficients of T, specified in increasing power (i.e. constant term first).

The orbital elements a,:attr:e, i, and Lan must be specified, as must either L and Lp or ap and M

Three additional keywords can be supplied:

Params outcoords:
The coordinate class that should be used as the output. Should be a astropysics.coords.coordsys.CartesianCoordinates subclass, and the origin will be taken as the center of the Keplerian orbit. Defaults to astropysics.coords.coordsys.RectangularCoordinates.
Params outtransfunc:
A function that maps the coordinates from the standard coordinate system (where the x-y plane is the plane of reference) to a system matching the type specified by outcoords. The function should have the signature f(x,y,z,jd) and return (xp,yp,zp). It can also be None to perform no trasnformation. Defaults to None.
Params Etol:Tolerance for eccentric anomaly (see Etol). Defaults to None.

Any other keywords will be passed into the constructor for EphemerisObject.

Raises TypeError:
If necessary orbital elements are missing.
E

Eccentric anamoly in degrees - calculated from mean anamoly with accuracy given by Etol.

Etol = None

Desired accuracy for iterative calculation of eccentric anamoly (or true anomaly) from mean anomaly. If None, default tolerance is used (1.5e-8), or if 0, an analytic approximation will be used (). This approximation can be 10x faster to compute but fails for e close to 1.

L

The mean longitude in degrees.

Lan

The longitude of the ascending node in degrees.

Lp

The longitude of the pericenter in degrees.

M

The mean anomaly in degrees.

P

Orbital period (if gravitational parameter GM=1).

a

The semi-major axis.

ap

The argument of the pericenter in degrees.

d

Current distance from focus of attraction to object.

dapo

Distance from focus of attraction at apocenter.

dperi

Distance from focus of attraction at pericenter.

e

getPhase(viewobj='Earth', illumobj='Sun')

Computes the phase of this object. The phase is computed as viwed from viewobj if illuminated by illumobj

Parameters: viewobj – The object viewing this object. Either a string with the name of a solar system object (from the list in list_solar_system_objects()), or a EphemerisObject object. If None, it is taken to be the coordinate origin. viewobj – The object illuminating this object. Either a string with the name of a solar system object (from the list in list_solar_system_objects()), or a EphemerisObject object. If None, it is taken to be the coordinate origin. The phase of the object as a float where 0 is new and 1 is full.
i

The orbital inclination in degrees.

nu

True anamoly in degrees () - calculated from eccentric anamoly with accuracy given by Etol.

class astropysics.coords.ephems.Moon

A KeplerianObject for Earth’s moon based on the model of Simon et al. 1994. The osculating elements for the “1992 values” are used to compute the location. The output coordinates are astropysics.coords.coordsys.RectangularGCRSCoordinates.

getPhase(viewobj=None, illumobj=None)

Computes the phase of the Moon. This is computed as viewed from the Earth and illuminated by the Sun if viewobj and illumobj are None - otherwise, see KeplerianObject.getPhase() for the meaning of the parameters.

Returns: A float where 1 is full and 0 is new.
class astropysics.coords.ephems.ProperMotionObject(name, ra0, dec0, dra=0, ddec=0, epoch0=2000, distpc0=None, rv=0, coordclass=None)

An object with linear proper motion relative to a specified epoch.

Parameters: name (str) – Name of the object. ra0 (float) – RA in degrees at the starting epoch. dec0 (float) – Dec in degrees at the starting epoch. dra (float) – Change in RA, arcsec/yr. ddec (float) – Proper motion in Dec, arcsec/yr. epoch0 – Epoch for which ra0,dec0,anddistpc0 are valid. distpc0 – Distance in pc at the starting epoch. rv (float) – Radial velocity in km/s coordclass (astropysics.coords.coordsys.EpochalLatLongCoordinates) – The type of output coordinates. If None, defaults to ICRSCoordinates.
dec

Declination at the current jd in degrees.

distancepc

Distance at the current jd in parsecs.

drastar

Proper motion in right ascention in arcseconds. This is distinguished from dra in that it is multiplied by cos(dec0) to produce a true proper motion component.

ra

RA at the current jd in degrees.

astropysics.coords.ephems.earth_pos_vel(jd, barycentric=False, kms=True)

Computes the earth’s position and velocity at a given julian date.

Output coordinates are aligned to GCRS/ICRS so that +z is along the spherical GCRS pole and +x points down the spherical GCRS origin.

Adapted from SOFA function epv00.c from fits to DE405, valid from ~ 1900-2100.

Parameters: jd – The julian date for the positions and velocities. barycentric (bool) – If True, the output positions and velocities are relative to the solar system barycenter. Otherwise, positions and velocities are heliocentric. kms (bool) – If True, velocity outputs are in km/s, otherwise AU/yr. 2 3-tuples (x,y,z),(vx,vy,vz) where x,y, and z are GCRS-aligned positions in AU, and vx,vy, and vz are velocities in km/s if kms is True, or AU/yr.
astropysics.coords.ephems.get_solar_system_ephems(objname, jds=None, coordsys=None)

Retrieves an EphemerisObject object or computes the coordinates for a solar system object.

Parameters: objname (str) – The (case-sensitive) name of the object (see list_solar_system_objects() for valid names) jds – The jds at which to compute the coordinates or None to return EphemerisObject instances. coordsys – Specifies the coordinate system class of the returned ephemerides. See EphemerisObject.__call__() for the details. Ignored if jds is None. A subclass of EphemerisObject if jds is None, or the appropriate coordinate object (or objects) as detailed in EphemerisObject.__call__() if jds is not None.
astropysics.coords.ephems.list_solar_system_objects()

Returns a list of objects that can be returned by get_solar_system_object().

astropysics.coords.ephems.set_solar_system_ephem_method(meth=None)

Sets the type of ephemerides to use. Must be ‘keplerian’ for now.

coords.funcs – coordinate and distance utility functions¶

This module contains functions for coordinate transforms and coordinate system calculations. It also includes distance-related calculations, including distances in expanding cosmologies.

Module API¶

astropysics.coords.funcs.angular_to_physical_size(angsize, zord, usez=False, **kwargs)

Converts an observed angular size (in arcsec or as an AngularSeparation object) to a physical size.

Parameters: angsize (float or an AngularSeparation object) – Angular size in arcsecond. zord (scalar number) – Redshift or distance usez (boolean) – If True, the input will be interpreted as a redshift, and kwargs will be passed into the distance calculation. The result will be in pc. Otherwise, zord will be interpreted as a distance.

kwargs are passed into cosmo_z_to_dist() if usez is True.

Returns: A scalar value for the physical size (in pc if redshift is used, otherwise in zord units)
astropysics.coords.funcs.cartesian_to_cylindrical(x, y, z, degrees=False)

Converts three arrays in 3D rectangular Cartesian coordinates to cylindrical polar coordinates.

Parameters: x (float or array-like) – x cartesian coordinate y (float or array-like) – y cartesian coordinate z (float or array-like) – z cartesian coordinate degrees (bool) – If True, the output angles will be in degrees, otherwise radians. Cylindrical coordinates as a (rho,theta,z) tuple (theta increasing from +x to +y, 0 at x-axis).
astropysics.coords.funcs.cartesian_to_polar(x, y, degrees=False)

Converts arrays in 2D rectangular Cartesian coordinates to polar coordinates.

Parameters: x (numpy.ndarray) – First cartesian coordinate y (numpy.ndarray) – Second cartesian coordinate degrees (boolean) – If True, the output theta angle will be in degrees, otherwise radians. (r,theta) where theta is measured from the +x axis increasing towards the +y axis
astropysics.coords.funcs.cartesian_to_spherical(x, y, z, degrees=False)

Converts three arrays in 3D rectangular cartesian coordinates to spherical polar coordinates.

Note that the spherical coordinates are in physicist convention such that (1,0,pi/2) is x-axis.

Parameters: x (numpy.ndarray) – First cartesian coordinate y (numpy.ndarray) – Second cartesian coordinate z (numpy.ndarray) – Third cartesian coordinate degrees (boolean) – If True, the output theta angle will be in degrees, otherwise radians. arrays (r,theta,phi)
astropysics.coords.funcs.colatitude_to_latitude(theta, degrees=False)

Converts from colatitude/inclination (i.e. “theta” in physicist convention) to latitude (i.e. 0 at the equator).

Parameters: theta (float or array-like) – input colatitude degrees (bool) – If True, the input is interpreted as degrees, otherwise radians. latitude
astropysics.coords.funcs.cosmo_dist_to_z(d, derr=None, disttype=0, inttol=1e-06, normed=False, intkwargs={})

Convert a distance to a redshift. See cosmo_z_to_dist() for meaning of parameters. Note that if d is None, the maximum distance will be returned.

astropysics.coords.funcs.cosmo_z_to_H(z, zerr=None)

Calculates the hubble constant as a function of redshift for the current astropysics.constant.Cosmology .

Parameters: z (scalar or array-like) – redshift zerr (scalar, array-like, or None) – uncertainty in redshift Hubble constant for the given redshift, or (H,upper_error,lower_error) if zerr is not None
astropysics.coords.funcs.cosmo_z_to_dist(z, zerr=None, disttype=0, inttol=1e-06, normed=False, intkwargs={})

Calculates the cosmolgical distance to some object given a redshift. Note that this uses H0,omegaM,omegaL, and omegaR from the current astropyscs.constants.Cosmology – if any of those do not exist in the current cosmology this will fail.

The distance type can be one of the following:

• ‘comoving’(0) : comoving distance (in Mpc)
• ‘luminosity’(1) : luminosity distance (in Mpc)
• ‘angular’(2) : angular diameter distance (in Mpc)
• ‘lookback’(3) : lookback time (in Gyr)
• ‘distmod’(4) : distance modulus
Parameters: z (array, scalar, or None) – The redshift at which to compute the distance, or None to compute the maximum value for this distance (for luminosity and distmod this is infinite) zerr (array, scalar, or None) – Symmetric error in redshift disttype (A string or int) – The type of distance to compute – may be any of the types described above. inttol (A float<1) – fractional precision of the output (used in integrals) normed (boolean) – If True, normalize output by result for z == None. If a scalar, normalize by the distance at that redshift. If False, no normalization. intkwargs (a dictionary) – keywords for integrals (see scipy.integrate) Distance of type selected by disttype in above units or normalized as controlled by normed parameter. If zerr is not None, the output is (z,zupper,zlower), otherwise just z.

Examples

In these examples we are assuming the WMAP7 BAOH0 cosmological parameters.

>>> from astropysics.constants import choose_cosmology
>>> cosmo = choose_cosmology('wmap7baoh0')

>>> '%.6f'%cosmo_z_to_dist(0.03)
'126.964723'
>>> '%.6f'%cosmo_z_to_dist(0.2)
'815.469170'
>>> '%.6f'%cosmo_z_to_dist(0.2,disttype=1)
'978.563004'
>>> '%.6f'%cosmo_z_to_dist(0.2,disttype='luminosity')
'978.563004'
>>> '%.6f'%cosmo_z_to_dist(0.2,disttype='angular')
'679.557642'
>>> '%.3f'%cosmo_z_to_dist(1,disttype='lookback')
'7.789'
>>> '%.2f'%cosmo_z_to_dist(0.5,disttype='distmod')
'42.27'
>>> '%.6f'%cosmo_z_to_dist(0.2,disttype='angular',normed=True)
'0.382326'
>>> '%.6f'%cosmo_z_to_dist(0.8,disttype='angular',normed=True)
'0.879027'
>>> '%.6f'%cosmo_z_to_dist(1.64,disttype='angular',normed=True)
'1.000000'
>>> '%.6f'%cosmo_z_to_dist(2.5,disttype='angular',normed=True)
'0.956971'

astropysics.coords.funcs.cylindrical_to_cartesian(s, t, z, degrees=False)

Converts three arrays in cylindrical polar coordinates to 3D rectangular Cartesian coordinates.

Parameters: s (float or array-like) – radial polar coordinate t (float or array-like) – polar angle (increasing from +x to +y, 0 at x-axis) z (float or array-like) – z coordinate degrees (bool) – If True, the output angles will be in degrees, otherwise radians. Cartesian coordinates as an (x,y,z) tuple.
astropysics.coords.funcs.earth_rotation_angle(jd, degrees=True)

Earth Rotation Angle (ERA) for a given Julian Date.

Parameters: jd (scalar or array-like) – The Julian Date or a sequence of JDs degrees (bool or None) – If True, the ERA is returned in degrees, if None, 1=full rotation. Otherwise, radians. ERA or an array of angles (if jd is an array)
astropysics.coords.funcs.equation_of_the_equinoxes(jd)

Computes equation of the equinoxes GAST-GMST. That is, the difference between GMT computed using the mean equinox instead of the true equinox (i.e. including nutation).

Parameters: jd (scalar or array-like) – The Julian Date or a sequence of JDs. the equation of the equinoxes for the provided date in hours.
astropysics.coords.funcs.equation_of_the_origins(jd)

Computes the equation of the origins ERA - GAST (ERA = Earth Rotation Angle, GAST = Greenwich Apparent Sidereal Time). This quantity is also the difference in RA between the Celestial Intermediate Origin and the Equinox.

Parameters: jd (scalar or array-like) – The Julian Date or a sequence of JDs. the equation of the origins for the provided date in hours.
astropysics.coords.funcs.geocentric_to_geographic_latitude(geoclat)

Converts a geocentric latitude to a geographic/geodetic latitude.

Parameters: geoclat – An astropysics.coords.AngularCoordinate object (or arguments to create one) or an angle in degrees for the geocentric latitude. An astropysics.coords.AngularCoordinate object with the geographic latitude.
astropysics.coords.funcs.geographic_to_geocentric_latitude(geoglat)

Converts a geographic/geodetic latitude to a geocentric latitude.

Parameters: geoglat – An astropysics.coords.AngularCoordinate object (or arguments to create one) or an angle in degrees for the geographic latitude. An astropysics.coords.AngularCoordinate object with the geocentric latitude.
astropysics.coords.funcs.greenwich_sidereal_time(jd, apparent=True)

Computes the Greenwich Sidereal Time for a given Julian Date.

Parameters: jd (scalar or array-like) – The Julian Date or a sequence of JDs, UT1 apparent – If True, the Greenwich Apparent Sidereal Time (GAST) is returned, using the method in the SOFA function iauGst00b, which computes nutation from the IAU 2000B nutation model, leaves out complementary terms in the equation of the equinox and uses UT1 instead of TT in the expression for GMST. In the special case that ‘simple’ is given, a faster (but much lower precision) nutation model will be used. If False, the Greenwich Mean Sidereal Time (GMST) is returned, instead. GMST or GAST in hours or an array of times (if jd is an array)

equation_of_the_equinoxes(), USNO Circular 179, http://www.usno.navy.mil/USNO/astronomical-applications/astronomical-information-center/approx-sider-time, IERS Technical Note No. 32 (esp. 5.10 Method (2B)), and SOFA functions iauGmst00 and iauGst00b

astropysics.coords.funcs.latitude_to_colatitude(lat, degrees=False)

converts from latitude (i.e. 0 at the equator) to colatitude/inclination (i.e. “theta” in physicist convention).

astropysics.coords.funcs.match_coords(a1, b1, a2, b2, eps=1, mode='mask')

Match one pair of coordinate arrays to another within a specified tolerance (eps).

Distance is determined by the cartesian distance between the two arrays, implying the small-angle approximation if the input coordinates are spherical. Units are arbitrary, but should match between all coordinates (and eps should be in the same units)

Parameters: a1 (array-like) – the first coordinate for the first set of coordinates b1 (array-like) – the second coordinate for the first set of coordinates a2 (array-like) – the first coordinate for the second set of coordinates b2 (array-like) – the second coordinate for the second set of coordinates eps (float) – The maximum separation allowed for coordinate pairs to be considered matched. mode – Determines behavior if more than one coordinate pair matches. Can be: ‘mask’ Returns a 2-tuple of boolean arrays (mask1,mask2) where mask1 matches the shape of the first coordinate set (a1 and b1), and mask2 matches second set (a2 and b2). The mask value is True if a match is found for that coordinate pair, otherwise, False. ‘maskexcept’ Retuns the same values as ‘mask’, and will raise an exception if more than one match is found. ‘maskwarn’ Retuns the same values as ‘mask’, and a warning will be issued if more than one match is found. ‘count’ Returns a 2-tuple (nmatch1,nmatch2) with the number of objects that matched for each of the two sets of coordinate systems. ‘index’ Returns a 2-tuple of integer arrays (ind1,ind2). ind1 is a set of indecies into the first coordinate set, and ind2 indexes the second. The two arrays match in shape and each element is the index for a matched pair of coordinates - e.g. a1[ind1[i]] and a2[ind2[i]] will give the “a” coordinate for a matched pair of coordinates. ‘match2D’ Returns a 2-dimensional bool array. The array element M[i,j] is True if the ith coordinate of the first coordinate set matches the jth coordinate of the second set. ‘nearest’ Returns (nearestind,distance,match). nearestind is an int array such that nearestind holds indecies into the second set of coordinates for the nearest object to the ith object in the first coordinate set (hence, it’s shape matches the first coordinate set). distance is a float array of the same shape giving the corresponding distance, and match is a boolean array that is True if the distance is within eps, and is the same shape as the other outputs. Note that if a1 and b1 are the same object (and a2 and b2), this finds the second-closest match (because the first will always be the object itself if the coordinate pairs are the same) This mode is a wrapper around match_nearest_coords(). See mode for a description of return types.

Examples

>>> from numpy import array
>>> ra1 = array([1,2,3,4])
>>> dec1 = array([0,0,0,0])
>>> ra2 = array([4,3,2,1])
>>> dec2 = array([3.5,2.5,1.5,.5])
>>> match_coords(ra1,dec1,ra2,dec2,1)
(array([ True, False, False, False], dtype=bool), array([False, False, False,  True], dtype=bool))

astropysics.coords.funcs.match_nearest_coords(c1, c2=None, n=None)

Match a set of coordinates to their nearest neighbor(s) in another set of coordinates.

Parameters: c1 – A D x N array with coordinate values (either as floats or AngularPosition objects) or a sequence of LatLongCoordinates objects for the first set of coordinates. c2 – A D x N array with coordinate values (either as floats or AngularPosition objects) or a sequence of LatLongCoordinates objects for the second set of coordinates. Alternatively, if this is None, c2 will be set to c1, finding the nearest neighbor of a point in c1 to another point in c1. n (int) – Specifies the nth nearest neighbor to be returned (1 means the closest match). If None, it will default to 2 if c1 and c2 are the same object (just equality is not enough - they must actually be the same in-memory array), or 1 otherwise. This is because if c1 and c2 are the same, a coordinate matches to itself instead of the nearest other coordinate. (seps,ind2) where both are arrays matching the shape of c1. ind2 is indecies into c2 to find the nearest to the corresponding c1 coordinate, and seps are the distances.
astropysics.coords.funcs.obliquity(jd, algorithm=2006)

Computes the obliquity of the Earth at the requested Julian Date.

Parameters: jd (scalar or array-like) – julian date at which to compute obliquity algorithm (int) – Year of algorithm based on IAU adoption. Can be 2006, 2000 or 1980. The 2006 algorithm is mentioned in Circular 179, but the canonical reference for the IAU adoption is apparently Hilton et al. 06 is composed of the 1980 algorithm with a precession-rate correction due to the 2000 precession models, and a description of the 1980 algorithm can be found in the Explanatory Supplement to the Astronomical Almanac. mean obliquity in degrees (or array of obliquities)

• Hilton, J. et al., 2006, Celest.Mech.Dyn.Astron. 94, 351. 2000
• USNO Circular 179
• Explanatory Supplement to the Astronomical Almanac: P. Kenneth Seidelmann (ed), University Science Books (1992).
astropysics.coords.funcs.offset_proj_sep(rx, ty, pz, offset, spherical=False)

computes the projected separation for a list of points in galacto-centric coordinates as seen from a point offset (an [[x,y,z]] 2-sequence)

spherical determines if the inputs are spherical coords or cartesian. If it is ‘degrees’, spherical coordinates will be used, converting from degrees to radians

astropysics.coords.funcs.physical_to_angular_size(physize, zord, usez=True, objout=False, **kwargs)

Converts a physical size (in pc) to an observed angular size (in arcsec or as an AngularSeparation object if objout is True)

if usez is True, zord is interpreted as a redshift, and cosmo_z_to_dist is used to determine the distance, with kwargs passed into cosmo_z_to_dist otherwise, zord is taken directly as a angular diameter distance (in pc) and kwargs should be absent

Parameters: physize (float) – Physical size in pc zord (scalar number) – Redshift or distance usez (boolean) – If True, the input will be interpreted as a redshift, and kwargs will be passed into the distance calculation. The result will be in pc. Otherwise, zord will be interpreted as a distance. objout – If True, return value is an AngularSeparation object, otherwise, angular size in arcsec. bool

kwargs are passed into cosmo_z_to_dist() if usez is True.

Returns: The angular size in acsec, or an AngularSeparation object if objout is True.
astropysics.coords.funcs.polar_to_cartesian(r, t, degrees=False)

Converts arrays in 2D polar coordinates to rectangular cartesian coordinates.

Note that the spherical coordinates are in physicist convention such that (1,0,pi/2) is x-axis.

Parameters: r (numpy.ndarray) – Radial coordinate t (numpy.ndarray) – Azimuthal angle from +x-axis increasing towards +y-axis degrees (boolean) – If True, the input angles will be in degrees, otherwise radians. arrays (x,y)

Convert a sequence of string coordinate specifiers to decimal degree arrays.

Two input forms are accepted:

In this form, rastrs and decstrs are sequences of strings with the RA and Dec, respectively.

In this form, radecstrs is a sequence of strings in any form accepted by the EquatorialCoordinatesBase constructor. (typically canonical from like 17:43:54.23 +32:23:12.3)

Returns: (ras,decs) where ras and decs are ndarrays specifying the ra and dec in decimal degrees.
astropysics.coords.funcs.separation_matrix(v, w=None, tri=False)

Computes a matrix of the separation between each of the components of the first dimension of an array. That is, A[i,j] = v[i]-w[j].

Parameters: v – The first array with first dimension n w – The second array with first dimension m, and all following dimensions matched to v. If None, v will be treated as w (e.g. the separation matrix of v with itself will be returned). tri (bool) – If True, the lower triangular part of the matrix is set to 0 (this is really only useful if w is None) Separation matrix with dimension nXmX(whatever the remaining dimensions are)

scipy.spatial.distance, in particular the scipy.spatial.distance.pdist() function. It is much more efficient and flexible at computing distances if individual components and sign information is unnecessary.

astropysics.coords.funcs.sky_sep_to_3d_sep(pos1, pos2, d1, d2)

Compute the full 3D separation between two objects at distances d1 and d2 and angular positions pos1 and pos2 (LatLongCoordinates objects, or an argument that will be used to generate a EquatorialCoordinatesEquinox object)

Parameters: pos1 (LatLongCoordinates or initializer) – on-sky position of first object pos2 (LatLongCoordinates or initializer) – on-sky position of second object d1 (scalar) – distance to first object d2 (scalar) – distance to second object
>>> from coordsys import LatLongCoordinates
>>> p1 = LatLongCoordinates(0,0)
>>> p2 = LatLongCoordinates(0,10)
>>> '%.10f'%sky_sep_to_3d_sep(p1,p2,20,25)
'6.3397355613'
>>> '%.10f'%sky_sep_to_3d_sep('0h0m0s +0:0:0','10:20:30 +0:0:0',1,2)
'2.9375007333'

astropysics.coords.funcs.spherical_to_cartesian(r, t, p, degrees=False)

Converts arrays in 3D spherical polar coordinates to rectangular cartesian coordinates.

Note that the spherical coordinates are in physicist convention such that (1,0,pi/2) is x-axis.

Parameters: r (numpy.ndarray) – Radial coordinate t (numpy.ndarray) – Colatitude (angle from z-axis) p (numpy.ndarray) – Azimuthal angle from +x-axis increasing towards +y-axis degrees (boolean) – If True, the input angles will be in degrees, otherwise radians. arrays (x,y,z)