INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Convert to an ISO 8601 string like ``2014-01-18T01:35:38Z`` in UTC.
If this time is an array of dates, then a sequence of strings is
returned instead of a single string. | def utc_iso(self, delimiter='T', places=0):
"""Convert to an ISO 8601 string like ``2014-01-18T01:35:38Z`` in UTC.
If this time is an array of dates, then a sequence of strings is
returned instead of a single string.
"""
# "places" used to be the 1st argument, so continue to al... |
Convert to an ``A.D. 2014-Jan-18 01:35:37.5000 UT`` string.
Returns a string for this date and time in UTC, in the format
used by the JPL HORIZONS system. If this time is an array of
dates, then a sequence of strings is returned instead of a
single string. | def utc_jpl(self):
"""Convert to an ``A.D. 2014-Jan-18 01:35:37.5000 UT`` string.
Returns a string for this date and time in UTC, in the format
used by the JPL HORIZONS system. If this time is an array of
dates, then a sequence of strings is returned instead of a
single string.... |
Format the UTC time using a Python date formatting string.
This internally calls the Python ``strftime()`` routine from the
Standard Library ``time()`` module, for which you can find a
quick reference at ``http://strftime.org/``. If this object is
an array of times, then a sequence of ... | def utc_strftime(self, format):
"""Format the UTC time using a Python date formatting string.
This internally calls the Python ``strftime()`` routine from the
Standard Library ``time()`` module, for which you can find a
quick reference at ``http://strftime.org/``. If this object is
... |
Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below. | def _utc_year(self):
"""Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below.
"""
d = self._utc_float() - 1721059.5
#d += offset
C = 365 * 100 + 24
d -= 365
d += d // C - d // (4 * C... |
Return UTC as (year, month, day, hour, minute, second.fraction).
The `offset` is added to the UTC time before it is split into
its components. This is useful if the user is going to round
the result before displaying it. If the result is going to be
displayed as seconds, for example, ... | def _utc_tuple(self, offset=0.0):
"""Return UTC as (year, month, day, hour, minute, second.fraction).
The `offset` is added to the UTC time before it is split into
its components. This is useful if the user is going to round
the result before displaying it. If the result is going to b... |
Return UTC as a floating point Julian date. | def _utc_float(self):
"""Return UTC as a floating point Julian date."""
tai = self.tai
leap_dates = self.ts.leap_dates
leap_offsets = self.ts.leap_offsets
leap_reverse_dates = leap_dates + leap_offsets / DAY_S
i = searchsorted(leap_reverse_dates, tai, 'right')
ret... |
DEPRECATED: See stars.rst for how to load a star catalog. | def NamedStar(name):
"""DEPRECATED: See stars.rst for how to load a star catalog."""
try:
hid = named_star_dict[name]
return hipparcos.get(str(hid))
except KeyError:
raise ValueError("No star named {0} known to skyfield.".format(name)) |
Compute the position and velocity of a terrestrial observer.
`latitude` - Latitude in radians.
`longitude` - Longitude in radians.
`elevation` - Elevation above sea level in au.
`gast` - Hours of Greenwich Apparent Sidereal Time (can be an array).
The return value is a tuple of two 3-vectors `(pos... | def terra(latitude, longitude, elevation, gast):
"""Compute the position and velocity of a terrestrial observer.
`latitude` - Latitude in radians.
`longitude` - Longitude in radians.
`elevation` - Elevation above sea level in au.
`gast` - Hours of Greenwich Apparent Sidereal Time (can be an array).... |
Convert a geocentric (x,y,z) at time `t` to latitude and longitude.
Returns a tuple of latitude, longitude, and elevation whose units
are radians and meters. Based on Dr. T.S. Kelso's quite helpful
article "Orbital Coordinate Systems, Part III":
https://www.celestrak.com/columns/v02n03/ | def reverse_terra(xyz_au, gast, iterations=3):
"""Convert a geocentric (x,y,z) at time `t` to latitude and longitude.
Returns a tuple of latitude, longitude, and elevation whose units
are radians and meters. Based on Dr. T.S. Kelso's quite helpful
article "Orbital Coordinate Systems, Part III":
ht... |
Determine the angle of an object above or below the Earth's limb.
Given an object's GCRS `position_au` [x,y,z] vector and the position
of an `observer_au` as a vector in the same coordinate system,
return a tuple that provides `(limb_ang, nadir_ang)`:
limb_angle
Angle of observed object above ... | def compute_limb_angle(position_au, observer_au):
"""Determine the angle of an object above or below the Earth's limb.
Given an object's GCRS `position_au` [x,y,z] vector and the position
of an `observer_au` as a vector in the same coordinate system,
return a tuple that provides `(limb_ang, nadir_ang)`... |
Compute Greenwich sidereal time at the given ``Time``. | def sidereal_time(t):
"""Compute Greenwich sidereal time at the given ``Time``."""
# Compute the Earth Rotation Angle. Time argument is UT1.
theta = earth_rotation_angle(t.ut1)
# The equinox method. See Circular 179, Section 2.6.2.
# Precession-in-RA terms in mean sidereal time taken from third... |
Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon. | def refraction(alt_degrees, temperature_C, pressure_mbar):
"""Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon.
"""
r = 0.016667 / tan((alt_degrees + ... |
Given an unrefracted `alt` determine where it will appear in the sky. | def refract(alt_degrees, temperature_C, pressure_mbar):
"""Given an unrefracted `alt` determine where it will appear in the sky."""
alt = alt_degrees
while True:
alt1 = alt
alt = alt_degrees + refraction(alt, temperature_C, pressure_mbar)
converged = abs(alt - alt1) <= 3.0e-5
... |
Return the rotation matrices for precessing to an array of epochs.
`jd_tdb` - array of TDB Julian dates
The array returned has the shape `(3, 3, n)` where `n` is the number
of dates that have been provided as input. | def compute_precession(jd_tdb):
"""Return the rotation matrices for precessing to an array of epochs.
`jd_tdb` - array of TDB Julian dates
The array returned has the shape `(3, 3, n)` where `n` is the number
of dates that have been provided as input.
"""
eps0 = 84381.406
# 't' is time in... |
Generate the nutation rotations for Time `t`.
If the Julian date is scalar, a simple ``(3, 3)`` matrix is
returned; if the date is an array of length ``n``, then an array of
matrices is returned with dimensions ``(3, 3, n)``. | def compute_nutation(t):
"""Generate the nutation rotations for Time `t`.
If the Julian date is scalar, a simple ``(3, 3)`` matrix is
returned; if the date is an array of length ``n``, then an array of
matrices is returned with dimensions ``(3, 3, n)``.
"""
oblm, oblt, eqeq, psi, eps = t._eart... |
Return a tuple of information about the earth's axis and position.
`t` - A Time object.
The returned tuple contains five items:
``mean_ob`` - Mean obliquity of the ecliptic in degrees.
``true_ob`` - True obliquity of the ecliptic in degrees.
``eq_eq`` - Equation of the equinoxes in seconds of tim... | def earth_tilt(t):
"""Return a tuple of information about the earth's axis and position.
`t` - A Time object.
The returned tuple contains five items:
``mean_ob`` - Mean obliquity of the ecliptic in degrees.
``true_ob`` - True obliquity of the ecliptic in degrees.
``eq_eq`` - Equation of the e... |
Return the mean obliquity of the ecliptic in arcseconds.
`jd_tt` - TDB time as a Julian date float, or NumPy array of floats | def mean_obliquity(jd_tdb):
"""Return the mean obliquity of the ecliptic in arcseconds.
`jd_tt` - TDB time as a Julian date float, or NumPy array of floats
"""
# Compute time in Julian centuries from epoch J2000.0.
t = (jd_tdb - T0) / 36525.0
# Compute the mean obliquity in arcseconds. Use ... |
Compute the complementary terms of the equation of the equinoxes.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats | def equation_of_the_equinoxes_complimentary_terms(jd_tt):
"""Compute the complementary terms of the equation of the equinoxes.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
"""
# Interval between fundamental epoch J2000.0 and current date.
t = (jd_tt - T0) / 36525.0
... |
Compute Earth nutation based on the IAU 2000A nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each value is either a float, or a NumPy array
with the same dimensions as the ... | def iau2000a(jd_tt):
"""Compute Earth nutation based on the IAU 2000A nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each value is either a float, or a NumPy array
with... |
Compute the fundamental arguments (mean elements) of Sun and Moon.
`t` - TDB time in Julian centuries since J2000.0, as float or NumPy array
Outputs fundamental arguments, in radians:
a[0] = l (mean anomaly of the Moon)
a[1] = l' (mean anomaly of the Sun)
a[2] = F (mean argument ... | def fundamental_arguments(t):
"""Compute the fundamental arguments (mean elements) of Sun and Moon.
`t` - TDB time in Julian centuries since J2000.0, as float or NumPy array
Outputs fundamental arguments, in radians:
a[0] = l (mean anomaly of the Moon)
a[1] = l' (mean anomaly of the S... |
Compute Earth nutation based on the faster IAU 2000B nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each is either a float, or a NumPy array with
the same dimensions as the... | def iau2000b(jd_tt):
"""Compute Earth nutation based on the faster IAU 2000B nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each is either a float, or a NumPy array with
... |
DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead. | def parse(line):
"DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead."
# See ftp://cdsarc.u-strasbg.fr/cats/I/239/ReadMe
star = Star(
ra=Angle(degrees=float(line[51:63])),
dec=Angle(degrees=float(line[64:76])),
ra_mas_per_year=float(line[87:95]),
dec_mas... |
DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead. | def load(match_function):
"DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead."
from skyfield import api
with api.load.open(url) as f:
for line in gzip.GzipFile(fileobj=f):
if match_function(line):
yield parse(line) |
Given an open file for `hip_main.dat.gz`, return a parsed dataframe.
If your copy of ``hip_main.dat`` has already been unzipped, pass the
optional argument ``compression=None``. | def load_dataframe(fobj, compression='gzip'):
"""Given an open file for `hip_main.dat.gz`, return a parsed dataframe.
If your copy of ``hip_main.dat`` has already been unzipped, pass the
optional argument ``compression=None``.
"""
try:
from pandas import read_fwf
except ImportError:
... |
DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead. | def get(which):
"DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead."
if isinstance(which, str):
pattern = ('H| %6s' % which).encode('ascii')
for star in load(lambda line: line.startswith(pattern)):
return star
else:
patterns = set(id.encode('as... |
Compute the rotation from the ICRF into the alt-az system. | def _altaz_rotation(self, t):
"""Compute the rotation from the ICRF into the alt-az system."""
R_lon = rot_z(- self.longitude.radians - t.gast * tau / 24.0)
return einsum('ij...,jk...,kl...->il...', self.R_lat, R_lon, t.M) |
Compute the GCRS position and velocity of this Topos at time `t`. | def _at(self, t):
"""Compute the GCRS position and velocity of this Topos at time `t`."""
pos, vel = terra(self.latitude.radians, self.longitude.radians,
self.elevation.au, t.gast)
pos = einsum('ij...,j...->i...', t.MT, pos)
vel = einsum('ij...,j...->i...', t.MT,... |
Produce the osculating orbital elements for a position.
The ``position`` should be an :class:`~skyfield.positionlib.ICRF`
instance like that returned by the ``at()`` method of any Solar
System body, specifying a position, a velocity, and a time. An
instance of :class:`~skyfield.elementslib.OsculatingE... | def osculating_elements_of(position, reference_frame=None):
"""Produce the osculating orbital elements for a position.
The ``position`` should be an :class:`~skyfield.positionlib.ICRF`
instance like that returned by the ``at()`` method of any Solar
System body, specifying a position, a velocity, and a ... |
Return the angle of Greenwich Mean Standard Time 1982 given the JD.
This angle defines the difference between the idiosyncratic True
Equator Mean Equinox (TEME) frame of reference used by SGP4 and the
more standard Pseudo Earth Fixed (PEF) frame of reference.
From AIAA 2006-6753 Appendix C. | def theta_GMST1982(jd_ut1):
"""Return the angle of Greenwich Mean Standard Time 1982 given the JD.
This angle defines the difference between the idiosyncratic True
Equator Mean Equinox (TEME) frame of reference used by SGP4 and the
more standard Pseudo Earth Fixed (PEF) frame of reference.
From AI... |
Convert TEME position and velocity into standard ITRS coordinates.
This converts a position and velocity vector in the idiosyncratic
True Equator Mean Equinox (TEME) frame of reference used by the SGP4
theory into vectors into the more standard ITRS frame of reference.
The velocity should be provided i... | def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0):
"""Convert TEME position and velocity into standard ITRS coordinates.
This converts a position and velocity vector in the idiosyncratic
True Equator Mean Equinox (TEME) frame of reference used by the SGP4
theory into vectors into the more standard... |
Return the raw true equator mean equinox (TEME) vectors from SGP4.
Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
expressed in kilometers and kilometers per second. Note that we
assume the TLE epoch to be a UTC date, per AIAA 2006-6753. | def _position_and_velocity_TEME_km(self, t):
"""Return the raw true equator mean equinox (TEME) vectors from SGP4.
Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
expressed in kilometers and kilometers per second. Note that we
assume the TLE epoch to be a UTC date, per ... |
Return the ITRF position, velocity, and error at time `t`.
The position is an x,y,z vector measured in au, the velocity is
an x,y,z vector measured in au/day, and the error is a vector of
possible error messages for the time or vector of times `t`. | def ITRF_position_velocity_error(self, t):
"""Return the ITRF position, velocity, and error at time `t`.
The position is an x,y,z vector measured in au, the velocity is
an x,y,z vector measured in au/day, and the error is a vector of
possible error messages for the time or vector of tim... |
Compute this satellite's GCRS position and velocity at time `t`. | def _at(self, t):
"""Compute this satellite's GCRS position and velocity at time `t`."""
rITRF, vITRF, error = self.ITRF_position_velocity_error(t)
rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF)
return rGCRS, vGCRS, rGCRS, error |
Table of smoothed Delta T values from Morrison and Stephenson, 2004. | def morrison_and_stephenson_2004_table():
"""Table of smoothed Delta T values from Morrison and Stephenson, 2004."""
import pandas as pd
f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html')
tables = pd.read_html(f.read())
df = tables[0]
return pd.DataFrame({'year': df[0], 'delta_t': ... |
Given 2 vectors in `v` and `u`, return the angle separating them.
This works whether `v` and `u` each have the shape ``(3,)``, or
whether they are each whole arrays of corresponding x, y, and z
coordinates and have shape ``(3, N)``. The returned angle will be
between 0 and 180 degrees.
This formul... | def angle_between(u_vec, v_vec):
"""Given 2 vectors in `v` and `u`, return the angle separating them.
This works whether `v` and `u` each have the shape ``(3,)``, or
whether they are each whole arrays of corresponding x, y, and z
coordinates and have shape ``(3, N)``. The returned angle will be
bet... |
Convert ``[x y z]`` into spherical coordinates ``(r, theta, phi)``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three return values is designed to
match both ISO 31-11 and the traditional order used by p... | def to_polar(xyz):
"""Convert ``[x y z]`` into spherical coordinates ``(r, theta, phi)``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three return values is designed to
match both ISO 31-11 and the t... |
Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three polar parameters is designed to
match both ISO 31-11 and the traditional order used by ... | def from_polar(r, theta, phi):
"""Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``.
``r`` - vector length
``theta`` - angle above (+) or below (-) the xy-plane
``phi`` - angle around the z-axis
The meaning and order of the three polar parameters is designed to
match both ISO 31... |
Compute the star's position as an ICRF position and velocity. | def _compute_vectors(self):
"""Compute the star's position as an ICRF position and velocity."""
# Use 1 gigaparsec for stars whose parallax is zero.
parallax = self.parallax_mas
if parallax <= 0.0:
parallax = 1.0e-6
# Convert right ascension, declination, and paral... |
As a convenience, turn Python lists and tuples into NumPy arrays. | def _to_array(value):
"""As a convenience, turn Python lists and tuples into NumPy arrays."""
if isinstance(value, (tuple, list)):
return array(value)
elif isinstance(value, (float, int)):
return np.float64(value)
else:
return value |
Decompose `value` into units, minutes, and seconds.
Note that this routine is not appropriate for displaying a value,
because rounding to the smallest digit of display is necessary
before showing a value to the user. Use `_sexagesimalize_to_int()`
for data being displayed to the user.
This routin... | def _sexagesimalize_to_float(value):
"""Decompose `value` into units, minutes, and seconds.
Note that this routine is not appropriate for displaying a value,
because rounding to the smallest digit of display is necessary
before showing a value to the user. Use `_sexagesimalize_to_int()`
for data b... |
Decompose `value` into units, minutes, seconds, and second fractions.
This routine prepares a value for sexagesimal display, with its
seconds fraction expressed as an integer with `places` digits. The
result is a tuple of five integers:
``(sign [either +1 or -1], units, minutes, seconds, second_fract... | def _sexagesimalize_to_int(value, places=0):
"""Decompose `value` into units, minutes, seconds, and second fractions.
This routine prepares a value for sexagesimal display, with its
seconds fraction expressed as an integer with `places` digits. The
result is a tuple of five integers:
``(sign [eit... |
Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan' | def _hstr(hours, places=2):
"""Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan'
"""
if isnan(hours):
return 'nan'
sgn, h, m, s, etc = _sexagesimalize... |
r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan' | def _dstr(degrees, places=1, signed=False):
r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan'
... |
Return `value` after interpreting a (units, minutes, seconds) tuple.
When `value` is not a tuple, it is simply returned.
>>> _unsexagesimalize(3.25)
3.25
An input tuple is interpreted as units, minutes, and seconds. Note
that only the sign of `units` is significant! So all of the
following ... | def _unsexagesimalize(value):
"""Return `value` after interpreting a (units, minutes, seconds) tuple.
When `value` is not a tuple, it is simply returned.
>>> _unsexagesimalize(3.25)
3.25
An input tuple is interpreted as units, minutes, and seconds. Note
that only the sign of `units` is signi... |
Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. A pair of such
arguments can be passed to this routine for interp... | def _interpret_angle(name, angle_object, angle_float, unit='degrees'):
"""Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal... |
Interpret a string, float, or tuple as a latitude or longitude angle.
`value` - The string to interpret.
`name` - 'latitude' or 'longitude', for use in exception messages.
`positive` - The string that indicates a positive angle ('N' or 'E').
`negative` - The string that indicates a negative angle ('S' ... | def _interpret_ltude(value, name, psuffix, nsuffix):
"""Interpret a string, float, or tuple as a latitude or longitude angle.
`value` - The string to interpret.
`name` - 'latitude' or 'longitude', for use in exception messages.
`positive` - The string that indicates a positive angle ('N' or 'E').
`... |
Convert this distance to the given AstroPy unit. | def to(self, unit):
"""Convert this distance to the given AstroPy unit."""
from astropy.units import au
return (self.au * au).to(unit) |
Convert this velocity to the given AstroPy unit. | def to(self, unit):
"""Convert this velocity to the given AstroPy unit."""
from astropy.units import au, d
return (self.au_per_d * au / d).to(unit) |
Convert to a tuple (hours, minutes, seconds).
All three quantities will have the same sign as the angle itself. | def hms(self, warn=True):
"""Convert to a tuple (hours, minutes, seconds).
All three quantities will have the same sign as the angle itself.
"""
if warn and self.preference != 'hours':
raise WrongUnitError('hms')
sign, units, minutes, seconds = _sexagesimalize_to_fl... |
Convert to a tuple (sign, hours, minutes, seconds).
The ``sign`` will be either +1 or -1, and the other quantities
will all be positive. | def signed_hms(self, warn=True):
"""Convert to a tuple (sign, hours, minutes, seconds).
The ``sign`` will be either +1 or -1, and the other quantities
will all be positive.
"""
if warn and self.preference != 'hours':
raise WrongUnitError('signed_hms')
return... |
Convert to a string like ``12h 07m 30.00s``. | def hstr(self, places=2, warn=True):
"""Convert to a string like ``12h 07m 30.00s``."""
if warn and self.preference != 'hours':
raise WrongUnitError('hstr')
if self.radians.size == 0:
return '<Angle []>'
hours = self._hours
shape = getattr(hours, 'shape', ... |
Convert to a tuple (degrees, minutes, seconds).
All three quantities will have the same sign as the angle itself. | def dms(self, warn=True):
"""Convert to a tuple (degrees, minutes, seconds).
All three quantities will have the same sign as the angle itself.
"""
if warn and self.preference != 'degrees':
raise WrongUnitError('dms')
sign, units, minutes, seconds = _sexagesimalize_t... |
Convert to a tuple (degrees, hours, minutes, seconds).
The ``sign`` will be either +1 or -1, and the other quantities
will all be positive. | def signed_dms(self, warn=True):
"""Convert to a tuple (degrees, hours, minutes, seconds).
The ``sign`` will be either +1 or -1, and the other quantities
will all be positive.
"""
if warn and self.preference != 'degrees':
raise WrongUnitError('signed_dms')
r... |
Convert to a string like ``181deg 52\' 30.0"``. | def dstr(self, places=1, warn=True):
"""Convert to a string like ``181deg 52\' 30.0"``."""
if warn and self.preference != 'degrees':
raise WrongUnitError('dstr')
if self.radians.size == 0:
return '<Angle []>'
degrees = self._degrees
signed = self.signed
... |
Convert this angle to the given AstroPy unit. | def to(self, unit):
"""Convert this angle to the given AstroPy unit."""
from astropy.units import rad
return (self.radians * rad).to(unit)
# Or should this do:
from astropy.coordinates import Angle
from astropy.units import rad
return Angle(self.radians, rad).to(... |
Compute (alt, az, distance) relative to the observer's horizon. | def _to_altaz(position_au, observer_data, temperature_C, pressure_mbar):
"""Compute (alt, az, distance) relative to the observer's horizon.
"""
elevation_m = observer_data.elevation_m
R = observer_data.altaz_rotation
if (elevation_m is None) or (R is None):
raise ValueError('to compute an ... |
r"""Compute equatorial (RA, declination, distance)
When called without a parameter, this returns standard ICRF
right ascension and declination:
>>> ra, dec, distance = ICRF([1, 2, 3]).radec()
>>> print(ra, dec, distance, sep='\n')
04h 13m 44.39s
+53deg 18' 02.8"
... | def radec(self, epoch=None):
r"""Compute equatorial (RA, declination, distance)
When called without a parameter, this returns standard ICRF
right ascension and declination:
>>> ra, dec, distance = ICRF([1, 2, 3]).radec()
>>> print(ra, dec, distance, sep='\n')
04h 13m 44... |
Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1], [0,0,0,0]])
>>> directions.separation_from(... | def separation_from(self, another_icrf):
"""Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1],... |
Compute cartesian CIRS coordinates at a given epoch (x, y, z).
Calculate coordinates in the Celestial Intermediate Reference System
(CIRS), a dynamical coordinate system referenced to the Celestial
Intermediate Origin (CIO). As this is a dynamical system it must be
calculated at a speci... | def cirs_xyz(self, epoch):
"""Compute cartesian CIRS coordinates at a given epoch (x, y, z).
Calculate coordinates in the Celestial Intermediate Reference System
(CIRS), a dynamical coordinate system referenced to the Celestial
Intermediate Origin (CIO). As this is a dynamical system it... |
Get spherical CIRS coordinates at a given epoch (ra, dec, distance).
Calculate coordinates in the Celestial Intermediate Reference System
(CIRS), a dynamical coordinate system referenced to the Celestial
Intermediate Origin (CIO). As this is a dynamical system it must be
calculated at a... | def cirs_radec(self, epoch):
"""Get spherical CIRS coordinates at a given epoch (ra, dec, distance).
Calculate coordinates in the Celestial Intermediate Reference System
(CIRS), a dynamical coordinate system referenced to the Celestial
Intermediate Origin (CIO). As this is a dynamical s... |
Compute J2000 ecliptic position vector (x, y, z).
If you instead want the coordinates referenced to the dynamical
system defined by the Earth's true equator and equinox, provide
an epoch time. | def ecliptic_xyz(self, epoch=None):
"""Compute J2000 ecliptic position vector (x, y, z).
If you instead want the coordinates referenced to the dynamical
system defined by the Earth's true equator and equinox, provide
an epoch time.
"""
if epoch is None:
vect... |
Compute J2000 ecliptic velocity vector (x_dot, y_dot, z_dot) | def ecliptic_velocity(self):
"""Compute J2000 ecliptic velocity vector (x_dot, y_dot, z_dot)"""
vector = _ECLIPJ2000.dot(self.velocity.au_per_d)
return Velocity(vector) |
Compute J2000 ecliptic coordinates (lat, lon, distance)
If you instead want the coordinates referenced to the dynamical
system defined by the Earth's true equator and equinox, provide
an epoch time. | def ecliptic_latlon(self, epoch=None):
"""Compute J2000 ecliptic coordinates (lat, lon, distance)
If you instead want the coordinates referenced to the dynamical
system defined by the Earth's true equator and equinox, provide
an epoch time.
"""
vector = self.ecliptic_xy... |
Compute galactic coordinates (x, y, z) | def galactic_xyz(self):
"""Compute galactic coordinates (x, y, z)"""
vector = _GALACTIC.dot(self.position.au)
return Distance(vector) |
Compute galactic coordinates (lat, lon, distance) | def galactic_latlon(self):
"""Compute galactic coordinates (lat, lon, distance)"""
vector = _GALACTIC.dot(self.position.au)
d, lat, lon = to_polar(vector)
return (Angle(radians=lat, signed=True),
Angle(radians=lon),
Distance(au=d)) |
Convert this distance to an AstroPy ``SkyCoord`` object. | def to_skycoord(self, unit=None):
"""Convert this distance to an AstroPy ``SkyCoord`` object."""
from astropy.coordinates import SkyCoord
from astropy.units import au
x, y, z = self.position.au
return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au) |
Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as either a
float or a tuple of degrees, arcminutes, and arcseconds::
alt=Angle(...), az=Angle(...)
al... | def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None,
distance=Distance(au=0.1)):
"""Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as... |
Compute (alt, az, distance) relative to the observer's horizon
The altitude returned is an `Angle` in degrees above the
horizon, while the azimuth is the compass direction in degrees
with north being 0 degrees and east being 90 degrees. | def altaz(self, temperature_C=None, pressure_mbar='standard'):
"""Compute (alt, az, distance) relative to the observer's horizon
The altitude returned is an `Angle` in degrees above the
horizon, while the azimuth is the compass direction in degrees
with north being 0 degrees and east be... |
Compute the `Astrometric` position of a body from this location.
To compute the body's astrometric position, it is first asked
for its position at the time `t` of this position itself. The
distance to the body is then divided by the speed of light to
find how long it takes its light to... | def observe(self, body):
"""Compute the `Astrometric` position of a body from this location.
To compute the body's astrometric position, it is first asked
for its position at the time `t` of this position itself. The
distance to the body is then divided by the speed of light to
... |
Compute an :class:`Apparent` position for this body.
This applies two effects to the position that arise from
relativity and shift slightly where the other body will appear
in the sky: the deflection that the image will experience if its
light passes close to large masses in the Solar S... | def apparent(self):
"""Compute an :class:`Apparent` position for this body.
This applies two effects to the position that arise from
relativity and shift slightly where the other body will appear
in the sky: the deflection that the image will experience if its
light passes close... |
Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
height of this position above t... | def subpoint(self):
"""Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
... |
Experiment in progress, hence the underscore; expect changes. | def _plot_stars(catalog, observer, project, ax, mag1, mag2, margin=1.25):
"""Experiment in progress, hence the underscore; expect changes."""
art = []
# from astropy import wcs
# w = wcs.WCS(naxis=2)
# w.wcs.crpix = [-234.75, 8.3393]
# w.wcs.cdelt = np.array([-0.066667, 0.066667])
# w.wcs.... |
Compute the phase angle of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be an
:class:`~skyfield.units.Angle` object. | def phase_angle(ephemeris, body, t):
"""Compute the phase angle of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be an
:class:`~skyfi... |
Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
floating point number between zero and one. This ... | def fraction_illuminated(ephemeris, body, t):
"""Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
... |
Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to another. Use this to
search for events like sunrise or moon phases.
A ... | def find_discrete(start_time, end_time, f, epsilon=EPSILON, num=12):
"""Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to anot... |
Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter. | def seasons(ephemeris):
"""Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.
"""
earth = ephemeris... |
Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``. | def sunrise_sunset(ephemeris, topos):
"""Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``.
"""
sun = ephemeris['sun']
... |
Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
you want to give string names to e... | def moon_phases(ephemeris):
"""Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
... |
http://ssd.jpl.nasa.gov/txt/aprx_pos_planets.pdf
x_ecl = cos(w)cos(Om)-sin(w)sin(Om)cos(I) * x_prime +
(-sin(w)cos(Om) - cos(w)sin(Om)cos(I)) * y_prime
y_ecl = cos(w)sin(Om)-sin(w)cos(Om)cos(I) * x_prime +
(-sin(w)cos(Om) - cos(w)sin(Om)cos(I)) * y_prime
z_ecl = (sin(w)si... | def getECLCoordinatesAtTime(self, date):
# localize the orbital parameters
a = self.semimajor_axis
e = self.eccentricity
I = self.inclination
Om = self.longitude_ascending
#n = 0.230605479
n = 0.230652907
w = self.argument_perihelion
M = self.me... |
Compute the formulae to cut-and-paste into the routine below. | def _derive_stereographic():
"""Compute the formulae to cut-and-paste into the routine below."""
from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix
x_c, y_c, z_c, x, y, z = symbols('x_c y_c z_c x y z')
# The angles we'll need to rotate through.
around_z = atan2(x_c, y_c)
aroun... |
Compute *x* and *y* coordinates at which to plot the positions. | def build_stereographic_projection(center):
"""Compute *x* and *y* coordinates at which to plot the positions."""
# TODO: Computing the center should really be done using
# optimization, as in:
# https://math.stackexchange.com/questions/409217/
p = center.position.au
u = p / length_of(p)
c ... |
Plots PCA components' explained variance ratios. (new in v0.2.2)
Args:
clf: PCA instance that has the ``explained_variance_ratio_`` attribute.
title (string, optional): Title of the generated plot. Defaults to
"PCA Component Explained Variances"
target_explained_variance (floa... | def plot_pca_component_variance(clf, title='PCA Component Explained Variances',
target_explained_variance=0.75, ax=None,
figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Plots PCA components' explained v... |
Plots the 2-dimensional projection of PCA on a given dataset.
Args:
clf: Fitted PCA instance that can ``transform`` given data set into 2
dimensions.
X (array-like, shape (n_samples, n_features)):
Feature set to project, where n_samples is the number of samples
... | def plot_pca_2d_projection(clf, X, y, title='PCA 2-D Projection',
biplot=False, feature_labels=None,
ax=None, figsize=None, cmap='Spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots the 2-dimensional projection of PCA ... |
Embeds scikit-plot instance methods in an sklearn classifier.
Args:
clf: Scikit-learn classifier instance
Returns:
The same scikit-learn classifier instance passed in **clf**
with embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the in... | def classifier_factory(clf):
"""Embeds scikit-plot instance methods in an sklearn classifier.
Args:
clf: Scikit-learn classifier instance
Returns:
The same scikit-learn classifier instance passed in **clf**
with embedded scikit-plot instance methods.
Raises:
ValueError... |
Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_feat... | def plot_confusion_matrix_with_cv(clf, X, y, labels=None, true_labels=None,
pred_labels=None, title=None,
normalize=False, hide_zeros=False,
x_tick_rotation=0, do_cv=True, cv=None,
shu... |
Generates the KS Statistic plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_f... | def plot_ks_statistic_with_cv(clf, X, y, title='KS Statistic Plot',
do_cv=True, cv=None, shuffle=True,
random_state=None, ax=None, figsize=None,
title_fontsize="large", text_fontsize="medium"):
"""Generates the KS Statistic pl... |
Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_... | def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
... |
Generates the ROC curves from labels and predicted scores/probabilities
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_probas (array-like, shape (n_samples, n_classes)):
Prediction probabilities for each class returned by a classifier.... | def plot_roc_curve(y_true, y_probas, title='ROC Curves',
curves=('micro', 'macro', 'each_class'),
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Generates the ROC curves from labels and predicted scores/probab... |
Generates the KS Statistic plot from labels and scores/probabilities
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_probas (array-like, shape (n_samples, n_classes)):
Prediction probabilities for each class returned by a classifier.
... | def plot_ks_statistic(y_true, y_probas, title='KS Statistic Plot',
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Generates the KS Statistic plot from labels and scores/probabilities
Args:
y_true (array-like, shape (n_samples)):
... |
Generates the Precision Recall Curve from labels and probabilities
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_probas (array-like, shape (n_samples, n_classes)):
Prediction probabilities for each class returned by a classifier.
... | def plot_precision_recall_curve(y_true, y_probas,
title='Precision-Recall Curve',
curves=('micro', 'each_class'), ax=None,
figsize=None, cmap='nipy_spectral',
title_fontsize="large",
... |
Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults ... | def plot_feature_importances(clf, title='Feature Importance',
feature_names=None, max_num_features=20,
order='descending', x_tick_rotation=0, ax=None,
figsize=None, title_fontsize="large",
text_fontsize="... |
Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is... | def plot_silhouette(clf, X, title='Silhouette Analysis', metric='euclidean',
copy=True, ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer ... |
Plots elbow curve of different values of K for KMeans clustering.
Args:
clf: Clusterer instance that implements ``fit`` and ``fit_predict``
methods and a ``score`` parameter.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of sa... | def plot_elbow_curve(clf, X, title='Elbow Plot', cluster_ranges=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Plots elbow curve of different values of K for KMeans clustering.
Args:
clf: Clusterer instance that implements ``fi... |
Plots the 2-dimensional projection of PCA on a given dataset.
Args:
clf: Fitted PCA instance that can ``transform`` given data set into 2
dimensions.
X (array-like, shape (n_samples, n_features)):
Feature set to project, where n_samples is the number of samples
... | def plot_pca_2d_projection(clf, X, y, title='PCA 2-D Projection', ax=None,
figsize=None, cmap='Spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots the 2-dimensional projection of PCA on a given dataset.
Args:
clf: Fitted PCA instanc... |
Plots elbow curve of different values of K for KMeans clustering.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
X (array-like, shape (n_sample... | def plot_elbow_curve(clf, X, title='Elbow Plot', cluster_ranges=None, n_jobs=1,
show_cluster_time=True, ax=None, figsize=None,
title_fontsize="large", text_fontsize="medium"):
"""Plots elbow curve of different values of K for KMeans clustering.
Args:
clf: Clust... |
Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
X (array-like, shape (n_samples, n_features)):
... | def _clone_and_score_clusterer(clf, X, n_clusters):
"""Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
... |
Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
... | def plot_learning_curve(clf, X, y, title='Learning Curve', cv=None,
shuffle=False, random_state=None,
train_sizes=None, n_jobs=1, scoring=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""G... |
Generates the ROC curves from labels and predicted scores/probabilities
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_probas (array-like, shape (n_samples, n_classes)):
Prediction probabilities for each class returned by a classifier.... | def plot_roc(y_true, y_probas, title='ROC Curves',
plot_micro=True, plot_macro=True, classes_to_plot=None,
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Generates the ROC curves from labels and predicted scor... |
Generates the Precision Recall Curve from labels and probabilities
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_probas (array-like, shape (n_samples, n_classes)):
Prediction probabilities for each class returned by a classifier.
... | def plot_precision_recall(y_true, y_probas,
title='Precision-Recall Curve',
plot_micro=True,
classes_to_plot=None, ax=None,
figsize=None, cmap='nipy_spectral',
title_fontsize="large",
... |
Plots calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should clas... | def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,
title='Calibration plots (Reliability Curves)',
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots calibrati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.