hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
37a7f66818ba204421179375452a66cf407ae32a0f470acfad52151de98cfbca | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# This file was automatically generated from ply. To re-generate this file,
# remove it from this folder, then build astropy and run the tests in-place:
#
# python setup.py build_ext --inplace
# pytest astropy/coordinates
#
# You can then commit the changes to this file.
# angle_parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'COLON DEGREE EASTWEST HOUR MINUTE NORTHSOUTH SECOND SIGN SIMPLE_UNIT UFLOAT UINT\n angle : sign hms eastwest\n | sign dms dir\n | sign arcsecond dir\n | sign arcminute dir\n | sign simple dir\n \n sign : SIGN\n |\n \n eastwest : EASTWEST\n |\n \n dir : EASTWEST\n | NORTHSOUTH\n |\n \n ufloat : UFLOAT\n | UINT\n \n colon : UINT COLON ufloat\n | UINT COLON UINT COLON ufloat\n \n spaced : UINT ufloat\n | UINT UINT ufloat\n \n generic : colon\n | spaced\n | ufloat\n \n hms : UINT HOUR\n | UINT HOUR ufloat\n | UINT HOUR UINT MINUTE\n | UINT HOUR UFLOAT MINUTE\n | UINT HOUR UINT MINUTE ufloat\n | UINT HOUR UINT MINUTE ufloat SECOND\n | generic HOUR\n \n dms : UINT DEGREE\n | UINT DEGREE ufloat\n | UINT DEGREE UINT MINUTE\n | UINT DEGREE UFLOAT MINUTE\n | UINT DEGREE UINT MINUTE ufloat\n | UINT DEGREE UINT MINUTE ufloat SECOND\n | generic DEGREE\n \n simple : generic\n | generic SIMPLE_UNIT\n \n arcsecond : generic SECOND\n \n arcminute : generic MINUTE\n '
_lr_action_items = {'SIGN':([0,],[3,]),'UINT':([0,2,3,9,23,24,26,27,43,45,47,],[-7,9,-6,23,33,35,38,41,33,33,33,]),'UFLOAT':([0,2,3,9,23,24,26,27,43,45,47,],[-7,11,-6,11,11,37,40,11,11,11,11,]),'$end':([1,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,48,49,50,51,52,],[0,-9,-12,-12,-12,-12,-14,-21,-13,-36,-19,-20,-1,-8,-2,-10,-11,-3,-4,-5,-14,-22,-17,-29,-28,-35,-38,-39,-37,-14,-18,-14,-23,-13,-14,-30,-13,-14,-15,-24,-25,-31,-32,-26,-33,-16,-27,-34,]),'EASTWEST':([4,5,6,7,8,9,10,11,12,13,14,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,48,49,50,51,52,],[16,18,18,18,18,-14,-21,-13,-36,-19,-20,-14,-22,-17,-29,-28,-35,-38,-39,-37,-14,-18,-14,-23,-13,-14,-30,-13,-14,-15,-24,-25,-31,-32,-26,-33,-16,-27,-34,]),'NORTHSOUTH':([5,6,7,8,9,10,11,12,13,14,23,25,26,29,30,31,32,33,34,38,39,40,41,42,45,46,49,50,52,],[19,19,19,19,-14,-21,-13,-36,-19,-20,-14,-17,-29,-35,-38,-39,-37,-14,-18,-14,-30,-13,-14,-15,-31,-32,-33,-16,-34,]),'HOUR':([9,10,11,12,13,14,23,25,33,34,41,42,50,],[24,-21,-13,28,-19,-20,-14,-17,-14,-18,-14,-15,-16,]),'DEGREE':([9,10,11,12,13,14,23,25,33,34,41,42,50,],[26,-21,-13,29,-19,-20,-14,-17,-14,-18,-14,-15,-16,]),'COLON':([9,41,],[27,47,]),'SECOND':([9,10,11,12,13,14,23,25,33,34,41,42,48,49,50,],[-14,-21,-13,30,-19,-20,-14,-17,-14,-18,-14,-15,51,52,-16,]),'MINUTE':([9,10,11,12,13,14,23,25,33,34,35,37,38,40,41,42,50,],[-14,-21,-13,31,-19,-20,-14,-17,-14,-18,43,44,45,46,-14,-15,-16,]),'SIMPLE_UNIT':([9,10,11,12,13,14,23,25,33,34,41,42,50,],[-14,-21,-13,32,-19,-20,-14,-17,-14,-18,-14,-15,-16,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'angle':([0,],[1,]),'sign':([0,],[2,]),'hms':([2,],[4,]),'dms':([2,],[5,]),'arcsecond':([2,],[6,]),'arcminute':([2,],[7,]),'simple':([2,],[8,]),'ufloat':([2,9,23,24,26,27,43,45,47,],[10,25,34,36,39,42,48,49,50,]),'generic':([2,],[12,]),'colon':([2,],[13,]),'spaced':([2,],[14,]),'eastwest':([4,],[15,]),'dir':([5,6,7,8,],[17,20,21,22,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> angle","S'",1,None,None,None),
('angle -> sign hms eastwest','angle',3,'p_angle','angle_formats.py',159),
('angle -> sign dms dir','angle',3,'p_angle','angle_formats.py',160),
('angle -> sign arcsecond dir','angle',3,'p_angle','angle_formats.py',161),
('angle -> sign arcminute dir','angle',3,'p_angle','angle_formats.py',162),
('angle -> sign simple dir','angle',3,'p_angle','angle_formats.py',163),
('sign -> SIGN','sign',1,'p_sign','angle_formats.py',174),
('sign -> <empty>','sign',0,'p_sign','angle_formats.py',175),
('eastwest -> EASTWEST','eastwest',1,'p_eastwest','angle_formats.py',184),
('eastwest -> <empty>','eastwest',0,'p_eastwest','angle_formats.py',185),
('dir -> EASTWEST','dir',1,'p_dir','angle_formats.py',194),
('dir -> NORTHSOUTH','dir',1,'p_dir','angle_formats.py',195),
('dir -> <empty>','dir',0,'p_dir','angle_formats.py',196),
('ufloat -> UFLOAT','ufloat',1,'p_ufloat','angle_formats.py',205),
('ufloat -> UINT','ufloat',1,'p_ufloat','angle_formats.py',206),
('colon -> UINT COLON ufloat','colon',3,'p_colon','angle_formats.py',212),
('colon -> UINT COLON UINT COLON ufloat','colon',5,'p_colon','angle_formats.py',213),
('spaced -> UINT ufloat','spaced',2,'p_spaced','angle_formats.py',222),
('spaced -> UINT UINT ufloat','spaced',3,'p_spaced','angle_formats.py',223),
('generic -> colon','generic',1,'p_generic','angle_formats.py',232),
('generic -> spaced','generic',1,'p_generic','angle_formats.py',233),
('generic -> ufloat','generic',1,'p_generic','angle_formats.py',234),
('hms -> UINT HOUR','hms',2,'p_hms','angle_formats.py',240),
('hms -> UINT HOUR ufloat','hms',3,'p_hms','angle_formats.py',241),
('hms -> UINT HOUR UINT MINUTE','hms',4,'p_hms','angle_formats.py',242),
('hms -> UINT HOUR UFLOAT MINUTE','hms',4,'p_hms','angle_formats.py',243),
('hms -> UINT HOUR UINT MINUTE ufloat','hms',5,'p_hms','angle_formats.py',244),
('hms -> UINT HOUR UINT MINUTE ufloat SECOND','hms',6,'p_hms','angle_formats.py',245),
('hms -> generic HOUR','hms',2,'p_hms','angle_formats.py',246),
('dms -> UINT DEGREE','dms',2,'p_dms','angle_formats.py',257),
('dms -> UINT DEGREE ufloat','dms',3,'p_dms','angle_formats.py',258),
('dms -> UINT DEGREE UINT MINUTE','dms',4,'p_dms','angle_formats.py',259),
('dms -> UINT DEGREE UFLOAT MINUTE','dms',4,'p_dms','angle_formats.py',260),
('dms -> UINT DEGREE UINT MINUTE ufloat','dms',5,'p_dms','angle_formats.py',261),
('dms -> UINT DEGREE UINT MINUTE ufloat SECOND','dms',6,'p_dms','angle_formats.py',262),
('dms -> generic DEGREE','dms',2,'p_dms','angle_formats.py',263),
('simple -> generic','simple',1,'p_simple','angle_formats.py',274),
('simple -> generic SIMPLE_UNIT','simple',2,'p_simple','angle_formats.py',275),
('arcsecond -> generic SECOND','arcsecond',2,'p_arcsecond','angle_formats.py',284),
('arcminute -> generic MINUTE','arcminute',2,'p_arcminute','angle_formats.py',290),
]
|
239ed5d4dda1b28507dc79048a61e525d61e98749eaa57f4b2ed76e9fea61fcf | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains standard functions for earth orientation, such as
precession and nutation.
This module is (currently) not intended to be part of the public API, but
is instead primarily for internal use in `coordinates`
"""
import numpy as np
from astropy.time import Time
from astropy import units as u
from .matrix_utilities import rotation_matrix, matrix_product, matrix_transpose
jd1950 = Time('B1950').jd
jd2000 = Time('J2000').jd
_asecperrad = u.radian.to(u.arcsec)
def eccentricity(jd):
"""
Eccentricity of the Earth's orbit at the requested Julian Date.
Parameters
----------
jd : scalar or array-like
Julian date at which to compute the eccentricity
Returns
-------
eccentricity : scalar or array
The eccentricity (or array of eccentricities)
References
----------
* Explanatory Supplement to the Astronomical Almanac: P. Kenneth
Seidelmann (ed), University Science Books (1992).
"""
T = (jd - jd1950) / 36525.0
p = (-0.000000126, - 0.00004193, 0.01673011)
return np.polyval(p, T)
def mean_lon_of_perigee(jd):
"""
Computes the mean longitude of perigee of the Earth's orbit at the
requested Julian Date.
Parameters
----------
jd : scalar or array-like
Julian date at which to compute the mean longitude of perigee
Returns
-------
mean_lon_of_perigee : scalar or array
Mean longitude of perigee in degrees (or array of mean longitudes)
References
----------
* Explanatory Supplement to the Astronomical Almanac: P. Kenneth
Seidelmann (ed), University Science Books (1992).
"""
T = (jd - jd1950) / 36525.0
p = (0.012, 1.65, 6190.67, 1015489.951)
return np.polyval(p, T) / 3600.
def obliquity(jd, algorithm=2006):
"""
Computes the obliquity of the Earth at the requested Julian Date.
Parameters
----------
jd : scalar or array-like
Julian date at which to compute the obliquity
algorithm : int
Year of algorithm based on IAU adoption. Can be 2006, 2000 or 1980. The
2006 algorithm is mentioned in Circular 179, but the canonical reference
for the IAU adoption is apparently Hilton et al. 06 is composed of the
1980 algorithm with a precession-rate correction due to the 2000
precession models, and a description of the 1980 algorithm can be found
in the Explanatory Supplement to the Astronomical Almanac.
Returns
-------
obliquity : scalar or array
Mean obliquity in degrees (or array of obliquities)
References
----------
* Hilton, J. et al., 2006, Celest.Mech.Dyn.Astron. 94, 351. 2000
* USNO Circular 179
* Explanatory Supplement to the Astronomical Almanac: P. Kenneth
Seidelmann (ed), University Science Books (1992).
"""
T = (jd - jd2000) / 36525.0
if algorithm == 2006:
p = (-0.0000000434, -0.000000576, 0.00200340, -0.0001831, -46.836769, 84381.406)
corr = 0
elif algorithm == 2000:
p = (0.001813, -0.00059, -46.8150, 84381.448)
corr = -0.02524 * T
elif algorithm == 1980:
p = (0.001813, -0.00059, -46.8150, 84381.448)
corr = 0
else:
raise ValueError('invalid algorithm year for computing obliquity')
return (np.polyval(p, T) + corr) / 3600.
# TODO: replace this with SOFA equivalent
def precession_matrix_Capitaine(fromepoch, toepoch):
"""
Computes the precession matrix from one Julian epoch to another.
The exact method is based on Capitaine et al. 2003, which should
match the IAU 2006 standard.
Parameters
----------
fromepoch : `~astropy.time.Time`
The epoch to precess from.
toepoch : `~astropy.time.Time`
The epoch to precess to.
Returns
-------
pmatrix : 3x3 array
Precession matrix to get from ``fromepoch`` to ``toepoch``
References
----------
USNO Circular 179
"""
mat_fromto2000 = matrix_transpose(
_precess_from_J2000_Capitaine(fromepoch.jyear))
mat_2000toto = _precess_from_J2000_Capitaine(toepoch.jyear)
return np.dot(mat_2000toto, mat_fromto2000)
def _precess_from_J2000_Capitaine(epoch):
"""
Computes the precession matrix from J2000 to the given Julian Epoch.
Expression from from Capitaine et al. 2003 as expressed in the USNO
Circular 179. This should match the IAU 2006 standard from SOFA.
Parameters
----------
epoch : scalar
The epoch as a Julian year number (e.g. J2000 is 2000.0)
"""
T = (epoch - 2000.0) / 100.0
# from USNO circular
pzeta = (-0.0000003173, -0.000005971, 0.01801828, 0.2988499, 2306.083227, 2.650545)
pz = (-0.0000002904, -0.000028596, 0.01826837, 1.0927348, 2306.077181, -2.650545)
ptheta = (-0.0000001274, -0.000007089, -0.04182264, -0.4294934, 2004.191903, 0)
zeta = np.polyval(pzeta, T) / 3600.0
z = np.polyval(pz, T) / 3600.0
theta = np.polyval(ptheta, T) / 3600.0
return matrix_product(rotation_matrix(-z, 'z'),
rotation_matrix(theta, 'y'),
rotation_matrix(-zeta, 'z'))
def _precession_matrix_besselian(epoch1, epoch2):
"""
Computes the precession matrix from one Besselian epoch to another using
Newcomb's method.
``epoch1`` and ``epoch2`` are in Besselian year numbers.
"""
# tropical years
t1 = (epoch1 - 1850.0) / 1000.0
t2 = (epoch2 - 1850.0) / 1000.0
dt = t2 - t1
zeta1 = 23035.545 + t1 * 139.720 + 0.060 * t1 * t1
zeta2 = 30.240 - 0.27 * t1
zeta3 = 17.995
pzeta = (zeta3, zeta2, zeta1, 0)
zeta = np.polyval(pzeta, dt) / 3600
z1 = 23035.545 + t1 * 139.720 + 0.060 * t1 * t1
z2 = 109.480 + 0.39 * t1
z3 = 18.325
pz = (z3, z2, z1, 0)
z = np.polyval(pz, dt) / 3600
theta1 = 20051.12 - 85.29 * t1 - 0.37 * t1 * t1
theta2 = -42.65 - 0.37 * t1
theta3 = -41.8
ptheta = (theta3, theta2, theta1, 0)
theta = np.polyval(ptheta, dt) / 3600
return matrix_product(rotation_matrix(-z, 'z'),
rotation_matrix(theta, 'y'),
rotation_matrix(-zeta, 'z'))
def _load_nutation_data(datastr, seriestype):
"""
Loads nutation series from data stored in string form.
Seriestype can be 'lunisolar' or 'planetary'
"""
if seriestype == 'lunisolar':
dtypes = [('nl', int),
('nlp', int),
('nF', int),
('nD', int),
('nOm', int),
('ps', float),
('pst', float),
('pc', float),
('ec', float),
('ect', float),
('es', float)]
elif seriestype == 'planetary':
dtypes = [('nl', int),
('nF', int),
('nD', int),
('nOm', int),
('nme', int),
('nve', int),
('nea', int),
('nma', int),
('nju', int),
('nsa', int),
('nur', int),
('nne', int),
('npa', int),
('sp', int),
('cp', int),
('se', int),
('ce', int)]
else:
raise ValueError('requested invalid nutation series type')
lines = [l for l in datastr.split('\n')
if not l.startswith('#') if not l.strip() == '']
lists = [[] for _ in dtypes]
for l in lines:
for i, e in enumerate(l.split(' ')):
lists[i].append(dtypes[i][1](e))
return np.rec.fromarrays(lists, names=[e[0] for e in dtypes])
_nut_data_00b = """
#l lprime F D Omega longitude_sin longitude_sin*t longitude_cos obliquity_cos obliquity_cos*t,obliquity_sin
0 0 0 0 1 -172064161.0 -174666.0 33386.0 92052331.0 9086.0 15377.0
0 0 2 -2 2 -13170906.0 -1675.0 -13696.0 5730336.0 -3015.0 -4587.0
0 0 2 0 2 -2276413.0 -234.0 2796.0 978459.0 -485.0 1374.0
0 0 0 0 2 2074554.0 207.0 -698.0 -897492.0 470.0 -291.0
0 1 0 0 0 1475877.0 -3633.0 11817.0 73871.0 -184.0 -1924.0
0 1 2 -2 2 -516821.0 1226.0 -524.0 224386.0 -677.0 -174.0
1 0 0 0 0 711159.0 73.0 -872.0 -6750.0 0.0 358.0
0 0 2 0 1 -387298.0 -367.0 380.0 200728.0 18.0 318.0
1 0 2 0 2 -301461.0 -36.0 816.0 129025.0 -63.0 367.0
0 -1 2 -2 2 215829.0 -494.0 111.0 -95929.0 299.0 132.0
0 0 2 -2 1 128227.0 137.0 181.0 -68982.0 -9.0 39.0
-1 0 2 0 2 123457.0 11.0 19.0 -53311.0 32.0 -4.0
-1 0 0 2 0 156994.0 10.0 -168.0 -1235.0 0.0 82.0
1 0 0 0 1 63110.0 63.0 27.0 -33228.0 0.0 -9.0
-1 0 0 0 1 -57976.0 -63.0 -189.0 31429.0 0.0 -75.0
-1 0 2 2 2 -59641.0 -11.0 149.0 25543.0 -11.0 66.0
1 0 2 0 1 -51613.0 -42.0 129.0 26366.0 0.0 78.0
-2 0 2 0 1 45893.0 50.0 31.0 -24236.0 -10.0 20.0
0 0 0 2 0 63384.0 11.0 -150.0 -1220.0 0.0 29.0
0 0 2 2 2 -38571.0 -1.0 158.0 16452.0 -11.0 68.0
0 -2 2 -2 2 32481.0 0.0 0.0 -13870.0 0.0 0.0
-2 0 0 2 0 -47722.0 0.0 -18.0 477.0 0.0 -25.0
2 0 2 0 2 -31046.0 -1.0 131.0 13238.0 -11.0 59.0
1 0 2 -2 2 28593.0 0.0 -1.0 -12338.0 10.0 -3.0
-1 0 2 0 1 20441.0 21.0 10.0 -10758.0 0.0 -3.0
2 0 0 0 0 29243.0 0.0 -74.0 -609.0 0.0 13.0
0 0 2 0 0 25887.0 0.0 -66.0 -550.0 0.0 11.0
0 1 0 0 1 -14053.0 -25.0 79.0 8551.0 -2.0 -45.0
-1 0 0 2 1 15164.0 10.0 11.0 -8001.0 0.0 -1.0
0 2 2 -2 2 -15794.0 72.0 -16.0 6850.0 -42.0 -5.0
0 0 -2 2 0 21783.0 0.0 13.0 -167.0 0.0 13.0
1 0 0 -2 1 -12873.0 -10.0 -37.0 6953.0 0.0 -14.0
0 -1 0 0 1 -12654.0 11.0 63.0 6415.0 0.0 26.0
-1 0 2 2 1 -10204.0 0.0 25.0 5222.0 0.0 15.0
0 2 0 0 0 16707.0 -85.0 -10.0 168.0 -1.0 10.0
1 0 2 2 2 -7691.0 0.0 44.0 3268.0 0.0 19.0
-2 0 2 0 0 -11024.0 0.0 -14.0 104.0 0.0 2.0
0 1 2 0 2 7566.0 -21.0 -11.0 -3250.0 0.0 -5.0
0 0 2 2 1 -6637.0 -11.0 25.0 3353.0 0.0 14.0
0 -1 2 0 2 -7141.0 21.0 8.0 3070.0 0.0 4.0
0 0 0 2 1 -6302.0 -11.0 2.0 3272.0 0.0 4.0
1 0 2 -2 1 5800.0 10.0 2.0 -3045.0 0.0 -1.0
2 0 2 -2 2 6443.0 0.0 -7.0 -2768.0 0.0 -4.0
-2 0 0 2 1 -5774.0 -11.0 -15.0 3041.0 0.0 -5.0
2 0 2 0 1 -5350.0 0.0 21.0 2695.0 0.0 12.0
0 -1 2 -2 1 -4752.0 -11.0 -3.0 2719.0 0.0 -3.0
0 0 0 -2 1 -4940.0 -11.0 -21.0 2720.0 0.0 -9.0
-1 -1 0 2 0 7350.0 0.0 -8.0 -51.0 0.0 4.0
2 0 0 -2 1 4065.0 0.0 6.0 -2206.0 0.0 1.0
1 0 0 2 0 6579.0 0.0 -24.0 -199.0 0.0 2.0
0 1 2 -2 1 3579.0 0.0 5.0 -1900.0 0.0 1.0
1 -1 0 0 0 4725.0 0.0 -6.0 -41.0 0.0 3.0
-2 0 2 0 2 -3075.0 0.0 -2.0 1313.0 0.0 -1.0
3 0 2 0 2 -2904.0 0.0 15.0 1233.0 0.0 7.0
0 -1 0 2 0 4348.0 0.0 -10.0 -81.0 0.0 2.0
1 -1 2 0 2 -2878.0 0.0 8.0 1232.0 0.0 4.0
0 0 0 1 0 -4230.0 0.0 5.0 -20.0 0.0 -2.0
-1 -1 2 2 2 -2819.0 0.0 7.0 1207.0 0.0 3.0
-1 0 2 0 0 -4056.0 0.0 5.0 40.0 0.0 -2.0
0 -1 2 2 2 -2647.0 0.0 11.0 1129.0 0.0 5.0
-2 0 0 0 1 -2294.0 0.0 -10.0 1266.0 0.0 -4.0
1 1 2 0 2 2481.0 0.0 -7.0 -1062.0 0.0 -3.0
2 0 0 0 1 2179.0 0.0 -2.0 -1129.0 0.0 -2.0
-1 1 0 1 0 3276.0 0.0 1.0 -9.0 0.0 0.0
1 1 0 0 0 -3389.0 0.0 5.0 35.0 0.0 -2.0
1 0 2 0 0 3339.0 0.0 -13.0 -107.0 0.0 1.0
-1 0 2 -2 1 -1987.0 0.0 -6.0 1073.0 0.0 -2.0
1 0 0 0 2 -1981.0 0.0 0.0 854.0 0.0 0.0
-1 0 0 1 0 4026.0 0.0 -353.0 -553.0 0.0 -139.0
0 0 2 1 2 1660.0 0.0 -5.0 -710.0 0.0 -2.0
-1 0 2 4 2 -1521.0 0.0 9.0 647.0 0.0 4.0
-1 1 0 1 1 1314.0 0.0 0.0 -700.0 0.0 0.0
0 -2 2 -2 1 -1283.0 0.0 0.0 672.0 0.0 0.0
1 0 2 2 1 -1331.0 0.0 8.0 663.0 0.0 4.0
-2 0 2 2 2 1383.0 0.0 -2.0 -594.0 0.0 -2.0
-1 0 0 0 2 1405.0 0.0 4.0 -610.0 0.0 2.0
1 1 2 -2 2 1290.0 0.0 0.0 -556.0 0.0 0.0
"""[1:-1]
_nut_data_00b = _load_nutation_data(_nut_data_00b, 'lunisolar')
# TODO: replace w/SOFA equivalent
def nutation_components2000B(jd):
"""
Computes nutation components following the IAU 2000B specification
Parameters
----------
jd : scalar
epoch at which to compute the nutation components as a JD
Returns
-------
eps : float
epsilon in radians
dpsi : float
dpsi in radians
deps : float
depsilon in raidans
"""
epsa = np.radians(obliquity(jd, 2000))
t = (jd - jd2000) / 36525
# Fundamental (Delaunay) arguments from Simon et al. (1994) via SOFA
# Mean anomaly of moon
el = ((485868.249036 + 1717915923.2178 * t) % 1296000) / _asecperrad
# Mean anomaly of sun
elp = ((1287104.79305 + 129596581.0481 * t) % 1296000) / _asecperrad
# Mean argument of the latitude of Moon
F = ((335779.526232 + 1739527262.8478 * t) % 1296000) / _asecperrad
# Mean elongation of the Moon from Sun
D = ((1072260.70369 + 1602961601.2090 * t) % 1296000) / _asecperrad
# Mean longitude of the ascending node of Moon
Om = ((450160.398036 + -6962890.5431 * t) % 1296000) / _asecperrad
# compute nutation series using array loaded from data directory
dat = _nut_data_00b
arg = dat.nl * el + dat.nlp * elp + dat.nF * F + dat.nD * D + dat.nOm * Om
sarg = np.sin(arg)
carg = np.cos(arg)
p1u_asecperrad = _asecperrad * 1e7 # 0.1 microasrcsecperrad
dpsils = np.sum((dat.ps + dat.pst * t) * sarg + dat.pc * carg) / p1u_asecperrad
depsls = np.sum((dat.ec + dat.ect * t) * carg + dat.es * sarg) / p1u_asecperrad
# fixed offset in place of planetary tersm
m_asecperrad = _asecperrad * 1e3 # milliarcsec per rad
dpsipl = -0.135 / m_asecperrad
depspl = 0.388 / m_asecperrad
return epsa, dpsils + dpsipl, depsls + depspl # all in radians
def nutation_matrix(epoch):
"""
Nutation matrix generated from nutation components.
Matrix converts from mean coordinate to true coordinate as
r_true = M * r_mean
"""
# TODO: implement higher precision 2006/2000A model if requested/needed
epsa, dpsi, deps = nutation_components2000B(epoch.jd) # all in radians
return matrix_product(rotation_matrix(-(epsa + deps), 'x', False),
rotation_matrix(-dpsi, 'z', False),
rotation_matrix(epsa, 'x', False))
|
a968b26d0a0e06991f74d359255af0ac35715ce2d2a152ce4cbe0de5fd4c0c5c | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains modules and packages for interpreting data storage
formats used by and in astropy.
"""
|
6bd1e09b154a60e342c88e4d9fd6c5f48ff690cc8d1aaf410d8b736d0a56bb30 | """Implements the wrapper for the Astropy test runner.
This is for backward-compatibility for other downstream packages and can be removed
once astropy-helpers has reached end-of-life.
"""
import os
import stat
import shutil
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from setuptools import Command
from astropy.logger import log
@contextmanager
def _suppress_stdout():
'''
A context manager to temporarily disable stdout.
Used later when installing a temporary copy of astropy to avoid a
very verbose output.
'''
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
class FixRemoteDataOption(type):
"""
This metaclass is used to catch cases where the user is running the tests
with --remote-data. We've now changed the --remote-data option so that it
takes arguments, but we still want --remote-data to work as before and to
enable all remote tests. With this metaclass, we can modify sys.argv
before setuptools try to parse the command-line options.
"""
def __init__(cls, name, bases, dct):
try:
idx = sys.argv.index('--remote-data')
except ValueError:
pass
else:
sys.argv[idx] = '--remote-data=any'
try:
idx = sys.argv.index('-R')
except ValueError:
pass
else:
sys.argv[idx] = '-R=any'
return super().__init__(name, bases, dct)
class AstropyTest(Command, metaclass=FixRemoteDataOption):
description = 'Run the tests for this package'
user_options = [
('package=', 'P',
"The name of a specific package to test, e.g. 'io.fits' or 'utils'. "
"Accepts comma separated string to specify multiple packages. "
"If nothing is specified, all default tests are run."),
('test-path=', 't',
'Specify a test location by path. If a relative path to a .py file, '
'it is relative to the built package, so e.g., a leading "astropy/" '
'is necessary. If a relative path to a .rst file, it is relative to '
'the directory *below* the --docs-path directory, so a leading '
'"docs/" is usually necessary. May also be an absolute path.'),
('verbose-results', 'V',
'Turn on verbose output from pytest.'),
('plugins=', 'p',
'Plugins to enable when running pytest.'),
('pastebin=', 'b',
"Enable pytest pastebin output. Either 'all' or 'failed'."),
('args=', 'a',
'Additional arguments to be passed to pytest.'),
('remote-data=', 'R', 'Run tests that download remote data. Should be '
'one of none/astropy/any (defaults to none).'),
('pep8', '8',
'Enable PEP8 checking and disable regular tests. '
'Requires the pytest-pep8 plugin.'),
('pdb', 'd',
'Start the interactive Python debugger on errors.'),
('coverage', 'c',
'Create a coverage report. Requires the coverage package.'),
('open-files', 'o', 'Fail if any tests leave files open. Requires the '
'psutil package.'),
('parallel=', 'j',
'Run the tests in parallel on the specified number of '
'CPUs. If "auto", all the cores on the machine will be '
'used. Requires the pytest-xdist plugin.'),
('docs-path=', None,
'The path to the documentation .rst files. If not provided, and '
'the current directory contains a directory called "docs", that '
'will be used.'),
('skip-docs', None,
"Don't test the documentation .rst files."),
('repeat=', None,
'How many times to repeat each test (can be used to check for '
'sporadic failures).'),
('temp-root=', None,
'The root directory in which to create the temporary testing files. '
'If unspecified the system default is used (e.g. /tmp) as explained '
'in the documentation for tempfile.mkstemp.'),
('verbose-install', None,
'Turn on terminal output from the installation of astropy in a '
'temporary folder.'),
('readonly', None,
'Make the temporary installation being tested read-only.')
]
package_name = ''
def initialize_options(self):
self.package = None
self.test_path = None
self.verbose_results = False
self.plugins = None
self.pastebin = None
self.args = None
self.remote_data = 'none'
self.pep8 = False
self.pdb = False
self.coverage = False
self.open_files = False
self.parallel = 0
self.docs_path = None
self.skip_docs = False
self.repeat = None
self.temp_root = None
self.verbose_install = False
self.readonly = False
def finalize_options(self):
# Normally we would validate the options here, but that's handled in
# run_tests
pass
def generate_testing_command(self):
"""
Build a Python script to run the tests.
"""
cmd_pre = '' # Commands to run before the test function
cmd_post = '' # Commands to run after the test function
if self.coverage:
pre, post = self._generate_coverage_commands()
cmd_pre += pre
cmd_post += post
set_flag = "import builtins; builtins._ASTROPY_TEST_ = True"
cmd = ('{cmd_pre}{0}; import {1.package_name}, sys; result = ('
'{1.package_name}.test('
'package={1.package!r}, '
'test_path={1.test_path!r}, '
'args={1.args!r}, '
'plugins={1.plugins!r}, '
'verbose={1.verbose_results!r}, '
'pastebin={1.pastebin!r}, '
'remote_data={1.remote_data!r}, '
'pep8={1.pep8!r}, '
'pdb={1.pdb!r}, '
'open_files={1.open_files!r}, '
'parallel={1.parallel!r}, '
'docs_path={1.docs_path!r}, '
'skip_docs={1.skip_docs!r}, '
'add_local_eggs_to_path=True, ' # see _build_temp_install below
'repeat={1.repeat!r})); '
'{cmd_post}'
'sys.exit(result)')
return cmd.format(set_flag, self, cmd_pre=cmd_pre, cmd_post=cmd_post)
def run(self):
"""
Run the tests!
"""
# Install the runtime dependencies.
if self.distribution.install_requires:
self.distribution.fetch_build_eggs(self.distribution.install_requires)
# Ensure there is a doc path
if self.docs_path is None:
cfg_docs_dir = self.distribution.get_option_dict('build_docs').get('source_dir', None)
# Some affiliated packages use this.
# See astropy/package-template#157
if cfg_docs_dir is not None and os.path.exists(cfg_docs_dir[1]):
self.docs_path = os.path.abspath(cfg_docs_dir[1])
# fall back on a default path of "docs"
elif os.path.exists('docs'): # pragma: no cover
self.docs_path = os.path.abspath('docs')
# Build a testing install of the package
self._build_temp_install()
# Install the test dependencies
# NOTE: we do this here after _build_temp_install because there is
# a weird but which occurs if psutil is installed in this way before
# astropy is built, Cython can have segmentation fault. Strange, eh?
if self.distribution.tests_require:
self.distribution.fetch_build_eggs(self.distribution.tests_require)
# Copy any additional dependencies that may have been installed via
# tests_requires or install_requires. We then pass the
# add_local_eggs_to_path=True option to package.test() to make sure the
# eggs get included in the path.
if os.path.exists('.eggs'):
shutil.copytree('.eggs', os.path.join(self.testing_path, '.eggs'))
# This option exists so that we can make sure that the tests don't
# write to an installed location.
if self.readonly:
log.info('changing permissions of temporary installation to read-only')
self._change_permissions_testing_path(writable=False)
# Run everything in a try: finally: so that the tmp dir gets deleted.
try:
# Construct this modules testing command
cmd = self.generate_testing_command()
# Run the tests in a subprocess--this is necessary since
# new extension modules may have appeared, and this is the
# easiest way to set up a new environment
testproc = subprocess.Popen(
[sys.executable, '-c', cmd],
cwd=self.testing_path, close_fds=False)
retcode = testproc.wait()
except KeyboardInterrupt:
import signal
# If a keyboard interrupt is handled, pass it to the test
# subprocess to prompt pytest to initiate its teardown
testproc.send_signal(signal.SIGINT)
retcode = testproc.wait()
finally:
# Remove temporary directory
if self.readonly:
self._change_permissions_testing_path(writable=True)
shutil.rmtree(self.tmp_dir)
raise SystemExit(retcode)
def _build_temp_install(self):
"""
Install the package and to a temporary directory for the purposes of
testing. This allows us to test the install command, include the
entry points, and also avoids creating pyc and __pycache__ directories
inside the build directory
"""
# On OSX the default path for temp files is under /var, but in most
# cases on OSX /var is actually a symlink to /private/var; ensure we
# dereference that link, because pytest is very sensitive to relative
# paths...
tmp_dir = tempfile.mkdtemp(prefix=self.package_name + '-test-',
dir=self.temp_root)
self.tmp_dir = os.path.realpath(tmp_dir)
log.info(f'installing to temporary directory: {self.tmp_dir}')
# We now install the package to the temporary directory. We do this
# rather than build and copy because this will ensure that e.g. entry
# points work.
self.reinitialize_command('install')
install_cmd = self.distribution.get_command_obj('install')
install_cmd.prefix = self.tmp_dir
if self.verbose_install:
self.run_command('install')
else:
with _suppress_stdout():
self.run_command('install')
# We now get the path to the site-packages directory that was created
# inside self.tmp_dir
install_cmd = self.get_finalized_command('install')
self.testing_path = install_cmd.install_lib
# Ideally, docs_path is set properly in run(), but if it is still
# not set here, do not pretend it is, otherwise bad things happen.
# See astropy/package-template#157
if self.docs_path is not None:
new_docs_path = os.path.join(self.testing_path,
os.path.basename(self.docs_path))
shutil.copytree(self.docs_path, new_docs_path)
self.docs_path = new_docs_path
shutil.copy('setup.cfg', self.testing_path)
def _change_permissions_testing_path(self, writable=False):
if writable:
basic_flags = stat.S_IRUSR | stat.S_IWUSR
else:
basic_flags = stat.S_IRUSR
for root, dirs, files in os.walk(self.testing_path):
for dirname in dirs:
os.chmod(os.path.join(root, dirname), basic_flags | stat.S_IXUSR)
for filename in files:
os.chmod(os.path.join(root, filename), basic_flags)
def _generate_coverage_commands(self):
"""
This method creates the post and pre commands if coverage is to be
generated
"""
if self.parallel != 0:
raise ValueError(
"--coverage can not be used with --parallel")
try:
import coverage # pylint: disable=W0611
except ImportError:
raise ImportError(
"--coverage requires that the coverage package is "
"installed.")
# Don't use get_pkg_data_filename here, because it
# requires importing astropy.config and thus screwing
# up coverage results for those packages.
coveragerc = os.path.join(
self.testing_path, self.package_name.replace('.', '/'),
'tests', 'coveragerc')
with open(coveragerc, 'r') as fd:
coveragerc_content = fd.read()
coveragerc_content = coveragerc_content.replace(
"{packagename}", self.package_name.replace('.', '/'))
tmp_coveragerc = os.path.join(self.tmp_dir, 'coveragerc')
with open(tmp_coveragerc, 'wb') as tmp:
tmp.write(coveragerc_content.encode('utf-8'))
cmd_pre = (
'import coverage; '
'cov = coverage.coverage(data_file=r"{}", config_file=r"{}"); '
'cov.start();'.format(
os.path.abspath(".coverage"), os.path.abspath(tmp_coveragerc)))
cmd_post = (
'cov.stop(); '
'from astropy.tests.helper import _save_coverage; '
'_save_coverage(cov, result, r"{}", r"{}");'.format(
os.path.abspath('.'), os.path.abspath(self.testing_path)))
return cmd_pre, cmd_post
|
2b59e0119fb8f8adfd927a7c41ebb087bd83c2b16094cf91dbbf31f12ad290b7 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package contains utilities to run the astropy test suite, tools
for writing tests, and general tests that are not associated with a
particular package.
"""
|
91be0b50ef01b2b1f50df86f57c9cb3a94ed090b06e95754bc51d5c8ffeb939d | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import importlib
import sys
import warnings
import logging
import locale
import pytest
from astropy import log
from astropy.logger import LoggingError, conf
from astropy.utils.exceptions import AstropyWarning, AstropyUserWarning
# Save original values of hooks. These are not the system values, but the
# already overwritten values since the logger already gets imported before
# this file gets executed.
_excepthook = sys.__excepthook__
_showwarning = warnings.showwarning
try:
ip = get_ipython()
except NameError:
ip = None
def setup_function(function):
# Reset modules to default
importlib.reload(warnings)
importlib.reload(sys)
# Reset internal original hooks
log._showwarning_orig = None
log._excepthook_orig = None
# Set up the logger
log._set_defaults()
# Reset hooks
if log.warnings_logging_enabled():
log.disable_warnings_logging()
if log.exception_logging_enabled():
log.disable_exception_logging()
teardown_module = setup_function
def test_warnings_logging_disable_no_enable():
with pytest.raises(LoggingError) as e:
log.disable_warnings_logging()
assert e.value.args[0] == 'Warnings logging has not been enabled'
def test_warnings_logging_enable_twice():
log.enable_warnings_logging()
with pytest.raises(LoggingError) as e:
log.enable_warnings_logging()
assert e.value.args[0] == 'Warnings logging has already been enabled'
def test_warnings_logging_overridden():
log.enable_warnings_logging()
warnings.showwarning = lambda: None
with pytest.raises(LoggingError, match=r'Cannot disable warnings logging: '
r'warnings\.showwarning was not set by this logger, or has been overridden'):
log.disable_warnings_logging()
def test_warnings_logging():
# Without warnings logging
with pytest.warns(AstropyUserWarning, match="This is a warning") as warn_list:
with log.log_to_list() as log_list:
warnings.warn("This is a warning", AstropyUserWarning)
assert len(log_list) == 0
assert len(warn_list) == 1
# With warnings logging
with warnings.catch_warnings(record=True) as warn_list:
log.enable_warnings_logging()
with log.log_to_list() as log_list:
warnings.warn("This is a warning", AstropyUserWarning)
log.disable_warnings_logging()
assert len(log_list) == 1
assert len(warn_list) == 0
assert log_list[0].levelname == 'WARNING'
assert log_list[0].message.startswith('This is a warning')
assert log_list[0].origin == 'astropy.tests.test_logger'
# With warnings logging (differentiate between Astropy and non-Astropy)
with pytest.warns(UserWarning, match="This is another warning, not "
"from Astropy") as warn_list:
log.enable_warnings_logging()
with log.log_to_list() as log_list:
warnings.warn("This is a warning", AstropyUserWarning)
warnings.warn("This is another warning, not from Astropy")
log.disable_warnings_logging()
assert len(log_list) == 1
assert len(warn_list) == 1
assert log_list[0].levelname == 'WARNING'
assert log_list[0].message.startswith('This is a warning')
assert log_list[0].origin == 'astropy.tests.test_logger'
# Without warnings logging
with pytest.warns(AstropyUserWarning, match="This is a warning") as warn_list:
with log.log_to_list() as log_list:
warnings.warn("This is a warning", AstropyUserWarning)
assert len(log_list) == 0
assert len(warn_list) == 1
def test_warnings_logging_with_custom_class():
class CustomAstropyWarningClass(AstropyWarning):
pass
# With warnings logging
with warnings.catch_warnings(record=True) as warn_list:
log.enable_warnings_logging()
with log.log_to_list() as log_list:
warnings.warn("This is a warning", CustomAstropyWarningClass)
log.disable_warnings_logging()
assert len(log_list) == 1
assert len(warn_list) == 0
assert log_list[0].levelname == 'WARNING'
assert log_list[0].message.startswith('CustomAstropyWarningClass: This is a warning')
assert log_list[0].origin == 'astropy.tests.test_logger'
def test_warning_logging_with_io_votable_warning():
from astropy.io.votable.exceptions import W02, vo_warn
with warnings.catch_warnings(record=True) as warn_list:
log.enable_warnings_logging()
with log.log_to_list() as log_list:
vo_warn(W02, ('a', 'b'))
log.disable_warnings_logging()
assert len(log_list) == 1
assert len(warn_list) == 0
assert log_list[0].levelname == 'WARNING'
x = log_list[0].message.startswith("W02: ?:?:?: W02: a attribute 'b' is "
"invalid. Must be a standard XML id")
assert x
assert log_list[0].origin == 'astropy.tests.test_logger'
def test_import_error_in_warning_logging():
"""
Regression test for https://github.com/astropy/astropy/issues/2671
This test actually puts a goofy fake module into ``sys.modules`` to test
this problem.
"""
class FakeModule:
def __getattr__(self, attr):
raise ImportError('_showwarning should ignore any exceptions '
'here')
log.enable_warnings_logging()
sys.modules['<test fake module>'] = FakeModule()
try:
warnings.showwarning(AstropyWarning('Regression test for #2671'),
AstropyWarning, '<this is only a test>', 1)
finally:
del sys.modules['<test fake module>']
def test_exception_logging_disable_no_enable():
with pytest.raises(LoggingError) as e:
log.disable_exception_logging()
assert e.value.args[0] == 'Exception logging has not been enabled'
def test_exception_logging_enable_twice():
log.enable_exception_logging()
with pytest.raises(LoggingError) as e:
log.enable_exception_logging()
assert e.value.args[0] == 'Exception logging has already been enabled'
# You can't really override the exception handler in IPython this way, so
# this test doesn't really make sense in the IPython context.
@pytest.mark.skipif("ip is not None")
def test_exception_logging_overridden():
log.enable_exception_logging()
sys.excepthook = lambda etype, evalue, tb: None
with pytest.raises(LoggingError, match='Cannot disable exception logging: '
'sys.excepthook was not set by this logger, or has been overridden'):
log.disable_exception_logging()
@pytest.mark.xfail("ip is not None")
def test_exception_logging():
# Without exception logging
try:
with log.log_to_list() as log_list:
raise Exception("This is an Exception")
except Exception as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0] == "This is an Exception"
else:
assert False # exception should have been raised
assert len(log_list) == 0
# With exception logging
try:
log.enable_exception_logging()
with log.log_to_list() as log_list:
raise Exception("This is an Exception")
except Exception as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0] == "This is an Exception"
else:
assert False # exception should have been raised
assert len(log_list) == 1
assert log_list[0].levelname == 'ERROR'
assert log_list[0].message.startswith('Exception: This is an Exception')
assert log_list[0].origin == 'astropy.tests.test_logger'
# Without exception logging
log.disable_exception_logging()
try:
with log.log_to_list() as log_list:
raise Exception("This is an Exception")
except Exception as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0] == "This is an Exception"
else:
assert False # exception should have been raised
assert len(log_list) == 0
@pytest.mark.xfail("ip is not None")
def test_exception_logging_origin():
# The point here is to get an exception raised from another location
# and make sure the error's origin is reported correctly
from astropy.utils.collections import HomogeneousList
l = HomogeneousList(int) # noqa
try:
log.enable_exception_logging()
with log.log_to_list() as log_list:
l.append('foo')
except TypeError as exc:
sys.excepthook(*sys.exc_info())
assert exc.args[0].startswith(
"homogeneous list must contain only objects of type ")
else:
assert False
assert len(log_list) == 1
assert log_list[0].levelname == 'ERROR'
assert log_list[0].message.startswith(
"TypeError: homogeneous list must contain only objects of type ")
assert log_list[0].origin == 'astropy.utils.collections'
@pytest.mark.skip(reason="Infinite recursion on Python 3.5+, probably a real issue")
# @pytest.mark.xfail("ip is not None")
def test_exception_logging_argless_exception():
"""
Regression test for a crash that occurred on Python 3 when logging an
exception that was instantiated with no arguments (no message, etc.)
Regression test for https://github.com/astropy/astropy/pull/4056
"""
try:
log.enable_exception_logging()
with log.log_to_list() as log_list:
raise Exception()
except Exception:
sys.excepthook(*sys.exc_info())
else:
assert False # exception should have been raised
assert len(log_list) == 1
assert log_list[0].levelname == 'ERROR'
assert log_list[0].message == 'Exception [astropy.tests.test_logger]'
assert log_list[0].origin == 'astropy.tests.test_logger'
@pytest.mark.parametrize(('level'), [None, 'DEBUG', 'INFO', 'WARN', 'ERROR'])
def test_log_to_list(level):
orig_level = log.level
try:
if level is not None:
log.setLevel(level)
with log.log_to_list() as log_list:
log.error("Error message")
log.warning("Warning message")
log.info("Information message")
log.debug("Debug message")
finally:
log.setLevel(orig_level)
if level is None:
# The log level *should* be set to whatever it was in the config
level = conf.log_level
# Check list length
if level == 'DEBUG':
assert len(log_list) == 4
elif level == 'INFO':
assert len(log_list) == 3
elif level == 'WARN':
assert len(log_list) == 2
elif level == 'ERROR':
assert len(log_list) == 1
# Check list content
assert log_list[0].levelname == 'ERROR'
assert log_list[0].message.startswith('Error message')
assert log_list[0].origin == 'astropy.tests.test_logger'
if len(log_list) >= 2:
assert log_list[1].levelname == 'WARNING'
assert log_list[1].message.startswith('Warning message')
assert log_list[1].origin == 'astropy.tests.test_logger'
if len(log_list) >= 3:
assert log_list[2].levelname == 'INFO'
assert log_list[2].message.startswith('Information message')
assert log_list[2].origin == 'astropy.tests.test_logger'
if len(log_list) >= 4:
assert log_list[3].levelname == 'DEBUG'
assert log_list[3].message.startswith('Debug message')
assert log_list[3].origin == 'astropy.tests.test_logger'
def test_log_to_list_level():
with log.log_to_list(filter_level='ERROR') as log_list:
log.error("Error message")
log.warning("Warning message")
assert len(log_list) == 1 and log_list[0].levelname == 'ERROR'
def test_log_to_list_origin1():
with log.log_to_list(filter_origin='astropy.tests') as log_list:
log.error("Error message")
log.warning("Warning message")
assert len(log_list) == 2
def test_log_to_list_origin2():
with log.log_to_list(filter_origin='astropy.wcs') as log_list:
log.error("Error message")
log.warning("Warning message")
assert len(log_list) == 0
@pytest.mark.parametrize(('level'), [None, 'DEBUG', 'INFO', 'WARN', 'ERROR'])
def test_log_to_file(tmpdir, level):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
orig_level = log.level
try:
if level is not None:
log.setLevel(level)
with log.log_to_file(log_path):
log.error("Error message")
log.warning("Warning message")
log.info("Information message")
log.debug("Debug message")
log_file.close()
finally:
log.setLevel(orig_level)
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
if level is None:
# The log level *should* be set to whatever it was in the config
level = conf.log_level
# Check list length
if level == 'DEBUG':
assert len(log_entries) == 4
elif level == 'INFO':
assert len(log_entries) == 3
elif level == 'WARN':
assert len(log_entries) == 2
elif level == 'ERROR':
assert len(log_entries) == 1
# Check list content
assert eval(log_entries[0].strip())[-3:] == (
'astropy.tests.test_logger', 'ERROR', 'Error message')
if len(log_entries) >= 2:
assert eval(log_entries[1].strip())[-3:] == (
'astropy.tests.test_logger', 'WARNING', 'Warning message')
if len(log_entries) >= 3:
assert eval(log_entries[2].strip())[-3:] == (
'astropy.tests.test_logger', 'INFO', 'Information message')
if len(log_entries) >= 4:
assert eval(log_entries[3].strip())[-3:] == (
'astropy.tests.test_logger', 'DEBUG', 'Debug message')
def test_log_to_file_level(tmpdir):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
with log.log_to_file(log_path, filter_level='ERROR'):
log.error("Error message")
log.warning("Warning message")
log_file.close()
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
assert len(log_entries) == 1
assert eval(log_entries[0].strip())[-2:] == (
'ERROR', 'Error message')
def test_log_to_file_origin1(tmpdir):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
with log.log_to_file(log_path, filter_origin='astropy.tests'):
log.error("Error message")
log.warning("Warning message")
log_file.close()
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
assert len(log_entries) == 2
def test_log_to_file_origin2(tmpdir):
local_path = tmpdir.join('test.log')
log_file = local_path.open('wb')
log_path = str(local_path.realpath())
with log.log_to_file(log_path, filter_origin='astropy.wcs'):
log.error("Error message")
log.warning("Warning message")
log_file.close()
log_file = local_path.open('rb')
log_entries = log_file.readlines()
log_file.close()
assert len(log_entries) == 0
@pytest.mark.parametrize(('encoding'), ['', 'utf-8', 'cp1252'])
def test_log_to_file_encoding(tmpdir, encoding):
local_path = tmpdir.join('test.log')
log_path = str(local_path.realpath())
orig_encoding = conf.log_file_encoding
conf.log_file_encoding = encoding
with log.log_to_file(log_path):
for handler in log.handlers:
if isinstance(handler, logging.FileHandler):
if encoding:
assert handler.stream.encoding == encoding
else:
assert handler.stream.encoding == locale.getpreferredencoding()
conf.log_file_encoding = orig_encoding
|
37a904785c61f3ef9f4983912e9f8ddb4a69743c4e2554bd6dd88b6d8eddeb8e | """Implements the Astropy TestRunner which is a thin wrapper around pytest."""
import inspect
import os
import glob
import copy
import shlex
import sys
import tempfile
import warnings
from collections import OrderedDict
from importlib.util import find_spec
from functools import wraps
from astropy.config.paths import set_temp_config, set_temp_cache
from astropy.utils import find_current_module
from astropy.utils.exceptions import AstropyWarning, AstropyDeprecationWarning
__all__ = ['TestRunner', 'TestRunnerBase', 'keyword']
class keyword:
"""
A decorator to mark a method as keyword argument for the ``TestRunner``.
Parameters
----------
default_value : `object`
The default value for the keyword argument. (Default: `None`)
priority : `int`
keyword argument methods are executed in order of descending priority.
"""
def __init__(self, default_value=None, priority=0):
self.default_value = default_value
self.priority = priority
def __call__(self, f):
def keyword(*args, **kwargs):
return f(*args, **kwargs)
keyword._default_value = self.default_value
keyword._priority = self.priority
# Set __doc__ explicitly here rather than using wraps because we want
# to keep the function name as keyword so we can inspect it later.
keyword.__doc__ = f.__doc__
return keyword
class TestRunnerBase:
"""
The base class for the TestRunner.
A test runner can be constructed by creating a subclass of this class and
defining 'keyword' methods. These are methods that have the
:class:`~astropy.tests.runner.keyword` decorator, these methods are used to
construct allowed keyword arguments to the
``run_tests`` method as a way to allow
customization of individual keyword arguments (and associated logic)
without having to re-implement the whole
``run_tests`` method.
Examples
--------
A simple keyword method::
class MyRunner(TestRunnerBase):
@keyword('default_value'):
def spam(self, spam, kwargs):
\"\"\"
spam : `str`
The parameter description for the run_tests docstring.
\"\"\"
# Return value must be a list with a CLI parameter for pytest.
return ['--spam={}'.format(spam)]
"""
def __init__(self, base_path):
self.base_path = os.path.abspath(base_path)
def __new__(cls, *args, **kwargs):
# Before constructing the class parse all the methods that have been
# decorated with ``keyword``.
# The objective of this method is to construct a default set of keyword
# arguments to the ``run_tests`` method. It does this by inspecting the
# methods of the class for functions with the name ``keyword`` which is
# the name of the decorator wrapping function. Once it has created this
# dictionary, it also formats the docstring of ``run_tests`` to be
# comprised of the docstrings for the ``keyword`` methods.
# To add a keyword argument to the ``run_tests`` method, define a new
# method decorated with ``@keyword`` and with the ``self, name, kwargs``
# signature.
# Get all 'function' members as the wrapped methods are functions
functions = inspect.getmembers(cls, predicate=inspect.isfunction)
# Filter out anything that's not got the name 'keyword'
keywords = filter(lambda func: func[1].__name__ == 'keyword', functions)
# Sort all keywords based on the priority flag.
sorted_keywords = sorted(keywords, key=lambda x: x[1]._priority, reverse=True)
cls.keywords = OrderedDict()
doc_keywords = ""
for name, func in sorted_keywords:
# Here we test if the function has been overloaded to return
# NotImplemented which is the way to disable arguments on
# subclasses. If it has been disabled we need to remove it from the
# default keywords dict. We do it in the try except block because
# we do not have access to an instance of the class, so this is
# going to error unless the method is just doing `return
# NotImplemented`.
try:
# Second argument is False, as it is normally a bool.
# The other two are placeholders for objects.
if func(None, False, None) is NotImplemented:
continue
except Exception:
pass
# Construct the default kwargs dict and docstring
cls.keywords[name] = func._default_value
if func.__doc__:
doc_keywords += ' '*8
doc_keywords += func.__doc__.strip()
doc_keywords += '\n\n'
cls.run_tests.__doc__ = cls.RUN_TESTS_DOCSTRING.format(keywords=doc_keywords)
return super().__new__(cls)
def _generate_args(self, **kwargs):
# Update default values with passed kwargs
# but don't modify the defaults
keywords = copy.deepcopy(self.keywords)
keywords.update(kwargs)
# Iterate through the keywords (in order of priority)
args = []
for keyword in keywords.keys():
func = getattr(self, keyword)
result = func(keywords[keyword], keywords)
# Allow disabling of options in a subclass
if result is NotImplemented:
raise TypeError(f"run_tests() got an unexpected keyword argument {keyword}")
# keyword methods must return a list
if not isinstance(result, list):
raise TypeError(f"{keyword} keyword method must return a list")
args += result
return args
RUN_TESTS_DOCSTRING = \
"""
Run the tests for the package.
This method builds arguments for and then calls ``pytest.main``.
Parameters
----------
{keywords}
"""
_required_dependencies = ['pytest', 'pytest_remotedata', 'pytest_doctestplus', 'pytest_astropy_header']
_missing_dependancy_error = (
"Test dependencies are missing: {module}. You should install the "
"'pytest-astropy' package (you may need to update the package if you "
"have a previous version installed, e.g., "
"'pip install pytest-astropy --upgrade' or the equivalent with conda).")
@classmethod
def _has_test_dependencies(cls): # pragma: no cover
# Using the test runner will not work without these dependencies, but
# pytest-openfiles is optional, so it's not listed here.
for module in cls._required_dependencies:
spec = find_spec(module)
# Checking loader accounts for packages that were uninstalled
if spec is None or spec.loader is None:
raise RuntimeError(
cls._missing_dependancy_error.format(module=module))
def run_tests(self, **kwargs):
# The following option will include eggs inside a .eggs folder in
# sys.path when running the tests. This is possible so that when
# running pytest, test dependencies installed via e.g.
# tests_requires are available here. This is not an advertised option
# since it is only for internal use
if kwargs.pop('add_local_eggs_to_path', False):
# Add each egg to sys.path individually
for egg in glob.glob(os.path.join('.eggs', '*.egg')):
sys.path.insert(0, egg)
self._has_test_dependencies() # pragma: no cover
# The docstring for this method is defined as a class variable.
# This allows it to be built for each subclass in __new__.
# Don't import pytest until it's actually needed to run the tests
import pytest
# Raise error for undefined kwargs
allowed_kwargs = set(self.keywords.keys())
passed_kwargs = set(kwargs.keys())
if not passed_kwargs.issubset(allowed_kwargs):
wrong_kwargs = list(passed_kwargs.difference(allowed_kwargs))
raise TypeError(f"run_tests() got an unexpected keyword argument {wrong_kwargs[0]}")
args = self._generate_args(**kwargs)
if kwargs.get('plugins', None) is not None:
plugins = kwargs.pop('plugins')
elif self.keywords.get('plugins', None) is not None:
plugins = self.keywords['plugins']
else:
plugins = []
# Override the config locations to not make a new directory nor use
# existing cache or config. Note that we need to do this here in
# addition to in conftest.py - for users running tests interactively
# in e.g. IPython, conftest.py would get read in too late, so we need
# to do it here - but at the same time the code here doesn't work when
# running tests in parallel mode because this uses subprocesses which
# don't know about the temporary config/cache.
astropy_config = tempfile.mkdtemp('astropy_config')
astropy_cache = tempfile.mkdtemp('astropy_cache')
# Have to use nested with statements for cross-Python support
# Note, using these context managers here is superfluous if the
# config_dir or cache_dir options to pytest are in use, but it's
# also harmless to nest the contexts
with set_temp_config(astropy_config, delete=True):
with set_temp_cache(astropy_cache, delete=True):
return pytest.main(args=args, plugins=plugins)
@classmethod
def make_test_runner_in(cls, path):
"""
Constructs a `TestRunner` to run in the given path, and returns a
``test()`` function which takes the same arguments as
``TestRunner.run_tests``.
The returned ``test()`` function will be defined in the module this
was called from. This is used to implement the ``astropy.test()``
function (or the equivalent for affiliated packages).
"""
runner = cls(path)
@wraps(runner.run_tests, ('__doc__',))
def test(**kwargs):
return runner.run_tests(**kwargs)
module = find_current_module(2)
if module is not None:
test.__module__ = module.__name__
# A somewhat unusual hack, but delete the attached __wrapped__
# attribute--although this is normally used to tell if the function
# was wrapped with wraps, on some version of Python this is also
# used to determine the signature to display in help() which is
# not useful in this case. We don't really care in this case if the
# function was wrapped either
if hasattr(test, '__wrapped__'):
del test.__wrapped__
test.__test__ = False
return test
class TestRunner(TestRunnerBase):
"""
A test runner for astropy tests
"""
def packages_path(self, packages, base_path, error=None, warning=None):
"""
Generates the path for multiple packages.
Parameters
----------
packages : str
Comma separated string of packages.
base_path : str
Base path to the source code or documentation.
error : str
Error message to be raised as ``ValueError``. Individual package
name and path can be accessed by ``{name}`` and ``{path}``
respectively. No error is raised if `None`. (Default: `None`)
warning : str
Warning message to be issued. Individual package
name and path can be accessed by ``{name}`` and ``{path}``
respectively. No warning is issues if `None`. (Default: `None`)
Returns
-------
paths : list of str
List of strings of existing package paths.
"""
packages = packages.split(",")
paths = []
for package in packages:
path = os.path.join(
base_path, package.replace('.', os.path.sep))
if not os.path.isdir(path):
info = {'name': package, 'path': path}
if error is not None:
raise ValueError(error.format(**info))
if warning is not None:
warnings.warn(warning.format(**info))
else:
paths.append(path)
return paths
# Increase priority so this warning is displayed first.
@keyword(priority=1000)
def coverage(self, coverage, kwargs):
if coverage:
warnings.warn(
"The coverage option is ignored on run_tests, since it "
"can not be made to work in that context. Use "
"'python setup.py test --coverage' instead.",
AstropyWarning)
return []
# test_path depends on self.package_path so make sure this runs before
# test_path.
@keyword(priority=1)
def package(self, package, kwargs):
"""
package : str, optional
The name of a specific package to test, e.g. 'io.fits' or
'utils'. Accepts comma separated string to specify multiple
packages. If nothing is specified all default tests are run.
"""
if package is None:
self.package_path = [self.base_path]
else:
error_message = ('package to test is not found: {name} '
'(at path {path}).')
self.package_path = self.packages_path(package, self.base_path,
error=error_message)
if not kwargs['test_path']:
return self.package_path
return []
@keyword()
def test_path(self, test_path, kwargs):
"""
test_path : str, optional
Specify location to test by path. May be a single file or
directory. Must be specified absolutely or relative to the
calling directory.
"""
all_args = []
# Ensure that the package kwarg has been run.
self.package(kwargs['package'], kwargs)
if test_path:
base, ext = os.path.splitext(test_path)
if ext in ('.rst', ''):
if kwargs['docs_path'] is None:
# This shouldn't happen from "python setup.py test"
raise ValueError(
"Can not test .rst files without a docs_path "
"specified.")
abs_docs_path = os.path.abspath(kwargs['docs_path'])
abs_test_path = os.path.abspath(
os.path.join(abs_docs_path, os.pardir, test_path))
common = os.path.commonprefix((abs_docs_path, abs_test_path))
if os.path.exists(abs_test_path) and common == abs_docs_path:
# Turn on the doctest_rst plugin
all_args.append('--doctest-rst')
test_path = abs_test_path
# Check that the extensions are in the path and not at the end to
# support specifying the name of the test, i.e.
# test_quantity.py::test_unit
if not (os.path.isdir(test_path) or ('.py' in test_path or '.rst' in test_path)):
raise ValueError("Test path must be a directory or a path to "
"a .py or .rst file")
return all_args + [test_path]
return []
@keyword()
def args(self, args, kwargs):
"""
args : str, optional
Additional arguments to be passed to ``pytest.main`` in the ``args``
keyword argument.
"""
if args:
return shlex.split(args, posix=not sys.platform.startswith('win'))
return []
@keyword(default_value=[])
def plugins(self, plugins, kwargs):
"""
plugins : list, optional
Plugins to be passed to ``pytest.main`` in the ``plugins`` keyword
argument.
"""
# Plugins are handled independently by `run_tests` so we define this
# keyword just for the docstring
return []
@keyword()
def verbose(self, verbose, kwargs):
"""
verbose : bool, optional
Convenience option to turn on verbose output from pytest. Passing
True is the same as specifying ``-v`` in ``args``.
"""
if verbose:
return ['-v']
return []
@keyword()
def pastebin(self, pastebin, kwargs):
"""
pastebin : ('failed', 'all', None), optional
Convenience option for turning on pytest pastebin output. Set to
'failed' to upload info for failed tests, or 'all' to upload info
for all tests.
"""
if pastebin is not None:
if pastebin in ['failed', 'all']:
return [f'--pastebin={pastebin}']
else:
raise ValueError("pastebin should be 'failed' or 'all'")
return []
@keyword(default_value='none')
def remote_data(self, remote_data, kwargs):
"""
remote_data : {'none', 'astropy', 'any'}, optional
Controls whether to run tests marked with @pytest.mark.remote_data. This can be
set to run no tests with remote data (``none``), only ones that use
data from http://data.astropy.org (``astropy``), or all tests that
use remote data (``any``). The default is ``none``.
"""
if remote_data is True:
remote_data = 'any'
elif remote_data is False:
remote_data = 'none'
elif remote_data not in ('none', 'astropy', 'any'):
warnings.warn("The remote_data option should be one of "
"none/astropy/any (found {}). For backward-compatibility, "
"assuming 'any', but you should change the option to be "
"one of the supported ones to avoid issues in "
"future.".format(remote_data),
AstropyDeprecationWarning)
remote_data = 'any'
return [f'--remote-data={remote_data}']
@keyword()
def pep8(self, pep8, kwargs):
"""
pep8 : bool, optional
Turn on PEP8 checking via the pytest-pep8 plugin and disable normal
tests. Same as specifying ``--pep8 -k pep8`` in ``args``.
"""
if pep8:
try:
import pytest_pep8 # pylint: disable=W0611
except ImportError:
raise ImportError('PEP8 checking requires pytest-pep8 plugin: '
'https://pypi.org/project/pytest-pep8')
else:
return ['--pep8', '-k', 'pep8']
return []
@keyword()
def pdb(self, pdb, kwargs):
"""
pdb : bool, optional
Turn on PDB post-mortem analysis for failing tests. Same as
specifying ``--pdb`` in ``args``.
"""
if pdb:
return ['--pdb']
return []
@keyword()
def open_files(self, open_files, kwargs):
"""
open_files : bool, optional
Fail when any tests leave files open. Off by default, because
this adds extra run time to the test suite. Requires the
``psutil`` package.
"""
if open_files:
if kwargs['parallel'] != 0:
raise SystemError(
"open file detection may not be used in conjunction with "
"parallel testing.")
try:
import psutil # pylint: disable=W0611
except ImportError:
raise SystemError(
"open file detection requested, but psutil package "
"is not installed.")
return ['--open-files']
print("Checking for unclosed files")
return []
@keyword(0)
def parallel(self, parallel, kwargs):
"""
parallel : int or 'auto', optional
When provided, run the tests in parallel on the specified
number of CPUs. If parallel is ``'auto'``, it will use the all
the cores on the machine. Requires the ``pytest-xdist`` plugin.
"""
if parallel != 0:
try:
from xdist import plugin # noqa
except ImportError:
raise SystemError(
"running tests in parallel requires the pytest-xdist package")
return ['-n', str(parallel)]
return []
@keyword()
def docs_path(self, docs_path, kwargs):
"""
docs_path : str, optional
The path to the documentation .rst files.
"""
paths = []
if docs_path is not None and not kwargs['skip_docs']:
if kwargs['package'] is not None:
warning_message = ("Can not test .rst docs for {name}, since "
"docs path ({path}) does not exist.")
paths = self.packages_path(kwargs['package'], docs_path,
warning=warning_message)
elif not kwargs['test_path']:
paths = [docs_path, ]
if len(paths) and not kwargs['test_path']:
paths.append('--doctest-rst')
return paths
@keyword()
def skip_docs(self, skip_docs, kwargs):
"""
skip_docs : `bool`, optional
When `True`, skips running the doctests in the .rst files.
"""
# Skip docs is a bool used by docs_path only.
return []
@keyword()
def repeat(self, repeat, kwargs):
"""
repeat : `int`, optional
If set, specifies how many times each test should be run. This is
useful for diagnosing sporadic failures.
"""
if repeat:
return [f'--repeat={repeat}']
return []
# Override run_tests for astropy-specific fixes
def run_tests(self, **kwargs):
# This prevents cyclical import problems that make it
# impossible to test packages that define Table types on their
# own.
from astropy.table import Table # pylint: disable=W0611
return super().run_tests(**kwargs)
|
47e68b1aa399c1e3e480e17b71dc4fe632d7b7f5080d651467debbdaa5ead040 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides the tools used to internally run the astropy test suite
from the installed astropy. It makes use of the `pytest`_ testing framework.
"""
import os
import sys
import pickle
import warnings
import functools
import pytest
from astropy.units import allclose as quantity_allclose # noqa: F401
from astropy.utils.decorators import deprecated
from astropy.utils.exceptions import (AstropyDeprecationWarning,
AstropyPendingDeprecationWarning)
# For backward-compatibility with affiliated packages
from .runner import TestRunner # pylint: disable=W0611 # noqa
__all__ = ['assert_follows_unicode_guidelines',
'assert_quantity_allclose', 'check_pickling_recovery',
'pickle_protocol', 'generic_recursive_equality_test']
def _save_coverage(cov, result, rootdir, testing_path):
"""
This method is called after the tests have been run in coverage mode
to cleanup and then save the coverage data and report.
"""
from astropy.utils.console import color_print
if result != 0:
return
# The coverage report includes the full path to the temporary
# directory, so we replace all the paths with the true source
# path. Note that this will not work properly for packages that still
# rely on 2to3.
try:
# Coverage 4.0: _harvest_data has been renamed to get_data, the
# lines dict is private
cov.get_data()
except AttributeError:
# Coverage < 4.0
cov._harvest_data()
lines = cov.data.lines
else:
lines = cov.data._lines
for key in list(lines.keys()):
new_path = os.path.relpath(
os.path.realpath(key),
os.path.realpath(testing_path))
new_path = os.path.abspath(
os.path.join(rootdir, new_path))
lines[new_path] = lines.pop(key)
color_print('Saving coverage data in .coverage...', 'green')
cov.save()
color_print('Saving HTML coverage report in htmlcov...', 'green')
cov.html_report(directory=os.path.join(rootdir, 'htmlcov'))
@deprecated('5.1', alternative='pytest.raises')
class raises:
"""
A decorator to mark that a test should raise a given exception.
Use as follows::
@raises(ZeroDivisionError)
def test_foo():
x = 1/0
This can also be used a context manager, in which case it is just
an alias for the ``pytest.raises`` context manager (because the
two have the same name this help avoid confusion by being
flexible).
.. note:: Usage of ``pytest.raises`` is preferred.
"""
# pep-8 naming exception -- this is a decorator class
def __init__(self, exc):
self._exc = exc
self._ctx = None
def __call__(self, func):
@functools.wraps(func)
def run_raises_test(*args, **kwargs):
pytest.raises(self._exc, func, *args, **kwargs)
return run_raises_test
def __enter__(self):
self._ctx = pytest.raises(self._exc)
return self._ctx.__enter__()
def __exit__(self, *exc_info):
return self._ctx.__exit__(*exc_info)
# TODO: Remove these when deprecation period of things deprecated in PR 12633 are removed.
_deprecations_as_exceptions = False
_include_astropy_deprecations = True
_modules_to_ignore_on_import = set([
r'compiler', # A deprecated stdlib module used by pytest
r'scipy',
r'pygments',
r'ipykernel',
r'IPython', # deprecation warnings for async and await
r'setuptools'])
_warnings_to_ignore_entire_module = set([])
_warnings_to_ignore_by_pyver = {
None: set([ # Python version agnostic
# https://github.com/astropy/astropy/pull/7372
(r"Importing from numpy\.testing\.decorators is deprecated, "
r"import from numpy\.testing instead\.", DeprecationWarning),
# inspect raises this slightly different warning on Python 3.7.
# Keeping it since e.g. lxml as of 3.8.0 is still calling getargspec()
(r"inspect\.getargspec\(\) is deprecated, use "
r"inspect\.signature\(\) or inspect\.getfullargspec\(\)",
DeprecationWarning),
# https://github.com/astropy/pytest-doctestplus/issues/29
(r"split\(\) requires a non-empty pattern match", FutureWarning),
# Package resolution warning that we can do nothing about
(r"can't resolve package from __spec__ or __package__, "
r"falling back on __name__ and __path__", ImportWarning)]),
(3, 7): set([
# Deprecation warning for collections.abc, fixed in Astropy but still
# used in lxml, and maybe others
(r"Using or importing the ABCs from 'collections'",
DeprecationWarning)])
}
@deprecated('5.1', alternative='https://docs.pytest.org/en/stable/warnings.html')
def enable_deprecations_as_exceptions(include_astropy_deprecations=True,
modules_to_ignore_on_import=[],
warnings_to_ignore_entire_module=[],
warnings_to_ignore_by_pyver={}):
"""
Turn on the feature that turns deprecations into exceptions.
Parameters
----------
include_astropy_deprecations : bool
If set to `True`, ``AstropyDeprecationWarning`` and
``AstropyPendingDeprecationWarning`` are also turned into exceptions.
modules_to_ignore_on_import : list of str
List of additional modules that generate deprecation warnings
on import, which are to be ignored. By default, these are already
included: ``compiler``, ``scipy``, ``pygments``, ``ipykernel``, and
``setuptools``.
warnings_to_ignore_entire_module : list of str
List of modules with deprecation warnings to ignore completely,
not just during import. If ``include_astropy_deprecations=True``
is given, ``AstropyDeprecationWarning`` and
``AstropyPendingDeprecationWarning`` are also ignored for the modules.
warnings_to_ignore_by_pyver : dict
Dictionary mapping tuple of ``(major, minor)`` Python version to
a list of ``(warning_message, warning_class)`` to ignore.
Python version-agnostic warnings should be mapped to `None` key.
This is in addition of those already ignored by default
(see ``_warnings_to_ignore_by_pyver`` values).
"""
global _deprecations_as_exceptions
_deprecations_as_exceptions = True
global _include_astropy_deprecations
_include_astropy_deprecations = include_astropy_deprecations
global _modules_to_ignore_on_import
_modules_to_ignore_on_import.update(modules_to_ignore_on_import)
global _warnings_to_ignore_entire_module
_warnings_to_ignore_entire_module.update(warnings_to_ignore_entire_module)
global _warnings_to_ignore_by_pyver
for key, val in warnings_to_ignore_by_pyver.items():
if key in _warnings_to_ignore_by_pyver:
_warnings_to_ignore_by_pyver[key].update(val)
else:
_warnings_to_ignore_by_pyver[key] = set(val)
@deprecated('5.1', alternative='https://docs.pytest.org/en/stable/warnings.html')
def treat_deprecations_as_exceptions():
"""
Turn all DeprecationWarnings (which indicate deprecated uses of
Python itself or Numpy, but not within Astropy, where we use our
own deprecation warning class) into exceptions so that we find
out about them early.
This completely resets the warning filters and any "already seen"
warning state.
"""
# First, totally reset the warning state. The modules may change during
# this iteration thus we copy the original state to a list to iterate
# on. See https://github.com/astropy/astropy/pull/5513.
for module in list(sys.modules.values()):
try:
del module.__warningregistry__
except Exception:
pass
if not _deprecations_as_exceptions:
return
warnings.resetwarnings()
# Hide the next couple of DeprecationWarnings
warnings.simplefilter('ignore', DeprecationWarning)
# Here's the wrinkle: a couple of our third-party dependencies
# (pytest and scipy) are still using deprecated features
# themselves, and we'd like to ignore those. Fortunately, those
# show up only at import time, so if we import those things *now*,
# before we turn the warnings into exceptions, we're golden.
for m in _modules_to_ignore_on_import:
try:
__import__(m)
except ImportError:
pass
# Now, start over again with the warning filters
warnings.resetwarnings()
# Now, turn these warnings into exceptions
_all_warns = [DeprecationWarning, FutureWarning, ImportWarning]
# Only turn astropy deprecation warnings into exceptions if requested
if _include_astropy_deprecations:
_all_warns += [AstropyDeprecationWarning,
AstropyPendingDeprecationWarning]
for w in _all_warns:
warnings.filterwarnings("error", ".*", w)
# This ignores all specified warnings from given module(s),
# not just on import, for use of Astropy affiliated packages.
for m in _warnings_to_ignore_entire_module:
for w in _all_warns:
warnings.filterwarnings('ignore', category=w, module=m)
# This ignores only specified warnings by Python version, if applicable.
for v in _warnings_to_ignore_by_pyver:
if v is None or sys.version_info[:2] == v:
for s in _warnings_to_ignore_by_pyver[v]:
warnings.filterwarnings("ignore", s[0], s[1])
@deprecated('5.1', alternative='pytest.warns')
class catch_warnings(warnings.catch_warnings):
"""
A high-powered version of warnings.catch_warnings to use for testing
and to make sure that there is no dependence on the order in which
the tests are run.
This completely blitzes any memory of any warnings that have
appeared before so that all warnings will be caught and displayed.
``*args`` is a set of warning classes to collect. If no arguments are
provided, all warnings are collected.
Use as follows::
with catch_warnings(MyCustomWarning) as w:
do.something.bad()
assert len(w) > 0
.. note:: Usage of :ref:`pytest.warns <pytest:warns>` is preferred.
"""
def __init__(self, *classes):
super().__init__(record=True)
self.classes = classes
def __enter__(self):
warning_list = super().__enter__()
treat_deprecations_as_exceptions()
if len(self.classes) == 0:
warnings.simplefilter('always')
else:
warnings.simplefilter('ignore')
for cls in self.classes:
warnings.simplefilter('always', cls)
return warning_list
def __exit__(self, type, value, traceback):
treat_deprecations_as_exceptions()
@deprecated('5.1', alternative='pytest.mark.filterwarnings')
class ignore_warnings(catch_warnings):
"""
This can be used either as a context manager or function decorator to
ignore all warnings that occur within a function or block of code.
An optional category option can be supplied to only ignore warnings of a
certain category or categories (if a list is provided).
"""
def __init__(self, category=None):
super().__init__()
if isinstance(category, type) and issubclass(category, Warning):
self.category = [category]
else:
self.category = category
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Originally this just reused self, but that doesn't work if the
# function is called more than once so we need to make a new
# context manager instance for each call
with self.__class__(category=self.category):
return func(*args, **kwargs)
return wrapper
def __enter__(self):
retval = super().__enter__()
if self.category is not None:
for category in self.category:
warnings.simplefilter('ignore', category)
else:
warnings.simplefilter('ignore')
return retval
def assert_follows_unicode_guidelines(
x, roundtrip=None):
"""
Test that an object follows our Unicode policy. See
"Unicode guidelines" in the coding guidelines.
Parameters
----------
x : object
The instance to test
roundtrip : module, optional
When provided, this namespace will be used to evaluate
``repr(x)`` and ensure that it roundtrips. It will also
ensure that ``__bytes__(x)`` roundtrip.
If not provided, no roundtrip testing will be performed.
"""
from astropy import conf
with conf.set_temp('unicode_output', False):
bytes_x = bytes(x)
unicode_x = str(x)
repr_x = repr(x)
assert isinstance(bytes_x, bytes)
bytes_x.decode('ascii')
assert isinstance(unicode_x, str)
unicode_x.encode('ascii')
assert isinstance(repr_x, str)
if isinstance(repr_x, bytes):
repr_x.decode('ascii')
else:
repr_x.encode('ascii')
if roundtrip is not None:
assert x.__class__(bytes_x) == x
assert x.__class__(unicode_x) == x
assert eval(repr_x, roundtrip) == x
with conf.set_temp('unicode_output', True):
bytes_x = bytes(x)
unicode_x = str(x)
repr_x = repr(x)
assert isinstance(bytes_x, bytes)
bytes_x.decode('ascii')
assert isinstance(unicode_x, str)
assert isinstance(repr_x, str)
if isinstance(repr_x, bytes):
repr_x.decode('ascii')
else:
repr_x.encode('ascii')
if roundtrip is not None:
assert x.__class__(bytes_x) == x
assert x.__class__(unicode_x) == x
assert eval(repr_x, roundtrip) == x
@pytest.fixture(params=[0, 1, -1])
def pickle_protocol(request):
"""
Fixture to run all the tests for protocols 0 and 1, and -1 (most advanced).
(Originally from astropy.table.tests.test_pickle)
"""
return request.param
def generic_recursive_equality_test(a, b, class_history):
"""
Check if the attributes of a and b are equal. Then,
check if the attributes of the attributes are equal.
"""
dict_a = a.__getstate__() if hasattr(a, '__getstate__') else a.__dict__
dict_b = b.__dict__
for key in dict_a:
assert key in dict_b,\
f"Did not pickle {key}"
if hasattr(dict_a[key], '__eq__'):
eq = (dict_a[key] == dict_b[key])
if '__iter__' in dir(eq):
eq = (False not in eq)
assert eq, f"Value of {key} changed by pickling"
if hasattr(dict_a[key], '__dict__'):
if dict_a[key].__class__ in class_history:
# attempt to prevent infinite recursion
pass
else:
new_class_history = [dict_a[key].__class__]
new_class_history.extend(class_history)
generic_recursive_equality_test(dict_a[key],
dict_b[key],
new_class_history)
def check_pickling_recovery(original, protocol):
"""
Try to pickle an object. If successful, make sure
the object's attributes survived pickling and unpickling.
"""
f = pickle.dumps(original, protocol=protocol)
unpickled = pickle.loads(f)
class_history = [original.__class__]
generic_recursive_equality_test(original, unpickled,
class_history)
def assert_quantity_allclose(actual, desired, rtol=1.e-7, atol=None,
**kwargs):
"""
Raise an assertion if two objects are not equal up to desired tolerance.
This is a :class:`~astropy.units.Quantity`-aware version of
:func:`numpy.testing.assert_allclose`.
"""
import numpy as np
from astropy.units.quantity import _unquantify_allclose_arguments
np.testing.assert_allclose(*_unquantify_allclose_arguments(
actual, desired, rtol, atol), **kwargs)
|
61ac8618a15f3dc44e8d41f6b4501cb542a1afe23047c365409c8eac538b1b9d | try:
import matplotlib
from matplotlib import pyplot as plt # noqa
except ImportError:
MPL_VERSION = ''
ROOT = ''
IMAGE_REFERENCE_DIR = ''
else:
MPL_VERSION = matplotlib.__version__
# The developer versions of the form 3.2.x+... contain changes that will only
# be included in the 3.3.x release, so we update this here.
if MPL_VERSION[:3] == '3.2' and '+' in MPL_VERSION:
MPL_VERSION = '3.3'
ROOT = "http://{server}/testing/astropy/2021-08-25T18:18:36.000000/{mpl_version}/"
IMAGE_REFERENCE_DIR = (
ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' +
ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))
|
cc9a8f29c81275c0cdced6a240e39ba56d3721558de33f28ec25178f86a30e0f | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from copy import deepcopy
import numpy as np
from astropy.table import groups, QTable, Table
from astropy.time import Time, TimeDelta
from astropy import units as u
from astropy.units import Quantity, UnitsError
from astropy.utils.decorators import deprecated_renamed_argument
from astropy.timeseries.core import BaseTimeSeries, autocheck_required_columns
__all__ = ['TimeSeries']
@autocheck_required_columns
class TimeSeries(BaseTimeSeries):
"""
A class to represent time series data in tabular form.
`~astropy.timeseries.TimeSeries` provides a class for representing time
series as a collection of values of different quantities measured at specific
points in time (for time series with finite time bins, see the
`~astropy.timeseries.BinnedTimeSeries` class).
`~astropy.timeseries.TimeSeries` is a sub-class of `~astropy.table.QTable`
and thus provides all the standard table maniplation methods available to
tables, but it also provides additional conveniences for dealing with time
series, such as a flexible initializer for setting up the times, a method
for folding time series, and a ``time`` attribute for easy access to the
time values.
See also: https://docs.astropy.org/en/stable/timeseries/
Parameters
----------
data : numpy ndarray, dict, list, `~astropy.table.Table`, or table-like object, optional
Data to initialize time series. This does not need to contain the times,
which can be provided separately, but if it does contain the times they
should be in a column called ``'time'`` to be automatically recognized.
time : `~astropy.time.Time`, `~astropy.time.TimeDelta` or iterable
The times at which the values are sampled - this can be either given
directly as a `~astropy.time.Time` or `~astropy.time.TimeDelta` array
or as any iterable that initializes the `~astropy.time.Time` class. If
this is given, then the remaining time-related arguments should not be used.
time_start : `~astropy.time.Time` or str
The time of the first sample in the time series. This is an alternative
to providing ``time`` and requires that ``time_delta`` is also provided.
time_delta : `~astropy.time.TimeDelta` or `~astropy.units.Quantity` ['time']
The step size in time for the series. This can either be a scalar if
the time series is evenly sampled, or an array of values if it is not.
n_samples : int
The number of time samples for the series. This is only used if both
``time_start`` and ``time_delta`` are provided and are scalar values.
**kwargs : dict, optional
Additional keyword arguments are passed to `~astropy.table.QTable`.
"""
_required_columns = ['time']
def __init__(self, data=None, *, time=None, time_start=None,
time_delta=None, n_samples=None, **kwargs):
super().__init__(data=data, **kwargs)
# For some operations, an empty time series needs to be created, then
# columns added one by one. We should check that when columns are added
# manually, time is added first and is of the right type.
if data is None and time is None and time_start is None and time_delta is None:
self._required_columns_relax = True
return
# First if time has been given in the table data, we should extract it
# and treat it as if it had been passed as a keyword argument.
if data is not None:
if n_samples is not None:
if n_samples != len(self):
raise TypeError("'n_samples' has been given both and it is not the "
"same length as the input data.")
else:
n_samples = len(self)
if 'time' in self.colnames:
if time is None:
time = self.columns['time']
else:
raise TypeError("'time' has been given both in the table and as a keyword argument")
if time is None and time_start is None:
raise TypeError("Either 'time' or 'time_start' should be specified")
elif time is not None and time_start is not None:
raise TypeError("Cannot specify both 'time' and 'time_start'")
if time is not None and not isinstance(time, (Time, TimeDelta)):
time = Time(time)
if time_start is not None and not isinstance(time_start, (Time, TimeDelta)):
time_start = Time(time_start)
if time_delta is not None and not isinstance(time_delta, (Quantity, TimeDelta)):
raise TypeError("'time_delta' should be a Quantity or a TimeDelta")
if isinstance(time_delta, TimeDelta):
time_delta = time_delta.sec * u.s
if time_start is not None:
# We interpret this as meaning that time is that of the first
# sample and that the interval is given by time_delta.
if time_delta is None:
raise TypeError("'time' is scalar, so 'time_delta' is required")
if time_delta.isscalar:
time_delta = np.repeat(time_delta, n_samples)
time_delta = np.cumsum(time_delta)
time_delta = np.roll(time_delta, 1)
time_delta[0] = 0. * u.s
time = time_start + time_delta
elif len(self.colnames) > 0 and len(time) != len(self):
raise ValueError("Length of 'time' ({}) should match "
"data length ({})".format(len(time), n_samples))
elif time_delta is not None:
raise TypeError("'time_delta' should not be specified since "
"'time' is an array")
with self._delay_required_column_checks():
if 'time' in self.colnames:
self.remove_column('time')
self.add_column(time, index=0, name='time')
@property
def time(self):
"""
The time values.
"""
return self['time']
@deprecated_renamed_argument('midpoint_epoch', 'epoch_time', '4.0')
def fold(self, period=None, epoch_time=None, epoch_phase=0,
wrap_phase=None, normalize_phase=False):
"""
Return a new `~astropy.timeseries.TimeSeries` folded with a period and
epoch.
Parameters
----------
period : `~astropy.units.Quantity` ['time']
The period to use for folding
epoch_time : `~astropy.time.Time`
The time to use as the reference epoch, at which the relative time
offset / phase will be ``epoch_phase``. Defaults to the first time
in the time series.
epoch_phase : float or `~astropy.units.Quantity` ['dimensionless', 'time']
Phase of ``epoch_time``. If ``normalize_phase`` is `True`, this
should be a dimensionless value, while if ``normalize_phase`` is
``False``, this should be a `~astropy.units.Quantity` with time
units. Defaults to 0.
wrap_phase : float or `~astropy.units.Quantity` ['dimensionless', 'time']
The value of the phase above which values are wrapped back by one
period. If ``normalize_phase`` is `True`, this should be a
dimensionless value, while if ``normalize_phase`` is ``False``,
this should be a `~astropy.units.Quantity` with time units.
Defaults to half the period, so that the resulting time series goes
from ``-period / 2`` to ``period / 2`` (if ``normalize_phase`` is
`False`) or -0.5 to 0.5 (if ``normalize_phase`` is `True`).
normalize_phase : bool
If `False` phase is returned as `~astropy.time.TimeDelta`,
otherwise as a dimensionless `~astropy.units.Quantity`.
Returns
-------
folded_timeseries : `~astropy.timeseries.TimeSeries`
The folded time series object with phase as the ``time`` column.
"""
if not isinstance(period, Quantity) or period.unit.physical_type != 'time':
raise UnitsError('period should be a Quantity in units of time')
folded = self.copy()
if epoch_time is None:
epoch_time = self.time[0]
else:
epoch_time = Time(epoch_time)
period_sec = period.to_value(u.s)
if normalize_phase:
if isinstance(epoch_phase, Quantity) and epoch_phase.unit.physical_type != 'dimensionless':
raise UnitsError('epoch_phase should be a dimensionless Quantity '
'or a float when normalize_phase=True')
epoch_phase_sec = epoch_phase * period_sec
else:
if epoch_phase == 0:
epoch_phase_sec = 0.
else:
if not isinstance(epoch_phase, Quantity) or epoch_phase.unit.physical_type != 'time':
raise UnitsError('epoch_phase should be a Quantity in units '
'of time when normalize_phase=False')
epoch_phase_sec = epoch_phase.to_value(u.s)
if wrap_phase is None:
wrap_phase = period_sec / 2
else:
if normalize_phase:
if isinstance(wrap_phase, Quantity) and not wrap_phase.unit.is_equivalent(u.one):
raise UnitsError('wrap_phase should be dimensionless when '
'normalize_phase=True')
else:
if wrap_phase < 0 or wrap_phase > 1:
raise ValueError('wrap_phase should be between 0 and 1')
else:
wrap_phase = wrap_phase * period_sec
else:
if isinstance(wrap_phase, Quantity) and wrap_phase.unit.physical_type == 'time':
if wrap_phase < 0 or wrap_phase > period:
raise ValueError('wrap_phase should be between 0 and the period')
else:
wrap_phase = wrap_phase.to_value(u.s)
else:
raise UnitsError('wrap_phase should be a Quantity in units '
'of time when normalize_phase=False')
relative_time_sec = (((self.time - epoch_time).sec
+ epoch_phase_sec
+ (period_sec - wrap_phase)) % period_sec
- (period_sec - wrap_phase))
folded_time = TimeDelta(relative_time_sec * u.s)
if normalize_phase:
folded_time = (folded_time / period).decompose()
period = period_sec = 1
with folded._delay_required_column_checks():
folded.remove_column('time')
folded.add_column(folded_time, name='time', index=0)
return folded
def __getitem__(self, item):
if self._is_list_or_tuple_of_str(item):
if 'time' not in item:
out = QTable([self[x] for x in item],
meta=deepcopy(self.meta),
copy_indices=self._copy_indices)
out._groups = groups.TableGroups(out, indices=self.groups._indices,
keys=self.groups._keys)
return out
return super().__getitem__(item)
def add_column(self, *args, **kwargs):
"""
See :meth:`~astropy.table.Table.add_column`.
"""
# Note that the docstring is inherited from QTable
result = super().add_column(*args, **kwargs)
if len(self.indices) == 0 and 'time' in self.colnames:
self.add_index('time')
return result
def add_columns(self, *args, **kwargs):
"""
See :meth:`~astropy.table.Table.add_columns`.
"""
# Note that the docstring is inherited from QTable
result = super().add_columns(*args, **kwargs)
if len(self.indices) == 0 and 'time' in self.colnames:
self.add_index('time')
return result
@classmethod
def from_pandas(self, df, time_scale='utc'):
"""
Convert a :class:`~pandas.DataFrame` to a
:class:`astropy.timeseries.TimeSeries`.
Parameters
----------
df : :class:`pandas.DataFrame`
A pandas :class:`pandas.DataFrame` instance.
time_scale : str
The time scale to pass into `astropy.time.Time`.
Defaults to ``UTC``.
"""
from pandas import DataFrame, DatetimeIndex
if not isinstance(df, DataFrame):
raise TypeError("Input should be a pandas DataFrame")
if not isinstance(df.index, DatetimeIndex):
raise TypeError("DataFrame does not have a DatetimeIndex")
time = Time(df.index, scale=time_scale)
table = Table.from_pandas(df)
return TimeSeries(time=time, data=table)
def to_pandas(self):
"""
Convert this :class:`~astropy.timeseries.TimeSeries` to a
:class:`~pandas.DataFrame` with a :class:`~pandas.DatetimeIndex` index.
Returns
-------
dataframe : :class:`pandas.DataFrame`
A pandas :class:`pandas.DataFrame` instance
"""
return Table(self).to_pandas(index='time')
@classmethod
def read(self, filename, time_column=None, time_format=None, time_scale=None, format=None, *args, **kwargs):
"""
Read and parse a file and returns a `astropy.timeseries.TimeSeries`.
This method uses the unified I/O infrastructure in Astropy which makes
it easy to define readers/writers for various classes
(https://docs.astropy.org/en/stable/io/unified.html). By default, this
method will try and use readers defined specifically for the
`astropy.timeseries.TimeSeries` class - however, it is also
possible to use the ``format`` keyword to specify formats defined for
the `astropy.table.Table` class - in this case, you will need to also
provide the column names for column containing the start times for the
bins, as well as other column names (see the Parameters section below
for details)::
>>> from astropy.timeseries import TimeSeries
>>> ts = TimeSeries.read('sampled.dat', format='ascii.ecsv',
... time_column='date') # doctest: +SKIP
Parameters
----------
filename : str
File to parse.
format : str
File format specifier.
time_column : str, optional
The name of the time column.
time_format : str, optional
The time format for the time column.
time_scale : str, optional
The time scale for the time column.
*args : tuple, optional
Positional arguments passed through to the data reader.
**kwargs : dict, optional
Keyword arguments passed through to the data reader.
Returns
-------
out : `astropy.timeseries.sampled.TimeSeries`
TimeSeries corresponding to file contents.
Notes
-----
"""
try:
# First we try the readers defined for the BinnedTimeSeries class
return super().read(filename, format=format, *args, **kwargs)
except TypeError:
# Otherwise we fall back to the default Table readers
if time_column is None:
raise ValueError("``time_column`` should be provided since the default Table readers are being used.")
table = Table.read(filename, format=format, *args, **kwargs)
if time_column in table.colnames:
time = Time(table.columns[time_column], scale=time_scale, format=time_format)
table.remove_column(time_column)
else:
raise ValueError(f"Time column '{time_column}' not found in the input data.")
return TimeSeries(time=time, data=table)
|
bf843887ca0c193e67ffdabd2f19f4e5c4d085ecdcd0884fc82c3d6e3af2caf9 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
import numpy as np
from astropy import units as u
from astropy.time import Time, TimeDelta
from astropy.utils.exceptions import AstropyUserWarning
from astropy.timeseries.sampled import TimeSeries
from astropy.timeseries.binned import BinnedTimeSeries
__all__ = ['aggregate_downsample']
def reduceat(array, indices, function):
"""
Manual reduceat functionality for cases where Numpy functions don't have a reduceat.
It will check if the input function has a reduceat and call that if it does.
"""
if len(indices) == 0:
return np.array([])
elif hasattr(function, 'reduceat'):
return np.array(function.reduceat(array, indices))
else:
result = []
for i in range(len(indices) - 1):
if indices[i+1] <= indices[i]+1:
result.append(function(array[indices[i]]))
else:
result.append(function(array[indices[i]:indices[i+1]]))
result.append(function(array[indices[-1]:]))
return np.array(result)
def aggregate_downsample(time_series, *, time_bin_size=None, time_bin_start=None,
time_bin_end=None, n_bins=None, aggregate_func=None):
"""
Downsample a time series by binning values into bins with a fixed size or
custom sizes, using a single function to combine the values in the bin.
Parameters
----------
time_series : :class:`~astropy.timeseries.TimeSeries`
The time series to downsample.
time_bin_size : `~astropy.units.Quantity` or `~astropy.time.TimeDelta` ['time'], optional
The time interval for the binned time series - this is either a scalar
value (in which case all time bins will be assumed to have the same
duration) or as an array of values (in which case each time bin can
have a different duration). If this argument is provided,
``time_bin_end`` should not be provided.
time_bin_start : `~astropy.time.Time` or iterable, optional
The start time for the binned time series - this can be either given
directly as a `~astropy.time.Time` array or as any iterable that
initializes the `~astropy.time.Time` class. This can also be a scalar
value if ``time_bin_size`` or ``time_bin_end`` is provided.
Defaults to the first time in the sampled time series.
time_bin_end : `~astropy.time.Time` or iterable, optional
The times of the end of each bin - this can be either given directly as
a `~astropy.time.Time` array or as any iterable that initializes the
`~astropy.time.Time` class. This can only be given if ``time_bin_start``
is provided or its default is used. If ``time_bin_end`` is scalar and
``time_bin_start`` is an array, time bins are assumed to be contiguous;
the end of each bin is the start of the next one, and ``time_bin_end`` gives
the end time for the last bin. If ``time_bin_end`` is an array and
``time_bin_start`` is scalar, bins will be contiguous. If both ``time_bin_end``
and ``time_bin_start`` are arrays, bins do not need to be contiguous.
If this argument is provided, ``time_bin_size`` should not be provided.
n_bins : int, optional
The number of bins to use. Defaults to the number needed to fit all
the original points. If both ``time_bin_start`` and ``time_bin_size``
are provided and are scalar values, this determines the total bins
within that interval. If ``time_bin_start`` is an iterable, this
parameter will be ignored.
aggregate_func : callable, optional
The function to use for combining points in the same bin. Defaults
to np.nanmean.
Returns
-------
binned_time_series : :class:`~astropy.timeseries.BinnedTimeSeries`
The downsampled time series.
"""
if not isinstance(time_series, TimeSeries):
raise TypeError("time_series should be a TimeSeries")
if time_bin_size is not None and not isinstance(time_bin_size, (u.Quantity, TimeDelta)):
raise TypeError("'time_bin_size' should be a Quantity or a TimeDelta")
if time_bin_start is not None and not isinstance(time_bin_start, (Time, TimeDelta)):
time_bin_start = Time(time_bin_start)
if time_bin_end is not None and not isinstance(time_bin_end, (Time, TimeDelta)):
time_bin_end = Time(time_bin_end)
# Use the table sorted by time
ts_sorted = time_series.iloc[:]
# If start time is not provided, it is assumed to be the start of the timeseries
if time_bin_start is None:
time_bin_start = ts_sorted.time[0]
# Total duration of the timeseries is needed for determining either
# `time_bin_size` or `nbins` in the case of scalar `time_bin_start`
if time_bin_start.isscalar:
time_duration = (ts_sorted.time[-1] - time_bin_start).sec
if time_bin_size is None and time_bin_end is None:
if time_bin_start.isscalar:
if n_bins is None:
raise TypeError("With single 'time_bin_start' either 'n_bins', "
"'time_bin_size' or time_bin_end' must be provided")
else:
# `nbins` defaults to the number needed to fit all points
time_bin_size = time_duration / n_bins * u.s
else:
time_bin_end = np.maximum(ts_sorted.time[-1], time_bin_start[-1])
if time_bin_start.isscalar:
if time_bin_size is not None:
if time_bin_size.isscalar:
# Determine the number of bins
if n_bins is None:
bin_size_sec = time_bin_size.to_value(u.s)
n_bins = int(np.ceil(time_duration/bin_size_sec))
elif time_bin_end is not None:
if not time_bin_end.isscalar:
# Convert start time to an array and populate using `time_bin_end`
scalar_start_time = time_bin_start
time_bin_start = time_bin_end.replicate(copy=True)
time_bin_start[0] = scalar_start_time
time_bin_start[1:] = time_bin_end[:-1]
# Check for overlapping bins, and warn if they are present
if time_bin_end is not None:
if (not time_bin_end.isscalar and not time_bin_start.isscalar and
np.any(time_bin_start[1:] < time_bin_end[:-1])):
warnings.warn("Overlapping bins should be avoided since they "
"can lead to double-counting of data during binning.",
AstropyUserWarning)
binned = BinnedTimeSeries(time_bin_size=time_bin_size,
time_bin_start=time_bin_start,
time_bin_end=time_bin_end,
n_bins=n_bins)
if aggregate_func is None:
aggregate_func = np.nanmean
# Start and end times of the binned timeseries
bin_start = binned.time_bin_start
bin_end = binned.time_bin_end
# Set `n_bins` to match the length of `time_bin_start` if
# `n_bins` is unspecified or if `time_bin_start` is an iterable
if n_bins is None or not time_bin_start.isscalar:
n_bins = len(bin_start)
# Find the subset of the table that is inside the union of all bins
keep = ((ts_sorted.time >= bin_start[0]) & (ts_sorted.time <= bin_end[-1]))
# Find out indices to be removed because of uncontiguous bins
for ind in range(n_bins-1):
delete_indices = np.where(np.logical_and(ts_sorted.time > bin_end[ind],
ts_sorted.time < bin_start[ind+1]))
keep[delete_indices] = False
subset = ts_sorted[keep]
# Figure out which bin each row falls in by sorting with respect
# to the bin end times
indices = np.searchsorted(bin_end, ts_sorted.time[keep])
# For time == bin_start[i+1] == bin_end[i], let bin_start takes precedence
if len(indices) and np.all(bin_start[1:] >= bin_end[:-1]):
indices_start = np.searchsorted(subset.time, bin_start[bin_start <= ts_sorted.time[-1]])
indices[indices_start] = np.arange(len(indices_start))
# Determine rows where values are defined
if len(indices):
groups = np.hstack([0, np.nonzero(np.diff(indices))[0] + 1])
else:
groups = np.array([])
# Find unique indices to determine which rows in the final time series
# will not be empty.
unique_indices = np.unique(indices)
# Add back columns
for colname in subset.colnames:
if colname == 'time':
continue
values = subset[colname]
# FIXME: figure out how to avoid the following, if possible
if not isinstance(values, (np.ndarray, u.Quantity)):
warnings.warn("Skipping column {0} since it has a mix-in type", AstropyUserWarning)
continue
if isinstance(values, u.Quantity):
data = u.Quantity(np.repeat(np.nan, n_bins), unit=values.unit)
data[unique_indices] = u.Quantity(reduceat(values.value, groups, aggregate_func),
values.unit, copy=False)
else:
data = np.ma.zeros(n_bins, dtype=values.dtype)
data.mask = 1
data[unique_indices] = reduceat(values, groups, aggregate_func)
data.mask[unique_indices] = 0
binned[colname] = data
return binned
|
13de87d77c2a63ef0c771caad73a501c24e16d083e7d0290b6991dce1634b291 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from types import FunctionType
from contextlib import contextmanager
from functools import wraps
from astropy.table import QTable
__all__ = ['BaseTimeSeries', 'autocheck_required_columns']
COLUMN_RELATED_METHODS = ['add_column',
'add_columns',
'keep_columns',
'remove_column',
'remove_columns',
'rename_column']
def autocheck_required_columns(cls):
"""
This is a decorator that ensures that the table contains specific
methods indicated by the _required_columns attribute. The aim is to
decorate all methods that might affect the columns in the table and check
for consistency after the methods have been run.
"""
def decorator_method(method):
@wraps(method)
def wrapper(self, *args, **kwargs):
result = method(self, *args, **kwargs)
self._check_required_columns()
return result
return wrapper
for name in COLUMN_RELATED_METHODS:
if (not hasattr(cls, name) or
not isinstance(getattr(cls, name), FunctionType)):
raise ValueError(f"{name} is not a valid method")
setattr(cls, name, decorator_method(getattr(cls, name)))
return cls
class BaseTimeSeries(QTable):
_required_columns = None
_required_columns_enabled = True
# If _required_column_relax is True, we don't require the columns to be
# present but we do require them to be the correct ones IF present. Note
# that this is a temporary state - as soon as the required columns
# are all present, we toggle this to False
_required_columns_relax = False
def _check_required_columns(self):
if not self._required_columns_enabled:
return
if self._required_columns is not None:
if self._required_columns_relax:
required_columns = self._required_columns[:len(self.colnames)]
else:
required_columns = self._required_columns
plural = 's' if len(required_columns) > 1 else ''
if not self._required_columns_relax and len(self.colnames) == 0:
raise ValueError("{} object is invalid - expected '{}' "
"as the first column{} but time series has no columns"
.format(self.__class__.__name__, required_columns[0], plural))
elif self.colnames[:len(required_columns)] != required_columns:
raise ValueError("{} object is invalid - expected '{}' "
"as the first column{} but found '{}'"
.format(self.__class__.__name__, required_columns[0], plural, self.colnames[0]))
if (self._required_columns_relax
and self._required_columns == self.colnames[:len(self._required_columns)]):
self._required_columns_relax = False
@contextmanager
def _delay_required_column_checks(self):
self._required_columns_enabled = False
yield
self._required_columns_enabled = True
self._check_required_columns()
|
12bafefa90c79474248dd9aa46b3f10a322499a8d87d943825115af1595d43c6 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains classes and functions for work with time series.
"""
from astropy.timeseries.core import * # noqa
from astropy.timeseries.sampled import * # noqa
from astropy.timeseries.binned import * # noqa
from astropy.timeseries import io # noqa
from astropy.timeseries.downsample import * # noqa
from astropy.timeseries.periodograms import * # noqa
|
a01017aa601ac8d7d297ab2b3f1618ba9d01c07cf322db3fdf9e6ddeccaaa711 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from copy import deepcopy
import numpy as np
from astropy.table import groups, Table, QTable
from astropy.time import Time, TimeDelta
from astropy import units as u
from astropy.units import Quantity
from astropy.timeseries.core import BaseTimeSeries, autocheck_required_columns
__all__ = ['BinnedTimeSeries']
@autocheck_required_columns
class BinnedTimeSeries(BaseTimeSeries):
"""
A class to represent binned time series data in tabular form.
`~astropy.timeseries.BinnedTimeSeries` provides a class for
representing time series as a collection of values of different
quantities measured in time bins (for time series with values
sampled at specific times, see the `~astropy.timeseries.TimeSeries`
class). `~astropy.timeseries.BinnedTimeSeries` is a sub-class of
`~astropy.table.QTable` and thus provides all the standard table
maniplation methods available to tables, but it also provides
additional conveniences for dealing with time series, such as a
flexible initializer for setting up the times, and attributes to
access the start/center/end time of bins.
See also: https://docs.astropy.org/en/stable/timeseries/
Parameters
----------
data : numpy ndarray, dict, list, table-like object, optional
Data to initialize time series. This does not need to contain the
times, which can be provided separately, but if it does contain the
times they should be in columns called ``'time_bin_start'`` and
``'time_bin_size'`` to be automatically recognized.
time_bin_start : `~astropy.time.Time` or iterable
The times of the start of each bin - this can be either given
directly as a `~astropy.time.Time` array or as any iterable that
initializes the `~astropy.time.Time` class. If this is given, then
the remaining time-related arguments should not be used. This can also
be a scalar value if ``time_bin_size`` is provided.
time_bin_end : `~astropy.time.Time` or iterable
The times of the end of each bin - this can be either given directly
as a `~astropy.time.Time` array or as any value or iterable that
initializes the `~astropy.time.Time` class. If this is given, then the
remaining time-related arguments should not be used. This can only be
given if ``time_bin_start`` is an array of values. If ``time_bin_end``
is a scalar, time bins are assumed to be contiguous, such that the end
of each bin is the start of the next one, and ``time_bin_end`` gives
the end time for the last bin. If ``time_bin_end`` is an array, the
time bins do not need to be contiguous. If this argument is provided,
``time_bin_size`` should not be provided.
time_bin_size : `~astropy.time.TimeDelta` or `~astropy.units.Quantity`
The size of the time bins, either as a scalar value (in which case all
time bins will be assumed to have the same duration) or as an array of
values (in which case each time bin can have a different duration).
If this argument is provided, ``time_bin_end`` should not be provided.
n_bins : int
The number of time bins for the series. This is only used if both
``time_bin_start`` and ``time_bin_size`` are provided and are scalar
values.
**kwargs : dict, optional
Additional keyword arguments are passed to `~astropy.table.QTable`.
"""
_required_columns = ['time_bin_start', 'time_bin_size']
def __init__(self, data=None, *, time_bin_start=None, time_bin_end=None,
time_bin_size=None, n_bins=None, **kwargs):
super().__init__(data=data, **kwargs)
# For some operations, an empty time series needs to be created, then
# columns added one by one. We should check that when columns are added
# manually, time is added first and is of the right type.
if (data is None and time_bin_start is None and time_bin_end is None and
time_bin_size is None and n_bins is None):
self._required_columns_relax = True
return
# First if time_bin_start and time_bin_end have been given in the table data, we
# should extract them and treat them as if they had been passed as
# keyword arguments.
if 'time_bin_start' in self.colnames:
if time_bin_start is None:
time_bin_start = self.columns['time_bin_start']
else:
raise TypeError("'time_bin_start' has been given both in the table "
"and as a keyword argument")
if 'time_bin_size' in self.colnames:
if time_bin_size is None:
time_bin_size = self.columns['time_bin_size']
else:
raise TypeError("'time_bin_size' has been given both in the table "
"and as a keyword argument")
if time_bin_start is None:
raise TypeError("'time_bin_start' has not been specified")
if time_bin_end is None and time_bin_size is None:
raise TypeError("Either 'time_bin_size' or 'time_bin_end' should be specified")
if not isinstance(time_bin_start, (Time, TimeDelta)):
time_bin_start = Time(time_bin_start)
if time_bin_end is not None and not isinstance(time_bin_end, (Time, TimeDelta)):
time_bin_end = Time(time_bin_end)
if time_bin_size is not None and not isinstance(time_bin_size, (Quantity, TimeDelta)):
raise TypeError("'time_bin_size' should be a Quantity or a TimeDelta")
if isinstance(time_bin_size, TimeDelta):
time_bin_size = time_bin_size.sec * u.s
if n_bins is not None and time_bin_size is not None:
if not (time_bin_start.isscalar and time_bin_size.isscalar):
raise TypeError("'n_bins' cannot be specified if 'time_bin_start' or "
"'time_bin_size' are not scalar'")
if time_bin_start.isscalar:
# We interpret this as meaning that this is the start of the
# first bin and that the bins are contiguous. In this case,
# we require time_bin_size to be specified.
if time_bin_size is None:
raise TypeError("'time_bin_start' is scalar, so 'time_bin_size' is required")
if time_bin_size.isscalar:
if data is not None:
if n_bins is not None:
if n_bins != len(self):
raise TypeError("'n_bins' has been given and it is not the "
"same length as the input data.")
else:
n_bins = len(self)
time_bin_size = np.repeat(time_bin_size, n_bins)
time_delta = np.cumsum(time_bin_size)
time_bin_end = time_bin_start + time_delta
# Now shift the array so that the first entry is 0
time_delta = np.roll(time_delta, 1)
time_delta[0] = 0. * u.s
# Make time_bin_start into an array
time_bin_start = time_bin_start + time_delta
else:
if len(self.colnames) > 0 and len(time_bin_start) != len(self):
raise ValueError("Length of 'time_bin_start' ({}) should match "
"table length ({})".format(len(time_bin_start), len(self)))
if time_bin_end is not None:
if time_bin_end.isscalar:
times = time_bin_start.copy()
times[:-1] = times[1:]
times[-1] = time_bin_end
time_bin_end = times
time_bin_size = (time_bin_end - time_bin_start).sec * u.s
if time_bin_size.isscalar:
time_bin_size = np.repeat(time_bin_size, len(self))
with self._delay_required_column_checks():
if 'time_bin_start' in self.colnames:
self.remove_column('time_bin_start')
if 'time_bin_size' in self.colnames:
self.remove_column('time_bin_size')
self.add_column(time_bin_start, index=0, name='time_bin_start')
self.add_index('time_bin_start')
self.add_column(time_bin_size, index=1, name='time_bin_size')
@property
def time_bin_start(self):
"""
The start times of all the time bins.
"""
return self['time_bin_start']
@property
def time_bin_center(self):
"""
The center times of all the time bins.
"""
return self['time_bin_start'] + self['time_bin_size'] * 0.5
@property
def time_bin_end(self):
"""
The end times of all the time bins.
"""
return self['time_bin_start'] + self['time_bin_size']
@property
def time_bin_size(self):
"""
The sizes of all the time bins.
"""
return self['time_bin_size']
def __getitem__(self, item):
if self._is_list_or_tuple_of_str(item):
if 'time_bin_start' not in item or 'time_bin_size' not in item:
out = QTable([self[x] for x in item],
meta=deepcopy(self.meta),
copy_indices=self._copy_indices)
out._groups = groups.TableGroups(out, indices=self.groups._indices,
keys=self.groups._keys)
return out
return super().__getitem__(item)
@classmethod
def read(self, filename, time_bin_start_column=None, time_bin_end_column=None,
time_bin_size_column=None, time_bin_size_unit=None, time_format=None, time_scale=None,
format=None, *args, **kwargs):
"""
Read and parse a file and returns a `astropy.timeseries.BinnedTimeSeries`.
This method uses the unified I/O infrastructure in Astropy which makes
it easy to define readers/writers for various classes
(https://docs.astropy.org/en/stable/io/unified.html). By default, this
method will try and use readers defined specifically for the
`astropy.timeseries.BinnedTimeSeries` class - however, it is also
possible to use the ``format`` keyword to specify formats defined for
the `astropy.table.Table` class - in this case, you will need to also
provide the column names for column containing the start times for the
bins, as well as other column names (see the Parameters section below
for details)::
>>> from astropy.timeseries.binned import BinnedTimeSeries
>>> ts = BinnedTimeSeries.read('binned.dat', format='ascii.ecsv',
... time_bin_start_column='date_start',
... time_bin_end_column='date_end') # doctest: +SKIP
Parameters
----------
filename : str
File to parse.
format : str
File format specifier.
time_bin_start_column : str
The name of the column with the start time for each bin.
time_bin_end_column : str, optional
The name of the column with the end time for each bin. Either this
option or ``time_bin_size_column`` should be specified.
time_bin_size_column : str, optional
The name of the column with the size for each bin. Either this
option or ``time_bin_end_column`` should be specified.
time_bin_size_unit : `astropy.units.Unit`, optional
If ``time_bin_size_column`` is specified but does not have a unit
set in the table, you can specify the unit manually.
time_format : str, optional
The time format for the start and end columns.
time_scale : str, optional
The time scale for the start and end columns.
*args : tuple, optional
Positional arguments passed through to the data reader.
**kwargs : dict, optional
Keyword arguments passed through to the data reader.
Returns
-------
out : `astropy.timeseries.binned.BinnedTimeSeries`
BinnedTimeSeries corresponding to the file.
"""
try:
# First we try the readers defined for the BinnedTimeSeries class
return super().read(filename, format=format, *args, **kwargs)
except TypeError:
# Otherwise we fall back to the default Table readers
if time_bin_start_column is None:
raise ValueError("``time_bin_start_column`` should be provided since the default Table readers are being used.")
if time_bin_end_column is None and time_bin_size_column is None:
raise ValueError("Either `time_bin_end_column` or `time_bin_size_column` should be provided.")
elif time_bin_end_column is not None and time_bin_size_column is not None:
raise ValueError("Cannot specify both `time_bin_end_column` and `time_bin_size_column`.")
table = Table.read(filename, format=format, *args, **kwargs)
if time_bin_start_column in table.colnames:
time_bin_start = Time(table.columns[time_bin_start_column],
scale=time_scale, format=time_format)
table.remove_column(time_bin_start_column)
else:
raise ValueError(f"Bin start time column '{time_bin_start_column}' not found in the input data.")
if time_bin_end_column is not None:
if time_bin_end_column in table.colnames:
time_bin_end = Time(table.columns[time_bin_end_column],
scale=time_scale, format=time_format)
table.remove_column(time_bin_end_column)
else:
raise ValueError(f"Bin end time column '{time_bin_end_column}' not found in the input data.")
time_bin_size = None
elif time_bin_size_column is not None:
if time_bin_size_column in table.colnames:
time_bin_size = table.columns[time_bin_size_column]
table.remove_column(time_bin_size_column)
else:
raise ValueError(f"Bin size column '{time_bin_size_column}' not found in the input data.")
if time_bin_size.unit is None:
if time_bin_size_unit is None or not isinstance(time_bin_size_unit, u.UnitBase):
raise ValueError("The bin size unit should be specified as an astropy Unit using ``time_bin_size_unit``.")
time_bin_size = time_bin_size * time_bin_size_unit
else:
time_bin_size = u.Quantity(time_bin_size)
time_bin_end = None
if time_bin_start.isscalar and time_bin_size.isscalar:
return BinnedTimeSeries(data=table,
time_bin_start=time_bin_start,
time_bin_end=time_bin_end,
time_bin_size=time_bin_size,
n_bins=len(table))
else:
return BinnedTimeSeries(data=table,
time_bin_start=time_bin_start,
time_bin_end=time_bin_end,
time_bin_size=time_bin_size)
|
2b052e76622356a4fb1d7bb817a70f3191e445a7cb445f94d90ea01556079572 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import numpy as np
from .constant import Constant
# ASTRONOMICAL CONSTANTS
class IAU2012(Constant):
default_reference = 'IAU 2012'
_registry = {}
_has_incompatible_units = set()
# DISTANCE
# Astronomical Unit
au = IAU2012('au', "Astronomical Unit", 1.49597870700e11, 'm', 0.0,
"IAU 2012 Resolution B2", system='si')
# Parsec
pc = IAU2012('pc', "Parsec", au.value / np.tan(np.radians(1. / 3600.)), 'm',
au.uncertainty / np.tan(np.radians(1. / 3600.)),
"Derived from au", system='si')
# Kiloparsec
kpc = IAU2012('kpc', "Kiloparsec",
1000. * au.value / np.tan(np.radians(1. / 3600.)), 'm',
1000. * au.uncertainty / np.tan(np.radians(1. / 3600.)),
"Derived from au", system='si')
# Luminosity not defined till 2015 (https://arxiv.org/abs/1510.06262)
L_bol0 = IAU2012('L_bol0', "Luminosity for absolute bolometric magnitude 0",
3.0128e28, "W", 0.0, "IAU 2015 Resolution B 2", system='si')
# SOLAR QUANTITIES
# Solar luminosity
L_sun = IAU2012('L_sun', "Solar luminosity", 3.846e26, 'W', 0.0005e26,
"Allen's Astrophysical Quantities 4th Ed.", system='si')
# Solar mass
M_sun = IAU2012('M_sun', "Solar mass", 1.9891e30, 'kg', 0.00005e30,
"Allen's Astrophysical Quantities 4th Ed.", system='si')
# Solar radius
R_sun = IAU2012('R_sun', "Solar radius", 6.95508e8, 'm', 0.00026e8,
"Allen's Astrophysical Quantities 4th Ed.", system='si')
# OTHER SOLAR SYSTEM QUANTITIES
# Jupiter mass
M_jup = IAU2012('M_jup', "Jupiter mass", 1.8987e27, 'kg', 0.00005e27,
"Allen's Astrophysical Quantities 4th Ed.", system='si')
# Jupiter equatorial radius
R_jup = IAU2012('R_jup', "Jupiter equatorial radius", 7.1492e7, 'm',
0.00005e7, "Allen's Astrophysical Quantities 4th Ed.",
system='si')
# Earth mass
M_earth = IAU2012('M_earth', "Earth mass", 5.9742e24, 'kg', 0.00005e24,
"Allen's Astrophysical Quantities 4th Ed.", system='si')
# Earth equatorial radius
R_earth = IAU2012('R_earth', "Earth equatorial radius", 6.378136e6, 'm',
0.0000005e6, "Allen's Astrophysical Quantities 4th Ed.",
system='si')
|
962480a7a67d3204612f2c04dc495749b714fd32724ba9c8beea205bcbff4961 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import numpy as np
from .constant import Constant, EMConstant
# PHYSICAL CONSTANTS
class CODATA2014(Constant):
default_reference = 'CODATA 2014'
_registry = {}
_has_incompatible_units = set()
class EMCODATA2014(CODATA2014, EMConstant):
_registry = CODATA2014._registry
h = CODATA2014('h', "Planck constant", 6.626070040e-34,
'J s', 0.000000081e-34, system='si')
hbar = CODATA2014('hbar', "Reduced Planck constant", 1.054571800e-34,
'J s', 0.000000013e-34, system='si')
k_B = CODATA2014('k_B', "Boltzmann constant", 1.38064852e-23,
'J / (K)', 0.00000079e-23, system='si')
c = CODATA2014('c', "Speed of light in vacuum", 299792458.,
'm / (s)', 0.0, system='si')
G = CODATA2014('G', "Gravitational constant", 6.67408e-11,
'm3 / (kg s2)', 0.00031e-11, system='si')
g0 = CODATA2014('g0', "Standard acceleration of gravity", 9.80665,
'm / s2', 0.0, system='si')
m_p = CODATA2014('m_p', "Proton mass", 1.672621898e-27,
'kg', 0.000000021e-27, system='si')
m_n = CODATA2014('m_n', "Neutron mass", 1.674927471e-27,
'kg', 0.000000021e-27, system='si')
m_e = CODATA2014('m_e', "Electron mass", 9.10938356e-31,
'kg', 0.00000011e-31, system='si')
u = CODATA2014('u', "Atomic mass", 1.660539040e-27,
'kg', 0.000000020e-27, system='si')
sigma_sb = CODATA2014('sigma_sb', "Stefan-Boltzmann constant", 5.670367e-8,
'W / (K4 m2)', 0.000013e-8, system='si')
e = EMCODATA2014('e', 'Electron charge', 1.6021766208e-19,
'C', 0.0000000098e-19, system='si')
eps0 = EMCODATA2014('eps0', 'Electric constant', 8.854187817e-12,
'F/m', 0.0, system='si')
N_A = CODATA2014('N_A', "Avogadro's number", 6.022140857e23,
'1 / (mol)', 0.000000074e23, system='si')
R = CODATA2014('R', "Gas constant", 8.3144598,
'J / (K mol)', 0.0000048, system='si')
Ryd = CODATA2014('Ryd', 'Rydberg constant', 10973731.568508,
'1 / (m)', 0.000065, system='si')
a0 = CODATA2014('a0', "Bohr radius", 0.52917721067e-10,
'm', 0.00000000012e-10, system='si')
muB = CODATA2014('muB', "Bohr magneton", 927.4009994e-26,
'J/T', 0.00002e-26, system='si')
alpha = CODATA2014('alpha', "Fine-structure constant", 7.2973525664e-3,
'', 0.0000000017e-3, system='si')
atm = CODATA2014('atm', "Standard atmosphere", 101325,
'Pa', 0.0, system='si')
mu0 = CODATA2014('mu0', "Magnetic constant", 4.0e-7 * np.pi, 'N/A2', 0.0,
system='si')
sigma_T = CODATA2014('sigma_T', "Thomson scattering cross-section",
0.66524587158e-28, 'm2', 0.00000000091e-28,
system='si')
b_wien = CODATA2014('b_wien', 'Wien wavelength displacement law constant',
2.8977729e-3, 'm K', 0.0000017e-3, system='si')
# cgs constants
# Only constants that cannot be converted directly from S.I. are defined here.
e_esu = EMCODATA2014(e.abbrev, e.name, e.value * c.value * 10.0,
'statC', e.uncertainty * c.value * 10.0, system='esu')
e_emu = EMCODATA2014(e.abbrev, e.name, e.value / 10, 'abC',
e.uncertainty / 10, system='emu')
e_gauss = EMCODATA2014(e.abbrev, e.name, e.value * c.value * 10.0,
'Fr', e.uncertainty * c.value * 10.0, system='gauss')
|
089651864317bba25e07875b72e9a461233662cb29a69224b2a40a6609639bb8 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Contains astronomical and physical constants for use in Astropy or other
places.
A typical use case might be::
>>> from astropy.constants import c, m_e
>>> # ... define the mass of something you want the rest energy of as m ...
>>> m = m_e
>>> E = m * c**2
>>> E.to('MeV') # doctest: +FLOAT_CMP
<Quantity 0.510998927603161 MeV>
"""
import warnings
from astropy.utils import find_current_module
# Hack to make circular imports with units work
# isort: split
from astropy import units
del units
from . import cgs # noqa
from . import si # noqa
from . import utils as _utils # noqa
from .config import codata, iaudata # noqa
from .constant import Constant, EMConstant # noqa
# for updating the constants module docstring
_lines = [
'The following constants are available:\n',
'========== ============== ================ =========================',
' Name Value Unit Description',
'========== ============== ================ =========================',
]
# Catch warnings about "already has a definition in the None system"
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'Constant .*already has a definition')
_utils._set_c(codata, iaudata, find_current_module(),
not_in_module_only=True, doclines=_lines, set_class=True)
_lines.append(_lines[1])
if __doc__ is not None:
__doc__ += '\n'.join(_lines)
# Clean up namespace
del find_current_module
del warnings
del _utils
del _lines
|
fd79b52eba117c7394745dc90764d9b527072abba1fd56f786b1d32527a232af | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import numpy as np
from .constant import Constant, EMConstant
# PHYSICAL CONSTANTS
class CODATA2010(Constant):
default_reference = 'CODATA 2010'
_registry = {}
_has_incompatible_units = set()
def __new__(cls, abbrev, name, value, unit, uncertainty,
reference=default_reference, system=None):
return super().__new__(
cls, abbrev, name, value, unit, uncertainty, reference, system)
class EMCODATA2010(CODATA2010, EMConstant):
_registry = CODATA2010._registry
h = CODATA2010('h', "Planck constant", 6.62606957e-34, 'J s',
0.00000029e-34, system='si')
hbar = CODATA2010('hbar', "Reduced Planck constant",
h.value * 0.5 / np.pi, 'J s',
h.uncertainty * 0.5 / np.pi,
h.reference, system='si')
k_B = CODATA2010('k_B', "Boltzmann constant", 1.3806488e-23, 'J / (K)',
0.0000013e-23, system='si')
c = CODATA2010('c', "Speed of light in vacuum", 2.99792458e8, 'm / (s)', 0.,
system='si')
G = CODATA2010('G', "Gravitational constant", 6.67384e-11, 'm3 / (kg s2)',
0.00080e-11, system='si')
g0 = CODATA2010('g0', "Standard acceleration of gravity", 9.80665, 'm / s2',
0.0, system='si')
m_p = CODATA2010('m_p', "Proton mass", 1.672621777e-27, 'kg', 0.000000074e-27,
system='si')
m_n = CODATA2010('m_n', "Neutron mass", 1.674927351e-27, 'kg', 0.000000074e-27,
system='si')
m_e = CODATA2010('m_e', "Electron mass", 9.10938291e-31, 'kg', 0.00000040e-31,
system='si')
u = CODATA2010('u', "Atomic mass", 1.660538921e-27, 'kg', 0.000000073e-27,
system='si')
sigma_sb = CODATA2010('sigma_sb', "Stefan-Boltzmann constant", 5.670373e-8,
'W / (K4 m2)', 0.000021e-8, system='si')
e = EMCODATA2010('e', 'Electron charge', 1.602176565e-19, 'C', 0.000000035e-19,
system='si')
eps0 = EMCODATA2010('eps0', 'Electric constant', 8.854187817e-12, 'F/m', 0.0,
system='si')
N_A = CODATA2010('N_A', "Avogadro's number", 6.02214129e23, '1 / (mol)',
0.00000027e23, system='si')
R = CODATA2010('R', "Gas constant", 8.3144621, 'J / (K mol)', 0.0000075,
system='si')
Ryd = CODATA2010('Ryd', 'Rydberg constant', 10973731.568539, '1 / (m)',
0.000055, system='si')
a0 = CODATA2010('a0', "Bohr radius", 0.52917721092e-10, 'm', 0.00000000017e-10,
system='si')
muB = CODATA2010('muB', "Bohr magneton", 927.400968e-26, 'J/T', 0.00002e-26,
system='si')
alpha = CODATA2010('alpha', "Fine-structure constant", 7.2973525698e-3,
'', 0.0000000024e-3, system='si')
atm = CODATA2010('atm', "Standard atmosphere", 101325, 'Pa', 0.0,
system='si')
mu0 = CODATA2010('mu0', "Magnetic constant", 4.0e-7 * np.pi, 'N/A2', 0.0,
system='si')
sigma_T = CODATA2010('sigma_T', "Thomson scattering cross-section",
0.6652458734e-28, 'm2', 0.0000000013e-28, system='si')
b_wien = Constant('b_wien', 'Wien wavelength displacement law constant',
2.8977721e-3, 'm K', 0.0000026e-3, 'CODATA 2010', system='si')
# cgs constants
# Only constants that cannot be converted directly from S.I. are defined here.
e_esu = EMCODATA2010(e.abbrev, e.name, e.value * c.value * 10.0,
'statC', e.uncertainty * c.value * 10.0, system='esu')
e_emu = EMCODATA2010(e.abbrev, e.name, e.value / 10, 'abC',
e.uncertainty / 10, system='emu')
e_gauss = EMCODATA2010(e.abbrev, e.name, e.value * c.value * 10.0,
'Fr', e.uncertainty * c.value * 10.0, system='gauss')
|
b0178bb8388a3015d0974ce61b2fe5bf201adea6495584ade50f10ab30540c78 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants for Astropy v1.3 and earlier.
See :mod:`astropy.constants` for a complete listing of constants
defined in Astropy.
"""
from astropy.utils import find_current_module
from . import codata2010, iau2012
from . import utils as _utils
codata = codata2010
iaudata = iau2012
_utils._set_c(codata, iaudata, find_current_module())
# Clean up namespace
del find_current_module
del _utils
|
b039f90e668a1e39fdf5c494c7274c2beefaa71499ee7dd66f7d5b051d0a1a6c | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import numpy as np
from .config import codata
from .constant import Constant
# ASTRONOMICAL CONSTANTS
class IAU2015(Constant):
default_reference = 'IAU 2015'
_registry = {}
_has_incompatible_units = set()
# DISTANCE
# Astronomical Unit (did not change from 2012)
au = IAU2015('au', "Astronomical Unit", 1.49597870700e11, 'm', 0.0,
"IAU 2012 Resolution B2", system='si')
# Parsec
pc = IAU2015('pc', "Parsec", au.value / np.radians(1. / 3600.), 'm',
au.uncertainty / np.radians(1. / 3600.),
"Derived from au + IAU 2015 Resolution B 2 note [4]", system='si')
# Kiloparsec
kpc = IAU2015('kpc', "Kiloparsec",
1000. * au.value / np.radians(1. / 3600.), 'm',
1000. * au.uncertainty / np.radians(1. / 3600.),
"Derived from au + IAU 2015 Resolution B 2 note [4]", system='si')
# Luminosity
L_bol0 = IAU2015('L_bol0', "Luminosity for absolute bolometric magnitude 0",
3.0128e28, "W", 0.0, "IAU 2015 Resolution B 2", system='si')
# SOLAR QUANTITIES
# Solar luminosity
L_sun = IAU2015('L_sun', "Nominal solar luminosity", 3.828e26,
'W', 0.0, "IAU 2015 Resolution B 3", system='si')
# Solar mass parameter
GM_sun = IAU2015('GM_sun', 'Nominal solar mass parameter', 1.3271244e20,
'm3 / (s2)', 0.0, "IAU 2015 Resolution B 3", system='si')
# Solar mass (derived from mass parameter and gravitational constant)
M_sun = IAU2015('M_sun', "Solar mass", GM_sun.value / codata.G.value,
'kg', ((codata.G.uncertainty / codata.G.value) *
(GM_sun.value / codata.G.value)),
f"IAU 2015 Resolution B 3 + {codata.G.reference}",
system='si')
# Solar radius
R_sun = IAU2015('R_sun', "Nominal solar radius", 6.957e8, 'm', 0.0,
"IAU 2015 Resolution B 3", system='si')
# OTHER SOLAR SYSTEM QUANTITIES
# Jupiter mass parameter
GM_jup = IAU2015('GM_jup', 'Nominal Jupiter mass parameter', 1.2668653e17,
'm3 / (s2)', 0.0, "IAU 2015 Resolution B 3", system='si')
# Jupiter mass (derived from mass parameter and gravitational constant)
M_jup = IAU2015('M_jup', "Jupiter mass", GM_jup.value / codata.G.value,
'kg', ((codata.G.uncertainty / codata.G.value) *
(GM_jup.value / codata.G.value)),
f"IAU 2015 Resolution B 3 + {codata.G.reference}",
system='si')
# Jupiter equatorial radius
R_jup = IAU2015('R_jup', "Nominal Jupiter equatorial radius", 7.1492e7,
'm', 0.0, "IAU 2015 Resolution B 3", system='si')
# Earth mass parameter
GM_earth = IAU2015('GM_earth', 'Nominal Earth mass parameter', 3.986004e14,
'm3 / (s2)', 0.0, "IAU 2015 Resolution B 3", system='si')
# Earth mass (derived from mass parameter and gravitational constant)
M_earth = IAU2015('M_earth', "Earth mass",
GM_earth.value / codata.G.value,
'kg', ((codata.G.uncertainty / codata.G.value) *
(GM_earth.value / codata.G.value)),
f"IAU 2015 Resolution B 3 + {codata.G.reference}",
system='si')
# Earth equatorial radius
R_earth = IAU2015('R_earth', "Nominal Earth equatorial radius", 6.3781e6,
'm', 0.0, "IAU 2015 Resolution B 3", system='si')
|
9a3dea90e2172c28bbc5a2eb2695408d7594a87f2a3dea949b2c21eda17b3926 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Configures the codata and iaudata used, possibly using user configuration.
"""
# Note: doing this in __init__ causes import problems with units,
# as si.py and cgs.py have to import the result.
import importlib
import astropy
phys_version = astropy.physical_constants.get()
astro_version = astropy.astronomical_constants.get()
codata = importlib.import_module('.constants.' + phys_version, 'astropy')
iaudata = importlib.import_module('.constants.' + astro_version, 'astropy')
|
88f385a7cb4c00df5cd822b50da19f8f261818590511e060e06009f3e48221a5 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants for Astropy v2.0.
See :mod:`astropy.constants` for a complete listing of constants defined
in Astropy.
"""
import warnings
from astropy.utils import find_current_module
from . import codata2014, iau2015
from . import utils as _utils
codata = codata2014
iaudata = iau2015
_utils._set_c(codata, iaudata, find_current_module())
# Overwrite the following for consistency.
# https://github.com/astropy/astropy/issues/8920
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'Constant .*already has a definition')
# Solar mass (derived from mass parameter and gravitational constant)
M_sun = iau2015.IAU2015(
'M_sun', "Solar mass", iau2015.GM_sun.value / codata2014.G.value,
'kg', ((codata2014.G.uncertainty / codata2014.G.value) *
(iau2015.GM_sun.value / codata2014.G.value)),
f"IAU 2015 Resolution B 3 + {codata2014.G.reference}", system='si')
# Jupiter mass (derived from mass parameter and gravitational constant)
M_jup = iau2015.IAU2015(
'M_jup', "Jupiter mass", iau2015.GM_jup.value / codata2014.G.value,
'kg', ((codata2014.G.uncertainty / codata2014.G.value) *
(iau2015.GM_jup.value / codata2014.G.value)),
f"IAU 2015 Resolution B 3 + {codata2014.G.reference}", system='si')
# Earth mass (derived from mass parameter and gravitational constant)
M_earth = iau2015.IAU2015(
'M_earth', "Earth mass",
iau2015.GM_earth.value / codata2014.G.value,
'kg', ((codata2014.G.uncertainty / codata2014.G.value) *
(iau2015.GM_earth.value / codata2014.G.value)),
f"IAU 2015 Resolution B 3 + {codata2014.G.reference}", system='si')
# Clean up namespace
del warnings
del find_current_module
del _utils
|
185b5aa991e83f454530c0e08b0d3349a67b22157b508e9098d1d0d3bd834749 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Utility functions for ``constants`` sub-package."""
import itertools
__all__ = []
def _get_c(codata, iaudata, module, not_in_module_only=True):
"""
Generator to return a Constant object.
Parameters
----------
codata, iaudata : obj
Modules containing CODATA and IAU constants of interest.
module : obj
Namespace module of interest.
not_in_module_only : bool
If ``True``, ignore constants that are already in the
namespace of ``module``.
Returns
-------
_c : Constant
Constant object to process.
"""
from .constant import Constant
for _nm, _c in itertools.chain(sorted(vars(codata).items()),
sorted(vars(iaudata).items())):
if not isinstance(_c, Constant):
continue
elif (not not_in_module_only) or (_c.abbrev not in module.__dict__):
yield _c
def _set_c(codata, iaudata, module, not_in_module_only=True, doclines=None,
set_class=False):
"""
Set constants in a given module namespace.
Parameters
----------
codata, iaudata : obj
Modules containing CODATA and IAU constants of interest.
module : obj
Namespace module to modify with the given ``codata`` and ``iaudata``.
not_in_module_only : bool
If ``True``, constants that are already in the namespace
of ``module`` will not be modified.
doclines : list or None
If a list is given, this list will be modified in-place to include
documentation of modified constants. This can be used to update
docstring of ``module``.
set_class : bool
Namespace of ``module`` is populated with ``_c.__class__``
instead of just ``_c`` from :func:`_get_c`.
"""
for _c in _get_c(codata, iaudata, module,
not_in_module_only=not_in_module_only):
if set_class:
value = _c.__class__(_c.abbrev, _c.name, _c.value,
_c._unit_string, _c.uncertainty,
_c.reference)
else:
value = _c
setattr(module, _c.abbrev, value)
if doclines is not None:
doclines.append('{:^10} {:^14.9g} {:^16} {}'.format(
_c.abbrev, _c.value, _c._unit_string, _c.name))
|
72b4dd0198b2a91b998465ebd1f7f7dd57e2724af501ee3fe91131f0fab930ac | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in cgs units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import itertools
from .config import codata, iaudata
from .constant import Constant
for _nm, _c in itertools.chain(sorted(vars(codata).items()),
sorted(vars(iaudata).items())):
if (isinstance(_c, Constant) and _c.abbrev not in locals()
and _c.system in ['esu', 'gauss', 'emu']):
locals()[_c.abbrev] = _c
|
9be6c25ddb4036b8127c2a045df1fb9f648f769af80e0c0b357549445ca6d986 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import functools
import types
import warnings
import numpy as np
from astropy.units.core import Unit, UnitsError
from astropy.units.quantity import Quantity
from astropy.utils import lazyproperty
from astropy.utils.exceptions import AstropyUserWarning
__all__ = ['Constant', 'EMConstant']
class ConstantMeta(type):
"""Metaclass for `~astropy.constants.Constant`. The primary purpose of this
is to wrap the double-underscore methods of `~astropy.units.Quantity`
which is the superclass of `~astropy.constants.Constant`.
In particular this wraps the operator overloads such as `__add__` to
prevent their use with constants such as ``e`` from being used in
expressions without specifying a system. The wrapper checks to see if the
constant is listed (by name) in ``Constant._has_incompatible_units``, a set
of those constants that are defined in different systems of units are
physically incompatible. It also performs this check on each `Constant` if
it hasn't already been performed (the check is deferred until the
`Constant` is actually used in an expression to speed up import times,
among other reasons).
"""
def __new__(mcls, name, bases, d):
def wrap(meth):
@functools.wraps(meth)
def wrapper(self, *args, **kwargs):
name_lower = self.name.lower()
instances = self._registry[name_lower]
if not self._checked_units:
for inst in instances.values():
try:
self.unit.to(inst.unit)
except UnitsError:
self._has_incompatible_units.add(name_lower)
self._checked_units = True
if (not self.system and
name_lower in self._has_incompatible_units):
systems = sorted([x for x in instances if x])
raise TypeError(
'Constant {!r} does not have physically compatible '
'units across all systems of units and cannot be '
'combined with other values without specifying a '
'system (eg. {}.{})'.format(self.abbrev, self.abbrev,
systems[0]))
return meth(self, *args, **kwargs)
return wrapper
# The wrapper applies to so many of the __ methods that it's easier to
# just exclude the ones it doesn't apply to
exclude = set(['__new__', '__array_finalize__', '__array_wrap__',
'__dir__', '__getattr__', '__init__', '__str__',
'__repr__', '__hash__', '__iter__', '__getitem__',
'__len__', '__bool__', '__quantity_subclass__',
'__setstate__'])
for attr, value in vars(Quantity).items():
if (isinstance(value, types.FunctionType) and
attr.startswith('__') and attr.endswith('__') and
attr not in exclude):
d[attr] = wrap(value)
return super().__new__(mcls, name, bases, d)
class Constant(Quantity, metaclass=ConstantMeta):
"""A physical or astronomical constant.
These objects are quantities that are meant to represent physical
constants.
"""
_registry = {}
_has_incompatible_units = set()
def __new__(cls, abbrev, name, value, unit, uncertainty,
reference=None, system=None):
if reference is None:
reference = getattr(cls, 'default_reference', None)
if reference is None:
raise TypeError(f"{cls} requires a reference.")
name_lower = name.lower()
instances = cls._registry.setdefault(name_lower, {})
# By-pass Quantity initialization, since units may not yet be
# initialized here, and we store the unit in string form.
inst = np.array(value).view(cls)
if system in instances:
warnings.warn('Constant {!r} already has a definition in the '
'{!r} system from {!r} reference'.format(
name, system, reference), AstropyUserWarning)
for c in instances.values():
if system is not None and not hasattr(c.__class__, system):
setattr(c, system, inst)
if c.system is not None and not hasattr(inst.__class__, c.system):
setattr(inst, c.system, c)
instances[system] = inst
inst._abbrev = abbrev
inst._name = name
inst._value = value
inst._unit_string = unit
inst._uncertainty = uncertainty
inst._reference = reference
inst._system = system
inst._checked_units = False
return inst
def __repr__(self):
return ('<{} name={!r} value={} uncertainty={} unit={!r} '
'reference={!r}>'.format(self.__class__, self.name, self.value,
self.uncertainty, str(self.unit),
self.reference))
def __str__(self):
return (' Name = {}\n'
' Value = {}\n'
' Uncertainty = {}\n'
' Unit = {}\n'
' Reference = {}'.format(self.name, self.value,
self.uncertainty, self.unit,
self.reference))
def __quantity_subclass__(self, unit):
return super().__quantity_subclass__(unit)[0], False
def copy(self):
"""
Return a copy of this `Constant` instance. Since they are by
definition immutable, this merely returns another reference to
``self``.
"""
return self
__deepcopy__ = __copy__ = copy
@property
def abbrev(self):
"""A typical ASCII text abbreviation of the constant, also generally
the same as the Python variable used for this constant.
"""
return self._abbrev
@property
def name(self):
"""The full name of the constant."""
return self._name
@lazyproperty
def _unit(self):
"""The unit(s) in which this constant is defined."""
return Unit(self._unit_string)
@property
def uncertainty(self):
"""The known absolute uncertainty in this constant's value."""
return self._uncertainty
@property
def reference(self):
"""The source used for the value of this constant."""
return self._reference
@property
def system(self):
"""The system of units in which this constant is defined (typically
`None` so long as the constant's units can be directly converted
between systems).
"""
return self._system
def _instance_or_super(self, key):
instances = self._registry[self.name.lower()]
inst = instances.get(key)
if inst is not None:
return inst
else:
return getattr(super(), key)
@property
def si(self):
"""If the Constant is defined in the SI system return that instance of
the constant, else convert to a Quantity in the appropriate SI units.
"""
return self._instance_or_super('si')
@property
def cgs(self):
"""If the Constant is defined in the CGS system return that instance of
the constant, else convert to a Quantity in the appropriate CGS units.
"""
return self._instance_or_super('cgs')
def __array_finalize__(self, obj):
for attr in ('_abbrev', '_name', '_value', '_unit_string',
'_uncertainty', '_reference', '_system'):
setattr(self, attr, getattr(obj, attr, None))
self._checked_units = getattr(obj, '_checked_units', False)
class EMConstant(Constant):
"""An electromagnetic constant."""
@property
def cgs(self):
"""Overridden for EMConstant to raise a `TypeError`
emphasizing that there are multiple EM extensions to CGS.
"""
raise TypeError("Cannot convert EM constants to cgs because there "
"are different systems for E.M constants within the "
"c.g.s system (ESU, Gaussian, etc.). Instead, "
"directly use the constant with the appropriate "
"suffix (e.g. e.esu, e.gauss, etc.).")
|
bcbc46772575b503a3faf8cbff3d5bbcff77ca65a48021cb1c36552ae5ab0373 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants for Astropy v4.0.
See :mod:`astropy.constants` for a complete listing of constants defined
in Astropy.
"""
import warnings
from astropy.utils import find_current_module
from . import codata2018, iau2015
from . import utils as _utils
codata = codata2018
iaudata = iau2015
_utils._set_c(codata, iaudata, find_current_module())
# Overwrite the following for consistency.
# https://github.com/astropy/astropy/issues/8920
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'Constant .*already has a definition')
# Solar mass (derived from mass parameter and gravitational constant)
M_sun = iau2015.IAU2015(
'M_sun', "Solar mass", iau2015.GM_sun.value / codata2018.G.value,
'kg', ((codata2018.G.uncertainty / codata2018.G.value) *
(iau2015.GM_sun.value / codata2018.G.value)),
f"IAU 2015 Resolution B 3 + {codata2018.G.reference}", system='si')
# Jupiter mass (derived from mass parameter and gravitational constant)
M_jup = iau2015.IAU2015(
'M_jup', "Jupiter mass", iau2015.GM_jup.value / codata2018.G.value,
'kg', ((codata2018.G.uncertainty / codata2018.G.value) *
(iau2015.GM_jup.value / codata2018.G.value)),
f"IAU 2015 Resolution B 3 + {codata2018.G.reference}", system='si')
# Earth mass (derived from mass parameter and gravitational constant)
M_earth = iau2015.IAU2015(
'M_earth', "Earth mass",
iau2015.GM_earth.value / codata2018.G.value,
'kg', ((codata2018.G.uncertainty / codata2018.G.value) *
(iau2015.GM_earth.value / codata2018.G.value)),
f"IAU 2015 Resolution B 3 + {codata2018.G.reference}", system='si')
# Clean up namespace
del warnings
del find_current_module
del _utils
|
976ff12fa11e050043c7801f3a4cb51982819dfaa6e5ba50cab1302bf7277924 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import itertools
from .config import codata, iaudata
from .constant import Constant
for _nm, _c in itertools.chain(sorted(vars(codata).items()),
sorted(vars(iaudata).items())):
if (isinstance(_c, Constant) and _c.abbrev not in locals()
and _c.system == 'si'):
locals()[_c.abbrev] = _c
|
00c41d4824c990c4eb4e3ce78c573bb001c0835bddee0dfd3c55fbcbe31883c3 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import math
from .constant import Constant, EMConstant
# PHYSICAL CONSTANTS
# https://en.wikipedia.org/wiki/2019_redefinition_of_SI_base_units
class CODATA2018(Constant):
default_reference = 'CODATA 2018'
_registry = {}
_has_incompatible_units = set()
class EMCODATA2018(CODATA2018, EMConstant):
_registry = CODATA2018._registry
h = CODATA2018('h', "Planck constant", 6.62607015e-34,
'J s', 0.0, system='si')
hbar = CODATA2018('hbar', "Reduced Planck constant", h.value / (2 * math.pi),
'J s', 0.0, system='si')
k_B = CODATA2018('k_B', "Boltzmann constant", 1.380649e-23,
'J / (K)', 0.0, system='si')
c = CODATA2018('c', "Speed of light in vacuum", 299792458.,
'm / (s)', 0.0, system='si')
G = CODATA2018('G', "Gravitational constant", 6.67430e-11,
'm3 / (kg s2)', 0.00015e-11, system='si')
g0 = CODATA2018('g0', "Standard acceleration of gravity", 9.80665,
'm / s2', 0.0, system='si')
m_p = CODATA2018('m_p', "Proton mass", 1.67262192369e-27,
'kg', 0.00000000051e-27, system='si')
m_n = CODATA2018('m_n', "Neutron mass", 1.67492749804e-27,
'kg', 0.00000000095e-27, system='si')
m_e = CODATA2018('m_e', "Electron mass", 9.1093837015e-31,
'kg', 0.0000000028e-31, system='si')
u = CODATA2018('u', "Atomic mass", 1.66053906660e-27,
'kg', 0.00000000050e-27, system='si')
sigma_sb = CODATA2018(
'sigma_sb', "Stefan-Boltzmann constant",
2 * math.pi ** 5 * k_B.value ** 4 / (15 * h.value ** 3 * c.value ** 2),
'W / (K4 m2)', 0.0, system='si')
e = EMCODATA2018('e', 'Electron charge', 1.602176634e-19,
'C', 0.0, system='si')
eps0 = EMCODATA2018('eps0', 'Vacuum electric permittivity', 8.8541878128e-12,
'F/m', 0.0000000013e-12, system='si')
N_A = CODATA2018('N_A', "Avogadro's number", 6.02214076e23,
'1 / (mol)', 0.0, system='si')
R = CODATA2018('R', "Gas constant", k_B.value * N_A.value,
'J / (K mol)', 0.0, system='si')
Ryd = CODATA2018('Ryd', 'Rydberg constant', 10973731.568160,
'1 / (m)', 0.000021, system='si')
a0 = CODATA2018('a0', "Bohr radius", 5.29177210903e-11,
'm', 0.00000000080e-11, system='si')
muB = CODATA2018('muB', "Bohr magneton", 9.2740100783e-24,
'J/T', 0.0000000028e-24, system='si')
alpha = CODATA2018('alpha', "Fine-structure constant", 7.2973525693e-3,
'', 0.0000000011e-3, system='si')
atm = CODATA2018('atm', "Standard atmosphere", 101325,
'Pa', 0.0, system='si')
mu0 = CODATA2018('mu0', "Vacuum magnetic permeability", 1.25663706212e-6,
'N/A2', 0.00000000019e-6, system='si')
sigma_T = CODATA2018('sigma_T', "Thomson scattering cross-section",
6.6524587321e-29, 'm2', 0.0000000060e-29,
system='si')
# Formula taken from NIST wall chart.
# The numerical factor is from a numerical solution to the equation for the
# maximum. See https://en.wikipedia.org/wiki/Wien%27s_displacement_law
b_wien = CODATA2018('b_wien', 'Wien wavelength displacement law constant',
h.value * c.value / (k_B.value * 4.965114231744276), 'm K',
0.0, system='si')
# CGS constants.
# Only constants that cannot be converted directly from S.I. are defined here.
# Because both e and c are exact, these are also exact by definition.
e_esu = EMCODATA2018(e.abbrev, e.name, e.value * c.value * 10.0,
'statC', 0.0, system='esu')
e_emu = EMCODATA2018(e.abbrev, e.name, e.value / 10, 'abC',
0.0, system='emu')
e_gauss = EMCODATA2018(e.abbrev, e.name, e.value * c.value * 10.0,
'Fr', 0.0, system='gauss')
|
e49231749ad552e062197ebbba862da1c031a01008ec76d5c0a6af792afaf50b | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""This module contains dictionaries with sets of parameters for a
given cosmology.
Each cosmology has the following parameters defined:
========== =====================================
Oc0 Omega cold dark matter at z=0
Ob0 Omega baryon at z=0
Om0 Omega matter at z=0
flat Is this assumed flat? If not, Ode0 must be specified
Ode0 Omega dark energy at z=0 if flat is False
H0 Hubble parameter at z=0 in km/s/Mpc
n Density perturbation spectral index
Tcmb0 Current temperature of the CMB
Neff Effective number of neutrino species
m_nu Assumed mass of neutrino species, in eV.
sigma8 Density perturbation amplitude
tau Ionisation optical depth
z_reion Redshift of hydrogen reionisation
t0 Age of the universe in Gyr
reference Reference for the parameters
========== =====================================
The list of cosmologies available are given by the tuple
`available`. Current cosmologies available:
Planck 2018 (Planck18) parameters from Planck Collaboration 2020,
A&A, 641, A6 (Paper VI), Table 2 (TT, TE, EE + lowE + lensing + BAO)
Planck 2015 (Planck15) parameters from Planck Collaboration 2016, A&A, 594, A13
(Paper XIII), Table 4 (TT, TE, EE + lowP + lensing + ext)
Planck 2013 (Planck13) parameters from Planck Collaboration 2014, A&A, 571, A16
(Paper XVI), Table 5 (Planck + WP + highL + BAO)
WMAP 9 year (WMAP9) parameters from Hinshaw et al. 2013, ApJS, 208, 19,
doi: 10.1088/0067-0049/208/2/19. Table 4 (WMAP9 + eCMB + BAO + H0)
WMAP 7 year (WMAP7) parameters from Komatsu et al. 2011, ApJS, 192, 18,
doi: 10.1088/0067-0049/192/2/18. Table 1 (WMAP + BAO + H0 ML).
WMAP 5 year (WMAP5) parameters from Komatsu et al. 2009, ApJS, 180, 330,
doi: 10.1088/0067-0049/180/2/330. Table 1 (WMAP + BAO + SN ML).
WMAP 3 year (WMAP3) parameters from Spergel et al. 2007, ApJS, 170, 377,
doi: 10.1086/513700. Table 6. (WMAP + SNGold) Obtained from https://lambda.gsfc.nasa.gov/product/map/dr2/params/lcdm_wmap_sngold.cfm
Tcmb0 and Neff are the standard values as also used for WMAP5, 7, 9.
Pending WMAP team approval and subject to change.
WMAP 1 year (WMAP1) parameters from Spergel et al. 2003, ApJS, 148, 175,
doi: 10.1086/377226. Table 7 (WMAP + CBI + ACBAR + 2dFGRS + Lya)
Tcmb0 and Neff are the standard values as also used for WMAP5, 7, 9.
Pending WMAP team approval and subject to change.
"""
# STDLIB
import sys
from types import MappingProxyType
# LOCAL
from .realizations import available
__all__ = ["available"] + list(available)
def __getattr__(name):
"""Get parameters of cosmology representations with lazy import from
`PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_.
"""
from astropy.cosmology import realizations
cosmo = getattr(realizations, name)
m = cosmo.to_format("mapping", cosmology_as_str=True, move_from_meta=True)
proxy = MappingProxyType(m)
# Cache in this module so `__getattr__` is only called once per `name`.
setattr(sys.modules[__name__], name, proxy)
return proxy
def __dir__():
"""Directory, including lazily-imported objects."""
return __all__
|
c6905a0e821ad74b5c19dfa4118df045377ec4aa77fb30132794e045e895edbe | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import copy
import warnings
from astropy.cosmology import units as cu
from astropy.io import registry as io_registry
from astropy.units import add_enabled_units
from astropy.utils.exceptions import AstropyUserWarning
__all__ = ["CosmologyRead", "CosmologyWrite",
"CosmologyFromFormat", "CosmologyToFormat"]
__doctest_skip__ = __all__
# ==============================================================================
# Read / Write
readwrite_registry = io_registry.UnifiedIORegistry()
class CosmologyRead(io_registry.UnifiedReadWrite):
"""Read and parse data to a `~astropy.cosmology.Cosmology`.
This function provides the Cosmology interface to the Astropy unified I/O
layer. This allows easily reading a file in supported data formats using
syntax such as::
>>> from astropy.cosmology import Cosmology
>>> cosmo1 = Cosmology.read('<file name>')
When the ``read`` method is called from a subclass the subclass will
provide a keyword argument ``cosmology=<class>`` to the registered read
method. The method uses this cosmology class, regardless of the class
indicated in the file, and sets parameters' default values from the class'
signature.
Get help on the available readers using the ``help()`` method::
>>> Cosmology.read.help() # Get help reading and list supported formats
>>> Cosmology.read.help(format='<format>') # Get detailed help on a format
>>> Cosmology.read.list_formats() # Print list of available formats
See also: https://docs.astropy.org/en/stable/io/unified.html
Parameters
----------
*args
Positional arguments passed through to data reader. If supplied the
first argument is typically the input filename.
format : str (optional, keyword-only)
File format specifier.
**kwargs
Keyword arguments passed through to data reader.
Returns
-------
out : `~astropy.cosmology.Cosmology` subclass instance
`~astropy.cosmology.Cosmology` corresponding to file contents.
Notes
-----
"""
def __init__(self, instance, cosmo_cls):
super().__init__(instance, cosmo_cls, "read", registry=readwrite_registry)
def __call__(self, *args, **kwargs):
from astropy.cosmology.core import Cosmology
# so subclasses can override, also pass the class as a kwarg.
# allows for `FlatLambdaCDM.read` and
# `Cosmology.read(..., cosmology=FlatLambdaCDM)`
if self._cls is not Cosmology:
kwargs.setdefault("cosmology", self._cls) # set, if not present
# check that it is the correct cosmology, can be wrong if user
# passes in e.g. `w0wzCDM.read(..., cosmology=FlatLambdaCDM)`
valid = (self._cls, self._cls.__qualname__)
if kwargs["cosmology"] not in valid:
raise ValueError(
"keyword argument `cosmology` must be either the class "
f"{valid[0]} or its qualified name '{valid[1]}'")
with add_enabled_units(cu):
cosmo = self.registry.read(self._cls, *args, **kwargs)
return cosmo
class CosmologyWrite(io_registry.UnifiedReadWrite):
"""Write this Cosmology object out in the specified format.
This function provides the Cosmology interface to the astropy unified I/O
layer. This allows easily writing a file in supported data formats
using syntax such as::
>>> from astropy.cosmology import Planck18
>>> Planck18.write('<file name>')
Get help on the available writers for ``Cosmology`` using the ``help()``
method::
>>> Cosmology.write.help() # Get help writing and list supported formats
>>> Cosmology.write.help(format='<format>') # Get detailed help on format
>>> Cosmology.write.list_formats() # Print list of available formats
Parameters
----------
*args
Positional arguments passed through to data writer. If supplied the
first argument is the output filename.
format : str (optional, keyword-only)
File format specifier.
**kwargs
Keyword arguments passed through to data writer.
Notes
-----
"""
def __init__(self, instance, cls):
super().__init__(instance, cls, "write", registry=readwrite_registry)
def __call__(self, *args, **kwargs):
self.registry.write(self._instance, *args, **kwargs)
# ==============================================================================
# Format Interchange
# for transforming instances, e.g. Cosmology <-> dict
convert_registry = io_registry.UnifiedIORegistry()
class CosmologyFromFormat(io_registry.UnifiedReadWrite):
"""Transform object to a `~astropy.cosmology.Cosmology`.
This function provides the Cosmology interface to the Astropy unified I/O
layer. This allows easily parsing supported data formats using
syntax such as::
>>> from astropy.cosmology import Cosmology
>>> cosmo1 = Cosmology.from_format(cosmo_mapping, format='mapping')
When the ``from_format`` method is called from a subclass the subclass will
provide a keyword argument ``cosmology=<class>`` to the registered parser.
The method uses this cosmology class, regardless of the class indicated in
the data, and sets parameters' default values from the class' signature.
Get help on the available readers using the ``help()`` method::
>>> Cosmology.from_format.help() # Get help and list supported formats
>>> Cosmology.from_format.help('<format>') # Get detailed help on a format
>>> Cosmology.from_format.list_formats() # Print list of available formats
See also: https://docs.astropy.org/en/stable/io/unified.html
Parameters
----------
obj : object
The object to parse according to 'format'
*args
Positional arguments passed through to data parser.
format : str or None, optional keyword-only
Object format specifier. For `None` (default) CosmologyFromFormat tries
to identify the correct format.
**kwargs
Keyword arguments passed through to data parser.
Parsers should accept the following keyword arguments:
- cosmology : the class (or string name thereof) to use / check when
constructing the cosmology instance.
Returns
-------
out : `~astropy.cosmology.Cosmology` subclass instance
`~astropy.cosmology.Cosmology` corresponding to ``obj`` contents.
"""
def __init__(self, instance, cosmo_cls):
super().__init__(instance, cosmo_cls, "read", registry=convert_registry)
def __call__(self, obj, *args, format=None, **kwargs):
from astropy.cosmology.core import Cosmology
# so subclasses can override, also pass the class as a kwarg.
# allows for `FlatLambdaCDM.read` and
# `Cosmology.read(..., cosmology=FlatLambdaCDM)`
if self._cls is not Cosmology:
kwargs.setdefault("cosmology", self._cls) # set, if not present
# check that it is the correct cosmology, can be wrong if user
# passes in e.g. `w0wzCDM.read(..., cosmology=FlatLambdaCDM)`
valid = (self._cls, self._cls.__qualname__)
if kwargs["cosmology"] not in valid:
raise ValueError(
"keyword argument `cosmology` must be either the class "
f"{valid[0]} or its qualified name '{valid[1]}'")
with add_enabled_units(cu):
cosmo = self.registry.read(self._cls, obj, *args, format=format, **kwargs)
return cosmo
class CosmologyToFormat(io_registry.UnifiedReadWrite):
"""Transform this Cosmology to another format.
This function provides the Cosmology interface to the astropy unified I/O
layer. This allows easily transforming to supported data formats
using syntax such as::
>>> from astropy.cosmology import Planck18
>>> Planck18.to_format("mapping")
{'cosmology': astropy.cosmology.core.FlatLambdaCDM,
'name': 'Planck18',
'H0': <Quantity 67.66 km / (Mpc s)>,
'Om0': 0.30966,
...
Get help on the available representations for ``Cosmology`` using the
``help()`` method::
>>> Cosmology.to_format.help() # Get help and list supported formats
>>> Cosmology.to_format.help('<format>') # Get detailed help on format
>>> Cosmology.to_format.list_formats() # Print list of available formats
Parameters
----------
format : str
Format specifier.
*args
Positional arguments passed through to data writer. If supplied the
first argument is the output filename.
**kwargs
Keyword arguments passed through to data writer.
"""
def __init__(self, instance, cls):
super().__init__(instance, cls, "write", registry=convert_registry)
def __call__(self, format, *args, **kwargs):
return self.registry.write(self._instance, None, *args, format=format,
**kwargs)
|
af167934d42107f854842b239855a5ae9899fd37e66c52fbcfb05dca24a053ff | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import abc
import functools
import inspect
from types import FunctionType, MappingProxyType
import numpy as np
import astropy.units as u
from astropy.io.registry import UnifiedReadWriteMethod
from astropy.utils.decorators import classproperty
from astropy.utils.metadata import MetaData
from .connect import CosmologyFromFormat, CosmologyRead, CosmologyToFormat, CosmologyWrite
from .parameter import Parameter
# Originally authored by Andrew Becker (becker@astro.washington.edu),
# and modified by Neil Crighton (neilcrighton@gmail.com), Roban Kramer
# (robanhk@gmail.com), and Nathaniel Starkman (n.starkman@mail.utoronto.ca).
# Many of these adapted from Hogg 1999, astro-ph/9905116
# and Linder 2003, PRL 90, 91301
__all__ = ["Cosmology", "CosmologyError", "FlatCosmologyMixin"]
__doctest_requires__ = {} # needed until __getattr__ removed
# registry of cosmology classes with {key=name : value=class}
_COSMOLOGY_CLASSES = dict()
class CosmologyError(Exception):
pass
class Cosmology(metaclass=abc.ABCMeta):
"""Base-class for all Cosmologies.
Parameters
----------
*args
Arguments into the cosmology; used by subclasses, not this base class.
name : str or None (optional, keyword-only)
The name of the cosmology.
meta : dict or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
**kwargs
Arguments into the cosmology; used by subclasses, not this base class.
Notes
-----
Class instances are static -- you cannot (and should not) change the values
of the parameters. That is, all of the above attributes (except meta) are
read only.
For details on how to create performant custom subclasses, see the
documentation on :ref:`astropy-cosmology-fast-integrals`.
"""
meta = MetaData()
# Unified I/O object interchange methods
from_format = UnifiedReadWriteMethod(CosmologyFromFormat)
to_format = UnifiedReadWriteMethod(CosmologyToFormat)
# Unified I/O read and write methods
read = UnifiedReadWriteMethod(CosmologyRead)
write = UnifiedReadWriteMethod(CosmologyWrite)
# Parameters
__parameters__ = ()
__all_parameters__ = ()
# ---------------------------------------------------------------
def __init_subclass__(cls):
super().__init_subclass__()
# -------------------
# Parameters
# Get parameters that are still Parameters, either in this class or above.
parameters = []
derived_parameters = []
for n in cls.__parameters__:
p = getattr(cls, n)
if isinstance(p, Parameter):
derived_parameters.append(n) if p.derived else parameters.append(n)
# Add new parameter definitions
for n, v in cls.__dict__.items():
if n in parameters or n.startswith("_") or not isinstance(v, Parameter):
continue
derived_parameters.append(n) if v.derived else parameters.append(n)
# reorder to match signature
ordered = [parameters.pop(parameters.index(n))
for n in cls._init_signature.parameters.keys()
if n in parameters]
parameters = ordered + parameters # place "unordered" at the end
cls.__parameters__ = tuple(parameters)
cls.__all_parameters__ = cls.__parameters__ + tuple(derived_parameters)
# -------------------
# register as a Cosmology subclass
_COSMOLOGY_CLASSES[cls.__qualname__] = cls
@classproperty(lazy=True)
def _init_signature(cls):
"""Initialization signature (without 'self')."""
# get signature, dropping "self" by taking arguments [1:]
sig = inspect.signature(cls.__init__)
sig = sig.replace(parameters=list(sig.parameters.values())[1:])
return sig
# ---------------------------------------------------------------
def __init__(self, name=None, meta=None):
self._name = str(name) if name is not None else name
self.meta.update(meta or {})
@property
def name(self):
"""The name of the Cosmology instance."""
return self._name
@property
@abc.abstractmethod
def is_flat(self):
"""
Return bool; `True` if the cosmology is flat.
This is abstract and must be defined in subclasses.
"""
raise NotImplementedError("is_flat is not implemented")
def clone(self, *, meta=None, **kwargs):
"""Returns a copy of this object with updated parameters, as specified.
This cannot be used to change the type of the cosmology, so ``clone()``
cannot be used to change between flat and non-flat cosmologies.
Parameters
----------
meta : mapping or None (optional, keyword-only)
Metadata that will update the current metadata.
**kwargs
Cosmology parameter (and name) modifications.
If any parameter is changed and a new name is not given, the name
will be set to "[old name] (modified)".
Returns
-------
newcosmo : `~astropy.cosmology.Cosmology` subclass instance
A new instance of this class with updated parameters as specified.
If no modifications are requested, then a reference to this object
is returned instead of copy.
Examples
--------
To make a copy of the ``Planck13`` cosmology with a different matter
density (``Om0``), and a new name:
>>> from astropy.cosmology import Planck13
>>> newcosmo = Planck13.clone(name="Modified Planck 2013", Om0=0.35)
If no name is specified, the new name will note the modification.
>>> Planck13.clone(Om0=0.35).name
'Planck13 (modified)'
"""
# Quick return check, taking advantage of the Cosmology immutability.
if meta is None and not kwargs:
return self
# There are changed parameter or metadata values.
# The name needs to be changed accordingly, if it wasn't already.
kwargs.setdefault("name", (self.name + " (modified)"
if self.name is not None else None))
# mix new meta into existing, preferring the former.
new_meta = {**self.meta, **(meta or {})}
# Mix kwargs into initial arguments, preferring the former.
new_init = {**self._init_arguments, "meta": new_meta, **kwargs}
# Create BoundArgument to handle args versus kwargs.
# This also handles all errors from mismatched arguments
ba = self._init_signature.bind_partial(**new_init)
# Return new instance, respecting args vs kwargs
return self.__class__(*ba.args, **ba.kwargs)
@property
def _init_arguments(self):
# parameters
kw = {n: getattr(self, n) for n in self.__parameters__}
# other info
kw["name"] = self.name
kw["meta"] = self.meta
return kw
# ---------------------------------------------------------------
# comparison methods
def is_equivalent(self, other, *, format=False):
r"""Check equivalence between Cosmologies.
Two cosmologies may be equivalent even if not the same class.
For example, an instance of ``LambdaCDM`` might have :math:`\Omega_0=1`
and :math:`\Omega_k=0` and therefore be flat, like ``FlatLambdaCDM``.
Parameters
----------
other : `~astropy.cosmology.Cosmology` subclass instance
The object in which to compare.
format : bool or None or str, optional keyword-only
Whether to allow, before equivalence is checked, the object to be
converted to a |Cosmology|. This allows, e.g. a |Table| to be
equivalent to a Cosmology.
`False` (default) will not allow conversion. `True` or `None` will,
and will use the auto-identification to try to infer the correct
format. A `str` is assumed to be the correct format to use when
converting.
Returns
-------
bool
True if cosmologies are equivalent, False otherwise.
Examples
--------
Two cosmologies may be equivalent even if not of the same class.
In this examples the ``LambdaCDM`` has ``Ode0`` set to the same value
calculated in ``FlatLambdaCDM``.
>>> import astropy.units as u
>>> from astropy.cosmology import LambdaCDM, FlatLambdaCDM
>>> cosmo1 = LambdaCDM(70 * (u.km/u.s/u.Mpc), 0.3, 0.7)
>>> cosmo2 = FlatLambdaCDM(70 * (u.km/u.s/u.Mpc), 0.3)
>>> cosmo1.is_equivalent(cosmo2)
True
While in this example, the cosmologies are not equivalent.
>>> cosmo3 = FlatLambdaCDM(70 * (u.km/u.s/u.Mpc), 0.3, Tcmb0=3 * u.K)
>>> cosmo3.is_equivalent(cosmo2)
False
Also, using the keyword argument, the notion of equivalence is extended
to any Python object that can be converted to a |Cosmology|.
>>> from astropy.cosmology import Planck18
>>> tbl = Planck18.to_format("astropy.table")
>>> Planck18.is_equivalent(tbl, format=True)
True
The list of valid formats, e.g. the |Table| in this example, may be
checked with ``Cosmology.from_format.list_formats()``.
As can be seen in the list of formats, not all formats can be
auto-identified by ``Cosmology.from_format.registry``. Objects of
these kinds can still be checked for equivalence, but the correct
format string must be used.
>>> tbl = Planck18.to_format("yaml")
>>> Planck18.is_equivalent(tbl, format="yaml")
True
"""
# Allow for different formats to be considered equivalent.
if format is not False:
format = None if format is True else format # str->str, None/True->None
try:
other = Cosmology.from_format(other, format=format)
except Exception: # TODO! should enforce only TypeError
return False
# The options are: 1) same class & parameters; 2) same class, different
# parameters; 3) different classes, equivalent parameters; 4) different
# classes, different parameters. (1) & (3) => True, (2) & (4) => False.
equiv = self.__equiv__(other)
if equiv is NotImplemented and hasattr(other, "__equiv__"):
equiv = other.__equiv__(self) # that failed, try from 'other'
return equiv if equiv is not NotImplemented else False
def __equiv__(self, other):
"""Cosmology equivalence. Use ``.is_equivalent()`` for actual check!
Parameters
----------
other : `~astropy.cosmology.Cosmology` subclass instance
The object in which to compare.
Returns
-------
bool or `NotImplemented`
`NotImplemented` if 'other' is from a different class.
`True` if 'other' is of the same class and has matching parameters
and parameter values. `False` otherwise.
"""
if other.__class__ is not self.__class__:
return NotImplemented # allows other.__equiv__
# check all parameters in 'other' match those in 'self' and 'other' has
# no extra parameters (latter part should never happen b/c same class)
params_eq = (set(self.__all_parameters__) == set(other.__all_parameters__)
and all(np.all(getattr(self, k) == getattr(other, k))
for k in self.__all_parameters__))
return params_eq
def __eq__(self, other):
"""Check equality between Cosmologies.
Checks the Parameters and immutable fields (i.e. not "meta").
Parameters
----------
other : `~astropy.cosmology.Cosmology` subclass instance
The object in which to compare.
Returns
-------
bool
`True` if Parameters and names are the same, `False` otherwise.
"""
if other.__class__ is not self.__class__:
return NotImplemented # allows other.__eq__
# check all parameters in 'other' match those in 'self'
equivalent = self.__equiv__(other)
# non-Parameter checks: name
name_eq = (self.name == other.name)
return equivalent and name_eq
# ---------------------------------------------------------------
def __repr__(self):
ps = {k: getattr(self, k) for k in self.__parameters__} # values
cps = {k: getattr(self.__class__, k) for k in self.__parameters__} # Parameter objects
namelead = f"{self.__class__.__qualname__}("
if self.name is not None:
namelead += f"name=\"{self.name}\", "
# nicely formatted parameters
fmtps = (k + '=' + format(v, cps[k].format_spec if v is not None else '')
for k, v in ps.items())
return namelead + ", ".join(fmtps) + ")"
def __astropy_table__(self, cls, copy, **kwargs):
"""Return a `~astropy.table.Table` of type ``cls``.
Parameters
----------
cls : type
Astropy ``Table`` class or subclass.
copy : bool
Ignored.
**kwargs : dict, optional
Additional keyword arguments. Passed to ``self.to_format()``.
See ``Cosmology.to_format.help("astropy.table")`` for allowed kwargs.
Returns
-------
`astropy.table.Table` or subclass instance
Instance of type ``cls``.
"""
return self.to_format("astropy.table", cls=cls, **kwargs)
class FlatCosmologyMixin(metaclass=abc.ABCMeta):
"""
Mixin class for flat cosmologies. Do NOT instantiate directly.
Note that all instances of ``FlatCosmologyMixin`` are flat, but not all
flat cosmologies are instances of ``FlatCosmologyMixin``. As example,
``LambdaCDM`` **may** be flat (for the a specific set of parameter values),
but ``FlatLambdaCDM`` **will** be flat.
"""
@property
def is_flat(self):
"""Return `True`, the cosmology is flat."""
return True
# -----------------------------------------------------------------------------
def __getattr__(attr):
from . import flrw
if hasattr(flrw, attr):
import warnings
from astropy.utils.exceptions import AstropyDeprecationWarning
warnings.warn(
f"`astropy.cosmology.core.{attr}` has been moved (since v5.0) and "
f"should be imported as ``from astropy.cosmology import {attr}``."
" In future this will raise an exception.",
AstropyDeprecationWarning
)
return getattr(flrw, attr)
raise AttributeError(f"module {__name__!r} has no attribute {attr!r}.")
|
74bcdc4e801627cb6d98839998bf856bb6c6b1a556cdab7315493169e132d998 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
""" astropy.cosmology contains classes and functions for cosmological
distance measures and other cosmology-related calculations.
See the `Astropy documentation
<https://docs.astropy.org/en/latest/cosmology/index.html>`_ for more
detailed usage examples and references.
"""
from . import core, flrw, funcs, parameter, units, utils
from . import io # needed before 'realizations' # isort: split
from . import realizations
from .core import *
from .flrw import *
from .funcs import *
from .parameter import *
from .realizations import available, default_cosmology
from .utils import *
__all__ = (core.__all__ + flrw.__all__ # cosmology classes
+ realizations.__all__ # instances thereof
+ ["units"]
+ funcs.__all__ + parameter.__all__ + utils.__all__) # utils
def __getattr__(name):
"""Get realizations using lazy import from
`PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_.
Raises
------
AttributeError
If "name" is not in :mod:`astropy.cosmology.realizations`
"""
if name not in realizations.available:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}.")
return getattr(realizations, name)
def __dir__():
"""Directory, including lazily-imported objects."""
return __all__
|
359ff16a32d960f853bcbe1012d4994b8646a21467e97ff1d3d089707f5331a1 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import astropy.units as u
from astropy.utils.decorators import classproperty
__all__ = ["Parameter"]
class Parameter:
r"""Cosmological parameter (descriptor).
Should only be used with a :class:`~astropy.cosmology.Cosmology` subclass.
Parameters
----------
derived : bool (optional, keyword-only)
Whether the Parameter is 'derived', default `False`.
Derived parameters behave similarly to normal parameters, but are not
sorted by the |Cosmology| signature (probably not there) and are not
included in all methods. For reference, see ``Ode0`` in
``FlatFLRWMixin``, which removes :math:`\Omega_{de,0}`` as an
independent parameter (:math:`\Omega_{de,0} \equiv 1 - \Omega_{tot}`).
unit : unit-like or None (optional, keyword-only)
The `~astropy.units.Unit` for the Parameter. If None (default) no
unit as assumed.
equivalencies : `~astropy.units.Equivalency` or sequence thereof
Unit equivalencies for this Parameter.
fvalidate : callable[[object, object, Any], Any] or str (optional, keyword-only)
Function to validate the Parameter value from instances of the
cosmology class. If "default", uses default validator to assign units
(with equivalencies), if Parameter has units.
For other valid string options, see ``Parameter._registry_validators``.
'fvalidate' can also be set through a decorator with
:meth:`~astropy.cosmology.Parameter.validator`.
fmt : str (optional, keyword-only)
`format` specification, used when making string representation
of the containing Cosmology.
See https://docs.python.org/3/library/string.html#formatspec
doc : str or None (optional, keyword-only)
Parameter description.
Examples
--------
For worked examples see :class:`~astropy.cosmology.FLRW`.
"""
_registry_validators = {}
def __init__(self, *, derived=False, unit=None, equivalencies=[],
fvalidate="default", fmt="", doc=None):
# attribute name on container cosmology class.
# really set in __set_name__, but if Parameter is not init'ed as a
# descriptor this ensures that the attributes exist.
self._attr_name = self._attr_name_private = None
self._derived = derived
self._fmt = str(fmt) # @property is `format_spec`
self.__doc__ = doc
# units stuff
self._unit = u.Unit(unit) if unit is not None else None
self._equivalencies = equivalencies
# Parse registered `fvalidate`
self._fvalidate_in = fvalidate # Always store input fvalidate.
if callable(fvalidate):
pass
elif fvalidate in self._registry_validators:
fvalidate = self._registry_validators[fvalidate]
elif isinstance(fvalidate, str):
raise ValueError("`fvalidate`, if str, must be in "
f"{self._registry_validators.keys()}")
else:
raise TypeError("`fvalidate` must be a function or "
f"{self._registry_validators.keys()}")
self._fvalidate = fvalidate
def __set_name__(self, cosmo_cls, name):
# attribute name on container cosmology class
self._attr_name = name
self._attr_name_private = "_" + name
@property
def name(self):
"""Parameter name."""
return self._attr_name
@property
def unit(self):
"""Parameter unit."""
return self._unit
@property
def equivalencies(self):
"""Equivalencies used when initializing Parameter."""
return self._equivalencies
@property
def format_spec(self):
"""String format specification."""
return self._fmt
@property
def derived(self):
"""Whether the Parameter is derived; true parameters are not."""
return self._derived
# -------------------------------------------
# descriptor and property-like methods
def __get__(self, cosmology, cosmo_cls=None):
# get from class
if cosmology is None:
return self
return getattr(cosmology, self._attr_name_private)
def __set__(self, cosmology, value):
"""Allows attribute setting once. Raises AttributeError subsequently."""
# raise error if setting 2nd time.
if hasattr(cosmology, self._attr_name_private):
raise AttributeError("can't set attribute")
# validate value, generally setting units if present
value = self.validate(cosmology, value)
setattr(cosmology, self._attr_name_private, value)
# -------------------------------------------
# validate value
@property
def fvalidate(self):
"""Function to validate a potential value of this Parameter.."""
return self._fvalidate
def validator(self, fvalidate):
"""Make new Parameter with custom ``fvalidate``.
Note: ``Parameter.fvalidator`` must be the top-most descriptor decorator.
Parameters
----------
fvalidate : callable[[type, type, Any], Any]
Returns
-------
`~astropy.cosmology.Parameter`
Copy of this Parameter but with custom ``fvalidate``.
"""
return self.clone(fvalidate=fvalidate)
def validate(self, cosmology, value):
"""Run the validator on this Parameter.
Parameters
----------
cosmology : `~astropy.cosmology.Cosmology` instance
value : Any
The object to validate.
Returns
-------
Any
The output of calling ``fvalidate(cosmology, self, value)``
(yes, that parameter order).
"""
return self.fvalidate(cosmology, self, value)
@classmethod
def register_validator(cls, key, fvalidate=None):
"""Decorator to register a new kind of validator function.
Parameters
----------
key : str
fvalidate : callable[[object, object, Any], Any] or None, optional
Value validation function.
Returns
-------
``validator`` or callable[``validator``]
if validator is None returns a function that takes and registers a
validator. This allows ``register_validator`` to be used as a
decorator.
"""
if key in cls._registry_validators:
raise KeyError(f"validator {key!r} already registered with Parameter.")
# fvalidate directly passed
if fvalidate is not None:
cls._registry_validators[key] = fvalidate
return fvalidate
# for use as a decorator
def register(fvalidate):
"""Register validator function.
Parameters
----------
fvalidate : callable[[object, object, Any], Any]
Validation function.
Returns
-------
``validator``
"""
cls._registry_validators[key] = fvalidate
return fvalidate
return register
# -------------------------------------------
def _get_init_arguments(self, processed=False):
"""Initialization arguments.
Parameters
----------
processed : bool
Whether to more closely reproduce the input arguments (`False`,
default) or the processed arguments (`True`). The former is better
for string representations and round-tripping with ``eval(repr())``.
Returns
-------
dict[str, Any]
"""
# The keys are added in this order because `repr` prints them in order.
kw = {"derived": self.derived,
"unit": self.unit,
"equivalencies": self.equivalencies,
# Validator is always turned into a function, but for ``repr`` it's nice
# to know if it was originally a string.
"fvalidate": self.fvalidate if processed else self._fvalidate_in,
"fmt": self.format_spec,
"doc": self.__doc__}
return kw
def clone(self, **kw):
"""Clone this `Parameter`, changing any constructor argument.
Parameters
----------
**kw
Passed to constructor. The current values, eg. ``fvalidate`` are
used as the default values, so an empty ``**kw`` is an exact copy.
Examples
--------
>>> p = Parameter()
>>> p
Parameter(derived=False, unit=None, equivalencies=[],
fvalidate='default', fmt='', doc=None)
>>> p.clone(unit="km")
Parameter(derived=False, unit=Unit("km"), equivalencies=[],
fvalidate='default', fmt='', doc=None)
"""
# Start with defaults, update from kw.
kwargs = {**self._get_init_arguments(), **kw}
# All initialization failures, like incorrect input are handled by init
cloned = type(self)(**kwargs)
# Transfer over the __set_name__ stuff. If `clone` is used to make a
# new descriptor, __set_name__ will be called again, overwriting this.
cloned._attr_name = self._attr_name
cloned._attr_name_private = self._attr_name_private
return cloned
def __eq__(self, other):
"""Check Parameter equality. Only equal to other Parameter objects.
Returns
-------
NotImplemented or True
`True` if equal, `NotImplemented` otherwise. This allows `other` to
be check for equality with ``other.__eq__``.
Examples
--------
>>> p1, p2 = Parameter(unit="km"), Parameter(unit="km")
>>> p1 == p2
True
>>> p3 = Parameter(unit="km / s")
>>> p3 == p1
False
>>> p1 != 2
True
"""
if not isinstance(other, Parameter):
return NotImplemented
# Check equality on all `_init_arguments` & `name`.
# Need to compare the processed arguments because the inputs are many-
# to-one, e.g. `fvalidate` can be a string or the equivalent function.
return ((self._get_init_arguments(True) == other._get_init_arguments(True))
and (self.name == other.name))
def __repr__(self):
"""String representation.
``eval(repr())`` should work, depending if contents like ``fvalidate``
can be similarly round-tripped.
"""
return "Parameter({})".format(", ".join(f"{k}={v!r}" for k, v in
self._get_init_arguments().items()))
# ===================================================================
# Built-in validators
@Parameter.register_validator("default")
def _validate_with_unit(cosmology, param, value):
"""
Default Parameter value validator.
Adds/converts units if Parameter has a unit.
"""
if param.unit is not None:
with u.add_enabled_equivalencies(param.equivalencies):
value = u.Quantity(value, param.unit)
return value
@Parameter.register_validator("float")
def _validate_to_float(cosmology, param, value):
"""Parameter value validator with units, and converted to float."""
value = _validate_with_unit(cosmology, param, value)
return float(value)
@Parameter.register_validator("scalar")
def _validate_to_scalar(cosmology, param, value):
""""""
value = _validate_with_unit(cosmology, param, value)
if not value.isscalar:
raise ValueError(f"{param.name} is a non-scalar quantity")
return value
@Parameter.register_validator("non-negative")
def _validate_non_negative(cosmology, param, value):
"""Parameter value validator where value is a positive float."""
value = _validate_to_float(cosmology, param, value)
if value < 0.0:
raise ValueError(f"{param.name} cannot be negative.")
return value
|
a563c44ea373606c2aa93c54655c2c69444c59dea5b4678d57d02e363f4b431e | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
from abc import abstractmethod
from math import acos, cos, exp, floor, inf, log, pi, sin, sqrt
from numbers import Number
import numpy as np
import astropy.constants as const
import astropy.units as u
from astropy.utils.compat.optional_deps import HAS_SCIPY
from astropy.utils.decorators import lazyproperty
from astropy.utils.exceptions import AstropyUserWarning
from . import scalar_inv_efuncs
from . import units as cu
from .core import Cosmology, FlatCosmologyMixin, Parameter
from .parameter import _validate_non_negative, _validate_with_unit
from .utils import aszarr, vectorize_redshift_method
# isort: split
if HAS_SCIPY:
from scipy.integrate import quad
from scipy.special import ellipkinc, hyp2f1
else:
def quad(*args, **kwargs):
raise ModuleNotFoundError("No module named 'scipy.integrate'")
def ellipkinc(*args, **kwargs):
raise ModuleNotFoundError("No module named 'scipy.special'")
def hyp2f1(*args, **kwargs):
raise ModuleNotFoundError("No module named 'scipy.special'")
__all__ = ["FLRW", "LambdaCDM", "FlatLambdaCDM", "wCDM", "FlatwCDM",
"w0waCDM", "Flatw0waCDM", "wpwaCDM", "w0wzCDM", "FlatFLRWMixin"]
__doctest_requires__ = {'*': ['scipy']}
# Some conversion constants -- useful to compute them once here and reuse in
# the initialization rather than have every object do them.
H0units_to_invs = (u.km / (u.s * u.Mpc)).to(1.0 / u.s)
sec_to_Gyr = u.s.to(u.Gyr)
# const in critical density in cgs units (g cm^-3)
critdens_const = (3 / (8 * pi * const.G)).cgs.value
# angle conversions
radian_in_arcsec = (1 * u.rad).to(u.arcsec)
radian_in_arcmin = (1 * u.rad).to(u.arcmin)
# Radiation parameter over c^2 in cgs (g cm^-3 K^-4)
a_B_c2 = (4 * const.sigma_sb / const.c ** 3).cgs.value
# Boltzmann constant in eV / K
kB_evK = const.k_B.to(u.eV / u.K)
class FLRW(Cosmology):
"""
A class describing an isotropic and homogeneous
(Friedmann-Lemaitre-Robertson-Walker) cosmology.
This is an abstract base class -- you cannot instantiate examples of this
class, but must work with one of its subclasses, such as
:class:`~astropy.cosmology.LambdaCDM` or :class:`~astropy.cosmology.wCDM`.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0. Note that this does not include massive
neutrinos.
Ode0 : float
Omega dark energy: density of dark energy in units of the critical
density at z=0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Notes
-----
Class instances are immutable -- you cannot change the parameters' values.
That is, all of the above attributes (except meta) are read only.
For details on how to create performant custom subclasses, see the
documentation on :ref:`astropy-cosmology-fast-integrals`.
"""
H0 = Parameter(doc="Hubble constant as an `~astropy.units.Quantity` at z=0.",
unit="km/(s Mpc)", fvalidate="scalar")
Om0 = Parameter(doc="Omega matter; matter density/critical density at z=0.",
fvalidate="non-negative")
Ode0 = Parameter(doc="Omega dark energy; dark energy density/critical density at z=0.",
fvalidate="float")
Tcmb0 = Parameter(doc="Temperature of the CMB as `~astropy.units.Quantity` at z=0.",
unit="Kelvin", fvalidate="scalar")
Neff = Parameter(doc="Number of effective neutrino species.", fvalidate="non-negative")
m_nu = Parameter(doc="Mass of neutrino species.",
unit="eV", equivalencies=u.mass_energy())
Ob0 = Parameter(doc="Omega baryon; baryonic matter density/critical density at z=0.")
def __init__(self, H0, Om0, Ode0, Tcmb0=0.0*u.K, Neff=3.04, m_nu=0.0*u.eV,
Ob0=None, *, name=None, meta=None):
super().__init__(name=name, meta=meta)
# Assign (and validate) Parameters
self.H0 = H0
self.Om0 = Om0
self.Ode0 = Ode0
self.Tcmb0 = Tcmb0
self.Neff = Neff
self.m_nu = m_nu # (reset later, this is just for unit validation)
self.Ob0 = Ob0 # (must be after Om0)
# Derived quantities:
# Dark matter density; matter - baryons, if latter is not None.
self._Odm0 = None if Ob0 is None else (self._Om0 - self._Ob0)
# 100 km/s/Mpc * h = H0 (so h is dimensionless)
self._h = self._H0.value / 100.0
# Hubble distance
self._hubble_distance = (const.c / self._H0).to(u.Mpc)
# H0 in s^-1
H0_s = self._H0.value * H0units_to_invs
# Hubble time
self._hubble_time = (sec_to_Gyr / H0_s) << u.Gyr
# Critical density at z=0 (grams per cubic cm)
cd0value = critdens_const * H0_s ** 2
self._critical_density0 = cd0value << u.g / u.cm ** 3
# Compute photon density from Tcmb
self._Ogamma0 = a_B_c2 * self._Tcmb0.value ** 4 / self._critical_density0.value
# Compute Neutrino temperature:
# The constant in front is (4/11)^1/3 -- see any cosmology book for an
# explanation -- for example, Weinberg 'Cosmology' p 154 eq (3.1.21).
self._Tnu0 = 0.7137658555036082 * self._Tcmb0
# Compute neutrino parameters:
if self._m_nu is None:
self._nneutrinos = 0
self._neff_per_nu = None
self._massivenu = False
self._massivenu_mass = None
self._nmassivenu = self._nmasslessnu = None
else:
self._nneutrinos = floor(self._Neff)
# We are going to share Neff between the neutrinos equally. In
# detail this is not correct, but it is a standard assumption
# because properly calculating it is a) complicated b) depends on
# the details of the massive neutrinos (e.g., their weak
# interactions, which could be unusual if one is considering
# sterile neutrinos).
self._neff_per_nu = self._Neff / self._nneutrinos
# Now figure out if we have massive neutrinos to deal with, and if
# so, get the right number of masses. It is worth keeping track of
# massless ones separately (since they are easy to deal with, and a
# common use case is to have only one massive neutrino).
massive = np.nonzero(self._m_nu.value > 0)[0]
self._massivenu = massive.size > 0
self._nmassivenu = len(massive)
self._massivenu_mass = self._m_nu[massive].value if self._massivenu else None
self._nmasslessnu = self._nneutrinos - self._nmassivenu
# Compute Neutrino Omega and total relativistic component for massive
# neutrinos. We also store a list version, since that is more efficient
# to do integrals with (perhaps surprisingly! But small python lists
# are more efficient than small NumPy arrays).
if self._massivenu: # (`_massivenu` set in `m_nu`)
nu_y = self._massivenu_mass / (kB_evK * self._Tnu0)
self._nu_y = nu_y.value
self._nu_y_list = self._nu_y.tolist()
self._Onu0 = self._Ogamma0 * self.nu_relative_density(0)
else:
# This case is particularly simple, so do it directly The 0.2271...
# is 7/8 (4/11)^(4/3) -- the temperature bit ^4 (blackbody energy
# density) times 7/8 for FD vs. BE statistics.
self._Onu0 = 0.22710731766 * self._Neff * self._Ogamma0
self._nu_y = self._nu_y_list = None
# Compute curvature density
self._Ok0 = 1.0 - self._Om0 - self._Ode0 - self._Ogamma0 - self._Onu0
# Subclasses should override this reference if they provide
# more efficient scalar versions of inv_efunc.
self._inv_efunc_scalar = self.inv_efunc
self._inv_efunc_scalar_args = ()
# ---------------------------------------------------------------
# Parameter details
@Ob0.validator
def Ob0(self, param, value):
"""Validate baryon density to None or positive float > matter density."""
if value is None:
return value
value = _validate_non_negative(self, param, value)
if value > self.Om0:
raise ValueError("baryonic density can not be larger than total matter density.")
return value
@m_nu.validator
def m_nu(self, param, value):
"""Validate neutrino masses to right value, units, and shape.
There are no neutrinos if floor(Neff) or Tcmb0 are 0.
The number of neutrinos must match floor(Neff).
Neutrino masses cannot be negative.
"""
# Check if there are any neutrinos
if (nneutrinos := floor(self._Neff)) == 0 or self._Tcmb0.value == 0:
return None # None, regardless of input
# Validate / set units
value = _validate_with_unit(self, param, value)
# Check values and data shapes
if value.shape not in ((), (nneutrinos,)):
raise ValueError("unexpected number of neutrino masses — "
f"expected {nneutrinos}, got {len(value)}.")
elif np.any(value.value < 0):
raise ValueError("invalid (negative) neutrino mass encountered.")
# scalar -> array
if value.isscalar:
value = np.full_like(value, value, shape=nneutrinos)
return value
# ---------------------------------------------------------------
# properties
@property
def is_flat(self):
"""Return bool; `True` if the cosmology is flat."""
return bool((self._Ok0 == 0.0) and (self.Otot0 == 1.0))
@property
def Otot0(self):
"""Omega total; the total density/critical density at z=0."""
return self._Om0 + self._Ogamma0 + self._Onu0 + self._Ode0 + self._Ok0
@property
def Odm0(self):
"""Omega dark matter; dark matter density/critical density at z=0."""
return self._Odm0
@property
def Ok0(self):
"""Omega curvature; the effective curvature density/critical density at z=0."""
return self._Ok0
@property
def Tnu0(self):
"""Temperature of the neutrino background as `~astropy.units.Quantity` at z=0."""
return self._Tnu0
@property
def has_massive_nu(self):
"""Does this cosmology have at least one massive neutrino species?"""
if self._Tnu0.value == 0:
return False
return self._massivenu
@property
def h(self):
"""Dimensionless Hubble constant: h = H_0 / 100 [km/sec/Mpc]."""
return self._h
@property
def hubble_time(self):
"""Hubble time as `~astropy.units.Quantity`."""
return self._hubble_time
@property
def hubble_distance(self):
"""Hubble distance as `~astropy.units.Quantity`."""
return self._hubble_distance
@property
def critical_density0(self):
"""Critical density as `~astropy.units.Quantity` at z=0."""
return self._critical_density0
@property
def Ogamma0(self):
"""Omega gamma; the density/critical density of photons at z=0."""
return self._Ogamma0
@property
def Onu0(self):
"""Omega nu; the density/critical density of neutrinos at z=0."""
return self._Onu0
# ---------------------------------------------------------------
@abstractmethod
def w(self, z):
r"""The dark energy equation of state.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
w : ndarray or float
The dark energy equation of state.
`float` if scalar input.
Notes
-----
The dark energy equation of state is defined as
:math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at
redshift z and :math:`\rho(z)` is the density at redshift z, both in
units where c=1.
This must be overridden by subclasses.
"""
raise NotImplementedError("w(z) is not implemented")
def Otot(self, z):
"""The total density parameter at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts.
Returns
-------
Otot : ndarray or float
The total density relative to the critical density at each redshift.
Returns float if input scalar.
"""
return self.Om(z) + self.Ogamma(z) + self.Onu(z) + self.Ode(z) + self.Ok(z)
def Om(self, z):
"""
Return the density parameter for non-relativistic matter
at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Om : ndarray or float
The density of non-relativistic matter relative to the critical
density at each redshift.
Returns `float` if the input is scalar.
Notes
-----
This does not include neutrinos, even if non-relativistic at the
redshift of interest; see `Onu`.
"""
z = aszarr(z)
return self._Om0 * (z + 1.0) ** 3 * self.inv_efunc(z) ** 2
def Ob(self, z):
"""Return the density parameter for baryonic matter at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Ob : ndarray or float
The density of baryonic matter relative to the critical density at
each redshift.
Returns `float` if the input is scalar.
Raises
------
ValueError
If ``Ob0`` is `None`.
"""
if self._Ob0 is None:
raise ValueError("Baryon density not set for this cosmology")
z = aszarr(z)
return self._Ob0 * (z + 1.0) ** 3 * self.inv_efunc(z) ** 2
def Odm(self, z):
"""Return the density parameter for dark matter at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Odm : ndarray or float
The density of non-relativistic dark matter relative to the
critical density at each redshift.
Returns `float` if the input is scalar.
Raises
------
ValueError
If ``Ob0`` is `None`.
Notes
-----
This does not include neutrinos, even if non-relativistic at the
redshift of interest.
"""
if self._Odm0 is None:
raise ValueError("Baryonic density not set for this cosmology, "
"unclear meaning of dark matter density")
z = aszarr(z)
return self._Odm0 * (z + 1.0) ** 3 * self.inv_efunc(z) ** 2
def Ok(self, z):
"""
Return the equivalent density parameter for curvature at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Ok : ndarray or float
The equivalent density parameter for curvature at each redshift.
Returns `float` if the input is scalar.
"""
z = aszarr(z)
if self._Ok0 == 0: # Common enough to be worth checking explicitly
return np.zeros(z.shape) if hasattr(z, "shape") else 0.0
return self._Ok0 * (z + 1.0) ** 2 * self.inv_efunc(z) ** 2
def Ode(self, z):
"""Return the density parameter for dark energy at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Ode : ndarray or float
The density of non-relativistic matter relative to the critical
density at each redshift.
Returns `float` if the input is scalar.
"""
z = aszarr(z)
if self._Ode0 == 0: # Common enough to be worth checking explicitly
return np.zeros(z.shape) if hasattr(z, "shape") else 0.0
return self._Ode0 * self.de_density_scale(z) * self.inv_efunc(z) ** 2
def Ogamma(self, z):
"""Return the density parameter for photons at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Ogamma : ndarray or float
The energy density of photons relative to the critical density at
each redshift.
Returns `float` if the input is scalar.
"""
z = aszarr(z)
return self._Ogamma0 * (z + 1.0) ** 4 * self.inv_efunc(z) ** 2
def Onu(self, z):
r"""Return the density parameter for neutrinos at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Onu : ndarray or float
The energy density of neutrinos relative to the critical density at
each redshift. Note that this includes their kinetic energy (if
they have mass), so it is not equal to the commonly used
:math:`\sum \frac{m_{\nu}}{94 eV}`, which does not include
kinetic energy.
Returns `float` if the input is scalar.
"""
z = aszarr(z)
if self._Onu0 == 0: # Common enough to be worth checking explicitly
return np.zeros(z.shape) if hasattr(z, "shape") else 0.0
return self.Ogamma(z) * self.nu_relative_density(z)
def Tcmb(self, z):
"""Return the CMB temperature at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Tcmb : `~astropy.units.Quantity` ['temperature']
The temperature of the CMB in K.
"""
return self._Tcmb0 * (aszarr(z) + 1.0)
def Tnu(self, z):
"""Return the neutrino temperature at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
Tnu : `~astropy.units.Quantity` ['temperature']
The temperature of the cosmic neutrino background in K.
"""
return self._Tnu0 * (aszarr(z) + 1.0)
def nu_relative_density(self, z):
r"""Neutrino density function relative to the energy density in photons.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
f : ndarray or float
The neutrino density scaling factor relative to the density in
photons at each redshift.
Only returns `float` if z is scalar.
Notes
-----
The density in neutrinos is given by
.. math::
\rho_{\nu} \left(a\right) = 0.2271 \, N_{eff} \,
f\left(m_{\nu} a / T_{\nu 0} \right) \,
\rho_{\gamma} \left( a \right)
where
.. math::
f \left(y\right) = \frac{120}{7 \pi^4}
\int_0^{\infty} \, dx \frac{x^2 \sqrt{x^2 + y^2}}
{e^x + 1}
assuming that all neutrino species have the same mass.
If they have different masses, a similar term is calculated for each
one. Note that ``f`` has the asymptotic behavior :math:`f(0) = 1`. This
method returns :math:`0.2271 f` using an analytical fitting formula
given in Komatsu et al. 2011, ApJS 192, 18.
"""
# Note that there is also a scalar-z-only cython implementation of
# this in scalar_inv_efuncs.pyx, so if you find a problem in this
# you need to update there too.
# See Komatsu et al. 2011, eq 26 and the surrounding discussion
# for an explanation of what we are doing here.
# However, this is modified to handle multiple neutrino masses
# by computing the above for each mass, then summing
prefac = 0.22710731766 # 7/8 (4/11)^4/3 -- see any cosmo book
# The massive and massless contribution must be handled separately
# But check for common cases first
z = aszarr(z)
if not self._massivenu:
return prefac * self._Neff * (np.ones(z.shape) if hasattr(z, "shape") else 1.0)
# These are purely fitting constants -- see the Komatsu paper
p = 1.83
invp = 0.54644808743 # 1.0 / p
k = 0.3173
curr_nu_y = self._nu_y / (1. + np.expand_dims(z, axis=-1))
rel_mass_per = (1.0 + (k * curr_nu_y) ** p) ** invp
rel_mass = rel_mass_per.sum(-1) + self._nmasslessnu
return prefac * self._neff_per_nu * rel_mass
def _w_integrand(self, ln1pz):
"""Internal convenience function for w(z) integral (eq. 5 of [1]_).
Parameters
----------
ln1pz : `~numbers.Number` or scalar ndarray
Assumes scalar input, since this should only be called inside an
integral.
References
----------
.. [1] Linder, E. (2003). Exploring the Expansion History of the
Universe. Phys. Rev. Lett., 90, 091301.
"""
return 1.0 + self.w(exp(ln1pz) - 1.0)
def de_density_scale(self, z):
r"""Evaluates the redshift dependence of the dark energy density.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
I : ndarray or float
The scaling of the energy density of dark energy with redshift.
Returns `float` if the input is scalar.
Notes
-----
The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`,
and is given by
.. math::
I = \exp \left( 3 \int_{a}^1 \frac{ da^{\prime} }{ a^{\prime} }
\left[ 1 + w\left( a^{\prime} \right) \right] \right)
The actual integral used is rewritten from [1]_ to be in terms of z.
It will generally helpful for subclasses to overload this method if
the integral can be done analytically for the particular dark
energy equation of state that they implement.
References
----------
.. [1] Linder, E. (2003). Exploring the Expansion History of the
Universe. Phys. Rev. Lett., 90, 091301.
"""
# This allows for an arbitrary w(z) following eq (5) of
# Linder 2003, PRL 90, 91301. The code here evaluates
# the integral numerically. However, most popular
# forms of w(z) are designed to make this integral analytic,
# so it is probably a good idea for subclasses to overload this
# method if an analytic form is available.
z = aszarr(z)
if not isinstance(z, (Number, np.generic)): # array/Quantity
ival = np.array([quad(self._w_integrand, 0, log(1 + redshift))[0]
for redshift in z])
return np.exp(3 * ival)
else: # scalar
ival = quad(self._w_integrand, 0, log(z + 1.0))[0]
return exp(3 * ival)
def efunc(self, z):
"""Function used to calculate H(z), the Hubble parameter.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H(z) = H_0 E(z)`.
Notes
-----
It is not necessary to override this method, but if de_density_scale
takes a particularly simple form, it may be advantageous to.
"""
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return np.sqrt(zp1 ** 2 * ((Or * zp1 + self._Om0) * zp1 + self._Ok0) +
self._Ode0 * self.de_density_scale(z))
def inv_efunc(self, z):
"""Inverse of ``efunc``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The redshift scaling of the inverse Hubble constant.
Returns `float` if the input is scalar.
"""
# Avoid the function overhead by repeating code
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return (zp1 ** 2 * ((Or * zp1 + self._Om0) * zp1 + self._Ok0) +
self._Ode0 * self.de_density_scale(z))**(-0.5)
def _lookback_time_integrand_scalar(self, z):
"""Integrand of the lookback time (equation 30 of [1]_).
Parameters
----------
z : float
Input redshift.
Returns
-------
I : float
The integrand for the lookback time.
References
----------
.. [1] Hogg, D. (1999). Distance measures in cosmology, section 11.
arXiv e-prints, astro-ph/9905116.
"""
return self._inv_efunc_scalar(z, *self._inv_efunc_scalar_args) / (z + 1.0)
def lookback_time_integrand(self, z):
"""Integrand of the lookback time (equation 30 of [1]_).
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
I : float or array
The integrand for the lookback time.
References
----------
.. [1] Hogg, D. (1999). Distance measures in cosmology, section 11.
arXiv e-prints, astro-ph/9905116.
"""
z = aszarr(z)
return self.inv_efunc(z) / (z + 1.0)
def _abs_distance_integrand_scalar(self, z):
"""Integrand of the absorption distance [1]_.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
X : float
The integrand for the absorption distance.
References
----------
.. [1] Hogg, D. (1999). Distance measures in cosmology, section 11.
arXiv e-prints, astro-ph/9905116.
"""
args = self._inv_efunc_scalar_args
return (z + 1.0) ** 2 * self._inv_efunc_scalar(z, *args)
def abs_distance_integrand(self, z):
"""Integrand of the absorption distance [1]_.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
X : float or array
The integrand for the absorption distance.
References
----------
.. [1] Hogg, D. (1999). Distance measures in cosmology, section 11.
arXiv e-prints, astro-ph/9905116.
"""
z = aszarr(z)
return (z + 1.0) ** 2 * self.inv_efunc(z)
def H(self, z):
"""Hubble parameter (km/s/Mpc) at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
H : `~astropy.units.Quantity` ['frequency']
Hubble parameter at each input redshift.
"""
return self._H0 * self.efunc(z)
def scale_factor(self, z):
"""Scale factor at redshift ``z``.
The scale factor is defined as :math:`a = 1 / (1 + z)`.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
a : ndarray or float
Scale factor at each input redshift.
Returns `float` if the input is scalar.
"""
return 1.0 / (aszarr(z) + 1.0)
def lookback_time(self, z):
"""Lookback time in Gyr to redshift ``z``.
The lookback time is the difference between the age of the Universe now
and the age at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
Lookback time in Gyr to each input redshift.
See Also
--------
z_at_value : Find the redshift corresponding to a lookback time.
"""
return self._lookback_time(z)
def _lookback_time(self, z):
"""Lookback time in Gyr to redshift ``z``.
The lookback time is the difference between the age of the Universe now
and the age at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
Lookback time in Gyr to each input redshift.
"""
return self._hubble_time * self._integral_lookback_time(z)
@vectorize_redshift_method
def _integral_lookback_time(self, z, /):
"""Lookback time to redshift ``z``. Value in units of Hubble time.
The lookback time is the difference between the age of the Universe now
and the age at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : float or ndarray
Lookback time to each input redshift in Hubble time units.
Returns `float` if input scalar, `~numpy.ndarray` otherwise.
"""
return quad(self._lookback_time_integrand_scalar, 0, z)[0]
def lookback_distance(self, z):
"""
The lookback distance is the light travel time distance to a given
redshift. It is simply c * lookback_time. It may be used to calculate
the proper distance between two redshifts, e.g. for the mean free path
to ionizing radiation.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Lookback distance in Mpc
"""
return (self.lookback_time(z) * const.c).to(u.Mpc)
def age(self, z):
"""Age of the universe in Gyr at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
The age of the universe in Gyr at each input redshift.
See Also
--------
z_at_value : Find the redshift corresponding to an age.
"""
return self._age(z)
def _age(self, z):
"""Age of the universe in Gyr at redshift ``z``.
This internal function exists to be re-defined for optimizations.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
The age of the universe in Gyr at each input redshift.
"""
return self._hubble_time * self._integral_age(z)
@vectorize_redshift_method
def _integral_age(self, z, /):
"""Age of the universe at redshift ``z``. Value in units of Hubble time.
Calculated using explicit integration.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : float or ndarray
The age of the universe at each input redshift in Hubble time units.
Returns `float` if input scalar, `~numpy.ndarray` otherwise.
See Also
--------
z_at_value : Find the redshift corresponding to an age.
"""
return quad(self._lookback_time_integrand_scalar, z, np.inf)[0]
def critical_density(self, z):
"""Critical density in grams per cubic cm at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
rho : `~astropy.units.Quantity`
Critical density in g/cm^3 at each input redshift.
"""
return self._critical_density0 * (self.efunc(z)) ** 2
def comoving_distance(self, z):
"""Comoving line-of-sight distance in Mpc at a given redshift.
The comoving distance along the line-of-sight between two objects
remains constant with time for objects in the Hubble flow.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving distance in Mpc to each input redshift.
"""
return self._comoving_distance_z1z2(0, z)
def _comoving_distance_z1z2(self, z1, z2):
"""
Comoving line-of-sight distance in Mpc between objects at redshifts
``z1`` and ``z2``.
The comoving distance along the line-of-sight between two objects
remains constant with time for objects in the Hubble flow.
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving distance in Mpc between each input redshift.
"""
return self._integral_comoving_distance_z1z2(z1, z2)
@vectorize_redshift_method(nin=2)
def _integral_comoving_distance_z1z2_scalar(self, z1, z2, /):
"""
Comoving line-of-sight distance between objects at redshifts ``z1`` and
``z2``. Value in Mpc.
The comoving distance along the line-of-sight between two objects
remains constant with time for objects in the Hubble flow.
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts.
Returns
-------
d : float or ndarray
Comoving distance in Mpc between each input redshift.
Returns `float` if input scalar, `~numpy.ndarray` otherwise.
"""
return quad(self._inv_efunc_scalar, z1, z2, args=self._inv_efunc_scalar_args)[0]
def _integral_comoving_distance_z1z2(self, z1, z2):
"""
Comoving line-of-sight distance in Mpc between objects at redshifts
``z1`` and ``z2``. The comoving distance along the line-of-sight
between two objects remains constant with time for objects in the
Hubble flow.
Parameters
----------
z1, z2 : Quantity-like ['redshift'] or array-like
Input redshifts.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving distance in Mpc between each input redshift.
"""
return self._hubble_distance * self._integral_comoving_distance_z1z2_scalar(z1, z2)
def comoving_transverse_distance(self, z):
r"""Comoving transverse distance in Mpc at a given redshift.
This value is the transverse comoving distance at redshift ``z``
corresponding to an angular separation of 1 radian. This is the same as
the comoving distance if :math:`\Omega_k` is zero (as in the current
concordance Lambda-CDM model).
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving transverse distance in Mpc at each input redshift.
Notes
-----
This quantity is also called the 'proper motion distance' in some texts.
"""
return self._comoving_transverse_distance_z1z2(0, z)
def _comoving_transverse_distance_z1z2(self, z1, z2):
r"""Comoving transverse distance in Mpc between two redshifts.
This value is the transverse comoving distance at redshift ``z2`` as
seen from redshift ``z1`` corresponding to an angular separation of
1 radian. This is the same as the comoving distance if :math:`\Omega_k`
is zero (as in the current concordance Lambda-CDM model).
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving transverse distance in Mpc between input redshift.
Notes
-----
This quantity is also called the 'proper motion distance' in some texts.
"""
Ok0 = self._Ok0
dc = self._comoving_distance_z1z2(z1, z2)
if Ok0 == 0:
return dc
sqrtOk0 = sqrt(abs(Ok0))
dh = self._hubble_distance
if Ok0 > 0:
return dh / sqrtOk0 * np.sinh(sqrtOk0 * dc.value / dh.value)
else:
return dh / sqrtOk0 * np.sin(sqrtOk0 * dc.value / dh.value)
def angular_diameter_distance(self, z):
"""Angular diameter distance in Mpc at a given redshift.
This gives the proper (sometimes called 'physical') transverse
distance corresponding to an angle of 1 radian for an object
at redshift ``z`` ([1]_, [2]_, [3]_).
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Angular diameter distance in Mpc at each input redshift.
References
----------
.. [1] Weinberg, 1972, pp 420-424; Weedman, 1986, pp 421-424.
.. [2] Weedman, D. (1986). Quasar astronomy, pp 65-67.
.. [3] Peebles, P. (1993). Principles of Physical Cosmology, pp 325-327.
"""
z = aszarr(z)
return self.comoving_transverse_distance(z) / (z + 1.0)
def luminosity_distance(self, z):
"""Luminosity distance in Mpc at redshift ``z``.
This is the distance to use when converting between the bolometric flux
from an object at redshift ``z`` and its bolometric luminosity [1]_.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Luminosity distance in Mpc at each input redshift.
See Also
--------
z_at_value : Find the redshift corresponding to a luminosity distance.
References
----------
.. [1] Weinberg, 1972, pp 420-424; Weedman, 1986, pp 60-62.
"""
z = aszarr(z)
return (z + 1.0) * self.comoving_transverse_distance(z)
def angular_diameter_distance_z1z2(self, z1, z2):
"""Angular diameter distance between objects at 2 redshifts.
Useful for gravitational lensing, for example computing the angular
diameter distance between a lensed galaxy and the foreground lens.
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts. For most practical applications such as
gravitational lensing, ``z2`` should be larger than ``z1``. The
method will work for ``z2 < z1``; however, this will return
negative distances.
Returns
-------
d : `~astropy.units.Quantity`
The angular diameter distance between each input redshift pair.
Returns scalar if input is scalar, array else-wise.
"""
z1, z2 = aszarr(z1), aszarr(z2)
if np.any(z2 < z1):
warnings.warn(f"Second redshift(s) z2 ({z2}) is less than first "
f"redshift(s) z1 ({z1}).", AstropyUserWarning)
return self._comoving_transverse_distance_z1z2(z1, z2) / (z2 + 1.0)
@vectorize_redshift_method
def absorption_distance(self, z, /):
"""Absorption distance at redshift ``z``.
This is used to calculate the number of objects with some cross section
of absorption and number density intersecting a sightline per unit
redshift path ([1]_, [2]_).
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : float or ndarray
Absorption distance (dimensionless) at each input redshift.
Returns `float` if input scalar, `~numpy.ndarray` otherwise.
References
----------
.. [1] Hogg, D. (1999). Distance measures in cosmology, section 11.
arXiv e-prints, astro-ph/9905116.
.. [2] Bahcall, John N. and Peebles, P.J.E. 1969, ApJ, 156L, 7B
"""
return quad(self._abs_distance_integrand_scalar, 0, z)[0]
def distmod(self, z):
"""Distance modulus at redshift ``z``.
The distance modulus is defined as the (apparent magnitude - absolute
magnitude) for an object at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
distmod : `~astropy.units.Quantity` ['length']
Distance modulus at each input redshift, in magnitudes.
See Also
--------
z_at_value : Find the redshift corresponding to a distance modulus.
"""
# Remember that the luminosity distance is in Mpc
# Abs is necessary because in certain obscure closed cosmologies
# the distance modulus can be negative -- which is okay because
# it enters as the square.
val = 5. * np.log10(abs(self.luminosity_distance(z).value)) + 25.0
return u.Quantity(val, u.mag)
def comoving_volume(self, z):
r"""Comoving volume in cubic Mpc at redshift ``z``.
This is the volume of the universe encompassed by redshifts less than
``z``. For the case of :math:`\Omega_k = 0` it is a sphere of radius
`comoving_distance` but it is less intuitive if :math:`\Omega_k` is not.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
V : `~astropy.units.Quantity`
Comoving volume in :math:`Mpc^3` at each input redshift.
"""
Ok0 = self._Ok0
if Ok0 == 0:
return 4.0 / 3.0 * pi * self.comoving_distance(z) ** 3
dh = self._hubble_distance.value # .value for speed
dm = self.comoving_transverse_distance(z).value
term1 = 4.0 * pi * dh ** 3 / (2.0 * Ok0) * u.Mpc ** 3
term2 = dm / dh * np.sqrt(1 + Ok0 * (dm / dh) ** 2)
term3 = sqrt(abs(Ok0)) * dm / dh
if Ok0 > 0:
return term1 * (term2 - 1. / sqrt(abs(Ok0)) * np.arcsinh(term3))
else:
return term1 * (term2 - 1. / sqrt(abs(Ok0)) * np.arcsin(term3))
def differential_comoving_volume(self, z):
"""Differential comoving volume at redshift z.
Useful for calculating the effective comoving volume.
For example, allows for integration over a comoving volume that has a
sensitivity function that changes with redshift. The total comoving
volume is given by integrating ``differential_comoving_volume`` to
redshift ``z`` and multiplying by a solid angle.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
dV : `~astropy.units.Quantity`
Differential comoving volume per redshift per steradian at each
input redshift.
"""
dm = self.comoving_transverse_distance(z)
return self._hubble_distance * (dm ** 2.0) / (self.efunc(z) << u.steradian)
def kpc_comoving_per_arcmin(self, z):
"""
Separation in transverse comoving kpc corresponding to an arcminute at
redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : `~astropy.units.Quantity` ['length']
The distance in comoving kpc corresponding to an arcmin at each
input redshift.
"""
return self.comoving_transverse_distance(z).to(u.kpc) / radian_in_arcmin
def kpc_proper_per_arcmin(self, z):
"""
Separation in transverse proper kpc corresponding to an arcminute at
redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
d : `~astropy.units.Quantity` ['length']
The distance in proper kpc corresponding to an arcmin at each input
redshift.
"""
return self.angular_diameter_distance(z).to(u.kpc) / radian_in_arcmin
def arcsec_per_kpc_comoving(self, z):
"""
Angular separation in arcsec corresponding to a comoving kpc at
redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
theta : `~astropy.units.Quantity` ['angle']
The angular separation in arcsec corresponding to a comoving kpc at
each input redshift.
"""
return radian_in_arcsec / self.comoving_transverse_distance(z).to(u.kpc)
def arcsec_per_kpc_proper(self, z):
"""
Angular separation in arcsec corresponding to a proper kpc at redshift
``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
theta : `~astropy.units.Quantity` ['angle']
The angular separation in arcsec corresponding to a proper kpc at
each input redshift.
"""
return radian_in_arcsec / self.angular_diameter_distance(z).to(u.kpc)
class FlatFLRWMixin(FlatCosmologyMixin):
"""
Mixin class for flat FLRW cosmologies. Do NOT instantiate directly.
Must precede the base class in the multiple-inheritance so that this
mixin's ``__init__`` proceeds the base class'.
Note that all instances of ``FlatFLRWMixin`` are flat, but not all
flat cosmologies are instances of ``FlatFLRWMixin``. As example,
``LambdaCDM`` **may** be flat (for the a specific set of parameter values),
but ``FlatLambdaCDM`` **will** be flat.
"""
Ode0 = FLRW.Ode0.clone(derived=True) # same as FLRW, but now a derived param.
def __init_subclass__(cls):
super().__init_subclass__()
if "Ode0" in cls._init_signature.parameters:
raise TypeError("subclasses of `FlatFLRWMixin` cannot have `Ode0` in `__init__`")
def __init__(self, *args, **kw):
super().__init__(*args, **kw) # guaranteed not to have `Ode0`
# Do some twiddling after the fact to get flatness
self._Ok0 = 0.0
self._Ode0 = 1.0 - (self._Om0 + self._Ogamma0 + self._Onu0 + self._Ok0)
@property
def Otot0(self):
"""Omega total; the total density/critical density at z=0."""
return 1.0
def Otot(self, z):
"""The total density parameter at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts.
Returns
-------
Otot : ndarray or float
Returns float if input scalar. Value of 1.
"""
return 1.0 if isinstance(z, (Number, np.generic)) else np.ones_like(z, subok=False)
def __equiv__(self, other):
"""flat-FLRW equivalence. Use ``.is_equivalent()`` for actual check!
Parameters
----------
other : `~astropy.cosmology.FLRW` subclass instance
The object in which to compare.
Returns
-------
bool or `NotImplemented`
`True` if 'other' is of the same class / non-flat class (e.g.
``FlatLambdaCDM`` and ``LambdaCDM``) has matching parameters
and parameter values. `False` if 'other' is of the same class but
has different parameters. `NotImplemented` otherwise.
"""
# check if case (1): same class & parameters
if isinstance(other, FlatFLRWMixin):
return super().__equiv__(other)
# check cases (3, 4), if other is the non-flat version of this class
# this makes the assumption that any further subclass of a flat cosmo
# keeps the same physics.
comparable_classes = [c for c in self.__class__.mro()[1:]
if (issubclass(c, FLRW) and c is not FLRW)]
if other.__class__ not in comparable_classes:
return NotImplemented
# check if have equivalent parameters
# check all parameters in other match those in 'self' and 'other' has
# no extra parameters (case (2)) except for 'Ode0' and that other
params_eq = (
set(self.__all_parameters__) == set(other.__all_parameters__) # no extra
and all(np.all(getattr(self, k) == getattr(other, k)) # equal
for k in self.__parameters__)
and other.is_flat
)
return params_eq
class LambdaCDM(FLRW):
"""FLRW cosmology with a cosmological constant and curvature.
This has no additional attributes beyond those of FLRW.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
Ode0 : float
Omega dark energy: density of the cosmological constant in units of
the critical density at z=0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import LambdaCDM
>>> cosmo = LambdaCDM(H0=70, Om0=0.3, Ode0=0.7)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
"""
def __init__(self, H0, Om0, Ode0, Tcmb0=0.0*u.K, Neff=3.04, m_nu=0.0*u.eV,
Ob0=None, *, name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=Ode0, Tcmb0=Tcmb0, Neff=Neff,
m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.lcdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0)
if self._Ok0 == 0:
self._optimize_flat_norad()
else:
self._comoving_distance_z1z2 = self._elliptic_comoving_distance_z1z2
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.lcdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0 + self._Onu0)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.lcdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list)
def _optimize_flat_norad(self):
"""Set optimizations for flat LCDM cosmologies with no radiation."""
# Call out the Om0=0 (de Sitter) and Om0=1 (Einstein-de Sitter)
# The dS case is required because the hypergeometric case
# for Omega_M=0 would lead to an infinity in its argument.
# The EdS case is three times faster than the hypergeometric.
if self._Om0 == 0:
self._comoving_distance_z1z2 = self._dS_comoving_distance_z1z2
self._age = self._dS_age
self._lookback_time = self._dS_lookback_time
elif self._Om0 == 1:
self._comoving_distance_z1z2 = self._EdS_comoving_distance_z1z2
self._age = self._EdS_age
self._lookback_time = self._EdS_lookback_time
else:
self._comoving_distance_z1z2 = self._hypergeometric_comoving_distance_z1z2
self._age = self._flat_age
self._lookback_time = self._flat_lookback_time
def w(self, z):
r"""Returns dark energy equation of state at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
w : ndarray or float
The dark energy equation of state.
Returns `float` if the input is scalar.
Notes
-----
The dark energy equation of state is defined as
:math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at
redshift z and :math:`\rho(z)` is the density at redshift z, both in
units where c=1. Here this is :math:`w(z) = -1`.
"""
z = aszarr(z)
return -1.0 * (np.ones(z.shape) if hasattr(z, "shape") else 1.0)
def de_density_scale(self, z):
r"""Evaluates the redshift dependence of the dark energy density.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
I : ndarray or float
The scaling of the energy density of dark energy with redshift.
Returns `float` if the input is scalar.
Notes
-----
The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`,
and in this case is given by :math:`I = 1`.
"""
z = aszarr(z)
return np.ones(z.shape) if hasattr(z, "shape") else 1.0
def _elliptic_comoving_distance_z1z2(self, z1, z2):
r"""Comoving transverse distance in Mpc between two redshifts.
This value is the transverse comoving distance at redshift ``z``
corresponding to an angular separation of 1 radian. This is the same as
the comoving distance if :math:`\Omega_k` is zero.
For :math:`\Omega_{rad} = 0` the comoving distance can be directly
calculated as an elliptic integral [1]_.
Not valid or appropriate for flat cosmologies (Ok0=0).
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving distance in Mpc between each input redshift.
References
----------
.. [1] Kantowski, R., Kao, J., & Thomas, R. (2000). Distance-Redshift
in Inhomogeneous FLRW. arXiv e-prints, astro-ph/0002334.
"""
try:
z1, z2 = np.broadcast_arrays(z1, z2)
except ValueError as e:
raise ValueError("z1 and z2 have different shapes") from e
# The analytic solution is not valid for any of Om0, Ode0, Ok0 == 0.
# Use the explicit integral solution for these cases.
if self._Om0 == 0 or self._Ode0 == 0 or self._Ok0 == 0:
return self._integral_comoving_distance_z1z2(z1, z2)
b = -(27. / 2) * self._Om0**2 * self._Ode0 / self._Ok0**3
kappa = b / abs(b)
if (b < 0) or (2 < b):
def phi_z(Om0, Ok0, kappa, y1, A, z):
return np.arccos(((z + 1.0) * Om0 / abs(Ok0) + kappa * y1 - A) /
((z + 1.0) * Om0 / abs(Ok0) + kappa * y1 + A))
v_k = pow(kappa * (b - 1) + sqrt(b * (b - 2)), 1. / 3)
y1 = (-1 + kappa * (v_k + 1 / v_k)) / 3
A = sqrt(y1 * (3 * y1 + 2))
g = 1 / sqrt(A)
k2 = (2 * A + kappa * (1 + 3 * y1)) / (4 * A)
phi_z1 = phi_z(self._Om0, self._Ok0, kappa, y1, A, z1)
phi_z2 = phi_z(self._Om0, self._Ok0, kappa, y1, A, z2)
# Get lower-right 0<b<2 solution in Om0, Ode0 plane.
# Fot the upper-left 0<b<2 solution the Big Bang didn't happen.
elif (0 < b) and (b < 2) and self._Om0 > self._Ode0:
def phi_z(Om0, Ok0, y1, y2, z):
return np.arcsin(np.sqrt((y1 - y2) /
((z + 1.0) * Om0 / abs(Ok0) + y1)))
yb = cos(acos(1 - b) / 3)
yc = sqrt(3) * sin(acos(1 - b) / 3)
y1 = (1. / 3) * (-1 + yb + yc)
y2 = (1. / 3) * (-1 - 2 * yb)
y3 = (1. / 3) * (-1 + yb - yc)
g = 2 / sqrt(y1 - y2)
k2 = (y1 - y3) / (y1 - y2)
phi_z1 = phi_z(self._Om0, self._Ok0, y1, y2, z1)
phi_z2 = phi_z(self._Om0, self._Ok0, y1, y2, z2)
else:
return self._integral_comoving_distance_z1z2(z1, z2)
prefactor = self._hubble_distance / sqrt(abs(self._Ok0))
return prefactor * g * (ellipkinc(phi_z1, k2) - ellipkinc(phi_z2, k2))
def _dS_comoving_distance_z1z2(self, z1, z2):
r"""
Comoving line-of-sight distance in Mpc between objects at redshifts
``z1`` and ``z2`` in a flat, :math:`\Omega_{\Lambda}=1` cosmology
(de Sitter).
The comoving distance along the line-of-sight between two objects
remains constant with time for objects in the Hubble flow.
The de Sitter case has an analytic solution.
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts. Must be 1D or scalar.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving distance in Mpc between each input redshift.
"""
try:
z1, z2 = np.broadcast_arrays(z1, z2)
except ValueError as e:
raise ValueError("z1 and z2 have different shapes") from e
return self._hubble_distance * (z2 - z1)
def _EdS_comoving_distance_z1z2(self, z1, z2):
r"""
Comoving line-of-sight distance in Mpc between objects at redshifts
``z1`` and ``z2`` in a flat, :math:`\Omega_M=1` cosmology
(Einstein - de Sitter).
The comoving distance along the line-of-sight between two objects
remains constant with time for objects in the Hubble flow.
For :math:`\Omega_M=1`, :math:`\Omega_{rad}=0` the comoving distance
has an analytic solution.
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts. Must be 1D or scalar.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving distance in Mpc between each input redshift.
"""
try:
z1, z2 = np.broadcast_arrays(z1, z2)
except ValueError as e:
raise ValueError("z1 and z2 have different shapes") from e
prefactor = 2 * self._hubble_distance
return prefactor * ((z1 + 1.0)**(-1./2) - (z2 + 1.0)**(-1./2))
def _hypergeometric_comoving_distance_z1z2(self, z1, z2):
r"""
Comoving line-of-sight distance in Mpc between objects at redshifts
``z1`` and ``z2``.
The comoving distance along the line-of-sight between two objects
remains constant with time for objects in the Hubble flow.
For :math:`\Omega_{rad} = 0` the comoving distance can be directly
calculated as a hypergeometric function [1]_.
Parameters
----------
z1, z2 : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshifts.
Returns
-------
d : `~astropy.units.Quantity` ['length']
Comoving distance in Mpc between each input redshift.
References
----------
.. [1] Baes, M., Camps, P., & Van De Putte, D. (2017). Analytical
expressions and numerical evaluation of the luminosity distance
in a flat cosmology. MNRAS, 468(1), 927-930.
"""
try:
z1, z2 = np.broadcast_arrays(z1, z2)
except ValueError as e:
raise ValueError("z1 and z2 have different shapes") from e
s = ((1 - self._Om0) / self._Om0) ** (1./3)
# Use np.sqrt here to handle negative s (Om0>1).
prefactor = self._hubble_distance / np.sqrt(s * self._Om0)
return prefactor * (self._T_hypergeometric(s / (z1 + 1.0)) -
self._T_hypergeometric(s / (z2 + 1.0)))
def _T_hypergeometric(self, x):
r"""Compute value using Gauss Hypergeometric function 2F1.
.. math::
T(x) = 2 \sqrt(x) _{2}F_{1}\left(\frac{1}{6}, \frac{1}{2};
\frac{7}{6}; -x^3 \right)
Notes
-----
The :func:`scipy.special.hyp2f1` code already implements the
hypergeometric transformation suggested by Baes et al. [1]_ for use in
actual numerical evaulations.
References
----------
.. [1] Baes, M., Camps, P., & Van De Putte, D. (2017). Analytical
expressions and numerical evaluation of the luminosity distance
in a flat cosmology. MNRAS, 468(1), 927-930.
"""
return 2 * np.sqrt(x) * hyp2f1(1./6, 1./2, 7./6, -x**3)
def _dS_age(self, z):
"""Age of the universe in Gyr at redshift ``z``.
The age of a de Sitter Universe is infinite.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
The age of the universe in Gyr at each input redshift.
"""
t = (inf if isinstance(z, Number) else np.full_like(z, inf, dtype=float))
return self._hubble_time * t
def _EdS_age(self, z):
r"""Age of the universe in Gyr at redshift ``z``.
For :math:`\Omega_{rad} = 0` (:math:`T_{CMB} = 0`; massless neutrinos)
the age can be directly calculated as an elliptic integral [1]_.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
The age of the universe in Gyr at each input redshift.
References
----------
.. [1] Thomas, R., & Kantowski, R. (2000). Age-redshift relation for
standard cosmology. PRD, 62(10), 103507.
"""
return (2./3) * self._hubble_time * (aszarr(z) + 1.0) ** (-1.5)
def _flat_age(self, z):
r"""Age of the universe in Gyr at redshift ``z``.
For :math:`\Omega_{rad} = 0` (:math:`T_{CMB} = 0`; massless neutrinos)
the age can be directly calculated as an elliptic integral [1]_.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
The age of the universe in Gyr at each input redshift.
References
----------
.. [1] Thomas, R., & Kantowski, R. (2000). Age-redshift relation for
standard cosmology. PRD, 62(10), 103507.
"""
# Use np.sqrt, np.arcsinh instead of math.sqrt, math.asinh
# to handle properly the complex numbers for 1 - Om0 < 0
prefactor = (2./3) * self._hubble_time / np.emath.sqrt(1 - self._Om0)
arg = np.arcsinh(np.emath.sqrt((1 / self._Om0 - 1 + 0j) / (aszarr(z) + 1.0)**3))
return (prefactor * arg).real
def _EdS_lookback_time(self, z):
r"""Lookback time in Gyr to redshift ``z``.
The lookback time is the difference between the age of the Universe now
and the age at redshift ``z``.
For :math:`\Omega_{rad} = 0` (:math:`T_{CMB} = 0`; massless neutrinos)
the age can be directly calculated as an elliptic integral.
The lookback time is here calculated based on the ``age(0) - age(z)``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
Lookback time in Gyr to each input redshift.
"""
return self._EdS_age(0) - self._EdS_age(z)
def _dS_lookback_time(self, z):
r"""Lookback time in Gyr to redshift ``z``.
The lookback time is the difference between the age of the Universe now
and the age at redshift ``z``.
For :math:`\Omega_{rad} = 0` (:math:`T_{CMB} = 0`; massless neutrinos)
the age can be directly calculated.
.. math::
a = exp(H * t) \ \text{where t=0 at z=0}
t = (1/H) (ln 1 - ln a) = (1/H) (0 - ln (1/(1+z))) = (1/H) ln(1+z)
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
Lookback time in Gyr to each input redshift.
"""
return self._hubble_time * np.log(aszarr(z) + 1.0)
def _flat_lookback_time(self, z):
r"""Lookback time in Gyr to redshift ``z``.
The lookback time is the difference between the age of the Universe now
and the age at redshift ``z``.
For :math:`\Omega_{rad} = 0` (:math:`T_{CMB} = 0`; massless neutrinos)
the age can be directly calculated.
The lookback time is here calculated based on the ``age(0) - age(z)``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
t : `~astropy.units.Quantity` ['time']
Lookback time in Gyr to each input redshift.
"""
return self._flat_age(0) - self._flat_age(z)
def efunc(self, z):
"""Function used to calculate H(z), the Hubble parameter.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H(z) = H_0 E(z)`.
"""
# We override this because it takes a particularly simple
# form for a cosmological constant
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return np.sqrt(zp1 ** 2 * ((Or * zp1 + self._Om0) * zp1 + self._Ok0) + self._Ode0)
def inv_efunc(self, z):
r"""Function used to calculate :math:`\frac{1}{H_z}`.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The inverse redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H_z = H_0 / E`.
"""
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return (zp1 ** 2 * ((Or * zp1 + self._Om0) * zp1 + self._Ok0) + self._Ode0)**(-0.5)
class FlatLambdaCDM(FlatFLRWMixin, LambdaCDM):
"""FLRW cosmology with a cosmological constant and no curvature.
This has no additional attributes beyond those of FLRW.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import FlatLambdaCDM
>>> cosmo = FlatLambdaCDM(H0=70, Om0=0.3)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
"""
def __init__(self, H0, Om0, Tcmb0=0.0*u.K, Neff=3.04, m_nu=0.0*u.eV,
Ob0=None, *, name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=0.0, Tcmb0=Tcmb0, Neff=Neff,
m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.flcdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0)
# Repeat the optimization reassignments here because the init
# of the LambaCDM above didn't actually create a flat cosmology.
# That was done through the explicit tweak setting self._Ok0.
self._optimize_flat_norad()
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.flcdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._Ogamma0 + self._Onu0)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.flcdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list)
def efunc(self, z):
"""Function used to calculate H(z), the Hubble parameter.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H(z) = H_0 E(z)`.
"""
# We override this because it takes a particularly simple
# form for a cosmological constant
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return np.sqrt(zp1 ** 3 * (Or * zp1 + self._Om0) + self._Ode0)
def inv_efunc(self, z):
r"""Function used to calculate :math:`\frac{1}{H_z}`.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The inverse redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H_z = H_0 / E`.
"""
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return (zp1 ** 3 * (Or * zp1 + self._Om0) + self._Ode0)**(-0.5)
class wCDM(FLRW):
"""
FLRW cosmology with a constant dark energy equation of state and curvature.
This has one additional attribute beyond those of FLRW.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
Ode0 : float
Omega dark energy: density of dark energy in units of the critical
density at z=0.
w0 : float, optional
Dark energy equation of state at all redshifts. This is
pressure/density for dark energy in units where c=1. A cosmological
constant has w0=-1.0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import wCDM
>>> cosmo = wCDM(H0=70, Om0=0.3, Ode0=0.7, w0=-0.9)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
"""
w0 = Parameter(doc="Dark energy equation of state.", fvalidate="float")
def __init__(self, H0, Om0, Ode0, w0=-1.0, Tcmb0=0.0*u.K, Neff=3.04,
m_nu=0.0*u.eV, Ob0=None, *, name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=Ode0, Tcmb0=Tcmb0, Neff=Neff,
m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
self.w0 = w0
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.wcdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._w0)
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.wcdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0 + self._Onu0,
self._w0)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.wcdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list, self._w0)
def w(self, z):
r"""Returns dark energy equation of state at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
w : ndarray or float
The dark energy equation of state
Returns `float` if the input is scalar.
Notes
-----
The dark energy equation of state is defined as
:math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at
redshift z and :math:`\rho(z)` is the density at redshift z, both in
units where c=1. Here this is :math:`w(z) = w_0`.
"""
z = aszarr(z)
return self._w0 * (np.ones(z.shape) if hasattr(z, "shape") else 1.0)
def de_density_scale(self, z):
r"""Evaluates the redshift dependence of the dark energy density.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
I : ndarray or float
The scaling of the energy density of dark energy with redshift.
Returns `float` if the input is scalar.
Notes
-----
The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`,
and in this case is given by
:math:`I = \left(1 + z\right)^{3\left(1 + w_0\right)}`
"""
return (aszarr(z) + 1.0) ** (3.0 * (1. + self._w0))
def efunc(self, z):
"""Function used to calculate H(z), the Hubble parameter.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H(z) = H_0 E(z)`.
"""
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return np.sqrt(zp1 ** 2 * ((Or * zp1 + self._Om0) * zp1 + self._Ok0) +
self._Ode0 * zp1 ** (3. * (1. + self._w0)))
def inv_efunc(self, z):
r"""Function used to calculate :math:`\frac{1}{H_z}`.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The inverse redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H_z = H_0 / E`.
"""
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return (zp1 ** 2 * ((Or * zp1 + self._Om0) * zp1 + self._Ok0) +
self._Ode0 * zp1 ** (3. * (1. + self._w0)))**(-0.5)
class FlatwCDM(FlatFLRWMixin, wCDM):
"""
FLRW cosmology with a constant dark energy equation of state and no spatial
curvature.
This has one additional attribute beyond those of FLRW.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
w0 : float, optional
Dark energy equation of state at all redshifts. This is
pressure/density for dark energy in units where c=1. A cosmological
constant has w0=-1.0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import FlatwCDM
>>> cosmo = FlatwCDM(H0=70, Om0=0.3, w0=-0.9)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
"""
def __init__(self, H0, Om0, w0=-1.0, Tcmb0=0.0*u.K, Neff=3.04, m_nu=0.0*u.eV,
Ob0=None, *, name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=0.0, w0=w0, Tcmb0=Tcmb0,
Neff=Neff, m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.fwcdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._w0)
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.fwcdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._Ogamma0 + self._Onu0,
self._w0)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.fwcdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list, self._w0)
def efunc(self, z):
"""Function used to calculate H(z), the Hubble parameter.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H(z) = H_0 E(z)`.
"""
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return np.sqrt(zp1 ** 3 * (Or * zp1 + self._Om0) +
self._Ode0 * zp1 ** (3. * (1 + self._w0)))
def inv_efunc(self, z):
r"""Function used to calculate :math:`\frac{1}{H_z}`.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
E : ndarray or float
The inverse redshift scaling of the Hubble constant.
Returns `float` if the input is scalar.
Defined such that :math:`H(z) = H_0 E(z)`.
"""
Or = self._Ogamma0 + (self._Onu0 if not self._massivenu
else self._Ogamma0 * self.nu_relative_density(z))
zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless])
return (zp1 ** 3 * (Or * zp1 + self._Om0) +
self._Ode0 * zp1 ** (3. * (1. + self._w0)))**(-0.5)
class w0waCDM(FLRW):
r"""FLRW cosmology with a CPL dark energy equation of state and curvature.
The equation for the dark energy equation of state uses the
CPL form as described in Chevallier & Polarski [1]_ and Linder [2]_:
:math:`w(z) = w_0 + w_a (1-a) = w_0 + w_a z / (1+z)`.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
Ode0 : float
Omega dark energy: density of dark energy in units of the critical
density at z=0.
w0 : float, optional
Dark energy equation of state at z=0 (a=1). This is pressure/density
for dark energy in units where c=1.
wa : float, optional
Negative derivative of the dark energy equation of state with respect
to the scale factor. A cosmological constant has w0=-1.0 and wa=0.0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import w0waCDM
>>> cosmo = w0waCDM(H0=70, Om0=0.3, Ode0=0.7, w0=-0.9, wa=0.2)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
References
----------
.. [1] Chevallier, M., & Polarski, D. (2001). Accelerating Universes with
Scaling Dark Matter. International Journal of Modern Physics D,
10(2), 213-223.
.. [2] Linder, E. (2003). Exploring the Expansion History of the
Universe. Phys. Rev. Lett., 90, 091301.
"""
w0 = Parameter(doc="Dark energy equation of state at z=0.", fvalidate="float")
wa = Parameter(doc="Negative derivative of dark energy equation of state w.r.t. a.",
fvalidate="float")
def __init__(self, H0, Om0, Ode0, w0=-1.0, wa=0.0, Tcmb0=0.0*u.K, Neff=3.04,
m_nu=0.0*u.eV, Ob0=None, *, name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=Ode0, Tcmb0=Tcmb0, Neff=Neff,
m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
self.w0 = w0
self.wa = wa
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.w0wacdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._w0, self._wa)
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.w0wacdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0 + self._Onu0,
self._w0, self._wa)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.w0wacdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list, self._w0,
self._wa)
def w(self, z):
r"""Returns dark energy equation of state at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
w : ndarray or float
The dark energy equation of state
Returns `float` if the input is scalar.
Notes
-----
The dark energy equation of state is defined as
:math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at
redshift z and :math:`\rho(z)` is the density at redshift z, both in
units where c=1. Here this is
:math:`w(z) = w_0 + w_a (1 - a) = w_0 + w_a \frac{z}{1+z}`.
"""
z = aszarr(z)
return self._w0 + self._wa * z / (z + 1.0)
def de_density_scale(self, z):
r"""Evaluates the redshift dependence of the dark energy density.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
I : ndarray or float
The scaling of the energy density of dark energy with redshift.
Returns `float` if the input is scalar.
Notes
-----
The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`,
and in this case is given by
.. math::
I = \left(1 + z\right)^{3 \left(1 + w_0 + w_a\right)}
\exp \left(-3 w_a \frac{z}{1+z}\right)
"""
z = aszarr(z)
zp1 = z + 1.0 # (converts z [unit] -> z [dimensionless])
return zp1 ** (3 * (1 + self._w0 + self._wa)) * np.exp(-3 * self._wa * z / zp1)
class Flatw0waCDM(FlatFLRWMixin, w0waCDM):
"""FLRW cosmology with a CPL dark energy equation of state and no
curvature.
The equation for the dark energy equation of state uses the CPL form as
described in Chevallier & Polarski [1]_ and Linder [2]_:
:math:`w(z) = w_0 + w_a (1-a) = w_0 + w_a z / (1+z)`.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
w0 : float, optional
Dark energy equation of state at z=0 (a=1). This is pressure/density
for dark energy in units where c=1.
wa : float, optional
Negative derivative of the dark energy equation of state with respect
to the scale factor. A cosmological constant has w0=-1.0 and wa=0.0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import Flatw0waCDM
>>> cosmo = Flatw0waCDM(H0=70, Om0=0.3, w0=-0.9, wa=0.2)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
References
----------
.. [1] Chevallier, M., & Polarski, D. (2001). Accelerating Universes with
Scaling Dark Matter. International Journal of Modern Physics D,
10(2), 213-223.
.. [2] Linder, E. (2003). Exploring the Expansion History of the
Universe. Phys. Rev. Lett., 90, 091301.
"""
def __init__(self, H0, Om0, w0=-1.0, wa=0.0, Tcmb0=0.0*u.K, Neff=3.04,
m_nu=0.0*u.eV, Ob0=None, *, name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=0.0, w0=w0, wa=wa, Tcmb0=Tcmb0,
Neff=Neff, m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.fw0wacdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._w0, self._wa)
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.fw0wacdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._Ogamma0 + self._Onu0,
self._w0, self._wa)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.fw0wacdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list, self._w0,
self._wa)
class wpwaCDM(FLRW):
r"""
FLRW cosmology with a CPL dark energy equation of state, a pivot redshift,
and curvature.
The equation for the dark energy equation of state uses the CPL form as
described in Chevallier & Polarski [1]_ and Linder [2]_, but modified to
have a pivot redshift as in the findings of the Dark Energy Task Force
[3]_: :math:`w(a) = w_p + w_a (a_p - a) = w_p + w_a( 1/(1+zp) - 1/(1+z) )`.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
Ode0 : float
Omega dark energy: density of dark energy in units of the critical
density at z=0.
wp : float, optional
Dark energy equation of state at the pivot redshift zp. This is
pressure/density for dark energy in units where c=1.
wa : float, optional
Negative derivative of the dark energy equation of state with respect
to the scale factor. A cosmological constant has wp=-1.0 and wa=0.0.
zp : float or quantity-like ['redshift'], optional
Pivot redshift -- the redshift where w(z) = wp
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import wpwaCDM
>>> cosmo = wpwaCDM(H0=70, Om0=0.3, Ode0=0.7, wp=-0.9, wa=0.2, zp=0.4)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
References
----------
.. [1] Chevallier, M., & Polarski, D. (2001). Accelerating Universes with
Scaling Dark Matter. International Journal of Modern Physics D,
10(2), 213-223.
.. [2] Linder, E. (2003). Exploring the Expansion History of the
Universe. Phys. Rev. Lett., 90, 091301.
.. [3] Albrecht, A., Amendola, L., Bernstein, G., Clowe, D., Eisenstein,
D., Guzzo, L., Hirata, C., Huterer, D., Kirshner, R., Kolb, E., &
Nichol, R. (2009). Findings of the Joint Dark Energy Mission Figure
of Merit Science Working Group. arXiv e-prints, arXiv:0901.0721.
"""
wp = Parameter(doc="Dark energy equation of state at the pivot redshift zp.", fvalidate="float")
wa = Parameter(doc="Negative derivative of dark energy equation of state w.r.t. a.",
fvalidate="float")
zp = Parameter(doc="The pivot redshift, where w(z) = wp.", unit=cu.redshift)
def __init__(self, H0, Om0, Ode0, wp=-1.0, wa=0.0, zp=0.0 * cu.redshift,
Tcmb0=0.0*u.K, Neff=3.04, m_nu=0.0*u.eV, Ob0=None, *,
name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=Ode0, Tcmb0=Tcmb0, Neff=Neff,
m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
self.wp = wp
self.wa = wa
self.zp = zp
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
apiv = 1.0 / (1.0 + self._zp.value)
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.wpwacdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._wp, apiv, self._wa)
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.wpwacdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0 + self._Onu0,
self._wp, apiv, self._wa)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.wpwacdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list, self._wp,
apiv, self._wa)
def w(self, z):
r"""Returns dark energy equation of state at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
w : ndarray or float
The dark energy equation of state
Returns `float` if the input is scalar.
Notes
-----
The dark energy equation of state is defined as
:math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at
redshift z and :math:`\rho(z)` is the density at redshift z, both in
units where c=1. Here this is :math:`w(z) = w_p + w_a (a_p - a)` where
:math:`a = 1/1+z` and :math:`a_p = 1 / 1 + z_p`.
"""
apiv = 1.0 / (1.0 + self._zp.value)
return self._wp + self._wa * (apiv - 1.0 / (aszarr(z) + 1.0))
def de_density_scale(self, z):
r"""Evaluates the redshift dependence of the dark energy density.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
I : ndarray or float
The scaling of the energy density of dark energy with redshift.
Returns `float` if the input is scalar.
Notes
-----
The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`,
and in this case is given by
.. math::
a_p = \frac{1}{1 + z_p}
I = \left(1 + z\right)^{3 \left(1 + w_p + a_p w_a\right)}
\exp \left(-3 w_a \frac{z}{1+z}\right)
"""
z = aszarr(z)
zp1 = z + 1.0 # (converts z [unit] -> z [dimensionless])
apiv = 1. / (1. + self._zp.value)
return zp1 ** (3. * (1. + self._wp + apiv * self._wa)) * \
np.exp(-3. * self._wa * z / zp1)
class w0wzCDM(FLRW):
"""
FLRW cosmology with a variable dark energy equation of state and curvature.
The equation for the dark energy equation of state uses the simple form:
:math:`w(z) = w_0 + w_z z`.
This form is not recommended for z > 1.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/sec/Mpc].
Om0 : float
Omega matter: density of non-relativistic matter in units of the
critical density at z=0.
Ode0 : float
Omega dark energy: density of dark energy in units of the critical
density at z=0.
w0 : float, optional
Dark energy equation of state at z=0. This is pressure/density for
dark energy in units where c=1.
wz : float, optional
Derivative of the dark energy equation of state with respect to z.
A cosmological constant has w0=-1.0 and wz=0.0.
Tcmb0 : float or scalar quantity-like ['temperature'], optional
Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K].
Setting this to zero will turn off both photons and neutrinos
(even massive ones).
Neff : float, optional
Effective number of Neutrino species. Default 3.04.
m_nu : quantity-like ['energy', 'mass'] or array-like, optional
Mass of each neutrino species in [eV] (mass-energy equivalency enabled).
If this is a scalar Quantity, then all neutrino species are assumed to
have that mass. Otherwise, the mass of each species. The actual number
of neutrino species (and hence the number of elements of m_nu if it is
not scalar) must be the floor of Neff. Typically this means you should
provide three neutrino masses unless you are considering something like
a sterile neutrino.
Ob0 : float or None, optional
Omega baryons: density of baryonic matter in units of the critical
density at z=0. If this is set to None (the default), any computation
that requires its value will raise an exception.
name : str or None (optional, keyword-only)
Name for this cosmological object.
meta : mapping or None (optional, keyword-only)
Metadata for the cosmology, e.g., a reference.
Examples
--------
>>> from astropy.cosmology import w0wzCDM
>>> cosmo = w0wzCDM(H0=70, Om0=0.3, Ode0=0.7, w0=-0.9, wz=0.2)
The comoving distance in Mpc at redshift z:
>>> z = 0.5
>>> dc = cosmo.comoving_distance(z)
"""
w0 = Parameter(doc="Dark energy equation of state at z=0.", fvalidate="float")
wz = Parameter(doc="Derivative of the dark energy equation of state w.r.t. z.", fvalidate="float")
def __init__(self, H0, Om0, Ode0, w0=-1.0, wz=0.0, Tcmb0=0.0*u.K, Neff=3.04,
m_nu=0.0*u.eV, Ob0=None, *, name=None, meta=None):
super().__init__(H0=H0, Om0=Om0, Ode0=Ode0, Tcmb0=Tcmb0, Neff=Neff,
m_nu=m_nu, Ob0=Ob0, name=name, meta=meta)
self.w0 = w0
self.wz = wz
# Please see :ref:`astropy-cosmology-fast-integrals` for discussion
# about what is being done here.
if self._Tcmb0.value == 0:
self._inv_efunc_scalar = scalar_inv_efuncs.w0wzcdm_inv_efunc_norel
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._w0, self._wz)
elif not self._massivenu:
self._inv_efunc_scalar = scalar_inv_efuncs.w0wzcdm_inv_efunc_nomnu
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0 + self._Onu0,
self._w0, self._wz)
else:
self._inv_efunc_scalar = scalar_inv_efuncs.w0wzcdm_inv_efunc
self._inv_efunc_scalar_args = (self._Om0, self._Ode0, self._Ok0,
self._Ogamma0, self._neff_per_nu,
self._nmasslessnu,
self._nu_y_list, self._w0,
self._wz)
def w(self, z):
r"""Returns dark energy equation of state at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
w : ndarray or float
The dark energy equation of state.
Returns `float` if the input is scalar.
Notes
-----
The dark energy equation of state is defined as
:math:`w(z) = P(z)/\rho(z)`, where :math:`P(z)` is the pressure at
redshift z and :math:`\rho(z)` is the density at redshift z, both in
units where c=1. Here this is given by :math:`w(z) = w_0 + w_z z`.
"""
return self._w0 + self._wz * aszarr(z)
def de_density_scale(self, z):
r"""Evaluates the redshift dependence of the dark energy density.
Parameters
----------
z : Quantity-like ['redshift'], array-like, or `~numbers.Number`
Input redshift.
Returns
-------
I : ndarray or float
The scaling of the energy density of dark energy with redshift.
Returns `float` if the input is scalar.
Notes
-----
The scaling factor, I, is defined by :math:`\rho(z) = \rho_0 I`,
and in this case is given by
.. math::
I = \left(1 + z\right)^{3 \left(1 + w_0 - w_z\right)}
\exp \left(-3 w_z z\right)
"""
z = aszarr(z)
zp1 = z + 1.0 # (converts z [unit] -> z [dimensionless])
return zp1 ** (3. * (1. + self._w0 - self._wz)) * np.exp(-3. * self._wz * z)
|
6c5f2c742ebd1b3237e201af83be58da5518b507dd607abe6ae185575e72ad98 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Convenience functions for `astropy.cosmology`.
"""
import warnings
import numpy as np
from astropy.units import Quantity
from astropy.utils.exceptions import AstropyUserWarning
from . import units as cu
from .core import CosmologyError
__all__ = ['z_at_value']
__doctest_requires__ = {'*': ['scipy']}
def _z_at_scalar_value(func, fval, zmin=1e-8, zmax=1000, ztol=1e-8, maxfun=500,
method='Brent', bracket=None, verbose=False):
"""
Find the redshift ``z`` at which ``func(z) = fval``.
See :func:`astropy.cosmology.funcs.z_at_value`.
"""
from scipy.optimize import minimize_scalar
opt = {'maxiter': maxfun}
# Assume custom methods support the same options as default; otherwise user
# will see warnings.
if str(method).lower() == 'bounded':
opt['xatol'] = ztol
if bracket is not None:
warnings.warn(f"Option 'bracket' is ignored by method {method}.")
bracket = None
else:
opt['xtol'] = ztol
# fval falling inside the interval of bracketing function values does not
# guarantee it has a unique solution, but for Standard Cosmological
# quantities normally should (being monotonic or having a single extremum).
# In these cases keep solver from returning solutions outside of bracket.
fval_zmin, fval_zmax = func(zmin), func(zmax)
nobracket = False
if np.sign(fval - fval_zmin) != np.sign(fval_zmax - fval):
if bracket is None:
nobracket = True
else:
fval_brac = func(np.asanyarray(bracket))
if np.sign(fval - fval_brac[0]) != np.sign(fval_brac[-1] - fval):
nobracket = True
else:
zmin, zmax = bracket[0], bracket[-1]
fval_zmin, fval_zmax = fval_brac[[0, -1]]
if nobracket:
warnings.warn(f"fval is not bracketed by func(zmin)={fval_zmin} and "
f"func(zmax)={fval_zmax}. This means either there is no "
"solution, or that there is more than one solution "
"between zmin and zmax satisfying fval = func(z).",
AstropyUserWarning)
if isinstance(fval_zmin, Quantity):
val = fval.to_value(fval_zmin.unit)
else:
val = fval
# 'Brent' and 'Golden' ignore `bounds`, force solution inside zlim
def f(z):
if z > zmax:
return 1.e300 * (1.0 + z - zmax)
elif z < zmin:
return 1.e300 * (1.0 + zmin - z)
elif isinstance(fval_zmin, Quantity):
return abs(func(z).value - val)
else:
return abs(func(z) - val)
res = minimize_scalar(f, method=method, bounds=(zmin, zmax),
bracket=bracket, options=opt)
# Scipy docs state that `OptimizeResult` always has 'status' and 'message'
# attributes, but only `_minimize_scalar_bounded()` seems to have really
# implemented them.
if not res.success:
warnings.warn(f"Solver returned {res.get('status')}: {res.get('message', 'Unsuccessful')}\n"
f"Precision {res.fun} reached after {res.nfev} function calls.",
AstropyUserWarning)
if verbose:
print(res)
if np.allclose(res.x, zmax):
raise CosmologyError(
f"Best guess z={res.x} is very close to the upper z limit {zmax}."
"\nTry re-running with a different zmax.")
elif np.allclose(res.x, zmin):
raise CosmologyError(
f"Best guess z={res.x} is very close to the lower z limit {zmin}."
"\nTry re-running with a different zmin.")
return res.x
def z_at_value(func, fval, zmin=1e-8, zmax=1000, ztol=1e-8, maxfun=500,
method='Brent', bracket=None, verbose=False):
"""Find the redshift ``z`` at which ``func(z) = fval``.
This finds the redshift at which one of the cosmology functions or
methods (for example Planck13.distmod) is equal to a known value.
.. warning::
Make sure you understand the behavior of the function that you are
trying to invert! Depending on the cosmology, there may not be a
unique solution. For example, in the standard Lambda CDM cosmology,
there are two redshifts which give an angular diameter distance of
1500 Mpc, z ~ 0.7 and z ~ 3.8. To force ``z_at_value`` to find the
solution you are interested in, use the ``zmin`` and ``zmax`` keywords
to limit the search range (see the example below).
Parameters
----------
func : function or method
A function that takes a redshift as input.
fval : `~astropy.units.Quantity`
The (scalar or array) value of ``func(z)`` to recover.
zmin : float or array-like['dimensionless'] or quantity-like, optional
The lower search limit for ``z``. Beware of divergences
in some cosmological functions, such as distance moduli,
at z=0 (default 1e-8).
zmax : float or array-like['dimensionless'] or quantity-like, optional
The upper search limit for ``z`` (default 1000).
ztol : float or array-like['dimensionless'], optional
The relative error in ``z`` acceptable for convergence.
maxfun : int or array-like, optional
The maximum number of function evaluations allowed in the
optimization routine (default 500).
method : str or callable, optional
Type of solver to pass to the minimizer. The built-in options provided
by :func:`~scipy.optimize.minimize_scalar` are 'Brent' (default),
'Golden' and 'Bounded' with names case insensitive - see documentation
there for details. It also accepts a custom solver by passing any
user-provided callable object that meets the requirements listed
therein under the Notes on "Custom minimizers" - or in more detail in
:doc:`scipy:tutorial/optimize` - although their use is currently
untested.
.. versionadded:: 4.3
bracket : sequence or object array[sequence], optional
For methods 'Brent' and 'Golden', ``bracket`` defines the bracketing
interval and can either have three items (z1, z2, z3) so that
z1 < z2 < z3 and ``func(z2) < func (z1), func(z3)`` or two items z1
and z3 which are assumed to be a starting interval for a downhill
bracket search. For non-monotonic functions such as angular diameter
distance this may be used to start the search on the desired side of
the maximum, but see Examples below for usage notes.
.. versionadded:: 4.3
verbose : bool, optional
Print diagnostic output from solver (default `False`).
.. versionadded:: 4.3
Returns
-------
z : `~astropy.units.Quantity` ['redshift']
The redshift ``z`` satisfying ``zmin < z < zmax`` and ``func(z) =
fval`` within ``ztol``. Has units of cosmological redshift.
Warns
-----
:class:`~astropy.utils.exceptions.AstropyUserWarning`
If ``fval`` is not bracketed by ``func(zmin)=fval(zmin)`` and
``func(zmax)=fval(zmax)``.
If the solver was not successful.
Raises
------
:class:`astropy.cosmology.CosmologyError`
If the result is very close to either ``zmin`` or ``zmax``.
ValueError
If ``bracket`` is not an array nor a 2 (or 3) element sequence.
TypeError
If ``bracket`` is not an object array. 2 (or 3) element sequences will
be turned into object arrays, so this error should only occur if a
non-object array is used for ``bracket``.
Notes
-----
This works for any arbitrary input cosmology, but is inefficient if you
want to invert a large number of values for the same cosmology. In this
case, it is faster to instead generate an array of values at many
closely-spaced redshifts that cover the relevant redshift range, and then
use interpolation to find the redshift at each value you are interested
in. For example, to efficiently find the redshifts corresponding to 10^6
values of the distance modulus in a Planck13 cosmology, you could do the
following:
>>> import astropy.units as u
>>> from astropy.cosmology import Planck13, z_at_value
Generate 10^6 distance moduli between 24 and 44 for which we
want to find the corresponding redshifts:
>>> Dvals = (24 + np.random.rand(1000000) * 20) * u.mag
Make a grid of distance moduli covering the redshift range we
need using 50 equally log-spaced values between zmin and
zmax. We use log spacing to adequately sample the steep part of
the curve at low distance moduli:
>>> zmin = z_at_value(Planck13.distmod, Dvals.min())
>>> zmax = z_at_value(Planck13.distmod, Dvals.max())
>>> zgrid = np.geomspace(zmin, zmax, 50)
>>> Dgrid = Planck13.distmod(zgrid)
Finally interpolate to find the redshift at each distance modulus:
>>> zvals = np.interp(Dvals.value, Dgrid.value, zgrid)
Examples
--------
>>> import astropy.units as u
>>> from astropy.cosmology import Planck13, Planck18, z_at_value
The age and lookback time are monotonic with redshift, and so a
unique solution can be found:
>>> z_at_value(Planck13.age, 2 * u.Gyr) # doctest: +FLOAT_CMP
<Quantity 3.19812268 redshift>
The angular diameter is not monotonic however, and there are two
redshifts that give a value of 1500 Mpc. You can use the zmin and
zmax keywords to find the one you are interested in:
>>> z_at_value(Planck18.angular_diameter_distance,
... 1500 * u.Mpc, zmax=1.5) # doctest: +FLOAT_CMP
<Quantity 0.68044452 redshift>
>>> z_at_value(Planck18.angular_diameter_distance,
... 1500 * u.Mpc, zmin=2.5) # doctest: +FLOAT_CMP
<Quantity 3.7823268 redshift>
Alternatively the ``bracket`` option may be used to initialize the
function solver on a desired region, but one should be aware that this
does not guarantee it will remain close to this starting bracket.
For the example of angular diameter distance, which has a maximum near
a redshift of 1.6 in this cosmology, defining a bracket on either side
of this maximum will often return a solution on the same side:
>>> z_at_value(Planck18.angular_diameter_distance,
... 1500 * u.Mpc, bracket=(1.0, 1.2)) # doctest: +FLOAT_CMP +IGNORE_WARNINGS
<Quantity 0.68044452 redshift>
But this is not ascertained especially if the bracket is chosen too wide
and/or too close to the turning point:
>>> z_at_value(Planck18.angular_diameter_distance,
... 1500 * u.Mpc, bracket=(0.1, 1.5)) # doctest: +SKIP
<Quantity 3.7823268 redshift> # doctest: +SKIP
Likewise, even for the same minimizer and same starting conditions different
results can be found depending on architecture or library versions:
>>> z_at_value(Planck18.angular_diameter_distance,
... 1500 * u.Mpc, bracket=(2.0, 2.5)) # doctest: +SKIP
<Quantity 3.7823268 redshift> # doctest: +SKIP
>>> z_at_value(Planck18.angular_diameter_distance,
... 1500 * u.Mpc, bracket=(2.0, 2.5)) # doctest: +SKIP
<Quantity 0.68044452 redshift> # doctest: +SKIP
It is therefore generally safer to use the 3-parameter variant to ensure
the solution stays within the bracketing limits:
>>> z_at_value(Planck18.angular_diameter_distance, 1500 * u.Mpc,
... bracket=(0.1, 1.0, 1.5)) # doctest: +FLOAT_CMP
<Quantity 0.68044452 redshift>
Also note that the luminosity distance and distance modulus (two
other commonly inverted quantities) are monotonic in flat and open
universes, but not in closed universes.
All the arguments except ``func``, ``method`` and ``verbose`` accept array
inputs. This does NOT use interpolation tables or any method to speed up
evaluations, rather providing a convenient means to broadcast arguments
over an element-wise scalar evaluation.
The most common use case for non-scalar input is to evaluate 'func' for an
array of ``fval``:
>>> z_at_value(Planck13.age, [2, 7] * u.Gyr) # doctest: +FLOAT_CMP
<Quantity [3.19812061, 0.75620443] redshift>
``fval`` can be any shape:
>>> z_at_value(Planck13.age, [[2, 7], [1, 3]]*u.Gyr) # doctest: +FLOAT_CMP
<Quantity [[3.19812061, 0.75620443],
[5.67661227, 2.19131955]] redshift>
Other arguments can be arrays. For non-monotic functions -- for example,
the angular diameter distance -- this can be useful to find all solutions.
>>> z_at_value(Planck13.angular_diameter_distance, 1500 * u.Mpc,
... zmin=[0, 2.5], zmax=[2, 4]) # doctest: +FLOAT_CMP
<Quantity [0.68127747, 3.79149062] redshift>
The ``bracket`` argument can likewise be be an array. However, since
bracket must already be a sequence (or None), it MUST be given as an
object `numpy.ndarray`. Importantly, the depth of the array must be such
that each bracket subsequence is an object. Errors or unexpected results
will happen otherwise. A convenient means to ensure the right depth is by
including a length-0 tuple as a bracket and then truncating the object
array to remove the placeholder. This can be seen in the following
example:
>>> bracket=np.array([(1.0, 1.2),(2.0, 2.5), ()], dtype=object)[:-1]
>>> z_at_value(Planck18.angular_diameter_distance, 1500 * u.Mpc,
... bracket=bracket) # doctest: +SKIP
<Quantity [0.68044452, 3.7823268] redshift>
"""
# `fval` can be a Quantity, which isn't (yet) compatible w/ `numpy.nditer`
# so we strip it of units for broadcasting and restore the units when
# passing the elements to `_z_at_scalar_value`.
fval = np.asanyarray(fval)
unit = getattr(fval, 'unit', 1) # can be unitless
zmin = Quantity(zmin, cu.redshift).value # must be unitless
zmax = Quantity(zmax, cu.redshift).value
# bracket must be an object array (assumed to be correct) or a 'scalar'
# bracket: 2 or 3 elt sequence
if not isinstance(bracket, np.ndarray): # 'scalar' bracket
if bracket is not None and len(bracket) not in (2, 3):
raise ValueError("`bracket` is not an array "
"nor a 2 (or 3) element sequence.")
else: # munge bracket into a 1-elt object array
bracket = np.array([bracket, ()], dtype=object)[:1].squeeze()
if bracket.dtype != np.object_:
raise TypeError(f"`bracket` has dtype {bracket.dtype}, not 'O'")
# make multi-dimensional iterator for all but `method`, `verbose`
with np.nditer(
[fval, zmin, zmax, ztol, maxfun, bracket, None],
flags = ['refs_ok'],
op_flags = [*[['readonly']] * 6, # ← inputs output ↓
['writeonly', 'allocate', 'no_subtype']],
op_dtypes = (*(None,)*6, fval.dtype),
casting="no",
) as it:
for fv, zmn, zmx, zt, mfe, bkt, zs in it: # ← eltwise unpack & eval ↓
zs[...] = _z_at_scalar_value(func, fv * unit, zmin=zmn, zmax=zmx,
ztol=zt, maxfun=mfe, bracket=bkt.item(),
# not broadcasted
method=method, verbose=verbose)
# since bracket is an object array, the output will be too, so it is
# cast to the same type as the function value.
result = it.operands[-1] # zs
return result << cu.redshift
|
0cf697f9e13d46cb19ec2fcefcaeb5fa9783a44383a4a3f6f84010f6b5a099dd | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import functools
from math import inf
from numbers import Number
import numpy as np
from astropy.units import Quantity
from astropy.utils import isiterable
from astropy.utils.decorators import deprecated
from . import units as cu
__all__ = [] # nothing is publicly scoped
__doctest_skip__ = ["inf_like", "vectorize_if_needed"]
def vectorize_redshift_method(func=None, nin=1):
"""Vectorize a method of redshift(s).
Parameters
----------
func : callable or None
method to wrap. If `None` returns a :func:`functools.partial`
with ``nin`` loaded.
nin : int
Number of positional redshift arguments.
Returns
-------
wrapper : callable
:func:`functools.wraps` of ``func`` where the first ``nin``
arguments are converted from |Quantity| to :class:`numpy.ndarray`.
"""
# allow for pie-syntax & setting nin
if func is None:
return functools.partial(vectorize_redshift_method, nin=nin)
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
"""
:func:`functools.wraps` of ``func`` where the first ``nin``
arguments are converted from |Quantity| to `numpy.ndarray` or scalar.
"""
# process inputs
# TODO! quantity-aware vectorization can simplify this.
zs = [z if not isinstance(z, Quantity) else z.to_value(cu.redshift)
for z in args[:nin]]
# scalar inputs
if all(isinstance(z, (Number, np.generic)) for z in zs):
return func(self, *zs, *args[nin:], **kwargs)
# non-scalar. use vectorized func
return wrapper.__vectorized__(self, *zs, *args[nin:], **kwargs)
wrapper.__vectorized__ = np.vectorize(func) # attach vectorized function
# TODO! use frompyfunc when can solve return type errors
return wrapper
@deprecated(
since="5.0",
message="vectorize_if_needed has been removed because it constructs a new ufunc on each call",
alternative="use a pre-vectorized function instead for a target array 'z'"
)
def vectorize_if_needed(f, *x, **vkw):
"""Helper function to vectorize scalar functions on array inputs.
Parameters
----------
f : callable
'f' must accept positional arguments and no mandatory keyword
arguments.
*x
Arguments into ``f``.
**vkw
Keyword arguments into :class:`numpy.vectorize`.
Examples
--------
>>> func = lambda x: x ** 2
>>> vectorize_if_needed(func, 2)
4
>>> vectorize_if_needed(func, [2, 3])
array([4, 9])
"""
return np.vectorize(f, **vkw)(*x) if any(map(isiterable, x)) else f(*x)
@deprecated(
since="5.0",
message="inf_like has been removed because it duplicates functionality provided by numpy.full_like()",
alternative="Use numpy.full_like(z, numpy.inf) instead for a target array 'z'"
)
def inf_like(x):
"""Return the shape of x with value infinity and dtype='float'.
Preserves 'shape' for both array and scalar inputs.
But always returns a float array, even if x is of integer type.
Parameters
----------
x : scalar or array-like
Must work with functions `numpy.isscalar` and `numpy.full_like` (if `x`
is not a scalar`
Returns
-------
`math.inf` or ndarray[float] thereof
Returns a scalar `~math.inf` if `x` is a scalar, an array of floats
otherwise.
Examples
--------
>>> inf_like(0.) # float scalar
inf
>>> inf_like(1) # integer scalar should give float output
inf
>>> inf_like([0., 1., 2., 3.]) # float list
array([inf, inf, inf, inf])
>>> inf_like([0, 1, 2, 3]) # integer list should give float output
array([inf, inf, inf, inf])
"""
return inf if np.isscalar(x) else np.full_like(x, inf, dtype=float)
def aszarr(z):
"""
Redshift as a `~numbers.Number` or `~numpy.ndarray` / |Quantity| / |Column|.
Allows for any ndarray ducktype by checking for attribute "shape".
"""
if isinstance(z, (Number, np.generic)): # scalars
return z
elif hasattr(z, "shape"): # ducktypes NumPy array
if hasattr(z, "unit"): # Quantity Column
return (z << cu.redshift).value # for speed only use enabled equivs
return z
# not one of the preferred types: Number / array ducktype
return Quantity(z, cu.redshift).value
|
725c8903b83c94a766cea2c7f666157b3547c8eac417ec10d93a757730166298 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Cosmological units and equivalencies.
""" # (newline needed for unit summary)
import astropy.units as u
from astropy.units.utils import generate_unit_summary as _generate_unit_summary
__all__ = ["littleh", "redshift",
# redshift equivalencies
"dimensionless_redshift", "with_redshift",
"redshift_distance", "redshift_hubble", "redshift_temperature",
# other equivalencies
"with_H0"]
__doctest_requires__ = {('with_redshift', 'redshift_distance'): ['scipy']}
_ns = globals()
###############################################################################
# Cosmological Units
# This is not formally a unit, but is used in that way in many contexts, and
# an appropriate equivalency is only possible if it's treated as a unit.
redshift = u.def_unit(['redshift'], prefixes=False, namespace=_ns,
doc="Cosmological redshift.", format={'latex': r''})
# This is not formally a unit, but is used in that way in many contexts, and
# an appropriate equivalency is only possible if it's treated as a unit (see
# https://arxiv.org/pdf/1308.4150.pdf for more)
# Also note that h or h100 or h_100 would be a better name, but they either
# conflict or have numbers in them, which is disallowed
littleh = u.def_unit(['littleh'], namespace=_ns, prefixes=False,
doc='Reduced/"dimensionless" Hubble constant',
format={'latex': r'h_{100}'})
###############################################################################
# Equivalencies
def dimensionless_redshift():
"""Allow redshift to be 1-to-1 equivalent to dimensionless.
It is special compared to other equivalency pairs in that it
allows this independent of the power to which the redshift is raised,
and independent of whether it is part of a more complicated unit.
It is similar to u.dimensionless_angles() in this respect.
"""
return u.Equivalency([(redshift, None)], "dimensionless_redshift")
def redshift_distance(cosmology=None, kind="comoving", **atzkw):
"""Convert quantities between redshift and distance.
Care should be taken to not misinterpret a relativistic, gravitational, etc
redshift as a cosmological one.
Parameters
----------
cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional
A cosmology realization or built-in cosmology's name (e.g. 'Planck18').
If None, will use the default cosmology
(controlled by :class:`~astropy.cosmology.default_cosmology`).
kind : {'comoving', 'lookback', 'luminosity'} or None, optional
The distance type for the Equivalency.
Note this does NOT include the angular diameter distance as this
distance measure is not monotonic.
**atzkw
keyword arguments for :func:`~astropy.cosmology.z_at_value`
Returns
-------
`~astropy.units.equivalencies.Equivalency`
Equivalency between redshift and temperature.
Examples
--------
>>> import astropy.units as u
>>> import astropy.cosmology.units as cu
>>> from astropy.cosmology import WMAP9
>>> z = 1100 * cu.redshift
>>> z.to(u.Mpc, cu.redshift_distance(WMAP9, kind="comoving")) # doctest: +FLOAT_CMP
<Quantity 14004.03157418 Mpc>
"""
from astropy.cosmology import default_cosmology, z_at_value
# get cosmology: None -> default and process str / class
cosmology = cosmology if cosmology is not None else default_cosmology.get()
with default_cosmology.set(cosmology): # if already cosmo, passes through
cosmology = default_cosmology.get()
allowed_kinds = ('comoving', 'lookback', 'luminosity')
if kind not in allowed_kinds:
raise ValueError(f"`kind` is not one of {allowed_kinds}")
method = getattr(cosmology, kind + "_distance")
def z_to_distance(z):
"""Redshift to distance."""
return method(z)
def distance_to_z(d):
"""Distance to redshift."""
return z_at_value(method, d << u.Mpc, **atzkw)
return u.Equivalency([(redshift, u.Mpc, z_to_distance, distance_to_z)],
"redshift_distance",
{'cosmology': cosmology, "distance": kind})
def redshift_hubble(cosmology=None, **atzkw):
"""Convert quantities between redshift and Hubble parameter and little-h.
Care should be taken to not misinterpret a relativistic, gravitational, etc
redshift as a cosmological one.
Parameters
----------
cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional
A cosmology realization or built-in cosmology's name (e.g. 'Planck18').
If None, will use the default cosmology
(controlled by :class:`~astropy.cosmology.default_cosmology`).
**atzkw
keyword arguments for :func:`~astropy.cosmology.z_at_value`
Returns
-------
`~astropy.units.equivalencies.Equivalency`
Equivalency between redshift and Hubble parameter and little-h unit.
Examples
--------
>>> import astropy.units as u
>>> import astropy.cosmology.units as cu
>>> from astropy.cosmology import WMAP9
>>> z = 1100 * cu.redshift
>>> equivalency = cu.redshift_hubble(WMAP9) # construct equivalency
>>> z.to(u.km / u.s / u.Mpc, equivalency) # doctest: +FLOAT_CMP
<Quantity 1565637.40154275 km / (Mpc s)>
>>> z.to(cu.littleh, equivalency) # doctest: +FLOAT_CMP
<Quantity 15656.37401543 littleh>
"""
from astropy.cosmology import default_cosmology, z_at_value
# get cosmology: None -> default and process str / class
cosmology = cosmology if cosmology is not None else default_cosmology.get()
with default_cosmology.set(cosmology): # if already cosmo, passes through
cosmology = default_cosmology.get()
def z_to_hubble(z):
"""Redshift to Hubble parameter."""
return cosmology.H(z)
def hubble_to_z(H):
"""Hubble parameter to redshift."""
return z_at_value(cosmology.H, H << (u.km / u.s / u.Mpc), **atzkw)
def z_to_littleh(z):
"""Redshift to :math:`h`-unit Quantity."""
return z_to_hubble(z).to_value(u.km / u.s / u.Mpc) / 100 * littleh
def littleh_to_z(h):
""":math:`h`-unit Quantity to redshift."""
return hubble_to_z(h * 100)
return u.Equivalency([(redshift, u.km / u.s / u.Mpc, z_to_hubble, hubble_to_z),
(redshift, littleh, z_to_littleh, littleh_to_z)],
"redshift_hubble",
{'cosmology': cosmology})
def redshift_temperature(cosmology=None, **atzkw):
"""Convert quantities between redshift and CMB temperature.
Care should be taken to not misinterpret a relativistic, gravitational, etc
redshift as a cosmological one.
Parameters
----------
cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional
A cosmology realization or built-in cosmology's name (e.g. 'Planck18').
If None, will use the default cosmology
(controlled by :class:`~astropy.cosmology.default_cosmology`).
**atzkw
keyword arguments for :func:`~astropy.cosmology.z_at_value`
Returns
-------
`~astropy.units.equivalencies.Equivalency`
Equivalency between redshift and temperature.
Examples
--------
>>> import astropy.units as u
>>> import astropy.cosmology.units as cu
>>> from astropy.cosmology import WMAP9
>>> z = 1100 * cu.redshift
>>> z.to(u.K, cu.redshift_temperature(WMAP9))
<Quantity 3000.225 K>
"""
from astropy.cosmology import default_cosmology, z_at_value
# get cosmology: None -> default and process str / class
cosmology = cosmology if cosmology is not None else default_cosmology.get()
with default_cosmology.set(cosmology): # if already cosmo, passes through
cosmology = default_cosmology.get()
def z_to_Tcmb(z):
return cosmology.Tcmb(z)
def Tcmb_to_z(T):
return z_at_value(cosmology.Tcmb, T << u.K, **atzkw)
return u.Equivalency([(redshift, u.K, z_to_Tcmb, Tcmb_to_z)],
"redshift_temperature",
{'cosmology': cosmology})
def with_redshift(cosmology=None, *,
distance="comoving", hubble=True, Tcmb=True,
atzkw=None):
"""Convert quantities between measures of cosmological distance.
Note: by default all equivalencies are on and must be explicitly turned off.
Care should be taken to not misinterpret a relativistic, gravitational, etc
redshift as a cosmological one.
Parameters
----------
cosmology : `~astropy.cosmology.Cosmology`, str, or None, optional
A cosmology realization or built-in cosmology's name (e.g. 'Planck18').
If `None`, will use the default cosmology
(controlled by :class:`~astropy.cosmology.default_cosmology`).
distance : {'comoving', 'lookback', 'luminosity'} or None (optional, keyword-only)
The type of distance equivalency to create or `None`.
Default is 'comoving'.
hubble : bool (optional, keyword-only)
Whether to create a Hubble parameter <-> redshift equivalency, using
``Cosmology.H``. Default is `True`.
Tcmb : bool (optional, keyword-only)
Whether to create a CMB temperature <-> redshift equivalency, using
``Cosmology.Tcmb``. Default is `True`.
atzkw : dict or None (optional, keyword-only)
keyword arguments for :func:`~astropy.cosmology.z_at_value`
Returns
-------
`~astropy.units.equivalencies.Equivalency`
With equivalencies between redshift and distance / Hubble / temperature.
Examples
--------
>>> import astropy.units as u
>>> import astropy.cosmology.units as cu
>>> from astropy.cosmology import WMAP9
>>> equivalency = cu.with_redshift(WMAP9)
>>> z = 1100 * cu.redshift
Redshift to (comoving) distance:
>>> z.to(u.Mpc, equivalency) # doctest: +FLOAT_CMP
<Quantity 14004.03157418 Mpc>
Redshift to the Hubble parameter:
>>> z.to(u.km / u.s / u.Mpc, equivalency) # doctest: +FLOAT_CMP
<Quantity 1565637.40154275 km / (Mpc s)>
>>> z.to(cu.littleh, equivalency) # doctest: +FLOAT_CMP
<Quantity 15656.37401543 littleh>
Redshift to CMB temperature:
>>> z.to(u.K, equivalency)
<Quantity 3000.225 K>
"""
from astropy.cosmology import default_cosmology, z_at_value
# get cosmology: None -> default and process str / class
cosmology = cosmology if cosmology is not None else default_cosmology.get()
with default_cosmology.set(cosmology): # if already cosmo, passes through
cosmology = default_cosmology.get()
atzkw = atzkw if atzkw is not None else {}
equivs = [] # will append as built
# Hubble <-> Redshift
if hubble:
equivs.extend(redshift_hubble(cosmology, **atzkw))
# CMB Temperature <-> Redshift
if Tcmb:
equivs.extend(redshift_temperature(cosmology, **atzkw))
# Distance <-> Redshift, but need to choose which distance
if distance is not None:
equivs.extend(redshift_distance(cosmology, kind=distance, **atzkw))
# -----------
return u.Equivalency(equivs, "with_redshift",
{'cosmology': cosmology,
'distance': distance, 'hubble': hubble, 'Tcmb': Tcmb})
# ===================================================================
def with_H0(H0=None):
"""
Convert between quantities with little-h and the equivalent physical units.
Parameters
----------
H0 : None or `~astropy.units.Quantity` ['frequency']
The value of the Hubble constant to assume. If a
`~astropy.units.Quantity`, will assume the quantity *is* ``H0``. If
`None` (default), use the ``H0`` attribute from
:mod:`~astropy.cosmology.default_cosmology`.
References
----------
For an illuminating discussion on why you may or may not want to use
little-h at all, see https://arxiv.org/pdf/1308.4150.pdf
"""
if H0 is None:
from .realizations import default_cosmology
H0 = default_cosmology.get().H0
h100_val_unit = u.Unit(100/(H0.to_value(u.km / u.s / u.Mpc)) * littleh)
return u.Equivalency([(h100_val_unit, None)], "with_H0", kwargs={"H0": H0})
# ===================================================================
# Enable the set of default equivalencies.
# If the cosmology package is imported, this is added to the list astropy-wide.
u.add_enabled_equivalencies(dimensionless_redshift())
# =============================================================================
# DOCSTRING
# This generates a docstring for this module that describes all of the
# standard units defined here.
if __doc__ is not None:
__doc__ += _generate_unit_summary(_ns)
|
5a6310e2fe97f6e9a446fe4f52ca0b538260e9689927ed6104d3a303a1406145 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# STDLIB
import pathlib
import sys
# LOCAL
from astropy.utils.data import get_pkg_data_path
from astropy.utils.decorators import deprecated
from astropy.utils.state import ScienceState
from .core import Cosmology
_COSMOLOGY_DATA_DIR = pathlib.Path(get_pkg_data_path("cosmology", "data", package="astropy"))
available = tuple(sorted([p.stem for p in _COSMOLOGY_DATA_DIR.glob("*.ecsv")]))
__all__ = ["available", "default_cosmology"] + list(available)
__doctest_requires__ = {"*": ["scipy"]}
def __getattr__(name):
"""Make specific realizations from data files with lazy import from
`PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_.
Raises
------
AttributeError
If "name" is not in :mod:`astropy.cosmology.realizations`
"""
if name not in available:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}.")
cosmo = Cosmology.read(str(_COSMOLOGY_DATA_DIR / name) + ".ecsv", format="ascii.ecsv")
cosmo.__doc__ = (f"{name} instance of {cosmo.__class__.__qualname__} "
f"cosmology\n(from {cosmo.meta['reference']})")
# Cache in this module so `__getattr__` is only called once per `name`.
setattr(sys.modules[__name__], name, cosmo)
return cosmo
def __dir__():
"""Directory, including lazily-imported objects."""
return __all__
#########################################################################
# The science state below contains the current cosmology.
#########################################################################
class default_cosmology(ScienceState):
"""The default cosmology to use.
To change it::
>>> from astropy.cosmology import default_cosmology, WMAP7
>>> with default_cosmology.set(WMAP7):
... # WMAP7 cosmology in effect
... pass
Or, you may use a string::
>>> with default_cosmology.set('WMAP7'):
... # WMAP7 cosmology in effect
... pass
To get the default cosmology:
>>> default_cosmology.get()
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, ...
To get a specific cosmology:
>>> default_cosmology.get("Planck13")
FlatLambdaCDM(name="Planck13", H0=67.77 km / (Mpc s), Om0=0.30712, ...
"""
_default_value = "Planck18"
_value = "Planck18"
@classmethod
def get(cls, key=None):
"""Get the science state value of ``key``.
Parameters
----------
key : str or None
The built-in |Cosmology| realization to retrieve.
If None (default) get the current value.
Returns
-------
`astropy.cosmology.Cosmology` or None
`None` only if ``key`` is "no_default"
Raises
------
TypeError
If ``key`` is not a str, |Cosmology|, or None.
ValueError
If ``key`` is a str, but not for a built-in Cosmology
Examples
--------
To get the default cosmology:
>>> default_cosmology.get()
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966, ...
To get a specific cosmology:
>>> default_cosmology.get("Planck13")
FlatLambdaCDM(name="Planck13", H0=67.77 km / (Mpc s), Om0=0.30712, ...
"""
if key is None:
key = cls._value
if isinstance(key, str):
# special-case one string
if key == "no_default":
return None
# all other options should be built-in realizations
try:
value = getattr(sys.modules[__name__], key)
except AttributeError:
raise ValueError(f"Unknown cosmology {key!r}. "
f"Valid cosmologies:\n{available}")
elif isinstance(key, Cosmology):
value = key
else:
raise TypeError("'key' must be must be None, a string, "
f"or Cosmology instance, not {type(key)}.")
# validate value to `Cosmology`, if not already
return cls.validate(value)
@deprecated("5.0", alternative="get")
@classmethod
def get_cosmology_from_string(cls, arg):
"""Return a cosmology instance from a string."""
return cls.get(arg)
@classmethod
def validate(cls, value):
"""Return a Cosmology given a value.
Parameters
----------
value : None, str, or `~astropy.cosmology.Cosmology`
Returns
-------
`~astropy.cosmology.Cosmology` instance
Raises
------
TypeError
If ``value`` is not a string or |Cosmology|.
"""
# None -> default
if value is None:
value = cls._default_value
# Parse to Cosmology. Error if cannot.
if isinstance(value, str):
value = cls.get(value)
elif not isinstance(value, Cosmology):
raise TypeError("default_cosmology must be a string or Cosmology instance, "
f"not {value}.")
return value
|
514102f67ad180e9699b39d6f8add53c60d3ee4554f60ab206496631196ceafd | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# The BoxLeastSquares periodogram functionality has been moved to
# astropy.timeseries.periodograms.bls. The purpose of this file is to provide backward-
# compatibility during a transition phase. We can't emit a deprecation warning
# simply on import of this module, since the classes are imported into the
# top-level astropy.stats, so instead we wrap the main class and emit a
# warning during initialization.
import warnings
from astropy.timeseries.periodograms.bls import (BoxLeastSquares as TimeseriesBoxLeastSquares,
BoxLeastSquaresResults as TimeseriesBoxLeastSquaresResults)
from astropy.utils.exceptions import AstropyDeprecationWarning
__all__ = ['BoxLeastSquares', 'BoxLeastSquaresResults']
class BoxLeastSquares(TimeseriesBoxLeastSquares):
"""
Compute the box least squares periodogram.
This class has been deprecated and will be removed in a future version.
Use `astropy.timeseries.BoxLeastSquares` instead.
"""
def __init__(self, *args, **kwargs):
warnings.warn('Importing BoxLeastSquares from astropy.stats has been '
'deprecated and will no longer be supported in future. '
'Please import this class from the astropy.timeseries '
'module instead', AstropyDeprecationWarning)
super().__init__(*args, **kwargs)
class BoxLeastSquaresResults(TimeseriesBoxLeastSquaresResults):
"""
The results of a BoxLeastSquares search.
This class has been deprecated and will be removed in a future version.
Use `astropy.timeseries.BoxLeastSquaresResults` instead.
"""
def __init__(self, *args, **kwargs):
warnings.warn('Importing BoxLeastSquaresResults from astropy.stats has been '
'deprecated and will no longer be supported in future. '
'Please import this class from the astropy.timeseries '
'module instead', AstropyDeprecationWarning)
super().__init__(*args, **kwargs)
|
73a59d0ed5fc2aa8d418f9e75ac2bd38c165e4667d13b691f758fbf1bb5fe407 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from astropy.stats.jackknife import jackknife_resampling, jackknife_stats
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
def test_jackknife_resampling():
data = np.array([1, 2, 3, 4])
answer = np.array([[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]])
assert_equal(answer, jackknife_resampling(data))
# test jackknife stats, except confidence interval
@pytest.mark.skipif('not HAS_SCIPY')
def test_jackknife_stats():
# Test from the third example of Ref.[3]
data = np.array((115, 170, 142, 138, 280, 470, 480, 141, 390))
# true estimate, bias, and std_err
answer = (258.4444, 0.0, 50.25936)
assert_allclose(answer, jackknife_stats(data, np.mean)[0:3], atol=1e-4)
# test jackknife stats, including confidence intervals
@pytest.mark.skipif('not HAS_SCIPY')
def test_jackknife_stats_conf_interval():
# Test from the first example of Ref.[3]
data = np.array([48, 42, 36, 33, 20, 16, 29, 39, 42, 38, 42, 36, 20, 15,
42, 33, 22, 20, 41, 43, 45, 34, 14, 22, 6, 7, 0, 15, 33,
34, 28, 29, 34, 41, 4, 13, 32, 38, 24, 25, 47, 27, 41, 41,
24, 28, 26, 14, 30, 28, 41, 40])
data = np.reshape(data, (-1, 2))
data = data[:, 1]
# true estimate, bias, and std_err
answer = (113.7862, -4.376391, 22.26572)
# calculate the mle of the variance (biased estimator!)
def mle_var(x): return np.sum((x - np.mean(x))*(x - np.mean(x)))/len(x)
assert_allclose(answer, jackknife_stats(data, mle_var, 0.95)[0:3],
atol=1e-4)
# test confidence interval
answer = np.array((70.14615, 157.42616))
assert_allclose(answer, jackknife_stats(data, mle_var, 0.95)[3], atol=1e-4)
def test_jackknife_stats_exceptions():
with pytest.raises(ValueError):
jackknife_stats(np.arange(2), np.mean, confidence_level=42)
|
fcb5764e3a3d85257b1b137fe077eaa0f6ecf350306a43f4add1ea95952a69ac | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy.stats import (histogram, calculate_bin_edges, scott_bin_width,
freedman_bin_width, knuth_bin_width)
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
def test_scott_bin_width(N=10000, rseed=0):
rng = np.random.default_rng(rseed)
X = rng.standard_normal(N)
delta = scott_bin_width(X)
assert_allclose(delta, 3.5 * np.std(X) / N ** (1 / 3))
delta, bins = scott_bin_width(X, return_bins=True)
assert_allclose(delta, 3.5 * np.std(X) / N ** (1 / 3))
with pytest.raises(ValueError):
scott_bin_width(rng.random((2, 10)))
def test_freedman_bin_width(N=10000, rseed=0):
rng = np.random.default_rng(rseed)
X = rng.standard_normal(N)
v25, v75 = np.percentile(X, [25, 75])
delta = freedman_bin_width(X)
assert_allclose(delta, 2 * (v75 - v25) / N ** (1 / 3))
delta, bins = freedman_bin_width(X, return_bins=True)
assert_allclose(delta, 2 * (v75 - v25) / N ** (1 / 3))
with pytest.raises(ValueError):
freedman_bin_width(rng.random((2, 10)))
# data with too small IQR
test_x = [1, 2, 3] + [4] * 100 + [5, 6, 7]
with pytest.raises(ValueError) as e:
with pytest.warns(RuntimeWarning, match=r'divide by zero encountered'):
freedman_bin_width(test_x, return_bins=True)
assert 'Please use another bin method' in str(e.value)
# data with small IQR but not too small
test_x = np.asarray([1, 2, 3] * 100 + [4] + [5, 6, 7], dtype=np.float32)
test_x *= 1.5e-6
delta, bins = freedman_bin_width(test_x, return_bins=True)
assert_allclose(delta, 8.923325554510689e-07)
@pytest.mark.skipif('not HAS_SCIPY')
def test_knuth_bin_width(N=10000, rseed=0):
rng = np.random.default_rng(rseed)
X = rng.standard_normal(N)
dx, bins = knuth_bin_width(X, return_bins=True)
assert_allclose(len(bins), 58)
dx2 = knuth_bin_width(X)
assert dx == dx2
with pytest.raises(ValueError):
knuth_bin_width(rng.random((2, 10)))
@pytest.mark.skipif('not HAS_SCIPY')
def test_knuth_histogram(N=1000, rseed=0):
rng = np.random.default_rng(rseed)
x = rng.standard_normal(N)
counts, bins = histogram(x, 'knuth')
assert (counts.sum() == len(x))
assert (len(counts) == len(bins) - 1)
_bin_types_to_test = [30, 'scott', 'freedman', 'blocks']
if HAS_SCIPY:
_bin_types_to_test += ['knuth']
@pytest.mark.parametrize('bin_type',
_bin_types_to_test + [np.linspace(-5, 5, 31)])
def test_histogram(bin_type, N=1000, rseed=0):
rng = np.random.default_rng(rseed)
x = rng.standard_normal(N)
counts, bins = histogram(x, bin_type)
assert (counts.sum() == len(x))
assert (len(counts) == len(bins) - 1)
# Don't include a list of bins as a bin_type here because the effect
# of range is different in that case
@pytest.mark.parametrize('bin_type', _bin_types_to_test)
def test_histogram_range(bin_type, N=1000, rseed=0):
# Regression test for #8010
rng = np.random.default_rng(rseed)
x = rng.standard_normal(N)
range = (0.1, 0.8)
bins = calculate_bin_edges(x, bin_type, range=range)
assert bins.max() == range[1]
assert bins.min() == range[0]
def test_histogram_range_with_bins_list(N=1000, rseed=0):
# The expected result when the input bins is a list is
# the same list on output.
rng = np.random.default_rng(rseed)
x = rng.standard_normal(N)
range = (0.1, 0.8)
input_bins = np.linspace(-5, 5, 31)
bins = calculate_bin_edges(x, input_bins, range=range)
assert all(bins == input_bins)
@pytest.mark.skipif('not HAS_SCIPY')
def test_histogram_output_knuth():
rng = np.random.default_rng(0)
X = rng.standard_normal(100)
counts, bins = histogram(X, bins='knuth')
assert_allclose(counts, [2, 1, 13, 19, 15, 18, 14, 10, 8])
assert_allclose(bins, [-2.32503077, -1.84420596, -1.36338114, -0.88255632, -0.4017315,
0.07909331, 0.55991813, 1.04074295, 1.52156777, 2.00239258])
def test_histogram_output():
rng = np.random.default_rng(0)
X = rng.standard_normal(100)
counts, bins = histogram(X, bins=10)
assert_allclose(counts, [2, 0, 12, 14, 14, 17, 16, 8, 9, 8])
assert_allclose(bins, [-2.32503077, -1.89228844, -1.4595461, -1.02680377, -0.59406143,
-0.1613191, 0.27142324, 0.70416558, 1.13690791, 1.56965025,
2.00239258])
counts, bins = histogram(X, bins='scott')
assert_allclose(counts, [2, 14, 27, 25, 16, 16])
assert_allclose(bins, [-2.32503077, -1.59953424, -0.87403771, -0.14854117, 0.57695536,
1.3024519, 2.02794843])
counts, bins = histogram(X, bins='freedman')
assert_allclose(counts, [2, 11, 16, 18, 22, 14, 13, 4])
assert_allclose(bins, [-2.32503077, -1.74087192, -1.15671306, -0.5725542, 0.01160465,
0.59576351, 1.17992237, 1.76408122, 2.34824008], rtol=2e-7)
counts, bins = histogram(X, bins='blocks')
assert_allclose(counts, [3, 97])
assert_allclose(bins, [-2.32503077, -1.37136996, 2.00239258])
def test_histogram_badargs(N=1000, rseed=0):
rng = np.random.default_rng(rseed)
x = rng.standard_normal(N)
# weights is not supported
for bins in ['scott', 'freedman', 'blocks']:
with pytest.raises(NotImplementedError):
histogram(x, bins, weights=x)
# bad bins arg gives ValueError
with pytest.raises(ValueError):
histogram(x, bins='bad_argument')
|
cfbe2601a1de4d1c658b9073f5d00fbe2f2def10b56698a76e024da2735edfbb | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from astropy import units as u
from astropy.stats import mad_std
from astropy.stats.sigma_clipping import sigma_clip, SigmaClip, sigma_clipped_stats
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.misc import NumpyRNGContext
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
def test_sigma_clip():
# need to seed the numpy RNG to make sure we don't get some
# amazingly flukey random number that breaks one of the tests
with NumpyRNGContext(12345):
# Amazing, I've got the same combination on my luggage!
randvar = np.random.randn(10000)
filtered_data = sigma_clip(randvar, sigma=1, maxiters=2)
assert sum(filtered_data.mask) > 0
assert sum(~filtered_data.mask) < randvar.size
# this is actually a silly thing to do, because it uses the
# standard deviation as the variance, but it tests to make sure
# these arguments are actually doing something
filtered_data2 = sigma_clip(randvar, sigma=1, maxiters=2,
stdfunc=np.var)
assert not np.all(filtered_data.mask == filtered_data2.mask)
filtered_data3 = sigma_clip(randvar, sigma=1, maxiters=2,
cenfunc=np.mean)
assert not np.all(filtered_data.mask == filtered_data3.mask)
# make sure the maxiters=None method works at all.
filtered_data = sigma_clip(randvar, sigma=3, maxiters=None)
# test copying
assert filtered_data.data[0] == randvar[0]
filtered_data.data[0] += 1.
assert filtered_data.data[0] != randvar[0]
filtered_data = sigma_clip(randvar, sigma=3, maxiters=None,
copy=False)
assert filtered_data.data[0] == randvar[0]
filtered_data.data[0] += 1.
assert filtered_data.data[0] == randvar[0]
# test axis
data = np.arange(5) + np.random.normal(0., 0.05, (5, 5)) + \
np.diag(np.ones(5))
filtered_data = sigma_clip(data, axis=0, sigma=2.3)
assert filtered_data.count() == 20
filtered_data = sigma_clip(data, axis=1, sigma=2.3)
assert filtered_data.count() == 25
@pytest.mark.skipif('not HAS_SCIPY')
def test_axis_none():
"""
For masked=False and axis=None, masked elements should be removed
from the result.
"""
data = np.arange(10.)
data[0] = 100
result = sigma_clip(data, masked=False, axis=None)
assert_equal(result, data[1:])
@pytest.mark.skipif('not HAS_SCIPY')
def test_compare_to_scipy_sigmaclip():
from scipy import stats
# need to seed the numpy RNG to make sure we don't get some
# amazingly flukey random number that breaks one of the tests
with NumpyRNGContext(12345):
randvar = np.random.randn(10000)
astropyres = sigma_clip(randvar, sigma=3, maxiters=None,
cenfunc=np.mean)
scipyres = stats.sigmaclip(randvar, 3, 3)[0]
assert astropyres.count() == len(scipyres)
assert_equal(astropyres[~astropyres.mask].data, scipyres)
def test_sigma_clip_scalar_mask():
"""Test that the returned mask is not a scalar."""
data = np.arange(5)
result = sigma_clip(data, sigma=100., maxiters=1)
assert result.mask.shape != ()
def test_sigma_clip_class():
with NumpyRNGContext(12345):
data = np.random.randn(100)
data[10] = 1.e5
sobj = SigmaClip(sigma=1, maxiters=2)
sfunc = sigma_clip(data, sigma=1, maxiters=2)
assert_equal(sobj(data), sfunc)
def test_sigma_clip_mean():
with NumpyRNGContext(12345):
data = np.random.normal(0., 0.05, (10, 10))
data[2, 2] = 1.e5
sobj1 = SigmaClip(sigma=1, maxiters=2, cenfunc='mean')
sobj2 = SigmaClip(sigma=1, maxiters=2, cenfunc=np.nanmean)
assert_equal(sobj1(data), sobj2(data))
assert_equal(sobj1(data, axis=0), sobj2(data, axis=0))
def test_sigma_clip_invalid_cenfunc_stdfunc():
with pytest.raises(ValueError):
SigmaClip(cenfunc='invalid')
with pytest.raises(ValueError):
SigmaClip(stdfunc='invalid')
def test_sigma_clipped_stats():
"""Test list data with input mask or mask_value (#3268)."""
# test list data with mask
data = [0, 1]
mask = np.array([True, False])
result = sigma_clipped_stats(data, mask=mask)
# Check that the result of np.ma.median was converted to a scalar
assert isinstance(result[1], float)
assert result == (1., 1., 0.)
result2 = sigma_clipped_stats(data, mask=mask, axis=0)
assert_equal(result, result2)
# test list data with mask_value
result = sigma_clipped_stats(data, mask_value=0.)
assert isinstance(result[1], float)
assert result == (1., 1., 0.)
# test without mask
data = [0, 2]
result = sigma_clipped_stats(data)
assert isinstance(result[1], float)
assert result == (1., 1., 1.)
_data = np.arange(10)
data = np.ma.MaskedArray([_data, _data, 10 * _data])
mean = sigma_clip(data, axis=0, sigma=1).mean(axis=0)
assert_equal(mean, _data)
mean, median, stddev = sigma_clipped_stats(data, axis=0, sigma=1)
assert_equal(mean, _data)
assert_equal(median, _data)
assert_equal(stddev, np.zeros_like(_data))
def test_sigma_clipped_stats_ddof():
with NumpyRNGContext(12345):
data = np.random.randn(10000)
data[10] = 1.e5
mean1, median1, stddev1 = sigma_clipped_stats(data)
mean2, median2, stddev2 = sigma_clipped_stats(data, std_ddof=1)
assert mean1 == mean2
assert median1 == median2
assert_allclose(stddev1, 0.98156805711673156)
assert_allclose(stddev2, 0.98161731654802831)
def test_invalid_sigma_clip():
"""Test sigma_clip of data containing invalid values."""
data = np.ones((5, 5))
data[2, 2] = 1000
data[3, 4] = np.nan
data[1, 1] = np.inf
data_ma = np.ma.MaskedArray(data)
with pytest.warns(AstropyUserWarning,
match=r'Input data contains invalid values'):
result = sigma_clip(data)
with pytest.warns(AstropyUserWarning,
match=r'Input data contains invalid values'):
result_ma = sigma_clip(data_ma)
assert_equal(result.data, result_ma.data)
assert_equal(result.mask, result_ma.mask)
# Pre #4051 if data contains any NaN or infs sigma_clip returns the
# mask containing `False` only or TypeError if data also contains a
# masked value.
assert result.mask[2, 2]
assert result.mask[3, 4]
assert result.mask[1, 1]
with pytest.warns(AstropyUserWarning,
match=r'Input data contains invalid values'):
result2 = sigma_clip(data, axis=0)
assert result2.mask[1, 1]
assert result2.mask[3, 4]
with pytest.warns(AstropyUserWarning,
match=r'Input data contains invalid values'):
result3 = sigma_clip(data, axis=0, copy=False)
assert result3.mask[1, 1]
assert result3.mask[3, 4]
# stats along axis with all nans
data[0, :] = np.nan # row of all nans
with pytest.warns(AstropyUserWarning,
match=r'Input data contains invalid values'):
_, minarr, maxarr = sigma_clip(data, axis=1, masked=False,
return_bounds=True)
assert np.isnan(minarr[0])
assert np.isnan(maxarr[0])
def test_sigmaclip_negative_axis():
"""Test that dimensions are expanded correctly even if axis is negative."""
data = np.ones((3, 4))
# without correct expand_dims this would raise a ValueError
sigma_clip(data, axis=-1)
def test_sigmaclip_fully_masked():
"""
Make sure a fully masked array is returned when sigma clipping a
fully masked array.
"""
data = np.ma.MaskedArray(data=[[1., 0.], [0., 1.]],
mask=[[True, True], [True, True]])
clipped_data = sigma_clip(data)
assert np.ma.allequal(data, clipped_data)
clipped_data = sigma_clip(data, masked=False)
assert not isinstance(clipped_data, np.ma.MaskedArray)
assert np.all(np.isnan(clipped_data))
clipped_data, low, high = sigma_clip(data, return_bounds=True)
assert np.ma.allequal(data, clipped_data)
assert np.isnan(low)
assert np.isnan(high)
def test_sigmaclip_empty_masked():
"""
Make sure an empty masked array is returned when sigma clipping an
empty masked array.
"""
data = np.ma.MaskedArray(data=[], mask=[])
clipped_data = sigma_clip(data)
assert np.ma.allequal(data, clipped_data)
clipped_data, low, high = sigma_clip(data, return_bounds=True)
assert np.ma.allequal(data, clipped_data)
assert np.isnan(low)
assert np.isnan(high)
def test_sigmaclip_empty():
"""
Make sure an empty array is returned when sigma clipping an empty
array.
"""
data = np.array([])
clipped_data = sigma_clip(data)
assert isinstance(clipped_data, np.ma.MaskedArray)
assert_equal(data, clipped_data.data)
clipped_data, low, high = sigma_clip(data, return_bounds=True)
assert_equal(data, clipped_data)
assert np.isnan(low)
assert np.isnan(high)
def test_sigma_clip_axis_tuple_3D():
"""Test sigma clipping over a subset of axes (issue #7227).
"""
data = np.sin(0.78 * np.arange(27)).reshape(3, 3, 3)
mask = np.zeros_like(data, dtype=np.bool_)
data_t = np.rollaxis(data, 1, 0)
mask_t = np.rollaxis(mask, 1, 0)
# Loop over what was originally axis 1 and clip each plane directly:
for data_plane, mask_plane in zip(data_t, mask_t):
mean = data_plane.mean()
maxdev = 1.5 * data_plane.std()
mask_plane[:] = np.logical_or(data_plane < mean - maxdev,
data_plane > mean + maxdev)
# Do the equivalent thing using sigma_clip:
result = sigma_clip(data, sigma=1.5, cenfunc=np.mean, maxiters=1,
axis=(0, -1))
assert_equal(result.mask, mask)
def test_sigmaclip_repr():
sigclip = SigmaClip()
sigclip_repr = ("SigmaClip(sigma=3.0, sigma_lower=3.0, sigma_upper=3.0,"
" maxiters=5, cenfunc='median', stdfunc='std', "
"grow=False)")
sigclip_str = ("<SigmaClip>\n sigma: 3.0\n sigma_lower: 3.0\n"
" sigma_upper: 3.0\n maxiters: 5\n"
" cenfunc: 'median'\n stdfunc: 'std'\n"
" grow: False")
assert repr(sigclip) == sigclip_repr
assert str(sigclip) == sigclip_str
def test_sigma_clippped_stats_unit():
data = np.array([1, 1]) * u.kpc
result = sigma_clipped_stats(data)
assert result == (1. * u.kpc, 1. * u.kpc, 0. * u.kpc)
def test_sigma_clippped_stats_all_masked():
"""
Test sigma_clipped_stats when the input array is completely masked.
"""
arr = np.ma.MaskedArray(np.arange(10), mask=True)
result = sigma_clipped_stats(arr)
assert result == (np.ma.masked, np.ma.masked, np.ma.masked)
arr = np.ma.MaskedArray(np.zeros(10), mask=False)
result = sigma_clipped_stats(arr, mask_value=0.)
assert result == (np.ma.masked, np.ma.masked, np.ma.masked)
arr = np.ma.MaskedArray(np.arange(10), mask=False)
mask = arr < 20
result = sigma_clipped_stats(arr, mask=mask)
assert result == (np.ma.masked, np.ma.masked, np.ma.masked)
def test_sigma_clip_masked_data_values():
"""
Test that the data values & type returned by sigma_clip are the same as
its input when using masked=True (rather than being upcast to float64 &
containing NaNs as in issue #10605) and also that the input data get
copied or referenced as appropriate.
"""
data = np.array([-2, 5, -5, -6, 20, 14, 1])
result = sigma_clip(data, sigma=1.5, maxiters=3, axis=None, masked=True,
copy=True)
assert result.dtype == data.dtype
assert_equal(result.data, data)
assert not np.shares_memory(result.data, data)
result = sigma_clip(data, sigma=1.5, maxiters=3, axis=None, masked=True,
copy=False)
assert result.dtype == data.dtype
assert_equal(result.data, data)
assert np.shares_memory(result.data, data)
# (The fact that the arrays share memory probably also means they're the
# same, but doesn't strictly prove it, eg. one could be reversed.)
result = sigma_clip(data, sigma=1.5, maxiters=3, axis=0, masked=True,
copy=True)
assert result.dtype == data.dtype
assert_equal(result.data, data)
assert not np.shares_memory(result.data, data)
result = sigma_clip(data, sigma=1.5, maxiters=3, axis=0, masked=True,
copy=False)
assert result.dtype == data.dtype
assert_equal(result.data, data)
assert np.shares_memory(result.data, data)
@pytest.mark.skipif('not HAS_SCIPY')
def test_sigma_clip_grow():
"""
Test sigma_clip with growth of masking to include the neighbours within a
specified radius of deviant values.
"""
# We could use a random seed here, but enumerating the data guarantees that
# we test sigma_clip itself and not random number generation.
data = np.array(
[-0.2 , 0.48, -0.52, -0.56, 1.97, 1.39, 0.09, 0.28, 0.77, 1.25,
1.01, -1.3 , 0.27, 0.23, 1.35, 0.89, -2. , -0.37, 1.67, -0.44,
-0.54, 0.48, 3.25, -1.02, -0.58, 0.12, 0.3 , 0.52, 0. , 1.34,
-0.71, -0.83, -2.37, -1.86, -0.86, 0.56, -1.27, 0.12, -1.06, 0.33,
-2.36, -0.2 , -1.54, -0.97, -1.31, 0.29, 0.38, -0.75, 0.33, 1.35,
0.07, 0.25, -0.01, 1. , 1.33, -0.92, -1.55, 0.02, 0.76, -0.66,
0.86, -0.01, 0.05, 0.67, 0.85, -0.96, -0.02, -2.3 , -0.65, -1.22,
-1.33, 1.07, 0.72, 0.69, 1. , -0.5 , -0.62, -0.92, -0.73, 0.22,
0.05, -1.16, 0.82, 0.43, 1.01, 1.82, -1. , 0.85, -0.13, 0.91,
0.19, 2.17, -0.11, 2. , 0.03, 0.8 , 0.12, -0.75, 0.58, 0.15]
)
# Test growth to immediate neighbours in simple 1D case:
filtered_data = sigma_clip(data, sigma=2, maxiters=3, grow=1)
# Indices of the 26/100 points expected to be masked:
expected = np.array([3, 4, 5, 15, 16, 17, 21, 22, 23, 31, 32, 33, 39, 40,
41, 66, 67, 68, 84, 85, 86, 90, 91, 92, 93, 94])
assert np.array_equal(np.where(filtered_data.mask)[0], expected)
# Test block growth in 2 of 3 dimensions (as in a 2D model set):
data = data.reshape(4, 5, 5)
filtered_data = sigma_clip(data, sigma=2.1, maxiters=1, grow=1.5,
axis=(1, 2))
expected = np.array(
[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[3, 3, 3, 4, 4, 4, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4,
2, 2, 2, 3, 3, 3, 4, 4, 4, 2, 2, 2, 3, 3, 3, 4, 4, 4],
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 0, 1, 2, 3, 0, 1, 0, 1,
1, 2, 3, 1, 2, 3, 1, 2, 3, 0, 1, 2, 0, 1, 2, 0, 1, 2]]
)
assert np.array_equal(np.where(filtered_data.mask), expected)
# Test ~spherical growth (of a single very-deviant point) in 3D data:
data[1, 2, 2] = 100.
filtered_data = sigma_clip(data, sigma=3., maxiters=1, grow=2.)
expected = np.array(
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3],
[1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 1,
1, 1, 2, 2, 2, 3, 3, 3, 2],
[1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 2, 1,
2, 3, 1, 2, 3, 1, 2, 3, 2]]
)
assert np.array_equal(np.where(filtered_data.mask), expected)
@pytest.mark.parametrize(('axis', 'bounds_shape'), [(0, (4, 5, 6, 7)),
(1, (3, 5, 6, 7)),
(-1, (3, 4, 5, 6)),
((1, 3), (3, 5, 7)),
((3, 1), (3, 5, 7)),
((1, 2, 4), (3, 6))])
def test_sigma_clip_axis_shapes(axis, bounds_shape):
# Check the shapes of the output for different use cases
with NumpyRNGContext(12345):
array = np.random.random((3, 4, 5, 6, 7))
result1 = sigma_clip(array, axis=axis)
assert result1.shape == array.shape
result2, bound1, bound2 = sigma_clip(array, axis=axis, return_bounds=True)
assert result2.shape == array.shape
assert bound1.shape == bounds_shape
assert bound2.shape == bounds_shape
@pytest.mark.parametrize('dtype', ['>f2', '<f2', '>f4', '<f4', '>f8', '<f8', '<i4', '>i8'])
def test_sigma_clip_dtypes(dtype):
# Check the shapes of the output for different use cases
with NumpyRNGContext(12345):
array = np.random.randint(-5, 5, 1000).astype(float)
array[30] = 100
reference = sigma_clip(array, copy=True, masked=False)
actual = sigma_clip(array.astype(dtype), copy=True, masked=False)
assert_equal(reference, actual)
def test_mad_std():
# Check with a small array where we know how the result should differ from std
# Choose an array with few elements and a high proportion of outliers since
# in this case std and mad_std will be very different.
array = np.array([1, 10000, 4, 3, 10000])
# First check with regular std, which shouldn't remove any values
result_std = sigma_clip(array, cenfunc='median', stdfunc='std',
maxiters=1, sigma=5, masked=False)
assert_equal(result_std, array)
# Whereas using mad_std should result in the high values being removed
result_mad_std = sigma_clip(array, cenfunc='median', stdfunc='mad_std',
maxiters=1, sigma=5, masked=False)
assert_equal(result_mad_std, [1, 4, 3])
# We now check this again but with the axis= keyword set since at the time
# of writing this test this relies on a fast C implementation in which we
# have re-inplemented mad_std.
result_std = sigma_clip(array, cenfunc='median', stdfunc='std',
maxiters=1, sigma=5, masked=False, axis=0)
assert_equal(result_std, array)
result_mad_std = sigma_clip(array, cenfunc='median', stdfunc='mad_std',
maxiters=1, sigma=5, masked=False, axis=0)
assert_equal(result_mad_std, [1, np.nan, 4, 3, np.nan])
def test_mad_std_large():
# And now test with a larger array and compare with Python mad_std function
with NumpyRNGContext(12345):
array = np.random.uniform(-1, 2, (30, 40))
def nan_mad_std(data, axis=None):
return mad_std(data, axis=axis, ignore_nan=True)
result1 = sigma_clip(array, sigma=2, maxiters=None,
stdfunc=nan_mad_std, axis=0, masked=False)
result2 = sigma_clip(array, sigma=2, maxiters=None,
stdfunc='mad_std', axis=0, masked=False)
assert_allclose(result1, result2)
|
41213e9cd2f22587c3bf27b492db0abc3895a3a558f1270cca8754005db02dae |
from numpy.testing import assert_allclose
from astropy.stats.info_theory import bayesian_info_criterion, bayesian_info_criterion_lsq
from astropy.stats.info_theory import akaike_info_criterion, akaike_info_criterion_lsq
def test_bayesian_info_criterion():
# This test is from an example presented in Ref [1]
lnL = (-176.4, -173.0)
n_params = (2, 3)
n_samples = 100
answer = 2.195
bic_g = bayesian_info_criterion(lnL[0], n_params[0], n_samples)
bic_t = bayesian_info_criterion(lnL[1], n_params[1], n_samples)
assert_allclose(answer, bic_g - bic_t, atol=1e-1)
def test_akaike_info_criterion():
# This test is from an example presented in Ref [2]
n_samples = 121
lnL = (-3.54, -4.17)
n_params = (6, 5)
answer = 0.95
aic_1 = akaike_info_criterion(lnL[0], n_params[0], n_samples)
aic_2 = akaike_info_criterion(lnL[1], n_params[1], n_samples)
assert_allclose(answer, aic_1 - aic_2, atol=1e-2)
def test_akaike_info_criterion_lsq():
# This test is from an example presented in Ref [1]
n_samples = 100
n_params = (4, 3, 3)
ssr = (25.0, 26.0, 27.0)
answer = (-130.21, -128.46, -124.68)
assert_allclose(answer[0],
akaike_info_criterion_lsq(ssr[0], n_params[0], n_samples),
atol=1e-2)
assert_allclose(answer[1],
akaike_info_criterion_lsq(ssr[1], n_params[1], n_samples),
atol=1e-2)
assert_allclose(answer[2],
akaike_info_criterion_lsq(ssr[2], n_params[2], n_samples),
atol=1e-2)
def test_bayesian_info_criterion_lsq():
"""This test is from:
http://www.statoek.wiso.uni-goettingen.de/veranstaltungen/non_semi_models/
AkaikeLsg.pdf
Note that in there, they compute a "normalized BIC". Therefore, the
answers presented here are recalculated versions based on their values.
"""
n_samples = 25
n_params = (1, 2, 1)
ssr = (48959, 32512, 37980)
answer = (192.706, 185.706, 186.360)
assert_allclose(answer[0], bayesian_info_criterion_lsq(ssr[0],
n_params[0],
n_samples),
atol=1e-2)
assert_allclose(answer[1], bayesian_info_criterion_lsq(ssr[1],
n_params[1],
n_samples),
atol=1e-2)
assert_allclose(answer[2], bayesian_info_criterion_lsq(ssr[2],
n_params[2],
n_samples),
atol=1e-2)
|
8b0b2c4401fc4fae30ee0fd4cf71caf5c25592ac5957fbd100472aac62f400c0 |
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from astropy import units as u
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
from astropy.stats.circstats import _length, circmean, circvar, circmoment, circcorrcoef
from astropy.stats.circstats import rayleightest, vtest, vonmisesmle
def test__length():
# testing against R CircStats package
# Ref. [1] pages 6 and 125
weights = np.array([12, 1, 6, 1, 2, 1, 1])
answer = 0.766282
data = np.array([0, 3.6, 36, 72, 108, 169.2, 324])*u.deg
assert_allclose(answer, _length(data, weights=weights), atol=1e-4)
def test_circmean():
# testing against R CircStats package
# Ref[1], page 23
data = np.array([51, 67, 40, 109, 31, 358])*u.deg
answer = 48.63*u.deg
assert_equal(answer, np.around(circmean(data), 2))
@pytest.mark.skipif('not HAS_SCIPY')
def test_circmean_against_scipy():
import scipy.stats
# testing against scipy.stats.circmean function
# the data is the same as the test before, but in radians
data = np.array([0.89011792, 1.1693706, 0.6981317, 1.90240888, 0.54105207,
6.24827872])
answer = scipy.stats.circmean(data)
assert_equal(np.around(answer, 2), np.around(circmean(data), 2))
def test_circvar():
# testing against R CircStats package
# Ref[1], page 23
data = np.array([51, 67, 40, 109, 31, 358])*u.deg
answer = 0.1635635
assert_allclose(answer, circvar(data), atol=1e-4)
def test_circmoment():
# testing against R CircStats package
# Ref[1], page 23
data = np.array([51, 67, 40, 109, 31, 358])*u.deg
# 2nd, 3rd, and 4th moments
# this is the answer given in Ref[1] in radians
answer = np.array([1.588121, 1.963919, 2.685556])
answer = np.around(np.rad2deg(answer)*u.deg, 4)
result = (np.around(circmoment(data, p=2)[0], 4),
np.around(circmoment(data, p=3)[0], 4),
np.around(circmoment(data, p=4)[0], 4))
assert_equal(answer[0], result[0])
assert_equal(answer[1], result[1])
assert_equal(answer[2], result[2])
# testing lengths
answer = np.array([0.4800428, 0.236541, 0.2255761])
assert_allclose(answer, (circmoment(data, p=2)[1],
circmoment(data, p=3)[1],
circmoment(data, p=4)[1]), atol=1e-4)
def test_circcorrcoef():
# testing against R CircStats package
# Ref[1], page 180
alpha = np.array([356, 97, 211, 232, 343, 292, 157, 302, 335, 302, 324,
85, 324, 340, 157, 238, 254, 146, 232, 122, 329])*u.deg
beta = np.array([119, 162, 221, 259, 270, 29, 97, 292, 40, 313, 94, 45,
47, 108, 221, 270, 119, 248, 270, 45, 23])*u.deg
answer = 0.2704648
assert_allclose(answer, circcorrcoef(alpha, beta), atol=1e-4)
def test_rayleightest():
# testing against R CircStats package
data = np.array([190.18, 175.48, 155.95, 217.83, 156.36])*u.deg
# answer was obtained through R CircStats function r.test(x)
answer = (0.00640418, 0.9202565)
result = (rayleightest(data), _length(data))
assert_allclose(answer[0], result[0], atol=1e-4)
assert_allclose(answer[1], result[1], atol=1e-4)
@pytest.mark.skipif('not HAS_SCIPY')
def test_vtest():
# testing against R CircStats package
data = np.array([190.18, 175.48, 155.95, 217.83, 156.36])*u.deg
# answer was obtained through R CircStats function v0.test(x)
answer = 0.9994725
assert_allclose(answer, vtest(data), atol=1e-5)
def test_vonmisesmle():
# testing against R CircStats package
# testing non-Quantity
data = np.array([3.3699057, 4.0411630, 0.5014477, 2.6223103, 3.7336524,
1.8136389, 4.1566039, 2.7806317, 2.4672173,
2.8493644])
# answer was obtained through R CircStats function vm.ml(x)
answer = (3.006514, 1.474132)
assert_allclose(answer[0], vonmisesmle(data)[0], atol=1e-5)
assert_allclose(answer[1], vonmisesmle(data)[1], atol=1e-5)
# testing with Quantity
data = np.rad2deg(data)*u.deg
answer = np.rad2deg(3.006514)*u.deg
assert_equal(np.around(answer, 3), np.around(vonmisesmle(data)[0], 3))
|
56d1cb02a9ae285bbf1fecd1d170cfed6deaf54e5b5f9054681de948222968ee |
import numpy as np
import pytest
from numpy.testing import assert_allclose
from astropy.stats.spatial import RipleysKEstimator
from astropy.utils.misc import NumpyRNGContext
a = np.array([[1, 4], [2, 5], [3, 6]])
b = np.array([[-1, 1], [-2, 2], [-3, 3]])
@pytest.mark.parametrize("points, x_min, x_max", [(a, 0, 10), (b, -5, 5)])
def test_ripley_K_implementation(points, x_min, x_max):
"""
Test against Ripley's K function implemented in R package `spatstat`
+-+---------+---------+----------+---------+-+
6 + * +
| |
| |
5.5 + +
| |
| |
5 + * +
| |
4.5 + +
| |
| |
4 + * +
+-+---------+---------+----------+---------+-+
1 1.5 2 2.5 3
+-+---------+---------+----------+---------+-+
3 + * +
| |
| |
2.5 + +
| |
| |
2 + * +
| |
1.5 + +
| |
| |
1 + * +
+-+---------+---------+----------+---------+-+
-3 -2.5 -2 -1.5 -1
"""
area = 100
r = np.linspace(0, 2.5, 5)
Kest = RipleysKEstimator(area=area, x_min=x_min, y_min=x_min, x_max=x_max,
y_max=x_max)
ANS_NONE = np.array([0, 0, 0, 66.667, 66.667])
assert_allclose(ANS_NONE, Kest(data=points, radii=r, mode='none'),
atol=1e-3)
ANS_TRANS = np.array([0, 0, 0, 82.304, 82.304])
assert_allclose(ANS_TRANS, Kest(data=points, radii=r, mode='translation'),
atol=1e-3)
with NumpyRNGContext(123):
a = np.random.uniform(low=5, high=10, size=(100, 2))
b = np.random.uniform(low=-5, high=-10, size=(100, 2))
@pytest.mark.parametrize("points", [a, b])
def test_ripley_uniform_property(points):
# Ripley's K function without edge-correction converges to the area when
# the number of points and the argument radii are large enough, i.e.,
# K(x) --> area as x --> inf
area = 50
Kest = RipleysKEstimator(area=area)
r = np.linspace(0, 20, 5)
assert_allclose(area, Kest(data=points, radii=r, mode='none')[4])
with NumpyRNGContext(123):
a = np.random.uniform(low=0, high=1, size=(500, 2))
b = np.random.uniform(low=-1, high=0, size=(500, 2))
@pytest.mark.parametrize("points, low, high", [(a, 0, 1), (b, -1, 0)])
def test_ripley_large_density(points, low, high):
Kest = RipleysKEstimator(area=1, x_min=low, x_max=high, y_min=low,
y_max=high)
r = np.linspace(0, 0.25, 25)
Kpos = Kest.poisson(r)
modes = ['ohser', 'translation', 'ripley']
for m in modes:
Kest_r = Kest(data=points, radii=r, mode=m)
assert_allclose(Kpos, Kest_r, atol=1e-1)
with NumpyRNGContext(123):
a = np.random.uniform(low=5, high=10, size=(500, 2))
b = np.random.uniform(low=-10, high=-5, size=(500, 2))
@pytest.mark.parametrize("points, low, high", [(a, 5, 10), (b, -10, -5)])
def test_ripley_modes(points, low, high):
Kest = RipleysKEstimator(area=25, x_max=high, y_max=high, x_min=low,
y_min=low)
r = np.linspace(0, 1.2, 25)
Kpos_mean = np.mean(Kest.poisson(r))
modes = ['ohser', 'translation', 'ripley']
for m in modes:
Kest_mean = np.mean(Kest(data=points, radii=r, mode=m))
assert_allclose(Kpos_mean, Kest_mean, atol=1e-1, rtol=1e-1)
with NumpyRNGContext(123):
a = np.random.uniform(low=0, high=1, size=(50, 2))
b = np.random.uniform(low=-1, high=0, size=(50, 2))
@pytest.mark.parametrize("points, low, high", [(a, 0, 1), (b, -1, 0)])
def test_ripley_large_density_var_width(points, low, high):
Kest = RipleysKEstimator(area=1, x_min=low, x_max=high, y_min=low,
y_max=high)
r = np.linspace(0, 0.25, 25)
Kpos = Kest.poisson(r)
Kest_r = Kest(data=points, radii=r, mode='var-width')
assert_allclose(Kpos, Kest_r, atol=1e-1)
with NumpyRNGContext(123):
a = np.random.uniform(low=5, high=10, size=(50, 2))
b = np.random.uniform(low=-10, high=-5, size=(50, 2))
@pytest.mark.parametrize("points, low, high", [(a, 5, 10), (b, -10, -5)])
def test_ripley_var_width(points, low, high):
Kest = RipleysKEstimator(area=25, x_max=high, y_max=high, x_min=low,
y_min=low)
r = np.linspace(0, 1.2, 25)
Kest_ohser = np.mean(Kest(data=points, radii=r, mode='ohser'))
Kest_var_width = np.mean(Kest(data=points, radii=r, mode='var-width'))
assert_allclose(Kest_ohser, Kest_var_width, atol=1e-1, rtol=1e-1)
|
9937fbc01eaaca89a3907899100c4a19fb12ce6fb50217087aef94400afb12a5 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy.stats import bayesian_blocks, RegularEvents
def test_single_change_point(rseed=0):
rng = np.random.default_rng(rseed)
x = np.concatenate([rng.random(100),
1 + rng.random(200)])
bins = bayesian_blocks(x)
assert (len(bins) == 3)
assert_allclose(bins[1], 0.927289, rtol=0.02)
def test_duplicate_events(rseed=0):
rng = np.random.default_rng(rseed)
t = rng.random(100)
t[80:] = t[:20]
# Using int array as a regression test for gh-6877
x = np.ones(t.shape, dtype=int)
x[:20] += 1
bins1 = bayesian_blocks(t)
bins2 = bayesian_blocks(t[:80], x[:80])
assert_allclose(bins1, bins2)
def test_measures_fitness_homoscedastic(rseed=0):
rng = np.random.default_rng(rseed)
t = np.linspace(0, 1, 11)
x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2)
sigma = 0.05
x = x + sigma * rng.standard_normal(len(x))
bins = bayesian_blocks(t, x, sigma, fitness='measures')
assert_allclose(bins, [0, 0.45, 0.55, 1])
def test_measures_fitness_heteroscedastic():
rng = np.random.default_rng(1)
t = np.linspace(0, 1, 11)
x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2)
sigma = 0.02 + 0.02 * rng.random(len(x))
x = x + sigma * rng.standard_normal(len(x))
bins = bayesian_blocks(t, x, sigma, fitness='measures')
assert_allclose(bins, [0, 0.45, 0.55, 1])
def test_regular_events():
rng = np.random.default_rng(1234)
dt = 0.01
steps = np.concatenate([np.unique(rng.integers(0, 500, 100)),
np.unique(rng.integers(500, 1000, 200))])
t = dt * steps
# string fitness
bins1 = bayesian_blocks(t, fitness='regular_events', dt=dt)
assert (len(bins1) == 3)
assert_allclose(bins1[1], 5, rtol=0.05)
# class name fitness
bins2 = bayesian_blocks(t, fitness=RegularEvents, dt=dt)
assert_allclose(bins1, bins2)
# class instance fitness
bins3 = bayesian_blocks(t, fitness=RegularEvents(dt=dt))
assert_allclose(bins1, bins3)
def test_errors():
rng = np.random.default_rng(0)
t = rng.random(100)
# x must be integer or None for events
with pytest.raises(ValueError):
bayesian_blocks(t, fitness='events', x=t)
# x must be binary for regular events
with pytest.raises(ValueError):
bayesian_blocks(t, fitness='regular_events', x=10 * t, dt=1)
# x must be specified for measures
with pytest.raises(ValueError):
bayesian_blocks(t, fitness='measures')
# sigma cannot be specified without x
with pytest.raises(ValueError):
bayesian_blocks(t, fitness='events', sigma=0.5)
# length of x must match length of t
with pytest.raises(ValueError):
bayesian_blocks(t, fitness='measures', x=t[:-1])
# repeated values in t fail when x is specified
t2 = t.copy()
t2[1] = t2[0]
with pytest.raises(ValueError):
bayesian_blocks(t2, fitness='measures', x=t)
# sigma must be broadcastable with x
with pytest.raises(ValueError):
bayesian_blocks(t, fitness='measures', x=t, sigma=t[:-1])
def test_fitness_function_results():
"""Test results for several fitness functions"""
rng = np.random.default_rng(42)
# Event Data
t = rng.standard_normal(100)
edges = bayesian_blocks(t, fitness='events')
assert_allclose(edges, [-1.95103519, -1.01861547, 0.95442154, 2.1416476])
# Event data with repeats
t[80:] = t[:20]
edges = bayesian_blocks(t, fitness='events', p0=0.01)
assert_allclose(edges, [-1.95103519, -1.08663566, 1.17575682, 2.1416476])
# Regular event data
dt = 0.01
t = dt * np.arange(1000)
x = np.zeros(len(t))
N = len(t) // 10
x[rng.integers(0, len(t), N)] = 1
x[rng.integers(0, len(t) // 2, N)] = 1
edges = bayesian_blocks(t, x, fitness='regular_events', dt=dt)
assert_allclose(edges, [0, 4.365, 4.995, 9.99])
# Measured point data with errors
t = 100 * rng.random(20)
x = np.exp(-0.5 * (t - 50) ** 2)
sigma = 0.1
x_obs = x + sigma * rng.standard_normal(len(x))
edges = bayesian_blocks(t, x_obs, sigma, fitness='measures')
expected = [1.39362877, 44.30811196, 49.46626158, 54.37232704, 92.7562551]
assert_allclose(edges, expected)
# Optional arguments are passed (p0)
p0_sel = 0.05
edges = bayesian_blocks(t, x_obs, sigma, fitness='measures', p0=p0_sel)
assert_allclose(edges, expected)
# Optional arguments are passed (ncp_prior)
ncp_prior_sel = 4 - np.log(73.53 * p0_sel * (len(t) ** -0.478))
edges = bayesian_blocks(t, x_obs, sigma, fitness='measures',
ncp_prior=ncp_prior_sel)
assert_allclose(edges, expected)
# Optional arguments are passed (gamma)
gamma_sel = np.exp(-ncp_prior_sel)
edges = bayesian_blocks(t, x_obs, sigma, fitness='measures',
gamma=gamma_sel)
assert_allclose(edges, expected)
def test_zero_change_points(rseed=0):
"""
Ensure that edges contains both endpoints when there are no change points
"""
np.random.seed(rseed)
# Using the failed edge case from
# https://github.com/astropy/astropy/issues/8558
values = np.array([1, 1, 1, 1, 1, 1, 1, 1, 2])
bins = bayesian_blocks(values)
assert values.min() == bins[0]
assert values.max() == bins[-1]
|
5dfeb4887e8fd6d64bd4edba9f58a07fa6695d0c40528cac55d1ffce67e11365 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from astropy.utils.compat.optional_deps import HAS_SCIPY, HAS_MPMATH # noqa
from astropy.stats import funcs
from astropy import units as u
from astropy.utils.misc import NumpyRNGContext
def test_median_absolute_deviation():
with NumpyRNGContext(12345):
# test that it runs
randvar = np.random.randn(10000)
mad = funcs.median_absolute_deviation(randvar)
# test whether an array is returned if an axis is used
randvar = randvar.reshape((10, 1000))
mad = funcs.median_absolute_deviation(randvar, axis=1)
assert len(mad) == 10
assert mad.size < randvar.size
mad = funcs.median_absolute_deviation(randvar, axis=0)
assert len(mad) == 1000
assert mad.size < randvar.size
# Test some actual values in a 3 dimensional array
x = np.arange(3 * 4 * 5)
a = np.array([sum(x[:i + 1]) for i in range(len(x))]).reshape(3, 4, 5)
mad = funcs.median_absolute_deviation(a)
assert mad == 389.5
mad = funcs.median_absolute_deviation(a, axis=0)
assert_allclose(mad, [[210., 230., 250., 270., 290.],
[310., 330., 350., 370., 390.],
[410., 430., 450., 470., 490.],
[510., 530., 550., 570., 590.]])
mad = funcs.median_absolute_deviation(a, axis=1)
assert_allclose(mad, [[27.5, 32.5, 37.5, 42.5, 47.5],
[127.5, 132.5, 137.5, 142.5, 147.5],
[227.5, 232.5, 237.5, 242.5, 247.5]])
mad = funcs.median_absolute_deviation(a, axis=2)
assert_allclose(mad, [[3., 8., 13., 18.],
[23., 28., 33., 38.],
[43., 48., 53., 58.]])
def test_median_absolute_deviation_masked():
# Based on the changes introduces in #4658
# normal masked arrays without masked values are handled like normal
# numpy arrays
array = np.ma.array([1, 2, 3])
assert funcs.median_absolute_deviation(array) == 1
# masked numpy arrays return something different (rank 0 masked array)
# but one can still compare it without np.all!
array = np.ma.array([1, 4, 3], mask=[0, 1, 0])
assert funcs.median_absolute_deviation(array) == 1
# Just cross check if that's identical to the function on the unmasked
# values only
assert funcs.median_absolute_deviation(array) == (
funcs.median_absolute_deviation(array[~array.mask]))
# Multidimensional masked array
array = np.ma.array([[1, 4], [2, 2]], mask=[[1, 0], [0, 0]])
funcs.median_absolute_deviation(array)
assert funcs.median_absolute_deviation(array) == 0
# Just to compare it with the data without mask:
assert funcs.median_absolute_deviation(array.data) == 0.5
# And check if they are also broadcasted correctly
np.testing.assert_array_equal(
funcs.median_absolute_deviation(array, axis=0).data, [0, 1])
np.testing.assert_array_equal(
funcs.median_absolute_deviation(array, axis=1).data, [0, 0])
def test_median_absolute_deviation_nans():
array = np.array([[1, 4, 3, np.nan],
[2, 5, np.nan, 4]])
assert_equal(funcs.median_absolute_deviation(array, func=np.nanmedian,
axis=1), [1, 1])
array = np.ma.masked_invalid(array)
assert funcs.median_absolute_deviation(array) == 1
def test_median_absolute_deviation_nans_masked():
"""
Regression test to ensure ignore_nan=True gives same results for
ndarray and masked arrays that contain +/-inf.
"""
data1 = np.array([1., np.nan, 2, np.inf])
data2 = np.ma.masked_array(data1, mask=False)
mad1 = funcs.median_absolute_deviation(data1, ignore_nan=True)
mad2 = funcs.median_absolute_deviation(data2, ignore_nan=True)
assert_equal(mad1, mad2)
# ensure that input masked array is not modified
assert np.isnan(data2[1])
def test_median_absolute_deviation_multidim_axis():
array = np.ones((5, 4, 3)) * np.arange(5)[:, np.newaxis, np.newaxis]
mad1 = funcs.median_absolute_deviation(array, axis=(1, 2))
mad2 = funcs.median_absolute_deviation(array, axis=(2, 1))
assert_equal(mad1, np.zeros(5))
assert_equal(mad1, mad2)
def test_median_absolute_deviation_quantity():
# Based on the changes introduces in #4658
# Just a small test that this function accepts Quantities and returns a
# quantity
a = np.array([1, 16, 5]) * u.m
mad = funcs.median_absolute_deviation(a)
# Check for the correct unit and that the result is identical to the
# result without units.
assert mad.unit == a.unit
assert mad.value == funcs.median_absolute_deviation(a.value)
@pytest.mark.skipif('not HAS_SCIPY')
def test_binom_conf_interval():
# Test Wilson and Jeffreys interval for corner cases:
# Corner cases: k = 0, k = n, confidence_level = 0., confidence_level = 1.
n = 5
k = [0, 4, 5]
for conf in [0., 0.5, 1.]:
res = funcs.binom_conf_interval(k, n, confidence_level=conf, interval='wilson')
assert ((res >= 0.) & (res <= 1.)).all()
res = funcs.binom_conf_interval(k, n, confidence_level=conf, interval='jeffreys')
assert ((res >= 0.) & (res <= 1.)).all()
# Test Jeffreys interval accuracy against table in Brown et al. (2001).
# (See `binom_conf_interval` docstring for reference.)
k = [0, 1, 2, 3, 4]
n = 7
conf = 0.95
result = funcs.binom_conf_interval(k, n, confidence_level=conf, interval='jeffreys')
table = np.array([[0.000, 0.016, 0.065, 0.139, 0.234],
[0.292, 0.501, 0.648, 0.766, 0.861]])
assert_allclose(result, table, atol=1.e-3, rtol=0.)
# Test scalar version
result = np.array([funcs.binom_conf_interval(kval, n, confidence_level=conf,
interval='jeffreys')
for kval in k]).transpose()
assert_allclose(result, table, atol=1.e-3, rtol=0.)
# Test flat
result = funcs.binom_conf_interval(k, n, confidence_level=conf, interval='flat')
table = np.array([[0., 0.03185, 0.08523, 0.15701, 0.24486],
[0.36941, 0.52650, 0.65085, 0.75513, 0.84298]])
assert_allclose(result, table, atol=1.e-3, rtol=0.)
# Test Wald interval
result = funcs.binom_conf_interval(0, 5, interval='wald')
assert_allclose(result, 0.) # conf interval is [0, 0] when k = 0
result = funcs.binom_conf_interval(5, 5, interval='wald')
assert_allclose(result, 1.) # conf interval is [1, 1] when k = n
result = funcs.binom_conf_interval(500, 1000, confidence_level=0.68269,
interval='wald')
assert_allclose(result[0], 0.5 - 0.5 / np.sqrt(1000.))
assert_allclose(result[1], 0.5 + 0.5 / np.sqrt(1000.))
# Test shapes
k = 3
n = 7
for interval in ['wald', 'wilson', 'jeffreys', 'flat']:
result = funcs.binom_conf_interval(k, n, interval=interval)
assert result.shape == (2,)
k = np.array(k)
for interval in ['wald', 'wilson', 'jeffreys', 'flat']:
result = funcs.binom_conf_interval(k, n, interval=interval)
assert result.shape == (2,)
n = np.array(n)
for interval in ['wald', 'wilson', 'jeffreys', 'flat']:
result = funcs.binom_conf_interval(k, n, interval=interval)
assert result.shape == (2,)
k = np.array([1, 3, 5])
for interval in ['wald', 'wilson', 'jeffreys', 'flat']:
result = funcs.binom_conf_interval(k, n, interval=interval)
assert result.shape == (2, 3)
n = np.array([5, 5, 5])
for interval in ['wald', 'wilson', 'jeffreys', 'flat']:
result = funcs.binom_conf_interval(k, n, interval=interval)
assert result.shape == (2, 3)
@pytest.mark.skipif('not HAS_SCIPY')
def test_binned_binom_proportion():
# Check that it works.
nbins = 20
x = np.linspace(0., 10., 100) # Guarantee an `x` in every bin.
success = np.ones(len(x), dtype=bool)
bin_ctr, bin_hw, p, perr = funcs.binned_binom_proportion(x, success,
bins=nbins)
# Check shape of outputs
assert bin_ctr.shape == (nbins,)
assert bin_hw.shape == (nbins,)
assert p.shape == (nbins,)
assert perr.shape == (2, nbins)
# Check that p is 1 in all bins, since success = True for all `x`.
assert (p == 1.).all()
# Check that p is 0 in all bins if success = False for all `x`.
success[:] = False
bin_ctr, bin_hw, p, perr = funcs.binned_binom_proportion(x, success,
bins=nbins)
assert (p == 0.).all()
def test_binned_binom_proportion_exception():
with pytest.raises(ValueError):
funcs.binned_binom_proportion([0], [1, 2], confidence_level=0.75)
def test_signal_to_noise_oir_ccd():
result = funcs.signal_to_noise_oir_ccd(1, 25, 0, 0, 0, 1)
assert 5.0 == result
# check to make sure gain works
result = funcs.signal_to_noise_oir_ccd(1, 5, 0, 0, 0, 1, 5)
assert 5.0 == result
# now add in sky, dark current, and read noise
# make sure the snr goes down
result = funcs.signal_to_noise_oir_ccd(1, 25, 1, 0, 0, 1)
assert result < 5.0
result = funcs.signal_to_noise_oir_ccd(1, 25, 0, 1, 0, 1)
assert result < 5.0
result = funcs.signal_to_noise_oir_ccd(1, 25, 0, 0, 1, 1)
assert result < 5.0
# make sure snr increases with time
result = funcs.signal_to_noise_oir_ccd(2, 25, 0, 0, 0, 1)
assert result > 5.0
def test_bootstrap():
bootarr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
# test general bootstrapping
answer = np.array([[7, 4, 8, 5, 7, 0, 3, 7, 8, 5],
[4, 8, 8, 3, 6, 5, 2, 8, 6, 2]])
with NumpyRNGContext(42):
assert_equal(answer, funcs.bootstrap(bootarr, 2))
# test with a bootfunction
with NumpyRNGContext(42):
bootresult = np.mean(funcs.bootstrap(bootarr, 10000, bootfunc=np.mean))
assert_allclose(np.mean(bootarr), bootresult, atol=0.01)
@pytest.mark.skipif('not HAS_SCIPY')
def test_bootstrap_multiple_outputs():
from scipy.stats import spearmanr
# test a bootfunc with several output values
# return just bootstrapping with one output from bootfunc
with NumpyRNGContext(42):
bootarr = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[4, 8, 8, 3, 6, 5, 2, 8, 6, 2]]).T
answer = np.array((0.19425, 0.02094))
def bootfunc(x): return spearmanr(x)[0]
bootresult = funcs.bootstrap(bootarr, 2,
bootfunc=bootfunc)
assert_allclose(answer, bootresult, atol=1e-3)
# test a bootfunc with several output values
# return just bootstrapping with the second output from bootfunc
with NumpyRNGContext(42):
bootarr = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[4, 8, 8, 3, 6, 5, 2, 8, 6, 2]]).T
answer = np.array((0.5907,
0.9541))
def bootfunc(x): return spearmanr(x)[1]
bootresult = funcs.bootstrap(bootarr, 2,
bootfunc=bootfunc)
assert_allclose(answer, bootresult, atol=1e-3)
# return just bootstrapping with two outputs from bootfunc
with NumpyRNGContext(42):
answer = np.array(((0.1942, 0.5907),
(0.0209, 0.9541),
(0.4286, 0.2165)))
def bootfunc(x): return spearmanr(x)
bootresult = funcs.bootstrap(bootarr, 3,
bootfunc=bootfunc)
assert bootresult.shape == (3, 2)
assert_allclose(answer, bootresult, atol=1e-3)
def test_mad_std():
with NumpyRNGContext(12345):
data = np.random.normal(5, 2, size=(100, 100))
assert_allclose(funcs.mad_std(data), 2.0, rtol=0.05)
def test_mad_std_scalar_return():
with NumpyRNGContext(12345):
data = np.random.normal(5, 2, size=(10, 10))
# make a masked array with no masked points
data = np.ma.masked_where(np.isnan(data), data)
rslt = funcs.mad_std(data)
# want a scalar result, NOT a masked array
assert np.isscalar(rslt)
data[5, 5] = np.nan
rslt = funcs.mad_std(data, ignore_nan=True)
assert np.isscalar(rslt)
rslt = funcs.mad_std(data)
assert np.isscalar(rslt)
assert np.isnan(rslt)
def test_mad_std_warns():
with NumpyRNGContext(12345):
data = np.random.normal(5, 2, size=(10, 10))
data[5, 5] = np.nan
rslt = funcs.mad_std(data, ignore_nan=False)
assert np.isnan(rslt)
@pytest.mark.filterwarnings('ignore:Invalid value encountered in median')
def test_mad_std_withnan():
with NumpyRNGContext(12345):
data = np.empty([102, 102])
data[:] = np.nan
data[1:-1, 1:-1] = np.random.normal(5, 2, size=(100, 100))
assert_allclose(funcs.mad_std(data, ignore_nan=True), 2.0, rtol=0.05)
assert np.isnan(funcs.mad_std([1, 2, 3, 4, 5, np.nan]))
assert_allclose(funcs.mad_std([1, 2, 3, 4, 5, np.nan], ignore_nan=True),
1.482602218505602)
def test_mad_std_with_axis():
data = np.array([[1, 2, 3, 4],
[4, 3, 2, 1]])
# results follow data symmetry
result_axis0 = np.array([2.22390333, 0.74130111, 0.74130111,
2.22390333])
result_axis1 = np.array([1.48260222, 1.48260222])
assert_allclose(funcs.mad_std(data, axis=0), result_axis0)
assert_allclose(funcs.mad_std(data, axis=1), result_axis1)
def test_mad_std_with_axis_and_nan():
data = np.array([[1, 2, 3, 4, np.nan],
[4, 3, 2, 1, np.nan]])
# results follow data symmetry
result_axis0 = np.array([2.22390333, 0.74130111, 0.74130111,
2.22390333, np.nan])
result_axis1 = np.array([1.48260222, 1.48260222])
with pytest.warns(RuntimeWarning,
match=r'All-NaN slice encountered'):
assert_allclose(funcs.mad_std(data, axis=0, ignore_nan=True), result_axis0)
assert_allclose(funcs.mad_std(data, axis=1, ignore_nan=True), result_axis1)
def test_mad_std_with_axis_and_nan_array_type():
# mad_std should return a masked array if given one, and not otherwise
data = np.array([[1, 2, 3, 4, np.nan],
[4, 3, 2, 1, np.nan]])
with pytest.warns(RuntimeWarning,
match=r'All-NaN slice encountered'):
result = funcs.mad_std(data, axis=0, ignore_nan=True)
assert not np.ma.isMaskedArray(result)
data = np.ma.masked_where(np.isnan(data), data)
result = funcs.mad_std(data, axis=0, ignore_nan=True)
assert np.ma.isMaskedArray(result)
def test_gaussian_fwhm_to_sigma():
fwhm = (2.0 * np.sqrt(2.0 * np.log(2.0)))
assert_allclose(funcs.gaussian_fwhm_to_sigma * fwhm, 1.0, rtol=1.0e-6)
def test_gaussian_sigma_to_fwhm():
sigma = 1.0 / (2.0 * np.sqrt(2.0 * np.log(2.0)))
assert_allclose(funcs.gaussian_sigma_to_fwhm * sigma, 1.0, rtol=1.0e-6)
def test_gaussian_sigma_to_fwhm_to_sigma():
assert_allclose(funcs.gaussian_fwhm_to_sigma *
funcs.gaussian_sigma_to_fwhm, 1.0)
def test_poisson_conf_interval_rootn():
assert_allclose(funcs.poisson_conf_interval(16, interval='root-n'),
(12, 20))
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('interval', ['root-n-0',
'pearson',
'sherpagehrels',
'frequentist-confidence'])
def test_poisson_conf_large(interval):
n = 100
assert_allclose(funcs.poisson_conf_interval(n, interval='root-n'),
funcs.poisson_conf_interval(n, interval=interval),
rtol=2e-2)
def test_poisson_conf_array_rootn0_zero():
n = np.zeros((3, 4, 5))
assert_allclose(funcs.poisson_conf_interval(n, interval='root-n-0'),
funcs.poisson_conf_interval(n[0, 0, 0], interval='root-n-0')[:, None, None, None] * np.ones_like(n)) # noqa: E501
assert not np.any(np.isnan(
funcs.poisson_conf_interval(n, interval='root-n-0')))
@pytest.mark.skipif('not HAS_SCIPY')
def test_poisson_conf_array_frequentist_confidence_zero():
n = np.zeros((3, 4, 5))
assert_allclose(
funcs.poisson_conf_interval(n, interval='frequentist-confidence'),
funcs.poisson_conf_interval(n[0, 0, 0], interval='frequentist-confidence')[:, None, None, None] * np.ones_like(n)) # noqa: E501
assert not np.any(np.isnan(
funcs.poisson_conf_interval(n, interval='root-n-0')))
def test_poisson_conf_list_rootn0_zero():
n = [0, 0, 0]
assert_allclose(funcs.poisson_conf_interval(n, interval='root-n-0'),
[[0, 0, 0], [1, 1, 1]])
assert not np.any(np.isnan(
funcs.poisson_conf_interval(n, interval='root-n-0')))
def test_poisson_conf_array_rootn0():
n = 7 * np.ones((3, 4, 5))
assert_allclose(funcs.poisson_conf_interval(n, interval='root-n-0'),
funcs.poisson_conf_interval(n[0, 0, 0], interval='root-n-0')[:, None, None, None] * np.ones_like(n)) # noqa: E501
n[1, 2, 3] = 0
assert not np.any(np.isnan(
funcs.poisson_conf_interval(n, interval='root-n-0')))
@pytest.mark.skipif('not HAS_SCIPY')
def test_poisson_conf_array_fc():
n = 7 * np.ones((3, 4, 5))
assert_allclose(
funcs.poisson_conf_interval(n, interval='frequentist-confidence'),
funcs.poisson_conf_interval(n[0, 0, 0], interval='frequentist-confidence')[:, None, None, None] * np.ones_like(n)) # noqa: E501
n[1, 2, 3] = 0
assert not np.any(np.isnan(
funcs.poisson_conf_interval(n, interval='frequentist-confidence')))
@pytest.mark.skipif('not HAS_SCIPY')
def test_poisson_conf_frequentist_confidence_gehrels():
"""Test intervals against those published in Gehrels 1986"""
nlh = np.array([(0, 0, 1.841),
(1, 0.173, 3.300),
(2, 0.708, 4.638),
(3, 1.367, 5.918),
(4, 2.086, 7.163),
(5, 2.840, 8.382),
(6, 3.620, 9.584),
(7, 4.419, 10.77),
(8, 5.232, 11.95),
(9, 6.057, 13.11),
(10, 6.891, 14.27),
])
assert_allclose(
funcs.poisson_conf_interval(nlh[:, 0],
interval='frequentist-confidence'),
nlh[:, 1:].T, rtol=0.001, atol=0.001)
@pytest.mark.skipif('not HAS_SCIPY')
def test_poisson_conf_frequentist_confidence_gehrels_2sigma():
"""Test intervals against those published in Gehrels 1986
Note: I think there's a typo (transposition of digits) in Gehrels 1986,
specifically for the two-sigma lower limit for 3 events; they claim
0.569 but this function returns 0.59623...
"""
nlh = np.array([(0, 2, 0, 3.783),
(1, 2, 2.30e-2, 5.683),
(2, 2, 0.230, 7.348),
(3, 2, 0.596, 8.902),
(4, 2, 1.058, 10.39),
(5, 2, 1.583, 11.82),
(6, 2, 2.153, 13.22),
(7, 2, 2.758, 14.59),
(8, 2, 3.391, 15.94),
(9, 2, 4.046, 17.27),
(10, 2, 4.719, 18.58)])
assert_allclose(
funcs.poisson_conf_interval(nlh[:, 0], sigma=2,
interval='frequentist-confidence').T,
nlh[:, 2:], rtol=0.01)
@pytest.mark.skipif('not HAS_SCIPY')
def test_poisson_conf_frequentist_confidence_gehrels_3sigma():
"""Test intervals against those published in Gehrels 1986"""
nlh = np.array([(0, 3, 0, 6.608),
(1, 3, 1.35e-3, 8.900),
(2, 3, 5.29e-2, 10.87),
(3, 3, 0.212, 12.68),
(4, 3, 0.465, 14.39),
(5, 3, 0.792, 16.03),
(6, 3, 1.175, 17.62),
(7, 3, 1.603, 19.17),
(8, 3, 2.068, 20.69),
(9, 3, 2.563, 22.18),
(10, 3, 3.084, 23.64),
])
assert_allclose(
funcs.poisson_conf_interval(nlh[:, 0], sigma=3,
interval='frequentist-confidence').T,
nlh[:, 2:], rtol=0.01, verbose=True)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('n', [0, 1, 2, 3, 10, 20, 100])
def test_poisson_conf_gehrels86(n):
assert_allclose(
funcs.poisson_conf_interval(n, interval='sherpagehrels')[1],
funcs.poisson_conf_interval(n, interval='frequentist-confidence')[1],
rtol=0.02)
@pytest.mark.skipif('not HAS_SCIPY')
def test_scipy_poisson_limit():
'''Test that the lower-level routine gives the snae number.
Test numbers are from table1 1, 3 in
Kraft, Burrows and Nousek in
`ApJ 374, 344 (1991) <https://ui.adsabs.harvard.edu/abs/1991ApJ...374..344K>`_
'''
assert_allclose(funcs._scipy_kraft_burrows_nousek(5, 2.5, .99),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs._scipy_kraft_burrows_nousek(np.int32(5.), 2.5, .99),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs._scipy_kraft_burrows_nousek(np.int64(5.), 2.5, .99),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs._scipy_kraft_burrows_nousek(5, np.float32(2.5), .99),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs._scipy_kraft_burrows_nousek(5, np.float64(2.5), .99),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs._scipy_kraft_burrows_nousek(5, 2.5, np.float32(.99)),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs._scipy_kraft_burrows_nousek(5, 2.5, np.float64(.99)),
(0, 10.67), rtol=1e-3)
conf = funcs.poisson_conf_interval([5, 6], 'kraft-burrows-nousek',
background=[2.5, 2.],
confidence_level=[.99, .9])
assert_allclose(conf[:, 0], (0, 10.67), rtol=1e-3)
assert_allclose(conf[:, 1], (0.81, 8.99), rtol=5e-3)
@pytest.mark.skipif('not HAS_MPMATH')
def test_mpmath_poisson_limit():
assert_allclose(funcs._mpmath_kraft_burrows_nousek(1., .1, .99),
(0.00, 6.54), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(1., .5, .95),
(0.00, 4.36), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(5., 0., .99),
(1.17, 13.32), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(5., 2.5, .99),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(np.int32(6), 2., .9),
(0.81, 8.99), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(np.int64(6), 2., .9),
(0.81, 8.99), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(6., np.float32(2.), .9),
(0.81, 8.99), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(6., np.float64(2.), .9),
(0.81, 8.99), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(6., 2., np.float32(.9)),
(0.81, 8.99), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(6., 2., np.float64(.9)),
(0.81, 8.99), rtol=5e-3)
assert_allclose(funcs._mpmath_kraft_burrows_nousek(5., 2.5, .99),
(0, 10.67), rtol=1e-3)
assert_allclose(funcs.poisson_conf_interval(
n=160, background=154.543,
confidence_level=.95, interval='kraft-burrows-nousek')[:, 0], (0, 30.30454909))
# For this one we do not have the "true" answer from the publication,
# but we want to make sure that it at least runs without error
# see https://github.com/astropy/astropy/issues/9596
_ = funcs._mpmath_kraft_burrows_nousek(1000., 900., .9)
@pytest.mark.skipif('not HAS_SCIPY')
def test_poisson_conf_value_errors():
with pytest.raises(ValueError, match='Only sigma=1 supported'):
funcs.poisson_conf_interval([5, 6], 'root-n', sigma=2)
with pytest.raises(ValueError, match='background not supported'):
funcs.poisson_conf_interval([5, 6], 'pearson', background=[2.5, 2.])
with pytest.raises(ValueError, match='confidence_level not supported'):
funcs.poisson_conf_interval([5, 6], 'sherpagehrels',
confidence_level=[2.5, 2.])
with pytest.raises(ValueError, match='Invalid method'):
funcs.poisson_conf_interval(1, 'foo')
@pytest.mark.skipif('not HAS_SCIPY')
def test_poisson_conf_kbn_value_errors():
with pytest.raises(ValueError, match='number between 0 and 1'):
funcs.poisson_conf_interval(5, 'kraft-burrows-nousek',
background=2.5,
confidence_level=99)
with pytest.raises(ValueError, match='Set confidence_level for method'):
funcs.poisson_conf_interval(5, 'kraft-burrows-nousek',
background=2.5)
with pytest.raises(ValueError, match='Background must be'):
funcs.poisson_conf_interval(5, 'kraft-burrows-nousek',
background=-2.5,
confidence_level=.99)
with pytest.raises(TypeError, match='Number of counts must be integer'):
funcs.poisson_conf_interval(5., 'kraft-burrows-nousek',
background=2.5, confidence_level=.99)
with pytest.raises(TypeError, match='Number of counts must be integer'):
funcs.poisson_conf_interval([5., 6.], 'kraft-burrows-nousek',
background=[2.5, 2.],
confidence_level=[.99, .9])
@pytest.mark.skipif('HAS_SCIPY or HAS_MPMATH')
def test_poisson_limit_nodependencies():
with pytest.raises(ImportError):
funcs.poisson_conf_interval(20, interval='kraft-burrows-nousek',
background=10., confidence_level=.95)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('N', [10, 100, 1000, 10000])
def test_uniform(N):
with NumpyRNGContext(12345):
assert funcs.kuiper(np.random.random(N))[1] > 0.01
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('N,M', [(100, 100),
(20, 100),
(100, 20),
(10, 20),
(5, 5),
(1000, 100)])
def test_kuiper_two_uniform(N, M):
with NumpyRNGContext(12345):
assert funcs.kuiper_two(np.random.random(N),
np.random.random(M))[1] > 0.01
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('N,M', [(100, 100),
(20, 100),
(100, 20),
(10, 20),
(5, 5),
(1000, 100)])
def test_kuiper_two_nonuniform(N, M):
with NumpyRNGContext(12345):
assert funcs.kuiper_two(np.random.random(N)**2,
np.random.random(M)**2)[1] > 0.01
@pytest.mark.skipif('not HAS_SCIPY')
def test_detect_kuiper_two_different():
with NumpyRNGContext(12345):
D, f = funcs.kuiper_two(np.random.random(500) * 0.5,
np.random.random(500))
assert f < 0.01
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('N,M', [(100, 100),
(20, 100),
(100, 20),
(10, 20),
(5, 5),
(1000, 100)])
def test_fpp_kuiper_two(N, M):
from scipy.stats import binom
with NumpyRNGContext(12345):
R = 100
fpp = 0.05
fps = 0
for i in range(R):
D, f = funcs.kuiper_two(np.random.random(N), np.random.random(M))
if f < fpp:
fps += 1
assert binom(R, fpp).sf(fps - 1) > 0.005
assert binom(R, fpp).cdf(fps - 1) > 0.005
@pytest.mark.skipif('not HAS_SCIPY')
def test_kuiper_false_positive_probability():
fpp = funcs.kuiper_false_positive_probability(0.5353333333333409, 1500.)
assert fpp == 0
@pytest.mark.skipif('not HAS_SCIPY')
def test_histogram():
from scipy.stats import chi2
with NumpyRNGContext(1234):
a, b = 0.3, 3.14
s = np.random.uniform(a, b, 10000) % 1
b, w = funcs.fold_intervals([(a, b, 1. / (b - a))])
h = funcs.histogram_intervals(16, b, w)
nn, bb = np.histogram(s, bins=len(h), range=(0, 1))
uu = np.sqrt(nn)
nn, uu = len(h) * nn / h / len(s), len(h) * uu / h / len(s)
c2 = np.sum(((nn - 1) / uu)**2)
assert chi2(len(h)).cdf(c2) > 0.01
assert chi2(len(h)).sf(c2) > 0.01
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize("ii,rr", [
((4, (0, 1), (1,)), (1, 1, 1, 1)),
((2, (0, 1), (1,)), (1, 1)),
((4, (0, 0.5, 1), (1, 1)), (1, 1, 1, 1)),
((4, (0, 0.5, 1), (1, 2)), (1, 1, 2, 2)),
((3, (0, 0.5, 1), (1, 2)), (1, 1.5, 2)),
])
def test_histogram_intervals_known(ii, rr):
with NumpyRNGContext(1234):
assert_allclose(funcs.histogram_intervals(*ii), rr)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('N,m,p', [pytest.param(100, 10000, 0.01,
marks=pytest.mark.skip('Test too slow')),
pytest.param(300, 10000, 0.001,
marks=pytest.mark.skip('Test too slow')),
(10, 10000, 0.001),
(3, 10000, 0.001),
])
def test_uniform_binomial(N, m, p):
"""Check that the false positive probability is right
In particular, run m trials with N uniformly-distributed photons
and check that the number of false positives is consistent with
a binomial distribution. The more trials, the tighter the bounds
but the longer the runtime.
"""
from scipy.stats import binom
with NumpyRNGContext(1234):
fpps = np.array([funcs.kuiper(np.random.random(N))[1]
for i in range(m)])
assert (fpps >= 0).all()
assert (fpps <= 1).all()
low = binom(n=m, p=p).ppf(0.01)
high = binom(n=m, p=p).ppf(0.99)
assert (low < sum(fpps < p) < high)
|
5684871d4fce7dc0b09f7528cae83dfbd156218b2532e1d5760f78caba70490a | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import (assert_allclose, assert_array_almost_equal_nulp,
assert_equal)
from astropy.stats.biweight import (biweight_location, biweight_scale,
biweight_midvariance,
biweight_midcovariance,
biweight_midcorrelation)
from astropy.tests.helper import assert_quantity_allclose
import astropy.units as u
from astropy.utils.misc import NumpyRNGContext
def test_biweight_location():
with NumpyRNGContext(12345):
# test that it runs
randvar = np.random.randn(10000)
cbl = biweight_location(randvar)
assert abs(cbl - 0) < 1e-2
def test_biweight_location_constant():
cbl = biweight_location(np.ones((10, 5)))
assert cbl == 1.
def test_biweight_location_constant_axis_2d():
shape = (10, 5)
data = np.ones(shape)
cbl = biweight_location(data, axis=0)
assert_allclose(cbl, np.ones(shape[1]))
cbl = biweight_location(data, axis=1)
assert_allclose(cbl, np.ones(shape[0]))
val1 = 100.
val2 = 2.
val3 = 5.
data = np.arange(50).reshape(10, 5)
data[2] = val1
data[7] = val2
data[8] = [val3, 0.8, val3, -0.8, val3]
cbl = biweight_location(data, axis=1)
assert_allclose(cbl[2], val1)
assert_allclose(cbl[7], val2)
assert_allclose(cbl[8], val3)
def test_biweight_location_constant_axis_3d():
shape = (10, 5, 2)
data = np.ones(shape)
cbl = biweight_location(data, axis=0)
assert_allclose(cbl, np.ones((shape[1], shape[2])))
cbl = biweight_location(data, axis=1)
assert_allclose(cbl, np.ones((shape[0], shape[2])))
cbl = biweight_location(data, axis=2)
assert_allclose(cbl, np.ones((shape[0], shape[1])))
def test_biweight_location_small():
bw_loc = biweight_location([1, 3, 5, 500, 2])
assert_allclose(bw_loc, 2.7456117)
def test_biweight_location_axis():
"""Test a 2D array with the axis keyword."""
with NumpyRNGContext(12345):
ny = 100
nx = 200
data = np.random.normal(5, 2, (ny, nx))
bw = biweight_location(data, axis=0)
bwi = []
for i in range(nx):
bwi.append(biweight_location(data[:, i]))
bwi = np.array(bwi)
assert_allclose(bw, bwi)
bw = biweight_location(data, axis=1)
bwi = []
for i in range(ny):
bwi.append(biweight_location(data[i, :]))
bwi = np.array(bwi)
assert_allclose(bw, bwi)
def test_biweight_location_axis_3d():
"""Test a 3D array with the axis keyword."""
with NumpyRNGContext(12345):
nz = 3
ny = 4
nx = 5
data = np.random.normal(5, 2, (nz, ny, nx))
bw = biweight_location(data, axis=0)
assert bw.shape == (ny, nx)
y = 0
bwi = []
for i in range(nx):
bwi.append(biweight_location(data[:, y, i]))
bwi = np.array(bwi)
assert_allclose(bw[y], bwi)
def test_biweight_location_axis_tuple():
"""Test a 3D array with a tuple axis keyword."""
data = np.arange(24).reshape(2, 3, 4)
data[0, 0] = 100.
assert_equal(biweight_location(data, axis=0),
biweight_location(data, axis=(0,)))
assert_equal(biweight_location(data, axis=-1),
biweight_location(data, axis=(2,)))
assert_equal(biweight_location(data, axis=(0, 1)),
biweight_location(data, axis=(1, 0)))
assert_equal(biweight_location(data, axis=(0, 2)),
biweight_location(data, axis=(0, -1)))
assert_equal(biweight_location(data, axis=(0, 1, 2)),
biweight_location(data, axis=(2, 0, 1)))
assert_equal(biweight_location(data, axis=(0, 1, 2)),
biweight_location(data, axis=None))
@pytest.mark.filterwarnings('ignore:All-NaN slice encountered')
@pytest.mark.filterwarnings('ignore:Invalid value encountered in median')
def test_biweight_location_ignore_nan():
data1d = np.array([1, 3, 5, 500, 2, np.nan])
data2d = np.array([data1d, data1d])
assert np.isnan(biweight_location(data1d, ignore_nan=False))
biw_expected = biweight_location(data1d[:-1], ignore_nan=False)
assert_equal(biweight_location(data1d, ignore_nan=True), biw_expected)
assert_equal(biweight_location(data2d, axis=0, ignore_nan=True),
data1d)
assert_equal(biweight_location(data2d, axis=1, ignore_nan=True),
[biw_expected, biw_expected])
@pytest.mark.filterwarnings('ignore:All-NaN slice encountered')
@pytest.mark.filterwarnings('ignore:Invalid value encountered in median')
def test_biweight_location_nan():
data1d = np.array([1, 3, 5, 500, 2, np.nan])
all_nan = data1d.copy()
all_nan[:] = np.nan
data2d = np.array([data1d, data1d, all_nan])
data1d_masked = np.ma.masked_invalid(data1d)
data1d_masked.data[0] = np.nan
data2d_masked = np.ma.masked_invalid(data2d)
assert np.isnan(biweight_location(data1d))
bw_loc = biweight_location(data1d_masked)
assert not isinstance(bw_loc, np.ma.MaskedArray)
assert np.isnan(biweight_location(data2d))
for axis in (0, 1):
assert np.all(np.isnan(biweight_location(data2d, axis=axis)))
assert isinstance(biweight_location(data2d_masked, axis=axis),
np.ma.MaskedArray)
@pytest.mark.filterwarnings('ignore:All-NaN slice encountered')
@pytest.mark.filterwarnings('ignore:Invalid value encountered in median')
def test_biweight_location_masked():
data1d = np.array([1, 3, 5, 500, 2, np.nan])
data2d = np.array([data1d, data1d])
data1d_masked = np.ma.masked_invalid(data1d)
data2d_masked = np.ma.masked_invalid(data2d)
assert_equal(biweight_location(data1d, ignore_nan=True),
biweight_location(data1d_masked))
assert_equal(biweight_location(data2d, ignore_nan=True),
biweight_location(data2d_masked))
bw_loc = biweight_location(data1d_masked)
assert_allclose(bw_loc, 2.7456117)
assert np.isscalar(bw_loc)
bw_loc = biweight_location(data2d, ignore_nan=True, axis=1)
bw_loc_masked = biweight_location(data2d_masked, axis=1)
assert isinstance(bw_loc_masked, np.ma.MaskedArray)
assert ~np.any(bw_loc_masked.mask) # mask is all False
assert_equal(bw_loc, bw_loc_masked.data)
bw_loc = biweight_location(data2d, ignore_nan=True, axis=0)
bw_loc_masked = biweight_location(data2d_masked, axis=0)
assert_equal(bw_loc_masked.data[:-1], bw_loc[:-1])
assert bw_loc_masked.mask[-1] # last mask element is True
data1d_masked.data[0] = np.nan # unmasked NaN
bw_loc = biweight_location(data1d_masked)
assert not isinstance(bw_loc, np.ma.MaskedArray)
assert np.isscalar(bw_loc)
assert np.isnan(bw_loc)
assert_equal(biweight_location(data1d_masked, ignore_nan=True),
biweight_location(data1d[1:], ignore_nan=True))
# ensure that input masked array is not modified
assert np.isnan(data1d_masked[0])
def test_biweight_scale():
# NOTE: biweight_scale is covered by biweight_midvariance tests
data = [1, 3, 5, 500, 2]
scl = biweight_scale(data)
var = biweight_midvariance(data)
assert_allclose(scl, np.sqrt(var))
data = np.ma.masked_invalid([1, 3, 5, 500, 2, np.nan])
data[0] = np.nan
scl = biweight_scale(data, ignore_nan=True)
var = biweight_midvariance(data, ignore_nan=True)
assert_allclose(scl, np.sqrt(var))
def test_biweight_midvariance():
with NumpyRNGContext(12345):
# test that it runs
randvar = np.random.randn(10000)
var = biweight_midvariance(randvar)
assert_allclose(var, 1.0, rtol=0.02)
def test_biweight_midvariance_small():
data = [1, 3, 5, 500, 2]
var = biweight_midvariance(data)
assert_allclose(var, 2.9238456) # verified with R
var = biweight_midvariance(data, modify_sample_size=True)
assert_allclose(var, 2.3390765)
def test_biweight_midvariance_5127():
# test a regression introduced in #5127
rand = np.random.default_rng(12345)
data = rand.normal(loc=0., scale=20., size=(100, 100))
var = biweight_midvariance(data)
assert_allclose(var, 409.87135608846205)
def test_biweight_midvariance_axis():
"""Test a 2D array with the axis keyword."""
with NumpyRNGContext(12345):
ny = 100
nx = 200
data = np.random.normal(5, 2, (ny, nx))
bw = biweight_midvariance(data, axis=0)
bwi = []
for i in range(nx):
bwi.append(biweight_midvariance(data[:, i]))
bwi = np.array(bwi)
assert_allclose(bw, bwi)
bw = biweight_midvariance(data, axis=1)
bwi = []
for i in range(ny):
bwi.append(biweight_midvariance(data[i, :]))
bwi = np.array(bwi)
assert_allclose(bw, bwi)
def test_biweight_midvariance_axis_3d():
"""Test a 3D array with the axis keyword."""
with NumpyRNGContext(12345):
nz = 3
ny = 4
nx = 5
data = np.random.normal(5, 2, (nz, ny, nx))
bw = biweight_midvariance(data, axis=0)
assert bw.shape == (ny, nx)
y = 0
bwi = []
for i in range(nx):
bwi.append(biweight_midvariance(data[:, y, i]))
bwi = np.array(bwi)
assert_allclose(bw[y], bwi)
@pytest.mark.filterwarnings('ignore:All-NaN slice encountered')
@pytest.mark.filterwarnings('ignore:Invalid value encountered in median')
def test_biweight_midvariance_ignore_nan():
data1d = np.array([1, 3, 5, 500, 2, np.nan])
data2d = np.array([data1d, data1d])
assert np.isnan(biweight_midvariance(data1d, ignore_nan=False))
biw_var = biweight_midvariance(data1d[:-1], ignore_nan=False)
biw_var_nonan = biweight_midvariance(data1d, ignore_nan=True)
assert_equal(biw_var_nonan, biw_var)
assert_equal(biweight_midvariance(data2d, axis=0, ignore_nan=True),
[0., 0., 0., 0., 0., np.nan])
assert_equal(biweight_midvariance(data2d, axis=1, ignore_nan=True),
[biw_var_nonan, biw_var_nonan])
@pytest.mark.filterwarnings('ignore:All-NaN slice encountered')
@pytest.mark.filterwarnings('ignore:Invalid value encountered in median')
def test_biweight_scale_nan():
data1d = np.array([1, 3, 5, 500, 2, np.nan])
all_nan = data1d.copy()
all_nan[:] = np.nan
data2d = np.array([data1d, data1d, all_nan])
data1d_masked = np.ma.masked_invalid(data1d)
data1d_masked.data[0] = np.nan
data2d_masked = np.ma.masked_invalid(data2d)
assert np.isnan(biweight_scale(data1d))
bw_scl = biweight_scale(data1d_masked)
assert not isinstance(bw_scl, np.ma.MaskedArray)
assert np.isnan(bw_scl)
assert np.isnan(biweight_scale(data2d))
assert_allclose(biweight_scale(data2d_masked), 1.709926, atol=1e-5)
for axis in (0, 1):
assert np.all(np.isnan(biweight_scale(data2d, axis=axis)))
assert isinstance(biweight_scale(data2d_masked, axis=axis),
np.ma.MaskedArray)
@pytest.mark.filterwarnings('ignore:All-NaN slice encountered')
@pytest.mark.filterwarnings('ignore:Invalid value encountered in median')
def test_biweight_midvariance_masked():
data1d = np.array([1, 3, 5, 500, 2, np.nan])
data2d = np.array([data1d, data1d])
data1d_masked = np.ma.masked_invalid(data1d)
data2d_masked = np.ma.masked_invalid(data2d)
assert_equal(biweight_midvariance(data1d, ignore_nan=True),
biweight_midvariance(data1d_masked))
assert_equal(biweight_midvariance(data2d, ignore_nan=True),
biweight_midvariance(data2d_masked))
bw_scl = biweight_midvariance(data1d_masked)
assert_allclose(bw_scl, 2.9238456)
assert np.isscalar(bw_scl)
bw_loc = biweight_midvariance(data2d, ignore_nan=True, axis=1)
bw_loc_masked = biweight_midvariance(data2d_masked, axis=1)
assert isinstance(bw_loc_masked, np.ma.MaskedArray)
assert ~np.any(bw_loc_masked.mask) # mask is all False
assert_equal(bw_loc, bw_loc_masked.data)
bw_loc = biweight_midvariance(data2d, ignore_nan=True, axis=0)
bw_loc_masked = biweight_midvariance(data2d_masked, axis=0)
assert_equal(bw_loc_masked.data[:-1], bw_loc[:-1])
assert bw_loc_masked.mask[-1] # last mask element is True
data1d_masked.data[0] = np.nan # unmasked NaN
bw_scl = biweight_midvariance(data1d_masked)
assert not isinstance(bw_scl, np.ma.MaskedArray)
assert np.isscalar(bw_scl)
assert np.isnan(bw_scl)
assert_equal(biweight_midvariance(data1d_masked, ignore_nan=True),
biweight_midvariance(data1d[1:], ignore_nan=True))
# ensure that input masked array is not modified
assert np.isnan(data1d_masked[0])
def test_biweight_scale_axis_tuple():
"""Test a 3D array with a tuple axis keyword."""
data = np.arange(24).reshape(2, 3, 4)
data[0, 0] = 100.
assert_equal(biweight_scale(data, axis=0),
biweight_scale(data, axis=(0,)))
assert_equal(biweight_scale(data, axis=-1),
biweight_scale(data, axis=(2,)))
assert_equal(biweight_scale(data, axis=(0, 1)),
biweight_scale(data, axis=(1, 0)))
assert_equal(biweight_scale(data, axis=(0, 2)),
biweight_scale(data, axis=(0, -1)))
assert_equal(biweight_scale(data, axis=(0, 1, 2)),
biweight_scale(data, axis=(2, 0, 1)))
assert_equal(biweight_scale(data, axis=(0, 1, 2)),
biweight_scale(data, axis=None))
assert_equal(biweight_scale(data, axis=(0, 2), modify_sample_size=True),
biweight_scale(data, axis=(0, -1), modify_sample_size=True))
def test_biweight_midvariance_constant_axis():
bw = biweight_midvariance(np.ones((10, 5)))
assert bw == 0.0
def test_biweight_midvariance_constant_axis_2d():
shape = (10, 5)
data = np.ones(shape)
cbl = biweight_midvariance(data, axis=0)
assert_allclose(cbl, np.zeros(shape[1]))
cbl = biweight_midvariance(data, axis=1)
assert_allclose(cbl, np.zeros(shape[0]))
data = np.arange(50).reshape(10, 5)
data[2] = 100.
data[7] = 2.
data[8] = [5.0, 0.8, 5.0, -0.8, 5.0]
bw = biweight_midvariance(data, axis=1)
assert_allclose(bw[2], 0.)
assert_allclose(bw[7], 0.)
assert_allclose(bw[8], 0.)
def test_biweight_midvariance_constant_axis_3d():
shape = (10, 5, 2)
data = np.ones(shape)
cbl = biweight_midvariance(data, axis=0)
assert_allclose(cbl, np.zeros((shape[1], shape[2])))
cbl = biweight_midvariance(data, axis=1)
assert_allclose(cbl, np.zeros((shape[0], shape[2])))
cbl = biweight_midvariance(data, axis=2)
assert_allclose(cbl, np.zeros((shape[0], shape[1])))
def test_biweight_midcovariance_1d():
d = [0, 1, 2]
cov = biweight_midcovariance(d)
var = biweight_midvariance(d)
assert_allclose(cov, [[var]])
def test_biweight_midcovariance_2d():
d = [[0, 1, 2], [2, 1, 0]]
cov = biweight_midcovariance(d)
val = 0.70121809
assert_allclose(cov, [[val, -val], [-val, val]]) # verified with R
d = [[5, 1, 10], [500, 5, 2]]
cov = biweight_midcovariance(d)
assert_allclose(cov, [[14.54159077, -7.79026256], # verified with R
[-7.79026256, 6.92087252]])
cov = biweight_midcovariance(d, modify_sample_size=True)
assert_allclose(cov, [[14.54159077, -5.19350838],
[-5.19350838, 4.61391501]])
def test_biweight_midcovariance_constant():
data = np.ones((3, 10))
val3 = 5.0
data[1] = [val3, 0.8, val3, -0.8, val3, val3, val3, 1.0, val3, -0.7]
cov = biweight_midcovariance(data)
assert_allclose(cov, np.zeros((3, 3)))
rng = np.random.default_rng(123)
data = rng.random((5, 5))
val3 = 5.0
data[1] = [val3, 0.8, val3, -0.8, val3]
cov = biweight_midcovariance(data)
assert_allclose(cov[1, :], 0.)
assert_allclose(cov[:, 1], 0.)
def test_biweight_midcovariance_midvariance():
"""
Test that biweight_midcovariance diagonal elements agree with
biweight_midvariance.
"""
rng = np.random.default_rng(1)
d = rng.normal(0, 2, size=(100, 3))
cov = biweight_midcovariance(d)
var = [biweight_midvariance(a) for a in d]
assert_allclose(cov.diagonal(), var)
cov2 = biweight_midcovariance(d, modify_sample_size=True)
var2 = [biweight_midvariance(a, modify_sample_size=True)
for a in d]
assert_allclose(cov2.diagonal(), var2)
def test_midcovariance_shape():
"""
Test that biweight_midcovariance raises error with a 3D array.
"""
d = np.ones(27).reshape(3, 3, 3)
with pytest.raises(ValueError) as e:
biweight_midcovariance(d)
assert 'The input array must be 2D or 1D.' in str(e.value)
def test_midcovariance_M_shape():
"""
Test that biweight_midcovariance raises error when M is not a scalar
or 1D array.
"""
d = [0, 1, 2]
M = [[0, 1], [2, 3]]
with pytest.raises(ValueError) as e:
biweight_midcovariance(d, M=M)
assert 'M must be a scalar or 1D array.' in str(e.value)
def test_biweight_midcovariance_symmetric():
"""
Regression test to ensure that midcovariance matrix is symmetric
when ``modify_sample_size=True`` (see #5972).
"""
rng = np.random.default_rng(1)
d = rng.gamma(2, 2, size=(3, 500))
cov = biweight_midcovariance(d)
assert_array_almost_equal_nulp(cov, cov.T, nulp=5)
cov = biweight_midcovariance(d, modify_sample_size=True)
assert_array_almost_equal_nulp(cov, cov.T, nulp=5)
def test_biweight_midcorrelation():
x = [0, 1, 2]
y = [2, 1, 0]
assert_allclose(biweight_midcorrelation(x, x), 1.0)
assert_allclose(biweight_midcorrelation(x, y), -1.0)
x = [5, 1, 10, 12.4, 13.2]
y = [500, 5, 2, 7.1, 0.9]
# verified with R
assert_allclose(biweight_midcorrelation(x, y), -0.14411038976763313)
def test_biweight_midcorrelation_inputs():
a1 = np.ones((3, 3))
a2 = np.ones(5)
a3 = np.ones(7)
with pytest.raises(ValueError) as e:
biweight_midcorrelation(a1, a2)
assert 'x must be a 1D array.' in str(e.value)
with pytest.raises(ValueError) as e:
biweight_midcorrelation(a2, a1)
assert 'y must be a 1D array.' in str(e.value)
with pytest.raises(ValueError) as e:
biweight_midcorrelation(a2, a3)
assert 'x and y must have the same shape.' in str(e.value)
def test_biweight_32bit_runtime_warnings():
"""Regression test for #6905."""
with NumpyRNGContext(12345):
data = np.random.random(100).astype(np.float32)
data[50] = 30000.
biweight_scale(data)
biweight_midvariance(data)
def test_biweight_scl_var_constant_units():
unit = u.km
data = np.ones(10) << unit
biwscl = biweight_scale(data)
biwvar = biweight_midvariance(data)
assert isinstance(biwscl, u.Quantity)
assert isinstance(biwvar, u.Quantity)
assert_quantity_allclose(biwscl, 0. << unit)
assert_quantity_allclose(biwvar, 0. << unit ** 2)
data = np.ones(10) << unit
data[0] = np.nan
biwscl = biweight_scale(data)
biwvar = biweight_midvariance(data)
assert isinstance(biwscl, u.Quantity)
assert isinstance(biwvar, u.Quantity)
assert_quantity_allclose(biwscl, np.nan << unit)
assert_quantity_allclose(biwvar, np.nan << unit ** 2)
|
c14351a9fc91175cdad57b0701412290cf8816e390eedbd74eddffb961eb9ed8 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# The LombScargle periodogram functionality has been moved to
# astropy.timeseries.periodograms.bls. The purpose of this file is to provide backward-
# compatibility during a transition phase. We can't emit a deprecation warning
# simply on import of this module, since the classes are imported into the
# top-level astropy.stats, so instead we wrap the main class and emit a
# warning during initialization.
import warnings
from astropy.timeseries.periodograms.lombscargle import LombScargle as TimeseriesLombScargle
from astropy.utils.exceptions import AstropyDeprecationWarning
__all__ = ['LombScargle']
class LombScargle(TimeseriesLombScargle):
"""
Compute the Lomb-Scargle Periodogram.
This class has been deprecated and will be removed in a future version.
Use `astropy.timeseries.LombScargle` instead.
"""
def __init__(self, *args, **kwargs):
warnings.warn('Importing LombScargle from astropy.stats has been '
'deprecated and will no longer be supported in future. '
'Please import this class from the astropy.timeseries '
'module instead', AstropyDeprecationWarning)
super().__init__(*args, **kwargs)
|
1c43909c8e64e3e580cd93fb86e01dc25122c2132b3298a50e094a45cd591803 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
``showtable`` is a command-line script based on ``astropy.io`` and
``astropy.table`` for printing ASCII, FITS, HDF5 or VOTable files(s) to the
standard output.
Example usage of ``showtable``:
1. FITS::
$ showtable astropy/io/fits/tests/data/table.fits
target V_mag
------- -----
NGC1001 11.1
NGC1002 12.3
NGC1003 15.2
2. ASCII::
$ showtable astropy/io/ascii/tests/t/simple_csv.csv
a b c
--- --- ---
1 2 3
4 5 6
3. XML::
$ showtable astropy/io/votable/tests/data/names.xml --max-width 70
col1 col2 col3 ... col15 col16 col17
--- deg deg ... mag mag ---
------------------------- -------- ------- ... ----- ----- -----
SSTGLMC G000.0000+00.1611 0.0000 0.1611 ... -- -- AA
4. Print all the FITS tables in the current directory::
$ showtable *.fits
"""
import argparse
import textwrap
import warnings
from astropy import log
from astropy.table import Table
from astropy.utils.exceptions import AstropyUserWarning
def showtable(filename, args):
"""
Read a table and print to the standard output.
Parameters
----------
filename : str
The path to a FITS file.
"""
if args.info and args.stats:
warnings.warn('--info and --stats cannot be used together',
AstropyUserWarning)
if (any((args.max_lines, args.max_width, args.hide_unit, args.show_dtype))
and (args.info or args.stats)):
warnings.warn('print parameters are ignored if --info or --stats is '
'used', AstropyUserWarning)
# these parameters are passed to Table.read if they are specified in the
# command-line
read_kwargs = ('hdu', 'format', 'table_id', 'delimiter')
kwargs = {k: v for k, v in vars(args).items()
if k in read_kwargs and v is not None}
try:
table = Table.read(filename, **kwargs)
if args.info:
table.info('attributes')
elif args.stats:
table.info('stats')
else:
formatter = table.more if args.more else table.pprint
formatter(max_lines=args.max_lines, max_width=args.max_width,
show_unit=(False if args.hide_unit else None),
show_dtype=args.show_dtype)
except IOError as e:
log.error(str(e))
def main(args=None):
"""The main function called by the `showtable` script."""
parser = argparse.ArgumentParser(
description=textwrap.dedent("""
Print tables from ASCII, FITS, HDF5, VOTable file(s). The tables
are read with 'astropy.table.Table.read' and are printed with
'astropy.table.Table.pprint'. The default behavior is to make the
table output fit onto a single screen page. For a long and wide
table this will mean cutting out inner rows and columns. To print
**all** the rows or columns use ``--max-lines=-1`` or
``max-width=-1``, respectively. The complete list of supported
formats can be found at
http://astropy.readthedocs.io/en/latest/io/unified.html#built-in-table-readers-writers
"""))
addarg = parser.add_argument
addarg('filename', nargs='+', help='path to one or more files')
addarg('--format', help='input table format, should be specified if it '
'cannot be automatically detected')
addarg('--more', action='store_true',
help='use the pager mode from Table.more')
addarg('--info', action='store_true',
help='show information about the table columns')
addarg('--stats', action='store_true',
help='show statistics about the table columns')
# pprint arguments
pprint_args = parser.add_argument_group('pprint arguments')
addarg = pprint_args.add_argument
addarg('--max-lines', type=int,
help='maximum number of lines in table output (default=screen '
'length, -1 for no limit)')
addarg('--max-width', type=int,
help='maximum width in table output (default=screen width, '
'-1 for no limit)')
addarg('--hide-unit', action='store_true',
help='hide the header row for unit (which is shown '
'only if one or more columns has a unit)')
addarg('--show-dtype', action='store_true',
help='include a header row for column dtypes')
# ASCII-specific arguments
ascii_args = parser.add_argument_group('ASCII arguments')
addarg = ascii_args.add_argument
addarg('--delimiter', help='column delimiter string')
# FITS-specific arguments
fits_args = parser.add_argument_group('FITS arguments')
addarg = fits_args.add_argument
addarg('--hdu', help='name of the HDU to show')
# HDF5-specific arguments
hdf5_args = parser.add_argument_group('HDF5 arguments')
addarg = hdf5_args.add_argument
addarg('--path', help='the path from which to read the table')
# VOTable-specific arguments
votable_args = parser.add_argument_group('VOTable arguments')
addarg = votable_args.add_argument
addarg('--table-id', help='the table to read in')
args = parser.parse_args(args)
for idx, filename in enumerate(args.filename):
if idx > 0:
print()
showtable(filename, args)
|
6bc2342181e44242e550b724cafd64e2d3deb626ed6b9dbee2f6317e99718065 | # This module handles the definition of mixin 'handlers' which are functions
# that given an arbitrary object (e.g. a dask array) will return an object that
# can be used as a mixin column. This is useful because it means that users can
# then add objects to tables that are not formally mixin columns and where
# adding an info attribute is beyond our control.
__all__ = ['MixinRegistryError', 'register_mixin_handler', 'get_mixin_handler']
# The internal dictionary of handlers maps fully qualified names of classes
# to a function that can take an object and return a mixin-compatible object.
_handlers = {}
class MixinRegistryError(Exception):
pass
def register_mixin_handler(fully_qualified_name, handler, force=False):
"""
Register a mixin column 'handler'.
A mixin column handler is a function that given an arbitrary Python object,
will return an object with the .info attribute that can then be used as a
mixin column (this can be e.g. a copy of the object with a new attribute,
a subclass instance, or a wrapper class - this is left up to the handler).
The handler will be used on classes that have an exactly matching fully
qualified name.
Parameters
----------
fully_qualified_name : str
The fully qualified name of the class that the handler can operate on,
such as e.g. ``dask.array.core.Array``.
handler : func
The handler function.
force : bool, optional
Whether to overwrite any previous handler if there is already one for
the same fully qualified name.
"""
if fully_qualified_name not in _handlers or force:
_handlers[fully_qualified_name] = handler
else:
raise MixinRegistryError(f"Handler for class {fully_qualified_name} is already defined")
def get_mixin_handler(obj):
"""
Given an arbitrary object, return the matching mixin handler (if any).
Parameters
----------
obj : object or str
The object to find a mixin handler for, or a fully qualified name.
Returns
-------
handler : None or func
Then matching handler, if found, or `None`
"""
if isinstance(obj, str):
return _handlers.get(obj, None)
else:
return _handlers.get(obj.__class__.__module__ + '.' + obj.__class__.__name__, None)
# Add built-in handlers to registry. Note that any third-party package imports
# required by the handlers should go inside the handler function to delay
# the imports until they are actually needed.
def dask_handler(arr):
from astropy.table.mixins.dask import as_dask_column
return as_dask_column(arr)
register_mixin_handler('dask.array.core.Array', dask_handler)
|
5f95512de18bcf2239352ddf7760a24d8b4cd125d0e4d44b0db51168b278a497 | import dask.array as da
from astropy.utils.data_info import ParentDtypeInfo
__all__ = ['as_dask_column']
class DaskInfo(ParentDtypeInfo):
@staticmethod
def default_format(val):
return f'{val.compute()}'
class DaskColumn(da.Array):
info = DaskInfo()
def copy(self):
# Array hard-codes the resulting copied array as Array, so need to
# overload this since Table tries to copy the array.
return as_dask_column(self, info=self.info)
def __getitem__(self, item):
result = super().__getitem__(item)
if isinstance(item, int):
return result
else:
return as_dask_column(result, info=self.info)
def insert(self, obj, values, axis=0):
return as_dask_column(da.insert(self, obj, values, axis=axis),
info=self.info)
def as_dask_column(array, info=None):
result = DaskColumn(array.dask, array.name, array.chunks, meta=array)
if info is not None:
result.info = info
return result
|
969d0da04193d9c32c29b29bcde93729bb6ee698205c8ae647abd95efe3168de | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from astropy.table.sorted_array import SortedArray
from astropy.table.table import Table
@pytest.fixture
def array():
# composite index
col0 = np.array([x % 2 for x in range(1, 11)])
col1 = np.array([x for x in range(1, 11)])
t = Table([col0, col1])
t = t[t.argsort()]
return SortedArray(t, t['col1'].copy())
@pytest.fixture
def wide_array():
# array with 100 columns
t = Table([[x] * 10 for x in np.arange(100)])
return SortedArray(t, t['col0'].copy())
def test_array_find(array):
for i in range(1, 11):
print(f"Searching for {i}")
assert array.find((i % 2, i)) == [i]
assert array.find((1, 4)) == []
def test_array_range(array):
assert np.all(array.range((0, 8), (1, 3), (True, True)) == [8, 10, 1, 3])
assert np.all(array.range((0, 8), (1, 3), (False, True)) == [10, 1, 3])
assert np.all(array.range((0, 8), (1, 3), (True, False)) == [8, 10, 1])
def test_wide_array(wide_array):
# checks for a previous bug in which the length of a
# sliced SortedArray was set to the number of columns
# instead of the number of elements in each column
first_row = wide_array[:1].data
assert np.all(first_row == Table([[x] for x in np.arange(100)]))
|
28e50191a49c18434d0a66e36dde536586378c04b8c1babf11bb5b62eedd4cd2 | import numpy as np
from astropy.table import np_utils
def test_common_dtype():
"""
Test that allowed combinations are those expected.
"""
dtype = [('int', int),
('uint8', np.uint8),
('float32', np.float32),
('float64', np.float64),
('str', 'S2'),
('uni', 'U2'),
('bool', bool),
('object', np.object_)]
arr = np.empty(1, dtype=dtype)
fail = set()
succeed = set()
for name1, type1 in dtype:
for name2, type2 in dtype:
try:
np_utils.common_dtype([arr[name1], arr[name2]])
succeed.add(f'{name1} {name2}')
except np_utils.TableMergeError:
fail.add(f'{name1} {name2}')
# known bad combinations
bad = set(['str int', 'str bool', 'uint8 bool', 'uint8 str', 'object float32',
'bool object', 'uni uint8', 'int str', 'bool str', 'bool float64',
'bool uni', 'str float32', 'uni float64', 'uni object', 'bool uint8',
'object float64', 'float32 bool', 'str uint8', 'uni bool', 'float64 bool',
'float64 object', 'int bool', 'uni int', 'uint8 object', 'int uni', 'uint8 uni',
'float32 uni', 'object uni', 'bool float32', 'uni float32', 'object str',
'int object', 'str float64', 'object int', 'float64 uni', 'bool int',
'object bool', 'object uint8', 'float32 object', 'str object', 'float64 str',
'float32 str'])
assert fail == bad
good = set(['float64 int', 'int int', 'uint8 float64', 'uint8 int', 'str uni',
'float32 float32', 'float64 float64', 'float64 uint8', 'float64 float32',
'int uint8', 'int float32', 'uni str', 'int float64', 'uint8 float32',
'float32 int', 'float32 uint8', 'bool bool', 'uint8 uint8', 'str str',
'float32 float64', 'object object', 'uni uni'])
assert succeed == good
|
9ce51b0e86f9483dff26196b5eb35a2e50541e4a000c986dffabaec88036df9b | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy.utils.tests.test_metadata import MetaBaseTest
import gc
import sys
import copy
from io import StringIO
from collections import OrderedDict
import pickle
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal
from astropy.io import fits
from astropy.table import (Table, QTable, Column, MaskedColumn, TableReplaceWarning,
TableAttribute)
from astropy.tests.helper import assert_follows_unicode_guidelines
from astropy.coordinates import SkyCoord
from astropy.utils.data import get_pkg_data_filename
from astropy.utils.exceptions import AstropyUserWarning
from astropy import table
from astropy import units as u
from astropy.time import Time, TimeDelta
from .conftest import MaskedTable, MIXIN_COLS
from astropy.utils.compat.optional_deps import HAS_PANDAS # noqa
class SetupData:
def _setup(self, table_types):
self._table_type = table_types.Table
self._column_type = table_types.Column
@property
def a(self):
if self._column_type is not None:
if not hasattr(self, '_a'):
self._a = self._column_type(
[1, 2, 3], name='a', format='%d',
meta={'aa': [0, 1, 2, 3, 4]})
return self._a
@property
def b(self):
if self._column_type is not None:
if not hasattr(self, '_b'):
self._b = self._column_type(
[4, 5, 6], name='b', format='%d', meta={'aa': 1})
return self._b
@property
def c(self):
if self._column_type is not None:
if not hasattr(self, '_c'):
self._c = self._column_type([7, 8, 9], 'c')
return self._c
@property
def d(self):
if self._column_type is not None:
if not hasattr(self, '_d'):
self._d = self._column_type([7, 8, 7], 'd')
return self._d
@property
def obj(self):
if self._column_type is not None:
if not hasattr(self, '_obj'):
self._obj = self._column_type([1, 'string', 3], 'obj', dtype='O')
return self._obj
@property
def t(self):
if self._table_type is not None:
if not hasattr(self, '_t'):
self._t = self._table_type([self.a, self.b])
return self._t
@pytest.mark.usefixtures('table_types')
class TestSetTableColumn(SetupData):
def test_set_row(self, table_types):
"""Set a row from a tuple of values"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t[1] = (20, 21)
assert t['a'][0] == 1
assert t['a'][1] == 20
assert t['a'][2] == 3
assert t['b'][0] == 4
assert t['b'][1] == 21
assert t['b'][2] == 6
def test_set_row_existing(self, table_types):
"""Set a row from another existing row"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t[0] = t[1]
assert t[0][0] == 2
assert t[0][1] == 5
def test_set_row_fail_1(self, table_types):
"""Set a row from an incorrectly-sized or typed set of values"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
with pytest.raises(ValueError):
t[1] = (20, 21, 22)
with pytest.raises(ValueError):
t[1] = 0
def test_set_row_fail_2(self, table_types):
"""Set a row from an incorrectly-typed tuple of values"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
with pytest.raises(ValueError):
t[1] = ('abc', 'def')
def test_set_new_col_new_table(self, table_types):
"""Create a new column in empty table using the item access syntax"""
self._setup(table_types)
t = table_types.Table()
t['aa'] = self.a
# Test that the new column name is 'aa' and that the values match
assert np.all(t['aa'] == self.a)
assert t.colnames == ['aa']
def test_set_new_col_new_table_quantity(self, table_types):
"""Create a new column (from a quantity) in empty table using the item access syntax"""
self._setup(table_types)
t = table_types.Table()
t['aa'] = np.array([1, 2, 3]) * u.m
assert np.all(t['aa'] == np.array([1, 2, 3]))
assert t['aa'].unit == u.m
t['bb'] = 3 * u.m
assert np.all(t['bb'] == 3)
assert t['bb'].unit == u.m
def test_set_new_col_existing_table(self, table_types):
"""Create a new column in an existing table using the item access syntax"""
self._setup(table_types)
t = table_types.Table([self.a])
# Add a column
t['bb'] = self.b
assert np.all(t['bb'] == self.b)
assert t.colnames == ['a', 'bb']
assert t['bb'].meta == self.b.meta
assert t['bb'].format == self.b.format
# Add another column
t['c'] = t['a']
assert np.all(t['c'] == t['a'])
assert t.colnames == ['a', 'bb', 'c']
assert t['c'].meta == t['a'].meta
assert t['c'].format == t['a'].format
# Add a multi-dimensional column
t['d'] = table_types.Column(np.arange(12).reshape(3, 2, 2))
assert t['d'].shape == (3, 2, 2)
assert t['d'][0, 0, 1] == 1
# Add column from a list
t['e'] = ['hello', 'the', 'world']
assert np.all(t['e'] == np.array(['hello', 'the', 'world']))
# Make sure setting existing column still works
t['e'] = ['world', 'hello', 'the']
assert np.all(t['e'] == np.array(['world', 'hello', 'the']))
# Add a column via broadcasting
t['f'] = 10
assert np.all(t['f'] == 10)
# Add a column from a Quantity
t['g'] = np.array([1, 2, 3]) * u.m
assert np.all(t['g'].data == np.array([1, 2, 3]))
assert t['g'].unit == u.m
# Add a column from a (scalar) Quantity
t['g'] = 3 * u.m
assert np.all(t['g'].data == 3)
assert t['g'].unit == u.m
def test_set_new_unmasked_col_existing_table(self, table_types):
"""Create a new column in an existing table using the item access syntax"""
self._setup(table_types)
t = table_types.Table([self.a]) # masked or unmasked
b = table.Column(name='b', data=[1, 2, 3]) # unmasked
t['b'] = b
assert np.all(t['b'] == b)
def test_set_new_masked_col_existing_table(self, table_types):
"""Create a new column in an existing table using the item access syntax"""
self._setup(table_types)
t = table_types.Table([self.a]) # masked or unmasked
b = table.MaskedColumn(name='b', data=[1, 2, 3]) # masked
t['b'] = b
assert np.all(t['b'] == b)
def test_set_new_col_existing_table_fail(self, table_types):
"""Generate failure when creating a new column using the item access syntax"""
self._setup(table_types)
t = table_types.Table([self.a])
# Wrong size
with pytest.raises(ValueError):
t['b'] = [1, 2]
@pytest.mark.usefixtures('table_types')
class TestEmptyData():
def test_1(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a', dtype=int, length=100))
assert len(t['a']) == 100
def test_2(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a', dtype=int, shape=(3, ), length=100))
assert len(t['a']) == 100
def test_3(self, table_types):
t = table_types.Table() # length is not given
t.add_column(table_types.Column(name='a', dtype=int))
assert len(t['a']) == 0
def test_4(self, table_types):
t = table_types.Table() # length is not given
t.add_column(table_types.Column(name='a', dtype=int, shape=(3, 4)))
assert len(t['a']) == 0
def test_5(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a')) # dtype is not specified
assert len(t['a']) == 0
def test_scalar(self, table_types):
"""Test related to #3811 where setting empty tables to scalar values
should raise an error instead of having an error raised when accessing
the table."""
t = table_types.Table()
with pytest.raises(TypeError, match='Empty table cannot have column set to scalar value'):
t.add_column(0)
def test_add_via_setitem_and_slice(self, table_types):
"""Test related to #3023 where a MaskedColumn is created with name=None
and then gets changed to name='a'. After PR #2790 this test fails
without the #3023 fix."""
t = table_types.Table()
t['a'] = table_types.Column([1, 2, 3])
t2 = t[:]
assert t2.colnames == t.colnames
@pytest.mark.usefixtures('table_types')
class TestNewFromColumns():
def test_simple(self, table_types):
cols = [table_types.Column(name='a', data=[1, 2, 3]),
table_types.Column(name='b', data=[4, 5, 6], dtype=np.float32)]
t = table_types.Table(cols)
assert np.all(t['a'].data == np.array([1, 2, 3]))
assert np.all(t['b'].data == np.array([4, 5, 6], dtype=np.float32))
assert type(t['b'][1]) is np.float32
def test_from_np_array(self, table_types):
cols = [table_types.Column(name='a', data=np.array([1, 2, 3], dtype=np.int64),
dtype=np.float64),
table_types.Column(name='b', data=np.array([4, 5, 6], dtype=np.float32))]
t = table_types.Table(cols)
assert np.all(t['a'] == np.array([1, 2, 3], dtype=np.float64))
assert np.all(t['b'] == np.array([4, 5, 6], dtype=np.float32))
assert type(t['a'][1]) is np.float64
assert type(t['b'][1]) is np.float32
def test_size_mismatch(self, table_types):
cols = [table_types.Column(name='a', data=[1, 2, 3]),
table_types.Column(name='b', data=[4, 5, 6, 7])]
with pytest.raises(ValueError):
table_types.Table(cols)
def test_name_none(self, table_types):
"""Column with name=None can init a table whether or not names are supplied"""
c = table_types.Column(data=[1, 2], name='c')
d = table_types.Column(data=[3, 4])
t = table_types.Table([c, d], names=(None, 'd'))
assert t.colnames == ['c', 'd']
t = table_types.Table([c, d])
assert t.colnames == ['c', 'col1']
@pytest.mark.usefixtures('table_types')
class TestReverse():
def test_reverse(self, table_types):
t = table_types.Table([[1, 2, 3],
['a', 'b', 'cc']])
t.reverse()
assert np.all(t['col0'] == np.array([3, 2, 1]))
assert np.all(t['col1'] == np.array(['cc', 'b', 'a']))
t2 = table_types.Table(t, copy=False)
assert np.all(t2['col0'] == np.array([3, 2, 1]))
assert np.all(t2['col1'] == np.array(['cc', 'b', 'a']))
t2 = table_types.Table(t, copy=True)
assert np.all(t2['col0'] == np.array([3, 2, 1]))
assert np.all(t2['col1'] == np.array(['cc', 'b', 'a']))
t2.sort('col0')
assert np.all(t2['col0'] == np.array([1, 2, 3]))
assert np.all(t2['col1'] == np.array(['a', 'b', 'cc']))
def test_reverse_big(self, table_types):
x = np.arange(10000)
y = x + 1
t = table_types.Table([x, y], names=('x', 'y'))
t.reverse()
assert np.all(t['x'] == x[::-1])
assert np.all(t['y'] == y[::-1])
def test_reverse_mixin(self):
"""Test reverse for a mixin with no item assignment, fix for #9836"""
sc = SkyCoord([1, 2], [3, 4], unit='deg')
t = Table([[2, 1], sc], names=['a', 'sc'])
t.reverse()
assert np.all(t['a'] == [1, 2])
assert np.allclose(t['sc'].ra.to_value('deg'), [2, 1])
@pytest.mark.usefixtures('table_types')
class TestRound():
def test_round_int(self, table_types):
t = table_types.Table([['a', 'b', 'c'],
[1.11, 2.3, 3.0],
[1.123456, 2.9876, 3.901]])
t.round()
assert np.all(t['col0'] == ['a', 'b', 'c'])
assert np.all(t['col1'] == [1., 2., 3.])
assert np.all(t['col2'] == [1., 3., 4.])
def test_round_dict(self, table_types):
t = table_types.Table([['a', 'b', 'c'],
[1.5, 2.5, 3.0111],
[1.123456, 2.9876, 3.901]])
t.round({'col1': 0, 'col2': 3})
assert np.all(t['col0'] == ['a', 'b', 'c'])
assert np.all(t['col1'] == [2.0, 2.0, 3.0])
assert np.all(t['col2'] == [1.123, 2.988, 3.901])
def test_round_invalid(self, table_types):
t = table_types.Table([[1, 2, 3]])
with pytest.raises(ValueError, match="'decimals' argument must be an int or a dict"):
t.round(0.5)
def test_round_kind(self, table_types):
for typecode in 'bBhHiIlLqQpPefdgFDG': # AllInteger, AllFloat
arr = np.array([4, 16], dtype=typecode)
t = Table([arr])
col0 = t['col0']
t.round(decimals=-1) # Round to nearest 10
assert np.all(t['col0'] == [0, 20])
assert t['col0'] is col0
@pytest.mark.usefixtures('table_types')
class TestColumnAccess():
def test_1(self, table_types):
t = table_types.Table()
with pytest.raises(KeyError):
t['a']
def test_2(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a', data=[1, 2, 3]))
assert np.all(t['a'] == np.array([1, 2, 3]))
with pytest.raises(KeyError):
t['b'] # column does not exist
def test_itercols(self, table_types):
names = ['a', 'b', 'c']
t = table_types.Table([[1], [2], [3]], names=names)
for name, col in zip(names, t.itercols()):
assert name == col.name
assert isinstance(col, table_types.Column)
@pytest.mark.usefixtures('table_types')
class TestAddLength(SetupData):
def test_right_length(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a])
t.add_column(self.b)
def test_too_long(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a])
with pytest.raises(ValueError):
t.add_column(table_types.Column(name='b', data=[4, 5, 6, 7])) # data too long
def test_too_short(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a])
with pytest.raises(ValueError):
t.add_column(table_types.Column(name='b', data=[4, 5])) # data too short
@pytest.mark.usefixtures('table_types')
class TestAddPosition(SetupData):
def test_1(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_column(self.a, 0)
def test_2(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_column(self.a, 1)
def test_3(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_column(self.a, -1)
def test_5(self, table_types):
self._setup(table_types)
t = table_types.Table()
with pytest.raises(ValueError):
t.index_column('b')
def test_6(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_column(self.a)
t.add_column(self.b)
assert t.colnames == ['a', 'b']
def test_7(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a])
t.add_column(self.b, t.index_column('a'))
assert t.colnames == ['b', 'a']
def test_8(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a])
t.add_column(self.b, t.index_column('a') + 1)
assert t.colnames == ['a', 'b']
def test_9(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_column(self.a)
t.add_column(self.b, t.index_column('a') + 1)
t.add_column(self.c, t.index_column('b'))
assert t.colnames == ['a', 'c', 'b']
def test_10(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_column(self.a)
ia = t.index_column('a')
t.add_column(self.b, ia + 1)
t.add_column(self.c, ia)
assert t.colnames == ['c', 'a', 'b']
@pytest.mark.usefixtures('table_types')
class TestAddName(SetupData):
def test_override_name(self, table_types):
self._setup(table_types)
t = table_types.Table()
# Check that we can override the name of the input column in the Table
t.add_column(self.a, name='b')
t.add_column(self.b, name='a')
assert t.colnames == ['b', 'a']
# Check that we did not change the name of the input column
assert self.a.info.name == 'a'
assert self.b.info.name == 'b'
# Now test with an input column from another table
t2 = table_types.Table()
t2.add_column(t['a'], name='c')
assert t2.colnames == ['c']
# Check that we did not change the name of the input column
assert t.colnames == ['b', 'a']
# Check that we can give a name if none was present
col = table_types.Column([1, 2, 3])
t.add_column(col, name='c')
assert t.colnames == ['b', 'a', 'c']
def test_default_name(self, table_types):
t = table_types.Table()
col = table_types.Column([1, 2, 3])
t.add_column(col)
assert t.colnames == ['col0']
@pytest.mark.usefixtures('table_types')
class TestInitFromTable(SetupData):
def test_from_table_cols(self, table_types):
"""Ensure that using cols from an existing table gives
a clean copy.
"""
self._setup(table_types)
t = self.t
cols = t.columns
# Construct Table with cols via Table._new_from_cols
t2a = table_types.Table([cols['a'], cols['b'], self.c])
# Construct with add_column
t2b = table_types.Table()
t2b.add_column(cols['a'])
t2b.add_column(cols['b'])
t2b.add_column(self.c)
t['a'][1] = 20
t['b'][1] = 21
for t2 in [t2a, t2b]:
t2['a'][2] = 10
t2['b'][2] = 11
t2['c'][2] = 12
t2.columns['a'].meta['aa'][3] = 10
assert np.all(t['a'] == np.array([1, 20, 3]))
assert np.all(t['b'] == np.array([4, 21, 6]))
assert np.all(t2['a'] == np.array([1, 2, 10]))
assert np.all(t2['b'] == np.array([4, 5, 11]))
assert np.all(t2['c'] == np.array([7, 8, 12]))
assert t2['a'].name == 'a'
assert t2.columns['a'].meta['aa'][3] == 10
assert t.columns['a'].meta['aa'][3] == 3
@pytest.mark.usefixtures('table_types')
class TestAddColumns(SetupData):
def test_add_columns1(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_columns([self.a, self.b, self.c])
assert t.colnames == ['a', 'b', 'c']
def test_add_columns2(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.add_columns([self.c, self.d])
assert t.colnames == ['a', 'b', 'c', 'd']
assert np.all(t['c'] == np.array([7, 8, 9]))
def test_add_columns3(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.add_columns([self.c, self.d], indexes=[1, 0])
assert t.colnames == ['d', 'a', 'c', 'b']
def test_add_columns4(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.add_columns([self.c, self.d], indexes=[0, 0])
assert t.colnames == ['c', 'd', 'a', 'b']
def test_add_columns5(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.add_columns([self.c, self.d], indexes=[2, 2])
assert t.colnames == ['a', 'b', 'c', 'd']
def test_add_columns6(self, table_types):
"""Check that we can override column names."""
self._setup(table_types)
t = table_types.Table()
t.add_columns([self.a, self.b, self.c], names=['b', 'c', 'a'])
assert t.colnames == ['b', 'c', 'a']
def test_add_columns7(self, table_types):
"""Check that default names are used when appropriate."""
t = table_types.Table()
col0 = table_types.Column([1, 2, 3])
col1 = table_types.Column([4, 5, 3])
t.add_columns([col0, col1])
assert t.colnames == ['col0', 'col1']
def test_add_duplicate_column(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_column(self.a)
with pytest.raises(ValueError):
t.add_column(table_types.Column(name='a', data=[0, 1, 2]))
t.add_column(table_types.Column(name='a', data=[0, 1, 2]),
rename_duplicate=True)
t.add_column(self.b)
t.add_column(self.c)
assert t.colnames == ['a', 'a_1', 'b', 'c']
t.add_column(table_types.Column(name='a', data=[0, 1, 2]),
rename_duplicate=True)
assert t.colnames == ['a', 'a_1', 'b', 'c', 'a_2']
# test adding column from a separate Table
t1 = table_types.Table()
t1.add_column(self.a)
with pytest.raises(ValueError):
t.add_column(t1['a'])
t.add_column(t1['a'], rename_duplicate=True)
t1['a'][0] = 100 # Change original column
assert t.colnames == ['a', 'a_1', 'b', 'c', 'a_2', 'a_3']
assert t1.colnames == ['a']
# Check new column didn't change (since name conflict forced a copy)
assert t['a_3'][0] == self.a[0]
# Check that rename_duplicate=True is ok if there are no duplicates
t.add_column(table_types.Column(name='q', data=[0, 1, 2]),
rename_duplicate=True)
assert t.colnames == ['a', 'a_1', 'b', 'c', 'a_2', 'a_3', 'q']
def test_add_duplicate_columns(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b, self.c])
with pytest.raises(ValueError):
t.add_columns([table_types.Column(name='a', data=[0, 1, 2]),
table_types.Column(name='b', data=[0, 1, 2])])
t.add_columns([table_types.Column(name='a', data=[0, 1, 2]),
table_types.Column(name='b', data=[0, 1, 2])],
rename_duplicate=True)
t.add_column(self.d)
assert t.colnames == ['a', 'b', 'c', 'a_1', 'b_1', 'd']
@pytest.mark.usefixtures('table_types')
class TestAddRow(SetupData):
@property
def b(self):
if self._column_type is not None:
if not hasattr(self, '_b'):
self._b = self._column_type(name='b', data=[4.0, 5.1, 6.2])
return self._b
@property
def c(self):
if self._column_type is not None:
if not hasattr(self, '_c'):
self._c = self._column_type(name='c', data=['7', '8', '9'])
return self._c
@property
def d(self):
if self._column_type is not None:
if not hasattr(self, '_d'):
self._d = self._column_type(name='d', data=[[1, 2], [3, 4], [5, 6]])
return self._d
@property
def t(self):
if self._table_type is not None:
if not hasattr(self, '_t'):
self._t = self._table_type([self.a, self.b, self.c])
return self._t
def test_add_none_to_empty_table(self, table_types):
self._setup(table_types)
t = table_types.Table(names=('a', 'b', 'c'), dtype=('(2,)i', 'S4', 'O'))
t.add_row()
assert np.all(t['a'][0] == [0, 0])
assert t['b'][0] == ''
assert t['c'][0] == 0
t.add_row()
assert np.all(t['a'][1] == [0, 0])
assert t['b'][1] == ''
assert t['c'][1] == 0
def test_add_stuff_to_empty_table(self, table_types):
self._setup(table_types)
t = table_types.Table(names=('a', 'b', 'obj'), dtype=('(2,)i', 'S8', 'O'))
t.add_row([[1, 2], 'hello', 'world'])
assert np.all(t['a'][0] == [1, 2])
assert t['b'][0] == 'hello'
assert t['obj'][0] == 'world'
# Make sure it is not repeating last row but instead
# adding zeros (as documented)
t.add_row()
assert np.all(t['a'][1] == [0, 0])
assert t['b'][1] == ''
assert t['obj'][1] == 0
def test_add_table_row(self, table_types):
self._setup(table_types)
t = self.t
t['d'] = self.d
t2 = table_types.Table([self.a, self.b, self.c, self.d])
t.add_row(t2[0])
assert len(t) == 4
assert np.all(t['a'] == np.array([1, 2, 3, 1]))
assert np.allclose(t['b'], np.array([4.0, 5.1, 6.2, 4.0]))
assert np.all(t['c'] == np.array(['7', '8', '9', '7']))
assert np.all(t['d'] == np.array([[1, 2], [3, 4], [5, 6], [1, 2]]))
def test_add_table_row_obj(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b, self.obj])
t.add_row([1, 4.0, [10]])
assert len(t) == 4
assert np.all(t['a'] == np.array([1, 2, 3, 1]))
assert np.allclose(t['b'], np.array([4.0, 5.1, 6.2, 4.0]))
assert np.all(t['obj'] == np.array([1, 'string', 3, [10]], dtype='O'))
def test_add_qtable_row_multidimensional(self):
q = [[1, 2], [3, 4]] * u.m
qt = table.QTable([q])
qt.add_row(([5, 6] * u.km,))
assert np.all(qt['col0'] == [[1, 2], [3, 4], [5000, 6000]] * u.m)
def test_add_with_tuple(self, table_types):
self._setup(table_types)
t = self.t
t.add_row((4, 7.2, '1'))
assert len(t) == 4
assert np.all(t['a'] == np.array([1, 2, 3, 4]))
assert np.allclose(t['b'], np.array([4.0, 5.1, 6.2, 7.2]))
assert np.all(t['c'] == np.array(['7', '8', '9', '1']))
def test_add_with_list(self, table_types):
self._setup(table_types)
t = self.t
t.add_row([4, 7.2, '10'])
assert len(t) == 4
assert np.all(t['a'] == np.array([1, 2, 3, 4]))
assert np.allclose(t['b'], np.array([4.0, 5.1, 6.2, 7.2]))
assert np.all(t['c'] == np.array(['7', '8', '9', '10']))
def test_add_with_dict(self, table_types):
self._setup(table_types)
t = self.t
t.add_row({'a': 4, 'b': 7.2})
assert len(t) == 4
assert np.all(t['a'] == np.array([1, 2, 3, 4]))
assert np.allclose(t['b'], np.array([4.0, 5.1, 6.2, 7.2]))
if t.masked:
assert np.all(t['c'] == np.array(['7', '8', '9', '7']))
else:
assert np.all(t['c'] == np.array(['7', '8', '9', '']))
def test_add_with_none(self, table_types):
self._setup(table_types)
t = self.t
t.add_row()
assert len(t) == 4
assert np.all(t['a'].data == np.array([1, 2, 3, 0]))
assert np.allclose(t['b'], np.array([4.0, 5.1, 6.2, 0.0]))
assert np.all(t['c'].data == np.array(['7', '8', '9', '']))
def test_add_missing_column(self, table_types):
self._setup(table_types)
t = self.t
with pytest.raises(ValueError):
t.add_row({'bad_column': 1})
def test_wrong_size_tuple(self, table_types):
self._setup(table_types)
t = self.t
with pytest.raises(ValueError):
t.add_row((1, 2))
def test_wrong_vals_type(self, table_types):
self._setup(table_types)
t = self.t
with pytest.raises(TypeError):
t.add_row(1)
def test_add_row_failures(self, table_types):
self._setup(table_types)
t = self.t
t_copy = table_types.Table(t, copy=True)
# Wrong number of columns
try:
t.add_row([1, 2, 3, 4])
except ValueError:
pass
assert len(t) == 3
assert np.all(t.as_array() == t_copy.as_array())
# Wrong data type
try:
t.add_row(['one', 2, 3])
except ValueError:
pass
assert len(t) == 3
assert np.all(t.as_array() == t_copy.as_array())
def test_insert_table_row(self, table_types):
"""
Light testing of Table.insert_row() method. The deep testing is done via
the add_row() tests which calls insert_row(index=len(self), ...), so
here just test that the added index parameter is handled correctly.
"""
self._setup(table_types)
row = (10, 40.0, 'x', [10, 20])
for index in range(-3, 4):
indices = np.insert(np.arange(3), index, 3)
t = table_types.Table([self.a, self.b, self.c, self.d])
t2 = t.copy()
t.add_row(row) # By now we know this works
t2.insert_row(index, row)
for name in t.colnames:
if t[name].dtype.kind == 'f':
assert np.allclose(t[name][indices], t2[name])
else:
assert np.all(t[name][indices] == t2[name])
for index in (-4, 4):
t = table_types.Table([self.a, self.b, self.c, self.d])
with pytest.raises(IndexError):
t.insert_row(index, row)
@pytest.mark.usefixtures('table_types')
class TestTableColumn(SetupData):
def test_column_view(self, table_types):
self._setup(table_types)
t = self.t
a = t.columns['a']
a[2] = 10
assert t['a'][2] == 10
@pytest.mark.usefixtures('table_types')
class TestArrayColumns(SetupData):
def test_1d(self, table_types):
self._setup(table_types)
b = table_types.Column(name='b', dtype=int, shape=(2, ), length=3)
t = table_types.Table([self.a])
t.add_column(b)
assert t['b'].shape == (3, 2)
assert t['b'][0].shape == (2, )
def test_2d(self, table_types):
self._setup(table_types)
b = table_types.Column(name='b', dtype=int, shape=(2, 4), length=3)
t = table_types.Table([self.a])
t.add_column(b)
assert t['b'].shape == (3, 2, 4)
assert t['b'][0].shape == (2, 4)
def test_3d(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a])
b = table_types.Column(name='b', dtype=int, shape=(2, 4, 6), length=3)
t.add_column(b)
assert t['b'].shape == (3, 2, 4, 6)
assert t['b'][0].shape == (2, 4, 6)
@pytest.mark.usefixtures('table_types')
class TestRemove(SetupData):
@property
def t(self):
if self._table_type is not None:
if not hasattr(self, '_t'):
self._t = self._table_type([self.a])
return self._t
@property
def t2(self):
if self._table_type is not None:
if not hasattr(self, '_t2'):
self._t2 = self._table_type([self.a, self.b, self.c])
return self._t2
def test_1(self, table_types):
self._setup(table_types)
self.t.remove_columns('a')
assert self.t.colnames == []
assert self.t.as_array().size == 0
# Regression test for gh-8640
assert not self.t
assert isinstance(self.t == None, np.ndarray) # noqa
assert (self.t == None).size == 0 # noqa
def test_2(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.remove_columns('a')
assert self.t.colnames == ['b']
assert self.t.dtype.names == ('b',)
assert np.all(self.t['b'] == np.array([4, 5, 6]))
def test_3(self, table_types):
"""Check remove_columns works for a single column with a name of
more than one character. Regression test against #2699"""
self._setup(table_types)
self.t['new_column'] = self.t['a']
assert 'new_column' in self.t.columns.keys()
self.t.remove_columns('new_column')
assert 'new_column' not in self.t.columns.keys()
def test_remove_nonexistent_row(self, table_types):
self._setup(table_types)
with pytest.raises(IndexError):
self.t.remove_row(4)
def test_remove_row_0(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
self.t.remove_row(0)
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['b'] == np.array([5, 6]))
def test_remove_row_1(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
self.t.remove_row(1)
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['a'] == np.array([1, 3]))
def test_remove_row_2(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
self.t.remove_row(2)
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['c'] == np.array([7, 8]))
def test_remove_row_slice(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
self.t.remove_rows(slice(0, 2, 1))
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['c'] == np.array([9]))
def test_remove_row_list(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
self.t.remove_rows([0, 2])
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['c'] == np.array([8]))
def test_remove_row_preserves_meta(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.remove_rows([0, 2])
assert self.t['a'].meta == {'aa': [0, 1, 2, 3, 4]}
assert self.t.dtype == np.dtype([('a', 'int'),
('b', 'int')])
def test_delitem_row(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
del self.t[1]
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['a'] == np.array([1, 3]))
@pytest.mark.parametrize("idx", [[0, 2], np.array([0, 2])])
def test_delitem_row_list(self, table_types, idx):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
del self.t[idx]
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['c'] == np.array([8]))
def test_delitem_row_slice(self, table_types):
self._setup(table_types)
self.t.add_column(self.b)
self.t.add_column(self.c)
del self.t[0:2]
assert self.t.colnames == ['a', 'b', 'c']
assert np.all(self.t['c'] == np.array([9]))
def test_delitem_row_fail(self, table_types):
self._setup(table_types)
with pytest.raises(IndexError):
del self.t[4]
def test_delitem_row_float(self, table_types):
self._setup(table_types)
with pytest.raises(IndexError):
del self.t[1.]
def test_delitem1(self, table_types):
self._setup(table_types)
del self.t['a']
assert self.t.colnames == []
assert self.t.as_array().size == 0
# Regression test for gh-8640
assert not self.t
assert isinstance(self.t == None, np.ndarray) # noqa
assert (self.t == None).size == 0 # noqa
def test_delitem2(self, table_types):
self._setup(table_types)
del self.t2['b']
assert self.t2.colnames == ['a', 'c']
def test_delitems(self, table_types):
self._setup(table_types)
del self.t2['a', 'b']
assert self.t2.colnames == ['c']
def test_delitem_fail(self, table_types):
self._setup(table_types)
with pytest.raises(KeyError):
del self.t['d']
@pytest.mark.usefixtures('table_types')
class TestKeep(SetupData):
def test_1(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.keep_columns([])
assert t.colnames == []
assert t.as_array().size == 0
# Regression test for gh-8640
assert not t
assert isinstance(t == None, np.ndarray) # noqa
assert (t == None).size == 0 # noqa
def test_2(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.keep_columns('b')
assert t.colnames == ['b']
assert t.dtype.names == ('b',)
assert np.all(t['b'] == np.array([4, 5, 6]))
@pytest.mark.usefixtures('table_types')
class TestRename(SetupData):
def test_1(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a])
t.rename_column('a', 'b')
assert t.colnames == ['b']
assert t.dtype.names == ('b',)
assert np.all(t['b'] == np.array([1, 2, 3]))
def test_2(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.rename_column('a', 'c')
t.rename_column('b', 'a')
assert t.colnames == ['c', 'a']
assert t.dtype.names == ('c', 'a')
if t.masked:
assert t.mask.dtype.names == ('c', 'a')
assert np.all(t['c'] == np.array([1, 2, 3]))
assert np.all(t['a'] == np.array([4, 5, 6]))
def test_rename_by_attr(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t['a'].name = 'c'
t['b'].name = 'a'
assert t.colnames == ['c', 'a']
assert t.dtype.names == ('c', 'a')
assert np.all(t['c'] == np.array([1, 2, 3]))
assert np.all(t['a'] == np.array([4, 5, 6]))
def test_rename_columns(self, table_types):
self._setup(table_types)
t = table_types.Table([self.a, self.b, self.c])
t.rename_columns(('a', 'b', 'c'), ('aa', 'bb', 'cc'))
assert t.colnames == ['aa', 'bb', 'cc']
t.rename_columns(['bb', 'cc'], ['b', 'c'])
assert t.colnames == ['aa', 'b', 'c']
with pytest.raises(TypeError):
t.rename_columns(('aa'), ['a'])
with pytest.raises(ValueError):
t.rename_columns(['a'], ['b', 'c'])
@pytest.mark.usefixtures('table_types')
class TestSort():
def test_single(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a', data=[2, 1, 3]))
t.add_column(table_types.Column(name='b', data=[6, 5, 4]))
t.add_column(table_types.Column(name='c', data=[(1, 2), (3, 4), (4, 5)]))
assert np.all(t['a'] == np.array([2, 1, 3]))
assert np.all(t['b'] == np.array([6, 5, 4]))
t.sort('a')
assert np.all(t['a'] == np.array([1, 2, 3]))
assert np.all(t['b'] == np.array([5, 6, 4]))
assert np.all(t['c'] == np.array([[3, 4],
[1, 2],
[4, 5]]))
t.sort('b')
assert np.all(t['a'] == np.array([3, 1, 2]))
assert np.all(t['b'] == np.array([4, 5, 6]))
assert np.all(t['c'] == np.array([[4, 5],
[3, 4],
[1, 2]]))
@pytest.mark.parametrize('create_index', [False, True])
def test_single_reverse(self, table_types, create_index):
t = table_types.Table()
t.add_column(table_types.Column(name='a', data=[2, 1, 3]))
t.add_column(table_types.Column(name='b', data=[6, 5, 4]))
t.add_column(table_types.Column(name='c', data=[(1, 2), (3, 4), (4, 5)]))
assert np.all(t['a'] == np.array([2, 1, 3]))
assert np.all(t['b'] == np.array([6, 5, 4]))
t.sort('a', reverse=True)
assert np.all(t['a'] == np.array([3, 2, 1]))
assert np.all(t['b'] == np.array([4, 6, 5]))
assert np.all(t['c'] == np.array([[4, 5],
[1, 2],
[3, 4]]))
t.sort('b', reverse=True)
assert np.all(t['a'] == np.array([2, 1, 3]))
assert np.all(t['b'] == np.array([6, 5, 4]))
assert np.all(t['c'] == np.array([[1, 2],
[3, 4],
[4, 5]]))
def test_single_big(self, table_types):
"""Sort a big-ish table with a non-trivial sort order"""
x = np.arange(10000)
y = np.sin(x)
t = table_types.Table([x, y], names=('x', 'y'))
t.sort('y')
idx = np.argsort(y)
assert np.all(t['x'] == x[idx])
assert np.all(t['y'] == y[idx])
@pytest.mark.parametrize('reverse', [True, False])
def test_empty_reverse(self, table_types, reverse):
t = table_types.Table([[], []], dtype=['f4', 'U1'])
t.sort('col1', reverse=reverse)
def test_multiple(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a', data=[2, 1, 3, 2, 3, 1]))
t.add_column(table_types.Column(name='b', data=[6, 5, 4, 3, 5, 4]))
assert np.all(t['a'] == np.array([2, 1, 3, 2, 3, 1]))
assert np.all(t['b'] == np.array([6, 5, 4, 3, 5, 4]))
t.sort(['a', 'b'])
assert np.all(t['a'] == np.array([1, 1, 2, 2, 3, 3]))
assert np.all(t['b'] == np.array([4, 5, 3, 6, 4, 5]))
t.sort(['b', 'a'])
assert np.all(t['a'] == np.array([2, 1, 3, 1, 3, 2]))
assert np.all(t['b'] == np.array([3, 4, 4, 5, 5, 6]))
t.sort(('a', 'b'))
assert np.all(t['a'] == np.array([1, 1, 2, 2, 3, 3]))
assert np.all(t['b'] == np.array([4, 5, 3, 6, 4, 5]))
def test_multiple_reverse(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a', data=[2, 1, 3, 2, 3, 1]))
t.add_column(table_types.Column(name='b', data=[6, 5, 4, 3, 5, 4]))
assert np.all(t['a'] == np.array([2, 1, 3, 2, 3, 1]))
assert np.all(t['b'] == np.array([6, 5, 4, 3, 5, 4]))
t.sort(['a', 'b'], reverse=True)
assert np.all(t['a'] == np.array([3, 3, 2, 2, 1, 1]))
assert np.all(t['b'] == np.array([5, 4, 6, 3, 5, 4]))
t.sort(['b', 'a'], reverse=True)
assert np.all(t['a'] == np.array([2, 3, 1, 3, 1, 2]))
assert np.all(t['b'] == np.array([6, 5, 5, 4, 4, 3]))
t.sort(('a', 'b'), reverse=True)
assert np.all(t['a'] == np.array([3, 3, 2, 2, 1, 1]))
assert np.all(t['b'] == np.array([5, 4, 6, 3, 5, 4]))
def test_multiple_with_bytes(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='firstname', data=[b"Max", b"Jo", b"John"]))
t.add_column(table_types.Column(name='name', data=[b"Miller", b"Miller", b"Jackson"]))
t.add_column(table_types.Column(name='tel', data=[12, 15, 19]))
t.sort(['name', 'firstname'])
assert np.all([t['firstname'] == np.array([b"John", b"Jo", b"Max"])])
assert np.all([t['name'] == np.array([b"Jackson", b"Miller", b"Miller"])])
assert np.all([t['tel'] == np.array([19, 15, 12])])
def test_multiple_with_unicode(self, table_types):
# Before Numpy 1.6.2, sorting with multiple column names
# failed when a unicode column was present.
t = table_types.Table()
t.add_column(table_types.Column(
name='firstname',
data=[str(x) for x in ["Max", "Jo", "John"]]))
t.add_column(table_types.Column(
name='name',
data=[str(x) for x in ["Miller", "Miller", "Jackson"]]))
t.add_column(table_types.Column(name='tel', data=[12, 15, 19]))
t.sort(['name', 'firstname'])
assert np.all([t['firstname'] == np.array(
[str(x) for x in ["John", "Jo", "Max"]])])
assert np.all([t['name'] == np.array(
[str(x) for x in ["Jackson", "Miller", "Miller"]])])
assert np.all([t['tel'] == np.array([19, 15, 12])])
def test_argsort(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='a', data=[2, 1, 3, 2, 3, 1]))
t.add_column(table_types.Column(name='b', data=[6, 5, 4, 3, 5, 4]))
assert np.all(t.argsort() == t.as_array().argsort())
i0 = t.argsort('a')
i1 = t.as_array().argsort(order=['a'])
assert np.all(t['a'][i0] == t['a'][i1])
i0 = t.argsort(['a', 'b'])
i1 = t.as_array().argsort(order=['a', 'b'])
assert np.all(t['a'][i0] == t['a'][i1])
assert np.all(t['b'][i0] == t['b'][i1])
@pytest.mark.parametrize('add_index', [False, True])
def test_argsort_reverse(self, table_types, add_index):
t = table_types.Table()
t.add_column(table_types.Column(name='a', data=[2, 1, 3, 2, 3, 1]))
t.add_column(table_types.Column(name='b', data=[6, 5, 4, 3, 5, 4]))
if add_index:
t.add_index('a')
assert np.all(t.argsort(reverse=True) == np.array([4, 2, 0, 3, 1, 5]))
i0 = t.argsort('a', reverse=True)
i1 = np.array([4, 2, 3, 0, 5, 1])
assert np.all(t['a'][i0] == t['a'][i1])
i0 = t.argsort(['a', 'b'], reverse=True)
i1 = np.array([4, 2, 0, 3, 1, 5])
assert np.all(t['a'][i0] == t['a'][i1])
assert np.all(t['b'][i0] == t['b'][i1])
def test_argsort_bytes(self, table_types):
t = table_types.Table()
t.add_column(table_types.Column(name='firstname', data=[b"Max", b"Jo", b"John"]))
t.add_column(table_types.Column(name='name', data=[b"Miller", b"Miller", b"Jackson"]))
t.add_column(table_types.Column(name='tel', data=[12, 15, 19]))
assert np.all(t.argsort(['name', 'firstname']) == np.array([2, 1, 0]))
def test_argsort_unicode(self, table_types):
# Before Numpy 1.6.2, sorting with multiple column names
# failed when a unicode column was present.
t = table_types.Table()
t.add_column(table_types.Column(
name='firstname',
data=[str(x) for x in ["Max", "Jo", "John"]]))
t.add_column(table_types.Column(
name='name',
data=[str(x) for x in ["Miller", "Miller", "Jackson"]]))
t.add_column(table_types.Column(name='tel', data=[12, 15, 19]))
assert np.all(t.argsort(['name', 'firstname']) == np.array([2, 1, 0]))
def test_rebuild_column_view_then_rename(self, table_types):
"""
Issue #2039 where renaming fails after any method that calls
_rebuild_table_column_view (this includes sort and add_row).
"""
t = table_types.Table([[1]], names=('a',))
assert t.colnames == ['a']
assert t.dtype.names == ('a',)
t.add_row((2,))
assert t.colnames == ['a']
assert t.dtype.names == ('a',)
t.rename_column('a', 'b')
assert t.colnames == ['b']
assert t.dtype.names == ('b',)
t.sort('b')
assert t.colnames == ['b']
assert t.dtype.names == ('b',)
t.rename_column('b', 'c')
assert t.colnames == ['c']
assert t.dtype.names == ('c',)
@pytest.mark.parametrize('kwargs', [{}, {'kind': 'stable'}, {'kind': 'quicksort'}])
def test_sort_kind(kwargs):
t = Table()
t['a'] = [2, 1, 3, 2, 3, 1]
t['b'] = [6, 5, 4, 3, 5, 4]
t_struct = t.as_array()
# Since sort calls Table.argsort this covers `kind` for both methods
t.sort(['a', 'b'], **kwargs)
assert np.all(t.as_array() == np.sort(t_struct, **kwargs))
@pytest.mark.usefixtures('table_types')
class TestIterator():
def test_iterator(self, table_types):
d = np.array([(2, 1),
(3, 6),
(4, 5)], dtype=[('a', 'i4'), ('b', 'i4')])
t = table_types.Table(d)
if t.masked:
with pytest.raises(ValueError):
t[0] == d[0]
else:
for row, np_row in zip(t, d):
assert np.all(row == np_row)
@pytest.mark.usefixtures('table_types')
class TestSetMeta():
def test_set_meta(self, table_types):
d = table_types.Table(names=('a', 'b'))
d.meta['a'] = 1
d.meta['b'] = 1
d.meta['c'] = 1
d.meta['d'] = 1
assert list(d.meta.keys()) == ['a', 'b', 'c', 'd']
@pytest.mark.usefixtures('table_types')
class TestConvertNumpyArray():
def test_convert_numpy_array(self, table_types):
d = table_types.Table([[1, 2], [3, 4]], names=('a', 'b'))
np_data = np.array(d)
if table_types.Table is not MaskedTable:
assert np.all(np_data == d.as_array())
assert np_data is not d.as_array()
assert d.colnames == list(np_data.dtype.names)
np_data = np.array(d, copy=False)
if table_types.Table is not MaskedTable:
assert np.all(np_data == d.as_array())
assert d.colnames == list(np_data.dtype.names)
with pytest.raises(ValueError):
np_data = np.array(d, dtype=[('c', 'i8'), ('d', 'i8')])
def test_as_array_byteswap(self, table_types):
"""Test for https://github.com/astropy/astropy/pull/4080"""
byte_orders = ('>', '<')
native_order = byte_orders[sys.byteorder == 'little']
for order in byte_orders:
col = table_types.Column([1.0, 2.0], name='a', dtype=order + 'f8')
t = table_types.Table([col])
arr = t.as_array()
assert arr['a'].dtype.byteorder in (native_order, '=')
arr = t.as_array(keep_byteorder=True)
if order == native_order:
assert arr['a'].dtype.byteorder in (order, '=')
else:
assert arr['a'].dtype.byteorder == order
def test_byteswap_fits_array(self, table_types):
"""
Test for https://github.com/astropy/astropy/pull/4080, demonstrating
that FITS tables are converted to native byte order.
"""
non_native_order = ('>', '<')[sys.byteorder != 'little']
filename = get_pkg_data_filename('data/tb.fits',
'astropy.io.fits.tests')
t = table_types.Table.read(filename)
arr = t.as_array()
for idx in range(len(arr.dtype)):
assert arr.dtype[idx].byteorder != non_native_order
with fits.open(filename, character_as_bytes=True) as hdul:
data = hdul[1].data
for colname in data.columns.names:
assert np.all(data[colname] == arr[colname])
arr2 = t.as_array(keep_byteorder=True)
for colname in data.columns.names:
assert (data[colname].dtype.byteorder
== arr2[colname].dtype.byteorder)
def _assert_copies(t, t2, deep=True):
assert t.colnames == t2.colnames
np.testing.assert_array_equal(t.as_array(), t2.as_array())
assert t.meta == t2.meta
for col, col2 in zip(t.columns.values(), t2.columns.values()):
if deep:
assert not np.may_share_memory(col, col2)
else:
assert np.may_share_memory(col, col2)
def test_copy():
t = table.Table([[1, 2, 3], [2, 3, 4]], names=['x', 'y'])
t2 = t.copy()
_assert_copies(t, t2)
def test_copy_masked():
t = table.Table([[1, 2, 3], [2, 3, 4]], names=['x', 'y'], masked=True,
meta={'name': 'test'})
t['x'].mask == [True, False, True]
t2 = t.copy()
_assert_copies(t, t2)
def test_copy_protocol():
t = table.Table([[1, 2, 3], [2, 3, 4]], names=['x', 'y'])
t2 = copy.copy(t)
t3 = copy.deepcopy(t)
_assert_copies(t, t2, deep=False)
_assert_copies(t, t3)
def test_disallow_inequality_comparisons():
"""
Regression test for #828 - disallow comparison operators on whole Table
"""
t = table.Table()
with pytest.raises(TypeError):
t > 2
with pytest.raises(TypeError):
t < 1.1
with pytest.raises(TypeError):
t >= 5.5
with pytest.raises(TypeError):
t <= -1.1
def test_values_equal_part1():
col1 = [1, 2]
col2 = [1.0, 2.0]
col3 = ['a', 'b']
t1 = table.Table([col1, col2, col3], names=['a', 'b', 'c'])
t2 = table.Table([col1, col2], names=['a', 'b'])
t3 = table.table_helpers.simple_table()
tm = t1.copy()
tm['time'] = Time([1, 2], format='cxcsec')
tm1 = tm.copy()
tm1['time'][0] = np.ma.masked
tq = table.table_helpers.simple_table()
tq['quantity'] = [1., 2., 3.] * u.m
tsk = table.table_helpers.simple_table()
tsk['sk'] = SkyCoord(1, 2, unit='deg')
eqsk = tsk.values_equal(tsk)
for col in eqsk.itercols():
assert np.all(col)
with pytest.raises(ValueError, match='cannot compare tables with different column names'):
t2.values_equal(t1)
with pytest.raises(ValueError, match='unable to compare column a'):
# Shape mismatch
t3.values_equal(t1)
with pytest.raises(ValueError, match='unable to compare column c'):
# Type mismatch in column c causes FutureWarning
t1.values_equal(2)
with pytest.raises(ValueError, match='unable to compare column c'):
t1.values_equal([1, 2])
eq = t2.values_equal(t2)
for col in eq.colnames:
assert np.all(eq[col] == [True, True])
eq1 = tm1.values_equal(tm)
for col in eq1.colnames:
assert np.all(eq1[col] == [True, True])
eq2 = tq.values_equal(tq)
for col in eq2.colnames:
assert np.all(eq2[col] == [True, True, True])
eq3 = t2.values_equal(2)
for col in eq3.colnames:
assert np.all(eq3[col] == [False, True])
eq4 = t2.values_equal([1, 2])
for col in eq4.colnames:
assert np.all(eq4[col] == [True, True])
# Compare table to its first row
t = table.Table(rows=[(1, 'a'),
(1, 'b')])
eq = t.values_equal(t[0])
assert np.all(eq['col0'] == [True, True])
assert np.all(eq['col1'] == [True, False])
def test_rows_equal():
t = table.Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 a 4.0 3',
' 0 a 0.0 4',
' 1 b 3.0 5',
' 1 a 2.0 6',
' 1 a 1.0 7'],
format='ascii')
# All rows are equal
assert np.all(t == t)
# Assert no rows are different
assert not np.any(t != t)
# Check equality result for a given row
assert np.all((t == t[3]) == np.array([0, 0, 0, 1, 0, 0, 0, 0], dtype=bool))
# Check inequality result for a given row
assert np.all((t != t[3]) == np.array([1, 1, 1, 0, 1, 1, 1, 1], dtype=bool))
t2 = table.Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 3 b 6.0 2',
' 2 a 4.0 3',
' 0 a 1.0 4',
' 1 b 3.0 5',
' 1 c 2.0 6',
' 1 a 1.0 7',
], format='ascii')
# In the above cases, Row.__eq__ gets called, but now need to make sure
# Table.__eq__ also gets called.
assert np.all((t == t2) == np.array([1, 1, 0, 1, 0, 1, 0, 1], dtype=bool))
assert np.all((t != t2) == np.array([0, 0, 1, 0, 1, 0, 1, 0], dtype=bool))
# Check that comparing to a structured array works
assert np.all((t == t2.as_array()) == np.array([1, 1, 0, 1, 0, 1, 0, 1], dtype=bool))
assert np.all((t.as_array() == t2) == np.array([1, 1, 0, 1, 0, 1, 0, 1], dtype=bool))
def test_equality_masked():
t = table.Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 a 4.0 3',
' 0 a 0.0 4',
' 1 b 3.0 5',
' 1 a 2.0 6',
' 1 a 1.0 7',
], format='ascii')
# Make into masked table
t = table.Table(t, masked=True)
# All rows are equal
assert np.all(t == t)
# Assert no rows are different
assert not np.any(t != t)
# Check equality result for a given row
assert np.all((t == t[3]) == np.array([0, 0, 0, 1, 0, 0, 0, 0], dtype=bool))
# Check inequality result for a given row
assert np.all((t != t[3]) == np.array([1, 1, 1, 0, 1, 1, 1, 1], dtype=bool))
t2 = table.Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 3 b 6.0 2',
' 2 a 4.0 3',
' 0 a 1.0 4',
' 1 b 3.0 5',
' 1 c 2.0 6',
' 1 a 1.0 7',
], format='ascii')
# In the above cases, Row.__eq__ gets called, but now need to make sure
# Table.__eq__ also gets called.
assert np.all((t == t2) == np.array([1, 1, 0, 1, 0, 1, 0, 1], dtype=bool))
assert np.all((t != t2) == np.array([0, 0, 1, 0, 1, 0, 1, 0], dtype=bool))
# Check that masking a value causes the row to differ
t.mask['a'][0] = True
assert np.all((t == t2) == np.array([0, 1, 0, 1, 0, 1, 0, 1], dtype=bool))
assert np.all((t != t2) == np.array([1, 0, 1, 0, 1, 0, 1, 0], dtype=bool))
# Check that comparing to a structured array works
assert np.all((t == t2.as_array()) == np.array([0, 1, 0, 1, 0, 1, 0, 1], dtype=bool))
@pytest.mark.xfail
def test_equality_masked_bug():
"""
This highlights a Numpy bug. Once it works, it can be moved into the
test_equality_masked test. Related Numpy bug report:
https://github.com/numpy/numpy/issues/3840
"""
t = table.Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 a 4.0 3',
' 0 a 0.0 4',
' 1 b 3.0 5',
' 1 a 2.0 6',
' 1 a 1.0 7',
], format='ascii')
t = table.Table(t, masked=True)
t2 = table.Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 3 b 6.0 2',
' 2 a 4.0 3',
' 0 a 1.0 4',
' 1 b 3.0 5',
' 1 c 2.0 6',
' 1 a 1.0 7',
], format='ascii')
assert np.all((t.as_array() == t2) == np.array([0, 1, 0, 1, 0, 1, 0, 1], dtype=bool))
# Check that the meta descriptor is working as expected. The MetaBaseTest class
# takes care of defining all the tests, and we simply have to define the class
# and any minimal set of args to pass.
class TestMetaTable(MetaBaseTest):
test_class = table.Table
args = ()
def test_unicode_content():
# If we don't have unicode literals then return
if isinstance('', bytes):
return
# Define unicode literals
string_a = 'астрономическая питона'
string_b = 'миллиарды световых лет'
a = table.Table(
[[string_a, 2],
[string_b, 3]],
names=('a', 'b'))
assert string_a in str(a)
# This only works because the coding of this file is utf-8, which
# matches the default encoding of Table.__str__
assert string_a.encode('utf-8') in bytes(a)
def test_unicode_policy():
t = table.Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 a 4.0 3',
' 0 a 0.0 4',
' 1 b 3.0 5',
' 1 a 2.0 6',
' 1 a 1.0 7',
], format='ascii')
assert_follows_unicode_guidelines(t)
@pytest.mark.parametrize('uni', ['питона', 'ascii'])
def test_unicode_bytestring_conversion(table_types, uni):
"""
Test converting columns to all unicode or all bytestring. This
makes two columns, one which is unicode (str in Py3) and one which
is bytes (UTF-8 encoded). There are two code paths in the conversions,
a faster one where the data are actually ASCII and a slower one where
UTF-8 conversion is required. This tests both via the ``uni`` param.
"""
byt = uni.encode('utf-8')
t = table_types.Table([[byt], [uni], [1]], dtype=('S', 'U', 'i'))
assert t['col0'].dtype.kind == 'S'
assert t['col1'].dtype.kind == 'U'
assert t['col2'].dtype.kind == 'i'
t['col0'].description = 'col0'
t['col1'].description = 'col1'
t['col0'].meta['val'] = 'val0'
t['col1'].meta['val'] = 'val1'
# Unicode to bytestring
t1 = t.copy()
t1.convert_unicode_to_bytestring()
assert t1['col0'].dtype.kind == 'S'
assert t1['col1'].dtype.kind == 'S'
assert t1['col2'].dtype.kind == 'i'
# Meta made it through
assert t1['col0'].description == 'col0'
assert t1['col1'].description == 'col1'
assert t1['col0'].meta['val'] == 'val0'
assert t1['col1'].meta['val'] == 'val1'
# Need to de-fang the automatic unicode sandwiching of Table
assert np.array(t1['col0'])[0] == byt
assert np.array(t1['col1'])[0] == byt
assert np.array(t1['col2'])[0] == 1
# Bytestring to unicode
t1 = t.copy()
t1.convert_bytestring_to_unicode()
assert t1['col0'].dtype.kind == 'U'
assert t1['col1'].dtype.kind == 'U'
assert t1['col2'].dtype.kind == 'i'
# Meta made it through
assert t1['col0'].description == 'col0'
assert t1['col1'].description == 'col1'
assert t1['col0'].meta['val'] == 'val0'
assert t1['col1'].meta['val'] == 'val1'
# No need to de-fang the automatic unicode sandwiching of Table here, but
# do just for consistency to prove things are working.
assert np.array(t1['col0'])[0] == uni
assert np.array(t1['col1'])[0] == uni
assert np.array(t1['col2'])[0] == 1
def test_table_deletion():
"""
Regression test for the reference cycle discussed in
https://github.com/astropy/astropy/issues/2877
"""
deleted = set()
# A special table subclass which leaves a record when it is finalized
class TestTable(table.Table):
def __del__(self):
deleted.add(id(self))
t = TestTable({'a': [1, 2, 3]})
the_id = id(t)
assert t['a'].parent_table is t
del t
# Cleanup
gc.collect()
assert the_id in deleted
def test_nested_iteration():
"""
Regression test for issue 3358 where nested iteration over a single table fails.
"""
t = table.Table([[0, 1]], names=['a'])
out = []
for r1 in t:
for r2 in t:
out.append((r1['a'], r2['a']))
assert out == [(0, 0), (0, 1), (1, 0), (1, 1)]
def test_table_init_from_degenerate_arrays(table_types):
t = table_types.Table(np.array([]))
assert len(t.columns) == 0
with pytest.raises(ValueError):
t = table_types.Table(np.array(0))
t = table_types.Table(np.array([1, 2, 3]))
assert len(t.columns) == 3
@pytest.mark.skipif('not HAS_PANDAS')
class TestPandas:
def test_simple(self):
t = table.Table()
for endian in ['<', '>', '=']:
for kind in ['f', 'i']:
for byte in ['2', '4', '8']:
dtype = np.dtype(endian + kind + byte)
x = np.array([1, 2, 3], dtype=dtype)
t[endian + kind + byte] = x.newbyteorder(endian)
t['u'] = ['a', 'b', 'c']
t['s'] = ['a', 'b', 'c']
d = t.to_pandas()
for column in t.columns:
if column == 'u':
assert np.all(t['u'] == np.array(['a', 'b', 'c']))
assert d[column].dtype == np.dtype("O") # upstream feature of pandas
elif column == 's':
assert np.all(t['s'] == np.array(['a', 'b', 'c']))
assert d[column].dtype == np.dtype("O") # upstream feature of pandas
else:
# We should be able to compare exact values here
assert np.all(t[column] == d[column])
if t[column].dtype.isnative:
assert d[column].dtype == t[column].dtype
else:
assert d[column].dtype == t[column].byteswap().newbyteorder().dtype
# Regression test for astropy/astropy#1156 - the following code gave a
# ValueError: Big-endian buffer not supported on little-endian
# compiler. We now automatically swap the endian-ness to native order
# upon adding the arrays to the data frame.
# Explicitly testing little/big/native endian separately -
# regression for a case in astropy/astropy#11286 not caught by #3729.
d[['<i4', '>i4']]
d[['<f4', '>f4']]
t2 = table.Table.from_pandas(d)
for column in t.columns:
if column in ('u', 's'):
assert np.all(t[column] == t2[column])
else:
assert_allclose(t[column], t2[column])
if t[column].dtype.isnative:
assert t[column].dtype == t2[column].dtype
else:
assert t[column].byteswap().newbyteorder().dtype == t2[column].dtype
@pytest.mark.parametrize('unsigned', ['u', ''])
@pytest.mark.parametrize('bits', [8, 16, 32, 64])
def test_nullable_int(self, unsigned, bits):
np_dtype = f'{unsigned}int{bits}'
c = MaskedColumn([1, 2], mask=[False, True], dtype=np_dtype)
t = Table([c])
df = t.to_pandas()
pd_dtype = np_dtype.replace('i', 'I').replace('u', 'U')
assert str(df['col0'].dtype) == pd_dtype
t2 = Table.from_pandas(df)
assert str(t2['col0'].dtype) == np_dtype
assert np.all(t2['col0'].mask == [False, True])
assert np.all(t2['col0'] == c)
def test_2d(self):
t = table.Table()
t['a'] = [1, 2, 3]
t['b'] = np.ones((3, 2))
with pytest.raises(ValueError,
match='Cannot convert a table with multidimensional columns'):
t.to_pandas()
def test_mixin_pandas(self):
t = table.QTable()
for name in sorted(MIXIN_COLS):
if not name.startswith('ndarray'):
t[name] = MIXIN_COLS[name]
t['dt'] = TimeDelta([0, 2, 4, 6], format='sec')
tp = t.to_pandas()
t2 = table.Table.from_pandas(tp)
assert np.allclose(t2['quantity'], [0, 1, 2, 3])
assert np.allclose(t2['longitude'], [0., 1., 5., 6.])
assert np.allclose(t2['latitude'], [5., 6., 10., 11.])
assert np.allclose(t2['skycoord.ra'], [0, 1, 2, 3])
assert np.allclose(t2['skycoord.dec'], [0, 1, 2, 3])
assert np.allclose(t2['arraywrap'], [0, 1, 2, 3])
assert np.allclose(t2['arrayswap'], [0, 1, 2, 3])
assert np.allclose(t2['earthlocation.y'], [0, 110708, 547501, 654527], rtol=0, atol=1)
# For pandas, Time, TimeDelta are the mixins that round-trip the class
assert isinstance(t2['time'], Time)
assert np.allclose(t2['time'].jyear, [2000, 2001, 2002, 2003])
assert np.all(t2['time'].isot == ['2000-01-01T12:00:00.000',
'2000-12-31T18:00:00.000',
'2002-01-01T00:00:00.000',
'2003-01-01T06:00:00.000'])
assert t2['time'].format == 'isot'
# TimeDelta
assert isinstance(t2['dt'], TimeDelta)
assert np.allclose(t2['dt'].value, [0, 2, 4, 6])
assert t2['dt'].format == 'sec'
@pytest.mark.parametrize('use_IndexedTable', [False, True])
def test_to_pandas_index(self, use_IndexedTable):
"""Test to_pandas() with different indexing options.
This also tests the fix for #12014. The exception seen there is
reproduced here without the fix.
"""
import pandas as pd
class IndexedTable(table.QTable):
"""Always index the first column"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_index(self.colnames[0])
row_index = pd.RangeIndex(0, 2, 1)
tm_index = pd.DatetimeIndex(['1998-01-01', '2002-01-01'],
dtype='datetime64[ns]',
name='tm', freq=None)
tm = Time([1998, 2002], format='jyear')
x = [1, 2]
table_cls = IndexedTable if use_IndexedTable else table.QTable
t = table_cls([tm, x], names=['tm', 'x'])
tp = t.to_pandas()
if not use_IndexedTable:
assert np.all(tp.index == row_index)
tp = t.to_pandas(index='tm')
assert np.all(tp.index == tm_index)
t.add_index('tm')
tp = t.to_pandas()
assert np.all(tp.index == tm_index)
# Make sure writing to pandas didn't hack the original table
assert t['tm'].info.indices
tp = t.to_pandas(index=True)
assert np.all(tp.index == tm_index)
tp = t.to_pandas(index=False)
assert np.all(tp.index == row_index)
with pytest.raises(ValueError) as err:
t.to_pandas(index='not a column')
assert 'index must be None, False' in str(err.value)
def test_mixin_pandas_masked(self):
tm = Time([1, 2, 3], format='cxcsec')
dt = TimeDelta([1, 2, 3], format='sec')
tm[1] = np.ma.masked
dt[1] = np.ma.masked
t = table.QTable([tm, dt], names=['tm', 'dt'])
tp = t.to_pandas()
assert np.all(tp['tm'].isnull() == [False, True, False])
assert np.all(tp['dt'].isnull() == [False, True, False])
t2 = table.Table.from_pandas(tp)
assert np.all(t2['tm'].mask == tm.mask)
assert np.ma.allclose(t2['tm'].jd, tm.jd, rtol=1e-14, atol=1e-14)
assert np.all(t2['dt'].mask == dt.mask)
assert np.ma.allclose(t2['dt'].jd, dt.jd, rtol=1e-14, atol=1e-14)
def test_from_pandas_index(self):
tm = Time([1998, 2002], format='jyear')
x = [1, 2]
t = table.Table([tm, x], names=['tm', 'x'])
tp = t.to_pandas(index='tm')
t2 = table.Table.from_pandas(tp)
assert t2.colnames == ['x']
t2 = table.Table.from_pandas(tp, index=True)
assert t2.colnames == ['tm', 'x']
assert np.allclose(t2['tm'].jyear, tm.jyear)
@pytest.mark.parametrize('use_nullable_int', [True, False])
def test_masking(self, use_nullable_int):
t = table.Table(masked=True)
t['a'] = [1, 2, 3]
t['a'].mask = [True, False, True]
t['b'] = [1., 2., 3.]
t['b'].mask = [False, False, True]
t['u'] = ['a', 'b', 'c']
t['u'].mask = [False, True, False]
t['s'] = ['a', 'b', 'c']
t['s'].mask = [False, True, False]
# https://github.com/astropy/astropy/issues/7741
t['Source'] = [2584290278794471936, 2584290038276303744,
2584288728310999296]
t['Source'].mask = [False, False, False]
if use_nullable_int: # Default
# No warning with the default use_nullable_int=True
d = t.to_pandas(use_nullable_int=use_nullable_int)
else:
with pytest.warns(TableReplaceWarning,
match=r"converted column 'a' from int(32|64) to float64"):
d = t.to_pandas(use_nullable_int=use_nullable_int)
t2 = table.Table.from_pandas(d)
for name, column in t.columns.items():
assert np.all(column.data == t2[name].data)
if hasattr(t2[name], 'mask'):
assert np.all(column.mask == t2[name].mask)
if column.dtype.kind == 'i':
if np.any(column.mask) and not use_nullable_int:
assert t2[name].dtype.kind == 'f'
else:
assert t2[name].dtype.kind == 'i'
assert_array_equal(column.data,
t2[name].data.astype(column.dtype))
else:
if column.dtype.byteorder in ('=', '|'):
assert column.dtype == t2[name].dtype
else:
assert column.byteswap().newbyteorder().dtype == t2[name].dtype
def test_units(self):
import pandas as pd
import astropy.units as u
df = pd.DataFrame({'x': [1, 2, 3], 't': [1.3, 1.2, 1.8]})
t = table.Table.from_pandas(df, units={'x': u.m, 't': u.s})
assert t['x'].unit == u.m
assert t['t'].unit == u.s
# test error if not a mapping
with pytest.raises(TypeError):
table.Table.from_pandas(df, units=[u.m, u.s])
# test warning is raised if additional columns in units dict
with pytest.warns(UserWarning) as record:
table.Table.from_pandas(df, units={'x': u.m, 't': u.s, 'y': u.m})
assert len(record) == 1
assert "{'y'}" in record[0].message.args[0]
def test_to_pandas_masked_int_data_with__index(self):
data = {"data": [0, 1, 2], "index": [10, 11, 12]}
t = table.Table(data=data, masked=True)
t.add_index("index")
t["data"].mask = [1, 1, 0]
df = t.to_pandas()
assert df["data"].iloc[-1] == 2
@pytest.mark.usefixtures('table_types')
class TestReplaceColumn(SetupData):
def test_fail_replace_column(self, table_types):
"""Raise exception when trying to replace column via table.columns object"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
with pytest.raises(ValueError,
match=r"Cannot replace column 'a'. Use "
"Table.replace_column.. instead."):
t.columns['a'] = [1, 2, 3]
with pytest.raises(ValueError, match=r"column name not there is not in the table"):
t.replace_column('not there', [1, 2, 3])
with pytest.raises(ValueError, match=r"length of new column must match table length"):
t.replace_column('a', [1, 2])
def test_replace_column(self, table_types):
"""Replace existing column with a new column"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
ta = t['a']
tb = t['b']
vals = [1.2, 3.4, 5.6]
for col in (vals,
table_types.Column(vals),
table_types.Column(vals, name='a'),
table_types.Column(vals, name='b')):
t.replace_column('a', col)
assert np.all(t['a'] == vals)
assert t['a'] is not ta # New a column
assert t['b'] is tb # Original b column unchanged
assert t.colnames == ['a', 'b']
assert t['a'].meta == {}
assert t['a'].format is None
# Special case: replacing the only column can resize table
del t['b']
assert len(t) == 3
t['a'] = [1, 2]
assert len(t) == 2
def test_replace_index_column(self, table_types):
"""Replace index column and generate expected exception"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
t.add_index('a')
with pytest.raises(ValueError) as err:
t.replace_column('a', [1, 2, 3])
assert err.value.args[0] == 'cannot replace a table index column'
def test_replace_column_no_copy(self):
t = Table([[1, 2], [3, 4]], names=['a', 'b'])
a = np.array([1.5, 2.5])
t.replace_column('a', a, copy=False)
assert t['a'][0] == a[0]
t['a'][0] = 10
assert t['a'][0] == a[0]
class TestQTableColumnConversionCornerCases:
def test_replace_with_masked_col_with_units_in_qtable(self):
"""This is a small regression from #8902"""
t = QTable([[1, 2], [3, 4]], names=['a', 'b'])
t['a'] = MaskedColumn([5, 6], unit='m')
assert isinstance(t['a'], u.Quantity)
def test_do_not_replace_string_column_with_units_in_qtable(self):
t = QTable([[1*u.m]])
with pytest.warns(AstropyUserWarning, match='convert it to Quantity failed'):
t['a'] = Column(['a'], unit=u.m)
assert isinstance(t['a'], Column)
class Test__Astropy_Table__():
"""
Test initializing a Table subclass from a table-like object that
implements the __astropy_table__ interface method.
"""
class SimpleTable:
def __init__(self):
self.columns = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9] * u.m]
self.names = ['a', 'b', 'c']
self.meta = OrderedDict([('a', 1), ('b', 2)])
def __astropy_table__(self, cls, copy, **kwargs):
a, b, c = self.columns
c.info.name = 'c'
cols = [table.Column(a, name='a'),
table.MaskedColumn(b, name='b'),
c]
names = [col.info.name for col in cols]
return cls(cols, names=names, copy=copy, meta=kwargs or self.meta)
def test_simple_1(self):
"""Make a SimpleTable and convert to Table, QTable with copy=False, True"""
for table_cls in (table.Table, table.QTable):
col_c_class = u.Quantity if table_cls is table.QTable else table.Column
for cpy in (False, True):
st = self.SimpleTable()
# Test putting in a non-native kwarg `extra_meta` to Table initializer
t = table_cls(st, copy=cpy, extra_meta='extra!')
assert t.colnames == ['a', 'b', 'c']
assert t.meta == {'extra_meta': 'extra!'}
assert np.all(t['a'] == st.columns[0])
assert np.all(t['b'] == st.columns[1])
vals = t['c'].value if table_cls is table.QTable else t['c']
assert np.all(st.columns[2].value == vals)
assert isinstance(t['a'], table.Column)
assert isinstance(t['b'], table.MaskedColumn)
assert isinstance(t['c'], col_c_class)
assert t['c'].unit is u.m
assert type(t) is table_cls
# Copy being respected?
t['a'][0] = 10
assert st.columns[0][0] == 1 if cpy else 10
def test_simple_2(self):
"""Test converting a SimpleTable and changing column names and types"""
st = self.SimpleTable()
dtypes = [np.int32, np.float32, np.float16]
names = ['a', 'b', 'c']
meta = OrderedDict([('c', 3)])
t = table.Table(st, dtype=dtypes, names=names, meta=meta)
assert t.colnames == names
assert all(col.dtype.type is dtype
for col, dtype in zip(t.columns.values(), dtypes))
# The supplied meta is overrides the existing meta. Changed in astropy 3.2.
assert t.meta != st.meta
assert t.meta == meta
def test_kwargs_exception(self):
"""If extra kwargs provided but without initializing with a table-like
object, exception is raised"""
with pytest.raises(TypeError) as err:
table.Table([[1]], extra_meta='extra!')
assert '__init__() got unexpected keyword argument' in str(err.value)
class TestUpdate():
def _setup(self):
self.a = Column((1, 2, 3), name='a')
self.b = Column((4, 5, 6), name='b')
self.c = Column((7, 8, 9), name='c')
self.d = Column((10, 11, 12), name='d')
def test_different_lengths(self):
self._setup()
t1 = Table([self.a])
t2 = Table([self.b[:-1]])
msg = 'Inconsistent data column lengths'
with pytest.raises(ValueError, match=msg):
t1.update(t2)
# If update didn't succeed then t1 and t2 should not have changed.
assert t1.colnames == ['a']
assert np.all(t1['a'] == self.a)
assert t2.colnames == ['b']
assert np.all(t2['b'] == self.b[:-1])
def test_invalid_inputs(self):
# If input is invalid then nothing should be modified.
self._setup()
t = Table([self.a])
d = {'b': self.b, 'c': [0]}
msg = 'Inconsistent data column lengths: {1, 3}'
with pytest.raises(ValueError, match=msg):
t.update(d)
assert t.colnames == ['a']
assert np.all(t['a'] == self.a)
assert d == {'b': self.b, 'c': [0]}
def test_metadata_conflict(self):
self._setup()
t1 = Table([self.a], meta={'a': 0, 'b': [0], 'c': True})
t2 = Table([self.b], meta={'a': 1, 'b': [1]})
t2meta = copy.deepcopy(t2.meta)
t1.update(t2)
assert t1.meta == {'a': 1, 'b': [0, 1], 'c': True}
# t2 metadata should not have changed.
assert t2.meta == t2meta
def test_update(self):
self._setup()
t1 = Table([self.a, self.b])
t2 = Table([self.b, self.c])
t2['b'] += 1
t1.update(t2)
assert t1.colnames == ['a', 'b', 'c']
assert np.all(t1['a'] == self.a)
assert np.all(t1['b'] == self.b+1)
assert np.all(t1['c'] == self.c)
# t2 should not have changed.
assert t2.colnames == ['b', 'c']
assert np.all(t2['b'] == self.b+1)
assert np.all(t2['c'] == self.c)
d = {'b': list(self.b), 'd': list(self.d)}
dc = copy.deepcopy(d)
t2.update(d)
assert t2.colnames == ['b', 'c', 'd']
assert np.all(t2['b'] == self.b)
assert np.all(t2['c'] == self.c)
assert np.all(t2['d'] == self.d)
# d should not have changed.
assert d == dc
# Columns were copied, so changing t2 shouldn't have affected t1.
assert t1.colnames == ['a', 'b', 'c']
assert np.all(t1['a'] == self.a)
assert np.all(t1['b'] == self.b+1)
assert np.all(t1['c'] == self.c)
def test_update_without_copy(self):
self._setup()
t1 = Table([self.a, self.b])
t2 = Table([self.b, self.c])
t1.update(t2, copy=False)
t2['b'] -= 1
assert t1.colnames == ['a', 'b', 'c']
assert np.all(t1['a'] == self.a)
assert np.all(t1['b'] == self.b-1)
assert np.all(t1['c'] == self.c)
d = {'b': np.array(self.b), 'd': np.array(self.d)}
t2.update(d, copy=False)
d['b'] *= 2
assert t2.colnames == ['b', 'c', 'd']
assert np.all(t2['b'] == 2*self.b)
assert np.all(t2['c'] == self.c)
assert np.all(t2['d'] == self.d)
def test_table_meta_copy():
"""
Test no copy vs light (key) copy vs deep copy of table meta for different
situations. #8404.
"""
t = table.Table([[1]])
meta = {1: [1, 2]}
# Assigning meta directly implies using direct object reference
t.meta = meta
assert t.meta is meta
# Table slice implies key copy, so values are unchanged
t2 = t[:]
assert t2.meta is not t.meta # NOT the same OrderedDict object but equal
assert t2.meta == t.meta
assert t2.meta[1] is t.meta[1] # Value IS the list same object
# Table init with copy=False implies key copy
t2 = table.Table(t, copy=False)
assert t2.meta is not t.meta # NOT the same OrderedDict object but equal
assert t2.meta == t.meta
assert t2.meta[1] is t.meta[1] # Value IS the same list object
# Table init with copy=True implies deep copy
t2 = table.Table(t, copy=True)
assert t2.meta is not t.meta # NOT the same OrderedDict object but equal
assert t2.meta == t.meta
assert t2.meta[1] is not t.meta[1] # Value is NOT the same list object
def test_table_meta_copy_with_meta_arg():
"""
Test no copy vs light (key) copy vs deep copy of table meta when meta is
supplied as a table init argument. #8404.
"""
meta = {1: [1, 2]}
meta2 = {2: [3, 4]}
t = table.Table([[1]], meta=meta, copy=False)
assert t.meta is meta
t = table.Table([[1]], meta=meta) # default copy=True
assert t.meta is not meta
assert t.meta == meta
# Test initializing from existing table with meta with copy=False
t2 = table.Table(t, meta=meta2, copy=False)
assert t2.meta is meta2
assert t2.meta != t.meta # Change behavior in #8404
# Test initializing from existing table with meta with default copy=True
t2 = table.Table(t, meta=meta2)
assert t2.meta is not meta2
assert t2.meta != t.meta # Change behavior in #8404
# Table init with copy=True and empty dict meta gets that empty dict
t2 = table.Table(t, copy=True, meta={})
assert t2.meta == {}
# Table init with copy=True and kwarg meta=None gets the original table dict.
# This is a somewhat ambiguous case because it could be interpreted as the
# user wanting NO meta set on the output. This could be implemented by inspecting
# call args.
t2 = table.Table(t, copy=True, meta=None)
assert t2.meta == t.meta
# Test initializing empty table with meta with copy=False
t = table.Table(meta=meta, copy=False)
assert t.meta is meta
assert t.meta[1] is meta[1]
# Test initializing empty table with meta with default copy=True (deepcopy meta)
t = table.Table(meta=meta)
assert t.meta is not meta
assert t.meta == meta
assert t.meta[1] is not meta[1]
def test_replace_column_qtable():
"""Replace existing Quantity column with a new column in a QTable"""
a = [1, 2, 3] * u.m
b = [4, 5, 6]
t = table.QTable([a, b], names=['a', 'b'])
ta = t['a']
tb = t['b']
ta.info.meta = {'aa': [0, 1, 2, 3, 4]}
ta.info.format = '%f'
t.replace_column('a', a.to('cm'))
assert np.all(t['a'] == ta)
assert t['a'] is not ta # New a column
assert t['b'] is tb # Original b column unchanged
assert t.colnames == ['a', 'b']
assert t['a'].info.meta is None
assert t['a'].info.format is None
def test_replace_update_column_via_setitem():
"""
Test table update like ``t['a'] = value``. This leverages off the
already well-tested ``replace_column`` and in-place update
``t['a'][:] = value``, so this testing is fairly light.
"""
a = [1, 2] * u.m
b = [3, 4]
t = table.QTable([a, b], names=['a', 'b'])
assert isinstance(t['a'], u.Quantity)
# Inplace update
ta = t['a']
t['a'] = 5 * u.m
assert np.all(t['a'] == [5, 5] * u.m)
assert t['a'] is ta
# Replace
t['a'] = [5, 6]
assert np.all(t['a'] == [5, 6])
assert isinstance(t['a'], table.Column)
assert t['a'] is not ta
def test_replace_update_column_via_setitem_warnings_normal():
"""
Test warnings related to table replace change in #5556:
Normal warning-free replace
"""
t = table.Table([[1, 2, 3], [4, 5, 6]], names=['a', 'b'])
with table.conf.set_temp('replace_warnings',
['refcount', 'attributes', 'slice']):
t['a'] = 0 # in-place update
t['a'] = [10, 20, 30] # replace column
def test_replace_update_column_via_setitem_warnings_slice():
"""
Test warnings related to table replace change in #5556:
Replace a slice, one warning.
"""
t = table.Table([[1, 2, 3], [4, 5, 6]], names=['a', 'b'])
with table.conf.set_temp('replace_warnings',
['refcount', 'attributes', 'slice']):
t2 = t[:2]
t2['a'] = 0 # in-place slice update
assert np.all(t['a'] == [0, 0, 3])
with pytest.warns(TableReplaceWarning, match="replaced column 'a' "
"which looks like an array slice") as w:
t2['a'] = [10, 20] # replace slice
assert len(w) == 1
def test_replace_update_column_via_setitem_warnings_attributes():
"""
Test warnings related to table replace change in #5556:
Lost attributes.
"""
t = table.Table([[1, 2, 3], [4, 5, 6]], names=['a', 'b'])
t['a'].unit = 'm'
with pytest.warns(TableReplaceWarning, match=r"replaced column 'a' "
r"and column attributes \['unit'\]") as w:
with table.conf.set_temp('replace_warnings',
['refcount', 'attributes', 'slice']):
t['a'] = [10, 20, 30]
assert len(w) == 1
def test_replace_update_column_via_setitem_warnings_refcount():
"""
Test warnings related to table replace change in #5556:
Reference count changes.
"""
t = table.Table([[1, 2, 3], [4, 5, 6]], names=['a', 'b'])
ta = t['a'] # noqa : Generate an extra reference to original column
with pytest.warns(TableReplaceWarning, match="replaced column 'a' and the "
"number of references") as w:
with table.conf.set_temp('replace_warnings',
['refcount', 'attributes', 'slice']):
t['a'] = [10, 20, 30]
assert len(w) == 1
def test_replace_update_column_via_setitem_warnings_always():
"""
Test warnings related to table replace change in #5556:
Test 'always' setting that raises warning for any replace.
"""
from inspect import currentframe, getframeinfo
t = table.Table([[1, 2, 3], [4, 5, 6]], names=['a', 'b'])
with table.conf.set_temp('replace_warnings', ['always']):
t['a'] = 0 # in-place slice update
with pytest.warns(TableReplaceWarning, match="replaced column 'a'") as w:
frameinfo = getframeinfo(currentframe())
t['a'] = [10, 20, 30] # replace column
assert len(w) == 1
# Make sure the warning points back to the user code line
assert w[0].lineno == frameinfo.lineno + 1
assert 'test_table' in w[0].filename
def test_replace_update_column_via_setitem_replace_inplace():
"""
Test the replace_inplace config option related to #5556. In this
case no replace is done.
"""
t = table.Table([[1, 2, 3], [4, 5, 6]], names=['a', 'b'])
ta = t['a']
t['a'].unit = 'm'
with table.conf.set_temp('replace_inplace', True):
with table.conf.set_temp('replace_warnings',
['always', 'refcount', 'attributes', 'slice']):
t['a'] = 0 # in-place update
assert ta is t['a']
t['a'] = [10, 20, 30] # normally replaces column, but not now
assert ta is t['a']
assert np.all(t['a'] == [10, 20, 30])
def test_primary_key_is_inherited():
"""Test whether a new Table inherits the primary_key attribute from
its parent Table. Issue #4672"""
t = table.Table([(2, 3, 2, 1), (8, 7, 6, 5)], names=('a', 'b'))
t.add_index('a')
original_key = t.primary_key
# can't test if tuples are equal, so just check content
assert original_key[0] == 'a'
t2 = t[:]
t3 = t.copy()
t4 = table.Table(t)
# test whether the reference is the same in the following
assert original_key == t2.primary_key
assert original_key == t3.primary_key
assert original_key == t4.primary_key
# just test one element, assume rest are equal if assert passes
assert t.loc[1] == t2.loc[1]
assert t.loc[1] == t3.loc[1]
assert t.loc[1] == t4.loc[1]
def test_qtable_read_for_ipac_table_with_char_columns():
'''Test that a char column of a QTable is assigned no unit and not
a dimensionless unit, otherwise conversion of reader output to
QTable fails.'''
t1 = table.QTable([["A"]], names="B")
out = StringIO()
t1.write(out, format="ascii.ipac")
t2 = table.QTable.read(out.getvalue(), format="ascii.ipac", guess=False)
assert t2["B"].unit is None
def test_create_table_from_final_row():
"""Regression test for issue #8422: passing the last row of a table into
Table should return a new table containing that row."""
t1 = table.Table([(1, 2)], names=['col'])
row = t1[-1]
t2 = table.Table(row)['col']
assert t2[0] == 2
def test_key_values_in_as_array():
# Test for checking column slicing using key_values in Table.as_array()
data_rows = [(1, 2.0, 'x'),
(4, 5.0, 'y'),
(5, 8.2, 'z')]
# Creating a table with three columns
t1 = table.Table(rows=data_rows, names=('a', 'b', 'c'),
meta={'name': 'first table'},
dtype=('i4', 'f8', 'S1'))
# Values of sliced column a,b is stored in a numpy array
a = np.array([(1, 2.), (4, 5.), (5, 8.2)],
dtype=[('a', '<i4'), ('b', '<f8')])
# Values for sliced column c is stored in a numpy array
b = np.array([(b'x',), (b'y',), (b'z',)], dtype=[('c', 'S1')])
# Comparing initialised array with sliced array using Table.as_array()
assert np.array_equal(a, t1.as_array(names=['a', 'b']))
assert np.array_equal(b, t1.as_array(names=['c']))
def test_tolist():
t = table.Table([[1, 2, 3], [1.1, 2.2, 3.3], [b'foo', b'bar', b'hello']],
names=('a', 'b', 'c'))
assert t['a'].tolist() == [1, 2, 3]
assert_array_equal(t['b'].tolist(), [1.1, 2.2, 3.3])
assert t['c'].tolist() == ['foo', 'bar', 'hello']
assert isinstance(t['a'].tolist()[0], int)
assert isinstance(t['b'].tolist()[0], float)
assert isinstance(t['c'].tolist()[0], str)
t = table.Table([[[1, 2], [3, 4]],
[[b'foo', b'bar'], [b'hello', b'world']]],
names=('a', 'c'))
assert t['a'].tolist() == [[1, 2], [3, 4]]
assert t['c'].tolist() == [['foo', 'bar'], ['hello', 'world']]
assert isinstance(t['a'].tolist()[0][0], int)
assert isinstance(t['c'].tolist()[0][0], str)
class MyTable(Table):
foo = TableAttribute()
bar = TableAttribute(default=[])
baz = TableAttribute(default=1)
def test_table_attribute():
assert repr(MyTable.baz) == '<TableAttribute name=baz default=1>'
t = MyTable([[1, 2]])
# __attributes__ created on the fly on the first access of an attribute
# that has a non-None default.
assert '__attributes__' not in t.meta
assert t.foo is None
assert '__attributes__' not in t.meta
assert t.baz == 1
assert '__attributes__' in t.meta
t.bar.append(2.0)
assert t.bar == [2.0]
assert t.baz == 1
t.baz = 'baz'
assert t.baz == 'baz'
# Table attributes round-trip through pickle
tp = pickle.loads(pickle.dumps(t))
assert tp.foo is None
assert tp.baz == 'baz'
assert tp.bar == [2.0]
# Allow initialization of attributes in table creation, with / without data
for data in None, [[1, 2]]:
t2 = MyTable(data, foo=3, bar='bar', baz='baz')
assert t2.foo == 3
assert t2.bar == 'bar'
assert t2.baz == 'baz'
# Initializing from an existing MyTable works, with and without kwarg attrs
t3 = MyTable(t2)
assert t3.foo == 3
assert t3.bar == 'bar'
assert t3.baz == 'baz'
t3 = MyTable(t2, foo=5, bar='fubar')
assert t3.foo == 5
assert t3.bar == 'fubar'
assert t3.baz == 'baz'
# Deleting attributes removes it from attributes
del t.baz
assert 'baz' not in t.meta['__attributes__']
del t.bar
assert '__attributes__' not in t.meta
def test_table_attribute_ecsv():
# Table attribute round-trip through ECSV
t = MyTable([[1, 2]], bar=[2.0], baz='baz')
out = StringIO()
t.write(out, format='ascii.ecsv')
t2 = MyTable.read(out.getvalue(), format='ascii.ecsv')
assert t2.foo is None
assert t2.bar == [2.0]
assert t2.baz == 'baz'
def test_table_attribute_fail():
# Code raises ValueError(f'{attr} not allowed as TableAttribute') but in this
# context it gets re-raised as a RuntimeError during class definition.
with pytest.raises(RuntimeError, match='Error calling __set_name__'):
class MyTable2(Table):
descriptions = TableAttribute() # Conflicts with init arg
with pytest.raises(RuntimeError, match='Error calling __set_name__'):
class MyTable3(Table):
colnames = TableAttribute() # Conflicts with built-in property
def test_set_units_fail():
dat = [[1.0, 2.0], ['aa', 'bb']]
with pytest.raises(ValueError, match='sequence of unit values must match number of columns'):
Table(dat, units=[u.m])
with pytest.raises(ValueError, match='invalid column name c for setting unit attribute'):
Table(dat, units={'c': u.m})
def test_set_units():
dat = [[1.0, 2.0], ['aa', 'bb'], [3, 4]]
exp_units = (u.m, None, None)
for cls in Table, QTable:
for units in ({'a': u.m, 'c': ''}, exp_units):
qt = cls(dat, units=units, names=['a', 'b', 'c'])
if cls is QTable:
assert isinstance(qt['a'], u.Quantity)
assert isinstance(qt['b'], table.Column)
assert isinstance(qt['c'], table.Column)
for col, unit in zip(qt.itercols(), exp_units):
assert col.info.unit is unit
def test_set_descriptions():
dat = [[1.0, 2.0], ['aa', 'bb']]
exp_descriptions = ('my description', None)
for cls in Table, QTable:
for descriptions in ({'a': 'my description'}, exp_descriptions):
qt = cls(dat, descriptions=descriptions, names=['a', 'b'])
for col, description in zip(qt.itercols(), exp_descriptions):
assert col.info.description == description
def test_set_units_from_row():
text = ['a,b',
',s',
'1,2',
'3,4']
units = Table.read(text, format='ascii', data_start=1, data_end=2)[0]
t = Table.read(text, format='ascii', data_start=2, units=units)
assert isinstance(units, table.Row)
assert t['a'].info.unit is None
assert t['b'].info.unit is u.s
def test_set_units_descriptions_read():
"""Test setting units and descriptions via Table.read. The test here
is less comprehensive because the implementation is exactly the same
as for Table.__init__ (calling Table._set_column_attribute) """
for cls in Table, QTable:
t = cls.read(['a b', '1 2'],
format='ascii',
units=[u.m, u.s],
descriptions=['hi', 'there'])
assert t['a'].info.unit is u.m
assert t['b'].info.unit is u.s
assert t['a'].info.description == 'hi'
assert t['b'].info.description == 'there'
def test_broadcasting_8933():
"""Explicitly check re-work of code related to broadcasting in #8933"""
t = table.Table([[1, 2]]) # Length=2 table
t['a'] = [[3, 4]] # Can broadcast if ndim > 1 and shape[0] == 1
t['b'] = 5
t['c'] = [1] # Treat as broadcastable scalar, not length=1 array (which would fail)
assert np.all(t['a'] == [[3, 4], [3, 4]])
assert np.all(t['b'] == [5, 5])
assert np.all(t['c'] == [1, 1])
# Test that broadcasted column is writeable
t['c'][1] = 10
assert np.all(t['c'] == [1, 10])
def test_custom_masked_column_in_nonmasked_table():
"""Test the refactor and change in column upgrades introduced
in 95902650f. This fixes a regression introduced by #8789
(Change behavior of Table regarding masked columns)."""
class MyMaskedColumn(table.MaskedColumn):
pass
class MySubMaskedColumn(MyMaskedColumn):
pass
class MyColumn(table.Column):
pass
class MySubColumn(MyColumn):
pass
class MyTable(table.Table):
Column = MyColumn
MaskedColumn = MyMaskedColumn
a = table.Column([1])
b = table.MaskedColumn([2], mask=[True])
c = MyMaskedColumn([3], mask=[True])
d = MySubColumn([4])
e = MySubMaskedColumn([5], mask=[True])
# Two different pathways for making table
t1 = MyTable([a, b, c, d, e], names=['a', 'b', 'c', 'd', 'e'])
t2 = MyTable()
t2['a'] = a
t2['b'] = b
t2['c'] = c
t2['d'] = d
t2['e'] = e
for t in (t1, t2):
assert type(t['a']) is MyColumn
assert type(t['b']) is MyMaskedColumn # upgrade
assert type(t['c']) is MyMaskedColumn
assert type(t['d']) is MySubColumn
assert type(t['e']) is MySubMaskedColumn # sub-class not downgraded
def test_sort_with_mutable_skycoord():
"""Test sorting a table that has a mutable column such as SkyCoord.
In this case the sort is done in-place
"""
t = Table([[2, 1], SkyCoord([4, 3], [6, 5], unit='deg,deg')], names=['a', 'sc'])
meta = {'a': [1, 2]}
ta = t['a']
tsc = t['sc']
t['sc'].info.meta = meta
t.sort('a')
assert np.all(t['a'] == [1, 2])
assert np.allclose(t['sc'].ra.to_value(u.deg), [3, 4])
assert np.allclose(t['sc'].dec.to_value(u.deg), [5, 6])
assert t['a'] is ta
assert t['sc'] is tsc
# Prior to astropy 4.1 this was a deep copy of SkyCoord column; after 4.1
# it is a reference.
t['sc'].info.meta['a'][0] = 100
assert meta['a'][0] == 100
def test_sort_with_non_mutable():
"""Test sorting a table that has a non-mutable column.
"""
t = Table([[2, 1], [3, 4]], names=['a', 'b'])
ta = t['a']
tb = t['b']
t['b'].setflags(write=False)
meta = {'a': [1, 2]}
t['b'].info.meta = meta
t.sort('a')
assert np.all(t['a'] == [1, 2])
assert np.all(t['b'] == [4, 3])
assert ta is t['a']
assert tb is not t['b']
# Prior to astropy 4.1 this was a deep copy of SkyCoord column; after 4.1
# it is a reference.
t['b'].info.meta['a'][0] = 100
assert meta['a'][0] == 1
def test_init_with_list_of_masked_arrays():
"""Test the fix for #8977"""
m0 = np.ma.array([0, 1, 2], mask=[True, False, True])
m1 = np.ma.array([3, 4, 5], mask=[False, True, False])
mc = [m0, m1]
# Test _init_from_list
t = table.Table([mc], names=['a'])
# Test add_column
t['b'] = [m1, m0]
assert t['a'].shape == (2, 3)
assert np.all(t['a'][0] == m0)
assert np.all(t['a'][1] == m1)
assert np.all(t['a'][0].mask == m0.mask)
assert np.all(t['a'][1].mask == m1.mask)
assert t['b'].shape == (2, 3)
assert np.all(t['b'][0] == m1)
assert np.all(t['b'][1] == m0)
assert np.all(t['b'][0].mask == m1.mask)
assert np.all(t['b'][1].mask == m0.mask)
def test_data_to_col_convert_strategy():
"""Test the update to how data_to_col works (#8972), using the regression
example from #8971.
"""
t = table.Table([[0, 1]])
t['a'] = 1
t['b'] = np.int64(2) # Failed previously
assert np.all(t['a'] == [1, 1])
assert np.all(t['b'] == [2, 2])
def test_rows_with_mixins():
"""Test for #9165 to allow adding a list of mixin objects.
Also test for fix to #9357 where group_by() failed due to
mixin object not having info.indices set to [].
"""
tm = Time([1, 2], format='cxcsec')
q = [1, 2] * u.m
mixed1 = [1 * u.m, 2] # Mixed input, fails to convert to Quantity
mixed2 = [2, 1 * u.m] # Mixed input, not detected as potential mixin
rows = [(1, q[0], tm[0]),
(2, q[1], tm[1])]
t = table.QTable(rows=rows)
t['a'] = [q[0], q[1]]
t['b'] = [tm[0], tm[1]]
t['m1'] = mixed1
t['m2'] = mixed2
assert np.all(t['col1'] == q)
assert np.all(t['col2'] == tm)
assert np.all(t['a'] == q)
assert np.all(t['b'] == tm)
assert np.all(t['m1'][ii] == mixed1[ii] for ii in range(2))
assert np.all(t['m2'][ii] == mixed2[ii] for ii in range(2))
assert type(t['m1']) is table.Column
assert t['m1'].dtype is np.dtype(object)
assert type(t['m2']) is table.Column
assert t['m2'].dtype is np.dtype(object)
# Ensure group_by() runs without failing for sortable columns.
# The columns 'm1', and 'm2' are object dtype and not sortable.
for name in ['col0', 'col1', 'col2', 'a', 'b']:
t.group_by(name)
# For good measure include exactly the failure in #9357 in which the
# list of Time() objects is in the Table initializer.
mjds = [Time(58000, format="mjd")]
t = Table([mjds, ["gbt"]], names=("mjd", "obs"))
t.group_by("obs")
def test_iterrows():
dat = [(1, 2, 3),
(4, 5, 6),
(7, 8, 6)]
t = table.Table(rows=dat, names=('a', 'b', 'c'))
c_s = []
a_s = []
for c, a in t.iterrows('c', 'a'):
a_s.append(a)
c_s.append(c)
assert np.all(t['a'] == a_s)
assert np.all(t['c'] == c_s)
rows = [row for row in t.iterrows()]
assert rows == dat
with pytest.raises(ValueError, match='d is not a valid column name'):
t.iterrows('d')
def test_values_and_types():
dat = [(1, 2, 3),
(4, 5, 6),
(7, 8, 6)]
t = table.Table(rows=dat, names=('a', 'b', 'c'))
assert isinstance(t.values(), type(OrderedDict().values()))
assert isinstance(t.columns.values(), type(OrderedDict().values()))
assert isinstance(t.columns.keys(), type(OrderedDict().keys()))
for i in t.values():
assert isinstance(i, table.column.Column)
def test_items():
dat = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
t = table.Table(rows=dat, names=('a', 'b', 'c'))
assert isinstance(t.items(), type(OrderedDict({}).items()))
for i in list(t.items()):
assert isinstance(i, tuple)
def test_read_write_not_replaceable():
t = table.Table()
with pytest.raises(AttributeError):
t.read = 'fake_read'
with pytest.raises(AttributeError):
t.write = 'fake_write'
def test_keep_columns_with_generator():
# Regression test for #12529
t = table.table_helpers.simple_table(1)
t.keep_columns(col for col in t.colnames if col == 'a')
assert t.colnames == ['a']
def test_remove_columns_with_generator():
# Regression test for #12529
t = table.table_helpers.simple_table(1)
t.remove_columns(col for col in t.colnames if col == 'a')
assert t.colnames == ['b', 'c']
def test_keep_columns_invalid_names_messages():
t = table.table_helpers.simple_table(1)
with pytest.raises(KeyError, match='column "d" does not exist'):
t.keep_columns(['c', 'd'])
with pytest.raises(KeyError,
match='columns {\'[de]\', \'[de]\'} do not exist'):
t.keep_columns(['c', 'd', 'e'])
def test_remove_columns_invalid_names_messages():
t = table.table_helpers.simple_table(1)
with pytest.raises(KeyError, match='column "d" does not exist'):
t.remove_columns(['c', 'd'])
with pytest.raises(KeyError,
match='columns {\'[de]\', \'[de]\'} do not exist'):
t.remove_columns(['c', 'd', 'e'])
|
c7018b8f6ebbb185af110b66a309586130a827030fdccc4c1aa1d35eb7db4250 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
from io import StringIO
from collections import OrderedDict
from copy import deepcopy
import numpy as np
import pytest
from astropy import units as u
from astropy import time
from astropy import coordinates
from astropy import table
from astropy.table.info import serialize_method_as
from astropy.utils.data_info import data_info_factory, dtype_info_name
from astropy.table.table_helpers import simple_table
def test_table_info_attributes(table_types):
"""
Test the info() method of printing a summary of table column attributes
"""
a = np.array([1, 2, 3], dtype='int32')
b = np.array([1, 2, 3], dtype='float32')
c = np.array(['a', 'c', 'e'], dtype='|S1')
t = table_types.Table([a, b, c], names=['a', 'b', 'c'])
# Minimal output for a typical table
tinfo = t.info(out=None)
subcls = ['class'] if table_types.Table.__name__ == 'MyTable' else []
assert tinfo.colnames == ['name', 'dtype', 'shape', 'unit', 'format',
'description', 'class', 'n_bad', 'length']
assert np.all(tinfo['name'] == ['a', 'b', 'c'])
assert np.all(tinfo['dtype'] == ['int32', 'float32', dtype_info_name('S1')])
if subcls:
assert np.all(tinfo['class'] == ['MyColumn'] * 3)
# All output fields including a mixin column
t['d'] = [1, 2, 3] * u.m
t['d'].description = 'quantity'
t['a'].format = '%02d'
t['e'] = time.Time([1, 2, 3], format='mjd')
t['e'].info.description = 'time'
t['f'] = coordinates.SkyCoord([1, 2, 3], [1, 2, 3], unit='deg')
t['f'].info.description = 'skycoord'
tinfo = t.info(out=None)
assert np.all(tinfo['name'] == 'a b c d e f'.split())
assert np.all(tinfo['dtype'] == ['int32', 'float32', dtype_info_name('S1'), 'float64',
'object', 'object'])
assert np.all(tinfo['unit'] == ['', '', '', 'm', '', 'deg,deg'])
assert np.all(tinfo['format'] == ['%02d', '', '', '', '', ''])
assert np.all(tinfo['description'] == ['', '', '', 'quantity', 'time', 'skycoord'])
cls = t.ColumnClass.__name__
assert np.all(tinfo['class'] == [cls, cls, cls, cls, 'Time', 'SkyCoord'])
# Test that repr(t.info) is same as t.info()
out = StringIO()
t.info(out=out)
assert repr(t.info) == out.getvalue()
def test_table_info_stats(table_types):
"""
Test the info() method of printing a summary of table column statistics
"""
a = np.array([1, 2, 1, 2], dtype='int32')
b = np.array([1, 2, 1, 2], dtype='float32')
c = np.array(['a', 'c', 'e', 'f'], dtype='|S1')
d = time.Time([1, 2, 1, 2], format='mjd')
t = table_types.Table([a, b, c, d], names=['a', 'b', 'c', 'd'])
# option = 'stats'
masked = 'masked=True ' if t.masked else ''
out = StringIO()
t.info('stats', out=out)
table_header_line = f'<{t.__class__.__name__} {masked}length=4>'
exp = [table_header_line,
'name mean std min max',
'---- ---- --- --- ---',
' a 1.5 0.5 1 2',
' b 1.5 0.5 1 2',
' c -- -- -- --',
' d -- -- 1.0 2.0']
assert out.getvalue().splitlines() == exp
# option = ['attributes', 'stats']
tinfo = t.info(['attributes', 'stats'], out=None)
assert tinfo.colnames == ['name', 'dtype', 'shape', 'unit', 'format', 'description',
'class', 'mean', 'std', 'min', 'max', 'n_bad', 'length']
assert np.all(tinfo['mean'] == ['1.5', '1.5', '--', '--'])
assert np.all(tinfo['std'] == ['0.5', '0.5', '--', '--'])
assert np.all(tinfo['min'] == ['1', '1', '--', '1.0'])
assert np.all(tinfo['max'] == ['2', '2', '--', '2.0'])
out = StringIO()
t.info('stats', out=out)
exp = [table_header_line,
'name mean std min max',
'---- ---- --- --- ---',
' a 1.5 0.5 1 2',
' b 1.5 0.5 1 2',
' c -- -- -- --',
' d -- -- 1.0 2.0']
assert out.getvalue().splitlines() == exp
# option = ['attributes', custom]
custom = data_info_factory(names=['sum', 'first'],
funcs=[np.sum, lambda col: col[0]])
out = StringIO()
tinfo = t.info(['attributes', custom], out=None)
assert tinfo.colnames == ['name', 'dtype', 'shape', 'unit', 'format', 'description',
'class', 'sum', 'first', 'n_bad', 'length']
assert np.all(tinfo['name'] == ['a', 'b', 'c', 'd'])
assert np.all(tinfo['dtype'] == ['int32', 'float32', dtype_info_name('S1'), 'object'])
assert np.all(tinfo['sum'] == ['6', '6', '--', '--'])
assert np.all(tinfo['first'] == ['1', '1', 'a', '1.0'])
def test_data_info():
"""
Test getting info for just a column.
"""
cols = [table.Column([1.0, 2.0, np.nan], name='name',
description='description', unit='m/s'),
table.MaskedColumn([1.0, 2.0, 3.0], name='name',
description='description', unit='m/s',
mask=[False, False, True])]
for c in cols:
# Test getting the full ordered dict
cinfo = c.info(out=None)
assert cinfo == OrderedDict([('name', 'name'),
('dtype', 'float64'),
('shape', ''),
('unit', 'm / s'),
('format', ''),
('description', 'description'),
('class', type(c).__name__),
('n_bad', 1),
('length', 3)])
# Test the console (string) version which omits trivial values
out = StringIO()
c.info(out=out)
exp = ['name = name',
'dtype = float64',
'unit = m / s',
'description = description',
f'class = {type(c).__name__}',
'n_bad = 1',
'length = 3']
assert out.getvalue().splitlines() == exp
# repr(c.info) gives the same as c.info()
assert repr(c.info) == out.getvalue()
# Test stats info
cinfo = c.info('stats', out=None)
assert cinfo == OrderedDict([('name', 'name'),
('mean', '1.5'),
('std', '0.5'),
('min', '1'),
('max', '2'),
('n_bad', 1),
('length', 3)])
def test_data_info_subclass():
class Column(table.Column):
"""
Confusingly named Column on purpose, but that is legal.
"""
pass
for data in ([], [1, 2]):
c = Column(data, dtype='int64')
cinfo = c.info(out=None)
assert cinfo == OrderedDict([('dtype', 'int64'),
('shape', ''),
('unit', ''),
('format', ''),
('description', ''),
('class', 'Column'),
('n_bad', 0),
('length', len(data))])
def test_scalar_info():
"""
Make sure info works with scalar values
"""
c = time.Time('2000:001')
cinfo = c.info(out=None)
assert cinfo['n_bad'] == 0
assert 'length' not in cinfo
def test_empty_table():
t = table.Table()
out = StringIO()
t.info(out=out)
exp = ['<Table length=0>', '<No columns>']
assert out.getvalue().splitlines() == exp
def test_class_attribute():
"""
Test that class info column is suppressed only for identical non-mixin
columns.
"""
vals = [[1] * u.m, [2] * u.m]
texp = ['<Table length=1>',
'name dtype unit',
'---- ------- ----',
'col0 float64 m',
'col1 float64 m']
qexp = ['<QTable length=1>',
'name dtype unit class ',
'---- ------- ---- --------',
'col0 float64 m Quantity',
'col1 float64 m Quantity']
for table_cls, exp in ((table.Table, texp),
(table.QTable, qexp)):
t = table_cls(vals)
out = StringIO()
t.info(out=out)
assert out.getvalue().splitlines() == exp
def test_ignore_warnings():
t = table.Table([[np.nan, np.nan]])
with warnings.catch_warnings(record=True) as warns:
t.info('stats', out=None)
assert len(warns) == 0
def test_no_deprecation_warning():
# regression test for #5459, where numpy deprecation warnings were
# emitted unnecessarily.
t = simple_table()
with warnings.catch_warnings(record=True) as warns:
t.info()
assert len(warns) == 0
def test_lost_parent_error():
c = table.Column([1, 2, 3], name='a')
with pytest.raises(AttributeError,
match='failed to access "info" attribute'):
c[:].info.name
def test_info_serialize_method():
"""
Unit test of context manager to set info.serialize_method. Normally just
used to set this for writing a Table to file (FITS, ECSV, HDF5).
"""
t = table.Table({'tm': time.Time([1, 2], format='cxcsec'),
'sc': coordinates.SkyCoord([1, 2], [1, 2], unit='deg'),
'mc': table.MaskedColumn([1, 2], mask=[True, False]),
'mc2': table.MaskedColumn([1, 2], mask=[True, False])}
)
origs = {}
for name in ('tm', 'mc', 'mc2'):
origs[name] = deepcopy(t[name].info.serialize_method)
# Test setting by name and getting back to originals
with serialize_method_as(t, {'tm': 'test_tm', 'mc': 'test_mc'}):
for name in ('tm', 'mc'):
assert all(t[name].info.serialize_method[key] == 'test_' + name
for key in t[name].info.serialize_method)
assert t['mc2'].info.serialize_method == origs['mc2']
assert not hasattr(t['sc'].info, 'serialize_method')
for name in ('tm', 'mc', 'mc2'):
assert t[name].info.serialize_method == origs[name] # dict compare
assert not hasattr(t['sc'].info, 'serialize_method')
# Test setting by name and class, where name takes precedence. Also
# test that it works for subclasses.
with serialize_method_as(t, {'tm': 'test_tm', 'mc': 'test_mc',
table.Column: 'test_mc2'}):
for name in ('tm', 'mc', 'mc2'):
assert all(t[name].info.serialize_method[key] == 'test_' + name
for key in t[name].info.serialize_method)
assert not hasattr(t['sc'].info, 'serialize_method')
for name in ('tm', 'mc', 'mc2'):
assert t[name].info.serialize_method == origs[name] # dict compare
assert not hasattr(t['sc'].info, 'serialize_method')
# Test supplying a single string that all applies to all columns with
# a serialize_method.
with serialize_method_as(t, 'test'):
for name in ('tm', 'mc', 'mc2'):
assert all(t[name].info.serialize_method[key] == 'test'
for key in t[name].info.serialize_method)
assert not hasattr(t['sc'].info, 'serialize_method')
for name in ('tm', 'mc', 'mc2'):
assert t[name].info.serialize_method == origs[name] # dict compare
assert not hasattr(t['sc'].info, 'serialize_method')
def test_info_serialize_method_exception():
"""
Unit test of context manager to set info.serialize_method. Normally just
used to set this for writing a Table to file (FITS, ECSV, HDF5).
"""
t = simple_table(masked=True)
origs = deepcopy(t['a'].info.serialize_method)
try:
with serialize_method_as(t, 'test'):
assert all(t['a'].info.serialize_method[key] == 'test'
for key in t['a'].info.serialize_method)
raise ZeroDivisionError()
except ZeroDivisionError:
pass
assert t['a'].info.serialize_method == origs # dict compare
|
fbc03c98dcf79a81fa53868c189dadc6cd5ea3bb9dad33b652d8d352f7f231a1 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
import pytest
import numpy as np
from .test_table import SetupData
from astropy.table.bst import BST
from astropy.table.sorted_array import SortedArray
from astropy.table.soco import SCEngine
from astropy.table import QTable, Row, Table, Column, hstack
from astropy import units as u
from astropy.time import Time
from astropy.table.column import BaseColumn
from astropy.table.index import get_index, SlicedIndex
from astropy.utils.compat.optional_deps import HAS_SORTEDCONTAINERS
available_engines = [BST, SortedArray]
if HAS_SORTEDCONTAINERS:
available_engines.append(SCEngine)
@pytest.fixture(params=available_engines)
def engine(request):
return request.param
_col = [1, 2, 3, 4, 5]
@pytest.fixture(params=[
_col,
u.Quantity(_col),
Time(_col, format='jyear'),
])
def main_col(request):
return request.param
def assert_col_equal(col, array):
if isinstance(col, Time):
assert np.all(col == Time(array, format='jyear'))
else:
assert np.all(col == col.__class__(array))
@pytest.mark.usefixtures('table_types')
class TestIndex(SetupData):
def _setup(self, main_col, table_types):
super()._setup(table_types)
self.main_col = main_col
if isinstance(main_col, u.Quantity):
self._table_type = QTable
if not isinstance(main_col, list):
self._column_type = lambda x: x # don't change mixin type
self.mutable = isinstance(main_col, (list, u.Quantity))
def make_col(self, name, lst):
return self._column_type(lst, name=name)
def make_val(self, val):
if isinstance(self.main_col, Time):
return Time(val, format='jyear')
return val
@property
def t(self):
if not hasattr(self, '_t'):
# Note that order of columns is important, and the 'a' column is
# last to ensure that the index column does not need to be the first
# column (as was discovered in #10025). Most testing uses 'a' and
# ('a', 'b') for the columns.
self._t = self._table_type()
self._t['b'] = self._column_type([4.0, 5.1, 6.2, 7.0, 1.1])
self._t['c'] = self._column_type(['7', '8', '9', '10', '11'])
self._t['a'] = self._column_type(self.main_col)
return self._t
@pytest.mark.parametrize("composite", [False, True])
def test_table_index(self, main_col, table_types, composite, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index(('a', 'b') if composite else 'a', engine=engine)
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
if not self.mutable:
return
# test altering table columns
t['a'][0] = 4
t.add_row((6.0, '7', 6))
t['a'][3] = 10
t.remove_row(2)
t.add_row((5.0, '9', 4))
assert_col_equal(t['a'], np.array([4, 2, 10, 5, 6, 4]))
assert np.allclose(t['b'], np.array([4.0, 5.1, 7.0, 1.1, 6.0, 5.0]))
assert np.all(t['c'].data == np.array(['7', '8', '10', '11', '7', '9']))
index = t.indices[0]
ll = list(index.data.items())
if composite:
assert np.all(ll == [((2, 5.1), [1]),
((4, 4.0), [0]),
((4, 5.0), [5]),
((5, 1.1), [3]),
((6, 6.0), [4]),
((10, 7.0), [2])])
else:
assert np.all(ll == [((2,), [1]),
((4,), [0, 5]),
((5,), [3]),
((6,), [4]),
((10,), [2])])
t.remove_indices('a')
assert len(t.indices) == 0
def test_table_slicing(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine)
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
for slice_ in ([0, 2], np.array([0, 2])):
t2 = t[slice_]
# t2 should retain an index on column 'a'
assert len(t2.indices) == 1
assert_col_equal(t2['a'], [1, 3])
# the index in t2 should reorder row numbers after slicing
assert np.all(t2.indices[0].sorted_data() == [0, 1])
# however, this index should be a deep copy of t1's index
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
def test_remove_rows(self, main_col, table_types, engine):
self._setup(main_col, table_types)
if not self.mutable:
return
t = self.t
t.add_index('a', engine=engine)
# remove individual row
t2 = t.copy()
t2.remove_rows(2)
assert_col_equal(t2['a'], [1, 2, 4, 5])
assert np.all(t2.indices[0].sorted_data() == [0, 1, 2, 3])
# remove by list, ndarray, or slice
for cut in ([0, 2, 4], np.array([0, 2, 4]), slice(0, 5, 2)):
t2 = t.copy()
t2.remove_rows(cut)
assert_col_equal(t2['a'], [2, 4])
assert np.all(t2.indices[0].sorted_data() == [0, 1])
with pytest.raises(ValueError):
t.remove_rows((0, 2, 4))
def test_col_get_slice(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine)
# get slice
t2 = t[1:3] # table slice
assert_col_equal(t2['a'], [2, 3])
assert np.all(t2.indices[0].sorted_data() == [0, 1])
col_slice = t['a'][1:3]
assert_col_equal(col_slice, [2, 3])
# true column slices discard indices
if isinstance(t['a'], BaseColumn):
assert len(col_slice.info.indices) == 0
# take slice of slice
t2 = t[::2]
assert_col_equal(t2['a'], np.array([1, 3, 5]))
t3 = t2[::-1]
assert_col_equal(t3['a'], np.array([5, 3, 1]))
assert np.all(t3.indices[0].sorted_data() == [2, 1, 0])
t3 = t2[:2]
assert_col_equal(t3['a'], np.array([1, 3]))
assert np.all(t3.indices[0].sorted_data() == [0, 1])
# out-of-bound slices
for t_empty in (t2[3:], t2[2:1], t3[2:]):
assert len(t_empty['a']) == 0
assert np.all(t_empty.indices[0].sorted_data() == [])
if self.mutable:
# get boolean mask
mask = t['a'] % 2 == 1
t2 = t[mask]
assert_col_equal(t2['a'], [1, 3, 5])
assert np.all(t2.indices[0].sorted_data() == [0, 1, 2])
def test_col_set_slice(self, main_col, table_types, engine):
self._setup(main_col, table_types)
if not self.mutable:
return
t = self.t
t.add_index('a', engine=engine)
# set slice
t2 = t.copy()
t2['a'][1:3] = np.array([6, 7])
assert_col_equal(t2['a'], np.array([1, 6, 7, 4, 5]))
assert np.all(t2.indices[0].sorted_data() == [0, 3, 4, 1, 2])
# change original table via slice reference
t2 = t.copy()
t3 = t2[1:3]
assert_col_equal(t3['a'], np.array([2, 3]))
assert np.all(t3.indices[0].sorted_data() == [0, 1])
t3['a'][0] = 5
assert_col_equal(t3['a'], np.array([5, 3]))
assert_col_equal(t2['a'], np.array([1, 5, 3, 4, 5]))
assert np.all(t3.indices[0].sorted_data() == [1, 0])
assert np.all(t2.indices[0].sorted_data() == [0, 2, 3, 1, 4])
# set boolean mask
t2 = t.copy()
mask = t['a'] % 2 == 1
t2['a'][mask] = 0.
assert_col_equal(t2['a'], [0, 2, 0, 4, 0])
assert np.all(t2.indices[0].sorted_data() == [0, 2, 4, 1, 3])
def test_multiple_slices(self, main_col, table_types, engine):
self._setup(main_col, table_types)
if not self.mutable:
return
t = self.t
t.add_index('a', engine=engine)
for i in range(6, 51):
t.add_row((1.0, 'A', i))
assert_col_equal(t['a'], [i for i in range(1, 51)])
assert np.all(t.indices[0].sorted_data() == [i for i in range(50)])
evens = t[::2]
assert np.all(evens.indices[0].sorted_data() == [i for i in range(25)])
reverse = evens[::-1]
index = reverse.indices[0]
assert (index.start, index.stop, index.step) == (48, -2, -2)
assert np.all(index.sorted_data() == [i for i in range(24, -1, -1)])
# modify slice of slice
reverse[-10:] = 0
expected = np.array([i for i in range(1, 51)])
expected[:20][expected[:20] % 2 == 1] = 0
assert_col_equal(t['a'], expected)
assert_col_equal(evens['a'], expected[::2])
assert_col_equal(reverse['a'], expected[::2][::-1])
# first ten evens are now zero
assert np.all(t.indices[0].sorted_data()
== ([0, 2, 4, 6, 8, 10, 12, 14, 16, 18,
1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
+ [i for i in range(20, 50)]))
assert np.all(evens.indices[0].sorted_data() == [i for i in range(25)])
assert np.all(reverse.indices[0].sorted_data()
== [i for i in range(24, -1, -1)])
# try different step sizes of slice
t2 = t[1:20:2]
assert_col_equal(t2['a'], [2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
assert np.all(t2.indices[0].sorted_data() == [i for i in range(10)])
t3 = t2[::3]
assert_col_equal(t3['a'], [2, 8, 14, 20])
assert np.all(t3.indices[0].sorted_data() == [0, 1, 2, 3])
t4 = t3[2::-1]
assert_col_equal(t4['a'], [14, 8, 2])
assert np.all(t4.indices[0].sorted_data() == [2, 1, 0])
def test_sort(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t[::-1] # reverse table
assert_col_equal(t['a'], [5, 4, 3, 2, 1])
t.add_index('a', engine=engine)
assert np.all(t.indices[0].sorted_data() == [4, 3, 2, 1, 0])
if not self.mutable:
return
# sort table by column a
t2 = t.copy()
t2.sort('a')
assert_col_equal(t2['a'], [1, 2, 3, 4, 5])
assert np.all(t2.indices[0].sorted_data() == [0, 1, 2, 3, 4])
# sort table by primary key
t2 = t.copy()
t2.sort()
assert_col_equal(t2['a'], [1, 2, 3, 4, 5])
assert np.all(t2.indices[0].sorted_data() == [0, 1, 2, 3, 4])
def test_insert_row(self, main_col, table_types, engine):
self._setup(main_col, table_types)
if not self.mutable:
return
t = self.t
t.add_index('a', engine=engine)
t.insert_row(2, (1.0, '12', 6))
assert_col_equal(t['a'], [1, 2, 6, 3, 4, 5])
assert np.all(t.indices[0].sorted_data() == [0, 1, 3, 4, 5, 2])
t.insert_row(1, (4.0, '13', 0))
assert_col_equal(t['a'], [1, 0, 2, 6, 3, 4, 5])
assert np.all(t.indices[0].sorted_data() == [1, 0, 2, 4, 5, 6, 3])
def test_index_modes(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine)
# first, no special mode
assert len(t[[1, 3]].indices) == 1
assert len(t[::-1].indices) == 1
assert len(self._table_type(t).indices) == 1
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
t2 = t.copy()
# non-copy mode
with t.index_mode('discard_on_copy'):
assert len(t[[1, 3]].indices) == 0
assert len(t[::-1].indices) == 0
assert len(self._table_type(t).indices) == 0
assert len(t2.copy().indices) == 1 # mode should only affect t
# make sure non-copy mode is exited correctly
assert len(t[[1, 3]].indices) == 1
if not self.mutable:
return
# non-modify mode
with t.index_mode('freeze'):
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
t['a'][0] = 6
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
t.add_row((1.5, '12', 2))
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
t.remove_rows([1, 3])
assert np.all(t.indices[0].sorted_data() == [0, 1, 2, 3, 4])
assert_col_equal(t['a'], [6, 3, 5, 2])
# mode should only affect t
assert np.all(t2.indices[0].sorted_data() == [0, 1, 2, 3, 4])
t2['a'][0] = 6
assert np.all(t2.indices[0].sorted_data() == [1, 2, 3, 4, 0])
# make sure non-modify mode is exited correctly
assert np.all(t.indices[0].sorted_data() == [3, 1, 2, 0])
if isinstance(t['a'], BaseColumn):
assert len(t['a'][::-1].info.indices) == 0
with t.index_mode('copy_on_getitem'):
assert len(t['a'][[1, 2]].info.indices) == 1
# mode should only affect t
assert len(t2['a'][[1, 2]].info.indices) == 0
assert len(t['a'][::-1].info.indices) == 0
assert len(t2['a'][::-1].info.indices) == 0
def test_index_retrieval(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine)
t.add_index(['a', 'c'], engine=engine)
assert len(t.indices) == 2
assert len(t.indices['a'].columns) == 1
assert len(t.indices['a', 'c'].columns) == 2
with pytest.raises(IndexError):
t.indices['b']
def test_col_rename(self, main_col, table_types, engine):
'''
Checks for a previous bug in which copying a Table
with different column names raised an exception.
'''
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine)
t2 = self._table_type(self.t, names=['d', 'e', 'f'])
assert len(t2.indices) == 1
def test_table_loc(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine)
t.add_index('b', engine=engine)
t2 = t.loc[self.make_val(3)] # single label, with primary key 'a'
assert_col_equal(t2['a'], [3])
assert isinstance(t2, Row)
# list search
t2 = t.loc[[self.make_val(1), self.make_val(4), self.make_val(2)]]
assert_col_equal(t2['a'], [1, 4, 2]) # same order as input list
if not isinstance(main_col, Time):
# ndarray search
t2 = t.loc[np.array([1, 4, 2])]
assert_col_equal(t2['a'], [1, 4, 2])
assert_col_equal(t2['a'], [1, 4, 2])
t2 = t.loc[self.make_val(3): self.make_val(5)] # range search
assert_col_equal(t2['a'], [3, 4, 5])
t2 = t.loc['b', 5.0:7.0]
assert_col_equal(t2['b'], [5.1, 6.2, 7.0])
# search by sorted index
t2 = t.iloc[0:2] # two smallest rows by column 'a'
assert_col_equal(t2['a'], [1, 2])
t2 = t.iloc['b', 2:] # exclude two smallest rows in column 'b'
assert_col_equal(t2['b'], [5.1, 6.2, 7.0])
for t2 in (t.loc[:], t.iloc[:]):
assert_col_equal(t2['a'], [1, 2, 3, 4, 5])
def test_table_loc_indices(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine)
t.add_index('b', engine=engine)
t2 = t.loc_indices[self.make_val(3)] # single label, with primary key 'a'
assert t2 == 2
# list search
t2 = t.loc_indices[[self.make_val(1), self.make_val(4), self.make_val(2)]]
for i, p in zip(t2, [1, 4, 2]): # same order as input list
assert i == p - 1
def test_invalid_search(self, main_col, table_types, engine):
# using .loc and .loc_indices with a value not present should raise an exception
self._setup(main_col, table_types)
t = self.t
t.add_index('a')
with pytest.raises(KeyError):
t.loc[self.make_val(6)]
with pytest.raises(KeyError):
t.loc_indices[self.make_val(6)]
def test_copy_index_references(self, main_col, table_types, engine):
# check against a bug in which indices were given an incorrect
# column reference when copied
self._setup(main_col, table_types)
t = self.t
t.add_index('a')
t.add_index('b')
t2 = t.copy()
assert t2.indices['a'].columns[0] is t2['a']
assert t2.indices['b'].columns[0] is t2['b']
def test_unique_index(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = self.t
t.add_index('a', engine=engine, unique=True)
assert np.all(t.indices['a'].sorted_data() == [0, 1, 2, 3, 4])
if self.mutable:
with pytest.raises(ValueError):
t.add_row((5.0, '9', 5))
def test_copy_indexed_table(self, table_types):
self._setup(_col, table_types)
t = self.t
t.add_index('a')
t.add_index(['a', 'b'])
for tp in (self._table_type(t), t.copy()):
assert len(t.indices) == len(tp.indices)
for index, indexp in zip(t.indices, tp.indices):
assert np.all(index.data.data == indexp.data.data)
assert index.data.data.colnames == indexp.data.data.colnames
def test_updating_row_byindex(self, main_col, table_types, engine):
self._setup(main_col, table_types)
t = Table([['a', 'b', 'c', 'd'], [2, 3, 4, 5], [3, 4, 5, 6]],
names=('a', 'b', 'c'), meta={'name': 'first table'})
t.add_index('a', engine=engine)
t.add_index('b', engine=engine)
t.loc['c'] = ['g', 40, 50] # single label, with primary key 'a'
t2 = t[2]
assert list(t2) == ['g', 40, 50]
# list search
t.loc[['a', 'd', 'b']] = [['a', 20, 30], ['d', 50, 60], ['b', 30, 40]]
t2 = [['a', 20, 30], ['d', 50, 60], ['b', 30, 40]]
for i, p in zip(t2, [1, 4, 2]): # same order as input list
assert list(t[p - 1]) == i
def test_invalid_updates(self, main_col, table_types, engine):
# using .loc and .loc_indices with a value not present should raise an exception
self._setup(main_col, table_types)
t = Table([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]],
names=('a', 'b', 'c'), meta={'name': 'first table'})
t.add_index('a')
with pytest.raises(ValueError):
t.loc[3] = [[1, 2, 3]]
with pytest.raises(ValueError):
t.loc[[1, 4, 2]] = [[1, 2, 3], [4, 5, 6]]
with pytest.raises(ValueError):
t.loc[[1, 4, 2]] = [[1, 2, 3], [4, 5, 6], [2, 3]]
with pytest.raises(ValueError):
t.loc[[1, 4, 2]] = [[1, 2, 3], [4, 5], [2, 3]]
def test_get_index():
a = [1, 4, 5, 2, 7, 4, 45]
b = [2.0, 5.0, 8.2, 3.7, 4.3, 6.5, 3.3]
t = Table([a, b], names=('a', 'b'), meta={'name': 'first table'})
t.add_index(['a'])
# Getting the values of index using names
x1 = get_index(t, names=['a'])
assert isinstance(x1, SlicedIndex)
assert len(x1.columns) == 1
assert len(x1.columns[0]) == 7
assert x1.columns[0].info.name == 'a'
# Getting the vales of index using table_copy
x2 = get_index(t, table_copy=t[['a']])
assert isinstance(x2, SlicedIndex)
assert len(x2.columns) == 1
assert len(x2.columns[0]) == 7
assert x2.columns[0].info.name == 'a'
with pytest.raises(ValueError):
get_index(t, names=['a'], table_copy=t[['a']])
with pytest.raises(ValueError):
get_index(t, names=None, table_copy=None)
def test_table_index_time_warning(engine):
# Make sure that no ERFA warnings are emitted when indexing a table by
# a Time column with a non-default time scale
tab = Table()
tab['a'] = Time([1, 2, 3], format='jyear', scale='tai')
tab['b'] = [4, 3, 2]
with warnings.catch_warnings(record=True) as wlist:
tab.add_index(('a', 'b'), engine=engine)
assert len(wlist) == 0
@pytest.mark.parametrize('col', [
Column(np.arange(50000, 50005)),
np.arange(50000, 50005) * u.m,
Time(np.arange(50000, 50005), format='mjd')])
def test_table_index_does_not_propagate_to_column_slices(col):
# They lost contact to the parent table, so they should also not have
# information on the indices; this helps prevent large memory usage if,
# e.g., a large time column is turned into an object array; see gh-10688.
tab = QTable()
tab['t'] = col
tab.add_index('t')
t = tab['t']
assert t.info.indices
tx = t[1:]
assert not tx.info.indices
tabx = tab[1:]
t = tabx['t']
assert t.info.indices
def test_hstack_qtable_table():
# Check in particular that indices are initialized or copied correctly
# for a Column that is being converted to a Quantity.
qtab = QTable([np.arange(5.)*u.m], names=['s'])
qtab.add_index('s')
tab = Table([Column(np.arange(5.), unit=u.s)], names=['t'])
qstack = hstack([qtab, tab])
assert qstack['t'].info.indices == []
assert qstack.indices == []
def test_index_slice_exception():
with pytest.raises(TypeError, match='index_slice must be tuple or slice'):
SlicedIndex(None, None)
|
3994814cf4403b97d67b83c4f1dcba5f76bbb146d24d083888667175570dbc17 | from os.path import abspath, dirname, join
import textwrap
import pytest
from astropy.coordinates import SkyCoord
from astropy.time import Time
from astropy.table.table import Table
from astropy import extern
from astropy.utils.compat.optional_deps import HAS_BLEACH, HAS_IPYTHON # noqa
from astropy.utils.misc import _NOT_OVERWRITING_MSG_MATCH
EXTERN_DIR = abspath(join(dirname(extern.__file__), 'jquery', 'data'))
REFERENCE = """
<html>
<head>
<meta charset="utf-8"/>
<meta content="text/html;charset=UTF-8" http-equiv="Content-type"/>
<style>
body {font-family: sans-serif;}
table.dataTable {width: auto !important; margin: 0 !important;}
.dataTables_filter, .dataTables_paginate {float: left !important; margin-left:1em}
</style>
<link href="%(datatables_css_url)s" rel="stylesheet" type="text/css"/>
<script src="%(jquery_url)s">
</script>
<script src="%(datatables_js_url)s">
</script>
</head>
<body>
<script>
var astropy_sort_num = function(a, b) {
var a_num = parseFloat(a);
var b_num = parseFloat(b);
if (isNaN(a_num) && isNaN(b_num))
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
else if (!isNaN(a_num) && !isNaN(b_num))
return ((a_num < b_num) ? -1 : ((a_num > b_num) ? 1 : 0));
else
return isNaN(a_num) ? -1 : 1;
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"optionalnum-asc": astropy_sort_num,
"optionalnum-desc": function (a,b) { return -astropy_sort_num(a, b); }
});
$(document).ready(function() {
$('#%(table_id)s').dataTable({
order: [],
pageLength: %(length)s,
lengthMenu: [[%(display_length)s, -1], [%(display_length)s, 'All']],
pagingType: "full_numbers",
columnDefs: [{targets: [0], type: "optionalnum"}]
});
} ); </script>
<table class="%(table_class)s" id="%(table_id)s">
<thead>
<tr>
<th>a</th>
<th>b</th>
</tr>
</thead>
%(lines)s
</table>
</body>
</html>
"""
TPL = (' <tr>\n'
' <td>{0}</td>\n'
' <td>{1}</td>\n'
' </tr>')
def format_lines(col1, col2):
col1_format = getattr(col1.info, 'default_format', lambda x: x)
col2_format = getattr(col2.info, 'default_format', lambda x: x)
return '\n'.join(TPL.format(col1_format(v1), col2_format(v2))
for v1, v2 in zip(col1, col2))
def test_write_jsviewer_default(tmpdir):
t = Table()
t['a'] = [1, 2, 3, 4, 5]
t['b'] = ['a', 'b', 'c', 'd', 'e']
t['a'].unit = 'm'
tmpfile = tmpdir.join('test.html').strpath
t.write(tmpfile, format='jsviewer')
ref = REFERENCE % dict(
lines=format_lines(t['a'], t['b']),
table_class='display compact',
table_id=f'table{id(t)}',
length='50',
display_length='10, 25, 50, 100, 500, 1000',
datatables_css_url='https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css',
datatables_js_url='https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js',
jquery_url='https://code.jquery.com/jquery-3.1.1.min.js'
)
with open(tmpfile) as f:
assert f.read().strip() == ref.strip()
def test_write_jsviewer_overwrite(tmpdir):
t = Table()
t['a'] = [1, 2, 3, 4, 5]
t['b'] = ['a', 'b', 'c', 'd', 'e']
t['a'].unit = 'm'
tmpfile = tmpdir.join('test.html').strpath
# normal write
t.write(tmpfile, format='jsviewer')
# errors on overwrite
with pytest.raises(OSError, match=_NOT_OVERWRITING_MSG_MATCH):
t.write(tmpfile, format='jsviewer')
# unless specified
t.write(tmpfile, format='jsviewer', overwrite=True)
@pytest.mark.parametrize('mixin', [
Time(['J2000', 'J2001']),
Time([50000., 50001.0001], format='mjd'),
SkyCoord(ra=[100., 110.], dec=[-10., 10.], unit='deg')])
def test_write_jsviewer_mixin(tmpdir, mixin):
t = Table()
t['a'] = [1, 2]
t['b'] = mixin
t['a'].unit = 'm'
tmpfile = tmpdir.join('test.html').strpath
t.write(tmpfile, format='jsviewer')
ref = REFERENCE % dict(
lines=format_lines(t['a'], t['b']),
table_class='display compact',
table_id=f'table{id(t)}',
length='50',
display_length='10, 25, 50, 100, 500, 1000',
datatables_css_url='https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css',
datatables_js_url='https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js',
jquery_url='https://code.jquery.com/jquery-3.1.1.min.js'
)
with open(tmpfile) as f:
assert f.read().strip() == ref.strip()
@pytest.mark.skipif('not HAS_BLEACH')
def test_write_jsviewer_options(tmpdir):
t = Table()
t['a'] = [1, 2, 3, 4, 5]
t['b'] = ['<b>a</b>', 'b', 'c', 'd', 'e']
t['a'].unit = 'm'
tmpfile = tmpdir.join('test.html').strpath
t.write(tmpfile, format='jsviewer', table_id='test', max_lines=3,
jskwargs={'display_length': 5}, table_class='display hover',
htmldict=dict(raw_html_cols='b'))
ref = REFERENCE % dict(
lines=format_lines(t['a'][:3], t['b'][:3]),
table_class='display hover',
table_id='test',
length='5',
display_length='5, 10, 25, 50, 100, 500, 1000',
datatables_css_url='https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css',
datatables_js_url='https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js',
jquery_url='https://code.jquery.com/jquery-3.1.1.min.js'
)
with open(tmpfile) as f:
assert f.read().strip() == ref.strip()
def test_write_jsviewer_local(tmpdir):
t = Table()
t['a'] = [1, 2, 3, 4, 5]
t['b'] = ['a', 'b', 'c', 'd', 'e']
t['a'].unit = 'm'
tmpfile = tmpdir.join('test.html').strpath
t.write(tmpfile, format='jsviewer', table_id='test',
jskwargs={'use_local_files': True})
ref = REFERENCE % dict(
lines=format_lines(t['a'], t['b']),
table_class='display compact',
table_id='test',
length='50',
display_length='10, 25, 50, 100, 500, 1000',
datatables_css_url='file://' + join(EXTERN_DIR, 'css', 'jquery.dataTables.css'),
datatables_js_url='file://' + join(EXTERN_DIR, 'js', 'jquery.dataTables.min.js'),
jquery_url='file://' + join(EXTERN_DIR, 'js', 'jquery-3.1.1.min.js')
)
with open(tmpfile) as f:
assert f.read().strip() == ref.strip()
@pytest.mark.skipif('not HAS_IPYTHON')
def test_show_in_notebook():
t = Table()
t['a'] = [1, 2, 3, 4, 5]
t['b'] = ['b', 'c', 'a', 'd', 'e']
htmlstr_windx = t.show_in_notebook().data # should default to 'idx'
htmlstr_windx_named = t.show_in_notebook(show_row_index='realidx').data
htmlstr_woindx = t.show_in_notebook(show_row_index=False).data
assert (textwrap.dedent("""
<thead><tr><th>idx</th><th>a</th><th>b</th></tr></thead>
<tr><td>0</td><td>1</td><td>b</td></tr>
<tr><td>1</td><td>2</td><td>c</td></tr>
<tr><td>2</td><td>3</td><td>a</td></tr>
<tr><td>3</td><td>4</td><td>d</td></tr>
<tr><td>4</td><td>5</td><td>e</td></tr>
""").strip() in htmlstr_windx)
assert '<thead><tr><th>realidx</th><th>a</th><th>b</th></tr></thead>' in htmlstr_windx_named
assert '<thead><tr><th>a</th><th>b</th></tr></thead>' in htmlstr_woindx
|
748aaddb9faff2cba63c7923bc334e9bbdbcc54291357f31b42122baa1a627c6 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from collections import OrderedDict, UserDict
from collections.abc import Mapping
import pytest
import numpy as np
from astropy.table import Column, TableColumns, Table, MaskedColumn
import astropy.units as u
class DictLike(Mapping):
"""A minimal mapping-like object that does not subclass dict.
This is used to test code that expects dict-like but without actually
inheriting from dict.
"""
def __init__(self, *args, **kwargs):
self._data = dict(*args, **kwargs)
def __getitem__(self, item):
return self._data[item]
def __setitem__(self, item, value):
self._data[item] = value
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
class TestTableColumnsInit():
def test_init(self):
"""Test initialisation with lists, tuples, dicts of arrays
rather than Columns [regression test for #2647]"""
x1 = np.arange(10.)
x2 = np.arange(5.)
x3 = np.arange(7.)
col_list = [('x1', x1), ('x2', x2), ('x3', x3)]
tc_list = TableColumns(col_list)
for col in col_list:
assert col[0] in tc_list
assert tc_list[col[0]] is col[1]
col_tuple = (('x1', x1), ('x2', x2), ('x3', x3))
tc_tuple = TableColumns(col_tuple)
for col in col_tuple:
assert col[0] in tc_tuple
assert tc_tuple[col[0]] is col[1]
col_dict = dict([('x1', x1), ('x2', x2), ('x3', x3)])
tc_dict = TableColumns(col_dict)
for col in tc_dict.keys():
assert col in tc_dict
assert tc_dict[col] is col_dict[col]
columns = [Column(col[1], name=col[0]) for col in col_list]
tc = TableColumns(columns)
for col in columns:
assert col.name in tc
assert tc[col.name] is col
# pytest.mark.usefixtures('table_type')
class BaseInitFrom():
def _setup(self, table_type):
pass
def test_basic_init(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=('a', 'b', 'c'))
assert t.colnames == ['a', 'b', 'c']
assert np.all(t['a'] == np.array([1, 3]))
assert np.all(t['b'] == np.array([2, 4]))
assert np.all(t['c'] == np.array([3, 5]))
assert all(t[name].name == name for name in t.colnames)
def test_set_dtype(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=('a', 'b', 'c'), dtype=('i4', 'f4', 'f8'))
assert t.colnames == ['a', 'b', 'c']
assert np.all(t['a'] == np.array([1, 3], dtype='i4'))
assert np.all(t['b'] == np.array([2, 4], dtype='f4'))
assert np.all(t['c'] == np.array([3, 5], dtype='f8'))
assert t['a'].dtype.type == np.int32
assert t['b'].dtype.type == np.float32
assert t['c'].dtype.type == np.float64
assert all(t[name].name == name for name in t.colnames)
def test_names_dtype_mismatch(self, table_type):
self._setup(table_type)
with pytest.raises(ValueError):
table_type(self.data, names=('a',), dtype=('i4', 'f4', 'i4'))
def test_names_cols_mismatch(self, table_type):
self._setup(table_type)
with pytest.raises(ValueError):
table_type(self.data, names=('a',), dtype=('i4'))
@pytest.mark.usefixtures('table_type')
class BaseInitFromListLike(BaseInitFrom):
def test_names_cols_mismatch(self, table_type):
self._setup(table_type)
with pytest.raises(ValueError):
table_type(self.data, names=['a'], dtype=[int])
def test_names_copy_false(self, table_type):
self._setup(table_type)
with pytest.raises(ValueError):
table_type(self.data, names=['a'], dtype=[int], copy=False)
@pytest.mark.usefixtures('table_type')
class BaseInitFromDictLike(BaseInitFrom):
pass
@pytest.mark.usefixtures('table_type')
class TestInitFromNdarrayHomo(BaseInitFromListLike):
def setup_method(self, method):
self.data = np.array([(1, 2, 3),
(3, 4, 5)],
dtype='i4')
def test_default_names(self, table_type):
self._setup(table_type)
t = table_type(self.data)
assert t.colnames == ['col0', 'col1', 'col2']
def test_ndarray_ref(self, table_type):
"""Init with ndarray and copy=False and show that this is a reference
to input ndarray"""
self._setup(table_type)
t = table_type(self.data, copy=False)
t['col1'][1] = 0
assert t.as_array()['col1'][1] == 0
assert t['col1'][1] == 0
assert self.data[1][1] == 0
def test_partial_names_dtype(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['a', None, 'c'], dtype=[None, None, 'f8'])
assert t.colnames == ['a', 'col1', 'c']
assert t['a'].dtype.type == np.int32
assert t['col1'].dtype.type == np.int32
assert t['c'].dtype.type == np.float64
assert all(t[name].name == name for name in t.colnames)
def test_partial_names_ref(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['a', None, 'c'])
assert t.colnames == ['a', 'col1', 'c']
assert t['a'].dtype.type == np.int32
assert t['col1'].dtype.type == np.int32
assert t['c'].dtype.type == np.int32
assert all(t[name].name == name for name in t.colnames)
@pytest.mark.usefixtures('table_type')
class TestInitFromListOfLists(BaseInitFromListLike):
def setup_method(self, table_type):
self._setup(table_type)
self.data = [(np.int32(1), np.int32(3)),
Column(name='col1', data=[2, 4], dtype=np.int32),
np.array([3, 5], dtype=np.int32)]
def test_default_names(self, table_type):
self._setup(table_type)
t = table_type(self.data)
assert t.colnames == ['col0', 'col1', 'col2']
assert all(t[name].name == name for name in t.colnames)
def test_partial_names_dtype(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['b', None, 'c'],
dtype=['f4', None, 'f8'])
assert t.colnames == ['b', 'col1', 'c']
assert t['b'].dtype.type == np.float32
assert t['col1'].dtype.type == np.int32
assert t['c'].dtype.type == np.float64
assert all(t[name].name == name for name in t.colnames)
def test_bad_data(self, table_type):
self._setup(table_type)
with pytest.raises(ValueError):
table_type([[1, 2],
[3, 4, 5]])
@pytest.mark.usefixtures('table_type')
class TestInitFromListOfDicts(BaseInitFromListLike):
def _setup(self, table_type):
self.data = [{'a': 1, 'b': 2, 'c': 3},
{'a': 3, 'b': 4, 'c': 5}]
self.data_ragged = [{'a': 1, 'b': 2},
{'a': 2, 'c': 4}]
def test_names(self, table_type):
self._setup(table_type)
t = table_type(self.data)
assert all(colname in set(['a', 'b', 'c']) for colname in t.colnames)
def test_names_ordered(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=('c', 'b', 'a'))
assert t.colnames == ['c', 'b', 'a']
def test_missing_data_init_from_dict(self, table_type):
self._setup(table_type)
dat = self.data_ragged
for rows in [False, True]:
t = table_type(rows=dat) if rows else table_type(dat)
assert np.all(t['a'] == [1, 2])
assert np.all(t['b'].mask == [False, True])
assert np.all(t['b'].data == [2, 2])
assert np.all(t['c'].mask == [True, False])
assert np.all(t['c'].data == [4, 4])
assert type(t['a']) is (MaskedColumn if t.masked else Column)
assert type(t['b']) is MaskedColumn
assert type(t['c']) is MaskedColumn
class TestInitFromListOfMapping(TestInitFromListOfDicts):
"""Test that init from a Mapping that is not a dict subclass works"""
def _setup(self, table_type):
self.data = [DictLike(a=1, b=2, c=3),
DictLike(a=3, b=4, c=5)]
self.data_ragged = [DictLike(a=1, b=2),
DictLike(a=2, c=4)]
# Make sure data rows are not a dict subclass
assert not isinstance(self.data[0], dict)
@pytest.mark.usefixtures('table_type')
class TestInitFromColsList(BaseInitFromListLike):
def _setup(self, table_type):
self.data = [Column([1, 3], name='x', dtype=np.int32),
np.array([2, 4], dtype=np.int32),
np.array([3, 5], dtype='i8')]
def test_default_names(self, table_type):
self._setup(table_type)
t = table_type(self.data)
assert t.colnames == ['x', 'col1', 'col2']
assert all(t[name].name == name for name in t.colnames)
def test_partial_names_dtype(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['b', None, 'c'], dtype=['f4', None, 'f8'])
assert t.colnames == ['b', 'col1', 'c']
assert t['b'].dtype.type == np.float32
assert t['col1'].dtype.type == np.int32
assert t['c'].dtype.type == np.float64
assert all(t[name].name == name for name in t.colnames)
def test_ref(self, table_type):
"""Test that initializing from a list of columns can be done by reference"""
self._setup(table_type)
t = table_type(self.data, copy=False)
t['x'][0] = 100
assert self.data[0][0] == 100
@pytest.mark.usefixtures('table_type')
class TestInitFromNdarrayStruct(BaseInitFromDictLike):
def _setup(self, table_type):
self.data = np.array([(1, 2, 3),
(3, 4, 5)],
dtype=[('x', 'i8'), ('y', 'i4'), ('z', 'i8')])
def test_ndarray_ref(self, table_type):
"""Init with ndarray and copy=False and show that table uses reference
to input ndarray"""
self._setup(table_type)
t = table_type(self.data, copy=False)
t['x'][1] = 0 # Column-wise assignment
t[0]['y'] = 0 # Row-wise assignment
assert self.data['x'][1] == 0
assert self.data['y'][0] == 0
assert np.all(np.array(t) == self.data)
assert all(t[name].name == name for name in t.colnames)
def test_partial_names_dtype(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['e', None, 'd'], dtype=['f4', None, 'f8'])
assert t.colnames == ['e', 'y', 'd']
assert t['e'].dtype.type == np.float32
assert t['y'].dtype.type == np.int32
assert t['d'].dtype.type == np.float64
assert all(t[name].name == name for name in t.colnames)
def test_partial_names_ref(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['e', None, 'd'], copy=False)
assert t.colnames == ['e', 'y', 'd']
assert t['e'].dtype.type == np.int64
assert t['y'].dtype.type == np.int32
assert t['d'].dtype.type == np.int64
assert all(t[name].name == name for name in t.colnames)
@pytest.mark.usefixtures('table_type')
class TestInitFromDict(BaseInitFromDictLike):
def _setup(self, table_type):
self.data = dict([('a', Column([1, 3], name='x')),
('b', [2, 4]),
('c', np.array([3, 5], dtype='i8'))])
@pytest.mark.usefixtures('table_type')
class TestInitFromMapping(BaseInitFromDictLike):
def _setup(self, table_type):
self.data = UserDict([('a', Column([1, 3], name='x')),
('b', [2, 4]),
('c', np.array([3, 5], dtype='i8'))])
assert isinstance(self.data, Mapping)
assert not isinstance(self.data, dict)
@pytest.mark.usefixtures('table_type')
class TestInitFromOrderedDict(BaseInitFromDictLike):
def _setup(self, table_type):
self.data = OrderedDict([('a', Column(name='x', data=[1, 3])),
('b', [2, 4]),
('c', np.array([3, 5], dtype='i8'))])
def test_col_order(self, table_type):
self._setup(table_type)
t = table_type(self.data)
assert t.colnames == ['a', 'b', 'c']
@pytest.mark.usefixtures('table_type')
class TestInitFromRow(BaseInitFromDictLike):
def _setup(self, table_type):
arr = np.array([(1, 2, 3),
(3, 4, 5)],
dtype=[('x', 'i8'), ('y', 'i8'), ('z', 'f8')])
self.data = table_type(arr, meta={'comments': ['comment1', 'comment2']})
def test_init_from_row(self, table_type):
self._setup(table_type)
t = table_type(self.data[0])
# Values and meta match original
assert t.meta['comments'][0] == 'comment1'
for name in t.colnames:
assert np.all(t[name] == self.data[name][0:1])
assert all(t[name].name == name for name in t.colnames)
# Change value in new instance and check that original is the same
t['x'][0] = 8
t.meta['comments'][1] = 'new comment2'
assert np.all(t['x'] == np.array([8]))
assert np.all(self.data['x'] == np.array([1, 3]))
assert self.data.meta['comments'][1] == 'comment2'
@pytest.mark.usefixtures('table_type')
class TestInitFromTable(BaseInitFromDictLike):
def _setup(self, table_type):
arr = np.array([(1, 2, 3),
(3, 4, 5)],
dtype=[('x', 'i8'), ('y', 'i8'), ('z', 'f8')])
self.data = table_type(arr, meta={'comments': ['comment1', 'comment2']})
def test_data_meta_copy(self, table_type):
self._setup(table_type)
t = table_type(self.data)
assert t.meta['comments'][0] == 'comment1'
t['x'][1] = 8
t.meta['comments'][1] = 'new comment2'
assert self.data.meta['comments'][1] == 'comment2'
assert np.all(t['x'] == np.array([1, 8]))
assert np.all(self.data['x'] == np.array([1, 3]))
assert t['z'].name == 'z'
assert all(t[name].name == name for name in t.colnames)
def test_table_ref(self, table_type):
self._setup(table_type)
t = table_type(self.data, copy=False)
t['x'][1] = 0
assert t['x'][1] == 0
assert self.data['x'][1] == 0
assert np.all(t.as_array() == self.data.as_array())
assert all(t[name].name == name for name in t.colnames)
def test_partial_names_dtype(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['e', None, 'd'], dtype=['f4', None, 'i8'])
assert t.colnames == ['e', 'y', 'd']
assert t['e'].dtype.type == np.float32
assert t['y'].dtype.type == np.int64
assert t['d'].dtype.type == np.int64
assert all(t[name].name == name for name in t.colnames)
def test_partial_names_ref(self, table_type):
self._setup(table_type)
t = table_type(self.data, names=['e', None, 'd'], copy=False)
assert t.colnames == ['e', 'y', 'd']
assert t['e'].dtype.type == np.int64
assert t['y'].dtype.type == np.int64
assert t['d'].dtype.type == np.float64
assert all(t[name].name == name for name in t.colnames)
def test_init_from_columns(self, table_type):
self._setup(table_type)
t = table_type(self.data)
t2 = table_type(t.columns['z', 'x', 'y'])
assert t2.colnames == ['z', 'x', 'y']
assert t2.dtype.names == ('z', 'x', 'y')
def test_init_from_columns_slice(self, table_type):
self._setup(table_type)
t = table_type(self.data)
t2 = table_type(t.columns[0:2])
assert t2.colnames == ['x', 'y']
assert t2.dtype.names == ('x', 'y')
def test_init_from_columns_mix(self, table_type):
self._setup(table_type)
t = table_type(self.data)
t2 = table_type([t.columns[0], t.columns['z']])
assert t2.colnames == ['x', 'z']
assert t2.dtype.names == ('x', 'z')
@pytest.mark.usefixtures('table_type')
class TestInitFromNone():
# Note table_table.TestEmptyData tests initializing a completely empty
# table and adding data.
def test_data_none_with_cols(self, table_type):
"""
Test different ways of initing an empty table
"""
np_t = np.empty(0, dtype=[('a', 'f4', (2,)),
('b', 'i4')])
for kwargs in ({'names': ('a', 'b')},
{'names': ('a', 'b'), 'dtype': (('f4', (2,)), 'i4')},
{'dtype': [('a', 'f4', (2,)), ('b', 'i4')]},
{'dtype': np_t.dtype}):
t = table_type(**kwargs)
assert t.colnames == ['a', 'b']
assert len(t['a']) == 0
assert len(t['b']) == 0
if 'dtype' in kwargs:
assert t['a'].dtype.type == np.float32
assert t['b'].dtype.type == np.int32
assert t['a'].shape[1:] == (2,)
@pytest.mark.usefixtures('table_types')
class TestInitFromRows():
def test_init_with_rows(self, table_type):
for rows in ([[1, 'a'], [2, 'b']],
[(1, 'a'), (2, 'b')],
((1, 'a'), (2, 'b'))):
t = table_type(rows=rows, names=('a', 'b'))
assert np.all(t['a'] == [1, 2])
assert np.all(t['b'] == ['a', 'b'])
assert t.colnames == ['a', 'b']
assert t['a'].dtype.kind == 'i'
assert t['b'].dtype.kind in ('S', 'U')
# Regression test for
# https://github.com/astropy/astropy/issues/3052
assert t['b'].dtype.str.endswith('1')
rows = np.arange(6).reshape(2, 3)
t = table_type(rows=rows, names=('a', 'b', 'c'), dtype=['f8', 'f4', 'i8'])
assert np.all(t['a'] == [0, 3])
assert np.all(t['b'] == [1, 4])
assert np.all(t['c'] == [2, 5])
assert t.colnames == ['a', 'b', 'c']
assert t['a'].dtype.str.endswith('f8')
assert t['b'].dtype.str.endswith('f4')
assert t['c'].dtype.str.endswith('i8')
def test_init_with_rows_and_data(self, table_type):
with pytest.raises(ValueError) as err:
table_type(data=[[1]], rows=[[1]])
assert "Cannot supply both `data` and `rows` values" in str(err.value)
@pytest.mark.parametrize('has_data', [True, False])
def test_init_table_with_names_and_structured_dtype(has_data):
"""Test fix for #10393"""
arr = np.ones(2, dtype=np.dtype([('a', 'i4'), ('b', 'f4')]))
data_args = [arr] if has_data else []
t = Table(*data_args, names=['x', 'y'], dtype=arr.dtype)
assert t.colnames == ['x', 'y']
assert str(t['x'].dtype) == 'int32'
assert str(t['y'].dtype) == 'float32'
assert len(t) == (2 if has_data else 0)
@pytest.mark.usefixtures('table_type')
def test_init_and_ref_from_multidim_ndarray(table_type):
"""
Test that initializing from an ndarray structured array with
a multi-dim column works for both copy=False and True and that
the referencing is as expected.
"""
for copy in (False, True):
nd = np.array([(1, [10, 20]),
(3, [30, 40])],
dtype=[('a', 'i8'), ('b', 'i8', (2,))])
t = table_type(nd, copy=copy)
assert t.colnames == ['a', 'b']
assert t['a'].shape == (2,)
assert t['b'].shape == (2, 2)
t['a'][0] = -200
t['b'][1][1] = -100
if copy:
assert nd['a'][0] == 1
assert nd['b'][1][1] == 40
else:
assert nd['a'][0] == -200
assert nd['b'][1][1] == -100
@pytest.mark.usefixtures('table_type')
@pytest.mark.parametrize('copy', [False, True])
def test_init_and_ref_from_dict(table_type, copy):
"""
Test that initializing from a dict works for both copy=False and True and that
the referencing is as expected.
"""
x1 = np.arange(10.)
x2 = np.zeros(10)
col_dict = dict([('x1', x1), ('x2', x2)])
t = table_type(col_dict, copy=copy)
assert set(t.colnames) == set(['x1', 'x2'])
assert t['x1'].shape == (10,)
assert t['x2'].shape == (10,)
t['x1'][0] = -200
t['x2'][1] = -100
if copy:
assert x1[0] == 0.
assert x2[1] == 0.
else:
assert x1[0] == -200
assert x2[1] == -100
def test_add_none_object_column():
"""Test fix for a problem introduced in #10636 (see
https://github.com/astropy/astropy/pull/10636#issuecomment-676847515)
"""
t = Table(data={'a': [1, 2, 3]})
t['b'] = None
assert all(val is None for val in t['b'])
assert t['b'].dtype.kind == 'O'
@pytest.mark.usefixtures('table_type')
def test_init_from_row_OrderedDict(table_type):
row1 = OrderedDict([('b', 1), ('a', 0)])
row2 = {'a': 10, 'b': 20}
rows12 = [row1, row2]
row3 = dict([('b', 1), ('a', 0)])
row4 = dict([('b', 11), ('a', 10)])
rows34 = [row3, row4]
t1 = table_type(rows=rows12)
t2 = table_type(rows=rows34)
t3 = t2[sorted(t2.colnames)]
assert t1.colnames == ['b', 'a']
assert t2.colnames == ['b', 'a']
assert t3.colnames == ['a', 'b']
def test_init_from_rows_as_generator():
rows = ((1 + ii, 2 + ii) for ii in range(2))
t = Table(rows=rows)
assert np.all(t['col0'] == [1, 2])
assert np.all(t['col1'] == [2, 3])
@pytest.mark.parametrize('dtype', ['fail', 'i4'])
def test_init_bad_dtype_in_empty_table(dtype):
with pytest.raises(ValueError,
match='type was specified but could not be parsed for column names'):
Table(dtype=dtype)
def test_init_data_type_not_allowed_to_init_table():
with pytest.raises(ValueError,
match="Data type <class 'str'> not allowed to init Table"):
Table('hello')
def test_init_Table_from_list_of_quantity():
"""Test fix for #11327"""
# Variation on original example in #11327 at the Table level
data = [{'x': 5 * u.m, 'y': 1 * u.m}, {'x': 10 * u.m, 'y': 3}]
t = Table(data)
assert t['x'].unit is u.m
assert t['y'].unit is None
assert t['x'].dtype.kind == 'f'
assert t['y'].dtype.kind == 'O'
assert np.all(t['x'] == [5, 10])
assert t['y'][0] == 1 * u.m
assert t['y'][1] == 3
|
24fc704dcc5c0bdf8c554bf570c146738a16355a93055cfcb4ef6792a168d9aa | import os
import re
import pytest
from astropy.table.scripts import showtable
ROOT = os.path.abspath(os.path.dirname(__file__))
ASCII_ROOT = os.path.join(ROOT, '..', '..', 'io', 'ascii', 'tests')
FITS_ROOT = os.path.join(ROOT, '..', '..', 'io', 'fits', 'tests')
VOTABLE_ROOT = os.path.join(ROOT, '..', '..', 'io', 'votable', 'tests')
def test_missing_file(capsys):
showtable.main(['foobar.fits'])
out, err = capsys.readouterr()
assert err.startswith("ERROR: [Errno 2] No such file or directory: "
"'foobar.fits'")
def test_info(capsys):
showtable.main([os.path.join(FITS_ROOT, 'data/table.fits'), '--info'])
out, err = capsys.readouterr()
assert out.splitlines() == ['<Table length=3>',
' name dtype ',
'------ -------',
'target bytes20',
' V_mag float32']
def test_stats(capsys):
showtable.main([os.path.join(FITS_ROOT, 'data/table.fits'), '--stats'])
out, err = capsys.readouterr()
expected = ['<Table length=3>',
' name mean std min max ',
'------ ------- ------- ---- ----',
'target -- -- -- --',
' V_mag 12.866[0-9]? 1.72111 11.1 15.2']
out = out.splitlines()
assert out[:4] == expected[:4]
# Here we use re.match as in some cases one of the values above is
# platform-dependent.
assert re.match(expected[4], out[4]) is not None
def test_fits(capsys):
showtable.main([os.path.join(FITS_ROOT, 'data/table.fits')])
out, err = capsys.readouterr()
assert out.splitlines() == [' target V_mag',
'------- -----',
'NGC1001 11.1',
'NGC1002 12.3',
'NGC1003 15.2']
def test_fits_hdu(capsys):
from astropy.units import UnitsWarning
with pytest.warns(UnitsWarning):
showtable.main([
os.path.join(FITS_ROOT, 'data/zerowidth.fits'),
'--hdu', 'AIPS OF',
])
out, err = capsys.readouterr()
assert out.startswith(
' TIME SOURCE ID ANTENNA NO. SUBARRAY FREQ ID ANT FLAG STATUS 1\n'
' DAYS \n'
'---------- --------- ----------- -------- ------- -------- --------\n'
'0.14438657 1 10 1 1 4 4\n')
def test_csv(capsys):
showtable.main([os.path.join(ASCII_ROOT, 'data/simple_csv.csv')])
out, err = capsys.readouterr()
assert out.splitlines() == [' a b c ',
'--- --- ---',
' 1 2 3',
' 4 5 6']
def test_ascii_format(capsys):
showtable.main([os.path.join(ASCII_ROOT, 'data/commented_header.dat'),
'--format', 'ascii.commented_header'])
out, err = capsys.readouterr()
assert out.splitlines() == [' a b c ',
'--- --- ---',
' 1 2 3',
' 4 5 6']
def test_ascii_delimiter(capsys):
showtable.main([os.path.join(ASCII_ROOT, 'data/simple2.txt'),
'--format', 'ascii', '--delimiter', '|'])
out, err = capsys.readouterr()
assert out.splitlines() == [
"obsid redshift X Y object rad ",
"----- -------- ---- ---- ----------- ----",
" 3102 0.32 4167 4085 Q1250+568-A 9.0",
" 3102 0.32 4706 3916 Q1250+568-B 14.0",
" 877 0.22 4378 3892 'Source 82' 12.5",
]
def test_votable(capsys):
showtable.main([os.path.join(VOTABLE_ROOT, 'data/regression.xml'),
'--table-id', 'main_table', '--max-width', '50'])
out, err = capsys.readouterr()
assert out.splitlines() == [
' string_test string_test_2 ... bitarray2 [16]',
'----------------- ------------- ... --------------',
' String & test Fixed stri ... True .. False',
'String & test 0123456789 ... -- .. --',
' XXXX XXXX ... -- .. --',
' ... -- .. --',
' ... -- .. --',
]
def test_max_lines(capsys):
showtable.main([os.path.join(ASCII_ROOT, 'data/cds2.dat'),
'--format', 'ascii.cds', '--max-lines', '7',
'--max-width', '30'])
out, err = capsys.readouterr()
assert out.splitlines() == [
' SST ... Note',
' ... ',
'--------------- ... ----',
'041314.1+281910 ... --',
' ... ... ...',
'044427.1+251216 ... --',
'044642.6+245903 ... --',
'Length = 215 rows',
]
def test_show_dtype(capsys):
showtable.main([os.path.join(FITS_ROOT, 'data/table.fits'),
'--show-dtype'])
out, err = capsys.readouterr()
assert out.splitlines() == [
' target V_mag ',
'bytes20 float32',
'------- -------',
'NGC1001 11.1',
'NGC1002 12.3',
'NGC1003 15.2',
]
def test_hide_unit(capsys):
showtable.main([os.path.join(ASCII_ROOT, 'data/cds.dat'),
'--format', 'ascii.cds'])
out, err = capsys.readouterr()
assert out.splitlines() == [
'Index RAh RAm RAs DE- DEd DEm DEs Match Class AK Fit ',
' h min s deg arcmin arcsec mag GMsun',
'----- --- --- ----- --- --- ------ ------ ----- ----- --- -----',
' 1 3 28 39.09 + 31 6 1.9 -- I* -- 1.35',
]
showtable.main([os.path.join(ASCII_ROOT, 'data/cds.dat'),
'--format', 'ascii.cds', '--hide-unit'])
out, err = capsys.readouterr()
assert out.splitlines() == [
'Index RAh RAm RAs DE- DEd DEm DEs Match Class AK Fit ',
'----- --- --- ----- --- --- --- --- ----- ----- --- ----',
' 1 3 28 39.09 + 31 6 1.9 -- I* -- 1.35',
]
|
19f176ef230bdee9bff7bba6da6cd7536557ae2f232d4eefb7ac2425568849d4 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from astropy.table import Table, Column, QTable, table_helpers, NdarrayMixin, unique
from astropy.utils.compat import NUMPY_LT_1_22, NUMPY_LT_1_22_1
from astropy.utils.exceptions import AstropyUserWarning
from astropy import time
from astropy import units as u
from astropy import coordinates
def sort_eq(list1, list2):
return sorted(list1) == sorted(list2)
def test_column_group_by(T1):
for masked in (False, True):
t1 = Table(T1, masked=masked)
t1a = t1['a'].copy()
# Group by a Column (i.e. numpy array)
t1ag = t1a.group_by(t1['a'])
assert np.all(t1ag.groups.indices == np.array([0, 1, 4, 8]))
# Group by a Table
t1ag = t1a.group_by(t1['a', 'b'])
assert np.all(t1ag.groups.indices == np.array([0, 1, 3, 4, 5, 7, 8]))
# Group by a numpy structured array
t1ag = t1a.group_by(t1['a', 'b'].as_array())
assert np.all(t1ag.groups.indices == np.array([0, 1, 3, 4, 5, 7, 8]))
def test_table_group_by(T1):
"""
Test basic table group_by functionality for possible key types and for
masked/unmasked tables.
"""
for masked in (False, True):
t1 = Table(T1, masked=masked)
# Group by a single column key specified by name
tg = t1.group_by('a')
assert np.all(tg.groups.indices == np.array([0, 1, 4, 8]))
assert str(tg.groups) == "<TableGroups indices=[0 1 4 8]>"
assert str(tg['a'].groups) == "<ColumnGroups indices=[0 1 4 8]>"
# Sorted by 'a' and in original order for rest
assert tg.pformat() == [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 1 b 3.0 5',
' 1 a 2.0 6',
' 1 a 1.0 7',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 a 4.0 3']
assert tg.meta['ta'] == 1
assert tg['c'].meta['a'] == 1
assert tg['c'].description == 'column c'
# Group by a table column
tg2 = t1.group_by(t1['a'])
assert tg.pformat() == tg2.pformat()
# Group by two columns spec'd by name
for keys in (['a', 'b'], ('a', 'b')):
tg = t1.group_by(keys)
assert np.all(tg.groups.indices == np.array([0, 1, 3, 4, 5, 7, 8]))
# Sorted by 'a', 'b' and in original order for rest
assert tg.pformat() == [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 1 a 2.0 6',
' 1 a 1.0 7',
' 1 b 3.0 5',
' 2 a 4.0 3',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 c 7.0 0']
# Group by a Table
tg2 = t1.group_by(t1['a', 'b'])
assert tg.pformat() == tg2.pformat()
# Group by a structured array
tg2 = t1.group_by(t1['a', 'b'].as_array())
assert tg.pformat() == tg2.pformat()
# Group by a simple ndarray
tg = t1.group_by(np.array([0, 1, 0, 1, 2, 1, 0, 0]))
assert np.all(tg.groups.indices == np.array([0, 4, 7, 8]))
assert tg.pformat() == [' a b c d ',
'--- --- --- ---',
' 2 c 7.0 0',
' 2 b 6.0 2',
' 1 a 2.0 6',
' 1 a 1.0 7',
' 2 b 5.0 1',
' 2 a 4.0 3',
' 1 b 3.0 5',
' 0 a 0.0 4']
def test_groups_keys(T1):
tg = T1.group_by('a')
keys = tg.groups.keys
assert keys.dtype.names == ('a',)
assert np.all(keys['a'] == np.array([0, 1, 2]))
tg = T1.group_by(['a', 'b'])
keys = tg.groups.keys
assert keys.dtype.names == ('a', 'b')
assert np.all(keys['a'] == np.array([0, 1, 1, 2, 2, 2]))
assert np.all(keys['b'] == np.array(['a', 'a', 'b', 'a', 'b', 'c']))
# Grouping by Column ignores column name
tg = T1.group_by(T1['b'])
keys = tg.groups.keys
assert keys.dtype.names is None
def test_groups_iterator(T1):
tg = T1.group_by('a')
for ii, group in enumerate(tg.groups):
assert group.pformat() == tg.groups[ii].pformat()
assert group['a'][0] == tg['a'][tg.groups.indices[ii]]
def test_grouped_copy(T1):
"""
Test that copying a table or column copies the groups properly
"""
for masked in (False, True):
t1 = Table(T1, masked=masked)
tg = t1.group_by('a')
tgc = tg.copy()
assert np.all(tgc.groups.indices == tg.groups.indices)
assert np.all(tgc.groups.keys == tg.groups.keys)
tac = tg['a'].copy()
assert np.all(tac.groups.indices == tg['a'].groups.indices)
c1 = t1['a'].copy()
gc1 = c1.group_by(t1['a'])
gc1c = gc1.copy()
assert np.all(gc1c.groups.indices == np.array([0, 1, 4, 8]))
def test_grouped_slicing(T1):
"""
Test that slicing a table removes previous grouping
"""
for masked in (False, True):
t1 = Table(T1, masked=masked)
# Regular slice of a table
tg = t1.group_by('a')
tg2 = tg[3:5]
assert np.all(tg2.groups.indices == np.array([0, len(tg2)]))
assert tg2.groups.keys is None
def test_group_column_from_table(T1):
"""
Group a column that is part of a table
"""
cg = T1['c'].group_by(np.array(T1['a']))
assert np.all(cg.groups.keys == np.array([0, 1, 2]))
assert np.all(cg.groups.indices == np.array([0, 1, 4, 8]))
def test_table_groups_mask_index(T1):
"""
Use boolean mask as item in __getitem__ for groups
"""
for masked in (False, True):
t1 = Table(T1, masked=masked).group_by('a')
t2 = t1.groups[np.array([True, False, True])]
assert len(t2.groups) == 2
assert t2.groups[0].pformat() == t1.groups[0].pformat()
assert t2.groups[1].pformat() == t1.groups[2].pformat()
assert np.all(t2.groups.keys['a'] == np.array([0, 2]))
def test_table_groups_array_index(T1):
"""
Use numpy array as item in __getitem__ for groups
"""
for masked in (False, True):
t1 = Table(T1, masked=masked).group_by('a')
t2 = t1.groups[np.array([0, 2])]
assert len(t2.groups) == 2
assert t2.groups[0].pformat() == t1.groups[0].pformat()
assert t2.groups[1].pformat() == t1.groups[2].pformat()
assert np.all(t2.groups.keys['a'] == np.array([0, 2]))
def test_table_groups_slicing(T1):
"""
Test that slicing table groups works
"""
for masked in (False, True):
t1 = Table(T1, masked=masked).group_by('a')
# slice(0, 2)
t2 = t1.groups[0:2]
assert len(t2.groups) == 2
assert t2.groups[0].pformat() == t1.groups[0].pformat()
assert t2.groups[1].pformat() == t1.groups[1].pformat()
assert np.all(t2.groups.keys['a'] == np.array([0, 1]))
# slice(1, 2)
t2 = t1.groups[1:2]
assert len(t2.groups) == 1
assert t2.groups[0].pformat() == t1.groups[1].pformat()
assert np.all(t2.groups.keys['a'] == np.array([1]))
# slice(0, 3, 2)
t2 = t1.groups[0:3:2]
assert len(t2.groups) == 2
assert t2.groups[0].pformat() == t1.groups[0].pformat()
assert t2.groups[1].pformat() == t1.groups[2].pformat()
assert np.all(t2.groups.keys['a'] == np.array([0, 2]))
def test_grouped_item_access(T1):
"""
Test that column slicing preserves grouping
"""
for masked in (False, True):
t1 = Table(T1, masked=masked)
# Regular slice of a table
tg = t1.group_by('a')
tgs = tg['a', 'c', 'd']
assert np.all(tgs.groups.keys == tg.groups.keys)
assert np.all(tgs.groups.indices == tg.groups.indices)
tgsa = tgs.groups.aggregate(np.sum)
assert tgsa.pformat() == [' a c d ',
'--- ---- ---',
' 0 0.0 4',
' 1 6.0 18',
' 2 22.0 6']
tgs = tg['c', 'd']
assert np.all(tgs.groups.keys == tg.groups.keys)
assert np.all(tgs.groups.indices == tg.groups.indices)
tgsa = tgs.groups.aggregate(np.sum)
assert tgsa.pformat() == [' c d ',
'---- ---',
' 0.0 4',
' 6.0 18',
'22.0 6']
def test_mutable_operations(T1):
"""
Operations like adding or deleting a row should removing grouping,
but adding or removing or renaming a column should retain grouping.
"""
for masked in (False, True):
t1 = Table(T1, masked=masked)
# add row
tg = t1.group_by('a')
tg.add_row((0, 'a', 3.0, 4))
assert np.all(tg.groups.indices == np.array([0, len(tg)]))
assert tg.groups.keys is None
# remove row
tg = t1.group_by('a')
tg.remove_row(4)
assert np.all(tg.groups.indices == np.array([0, len(tg)]))
assert tg.groups.keys is None
# add column
tg = t1.group_by('a')
indices = tg.groups.indices.copy()
tg.add_column(Column(name='e', data=np.arange(len(tg))))
assert np.all(tg.groups.indices == indices)
assert np.all(tg['e'].groups.indices == indices)
assert np.all(tg['e'].groups.keys == tg.groups.keys)
# remove column (not key column)
tg = t1.group_by('a')
tg.remove_column('b')
assert np.all(tg.groups.indices == indices)
# Still has original key col names
assert tg.groups.keys.dtype.names == ('a',)
assert np.all(tg['a'].groups.indices == indices)
# remove key column
tg = t1.group_by('a')
tg.remove_column('a')
assert np.all(tg.groups.indices == indices)
assert tg.groups.keys.dtype.names == ('a',)
assert np.all(tg['b'].groups.indices == indices)
# rename key column
tg = t1.group_by('a')
tg.rename_column('a', 'aa')
assert np.all(tg.groups.indices == indices)
assert tg.groups.keys.dtype.names == ('a',)
assert np.all(tg['aa'].groups.indices == indices)
def test_group_by_masked(T1):
t1m = Table(T1, masked=True)
t1m['c'].mask[4] = True
t1m['d'].mask[5] = True
assert t1m.group_by('a').pformat() == [' a b c d ',
'--- --- --- ---',
' 0 a -- 4',
' 1 b 3.0 --',
' 1 a 2.0 6',
' 1 a 1.0 7',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 a 4.0 3']
def test_group_by_errors(T1):
"""
Appropriate errors get raised.
"""
# Bad column name as string
with pytest.raises(ValueError):
T1.group_by('f')
# Bad column names in list
with pytest.raises(ValueError):
T1.group_by(['f', 'g'])
# Wrong length array
with pytest.raises(ValueError):
T1.group_by(np.array([1, 2]))
# Wrong type
with pytest.raises(TypeError):
T1.group_by(None)
# Masked key column
t1 = Table(T1, masked=True)
t1['a'].mask[4] = True
with pytest.raises(ValueError):
t1.group_by('a')
def test_groups_keys_meta(T1):
"""
Make sure the keys meta['grouped_by_table_cols'] is working.
"""
# Group by column in this table
tg = T1.group_by('a')
assert tg.groups.keys.meta['grouped_by_table_cols'] is True
assert tg['c'].groups.keys.meta['grouped_by_table_cols'] is True
assert tg.groups[1].groups.keys.meta['grouped_by_table_cols'] is True
assert (tg['d'].groups[np.array([False, True, True])]
.groups.keys.meta['grouped_by_table_cols'] is True)
# Group by external Table
tg = T1.group_by(T1['a', 'b'])
assert tg.groups.keys.meta['grouped_by_table_cols'] is False
assert tg['c'].groups.keys.meta['grouped_by_table_cols'] is False
assert tg.groups[1].groups.keys.meta['grouped_by_table_cols'] is False
# Group by external numpy array
tg = T1.group_by(T1['a', 'b'].as_array())
assert not hasattr(tg.groups.keys, 'meta')
assert not hasattr(tg['c'].groups.keys, 'meta')
# Group by Column
tg = T1.group_by(T1['a'])
assert 'grouped_by_table_cols' not in tg.groups.keys.meta
assert 'grouped_by_table_cols' not in tg['c'].groups.keys.meta
def test_table_aggregate(T1):
"""
Aggregate a table
"""
# Table with only summable cols
t1 = T1['a', 'c', 'd']
tg = t1.group_by('a')
tga = tg.groups.aggregate(np.sum)
assert tga.pformat() == [' a c d ',
'--- ---- ---',
' 0 0.0 4',
' 1 6.0 18',
' 2 22.0 6']
# Reverts to default groups
assert np.all(tga.groups.indices == np.array([0, 3]))
assert tga.groups.keys is None
# metadata survives
assert tga.meta['ta'] == 1
assert tga['c'].meta['a'] == 1
assert tga['c'].description == 'column c'
# Aggregate with np.sum with masked elements. This results
# in one group with no elements, hence a nan result and conversion
# to float for the 'd' column.
t1m = Table(t1, masked=True)
t1m['c'].mask[4:6] = True
t1m['d'].mask[4:6] = True
tg = t1m.group_by('a')
with pytest.warns(UserWarning, match="converting a masked element to nan"):
tga = tg.groups.aggregate(np.sum)
assert tga.pformat() == [' a c d ',
'--- ---- ----',
' 0 nan nan',
' 1 3.0 13.0',
' 2 22.0 6.0']
# Aggregrate with np.sum with masked elements, but where every
# group has at least one remaining (unmasked) element. Then
# the int column stays as an int.
t1m = Table(t1, masked=True)
t1m['c'].mask[5] = True
t1m['d'].mask[5] = True
tg = t1m.group_by('a')
tga = tg.groups.aggregate(np.sum)
assert tga.pformat() == [' a c d ',
'--- ---- ---',
' 0 0.0 4',
' 1 3.0 13',
' 2 22.0 6']
# Aggregate with a column type that cannot by supplied to the aggregating
# function. This raises a warning but still works.
tg = T1.group_by('a')
with pytest.warns(AstropyUserWarning, match="Cannot aggregate column"):
tga = tg.groups.aggregate(np.sum)
assert tga.pformat() == [' a c d ',
'--- ---- ---',
' 0 0.0 4',
' 1 6.0 18',
' 2 22.0 6']
def test_table_aggregate_reduceat(T1):
"""
Aggregate table with functions which have a reduceat method
"""
# Comparison functions without reduceat
def np_mean(x):
return np.mean(x)
def np_sum(x):
return np.sum(x)
def np_add(x):
return np.add(x)
# Table with only summable cols
t1 = T1['a', 'c', 'd']
tg = t1.group_by('a')
# Comparison
tga_r = tg.groups.aggregate(np.sum)
tga_a = tg.groups.aggregate(np.add)
tga_n = tg.groups.aggregate(np_sum)
assert np.all(tga_r == tga_n)
assert np.all(tga_a == tga_n)
assert tga_n.pformat() == [' a c d ',
'--- ---- ---',
' 0 0.0 4',
' 1 6.0 18',
' 2 22.0 6']
tga_r = tg.groups.aggregate(np.mean)
tga_n = tg.groups.aggregate(np_mean)
assert np.all(tga_r == tga_n)
assert tga_n.pformat() == [' a c d ',
'--- --- ---',
' 0 0.0 4.0',
' 1 2.0 6.0',
' 2 5.5 1.5']
# Binary ufunc np_add should raise warning without reduceat
t2 = T1['a', 'c']
tg = t2.group_by('a')
with pytest.warns(AstropyUserWarning, match="Cannot aggregate column"):
tga = tg.groups.aggregate(np_add)
assert tga.pformat() == [' a ',
'---',
' 0',
' 1',
' 2']
def test_column_aggregate(T1):
"""
Aggregate a single table column
"""
for masked in (False, True):
tg = Table(T1, masked=masked).group_by('a')
tga = tg['c'].groups.aggregate(np.sum)
assert tga.pformat() == [' c ',
'----',
' 0.0',
' 6.0',
'22.0']
@pytest.mark.skipif(not NUMPY_LT_1_22 and NUMPY_LT_1_22_1,
reason='https://github.com/numpy/numpy/issues/20699')
def test_column_aggregate_f8():
"""https://github.com/astropy/astropy/issues/12706"""
# Just want to make sure it does not crash again.
for masked in (False, True):
tg = Table({'a': np.arange(2, dtype='>f8')}, masked=masked).group_by('a')
tga = tg['a'].groups.aggregate(np.sum)
assert tga.pformat() == [' a ',
'---',
'0.0',
'1.0']
def test_table_filter():
"""
Table groups filtering
"""
def all_positive(table, key_colnames):
colnames = [name for name in table.colnames if name not in key_colnames]
for colname in colnames:
if np.any(table[colname] < 0):
return False
return True
# Negative value in 'a' column should not filter because it is a key col
t = Table.read([' a c d',
' -2 7.0 0',
' -2 5.0 1',
' 0 0.0 4',
' 1 3.0 5',
' 1 2.0 -6',
' 1 1.0 7',
' 3 3.0 5',
' 3 -2.0 6',
' 3 1.0 7',
], format='ascii')
tg = t.group_by('a')
t2 = tg.groups.filter(all_positive)
assert t2.groups[0].pformat() == [' a c d ',
'--- --- ---',
' -2 7.0 0',
' -2 5.0 1']
assert t2.groups[1].pformat() == [' a c d ',
'--- --- ---',
' 0 0.0 4']
def test_column_filter():
"""
Table groups filtering
"""
def all_positive(column):
if np.any(column < 0):
return False
return True
# Negative value in 'a' column should not filter because it is a key col
t = Table.read([' a c d',
' -2 7.0 0',
' -2 5.0 1',
' 0 0.0 4',
' 1 3.0 5',
' 1 2.0 -6',
' 1 1.0 7',
' 3 3.0 5',
' 3 -2.0 6',
' 3 1.0 7',
], format='ascii')
tg = t.group_by('a')
c2 = tg['c'].groups.filter(all_positive)
assert len(c2.groups) == 3
assert c2.groups[0].pformat() == [' c ', '---', '7.0', '5.0']
assert c2.groups[1].pformat() == [' c ', '---', '0.0']
assert c2.groups[2].pformat() == [' c ', '---', '3.0', '2.0', '1.0']
def test_group_mixins():
"""
Test grouping a table with mixin columns
"""
# Setup mixins
idx = np.arange(4)
x = np.array([3., 1., 2., 1.])
q = x * u.m
lon = coordinates.Longitude(x * u.deg)
lat = coordinates.Latitude(x * u.deg)
# For Time do J2000.0 + few * 0.1 ns (this requires > 64 bit precision)
tm = time.Time(2000, format='jyear') + time.TimeDelta(x * 1e-10, format='sec')
sc = coordinates.SkyCoord(ra=lon, dec=lat)
aw = table_helpers.ArrayWrapper(x)
nd = np.array([(3, 'c'), (1, 'a'), (2, 'b'), (1, 'a')],
dtype='<i4,|S1').view(NdarrayMixin)
qt = QTable([idx, x, q, lon, lat, tm, sc, aw, nd],
names=['idx', 'x', 'q', 'lon', 'lat', 'tm', 'sc', 'aw', 'nd'])
# Test group_by with each supported mixin type
mixin_keys = ['x', 'q', 'lon', 'lat', 'tm', 'sc', 'aw', 'nd']
for key in mixin_keys:
qtg = qt.group_by(key)
# Test that it got the sort order correct
assert np.all(qtg['idx'] == [1, 3, 2, 0])
# Test that the groups are right
# Note: skip testing SkyCoord column because that doesn't have equality
for name in ['x', 'q', 'lon', 'lat', 'tm', 'aw', 'nd']:
assert np.all(qt[name][[1, 3]] == qtg.groups[0][name])
assert np.all(qt[name][[2]] == qtg.groups[1][name])
assert np.all(qt[name][[0]] == qtg.groups[2][name])
# Test that unique also works with mixins since most of the work is
# done with group_by(). This is using *every* mixin as key.
uqt = unique(qt, keys=mixin_keys)
assert len(uqt) == 3
assert np.all(uqt['idx'] == [1, 2, 0])
assert np.all(uqt['x'] == [1., 2., 3.])
# Column group_by() with mixins
idxg = qt['idx'].group_by(qt[mixin_keys])
assert np.all(idxg == [1, 3, 2, 0])
|
e7f41e4eb64df325591e837ca818667c5d2f57bd5457dacbdcd30dda5c842840 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test behavior related to masked tables"""
import pytest
import numpy as np
import numpy.ma as ma
from astropy.table import Column, MaskedColumn, Table, QTable
from astropy.table.column import BaseColumn
from astropy.time import Time
from astropy.utils.masked import Masked
import astropy.units as u
class SetupData:
def setup_method(self, method):
self.a = MaskedColumn(name='a', data=[1, 2, 3], fill_value=1)
self.b = MaskedColumn(name='b', data=[4, 5, 6], mask=True)
self.c = MaskedColumn(name='c', data=[7, 8, 9], mask=False)
self.d_mask = np.array([False, True, False])
self.d = MaskedColumn(name='d', data=[7, 8, 7], mask=self.d_mask)
self.t = Table([self.a, self.b], masked=True)
self.ca = Column(name='ca', data=[1, 2, 3])
self.sc = MaskedColumn(name='sc', data=[(1, 1.), (2, 2.), (3, 3.)],
dtype='i8,f8', fill_value=(0, -1.))
class TestPprint(SetupData):
def test_pformat(self):
assert self.t.pformat() == [' a b ', '--- ---', ' 1 --', ' 2 --', ' 3 --']
class TestFilled:
"""Test the filled method in MaskedColumn and Table"""
def setup_method(self, method):
mask = [True, False, False]
self.meta = {'a': 1, 'b': [2, 3]}
self.a = MaskedColumn(name='a', data=[1, 2, 3], fill_value=10, mask=mask, meta={'a': 1})
self.b = MaskedColumn(name='b', data=[4.0, 5.0, 6.0], fill_value=10.0, mask=mask)
self.c = MaskedColumn(name='c', data=['7', '8', '9'], fill_value='1', mask=mask)
def test_filled_column(self):
f = self.a.filled()
assert np.all(f == [10, 2, 3])
assert isinstance(f, Column)
assert not isinstance(f, MaskedColumn)
# Confirm copy, not ref
assert f.meta['a'] == 1
f.meta['a'] = 2
f[1] = 100
assert self.a[1] == 2
assert self.a.meta['a'] == 1
# Fill with arg fill_value not column fill_value
f = self.a.filled(20)
assert np.all(f == [20, 2, 3])
f = self.b.filled()
assert np.all(f == [10.0, 5.0, 6.0])
assert isinstance(f, Column)
f = self.c.filled()
assert np.all(f == ['1', '8', '9'])
assert isinstance(f, Column)
def test_filled_masked_table(self, tableclass):
t = tableclass([self.a, self.b, self.c], meta=self.meta)
f = t.filled()
assert isinstance(f, Table)
assert f.masked is False
assert np.all(f['a'] == [10, 2, 3])
assert np.allclose(f['b'], [10.0, 5.0, 6.0])
assert np.all(f['c'] == ['1', '8', '9'])
# Confirm copy, not ref
assert f.meta['b'] == [2, 3]
f.meta['b'][0] = 20
assert t.meta['b'] == [2, 3]
f['a'][2] = 100
assert t['a'][2] == 3
def test_filled_unmasked_table(self, tableclass):
t = tableclass([(1, 2), ('3', '4')], names=('a', 'b'), meta=self.meta)
f = t.filled()
assert isinstance(f, Table)
assert f.masked is False
assert np.all(f['a'] == t['a'])
assert np.all(f['b'] == t['b'])
# Confirm copy, not ref
assert f.meta['b'] == [2, 3]
f.meta['b'][0] = 20
assert t.meta['b'] == [2, 3]
f['a'][1] = 100
assert t['a'][1] == 2
class TestFillValue(SetupData):
"""Test setting and getting fill value in MaskedColumn and Table"""
def test_init_set_fill_value(self):
"""Check that setting fill_value in the MaskedColumn init works"""
assert self.a.fill_value == 1
c = MaskedColumn(name='c', data=['xxxx', 'yyyy'], fill_value='none')
assert c.fill_value == 'none'
def test_set_get_fill_value_for_bare_column(self):
"""Check set and get of fill value works for bare Column"""
self.d.fill_value = -999
assert self.d.fill_value == -999
assert np.all(self.d.filled() == [7, -999, 7])
def test_set_get_fill_value_for_str_column(self):
c = MaskedColumn(name='c', data=['xxxx', 'yyyy'], mask=[True, False])
# assert np.all(c.filled() == ['N/A', 'yyyy'])
c.fill_value = 'ABCDEF'
assert c.fill_value == 'ABCD' # string truncated to dtype length
assert np.all(c.filled() == ['ABCD', 'yyyy'])
assert np.all(c.filled('XY') == ['XY', 'yyyy'])
def test_set_get_fill_value_for_structured_column(self):
assert self.sc.fill_value == np.array((0, -1.), self.sc.dtype)
sc = self.sc.copy()
assert sc.fill_value.item() == (0, -1.)
sc.fill_value = (-1, np.inf)
assert sc.fill_value == np.array((-1, np.inf), self.sc.dtype)
sc2 = MaskedColumn(sc, fill_value=(-2, -np.inf))
assert sc2.fill_value == np.array((-2, -np.inf), sc2.dtype)
def test_table_column_mask_not_ref(self):
"""Table column mask is not ref of original column mask"""
self.b.fill_value = -999
assert self.t['b'].fill_value != -999
def test_set_get_fill_value_for_table_column(self):
"""Check set and get of fill value works for Column in a Table"""
self.t['b'].fill_value = 1
assert self.t['b'].fill_value == 1
assert np.all(self.t['b'].filled() == [1, 1, 1])
def test_data_attribute_fill_and_mask(self):
"""Check that .data attribute preserves fill_value and mask"""
self.t['b'].fill_value = 1
self.t['b'].mask = [True, False, True]
assert self.t['b'].data.fill_value == 1
assert np.all(self.t['b'].data.mask == [True, False, True])
class TestMaskedColumnInit(SetupData):
"""Initialization of a masked column"""
def test_set_mask_and_not_ref(self):
"""Check that mask gets set properly and that it is a copy, not ref"""
assert np.all(~self.a.mask)
assert np.all(self.b.mask)
assert np.all(~self.c.mask)
assert np.all(self.d.mask == self.d_mask)
self.d.mask[0] = True
assert not np.all(self.d.mask == self.d_mask)
def test_set_mask_from_list(self):
"""Set mask from a list"""
mask_list = [False, True, False]
a = MaskedColumn(name='a', data=[1, 2, 3], mask=mask_list)
assert np.all(a.mask == mask_list)
def test_override_existing_mask(self):
"""Override existing mask values"""
mask_list = [False, True, False]
b = MaskedColumn(name='b', data=self.b, mask=mask_list)
assert np.all(b.mask == mask_list)
def test_incomplete_mask_spec(self):
"""Incomplete mask specification raises MaskError"""
mask_list = [False, True]
with pytest.raises(ma.MaskError):
MaskedColumn(name='b', length=4, mask=mask_list)
class TestTableInit(SetupData):
"""Initializing a table"""
@pytest.mark.parametrize('type_str', ('?', 'b', 'i2', 'f4', 'c8', 'S', 'U', 'O'))
@pytest.mark.parametrize('shape', ((8,), (4, 2), (2, 2, 2)))
def test_init_from_sequence_data_numeric_typed(self, type_str, shape):
"""Test init from list or list of lists with dtype specified, optionally
including an np.ma.masked element.
"""
# Make data of correct dtype and shape, then turn into a list,
# then use that to init Table with spec'd type_str.
data = list(range(8))
np_data = np.array(data, dtype=type_str).reshape(shape)
np_data_list = np_data.tolist()
t = Table([np_data_list], dtype=[type_str])
col = t['col0']
assert col.dtype == np_data.dtype
assert np.all(col == np_data)
assert type(col) is Column
# Introduce np.ma.masked in the list input and confirm dtype still OK.
if len(shape) == 1:
np_data_list[-1] = np.ma.masked
elif len(shape) == 2:
np_data_list[-1][-1] = np.ma.masked
else:
np_data_list[-1][-1][-1] = np.ma.masked
last_idx = tuple(-1 for _ in shape)
t = Table([np_data_list], dtype=[type_str])
col = t['col0']
assert col.dtype == np_data.dtype
assert np.all(col == np_data)
assert col.mask[last_idx]
assert type(col) is MaskedColumn
@pytest.mark.parametrize('type_str', ('?', 'b', 'i2', 'f4', 'c8', 'S', 'U', 'O'))
@pytest.mark.parametrize('shape', ((8,), (4, 2), (2, 2, 2)))
def test_init_from_sequence_data_numeric_untyped(self, type_str, shape):
"""Test init from list or list of lists with dtype NOT specified,
optionally including an np.ma.masked element.
"""
data = list(range(8))
np_data = np.array(data, dtype=type_str).reshape(shape)
np_data_list = np_data.tolist()
t = Table([np_data_list])
# Grab the dtype that numpy assigns for the Python list inputs
dtype_expected = t['col0'].dtype
# Introduce np.ma.masked in the list input and confirm dtype still OK.
if len(shape) == 1:
np_data_list[-1] = np.ma.masked
elif len(shape) == 2:
np_data_list[-1][-1] = np.ma.masked
else:
np_data_list[-1][-1][-1] = np.ma.masked
last_idx = tuple(-1 for _ in shape)
t = Table([np_data_list])
col = t['col0']
# Confirm dtype is same as for untype list input w/ no mask
assert col.dtype == dtype_expected
assert np.all(col == np_data)
assert col.mask[last_idx]
assert type(col) is MaskedColumn
def test_initialization_with_all_columns(self):
t1 = Table([self.a, self.b, self.c, self.d, self.ca, self.sc])
assert t1.colnames == ['a', 'b', 'c', 'd', 'ca', 'sc']
# Check we get the same result by passing in as list of dict.
# (Regression test for error uncovered by scintillometry package.)
lofd = [{k: row[k] for k in t1.colnames} for row in t1]
t2 = Table(lofd)
for k in t1.colnames:
assert t1[k].dtype == t2[k].dtype
assert np.all(t1[k] == t2[k]) in (True, np.ma.masked)
assert np.all(getattr(t1[k], 'mask', False)
== getattr(t2[k], 'mask', False))
def test_mask_false_if_input_mask_not_true(self):
"""Masking is always False if initial masked arg is not True"""
t = Table([self.ca, self.a])
assert t.masked is False # True before astropy 4.0
t = Table([self.ca])
assert t.masked is False
t = Table([self.ca, ma.array([1, 2, 3])])
assert t.masked is False # True before astropy 4.0
def test_mask_false_if_no_input_masked(self):
"""Masking not true if not (requested or input requires mask)"""
t0 = Table([[3, 4]], masked=False)
t1 = Table(t0, masked=True)
t2 = Table(t1, masked=False)
assert not t0.masked
assert t1.masked
assert not t2.masked
def test_mask_property(self):
t = self.t
# Access table mask (boolean structured array) by column name
assert np.all(t.mask['a'] == np.array([False, False, False]))
assert np.all(t.mask['b'] == np.array([True, True, True]))
# Check that setting mask from table mask has the desired effect on column
t.mask['b'] = np.array([False, True, False])
assert np.all(t['b'].mask == np.array([False, True, False]))
# Non-masked table returns None for mask attribute
t2 = Table([self.ca], masked=False)
assert t2.mask is None
# Set mask property globally and verify local correctness
for mask in (True, False):
t.mask = mask
for name in ('a', 'b'):
assert np.all(t[name].mask == mask)
class TestAddColumn:
def test_add_masked_column_to_masked_table(self):
t = Table(masked=True)
assert t.masked
t.add_column(MaskedColumn(name='a', data=[1, 2, 3], mask=[0, 1, 0]))
assert t.masked
t.add_column(MaskedColumn(name='b', data=[4, 5, 6], mask=[1, 0, 1]))
assert t.masked
assert isinstance(t['a'], MaskedColumn)
assert isinstance(t['b'], MaskedColumn)
assert np.all(t['a'] == np.array([1, 2, 3]))
assert np.all(t['a'].mask == np.array([0, 1, 0], bool))
assert np.all(t['b'] == np.array([4, 5, 6]))
assert np.all(t['b'].mask == np.array([1, 0, 1], bool))
def test_add_masked_column_to_non_masked_table(self):
t = Table(masked=False)
assert not t.masked
t.add_column(Column(name='a', data=[1, 2, 3]))
assert not t.masked
t.add_column(MaskedColumn(name='b', data=[4, 5, 6], mask=[1, 0, 1]))
assert not t.masked # Changed in 4.0, table no longer auto-upgrades
assert isinstance(t['a'], Column) # Was MaskedColumn before 4.0
assert isinstance(t['b'], MaskedColumn)
assert np.all(t['a'] == np.array([1, 2, 3]))
assert not hasattr(t['a'], 'mask')
assert np.all(t['b'] == np.array([4, 5, 6]))
assert np.all(t['b'].mask == np.array([1, 0, 1], bool))
def test_add_non_masked_column_to_masked_table(self):
t = Table(masked=True)
assert t.masked
t.add_column(Column(name='a', data=[1, 2, 3]))
assert t.masked
t.add_column(MaskedColumn(name='b', data=[4, 5, 6], mask=[1, 0, 1]))
assert t.masked
assert isinstance(t['a'], MaskedColumn)
assert isinstance(t['b'], MaskedColumn)
assert np.all(t['a'] == np.array([1, 2, 3]))
assert np.all(t['a'].mask == np.array([0, 0, 0], bool))
assert np.all(t['b'] == np.array([4, 5, 6]))
assert np.all(t['b'].mask == np.array([1, 0, 1], bool))
def test_convert_to_masked_table_only_if_necessary(self):
# Do not convert to masked table, if new column has no masked value.
# See #1185 for details.
t = Table(masked=False)
assert not t.masked
t.add_column(Column(name='a', data=[1, 2, 3]))
assert not t.masked
t.add_column(MaskedColumn(name='b', data=[4, 5, 6], mask=[0, 0, 0]))
assert not t.masked
assert np.all(t['a'] == np.array([1, 2, 3]))
assert np.all(t['b'] == np.array([4, 5, 6]))
class TestRenameColumn:
def test_rename_masked_column(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1, 2, 3], mask=[0, 1, 0]))
t['a'].fill_value = 42
t.rename_column('a', 'b')
assert t.masked
assert np.all(t['b'] == np.array([1, 2, 3]))
assert np.all(t['b'].mask == np.array([0, 1, 0], bool))
assert t['b'].fill_value == 42
assert t.colnames == ['b']
class TestRemoveColumn:
def test_remove_masked_column(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1, 2, 3], mask=[0, 1, 0]))
t['a'].fill_value = 42
t.add_column(MaskedColumn(name='b', data=[4, 5, 6], mask=[1, 0, 1]))
t.remove_column('b')
assert t.masked
assert np.all(t['a'] == np.array([1, 2, 3]))
assert np.all(t['a'].mask == np.array([0, 1, 0], bool))
assert t['a'].fill_value == 42
assert t.colnames == ['a']
class TestAddRow:
def test_add_masked_row_to_masked_table_iterable(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1], mask=[0]))
t.add_column(MaskedColumn(name='b', data=[4], mask=[1]))
t.add_row([2, 5], mask=[1, 0])
t.add_row([3, 6], mask=[0, 1])
assert t.masked
assert np.all(np.array(t['a']) == np.array([1, 2, 3]))
assert np.all(t['a'].mask == np.array([0, 1, 0], bool))
assert np.all(np.array(t['b']) == np.array([4, 5, 6]))
assert np.all(t['b'].mask == np.array([1, 0, 1], bool))
def test_add_masked_row_to_masked_table_mapping1(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1], mask=[0]))
t.add_column(MaskedColumn(name='b', data=[4], mask=[1]))
t.add_row({'b': 5, 'a': 2}, mask={'a': 1, 'b': 0})
t.add_row({'a': 3, 'b': 6}, mask={'b': 1, 'a': 0})
assert t.masked
assert np.all(np.array(t['a']) == np.array([1, 2, 3]))
assert np.all(t['a'].mask == np.array([0, 1, 0], bool))
assert np.all(np.array(t['b']) == np.array([4, 5, 6]))
assert np.all(t['b'].mask == np.array([1, 0, 1], bool))
def test_add_masked_row_to_masked_table_mapping2(self):
# When adding values to a masked table, if the mask is specified as a
# dict, then values not specified will have mask values set to True
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1], mask=[0]))
t.add_column(MaskedColumn(name='b', data=[4], mask=[1]))
t.add_row({'b': 5}, mask={'b': 0})
t.add_row({'a': 3}, mask={'a': 0})
assert t.masked
assert t['a'][0] == 1 and t['a'][2] == 3
assert np.all(t['a'].mask == np.array([0, 1, 0], bool))
assert t['b'][1] == 5
assert np.all(t['b'].mask == np.array([1, 0, 1], bool))
def test_add_masked_row_to_masked_table_mapping3(self):
# When adding values to a masked table, if mask is not passed to
# add_row, then the mask should be set to False if values are present
# and True if not.
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1], mask=[0]))
t.add_column(MaskedColumn(name='b', data=[4], mask=[1]))
t.add_row({'b': 5})
t.add_row({'a': 3})
assert t.masked
assert t['a'][0] == 1 and t['a'][2] == 3
assert np.all(t['a'].mask == np.array([0, 1, 0], bool))
assert t['b'][1] == 5
assert np.all(t['b'].mask == np.array([1, 0, 1], bool))
def test_add_masked_row_to_masked_table_mapping4(self):
# When adding values to a masked table, if the mask is specified as a
# dict, then keys in values should match keys in mask
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1], mask=[0]))
t.add_column(MaskedColumn(name='b', data=[4], mask=[1]))
with pytest.raises(ValueError) as exc:
t.add_row({'b': 5}, mask={'a': True})
assert exc.value.args[0] == 'keys in mask should match keys in vals'
def test_add_masked_row_to_masked_table_mismatch(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name='a', data=[1], mask=[0]))
t.add_column(MaskedColumn(name='b', data=[4], mask=[1]))
with pytest.raises(TypeError) as exc:
t.add_row([2, 5], mask={'a': 1, 'b': 0})
assert exc.value.args[0] == "Mismatch between type of vals and mask"
with pytest.raises(TypeError) as exc:
t.add_row({'b': 5, 'a': 2}, mask=[1, 0])
assert exc.value.args[0] == "Mismatch between type of vals and mask"
def test_add_masked_row_to_non_masked_table_iterable(self):
t = Table(masked=False)
t['a'] = [1]
t['b'] = [4]
t['c'] = Time([1], format='cxcsec')
tm = Time(2, format='cxcsec')
assert not t.masked
t.add_row([2, 5, tm])
assert not t.masked
t.add_row([3, 6, tm], mask=[0, 1, 1])
assert not t.masked
assert type(t['a']) is Column
assert type(t['b']) is MaskedColumn
assert type(t['c']) is Time
assert np.all(t['a'] == [1, 2, 3])
assert np.all(t['b'].data == [4, 5, 6])
assert np.all(t['b'].mask == [False, False, True])
assert np.all(t['c'][:2] == Time([1, 2], format='cxcsec'))
assert np.all(t['c'].mask == [False, False, True])
def test_add_row_cannot_mask_column_raises_typeerror(self):
t = QTable()
t['a'] = [1, 2] * u.m
t.add_row((3 * u.m,)) # No problem
with pytest.raises(ValueError) as exc:
t.add_row((3 * u.m,), mask=(True,))
assert (exc.value.args[0].splitlines()
== ["Unable to insert row because of exception in column 'a':",
"mask was supplied for column 'a' but it does not support masked values"])
def test_setting_from_masked_column():
"""Test issue in #2997"""
mask_b = np.array([True, True, False, False])
for select in (mask_b, slice(0, 2)):
t = Table(masked=True)
t['a'] = Column([1, 2, 3, 4])
t['b'] = MaskedColumn([11, 22, 33, 44], mask=mask_b)
t['c'] = MaskedColumn([111, 222, 333, 444], mask=[True, False, True, False])
t['b'][select] = t['c'][select]
assert t['b'][1] == t[1]['b']
assert t['b'][0] is np.ma.masked # Original state since t['c'][0] is masked
assert t['b'][1] == 222 # New from t['c'] since t['c'][1] is unmasked
assert t['b'][2] == 33
assert t['b'][3] == 44
assert np.all(t['b'].mask == t.mask['b']) # Avoid t.mask in general, this is for testing
mask_before_add = t.mask.copy()
t['d'] = np.arange(len(t))
assert np.all(t.mask['b'] == mask_before_add['b'])
def test_coercing_fill_value_type():
"""
Test that masked column fill_value is coerced into the correct column type.
"""
# This is the original example posted on the astropy@scipy mailing list
t = Table({'a': ['1']}, masked=True)
t['a'].set_fill_value('0')
t2 = Table(t, names=['a'], dtype=[np.int32])
assert isinstance(t2['a'].fill_value, np.int32)
# Unit test the same thing.
c = MaskedColumn(['1'])
c.set_fill_value('0')
c2 = MaskedColumn(c, dtype=np.int32)
assert isinstance(c2.fill_value, np.int32)
def test_mask_copy():
"""Test that the mask is copied when copying a table (issue #7362)."""
c = MaskedColumn([1, 2], mask=[False, True])
c2 = MaskedColumn(c, copy=True)
c2.mask[0] = True
assert np.all(c.mask == [False, True])
assert np.all(c2.mask == [True, True])
def test_masked_as_array_with_mixin():
"""Test that as_array() and Table.mask attr work with masked mixin columns"""
t = Table()
t['a'] = Time([1, 2], format='cxcsec')
t['b'] = [3, 4]
t['c'] = [5, 6] * u.m
# With no mask, the output should be ndarray
ta = t.as_array()
assert isinstance(ta, np.ndarray) and not isinstance(ta, np.ma.MaskedArray)
# With a mask, output is MaskedArray
t['a'][1] = np.ma.masked
ta = t.as_array()
assert isinstance(ta, np.ma.MaskedArray)
assert np.all(ta['a'].mask == [False, True])
assert np.isclose(ta['a'][0].cxcsec, 1.0)
assert np.all(ta['b'].mask == False) # noqa
assert np.all(ta['c'].mask == False) # noqa
# Check table ``mask`` property
tm = t.mask
assert np.all(tm['a'] == [False, True])
assert np.all(tm['b'] == False) # noqa
assert np.all(tm['c'] == False) # noqa
def test_masked_column_with_unit_in_qtable():
"""Test that adding a MaskedColumn with a unit to QTable creates a MaskedQuantity."""
MaskedQuantity = Masked(u.Quantity)
t = QTable()
t['a'] = MaskedColumn([1, 2])
assert isinstance(t['a'], MaskedColumn)
t['b'] = MaskedColumn([1, 2], unit=u.m)
assert isinstance(t['b'], MaskedQuantity)
assert np.all(t['b'].mask == False) # noqa
t['c'] = MaskedColumn([1, 2], unit=u.m, mask=[True, False])
assert isinstance(t['c'], MaskedQuantity)
assert np.all(t['c'].mask == [True, False])
def test_masked_quantity_in_table():
MaskedQuantity = Masked(u.Quantity)
t = Table()
t['b'] = MaskedQuantity([1, 2], unit=u.m)
assert isinstance(t['b'], MaskedColumn)
assert np.all(t['b'].mask == False) # noqa
t['c'] = MaskedQuantity([1, 2], unit=u.m, mask=[True, False])
assert isinstance(t['c'], MaskedColumn)
assert np.all(t['c'].mask == [True, False])
def test_masked_column_data_attribute_is_plain_masked_array():
c = MaskedColumn([1, 2], mask=[False, True])
c_data = c.data
assert type(c_data) is np.ma.MaskedArray
assert type(c_data.data) is np.ndarray
def test_mask_slicing_count_array_finalize():
"""Check that we don't finalize MaskedColumn too often.
Regression test for gh-6721.
"""
# Create a new BaseColumn class that counts how often
# ``__array_finalize__`` is called.
class MyBaseColumn(BaseColumn):
counter = 0
def __array_finalize__(self, obj):
super().__array_finalize__(obj)
MyBaseColumn.counter += 1
# Base a new MaskedColumn class on it. The normal MaskedColumn
# hardcodes the initialization to BaseColumn, so we exchange that.
class MyMaskedColumn(MaskedColumn, Column, MyBaseColumn):
def __new__(cls, *args, **kwargs):
self = super().__new__(cls, *args, **kwargs)
self._baseclass = MyBaseColumn
return self
# Creation really needs 2 finalizations (once for the BaseColumn
# call inside ``__new__`` and once when the view as a MaskedColumn
# is taken), but since the first is hardcoded, we do not capture it
# and thus the count is only 1.
c = MyMaskedColumn([1, 2], mask=[False, True])
assert MyBaseColumn.counter == 1
# slicing should need only one ``__array_finalize__`` (used to be 3).
c0 = c[:]
assert MyBaseColumn.counter == 2
# repr should need none (used to be 2!!)
repr(c0)
assert MyBaseColumn.counter == 2
|
ea1dbfd0aacf254431687a9b0e63c34bb15e975dde27fb81d74b3b68a8951d32 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
""" Verify item access API in:
https://github.com/astropy/astropy/wiki/Table-item-access-definition
"""
import pytest
import numpy as np
@pytest.mark.usefixtures('table_data')
class BaseTestItems():
pass
@pytest.mark.usefixtures('table_data')
class TestTableColumnsItems(BaseTestItems):
def test_by_name(self, table_data):
"""Access TableColumns by name and show that item access returns
a Column that refers to underlying table data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
assert self.tc['a'].name == 'a'
assert self.tc['a'][1] == 2
assert self.tc['a'].description == 'da'
assert self.tc['a'].format == '%i'
assert self.tc['a'].meta == {'ma': 1}
assert self.tc['a'].unit == 'ua'
assert self.tc['a'].attrs_equal(table_data.COLS[0])
assert isinstance(self.tc['a'], table_data.Column)
self.tc['b'][1] = 0
assert self.t['b'][1] == 0
def test_by_position(self, table_data):
"""Access TableColumns by position and show that item access returns
a Column that refers to underlying table data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
assert self.tc[1].name == 'b'
assert np.all(self.tc[1].data == table_data.COLS[1].data)
assert self.tc[1].description == 'db'
assert self.tc[1].format == '%d'
assert self.tc[1].meta == {'mb': 1}
assert self.tc[1].unit == 'ub'
assert self.tc[1].attrs_equal(table_data.COLS[1])
assert isinstance(self.tc[1], table_data.Column)
assert self.tc[2].unit == 'ub'
self.tc[1][1] = 0
assert self.t['b'][1] == 0
def test_mult_columns(self, table_data):
"""Access TableColumns with "fancy indexing" and showed that returned
TableColumns object still references original data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
tc2 = self.tc['b', 'c']
assert tc2[1].name == 'c'
assert tc2[1][1] == 8
assert tc2[0].name == 'b'
assert tc2[0][1] == 5
tc2['c'][1] = 0
assert self.tc['c'][1] == 0
assert self.t['c'][1] == 0
def test_column_slice(self, table_data):
"""Access TableColumns with slice and showed that returned
TableColumns object still references original data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
tc2 = self.tc[1:3]
assert tc2[1].name == 'c'
assert tc2[1][1] == 8
assert tc2[0].name == 'b'
assert tc2[0][1] == 5
tc2['c'][1] = 0
assert self.tc['c'][1] == 0
assert self.t['c'][1] == 0
@pytest.mark.usefixtures('table_data')
class TestTableItems(BaseTestItems):
@pytest.mark.parametrize("idx", [1, np.int64(1), np.array(1)])
def test_column(self, table_data, idx):
"""Column access returns REFERENCE to data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
a = self.t['a']
assert a[idx] == 2
a[idx] = 0
assert self.t['a'][idx] == 0
@pytest.mark.parametrize("idx", [1, np.int64(1), np.array(1)])
def test_row(self, table_data, idx):
"""Row access returns REFERENCE to data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
row = self.t[idx]
assert row['a'] == 2
assert row[idx] == 5
assert row.columns['a'].attrs_equal(table_data.COLS[0])
assert row.columns['b'].attrs_equal(table_data.COLS[1])
assert row.columns['c'].attrs_equal(table_data.COLS[2])
# Check that setting by col index sets the table and row value
row[idx] = 0
assert row[idx] == 0
assert row['b'] == 0
assert self.t['b'][idx] == 0
assert self.t[idx]['b'] == 0
# Check that setting by col name sets the table and row value
row['a'] = 0
assert row[0] == 0
assert row['a'] == 0
assert self.t['a'][1] == 0
assert self.t[1]['a'] == 0
def test_empty_iterable_item(self, table_data):
"""
Table item access with [], (), or np.array([]) returns the same table
with no rows.
"""
self.t = table_data.Table(table_data.COLS)
for item in [], (), np.array([]):
t2 = self.t[item]
assert not t2
assert len(t2) == 0
assert t2['a'].attrs_equal(table_data.COLS[0])
assert t2['b'].attrs_equal(table_data.COLS[1])
assert t2['c'].attrs_equal(table_data.COLS[2])
def test_table_slice(self, table_data):
"""Table slice returns REFERENCE to data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
t2 = self.t[1:3]
assert np.all(t2['a'] == table_data.DATA['a'][1:3])
assert t2['a'].attrs_equal(table_data.COLS[0])
assert t2['b'].attrs_equal(table_data.COLS[1])
assert t2['c'].attrs_equal(table_data.COLS[2])
t2['a'][0] = 0
assert np.all(self.t['a'] == np.array([1, 0, 3]))
assert t2.masked == self.t.masked
assert t2._column_class == self.t._column_class
assert isinstance(t2, table_data.Table)
def test_fancy_index_slice(self, table_data):
"""Table fancy slice returns COPY of data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
slice = np.array([0, 2])
t2 = self.t[slice]
assert np.all(t2['a'] == table_data.DATA['a'][slice])
assert t2['a'].attrs_equal(table_data.COLS[0])
assert t2['b'].attrs_equal(table_data.COLS[1])
assert t2['c'].attrs_equal(table_data.COLS[2])
t2['a'][0] = 0
assert np.all(self.t.as_array() == table_data.DATA)
assert np.any(t2['a'] != table_data.DATA['a'][slice])
assert t2.masked == self.t.masked
assert t2._column_class == self.t._column_class
assert isinstance(t2, table_data.Table)
def test_list_index_slice(self, table_data):
"""Table list index slice returns COPY of data"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
slice = [0, 2]
t2 = self.t[slice]
assert np.all(t2['a'] == table_data.DATA['a'][slice])
assert t2['a'].attrs_equal(table_data.COLS[0])
assert t2['b'].attrs_equal(table_data.COLS[1])
assert t2['c'].attrs_equal(table_data.COLS[2])
t2['a'][0] = 0
assert np.all(self.t.as_array() == table_data.DATA)
assert np.any(t2['a'] != table_data.DATA['a'][slice])
assert t2.masked == self.t.masked
assert t2._column_class == self.t._column_class
assert isinstance(t2, table_data.Table)
def test_select_columns(self, table_data):
"""Select columns returns COPY of data and all column
attributes"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
# try both lists and tuples
for columns in (('a', 'c'), ['a', 'c']):
t2 = self.t[columns]
assert np.all(t2['a'] == table_data.DATA['a'])
assert np.all(t2['c'] == table_data.DATA['c'])
assert t2['a'].attrs_equal(table_data.COLS[0])
assert t2['c'].attrs_equal(table_data.COLS[2])
t2['a'][0] = 0
assert np.all(self.t.as_array() == table_data.DATA)
assert np.any(t2['a'] != table_data.DATA['a'])
assert t2.masked == self.t.masked
assert t2._column_class == self.t._column_class
def test_select_columns_fail(self, table_data):
"""Selecting a column that doesn't exist fails"""
self.t = table_data.Table(table_data.COLS)
with pytest.raises(KeyError) as err:
self.t[['xxxx']]
assert "'xxxx'" in str(err.value)
with pytest.raises(KeyError) as err:
self.t[['xxxx', 'yyyy']]
assert "'xxxx'" in str(err.value)
def test_np_where(self, table_data):
"""Select rows using output of np.where"""
t = table_data.Table(table_data.COLS)
# Select last two rows
rows = np.where(t['a'] > 1.5)
t2 = t[rows]
assert np.all(t2['a'] == [2, 3])
assert np.all(t2['b'] == [5, 6])
assert isinstance(t2, table_data.Table)
# Select no rows
rows = np.where(t['a'] > 100)
t2 = t[rows]
assert len(t2) == 0
assert isinstance(t2, table_data.Table)
def test_np_integers(self, table_data):
"""
Select rows using numpy integers. This is a regression test for a
py 3.3 failure mode
"""
t = table_data.Table(table_data.COLS)
idxs = np.random.randint(len(t), size=2)
t[idxs[1]]
def test_select_bad_column(self, table_data):
"""Select column name that does not exist"""
self.t = table_data.Table(table_data.COLS)
self.tc = self.t.columns
with pytest.raises(ValueError):
self.t['a', 1]
|
e77e257a06b33ea0318ffee9ec485d32697ab8d805cb7941e4ac2a727cfcff17 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy import table
from astropy.table import pprint
class MyRow(table.Row):
def __str__(self):
return str(self.as_void())
class MyColumn(table.Column):
pass
class MyMaskedColumn(table.MaskedColumn):
pass
class MyTableColumns(table.TableColumns):
pass
class MyTableFormatter(pprint.TableFormatter):
pass
class MyTable(table.Table):
Row = MyRow
Column = MyColumn
MaskedColumn = MyMaskedColumn
TableColumns = MyTableColumns
TableFormatter = MyTableFormatter
def test_simple_subclass():
t = MyTable([[1, 2], [3, 4]])
row = t[0]
assert isinstance(row, MyRow)
assert isinstance(t['col0'], MyColumn)
assert isinstance(t.columns, MyTableColumns)
assert isinstance(t.formatter, MyTableFormatter)
t2 = MyTable(t)
row = t2[0]
assert isinstance(row, MyRow)
assert str(row) == '(1, 3)'
t3 = table.Table(t)
row = t3[0]
assert not isinstance(row, MyRow)
assert str(row) != '(1, 3)'
t = MyTable([[1, 2], [3, 4]], masked=True)
row = t[0]
assert isinstance(row, MyRow)
assert str(row) == '(1, 3)'
assert isinstance(t['col0'], MyMaskedColumn)
assert isinstance(t.formatter, MyTableFormatter)
class ParamsRow(table.Row):
"""
Row class that allows access to an arbitrary dict of parameters
stored as a dict object in the ``params`` column.
"""
def __getitem__(self, item):
if item not in self.colnames:
return super().__getitem__('params')[item]
else:
return super().__getitem__(item)
def keys(self):
out = [name for name in self.colnames if name != 'params']
params = [key.lower() for key in sorted(self['params'])]
return out + params
def values(self):
return [self[key] for key in self.keys()]
class ParamsTable(table.Table):
Row = ParamsRow
def test_params_table():
t = ParamsTable(names=['a', 'b', 'params'], dtype=['i', 'f', 'O'])
t.add_row((1, 2.0, {'x': 1.5, 'y': 2.5}))
t.add_row((2, 3.0, {'z': 'hello', 'id': 123123}))
assert t['params'][0] == {'x': 1.5, 'y': 2.5}
assert t[0]['params'] == {'x': 1.5, 'y': 2.5}
assert t[0]['y'] == 2.5
assert t[1]['id'] == 123123
assert list(t[1].keys()) == ['a', 'b', 'id', 'z']
assert list(t[1].values()) == [2, 3.0, 123123, 'hello']
|
c573ce0b4db783370fcec29f2bcbf5b6190a5496ab2edabe2291dacf7f1e05b6 |
import numpy as np
import pickle
from astropy.table import Table, Column, MaskedColumn, QTable
from astropy.table.table_helpers import simple_table
from astropy.units import Quantity, deg
from astropy.time import Time
from astropy.coordinates import SkyCoord
def test_pickle_column(protocol):
c = Column(data=[1, 2], name='a', format='%05d', description='col a', unit='cm', meta={'a': 1})
cs = pickle.dumps(c)
cp = pickle.loads(cs)
assert np.all(cp == c)
assert cp.attrs_equal(c)
assert cp._parent_table is None
assert repr(c) == repr(cp)
def test_pickle_masked_column(protocol):
c = MaskedColumn(data=[1, 2], name='a', format='%05d', description='col a', unit='cm',
meta={'a': 1})
c.mask[1] = True
c.fill_value = -99
cs = pickle.dumps(c)
cp = pickle.loads(cs)
assert np.all(cp._data == c._data)
assert np.all(cp.mask == c.mask)
assert cp.attrs_equal(c)
assert cp.fill_value == -99
assert cp._parent_table is None
assert repr(c) == repr(cp)
def test_pickle_multidimensional_column(protocol):
"""Regression test for https://github.com/astropy/astropy/issues/4098"""
a = np.zeros((3, 2))
c = Column(a, name='a')
cs = pickle.dumps(c)
cp = pickle.loads(cs)
assert np.all(c == cp)
assert c.shape == cp.shape
assert cp.attrs_equal(c)
assert repr(c) == repr(cp)
def test_pickle_table(protocol):
a = Column(data=[1, 2], name='a', format='%05d', description='col a', unit='cm', meta={'a': 1})
b = Column(data=[3.0, 4.0], name='b', format='%05d', description='col b', unit='cm',
meta={'b': 1})
for table_class in Table, QTable:
t = table_class([a, b], meta={'a': 1, 'b': Quantity(10, unit='s')})
t['c'] = Quantity([1, 2], unit='m')
t['d'] = Time(['2001-01-02T12:34:56', '2001-02-03T00:01:02'])
t['e'] = SkyCoord([125.0, 180.0] * deg, [-45.0, 36.5] * deg)
ts = pickle.dumps(t)
tp = pickle.loads(ts)
assert tp.__class__ is table_class
assert np.all(tp['a'] == t['a'])
assert np.all(tp['b'] == t['b'])
# test mixin columns
assert np.all(tp['c'] == t['c'])
assert np.all(tp['d'] == t['d'])
assert np.all(tp['e'].ra == t['e'].ra)
assert np.all(tp['e'].dec == t['e'].dec)
assert type(tp['c']) is type(t['c']) # nopep8
assert type(tp['d']) is type(t['d']) # nopep8
assert type(tp['e']) is type(t['e']) # nopep8
assert tp.meta == t.meta
assert type(tp) is type(t)
assert isinstance(tp['c'], Quantity if (table_class is QTable) else Column)
def test_pickle_masked_table(protocol):
a = Column(data=[1, 2], name='a', format='%05d', description='col a', unit='cm', meta={'a': 1})
b = Column(data=[3.0, 4.0], name='b', format='%05d', description='col b', unit='cm',
meta={'b': 1})
t = Table([a, b], meta={'a': 1}, masked=True)
t['a'].mask[1] = True
t['a'].fill_value = -99
ts = pickle.dumps(t)
tp = pickle.loads(ts)
for colname in ('a', 'b'):
for attr in ('_data', 'mask', 'fill_value'):
assert np.all(getattr(tp[colname], attr) == getattr(tp[colname], attr))
assert tp['a'].attrs_equal(t['a'])
assert tp['b'].attrs_equal(t['b'])
assert tp.meta == t.meta
def test_pickle_indexed_table(protocol):
"""
Ensure that any indices that have been added will survive pickling.
"""
t = simple_table()
t.add_index('a')
t.add_index(['a', 'b'])
ts = pickle.dumps(t)
tp = pickle.loads(ts)
assert len(t.indices) == len(tp.indices)
for index, indexp in zip(t.indices, tp.indices):
assert np.all(index.data.data == indexp.data.data)
assert index.data.data.colnames == indexp.data.data.colnames
|
9453be608bcd0db8b03419ed0e7119dfcfe6a4709826aa819ed46b7515494438 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
All of the pytest fixtures used by astropy.table are defined here.
`conftest.py` is a "special" module name for pytest that is always
imported, but is not looked in for tests, and it is the recommended
place to put fixtures that are shared between modules. These fixtures
can not be defined in a module by a different name and still be shared
between modules.
"""
from copy import deepcopy
from collections import OrderedDict
import pickle
import pytest
import numpy as np
from astropy import table
from astropy.table import Table, QTable
from astropy.table.table_helpers import ArrayWrapper
from astropy import time
from astropy import units as u
from astropy import coordinates
from astropy.table import pprint
@pytest.fixture(params=[table.Column, table.MaskedColumn])
def Column(request):
# Fixture to run all the Column tests for both an unmasked (ndarray)
# and masked (MaskedArray) column.
return request.param
class MaskedTable(table.Table):
def __init__(self, *args, **kwargs):
kwargs['masked'] = True
table.Table.__init__(self, *args, **kwargs)
class MyRow(table.Row):
pass
class MyColumn(table.Column):
pass
class MyMaskedColumn(table.MaskedColumn):
pass
class MyTableColumns(table.TableColumns):
pass
class MyTableFormatter(pprint.TableFormatter):
pass
class MyTable(table.Table):
Row = MyRow
Column = MyColumn
MaskedColumn = MyMaskedColumn
TableColumns = MyTableColumns
TableFormatter = MyTableFormatter
# Fixture to run all the Column tests for both an unmasked (ndarray)
# and masked (MaskedArray) column.
@pytest.fixture(params=['unmasked', 'masked', 'subclass'])
def table_types(request):
class TableTypes:
def __init__(self, request):
if request.param == 'unmasked':
self.Table = table.Table
self.Column = table.Column
elif request.param == 'masked':
self.Table = MaskedTable
self.Column = table.MaskedColumn
elif request.param == 'subclass':
self.Table = MyTable
self.Column = MyColumn
return TableTypes(request)
# Fixture to run all the Column tests for both an unmasked (ndarray)
# and masked (MaskedArray) column.
@pytest.fixture(params=[False, True])
def table_data(request):
class TableData:
def __init__(self, request):
self.Table = MaskedTable if request.param else table.Table
self.Column = table.MaskedColumn if request.param else table.Column
self.COLS = [
self.Column(name='a', data=[1, 2, 3], description='da',
format='%i', meta={'ma': 1}, unit='ua'),
self.Column(name='b', data=[4, 5, 6], description='db',
format='%d', meta={'mb': 1}, unit='ub'),
self.Column(name='c', data=[7, 8, 9], description='dc',
format='%f', meta={'mc': 1}, unit='ub')]
self.DATA = self.Table(self.COLS)
return TableData(request)
class SubclassTable(table.Table):
pass
@pytest.fixture(params=[True, False])
def tableclass(request):
return table.Table if request.param else SubclassTable
@pytest.fixture(params=list(range(0, pickle.HIGHEST_PROTOCOL + 1)))
def protocol(request):
"""
Fixture to run all the tests for all available pickle protocols.
"""
return request.param
# Fixture to run all tests for both an unmasked (ndarray) and masked
# (MaskedArray) column.
@pytest.fixture(params=[False, True])
def table_type(request):
return MaskedTable if request.param else table.Table
# Stuff for testing mixin columns
MIXIN_COLS = {'quantity': [0, 1, 2, 3] * u.m,
'longitude': coordinates.Longitude([0., 1., 5., 6.] * u.deg,
wrap_angle=180. * u.deg),
'latitude': coordinates.Latitude([5., 6., 10., 11.] * u.deg),
'time': time.Time([2000, 2001, 2002, 2003], format='jyear'),
'timedelta': time.TimeDelta([1, 2, 3, 4], format='jd'),
'skycoord': coordinates.SkyCoord(ra=[0, 1, 2, 3] * u.deg,
dec=[0, 1, 2, 3] * u.deg),
'sphericalrep': coordinates.SphericalRepresentation(
[0, 1, 2, 3]*u.deg, [0, 1, 2, 3]*u.deg, 1*u.kpc),
'cartesianrep': coordinates.CartesianRepresentation(
[0, 1, 2, 3]*u.pc, [4, 5, 6, 7]*u.pc, [9, 8, 8, 6]*u.pc),
'sphericaldiff': coordinates.SphericalCosLatDifferential(
[0, 1, 2, 3]*u.mas/u.yr, [0, 1, 2, 3]*u.mas/u.yr,
10*u.km/u.s),
'arraywrap': ArrayWrapper([0, 1, 2, 3]),
'arrayswap': ArrayWrapper(np.arange(4, dtype='i').byteswap().newbyteorder()),
'ndarraylil': np.array([(7, 'a'), (8, 'b'), (9, 'c'), (9, 'c')],
dtype='<i4,|S1').view(table.NdarrayMixin),
'ndarraybig': np.array([(7, 'a'), (8, 'b'), (9, 'c'), (9, 'c')],
dtype='>i4,|S1').view(table.NdarrayMixin),
}
MIXIN_COLS['earthlocation'] = coordinates.EarthLocation(
lon=MIXIN_COLS['longitude'], lat=MIXIN_COLS['latitude'],
height=MIXIN_COLS['quantity'])
MIXIN_COLS['sphericalrepdiff'] = coordinates.SphericalRepresentation(
MIXIN_COLS['sphericalrep'], differentials=MIXIN_COLS['sphericaldiff'])
@pytest.fixture(params=sorted(MIXIN_COLS))
def mixin_cols(request):
"""
Fixture to return a set of columns for mixin testing which includes
an index column 'i', two string cols 'a', 'b' (for joins etc), and
one of the available mixin column types.
"""
cols = OrderedDict()
mixin_cols = deepcopy(MIXIN_COLS)
cols['i'] = table.Column([0, 1, 2, 3], name='i')
cols['a'] = table.Column(['a', 'b', 'b', 'c'], name='a')
cols['b'] = table.Column(['b', 'c', 'a', 'd'], name='b')
cols['m'] = mixin_cols[request.param]
return cols
@pytest.fixture(params=[False, True])
def T1(request):
T = Table.read([' a b c d',
' 2 c 7.0 0',
' 2 b 5.0 1',
' 2 b 6.0 2',
' 2 a 4.0 3',
' 0 a 0.0 4',
' 1 b 3.0 5',
' 1 a 2.0 6',
' 1 a 1.0 7',
], format='ascii')
T.meta.update({'ta': 1})
T['c'].meta.update({'a': 1})
T['c'].description = 'column c'
if request.param:
T.add_index('a')
return T
@pytest.fixture(params=[Table, QTable])
def operation_table_type(request):
return request.param
|
1515117c5f72525c2d39136332b308f73f01e828f9cfb0d13bc3dddc93af518a | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy.table.table_helpers import ArrayWrapper
from astropy.coordinates.earth import EarthLocation
from astropy.units.quantity import Quantity
from collections import OrderedDict
from contextlib import nullcontext
import pytest
import numpy as np
from astropy.table import Table, QTable, TableMergeError, Column, MaskedColumn, NdarrayMixin
from astropy.table.operations import _get_out_class, join_skycoord, join_distance
from astropy import units as u
from astropy.utils import metadata
from astropy.utils.metadata import MergeConflictError
from astropy import table
from astropy.time import Time, TimeDelta
from astropy.coordinates import (SkyCoord, SphericalRepresentation,
UnitSphericalRepresentation,
CartesianRepresentation,
BaseRepresentationOrDifferential,
search_around_3d)
from astropy.coordinates.tests.test_representation import representation_equal
from astropy.io.misc.asdf.tags.helpers import skycoord_equal
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
def sort_eq(list1, list2):
return sorted(list1) == sorted(list2)
def check_mask(col, exp_mask):
"""Check that col.mask == exp_mask"""
if hasattr(col, 'mask'):
# Coerce expected mask into dtype of col.mask. In particular this is
# needed for types like EarthLocation where the mask is a structured
# array.
exp_mask = np.array(exp_mask).astype(col.mask.dtype)
out = np.all(col.mask == exp_mask)
else:
# With no mask the check is OK if all the expected mask values
# are False (i.e. no auto-conversion to MaskedQuantity if it was
# not required by the join).
out = np.all(exp_mask == False)
return out
class TestJoin():
def _setup(self, t_cls=Table):
lines1 = [' a b c ',
' 0 foo L1',
' 1 foo L2',
' 1 bar L3',
' 2 bar L4']
lines2 = [' a b d ',
' 1 foo R1',
' 1 foo R2',
' 2 bar R3',
' 4 bar R4']
self.t1 = t_cls.read(lines1, format='ascii')
self.t2 = t_cls.read(lines2, format='ascii')
self.t3 = t_cls(self.t2, copy=True)
self.t1.meta.update(OrderedDict([('b', [1, 2]), ('c', {'a': 1}), ('d', 1)]))
self.t2.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
self.t3.meta.update(OrderedDict([('b', 3), ('c', [1, 2]), ('d', 2), ('a', 1)]))
self.meta_merge = OrderedDict([('b', [1, 2, 3, 4]),
('c', {'a': 1, 'b': 1}),
('d', 1),
('a', 1)])
def test_table_meta_merge(self, operation_table_type):
self._setup(operation_table_type)
out = table.join(self.t1, self.t2, join_type='inner')
assert out.meta == self.meta_merge
def test_table_meta_merge_conflict(self, operation_table_type):
self._setup(operation_table_type)
with pytest.warns(metadata.MergeConflictWarning) as w:
out = table.join(self.t1, self.t3, join_type='inner')
assert len(w) == 3
assert out.meta == self.t3.meta
with pytest.warns(metadata.MergeConflictWarning) as w:
out = table.join(self.t1, self.t3, join_type='inner', metadata_conflicts='warn')
assert len(w) == 3
assert out.meta == self.t3.meta
out = table.join(self.t1, self.t3, join_type='inner', metadata_conflicts='silent')
assert out.meta == self.t3.meta
with pytest.raises(MergeConflictError):
out = table.join(self.t1, self.t3, join_type='inner', metadata_conflicts='error')
with pytest.raises(ValueError):
out = table.join(self.t1, self.t3, join_type='inner', metadata_conflicts='nonsense')
def test_both_unmasked_inner(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
# Basic join with default parameters (inner join on common keys)
t12 = table.join(t1, t2)
assert type(t12) is operation_table_type
assert type(t12['a']) is type(t1['a']) # noqa
assert type(t12['b']) is type(t1['b']) # noqa
assert type(t12['c']) is type(t1['c']) # noqa
assert type(t12['d']) is type(t2['d']) # noqa
assert t12.masked is False
assert sort_eq(t12.pformat(), [' a b c d ',
'--- --- --- ---',
' 1 foo L2 R1',
' 1 foo L2 R2',
' 2 bar L4 R3'])
# Table meta merged properly
assert t12.meta == self.meta_merge
def test_both_unmasked_left_right_outer(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
# Left join
t12 = table.join(t1, t2, join_type='left')
assert t12.has_masked_columns is True
assert t12.masked is False
for name in ('a', 'b', 'c'):
assert type(t12[name]) is Column
assert type(t12['d']) is MaskedColumn
assert sort_eq(t12.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 foo L1 --',
' 1 bar L3 --',
' 1 foo L2 R1',
' 1 foo L2 R2',
' 2 bar L4 R3'])
# Right join
t12 = table.join(t1, t2, join_type='right')
assert t12.has_masked_columns is True
assert t12.masked is False
assert sort_eq(t12.pformat(), [' a b c d ',
'--- --- --- ---',
' 1 foo L2 R1',
' 1 foo L2 R2',
' 2 bar L4 R3',
' 4 bar -- R4'])
# Outer join
t12 = table.join(t1, t2, join_type='outer')
assert t12.has_masked_columns is True
assert t12.masked is False
assert sort_eq(t12.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 foo L1 --',
' 1 bar L3 --',
' 1 foo L2 R1',
' 1 foo L2 R2',
' 2 bar L4 R3',
' 4 bar -- R4'])
# Check that the common keys are 'a', 'b'
t12a = table.join(t1, t2, join_type='outer')
t12b = table.join(t1, t2, join_type='outer', keys=['a', 'b'])
assert np.all(t12a.as_array() == t12b.as_array())
def test_both_unmasked_single_key_inner(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
# Inner join on 'a' column
t12 = table.join(t1, t2, keys='a')
assert type(t12) is operation_table_type
assert type(t12['a']) is type(t1['a']) # noqa
assert type(t12['b_1']) is type(t1['b']) # noqa
assert type(t12['c']) is type(t1['c']) # noqa
assert type(t12['b_2']) is type(t2['b']) # noqa
assert type(t12['d']) is type(t2['d']) # noqa
assert t12.masked is False
assert sort_eq(t12.pformat(), [' a b_1 c b_2 d ',
'--- --- --- --- ---',
' 1 foo L2 foo R1',
' 1 foo L2 foo R2',
' 1 bar L3 foo R1',
' 1 bar L3 foo R2',
' 2 bar L4 bar R3'])
def test_both_unmasked_single_key_left_right_outer(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
# Left join
t12 = table.join(t1, t2, join_type='left', keys='a')
assert t12.has_masked_columns is True
assert sort_eq(t12.pformat(), [' a b_1 c b_2 d ',
'--- --- --- --- ---',
' 0 foo L1 -- --',
' 1 foo L2 foo R1',
' 1 foo L2 foo R2',
' 1 bar L3 foo R1',
' 1 bar L3 foo R2',
' 2 bar L4 bar R3'])
# Right join
t12 = table.join(t1, t2, join_type='right', keys='a')
assert t12.has_masked_columns is True
assert sort_eq(t12.pformat(), [' a b_1 c b_2 d ',
'--- --- --- --- ---',
' 1 foo L2 foo R1',
' 1 foo L2 foo R2',
' 1 bar L3 foo R1',
' 1 bar L3 foo R2',
' 2 bar L4 bar R3',
' 4 -- -- bar R4'])
# Outer join
t12 = table.join(t1, t2, join_type='outer', keys='a')
assert t12.has_masked_columns is True
assert sort_eq(t12.pformat(), [' a b_1 c b_2 d ',
'--- --- --- --- ---',
' 0 foo L1 -- --',
' 1 foo L2 foo R1',
' 1 foo L2 foo R2',
' 1 bar L3 foo R1',
' 1 bar L3 foo R2',
' 2 bar L4 bar R3',
' 4 -- -- bar R4'])
def test_masked_unmasked(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
self._setup(operation_table_type)
t1 = self.t1
t1m = operation_table_type(self.t1, masked=True)
t2 = self.t2
# Result table is never masked
t1m2 = table.join(t1m, t2, join_type='inner')
assert t1m2.masked is False
# Result should match non-masked result
t12 = table.join(t1, t2)
assert np.all(t12.as_array() == np.array(t1m2))
# Mask out some values in left table and make sure they propagate
t1m['b'].mask[1] = True
t1m['c'].mask[2] = True
t1m2 = table.join(t1m, t2, join_type='inner', keys='a')
assert sort_eq(t1m2.pformat(), [' a b_1 c b_2 d ',
'--- --- --- --- ---',
' 1 -- L2 foo R1',
' 1 -- L2 foo R2',
' 1 bar -- foo R1',
' 1 bar -- foo R2',
' 2 bar L4 bar R3'])
t21m = table.join(t2, t1m, join_type='inner', keys='a')
assert sort_eq(t21m.pformat(), [' a b_1 d b_2 c ',
'--- --- --- --- ---',
' 1 foo R2 -- L2',
' 1 foo R2 bar --',
' 1 foo R1 -- L2',
' 1 foo R1 bar --',
' 2 bar R3 bar L4'])
def test_masked_masked(self, operation_table_type):
self._setup(operation_table_type)
"""Two masked tables"""
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
t1 = self.t1
t1m = operation_table_type(self.t1, masked=True)
t2 = self.t2
t2m = operation_table_type(self.t2, masked=True)
# Result table is never masked but original column types are preserved
t1m2m = table.join(t1m, t2m, join_type='inner')
assert t1m2m.masked is False
for col in t1m2m.itercols():
assert type(col) is MaskedColumn
# Result should match non-masked result
t12 = table.join(t1, t2)
assert np.all(t12.as_array() == np.array(t1m2m))
# Mask out some values in both tables and make sure they propagate
t1m['b'].mask[1] = True
t1m['c'].mask[2] = True
t2m['d'].mask[2] = True
t1m2m = table.join(t1m, t2m, join_type='inner', keys='a')
assert sort_eq(t1m2m.pformat(), [' a b_1 c b_2 d ',
'--- --- --- --- ---',
' 1 -- L2 foo R1',
' 1 -- L2 foo R2',
' 1 bar -- foo R1',
' 1 bar -- foo R2',
' 2 bar L4 bar --'])
def test_classes(self):
"""Ensure that classes and subclasses get through as expected"""
class MyCol(Column):
pass
class MyMaskedCol(MaskedColumn):
pass
t1 = Table()
t1['a'] = MyCol([1])
t1['b'] = MyCol([2])
t1['c'] = MyMaskedCol([3])
t2 = Table()
t2['a'] = Column([1, 2])
t2['d'] = MyCol([3, 4])
t2['e'] = MyMaskedCol([5, 6])
t12 = table.join(t1, t2, join_type='inner')
for name, exp_type in (('a', MyCol), ('b', MyCol), ('c', MyMaskedCol),
('d', MyCol), ('e', MyMaskedCol)):
assert type(t12[name] is exp_type)
t21 = table.join(t2, t1, join_type='left')
# Note col 'b' gets upgraded from MyCol to MaskedColumn since it needs to be
# masked, but col 'c' stays since MyMaskedCol supports masking.
for name, exp_type in (('a', MyCol), ('b', MaskedColumn), ('c', MyMaskedCol),
('d', MyCol), ('e', MyMaskedCol)):
assert type(t21[name] is exp_type)
def test_col_rename(self, operation_table_type):
self._setup(operation_table_type)
"""
Test auto col renaming when there is a conflict. Use
non-default values of uniq_col_name and table_names.
"""
t1 = self.t1
t2 = self.t2
t12 = table.join(t1, t2, uniq_col_name='x_{table_name}_{col_name}_y',
table_names=['L', 'R'], keys='a')
assert t12.colnames == ['a', 'x_L_b_y', 'c', 'x_R_b_y', 'd']
def test_rename_conflict(self, operation_table_type):
self._setup(operation_table_type)
"""
Test that auto-column rename fails because of a conflict
with an existing column
"""
t1 = self.t1
t2 = self.t2
t1['b_1'] = 1 # Add a new column b_1 that will conflict with auto-rename
with pytest.raises(TableMergeError):
table.join(t1, t2, keys='a')
def test_missing_keys(self, operation_table_type):
self._setup(operation_table_type)
"""Merge on a key column that doesn't exist"""
t1 = self.t1
t2 = self.t2
with pytest.raises(TableMergeError):
table.join(t1, t2, keys=['a', 'not there'])
def test_bad_join_type(self, operation_table_type):
self._setup(operation_table_type)
"""Bad join_type input"""
t1 = self.t1
t2 = self.t2
with pytest.raises(ValueError):
table.join(t1, t2, join_type='illegal value')
def test_no_common_keys(self, operation_table_type):
self._setup(operation_table_type)
"""Merge tables with no common keys"""
t1 = self.t1
t2 = self.t2
del t1['a']
del t1['b']
del t2['a']
del t2['b']
with pytest.raises(TableMergeError):
table.join(t1, t2)
def test_masked_key_column(self, operation_table_type):
self._setup(operation_table_type)
"""Merge on a key column that has a masked element"""
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
t1 = self.t1
t2 = operation_table_type(self.t2, masked=True)
table.join(t1, t2) # OK
t2['a'].mask[0] = True
with pytest.raises(TableMergeError):
table.join(t1, t2)
def test_col_meta_merge(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t2.rename_column('d', 'c') # force col conflict and renaming
meta1 = OrderedDict([('b', [1, 2]), ('c', {'a': 1}), ('d', 1)])
meta2 = OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)])
# Key col 'a', should first value ('cm')
t1['a'].unit = 'cm'
t2['a'].unit = 'm'
# Key col 'b', take first value 't1_b'
t1['b'].info.description = 't1_b'
# Key col 'b', take first non-empty value 't1_b'
t2['b'].info.format = '%6s'
# Key col 'a', should be merged meta
t1['a'].info.meta = meta1
t2['a'].info.meta = meta2
# Key col 'b', should be meta2
t2['b'].info.meta = meta2
# All these should pass through
t1['c'].info.format = '%3s'
t1['c'].info.description = 't1_c'
t2['c'].info.format = '%6s'
t2['c'].info.description = 't2_c'
if operation_table_type is Table:
ctx = pytest.warns(metadata.MergeConflictWarning, match=r"In merged column 'a' the 'unit' attribute does not match \(cm != m\)") # noqa
else:
ctx = nullcontext()
with ctx:
t12 = table.join(t1, t2, keys=['a', 'b'])
assert t12['a'].unit == 'm'
assert t12['b'].info.description == 't1_b'
assert t12['b'].info.format == '%6s'
assert t12['a'].info.meta == self.meta_merge
assert t12['b'].info.meta == meta2
assert t12['c_1'].info.format == '%3s'
assert t12['c_1'].info.description == 't1_c'
assert t12['c_2'].info.format == '%6s'
assert t12['c_2'].info.description == 't2_c'
def test_join_multidimensional(self, operation_table_type):
self._setup(operation_table_type)
# Regression test for #2984, which was an issue where join did not work
# on multi-dimensional columns.
t1 = operation_table_type()
t1['a'] = [1, 2, 3]
t1['b'] = np.ones((3, 4))
t2 = operation_table_type()
t2['a'] = [1, 2, 3]
t2['c'] = [4, 5, 6]
t3 = table.join(t1, t2)
np.testing.assert_allclose(t3['a'], t1['a'])
np.testing.assert_allclose(t3['b'], t1['b'])
np.testing.assert_allclose(t3['c'], t2['c'])
def test_join_multidimensional_masked(self, operation_table_type):
self._setup(operation_table_type)
"""
Test for outer join with multidimensional columns where masking is required.
(Issue #4059).
"""
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
a = table.MaskedColumn([1, 2, 3], name='a')
a2 = table.Column([1, 3, 4], name='a')
b = table.MaskedColumn([[1, 2],
[3, 4],
[5, 6]],
name='b',
mask=[[1, 0],
[0, 1],
[0, 0]])
c = table.Column([[1, 1],
[2, 2],
[3, 3]],
name='c')
t1 = operation_table_type([a, b])
t2 = operation_table_type([a2, c])
t12 = table.join(t1, t2, join_type='inner')
assert np.all(t12['b'].mask == [[True, False],
[False, False]])
assert not hasattr(t12['c'], 'mask')
t12 = table.join(t1, t2, join_type='outer')
assert np.all(t12['b'].mask == [[True, False],
[False, True],
[False, False],
[True, True]])
assert np.all(t12['c'].mask == [[False, False],
[True, True],
[False, False],
[False, False]])
def test_mixin_functionality(self, mixin_cols):
col = mixin_cols['m']
cls_name = type(col).__name__
len_col = len(col)
idx = np.arange(len_col)
t1 = table.QTable([idx, col], names=['idx', 'm1'])
t2 = table.QTable([idx, col], names=['idx', 'm2'])
# Set up join mismatches for different join_type cases
t1 = t1[[0, 1, 3]]
t2 = t2[[0, 2, 3]]
# Test inner join, which works for all mixin_cols
out = table.join(t1, t2, join_type='inner')
assert len(out) == 2
assert out['m2'].__class__ is col.__class__
assert np.all(out['idx'] == [0, 3])
if cls_name == 'SkyCoord':
# SkyCoord doesn't support __eq__ so use our own
assert skycoord_equal(out['m1'], col[[0, 3]])
assert skycoord_equal(out['m2'], col[[0, 3]])
elif 'Repr' in cls_name or 'Diff' in cls_name:
assert np.all(representation_equal(out['m1'], col[[0, 3]]))
assert np.all(representation_equal(out['m2'], col[[0, 3]]))
else:
assert np.all(out['m1'] == col[[0, 3]])
assert np.all(out['m2'] == col[[0, 3]])
# Check for left, right, outer join which requires masking. Works for
# the listed mixins classes.
if isinstance(col, (Quantity, Time, TimeDelta)):
out = table.join(t1, t2, join_type='left')
assert len(out) == 3
assert np.all(out['idx'] == [0, 1, 3])
assert np.all(out['m1'] == t1['m1'])
assert np.all(out['m2'] == t2['m2'])
check_mask(out['m1'], [False, False, False])
check_mask(out['m2'], [False, True, False])
out = table.join(t1, t2, join_type='right')
assert len(out) == 3
assert np.all(out['idx'] == [0, 2, 3])
assert np.all(out['m1'] == t1['m1'])
assert np.all(out['m2'] == t2['m2'])
check_mask(out['m1'], [False, True, False])
check_mask(out['m2'], [False, False, False])
out = table.join(t1, t2, join_type='outer')
assert len(out) == 4
assert np.all(out['idx'] == [0, 1, 2, 3])
assert np.all(out['m1'] == col)
assert np.all(out['m2'] == col)
assert check_mask(out['m1'], [False, False, True, False])
assert check_mask(out['m2'], [False, True, False, False])
else:
# Otherwise make sure it fails with the right exception message
for join_type in ('outer', 'left', 'right'):
with pytest.raises(NotImplementedError) as err:
table.join(t1, t2, join_type=join_type)
assert ('join requires masking' in str(err.value)
or 'join unavailable' in str(err.value))
def test_cartesian_join(self, operation_table_type):
t1 = Table(rows=[(1, 'a'),
(2, 'b')], names=['a', 'b'])
t2 = Table(rows=[(3, 'c'),
(4, 'd')], names=['a', 'c'])
t12 = table.join(t1, t2, join_type='cartesian')
assert t1.colnames == ['a', 'b']
assert t2.colnames == ['a', 'c']
assert len(t12) == len(t1) * len(t2)
assert str(t12).splitlines() == [
'a_1 b a_2 c ',
'--- --- --- ---',
' 1 a 3 c',
' 1 a 4 d',
' 2 b 3 c',
' 2 b 4 d']
with pytest.raises(ValueError, match='cannot supply keys for a cartesian join'):
t12 = table.join(t1, t2, join_type='cartesian', keys='a')
@pytest.mark.skipif('not HAS_SCIPY')
def test_join_with_join_skycoord_sky(self):
sc1 = SkyCoord([0, 1, 1.1, 2], [0, 0, 0, 0], unit='deg')
sc2 = SkyCoord([0.5, 1.05, 2.1], [0, 0, 0], unit='deg')
t1 = Table([sc1], names=['sc'])
t2 = Table([sc2], names=['sc'])
t12 = table.join(t1, t2, join_funcs={'sc': join_skycoord(0.2 * u.deg)})
exp = ['sc_id sc_1 sc_2 ',
' deg,deg deg,deg ',
'----- ------- --------',
' 1 1.0,0.0 1.05,0.0',
' 1 1.1,0.0 1.05,0.0',
' 2 2.0,0.0 2.1,0.0']
assert str(t12).splitlines() == exp
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('distance_func', ['search_around_3d', search_around_3d])
def test_join_with_join_skycoord_3d(self, distance_func):
sc1 = SkyCoord([0, 1, 1.1, 2]*u.deg, [0, 0, 0, 0]*u.deg, [1, 1, 2, 1]*u.m)
sc2 = SkyCoord([0.5, 1.05, 2.1]*u.deg, [0, 0, 0]*u.deg, [1, 1, 1]*u.m)
t1 = Table([sc1], names=['sc'])
t2 = Table([sc2], names=['sc'])
join_func = join_skycoord(np.deg2rad(0.2) * u.m,
distance_func=distance_func)
t12 = table.join(t1, t2, join_funcs={'sc': join_func})
exp = ['sc_id sc_1 sc_2 ',
' deg,deg,m deg,deg,m ',
'----- ----------- ------------',
' 1 1.0,0.0,1.0 1.05,0.0,1.0',
' 2 2.0,0.0,1.0 2.1,0.0,1.0']
assert str(t12).splitlines() == exp
@pytest.mark.skipif('not HAS_SCIPY')
def test_join_with_join_distance_1d(self):
c1 = [0, 1, 1.1, 2]
c2 = [0.5, 1.05, 2.1]
t1 = Table([c1], names=['col'])
t2 = Table([c2], names=['col'])
join_func = join_distance(0.2,
kdtree_args={'leafsize': 32},
query_args={'p': 2})
t12 = table.join(t1, t2, join_type='outer', join_funcs={'col': join_func})
exp = ['col_id col_1 col_2',
'------ ----- -----',
' 1 1.0 1.05',
' 1 1.1 1.05',
' 2 2.0 2.1',
' 3 0.0 --',
' 4 -- 0.5']
assert str(t12).splitlines() == exp
@pytest.mark.skipif('not HAS_SCIPY')
def test_join_with_join_distance_1d_multikey(self):
from astropy.table.operations import _apply_join_funcs
c1 = [0, 1, 1.1, 1.2, 2]
id1 = [0, 1, 2, 2, 3]
o1 = ['a', 'b', 'c', 'd', 'e']
c2 = [0.5, 1.05, 2.1]
id2 = [0, 2, 4]
o2 = ['z', 'y', 'x']
t1 = Table([c1, id1, o1], names=['col', 'id', 'o1'])
t2 = Table([c2, id2, o2], names=['col', 'id', 'o2'])
join_func = join_distance(0.2)
join_funcs = {'col': join_func}
t12 = table.join(t1, t2, join_type='outer', join_funcs=join_funcs)
exp = ['col_id col_1 id o1 col_2 o2',
'------ ----- --- --- ----- ---',
' 1 1.0 1 b -- --',
' 1 1.1 2 c 1.05 y',
' 1 1.2 2 d 1.05 y',
' 2 2.0 3 e -- --',
' 2 -- 4 -- 2.1 x',
' 3 0.0 0 a -- --',
' 4 -- 0 -- 0.5 z']
assert str(t12).splitlines() == exp
left, right, keys = _apply_join_funcs(t1, t2, ('col', 'id'), join_funcs)
assert keys == ('col_id', 'id')
@pytest.mark.skipif('not HAS_SCIPY')
def test_join_with_join_distance_1d_quantity(self):
c1 = [0, 1, 1.1, 2] * u.m
c2 = [500, 1050, 2100] * u.mm
t1 = QTable([c1], names=['col'])
t2 = QTable([c2], names=['col'])
join_func = join_distance(20 * u.cm)
t12 = table.join(t1, t2, join_funcs={'col': join_func})
exp = ['col_id col_1 col_2 ',
' m mm ',
'------ ----- ------',
' 1 1.0 1050.0',
' 1 1.1 1050.0',
' 2 2.0 2100.0']
assert str(t12).splitlines() == exp
# Generate column name conflict
t2['col_id'] = [0, 0, 0]
t2['col__id'] = [0, 0, 0]
t12 = table.join(t1, t2, join_funcs={'col': join_func})
exp = ['col___id col_1 col_2 col_id col__id',
' m mm ',
'-------- ----- ------ ------ -------',
' 1 1.0 1050.0 0 0',
' 1 1.1 1050.0 0 0',
' 2 2.0 2100.0 0 0']
assert str(t12).splitlines() == exp
@pytest.mark.skipif('not HAS_SCIPY')
def test_join_with_join_distance_2d(self):
c1 = np.array([[0, 1, 1.1, 2],
[0, 0, 1, 0]]).transpose()
c2 = np.array([[0.5, 1.05, 2.1],
[0, 0, 0]]).transpose()
t1 = Table([c1], names=['col'])
t2 = Table([c2], names=['col'])
join_func = join_distance(0.2,
kdtree_args={'leafsize': 32},
query_args={'p': 2})
t12 = table.join(t1, t2, join_type='outer', join_funcs={'col': join_func})
exp = ['col_id col_1 [2] col_2 [2] ',
'------ ---------- -----------',
' 1 1.0 .. 0.0 1.05 .. 0.0',
' 2 2.0 .. 0.0 2.1 .. 0.0',
' 3 0.0 .. 0.0 -- .. --',
' 4 1.1 .. 1.0 -- .. --',
' 5 -- .. -- 0.5 .. 0.0']
assert str(t12).splitlines() == exp
def test_keys_left_right_basic(self):
"""Test using the keys_left and keys_right args to specify different
join keys. This takes the standard test case but renames column 'a'
to 'x' and 'y' respectively for tables 1 and 2. Then it compares the
normal join on 'a' to the new join on 'x' and 'y'."""
self._setup()
for join_type in ('inner', 'left', 'right', 'outer'):
t1 = self.t1.copy()
t2 = self.t2.copy()
# Expected is same as joining on 'a' but with names 'x', 'y' instead
t12_exp = table.join(t1, t2, keys='a', join_type=join_type)
t12_exp.add_column(t12_exp['a'], name='x', index=1)
t12_exp.add_column(t12_exp['a'], name='y', index=len(t1.colnames) + 1)
del t12_exp['a']
# Different key names
t1.rename_column('a', 'x')
t2.rename_column('a', 'y')
keys_left_list = ['x'] # Test string key name
keys_right_list = [['y']] # Test list of string key names
if join_type == 'outer':
# Just do this for the outer join (others are the same)
keys_left_list.append([t1['x'].tolist()]) # Test list key column
keys_right_list.append([t2['y']]) # Test Column key column
for keys_left, keys_right in zip(keys_left_list, keys_right_list):
t12 = table.join(t1, t2, keys_left=keys_left, keys_right=keys_right,
join_type=join_type)
assert t12.colnames == t12_exp.colnames
for col in t12.values_equal(t12_exp).itercols():
assert np.all(col)
assert t12_exp.meta == t12.meta
def test_keys_left_right_exceptions(self):
"""Test exceptions using the keys_left and keys_right args to specify
different join keys.
"""
self._setup()
t1 = self.t1
t2 = self.t2
msg = r"left table does not have key column 'z'"
with pytest.raises(ValueError, match=msg):
table.join(t1, t2, keys_left='z', keys_right=['a'])
msg = r"left table has different length from key \[1, 2\]"
with pytest.raises(ValueError, match=msg):
table.join(t1, t2, keys_left=[[1, 2]], keys_right=['a'])
msg = r"keys arg must be None if keys_left and keys_right are supplied"
with pytest.raises(ValueError, match=msg):
table.join(t1, t2, keys_left='z', keys_right=['a'], keys='a')
msg = r"keys_left and keys_right args must have same length"
with pytest.raises(ValueError, match=msg):
table.join(t1, t2, keys_left=['a', 'b'], keys_right=['a'])
msg = r"keys_left and keys_right must both be provided"
with pytest.raises(ValueError, match=msg):
table.join(t1, t2, keys_left=['a', 'b'])
msg = r"cannot supply join_funcs arg and keys_left / keys_right"
with pytest.raises(ValueError, match=msg):
table.join(t1, t2, keys_left=['a'], keys_right=['a'], join_funcs={})
class TestSetdiff():
def _setup(self, t_cls=Table):
lines1 = [' a b ',
' 0 foo ',
' 1 foo ',
' 1 bar ',
' 2 bar ']
lines2 = [' a b ',
' 0 foo ',
' 3 foo ',
' 4 bar ',
' 2 bar ']
lines3 = [' a b d ',
' 0 foo R1',
' 8 foo R2',
' 1 bar R3',
' 4 bar R4']
self.t1 = t_cls.read(lines1, format='ascii')
self.t2 = t_cls.read(lines2, format='ascii')
self.t3 = t_cls.read(lines3, format='ascii')
def test_default_same_columns(self, operation_table_type):
self._setup(operation_table_type)
out = table.setdiff(self.t1, self.t2)
assert type(out['a']) is type(self.t1['a']) # noqa
assert type(out['b']) is type(self.t1['b']) # noqa
assert out.pformat() == [' a b ',
'--- ---',
' 1 bar',
' 1 foo']
def test_default_same_tables(self, operation_table_type):
self._setup(operation_table_type)
out = table.setdiff(self.t1, self.t1)
assert type(out['a']) is type(self.t1['a']) # noqa
assert type(out['b']) is type(self.t1['b']) # noqa
assert out.pformat() == [' a b ',
'--- ---']
def test_extra_col_left_table(self, operation_table_type):
self._setup(operation_table_type)
with pytest.raises(ValueError):
table.setdiff(self.t3, self.t1)
def test_extra_col_right_table(self, operation_table_type):
self._setup(operation_table_type)
out = table.setdiff(self.t1, self.t3)
assert type(out['a']) is type(self.t1['a']) # noqa
assert type(out['b']) is type(self.t1['b']) # noqa
assert out.pformat() == [' a b ',
'--- ---',
' 1 foo',
' 2 bar']
def test_keys(self, operation_table_type):
self._setup(operation_table_type)
out = table.setdiff(self.t3, self.t1, keys=['a', 'b'])
assert type(out['a']) is type(self.t1['a']) # noqa
assert type(out['b']) is type(self.t1['b']) # noqa
assert out.pformat() == [' a b d ',
'--- --- ---',
' 4 bar R4',
' 8 foo R2']
def test_missing_key(self, operation_table_type):
self._setup(operation_table_type)
with pytest.raises(ValueError):
table.setdiff(self.t3, self.t1, keys=['a', 'd'])
class TestVStack():
def _setup(self, t_cls=Table):
self.t1 = t_cls.read([' a b',
' 0. foo',
' 1. bar'], format='ascii')
self.t2 = t_cls.read([' a b c',
' 2. pez 4',
' 3. sez 5'], format='ascii')
self.t3 = t_cls.read([' a b',
' 4. 7',
' 5. 8',
' 6. 9'], format='ascii')
self.t4 = t_cls(self.t1, copy=True, masked=t_cls is Table)
# The following table has meta-data that conflicts with t1
self.t5 = t_cls(self.t1, copy=True)
self.t1.meta.update(OrderedDict([('b', [1, 2]), ('c', {'a': 1}), ('d', 1)]))
self.t2.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
self.t4.meta.update(OrderedDict([('b', [5, 6]), ('c', {'c': 1}), ('e', 1)]))
self.t5.meta.update(OrderedDict([('b', 3), ('c', 'k'), ('d', 1)]))
self.meta_merge = OrderedDict([('b', [1, 2, 3, 4, 5, 6]),
('c', {'a': 1, 'b': 1, 'c': 1}),
('d', 1),
('a', 1),
('e', 1)])
def test_validate_join_type(self):
self._setup()
with pytest.raises(TypeError, match='Did you accidentally call vstack'):
table.vstack(self.t1, self.t2)
def test_stack_rows(self, operation_table_type):
self._setup(operation_table_type)
t2 = self.t1.copy()
t2.meta.clear()
out = table.vstack([self.t1, t2[1]])
assert type(out['a']) is type(self.t1['a']) # noqa
assert type(out['b']) is type(self.t1['b']) # noqa
assert out.pformat() == [' a b ',
'--- ---',
'0.0 foo',
'1.0 bar',
'1.0 bar']
def test_stack_table_column(self, operation_table_type):
self._setup(operation_table_type)
t2 = self.t1.copy()
t2.meta.clear()
out = table.vstack([self.t1, t2['a']])
assert out.masked is False
assert out.pformat() == [' a b ',
'--- ---',
'0.0 foo',
'1.0 bar',
'0.0 --',
'1.0 --']
def test_table_meta_merge(self, operation_table_type):
self._setup(operation_table_type)
out = table.vstack([self.t1, self.t2, self.t4], join_type='inner')
assert out.meta == self.meta_merge
def test_table_meta_merge_conflict(self, operation_table_type):
self._setup(operation_table_type)
with pytest.warns(metadata.MergeConflictWarning) as w:
out = table.vstack([self.t1, self.t5], join_type='inner')
assert len(w) == 2
assert out.meta == self.t5.meta
with pytest.warns(metadata.MergeConflictWarning) as w:
out = table.vstack([self.t1, self.t5], join_type='inner', metadata_conflicts='warn')
assert len(w) == 2
assert out.meta == self.t5.meta
out = table.vstack([self.t1, self.t5], join_type='inner', metadata_conflicts='silent')
assert out.meta == self.t5.meta
with pytest.raises(MergeConflictError):
out = table.vstack([self.t1, self.t5], join_type='inner', metadata_conflicts='error')
with pytest.raises(ValueError):
out = table.vstack([self.t1, self.t5], join_type='inner', metadata_conflicts='nonsense')
def test_bad_input_type(self, operation_table_type):
self._setup(operation_table_type)
with pytest.raises(ValueError):
table.vstack([])
with pytest.raises(TypeError):
table.vstack(1)
with pytest.raises(TypeError):
table.vstack([self.t2, 1])
with pytest.raises(ValueError):
table.vstack([self.t1, self.t2], join_type='invalid join type')
def test_stack_basic_inner(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t4 = self.t4
t12 = table.vstack([t1, t2], join_type='inner')
assert t12.masked is False
assert type(t12) is operation_table_type
assert type(t12['a']) is type(t1['a']) # noqa
assert type(t12['b']) is type(t1['b']) # noqa
assert t12.pformat() == [' a b ',
'--- ---',
'0.0 foo',
'1.0 bar',
'2.0 pez',
'3.0 sez']
t124 = table.vstack([t1, t2, t4], join_type='inner')
assert type(t124) is operation_table_type
assert type(t12['a']) is type(t1['a']) # noqa
assert type(t12['b']) is type(t1['b']) # noqa
assert t124.pformat() == [' a b ',
'--- ---',
'0.0 foo',
'1.0 bar',
'2.0 pez',
'3.0 sez',
'0.0 foo',
'1.0 bar']
def test_stack_basic_outer(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t4 = self.t4
t12 = table.vstack([t1, t2], join_type='outer')
assert t12.masked is False
assert t12.pformat() == [' a b c ',
'--- --- ---',
'0.0 foo --',
'1.0 bar --',
'2.0 pez 4',
'3.0 sez 5']
t124 = table.vstack([t1, t2, t4], join_type='outer')
assert t124.masked is False
assert t124.pformat() == [' a b c ',
'--- --- ---',
'0.0 foo --',
'1.0 bar --',
'2.0 pez 4',
'3.0 sez 5',
'0.0 foo --',
'1.0 bar --']
def test_stack_incompatible(self, operation_table_type):
self._setup(operation_table_type)
with pytest.raises(TableMergeError) as excinfo:
table.vstack([self.t1, self.t3], join_type='inner')
assert ("The 'b' columns have incompatible types: {}"
.format([self.t1['b'].dtype.name, self.t3['b'].dtype.name])
in str(excinfo.value))
with pytest.raises(TableMergeError) as excinfo:
table.vstack([self.t1, self.t3], join_type='outer')
assert "The 'b' columns have incompatible types:" in str(excinfo.value)
with pytest.raises(TableMergeError):
table.vstack([self.t1, self.t2], join_type='exact')
t1_reshape = self.t1.copy()
t1_reshape['b'].shape = [2, 1]
with pytest.raises(TableMergeError) as excinfo:
table.vstack([self.t1, t1_reshape])
assert "have different shape" in str(excinfo.value)
def test_vstack_one_masked(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
self._setup(operation_table_type)
t1 = self.t1
t4 = self.t4
t4['b'].mask[1] = True
t14 = table.vstack([t1, t4])
assert t14.masked is False
assert t14.pformat() == [' a b ',
'--- ---',
'0.0 foo',
'1.0 bar',
'0.0 foo',
'1.0 --']
def test_col_meta_merge_inner(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t4 = self.t4
# Key col 'a', should last value ('km')
t1['a'].info.unit = 'cm'
t2['a'].info.unit = 'm'
t4['a'].info.unit = 'km'
# Key col 'a' format should take last when all match
t1['a'].info.format = '%f'
t2['a'].info.format = '%f'
t4['a'].info.format = '%f'
# Key col 'b', take first value 't1_b'
t1['b'].info.description = 't1_b'
# Key col 'b', take first non-empty value '%6s'
t4['b'].info.format = '%6s'
# Key col 'a', should be merged meta
t1['a'].info.meta.update(OrderedDict([('b', [1, 2]), ('c', {'a': 1}), ('d', 1)]))
t2['a'].info.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
t4['a'].info.meta.update(OrderedDict([('b', [5, 6]), ('c', {'c': 1}), ('e', 1)]))
# Key col 'b', should be meta2
t2['b'].info.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
if operation_table_type is Table:
ctx = pytest.warns(metadata.MergeConflictWarning)
else:
ctx = nullcontext()
with ctx as warning_lines:
out = table.vstack([t1, t2, t4], join_type='inner')
if operation_table_type is Table:
assert len(warning_lines) == 2
assert ("In merged column 'a' the 'unit' attribute does not match (cm != m)"
in str(warning_lines[0].message))
assert ("In merged column 'a' the 'unit' attribute does not match (m != km)"
in str(warning_lines[1].message))
# Check units are suitably ignored for a regular Table
assert out.pformat() == [' a b ',
' km ',
'-------- ------',
'0.000000 foo',
'1.000000 bar',
'2.000000 pez',
'3.000000 sez',
'0.000000 foo',
'1.000000 bar']
else:
# Check QTable correctly dealt with units.
assert out.pformat() == [' a b ',
' km ',
'-------- ------',
'0.000000 foo',
'0.000010 bar',
'0.002000 pez',
'0.003000 sez',
'0.000000 foo',
'1.000000 bar']
assert out['a'].info.unit == 'km'
assert out['a'].info.format == '%f'
assert out['b'].info.description == 't1_b'
assert out['b'].info.format == '%6s'
assert out['a'].info.meta == self.meta_merge
assert out['b'].info.meta == OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)])
def test_col_meta_merge_outer(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t4 = self.t4
# Key col 'a', should last value ('km')
t1['a'].unit = 'cm'
t2['a'].unit = 'm'
t4['a'].unit = 'km'
# Key col 'a' format should take last when all match
t1['a'].info.format = '%0d'
t2['a'].info.format = '%0d'
t4['a'].info.format = '%0d'
# Key col 'b', take first value 't1_b'
t1['b'].info.description = 't1_b'
# Key col 'b', take first non-empty value '%6s'
t4['b'].info.format = '%6s'
# Key col 'a', should be merged meta
t1['a'].info.meta.update(OrderedDict([('b', [1, 2]), ('c', {'a': 1}), ('d', 1)]))
t2['a'].info.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
t4['a'].info.meta.update(OrderedDict([('b', [5, 6]), ('c', {'c': 1}), ('e', 1)]))
# Key col 'b', should be meta2
t2['b'].info.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
# All these should pass through
t2['c'].unit = 'm'
t2['c'].info.format = '%6s'
t2['c'].info.description = 't2_c'
with pytest.warns(metadata.MergeConflictWarning) as warning_lines:
out = table.vstack([t1, t2, t4], join_type='outer')
assert len(warning_lines) == 2
assert ("In merged column 'a' the 'unit' attribute does not match (cm != m)"
in str(warning_lines[0].message))
assert ("In merged column 'a' the 'unit' attribute does not match (m != km)"
in str(warning_lines[1].message))
assert out['a'].unit == 'km'
assert out['a'].info.format == '%0d'
assert out['b'].info.description == 't1_b'
assert out['b'].info.format == '%6s'
assert out['a'].info.meta == self.meta_merge
assert out['b'].info.meta == OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)])
assert out['c'].info.unit == 'm'
assert out['c'].info.format == '%6s'
assert out['c'].info.description == 't2_c'
def test_vstack_one_table(self, operation_table_type):
self._setup(operation_table_type)
"""Regression test for issue #3313"""
assert (self.t1 == table.vstack(self.t1)).all()
assert (self.t1 == table.vstack([self.t1])).all()
def test_mixin_functionality(self, mixin_cols):
col = mixin_cols['m']
len_col = len(col)
t = table.QTable([col], names=['a'])
cls_name = type(col).__name__
# Vstack works for these classes:
if isinstance(col, (u.Quantity, Time, TimeDelta, SkyCoord, EarthLocation,
BaseRepresentationOrDifferential)):
out = table.vstack([t, t])
assert len(out) == len_col * 2
if cls_name == 'SkyCoord':
# Argh, SkyCoord needs __eq__!!
assert skycoord_equal(out['a'][len_col:], col)
assert skycoord_equal(out['a'][:len_col], col)
elif 'Repr' in cls_name or 'Diff' in cls_name:
assert np.all(representation_equal(out['a'][:len_col], col))
assert np.all(representation_equal(out['a'][len_col:], col))
else:
assert np.all(out['a'][:len_col] == col)
assert np.all(out['a'][len_col:] == col)
else:
with pytest.raises(NotImplementedError) as err:
table.vstack([t, t])
assert ('vstack unavailable for mixin column type(s): {}'
.format(cls_name) in str(err.value))
# Check for outer stack which requires masking. Only Time supports
# this currently.
t2 = table.QTable([col], names=['b']) # different from col name for t
if isinstance(col, (Time, TimeDelta, Quantity)):
out = table.vstack([t, t2], join_type='outer')
assert len(out) == len_col * 2
assert np.all(out['a'][:len_col] == col)
assert np.all(out['b'][len_col:] == col)
assert check_mask(out['a'], [False] * len_col + [True] * len_col)
assert check_mask(out['b'], [True] * len_col + [False] * len_col)
# check directly stacking mixin columns:
out2 = table.vstack([t, t2['b']])
assert np.all(out['a'] == out2['a'])
assert np.all(out['b'] == out2['b'])
else:
with pytest.raises(NotImplementedError) as err:
table.vstack([t, t2], join_type='outer')
assert ('vstack requires masking' in str(err.value)
or 'vstack unavailable' in str(err.value))
def test_vstack_different_representation(self):
"""Test that representations can be mixed together."""
rep1 = CartesianRepresentation([1, 2]*u.km, [3, 4]*u.km, 1*u.km)
rep2 = SphericalRepresentation([0]*u.deg, [0]*u.deg, 10*u.km)
t1 = Table([rep1])
t2 = Table([rep2])
t12 = table.vstack([t1, t2])
expected = CartesianRepresentation([1, 2, 10]*u.km,
[3, 4, 0]*u.km,
[1, 1, 0]*u.km)
assert np.all(representation_equal(t12['col0'], expected))
rep3 = UnitSphericalRepresentation([0]*u.deg, [0]*u.deg)
t3 = Table([rep3])
with pytest.raises(ValueError, match='representations are inconsistent'):
table.vstack([t1, t3])
class TestDStack():
def _setup(self, t_cls=Table):
self.t1 = t_cls.read([' a b',
' 0. foo',
' 1. bar'], format='ascii')
self.t2 = t_cls.read([' a b c',
' 2. pez 4',
' 3. sez 5'], format='ascii')
self.t2['d'] = Time([1, 2], format='cxcsec')
self.t3 = t_cls({'a': [[5., 6.], [4., 3.]],
'b': [['foo', 'bar'], ['pez', 'sez']]},
names=('a', 'b'))
self.t4 = t_cls(self.t1, copy=True, masked=t_cls is Table)
self.t5 = t_cls({'a': [[4., 2.], [1., 6.]],
'b': [['foo', 'pez'], ['bar', 'sez']]},
names=('a', 'b'))
self.t6 = t_cls.read([' a b c',
' 7. pez 2',
' 4. sez 6',
' 6. foo 3'], format='ascii')
def test_validate_join_type(self):
self._setup()
with pytest.raises(TypeError, match='Did you accidentally call dstack'):
table.dstack(self.t1, self.t2)
@staticmethod
def compare_dstack(tables, out):
for ii, tbl in enumerate(tables):
for name, out_col in out.columns.items():
if name in tbl.colnames:
# Columns always compare equal
assert np.all(tbl[name] == out[name][:, ii])
# If input has a mask then output must have same mask
if hasattr(tbl[name], 'mask'):
assert np.all(tbl[name].mask == out[name].mask[:, ii])
# If input has no mask then output might have a mask (if other table
# is missing that column). If so then all mask values should be False.
elif hasattr(out[name], 'mask'):
assert not np.any(out[name].mask[:, ii])
else:
# Column missing for this table, out must have a mask with all True.
assert np.all(out[name].mask[:, ii])
def test_dstack_table_column(self, operation_table_type):
"""Stack a table with 3 cols and one column (gets auto-converted to Table).
"""
self._setup(operation_table_type)
t2 = self.t1.copy()
out = table.dstack([self.t1, t2['a']])
self.compare_dstack([self.t1, t2[('a',)]], out)
def test_dstack_basic_outer(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail('Quantity columns do not support masking.')
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t4 = self.t4
t4['a'].mask[0] = True
# Test for non-masked table
t12 = table.dstack([t1, t2], join_type='outer')
assert type(t12) is operation_table_type
assert type(t12['a']) is type(t1['a']) # noqa
assert type(t12['b']) is type(t1['b']) # noqa
self.compare_dstack([t1, t2], t12)
# Test for masked table
t124 = table.dstack([t1, t2, t4], join_type='outer')
assert type(t124) is operation_table_type
assert type(t124['a']) is type(t4['a']) # noqa
assert type(t124['b']) is type(t4['b']) # noqa
self.compare_dstack([t1, t2, t4], t124)
def test_dstack_basic_inner(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t4 = self.t4
# Test for masked table
t124 = table.dstack([t1, t2, t4], join_type='inner')
assert type(t124) is operation_table_type
assert type(t124['a']) is type(t4['a']) # noqa
assert type(t124['b']) is type(t4['b']) # noqa
self.compare_dstack([t1, t2, t4], t124)
def test_dstack_multi_dimension_column(self, operation_table_type):
self._setup(operation_table_type)
t3 = self.t3
t5 = self.t5
t2 = self.t2
t35 = table.dstack([t3, t5])
assert type(t35) is operation_table_type
assert type(t35['a']) is type(t3['a']) # noqa
assert type(t35['b']) is type(t3['b']) # noqa
self.compare_dstack([t3, t5], t35)
with pytest.raises(TableMergeError):
table.dstack([t2, t3])
def test_dstack_different_length_table(self, operation_table_type):
self._setup(operation_table_type)
t2 = self.t2
t6 = self.t6
with pytest.raises(ValueError):
table.dstack([t2, t6])
def test_dstack_single_table(self):
self._setup(Table)
out = table.dstack(self.t1)
assert np.all(out == self.t1)
def test_dstack_representation(self):
rep1 = SphericalRepresentation([1, 2]*u.deg, [3, 4]*u.deg, 1*u.kpc)
rep2 = SphericalRepresentation([10, 20]*u.deg, [30, 40]*u.deg, 10*u.kpc)
t1 = Table([rep1])
t2 = Table([rep2])
t12 = table.dstack([t1, t2])
assert np.all(representation_equal(t12['col0'][:, 0], rep1))
assert np.all(representation_equal(t12['col0'][:, 1], rep2))
def test_dstack_skycoord(self):
sc1 = SkyCoord([1, 2]*u.deg, [3, 4]*u.deg)
sc2 = SkyCoord([10, 20]*u.deg, [30, 40]*u.deg)
t1 = Table([sc1])
t2 = Table([sc2])
t12 = table.dstack([t1, t2])
assert skycoord_equal(sc1, t12['col0'][:, 0])
assert skycoord_equal(sc2, t12['col0'][:, 1])
class TestHStack():
def _setup(self, t_cls=Table):
self.t1 = t_cls.read([' a b',
' 0. foo',
' 1. bar'], format='ascii')
self.t2 = t_cls.read([' a b c',
' 2. pez 4',
' 3. sez 5'], format='ascii')
self.t3 = t_cls.read([' d e',
' 4. 7',
' 5. 8',
' 6. 9'], format='ascii')
self.t4 = t_cls(self.t1, copy=True, masked=True)
self.t4['a'].name = 'f'
self.t4['b'].name = 'g'
# The following table has meta-data that conflicts with t1
self.t5 = t_cls(self.t1, copy=True)
self.t1.meta.update(OrderedDict([('b', [1, 2]), ('c', {'a': 1}), ('d', 1)]))
self.t2.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
self.t4.meta.update(OrderedDict([('b', [5, 6]), ('c', {'c': 1}), ('e', 1)]))
self.t5.meta.update(OrderedDict([('b', 3), ('c', 'k'), ('d', 1)]))
self.meta_merge = OrderedDict([('b', [1, 2, 3, 4, 5, 6]),
('c', {'a': 1, 'b': 1, 'c': 1}),
('d', 1),
('a', 1),
('e', 1)])
def test_validate_join_type(self):
self._setup()
with pytest.raises(TypeError, match='Did you accidentally call hstack'):
table.hstack(self.t1, self.t2)
def test_stack_same_table(self, operation_table_type):
"""
From #2995, test that hstack'ing references to the same table has the
expected output.
"""
self._setup(operation_table_type)
out = table.hstack([self.t1, self.t1])
assert out.masked is False
assert out.pformat() == ['a_1 b_1 a_2 b_2',
'--- --- --- ---',
'0.0 foo 0.0 foo',
'1.0 bar 1.0 bar']
def test_stack_rows(self, operation_table_type):
self._setup(operation_table_type)
out = table.hstack([self.t1[0], self.t2[1]])
assert out.masked is False
assert out.pformat() == ['a_1 b_1 a_2 b_2 c ',
'--- --- --- --- ---',
'0.0 foo 3.0 sez 5']
def test_stack_columns(self, operation_table_type):
self._setup(operation_table_type)
out = table.hstack([self.t1, self.t2['c']])
assert type(out['a']) is type(self.t1['a']) # noqa
assert type(out['b']) is type(self.t1['b']) # noqa
assert type(out['c']) is type(self.t2['c']) # noqa
assert out.pformat() == [' a b c ',
'--- --- ---',
'0.0 foo 4',
'1.0 bar 5']
def test_table_meta_merge(self, operation_table_type):
self._setup(operation_table_type)
out = table.hstack([self.t1, self.t2, self.t4], join_type='inner')
assert out.meta == self.meta_merge
def test_table_meta_merge_conflict(self, operation_table_type):
self._setup(operation_table_type)
with pytest.warns(metadata.MergeConflictWarning) as w:
out = table.hstack([self.t1, self.t5], join_type='inner')
assert len(w) == 2
assert out.meta == self.t5.meta
with pytest.warns(metadata.MergeConflictWarning) as w:
out = table.hstack([self.t1, self.t5], join_type='inner', metadata_conflicts='warn')
assert len(w) == 2
assert out.meta == self.t5.meta
out = table.hstack([self.t1, self.t5], join_type='inner', metadata_conflicts='silent')
assert out.meta == self.t5.meta
with pytest.raises(MergeConflictError):
out = table.hstack([self.t1, self.t5], join_type='inner', metadata_conflicts='error')
with pytest.raises(ValueError):
out = table.hstack([self.t1, self.t5], join_type='inner', metadata_conflicts='nonsense')
def test_bad_input_type(self, operation_table_type):
self._setup(operation_table_type)
with pytest.raises(ValueError):
table.hstack([])
with pytest.raises(TypeError):
table.hstack(1)
with pytest.raises(TypeError):
table.hstack([self.t2, 1])
with pytest.raises(ValueError):
table.hstack([self.t1, self.t2], join_type='invalid join type')
def test_stack_basic(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t2 = self.t2
t3 = self.t3
t4 = self.t4
out = table.hstack([t1, t2], join_type='inner')
assert out.masked is False
assert type(out) is operation_table_type
assert type(out['a_1']) is type(t1['a']) # noqa
assert type(out['b_1']) is type(t1['b']) # noqa
assert type(out['a_2']) is type(t2['a']) # noqa
assert type(out['b_2']) is type(t2['b']) # noqa
assert out.pformat() == ['a_1 b_1 a_2 b_2 c ',
'--- --- --- --- ---',
'0.0 foo 2.0 pez 4',
'1.0 bar 3.0 sez 5']
# stacking as a list gives same result
out_list = table.hstack([t1, t2], join_type='inner')
assert out.pformat() == out_list.pformat()
out = table.hstack([t1, t2], join_type='outer')
assert out.pformat() == out_list.pformat()
out = table.hstack([t1, t2, t3, t4], join_type='outer')
assert out.masked is False
assert out.pformat() == ['a_1 b_1 a_2 b_2 c d e f g ',
'--- --- --- --- --- --- --- --- ---',
'0.0 foo 2.0 pez 4 4.0 7 0.0 foo',
'1.0 bar 3.0 sez 5 5.0 8 1.0 bar',
' -- -- -- -- -- 6.0 9 -- --']
out = table.hstack([t1, t2, t3, t4], join_type='inner')
assert out.masked is False
assert out.pformat() == ['a_1 b_1 a_2 b_2 c d e f g ',
'--- --- --- --- --- --- --- --- ---',
'0.0 foo 2.0 pez 4 4.0 7 0.0 foo',
'1.0 bar 3.0 sez 5 5.0 8 1.0 bar']
def test_stack_incompatible(self, operation_table_type):
self._setup(operation_table_type)
# For join_type exact, which will fail here because n_rows
# does not match
with pytest.raises(TableMergeError):
table.hstack([self.t1, self.t3], join_type='exact')
def test_hstack_one_masked(self, operation_table_type):
if operation_table_type is QTable:
pytest.xfail()
self._setup(operation_table_type)
t1 = self.t1
t2 = operation_table_type(t1, copy=True, masked=True)
t2.meta.clear()
t2['b'].mask[1] = True
out = table.hstack([t1, t2])
assert out.pformat() == ['a_1 b_1 a_2 b_2',
'--- --- --- ---',
'0.0 foo 0.0 foo',
'1.0 bar 1.0 --']
def test_table_col_rename(self, operation_table_type):
self._setup(operation_table_type)
out = table.hstack([self.t1, self.t2], join_type='inner',
uniq_col_name='{table_name}_{col_name}',
table_names=('left', 'right'))
assert out.masked is False
assert out.pformat() == ['left_a left_b right_a right_b c ',
'------ ------ ------- ------- ---',
' 0.0 foo 2.0 pez 4',
' 1.0 bar 3.0 sez 5']
def test_col_meta_merge(self, operation_table_type):
self._setup(operation_table_type)
t1 = self.t1
t3 = self.t3[:2]
t4 = self.t4
# Just set a bunch of meta and make sure it is the same in output
meta1 = OrderedDict([('b', [1, 2]), ('c', {'a': 1}), ('d', 1)])
t1['a'].unit = 'cm'
t1['b'].info.description = 't1_b'
t4['f'].info.format = '%6s'
t1['b'].info.meta.update(meta1)
t3['d'].info.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
t4['g'].info.meta.update(OrderedDict([('b', [5, 6]), ('c', {'c': 1}), ('e', 1)]))
t3['e'].info.meta.update(OrderedDict([('b', [3, 4]), ('c', {'b': 1}), ('a', 1)]))
t3['d'].unit = 'm'
t3['d'].info.format = '%6s'
t3['d'].info.description = 't3_c'
out = table.hstack([t1, t3, t4], join_type='exact')
for t in [t1, t3, t4]:
for name in t.colnames:
for attr in ('meta', 'unit', 'format', 'description'):
assert getattr(out[name].info, attr) == getattr(t[name].info, attr)
# Make sure we got a copy of meta, not ref
t1['b'].info.meta['b'] = None
assert out['b'].info.meta['b'] == [1, 2]
def test_hstack_one_table(self, operation_table_type):
self._setup(operation_table_type)
"""Regression test for issue #3313"""
assert (self.t1 == table.hstack(self.t1)).all()
assert (self.t1 == table.hstack([self.t1])).all()
def test_mixin_functionality(self, mixin_cols):
col1 = mixin_cols['m']
col2 = col1[2:4] # Shorter version of col1
t1 = table.QTable([col1])
t2 = table.QTable([col2])
cls_name = type(col1).__name__
out = table.hstack([t1, t2], join_type='inner')
assert type(out['col0_1']) is type(out['col0_2']) # noqa
assert len(out) == len(col2)
# Check that columns are as expected.
if cls_name == 'SkyCoord':
assert skycoord_equal(out['col0_1'], col1[:len(col2)])
assert skycoord_equal(out['col0_2'], col2)
elif 'Repr' in cls_name or 'Diff' in cls_name:
assert np.all(representation_equal(out['col0_1'], col1[:len(col2)]))
assert np.all(representation_equal(out['col0_2'], col2))
else:
assert np.all(out['col0_1'] == col1[:len(col2)])
assert np.all(out['col0_2'] == col2)
# Time class supports masking, all other mixins do not
if isinstance(col1, (Time, TimeDelta, Quantity)):
out = table.hstack([t1, t2], join_type='outer')
assert len(out) == len(t1)
assert np.all(out['col0_1'] == col1)
assert np.all(out['col0_2'][:len(col2)] == col2)
assert check_mask(out['col0_2'], [False, False, True, True])
# check directly stacking mixin columns:
out2 = table.hstack([t1, t2['col0']], join_type='outer')
assert np.all(out['col0_1'] == out2['col0_1'])
assert np.all(out['col0_2'] == out2['col0_2'])
else:
with pytest.raises(NotImplementedError) as err:
table.hstack([t1, t2], join_type='outer')
assert 'hstack requires masking' in str(err.value)
def test_unique(operation_table_type):
t = operation_table_type.read(
[' a b c d',
' 2 b 7.0 0',
' 1 c 3.0 5',
' 2 b 6.0 2',
' 2 a 4.0 3',
' 1 a 1.0 7',
' 2 b 5.0 1',
' 0 a 0.0 4',
' 1 a 2.0 6',
' 1 c 3.0 5',
], format='ascii')
tu = operation_table_type(np.sort(t[:-1]))
t_all = table.unique(t)
assert sort_eq(t_all.pformat(), tu.pformat())
t_s = t.copy()
del t_s['b', 'c', 'd']
t_all = table.unique(t_s)
assert sort_eq(t_all.pformat(), [' a ',
'---',
' 0',
' 1',
' 2'])
key1 = 'a'
t1a = table.unique(t, key1)
assert sort_eq(t1a.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 1 c 3.0 5',
' 2 b 7.0 0'])
t1b = table.unique(t, key1, keep='last')
assert sort_eq(t1b.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 1 c 3.0 5',
' 2 b 5.0 1'])
t1c = table.unique(t, key1, keep='none')
assert sort_eq(t1c.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4'])
key2 = ['a', 'b']
t2a = table.unique(t, key2)
assert sort_eq(t2a.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 1 a 1.0 7',
' 1 c 3.0 5',
' 2 a 4.0 3',
' 2 b 7.0 0'])
t2b = table.unique(t, key2, keep='last')
assert sort_eq(t2b.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 1 a 2.0 6',
' 1 c 3.0 5',
' 2 a 4.0 3',
' 2 b 5.0 1'])
t2c = table.unique(t, key2, keep='none')
assert sort_eq(t2c.pformat(), [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 2 a 4.0 3'])
key2 = ['a', 'a']
with pytest.raises(ValueError) as exc:
t2a = table.unique(t, key2)
assert exc.value.args[0] == "duplicate key names"
with pytest.raises(ValueError) as exc:
table.unique(t, key2, keep=True)
assert exc.value.args[0] == (
"'keep' should be one of 'first', 'last', 'none'")
t1_m = operation_table_type(t1a, masked=True)
t1_m['a'].mask[1] = True
with pytest.raises(ValueError) as exc:
t1_mu = table.unique(t1_m)
assert exc.value.args[0] == (
"cannot use columns with masked values as keys; "
"remove column 'a' from keys and rerun unique()")
t1_mu = table.unique(t1_m, silent=True)
assert t1_mu.masked is False
assert t1_mu.pformat() == [' a b c d ',
'--- --- --- ---',
' 0 a 0.0 4',
' 2 b 7.0 0',
' -- c 3.0 5']
with pytest.raises(ValueError):
t1_mu = table.unique(t1_m, silent=True, keys='a')
t1_m = operation_table_type(t, masked=True)
t1_m['a'].mask[1] = True
t1_m['d'].mask[3] = True
# Test that multiple masked key columns get removed in the correct
# order
t1_mu = table.unique(t1_m, keys=['d', 'a', 'b'], silent=True)
assert t1_mu.masked is False
assert t1_mu.pformat() == [' a b c d ',
'--- --- --- ---',
' 2 a 4.0 --',
' 2 b 7.0 0',
' -- c 3.0 5']
def test_vstack_bytes(operation_table_type):
"""
Test for issue #5617 when vstack'ing bytes columns in Py3.
This is really an upstream numpy issue numpy/numpy/#8403.
"""
t = operation_table_type([[b'a']], names=['a'])
assert t['a'].itemsize == 1
t2 = table.vstack([t, t])
assert len(t2) == 2
assert t2['a'].itemsize == 1
def test_vstack_unicode():
"""
Test for problem related to issue #5617 when vstack'ing *unicode*
columns. In this case the character size gets multiplied by 4.
"""
t = table.Table([['a']], names=['a'])
assert t['a'].itemsize == 4 # 4-byte / char for U dtype
t2 = table.vstack([t, t])
assert len(t2) == 2
assert t2['a'].itemsize == 4
def test_join_mixins_time_quantity():
"""
Test for table join using non-ndarray key columns.
"""
tm1 = Time([2, 1, 2], format='cxcsec')
q1 = [2, 1, 1] * u.m
idx1 = [1, 2, 3]
tm2 = Time([2, 3], format='cxcsec')
q2 = [2, 3] * u.m
idx2 = [10, 20]
t1 = Table([tm1, q1, idx1], names=['tm', 'q', 'idx'])
t2 = Table([tm2, q2, idx2], names=['tm', 'q', 'idx'])
# Output:
#
# <Table length=4>
# tm q idx_1 idx_2
# m
# object float64 int64 int64
# ------------------ ------- ----- -----
# 0.9999999999969589 1.0 2 --
# 2.00000000000351 1.0 3 --
# 2.00000000000351 2.0 1 10
# 3.000000000000469 3.0 -- 20
t12 = table.join(t1, t2, join_type='outer', keys=['tm', 'q'])
# Key cols are lexically sorted
assert np.all(t12['tm'] == Time([1, 2, 2, 3], format='cxcsec'))
assert np.all(t12['q'] == [1, 1, 2, 3] * u.m)
assert np.all(t12['idx_1'] == np.ma.array([2, 3, 1, 0], mask=[0, 0, 0, 1]))
assert np.all(t12['idx_2'] == np.ma.array([0, 0, 10, 20], mask=[1, 1, 0, 0]))
def test_join_mixins_not_sortable():
"""
Test for table join using non-ndarray key columns that are not sortable.
"""
sc = SkyCoord([1, 2], [3, 4], unit='deg,deg')
t1 = Table([sc, [1, 2]], names=['sc', 'idx1'])
t2 = Table([sc, [10, 20]], names=['sc', 'idx2'])
with pytest.raises(TypeError, match='one or more key columns are not sortable'):
table.join(t1, t2, keys='sc')
def test_join_non_1d_key_column():
c1 = [[1, 2], [3, 4]]
c2 = [1, 2]
t1 = Table([c1, c2], names=['a', 'b'])
t2 = t1.copy()
with pytest.raises(ValueError, match="key column 'a' must be 1-d"):
table.join(t1, t2, keys='a')
def test_argsort_time_column():
"""Regression test for #10823."""
times = Time(['2016-01-01', '2018-01-01', '2017-01-01'])
t = Table([times], names=['time'])
i = t.argsort('time')
assert np.all(i == times.argsort())
def test_sort_indexed_table():
"""Test fix for #9473 and #6545 - and another regression test for #10823."""
t = Table([[1, 3, 2], [6, 4, 5]], names=('a', 'b'))
t.add_index('a')
t.sort('a')
assert np.all(t['a'] == [1, 2, 3])
assert np.all(t['b'] == [6, 5, 4])
t.sort('b')
assert np.all(t['b'] == [4, 5, 6])
assert np.all(t['a'] == [3, 2, 1])
times = ['2016-01-01', '2018-01-01', '2017-01-01']
tm = Time(times)
t2 = Table([tm, [3, 2, 1]], names=['time', 'flux'])
t2.sort('flux')
assert np.all(t2['flux'] == [1, 2, 3])
t2.sort('time')
assert np.all(t2['flux'] == [3, 1, 2])
assert np.all(t2['time'] == tm[[0, 2, 1]])
# Using the table as a TimeSeries implicitly sets the index, so
# this test is a bit different from the above.
from astropy.timeseries import TimeSeries
ts = TimeSeries(time=times)
ts['flux'] = [3, 2, 1]
ts.sort('flux')
assert np.all(ts['flux'] == [1, 2, 3])
ts.sort('time')
assert np.all(ts['flux'] == [3, 1, 2])
assert np.all(ts['time'] == tm[[0, 2, 1]])
def test_get_out_class():
c = table.Column([1, 2])
mc = table.MaskedColumn([1, 2])
q = [1, 2] * u.m
assert _get_out_class([c, mc]) is mc.__class__
assert _get_out_class([mc, c]) is mc.__class__
assert _get_out_class([c, c]) is c.__class__
assert _get_out_class([c]) is c.__class__
with pytest.raises(ValueError):
_get_out_class([c, q])
with pytest.raises(ValueError):
_get_out_class([q, c])
def test_masking_required_exception():
"""
Test that outer join, hstack and vstack fail for a mixin column which
does not support masking.
"""
col = table.NdarrayMixin([0, 1, 2, 3])
t1 = table.QTable([[1, 2, 3, 4], col], names=['a', 'b'])
t2 = table.QTable([[1, 2], col[:2]], names=['a', 'c'])
with pytest.raises(NotImplementedError) as err:
table.vstack([t1, t2], join_type='outer')
assert 'vstack unavailable' in str(err.value)
with pytest.raises(NotImplementedError) as err:
table.hstack([t1, t2], join_type='outer')
assert 'hstack requires masking' in str(err.value)
with pytest.raises(NotImplementedError) as err:
table.join(t1, t2, join_type='outer')
assert 'join requires masking' in str(err.value)
def test_stack_columns():
c = table.Column([1, 2])
mc = table.MaskedColumn([1, 2])
q = [1, 2] * u.m
time = Time(['2001-01-02T12:34:56', '2001-02-03T00:01:02'])
sc = SkyCoord([1, 2], [3, 4], unit='deg')
cq = table.Column([11, 22], unit=u.m)
t = table.hstack([c, q])
assert t.__class__ is table.QTable
assert t.masked is False
t = table.hstack([q, c])
assert t.__class__ is table.QTable
assert t.masked is False
t = table.hstack([mc, q])
assert t.__class__ is table.QTable
assert t.masked is False
t = table.hstack([c, mc])
assert t.__class__ is table.Table
assert t.masked is False
t = table.vstack([q, q])
assert t.__class__ is table.QTable
t = table.vstack([c, c])
assert t.__class__ is table.Table
t = table.hstack([c, time])
assert t.__class__ is table.Table
t = table.hstack([c, sc])
assert t.__class__ is table.Table
t = table.hstack([q, time, sc])
assert t.__class__ is table.QTable
with pytest.raises(ValueError):
table.vstack([c, q])
with pytest.raises(ValueError):
t = table.vstack([q, cq])
def test_mixin_join_regression():
# This used to trigger a ValueError:
# ValueError: NumPy boolean array indexing assignment cannot assign
# 6 input values to the 4 output values where the mask is true
t1 = QTable()
t1['index'] = [1, 2, 3, 4, 5]
t1['flux1'] = [2, 3, 2, 1, 1] * u.Jy
t1['flux2'] = [2, 3, 2, 1, 1] * u.Jy
t2 = QTable()
t2['index'] = [3, 4, 5, 6]
t2['flux1'] = [2, 1, 1, 3] * u.Jy
t2['flux2'] = [2, 1, 1, 3] * u.Jy
t12 = table.join(t1, t2, keys=('index', 'flux1', 'flux2'), join_type='outer')
assert len(t12) == 6
|
eded84ad1d8fc05cf89aa0e4735b1653ce3d29f246611ce89713b5c83bb6b331 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy.utils.tests.test_metadata import MetaBaseTest
import operator
import pytest
import numpy as np
from numpy.testing import assert_array_equal
from astropy.tests.helper import assert_follows_unicode_guidelines
from astropy import table
from astropy import time
from astropy import units as u
class TestColumn():
def test_subclass(self, Column):
c = Column(name='a')
assert isinstance(c, np.ndarray)
c2 = c * 2
assert isinstance(c2, Column)
assert isinstance(c2, np.ndarray)
def test_numpy_ops(self, Column):
"""Show that basic numpy operations with Column behave sensibly"""
arr = np.array([1, 2, 3])
c = Column(arr, name='a')
for op, test_equal in ((operator.eq, True),
(operator.ne, False),
(operator.ge, True),
(operator.gt, False),
(operator.le, True),
(operator.lt, False)):
for eq in (op(c, arr), op(arr, c)):
assert np.all(eq) if test_equal else not np.any(eq)
assert len(eq) == 3
if Column is table.Column:
assert type(eq) == np.ndarray
else:
assert type(eq) == np.ma.core.MaskedArray
assert eq.dtype.str == '|b1'
lt = c - 1 < arr
assert np.all(lt)
def test_numpy_boolean_ufuncs(self, Column):
"""Show that basic numpy operations with Column behave sensibly"""
arr = np.array([1, 2, 3])
c = Column(arr, name='a')
for ufunc, test_true in ((np.isfinite, True),
(np.isinf, False),
(np.isnan, False),
(np.sign, True),
(np.signbit, False)):
result = ufunc(c)
assert len(result) == len(c)
assert np.all(result) if test_true else not np.any(result)
if Column is table.Column:
assert type(result) == np.ndarray
else:
assert type(result) == np.ma.core.MaskedArray
if ufunc is not np.sign:
assert result.dtype.str == '|b1'
def test_view(self, Column):
c = np.array([1, 2, 3], dtype=np.int64).view(Column)
assert repr(c) == f"<{Column.__name__} dtype='int64' length=3>\n1\n2\n3"
def test_format(self, Column):
"""Show that the formatted output from str() works"""
from astropy import conf
with conf.set_temp('max_lines', 8):
c1 = Column(np.arange(2000), name='a', dtype=float,
format='%6.2f')
assert str(c1).splitlines() == [' a ',
'-------',
' 0.00',
' 1.00',
' ...',
'1998.00',
'1999.00',
'Length = 2000 rows']
def test_convert_numpy_array(self, Column):
d = Column([1, 2, 3], name='a', dtype='i8')
np_data = np.array(d)
assert np.all(np_data == d)
np_data = np.array(d, copy=False)
assert np.all(np_data == d)
np_data = np.array(d, dtype='i4')
assert np.all(np_data == d)
def test_convert_unit(self, Column):
d = Column([1, 2, 3], name='a', dtype="f8", unit="m")
d.convert_unit_to("km")
assert np.all(d.data == [0.001, 0.002, 0.003])
def test_array_wrap(self):
"""Test that the __array_wrap__ method converts a reduction ufunc
output that has a different shape into an ndarray view. Without this a
method call like c.mean() returns a Column array object with length=1."""
# Mean and sum for a 1-d float column
c = table.Column(name='a', data=[1., 2., 3.])
assert np.allclose(c.mean(), 2.0)
assert isinstance(c.mean(), (np.floating, float))
assert np.allclose(c.sum(), 6.)
assert isinstance(c.sum(), (np.floating, float))
# Non-reduction ufunc preserves Column class
assert isinstance(np.cos(c), table.Column)
# Sum for a 1-d int column
c = table.Column(name='a', data=[1, 2, 3])
assert np.allclose(c.sum(), 6)
assert isinstance(c.sum(), (np.integer, int))
# Sum for a 2-d int column
c = table.Column(name='a', data=[[1, 2, 3],
[4, 5, 6]])
assert c.sum() == 21
assert isinstance(c.sum(), (np.integer, int))
assert np.all(c.sum(axis=0) == [5, 7, 9])
assert c.sum(axis=0).shape == (3,)
assert isinstance(c.sum(axis=0), np.ndarray)
# Sum and mean for a 1-d masked column
c = table.MaskedColumn(name='a', data=[1., 2., 3.], mask=[0, 0, 1])
assert np.allclose(c.mean(), 1.5)
assert isinstance(c.mean(), (np.floating, float))
assert np.allclose(c.sum(), 3.)
assert isinstance(c.sum(), (np.floating, float))
def test_name_none(self, Column):
"""Can create a column without supplying name, which defaults to None"""
c = Column([1, 2])
assert c.name is None
assert np.all(c == np.array([1, 2]))
def test_quantity_init(self, Column):
c = Column(data=np.array([1, 2, 3]) * u.m)
assert np.all(c.data == np.array([1, 2, 3]))
assert np.all(c.unit == u.m)
c = Column(data=np.array([1, 2, 3]) * u.m, unit=u.cm)
assert np.all(c.data == np.array([100, 200, 300]))
assert np.all(c.unit == u.cm)
def test_quantity_comparison(self, Column):
# regression test for gh-6532
c = Column([1, 2100, 3], unit='Hz')
q = 2 * u.kHz
check = c < q
assert np.all(check == [True, False, True])
# This already worked, but just in case.
check = q >= c
assert np.all(check == [True, False, True])
def test_attrs_survive_getitem_after_change(self, Column):
"""
Test for issue #3023: when calling getitem with a MaskedArray subclass
the original object attributes are not copied.
"""
c1 = Column([1, 2, 3], name='a', unit='m', format='%i',
description='aa', meta={'a': 1})
c1.name = 'b'
c1.unit = 'km'
c1.format = '%d'
c1.description = 'bb'
c1.meta = {'bbb': 2}
for item in (slice(None, None), slice(None, 1), np.array([0, 2]),
np.array([False, True, False])):
c2 = c1[item]
assert c2.name == 'b'
assert c2.unit is u.km
assert c2.format == '%d'
assert c2.description == 'bb'
assert c2.meta == {'bbb': 2}
# Make sure that calling getitem resulting in a scalar does
# not copy attributes.
val = c1[1]
for attr in ('name', 'unit', 'format', 'description', 'meta'):
assert not hasattr(val, attr)
def test_to_quantity(self, Column):
d = Column([1, 2, 3], name='a', dtype="f8", unit="m")
assert np.all(d.quantity == ([1, 2, 3.] * u.m))
assert np.all(d.quantity.value == ([1, 2, 3.] * u.m).value)
assert np.all(d.quantity == d.to('m'))
assert np.all(d.quantity.value == d.to('m').value)
np.testing.assert_allclose(d.to(u.km).value, ([.001, .002, .003] * u.km).value)
np.testing.assert_allclose(d.to('km').value, ([.001, .002, .003] * u.km).value)
np.testing.assert_allclose(d.to(u.MHz, u.equivalencies.spectral()).value,
[299.792458, 149.896229, 99.93081933])
d_nounit = Column([1, 2, 3], name='a', dtype="f8", unit=None)
with pytest.raises(u.UnitsError):
d_nounit.to(u.km)
assert np.all(d_nounit.to(u.dimensionless_unscaled) == np.array([1, 2, 3]))
# make sure the correct copy/no copy behavior is happening
q = [1, 3, 5] * u.km
# to should always make a copy
d.to(u.km)[:] = q
np.testing.assert_allclose(d, [1, 2, 3])
# explicit copying of the quantity should not change the column
d.quantity.copy()[:] = q
np.testing.assert_allclose(d, [1, 2, 3])
# but quantity directly is a "view", accessing the underlying column
d.quantity[:] = q
np.testing.assert_allclose(d, [1000, 3000, 5000])
# view should also work for integers
d2 = Column([1, 2, 3], name='a', dtype=int, unit="m")
d2.quantity[:] = q
np.testing.assert_allclose(d2, [1000, 3000, 5000])
# but it should fail for strings or other non-numeric tables
d3 = Column(['arg', 'name', 'stuff'], name='a', unit="m")
with pytest.raises(TypeError):
d3.quantity
def test_to_funcunit_quantity(self, Column):
"""
Tests for #8424, check if function-unit can be retrieved from column.
"""
d = Column([1, 2, 3], name='a', dtype="f8", unit="dex(AA)")
assert np.all(d.quantity == ([1, 2, 3] * u.dex(u.AA)))
assert np.all(d.quantity.value == ([1, 2, 3] * u.dex(u.AA)).value)
assert np.all(d.quantity == d.to("dex(AA)"))
assert np.all(d.quantity.value == d.to("dex(AA)").value)
# make sure, casting to linear unit works
q = [10, 100, 1000] * u.AA
np.testing.assert_allclose(d.to(u.AA), q)
def test_item_access_type(self, Column):
"""
Tests for #3095, which forces integer item access to always return a plain
ndarray or MaskedArray, even in the case of a multi-dim column.
"""
integer_types = (int, np.int_)
for int_type in integer_types:
c = Column([[1, 2], [3, 4]])
i0 = int_type(0)
i1 = int_type(1)
assert np.all(c[i0] == [1, 2])
assert type(c[i0]) == (np.ma.MaskedArray if hasattr(Column, 'mask') else np.ndarray)
assert c[i0].shape == (2,)
c01 = c[i0:i1]
assert np.all(c01 == [[1, 2]])
assert isinstance(c01, Column)
assert c01.shape == (1, 2)
c = Column([1, 2])
assert np.all(c[i0] == 1)
assert isinstance(c[i0], np.integer)
assert c[i0].shape == ()
c01 = c[i0:i1]
assert np.all(c01 == [1])
assert isinstance(c01, Column)
assert c01.shape == (1,)
def test_insert_basic(self, Column):
c = Column([0, 1, 2], name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
# Basic insert
c1 = c.insert(1, 100)
assert np.all(c1 == [0, 100, 1, 2])
assert c1.attrs_equal(c)
assert type(c) is type(c1)
if hasattr(c1, 'mask'):
assert c1.data.shape == c1.mask.shape
c1 = c.insert(-1, 100)
assert np.all(c1 == [0, 1, 100, 2])
c1 = c.insert(3, 100)
assert np.all(c1 == [0, 1, 2, 100])
c1 = c.insert(-3, 100)
assert np.all(c1 == [100, 0, 1, 2])
c1 = c.insert(1, [100, 200, 300])
if hasattr(c1, 'mask'):
assert c1.data.shape == c1.mask.shape
# Out of bounds index
with pytest.raises((ValueError, IndexError)):
c1 = c.insert(-4, 100)
with pytest.raises((ValueError, IndexError)):
c1 = c.insert(4, 100)
def test_insert_axis(self, Column):
"""Insert with non-default axis kwarg"""
c = Column([[1, 2], [3, 4]])
c1 = c.insert(1, [5, 6], axis=None)
assert np.all(c1 == [1, 5, 6, 2, 3, 4])
c1 = c.insert(1, [5, 6], axis=1)
assert np.all(c1 == [[1, 5, 2], [3, 6, 4]])
def test_insert_string_expand(self, Column):
c = Column(['a', 'b'])
c1 = c.insert(0, 'abc')
assert np.all(c1 == ['abc', 'a', 'b'])
c = Column(['a', 'b'])
c1 = c.insert(0, ['c', 'def'])
assert np.all(c1 == ['c', 'def', 'a', 'b'])
def test_insert_string_masked_values(self):
c = table.MaskedColumn(['a', 'b'])
c1 = c.insert(0, np.ma.masked)
assert np.all(c1 == ['', 'a', 'b'])
assert np.all(c1.mask == [True, False, False])
assert c1.dtype == 'U1'
c2 = c.insert(1, np.ma.MaskedArray(['ccc', 'dd'], mask=[True, False]))
assert np.all(c2 == ['a', 'ccc', 'dd', 'b'])
assert np.all(c2.mask == [False, True, False, False])
assert c2.dtype == 'U3'
def test_insert_string_type_error(self, Column):
c = Column([1, 2])
with pytest.raises(ValueError, match='invalid literal for int'):
c.insert(0, 'string')
c = Column(['a', 'b'])
with pytest.raises(TypeError, match='string operation on non-string array'):
c.insert(0, 1)
def test_insert_multidim(self, Column):
c = Column([[1, 2],
[3, 4]], name='a', dtype=int)
# Basic insert
c1 = c.insert(1, [100, 200])
assert np.all(c1 == [[1, 2], [100, 200], [3, 4]])
# Broadcast
c1 = c.insert(1, 100)
assert np.all(c1 == [[1, 2], [100, 100], [3, 4]])
# Wrong shape
with pytest.raises(ValueError):
c1 = c.insert(1, [100, 200, 300])
def test_insert_object(self, Column):
c = Column(['a', 1, None], name='a', dtype=object)
# Basic insert
c1 = c.insert(1, [100, 200])
assert np.all(c1 == np.array(['a', [100, 200], 1, None],
dtype=object))
def test_insert_masked(self):
c = table.MaskedColumn([0, 1, 2], name='a', fill_value=9999,
mask=[False, True, False])
# Basic insert
c1 = c.insert(1, 100)
assert np.all(c1.data.data == [0, 100, 1, 2])
assert c1.fill_value == 9999
assert np.all(c1.data.mask == [False, False, True, False])
assert type(c) is type(c1)
for mask in (False, True):
c1 = c.insert(1, 100, mask=mask)
assert np.all(c1.data.data == [0, 100, 1, 2])
assert np.all(c1.data.mask == [False, mask, True, False])
def test_masked_multidim_as_list(self):
data = np.ma.MaskedArray([1, 2], mask=[True, False])
c = table.MaskedColumn([data])
assert c.shape == (1, 2)
assert np.all(c[0].mask == [True, False])
def test_insert_masked_multidim(self):
c = table.MaskedColumn([[1, 2],
[3, 4]], name='a', dtype=int)
c1 = c.insert(1, [100, 200], mask=True)
assert np.all(c1.data.data == [[1, 2], [100, 200], [3, 4]])
assert np.all(c1.data.mask == [[False, False], [True, True], [False, False]])
c1 = c.insert(1, [100, 200], mask=[True, False])
assert np.all(c1.data.data == [[1, 2], [100, 200], [3, 4]])
assert np.all(c1.data.mask == [[False, False], [True, False], [False, False]])
with pytest.raises(ValueError):
c1 = c.insert(1, [100, 200], mask=[True, False, True])
def test_mask_on_non_masked_table(self):
"""
When table is not masked and trying to set mask on column then
it's Raise AttributeError.
"""
t = table.Table([[1, 2], [3, 4]], names=('a', 'b'), dtype=('i4', 'f8'))
with pytest.raises(AttributeError):
t['a'].mask = [True, False]
class TestAttrEqual():
"""Bunch of tests originally from ATpy that test the attrs_equal method."""
def test_5(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy')
c2 = Column(name='a', dtype=int, unit='mJy')
assert c1.attrs_equal(c2)
def test_6(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
assert c1.attrs_equal(c2)
def test_7(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='b', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
assert not c1.attrs_equal(c2)
def test_8(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='a', dtype=float, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
assert not c1.attrs_equal(c2)
def test_9(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='a', dtype=int, unit='erg.cm-2.s-1.Hz-1', format='%i',
description='test column', meta={'c': 8, 'd': 12})
assert not c1.attrs_equal(c2)
def test_10(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='a', dtype=int, unit='mJy', format='%g',
description='test column', meta={'c': 8, 'd': 12})
assert not c1.attrs_equal(c2)
def test_11(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='another test column', meta={'c': 8, 'd': 12})
assert not c1.attrs_equal(c2)
def test_12(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'e': 8, 'd': 12})
assert not c1.attrs_equal(c2)
def test_13(self, Column):
c1 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 9, 'd': 12})
assert not c1.attrs_equal(c2)
def test_col_and_masked_col(self):
c1 = table.Column(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
c2 = table.MaskedColumn(name='a', dtype=int, unit='mJy', format='%i',
description='test column', meta={'c': 8, 'd': 12})
assert c1.attrs_equal(c2)
assert c2.attrs_equal(c1)
# Check that the meta descriptor is working as expected. The MetaBaseTest class
# takes care of defining all the tests, and we simply have to define the class
# and any minimal set of args to pass.
class TestMetaColumn(MetaBaseTest):
test_class = table.Column
args = ()
class TestMetaMaskedColumn(MetaBaseTest):
test_class = table.MaskedColumn
args = ()
def test_getitem_metadata_regression():
"""
Regression test for #1471: MaskedArray does not call __array_finalize__ so
the meta-data was not getting copied over. By overloading _update_from we
are able to work around this bug.
"""
# Make sure that meta-data gets propagated with __getitem__
c = table.Column(data=[1, 2], name='a', description='b', unit='m', format="%i", meta={'c': 8})
assert c[1:2].name == 'a'
assert c[1:2].description == 'b'
assert c[1:2].unit == 'm'
assert c[1:2].format == '%i'
assert c[1:2].meta['c'] == 8
c = table.MaskedColumn(data=[1, 2], name='a', description='b',
unit='m', format="%i", meta={'c': 8})
assert c[1:2].name == 'a'
assert c[1:2].description == 'b'
assert c[1:2].unit == 'm'
assert c[1:2].format == '%i'
assert c[1:2].meta['c'] == 8
# As above, but with take() - check the method and the function
c = table.Column(data=[1, 2, 3], name='a', description='b',
unit='m', format="%i", meta={'c': 8})
for subset in [c.take([0, 1]), np.take(c, [0, 1])]:
assert subset.name == 'a'
assert subset.description == 'b'
assert subset.unit == 'm'
assert subset.format == '%i'
assert subset.meta['c'] == 8
# Metadata isn't copied for scalar values
for subset in [c.take(0), np.take(c, 0)]:
assert subset == 1
assert subset.shape == ()
assert not isinstance(subset, table.Column)
c = table.MaskedColumn(data=[1, 2, 3], name='a', description='b',
unit='m', format="%i", meta={'c': 8})
for subset in [c.take([0, 1]), np.take(c, [0, 1])]:
assert subset.name == 'a'
assert subset.description == 'b'
assert subset.unit == 'm'
assert subset.format == '%i'
assert subset.meta['c'] == 8
# Metadata isn't copied for scalar values
for subset in [c.take(0), np.take(c, 0)]:
assert subset == 1
assert subset.shape == ()
assert not isinstance(subset, table.MaskedColumn)
def test_unicode_guidelines():
arr = np.array([1, 2, 3])
c = table.Column(arr, name='a')
assert_follows_unicode_guidelines(c)
def test_scalar_column():
"""
Column is not designed to hold scalars, but for numpy 1.6 this can happen:
>> type(np.std(table.Column([1, 2])))
astropy.table.column.Column
"""
c = table.Column(1.5)
assert repr(c) == '1.5'
assert str(c) == '1.5'
def test_qtable_column_conversion():
"""
Ensures that a QTable that gets assigned a unit switches to be Quantity-y
"""
qtab = table.QTable([[1, 2], [3, 4.2]], names=['i', 'f'])
assert isinstance(qtab['i'], table.column.Column)
assert isinstance(qtab['f'], table.column.Column)
qtab['i'].unit = 'km/s'
assert isinstance(qtab['i'], u.Quantity)
assert isinstance(qtab['f'], table.column.Column)
# should follow from the above, but good to make sure as a #4497 regression test
assert isinstance(qtab['i'][0], u.Quantity)
assert isinstance(qtab[0]['i'], u.Quantity)
assert not isinstance(qtab['f'][0], u.Quantity)
assert not isinstance(qtab[0]['f'], u.Quantity)
# Regression test for #5342: if a function unit is assigned, the column
# should become the appropriate FunctionQuantity subclass.
qtab['f'].unit = u.dex(u.cm / u.s**2)
assert isinstance(qtab['f'], u.Dex)
@pytest.mark.parametrize('masked', [True, False])
def test_string_truncation_warning(masked):
"""
Test warnings associated with in-place assignment to a string
column that results in truncation of the right hand side.
"""
from inspect import currentframe, getframeinfo
t = table.Table([['aa', 'bb']], names=['a'], masked=masked)
t['a'][1] = 'cc'
t['a'][:] = 'dd'
with pytest.warns(table.StringTruncateWarning, match=r'truncated right side '
r'string\(s\) longer than 2 character\(s\)') as w:
frameinfo = getframeinfo(currentframe())
t['a'][0] = 'eee' # replace item with string that gets truncated
assert t['a'][0] == 'ee'
assert len(w) == 1
# Make sure the warning points back to the user code line
assert w[0].lineno == frameinfo.lineno + 1
assert 'test_column' in w[0].filename
with pytest.warns(table.StringTruncateWarning, match=r'truncated right side '
r'string\(s\) longer than 2 character\(s\)') as w:
t['a'][:] = ['ff', 'ggg'] # replace item with string that gets truncated
assert np.all(t['a'] == ['ff', 'gg'])
assert len(w) == 1
# Test the obscure case of assigning from an array that was originally
# wider than any of the current elements (i.e. dtype is U4 but actual
# elements are U1 at the time of assignment).
val = np.array(['ffff', 'gggg'])
val[:] = ['f', 'g']
t['a'][:] = val
assert np.all(t['a'] == ['f', 'g'])
def test_string_truncation_warning_masked():
"""
Test warnings associated with in-place assignment to a string
to a masked column, specifically where the right hand side
contains np.ma.masked.
"""
# Test for strings, but also cover assignment of np.ma.masked to
# int and float masked column setting. This was previously only
# covered in an unrelated io.ascii test (test_line_endings) which
# showed an unexpected difference between handling of str and numeric
# masked arrays.
for values in (['a', 'b'], [1, 2], [1.0, 2.0]):
mc = table.MaskedColumn(values)
mc[1] = np.ma.masked
assert np.all(mc.mask == [False, True])
mc[:] = np.ma.masked
assert np.all(mc.mask == [True, True])
mc = table.MaskedColumn(['aa', 'bb'])
with pytest.warns(table.StringTruncateWarning, match=r'truncated right side '
r'string\(s\) longer than 2 character\(s\)') as w:
mc[:] = [np.ma.masked, 'ggg'] # replace item with string that gets truncated
assert mc[1] == 'gg'
assert np.all(mc.mask == [True, False])
assert len(w) == 1
@pytest.mark.parametrize('Column', (table.Column, table.MaskedColumn))
def test_col_unicode_sandwich_create_from_str(Column):
"""
Create a bytestring Column from strings (including unicode) in Py3.
"""
# a-umlaut is a 2-byte character in utf-8, test fails with ascii encoding.
# Stress the system by injecting non-ASCII characters.
uba = 'bä'
c = Column([uba, 'def'], dtype='S')
assert c.dtype.char == 'S'
assert c[0] == uba
assert isinstance(c[0], str)
assert isinstance(c[:0], table.Column)
assert np.all(c[:2] == np.array([uba, 'def']))
@pytest.mark.parametrize('Column', (table.Column, table.MaskedColumn))
def test_col_unicode_sandwich_bytes_obj(Column):
"""
Create a Column of dtype object with bytestring in it and make sure
it keeps the bytestring and not convert to str with accessed.
"""
c = Column([None, b'def'])
assert c.dtype.char == 'O'
assert not c[0]
assert c[1] == b'def'
assert isinstance(c[1], bytes)
assert not isinstance(c[1], str)
assert isinstance(c[:0], table.Column)
assert np.all(c[:2] == np.array([None, b'def']))
assert not np.all(c[:2] == np.array([None, 'def']))
@pytest.mark.parametrize('Column', (table.Column, table.MaskedColumn))
def test_col_unicode_sandwich_bytes(Column):
"""
Create a bytestring Column from bytes and ensure that it works in Python 3 in
a convenient way like in Python 2.
"""
# a-umlaut is a 2-byte character in utf-8, test fails with ascii encoding.
# Stress the system by injecting non-ASCII characters.
uba = 'bä'
uba8 = uba.encode('utf-8')
c = Column([uba8, b'def'])
assert c.dtype.char == 'S'
assert c[0] == uba
assert isinstance(c[0], str)
assert isinstance(c[:0], table.Column)
assert np.all(c[:2] == np.array([uba, 'def']))
assert isinstance(c[:], table.Column)
assert c[:].dtype.char == 'S'
# Array / list comparisons
assert np.all(c == [uba, 'def'])
ok = c == [uba8, b'def']
assert type(ok) is type(c.data) # noqa
assert ok.dtype.char == '?'
assert np.all(ok)
assert np.all(c == np.array([uba, 'def']))
assert np.all(c == np.array([uba8, b'def']))
# Scalar compare
cmps = (uba, uba8)
for cmp in cmps:
ok = c == cmp
assert type(ok) is type(c.data) # noqa
assert np.all(ok == [True, False])
def test_col_unicode_sandwich_unicode():
"""
Sanity check that Unicode Column behaves normally.
"""
uba = 'bä'
uba8 = uba.encode('utf-8')
c = table.Column([uba, 'def'], dtype='U')
assert c[0] == uba
assert isinstance(c[:0], table.Column)
assert isinstance(c[0], str)
assert np.all(c[:2] == np.array([uba, 'def']))
assert isinstance(c[:], table.Column)
assert c[:].dtype.char == 'U'
ok = c == [uba, 'def']
assert type(ok) == np.ndarray
assert ok.dtype.char == '?'
assert np.all(ok)
assert np.all(c != [uba8, b'def'])
def test_masked_col_unicode_sandwich():
"""
Create a bytestring MaskedColumn and ensure that it works in Python 3 in
a convenient way like in Python 2.
"""
c = table.MaskedColumn([b'abc', b'def'])
c[1] = np.ma.masked
assert isinstance(c[:0], table.MaskedColumn)
assert isinstance(c[0], str)
assert c[0] == 'abc'
assert c[1] is np.ma.masked
assert isinstance(c[:], table.MaskedColumn)
assert c[:].dtype.char == 'S'
ok = c == ['abc', 'def']
assert ok[0] == True # noqa
assert ok[1] is np.ma.masked
assert np.all(c == [b'abc', b'def'])
assert np.all(c == np.array(['abc', 'def']))
assert np.all(c == np.array([b'abc', b'def']))
for cmp in ('abc', b'abc'):
ok = c == cmp
assert type(ok) is np.ma.MaskedArray
assert ok[0] == True # noqa
assert ok[1] is np.ma.masked
@pytest.mark.parametrize('Column', (table.Column, table.MaskedColumn))
def test_unicode_sandwich_set(Column):
"""
Test setting
"""
uba = 'bä'
c = Column([b'abc', b'def'])
c[0] = b'aa'
assert np.all(c == ['aa', 'def'])
c[0] = uba # a-umlaut is a 2-byte character in utf-8, test fails with ascii encoding
assert np.all(c == [uba, 'def'])
assert c.pformat() == ['None', '----', ' ' + uba, ' def']
c[:] = b'cc'
assert np.all(c == ['cc', 'cc'])
c[:] = uba
assert np.all(c == [uba, uba])
c[:] = ''
c[:] = [uba, b'def']
assert np.all(c == [uba, b'def'])
@pytest.mark.parametrize('class1', [table.MaskedColumn, table.Column])
@pytest.mark.parametrize('class2', [table.MaskedColumn, table.Column, str, list])
def test_unicode_sandwich_compare(class1, class2):
"""Test that comparing a bytestring Column/MaskedColumn with various
str (unicode) object types gives the expected result. Tests #6838.
"""
obj1 = class1([b'a', b'c'])
if class2 is str:
obj2 = 'a'
elif class2 is list:
obj2 = ['a', 'b']
else:
obj2 = class2(['a', 'b'])
assert np.all((obj1 == obj2) == [True, False])
assert np.all((obj2 == obj1) == [True, False])
assert np.all((obj1 != obj2) == [False, True])
assert np.all((obj2 != obj1) == [False, True])
assert np.all((obj1 > obj2) == [False, True])
assert np.all((obj2 > obj1) == [False, False])
assert np.all((obj1 <= obj2) == [True, False])
assert np.all((obj2 <= obj1) == [True, True])
assert np.all((obj1 < obj2) == [False, False])
assert np.all((obj2 < obj1) == [False, True])
assert np.all((obj1 >= obj2) == [True, True])
assert np.all((obj2 >= obj1) == [True, False])
def test_unicode_sandwich_masked_compare():
"""Test the fix for #6839 from #6899."""
c1 = table.MaskedColumn(['a', 'b', 'c', 'd'],
mask=[True, False, True, False])
c2 = table.MaskedColumn([b'a', b'b', b'c', b'd'],
mask=[True, True, False, False])
for cmp in ((c1 == c2), (c2 == c1)):
assert cmp[0] is np.ma.masked
assert cmp[1] is np.ma.masked
assert cmp[2] is np.ma.masked
assert cmp[3]
for cmp in ((c1 != c2), (c2 != c1)):
assert cmp[0] is np.ma.masked
assert cmp[1] is np.ma.masked
assert cmp[2] is np.ma.masked
assert not cmp[3]
# Note: comparisons <, >, >=, <= fail to return a masked array entirely,
# see https://github.com/numpy/numpy/issues/10092.
def test_structured_masked_column_roundtrip():
mc = table.MaskedColumn([(1., 2.), (3., 4.)],
mask=[(False, False), (False, False)], dtype='f8,f8')
assert len(mc.dtype.fields) == 2
mc2 = table.MaskedColumn(mc)
assert_array_equal(mc2, mc)
@pytest.mark.parametrize('dtype', ['i4,f4', 'f4,(2,)f8'])
def test_structured_empty_column_init(dtype):
dtype = np.dtype(dtype)
c = table.Column(length=5, shape=(2,), dtype=dtype)
assert c.shape == (5, 2)
assert c.dtype == dtype
def test_column_value_access():
"""Can a column's underlying data consistently be accessed via `.value`,
whether it is a `Column`, `MaskedColumn`, `Quantity`, or `Time`?"""
data = np.array([1, 2, 3])
tbl = table.QTable({'a': table.Column(data),
'b': table.MaskedColumn(data),
'c': u.Quantity(data),
'd': time.Time(data, format='mjd')})
assert type(tbl['a'].value) == np.ndarray
assert type(tbl['b'].value) == np.ma.MaskedArray
assert type(tbl['c'].value) == np.ndarray
assert type(tbl['d'].value) == np.ndarray
def test_masked_column_serialize_method_propagation():
mc = table.MaskedColumn([1., 2., 3.], mask=[True, False, True])
assert mc.info.serialize_method['ecsv'] == 'null_value'
mc.info.serialize_method['ecsv'] = 'data_mask'
assert mc.info.serialize_method['ecsv'] == 'data_mask'
mc2 = mc.copy()
assert mc2.info.serialize_method['ecsv'] == 'data_mask'
mc3 = table.MaskedColumn(mc)
assert mc3.info.serialize_method['ecsv'] == 'data_mask'
mc4 = mc.view(table.MaskedColumn)
assert mc4.info.serialize_method['ecsv'] == 'data_mask'
mc5 = mc[1:]
assert mc5.info.serialize_method['ecsv'] == 'data_mask'
@pytest.mark.parametrize('dtype', ['S', 'U', 'i'])
def test_searchsorted(Column, dtype):
c = Column([1, 2, 2, 3], dtype=dtype)
if isinstance(Column, table.MaskedColumn):
# Searchsorted seems to ignore the mask
c[2] = np.ma.masked
if dtype == 'i':
vs = (2, [2, 1])
else:
vs = ('2', ['2', '1'], b'2', [b'2', b'1'])
for v in vs:
v = np.array(v, dtype=dtype)
exp = np.searchsorted(c.data, v, side='right')
res = c.searchsorted(v, side='right')
assert np.all(res == exp)
res = np.searchsorted(c, v, side='right')
assert np.all(res == exp)
|
f5fea9038e891581ed8b1ed56bdc6e546bf44a5a3489de4bdb74511d9febda15 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import sys
import pytest
import numpy as np
from astropy import table
from astropy.table import Row
from astropy import units as u
from .conftest import MaskedTable
def test_masked_row_with_object_col():
"""
Numpy < 1.8 has a bug in masked array that prevents access a row if there is
a column with object type.
"""
t = table.Table([[1]], dtype=['O'], masked=True)
t['col0'].mask = False
assert t[0]['col0'] == 1
t['col0'].mask = True
assert t[0]['col0'] is np.ma.masked
@pytest.mark.usefixtures('table_types')
class TestRow():
def _setup(self, table_types):
self._table_type = table_types.Table
self._column_type = table_types.Column
@property
def t(self):
# pytest wants to run this method once before table_types is run
# to set Table and Column. In this case just return None, which would
# cause any downstream test to fail if this happened in any other context.
if self._column_type is None:
return None
if not hasattr(self, '_t'):
a = self._column_type(name='a', data=[1, 2, 3], dtype='i8')
b = self._column_type(name='b', data=[4, 5, 6], dtype='i8')
self._t = self._table_type([a, b])
return self._t
def test_subclass(self, table_types):
"""Row is subclass of ndarray and Row"""
self._setup(table_types)
c = Row(self.t, 2)
assert isinstance(c, Row)
def test_values(self, table_types):
"""Row accurately reflects table values and attributes"""
self._setup(table_types)
table = self.t
row = table[1]
assert row['a'] == 2
assert row['b'] == 5
assert row[0] == 2
assert row[1] == 5
assert row.meta is table.meta
assert row.colnames == table.colnames
assert row.columns is table.columns
with pytest.raises(IndexError):
row[2]
if sys.byteorder == 'little':
assert str(row.dtype) == "[('a', '<i8'), ('b', '<i8')]"
else:
assert str(row.dtype) == "[('a', '>i8'), ('b', '>i8')]"
def test_ref(self, table_types):
"""Row is a reference into original table data"""
self._setup(table_types)
table = self.t
row = table[1]
row['a'] = 10
if table_types.Table is not MaskedTable:
assert table['a'][1] == 10
def test_left_equal(self, table_types):
"""Compare a table row to the corresponding structured array row"""
self._setup(table_types)
np_t = self.t.as_array()
if table_types.Table is MaskedTable:
with pytest.raises(ValueError):
self.t[0] == np_t[0]
else:
for row, np_row in zip(self.t, np_t):
assert np.all(row == np_row)
def test_left_not_equal(self, table_types):
"""Compare a table row to the corresponding structured array row"""
self._setup(table_types)
np_t = self.t.as_array()
np_t['a'] = [0, 0, 0]
if table_types.Table is MaskedTable:
with pytest.raises(ValueError):
self.t[0] == np_t[0]
else:
for row, np_row in zip(self.t, np_t):
assert np.all(row != np_row)
def test_right_equal(self, table_types):
"""Test right equal"""
self._setup(table_types)
np_t = self.t.as_array()
if table_types.Table is MaskedTable:
with pytest.raises(ValueError):
self.t[0] == np_t[0]
else:
for row, np_row in zip(self.t, np_t):
assert np.all(np_row == row)
def test_convert_numpy_array(self, table_types):
self._setup(table_types)
d = self.t[1]
np_data = np.array(d)
if table_types.Table is not MaskedTable:
assert np.all(np_data == d.as_void())
assert np_data is not d.as_void()
assert d.colnames == list(np_data.dtype.names)
np_data = np.array(d, copy=False)
if table_types.Table is not MaskedTable:
assert np.all(np_data == d.as_void())
assert np_data is not d.as_void()
assert d.colnames == list(np_data.dtype.names)
with pytest.raises(ValueError):
np_data = np.array(d, dtype=[('c', 'i8'), ('d', 'i8')])
def test_format_row(self, table_types):
"""Test formatting row"""
self._setup(table_types)
table = self.t
row = table[0]
assert repr(row).splitlines() == ['<{} {}{}>'
.format(row.__class__.__name__,
'index=0',
' masked=True' if table.masked else ''),
' a b ',
'int64 int64',
'----- -----',
' 1 4']
assert str(row).splitlines() == [' a b ',
'--- ---',
' 1 4']
assert row._repr_html_().splitlines() == [
'<i>{} {}{}</i>'
.format(row.__class__.__name__,
'index=0',
' masked=True' if table.masked else ''),
f'<table id="table{id(table)}">',
'<thead><tr><th>a</th><th>b</th></tr></thead>',
'<thead><tr><th>int64</th><th>int64</th></tr></thead>',
'<tr><td>1</td><td>4</td></tr>',
'</table>']
def test_as_void(self, table_types):
"""Test the as_void() method"""
self._setup(table_types)
table = self.t
row = table[0]
# If masked then with no masks, issue numpy/numpy#483 should come
# into play. Make sure as_void() code is working.
row_void = row.as_void()
if table.masked:
assert isinstance(row_void, np.ma.mvoid)
else:
assert isinstance(row_void, np.void)
assert row_void['a'] == 1
assert row_void['b'] == 4
# Confirm row is a view of table but row_void is not.
table['a'][0] = -100
assert row['a'] == -100
assert row_void['a'] == 1
# Make sure it works for a table that has masked elements
if table.masked:
table['a'].mask = True
# row_void is not a view, need to re-make
assert row_void['a'] == 1
row_void = row.as_void() # but row is a view
assert row['a'] is np.ma.masked
def test_row_and_as_void_with_objects(self, table_types):
"""Test the deprecated data property and as_void() method"""
t = table_types.Table([[{'a': 1}, {'b': 2}]], names=('a',))
assert t[0][0] == {'a': 1}
assert t[0]['a'] == {'a': 1}
assert t[0].as_void()[0] == {'a': 1}
assert t[0].as_void()['a'] == {'a': 1}
def test_bounds_checking(self, table_types):
"""Row gives index error upon creation for out-of-bounds index"""
self._setup(table_types)
for ibad in (-5, -4, 3, 4):
with pytest.raises(IndexError):
self.t[ibad]
def test_create_rows_from_list(self, table_types):
"""https://github.com/astropy/astropy/issues/8976"""
orig_tab = table_types.Table([[1, 2, 3], [4, 5, 6]], names=('a', 'b'))
new_tab = type(orig_tab)(rows=[row for row in orig_tab],
names=orig_tab.dtype.names)
assert np.all(orig_tab == new_tab)
def test_row_keys_values(self, table_types):
self._setup(table_types)
row = self.t[0]
for row_key, col_key in zip(row.keys(), self.t.columns.keys()):
assert row_key == col_key
for row_value, col in zip(row.values(), self.t.columns.values()):
assert row_value == col[0]
def test_row_as_mapping(self, table_types):
self._setup(table_types)
row = self.t[0]
row_dict = dict(row)
for key, value in row_dict.items():
assert row[key] == value
def f(**kwargs):
return kwargs
row_splatted = f(**row)
for key, value in row_splatted.items():
assert row[key] == value
def test_row_as_sequence(self, table_types):
self._setup(table_types)
row = self.t[0]
row_tuple = tuple(row)
keys = tuple(row.keys())
for key, value in zip(keys, row_tuple):
assert row[key] == value
def f(*args):
return args
row_splatted = f(*row)
for key, value in zip(keys, row_splatted):
assert row[key] == value
def test_row_tuple_column_slice():
"""
Test getting and setting a row using a tuple or list of column names
"""
t = table.QTable([[1, 2, 3] * u.m,
[10., 20., 30.],
[100., 200., 300.],
['x', 'y', 'z']], names=['a', 'b', 'c', 'd'])
# Get a row for index=1
r1 = t[1]
# Column slice with tuple of col names
r1_abc = r1['a', 'b', 'c'] # Row object for these cols
r1_abc_repr = ['<Row index=1>',
' a b c ',
' m ',
'float64 float64 float64',
'------- ------- -------',
' 2.0 20.0 200.0']
assert repr(r1_abc).splitlines() == r1_abc_repr
# Column slice with list of col names
r1_abc = r1[['a', 'b', 'c']]
assert repr(r1_abc).splitlines() == r1_abc_repr
# Make sure setting on a tuple or slice updates parent table and row
r1['c'] = 1000
r1['a', 'b'] = 1000 * u.cm, 100.
assert r1['a'] == 10 * u.m
assert r1['b'] == 100
assert t['a'][1] == 10 * u.m
assert t['b'][1] == 100.
assert t['c'][1] == 1000
# Same but using a list of column names instead of tuple
r1[['a', 'b']] = 2000 * u.cm, 200.
assert r1['a'] == 20 * u.m
assert r1['b'] == 200
assert t['a'][1] == 20 * u.m
assert t['b'][1] == 200.
# Set column slice of column slice
r1_abc['a', 'c'] = -1 * u.m, -10
assert t['a'][1] == -1 * u.m
assert t['b'][1] == 200.
assert t['c'][1] == -10.
# Bad column name
with pytest.raises(KeyError) as err:
t[1]['a', 'not_there']
assert "'not_there'" in str(err.value)
# Too many values
with pytest.raises(ValueError) as err:
t[1]['a', 'b'] = 1 * u.m, 2, 3
assert 'right hand side must be a sequence' in str(err.value)
# Something without a length
with pytest.raises(ValueError) as err:
t[1]['a', 'b'] = 1
assert 'right hand side must be a sequence' in str(err.value)
def test_row_tuple_column_slice_transaction():
"""
Test that setting a row that fails part way through does not
change the table at all.
"""
t = table.QTable([[10., 20., 30.],
[1, 2, 3] * u.m], names=['a', 'b'])
tc = t.copy()
# First one succeeds but second fails.
with pytest.raises(ValueError) as err:
t[1]['a', 'b'] = (-1, -1 * u.s) # Bad unit
assert "'s' (time) and 'm' (length) are not convertible" in str(err.value)
assert t[1] == tc[1]
def test_uint_indexing():
"""
Test that accessing a row with an unsigned integer
works as with a signed integer. Similarly tests
that printing such a row works.
This is non-trivial: adding a signed and unsigned
integer in numpy results in a float, which is an
invalid slice index.
Regression test for gh-7464.
"""
t = table.Table([[1., 2., 3.]], names='a')
assert t['a'][1] == 2.
assert t['a'][np.int_(1)] == 2.
assert t['a'][np.uint(1)] == 2.
assert t[np.uint(1)]['a'] == 2.
trepr = ['<Row index=1>',
' a ',
'float64',
'-------',
' 2.0']
assert repr(t[1]).splitlines() == trepr
assert repr(t[np.int_(1)]).splitlines() == trepr
assert repr(t[np.uint(1)]).splitlines() == trepr
|
ce6ab8a6ad50fe969cd4aa30362534fbaf5568b7bab4cf3e8f22016cc9659265 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import copy
import pickle
from io import StringIO
import pytest
import numpy as np
from astropy.table.serialize import represent_mixins_as_columns
from astropy.utils.data_info import ParentDtypeInfo
from astropy.table.table_helpers import ArrayWrapper
from astropy.coordinates import EarthLocation, SkyCoord
from astropy.table import Table, QTable, join, hstack, vstack, Column, NdarrayMixin
from astropy.table import serialize
from astropy import time
from astropy import coordinates
from astropy import units as u
from astropy.table.column import BaseColumn
from astropy.table import table_helpers
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.metadata import MergeConflictWarning
from astropy.coordinates.tests.test_representation import representation_equal
from astropy.io.misc.asdf.tags.helpers import skycoord_equal
from .conftest import MIXIN_COLS
def test_attributes(mixin_cols):
"""
Required attributes for a column can be set.
"""
m = mixin_cols['m']
m.info.name = 'a'
assert m.info.name == 'a'
m.info.description = 'a'
assert m.info.description == 'a'
# Cannot set unit for these classes
if isinstance(m, (u.Quantity, coordinates.SkyCoord, time.Time, time.TimeDelta,
coordinates.BaseRepresentationOrDifferential)):
with pytest.raises(AttributeError):
m.info.unit = u.m
else:
m.info.unit = u.m
assert m.info.unit is u.m
m.info.format = 'a'
assert m.info.format == 'a'
m.info.meta = {'a': 1}
assert m.info.meta == {'a': 1}
with pytest.raises(AttributeError):
m.info.bad_attr = 1
with pytest.raises(AttributeError):
m.info.bad_attr
def check_mixin_type(table, table_col, in_col):
# We check for QuantityInfo rather than just isinstance(col, u.Quantity)
# since we want to treat EarthLocation as a mixin, even though it is
# a Quantity subclass.
if ((isinstance(in_col.info, u.QuantityInfo) and type(table) is not QTable)
or isinstance(in_col, Column)):
assert type(table_col) is table.ColumnClass
else:
assert type(table_col) is type(in_col)
# Make sure in_col got copied and creating table did not touch it
assert in_col.info.name is None
def test_make_table(table_types, mixin_cols):
"""
Make a table with the columns in mixin_cols, which is an ordered dict of
three cols: 'a' and 'b' are table_types.Column type, and 'm' is a mixin.
"""
t = table_types.Table(mixin_cols)
check_mixin_type(t, t['m'], mixin_cols['m'])
cols = list(mixin_cols.values())
t = table_types.Table(cols, names=('i', 'a', 'b', 'm'))
check_mixin_type(t, t['m'], mixin_cols['m'])
t = table_types.Table(cols)
check_mixin_type(t, t['col3'], mixin_cols['m'])
def test_io_ascii_write():
"""
Test that table with mixin column can be written by io.ascii for
every pure Python writer. No validation of the output is done,
this just confirms no exceptions.
"""
from astropy.io.ascii.connect import _get_connectors_table
t = QTable(MIXIN_COLS)
for fmt in _get_connectors_table():
if fmt['Write'] and '.fast_' not in fmt['Format']:
out = StringIO()
t.write(out, format=fmt['Format'])
def test_votable_quantity_write(tmpdir):
"""
Test that table with Quantity mixin column can be round-tripped by
io.votable. Note that FITS and HDF5 mixin support are tested (much more
thoroughly) in their respective subpackage tests
(io/fits/tests/test_connect.py and io/misc/tests/test_hdf5.py).
"""
t = QTable()
t['a'] = u.Quantity([1, 2, 4], unit='nm')
filename = str(tmpdir.join('table-tmp'))
t.write(filename, format='votable', overwrite=True)
qt = QTable.read(filename, format='votable')
assert isinstance(qt['a'], u.Quantity)
assert qt['a'].unit == 'nm'
@pytest.mark.remote_data
@pytest.mark.parametrize('table_types', (Table, QTable))
def test_io_time_write_fits_standard(tmpdir, table_types):
"""
Test that table with Time mixin columns can be written by io.fits.
Validation of the output is done. Test that io.fits writes a table
containing Time mixin columns that can be partially round-tripped
(metadata scale, location).
Note that we postpone checking the "local" scale, since that cannot
be done with format 'cxcsec', as it requires an epoch.
"""
t = table_types([[1, 2], ['string', 'column']])
for scale in time.STANDARD_TIME_SCALES:
t['a' + scale] = time.Time([[1, 2], [3, 4]], format='cxcsec',
scale=scale, location=EarthLocation(
-2446354, 4237210, 4077985, unit='m'))
t['b' + scale] = time.Time(['1999-01-01T00:00:00.123456789',
'2010-01-01T00:00:00'], scale=scale)
t['c'] = [3., 4.]
filename = str(tmpdir.join('table-tmp'))
# Show that FITS format succeeds
with pytest.warns(
AstropyUserWarning,
match='Time Column "btai" has no specified location, '
'but global Time Position is present'):
t.write(filename, format='fits', overwrite=True)
with pytest.warns(
AstropyUserWarning,
match='Time column reference position "TRPOSn" is not specified'):
tm = table_types.read(filename, format='fits', astropy_native=True)
for scale in time.STANDARD_TIME_SCALES:
for ab in ('a', 'b'):
name = ab + scale
# Assert that the time columns are read as Time
assert isinstance(tm[name], time.Time)
# Assert that the scales round-trip
assert tm[name].scale == t[name].scale
# Assert that the format is jd
assert tm[name].format == 'jd'
# Assert that the location round-trips
assert tm[name].location == t[name].location
# Finally assert that the column data round-trips
assert (tm[name] == t[name]).all()
for name in ('col0', 'col1', 'c'):
# Assert that the non-time columns are read as Column
assert isinstance(tm[name], Column)
# Assert that the non-time columns' data round-trips
assert (tm[name] == t[name]).all()
# Test for conversion of time data to its value, as defined by its format
for scale in time.STANDARD_TIME_SCALES:
for ab in ('a', 'b'):
name = ab + scale
t[name].info.serialize_method['fits'] = 'formatted_value'
t.write(filename, format='fits', overwrite=True)
tm = table_types.read(filename, format='fits')
for scale in time.STANDARD_TIME_SCALES:
for ab in ('a', 'b'):
name = ab + scale
assert not isinstance(tm[name], time.Time)
assert (tm[name] == t[name].value).all()
@pytest.mark.parametrize('table_types', (Table, QTable))
def test_io_time_write_fits_local(tmpdir, table_types):
"""
Test that table with a Time mixin with scale local can also be written
by io.fits. Like ``test_io_time_write_fits_standard`` above, but avoiding
``cxcsec`` format, which requires an epoch and thus cannot be used for a
local time scale.
"""
t = table_types([[1, 2], ['string', 'column']])
t['a_local'] = time.Time([[50001, 50002], [50003, 50004]],
format='mjd', scale='local',
location=EarthLocation(-2446354, 4237210, 4077985,
unit='m'))
t['b_local'] = time.Time(['1999-01-01T00:00:00.123456789',
'2010-01-01T00:00:00'], scale='local')
t['c'] = [3., 4.]
filename = str(tmpdir.join('table-tmp'))
# Show that FITS format succeeds
with pytest.warns(AstropyUserWarning,
match='Time Column "b_local" has no specified location'):
t.write(filename, format='fits', overwrite=True)
with pytest.warns(AstropyUserWarning,
match='Time column reference position "TRPOSn" is not specified.'):
tm = table_types.read(filename, format='fits', astropy_native=True)
for ab in ('a', 'b'):
name = ab + '_local'
# Assert that the time columns are read as Time
assert isinstance(tm[name], time.Time)
# Assert that the scales round-trip
assert tm[name].scale == t[name].scale
# Assert that the format is jd
assert tm[name].format == 'jd'
# Assert that the location round-trips
assert tm[name].location == t[name].location
# Finally assert that the column data round-trips
assert (tm[name] == t[name]).all()
for name in ('col0', 'col1', 'c'):
# Assert that the non-time columns are read as Column
assert isinstance(tm[name], Column)
# Assert that the non-time columns' data round-trips
assert (tm[name] == t[name]).all()
# Test for conversion of time data to its value, as defined by its format.
for ab in ('a', 'b'):
name = ab + '_local'
t[name].info.serialize_method['fits'] = 'formatted_value'
t.write(filename, format='fits', overwrite=True)
tm = table_types.read(filename, format='fits')
for ab in ('a', 'b'):
name = ab + '_local'
assert not isinstance(tm[name], time.Time)
assert (tm[name] == t[name].value).all()
def test_votable_mixin_write_fail(mixin_cols):
"""
Test that table with mixin columns (excluding Quantity) cannot be written by
io.votable.
"""
t = QTable(mixin_cols)
# Only do this test if there are unsupported column types (i.e. anything besides
# BaseColumn and Quantity class instances).
unsupported_cols = t.columns.not_isinstance((BaseColumn, u.Quantity))
if not unsupported_cols:
pytest.skip("no unsupported column types")
out = StringIO()
with pytest.raises(ValueError) as err:
t.write(out, format='votable')
assert 'cannot write table with mixin column(s)' in str(err.value)
def test_join(table_types):
"""
Join tables with mixin cols. Use column "i" as proxy for what the
result should be for each mixin.
"""
t1 = table_types.Table()
t1['a'] = table_types.Column(['a', 'b', 'b', 'c'])
t1['i'] = table_types.Column([0, 1, 2, 3])
for name, col in MIXIN_COLS.items():
t1[name] = col
t2 = table_types.Table(t1)
t2['a'] = ['b', 'c', 'a', 'd']
for name, col in MIXIN_COLS.items():
t1[name].info.description = name
t2[name].info.description = name + '2'
for join_type in ('inner', 'left'):
t12 = join(t1, t2, keys='a', join_type=join_type)
idx1 = t12['i_1']
idx2 = t12['i_2']
for name, col in MIXIN_COLS.items():
name1 = name + '_1'
name2 = name + '_2'
assert_table_name_col_equal(t12, name1, col[idx1])
assert_table_name_col_equal(t12, name2, col[idx2])
assert t12[name1].info.description == name
assert t12[name2].info.description == name + '2'
for join_type in ('outer', 'right'):
with pytest.raises(NotImplementedError) as exc:
t12 = join(t1, t2, keys='a', join_type=join_type)
assert 'join requires masking column' in str(exc.value)
with pytest.raises(TypeError) as exc:
t12 = join(t1, t2, keys=['a', 'skycoord'])
assert 'one or more key columns are not sortable' in str(exc.value)
# Join does work for a mixin which is a subclass of np.ndarray
with pytest.warns(MergeConflictWarning,
match="In merged column 'quantity' the 'description' "
"attribute does not match"):
t12 = join(t1, t2, keys=['quantity'])
assert np.all(t12['a_1'] == t1['a'])
def test_hstack(table_types):
"""
Hstack tables with mixin cols. Use column "i" as proxy for what the
result should be for each mixin.
"""
t1 = table_types.Table()
t1['i'] = table_types.Column([0, 1, 2, 3])
for name, col in MIXIN_COLS.items():
t1[name] = col
t1[name].info.description = name
t1[name].info.meta = {'a': 1}
for join_type in ('inner', 'outer'):
for chop in (True, False):
t2 = table_types.Table(t1)
if chop:
t2 = t2[:-1]
if join_type == 'outer':
with pytest.raises(NotImplementedError) as exc:
t12 = hstack([t1, t2], join_type=join_type)
assert 'hstack requires masking column' in str(exc.value)
continue
t12 = hstack([t1, t2], join_type=join_type)
idx1 = t12['i_1']
idx2 = t12['i_2']
for name, col in MIXIN_COLS.items():
name1 = name + '_1'
name2 = name + '_2'
assert_table_name_col_equal(t12, name1, col[idx1])
assert_table_name_col_equal(t12, name2, col[idx2])
for attr in ('description', 'meta'):
assert getattr(t1[name].info, attr) == getattr(t12[name1].info, attr)
assert getattr(t2[name].info, attr) == getattr(t12[name2].info, attr)
def assert_table_name_col_equal(t, name, col):
"""
Assert all(t[name] == col), with special handling for known mixin cols.
"""
if isinstance(col, coordinates.SkyCoord):
assert np.all(t[name].ra == col.ra)
assert np.all(t[name].dec == col.dec)
elif isinstance(col, coordinates.BaseRepresentationOrDifferential):
assert np.all(representation_equal(t[name], col))
elif isinstance(col, u.Quantity):
if type(t) is QTable:
assert np.all(t[name] == col)
elif isinstance(col, table_helpers.ArrayWrapper):
assert np.all(t[name].data == col.data)
else:
assert np.all(t[name] == col)
def test_get_items(mixin_cols):
"""
Test that slicing / indexing table gives right values and col attrs inherit
"""
attrs = ('name', 'unit', 'dtype', 'format', 'description', 'meta')
m = mixin_cols['m']
m.info.name = 'm'
m.info.format = '{0}'
m.info.description = 'd'
m.info.meta = {'a': 1}
t = QTable([m])
for item in ([1, 3], np.array([0, 2]), slice(1, 3)):
t2 = t[item]
m2 = m[item]
assert_table_name_col_equal(t2, 'm', m[item])
for attr in attrs:
assert getattr(t2['m'].info, attr) == getattr(m.info, attr)
assert getattr(m2.info, attr) == getattr(m.info, attr)
def test_info_preserved_pickle_copy_init(mixin_cols):
"""
Test copy, pickle, and init from class roundtrip preserve info. This
tests not only the mixin classes but a regular column as well.
"""
def pickle_roundtrip(c):
return pickle.loads(pickle.dumps(c))
def init_from_class(c):
return c.__class__(c)
attrs = ('name', 'unit', 'dtype', 'format', 'description', 'meta')
for colname in ('i', 'm'):
m = mixin_cols[colname]
m.info.name = colname
m.info.format = '{0}'
m.info.description = 'd'
m.info.meta = {'a': 1}
for func in (copy.copy, copy.deepcopy, pickle_roundtrip, init_from_class):
m2 = func(m)
for attr in attrs:
# non-native byteorder not preserved by last 2 func, _except_ for structured dtype
if (attr != 'dtype'
or getattr(m.info.dtype, 'isnative', True)
or m.info.dtype.name.startswith('void')
or func in (copy.copy, copy.deepcopy)):
original = getattr(m.info, attr)
else:
# func does not preserve byteorder, check against (native) type.
original = m.info.dtype.newbyteorder('=')
assert getattr(m2.info, attr) == original
def test_add_column(mixin_cols):
"""
Test that adding a column preserves values and attributes
"""
attrs = ('name', 'unit', 'dtype', 'format', 'description', 'meta')
m = mixin_cols['m']
assert m.info.name is None
# Make sure adding column in various ways doesn't touch
t = QTable([m], names=['a'])
assert m.info.name is None
t['new'] = m
assert m.info.name is None
m.info.name = 'm'
m.info.format = '{0}'
m.info.description = 'd'
m.info.meta = {'a': 1}
t = QTable([m])
# Add columns m2, m3, m4 by two different methods and test expected equality
t['m2'] = m
m.info.name = 'm3'
t.add_columns([m], copy=True)
m.info.name = 'm4'
t.add_columns([m], copy=False)
for name in ('m2', 'm3', 'm4'):
assert_table_name_col_equal(t, name, m)
for attr in attrs:
if attr != 'name':
assert getattr(t['m'].info, attr) == getattr(t[name].info, attr)
# Also check that one can set using a scalar.
s = m[0]
if type(s) is type(m) and 'info' in s.__dict__:
# We're not going to worry about testing classes for which scalars
# are a different class than the real array, or where info is not copied.
t['s'] = m[0]
assert_table_name_col_equal(t, 's', m[0])
for attr in attrs:
if attr != 'name':
assert getattr(t['m'].info, attr) == getattr(t['s'].info, attr)
# While we're add it, also check a length-1 table.
t = QTable([m[1:2]], names=['m'])
if type(s) is type(m) and 'info' in s.__dict__:
t['s'] = m[0]
assert_table_name_col_equal(t, 's', m[0])
for attr in attrs:
if attr != 'name':
assert getattr(t['m'].info, attr) == getattr(t['s'].info, attr)
def test_vstack():
"""
Vstack tables with mixin cols.
"""
t1 = QTable(MIXIN_COLS)
t2 = QTable(MIXIN_COLS)
with pytest.raises(NotImplementedError):
vstack([t1, t2])
def test_insert_row(mixin_cols):
"""
Test inserting a row, which works for Column, Quantity, Time and SkyCoord.
"""
t = QTable(mixin_cols)
t0 = t.copy()
t['m'].info.description = 'd'
idxs = [0, -1, 1, 2, 3]
if isinstance(t['m'], (u.Quantity, Column, time.Time, time.TimeDelta, coordinates.SkyCoord)):
t.insert_row(1, t[-1])
for name in t.colnames:
col = t[name]
if isinstance(col, coordinates.SkyCoord):
assert skycoord_equal(col, t0[name][idxs])
else:
assert np.all(col == t0[name][idxs])
assert t['m'].info.description == 'd'
else:
with pytest.raises(ValueError) as exc:
t.insert_row(1, t[-1])
assert "Unable to insert row" in str(exc.value)
def test_insert_row_bad_unit():
"""
Insert a row into a QTable with the wrong unit
"""
t = QTable([[1] * u.m])
with pytest.raises(ValueError) as exc:
t.insert_row(0, (2 * u.m / u.s,))
assert "'m / s' (speed/velocity) and 'm' (length) are not convertible" in str(exc.value)
def test_convert_np_array(mixin_cols):
"""
Test that converting to numpy array creates an object dtype and that
each instance in the array has the expected type.
"""
t = QTable(mixin_cols)
ta = t.as_array()
m = mixin_cols['m']
dtype_kind = m.dtype.kind if hasattr(m, 'dtype') else 'O'
assert ta['m'].dtype.kind == dtype_kind
def test_assignment_and_copy():
"""
Test that assignment of an int, slice, and fancy index works.
Along the way test that copying table works.
"""
for name in ('quantity', 'arraywrap'):
m = MIXIN_COLS[name]
t0 = QTable([m], names=['m'])
for i0, i1 in ((1, 2),
(slice(0, 2), slice(1, 3)),
(np.array([1, 2]), np.array([2, 3]))):
t = t0.copy()
t['m'][i0] = m[i1]
if name == 'arraywrap':
assert np.all(t['m'].data[i0] == m.data[i1])
assert np.all(t0['m'].data[i0] == m.data[i0])
assert np.all(t0['m'].data[i0] != t['m'].data[i0])
else:
assert np.all(t['m'][i0] == m[i1])
assert np.all(t0['m'][i0] == m[i0])
assert np.all(t0['m'][i0] != t['m'][i0])
def test_conversion_qtable_table():
"""
Test that a table round trips from QTable => Table => QTable
"""
qt = QTable(MIXIN_COLS)
names = qt.colnames
for name in names:
qt[name].info.description = name
t = Table(qt)
for name in names:
assert t[name].info.description == name
if name == 'quantity':
assert np.all(t['quantity'] == qt['quantity'].value)
assert np.all(t['quantity'].unit is qt['quantity'].unit)
assert isinstance(t['quantity'], t.ColumnClass)
else:
assert_table_name_col_equal(t, name, qt[name])
qt2 = QTable(qt)
for name in names:
assert qt2[name].info.description == name
assert_table_name_col_equal(qt2, name, qt[name])
def test_setitem_as_column_name():
"""
Test for mixin-related regression described in #3321.
"""
t = Table()
t['a'] = ['x', 'y']
t['b'] = 'b' # Previously was failing with KeyError
assert np.all(t['a'] == ['x', 'y'])
assert np.all(t['b'] == ['b', 'b'])
def test_quantity_representation():
"""
Test that table representation of quantities does not have unit
"""
t = QTable([[1, 2] * u.m])
assert t.pformat() == ['col0',
' m ',
'----',
' 1.0',
' 2.0']
def test_representation_representation():
"""
Test that Representations are represented correctly.
"""
# With no unit we get "None" in the unit row
c = coordinates.CartesianRepresentation([0], [1], [0], unit=u.one)
t = Table([c])
assert t.pformat() == [' col0 ',
'------------',
'(0., 1., 0.)']
c = coordinates.CartesianRepresentation([0], [1], [0], unit='m')
t = Table([c])
assert t.pformat() == [' col0 ',
' m ',
'------------',
'(0., 1., 0.)']
c = coordinates.SphericalRepresentation([10]*u.deg, [20]*u.deg, [1]*u.pc)
t = Table([c])
assert t.pformat() == [' col0 ',
' deg, deg, pc ',
'--------------',
'(10., 20., 1.)']
c = coordinates.UnitSphericalRepresentation([10]*u.deg, [20]*u.deg)
t = Table([c])
assert t.pformat() == [' col0 ',
' deg ',
'----------',
'(10., 20.)']
c = coordinates.SphericalCosLatDifferential(
[10]*u.mas/u.yr, [2]*u.mas/u.yr, [10]*u.km/u.s)
t = Table([c])
assert t.pformat() == [' col0 ',
'mas / yr, mas / yr, km / s',
'--------------------------',
' (10., 2., 10.)']
def test_skycoord_representation():
"""
Test that skycoord representation works, both in the way that the
values are output and in changing the frame representation.
"""
# With no unit we get "None" in the unit row
c = coordinates.SkyCoord([0], [1], [0], representation_type='cartesian')
t = Table([c])
assert t.pformat() == [' col0 ',
'None,None,None',
'--------------',
' 0.0,1.0,0.0']
# Test that info works with a dynamically changed representation
c = coordinates.SkyCoord([0], [1], [0], unit='m', representation_type='cartesian')
t = Table([c])
assert t.pformat() == [' col0 ',
' m,m,m ',
'-----------',
'0.0,1.0,0.0']
t['col0'].representation_type = 'unitspherical'
assert t.pformat() == [' col0 ',
'deg,deg ',
'--------',
'90.0,0.0']
t['col0'].representation_type = 'cylindrical'
assert t.pformat() == [' col0 ',
' m,deg,m ',
'------------',
'1.0,90.0,0.0']
def test_ndarray_mixin():
"""
Test directly adding a plain structured array into a table instead of the
view as an NdarrayMixin. Once added as an NdarrayMixin then all the previous
tests apply.
"""
a = np.array([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')],
dtype='<i4,' + ('|U1'))
b = np.array([(10, 'aa'), (20, 'bb'), (30, 'cc'), (40, 'dd')],
dtype=[('x', 'i4'), ('y', ('U2'))])
c = np.rec.fromrecords([(100, 'raa'), (200, 'rbb'), (300, 'rcc'), (400, 'rdd')],
names=['rx', 'ry'])
d = np.arange(8).reshape(4, 2).view(NdarrayMixin)
# Add one during initialization and the next as a new column.
t = Table([a], names=['a'])
t['b'] = b
t['c'] = c
t['d'] = d
assert isinstance(t['a'], NdarrayMixin)
assert t['a'][1][1] == a[1][1]
assert t['a'][2][0] == a[2][0]
assert t[1]['a'][1] == a[1][1]
assert t[2]['a'][0] == a[2][0]
assert isinstance(t['b'], NdarrayMixin)
assert t['b'][1]['x'] == b[1]['x']
assert t['b'][1]['y'] == b[1]['y']
assert t[1]['b']['x'] == b[1]['x']
assert t[1]['b']['y'] == b[1]['y']
assert isinstance(t['c'], NdarrayMixin)
assert t['c'][1]['rx'] == c[1]['rx']
assert t['c'][1]['ry'] == c[1]['ry']
assert t[1]['c']['rx'] == c[1]['rx']
assert t[1]['c']['ry'] == c[1]['ry']
assert isinstance(t['d'], NdarrayMixin)
assert t['d'][1][0] == d[1][0]
assert t['d'][1][1] == d[1][1]
assert t[1]['d'][0] == d[1][0]
assert t[1]['d'][1] == d[1][1]
assert t.pformat() == [' a b c d [2] ',
'-------- ---------- ------------ ------',
"(1, 'a') (10, 'aa') (100, 'raa') 0 .. 1",
"(2, 'b') (20, 'bb') (200, 'rbb') 2 .. 3",
"(3, 'c') (30, 'cc') (300, 'rcc') 4 .. 5",
"(4, 'd') (40, 'dd') (400, 'rdd') 6 .. 7"]
def test_possible_string_format_functions():
"""
The QuantityInfo info class for Quantity implements a
possible_string_format_functions() method that overrides the
standard pprint._possible_string_format_functions() function.
Test this.
"""
t = QTable([[1, 2] * u.m])
t['col0'].info.format = '%.3f'
assert t.pformat() == [' col0',
' m ',
'-----',
'1.000',
'2.000']
t['col0'].info.format = 'hi {:.3f}'
assert t.pformat() == [' col0 ',
' m ',
'--------',
'hi 1.000',
'hi 2.000']
t['col0'].info.format = '.4f'
assert t.pformat() == [' col0 ',
' m ',
'------',
'1.0000',
'2.0000']
def test_rename_mixin_columns(mixin_cols):
"""
Rename a mixin column.
"""
t = QTable(mixin_cols)
tc = t.copy()
t.rename_column('m', 'mm')
assert t.colnames == ['i', 'a', 'b', 'mm']
if isinstance(t['mm'], table_helpers.ArrayWrapper):
assert np.all(t['mm'].data == tc['m'].data)
elif isinstance(t['mm'], coordinates.SkyCoord):
assert np.all(t['mm'].ra == tc['m'].ra)
assert np.all(t['mm'].dec == tc['m'].dec)
elif isinstance(t['mm'], coordinates.BaseRepresentationOrDifferential):
assert np.all(representation_equal(t['mm'], tc['m']))
else:
assert np.all(t['mm'] == tc['m'])
def test_represent_mixins_as_columns_unit_fix():
"""
If the unit is invalid for a column that gets serialized this would
cause an exception. Fixed in #7481.
"""
t = Table({'a': [1, 2]}, masked=True)
t['a'].unit = 'not a valid unit'
t['a'].mask[1] = True
serialize.represent_mixins_as_columns(t)
def test_primary_data_column_gets_description():
"""
If the mixin defines a primary data column, that should get the
description, format, etc., so no __info__ should be needed.
"""
t = QTable({'a': [1, 2] * u.m})
t['a'].info.description = 'parrot'
t['a'].info.format = '7.2f'
tser = serialize.represent_mixins_as_columns(t)
assert '__info__' not in tser.meta['__serialized_columns__']['a']
assert tser['a'].format == '7.2f'
assert tser['a'].description == 'parrot'
def test_skycoord_with_velocity():
# Regression test for gh-6447
sc = SkyCoord([1], [2], unit='deg', galcen_v_sun=None)
t = Table([sc])
s = StringIO()
t.write(s, format='ascii.ecsv', overwrite=True)
s.seek(0)
t2 = Table.read(s.read(), format='ascii.ecsv')
assert skycoord_equal(t2['col0'], sc)
@pytest.mark.parametrize('table_cls', [Table, QTable])
def test_ensure_input_info_is_unchanged(table_cls):
"""If a mixin input to a table has no info, it should stay that way.
This since having 'info' slows down slicing, etc.
See gh-11066.
"""
q = [1, 2] * u.m
assert 'info' not in q.__dict__
t = table_cls([q], names=['q'])
assert 'info' not in q.__dict__
t = table_cls([q])
assert 'info' not in q.__dict__
t = table_cls({'q': q})
assert 'info' not in q.__dict__
t['q2'] = q
assert 'info' not in q.__dict__
sc = SkyCoord([1, 2], [2, 3], unit='deg')
t['sc'] = sc
assert 'info' not in sc.__dict__
def test_bad_info_class():
"""Make a mixin column class that does not trigger the machinery to generate
a pure column representation"""
class MyArrayWrapper(ArrayWrapper):
info = ParentDtypeInfo()
t = Table()
t['tm'] = MyArrayWrapper([0, 1, 2])
out = StringIO()
match = r"failed to represent column 'tm' \(MyArrayWrapper\) as one or more Column subclasses"
with pytest.raises(TypeError, match=match):
represent_mixins_as_columns(t)
|
1de438ce74d6d9d94e14cf4dd8bcc979544ea5c60581b871aef565167cddbc65 | # This Python file uses the following encoding: utf-8
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from io import StringIO
from astropy import table
from astropy.io import ascii
from astropy.table import Table, QTable
from astropy.table.table_helpers import simple_table
from astropy import units as u
from astropy.utils import console
BIG_WIDE_ARR = np.arange(2000, dtype=np.float64).reshape(100, 20)
SMALL_ARR = np.arange(18, dtype=np.int64).reshape(6, 3)
@pytest.mark.usefixtures('table_type')
class TestMultiD():
def test_multidim(self, table_type):
"""Test printing with multidimensional column"""
arr = [np.array([[1, 2],
[10, 20]], dtype=np.int64),
np.array([[3, 4],
[30, 40]], dtype=np.int64),
np.array([[5, 6],
[50, 60]], dtype=np.int64)]
t = table_type(arr)
lines = t.pformat()
assert lines == ['col0 [2] col1 [2] col2 [2]',
'-------- -------- --------',
' 1 .. 2 3 .. 4 5 .. 6',
'10 .. 20 30 .. 40 50 .. 60']
lines = t.pformat(html=True)
assert lines == [
f'<table id="table{id(t)}">',
'<thead><tr><th>col0 [2]</th><th>col1 [2]</th><th>col2 [2]</th></tr></thead>',
'<tr><td>1 .. 2</td><td>3 .. 4</td><td>5 .. 6</td></tr>',
'<tr><td>10 .. 20</td><td>30 .. 40</td><td>50 .. 60</td></tr>',
'</table>']
nbclass = table.conf.default_notebook_table_class
masked = 'masked=True ' if t.masked else ''
assert t._repr_html_().splitlines() == [
f'<div><i>{table_type.__name__} {masked}length=2</i>',
f'<table id="table{id(t)}" class="{nbclass}">',
'<thead><tr><th>col0 [2]</th><th>col1 [2]</th><th>col2 [2]</th></tr></thead>',
'<thead><tr><th>int64</th><th>int64</th><th>int64</th></tr></thead>',
'<tr><td>1 .. 2</td><td>3 .. 4</td><td>5 .. 6</td></tr>',
'<tr><td>10 .. 20</td><td>30 .. 40</td><td>50 .. 60</td></tr>',
'</table></div>']
t = table_type([arr])
lines = t.pformat()
assert lines == ['col0 [2,2]',
'----------',
' 1 .. 20',
' 3 .. 40',
' 5 .. 60']
def test_fake_multidim(self, table_type):
"""Test printing with 'fake' multidimensional column"""
arr = [np.array([[(1,)],
[(10,)]], dtype=np.int64),
np.array([[(3,)],
[(30,)]], dtype=np.int64),
np.array([[(5,)],
[(50,)]], dtype=np.int64)]
t = table_type(arr)
lines = t.pformat()
assert lines == ['col0 [1,1] col1 [1,1] col2 [1,1]',
'---------- ---------- ----------',
' 1 3 5',
' 10 30 50']
lines = t.pformat(html=True)
assert lines == [
f'<table id="table{id(t)}">',
'<thead><tr><th>col0 [1,1]</th><th>col1 [1,1]</th><th>col2 [1,1]</th></tr></thead>',
'<tr><td>1</td><td>3</td><td>5</td></tr>',
'<tr><td>10</td><td>30</td><td>50</td></tr>',
'</table>']
nbclass = table.conf.default_notebook_table_class
masked = 'masked=True ' if t.masked else ''
assert t._repr_html_().splitlines() == [
f'<div><i>{table_type.__name__} {masked}length=2</i>',
f'<table id="table{id(t)}" class="{nbclass}">',
'<thead><tr><th>col0 [1,1]</th><th>col1 [1,1]</th><th>col2 [1,1]</th></tr></thead>',
'<thead><tr><th>int64</th><th>int64</th><th>int64</th></tr></thead>',
'<tr><td>1</td><td>3</td><td>5</td></tr>', '<tr><td>10</td><td>30</td><td>50</td></tr>',
'</table></div>']
t = table_type([arr])
lines = t.pformat()
assert lines == ['col0 [2,1,1]',
'------------',
' 1 .. 10',
' 3 .. 30',
' 5 .. 50']
def test_html_escaping():
t = table.Table([('<script>alert("gotcha");</script>', 2, 3)])
nbclass = table.conf.default_notebook_table_class
assert t._repr_html_().splitlines() == [
'<div><i>Table length=3</i>',
f'<table id="table{id(t)}" class="{nbclass}">',
'<thead><tr><th>col0</th></tr></thead>',
'<thead><tr><th>str33</th></tr></thead>',
'<tr><td><script>alert("gotcha");</script></td></tr>',
'<tr><td>2</td></tr>',
'<tr><td>3</td></tr>',
'</table></div>']
@pytest.mark.usefixtures('table_type')
class TestPprint():
def _setup(self, table_type):
self.tb = table_type(BIG_WIDE_ARR)
self.tb['col0'].format = 'e'
self.tb['col1'].format = '.6f'
self.tb['col0'].unit = 'km**2'
self.tb['col19'].unit = 'kg s m**-2'
self.ts = table_type(SMALL_ARR)
def test_empty_table(self, table_type):
t = table_type()
lines = t.pformat()
assert lines == ['<No columns>']
c = repr(t)
masked = 'masked=True ' if t.masked else ''
assert c.splitlines() == [f'<{table_type.__name__} {masked}length=0>',
'<No columns>']
def test_format0(self, table_type):
"""Try getting screen size but fail to defaults because testing doesn't
have access to screen (fcntl.ioctl fails).
"""
self._setup(table_type)
arr = np.arange(4000, dtype=np.float64).reshape(100, 40)
lines = table_type(arr).pformat()
nlines, width = console.terminal_size()
assert len(lines) == nlines
for line in lines[:-1]: # skip last "Length = .. rows" line
assert width - 10 < len(line) <= width
def test_format1(self, table_type):
"""Basic test of formatting, unit header row included"""
self._setup(table_type)
lines = self.tb.pformat(max_lines=8, max_width=40)
assert lines == [' col0 col1 ... col19 ',
' km2 ... kg s / m2',
'------------ ----------- ... ---------',
'0.000000e+00 1.000000 ... 19.0',
' ... ... ... ...',
'1.960000e+03 1961.000000 ... 1979.0',
'1.980000e+03 1981.000000 ... 1999.0',
'Length = 100 rows']
def test_format2(self, table_type):
"""Basic test of formatting, unit header row excluded"""
self._setup(table_type)
lines = self.tb.pformat(max_lines=8, max_width=40, show_unit=False)
assert lines == [' col0 col1 ... col19 ',
'------------ ----------- ... ------',
'0.000000e+00 1.000000 ... 19.0',
'2.000000e+01 21.000000 ... 39.0',
' ... ... ... ...',
'1.960000e+03 1961.000000 ... 1979.0',
'1.980000e+03 1981.000000 ... 1999.0',
'Length = 100 rows']
def test_format3(self, table_type):
"""Include the unit header row"""
self._setup(table_type)
lines = self.tb.pformat(max_lines=8, max_width=40, show_unit=True)
assert lines == [' col0 col1 ... col19 ',
' km2 ... kg s / m2',
'------------ ----------- ... ---------',
'0.000000e+00 1.000000 ... 19.0',
' ... ... ... ...',
'1.960000e+03 1961.000000 ... 1979.0',
'1.980000e+03 1981.000000 ... 1999.0',
'Length = 100 rows']
def test_format4(self, table_type):
"""Do not include the name header row"""
self._setup(table_type)
lines = self.tb.pformat(max_lines=8, max_width=40, show_name=False)
assert lines == [' km2 ... kg s / m2',
'------------ ----------- ... ---------',
'0.000000e+00 1.000000 ... 19.0',
'2.000000e+01 21.000000 ... 39.0',
' ... ... ... ...',
'1.960000e+03 1961.000000 ... 1979.0',
'1.980000e+03 1981.000000 ... 1999.0',
'Length = 100 rows']
def test_noclip(self, table_type):
"""Basic table print"""
self._setup(table_type)
lines = self.ts.pformat(max_lines=-1, max_width=-1)
assert lines == ['col0 col1 col2',
'---- ---- ----',
' 0 1 2',
' 3 4 5',
' 6 7 8',
' 9 10 11',
' 12 13 14',
' 15 16 17']
def test_clip1(self, table_type):
"""max lines below hard limit of 8
"""
self._setup(table_type)
lines = self.ts.pformat(max_lines=3, max_width=-1)
assert lines == ['col0 col1 col2',
'---- ---- ----',
' 0 1 2',
' 3 4 5',
' 6 7 8',
' 9 10 11',
' 12 13 14',
' 15 16 17']
def test_clip2(self, table_type):
"""max lines below hard limit of 8 and output longer than 8
"""
self._setup(table_type)
lines = self.ts.pformat(max_lines=3, max_width=-1, show_unit=True, show_dtype=True)
assert lines == [' col0 col1 col2',
' ',
'int64 int64 int64',
'----- ----- -----',
' 0 1 2',
' ... ... ...',
' 15 16 17',
'Length = 6 rows']
def test_clip3(self, table_type):
"""Max lines below hard limit of 8 and max width below hard limit
of 10
"""
self._setup(table_type)
lines = self.ts.pformat(max_lines=3, max_width=1, show_unit=True)
assert lines == ['col0 ...',
' ...',
'---- ...',
' 0 ...',
' ... ...',
' 12 ...',
' 15 ...',
'Length = 6 rows']
def test_clip4(self, table_type):
"""Test a range of max_lines"""
self._setup(table_type)
for max_lines in (0, 1, 4, 5, 6, 7, 8, 100, 101, 102, 103, 104, 130):
lines = self.tb.pformat(max_lines=max_lines, show_unit=False)
assert len(lines) == max(8, min(102, max_lines))
def test_pformat_all(self, table_type):
"""Test that all rows are printed by default"""
self._setup(table_type)
lines = self.tb.pformat_all()
# +3 accounts for the three header lines in this table
assert len(lines) == BIG_WIDE_ARR.shape[0] + 3
@pytest.fixture
def test_pprint_all(self, table_type, capsys):
"""Test that all rows are printed by default"""
self._setup(table_type)
self.tb.pprint_all()
(out, err) = capsys.readouterr()
# +3 accounts for the three header lines in this table
assert len(out) == BIG_WIDE_ARR.shape[0] + 3
@pytest.mark.usefixtures('table_type')
class TestFormat():
def test_column_format(self, table_type):
t = table_type([[1, 2], [3, 4]], names=('a', 'b'))
# default (format=None)
assert str(t['a']) == ' a \n---\n 1\n 2'
# just a plain format string
t['a'].format = '5.2f'
assert str(t['a']) == ' a \n-----\n 1.00\n 2.00'
# Old-style that is almost new-style
t['a'].format = '{ %4.2f }'
assert str(t['a']) == ' a \n--------\n{ 1.00 }\n{ 2.00 }'
# New-style that is almost old-style
t['a'].format = '%{0:}'
assert str(t['a']) == ' a \n---\n %1\n %2'
# New-style with extra spaces
t['a'].format = ' {0:05d} '
assert str(t['a']) == ' a \n-------\n 00001 \n 00002 '
# New-style has precedence
t['a'].format = '%4.2f {0:}'
assert str(t['a']) == ' a \n-------\n%4.2f 1\n%4.2f 2'
# Invalid format spec
with pytest.raises(ValueError):
t['a'].format = 'fail'
assert t['a'].format == '%4.2f {0:}' # format did not change
def test_column_format_with_threshold(self, table_type):
from astropy import conf
with conf.set_temp('max_lines', 8):
t = table_type([np.arange(20)], names=['a'])
t['a'].format = '%{0:}'
assert str(t['a']).splitlines() == [' a ',
'---',
' %0',
' %1',
'...',
'%18',
'%19',
'Length = 20 rows']
t['a'].format = '{ %4.2f }'
assert str(t['a']).splitlines() == [' a ',
'---------',
' { 0.00 }',
' { 1.00 }',
' ...',
'{ 18.00 }',
'{ 19.00 }',
'Length = 20 rows']
def test_column_format_func(self, table_type):
# run most of functions twice
# 1) astropy.table.pprint._format_funcs gets populated
# 2) astropy.table.pprint._format_funcs gets used
t = table_type([[1., 2.], [3, 4]], names=('a', 'b'))
# mathematical function
t['a'].format = lambda x: str(x * 3.)
assert str(t['a']) == ' a \n---\n3.0\n6.0'
assert str(t['a']) == ' a \n---\n3.0\n6.0'
def test_column_format_callable(self, table_type):
# run most of functions twice
# 1) astropy.table.pprint._format_funcs gets populated
# 2) astropy.table.pprint._format_funcs gets used
t = table_type([[1., 2.], [3, 4]], names=('a', 'b'))
# mathematical function
class format:
def __call__(self, x):
return str(x * 3.)
t['a'].format = format()
assert str(t['a']) == ' a \n---\n3.0\n6.0'
assert str(t['a']) == ' a \n---\n3.0\n6.0'
def test_column_format_func_wrong_number_args(self, table_type):
t = table_type([[1., 2.], [3, 4]], names=('a', 'b'))
# function that expects wrong number of arguments
def func(a, b):
pass
with pytest.raises(ValueError):
t['a'].format = func
def test_column_format_func_multiD(self, table_type):
arr = [np.array([[1, 2],
[10, 20]])]
t = table_type(arr, names=['a'])
# mathematical function
t['a'].format = lambda x: str(x * 3.)
outstr = ' a [2] \n------------\n 3.0 .. 6.0\n30.0 .. 60.0'
assert str(t['a']) == outstr
assert str(t['a']) == outstr
def test_column_format_func_not_str(self, table_type):
t = table_type([[1., 2.], [3, 4]], names=('a', 'b'))
# mathematical function
with pytest.raises(ValueError):
t['a'].format = lambda x: x * 3
def test_column_alignment(self, table_type):
t = table_type([[1], [2], [3], [4]],
names=('long title a', 'long title b',
'long title c', 'long title d'))
t['long title a'].format = '<'
t['long title b'].format = '^'
t['long title c'].format = '>'
t['long title d'].format = '0='
assert str(t['long title a']) == 'long title a\n------------\n1 '
assert str(t['long title b']) == 'long title b\n------------\n 2 '
assert str(t['long title c']) == 'long title c\n------------\n 3'
assert str(t['long title d']) == 'long title d\n------------\n000000000004'
class TestFormatWithMaskedElements():
def test_column_format(self):
t = Table([[1, 2, 3], [3, 4, 5]], names=('a', 'b'), masked=True)
t['a'].mask = [True, False, True]
# default (format=None)
assert str(t['a']) == ' a \n---\n --\n 2\n --'
# just a plain format string
t['a'].format = '5.2f'
assert str(t['a']) == ' a \n-----\n --\n 2.00\n --'
# Old-style that is almost new-style
t['a'].format = '{ %4.2f }'
assert str(t['a']) == ' a \n--------\n --\n{ 2.00 }\n --'
# New-style that is almost old-style
t['a'].format = '%{0:}'
assert str(t['a']) == ' a \n---\n --\n %2\n --'
# New-style with extra spaces
t['a'].format = ' {0:05d} '
assert str(t['a']) == ' a \n-------\n --\n 00002 \n --'
# New-style has precedence
t['a'].format = '%4.2f {0:}'
assert str(t['a']) == ' a \n-------\n --\n%4.2f 2\n --'
def test_column_format_with_threshold_masked_table(self):
from astropy import conf
with conf.set_temp('max_lines', 8):
t = Table([np.arange(20)], names=['a'], masked=True)
t['a'].format = '%{0:}'
t['a'].mask[0] = True
t['a'].mask[-1] = True
assert str(t['a']).splitlines() == [' a ',
'---',
' --',
' %1',
'...',
'%18',
' --',
'Length = 20 rows']
t['a'].format = '{ %4.2f }'
assert str(t['a']).splitlines() == [' a ',
'---------',
' --',
' { 1.00 }',
' ...',
'{ 18.00 }',
' --',
'Length = 20 rows']
def test_column_format_func(self):
# run most of functions twice
# 1) astropy.table.pprint._format_funcs gets populated
# 2) astropy.table.pprint._format_funcs gets used
t = Table([[1., 2., 3.], [3, 4, 5]], names=('a', 'b'), masked=True)
t['a'].mask = [True, False, True]
# mathematical function
t['a'].format = lambda x: str(x * 3.)
assert str(t['a']) == ' a \n---\n --\n6.0\n --'
assert str(t['a']) == ' a \n---\n --\n6.0\n --'
def test_column_format_func_with_special_masked(self):
# run most of functions twice
# 1) astropy.table.pprint._format_funcs gets populated
# 2) astropy.table.pprint._format_funcs gets used
t = Table([[1., 2., 3.], [3, 4, 5]], names=('a', 'b'), masked=True)
t['a'].mask = [True, False, True]
# mathematical function
def format_func(x):
if x is np.ma.masked:
return '!!'
else:
return str(x * 3.)
t['a'].format = format_func
assert str(t['a']) == ' a \n---\n !!\n6.0\n !!'
assert str(t['a']) == ' a \n---\n !!\n6.0\n !!'
def test_column_format_callable(self):
# run most of functions twice
# 1) astropy.table.pprint._format_funcs gets populated
# 2) astropy.table.pprint._format_funcs gets used
t = Table([[1., 2., 3.], [3, 4, 5]], names=('a', 'b'), masked=True)
t['a'].mask = [True, False, True]
# mathematical function
class format:
def __call__(self, x):
return str(x * 3.)
t['a'].format = format()
assert str(t['a']) == ' a \n---\n --\n6.0\n --'
assert str(t['a']) == ' a \n---\n --\n6.0\n --'
def test_column_format_func_wrong_number_args(self):
t = Table([[1., 2.], [3, 4]], names=('a', 'b'), masked=True)
t['a'].mask = [True, False]
# function that expects wrong number of arguments
def func(a, b):
pass
with pytest.raises(ValueError):
t['a'].format = func
# but if all are masked, it never gets called
t['a'].mask = [True, True]
assert str(t['a']) == ' a \n---\n --\n --'
def test_column_format_func_multiD(self):
arr = [np.array([[1, 2],
[10, 20]])]
t = Table(arr, names=['a'], masked=True)
t['a'].mask[0, 1] = True
t['a'].mask[1, 1] = True
# mathematical function
t['a'].format = lambda x: str(x * 3.)
outstr = ' a [2] \n----------\n 3.0 .. --\n30.0 .. --'
assert str(t['a']) == outstr
assert str(t['a']) == outstr
def test_pprint_npfloat32():
"""
Test for #148, that np.float32 cannot by itself be formatted as float,
but has to be converted to a python float.
"""
dat = np.array([1., 2.], dtype=np.float32)
t = Table([dat], names=['a'])
t['a'].format = '5.2f'
assert str(t['a']) == ' a \n-----\n 1.00\n 2.00'
def test_pprint_py3_bytes():
"""
Test for #1346 and #4944. Make sure a bytestring (dtype=S<N>) in Python 3
is printed correctly (without the "b" prefix like b'string').
"""
val = bytes('val', encoding='utf-8')
blah = 'bläh'.encode('utf-8')
dat = np.array([val, blah], dtype=[('col', 'S10')])
t = table.Table(dat)
assert t['col'].pformat() == ['col ', '----', ' val', 'bläh']
def test_pprint_nameless_col():
"""Regression test for #2213, making sure a nameless column can be printed
using None as the name.
"""
col = table.Column([1., 2.])
assert str(col).startswith('None')
def test_html():
"""Test HTML printing"""
dat = np.array([1., 2.], dtype=np.float32)
t = Table([dat], names=['a'])
lines = t.pformat(html=True)
assert lines == [f'<table id="table{id(t)}">',
'<thead><tr><th>a</th></tr></thead>',
'<tr><td>1.0</td></tr>',
'<tr><td>2.0</td></tr>',
'</table>']
lines = t.pformat(html=True, tableclass='table-striped')
assert lines == [
f'<table id="table{id(t)}" class="table-striped">',
'<thead><tr><th>a</th></tr></thead>',
'<tr><td>1.0</td></tr>',
'<tr><td>2.0</td></tr>',
'</table>']
lines = t.pformat(html=True, tableclass=['table', 'table-striped'])
assert lines == [
f'<table id="table{id(t)}" class="table table-striped">',
'<thead><tr><th>a</th></tr></thead>',
'<tr><td>1.0</td></tr>',
'<tr><td>2.0</td></tr>',
'</table>']
def test_align():
t = simple_table(2, kinds='iS')
assert t.pformat() == [' a b ',
'--- ---',
' 1 b',
' 2 c']
# Use column format attribute
t['a'].format = '<'
assert t.pformat() == [' a b ',
'--- ---',
'1 b',
'2 c']
# Now override column format attribute with various combinations of align
tpf = [' a b ',
'--- ---',
' 1 b ',
' 2 c ']
for align in ('^', ['^', '^'], ('^', '^')):
assert tpf == t.pformat(align=align)
assert t.pformat(align='<') == [' a b ',
'--- ---',
'1 b ',
'2 c ']
assert t.pformat(align='0=') == [' a b ',
'--- ---',
'001 00b',
'002 00c']
assert t.pformat(align=['<', '^']) == [' a b ',
'--- ---',
'1 b ',
'2 c ']
# Now use fill characters. Stress the system using a fill
# character that is the same as an align character.
t = simple_table(2, kinds='iS')
assert t.pformat(align='^^') == [' a b ',
'--- ---',
'^1^ ^b^',
'^2^ ^c^']
assert t.pformat(align='^>') == [' a b ',
'--- ---',
'^^1 ^^b',
'^^2 ^^c']
assert t.pformat(align='^<') == [' a b ',
'--- ---',
'1^^ b^^',
'2^^ c^^']
# Complicated interaction (same as narrative docs example)
t1 = Table([[1.0, 2.0], [1, 2]], names=['column1', 'column2'])
t1['column1'].format = '#^.2f'
assert t1.pformat() == ['column1 column2',
'------- -------',
'##1.00# 1',
'##2.00# 2']
assert t1.pformat(align='!<') == ['column1 column2',
'------- -------',
'1.00!!! 1!!!!!!',
'2.00!!! 2!!!!!!']
assert t1.pformat(align=[None, '!<']) == ['column1 column2',
'------- -------',
'##1.00# 1!!!!!!',
'##2.00# 2!!!!!!']
# Zero fill
t['a'].format = '+d'
assert t.pformat(align='0=') == [' a b ',
'--- ---',
'+01 00b',
'+02 00c']
with pytest.raises(ValueError):
t.pformat(align=['fail'])
with pytest.raises(TypeError):
t.pformat(align=0)
with pytest.raises(TypeError):
t.pprint(align=0)
# Make sure pprint() does not raise an exception
t.pprint()
with pytest.raises(ValueError):
t.pprint(align=['<', '<', '<'])
with pytest.raises(ValueError):
t.pprint(align='x=')
def test_auto_format_func():
"""Test for #5802 (fix for #5800 where format_func key is not unique)"""
t = Table([[1, 2] * u.m])
t['col0'].format = '%f'
t.pformat() # Force caching of format function
qt = QTable(t)
qt.pformat() # Generates exception prior to #5802
def test_decode_replace():
"""
Test printing a bytestring column with a value that fails
decoding to utf-8 and gets replaced by U+FFFD. See
https://docs.python.org/3/library/codecs.html#codecs.replace_errors
"""
t = Table([[b'Z\xf0']])
assert t.pformat() == ['col0', '----', ' Z\ufffd']
class TestColumnsShowHide:
"""Tests of show and hide table columns"""
def setup_method(self):
self.t = simple_table(size=1, cols=4, kinds='i')
@pytest.mark.parametrize('attr', ('pprint_exclude_names', 'pprint_include_names'))
def test_basic(self, attr):
t = self.t
assert repr(getattr(Table, attr)) == f'<PprintIncludeExclude name={attr} default=None>'
t_show_hide = getattr(t, attr)
assert repr(t_show_hide) == f'<PprintIncludeExclude name={attr} value=None>'
# Default value is None
assert t_show_hide() is None
def test_slice(self):
t = self.t
t.pprint_include_names = 'a'
t.pprint_exclude_names = 'b'
t2 = t[0:1]
assert t2.pprint_include_names() == ('a',)
assert t2.pprint_exclude_names() == ('b',)
def test_copy(self):
t = self.t
t.pprint_include_names = 'a'
t.pprint_exclude_names = 'b'
t2 = t.copy()
assert t2.pprint_include_names() == ('a',)
assert t2.pprint_exclude_names() == ('b',)
t2.pprint_include_names = 'c'
t2.pprint_exclude_names = 'd'
assert t.pprint_include_names() == ('a',)
assert t.pprint_exclude_names() == ('b',)
assert t2.pprint_include_names() == ('c',)
assert t2.pprint_exclude_names() == ('d',)
@pytest.mark.parametrize('attr', ('pprint_exclude_names', 'pprint_include_names'))
@pytest.mark.parametrize('value', ('z', ['a', 'z']))
def test_setting(self, attr, value):
t = self.t
t_show_hide = getattr(t, attr)
# Expected attribute value ('z',) or ('a', 'z')
exp = (value,) if isinstance(value, str) else tuple(value)
# Context manager, can include column names that do not exist
with t_show_hide.set(value):
assert t_show_hide() == exp
assert t.meta['__attributes__'] == {attr: exp}
assert t_show_hide() is None
# Setting back to None clears out meta
assert t.meta == {}
# Do `t.pprint_include_names/hide = value`
setattr(t, attr, value)
assert t_show_hide() == exp
# Clear attribute
t_show_hide.set(None)
assert t_show_hide() is None
# Now use set() method
t_show_hide.set(value)
assert t_show_hide() == exp
with t_show_hide.set(None):
assert t_show_hide() is None
assert t.meta == {}
assert t_show_hide() == exp
@pytest.mark.parametrize('attr', ('pprint_exclude_names', 'pprint_include_names'))
@pytest.mark.parametrize('value', ('z', ['a', 'z'], ('a', 'z')))
def test_add_remove(self, attr, value):
t = self.t
t_show_hide = getattr(t, attr)
# Expected attribute value ('z') or ('a', 'z')
exp = (value,) if isinstance(value, str) else tuple(value)
# add() method for str or list of str
t_show_hide.add(value)
assert t_show_hide() == exp
# Adding twice has no effect
t_show_hide.add(value)
assert t_show_hide() == exp
# Remove values (str or list of str). Reverts to None if all names are
# removed.
t_show_hide.remove(value)
assert t_show_hide() is None
# Remove just one name, possibly leaving a name.
t_show_hide.add(value)
t_show_hide.remove('z')
assert t_show_hide() == (None if value == 'z' else ('a',))
# Cannot remove name not in the list
t_show_hide.set(['a', 'z'])
with pytest.raises(ValueError, match=f'x not in {attr}'):
t_show_hide.remove(('x', 'z'))
@pytest.mark.parametrize('attr', ('pprint_exclude_names', 'pprint_include_names'))
def test_rename(self, attr):
t = self.t
t_hide_show = getattr(t, attr)
t_hide_show.set(['a', 'b'])
t.rename_column('a', 'aa')
assert t_hide_show() == ('aa', 'b')
@pytest.mark.parametrize('attr', ('pprint_exclude_names', 'pprint_include_names'))
def test_remove(self, attr):
t = self.t
t_hide_show = getattr(t, attr)
t_hide_show.set(['a', 'b'])
del t['a']
assert t_hide_show() == ('b',)
def test_serialization(self):
# Serialization works for ECSV. Currently fails for FITS, works with
# HDF5.
t = self.t
t.pprint_exclude_names = ['a', 'y']
t.pprint_include_names = ['b', 'z']
out = StringIO()
ascii.write(t, out, format='ecsv')
t2 = ascii.read(out.getvalue(), format='ecsv')
assert t2.pprint_exclude_names() == ('a', 'y')
assert t2.pprint_include_names() == ('b', 'z')
def test_output(self):
"""Test that pprint_include/exclude_names actually changes the print output"""
t = self.t
exp = [' b d ',
'--- ---',
' 2 4']
with t.pprint_exclude_names.set(['a', 'c']):
out = t.pformat_all()
assert out == exp
with t.pprint_include_names.set(['b', 'd']):
out = t.pformat_all()
assert out == exp
with t.pprint_exclude_names.set(['a', 'c']):
out = t.pformat_all()
assert out == exp
with t.pprint_include_names.set(['b', 'd']):
out = t.pformat_all()
assert out == exp
# Mixture (not common in practice but possible). Note, the trailing
# backslash instead of parens is needed for Python < 3.9. See:
# https://bugs.python.org/issue12782.
with t.pprint_include_names.set(['b', 'c', 'd']), \
t.pprint_exclude_names.set(['c']):
out = t.pformat_all()
assert out == exp
def test_output_globs(self):
"""Test that pprint_include/exclude_names works with globs (fnmatch)"""
t = self.t
t['a2'] = 1
t['a23'] = 2
# Show only the a* columns
exp = [' a a2 a23',
'--- --- ---',
' 1 1 2']
with t.pprint_include_names.set('a*'):
out = t.pformat_all()
assert out == exp
# Show a* but exclude a??
exp = [' a a2',
'--- ---',
' 1 1']
with t.pprint_include_names.set('a*'), t.pprint_exclude_names.set('a??'):
out = t.pformat_all()
assert out == exp
# Exclude a??
exp = [' a b c d a2',
'--- --- --- --- ---',
' 1 2 3 4 1']
with t.pprint_exclude_names.set('a??'):
out = t.pformat_all()
assert out == exp
def test_embedded_newline_tab():
"""Newlines and tabs are escaped in table repr"""
t = Table(rows=[['a', 'b \n c \t \n d'], ['x', 'y\n']])
exp = [
r'col0 col1 ',
r'---- --------------',
r' a b \n c \t \n d',
r' x y\n']
assert t.pformat_all() == exp
|
78a7645fdca679f77212e4057ec6c029b9b6017d05e9498790cce9cbeaa386f6 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from astropy.table.bst import BST
def get_tree(TreeType):
b = TreeType([], [])
for val in [5, 2, 9, 3, 4, 1, 6, 10, 8, 7]:
b.add(val)
return b
@pytest.fixture
def tree():
return get_tree(BST)
r'''
5
/ \
2 9
/ \ / \
1 3 6 10
\ \
4 8
/
7
'''
@pytest.fixture
def bst(tree):
return tree
def test_bst_add(bst):
root = bst.root
assert root.data == [5]
assert root.left.data == [2]
assert root.right.data == [9]
assert root.left.left.data == [1]
assert root.left.right.data == [3]
assert root.right.left.data == [6]
assert root.right.right.data == [10]
assert root.left.right.right.data == [4]
assert root.right.left.right.data == [8]
assert root.right.left.right.left.data == [7]
def test_bst_dimensions(bst):
assert bst.size == 10
assert bst.height == 4
def test_bst_find(tree):
bst = tree
for i in range(1, 11):
node = bst.find(i)
assert node == [i]
assert bst.find(0) == []
assert bst.find(11) == []
assert bst.find('1') == []
def test_bst_traverse(bst):
preord = [5, 2, 1, 3, 4, 9, 6, 8, 7, 10]
inord = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
postord = [1, 4, 3, 2, 7, 8, 6, 10, 9, 5]
traversals = {}
for order in ('preorder', 'inorder', 'postorder'):
traversals[order] = [x.key for x in bst.traverse(order)]
assert traversals['preorder'] == preord
assert traversals['inorder'] == inord
assert traversals['postorder'] == postord
def test_bst_remove(bst):
order = (6, 9, 1, 3, 7, 2, 10, 5, 4, 8)
vals = set(range(1, 11))
for i, val in enumerate(order):
assert bst.remove(val) is True
assert bst.is_valid()
assert set([x.key for x in bst.traverse('inorder')]) == \
vals.difference(order[:i + 1])
assert bst.size == 10 - i - 1
assert bst.remove(-val) is False
def test_bst_duplicate(bst):
bst.add(10, 11)
assert bst.find(10) == [10, 11]
assert bst.remove(10, data=10) is True
assert bst.find(10) == [11]
with pytest.raises(ValueError):
bst.remove(10, data=30) # invalid data
assert bst.remove(10) is True
assert bst.remove(10) is False
def test_bst_range(tree):
bst = tree
lst = bst.range_nodes(4, 8)
assert sorted(x.key for x in lst) == [4, 5, 6, 7, 8]
lst = bst.range_nodes(10, 11)
assert [x.key for x in lst] == [10]
lst = bst.range_nodes(11, 20)
assert len(lst) == 0
|
1dda95479473a5dd293203e776da4ec36c5897559bd7552c0b29447c1616d29d | from copy import copy
from unittest.mock import MagicMock
import pytest
import numpy as np
from numpy.testing import assert_equal
from astropy.table import Table
from astropy.table.table_helpers import ArrayWrapper
from astropy.table.mixins.registry import (_handlers, register_mixin_handler,
MixinRegistryError, get_mixin_handler)
ORIGINAL = {}
def setup_function(function):
ORIGINAL['handlers'] = copy(_handlers)
_handlers.clear()
def teardown_function(function):
_handlers.clear()
_handlers.update(ORIGINAL['handlers'])
class SpamData:
pass
class SpamWrapper(ArrayWrapper):
def __init__(self):
super().__init__([0, 1, 3, 4, 5])
FULL_QUALNAME = 'astropy.table.mixins.tests.test_registry.SpamData'
def handle_spam(obj):
return SpamWrapper()
def handle_spam_alt(obj):
return SpamWrapper()
def test_no_handler():
data = SpamData()
assert get_mixin_handler(data) is None
def test_register_handler():
register_mixin_handler(FULL_QUALNAME, handle_spam)
assert get_mixin_handler(SpamData()) is handle_spam
def test_register_handler_override():
register_mixin_handler(FULL_QUALNAME, handle_spam)
with pytest.raises(MixinRegistryError) as exc:
register_mixin_handler(FULL_QUALNAME, handle_spam_alt)
assert exc.value.args[0] == 'Handler for class astropy.table.mixins.tests.test_registry.SpamData is already defined'
register_mixin_handler(FULL_QUALNAME, handle_spam_alt, force=True)
assert get_mixin_handler(SpamData()) is handle_spam_alt
def test_get_mixin_handler_str():
# Check that we can also pass a fully qualified name to get_mixin_handler
register_mixin_handler(FULL_QUALNAME, handle_spam)
assert get_mixin_handler(FULL_QUALNAME) is handle_spam
def test_add_column():
t = Table()
with pytest.raises(TypeError):
t['a'] = SpamData()
register_mixin_handler(FULL_QUALNAME, handle_spam)
t['a'] = SpamData()
assert len(t) == 5
assert isinstance(t['a'], SpamWrapper)
assert_equal(t['a'].data, [0, 1, 3, 4, 5])
def invalid_handler(obj):
return 'invalid'
def test_invalid_handler():
t = Table()
register_mixin_handler(FULL_QUALNAME, invalid_handler)
with pytest.raises(TypeError) as exc:
t['a'] = SpamData()
assert exc.value.args[0] == (f'Mixin handler for object of type {FULL_QUALNAME} '
f'did not return a valid mixin column')
|
188cc03c7713dce758d1fd1152392baaf7b16fcab78833b8cfb7fe577f9ee9ef | import pytest
import numpy as np
from numpy.testing import assert_equal
from astropy.table import Table
da = pytest.importorskip('dask.array')
class TestDaskHandler:
def setup_method(self, method):
self.t = Table()
self.t['a'] = da.arange(10)
def test_add_row(self):
self.t.add_row(self.t[0])
assert_equal(self.t['a'].compute(), np.hstack([np.arange(10), 0]))
def test_get_column(self):
assert isinstance(self.t['a'], da.Array)
assert_equal(self.t['a'].compute(), np.arange(10))
def test_slicing_row_single(self):
sub = self.t[5]
assert isinstance(sub['a'], da.Array)
assert not hasattr(sub['a'], 'info') # should be a plain dask array
assert sub['a'].compute() == 5
def test_slicing_row_range(self):
sub = self.t[5:]
assert isinstance(sub['a'], da.Array)
assert hasattr(sub['a'], 'info') # should be a mixin column
assert_equal(sub['a'].compute(), np.arange(5, 10))
def test_slicing_column_range(self):
sub = self.t[('a',)]
assert isinstance(sub['a'], da.Array)
assert hasattr(sub['a'], 'info') # should be a mixin column
assert_equal(sub['a'].compute(), np.arange(10))
def test_pformat(self):
assert self.t.pformat_all() == [' a ', '---', ' 0', ' 1', ' 2',
' 3', ' 4', ' 5', ' 6', ' 7',
' 8', ' 9']
def test_info_preserved(self):
self.t['a'].info.description = 'A dask column'
sub = self.t[1:3]
assert sub['a'].info.name == 'a'
assert sub['a'].info.description == 'A dask column'
col = self.t['a'].copy()
assert col.info.name == 'a'
assert col.info.description == 'A dask column'
self.t.add_row(self.t[0])
assert self.t['a'].info.name == 'a'
assert self.t['a'].info.description == 'A dask column'
|
40fb09dc07340f84460bc091ade1e6d3902dc71530444ab87cb61c8fae347168 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import itertools
from contextlib import nullcontext
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_almost_equal_nulp, assert_array_equal
from astropy import units as u
from astropy.convolution.convolve import convolve, convolve_fft
from astropy.utils.exceptions import AstropyUserWarning
VALID_DTYPES = ('>f4', '<f4', '>f8', '<f8')
VALID_DTYPE_MATRIX = list(itertools.product(VALID_DTYPES, VALID_DTYPES))
BOUNDARY_OPTIONS = [None, 'fill', 'wrap']
NANTREATMENT_OPTIONS = ('interpolate', 'fill')
NORMALIZE_OPTIONS = [True, False]
PRESERVE_NAN_OPTIONS = [True, False]
"""
What does convolution mean? We use the 'same size' assumption here (i.e.,
you expect an array of the exact same size as the one you put in)
Convolving any array with a kernel that is [1] should result in the same array returned
Working example array: [1, 2, 3, 4, 5]
Convolved with [1] = [1, 2, 3, 4, 5]
Convolved with [1, 1] = [1, 3, 5, 7, 9] THIS IS NOT CONSISTENT!
Convolved with [1, 0] = [1, 2, 3, 4, 5]
Convolved with [0, 1] = [0, 1, 2, 3, 4]
"""
# NOTE: use_numpy_fft is redundant if you don't have FFTW installed
option_names = ('boundary', 'nan_treatment', 'normalize_kernel', 'dealias')
options = list(itertools.product(BOUNDARY_OPTIONS,
NANTREATMENT_OPTIONS,
(True, False),
(True, False)
))
option_names_preserve_nan = ('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan')
options_preserve_nan = list(itertools.product(BOUNDARY_OPTIONS,
NANTREATMENT_OPTIONS,
(True, False),
(True, False)))
def expected_boundary_warning(boundary=None):
# Helper that returns the appropriate context manager for the boundary=None
# warning depending on the value of boundary.
if boundary is None:
ctx = pytest.warns(AstropyUserWarning,
match='The convolve_fft version of boundary=None '
'is equivalent to the convolve boundary=\'fill\'')
else:
ctx = nullcontext()
return ctx
def expected_dealias_error(boundary=None, dealias=False):
# Helper that returns the appropriate context manager for the boundary=None
# warning depending on the value of boundary.
if dealias and boundary == 'wrap':
ctx = pytest.raises(ValueError)
else:
ctx = nullcontext()
return ctx
def assert_floatclose(x, y):
"""Assert arrays are close to within expected floating point rounding.
Check that the result is correct at the precision expected for 64 bit
numbers, taking account that the tolerance has to reflect that all powers
in the FFTs enter our values.
"""
# The number used is set by the fact that the Windows FFT sometimes
# returns an answer that is EXACTLY 10*np.spacing.
assert_allclose(x, y, atol=10*np.spacing(x.max()), rtol=0.)
class TestConvolve1D:
@pytest.mark.parametrize(option_names, options)
def test_quantity(self, boundary, nan_treatment, normalize_kernel, dealias):
"""
Test that convolve_fft works correctly when input array is a Quantity
"""
x = np.array([1., 4., 5., 6., 5., 7., 8.], dtype='float64') * u.ph
y = np.array([0.2, 0.6, 0.2], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
dealias=dealias)
assert x.unit == z.unit
@pytest.mark.parametrize(option_names, options)
def test_unity_1_none(self, boundary, nan_treatment, normalize_kernel, dealias):
'''
Test that a unit kernel with a single element returns the same array
'''
x = np.array([1., 2., 3.], dtype='float64')
y = np.array([1.], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
dealias=dealias)
assert_floatclose(z, x)
@pytest.mark.parametrize(option_names, options)
def test_unity_3(self, boundary, nan_treatment, normalize_kernel, dealias):
'''
Test that a unit kernel with three elements returns the same array
(except when boundary is None).
'''
x = np.array([1., 2., 3.], dtype='float64')
y = np.array([0., 1., 0.], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
dealias=dealias)
assert_floatclose(z, x)
@pytest.mark.parametrize(option_names, options)
def test_uniform_3(self, boundary, nan_treatment, normalize_kernel, dealias):
'''
Test that the different modes are producing the correct results using
a uniform kernel with three elements
'''
x = np.array([1., 0., 3.], dtype='float64')
y = np.array([1., 1., 1.], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
dealias=dealias)
answer_key = (boundary, nan_treatment, normalize_kernel)
answer_dict = {
'sum_fill_zeros': np.array([1., 4., 3.], dtype='float64'),
'average_fill_zeros': np.array([1 / 3., 4 / 3., 1.], dtype='float64'),
'sum_wrap': np.array([4., 4., 4.], dtype='float64'),
'average_wrap': np.array([4 / 3., 4 / 3., 4 / 3.], dtype='float64'),
}
result_dict = {
# boundary, nan_treatment, normalize_kernel
('fill', 'interpolate', True): answer_dict['average_fill_zeros'],
('wrap', 'interpolate', True): answer_dict['average_wrap'],
('fill', 'interpolate', False): answer_dict['sum_fill_zeros'],
('wrap', 'interpolate', False): answer_dict['sum_wrap'],
}
for k in list(result_dict.keys()):
result_dict[(k[0], 'fill', k[2])] = result_dict[k]
for k in list(result_dict.keys()):
if k[0] == 'fill':
result_dict[(None, k[1], k[2])] = result_dict[k]
assert_floatclose(z, result_dict[answer_key])
@pytest.mark.parametrize(option_names, options)
def test_halfity_3(self, boundary, nan_treatment, normalize_kernel, dealias):
'''
Test that the different modes are producing the correct results using
a uniform, non-unity kernel with three elements
'''
x = np.array([1., 0., 3.], dtype='float64')
y = np.array([0.5, 0.5, 0.5], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
dealias=dealias)
answer_dict = {
'sum': np.array([0.5, 2.0, 1.5], dtype='float64'),
'sum_zeros': np.array([0.5, 2., 1.5], dtype='float64'),
'sum_nozeros': np.array([0.5, 2., 1.5], dtype='float64'),
'average': np.array([1 / 3., 4 / 3., 1.], dtype='float64'),
'sum_wrap': np.array([2., 2., 2.], dtype='float64'),
'average_wrap': np.array([4 / 3., 4 / 3., 4 / 3.], dtype='float64'),
'average_zeros': np.array([1 / 3., 4 / 3., 1.], dtype='float64'),
'average_nozeros': np.array([0.5, 4 / 3., 1.5], dtype='float64'),
}
if normalize_kernel:
answer_key = 'average'
else:
answer_key = 'sum'
if boundary == 'wrap':
answer_key += '_wrap'
else:
# average = average_zeros; sum = sum_zeros
answer_key += '_zeros'
assert_floatclose(z, answer_dict[answer_key])
@pytest.mark.parametrize(option_names_preserve_nan, options_preserve_nan)
def test_unity_3_withnan(self, boundary, nan_treatment, normalize_kernel,
preserve_nan):
'''
Test that a unit kernel with three elements returns the same array
(except when boundary is None). This version includes a NaN value in
the original array.
'''
x = np.array([1., np.nan, 3.], dtype='float64')
y = np.array([0., 1., 0.], dtype='float64')
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[1])
z = np.nan_to_num(z)
assert_floatclose(z, [1., 0., 3.])
inputs = (np.array([1., np.nan, 3.], dtype='float64'),
np.array([1., np.inf, 3.], dtype='float64'))
outputs = (np.array([1., 0., 3.], dtype='float64'),
np.array([1., 0., 3.], dtype='float64'))
options_unity1withnan = list(itertools.product(BOUNDARY_OPTIONS,
NANTREATMENT_OPTIONS,
(True, False),
(True, False),
inputs, outputs))
@pytest.mark.parametrize(option_names_preserve_nan + ('inval', 'outval'),
options_unity1withnan)
def test_unity_1_withnan(self, boundary, nan_treatment, normalize_kernel,
preserve_nan, inval, outval):
'''
Test that a unit kernel with three elements returns the same array
(except when boundary is None). This version includes a NaN value in
the original array.
'''
x = inval
y = np.array([1.], dtype='float64')
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[1])
z = np.nan_to_num(z)
assert_floatclose(z, outval)
@pytest.mark.parametrize(option_names_preserve_nan, options_preserve_nan)
def test_uniform_3_withnan(self, boundary, nan_treatment,
normalize_kernel, preserve_nan):
'''
Test that the different modes are producing the correct results using
a uniform kernel with three elements. This version includes a NaN
value in the original array.
'''
x = np.array([1., np.nan, 3.], dtype='float64')
y = np.array([1., 1., 1.], dtype='float64')
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[1])
answer_dict = {
'sum': np.array([1., 4., 3.], dtype='float64'),
'sum_nozeros': np.array([1., 4., 3.], dtype='float64'),
'sum_zeros': np.array([1., 4., 3.], dtype='float64'),
'sum_nozeros_interpnan': np.array([1., 4., 3.], dtype='float64'),
'average': np.array([1., 2., 3.], dtype='float64'),
'sum_wrap': np.array([4., 4., 4.], dtype='float64'),
'average_wrap': np.array([4/3., 4/3., 4/3.], dtype='float64'),
'average_wrap_interpnan': np.array([2, 2, 2], dtype='float64'),
'average_nozeros': np.array([1/2., 4/3., 3/2.], dtype='float64'),
'average_nozeros_interpnan': np.array([1., 2., 3.], dtype='float64'),
'average_zeros': np.array([1 / 3., 4 / 3., 3 / 3.], dtype='float64'),
'average_zeros_interpnan': np.array([1 / 2., 4 / 2., 3 / 2.], dtype='float64'),
}
for key in list(answer_dict.keys()):
if 'sum' in key:
answer_dict[key+"_interpnan"] = answer_dict[key] * 3./2.
if normalize_kernel:
answer_key = 'average'
else:
answer_key = 'sum'
if boundary == 'wrap':
answer_key += '_wrap'
else:
# average = average_zeros; sum = sum_zeros
answer_key += '_zeros'
if nan_treatment == 'interpolate':
answer_key += '_interpnan'
posns = np.isfinite(z)
answer = answer_dict[answer_key][posns]
# check that fill is set and that the 1'th position that was originally
# NaN is included in the check
if (nan_treatment == 'fill') and posns[1]:
# we fill the center with the sum of the input array divided by
# three, since we've now pre-filled the center value with zero
answer[1] = 4 / (3. if normalize_kernel else 1.)
assert_floatclose(z[posns], answer)
def test_nan_interpolate(self):
# Test masked array
array = np.array([1., np.nan, 3.], dtype='float64')
kernel = np.array([1, 1, 1])
masked_array = np.ma.masked_array(array, mask=[0, 1, 0])
result = convolve_fft(masked_array, kernel, boundary='fill',
nan_treatment='interpolate',
fill_value=np.nan)
assert_floatclose(result, [1, 2, 3])
def test_nan_fill(self):
# regression for #8121
# Test masked array
array = np.array([1., np.nan, 3.], dtype='float64')
kernel = np.array([1, 1, 1])
result = convolve_fft(array, kernel, boundary='fill',
nan_treatment='fill',
fill_value=0)
# note that, because fill_value also affects boundary='fill', the edge
# pixels are treated as zero rather than being ignored.
assert_floatclose(result, [1/3., 4/3., 1.])
def test_nan_fill_two(self):
# regression for #8121
# Test masked array
array = np.array([1., np.nan, 3.], dtype='float64')
kernel = np.array([1, 1, 1])
result = convolve_fft(array, kernel, boundary='fill',
nan_treatment='fill',
fill_value=1)
# note that, because fill_value also affects boundary='fill', the edge
# pixels are treated as fill_value=1 rather than being ignored.
assert_floatclose(result, [1., 5/3., 5/3.])
def test_masked_array(self):
"""
Check whether convolve_fft works with masked arrays.
"""
# Test masked array
array = np.array([1., 2., 3.], dtype='float64')
kernel = np.array([1, 1, 1])
masked_array = np.ma.masked_array(array, mask=[0, 1, 0])
result = convolve_fft(masked_array, kernel, boundary='fill',
fill_value=0.)
assert_floatclose(result, [1./2, 2, 3./2])
# Now test against convolve()
convolve_result = convolve(masked_array, kernel, boundary='fill',
fill_value=0.)
assert_floatclose(convolve_result, result)
# Test masked kernel
array = np.array([1., 2., 3.], dtype='float64')
kernel = np.array([1, 1, 1])
masked_kernel = np.ma.masked_array(kernel, mask=[0, 1, 0])
result = convolve_fft(array, masked_kernel, boundary='fill',
fill_value=0.)
assert_floatclose(result, [1, 2, 1])
# Now test against convolve()
convolve_result = convolve(array, masked_kernel, boundary='fill',
fill_value=0.)
assert_floatclose(convolve_result, result)
def test_normalize_function(self):
"""
Check if convolve_fft works when passing a normalize function.
"""
array = [1, 2, 3]
kernel = [3, 3, 3]
result = convolve_fft(array, kernel, normalize_kernel=np.max)
assert_floatclose(result, [3, 6, 5])
@pytest.mark.parametrize(option_names, options)
def test_normalization_is_respected(self, boundary,
nan_treatment,
normalize_kernel,
dealias):
"""
Check that if normalize_kernel is False then the normalization
tolerance is respected.
"""
array = np.array([1, 2, 3])
# A simple identity kernel to which a non-zero normalization is added.
base_kernel = np.array([1.0])
# Use the same normalization error tolerance in all cases.
normalization_rtol = 1e-4
# Add the error below to the kernel.
norm_error = [normalization_rtol / 10, normalization_rtol * 10]
for err in norm_error:
kernel = base_kernel + err
result = convolve_fft(array, kernel,
normalize_kernel=normalize_kernel,
nan_treatment=nan_treatment,
normalization_zero_tol=normalization_rtol)
if normalize_kernel:
# Kernel has been normalized to 1.
assert_floatclose(result, array)
else:
# Kernel should not have been normalized...
assert_floatclose(result, array * kernel)
class TestConvolve2D:
@pytest.mark.parametrize(option_names, options)
def test_unity_1x1_none(self, boundary, nan_treatment, normalize_kernel, dealias):
'''
Test that a 1x1 unit kernel returns the same array
'''
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype='float64')
y = np.array([[1.]], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
dealias=dealias)
assert_floatclose(z, x)
@pytest.mark.parametrize(option_names, options)
def test_unity_3x3(self, boundary, nan_treatment, normalize_kernel, dealias):
'''
Test that a 3x3 unit kernel returns the same array (except when
boundary is None).
'''
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype='float64')
y = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
dealias=dealias)
assert_floatclose(z, x)
@pytest.mark.parametrize(option_names, options)
def test_uniform_3x3(self, boundary, nan_treatment, normalize_kernel, dealias):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel.
'''
x = np.array([[0., 0., 3.],
[1., 0., 0.],
[0., 2., 0.]], dtype='float64')
y = np.array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype='float64')
with expected_boundary_warning(boundary=boundary):
with expected_dealias_error(boundary=boundary, dealias=dealias):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
fill_value=np.nan if normalize_kernel else 0,
normalize_kernel=normalize_kernel,
dealias=dealias)
w = np.array([[4., 6., 4.],
[6., 9., 6.],
[4., 6., 4.]], dtype='float64')
answer_dict = {
'sum': np.array([[1., 4., 3.],
[3., 6., 5.],
[3., 3., 2.]], dtype='float64'),
'sum_wrap': np.array([[6., 6., 6.],
[6., 6., 6.],
[6., 6., 6.]], dtype='float64'),
}
answer_dict['average'] = answer_dict['sum'] / w
answer_dict['average_wrap'] = answer_dict['sum_wrap'] / 9.
answer_dict['average_withzeros'] = answer_dict['sum'] / 9.
answer_dict['sum_withzeros'] = answer_dict['sum']
if normalize_kernel:
answer_key = 'average'
else:
answer_key = 'sum'
if boundary == 'wrap':
answer_key += '_wrap'
elif nan_treatment == 'fill':
answer_key += '_withzeros'
a = answer_dict[answer_key]
assert_floatclose(z, a)
@pytest.mark.parametrize(option_names_preserve_nan, options_preserve_nan)
def test_unity_3x3_withnan(self, boundary, nan_treatment,
normalize_kernel, preserve_nan):
'''
Test that a 3x3 unit kernel returns the same array (except when
boundary is None). This version includes a NaN value in the original
array.
'''
x = np.array([[1., 2., 3.],
[4., np.nan, 6.],
[7., 8., 9.]], dtype='float64')
y = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype='float64')
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[1, 1])
z = np.nan_to_num(z)
x = np.nan_to_num(x)
assert_floatclose(z, x)
@pytest.mark.parametrize(option_names_preserve_nan, options_preserve_nan)
def test_uniform_3x3_withnan(self, boundary, nan_treatment,
normalize_kernel, preserve_nan):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel. This version includes a NaN value in the
original array.
'''
x = np.array([[0., 0., 3.],
[1., np.nan, 0.],
[0., 2., 0.]], dtype='float64')
y = np.array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype='float64')
# commented out: allow unnormalized nan-ignoring convolution
# # kernel is not normalized, so this situation -> exception
# if nan_treatment and not normalize_kernel:
# with pytest.raises(ValueError):
# z = convolve_fft(x, y, boundary=boundary,
# nan_treatment=nan_treatment,
# normalize_kernel=normalize_kernel,
# ignore_edge_zeros=ignore_edge_zeros,
# )
# return
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary,
nan_treatment=nan_treatment,
# you cannot fill w/nan, you can only interpolate over it
fill_value=np.nan if normalize_kernel and nan_treatment=='interpolate' else 0,
normalize_kernel=normalize_kernel,
preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[1, 1])
# weights
w_n = np.array([[3., 5., 3.],
[5., 8., 5.],
[3., 5., 3.]], dtype='float64')
w_z = np.array([[4., 6., 4.],
[6., 9., 6.],
[4., 6., 4.]], dtype='float64')
answer_dict = {
'sum': np.array([[1., 4., 3.],
[3., 6., 5.],
[3., 3., 2.]], dtype='float64'),
'sum_wrap': np.array([[6., 6., 6.],
[6., 6., 6.],
[6., 6., 6.]], dtype='float64'),
}
answer_dict['average'] = answer_dict['sum'] / w_z
answer_dict['average_interpnan'] = answer_dict['sum'] / w_n
answer_dict['average_wrap_interpnan'] = answer_dict['sum_wrap'] / 8.
answer_dict['average_wrap'] = answer_dict['sum_wrap'] / 9.
answer_dict['average_withzeros'] = answer_dict['sum'] / 9.
answer_dict['average_withzeros_interpnan'] = answer_dict['sum'] / 8.
answer_dict['sum_withzeros'] = answer_dict['sum']
answer_dict['sum_interpnan'] = answer_dict['sum'] * 9/8.
answer_dict['sum_withzeros_interpnan'] = answer_dict['sum']
answer_dict['sum_wrap_interpnan'] = answer_dict['sum_wrap'] * 9/8.
if normalize_kernel:
answer_key = 'average'
else:
answer_key = 'sum'
if boundary == 'wrap':
answer_key += '_wrap'
elif nan_treatment == 'fill':
answer_key += '_withzeros'
if nan_treatment == 'interpolate':
answer_key += '_interpnan'
answer_dict[answer_key]
# Skip the NaN at [1, 1] when preserve_nan=True
posns = np.where(np.isfinite(z))
# for reasons unknown, the Windows FFT returns an answer for the [0, 0]
# component that is EXACTLY 10*np.spacing
assert_floatclose(z[posns], z[posns])
def test_big_fail(self):
""" Test that convolve_fft raises an exception if a too-large array is passed in."""
with pytest.raises((ValueError, MemoryError)):
# while a good idea, this approach did not work; it actually writes to disk
# arr = np.memmap('file.np', mode='w+', shape=(512, 512, 512), dtype=complex)
# this just allocates the memory but never touches it; it's better:
arr = np.empty([512, 512, 512], dtype=complex)
# note 512**3 * 16 bytes = 2.0 GB
convolve_fft(arr, arr)
def test_padding(self):
"""
Test that convolve_fft pads to _next_fast_lengths and does not expand all dimensions
to length of longest side (#11242/#10047).
"""
# old implementation expanded this to up to 2048**3
shape = (1, 1226, 518)
img = np.zeros(shape, dtype='float64')
img[0, 600:610, 300:304] = 1.0
kernel = np.zeros((1, 7, 7), dtype='float64')
kernel[0, 3, 3] = 1.0
with pytest.warns(AstropyUserWarning,
match="psf_pad was set to False, which overrides the boundary='fill'"):
img_fft = convolve_fft(img, kernel, return_fft=True, psf_pad=False, fft_pad=False)
assert_array_equal(img_fft.shape, shape)
img_fft = convolve_fft(img, kernel, return_fft=True, psf_pad=False, fft_pad=True)
# should be from either hardcoded _good_sizes[] or scipy.fft.next_fast_len()
assert img_fft.shape in ((1, 1250, 540), (1, 1232, 525))
img_fft = convolve_fft(img, kernel, return_fft=True, psf_pad=True, fft_pad=False)
assert_array_equal(img_fft.shape, np.array(shape) + np.array(kernel.shape))
img_fft = convolve_fft(img, kernel, return_fft=True, psf_pad=True, fft_pad=True)
assert img_fft.shape in ((2, 1250, 540), (2, 1250, 525))
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_non_normalized_kernel(self, boundary):
x = np.array([[0., 0., 4.],
[1., 2., 0.],
[0., 3., 0.]], dtype='float')
y = np.array([[1., -1., 1.],
[-1., 0., -1.],
[1., -1., 1.]], dtype='float')
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary, nan_treatment='fill',
normalize_kernel=False)
if boundary in (None, 'fill'):
assert_floatclose(z, np.array([[1., -5., 2.],
[1., 0., -3.],
[-2., -1., -1.]], dtype='float'))
elif boundary == 'wrap':
assert_floatclose(z, np.array([[0., -8., 6.],
[5., 0., -4.],
[2., 3., -4.]], dtype='float'))
else:
raise ValueError("Invalid boundary specification")
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_asymmetric_kernel(boundary):
'''
Make sure that asymmetric convolution
functions go the right direction
'''
x = np.array([3., 0., 1.], dtype='>f8')
y = np.array([1, 2, 3], dtype='>f8')
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary, normalize_kernel=False)
if boundary in (None, 'fill'):
assert_array_almost_equal_nulp(z, np.array([6., 10., 2.], dtype='float'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([9., 10., 5.], dtype='float'), 10)
@pytest.mark.parametrize(('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan', 'dtype'),
itertools.product(BOUNDARY_OPTIONS,
NANTREATMENT_OPTIONS,
NORMALIZE_OPTIONS,
PRESERVE_NAN_OPTIONS,
VALID_DTYPES))
def test_input_unmodified(boundary, nan_treatment,
normalize_kernel, preserve_nan, dtype):
"""
Test that convolve_fft works correctly when inputs are lists
"""
array = [1., 4., 5., 6., 5., 7., 8.]
kernel = [0.2, 0.6, 0.2]
x = np.array(array, dtype=dtype)
y = np.array(kernel, dtype=dtype)
# Make pseudoimmutable
x.flags.writeable = False
y.flags.writeable = False
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary, nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel, preserve_nan=preserve_nan)
assert np.all(np.array(array, dtype=dtype) == x)
assert np.all(np.array(kernel, dtype=dtype) == y)
@pytest.mark.parametrize(('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan', 'dtype'),
itertools.product(BOUNDARY_OPTIONS,
NANTREATMENT_OPTIONS,
NORMALIZE_OPTIONS,
PRESERVE_NAN_OPTIONS,
VALID_DTYPES))
def test_input_unmodified_with_nan(boundary, nan_treatment,
normalize_kernel, preserve_nan, dtype):
"""
Test that convolve_fft doesn't modify the input data
"""
array = [1., 4., 5., np.nan, 5., 7., 8.]
kernel = [0.2, 0.6, 0.2]
x = np.array(array, dtype=dtype)
y = np.array(kernel, dtype=dtype)
# Make pseudoimmutable
x.flags.writeable = False
y.flags.writeable = False
# make copies for post call comparison
x_copy = x.copy()
y_copy = y.copy()
with expected_boundary_warning(boundary=boundary):
z = convolve_fft(x, y, boundary=boundary, nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel, preserve_nan=preserve_nan)
# ( NaN == NaN ) = False
# Only compare non NaN values for canonical equivalence
# and then check NaN explicitly with np.isnan()
array_is_nan = np.isnan(array)
kernel_is_nan = np.isnan(kernel)
array_not_nan = ~array_is_nan
kernel_not_nan = ~kernel_is_nan
assert np.all(x_copy[array_not_nan] == x[array_not_nan])
assert np.all(y_copy[kernel_not_nan] == y[kernel_not_nan])
assert np.all(np.isnan(x[array_is_nan]))
assert np.all(np.isnan(y[kernel_is_nan]))
@pytest.mark.parametrize('error_kwarg', [{'psf_pad': True}, {'fft_pad': True}, {'dealias': True}])
def test_convolve_fft_boundary_wrap_error(error_kwarg):
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype='>f8')
y = np.array([[1.]], dtype='>f8')
assert (convolve_fft(x, y, boundary='wrap') == x).all()
with pytest.raises(ValueError) as err:
convolve_fft(x, y, boundary='wrap', **error_kwarg)
assert str(err.value) == \
f"With boundary='wrap', {list(error_kwarg.keys())[0]} cannot be enabled."
def test_convolve_fft_boundary_extend_error():
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype='>f8')
y = np.array([[1.]], dtype='>f8')
with pytest.raises(NotImplementedError) as err:
convolve_fft(x, y, boundary='extend')
assert str(err.value) == \
"The 'extend' option is not implemented for fft-based convolution"
|
08fe0510cca566e2742e382d50aabc30e7b6aeed264f9f6ae9501f656e0211dc | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from astropy import convolution as conv
from astropy.tests.helper import check_pickling_recovery, pickle_protocol # noqa
@pytest.mark.parametrize(("name", "args", "kwargs", "xfail"),
[(conv.CustomKernel, [],
{'array': np.random.rand(15)},
False),
(conv.Gaussian1DKernel, [1.0],
{'x_size': 5},
True),
(conv.Gaussian2DKernel, [1.0],
{'x_size': 5, 'y_size': 5},
True),
])
def test_simple_object(pickle_protocol, name, args, kwargs, xfail):
# Tests easily instantiated objects
if xfail:
pytest.xfail()
original = name(*args, **kwargs)
check_pickling_recovery(original, pickle_protocol)
|
363a37bb36e4fcba28f73d9729bce3d18eb1191398086da56d352616a121e5c2 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from astropy.convolution.convolve import convolve, convolve_fft
from astropy.convolution.kernels import Gaussian2DKernel
from astropy.nddata import NDData
def test_basic_nddata():
arr = np.zeros((11, 11))
arr[5, 5] = 1
ndd = NDData(arr)
test_kernel = Gaussian2DKernel(1)
result = convolve(ndd, test_kernel)
x, y = np.mgrid[:11, :11]
expected = result[5, 5] * np.exp(-0.5 * ((x - 5)**2 + (y - 5)**2))
np.testing.assert_allclose(result, expected, atol=1e-6)
resultf = convolve_fft(ndd, test_kernel)
np.testing.assert_allclose(resultf, expected, atol=1e-6)
@pytest.mark.parametrize('convfunc',
[lambda *args: convolve(*args, nan_treatment='interpolate', normalize_kernel=True),
lambda *args: convolve_fft(*args, nan_treatment='interpolate', normalize_kernel=True)])
def test_masked_nddata(convfunc):
arr = np.zeros((11, 11))
arr[4, 5] = arr[6, 5] = arr[5, 4] = arr[5, 6] = 0.2
arr[5, 5] = 1.5
ndd_base = NDData(arr)
mask = arr < 0 # this is all False
mask[5, 5] = True
ndd_mask = NDData(arr, mask=mask)
arrnan = arr.copy()
arrnan[5, 5] = np.nan
ndd_nan = NDData(arrnan)
test_kernel = Gaussian2DKernel(1)
result_base = convfunc(ndd_base, test_kernel)
result_nan = convfunc(ndd_nan, test_kernel)
result_mask = convfunc(ndd_mask, test_kernel)
assert np.allclose(result_nan, result_mask)
assert not np.allclose(result_base, result_mask)
assert not np.allclose(result_base, result_nan)
# check to make sure the mask run doesn't talk back to the initial array
assert np.sum(np.isnan(ndd_base.data)) != np.sum(np.isnan(ndd_nan.data))
|
a4333a786787291fa3df3dd978b7cdb832e5bb980dbbb60aa0f8f1918e5c6aea | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import itertools
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_almost_equal
from astropy import units as u
from astropy.convolution.convolve import convolve, convolve_fft
from astropy.convolution.kernels import (Box2DKernel, Gaussian2DKernel,
Moffat2DKernel, Tophat2DKernel)
from astropy.utils.exceptions import AstropyDeprecationWarning
SHAPES_ODD = [[15, 15], [31, 31]]
SHAPES_EVEN = [[8, 8], [16, 16], [32, 32]] # FIXME: not used ?!
NOSHAPE = [[None, None]]
WIDTHS = [2, 3, 4, 5]
KERNELS = []
for shape in SHAPES_ODD + NOSHAPE:
for width in WIDTHS:
KERNELS.append(Gaussian2DKernel(width,
x_size=shape[0],
y_size=shape[1],
mode='oversample',
factor=10))
KERNELS.append(Box2DKernel(width,
x_size=shape[0],
y_size=shape[1],
mode='oversample',
factor=10))
KERNELS.append(Tophat2DKernel(width,
x_size=shape[0],
y_size=shape[1],
mode='oversample',
factor=10))
KERNELS.append(Moffat2DKernel(width, 2,
x_size=shape[0],
y_size=shape[1],
mode='oversample',
factor=10))
class Test2DConvolutions:
@pytest.mark.parametrize('kernel', KERNELS)
def test_centered_makekernel(self, kernel):
"""
Test smoothing of an image with a single positive pixel
"""
shape = kernel.array.shape
x = np.zeros(shape)
xslice = tuple([slice(sh // 2, sh // 2 + 1) for sh in shape])
x[xslice] = 1.0
c2 = convolve_fft(x, kernel, boundary='fill')
c1 = convolve(x, kernel, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
@pytest.mark.parametrize('kernel', KERNELS)
def test_random_makekernel(self, kernel):
"""
Test smoothing of an image made of random noise
"""
shape = kernel.array.shape
x = np.random.randn(*shape)
c2 = convolve_fft(x, kernel, boundary='fill')
c1 = convolve(x, kernel, boundary='fill')
# not clear why, but these differ by a couple ulps...
assert_almost_equal(c1, c2, decimal=12)
@pytest.mark.parametrize(('shape', 'width'), list(itertools.product(SHAPES_ODD, WIDTHS)))
def test_uniform_smallkernel(self, shape, width):
"""
Test smoothing of an image with a single positive pixel
Uses a simple, small kernel
"""
if width % 2 == 0:
# convolve does not accept odd-shape kernels
return
kernel = np.ones([width, width])
x = np.zeros(shape)
xslice = tuple([slice(sh // 2, sh // 2 + 1) for sh in shape])
x[xslice] = 1.0
c2 = convolve_fft(x, kernel, boundary='fill')
c1 = convolve(x, kernel, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
@pytest.mark.parametrize(('shape', 'width'), list(itertools.product(SHAPES_ODD, [1, 3, 5])))
def test_smallkernel_Box2DKernel(self, shape, width):
"""
Test smoothing of an image with a single positive pixel
Compares a small uniform kernel to the Box2DKernel
"""
kernel1 = np.ones([width, width]) / float(width) ** 2
kernel2 = Box2DKernel(width, mode='oversample', factor=10)
x = np.zeros(shape)
xslice = tuple([slice(sh // 2, sh // 2 + 1) for sh in shape])
x[xslice] = 1.0
c2 = convolve_fft(x, kernel2, boundary='fill')
c1 = convolve_fft(x, kernel1, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
c2 = convolve(x, kernel2, boundary='fill')
c1 = convolve(x, kernel1, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
def test_gaussian_2d_kernel_quantity():
# Make sure that the angle can be a quantity
kernel1 = Gaussian2DKernel(x_stddev=2, y_stddev=4, theta=45 * u.deg)
kernel2 = Gaussian2DKernel(x_stddev=2, y_stddev=4, theta=np.pi / 4)
assert_allclose(kernel1.array, kernel2.array)
def test_deprecated_hat():
# 'MexicanHat' was deprecated as a name for the kernels which are now
# 'RickerWavelet'. This test ensures that the kernels are correctly
# deprecated, and can be imported from the top-level package.
from astropy.convolution import MexicanHat1DKernel, MexicanHat2DKernel
with pytest.warns(AstropyDeprecationWarning):
MexicanHat1DKernel(2)
with pytest.warns(AstropyDeprecationWarning):
MexicanHat2DKernel(2)
|
1afb6c448764e7e12c2c9d8e984da28248e6ec680679de78bf697ad2789c8154 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import itertools
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_almost_equal
from astropy.convolution.convolve import convolve, convolve_fft
from astropy.convolution.kernels import (AiryDisk2DKernel, Box1DKernel, Box2DKernel, CustomKernel,
Gaussian1DKernel, Gaussian2DKernel, Kernel1D, Kernel2D,
Model1DKernel, Model2DKernel, RickerWavelet1DKernel,
RickerWavelet2DKernel, Ring2DKernel, Tophat2DKernel,
Trapezoid1DKernel, TrapezoidDisk2DKernel)
from astropy.convolution.utils import KernelSizeError
from astropy.modeling.models import Box2D, Gaussian1D, Gaussian2D
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
from astropy.utils.exceptions import AstropyUserWarning
WIDTHS_ODD = [3, 5, 7, 9]
WIDTHS_EVEN = [2, 4, 8, 16]
MODES = ['center', 'linear_interp', 'oversample', 'integrate']
KERNEL_TYPES = [Gaussian1DKernel, Gaussian2DKernel,
Box1DKernel, Box2DKernel,
Trapezoid1DKernel, TrapezoidDisk2DKernel,
RickerWavelet1DKernel, Tophat2DKernel, AiryDisk2DKernel,
Ring2DKernel]
NUMS = [1, 1., np.float32(1.), np.float64(1.)]
# Test data
delta_pulse_1D = np.zeros(81)
delta_pulse_1D[40] = 1
delta_pulse_2D = np.zeros((81, 81))
delta_pulse_2D[40, 40] = 1
random_data_1D = np.random.rand(61)
random_data_2D = np.random.rand(61, 61)
class TestKernels:
"""
Test class for the built-in convolution kernels.
"""
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize(('width'), WIDTHS_ODD)
def test_scipy_filter_gaussian(self, width):
"""
Test GaussianKernel against SciPy ndimage gaussian filter.
"""
from scipy.ndimage import gaussian_filter
gauss_kernel_1D = Gaussian1DKernel(width)
gauss_kernel_1D.normalize()
gauss_kernel_2D = Gaussian2DKernel(width)
gauss_kernel_2D.normalize()
astropy_1D = convolve(delta_pulse_1D, gauss_kernel_1D, boundary='fill')
astropy_2D = convolve(delta_pulse_2D, gauss_kernel_2D, boundary='fill')
scipy_1D = gaussian_filter(delta_pulse_1D, width)
scipy_2D = gaussian_filter(delta_pulse_2D, width)
assert_almost_equal(astropy_1D, scipy_1D, decimal=12)
assert_almost_equal(astropy_2D, scipy_2D, decimal=12)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize(('width'), WIDTHS_ODD)
def test_scipy_filter_gaussian_laplace(self, width):
"""
Test RickerWavelet kernels against SciPy ndimage gaussian laplace filters.
"""
from scipy.ndimage import gaussian_laplace
ricker_kernel_1D = RickerWavelet1DKernel(width)
ricker_kernel_2D = RickerWavelet2DKernel(width)
astropy_1D = convolve(delta_pulse_1D, ricker_kernel_1D, boundary='fill', normalize_kernel=False)
astropy_2D = convolve(delta_pulse_2D, ricker_kernel_2D, boundary='fill', normalize_kernel=False)
with pytest.raises(Exception) as exc:
astropy_1D = convolve(delta_pulse_1D, ricker_kernel_1D, boundary='fill', normalize_kernel=True)
assert 'sum is close to zero' in exc.value.args[0]
with pytest.raises(Exception) as exc:
astropy_2D = convolve(delta_pulse_2D, ricker_kernel_2D, boundary='fill', normalize_kernel=True)
assert 'sum is close to zero' in exc.value.args[0]
# The Laplace of Gaussian filter is an inverted Ricker Wavelet filter.
scipy_1D = -gaussian_laplace(delta_pulse_1D, width)
scipy_2D = -gaussian_laplace(delta_pulse_2D, width)
# There is a slight deviation in the normalization. They differ by a
# factor of ~1.0000284132604045. The reason is not known.
assert_almost_equal(astropy_1D, scipy_1D, decimal=5)
assert_almost_equal(astropy_2D, scipy_2D, decimal=5)
@pytest.mark.parametrize(('kernel_type', 'width'), list(itertools.product(KERNEL_TYPES, WIDTHS_ODD)))
def test_delta_data(self, kernel_type, width):
"""
Test smoothing of an image with a single positive pixel
"""
if kernel_type == AiryDisk2DKernel and not HAS_SCIPY:
pytest.skip("Omitting AiryDisk2DKernel, which requires SciPy")
if not kernel_type == Ring2DKernel:
kernel = kernel_type(width)
else:
kernel = kernel_type(width, width * 0.2)
if kernel.dimension == 1:
c1 = convolve_fft(delta_pulse_1D, kernel, boundary='fill', normalize_kernel=False)
c2 = convolve(delta_pulse_1D, kernel, boundary='fill', normalize_kernel=False)
assert_almost_equal(c1, c2, decimal=12)
else:
c1 = convolve_fft(delta_pulse_2D, kernel, boundary='fill', normalize_kernel=False)
c2 = convolve(delta_pulse_2D, kernel, boundary='fill', normalize_kernel=False)
assert_almost_equal(c1, c2, decimal=12)
@pytest.mark.parametrize(('kernel_type', 'width'), list(itertools.product(KERNEL_TYPES, WIDTHS_ODD)))
def test_random_data(self, kernel_type, width):
"""
Test smoothing of an image made of random noise
"""
if kernel_type == AiryDisk2DKernel and not HAS_SCIPY:
pytest.skip("Omitting AiryDisk2DKernel, which requires SciPy")
if not kernel_type == Ring2DKernel:
kernel = kernel_type(width)
else:
kernel = kernel_type(width, width * 0.2)
if kernel.dimension == 1:
c1 = convolve_fft(random_data_1D, kernel, boundary='fill', normalize_kernel=False)
c2 = convolve(random_data_1D, kernel, boundary='fill', normalize_kernel=False)
assert_almost_equal(c1, c2, decimal=12)
else:
c1 = convolve_fft(random_data_2D, kernel, boundary='fill', normalize_kernel=False)
c2 = convolve(random_data_2D, kernel, boundary='fill', normalize_kernel=False)
assert_almost_equal(c1, c2, decimal=12)
@pytest.mark.parametrize(('width'), WIDTHS_ODD)
def test_uniform_smallkernel(self, width):
"""
Test smoothing of an image with a single positive pixel
Instead of using kernel class, uses a simple, small kernel
"""
kernel = np.ones([width, width])
c2 = convolve_fft(delta_pulse_2D, kernel, boundary='fill')
c1 = convolve(delta_pulse_2D, kernel, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
@pytest.mark.parametrize(('width'), WIDTHS_ODD)
def test_smallkernel_vs_Box2DKernel(self, width):
"""
Test smoothing of an image with a single positive pixel
"""
kernel1 = np.ones([width, width]) / width ** 2
kernel2 = Box2DKernel(width)
c2 = convolve_fft(delta_pulse_2D, kernel2, boundary='fill')
c1 = convolve_fft(delta_pulse_2D, kernel1, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
def test_convolve_1D_kernels(self):
"""
Check if convolving two kernels with each other works correctly.
"""
gauss_1 = Gaussian1DKernel(3)
gauss_2 = Gaussian1DKernel(4)
test_gauss_3 = Gaussian1DKernel(5)
with pytest.warns(AstropyUserWarning, match=r'Both array and kernel '
r'are Kernel instances'):
gauss_3 = convolve(gauss_1, gauss_2)
assert np.all(np.abs((gauss_3 - test_gauss_3).array) < 0.01)
def test_convolve_2D_kernels(self):
"""
Check if convolving two kernels with each other works correctly.
"""
gauss_1 = Gaussian2DKernel(3)
gauss_2 = Gaussian2DKernel(4)
test_gauss_3 = Gaussian2DKernel(5)
with pytest.warns(AstropyUserWarning, match=r'Both array and kernel '
r'are Kernel instances'):
gauss_3 = convolve(gauss_1, gauss_2)
assert np.all(np.abs((gauss_3 - test_gauss_3).array) < 0.01)
@pytest.mark.parametrize(('number'), NUMS)
def test_multiply_scalar(self, number):
"""
Check if multiplying a kernel with a scalar works correctly.
"""
gauss = Gaussian1DKernel(3)
gauss_new = number * gauss
assert_almost_equal(gauss_new.array, gauss.array * number, decimal=12)
@pytest.mark.parametrize(('number'), NUMS)
def test_multiply_scalar_type(self, number):
"""
Check if multiplying a kernel with a scalar works correctly.
"""
gauss = Gaussian1DKernel(3)
gauss_new = number * gauss
assert type(gauss_new) is Gaussian1DKernel
@pytest.mark.parametrize(('number'), NUMS)
def test_rmultiply_scalar_type(self, number):
"""
Check if multiplying a kernel with a scalar works correctly.
"""
gauss = Gaussian1DKernel(3)
gauss_new = gauss * number
assert type(gauss_new) is Gaussian1DKernel
def test_multiply_kernel1d(self):
"""Test that multiplying two 1D kernels raises an exception."""
gauss = Gaussian1DKernel(3)
with pytest.raises(Exception):
gauss * gauss
def test_multiply_kernel2d(self):
"""Test that multiplying two 2D kernels raises an exception."""
gauss = Gaussian2DKernel(3)
with pytest.raises(Exception):
gauss * gauss
def test_multiply_kernel1d_kernel2d(self):
"""
Test that multiplying a 1D kernel with a 2D kernel raises an
exception.
"""
with pytest.raises(Exception):
Gaussian1DKernel(3) * Gaussian2DKernel(3)
def test_add_kernel_scalar(self):
"""Test that adding a scalar to a kernel raises an exception."""
with pytest.raises(Exception):
Gaussian1DKernel(3) + 1
def test_model_1D_kernel(self):
"""
Check Model1DKernel against Gaussian1Dkernel
"""
stddev = 5.
gauss = Gaussian1D(1. / np.sqrt(2 * np.pi * stddev**2), 0, stddev)
model_gauss_kernel = Model1DKernel(gauss, x_size=21)
gauss_kernel = Gaussian1DKernel(stddev, x_size=21)
assert_almost_equal(model_gauss_kernel.array, gauss_kernel.array,
decimal=12)
def test_model_2D_kernel(self):
"""
Check Model2DKernel against Gaussian2Dkernel
"""
stddev = 5.
gauss = Gaussian2D(1. / (2 * np.pi * stddev**2), 0, 0, stddev, stddev)
model_gauss_kernel = Model2DKernel(gauss, x_size=21)
gauss_kernel = Gaussian2DKernel(stddev, x_size=21)
assert_almost_equal(model_gauss_kernel.array, gauss_kernel.array,
decimal=12)
def test_custom_1D_kernel(self):
"""
Check CustomKernel against Box1DKernel.
"""
# Define one dimensional array:
array = np.ones(5)
custom = CustomKernel(array)
custom.normalize()
box = Box1DKernel(5)
c2 = convolve(delta_pulse_1D, custom, boundary='fill')
c1 = convolve(delta_pulse_1D, box, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
def test_custom_2D_kernel(self):
"""
Check CustomKernel against Box2DKernel.
"""
# Define one dimensional array:
array = np.ones((5, 5))
custom = CustomKernel(array)
custom.normalize()
box = Box2DKernel(5)
c2 = convolve(delta_pulse_2D, custom, boundary='fill')
c1 = convolve(delta_pulse_2D, box, boundary='fill')
assert_almost_equal(c1, c2, decimal=12)
def test_custom_1D_kernel_list(self):
"""
Check if CustomKernel works with lists.
"""
custom = CustomKernel([1, 1, 1, 1, 1])
assert custom.is_bool is True
def test_custom_2D_kernel_list(self):
"""
Check if CustomKernel works with lists.
"""
custom = CustomKernel([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
assert custom.is_bool is True
def test_custom_1D_kernel_zerosum(self):
"""
Check if CustomKernel works when the input array/list
sums to zero.
"""
array = [-2, -1, 0, 1, 2]
custom = CustomKernel(array)
with pytest.warns(AstropyUserWarning, match=r'kernel cannot be '
r'normalized because it sums to zero'):
custom.normalize()
assert custom.truncation == 0.
assert custom._kernel_sum == 0.
def test_custom_2D_kernel_zerosum(self):
"""
Check if CustomKernel works when the input array/list
sums to zero.
"""
array = [[0, -1, 0], [-1, 4, -1], [0, -1, 0]]
custom = CustomKernel(array)
with pytest.warns(AstropyUserWarning, match=r'kernel cannot be '
r'normalized because it sums to zero'):
custom.normalize()
assert custom.truncation == 0.
assert custom._kernel_sum == 0.
def test_custom_kernel_odd_error(self):
"""
Check if CustomKernel raises if the array size is odd.
"""
with pytest.raises(KernelSizeError):
CustomKernel([1, 1, 1, 1])
def test_add_1D_kernels(self):
"""
Check if adding of two 1D kernels works.
"""
box_1 = Box1DKernel(5)
box_2 = Box1DKernel(3)
box_3 = Box1DKernel(1)
box_sum_1 = box_1 + box_2 + box_3
box_sum_2 = box_2 + box_3 + box_1
box_sum_3 = box_3 + box_1 + box_2
ref = [1/5., 1/5. + 1/3., 1 + 1/3. + 1/5., 1/5. + 1/3., 1/5.]
assert_almost_equal(box_sum_1.array, ref, decimal=12)
assert_almost_equal(box_sum_2.array, ref, decimal=12)
assert_almost_equal(box_sum_3.array, ref, decimal=12)
# Assert that the kernels haven't changed
assert_almost_equal(box_1.array, [0.2, 0.2, 0.2, 0.2, 0.2], decimal=12)
assert_almost_equal(box_2.array, [1/3., 1/3., 1/3.], decimal=12)
assert_almost_equal(box_3.array, [1], decimal=12)
def test_add_2D_kernels(self):
"""
Check if adding of two 1D kernels works.
"""
box_1 = Box2DKernel(3)
box_2 = Box2DKernel(1)
box_sum_1 = box_1 + box_2
box_sum_2 = box_2 + box_1
ref = [[1 / 9., 1 / 9., 1 / 9.],
[1 / 9., 1 + 1 / 9., 1 / 9.],
[1 / 9., 1 / 9., 1 / 9.]]
ref_1 = [[1 / 9., 1 / 9., 1 / 9.],
[1 / 9., 1 / 9., 1 / 9.],
[1 / 9., 1 / 9., 1 / 9.]]
assert_almost_equal(box_2.array, [[1]], decimal=12)
assert_almost_equal(box_1.array, ref_1, decimal=12)
assert_almost_equal(box_sum_1.array, ref, decimal=12)
assert_almost_equal(box_sum_2.array, ref, decimal=12)
def test_Gaussian1DKernel_even_size(self):
"""
Check if even size for GaussianKernel works.
"""
gauss = Gaussian1DKernel(3, x_size=10)
assert gauss.array.size == 10
def test_Gaussian2DKernel_even_size(self):
"""
Check if even size for GaussianKernel works.
"""
gauss = Gaussian2DKernel(3, x_size=10, y_size=10)
assert gauss.array.shape == (10, 10)
# https://github.com/astropy/astropy/issues/3605
def test_Gaussian2DKernel_rotated(self):
gauss = Gaussian2DKernel(
x_stddev=3, y_stddev=1.5, theta=0.7853981633974483,
x_size=5, y_size=5) # rotated 45 deg ccw
ans = [[0.02267712, 0.02464785, 0.02029238, 0.01265463, 0.00597762],
[0.02464785, 0.03164847, 0.03078144, 0.02267712, 0.01265463],
[0.02029238, 0.03078144, 0.03536777, 0.03078144, 0.02029238],
[0.01265463, 0.02267712, 0.03078144, 0.03164847, 0.02464785],
[0.00597762, 0.01265463, 0.02029238, 0.02464785, 0.02267712]]
assert_allclose(gauss, ans, rtol=0.001) # Rough comparison at 0.1 %
def test_normalize_peak(self):
"""
Check if normalize works with peak mode.
"""
custom = CustomKernel([1, 2, 3, 2, 1])
custom.normalize(mode='peak')
assert custom.array.max() == 1
def test_check_kernel_attributes(self):
"""
Check if kernel attributes are correct.
"""
box = Box2DKernel(5)
# Check truncation
assert box.truncation == 0
# Check model
assert isinstance(box.model, Box2D)
# Check center
assert box.center == [2, 2]
# Check normalization
box.normalize()
assert_almost_equal(box._kernel_sum, 1., decimal=12)
# Check separability
assert box.separable
@pytest.mark.parametrize(('kernel_type', 'mode'), list(itertools.product(KERNEL_TYPES, MODES)))
def test_discretize_modes(self, kernel_type, mode):
"""
Check if the different modes result in kernels that work with convolve.
Use only small kernel width, to make the test pass quickly.
"""
if kernel_type == AiryDisk2DKernel and not HAS_SCIPY:
pytest.skip("Omitting AiryDisk2DKernel, which requires SciPy")
if not kernel_type == Ring2DKernel:
kernel = kernel_type(3)
else:
kernel = kernel_type(3, 3 * 0.2)
if kernel.dimension == 1:
c1 = convolve_fft(delta_pulse_1D, kernel, boundary='fill', normalize_kernel=False)
c2 = convolve(delta_pulse_1D, kernel, boundary='fill', normalize_kernel=False)
assert_almost_equal(c1, c2, decimal=12)
else:
c1 = convolve_fft(delta_pulse_2D, kernel, boundary='fill', normalize_kernel=False)
c2 = convolve(delta_pulse_2D, kernel, boundary='fill', normalize_kernel=False)
assert_almost_equal(c1, c2, decimal=12)
@pytest.mark.parametrize(('width'), WIDTHS_EVEN)
def test_box_kernels_even_size(self, width):
"""
Check if BoxKernel work properly with even sizes.
"""
kernel_1D = Box1DKernel(width)
assert kernel_1D.shape[0] % 2 != 0
assert kernel_1D.array.sum() == 1.
kernel_2D = Box2DKernel(width)
assert np.all([_ % 2 != 0 for _ in kernel_2D.shape])
assert kernel_2D.array.sum() == 1.
def test_kernel_normalization(self):
"""
Test that repeated normalizations do not change the kernel [#3747].
"""
kernel = CustomKernel(np.ones(5))
kernel.normalize()
data = np.copy(kernel.array)
kernel.normalize()
assert_allclose(data, kernel.array)
kernel.normalize()
assert_allclose(data, kernel.array)
def test_kernel_normalization_mode(self):
"""
Test that an error is raised if mode is invalid.
"""
with pytest.raises(ValueError):
kernel = CustomKernel(np.ones(3))
kernel.normalize(mode='invalid')
def test_kernel1d_int_size(self):
"""
Test that an error is raised if ``Kernel1D`` ``x_size`` is not
an integer.
"""
with pytest.raises(TypeError):
Gaussian1DKernel(3, x_size=1.2)
def test_kernel2d_int_xsize(self):
"""
Test that an error is raised if ``Kernel2D`` ``x_size`` is not
an integer.
"""
with pytest.raises(TypeError):
Gaussian2DKernel(3, x_size=1.2)
def test_kernel2d_int_ysize(self):
"""
Test that an error is raised if ``Kernel2D`` ``y_size`` is not
an integer.
"""
with pytest.raises(TypeError):
Gaussian2DKernel(3, x_size=5, y_size=1.2)
def test_kernel1d_initialization(self):
"""
Test that an error is raised if an array or model is not
specified for ``Kernel1D``.
"""
with pytest.raises(TypeError):
Kernel1D()
def test_kernel2d_initialization(self):
"""
Test that an error is raised if an array or model is not
specified for ``Kernel2D``.
"""
with pytest.raises(TypeError):
Kernel2D()
def test_array_keyword_not_allowed(self):
"""
Regression test for issue #10439
"""
x = np.ones([10, 10])
with pytest.raises(TypeError, match=r".* allowed .*"):
AiryDisk2DKernel(2, array=x)
Box1DKernel(2, array=x)
Box2DKernel(2, array=x)
Gaussian1DKernel(2, array=x)
Gaussian2DKernel(2, array=x)
RickerWavelet1DKernel(2, array=x)
RickerWavelet2DKernel(2, array=x)
Model1DKernel(Gaussian1D(1, 0, 2), array=x)
Model2DKernel(Gaussian2D(1, 0, 0, 2, 2), array=x)
Ring2DKernel(9, 8, array=x)
Tophat2DKernel(2, array=x)
Trapezoid1DKernel(2, array=x)
Trapezoid1DKernel(2, array=x)
|
22322aa96ee8b0a080322f37165c6c2f76c9900cfb2066180b7a5ccc91ee87da | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import itertools
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy.convolution.utils import discretize_model
from astropy.modeling.functional_models import (Box1D, Box2D, Gaussian1D, Gaussian2D,
RickerWavelet1D, RickerWavelet2D)
from astropy.modeling.tests.example_models import models_1D, models_2D
from astropy.modeling.tests.test_models import create_model
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
modes = ['center', 'linear_interp', 'oversample']
test_models_1D = [Gaussian1D, Box1D, RickerWavelet1D]
test_models_2D = [Gaussian2D, Box2D, RickerWavelet2D]
@pytest.mark.parametrize(('model_class', 'mode'), list(itertools.product(test_models_1D, modes)))
def test_pixel_sum_1D(model_class, mode):
"""
Test if the sum of all pixels corresponds nearly to the integral.
"""
if model_class == Box1D and mode == "center":
pytest.skip("Non integrating mode. Skip integral test.")
parameters = models_1D[model_class]
model = create_model(model_class, parameters)
values = discretize_model(model, models_1D[model_class]['x_lim'], mode=mode)
assert_allclose(values.sum(), models_1D[model_class]['integral'], atol=0.0001)
@pytest.mark.parametrize('mode', modes)
def test_gaussian_eval_1D(mode):
"""
Discretize Gaussian with different modes and check
if result is at least similar to Gaussian1D.eval().
"""
model = Gaussian1D(1, 0, 20)
x = np.arange(-100, 101)
values = model(x)
disc_values = discretize_model(model, (-100, 101), mode=mode)
assert_allclose(values, disc_values, atol=0.001)
@pytest.mark.parametrize(('model_class', 'mode'), list(itertools.product(test_models_2D, modes)))
def test_pixel_sum_2D(model_class, mode):
"""
Test if the sum of all pixels corresponds nearly to the integral.
"""
if model_class == Box2D and mode == "center":
pytest.skip("Non integrating mode. Skip integral test.")
parameters = models_2D[model_class]
model = create_model(model_class, parameters)
values = discretize_model(model, models_2D[model_class]['x_lim'],
models_2D[model_class]['y_lim'], mode=mode)
assert_allclose(values.sum(), models_2D[model_class]['integral'], atol=0.0001)
@pytest.mark.parametrize('mode', modes)
def test_gaussian_eval_2D(mode):
"""
Discretize Gaussian with different modes and check
if result is at least similar to Gaussian2D.eval()
"""
model = Gaussian2D(0.01, 0, 0, 1, 1)
x = np.arange(-2, 3)
y = np.arange(-2, 3)
x, y = np.meshgrid(x, y)
values = model(x, y)
disc_values = discretize_model(model, (-2, 3), (-2, 3), mode=mode)
assert_allclose(values, disc_values, atol=1e-2)
@pytest.mark.skipif('not HAS_SCIPY')
def test_gaussian_eval_2D_integrate_mode():
"""
Discretize Gaussian with integrate mode
"""
model_list = [Gaussian2D(.01, 0, 0, 2, 2),
Gaussian2D(.01, 0, 0, 1, 2),
Gaussian2D(.01, 0, 0, 2, 1)]
x = np.arange(-2, 3)
y = np.arange(-2, 3)
x, y = np.meshgrid(x, y)
for model in model_list:
values = model(x, y)
disc_values = discretize_model(model, (-2, 3), (-2, 3), mode='integrate')
assert_allclose(values, disc_values, atol=1e-2)
@pytest.mark.skipif('not HAS_SCIPY')
def test_subpixel_gauss_1D():
"""
Test subpixel accuracy of the integrate mode with gaussian 1D model.
"""
gauss_1D = Gaussian1D(1, 0, 0.1)
values = discretize_model(gauss_1D, (-1, 2), mode='integrate', factor=100)
assert_allclose(values.sum(), np.sqrt(2 * np.pi) * 0.1, atol=0.00001)
@pytest.mark.skipif('not HAS_SCIPY')
def test_subpixel_gauss_2D():
"""
Test subpixel accuracy of the integrate mode with gaussian 2D model.
"""
gauss_2D = Gaussian2D(1, 0, 0, 0.1, 0.1)
values = discretize_model(gauss_2D, (-1, 2), (-1, 2), mode='integrate', factor=100)
assert_allclose(values.sum(), 2 * np.pi * 0.01, atol=0.00001)
def test_discretize_callable_1d():
"""
Test discretize when a 1d function is passed.
"""
def f(x):
return x ** 2
y = discretize_model(f, (-5, 6))
assert_allclose(y, np.arange(-5, 6) ** 2)
def test_discretize_callable_2d():
"""
Test discretize when a 2d function is passed.
"""
def f(x, y):
return x ** 2 + y ** 2
actual = discretize_model(f, (-5, 6), (-5, 6))
y, x = (np.indices((11, 11)) - 5)
desired = x ** 2 + y ** 2
assert_allclose(actual, desired)
def test_type_exception():
"""
Test type exception.
"""
with pytest.raises(TypeError) as exc:
discretize_model(float(0), (-10, 11))
assert exc.value.args[0] == 'Model must be callable.'
def test_dim_exception_1d():
"""
Test dimension exception 1d.
"""
def f(x):
return x ** 2
with pytest.raises(ValueError) as exc:
discretize_model(f, (-10, 11), (-10, 11))
assert exc.value.args[0] == "y range specified, but model is only 1-d."
def test_dim_exception_2d():
"""
Test dimension exception 2d.
"""
def f(x, y):
return x ** 2 + y ** 2
with pytest.raises(ValueError) as exc:
discretize_model(f, (-10, 11))
assert exc.value.args[0] == "y range not specified, but model is 2-d"
def test_float_x_range_exception():
def f(x, y):
return x ** 2 + y ** 2
with pytest.raises(ValueError) as exc:
discretize_model(f, (-10.002, 11.23))
assert exc.value.args[0] == ("The difference between the upper and lower"
" limit of 'x_range' must be a whole number.")
def test_float_y_range_exception():
def f(x, y):
return x ** 2 + y ** 2
with pytest.raises(ValueError) as exc:
discretize_model(f, (-10, 11), (-10.002, 11.23))
assert exc.value.args[0] == ("The difference between the upper and lower"
" limit of 'y_range' must be a whole number.")
def test_discretize_oversample():
gauss_2D = Gaussian2D(amplitude=1.0, x_mean=5.,
y_mean=125., x_stddev=0.75, y_stddev=3)
values = discretize_model(gauss_2D,
x_range=[0, 10],
y_range=[100, 135],
mode='oversample', factor=10)
vmax = np.max(values)
vmax_yx = np.unravel_index(values.argmax(), values.shape)
values_osf1 = discretize_model(gauss_2D,
x_range=[0, 10],
y_range=[100, 135],
mode='oversample', factor=1)
values_center = discretize_model(gauss_2D,
x_range=[0, 10],
y_range=[100, 135],
mode = 'center')
assert values.shape == (35, 10)
assert_allclose(vmax, 0.927, atol=1e-3)
assert vmax_yx == (25, 5)
assert_allclose(values_center, values_osf1)
|
57c49064726c210c5f9649c3f8f2f3991a71f97f3a9b56c99fe16d9347f4aa9b | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import itertools
from contextlib import nullcontext
import pytest
import numpy as np
import numpy.ma as ma
from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_almost_equal_nulp
from astropy import units as u
from astropy.convolution.convolve import convolve, convolve_fft
from astropy.convolution.kernels import Gaussian2DKernel
from astropy.utils.compat.optional_deps import HAS_PANDAS, HAS_SCIPY # noqa
from astropy.utils.exceptions import AstropyUserWarning
VALID_DTYPES = ('>f4', '<f4', '>f8', '<f8')
VALID_DTYPE_MATRIX = list(itertools.product(VALID_DTYPES, VALID_DTYPES))
BOUNDARY_OPTIONS = [None, 'fill', 'wrap', 'extend']
NANHANDLING_OPTIONS = ['interpolate', 'fill']
NORMALIZE_OPTIONS = [True, False]
PRESERVE_NAN_OPTIONS = [True, False]
BOUNDARIES_AND_CONVOLUTIONS = (list(zip(itertools.cycle((convolve,)),
BOUNDARY_OPTIONS)) + [(convolve_fft,
'wrap'),
(convolve_fft,
'fill')])
class TestConvolve1D:
def test_list(self):
"""
Test that convolve works correctly when inputs are lists
"""
x = [1, 4, 5, 6, 5, 7, 8]
y = [0.2, 0.6, 0.2]
z = convolve(x, y, boundary=None)
assert_array_almost_equal_nulp(z,
np.array([0., 3.6, 5., 5.6, 5.6, 6.8, 0.]), 10)
def test_tuple(self):
"""
Test that convolve works correctly when inputs are tuples
"""
x = (1, 4, 5, 6, 5, 7, 8)
y = (0.2, 0.6, 0.2)
z = convolve(x, y, boundary=None)
assert_array_almost_equal_nulp(z,
np.array([0., 3.6, 5., 5.6, 5.6, 6.8, 0.]), 10)
@pytest.mark.parametrize(('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan', 'dtype'),
itertools.product(BOUNDARY_OPTIONS,
NANHANDLING_OPTIONS,
NORMALIZE_OPTIONS,
PRESERVE_NAN_OPTIONS,
VALID_DTYPES))
def test_quantity(self, boundary, nan_treatment,
normalize_kernel, preserve_nan, dtype):
"""
Test that convolve works correctly when input array is a Quantity
"""
x = np.array([1, 4, 5, 6, 5, 7, 8], dtype=dtype) * u.ph
y = np.array([0.2, 0.6, 0.2], dtype=dtype)
z = convolve(x, y, boundary=boundary, nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel, preserve_nan=preserve_nan)
assert x.unit == z.unit
@pytest.mark.parametrize(('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan', 'dtype'),
itertools.product(BOUNDARY_OPTIONS,
NANHANDLING_OPTIONS,
NORMALIZE_OPTIONS,
PRESERVE_NAN_OPTIONS,
VALID_DTYPES))
def test_input_unmodified(self, boundary, nan_treatment,
normalize_kernel, preserve_nan, dtype):
"""
Test that convolve works correctly when inputs are lists
"""
array = [1., 4., 5., 6., 5., 7., 8.]
kernel = [0.2, 0.6, 0.2]
x = np.array(array, dtype=dtype)
y = np.array(kernel, dtype=dtype)
# Make pseudoimmutable
x.flags.writeable = False
y.flags.writeable = False
z = convolve(x, y, boundary=boundary, nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel, preserve_nan=preserve_nan)
assert np.all(np.array(array, dtype=dtype) == x)
assert np.all(np.array(kernel, dtype=dtype) == y)
@pytest.mark.parametrize(('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan', 'dtype'),
itertools.product(BOUNDARY_OPTIONS,
NANHANDLING_OPTIONS,
NORMALIZE_OPTIONS,
PRESERVE_NAN_OPTIONS,
VALID_DTYPES))
def test_input_unmodified_with_nan(self, boundary, nan_treatment,
normalize_kernel, preserve_nan, dtype):
"""
Test that convolve doesn't modify the input data
"""
array = [1., 4., 5., np.nan, 5., 7., 8.]
kernel = [0.2, 0.6, 0.2]
x = np.array(array, dtype=dtype)
y = np.array(kernel, dtype=dtype)
# Make pseudoimmutable
x.flags.writeable = False
y.flags.writeable = False
# make copies for post call comparison
x_copy = x.copy()
y_copy = y.copy()
z = convolve(x, y, boundary=boundary, nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel, preserve_nan=preserve_nan)
# ( NaN == NaN ) = False
# Only compare non NaN values for canonical equivalence
# and then check NaN explicitly with np.isnan()
array_is_nan = np.isnan(array)
kernel_is_nan = np.isnan(kernel)
array_not_nan = ~array_is_nan
kernel_not_nan = ~kernel_is_nan
assert np.all(x_copy[array_not_nan] == x[array_not_nan])
assert np.all(y_copy[kernel_not_nan] == y[kernel_not_nan])
assert np.all(np.isnan(x[array_is_nan]))
assert np.all(np.isnan(y[kernel_is_nan]))
@pytest.mark.parametrize(('dtype_array', 'dtype_kernel'), VALID_DTYPE_MATRIX)
def test_dtype(self, dtype_array, dtype_kernel):
'''
Test that 32- and 64-bit floats are correctly handled
'''
x = np.array([1., 2., 3.], dtype=dtype_array)
y = np.array([0., 1., 0.], dtype=dtype_kernel)
z = convolve(x, y)
assert x.dtype == z.dtype
@pytest.mark.parametrize(('convfunc', 'boundary',), BOUNDARIES_AND_CONVOLUTIONS)
def test_unity_1_none(self, boundary, convfunc):
'''
Test that a unit kernel with a single element returns the same array
'''
x = np.array([1., 2., 3.], dtype='>f8')
y = np.array([1.], dtype='>f8')
z = convfunc(x, y, boundary=boundary)
np.testing.assert_allclose(z, x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_unity_3(self, boundary):
'''
Test that a unit kernel with three elements returns the same array
(except when boundary is None).
'''
x = np.array([1., 2., 3.], dtype='>f8')
y = np.array([0., 1., 0.], dtype='>f8')
z = convolve(x, y, boundary=boundary)
if boundary is None:
assert np.all(z == np.array([0., 2., 0.], dtype='>f8'))
else:
assert np.all(z == x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_uniform_3(self, boundary):
'''
Test that the different modes are producing the correct results using
a uniform kernel with three elements
'''
x = np.array([1., 0., 3.], dtype='>f8')
y = np.array([1., 1., 1.], dtype='>f8')
z = convolve(x, y, boundary=boundary, normalize_kernel=False)
if boundary is None:
assert np.all(z == np.array([0., 4., 0.], dtype='>f8'))
elif boundary == 'fill':
assert np.all(z == np.array([1., 4., 3.], dtype='>f8'))
elif boundary == 'wrap':
assert np.all(z == np.array([4., 4., 4.], dtype='>f8'))
else:
assert np.all(z == np.array([2., 4., 6.], dtype='>f8'))
@pytest.mark.parametrize(('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan'),
itertools.product(BOUNDARY_OPTIONS,
NANHANDLING_OPTIONS,
NORMALIZE_OPTIONS,
PRESERVE_NAN_OPTIONS))
def test_unity_3_withnan(self, boundary, nan_treatment,
normalize_kernel, preserve_nan):
'''
Test that a unit kernel with three elements returns the same array
(except when boundary is None). This version includes a NaN value in
the original array.
'''
x = np.array([1., np.nan, 3.], dtype='>f8')
y = np.array([0., 1., 0.], dtype='>f8')
# Since the kernel is actually only one pixel wide (because of the
# zeros) the NaN value doesn't get interpolated over so a warning is
# expected.
if nan_treatment == 'interpolate' and not preserve_nan:
ctx = pytest.warns(AstropyUserWarning,
match="nan_treatment='interpolate', however, "
"NaN values detected")
else:
ctx = nullcontext()
with ctx:
z = convolve(x, y, boundary=boundary, nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[1])
x = np.nan_to_num(z)
z = np.nan_to_num(z)
if boundary is None:
assert np.all(z == np.array([0., 0., 0.], dtype='>f8'))
else:
assert np.all(z == x)
@pytest.mark.parametrize(('boundary', 'nan_treatment',
'normalize_kernel', 'preserve_nan'),
itertools.product(BOUNDARY_OPTIONS,
NANHANDLING_OPTIONS,
NORMALIZE_OPTIONS,
PRESERVE_NAN_OPTIONS))
def test_uniform_3_withnan(self, boundary, nan_treatment, normalize_kernel,
preserve_nan):
'''
Test that the different modes are producing the correct results using
a uniform kernel with three elements. This version includes a NaN
value in the original array.
'''
x = np.array([1., np.nan, 3.], dtype='>f8')
y = np.array([1., 1., 1.], dtype='>f8')
z = convolve(x, y, boundary=boundary, nan_treatment=nan_treatment,
normalize_kernel=normalize_kernel,
preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[1])
z = np.nan_to_num(z)
# boundary, nan_treatment, normalize_kernel
rslt = {
(None, 'interpolate', True): [0, 2, 0],
(None, 'interpolate', False): [0, 6, 0],
(None, 'fill', True): [0, 4/3., 0],
(None, 'fill', False): [0, 4, 0],
('fill', 'interpolate', True): [1/2., 2, 3/2.],
('fill', 'interpolate', False): [3/2., 6, 9/2.],
('fill', 'fill', True): [1/3., 4/3., 3/3.],
('fill', 'fill', False): [1, 4, 3],
('wrap', 'interpolate', True): [2, 2, 2],
('wrap', 'interpolate', False): [6, 6, 6],
('wrap', 'fill', True): [4/3., 4/3., 4/3.],
('wrap', 'fill', False): [4, 4, 4],
('extend', 'interpolate', True): [1, 2, 3],
('extend', 'interpolate', False): [3, 6, 9],
('extend', 'fill', True): [2/3., 4/3., 6/3.],
('extend', 'fill', False): [2, 4, 6],
}[boundary, nan_treatment, normalize_kernel]
if preserve_nan:
rslt[1] = 0
assert_array_almost_equal_nulp(z, np.array(rslt, dtype='>f8'), 10)
@pytest.mark.parametrize(('boundary', 'normalize_kernel'),
itertools.product(BOUNDARY_OPTIONS,
NORMALIZE_OPTIONS))
def test_zero_sum_kernel(self, boundary, normalize_kernel):
"""
Test that convolve works correctly with zero sum kernels.
"""
if normalize_kernel:
pytest.xfail("You can't normalize by a zero sum kernel")
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [-1, -1, -1, -1, 8, -1, -1, -1, -1]
assert(np.isclose(sum(y), 0, atol=1e-8))
z = convolve(x, y, boundary=boundary, normalize_kernel=normalize_kernel)
# boundary, normalize_kernel == False
rslt = {
(None): [0., 0., 0., 0., 0., 0., 0., 0., 0.],
('fill'): [-6., -3., -1., 0., 0., 10., 21., 33., 46.],
('wrap'): [-36., -27., -18., -9., 0., 9., 18., 27., 36.],
('extend'): [-10., -6., -3., -1., 0., 1., 3., 6., 10.]
}[boundary]
assert_array_almost_equal_nulp(z, np.array(rslt, dtype='>f8'), 10)
@pytest.mark.parametrize(('boundary', 'normalize_kernel'),
itertools.product(BOUNDARY_OPTIONS,
NORMALIZE_OPTIONS))
def test_int_masked_kernel(self, boundary, normalize_kernel):
"""
Test that convolve works correctly with integer masked kernels.
"""
if normalize_kernel:
pytest.xfail("You can't normalize by a zero sum kernel")
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = ma.array([-1, -1, -1, -1, 8, -1, -1, -1, -1], mask=[1, 0, 0, 0, 0, 0, 0, 0, 0], fill_value=0.)
z = convolve(x, y, boundary=boundary, normalize_kernel=normalize_kernel)
# boundary, normalize_kernel == False
rslt = {
(None): [0., 0., 0., 0., 9., 0., 0., 0., 0.],
('fill'): [-1., 3., 6., 8., 9., 10., 21., 33., 46.],
('wrap'): [-31., -21., -11., -1., 9., 10., 20., 30., 40.],
('extend'): [-5., 0., 4., 7., 9., 10., 12., 15., 19.]
}[boundary]
assert_array_almost_equal_nulp(z, np.array(rslt, dtype='>f8'), 10)
@pytest.mark.parametrize('preserve_nan', PRESERVE_NAN_OPTIONS)
def test_int_masked_array(self, preserve_nan):
"""
Test that convolve works correctly with integer masked arrays.
"""
x = ma.array([3, 5, 7, 11, 13], mask=[0, 0, 1, 0, 0], fill_value=0.)
y = np.array([1., 1., 1.], dtype='>f8')
z = convolve(x, y, preserve_nan=preserve_nan)
if preserve_nan:
assert np.isnan(z[2])
z[2] = 8
assert_array_almost_equal_nulp(z, (8/3., 4, 8, 12, 8), 10)
class TestConvolve2D:
def test_list(self):
"""
Test that convolve works correctly when inputs are lists
"""
x = [[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
z = convolve(x, x, boundary='fill', fill_value=1, normalize_kernel=True)
assert_array_almost_equal_nulp(z, x, 10)
z = convolve(x, x, boundary='fill', fill_value=1, normalize_kernel=False)
assert_array_almost_equal_nulp(z, np.array(x, float)*9, 10)
@pytest.mark.parametrize(('dtype_array', 'dtype_kernel'), VALID_DTYPE_MATRIX)
def test_dtype(self, dtype_array, dtype_kernel):
'''
Test that 32- and 64-bit floats are correctly handled
'''
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype=dtype_array)
y = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype=dtype_kernel)
z = convolve(x, y)
assert x.dtype == z.dtype
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_unity_1x1_none(self, boundary):
'''
Test that a 1x1 unit kernel returns the same array
'''
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype='>f8')
y = np.array([[1.]], dtype='>f8')
z = convolve(x, y, boundary=boundary)
assert np.all(z == x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_unity_3x3(self, boundary):
'''
Test that a 3x3 unit kernel returns the same array (except when
boundary is None).
'''
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype='>f8')
y = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype='>f8')
z = convolve(x, y, boundary=boundary)
if boundary is None:
assert np.all(z == np.array([[0., 0., 0.],
[0., 5., 0.],
[0., 0., 0.]], dtype='>f8'))
else:
assert np.all(z == x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_uniform_3x3(self, boundary):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel.
'''
x = np.array([[0., 0., 3.],
[1., 0., 0.],
[0., 2., 0.]], dtype='>f8')
y = np.array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype='>f8')
z = convolve(x, y, boundary=boundary, normalize_kernel=False)
if boundary is None:
assert_array_almost_equal_nulp(z, np.array([[0., 0., 0.],
[0., 6., 0.],
[0., 0., 0.]], dtype='>f8'), 10)
elif boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([[1., 4., 3.],
[3., 6., 5.],
[3., 3., 2.]], dtype='>f8'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([[6., 6., 6.],
[6., 6., 6.],
[6., 6., 6.]], dtype='>f8'), 10)
else:
assert_array_almost_equal_nulp(z, np.array([[2., 7., 12.],
[4., 6., 8.],
[6., 5., 4.]], dtype='>f8'), 10)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_unity_3x3_withnan(self, boundary):
'''
Test that a 3x3 unit kernel returns the same array (except when
boundary is None). This version includes a NaN value in the original
array.
'''
x = np.array([[1., 2., 3.],
[4., np.nan, 6.],
[7., 8., 9.]], dtype='>f8')
y = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype='>f8')
z = convolve(x, y, boundary=boundary, nan_treatment='fill',
preserve_nan=True)
assert np.isnan(z[1, 1])
x = np.nan_to_num(z)
z = np.nan_to_num(z)
if boundary is None:
assert np.all(z == np.array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype='>f8'))
else:
assert np.all(z == x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_uniform_3x3_withnanfilled(self, boundary):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel. This version includes a NaN value in the
original array.
'''
x = np.array([[0., 0., 4.],
[1., np.nan, 0.],
[0., 3., 0.]], dtype='>f8')
y = np.array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype='>f8')
z = convolve(x, y, boundary=boundary, nan_treatment='fill',
normalize_kernel=False)
if boundary is None:
assert_array_almost_equal_nulp(z, np.array([[0., 0., 0.],
[0., 8., 0.],
[0., 0., 0.]], dtype='>f8'), 10)
elif boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([[1., 5., 4.],
[4., 8., 7.],
[4., 4., 3.]], dtype='>f8'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([[8., 8., 8.],
[8., 8., 8.],
[8., 8., 8.]], dtype='>f8'), 10)
elif boundary == 'extend':
assert_array_almost_equal_nulp(z, np.array([[2., 9., 16.],
[5., 8., 11.],
[8., 7., 6.]], dtype='>f8'), 10)
else:
raise ValueError("Invalid boundary specification")
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_uniform_3x3_withnaninterped(self, boundary):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel. This version includes a NaN value in the
original array.
'''
x = np.array([[0., 0., 4.],
[1., np.nan, 0.],
[0., 3., 0.]], dtype='>f8')
y = np.array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype='>f8')
z = convolve(x, y, boundary=boundary, nan_treatment='interpolate',
normalize_kernel=True)
if boundary is None:
assert_array_almost_equal_nulp(z, np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype='>f8'), 10)
elif boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([[1./8, 5./8, 4./8],
[4./8, 8./8, 7./8],
[4./8, 4./8, 3./8]], dtype='>f8'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype='>f8'), 10)
elif boundary == 'extend':
assert_array_almost_equal_nulp(z, np.array([[2./8, 9./8, 16./8],
[5./8, 8./8, 11./8],
[8./8, 7./8, 6./8]], dtype='>f8'), 10)
else:
raise ValueError("Invalid boundary specification")
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_non_normalized_kernel_2D(self, boundary):
x = np.array([[0., 0., 4.],
[1., 2., 0.],
[0., 3., 0.]], dtype='float')
y = np.array([[1., -1., 1.],
[-1., 0., -1.],
[1., -1., 1.]], dtype='float')
z = convolve(x, y, boundary=boundary, nan_treatment='fill',
normalize_kernel=False)
if boundary is None:
assert_array_almost_equal_nulp(z, np.array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype='float'), 10)
elif boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([[1., -5., 2.],
[1., 0., -3.],
[-2., -1., -1.]], dtype='float'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([[0., -8., 6.],
[5., 0., -4.],
[2., 3., -4.]], dtype='float'), 10)
elif boundary == 'extend':
assert_array_almost_equal_nulp(z, np.array([[2., -1., -2.],
[0., 0., 1.],
[2., -4., 2.]], dtype='float'), 10)
else:
raise ValueError("Invalid boundary specification")
class TestConvolve3D:
def test_list(self):
"""
Test that convolve works correctly when inputs are lists
"""
x = [[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]]
z = convolve(x, x, boundary='fill', fill_value=1, normalize_kernel=False)
assert_array_almost_equal_nulp(z / 27, x, 10)
@pytest.mark.parametrize(('dtype_array', 'dtype_kernel'), VALID_DTYPE_MATRIX)
def test_dtype(self, dtype_array, dtype_kernel):
'''
Test that 32- and 64-bit floats are correctly handled
'''
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]], dtype=dtype_array)
y = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype=dtype_kernel)
z = convolve(x, y)
assert x.dtype == z.dtype
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_unity_1x1x1_none(self, boundary):
'''
Test that a 1x1x1 unit kernel returns the same array
'''
x = np.array([[[1., 2., 1.], [2., 3., 1.], [3., 2., 5.]],
[[4., 3., 1.], [5., 0., 2.], [6., 1., 1.]],
[[7., 0., 2.], [8., 2., 3.], [9., 2., 2.]]], dtype='>f8')
y = np.array([[[1.]]], dtype='>f8')
z = convolve(x, y, boundary=boundary)
assert np.all(z == x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_unity_3x3x3(self, boundary):
'''
Test that a 3x3x3 unit kernel returns the same array (except when
boundary is None).
'''
x = np.array([[[1., 2., 1.], [2., 3., 1.], [3., 2., 5.]],
[[4., 3., 1.], [5., 3., 2.], [6., 1., 1.]],
[[7., 0., 2.], [8., 2., 3.], [9., 2., 2.]]], dtype='>f8')
y = np.zeros((3, 3, 3), dtype='>f8')
y[1, 1, 1] = 1.
z = convolve(x, y, boundary=boundary)
if boundary is None:
assert np.all(z == np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 3., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]], dtype='>f8'))
else:
assert np.all(z == x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_uniform_3x3x3(self, boundary):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel.
'''
x = np.array([[[1., 2., 1.], [2., 3., 1.], [3., 2., 5.]],
[[4., 3., 1.], [5., 3., 2.], [6., 1., 1.]],
[[7., 0., 2.], [8., 2., 3.], [9., 2., 2.]]], dtype='>f8')
y = np.ones((3, 3, 3), dtype='>f8')
z = convolve(x, y, boundary=boundary, normalize_kernel=False)
if boundary is None:
assert_array_almost_equal_nulp(z, np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 81., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]], dtype='>f8'), 10)
elif boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([[[23., 28., 16.], [35., 46., 25.], [25., 34., 18.]],
[[40., 50., 23.], [63., 81., 36.], [46., 60., 27.]],
[[32., 40., 16.], [50., 61., 22.], [36., 44., 16.]]], dtype='>f8'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([[[81., 81., 81.], [81., 81., 81.], [81., 81., 81.]],
[[81., 81., 81.], [81., 81., 81.], [81., 81., 81.]],
[[81., 81., 81.], [81., 81., 81.], [81., 81., 81.]]], dtype='>f8'), 10)
else:
assert_array_almost_equal_nulp(z, np.array([[[65., 54., 43.], [75., 66., 57.], [85., 78., 71.]],
[[96., 71., 46.], [108., 81., 54.], [120., 91., 62.]],
[[127., 88., 49.], [141., 96., 51.], [155., 104., 53.]]], dtype='>f8'), 10)
@pytest.mark.parametrize(('boundary', 'nan_treatment'),
itertools.product(BOUNDARY_OPTIONS,
NANHANDLING_OPTIONS))
def test_unity_3x3x3_withnan(self, boundary, nan_treatment):
'''
Test that a 3x3x3 unit kernel returns the same array (except when
boundary is None). This version includes a NaN value in the original
array.
'''
x = np.array([[[1., 2., 1.], [2., 3., 1.], [3., 2., 5.]],
[[4., 3., 1.], [5., np.nan, 2.], [6., 1., 1.]],
[[7., 0., 2.], [8., 2., 3.], [9., 2., 2.]]], dtype='>f8')
y = np.zeros((3, 3, 3), dtype='>f8')
y[1, 1, 1] = 1.
z = convolve(x, y, boundary=boundary, nan_treatment=nan_treatment,
preserve_nan=True)
assert np.isnan(z[1, 1, 1])
x = np.nan_to_num(z)
z = np.nan_to_num(z)
if boundary is None:
assert np.all(z == np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]], dtype='>f8'))
else:
assert np.all(z == x)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_uniform_3x3x3_withnan_filled(self, boundary):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel. This version includes a NaN value in the
original array.
'''
x = np.array([[[1., 2., 1.], [2., 3., 1.], [3., 2., 5.]],
[[4., 3., 1.], [5., np.nan, 2.], [6., 1., 1.]],
[[7., 0., 2.], [8., 2., 3.], [9., 2., 2.]]], dtype='>f8')
y = np.ones((3, 3, 3), dtype='>f8')
z = convolve(x, y, boundary=boundary, nan_treatment='fill',
normalize_kernel=False)
if boundary is None:
assert_array_almost_equal_nulp(z, np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 78., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]], dtype='>f8'), 10)
elif boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([[[20., 25., 13.],
[32., 43., 22.],
[22., 31., 15.]],
[[37., 47., 20.],
[60., 78., 33.],
[43., 57., 24.]],
[[29., 37., 13.],
[47., 58., 19.],
[33., 41., 13.]]], dtype='>f8'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([[[78., 78., 78.], [78., 78., 78.], [78., 78., 78.]],
[[78., 78., 78.], [78., 78., 78.], [78., 78., 78.]],
[[78., 78., 78.], [78., 78., 78.], [78., 78., 78.]]], dtype='>f8'), 10)
elif boundary == 'extend':
assert_array_almost_equal_nulp(z, np.array([[[62., 51., 40.],
[72., 63., 54.],
[82., 75., 68.]],
[[93., 68., 43.],
[105., 78., 51.],
[117., 88., 59.]],
[[124., 85., 46.],
[138., 93., 48.],
[152., 101., 50.]]],
dtype='>f8'), 10)
else:
raise ValueError("Invalid Boundary Option")
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_uniform_3x3x3_withnan_interped(self, boundary):
'''
Test that the different modes are producing the correct results using
a 3x3 uniform kernel. This version includes a NaN value in the
original array.
'''
x = np.array([[[1., 2., 1.], [2., 3., 1.], [3., 2., 5.]],
[[4., 3., 1.], [5., np.nan, 2.], [6., 1., 1.]],
[[7., 0., 2.], [8., 2., 3.], [9., 2., 2.]]], dtype='>f8')
y = np.ones((3, 3, 3), dtype='>f8')
z = convolve(x, y, boundary=boundary, nan_treatment='interpolate',
normalize_kernel=True)
kernsum = y.sum() - 1 # one nan is missing
mid = x[np.isfinite(x)].sum() / kernsum
if boundary is None:
assert_array_almost_equal_nulp(z, np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 78., 0.], [0., 0., 0.]],
[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]],
dtype='>f8')/kernsum, 10)
elif boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([[[20., 25., 13.],
[32., 43., 22.],
[22., 31., 15.]],
[[37., 47., 20.],
[60., 78., 33.],
[43., 57., 24.]],
[[29., 37., 13.],
[47., 58., 19.],
[33., 41., 13.]]],
dtype='>f8')/kernsum, 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.tile(mid.astype('>f8'), [3, 3, 3]), 10)
elif boundary == 'extend':
assert_array_almost_equal_nulp(z, np.array([[[62., 51., 40.],
[72., 63., 54.],
[82., 75., 68.]],
[[93., 68., 43.],
[105., 78., 51.],
[117., 88., 59.]],
[[124., 85., 46.],
[138., 93., 48.],
[152., 101., 50.]]],
dtype='>f8')/kernsum, 10)
else:
raise ValueError("Invalid Boundary Option")
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_asymmetric_kernel(boundary):
'''
Regression test for #6264: make sure that asymmetric convolution
functions go the right direction
'''
x = np.array([3., 0., 1.], dtype='>f8')
y = np.array([1, 2, 3], dtype='>f8')
z = convolve(x, y, boundary=boundary, normalize_kernel=False)
if boundary == 'fill':
assert_array_almost_equal_nulp(z, np.array([6., 10., 2.], dtype='float'), 10)
elif boundary is None:
assert_array_almost_equal_nulp(z, np.array([0., 10., 0.], dtype='float'), 10)
elif boundary == 'extend':
assert_array_almost_equal_nulp(z, np.array([15., 10., 3.], dtype='float'), 10)
elif boundary == 'wrap':
assert_array_almost_equal_nulp(z, np.array([9., 10., 5.], dtype='float'), 10)
@pytest.mark.parametrize('ndims', (1, 2, 3))
def test_convolution_consistency(ndims):
np.random.seed(0)
array = np.random.randn(*([3]*ndims))
np.random.seed(0)
kernel = np.random.rand(*([3]*ndims))
conv_f = convolve_fft(array, kernel, boundary='fill')
conv_d = convolve(array, kernel, boundary='fill')
assert_array_almost_equal_nulp(conv_f, conv_d, 30)
def test_astropy_convolution_against_numpy():
x = np.array([1, 2, 3])
y = np.array([5, 4, 3, 2, 1])
assert_array_almost_equal(np.convolve(y, x, 'same'),
convolve(y, x, normalize_kernel=False))
assert_array_almost_equal(np.convolve(y, x, 'same'),
convolve_fft(y, x, normalize_kernel=False))
@pytest.mark.skipif('not HAS_SCIPY')
def test_astropy_convolution_against_scipy():
from scipy.signal import fftconvolve
x = np.array([1, 2, 3])
y = np.array([5, 4, 3, 2, 1])
assert_array_almost_equal(fftconvolve(y, x, 'same'),
convolve(y, x, normalize_kernel=False))
assert_array_almost_equal(fftconvolve(y, x, 'same'),
convolve_fft(y, x, normalize_kernel=False))
@pytest.mark.skipif('not HAS_PANDAS')
def test_regression_6099():
import pandas
wave = np.array(np.linspace(5000, 5100, 10))
boxcar = 3
nonseries_result = convolve(wave, np.ones((boxcar,))/boxcar)
wave_series = pandas.Series(wave)
series_result = convolve(wave_series, np.ones((boxcar,))/boxcar)
assert_array_almost_equal(nonseries_result, series_result)
def test_invalid_array_convolve():
kernel = np.ones(3)/3.
with pytest.raises(TypeError):
convolve('glork', kernel)
@pytest.mark.parametrize(('boundary'), BOUNDARY_OPTIONS)
def test_non_square_kernel_asymmetric(boundary):
# Regression test for a bug that occurred when using non-square kernels in
# 2D when using boundary=None
kernel = np.array([[1, 2, 3, 2, 1], [0, 1, 2, 1, 0], [0, 0, 0, 0, 0]])
image = np.zeros((13, 13))
image[6, 6] = 1
result = convolve(image, kernel, normalize_kernel=False, boundary=boundary)
assert_allclose(result[5:8, 4:9], kernel)
@pytest.mark.parametrize(('boundary', 'normalize_kernel'),
itertools.product(BOUNDARY_OPTIONS,
NORMALIZE_OPTIONS))
def test_uninterpolated_nan_regions(boundary, normalize_kernel):
#8086
# Test NaN interpolation of contiguous NaN regions with kernels of size
# identical and greater than that of the region of NaN values.
# Test case: kernel.shape == NaN_region.shape
kernel = Gaussian2DKernel(1, 5, 5)
nan_centroid = np.full(kernel.shape, np.nan)
image = np.pad(nan_centroid, pad_width=kernel.shape[0]*2, mode='constant',
constant_values=1)
with pytest.warns(AstropyUserWarning,
match=r"nan_treatment='interpolate', however, NaN values detected "
r"post convolution. A contiguous region of NaN values, larger "
r"than the kernel size, are present in the input array. "
r"Increase the kernel size to avoid this."):
result = convolve(image, kernel, boundary=boundary, nan_treatment='interpolate',
normalize_kernel=normalize_kernel)
assert(np.any(np.isnan(result)))
# Test case: kernel.shape > NaN_region.shape
nan_centroid = np.full((kernel.shape[0]-1, kernel.shape[1]-1), np.nan) # 1 smaller than kerenel
image = np.pad(nan_centroid, pad_width=kernel.shape[0]*2, mode='constant',
constant_values=1)
result = convolve(image, kernel, boundary=boundary, nan_treatment='interpolate',
normalize_kernel=normalize_kernel)
assert(~np.any(np.isnan(result))) # Note: negation
def test_regressiontest_issue9168():
"""
Issue #9168 pointed out that kernels can be (unitless) quantities, which
leads to crashes when inplace modifications are made to arrays in
convolve/convolve_fft, so we now strip the quantity aspects off of kernels.
"""
x = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]],)
kernel_fwhm = 1*u.arcsec
pixel_size = 1*u.arcsec
kernel = Gaussian2DKernel(x_stddev=kernel_fwhm/pixel_size)
result = convolve_fft(x, kernel, boundary='fill', fill_value=np.nan,
preserve_nan=True)
result = convolve(x, kernel, boundary='fill', fill_value=np.nan,
preserve_nan=True)
def test_convolve_nan_zero_sum_kernel():
with pytest.raises(ValueError,
match="Setting nan_treatment='interpolate' "
"requires the kernel to be normalized, but the "
"input kernel has a sum close to zero. For a "
"zero-sum kernel and data with NaNs, set "
"nan_treatment='fill'."):
convolve([1, np.nan, 3], [-1, 2, -1], normalize_kernel=False)
|
71167bf445d94478e88a024dcf193a8bf678c87ba483e4370d39c0996881af35 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import math
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_almost_equal
from astropy.convolution.convolve import convolve, convolve_fft, convolve_models
from astropy.modeling import fitting, models
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
from astropy.utils.misc import NumpyRNGContext
class TestConvolve1DModels:
@pytest.mark.parametrize('mode', ['convolve_fft', 'convolve'])
@pytest.mark.skipif('not HAS_SCIPY')
def test_is_consistency_with_astropy_convolution(self, mode):
kernel = models.Gaussian1D(1, 0, 1)
model = models.Gaussian1D(1, 0, 1)
model_conv = convolve_models(model, kernel, mode=mode)
x = np.arange(-5, 6)
ans = eval(f"{mode}(model(x), kernel(x))")
assert_allclose(ans, model_conv(x), atol=1e-5)
@pytest.mark.parametrize('mode', ['convolve_fft', 'convolve'])
@pytest.mark.skipif('not HAS_SCIPY')
def test_against_scipy(self, mode):
from scipy.signal import fftconvolve
kernel = models.Gaussian1D(1, 0, 1)
model = models.Gaussian1D(1, 0, 1)
model_conv = convolve_models(model, kernel, mode=mode)
x = np.arange(-5, 6)
ans = fftconvolve(kernel(x), model(x), mode='same')
assert_allclose(ans, model_conv(x) * kernel(x).sum(), atol=1e-5)
@pytest.mark.parametrize('mode', ['convolve_fft', 'convolve'])
@pytest.mark.skipif('not HAS_SCIPY')
def test_against_scipy_with_additional_keywords(self, mode):
from scipy.signal import fftconvolve
kernel = models.Gaussian1D(1, 0, 1)
model = models.Gaussian1D(1, 0, 1)
model_conv = convolve_models(model, kernel, mode=mode,
normalize_kernel=False)
x = np.arange(-5, 6)
ans = fftconvolve(kernel(x), model(x), mode='same')
assert_allclose(ans, model_conv(x), atol=1e-5)
@pytest.mark.parametrize('mode', ['convolve_fft', 'convolve'])
def test_sum_of_gaussians(self, mode):
"""
Test that convolving N(a, b) with N(c, d) gives N(a + c, b + d),
where N(., .) stands for Gaussian probability density function,
in which a and c are their means and b and d are their variances.
"""
kernel = models.Gaussian1D(1 / math.sqrt(2 * np.pi), 1, 1)
model = models.Gaussian1D(1 / math.sqrt(2 * np.pi), 3, 1)
model_conv = convolve_models(model, kernel, mode=mode,
normalize_kernel=False)
ans = models.Gaussian1D(1 / (2 * math.sqrt(np.pi)), 4, np.sqrt(2))
x = np.arange(-5, 6)
assert_allclose(ans(x), model_conv(x), atol=1e-3)
@pytest.mark.parametrize('mode', ['convolve_fft', 'convolve'])
def test_convolve_box_models(self, mode):
kernel = models.Box1D()
model = models.Box1D()
model_conv = convolve_models(model, kernel, mode=mode)
x = np.linspace(-1, 1, 99)
ans = (x + 1) * (x < 0) + (-x + 1) * (x >= 0)
assert_allclose(ans, model_conv(x), atol=1e-3)
@pytest.mark.parametrize('mode', ['convolve_fft', 'convolve'])
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitting_convolve_models(self, mode):
"""
test that a convolve model can be fitted
"""
b1 = models.Box1D()
g1 = models.Gaussian1D()
x = np.linspace(-5, 5, 99)
fake_model = models.Gaussian1D(amplitude=10)
with NumpyRNGContext(123):
fake_data = fake_model(x) + np.random.normal(size=len(x))
init_model = convolve_models(b1, g1, mode=mode, normalize_kernel=False)
fitter = fitting.LevMarLSQFitter()
fitted_model = fitter(init_model, x, fake_data)
me = np.mean(fitted_model(x) - fake_data)
assert_almost_equal(me, 0.0, decimal=2)
|
c96771313e5df05cc30d4ccb89708d4c24376f1bc65b98044eb0a4cef3ea2b88 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import timeit
import numpy as np # pylint: disable=W0611
# largest image size to use for "linear" and fft convolutions
max_exponents_linear = {1: 15, 2: 7, 3: 5}
max_exponents_fft = {1: 15, 2: 10, 3: 7}
if __name__ == "__main__":
for ndims in [1, 2, 3]:
print("\n{}-dimensional arrays ('n' is the size of the image AND "
"the kernel)".format(ndims))
print(" ".join(["%17s" % n for n in ("n", "convolve", "convolve_fft")]))
for ii in range(3, max_exponents_fft[ndims]):
# array = np.random.random([2**ii]*ndims)
# test ODD sizes too
if ii < max_exponents_fft[ndims]:
setup = ("""
import numpy as np
from astropy.convolution.convolve import convolve
from astropy.convolution.convolve import convolve_fft
array = np.random.random([%i]*%i)
kernel = np.random.random([%i]*%i)""") % (2 ** ii - 1, ndims, 2 ** ii - 1, ndims)
print("%16i:" % (int(2 ** ii - 1)), end=' ')
if ii <= max_exponents_linear[ndims]:
for convolve_type, extra in zip(("", "_fft"),
("", "fft_pad=False")):
statement = f"convolve{convolve_type}(array, kernel, boundary='fill', {extra})"
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
print(f"{besttime:17f}", end=' ')
else:
print("%17s" % "skipped", end=' ')
statement = "convolve_fft(array, kernel, boundary='fill')"
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
print(f"{besttime:17f}", end=' ')
print()
setup = ("""
import numpy as np
from astropy.convolution.convolve import convolve
from astropy.convolution.convolve import convolve_fft
array = np.random.random([%i]*%i)
kernel = np.random.random([%i]*%i)""") % (2 ** ii, ndims, 2 ** ii, ndims)
print("%16i:" % (int(2 ** ii)), end=' ')
if ii <= max_exponents_linear[ndims]:
for convolve_type in ("", "_fft",):
# convolve doesn't allow even-sized kernels
if convolve_type == "":
print("%17s" % ("-"), end=' ')
else:
statement = f"convolve{convolve_type}(array, kernel, boundary='fill')"
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
print(f"{besttime:17f}", end=' ')
else:
print("%17s" % "skipped", end=' ')
statement = "convolve_fft(array, kernel, boundary='fill')"
besttime = min(timeit.Timer(stmt=statement, setup=setup).repeat(3, 10))
print(f"{besttime:17f}", end=' ')
print()
"""
Unfortunately, these tests are pretty strongly inconclusive
NOTE: Runtime has units seconds and represents wall clock time.
RESULTS on a late 2013 Mac Pro:
3.5 GHz 6-Core Intel Xeon E5
32 GB 1866 MHz DDR3 ECC
Python 3.5.4 :: Anaconda custom (x86_64)
clang version 6.0.0 (tags/RELEASE_600/final)
llvm-opnemp r327556 | grokos | 2018-03-14 15:11:36 -0400 (Wed, 14 Mar 2018)
With OpenMP (hyperthreaded 12procs), convolve() only:
1-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fft
7: 0.002895 0.007321
15: 0.002684 0.008028
31: 0.002733 0.008684
63: 0.002728 0.009127
127: 0.002851 0.012659
255: 0.002835 0.010550
511: 0.003051 0.017137
1023: 0.004042 0.019384
2047: 0.007371 0.049246
4095: 0.021903 0.039821
8191: 0.067098 8.335749
16383: 0.256072 0.272165
2-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fft
7: 0.002696 0.014745
15: 0.002839 0.014826
31: 0.004286 0.045167
63: 0.022941 0.063715
127: 0.325557 0.925577
255: skipped 0.694621
511: skipped 3.734946
3-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fft
7: 0.003502 0.033121
8: 0.003407 0.030351
15: 0.026338 0.062235
31: 1.239503 1.586930
63: skipped 10.792675
With OpenMP but single threaded (n_threads = 1), convolve() only:
1-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fft
7: 0.001754 0.004687
15: 0.001706 0.005133
31: 0.001744 0.005381
63: 0.001725 0.005582
127: 0.001801 0.007405
255: 0.002262 0.006528
511: 0.003866 0.009913
1023: 0.009820 0.011511
2047: 0.034707 0.028171
4095: 0.132908 0.024133
8191: 0.527692 8.311933
16383: 2.103046 0.269368
2-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fft
7: 0.001734 0.009458
15: 0.002336 0.010310
31: 0.009123 0.025427
63: 0.126701 0.040610
127: 2.126114 0.926549
255: skipped 0.690896
511: skipped 3.756475
3-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fft
7: 0.002822 0.019498
15: 0.096008 0.063744
31: 7.373533 1.578913
63: skipped 10.811530
RESULTS on a 2011 Mac Air:
1-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fftnp convolve_fftw convolve_fftsp
7: 0.000408 0.002334 0.005571 0.002677
15: 0.000361 0.002491 0.005648 0.002678
31: 0.000535 0.002450 0.005988 0.002880
63: 0.000509 0.002876 0.008003 0.002981
127: 0.000801 0.004080 0.008513 0.003932
255: 0.002453 0.003111 0.007518 0.003564
511: 0.008394 0.006224 0.010247 0.005991
1023: 0.028741 0.007538 0.009591 0.007696
2047: 0.106323 0.021575 0.022041 0.020682
4095: 0.411936 0.021675 0.019761 0.020939
8191: 1.664517 8.278320 0.073001 7.803563
16383: 6.654678 0.251661 0.202271 0.222171
2-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fftnp convolve_fftw convolve_fftsp
7: 0.000552 0.003524 0.006667 0.004318
15: 0.002986 0.005093 0.012941 0.005951
31: 0.074360 0.033973 0.031800 0.036937
63: 0.848471 0.057407 0.052192 0.053213
127: 14.656414 1.005329 0.402113 0.955279
255: skipped 1.715546 1.566876 1.745338
511: skipped 4.066155 4.303350 3.930661
3-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fftnp convolve_fftw convolve_fftsp
7: 0.009239 0.012957 0.011957 0.015997
15: 0.772434 0.075621 0.056711 0.079508
31: 62.824051 2.295193 1.189505 2.351136
63: skipped 11.250225 10.982726 10.585744
On a 2009 Mac Pro:
1-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fftnp convolve_fftw convolve_fftsp
7: 0.000360 0.002269 0.004986 0.002476
15: 0.000364 0.002255 0.005244 0.002471
31: 0.000385 0.002380 0.005422 0.002588
63: 0.000474 0.002407 0.005392 0.002637
127: 0.000752 0.004122 0.007827 0.003966
255: 0.004316 0.003258 0.006566 0.003324
511: 0.011517 0.007158 0.009898 0.006238
1023: 0.034105 0.009211 0.009468 0.008260
2047: 0.113620 0.028097 0.020662 0.021603
4095: 0.403373 0.023211 0.018767 0.020065
8191: 1.519329 8.454573 0.211436 7.212381
16383: 5.887481 0.317428 0.153344 0.237119
2-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fftnp convolve_fftw convolve_fftsp
7: 0.000474 0.003470 0.006131 0.003503
15: 0.002011 0.004481 0.007825 0.004496
31: 0.027291 0.019433 0.014841 0.018034
63: 0.445680 0.038171 0.026753 0.037404
127: 7.003774 0.925921 0.282591 0.762671
255: skipped 0.804682 0.708849 0.869368
511: skipped 3.643626 3.687562 4.584770
3-dimensional arrays ('n' is the size of the image AND the kernel)
n convolve convolve_fftnp convolve_fftw convolve_fftsp
7: 0.004520 0.011519 0.009464 0.012335
15: 0.329566 0.060978 0.045495 0.073692
31: 24.935228 1.654920 0.710509 1.773879
63: skipped 8.982771 12.407683 16.900078
"""
|
234ae0c5d937ad37acbe0f796d2d7c16a9861afe5c2ed22ffe34813a627186ee | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import io
import os
import sys
import subprocess
import pytest
from astropy.config import (configuration, set_temp_config, paths,
create_config_file)
from astropy.utils.data import get_pkg_data_filename
from astropy.utils.exceptions import AstropyDeprecationWarning
OLD_CONFIG = {}
def setup_module():
OLD_CONFIG.clear()
OLD_CONFIG.update(configuration._cfgobjs)
def teardown_module():
configuration._cfgobjs.clear()
configuration._cfgobjs.update(OLD_CONFIG)
def test_paths():
assert 'astropy' in paths.get_config_dir()
assert 'astropy' in paths.get_cache_dir()
assert 'testpkg' in paths.get_config_dir(rootname='testpkg')
assert 'testpkg' in paths.get_cache_dir(rootname='testpkg')
def test_set_temp_config(tmpdir, monkeypatch):
# Check that we start in an understood state.
assert configuration._cfgobjs == OLD_CONFIG
# Temporarily remove any temporary overrides of the configuration dir.
monkeypatch.setattr(paths.set_temp_config, '_temp_path', None)
orig_config_dir = paths.get_config_dir(rootname='astropy')
temp_config_dir = str(tmpdir.mkdir('config'))
temp_astropy_config = os.path.join(temp_config_dir, 'astropy')
# Test decorator mode
@paths.set_temp_config(temp_config_dir)
def test_func():
assert paths.get_config_dir(rootname='astropy') == temp_astropy_config
# Test temporary restoration of original default
with paths.set_temp_config() as d:
assert d == orig_config_dir == paths.get_config_dir(rootname='astropy')
test_func()
# Test context manager mode (with cleanup)
with paths.set_temp_config(temp_config_dir, delete=True):
assert paths.get_config_dir(rootname='astropy') == temp_astropy_config
assert not os.path.exists(temp_config_dir)
# Check that we have returned to our old configuration.
assert configuration._cfgobjs == OLD_CONFIG
def test_set_temp_cache(tmpdir, monkeypatch):
monkeypatch.setattr(paths.set_temp_cache, '_temp_path', None)
orig_cache_dir = paths.get_cache_dir(rootname='astropy')
temp_cache_dir = str(tmpdir.mkdir('cache'))
temp_astropy_cache = os.path.join(temp_cache_dir, 'astropy')
# Test decorator mode
@paths.set_temp_cache(temp_cache_dir)
def test_func():
assert paths.get_cache_dir(rootname='astropy') == temp_astropy_cache
# Test temporary restoration of original default
with paths.set_temp_cache() as d:
assert d == orig_cache_dir == paths.get_cache_dir(rootname='astropy')
test_func()
# Test context manager mode (with cleanup)
with paths.set_temp_cache(temp_cache_dir, delete=True):
assert paths.get_cache_dir(rootname='astropy') == temp_astropy_cache
assert not os.path.exists(temp_cache_dir)
def test_set_temp_cache_resets_on_exception(tmpdir):
"""Test for regression of bug #9704"""
t = paths.get_cache_dir()
a = tmpdir / 'a'
with open(a, 'wt') as f:
f.write("not a good cache\n")
with pytest.raises(OSError):
with paths.set_temp_cache(a):
pass
assert t == paths.get_cache_dir()
def test_config_file():
from astropy.config.configuration import get_config, reload_config
apycfg = get_config('astropy')
assert apycfg.filename.endswith('astropy.cfg')
cfgsec = get_config('astropy.config')
assert cfgsec.depth == 1
assert cfgsec.name == 'config'
assert cfgsec.parent.filename.endswith('astropy.cfg')
# try with a different package name, still inside astropy config dir:
testcfg = get_config('testpkg', rootname='astropy')
parts = os.path.normpath(testcfg.filename).split(os.sep)
assert '.astropy' in parts or 'astropy' in parts
assert parts[-1] == 'testpkg.cfg'
configuration._cfgobjs['testpkg'] = None # HACK
# try with a different package name, no specified root name (should
# default to astropy):
testcfg = get_config('testpkg')
parts = os.path.normpath(testcfg.filename).split(os.sep)
assert '.astropy' in parts or 'astropy' in parts
assert parts[-1] == 'testpkg.cfg'
configuration._cfgobjs['testpkg'] = None # HACK
# try with a different package name, specified root name:
testcfg = get_config('testpkg', rootname='testpkg')
parts = os.path.normpath(testcfg.filename).split(os.sep)
assert '.testpkg' in parts or 'testpkg' in parts
assert parts[-1] == 'testpkg.cfg'
configuration._cfgobjs['testpkg'] = None # HACK
# try with a subpackage with specified root name:
testcfg_sec = get_config('testpkg.somemodule', rootname='testpkg')
parts = os.path.normpath(testcfg_sec.parent.filename).split(os.sep)
assert '.testpkg' in parts or 'testpkg' in parts
assert parts[-1] == 'testpkg.cfg'
configuration._cfgobjs['testpkg'] = None # HACK
reload_config('astropy')
def check_config(conf):
# test that the output contains some lines that we expect
assert '# unicode_output = False' in conf
assert '[io.fits]' in conf
assert '[table]' in conf
assert '# replace_warnings = ,' in conf
assert '[table.jsviewer]' in conf
assert '# css_urls = https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css,' in conf
assert '[visualization.wcsaxes]' in conf
assert '## Whether to log exceptions before raising them.' in conf
assert '# log_exceptions = False' in conf
def test_generate_config(tmp_path):
from astropy.config.configuration import generate_config
out = io.StringIO()
generate_config('astropy', out)
conf = out.getvalue()
outfile = tmp_path / 'astropy.cfg'
generate_config('astropy', outfile)
with open(outfile) as fp:
conf2 = fp.read()
for c in (conf, conf2):
check_config(c)
def test_generate_config2(tmp_path):
"""Test that generate_config works with the default filename."""
with set_temp_config(tmp_path):
from astropy.config.configuration import generate_config
generate_config('astropy')
assert os.path.exists(tmp_path / 'astropy' / 'astropy.cfg')
with open(tmp_path / 'astropy' / 'astropy.cfg') as fp:
conf = fp.read()
check_config(conf)
def test_create_config_file(tmp_path, caplog):
with set_temp_config(tmp_path):
create_config_file('astropy')
# check that the config file has been created
assert ('The configuration file has been successfully written'
in caplog.records[0].message)
assert os.path.exists(tmp_path / 'astropy' / 'astropy.cfg')
with open(tmp_path / 'astropy' / 'astropy.cfg') as fp:
conf = fp.read()
check_config(conf)
caplog.clear()
# now modify the config file
conf = conf.replace('# unicode_output = False', 'unicode_output = True')
with open(tmp_path / 'astropy' / 'astropy.cfg', mode='w') as fp:
fp.write(conf)
with set_temp_config(tmp_path):
create_config_file('astropy')
# check that the config file has not been overwritten since it was modified
assert ('The configuration file already exists and seems to have been '
'customized' in caplog.records[0].message)
caplog.clear()
with set_temp_config(tmp_path):
create_config_file('astropy', overwrite=True)
# check that the config file has been overwritten
assert ('The configuration file has been successfully written'
in caplog.records[0].message)
def test_configitem():
from astropy.config.configuration import ConfigNamespace, ConfigItem, get_config
ci = ConfigItem(34, 'this is a Description')
class Conf(ConfigNamespace):
tstnm = ci
conf = Conf()
assert ci.module == 'astropy.config.tests.test_configs'
assert ci() == 34
assert ci.description == 'this is a Description'
assert conf.tstnm == 34
sec = get_config(ci.module)
assert sec['tstnm'] == 34
ci.description = 'updated Descr'
ci.set(32)
assert ci() == 32
# It's useful to go back to the default to allow other test functions to
# call this one and still be in the default configuration.
ci.description = 'this is a Description'
ci.set(34)
assert ci() == 34
# Test iterator for one-item namespace
result = [x for x in conf]
assert result == ['tstnm']
result = [x for x in conf.keys()]
assert result == ['tstnm']
result = [x for x in conf.values()]
assert result == [ci]
result = [x for x in conf.items()]
assert result == [('tstnm', ci)]
def test_configitem_types():
from astropy.config.configuration import ConfigNamespace, ConfigItem
ci1 = ConfigItem(34)
ci2 = ConfigItem(34.3)
ci3 = ConfigItem(True)
ci4 = ConfigItem('astring')
class Conf(ConfigNamespace):
tstnm1 = ci1
tstnm2 = ci2
tstnm3 = ci3
tstnm4 = ci4
conf = Conf()
assert isinstance(conf.tstnm1, int)
assert isinstance(conf.tstnm2, float)
assert isinstance(conf.tstnm3, bool)
assert isinstance(conf.tstnm4, str)
with pytest.raises(TypeError):
conf.tstnm1 = 34.3
conf.tstnm2 = 12 # this would should succeed as up-casting
with pytest.raises(TypeError):
conf.tstnm3 = 'fasd'
with pytest.raises(TypeError):
conf.tstnm4 = 546.245
# Test iterator for multi-item namespace. Assume ordered by insertion order.
item_names = [x for x in conf]
assert item_names == ['tstnm1', 'tstnm2', 'tstnm3', 'tstnm4']
result = [x for x in conf.keys()]
assert result == item_names
result = [x for x in conf.values()]
assert result == [ci1, ci2, ci3, ci4]
result = [x for x in conf.items()]
assert result == [('tstnm1', ci1), ('tstnm2', ci2), ('tstnm3', ci3), ('tstnm4', ci4)]
def test_configitem_options(tmpdir):
from astropy.config.configuration import ConfigNamespace, ConfigItem, get_config
cio = ConfigItem(['op1', 'op2', 'op3'])
class Conf(ConfigNamespace):
tstnmo = cio
conf = Conf() # noqa
sec = get_config(cio.module)
assert isinstance(cio(), str)
assert cio() == 'op1'
assert sec['tstnmo'] == 'op1'
cio.set('op2')
with pytest.raises(TypeError):
cio.set('op5')
assert sec['tstnmo'] == 'op2'
# now try saving
apycfg = sec
while apycfg.parent is not apycfg:
apycfg = apycfg.parent
f = tmpdir.join('astropy.cfg')
with open(f.strpath, 'wb') as fd:
apycfg.write(fd)
with open(f.strpath, 'r', encoding='utf-8') as fd:
lns = [x.strip() for x in f.readlines()]
assert 'tstnmo = op2' in lns
def test_config_noastropy_fallback(monkeypatch):
"""
Tests to make sure configuration items fall back to their defaults when
there's a problem accessing the astropy directory
"""
# make sure the config directory is not searched
monkeypatch.setenv('XDG_CONFIG_HOME', 'foo')
monkeypatch.delenv('XDG_CONFIG_HOME')
monkeypatch.setattr(paths.set_temp_config, '_temp_path', None)
# make sure the _find_or_create_root_dir function fails as though the
# astropy dir could not be accessed
def osraiser(dirnm, linkto, pkgname=None):
raise OSError
monkeypatch.setattr(paths, '_find_or_create_root_dir', osraiser)
# also have to make sure the stored configuration objects are cleared
monkeypatch.setattr(configuration, '_cfgobjs', {})
with pytest.raises(OSError):
# make sure the config dir search fails
paths.get_config_dir(rootname='astropy')
# now run the basic tests, and make sure the warning about no astropy
# is present
test_configitem()
def test_configitem_setters():
from astropy.config.configuration import ConfigNamespace, ConfigItem
class Conf(ConfigNamespace):
tstnm12 = ConfigItem(42, 'this is another Description')
conf = Conf()
assert conf.tstnm12 == 42
with conf.set_temp('tstnm12', 45):
assert conf.tstnm12 == 45
assert conf.tstnm12 == 42
conf.tstnm12 = 43
assert conf.tstnm12 == 43
with conf.set_temp('tstnm12', 46):
assert conf.tstnm12 == 46
# Make sure it is reset even with Exception
try:
with conf.set_temp('tstnm12', 47):
raise Exception
except Exception:
pass
assert conf.tstnm12 == 43
def test_empty_config_file():
from astropy.config.configuration import is_unedited_config_file
def get_content(fn):
with open(get_pkg_data_filename(fn), 'rt', encoding='latin-1') as fd:
return fd.read()
content = get_content('data/empty.cfg')
assert is_unedited_config_file(content)
content = get_content('data/not_empty.cfg')
assert not is_unedited_config_file(content)
class TestAliasRead:
def setup_class(self):
configuration._override_config_file = get_pkg_data_filename('data/alias.cfg')
def test_alias_read(self):
from astropy.utils.data import conf
with pytest.warns(
AstropyDeprecationWarning,
match=r"Config parameter 'name_resolve_timeout' in section "
r"\[coordinates.name_resolve\].*") as w:
conf.reload()
assert conf.remote_timeout == 42
assert len(w) == 1
def teardown_class(self):
from astropy.utils.data import conf
configuration._override_config_file = None
conf.reload()
def test_configitem_unicode(tmpdir):
from astropy.config.configuration import ConfigNamespace, ConfigItem, get_config
cio = ConfigItem('ასტრონომიის')
class Conf(ConfigNamespace):
tstunicode = cio
conf = Conf() # noqa
sec = get_config(cio.module)
assert isinstance(cio(), str)
assert cio() == 'ასტრონომიის'
assert sec['tstunicode'] == 'ასტრონომიის'
def test_warning_move_to_top_level():
# Check that the warning about deprecation config items in the
# file works. See #2514
from astropy import conf
configuration._override_config_file = get_pkg_data_filename('data/deprecated.cfg')
try:
with pytest.warns(AstropyDeprecationWarning) as w:
conf.reload()
conf.max_lines
assert len(w) == 1
finally:
configuration._override_config_file = None
conf.reload()
def test_no_home():
# "import astropy" fails when neither $HOME or $XDG_CONFIG_HOME
# are set. To test, we unset those environment variables for a
# subprocess and try to import astropy.
test_path = os.path.dirname(__file__)
astropy_path = os.path.abspath(
os.path.join(test_path, '..', '..', '..'))
env = os.environ.copy()
paths = [astropy_path]
if env.get('PYTHONPATH'):
paths.append(env.get('PYTHONPATH'))
env['PYTHONPATH'] = os.pathsep.join(paths)
for val in ['HOME', 'XDG_CONFIG_HOME']:
if val in env:
del env[val]
retcode = subprocess.check_call(
[sys.executable, '-c', 'import astropy'],
env=env)
assert retcode == 0
|
430ed5da429a7e8b4083361653c32f9a84b10b51d9068557440e138bd8013f89 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from astropy import units as u
from astropy.coordinates import Angle
from astropy.uncertainty.core import Distribution
from astropy.uncertainty import distributions as ds
from astropy.utils import NumpyRNGContext
from astropy.tests.helper import assert_quantity_allclose
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
if HAS_SCIPY:
from scipy.stats import norm # pylint: disable=W0611
SMAD_FACTOR = 1 / norm.ppf(0.75)
class TestInit:
@classmethod
def setup_class(self):
self.rates = np.array([1, 5, 30, 400])[:, np.newaxis]
self.parr = np.random.poisson(self.rates, (4, 1000))
self.parr_t = np.random.poisson(self.rates.squeeze(), (1000, 4))
def test_numpy_init(self):
# Test that we can initialize directly from a Numpy array
Distribution(self.parr)
def test_numpy_init_T(self):
Distribution(self.parr_t.T)
def test_quantity_init(self):
# Test that we can initialize directly from a Quantity
pq = self.parr << u.ct
pqd = Distribution(pq)
assert isinstance(pqd, u.Quantity)
assert isinstance(pqd, Distribution)
assert isinstance(pqd.value, Distribution)
assert_array_equal(pqd.value.distribution, self.parr)
def test_quantity_init_T(self):
# Test that we can initialize directly from a Quantity
pq = self.parr_t << u.ct
Distribution(pq.T)
def test_quantity_init_with_distribution(self):
# Test that we can initialize a Quantity from a Distribution.
pd = Distribution(self.parr)
qpd = pd << u.ct
assert isinstance(qpd, u.Quantity)
assert isinstance(qpd, Distribution)
assert qpd.unit == u.ct
assert_array_equal(qpd.value.distribution, pd.distribution.astype(float))
def test_init_scalar():
parr = np.random.poisson(np.array([1, 5, 30, 400])[:, np.newaxis],
(4, 1000))
with pytest.raises(TypeError) as exc:
Distribution(parr.ravel()[0])
assert exc.value.args[0] == "Attempted to initialize a Distribution with a scalar"
class TestDistributionStatistics():
def setup_class(self):
with NumpyRNGContext(12345):
self.data = np.random.normal(np.array([1, 2, 3, 4])[:, np.newaxis],
np.array([3, 2, 4, 5])[:, np.newaxis],
(4, 10000))
self.distr = Distribution(self.data * u.kpc)
def test_shape(self):
# Distribution shape
assert self.distr.shape == (4, )
assert self.distr.distribution.shape == (4, 10000)
def test_size(self):
# Total number of values
assert self.distr.size == 4
assert self.distr.distribution.size == 40000
def test_n_samples(self):
# Number of samples
assert self.distr.n_samples == 10000
def test_n_distr(self):
assert self.distr.shape == (4,)
def test_pdf_mean(self):
# Mean of each PDF
expected = np.mean(self.data, axis=-1) * self.distr.unit
pdf_mean = self.distr.pdf_mean()
assert_quantity_allclose(pdf_mean, expected)
assert_quantity_allclose(pdf_mean, [1, 2, 3, 4] * self.distr.unit, rtol=0.05)
# make sure the right type comes out - should be a Quantity because it's
# now a summary statistic
assert not isinstance(pdf_mean, Distribution)
assert isinstance(pdf_mean, u.Quantity)
# Check with out argument.
out = pdf_mean * 0.
pdf_mean2 = self.distr.pdf_mean(out=out)
assert pdf_mean2 is out
assert np.all(pdf_mean2 == pdf_mean)
def test_pdf_std(self):
# Standard deviation of each PDF
expected = np.std(self.data, axis=-1) * self.distr.unit
pdf_std = self.distr.pdf_std()
assert_quantity_allclose(pdf_std, expected)
assert_quantity_allclose(pdf_std, [3, 2, 4, 5] * self.distr.unit, rtol=0.05)
# make sure the right type comes out - should be a Quantity because it's
# now a summary statistic
assert not isinstance(pdf_std, Distribution)
assert isinstance(pdf_std, u.Quantity)
# Check with proper ddof, using out argument.
out = pdf_std * 0.
expected = np.std(self.data, axis=-1, ddof=1) * self.distr.unit
pdf_std2 = self.distr.pdf_std(ddof=1, out=out)
assert pdf_std2 is out
assert np.all(pdf_std2 == expected)
def test_pdf_var(self):
# Variance of each PDF
expected = np.var(self.data, axis=-1) * self.distr.unit**2
pdf_var = self.distr.pdf_var()
assert_quantity_allclose(pdf_var, expected)
assert_quantity_allclose(pdf_var, [9, 4, 16, 25] * self.distr.unit**2, rtol=0.1)
# make sure the right type comes out - should be a Quantity because it's
# now a summary statistic
assert not isinstance(pdf_var, Distribution)
assert isinstance(pdf_var, u.Quantity)
# Check with proper ddof, using out argument.
out = pdf_var * 0.
expected = np.var(self.data, axis=-1, ddof=1) * self.distr.unit**2
pdf_var2 = self.distr.pdf_var(ddof=1, out=out)
assert pdf_var2 is out
assert np.all(pdf_var2 == expected)
def test_pdf_median(self):
# Median of each PDF
expected = np.median(self.data, axis=-1) * self.distr.unit
pdf_median = self.distr.pdf_median()
assert_quantity_allclose(pdf_median, expected)
assert_quantity_allclose(pdf_median, [1, 2, 3, 4] * self.distr.unit, rtol=0.1)
# make sure the right type comes out - should be a Quantity because it's
# now a summary statistic
assert not isinstance(pdf_median, Distribution)
assert isinstance(pdf_median, u.Quantity)
# Check with out argument.
out = pdf_median * 0.
pdf_median2 = self.distr.pdf_median(out=out)
assert pdf_median2 is out
assert np.all(pdf_median2 == expected)
@pytest.mark.skipif(not HAS_SCIPY, reason='no scipy')
def test_pdf_mad_smad(self):
# Median absolute deviation of each PDF
median = np.median(self.data, axis=-1, keepdims=True)
expected = np.median(np.abs(self.data - median), axis=-1) * self.distr.unit
pdf_mad = self.distr.pdf_mad()
assert_quantity_allclose(pdf_mad, expected)
pdf_smad = self.distr.pdf_smad()
assert_quantity_allclose(pdf_smad, pdf_mad * SMAD_FACTOR, rtol=1e-5)
assert_quantity_allclose(pdf_smad, [3, 2, 4, 5] * self.distr.unit, rtol=0.05)
# make sure the right type comes out - should be a Quantity because it's
# now a summary statistic
assert not isinstance(pdf_mad, Distribution)
assert isinstance(pdf_mad, u.Quantity)
assert not isinstance(pdf_smad, Distribution)
assert isinstance(pdf_smad, u.Quantity)
# Check out argument for smad (which checks mad too).
out = pdf_smad * 0.
pdf_smad2 = self.distr.pdf_smad(out=out)
assert pdf_smad2 is out
assert np.all(pdf_smad2 == pdf_smad)
def test_percentile(self):
expected = np.percentile(self.data, [10, 50, 90], axis=-1) * self.distr.unit
percs = self.distr.pdf_percentiles([10, 50, 90])
assert_quantity_allclose(percs, expected)
assert percs.shape == (3, 4)
# make sure the right type comes out - should be a Quantity because it's
# now a summary statistic
assert not isinstance(percs, Distribution)
assert isinstance(percs, u.Quantity)
def test_add_quantity(self):
distrplus = self.distr + [2000, 0, 0, 500] * u.pc
expected = (np.median(self.data, axis=-1) + np.array([2, 0, 0, 0.5])) * self.distr.unit
assert_quantity_allclose(distrplus.pdf_median(), expected)
expected = np.var(self.data, axis=-1) * self.distr.unit**2
assert_quantity_allclose(distrplus.pdf_var(), expected)
def test_add_distribution(self):
another_data = (np.random.randn(4, 10000)
* np.array([1000, .01, 80, 10])[:, np.newaxis]
+ np.array([2000, 0, 0, 500])[:, np.newaxis])
# another_data is in pc, but main distr is in kpc
another_distr = Distribution(another_data * u.pc)
combined_distr = self.distr + another_distr
expected = np.median(self.data + another_data/1000,
axis=-1) * self.distr.unit
assert_quantity_allclose(combined_distr.pdf_median(), expected)
expected = np.var(self.data + another_data/1000, axis=-1) * self.distr.unit**2
assert_quantity_allclose(combined_distr.pdf_var(), expected)
def test_helper_normal_samples():
centerq = [1, 5, 30, 400] * u.kpc
with NumpyRNGContext(12345):
n_dist = ds.normal(centerq, std=[0.2, 1.5, 4, 1]*u.kpc, n_samples=100)
assert n_dist.distribution.shape == (4, 100)
assert n_dist.shape == (4, )
assert n_dist.unit == u.kpc
assert np.all(n_dist.pdf_std() > 100*u.pc)
n_dist2 = ds.normal(centerq, std=[0.2, 1.5, 4, 1]*u.pc, n_samples=20000)
assert n_dist2.distribution.shape == (4, 20000)
assert n_dist2.shape == (4, )
assert n_dist2.unit == u.kpc
assert np.all(n_dist2.pdf_std() < 100*u.pc)
def test_helper_poisson_samples():
centerqcounts = [1, 5, 30, 400] * u.count
with NumpyRNGContext(12345):
p_dist = ds.poisson(centerqcounts, n_samples=100)
assert p_dist.shape == (4,)
assert p_dist.distribution.shape == (4, 100)
assert p_dist.unit == u.count
p_min = np.min(p_dist)
assert isinstance(p_min, Distribution)
assert p_min.shape == ()
assert np.all(p_min >= 0)
assert np.all(np.abs(p_dist.pdf_mean() - centerqcounts) < centerqcounts)
def test_helper_uniform_samples():
udist = ds.uniform(lower=[1, 2]*u.kpc, upper=[3, 4]*u.kpc, n_samples=1000)
assert udist.shape == (2, )
assert udist.distribution.shape == (2, 1000)
assert np.all(np.min(udist.distribution, axis=-1) > [1, 2]*u.kpc)
assert np.all(np.max(udist.distribution, axis=-1) < [3, 4]*u.kpc)
# try the alternative creator
udist = ds.uniform(center=[1, 3, 2] * u.pc, width=[5, 4, 3] * u.pc, n_samples=1000)
assert udist.shape == (3, )
assert udist.distribution.shape == (3, 1000)
assert np.all(np.min(udist.distribution, axis=-1) > [-1.5, 1, 0.5]*u.pc)
assert np.all(np.max(udist.distribution, axis=-1) < [3.5, 5, 3.5]*u.pc)
def test_helper_normal_exact():
pytest.skip('distribution stretch goal not yet implemented')
centerq = [1, 5, 30, 400] * u.kpc
ds.normal(centerq, std=[0.2, 1.5, 4, 1]*u.kpc)
ds.normal(centerq, var=[0.04, 2.25, 16, 1]*u.kpc**2)
ds.normal(centerq, ivar=[25, 0.44444444, 0.625, 1]*u.kpc**-2)
def test_helper_poisson_exact():
pytest.skip('distribution stretch goal not yet implemented')
centerq = [1, 5, 30, 400] * u.one
ds.poisson(centerq, n_samples=1000)
with pytest.raises(u.UnitsError) as exc:
centerq = [1, 5, 30, 400] * u.kpc
ds.poisson(centerq, n_samples=1000)
assert exc.value.args[0] == ("Poisson distribution can only be computed "
"for dimensionless quantities")
def test_reprs():
darr = np.arange(30).reshape(3, 10)
distr = Distribution(darr * u.kpc)
assert 'n_samples=10' in repr(distr)
assert 'n_samples=10' in str(distr)
assert r'n_{\rm samp}=10' in distr._repr_latex_()
@pytest.mark.parametrize("func, kws", [
(ds.normal, {'center': 0, 'std': 2}),
(ds.uniform, {'lower': 0, 'upper': 2}),
(ds.poisson, {'center': 2}),
(ds.normal, {'center': 0*u.count, 'std': 2*u.count}),
(ds.uniform, {'lower': 0*u.count, 'upper': 2*u.count}),
(ds.poisson, {'center': 2*u.count})
])
def test_wrong_kw_fails(func, kws):
with pytest.raises(Exception):
kw_temp = kws.copy()
kw_temp['n_sample'] = 100 # note the missing "s"
assert func(**kw_temp).n_samples == 100
kw_temp = kws.copy()
kw_temp['n_samples'] = 100
assert func(**kw_temp).n_samples == 100
def test_index_assignment_quantity():
arr = np.random.randn(2, 1000)
distr = Distribution(arr*u.kpc)
d1q, d2q = distr
assert isinstance(d1q, Distribution)
assert isinstance(d2q, Distribution)
ndistr = ds.normal(center=[1, 2]*u.kpc, std=[3, 4]*u.kpc, n_samples=1000)
n1, n2 = ndistr
assert isinstance(n1, ds.Distribution)
assert isinstance(n2, ds.Distribution)
def test_index_assignment_array():
arr = np.random.randn(2, 1000)
distr = Distribution(arr)
d1a, d2a = distr
assert isinstance(d1a, Distribution)
assert isinstance(d2a, Distribution)
ndistr = ds.normal(center=[1, 2], std=[3, 4], n_samples=1000)
n1, n2 = ndistr
assert isinstance(n1, ds.Distribution)
assert isinstance(n2, ds.Distribution)
def test_histogram():
arr = np.random.randn(2, 3, 1000)
distr = Distribution(arr)
hist, bins = distr.pdf_histogram(bins=10)
assert hist.shape == (2, 3, 10)
assert bins.shape == (2, 3, 11)
def test_array_repr_latex():
# as of this writing ndarray does not have a _repr_latex_, and this test
# ensure distributions account for that. However, if in the future ndarray
# gets a _repr_latex_, we can skip this.
arr = np.random.randn(4, 1000)
if hasattr(arr, '_repr_latex_'):
pytest.skip('in this version of numpy, ndarray has a _repr_latex_')
distr = Distribution(arr)
assert distr._repr_latex_() is None
def test_distr_to():
distr = ds.normal(10*u.cm, n_samples=100, std=1*u.cm)
todistr = distr.to(u.m)
assert_quantity_allclose(distr.pdf_mean().to(u.m), todistr.pdf_mean())
def test_distr_noq_to():
# this is an array distribution not a quantity
distr = ds.normal(10, n_samples=100, std=1)
with pytest.raises(AttributeError):
distr.to(u.m)
def test_distr_to_value():
distr = ds.normal(10*u.cm, n_samples=100, std=1*u.cm)
tovdistr = distr.to_value(u.m)
assert np.allclose(distr.pdf_mean().to_value(u.m), tovdistr.pdf_mean())
def test_distr_noq_to_value():
distr = ds.normal(10, n_samples=100, std=1)
with pytest.raises(AttributeError):
distr.to_value(u.m)
def test_distr_angle():
# Check that Quantity subclasses decay to Quantity appropriately.
distr = Distribution([2., 3., 4.])
ad = Angle(distr, 'deg')
ad_plus_ad = ad + ad
assert isinstance(ad_plus_ad, Angle)
assert isinstance(ad_plus_ad, Distribution)
ad_times_ad = ad * ad
assert not isinstance(ad_times_ad, Angle)
assert isinstance(ad_times_ad, u.Quantity)
assert isinstance(ad_times_ad, Distribution)
ad += ad
assert isinstance(ad, Angle)
assert isinstance(ad, Distribution)
assert_array_equal(ad.distribution, ad_plus_ad.distribution)
with pytest.raises(u.UnitTypeError):
ad *= ad
def test_distr_angle_view_as_quantity():
# Check that Quantity subclasses decay to Quantity appropriately.
distr = Distribution([2., 3., 4.])
ad = Angle(distr, 'deg')
qd = ad.view(u.Quantity)
assert not isinstance(qd, Angle)
assert isinstance(qd, u.Quantity)
assert isinstance(qd, Distribution)
# View directly as DistributionQuantity class.
qd2 = ad.view(qd.__class__)
assert not isinstance(qd2, Angle)
assert isinstance(qd2, u.Quantity)
assert isinstance(qd2, Distribution)
assert_array_equal(qd2.distribution, qd.distribution)
qd3 = ad.view(qd.dtype, qd.__class__)
assert not isinstance(qd3, Angle)
assert isinstance(qd3, u.Quantity)
assert isinstance(qd3, Distribution)
assert_array_equal(qd3.distribution, qd.distribution)
def test_distr_cannot_view_new_dtype():
# A Distribution has a very specific structured dtype with just one
# element that holds the array of samples. As it is not clear what
# to do with a view as a new dtype, we just error on it.
# TODO: with a lot of thought, this restriction can likely be relaxed.
distr = Distribution([2., 3., 4.])
with pytest.raises(ValueError, match='with a new dtype'):
distr.view(np.dtype('f8'))
# Check subclass just in case.
ad = Angle(distr, 'deg')
with pytest.raises(ValueError, match='with a new dtype'):
ad.view(np.dtype('f8'))
with pytest.raises(ValueError, match='with a new dtype'):
ad.view(np.dtype('f8'), Distribution)
def test_scalar_quantity_distribution():
# Regression test for gh-12336
angles = Distribution([90., 30., 0.] * u.deg)
sin_angles = np.sin(angles) # This failed in 4.3.
assert isinstance(sin_angles, Distribution)
assert isinstance(sin_angles, u.Quantity)
assert_array_equal(sin_angles, Distribution(np.sin([90., 30., 0.]*u.deg)))
|
e2297945c013874f92544f5b60a26ba3cd7f1d7b2920ece3038074eeb9f4b21a | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Module to test statistic functions
"""
# pylint: disable=invalid-name
import pytest
import numpy as np
from numpy.testing import assert_almost_equal
from astropy.modeling.models import Identity, Mapping
from astropy.modeling.fitting import LinearLSQFitter
from astropy.modeling.statistic import (
leastsquare,
leastsquare_1d,
leastsquare_2d,
leastsquare_3d,
)
class TestLeastSquare_XD:
"""Tests for leastsquare with pre-specified number of dimensions."""
@classmethod
def setup_class(cls):
cls.model1D = Identity(n_inputs=1)
cls.model2D = Identity(n_inputs=2) | Mapping((0,), n_inputs=2)
cls.model3D = Identity(n_inputs=3) | Mapping((0,), n_inputs=3)
cls.data = cls.x = cls.y = cls.z = np.linspace(0, 10, num=100)
cls.lsq_exp = 0
def test_1d_no_weights(self):
lsq = leastsquare_1d(self.data, self.model1D, None, self.x)
assert_almost_equal(lsq, self.lsq_exp)
def test_1d_with_weights(self):
lsq = leastsquare_1d(self.data, self.model1D, np.ones(100), self.x)
assert_almost_equal(lsq, self.lsq_exp)
def test_2d_no_weights(self):
lsq = leastsquare_2d(self.data, self.model2D, None, self.x, self.y)
assert_almost_equal(lsq, self.lsq_exp)
def test_2d_with_weights(self):
lsq = leastsquare_2d(
self.data, self.model2D, np.ones(100), self.x, self.y
)
assert_almost_equal(lsq, self.lsq_exp)
def test_3d_no_weights(self):
lsq = leastsquare_3d(
self.data, self.model3D, None, self.x, self.y, self.z
)
assert_almost_equal(lsq, self.lsq_exp)
def test_3d_with_weights(self):
lsq = leastsquare_3d(
self.data, self.model3D, np.ones(100), self.x, self.y, self.z
)
assert_almost_equal(lsq, self.lsq_exp)
class TestLeastSquare_ND:
"""Tests for leastsquare."""
@classmethod
def setup_class(cls):
cls.model1D = Identity(n_inputs=1)
cls.model3D = Identity(n_inputs=3) | Mapping((0,), n_inputs=3)
cls.data = cls.x = cls.y = cls.z = np.linspace(0, 10, num=100)
cls.lsq_exp = 0
def test_1d_no_weights(self):
lsq = leastsquare(self.data, self.model1D, None, self.x)
assert_almost_equal(lsq, self.lsq_exp)
def test_1d_with_weights(self):
lsq = leastsquare(self.data, self.model1D, np.ones(100), self.x)
assert_almost_equal(lsq, self.lsq_exp)
def test_3d_no_weights(self):
lsq = leastsquare(
self.data, self.model3D, None, self.x, self.y, self.z
)
assert_almost_equal(lsq, self.lsq_exp)
def test_3d_with_weights(self):
lsq = leastsquare(
self.data, self.model3D, np.ones(100), self.x, self.y, self.z
)
assert_almost_equal(lsq, self.lsq_exp)
def test_shape_mismatch(self):
with pytest.raises(ValueError):
leastsquare(0, self.model1D, None, self.x)
|
74f0acd46516ff5d828aea00ec13a5e4f04a078fa27e52d6f6b47650758da0d6 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test sky projections defined in WCS Paper II"""
# pylint: disable=invalid-name, no-member
import os
import pytest
import numpy as np
import unittest.mock as mk
from numpy.testing import assert_allclose, assert_almost_equal
from astropy.modeling import projections
from astropy.modeling.parameters import InputParameterError
from astropy import units as u
from astropy.io import fits
from astropy import wcs
from astropy.utils.data import get_pkg_data_filename
from astropy.tests.helper import assert_quantity_allclose
def test_new_wcslib_projections():
# Test that we are aware of all WCSLIB projections.
# Dectect if a new WCSLIB release introduced new projections.
assert not set(wcs.PRJ_CODES).symmetric_difference(
projections.projcodes + projections._NOT_SUPPORTED_PROJ_CODES
)
def test_Projection_properties():
projection = projections.Sky2Pix_PlateCarree()
assert projection.n_inputs == 2
assert projection.n_outputs == 2
PIX_COORDINATES = [-10, 30]
MAPS_DIR = os.path.join(os.pardir, os.pardir, "wcs", "tests", "data", "maps")
pars = [(x,) for x in projections.projcodes]
# There is no groundtruth file for the XPH projection available here:
# https://www.atnf.csiro.au/people/mcalabre/WCS/example_data.html
pars.remove(('XPH',))
@pytest.mark.parametrize(('code',), pars)
def test_Sky2Pix(code):
"""Check astropy model eval against wcslib eval"""
wcs_map = os.path.join(MAPS_DIR, f"1904-66_{code}.hdr")
test_file = get_pkg_data_filename(wcs_map)
header = fits.Header.fromfile(test_file, endcard=False, padding=False)
params = []
for i in range(3):
key = f'PV2_{i + 1}'
if key in header:
params.append(header[key])
w = wcs.WCS(header)
w.wcs.crval = [0., 0.]
w.wcs.crpix = [0, 0]
w.wcs.cdelt = [1, 1]
wcslibout = w.wcs.p2s([PIX_COORDINATES], 1)
wcs_pix = w.wcs.s2p(wcslibout['world'], 1)['pixcrd']
model = getattr(projections, 'Sky2Pix_' + code)
tinv = model(*params)
x, y = tinv(wcslibout['phi'], wcslibout['theta'])
assert_almost_equal(np.asarray(x), wcs_pix[:, 0])
assert_almost_equal(np.asarray(y), wcs_pix[:, 1])
assert isinstance(tinv.prjprm, wcs.Prjprm)
@pytest.mark.parametrize(('code',), pars)
def test_Pix2Sky(code):
"""Check astropy model eval against wcslib eval"""
wcs_map = os.path.join(MAPS_DIR, f"1904-66_{code}.hdr")
test_file = get_pkg_data_filename(wcs_map)
header = fits.Header.fromfile(test_file, endcard=False, padding=False)
params = []
for i in range(3):
key = f'PV2_{i + 1}'
if key in header:
params.append(header[key])
w = wcs.WCS(header)
w.wcs.crval = [0., 0.]
w.wcs.crpix = [0, 0]
w.wcs.cdelt = [1, 1]
wcslibout = w.wcs.p2s([PIX_COORDINATES], 1)
wcs_phi = wcslibout['phi']
wcs_theta = wcslibout['theta']
model = getattr(projections, 'Pix2Sky_' + code)
tanprj = model(*params)
phi, theta = tanprj(*PIX_COORDINATES)
assert_almost_equal(np.asarray(phi), wcs_phi)
assert_almost_equal(np.asarray(theta), wcs_theta)
@pytest.mark.parametrize(('code',), pars)
def test_Sky2Pix_unit(code):
"""Check astropy model eval against wcslib eval"""
wcs_map = os.path.join(MAPS_DIR, f"1904-66_{code}.hdr")
test_file = get_pkg_data_filename(wcs_map)
header = fits.Header.fromfile(test_file, endcard=False, padding=False)
params = []
for i in range(3):
key = f'PV2_{i + 1}'
if key in header:
params.append(header[key])
w = wcs.WCS(header)
w.wcs.crval = [0., 0.]
w.wcs.crpix = [0, 0]
w.wcs.cdelt = [1, 1]
wcslibout = w.wcs.p2s([PIX_COORDINATES], 1)
wcs_pix = w.wcs.s2p(wcslibout['world'], 1)['pixcrd']
model = getattr(projections, 'Sky2Pix_' + code)
tinv = model(*params)
x, y = tinv(wcslibout['phi'] * u.deg, wcslibout['theta'] * u.deg)
assert_quantity_allclose(x, wcs_pix[:, 0] * u.deg)
assert_quantity_allclose(y, wcs_pix[:, 1] * u.deg)
@pytest.mark.parametrize(('code',), pars)
def test_Pix2Sky_unit(code):
"""Check astropy model eval against wcslib eval"""
wcs_map = os.path.join(MAPS_DIR, f"1904-66_{code}.hdr")
test_file = get_pkg_data_filename(wcs_map)
header = fits.Header.fromfile(test_file, endcard=False, padding=False)
params = []
for i in range(3):
key = f'PV2_{i + 1}'
if key in header:
params.append(header[key])
w = wcs.WCS(header)
w.wcs.crval = [0., 0.]
w.wcs.crpix = [0, 0]
w.wcs.cdelt = [1, 1]
wcslibout = w.wcs.p2s([PIX_COORDINATES], 1)
wcs_phi = wcslibout['phi']
wcs_theta = wcslibout['theta']
model = getattr(projections, 'Pix2Sky_' + code)
tanprj = model(*params)
phi, theta = tanprj(*PIX_COORDINATES * u.deg)
assert_quantity_allclose(phi, wcs_phi * u.deg)
assert_quantity_allclose(theta, wcs_theta * u.deg)
phi, theta = tanprj(*(PIX_COORDINATES * u.deg).to(u.rad))
assert_quantity_allclose(phi, wcs_phi * u.deg)
assert_quantity_allclose(theta, wcs_theta * u.deg)
phi, theta = tanprj(*(PIX_COORDINATES * u.deg).to(u.arcmin))
assert_quantity_allclose(phi, wcs_phi * u.deg)
assert_quantity_allclose(theta, wcs_theta * u.deg)
@pytest.mark.parametrize(('code',), pars)
def test_projection_default(code):
"""Check astropy model eval with default parameters"""
# Just makes sure that the default parameter values are reasonable
# and accepted by wcslib.
model = getattr(projections, 'Sky2Pix_' + code)
tinv = model()
x, y = tinv(45, 45)
model = getattr(projections, 'Pix2Sky_' + code)
tinv = model()
x, y = tinv(0, 0)
class TestZenithalPerspective:
"""Test Zenithal Perspective projection"""
def setup_class(self):
ID = 'AZP'
wcs_map = os.path.join(MAPS_DIR, f"1904-66_{ID}.hdr")
test_file = get_pkg_data_filename(wcs_map)
header = fits.Header.fromfile(test_file, endcard=False, padding=False)
self.wazp = wcs.WCS(header)
self.wazp.wcs.crpix = np.array([0., 0.])
self.wazp.wcs.crval = np.array([0., 0.])
self.wazp.wcs.cdelt = np.array([1., 1.])
self.pv_kw = [kw[2] for kw in self.wazp.wcs.get_pv()]
self.azp = projections.Pix2Sky_ZenithalPerspective(*self.pv_kw)
def test_AZP_p2s(self):
wcslibout = self.wazp.wcs.p2s([[-10, 30]], 1)
wcs_phi = wcslibout['phi']
wcs_theta = wcslibout['theta']
phi, theta = self.azp(-10, 30)
assert_almost_equal(np.asarray(phi), wcs_phi)
assert_almost_equal(np.asarray(theta), wcs_theta)
def test_AZP_s2p(self):
wcslibout = self.wazp.wcs.p2s([[-10, 30]], 1)
wcs_pix = self.wazp.wcs.s2p(wcslibout['world'], 1)['pixcrd']
x, y = self.azp.inverse(wcslibout['phi'], wcslibout['theta'])
assert_almost_equal(np.asarray(x), wcs_pix[:, 0])
assert_almost_equal(np.asarray(y), wcs_pix[:, 1])
def test_validate(self):
message = "Zenithal perspective projection is not defined for mu = -1"
with pytest.raises(InputParameterError) as err:
projections.Pix2Sky_ZenithalPerspective(-1)
assert str(err.value) == message
with pytest.raises(InputParameterError) as err:
projections.Sky2Pix_ZenithalPerspective(-1)
assert str(err.value) == message
with pytest.raises(InputParameterError) as err:
projections.Pix2Sky_SlantZenithalPerspective(-1)
assert str(err.value) == message
with pytest.raises(InputParameterError) as err:
projections.Sky2Pix_SlantZenithalPerspective(-1)
assert str(err.value) == message
class TestCylindricalPerspective:
"""Test cylindrical perspective projection"""
def setup_class(self):
ID = "CYP"
wcs_map = os.path.join(MAPS_DIR, f"1904-66_{ID}.hdr")
test_file = get_pkg_data_filename(wcs_map)
header = fits.Header.fromfile(test_file, endcard=False, padding=False)
self.wazp = wcs.WCS(header)
self.wazp.wcs.crpix = np.array([0., 0.])
self.wazp.wcs.crval = np.array([0., 0.])
self.wazp.wcs.cdelt = np.array([1., 1.])
self.pv_kw = [kw[2] for kw in self.wazp.wcs.get_pv()]
self.azp = projections.Pix2Sky_CylindricalPerspective(*self.pv_kw)
def test_CYP_p2s(self):
wcslibout = self.wazp.wcs.p2s([[-10, 30]], 1)
wcs_phi = wcslibout['phi']
wcs_theta = wcslibout['theta']
phi, theta = self.azp(-10, 30)
assert_almost_equal(np.asarray(phi), wcs_phi)
assert_almost_equal(np.asarray(theta), wcs_theta)
def test_CYP_s2p(self):
wcslibout = self.wazp.wcs.p2s([[-10, 30]], 1)
wcs_pix = self.wazp.wcs.s2p(wcslibout['world'], 1)['pixcrd']
x, y = self.azp.inverse(wcslibout['phi'], wcslibout['theta'])
assert_almost_equal(np.asarray(x), wcs_pix[:, 0])
assert_almost_equal(np.asarray(y), wcs_pix[:, 1])
def test_validate(self):
message0 = "CYP projection is not defined for mu = -lambda"
message1 = "CYP projection is not defined for lambda = -mu"
# Pix2Sky_CylindricalPerspective
with pytest.raises(InputParameterError) as err:
projections.Pix2Sky_CylindricalPerspective(1, -1)
assert str(err.value) == message0 or str(err.value) == message1
with pytest.raises(InputParameterError) as err:
projections.Pix2Sky_CylindricalPerspective(-1, 1)
assert str(err.value) == message0 or str(err.value) == message1
model = projections.Pix2Sky_CylindricalPerspective()
with pytest.raises(InputParameterError) as err:
model.mu = -1
assert str(err.value) == message0
with pytest.raises(InputParameterError) as err:
model.lam = -1
assert str(err.value) == message1
# Sky2Pix_CylindricalPerspective
with pytest.raises(InputParameterError) as err:
projections.Sky2Pix_CylindricalPerspective(1, -1)
assert str(err.value) == message0 or str(err.value) == message1
with pytest.raises(InputParameterError) as err:
projections.Sky2Pix_CylindricalPerspective(-1, 1)
assert str(err.value) == message0 or str(err.value) == message1
model = projections.Sky2Pix_CylindricalPerspective()
with pytest.raises(InputParameterError) as err:
model.mu = -1
assert str(err.value) == message0
with pytest.raises(InputParameterError) as err:
model.lam = -1
assert str(err.value) == message1
def test_AffineTransformation2D():
# Simple test with a scale and translation
model = projections.AffineTransformation2D(
matrix=[[2, 0], [0, 2]], translation=[1, 1])
# Coordinates for vertices of a rectangle
rect = [[0, 0], [1, 0], [0, 3], [1, 3]]
x, y = zip(*rect)
new_rect = np.vstack(model(x, y)).T
assert np.all(new_rect == [[1, 1], [3, 1], [1, 7], [3, 7]])
# Matrix validation error
with pytest.raises(InputParameterError) as err:
model.matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
assert str(err.value) ==\
"Expected transformation matrix to be a 2x2 array"
# Translation validation error
with pytest.raises(InputParameterError) as err:
model.translation = [1, 2, 3]
assert str(err.value) ==\
"Expected translation vector to be a 2 element row or column vector array"
with pytest.raises(InputParameterError) as err:
model.translation = [[1], [2]]
assert str(err.value) ==\
"Expected translation vector to be a 2 element row or column vector array"
with pytest.raises(InputParameterError) as err:
model.translation = [[1, 2, 3]]
assert str(err.value) ==\
"Expected translation vector to be a 2 element row or column vector array"
# Incompatible shape error
a = np.array([[1], [2], [3], [4]])
b = a.ravel()
with mk.patch.object(np, 'vstack', autospec=True,
side_effect=[a, b]) as mk_vstack:
message = "Incompatible input shapes"
with pytest.raises(ValueError) as err:
model(x, y)
assert str(err.value) == message
with pytest.raises(ValueError) as err:
model(x, y)
assert str(err.value) == message
assert mk_vstack.call_count == 2
# Input shape evaluation error
x = np.array([1, 2])
y = np.array([1, 2, 3])
with pytest.raises(ValueError) as err:
model.evaluate(x, y, model.matrix, model.translation)
assert str(err.value) ==\
"Expected input arrays to have the same shape"
def test_AffineTransformation2D_inverse():
# Test non-invertible model
model1 = projections.AffineTransformation2D(
matrix=[[1, 1], [1, 1]])
with pytest.raises(InputParameterError):
model1.inverse
model2 = projections.AffineTransformation2D(
matrix=[[1.2, 3.4], [5.6, 7.8]], translation=[9.1, 10.11])
# Coordinates for vertices of a rectangle
rect = [[0, 0], [1, 0], [0, 3], [1, 3]]
x, y = zip(*rect)
x_new, y_new = model2.inverse(*model2(x, y))
assert_allclose([x, y], [x_new, y_new], atol=1e-10)
model3 = projections.AffineTransformation2D(
matrix=[[1.2, 3.4], [5.6, 7.8]] * u.m, translation=[9.1, 10.11] * u.m)
x_new, y_new = model3.inverse(*model3(x * u.m, y * u.m))
assert_allclose([x, y], [x_new, y_new], atol=1e-10)
model4 = projections.AffineTransformation2D(
matrix=[[1.2, 3.4], [5.6, 7.8]] * u.m, translation=[9.1, 10.11] * u.km)
with pytest.raises(ValueError) as err:
model4.inverse(*model4(x * u.m, y * u.m))
assert str(err.value) ==\
"matrix and translation must have the same units."
def test_c_projection_striding():
# This is just a simple test to make sure that the striding is
# handled correctly in the projection C extension
coords = np.arange(10).reshape((5, 2))
model = projections.Sky2Pix_ZenithalPerspective(2, 30)
phi, theta = model(coords[:, 0], coords[:, 1])
assert_almost_equal(
phi,
[0., 2.2790416, 4.4889294, 6.6250643, 8.68301])
assert_almost_equal(
theta,
[-76.4816918, -75.3594654, -74.1256332, -72.784558, -71.3406629])
def test_c_projections_shaped():
nx, ny = (5, 2)
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
xv, yv = np.meshgrid(x, y)
model = projections.Pix2Sky_TAN()
phi, theta = model(xv, yv)
assert_allclose(
phi,
[[0., 90., 90., 90., 90.],
[180., 165.96375653, 153.43494882, 143.13010235, 135.]])
assert_allclose(
theta,
[[90., 89.75000159, 89.50001269, 89.25004283, 89.00010152],
[89.00010152, 88.96933478, 88.88210788, 88.75019826, 88.58607353]])
def test_affine_with_quantities():
x = 1
y = 2
xdeg = (x * u.pix).to(u.deg, equivalencies=u.pixel_scale(2.5 * u.deg / u.pix))
ydeg = (y * u.pix).to(u.deg, equivalencies=u.pixel_scale(2.5 * u.deg / u.pix))
xpix = x * u.pix
ypix = y * u.pix
# test affine with matrix only
qaff = projections.AffineTransformation2D(matrix=[[1, 2], [2, 1]] * u.deg)
with pytest.raises(ValueError):
qx1, qy1 = qaff(xpix, ypix, equivalencies={
'x': u.pixel_scale(2.5 * u.deg / u.pix),
'y': u.pixel_scale(2.5 * u.deg / u.pix)})
# test affine with matrix and translation
qaff = projections.AffineTransformation2D(matrix=[[1, 2], [2, 1]] * u.deg,
translation=[1, 2] * u.deg)
qx1, qy1 = qaff(xpix, ypix, equivalencies={
'x': u.pixel_scale(2.5 * u.deg / u.pix),
'y': u.pixel_scale(2.5 * u.deg / u.pix)})
aff = projections.AffineTransformation2D(matrix=[[1, 2], [2, 1]], translation=[1, 2])
x1, y1 = aff(xdeg.value, ydeg.value)
assert_quantity_allclose(qx1, x1 * u.deg)
assert_quantity_allclose(qy1, y1 * u.deg)
# test the case of WCS PC and CDELT transformations
pc = np.array([[0.86585778922708, 0.50029020461607],
[-0.50029020461607, 0.86585778922708]])
cdelt = np.array([[1, 3.0683055555556E-05], [3.0966944444444E-05, 1]])
matrix = cdelt * pc
qaff = projections.AffineTransformation2D(matrix=matrix * u.deg,
translation=[0, 0] * u.deg)
inv_matrix = np.linalg.inv(matrix)
inv_qaff = projections.AffineTransformation2D(matrix=inv_matrix * u.pix,
translation=[0, 0] * u.pix)
qaff.inverse = inv_qaff
qx1, qy1 = qaff(xpix, ypix, equivalencies={
'x': u.pixel_scale(1 * u.deg / u.pix),
'y': u.pixel_scale(1 * u.deg / u.pix)})
x1, y1 = qaff.inverse(qx1, qy1, equivalencies={
'x': u.pixel_scale(1 * u.deg / u.pix),
'y': u.pixel_scale(1 * u.deg / u.pix)})
assert_quantity_allclose(x1, xpix)
assert_quantity_allclose(y1, ypix)
def test_Pix2Sky_ZenithalPerspective_inverse():
model = projections.Pix2Sky_ZenithalPerspective(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_ZenithalPerspective)
assert inverse.mu == model.mu == 2
assert_allclose(inverse.gamma, model.gamma)
assert_allclose(inverse.gamma, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_ZenithalPerspective_inverse():
model = projections.Sky2Pix_ZenithalPerspective(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_AZP)
assert inverse.mu == model.mu == 2
assert_allclose(inverse.gamma, model.gamma)
assert_allclose(inverse.gamma, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_SlantZenithalPerspective_inverse():
model = projections.Pix2Sky_SlantZenithalPerspective(2, 30, 40)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_SlantZenithalPerspective)
assert inverse.mu == model.mu == 2
assert_allclose(inverse.phi0, model.phi0)
assert_allclose(inverse.theta0, model.theta0)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_SlantZenithalPerspective_inverse():
model = projections.Sky2Pix_SlantZenithalPerspective(2, 30, 40)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_SlantZenithalPerspective)
assert inverse.mu == model.mu == 2
assert_allclose(inverse.phi0, model.phi0)
assert_allclose(inverse.theta0, model.theta0)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_Gnomonic_inverse():
model = projections.Pix2Sky_Gnomonic()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_Gnomonic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_Gnomonic_inverse():
model = projections.Sky2Pix_Gnomonic()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_Gnomonic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_Stereographic_inverse():
model = projections.Pix2Sky_Stereographic()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_Stereographic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_Stereographic_inverse():
model = projections.Sky2Pix_Stereographic()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_Stereographic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_SlantOrthographic_inverse():
model = projections.Pix2Sky_SlantOrthographic(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_SlantOrthographic)
assert inverse.xi == model.xi == 2
assert inverse.eta == model.eta == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-8)
assert_allclose(b, y, atol=1e-8)
def test_Sky2Pix_SlantOrthographic_inverse():
model = projections.Sky2Pix_SlantOrthographic(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_SlantOrthographic)
assert inverse.xi == model.xi == 2
assert inverse.eta == model.eta == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-8)
assert_allclose(b, y, atol=1e-8)
def test_Pix2Sky_ZenithalEquidistant_inverse():
model = projections.Pix2Sky_ZenithalEquidistant()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_ZenithalEquidistant)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_ZenithalEquidistant_inverse():
model = projections.Sky2Pix_ZenithalEquidistant()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_ZenithalEquidistant)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_ZenithalEqualArea_inverse():
model = projections.Pix2Sky_ZenithalEqualArea()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_ZenithalEqualArea)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_ZenithalEqualArea_inverse():
model = projections.Sky2Pix_ZenithalEqualArea()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_ZenithalEqualArea)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_Airy_inverse():
model = projections.Pix2Sky_Airy(30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_Airy)
assert inverse.theta_b == model.theta_b == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_Airy_inverse():
model = projections.Sky2Pix_Airy(30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_Airy)
assert inverse.theta_b == model.theta_b == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_CylindricalPerspective_inverse():
model = projections.Pix2Sky_CylindricalPerspective(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_CylindricalPerspective)
assert inverse.mu == model.mu == 2
assert inverse.lam == model.lam == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_CylindricalPerspective_inverse():
model = projections.Sky2Pix_CylindricalPerspective(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_CylindricalPerspective)
assert inverse.mu == model.mu == 2
assert inverse.lam == model.lam == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_CylindricalEqualArea_inverse():
model = projections.Pix2Sky_CylindricalEqualArea(0.567)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_CylindricalEqualArea)
assert inverse.lam == model.lam == 0.567
def test_Sky2Pix_CylindricalEqualArea_inverse():
model = projections.Sky2Pix_CylindricalEqualArea(0.765)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_CylindricalEqualArea)
assert inverse.lam == model.lam == 0.765
def test_Pix2Sky_PlateCarree_inverse():
model = projections.Pix2Sky_PlateCarree()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_PlateCarree)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_PlateCarree_inverse():
model = projections.Sky2Pix_PlateCarree()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_PlateCarree)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_Mercator_inverse():
model = projections.Pix2Sky_Mercator()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_Mercator)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_Mercator_inverse():
model = projections.Sky2Pix_Mercator()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_Mercator)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_SansonFlamsteed_inverse():
model = projections.Pix2Sky_SansonFlamsteed()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_SansonFlamsteed)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_SansonFlamsteed_inverse():
model = projections.Sky2Pix_SansonFlamsteed()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_SansonFlamsteed)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_Parabolic_inverse():
model = projections.Pix2Sky_Parabolic()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_Parabolic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_Parabolic_inverse():
model = projections.Sky2Pix_Parabolic()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_Parabolic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_Molleweide_inverse():
model = projections.Pix2Sky_Molleweide()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_Molleweide)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_Molleweide_inverse():
model = projections.Sky2Pix_Molleweide()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_Molleweide)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_HammerAitoff_inverse():
model = projections.Pix2Sky_HammerAitoff()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_HammerAitoff)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_HammerAitoff_inverse():
model = projections.Sky2Pix_HammerAitoff()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_HammerAitoff)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_ConicPerspective_inverse():
model = projections.Pix2Sky_ConicPerspective(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_ConicPerspective)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_ConicPerspective_inverse():
model = projections.Sky2Pix_ConicPerspective(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_ConicPerspective)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_ConicEqualArea_inverse():
model = projections.Pix2Sky_ConicEqualArea(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_ConicEqualArea)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_ConicEqualArea_inverse():
model = projections.Sky2Pix_ConicEqualArea(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_ConicEqualArea)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_ConicEquidistant_inverse():
model = projections.Pix2Sky_ConicEquidistant(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_ConicEquidistant)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_ConicEquidistant_inverse():
model = projections.Sky2Pix_ConicEquidistant(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_ConicEquidistant)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_ConicOrthomorphic_inverse():
model = projections.Pix2Sky_ConicOrthomorphic(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_ConicOrthomorphic)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_ConicOrthomorphic_inverse():
model = projections.Sky2Pix_ConicOrthomorphic(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_ConicOrthomorphic)
assert inverse.sigma == model.sigma == 2
assert_allclose(inverse.delta, model.delta)
assert_allclose(inverse.delta, 30)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_BonneEqualArea_inverse():
model = projections.Pix2Sky_BonneEqualArea(2)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_BonneEqualArea)
assert inverse.theta1 == model.theta1 == 2
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_BonneEqualArea_inverse():
model = projections.Sky2Pix_BonneEqualArea(2)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_BonneEqualArea)
assert inverse.theta1 == model.theta1 == 2
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_Polyconic_inverse():
model = projections.Pix2Sky_Polyconic()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_Polyconic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_Polyconic_inverse():
model = projections.Sky2Pix_Polyconic()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_Polyconic)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_TangentialSphericalCube_inverse():
model = projections.Pix2Sky_TangentialSphericalCube()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_TangentialSphericalCube)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_TangentialSphericalCube_inverse():
model = projections.Sky2Pix_TangentialSphericalCube()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_TangentialSphericalCube)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_COBEQuadSphericalCube_inverse():
model = projections.Pix2Sky_COBEQuadSphericalCube()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_COBEQuadSphericalCube)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-3)
assert_allclose(b, y, atol=1e-3)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-3)
assert_allclose(b, y, atol=1e-3)
def test_Sky2Pix_COBEQuadSphericalCube_inverse():
model = projections.Sky2Pix_COBEQuadSphericalCube()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_COBEQuadSphericalCube)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-3)
assert_allclose(b, y, atol=1e-3)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-3)
assert_allclose(b, y, atol=1e-3)
def test_Pix2Sky_QuadSphericalCube_inverse():
model = projections.Pix2Sky_QuadSphericalCube()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_QuadSphericalCube)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_QuadSphericalCube_inverse():
model = projections.Sky2Pix_QuadSphericalCube()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_QuadSphericalCube)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_HEALPix_inverse():
model = projections.Pix2Sky_HEALPix(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_HEALPix)
assert inverse.H == model.H == 2
assert inverse.X == model.X == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_HEALPix_inverse():
model = projections.Sky2Pix_HEALPix(2, 30)
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_HEALPix)
assert inverse.H == model.H == 2
assert inverse.X == model.X == 30
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Pix2Sky_HEALPixPolar_inverse():
model = projections.Pix2Sky_HEALPixPolar()
inverse = model.inverse
assert isinstance(inverse, projections.Sky2Pix_HEALPixPolar)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
def test_Sky2Pix_HEALPixPolar_inverse():
model = projections.Sky2Pix_HEALPixPolar()
inverse = model.inverse
assert isinstance(inverse, projections.Pix2Sky_HEALPixPolar)
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
a, b = model(*inverse(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
a, b = inverse(*model(x, y))
assert_allclose(a, x, atol=1e-12)
assert_allclose(b, y, atol=1e-12)
|
87d8ac553334cf548bf24909bd94fdb055b80bdc8ffb780bbfae888919d47311 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides functions to help with testing against iraf tasks
"""
from astropy.logger import log
import numpy as np
iraf_models_map = {1.: 'Chebyshev',
2.: 'Legendre',
3.: 'Spline3',
4.: 'Spline1'}
def get_records(fname):
"""
Read the records of an IRAF database file into a python list
Parameters
----------
fname : str
name of an IRAF database file
Returns
-------
A list of records
"""
f = open(fname)
dtb = f.read()
f.close()
recs = dtb.split('begin')[1:]
records = [Record(r) for r in recs]
return records
def get_database_string(fname):
"""
Read an IRAF database file
Parameters
----------
fname : str
name of an IRAF database file
Returns
-------
the database file as a string
"""
f = open(fname)
dtb = f.read()
f.close()
return dtb
class Record:
"""
A base class for all records - represents an IRAF database record
Attributes
----------
recstr: string
the record as a string
fields: dict
the fields in the record
taskname: string
the name of the task which created the database file
"""
def __init__(self, recstr):
self.recstr = recstr
self.fields = self.get_fields()
self.taskname = self.get_task_name()
def aslist(self):
reclist = self.recstr.split('\n')
reclist = [l.strip() for l in reclist]
[reclist.remove(l) for l in reclist if len(l) == 0]
return reclist
def get_fields(self):
# read record fields as an array
fields = {}
flist = self.aslist()
numfields = len(flist)
for i in range(numfields):
line = flist[i]
if line and line[0].isalpha():
field = line.split()
if i + 1 < numfields:
if not flist[i + 1][0].isalpha():
fields[field[0]] = self.read_array_field(
flist[i:i + int(field[1]) + 1])
else:
fields[field[0]] = " ".join(s for s in field[1:])
else:
fields[field[0]] = " ".join(s for s in field[1:])
else:
continue
return fields
def get_task_name(self):
try:
return self.fields['task']
except KeyError:
return None
def read_array_field(self, fieldlist):
# Turn an iraf record array field into a numpy array
fieldline = [l.split() for l in fieldlist[1:]]
# take only the first 3 columns
# identify writes also strings at the end of some field lines
xyz = [l[:3] for l in fieldline]
try:
farr = np.array(xyz)
except Exception:
log.debug(f"Could not read array field {fieldlist[0].split()[0]}")
return farr.astype(np.float64)
class IdentifyRecord(Record):
"""
Represents a database record for the onedspec.identify task
Attributes
----------
x: array
the X values of the identified features
this represents values on axis1 (image rows)
y: int
the Y values of the identified features
(image columns)
z: array
the values which X maps into
modelname: string
the function used to fit the data
nterms: int
degree of the polynomial which was fit to the data
in IRAF this is the number of coefficients, not the order
mrange: list
the range of the data
coeff: array
function (modelname) coefficients
"""
def __init__(self, recstr):
super().__init__(recstr)
self._flatcoeff = self.fields['coefficients'].flatten()
self.x = self.fields['features'][:, 0]
self.y = self.get_ydata()
self.z = self.fields['features'][:, 1]
self.modelname = self.get_model_name()
self.nterms = self.get_nterms()
self.mrange = self.get_range()
self.coeff = self.get_coeff()
def get_model_name(self):
return iraf_models_map[self._flatcoeff[0]]
def get_nterms(self):
return self._flatcoeff[1]
def get_range(self):
low = self._flatcoeff[2]
high = self._flatcoeff[3]
return [low, high]
def get_coeff(self):
return self._flatcoeff[4:]
def get_ydata(self):
image = self.fields['image']
left = image.find('[') + 1
right = image.find(']')
section = image[left:right]
if ',' in section:
yind = image.find(',') + 1
return int(image[yind:-1])
else:
return int(section)
class FitcoordsRecord(Record):
"""
Represents a database record for the longslit.fitccords task
Attributes
----------
modelname: string
the function used to fit the data
xorder: int
number of terms in x
yorder: int
number of terms in y
xbounds: list
data range in x
ybounds: list
data range in y
coeff: array
function coefficients
"""
def __init__(self, recstr):
super().__init__(recstr)
self._surface = self.fields['surface'].flatten()
self.modelname = iraf_models_map[self._surface[0]]
self.xorder = self._surface[1]
self.yorder = self._surface[2]
self.xbounds = [self._surface[4], self._surface[5]]
self.ybounds = [self._surface[6], self._surface[7]]
self.coeff = self.get_coeff()
def get_coeff(self):
return self._surface[8:]
class IDB:
"""
Base class for an IRAF identify database
Attributes
----------
records: list
a list of all `IdentifyRecord` in the database
numrecords: int
number of records
"""
def __init__(self, dtbstr):
self.records = [IdentifyRecord(rstr) for rstr in self.aslist(dtbstr)]
self.numrecords = len(self.records)
def aslist(self, dtb):
# return a list of records
# if the first one is a comment remove it from the list
rl = dtb.split('begin')
try:
rl0 = rl[0].split('\n')
except Exception:
return rl
if len(rl0) == 2 and rl0[0].startswith('#') and not rl0[1].strip():
return rl[1:]
else:
return rl
class ReidentifyRecord(IDB):
"""
Represents a database record for the onedspec.reidentify task
"""
def __init__(self, databasestr):
super().__init__(databasestr)
self.x = np.array([r.x for r in self.records])
self.y = self.get_ydata()
self.z = np.array([r.z for r in self.records])
def get_ydata(self):
y = np.ones(self.x.shape)
y = y * np.array([r.y for r in self.records])[:, np.newaxis]
return y
|
fb00c1b993a05f57e023cd4b8967038cd2c472e0dd0477dbb00abcd8b49b797f | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Here are all the test parameters and values for the each
`~astropy.modeling.FittableModel` defined. There is a dictionary for 1D and a
dictionary for 2D models.
Explanation of keywords of the dictionaries:
"parameters" : list or dict
Model parameters, the model is tested with. Make sure you keep the right
order. For polynomials you can also use a dict to specify the
coefficients. See examples below.
"x_values" : list
x values where the model is evaluated.
"y_values" : list
Reference y values for the in x_values given positions.
"z_values" : list
Reference z values for the in x_values and y_values given positions.
(2D model option)
"x_lim" : list
x test range for the model fitter. Depending on the model this can differ
e.g. the PowerLaw model should be tested over a few magnitudes.
"y_lim" : list
y test range for the model fitter. Depending on the model this can differ
e.g. the PowerLaw model should be tested over a few magnitudes. (2D model
option)
"log_fit" : bool
PowerLaw models should be tested over a few magnitudes. So log_fit should
be true.
"requires_scipy" : bool
If a model requires scipy (Bessel functions etc.) set this flag.
"integral" : float
Approximate value of the integral in the range x_lim (and y_lim).
"deriv_parameters" : list
If given the test of the derivative will use these parameters to create a
model (optional)
"deriv_initial" : list
If given the test of the derivative will use these parameters as initial
values for the fit (optional)
"""
from astropy.modeling.functional_models import (
Gaussian1D,
Sine1D, Cosine1D, Tangent1D, ArcSine1D, ArcCosine1D, ArcTangent1D,
Box1D, Linear1D, Lorentz1D,
RickerWavelet1D, Trapezoid1D, Const1D, Moffat1D,
Gaussian2D, Const2D, Box2D, RickerWavelet2D,
TrapezoidDisk2D, AiryDisk2D, Moffat2D, Disk2D,
Ring2D, Sersic1D, Sersic2D, Voigt1D, Planar2D, KingProjectedAnalytic1D,
Exponential1D, Logarithmic1D)
from astropy.modeling.physical_models import Drude1D, Plummer1D
from astropy.modeling.polynomial import Polynomial1D, Polynomial2D
from astropy.modeling.powerlaws import (
PowerLaw1D, BrokenPowerLaw1D, SmoothlyBrokenPowerLaw1D, ExponentialCutoffPowerLaw1D,
LogParabola1D)
import numpy as np
# 1D Models
models_1D = {
Gaussian1D: {
'parameters': [1, 0, 1],
'x_values': [0, np.sqrt(2), -np.sqrt(2)],
'y_values': [1.0, 0.367879, 0.367879],
'x_lim': [-10, 10],
'integral': np.sqrt(2 * np.pi),
'bbox_peak': True
},
Sine1D: {
'parameters': [1, 0.1, 0],
'x_values': [0, 2.5],
'y_values': [0, 1],
'x_lim': [-10, 10],
'integral': 0
},
Cosine1D: {
'parameters': [1, 0.1, 0],
'x_values': [0, 2.5],
'y_values': [1, 0],
'x_lim': [-10, 10],
'integral': 0
},
Tangent1D: {
'parameters': [1, 0.1, 0],
'x_values': [0, 1.25],
'y_values': [0, 1],
'x_lim': [-10, 10],
'integral': 0
},
ArcSine1D: {
'parameters': [1, 0.1, 0],
'x_values': [0, 1],
'y_values': [0, 2.5],
'x_lim': [-0.5, 0.5],
'integral': 0
},
ArcCosine1D: {
'parameters': [1, 0.1, 0],
'x_values': [1, 0],
'y_values': [0, 2.5],
'x_lim': [-0.5, 0.5],
'integral': 0
},
ArcTangent1D: {
'parameters': [1, 0.1, 0],
'x_values': [0, 1],
'y_values': [0, 1.25],
'x_lim': [-10, 10],
'integral': 0
},
Box1D: {
'parameters': [1, 0, 10],
'x_values': [-5, 5, 0, -10, 10],
'y_values': [1, 1, 1, 0, 0],
'x_lim': [-10, 10],
'integral': 10,
'bbox_peak': True
},
Linear1D: {
'parameters': [1, 0],
'x_values': [0, np.pi, 42, -1],
'y_values': [0, np.pi, 42, -1],
'x_lim': [-10, 10],
'integral': 0
},
Lorentz1D: {
'parameters': [1, 0, 1],
'x_values': [0, -1, 1, 0.5, -0.5],
'y_values': [1., 0.2, 0.2, 0.5, 0.5],
'x_lim': [-10, 10],
'integral': 1,
'bbox_peak': True
},
RickerWavelet1D: {
'parameters': [1, 0, 1],
'x_values': [0, 1, -1, 3, -3],
'y_values': [1.0, 0.0, 0.0, -0.088872, -0.088872],
'x_lim': [-20, 20],
'integral': 0,
'bbox_peak': True
},
Trapezoid1D: {
'parameters': [1, 0, 2, 1],
'x_values': [0, 1, -1, 1.5, -1.5, 2, 2],
'y_values': [1, 1, 1, 0.5, 0.5, 0, 0],
'x_lim': [-10, 10],
'integral': 3,
'bbox_peak': True
},
Const1D: {
'parameters': [1],
'x_values': [-1, 1, np.pi, -42., 0],
'y_values': [1, 1, 1, 1, 1],
'x_lim': [-10, 10],
'integral': 20
},
Moffat1D: {
'parameters': [1, 0, 1, 2],
'x_values': [0, 1, -1, 3, -3],
'y_values': [1.0, 0.25, 0.25, 0.01, 0.01],
'x_lim': [-10, 10],
'integral': 1,
'deriv_parameters': [23.4, 1.2, 2.1, 2.3],
'deriv_initial': [10, 1, 1, 1]
},
PowerLaw1D: {
'parameters': [1, 1, 2],
'constraints': {'fixed': {'x_0': True}},
'x_values': [1, 10, 100],
'y_values': [1.0, 0.01, 0.0001],
'x_lim': [1, 10],
'log_fit': True,
'integral': 0.99
},
BrokenPowerLaw1D: {
'parameters': [1, 1, 2, 3],
'constraints': {'fixed': {'x_break': True}},
'x_values': [0.1, 1, 10, 100],
'y_values': [1e2, 1.0, 1e-3, 1e-6],
'x_lim': [0.1, 100],
'log_fit': True
},
SmoothlyBrokenPowerLaw1D: {
'parameters': [1, 1, -2, 2, 0.5],
'constraints': {'fixed': {'x_break': True, 'delta': True}},
'x_values': [0.01, 1, 100],
'y_values': [3.99920012e-04, 1.0, 3.99920012e-04],
'x_lim': [0.01, 100],
'log_fit': True
},
ExponentialCutoffPowerLaw1D: {
'parameters': [1, 1, 2, 3],
'constraints': {'fixed': {'x_0': True}},
'x_values': [0.1, 1, 10, 100],
'y_values': [9.67216100e+01, 7.16531311e-01, 3.56739933e-04,
3.33823780e-19],
'x_lim': [0.01, 100],
'log_fit': True
},
LogParabola1D: {
'parameters': [1, 2, 3, 0.1],
'constraints': {'fixed': {'x_0': True}},
'x_values': [0.1, 1, 10, 100],
'y_values': [3.26089063e+03, 7.62472488e+00, 6.17440488e-03,
1.73160572e-06],
'x_lim': [0.1, 100],
'log_fit': True
},
Polynomial1D: {
'parameters': {'degree': 2, 'c0': 1., 'c1': 1., 'c2': 1.},
'x_values': [1, 10, 100],
'y_values': [3, 111, 10101],
'x_lim': [-3, 3]
},
Sersic1D: {
'parameters': [1, 20, 4],
'x_values': [0.1, 1, 10, 100],
'y_values': [2.78629391e+02, 5.69791430e+01, 3.38788244e+00,
2.23941982e-02],
'requires_scipy': True,
'x_lim': [0, 10],
'log_fit': True
},
Voigt1D: {
'parameters': [0, 1, 0.5, 0.9],
'x_values': [0, 0.2, 0.5, 1, 2, 4, 8, 20],
'y_values': [0.52092360, 0.479697445, 0.317550374, 0.0988079347,
1.73876624e-2, 4.00173216e-3, 9.82351731e-4, 1.56396993e-4],
'x_lim': [-3, 3]
},
KingProjectedAnalytic1D: {
'parameters': [1, 1, 2],
'x_values': [0, 0.1, 0.5, 0.8],
'y_values': [0.30557281, 0.30011069, 0.2, 0.1113258],
'x_lim': [0, 10],
'y_lim': [0, 10],
'bbox_peak': True
},
Drude1D: {
'parameters': [1.0, 8.0, 1.0],
'x_values': [7.0, 8.0, 9.0, 10.0],
'y_values': [0.17883212, 1.0, 0.21891892, 0.07163324],
'x_lim': [1.0, 20.0],
'y_lim': [0.0, 10.0],
'bbox_peak': True
},
Plummer1D: {
'parameters': [10., 0.5],
'x_values': [1.0000e-03, 2.5005e+00, 5.0000e+00],
'y_values': [1.90984022e+01, 5.53541843e-03, 1.86293603e-04],
'x_lim': [0.001, 100]
},
Exponential1D: {
'parameters': [1, 1],
'x_values': [0, 0.5, 1],
'y_values': [1, np.sqrt(np.e), np.e],
'x_lim': [0, 2],
'integral': (np.e**2 - 1.),
},
Logarithmic1D: {
'parameters': [1, 1],
'x_values': [1, np.e, np.e**2],
'y_values': [0, 1, 2],
'x_lim': [1, np.e**2],
'integral': (np.e**2 + 1),
}
}
# 2D Models
models_2D = {
Gaussian2D: {
'parameters': [1, 0, 0, 1, 1],
'constraints': {'fixed': {'theta': True}},
'x_values': [0, np.sqrt(2), -np.sqrt(2)],
'y_values': [0, np.sqrt(2), -np.sqrt(2)],
'z_values': [1, 1. / np.exp(1) ** 2, 1. / np.exp(1) ** 2],
'x_lim': [-10, 10],
'y_lim': [-10, 10],
'integral': 2 * np.pi,
'deriv_parameters': [137., 5.1, 5.4, 1.5, 2., np.pi/4],
'deriv_initial': [10, 5, 5, 4, 4, .5],
'bbox_peak': True
},
Const2D: {
'parameters': [1],
'x_values': [-1, 1, np.pi, -42., 0],
'y_values': [0, 1, 42, np.pi, -1],
'z_values': [1, 1, 1, 1, 1],
'x_lim': [-10, 10],
'y_lim': [-10, 10],
'integral': 400
},
Box2D: {
'parameters': [1, 0, 0, 10, 10],
'x_values': [-5, 5, -5, 5, 0, -10, 10],
'y_values': [-5, 5, 0, 0, 0, -10, 10],
'z_values': [1, 1, 1, 1, 1, 0, 0],
'x_lim': [-10, 10],
'y_lim': [-10, 10],
'integral': 100,
'bbox_peak': True
},
RickerWavelet2D: {
'parameters': [1, 0, 0, 1],
'x_values': [0, 0, 0, 0, 0, 1, -1, 3, -3],
'y_values': [0, 1, -1, 3, -3, 0, 0, 0, 0],
'z_values': [1.0, 0.303265, 0.303265, -0.038881, -0.038881,
0.303265, 0.303265, -0.038881, -0.038881],
'x_lim': [-10, 11],
'y_lim': [-10, 11],
'integral': 0
},
TrapezoidDisk2D: {
'parameters': [1, 0, 0, 1, 1],
'x_values': [0, 0.5, 0, 1.5],
'y_values': [0, 0.5, 1.5, 0],
'z_values': [1, 1, 0.5, 0.5],
'x_lim': [-3, 3],
'y_lim': [-3, 3],
'bbox_peak': True
},
AiryDisk2D: {
'parameters': [7, 0, 0, 10],
'x_values': [0, 1, -1, -0.5, -0.5],
'y_values': [0, -1, 0.5, 0.5, -0.5],
'z_values': [7., 6.50158267, 6.68490643, 6.87251093, 6.87251093],
'x_lim': [-10, 10],
'y_lim': [-10, 10],
'requires_scipy': True
},
Moffat2D: {
'parameters': [1, 0, 0, 1, 2],
'x_values': [0, 1, -1, 3, -3],
'y_values': [0, -1, 3, 1, -3],
'z_values': [1.0, 0.111111, 0.008264, 0.008264, 0.00277],
'x_lim': [-3, 3],
'y_lim': [-3, 3]
},
Polynomial2D: {
'parameters': {'degree': 1, 'c0_0': 1., 'c1_0': 1., 'c0_1': 1.},
'x_values': [1, 2, 3],
'y_values': [1, 3, 2],
'z_values': [3, 6, 6],
'x_lim': [1, 100],
'y_lim': [1, 100]
},
Disk2D: {
'parameters': [1, 0, 0, 5],
'x_values': [-5, 5, -5, 5, 0, -10, 10],
'y_values': [-5, 5, 0, 0, 0, -10, 10],
'z_values': [0, 0, 1, 1, 1, 0, 0],
'x_lim': [-10, 10],
'y_lim': [-10, 10],
'integral': np.pi * 5 ** 2,
'bbox_peak': True
},
Ring2D: {
'parameters': [1, 0, 0, 5, 5],
'x_values': [-5, 5, -5, 5, 0, -10, 10],
'y_values': [-5, 5, 0, 0, 0, -10, 10],
'z_values': [1, 1, 1, 1, 0, 0, 0],
'x_lim': [-10, 10],
'y_lim': [-10, 10],
'integral': np.pi * (10 ** 2 - 5 ** 2),
'bbox_peak': True
},
Sersic2D: {
'parameters': [1, 25, 4, 50, 50, 0.5, -1],
'x_values': [0.0, 1, 10, 100],
'y_values': [1, 100, 0.0, 10],
'z_values': [1.686398e-02, 9.095221e-02, 2.341879e-02, 9.419231e-02],
'requires_scipy': True,
'x_lim': [1, 1e10],
'y_lim': [1, 1e10]
},
Planar2D: {
'parameters': [1, 1, 0],
'x_values': [0, np.pi, 42, -1],
'y_values': [np.pi, 0, -1, 42],
'z_values': [np.pi, np.pi, 41, 41],
'x_lim': [-10, 10],
'y_lim': [-10, 10],
'integral': 0
}
}
|
fd857ada0fd26e96966ed5171cf85e8a2ca5c1dc8976c3d3a924bf6a15deedb0 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Module to test fitting routines
"""
# pylint: disable=invalid-name
import os.path
import warnings
from unittest import mock
from importlib.metadata import EntryPoint
import pytest
import numpy as np
import unittest.mock as mk
from numpy import linalg
from numpy.testing import assert_allclose, assert_almost_equal, assert_equal
from astropy.modeling import models
from astropy.modeling.core import Fittable2DModel, Parameter
from astropy.modeling.fitting import (
SimplexLSQFitter, SLSQPLSQFitter, LinearLSQFitter, LevMarLSQFitter,
JointFitter, Fitter, FittingWithOutlierRemoval)
from astropy.modeling.optimizers import Optimization
from astropy.utils import NumpyRNGContext
from astropy.utils.data import get_pkg_data_filename
from astropy.stats import sigma_clip
from astropy.utils.compat.optional_deps import HAS_SCIPY
from astropy.utils.exceptions import AstropyUserWarning
from astropy.modeling.fitting import populate_entry_points
from . import irafutil
if HAS_SCIPY:
from scipy import optimize
fitters = [SimplexLSQFitter, SLSQPLSQFitter]
_RANDOM_SEED = 0x1337
class TestPolynomial2D:
"""Tests for 2D polynomail fitting."""
def setup_class(self):
self.model = models.Polynomial2D(2)
self.y, self.x = np.mgrid[:5, :5]
def poly2(x, y):
return 1 + 2 * x + 3 * x ** 2 + 4 * y + 5 * y ** 2 + 6 * x * y
self.z = poly2(self.x, self.y)
def test_poly2D_fitting(self):
fitter = LinearLSQFitter()
v = self.model.fit_deriv(x=self.x, y=self.y)
p = linalg.lstsq(v, self.z.flatten(), rcond=-1)[0]
new_model = fitter(self.model, self.x, self.y, self.z)
assert_allclose(new_model.parameters, p)
def test_eval(self):
fitter = LinearLSQFitter()
new_model = fitter(self.model, self.x, self.y, self.z)
assert_allclose(new_model(self.x, self.y), self.z)
@pytest.mark.skipif('not HAS_SCIPY')
def test_polynomial2D_nonlinear_fitting(self):
self.model.parameters = [.6, 1.8, 2.9, 3.7, 4.9, 6.7]
nlfitter = LevMarLSQFitter()
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
new_model = nlfitter(self.model, self.x, self.y, self.z)
assert_allclose(new_model.parameters, [1, 2, 3, 4, 5, 6])
class TestICheb2D:
"""
Tests 2D Chebyshev polynomial fitting
Create a 2D polynomial (z) using Polynomial2DModel and default coefficients
Fit z using a ICheb2D model
Evaluate the ICheb2D polynomial and compare with the initial z
"""
def setup_class(self):
self.pmodel = models.Polynomial2D(2)
self.y, self.x = np.mgrid[:5, :5]
self.z = self.pmodel(self.x, self.y)
self.cheb2 = models.Chebyshev2D(2, 2)
self.fitter = LinearLSQFitter()
def test_default_params(self):
self.cheb2.parameters = np.arange(9)
p = np.array([1344., 1772., 400., 1860., 2448., 552., 432., 568.,
128.])
z = self.cheb2(self.x, self.y)
model = self.fitter(self.cheb2, self.x, self.y, z)
assert_almost_equal(model.parameters, p)
def test_poly2D_cheb2D(self):
model = self.fitter(self.cheb2, self.x, self.y, self.z)
z1 = model(self.x, self.y)
assert_almost_equal(self.z, z1)
@pytest.mark.skipif('not HAS_SCIPY')
def test_chebyshev2D_nonlinear_fitting(self):
cheb2d = models.Chebyshev2D(2, 2)
cheb2d.parameters = np.arange(9)
z = cheb2d(self.x, self.y)
cheb2d.parameters = [0.1, .6, 1.8, 2.9, 3.7, 4.9, 6.7, 7.5, 8.9]
nlfitter = LevMarLSQFitter()
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
model = nlfitter(cheb2d, self.x, self.y, z)
assert_allclose(model.parameters, [0, 1, 2, 3, 4, 5, 6, 7, 8],
atol=10**-9)
@pytest.mark.skipif('not HAS_SCIPY')
def test_chebyshev2D_nonlinear_fitting_with_weights(self):
cheb2d = models.Chebyshev2D(2, 2)
cheb2d.parameters = np.arange(9)
z = cheb2d(self.x, self.y)
cheb2d.parameters = [0.1, .6, 1.8, 2.9, 3.7, 4.9, 6.7, 7.5, 8.9]
nlfitter = LevMarLSQFitter()
weights = np.ones_like(self.y)
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
model = nlfitter(cheb2d, self.x, self.y, z, weights=weights)
assert_allclose(model.parameters, [0, 1, 2, 3, 4, 5, 6, 7, 8],
atol=10**-9)
@pytest.mark.skipif('not HAS_SCIPY')
class TestJointFitter:
"""
Tests the joint fitting routine using 2 gaussian models
"""
def setup_class(self):
"""
Create 2 gaussian models and some data with noise.
Create a fitter for the two models keeping the amplitude parameter
common for the two models.
"""
self.g1 = models.Gaussian1D(10, mean=14.9, stddev=.3)
self.g2 = models.Gaussian1D(10, mean=13, stddev=.4)
self.jf = JointFitter([self.g1, self.g2],
{self.g1: ['amplitude'],
self.g2: ['amplitude']}, [9.8])
self.x = np.arange(10, 20, .1)
y1 = self.g1(self.x)
y2 = self.g2(self.x)
with NumpyRNGContext(_RANDOM_SEED):
n = np.random.randn(100)
self.ny1 = y1 + 2 * n
self.ny2 = y2 + 2 * n
self.jf(self.x, self.ny1, self.x, self.ny2)
def test_joint_parameter(self):
"""
Tests that the amplitude of the two models is the same
"""
assert_allclose(self.jf.fitparams[0], self.g1.parameters[0])
assert_allclose(self.jf.fitparams[0], self.g2.parameters[0])
def test_joint_fitter(self):
"""
Tests the fitting routine with similar procedure.
Compares the fitted parameters.
"""
p1 = [14.9, .3]
p2 = [13, .4]
A = 9.8
p = np.r_[A, p1, p2]
def model(A, p, x):
return A * np.exp(-0.5 / p[1] ** 2 * (x - p[0]) ** 2)
def errfunc(p, x1, y1, x2, y2):
return np.ravel(np.r_[model(p[0], p[1:3], x1) - y1,
model(p[0], p[3:], x2) - y2])
coeff, _ = optimize.leastsq(errfunc, p,
args=(self.x, self.ny1, self.x, self.ny2))
assert_allclose(coeff, self.jf.fitparams, rtol=10 ** (-2))
class TestLinearLSQFitter:
def test_compound_model_raises_error(self):
"""Test that if an user tries to use a compound model, raises an error"""
with pytest.raises(ValueError) as excinfo:
init_model1 = models.Polynomial1D(degree=2, c0=[1, 1], n_models=2)
init_model2 = models.Polynomial1D(degree=2, c0=[1, 1], n_models=2)
init_model_comp = init_model1 + init_model2
x = np.arange(10)
y = init_model_comp(x, model_set_axis=False)
fitter = LinearLSQFitter()
_ = fitter(init_model_comp, x, y)
assert "Model must be simple, not compound" in str(excinfo.value)
def test_chebyshev1D(self):
"""Tests fitting a 1D Chebyshev polynomial to some real world data."""
test_file = get_pkg_data_filename(os.path.join('data',
'idcompspec.fits'))
with open(test_file) as f:
lines = f.read()
reclist = lines.split('begin')
record = irafutil.IdentifyRecord(reclist[1])
coeffs = record.coeff
order = int(record.fields['order'])
initial_model = models.Chebyshev1D(order - 1,
domain=record.get_range())
fitter = LinearLSQFitter()
fitted_model = fitter(initial_model, record.x, record.z)
assert_allclose(fitted_model.parameters, np.array(coeffs),
rtol=10e-2)
def test_linear_fit_model_set(self):
"""Tests fitting multiple models simultaneously."""
init_model = models.Polynomial1D(degree=2, c0=[1, 1], n_models=2)
x = np.arange(10)
y_expected = init_model(x, model_set_axis=False)
assert y_expected.shape == (2, 10)
# Add a bit of random noise
with NumpyRNGContext(_RANDOM_SEED):
y = y_expected + np.random.normal(0, 0.01, size=y_expected.shape)
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y)
assert_allclose(fitted_model(x, model_set_axis=False), y_expected,
rtol=1e-1)
def test_linear_fit_2d_model_set(self):
"""Tests fitted multiple 2-D models simultaneously."""
init_model = models.Polynomial2D(degree=2, c0_0=[1, 1], n_models=2)
x = np.arange(10)
y = np.arange(10)
z_expected = init_model(x, y, model_set_axis=False)
assert z_expected.shape == (2, 10)
# Add a bit of random noise
with NumpyRNGContext(_RANDOM_SEED):
z = z_expected + np.random.normal(0, 0.01, size=z_expected.shape)
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y, z)
assert_allclose(fitted_model(x, y, model_set_axis=False), z_expected,
rtol=1e-1)
def test_linear_fit_fixed_parameter(self):
"""
Tests fitting a polynomial model with a fixed parameter (issue #6135).
"""
init_model = models.Polynomial1D(degree=2, c1=1)
init_model.c1.fixed = True
x = np.arange(10)
y = 2 + x + 0.5*x*x
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y)
assert_allclose(fitted_model.parameters, [2., 1., 0.5], atol=1e-14)
def test_linear_fit_model_set_fixed_parameter(self):
"""
Tests fitting a polynomial model set with a fixed parameter (#6135).
"""
init_model = models.Polynomial1D(degree=2, c1=[1, -2], n_models=2)
init_model.c1.fixed = True
x = np.arange(10)
yy = np.array([2 + x + 0.5*x*x, -2*x])
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, yy)
assert_allclose(fitted_model.c0, [2., 0.], atol=1e-14)
assert_allclose(fitted_model.c1, [1., -2.], atol=1e-14)
assert_allclose(fitted_model.c2, [0.5, 0.], atol=1e-14)
def test_linear_fit_2d_model_set_fixed_parameters(self):
"""
Tests fitting a 2d polynomial model set with fixed parameters (#6135).
"""
init_model = models.Polynomial2D(degree=2, c1_0=[1, 2], c0_1=[-0.5, 1],
n_models=2,
fixed={'c1_0': True, 'c0_1': True})
x, y = np.mgrid[0:5, 0:5]
zz = np.array([1+x-0.5*y+0.1*x*x, 2*x+y-0.2*y*y])
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y, zz)
assert_allclose(fitted_model(x, y, model_set_axis=False), zz,
atol=1e-14)
def test_linear_fit_model_set_masked_values(self):
"""
Tests model set fitting with masked value(s) (#4824, #6819).
"""
# NB. For single models, there is an equivalent doctest.
init_model = models.Polynomial1D(degree=1, n_models=2)
x = np.arange(10)
y = np.ma.masked_array([2*x+1, x-2], mask=np.zeros_like([x, x]))
y[0, 7] = 100. # throw off fit coefficients if unmasked
y.mask[0, 7] = True
y[1, 1:3] = -100.
y.mask[1, 1:3] = True
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y)
assert_allclose(fitted_model.c0, [1., -2.], atol=1e-14)
assert_allclose(fitted_model.c1, [2., 1.], atol=1e-14)
def test_linear_fit_2d_model_set_masked_values(self):
"""
Tests 2D model set fitting with masked value(s) (#4824, #6819).
"""
init_model = models.Polynomial2D(1, n_models=2)
x, y = np.mgrid[0:5, 0:5]
z = np.ma.masked_array([2*x+3*y+1, x-0.5*y-2],
mask=np.zeros_like([x, x]))
z[0, 3, 1] = -1000. # throw off fit coefficients if unmasked
z.mask[0, 3, 1] = True
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y, z)
assert_allclose(fitted_model.c0_0, [1., -2.], atol=1e-14)
assert_allclose(fitted_model.c1_0, [2., 1.], atol=1e-14)
assert_allclose(fitted_model.c0_1, [3., -0.5], atol=1e-14)
@pytest.mark.skipif('not HAS_SCIPY')
class TestNonLinearFitters:
"""Tests non-linear least squares fitting and the SLSQP algorithm."""
def setup_class(self):
self.initial_values = [100, 5, 1]
self.xdata = np.arange(0, 10, 0.1)
sigma = 4. * np.ones_like(self.xdata)
with NumpyRNGContext(_RANDOM_SEED):
yerror = np.random.normal(0, sigma)
def func(p, x):
return p[0] * np.exp(-0.5 / p[2] ** 2 * (x - p[1]) ** 2)
self.ydata = func(self.initial_values, self.xdata) + yerror
self.gauss = models.Gaussian1D(100, 5, stddev=1)
def test_estimated_vs_analytic_deriv(self):
"""
Runs `LevMarLSQFitter` with estimated and analytic derivatives of a
`Gaussian1D`.
"""
fitter = LevMarLSQFitter()
model = fitter(self.gauss, self.xdata, self.ydata)
g1e = models.Gaussian1D(100, 5.0, stddev=1)
efitter = LevMarLSQFitter()
emodel = efitter(g1e, self.xdata, self.ydata, estimate_jacobian=True)
assert_allclose(model.parameters, emodel.parameters, rtol=10 ** (-3))
def test_estimated_vs_analytic_deriv_with_weights(self):
"""
Runs `LevMarLSQFitter` with estimated and analytic derivatives of a
`Gaussian1D`.
"""
weights = 1.0 / (self.ydata / 10.)
fitter = LevMarLSQFitter()
model = fitter(self.gauss, self.xdata, self.ydata, weights=weights)
g1e = models.Gaussian1D(100, 5.0, stddev=1)
efitter = LevMarLSQFitter()
emodel = efitter(g1e, self.xdata, self.ydata, weights=weights, estimate_jacobian=True)
assert_allclose(model.parameters, emodel.parameters, rtol=10 ** (-3))
def test_with_optimize(self):
"""
Tests results from `LevMarLSQFitter` against `scipy.optimize.leastsq`.
"""
fitter = LevMarLSQFitter()
model = fitter(self.gauss, self.xdata, self.ydata,
estimate_jacobian=True)
def func(p, x):
return p[0] * np.exp(-0.5 / p[2] ** 2 * (x - p[1]) ** 2)
def errfunc(p, x, y):
return func(p, x) - y
result = optimize.leastsq(errfunc, self.initial_values,
args=(self.xdata, self.ydata))
assert_allclose(model.parameters, result[0], rtol=10 ** (-3))
def test_with_weights(self):
"""
Tests results from `LevMarLSQFitter` with weights.
"""
# part 1: weights are equal to 1
fitter = LevMarLSQFitter()
model = fitter(self.gauss, self.xdata, self.ydata,
estimate_jacobian=True)
withw = fitter(self.gauss, self.xdata, self.ydata,
estimate_jacobian=True, weights=np.ones_like(self.xdata))
assert_allclose(model.parameters, withw.parameters, rtol=10 ** (-4))
# part 2: weights are 0 or 1 (effectively, they are a mask)
weights = np.zeros_like(self.xdata)
weights[::2] = 1.
mask = weights >= 1.
model = fitter(self.gauss, self.xdata[mask], self.ydata[mask],
estimate_jacobian=True)
withw = fitter(self.gauss, self.xdata, self.ydata,
estimate_jacobian=True, weights=weights)
assert_allclose(model.parameters, withw.parameters, rtol=10 ** (-4))
@pytest.mark.filterwarnings(r'ignore:.* Maximum number of iterations reached')
@pytest.mark.filterwarnings(r'ignore:Values in x were outside bounds during a minimize step, clipping to bounds')
@pytest.mark.parametrize('fitter_class', fitters)
def test_fitter_against_LevMar(self, fitter_class):
"""Tests results from non-linear fitters against `LevMarLSQFitter`."""
levmar = LevMarLSQFitter()
fitter = fitter_class()
# This emits a warning from fitter that we need to ignore with
# pytest.mark.filterwarnings above.
new_model = fitter(self.gauss, self.xdata, self.ydata)
model = levmar(self.gauss, self.xdata, self.ydata)
assert_allclose(model.parameters, new_model.parameters,
rtol=10 ** (-4))
@pytest.mark.filterwarnings(r'ignore:Values in x were outside bounds during a minimize step, clipping to bounds')
def test_LSQ_SLSQP_with_constraints(self):
"""
Runs `LevMarLSQFitter` and `SLSQPLSQFitter` on a model with
constraints.
"""
g1 = models.Gaussian1D(100, 5, stddev=1)
g1.mean.fixed = True
fitter = LevMarLSQFitter()
fslsqp = SLSQPLSQFitter()
slsqp_model = fslsqp(g1, self.xdata, self.ydata)
model = fitter(g1, self.xdata, self.ydata)
assert_allclose(model.parameters, slsqp_model.parameters,
rtol=10 ** (-4))
def test_LevMar_with_weights(self):
"""
Tests that issue #11581 has been solved.
"""
np.random.seed(42)
norder = 2
fitter1 = LevMarLSQFitter()
fitter2 = LinearLSQFitter()
model = models.Polynomial1D(norder)
npts = 10000
c = [2.0, -10.0, 7.0]
tw = np.random.uniform(0.0, 10.0, npts)
tx = np.random.uniform(0.0, 10.0, npts)
ty = c[0] + c[1] * tx + c[2] * (tx ** 2)
ty += np.random.normal(0.0, 1.5, npts)
with pytest.warns(AstropyUserWarning, match=r'Model is linear in parameters'):
tf1 = fitter1(model, tx, ty, weights=tw)
tf2 = fitter2(model, tx, ty, weights=tw)
assert_allclose(tf1.parameters, tf2.parameters,
atol=10 ** (-16))
assert_allclose(tf1.parameters, c,
rtol=10 ** (-2), atol=10 ** (-2))
model = models.Gaussian1D()
fitter1(model, tx, ty, weights=tw)
model = models.Polynomial2D(norder)
nxpts = 100
nypts = 150
npts = nxpts * nypts
c = [1.0, 4.0, 7.0, -8.0, -9.0, -3.0]
tw = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts)
tx = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts)
ty = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts)
tz = c[0] + c[1] * tx + c[2] * (tx ** 2) + c[3] * ty + c[4] * (ty ** 2) + c[5] * tx * ty
tz += np.random.normal(0.0, 1.5, npts).reshape(nxpts, nypts)
with pytest.warns(AstropyUserWarning, match=r'Model is linear in parameters'):
tf1 = fitter1(model, tx, ty, tz, weights=tw)
tf2 = fitter2(model, tx, ty, tz, weights=tw)
assert_allclose(tf1.parameters, tf2.parameters,
atol=10 ** (-16))
assert_allclose(tf1.parameters, c,
rtol=10 ** (-2), atol=10 ** (-2))
def test_simplex_lsq_fitter(self):
"""A basic test for the `SimplexLSQ` fitter."""
class Rosenbrock(Fittable2DModel):
a = Parameter()
b = Parameter()
@staticmethod
def evaluate(x, y, a, b):
return (a - x) ** 2 + b * (y - x ** 2) ** 2
x = y = np.linspace(-3.0, 3.0, 100)
with NumpyRNGContext(_RANDOM_SEED):
z = Rosenbrock.evaluate(x, y, 1.0, 100.0)
z += np.random.normal(0., 0.1, size=z.shape)
fitter = SimplexLSQFitter()
r_i = Rosenbrock(1, 100)
r_f = fitter(r_i, x, y, z)
assert_allclose(r_f.parameters, [1.0, 100.0], rtol=1e-2)
def test_param_cov(self):
"""
Tests that the 'param_cov' fit_info entry gets the right answer for
*linear* least squares, where the answer is exact
"""
a = 2
b = 100
with NumpyRNGContext(_RANDOM_SEED):
x = np.linspace(0, 1, 100)
# y scatter is amplitude ~1 to make sure covarience is
# non-negligible
y = x*a + b + np.random.randn(len(x))
# first compute the ordinary least squares covariance matrix
X = np.vstack([x, np.ones(len(x))]).T
beta = np.matmul(np.matmul(np.linalg.inv(np.matmul(X.T, X)), X.T), y.T)
s2 = (np.sum((y - np.matmul(X, beta).ravel())**2) /
(len(y) - len(beta)))
olscov = np.linalg.inv(np.matmul(X.T, X)) * s2
# now do the non-linear least squares fit
mod = models.Linear1D(a, b)
fitter = LevMarLSQFitter()
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
fmod = fitter(mod, x, y)
assert_allclose(fmod.parameters, beta.ravel())
assert_allclose(olscov, fitter.fit_info['param_cov'])
class TestEntryPoint:
"""Tests population of fitting with entry point fitters"""
def setup_class(self):
self.exception_not_thrown = Exception("The test should not have gotten here. There was no exception thrown")
def successfulimport(self):
# This should work
class goodclass(Fitter):
__name__ = "GoodClass"
return goodclass
def raiseimporterror(self):
# This should fail as it raises an Import Error
raise ImportError
def returnbadfunc(self):
def badfunc():
# This should import but it should fail type check
pass
return badfunc
def returnbadclass(self):
# This should import But it should fail subclass type check
class badclass:
pass
return badclass
def test_working(self):
"""This should work fine"""
mock_entry_working = mock.create_autospec(EntryPoint)
mock_entry_working.name = "Working"
mock_entry_working.load = self.successfulimport
populate_entry_points([mock_entry_working])
def test_import_error(self):
"""This raises an import error on load to test that it is handled correctly"""
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
mock_entry_importerror = mock.create_autospec(EntryPoint)
mock_entry_importerror.name = "IErr"
mock_entry_importerror.load = self.raiseimporterror
populate_entry_points([mock_entry_importerror])
except AstropyUserWarning as w:
if "ImportError" in w.args[0]: # any error for this case should have this in it.
pass
else:
raise w
else:
raise self.exception_not_thrown
def test_bad_func(self):
"""This returns a function which fails the type check"""
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
mock_entry_badfunc = mock.create_autospec(EntryPoint)
mock_entry_badfunc.name = "BadFunc"
mock_entry_badfunc.load = self.returnbadfunc
populate_entry_points([mock_entry_badfunc])
except AstropyUserWarning as w:
if "Class" in w.args[0]: # any error for this case should have this in it.
pass
else:
raise w
else:
raise self.exception_not_thrown
def test_bad_class(self):
"""This returns a class which doesn't inherient from fitter """
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
mock_entry_badclass = mock.create_autospec(EntryPoint)
mock_entry_badclass.name = "BadClass"
mock_entry_badclass.load = self.returnbadclass
populate_entry_points([mock_entry_badclass])
except AstropyUserWarning as w:
if 'modeling.Fitter' in w.args[0]: # any error for this case should have this in it.
pass
else:
raise w
else:
raise self.exception_not_thrown
@pytest.mark.skipif('not HAS_SCIPY')
class Test1DFittingWithOutlierRemoval:
def setup_class(self):
self.x = np.linspace(-5., 5., 200)
self.model_params = (3.0, 1.3, 0.8)
def func(p, x):
return p[0]*np.exp(-0.5*(x - p[1])**2/p[2]**2)
self.y = func(self.model_params, self.x)
@pytest.mark.filterwarnings('ignore:The fit may be unsuccessful')
@pytest.mark.filterwarnings(r'ignore:Values in x were outside bounds during a minimize step, clipping to bounds')
def test_with_fitters_and_sigma_clip(self):
import scipy.stats as stats
np.random.seed(0)
c = stats.bernoulli.rvs(0.25, size=self.x.shape)
self.y += (np.random.normal(0., 0.2, self.x.shape) +
c*np.random.normal(3.0, 5.0, self.x.shape))
g_init = models.Gaussian1D(amplitude=1., mean=0, stddev=1.)
# test with Levenberg-Marquardt Least Squares fitter
fit = FittingWithOutlierRemoval(LevMarLSQFitter(), sigma_clip,
niter=3, sigma=3.0)
fitted_model, _ = fit(g_init, self.x, self.y)
assert_allclose(fitted_model.parameters, self.model_params, rtol=1e-1)
# test with Sequential Least Squares Programming fitter
fit = FittingWithOutlierRemoval(SLSQPLSQFitter(), sigma_clip,
niter=3, sigma=3.0)
fitted_model, _ = fit(g_init, self.x, self.y)
assert_allclose(fitted_model.parameters, self.model_params, rtol=1e-1)
# test with Simplex LSQ fitter
fit = FittingWithOutlierRemoval(SimplexLSQFitter(), sigma_clip,
niter=3, sigma=3.0)
fitted_model, _ = fit(g_init, self.x, self.y)
assert_allclose(fitted_model.parameters, self.model_params, atol=1e-1)
@pytest.mark.skipif('not HAS_SCIPY')
class Test2DFittingWithOutlierRemoval:
def setup_class(self):
self.y, self.x = np.mgrid[-3:3:128j, -3:3:128j]
self.model_params = (3.0, 1.0, 0.0, 0.8, 0.8)
def Gaussian_2D(p, pos):
return p[0]*np.exp(-0.5*(pos[0] - p[2])**2 / p[4]**2 -
0.5*(pos[1] - p[1])**2 / p[3]**2)
self.z = Gaussian_2D(self.model_params, np.array([self.y, self.x]))
def initial_guess(self, data, pos):
y = pos[0]
x = pos[1]
"""computes the centroid of the data as the initial guess for the
center position"""
wx = x * data
wy = y * data
total_intensity = np.sum(data)
x_mean = np.sum(wx) / total_intensity
y_mean = np.sum(wy) / total_intensity
x_to_pixel = x[0].size / (x[x[0].size - 1][x[0].size - 1] - x[0][0])
y_to_pixel = y[0].size / (y[y[0].size - 1][y[0].size - 1] - y[0][0])
x_pos = np.around(x_mean * x_to_pixel + x[0].size / 2.).astype(int)
y_pos = np.around(y_mean * y_to_pixel + y[0].size / 2.).astype(int)
amplitude = data[y_pos][x_pos]
return amplitude, x_mean, y_mean
@pytest.mark.filterwarnings('ignore:The fit may be unsuccessful')
@pytest.mark.filterwarnings(r'ignore:Values in x were outside bounds during a minimize step, clipping to bounds')
def test_with_fitters_and_sigma_clip(self):
import scipy.stats as stats
np.random.seed(0)
c = stats.bernoulli.rvs(0.25, size=self.z.shape)
self.z += (np.random.normal(0., 0.2, self.z.shape) +
c*np.random.normal(self.z, 2.0, self.z.shape))
guess = self.initial_guess(self.z, np.array([self.y, self.x]))
g2_init = models.Gaussian2D(amplitude=guess[0], x_mean=guess[1],
y_mean=guess[2], x_stddev=0.75,
y_stddev=1.25)
# test with Levenberg-Marquardt Least Squares fitter
fit = FittingWithOutlierRemoval(LevMarLSQFitter(), sigma_clip,
niter=3, sigma=3.)
fitted_model, _ = fit(g2_init, self.x, self.y, self.z)
assert_allclose(fitted_model.parameters[0:5], self.model_params,
atol=1e-1)
# test with Sequential Least Squares Programming fitter
fit = FittingWithOutlierRemoval(SLSQPLSQFitter(), sigma_clip, niter=3,
sigma=3.)
fitted_model, _ = fit(g2_init, self.x, self.y, self.z)
assert_allclose(fitted_model.parameters[0:5], self.model_params,
atol=1e-1)
# test with Simplex LSQ fitter
fit = FittingWithOutlierRemoval(SimplexLSQFitter(), sigma_clip,
niter=3, sigma=3.)
fitted_model, _ = fit(g2_init, self.x, self.y, self.z)
assert_allclose(fitted_model.parameters[0:5], self.model_params,
atol=1e-1)
def test_1d_set_fitting_with_outlier_removal():
"""Test model set fitting with outlier removal (issue #6819)"""
poly_set = models.Polynomial1D(2, n_models=2)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(),
sigma_clip, sigma=2.5, niter=3,
cenfunc=np.ma.mean, stdfunc=np.ma.std)
x = np.arange(10)
y = np.array([2.5*x - 4, 2*x*x + x + 10])
y[1, 5] = -1000 # outlier
poly_set, filt_y = fitter(poly_set, x, y)
assert_allclose(poly_set.c0, [-4., 10.], atol=1e-14)
assert_allclose(poly_set.c1, [2.5, 1.], atol=1e-14)
assert_allclose(poly_set.c2, [0., 2.], atol=1e-14)
def test_2d_set_axis_2_fitting_with_outlier_removal():
"""Test fitting 2D model set (axis 2) with outlier removal (issue #6819)"""
poly_set = models.Polynomial2D(1, n_models=2, model_set_axis=2)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(),
sigma_clip, sigma=2.5, niter=3,
cenfunc=np.ma.mean, stdfunc=np.ma.std)
y, x = np.mgrid[0:5, 0:5]
z = np.rollaxis(np.array([x+y, 1-0.1*x+0.2*y]), 0, 3)
z[3, 3:5, 0] = 100. # outliers
poly_set, filt_z = fitter(poly_set, x, y, z)
assert_allclose(poly_set.c0_0, [[[0., 1.]]], atol=1e-14)
assert_allclose(poly_set.c1_0, [[[1., -0.1]]], atol=1e-14)
assert_allclose(poly_set.c0_1, [[[1., 0.2]]], atol=1e-14)
@pytest.mark.skipif('not HAS_SCIPY')
class TestWeightedFittingWithOutlierRemoval:
"""Issue #7020 """
def setup_class(self):
# values of x,y not important as we fit y(x,y) = p0 model here
self.y, self.x = np.mgrid[0:20, 0:20]
self.z = np.mod(self.x + self.y, 2) * 2 - 1 # -1,1 chessboard
self.weights = np.mod(self.x + self.y, 2) * 2 + 1 # 1,3 chessboard
self.z[0, 0] = 1000.0 # outlier
self.z[0, 1] = 1000.0 # outlier
self.x1d = self.x.flatten()
self.z1d = self.z.flatten()
self.weights1d = self.weights.flatten()
def test_1d_without_weights_without_sigma_clip(self):
model = models.Polynomial1D(0)
fitter = LinearLSQFitter()
fit = fitter(model, self.x1d, self.z1d)
assert_allclose(fit.parameters[0], self.z1d.mean(), atol=10**(-2))
def test_1d_without_weights_with_sigma_clip(self):
model = models.Polynomial1D(0)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip,
niter=3, sigma=3.)
fit, mask = fitter(model, self.x1d, self.z1d)
assert((~mask).sum() == self.z1d.size - 2)
assert(mask[0] and mask[1])
assert_allclose(fit.parameters[0], 0.0, atol=10**(-2)) # with removed outliers mean is 0.0
def test_1d_with_weights_without_sigma_clip(self):
model = models.Polynomial1D(0)
fitter = LinearLSQFitter()
fit = fitter(model, self.x1d, self.z1d, weights=self.weights1d)
assert(fit.parameters[0] > 1.0) # outliers pulled it high
def test_1d_with_weights_with_sigma_clip(self):
"""smoke test for #7020 - fails without fitting.py patch because weights does not propagate"""
model = models.Polynomial1D(0)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip,
niter=3, sigma=3.)
fit, filtered = fitter(model, self.x1d, self.z1d, weights=self.weights1d)
assert(fit.parameters[0] > 10**(-2)) # weights pulled it > 0
assert(fit.parameters[0] < 1.0) # outliers didn't pull it out of [-1:1] because they had been removed
def test_1d_set_with_common_weights_with_sigma_clip(self):
"""added for #6819 (1D model set with weights in common)"""
model = models.Polynomial1D(0, n_models=2)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip,
niter=3, sigma=3.)
z1d = np.array([self.z1d, self.z1d])
fit, filtered = fitter(model, self.x1d, z1d, weights=self.weights1d)
assert_allclose(fit.parameters, [0.8, 0.8], atol=1e-14)
def test_1d_set_with_weights_with_sigma_clip(self):
"""1D model set with separate weights"""
model = models.Polynomial1D(0, n_models=2)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip,
niter=3, sigma=3.)
z1d = np.array([self.z1d, self.z1d])
weights = np.array([self.weights1d, self.weights1d])
fit, filtered = fitter(model, self.x1d, z1d, weights=weights)
assert_allclose(fit.parameters, [0.8, 0.8], atol=1e-14)
def test_2d_without_weights_without_sigma_clip(self):
model = models.Polynomial2D(0)
fitter = LinearLSQFitter()
fit = fitter(model, self.x, self.y, self.z)
assert_allclose(fit.parameters[0], self.z.mean(), atol=10**(-2))
def test_2d_without_weights_with_sigma_clip(self):
model = models.Polynomial2D(0)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip,
niter=3, sigma=3.)
fit, mask = fitter(model, self.x, self.y, self.z)
assert((~mask).sum() == self.z.size - 2)
assert(mask[0, 0] and mask[0, 1])
assert_allclose(fit.parameters[0], 0.0, atol=10**(-2))
def test_2d_with_weights_without_sigma_clip(self):
model = models.Polynomial2D(0)
fitter = LevMarLSQFitter() # LinearLSQFitter doesn't handle weights properly in 2D
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
fit = fitter(model, self.x, self.y, self.z, weights=self.weights)
assert(fit.parameters[0] > 1.0) # outliers pulled it high
def test_2d_linear_with_weights_without_sigma_clip(self):
model = models.Polynomial2D(0)
fitter = LinearLSQFitter() # LinearLSQFitter doesn't handle weights properly in 2D
fit = fitter(model, self.x, self.y, self.z, weights=self.weights)
assert(fit.parameters[0] > 1.0) # outliers pulled it high
def test_2d_with_weights_with_sigma_clip(self):
"""smoke test for #7020 - fails without fitting.py patch because
weights does not propagate"""
model = models.Polynomial2D(0)
fitter = FittingWithOutlierRemoval(LevMarLSQFitter(), sigma_clip,
niter=3, sigma=3.)
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
fit, filtered = fitter(model, self.x, self.y, self.z,
weights=self.weights)
assert(fit.parameters[0] > 10**(-2)) # weights pulled it > 0
assert(fit.parameters[0] < 1.0) # outliers didn't pull it out of [-1:1] because they had been removed
def test_2d_linear_with_weights_with_sigma_clip(self):
"""same as test above with a linear fitter."""
model = models.Polynomial2D(0)
fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip,
niter=3, sigma=3.)
fit, filtered = fitter(model, self.x, self.y, self.z,
weights=self.weights)
assert(fit.parameters[0] > 10**(-2)) # weights pulled it > 0
assert(fit.parameters[0] < 1.0) # outliers didn't pull it out of [-1:1] because they had been removed
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitters_with_weights():
"""Issue #5737 """
Xin, Yin = np.mgrid[0:21, 0:21]
fitter = LevMarLSQFitter()
with NumpyRNGContext(_RANDOM_SEED):
zsig = np.random.normal(0, 0.01, size=Xin.shape)
# Non-linear model
g2 = models.Gaussian2D(10, 10, 9, 2, 3)
z = g2(Xin, Yin)
gmod = fitter(models.Gaussian2D(15, 7, 8, 1.3, 1.2), Xin, Yin, z + zsig)
assert_allclose(gmod.parameters, g2.parameters, atol=10 ** (-2))
# Linear model
p2 = models.Polynomial2D(3)
p2.parameters = np.arange(10)/1.2
z = p2(Xin, Yin)
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
pmod = fitter(models.Polynomial2D(3), Xin, Yin, z + zsig)
assert_allclose(pmod.parameters, p2.parameters, atol=10 ** (-2))
def test_linear_fitter_with_weights():
"""Regression test for #7035"""
Xin, Yin = np.mgrid[0:21, 0:21]
fitter = LinearLSQFitter()
with NumpyRNGContext(_RANDOM_SEED):
zsig = np.random.normal(0, 0.01, size=Xin.shape)
p2 = models.Polynomial2D(3)
p2.parameters = np.arange(10)/1.2
z = p2(Xin, Yin)
pmod = fitter(models.Polynomial2D(3), Xin, Yin, z + zsig, weights=zsig**(-2))
assert_allclose(pmod.parameters, p2.parameters, atol=10 ** (-2))
def test_linear_fitter_with_weights_flat():
"""Same as the above #7035 test but with flattened inputs"""
Xin, Yin = np.mgrid[0:21, 0:21]
Xin, Yin = Xin.flatten(), Yin.flatten()
fitter = LinearLSQFitter()
with NumpyRNGContext(_RANDOM_SEED):
zsig = np.random.normal(0, 0.01, size=Xin.shape)
p2 = models.Polynomial2D(3)
p2.parameters = np.arange(10)/1.2
z = p2(Xin, Yin)
pmod = fitter(models.Polynomial2D(3), Xin, Yin, z + zsig, weights=zsig**(-2))
assert_allclose(pmod.parameters, p2.parameters, atol=10 ** (-2))
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.filterwarnings('ignore:The fit may be unsuccessful')
def test_fitters_interface():
"""
Test that ``**kwargs`` work with all optimizers.
This is a basic smoke test.
"""
levmar = LevMarLSQFitter()
slsqp = SLSQPLSQFitter()
simplex = SimplexLSQFitter()
kwargs = {'maxiter': 77, 'verblevel': 1, 'epsilon': 1e-2, 'acc': 1e-6}
simplex_kwargs = {'maxiter': 77, 'verblevel': 1, 'acc': 1e-6}
model = models.Gaussian1D(10, 4, .3)
x = np.arange(21)
y = model(x)
_ = slsqp(model, x, y, **kwargs)
_ = simplex(model, x, y, **simplex_kwargs)
kwargs.pop('verblevel')
_ = levmar(model, x, y, **kwargs)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('fitter_class', [SLSQPLSQFitter, SimplexLSQFitter])
def test_optimizers(fitter_class):
fitter = fitter_class()
# Test maxiter
assert fitter._opt_method.maxiter == 100
fitter._opt_method.maxiter = 1000
assert fitter._opt_method.maxiter == 1000
# Test eps
assert fitter._opt_method.eps == np.sqrt(np.finfo(float).eps)
fitter._opt_method.eps = 1e-16
assert fitter._opt_method.eps == 1e-16
# Test acc
assert fitter._opt_method.acc == 1e-7
fitter._opt_method.acc = 1e-16
assert fitter._opt_method.acc == 1e-16
# Test repr
assert repr(fitter._opt_method) ==\
f"{fitter._opt_method.__class__.__name__}()"
fitparams = mk.MagicMock()
final_func_val = mk.MagicMock()
numiter = mk.MagicMock()
funcalls = mk.MagicMock()
exit_mode = 1
mess = mk.MagicMock()
xtol = mk.MagicMock()
if fitter_class == SLSQPLSQFitter:
return_value = (fitparams, final_func_val, numiter, exit_mode, mess)
fit_info = {
'final_func_val': final_func_val,
'numiter': numiter,
'exit_mode': exit_mode,
'message': mess
}
else:
return_value = (fitparams, final_func_val, numiter, funcalls, exit_mode)
fit_info = {
'final_func_val': final_func_val,
'numiter': numiter,
'exit_mode': exit_mode,
'num_function_calls': funcalls
}
with mk.patch.object(fitter._opt_method.__class__, 'opt_method',
return_value=return_value):
with pytest.warns(AstropyUserWarning, match=r"The fit may be unsuccessful; .*"):
assert (fitparams, fit_info) == fitter._opt_method(mk.MagicMock(), mk.MagicMock(),
mk.MagicMock(), xtol=xtol)
assert fit_info == fitter._opt_method.fit_info
if isinstance(fitter, SLSQPLSQFitter):
fitter._opt_method.acc == 1e-16
else:
fitter._opt_method.acc == xtol
@mk.patch.multiple(Optimization, __abstractmethods__=set())
def test_Optimization_abstract_call():
optimization = Optimization(mk.MagicMock())
with pytest.raises(NotImplementedError) as err:
optimization()
assert str(err.value) ==\
"Subclasses should implement this method"
def test_fitting_with_outlier_removal_niter():
"""
Test that FittingWithOutlierRemoval stops prior to reaching niter if the
set of masked points has converged and correctly reports the actual number
of iterations performed.
"""
# 2 rows with some noise around a constant level and 1 deviant point:
x = np.arange(25)
with NumpyRNGContext(_RANDOM_SEED):
y = np.random.normal(loc=10., scale=1., size=(2, 25))
y[0, 14] = 100.
# Fit 2 models with up to 5 iterations (should only take 2):
fitter = FittingWithOutlierRemoval(
fitter=LinearLSQFitter(), outlier_func=sigma_clip, niter=5,
sigma_lower=3., sigma_upper=3., maxiters=1
)
model, mask = fitter(models.Chebyshev1D(2, n_models=2), x, y)
# Confirm that only the deviant point was rejected, in 2 iterations:
assert_equal(np.where(mask), [[0], [14]])
assert fitter.fit_info['niter'] == 2
# Refit just the first row without any rejection iterations, to ensure
# there are no regressions for that special case:
fitter = FittingWithOutlierRemoval(
fitter=LinearLSQFitter(), outlier_func=sigma_clip, niter=0,
sigma_lower=3., sigma_upper=3., maxiters=1
)
model, mask = fitter(models.Chebyshev1D(2), x, y[0])
# Confirm that there were no iterations or rejected points:
assert mask.sum() == 0
assert fitter.fit_info['niter'] == 0
@pytest.mark.skipif('not HAS_SCIPY')
class TestFittingUncertanties:
"""
Test that parameter covariance is calculated correctly for the fitters
that do so (currently LevMarLSQFitter, LinearLSQFitter).
"""
example_1D_models = [models.Polynomial1D(2), models.Linear1D()]
example_1D_sets = [models.Polynomial1D(2, n_models=2, model_set_axis=False),
models.Linear1D(n_models=2, slope=[1., 1.], intercept=[0, 0])]
def setup_class(self):
self.x = np.arange(10)
self.x_grid = np.random.randint(0, 100, size=100).reshape(10, 10)
self.y_grid = np.random.randint(0, 100, size=100).reshape(10, 10)
self.rand_grid = np.random.random(100).reshape(10, 10)
self.rand = self.rand_grid[0]
@pytest.mark.parametrize(('single_model', 'model_set'),
list(zip(example_1D_models, example_1D_sets)))
def test_1d_models(self, single_model, model_set):
""" Test that fitting uncertainties are computed correctly for 1D models
and 1D model sets. Use covariance/stds given by LevMarLSQFitter as
a benchmark since they are returned by the numpy fitter.
"""
levmar_fitter = LevMarLSQFitter(calc_uncertainties=True)
linlsq_fitter = LinearLSQFitter(calc_uncertainties=True)
# test 1D single models
# fit single model w/ nonlinear fitter
y = single_model(self.x) + self.rand
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
fit_model_levmar = levmar_fitter(single_model, self.x, y)
cov_model_levmar = fit_model_levmar.cov_matrix.cov_matrix
# fit single model w/ linlsq fitter
fit_model_linlsq = linlsq_fitter(single_model, self.x, y)
cov_model_linlsq = fit_model_linlsq.cov_matrix.cov_matrix
# check covariance, stds computed correctly computed
assert_allclose(cov_model_linlsq, cov_model_levmar)
assert_allclose(np.sqrt(np.diag(cov_model_linlsq)),
fit_model_linlsq.stds.stds)
# now test 1D model sets
# fit set of models w/ linear fitter
y = model_set(self.x, model_set_axis=False) +\
np.array([self.rand, self.rand])
fit_1d_set_linlsq = linlsq_fitter(model_set, self.x, y)
cov_1d_set_linlsq = [j.cov_matrix for j in
fit_1d_set_linlsq.cov_matrix]
# make sure cov matrix from single model fit w/ levmar fitter matches
# the cov matrix of first model in the set
assert_allclose(cov_1d_set_linlsq[0], cov_model_levmar)
assert_allclose(np.sqrt(np.diag(cov_1d_set_linlsq[0])),
fit_1d_set_linlsq.stds[0].stds)
def test_2d_models(self):
"""
Test that fitting uncertainties are computed correctly for 2D models
and 2D model sets. Use covariance/stds given by LevMarLSQFitter as
a benchmark since they are returned by the numpy fitter.
"""
levmar_fitter = LevMarLSQFitter(calc_uncertainties=True)
linlsq_fitter = LinearLSQFitter(calc_uncertainties=True)
single_model = models.Polynomial2D(2, c0_0=2)
model_set = models.Polynomial2D(degree=2, n_models=2, c0_0=[2, 3],
model_set_axis=False)
# fit single model w/ nonlinear fitter
z_grid = single_model(self.x_grid, self.y_grid) + self.rand_grid
with pytest.warns(AstropyUserWarning,
match=r'Model is linear in parameters'):
fit_model_levmar = levmar_fitter(single_model, self.x_grid,
self.y_grid, z_grid)
cov_model_levmar = fit_model_levmar.cov_matrix.cov_matrix
# fit single model w/ nonlinear fitter
fit_model_linlsq = linlsq_fitter(single_model, self.x_grid,
self.y_grid, z_grid)
cov_model_linlsq = fit_model_linlsq.cov_matrix.cov_matrix
assert_allclose(cov_model_levmar, cov_model_linlsq)
assert_allclose(np.sqrt(np.diag(cov_model_linlsq)),
fit_model_linlsq.stds.stds)
# fit 2d model set
z_grid = model_set(self.x_grid, self.y_grid) + np.array((self.rand_grid,
self.rand_grid))
fit_2d_set_linlsq = linlsq_fitter(model_set, self.x_grid, self.y_grid,
z_grid)
cov_2d_set_linlsq = [j.cov_matrix for j in fit_2d_set_linlsq.cov_matrix]
# make sure cov matrix from single model fit w/ levmar fitter matches
# the cov matrix of first model in the set
assert_allclose(cov_2d_set_linlsq[0], cov_model_levmar)
assert_allclose(np.sqrt(np.diag(cov_2d_set_linlsq[0])),
fit_2d_set_linlsq.stds[0].stds)
def test_covariance_std_printing_indexing(self, capsys):
"""
Test printing methods and indexing.
"""
# test str representation for Covariance/stds
fitter = LinearLSQFitter(calc_uncertainties=True)
mod = models.Linear1D()
fit_mod = fitter(mod, self.x, mod(self.x)+self.rand)
print(fit_mod.cov_matrix)
captured = capsys.readouterr()
assert "slope | 0.001" in captured.out
assert "intercept| -0.006, 0.041" in captured.out
print(fit_mod.stds)
captured = capsys.readouterr()
assert "slope | 0.038" in captured.out
assert "intercept| 0.203" in captured.out
# test 'pprint' for Covariance/stds
print(fit_mod.cov_matrix.pprint(round_val=5, max_lines=1))
captured = capsys.readouterr()
assert "slope | 0.00144" in captured.out
assert "intercept" not in captured.out
print(fit_mod.stds.pprint(max_lines=1, round_val=5))
captured = capsys.readouterr()
assert "slope | 0.03799" in captured.out
assert "intercept" not in captured.out
# test indexing for Covariance class.
assert fit_mod.cov_matrix[0, 0] == fit_mod.cov_matrix['slope', 'slope']
# test indexing for stds class.
assert fit_mod.stds[1] == fit_mod.stds['intercept']
|
51289dbb8573aace421e08e79a55decfd5a2a17a531b3f0bf0940064f34413a9 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# pylint: disable=invalid-name
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal, assert_array_less
from astropy import units as u
from astropy.modeling import models, InputParameterError
from astropy.coordinates import Angle
from astropy.modeling import fitting
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
def test_sigma_constant():
"""
Test that the GAUSSIAN_SIGMA_TO_FWHM constant matches the
gaussian_sigma_to_fwhm constant in astropy.stats. We define
it manually in astropy.modeling to avoid importing from
astropy.stats.
"""
from astropy.stats.funcs import gaussian_sigma_to_fwhm
from astropy.modeling.functional_models import GAUSSIAN_SIGMA_TO_FWHM
assert gaussian_sigma_to_fwhm == GAUSSIAN_SIGMA_TO_FWHM
def test_Trapezoid1D():
"""Regression test for https://github.com/astropy/astropy/issues/1721"""
model = models.Trapezoid1D(amplitude=4.2, x_0=2.0, width=1.0, slope=3)
xx = np.linspace(0, 4, 8)
yy = model(xx)
yy_ref = [0., 1.41428571, 3.12857143, 4.2, 4.2, 3.12857143, 1.41428571, 0.]
assert_allclose(yy, yy_ref, rtol=0, atol=1e-6)
def test_Gaussian1D():
model = models.Gaussian1D(4.2, 1.7, stddev=5.1)
x = np.mgrid[0:5]
g = model(x)
g_ref = [3.97302977, 4.16062403, 4.19273985, 4.06574509, 3.79389376]
assert_allclose(g, g_ref, rtol=0, atol=1e-6)
assert_allclose(model.fwhm, 12.009582229657841)
def test_Gaussian2D():
"""
Test rotated elliptical Gaussian2D model.
https://github.com/astropy/astropy/pull/2038
"""
model = models.Gaussian2D(4.2, 1.7, 3.1, x_stddev=5.1, y_stddev=3.3,
theta=np.pi/6.)
y, x = np.mgrid[0:5, 0:5]
g = model(x, y)
g_ref = [[3.01907812, 2.99051889, 2.81271552, 2.5119566, 2.13012709],
[3.55982239, 3.6086023, 3.4734158, 3.17454575, 2.75494838],
[3.88059142, 4.0257528, 3.96554926, 3.70908389, 3.29410187],
[3.91095768, 4.15212857, 4.18567526, 4.00652015, 3.64146544],
[3.6440466, 3.95922417, 4.08454159, 4.00113878, 3.72161094]]
assert_allclose(g, g_ref, rtol=0, atol=1e-6)
assert_allclose([model.x_fwhm, model.y_fwhm],
[12.009582229657841, 7.7709061486021325])
def test_Gaussian2DCovariance():
"""
Test rotated elliptical Gaussian2D model when cov_matrix is input.
https://github.com/astropy/astropy/pull/2199
"""
cov_matrix = [[49., -16.], [-16., 9.]]
model = models.Gaussian2D(17., 2.0, 2.5, cov_matrix=cov_matrix)
y, x = np.mgrid[0:5, 0:5]
g = model(x, y)
g_ref = [[4.3744505, 5.8413977, 7.42988694, 9.00160175, 10.38794269],
[8.83290201, 10.81772851, 12.61946384, 14.02225593, 14.84113227],
[13.68528889, 15.37184621, 16.44637743, 16.76048705, 16.26953638],
[16.26953638, 16.76048705, 16.44637743, 15.37184621, 13.68528889],
[14.84113227, 14.02225593, 12.61946384, 10.81772851, 8.83290201]]
assert_allclose(g, g_ref, rtol=0, atol=1e-6)
# Test bad cov_matrix shape
cov_matrix = [[49., 3.14, -16.],
[3.14, -16., 9.],
[-16, 27, 3.14]]
with pytest.raises(ValueError) as err:
models.Gaussian2D(17., 2.0, 2.5, cov_matrix=cov_matrix)
assert str(err.value) == \
"Covariance matrix must be 2x2"
def test_Gaussian2DRotation():
amplitude = 42
x_mean, y_mean = 0, 0
x_stddev, y_stddev = 2, 3
theta = Angle(10, 'deg')
pars = dict(amplitude=amplitude, x_mean=x_mean, y_mean=y_mean,
x_stddev=x_stddev, y_stddev=y_stddev)
rotation = models.Rotation2D(angle=theta.degree)
point1 = (x_mean + 2 * x_stddev, y_mean + 2 * y_stddev)
point2 = rotation(*point1)
g1 = models.Gaussian2D(theta=0, **pars)
g2 = models.Gaussian2D(theta=theta.radian, **pars)
value1 = g1(*point1)
value2 = g2(*point2)
assert_allclose(value1, value2)
def test_Gaussian2D_invalid_inputs():
x_stddev = 5.1
y_stddev = 3.3
theta = 10
cov_matrix = [[49., -16.], [-16., 9.]]
# first make sure the valid ones are OK
models.Gaussian2D()
models.Gaussian2D(x_stddev=x_stddev, y_stddev=y_stddev, theta=theta)
models.Gaussian2D(x_stddev=None, y_stddev=y_stddev, theta=theta)
models.Gaussian2D(x_stddev=x_stddev, y_stddev=None, theta=theta)
models.Gaussian2D(x_stddev=x_stddev, y_stddev=y_stddev, theta=None)
models.Gaussian2D(cov_matrix=cov_matrix)
with pytest.raises(InputParameterError):
models.Gaussian2D(x_stddev=0, cov_matrix=cov_matrix)
with pytest.raises(InputParameterError):
models.Gaussian2D(y_stddev=0, cov_matrix=cov_matrix)
with pytest.raises(InputParameterError):
models.Gaussian2D(theta=0, cov_matrix=cov_matrix)
@pytest.mark.parametrize('gamma', (10, -10))
def test_moffat_fwhm(gamma):
ans = 34.641016151377542
kwargs = {'gamma': gamma, 'alpha': 0.5}
m1 = models.Moffat1D(**kwargs)
m2 = models.Moffat2D(**kwargs)
assert_allclose([m1.fwhm, m2.fwhm], ans)
assert_array_less(0, [m1.fwhm, m2.fwhm])
def test_RedshiftScaleFactor():
"""Like ``test_ScaleModel()``."""
# Scale by a scalar
m = models.RedshiftScaleFactor(0.4)
assert m(0) == 0
assert_array_equal(m([1, 2]), [1.4, 2.8])
assert_allclose(m.inverse(m([1, 2])), [1, 2])
# Scale by a list
m = models.RedshiftScaleFactor([-0.5, 0, 0.5], n_models=3)
assert_array_equal(m(0), 0)
assert_array_equal(m([1, 2], model_set_axis=False),
[[0.5, 1], [1, 2], [1.5, 3]])
assert_allclose(m.inverse(m([1, 2], model_set_axis=False)),
[[1, 2], [1, 2], [1, 2]])
def test_RedshiftScaleFactor_inverse():
m = models.RedshiftScaleFactor(1.2345)
assert_allclose(m.inverse(m(6.789)), 6.789)
def test_RedshiftScaleFactor_inverse_bounding_box():
model = models.RedshiftScaleFactor(2)
model.bounding_box = (1, 5)
assert model.bounding_box == (1, 5)
inverse_model = model.inverse
assert inverse_model.bounding_box == (3, 15)
assert_allclose(inverse_model(model(4, with_bounding_box=True), with_bounding_box=True), 4)
@pytest.mark.skipif('not HAS_SCIPY')
def test_RedshiftScaleFactor_model_levmar_fit():
"""Test fitting RedshiftScaleFactor model with LevMarLSQFitter."""
init_model = models.RedshiftScaleFactor()
x = np.arange(10)
y = 2.7174 * x
fitter = fitting.LevMarLSQFitter()
fitted_model = fitter(init_model, x, y)
assert_allclose(fitted_model.parameters, [1.7174])
def test_Ellipse2D():
"""Test Ellipse2D model."""
amplitude = 7.5
x0, y0 = 15, 15
theta = Angle(45, 'deg')
em = models.Ellipse2D(amplitude, x0, y0, 7, 3, theta.radian)
y, x = np.mgrid[0:30, 0:30]
e = em(x, y)
assert np.all(e[e > 0] == amplitude)
assert e[y0, x0] == amplitude
rotation = models.Rotation2D(angle=theta.degree)
point1 = [2, 0] # Rotation2D center is (0, 0)
point2 = rotation(*point1)
point1 = np.array(point1) + [x0, y0]
point2 = np.array(point2) + [x0, y0]
e1 = models.Ellipse2D(amplitude, x0, y0, 7, 3, theta=0.)
e2 = models.Ellipse2D(amplitude, x0, y0, 7, 3, theta=theta.radian)
assert e1(*point1) == e2(*point2)
def test_Ellipse2D_circular():
"""Test that circular Ellipse2D agrees with Disk2D [3736]."""
amplitude = 7.5
radius = 10
size = (radius * 2) + 1
y, x = np.mgrid[0:size, 0:size]
ellipse = models.Ellipse2D(amplitude, radius, radius, radius, radius,
theta=0)(x, y)
disk = models.Disk2D(amplitude, radius, radius, radius)(x, y)
assert np.all(ellipse == disk)
def test_Scale_inverse():
m = models.Scale(1.2345)
assert_allclose(m.inverse(m(6.789)), 6.789)
def test_Scale_inverse_bounding_box():
model = models.Scale(2)
model.bounding_box = (1, 5)
assert model.bounding_box == (1, 5)
inverse_model = model.inverse
assert inverse_model.bounding_box == (2, 10)
assert inverse_model(model(4, with_bounding_box=True), with_bounding_box=True) == 4.0
def test_Multiply_inverse():
m = models.Multiply(1.2345)
assert_allclose(m.inverse(m(6.789)), 6.789)
def test_Multiply_inverse_bounding_box():
model = models.Multiply(2)
model.bounding_box = (1, 5)
assert model.bounding_box == (1, 5)
inverse_model = model.inverse
assert inverse_model.bounding_box == (2, 10)
assert inverse_model(model(4, with_bounding_box=True), with_bounding_box=True) == 4.0
def test_Shift_inverse():
m = models.Shift(1.2345)
assert_allclose(m.inverse(m(6.789)), 6.789)
def test_Shift_inverse_bounding_box():
model = models.Shift(10)
model.bounding_box = (1, 5)
assert model.bounding_box == (1, 5)
inverse_model = model.inverse
assert inverse_model.bounding_box == (11, 15)
assert inverse_model(model(4, with_bounding_box=True), with_bounding_box=True) == 4.0
@pytest.mark.skipif('not HAS_SCIPY')
def test_Shift_model_levmar_fit():
"""Test fitting Shift model with LevMarLSQFitter (issue #6103)."""
init_model = models.Shift()
x = np.arange(10)
y = x + 0.1
fitter = fitting.LevMarLSQFitter()
with pytest.warns(AstropyUserWarning,
match='Model is linear in parameters'):
fitted_model = fitter(init_model, x, y)
assert_allclose(fitted_model.parameters, [0.1], atol=1e-15)
def test_Shift_model_set_linear_fit():
"""Test linear fitting of Shift model (issue #6103)."""
init_model = models.Shift(offset=[0, 0], n_models=2)
x = np.arange(10)
yy = np.array([x+0.1, x-0.2])
fitter = fitting.LinearLSQFitter()
fitted_model = fitter(init_model, x, yy)
assert_allclose(fitted_model.parameters, [0.1, -0.2], atol=1e-15)
@pytest.mark.parametrize('Model', (models.Scale, models.Multiply))
def test_Scale_model_set_linear_fit(Model):
"""Test linear fitting of Scale model (#6103)."""
init_model = Model(factor=[0, 0], n_models=2)
x = np.arange(-3, 7)
yy = np.array([1.15*x, 0.96*x])
fitter = fitting.LinearLSQFitter()
fitted_model = fitter(init_model, x, yy)
assert_allclose(fitted_model.parameters, [1.15, 0.96], atol=1e-15)
@pytest.mark.parametrize('Model', (models.Scale, models.Multiply))
def test_Scale_model_evaluate_without_units(Model):
m = Model(factor=4*u.m)
kwargs = {'x': 3*u.m, 'y': 7*u.m}
mnu = m.without_units_for_data(**kwargs)
x = np.linspace(-1, 1, 100)
assert_allclose(mnu(x), 4*x)
# https://github.com/astropy/astropy/issues/6178
def test_Ring2D_rout():
# Test with none of r_in, r_out, width specified
m = models.Ring2D(amplitude=1, x_0=1, y_0=1)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 1
assert m.width.value == 1
# Test with r_in specified only
m = models.Ring2D(amplitude=1, x_0=1, y_0=1, r_in=4)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 4
assert m.width.value == 1
# Test with r_out specified only
m = models.Ring2D(amplitude=1, x_0=1, y_0=1, r_out=7)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 1
assert m.width.value == 6
# Error when r_out is too small for default r_in
with pytest.raises(InputParameterError) as err:
models.Ring2D(amplitude=1, x_0=1, y_0=1, r_out=0.5)
assert str(err.value) == "r_in=1 and width=-0.5 must both be >=0"
# Test with width specified only
m = models.Ring2D(amplitude=1, x_0=1, y_0=1, width=11)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 1
assert m.width.value == 11
# Test with r_in and r_out specified only
m = models.Ring2D(amplitude=1, x_0=1, y_0=1, r_in=2, r_out=5)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 2
assert m.width.value == 3
# Error when r_out is smaller than r_in
with pytest.raises(InputParameterError) as err:
models.Ring2D(amplitude=1, x_0=1, y_0=1, r_out=1, r_in=4)
assert str(err.value) == "r_in=4 and width=-3 must both be >=0"
# Test with r_in and width specified only
m = models.Ring2D(amplitude=1, x_0=1, y_0=1, r_in=2, width=4)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 2
assert m.width.value == 4
# Test with r_out and width specified only
m = models.Ring2D(amplitude=1, x_0=1, y_0=1, r_out=12, width=7)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 5
assert m.width.value == 7
# Error when width is larger than r_out
with pytest.raises(InputParameterError) as err:
models.Ring2D(amplitude=1, x_0=1, y_0=1, r_out=1, width=4)
assert str(err.value) == "r_in=-3 and width=4 must both be >=0"
# Test with r_in, r_out, and width all specified
m = models.Ring2D(amplitude=1, x_0=1, y_0=1, r_in=3, r_out=11, width=8)
assert m.amplitude.value == 1
assert m.x_0.value == 1
assert m.y_0.value == 1
assert m.r_in.value == 3
assert m.width.value == 8
# error when specifying all
with pytest.raises(InputParameterError) as err:
models.Ring2D(amplitude=1, x_0=1, y_0=1, r_in=3, r_out=11, width=7)
assert str(err.value) == "Width must be r_out - r_in"
@pytest.mark.skipif("not HAS_SCIPY")
def test_Voigt1D():
voi = models.Voigt1D(amplitude_L=-0.5, x_0=1.0, fwhm_L=5.0, fwhm_G=5.0)
xarr = np.linspace(-5.0, 5.0, num=40)
yarr = voi(xarr)
voi_init = models.Voigt1D(amplitude_L=-1.0, x_0=1.0, fwhm_L=5.0, fwhm_G=5.0)
fitter = fitting.LevMarLSQFitter()
voi_fit = fitter(voi_init, xarr, yarr)
assert_allclose(voi_fit.param_sets, voi.param_sets)
# Invalid method
with pytest.raises(ValueError) as err:
models.Voigt1D(method='test')
assert str(err.value) ==\
"Not a valid method for Voigt1D Faddeeva function: test."
@pytest.mark.skipif("not HAS_SCIPY")
@pytest.mark.parametrize('algorithm', ('humlicek2', 'wofz'))
def test_Voigt1D_norm(algorithm):
"""Test integral of normalized Voigt profile."""
from scipy.integrate import quad
voi = models.Voigt1D(amplitude_L=1.0/np.pi, x_0=0.0, fwhm_L=2.0, fwhm_G=1.5, method=algorithm)
if algorithm == 'wofz':
atol = 1e-14
else:
atol = 1e-8
assert_allclose(quad(voi, -np.inf, np.inf)[0], 1.0, atol=atol)
@pytest.mark.skipif("not HAS_SCIPY")
@pytest.mark.parametrize('doppler', (1.e-3, 1.e-2, 0.1, 0.5, 1.0, 2.5, 5.0, 10))
def test_Voigt1D_hum2(doppler):
"""Verify accuracy of Voigt profile in Humlicek approximation to Faddeeva.cc (SciPy)."""
x = np.linspace(-20, 20, 400001)
voi_w = models.Voigt1D(amplitude_L=2.0/np.pi, fwhm_L=1.0, fwhm_G=doppler, method='wofz')
vf_w = voi_w(x)
dvda_w = voi_w.fit_deriv(x, x_0=0, amplitude_L=2.0/np.pi, fwhm_L=1.0, fwhm_G=doppler)
voi_h = models.Voigt1D(amplitude_L=2.0/np.pi, fwhm_L=1.0, fwhm_G=doppler, method='humlicek2')
vf_h = voi_h(x)
dvda_h = voi_h.fit_deriv(x, x_0=0, amplitude_L=2.0/np.pi, fwhm_L=1.0, fwhm_G=doppler)
assert_allclose(vf_h, vf_w, rtol=1e-7 * (2 + 1 / np.sqrt(doppler)))
assert_allclose(dvda_h, dvda_w, rtol=1e-9, atol=1e-7 * (1 + 30 / doppler))
@pytest.mark.skipif("not HAS_SCIPY")
def test_KingProjectedAnalytic1D_fit():
km = models.KingProjectedAnalytic1D(amplitude=1, r_core=1, r_tide=2)
xarr = np.linspace(0.1, 2, 10)
yarr = km(xarr)
km_init = models.KingProjectedAnalytic1D(amplitude=1, r_core=1, r_tide=1)
fitter = fitting.LevMarLSQFitter()
km_fit = fitter(km_init, xarr, yarr)
assert_allclose(km_fit.param_sets, km.param_sets)
assert_allclose(km_fit.concentration, 0.30102999566398136)
@pytest.mark.parametrize('model', [models.Exponential1D(), models.Logarithmic1D()])
def test_ExponentialAndLogarithmic1D_fit(model):
xarr = np.linspace(0.1, 10., 200)
assert_allclose(xarr, model.inverse(model(xarr)))
@pytest.mark.parametrize('model', [models.Exponential1D(), models.Logarithmic1D()])
def test_ExponentialAndLogarithmic_set_tau(model):
message = "0 is not an allowed value for tau"
with pytest.raises(ValueError) as err:
model.tau = 0
assert str(err.value) == message
def test_Linear1D_inverse():
model = models.Linear1D(slope=4, intercept=-12)
inverse = model.inverse
assert inverse.slope == 1/4
assert inverse.intercept == 3
@pytest.mark.parametrize('trig', [(models.Sine1D, [-0.25, 0.25]),
(models.ArcSine1D, [-0.25, 0.25]),
(models.Cosine1D, [0, 0.5]),
(models.ArcCosine1D, [0, 0.5]),
(models.Tangent1D, [-0.25, 0.25]),
(models.ArcTangent1D, [-0.25, 0.25])])
def test_trig_inverse(trig):
mdl = trig[0]()
lower, upper = trig[1]
x = np.arange(lower, upper, 0.01)
assert_allclose(mdl.inverse(mdl(x)), x, atol=1e-10)
assert_allclose(mdl(mdl.inverse(x)), x, atol=1e-10)
|
939da877ce0b261d7d939ac2c6d12d7e2ed9778759c70b5cefbba68498e488d5 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# pylint: disable=invalid-name
import pytest
import numpy as np
from inspect import Parameter
from astropy.modeling.utils import (poly_map_domain, _validate_domain_window,
get_inputs_and_params, _SpecialOperatorsDict)
def test_poly_map_domain():
oldx = np.array([1, 2, 3, 4])
# test shift/scale
assert (poly_map_domain(oldx, (-4, 4), (-3, 3)) == [0.75, 1.5, 2.25, 3]).all()
# errors
MESSAGE = 'Expected "domain" and "window" to be a tuple of size 2.'
with pytest.raises(ValueError) as err:
poly_map_domain(oldx, (-4,), (-3, 3))
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
poly_map_domain(oldx, (-4, 4, -4), (-3, 3))
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
poly_map_domain(oldx, (-4, 4), (-3,))
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
poly_map_domain(oldx, (-4, 4), (-3, 3, -3))
assert str(err.value) == MESSAGE
def test__validate_domain_window():
# Test if None
assert _validate_domain_window(None) is None
# Test normal
assert _validate_domain_window((-2, 2)) == (-2, 2)
assert _validate_domain_window([-2, 2]) == (-2, 2)
assert _validate_domain_window(np.array([-2, 2])) == (-2, 2)
# Test error
MESSAGE = 'domain and window should be tuples of size 2.'
with pytest.raises(ValueError) as err:
_validate_domain_window((-2, 2, -2))
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
_validate_domain_window((-2,))
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
_validate_domain_window([-2])
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
_validate_domain_window(np.array([-2]))
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
_validate_domain_window(-2)
assert str(err.value) == MESSAGE
def test_get_inputs_and_params():
# test normal
def func1(input0, input1, param0=5, param1=7):
pass
inputs, params = get_inputs_and_params(func1)
for index, _input in enumerate(inputs):
assert isinstance(_input, Parameter)
assert _input.name == f"input{index}"
assert _input.kind == _input.POSITIONAL_OR_KEYWORD
assert _input.default == Parameter.empty
default = [5, 7]
for index, param in enumerate(params):
assert isinstance(param, Parameter)
assert param.name == f"param{index}"
assert param.kind == param.POSITIONAL_OR_KEYWORD
assert param.default == default[index]
# Error
MESSAGE = "Signature must not have *args or **kwargs"
def func2(input0, input1, *args, param0=5, param1=7):
pass
def func3(input0, input1, param0=5, param1=7, **kwargs):
pass
with pytest.raises(ValueError) as err:
get_inputs_and_params(func2)
assert str(err.value) == MESSAGE
with pytest.raises(ValueError) as err:
get_inputs_and_params(func3)
assert str(err.value) == MESSAGE
class Test_SpecialOperatorsDict:
def setup(self):
self.key = 'test'
self.val = 'value'
def test__set_value(self):
special_operators = _SpecialOperatorsDict()
assert self.key not in special_operators
special_operators._set_value(self.key, self.val)
assert self.key in special_operators
assert special_operators[self.key] == self.val
with pytest.raises(ValueError, match='Special operator "test" already exists'):
special_operators._set_value(self.key, self.val)
def test___setitem__(self):
special_operators = _SpecialOperatorsDict()
assert self.key not in special_operators
with pytest.deprecated_call():
special_operators[self.key] = self.val
assert self.key in special_operators
assert special_operators[self.key] == self.val
def test__SpecialOperatorsDict__get_unique_id(self):
special_operators = _SpecialOperatorsDict()
assert special_operators._unique_id == 0
assert special_operators._get_unique_id() == 1
assert special_operators._unique_id == 1
assert special_operators._get_unique_id() == 2
assert special_operators._unique_id == 2
assert special_operators._get_unique_id() == 3
assert special_operators._unique_id == 3
def test__SpecialOperatorsDict_add(self):
special_operators = _SpecialOperatorsDict()
operator_name = 'test'
operator = 'operator'
key0 = special_operators.add(operator_name, operator)
assert key0 == (operator_name, special_operators._unique_id)
assert key0 in special_operators
assert special_operators[key0] == operator
key1 = special_operators.add(operator_name, operator)
assert key1 == (operator_name, special_operators._unique_id)
assert key1 in special_operators
assert special_operators[key1] == operator
assert key0 != key1
|
1a35a079596d588a1b284adcf2930b6db8f735cfc53603e5ba46636c47b9a2ba | # Licensed under a 3-clause BSD style license - see LICENSE.rst:
"""
Tests for model evaluation.
Compare the results of some models with other programs.
"""
# pylint: disable=invalid-name, no-member
import pytest
import numpy as np
import unittest.mock as mk
import astropy.modeling.tabular as tabular_models
from numpy.testing import assert_allclose, assert_equal
from astropy import units as u
from astropy.modeling import fitting, models
from astropy.modeling.models import Gaussian2D
from astropy.modeling.bounding_box import ModelBoundingBox
from astropy.modeling.core import FittableModel, _ModelMeta, Model
from astropy.modeling.parameters import Parameter
from astropy.modeling.polynomial import PolynomialBase
from astropy.modeling.powerlaws import SmoothlyBrokenPowerLaw1D
from astropy.modeling.parameters import InputParameterError
from astropy.modeling.separable import separability_matrix
from astropy.tests.helper import assert_quantity_allclose
from astropy.utils import NumpyRNGContext
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
from .example_models import models_1D, models_2D
@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*
"""
da = np.sin(2 * np.pi * frequency * x)
df = 2 * np.pi * x * amplitude * np.cos(2 * np.pi * frequency * x)
return np.vstack((da, df))
SineModel = models.custom_model(sine_model, fit_deriv=sine_deriv)
x = np.linspace(0, 4, 50)
sin_model = SineModel()
sin_model.evaluate(x, 5., 2.)
sin_model.fit_deriv(x, 5., 2.)
np.random.seed(0)
data = sin_model(x) + np.random.rand(len(x)) - 0.5
fitter = fitting.LevMarLSQFitter()
model = fitter(sin_model, x, data)
assert np.all((np.array([model.amplitude.value, model.frequency.value]) -
np.array([amplitude, frequency])) < 0.001)
def test_custom_model_init():
@models.custom_model
def SineModel(x, amplitude=4, frequency=1):
"""Model function"""
return amplitude * np.sin(2 * np.pi * frequency * x)
sin_model = SineModel(amplitude=2., frequency=0.5)
assert sin_model.amplitude == 2.
assert sin_model.frequency == 0.5
def test_custom_model_defaults():
@models.custom_model
def SineModel(x, amplitude=4, frequency=1):
"""Model function"""
return amplitude * np.sin(2 * np.pi * frequency * x)
sin_model = SineModel()
assert SineModel.amplitude.default == 4
assert SineModel.frequency.default == 1
assert sin_model.amplitude == 4
assert sin_model.frequency == 1
def test_inconsistent_input_shapes():
g = Gaussian2D()
x = np.arange(-1., 1, .2)
y = x.copy()
# check scalar input broadcasting works
assert np.abs(g(x, 0) - g(x, 0 * x)).sum() == 0
# but not array broadcasting
x.shape = (10, 1)
y.shape = (1, 10)
result = g(x, y)
assert result.shape == (10, 10)
def test_custom_model_bounding_box():
"""Test bounding box evaluation for a 3D model"""
def ellipsoid(x, y, z, x0=13, y0=10, z0=8, a=4, b=3, c=2, amp=1):
rsq = ((x - x0) / a) ** 2 + ((y - y0) / b) ** 2 + ((z - z0) / c) ** 2
val = (rsq < 1) * amp
return val
class Ellipsoid3D(models.custom_model(ellipsoid)):
@property
def bounding_box(self):
return ((self.z0 - self.c, self.z0 + self.c),
(self.y0 - self.b, self.y0 + self.b),
(self.x0 - self.a, self.x0 + self.a))
model = Ellipsoid3D()
bbox = model.bounding_box
zlim, ylim, xlim = bbox.bounding_box()
dz, dy, dx = np.diff(bbox) / 2
z1, y1, x1 = np.mgrid[slice(zlim[0], zlim[1] + 1),
slice(ylim[0], ylim[1] + 1),
slice(xlim[0], xlim[1] + 1)]
z2, y2, x2 = np.mgrid[slice(zlim[0] - dz, zlim[1] + dz + 1),
slice(ylim[0] - dy, ylim[1] + dy + 1),
slice(xlim[0] - dx, xlim[1] + dx + 1)]
arr = model(x2, y2, z2, with_bounding_box=True)
sub_arr = model(x1, y1, z1, with_bounding_box=True)
# check for flux agreement
assert abs(np.nansum(arr) - np.nansum(sub_arr)) < np.nansum(arr) * 1e-7
class Fittable2DModelTester:
"""
Test class for all two dimensional parametric models.
Test values have to be defined in example_models.py. It currently test the
model with different input types, evaluates the model at different
positions and assures that it gives the correct values. And tests if the
model works with non-linear fitters.
This can be used as a base class for user defined model testing.
"""
def setup_class(self):
self.N = 100
self.M = 100
self.eval_error = 0.0001
self.fit_error = 0.1
self.x = 5.3
self.y = 6.7
self.x1 = np.arange(1, 10, .1)
self.y1 = np.arange(1, 10, .1)
self.y2, self.x2 = np.mgrid[:10, :8]
def test_input2D(self, model_class, test_parameters):
"""Test model with different input types."""
model = create_model(model_class, test_parameters)
model(self.x, self.y)
model(self.x1, self.y1)
model(self.x2, self.y2)
def test_eval2D(self, model_class, test_parameters):
"""Test model values add certain given points"""
model = create_model(model_class, test_parameters)
x = test_parameters['x_values']
y = test_parameters['y_values']
z = test_parameters['z_values']
assert np.all(np.abs(model(x, y) - z) < self.eval_error)
def test_bounding_box2D(self, model_class, test_parameters):
"""Test bounding box evaluation"""
model = create_model(model_class, test_parameters)
# testing setter
model.bounding_box = ((-5, 5), (-5, 5))
assert model.bounding_box == ((-5, 5), (-5, 5))
model.bounding_box = None
with pytest.raises(NotImplementedError):
model.bounding_box
# test the exception of dimensions don't match
with pytest.raises(ValueError):
model.bounding_box = (-5, 5)
del model.bounding_box
try:
bbox = model.bounding_box
except NotImplementedError:
return
ddx = 0.01
ylim, xlim = bbox
x1 = np.arange(xlim[0], xlim[1], ddx)
y1 = np.arange(ylim[0], ylim[1], ddx)
x2 = np.concatenate(([xlim[0] - idx * ddx for idx in range(10, 0, -1)],
x1,
[xlim[1] + idx * ddx for idx in range(1, 10)]))
y2 = np.concatenate(([ylim[0] - idx * ddx for idx in range(10, 0, -1)],
y1,
[ylim[1] + idx * ddx for idx in range(1, 10)]))
inside_bbox = model(x1, y1)
outside_bbox = model(x2, y2, with_bounding_box=True)
outside_bbox = outside_bbox[~np.isnan(outside_bbox)]
assert np.all(inside_bbox == outside_bbox)
def test_bounding_box2D_peak(self, model_class, test_parameters):
if not test_parameters.pop('bbox_peak', False):
return
model = create_model(model_class, test_parameters)
bbox = model.bounding_box
ylim, xlim = bbox
dy, dx = np.diff(bbox)/2
y1, x1 = np.mgrid[slice(ylim[0], ylim[1] + 1),
slice(xlim[0], xlim[1] + 1)]
y2, x2 = np.mgrid[slice(ylim[0] - dy, ylim[1] + dy + 1),
slice(xlim[0] - dx, xlim[1] + dx + 1)]
arr = model(x2, y2)
sub_arr = model(x1, y1)
# check for flux agreement
assert abs(arr.sum() - sub_arr.sum()) < arr.sum() * 1e-7
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitter2D(self, model_class, test_parameters):
"""Test if the parametric model works with the fitter."""
x_lim = test_parameters['x_lim']
y_lim = test_parameters['y_lim']
parameters = test_parameters['parameters']
model = create_model(model_class, test_parameters)
if isinstance(parameters, dict):
parameters = [parameters[name] for name in model.param_names]
if "log_fit" in test_parameters:
if test_parameters['log_fit']:
x = np.logspace(x_lim[0], x_lim[1], self.N)
y = np.logspace(y_lim[0], y_lim[1], self.N)
else:
x = np.linspace(x_lim[0], x_lim[1], self.N)
y = np.linspace(y_lim[0], y_lim[1], self.N)
xv, yv = np.meshgrid(x, y)
np.random.seed(0)
# add 10% noise to the amplitude
noise = np.random.rand(self.N, self.N) - 0.5
data = model(xv, yv) + 0.1 * parameters[0] * noise
fitter = fitting.LevMarLSQFitter()
new_model = fitter(model, xv, yv, data)
params = [getattr(new_model, name) for name in new_model.param_names]
fixed = [param.fixed for param in params]
expected = np.array([val for val, fixed in zip(parameters, fixed)
if not fixed])
fitted = np.array([param.value for param in params
if not param.fixed])
assert_allclose(fitted, expected,
atol=self.fit_error)
@pytest.mark.skipif('not HAS_SCIPY')
def test_deriv_2D(self, model_class, test_parameters):
"""
Test the derivative of a model by fitting with an estimated and
analytical derivative.
"""
x_lim = test_parameters['x_lim']
y_lim = test_parameters['y_lim']
if model_class.fit_deriv is None or issubclass(model_class, PolynomialBase):
return
if "log_fit" in test_parameters:
if test_parameters['log_fit']:
x = np.logspace(x_lim[0], x_lim[1], self.N)
y = np.logspace(y_lim[0], y_lim[1], self.M)
x_test = np.logspace(x_lim[0], x_lim[1], self.N*10)
y_test = np.logspace(y_lim[0], y_lim[1], self.M*10)
else:
x = np.linspace(x_lim[0], x_lim[1], self.N)
y = np.linspace(y_lim[0], y_lim[1], self.M)
x_test = np.linspace(x_lim[0], x_lim[1], self.N*10)
y_test = np.linspace(y_lim[0], y_lim[1], self.M*10)
xv, yv = np.meshgrid(x, y)
xv_test, yv_test = np.meshgrid(x_test, y_test)
try:
model_with_deriv = create_model(model_class, test_parameters,
use_constraints=False,
parameter_key='deriv_initial')
model_no_deriv = create_model(model_class, test_parameters,
use_constraints=False,
parameter_key='deriv_initial')
model = create_model(model_class, test_parameters,
use_constraints=False,
parameter_key='deriv_initial')
except KeyError:
model_with_deriv = create_model(model_class, test_parameters,
use_constraints=False)
model_no_deriv = create_model(model_class, test_parameters,
use_constraints=False)
model = create_model(model_class, test_parameters,
use_constraints=False)
# add 10% noise to the amplitude
rsn = np.random.default_rng(0)
amplitude = test_parameters['parameters'][0]
n = 0.1 * amplitude * (rsn.random((self.M, self.N)) - 0.5)
data = model(xv, yv) + n
fitter_with_deriv = fitting.LevMarLSQFitter()
new_model_with_deriv = fitter_with_deriv(model_with_deriv, xv, yv,
data)
fitter_no_deriv = fitting.LevMarLSQFitter()
new_model_no_deriv = fitter_no_deriv(model_no_deriv, xv, yv, data,
estimate_jacobian=True)
assert_allclose(new_model_with_deriv(xv_test, yv_test),
new_model_no_deriv(xv_test, yv_test),
rtol=1e-2)
if model_class != Gaussian2D:
assert_allclose(new_model_with_deriv.parameters,
new_model_no_deriv.parameters,
rtol=0.1)
class Fittable1DModelTester:
"""
Test class for all one dimensional parametric models.
Test values have to be defined in example_models.py. It currently test the
model with different input types, evaluates the model at different
positions and assures that it gives the correct values. And tests if the
model works with non-linear fitters.
This can be used as a base class for user defined model testing.
"""
def setup_class(self):
self.N = 100
self.M = 100
self.eval_error = 0.0001
self.fit_error = 0.11
self.x = 5.3
self.y = 6.7
self.x1 = np.arange(1, 10, .1)
self.y1 = np.arange(1, 10, .1)
self.y2, self.x2 = np.mgrid[:10, :8]
@pytest.mark.filterwarnings(r'ignore:.*:RuntimeWarning')
def test_input1D(self, model_class, test_parameters):
"""Test model with different input types."""
model = create_model(model_class, test_parameters)
model(self.x)
model(self.x1)
model(self.x2)
def test_eval1D(self, model_class, test_parameters):
"""
Test model values at certain given points
"""
model = create_model(model_class, test_parameters)
x = test_parameters['x_values']
y = test_parameters['y_values']
assert_allclose(model(x), y, atol=self.eval_error)
def test_bounding_box1D(self, model_class, test_parameters):
"""Test bounding box evaluation"""
model = create_model(model_class, test_parameters)
# testing setter
model.bounding_box = (-5, 5)
model.bounding_box = None
with pytest.raises(NotImplementedError):
model.bounding_box
del model.bounding_box
# test exception if dimensions don't match
with pytest.raises(ValueError):
model.bounding_box = 5
try:
bbox = model.bounding_box.bounding_box()
except NotImplementedError:
return
ddx = 0.01
x1 = np.arange(bbox[0], bbox[1], ddx)
x2 = np.concatenate(([bbox[0] - idx * ddx for idx in range(10, 0, -1)],
x1,
[bbox[1] + idx * ddx for idx in range(1, 10)]))
inside_bbox = model(x1)
outside_bbox = model(x2, with_bounding_box=True)
outside_bbox = outside_bbox[~np.isnan(outside_bbox)]
assert np.all(inside_bbox == outside_bbox)
def test_bounding_box1D_peak(self, model_class, test_parameters):
if not test_parameters.pop('bbox_peak', False):
return
model = create_model(model_class, test_parameters)
bbox = model.bounding_box
if isinstance(model, models.Lorentz1D) or isinstance(model, models.Drude1D):
rtol = 0.01 # 1% agreement is enough due to very extended wings
ddx = 0.1 # Finer sampling to "integrate" flux for narrow peak
else:
rtol = 1e-7
ddx = 1
if isinstance(bbox, ModelBoundingBox):
bbox = bbox.bounding_box()
dx = np.diff(bbox) / 2
x1 = np.mgrid[slice(bbox[0], bbox[1] + 1, ddx)]
x2 = np.mgrid[slice(bbox[0] - dx, bbox[1] + dx + 1, ddx)]
arr = model(x2)
sub_arr = model(x1)
# check for flux agreement
assert abs(arr.sum() - sub_arr.sum()) < arr.sum() * rtol
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitter1D(self, model_class, test_parameters):
"""
Test if the parametric model works with the fitter.
"""
x_lim = test_parameters['x_lim']
parameters = test_parameters['parameters']
model = create_model(model_class, test_parameters)
if isinstance(parameters, dict):
parameters = [parameters[name] for name in model.param_names]
if "log_fit" in test_parameters:
if test_parameters['log_fit']:
x = np.logspace(x_lim[0], x_lim[1], self.N)
else:
x = np.linspace(x_lim[0], x_lim[1], self.N)
np.random.seed(0)
# add 10% noise to the amplitude
relative_noise_amplitude = 0.01
data = ((1 + relative_noise_amplitude * np.random.randn(len(x))) *
model(x))
fitter = fitting.LevMarLSQFitter()
new_model = fitter(model, x, data)
# Only check parameters that were free in the fit
params = [getattr(new_model, name) for name in new_model.param_names]
fixed = [param.fixed for param in params]
expected = np.array([val for val, fixed in zip(parameters, fixed)
if not fixed])
fitted = np.array([param.value for param in params
if not param.fixed])
assert_allclose(fitted, expected, atol=self.fit_error)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.filterwarnings(r'ignore:.*:RuntimeWarning')
def test_deriv_1D(self, model_class, test_parameters):
"""
Test the derivative of a model by comparing results with an estimated
derivative.
"""
x_lim = test_parameters['x_lim']
if model_class.fit_deriv is None or issubclass(model_class, PolynomialBase):
return
if "log_fit" in test_parameters:
if test_parameters['log_fit']:
x = np.logspace(x_lim[0], x_lim[1], self.N)
else:
x = np.linspace(x_lim[0], x_lim[1], self.N)
parameters = test_parameters['parameters']
model_with_deriv = create_model(model_class, test_parameters,
use_constraints=False)
model_no_deriv = create_model(model_class, test_parameters,
use_constraints=False)
# NOTE: PR 10644 replaced deprecated usage of RandomState but could not
# find a new seed that did not cause test failure, resorted to hardcoding.
# add 10% noise to the amplitude
rsn_rand_1234567890 = np.array([
0.61879477, 0.59162363, 0.88868359, 0.89165480, 0.45756748,
0.77818808, 0.26706377, 0.99610621, 0.54009489, 0.53752161,
0.40099938, 0.70540579, 0.40518559, 0.94999075, 0.03075388,
0.13602495, 0.08297726, 0.42352224, 0.23449723, 0.74743526,
0.65177865, 0.68998682, 0.16413419, 0.87642114, 0.44733314,
0.57871104, 0.52377835, 0.62689056, 0.34869427, 0.26209748,
0.07498055, 0.17940570, 0.82999425, 0.98759822, 0.11326099,
0.63846415, 0.73056694, 0.88321124, 0.52721004, 0.66487673,
0.74209309, 0.94083846, 0.70123128, 0.29534353, 0.76134369,
0.77593881, 0.36985514, 0.89519067, 0.33082813, 0.86108824,
0.76897859, 0.61343376, 0.43870907, 0.91913538, 0.76958966,
0.51063556, 0.04443249, 0.57463611, 0.31382006, 0.41221713,
0.21531811, 0.03237521, 0.04166386, 0.73109303, 0.74556052,
0.64716325, 0.77575353, 0.64599254, 0.16885816, 0.48485480,
0.53844248, 0.99690349, 0.23657074, 0.04119088, 0.46501519,
0.35739006, 0.23002665, 0.53420791, 0.71639475, 0.81857486,
0.73994342, 0.07948837, 0.75688276, 0.13240193, 0.48465576,
0.20624753, 0.02298276, 0.54257873, 0.68123230, 0.35887468,
0.36296147, 0.67368397, 0.29505730, 0.66558885, 0.93652252,
0.36755130, 0.91787687, 0.75922703, 0.48668067, 0.45967890])
n = 0.1 * parameters[0] * (rsn_rand_1234567890 - 0.5)
data = model_with_deriv(x) + n
fitter_with_deriv = fitting.LevMarLSQFitter()
new_model_with_deriv = fitter_with_deriv(model_with_deriv, x, data)
fitter_no_deriv = fitting.LevMarLSQFitter()
new_model_no_deriv = fitter_no_deriv(model_no_deriv, x, data,
estimate_jacobian=True)
assert_allclose(new_model_with_deriv.parameters,
new_model_no_deriv.parameters, atol=0.15)
def create_model(model_class, test_parameters, use_constraints=True,
parameter_key='parameters'):
"""Create instance of model class."""
constraints = {}
if issubclass(model_class, PolynomialBase):
return model_class(**test_parameters[parameter_key])
elif issubclass(model_class, FittableModel):
if "requires_scipy" in test_parameters and not HAS_SCIPY:
pytest.skip("SciPy not found")
if use_constraints:
if 'constraints' in test_parameters:
constraints = test_parameters['constraints']
return model_class(*test_parameters[parameter_key], **constraints)
@pytest.mark.filterwarnings(r'ignore:Model is linear in parameters.*')
@pytest.mark.filterwarnings(r'ignore:The fit may be unsuccessful.*')
@pytest.mark.parametrize(('model_class', 'test_parameters'),
sorted(models_1D.items(), key=lambda x: str(x[0])))
class TestFittable1DModels(Fittable1DModelTester):
pass
@pytest.mark.filterwarnings(r'ignore:Model is linear in parameters.*')
@pytest.mark.parametrize(('model_class', 'test_parameters'),
sorted(models_2D.items(), key=lambda x: str(x[0])))
class TestFittable2DModels(Fittable2DModelTester):
pass
def test_ShiftModel():
# Shift by a scalar
m = models.Shift(42)
assert m(0) == 42
assert_equal(m([1, 2]), [43, 44])
# Shift by a list
m = models.Shift([42, 43], n_models=2)
assert_equal(m(0), [42, 43])
assert_equal(m([1, 2], model_set_axis=False),
[[43, 44], [44, 45]])
def test_ScaleModel():
# Scale by a scalar
m = models.Scale(42)
assert m(0) == 0
assert_equal(m([1, 2]), [42, 84])
# Scale by a list
m = models.Scale([42, 43], n_models=2)
assert_equal(m(0), [0, 0])
assert_equal(m([1, 2], model_set_axis=False),
[[42, 84], [43, 86]])
def test_voigt_model():
"""
Currently just tests that the model peaks at its origin.
Regression test for https://github.com/astropy/astropy/issues/3942
"""
m = models.Voigt1D(x_0=5, amplitude_L=10, fwhm_L=0.5, fwhm_G=0.9)
x = np.arange(0, 10, 0.01)
y = m(x)
assert y[500] == y.max() # y[500] is right at the center
def test_model_instance_repr():
m = models.Gaussian1D(1.5, 2.5, 3.5)
assert repr(m) == '<Gaussian1D(amplitude=1.5, mean=2.5, stddev=3.5)>'
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_interp_1d():
"""
Test Tabular1D model.
"""
points = np.arange(0, 5)
values = [1., 10, 2, 45, -3]
LookupTable = models.tabular_model(1)
model = LookupTable(points=points, lookup_table=values)
xnew = [0., .7, 1.4, 2.1, 3.9]
ans1 = [1., 7.3, 6.8, 6.3, 1.8]
assert_allclose(model(xnew), ans1)
# Test evaluate without passing `points`.
model = LookupTable(lookup_table=values)
assert_allclose(model(xnew), ans1)
# Test bounds error.
xextrap = [0., .7, 1.4, 2.1, 3.9, 4.1]
with pytest.raises(ValueError):
model(xextrap)
# test extrapolation and fill value
model = LookupTable(lookup_table=values, bounds_error=False,
fill_value=None)
assert_allclose(model(xextrap),
[1., 7.3, 6.8, 6.3, 1.8, -7.8])
# Test unit support
xnew = xnew * u.nm
ans1 = ans1 * u.nJy
model = LookupTable(points=points*u.nm, lookup_table=values*u.nJy)
assert_quantity_allclose(model(xnew), ans1)
assert_quantity_allclose(model(xnew.to(u.nm)), ans1)
assert model.bounding_box == (0 * u.nm, 4 * u.nm)
# Test fill value unit conversion and unitless input on table with unit
model = LookupTable([1, 2, 3], [10, 20, 30] * u.nJy, bounds_error=False,
fill_value=1e-33*(u.W / (u.m * u.m * u.Hz)))
assert_quantity_allclose(model(np.arange(5)),
[100, 10, 20, 30, 100] * u.nJy)
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_interp_2d():
table = np.array([
[-0.04614432, -0.02512547, -0.00619557, 0.0144165, 0.0297525],
[-0.04510594, -0.03183369, -0.01118008, 0.01201388, 0.02496205],
[-0.05464094, -0.02804499, -0.00960086, 0.01134333, 0.02284104],
[-0.04879338, -0.02539565, -0.00440462, 0.01795145, 0.02122417],
[-0.03637372, -0.01630025, -0.00157902, 0.01649774, 0.01952131]])
points = np.arange(0, 5)
points = (points, points)
xnew = np.array([0., .7, 1.4, 2.1, 3.9])
LookupTable = models.tabular_model(2)
model = LookupTable(points, table)
znew = model(xnew, xnew)
result = np.array(
[-0.04614432, -0.03450009, -0.02241028, -0.0069727, 0.01938675])
assert_allclose(znew, result, atol=1e-7)
# test 2D arrays as input
a = np.arange(12).reshape((3, 4))
y, x = np.mgrid[:3, :4]
t = models.Tabular2D(lookup_table=a)
r = t(y, x)
assert_allclose(a, r)
with pytest.raises(ValueError):
model = LookupTable(points=([1.2, 2.3], [1.2, 6.7], [3, 4]))
with pytest.raises(ValueError):
model = LookupTable(lookup_table=[1, 2, 3])
with pytest.raises(NotImplementedError):
model = LookupTable(n_models=2)
with pytest.raises(ValueError):
model = LookupTable(([1, 2], [3, 4]), [5, 6])
with pytest.raises(ValueError):
model = LookupTable(([1, 2] * u.m, [3, 4]), [[5, 6], [7, 8]])
with pytest.raises(ValueError):
model = LookupTable(points, table, bounds_error=False,
fill_value=1*u.Jy)
# Test unit support
points = points[0] * u.nm
points = (points, points)
xnew = xnew * u.nm
model = LookupTable(points, table * u.nJy)
result = result * u.nJy
assert_quantity_allclose(model(xnew, xnew), result, atol=1e-7*u.nJy)
xnew = xnew.to(u.m)
assert_quantity_allclose(model(xnew, xnew), result, atol=1e-7*u.nJy)
bbox = (0 * u.nm, 4 * u.nm)
bbox = (bbox, bbox)
assert model.bounding_box == bbox
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_nd():
a = np.arange(24).reshape((2, 3, 4))
x, y, z = np.mgrid[:2, :3, :4]
tab = models.tabular_model(3)
t = tab(lookup_table=a)
result = t(x, y, z)
assert_allclose(a, result)
with pytest.raises(ValueError):
models.tabular_model(0)
def test_with_bounding_box():
"""
Test the option to evaluate a model respecting
its bunding_box.
"""
p = models.Polynomial2D(2) & models.Polynomial2D(2)
m = models.Mapping((0, 1, 0, 1)) | p
with NumpyRNGContext(1234567):
m.parameters = np.random.rand(12)
m.bounding_box = ((3, 9), (1, 8))
x, y = np.mgrid[:10, :10]
a, b = m(x, y)
aw, bw = m(x, y, with_bounding_box=True)
ind = (~np.isnan(aw)).nonzero()
assert_allclose(a[ind], aw[ind])
assert_allclose(b[ind], bw[ind])
aw, bw = m(x, y, with_bounding_box=True, fill_value=1000)
ind = (aw != 1000).nonzero()
assert_allclose(a[ind], aw[ind])
assert_allclose(b[ind], bw[ind])
# test the order of bbox is not reversed for 1D models
p = models.Polynomial1D(1, c0=12, c1=2.3)
p.bounding_box = (0, 5)
assert(p(1) == p(1, with_bounding_box=True))
t3 = models.Shift(10) & models.Scale(2) & models.Shift(-1)
t3.bounding_box = ((4.3, 6.9), (6, 15), (-1, 10))
assert_allclose(t3([1, 1], [7, 7], [3, 5], with_bounding_box=True),
[[np.nan, 11], [np.nan, 14], [np.nan, 4]])
trans3 = models.Shift(10) & models.Scale(2) & models.Shift(-1)
trans3.bounding_box = ((4.3, 6.9), (6, 15), (-1, 10))
assert_allclose(trans3(1, 7, 5, with_bounding_box=True), [11, 14, 4])
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_with_bounding_box():
points = np.arange(5)
values = np.array([1.5, 3.4, 6.7, 7, 32])
t = models.Tabular1D(points, values)
result = t(1, with_bounding_box=True)
assert result == 3.4
assert t.inverse(result, with_bounding_box=True) == 1.
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_bounding_box_with_units():
points = np.arange(5)*u.pix
lt = np.arange(5)*u.AA
t = models.Tabular1D(points, lt)
result = t(1*u.pix, with_bounding_box=True)
assert result == 1.*u.AA
assert t.inverse(result, with_bounding_box=True) == 1*u.pix
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular1d_inverse():
"""Test that the Tabular1D inverse is defined"""
points = np.arange(5)
values = np.array([1.5, 3.4, 6.7, 7, 32])
t = models.Tabular1D(points, values)
result = t.inverse((3.4, 6.7))
assert_allclose(result, np.array((1., 2.)))
# Check that it works for descending values in lookup_table
t2 = models.Tabular1D(points, values[::-1])
assert_allclose(t2.inverse.points[0], t2.lookup_table[::-1])
result2 = t2.inverse((7, 6.7))
assert_allclose(result2, np.array((1., 2.)))
# Check that it errors on double-valued lookup_table
points = np.arange(5)
values = np.array([1.5, 3.4, 3.4, 32, 25])
t = models.Tabular1D(points, values)
with pytest.raises(NotImplementedError):
t.inverse((3.4, 7.))
# Check that Tabular2D.inverse raises an error
table = np.arange(5*5).reshape(5, 5)
points = np.arange(0, 5)
points = (points, points)
t3 = models.Tabular2D(points=points, lookup_table=table)
with pytest.raises(NotImplementedError):
t3.inverse((3, 3))
# Check that it uses the same kwargs as the original model
points = np.arange(5)
values = np.array([1.5, 3.4, 6.7, 7, 32])
t = models.Tabular1D(points, values)
with pytest.raises(ValueError):
t.inverse(100)
t = models.Tabular1D(points, values, bounds_error=False, fill_value=None)
result = t.inverse(100)
assert_allclose(t(result), 100)
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_grid_shape_mismatch_error():
points = np.arange(5)
lt = np.mgrid[0:5, 0:5][0]
with pytest.raises(ValueError) as err:
models.Tabular2D(points, lt)
assert str(err.value) ==\
"Expected grid points in 2 directions, got 5."
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_repr():
points = np.arange(5)
lt = np.arange(5)
t = models.Tabular1D(points, lt)
assert repr(t) ==\
"<Tabular1D(points=(array([0, 1, 2, 3, 4]),), lookup_table=[0 1 2 3 4])>"
table = np.arange(5*5).reshape(5, 5)
points = np.arange(0, 5)
points = (points, points)
t = models.Tabular2D(points=points, lookup_table=table)
assert repr(t) ==\
"<Tabular2D(points=(array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4])), " +\
"lookup_table=[[ 0 1 2 3 4]\n" +\
" [ 5 6 7 8 9]\n" +\
" [10 11 12 13 14]\n" +\
" [15 16 17 18 19]\n" +\
" [20 21 22 23 24]])>"
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_str():
points = np.arange(5)
lt = np.arange(5)
t = models.Tabular1D(points, lt)
assert str(t) ==\
"Model: Tabular1D\n" +\
"N_inputs: 1\n" +\
"N_outputs: 1\n" +\
"Parameters: \n" +\
" points: (array([0, 1, 2, 3, 4]),)\n" +\
" lookup_table: [0 1 2 3 4]\n" +\
" method: linear\n" +\
" fill_value: nan\n" +\
" bounds_error: True"
table = np.arange(5*5).reshape(5, 5)
points = np.arange(0, 5)
points = (points, points)
t = models.Tabular2D(points=points, lookup_table=table)
assert str(t) ==\
"Model: Tabular2D\n" +\
"N_inputs: 2\n" +\
"N_outputs: 1\n" +\
"Parameters: \n" +\
" points: (array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))\n" +\
" lookup_table: [[ 0 1 2 3 4]\n" +\
" [ 5 6 7 8 9]\n" +\
" [10 11 12 13 14]\n" +\
" [15 16 17 18 19]\n" +\
" [20 21 22 23 24]]\n" +\
" method: linear\n" +\
" fill_value: nan\n" +\
" bounds_error: True"
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_evaluate():
points = np.arange(5)
lt = np.arange(5)[::-1]
t = models.Tabular1D(points, lt)
assert (t.evaluate([1, 2, 3]) == [3, 2, 1]).all()
assert (t.evaluate(np.array([1, 2, 3]) * u.m) == [3, 2, 1]).all()
t.n_outputs = 2
value = [np.array([3, 2, 1]), np.array([1, 2, 3])]
with mk.patch.object(tabular_models, 'interpn', autospec=True, return_value=value) as mkInterpn:
outputs = t.evaluate([1, 2, 3])
for index, output in enumerate(outputs):
assert np.all(value[index] == output)
assert mkInterpn.call_count == 1
@pytest.mark.skipif("not HAS_SCIPY")
def test_tabular_module_name():
"""
The module name must be set manually because
these classes are created dynamically.
"""
for model in [models.Tabular1D, models.Tabular2D]:
assert model.__module__ == "astropy.modeling.tabular"
class classmodel(FittableModel):
f = Parameter(default=1)
x = Parameter(default=0)
y = Parameter(default=2)
def __init__(self, f=f.default, x=x.default, y=y.default):
super().__init__(f, x, y)
def evaluate(self):
pass
class subclassmodel(classmodel):
f = Parameter(default=3, fixed=True)
x = Parameter(default=10)
y = Parameter(default=12)
h = Parameter(default=5)
def __init__(self, f=f.default, x=x.default, y=y.default, h=h.default):
super().__init__(f, x, y)
def evaluate(self):
pass
def test_parameter_inheritance():
b = subclassmodel()
assert b.param_names == ('f', 'x', 'y', 'h')
assert b.h == 5
assert b.f == 3
assert b.f.fixed == True # noqa: E712
def test_parameter_description():
model = models.Gaussian1D(1.5, 2.5, 3.5)
assert model.amplitude._description == "Amplitude (peak value) of the Gaussian"
assert model.mean._description == "Position of peak (Gaussian)"
model = models.Voigt1D(x_0=5, amplitude_L=10, fwhm_L=0.5, fwhm_G=0.9)
assert model.amplitude_L._description == "The Lorentzian amplitude"
assert model.fwhm_L._description == "The Lorentzian full width at half maximum"
assert model.fwhm_G._description == "The Gaussian full width at half maximum"
def test_SmoothlyBrokenPowerLaw1D_validators():
with pytest.raises(InputParameterError) as err:
SmoothlyBrokenPowerLaw1D(amplitude=-1)
assert str(err.value) ==\
"amplitude parameter must be > 0"
with pytest.raises(InputParameterError) as err:
SmoothlyBrokenPowerLaw1D(delta=0)
assert str(err.value) ==\
"delta parameter must be >= 0.001"
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.filterwarnings(r'ignore:.*:RuntimeWarning')
@pytest.mark.filterwarnings(r'ignore:The fit may be unsuccessful.*')
def test_SmoothlyBrokenPowerLaw1D_fit_deriv():
x_lim = [0.01, 100]
x = np.logspace(x_lim[0], x_lim[1], 100)
parameters = {'parameters': [1, 10, -2, 2, 0.5],
'constraints': {'fixed': {'x_break': True, 'delta': True}}}
model_with_deriv = create_model(SmoothlyBrokenPowerLaw1D, parameters,
use_constraints=False)
model_no_deriv = create_model(SmoothlyBrokenPowerLaw1D, parameters,
use_constraints=False)
# NOTE: PR 10644 replaced deprecated usage of RandomState but could not
# find a new seed that did not cause test failure, resorted to hardcoding.
# add 10% noise to the amplitude
rsn_rand_1234567890 = np.array([
0.61879477, 0.59162363, 0.88868359, 0.89165480, 0.45756748,
0.77818808, 0.26706377, 0.99610621, 0.54009489, 0.53752161,
0.40099938, 0.70540579, 0.40518559, 0.94999075, 0.03075388,
0.13602495, 0.08297726, 0.42352224, 0.23449723, 0.74743526,
0.65177865, 0.68998682, 0.16413419, 0.87642114, 0.44733314,
0.57871104, 0.52377835, 0.62689056, 0.34869427, 0.26209748,
0.07498055, 0.17940570, 0.82999425, 0.98759822, 0.11326099,
0.63846415, 0.73056694, 0.88321124, 0.52721004, 0.66487673,
0.74209309, 0.94083846, 0.70123128, 0.29534353, 0.76134369,
0.77593881, 0.36985514, 0.89519067, 0.33082813, 0.86108824,
0.76897859, 0.61343376, 0.43870907, 0.91913538, 0.76958966,
0.51063556, 0.04443249, 0.57463611, 0.31382006, 0.41221713,
0.21531811, 0.03237521, 0.04166386, 0.73109303, 0.74556052,
0.64716325, 0.77575353, 0.64599254, 0.16885816, 0.48485480,
0.53844248, 0.99690349, 0.23657074, 0.04119088, 0.46501519,
0.35739006, 0.23002665, 0.53420791, 0.71639475, 0.81857486,
0.73994342, 0.07948837, 0.75688276, 0.13240193, 0.48465576,
0.20624753, 0.02298276, 0.54257873, 0.68123230, 0.35887468,
0.36296147, 0.67368397, 0.29505730, 0.66558885, 0.93652252,
0.36755130, 0.91787687, 0.75922703, 0.48668067, 0.45967890])
n = 0.1 * parameters['parameters'][0] * (rsn_rand_1234567890 - 0.5)
data = model_with_deriv(x) + n
fitter_with_deriv = fitting.LevMarLSQFitter()
new_model_with_deriv = fitter_with_deriv(model_with_deriv, x, data)
fitter_no_deriv = fitting.LevMarLSQFitter()
new_model_no_deriv = fitter_no_deriv(model_no_deriv, x, data,
estimate_jacobian=True)
assert_allclose(new_model_with_deriv.parameters,
new_model_no_deriv.parameters, atol=0.5)
class _ExtendedModelMeta(_ModelMeta):
@classmethod
def __prepare__(mcls, name, bases, **kwds):
# this shows the parent class machinery still applies
namespace = super().__prepare__(name, bases, **kwds)
# the custom bit
namespace.update(kwds)
return namespace
model = models.Gaussian1D(1.5, 2.5, 3.5)
assert model.amplitude._description == "Amplitude (peak value) of the Gaussian"
assert model.mean._description == "Position of peak (Gaussian)"
def test_metaclass_kwargs():
"""Test can pass kwargs to Models"""
class ClassModel(FittableModel, flag="flag"):
def evaluate(self):
pass
# Nothing further to test, just making the class is good enough.
def test_submetaclass_kwargs():
"""Test can pass kwargs to Model subclasses."""
class ClassModel(FittableModel, metaclass=_ExtendedModelMeta, flag="flag"):
def evaluate(self):
pass
assert ClassModel.flag == "flag"
class ModelDefault(Model):
slope = Parameter()
intercept = Parameter()
_separable = False
@staticmethod
def evaluate(x, slope, intercept):
return slope * x + intercept
class ModelCustom(ModelDefault):
def _calculate_separability_matrix(self):
return np.array([[0, ]])
def test_custom_separability_matrix():
original = separability_matrix(ModelDefault(slope=1, intercept=2))
assert original.all()
custom = separability_matrix(ModelCustom(slope=1, intercept=2))
assert not custom.any()
|
d6da02f65576a7c301621dc1cb4968ac3d7ab44dda0bf8cef2a9bfc2749d6445 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module tests model set evaluation and fitting for some common use cases.
"""
# pylint: disable=invalid-name
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy.modeling.models import (Polynomial1D, Polynomial2D, Legendre1D, Legendre2D,
Chebyshev2D, Chebyshev1D, Hermite1D, Hermite2D,
Linear1D, Planar2D)
from astropy.modeling.fitting import LinearLSQFitter, FittingWithOutlierRemoval
from astropy.modeling.core import Model
from astropy.modeling.parameters import Parameter
from astropy.utils import NumpyRNGContext
from astropy.stats import sigma_clip
x = np.arange(4)
xx = np.array([x, x + 10])
xxx = np.arange(24).reshape((3, 4, 2))
_RANDOM_SEED = 0x1337
class TParModel(Model):
"""
A toy model to test parameters machinery
"""
# standard_broadasting = False
n_inputs = 1
outputs = ('x',)
coeff = Parameter()
e = Parameter()
def __init__(self, coeff, e, **kwargs):
super().__init__(coeff=coeff, e=e, **kwargs)
@staticmethod
def evaluate(x, coeff, e):
return x*coeff + e
@pytest.mark.parametrize('model_class', [Polynomial1D, Chebyshev1D, Legendre1D, Hermite1D])
def test_model1d_axis_1(model_class):
"""
Test that a model initialized with model_set_axis=1
can be evaluated with model_set_axis=False.
"""
n_models = 2
model_axis = 1
c0 = [[2, 3]]
c1 = [[1, 2]]
t1 = model_class(1, c0=2, c1=1)
t2 = model_class(1, c0=3, c1=2)
p1 = model_class(1, c0=c0, c1=c1, n_models=n_models, model_set_axis=model_axis)
with pytest.raises(ValueError):
p1(x)
y = p1(x, model_set_axis=False)
assert y.shape[model_axis] == n_models
assert_allclose(y[:, 0], t1(x))
assert_allclose(y[:, 1], t2(x))
y = p1(xx, model_set_axis=False)
assert y.shape[model_axis] == n_models
assert_allclose(y[:, 0, :], t1(xx))
assert_allclose(y[:, 1, :], t2(xx))
y = p1(xxx, model_set_axis=False)
assert y.shape[model_axis] == n_models
assert_allclose(y[:, 0, :, :], t1(xxx))
assert_allclose(y[:, 1, :, :], t2(xxx))
@pytest.mark.parametrize('model_class', [Polynomial1D, Chebyshev1D, Legendre1D, Hermite1D])
def test_model1d_axis_2(model_class):
"""
Test that a model initialized with model_set_axis=2
can be evaluated with model_set_axis=False.
"""
p1 = model_class(1, c0=[[[1, 2, 3]]], c1=[[[10, 20, 30]]],
n_models=3, model_set_axis=2)
t1 = model_class(1, c0=1, c1=10)
t2 = model_class(1, c0=2, c1=20)
t3 = model_class(1, c0=3, c1=30)
with pytest.raises(ValueError):
p1(x)
with pytest.raises(ValueError):
p1(xx)
y = p1(x, model_set_axis=False)
assert y.shape == (1, 4, 3)
assert_allclose(y[:, :, 0].flatten(), t1(x))
assert_allclose(y[:, :, 1].flatten(), t2(x))
assert_allclose(y[:, :, 2].flatten(), t3(x))
@pytest.mark.parametrize('model_class', [Polynomial1D, Chebyshev1D, Legendre1D, Hermite1D])
def test_model1d_axis_0(model_class):
"""
Test that a model initialized with model_set_axis=0
can be evaluated with model_set_axis=False.
"""
p1 = model_class(1, n_models=2, model_set_axis=0)
p1.c0 = [2, 3]
p1.c1 = [1, 2]
t1 = model_class(1, c0=2, c1=1)
t2 = model_class(1, c0=3, c1=2)
with pytest.raises(ValueError):
p1(x)
y = p1(xx)
assert len(y) == 2
assert_allclose(y[0], t1(xx[0]))
assert_allclose(y[1], t2(xx[1]))
y = p1(x, model_set_axis=False)
assert len(y) == 2
assert_allclose(y[0], t1(x))
assert_allclose(y[1], t2(x))
y = p1(xx, model_set_axis=False)
assert len(y) == 2
assert_allclose(y[0], t1(xx))
assert_allclose(y[1], t2(xx))
y = p1(xxx, model_set_axis=False)
assert_allclose(y[0], t1(xxx))
assert_allclose(y[1], t2(xxx))
assert len(y) == 2
@pytest.mark.parametrize('model_class', [Chebyshev2D, Legendre2D, Hermite2D])
def test_model2d_axis_2(model_class):
"""
Test that a model initialized with model_set_axis=2
can be evaluated with model_set_axis=False.
"""
p2 = model_class(1, 1, c0_0=[[[0, 1, 2]]], c0_1=[[[3, 4, 5]]],
c1_0=[[[5, 6, 7]]], c1_1=[[[1,1,1]]], n_models=3, model_set_axis=2)
t1 = model_class(1, 1, c0_0=0, c0_1=3, c1_0=5, c1_1=1)
t2 = model_class(1, 1, c0_0=1, c0_1=4, c1_0=6, c1_1=1)
t3 = model_class(1, 1, c0_0=2, c0_1=5, c1_0=7, c1_1=1)
assert p2.c0_0.shape == (1, 1, 3)
y = p2(x, x, model_set_axis=False)
assert y.shape == (1, 4, 3)
# These are columns along the 2nd axis.
assert_allclose(y[:, :, 0].flatten(), t1(x, x))
assert_allclose(y[:, :, 1].flatten(), t2(x, x))
assert_allclose(y[:, :, 2].flatten(), t3(x, x))
def test_negative_axis():
p1 = Polynomial1D(1, c0=[1, 2], c1=[3, 4], n_models=2, model_set_axis=-1)
t1 = Polynomial1D(1, c0=1, c1=3)
t2 = Polynomial1D(1, c0=2, c1=4)
with pytest.raises(ValueError):
p1(x)
with pytest.raises(ValueError):
p1(xx)
xxt = xx.T
y = p1(xxt)
assert_allclose(y[:, 0], t1(xxt[:, 0]))
assert_allclose(y[:, 1], t2(xxt[:, 1]))
def test_shapes():
p2 = Polynomial1D(1, n_models=3, model_set_axis=2)
assert p2.c0.shape == (1, 1, 3)
assert p2.c1.shape == (1, 1, 3)
p1 = Polynomial1D(1, n_models=2, model_set_axis=1)
assert p1.c0.shape == (1, 2)
assert p1.c1.shape == (1, 2)
p1 = Polynomial1D(1, c0=[1, 2], c1=[3, 4], n_models=2, model_set_axis=-1)
assert p1.c0.shape == (2,)
assert p1.c1.shape == (2,)
e1 = [1, 2]
e2 = [3, 4]
a1 = np.array([[10, 20], [30, 40]])
a2 = np.array([[50, 60], [70, 80]])
t = TParModel([a1, a2], [e1, e2], n_models=2, model_set_axis=-1)
assert t.coeff.shape == (2, 2, 2)
assert t.e.shape == (2, 2)
t = TParModel([[a1, a2]], [[e1, e2]], n_models=2, model_set_axis=1)
assert t.coeff.shape == (1, 2, 2, 2)
assert t.e.shape == (1, 2, 2)
t = TParModel([a1, a2], [e1, e2], n_models=2, model_set_axis=0)
assert t.coeff.shape == (2, 2, 2)
assert t.e.shape == (2, 2)
t = TParModel([a1, a2], e=[1, 2], n_models=2, model_set_axis=0)
assert t.coeff.shape == (2, 2, 2)
assert t.e.shape == (2,)
def test_eval():
""" Tests evaluation of Linear1D and Planar2D with different model_set_axis."""
model = Linear1D(slope=[1, 2], intercept=[3, 4], n_models=2)
p = Polynomial1D(1, c0=[3, 4], c1=[1, 2], n_models=2)
assert_allclose(model(xx), p(xx))
assert_allclose(model(x, model_set_axis=False), p(x, model_set_axis=False))
with pytest.raises(ValueError):
model(x)
model = Linear1D(slope=[[1, 2]], intercept=[[3, 4]], n_models=2, model_set_axis=1)
p = Polynomial1D(1, c0=[[3, 4]], c1=[[1, 2]], n_models=2, model_set_axis=1)
assert_allclose(model(xx.T), p(xx.T))
assert_allclose(model(x, model_set_axis=False), p(x, model_set_axis=False))
with pytest.raises(ValueError):
model(xx)
model = Planar2D(slope_x=[1, 2], slope_y=[1, 2], intercept=[3, 4], n_models=2)
y = model(xx, xx)
assert y.shape == (2, 4)
with pytest.raises(ValueError):
model(x)
# Test fitting
@pytest.mark.parametrize('model_class', [Polynomial1D, Chebyshev1D, Legendre1D, Hermite1D])
def test_linearlsqfitter(model_class):
"""
Issue #7159
"""
p = model_class(1, n_models=2, model_set_axis=1)
# Generate data for fitting 2 models and re-stack them along the last axis:
y = np.array([2*x+1, x+4])
y = np.rollaxis(y, 0, -1).T
f = LinearLSQFitter()
# This seems to fit the model_set correctly:
fit = f(p, x, y)
model_y = fit(x, model_set_axis=False)
m1 = model_class(1, c0=fit.c0[0][0], c1=fit.c1[0][0], domain=fit.domain)
m2 = model_class(1, c0=fit.c0[0][1], c1=fit.c1[0][1], domain=fit.domain)
assert_allclose(model_y[:, 0], m1(x))
assert_allclose(model_y[:, 1], m2(x))
p = model_class(1, n_models=2, model_set_axis=0)
fit = f(p, x, y.T)
def test_model_set_axis_outputs():
fitter = LinearLSQFitter()
model_set = Polynomial2D(1, n_models=2, model_set_axis=2)
y2, x2 = np.mgrid[: 5, : 5]
# z = np.moveaxis([x2 + y2, 1 - 0.1 * x2 + 0.2 * y2]), 0, 2)
z = np.rollaxis(np.array([x2 + y2, 1 - 0.1 * x2 + 0.2 * y2]), 0, 3)
model = fitter(model_set, x2, y2, z)
res = model(x2, y2, model_set_axis=False)
assert z.shape == res.shape
# Test initializing with integer model_set_axis
# and evaluating with a different model_set_axis
model_set = Polynomial1D(1, c0=[1, 2], c1=[2, 3],
n_models=2, model_set_axis=0)
y0 = model_set(xx)
y1 = model_set(xx.T, model_set_axis=1)
assert_allclose(y0[0], y1[:, 0])
assert_allclose(y0[1], y1[:, 1])
model_set = Polynomial1D(1, c0=[[1, 2]], c1=[[2, 3]],
n_models=2, model_set_axis=1)
y0 = model_set(xx.T)
y1 = model_set(xx, model_set_axis=0)
assert_allclose(y0[:, 0], y1[0])
assert_allclose(y0[:, 1], y1[1])
with pytest.raises(ValueError):
model_set(x)
def test_fitting_shapes():
""" Test fitting model sets of Linear1D and Planar2D."""
fitter = LinearLSQFitter()
model = Linear1D(slope=[1, 2], intercept=[3, 4], n_models=2)
y = model(xx)
fit_model = fitter(model, x, y)
model = Linear1D(slope=[[1, 2]], intercept=[[3, 4]], n_models=2, model_set_axis=1)
fit_model = fitter(model, x, y.T)
model = Planar2D(slope_x=[1, 2], slope_y=[1, 2], intercept=[3, 4], n_models=2)
y = model(xx, xx)
fit_model = fitter(model, x, x, y)
def test_compound_model_sets():
with pytest.raises(ValueError):
Polynomial1D(1, n_models=2, model_set_axis=1) | Polynomial1D(1, n_models=2, model_set_axis=0)
def test_linear_fit_model_set_errors():
init_model = Polynomial1D(degree=2, c0=[1, 1], n_models=2)
x = np.arange(10)
y = init_model(x, model_set_axis=False)
fitter = LinearLSQFitter()
with pytest.raises(ValueError):
fitter(init_model, x[:5], y)
with pytest.raises(ValueError):
fitter(init_model, x, y[:, :5])
def test_linear_fit_model_set_common_weight():
"""Tests fitting multiple models simultaneously."""
init_model = Polynomial1D(degree=2, c0=[1, 1], n_models=2)
x = np.arange(10)
y_expected = init_model(x, model_set_axis=False)
assert y_expected.shape == (2, 10)
# Add a bit of random noise
with NumpyRNGContext(_RANDOM_SEED):
y = y_expected + np.random.normal(0, 0.01, size=y_expected.shape)
fitter = LinearLSQFitter()
weights = np.ones(10)
weights[[0, -1]] = 0
fitted_model = fitter(init_model, x, y, weights=weights)
assert_allclose(fitted_model(x, model_set_axis=False), y_expected,
rtol=1e-1)
# Check that using null weights raises an error
# ValueError: On entry to DLASCL parameter number 4 had an illegal value
with pytest.raises(ValueError,
match='Found NaNs in the coefficient matrix'):
with pytest.warns(RuntimeWarning,
match=r'invalid value encountered in.*divide'):
fitted_model = fitter(init_model, x, y, weights=np.zeros(10))
def test_linear_fit_model_set_weights():
"""Tests fitting multiple models simultaneously."""
init_model = Polynomial1D(degree=2, c0=[1, 1], n_models=2)
x = np.arange(10)
y_expected = init_model(x, model_set_axis=False)
assert y_expected.shape == (2, 10)
# Add a bit of random noise
with NumpyRNGContext(_RANDOM_SEED):
y = y_expected + np.random.normal(0, 0.01, size=y_expected.shape)
weights = np.ones_like(y)
# Put a null weight for the min and max values
weights[[0, 1], weights.argmin(axis=1)] = 0
weights[[0, 1], weights.argmax(axis=1)] = 0
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y, weights=weights)
assert_allclose(fitted_model(x, model_set_axis=False), y_expected,
rtol=1e-1)
# Check that using null weights raises an error
weights[0] = 0
with pytest.raises(ValueError,
match='Found NaNs in the coefficient matrix'):
with pytest.warns(RuntimeWarning,
match=r'invalid value encountered in.*divide'):
fitted_model = fitter(init_model, x, y, weights=weights)
# Now we mask the values where weight is 0
with pytest.warns(RuntimeWarning,
match=r'invalid value encountered in.*divide'):
fitted_model = fitter(init_model, x,
np.ma.array(y, mask=np.isclose(weights, 0)),
weights=weights)
# Parameters for the first model are all NaNs
assert np.all(np.isnan(fitted_model.param_sets[:, 0]))
assert np.all(np.isnan(fitted_model(x, model_set_axis=False)[0]))
# Second model is fitted correctly
assert_allclose(fitted_model(x, model_set_axis=False)[1], y_expected[1],
rtol=1e-1)
def test_linear_fit_2d_model_set_errors():
init_model = Polynomial2D(degree=2, c0_0=[1, 1], n_models=2)
x = np.arange(10)
y = np.arange(10)
z = init_model(x, y, model_set_axis=False)
fitter = LinearLSQFitter()
with pytest.raises(ValueError):
fitter(init_model, x[:5], y, z)
with pytest.raises(ValueError):
fitter(init_model, x, y, z[:, :5])
def test_linear_fit_2d_model_set_common_weight():
init_model = Polynomial2D(degree=2, c1_0=[1, 2], c0_1=[-0.5, 1],
n_models=2,
fixed={'c1_0': True, 'c0_1': True})
x, y = np.mgrid[0:5, 0:5]
zz = np.array([1+x-0.5*y+0.1*x*x, 2*x+y-0.2*y*y])
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y, zz, weights=np.ones((5, 5)))
assert_allclose(fitted_model(x, y, model_set_axis=False), zz,
atol=1e-14)
def test_linear_fit_flat_2d_model_set_common_weight():
init_model = Polynomial2D(degree=2, c1_0=[1, 2], c0_1=[-0.5, 1],
n_models=2,
fixed={'c1_0': True, 'c0_1': True})
x, y = np.mgrid[0:5, 0:5]
x, y = x.flatten(), y.flatten()
zz = np.array([1+x-0.5*y+0.1*x*x, 2*x+y-0.2*y*y])
weights = np.ones(25)
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y, zz, weights=weights)
assert_allclose(fitted_model(x, y, model_set_axis=False), zz,
atol=1e-14)
def test_linear_fit_2d_model_set_weights():
init_model = Polynomial2D(degree=2, c1_0=[1, 2], c0_1=[-0.5, 1],
n_models=2,
fixed={'c1_0': True, 'c0_1': True})
x, y = np.mgrid[0:5, 0:5]
zz = np.array([1+x-0.5*y+0.1*x*x, 2*x+y-0.2*y*y])
fitter = LinearLSQFitter()
weights = [np.ones((5, 5)), np.ones((5, 5))]
fitted_model = fitter(init_model, x, y, zz, weights=weights)
assert_allclose(fitted_model(x, y, model_set_axis=False), zz,
atol=1e-14)
def test_linear_fit_flat_2d_model_set_weights():
init_model = Polynomial2D(degree=2, c1_0=[1, 2], c0_1=[-0.5, 1],
n_models=2,
fixed={'c1_0': True, 'c0_1': True})
x, y = np.mgrid[0:5, 0:5]
x, y = x.flatten(), y.flatten()
zz = np.array([1+x-0.5*y+0.1*x*x, 2*x+y-0.2*y*y])
weights = np.ones((2, 25))
fitter = LinearLSQFitter()
fitted_model = fitter(init_model, x, y, zz, weights=weights)
assert_allclose(fitted_model(x, y, model_set_axis=False), zz,
atol=1e-14)
class Test1ModelSet:
"""
Check that fitting a single model works with a length-1 model set axis.
It's not clear that this was originally intended usage, but it can be
convenient, eg. when fitting a range of image rows that may be a single
row, and some existing scripts might rely on it working.
Currently this does not work with FittingWithOutlierRemoval.
"""
def setup_class(self):
self.x1 = np.arange(0, 10)
self.y1 = np.array([0.5 + 2.5*self.x1])
self.w1 = np.ones((10,))
self.y1[0, 8] = 100.
self.w1[8] = 0.
self.y2, self.x2 = np.mgrid[0:10, 0:10]
self.z2 = np.array([1 - 0.1*self.x2 + 0.2*self.y2])
self.w2 = np.ones((10, 10))
self.z2[0, 1, 2] = 100.
self.w2[1, 2] = 0.
def test_linear_1d_common_weights(self):
model = Polynomial1D(1)
fitter = LinearLSQFitter()
model = fitter(model, self.x1, self.y1, weights=self.w1)
assert_allclose(model.c0, 0.5, atol=1e-12)
assert_allclose(model.c1, 2.5, atol=1e-12)
def test_linear_1d_separate_weights(self):
model = Polynomial1D(1)
fitter = LinearLSQFitter()
model = fitter(model, self.x1, self.y1,
weights=self.w1[np.newaxis, ...])
assert_allclose(model.c0, 0.5, atol=1e-12)
assert_allclose(model.c1, 2.5, atol=1e-12)
def test_linear_1d_separate_weights_axis_1(self):
model = Polynomial1D(1, model_set_axis=1)
fitter = LinearLSQFitter()
model = fitter(model, self.x1, self.y1.T,
weights=self.w1[..., np.newaxis])
assert_allclose(model.c0, 0.5, atol=1e-12)
assert_allclose(model.c1, 2.5, atol=1e-12)
def test_linear_2d_common_weights(self):
model = Polynomial2D(1)
fitter = LinearLSQFitter()
model = fitter(model, self.x2, self.y2, self.z2, weights=self.w2)
assert_allclose(model.c0_0, 1., atol=1e-12)
assert_allclose(model.c1_0, -0.1, atol=1e-12)
assert_allclose(model.c0_1, 0.2, atol=1e-12)
def test_linear_2d_separate_weights(self):
model = Polynomial2D(1)
fitter = LinearLSQFitter()
model = fitter(model, self.x2, self.y2, self.z2,
weights=self.w2[np.newaxis, ...])
assert_allclose(model.c0_0, 1., atol=1e-12)
assert_allclose(model.c1_0, -0.1, atol=1e-12)
assert_allclose(model.c0_1, 0.2, atol=1e-12)
def test_linear_2d_separate_weights_axis_2(self):
model = Polynomial2D(1, model_set_axis=2)
fitter = LinearLSQFitter()
model = fitter(model, self.x2, self.y2, np.rollaxis(self.z2, 0, 3),
weights=self.w2[..., np.newaxis])
assert_allclose(model.c0_0, 1., atol=1e-12)
assert_allclose(model.c1_0, -0.1, atol=1e-12)
assert_allclose(model.c0_1, 0.2, atol=1e-12)
|
addb61bc691884e38671a2e472ab0e7f9f34314a7e921e567d9ac4c25bdccb79 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# pylint: disable=invalid-name, no-member
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy.wcs import wcs
from astropy.modeling import models
from astropy import units as u
from astropy.tests.helper import assert_quantity_allclose
@pytest.mark.parametrize(('inp'), [(0, 0), (4000, -20.56), (-2001.5, 45.9),
(0, 90), (0, -90), (np.mgrid[:4, :6])])
def test_against_wcslib(inp):
w = wcs.WCS()
crval = [202.4823228, 47.17511893]
w.wcs.crval = crval
w.wcs.ctype = ['RA---TAN', 'DEC--TAN']
lonpole = 180
tan = models.Pix2Sky_TAN()
n2c = models.RotateNative2Celestial(crval[0] * u.deg, crval[1] * u.deg, lonpole * u.deg)
c2n = models.RotateCelestial2Native(crval[0] * u.deg, crval[1] * u.deg, lonpole * u.deg)
m = tan | n2c
minv = c2n | tan.inverse
radec = w.wcs_pix2world(inp[0], inp[1], 1)
xy = w.wcs_world2pix(radec[0], radec[1], 1)
assert_allclose(m(*inp), radec, atol=1e-12)
assert_allclose(minv(*radec), xy, atol=1e-12)
@pytest.mark.parametrize(('inp'), [(40 * u.deg, -0.057 * u.rad), (21.5 * u.arcsec, 45.9 * u.deg)])
def test_roundtrip_sky_rotation(inp):
lon, lat, lon_pole = 42 * u.deg, (43 * u.deg).to(u.arcsec), (44 * u.deg).to(u.rad)
n2c = models.RotateNative2Celestial(lon, lat, lon_pole)
c2n = models.RotateCelestial2Native(lon, lat, lon_pole)
assert_quantity_allclose(n2c.inverse(*n2c(*inp)), inp, atol=1e-13 * u.deg)
assert_quantity_allclose(c2n.inverse(*c2n(*inp)), inp, atol=1e-13 * u.deg)
def test_Rotation2D():
model = models.Rotation2D(angle=90 * u.deg)
a, b = 1 * u.deg, 0 * u.deg
x, y = model(a, b)
assert_quantity_allclose([x, y], [0 * u.deg, 1 * u.deg], atol=1e-10 * u.deg)
def test_Rotation2D_inverse():
model = models.Rotation2D(angle=234.23494 * u.deg)
x, y = model.inverse(*model(1 * u.deg, 0 * u.deg))
assert_quantity_allclose([x, y], [1 * u.deg, 0 * u.deg], atol=1e-10 * u.deg)
def test_euler_angle_rotations():
ydeg = (90 * u.deg, 0 * u.deg)
y = (90, 0)
z = (0, 90)
# rotate y into minus z
model = models.EulerAngleRotation(0 * u.rad, np.pi / 2 * u.rad, 0 * u.rad, 'zxz')
assert_allclose(model(*z), y, atol=10**-12)
model = models.EulerAngleRotation(0 * u.deg, 90 * u.deg, 0 * u.deg, 'zxz')
assert_quantity_allclose(model(*(z * u.deg)), ydeg, atol=10**-12 * u.deg)
@pytest.mark.parametrize(('params'), [(60, 10, 25),
(60 * u.deg, 10 * u.deg, 25 * u.deg),
((60 * u.deg).to(u.rad),
(10 * u.deg).to(u.rad),
(25 * u.deg).to(u.rad))])
def test_euler_rotations_with_units(params):
x = 1 * u.deg
y = 1 * u.deg
phi, theta, psi = params
urot = models.EulerAngleRotation(phi, theta, psi, axes_order='xyz')
a, b = urot(x.value, y.value)
assert_allclose((a, b), (-23.614457631192547, 9.631254579686113))
a, b = urot(x, y)
assert_quantity_allclose((a, b), (-23.614457631192547 * u.deg, 9.631254579686113 * u.deg))
a, b = urot(x.to(u.rad), y.to(u.rad))
assert_quantity_allclose((a, b), (-23.614457631192547 * u.deg, 9.631254579686113 * u.deg))
def test_attributes():
n2c = models.RotateNative2Celestial(20016 * u.arcsec, -72.3 * u.deg, np.pi * u.rad)
assert_allclose(n2c.lat.value, -72.3)
assert_allclose(n2c.lat._raw_value, -1.2618730491919001)
assert_allclose(n2c.lon.value, 20016)
assert_allclose(n2c.lon._raw_value, 0.09704030641088472)
assert_allclose(n2c.lon_pole.value, np.pi)
assert_allclose(n2c.lon_pole._raw_value, np.pi)
assert n2c.lon.unit is u.Unit("arcsec")
assert n2c.lon.internal_unit is u.Unit("rad")
assert n2c.lat.unit is u.Unit("deg")
assert n2c.lat.internal_unit is u.Unit("rad")
assert n2c.lon_pole.unit is u.Unit("rad")
assert n2c.lon_pole.internal_unit is u.Unit("rad")
|
c7f9f88ebde84bf953c7e5cef3c16d82f3be802cbd55c447da5ea35e581fd9a6 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests that relate to evaluating models with quantity parameters
"""
# pylint: disable=invalid-name, no-member
import numpy as np
import pytest
from numpy.testing import assert_allclose
from astropy.modeling.core import Model
from astropy.modeling.models import Gaussian1D, Shift, Scale, Pix2Sky_TAN
from astropy import units as u
from astropy.units import UnitsError
from astropy.tests.helper import assert_quantity_allclose
# We start off by taking some simple cases where the units are defined by
# whatever the model is initialized with, and we check that the model evaluation
# returns quantities.
def test_evaluate_with_quantities():
"""
Test evaluation of a single model with Quantity parameters that do
not explicitly require units.
"""
# We create two models here - one with quantities, and one without. The one
# without is used to create the reference values for comparison.
g = Gaussian1D(1, 1, 0.1)
gq = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m)
# We first check that calling the Gaussian with quantities returns the
# expected result
assert_quantity_allclose(gq(1 * u.m), g(1) * u.J)
# Units have to be specified for the Gaussian with quantities - if not, an
# error is raised
with pytest.raises(UnitsError) as exc:
gq(1)
assert exc.value.args[0] == ("Gaussian1D: Units of input 'x', (dimensionless), could not be "
"converted to required input units of m (length)")
# However, zero is a special case
assert_quantity_allclose(gq(0), g(0) * u.J)
# We can also evaluate models with equivalent units
assert_allclose(gq(0.0005 * u.km).value, g(0.5))
# But not with incompatible units
with pytest.raises(UnitsError) as exc:
gq(3 * u.s)
assert exc.value.args[0] == ("Gaussian1D: Units of input 'x', s (time), could not be "
"converted to required input units of m (length)")
# We also can't evaluate the model without quantities with a quantity
with pytest.raises(UnitsError) as exc:
g(3 * u.m)
# TODO: determine what error message should be here
# assert exc.value.args[0] == ("Units of input 'x', m (length), could not be "
# "converted to required dimensionless input")
def test_evaluate_with_quantities_and_equivalencies():
"""
We now make sure that equivalencies are correctly taken into account
"""
g = Gaussian1D(1 * u.Jy, 10 * u.nm, 2 * u.nm)
# We aren't setting the equivalencies, so this won't work
with pytest.raises(UnitsError) as exc:
g(30 * u.PHz)
assert exc.value.args[0] == ("Gaussian1D: Units of input 'x', PHz (frequency), could "
"not be converted to required input units of "
"nm (length)")
# But it should now work if we pass equivalencies when evaluating
assert_quantity_allclose(g(30 * u.PHz, equivalencies={'x': u.spectral()}),
g(9.993081933333332 * u.nm))
class MyTestModel(Model):
n_inputs = 2
n_outputs = 1
def evaluate(self, a, b):
print('a', a)
print('b', b)
return a * b
class TestInputUnits():
def setup_method(self, method):
self.model = MyTestModel()
def test_evaluate(self):
# We should be able to evaluate with anything
assert_quantity_allclose(self.model(3, 5), 15)
assert_quantity_allclose(self.model(4 * u.m, 5), 20 * u.m)
assert_quantity_allclose(self.model(3 * u.deg, 5), 15 * u.deg)
def test_input_units(self):
self.model._input_units = {'x': u.deg}
assert_quantity_allclose(self.model(3 * u.deg, 4), 12 * u.deg)
assert_quantity_allclose(self.model(4 * u.rad, 2), 8 * u.rad)
assert_quantity_allclose(self.model(4 * u.rad, 2 * u.s), 8 * u.rad * u.s)
with pytest.raises(UnitsError) as exc:
self.model(4 * u.s, 3)
assert exc.value.args[0] == ("MyTestModel: Units of input 'x', s (time), could not be "
"converted to required input units of deg (angle)")
with pytest.raises(UnitsError) as exc:
self.model(3, 3)
assert exc.value.args[0] == ("MyTestModel: Units of input 'x', (dimensionless), could "
"not be converted to required input units of deg (angle)")
def test_input_units_allow_dimensionless(self):
self.model._input_units = {'x': u.deg}
self.model._input_units_allow_dimensionless = True
assert_quantity_allclose(self.model(3 * u.deg, 4), 12 * u.deg)
assert_quantity_allclose(self.model(4 * u.rad, 2), 8 * u.rad)
with pytest.raises(UnitsError) as exc:
self.model(4 * u.s, 3)
assert exc.value.args[0] == ("MyTestModel: Units of input 'x', s (time), could not be "
"converted to required input units of deg (angle)")
assert_quantity_allclose(self.model(3, 3), 9)
def test_input_units_strict(self):
self.model._input_units = {'x': u.deg}
self.model._input_units_strict = True
assert_quantity_allclose(self.model(3 * u.deg, 4), 12 * u.deg)
result = self.model(np.pi * u.rad, 2)
assert_quantity_allclose(result, 360 * u.deg)
assert result.unit is u.deg
def test_input_units_equivalencies(self):
self.model._input_units = {'x': u.micron}
with pytest.raises(UnitsError) as exc:
self.model(3 * u.PHz, 3)
assert exc.value.args[0] == ("MyTestModel: Units of input 'x', PHz (frequency), could "
"not be converted to required input units of "
"micron (length)")
self.model.input_units_equivalencies = {'x': u.spectral()}
assert_quantity_allclose(self.model(3 * u.PHz, 3),
3 * (3 * u.PHz).to(u.micron, equivalencies=u.spectral()))
def test_return_units(self):
self.model._input_units = {'z': u.deg}
self.model._return_units = {'z': u.rad}
result = self.model(3 * u.deg, 4)
assert_quantity_allclose(result, 12 * u.deg)
assert result.unit is u.rad
def test_return_units_scalar(self):
# Check that return_units also works when giving a single unit since
# there is only one output, so is unambiguous.
self.model._input_units = {'x': u.deg}
self.model._return_units = u.rad
result = self.model(3 * u.deg, 4)
assert_quantity_allclose(result, 12 * u.deg)
assert result.unit is u.rad
def test_and_input_units():
"""
Test units to first model in chain.
"""
s1 = Shift(10 * u.deg)
s2 = Shift(10 * u.deg)
cs = s1 & s2
out = cs(10 * u.arcsecond, 20 * u.arcsecond)
assert_quantity_allclose(out[0], 10 * u.deg + 10 * u.arcsec)
assert_quantity_allclose(out[1], 10 * u.deg + 20 * u.arcsec)
def test_plus_input_units():
"""
Test units to first model in chain.
"""
s1 = Shift(10 * u.deg)
s2 = Shift(10 * u.deg)
cs = s1 + s2
out = cs(10 * u.arcsecond)
assert_quantity_allclose(out, 20 * u.deg + 20 * u.arcsec)
def test_compound_input_units():
"""
Test units to first model in chain.
"""
s1 = Shift(10 * u.deg)
s2 = Shift(10 * u.deg)
cs = s1 | s2
out = cs(10 * u.arcsecond)
assert_quantity_allclose(out, 20 * u.deg + 10 * u.arcsec)
def test_compound_input_units_fail():
"""
Test incompatible units to first model in chain.
"""
s1 = Shift(10 * u.deg)
s2 = Shift(10 * u.deg)
cs = s1 | s2
with pytest.raises(UnitsError):
cs(10 * u.pix)
def test_compound_incompatible_units_fail():
"""
Test incompatible model units in chain.
"""
s1 = Shift(10 * u.pix)
s2 = Shift(10 * u.deg)
cs = s1 | s2
with pytest.raises(UnitsError):
cs(10 * u.pix)
def test_compound_pipe_equiv_call():
"""
Check that equivalencies work when passed to evaluate, for a chained model
(which has one input).
"""
s1 = Shift(10 * u.deg)
s2 = Shift(10 * u.deg)
cs = s1 | s2
out = cs(10 * u.pix, equivalencies={'x': u.pixel_scale(0.5 * u.deg / u.pix)})
assert_quantity_allclose(out, 25 * u.deg)
def test_compound_and_equiv_call():
"""
Check that equivalencies work when passed to evaluate, for a composite model
with two inputs.
"""
s1 = Shift(10 * u.deg)
s2 = Shift(10 * u.deg)
cs = s1 & s2
out = cs(10 * u.pix, 10 * u.pix, equivalencies={'x0': u.pixel_scale(0.5 * u.deg / u.pix),
'x1': u.pixel_scale(0.5 * u.deg / u.pix)})
assert_quantity_allclose(out[0], 15 * u.deg)
assert_quantity_allclose(out[1], 15 * u.deg)
def test_compound_input_units_equivalencies():
"""
Test setting input_units_equivalencies on one of the models.
"""
s1 = Shift(10 * u.deg)
s1.input_units_equivalencies = {'x': u.pixel_scale(0.5 * u.deg / u.pix)}
s2 = Shift(10 * u.deg)
sp = Shift(10 * u.pix)
cs = s1 | s2
assert cs.input_units_equivalencies == {'x': u.pixel_scale(0.5 * u.deg / u.pix)}
out = cs(10 * u.pix)
assert_quantity_allclose(out, 25 * u.deg)
cs = sp | s1
assert cs.input_units_equivalencies is None
out = cs(10 * u.pix)
assert_quantity_allclose(out, 20 * u.deg)
cs = s1 & s2
assert cs.input_units_equivalencies == {'x0': u.pixel_scale(0.5 * u.deg / u.pix)}
cs = cs.rename('TestModel')
out = cs(20 * u.pix, 10 * u.deg)
assert_quantity_allclose(out, 20 * u.deg)
with pytest.raises(UnitsError) as exc:
out = cs(20 * u.pix, 10 * u.pix)
assert exc.value.args[0] == "Shift: Units of input 'x', pix (unknown), could not be converted to required input units of deg (angle)"
def test_compound_input_units_strict():
"""
Test setting input_units_strict on one of the models.
"""
class ScaleDegrees(Scale):
input_units = {'x': u.deg}
s1 = ScaleDegrees(2)
s2 = Scale(2)
cs = s1 | s2
out = cs(10 * u.arcsec)
assert_quantity_allclose(out, 40 * u.arcsec)
assert out.unit is u.deg # important since this tests input_units_strict
cs = s2 | s1
out = cs(10 * u.arcsec)
assert_quantity_allclose(out, 40 * u.arcsec)
assert out.unit is u.deg # important since this tests input_units_strict
cs = s1 & s2
out = cs(10 * u.arcsec, 10 * u.arcsec)
assert_quantity_allclose(out, 20 * u.arcsec)
assert out[0].unit is u.deg
assert out[1].unit is u.arcsec
def test_compound_input_units_allow_dimensionless():
"""
Test setting input_units_allow_dimensionless on one of the models.
"""
class ScaleDegrees(Scale):
input_units = {'x': u.deg}
s1 = ScaleDegrees(2)
s1._input_units_allow_dimensionless = True
s2 = Scale(2)
cs = s1 | s2
cs = cs.rename('TestModel')
out = cs(10)
assert_quantity_allclose(out, 40 * u.one)
out = cs(10 * u.arcsec)
assert_quantity_allclose(out, 40 * u.arcsec)
with pytest.raises(UnitsError) as exc:
out = cs(10 * u.m)
assert exc.value.args[0] == ("ScaleDegrees: Units of input 'x', m (length), "
"could not be converted to required input units of deg (angle)")
s1._input_units_allow_dimensionless = False
cs = s1 | s2
cs = cs.rename('TestModel')
with pytest.raises(UnitsError) as exc:
out = cs(10)
assert exc.value.args[0] == ("ScaleDegrees: Units of input 'x', (dimensionless), "
"could not be converted to required input units of deg (angle)")
s1._input_units_allow_dimensionless = True
cs = s2 | s1
cs = cs.rename('TestModel')
out = cs(10)
assert_quantity_allclose(out, 40 * u.one)
out = cs(10 * u.arcsec)
assert_quantity_allclose(out, 40 * u.arcsec)
with pytest.raises(UnitsError) as exc:
out = cs(10 * u.m)
assert exc.value.args[0] == ("ScaleDegrees: Units of input 'x', m (length), "
"could not be converted to required input units of deg (angle)")
s1._input_units_allow_dimensionless = False
cs = s2 | s1
with pytest.raises(UnitsError) as exc:
out = cs(10)
assert exc.value.args[0] == ("ScaleDegrees: Units of input 'x', (dimensionless), "
"could not be converted to required input units of deg (angle)")
s1._input_units_allow_dimensionless = True
s1 = ScaleDegrees(2)
s1._input_units_allow_dimensionless = True
s2 = ScaleDegrees(2)
s2._input_units_allow_dimensionless = False
cs = s1 & s2
cs = cs.rename('TestModel')
out = cs(10, 10 * u.arcsec)
assert_quantity_allclose(out[0], 20 * u.one)
assert_quantity_allclose(out[1], 20 * u.arcsec)
with pytest.raises(UnitsError) as exc:
out = cs(10, 10)
assert exc.value.args[0] == ("ScaleDegrees: Units of input 'x', (dimensionless), "
"could not be converted to required input units of deg (angle)")
def test_compound_return_units():
"""
Test that return_units on the first model in the chain is respected for the
input to the second.
"""
class PassModel(Model):
n_inputs = 2
n_outputs = 2
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def input_units(self):
""" Input units. """
return {'x0': u.deg, 'x1': u.deg}
@property
def return_units(self):
""" Output units. """
return {'x0': u.deg, 'x1': u.deg}
def evaluate(self, x, y):
return x.value, y.value
cs = Pix2Sky_TAN() | PassModel()
assert_quantity_allclose(cs(0*u.deg, 0*u.deg), (0, 90)*u.deg)
|
fe54f71a7770137edefa8f366810bfb554843c2a242fcd0a2b091a410df8d5c3 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests that relate to fitting models with quantity parameters
"""
# pylint: disable=invalid-name, no-member
import numpy as np
import pytest
from astropy import units as u
from astropy.units import UnitsError
from astropy.tests.helper import assert_quantity_allclose
from astropy.utils import NumpyRNGContext
from astropy.modeling import fitting
from astropy.modeling import models
from astropy.modeling.core import Fittable1DModel
from astropy.modeling.parameters import Parameter
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
# Fitting should be as intuitive as possible to the user. Essentially, models
# and fitting should work without units, but if one has units, the other should
# have units too, and the resulting fitted parameters will also have units.
def _fake_gaussian_data():
# Generate fake data
with NumpyRNGContext(12345):
x = np.linspace(-5., 5., 2000)
y = 3 * np.exp(-0.5 * (x - 1.3)**2 / 0.8**2)
y += np.random.normal(0., 0.2, x.shape)
# Attach units to data
x = x * u.m
y = y * u.Jy
return x, y
compound_models_no_units = [
models.Linear1D() + models.Gaussian1D() + models.Gaussian1D(),
models.Linear1D() + models.Gaussian1D() | models.Scale(),
models.Linear1D() + models.Gaussian1D() | models.Shift(),
]
class CustomInputNamesModel(Fittable1DModel):
n_inputs = 1
n_outputs = 1
a = Parameter(default=1.0)
b = Parameter(default=1.0)
def __init__(self, a=a, b=b):
super().__init__(a=a, b=b)
self.inputs = ('inn',)
self.outputs = ('out',)
@staticmethod
def evaluate(inn, a, b):
return a * inn + b
@property
def input_units(self):
if self.a.unit is None and self.b.unit is None:
return None
else:
return {'inn': self.b.unit / self.a.unit}
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'a': outputs_unit['out'] / inputs_unit['inn'],
'b': outputs_unit['out']
}
def models_with_custom_names():
line = models.Linear1D(1 * u.m / u.s, 2 * u.m)
line.inputs = ('inn',)
line.outputs = ('out',)
custom_names_model = CustomInputNamesModel(1 * u.m / u.s, 2 * u.m)
return [line, custom_names_model]
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitting_simple():
x, y = _fake_gaussian_data()
# Fit the data using a Gaussian with units
g_init = models.Gaussian1D()
fit_g = fitting.LevMarLSQFitter()
g = fit_g(g_init, x, y)
# TODO: update actual numerical results once implemented, but these should
# be close to the values below.
assert_quantity_allclose(g.amplitude, 3 * u.Jy, rtol=0.05)
assert_quantity_allclose(g.mean, 1.3 * u.m, rtol=0.05)
assert_quantity_allclose(g.stddev, 0.8 * u.m, rtol=0.05)
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitting_with_initial_values():
x, y = _fake_gaussian_data()
# Fit the data using a Gaussian with units
g_init = models.Gaussian1D(amplitude=1. * u.mJy,
mean=3 * u.cm,
stddev=2 * u.mm)
fit_g = fitting.LevMarLSQFitter()
g = fit_g(g_init, x, y)
# TODO: update actual numerical results once implemented, but these should
# be close to the values below.
assert_quantity_allclose(g.amplitude, 3 * u.Jy, rtol=0.05)
assert_quantity_allclose(g.mean, 1.3 * u.m, rtol=0.05)
assert_quantity_allclose(g.stddev, 0.8 * u.m, rtol=0.05)
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitting_missing_data_units():
"""
Raise an error if the model has units but the data doesn't
"""
class UnorderedGaussian1D(models.Gaussian1D):
# Parameters are ordered differently here from Gaussian1D
# to ensure the order does not break functionality.
def _parameter_units_for_data_units(self, inputs_unit, outputs_unit):
return {'amplitude': outputs_unit['y'],
'mean': inputs_unit['x'],
'stddev': inputs_unit['x']}
g_init = UnorderedGaussian1D(amplitude=1. * u.mJy,
mean=3 * u.cm,
stddev=2 * u.mm)
fit_g = fitting.LevMarLSQFitter()
# We define flux unit so that conversion fails at wavelength unit.
# This is because the order of parameter unit conversion seems to
# follow the order defined in _parameter_units_for_data_units method.
with pytest.raises(UnitsError) as exc:
fit_g(g_init, [1, 2, 3],
[4, 5, 6] * (u.erg / (u.s * u.cm * u.cm * u.Hz)))
assert exc.value.args[0] == ("'cm' (length) and '' (dimensionless) are "
"not convertible")
with pytest.raises(UnitsError) as exc:
fit_g(g_init, [1, 2, 3] * u.m, [4, 5, 6])
assert exc.value.args[0] == ("'mJy' (spectral flux density) and '' "
"(dimensionless) are not convertible")
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitting_missing_model_units():
"""
Proceed if the data has units but the model doesn't
"""
x, y = _fake_gaussian_data()
g_init = models.Gaussian1D(amplitude=1., mean=3, stddev=2)
fit_g = fitting.LevMarLSQFitter()
g = fit_g(g_init, x, y)
assert_quantity_allclose(g.amplitude, 3 * u.Jy, rtol=0.05)
assert_quantity_allclose(g.mean, 1.3 * u.m, rtol=0.05)
assert_quantity_allclose(g.stddev, 0.8 * u.m, rtol=0.05)
g_init = models.Gaussian1D(amplitude=1., mean=3 * u.m, stddev=2 * u.m)
fit_g = fitting.LevMarLSQFitter()
g = fit_g(g_init, x, y)
assert_quantity_allclose(g.amplitude, 3 * u.Jy, rtol=0.05)
assert_quantity_allclose(g.mean, 1.3 * u.m, rtol=0.05)
assert_quantity_allclose(g.stddev, 0.8 * u.m, rtol=0.05)
@pytest.mark.skipif('not HAS_SCIPY')
def test_fitting_incompatible_units():
"""
Raise an error if the data and model have incompatible units
"""
g_init = models.Gaussian1D(amplitude=1. * u.Jy,
mean=3 * u.m,
stddev=2 * u.cm)
fit_g = fitting.LevMarLSQFitter()
with pytest.raises(UnitsError) as exc:
fit_g(g_init, [1, 2, 3] * u.Hz, [4, 5, 6] * u.Jy)
assert exc.value.args[0] == ("'Hz' (frequency) and 'm' (length) are not convertible")
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.filterwarnings(r'ignore:The fit may be unsuccessful.*')
@pytest.mark.parametrize('model', compound_models_no_units)
def test_compound_without_units(model):
x = np.linspace(-5, 5, 10) * u.Angstrom
with NumpyRNGContext(12345):
y = np.random.sample(10)
fitter = fitting.LevMarLSQFitter()
res_fit = fitter(model, x, y * u.Hz)
for param_name in res_fit.param_names:
print(getattr(res_fit, param_name))
assert all([res_fit[i]._has_units for i in range(3)])
z = res_fit(x)
assert isinstance(z, u.Quantity)
res_fit = fitter(model, np.arange(10) * u.Unit('Angstrom'), y)
assert all([res_fit[i]._has_units for i in range(3)])
z = res_fit(x)
assert isinstance(z, np.ndarray)
# FIXME: See https://github.com/astropy/astropy/issues/10675
# @pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.skip(reason='Flaky and ill-conditioned')
def test_compound_fitting_with_units():
x = np.linspace(-5, 5, 15) * u.Angstrom
y = np.linspace(-5, 5, 15) * u.Angstrom
fitter = fitting.LevMarLSQFitter()
m = models.Gaussian2D(10*u.Hz,
3*u.Angstrom, 4*u.Angstrom,
1*u.Angstrom, 2*u.Angstrom)
p = models.Planar2D(3*u.Hz/u.Angstrom, 4*u.Hz/u.Angstrom, 1*u.Hz)
model = m + p
z = model(x, y)
res = fitter(model, x, y, z)
assert isinstance(res(x, y), np.ndarray)
assert all([res[i]._has_units for i in range(2)])
model = models.Gaussian2D() + models.Planar2D()
res = fitter(model, x, y, z)
assert isinstance(res(x, y), np.ndarray)
assert all([res[i]._has_units for i in range(2)])
# A case of a mixture of models with and without units
model = models.BlackBody(temperature=3000 * u.K) * models.Const1D(amplitude=1.0)
x = np.linspace(1, 3, 10000) * u.micron
with NumpyRNGContext(12345):
n = np.random.normal(3)
y = model(x)
res = fitter(model, x, y * (1 + n))
# The large rtol here is due to different results on linux and macosx, likely
# the model is ill-conditioned.
np.testing.assert_allclose(res.parameters, [3000, 2.1433621e+00, 2.647347e+00], rtol=0.4)
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.filterwarnings(r'ignore:Model is linear in parameters*')
@pytest.mark.parametrize('model', models_with_custom_names())
def test_fitting_custom_names(model):
""" Tests fitting of models with custom inputs and outsputs names."""
x = np.linspace(0, 10, 100) * u.s
y = model(x)
fitter = fitting.LevMarLSQFitter()
new_model = fitter(model, x, y)
for param_name in model.param_names:
assert_quantity_allclose(getattr(new_model, param_name).quantity,
getattr(model, param_name).quantity)
|
bd4e019e18d9e95083e2bb81e38174f863fdf781c0d984fe2a6fa1ac78efa8ef | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module tests fitting and model evaluation with various inputs
"""
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy.modeling import models
from astropy.modeling import fitting
from astropy.modeling.core import Model, FittableModel, Fittable1DModel
from astropy.modeling.parameters import Parameter
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
model1d_params = [
(models.Polynomial1D, [2]),
(models.Legendre1D, [2]),
(models.Chebyshev1D, [2]),
(models.Shift, [2]),
(models.Scale, [2])
]
model2d_params = [
(models.Polynomial2D, [2]),
(models.Legendre2D, [1, 2]),
(models.Chebyshev2D, [1, 2])
]
class TestInputType:
"""
This class tests that models accept numbers, lists and arrays.
Add new models to one of the lists above to test for this.
"""
def setup_class(self):
self.x = 5.3
self.y = 6.7
self.x1 = np.arange(1, 10, .1)
self.y1 = np.arange(1, 10, .1)
self.y2, self.x2 = np.mgrid[:10, :8]
@pytest.mark.parametrize(('model', 'params'), model1d_params)
def test_input1D(self, model, params):
m = model(*params)
m(self.x)
m(self.x1)
m(self.x2)
@pytest.mark.parametrize(('model', 'params'), model2d_params)
def test_input2D(self, model, params):
m = model(*params)
m(self.x, self.y)
m(self.x1, self.y1)
m(self.x2, self.y2)
class TestFitting:
"""Test various input options to fitting routines."""
def setup_class(self):
self.x1 = np.arange(10)
self.y, self.x = np.mgrid[:10, :10]
def test_linear_fitter_1set(self):
"""1 set 1D x, 1pset"""
expected = np.array([0, 1, 1, 1])
p1 = models.Polynomial1D(3)
p1.parameters = [0, 1, 1, 1]
y1 = p1(self.x1)
pfit = fitting.LinearLSQFitter()
model = pfit(p1, self.x1, y1)
assert_allclose(model.parameters, expected, atol=10 ** (-7))
def test_linear_fitter_Nset(self):
"""1 set 1D x, 2 sets 1D y, 2 param_sets"""
expected = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
p1 = models.Polynomial1D(3, n_models=2)
p1.parameters = [0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0]
params = {}
for i in range(4):
params[p1.param_names[i]] = [i, i]
p1 = models.Polynomial1D(3, model_set_axis=0, **params)
y1 = p1(self.x1, model_set_axis=False)
pfit = fitting.LinearLSQFitter()
model = pfit(p1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-7))
def test_linear_fitter_1dcheb(self):
"""1 pset, 1 set 1D x, 1 set 1D y, Chebyshev 1D polynomial"""
expected = np.array(
[[2817.2499999999995,
4226.6249999999991,
1680.7500000000009,
273.37499999999926]]).T
ch1 = models.Chebyshev1D(3)
ch1.parameters = [0, 1, 2, 3]
y1 = ch1(self.x1)
pfit = fitting.LinearLSQFitter()
model = pfit(ch1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-2))
def test_linear_fitter_1dlegend(self):
"""
1 pset, 1 set 1D x, 1 set 1D y, Legendre 1D polynomial
"""
expected = np.array(
[[1925.5000000000011,
3444.7500000000005,
1883.2500000000014,
364.4999999999996]]).T
leg1 = models.Legendre1D(3)
leg1.parameters = [1, 2, 3, 4]
y1 = leg1(self.x1)
pfit = fitting.LinearLSQFitter()
model = pfit(leg1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-12))
def test_linear_fitter_1set2d(self):
p2 = models.Polynomial2D(2)
p2.parameters = [0, 1, 2, 3, 4, 5]
expected = [0, 1, 2, 3, 4, 5]
z = p2(self.x, self.y)
pfit = fitting.LinearLSQFitter()
model = pfit(p2, self.x, self.y, z)
assert_allclose(model.parameters, expected, atol=10 ** (-12))
assert_allclose(model(self.x, self.y), z, atol=10 ** (-12))
def test_wrong_numpset(self):
"""
A ValueError is raised if a 1 data set (1d x, 1d y) is fit
with a model with multiple parameter sets.
"""
with pytest.raises(ValueError):
p1 = models.Polynomial1D(5)
y1 = p1(self.x1)
p1 = models.Polynomial1D(5, n_models=2)
pfit = fitting.LinearLSQFitter()
model = pfit(p1, self.x1, y1)
def test_wrong_pset(self):
"""A case of 1 set of x and multiple sets of y and parameters."""
expected = np.array([[1., 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]])
p1 = models.Polynomial1D(5, n_models=2)
params = {}
for i in range(6):
params[p1.param_names[i]] = [1, i]
p1 = models.Polynomial1D(5, model_set_axis=0, **params)
y1 = p1(self.x1, model_set_axis=False)
pfit = fitting.LinearLSQFitter()
model = pfit(p1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-7))
@pytest.mark.skipif('not HAS_SCIPY')
def test_nonlinear_lsqt_1set_1d(self):
"""1 set 1D x, 1 set 1D y, 1 pset NonLinearFitter"""
g1 = models.Gaussian1D(10, mean=3, stddev=.2)
y1 = g1(self.x1)
gfit = fitting.LevMarLSQFitter()
model = gfit(g1, self.x1, y1)
assert_allclose(model.parameters, [10, 3, .2])
@pytest.mark.skipif('not HAS_SCIPY')
def test_nonlinear_lsqt_Nset_1d(self):
"""1 set 1D x, 1 set 1D y, 2 param_sets, NonLinearFitter"""
with pytest.raises(ValueError):
g1 = models.Gaussian1D([10.2, 10], mean=[3, 3.2], stddev=[.23, .2],
n_models=2)
y1 = g1(self.x1, model_set_axis=False)
gfit = fitting.LevMarLSQFitter()
model = gfit(g1, self.x1, y1)
@pytest.mark.skipif('not HAS_SCIPY')
def test_nonlinear_lsqt_1set_2d(self):
"""1 set 2d x, 1set 2D y, 1 pset, NonLinearFitter"""
g2 = models.Gaussian2D(10, x_mean=3, y_mean=4, x_stddev=.3,
y_stddev=.2, theta=0)
z = g2(self.x, self.y)
gfit = fitting.LevMarLSQFitter()
model = gfit(g2, self.x, self.y, z)
assert_allclose(model.parameters, [10, 3, 4, .3, .2, 0])
@pytest.mark.skipif('not HAS_SCIPY')
def test_nonlinear_lsqt_Nset_2d(self):
"""1 set 2d x, 1set 2D y, 2 param_sets, NonLinearFitter"""
with pytest.raises(ValueError):
g2 = models.Gaussian2D([10, 10], [3, 3], [4, 4], x_stddev=[.3, .3],
y_stddev=[.2, .2], theta=[0, 0], n_models=2)
z = g2(self.x.flatten(), self.y.flatten())
gfit = fitting.LevMarLSQFitter()
model = gfit(g2, self.x, self.y, z)
class TestEvaluation:
"""
Test various input options to model evaluation
TestFitting actually covers evaluation of polynomials
"""
def setup_class(self):
self.x1 = np.arange(20)
self.y, self.x = np.mgrid[:10, :10]
def test_non_linear_NYset(self):
"""
This case covers:
N param sets , 1 set 1D x --> N 1D y data
"""
g1 = models.Gaussian1D([10, 10], [3, 3], [.2, .2], n_models=2)
y1 = g1(self.x1, model_set_axis=False)
assert np.all((y1[0, :] - y1[1, :]).nonzero() == np.array([]))
def test_non_linear_NXYset(self):
"""
This case covers: N param sets , N sets 1D x --> N N sets 1D y data
"""
g1 = models.Gaussian1D([10, 10], [3, 3], [.2, .2], n_models=2)
xx = np.array([self.x1, self.x1])
y1 = g1(xx)
assert_allclose(y1[:, 0], y1[:, 1], atol=10 ** (-12))
def test_p1_1set_1pset(self):
"""1 data set, 1 pset, Polynomial1D"""
p1 = models.Polynomial1D(4)
y1 = p1(self.x1)
assert y1.shape == (20,)
def test_p1_nset_npset(self):
"""N data sets, N param_sets, Polynomial1D"""
p1 = models.Polynomial1D(4, n_models=2)
y1 = p1(np.array([self.x1, self.x1]).T, model_set_axis=-1)
assert y1.shape == (20, 2)
assert_allclose(y1[0, :], y1[1, :], atol=10 ** (-12))
def test_p2_1set_1pset(self):
"""1 pset, 1 2D data set, Polynomial2D"""
p2 = models.Polynomial2D(5)
z = p2(self.x, self.y)
assert z.shape == (10, 10)
def test_p2_nset_npset(self):
"""N param_sets, N 2D data sets, Poly2d"""
p2 = models.Polynomial2D(5, n_models=2)
xx = np.array([self.x, self.x])
yy = np.array([self.y, self.y])
z = p2(xx, yy)
assert z.shape == (2, 10, 10)
def test_nset_domain(self):
"""
Test model set with negative model_set_axis.
In this case model_set_axis=-1 is identical to model_set_axis=1.
"""
xx = np.array([self.x1, self.x1]).T
xx[0, 0] = 100
xx[1, 0] = 100
xx[2, 0] = 99
p1 = models.Polynomial1D(5, c0=[1, 2], c1=[3, 4], n_models=2)
yy = p1(xx, model_set_axis=-1)
assert_allclose(xx.shape, yy.shape)
yy1 = p1(xx, model_set_axis=1)
assert_allclose(yy, yy1)
#x1 = xx[:, 0]
#x2 = xx[:, 1]
#p1 = models.Polynomial1D(5)
#assert_allclose(p1(x1), yy[0, :], atol=10 ** (-12))
#p1 = models.Polynomial1D(5)
#assert_allclose(p1(x2), yy[1, :], atol=10 ** (-12))
def test_evaluate_gauss2d(self):
cov = np.array([[1., 0.8], [0.8, 3]])
g = models.Gaussian2D(1., 5., 4., cov_matrix=cov)
y, x = np.mgrid[:10, :10]
g(x, y)
class TModel_1_1(Fittable1DModel):
p1 = Parameter()
p2 = Parameter()
@staticmethod
def evaluate(x, p1, p2):
return x + p1 + p2
class TestSingleInputSingleOutputSingleModel:
"""
A suite of tests to check various cases of parameter and input combinations
on models with n_input = n_output = 1 on a toy model with n_models=1.
Many of these tests mirror test cases in
``astropy.modeling.tests.test_parameters.TestParameterInitialization``,
except that this tests how different parameter arrangements interact with
different types of model inputs.
"""
def test_scalar_parameters_scalar_input(self):
"""
Scalar parameters with a scalar input should return a scalar.
"""
t = TModel_1_1(1, 10)
y = t(100)
assert isinstance(y, float)
assert np.ndim(y) == 0
assert y == 111
def test_scalar_parameters_1d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_1(1, 10)
y = t(np.arange(5) * 100)
assert isinstance(y, np.ndarray)
assert np.shape(y) == (5,)
assert np.all(y == [11, 111, 211, 311, 411])
def test_scalar_parameters_2d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_1(1, 10)
y = t(np.arange(6).reshape(2, 3) * 100)
assert isinstance(y, np.ndarray)
assert np.shape(y) == (2, 3)
assert np.all(y == [[11, 111, 211],
[311, 411, 511]])
def test_scalar_parameters_3d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_1(1, 10)
y = t(np.arange(12).reshape(2, 3, 2) * 100)
assert isinstance(y, np.ndarray)
assert np.shape(y) == (2, 3, 2)
assert np.all(y == [[[11, 111], [211, 311], [411, 511]],
[[611, 711], [811, 911], [1011, 1111]]])
def test_1d_array_parameters_scalar_input(self):
"""
Array parameters should all be broadcastable with each other, and with
a scalar input the output should be broadcast to the maximum dimensions
of the parameters.
"""
t = TModel_1_1([1, 2], [10, 20])
y = t(100)
assert isinstance(y, np.ndarray)
assert np.shape(y) == (2,)
assert np.all(y == [111, 122])
def test_1d_array_parameters_1d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_1([1, 2], [10, 20])
y1 = t([100, 200])
assert np.shape(y1) == (2,)
assert np.all(y1 == [111, 222])
y2 = t([[100], [200]])
assert np.shape(y2) == (2, 2)
assert np.all(y2 == [[111, 122], [211, 222]])
with pytest.raises(ValueError):
# Doesn't broadcast
y3 = t([100, 200, 300])
def test_2d_array_parameters_2d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_1([[1, 2], [3, 4]], [[10, 20], [30, 40]])
y1 = t([[100, 200], [300, 400]])
assert np.shape(y1) == (2, 2)
assert np.all(y1 == [[111, 222], [333, 444]])
y2 = t([[[[100]], [[200]]], [[[300]], [[400]]]])
assert np.shape(y2) == (2, 2, 2, 2)
assert np.all(y2 == [[[[111, 122], [133, 144]],
[[211, 222], [233, 244]]],
[[[311, 322], [333, 344]],
[[411, 422], [433, 444]]]])
with pytest.raises(ValueError):
# Doesn't broadcast
y3 = t([[100, 200, 300], [400, 500, 600]])
def test_mixed_array_parameters_1d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_1([[[0.01, 0.02, 0.03], [0.04, 0.05, 0.06]],
[[0.07, 0.08, 0.09], [0.10, 0.11, 0.12]]],
[1, 2, 3])
y1 = t([10, 20, 30])
assert np.shape(y1) == (2, 2, 3)
assert_allclose(y1, [[[11.01, 22.02, 33.03], [11.04, 22.05, 33.06]],
[[11.07, 22.08, 33.09], [11.10, 22.11, 33.12]]])
y2 = t([[[[10]]], [[[20]]], [[[30]]]])
assert np.shape(y2) == (3, 2, 2, 3)
assert_allclose(y2, [[[[11.01, 12.02, 13.03],
[11.04, 12.05, 13.06]],
[[11.07, 12.08, 13.09],
[11.10, 12.11, 13.12]]],
[[[21.01, 22.02, 23.03],
[21.04, 22.05, 23.06]],
[[21.07, 22.08, 23.09],
[21.10, 22.11, 23.12]]],
[[[31.01, 32.02, 33.03],
[31.04, 32.05, 33.06]],
[[31.07, 32.08, 33.09],
[31.10, 32.11, 33.12]]]])
class TestSingleInputSingleOutputTwoModel:
"""
A suite of tests to check various cases of parameter and input combinations
on models with n_input = n_output = 1 on a toy model with n_models=2.
Many of these tests mirror test cases in
``astropy.modeling.tests.test_parameters.TestParameterInitialization``,
except that this tests how different parameter arrangements interact with
different types of model inputs.
With n_models=2 all outputs should have a first dimension of size 2 (unless
defined with model_set_axis != 0).
"""
def test_scalar_parameters_scalar_input(self):
"""
Scalar parameters with a scalar input should return a 1-D array with
size equal to the number of models.
"""
t = TModel_1_1([1, 2], [10, 20], n_models=2)
y = t(100)
assert np.shape(y) == (2,)
assert np.all(y == [111, 122])
def test_scalar_parameters_1d_array_input(self):
"""
The dimension of the input should match the number of models unless
model_set_axis=False is given, in which case the input is copied across
all models.
"""
t = TModel_1_1([1, 2], [10, 20], n_models=2)
with pytest.raises(ValueError):
y = t(np.arange(5) * 100)
y1 = t([100, 200])
assert np.shape(y1) == (2,)
assert np.all(y1 == [111, 222])
y2 = t([100, 200], model_set_axis=False)
# In this case the value [100, 200, 300] should be evaluated on each
# model rather than evaluating the first model with 100 and the second
# model with 200
assert np.shape(y2) == (2, 2)
assert np.all(y2 == [[111, 211], [122, 222]])
y3 = t([100, 200, 300], model_set_axis=False)
assert np.shape(y3) == (2, 3)
assert np.all(y3 == [[111, 211, 311], [122, 222, 322]])
def test_scalar_parameters_2d_array_input(self):
"""
The dimension of the input should match the number of models unless
model_set_axis=False is given, in which case the input is copied across
all models.
"""
t = TModel_1_1([1, 2], [10, 20], n_models=2)
y1 = t(np.arange(6).reshape(2, 3) * 100)
assert np.shape(y1) == (2, 3)
assert np.all(y1 == [[11, 111, 211],
[322, 422, 522]])
y2 = t(np.arange(6).reshape(2, 3) * 100, model_set_axis=False)
assert np.shape(y2) == (2, 2, 3)
assert np.all(y2 == [[[11, 111, 211], [311, 411, 511]],
[[22, 122, 222], [322, 422, 522]]])
def test_scalar_parameters_3d_array_input(self):
"""
The dimension of the input should match the number of models unless
model_set_axis=False is given, in which case the input is copied across
all models.
"""
t = TModel_1_1([1, 2], [10, 20], n_models=2)
data = np.arange(12).reshape(2, 3, 2) * 100
y1 = t(data)
assert np.shape(y1) == (2, 3, 2)
assert np.all(y1 == [[[11, 111], [211, 311], [411, 511]],
[[622, 722], [822, 922], [1022, 1122]]])
y2 = t(data, model_set_axis=False)
assert np.shape(y2) == (2, 2, 3, 2)
assert np.all(y2 == np.array([data + 11, data + 22]))
def test_1d_array_parameters_scalar_input(self):
"""
Array parameters should all be broadcastable with each other, and with
a scalar input the output should be broadcast to the maximum dimensions
of the parameters.
"""
t = TModel_1_1([[1, 2, 3], [4, 5, 6]],
[[10, 20, 30], [40, 50, 60]], n_models=2)
y = t(100)
assert np.shape(y) == (2, 3)
assert np.all(y == [[111, 122, 133], [144, 155, 166]])
def test_1d_array_parameters_1d_array_input(self):
"""
When the input is an array, if model_set_axis=False then it must
broadcast with the shapes of the parameters (excluding the
model_set_axis).
Otherwise all dimensions must be broadcastable.
"""
t = TModel_1_1([[1, 2, 3], [4, 5, 6]],
[[10, 20, 30], [40, 50, 60]], n_models=2)
with pytest.raises(ValueError):
y1 = t([100, 200, 300])
y1 = t([100, 200])
assert np.shape(y1) == (2, 3)
assert np.all(y1 == [[111, 122, 133], [244, 255, 266]])
with pytest.raises(ValueError):
# Doesn't broadcast with the shape of the parameters, (3,)
y2 = t([100, 200], model_set_axis=False)
y2 = t([100, 200, 300], model_set_axis=False)
assert np.shape(y2) == (2, 3)
assert np.all(y2 == [[111, 222, 333],
[144, 255, 366]])
def test_2d_array_parameters_2d_array_input(self):
t = TModel_1_1([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],
[[[10, 20], [30, 40]], [[50, 60], [70, 80]]],
n_models=2)
y1 = t([[100, 200], [300, 400]])
assert np.shape(y1) == (2, 2, 2)
assert np.all(y1 == [[[111, 222], [133, 244]],
[[355, 466], [377, 488]]])
with pytest.raises(ValueError):
y2 = t([[100, 200, 300], [400, 500, 600]])
y2 = t([[[100, 200], [300, 400]], [[500, 600], [700, 800]]])
assert np.shape(y2) == (2, 2, 2)
assert np.all(y2 == [[[111, 222], [333, 444]],
[[555, 666], [777, 888]]])
def test_mixed_array_parameters_1d_array_input(self):
t = TModel_1_1([[[0.01, 0.02, 0.03], [0.04, 0.05, 0.06]],
[[0.07, 0.08, 0.09], [0.10, 0.11, 0.12]]],
[[1, 2, 3], [4, 5, 6]], n_models=2)
with pytest.raises(ValueError):
y = t([10, 20, 30])
y = t([10, 20, 30], model_set_axis=False)
assert np.shape(y) == (2, 2, 3)
assert_allclose(y, [[[11.01, 22.02, 33.03], [11.04, 22.05, 33.06]],
[[14.07, 25.08, 36.09], [14.10, 25.11, 36.12]]])
class TModel_1_2(FittableModel):
n_inputs =1
n_outputs = 2
p1 = Parameter()
p2 = Parameter()
p3 = Parameter()
@staticmethod
def evaluate(x, p1, p2, p3):
return (x + p1 + p2, x + p1 + p2 + p3)
class TestSingleInputDoubleOutputSingleModel:
"""
A suite of tests to check various cases of parameter and input combinations
on models with n_input = 1 but n_output = 2 on a toy model with n_models=1.
As of writing there are not enough controls to adjust how outputs from such
a model should be formatted (currently the shapes of outputs are assumed to
be directly associated with the shapes of corresponding inputs when
n_inputs == n_outputs). For now, the approach taken for cases like this is
to assume all outputs should have the same format.
"""
def test_scalar_parameters_scalar_input(self):
"""
Scalar parameters with a scalar input should return a scalar.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(100)
assert isinstance(y, float)
assert isinstance(z, float)
assert np.ndim(y) == np.ndim(z) == 0
assert y == 111
assert z == 1111
def test_scalar_parameters_1d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(np.arange(5) * 100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (5,)
assert np.all(y == [11, 111, 211, 311, 411])
assert np.all(z == (y + 1000))
def test_scalar_parameters_2d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(np.arange(6).reshape(2, 3) * 100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (2, 3)
assert np.all(y == [[11, 111, 211],
[311, 411, 511]])
assert np.all(z == (y + 1000))
def test_scalar_parameters_3d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(np.arange(12).reshape(2, 3, 2) * 100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (2, 3, 2)
assert np.all(y == [[[11, 111], [211, 311], [411, 511]],
[[611, 711], [811, 911], [1011, 1111]]])
assert np.all(z == (y + 1000))
def test_1d_array_parameters_scalar_input(self):
"""
Array parameters should all be broadcastable with each other, and with
a scalar input the output should be broadcast to the maximum dimensions
of the parameters.
"""
t = TModel_1_2([1, 2], [10, 20], [1000, 2000])
y, z = t(100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (2,)
assert np.all(y == [111, 122])
assert np.all(z == [1111, 2122])
def test_1d_array_parameters_1d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_2([1, 2], [10, 20], [1000, 2000])
y1, z1 = t([100, 200])
assert np.shape(y1) == np.shape(z1) == (2,)
assert np.all(y1 == [111, 222])
assert np.all(z1 == [1111, 2222])
y2, z2 = t([[100], [200]])
assert np.shape(y2) == np.shape(z2) == (2, 2)
assert np.all(y2 == [[111, 122], [211, 222]])
assert np.all(z2 == [[1111, 2122], [1211, 2222]])
with pytest.raises(ValueError):
# Doesn't broadcast
y3, z3 = t([100, 200, 300])
def test_2d_array_parameters_2d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_2([[1, 2], [3, 4]], [[10, 20], [30, 40]],
[[1000, 2000], [3000, 4000]])
y1, z1 = t([[100, 200], [300, 400]])
assert np.shape(y1) == np.shape(z1) == (2, 2)
assert np.all(y1 == [[111, 222], [333, 444]])
assert np.all(z1 == [[1111, 2222], [3333, 4444]])
y2, z2 = t([[[[100]], [[200]]], [[[300]], [[400]]]])
assert np.shape(y2) == np.shape(z2) == (2, 2, 2, 2)
assert np.all(y2 == [[[[111, 122], [133, 144]],
[[211, 222], [233, 244]]],
[[[311, 322], [333, 344]],
[[411, 422], [433, 444]]]])
assert np.all(z2 == [[[[1111, 2122], [3133, 4144]],
[[1211, 2222], [3233, 4244]]],
[[[1311, 2322], [3333, 4344]],
[[1411, 2422], [3433, 4444]]]])
with pytest.raises(ValueError):
# Doesn't broadcast
y3, z3 = t([[100, 200, 300], [400, 500, 600]])
def test_mixed_array_parameters_1d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_2([[[0.01, 0.02, 0.03], [0.04, 0.05, 0.06]],
[[0.07, 0.08, 0.09], [0.10, 0.11, 0.12]]],
[1, 2, 3], [100, 200, 300])
y1, z1 = t([10, 20, 30])
assert np.shape(y1) == np.shape(z1) == (2, 2, 3)
assert_allclose(y1, [[[11.01, 22.02, 33.03], [11.04, 22.05, 33.06]],
[[11.07, 22.08, 33.09], [11.10, 22.11, 33.12]]])
assert_allclose(z1, [[[111.01, 222.02, 333.03],
[111.04, 222.05, 333.06]],
[[111.07, 222.08, 333.09],
[111.10, 222.11, 333.12]]])
y2, z2 = t([[[[10]]], [[[20]]], [[[30]]]])
assert np.shape(y2) == np.shape(z2) == (3, 2, 2, 3)
assert_allclose(y2, [[[[11.01, 12.02, 13.03],
[11.04, 12.05, 13.06]],
[[11.07, 12.08, 13.09],
[11.10, 12.11, 13.12]]],
[[[21.01, 22.02, 23.03],
[21.04, 22.05, 23.06]],
[[21.07, 22.08, 23.09],
[21.10, 22.11, 23.12]]],
[[[31.01, 32.02, 33.03],
[31.04, 32.05, 33.06]],
[[31.07, 32.08, 33.09],
[31.10, 32.11, 33.12]]]])
assert_allclose(z2, [[[[111.01, 212.02, 313.03],
[111.04, 212.05, 313.06]],
[[111.07, 212.08, 313.09],
[111.10, 212.11, 313.12]]],
[[[121.01, 222.02, 323.03],
[121.04, 222.05, 323.06]],
[[121.07, 222.08, 323.09],
[121.10, 222.11, 323.12]]],
[[[131.01, 232.02, 333.03],
[131.04, 232.05, 333.06]],
[[131.07, 232.08, 333.09],
[131.10, 232.11, 333.12]]]])
# test broadcasting rules
broadcast_models = [
{
'model': models.Identity(2),
'inputs': [0, [1, 1]],
'outputs': [0, [1, 1]]
},
{
'model': models.Identity(2),
'inputs': [[1, 1], 0],
'outputs': [[1, 1], 0]
},
{
'model': models.Mapping((0, 1)),
'inputs': [0, [1, 1]],
'outputs': [0, [1, 1]]
},
{
'model': models.Mapping((1, 0)),
'inputs': [0, [1, 1]],
'outputs': [[1, 1], 0]
},
{
'model': models.Mapping((1, 0), n_inputs=3),
'inputs': [0, [1, 1], 2],
'outputs': [[1, 1], 0]
},
{
'model': models.Mapping((0, 1, 0)),
'inputs': [0, [1, 1]],
'outputs': [0, [1, 1], 0]
},
{
'model': models.Mapping((0, 1, 1)),
'inputs': [0, [1, 1]],
'outputs': [0, [1, 1], [1, 1]]
},
{
'model': models.Polynomial2D(1, c0_0=1),
'inputs': [0, [1, 1]],
'outputs': [1, 1]
},
{
'model': models.Polynomial2D(1, c0_0=1),
'inputs': [0, 1],
'outputs': 1
},
{
'model': models.Gaussian2D(1, 1, 2, 1, 1.2),
'inputs': [0, [1, 1]],
'outputs': [0.42860385, 0.42860385]
},
{
'model': models.Gaussian2D(1, 1, 2, 1, 1.2),
'inputs': [0, 1],
'outputs': 0.428603846153
},
{
'model': models.Polynomial2D(1, c0_0=1) & models.Polynomial2D(1, c0_0=2),
'inputs': [1, 1, 1, 1],
'outputs': (1, 2)
},
{
'model': models.Polynomial2D(1, c0_0=1) & models.Polynomial2D(1, c0_0=2),
'inputs': [1, 1, [1, 1], [1, 1]],
'outputs': (1, [2, 2])
},
{
'model': models.math.MultiplyUfunc(),
'inputs': [np.array([np.linspace(0, 1, 5)]).T, np.arange(2)],
'outputs': np.array([[0., 0.],
[0., 0.25],
[0., 0.5],
[0., 0.75],
[0., 1.]])
}
]
@pytest.mark.parametrize('model', broadcast_models)
def test_mixed_input(model):
result = model['model'](*model['inputs'])
if np.isscalar(result):
assert_allclose(result, model['outputs'])
else:
for i in range(len(result)):
assert_allclose(result[i], model['outputs'][i])
def test_more_outputs():
class M(FittableModel):
standard_broadcasting = False
n_inputs = 2
n_outputs = 3
a = Parameter()
def evaluate(self, x, y, a):
return a*x, a-x, a+y
def __call__(self, *args, **kwargs):
inputs, _ = super().prepare_inputs(*args, **kwargs)
outputs = self.evaluate(*inputs, *self.parameters)
output_shapes = [out.shape for out in outputs]
output_shapes = [() if shape == (1,) else shape for shape in output_shapes]
return self.prepare_outputs((tuple(output_shapes),), *outputs, **kwargs)
c = M(1)
result = c([1, 1], 1)
expected = [[1., 1.], [0., 0.], 2.]
for r, e in zip(result, expected):
assert_allclose(r, e)
c = M(1)
result = c(1, [1, 1])
expected = [1., 0., [2., 2.]]
for r, e in zip(result, expected):
assert_allclose(r, e)
class TInputFormatter(Model):
"""
A toy model to test input/output formatting.
"""
n_inputs = 2
n_outputs = 2
outputs = ('x', 'y')
@staticmethod
def evaluate(x, y):
return x, y
def test_format_input_scalars():
model = TInputFormatter()
result = model(1, 2)
assert result == (1, 2)
def test_format_input_arrays():
model = TInputFormatter()
result = model([1, 1], [2, 2])
assert_allclose(result, (np.array([1, 1]), np.array([2, 2])))
def test_format_input_arrays_transposed():
model = TInputFormatter()
input = np.array([[1, 1]]).T, np.array([[2, 2]]).T
result = model(*input)
assert_allclose(result, input)
@pytest.mark.parametrize('model',
[models.Gaussian2D(), models.Polynomial2D(1,),
models.Pix2Sky_TAN(), models.Tabular2D(lookup_table=np.ones((4,5)))])
@pytest.mark.skipif('not HAS_SCIPY')
def test_call_keyword_args_2(model):
"""
Test calling a model with positional, keywrd and a mixture of both arguments.
"""
positional = model(1, 2)
assert_allclose(positional, model(x=1, y=2))
assert_allclose(positional, model(1, y=2))
model.inputs = ('r', 't')
assert_allclose(positional, model(r=1, t=2))
assert_allclose(positional, model(1, t=2))
assert_allclose(positional, model(1, 2))
with pytest.raises(ValueError):
model(1, 2, 3)
with pytest.raises(ValueError):
model(1)
with pytest.raises(ValueError):
model(1, 2, t=12, r=3)
@pytest.mark.parametrize('model',
[models.Gaussian1D(), models.Polynomial1D(1,),
models.Tabular1D(lookup_table=np.ones((5,))),
models.Rotation2D(), models.Pix2Sky_TAN()])
@pytest.mark.skipif('not HAS_SCIPY')
def test_call_keyword_args_1(model):
"""
Test calling a model with positional, keywrd and a mixture of both arguments.
"""
positional = model(1)
assert_allclose(positional, model(x=1))
model.inputs = ('r',)
assert_allclose(positional, model(r=1))
with pytest.raises(ValueError):
model(1, 2, 3)
with pytest.raises(ValueError):
model()
with pytest.raises(ValueError):
model(1, 2, t=12, r=3)
@pytest.mark.parametrize('model',
[models.Gaussian2D() | models.Polynomial1D(1,),
models.Gaussian1D() & models.Polynomial1D(1,),
models.Gaussian2D() + models.Polynomial2D(1,),
models.Gaussian2D() - models.Polynomial2D(1,),
models.Gaussian2D() * models.Polynomial2D(1,),
models.Identity(2) | models.Polynomial2D(1),
models.Mapping((1,)) | models.Polynomial1D(1)])
def test_call_keyword_args_1(model):
"""
Test calling a model with positional, keywrd and a mixture of both arguments.
"""
positional = model(1, 2)
model.inputs = ('r', 't')
assert_allclose(positional, model(r=1, t = 2))
assert_allclose(positional, model(1, t=2))
with pytest.raises(ValueError):
model(1, 2, 3)
with pytest.raises(ValueError):
model()
with pytest.raises(ValueError):
model(1, 2, t=12, r=3)
@pytest.mark.parametrize('model',
[models.Identity(2), models.Mapping((0, 1)),
models.Mapping((1,))])
def test_call_keyword_mappings(model):
"""
Test calling a model with positional, keywrd and a mixture of both arguments.
"""
positional = model(1, 2)
assert_allclose(positional, model(x0=1, x1=2))
assert_allclose(positional, model(1, x1=2))
# We take a copy before modifying the model since otherwise this changes
# the instance used in the parametrize call and affects future test runs.
model = model.copy()
model.inputs = ('r', 't')
assert_allclose(positional, model(r=1, t=2))
assert_allclose(positional, model(1, t=2))
assert_allclose(positional, model(1, 2))
with pytest.raises(ValueError):
model(1, 2, 3)
with pytest.raises(ValueError):
model(1)
with pytest.raises(ValueError):
model(1, 2, t=12, r=3)
|
7374892302f3ed3075b08687c73b9da49b0f4d9aac08b7d3a1633d9cd2c9e6a2 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests that relate to using quantities/units on parameters of models.
"""
# pylint: disable=invalid-name, no-member
import numpy as np
import pytest
from astropy.modeling.core import Fittable1DModel, InputParameterError
from astropy.modeling.parameters import Parameter, ParameterDefinitionError
from astropy.modeling.models import (Gaussian1D, Pix2Sky_TAN, RotateNative2Celestial,
Rotation2D)
from astropy import units as u
from astropy.units import UnitsError
from astropy.tests.helper import assert_quantity_allclose
from astropy import coordinates as coord
class BaseTestModel(Fittable1DModel):
@staticmethod
def evaluate(x, a):
return x
def test_parameter_quantity():
"""
Basic tests for initializing general models (that do not require units)
with parameters that have units attached.
"""
g = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m)
assert g.amplitude.value == 1.0
assert g.amplitude.unit is u.J
assert g.mean.value == 1.0
assert g.mean.unit is u.m
assert g.stddev.value == 0.1
assert g.stddev.unit is u.m
def test_parameter_set_quantity():
"""
Make sure that parameters that start off as quantities can be set to any
other quantity, regardless of whether the units of the new quantity are
compatible with the original ones.
We basically leave it up to the evaluate method to raise errors if there
are issues with incompatible units, and we don't check for consistency
at the parameter level.
"""
g = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m)
# Try equivalent units
g.amplitude = 4 * u.kJ
assert_quantity_allclose(g.amplitude, 4 * u.kJ)
g.mean = 3 * u.km
assert_quantity_allclose(g.mean, 3 * u.km)
g.stddev = 2 * u.mm
assert_quantity_allclose(g.stddev, 2 * u.mm)
# Try different units
g.amplitude = 2 * u.s
assert_quantity_allclose(g.amplitude, 2 * u.s)
g.mean = 2 * u.Jy
assert_quantity_allclose(g.mean, 2 * u.Jy)
def test_parameter_lose_units():
"""
Check that parameters that have been set to a quantity that are then set to
a value with no units raise an exception. We do this because setting a
parameter to a value with no units is ambiguous if units were set before:
if a parameter is 1 * u.Jy and the parameter is then set to 4, does this mean
2 without units, or 2 * u.Jy?
"""
g = Gaussian1D(1 * u.Jy, 3, 0.1)
with pytest.raises(UnitsError) as exc:
g.amplitude = 2
assert exc.value.args[0] == ("The 'amplitude' parameter should be given as "
"a Quantity because it was originally "
"initialized as a Quantity")
def test_parameter_add_units():
"""
On the other hand, if starting from a parameter with no units, we should be
able to add units since this is unambiguous.
"""
g = Gaussian1D(1, 3, 0.1)
g.amplitude = 2 * u.Jy
assert_quantity_allclose(g.amplitude, 2 * u.Jy)
def test_parameter_change_unit():
"""
Test that changing the unit on a parameter does not work. This is an
ambiguous operation because it's not clear if it means that the value should
be converted or if the unit should be changed without conversion.
"""
g = Gaussian1D(1, 1 * u.m, 0.1 * u.m)
# Setting a unit on a unitless parameter should not work
with pytest.raises(ValueError) as exc:
g.amplitude.unit = u.Jy
assert exc.value.args[0] == ("Cannot attach units to parameters that were "
"not initially specified with units")
# But changing to another unit should not, even if it is an equivalent unit
with pytest.raises(ValueError) as exc:
g.mean.unit = u.cm
assert exc.value.args[0] == ("Cannot change the unit attribute directly, "
"instead change the parameter to a new quantity")
def test_parameter_set_value():
"""
Test that changing the value on a parameter works as expected.
"""
g = Gaussian1D(1 * u.Jy, 1 * u.m, 0.1 * u.m)
# To set a parameter to a quantity, we simply do
g.amplitude = 2 * u.Jy
# If we try setting the value, we need to pass a non-quantity value
# TODO: determine whether this is the desired behavior?
g.amplitude.value = 4
assert_quantity_allclose(g.amplitude, 4 * u.Jy)
assert g.amplitude.value == 4
assert g.amplitude.unit is u.Jy
# If we try setting it to a Quantity, we raise an error
with pytest.raises(TypeError) as exc:
g.amplitude.value = 3 * u.Jy
assert exc.value.args[0] == \
("The .value property on parameters should be set"
" to unitless values, not Quantity objects. To set"
"a parameter to a quantity simply set the "
"parameter directly without using .value")
def test_parameter_quantity_property():
"""
Test that the quantity property of Parameters behaves as expected
"""
# Since parameters have a .value and .unit parameter that return just the
# value and unit respectively, we also have a .quantity parameter that
# returns a Quantity instance.
g = Gaussian1D(1 * u.Jy, 1 * u.m, 0.1 * u.m)
assert_quantity_allclose(g.amplitude.quantity, 1 * u.Jy)
# Setting a parameter to a quantity changes the value and the default unit
g.amplitude.quantity = 5 * u.mJy
assert g.amplitude.value == 5
assert g.amplitude.unit is u.mJy
# And we can also set the parameter to a value with different units
g.amplitude.quantity = 4 * u.s
assert g.amplitude.value == 4
assert g.amplitude.unit is u.s
# But not to a value without units
with pytest.raises(TypeError) as exc:
g.amplitude.quantity = 3
assert exc.value.args[0] == "The .quantity attribute should be set to a Quantity object"
def test_parameter_default_units_match():
# If the unit and default quantity units are different, raise an error
with pytest.raises(ParameterDefinitionError) as exc:
class TestC(Fittable1DModel):
a = Parameter(default=1.0 * u.m, unit=u.Jy)
assert exc.value.args[0] == ("parameter default 1.0 m does not have units "
"equivalent to the required unit Jy")
@pytest.mark.parametrize(('unit', 'default'), ((u.m, 1.0), (None, 1 * u.m)))
def test_parameter_defaults(unit, default):
"""
Test that default quantities are correctly taken into account
"""
class TestModel(BaseTestModel):
a = Parameter(default=default, unit=unit)
# TODO: decide whether the default property should return a value or
# a quantity?
# The default unit and value should be set on the class
assert TestModel.a.unit == u.m
assert TestModel.a.default == 1.0
# Check that the default unit and value are also set on a class instance
m = TestModel()
assert m.a.unit == u.m
assert m.a.default == m.a.value == 1.0
# If the parameter is set to a different value, the default is still the
# internal default
m = TestModel(2.0 * u.m)
assert m.a.unit == u.m
assert m.a.value == 2.0
assert m.a.default == 1.0
# Instantiate with a different, but compatible unit
m = TestModel(2.0 * u.pc)
assert m.a.unit == u.pc
assert m.a.value == 2.0
# The default is still in the original units
# TODO: but how do we know what those units are if we don't return a
# quantity?
assert m.a.default == 1.0
# Initialize with a completely different unit
m = TestModel(2.0 * u.Jy)
assert m.a.unit == u.Jy
assert m.a.value == 2.0
# TODO: this illustrates why the default doesn't make sense anymore
assert m.a.default == 1.0
# Instantiating with different units works, and just replaces the original unit
with pytest.raises(InputParameterError) as exc:
TestModel(1.0)
assert exc.value.args[0] == ("TestModel.__init__() requires a "
"Quantity for parameter 'a'")
def test_parameter_quantity_arithmetic():
"""
Test that arithmetic operations with properties that have units return the
appropriate Quantities.
"""
g = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m)
# Addition should work if units are compatible
assert g.mean + (1 * u.m) == 2 * u.m
assert (1 * u.m) + g.mean == 2 * u.m
# Multiplication by a scalar should also preserve the quantity-ness
assert g.mean * 2 == (2 * u.m)
assert 2 * g.mean == (2 * u.m)
# Multiplication by a quantity should result in units being multiplied
assert g.mean * (2 * u.m) == (2 * (u.m ** 2))
assert (2 * u.m) * g.mean == (2 * (u.m ** 2))
# Negation should work properly too
assert -g.mean == (-1 * u.m)
assert abs(-g.mean) == g.mean
# However, addition of a quantity + scalar should not work
with pytest.raises(UnitsError) as exc:
g.mean + 1
assert exc.value.args[0] == ("Can only apply 'add' function to "
"dimensionless quantities when other argument "
"is not a quantity (unless the latter is all "
"zero/infinity/nan)")
with pytest.raises(UnitsError) as exc:
1 + g.mean
assert exc.value.args[0] == ("Can only apply 'add' function to "
"dimensionless quantities when other argument "
"is not a quantity (unless the latter is all "
"zero/infinity/nan)")
def test_parameter_quantity_comparison():
"""
Basic test of comparison operations on properties with units.
"""
g = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m)
# Essentially here we are checking that parameters behave like Quantity
assert g.mean == 1 * u.m
assert 1 * u.m == g.mean
assert g.mean != 1
assert 1 != g.mean
assert g.mean < 2 * u.m
assert 2 * u.m > g.mean
with pytest.raises(UnitsError) as exc:
g.mean < 2
assert exc.value.args[0] == ("Can only apply 'less' function to "
"dimensionless quantities when other argument "
"is not a quantity (unless the latter is all "
"zero/infinity/nan)")
with pytest.raises(UnitsError) as exc:
2 > g.mean
assert exc.value.args[0] == ("Can only apply 'less' function to "
"dimensionless quantities when other argument "
"is not a quantity (unless the latter is all "
"zero/infinity/nan)")
g = Gaussian1D([1, 2] * u.J, [1, 2] * u.m, [0.1, 0.2] * u.m)
assert np.all(g.mean == [1, 2] * u.m)
assert np.all([1, 2] * u.m == g.mean)
assert np.all(g.mean != [1, 2])
assert np.all([1, 2] != g.mean)
with pytest.raises(UnitsError) as exc:
g.mean < [3, 4]
assert exc.value.args[0] == ("Can only apply 'less' function to "
"dimensionless quantities when other argument "
"is not a quantity (unless the latter is all "
"zero/infinity/nan)")
with pytest.raises(UnitsError) as exc:
[3, 4] > g.mean
assert exc.value.args[0] == ("Can only apply 'less' function to "
"dimensionless quantities when other argument "
"is not a quantity (unless the latter is all "
"zero/infinity/nan)")
def test_parameters_compound_models():
tan = Pix2Sky_TAN()
sky_coords = coord.SkyCoord(ra=5.6, dec=-72, unit=u.deg)
lon_pole = 180 * u.deg
n2c = RotateNative2Celestial(sky_coords.ra, sky_coords.dec, lon_pole)
rot = Rotation2D(23)
m = rot | n2c
|
4695b412d6e02a065487268bf4390a3d755bbbc90800a3b056d3cbc64e1d7082 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for polynomial models."""
# pylint: disable=invalid-name
import os
import warnings
from itertools import product
import pytest
import numpy as np
import unittest.mock as mk
from numpy.testing import assert_allclose
from astropy.modeling import fitting
from astropy import wcs
from astropy.io import fits
from astropy.modeling.polynomial import (
Chebyshev1D, Hermite1D, Legendre1D, Polynomial1D,
Chebyshev2D, Hermite2D, Legendre2D, Polynomial2D, SIP,
PolynomialBase, OrthoPolynomialBase)
from astropy.modeling.functional_models import Linear1D
from astropy.modeling.mappings import Identity
from astropy.utils.data import get_pkg_data_filename
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.compat.optional_deps import HAS_SCIPY # noqa
linear1d = {
Chebyshev1D: {
'args': (3,),
'kwargs': {'domain': [1, 10]},
'parameters': {'c0': 1.2, 'c1': 2, 'c2': 2.3, 'c3': 0.2},
'constraints': {'fixed': {'c0': True}}
},
Hermite1D: {
'args': (3,),
'kwargs': {'domain': [1, 10]},
'parameters': {'c0': 1.2, 'c1': 2, 'c2': 2.3, 'c3': 0.2},
'constraints': {'fixed': {'c0': True}}
},
Legendre1D: {
'args': (3,),
'kwargs': {'domain': [1, 10]},
'parameters': {'c0': 1.2, 'c1': 2, 'c2': 2.3, 'c3': 0.2},
'constraints': {'fixed': {'c0': True}}
},
Polynomial1D: {
'args': (3,),
'kwargs': {'domain': [1, 10]},
'parameters': {'c0': 1.2, 'c1': 2, 'c2': 2.3, 'c3': 0.2},
'constraints': {'fixed': {'c0': True}}
},
Linear1D: {
'args': (),
'kwargs': {},
'parameters': {'intercept': 1.2, 'slope': 23.1},
'constraints': {'fixed': {'intercept': True}}
}
}
linear2d = {
Chebyshev2D: {
'args': (1, 1),
'kwargs': {'x_domain': [0, 99], 'y_domain': [0, 82]},
'parameters': {'c0_0': 1.2, 'c1_0': 2, 'c0_1': 2.3, 'c1_1': 0.2},
'constraints': {'fixed': {'c0_0': True}}
},
Hermite2D: {
'args': (1, 1),
'kwargs': {'x_domain': [0, 99], 'y_domain': [0, 82]},
'parameters': {'c0_0': 1.2, 'c1_0': 2, 'c0_1': 2.3, 'c1_1': 0.2},
'constraints': {'fixed': {'c0_0': True}}
},
Legendre2D: {
'args': (1, 1),
'kwargs': {'x_domain': [0, 99], 'y_domain': [0, 82]},
'parameters': {'c0_0': 1.2, 'c1_0': 2, 'c0_1': 2.3, 'c1_1': 0.2},
'constraints': {'fixed': {'c0_0': True}}
},
Polynomial2D: {
'args': (1,),
'kwargs': {},
'parameters': {'c0_0': 1.2, 'c1_0': 2, 'c0_1': 2.3},
'constraints': {'fixed': {'c0_0': True}}
}
}
@pytest.mark.skipif('not HAS_SCIPY')
class TestFitting:
"""Test linear fitter with polynomial models."""
def setup_class(self):
self.N = 100
self.M = 100
self.x1 = np.linspace(1, 10, 100)
self.y2, self.x2 = np.mgrid[:100, :83]
rsn = np.random.default_rng(0)
self.n1 = rsn.standard_normal(self.x1.size) * .1
self.n2 = rsn.standard_normal(self.x2.size)
self.n2.shape = self.x2.shape
self.linear_fitter = fitting.LinearLSQFitter()
self.non_linear_fitter = fitting.LevMarLSQFitter()
# TODO: Most of these test cases have some pretty repetitive setup that we
# could probably factor out
@pytest.mark.parametrize(('model_class', 'constraints'),
list(product(sorted(linear1d, key=str), (False, True))))
def test_linear_fitter_1D(self, model_class, constraints):
"""Test fitting with LinearLSQFitter"""
model_args = linear1d[model_class]
kwargs = {}
kwargs.update(model_args['kwargs'])
kwargs.update(model_args['parameters'])
if constraints:
kwargs.update(model_args['constraints'])
model = model_class(*model_args['args'], **kwargs)
y1 = model(self.x1)
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore', message=r'The fit may be poorly conditioned',
category=AstropyUserWarning)
model_lin = self.linear_fitter(model, self.x1, y1 + self.n1)
if constraints:
# For the constraints tests we're not checking the overall fit,
# just that the constraint was maintained
fixed = model_args['constraints'].get('fixed', None)
if fixed:
for param, value in fixed.items():
expected = model_args['parameters'][param]
assert getattr(model_lin, param).value == expected
else:
assert_allclose(model_lin.parameters, model.parameters,
atol=0.2)
@pytest.mark.parametrize(('model_class', 'constraints'),
list(product(sorted(linear1d, key=str), (False, True))))
def test_non_linear_fitter_1D(self, model_class, constraints):
"""Test fitting with non-linear LevMarLSQFitter"""
model_args = linear1d[model_class]
kwargs = {}
kwargs.update(model_args['kwargs'])
kwargs.update(model_args['parameters'])
if constraints:
kwargs.update(model_args['constraints'])
model = model_class(*model_args['args'], **kwargs)
y1 = model(self.x1)
with pytest.warns(AstropyUserWarning,
match='Model is linear in parameters'):
model_nlin = self.non_linear_fitter(model, self.x1, y1 + self.n1)
if constraints:
fixed = model_args['constraints'].get('fixed', None)
if fixed:
for param, value in fixed.items():
expected = model_args['parameters'][param]
assert getattr(model_nlin, param).value == expected
else:
assert_allclose(model_nlin.parameters, model.parameters,
atol=0.2)
@pytest.mark.parametrize(('model_class', 'constraints'),
list(product(sorted(linear2d, key=str), (False, True))))
def test_linear_fitter_2D(self, model_class, constraints):
"""Test fitting with LinearLSQFitter"""
model_args = linear2d[model_class]
kwargs = {}
kwargs.update(model_args['kwargs'])
kwargs.update(model_args['parameters'])
if constraints:
kwargs.update(model_args['constraints'])
model = model_class(*model_args['args'], **kwargs)
z = model(self.x2, self.y2)
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore', message=r'The fit may be poorly conditioned',
category=AstropyUserWarning)
model_lin = self.linear_fitter(model, self.x2, self.y2, z + self.n2)
if constraints:
fixed = model_args['constraints'].get('fixed', None)
if fixed:
for param, value in fixed.items():
expected = model_args['parameters'][param]
assert getattr(model_lin, param).value == expected
else:
assert_allclose(model_lin.parameters, model.parameters,
atol=0.2)
@pytest.mark.parametrize(('model_class', 'constraints'),
list(product(sorted(linear2d, key=str), (False, True))))
def test_non_linear_fitter_2D(self, model_class, constraints):
"""Test fitting with non-linear LevMarLSQFitter"""
model_args = linear2d[model_class]
kwargs = {}
kwargs.update(model_args['kwargs'])
kwargs.update(model_args['parameters'])
if constraints:
kwargs.update(model_args['constraints'])
model = model_class(*model_args['args'], **kwargs)
z = model(self.x2, self.y2)
with pytest.warns(AstropyUserWarning,
match='Model is linear in parameters'):
model_nlin = self.non_linear_fitter(model, self.x2, self.y2,
z + self.n2)
if constraints:
fixed = model_args['constraints'].get('fixed', None)
if fixed:
for param, value in fixed.items():
expected = model_args['parameters'][param]
assert getattr(model_nlin, param).value == expected
else:
assert_allclose(model_nlin.parameters, model.parameters,
atol=0.2)
@pytest.mark.parametrize('model_class',
[cls for cls in list(linear1d) + list(linear2d)])
def test_polynomial_init_with_constraints(model_class):
"""
Test that polynomial models can be instantiated with constraints, but no
parameters specified.
Regression test for https://github.com/astropy/astropy/issues/3606
"""
# Just determine which parameter to place a constraint on; it doesn't
# matter which parameter it is to exhibit the problem so long as it's a
# valid parameter for the model
if '1D' in model_class.__name__:
param = 'c0'
else:
param = 'c0_0'
if issubclass(model_class, Linear1D):
param = 'intercept'
if issubclass(model_class, OrthoPolynomialBase):
degree = (2, 2)
else:
degree = (2,)
m = model_class(*degree, fixed={param: True})
assert m.fixed[param] is True
assert getattr(m, param).fixed is True
if issubclass(model_class, OrthoPolynomialBase):
assert repr(m) ==\
f"<{model_class.__name__}(2, 2, c0_0=0., c1_0=0., c2_0=0., c0_1=0., c1_1=0., c2_1=0., c0_2=0., c1_2=0., c2_2=0.)>"
assert str(m) ==\
f"Model: {model_class.__name__}\n" +\
"Inputs: ('x', 'y')\n" +\
"Outputs: ('z',)\n" +\
"Model set size: 1\n" +\
"X_Degree: 2\n" +\
"Y_Degree: 2\n" +\
"Parameters:\n" +\
" c0_0 c1_0 c2_0 c0_1 c1_1 c2_1 c0_2 c1_2 c2_2\n" +\
" ---- ---- ---- ---- ---- ---- ---- ---- ----\n" +\
" 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0"
else:
if model_class.__name__ == 'Polynomial2D':
assert repr(m) ==\
"<Polynomial2D(2, c0_0=0., c1_0=0., c2_0=0., c0_1=0., c0_2=0., c1_1=0.)>"
assert str(m) ==\
"Model: Polynomial2D\n" +\
"Inputs: ('x', 'y')\n" +\
"Outputs: ('z',)\n" +\
"Model set size: 1\n" +\
"Degree: 2\n" +\
"Parameters:\n" +\
" c0_0 c1_0 c2_0 c0_1 c0_2 c1_1\n" +\
" ---- ---- ---- ---- ---- ----\n" +\
" 0.0 0.0 0.0 0.0 0.0 0.0"
elif model_class.__name__ == 'Linear1D':
assert repr(m) ==\
"<Linear1D(slope=2., intercept=0.)>"
assert str(m) ==\
"Model: Linear1D\n" +\
"Inputs: ('x',)\n" +\
"Outputs: ('y',)\n" +\
"Model set size: 1\n" +\
"Parameters:\n" +\
" slope intercept\n" +\
" ----- ---------\n" +\
" 2.0 0.0"
else:
assert repr(m) ==\
f"<{model_class.__name__}(2, c0=0., c1=0., c2=0.)>"
assert str(m) ==\
f"Model: {model_class.__name__}\n" +\
"Inputs: ('x',)\n" +\
"Outputs: ('y',)\n" +\
"Model set size: 1\n" +\
"Degree: 2\n" +\
"Parameters:\n" +\
" c0 c1 c2\n" +\
" --- --- ---\n" +\
" 0.0 0.0 0.0"
def test_sip_hst():
"""Test SIP against astropy.wcs"""
test_file = get_pkg_data_filename(os.path.join('data', 'hst_sip.hdr'))
hdr = fits.Header.fromtextfile(test_file)
crpix1 = hdr['CRPIX1']
crpix2 = hdr['CRPIX2']
wobj = wcs.WCS(hdr)
a_pars = dict(**hdr['A_*'])
b_pars = dict(**hdr['B_*'])
a_order = a_pars.pop('A_ORDER')
b_order = b_pars.pop('B_ORDER')
sip = SIP([crpix1, crpix2], a_order, b_order, a_pars, b_pars)
coords = [1, 1]
rel_coords = [1 - crpix1, 1 - crpix2]
astwcs_result = wobj.sip_pix2foc([coords], 1)[0] - rel_coords
assert_allclose(sip(1, 1), astwcs_result)
# Test changing of inputs and calling it with keyword argumenrts.
sip.inputs = ("r", "t")
assert_allclose(sip(r=1, t=1), astwcs_result)
assert_allclose(sip(1, t=1), astwcs_result)
# Test representations
assert repr(sip) ==\
"<SIP([<Shift(offset=-2048.)>, <Shift(offset=-1024.)>, " +\
"<_SIP1D(4, 'A', A_2_0=0.00000855, A_3_0=-0., A_4_0=0., A_0_2=0.00000217, " +\
"A_0_3=0., A_0_4=0., A_1_1=-0.0000052, A_1_2=-0., A_1_3=-0., " +\
"A_2_1=-0., A_2_2=0., A_3_1=0.)>, " +\
"<_SIP1D(4, 'B', B_2_0=-0.00000175, B_3_0=0., B_4_0=-0., B_0_2=-0.00000722, " +\
"B_0_3=-0., B_0_4=-0., B_1_1=0.00000618, B_1_2=-0., B_1_3=0., " +\
"B_2_1=-0., B_2_2=-0., B_3_1=-0.)>])>"
assert str(sip) ==\
"Model: SIP\n" +\
" Model: Shift\n" +\
" Inputs: ('x',)\n" +\
" Outputs: ('y',)\n" +\
" Model set size: 1\n" +\
" Parameters:\n" +\
" offset\n" +\
" -------\n" +\
" -2048.0\n" +\
"\n" +\
" Model: Shift\n" +\
" Inputs: ('x',)\n" +\
" Outputs: ('y',)\n" +\
" Model set size: 1\n" +\
" Parameters:\n" +\
" offset\n" +\
" -------\n" +\
" -1024.0\n" +\
"\n" +\
" Model: _SIP1D\n" +\
" Inputs: ('x', 'y')\n" +\
" Outputs: ('z',)\n" +\
" Model set size: 1\n" +\
" Order: 4\n" +\
" Coeff. Prefix: A\n" +\
" Parameters:\n" +\
" A_2_0 A_3_0 ... A_3_1 \n" +\
" --------------------- ---------------------- ... ---------------------\n" +\
" 8.551277582556502e-06 -4.730444829222791e-10 ... 1.971022971660309e-15\n" +\
"\n" +\
" Model: _SIP1D\n" +\
" Inputs: ('x', 'y')\n" +\
" Outputs: ('z',)\n" +\
" Model set size: 1\n" +\
" Order: 4\n" +\
" Coeff. Prefix: B\n" +\
" Parameters:\n" +\
" B_2_0 B_3_0 ... B_3_1 \n" +\
" ---------------------- --------------------- ... ----------------------\n" +\
" -1.746491877058669e-06 8.567635427816317e-11 ... -3.779506805487476e-15\n"
# Test get num of coeffs
assert sip.sip1d_a.get_num_coeff(1) == 6
# Test error
message = "Degree of polynomial must be 2< deg < 9"
sip.sip1d_a.order = 1
with pytest.raises(ValueError) as err:
sip.sip1d_a.get_num_coeff(1)
assert str(err.value) == message
sip.sip1d_a.order = 10
with pytest.raises(ValueError) as err:
sip.sip1d_a.get_num_coeff(1)
assert str(err.value) == message
def test_sip_irac():
"""Test forward and inverse SIP against astropy.wcs"""
test_file = get_pkg_data_filename(os.path.join('data', 'irac_sip.hdr'))
hdr = fits.Header.fromtextfile(test_file)
crpix1 = hdr['CRPIX1']
crpix2 = hdr['CRPIX2']
wobj = wcs.WCS(hdr)
a_pars = dict(**hdr['A_*'])
b_pars = dict(**hdr['B_*'])
ap_pars = dict(**hdr['AP_*'])
bp_pars = dict(**hdr['BP_*'])
a_order = a_pars.pop('A_ORDER')
b_order = b_pars.pop('B_ORDER')
ap_order = ap_pars.pop('AP_ORDER')
bp_order = bp_pars.pop('BP_ORDER')
del a_pars['A_DMAX']
del b_pars['B_DMAX']
pix = [200, 200]
rel_pix = [200 - crpix1, 200 - crpix2]
sip = SIP([crpix1, crpix2], a_order, b_order, a_pars, b_pars,
ap_order=ap_order, ap_coeff=ap_pars, bp_order=bp_order,
bp_coeff=bp_pars)
foc = wobj.sip_pix2foc([pix], 1)
newpix = wobj.sip_foc2pix(foc, 1)[0]
assert_allclose(sip(*pix), foc[0] - rel_pix)
assert_allclose(sip.inverse(*foc[0]) +
foc[0] - rel_pix, newpix - pix)
# Test inverse representations
assert repr(sip.inverse) ==\
"<InverseSIP([<Polynomial2D(2, c0_0=0., c1_0=0.0000114, c2_0=0.00002353, " +\
"c0_1=-0.00000546, c0_2=-0.00000667, c1_1=-0.00001801)>, " +\
"<Polynomial2D(2, c0_0=0., c1_0=-0.00001495, c2_0=0.00000122, c0_1=0.00001975, " +\
"c0_2=-0.00002601, c1_1=0.00002944)>])>"
assert str(sip.inverse) ==\
"Model: InverseSIP\n" +\
" Model: Polynomial2D\n" +\
" Inputs: ('x', 'y')\n" +\
" Outputs: ('z',)\n" +\
" Model set size: 1\n" +\
" Degree: 2\n" +\
" Parameters:\n" +\
" c0_0 c1_0 c2_0 c0_1 c0_2 c1_1 \n" +\
" ---- -------- --------- ---------- ---------- ----------\n" +\
" 0.0 1.14e-05 2.353e-05 -5.463e-06 -6.666e-06 -1.801e-05\n" +\
"\n" +\
" Model: Polynomial2D\n" +\
" Inputs: ('x', 'y')\n" +\
" Outputs: ('z',)\n" +\
" Model set size: 1\n" +\
" Degree: 2\n" +\
" Parameters:\n" +\
" c0_0 c1_0 c2_0 c0_1 c0_2 c1_1 \n" +\
" ---- ---------- --------- --------- ---------- ---------\n" +\
" 0.0 -1.495e-05 1.225e-06 1.975e-05 -2.601e-05 2.944e-05\n"
def test_sip_no_coeff():
sip = SIP([10, 12], 2, 2)
assert_allclose(sip.sip1d_a.parameters, [0., 0., 0])
assert_allclose(sip.sip1d_b.parameters, [0., 0., 0])
with pytest.raises(NotImplementedError):
sip.inverse
# Test model set
sip = SIP([10, 12], 2, 2, n_models=2)
assert sip.sip1d_a.model_set_axis == 0
assert sip.sip1d_b.model_set_axis == 0
@pytest.mark.parametrize('cls', (Polynomial1D, Chebyshev1D, Legendre1D,
Polynomial2D, Chebyshev2D, Legendre2D))
def test_zero_degree_polynomial(cls):
"""
A few tests that degree=0 polynomials are correctly evaluated and
fitted.
Regression test for https://github.com/astropy/astropy/pull/3589
"""
message = "Degree of polynomial must be positive or null"
if cls.n_inputs == 1: # Test 1D polynomials
p1 = cls(degree=0, c0=1)
assert p1(0) == 1
assert np.all(p1(np.zeros(5)) == np.ones(5))
x = np.linspace(0, 1, 100)
# Add a little noise along a straight line
y = 1 + np.random.uniform(0, 0.1, len(x))
p1_init = cls(degree=0)
fitter = fitting.LinearLSQFitter()
p1_fit = fitter(p1_init, x, y)
# The fit won't be exact of course, but it should get close to within
# 1%
assert_allclose(p1_fit.c0, 1, atol=0.10)
# Error from negative degree
with pytest.raises(ValueError) as err:
cls(degree=-1)
assert str(err.value) == message
elif cls.n_inputs == 2: # Test 2D polynomials
if issubclass(cls, OrthoPolynomialBase):
p2 = cls(x_degree=0, y_degree=0, c0_0=1)
# different shaped x and y inputs
a = np.array([1, 2, 3])
b = np.array([1, 2])
with mk.patch.object(PolynomialBase, 'prepare_inputs', autospec=True,
return_value=((a, b), mk.MagicMock())):
with pytest.raises(ValueError) as err:
p2.prepare_inputs(mk.MagicMock(), mk.MagicMock())
assert str(err.value) ==\
"Expected input arrays to have the same shape"
# Error from negative degree
with pytest.raises(ValueError) as err:
cls(x_degree=-1, y_degree=0)
assert str(err.value) == message
with pytest.raises(ValueError) as err:
cls(x_degree=0, y_degree=-1)
assert str(err.value) == message
else:
p2 = cls(degree=0, c0_0=1)
# Error from negative degree
with pytest.raises(ValueError) as err:
cls(degree=-1)
assert str(err.value) == message
assert p2(0, 0) == 1
assert np.all(p2(np.zeros(5), np.zeros(5)) == np.ones(5))
y, x = np.mgrid[0:1:100j, 0:1:100j]
z = (1 + np.random.uniform(0, 0.1, x.size)).reshape(100, 100)
if issubclass(cls, OrthoPolynomialBase):
p2_init = cls(x_degree=0, y_degree=0)
else:
p2_init = cls(degree=0)
fitter = fitting.LinearLSQFitter()
p2_fit = fitter(p2_init, x, y, z)
assert_allclose(p2_fit.c0_0, 1, atol=0.10)
@pytest.mark.skipif('not HAS_SCIPY')
def test_2d_orthopolynomial_in_compound_model():
"""
Ensure that OrthoPolynomialBase (ie. Chebyshev2D & Legendre2D) models get
evaluated & fitted correctly when part of a compound model.
Regression test for https://github.com/astropy/astropy/pull/6085.
"""
y, x = np.mgrid[0:5, 0:5]
z = x + y
fitter = fitting.LevMarLSQFitter()
simple_model = Chebyshev2D(2, 2)
with pytest.warns(AstropyUserWarning,
match='Model is linear in parameters'):
simple_fit = fitter(simple_model, x, y, z)
fitter = fitting.LevMarLSQFitter() # re-init to compare like with like
compound_model = Identity(2) | Chebyshev2D(2, 2)
compound_model.fittable = True
compound_model.linear = True
with pytest.warns(AstropyUserWarning,
match='Model is linear in parameters'):
compound_fit = fitter(compound_model, x, y, z)
assert_allclose(simple_fit(x, y), compound_fit(x, y), atol=1e-15)
def test_Hermite1D_clenshaw():
model = Hermite1D(degree=2)
assert model.clenshaw(1, [3]) == 3
assert model.clenshaw(1, [3, 4]) == 11
assert model.clenshaw(1, [3, 4, 5]) == 21
assert model.clenshaw(1, [3, 4, 5, 6]) == -3
def test__fcache():
model = OrthoPolynomialBase(x_degree=2, y_degree=2)
with pytest.raises(NotImplementedError) as err:
model._fcache(np.asanyarray(1), np.asanyarray(1))
assert str(err.value) == "Subclasses should implement this"
model = Hermite2D(x_degree=2, y_degree=2)
assert model._fcache(np.asanyarray(1), np.asanyarray(1)) ==\
{
0: np.asanyarray(1),
1: 2,
3: np.asanyarray(1),
4: 2,
2: 2.0,
5: -4.0
}
model = Legendre2D(x_degree=2, y_degree=2)
assert model._fcache(np.asanyarray(1), np.asanyarray(1)) ==\
{
0: np.asanyarray(1),
1: np.asanyarray(1),
2: 1.0,
3: np.asanyarray(1),
4: np.asanyarray(1),
5: 1.0
}
model = Chebyshev2D(x_degree=2, y_degree=2)
assert model._fcache(np.asanyarray(1), np.asanyarray(1)) ==\
{
0: np.asanyarray(1),
1: np.asanyarray(1),
2: 1.0,
3: np.asanyarray(1),
4: np.asanyarray(1),
5: 1.0
}
def test_fit_deriv_shape_error():
model = Hermite2D(x_degree=2, y_degree=2)
with pytest.raises(ValueError) as err:
model.fit_deriv(np.array([1, 2]), np.array([3, 4, 5]))
assert str(err.value) ==\
"x and y must have the same shape"
model = Chebyshev2D(x_degree=2, y_degree=2)
with pytest.raises(ValueError) as err:
model.fit_deriv(np.array([1, 2]), np.array([3, 4, 5]))
assert str(err.value) ==\
"x and y must have the same shape"
model = Legendre2D(x_degree=2, y_degree=2)
with pytest.raises(ValueError) as err:
model.fit_deriv(np.array([1, 2]), np.array([3, 4, 5]))
assert str(err.value) ==\
"x and y must have the same shape"
model = Polynomial2D(degree=2)
with pytest.raises(ValueError) as err:
model.fit_deriv(np.array([1, 2]), np.array([3, 4, 5]))
assert str(err.value) ==\
"Expected x and y to be of equal size"
|