def _find_rtd_version(): """Find closest RTD doc version.""" vstr = 'latest' try: import ginga from bs4 import BeautifulSoup except ImportError: return vstr # No active doc build before this release, just use latest. if not minversion(ginga, '2.6.0'): return vstr # Get RTD download listing. url = 'https://readthedocs.org/projects/ginga/downloads/' with urllib.request.urlopen(url) as r: soup = BeautifulSoup(r, 'html.parser') # Compile a list of available HTML doc versions for download. all_rtd_vernums = [] for link in soup.find_all('a'): href = link.get('href') if 'htmlzip' not in href: continue s = href.split('/')[-2] if s.startswith('v'): # Ignore latest and stable all_rtd_vernums.append(s) all_rtd_vernums.sort(reverse=True) # Find closest match. ginga_ver = ginga.__version__ for rtd_ver in all_rtd_vernums: if ginga_ver > rtd_ver[1:]: # Ignore "v" in comparison break else: vstr = rtd_ver return vstr
def test_insert(): """ Test Quantity.insert method. This does not test the full capabilities of the underlying np.insert, but hits the key functionality for Quantity. """ q = [1, 2] * u.m # Insert a compatible float with different units q2 = q.insert(0, 1 * u.km) assert np.all(q2.value == [1000, 1, 2]) assert q2.unit is u.m assert q2.dtype.kind == 'f' if minversion(np, '1.8.0'): q2 = q.insert(1, [1, 2] * u.km) assert np.all(q2.value == [1, 1000, 2000, 2]) assert q2.unit is u.m # Cannot convert 1.5 * u.s to m with pytest.raises(u.UnitsError): q.insert(1, 1.5 * u.s) # Tests with multi-dim quantity q = [[1, 2], [3, 4]] * u.m q2 = q.insert(1, [10, 20] * u.m, axis=0) assert np.all(q2.value == [[1, 2], [10, 20], [3, 4]]) q2 = q.insert(1, [10, 20] * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 20, 4]]) q2 = q.insert(1, 10 * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 10, 4]])
from astropy.utils import minversion from astropy.tests.helper import pytest from astropy.modeling.models import Gaussian2D from astropy.modeling.fitting import SLSQPLSQFitter from astropy.convolution.utils import discretize_model from astropy.table import Table from .. import IntegratedGaussianPRF, psf_photometry, subtract_psf from ..sandbox import DiscretePRF try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False if minversion(pytest, '2.8'): HAS_PYTEST_GEQ_28 = True else: HAS_PYTEST_GEQ_28 = False PSF_SIZE = 11 GAUSSIAN_WIDTH = 1. IMAGE_SIZE = 101 # Position and FLUXES of test sources INTAB = Table([[50., 23, 12, 86], [50., 83, 80, 84], [np.pi * 10, 3.654, 20., 80 / np.sqrt(3)]], names=['x_0', 'y_0', 'flux_0']) # Create test psf
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Define the Gammapy matplotlib plotting style.""" from __future__ import absolute_import, division, print_function, unicode_literals from astropy.visualization import astropy_mpl_style from astropy.utils import minversion # This returns False if matplotlib cannot be imported MATPLOTLIB_GE_1_5 = minversion('matplotlib', '1.5') __all__ = ['gammapy_mpl_style'] gammapy_mpl_style = astropy_mpl_style """ Gammapy matplotlib plotting style. """ color_cycle = ['#E24A33', # orange '#348ABD', # blue '#467821', # green '#A60628', # red '#7A68A6', # purple '#CF4457', # pink '#188487'] # turquoise if MATPLOTLIB_GE_1_5: # This is a dependency of matplotlib, so should be present. from cycler import cycler gammapy_mpl_style['axes.prop_cycle'] = cycler('color', color_cycle) else:
from ..circle import (CircularAperture, CircularAnnulus, SkyCircularAperture, SkyCircularAnnulus) from ..ellipse import (EllipticalAperture, EllipticalAnnulus, SkyEllipticalAperture, SkyEllipticalAnnulus) from ..rectangle import (RectangularAperture, RectangularAnnulus, SkyRectangularAperture, SkyRectangularAnnulus) from ...datasets import (get_path, make_4gaussians_image, make_wcs, make_imagehdu) try: import matplotlib # noqa HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False NUMPY_LT_1_14 = not minversion('numpy', '1.14dev') APERTURE_CL = [CircularAperture, CircularAnnulus, EllipticalAperture, EllipticalAnnulus, RectangularAperture, RectangularAnnulus] TEST_APERTURES = list(zip(APERTURE_CL, ((3.,), (3., 5.), (3., 5., 1.), (3., 5., 4., 1.), (5, 8, np.pi / 4), (8, 12, 8, np.pi / 8)))) @pytest.mark.parametrize(('aperture_class', 'params'), TEST_APERTURES)
observability_table, time_grid_from_range, SunSeparationConstraint, MoonSeparationConstraint, MoonIlluminationConstraint, LocalTimeConstraint, ) try: import ephem HAS_PYEPHEM = True except ImportError: HAS_PYEPHEM = False APY_LT104 = not minversion("astropy", "1.0.4") vega = FixedTarget(coord=SkyCoord(ra=279.23473479 * u.deg, dec=38.78368896 * u.deg), name="Vega") rigel = FixedTarget(coord=SkyCoord(ra=78.63446707 * u.deg, dec=8.20163837 * u.deg), name="Rigel") polaris = FixedTarget(coord=SkyCoord(ra=37.95456067 * u.deg, dec=89.26410897 * u.deg), name="Polaris") def test_at_night_basic(): subaru = Observer.at_site("Subaru") time_ranges = [ Time(["2001-02-03 04:05:06", "2001-02-04 04:05:06"]), # 1 day Time(["2007-08-09 10:11:12", "2007-08-09 11:11:12"]), ] # 1 hr targets = [vega, rigel, polaris] for time_range in time_ranges: # Calculate constraint using methods on astroplan.Observer:
import astropy.units as u from astropy.time import Time from astropy.coordinates import SkyCoord, get_sun, get_moon from astropy.utils import minversion import pytest from ..observer import Observer from ..target import FixedTarget, get_skycoord from ..constraints import (AltitudeConstraint, AirmassConstraint, AtNightConstraint, is_observable, is_always_observable, observability_table, time_grid_from_range, SunSeparationConstraint, MoonSeparationConstraint, MoonIlluminationConstraint, TimeConstraint, LocalTimeConstraint, months_observable, max_best_rescale, min_best_rescale) APY_LT104 = not minversion('astropy', '1.0.4') vega = FixedTarget(coord=SkyCoord(ra=279.23473479*u.deg, dec=38.78368896*u.deg), name="Vega") rigel = FixedTarget(coord=SkyCoord(ra=78.63446707*u.deg, dec=8.20163837*u.deg), name="Rigel") polaris = FixedTarget(coord=SkyCoord(ra=37.95456067*u.deg, dec=89.26410897*u.deg), name="Polaris") def test_at_night_basic(): subaru = Observer.at_site("Subaru") time_ranges = [Time(['2001-02-03 04:05:06', '2001-02-04 04:05:06']), # 1 day Time(['2007-08-09 10:11:12', '2007-08-09 11:11:12'])] # 1 hr targets = [vega, rigel, polaris] for time_range in time_ranges:
from astropy.utils.exceptions import AstropyUserWarning from ..groupstars import DAOGroup from ..models import IntegratedGaussianPRF from ..photometry import DAOPhotPSFPhotometry, IterativelySubtractedPSFPhotometry from ..photometry import BasicPSFPhotometry from ..sandbox import DiscretePRF from ...background import SigmaClip, MedianBackground, StdBackgroundRMS from ...background import MedianBackground, MMMBackground, SigmaClip from ...background import StdBackgroundRMS from ...datasets import make_gaussian_sources from ...datasets import make_noise_image from ...detection import DAOStarFinder ASTROPY_GT_1_1 = minversion("astropy", "1.1") try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False def make_psf_photometry_objs(std=1, sigma_psf=1): """ Produces baseline photometry objects which are then modified as-needed in specific tests below """
import astropy.units as u from astropy.time import Time from astropy.coordinates import SkyCoord, get_sun, get_moon, Angle from astropy.utils import minversion from astropy.tests.helper import pytest from ..observer import Observer from ..target import FixedTarget from ..constraints import ( AltitudeConstraint, AirmassConstraint, AtNightConstraint, is_observable, is_always_observable, observability_table, time_grid_from_range, SunSeparationConstraint, MoonSeparationConstraint, MoonIlluminationConstraint, TimeConstraint, LocalTimeConstraint, months_observable, max_best_rescale, min_best_rescale, AzimuthConstraint) APY_LT104 = not minversion('astropy', '1.0.4') vega = FixedTarget(coord=SkyCoord(ra=279.23473479 * u.deg, dec=38.78368896 * u.deg), name="Vega") rigel = FixedTarget(coord=SkyCoord(ra=78.63446707 * u.deg, dec=8.20163837 * u.deg), name="Rigel") polaris = FixedTarget(coord=SkyCoord(ra=37.95456067 * u.deg, dec=89.26410897 * u.deg), name="Polaris") def test_at_night_basic(): subaru = Observer.at_site("Subaru") time_ranges = [
import abc import numpy as np from .core import Model from astropy import units as u from astropy.utils import minversion try: import scipy from scipy.interpolate import interpn has_scipy = True except ImportError: has_scipy = False has_scipy = has_scipy and minversion(scipy, "0.14") __all__ = ['tabular_model', 'Tabular1D', 'Tabular2D'] __doctest_requires__ = {('tabular_model'): ['scipy']} class _Tabular(Model): """ Returns an interpolated lookup table value. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ), optional The points defining the regular grid in n dimensions. lookup_table : array-like, shape (m1, ..., mn, ...)
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Define the Gammapy matplotlib plotting style.""" from __future__ import absolute_import, division, print_function, unicode_literals from astropy.visualization import astropy_mpl_style from astropy.utils import minversion # This returns False if matplotlib cannot be imported MATPLOTLIB_GE_1_5 = minversion('matplotlib', '1.5') __all__ = ['gammapy_mpl_style'] gammapy_mpl_style = astropy_mpl_style """ Gammapy matplotlib plotting style. """ color_cycle = [ '#E24A33', # orange '#348ABD', # blue '#467821', # green '#A60628', # red '#7A68A6', # purple '#CF4457', # pink '#188487' ] # turquoise if MATPLOTLIB_GE_1_5: # This is a dependency of matplotlib, so should be present. from cycler import cycler gammapy_mpl_style['axes.prop_cycle'] = cycler('color', color_cycle)
from astropy.modeling.models import Gaussian2D from astropy.modeling.core import FittableModel from astropy.modeling.parameters import Parameter from astropy.modeling.polynomial import PolynomialBase from astropy import units as u from astropy.utils import minversion from astropy.tests.helper import assert_quantity_allclose from astropy.utils import NumpyRNGContext try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False HAS_SCIPY_14 = HAS_SCIPY and minversion(scipy, "0.14") @pytest.mark.skipif('not HAS_SCIPY') def test_custom_model(amplitude=4, frequency=1): def sine_model(x, amplitude=4, frequency=1): """ Model function """ return amplitude * np.sin(2 * np.pi * frequency * x) def sine_deriv(x, amplitude=4, frequency=1): """ Jacobian of model function, e.g. derivative of the function with respect to the *parameters* """
# mpdaf documentation build configuration file, created by # sphinx-quickstart on Fri Jun 22 10:03:09 2012. import os import sys import warnings from astropy.utils import minversion from pkg_resources import get_distribution IPYTHON_LT_7_1 = not minversion('IPython', '7.1.0') sys.setrecursionlimit(1500) # -- Project information ----------------------------------------------------- project = 'MPDAF' copyright = '2010-2019, CRAL' author = 'MPDAF Team' release = get_distribution('mpdaf').version # for example take major/minor version = '.'.join(release.split('.')[:2]) # -- General configuration ---------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones.
# LOCAL from .test_units import _area from .. import exceptions, units from ..models import (BlackBodyNorm1D, Box1D, ConstFlux1D, Empirical1D, GaussianFlux1D) from ..observation import Observation from ..spectrum import SourceSpectrum, SpectralElement try: import scipy except ImportError: HAS_SCIPY = False else: HAS_SCIPY = True HAS_SCIPY = HAS_SCIPY and minversion(scipy, '0.14') # Global test data files _specfile = get_pkg_data_filename( os.path.join('data', 'grw_70d5824_stisnic_005.fits')) _bandfile = get_pkg_data_filename( os.path.join('data', 'hst_acs_hrc_f555w.fits')) @pytest.mark.skipif('not HAS_SCIPY') class TestObservation(object): """Test Observation (most of them).""" def setup_class(self): sp = SourceSpectrum( ConstFlux1D, amplitude=1 * units.FLAM,
from __future__ import (absolute_import, division, print_function, unicode_literals) import os import astropy.units as u from astropy.tests.helper import assert_quantity_allclose, remote_data, pytest from astropy.utils import minversion from astropy.coordinates import SkyCoord from ...exoplanet_orbit_database import ExoplanetOrbitDatabase APY_LT12 = not minversion('astropy', '1.2') LOCAL_TABLE_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data', 'exoplanet_orbit_database.csv') @remote_data def test_exoplanet_orbit_database_table(): table = ExoplanetOrbitDatabase.get_table() # Number of columns expected as of Oct 8, 2016 assert len(table) >= 315 # Check some planets are in the table expected_planets = ['HD 189733 b', 'Kepler-186 f', 'TRAPPIST-1 b', 'HD 209458 b', 'Kepler-62 f', 'GJ 1214 b'] for planet in expected_planets: assert planet.lower().replace(" ", "") in table['NAME_LOWERCASE'] def test_parameter_units():
from astropy.tests.helper import pytest from astropy.utils import minversion from numpy.testing import assert_array_less, assert_allclose from ..data import DataManager from ..datasets import gammapy_extra __all__ = [ 'requires_dependency', 'requires_data', 'SHERPA_LT_4_8', 'assert_wcs_allclose', 'assert_skycoord_allclose', ] SHERPA_LT_4_8 = not minversion('sherpa', '4.8.2+81') # Cache for `requires_dependency` _requires_dependency_cache = dict() def requires_dependency(name): """Decorator to declare required dependencies for tests. Examples -------- :: from gammapy.utils.testing import requires_dependency
# -*- coding: utf-8 -*- # Licensed under the GPLv3 - see LICENSE """Provide a Phase class with integer and fractional part.""" import numpy as np from astropy import units as u from astropy.coordinates import Angle, Longitude from astropy.time.utils import two_sum, two_product from astropy.utils import minversion __all__ = ['Phase', 'FractionalPhase'] NUMPY_LT_1_16 = not minversion('numpy', '1.16') FRACTION_UFUNCS = {np.cos, np.sin, np.tan, np.spacing} COMPARISON_UFUNCS = { np.equal, np.not_equal, np.less, np.less_equal, np.greater, np.greater_equal } def day_frac(val1, val2, factor=None, divisor=None): """Return the sum of ``val1`` and ``val2`` as two float64s. The returned floats are an integer part and the fractional remainder, with the latter guaranteed to be within -0.5 and 0.5 (inclusive on either side, as the integer is rounded to even). The arithmetic is all done with exact floating point operations so no precision is lost to rounding error. It is assumed the sum is less
from __future__ import absolute_import, division, unicode_literals, print_function import numpy as np from numpy.testing import assert_array_equal from ... import yamlutil from .basic import TransformType try: import astropy except ImportError: HAS_ASTROPY = False else: HAS_ASTROPY = True from astropy.utils import minversion ASTROPY_13 = minversion(astropy, "1.3.dev16506") if HAS_ASTROPY and ASTROPY_13: __all__ = ['TabularType'] else: __all__ = [] class TabularType(TransformType): name = "transform/tabular" if HAS_ASTROPY and ASTROPY_13: types = [astropy.modeling.models.Tabular2D, astropy.modeling.models.Tabular1D ] else: types = []
from astropy.utils import minversion from astropy.coordinates import matching """ These are the tests for coordinate matching. Note that this requires scipy. """ try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False if HAS_SCIPY and minversion(scipy, '0.12.0', inclusive=False): OLDER_SCIPY = False else: OLDER_SCIPY = True @pytest.mark.skipif(not HAS_SCIPY, reason="Requires scipy.") def test_matching_function(): from astropy.coordinates import ICRS from astropy.coordinates.matching import match_coordinates_3d # this only uses match_coordinates_3d because that's the actual implementation cmatch = ICRS([4, 2.1] * u.degree, [0, 0] * u.degree) ccatalog = ICRS([1, 2, 3, 4] * u.degree, [0, 0, 0, 0] * u.degree) idx, d2d, d3d = match_coordinates_3d(cmatch, ccatalog)
from astropy.modeling import fitting, models from astropy.modeling.core import FittableModel from astropy.modeling.polynomial import PolynomialBase from astropy import units as u from astropy.utils import minversion from astropy.tests.helper import assert_quantity_allclose from astropy.utils import NumpyRNGContext try: import scipy from scipy import optimize # pylint: disable=W0611 HAS_SCIPY = True except ImportError: HAS_SCIPY = False HAS_SCIPY_14 = HAS_SCIPY and minversion(scipy, "0.14") @pytest.mark.skipif('not HAS_SCIPY') def test_custom_model(amplitude=4, frequency=1): def sine_model(x, amplitude=4, frequency=1): """ Model function """ return amplitude * np.sin(2 * np.pi * frequency * x) def sine_deriv(x, amplitude=4, frequency=1): """ Jacobian of model function, e.g. derivative of the function with respect to the *parameters*
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This is a collection of monkey patches and workarounds for bugs in earlier versions of Numpy. """ import numpy as np from astropy.utils import minversion __all__ = [ 'NUMPY_LT_1_19', 'NUMPY_LT_1_20', 'NUMPY_LT_1_21_1', 'NUMPY_LT_1_22', 'NUMPY_LT_1_22_1', 'NUMPY_LT_1_23' ] # TODO: It might also be nice to have aliases to these named for specific # features/bugs we're checking for (ex: # astropy.table.table._BROKEN_UNICODE_TABLE_SORT) NUMPY_LT_1_19 = not minversion(np, '1.19') NUMPY_LT_1_20 = not minversion(np, '1.20') NUMPY_LT_1_21_1 = not minversion(np, '1.21.1') NUMPY_LT_1_22 = not minversion(np, '1.22') NUMPY_LT_1_22_1 = not minversion(np, '1.22.1') NUMPY_LT_1_23 = not minversion(np, '1.23dev0')
from numpy.testing import assert_allclose, assert_array_equal, assert_equal from ..models import IntegratedGaussianPRF from ...datasets import make_gaussian_sources from ...datasets import make_noise_image from ..groupstars import DAOGroup from ..photometry import DAOPhotPSFPhotometry, IterativelySubtractedPSFPhotometry from ..photometry import BasicPSFPhotometry from ...detection import DAOStarFinder from ...background import SigmaClip, MedianBackground, StdBackgroundRMS from ...background import MedianBackground, MMMBackground, SigmaClip from ...background import StdBackgroundRMS ASTROPY_GT_1_1 = minversion('astropy', '1.1') try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False def make_psf_photometry_objs(std=1, sigma_psf=1): """ Produces baseline photometry objects which are then modified as-needed in specific tests below """ daofind = DAOStarFinder(threshold=5.0*std,
import astropy.io.fits as fits import numpy as np from astropy.tests.helper import catch_warnings from astropy.utils import minversion from astropy.utils.exceptions import AstropyUserWarning from astropy.nddata import CCDData from ..image_collection import ImageFileCollection _filters = [] _original_dir = '' _ASTROPY_LT_1_3 = not minversion("astropy", "1.3") def test_fits_summary(triage_setup): keywords = ['imagetyp', 'filter'] ic = ImageFileCollection(triage_setup.test_dir, keywords=keywords) summary = ic._fits_summary(header_keywords=keywords) assert len(summary['file']) == triage_setup.n_test['files'] for keyword in keywords: assert len(summary[keyword]) == triage_setup.n_test['files'] # explicit conversion to array is needed to avoid astropy Table bug in # 0.2.4 no_filter_no_object_row = np.array( summary['file'] == 'no_filter_no_object_bias.fit') # there should be no filter keyword in the bias file assert summary['filter'][no_filter_no_object_row].mask
import base64 import numpy as np from astropy.time import Time, TimeDelta from astropy import units as u from astropy import coordinates as coords from astropy.utils import minversion from astropy.table import SerializedColumn try: import yaml except ImportError: raise ImportError( '`import yaml` failed, PyYAML package is required for YAML') YAML_LT_3_12 = not minversion(yaml, '3.12') __all__ = ['AstropyLoader', 'AstropyDumper', 'load', 'load_all', 'dump'] def _unit_representer(dumper, obj): out = {'unit': str(obj.to_string())} return dumper.represent_mapping('!astropy.units.Unit', out) def _unit_constructor(loader, node): map = loader.construct_mapping(node) return u.Unit(map['unit'], parse_strict='warn') def _serialized_column_representer(dumper, obj):
from .. import exceptions, units from ..models import ( BlackBodyNorm1D, Box1D, ConstFlux1D, Empirical1D, Gaussian1D, GaussianAbsorption1D, GaussianFlux1D, Lorentz1D, MexicanHat1D, PowerLawFlux1D, get_waveset) from ..observation import Observation from ..spectrum import SourceSpectrum, SpectralElement try: import scipy except ImportError: HAS_SCIPY = False else: HAS_SCIPY = True HAS_SCIPY = HAS_SCIPY and minversion(scipy, '0.14') ASTROPY_LT_20 = not minversion(astropy, '2.0') # GLOBAL VARIABLES _vspec = None # Loaded in test_load_vspec() def setup_module(module): # https://github.com/astropy/astropy/issues/6383 if not ASTROPY_LT_20: import astropy.constants as const from astropy.constants import si, astropyconst13 const.sigma_sb = si.sigma_sb = astropyconst13.sigma_sb const.h = si.h = astropyconst13.h const.k_B = si.k_B = astropyconst13.k_B
tested, so this simply confirms that the add-on in CxoTime works. """ import pytest import numpy as np from astropy.utils import minversion from .. import CxoTime try: from Chandra.Time import DateTime HAS_DATETIME = True except ImportError: HAS_DATETIME = False ASTROPY_LT_1_1 = not minversion('astropy', '1.1') def test_cxotime_basic(): t = CxoTime(1) assert t.format == 'secs' assert t.scale == 'utc' assert np.allclose(t.secs, 1.0, rtol=1e-10, atol=0) assert t.tt.date == '1998:001:00:00:01.000' # Multi-dim input t = CxoTime([[1, 2], [3, 4]]) assert t.shape == (2, 2) t_date = [['1998:001:00:00:01.000', '1998:001:00:00:02.000'], ['1998:001:00:00:03.000', '1998:001:00:00:04.000']] assert np.all(t.tt.date == t_date)
import os import warnings # THIRD-PARTY import numpy as np from astropy import wcs from astropy.convolution import convolve_fft, Box2DKernel from astropy.io import ascii, fits from astropy.stats import biweight_location from astropy.stats import sigma_clip from astropy.utils import minversion from astropy.utils.exceptions import AstropyUserWarning from scipy.interpolate import griddata from scipy.ndimage import zoom ASTROPY_LT_3_1 = not minversion('astropy', '3.1') GINGA_LT_3 = not minversion('ginga', '3.0') __all__ = ['calc_stat', 'interpolate_badpix', 'find_ext', 'DQParser', 'scale_wcs', 'scale_image', 'scale_image_with_dq'] def calc_stat(data, sigma=1.8, niter=10, algorithm='median'): """Calculate statistics for given data. Parameters ---------- data : ndarray Data to be calculated from. sigma : float
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function try: import astropy except ImportError: HAS_ASTROPY = False else: HAS_ASTROPY = True from astropy.modeling import mappings from astropy.utils import minversion ASTROPY_12 = minversion(astropy, "1.2") from ...asdftypes import AsdfType from ... import tagged from ... import yamlutil __all__ = ['TransformType', 'IdentityType', 'ConstantType', 'DomainType'] class TransformType(AsdfType): requires = ['astropy'] @classmethod def _from_tree_base_transform_members(cls, model, node, ctx): if 'inverse' in node: model.inverse = yamlutil.tagged_tree_to_custom_tree( node['inverse'], ctx)
from astropy import units as u from astropy.utils import minversion from astropy.utils.data import get_pkg_data_filename # LOCAL from .. import exceptions from ..thermal import ThermalSpectralElement try: import scipy except ImportError: HAS_SCIPY = False else: HAS_SCIPY = True HAS_SCIPY = HAS_SCIPY and minversion(scipy, '0.14') ASTROPY_LT_20 = not minversion(astropy, '2.0') def setup_module(module): # https://github.com/astropy/astropy/issues/6383 if not ASTROPY_LT_20: import astropy.constants as const from astropy.constants import si, astropyconst13 const.sigma_sb = si.sigma_sb = astropyconst13.sigma_sb const.h = si.h = astropyconst13.h const.k_B = si.k_B = astropyconst13.k_B def teardown_module(module):
import astropy.io.fits as fits import numpy as np from astropy.tests.helper import catch_warnings from astropy.utils import minversion from astropy.utils.exceptions import AstropyUserWarning from astropy.nddata import CCDData from ..image_collection import ImageFileCollection _filters = [] _original_dir = '' _ASTROPY_LT_1_3 = not minversion("astropy", "1.3") def test_fits_summary(triage_setup): keywords = ['imagetyp', 'filter'] ic = ImageFileCollection(triage_setup.test_dir, keywords=keywords) summary = ic._fits_summary(header_keywords=keywords) assert len(summary['file']) == triage_setup.n_test['files'] for keyword in keywords: assert len(summary[keyword]) == triage_setup.n_test['files'] # explicit conversion to array is needed to avoid astropy Table bug in # 0.2.4 no_filter_no_object_row = np.array(summary['file'] == 'no_filter_no_object_bias.fit') # there should be no filter keyword in the bias file
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This is a collection of monkey patches and workarounds for bugs in earlier versions of Numpy. """ from astropy.utils import minversion __all__ = ['NUMPY_LT_1_14', 'NUMPY_LT_1_14_1', 'NUMPY_LT_1_14_2', 'NUMPY_LT_1_16'] # TODO: It might also be nice to have aliases to these named for specific # features/bugs we're checking for (ex: # astropy.table.table._BROKEN_UNICODE_TABLE_SORT) NUMPY_LT_1_14 = not minversion('numpy', '1.14') NUMPY_LT_1_14_1 = not minversion('numpy', '1.14.1') NUMPY_LT_1_14_2 = not minversion('numpy', '1.14.2') NUMPY_LT_1_16 = not minversion('numpy', '1.16')
import numpy as np from numpy.random import randn, normal from numpy.testing import assert_equal from numpy.testing.utils import assert_allclose from astropy.utils import minversion try: import scipy # pylint: disable=W0611 except ImportError: HAS_SCIPY = False SCIPY_LT_0_14 = True else: HAS_SCIPY = True SCIPY_LT_0_14 = not minversion(scipy, '0.14.0') try: import mpmath # pylint: disable=W0611 except ImportError: HAS_MPMATH = False else: HAS_MPMATH = True from ...tests.helper import pytest from ...extern.six.moves import range from .. import funcs # These are not part of __all__ because they are just the lower level versions # of poisson_upper_limit
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function import numpy as np try: import astropy except ImportError: HAS_ASTROPY = False test_models = [] else: HAS_ASTROPY = True from astropy.utils import minversion ASTROPY_13 = minversion(astropy, "1.3") from astropy.modeling import models as astmodels test_models = [astmodels.Identity(2), astmodels.Polynomial1D(2, c0=1, c1=2, c2=3), astmodels.Polynomial2D(1, c0_0=1, c0_1=2, c1_0=3), astmodels.Shift(2.), astmodels.Scale(3.4), astmodels.RotateNative2Celestial(5.63, -72.5, 180), astmodels.RotateCelestial2Native(5.63, -72.5, 180), astmodels.EulerAngleRotation(23, 14, 2.3, axes_order='xzx'), astmodels.Mapping((0, 1), n_inputs=3)] import pytest from ....tests import helpers from .... import util from ..basic import DomainType
import numpy as np from astropy.time import Time, TimeDelta from astropy import units as u from astropy import coordinates as coords from astropy.utils import minversion from astropy.table import SerializedColumn try: import yaml except ImportError: raise ImportError('`import yaml` failed, PyYAML package is required for YAML') YAML_LT_3_12 = not minversion(yaml, '3.12') __all__ = ['AstropyLoader', 'AstropyDumper', 'load', 'load_all', 'dump'] def _unit_representer(dumper, obj): out = {'unit': str(obj.to_string())} return dumper.represent_mapping('!astropy.units.Unit', out) def _unit_constructor(loader, node): map = loader.construct_mapping(node) return u.Unit(map['unit'])
from astropy.tests.helper import pytest from astropy.utils import minversion from astropy.utils.data import get_pkg_data_filename # LOCAL from .. import specio, units from ..models import BlackBody1D, ConstFlux1D, Empirical1D, PowerLawFlux1D try: import scipy except ImportError: HAS_SCIPY = False else: HAS_SCIPY = True HAS_SCIPY = HAS_SCIPY and minversion(scipy, '0.14') class TestBlackBody1D(object): """Test BlackBody1D model.""" def setup_class(self): self.m1 = BlackBody1D(temperature=5500) def test_lambda_max(self): np.testing.assert_allclose(self.m1.lambda_max, 5268.67, rtol=1e-5) def test_sampleset(self): f1 = self.m1(self.m1.sampleset()) assert f1[0] == 0 assert f1[-1] < self.m1(self.m1.lambda_max) * 0.05
from __future__ import (absolute_import, division, print_function, unicode_literals) import os import pytest import astropy.units as u from astropy.tests.helper import assert_quantity_allclose from astropy.utils import minversion from astropy.coordinates import SkyCoord from ...nasa_exoplanet_archive import NasaExoplanetArchive APY_LT12 = not minversion('astropy', '1.2') LOCAL_TABLE_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data', 'nasa_exoplanet_archive.csv') @pytest.mark.remote_data @pytest.mark.skipif('APY_LT12') def test_hd209458b_exoplanets_archive_apy_lt12(): # Testing intentionally un-stripped string: params = NasaExoplanetArchive.query_planet('HD 209458 b ') assert_quantity_allclose(params['pl_radj'], 1.320 * u.Unit('R_jup'), atol=0.1 * u.Unit('R_jup')) @pytest.mark.remote_data @pytest.mark.skipif('not APY_LT12') def test_hd209458b_exoplanets_archive_apy_gt12(): # Testing intentionally un-stripped string: with pytest.raises(ValueError):