Commit 7cdd7889 authored by Ole Streicher's avatar Ole Streicher

Beta release 0.2b2

parent 3ff241ae
Metadata-Version: 1.1
Name: astropy
Version: 0.2b1
Version: 0.2b2
Summary: Community-developed python astronomy tools
Home-page: http://astropy.org
Author: The Astropy Developers
Author-email: astropy.team@gmail.com
License: BSD
Download-URL: http://pypi.python.org/packages/source/a/astropy/astropy-0.2b1.tar.gz
Download-URL: http://pypi.python.org/packages/source/a/astropy/astropy-0.2b2.tar.gz
Description:
Astropy is a package intended to contain core functionality and some
common tools needed for performing astronomy and astrophysics research with
......
......@@ -36,7 +36,7 @@ def _get_test_runner():
def test(package=None, test_path=None, args=None, plugins=None,
verbose=False, pastebin=None, remote_data=False, pep8=False,
pdb=False, coverage=False):
pdb=False, coverage=False, open_files=False):
"""
Run Astropy tests using py.test. A proper set of arguments is
constructed and passed to `pytest.main`.
......@@ -86,6 +86,11 @@ def test(package=None, test_path=None, args=None, plugins=None,
Generate a test coverage report. The result will be placed in
the directory htmlcov.
open_files : bool, optional
Fail when any tests leave files open. Off by default, because
this adds extra run time to the test suite. Works only on
platforms with a working `lsof` command.
See Also
--------
pytest.main : py.test function wrapped by `run_tests`.
......@@ -96,8 +101,28 @@ def test(package=None, test_path=None, args=None, plugins=None,
package=package, test_path=test_path, args=args,
plugins=plugins, verbose=verbose, pastebin=pastebin,
remote_data=remote_data, pep8=pep8, pdb=pdb,
coverage=coverage)
coverage=coverage, open_files=open_files)
#if we are *not* in setup mode, import the logger
# if we are *not* in setup mode, import the logger and possibly populate the
# configuration file with the defaults
if not _ASTROPY_SETUP_:
from .logger import log
from . import config
import os
from warnings import warn
# add these here so we only need to cleanup the namespace at the end
config_dir = e = None
if not os.environ.get('ASTROPY_SKIP_CONFIG_UPDATE', False):
config_dir = os.path.dirname(__file__)
try:
config.configuration.update_default_config(__package__, config_dir)
except config.configuration.ConfigurationDefaultMissingError as e:
wmsg = (e.args[0] + " Cannot install default profile. If you are "
"importing from source, this is expected.")
warn(config.configuration.ConfigurationDefaultMissingWarning(wmsg))
del os, warn, config_dir, e # clean up namespace
# Licensed under a 3-clause BSD style license - see LICENSE.rst
class ConstantDefinition(float):
"""
A float with meta-data related to physical constants
......
This diff is collapsed.
......@@ -37,8 +37,8 @@ def _find_home():
if 'HOME' in env:
homedir = decodepath(env['HOME'])
else:
raise OSError('Could not find unix home directory to search for' +\
' astropy config dir')
raise OSError('Could not find unix home directory to search for '
'astropy config dir')
elif os.name == 'nt': # This is for all modern Windows (NT or after)
#Try for a network home first
if 'HOMESHARE' in env:
......@@ -54,7 +54,7 @@ def _find_home():
try:
import _winreg as wreg
key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
homedir = wreg.QueryValueEx(key, 'Personal')[0]
homedir = decodepath(homedir)
......@@ -64,15 +64,16 @@ def _find_home():
if 'HOME' in env:
homedir = decodepath(env['HOME'])
else:
raise OSError('Could not find windows home directory to' +\
' search for astropy config dir')
raise OSError('Could not find windows home directory to '
'search for astropy config dir')
else:
#for other platforms, try HOME, although it probably isn't there
if 'HOME' in env:
homedir = decodepath(env['HOME'])
else:
raise OSError('Could not find a home directory to search for ' +\
'astropy config dir - are you on an unspported platform?')
raise OSError('Could not find a home directory to search for '
'astropy config dir - are you on an unspported '
'platform?')
return homedir
......@@ -92,6 +93,7 @@ def get_config_dir(create=True):
The absolute path to the configuration directory.
"""
from os import path, environ
#symlink will be set to this if the directory is created
......@@ -106,7 +108,6 @@ def get_config_dir(create=True):
return path.abspath(xchpth)
else:
linkto = xchpth
return path.abspath(_find_or_create_astropy_dir('config', linkto))
......@@ -154,12 +155,20 @@ def _find_or_create_astropy_dir(dirnm, linkto):
if not path.exists(maindir):
#first create .astropy dir if needed
if not path.exists(innerdir):
mkdir(innerdir)
try:
mkdir(innerdir)
except OSError:
if not path.isdir(innerdir):
raise
elif not path.isdir(innerdir):
msg = 'Intended Astropy directory {0} is actually a file.'
raise IOError(msg.format(innerdir))
mkdir(maindir)
try:
mkdir(maindir)
except OSError:
if not path.isdir(maindir):
raise
if (not sys.platform.startswith('win') and
linkto is not None and
......
......@@ -29,9 +29,6 @@ class Constant(Quantity):
self.name = name
self.reference = reference
def __new__(cls, value, uncertainty, name, reference, units):
return super(Constant, cls).__new__(cls, value)
def __repr__(self):
s = "<Constant: "
s += "name='{0}' ".format(self.name)
......
......@@ -12,5 +12,6 @@ from .coordsystems import *
from .distances import *
from .transformations import *
from .builtin_systems import *
from .name_resolve import *
__doc__ += builtin_systems._transform_graph_docs
\ No newline at end of file
......@@ -460,7 +460,10 @@ def hours_to_string(h, precision=5, pad=False, sep=('h', 'm', 's')):
"""
if pad:
pad = 2
if h < 0:
pad = 3
else:
pad = 2
else:
pad = 0
......@@ -491,7 +494,10 @@ def degrees_to_string(d, precision=5, pad=False, sep=':'):
"""
if pad:
pad = 2
if d < 0:
pad = 3
else:
pad = 2
else:
pad = 0
......
......@@ -509,3 +509,36 @@ class SphericalCoordinatesBase(object):
dir_items.append(alias)
return sorted(set(dir_items))
# Name resolve
@classmethod
def from_name(cls, name):
"""
Given a name, query the CDS name resolver to attempt to retrieve
coordinate information for that object. The search database, sesame
url, and query timeout can be set through configuration items in
`astropy.coordinates.name_resolve` -- see docstring for
`astropy.coordinates.name_resolve.get_icrs_coordinates` for more
information.
Parameters
----------
name : str
The name of the object to get coordinates for, e.g. m42.
Returns
-------
coord : SphericalCoordinatesBase
Instance of a Coordinates class, specified by the class this is
called on, e.g. if `GalacticCoordinates.from_name('m42')`, will
get an instance of `GalacticCoordinates` representing the
position of M42.
"""
from .name_resolve import get_icrs_coordinates
icrs = get_icrs_coordinates(name)
if cls == icrs.__class__:
return icrs
else:
return icrs.transform_to(cls)
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains convenience functions for getting a coordinate object
for a named object by querying SESAME and getting the first returned result.
Note that this is intended to be a convenience, and is very simple. If you
need precise coordinates for an object you should find the appropriate
reference for that measurement and input the coordinates manually.
"""
from __future__ import division, print_function
# Standard library
import os
import re
import sys
import httplib
import urllib
import urllib2
from urlparse import urlparse
import socket
# Third party
import numpy as np
# Astropy
from ..config import ConfigurationItem
from .builtin_systems import ICRSCoordinates
from .. import units as u
__all__ = ["get_icrs_coordinates"]
SESAME_URL = ConfigurationItem("sesame_url",
["http://cdsweb.u-strasbg.fr/cgi-bin/nph-sesame/",
"http://vizier.cfa.harvard.edu/viz-bin/nph-sesame/"],
"The URL to Sesame's web-queryable database.",
cfgtype='string_list')
SESAME_DATABASE = ConfigurationItem("sesame_database", ['all', 'simbad', 'ned',
'vizier'],
"This specifies the default database that "
"SESAME will query when using the name "
"resolve mechanism in the coordinates "
"subpackage. Default is to search all "
"databases, but this can be 'all', "
"'simbad', 'ned', or 'vizier'.")
NAME_RESOLVE_TIMEOUT = ConfigurationItem('name_resolve_timeout', 5,
"This is the maximum time to wait "
"for a response from a name resolve "
"query to SESAME in seconds.")
class NameResolveError(Exception):
pass
def get_icrs_coordinates(name):
"""
Retrieve an ICRSCoordinates object by using an online name resolving
service to retrieve coordinates for the specified name. By default,
this will search all available databases until a match is found. If
you would like to specify the database, use the configuration item
`name_resolve.SESAME_DATABASE` . You can also specify a list of servers
to use for querying Sesame using the configuration item
`name_resolve.SESAME_URL`. This will try each one in order until a valid
response is returned. By default, this list includes the main Sesame
host and a mirror at vizier. A final configuration item,
`name_resolve.NAME_RESOLVE_TIMEOUT`, is the number of seconds to wait
for a response from the server before giving up. By default this is
5 seconds.
Parameters
----------
name : str
The name of the object to get coordinates for, e.g. M42.
Returns
-------
coord : SphericalCoordinatesBase
An `ICRSCoordinates` instance for the object name specified.
"""
database = SESAME_DATABASE()
# The web API just takes the first letter of the database name
db = database.upper()[0]
# Make sure we don't have duplicates in the url list
urls = []
domains = []
for url in SESAME_URL():
domain = urlparse(url).netloc
# Check for duplicates
if domain not in domains:
domains.append(domain)
# Add the query to the end of the url, add to url list
fmt_url = os.path.join(url, "{db}?{name}")
fmt_url = fmt_url.format(name=urllib.quote(name), db=db)
urls.append(fmt_url)
for url in urls:
try:
# Retrieve ascii name resolve data from CDS
resp = urllib2.urlopen(url, timeout=NAME_RESOLVE_TIMEOUT())
break
except urllib2.URLError, e:
# This catches a timeout error, see:
# http://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python
if isinstance(e.reason, socket.timeout):
# If it was a timeout, try with the next URL
continue
else:
raise NameResolveError("Unable to retrieve coordinates for name "
"'{0}'".format(name))
# All Sesame URL's timed out...
else:
raise NameResolveError("All Sesame queries timed out. Unable to "
"retrieve coordinates.")
resp_data = resp.read()
pattr = re.compile(r"%J\s*([0-9\.]+)\s*([\+\-\.0-9]+)")
matched = pattr.search(resp_data.decode('utf-8'))
if matched == None:
if db == "A":
err = "Unable to find coordinates for name '{0}'".format(name)
else:
err = "Unable to find coordinates for name '{0}' in database {1}"\
.format(name, database)
raise NameResolveError(err)
ra,dec = matched.groups()
return ICRSCoordinates(ra, dec, unit=(u.degree, u.degree))
\ No newline at end of file
# Licensed under a 3-clause BSD style license - see LICENSE.rst
def get_package_data():
return {'astropy.coordinates.tests.accuracy': ['*.csv']}
"""
This series of functions are used to generate the reference CSV files
used by the accuracy tests. Running this as a comand-line script will
generate them all.
"""
def ref_fk4_no_e_fk4(fnout='fk4_no_e_fk4.csv'):
"""
Accuracy tests for the FK4 (with no E-terms of aberration) to/from FK4
conversion, with arbitrary equinoxes and epoch of observation.
"""
import os
import numpy as np
import starlink.Ast as Ast
from astropy.table import Table, Column
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the FK4
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to FK4.
ra = np.random.uniform(0., 360., N)
dec = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
ra_fk4ne, dec_fk4ne = [], []
ra_fk4, dec_fk4 = [], []
for i in range(N):
# Set up frames for AST
frame_fk4ne = Ast.SkyFrame('System=FK4-NO-E,Epoch={epoch},Equinox=B1950'.format(epoch=obstime[i]))
frame_fk4 = Ast.SkyFrame('System=FK4,Epoch={epoch},Equinox=B1950'.format(epoch=obstime[i]))
# FK4 to FK4 (no E-terms)
frameset = frame_fk4.convert(frame_fk4ne)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk4ne.append(coords[0, 0])
dec_fk4ne.append(coords[1, 0])
# FK4 (no E-terms) to FK4
frameset = frame_fk4ne.convert(frame_fk4)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk4.append(coords[0, 0])
dec_fk4.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column('obstime', obstime))
t.add_column(Column('ra_in', ra))
t.add_column(Column('dec_in', dec))
t.add_column(Column('ra_fk4ne', ra_fk4ne))
t.add_column(Column('dec_fk4ne', dec_fk4ne))
t.add_column(Column('ra_fk4', ra_fk4))
t.add_column(Column('dec_fk4', dec_fk4))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')
def ref_fk4_no_e_fk5(fnout='fk4_no_e_fk5.csv'):
"""
Accuracy tests for the FK4 (with no E-terms of aberration) to/from FK5
conversion, with arbitrary equinoxes and epoch of observation.
"""
import os
import numpy as np
import starlink.Ast as Ast
from astropy.table import Table, Column
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the FK4
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to FK4.
ra = np.random.uniform(0., 360., N)
dec = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
equinox_fk4 = ["B{0:7.2f}".format(x) for x in np.random.uniform(1925., 1975., N)]
equinox_fk5 = ["J{0:7.2f}".format(x) for x in np.random.uniform(1975., 2025., N)]
ra_fk4, dec_fk4 = [], []
ra_fk5, dec_fk5 = [], []
for i in range(N):
# Set up frames for AST
frame_fk4 = Ast.SkyFrame('System=FK4-NO-E,Epoch={epoch},Equinox={equinox_fk4}'.format(epoch=obstime[i], equinox_fk4=equinox_fk4[i]))
frame_fk5 = Ast.SkyFrame('System=FK5,Epoch={epoch},Equinox={equinox_fk5}'.format(epoch=obstime[i], equinox_fk5=equinox_fk5[i]))
# FK4 to FK5
frameset = frame_fk4.convert(frame_fk5)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk5.append(coords[0, 0])
dec_fk5.append(coords[1, 0])
# FK5 to FK4
frameset = frame_fk5.convert(frame_fk4)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk4.append(coords[0, 0])
dec_fk4.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column('equinox_fk4', equinox_fk4))
t.add_column(Column('equinox_fk5', equinox_fk5))
t.add_column(Column('obstime', obstime))
t.add_column(Column('ra_in', ra))
t.add_column(Column('dec_in', dec))
t.add_column(Column('ra_fk5', ra_fk5))
t.add_column(Column('dec_fk5', dec_fk5))
t.add_column(Column('ra_fk4', ra_fk4))
t.add_column(Column('dec_fk4', dec_fk4))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')
def ref_galactic_fk4(fnout='galactic_fk4.csv'):
"""
Accuracy tests for the ICRS (with no E-terms of aberration) to/from FK5
conversion, with arbitrary equinoxes and epoch of observation.
"""
import os
import numpy as np
import starlink.Ast as Ast
from astropy.table import Table, Column
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the ICRS
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to ICRS.
lon = np.random.uniform(0., 360., N)
lat = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
equinox_fk4 = ["J{0:7.2f}".format(x) for x in np.random.uniform(1975., 2025., N)]
lon_gal, lat_gal = [], []
ra_fk4, dec_fk4 = [], []
for i in range(N):
# Set up frames for AST
frame_gal = Ast.SkyFrame('System=Galactic,Epoch={epoch}'.format(epoch=obstime[i]))
frame_fk4 = Ast.SkyFrame('System=FK4,Epoch={epoch},Equinox={equinox_fk4}'.format(epoch=obstime[i], equinox_fk4=equinox_fk4[i]))
# ICRS to FK5
frameset = frame_gal.convert(frame_fk4)
coords = np.degrees(frameset.tran([[np.radians(lon[i])], [np.radians(lat[i])]]))
ra_fk4.append(coords[0, 0])
dec_fk4.append(coords[1, 0])
# FK5 to ICRS
frameset = frame_fk4.convert(frame_gal)
coords = np.degrees(frameset.tran([[np.radians(lon[i])], [np.radians(lat[i])]]))
lon_gal.append(coords[0, 0])
lat_gal.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column('equinox_fk4', equinox_fk4))
t.add_column(Column('obstime', obstime))
t.add_column(Column('lon_in', lon))
t.add_column(Column('lat_in', lat))
t.add_column(Column('ra_fk4', ra_fk4))
t.add_column(Column('dec_fk4', dec_fk4))
t.add_column(Column('lon_gal', lon_gal))
t.add_column(Column('lat_gal', lat_gal))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')
def ref_icrs_fk5(fnout='icrs_fk5.csv'):
"""
Accuracy tests for the ICRS (with no E-terms of aberration) to/from FK5
conversion, with arbitrary equinoxes and epoch of observation.
"""
import os
import numpy as np
import starlink.Ast as Ast
from astropy.table import Table, Column
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the ICRS
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to ICRS.
ra = np.random.uniform(0., 360., N)
dec = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
equinox_fk5 = ["J{0:7.2f}".format(x) for x in np.random.uniform(1975., 2025., N)]
ra_icrs, dec_icrs = [], []
ra_fk5, dec_fk5 = [], []
for i in range(N):
# Set up frames for AST
frame_icrs = Ast.SkyFrame('System=ICRS,Epoch={epoch}'.format(epoch=obstime[i]))
frame_fk5 = Ast.SkyFrame('System=FK5,Epoch={epoch},Equinox={equinox_fk5}'.format(epoch=obstime[i], equinox_fk5=equinox_fk5[i]))
# ICRS to FK5
frameset = frame_icrs.convert(frame_fk5)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk5.append(coords[0, 0])
dec_fk5.append(coords[1, 0])
# FK5 to ICRS
frameset = frame_fk5.convert(frame_icrs)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_icrs.append(coords[0, 0])
dec_icrs.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column('equinox_fk5', equinox_fk5))
t.add_column(Column('obstime', obstime))
t.add_column(Column('ra_in', ra))
t.add_column(Column('dec_in', dec))
t.add_column(Column('ra_fk5', ra_fk5))
t.add_column(Column('dec_fk5', dec_fk5))
t.add_column(Column('ra_icrs', ra_icrs))
t.add_column(Column('dec_icrs', dec_icrs))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')