hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
38d9cd44585b1ece4f73af62e7a610cf35d604b0fc18a4495d078e8022e5f4e7 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Handles the "Console" unit format.
"""
from . import base, core, utils
class Console(base.Base):
"""
Output-only format for to display pretty formatting at the
console.
For example::
>>> import astropy.units as u
>>> print(u.Ry.decompose().to_string('console')) # doctest: +FLOAT_CMP
m^2 kg
2.1798721*10^-18 ------
s^2
"""
_times = "*"
_line = "-"
@classmethod
def _get_unit_name(cls, unit):
return unit.get_format_name('console')
@classmethod
def _format_superscript(cls, number):
return '^{0}'.format(number)
@classmethod
def _format_unit_list(cls, units):
out = []
for base, power in units:
if power == 1:
out.append(cls._get_unit_name(base))
else:
out.append('{0}{1}'.format(
cls._get_unit_name(base),
cls._format_superscript(
utils.format_power(power))))
return ' '.join(out)
@classmethod
def format_exponential_notation(cls, val):
m, ex = utils.split_mantissa_exponent(val)
parts = []
if m:
parts.append(m)
if ex:
parts.append("10{0}".format(
cls._format_superscript(ex)))
return cls._times.join(parts)
@classmethod
def to_string(cls, unit):
if isinstance(unit, core.CompositeUnit):
if unit.scale == 1:
s = ''
else:
s = cls.format_exponential_notation(unit.scale)
if len(unit.bases):
positives, negatives = utils.get_grouped_by_powers(
unit.bases, unit.powers)
if len(negatives):
if len(positives):
positives = cls._format_unit_list(positives)
else:
positives = '1'
negatives = cls._format_unit_list(negatives)
l = len(s)
r = max(len(positives), len(negatives))
f = "{{0:^{0}s}} {{1:^{1}s}}".format(l, r)
lines = [
f.format('', positives),
f.format(s, cls._line * r),
f.format('', negatives)
]
s = '\n'.join(lines)
else:
positives = cls._format_unit_list(positives)
s += positives
elif isinstance(unit, core.NamedUnit):
s = cls._get_unit_name(unit)
return s
|
e163ea9e1a3caee7c871bb461d56b3ce5a1aedcad21402a6eb9cee4f8c088f5d | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# This file is automatically generated. Do not edit.
_tabversion = '3.8'
_lr_method = 'LALR'
_lr_signature = 'A63D4C561E2ED1A045DB279536CAFDDA'
_lr_action_items = {'CARET':([16,17,29,42,],[39,39,39,39,]),'FUNCNAME':([0,1,4,5,7,8,9,14,15,16,17,19,20,21,22,24,25,27,31,33,34,35,36,45,52,55,58,59,65,66,67,69,72,73,74,76,77,79,81,],[18,-16,18,-32,-17,18,18,-14,-48,-37,-20,-15,18,-33,18,18,-46,-47,18,18,-53,-52,-36,-21,-18,-34,-38,-35,-23,-27,-22,-26,-51,-19,-55,-39,-24,-28,-25,]),'CLOSE_PAREN':([1,2,4,5,7,9,10,12,14,16,17,19,21,23,26,28,30,32,34,35,36,45,47,48,49,50,51,52,55,56,57,58,59,61,62,63,65,66,67,69,71,72,73,74,75,76,77,78,79,81,83,],[-16,-4,-10,-32,-17,-31,-1,-7,-14,-37,-20,-15,-33,-5,-8,-2,55,-30,-53,-52,-36,-21,-13,-11,-6,-9,-3,-18,-34,-29,74,-38,-35,-42,-41,76,-23,-27,-22,-26,79,-51,-19,-55,-40,-39,-24,81,-28,-25,-43,]),'UFLOAT':([0,6,13,33,41,60,68,70,],[-45,-44,34,-45,-45,34,-44,-45,]),'$end':([1,2,3,4,5,7,9,10,12,14,16,17,19,21,23,26,28,32,34,35,36,45,47,48,49,50,51,52,55,56,58,59,65,66,67,69,72,73,74,76,77,79,81,],[-16,-4,0,-10,-32,-17,-31,-1,-7,-14,-37,-20,-15,-33,-5,-8,-2,-30,-53,-52,-36,-21,-13,-11,-6,-9,-3,-18,-34,-29,-38,-35,-23,-27,-22,-26,-51,-19,-55,-39,-24,-28,-25,]),'SOLIDUS':([0,1,2,4,5,7,9,10,14,16,17,19,21,23,24,25,27,28,32,33,34,35,36,45,48,49,51,52,55,56,58,59,65,66,67,69,72,73,74,75,76,77,79,81,],[15,-16,15,15,-32,-17,-31,-12,-14,-37,-20,-15,-33,15,15,-46,-47,-12,-30,15,-53,-52,-36,-21,-11,15,-12,-18,-34,-29,-38,-35,-23,-27,-22,-26,-51,-19,-55,15,-39,-24,-28,-25,]),'UINT':([0,6,7,13,15,16,17,33,34,35,37,38,39,40,41,43,44,53,54,60,64,68,70,80,82,],[17,-44,29,35,-48,-45,42,17,-53,-52,58,-45,-50,-49,-45,66,-45,72,-45,75,-45,72,-45,-45,83,]),'SIGN':([0,15,16,17,29,33,38,39,40,41,42,44,46,54,64,70,80,],[6,-48,6,43,53,6,6,-50,-49,6,53,68,53,6,6,68,6,]),'DOUBLE_STAR':([16,17,29,42,],[40,40,40,40,]),'OPEN_PAREN':([0,1,4,5,7,8,9,11,14,15,16,17,18,19,20,21,22,24,25,27,31,33,34,35,36,38,39,40,44,45,52,54,55,58,59,64,65,66,67,69,72,73,74,76,77,79,81,],[8,-16,8,-32,-17,8,8,33,-14,-48,41,46,-54,-15,8,-33,8,8,-46,-47,8,8,-53,-52,-36,41,-50,-49,70,-21,-18,41,-34,-38,-35,41,-23,-27,-22,-26,-51,-19,-55,-39,-24,-28,-25,]),'PERIOD':([1,4,5,7,9,14,16,17,19,21,34,35,36,45,52,55,58,59,65,66,67,69,72,73,74,76,77,79,81,],[-16,27,-32,-17,27,-14,-37,-20,-15,-33,-53,-52,-36,-21,-18,-34,-38,-35,-23,-27,-22,-26,-51,-19,-55,-39,-24,-28,-25,]),'STAR':([1,4,5,7,9,14,16,17,19,21,34,35,36,45,52,55,58,59,65,66,67,69,72,73,74,76,77,79,81,],[-16,25,-32,-17,25,-14,-37,-20,-15,-33,-53,-52,-36,-21,-18,-34,-38,-35,-23,-27,-22,-26,-51,-19,-55,-39,-24,-28,-25,]),'UNIT':([0,1,4,5,7,8,9,14,15,16,17,19,20,21,22,24,25,27,31,33,34,35,36,45,52,55,58,59,65,66,67,69,72,73,74,76,77,79,81,],[16,-16,16,-32,-17,16,16,-14,-48,-37,-20,-15,16,-33,16,16,-46,-47,16,16,-53,-52,-36,-21,-18,-34,-38,-35,-23,-27,-22,-26,-51,-19,-55,-39,-24,-28,-25,]),}
_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 = {'power':([16,17,29,42,],[38,44,54,64,]),'sign':([0,16,33,38,41,44,54,64,70,80,],[13,37,13,37,60,37,37,37,60,82,]),'factor_int':([0,33,],[1,1,]),'numeric_power':([16,38,44,54,64,],[36,59,67,73,77,]),'division_product_of_units':([0,4,24,33,],[2,23,49,2,]),'signed_int':([17,29,42,44,46,70,],[45,52,65,69,71,78,]),'signed_float':([0,33,41,70,],[7,7,62,62,]),'factor':([0,33,],[4,4,]),'function':([0,4,8,9,20,22,24,31,33,],[5,5,5,5,5,5,5,5,5,]),'factor_fits':([0,33,],[14,14,]),'product':([4,9,],[24,31,]),'paren_expr':([41,70,],[63,63,]),'main':([0,33,],[3,57,]),'inverse_unit':([0,4,24,33,],[12,26,50,12,]),'factor_float':([0,33,],[19,19,]),'division':([0,2,4,23,24,33,49,75,],[20,22,20,22,20,20,22,80,]),'unit_expression':([0,4,8,9,20,22,24,31,33,],[9,9,9,9,47,9,9,9,9,]),'product_of_units':([0,4,8,9,22,24,31,33,],[10,28,30,32,48,51,56,10,]),'function_name':([0,4,8,9,20,22,24,31,33,],[11,11,11,11,11,11,11,11,11,]),'frac':([41,70,],[61,61,]),'unit_with_power':([0,4,8,9,20,22,24,31,33,],[21,21,21,21,21,21,21,21,21,]),}
_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' -> main","S'",1,None,None,None),
('main -> product_of_units','main',1,'p_main','generic.py',186),
('main -> factor product_of_units','main',2,'p_main','generic.py',187),
('main -> factor product product_of_units','main',3,'p_main','generic.py',188),
('main -> division_product_of_units','main',1,'p_main','generic.py',189),
('main -> factor division_product_of_units','main',2,'p_main','generic.py',190),
('main -> factor product division_product_of_units','main',3,'p_main','generic.py',191),
('main -> inverse_unit','main',1,'p_main','generic.py',192),
('main -> factor inverse_unit','main',2,'p_main','generic.py',193),
('main -> factor product inverse_unit','main',3,'p_main','generic.py',194),
('main -> factor','main',1,'p_main','generic.py',195),
('division_product_of_units -> division_product_of_units division product_of_units','division_product_of_units',3,'p_division_product_of_units','generic.py',207),
('division_product_of_units -> product_of_units','division_product_of_units',1,'p_division_product_of_units','generic.py',208),
('inverse_unit -> division unit_expression','inverse_unit',2,'p_inverse_unit','generic.py',218),
('factor -> factor_fits','factor',1,'p_factor','generic.py',224),
('factor -> factor_float','factor',1,'p_factor','generic.py',225),
('factor -> factor_int','factor',1,'p_factor','generic.py',226),
('factor_float -> signed_float','factor_float',1,'p_factor_float','generic.py',232),
('factor_float -> signed_float UINT signed_int','factor_float',3,'p_factor_float','generic.py',233),
('factor_float -> signed_float UINT power numeric_power','factor_float',4,'p_factor_float','generic.py',234),
('factor_int -> UINT','factor_int',1,'p_factor_int','generic.py',247),
('factor_int -> UINT signed_int','factor_int',2,'p_factor_int','generic.py',248),
('factor_int -> UINT power numeric_power','factor_int',3,'p_factor_int','generic.py',249),
('factor_int -> UINT UINT signed_int','factor_int',3,'p_factor_int','generic.py',250),
('factor_int -> UINT UINT power numeric_power','factor_int',4,'p_factor_int','generic.py',251),
('factor_fits -> UINT power OPEN_PAREN signed_int CLOSE_PAREN','factor_fits',5,'p_factor_fits','generic.py',269),
('factor_fits -> UINT power signed_int','factor_fits',3,'p_factor_fits','generic.py',270),
('factor_fits -> UINT SIGN UINT','factor_fits',3,'p_factor_fits','generic.py',271),
('factor_fits -> UINT OPEN_PAREN signed_int CLOSE_PAREN','factor_fits',4,'p_factor_fits','generic.py',272),
('product_of_units -> unit_expression product product_of_units','product_of_units',3,'p_product_of_units','generic.py',291),
('product_of_units -> unit_expression product_of_units','product_of_units',2,'p_product_of_units','generic.py',292),
('product_of_units -> unit_expression','product_of_units',1,'p_product_of_units','generic.py',293),
('unit_expression -> function','unit_expression',1,'p_unit_expression','generic.py',304),
('unit_expression -> unit_with_power','unit_expression',1,'p_unit_expression','generic.py',305),
('unit_expression -> OPEN_PAREN product_of_units CLOSE_PAREN','unit_expression',3,'p_unit_expression','generic.py',306),
('unit_with_power -> UNIT power numeric_power','unit_with_power',3,'p_unit_with_power','generic.py',315),
('unit_with_power -> UNIT numeric_power','unit_with_power',2,'p_unit_with_power','generic.py',316),
('unit_with_power -> UNIT','unit_with_power',1,'p_unit_with_power','generic.py',317),
('numeric_power -> sign UINT','numeric_power',2,'p_numeric_power','generic.py',328),
('numeric_power -> OPEN_PAREN paren_expr CLOSE_PAREN','numeric_power',3,'p_numeric_power','generic.py',329),
('paren_expr -> sign UINT','paren_expr',2,'p_paren_expr','generic.py',338),
('paren_expr -> signed_float','paren_expr',1,'p_paren_expr','generic.py',339),
('paren_expr -> frac','paren_expr',1,'p_paren_expr','generic.py',340),
('frac -> sign UINT division sign UINT','frac',5,'p_frac','generic.py',349),
('sign -> SIGN','sign',1,'p_sign','generic.py',355),
('sign -> <empty>','sign',0,'p_sign','generic.py',356),
('product -> STAR','product',1,'p_product','generic.py',365),
('product -> PERIOD','product',1,'p_product','generic.py',366),
('division -> SOLIDUS','division',1,'p_division','generic.py',372),
('power -> DOUBLE_STAR','power',1,'p_power','generic.py',378),
('power -> CARET','power',1,'p_power','generic.py',379),
('signed_int -> SIGN UINT','signed_int',2,'p_signed_int','generic.py',385),
('signed_float -> sign UINT','signed_float',2,'p_signed_float','generic.py',391),
('signed_float -> sign UFLOAT','signed_float',2,'p_signed_float','generic.py',392),
('function_name -> FUNCNAME','function_name',1,'p_function_name','generic.py',398),
('function -> function_name OPEN_PAREN main CLOSE_PAREN','function',4,'p_function','generic.py',404),
]
|
57eb95fa6464c345d21818ea84f4bb72dcd468b16bc453338f639567cc85a438 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
_tabversion = '3.8'
_lextokens = set(('UINT', 'PRODUCT', 'OPEN_PAREN', 'UNIT', 'SIGN', 'UFLOAT', 'DIVISION', 'CLOSE_PAREN', 'X'))
_lexreflags = 32
_lexliterals = ''
_lexstateinfo = {'INITIAL': 'inclusive'}
_lexstatere = {'INITIAL': [('(?P<t_UFLOAT>((\\d+\\.?\\d+)|(\\.\\d+))([eE][+-]?\\d+)?)|(?P<t_UINT>\\d+)|(?P<t_SIGN>[+-](?=\\d))|(?P<t_X>[x×])|(?P<t_UNIT>\\%|°|\\\\h|((?!\\d)\\w)+)|(?P<t_CLOSE_PAREN>\\))|(?P<t_OPEN_PAREN>\\()|(?P<t_PRODUCT>\\.)|(?P<t_DIVISION>/)', [None, ('t_UFLOAT', 'UFLOAT'), None, None, None, None, ('t_UINT', 'UINT'), ('t_SIGN', 'SIGN'), ('t_X', 'X'), ('t_UNIT', 'UNIT'), None, (None, 'CLOSE_PAREN'), (None, 'OPEN_PAREN'), (None, 'PRODUCT'), (None, 'DIVISION')])]}
_lexstateignore = {'INITIAL': ''}
_lexstateerrorf = {'INITIAL': 't_error'}
_lexstateeoff = {}
|
7e217c6bf8a3403dfc759cbdde35da3c80345d319683a45c41749fca4379041b | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# This file is automatically generated. Do not edit.
_tabversion = '3.8'
_lr_method = 'LALR'
_lr_signature = '6AD6E7286443B59D7DF329E6378BFC6B'
_lr_action_items = {'UINT':([0,2,7,9,18,22,23,28,31,32,35,37,40,42,59,60,63,],[-38,19,-20,33,-21,39,-29,39,-23,39,39,-22,-38,-37,39,39,66,]),'WHITESPACE':([0,3,4,6,7,8,12,13,15,17,18,19,20,21,25,29,36,39,41,43,44,46,47,48,49,51,52,53,54,56,61,62,64,65,67,],[1,-30,24,29,31,-16,1,-17,-6,-10,37,-40,-41,1,45,1,-7,-32,-33,-31,57,-8,-9,-19,58,-15,-12,-18,-11,1,-34,-35,-14,-13,-36,]),'CLOSE_PAREN':([3,4,15,17,19,20,33,34,36,38,39,41,43,46,47,52,54,55,56,61,62,64,65,66,67,],[-30,-5,-6,-10,-40,-41,-39,52,-7,54,-32,-33,-31,-8,-9,-12,-11,61,62,-34,-35,-14,-13,67,-36,]),'OPEN_PAREN':([0,3,6,7,8,12,13,16,18,19,20,21,22,23,24,25,26,27,28,29,31,32,35,37,39,41,44,45,48,49,51,53,57,58,59,60,61,62,67,],[12,21,12,-20,-16,12,-17,12,-21,-40,-41,12,40,-29,-24,-25,12,12,40,12,-23,40,40,-22,-32,-33,-26,-28,-19,-20,-15,-18,-27,-22,40,40,-34,-35,-36,]),'UNIT':([0,6,7,8,12,13,16,18,19,20,21,24,25,26,27,29,31,37,39,41,44,45,48,49,51,53,57,58,61,62,67,],[3,3,-20,-16,3,-17,3,-21,-40,-41,3,-24,-25,3,3,3,-23,-22,-32,-33,-26,-28,-19,-20,-15,-18,-27,-22,-34,-35,-36,]),'UFLOAT':([0,2,9,22,23,28,32,35,40,42,59,60,],[-38,20,-37,-38,-29,-38,-38,-38,-38,-37,-38,-38,]),'SIGN':([0,22,23,28,32,35,40,59,60,],[9,42,-29,42,42,42,9,42,42,]),'DIVISION':([0,1,3,4,6,8,12,13,15,17,19,20,21,24,29,36,39,41,43,46,47,48,51,52,53,54,56,61,62,64,65,67,],[7,18,-30,7,7,-16,7,-17,-6,-10,-40,-41,7,18,49,-7,-32,-33,-31,-8,-9,-19,-15,-12,-18,-11,7,-34,-35,-14,-13,-36,]),'$end':([3,4,10,11,14,15,17,19,20,30,36,39,41,43,46,47,50,52,54,61,62,64,65,67,],[-30,-5,-1,-2,0,-6,-10,-40,-41,-3,-7,-32,-33,-31,-8,-9,-4,-12,-11,-34,-35,-14,-13,-36,]),'STARSTAR':([3,5,8,13,19,20,33,52,54,],[23,23,23,23,-40,-41,-39,23,23,]),'LIT10':([0,],[8,]),'STAR':([3,4,15,17,19,20,24,36,39,41,43,46,47,52,54,61,62,64,65,67,],[-30,25,-6,-10,-40,-41,44,-7,-32,-33,-31,-8,-9,-12,-11,-34,-35,-14,-13,-36,]),'UNKNOWN':([0,],[10,]),}
_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 = {'sign':([0,22,28,32,35,40,59,60,],[2,2,2,2,2,2,2,2,]),'signed_float':([0,22,28,32,35,40,59,60,],[13,41,41,41,41,56,41,41,]),'numeric_power':([22,28,32,35,59,60,],[43,48,51,53,64,65,]),'product_of_units':([0,6,12,21,29,],[4,4,4,4,4,]),'signed_int':([0,40,],[5,55,]),'scale_factor':([0,],[6,]),'product':([4,],[26,]),'main':([0,],[14,]),'power':([3,5,8,13,52,54,],[22,28,32,35,59,60,]),'unit_expression':([0,6,12,16,21,26,27,29,],[15,15,15,36,15,46,47,15,]),'division':([0,4,6,12,21,29,56,],[16,27,16,16,16,16,63,]),'unit':([0,6,12,16,21,26,27,29,],[17,17,17,17,17,17,17,17,]),'complete_expression':([0,6,12,21,29,],[11,30,34,38,50,]),}
_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' -> main","S'",1,None,None,None),
('main -> UNKNOWN','main',1,'p_main','ogip.py',188),
('main -> complete_expression','main',1,'p_main','ogip.py',189),
('main -> scale_factor complete_expression','main',2,'p_main','ogip.py',190),
('main -> scale_factor WHITESPACE complete_expression','main',3,'p_main','ogip.py',191),
('complete_expression -> product_of_units','complete_expression',1,'p_complete_expression','ogip.py',202),
('product_of_units -> unit_expression','product_of_units',1,'p_product_of_units','ogip.py',208),
('product_of_units -> division unit_expression','product_of_units',2,'p_product_of_units','ogip.py',209),
('product_of_units -> product_of_units product unit_expression','product_of_units',3,'p_product_of_units','ogip.py',210),
('product_of_units -> product_of_units division unit_expression','product_of_units',3,'p_product_of_units','ogip.py',211),
('unit_expression -> unit','unit_expression',1,'p_unit_expression','ogip.py',225),
('unit_expression -> UNIT OPEN_PAREN complete_expression CLOSE_PAREN','unit_expression',4,'p_unit_expression','ogip.py',226),
('unit_expression -> OPEN_PAREN complete_expression CLOSE_PAREN','unit_expression',3,'p_unit_expression','ogip.py',227),
('unit_expression -> UNIT OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power','unit_expression',6,'p_unit_expression','ogip.py',228),
('unit_expression -> OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power','unit_expression',5,'p_unit_expression','ogip.py',229),
('scale_factor -> LIT10 power numeric_power','scale_factor',3,'p_scale_factor','ogip.py',263),
('scale_factor -> LIT10','scale_factor',1,'p_scale_factor','ogip.py',264),
('scale_factor -> signed_float','scale_factor',1,'p_scale_factor','ogip.py',265),
('scale_factor -> signed_float power numeric_power','scale_factor',3,'p_scale_factor','ogip.py',266),
('scale_factor -> signed_int power numeric_power','scale_factor',3,'p_scale_factor','ogip.py',267),
('division -> DIVISION','division',1,'p_division','ogip.py',282),
('division -> WHITESPACE DIVISION','division',2,'p_division','ogip.py',283),
('division -> WHITESPACE DIVISION WHITESPACE','division',3,'p_division','ogip.py',284),
('division -> DIVISION WHITESPACE','division',2,'p_division','ogip.py',285),
('product -> WHITESPACE','product',1,'p_product','ogip.py',291),
('product -> STAR','product',1,'p_product','ogip.py',292),
('product -> WHITESPACE STAR','product',2,'p_product','ogip.py',293),
('product -> WHITESPACE STAR WHITESPACE','product',3,'p_product','ogip.py',294),
('product -> STAR WHITESPACE','product',2,'p_product','ogip.py',295),
('power -> STARSTAR','power',1,'p_power','ogip.py',301),
('unit -> UNIT','unit',1,'p_unit','ogip.py',307),
('unit -> UNIT power numeric_power','unit',3,'p_unit','ogip.py',308),
('numeric_power -> UINT','numeric_power',1,'p_numeric_power','ogip.py',317),
('numeric_power -> signed_float','numeric_power',1,'p_numeric_power','ogip.py',318),
('numeric_power -> OPEN_PAREN signed_int CLOSE_PAREN','numeric_power',3,'p_numeric_power','ogip.py',319),
('numeric_power -> OPEN_PAREN signed_float CLOSE_PAREN','numeric_power',3,'p_numeric_power','ogip.py',320),
('numeric_power -> OPEN_PAREN signed_float division UINT CLOSE_PAREN','numeric_power',5,'p_numeric_power','ogip.py',321),
('sign -> SIGN','sign',1,'p_sign','ogip.py',332),
('sign -> <empty>','sign',0,'p_sign','ogip.py',333),
('signed_int -> SIGN UINT','signed_int',2,'p_signed_int','ogip.py',342),
('signed_float -> sign UINT','signed_float',2,'p_signed_float','ogip.py',348),
('signed_float -> sign UFLOAT','signed_float',2,'p_signed_float','ogip.py',349),
]
|
dba25bc246004194d62eedc1690fcfd1fe16fa8b7fb3d0a958f29a669f10cb4e | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
A collection of different unit formats.
"""
# This is pretty atrocious, but it will prevent a circular import for those
# formatters that need access to the units.core module An entry for it should
# exist in sys.modules since astropy.units.core imports this module
import sys
core = sys.modules['astropy.units.core']
from .base import Base
from .generic import Generic, Unscaled
from .cds import CDS
from .console import Console
from .fits import Fits
from .latex import Latex, LatexInline
from .ogip import OGIP
from .unicode_format import Unicode
from .vounit import VOUnit
__all__ = [
'Base', 'Generic', 'CDS', 'Console', 'Fits', 'Latex', 'LatexInline',
'OGIP', 'Unicode', 'Unscaled', 'VOUnit', 'get_format']
def get_format(format=None):
"""
Get a formatter by name.
Parameters
----------
format : str or `astropy.units.format.Base` instance or subclass
The name of the format, or the format instance or subclass
itself.
Returns
-------
format : `astropy.units.format.Base` instance
The requested formatter.
"""
if isinstance(format, type) and issubclass(format, Base):
return format
elif not (isinstance(format, str) or format is None):
raise TypeError(
"Formatter must a subclass or instance of a subclass of {0!r} "
"or a string giving the name of the formatter. Valid formatter "
"names are: [{1}]".format(Base, ', '.join(Base.registry)))
if format is None:
format = 'generic'
format_lower = format.lower()
if format_lower in Base.registry:
return Base.registry[format_lower]
raise ValueError("Unknown format {0!r}. Valid formatter names are: "
"[{1}]".format(format, ', '.join(Base.registry)))
|
025cecbffe6e0418813720533ec45c5db13a28fe84e0ac1f2d6ea4df64bdfbe1 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Handles the "VOUnit" unit format.
"""
import copy
import keyword
import operator
import re
import warnings
from . import core, generic, utils
class VOUnit(generic.Generic):
"""
The IVOA standard for units used by the VO.
This is an implementation of `Units in the VO 1.0
<http://www.ivoa.net/Documents/VOUnits/>`_.
"""
_explicit_custom_unit_regex = re.compile(
r"^[YZEPTGMkhdcmunpfazy]?'((?!\d)\w)+'$")
_custom_unit_regex = re.compile(r"^((?!\d)\w)+$")
_custom_units = {}
@staticmethod
def _generate_unit_names():
from ... import units as u
from ...units import required_by_vounit as uvo
names = {}
deprecated_names = set()
bases = [
'A', 'C', 'D', 'F', 'G', 'H', 'Hz', 'J', 'Jy', 'K', 'N',
'Ohm', 'Pa', 'R', 'Ry', 'S', 'T', 'V', 'W', 'Wb', 'a',
'adu', 'arcmin', 'arcsec', 'barn', 'beam', 'bin', 'cd',
'chan', 'count', 'ct', 'd', 'deg', 'eV', 'erg', 'g', 'h',
'lm', 'lx', 'lyr', 'm', 'mag', 'min', 'mol', 'pc', 'ph',
'photon', 'pix', 'pixel', 'rad', 'rad', 's', 'solLum',
'solMass', 'solRad', 'sr', 'u', 'voxel', 'yr'
]
binary_bases = [
'bit', 'byte', 'B'
]
simple_units = [
'Angstrom', 'angstrom', 'AU', 'au', 'Ba', 'dB', 'mas'
]
si_prefixes = [
'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd',
'', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
]
binary_prefixes = [
'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei'
]
deprecated_units = set([
'a', 'angstrom', 'Angstrom', 'au', 'Ba', 'barn', 'ct',
'erg', 'G', 'ph', 'pix'
])
def do_defines(bases, prefixes, skips=[]):
for base in bases:
for prefix in prefixes:
key = prefix + base
if key in skips:
continue
if keyword.iskeyword(key):
continue
names[key] = getattr(u if hasattr(u, key) else uvo, key)
if base in deprecated_units:
deprecated_names.add(key)
do_defines(bases, si_prefixes, ['pct', 'pcount', 'yd'])
do_defines(binary_bases, si_prefixes + binary_prefixes, ['dB', 'dbyte'])
do_defines(simple_units, [''])
return names, deprecated_names, []
@classmethod
def parse(cls, s, debug=False):
if s in ('unknown', 'UNKNOWN'):
return None
if s == '':
return core.dimensionless_unscaled
if s.count('/') > 1:
raise core.UnitsError(
"'{0}' contains multiple slashes, which is "
"disallowed by the VOUnit standard".format(s))
result = cls._do_parse(s, debug=debug)
if hasattr(result, 'function_unit'):
raise ValueError("Function units are not yet supported in "
"VOUnit.")
return result
@classmethod
def _parse_unit(cls, unit, detailed_exception=True):
if unit not in cls._units:
if cls._explicit_custom_unit_regex.match(unit):
return cls._def_custom_unit(unit)
if not cls._custom_unit_regex.match(unit):
raise ValueError()
warnings.warn(
"Unit {0!r} not supported by the VOUnit "
"standard. {1}".format(
unit, utils.did_you_mean_units(
unit, cls._units, cls._deprecated_units,
cls._to_decomposed_alternative)),
core.UnitsWarning)
return cls._def_custom_unit(unit)
if unit in cls._deprecated_units:
utils.unit_deprecation_warning(
unit, cls._units[unit], 'VOUnit',
cls._to_decomposed_alternative)
return cls._units[unit]
@classmethod
def _get_unit_name(cls, unit):
# The da- and d- prefixes are discouraged. This has the
# effect of adding a scale to value in the result.
if isinstance(unit, core.PrefixUnit):
if unit._represents.scale == 10.0:
raise ValueError(
"In '{0}': VOUnit can not represent units with the 'da' "
"(deka) prefix".format(unit))
elif unit._represents.scale == 0.1:
raise ValueError(
"In '{0}': VOUnit can not represent units with the 'd' "
"(deci) prefix".format(unit))
name = unit.get_format_name('vounit')
if unit in cls._custom_units.values():
return name
if name not in cls._units:
raise ValueError(
"Unit {0!r} is not part of the VOUnit standard".format(name))
if name in cls._deprecated_units:
utils.unit_deprecation_warning(
name, unit, 'VOUnit',
cls._to_decomposed_alternative)
return name
@classmethod
def _def_custom_unit(cls, unit):
def def_base(name):
if name in cls._custom_units:
return cls._custom_units[name]
if name.startswith("'"):
return core.def_unit(
[name[1:-1], name],
format={'vounit': name},
namespace=cls._custom_units)
else:
return core.def_unit(
name, namespace=cls._custom_units)
if unit in cls._custom_units:
return cls._custom_units[unit]
for short, full, factor in core.si_prefixes:
for prefix in short:
if unit.startswith(prefix):
base_name = unit[len(prefix):]
base_unit = def_base(base_name)
return core.PrefixUnit(
[prefix + x for x in base_unit.names],
core.CompositeUnit(factor, [base_unit], [1],
_error_check=False),
format={'vounit': prefix + base_unit.names[-1]},
namespace=cls._custom_units)
return def_base(unit)
@classmethod
def to_string(cls, unit):
from .. import core
# Remove units that aren't known to the format
unit = utils.decompose_to_known_units(unit, cls._get_unit_name)
if isinstance(unit, core.CompositeUnit):
if unit.physical_type == 'dimensionless' and unit.scale != 1:
raise core.UnitScaleError(
"The VOUnit format is not able to "
"represent scale for dimensionless units. "
"Multiply your data by {0:e}."
.format(unit.scale))
s = ''
if unit.scale != 1:
m, ex = utils.split_mantissa_exponent(unit.scale)
parts = []
if m:
parts.append(m)
if ex:
fex = '10'
if not ex.startswith('-'):
fex += '+'
fex += ex
parts.append(fex)
s += ' '.join(parts)
pairs = list(zip(unit.bases, unit.powers))
pairs.sort(key=operator.itemgetter(1), reverse=True)
s += cls._format_unit_list(pairs)
elif isinstance(unit, core.NamedUnit):
s = cls._get_unit_name(unit)
return s
@classmethod
def _to_decomposed_alternative(cls, unit):
from .. import core
try:
s = cls.to_string(unit)
except core.UnitScaleError:
scale = unit.scale
unit = copy.copy(unit)
unit._scale = 1.0
return '{0} (with data multiplied by {1})'.format(
cls.to_string(unit), scale)
return s
|
acbf20381e1700365602a04dbf25078a32aaf2f0248452e6e1db7531047065d2 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Handles the "LaTeX" unit format.
"""
import numpy as np
from . import base, core, utils
class Latex(base.Base):
"""
Output LaTeX to display the unit based on IAU style guidelines.
Attempts to follow the `IAU Style Manual
<https://www.iau.org/static/publications/stylemanual1989.pdf>`_.
"""
@classmethod
def _latex_escape(cls, name):
# This doesn't escape arbitrary LaTeX strings, but it should
# be good enough for unit names which are required to be alpha
# + "_" anyway.
return name.replace('_', r'\_')
@classmethod
def _get_unit_name(cls, unit):
name = unit.get_format_name('latex')
if name == unit.name:
return cls._latex_escape(name)
return name
@classmethod
def _format_unit_list(cls, units):
out = []
for base, power in units:
if power == 1:
out.append(cls._get_unit_name(base))
else:
out.append('{0}^{{{1}}}'.format(
cls._get_unit_name(base),
utils.format_power(power)))
return r'\,'.join(out)
@classmethod
def _format_bases(cls, unit):
positives, negatives = utils.get_grouped_by_powers(
unit.bases, unit.powers)
if len(negatives):
if len(positives):
positives = cls._format_unit_list(positives)
else:
positives = '1'
negatives = cls._format_unit_list(negatives)
s = r'\frac{{{0}}}{{{1}}}'.format(positives, negatives)
else:
positives = cls._format_unit_list(positives)
s = positives
return s
@classmethod
def to_string(cls, unit):
latex_name = None
if hasattr(unit, '_format'):
latex_name = unit._format.get('latex')
if latex_name is not None:
s = latex_name
elif isinstance(unit, core.CompositeUnit):
if unit.scale == 1:
s = ''
else:
s = cls.format_exponential_notation(unit.scale) + r'\,'
if len(unit.bases):
s += cls._format_bases(unit)
elif isinstance(unit, core.NamedUnit):
s = cls._latex_escape(unit.name)
return r'$\mathrm{{{0}}}$'.format(s)
@classmethod
def format_exponential_notation(cls, val, format_spec=".8g"):
"""
Formats a value in exponential notation for LaTeX.
Parameters
----------
val : number
The value to be formatted
format_spec : str, optional
Format used to split up mantissa and exponent
Returns
-------
latex_string : str
The value in exponential notation in a format suitable for LaTeX.
"""
if np.isfinite(val):
m, ex = utils.split_mantissa_exponent(val, format_spec)
parts = []
if m:
parts.append(m)
if ex:
parts.append("10^{{{0}}}".format(ex))
return r" \times ".join(parts)
else:
if np.isnan(val):
return r'{\rm NaN}'
elif val > 0:
# positive infinity
return r'\infty'
else:
# negative infinity
return r'-\infty'
class LatexInline(Latex):
"""
Output LaTeX to display the unit based on IAU style guidelines with negative
powers.
Attempts to follow the `IAU Style Manual
<https://www.iau.org/static/publications/stylemanual1989.pdf>`_ and the
`ApJ and AJ style guide
<http://journals.aas.org/authors/manuscript.html>`_.
"""
name = 'latex_inline'
@classmethod
def _format_bases(cls, unit):
return cls._format_unit_list(zip(unit.bases, unit.powers))
|
727470cf3e4fe5b4aa8a9f9af2ae0e9e14efec5240cfa9240df2dd2b68bff3d9 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Handles the "Unicode" unit format.
"""
from . import console, utils
class Unicode(console.Console):
"""
Output-only format to display pretty formatting at the console
using Unicode characters.
For example::
>>> import astropy.units as u
>>> print(u.bar.decompose().to_string('unicode'))
kg
100000 ────
m s²
"""
_times = "×"
_line = "─"
@classmethod
def _get_unit_name(cls, unit):
return unit.get_format_name('unicode')
@classmethod
def format_exponential_notation(cls, val):
m, ex = utils.split_mantissa_exponent(val)
parts = []
if m:
parts.append(m.replace('-', '−'))
if ex:
parts.append("10{0}".format(
cls._format_superscript(ex)))
return cls._times.join(parts)
@classmethod
def _format_superscript(cls, number):
mapping = {
'0': '⁰',
'1': '¹',
'2': '²',
'3': '³',
'4': '⁴',
'5': '⁵',
'6': '⁶',
'7': '⁷',
'8': '⁸',
'9': '⁹',
'-': '⁻',
'−': '⁻',
# This is actually a "raised omission bracket", but it's
# the closest thing I could find to a superscript solidus.
'/': '⸍',
}
output = []
for c in number:
output.append(mapping[c])
return ''.join(output)
|
eae2ef695eb6a14bfae3a8361c461a9691b7a882e60bb813de12ddfedc90d3c2 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
_tabversion = '3.8'
_lextokens = set(('CARET', 'CLOSE_PAREN', 'SOLIDUS', 'FUNCNAME', 'UFLOAT', 'STAR', 'SIGN', 'UINT', 'DOUBLE_STAR', 'OPEN_PAREN', 'PERIOD', 'UNIT'))
_lexreflags = 32
_lexliterals = ''
_lexstateinfo = {'INITIAL': 'inclusive'}
_lexstatere = {'INITIAL': [("(?P<t_UFLOAT>((\\d+\\.?\\d*)|(\\.\\d+))([eE][+-]?\\d+)?)|(?P<t_UINT>\\d+)|(?P<t_SIGN>[+-](?=\\d))|(?P<t_FUNCNAME>((sqrt)|(ln)|(exp)|(log)|(mag)|(dB)|(dex))(?=\\ *\\())|(?P<t_UNIT>%|([YZEPTGMkhdcmunpfazy]?'((?!\\d)\\w)+')|((?!\\d)\\w)+)|(?P<t_DOUBLE_STAR>\\*\\*)|(?P<t_CLOSE_PAREN>\\))|(?P<t_STAR>\\*)|(?P<t_PERIOD>\\.)|(?P<t_OPEN_PAREN>\\()|(?P<t_CARET>\\^)|(?P<t_SOLIDUS>/)", [None, ('t_UFLOAT', 'UFLOAT'), None, None, None, None, ('t_UINT', 'UINT'), ('t_SIGN', 'SIGN'), ('t_FUNCNAME', 'FUNCNAME'), None, None, None, None, None, None, None, None, ('t_UNIT', 'UNIT'), None, None, None, (None, 'DOUBLE_STAR'), (None, 'CLOSE_PAREN'), (None, 'STAR'), (None, 'PERIOD'), (None, 'OPEN_PAREN'), (None, 'CARET'), (None, 'SOLIDUS')])]}
_lexstateignore = {'INITIAL': ' '}
_lexstateerrorf = {'INITIAL': 't_error'}
_lexstateeoff = {}
|
9f61c75ddb89b5b7e26ae513db29a6d9b61285ac9423cbcf831fbb0bbc7ae1cd | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from ...utils.misc import InheritDocstrings
class _FormatterMeta(InheritDocstrings):
registry = {}
def __new__(mcls, name, bases, members):
if 'name' in members:
formatter_name = members['name'].lower()
else:
formatter_name = members['name'] = name.lower()
cls = super().__new__(mcls, name, bases, members)
mcls.registry[formatter_name] = cls
return cls
class Base(metaclass=_FormatterMeta):
"""
The abstract base class of all unit formats.
"""
def __new__(cls, *args, **kwargs):
# This __new__ is to make it clear that there is no reason to
# instantiate a Formatter--if you try to you'll just get back the
# class
return cls
@classmethod
def parse(cls, s):
"""
Convert a string to a unit object.
"""
raise NotImplementedError(
"Can not parse {0}".format(cls.__name__))
@classmethod
def to_string(cls, u):
"""
Convert a unit object to a string.
"""
raise NotImplementedError(
"Can not output in {0} format".format(cls.__name__))
|
0d79ec19f1173dd39e8acc53aa44ea50cd5d489628d872e93fee5bc3e4607722 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICNSE.rst
# Note that files generated by lex/yacc not always fully py 2/3 compatible.
# Hence, the ``clean_parse_tables.py`` tool in the astropy-tools
# (https://github.com/astropy/astropy-tools) repository should be used to fix
# this when/if lextab/parsetab files are re-generated.
"""
Handles units in `Office of Guest Investigator Programs (OGIP)
FITS files
<https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__.
"""
import keyword
import math
import os
import copy
import warnings
from fractions import Fraction
from . import core, generic, utils
class OGIP(generic.Generic):
"""
Support the units in `Office of Guest Investigator Programs (OGIP)
FITS files
<https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__.
"""
_tokens = (
'DIVISION',
'OPEN_PAREN',
'CLOSE_PAREN',
'WHITESPACE',
'STARSTAR',
'STAR',
'SIGN',
'UFLOAT',
'LIT10',
'UINT',
'UNKNOWN',
'UNIT'
)
@staticmethod
def _generate_unit_names():
from ... import units as u
names = {}
deprecated_names = set()
bases = [
'A', 'C', 'cd', 'eV', 'F', 'g', 'H', 'Hz', 'J',
'Jy', 'K', 'lm', 'lx', 'm', 'mol', 'N', 'ohm', 'Pa',
'pc', 'rad', 's', 'S', 'sr', 'T', 'V', 'W', 'Wb'
]
deprecated_bases = []
prefixes = [
'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd',
'', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
]
for base in bases + deprecated_bases:
for prefix in prefixes:
key = prefix + base
if keyword.iskeyword(key):
continue
names[key] = getattr(u, key)
for base in deprecated_bases:
for prefix in prefixes:
deprecated_names.add(prefix + base)
simple_units = [
'angstrom', 'arcmin', 'arcsec', 'AU', 'barn', 'bin',
'byte', 'chan', 'count', 'day', 'deg', 'erg', 'G',
'h', 'lyr', 'mag', 'min', 'photon', 'pixel',
'voxel', 'yr'
]
for unit in simple_units:
names[unit] = getattr(u, unit)
# Create a separate, disconnected unit for the special case of
# Crab and mCrab, since OGIP doesn't define their quantities.
Crab = u.def_unit(['Crab'], prefixes=False, doc='Crab (X-ray flux)')
mCrab = u.Unit(10 ** -3 * Crab)
names['Crab'] = Crab
names['mCrab'] = mCrab
deprecated_units = ['Crab', 'mCrab']
for unit in deprecated_units:
deprecated_names.add(unit)
# Define the function names, so we can parse them, even though
# we can't use any of them (other than sqrt) meaningfully for
# now.
functions = [
'log', 'ln', 'exp', 'sqrt', 'sin', 'cos', 'tan', 'asin',
'acos', 'atan', 'sinh', 'cosh', 'tanh'
]
for name in functions:
names[name] = name
return names, deprecated_names, functions
@classmethod
def _make_lexer(cls):
from ...extern.ply import lex
tokens = cls._tokens
t_DIVISION = r'/'
t_OPEN_PAREN = r'\('
t_CLOSE_PAREN = r'\)'
t_WHITESPACE = '[ \t]+'
t_STARSTAR = r'\*\*'
t_STAR = r'\*'
# NOTE THE ORDERING OF THESE RULES IS IMPORTANT!!
# Regular expression rules for simple tokens
def t_UFLOAT(t):
r'(((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+))|(((\d+\.\d*)|(\.\d+))([eE][+-]?\d+)?)'
t.value = float(t.value)
return t
def t_UINT(t):
r'\d+'
t.value = int(t.value)
return t
def t_SIGN(t):
r'[+-](?=\d)'
t.value = float(t.value + '1')
return t
def t_X(t): # multiplication for factor in front of unit
r'[x×]'
return t
def t_LIT10(t):
r'10'
return 10
def t_UNKNOWN(t):
r'[Uu][Nn][Kk][Nn][Oo][Ww][Nn]'
return None
def t_UNIT(t):
r'[a-zA-Z][a-zA-Z_]*'
t.value = cls._get_unit(t)
return t
# Don't ignore whitespace
t_ignore = ''
# Error handling rule
def t_error(t):
raise ValueError(
"Invalid character at col {0}".format(t.lexpos))
lexer = lex.lex(optimize=True, lextab='ogip_lextab',
outputdir=os.path.dirname(__file__))
return lexer
@classmethod
def _make_parser(cls):
"""
The grammar here is based on the description in the
`Specification of Physical Units within OGIP FITS files
<https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/>`__,
which is not terribly precise. The exact grammar is here is
based on the YACC grammar in the `unity library
<https://bitbucket.org/nxg/unity/>`_.
"""
from ...extern.ply import yacc
tokens = cls._tokens
def p_main(p):
'''
main : UNKNOWN
| complete_expression
| scale_factor complete_expression
| scale_factor WHITESPACE complete_expression
'''
if len(p) == 4:
p[0] = p[1] * p[3]
elif len(p) == 3:
p[0] = p[1] * p[2]
else:
p[0] = p[1]
def p_complete_expression(p):
'''
complete_expression : product_of_units
'''
p[0] = p[1]
def p_product_of_units(p):
'''
product_of_units : unit_expression
| division unit_expression
| product_of_units product unit_expression
| product_of_units division unit_expression
'''
if len(p) == 4:
if p[2] == 'DIVISION':
p[0] = p[1] / p[3]
else:
p[0] = p[1] * p[3]
elif len(p) == 3:
p[0] = p[2] ** -1
else:
p[0] = p[1]
def p_unit_expression(p):
'''
unit_expression : unit
| UNIT OPEN_PAREN complete_expression CLOSE_PAREN
| OPEN_PAREN complete_expression CLOSE_PAREN
| UNIT OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power
| OPEN_PAREN complete_expression CLOSE_PAREN power numeric_power
'''
# If we run p[1] in cls._functions, it will try and parse each
# item in the list into a unit, which is slow. Since we know that
# all the items in the list are strings, we can simply convert
# p[1] to a string instead.
p1_str = str(p[1])
if p1_str in cls._functions and p1_str != 'sqrt':
raise ValueError(
"The function '{0}' is valid in OGIP, but not understood "
"by astropy.units.".format(
p[1]))
if len(p) == 7:
if p1_str == 'sqrt':
p[0] = p[1] * p[3] ** (0.5 * p[6])
else:
p[0] = p[1] * p[3] ** p[6]
elif len(p) == 6:
p[0] = p[2] ** p[5]
elif len(p) == 5:
if p1_str == 'sqrt':
p[0] = p[3] ** 0.5
else:
p[0] = p[1] * p[3]
elif len(p) == 4:
p[0] = p[2]
else:
p[0] = p[1]
def p_scale_factor(p):
'''
scale_factor : LIT10 power numeric_power
| LIT10
| signed_float
| signed_float power numeric_power
| signed_int power numeric_power
'''
if len(p) == 4:
p[0] = 10 ** p[3]
else:
p[0] = p[1]
# Can't use np.log10 here, because p[0] may be a Python long.
if math.log10(p[0]) % 1.0 != 0.0:
from ..core import UnitsWarning
warnings.warn(
"'{0}' scale should be a power of 10 in "
"OGIP format".format(p[0]), UnitsWarning)
def p_division(p):
'''
division : DIVISION
| WHITESPACE DIVISION
| WHITESPACE DIVISION WHITESPACE
| DIVISION WHITESPACE
'''
p[0] = 'DIVISION'
def p_product(p):
'''
product : WHITESPACE
| STAR
| WHITESPACE STAR
| WHITESPACE STAR WHITESPACE
| STAR WHITESPACE
'''
p[0] = 'PRODUCT'
def p_power(p):
'''
power : STARSTAR
'''
p[0] = 'POWER'
def p_unit(p):
'''
unit : UNIT
| UNIT power numeric_power
'''
if len(p) == 4:
p[0] = p[1] ** p[3]
else:
p[0] = p[1]
def p_numeric_power(p):
'''
numeric_power : UINT
| signed_float
| OPEN_PAREN signed_int CLOSE_PAREN
| OPEN_PAREN signed_float CLOSE_PAREN
| OPEN_PAREN signed_float division UINT CLOSE_PAREN
'''
if len(p) == 6:
p[0] = Fraction(int(p[2]), int(p[4]))
elif len(p) == 4:
p[0] = p[2]
else:
p[0] = p[1]
def p_sign(p):
'''
sign : SIGN
|
'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = 1.0
def p_signed_int(p):
'''
signed_int : SIGN UINT
'''
p[0] = p[1] * p[2]
def p_signed_float(p):
'''
signed_float : sign UINT
| sign UFLOAT
'''
p[0] = p[1] * p[2]
def p_error(p):
raise ValueError()
parser = yacc.yacc(debug=False, tabmodule='ogip_parsetab',
outputdir=os.path.dirname(__file__),
write_tables=True)
return parser
@classmethod
def _get_unit(cls, t):
try:
return cls._parse_unit(t.value)
except ValueError as e:
raise ValueError(
"At col {0}, '{1}': {2}".format(
t.lexpos, t.value, str(e)))
@classmethod
def _validate_unit(cls, unit, detailed_exception=True):
if unit not in cls._units:
if detailed_exception:
raise ValueError(
"Unit '{0}' not supported by the OGIP "
"standard. {1}".format(
unit, utils.did_you_mean_units(
unit, cls._units, cls._deprecated_units,
cls._to_decomposed_alternative)))
else:
raise ValueError()
if unit in cls._deprecated_units:
utils.unit_deprecation_warning(
unit, cls._units[unit], 'OGIP',
cls._to_decomposed_alternative)
@classmethod
def _parse_unit(cls, unit, detailed_exception=True):
cls._validate_unit(unit, detailed_exception=detailed_exception)
return cls._units[unit]
@classmethod
def parse(cls, s, debug=False):
s = s.strip()
try:
# This is a short circuit for the case where the string is
# just a single unit name
return cls._parse_unit(s, detailed_exception=False)
except ValueError:
try:
return core.Unit(
cls._parser.parse(s, lexer=cls._lexer, debug=debug))
except ValueError as e:
if str(e):
raise
else:
raise ValueError(
"Syntax error parsing unit '{0}'".format(s))
@classmethod
def _get_unit_name(cls, unit):
name = unit.get_format_name('ogip')
cls._validate_unit(name)
return name
@classmethod
def _format_unit_list(cls, units):
out = []
units.sort(key=lambda x: cls._get_unit_name(x[0]).lower())
for base, power in units:
if power == 1:
out.append(cls._get_unit_name(base))
else:
power = utils.format_power(power)
if '/' in power:
out.append('{0}**({1})'.format(
cls._get_unit_name(base), power))
else:
out.append('{0}**{1}'.format(
cls._get_unit_name(base), power))
return ' '.join(out)
@classmethod
def to_string(cls, unit):
# Remove units that aren't known to the format
unit = utils.decompose_to_known_units(unit, cls._get_unit_name)
if isinstance(unit, core.CompositeUnit):
# Can't use np.log10 here, because p[0] may be a Python long.
if math.log10(unit.scale) % 1.0 != 0.0:
warnings.warn(
"'{0}' scale should be a power of 10 in "
"OGIP format".format(
unit.scale),
core.UnitsWarning)
return generic._to_string(cls, unit)
@classmethod
def _to_decomposed_alternative(cls, unit):
# Remove units that aren't known to the format
unit = utils.decompose_to_known_units(unit, cls._get_unit_name)
if isinstance(unit, core.CompositeUnit):
# Can't use np.log10 here, because p[0] may be a Python long.
if math.log10(unit.scale) % 1.0 != 0.0:
scale = unit.scale
unit = copy.copy(unit)
unit._scale = 1.0
return '{0} (with data multiplied by {1})'.format(
generic._to_string(cls, unit), scale)
return generic._to_string(unit)
|
f84afc9757e2357e935dc9225381db7b3efab69a189738f933c05f5e7ad6fb27 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Utilities shared by the different formats.
"""
import warnings
from fractions import Fraction
from ...utils.misc import did_you_mean
def get_grouped_by_powers(bases, powers):
"""
Groups the powers and bases in the given
`~astropy.units.CompositeUnit` into positive powers and
negative powers for easy display on either side of a solidus.
Parameters
----------
bases : list of `astropy.units.UnitBase` instances
powers : list of ints
Returns
-------
positives, negatives : tuple of lists
Each element in each list is tuple of the form (*base*,
*power*). The negatives have the sign of their power reversed
(i.e. the powers are all positive).
"""
positive = []
negative = []
for base, power in zip(bases, powers):
if power < 0:
negative.append((base, -power))
elif power > 0:
positive.append((base, power))
else:
raise ValueError("Unit with 0 power")
return positive, negative
def split_mantissa_exponent(v, format_spec=".8g"):
"""
Given a number, split it into its mantissa and base 10 exponent
parts, each as strings. If the exponent is too small, it may be
returned as the empty string.
Parameters
----------
v : float
format_spec : str, optional
Number representation formatting string
Returns
-------
mantissa, exponent : tuple of strings
"""
x = format(v, format_spec).split('e')
if x[0] != '1.' + '0' * (len(x[0]) - 2):
m = x[0]
else:
m = ''
if len(x) == 2:
ex = x[1].lstrip("0+")
if len(ex) > 0 and ex[0] == '-':
ex = '-' + ex[1:].lstrip('0')
else:
ex = ''
return m, ex
def decompose_to_known_units(unit, func):
"""
Partially decomposes a unit so it is only composed of units that
are "known" to a given format.
Parameters
----------
unit : `~astropy.units.UnitBase` instance
func : callable
This function will be called to determine if a given unit is
"known". If the unit is not known, this function should raise a
`ValueError`.
Returns
-------
unit : `~astropy.units.UnitBase` instance
A flattened unit.
"""
from .. import core
if isinstance(unit, core.CompositeUnit):
new_unit = core.Unit(unit.scale)
for base, power in zip(unit.bases, unit.powers):
new_unit = new_unit * decompose_to_known_units(base, func) ** power
return new_unit
elif isinstance(unit, core.NamedUnit):
try:
func(unit)
except ValueError:
if isinstance(unit, core.Unit):
return decompose_to_known_units(unit._represents, func)
raise
return unit
def format_power(power):
"""
Converts a value for a power (which may be floating point or a
`fractions.Fraction` object), into a string either looking like
an integer or a fraction.
"""
if not isinstance(power, Fraction):
if power % 1.0 != 0.0:
frac = Fraction.from_float(power)
power = frac.limit_denominator(10)
if power.denominator == 1:
power = int(power.numerator)
else:
power = int(power)
return str(power)
def _try_decomposed(unit, format_decomposed):
represents = getattr(unit, '_represents', None)
if represents is not None:
try:
represents_string = format_decomposed(represents)
except ValueError:
pass
else:
return represents_string
decomposed = unit.decompose()
if decomposed is not unit:
try:
decompose_string = format_decomposed(decomposed)
except ValueError:
pass
else:
return decompose_string
return None
def did_you_mean_units(s, all_units, deprecated_units, format_decomposed):
"""
A wrapper around `astropy.utils.misc.did_you_mean` that deals with
the display of deprecated units.
Parameters
----------
s : str
The invalid unit string
all_units : dict
A mapping from valid unit names to unit objects.
deprecated_units : sequence
The deprecated unit names
format_decomposed : callable
A function to turn a decomposed version of the unit into a
string. Should return `None` if not possible
Returns
-------
msg : str
A string message with a list of alternatives, or the empty
string.
"""
def fix_deprecated(x):
if x in deprecated_units:
results = [x + ' (deprecated)']
decomposed = _try_decomposed(
all_units[x], format_decomposed)
if decomposed is not None:
results.append(decomposed)
return results
return (x,)
return did_you_mean(s, all_units, fix=fix_deprecated)
def unit_deprecation_warning(s, unit, standard_name, format_decomposed):
"""
Raises a UnitsWarning about a deprecated unit in a given format.
Suggests a decomposed alternative if one is available.
Parameters
----------
s : str
The deprecated unit name.
unit : astropy.units.core.UnitBase
The unit object.
standard_name : str
The name of the format for which the unit is deprecated.
format_decomposed : callable
A function to turn a decomposed version of the unit into a
string. Should return `None` if not possible
"""
from ..core import UnitsWarning
message = "The unit '{0}' has been deprecated in the {1} standard.".format(
s, standard_name)
decomposed = _try_decomposed(unit, format_decomposed)
if decomposed is not None:
message += " Suggested: {0}.".format(decomposed)
warnings.warn(message, UnitsWarning)
|
bd98aabe9aab967b7c0b6ae1631fcd31ce895951f0be4d368d777a473a67adf7 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# This file is automatically generated. Do not edit.
_tabversion = '3.8'
_lr_method = 'LALR'
_lr_signature = '6FC211F72F2851FC3FF7D2BFF951FE7A'
_lr_action_items = {'UINT':([0,2,3,14,15,16,19,23,],[1,-21,20,-20,28,29,30,32,]),'PRODUCT':([2,12,13,18,30,31,],[-18,-10,27,-17,-19,-11,]),'CLOSE_PAREN':([2,7,8,12,13,18,22,25,30,31,33,34,],[-18,-4,-5,-10,-7,-17,31,-8,-19,-11,-9,-6,]),'UNIT':([0,1,5,6,10,11,17,20,21,26,27,28,35,36,],[2,-15,2,-16,2,2,-14,-23,-24,2,2,-22,-13,-12,]),'OPEN_PAREN':([0,1,5,6,10,11,17,20,21,26,27,28,35,36,],[5,-15,5,-16,5,5,-14,-23,-24,5,5,-22,-13,-12,]),'$end':([1,2,4,6,7,8,9,10,12,13,17,18,20,21,24,25,28,30,31,33,34,35,36,],[-15,-18,-2,-16,-4,-5,0,-3,-10,-7,-14,-17,-23,-24,-1,-8,-22,-19,-11,-9,-6,-13,-12,]),'DIVISION':([0,1,2,5,6,10,12,13,17,18,20,21,26,27,28,30,31,35,36,],[11,-15,-18,11,-16,11,-10,26,-14,-17,-23,-24,11,11,-22,-19,-11,-13,-12,]),'UFLOAT':([0,3,14,],[-21,21,-20,]),'X':([1,6,20,21,],[16,23,-23,-24,]),'SIGN':([0,1,2,29,32,],[14,15,14,15,15,]),}
_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 = {'division_of_units':([0,5,10,26,27,],[8,8,8,8,8,]),'main':([0,],[9,]),'combined_units':([0,5,10,26,27,],[4,22,24,33,34,]),'factor':([0,],[10,]),'signed_float':([0,],[6,]),'unit_with_power':([0,5,10,11,26,27,],[12,12,12,12,12,12,]),'product_of_units':([0,5,10,26,27,],[7,7,7,7,7,]),'signed_int':([1,29,32,],[17,35,36,]),'numeric_power':([2,],[18,]),'unit_expression':([0,5,10,11,26,27,],[13,13,13,25,13,13,]),'sign':([0,2,],[3,19,]),}
_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' -> main","S'",1,None,None,None),
('main -> factor combined_units','main',2,'p_main','cds.py',150),
('main -> combined_units','main',1,'p_main','cds.py',151),
('main -> factor','main',1,'p_main','cds.py',152),
('combined_units -> product_of_units','combined_units',1,'p_combined_units','cds.py',162),
('combined_units -> division_of_units','combined_units',1,'p_combined_units','cds.py',163),
('product_of_units -> unit_expression PRODUCT combined_units','product_of_units',3,'p_product_of_units','cds.py',169),
('product_of_units -> unit_expression','product_of_units',1,'p_product_of_units','cds.py',170),
('division_of_units -> DIVISION unit_expression','division_of_units',2,'p_division_of_units','cds.py',179),
('division_of_units -> unit_expression DIVISION combined_units','division_of_units',3,'p_division_of_units','cds.py',180),
('unit_expression -> unit_with_power','unit_expression',1,'p_unit_expression','cds.py',189),
('unit_expression -> OPEN_PAREN combined_units CLOSE_PAREN','unit_expression',3,'p_unit_expression','cds.py',190),
('factor -> signed_float X UINT signed_int','factor',4,'p_factor','cds.py',199),
('factor -> UINT X UINT signed_int','factor',4,'p_factor','cds.py',200),
('factor -> UINT signed_int','factor',2,'p_factor','cds.py',201),
('factor -> UINT','factor',1,'p_factor','cds.py',202),
('factor -> signed_float','factor',1,'p_factor','cds.py',203),
('unit_with_power -> UNIT numeric_power','unit_with_power',2,'p_unit_with_power','cds.py',220),
('unit_with_power -> UNIT','unit_with_power',1,'p_unit_with_power','cds.py',221),
('numeric_power -> sign UINT','numeric_power',2,'p_numeric_power','cds.py',230),
('sign -> SIGN','sign',1,'p_sign','cds.py',236),
('sign -> <empty>','sign',0,'p_sign','cds.py',237),
('signed_int -> SIGN UINT','signed_int',2,'p_signed_int','cds.py',246),
('signed_float -> sign UINT','signed_float',2,'p_signed_float','cds.py',252),
('signed_float -> sign UFLOAT','signed_float',2,'p_signed_float','cds.py',253),
]
|
653935f547791bf9ab0bffe2435a9a7ffa99f05f25b84aeb60893a701c313f3d | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Handles the "FITS" unit format.
"""
import numpy as np
import copy
import keyword
import operator
from . import core, generic, utils
class Fits(generic.Generic):
"""
The FITS standard unit format.
This supports the format defined in the Units section of the `FITS
Standard <https://fits.gsfc.nasa.gov/fits_standard.html>`_.
"""
name = 'fits'
@staticmethod
def _generate_unit_names():
from ... import units as u
names = {}
deprecated_names = set()
# Note about deprecated units: before v2.0, several units were treated
# as deprecated (G, barn, erg, Angstrom, angstrom). However, in the
# FITS 3.0 standard, these units are explicitly listed in the allowed
# units, but deprecated in the IAU Style Manual (McNally 1988). So
# after discussion (https://github.com/astropy/astropy/issues/2933),
# these units have been removed from the lists of deprecated units and
# bases.
bases = [
'm', 'g', 's', 'rad', 'sr', 'K', 'A', 'mol', 'cd',
'Hz', 'J', 'W', 'V', 'N', 'Pa', 'C', 'Ohm', 'S',
'F', 'Wb', 'T', 'H', 'lm', 'lx', 'a', 'yr', 'eV',
'pc', 'Jy', 'mag', 'R', 'bit', 'byte', 'G', 'barn'
]
deprecated_bases = []
prefixes = [
'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', 'c', 'd',
'', 'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
special_cases = {'dbyte': u.Unit('dbyte', 0.1*u.byte)}
for base in bases + deprecated_bases:
for prefix in prefixes:
key = prefix + base
if keyword.iskeyword(key):
continue
elif key in special_cases:
names[key] = special_cases[key]
else:
names[key] = getattr(u, key)
for base in deprecated_bases:
for prefix in prefixes:
deprecated_names.add(prefix + base)
simple_units = [
'deg', 'arcmin', 'arcsec', 'mas', 'min', 'h', 'd', 'Ry',
'solMass', 'u', 'solLum', 'solRad', 'AU', 'lyr', 'count',
'ct', 'photon', 'ph', 'pixel', 'pix', 'D', 'Sun', 'chan',
'bin', 'voxel', 'adu', 'beam', 'erg', 'Angstrom', 'angstrom'
]
deprecated_units = []
for unit in simple_units + deprecated_units:
names[unit] = getattr(u, unit)
for unit in deprecated_units:
deprecated_names.add(unit)
return names, deprecated_names, []
@classmethod
def _validate_unit(cls, unit, detailed_exception=True):
if unit not in cls._units:
if detailed_exception:
raise ValueError(
"Unit '{0}' not supported by the FITS standard. {1}".format(
unit, utils.did_you_mean_units(
unit, cls._units, cls._deprecated_units,
cls._to_decomposed_alternative)))
else:
raise ValueError()
if unit in cls._deprecated_units:
utils.unit_deprecation_warning(
unit, cls._units[unit], 'FITS',
cls._to_decomposed_alternative)
@classmethod
def _parse_unit(cls, unit, detailed_exception=True):
cls._validate_unit(unit)
return cls._units[unit]
@classmethod
def _get_unit_name(cls, unit):
name = unit.get_format_name('fits')
cls._validate_unit(name)
return name
@classmethod
def to_string(cls, unit):
# Remove units that aren't known to the format
unit = utils.decompose_to_known_units(unit, cls._get_unit_name)
parts = []
if isinstance(unit, core.CompositeUnit):
base = np.log10(unit.scale)
if base % 1.0 != 0.0:
raise core.UnitScaleError(
"The FITS unit format is not able to represent scales "
"that are not powers of 10. Multiply your data by "
"{0:e}.".format(unit.scale))
elif unit.scale != 1.0:
parts.append('10**{0}'.format(int(base)))
pairs = list(zip(unit.bases, unit.powers))
if len(pairs):
pairs.sort(key=operator.itemgetter(1), reverse=True)
parts.append(cls._format_unit_list(pairs))
s = ' '.join(parts)
elif isinstance(unit, core.NamedUnit):
s = cls._get_unit_name(unit)
return s
@classmethod
def _to_decomposed_alternative(cls, unit):
try:
s = cls.to_string(unit)
except core.UnitScaleError:
scale = unit.scale
unit = copy.copy(unit)
unit._scale = 1.0
return '{0} (with data multiplied by {1})'.format(
cls.to_string(unit), scale)
return s
@classmethod
def parse(cls, s, debug=False):
result = super().parse(s, debug)
if hasattr(result, 'function_unit'):
raise ValueError("Function units are not yet supported for "
"FITS units.")
return result
|
b6c8c93c4634356ecd4143b5a87ec7ed7c5dcaa1788de79778b8d518906c21f5 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# Note that files generated by lex/yacc not always fully py 2/3 compatible.
# Hence, the ``clean_parse_tables.py`` tool in the astropy-tools
# (https://github.com/astropy/astropy-tools) repository should be used to fix
# this when/if lextab/parsetab files are re-generated.
"""
Handles a "generic" string format for units
"""
import os
import re
import warnings
from . import core, utils
from .base import Base
from ...utils import classproperty
from ...utils.misc import did_you_mean
def _to_string(cls, unit):
if isinstance(unit, core.CompositeUnit):
parts = []
if cls._show_scale and unit.scale != 1:
parts.append('{0:g}'.format(unit.scale))
if len(unit.bases):
positives, negatives = utils.get_grouped_by_powers(
unit.bases, unit.powers)
if len(positives):
parts.append(cls._format_unit_list(positives))
elif len(parts) == 0:
parts.append('1')
if len(negatives):
parts.append('/')
unit_list = cls._format_unit_list(negatives)
if len(negatives) == 1:
parts.append('{0}'.format(unit_list))
else:
parts.append('({0})'.format(unit_list))
return ' '.join(parts)
elif isinstance(unit, core.NamedUnit):
return cls._get_unit_name(unit)
class Generic(Base):
"""
A "generic" format.
The syntax of the format is based directly on the FITS standard,
but instead of only supporting the units that FITS knows about, it
supports any unit available in the `astropy.units` namespace.
"""
_show_scale = True
_tokens = (
'DOUBLE_STAR',
'STAR',
'PERIOD',
'SOLIDUS',
'CARET',
'OPEN_PAREN',
'CLOSE_PAREN',
'FUNCNAME',
'UNIT',
'SIGN',
'UINT',
'UFLOAT'
)
@classproperty(lazy=True)
def _all_units(cls):
return cls._generate_unit_names()
@classproperty(lazy=True)
def _units(cls):
return cls._all_units[0]
@classproperty(lazy=True)
def _deprecated_units(cls):
return cls._all_units[1]
@classproperty(lazy=True)
def _functions(cls):
return cls._all_units[2]
@classproperty(lazy=True)
def _parser(cls):
return cls._make_parser()
@classproperty(lazy=True)
def _lexer(cls):
return cls._make_lexer()
@classmethod
def _make_lexer(cls):
from ...extern.ply import lex
tokens = cls._tokens
t_STAR = r'\*'
t_PERIOD = r'\.'
t_SOLIDUS = r'/'
t_DOUBLE_STAR = r'\*\*'
t_CARET = r'\^'
t_OPEN_PAREN = r'\('
t_CLOSE_PAREN = r'\)'
# NOTE THE ORDERING OF THESE RULES IS IMPORTANT!!
# Regular expression rules for simple tokens
def t_UFLOAT(t):
r'((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+)?'
if not re.search(r'[eE\.]', t.value):
t.type = 'UINT'
t.value = int(t.value)
elif t.value.endswith('.'):
t.type = 'UINT'
t.value = int(t.value[:-1])
else:
t.value = float(t.value)
return t
def t_UINT(t):
r'\d+'
t.value = int(t.value)
return t
def t_SIGN(t):
r'[+-](?=\d)'
t.value = float(t.value + '1')
return t
# This needs to be a function so we can force it to happen
# before t_UNIT
def t_FUNCNAME(t):
r'((sqrt)|(ln)|(exp)|(log)|(mag)|(dB)|(dex))(?=\ *\()'
return t
def t_UNIT(t):
r"%|([YZEPTGMkhdcmunpfazy]?'((?!\d)\w)+')|((?!\d)\w)+"
t.value = cls._get_unit(t)
return t
t_ignore = ' '
# Error handling rule
def t_error(t):
raise ValueError(
"Invalid character at col {0}".format(t.lexpos))
lexer = lex.lex(optimize=True, lextab='generic_lextab',
outputdir=os.path.dirname(__file__),
reflags=re.UNICODE)
return lexer
@classmethod
def _make_parser(cls):
"""
The grammar here is based on the description in the `FITS
standard
<http://fits.gsfc.nasa.gov/standard30/fits_standard30aa.pdf>`_,
Section 4.3, which is not terribly precise. The exact grammar
is here is based on the YACC grammar in the `unity library
<https://bitbucket.org/nxg/unity/>`_.
This same grammar is used by the `"fits"` and `"vounit"`
formats, the only difference being the set of available unit
strings.
"""
from ...extern.ply import yacc
tokens = cls._tokens
def p_main(p):
'''
main : product_of_units
| factor product_of_units
| factor product product_of_units
| division_product_of_units
| factor division_product_of_units
| factor product division_product_of_units
| inverse_unit
| factor inverse_unit
| factor product inverse_unit
| factor
'''
from ..core import Unit
if len(p) == 2:
p[0] = Unit(p[1])
elif len(p) == 3:
p[0] = Unit(p[1] * p[2])
elif len(p) == 4:
p[0] = Unit(p[1] * p[3])
def p_division_product_of_units(p):
'''
division_product_of_units : division_product_of_units division product_of_units
| product_of_units
'''
from ..core import Unit
if len(p) == 4:
p[0] = Unit(p[1] / p[3])
else:
p[0] = p[1]
def p_inverse_unit(p):
'''
inverse_unit : division unit_expression
'''
p[0] = p[2] ** -1
def p_factor(p):
'''
factor : factor_fits
| factor_float
| factor_int
'''
p[0] = p[1]
def p_factor_float(p):
'''
factor_float : signed_float
| signed_float UINT signed_int
| signed_float UINT power numeric_power
'''
if cls.name == 'fits':
raise ValueError("Numeric factor not supported by FITS")
if len(p) == 4:
p[0] = p[1] * p[2] ** float(p[3])
elif len(p) == 5:
p[0] = p[1] * p[2] ** float(p[4])
elif len(p) == 2:
p[0] = p[1]
def p_factor_int(p):
'''
factor_int : UINT
| UINT signed_int
| UINT power numeric_power
| UINT UINT signed_int
| UINT UINT power numeric_power
'''
if cls.name == 'fits':
raise ValueError("Numeric factor not supported by FITS")
if len(p) == 2:
p[0] = p[1]
elif len(p) == 3:
p[0] = p[1] ** float(p[2])
elif len(p) == 4:
if isinstance(p[2], int):
p[0] = p[1] * p[2] ** float(p[3])
else:
p[0] = p[1] ** float(p[3])
elif len(p) == 5:
p[0] = p[1] * p[2] ** p[4]
def p_factor_fits(p):
'''
factor_fits : UINT power OPEN_PAREN signed_int CLOSE_PAREN
| UINT power signed_int
| UINT SIGN UINT
| UINT OPEN_PAREN signed_int CLOSE_PAREN
'''
if p[1] != 10:
if cls.name == 'fits':
raise ValueError("Base must be 10")
else:
return
if len(p) == 4:
if p[2] in ('**', '^'):
p[0] = 10 ** p[3]
else:
p[0] = 10 ** (p[2] * p[3])
elif len(p) == 5:
p[0] = 10 ** p[3]
elif len(p) == 6:
p[0] = 10 ** p[4]
def p_product_of_units(p):
'''
product_of_units : unit_expression product product_of_units
| unit_expression product_of_units
| unit_expression
'''
if len(p) == 2:
p[0] = p[1]
elif len(p) == 3:
p[0] = p[1] * p[2]
else:
p[0] = p[1] * p[3]
def p_unit_expression(p):
'''
unit_expression : function
| unit_with_power
| OPEN_PAREN product_of_units CLOSE_PAREN
'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = p[2]
def p_unit_with_power(p):
'''
unit_with_power : UNIT power numeric_power
| UNIT numeric_power
| UNIT
'''
if len(p) == 2:
p[0] = p[1]
elif len(p) == 3:
p[0] = p[1] ** p[2]
else:
p[0] = p[1] ** p[3]
def p_numeric_power(p):
'''
numeric_power : sign UINT
| OPEN_PAREN paren_expr CLOSE_PAREN
'''
if len(p) == 3:
p[0] = p[1] * p[2]
elif len(p) == 4:
p[0] = p[2]
def p_paren_expr(p):
'''
paren_expr : sign UINT
| signed_float
| frac
'''
if len(p) == 3:
p[0] = p[1] * p[2]
else:
p[0] = p[1]
def p_frac(p):
'''
frac : sign UINT division sign UINT
'''
p[0] = (p[1] * p[2]) / (p[4] * p[5])
def p_sign(p):
'''
sign : SIGN
|
'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = 1.0
def p_product(p):
'''
product : STAR
| PERIOD
'''
pass
def p_division(p):
'''
division : SOLIDUS
'''
pass
def p_power(p):
'''
power : DOUBLE_STAR
| CARET
'''
p[0] = p[1]
def p_signed_int(p):
'''
signed_int : SIGN UINT
'''
p[0] = p[1] * p[2]
def p_signed_float(p):
'''
signed_float : sign UINT
| sign UFLOAT
'''
p[0] = p[1] * p[2]
def p_function_name(p):
'''
function_name : FUNCNAME
'''
p[0] = p[1]
def p_function(p):
'''
function : function_name OPEN_PAREN main CLOSE_PAREN
'''
if p[1] == 'sqrt':
p[0] = p[3] ** 0.5
return
elif p[1] in ('mag', 'dB', 'dex'):
function_unit = cls._parse_unit(p[1])
# In Generic, this is callable, but that does not have to
# be the case in subclasses (e.g., in VOUnit it is not).
if callable(function_unit):
p[0] = function_unit(p[3])
return
raise ValueError("'{0}' is not a recognized function".format(p[1]))
def p_error(p):
raise ValueError()
parser = yacc.yacc(debug=False, tabmodule='generic_parsetab',
outputdir=os.path.dirname(__file__))
return parser
@classmethod
def _get_unit(cls, t):
try:
return cls._parse_unit(t.value)
except ValueError as e:
raise ValueError(
"At col {0}, {1}".format(
t.lexpos, str(e)))
@classmethod
def _parse_unit(cls, s, detailed_exception=True):
registry = core.get_current_unit_registry().registry
if s == '%':
return registry['percent']
elif s in registry:
return registry[s]
if detailed_exception:
raise ValueError(
'{0} is not a valid unit. {1}'.format(
s, did_you_mean(s, registry)))
else:
raise ValueError()
@classmethod
def parse(cls, s, debug=False):
if not isinstance(s, str):
s = s.decode('ascii')
result = cls._do_parse(s, debug=debug)
if s.count('/') > 1:
warnings.warn(
"'{0}' contains multiple slashes, which is "
"discouraged by the FITS standard".format(s),
core.UnitsWarning)
return result
@classmethod
def _do_parse(cls, s, debug=False):
try:
# This is a short circuit for the case where the string
# is just a single unit name
return cls._parse_unit(s, detailed_exception=False)
except ValueError as e:
try:
return cls._parser.parse(s, lexer=cls._lexer, debug=debug)
except ValueError as e:
if str(e):
raise
else:
raise ValueError(
"Syntax error parsing unit '{0}'".format(s))
@classmethod
def _get_unit_name(cls, unit):
return unit.get_format_name('generic')
@classmethod
def _format_unit_list(cls, units):
out = []
units.sort(key=lambda x: cls._get_unit_name(x[0]).lower())
for base, power in units:
if power == 1:
out.append(cls._get_unit_name(base))
else:
power = utils.format_power(power)
if '/' in power:
out.append('{0}({1})'.format(
cls._get_unit_name(base), power))
else:
out.append('{0}{1}'.format(
cls._get_unit_name(base), power))
return ' '.join(out)
@classmethod
def to_string(cls, unit):
return _to_string(cls, unit)
class Unscaled(Generic):
"""
A format that doesn't display the scale part of the unit, other
than that, it is identical to the `Generic` format.
This is used in some error messages where the scale is irrelevant.
"""
_show_scale = False
|
319cd9387a9f00b05702c7b4b36e54a60657e3ddc65135abcae8272618178591 | # coding: utf-8
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Separate tests specifically for equivalencies."""
# THIRD-PARTY
import warnings
import pytest
import numpy as np
from numpy.testing.utils import assert_allclose
# LOCAL
from ... import units as u
from ... import constants
from ...tests.helper import assert_quantity_allclose
def test_dimensionless_angles():
# test that the angles_dimensionless option allows one to change
# by any order in radian in the unit (#1161)
rad1 = u.dimensionless_angles()
assert u.radian.to(1, equivalencies=rad1) == 1.
assert u.deg.to(1, equivalencies=rad1) == u.deg.to(u.rad)
assert u.steradian.to(1, equivalencies=rad1) == 1.
assert u.dimensionless_unscaled.to(u.steradian, equivalencies=rad1) == 1.
# now quantities
assert (1.*u.radian).to_value(1, equivalencies=rad1) == 1.
assert (1.*u.deg).to_value(1, equivalencies=rad1) == u.deg.to(u.rad)
assert (1.*u.steradian).to_value(1, equivalencies=rad1) == 1.
# more complicated example
I = 1.e45 * u.g * u.cm**2
Omega = u.cycle / (1.*u.s)
Erot = 0.5 * I * Omega**2
# check that equivalency makes this work
Erot_in_erg1 = Erot.to(u.erg, equivalencies=rad1)
# and check that value is correct
assert_allclose(Erot_in_erg1.value, (Erot/u.radian**2).to_value(u.erg))
# test build-in equivalency in subclass
class MyRad1(u.Quantity):
_equivalencies = rad1
phase = MyRad1(1., u.cycle)
assert phase.to_value(1) == u.cycle.to(u.radian)
@pytest.mark.parametrize('log_unit', (u.mag, u.dex, u.dB))
def test_logarithmic(log_unit):
# check conversion of mag, dB, and dex to dimensionless and vice versa
with pytest.raises(u.UnitsError):
log_unit.to(1, 0.)
with pytest.raises(u.UnitsError):
u.dimensionless_unscaled.to(log_unit)
assert log_unit.to(1, 0., equivalencies=u.logarithmic()) == 1.
assert u.dimensionless_unscaled.to(log_unit,
equivalencies=u.logarithmic()) == 0.
# also try with quantities
q_dex = np.array([0., -1., 1., 2.]) * u.dex
q_expected = 10.**q_dex.value * u.dimensionless_unscaled
q_log_unit = q_dex.to(log_unit)
assert np.all(q_log_unit.to(1, equivalencies=u.logarithmic()) ==
q_expected)
assert np.all(q_expected.to(log_unit, equivalencies=u.logarithmic()) ==
q_log_unit)
with u.set_enabled_equivalencies(u.logarithmic()):
assert np.all(np.abs(q_log_unit - q_expected.to(log_unit)) <
1.e-10*log_unit)
doppler_functions = [u.doppler_optical, u.doppler_radio, u.doppler_relativistic]
@pytest.mark.parametrize(('function'), doppler_functions)
def test_doppler_frequency_0(function):
rest = 105.01 * u.GHz
velo0 = rest.to(u.km/u.s, equivalencies=function(rest))
assert velo0.value == 0
@pytest.mark.parametrize(('function'), doppler_functions)
def test_doppler_wavelength_0(function):
rest = 105.01 * u.GHz
q1 = 0.00285489437196 * u.m
velo0 = q1.to(u.km/u.s, equivalencies=function(rest))
np.testing.assert_almost_equal(velo0.value, 0, decimal=6)
@pytest.mark.parametrize(('function'), doppler_functions)
def test_doppler_energy_0(function):
rest = 105.01 * u.GHz
q1 = 0.0004342864612223407 * u.eV
velo0 = q1.to(u.km/u.s, equivalencies=function(rest))
np.testing.assert_almost_equal(velo0.value, 0, decimal=6)
@pytest.mark.parametrize(('function'), doppler_functions)
def test_doppler_frequency_circle(function):
rest = 105.01 * u.GHz
shifted = 105.03 * u.GHz
velo = shifted.to(u.km/u.s, equivalencies=function(rest))
freq = velo.to(u.GHz, equivalencies=function(rest))
np.testing.assert_almost_equal(freq.value, shifted.value, decimal=7)
@pytest.mark.parametrize(('function'), doppler_functions)
def test_doppler_wavelength_circle(function):
rest = 105.01 * u.nm
shifted = 105.03 * u.nm
velo = shifted.to(u.km / u.s, equivalencies=function(rest))
wav = velo.to(u.nm, equivalencies=function(rest))
np.testing.assert_almost_equal(wav.value, shifted.value, decimal=7)
@pytest.mark.parametrize(('function'), doppler_functions)
def test_doppler_energy_circle(function):
rest = 1.0501 * u.eV
shifted = 1.0503 * u.eV
velo = shifted.to(u.km / u.s, equivalencies=function(rest))
en = velo.to(u.eV, equivalencies=function(rest))
np.testing.assert_almost_equal(en.value, shifted.value, decimal=7)
values_ghz = (999.899940784289, 999.8999307714406, 999.8999357778647)
@pytest.mark.parametrize(('function', 'value'),
list(zip(doppler_functions, values_ghz)))
def test_30kms(function, value):
rest = 1000 * u.GHz
velo = 30 * u.km/u.s
shifted = velo.to(u.GHz, equivalencies=function(rest))
np.testing.assert_almost_equal(shifted.value, value, decimal=7)
bad_values = (5, 5*u.Jy, None)
@pytest.mark.parametrize(('function', 'value'),
list(zip(doppler_functions, bad_values)))
def test_bad_restfreqs(function, value):
with pytest.raises(u.UnitsError):
function(value)
def test_massenergy():
# The relative tolerance of these tests is set by the uncertainties
# in the charge of the electron, which is known to about
# 3e-9 (relative tolerance). Therefore, we limit the
# precision of the tests to 1e-7 to be safe. The masses are
# (loosely) known to ~ 5e-8 rel tolerance, so we couldn't test to
# 1e-7 if we used the values from astropy.constants; that is,
# they might change by more than 1e-7 in some future update, so instead
# they are hardwired here.
# Electron, proton, neutron, muon, 1g
mass_eV = u.Quantity([510.998928e3, 938.272046e6, 939.565378e6,
105.6583715e6, 5.60958884539e32], u.eV)
mass_g = u.Quantity([9.10938291e-28, 1.672621777e-24, 1.674927351e-24,
1.88353147e-25, 1], u.g)
# Test both ways
assert np.allclose(mass_eV.to_value(u.g, equivalencies=u.mass_energy()),
mass_g.value, rtol=1e-7)
assert np.allclose(mass_g.to_value(u.eV, equivalencies=u.mass_energy()),
mass_eV.value, rtol=1e-7)
# Basic tests of 'derived' equivalencies
# Surface density
sdens_eV = u.Quantity(5.60958884539e32, u.eV / u.m**2)
sdens_g = u.Quantity(1e-4, u.g / u.cm**2)
assert np.allclose(sdens_eV.to_value(u.g / u.cm**2,
equivalencies=u.mass_energy()),
sdens_g.value, rtol=1e-7)
assert np.allclose(sdens_g.to_value(u.eV / u.m**2,
equivalencies=u.mass_energy()),
sdens_eV.value, rtol=1e-7)
# Density
dens_eV = u.Quantity(5.60958884539e32, u.eV / u.m**3)
dens_g = u.Quantity(1e-6, u.g / u.cm**3)
assert np.allclose(dens_eV.to_value(u.g / u.cm**3,
equivalencies=u.mass_energy()),
dens_g.value, rtol=1e-7)
assert np.allclose(dens_g.to_value(u.eV / u.m**3,
equivalencies=u.mass_energy()),
dens_eV.value, rtol=1e-7)
# Power
pow_eV = u.Quantity(5.60958884539e32, u.eV / u.s)
pow_g = u.Quantity(1, u.g / u.s)
assert np.allclose(pow_eV.to_value(u.g / u.s,
equivalencies=u.mass_energy()),
pow_g.value, rtol=1e-7)
assert np.allclose(pow_g.to_value(u.eV / u.s,
equivalencies=u.mass_energy()),
pow_eV.value, rtol=1e-7)
def test_is_equivalent():
assert u.m.is_equivalent(u.pc)
assert u.cycle.is_equivalent(u.mas)
assert not u.cycle.is_equivalent(u.dimensionless_unscaled)
assert u.cycle.is_equivalent(u.dimensionless_unscaled,
u.dimensionless_angles())
assert not (u.Hz.is_equivalent(u.J))
assert u.Hz.is_equivalent(u.J, u.spectral())
assert u.J.is_equivalent(u.Hz, u.spectral())
assert u.pc.is_equivalent(u.arcsecond, u.parallax())
assert u.arcminute.is_equivalent(u.au, u.parallax())
# Pass a tuple for multiple possibilities
assert u.cm.is_equivalent((u.m, u.s, u.kg))
assert u.ms.is_equivalent((u.m, u.s, u.kg))
assert u.g.is_equivalent((u.m, u.s, u.kg))
assert not u.L.is_equivalent((u.m, u.s, u.kg))
assert not (u.km / u.s).is_equivalent((u.m, u.s, u.kg))
def test_parallax():
a = u.arcsecond.to(u.pc, 10, u.parallax())
assert_allclose(a, 0.10)
b = u.pc.to(u.arcsecond, a, u.parallax())
assert_allclose(b, 10)
a = u.arcminute.to(u.au, 1, u.parallax())
assert_allclose(a, 3437.7467916)
b = u.au.to(u.arcminute, a, u.parallax())
assert_allclose(b, 1)
def test_parallax2():
a = u.arcsecond.to(u.pc, [0.1, 2.5], u.parallax())
assert_allclose(a, [10, 0.4])
def test_spectral():
a = u.AA.to(u.Hz, 1, u.spectral())
assert_allclose(a, 2.9979245799999995e+18)
b = u.Hz.to(u.AA, a, u.spectral())
assert_allclose(b, 1)
a = u.AA.to(u.MHz, 1, u.spectral())
assert_allclose(a, 2.9979245799999995e+12)
b = u.MHz.to(u.AA, a, u.spectral())
assert_allclose(b, 1)
a = u.m.to(u.Hz, 1, u.spectral())
assert_allclose(a, 2.9979245799999995e+8)
b = u.Hz.to(u.m, a, u.spectral())
assert_allclose(b, 1)
def test_spectral2():
a = u.nm.to(u.J, 500, u.spectral())
assert_allclose(a, 3.972891366538605e-19)
b = u.J.to(u.nm, a, u.spectral())
assert_allclose(b, 500)
a = u.AA.to(u.Hz, 1, u.spectral())
b = u.Hz.to(u.J, a, u.spectral())
c = u.AA.to(u.J, 1, u.spectral())
assert_allclose(b, c)
c = u.J.to(u.Hz, b, u.spectral())
assert_allclose(a, c)
def test_spectral3():
a = u.nm.to(u.Hz, [1000, 2000], u.spectral())
assert_allclose(a, [2.99792458e+14, 1.49896229e+14])
@pytest.mark.parametrize(
('in_val', 'in_unit'),
[([0.1, 5000.0, 10000.0], u.AA),
([1e+5, 2.0, 1.0], u.micron ** -1),
([2.99792458e+19, 5.99584916e+14, 2.99792458e+14], u.Hz),
([1.98644568e-14, 3.97289137e-19, 1.98644568e-19], u.J)])
def test_spectral4(in_val, in_unit):
"""Wave number conversion w.r.t. wavelength, freq, and energy."""
# Spectroscopic and angular
out_units = [u.micron ** -1, u.radian / u.micron]
answers = [[1e+5, 2.0, 1.0], [6.28318531e+05, 12.5663706, 6.28318531]]
for out_unit, ans in zip(out_units, answers):
# Forward
a = in_unit.to(out_unit, in_val, u.spectral())
assert_allclose(a, ans)
# Backward
b = out_unit.to(in_unit, ans, u.spectral())
assert_allclose(b, in_val)
def test_spectraldensity2():
# flux density
flambda = u.erg / u.angstrom / u.cm ** 2 / u.s
fnu = u.erg / u.Hz / u.cm ** 2 / u.s
a = flambda.to(fnu, 1, u.spectral_density(u.Quantity(3500, u.AA)))
assert_allclose(a, 4.086160166177361e-12)
# luminosity density
llambda = u.erg / u.angstrom / u.s
lnu = u.erg / u.Hz / u.s
a = llambda.to(lnu, 1, u.spectral_density(u.Quantity(3500, u.AA)))
assert_allclose(a, 4.086160166177361e-12)
a = lnu.to(llambda, 1, u.spectral_density(u.Quantity(3500, u.AA)))
assert_allclose(a, 2.44728537142857e11)
def test_spectraldensity3():
# Define F_nu in Jy
f_nu = u.Jy
# Define F_lambda in ergs / cm^2 / s / micron
f_lambda = u.erg / u.cm ** 2 / u.s / u.micron
# 1 GHz
one_ghz = u.Quantity(1, u.GHz)
# Convert to ergs / cm^2 / s / Hz
assert_allclose(f_nu.to(u.erg / u.cm ** 2 / u.s / u.Hz, 1.), 1.e-23, 10)
# Convert to ergs / cm^2 / s at 10 Ghz
assert_allclose(f_nu.to(u.erg / u.cm ** 2 / u.s, 1.,
equivalencies=u.spectral_density(one_ghz * 10)),
1.e-13, 10)
# Convert to F_lambda at 1 Ghz
assert_allclose(f_nu.to(f_lambda, 1.,
equivalencies=u.spectral_density(one_ghz)),
3.335640951981521e-20, 10)
# Convert to Jy at 1 Ghz
assert_allclose(f_lambda.to(u.Jy, 1.,
equivalencies=u.spectral_density(one_ghz)),
1. / 3.335640951981521e-20, 10)
# Convert to ergs / cm^2 / s at 10 microns
assert_allclose(f_lambda.to(u.erg / u.cm ** 2 / u.s, 1.,
equivalencies=u.spectral_density(u.Quantity(10, u.micron))),
10., 10)
def test_spectraldensity4():
"""PHOTLAM and PHOTNU conversions."""
flam = u.erg / (u.cm ** 2 * u.s * u.AA)
fnu = u.erg / (u.cm ** 2 * u.s * u.Hz)
photlam = u.photon / (u.cm ** 2 * u.s * u.AA)
photnu = u.photon / (u.cm ** 2 * u.s * u.Hz)
wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA)
flux_photlam = [9.7654e-3, 1.003896e-2, 9.78473e-3]
flux_photnu = [8.00335589e-14, 8.23668949e-14, 8.03700310e-14]
flux_flam = [3.9135e-14, 4.0209e-14, 3.9169e-14]
flux_fnu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25]
flux_jy = [3.20735792e-2, 3.29903646e-2, 3.21727226e-2]
flux_stmag = [12.41858665, 12.38919182, 12.41764379]
flux_abmag = [12.63463143, 12.60403221, 12.63128047]
# PHOTLAM <--> FLAM
assert_allclose(photlam.to(
flam, flux_photlam, u.spectral_density(wave)), flux_flam, rtol=1e-6)
assert_allclose(flam.to(
photlam, flux_flam, u.spectral_density(wave)), flux_photlam, rtol=1e-6)
# PHOTLAM <--> FNU
assert_allclose(photlam.to(
fnu, flux_photlam, u.spectral_density(wave)), flux_fnu, rtol=1e-6)
assert_allclose(fnu.to(
photlam, flux_fnu, u.spectral_density(wave)), flux_photlam, rtol=1e-6)
# PHOTLAM <--> Jy
assert_allclose(photlam.to(
u.Jy, flux_photlam, u.spectral_density(wave)), flux_jy, rtol=1e-6)
assert_allclose(u.Jy.to(
photlam, flux_jy, u.spectral_density(wave)), flux_photlam, rtol=1e-6)
# PHOTLAM <--> PHOTNU
assert_allclose(photlam.to(
photnu, flux_photlam, u.spectral_density(wave)), flux_photnu, rtol=1e-6)
assert_allclose(photnu.to(
photlam, flux_photnu, u.spectral_density(wave)), flux_photlam, rtol=1e-6)
# PHOTNU <--> FNU
assert_allclose(photnu.to(
fnu, flux_photnu, u.spectral_density(wave)), flux_fnu, rtol=1e-6)
assert_allclose(fnu.to(
photnu, flux_fnu, u.spectral_density(wave)), flux_photnu, rtol=1e-6)
# PHOTNU <--> FLAM
assert_allclose(photnu.to(
flam, flux_photnu, u.spectral_density(wave)), flux_flam, rtol=1e-6)
assert_allclose(flam.to(
photnu, flux_flam, u.spectral_density(wave)), flux_photnu, rtol=1e-6)
# PHOTLAM <--> STMAG
assert_allclose(photlam.to(
u.STmag, flux_photlam, u.spectral_density(wave)), flux_stmag, rtol=1e-6)
assert_allclose(u.STmag.to(
photlam, flux_stmag, u.spectral_density(wave)), flux_photlam, rtol=1e-6)
# PHOTLAM <--> ABMAG
assert_allclose(photlam.to(
u.ABmag, flux_photlam, u.spectral_density(wave)), flux_abmag, rtol=1e-6)
assert_allclose(u.ABmag.to(
photlam, flux_abmag, u.spectral_density(wave)), flux_photlam, rtol=1e-6)
def test_spectraldensity5():
""" Test photon luminosity density conversions. """
L_la = u.erg / (u.s * u.AA)
L_nu = u.erg / (u.s * u.Hz)
phot_L_la = u.photon / (u.s * u.AA)
phot_L_nu = u.photon / (u.s * u.Hz)
wave = u.Quantity([4956.8, 4959.55, 4962.3], u.AA)
flux_phot_L_la = [9.7654e-3, 1.003896e-2, 9.78473e-3]
flux_phot_L_nu = [8.00335589e-14, 8.23668949e-14, 8.03700310e-14]
flux_L_la = [3.9135e-14, 4.0209e-14, 3.9169e-14]
flux_L_nu = [3.20735792e-25, 3.29903646e-25, 3.21727226e-25]
# PHOTLAM <--> FLAM
assert_allclose(phot_L_la.to(
L_la, flux_phot_L_la, u.spectral_density(wave)), flux_L_la, rtol=1e-6)
assert_allclose(L_la.to(
phot_L_la, flux_L_la, u.spectral_density(wave)), flux_phot_L_la, rtol=1e-6)
# PHOTLAM <--> FNU
assert_allclose(phot_L_la.to(
L_nu, flux_phot_L_la, u.spectral_density(wave)), flux_L_nu, rtol=1e-6)
assert_allclose(L_nu.to(
phot_L_la, flux_L_nu, u.spectral_density(wave)), flux_phot_L_la, rtol=1e-6)
# PHOTLAM <--> PHOTNU
assert_allclose(phot_L_la.to(
phot_L_nu, flux_phot_L_la, u.spectral_density(wave)), flux_phot_L_nu, rtol=1e-6)
assert_allclose(phot_L_nu.to(
phot_L_la, flux_phot_L_nu, u.spectral_density(wave)), flux_phot_L_la, rtol=1e-6)
# PHOTNU <--> FNU
assert_allclose(phot_L_nu.to(
L_nu, flux_phot_L_nu, u.spectral_density(wave)), flux_L_nu, rtol=1e-6)
assert_allclose(L_nu.to(
phot_L_nu, flux_L_nu, u.spectral_density(wave)), flux_phot_L_nu, rtol=1e-6)
# PHOTNU <--> FLAM
assert_allclose(phot_L_nu.to(
L_la, flux_phot_L_nu, u.spectral_density(wave)), flux_L_la, rtol=1e-6)
assert_allclose(L_la.to(
phot_L_nu, flux_L_la, u.spectral_density(wave)), flux_phot_L_nu, rtol=1e-6)
def test_equivalent_units():
from .. import imperial
with u.add_enabled_units(imperial):
units = u.g.find_equivalent_units()
units_set = set(units)
match = set(
[u.M_e, u.M_p, u.g, u.kg, u.solMass, u.t, u.u, u.M_earth,
u.M_jup, imperial.oz, imperial.lb, imperial.st, imperial.ton,
imperial.slug])
assert units_set == match
r = repr(units)
assert r.count('\n') == len(units) + 2
def test_equivalent_units2():
units = set(u.Hz.find_equivalent_units(u.spectral()))
match = set(
[u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr,
u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad,
u.jupiterRad])
assert units == match
from .. import imperial
with u.add_enabled_units(imperial):
units = set(u.Hz.find_equivalent_units(u.spectral()))
match = set(
[u.AU, u.Angstrom, imperial.BTU, u.Hz, u.J, u.Ry,
imperial.cal, u.cm, u.eV, u.erg, imperial.ft, imperial.fur,
imperial.inch, imperial.kcal, u.lyr, u.m, imperial.mi,
imperial.mil, u.micron, u.pc, u.solRad, imperial.yd, u.Bq, u.Ci,
imperial.nmi, u.k, u.earthRad, u.jupiterRad])
assert units == match
units = set(u.Hz.find_equivalent_units(u.spectral()))
match = set(
[u.AU, u.Angstrom, u.Hz, u.J, u.Ry, u.cm, u.eV, u.erg, u.lyr,
u.m, u.micron, u.pc, u.solRad, u.Bq, u.Ci, u.k, u.earthRad,
u.jupiterRad])
assert units == match
def test_trivial_equivalency():
assert u.m.to(u.kg, equivalencies=[(u.m, u.kg)]) == 1.0
def test_invalid_equivalency():
with pytest.raises(ValueError):
u.m.to(u.kg, equivalencies=[(u.m,)])
with pytest.raises(ValueError):
u.m.to(u.kg, equivalencies=[(u.m, 5.0)])
def test_irrelevant_equivalency():
with pytest.raises(u.UnitsError):
u.m.to(u.kg, equivalencies=[(u.m, u.l)])
def test_brightness_temperature():
omega_B = np.pi * (50 * u.arcsec) ** 2
nu = u.GHz * 5
tb = 7.052590289134352 * u.K
np.testing.assert_almost_equal(
tb.value, (1 * u.Jy).to_value(
u.K, equivalencies=u.brightness_temperature(nu, beam_area=omega_B)))
np.testing.assert_almost_equal(
1.0, tb.to_value(
u.Jy, equivalencies=u.brightness_temperature(nu, beam_area=omega_B)))
def test_swapped_args_brightness_temperature():
"""
#5173 changes the order of arguments but accepts the old (deprecated) args
"""
omega_B = np.pi * (50 * u.arcsec) ** 2
nu = u.GHz * 5
tb = 7.052590289134352 * u.K
# https://docs.pytest.org/en/latest/warnings.html#ensuring-function-triggers
with warnings.catch_warnings():
warnings.simplefilter('always')
with pytest.warns(DeprecationWarning) as warning_list:
result = (1*u.Jy).to(u.K,
equivalencies=u.brightness_temperature(omega_B,
nu))
roundtrip = result.to(u.Jy,
equivalencies=u.brightness_temperature(omega_B,
nu))
assert len(warning_list) == 2
np.testing.assert_almost_equal(tb.value, result.value)
np.testing.assert_almost_equal(roundtrip.value, 1)
def test_surfacebrightness():
sb = 50*u.MJy/u.sr
k = sb.to(u.K, u.brightness_temperature(50*u.GHz))
np.testing.assert_almost_equal(k.value, 0.650965, 5)
assert k.unit.is_equivalent(u.K)
def test_beam():
# pick a beam area: 2 pi r^2 = area of a Gaussina with sigma=50 arcsec
omega_B = 2 * np.pi * (50 * u.arcsec) ** 2
new_beam = (5*u.beam).to(u.sr, u.equivalencies.beam_angular_area(omega_B))
np.testing.assert_almost_equal(omega_B.to(u.sr).value * 5, new_beam.value)
assert new_beam.unit.is_equivalent(u.sr)
# make sure that it's still consistent with 5 beams
nbeams = new_beam.to(u.beam, u.equivalencies.beam_angular_area(omega_B))
np.testing.assert_almost_equal(nbeams.value, 5)
# test inverse beam equivalency
# (this is just a sanity check that the equivalency is defined;
# it's not for testing numerical consistency)
new_inverse_beam = (5/u.beam).to(1/u.sr, u.equivalencies.beam_angular_area(omega_B))
# test practical case
# (this is by far the most important one)
flux_density = (5*u.Jy/u.beam).to(u.MJy/u.sr, u.equivalencies.beam_angular_area(omega_B))
np.testing.assert_almost_equal(flux_density.value, 13.5425483146382)
def test_equivalency_context():
with u.set_enabled_equivalencies(u.dimensionless_angles()):
phase = u.Quantity(1., u.cycle)
assert_allclose(np.exp(1j*phase), 1.)
Omega = u.cycle / (1.*u.minute)
assert_allclose(np.exp(1j*Omega*60.*u.second), 1.)
# ensure we can turn off equivalencies even within the scope
with pytest.raises(u.UnitsError):
phase.to(1, equivalencies=None)
# test the manager also works in the Quantity constructor.
q1 = u.Quantity(phase, u.dimensionless_unscaled)
assert_allclose(q1.value, u.cycle.to(u.radian))
# and also if we use a class that happens to have a unit attribute.
class MyQuantityLookalike(np.ndarray):
pass
mylookalike = np.array(1.).view(MyQuantityLookalike)
mylookalike.unit = 'cycle'
# test the manager also works in the Quantity constructor.
q2 = u.Quantity(mylookalike, u.dimensionless_unscaled)
assert_allclose(q2.value, u.cycle.to(u.radian))
with u.set_enabled_equivalencies(u.spectral()):
u.GHz.to(u.cm)
eq_on = u.GHz.find_equivalent_units()
with pytest.raises(u.UnitsError):
u.GHz.to(u.cm, equivalencies=None)
# without equivalencies, we should find a smaller (sub)set
eq_off = u.GHz.find_equivalent_units()
assert all(eq in set(eq_on) for eq in eq_off)
assert set(eq_off) < set(eq_on)
# Check the equivalency manager also works in ufunc evaluations,
# not just using (wrong) scaling. [#2496]
l2v = u.doppler_optical(6000 * u.angstrom)
l1 = 6010 * u.angstrom
assert l1.to(u.km/u.s, equivalencies=l2v) > 100. * u.km / u.s
with u.set_enabled_equivalencies(l2v):
assert l1 > 100. * u.km / u.s
assert abs((l1 - 500. * u.km / u.s).to(u.angstrom)) < 1. * u.km/u.s
def test_equivalency_context_manager():
base_registry = u.get_current_unit_registry()
def just_to_from_units(equivalencies):
return [(equiv[0], equiv[1]) for equiv in equivalencies]
tf_dimensionless_angles = just_to_from_units(u.dimensionless_angles())
tf_spectral = just_to_from_units(u.spectral())
assert base_registry.equivalencies == []
with u.set_enabled_equivalencies(u.dimensionless_angles()):
new_registry = u.get_current_unit_registry()
assert (set(just_to_from_units(new_registry.equivalencies)) ==
set(tf_dimensionless_angles))
assert set(new_registry.all_units) == set(base_registry.all_units)
with u.set_enabled_equivalencies(u.spectral()):
newer_registry = u.get_current_unit_registry()
assert (set(just_to_from_units(newer_registry.equivalencies)) ==
set(tf_spectral))
assert (set(newer_registry.all_units) ==
set(base_registry.all_units))
assert (set(just_to_from_units(new_registry.equivalencies)) ==
set(tf_dimensionless_angles))
assert set(new_registry.all_units) == set(base_registry.all_units)
with u.add_enabled_equivalencies(u.spectral()):
newer_registry = u.get_current_unit_registry()
assert (set(just_to_from_units(newer_registry.equivalencies)) ==
set(tf_dimensionless_angles) | set(tf_spectral))
assert (set(newer_registry.all_units) ==
set(base_registry.all_units))
assert base_registry is u.get_current_unit_registry()
def test_temperature():
from ..imperial import deg_F
t_k = 0 * u.K
assert_allclose(t_k.to_value(u.deg_C, u.temperature()), -273.15)
assert_allclose(t_k.to_value(deg_F, u.temperature()), -459.67)
def test_temperature_energy():
x = 1000 * u.K
y = (x * constants.k_B).to(u.keV)
assert_allclose(x.to_value(u.keV, u.temperature_energy()), y.value)
assert_allclose(y.to_value(u.K, u.temperature_energy()), x.value)
def test_molar_mass_amu():
x = 1 * (u.g/u.mol)
y = 1 * u.u
assert_allclose(x.to_value(u.u, u.molar_mass_amu()), y.value)
assert_allclose(y.to_value(u.g/u.mol, u.molar_mass_amu()), x.value)
with pytest.raises(u.UnitsError):
x.to(u.u)
def test_compose_equivalencies():
x = u.Unit("arcsec").compose(units=(u.pc,), equivalencies=u.parallax())
assert x[0] == u.pc
x = u.Unit("2 arcsec").compose(units=(u.pc,), equivalencies=u.parallax())
assert x[0] == u.Unit(0.5 * u.pc)
x = u.degree.compose(equivalencies=u.dimensionless_angles())
assert u.Unit(u.degree.to(u.radian)) in x
x = (u.nm).compose(units=(u.m, u.s), equivalencies=u.doppler_optical(0.55*u.micron))
for y in x:
if y.bases == [u.m, u.s]:
assert y.powers == [1, -1]
assert_allclose(
y.scale,
u.nm.to(u.m / u.s, equivalencies=u.doppler_optical(0.55 * u.micron)))
break
else:
assert False, "Didn't find speed in compose results"
def test_pixel_scale():
pix = 75*u.pix
asec = 30*u.arcsec
pixscale = 0.4*u.arcsec/u.pix
pixscale2 = 2.5*u.pix/u.arcsec
assert_quantity_allclose(pix.to(u.arcsec, u.pixel_scale(pixscale)), asec)
assert_quantity_allclose(pix.to(u.arcmin, u.pixel_scale(pixscale)), asec)
assert_quantity_allclose(pix.to(u.arcsec, u.pixel_scale(pixscale2)), asec)
assert_quantity_allclose(pix.to(u.arcmin, u.pixel_scale(pixscale2)), asec)
assert_quantity_allclose(asec.to(u.pix, u.pixel_scale(pixscale)), pix)
assert_quantity_allclose(asec.to(u.pix, u.pixel_scale(pixscale2)), pix)
def test_plate_scale():
mm = 1.5*u.mm
asec = 30*u.arcsec
platescale = 20*u.arcsec/u.mm
platescale2 = 0.05*u.mm/u.arcsec
assert_quantity_allclose(mm.to(u.arcsec, u.plate_scale(platescale)), asec)
assert_quantity_allclose(mm.to(u.arcmin, u.plate_scale(platescale)), asec)
assert_quantity_allclose(mm.to(u.arcsec, u.plate_scale(platescale2)), asec)
assert_quantity_allclose(mm.to(u.arcmin, u.plate_scale(platescale2)), asec)
assert_quantity_allclose(asec.to(u.mm, u.plate_scale(platescale)), mm)
assert_quantity_allclose(asec.to(u.mm, u.plate_scale(platescale2)), mm)
|
c6061ebbf7221599c53012ddd209b8791b5c0d3087e8ab2bf0ea83d39f236ac1 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Regression tests for deprecated units or those that are "soft" deprecated
because they are required for VOUnit support but are not in common use."""
import pytest
from .. import deprecated, required_by_vounit
from ... import units as u
def test_emu():
with pytest.raises(AttributeError):
u.emu
assert u.Bi.to(deprecated.emu, 1) == 1
with deprecated.enable():
assert u.Bi.compose()[0] == deprecated.emu
assert u.Bi.compose()[0] == u.Bi
# test that the earth/jupiter mass/rad are also in the deprecated bunch
for body in ('earth', 'jupiter'):
for phystype in ('Mass', 'Rad'):
# only test a couple prefixes to same time
for prefix in ('n', 'y'):
namewoprefix = body + phystype
unitname = prefix + namewoprefix
with pytest.raises(AttributeError):
getattr(u, unitname)
assert (getattr(deprecated, unitname).represents.bases[0] ==
getattr(u, namewoprefix))
def test_required_by_vounit():
# The tests below could be replicated with all the various prefixes, but it
# seems unnecessary because they all come as a set. So we only use nano for
# the purposes of this test.
with pytest.raises(AttributeError):
# nano-solar mass/rad/lum shouldn't be in the base unit namespace
u.nsolMass
u.nsolRad
u.nsolLum
# but they should be enabled by default via required_by_vounit, to allow
# the Unit constructor to accept them
assert u.Unit('nsolMass') == required_by_vounit.nsolMass
assert u.Unit('nsolRad') == required_by_vounit.nsolRad
assert u.Unit('nsolLum') == required_by_vounit.nsolLum
# but because they are prefixes, they shouldn't be in find_equivalent_units
assert required_by_vounit.nsolMass not in u.solMass.find_equivalent_units()
assert required_by_vounit.nsolRad not in u.solRad.find_equivalent_units()
assert required_by_vounit.nsolLum not in u.solLum.find_equivalent_units()
|
f415f51b9a64d074dd8707a8a98702c163143b572f42ee739b0d12f2ef2c1c5b | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Regression tests for the units.format package
"""
import pytest
from numpy.testing.utils import assert_allclose
from ...tests.helper import catch_warnings
from ... import units as u
from ...constants import si
from .. import core
from .. import format as u_format
from ..utils import is_effectively_unity
@pytest.mark.parametrize('strings, unit', [
(["m s", "m*s", "m.s"], u.m * u.s),
(["m/s", "m*s**-1", "m /s", "m / s", "m/ s"], u.m / u.s),
(["m**2", "m2", "m**(2)", "m**+2", "m+2", "m^(+2)"], u.m ** 2),
(["m**-3", "m-3", "m^(-3)", "/m3"], u.m ** -3),
(["m**(1.5)", "m(3/2)", "m**(3/2)", "m^(3/2)"], u.m ** 1.5),
(["2.54 cm"], u.Unit(u.cm * 2.54)),
(["10+8m"], u.Unit(u.m * 1e8)),
# This is the VOUnits documentation, but doesn't seem to follow the
# unity grammar (["3.45 10**(-4)Jy"], 3.45 * 1e-4 * u.Jy)
(["sqrt(m)"], u.m ** 0.5),
(["dB(mW)", "dB (mW)"], u.DecibelUnit(u.mW)),
(["mag"], u.mag),
(["mag(ct/s)"], u.MagUnit(u.ct / u.s)),
(["dex"], u.dex),
(["dex(cm s**-2)", "dex(cm/s2)"], u.DexUnit(u.cm / u.s**2))])
def test_unit_grammar(strings, unit):
for s in strings:
print(s)
unit2 = u_format.Generic.parse(s)
assert unit2 == unit
@pytest.mark.parametrize('string', ['sin( /pixel /s)', 'mag(mag)',
'dB(dB(mW))', 'dex()'])
def test_unit_grammar_fail(string):
with pytest.raises(ValueError):
print(string)
u_format.Generic.parse(string)
@pytest.mark.parametrize('strings, unit', [
(["0.1nm"], u.AA),
(["mW/m2"], u.Unit(u.erg / u.cm ** 2 / u.s)),
(["mW/(m2)"], u.Unit(u.erg / u.cm ** 2 / u.s)),
(["km/s", "km.s-1"], u.km / u.s),
(["10pix/nm"], u.Unit(10 * u.pix / u.nm)),
(["1.5x10+11m"], u.Unit(1.5e11 * u.m)),
(["1.5×10+11m"], u.Unit(1.5e11 * u.m)),
(["m2"], u.m ** 2),
(["10+21m"], u.Unit(u.m * 1e21)),
(["2.54cm"], u.Unit(u.cm * 2.54)),
(["20%"], 0.20 * u.dimensionless_unscaled),
(["10+9"], 1.e9 * u.dimensionless_unscaled),
(["2x10-9"], 2.e-9 * u.dimensionless_unscaled),
(["---"], u.dimensionless_unscaled),
(["ma"], u.ma),
(["mAU"], u.mAU),
(["uarcmin"], u.uarcmin),
(["uarcsec"], u.uarcsec),
(["kbarn"], u.kbarn),
(["Gbit"], u.Gbit),
(["Gibit"], 2 ** 30 * u.bit),
(["kbyte"], u.kbyte),
(["mRy"], 0.001 * u.Ry),
(["mmag"], u.mmag),
(["Mpc"], u.Mpc),
(["Gyr"], u.Gyr),
(["°"], u.degree),
(["°/s"], u.degree / u.s),
(["Å"], u.AA),
(["Å/s"], u.AA / u.s),
(["\\h"], si.h)])
def test_cds_grammar(strings, unit):
for s in strings:
print(s)
unit2 = u_format.CDS.parse(s)
assert unit2 == unit
@pytest.mark.parametrize('string', [
'0.1 nm',
'solMass(3/2)',
'km / s',
'km s-1',
'pix0.1nm',
'pix/(0.1nm)',
'km*s',
'km**2',
'5x8+3m',
'0.1---',
'---m',
'm---',
'mag(s-1)',
'dB(mW)',
'dex(cm s-2)'])
def test_cds_grammar_fail(string):
with pytest.raises(ValueError):
print(string)
u_format.CDS.parse(string)
# These examples are taken from the EXAMPLES section of
# https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/general/ogip_93_001/
@pytest.mark.parametrize('strings, unit', [
(["count /s", "count/s", "count s**(-1)", "count / s", "count /s "],
u.count / u.s),
(["/pixel /s", "/(pixel * s)"], (u.pixel * u.s) ** -1),
(["count /m**2 /s /eV", "count m**(-2) * s**(-1) * eV**(-1)",
"count /(m**2 * s * eV)"],
u.count * u.m ** -2 * u.s ** -1 * u.eV ** -1),
(["erg /pixel /s /GHz", "erg /s /GHz /pixel", "erg /pixel /(s * GHz)"],
u.erg / (u.s * u.GHz * u.pixel)),
(["keV**2 /yr /angstrom", "10**(10) keV**2 /yr /m"],
# Though this is given as an example, it seems to violate the rules
# of not raising scales to powers, so I'm just excluding it
# "(10**2 MeV)**2 /yr /m"
u.keV**2 / (u.yr * u.angstrom)),
(["10**(46) erg /s", "10**46 erg /s", "10**(39) J /s", "10**(39) W",
"10**(15) YW", "YJ /fs"],
10**46 * u.erg / u.s),
(["10**(-7) J /cm**2 /MeV", "10**(-9) J m**(-2) eV**(-1)",
"nJ m**(-2) eV**(-1)", "nJ /m**2 /eV"],
10 ** -7 * u.J * u.cm ** -2 * u.MeV ** -1),
(["sqrt(erg /pixel /s /GHz)", "(erg /pixel /s /GHz)**(0.5)",
"(erg /pixel /s /GHz)**(1/2)",
"erg**(0.5) pixel**(-0.5) s**(-0.5) GHz**(-0.5)"],
(u.erg * u.pixel ** -1 * u.s ** -1 * u.GHz ** -1) ** 0.5),
(["(count /s) (/pixel /s)", "(count /s) * (/pixel /s)",
"count /pixel /s**2"],
(u.count / u.s) * (1.0 / (u.pixel * u.s)))])
def test_ogip_grammar(strings, unit):
for s in strings:
print(s)
unit2 = u_format.OGIP.parse(s)
assert unit2 == unit
@pytest.mark.parametrize('string', [
'log(photon /m**2 /s /Hz)',
'sin( /pixel /s)',
'log(photon /cm**2 /s /Hz) /(sin( /pixel /s))',
'log(photon /cm**2 /s /Hz) (sin( /pixel /s))**(-1)',
'dB(mW)', 'dex(cm/s**2)'])
def test_ogip_grammar_fail(string):
with pytest.raises(ValueError):
print(string)
u_format.OGIP.parse(string)
@pytest.mark.parametrize('unit', [val for key, val in u.__dict__.items()
if (isinstance(val, core.UnitBase) and
not isinstance(val, core.PrefixUnit))])
def test_roundtrip(unit):
a = core.Unit(unit.to_string('generic'), format='generic')
b = core.Unit(unit.decompose().to_string('generic'), format='generic')
assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-2)
assert_allclose(b.decompose().scale, unit.decompose().scale, rtol=1e-2)
@pytest.mark.parametrize('unit', [
val for key, val in u_format.VOUnit._units.items()
if (isinstance(val, core.UnitBase) and
not isinstance(val, core.PrefixUnit))])
def test_roundtrip_vo_unit(unit):
a = core.Unit(unit.to_string('vounit'), format='vounit')
assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-2)
if unit not in (u.mag, u.dB):
ud = unit.decompose().to_string('vounit')
assert ' ' not in ud
b = core.Unit(ud, format='vounit')
assert_allclose(b.decompose().scale, unit.decompose().scale, rtol=1e-2)
@pytest.mark.parametrize('unit', [
val for key, val in u_format.Fits._units.items()
if (isinstance(val, core.UnitBase) and
not isinstance(val, core.PrefixUnit))])
def test_roundtrip_fits(unit):
s = unit.to_string('fits')
a = core.Unit(s, format='fits')
assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-2)
@pytest.mark.parametrize('unit', [
val for key, val in u_format.CDS._units.items()
if (isinstance(val, core.UnitBase) and
not isinstance(val, core.PrefixUnit))])
def test_roundtrip_cds(unit):
a = core.Unit(unit.to_string('cds'), format='cds')
assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-2)
try:
b = core.Unit(unit.decompose().to_string('cds'), format='cds')
except ValueError: # skip mag: decomposes into dex, unknown to OGIP
return
assert_allclose(b.decompose().scale, unit.decompose().scale, rtol=1e-2)
@pytest.mark.parametrize('unit', [
val for key, val in u_format.OGIP._units.items()
if (isinstance(val, core.UnitBase) and
not isinstance(val, core.PrefixUnit))])
def test_roundtrip_ogip(unit):
a = core.Unit(unit.to_string('ogip'), format='ogip')
assert_allclose(a.decompose().scale, unit.decompose().scale, rtol=1e-2)
try:
b = core.Unit(unit.decompose().to_string('ogip'), format='ogip')
except ValueError: # skip mag: decomposes into dex, unknown to OGIP
return
assert_allclose(b.decompose().scale, unit.decompose().scale, rtol=1e-2)
def test_fits_units_available():
u_format.Fits._units
def test_vo_units_available():
u_format.VOUnit._units
def test_cds_units_available():
u_format.CDS._units
def test_cds_non_ascii_unit():
"""Regression test for #5350. This failed with a decoding error as
μas could not be represented in ascii."""
from .. import cds
with cds.enable():
u.radian.find_equivalent_units(include_prefix_units=True)
def test_latex():
fluxunit = u.erg / (u.cm ** 2 * u.s)
assert fluxunit.to_string('latex') == r'$\mathrm{\frac{erg}{s\,cm^{2}}}$'
def test_new_style_latex():
fluxunit = u.erg / (u.cm ** 2 * u.s)
assert "{0:latex}".format(fluxunit) == r'$\mathrm{\frac{erg}{s\,cm^{2}}}$'
def test_latex_scale():
fluxunit = u.Unit(1.e-24 * u.erg / (u.cm ** 2 * u.s * u.Hz))
latex = r'$\mathrm{1 \times 10^{-24}\,\frac{erg}{Hz\,s\,cm^{2}}}$'
assert fluxunit.to_string('latex') == latex
def test_latex_inline_scale():
fluxunit = u.Unit(1.e-24 * u.erg / (u.cm ** 2 * u.s * u.Hz))
latex_inline = (r'$\mathrm{1 \times 10^{-24}\,erg'
r'\,Hz^{-1}\,s^{-1}\,cm^{-2}}$')
assert fluxunit.to_string('latex_inline') == latex_inline
@pytest.mark.parametrize('format_spec, string', [
('generic', 'erg / (cm2 s)'),
('s', 'erg / (cm2 s)'),
('console', ' erg \n ------\n s cm^2'),
('latex', '$\\mathrm{\\frac{erg}{s\\,cm^{2}}}$'),
('latex_inline', '$\\mathrm{erg\\,s^{-1}\\,cm^{-2}}$'),
('>20s', ' erg / (cm2 s)')])
def test_format_styles(format_spec, string):
fluxunit = u.erg / (u.cm ** 2 * u.s)
assert format(fluxunit, format_spec) == string
def test_flatten_to_known():
myunit = u.def_unit("FOOBAR_One", u.erg / u.Hz)
assert myunit.to_string('fits') == 'erg Hz-1'
myunit2 = myunit * u.bit ** 3
assert myunit2.to_string('fits') == 'bit3 erg Hz-1'
def test_flatten_impossible():
myunit = u.def_unit("FOOBAR_Two")
with u.add_enabled_units(myunit), pytest.raises(ValueError):
myunit.to_string('fits')
def test_console_out():
"""
Issue #436.
"""
u.Jy.decompose().to_string('console')
def test_flexible_float():
assert u.min._represents.to_string('latex') == r'$\mathrm{60\,s}$'
def test_fraction_repr():
area = u.cm ** 2.0
assert '.' not in area.to_string('latex')
fractional = u.cm ** 2.5
assert '5/2' in fractional.to_string('latex')
assert fractional.to_string('unicode') == 'cm⁵⸍²'
def test_scale_effectively_unity():
"""Scale just off unity at machine precision level is OK.
Ensures #748 does not recur
"""
a = (3. * u.N).cgs
assert is_effectively_unity(a.unit.scale)
assert len(a.__repr__().split()) == 3
def test_percent():
"""Test that the % unit is properly recognized. Since % is a special
symbol, this goes slightly beyond the roundtripping tested above."""
assert u.Unit('%') == u.percent == u.Unit(0.01)
assert u.Unit('%', format='cds') == u.Unit(0.01)
assert u.Unit(0.01).to_string('cds') == '%'
with pytest.raises(ValueError):
u.Unit('%', format='fits')
with pytest.raises(ValueError):
u.Unit('%', format='vounit')
def test_scaled_dimensionless():
"""Test that scaled dimensionless units are properly recognized in generic
and CDS, but not in fits and vounit."""
assert u.Unit('0.1') == u.Unit(0.1) == 0.1 * u.dimensionless_unscaled
assert u.Unit('1.e-4') == u.Unit(1.e-4)
assert u.Unit('10-4', format='cds') == u.Unit(1.e-4)
assert u.Unit('10+8').to_string('cds') == '10+8'
with pytest.raises(ValueError):
u.Unit(0.15).to_string('fits')
assert u.Unit(0.1).to_string('fits') == '10**-1'
with pytest.raises(ValueError):
u.Unit(0.1).to_string('vounit')
def test_deprecated_did_you_mean_units():
try:
u.Unit('ANGSTROM', format='fits')
except ValueError as e:
assert 'Did you mean Angstrom or angstrom?' in str(e)
try:
u.Unit('crab', format='ogip')
except ValueError as e:
assert 'Crab (deprecated)' in str(e)
assert 'mCrab (deprecated)' in str(e)
try:
u.Unit('ANGSTROM', format='vounit')
except ValueError as e:
assert 'angstrom (deprecated)' in str(e)
assert '0.1nm' in str(e)
assert str(e).count('0.1nm') == 1
with catch_warnings() as w:
u.Unit('angstrom', format='vounit')
assert len(w) == 1
assert '0.1nm' in str(w[0].message)
@pytest.mark.parametrize('string', ['mag(ct/s)', 'dB(mW)', 'dex(cm s**-2)'])
def test_fits_function(string):
# Function units cannot be written, so ensure they're not parsed either.
with pytest.raises(ValueError):
print(string)
u_format.Fits().parse(string)
@pytest.mark.parametrize('string', ['mag(ct/s)', 'dB(mW)', 'dex(cm s**-2)'])
def test_vounit_function(string):
# Function units cannot be written, so ensure they're not parsed either.
with pytest.raises(ValueError):
print(string)
u_format.VOUnit().parse(string)
def test_vounit_binary_prefix():
u.Unit('KiB', format='vounit') == u.Unit('1024 B')
u.Unit('Kibyte', format='vounit') == u.Unit('1024 B')
u.Unit('Kibit', format='vounit') == u.Unit('1024 B')
with catch_warnings() as w:
u.Unit('kibibyte', format='vounit')
assert len(w) == 1
def test_vounit_unknown():
assert u.Unit('unknown', format='vounit') is None
assert u.Unit('UNKNOWN', format='vounit') is None
assert u.Unit('', format='vounit') is u.dimensionless_unscaled
def test_vounit_details():
assert u.Unit('Pa', format='vounit') is u.Pascal
# The da- prefix is not allowed, and the d- prefix is discouraged
assert u.dam.to_string('vounit') == '10m'
assert u.Unit('dam dag').to_string('vounit') == '100g m'
def test_vounit_custom():
x = u.Unit("'foo' m", format='vounit')
x_vounit = x.to_string('vounit')
assert x_vounit == "'foo' m"
x_string = x.to_string()
assert x_string == "foo m"
x = u.Unit("m'foo' m", format='vounit')
assert x.bases[1]._represents.scale == 0.001
x_vounit = x.to_string('vounit')
assert x_vounit == "m m'foo'"
x_string = x.to_string()
assert x_string == 'm mfoo'
def test_vounit_implicit_custom():
x = u.Unit("furlong/week", format="vounit")
assert x.bases[0]._represents.scale == 1e-15
assert x.bases[0]._represents.bases[0].name == 'urlong'
def test_fits_scale_factor():
with pytest.raises(ValueError):
x = u.Unit('1000 erg/s/cm**2/Angstrom', format='fits')
with pytest.raises(ValueError):
x = u.Unit('12 erg/s/cm**2/Angstrom', format='fits')
x = u.Unit('10+2 erg/s/cm**2/Angstrom', format='fits')
assert x == 100 * (u.erg / u.s / u.cm ** 2 / u.Angstrom)
assert x.to_string(format='fits') == '10**2 Angstrom-1 cm-2 erg s-1'
x = u.Unit('10**(-20) erg/s/cm**2/Angstrom', format='fits')
assert x == 10**(-20) * (u.erg / u.s / u.cm ** 2 / u.Angstrom)
assert x.to_string(format='fits') == '10**-20 Angstrom-1 cm-2 erg s-1'
x = u.Unit('10**-20 erg/s/cm**2/Angstrom', format='fits')
assert x == 10**(-20) * (u.erg / u.s / u.cm ** 2 / u.Angstrom)
assert x.to_string(format='fits') == '10**-20 Angstrom-1 cm-2 erg s-1'
x = u.Unit('10^(-20) erg/s/cm**2/Angstrom', format='fits')
assert x == 10**(-20) * (u.erg / u.s / u.cm ** 2 / u.Angstrom)
assert x.to_string(format='fits') == '10**-20 Angstrom-1 cm-2 erg s-1'
x = u.Unit('10^-20 erg/s/cm**2/Angstrom', format='fits')
assert x == 10**(-20) * (u.erg / u.s / u.cm ** 2 / u.Angstrom)
assert x.to_string(format='fits') == '10**-20 Angstrom-1 cm-2 erg s-1'
x = u.Unit('10-20 erg/s/cm**2/Angstrom', format='fits')
assert x == 10**(-20) * (u.erg / u.s / u.cm ** 2 / u.Angstrom)
assert x.to_string(format='fits') == '10**-20 Angstrom-1 cm-2 erg s-1'
x = u.Unit('10**(-20)*erg/s/cm**2/Angstrom', format='fits')
assert x == 10**(-20) * (u.erg / u.s / u.cm ** 2 / u.Angstrom)
x = u.Unit(1.2 * u.erg)
with pytest.raises(ValueError):
x.to_string(format='fits')
x = u.Unit(100.0 * u.erg)
assert x.to_string(format='fits') == '10**2 erg'
|
7f135f7c8e1a418736b0cf1f2ffd49d145e967ef7963380599c18efc431ac2a7 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Regression tests for the units package
"""
import pickle
from fractions import Fraction
import pytest
import numpy as np
from numpy.testing.utils import assert_allclose
from ...tests.helper import raises, catch_warnings
from ... import units as u
from ... import constants as c
from .. import utils
def test_getting_started():
"""
Corresponds to "Getting Started" section in the docs.
"""
from .. import imperial
with imperial.enable():
speed_unit = u.cm / u.s
x = speed_unit.to(imperial.mile / u.hour, 1)
assert_allclose(x, 0.02236936292054402)
speed_converter = speed_unit._get_converter("mile hour^-1")
x = speed_converter([1., 1000., 5000.])
assert_allclose(x, [2.23693629e-02, 2.23693629e+01, 1.11846815e+02])
def test_initialisation():
assert u.Unit(u.m) is u.m
ten_meter = u.Unit(10.*u.m)
assert ten_meter == u.CompositeUnit(10., [u.m], [1])
assert u.Unit(ten_meter) is ten_meter
assert u.Unit(10.*ten_meter) == u.CompositeUnit(100., [u.m], [1])
foo = u.Unit('foo', (10. * ten_meter)**2, namespace=locals())
assert foo == u.CompositeUnit(10000., [u.m], [2])
assert u.Unit('m') == u.m
assert u.Unit('') == u.dimensionless_unscaled
assert u.one == u.dimensionless_unscaled
assert u.Unit('10 m') == ten_meter
assert u.Unit(10.) == u.CompositeUnit(10., [], [])
def test_invalid_power():
x = u.m ** Fraction(1, 3)
assert isinstance(x.powers[0], Fraction)
x = u.m ** Fraction(1, 2)
assert isinstance(x.powers[0], float)
# Test the automatic conversion to a fraction
x = u.m ** (1. / 3.)
assert isinstance(x.powers[0], Fraction)
def test_invalid_compare():
assert not (u.m == u.s)
def test_convert():
assert u.h._get_converter(u.s)(1) == 3600
def test_convert_fail():
with pytest.raises(u.UnitsError):
u.cm.to(u.s, 1)
with pytest.raises(u.UnitsError):
(u.cm / u.s).to(u.m, 1)
def test_composite():
assert (u.cm / u.s * u.h)._get_converter(u.m)(1) == 36
assert u.cm * u.cm == u.cm ** 2
assert u.cm * u.cm * u.cm == u.cm ** 3
assert u.Hz.to(1000 * u.Hz, 1) == 0.001
def test_str():
assert str(u.cm) == "cm"
def test_repr():
assert repr(u.cm) == 'Unit("cm")'
def test_represents():
assert u.m.represents is u.m
assert u.km.represents.scale == 1000.
assert u.km.represents.bases == [u.m]
assert u.Ry.scale == 1.0 and u.Ry.bases == [u.Ry]
assert_allclose(u.Ry.represents.scale, 13.605692518464949)
assert u.Ry.represents.bases == [u.eV]
bla = u.def_unit('bla', namespace=locals())
assert bla.represents is bla
blabla = u.def_unit('blabla', 10 * u.hr, namespace=locals())
assert blabla.represents.scale == 10.
assert blabla.represents.bases == [u.hr]
assert blabla.decompose().scale == 10 * 3600
assert blabla.decompose().bases == [u.s]
def test_units_conversion():
assert_allclose(u.kpc.to(u.Mpc), 0.001)
assert_allclose(u.Mpc.to(u.kpc), 1000)
assert_allclose(u.yr.to(u.Myr), 1.e-6)
assert_allclose(u.AU.to(u.pc), 4.84813681e-6)
assert_allclose(u.cycle.to(u.rad), 6.283185307179586)
def test_units_manipulation():
# Just do some manipulation and check it's happy
(u.kpc * u.yr) ** Fraction(1, 3) / u.Myr
(u.AA * u.erg) ** 9
def test_decompose():
assert u.Ry == u.Ry.decompose()
def test_dimensionless_to_si():
"""
Issue #1150: Test for conversion of dimensionless quantities
to the SI system
"""
testunit = ((1.0 * u.kpc) / (1.0 * u.Mpc))
assert testunit.unit.physical_type == 'dimensionless'
assert_allclose(testunit.si, 0.001)
def test_dimensionless_to_cgs():
"""
Issue #1150: Test for conversion of dimensionless quantities
to the CGS system
"""
testunit = ((1.0 * u.m) / (1.0 * u.km))
assert testunit.unit.physical_type == 'dimensionless'
assert_allclose(testunit.cgs, 0.001)
def test_unknown_unit():
with catch_warnings(u.UnitsWarning) as warning_lines:
u.Unit("FOO", parse_strict='warn')
assert 'FOO' in str(warning_lines[0].message)
def test_multiple_solidus():
assert u.Unit("m/s/kg").to_string() == u.m / u.s / u.kg
with catch_warnings(u.UnitsWarning) as warning_lines:
assert u.Unit("m/s/kg").to_string() == u.m / (u.s * u.kg)
assert 'm/s/kg' in str(warning_lines[0].message)
assert 'discouraged' in str(warning_lines[0].message)
with pytest.raises(ValueError):
u.Unit("m/s/kg", format="vounit")
def test_unknown_unit3():
unit = u.Unit("FOO", parse_strict='silent')
assert isinstance(unit, u.UnrecognizedUnit)
assert unit.name == "FOO"
unit2 = u.Unit("FOO", parse_strict='silent')
assert unit == unit2
assert unit.is_equivalent(unit2)
unit3 = u.Unit("BAR", parse_strict='silent')
assert unit != unit3
assert not unit.is_equivalent(unit3)
with pytest.raises(ValueError):
unit._get_converter(unit3)
x = unit.to_string('latex')
y = unit2.to_string('cgs')
with pytest.raises(ValueError):
unit4 = u.Unit("BAR", parse_strict='strict')
with pytest.raises(TypeError):
unit5 = u.Unit(None)
@raises(TypeError)
def test_invalid_scale():
x = ['a', 'b', 'c'] * u.m
def test_cds_power():
unit = u.Unit("10+22/cm2", format="cds", parse_strict='silent')
assert unit.scale == 1e22
def test_register():
foo = u.def_unit("foo", u.m ** 3, namespace=locals())
assert 'foo' in locals()
with u.add_enabled_units(foo):
assert 'foo' in u.get_current_unit_registry().registry
assert 'foo' not in u.get_current_unit_registry().registry
def test_in_units():
speed_unit = u.cm / u.s
x = speed_unit.in_units(u.pc / u.hour, 1)
def test_null_unit():
assert (u.m / u.m) == u.Unit(1)
def test_unrecognized_equivalency():
assert u.m.is_equivalent('foo') is False
assert u.m.is_equivalent('pc') is True
@raises(TypeError)
def test_unit_noarg():
u.Unit()
def test_convertible_exception():
try:
u.AA.to(u.h * u.s ** 2)
except u.UnitsError as e:
assert "length" in str(e)
def test_convertible_exception2():
try:
u.m.to(u.s)
except u.UnitsError as e:
assert "length" in str(e)
@raises(TypeError)
def test_invalid_type():
class A:
pass
u.Unit(A())
def test_steradian():
"""
Issue #599
"""
assert u.sr.is_equivalent(u.rad * u.rad)
results = u.sr.compose(units=u.cgs.bases)
assert results[0].bases[0] is u.rad
results = u.sr.compose(units=u.cgs.__dict__)
assert results[0].bases[0] is u.sr
def test_decompose_bases():
"""
From issue #576
"""
from .. import cgs
from ...constants import e
d = e.esu.unit.decompose(bases=cgs.bases)
assert d._bases == [u.cm, u.g, u.s]
assert d._powers == [Fraction(3, 2), 0.5, -1]
assert d._scale == 1.0
def test_complex_compose():
complex = u.cd * u.sr * u.Wb
composed = complex.compose()
assert set(composed[0]._bases) == set([u.lm, u.Wb])
def test_equiv_compose():
composed = u.m.compose(equivalencies=u.spectral())
assert any([u.Hz] == x.bases for x in composed)
def test_empty_compose():
with pytest.raises(u.UnitsError):
composed = u.m.compose(units=[])
def _unit_as_str(unit):
# This function serves two purposes - it is used to sort the units to
# test alphabetically, and it is also use to allow pytest to show the unit
# in the [] when running the parametrized tests.
return str(unit)
# We use a set to make sure we don't have any duplicates.
COMPOSE_ROUNDTRIP = set()
for val in u.__dict__.values():
if (isinstance(val, u.UnitBase) and
not isinstance(val, u.PrefixUnit)):
COMPOSE_ROUNDTRIP.add(val)
@pytest.mark.parametrize('unit', sorted(COMPOSE_ROUNDTRIP, key=_unit_as_str), ids=_unit_as_str)
def test_compose_roundtrip(unit):
composed_list = unit.decompose().compose()
found = False
for composed in composed_list:
if len(composed.bases):
if composed.bases[0] is unit:
found = True
break
elif len(unit.bases) == 0:
found = True
break
assert found
# We use a set to make sure we don't have any duplicates.
COMPOSE_CGS_TO_SI = set()
for val in u.cgs.__dict__.values():
# Can't decompose Celsius
if (isinstance(val, u.UnitBase) and
not isinstance(val, u.PrefixUnit) and
val != u.cgs.deg_C):
COMPOSE_CGS_TO_SI.add(val)
@pytest.mark.parametrize('unit', sorted(COMPOSE_CGS_TO_SI, key=_unit_as_str),
ids=_unit_as_str)
def test_compose_cgs_to_si(unit):
si = unit.to_system(u.si)
assert [x.is_equivalent(unit) for x in si]
assert si[0] == unit.si
# We use a set to make sure we don't have any duplicates.
COMPOSE_SI_TO_CGS = set()
for val in u.si.__dict__.values():
# Can't decompose Celsius
if (isinstance(val, u.UnitBase) and
not isinstance(val, u.PrefixUnit) and
val != u.si.deg_C):
COMPOSE_SI_TO_CGS.add(val)
@pytest.mark.parametrize('unit', sorted(COMPOSE_SI_TO_CGS, key=_unit_as_str), ids=_unit_as_str)
def test_compose_si_to_cgs(unit):
# Can't convert things with Ampere to CGS without more context
try:
cgs = unit.to_system(u.cgs)
except u.UnitsError:
if u.A in unit.decompose().bases:
pass
else:
raise
else:
assert [x.is_equivalent(unit) for x in cgs]
assert cgs[0] == unit.cgs
def test_to_cgs():
assert u.Pa.to_system(u.cgs)[1]._bases[0] is u.Ba
assert u.Pa.to_system(u.cgs)[1]._scale == 10.0
def test_decompose_to_cgs():
from .. import cgs
assert u.m.decompose(bases=cgs.bases)._bases[0] is cgs.cm
def test_compose_issue_579():
unit = u.kg * u.s ** 2 / u.m
result = unit.compose(units=[u.N, u.s, u.m])
assert len(result) == 1
assert result[0]._bases == [u.s, u.N, u.m]
assert result[0]._powers == [4, 1, -2]
def test_compose_prefix_unit():
x = u.m.compose(units=(u.m,))
assert x[0].bases[0] is u.m
assert x[0].scale == 1.0
x = u.m.compose(units=[u.km], include_prefix_units=True)
assert x[0].bases[0] is u.km
assert x[0].scale == 0.001
x = u.m.compose(units=[u.km])
assert x[0].bases[0] is u.km
assert x[0].scale == 0.001
x = (u.km/u.s).compose(units=(u.pc, u.Myr))
assert x[0].bases == [u.pc, u.Myr]
assert_allclose(x[0].scale, 1.0227121650537077)
with raises(u.UnitsError):
(u.km/u.s).compose(units=(u.pc, u.Myr), include_prefix_units=False)
def test_self_compose():
unit = u.kg * u.s
assert len(unit.compose(units=[u.g, u.s])) == 1
@raises(u.UnitsError)
def test_compose_failed():
unit = u.kg
result = unit.compose(units=[u.N])
def test_compose_fractional_powers():
# Warning: with a complicated unit, this test becomes very slow;
# e.g., x = (u.kg / u.s ** 3 * u.au ** 2.5 / u.yr ** 0.5 / u.sr ** 2)
# takes 3 s
x = u.m ** 0.5 / u.yr ** 1.5
factored = x.compose()
for unit in factored:
assert x.decompose() == unit.decompose()
factored = x.compose(units=u.cgs)
for unit in factored:
assert x.decompose() == unit.decompose()
factored = x.compose(units=u.si)
for unit in factored:
assert x.decompose() == unit.decompose()
def test_compose_best_unit_first():
results = u.l.compose()
assert len(results[0].bases) == 1
assert results[0].bases[0] is u.l
results = (u.s ** -1).compose()
assert results[0].bases[0] in (u.Hz, u.Bq)
results = (u.Ry.decompose()).compose()
assert results[0].bases[0] is u.Ry
def test_compose_no_duplicates():
new = u.kg / u.s ** 3 * u.au ** 2.5 / u.yr ** 0.5 / u.sr ** 2
composed = new.compose(units=u.cgs.bases)
assert len(composed) == 1
def test_long_int():
"""
Issue #672
"""
sigma = 10 ** 21 * u.M_p / u.cm ** 2
sigma.to(u.M_sun / u.pc ** 2)
def test_endian_independence():
"""
Regression test for #744
A logic issue in the units code meant that big endian arrays could not be
converted because the dtype is '>f4', not 'float32', and the code was
looking for the strings 'float' or 'int'.
"""
for endian in ['<', '>']:
for ntype in ['i', 'f']:
for byte in ['4', '8']:
x = np.array([1, 2, 3], dtype=(endian + ntype + byte))
u.m.to(u.cm, x)
def test_radian_base():
"""
Issue #863
"""
assert (1 * u.degree).si.unit == u.rad
def test_no_as():
# We don't define 'as', since it is a keyword, but we
# do want to define the long form (`attosecond`).
assert not hasattr(u, 'as')
assert hasattr(u, 'attosecond')
def test_no_duplicates_in_names():
# Regression test for #5036
assert u.ct.names == ['ct', 'count']
assert u.ct.short_names == ['ct', 'count']
assert u.ct.long_names == ['count']
assert set(u.ph.names) == set(u.ph.short_names) | set(u.ph.long_names)
def test_pickling():
p = pickle.dumps(u.m)
other = pickle.loads(p)
assert other is u.m
new_unit = u.IrreducibleUnit(['foo'], format={'baz': 'bar'})
# This is local, so the unit should not be registered.
assert 'foo' not in u.get_current_unit_registry().registry
# Test pickling of this unregistered unit.
p = pickle.dumps(new_unit)
new_unit_copy = pickle.loads(p)
assert new_unit_copy.names == ['foo']
assert new_unit_copy.get_format_name('baz') == 'bar'
# It should still not be registered.
assert 'foo' not in u.get_current_unit_registry().registry
# Now try the same with a registered unit.
with u.add_enabled_units([new_unit]):
p = pickle.dumps(new_unit)
assert 'foo' in u.get_current_unit_registry().registry
# Check that a registered unit can be loaded and that it gets re-enabled.
with u.add_enabled_units([]):
assert 'foo' not in u.get_current_unit_registry().registry
new_unit_copy = pickle.loads(p)
assert new_unit_copy.names == ['foo']
assert new_unit_copy.get_format_name('baz') == 'bar'
assert 'foo' in u.get_current_unit_registry().registry
# And just to be sure, that it gets removed outside of the context.
assert 'foo' not in u.get_current_unit_registry().registry
def test_pickle_unrecognized_unit():
"""
Issue #2047
"""
a = u.Unit('asdf', parse_strict='silent')
pickle.loads(pickle.dumps(a))
@raises(ValueError)
def test_duplicate_define():
u.def_unit('m', namespace=u.__dict__)
def test_all_units():
from ...units.core import get_current_unit_registry
registry = get_current_unit_registry()
assert len(registry.all_units) > len(registry.non_prefix_units)
def test_repr_latex():
assert u.m._repr_latex_() == u.m.to_string('latex')
def test_operations_with_strings():
assert u.m / '5s' == (u.m / (5.0 * u.s))
assert u.m * '5s' == (5.0 * u.m * u.s)
def test_comparison():
assert u.m > u.cm
assert u.m >= u.cm
assert u.cm < u.m
assert u.cm <= u.m
with pytest.raises(u.UnitsError):
u.m > u.kg
def test_compose_into_arbitrary_units():
# Issue #1438
from ...constants import G
G.decompose([u.kg, u.km, u.Unit("15 s")])
def test_unit_multiplication_with_string():
"""Check that multiplication with strings produces the correct unit."""
u1 = u.cm
us = 'kg'
assert us * u1 == u.Unit(us) * u1
assert u1 * us == u1 * u.Unit(us)
def test_unit_division_by_string():
"""Check that multiplication with strings produces the correct unit."""
u1 = u.cm
us = 'kg'
assert us / u1 == u.Unit(us) / u1
assert u1 / us == u1 / u.Unit(us)
def test_sorted_bases():
"""See #1616."""
assert (u.m * u.Jy).bases == (u.Jy * u.m).bases
def test_megabit():
"""See #1543"""
assert u.Mbit is u.Mb
assert u.megabit is u.Mb
assert u.Mbyte is u.MB
assert u.megabyte is u.MB
def test_composite_unit_get_format_name():
"""See #1576"""
unit1 = u.Unit('nrad/s')
unit2 = u.Unit('Hz(1/2)')
assert (str(u.CompositeUnit(1, [unit1, unit2], [1, -1])) ==
'nrad / (Hz(1/2) s)')
def test_unicode_policy():
from ...tests.helper import assert_follows_unicode_guidelines
assert_follows_unicode_guidelines(
u.degree, roundtrip=u.__dict__)
def test_suggestions():
for search, matches in [
('microns', 'micron'),
('s/microns', 'micron'),
('M', 'm'),
('metre', 'meter'),
('angstroms', 'Angstrom or angstrom'),
('milimeter', 'millimeter'),
('ångström', 'Angstrom or angstrom'),
('kev', 'EV, eV, kV or keV')]:
try:
u.Unit(search)
except ValueError as e:
assert 'Did you mean {0}?'.format(matches) in str(e)
else:
assert False, 'Expected ValueError'
def test_fits_hst_unit():
"""See #1911."""
x = u.Unit("erg /s /cm**2 /angstrom")
assert x == u.erg * u.s ** -1 * u.cm ** -2 * u.angstrom ** -1
def test_barn_prefixes():
"""Regression test for https://github.com/astropy/astropy/issues/3753"""
assert u.fbarn is u.femtobarn
assert u.pbarn is u.picobarn
def test_fractional_powers():
"""See #2069"""
m = 1e9 * u.Msun
tH = 1. / (70. * u.km / u.s / u.Mpc)
vc = 200 * u.km/u.s
x = (c.G ** 2 * m ** 2 * tH.cgs) ** Fraction(1, 3) / vc
v1 = x.to('pc')
x = (c.G ** 2 * m ** 2 * tH) ** Fraction(1, 3) / vc
v2 = x.to('pc')
x = (c.G ** 2 * m ** 2 * tH.cgs) ** (1.0 / 3.0) / vc
v3 = x.to('pc')
x = (c.G ** 2 * m ** 2 * tH) ** (1.0 / 3.0) / vc
v4 = x.to('pc')
assert_allclose(v1, v2)
assert_allclose(v2, v3)
assert_allclose(v3, v4)
x = u.m ** (1.0 / 11.0)
assert isinstance(x.powers[0], float)
x = u.m ** (3.0 / 7.0)
assert isinstance(x.powers[0], Fraction)
assert x.powers[0].numerator == 3
assert x.powers[0].denominator == 7
x = u.cm ** Fraction(1, 2) * u.cm ** Fraction(2, 3)
assert isinstance(x.powers[0], Fraction)
assert x.powers[0] == Fraction(7, 6)
def test_inherit_docstrings():
assert u.UnrecognizedUnit.is_unity.__doc__ == u.UnitBase.is_unity.__doc__
def test_sqrt_mag():
sqrt_mag = u.mag ** 0.5
assert hasattr(sqrt_mag.decompose().scale, 'imag')
assert (sqrt_mag.decompose())**2 == u.mag
def test_composite_compose():
# Issue #2382
composite_unit = u.s.compose(units=[u.Unit("s")])[0]
u.s.compose(units=[composite_unit])
def test_data_quantities():
assert u.byte.is_equivalent(u.bit)
def test_compare_with_none():
# Ensure that equality comparisons with `None` work, and don't
# raise exceptions. We are deliberately not using `is None` here
# because that doesn't trigger the bug. See #3108.
assert not (u.m == None) # nopep8
assert u.m != None # nopep8
def test_validate_power_detect_fraction():
frac = utils.validate_power(1.1666666666666665)
assert isinstance(frac, Fraction)
assert frac.numerator == 7
assert frac.denominator == 6
def test_complex_fractional_rounding_errors():
# See #3788
kappa = 0.34 * u.cm**2 / u.g
r_0 = 886221439924.7849 * u.cm
q = 1.75
rho_0 = 5e-10 * u.solMass / u.solRad**3
y = 0.5
beta = 0.19047619047619049
a = 0.47619047619047628
m_h = 1e6*u.solMass
t1 = 2 * c.c / (kappa * np.sqrt(np.pi))
t2 = (r_0**-q) / (rho_0 * y * beta * (a * c.G * m_h)**0.5)
result = ((t1 * t2)**-0.8)
assert result.unit.physical_type == 'length'
result.to(u.solRad)
def test_fractional_rounding_errors_simple():
x = (u.m ** 1.5) ** Fraction(4, 5)
assert isinstance(x.powers[0], Fraction)
assert x.powers[0].numerator == 6
assert x.powers[0].denominator == 5
def test_enable_unit_groupings():
from ...units import cds
with cds.enable():
assert cds.geoMass in u.kg.find_equivalent_units()
from ...units import imperial
with imperial.enable():
assert imperial.inch in u.m.find_equivalent_units()
def test_unit_summary_prefixes():
"""
Test for a few units that the unit summary table correctly reports
whether or not that unit supports prefixes.
Regression test for https://github.com/astropy/astropy/issues/3835
"""
from .. import astrophys
for summary in utils._iter_unit_summary(astrophys.__dict__):
unit, _, _, _, prefixes = summary
if unit.name == 'lyr':
assert prefixes
elif unit.name == 'pc':
assert prefixes
elif unit.name == 'barn':
assert prefixes
elif unit.name == 'cycle':
assert prefixes == 'No'
elif unit.name == 'vox':
assert prefixes == 'Yes'
|
d31ee12cb1ad061ffe762bc0bc4321853fddad68f1d8e2f7d0fd94c169dfb5c6 | # The purpose of these tests are to ensure that calling quantities using
# array methods returns quantities with the right units, or raises exceptions.
import pytest
import numpy as np
from ... import units as u
from ...utils.compat import NUMPY_LT_1_10_4
class TestQuantityArrayCopy:
"""
Test whether arrays are properly copied/used in place
"""
def test_copy_on_creation(self):
v = np.arange(1000.)
q_nocopy = u.Quantity(v, "km/s", copy=False)
q_copy = u.Quantity(v, "km/s", copy=True)
v[0] = -1.
assert q_nocopy[0].value == v[0]
assert q_copy[0].value != v[0]
def test_to_copies(self):
q = u.Quantity(np.arange(1., 100.), "km/s")
q2 = q.to(u.m/u.s)
assert np.all(q.value != q2.value)
q3 = q.to(u.km/u.s)
assert np.all(q.value == q3.value)
q[0] = -1.*u.km/u.s
assert q[0].value != q3[0].value
def test_si_copies(self):
q = u.Quantity(np.arange(100.), "m/s")
q2 = q.si
assert np.all(q.value == q2.value)
q[0] = -1.*u.m/u.s
assert q[0].value != q2[0].value
def test_getitem_is_view(self):
"""Check that [keys] work, and that, like ndarray, it returns
a view, so that changing one changes the other.
Also test that one can add axes (closes #1422)
"""
q = u.Quantity(np.arange(100.), "m/s")
q_sel = q[10:20]
q_sel[0] = -1.*u.m/u.s
assert q_sel[0] == q[10]
# also check that getitem can do new axes
q2 = q[:, np.newaxis]
q2[10, 0] = -9*u.m/u.s
assert np.all(q2.flatten() == q)
def test_flat(self):
q = u.Quantity(np.arange(9.).reshape(3, 3), "m/s")
q_flat = q.flat
# check that a single item is a quantity (with the right value)
assert q_flat[8] == 8. * u.m / u.s
# and that getting a range works as well
assert np.all(q_flat[0:2] == np.arange(2.) * u.m / u.s)
# as well as getting items via iteration
q_flat_list = [_q for _q in q.flat]
assert np.all(u.Quantity(q_flat_list) ==
u.Quantity([_a for _a in q.value.flat], q.unit))
# check that flat works like a view of the real array
q_flat[8] = -1. * u.km / u.s
assert q_flat[8] == -1. * u.km / u.s
assert q[2, 2] == -1. * u.km / u.s
# while if one goes by an iterated item, a copy is made
q_flat_list[8] = -2 * u.km / u.s
assert q_flat_list[8] == -2. * u.km / u.s
assert q_flat[8] == -1. * u.km / u.s
assert q[2, 2] == -1. * u.km / u.s
class TestQuantityReshapeFuncs:
"""Test different ndarray methods that alter the array shape
tests: reshape, squeeze, ravel, flatten, transpose, swapaxes
"""
def test_reshape(self):
q = np.arange(6.) * u.m
q_reshape = q.reshape(3, 2)
assert isinstance(q_reshape, u.Quantity)
assert q_reshape.unit == q.unit
assert np.all(q_reshape.value == q.value.reshape(3, 2))
def test_squeeze(self):
q = np.arange(6.).reshape(6, 1) * u.m
q_squeeze = q.squeeze()
assert isinstance(q_squeeze, u.Quantity)
assert q_squeeze.unit == q.unit
assert np.all(q_squeeze.value == q.value.squeeze())
def test_ravel(self):
q = np.arange(6.).reshape(3, 2) * u.m
q_ravel = q.ravel()
assert isinstance(q_ravel, u.Quantity)
assert q_ravel.unit == q.unit
assert np.all(q_ravel.value == q.value.ravel())
def test_flatten(self):
q = np.arange(6.).reshape(3, 2) * u.m
q_flatten = q.flatten()
assert isinstance(q_flatten, u.Quantity)
assert q_flatten.unit == q.unit
assert np.all(q_flatten.value == q.value.flatten())
def test_transpose(self):
q = np.arange(6.).reshape(3, 2) * u.m
q_transpose = q.transpose()
assert isinstance(q_transpose, u.Quantity)
assert q_transpose.unit == q.unit
assert np.all(q_transpose.value == q.value.transpose())
def test_swapaxes(self):
q = np.arange(6.).reshape(3, 1, 2) * u.m
q_swapaxes = q.swapaxes(0, 2)
assert isinstance(q_swapaxes, u.Quantity)
assert q_swapaxes.unit == q.unit
assert np.all(q_swapaxes.value == q.value.swapaxes(0, 2))
class TestQuantityStatsFuncs:
"""
Test statistical functions
"""
def test_mean(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
assert np.mean(q1) == 3.6 * u.m
def test_mean_inplace(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
qi = 1.5 * u.s
qi2 = np.mean(q1, out=qi)
assert qi2 is qi
assert qi == 3.6 * u.m
def test_std(self):
q1 = np.array([1., 2.]) * u.m
assert np.std(q1) == 0.5 * u.m
def test_std_inplace(self):
q1 = np.array([1., 2.]) * u.m
qi = 1.5 * u.s
np.std(q1, out=qi)
assert qi == 0.5 * u.m
def test_var(self):
q1 = np.array([1., 2.]) * u.m
assert np.var(q1) == 0.25 * u.m ** 2
def test_var_inplace(self):
q1 = np.array([1., 2.]) * u.m
qi = 1.5 * u.s
np.var(q1, out=qi)
assert qi == 0.25 * u.m ** 2
def test_median(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
assert np.median(q1) == 4. * u.m
def test_median_inplace(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
qi = 1.5 * u.s
np.median(q1, out=qi)
assert qi == 4 * u.m
def test_min(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
assert np.min(q1) == 1. * u.m
def test_min_inplace(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
qi = 1.5 * u.s
np.min(q1, out=qi)
assert qi == 1. * u.m
def test_argmin(self):
q1 = np.array([6., 2., 4., 5., 6.]) * u.m
assert np.argmin(q1) == 1
def test_max(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
assert np.max(q1) == 6. * u.m
def test_max_inplace(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
qi = 1.5 * u.s
np.max(q1, out=qi)
assert qi == 6. * u.m
def test_argmax(self):
q1 = np.array([5., 2., 4., 5., 6.]) * u.m
assert np.argmax(q1) == 4
def test_clip(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.km / u.m
c1 = q1.clip(1500, 5.5 * u.Mm / u.km)
assert np.all(c1 == np.array([1.5, 2., 4., 5., 5.5]) * u.km / u.m)
def test_clip_inplace(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.km / u.m
c1 = q1.clip(1500, 5.5 * u.Mm / u.km, out=q1)
assert np.all(q1 == np.array([1.5, 2., 4., 5., 5.5]) * u.km / u.m)
c1[0] = 10 * u.Mm/u.mm
assert np.all(c1.value == q1.value)
def test_conj(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.km / u.m
assert np.all(q1.conj() == q1)
def test_ptp(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
assert np.ptp(q1) == 5. * u.m
def test_ptp_inplace(self):
q1 = np.array([1., 2., 4., 5., 6.]) * u.m
qi = 1.5 * u.s
np.ptp(q1, out=qi)
assert qi == 5. * u.m
def test_round(self):
q1 = np.array([1.253, 2.253, 3.253]) * u.kg
assert np.all(np.round(q1) == np.array([1, 2, 3]) * u.kg)
assert np.all(np.round(q1, decimals=2) ==
np.round(q1.value, decimals=2) * u.kg)
assert np.all(q1.round(decimals=2) ==
q1.value.round(decimals=2) * u.kg)
def test_round_inplace(self):
q1 = np.array([1.253, 2.253, 3.253]) * u.kg
qi = np.zeros(3) * u.s
a = q1.round(decimals=2, out=qi)
assert a is qi
assert np.all(q1.round(decimals=2) == qi)
def test_sum(self):
q1 = np.array([1., 2., 6.]) * u.m
assert np.all(q1.sum() == 9. * u.m)
assert np.all(np.sum(q1) == 9. * u.m)
q2 = np.array([[4., 5., 9.], [1., 1., 1.]]) * u.s
assert np.all(q2.sum(0) == np.array([5., 6., 10.]) * u.s)
assert np.all(np.sum(q2, 0) == np.array([5., 6., 10.]) * u.s)
def test_sum_inplace(self):
q1 = np.array([1., 2., 6.]) * u.m
qi = 1.5 * u.s
np.sum(q1, out=qi)
assert qi == 9. * u.m
def test_cumsum(self):
q1 = np.array([1, 2, 6]) * u.m
assert np.all(q1.cumsum() == np.array([1, 3, 9]) * u.m)
assert np.all(np.cumsum(q1) == np.array([1, 3, 9]) * u.m)
q2 = np.array([4, 5, 9]) * u.s
assert np.all(q2.cumsum() == np.array([4, 9, 18]) * u.s)
assert np.all(np.cumsum(q2) == np.array([4, 9, 18]) * u.s)
def test_cumsum_inplace(self):
q1 = np.array([1, 2, 6]) * u.m
qi = np.ones(3) * u.s
np.cumsum(q1, out=qi)
assert np.all(qi == np.array([1, 3, 9]) * u.m)
q2 = q1
q1.cumsum(out=q1)
assert np.all(q2 == qi)
def test_nansum(self):
q1 = np.array([1., 2., np.nan]) * u.m
assert np.all(q1.nansum() == 3. * u.m)
assert np.all(np.nansum(q1) == 3. * u.m)
q2 = np.array([[np.nan, 5., 9.], [1., np.nan, 1.]]) * u.s
assert np.all(q2.nansum(0) == np.array([1., 5., 10.]) * u.s)
assert np.all(np.nansum(q2, 0) == np.array([1., 5., 10.]) * u.s)
def test_nansum_inplace(self):
q1 = np.array([1., 2., np.nan]) * u.m
qi = 1.5 * u.s
qout = q1.nansum(out=qi)
assert qout is qi
assert qi == np.nansum(q1.value) * q1.unit
qi2 = 1.5 * u.s
qout2 = np.nansum(q1, out=qi2)
assert qout2 is qi2
assert qi2 == np.nansum(q1.value) * q1.unit
def test_prod(self):
q1 = np.array([1, 2, 6]) * u.m
with pytest.raises(ValueError) as exc:
q1.prod()
assert 'cannot use prod' in exc.value.args[0]
with pytest.raises(ValueError) as exc:
np.prod(q1)
assert 'cannot use prod' in exc.value.args[0]
q2 = np.array([3., 4., 5.]) * u.Unit(1)
assert q2.prod() == 60. * u.Unit(1)
assert np.prod(q2) == 60. * u.Unit(1)
def test_cumprod(self):
q1 = np.array([1, 2, 6]) * u.m
with pytest.raises(ValueError) as exc:
q1.cumprod()
assert 'cannot use cumprod' in exc.value.args[0]
with pytest.raises(ValueError) as exc:
np.cumprod(q1)
assert 'cannot use cumprod' in exc.value.args[0]
q2 = np.array([3, 4, 5]) * u.Unit(1)
assert np.all(q2.cumprod() == np.array([3, 12, 60]) * u.Unit(1))
assert np.all(np.cumprod(q2) == np.array([3, 12, 60]) * u.Unit(1))
def test_diff(self):
q1 = np.array([1., 2., 4., 10.]) * u.m
assert np.all(q1.diff() == np.array([1., 2., 6.]) * u.m)
assert np.all(np.diff(q1) == np.array([1., 2., 6.]) * u.m)
def test_ediff1d(self):
q1 = np.array([1., 2., 4., 10.]) * u.m
assert np.all(q1.ediff1d() == np.array([1., 2., 6.]) * u.m)
assert np.all(np.ediff1d(q1) == np.array([1., 2., 6.]) * u.m)
@pytest.mark.xfail
def test_dot_func(self):
q1 = np.array([1., 2., 4., 10.]) * u.m
q2 = np.array([3., 4., 5., 6.]) * u.s
q3 = np.dot(q1, q2)
assert q3.value == np.dot(q1.value, q2.value)
assert q3.unit == u.m * u.s
def test_dot_meth(self):
q1 = np.array([1., 2., 4., 10.]) * u.m
q2 = np.array([3., 4., 5., 6.]) * u.s
q3 = q1.dot(q2)
assert q3.value == np.dot(q1.value, q2.value)
assert q3.unit == u.m * u.s
@pytest.mark.xfail(NUMPY_LT_1_10_4,
reason="Numpy 1.10.4 or later is required")
def test_trace_func(self):
q = np.array([[1., 2.], [3., 4.]]) * u.m
assert np.trace(q) == 5. * u.m
def test_trace_meth(self):
q1 = np.array([[1., 2.], [3., 4.]]) * u.m
assert q1.trace() == 5. * u.m
cont = u.Quantity(4., u.s)
q2 = np.array([[3., 4.], [5., 6.]]) * u.m
q2.trace(out=cont)
assert cont == 9. * u.m
def test_clip_func(self):
q = np.arange(10) * u.m
assert np.all(np.clip(q, 3 * u.m, 6 * u.m) == np.array([3., 3., 3., 3., 4., 5., 6., 6., 6., 6.]) * u.m)
def test_clip_meth(self):
expected = np.array([3., 3., 3., 3., 4., 5., 6., 6., 6., 6.]) * u.m
q1 = np.arange(10) * u.m
q3 = q1.clip(3 * u.m, 6 * u.m)
assert np.all(q1.clip(3 * u.m, 6 * u.m) == expected)
cont = np.zeros(10) * u.s
q1.clip(3 * u.m, 6 * u.m, out=cont)
assert np.all(cont == expected)
class TestArrayConversion:
"""
Test array conversion methods
"""
def test_item(self):
q1 = u.Quantity(np.array([1, 2, 3]), u.m / u.km, dtype=int)
assert q1.item(1) == 2 * q1.unit
q1.itemset(1, 1)
assert q1.item(1) == 1000 * u.m / u.km
q1.itemset(1, 100 * u.cm / u.km)
assert q1.item(1) == 1 * u.m / u.km
with pytest.raises(TypeError):
q1.itemset(1, 1.5 * u.m / u.km)
with pytest.raises(ValueError):
q1.itemset()
q1[1] = 1
assert q1[1] == 1000 * u.m / u.km
q1[1] = 100 * u.cm / u.km
assert q1[1] == 1 * u.m / u.km
with pytest.raises(TypeError):
q1[1] = 1.5 * u.m / u.km
q1 = np.array([1, 2, 3]) * u.m / u.km
assert all(q1.take((0, 2)) == np.array([1, 3]) * u.m / u.km)
q1.put((1, 2), (3, 4))
assert np.all(q1.take((1, 2)) == np.array([3000, 4000]) * q1.unit)
q1.put(0, 500 * u.cm / u.km)
assert q1.item(0) == 5 * u.m / u.km
def test_slice(self):
"""Test that setitem changes the unit if needed (or ignores it for
values where that is allowed; viz., #2695)"""
q2 = np.array([[1., 2., 3.], [4., 5., 6.]]) * u.km / u.m
q1 = q2.copy()
q2[0, 0] = 10000.
assert q2.unit == q1.unit
assert q2[0, 0].value == 10.
q2[0] = 9. * u.Mm / u.km
assert all(q2.flatten()[:3].value == np.array([9., 9., 9.]))
q2[0, :-1] = 8000.
assert all(q2.flatten()[:3].value == np.array([8., 8., 9.]))
with pytest.raises(u.UnitsError):
q2[1, 1] = 10 * u.s
# just to be sure, repeat with a dimensionfull unit
q3 = u.Quantity(np.arange(10.), "m/s")
q3[5] = 100. * u.cm / u.s
assert q3[5].value == 1.
# and check unit is ignored for 0, inf, nan, where that is reasonable
q3[5] = 0.
assert q3[5] == 0.
q3[5] = np.inf
assert np.isinf(q3[5])
q3[5] = np.nan
assert np.isnan(q3[5])
def test_fill(self):
q1 = np.array([1, 2, 3]) * u.m / u.km
q1.fill(2)
assert np.all(q1 == 2000 * u.m / u.km)
def test_repeat_compress_diagonal(self):
q1 = np.array([1, 2, 3]) * u.m / u.km
q2 = q1.repeat(2)
assert q2.unit == q1.unit
assert all(q2.value == q1.value.repeat(2))
q2.sort()
assert q2.unit == q1.unit
q2 = q1.compress(np.array([True, True, False, False]))
assert q2.unit == q1.unit
assert all(q2.value == q1.value.compress(np.array([True, True,
False, False])))
q1 = np.array([[1, 2], [3, 4]]) * u.m / u.km
q2 = q1.diagonal()
assert q2.unit == q1.unit
assert all(q2.value == q1.value.diagonal())
def test_view(self):
q1 = np.array([1, 2, 3], dtype=np.int64) * u.m / u.km
q2 = q1.view(np.ndarray)
assert not hasattr(q2, 'unit')
q3 = q2.view(u.Quantity)
assert q3._unit is None
# MaskedArray copies and properties assigned in __dict__
q4 = np.ma.MaskedArray(q1)
assert q4._unit is q1._unit
q5 = q4.view(u.Quantity)
assert q5.unit is q1.unit
def test_slice_to_quantity(self):
"""
Regression test for https://github.com/astropy/astropy/issues/2003
"""
a = np.random.uniform(size=(10, 8))
x, y, z = a[:, 1:4].T * u.km/u.s
total = np.sum(a[:, 1] * u.km / u.s - x)
assert isinstance(total, u.Quantity)
assert total == (0.0 * u.km / u.s)
def test_byte_type_view_field_changes(self):
q1 = np.array([1, 2, 3], dtype=np.int64) * u.m / u.km
q2 = q1.byteswap()
assert q2.unit == q1.unit
assert all(q2.value == q1.value.byteswap())
q2 = q1.astype(np.float64)
assert all(q2 == q1)
assert q2.dtype == np.float64
q2a = q1.getfield(np.int32, offset=0)
q2b = q1.byteswap().getfield(np.int32, offset=4)
assert q2a.unit == q1.unit
assert all(q2b.byteswap() == q2a)
def test_sort(self):
q1 = np.array([1., 5., 2., 4.]) * u.km / u.m
i = q1.argsort()
assert not hasattr(i, 'unit')
q1.sort()
i = q1.searchsorted([1500, 2500])
assert not hasattr(i, 'unit')
assert all(i == q1.to(
u.dimensionless_unscaled).value.searchsorted([1500, 2500]))
def test_not_implemented(self):
q1 = np.array([1, 2, 3]) * u.m / u.km
with pytest.raises(NotImplementedError):
q1.choose([0, 0, 1])
with pytest.raises(NotImplementedError):
q1.tolist()
with pytest.raises(NotImplementedError):
q1.tostring()
with pytest.raises(NotImplementedError):
q1.tofile(0)
with pytest.raises(NotImplementedError):
q1.dump('a.a')
with pytest.raises(NotImplementedError):
q1.dumps()
class TestRecArray:
"""Record arrays are not specifically supported, but we should not
prevent their use unnecessarily"""
def setup(self):
self.ra = (np.array(np.arange(12.).reshape(4, 3))
.view(dtype=('f8,f8,f8')).squeeze())
def test_creation(self):
qra = u.Quantity(self.ra, u.m)
assert np.all(qra[:2].value == self.ra[:2])
def test_equality(self):
qra = u.Quantity(self.ra, u.m)
qra[1] = qra[2]
assert qra[1] == qra[2]
|
53dcb3c23467a5d6c24798e19ba662c98087e6608693b023e555aff558318613 | # coding: utf-8
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Test the Logarithmic Units and Quantities
"""
import pickle
import itertools
import pytest
import numpy as np
from numpy.testing.utils import assert_allclose
from ...tests.helper import assert_quantity_allclose
from ... import units as u, constants as c
lu_units = [u.dex, u.mag, u.decibel]
lu_subclasses = [u.DexUnit, u.MagUnit, u.DecibelUnit]
lq_subclasses = [u.Dex, u.Magnitude, u.Decibel]
pu_sample = (u.dimensionless_unscaled, u.m, u.g/u.s**2, u.Jy)
class TestLogUnitCreation:
def test_logarithmic_units(self):
"""Check logarithmic units are set up correctly."""
assert u.dB.to(u.dex) == 0.1
assert u.dex.to(u.mag) == -2.5
assert u.mag.to(u.dB) == -4
@pytest.mark.parametrize('lu_unit, lu_cls', zip(lu_units, lu_subclasses))
def test_callable_units(self, lu_unit, lu_cls):
assert isinstance(lu_unit, u.UnitBase)
assert callable(lu_unit)
assert lu_unit._function_unit_class is lu_cls
@pytest.mark.parametrize('lu_unit', lu_units)
def test_equality_to_normal_unit_for_dimensionless(self, lu_unit):
lu = lu_unit()
assert lu == lu._default_function_unit # eg, MagUnit() == u.mag
assert lu._default_function_unit == lu # and u.mag == MagUnit()
@pytest.mark.parametrize('lu_unit, physical_unit',
itertools.product(lu_units, pu_sample))
def test_call_units(self, lu_unit, physical_unit):
"""Create a LogUnit subclass using the callable unit and physical unit,
and do basic check that output is right."""
lu1 = lu_unit(physical_unit)
assert lu1.physical_unit == physical_unit
assert lu1.function_unit == lu1._default_function_unit
def test_call_invalid_unit(self):
with pytest.raises(TypeError):
u.mag([])
with pytest.raises(ValueError):
u.mag(u.mag())
@pytest.mark.parametrize('lu_cls, physical_unit', itertools.product(
lu_subclasses + [u.LogUnit], pu_sample))
def test_subclass_creation(self, lu_cls, physical_unit):
"""Create a LogUnit subclass object for given physical unit,
and do basic check that output is right."""
lu1 = lu_cls(physical_unit)
assert lu1.physical_unit == physical_unit
assert lu1.function_unit == lu1._default_function_unit
lu2 = lu_cls(physical_unit,
function_unit=2*lu1._default_function_unit)
assert lu2.physical_unit == physical_unit
assert lu2.function_unit == u.Unit(2*lu2._default_function_unit)
with pytest.raises(ValueError):
lu_cls(physical_unit, u.m)
def test_predefined_magnitudes():
assert_quantity_allclose((-21.1*u.STmag).physical,
1.*u.erg/u.cm**2/u.s/u.AA)
assert_quantity_allclose((-48.6*u.ABmag).physical,
1.*u.erg/u.cm**2/u.s/u.Hz)
assert_quantity_allclose((0*u.M_bol).physical, c.L_bol0)
assert_quantity_allclose((0*u.m_bol).physical,
c.L_bol0/(4.*np.pi*(10.*c.pc)**2))
def test_predefined_reinitialisation():
assert u.mag('ST') == u.STmag
assert u.mag('AB') == u.ABmag
assert u.mag('Bol') == u.M_bol
assert u.mag('bol') == u.m_bol
def test_predefined_string_roundtrip():
"""Ensure roundtripping; see #5015"""
with u.magnitude_zero_points.enable():
assert u.Unit(u.STmag.to_string()) == u.STmag
assert u.Unit(u.ABmag.to_string()) == u.ABmag
assert u.Unit(u.M_bol.to_string()) == u.M_bol
assert u.Unit(u.m_bol.to_string()) == u.m_bol
def test_inequality():
"""Check __ne__ works (regresssion for #5342)."""
lu1 = u.mag(u.Jy)
lu2 = u.dex(u.Jy)
lu3 = u.mag(u.Jy**2)
lu4 = lu3 - lu1
assert lu1 != lu2
assert lu1 != lu3
assert lu1 == lu4
class TestLogUnitStrings:
def test_str(self):
"""Do some spot checks that str, repr, etc. work as expected."""
lu1 = u.mag(u.Jy)
assert str(lu1) == 'mag(Jy)'
assert repr(lu1) == 'Unit("mag(Jy)")'
assert lu1.to_string('generic') == 'mag(Jy)'
with pytest.raises(ValueError):
lu1.to_string('fits')
lu2 = u.dex()
assert str(lu2) == 'dex'
assert repr(lu2) == 'Unit("dex(1)")'
assert lu2.to_string() == 'dex(1)'
lu3 = u.MagUnit(u.Jy, function_unit=2*u.mag)
assert str(lu3) == '2 mag(Jy)'
assert repr(lu3) == 'MagUnit("Jy", unit="2 mag")'
assert lu3.to_string() == '2 mag(Jy)'
lu4 = u.mag(u.ct)
assert lu4.to_string('generic') == 'mag(ct)'
assert lu4.to_string('latex') == ('$\\mathrm{mag}$$\\mathrm{\\left( '
'\\mathrm{ct} \\right)}$')
assert lu4._repr_latex_() == lu4.to_string('latex')
class TestLogUnitConversion:
@pytest.mark.parametrize('lu_unit, physical_unit',
itertools.product(lu_units, pu_sample))
def test_physical_unit_conversion(self, lu_unit, physical_unit):
"""Check various LogUnit subclasses are equivalent and convertible
to their non-log counterparts."""
lu1 = lu_unit(physical_unit)
assert lu1.is_equivalent(physical_unit)
assert lu1.to(physical_unit, 0.) == 1.
assert physical_unit.is_equivalent(lu1)
assert physical_unit.to(lu1, 1.) == 0.
pu = u.Unit(8.*physical_unit)
assert lu1.is_equivalent(physical_unit)
assert lu1.to(pu, 0.) == 0.125
assert pu.is_equivalent(lu1)
assert_allclose(pu.to(lu1, 0.125), 0., atol=1.e-15)
# Check we round-trip.
value = np.linspace(0., 10., 6)
assert_allclose(pu.to(lu1, lu1.to(pu, value)), value, atol=1.e-15)
# And that we're not just returning True all the time.
pu2 = u.g
assert not lu1.is_equivalent(pu2)
with pytest.raises(u.UnitsError):
lu1.to(pu2)
assert not pu2.is_equivalent(lu1)
with pytest.raises(u.UnitsError):
pu2.to(lu1)
@pytest.mark.parametrize('lu_unit', lu_units)
def test_container_unit_conversion(self, lu_unit):
"""Check that conversion to logarithmic units (u.mag, u.dB, u.dex)
is only possible when the physical unit is dimensionless."""
values = np.linspace(0., 10., 6)
lu1 = lu_unit(u.dimensionless_unscaled)
assert lu1.is_equivalent(lu1.function_unit)
assert_allclose(lu1.to(lu1.function_unit, values), values)
lu2 = lu_unit(u.Jy)
assert not lu2.is_equivalent(lu2.function_unit)
with pytest.raises(u.UnitsError):
lu2.to(lu2.function_unit, values)
@pytest.mark.parametrize(
'flu_unit, tlu_unit, physical_unit',
itertools.product(lu_units, lu_units, pu_sample))
def test_subclass_conversion(self, flu_unit, tlu_unit, physical_unit):
"""Check various LogUnit subclasses are equivalent and convertible
to each other if they correspond to equivalent physical units."""
values = np.linspace(0., 10., 6)
flu = flu_unit(physical_unit)
tlu = tlu_unit(physical_unit)
assert flu.is_equivalent(tlu)
assert_allclose(flu.to(tlu), flu.function_unit.to(tlu.function_unit))
assert_allclose(flu.to(tlu, values),
values * flu.function_unit.to(tlu.function_unit))
tlu2 = tlu_unit(u.Unit(100.*physical_unit))
assert flu.is_equivalent(tlu2)
# Check that we round-trip.
assert_allclose(flu.to(tlu2, tlu2.to(flu, values)), values, atol=1.e-15)
tlu3 = tlu_unit(physical_unit.to_system(u.si)[0])
assert flu.is_equivalent(tlu3)
assert_allclose(flu.to(tlu3, tlu3.to(flu, values)), values, atol=1.e-15)
tlu4 = tlu_unit(u.g)
assert not flu.is_equivalent(tlu4)
with pytest.raises(u.UnitsError):
flu.to(tlu4, values)
def test_unit_decomposition(self):
lu = u.mag(u.Jy)
assert lu.decompose() == u.mag(u.Jy.decompose())
assert lu.decompose().physical_unit.bases == [u.kg, u.s]
assert lu.si == u.mag(u.Jy.si)
assert lu.si.physical_unit.bases == [u.kg, u.s]
assert lu.cgs == u.mag(u.Jy.cgs)
assert lu.cgs.physical_unit.bases == [u.g, u.s]
def test_unit_multiple_possible_equivalencies(self):
lu = u.mag(u.Jy)
assert lu.is_equivalent(pu_sample)
class TestLogUnitArithmetic:
def test_multiplication_division(self):
"""Check that multiplication/division with other units is only
possible when the physical unit is dimensionless, and that this
turns the unit into a normal one."""
lu1 = u.mag(u.Jy)
with pytest.raises(u.UnitsError):
lu1 * u.m
with pytest.raises(u.UnitsError):
u.m * lu1
with pytest.raises(u.UnitsError):
lu1 / lu1
for unit in (u.dimensionless_unscaled, u.m, u.mag, u.dex):
with pytest.raises(u.UnitsError):
lu1 / unit
lu2 = u.mag(u.dimensionless_unscaled)
with pytest.raises(u.UnitsError):
lu2 * lu1
with pytest.raises(u.UnitsError):
lu2 / lu1
# But dimensionless_unscaled can be cancelled.
assert lu2 / lu2 == u.dimensionless_unscaled
# With dimensionless, normal units are OK, but we return a plain unit.
tf = lu2 * u.m
tr = u.m * lu2
for t in (tf, tr):
assert not isinstance(t, type(lu2))
assert t == lu2.function_unit * u.m
with u.set_enabled_equivalencies(u.logarithmic()):
with pytest.raises(u.UnitsError):
t.to(lu2.physical_unit)
# Now we essentially have a LogUnit with a prefactor of 100,
# so should be equivalent again.
t = tf / u.cm
with u.set_enabled_equivalencies(u.logarithmic()):
assert t.is_equivalent(lu2.function_unit)
assert_allclose(t.to(u.dimensionless_unscaled, np.arange(3.)/100.),
lu2.to(lu2.physical_unit, np.arange(3.)))
# If we effectively remove lu1, a normal unit should be returned.
t2 = tf / lu2
assert not isinstance(t2, type(lu2))
assert t2 == u.m
t3 = tf / lu2.function_unit
assert not isinstance(t3, type(lu2))
assert t3 == u.m
# For completeness, also ensure non-sensical operations fail
with pytest.raises(TypeError):
lu1 * object()
with pytest.raises(TypeError):
slice(None) * lu1
with pytest.raises(TypeError):
lu1 / []
with pytest.raises(TypeError):
1 / lu1
@pytest.mark.parametrize('power', (2, 0.5, 1, 0))
def test_raise_to_power(self, power):
"""Check that raising LogUnits to some power is only possible when the
physical unit is dimensionless, and that conversion is turned off when
the resulting logarithmic unit (such as mag**2) is incompatible."""
lu1 = u.mag(u.Jy)
if power == 0:
assert lu1 ** power == u.dimensionless_unscaled
elif power == 1:
assert lu1 ** power == lu1
else:
with pytest.raises(u.UnitsError):
lu1 ** power
# With dimensionless, though, it works, but returns a normal unit.
lu2 = u.mag(u.dimensionless_unscaled)
t = lu2**power
if power == 0:
assert t == u.dimensionless_unscaled
elif power == 1:
assert t == lu2
else:
assert not isinstance(t, type(lu2))
assert t == lu2.function_unit**power
# also check we roundtrip
t2 = t**(1./power)
assert t2 == lu2.function_unit
with u.set_enabled_equivalencies(u.logarithmic()):
assert_allclose(t2.to(u.dimensionless_unscaled, np.arange(3.)),
lu2.to(lu2.physical_unit, np.arange(3.)))
@pytest.mark.parametrize('other', pu_sample)
def test_addition_subtraction_to_normal_units_fails(self, other):
lu1 = u.mag(u.Jy)
with pytest.raises(u.UnitsError):
lu1 + other
with pytest.raises(u.UnitsError):
lu1 - other
with pytest.raises(u.UnitsError):
other - lu1
def test_addition_subtraction_to_non_units_fails(self):
lu1 = u.mag(u.Jy)
with pytest.raises(TypeError):
lu1 + 1.
with pytest.raises(TypeError):
lu1 - [1., 2., 3.]
@pytest.mark.parametrize(
'other', (u.mag, u.mag(), u.mag(u.Jy), u.mag(u.m),
u.Unit(2*u.mag), u.MagUnit('', 2.*u.mag)))
def test_addition_subtraction(self, other):
"""Check physical units are changed appropriately"""
lu1 = u.mag(u.Jy)
other_pu = getattr(other, 'physical_unit', u.dimensionless_unscaled)
lu_sf = lu1 + other
assert lu_sf.is_equivalent(lu1.physical_unit * other_pu)
lu_sr = other + lu1
assert lu_sr.is_equivalent(lu1.physical_unit * other_pu)
lu_df = lu1 - other
assert lu_df.is_equivalent(lu1.physical_unit / other_pu)
lu_dr = other - lu1
assert lu_dr.is_equivalent(other_pu / lu1.physical_unit)
def test_complicated_addition_subtraction(self):
"""for fun, a more complicated example of addition and subtraction"""
dm0 = u.Unit('DM', 1./(4.*np.pi*(10.*u.pc)**2))
lu_dm = u.mag(dm0)
lu_absST = u.STmag - lu_dm
assert lu_absST.is_equivalent(u.erg/u.s/u.AA)
def test_neg_pos(self):
lu1 = u.mag(u.Jy)
neg_lu = -lu1
assert neg_lu != lu1
assert neg_lu.physical_unit == u.Jy**-1
assert -neg_lu == lu1
pos_lu = +lu1
assert pos_lu is not lu1
assert pos_lu == lu1
def test_pickle():
lu1 = u.dex(u.cm/u.s**2)
s = pickle.dumps(lu1)
lu2 = pickle.loads(s)
assert lu1 == lu2
def test_hashable():
lu1 = u.dB(u.mW)
lu2 = u.dB(u.m)
lu3 = u.dB(u.mW)
assert hash(lu1) != hash(lu2)
assert hash(lu1) == hash(lu3)
luset = {lu1, lu2, lu3}
assert len(luset) == 2
class TestLogQuantityCreation:
@pytest.mark.parametrize('lq, lu', zip(lq_subclasses + [u.LogQuantity],
lu_subclasses + [u.LogUnit]))
def test_logarithmic_quantities(self, lq, lu):
"""Check logarithmic quantities are all set up correctly"""
assert lq._unit_class == lu
assert type(lu()._quantity_class(1.)) is lq
@pytest.mark.parametrize('lq_cls, physical_unit',
itertools.product(lq_subclasses, pu_sample))
def test_subclass_creation(self, lq_cls, physical_unit):
"""Create LogQuantity subclass objects for some physical units,
and basic check on transformations"""
value = np.arange(1., 10.)
log_q = lq_cls(value * physical_unit)
assert log_q.unit.physical_unit == physical_unit
assert log_q.unit.function_unit == log_q.unit._default_function_unit
assert_allclose(log_q.physical.value, value)
with pytest.raises(ValueError):
lq_cls(value, physical_unit)
@pytest.mark.parametrize(
'unit', (u.mag, u.mag(), u.mag(u.Jy), u.mag(u.m),
u.Unit(2*u.mag), u.MagUnit('', 2.*u.mag),
u.MagUnit(u.Jy, -1*u.mag), u.MagUnit(u.m, -2.*u.mag)))
def test_different_units(self, unit):
q = u.Magnitude(1.23, unit)
assert q.unit.function_unit == getattr(unit, 'function_unit', unit)
assert q.unit.physical_unit is getattr(unit, 'physical_unit',
u.dimensionless_unscaled)
@pytest.mark.parametrize('value, unit', (
(1.*u.mag(u.Jy), None),
(1.*u.dex(u.Jy), None),
(1.*u.mag(u.W/u.m**2/u.Hz), u.mag(u.Jy)),
(1.*u.dex(u.W/u.m**2/u.Hz), u.mag(u.Jy))))
def test_function_values(self, value, unit):
lq = u.Magnitude(value, unit)
assert lq == value
assert lq.unit.function_unit == u.mag
assert lq.unit.physical_unit == getattr(unit, 'physical_unit',
value.unit.physical_unit)
@pytest.mark.parametrize(
'unit', (u.mag(), u.mag(u.Jy), u.mag(u.m), u.MagUnit('', 2.*u.mag),
u.MagUnit(u.Jy, -1*u.mag), u.MagUnit(u.m, -2.*u.mag)))
def test_indirect_creation(self, unit):
q1 = 2.5 * unit
assert isinstance(q1, u.Magnitude)
assert q1.value == 2.5
assert q1.unit == unit
pv = 100. * unit.physical_unit
q2 = unit * pv
assert q2.unit == unit
assert q2.unit.physical_unit == pv.unit
assert q2.to_value(unit.physical_unit) == 100.
assert (q2._function_view / u.mag).to_value(1) == -5.
q3 = unit / 0.4
assert q3 == q1
def test_from_view(self):
# Cannot view a physical quantity as a function quantity, since the
# values would change.
q = [100., 1000.] * u.cm/u.s**2
with pytest.raises(TypeError):
q.view(u.Dex)
# But fine if we have the right magnitude.
q = [2., 3.] * u.dex
lq = q.view(u.Dex)
assert isinstance(lq, u.Dex)
assert lq.unit.physical_unit == u.dimensionless_unscaled
assert np.all(q == lq)
def test_using_quantity_class(self):
"""Check that we can use Quantity if we have subok=True"""
# following issue #5851
lu = u.dex(u.AA)
with pytest.raises(u.UnitTypeError):
u.Quantity(1., lu)
q = u.Quantity(1., lu, subok=True)
assert type(q) is lu._quantity_class
def test_conversion_to_and_from_physical_quantities():
"""Ensures we can convert from regular quantities."""
mst = [10., 12., 14.] * u.STmag
flux_lambda = mst.physical
mst_roundtrip = flux_lambda.to(u.STmag)
# check we return a logquantity; see #5178.
assert isinstance(mst_roundtrip, u.Magnitude)
assert mst_roundtrip.unit == mst.unit
assert_allclose(mst_roundtrip.value, mst.value)
wave = [4956.8, 4959.55, 4962.3] * u.AA
flux_nu = mst.to(u.Jy, equivalencies=u.spectral_density(wave))
mst_roundtrip2 = flux_nu.to(u.STmag, u.spectral_density(wave))
assert isinstance(mst_roundtrip2, u.Magnitude)
assert mst_roundtrip2.unit == mst.unit
assert_allclose(mst_roundtrip2.value, mst.value)
def test_quantity_decomposition():
lq = 10.*u.mag(u.Jy)
assert lq.decompose() == lq
assert lq.decompose().unit.physical_unit.bases == [u.kg, u.s]
assert lq.si == lq
assert lq.si.unit.physical_unit.bases == [u.kg, u.s]
assert lq.cgs == lq
assert lq.cgs.unit.physical_unit.bases == [u.g, u.s]
class TestLogQuantityViews:
def setup(self):
self.lq = u.Magnitude(np.arange(10.) * u.Jy)
self.lq2 = u.Magnitude(np.arange(5.))
def test_value_view(self):
lq_value = self.lq.value
assert type(lq_value) is np.ndarray
lq_value[2] = -1.
assert np.all(self.lq.value == lq_value)
def test_function_view(self):
lq_fv = self.lq._function_view
assert type(lq_fv) is u.Quantity
assert lq_fv.unit is self.lq.unit.function_unit
lq_fv[3] = -2. * lq_fv.unit
assert np.all(self.lq.value == lq_fv.value)
def test_quantity_view(self):
# Cannot view as Quantity, since the unit cannot be represented.
with pytest.raises(TypeError):
self.lq.view(u.Quantity)
# But a dimensionless one is fine.
q2 = self.lq2.view(u.Quantity)
assert q2.unit is u.mag
assert np.all(q2.value == self.lq2.value)
lq3 = q2.view(u.Magnitude)
assert type(lq3.unit) is u.MagUnit
assert lq3.unit.physical_unit == u.dimensionless_unscaled
assert np.all(lq3 == self.lq2)
class TestLogQuantitySlicing:
def test_item_get_and_set(self):
lq1 = u.Magnitude(np.arange(1., 11.)*u.Jy)
assert lq1[9] == u.Magnitude(10.*u.Jy)
lq1[2] = 100.*u.Jy
assert lq1[2] == u.Magnitude(100.*u.Jy)
with pytest.raises(u.UnitsError):
lq1[2] = 100.*u.m
with pytest.raises(u.UnitsError):
lq1[2] = 100.*u.mag
with pytest.raises(u.UnitsError):
lq1[2] = u.Magnitude(100.*u.m)
assert lq1[2] == u.Magnitude(100.*u.Jy)
def test_slice_get_and_set(self):
lq1 = u.Magnitude(np.arange(1., 10.)*u.Jy)
lq1[2:4] = 100.*u.Jy
assert np.all(lq1[2:4] == u.Magnitude(100.*u.Jy))
with pytest.raises(u.UnitsError):
lq1[2:4] = 100.*u.m
with pytest.raises(u.UnitsError):
lq1[2:4] = 100.*u.mag
with pytest.raises(u.UnitsError):
lq1[2:4] = u.Magnitude(100.*u.m)
assert np.all(lq1[2] == u.Magnitude(100.*u.Jy))
class TestLogQuantityArithmetic:
def test_multiplication_division(self):
"""Check that multiplication/division with other quantities is only
possible when the physical unit is dimensionless, and that this turns
the result into a normal quantity."""
lq = u.Magnitude(np.arange(1., 11.)*u.Jy)
with pytest.raises(u.UnitsError):
lq * (1.*u.m)
with pytest.raises(u.UnitsError):
(1.*u.m) * lq
with pytest.raises(u.UnitsError):
lq / lq
for unit in (u.m, u.mag, u.dex):
with pytest.raises(u.UnitsError):
lq / unit
lq2 = u.Magnitude(np.arange(1, 11.))
with pytest.raises(u.UnitsError):
lq2 * lq
with pytest.raises(u.UnitsError):
lq2 / lq
with pytest.raises(u.UnitsError):
lq / lq2
# but dimensionless_unscaled can be cancelled
r = lq2 / u.Magnitude(2.)
assert r.unit == u.dimensionless_unscaled
assert np.all(r.value == lq2.value/2.)
# with dimensionless, normal units OK, but return normal quantities
tf = lq2 * u.m
tr = u.m * lq2
for t in (tf, tr):
assert not isinstance(t, type(lq2))
assert t.unit == lq2.unit.function_unit * u.m
with u.set_enabled_equivalencies(u.logarithmic()):
with pytest.raises(u.UnitsError):
t.to(lq2.unit.physical_unit)
t = tf / (50.*u.cm)
# now we essentially have the same quantity but with a prefactor of 2
assert t.unit.is_equivalent(lq2.unit.function_unit)
assert_allclose(t.to(lq2.unit.function_unit), lq2._function_view*2)
@pytest.mark.parametrize('power', (2, 0.5, 1, 0))
def test_raise_to_power(self, power):
"""Check that raising LogQuantities to some power is only possible when
the physical unit is dimensionless, and that conversion is turned off
when the resulting logarithmic unit (say, mag**2) is incompatible."""
lq = u.Magnitude(np.arange(1., 4.)*u.Jy)
if power == 0:
assert np.all(lq ** power == 1.)
elif power == 1:
assert np.all(lq ** power == lq)
else:
with pytest.raises(u.UnitsError):
lq ** power
# with dimensionless, it works, but falls back to normal quantity
# (except for power=1)
lq2 = u.Magnitude(np.arange(10.))
t = lq2**power
if power == 0:
assert t.unit is u.dimensionless_unscaled
assert np.all(t.value == 1.)
elif power == 1:
assert np.all(t == lq2)
else:
assert not isinstance(t, type(lq2))
assert t.unit == lq2.unit.function_unit ** power
with u.set_enabled_equivalencies(u.logarithmic()):
with pytest.raises(u.UnitsError):
t.to(u.dimensionless_unscaled)
def test_error_on_lq_as_power(self):
lq = u.Magnitude(np.arange(1., 4.)*u.Jy)
with pytest.raises(TypeError):
lq ** lq
@pytest.mark.parametrize('other', pu_sample)
def test_addition_subtraction_to_normal_units_fails(self, other):
lq = u.Magnitude(np.arange(1., 10.)*u.Jy)
q = 1.23 * other
with pytest.raises(u.UnitsError):
lq + q
with pytest.raises(u.UnitsError):
lq - q
with pytest.raises(u.UnitsError):
q - lq
@pytest.mark.parametrize(
'other', (1.23 * u.mag, 2.34 * u.mag(),
u.Magnitude(3.45 * u.Jy), u.Magnitude(4.56 * u.m),
5.67 * u.Unit(2*u.mag), u.Magnitude(6.78, 2.*u.mag)))
def test_addition_subtraction(self, other):
"""Check that addition/subtraction with quantities with magnitude or
MagUnit units works, and that it changes the physical units
appropriately."""
lq = u.Magnitude(np.arange(1., 10.)*u.Jy)
other_physical = other.to(getattr(other.unit, 'physical_unit',
u.dimensionless_unscaled),
equivalencies=u.logarithmic())
lq_sf = lq + other
assert_allclose(lq_sf.physical, lq.physical * other_physical)
lq_sr = other + lq
assert_allclose(lq_sr.physical, lq.physical * other_physical)
lq_df = lq - other
assert_allclose(lq_df.physical, lq.physical / other_physical)
lq_dr = other - lq
assert_allclose(lq_dr.physical, other_physical / lq.physical)
@pytest.mark.parametrize('other', pu_sample)
def test_inplace_addition_subtraction_unit_checks(self, other):
lu1 = u.mag(u.Jy)
lq1 = u.Magnitude(np.arange(1., 10.), lu1)
with pytest.raises(u.UnitsError):
lq1 += other
assert np.all(lq1.value == np.arange(1., 10.))
assert lq1.unit == lu1
with pytest.raises(u.UnitsError):
lq1 -= other
assert np.all(lq1.value == np.arange(1., 10.))
assert lq1.unit == lu1
@pytest.mark.parametrize(
'other', (1.23 * u.mag, 2.34 * u.mag(),
u.Magnitude(3.45 * u.Jy), u.Magnitude(4.56 * u.m),
5.67 * u.Unit(2*u.mag), u.Magnitude(6.78, 2.*u.mag)))
def test_inplace_addition_subtraction(self, other):
"""Check that inplace addition/subtraction with quantities with
magnitude or MagUnit units works, and that it changes the physical
units appropriately."""
lq = u.Magnitude(np.arange(1., 10.)*u.Jy)
other_physical = other.to(getattr(other.unit, 'physical_unit',
u.dimensionless_unscaled),
equivalencies=u.logarithmic())
lq_sf = lq.copy()
lq_sf += other
assert_allclose(lq_sf.physical, lq.physical * other_physical)
lq_df = lq.copy()
lq_df -= other
assert_allclose(lq_df.physical, lq.physical / other_physical)
def test_complicated_addition_subtraction(self):
"""For fun, a more complicated example of addition and subtraction."""
dm0 = u.Unit('DM', 1./(4.*np.pi*(10.*u.pc)**2))
DMmag = u.mag(dm0)
m_st = 10. * u.STmag
dm = 5. * DMmag
M_st = m_st - dm
assert M_st.unit.is_equivalent(u.erg/u.s/u.AA)
assert np.abs(M_st.physical /
(m_st.physical*4.*np.pi*(100.*u.pc)**2) - 1.) < 1.e-15
class TestLogQuantityComparisons:
def test_comparison_to_non_quantities_fails(self):
lq = u.Magnitude(np.arange(1., 10.)*u.Jy)
with pytest.raises(TypeError):
lq > 'a'
assert not (lq == 'a')
assert lq != 'a'
def test_comparison(self):
lq1 = u.Magnitude(np.arange(1., 4.)*u.Jy)
lq2 = u.Magnitude(2.*u.Jy)
assert np.all((lq1 > lq2) == np.array([True, False, False]))
assert np.all((lq1 == lq2) == np.array([False, True, False]))
lq3 = u.Dex(2.*u.Jy)
assert np.all((lq1 > lq3) == np.array([True, False, False]))
assert np.all((lq1 == lq3) == np.array([False, True, False]))
lq4 = u.Magnitude(2.*u.m)
assert not (lq1 == lq4)
assert lq1 != lq4
with pytest.raises(u.UnitsError):
lq1 < lq4
q5 = 1.5 * u.Jy
assert np.all((lq1 > q5) == np.array([True, False, False]))
assert np.all((q5 < lq1) == np.array([True, False, False]))
with pytest.raises(u.UnitsError):
lq1 >= 2.*u.m
with pytest.raises(u.UnitsError):
lq1 <= lq1.value * u.mag
# For physically dimensionless, we can compare with the function unit.
lq6 = u.Magnitude(np.arange(1., 4.))
fv6 = lq6.value * u.mag
assert np.all(lq6 == fv6)
# but not some arbitrary unit, of course.
with pytest.raises(u.UnitsError):
lq6 < 2.*u.m
class TestLogQuantityMethods:
def setup(self):
self.mJy = np.arange(1., 5.).reshape(2, 2) * u.mag(u.Jy)
self.m1 = np.arange(1., 5.5, 0.5).reshape(3, 3) * u.mag()
self.mags = (self.mJy, self.m1)
@pytest.mark.parametrize('method', ('mean', 'min', 'max', 'round', 'trace',
'std', 'var', 'ptp', 'diff', 'ediff1d'))
def test_always_ok(self, method):
for mag in self.mags:
res = getattr(mag, method)()
assert np.all(res.value ==
getattr(mag._function_view, method)().value)
if method in ('std', 'ptp', 'diff', 'ediff1d'):
assert res.unit == u.mag()
elif method == 'var':
assert res.unit == u.mag**2
else:
assert res.unit == mag.unit
def test_clip(self):
for mag in self.mags:
assert np.all(mag.clip(2. * mag.unit, 4. * mag.unit).value ==
mag.value.clip(2., 4.))
@pytest.mark.parametrize('method', ('sum', 'cumsum', 'nansum'))
def test_only_ok_if_dimensionless(self, method):
res = getattr(self.m1, method)()
assert np.all(res.value ==
getattr(self.m1._function_view, method)().value)
assert res.unit == self.m1.unit
with pytest.raises(TypeError):
getattr(self.mJy, method)()
def test_dot(self):
assert np.all(self.m1.dot(self.m1).value ==
self.m1.value.dot(self.m1.value))
@pytest.mark.parametrize('method', ('prod', 'cumprod'))
def test_never_ok(self, method):
with pytest.raises(ValueError):
getattr(self.mJy, method)()
with pytest.raises(ValueError):
getattr(self.m1, method)()
class TestLogQuantityUfuncs:
"""Spot checks on ufuncs."""
def setup(self):
self.mJy = np.arange(1., 5.).reshape(2, 2) * u.mag(u.Jy)
self.m1 = np.arange(1., 5.5, 0.5).reshape(3, 3) * u.mag()
self.mags = (self.mJy, self.m1)
def test_power(self):
assert np.all(np.power(self.mJy, 0.) == 1.)
assert np.all(np.power(self.m1, 1.) == self.m1)
assert np.all(np.power(self.mJy, 1.) == self.mJy)
assert np.all(np.power(self.m1, 2.) == self.m1 ** 2)
with pytest.raises(u.UnitsError):
np.power(self.mJy, 2.)
def test_not_implemented_with_physical_unit(self):
with pytest.raises(u.UnitsError):
np.square(self.mJy)
assert np.all(np.square(self.m1) == self.m1 ** 2)
|
2faa2fb2f6be34d3f8385f9036aade59ea272a2b615b779b44884cec042b013b | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from functools import wraps
from textwrap import dedent
import pytest
from ... import units as u # pylint: disable=W0611
def py3only(func):
@wraps(func)
def wrapper(*args, **kwargs):
src = func(*args, **kwargs)
code = compile(dedent(src), __file__, 'exec')
# This uses an unqualified exec statement illegally in Python 2,
# but perfectly allowed in Python 3 so in fact we eval the exec
# call :)
eval('exec(code)')
return wrapper
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.arcsec"),
("'angle'", "'angle'")])
def test_args3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary: {1}):
return solarx, solary
solarx, solary = myfunc_args(1*u.arcsec, 1*u.arcsec)
assert isinstance(solarx, u.Quantity)
assert isinstance(solary, u.Quantity)
assert solarx.unit == u.arcsec
assert solary.unit == u.arcsec
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.arcsec"),
("'angle'", "'angle'")])
def test_args_noconvert3(solarx_unit, solary_unit):
src = """
@u.quantity_input()
def myfunc_args(solarx: {0}, solary: {1}):
return solarx, solary
solarx, solary = myfunc_args(1*u.deg, 1*u.arcmin)
assert isinstance(solarx, u.Quantity)
assert isinstance(solary, u.Quantity)
assert solarx.unit == u.deg
assert solary.unit == u.arcmin
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit", [
"u.arcsec", "'angle'"])
def test_args_nonquantity3(solarx_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary):
return solarx, solary
solarx, solary = myfunc_args(1*u.arcsec, 100)
assert isinstance(solarx, u.Quantity)
assert isinstance(solary, int)
assert solarx.unit == u.arcsec
""".format(solarx_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.eV"),
("'angle'", "'energy'")])
def test_arg_equivalencies3(solarx_unit, solary_unit):
src = """
@u.quantity_input(equivalencies=u.mass_energy())
def myfunc_args(solarx: {0}, solary: {1}):
return solarx, solary+(10*u.J) # Add an energy to check equiv is working
solarx, solary = myfunc_args(1*u.arcsec, 100*u.gram)
assert isinstance(solarx, u.Quantity)
assert isinstance(solary, u.Quantity)
assert solarx.unit == u.arcsec
assert solary.unit == u.gram
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.deg"),
("'angle'", "'angle'")])
def test_wrong_unit3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary: {1}):
return solarx, solary
with pytest.raises(u.UnitsError) as e:
solarx, solary = myfunc_args(1*u.arcsec, 100*u.km)
str_to = str({1})
assert str(e.value) == "Argument 'solary' to function 'myfunc_args' must be in units convertible to '{{0}}'.".format(str_to)
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.deg"),
("'angle'", "'angle'")])
def test_not_quantity3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary: {1}):
return solarx, solary
with pytest.raises(TypeError) as e:
solarx, solary = myfunc_args(1*u.arcsec, 100)
assert str(e.value) == "Argument 'solary' to function 'myfunc_args' has no 'unit' attribute. You may want to pass in an astropy Quantity instead."
""".format(solarx_unit, solary_unit)
return src
@py3only
def test_decorator_override():
src = """
@u.quantity_input(solarx=u.arcsec)
def myfunc_args(solarx: u.km, solary: u.arcsec):
return solarx, solary
solarx, solary = myfunc_args(1*u.arcsec, 1*u.arcsec)
assert isinstance(solarx, u.Quantity)
assert isinstance(solary, u.Quantity)
assert solarx.unit == u.arcsec
assert solary.unit == u.arcsec
"""
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.deg"),
("'angle'", "'angle'")])
def test_kwargs3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary, myk: {1}=1*u.arcsec):
return solarx, solary, myk
solarx, solary, myk = myfunc_args(1*u.arcsec, 100, myk=100*u.deg)
assert isinstance(solarx, u.Quantity)
assert isinstance(solary, int)
assert isinstance(myk, u.Quantity)
assert myk.unit == u.deg
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.deg"),
("'angle'", "'angle'")])
def test_unused_kwargs3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary, myk: {1}=1*u.arcsec, myk2=1000):
return solarx, solary, myk, myk2
solarx, solary, myk, myk2 = myfunc_args(1*u.arcsec, 100, myk=100*u.deg, myk2=10)
assert isinstance(solarx, u.Quantity)
assert isinstance(solary, int)
assert isinstance(myk, u.Quantity)
assert isinstance(myk2, int)
assert myk.unit == u.deg
assert myk2 == 10
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,energy", [
("u.arcsec", "u.eV"),
("'angle'", "'energy'")])
def test_kwarg_equivalencies3(solarx_unit, energy):
src = """
@u.quantity_input(equivalencies=u.mass_energy())
def myfunc_args(solarx: {0}, energy: {1}=10*u.eV):
return solarx, energy+(10*u.J) # Add an energy to check equiv is working
solarx, energy = myfunc_args(1*u.arcsec, 100*u.gram)
assert isinstance(solarx, u.Quantity)
assert isinstance(energy, u.Quantity)
assert solarx.unit == u.arcsec
assert energy.unit == u.gram
""".format(solarx_unit, energy)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.deg"),
("'angle'", "'angle'")])
def test_kwarg_wrong_unit3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary: {1}=10*u.deg):
return solarx, solary
with pytest.raises(u.UnitsError) as e:
solarx, solary = myfunc_args(1*u.arcsec, solary=100*u.km)
str_to = str({1})
assert str(e.value) == "Argument 'solary' to function 'myfunc_args' must be in units convertible to '{{0}}'.".format(str_to)
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.deg"),
("'angle'", "'angle'")])
def test_kwarg_not_quantity3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary: {1}=10*u.deg):
return solarx, solary
with pytest.raises(TypeError) as e:
solarx, solary = myfunc_args(1*u.arcsec, solary=100)
assert str(e.value) == "Argument 'solary' to function 'myfunc_args' has no 'unit' attribute. You may want to pass in an astropy Quantity instead."
""".format(solarx_unit, solary_unit)
return src
@py3only
@pytest.mark.parametrize("solarx_unit,solary_unit", [
("u.arcsec", "u.deg"),
("'angle'", "'angle'")])
def test_kwarg_default3(solarx_unit, solary_unit):
src = """
@u.quantity_input
def myfunc_args(solarx: {0}, solary: {1}=10*u.deg):
return solarx, solary
solarx, solary = myfunc_args(1*u.arcsec)
""".format(solarx_unit, solary_unit)
return src
@py3only
def test_return_annotation():
src = """
@u.quantity_input
def myfunc_args(solarx: u.arcsec) -> u.deg:
return solarx
solarx = myfunc_args(1*u.arcsec)
assert solarx.unit is u.deg
"""
return src
|
c62e5b0e2241ff76e17247c18c62008a3108f613e821566e464daaf70a09cb41 | # coding: utf-8
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Test the Quantity class and related.
"""
import copy
import pickle
import decimal
from fractions import Fraction
import pytest
import numpy as np
from numpy.testing import (assert_allclose, assert_array_equal,
assert_array_almost_equal)
from ...tests.helper import catch_warnings, raises
from ...utils import isiterable, minversion
from ...utils.compat import NUMPY_LT_1_14
from ...utils.exceptions import AstropyDeprecationWarning
from ... import units as u
from ...units.quantity import _UNIT_NOT_INITIALISED
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from distutils.version import LooseVersion
MATPLOTLIB_LT_15 = LooseVersion(matplotlib.__version__) < LooseVersion("1.5")
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
""" The Quantity class will represent a number + unit + uncertainty """
class TestQuantityCreation:
def test_1(self):
# create objects through operations with Unit objects:
quantity = 11.42 * u.meter # returns a Quantity object
assert isinstance(quantity, u.Quantity)
quantity = u.meter * 11.42 # returns a Quantity object
assert isinstance(quantity, u.Quantity)
quantity = 11.42 / u.meter
assert isinstance(quantity, u.Quantity)
quantity = u.meter / 11.42
assert isinstance(quantity, u.Quantity)
quantity = 11.42 * u.meter / u.second
assert isinstance(quantity, u.Quantity)
with pytest.raises(TypeError):
quantity = 182.234 + u.meter
with pytest.raises(TypeError):
quantity = 182.234 - u.meter
with pytest.raises(TypeError):
quantity = 182.234 % u.meter
def test_2(self):
# create objects using the Quantity constructor:
q1 = u.Quantity(11.412, unit=u.meter)
q2 = u.Quantity(21.52, "cm")
q3 = u.Quantity(11.412)
# By default quantities that don't specify a unit are unscaled
# dimensionless
assert q3.unit == u.Unit(1)
with pytest.raises(TypeError):
q4 = u.Quantity(object(), unit=u.m)
def test_3(self):
# with pytest.raises(u.UnitsError):
with pytest.raises(ValueError): # Until @mdboom fixes the errors in units
q1 = u.Quantity(11.412, unit="testingggg")
def test_nan_inf(self):
# Not-a-number
q = u.Quantity('nan', unit='cm')
assert np.isnan(q.value)
q = u.Quantity('NaN', unit='cm')
assert np.isnan(q.value)
q = u.Quantity('-nan', unit='cm') # float() allows this
assert np.isnan(q.value)
q = u.Quantity('nan cm')
assert np.isnan(q.value)
assert q.unit == u.cm
# Infinity
q = u.Quantity('inf', unit='cm')
assert np.isinf(q.value)
q = u.Quantity('-inf', unit='cm')
assert np.isinf(q.value)
q = u.Quantity('inf cm')
assert np.isinf(q.value)
assert q.unit == u.cm
q = u.Quantity('Infinity', unit='cm') # float() allows this
assert np.isinf(q.value)
# make sure these strings don't parse...
with pytest.raises(TypeError):
q = u.Quantity('', unit='cm')
with pytest.raises(TypeError):
q = u.Quantity('spam', unit='cm')
def test_unit_property(self):
# test getting and setting 'unit' attribute
q1 = u.Quantity(11.4, unit=u.meter)
with pytest.raises(AttributeError):
q1.unit = u.cm
def test_preserve_dtype(self):
"""Test that if an explicit dtype is given, it is used, while if not,
numbers are converted to float (including decimal.Decimal, which
numpy converts to an object; closes #1419)
"""
# If dtype is specified, use it, but if not, convert int, bool to float
q1 = u.Quantity(12, unit=u.m / u.s, dtype=int)
assert q1.dtype == int
q2 = u.Quantity(q1)
assert q2.dtype == float
assert q2.value == float(q1.value)
assert q2.unit == q1.unit
# but we should preserve float32
a3 = np.array([1., 2.], dtype=np.float32)
q3 = u.Quantity(a3, u.yr)
assert q3.dtype == a3.dtype
# items stored as objects by numpy should be converted to float
# by default
q4 = u.Quantity(decimal.Decimal('10.25'), u.m)
assert q4.dtype == float
q5 = u.Quantity(decimal.Decimal('10.25'), u.m, dtype=object)
assert q5.dtype == object
def test_copy(self):
# By default, a new quantity is constructed, but not if copy=False
a = np.arange(10.)
q0 = u.Quantity(a, unit=u.m / u.s)
assert q0.base is not a
q1 = u.Quantity(a, unit=u.m / u.s, copy=False)
assert q1.base is a
q2 = u.Quantity(q0)
assert q2 is not q0
assert q2.base is not q0.base
q2 = u.Quantity(q0, copy=False)
assert q2 is q0
assert q2.base is q0.base
q3 = u.Quantity(q0, q0.unit, copy=False)
assert q3 is q0
assert q3.base is q0.base
q4 = u.Quantity(q0, u.cm / u.s, copy=False)
assert q4 is not q0
assert q4.base is not q0.base
def test_subok(self):
"""Test subok can be used to keep class, or to insist on Quantity"""
class MyQuantitySubclass(u.Quantity):
pass
myq = MyQuantitySubclass(np.arange(10.), u.m)
# try both with and without changing the unit
assert type(u.Quantity(myq)) is u.Quantity
assert type(u.Quantity(myq, subok=True)) is MyQuantitySubclass
assert type(u.Quantity(myq, u.km)) is u.Quantity
assert type(u.Quantity(myq, u.km, subok=True)) is MyQuantitySubclass
def test_order(self):
"""Test that order is correctly propagated to np.array"""
ac = np.array(np.arange(10.), order='C')
qcc = u.Quantity(ac, u.m, order='C')
assert qcc.flags['C_CONTIGUOUS']
qcf = u.Quantity(ac, u.m, order='F')
assert qcf.flags['F_CONTIGUOUS']
qca = u.Quantity(ac, u.m, order='A')
assert qca.flags['C_CONTIGUOUS']
# check it works also when passing in a quantity
assert u.Quantity(qcc, order='C').flags['C_CONTIGUOUS']
assert u.Quantity(qcc, order='A').flags['C_CONTIGUOUS']
assert u.Quantity(qcc, order='F').flags['F_CONTIGUOUS']
af = np.array(np.arange(10.), order='F')
qfc = u.Quantity(af, u.m, order='C')
assert qfc.flags['C_CONTIGUOUS']
qff = u.Quantity(ac, u.m, order='F')
assert qff.flags['F_CONTIGUOUS']
qfa = u.Quantity(af, u.m, order='A')
assert qfa.flags['F_CONTIGUOUS']
assert u.Quantity(qff, order='C').flags['C_CONTIGUOUS']
assert u.Quantity(qff, order='A').flags['F_CONTIGUOUS']
assert u.Quantity(qff, order='F').flags['F_CONTIGUOUS']
def test_ndmin(self):
"""Test that ndmin is correctly propagated to np.array"""
a = np.arange(10.)
q1 = u.Quantity(a, u.m, ndmin=1)
assert q1.ndim == 1 and q1.shape == (10,)
q2 = u.Quantity(a, u.m, ndmin=2)
assert q2.ndim == 2 and q2.shape == (1, 10)
# check it works also when passing in a quantity
q3 = u.Quantity(q1, u.m, ndmin=3)
assert q3.ndim == 3 and q3.shape == (1, 1, 10)
def test_non_quantity_with_unit(self):
"""Test that unit attributes in objects get recognized."""
class MyQuantityLookalike(np.ndarray):
pass
a = np.arange(3.)
mylookalike = a.copy().view(MyQuantityLookalike)
mylookalike.unit = 'm'
q1 = u.Quantity(mylookalike)
assert isinstance(q1, u.Quantity)
assert q1.unit is u.m
assert np.all(q1.value == a)
q2 = u.Quantity(mylookalike, u.mm)
assert q2.unit is u.mm
assert np.all(q2.value == 1000.*a)
q3 = u.Quantity(mylookalike, copy=False)
assert np.all(q3.value == mylookalike)
q3[2] = 0
assert q3[2] == 0.
assert mylookalike[2] == 0.
mylookalike = a.copy().view(MyQuantityLookalike)
mylookalike.unit = u.m
q4 = u.Quantity(mylookalike, u.mm, copy=False)
q4[2] = 0
assert q4[2] == 0.
assert mylookalike[2] == 2.
mylookalike.unit = 'nonsense'
with pytest.raises(TypeError):
u.Quantity(mylookalike)
class TestQuantityOperations:
q1 = u.Quantity(11.42, u.meter)
q2 = u.Quantity(8.0, u.centimeter)
def test_addition(self):
# Take units from left object, q1
new_quantity = self.q1 + self.q2
assert new_quantity.value == 11.5
assert new_quantity.unit == u.meter
# Take units from left object, q2
new_quantity = self.q2 + self.q1
assert new_quantity.value == 1150.0
assert new_quantity.unit == u.centimeter
new_q = u.Quantity(1500.1, u.m) + u.Quantity(13.5, u.km)
assert new_q.unit == u.m
assert new_q.value == 15000.1
def test_subtraction(self):
# Take units from left object, q1
new_quantity = self.q1 - self.q2
assert new_quantity.value == 11.34
assert new_quantity.unit == u.meter
# Take units from left object, q2
new_quantity = self.q2 - self.q1
assert new_quantity.value == -1134.0
assert new_quantity.unit == u.centimeter
def test_multiplication(self):
# Take units from left object, q1
new_quantity = self.q1 * self.q2
assert new_quantity.value == 91.36
assert new_quantity.unit == (u.meter * u.centimeter)
# Take units from left object, q2
new_quantity = self.q2 * self.q1
assert new_quantity.value == 91.36
assert new_quantity.unit == (u.centimeter * u.meter)
# Multiply with a number
new_quantity = 15. * self.q1
assert new_quantity.value == 171.3
assert new_quantity.unit == u.meter
# Multiply with a number
new_quantity = self.q1 * 15.
assert new_quantity.value == 171.3
assert new_quantity.unit == u.meter
def test_division(self):
# Take units from left object, q1
new_quantity = self.q1 / self.q2
assert_array_almost_equal(new_quantity.value, 1.4275, decimal=5)
assert new_quantity.unit == (u.meter / u.centimeter)
# Take units from left object, q2
new_quantity = self.q2 / self.q1
assert_array_almost_equal(new_quantity.value, 0.70052539404553416,
decimal=16)
assert new_quantity.unit == (u.centimeter / u.meter)
q1 = u.Quantity(11.4, unit=u.meter)
q2 = u.Quantity(10.0, unit=u.second)
new_quantity = q1 / q2
assert_array_almost_equal(new_quantity.value, 1.14, decimal=10)
assert new_quantity.unit == (u.meter / u.second)
# divide with a number
new_quantity = self.q1 / 10.
assert new_quantity.value == 1.142
assert new_quantity.unit == u.meter
# divide with a number
new_quantity = 11.42 / self.q1
assert new_quantity.value == 1.
assert new_quantity.unit == u.Unit("1/m")
def test_commutativity(self):
"""Regression test for issue #587."""
new_q = u.Quantity(11.42, 'm*s')
assert self.q1 * u.s == u.s * self.q1 == new_q
assert self.q1 / u.s == u.Quantity(11.42, 'm/s')
assert u.s / self.q1 == u.Quantity(1 / 11.42, 's/m')
def test_power(self):
# raise quantity to a power
new_quantity = self.q1 ** 2
assert_array_almost_equal(new_quantity.value, 130.4164, decimal=5)
assert new_quantity.unit == u.Unit("m^2")
new_quantity = self.q1 ** 3
assert_array_almost_equal(new_quantity.value, 1489.355288, decimal=7)
assert new_quantity.unit == u.Unit("m^3")
def test_matrix_multiplication(self):
a = np.eye(3)
q = a * u.m
result1 = eval("q @ a")
assert np.all(result1 == q)
result2 = eval("a @ q")
assert np.all(result2 == q)
result3 = eval("q @ q")
assert np.all(result3 == a * u.m ** 2)
# less trivial case.
q2 = np.array([[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]],
[[0., 1., 0.],
[0., 0., 1.],
[1., 0., 0.]],
[[0., 0., 1.],
[1., 0., 0.],
[0., 1., 0.]]]) / u.s
result4 = eval("q @ q2")
assert np.all(result4 == np.matmul(a, q2.value) * q.unit * q2.unit)
def test_unary(self):
# Test the minus unary operator
new_quantity = -self.q1
assert new_quantity.value == -self.q1.value
assert new_quantity.unit == self.q1.unit
new_quantity = -(-self.q1)
assert new_quantity.value == self.q1.value
assert new_quantity.unit == self.q1.unit
# Test the plus unary operator
new_quantity = +self.q1
assert new_quantity.value == self.q1.value
assert new_quantity.unit == self.q1.unit
def test_abs(self):
q = 1. * u.m / u.s
new_quantity = abs(q)
assert new_quantity.value == q.value
assert new_quantity.unit == q.unit
q = -1. * u.m / u.s
new_quantity = abs(q)
assert new_quantity.value == -q.value
assert new_quantity.unit == q.unit
def test_incompatible_units(self):
""" When trying to add or subtract units that aren't compatible, throw an error """
q1 = u.Quantity(11.412, unit=u.meter)
q2 = u.Quantity(21.52, unit=u.second)
with pytest.raises(u.UnitsError):
new_q = q1 + q2
def test_non_number_type(self):
q1 = u.Quantity(11.412, unit=u.meter)
type_err_msg = ("Unsupported operand type(s) for ufunc add: "
"'Quantity' and 'dict'")
with pytest.raises(TypeError) as exc:
q1 + {'a': 1}
assert exc.value.args[0] == type_err_msg
with pytest.raises(TypeError):
q1 + u.meter
def test_dimensionless_operations(self):
# test conversion to dimensionless
dq = 3. * u.m / u.km
dq1 = dq + 1. * u.mm / u.km
assert dq1.value == 3.001
assert dq1.unit == dq.unit
dq2 = dq + 1.
assert dq2.value == 1.003
assert dq2.unit == u.dimensionless_unscaled
# this test will check that operations with dimensionless Quantities
# don't work
with pytest.raises(u.UnitsError):
self.q1 + u.Quantity(0.1, unit=u.Unit(""))
with pytest.raises(u.UnitsError):
self.q1 - u.Quantity(0.1, unit=u.Unit(""))
# and test that scaling of integers works
q = u.Quantity(np.array([1, 2, 3]), u.m / u.km, dtype=int)
q2 = q + np.array([4, 5, 6])
assert q2.unit == u.dimensionless_unscaled
assert_allclose(q2.value, np.array([4.001, 5.002, 6.003]))
# but not if doing it inplace
with pytest.raises(TypeError):
q += np.array([1, 2, 3])
# except if it is actually possible
q = np.array([1, 2, 3]) * u.km / u.m
q += np.array([4, 5, 6])
assert q.unit == u.dimensionless_unscaled
assert np.all(q.value == np.array([1004, 2005, 3006]))
def test_complicated_operation(self):
""" Perform a more complicated test """
from .. import imperial
# Multiple units
distance = u.Quantity(15., u.meter)
time = u.Quantity(11., u.second)
velocity = (distance / time).to(imperial.mile / u.hour)
assert_array_almost_equal(
velocity.value, 3.05037, decimal=5)
G = u.Quantity(6.673E-11, u.m ** 3 / u.kg / u.s ** 2)
new_q = ((1. / (4. * np.pi * G)).to(u.pc ** -3 / u.s ** -2 * u.kg))
# Area
side1 = u.Quantity(11., u.centimeter)
side2 = u.Quantity(7., u.centimeter)
area = side1 * side2
assert_array_almost_equal(area.value, 77., decimal=15)
assert area.unit == u.cm * u.cm
def test_comparison(self):
# equality/ non-equality is straightforward for quantity objects
assert (1 / (u.cm * u.cm)) == 1 * u.cm ** -2
assert 1 * u.m == 100 * u.cm
assert 1 * u.m != 1 * u.cm
# when one is a unit, Quantity does not know what to do,
# but unit is fine with it, so it still works
unit = u.cm**3
q = 1. * unit
assert q.__eq__(unit) is NotImplemented
assert unit.__eq__(q) is True
assert q == unit
q = 1000. * u.mm**3
assert q == unit
# mismatched types should never work
assert not 1. * u.cm == 1.
assert 1. * u.cm != 1.
# comparison with zero should raise a deprecation warning
for quantity in (1. * u.cm, 1. * u.dimensionless_unscaled):
with catch_warnings(AstropyDeprecationWarning) as warning_lines:
bool(quantity)
assert warning_lines[0].category == AstropyDeprecationWarning
assert (str(warning_lines[0].message) == 'The truth value of '
'a Quantity is ambiguous. In the future this will '
'raise a ValueError.')
def test_numeric_converters(self):
# float, int, long, and __index__ should only work for single
# quantities, of appropriate type, and only if they are dimensionless.
# for index, this should be unscaled as well
# (Check on __index__ is also a regression test for #1557)
# quantities with units should never convert, or be usable as an index
q1 = u.Quantity(1, u.m)
converter_err_msg = ("only dimensionless scalar quantities "
"can be converted to Python scalars")
index_err_msg = ("only integer dimensionless scalar quantities "
"can be converted to a Python index")
with pytest.raises(TypeError) as exc:
float(q1)
assert exc.value.args[0] == converter_err_msg
with pytest.raises(TypeError) as exc:
int(q1)
assert exc.value.args[0] == converter_err_msg
# We used to test `q1 * ['a', 'b', 'c'] here, but that that worked
# at all was a really odd confluence of bugs. Since it doesn't work
# in numpy >=1.10 any more, just go directly for `__index__` (which
# makes the test more similar to the `int`, `long`, etc., tests).
with pytest.raises(TypeError) as exc:
q1.__index__()
assert exc.value.args[0] == index_err_msg
# dimensionless but scaled is OK, however
q2 = u.Quantity(1.23, u.m / u.km)
assert float(q2) == float(q2.to_value(u.dimensionless_unscaled))
assert int(q2) == int(q2.to_value(u.dimensionless_unscaled))
with pytest.raises(TypeError) as exc:
q2.__index__()
assert exc.value.args[0] == index_err_msg
# dimensionless unscaled is OK, though for index needs to be int
q3 = u.Quantity(1.23, u.dimensionless_unscaled)
assert float(q3) == 1.23
assert int(q3) == 1
with pytest.raises(TypeError) as exc:
q3.__index__()
assert exc.value.args[0] == index_err_msg
# integer dimensionless unscaled is good for all
q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int)
assert float(q4) == 2.
assert int(q4) == 2
assert q4.__index__() == 2
# but arrays are not OK
q5 = u.Quantity([1, 2], u.m)
with pytest.raises(TypeError) as exc:
float(q5)
assert exc.value.args[0] == converter_err_msg
with pytest.raises(TypeError) as exc:
int(q5)
assert exc.value.args[0] == converter_err_msg
with pytest.raises(TypeError) as exc:
q5.__index__()
assert exc.value.args[0] == index_err_msg
# See https://github.com/numpy/numpy/issues/5074
# It seems unlikely this will be resolved, so xfail'ing it.
@pytest.mark.xfail(reason="list multiplication only works for numpy <=1.10")
def test_numeric_converter_to_index_in_practice(self):
"""Test that use of __index__ actually works."""
q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int)
assert q4 * ['a', 'b', 'c'] == ['a', 'b', 'c', 'a', 'b', 'c']
def test_array_converters(self):
# Scalar quantity
q = u.Quantity(1.23, u.m)
assert np.all(np.array(q) == np.array([1.23]))
# Array quantity
q = u.Quantity([1., 2., 3.], u.m)
assert np.all(np.array(q) == np.array([1., 2., 3.]))
def test_quantity_conversion():
q1 = u.Quantity(0.1, unit=u.meter)
value = q1.value
assert value == 0.1
value_in_km = q1.to_value(u.kilometer)
assert value_in_km == 0.0001
new_quantity = q1.to(u.kilometer)
assert new_quantity.value == 0.0001
with pytest.raises(u.UnitsError):
q1.to(u.zettastokes)
with pytest.raises(u.UnitsError):
q1.to_value(u.zettastokes)
def test_quantity_value_views():
q1 = u.Quantity([1., 2.], unit=u.meter)
# views if the unit is the same.
v1 = q1.value
v1[0] = 0.
assert np.all(q1 == [0., 2.] * u.meter)
v2 = q1.to_value()
v2[1] = 3.
assert np.all(q1 == [0., 3.] * u.meter)
v3 = q1.to_value('m')
v3[0] = 1.
assert np.all(q1 == [1., 3.] * u.meter)
v4 = q1.to_value('cm')
v4[0] = 0.
# copy if different unit.
assert np.all(q1 == [1., 3.] * u.meter)
def test_quantity_conversion_with_equiv():
q1 = u.Quantity(0.1, unit=u.meter)
v2 = q1.to_value(u.Hz, equivalencies=u.spectral())
assert_allclose(v2, 2997924580.0)
q2 = q1.to(u.Hz, equivalencies=u.spectral())
assert_allclose(q2.value, v2)
q1 = u.Quantity(0.4, unit=u.arcsecond)
v2 = q1.to_value(u.au, equivalencies=u.parallax())
q2 = q1.to(u.au, equivalencies=u.parallax())
v3 = q2.to_value(u.arcminute, equivalencies=u.parallax())
q3 = q2.to(u.arcminute, equivalencies=u.parallax())
assert_allclose(v2, 515662.015)
assert_allclose(q2.value, v2)
assert q2.unit == u.au
assert_allclose(v3, 0.0066666667)
assert_allclose(q3.value, v3)
assert q3.unit == u.arcminute
def test_quantity_conversion_equivalency_passed_on():
class MySpectral(u.Quantity):
_equivalencies = u.spectral()
def __quantity_view__(self, obj, unit):
return obj.view(MySpectral)
def __quantity_instance__(self, *args, **kwargs):
return MySpectral(*args, **kwargs)
q1 = MySpectral([1000, 2000], unit=u.Hz)
q2 = q1.to(u.nm)
assert q2.unit == u.nm
q3 = q2.to(u.Hz)
assert q3.unit == u.Hz
assert_allclose(q3.value, q1.value)
q4 = MySpectral([1000, 2000], unit=u.nm)
q5 = q4.to(u.Hz).to(u.nm)
assert q5.unit == u.nm
assert_allclose(q4.value, q5.value)
# Regression test for issue #2315, divide-by-zero error when examining 0*unit
def test_self_equivalency():
assert u.deg.is_equivalent(0*u.radian)
assert u.deg.is_equivalent(1*u.radian)
def test_si():
q1 = 10. * u.m * u.s ** 2 / (200. * u.ms) ** 2 # 250 meters
assert q1.si.value == 250
assert q1.si.unit == u.m
q = 10. * u.m # 10 meters
assert q.si.value == 10
assert q.si.unit == u.m
q = 10. / u.m # 10 1 / meters
assert q.si.value == 10
assert q.si.unit == (1 / u.m)
def test_cgs():
q1 = 10. * u.cm * u.s ** 2 / (200. * u.ms) ** 2 # 250 centimeters
assert q1.cgs.value == 250
assert q1.cgs.unit == u.cm
q = 10. * u.m # 10 centimeters
assert q.cgs.value == 1000
assert q.cgs.unit == u.cm
q = 10. / u.cm # 10 1 / centimeters
assert q.cgs.value == 10
assert q.cgs.unit == (1 / u.cm)
q = 10. * u.Pa # 10 pascals
assert q.cgs.value == 100
assert q.cgs.unit == u.barye
class TestQuantityComparison:
def test_quantity_equality(self):
assert u.Quantity(1000, unit='m') == u.Quantity(1, unit='km')
assert not (u.Quantity(1, unit='m') == u.Quantity(1, unit='km'))
# for ==, !=, return False, True if units do not match
assert (u.Quantity(1100, unit=u.m) != u.Quantity(1, unit=u.s)) is True
assert (u.Quantity(1100, unit=u.m) == u.Quantity(1, unit=u.s)) is False
def test_quantity_comparison(self):
assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.kilometer)
assert u.Quantity(900, unit=u.meter) < u.Quantity(1, unit=u.kilometer)
with pytest.raises(u.UnitsError):
assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.second)
with pytest.raises(u.UnitsError):
assert u.Quantity(1100, unit=u.meter) < u.Quantity(1, unit=u.second)
assert u.Quantity(1100, unit=u.meter) >= u.Quantity(1, unit=u.kilometer)
assert u.Quantity(1000, unit=u.meter) >= u.Quantity(1, unit=u.kilometer)
assert u.Quantity(900, unit=u.meter) <= u.Quantity(1, unit=u.kilometer)
assert u.Quantity(1000, unit=u.meter) <= u.Quantity(1, unit=u.kilometer)
with pytest.raises(u.UnitsError):
assert u.Quantity(
1100, unit=u.meter) >= u.Quantity(1, unit=u.second)
with pytest.raises(u.UnitsError):
assert u.Quantity(1100, unit=u.meter) <= u.Quantity(1, unit=u.second)
assert u.Quantity(1200, unit=u.meter) != u.Quantity(1, unit=u.kilometer)
class TestQuantityDisplay:
scalarintq = u.Quantity(1, unit='m', dtype=int)
scalarfloatq = u.Quantity(1.3, unit='m')
arrq = u.Quantity([1, 2.3, 8.9], unit='m')
def test_dimensionless_quantity_repr(self):
q2 = u.Quantity(1., unit='m-1')
q3 = u.Quantity(1, unit='m-1', dtype=int)
if NUMPY_LT_1_14:
assert repr(self.scalarintq * q2) == "<Quantity 1.0>"
assert repr(self.arrq * q2) == "<Quantity [ 1. , 2.3, 8.9]>"
else:
assert repr(self.scalarintq * q2) == "<Quantity 1.>"
assert repr(self.arrq * q2) == "<Quantity [1. , 2.3, 8.9]>"
assert repr(self.scalarintq * q3) == "<Quantity 1>"
def test_dimensionless_quantity_str(self):
q2 = u.Quantity(1., unit='m-1')
q3 = u.Quantity(1, unit='m-1', dtype=int)
assert str(self.scalarintq * q2) == "1.0"
assert str(self.scalarintq * q3) == "1"
if NUMPY_LT_1_14:
assert str(self.arrq * q2) == "[ 1. 2.3 8.9]"
else:
assert str(self.arrq * q2) == "[1. 2.3 8.9]"
def test_dimensionless_quantity_format(self):
q1 = u.Quantity(3.14)
assert format(q1, '.2f') == '3.14'
def test_scalar_quantity_str(self):
assert str(self.scalarintq) == "1 m"
assert str(self.scalarfloatq) == "1.3 m"
def test_scalar_quantity_repr(self):
assert repr(self.scalarintq) == "<Quantity 1 m>"
assert repr(self.scalarfloatq) == "<Quantity 1.3 m>"
def test_array_quantity_str(self):
if NUMPY_LT_1_14:
assert str(self.arrq) == "[ 1. 2.3 8.9] m"
else:
assert str(self.arrq) == "[1. 2.3 8.9] m"
def test_array_quantity_repr(self):
if NUMPY_LT_1_14:
assert repr(self.arrq) == "<Quantity [ 1. , 2.3, 8.9] m>"
else:
assert repr(self.arrq) == "<Quantity [1. , 2.3, 8.9] m>"
def test_scalar_quantity_format(self):
assert format(self.scalarintq, '02d') == "01 m"
assert format(self.scalarfloatq, '.1f') == "1.3 m"
assert format(self.scalarfloatq, '.0f') == "1 m"
def test_uninitialized_unit_format(self):
bad_quantity = np.arange(10.).view(u.Quantity)
assert str(bad_quantity).endswith(_UNIT_NOT_INITIALISED)
assert repr(bad_quantity).endswith(_UNIT_NOT_INITIALISED + '>')
def test_repr_latex(self):
from ...units.quantity import conf
q2scalar = u.Quantity(1.5e14, 'm/s')
assert self.scalarintq._repr_latex_() == r'$1 \; \mathrm{m}$'
assert self.scalarfloatq._repr_latex_() == r'$1.3 \; \mathrm{m}$'
assert (q2scalar._repr_latex_() ==
r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$')
assert self.arrq._repr_latex_() == r'$[1,~2.3,~8.9] \; \mathrm{m}$'
qmed = np.arange(100)*u.m
qbig = np.arange(1000)*u.m
qvbig = np.arange(10000)*1e9*u.m
pops = np.get_printoptions()
oldlat = conf.latex_array_threshold
try:
# check precision behavior
q = u.Quantity(987654321.123456789, 'm/s')
qa = np.array([7.89123, 123456789.987654321, 0]) * u.cm
np.set_printoptions(precision=8)
assert q._repr_latex_() == r'$9.8765432 \times 10^{8} \; \mathrm{\frac{m}{s}}$'
assert qa._repr_latex_() == r'$[7.89123,~1.2345679 \times 10^{8},~0] \; \mathrm{cm}$'
np.set_printoptions(precision=2)
assert q._repr_latex_() == r'$9.9 \times 10^{8} \; \mathrm{\frac{m}{s}}$'
assert qa._repr_latex_() == r'$[7.9,~1.2 \times 10^{8},~0] \; \mathrm{cm}$'
# check thresholding behavior
conf.latex_array_threshold = 100 # should be default
lsmed = qmed._repr_latex_()
assert r'\dots' not in lsmed
lsbig = qbig._repr_latex_()
assert r'\dots' in lsbig
lsvbig = qvbig._repr_latex_()
assert r'\dots' in lsvbig
conf.latex_array_threshold = 1001
lsmed = qmed._repr_latex_()
assert r'\dots' not in lsmed
lsbig = qbig._repr_latex_()
assert r'\dots' not in lsbig
lsvbig = qvbig._repr_latex_()
assert r'\dots' in lsvbig
conf.latex_array_threshold = -1 # means use the numpy threshold
np.set_printoptions(threshold=99)
lsmed = qmed._repr_latex_()
assert r'\dots' in lsmed
lsbig = qbig._repr_latex_()
assert r'\dots' in lsbig
lsvbig = qvbig._repr_latex_()
assert r'\dots' in lsvbig
finally:
# prevent side-effects from influencing other tests
np.set_printoptions(**pops)
conf.latex_array_threshold = oldlat
qinfnan = [np.inf, -np.inf, np.nan] * u.m
assert qinfnan._repr_latex_() == r'$[\infty,~-\infty,~{\rm NaN}] \; \mathrm{m}$'
def test_decompose():
q1 = 5 * u.N
assert q1.decompose() == (5 * u.kg * u.m * u.s ** -2)
def test_decompose_regression():
"""
Regression test for bug #1163
If decompose was called multiple times on a Quantity with an array and a
scale != 1, the result changed every time. This is because the value was
being referenced not copied, then modified, which changed the original
value.
"""
q = np.array([1, 2, 3]) * u.m / (2. * u.km)
assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015]))
assert np.all(q == np.array([1, 2, 3]) * u.m / (2. * u.km))
assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015]))
def test_arrays():
"""
Test using quantites with array values
"""
qsec = u.Quantity(np.arange(10), u.second)
assert isinstance(qsec.value, np.ndarray)
assert not qsec.isscalar
# len and indexing should work for arrays
assert len(qsec) == len(qsec.value)
qsecsub25 = qsec[2:5]
assert qsecsub25.unit == qsec.unit
assert isinstance(qsecsub25, u.Quantity)
assert len(qsecsub25) == 3
# make sure isscalar, len, and indexing behave correcly for non-arrays.
qsecnotarray = u.Quantity(10., u.second)
assert qsecnotarray.isscalar
with pytest.raises(TypeError):
len(qsecnotarray)
with pytest.raises(TypeError):
qsecnotarray[0]
qseclen0array = u.Quantity(np.array(10), u.second, dtype=int)
# 0d numpy array should act basically like a scalar
assert qseclen0array.isscalar
with pytest.raises(TypeError):
len(qseclen0array)
with pytest.raises(TypeError):
qseclen0array[0]
assert isinstance(qseclen0array.value, int)
a = np.array([(1., 2., 3.), (4., 5., 6.), (7., 8., 9.)],
dtype=[('x', float),
('y', float),
('z', float)])
qkpc = u.Quantity(a, u.kpc)
assert not qkpc.isscalar
qkpc0 = qkpc[0]
assert qkpc0.value == a[0].item()
assert qkpc0.unit == qkpc.unit
assert isinstance(qkpc0, u.Quantity)
assert qkpc0.isscalar
qkpcx = qkpc['x']
assert np.all(qkpcx.value == a['x'])
assert qkpcx.unit == qkpc.unit
assert isinstance(qkpcx, u.Quantity)
assert not qkpcx.isscalar
qkpcx1 = qkpc['x'][1]
assert qkpcx1.unit == qkpc.unit
assert isinstance(qkpcx1, u.Quantity)
assert qkpcx1.isscalar
qkpc1x = qkpc[1]['x']
assert qkpc1x.isscalar
assert qkpc1x == qkpcx1
# can also create from lists, will auto-convert to arrays
qsec = u.Quantity(list(range(10)), u.second)
assert isinstance(qsec.value, np.ndarray)
# quantity math should work with arrays
assert_array_equal((qsec * 2).value, (np.arange(10) * 2))
assert_array_equal((qsec / 2).value, (np.arange(10) / 2))
# quantity addition/subtraction should *not* work with arrays b/c unit
# ambiguous
with pytest.raises(u.UnitsError):
assert_array_equal((qsec + 2).value, (np.arange(10) + 2))
with pytest.raises(u.UnitsError):
assert_array_equal((qsec - 2).value, (np.arange(10) + 2))
# should create by unit multiplication, too
qsec2 = np.arange(10) * u.second
qsec3 = u.second * np.arange(10)
assert np.all(qsec == qsec2)
assert np.all(qsec2 == qsec3)
# make sure numerical-converters fail when arrays are present
with pytest.raises(TypeError):
float(qsec)
with pytest.raises(TypeError):
int(qsec)
def test_array_indexing_slicing():
q = np.array([1., 2., 3.]) * u.m
assert q[0] == 1. * u.m
assert np.all(q[0:2] == u.Quantity([1., 2.], u.m))
def test_array_setslice():
q = np.array([1., 2., 3.]) * u.m
q[1:2] = np.array([400.]) * u.cm
assert np.all(q == np.array([1., 4., 3.]) * u.m)
def test_inverse_quantity():
"""
Regression test from issue #679
"""
q = u.Quantity(4., u.meter / u.second)
qot = q / 2
toq = 2 / q
npqot = q / np.array(2)
assert npqot.value == 2.0
assert npqot.unit == (u.meter / u.second)
assert qot.value == 2.0
assert qot.unit == (u.meter / u.second)
assert toq.value == 0.5
assert toq.unit == (u.second / u.meter)
def test_quantity_mutability():
q = u.Quantity(9.8, u.meter / u.second / u.second)
with pytest.raises(AttributeError):
q.value = 3
with pytest.raises(AttributeError):
q.unit = u.kg
def test_quantity_initialized_with_quantity():
q1 = u.Quantity(60, u.second)
q2 = u.Quantity(q1, u.minute)
assert q2.value == 1
q3 = u.Quantity([q1, q2], u.second)
assert q3[0].value == 60
assert q3[1].value == 60
q4 = u.Quantity([q2, q1])
assert q4.unit == q2.unit
assert q4[0].value == 1
assert q4[1].value == 1
def test_quantity_string_unit():
q1 = 1. * u.m / 's'
assert q1.value == 1
assert q1.unit == (u.m / u.s)
q2 = q1 * "m"
assert q2.unit == ((u.m * u.m) / u.s)
@raises(ValueError)
def test_quantity_invalid_unit_string():
"foo" * u.m
def test_implicit_conversion():
q = u.Quantity(1.0, u.meter)
# Manually turn this on to simulate what might happen in a subclass
q._include_easy_conversion_members = True
assert_allclose(q.centimeter, 100)
assert_allclose(q.cm, 100)
assert_allclose(q.parsec, 3.240779289469756e-17)
def test_implicit_conversion_autocomplete():
q = u.Quantity(1.0, u.meter)
# Manually turn this on to simulate what might happen in a subclass
q._include_easy_conversion_members = True
q.foo = 42
attrs = dir(q)
assert 'centimeter' in attrs
assert 'cm' in attrs
assert 'parsec' in attrs
assert 'foo' in attrs
assert 'to' in attrs
assert 'value' in attrs
# Something from the base class, object
assert '__setattr__' in attrs
with pytest.raises(AttributeError):
q.l
def test_quantity_iterability():
"""Regressiont est for issue #878.
Scalar quantities should not be iterable and should raise a type error on
iteration.
"""
q1 = [15.0, 17.0] * u.m
assert isiterable(q1)
q2 = next(iter(q1))
assert q2 == 15.0 * u.m
assert not isiterable(q2)
pytest.raises(TypeError, iter, q2)
def test_copy():
q1 = u.Quantity(np.array([[1., 2., 3.], [4., 5., 6.]]), unit=u.m)
q2 = q1.copy()
assert np.all(q1.value == q2.value)
assert q1.unit == q2.unit
assert q1.dtype == q2.dtype
assert q1.value is not q2.value
q3 = q1.copy(order='F')
assert q3.flags['F_CONTIGUOUS']
assert np.all(q1.value == q3.value)
assert q1.unit == q3.unit
assert q1.dtype == q3.dtype
assert q1.value is not q3.value
q4 = q1.copy(order='C')
assert q4.flags['C_CONTIGUOUS']
assert np.all(q1.value == q4.value)
assert q1.unit == q4.unit
assert q1.dtype == q4.dtype
assert q1.value is not q4.value
def test_deepcopy():
q1 = u.Quantity(np.array([1., 2., 3.]), unit=u.m)
q2 = copy.deepcopy(q1)
assert isinstance(q2, u.Quantity)
assert np.all(q1.value == q2.value)
assert q1.unit == q2.unit
assert q1.dtype == q2.dtype
assert q1.value is not q2.value
def test_equality_numpy_scalar():
"""
A regression test to ensure that numpy scalars are correctly compared
(which originally failed due to the lack of ``__array_priority__``).
"""
assert 10 != 10. * u.m
assert np.int64(10) != 10 * u.m
assert 10 * u.m != np.int64(10)
def test_quantity_pickelability():
"""
Testing pickleability of quantity
"""
q1 = np.arange(10) * u.m
q2 = pickle.loads(pickle.dumps(q1))
assert np.all(q1.value == q2.value)
assert q1.unit.is_equivalent(q2.unit)
assert q1.unit == q2.unit
def test_quantity_initialisation_from_string():
q = u.Quantity('1')
assert q.unit == u.dimensionless_unscaled
assert q.value == 1.
q = u.Quantity('1.5 m/s')
assert q.unit == u.m/u.s
assert q.value == 1.5
assert u.Unit(q) == u.Unit('1.5 m/s')
q = u.Quantity('.5 m')
assert q == u.Quantity(0.5, u.m)
q = u.Quantity('-1e1km')
assert q == u.Quantity(-10, u.km)
q = u.Quantity('-1e+1km')
assert q == u.Quantity(-10, u.km)
q = u.Quantity('+.5km')
assert q == u.Quantity(.5, u.km)
q = u.Quantity('+5e-1km')
assert q == u.Quantity(.5, u.km)
q = u.Quantity('5', u.m)
assert q == u.Quantity(5., u.m)
q = u.Quantity('5 km', u.m)
assert q.value == 5000.
assert q.unit == u.m
q = u.Quantity('5Em')
assert q == u.Quantity(5., u.Em)
with pytest.raises(TypeError):
u.Quantity('')
with pytest.raises(TypeError):
u.Quantity('m')
with pytest.raises(TypeError):
u.Quantity('1.2.3 deg')
with pytest.raises(TypeError):
u.Quantity('1+deg')
with pytest.raises(TypeError):
u.Quantity('1-2deg')
with pytest.raises(TypeError):
u.Quantity('1.2e-13.3m')
with pytest.raises(TypeError):
u.Quantity(['5'])
with pytest.raises(TypeError):
u.Quantity(np.array(['5']))
with pytest.raises(ValueError):
u.Quantity('5E')
with pytest.raises(ValueError):
u.Quantity('5 foo')
def test_unsupported():
q1 = np.arange(10) * u.m
with pytest.raises(TypeError):
q2 = np.bitwise_and(q1, q1)
def test_unit_identity():
q = 1.0 * u.hour
assert q.unit is u.hour
def test_quantity_to_view():
q1 = np.array([1000, 2000]) * u.m
q2 = q1.to(u.km)
assert q1.value[0] == 1000
assert q2.value[0] == 1
@raises(ValueError)
def test_quantity_tuple_power():
(5.0 * u.m) ** (1, 2)
def test_quantity_fraction_power():
q = (25.0 * u.m**2) ** Fraction(1, 2)
assert q.value == 5.
assert q.unit == u.m
# Regression check to ensure we didn't create an object type by raising
# the value of the quantity to a Fraction. [#3922]
assert q.dtype.kind == 'f'
def test_inherit_docstrings():
assert u.Quantity.argmax.__doc__ == np.ndarray.argmax.__doc__
def test_quantity_from_table():
"""
Checks that units from tables are respected when converted to a Quantity.
This also generically checks the use of *anything* with a `unit` attribute
passed into Quantity
"""
from... table import Table
t = Table(data=[np.arange(5), np.arange(5)], names=['a', 'b'])
t['a'].unit = u.kpc
qa = u.Quantity(t['a'])
assert qa.unit == u.kpc
assert_array_equal(qa.value, t['a'])
qb = u.Quantity(t['b'])
assert qb.unit == u.dimensionless_unscaled
assert_array_equal(qb.value, t['b'])
# This does *not* auto-convert, because it's not necessarily obvious that's
# desired. Instead we revert to standard `Quantity` behavior
qap = u.Quantity(t['a'], u.pc)
assert qap.unit == u.pc
assert_array_equal(qap.value, t['a'] * 1000)
qbp = u.Quantity(t['b'], u.pc)
assert qbp.unit == u.pc
assert_array_equal(qbp.value, t['b'])
def test_assign_slice_with_quantity_like():
# Regression tests for gh-5961
from ... table import Table, Column
# first check directly that we can use a Column to assign to a slice.
c = Column(np.arange(10.), unit=u.mm)
q = u.Quantity(c)
q[:2] = c[:2]
# next check that we do not fail the original problem.
t = Table()
t['x'] = np.arange(10) * u.mm
t['y'] = np.ones(10) * u.mm
assert type(t['x']) is Column
xy = np.vstack([t['x'], t['y']]).T * u.mm
ii = [0, 2, 4]
assert xy[ii, 0].unit == t['x'][ii].unit
# should not raise anything
xy[ii, 0] = t['x'][ii]
def test_insert():
"""
Test Quantity.insert method. This does not test the full capabilities
of the underlying np.insert, but hits the key functionality for
Quantity.
"""
q = [1, 2] * u.m
# Insert a compatible float with different units
q2 = q.insert(0, 1 * u.km)
assert np.all(q2.value == [1000, 1, 2])
assert q2.unit is u.m
assert q2.dtype.kind == 'f'
if minversion(np, '1.8.0'):
q2 = q.insert(1, [1, 2] * u.km)
assert np.all(q2.value == [1, 1000, 2000, 2])
assert q2.unit is u.m
# Cannot convert 1.5 * u.s to m
with pytest.raises(u.UnitsError):
q.insert(1, 1.5 * u.s)
# Tests with multi-dim quantity
q = [[1, 2], [3, 4]] * u.m
q2 = q.insert(1, [10, 20] * u.m, axis=0)
assert np.all(q2.value == [[1, 2],
[10, 20],
[3, 4]])
q2 = q.insert(1, [10, 20] * u.m, axis=1)
assert np.all(q2.value == [[1, 10, 2],
[3, 20, 4]])
q2 = q.insert(1, 10 * u.m, axis=1)
assert np.all(q2.value == [[1, 10, 2],
[3, 10, 4]])
def test_repr_array_of_quantity():
"""
Test print/repr of object arrays of Quantity objects with different
units.
Regression test for the issue first reported in
https://github.com/astropy/astropy/issues/3777
"""
a = np.array([1 * u.m, 2 * u.s], dtype=object)
if NUMPY_LT_1_14:
assert repr(a) == 'array([<Quantity 1.0 m>, <Quantity 2.0 s>], dtype=object)'
assert str(a) == '[<Quantity 1.0 m> <Quantity 2.0 s>]'
else:
assert repr(a) == 'array([<Quantity 1. m>, <Quantity 2. s>], dtype=object)'
assert str(a) == '[<Quantity 1. m> <Quantity 2. s>]'
class TestSpecificTypeQuantity:
def setup(self):
class Length(u.SpecificTypeQuantity):
_equivalent_unit = u.m
class Length2(Length):
_default_unit = u.m
class Length3(Length):
_unit = u.m
self.Length = Length
self.Length2 = Length2
self.Length3 = Length3
def test_creation(self):
l = self.Length(np.arange(10.)*u.km)
assert type(l) is self.Length
with pytest.raises(u.UnitTypeError):
self.Length(np.arange(10.) * u.hour)
with pytest.raises(u.UnitTypeError):
self.Length(np.arange(10.))
l2 = self.Length2(np.arange(5.))
assert type(l2) is self.Length2
assert l2._default_unit is self.Length2._default_unit
with pytest.raises(u.UnitTypeError):
self.Length3(np.arange(10.))
def test_view(self):
l = (np.arange(5.) * u.km).view(self.Length)
assert type(l) is self.Length
with pytest.raises(u.UnitTypeError):
(np.arange(5.) * u.s).view(self.Length)
v = np.arange(5.).view(self.Length)
assert type(v) is self.Length
assert v._unit is None
l3 = np.ones((2, 2)).view(self.Length3)
assert type(l3) is self.Length3
assert l3.unit is self.Length3._unit
def test_operation_precedence_and_fallback(self):
l = self.Length(np.arange(5.)*u.cm)
sum1 = l + 1.*u.m
assert type(sum1) is self.Length
sum2 = 1.*u.km + l
assert type(sum2) is self.Length
sum3 = l + l
assert type(sum3) is self.Length
res1 = l * (1.*u.m)
assert type(res1) is u.Quantity
res2 = l * l
assert type(res2) is u.Quantity
@pytest.mark.skipif('not HAS_MATPLOTLIB')
@pytest.mark.xfail('MATPLOTLIB_LT_15')
class TestQuantityMatplotlib:
"""Test if passing matplotlib quantities works.
TODO: create PNG output and check against reference image
once `astropy.wcsaxes` is merged, which provides
the machinery for this.
See https://github.com/astropy/astropy/issues/1881
See https://github.com/astropy/astropy/pull/2139
"""
def test_plot(self):
data = u.Quantity([4, 5, 6], 's')
plt.plot(data)
def test_scatter(self):
x = u.Quantity([4, 5, 6], 'second')
y = [1, 3, 4] * u.m
plt.scatter(x, y)
def test_unit_class_override():
class MyQuantity(u.Quantity):
pass
my_unit = u.Unit("my_deg", u.deg)
my_unit._quantity_class = MyQuantity
q1 = u.Quantity(1., my_unit)
assert type(q1) is u.Quantity
q2 = u.Quantity(1., my_unit, subok=True)
assert type(q2) is MyQuantity
|
c6ad841ab682b5a775b82fe0c6aebc76dfdf4fcd0630fef5a3698edfb0bc79e1 | import numpy as np
import pytest
from ... import units as u
class TestQuantityLinAlgFuncs:
"""
Test linear algebra functions
"""
@pytest.mark.xfail
def test_outer(self):
q1 = np.array([1, 2, 3]) * u.m
q2 = np.array([1, 2]) / u.s
o = np.outer(q1, q2)
assert np.all(o == np.array([[1, 2], [2, 4], [3, 6]]) * u.m / u.s)
@pytest.mark.xfail
def test_inner(self):
q1 = np.array([1, 2, 3]) * u.m
q2 = np.array([4, 5, 6]) / u.s
o = np.inner(q1, q2)
assert o == 32 * u.m / u.s
@pytest.mark.xfail
def test_dot(self):
q1 = np.array([1., 2., 3.]) * u.m
q2 = np.array([4., 5., 6.]) / u.s
o = np.dot(q1, q2)
assert o == 32. * u.m / u.s
@pytest.mark.xfail
def test_matmul(self):
q1 = np.eye(3) * u.m
q2 = np.array([4., 5., 6.]) / u.s
o = np.matmul(q1, q2)
assert o == q2 / u.s
|
dd43982d32621b9cc8f632fe16f007bd333c8a3dcbbfc4be72f3d4c0b002e541 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Regression tests for the physical_type support in the units package
"""
from ... import units as u
from ...units import physical
from ...constants import hbar
from ...tests.helper import raises
def test_simple():
assert u.m.physical_type == 'length'
def test_power():
assert (u.cm ** 3).physical_type == 'volume'
def test_speed():
assert (u.km / u.h).physical_type == 'speed'
def test_unknown():
assert (u.m * u.s).physical_type == 'unknown'
def test_dimensionless():
assert (u.m / u.m).physical_type == 'dimensionless'
def test_angular_momentum():
assert hbar.unit.physical_type == 'angular momentum'
def test_flam():
flam = u.erg / (u.cm**2 * u.s * u.AA)
assert flam.physical_type == 'spectral flux density wav'
def test_photlam():
photlam = u.photon / (u.cm ** 2 * u.s * u.AA)
assert photlam.physical_type == 'photon flux density wav'
def test_photnu():
photnu = u.photon / (u.cm ** 2 * u.s * u.Hz)
assert photnu.physical_type == 'photon flux density'
@raises(ValueError)
def test_redundant_physical_type():
physical.def_physical_type(u.m, 'utter craziness')
def test_data_quantity():
assert u.byte.physical_type == 'data quantity'
assert u.bit.physical_type == 'data quantity'
|
da157504899e8d0c5e088b667f9e6716341323590427e05f139a5a1a8ad5421d | # The purpose of these tests are to ensure that calling ufuncs with quantities
# returns quantities with the right units, or raises exceptions.
import warnings
import pytest
import numpy as np
from numpy.testing.utils import assert_allclose
from collections import namedtuple
from ... import units as u
from ...tests.helper import raises
from ...utils.compat import NUMPY_LT_1_13
try:
import scipy # pylint: disable=W0611
except ImportError:
HAS_SCIPY = False
else:
HAS_SCIPY = True
testcase = namedtuple('testcase', ['f', 'q_in', 'q_out'])
testexc = namedtuple('testexc', ['f', 'q_in', 'exc', 'msg'])
testwarn = namedtuple('testwarn', ['f', 'q_in', 'wfilter'])
@pytest.mark.skip
def test_testcase(tc):
results = tc.f(*tc.q_in)
# careful of the following line, would break on a function returning
# a single tuple (as opposed to tuple of return values)
results = (results, ) if type(results) != tuple else results
for result, expected in zip(results, tc.q_out):
assert result.unit == expected.unit
assert_allclose(result.value, expected.value, atol=1.E-15)
@pytest.mark.skip
def test_testexc(te):
with pytest.raises(te.exc) as exc:
te.f(*te.q_in)
if te.msg is not None:
assert te.msg in exc.value.args[0]
@pytest.mark.skip
def test_testwarn(tw):
with warnings.catch_warnings():
warnings.filterwarnings(tw.wfilter)
tw.f(*tw.q_in)
class TestUfuncCoverage:
"""Test that we cover all ufunc's"""
def test_coverage(self):
all_extern_ufuncs = set([])
all_np_ufuncs = set([ufunc for ufunc in np.core.umath.__dict__.values()
if type(ufunc) == np.ufunc])
all_extern_ufuncs |= all_np_ufuncs
from .. import quantity_helper as qh
all_q_ufuncs = (qh.UNSUPPORTED_UFUNCS |
set(qh.UFUNC_HELPERS.keys()))
# Ignore possible non-numpy ufuncs; for scipy in particular, we have
# support for some, but for others it still has to be decided whether
# we can support them or not.
if HAS_SCIPY:
import scipy.special as sps
all_sps_ufuncs = set([ufunc for ufunc in sps.__dict__.values()
if type(ufunc) == np.ufunc])
all_q_ufuncs -= all_sps_ufuncs
assert all_extern_ufuncs - all_q_ufuncs == set([])
assert all_q_ufuncs - all_extern_ufuncs == set([])
class TestQuantityTrigonometricFuncs:
"""
Test trigonometric functions
"""
@pytest.mark.parametrize('tc', (
testcase(
f=np.sin,
q_in=(30. * u.degree, ),
q_out=(0.5*u.dimensionless_unscaled, )
),
testcase(
f=np.sin,
q_in=(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian, ),
q_out=(np.array([0., 1. / np.sqrt(2.), 1.]) * u.one, )
),
testcase(
f=np.arcsin,
q_in=(np.sin(30. * u.degree), ),
q_out=(np.radians(30.) * u.radian, )
),
testcase(
f=np.arcsin,
q_in=(np.sin(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian), ),
q_out=(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian, )
),
testcase(
f=np.cos,
q_in=(np.pi / 3. * u.radian, ),
q_out=(0.5 * u.dimensionless_unscaled, )
),
testcase(
f=np.cos,
q_in=(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian, ),
q_out=(np.array([1., 1. / np.sqrt(2.), 0.]) * u.one, )
),
testcase(
f=np.arccos,
q_in=(np.cos(np.pi / 3. * u.radian), ),
q_out=(np.pi / 3. * u.radian, )
),
testcase(
f=np.arccos,
q_in=(np.cos(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian), ),
q_out=(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian, ),
),
testcase(
f=np.tan,
q_in=(np.pi / 3. * u.radian, ),
q_out=(np.sqrt(3.) * u.dimensionless_unscaled, )
),
testcase(
f=np.tan,
q_in=(np.array([0., 45., 135., 180.]) * u.degree, ),
q_out=(np.array([0., 1., -1., 0.]) * u.dimensionless_unscaled, )
),
testcase(
f=np.arctan,
q_in=(np.tan(np.pi / 3. * u.radian), ),
q_out=(np.pi / 3. * u.radian, )
),
testcase(
f=np.arctan,
q_in=(np.tan(np.array([10., 30., 70., 80.]) * u.degree), ),
q_out=(np.radians(np.array([10., 30., 70., 80.]) * u.degree), )
),
testcase(
f=np.arctan2,
q_in=(np.array([10., 30., 70., 80.]) * u.m, 2.0 * u.km),
q_out=(np.arctan2(np.array([10., 30., 70., 80.]),
2000.) * u.radian, )
),
testcase(
f=np.arctan2,
q_in=((np.array([10., 80.]) * u.m / (2.0 * u.km)).to(u.one), 1.),
q_out=(np.arctan2(np.array([10., 80.]) / 2000., 1.) * u.radian, )
),
testcase(
f=np.deg2rad,
q_in=(180. * u.degree, ),
q_out=(np.pi * u.radian, )
),
testcase(
f=np.radians,
q_in=(180. * u.degree, ),
q_out=(np.pi * u.radian, )
),
testcase(
f=np.deg2rad,
q_in=(3. * u.radian, ),
q_out=(3. * u.radian, )
),
testcase(
f=np.radians,
q_in=(3. * u.radian, ),
q_out=(3. * u.radian, )
),
testcase(
f=np.rad2deg,
q_in=(60. * u.degree, ),
q_out=(60. * u.degree, )
),
testcase(
f=np.degrees,
q_in=(60. * u.degree, ),
q_out=(60. * u.degree, )
),
testcase(
f=np.rad2deg,
q_in=(np.pi * u.radian, ),
q_out=(180. * u.degree, )
),
testcase(
f=np.degrees,
q_in=(np.pi * u.radian, ),
q_out=(180. * u.degree, )
)
))
def test_testcases(self, tc):
return test_testcase(tc)
@pytest.mark.parametrize('te', (
testexc(
f=np.deg2rad,
q_in=(3. * u.m, ),
exc=TypeError,
msg=None
),
testexc(
f=np.radians,
q_in=(3. * u.m, ),
exc=TypeError,
msg=None
),
testexc(
f=np.rad2deg,
q_in=(3. * u.m),
exc=TypeError,
msg=None
),
testexc(
f=np.degrees,
q_in=(3. * u.m),
exc=TypeError,
msg=None
),
testexc(
f=np.sin,
q_in=(3. * u.m, ),
exc=TypeError,
msg="Can only apply 'sin' function to quantities with angle units"
),
testexc(
f=np.arcsin,
q_in=(3. * u.m, ),
exc=TypeError,
msg="Can only apply 'arcsin' function to dimensionless quantities"
),
testexc(
f=np.cos,
q_in=(3. * u.s, ),
exc=TypeError,
msg="Can only apply 'cos' function to quantities with angle units"
),
testexc(
f=np.arccos,
q_in=(3. * u.s, ),
exc=TypeError,
msg="Can only apply 'arccos' function to dimensionless quantities"
),
testexc(
f=np.tan,
q_in=(np.array([1, 2, 3]) * u.N, ),
exc=TypeError,
msg="Can only apply 'tan' function to quantities with angle units"
),
testexc(
f=np.arctan,
q_in=(np.array([1, 2, 3]) * u.N, ),
exc=TypeError,
msg="Can only apply 'arctan' function to dimensionless quantities"
),
testexc(
f=np.arctan2,
q_in=(np.array([1, 2, 3]) * u.N, 1. * u.s),
exc=u.UnitsError,
msg="compatible dimensions"
),
testexc(
f=np.arctan2,
q_in=(np.array([1, 2, 3]) * u.N, 1.),
exc=u.UnitsError,
msg="dimensionless quantities when other arg"
)
))
def test_testexcs(self, te):
return test_testexc(te)
@pytest.mark.parametrize('tw', (
testwarn(
f=np.arcsin,
q_in=(27. * u.pc / (15 * u.kpc), ),
wfilter='error'
),
))
def test_testwarns(self, tw):
return test_testwarn(tw)
class TestQuantityMathFuncs:
"""
Test other mathematical functions
"""
def test_multiply_scalar(self):
assert np.multiply(4. * u.m, 2. / u.s) == 8. * u.m / u.s
assert np.multiply(4. * u.m, 2.) == 8. * u.m
assert np.multiply(4., 2. / u.s) == 8. / u.s
def test_multiply_array(self):
assert np.all(np.multiply(np.arange(3.) * u.m, 2. / u.s) ==
np.arange(0, 6., 2.) * u.m / u.s)
@pytest.mark.parametrize('function', (np.divide, np.true_divide))
def test_divide_scalar(self, function):
assert function(4. * u.m, 2. * u.s) == function(4., 2.) * u.m / u.s
assert function(4. * u.m, 2.) == function(4., 2.) * u.m
assert function(4., 2. * u.s) == function(4., 2.) / u.s
@pytest.mark.parametrize('function', (np.divide, np.true_divide))
def test_divide_array(self, function):
assert np.all(function(np.arange(3.) * u.m, 2. * u.s) ==
function(np.arange(3.), 2.) * u.m / u.s)
def test_floor_divide_remainder_and_divmod(self):
inch = u.Unit(0.0254 * u.m)
dividend = np.array([1., 2., 3.]) * u.m
divisor = np.array([3., 4., 5.]) * inch
quotient = dividend // divisor
remainder = dividend % divisor
assert_allclose(quotient.value, [13., 19., 23.])
assert quotient.unit == u.dimensionless_unscaled
assert_allclose(remainder.value, [0.0094, 0.0696, 0.079])
assert remainder.unit == dividend.unit
quotient2 = np.floor_divide(dividend, divisor)
remainder2 = np.remainder(dividend, divisor)
assert np.all(quotient2 == quotient)
assert np.all(remainder2 == remainder)
quotient3, remainder3 = divmod(dividend, divisor)
assert np.all(quotient3 == quotient)
assert np.all(remainder3 == remainder)
with pytest.raises(TypeError):
divmod(dividend, u.km)
with pytest.raises(TypeError):
dividend // u.km
with pytest.raises(TypeError):
dividend % u.km
if hasattr(np, 'divmod'): # not NUMPY_LT_1_13
quotient4, remainder4 = np.divmod(dividend, divisor)
assert np.all(quotient4 == quotient)
assert np.all(remainder4 == remainder)
with pytest.raises(TypeError):
np.divmod(dividend, u.km)
def test_sqrt_scalar(self):
assert np.sqrt(4. * u.m) == 2. * u.m ** 0.5
def test_sqrt_array(self):
assert np.all(np.sqrt(np.array([1., 4., 9.]) * u.m)
== np.array([1., 2., 3.]) * u.m ** 0.5)
def test_square_scalar(self):
assert np.square(4. * u.m) == 16. * u.m ** 2
def test_square_array(self):
assert np.all(np.square(np.array([1., 2., 3.]) * u.m)
== np.array([1., 4., 9.]) * u.m ** 2)
def test_reciprocal_scalar(self):
assert np.reciprocal(4. * u.m) == 0.25 / u.m
def test_reciprocal_array(self):
assert np.all(np.reciprocal(np.array([1., 2., 4.]) * u.m)
== np.array([1., 0.5, 0.25]) / u.m)
# heaviside only introduced in numpy 1.13
@pytest.mark.skipif("not hasattr(np, 'heaviside')")
def test_heaviside_scalar(self):
assert np.heaviside(0. * u.m, 0.5) == 0.5 * u.dimensionless_unscaled
assert np.heaviside(0. * u.s,
25 * u.percent) == 0.25 * u.dimensionless_unscaled
assert np.heaviside(2. * u.J, 0.25) == 1. * u.dimensionless_unscaled
@pytest.mark.skipif("not hasattr(np, 'heaviside')")
def test_heaviside_array(self):
values = np.array([-1., 0., 0., +1.])
halfway = np.array([0.75, 0.25, 0.75, 0.25]) * u.dimensionless_unscaled
assert np.all(np.heaviside(values * u.m,
halfway * u.dimensionless_unscaled) ==
[0, 0.25, 0.75, +1.] * u.dimensionless_unscaled)
@pytest.mark.parametrize('function', (np.cbrt, ))
def test_cbrt_scalar(self, function):
assert function(8. * u.m**3) == 2. * u.m
@pytest.mark.parametrize('function', (np.cbrt, ))
def test_cbrt_array(self, function):
# Calculate cbrt on both sides since on Windows the cube root of 64
# does not exactly equal 4. See 4388.
values = np.array([1., 8., 64.])
assert np.all(function(values * u.m**3) ==
function(values) * u.m)
def test_power_scalar(self):
assert np.power(4. * u.m, 2.) == 16. * u.m ** 2
assert np.power(4., 200. * u.cm / u.m) == \
u.Quantity(16., u.dimensionless_unscaled)
# regression check on #1696
assert np.power(4. * u.m, 0.) == 1. * u.dimensionless_unscaled
def test_power_array(self):
assert np.all(np.power(np.array([1., 2., 3.]) * u.m, 3.)
== np.array([1., 8., 27.]) * u.m ** 3)
# regression check on #1696
assert np.all(np.power(np.arange(4.) * u.m, 0.) ==
1. * u.dimensionless_unscaled)
# float_power only introduced in numpy 1.12
@pytest.mark.skipif("not hasattr(np, 'float_power')")
def test_float_power_array(self):
assert np.all(np.float_power(np.array([1., 2., 3.]) * u.m, 3.)
== np.array([1., 8., 27.]) * u.m ** 3)
# regression check on #1696
assert np.all(np.float_power(np.arange(4.) * u.m, 0.) ==
1. * u.dimensionless_unscaled)
@raises(ValueError)
def test_power_array_array(self):
np.power(4. * u.m, [2., 4.])
@raises(ValueError)
def test_power_array_array2(self):
np.power([2., 4.] * u.m, [2., 4.])
def test_power_array_array3(self):
# Identical unit fractions are converted automatically to dimensionless
# and should be allowed as base for np.power: #4764
q = [2., 4.] * u.m / u.m
powers = [2., 4.]
res = np.power(q, powers)
assert np.all(res.value == q.value ** powers)
assert res.unit == u.dimensionless_unscaled
# The same holds for unit fractions that are scaled dimensionless.
q2 = [2., 4.] * u.m / u.cm
# Test also against different types of exponent
for cls in (list, tuple, np.array, np.ma.array, u.Quantity):
res2 = np.power(q2, cls(powers))
assert np.all(res2.value == q2.to_value(1) ** powers)
assert res2.unit == u.dimensionless_unscaled
# Though for single powers, we keep the composite unit.
res3 = q2 ** 2
assert np.all(res3.value == q2.value ** 2)
assert res3.unit == q2.unit ** 2
assert np.all(res3 == q2 ** [2, 2])
def test_power_invalid(self):
with pytest.raises(TypeError) as exc:
np.power(3., 4. * u.m)
assert "raise something to a dimensionless" in exc.value.args[0]
def test_copysign_scalar(self):
assert np.copysign(3 * u.m, 1.) == 3. * u.m
assert np.copysign(3 * u.m, 1. * u.s) == 3. * u.m
assert np.copysign(3 * u.m, -1.) == -3. * u.m
assert np.copysign(3 * u.m, -1. * u.s) == -3. * u.m
def test_copysign_array(self):
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1.) ==
-np.array([1., 2., 3.]) * u.s)
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1. * u.m) ==
-np.array([1., 2., 3.]) * u.s)
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s,
np.array([-2., 2., -4.]) * u.m) ==
np.array([-1., 2., -3.]) * u.s)
q = np.copysign(np.array([1., 2., 3.]), -3 * u.m)
assert np.all(q == np.array([-1., -2., -3.]))
assert not isinstance(q, u.Quantity)
def test_ldexp_scalar(self):
assert np.ldexp(4. * u.m, 2) == 16. * u.m
def test_ldexp_array(self):
assert np.all(np.ldexp(np.array([1., 2., 3.]) * u.m, [3, 2, 1])
== np.array([8., 8., 6.]) * u.m)
def test_ldexp_invalid(self):
with pytest.raises(TypeError):
np.ldexp(3. * u.m, 4.)
with pytest.raises(TypeError):
np.ldexp(3., u.Quantity(4, u.m, dtype=int))
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_scalar(self, function):
q = function(3. * u.m / (6. * u.m))
assert q.unit == u.dimensionless_unscaled
assert q.value == function(0.5)
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_array(self, function):
q = function(np.array([2., 3., 6.]) * u.m / (6. * u.m))
assert q.unit == u.dimensionless_unscaled
assert np.all(q.value
== function(np.array([1. / 3., 1. / 2., 1.])))
# should also work on quantities that can be made dimensionless
q2 = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm))
assert q2.unit == u.dimensionless_unscaled
assert_allclose(q2.value,
function(np.array([100. / 3., 100. / 2., 100.])))
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_invalid_units(self, function):
# Can't use exp() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
function(3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply '{0}' function to "
"dimensionless quantities"
.format(function.__name__))
def test_modf_scalar(self):
q = np.modf(9. * u.m / (600. * u.cm))
assert q == (0.5 * u.dimensionless_unscaled,
1. * u.dimensionless_unscaled)
def test_modf_array(self):
v = np.arange(10.) * u.m / (500. * u.cm)
q = np.modf(v)
n = np.modf(v.to_value(u.dimensionless_unscaled))
assert q[0].unit == u.dimensionless_unscaled
assert q[1].unit == u.dimensionless_unscaled
assert all(q[0].value == n[0])
assert all(q[1].value == n[1])
def test_frexp_scalar(self):
q = np.frexp(3. * u.m / (6. * u.m))
assert q == (np.array(0.5), np.array(0.0))
def test_frexp_array(self):
q = np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.m))
assert all((_q0, _q1) == np.frexp(_d) for _q0, _q1, _d
in zip(q[0], q[1], [1. / 3., 1. / 2., 1.]))
def test_frexp_invalid_units(self):
# Can't use prod() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
np.frexp(3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply 'frexp' function to "
"unscaled dimensionless quantities")
# also does not work on quantities that can be made dimensionless
with pytest.raises(TypeError) as exc:
np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.cm))
assert exc.value.args[0] == ("Can only apply 'frexp' function to "
"unscaled dimensionless quantities")
@pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2))
def test_dimensionless_twoarg_array(self, function):
q = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm), 1.)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value,
function(np.array([100. / 3., 100. / 2., 100.]), 1.))
@pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2))
def test_dimensionless_twoarg_invalid_units(self, function):
with pytest.raises(TypeError) as exc:
function(1. * u.km / u.s, 3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply '{0}' function to "
"dimensionless quantities"
.format(function.__name__))
class TestInvariantUfuncs:
# np.positive was only added in numpy 1.13.
@pytest.mark.parametrize(('ufunc'), [np.absolute, np.fabs,
np.conj, np.conjugate,
np.negative, np.spacing, np.rint,
np.floor, np.ceil] +
[np.positive] if hasattr(np, 'positive') else [])
def test_invariant_scalar(self, ufunc):
q_i = 4.7 * u.m
q_o = ufunc(q_i)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i.unit
assert q_o.value == ufunc(q_i.value)
@pytest.mark.parametrize(('ufunc'), [np.absolute, np.conjugate,
np.negative, np.rint,
np.floor, np.ceil])
def test_invariant_array(self, ufunc):
q_i = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_o = ufunc(q_i)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i.unit
assert np.all(q_o.value == ufunc(q_i.value))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_scalar(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.km
q_o = ufunc(q_i1, q_i2)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_array(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_i2 = np.array([10., -5., 1.e6]) * u.g / u.us
q_o = ufunc(q_i1, q_i2)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_one_arbitrary(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
arbitrary_unit_value = np.array([0.])
q_o = ufunc(q_i1, arbitrary_unit_value)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, arbitrary_unit_value))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_invalid_units(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.s
with pytest.raises(u.UnitsError) as exc:
ufunc(q_i1, q_i2)
assert "compatible dimensions" in exc.value.args[0]
class TestComparisonUfuncs:
@pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal,
np.less, np.less_equal,
np.not_equal, np.equal])
def test_comparison_valid_units(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_i2 = np.array([10., -5., 1.e6]) * u.g / u.Ms
q_o = ufunc(q_i1, q_i2)
assert not isinstance(q_o, u.Quantity)
assert q_o.dtype == bool
assert np.all(q_o == ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
q_o2 = ufunc(q_i1 / q_i2, 2.)
assert not isinstance(q_o2, u.Quantity)
assert q_o2.dtype == bool
assert np.all(q_o2 == ufunc((q_i1 / q_i2)
.to_value(u.dimensionless_unscaled), 2.))
# comparison with 0., inf, nan is OK even for dimensional quantities
for arbitrary_unit_value in (0., np.inf, np.nan):
ufunc(q_i1, arbitrary_unit_value)
ufunc(q_i1, arbitrary_unit_value*np.ones(len(q_i1)))
# and just for completeness
ufunc(q_i1, np.array([0., np.inf, np.nan]))
@pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal,
np.less, np.less_equal,
np.not_equal, np.equal])
def test_comparison_invalid_units(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.s
with pytest.raises(u.UnitsError) as exc:
ufunc(q_i1, q_i2)
assert "compatible dimensions" in exc.value.args[0]
class TestInplaceUfuncs:
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_one_argument_ufunc_inplace(self, value):
# without scaling
s = value * u.rad
check = s
np.sin(s, out=s)
assert check is s
assert check.unit == u.dimensionless_unscaled
# with scaling
s2 = (value * u.rad).to(u.deg)
check2 = s2
np.sin(s2, out=s2)
assert check2 is s2
assert check2.unit == u.dimensionless_unscaled
assert_allclose(s.value, s2.value)
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_one_argument_ufunc_inplace_2(self, value):
"""Check inplace works with non-quantity input and quantity output"""
s = value * u.m
check = s
np.absolute(value, out=s)
assert check is s
assert np.all(check.value == np.absolute(value))
assert check.unit is u.dimensionless_unscaled
np.sqrt(value, out=s)
assert check is s
assert np.all(check.value == np.sqrt(value))
assert check.unit is u.dimensionless_unscaled
np.exp(value, out=s)
assert check is s
assert np.all(check.value == np.exp(value))
assert check.unit is u.dimensionless_unscaled
np.arcsin(value/10., out=s)
assert check is s
assert np.all(check.value == np.arcsin(value/10.))
assert check.unit is u.radian
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_one_argument_two_output_ufunc_inplace(self, value):
v = 100. * value * u.cm / u.m
v_copy = v.copy()
tmp = v.copy()
check = v
np.modf(v, tmp, v) # cannot use out1,out2 keywords with numpy 1.7
assert check is v
assert check.unit == u.dimensionless_unscaled
v2 = v_copy.to(u.dimensionless_unscaled)
check2 = v2
np.modf(v2, tmp, v2)
assert check2 is v2
assert check2.unit == u.dimensionless_unscaled
# can also replace in last position if no scaling is needed
v3 = v_copy.to(u.dimensionless_unscaled)
check3 = v3
np.modf(v3, v3, tmp)
assert check3 is v3
assert check3.unit == u.dimensionless_unscaled
# in np<1.13, without __array_ufunc__, one cannot replace input with
# first output when scaling
v4 = v_copy.copy()
if NUMPY_LT_1_13:
with pytest.raises(TypeError):
np.modf(v4, v4, tmp)
else:
check4 = v4
np.modf(v4, v4, tmp)
assert check4 is v4
assert check4.unit == u.dimensionless_unscaled
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_two_argument_ufunc_inplace_1(self, value):
s = value * u.cycle
check = s
s /= 2.
assert check is s
assert np.all(check.value == value / 2.)
s /= u.s
assert check is s
assert check.unit == u.cycle / u.s
s *= 2. * u.s
assert check is s
assert np.all(check == value * u.cycle)
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_two_argument_ufunc_inplace_2(self, value):
s = value * u.cycle
check = s
np.arctan2(s, s, out=s)
assert check is s
assert check.unit == u.radian
with pytest.raises(u.UnitsError):
s += 1. * u.m
assert check is s
assert check.unit == u.radian
np.arctan2(1. * u.deg, s, out=s)
assert check is s
assert check.unit == u.radian
np.add(1. * u.deg, s, out=s)
assert check is s
assert check.unit == u.deg
np.multiply(2. / u.s, s, out=s)
assert check is s
assert check.unit == u.deg / u.s
def test_two_argument_ufunc_inplace_3(self):
s = np.array([1., 2., 3.]) * u.dimensionless_unscaled
np.add(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s)
assert np.all(s.value == np.array([3., 6., 9.]))
assert s.unit is u.dimensionless_unscaled
np.arctan2(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s)
assert_allclose(s.value, np.arctan2(1., 2.))
assert s.unit is u.radian
@pytest.mark.skipif(NUMPY_LT_1_13, reason="numpy >=1.13 required.")
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_two_argument_two_output_ufunc_inplace(self, value):
v = value * u.m
divisor = 70.*u.cm
v1 = v.copy()
tmp = v.copy()
check = np.divmod(v1, divisor, out=(tmp, v1))
assert check[0] is tmp and check[1] is v1
assert tmp.unit == u.dimensionless_unscaled
assert v1.unit == v.unit
v2 = v.copy()
check2 = np.divmod(v2, divisor, out=(v2, tmp))
assert check2[0] is v2 and check2[1] is tmp
assert v2.unit == u.dimensionless_unscaled
assert tmp.unit == v.unit
v3a = v.copy()
v3b = v.copy()
check3 = np.divmod(v3a, divisor, out=(v3a, v3b))
assert check3[0] is v3a and check3[1] is v3b
assert v3a.unit == u.dimensionless_unscaled
assert v3b.unit == v.unit
def test_ufunc_inplace_non_contiguous_data(self):
# ensure inplace works also for non-contiguous data (closes #1834)
s = np.arange(10.) * u.m
s_copy = s.copy()
s2 = s[::2]
s2 += 1. * u.cm
assert np.all(s[::2] > s_copy[::2])
assert np.all(s[1::2] == s_copy[1::2])
def test_ufunc_inplace_non_standard_dtype(self):
"""Check that inplace operations check properly for casting.
First two tests that check that float32 is kept close #3976.
"""
a1 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32)
a1 *= np.float32(10)
assert a1.unit is u.m
assert a1.dtype == np.float32
a2 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32)
a2 += (20.*u.km)
assert a2.unit is u.m
assert a2.dtype == np.float32
# For integer, in-place only works if no conversion is done.
a3 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32)
a3 += u.Quantity(10, u.m, dtype=np.int64)
assert a3.unit is u.m
assert a3.dtype == np.int32
a4 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32)
with pytest.raises(TypeError):
a4 += u.Quantity(10, u.mm, dtype=np.int64)
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncAt:
"""Test that 'at' method for ufuncs (calculates in-place at given indices)
For Quantities, since calculations are in-place, it makes sense only
if the result is still a quantity, and if the unit does not have to change
"""
def test_one_argument_ufunc_at(self):
q = np.arange(10.) * u.m
i = np.array([1, 2])
qv = q.value.copy()
np.negative.at(q, i)
np.negative.at(qv, i)
assert np.all(q.value == qv)
assert q.unit is u.m
# cannot change from quantity to bool array
with pytest.raises(TypeError):
np.isfinite.at(q, i)
# for selective in-place, cannot change the unit
with pytest.raises(u.UnitsError):
np.square.at(q, i)
# except if the unit does not change (i.e., dimensionless)
d = np.arange(10.) * u.dimensionless_unscaled
dv = d.value.copy()
np.square.at(d, i)
np.square.at(dv, i)
assert np.all(d.value == dv)
assert d.unit is u.dimensionless_unscaled
d = np.arange(10.) * u.dimensionless_unscaled
dv = d.value.copy()
np.log.at(d, i)
np.log.at(dv, i)
assert np.all(d.value == dv)
assert d.unit is u.dimensionless_unscaled
# also for sine it doesn't work, even if given an angle
a = np.arange(10.) * u.radian
with pytest.raises(u.UnitsError):
np.sin.at(a, i)
# except, for consistency, if we have made radian equivalent to
# dimensionless (though hopefully it will never be needed)
av = a.value.copy()
with u.add_enabled_equivalencies(u.dimensionless_angles()):
np.sin.at(a, i)
np.sin.at(av, i)
assert_allclose(a.value, av)
# but we won't do double conversion
ad = np.arange(10.) * u.degree
with pytest.raises(u.UnitsError):
np.sin.at(ad, i)
def test_two_argument_ufunc_at(self):
s = np.arange(10.) * u.m
i = np.array([1, 2])
check = s.value.copy()
np.add.at(s, i, 1.*u.km)
np.add.at(check, i, 1000.)
assert np.all(s.value == check)
assert s.unit is u.m
with pytest.raises(u.UnitsError):
np.add.at(s, i, 1.*u.s)
# also raise UnitsError if unit would have to be changed
with pytest.raises(u.UnitsError):
np.multiply.at(s, i, 1*u.s)
# but be fine if it does not
s = np.arange(10.) * u.m
check = s.value.copy()
np.multiply.at(s, i, 2.*u.dimensionless_unscaled)
np.multiply.at(check, i, 2)
assert np.all(s.value == check)
s = np.arange(10.) * u.m
np.multiply.at(s, i, 2.)
assert np.all(s.value == check)
# of course cannot change class of data either
with pytest.raises(TypeError):
np.greater.at(s, i, 1.*u.km)
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncReduceReduceatAccumulate:
"""Test 'reduce', 'reduceat' and 'accumulate' methods for ufuncs
For Quantities, it makes sense only if the unit does not have to change
"""
def test_one_argument_ufunc_reduce_accumulate(self):
# one argument cannot be used
s = np.arange(10.) * u.radian
i = np.array([0, 5, 1, 6])
with pytest.raises(ValueError):
np.sin.reduce(s)
with pytest.raises(ValueError):
np.sin.accumulate(s)
with pytest.raises(ValueError):
np.sin.reduceat(s, i)
def test_two_argument_ufunc_reduce_accumulate(self):
s = np.arange(10.) * u.m
i = np.array([0, 5, 1, 6])
check = s.value.copy()
s_add_reduce = np.add.reduce(s)
check_add_reduce = np.add.reduce(check)
assert s_add_reduce.value == check_add_reduce
assert s_add_reduce.unit is u.m
s_add_accumulate = np.add.accumulate(s)
check_add_accumulate = np.add.accumulate(check)
assert np.all(s_add_accumulate.value == check_add_accumulate)
assert s_add_accumulate.unit is u.m
s_add_reduceat = np.add.reduceat(s, i)
check_add_reduceat = np.add.reduceat(check, i)
assert np.all(s_add_reduceat.value == check_add_reduceat)
assert s_add_reduceat.unit is u.m
# reduce(at) or accumulate on comparisons makes no sense,
# as intermediate result is not even a Quantity
with pytest.raises(TypeError):
np.greater.reduce(s)
with pytest.raises(TypeError):
np.greater.accumulate(s)
with pytest.raises(TypeError):
np.greater.reduceat(s, i)
# raise UnitsError if unit would have to be changed
with pytest.raises(u.UnitsError):
np.multiply.reduce(s)
with pytest.raises(u.UnitsError):
np.multiply.accumulate(s)
with pytest.raises(u.UnitsError):
np.multiply.reduceat(s, i)
# but be fine if it does not
s = np.arange(10.) * u.dimensionless_unscaled
check = s.value.copy()
s_multiply_reduce = np.multiply.reduce(s)
check_multiply_reduce = np.multiply.reduce(check)
assert s_multiply_reduce.value == check_multiply_reduce
assert s_multiply_reduce.unit is u.dimensionless_unscaled
s_multiply_accumulate = np.multiply.accumulate(s)
check_multiply_accumulate = np.multiply.accumulate(check)
assert np.all(s_multiply_accumulate.value == check_multiply_accumulate)
assert s_multiply_accumulate.unit is u.dimensionless_unscaled
s_multiply_reduceat = np.multiply.reduceat(s, i)
check_multiply_reduceat = np.multiply.reduceat(check, i)
assert np.all(s_multiply_reduceat.value == check_multiply_reduceat)
assert s_multiply_reduceat.unit is u.dimensionless_unscaled
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncOuter:
"""Test 'outer' methods for ufuncs
Just a few spot checks, since it uses the same code as the regular
ufunc call
"""
def test_one_argument_ufunc_outer(self):
# one argument cannot be used
s = np.arange(10.) * u.radian
with pytest.raises(ValueError):
np.sin.outer(s)
def test_two_argument_ufunc_outer(self):
s1 = np.arange(10.) * u.m
s2 = np.arange(2.) * u.s
check1 = s1.value
check2 = s2.value
s12_multiply_outer = np.multiply.outer(s1, s2)
check12_multiply_outer = np.multiply.outer(check1, check2)
assert np.all(s12_multiply_outer.value == check12_multiply_outer)
assert s12_multiply_outer.unit == s1.unit * s2.unit
# raise UnitsError if appropriate
with pytest.raises(u.UnitsError):
np.add.outer(s1, s2)
# but be fine if it does not
s3 = np.arange(2.) * s1.unit
check3 = s3.value
s13_add_outer = np.add.outer(s1, s3)
check13_add_outer = np.add.outer(check1, check3)
assert np.all(s13_add_outer.value == check13_add_outer)
assert s13_add_outer.unit is s1.unit
s13_greater_outer = np.greater.outer(s1, s3)
check13_greater_outer = np.greater.outer(check1, check3)
assert type(s13_greater_outer) is np.ndarray
assert np.all(s13_greater_outer == check13_greater_outer)
if HAS_SCIPY:
from scipy import special as sps
class TestScipySpecialUfuncs:
erf_like_ufuncs = (
sps.erf, sps.gamma, sps.loggamma, sps.gammasgn, sps.psi,
sps.rgamma, sps.erfc, sps.erfcx, sps.erfi, sps.wofz, sps.dawsn,
sps.entr, sps.exprel, sps.expm1, sps.log1p, sps.exp2, sps.exp10)
@pytest.mark.parametrize('function', erf_like_ufuncs)
def test_erf_scalar(self, function):
TestQuantityMathFuncs.test_exp_scalar(None, function)
@pytest.mark.parametrize('function', erf_like_ufuncs)
def test_erf_array(self, function):
TestQuantityMathFuncs.test_exp_array(None, function)
@pytest.mark.parametrize('function', erf_like_ufuncs)
def test_erf_invalid_units(self, function):
TestQuantityMathFuncs.test_exp_invalid_units(None, function)
@pytest.mark.parametrize('function', (sps.cbrt, ))
def test_cbrt_scalar(self, function):
TestQuantityMathFuncs.test_cbrt_scalar(None, function)
@pytest.mark.parametrize('function', (sps.cbrt, ))
def test_cbrt_array(self, function):
TestQuantityMathFuncs.test_cbrt_array(None, function)
@pytest.mark.parametrize('function', (sps.radian, ))
def test_radian(self, function):
q1 = function(180. * u.degree, 0. * u.arcmin, 0. * u.arcsec)
assert_allclose(q1.value, np.pi)
assert q1.unit == u.radian
q2 = function(0. * u.degree, 30. * u.arcmin, 0. * u.arcsec)
assert_allclose(q2.value, (30. * u.arcmin).to(u.radian).value)
assert q2.unit == u.radian
q3 = function(0. * u.degree, 0. * u.arcmin, 30. * u.arcsec)
assert_allclose(q3.value, (30. * u.arcsec).to(u.radian).value)
# the following doesn't make much sense in terms of the name of the
# routine, but we check it gives the correct result.
q4 = function(3. * u.radian, 0. * u.arcmin, 0. * u.arcsec)
assert_allclose(q4.value, 3.)
assert q4.unit == u.radian
with pytest.raises(TypeError):
function(3. * u.m, 2. * u.s, 1. * u.kg)
jv_like_ufuncs = (
sps.jv, sps.jn, sps.jve, sps.yn, sps.yv, sps.yve, sps.kn, sps.kv,
sps.kve, sps.iv, sps.ive, sps.hankel1, sps.hankel1e, sps.hankel2,
sps.hankel2e)
@pytest.mark.parametrize('function', jv_like_ufuncs)
def test_jv_scalar(self, function):
q = function(2. * u.m / (2. * u.m), 3. * u.m / (6. * u.m))
assert q.unit == u.dimensionless_unscaled
assert q.value == function(1.0, 0.5)
@pytest.mark.parametrize('function', jv_like_ufuncs)
def test_jv_array(self, function):
q = function(np.ones(3) * u.m / (1. * u.m),
np.array([2., 3., 6.]) * u.m / (6. * u.m))
assert q.unit == u.dimensionless_unscaled
assert np.all(q.value == function(
np.ones(3),
np.array([1. / 3., 1. / 2., 1.]))
)
# should also work on quantities that can be made dimensionless
q2 = function(np.ones(3) * u.m / (1. * u.m),
np.array([2., 3., 6.]) * u.m / (6. * u.cm))
assert q2.unit == u.dimensionless_unscaled
assert_allclose(q2.value,
function(np.ones(3),
np.array([100. / 3., 100. / 2., 100.])))
@pytest.mark.parametrize('function', jv_like_ufuncs)
def test_jv_invalid_units(self, function):
# Can't use jv() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
function(1. * u.kg, 3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply '{0}' function to "
"dimensionless quantities"
.format(function.__name__))
|
48db8b5f37090b97249ac28440f0b7b9a41dd1e8a25dac0b1b32d32221f7cd50 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from ... import units as u
from .py3_test_quantity_annotations import *
# list of pairs (target unit/physical type, input unit)
x_inputs = [(u.arcsec, u.deg), ('angle', u.deg),
(u.kpc/u.Myr, u.km/u.s), ('speed', u.km/u.s),
([u.arcsec, u.km], u.deg), ([u.arcsec, u.km], u.km), # multiple allowed
(['angle', 'length'], u.deg), (['angle', 'length'], u.km)]
y_inputs = [(u.arcsec, u.deg), ('angle', u.deg),
(u.kpc/u.Myr, u.km/u.s), ('speed', u.km/u.s)]
@pytest.fixture(scope="module",
params=list(range(len(x_inputs))))
def x_input(request):
return x_inputs[request.param]
@pytest.fixture(scope="module",
params=list(range(len(y_inputs))))
def y_input(request):
return y_inputs[request.param]
# ---- Tests that use the fixtures defined above ----
def test_args(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, y):
return x, y
x, y = myfunc_args(1*x_unit, 1*y_unit)
assert isinstance(x, u.Quantity)
assert isinstance(y, u.Quantity)
assert x.unit == x_unit
assert y.unit == y_unit
def test_args_nonquantity(x_input):
x_target, x_unit = x_input
@u.quantity_input(x=x_target)
def myfunc_args(x, y):
return x, y
x, y = myfunc_args(1*x_unit, 100)
assert isinstance(x, u.Quantity)
assert isinstance(y, int)
assert x.unit == x_unit
def test_wrong_unit(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, y):
return x, y
with pytest.raises(u.UnitsError) as e:
x, y = myfunc_args(1*x_unit, 100*u.Joule) # has to be an unspecified unit
str_to = str(y_target)
assert str(e.value) == "Argument 'y' to function 'myfunc_args' must be in units convertible to '{0}'.".format(str_to)
def test_not_quantity(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, y):
return x, y
with pytest.raises(TypeError) as e:
x, y = myfunc_args(1*x_unit, 100)
assert str(e.value) == "Argument 'y' to function 'myfunc_args' has no 'unit' attribute. You may want to pass in an astropy Quantity instead."
def test_kwargs(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, my_arg, y=1*y_unit):
return x, my_arg, y
x, my_arg, y = myfunc_args(1*x_unit, 100, y=100*y_unit)
assert isinstance(x, u.Quantity)
assert isinstance(my_arg, int)
assert isinstance(y, u.Quantity)
assert y.unit == y_unit
def test_unused_kwargs(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, my_arg1, y=y_unit, my_arg2=1000):
return x, my_arg1, y, my_arg2
x, my_arg1, y, my_arg2 = myfunc_args(1*x_unit, 100,
y=100*y_unit, my_arg2=10)
assert isinstance(x, u.Quantity)
assert isinstance(my_arg1, int)
assert isinstance(y, u.Quantity)
assert isinstance(my_arg2, int)
assert y.unit == y_unit
assert my_arg2 == 10
def test_kwarg_wrong_unit(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, y=10*y_unit):
return x, y
with pytest.raises(u.UnitsError) as e:
x, y = myfunc_args(1*x_unit, y=100*u.Joule)
str_to = str(y_target)
assert str(e.value) == "Argument 'y' to function 'myfunc_args' must be in units convertible to '{0}'.".format(str_to)
def test_kwarg_not_quantity(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, y=10*y_unit):
return x, y
with pytest.raises(TypeError) as e:
x, y = myfunc_args(1*x_unit, y=100)
assert str(e.value) == "Argument 'y' to function 'myfunc_args' has no 'unit' attribute. You may want to pass in an astropy Quantity instead."
def test_kwarg_default(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, y=10*y_unit):
return x, y
x, y = myfunc_args(1*x_unit)
assert isinstance(x, u.Quantity)
assert isinstance(y, u.Quantity)
assert x.unit == x_unit
assert y.unit == y_unit
def test_kwargs_input(x_input, y_input):
x_target, x_unit = x_input
y_target, y_unit = y_input
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x=1*x_unit, y=1*y_unit):
return x, y
kwargs = {'x': 10*x_unit, 'y': 10*y_unit}
x, y = myfunc_args(**kwargs)
assert isinstance(x, u.Quantity)
assert isinstance(y, u.Quantity)
assert x.unit == x_unit
assert y.unit == y_unit
def test_kwargs_extra(x_input):
x_target, x_unit = x_input
@u.quantity_input(x=x_target)
def myfunc_args(x, **kwargs):
return x
x = myfunc_args(1*x_unit)
assert isinstance(x, u.Quantity)
assert x.unit == x_unit
# ---- Tests that don't used the fixtures ----
@pytest.mark.parametrize("x_unit,y_unit", [
(u.arcsec, u.eV),
('angle', 'energy')])
def test_arg_equivalencies(x_unit, y_unit):
@u.quantity_input(x=x_unit, y=y_unit,
equivalencies=u.mass_energy())
def myfunc_args(x, y):
return x, y+(10*u.J) # Add an energy to check equiv is working
x, y = myfunc_args(1*u.arcsec, 100*u.gram)
assert isinstance(x, u.Quantity)
assert isinstance(y, u.Quantity)
assert x.unit == u.arcsec
assert y.unit == u.gram
@pytest.mark.parametrize("x_unit,energy_unit", [
(u.arcsec, u.eV),
('angle', 'energy')])
def test_kwarg_equivalencies(x_unit, energy_unit):
@u.quantity_input(x=x_unit, energy=energy_unit, equivalencies=u.mass_energy())
def myfunc_args(x, energy=10*u.eV):
return x, energy+(10*u.J) # Add an energy to check equiv is working
x, energy = myfunc_args(1*u.arcsec, 100*u.gram)
assert isinstance(x, u.Quantity)
assert isinstance(energy, u.Quantity)
assert x.unit == u.arcsec
assert energy.unit == u.gram
def test_no_equivalent():
class test_unit:
pass
class test_quantity:
unit = test_unit()
@u.quantity_input(x=u.arcsec)
def myfunc_args(x):
return x
with pytest.raises(TypeError) as e:
x, y = myfunc_args(test_quantity())
assert str(e.value) == "Argument 'x' to function 'myfunc_args' has a 'unit' attribute without an 'is_equivalent' method. You may want to pass in an astropy Quantity instead."
def test_kwarg_invalid_physical_type():
@u.quantity_input(x='angle', y='africanswallow')
def myfunc_args(x, y=10*u.deg):
return x, y
with pytest.raises(ValueError) as e:
x, y = myfunc_args(1*u.arcsec, y=100*u.deg)
assert str(e.value) == "Invalid unit or physical type 'africanswallow'."
def test_default_value_check():
x_target = u.deg
x_unit = u.arcsec
with pytest.raises(TypeError):
@u.quantity_input(x=x_target)
def myfunc_args(x=1.):
return x
x = myfunc_args()
x = myfunc_args(1*x_unit)
assert isinstance(x, u.Quantity)
assert x.unit == x_unit
def test_args_None():
x_target = u.deg
x_unit = u.arcsec
y_target = u.km
y_unit = u.kpc
@u.quantity_input(x=[x_target, None], y=[None, y_target])
def myfunc_args(x, y):
return x, y
x, y = myfunc_args(1*x_unit, None)
assert isinstance(x, u.Quantity)
assert x.unit == x_unit
assert y is None
x, y = myfunc_args(None, 1*y_unit)
assert isinstance(y, u.Quantity)
assert y.unit == y_unit
assert x is None
def test_args_None_kwarg():
x_target = u.deg
x_unit = u.arcsec
y_target = u.km
@u.quantity_input(x=x_target, y=y_target)
def myfunc_args(x, y=None):
return x, y
x, y = myfunc_args(1*x_unit)
assert isinstance(x, u.Quantity)
assert x.unit == x_unit
assert y is None
x, y = myfunc_args(1*x_unit, None)
assert isinstance(x, u.Quantity)
assert x.unit == x_unit
assert y is None
with pytest.raises(TypeError):
x, y = myfunc_args(None, None)
|
7114fa8e896836ad75786219942b114ede1d8e91e32388f95213aa56d1f1243e | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from .. import CompositeUnit, UnitsError, dimensionless_unscaled
from . import magnitude_zero_points as mag0
from .core import FunctionUnitBase, FunctionQuantity
from .units import dex, dB, mag
__all__ = ['LogUnit', 'MagUnit', 'DexUnit', 'DecibelUnit',
'LogQuantity', 'Magnitude', 'Decibel', 'Dex',
'STmag', 'ABmag', 'M_bol', 'm_bol']
class LogUnit(FunctionUnitBase):
"""Logarithmic unit containing a physical one
Usually, logarithmic units are instantiated via specific subclasses
such `MagUnit`, `DecibelUnit`, and `DexUnit`.
Parameters
----------
physical_unit : `~astropy.units.Unit` or `string`
Unit that is encapsulated within the logarithmic function unit.
If not given, dimensionless.
function_unit : `~astropy.units.Unit` or `string`
By default, the same as the logarithmic unit set by the subclass.
"""
# the four essential overrides of FunctionUnitBase
@property
def _default_function_unit(self):
return dex
@property
def _quantity_class(self):
return LogQuantity
def from_physical(self, x):
"""Transformation from value in physical to value in logarithmic units.
Used in equivalency."""
return dex.to(self._function_unit, np.log10(x))
def to_physical(self, x):
"""Transformation from value in logarithmic to value in physical units.
Used in equivalency."""
return 10 ** self._function_unit.to(dex, x)
# ^^^^ the four essential overrides of FunctionUnitBase
# add addition and subtraction, which imply multiplication/division of
# the underlying physical units
def _add_and_adjust_physical_unit(self, other, sign_self, sign_other):
"""Add/subtract LogUnit to/from another unit, and adjust physical unit.
self and other are multiplied by sign_self and sign_other, resp.
We wish to do: ±lu_1 + ±lu_2 -> lu_f (lu=logarithmic unit)
and pu_1^(±1) * pu_2^(±1) -> pu_f (pu=physical unit)
Raises
------
UnitsError
If function units are not equivalent.
"""
# First, insist on compatible logarithmic type. Here, plain u.mag,
# u.dex, and u.dB are OK, i.e., other does not have to be LogUnit
# (this will indirectly test whether other is a unit at all).
try:
getattr(other, 'function_unit', other)._to(self._function_unit)
except AttributeError:
# if other is not a unit (i.e., does not have _to).
return NotImplemented
except UnitsError:
raise UnitsError("Can only add/subtract logarithmic units of"
"of compatible type.")
other_physical_unit = getattr(other, 'physical_unit',
dimensionless_unscaled)
physical_unit = CompositeUnit(
1, [self._physical_unit, other_physical_unit],
[sign_self, sign_other])
return self._copy(physical_unit)
def __neg__(self):
return self._copy(self.physical_unit**(-1))
def __add__(self, other):
# Only know how to add to a logarithmic unit with compatible type,
# be it a plain one (u.mag, etc.,) or another LogUnit
return self._add_and_adjust_physical_unit(other, +1, +1)
def __radd__(self, other):
return self._add_and_adjust_physical_unit(other, +1, +1)
def __sub__(self, other):
return self._add_and_adjust_physical_unit(other, +1, -1)
def __rsub__(self, other):
# here, in normal usage other cannot be LogUnit; only equivalent one
# would be u.mag,u.dB,u.dex. But might as well use common routine.
return self._add_and_adjust_physical_unit(other, -1, +1)
class MagUnit(LogUnit):
"""Logarithmic physical units expressed in magnitudes
Parameters
----------
physical_unit : `~astropy.units.Unit` or `string`
Unit that is encapsulated within the magnitude function unit.
If not given, dimensionless.
function_unit : `~astropy.units.Unit` or `string`
By default, this is ``mag``, but this allows one to use an equivalent
unit such as ``2 mag``.
"""
def __init__(self, *args, **kwargs):
# Ensure we recognize magnitude zero points here.
with mag0.enable():
super().__init__(*args, **kwargs)
@property
def _default_function_unit(self):
return mag
@property
def _quantity_class(self):
return Magnitude
class DexUnit(LogUnit):
"""Logarithmic physical units expressed in magnitudes
Parameters
----------
physical_unit : `~astropy.units.Unit` or `string`
Unit that is encapsulated within the magnitude function unit.
If not given, dimensionless.
function_unit : `~astropy.units.Unit` or `string`
By default, this is ``dex`, but this allows one to use an equivalent
unit such as ``0.5 dex``.
"""
@property
def _default_function_unit(self):
return dex
@property
def _quantity_class(self):
return Dex
class DecibelUnit(LogUnit):
"""Logarithmic physical units expressed in dB
Parameters
----------
physical_unit : `~astropy.units.Unit` or `string`
Unit that is encapsulated within the decibel function unit.
If not given, dimensionless.
function_unit : `~astropy.units.Unit` or `string`
By default, this is ``dB``, but this allows one to use an equivalent
unit such as ``2 dB``.
"""
@property
def _default_function_unit(self):
return dB
@property
def _quantity_class(self):
return Decibel
class LogQuantity(FunctionQuantity):
"""A representation of a (scaled) logarithm of a number with a unit
Parameters
----------
value : number, `~astropy.units.Quantity`, `~astropy.units.function.logarithmic.LogQuantity`, or sequence of convertible items.
The numerical value of the logarithmic quantity. If a number or
a `~astropy.units.Quantity` with a logarithmic unit, it will be
converted to ``unit`` and the physical unit will be inferred from
``unit``. If a `~astropy.units.Quantity` with just a physical unit,
it will converted to the logarithmic unit, after, if necessary,
converting it to the physical unit inferred from ``unit``.
unit : string, `~astropy.units.UnitBase` or `~astropy.units.function.FunctionUnitBase` instance, optional
For an `~astropy.units.function.FunctionUnitBase` instance, the
physical unit will be taken from it; for other input, it will be
inferred from ``value``. By default, ``unit`` is set by the subclass.
dtype : `~numpy.dtype`, optional
The ``dtype`` of the resulting Numpy array or scalar that will
hold the value. If not provided, is is determined automatically
from the input value.
copy : bool, optional
If `True` (default), then the value is copied. Otherwise, a copy will
only be made if ``__array__`` returns a copy, if value is a nested
sequence, or if a copy is needed to satisfy an explicitly given
``dtype``. (The `False` option is intended mostly for internal use,
to speed up initialization where a copy is known to have been made.
Use with care.)
Examples
--------
Typically, use is made of an `~astropy.units.function.FunctionQuantity`
subclass, as in::
>>> import astropy.units as u
>>> u.Magnitude(-2.5)
<Magnitude -2.5 mag>
>>> u.Magnitude(10.*u.count/u.second)
<Magnitude -2.5 mag(ct / s)>
>>> u.Decibel(1.*u.W, u.DecibelUnit(u.mW)) # doctest: +FLOAT_CMP
<Decibel 30. dB(mW)>
"""
# only override of FunctionQuantity
_unit_class = LogUnit
# additions that work just for logarithmic units
def __add__(self, other):
# Add function units, thus multiplying physical units. If no unit is
# given, assume dimensionless_unscaled; this will give the appropriate
# exception in LogUnit.__add__.
new_unit = self.unit + getattr(other, 'unit', dimensionless_unscaled)
# Add actual logarithmic values, rescaling, e.g., dB -> dex.
result = self._function_view + getattr(other, '_function_view', other)
return self._new_view(result, new_unit)
def __radd__(self, other):
return self.__add__(other)
def __iadd__(self, other):
new_unit = self.unit + getattr(other, 'unit', dimensionless_unscaled)
# Do calculation in-place using _function_view of array.
function_view = self._function_view
function_view += getattr(other, '_function_view', other)
self._set_unit(new_unit)
return self
def __sub__(self, other):
# Subtract function units, thus dividing physical units.
new_unit = self.unit - getattr(other, 'unit', dimensionless_unscaled)
# Subtract actual logarithmic values, rescaling, e.g., dB -> dex.
result = self._function_view - getattr(other, '_function_view', other)
return self._new_view(result, new_unit)
def __rsub__(self, other):
new_unit = self.unit.__rsub__(
getattr(other, 'unit', dimensionless_unscaled))
result = self._function_view.__rsub__(
getattr(other, '_function_view', other))
# Ensure the result is in right function unit scale
# (with rsub, this does not have to be one's own).
result = result.to(new_unit.function_unit)
return self._new_view(result, new_unit)
def __isub__(self, other):
new_unit = self.unit - getattr(other, 'unit', dimensionless_unscaled)
# Do calculation in-place using _function_view of array.
function_view = self._function_view
function_view -= getattr(other, '_function_view', other)
self._set_unit(new_unit)
return self
# Could add __mul__ and __div__ and try interpreting other as a power,
# but this seems just too error-prone.
# Methods that do not work for function units generally but are OK for
# logarithmic units as they imply differences and independence of
# physical unit.
def var(self, axis=None, dtype=None, out=None, ddof=0):
return self._wrap_function(np.var, axis, dtype, out=out, ddof=ddof,
unit=self.unit.function_unit**2)
def std(self, axis=None, dtype=None, out=None, ddof=0):
return self._wrap_function(np.std, axis, dtype, out=out, ddof=ddof,
unit=self.unit._copy(dimensionless_unscaled))
def ptp(self, axis=None, out=None):
return self._wrap_function(np.ptp, axis, out=out,
unit=self.unit._copy(dimensionless_unscaled))
def diff(self, n=1, axis=-1):
return self._wrap_function(np.diff, n, axis,
unit=self.unit._copy(dimensionless_unscaled))
def ediff1d(self, to_end=None, to_begin=None):
return self._wrap_function(np.ediff1d, to_end, to_begin,
unit=self.unit._copy(dimensionless_unscaled))
_supported_functions = (FunctionQuantity._supported_functions |
set(getattr(np, function) for function in
('var', 'std', 'ptp', 'diff', 'ediff1d')))
class Dex(LogQuantity):
_unit_class = DexUnit
class Decibel(LogQuantity):
_unit_class = DecibelUnit
class Magnitude(LogQuantity):
_unit_class = MagUnit
dex._function_unit_class = DexUnit
dB._function_unit_class = DecibelUnit
mag._function_unit_class = MagUnit
STmag = MagUnit(mag0.ST)
STmag.__doc__ = "ST magnitude: STmag=-21.1 corresponds to 1 erg/s/cm2/A"
ABmag = MagUnit(mag0.AB)
ABmag.__doc__ = "AB magnitude: ABmag=-48.6 corresponds to 1 erg/s/cm2/Hz"
M_bol = MagUnit(mag0.Bol)
M_bol.__doc__ = ("Absolute bolometric magnitude: M_bol=0 corresponds to "
"L_bol0={0}".format(mag0.Bol.si))
m_bol = MagUnit(mag0.bol)
m_bol.__doc__ = ("Apparent bolometric magnitude: m_bol=0 corresponds to "
"f_bol0={0}".format(mag0.bol.si))
|
d04cf34218f1a7ff4bf7c66097a5e46a9c6f68a6568225bfeb29059ceb8ecf30 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Function Units and Quantities."""
from abc import ABCMeta, abstractmethod
import numpy as np
from .. import (Unit, UnitBase, UnitsError, UnitTypeError,
dimensionless_unscaled, Quantity)
__all__ = ['FunctionUnitBase', 'FunctionQuantity']
SUPPORTED_UFUNCS = set(getattr(np.core.umath, ufunc) for ufunc in (
'isfinite', 'isinf', 'isnan', 'sign', 'signbit',
'rint', 'floor', 'ceil', 'trunc', 'power',
'_ones_like', 'ones_like', 'positive') if hasattr(np.core.umath, ufunc))
# TODO: the following could work if helper changed relative to Quantity:
# - spacing should return dimensionless, not same unit
# - negative should negate unit too,
# - add, subtract, comparisons can work if units added/subtracted
SUPPORTED_FUNCTIONS = set(getattr(np, function) for function in
('clip', 'trace', 'mean', 'min', 'max', 'round'))
# subclassing UnitBase or CompositeUnit was found to be problematic, requiring
# a large number of overrides. Hence, define new class.
class FunctionUnitBase(metaclass=ABCMeta):
"""Abstract base class for function units.
Function units are functions containing a physical unit, such as dB(mW).
Most of the arithmetic operations on function units are defined in this
base class.
While instantiation is defined, this class should not be used directly.
Rather, subclasses should be used that override the abstract properties
`_default_function_unit` and `_quantity_class`, and the abstract methods
`from_physical`, and `to_physical`.
Parameters
----------
physical_unit : `~astropy.units.Unit` or `string`
Unit that is encapsulated within the function unit.
If not given, dimensionless.
function_unit : `~astropy.units.Unit` or `string`
By default, the same as the function unit set by the subclass.
"""
# ↓↓↓ the following four need to be set by subclasses
# Make this a property so we can ensure subclasses define it.
@property
@abstractmethod
def _default_function_unit(self):
"""Default function unit corresponding to the function.
This property should be overridden by subclasses, with, e.g.,
`~astropy.unit.MagUnit` returning `~astropy.unit.mag`.
"""
# This has to be a property because the function quantity will not be
# known at unit definition time, as it gets defined after.
@property
@abstractmethod
def _quantity_class(self):
"""Function quantity class corresponding to this function unit.
This property should be overridden by subclasses, with, e.g.,
`~astropy.unit.MagUnit` returning `~astropy.unit.Magnitude`.
"""
@abstractmethod
def from_physical(self, x):
"""Transformation from value in physical to value in function units.
This method should be overridden by subclasses. It is used to
provide automatic transformations using an equivalency.
"""
@abstractmethod
def to_physical(self, x):
"""Transformation from value in function to value in physical units.
This method should be overridden by subclasses. It is used to
provide automatic transformations using an equivalency.
"""
# ↑↑↑ the above four need to be set by subclasses
# have priority over arrays, regular units, and regular quantities
__array_priority__ = 30000
def __init__(self, physical_unit=None, function_unit=None):
if physical_unit is None:
self._physical_unit = dimensionless_unscaled
else:
self._physical_unit = Unit(physical_unit)
if (not isinstance(self._physical_unit, UnitBase) or
self._physical_unit.is_equivalent(
self._default_function_unit)):
raise ValueError("Unit {0} is not a physical unit."
.format(self._physical_unit))
if function_unit is None:
self._function_unit = self._default_function_unit
else:
# any function unit should be equivalent to subclass default
function_unit = Unit(getattr(function_unit, 'function_unit',
function_unit))
if function_unit.is_equivalent(self._default_function_unit):
self._function_unit = function_unit
else:
raise ValueError("Cannot initialize '{0}' instance with "
"function unit '{1}', as it is not "
"equivalent to default function unit '{2}'."
.format(self.__class__.__name__,
function_unit,
self._default_function_unit))
def _copy(self, physical_unit=None):
"""Copy oneself, possibly with a different physical unit."""
if physical_unit is None:
physical_unit = self.physical_unit
return self.__class__(physical_unit, self.function_unit)
@property
def physical_unit(self):
return self._physical_unit
@property
def function_unit(self):
return self._function_unit
@property
def equivalencies(self):
"""List of equivalencies between function and physical units.
Uses the `from_physical` and `to_physical` methods.
"""
return [(self, self.physical_unit,
self.to_physical, self.from_physical)]
# ↓↓↓ properties/methods required to behave like a unit
def decompose(self, bases=set()):
"""Copy the current unit with the physical unit decomposed.
For details, see `~astropy.units.UnitBase.decompose`.
"""
return self._copy(self.physical_unit.decompose(bases))
@property
def si(self):
"""Copy the current function unit with the physical unit in SI."""
return self._copy(self.physical_unit.si)
@property
def cgs(self):
"""Copy the current function unit with the physical unit in CGS."""
return self._copy(self.physical_unit.cgs)
def _get_physical_type_id(self):
"""Get physical type corresponding to physical unit."""
return self.physical_unit._get_physical_type_id()
@property
def physical_type(self):
"""Return the physical type of the physical unit (e.g., 'length')."""
return self.physical_unit.physical_type
def is_equivalent(self, other, equivalencies=[]):
"""
Returns `True` if this unit is equivalent to ``other``.
Parameters
----------
other : unit object or string or tuple
The unit to convert to. If a tuple of units is specified, this
method returns true if the unit matches any of those in the tuple.
equivalencies : list of equivalence pairs, optional
A list of equivalence pairs to try if the units are not
directly convertible. See :ref:`unit_equivalencies`.
This list is in addition to the built-in equivalencies between the
function unit and the physical one, as well as possible global
defaults set by, e.g., `~astropy.units.set_enabled_equivalencies`.
Use `None` to turn off any global equivalencies.
Returns
-------
bool
"""
if isinstance(other, tuple):
return any(self.is_equivalent(u, equivalencies=equivalencies)
for u in other)
other_physical_unit = getattr(other, 'physical_unit', (
dimensionless_unscaled if self.function_unit.is_equivalent(other)
else other))
return self.physical_unit.is_equivalent(other_physical_unit,
equivalencies)
def to(self, other, value=1., equivalencies=[]):
"""
Return the converted values in the specified unit.
Parameters
----------
other : `~astropy.units.Unit` object, `~astropy.units.function.FunctionUnitBase` object or string
The unit to convert to.
value : scalar int or float, or sequence convertible to array, optional
Value(s) in the current unit to be converted to the specified unit.
If not provided, defaults to 1.0.
equivalencies : list of equivalence pairs, optional
A list of equivalence pairs to try if the units are not
directly convertible. See :ref:`unit_equivalencies`.
This list is in meant to treat only equivalencies between different
physical units; the build-in equivalency between the function
unit and the physical one is automatically taken into account.
Returns
-------
values : scalar or array
Converted value(s). Input value sequences are returned as
numpy arrays.
Raises
------
UnitsError
If units are inconsistent.
"""
# conversion to one's own physical unit should be fastest
if other is self.physical_unit:
return self.to_physical(value)
other_function_unit = getattr(other, 'function_unit', other)
if self.function_unit.is_equivalent(other_function_unit):
# when other is an equivalent function unit:
# first convert physical units to other's physical units
other_physical_unit = getattr(other, 'physical_unit',
dimensionless_unscaled)
if self.physical_unit != other_physical_unit:
value_other_physical = self.physical_unit.to(
other_physical_unit, self.to_physical(value),
equivalencies)
# make function unit again, in own system
value = self.from_physical(value_other_physical)
# convert possible difference in function unit (e.g., dex->dB)
return self.function_unit.to(other_function_unit, value)
else:
# when other is not a function unit
return self.physical_unit.to(other, self.to_physical(value),
equivalencies)
def is_unity(self):
return False
def __eq__(self, other):
return (self.physical_unit == getattr(other, 'physical_unit',
dimensionless_unscaled) and
self.function_unit == getattr(other, 'function_unit', other))
def __ne__(self, other):
return not self.__eq__(other)
def __mul__(self, other):
if isinstance(other, (str, UnitBase, FunctionUnitBase)):
if self.physical_unit == dimensionless_unscaled:
# If dimensionless, drop back to normal unit and retry.
return self.function_unit * other
else:
raise UnitsError("Cannot multiply a function unit "
"with a physical dimension with any unit.")
else:
# Anything not like a unit, try initialising as a function quantity.
try:
return self._quantity_class(other, unit=self)
except Exception:
return NotImplemented
def __rmul__(self, other):
return self.__mul__(other)
def __div__(self, other):
if isinstance(other, (str, UnitBase, FunctionUnitBase)):
if self.physical_unit == dimensionless_unscaled:
# If dimensionless, drop back to normal unit and retry.
return self.function_unit / other
else:
raise UnitsError("Cannot divide a function unit "
"with a physical dimension by any unit.")
else:
# Anything not like a unit, try initialising as a function quantity.
try:
return self._quantity_class(1./other, unit=self)
except Exception:
return NotImplemented
def __rdiv__(self, other):
if isinstance(other, (str, UnitBase, FunctionUnitBase)):
if self.physical_unit == dimensionless_unscaled:
# If dimensionless, drop back to normal unit and retry.
return other / self.function_unit
else:
raise UnitsError("Cannot divide a function unit "
"with a physical dimension into any unit")
else:
# Don't know what to do with anything not like a unit.
return NotImplemented
__truediv__ = __div__
__rtruediv__ = __rdiv__
def __pow__(self, power):
if power == 0:
return dimensionless_unscaled
elif power == 1:
return self._copy()
if self.physical_unit == dimensionless_unscaled:
return self.function_unit ** power
raise UnitsError("Cannot raise a function unit "
"with a physical dimension to any power but 0 or 1.")
def __pos__(self):
return self._copy()
def to_string(self, format='generic'):
"""
Output the unit in the given format as a string.
The physical unit is appended, within parentheses, to the function
unit, as in "dB(mW)", with both units set using the given format
Parameters
----------
format : `astropy.units.format.Base` instance or str
The name of a format or a formatter object. If not
provided, defaults to the generic format.
"""
if format not in ('generic', 'unscaled', 'latex'):
raise ValueError("Function units cannot be written in {0} format. "
"Only 'generic', 'unscaled' and 'latex' are "
"supported.".format(format))
self_str = self.function_unit.to_string(format)
pu_str = self.physical_unit.to_string(format)
if pu_str == '':
pu_str = '1'
if format == 'latex':
self_str += r'$\mathrm{{\left( {0} \right)}}$'.format(
pu_str[1:-1]) # need to strip leading and trailing "$"
else:
self_str += '({0})'.format(pu_str)
return self_str
def __str__(self):
"""Return string representation for unit."""
self_str = str(self.function_unit)
pu_str = str(self.physical_unit)
if pu_str:
self_str += '({0})'.format(pu_str)
return self_str
def __repr__(self):
# By default, try to give a representation using `Unit(<string>)`,
# with string such that parsing it would give the correct FunctionUnit.
if callable(self.function_unit):
return 'Unit("{0}")'.format(self.to_string())
else:
return '{0}("{1}"{2})'.format(
self.__class__.__name__, self.physical_unit,
"" if self.function_unit is self._default_function_unit
else ', unit="{0}"'.format(self.function_unit))
def _repr_latex_(self):
"""
Generate latex representation of unit name. This is used by
the IPython notebook to print a unit with a nice layout.
Returns
-------
Latex string
"""
return self.to_string('latex')
def __hash__(self):
return hash((self.function_unit, self.physical_unit))
class FunctionQuantity(Quantity):
"""A representation of a (scaled) function of a number with a unit.
Function quantities are quantities whose units are functions containing a
physical unit, such as dB(mW). Most of the arithmetic operations on
function quantities are defined in this base class.
While instantiation is also defined here, this class should not be
instantiated directly. Rather, subclasses should be made which have
``_unit_class`` pointing back to the corresponding function unit class.
Parameters
----------
value : number, sequence of convertible items, `~astropy.units.Quantity`, or `~astropy.units.function.FunctionQuantity`
The numerical value of the function quantity. If a number or
a `~astropy.units.Quantity` with a function unit, it will be converted
to ``unit`` and the physical unit will be inferred from ``unit``.
If a `~astropy.units.Quantity` with just a physical unit, it will
converted to the function unit, after, if necessary, converting it to
the physical unit inferred from ``unit``.
unit : string, `~astropy.units.UnitBase` or `~astropy.units.function.FunctionUnitBase` instance, optional
For an `~astropy.units.function.FunctionUnitBase` instance, the
physical unit will be taken from it; for other input, it will be
inferred from ``value``. By default, ``unit`` is set by the subclass.
dtype : `~numpy.dtype`, optional
The dtype of the resulting Numpy array or scalar that will
hold the value. If not provided, it is determined from the input,
except that any input that cannot represent float (integer and bool)
is converted to float.
copy : bool, optional
If `True` (default), then the value is copied. Otherwise, a copy will
only be made if ``__array__`` returns a copy, if value is a nested
sequence, or if a copy is needed to satisfy an explicitly given
``dtype``. (The `False` option is intended mostly for internal use,
to speed up initialization where a copy is known to have been made.
Use with care.)
order : {'C', 'F', 'A'}, optional
Specify the order of the array. As in `~numpy.array`. Ignored
if the input does not need to be converted and ``copy=False``.
subok : bool, optional
If `False` (default), the returned array will be forced to be of the
class used. Otherwise, subclasses will be passed through.
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting array
should have. Ones will be pre-pended to the shape as needed to meet
this requirement. This parameter is ignored if the input is a
`~astropy.units.Quantity` and ``copy=False``.
Raises
------
TypeError
If the value provided is not a Python numeric type.
TypeError
If the unit provided is not a `~astropy.units.function.FunctionUnitBase`
or `~astropy.units.Unit` object, or a parseable string unit.
"""
_unit_class = None
"""Default `~astropy.units.function.FunctionUnitBase` subclass.
This should be overridden by subclasses.
"""
# Ensure priority over ndarray, regular Unit & Quantity, and FunctionUnit.
__array_priority__ = 40000
# Define functions that work on FunctionQuantity.
_supported_ufuncs = SUPPORTED_UFUNCS
_supported_functions = SUPPORTED_FUNCTIONS
def __new__(cls, value, unit=None, dtype=None, copy=True, order=None,
subok=False, ndmin=0):
if unit is not None:
# Convert possible string input to a (function) unit.
unit = Unit(unit)
if not isinstance(unit, FunctionUnitBase):
# By default, use value's physical unit.
value_unit = getattr(value, 'unit', None)
if value_unit is None:
# if iterable, see if first item has a unit
# (mixed lists fail in super call below).
try:
value_unit = getattr(value[0], 'unit')
except Exception:
pass
physical_unit = getattr(value_unit, 'physical_unit', value_unit)
unit = cls._unit_class(physical_unit, function_unit=unit)
# initialise!
return super().__new__(cls, value, unit, dtype=dtype, copy=copy,
order=order, subok=subok, ndmin=ndmin)
# ↓↓↓ properties not found in Quantity
@property
def physical(self):
"""The physical quantity corresponding the function one."""
return self.to(self.unit.physical_unit)
@property
def _function_view(self):
"""View as Quantity with function unit, dropping the physical unit.
Use `~astropy.units.quantity.Quantity.value` for just the value.
"""
return self._new_view(unit=self.unit.function_unit)
# ↓↓↓ methods overridden to change the behaviour
@property
def si(self):
"""Return a copy with the physical unit in SI units."""
return self.__class__(self.physical.si)
@property
def cgs(self):
"""Return a copy with the physical unit in CGS units."""
return self.__class__(self.physical.cgs)
def decompose(self, bases=[]):
"""Generate a new `FunctionQuantity` with the physical unit decomposed.
For details, see `~astropy.units.Quantity.decompose`.
"""
return self.__class__(self.physical.decompose(bases))
# ↓↓↓ methods overridden to add additional behaviour
def __array_prepare__(self, obj, context=None):
"""Check that the ufunc can deal with a FunctionQuantity."""
# If no context is set, just return the input
if context is None: # pragma: no cover
return obj
# Find out whether ufunc is supported
function = context[0]
if not (function in self._supported_ufuncs or
all(arg.unit.physical_unit == dimensionless_unscaled
for arg in context[1][:function.nin]
if (hasattr(arg, 'unit') and
hasattr(arg.unit, 'physical_unit')))):
raise UnitTypeError("Cannot use function '{0}' with function "
"quantities that are not dimensionless."
.format(context[0].__name__))
return super().__array_prepare__(obj, context)
def __quantity_subclass__(self, unit):
if isinstance(unit, FunctionUnitBase):
return self.__class__, True
else:
return super().__quantity_subclass__(unit)[0], False
def _set_unit(self, unit):
if not isinstance(unit, self._unit_class):
# Have to take care of, e.g., (10*u.mag).view(u.Magnitude)
try:
# "or 'nonsense'" ensures `None` breaks, just in case.
unit = self._unit_class(function_unit=unit or 'nonsense')
except Exception:
raise UnitTypeError(
"{0} instances require {1} function units"
.format(type(self).__name__, self._unit_class.__name__) +
", so cannot set it to '{0}'.".format(unit))
self._unit = unit
# ↓↓↓ methods overridden to change behaviour
def __mul__(self, other):
if self.unit.physical_unit == dimensionless_unscaled:
return self._function_view * other
raise UnitTypeError("Cannot multiply function quantities which "
"are not dimensionless with anything.")
def __truediv__(self, other):
if self.unit.physical_unit == dimensionless_unscaled:
return self._function_view / other
raise UnitTypeError("Cannot divide function quantities which "
"are not dimensionless by anything.")
def __rtruediv__(self, other):
if self.unit.physical_unit == dimensionless_unscaled:
return self._function_view.__rdiv__(other)
raise UnitTypeError("Cannot divide function quantities which "
"are not dimensionless into anything.")
def _comparison(self, other, comparison_func):
"""Do a comparison between self and other, raising UnitsError when
other cannot be converted to self because it has different physical
unit, and returning NotImplemented when there are other errors."""
try:
# will raise a UnitsError if physical units not equivalent
other_in_own_unit = self._to_own_unit(other, check_precision=False)
except UnitsError as exc:
if self.unit.physical_unit != dimensionless_unscaled:
raise exc
try:
other_in_own_unit = self._function_view._to_own_unit(
other, check_precision=False)
except Exception:
raise exc
except Exception:
return NotImplemented
return comparison_func(other_in_own_unit)
def __eq__(self, other):
try:
return self._comparison(other, self.value.__eq__)
except UnitsError:
return False
def __ne__(self, other):
try:
return self._comparison(other, self.value.__ne__)
except UnitsError:
return True
def __gt__(self, other):
return self._comparison(other, self.value.__gt__)
def __ge__(self, other):
return self._comparison(other, self.value.__ge__)
def __lt__(self, other):
return self._comparison(other, self.value.__lt__)
def __le__(self, other):
return self._comparison(other, self.value.__le__)
# Ensure Quantity methods are used only if they make sense.
def _wrap_function(self, function, *args, **kwargs):
if function in self._supported_functions:
return super()._wrap_function(function, *args, **kwargs)
# For dimensionless, we can convert to regular quantities.
if all(arg.unit.physical_unit == dimensionless_unscaled
for arg in (self,) + args
if (hasattr(arg, 'unit') and
hasattr(arg.unit, 'physical_unit'))):
args = tuple(getattr(arg, '_function_view', arg) for arg in args)
return self._function_view._wrap_function(function, *args, **kwargs)
raise TypeError("Cannot use method that uses function '{0}' with "
"function quantities that are not dimensionless."
.format(function.__name__))
|
81e5ed5bb926e319331a891a486371d1b6cf04525260b0327e5b36554b6fec56 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains classes and functions for defining and converting
between different function units and quantities, i.e., using units which
are some function of a physical unit, such as magnitudes and decibels.
"""
from .core import *
from .logarithmic import *
from .units import *
|
3a7e8ec5be0f7400cb3736b590907a54110e401adaf533b210abfaf47a50367e | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package defines magnitude zero points. By default, they are used to
define corresponding magnitudes, but not enabled as regular physical units.
To enable them, do::
>>> from astropy.units import magnitude_zero_points
>>> magnitude_zero_points.enable() # doctest: +SKIP
"""
import numpy as _numpy
from ..core import UnitBase, def_unit
from ...constants import si as _si
from .. import si, astrophys
_ns = globals()
def_unit(['Bol', 'L_bol'], _si.L_bol0, namespace=_ns, prefixes=False,
doc="Luminosity corresponding to absolute bolometric magnitude zero")
def_unit(['bol', 'f_bol'], _si.L_bol0 / (4 * _numpy.pi * (10.*astrophys.pc)**2),
namespace=_ns, prefixes=False, doc="Irradiance corresponding to "
"appparent bolometric magnitude zero")
def_unit(['AB'], 10.**(-0.4*48.6) * 1.e-3 * si.W / si.m**2 / si.Hz,
namespace=_ns, prefixes=False,
doc="AB magnitude zero flux density.")
def_unit(['ST'], 10.**(-0.4*21.1) * 1.e-3 * si.W / si.m**2 / si.AA,
namespace=_ns, prefixes=False,
doc="ST magnitude zero flux density.")
###########################################################################
# CLEANUP
del UnitBase
del def_unit
del si
del astrophys
###########################################################################
# DOCSTRING
# This generates a docstring for this module that describes all of the
# standard units defined here.
from ..utils import generate_unit_summary as _generate_unit_summary
if __doc__ is not None:
__doc__ += _generate_unit_summary(globals())
def enable():
"""
Enable magnitude zero point units so they appear in results of
`~astropy.units.UnitBase.find_equivalent_units` and
`~astropy.units.UnitBase.compose`.
This may be used with the ``with`` statement to enable these
units only temporarily.
"""
# Local import to avoid cyclical import
from ..core import add_enabled_units
# Local import to avoid polluting namespace
import inspect
return add_enabled_units(inspect.getmodule(enable))
|
bc1bdd1309a8b919efef3473bdf2ce42f4a2b2d8a026253f8212f725c83c89f6 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package defines units that can also be used as functions of other units.
If called, their arguments are used to initialize the corresponding function
unit (e.g., ``u.mag(u.ct/u.s)``). Note that the prefixed versions cannot be
called, as it would be unclear what, e.g., ``u.mmag(u.ct/u.s)`` would mean.
"""
from ..core import _add_prefixes
from .mixin import RegularFunctionUnit, IrreducibleFunctionUnit
_ns = globals()
###########################################################################
# Logarithmic units
# These calls are what core.def_unit would do, but we need to use the callable
# unit versions. The actual function unit classes get added in logarithmic.
dex = IrreducibleFunctionUnit(['dex'], namespace=_ns,
doc="Dex: Base 10 logarithmic unit")
dB = RegularFunctionUnit(['dB', 'decibel'], 0.1 * dex, namespace=_ns,
doc="Decibel: ten per base 10 logarithmic unit")
mag = RegularFunctionUnit(['mag'], -0.4 * dex, namespace=_ns,
doc=("Astronomical magnitude: "
"-2.5 per base 10 logarithmic unit"))
_add_prefixes(mag, namespace=_ns, prefixes=True)
###########################################################################
# CLEANUP
del RegularFunctionUnit
del IrreducibleFunctionUnit
###########################################################################
# DOCSTRING
# This generates a docstring for this module that describes all of the
# standard units defined here.
from ..utils import generate_unit_summary as _generate_unit_summary
if __doc__ is not None:
__doc__ += _generate_unit_summary(globals())
|
10fa5f2866135a8e8312b9530490a00f68e8482fb4b4df89f391c15fbac75fdf | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ..core import IrreducibleUnit, Unit
class FunctionMixin:
"""Mixin class that makes UnitBase subclasses callable.
Provides a __call__ method that passes on arguments to a FunctionUnit.
Instances of this class should define ``_function_unit_class`` pointing
to the relevant class.
See units.py and logarithmic.py for usage.
"""
def __call__(self, unit=None):
return self._function_unit_class(physical_unit=unit,
function_unit=self)
class IrreducibleFunctionUnit(FunctionMixin, IrreducibleUnit):
pass
class RegularFunctionUnit(FunctionMixin, Unit):
pass
|
fc6782acbaf6359c5cc2703c98ca5ac088a9713ebb82c49b4e6b9bd583b04831 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
import numpy as np
from ... import units as u
from ...utils.decorators import format_doc
from ...utils.exceptions import AstropyDeprecationWarning
from ..angles import Angle
from ..matrix_utilities import rotation_matrix, matrix_product, matrix_transpose
from .. import representation as r
from ..baseframe import (BaseCoordinateFrame, frame_transform_graph,
RepresentationMapping, base_doc)
from ..attributes import (Attribute, CoordinateAttribute,
QuantityAttribute,
DifferentialAttribute)
from ..transformations import AffineTransform
from ..errors import ConvertError
from .icrs import ICRS
__all__ = ['Galactocentric']
# Measured by minimizing the difference between a plane of coordinates along
# l=0, b=[-90,90] and the Galactocentric x-z plane
# This is not used directly, but accessed via `get_roll0`. We define it here to
# prevent having to create new Angle objects every time `get_roll0` is called.
_ROLL0 = Angle(58.5986320306*u.degree)
doc_components = """
x : `~astropy.units.Quantity`, optional
Cartesian, Galactocentric :math:`x` position component.
y : `~astropy.units.Quantity`, optional
Cartesian, Galactocentric :math:`y` position component.
z : `~astropy.units.Quantity`, optional
Cartesian, Galactocentric :math:`z` position component.
v_x : `~astropy.units.Quantity`, optional
Cartesian, Galactocentric :math:`v_x` velocity component.
v_y : `~astropy.units.Quantity`, optional
Cartesian, Galactocentric :math:`v_y` velocity component.
v_z : `~astropy.units.Quantity`, optional
Cartesian, Galactocentric :math:`v_z` velocity component.
"""
doc_footer = """
Other parameters
----------------
galcen_coord : `ICRS`, optional, must be keyword
The ICRS coordinates of the Galactic center.
galcen_distance : `~astropy.units.Quantity`, optional, must be keyword
The distance from the sun to the Galactic center.
galcen_v_sun : `~astropy.coordinates.representation.CartesianDifferential`, optional, must be keyword
The velocity of the sun *in the Galactocentric frame* as Cartesian
velocity components.
z_sun : `~astropy.units.Quantity`, optional, must be keyword
The distance from the sun to the Galactic midplane.
roll : `Angle`, optional, must be keyword
The angle to rotate about the final x-axis, relative to the
orientation for Galactic. For example, if this roll angle is 0,
the final x-z plane will align with the Galactic coordinates x-z
plane. Unless you really know what this means, you probably should
not change this!
Examples
--------
To transform to the Galactocentric frame with the default
frame attributes, pass the uninstantiated class name to the
``transform_to()`` method of a coordinate frame or
`~astropy.coordinates.SkyCoord` object::
>>> import astropy.units as u
>>> import astropy.coordinates as coord
>>> c = coord.ICRS(ra=[158.3122, 24.5] * u.degree,
... dec=[-17.3, 81.52] * u.degree,
... distance=[11.5, 24.12] * u.kpc)
>>> c.transform_to(coord.Galactocentric) # doctest: +FLOAT_CMP
<Galactocentric Coordinate (galcen_coord=<ICRS Coordinate: (ra, dec) in deg
( 266.4051, -28.936175)>, galcen_distance=8.3 kpc, galcen_v_sun=( 11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg): (x, y, z) in kpc
[( -9.6083819 , -9.40062188, 6.52056066),
(-21.28302307, 18.76334013, 7.84693855)]>
To specify a custom set of parameters, you have to include extra keyword
arguments when initializing the Galactocentric frame object::
>>> c.transform_to(coord.Galactocentric(galcen_distance=8.1*u.kpc)) # doctest: +FLOAT_CMP
<Galactocentric Coordinate (galcen_coord=<ICRS Coordinate: (ra, dec) in deg
( 266.4051, -28.936175)>, galcen_distance=8.1 kpc, galcen_v_sun=( 11.1, 232.24, 7.25) km / s, z_sun=27.0 pc, roll=0.0 deg): (x, y, z) in kpc
[( -9.40785924, -9.40062188, 6.52066574),
(-21.08239383, 18.76334013, 7.84798135)]>
Similarly, transforming from the Galactocentric frame to another coordinate frame::
>>> c = coord.Galactocentric(x=[-8.3, 4.5] * u.kpc,
... y=[0., 81.52] * u.kpc,
... z=[0.027, 24.12] * u.kpc)
>>> c.transform_to(coord.ICRS) # doctest: +FLOAT_CMP
<ICRS Coordinate: (ra, dec, distance) in (deg, deg, kpc)
[( 86.22349059, 28.83894138, 4.39157788e-05),
( 289.66802652, 49.88763881, 8.59640735e+01)]>
Or, with custom specification of the Galactic center::
>>> c = coord.Galactocentric(x=[-8.0, 4.5] * u.kpc,
... y=[0., 81.52] * u.kpc,
... z=[21.0, 24120.0] * u.pc,
... z_sun=21 * u.pc, galcen_distance=8. * u.kpc)
>>> c.transform_to(coord.ICRS) # doctest: +FLOAT_CMP
<ICRS Coordinate: (ra, dec, distance) in (deg, deg, kpc)
[( 86.2585249 , 28.85773187, 2.75625475e-05),
( 289.77285255, 50.06290457, 8.59216010e+01)]>
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer)
class Galactocentric(BaseCoordinateFrame):
r"""
A coordinate or frame in the Galactocentric system. This frame
requires specifying the Sun-Galactic center distance, and optionally
the height of the Sun above the Galactic midplane.
The position of the Sun is assumed to be on the x axis of the final,
right-handed system. That is, the x axis points from the position of
the Sun projected to the Galactic midplane to the Galactic center --
roughly towards :math:`(l,b) = (0^\circ,0^\circ)`. For the default
transformation (:math:`{\rm roll}=0^\circ`), the y axis points roughly
towards Galactic longitude :math:`l=90^\circ`, and the z axis points
roughly towards the North Galactic Pole (:math:`b=90^\circ`).
The default position of the Galactic Center in ICRS coordinates is
taken from Reid et al. 2004,
http://adsabs.harvard.edu/abs/2004ApJ...616..872R.
.. math::
{\rm RA} = 17:45:37.224~{\rm hr}\\
{\rm Dec} = -28:56:10.23~{\rm deg}
The default distance to the Galactic Center is 8.3 kpc, e.g.,
Gillessen et al. (2009),
https://ui.adsabs.harvard.edu/#abs/2009ApJ...692.1075G/abstract
The default height of the Sun above the Galactic midplane is taken to
be 27 pc, as measured by Chen et al. (2001),
https://ui.adsabs.harvard.edu/#abs/2001ApJ...553..184C/abstract
The default solar motion relative to the Galactic center is taken from a
combination of Schönrich et al. (2010) [for the peculiar velocity] and
Bovy (2015) [for the circular velocity at the solar radius],
https://ui.adsabs.harvard.edu/#abs/2010MNRAS.403.1829S/abstract
https://ui.adsabs.harvard.edu/#abs/2015ApJS..216...29B/abstract
For a more detailed look at the math behind this transformation, see
the document :ref:`coordinates-galactocentric`.
The frame attributes are listed under **Other Parameters**.
"""
default_representation = r.CartesianRepresentation
default_differential = r.CartesianDifferential
# frame attributes
galcen_coord = CoordinateAttribute(default=ICRS(ra=266.4051*u.degree,
dec=-28.936175*u.degree),
frame=ICRS)
galcen_distance = QuantityAttribute(default=8.3*u.kpc)
galcen_v_sun = DifferentialAttribute(
default=r.CartesianDifferential([11.1, 220+12.24, 7.25] * u.km/u.s),
allowed_classes=[r.CartesianDifferential])
z_sun = QuantityAttribute(default=27.*u.pc)
roll = QuantityAttribute(default=0.*u.deg)
def __init__(self, *args, **kwargs):
# backwards-compatibility
if ('galcen_ra' in kwargs or 'galcen_dec' in kwargs):
warnings.warn("The arguments 'galcen_ra', and 'galcen_dec' are "
"deprecated in favor of specifying the sky coordinate"
" as a CoordinateAttribute using the 'galcen_coord' "
"argument", AstropyDeprecationWarning)
galcen_kw = dict()
galcen_kw['ra'] = kwargs.pop('galcen_ra', self.galcen_coord.ra)
galcen_kw['dec'] = kwargs.pop('galcen_dec', self.galcen_coord.dec)
kwargs['galcen_coord'] = ICRS(**galcen_kw)
super().__init__(*args, **kwargs)
@property
def galcen_ra(self):
warnings.warn("The attribute 'galcen_ra' is deprecated. Use "
"'.galcen_coord.ra' instead.", AstropyDeprecationWarning)
return self.galcen_coord.ra
@property
def galcen_dec(self):
warnings.warn("The attribute 'galcen_dec' is deprecated. Use "
"'.galcen_coord.dec' instead.", AstropyDeprecationWarning)
return self.galcen_coord.dec
@classmethod
def get_roll0(cls):
"""
The additional roll angle (about the final x axis) necessary to align
the final z axis to match the Galactic yz-plane. Setting the ``roll``
frame attribute to -this method's return value removes this rotation,
allowing the use of the `Galactocentric` frame in more general contexts.
"""
# note that the actual value is defined at the module level. We make at
# a property here because this module isn't actually part of the public
# API, so it's better for it to be accessable from Galactocentric
return _ROLL0
# ICRS to/from Galactocentric ----------------------->
def get_matrix_vectors(galactocentric_frame, inverse=False):
"""
Use the ``inverse`` argument to get the inverse transformation, matrix and
offsets to go from Galactocentric to ICRS.
"""
# shorthand
gcf = galactocentric_frame
# rotation matrix to align x(ICRS) with the vector to the Galactic center
mat1 = rotation_matrix(-gcf.galcen_coord.dec, 'y')
mat2 = rotation_matrix(gcf.galcen_coord.ra, 'z')
# extra roll away from the Galactic x-z plane
mat0 = rotation_matrix(gcf.get_roll0() - gcf.roll, 'x')
# construct transformation matrix and use it
R = matrix_product(mat0, mat1, mat2)
# Now need to translate by Sun-Galactic center distance around x' and
# rotate about y' to account for tilt due to Sun's height above the plane
translation = r.CartesianRepresentation(gcf.galcen_distance * [1., 0., 0.])
z_d = gcf.z_sun / gcf.galcen_distance
H = rotation_matrix(-np.arcsin(z_d), 'y')
# compute total matrices
A = matrix_product(H, R)
# Now we re-align the translation vector to account for the Sun's height
# above the midplane
offset = -translation.transform(H)
if inverse:
# the inverse of a rotation matrix is a transpose, which is much faster
# and more stable to compute
A = matrix_transpose(A)
offset = (-offset).transform(A)
offset_v = r.CartesianDifferential.from_cartesian(
(-gcf.galcen_v_sun).to_cartesian().transform(A))
offset = offset.with_differentials(offset_v)
else:
offset = offset.with_differentials(gcf.galcen_v_sun)
return A, offset
def _check_coord_repr_diff_types(c):
if isinstance(c.data, r.UnitSphericalRepresentation):
raise ConvertError("Transforming to/from a Galactocentric frame "
"requires a 3D coordinate, e.g. (angle, angle, "
"distance) or (x, y, z).")
if ('s' in c.data.differentials and
isinstance(c.data.differentials['s'],
(r.UnitSphericalDifferential,
r.UnitSphericalCosLatDifferential,
r.RadialDifferential))):
raise ConvertError("Transforming to/from a Galactocentric frame "
"requires a 3D velocity, e.g., proper motion "
"components and radial velocity.")
@frame_transform_graph.transform(AffineTransform, ICRS, Galactocentric)
def icrs_to_galactocentric(icrs_coord, galactocentric_frame):
_check_coord_repr_diff_types(icrs_coord)
return get_matrix_vectors(galactocentric_frame)
@frame_transform_graph.transform(AffineTransform, Galactocentric, ICRS)
def galactocentric_to_icrs(galactocentric_coord, icrs_frame):
_check_coord_repr_diff_types(galactocentric_coord)
return get_matrix_vectors(galactocentric_coord, inverse=True)
|
aadf0c57ee3de06ba92c030523af0e48e329941b825d12914d462b9d9de52999 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ..matrix_utilities import (rotation_matrix,
matrix_product, matrix_transpose)
from ..baseframe import frame_transform_graph
from ..transformations import StaticMatrixTransform
from .galactic import Galactic
from .supergalactic import Supergalactic
@frame_transform_graph.transform(StaticMatrixTransform, Galactic, Supergalactic)
def gal_to_supergal():
mat1 = rotation_matrix(90, 'z')
mat2 = rotation_matrix(90 - Supergalactic._nsgp_gal.b.degree, 'y')
mat3 = rotation_matrix(Supergalactic._nsgp_gal.l.degree, 'z')
return matrix_product(mat1, mat2, mat3)
@frame_transform_graph.transform(StaticMatrixTransform, Supergalactic, Galactic)
def supergal_to_gal():
return matrix_transpose(gal_to_supergal())
|
43ede572f38eccac86fde8e88258ad37600bef230999db3bf95bf0b606027df3 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ...utils.decorators import format_doc
from ..baseframe import frame_transform_graph, base_doc
from ..attributes import TimeAttribute
from ..transformations import DynamicMatrixTransform
from .. import earth_orientation as earth
from .baseradec import BaseRADecFrame, doc_components
from .utils import EQUINOX_J2000
__all__ = ['FK5']
doc_footer = """
Other parameters
----------------
equinox : `~astropy.time.Time`
The equinox of this frame.
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer)
class FK5(BaseRADecFrame):
"""
A coordinate or frame in the FK5 system.
Note that this is a barycentric version of FK5 - that is, the origin for
this frame is the Solar System Barycenter, *not* the Earth geocenter.
The frame attributes are listed under **Other Parameters**.
"""
equinox = TimeAttribute(default=EQUINOX_J2000)
@staticmethod
def _precession_matrix(oldequinox, newequinox):
"""
Compute and return the precession matrix for FK5 based on Capitaine et
al. 2003/IAU2006. Used inside some of the transformation functions.
Parameters
----------
oldequinox : `~astropy.time.Time`
The equinox to precess from.
newequinox : `~astropy.time.Time`
The equinox to precess to.
Returns
-------
newcoord : array
The precession matrix to transform to the new equinox
"""
return earth.precession_matrix_Capitaine(oldequinox, newequinox)
# This is the "self-transform". Defined at module level because the decorator
# needs a reference to the FK5 class
@frame_transform_graph.transform(DynamicMatrixTransform, FK5, FK5)
def fk5_to_fk5(fk5coord1, fk5frame2):
return fk5coord1._precession_matrix(fk5coord1.equinox, fk5frame2.equinox)
|
818a08c19c442e45ee1c4490f56bc3d7f75cba5878ed5f96760861f0fbae86ca | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Contains the transformation functions for getting to/from ITRS, GCRS, and CIRS.
These are distinct from the ICRS and AltAz functions because they are just
rotations without aberration corrections or offsets.
"""
import numpy as np
from ..baseframe import frame_transform_graph
from ..transformations import FunctionTransformWithFiniteDifference
from ..matrix_utilities import matrix_transpose
from ... import _erfa as erfa
from .gcrs import GCRS, PrecessedGeocentric
from .cirs import CIRS
from .itrs import ITRS
from .utils import get_polar_motion, get_jd12
# # first define helper functions
def gcrs_to_cirs_mat(time):
# celestial-to-intermediate matrix
return erfa.c2i06a(*get_jd12(time, 'tt'))
def cirs_to_itrs_mat(time):
# compute the polar motion p-matrix
xp, yp = get_polar_motion(time)
sp = erfa.sp00(*get_jd12(time, 'tt'))
pmmat = erfa.pom00(xp, yp, sp)
# now determine the Earth Rotation Angle for the input obstime
# era00 accepts UT1, so we convert if need be
era = erfa.era00(*get_jd12(time, 'ut1'))
# c2tcio expects a GCRS->CIRS matrix, but we just set that to an I-matrix
# because we're already in CIRS
return erfa.c2tcio(np.eye(3), era, pmmat)
def gcrs_precession_mat(equinox):
gamb, phib, psib, epsa = erfa.pfw06(*get_jd12(equinox, 'tt'))
return erfa.fw2m(gamb, phib, psib, epsa)
# now the actual transforms
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, CIRS)
def gcrs_to_cirs(gcrs_coo, cirs_frame):
# first get us to a 0 pos/vel GCRS at the target obstime
gcrs_coo2 = gcrs_coo.transform_to(GCRS(obstime=cirs_frame.obstime))
# now get the pmatrix
pmat = gcrs_to_cirs_mat(cirs_frame.obstime)
crepr = gcrs_coo2.cartesian.transform(pmat)
return cirs_frame.realize_frame(crepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, GCRS)
def cirs_to_gcrs(cirs_coo, gcrs_frame):
# compute the pmatrix, and then multiply by its transpose
pmat = gcrs_to_cirs_mat(cirs_coo.obstime)
newrepr = cirs_coo.cartesian.transform(matrix_transpose(pmat))
gcrs = GCRS(newrepr, obstime=cirs_coo.obstime)
# now do any needed offsets (no-op if same obstime and 0 pos/vel)
return gcrs.transform_to(gcrs_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, ITRS)
def cirs_to_itrs(cirs_coo, itrs_frame):
# first get us to CIRS at the target obstime
cirs_coo2 = cirs_coo.transform_to(CIRS(obstime=itrs_frame.obstime))
# now get the pmatrix
pmat = cirs_to_itrs_mat(itrs_frame.obstime)
crepr = cirs_coo2.cartesian.transform(pmat)
return itrs_frame.realize_frame(crepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, CIRS)
def itrs_to_cirs(itrs_coo, cirs_frame):
# compute the pmatrix, and then multiply by its transpose
pmat = cirs_to_itrs_mat(itrs_coo.obstime)
newrepr = itrs_coo.cartesian.transform(matrix_transpose(pmat))
cirs = CIRS(newrepr, obstime=itrs_coo.obstime)
# now do any needed offsets (no-op if same obstime)
return cirs.transform_to(cirs_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, ITRS)
def itrs_to_itrs(from_coo, to_frame):
# this self-transform goes through CIRS right now, which implicitly also
# goes back to ICRS
return from_coo.transform_to(CIRS).transform_to(to_frame)
# TODO: implement GCRS<->CIRS if there's call for it. The thing that's awkward
# is that they both have obstimes, so an extra set of transformations are necessary.
# so unless there's a specific need for that, better to just have it go through the above
# two steps anyway
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, PrecessedGeocentric)
def gcrs_to_precessedgeo(from_coo, to_frame):
# first get us to GCRS with the right attributes (might be a no-op)
gcrs_coo = from_coo.transform_to(GCRS(obstime=to_frame.obstime,
obsgeoloc=to_frame.obsgeoloc,
obsgeovel=to_frame.obsgeovel))
# now precess to the requested equinox
pmat = gcrs_precession_mat(to_frame.equinox)
crepr = gcrs_coo.cartesian.transform(pmat)
return to_frame.realize_frame(crepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, PrecessedGeocentric, GCRS)
def precessedgeo_to_gcrs(from_coo, to_frame):
# first un-precess
pmat = gcrs_precession_mat(from_coo.equinox)
crepr = from_coo.cartesian.transform(matrix_transpose(pmat))
gcrs_coo = GCRS(crepr, obstime=to_frame.obstime,
obsgeoloc=to_frame.obsgeoloc,
obsgeovel=to_frame.obsgeovel)
# then move to the GCRS that's actually desired
return gcrs_coo.transform_to(to_frame)
|
a4fb2d69244bdf74bf49eac64ef13206a73a00fbae12aa13673105a2313d2edd | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ...utils.decorators import format_doc
from ..attributes import TimeAttribute
from .utils import DEFAULT_OBSTIME
from ..baseframe import base_doc
from .baseradec import BaseRADecFrame, doc_components
__all__ = ['HCRS']
doc_footer = """
Other parameters
----------------
obstime : `~astropy.time.Time`
The time at which the observation is taken. Used for determining the
position of the Sun.
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer)
class HCRS(BaseRADecFrame):
"""
A coordinate or frame in a Heliocentric system, with axes aligned to ICRS.
The ICRS has an origin at the Barycenter and axes which are fixed with
respect to space.
This coordinate system is distinct from ICRS mainly in that it is relative
to the Sun's center-of-mass rather than the solar system Barycenter.
In principle, therefore, this frame should include the effects of
aberration (unlike ICRS), but this is not done, since they are very small,
of the order of 8 milli-arcseconds.
For more background on the ICRS and related coordinate transformations, see
the references provided in the :ref:`astropy-coordinates-seealso` section of
the documentation.
The frame attributes are listed under **Other Parameters**.
"""
obstime = TimeAttribute(default=DEFAULT_OBSTIME)
# Transformations are defined in icrs_circ_transforms.py
|
9125b91d41afbc6f797774ed3df11dce4cbb187776e4792dd1029a1a1335a0ee | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from ... import units as u
from ...utils.decorators import format_doc
from ..baseframe import frame_transform_graph, base_doc
from ..attributes import TimeAttribute
from ..transformations import (FunctionTransformWithFiniteDifference,
FunctionTransform, DynamicMatrixTransform)
from ..representation import (CartesianRepresentation,
UnitSphericalRepresentation)
from .. import earth_orientation as earth
from .utils import EQUINOX_B1950
from .baseradec import doc_components, BaseRADecFrame
__all__ = ['FK4', 'FK4NoETerms']
doc_footer_fk4 = """
Other parameters
----------------
equinox : `~astropy.time.Time`
The equinox of this frame.
obstime : `~astropy.time.Time`
The time this frame was observed. If ``None``, will be the same as
``equinox``.
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer_fk4)
class FK4(BaseRADecFrame):
"""
A coordinate or frame in the FK4 system.
Note that this is a barycentric version of FK4 - that is, the origin for
this frame is the Solar System Barycenter, *not* the Earth geocenter.
The frame attributes are listed under **Other Parameters**.
"""
equinox = TimeAttribute(default=EQUINOX_B1950)
obstime = TimeAttribute(default=None, secondary_attribute='equinox')
# the "self" transform
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, FK4, FK4)
def fk4_to_fk4(fk4coord1, fk4frame2):
# deceptively complicated: need to transform to No E-terms FK4, precess, and
# then come back, because precession is non-trivial with E-terms
fnoe_w_eqx1 = fk4coord1.transform_to(FK4NoETerms(equinox=fk4coord1.equinox))
fnoe_w_eqx2 = fnoe_w_eqx1.transform_to(FK4NoETerms(equinox=fk4frame2.equinox))
return fnoe_w_eqx2.transform_to(fk4frame2)
@format_doc(base_doc, components=doc_components, footer=doc_footer_fk4)
class FK4NoETerms(BaseRADecFrame):
"""
A coordinate or frame in the FK4 system, but with the E-terms of aberration
removed.
The frame attributes are listed under **Other Parameters**.
"""
equinox = TimeAttribute(default=EQUINOX_B1950)
obstime = TimeAttribute(default=None, secondary_attribute='equinox')
@staticmethod
def _precession_matrix(oldequinox, newequinox):
"""
Compute and return the precession matrix for FK4 using Newcomb's method.
Used inside some of the transformation functions.
Parameters
----------
oldequinox : `~astropy.time.Time`
The equinox to precess from.
newequinox : `~astropy.time.Time`
The equinox to precess to.
Returns
-------
newcoord : array
The precession matrix to transform to the new equinox
"""
return earth._precession_matrix_besselian(oldequinox.byear, newequinox.byear)
# the "self" transform
@frame_transform_graph.transform(DynamicMatrixTransform, FK4NoETerms, FK4NoETerms)
def fk4noe_to_fk4noe(fk4necoord1, fk4neframe2):
return fk4necoord1._precession_matrix(fk4necoord1.equinox, fk4neframe2.equinox)
# FK4-NO-E to/from FK4 ----------------------------->
# Unlike other frames, this module include *two* frame classes for FK4
# coordinates - one including the E-terms of aberration (FK4), and
# one not including them (FK4NoETerms). The following functions
# implement the transformation between these two.
def fk4_e_terms(equinox):
"""
Return the e-terms of aberation vector
Parameters
----------
equinox : Time object
The equinox for which to compute the e-terms
"""
# Constant of aberration at J2000; from Explanatory Supplement to the
# Astronomical Almanac (Seidelmann, 2005).
k = 0.0056932 # in degrees (v_earth/c ~ 1e-4 rad ~ 0.0057 deg)
k = np.radians(k)
# Eccentricity of the Earth's orbit
e = earth.eccentricity(equinox.jd)
# Mean longitude of perigee of the solar orbit
g = earth.mean_lon_of_perigee(equinox.jd)
g = np.radians(g)
# Obliquity of the ecliptic
o = earth.obliquity(equinox.jd, algorithm=1980)
o = np.radians(o)
return e * k * np.sin(g), \
-e * k * np.cos(g) * np.cos(o), \
-e * k * np.cos(g) * np.sin(o)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, FK4, FK4NoETerms)
def fk4_to_fk4_no_e(fk4coord, fk4noeframe):
# Extract cartesian vector
rep = fk4coord.cartesian
# Find distance (for re-normalization)
d_orig = rep.norm()
rep /= d_orig
# Apply E-terms of aberration. Note that this depends on the equinox (not
# the observing time/epoch) of the coordinates. See issue #1496 for a
# discussion of this.
eterms_a = CartesianRepresentation(
u.Quantity(fk4_e_terms(fk4coord.equinox), u.dimensionless_unscaled,
copy=False), copy=False)
rep = rep - eterms_a + eterms_a.dot(rep) * rep
# Find new distance (for re-normalization)
d_new = rep.norm()
# Renormalize
rep *= d_orig / d_new
# now re-cast into an appropriate Representation, and precess if need be
if isinstance(fk4coord.data, UnitSphericalRepresentation):
rep = rep.represent_as(UnitSphericalRepresentation)
# if no obstime was given in the new frame, use the old one for consistency
newobstime = fk4coord._obstime if fk4noeframe._obstime is None else fk4noeframe._obstime
fk4noe = FK4NoETerms(rep, equinox=fk4coord.equinox, obstime=newobstime)
if fk4coord.equinox != fk4noeframe.equinox:
# precession
fk4noe = fk4noe.transform_to(fk4noeframe)
return fk4noe
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, FK4NoETerms, FK4)
def fk4_no_e_to_fk4(fk4noecoord, fk4frame):
# first precess, if necessary
if fk4noecoord.equinox != fk4frame.equinox:
fk4noe_w_fk4equinox = FK4NoETerms(equinox=fk4frame.equinox,
obstime=fk4noecoord.obstime)
fk4noecoord = fk4noecoord.transform_to(fk4noe_w_fk4equinox)
# Extract cartesian vector
rep = fk4noecoord.cartesian
# Find distance (for re-normalization)
d_orig = rep.norm()
rep /= d_orig
# Apply E-terms of aberration. Note that this depends on the equinox (not
# the observing time/epoch) of the coordinates. See issue #1496 for a
# discussion of this.
eterms_a = CartesianRepresentation(
u.Quantity(fk4_e_terms(fk4noecoord.equinox), u.dimensionless_unscaled,
copy=False), copy=False)
rep0 = rep.copy()
for _ in range(10):
rep = (eterms_a + rep0) / (1. + eterms_a.dot(rep))
# Find new distance (for re-normalization)
d_new = rep.norm()
# Renormalize
rep *= d_orig / d_new
# now re-cast into an appropriate Representation, and precess if need be
if isinstance(fk4noecoord.data, UnitSphericalRepresentation):
rep = rep.represent_as(UnitSphericalRepresentation)
return fk4frame.realize_frame(rep)
|
94e864a13bf474662a63c61bdb99203f894a4a6d689ac4492c99fcb266d2789b | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ...utils.decorators import format_doc
from .. import representation as r
from ..baseframe import BaseCoordinateFrame, RepresentationMapping, base_doc
__all__ = ['BaseRADecFrame']
doc_components = """
ra : `Angle`, optional, must be keyword
The RA for this object (``dec`` must also be given and ``representation``
must be None).
dec : `Angle`, optional, must be keyword
The Declination for this object (``ra`` must also be given and
``representation`` must be None).
distance : `~astropy.units.Quantity`, optional, must be keyword
The Distance for this object along the line-of-sight.
(``representation`` must be None).
pm_ra_cosdec : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Right Ascension (including the ``cos(dec)`` factor)
for this object (``pm_dec`` must also be given).
pm_dec : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Declination for this object (``pm_ra_cosdec`` must
also be given).
radial_velocity : :class:`~astropy.units.Quantity`, optional, must be keyword
The radial velocity of this object.
"""
@format_doc(base_doc, components=doc_components, footer="")
class BaseRADecFrame(BaseCoordinateFrame):
"""
A base class that defines default representation info for frames that
represent longitude and latitude as Right Ascension and Declination
following typical "equatorial" conventions.
"""
frame_specific_representation_info = {
r.SphericalRepresentation: [
RepresentationMapping('lon', 'ra'),
RepresentationMapping('lat', 'dec')
]
}
default_representation = r.SphericalRepresentation
default_differential = r.SphericalCosLatDifferential
|
59c23b9e42f4280ed05ccbbe6af79b1a366e965d0ba5ab9bb11f4d0b99825d77 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package contains the coordinate frames actually implemented by astropy.
Users shouldn't use this module directly, but rather import from the
`astropy.coordinates` module. While it is likely to exist for the long-term,
the existence of this package and details of its organization should be
considered an implementation detail, and is not guaranteed to hold for future
versions of astropy.
Notes
-----
The builtin frame classes are all imported automatically into this package's
namespace, so there's no need to access the sub-modules directly.
To implement a new frame in Astropy, a developer should add the frame as a new
module in this package. Any "self" transformations (i.e., those that transform
from one frame to another frame of the same class) should be included in that
module. Transformation functions connecting the new frame to other frames
should be in a separate module, which should be imported in this package's
``__init__.py`` to ensure the transformations are hooked up when this package is
imported. Placing the trasnformation functions in separate modules avoids
circular dependencies, because they need references to the frame classes.
"""
from .baseradec import BaseRADecFrame
from .icrs import ICRS
from .fk5 import FK5
from .fk4 import FK4, FK4NoETerms
from .galactic import Galactic
from .galactocentric import Galactocentric
from .lsr import LSR, GalacticLSR
from .supergalactic import Supergalactic
from .altaz import AltAz
from .gcrs import GCRS, PrecessedGeocentric
from .cirs import CIRS
from .itrs import ITRS
from .hcrs import HCRS
from .ecliptic import (GeocentricTrueEcliptic, BarycentricTrueEcliptic,
HeliocentricTrueEcliptic, BaseEclipticFrame)
from .skyoffset import SkyOffsetFrame
# need to import transformations so that they get registered in the graph
from . import icrs_fk5_transforms
from . import fk4_fk5_transforms
from . import galactic_transforms
from . import supergalactic_transforms
from . import icrs_cirs_transforms
from . import cirs_observed_transforms
from . import intermediate_rotation_transforms
from . import ecliptic_transforms
# we define an __all__ because otherwise the transformation modules get included
__all__ = ['ICRS', 'FK5', 'FK4', 'FK4NoETerms', 'Galactic', 'Galactocentric',
'Supergalactic', 'AltAz', 'GCRS', 'CIRS', 'ITRS', 'HCRS',
'PrecessedGeocentric', 'GeocentricTrueEcliptic',
'BarycentricTrueEcliptic', 'HeliocentricTrueEcliptic',
'SkyOffsetFrame', 'GalacticLSR', 'LSR',
'BaseEclipticFrame', 'BaseRADecFrame']
def _make_transform_graph_docs():
"""
Generates a string for use with the coordinate package's docstring
to show the available transforms and coordinate systems
"""
import inspect
from textwrap import dedent
from ..baseframe import BaseCoordinateFrame, frame_transform_graph
isclass = inspect.isclass
coosys = [item for item in globals().values()
if isclass(item) and issubclass(item, BaseCoordinateFrame)]
# currently, all of the priorities are set to 1, so we don't need to show
# then in the transform graph.
graphstr = frame_transform_graph.to_dot_graph(addnodes=coosys,
priorities=False)
docstr = """
The diagram below shows all of the coordinate systems built into the
`~astropy.coordinates` package, their aliases (useful for converting
other coordinates to them using attribute-style access) and the
pre-defined transformations between them. The user is free to
override any of these transformations by defining new transformations
between these systems, but the pre-defined transformations should be
sufficient for typical usage.
The color of an edge in the graph (i.e. the transformations between two
frames) is set by the type of transformation; the legend box defines the
mapping from transform class name to color.
.. graphviz::
"""
docstr = dedent(docstr) + ' ' + graphstr.replace('\n', '\n ')
# colors are in dictionary at the bottom of transformations.py
from ..transformations import trans_to_color
html_list_items = []
for cls, color in trans_to_color.items():
block = u"""
<li style='list-style: none;'>
<p style="font-size: 12px;line-height: 24px;font-weight: normal;color: #848484;padding: 0;margin: 0;">
<b>{0}:</b>
<span style="font-size: 24px; color: {1};"><b>➝</b></span>
</p>
</li>
""".format(cls.__name__, color)
html_list_items.append(block)
graph_legend = u"""
.. raw:: html
<ul>
{}
</ul>
""".format("\n".join(html_list_items))
docstr = docstr + dedent(graph_legend)
return docstr
_transform_graph_docs = _make_transform_graph_docs()
|
b4ea85be0ae6b17a2c8085c1fb89c3a80f6fa9b472ac214a639f363251a632b0 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import units as u
from ...utils.decorators import format_doc
from .. import representation as r
from ..baseframe import BaseCoordinateFrame, RepresentationMapping, base_doc
from .galactic import Galactic
__all__ = ['Supergalactic']
doc_components = """
sgl : `Angle`, optional, must be keyword
The supergalactic longitude for this object (``sgb`` must also be given and
``representation`` must be None).
sgb : `Angle`, optional, must be keyword
The supergalactic latitude for this object (``sgl`` must also be given and
``representation`` must be None).
distance : `~astropy.units.Quantity`, optional, must be keyword
The Distance for this object along the line-of-sight.
pm_sgl_cossgb : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Right Ascension for this object (``pm_sgb`` must
also be given).
pm_sgb : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Declination for this object (``pm_sgl_cossgb`` must
also be given).
radial_velocity : :class:`~astropy.units.Quantity`, optional, must be keyword
The radial velocity of this object.
"""
@format_doc(base_doc, components=doc_components, footer="")
class Supergalactic(BaseCoordinateFrame):
"""
Supergalactic Coordinates
(see Lahav et al. 2000, <http://adsabs.harvard.edu/abs/2000MNRAS.312..166L>,
and references therein).
"""
frame_specific_representation_info = {
r.SphericalRepresentation: [
RepresentationMapping('lon', 'sgl'),
RepresentationMapping('lat', 'sgb')
],
r.CartesianRepresentation: [
RepresentationMapping('x', 'sgx'),
RepresentationMapping('y', 'sgy'),
RepresentationMapping('z', 'sgz')
],
r.CartesianDifferential: [
RepresentationMapping('d_x', 'v_x', u.km/u.s),
RepresentationMapping('d_y', 'v_y', u.km/u.s),
RepresentationMapping('d_z', 'v_z', u.km/u.s)
],
}
default_representation = r.SphericalRepresentation
default_differential = r.SphericalCosLatDifferential
# North supergalactic pole in Galactic coordinates.
# Needed for transformations to/from Galactic coordinates.
_nsgp_gal = Galactic(l=47.37*u.degree, b=+6.32*u.degree)
|
a64e841319de8804d0998238c39427550a27cef7796b6f9f9cf9920127b68f8b | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ...utils.decorators import format_doc
from ..baseframe import base_doc
from .baseradec import BaseRADecFrame, doc_components
__all__ = ['ICRS']
@format_doc(base_doc, components=doc_components, footer="")
class ICRS(BaseRADecFrame):
"""
A coordinate or frame in the ICRS system.
If you're looking for "J2000" coordinates, and aren't sure if you want to
use this or `~astropy.coordinates.FK5`, you probably want to use ICRS. It's
more well-defined as a catalog coordinate and is an inertial system, and is
very close (within tens of milliarcseconds) to J2000 equatorial.
For more background on the ICRS and related coordinate transformations, see the
references provided in the :ref:`astropy-coordinates-seealso` section of the
documentation.
"""
|
0721ffcbc7daf9fb99f4d6fe88ec8467bca125f8140a4dba8425d39d916d8b96 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import units as u
from ...utils.decorators import format_doc
from ..attributes import (TimeAttribute,
CartesianRepresentationAttribute)
from .utils import DEFAULT_OBSTIME, EQUINOX_J2000
from ..baseframe import base_doc
from .baseradec import BaseRADecFrame, doc_components
__all__ = ['GCRS', 'PrecessedGeocentric']
doc_footer_gcrs = """
Other parameters
----------------
obstime : `~astropy.time.Time`
The time at which the observation is taken. Used for determining the
position of the Earth.
obsgeoloc : `~astropy.coordinates.CartesianRepresentation`, `~astropy.units.Quantity`
The position of the observer relative to the center-of-mass of the
Earth, oriented the same as BCRS/ICRS. Either [0, 0, 0],
`~astropy.coordinates.CartesianRepresentation`, or proper input for one,
i.e., a `~astropy.units.Quantity` with shape (3, ...) and length units.
Defaults to [0, 0, 0], meaning "true" GCRS.
obsgeovel : `~astropy.coordinates.CartesianRepresentation`, `~astropy.units.Quantity`
The velocity of the observer relative to the center-of-mass of the
Earth, oriented the same as BCRS/ICRS. Either [0, 0, 0],
`~astropy.coordinates.CartesianRepresentation`, or proper input for one,
i.e., a `~astropy.units.Quantity` with shape (3, ...) and velocity
units. Defaults to [0, 0, 0], meaning "true" GCRS.
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer_gcrs)
class GCRS(BaseRADecFrame):
"""
A coordinate or frame in the Geocentric Celestial Reference System (GCRS).
GCRS is distinct form ICRS mainly in that it is relative to the Earth's
center-of-mass rather than the solar system Barycenter. That means this
frame includes the effects of aberration (unlike ICRS). For more background
on the GCRS, see the references provided in the
:ref:`astropy-coordinates-seealso` section of the documentation. (Of
particular note is Section 1.2 of
`USNO Circular 179 <http://aa.usno.navy.mil/publications/docs/Circular_179.php>`_)
This frame also includes frames that are defined *relative* to the Earth,
but that are offset (in both position and velocity) from the Earth.
The frame attributes are listed under **Other Parameters**.
"""
obstime = TimeAttribute(default=DEFAULT_OBSTIME)
obsgeoloc = CartesianRepresentationAttribute(default=[0, 0, 0],
unit=u.m)
obsgeovel = CartesianRepresentationAttribute(default=[0, 0, 0],
unit=u.m/u.s)
# The "self-transform" is defined in icrs_cirs_transformations.py, because in
# the current implementation it goes through ICRS (like CIRS)
doc_footer_prec_geo = """
Other parameters
----------------
equinox : `~astropy.time.Time`
The (mean) equinox to precess the coordinates to.
obstime : `~astropy.time.Time`
The time at which the observation is taken. Used for determining the
position of the Earth.
obsgeoloc : `~astropy.coordinates.CartesianRepresentation`, `~astropy.units.Quantity`
The position of the observer relative to the center-of-mass of the
Earth, oriented the same as BCRS/ICRS. Either [0, 0, 0],
`~astropy.coordinates.CartesianRepresentation`, or proper input for one,
i.e., a `~astropy.units.Quantity` with shape (3, ...) and length units.
Defaults to [0, 0, 0], meaning "true" Geocentric.
obsgeovel : `~astropy.coordinates.CartesianRepresentation`, `~astropy.units.Quantity`
The velocity of the observer relative to the center-of-mass of the
Earth, oriented the same as BCRS/ICRS. Either 0,
`~astropy.coordinates.CartesianRepresentation`, or proper input for one,
i.e., a `~astropy.units.Quantity` with shape (3, ...) and velocity
units. Defaults to [0, 0, 0], meaning "true" Geocentric.
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer_prec_geo)
class PrecessedGeocentric(BaseRADecFrame):
"""
A coordinate frame defined in a similar manner as GCRS, but precessed to a
requested (mean) equinox. Note that this does *not* end up the same as
regular GCRS even for J2000 equinox, because the GCRS orientation is fixed
to that of ICRS, which is not quite the same as the dynamical J2000
orientation.
The frame attributes are listed under **Other Parameters**
"""
equinox = TimeAttribute(default=EQUINOX_J2000)
obstime = TimeAttribute(default=DEFAULT_OBSTIME)
obsgeoloc = CartesianRepresentationAttribute(default=[0, 0, 0], unit=u.m)
obsgeovel = CartesianRepresentationAttribute(default=[0, 0, 0], unit=u.m/u.s)
|
1fc64e257deab017865db87fc07191db330b7f21876e4b706302e8061581946a | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import units as u
from ...utils.decorators import format_doc
from .. import representation as r
from ..baseframe import BaseCoordinateFrame, RepresentationMapping, base_doc
from ..attributes import TimeAttribute
from .utils import EQUINOX_J2000, DEFAULT_OBSTIME
__all__ = ['GeocentricTrueEcliptic', 'BarycentricTrueEcliptic',
'HeliocentricTrueEcliptic', 'BaseEclipticFrame']
doc_components_ecl = """
lon : `Angle`, optional, must be keyword
The ecliptic longitude for this object (``lat`` must also be given and
``representation`` must be None).
lat : `Angle`, optional, must be keyword
The ecliptic latitude for this object (``lon`` must also be given and
``representation`` must be None).
distance : `~astropy.units.Quantity`, optional, must be keyword
The distance for this object from the {0}.
(``representation`` must be None).
pm_lon_coslat : `Angle`, optional, must be keyword
The proper motion in the ecliptic longitude (including the ``cos(lat)``
factor) for this object (``pm_lat`` must also be given).
pm_lat : `Angle`, optional, must be keyword
The proper motion in the ecliptic latitude for this object
(``pm_lon_coslat`` must also be given).
radial_velocity : :class:`~astropy.units.Quantity`, optional, must be keyword
The radial velocity of this object.
"""
@format_doc(base_doc,
components=doc_components_ecl.format('specified location'),
footer="")
class BaseEclipticFrame(BaseCoordinateFrame):
"""
A base class for frames that have names and conventions like that of
ecliptic frames.
.. warning::
In the current version of astropy, the ecliptic frames do not yet have
stringent accuracy tests. We recommend you test to "known-good" cases
to ensure this frames are what you are looking for. (and then ideally
you would contribute these tests to Astropy!)
"""
default_representation = r.SphericalRepresentation
default_differential = r.SphericalCosLatDifferential
doc_footer_geo = """
Other parameters
----------------
equinox : `~astropy.time.Time`, optional
The date to assume for this frame. Determines the location of the
x-axis and the location of the Earth (necessary for transformation to
non-geocentric systems). Defaults to the 'J2000' equinox.
"""
@format_doc(base_doc, components=doc_components_ecl.format('geocenter'),
footer=doc_footer_geo)
class GeocentricTrueEcliptic(BaseEclipticFrame):
"""
Geocentric ecliptic coordinates. These origin of the coordinates are the
geocenter (Earth), with the x axis pointing to the *true* (not mean) equinox
at the time specified by the ``equinox`` attribute, and the xy-plane in the
plane of the ecliptic for that date.
Be aware that the definition of "geocentric" here means that this frame
*includes* light deflection from the sun, aberration, etc when transforming
to/from e.g. ICRS.
The frame attributes are listed under **Other Parameters**.
"""
equinox = TimeAttribute(default=EQUINOX_J2000)
doc_footer_bary = """
Other parameters
----------------
equinox : `~astropy.time.Time`, optional
The date to assume for this frame. Determines the location of the
x-axis and the location of the Earth and Sun.
Defaults to the 'J2000' equinox.
"""
@format_doc(base_doc, components=doc_components_ecl.format("barycenter"),
footer=doc_footer_bary)
class BarycentricTrueEcliptic(BaseEclipticFrame):
"""
Barycentric ecliptic coordinates. These origin of the coordinates are the
barycenter of the solar system, with the x axis pointing in the direction of
the *true* (not mean) equinox as at the time specified by the ``equinox``
attribute (as seen from Earth), and the xy-plane in the plane of the
ecliptic for that date.
The frame attributes are listed under **Other Parameters**.
"""
equinox = TimeAttribute(default=EQUINOX_J2000)
doc_footer_helio = """
Other parameters
----------------
equinox : `~astropy.time.Time`, optional
The date to assume for this frame. Determines the location of the
x-axis and the location of the Earth and Sun.
Defaults to the 'J2000' equinox.
"""
@format_doc(base_doc, components=doc_components_ecl.format("sun's center"),
footer=doc_footer_helio)
class HeliocentricTrueEcliptic(BaseEclipticFrame):
"""
Heliocentric ecliptic coordinates. These origin of the coordinates are the
center of the sun, with the x axis pointing in the direction of
the *true* (not mean) equinox as at the time specified by the ``equinox``
attribute (as seen from Earth), and the xy-plane in the plane of the
ecliptic for that date.
The frame attributes are listed under **Other Parameters**.
{params}
"""
equinox = TimeAttribute(default=EQUINOX_J2000)
obstime = TimeAttribute(default=DEFAULT_OBSTIME)
|
4e165cf23556652415023d588bafac03df2a212ee5775817cb55117c92171cb5 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ...utils.decorators import format_doc
from ..representation import CartesianRepresentation, CartesianDifferential
from ..baseframe import BaseCoordinateFrame, base_doc
from ..attributes import TimeAttribute
from .utils import DEFAULT_OBSTIME
__all__ = ['ITRS']
@format_doc(base_doc, components="", footer="")
class ITRS(BaseCoordinateFrame):
"""
A coordinate or frame in the International Terrestrial Reference System
(ITRS). This is approximately a geocentric system, although strictly it is
defined by a series of reference locations near the surface of the Earth.
For more background on the ITRS, see the references provided in the
:ref:`astropy-coordinates-seealso` section of the documentation.
"""
default_representation = CartesianRepresentation
default_differential = CartesianDifferential
obstime = TimeAttribute(default=DEFAULT_OBSTIME)
@property
def earth_location(self):
"""
The data in this frame as an `~astropy.coordinates.EarthLocation` class.
"""
from ..earth import EarthLocation
cart = self.represent_as(CartesianRepresentation)
return EarthLocation(x=cart.x, y=cart.y, z=cart.z)
# Self-transform is in intermediate_rotation_transforms.py with all the other
# ITRS transforms
|
e1d350875bdc85f2ce84a8ee4267030f94a4db18e082cae7df5ee2d2df794e24 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains functions/values used repeatedly in different modules of
the ``builtin_frames`` package.
"""
import warnings
import numpy as np
from ... import units as u
from ... import _erfa as erfa
from ...time import Time
from ...utils import iers
from ...utils.exceptions import AstropyWarning
# The UTC time scale is not properly defined prior to 1960, so Time('B1950',
# scale='utc') will emit a warning. Instead, we use Time('B1950', scale='tai')
# which is equivalent, but does not emit a warning.
EQUINOX_J2000 = Time('J2000', scale='utc')
EQUINOX_B1950 = Time('B1950', scale='tai')
# This is a time object that is the default "obstime" when such an attribute is
# necessary. Currently, we use J2000.
DEFAULT_OBSTIME = Time('J2000', scale='utc')
PIOVER2 = np.pi / 2.
# comes from the mean of the 1962-2014 IERS B data
_DEFAULT_PM = (0.035, 0.29)*u.arcsec
def get_polar_motion(time):
"""
gets the two polar motion components in radians for use with apio13
"""
# Get the polar motion from the IERS table
xp, yp, status = iers.IERS_Auto.open().pm_xy(time, return_status=True)
wmsg = None
if np.any(status == iers.TIME_BEFORE_IERS_RANGE):
wmsg = ('Tried to get polar motions for times before IERS data is '
'valid. Defaulting to polar motion from the 50-yr mean for those. '
'This may affect precision at the 10s of arcsec level')
xp.ravel()[status.ravel() == iers.TIME_BEFORE_IERS_RANGE] = _DEFAULT_PM[0]
yp.ravel()[status.ravel() == iers.TIME_BEFORE_IERS_RANGE] = _DEFAULT_PM[1]
warnings.warn(wmsg, AstropyWarning)
if np.any(status == iers.TIME_BEYOND_IERS_RANGE):
wmsg = ('Tried to get polar motions for times after IERS data is '
'valid. Defaulting to polar motion from the 50-yr mean for those. '
'This may affect precision at the 10s of arcsec level')
xp.ravel()[status.ravel() == iers.TIME_BEYOND_IERS_RANGE] = _DEFAULT_PM[0]
yp.ravel()[status.ravel() == iers.TIME_BEYOND_IERS_RANGE] = _DEFAULT_PM[1]
warnings.warn(wmsg, AstropyWarning)
return xp.to_value(u.radian), yp.to_value(u.radian)
def _warn_iers(ierserr):
"""
Generate a warning for an IERSRangeerror
Parameters
----------
ierserr : An `~astropy.utils.iers.IERSRangeError`
"""
msg = '{0} Assuming UT1-UTC=0 for coordinate transformations.'
warnings.warn(msg.format(ierserr.args[0]), AstropyWarning)
def get_dut1utc(time):
"""
This function is used to get UT1-UTC in coordinates because normally it
gives an error outside the IERS range, but in coordinates we want to allow
it to go through but with a warning.
"""
try:
return time.delta_ut1_utc
except iers.IERSRangeError as e:
_warn_iers(e)
return np.zeros(time.shape)
def get_jd12(time, scale):
"""
Gets ``jd1`` and ``jd2`` from a time object in a particular scale.
Parameters
----------
time : `~astropy.time.Time`
The time to get the jds for
scale : str
The time scale to get the jds for
Returns
-------
jd1 : float
jd2 : float
"""
if time.scale == scale:
newtime = time
else:
try:
newtime = getattr(time, scale)
except iers.IERSRangeError as e:
_warn_iers(e)
newtime = time
return newtime.jd1, newtime.jd2
def norm(p):
"""
Normalise a p-vector.
"""
return p/np.sqrt(np.einsum('...i,...i', p, p))[..., np.newaxis]
def get_cip(jd1, jd2):
"""
Find the X, Y coordinates of the CIP and the CIO locator, s.
Parameters
----------
jd1 : float or `np.ndarray`
First part of two part Julian date (TDB)
jd2 : float or `np.ndarray`
Second part of two part Julian date (TDB)
Returns
--------
x : float or `np.ndarray`
x coordinate of the CIP
y : float or `np.ndarray`
y coordinate of the CIP
s : float or `np.ndarray`
CIO locator, s
"""
# classical NPB matrix, IAU 2006/2000A
rpnb = erfa.pnm06a(jd1, jd2)
# CIP X, Y coordinates from array
x, y = erfa.bpn2xy(rpnb)
# CIO locator, s
s = erfa.s06(jd1, jd2, x, y)
return x, y, s
def aticq(ri, di, astrom):
"""
A slightly modified version of the ERFA function ``eraAticq``.
``eraAticq`` performs the transformations between two coordinate systems,
with the details of the transformation being encoded into the ``astrom`` array.
The companion function ``eraAtciqz`` is meant to be its inverse. However, this
is not true for directions close to the Solar centre, since the light deflection
calculations are numerically unstable and therefore not reversible.
This version sidesteps that problem by artificially reducing the light deflection
for directions which are within 90 arcseconds of the Sun's position. This is the
same approach used by the ERFA functions above, except that they use a threshold of
9 arcseconds.
Parameters
----------
ri : float or `~numpy.ndarray`
right ascension, radians
di : float or `~numpy.ndarray`
declination, radians
astrom : eraASTROM array
ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13``
Returns
--------
rc : float or `~numpy.ndarray`
dc : float or `~numpy.ndarray`
"""
# RA, Dec to cartesian unit vectors
pos = erfa.s2c(ri, di)
# Bias-precession-nutation, giving GCRS proper direction.
ppr = erfa.trxp(astrom['bpn'], pos)
# Aberration, giving GCRS natural direction
d = np.zeros_like(ppr)
for j in range(2):
before = norm(ppr-d)
after = erfa.ab(before, astrom['v'], astrom['em'], astrom['bm1'])
d = after - before
pnat = norm(ppr-d)
# Light deflection by the Sun, giving BCRS coordinate direction
d = np.zeros_like(pnat)
for j in range(5):
before = norm(pnat-d)
after = erfa.ld(1.0, before, before, astrom['eh'], astrom['em'], 5e-8)
d = after - before
pco = norm(pnat-d)
# ICRS astrometric RA, Dec
rc, dc = erfa.c2s(pco)
return erfa.anp(rc), dc
def atciqz(rc, dc, astrom):
"""
A slightly modified version of the ERFA function ``eraAtciqz``.
``eraAtciqz`` performs the transformations between two coordinate systems,
with the details of the transformation being encoded into the ``astrom`` array.
The companion function ``eraAticq`` is meant to be its inverse. However, this
is not true for directions close to the Solar centre, since the light deflection
calculations are numerically unstable and therefore not reversible.
This version sidesteps that problem by artificially reducing the light deflection
for directions which are within 90 arcseconds of the Sun's position. This is the
same approach used by the ERFA functions above, except that they use a threshold of
9 arcseconds.
Parameters
----------
rc : float or `~numpy.ndarray`
right ascension, radians
dc : float or `~numpy.ndarray`
declination, radians
astrom : eraASTROM array
ERFA astrometry context, as produced by, e.g. ``eraApci13`` or ``eraApcs13``
Returns
--------
ri : float or `~numpy.ndarray`
di : float or `~numpy.ndarray`
"""
# BCRS coordinate direction (unit vector).
pco = erfa.s2c(rc, dc)
# Light deflection by the Sun, giving BCRS natural direction.
pnat = erfa.ld(1.0, pco, pco, astrom['eh'], astrom['em'], 5e-8)
# Aberration, giving GCRS proper direction.
ppr = erfa.ab(pnat, astrom['v'], astrom['em'], astrom['bm1'])
# Bias-precession-nutation, giving CIRS proper direction.
# Has no effect if matrix is identity matrix, in which case gives GCRS ppr.
pi = erfa.rxp(astrom['bpn'], ppr)
# CIRS (GCRS) RA, Dec
ri, di = erfa.c2s(pi)
return erfa.anp(ri), di
def prepare_earth_position_vel(time):
"""
Get barycentric position and velocity, and heliocentric position of Earth
Parameters
-----------
time : `~astropy.time.Time`
time at which to calculate position and velocity of Earth
Returns
--------
earth_pv : `np.ndarray`
Barycentric position and velocity of Earth, in au and au/day
earth_helio : `np.ndarray`
Heliocentric position of Earth in au
"""
# this goes here to avoid circular import errors
from ..solar_system import (get_body_barycentric, get_body_barycentric_posvel)
# get barycentric position and velocity of earth
earth_pv = get_body_barycentric_posvel('earth', time)
# get heliocentric position of earth, preparing it for passing to erfa.
sun = get_body_barycentric('sun', time)
earth_heliocentric = (earth_pv[0] -
sun).get_xyz(xyz_axis=-1).to_value(u.au)
# Also prepare earth_pv for passing to erfa, which wants xyz in last
# dimension, and pos/vel in one-but-last.
# (Note could use np.stack once our minimum numpy version is >=1.10.)
earth_pv = np.concatenate((earth_pv[0].get_xyz(xyz_axis=-1).to(u.au)
[..., np.newaxis, :].value,
earth_pv[1].get_xyz(xyz_axis=-1).to(u.au/u.d)
[..., np.newaxis, :].value), axis=-2)
return earth_pv, earth_heliocentric
|
c63b916fc1d9f9d6854a7aa98d9c7c568ed173f2d577dd4c822a33736e90587d | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Contains the transformation functions for getting to/from ecliptic systems.
"""
from ... import units as u
from ..baseframe import frame_transform_graph
from ..transformations import FunctionTransformWithFiniteDifference, DynamicMatrixTransform
from ..matrix_utilities import (rotation_matrix,
matrix_product, matrix_transpose)
from ..representation import CartesianRepresentation
from ... import _erfa as erfa
from .icrs import ICRS
from .gcrs import GCRS
from .ecliptic import GeocentricTrueEcliptic, BarycentricTrueEcliptic, HeliocentricTrueEcliptic
from .utils import get_jd12
from ..errors import UnitsError
def _ecliptic_rotation_matrix(equinox):
# This code calls pmat06 from ERFA, which retrieves the precession
# matrix (including frame bias) according to the IAU 2006 model, but
# leaves out the nutation. This matches what ERFA does in the ecm06
# function and also brings the results closer to what other libraries
# give (see https://github.com/astropy/astropy/pull/6508). However,
# notice that this makes the name "TrueEcliptic" misleading, and might
# be changed in the future (discussion in the same pull request)
jd1, jd2 = get_jd12(equinox, 'tt')
rbp = erfa.pmat06(jd1, jd2)
obl = erfa.obl06(jd1, jd2)*u.radian
return matrix_product(rotation_matrix(obl, 'x'), rbp)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
GCRS, GeocentricTrueEcliptic,
finite_difference_frameattr_name='equinox')
def gcrs_to_geoecliptic(gcrs_coo, to_frame):
# first get us to a 0 pos/vel GCRS at the target equinox
gcrs_coo2 = gcrs_coo.transform_to(GCRS(obstime=to_frame.equinox))
rmat = _ecliptic_rotation_matrix(to_frame.equinox)
newrepr = gcrs_coo2.cartesian.transform(rmat)
return to_frame.realize_frame(newrepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GeocentricTrueEcliptic, GCRS)
def geoecliptic_to_gcrs(from_coo, gcrs_frame):
rmat = _ecliptic_rotation_matrix(from_coo.equinox)
newrepr = from_coo.cartesian.transform(matrix_transpose(rmat))
gcrs = GCRS(newrepr, obstime=from_coo.equinox)
# now do any needed offsets (no-op if same obstime and 0 pos/vel)
return gcrs.transform_to(gcrs_frame)
@frame_transform_graph.transform(DynamicMatrixTransform, ICRS, BarycentricTrueEcliptic)
def icrs_to_baryecliptic(from_coo, to_frame):
return _ecliptic_rotation_matrix(to_frame.equinox)
@frame_transform_graph.transform(DynamicMatrixTransform, BarycentricTrueEcliptic, ICRS)
def baryecliptic_to_icrs(from_coo, to_frame):
return matrix_transpose(icrs_to_baryecliptic(to_frame, from_coo))
_NEED_ORIGIN_HINT = ("The input {0} coordinates do not have length units. This "
"probably means you created coordinates with lat/lon but "
"no distance. Heliocentric<->ICRS transforms cannot "
"function in this case because there is an origin shift.")
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
ICRS, HeliocentricTrueEcliptic,
finite_difference_frameattr_name='equinox')
def icrs_to_helioecliptic(from_coo, to_frame):
if not u.m.is_equivalent(from_coo.cartesian.x.unit):
raise UnitsError(_NEED_ORIGIN_HINT.format(from_coo.__class__.__name__))
# get barycentric sun coordinate
# this goes here to avoid circular import errors
from ..solar_system import get_body_barycentric
bary_sun_pos = get_body_barycentric('sun', to_frame.obstime)
# offset to heliocentric
heliocart = from_coo.cartesian - bary_sun_pos
# now compute the matrix to precess to the right orientation
rmat = _ecliptic_rotation_matrix(to_frame.equinox)
newrepr = heliocart.transform(rmat)
return to_frame.realize_frame(newrepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricTrueEcliptic, ICRS,
finite_difference_frameattr_name='equinox')
def helioecliptic_to_icrs(from_coo, to_frame):
if not u.m.is_equivalent(from_coo.cartesian.x.unit):
raise UnitsError(_NEED_ORIGIN_HINT.format(from_coo.__class__.__name__))
# first un-precess from ecliptic to ICRS orientation
rmat = _ecliptic_rotation_matrix(from_coo.equinox)
intermed_repr = from_coo.cartesian.transform(matrix_transpose(rmat))
# now offset back to barycentric, which is the correct center for ICRS
# this goes here to avoid circular import errors
from ..solar_system import get_body_barycentric
# get barycentric sun coordinate
bary_sun_pos = get_body_barycentric('sun', from_coo.obstime)
newrepr = intermed_repr + bary_sun_pos
return to_frame.realize_frame(newrepr)
|
a21be4160082e672799d68a10e2afd0fe94d6effd087c5e469435b477a0626d9 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Contains the transformation functions for getting from ICRS/HCRS to CIRS and
anything in between (currently that means GCRS)
"""
import numpy as np
from ... import units as u
from ..baseframe import frame_transform_graph
from ..transformations import FunctionTransformWithFiniteDifference, AffineTransform
from ..representation import (SphericalRepresentation, CartesianRepresentation,
UnitSphericalRepresentation)
from ... import _erfa as erfa
from .icrs import ICRS
from .gcrs import GCRS
from .cirs import CIRS
from .hcrs import HCRS
from .utils import get_jd12, aticq, atciqz, get_cip, prepare_earth_position_vel
# First the ICRS/CIRS related transforms
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, CIRS)
def icrs_to_cirs(icrs_coo, cirs_frame):
# first set up the astrometry context for ICRS<->CIRS
jd1, jd2 = get_jd12(cirs_frame.obstime, 'tdb')
x, y, s = get_cip(jd1, jd2)
earth_pv, earth_heliocentric = prepare_earth_position_vel(cirs_frame.obstime)
astrom = erfa.apci(jd1, jd2, earth_pv, earth_heliocentric, x, y, s)
if icrs_coo.data.get_name() == 'unitspherical' or icrs_coo.data.to_cartesian().x.unit == u.one:
# if no distance, just do the infinite-distance/no parallax calculation
usrepr = icrs_coo.represent_as(UnitSphericalRepresentation)
i_ra = usrepr.lon.to_value(u.radian)
i_dec = usrepr.lat.to_value(u.radian)
cirs_ra, cirs_dec = atciqz(i_ra, i_dec, astrom)
newrep = UnitSphericalRepresentation(lat=u.Quantity(cirs_dec, u.radian, copy=False),
lon=u.Quantity(cirs_ra, u.radian, copy=False),
copy=False)
else:
# When there is a distance, we first offset for parallax to get the
# astrometric coordinate direction and *then* run the ERFA transform for
# no parallax/PM. This ensures reversibility and is more sensible for
# inside solar system objects
astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au,
xyz_axis=-1, copy=False)
newcart = icrs_coo.cartesian - astrom_eb
srepr = newcart.represent_as(SphericalRepresentation)
i_ra = srepr.lon.to_value(u.radian)
i_dec = srepr.lat.to_value(u.radian)
cirs_ra, cirs_dec = atciqz(i_ra, i_dec, astrom)
newrep = SphericalRepresentation(lat=u.Quantity(cirs_dec, u.radian, copy=False),
lon=u.Quantity(cirs_ra, u.radian, copy=False),
distance=srepr.distance, copy=False)
return cirs_frame.realize_frame(newrep)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, ICRS)
def cirs_to_icrs(cirs_coo, icrs_frame):
srepr = cirs_coo.represent_as(SphericalRepresentation)
cirs_ra = srepr.lon.to_value(u.radian)
cirs_dec = srepr.lat.to_value(u.radian)
# set up the astrometry context for ICRS<->cirs and then convert to
# astrometric coordinate direction
jd1, jd2 = get_jd12(cirs_coo.obstime, 'tdb')
x, y, s = get_cip(jd1, jd2)
earth_pv, earth_heliocentric = prepare_earth_position_vel(cirs_coo.obstime)
astrom = erfa.apci(jd1, jd2, earth_pv, earth_heliocentric, x, y, s)
i_ra, i_dec = aticq(cirs_ra, cirs_dec, astrom)
if cirs_coo.data.get_name() == 'unitspherical' or cirs_coo.data.to_cartesian().x.unit == u.one:
# if no distance, just use the coordinate direction to yield the
# infinite-distance/no parallax answer
newrep = UnitSphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False),
lon=u.Quantity(i_ra, u.radian, copy=False),
copy=False)
else:
# When there is a distance, apply the parallax/offset to the SSB as the
# last step - ensures round-tripping with the icrs_to_cirs transform
# the distance in intermedrep is *not* a real distance as it does not
# include the offset back to the SSB
intermedrep = SphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False),
lon=u.Quantity(i_ra, u.radian, copy=False),
distance=srepr.distance,
copy=False)
astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au,
xyz_axis=-1, copy=False)
newrep = intermedrep + astrom_eb
return icrs_frame.realize_frame(newrep)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, CIRS)
def cirs_to_cirs(from_coo, to_frame):
if np.all(from_coo.obstime == to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
else:
# the CIRS<-> CIRS transform actually goes through ICRS. This has a
# subtle implication that a point in CIRS is uniquely determined
# by the corresponding astrometric ICRS coordinate *at its
# current time*. This has some subtle implications in terms of GR, but
# is sort of glossed over in the current scheme because we are dropping
# distances anyway.
return from_coo.transform_to(ICRS).transform_to(to_frame)
# Now the GCRS-related transforms to/from ICRS
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, GCRS)
def icrs_to_gcrs(icrs_coo, gcrs_frame):
# first set up the astrometry context for ICRS<->GCRS. There are a few steps...
# get the position and velocity arrays for the observatory. Need to
# have xyz in last dimension, and pos/vel in one-but-last.
# (Note could use np.stack once our minimum numpy version is >=1.10.)
pv = np.concatenate(
(gcrs_frame.obsgeoloc.get_xyz(xyz_axis=-1).value[..., np.newaxis, :],
gcrs_frame.obsgeovel.get_xyz(xyz_axis=-1).value[..., np.newaxis, :]),
axis=-2)
# find the position and velocity of earth
jd1, jd2 = get_jd12(gcrs_frame.obstime, 'tdb')
earth_pv, earth_heliocentric = prepare_earth_position_vel(gcrs_frame.obstime)
# get astrometry context object, astrom.
astrom = erfa.apcs(jd1, jd2, pv, earth_pv, earth_heliocentric)
if icrs_coo.data.get_name() == 'unitspherical' or icrs_coo.data.to_cartesian().x.unit == u.one:
# if no distance, just do the infinite-distance/no parallax calculation
usrepr = icrs_coo.represent_as(UnitSphericalRepresentation)
i_ra = usrepr.lon.to_value(u.radian)
i_dec = usrepr.lat.to_value(u.radian)
gcrs_ra, gcrs_dec = atciqz(i_ra, i_dec, astrom)
newrep = UnitSphericalRepresentation(lat=u.Quantity(gcrs_dec, u.radian, copy=False),
lon=u.Quantity(gcrs_ra, u.radian, copy=False),
copy=False)
else:
# When there is a distance, we first offset for parallax to get the
# BCRS coordinate direction and *then* run the ERFA transform for no
# parallax/PM. This ensures reversibility and is more sensible for
# inside solar system objects
astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au,
xyz_axis=-1, copy=False)
newcart = icrs_coo.cartesian - astrom_eb
srepr = newcart.represent_as(SphericalRepresentation)
i_ra = srepr.lon.to_value(u.radian)
i_dec = srepr.lat.to_value(u.radian)
gcrs_ra, gcrs_dec = atciqz(i_ra, i_dec, astrom)
newrep = SphericalRepresentation(lat=u.Quantity(gcrs_dec, u.radian, copy=False),
lon=u.Quantity(gcrs_ra, u.radian, copy=False),
distance=srepr.distance, copy=False)
return gcrs_frame.realize_frame(newrep)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
GCRS, ICRS)
def gcrs_to_icrs(gcrs_coo, icrs_frame):
srepr = gcrs_coo.represent_as(SphericalRepresentation)
gcrs_ra = srepr.lon.to_value(u.radian)
gcrs_dec = srepr.lat.to_value(u.radian)
# set up the astrometry context for ICRS<->GCRS and then convert to BCRS
# coordinate direction
pv = np.concatenate(
(gcrs_coo.obsgeoloc.get_xyz(xyz_axis=-1).value[..., np.newaxis, :],
gcrs_coo.obsgeovel.get_xyz(xyz_axis=-1).value[..., np.newaxis, :]),
axis=-2)
jd1, jd2 = get_jd12(gcrs_coo.obstime, 'tdb')
earth_pv, earth_heliocentric = prepare_earth_position_vel(gcrs_coo.obstime)
astrom = erfa.apcs(jd1, jd2, pv, earth_pv, earth_heliocentric)
i_ra, i_dec = aticq(gcrs_ra, gcrs_dec, astrom)
if gcrs_coo.data.get_name() == 'unitspherical' or gcrs_coo.data.to_cartesian().x.unit == u.one:
# if no distance, just use the coordinate direction to yield the
# infinite-distance/no parallax answer
newrep = UnitSphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False),
lon=u.Quantity(i_ra, u.radian, copy=False),
copy=False)
else:
# When there is a distance, apply the parallax/offset to the SSB as the
# last step - ensures round-tripping with the icrs_to_gcrs transform
# the distance in intermedrep is *not* a real distance as it does not
# include the offset back to the SSB
intermedrep = SphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False),
lon=u.Quantity(i_ra, u.radian, copy=False),
distance=srepr.distance,
copy=False)
astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au,
xyz_axis=-1, copy=False)
newrep = intermedrep + astrom_eb
return icrs_frame.realize_frame(newrep)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, GCRS)
def gcrs_to_gcrs(from_coo, to_frame):
if (np.all(from_coo.obstime == to_frame.obstime)
and np.all(from_coo.obsgeoloc == to_frame.obsgeoloc)):
return to_frame.realize_frame(from_coo.data)
else:
# like CIRS, we do this self-transform via ICRS
return from_coo.transform_to(ICRS).transform_to(to_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, HCRS)
def gcrs_to_hcrs(gcrs_coo, hcrs_frame):
if np.any(gcrs_coo.obstime != hcrs_frame.obstime):
# if they GCRS obstime and HCRS obstime are not the same, we first
# have to move to a GCRS where they are.
frameattrs = gcrs_coo.get_frame_attr_names()
frameattrs['obstime'] = hcrs_frame.obstime
gcrs_coo = gcrs_coo.transform_to(GCRS(**frameattrs))
srepr = gcrs_coo.represent_as(SphericalRepresentation)
gcrs_ra = srepr.lon.to_value(u.radian)
gcrs_dec = srepr.lat.to_value(u.radian)
# set up the astrometry context for ICRS<->GCRS and then convert to ICRS
# coordinate direction
pv = np.concatenate(
(gcrs_coo.obsgeoloc.get_xyz(xyz_axis=-1).value[..., np.newaxis, :],
gcrs_coo.obsgeovel.get_xyz(xyz_axis=-1).value[..., np.newaxis, :]),
axis=-2)
jd1, jd2 = get_jd12(hcrs_frame.obstime, 'tdb')
earth_pv, earth_heliocentric = prepare_earth_position_vel(gcrs_coo.obstime)
astrom = erfa.apcs(jd1, jd2, pv, earth_pv, earth_heliocentric)
i_ra, i_dec = aticq(gcrs_ra, gcrs_dec, astrom)
# convert to Quantity objects
i_ra = u.Quantity(i_ra, u.radian, copy=False)
i_dec = u.Quantity(i_dec, u.radian, copy=False)
if gcrs_coo.data.get_name() == 'unitspherical' or gcrs_coo.data.to_cartesian().x.unit == u.one:
# if no distance, just use the coordinate direction to yield the
# infinite-distance/no parallax answer
newrep = UnitSphericalRepresentation(lat=i_dec, lon=i_ra, copy=False)
else:
# When there is a distance, apply the parallax/offset to the
# Heliocentre as the last step to ensure round-tripping with the
# hcrs_to_gcrs transform
# Note that the distance in intermedrep is *not* a real distance as it
# does not include the offset back to the Heliocentre
intermedrep = SphericalRepresentation(lat=i_dec, lon=i_ra,
distance=srepr.distance,
copy=False)
# astrom['eh'] and astrom['em'] contain Sun to observer unit vector,
# and distance, respectively. Shapes are (X) and (X,3), where (X) is the
# shape resulting from broadcasting the shape of the times object
# against the shape of the pv array.
# broadcast em to eh and scale eh
eh = astrom['eh'] * astrom['em'][..., np.newaxis]
eh = CartesianRepresentation(eh, unit=u.au, xyz_axis=-1, copy=False)
newrep = intermedrep.to_cartesian() + eh
return hcrs_frame.realize_frame(newrep)
_NEED_ORIGIN_HINT = ("The input {0} coordinates do not have length units. This "
"probably means you created coordinates with lat/lon but "
"no distance. Heliocentric<->ICRS transforms cannot "
"function in this case because there is an origin shift.")
@frame_transform_graph.transform(AffineTransform, HCRS, ICRS)
def hcrs_to_icrs(hcrs_coo, icrs_frame):
# this is just an origin translation so without a distance it cannot go ahead
if isinstance(hcrs_coo.data, UnitSphericalRepresentation):
raise u.UnitsError(_NEED_ORIGIN_HINT.format(hcrs_coo.__class__.__name__))
if hcrs_coo.data.differentials:
from ..solar_system import get_body_barycentric_posvel
bary_sun_pos, bary_sun_vel = get_body_barycentric_posvel('sun',
hcrs_coo.obstime)
bary_sun_pos = bary_sun_pos.with_differentials(bary_sun_vel)
else:
from ..solar_system import get_body_barycentric
bary_sun_pos = get_body_barycentric('sun', hcrs_coo.obstime)
bary_sun_vel = None
return None, bary_sun_pos
@frame_transform_graph.transform(AffineTransform, ICRS, HCRS)
def icrs_to_hcrs(icrs_coo, hcrs_frame):
# this is just an origin translation so without a distance it cannot go ahead
if isinstance(icrs_coo.data, UnitSphericalRepresentation):
raise u.UnitsError(_NEED_ORIGIN_HINT.format(icrs_coo.__class__.__name__))
if icrs_coo.data.differentials:
from ..solar_system import get_body_barycentric_posvel
bary_sun_pos, bary_sun_vel = get_body_barycentric_posvel('sun',
hcrs_frame.obstime)
bary_sun_pos = -bary_sun_pos.with_differentials(-bary_sun_vel)
else:
from ..solar_system import get_body_barycentric
bary_sun_pos = -get_body_barycentric('sun', hcrs_frame.obstime)
bary_sun_vel = None
return None, bary_sun_pos
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, HCRS, HCRS)
def hcrs_to_hcrs(from_coo, to_frame):
if np.all(from_coo.obstime == to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
else:
# like CIRS, we do this self-transform via ICRS
return from_coo.transform_to(ICRS).transform_to(to_frame)
|
15c484e917adbf2e2b4caba0cdf977e721494bbe76570cac8a07b1fdd5ce6e72 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import units as u
from ...utils.compat import namedtuple_asdict
from .. import representation as r
from ..transformations import DynamicMatrixTransform, FunctionTransform
from ..baseframe import (frame_transform_graph, RepresentationMapping,
BaseCoordinateFrame)
from ..attributes import CoordinateAttribute, QuantityAttribute
from ..matrix_utilities import (rotation_matrix,
matrix_product, matrix_transpose)
_skyoffset_cache = {}
def make_skyoffset_cls(framecls):
"""
Create a new class that is the sky offset frame for a specific class of
origin frame. If such a class has already been created for this frame, the
same class will be returned.
The new class will always have component names for spherical coordinates of
``lon``/``lat``.
Parameters
----------
framecls : coordinate frame class (i.e., subclass of `~astropy.coordinates.BaseCoordinateFrame`)
The class to create the SkyOffsetFrame of.
Returns
-------
skyoffsetframecls : class
The class for the new skyoffset frame.
Notes
-----
This function is necessary because Astropy's frame transformations depend
on connection between specific frame *classes*. So each type of frame
needs its own distinct skyoffset frame class. This function generates
just that class, as well as ensuring that only one example of such a class
actually gets created in any given python session.
"""
if framecls in _skyoffset_cache:
return _skyoffset_cache[framecls]
# the class of a class object is the metaclass
framemeta = framecls.__class__
class SkyOffsetMeta(framemeta):
"""
This metaclass renames the class to be "SkyOffset<framecls>" and also
adjusts the frame specific representation info so that spherical names
are always "lon" and "lat" (instead of e.g. "ra" and "dec").
"""
def __new__(cls, name, bases, members):
# Only 'origin' is needed here, to set the origin frame properly.
members['origin'] = CoordinateAttribute(frame=framecls, default=None)
# This has to be done because FrameMeta will set these attributes
# to the defaults from BaseCoordinateFrame when it creates the base
# SkyOffsetFrame class initially.
members['_default_representation'] = framecls._default_representation
members['_default_differential'] = framecls._default_differential
newname = name[:-5] if name.endswith('Frame') else name
newname += framecls.__name__
return super().__new__(cls, newname, bases, members)
# We need this to handle the intermediate metaclass correctly, otherwise we could
# just subclass SkyOffsetFrame.
_SkyOffsetFramecls = SkyOffsetMeta('SkyOffsetFrame', (SkyOffsetFrame, framecls),
{'__doc__': SkyOffsetFrame.__doc__})
@frame_transform_graph.transform(FunctionTransform, _SkyOffsetFramecls, _SkyOffsetFramecls)
def skyoffset_to_skyoffset(from_skyoffset_coord, to_skyoffset_frame):
"""Transform between two skyoffset frames."""
# This transform goes through the parent frames on each side.
# from_frame -> from_frame.origin -> to_frame.origin -> to_frame
intermediate_from = from_skyoffset_coord.transform_to(from_skyoffset_coord.origin)
intermediate_to = intermediate_from.transform_to(to_skyoffset_frame.origin)
return intermediate_to.transform_to(to_skyoffset_frame)
@frame_transform_graph.transform(DynamicMatrixTransform, framecls, _SkyOffsetFramecls)
def reference_to_skyoffset(reference_frame, skyoffset_frame):
"""Convert a reference coordinate to an sky offset frame."""
# Define rotation matrices along the position angle vector, and
# relative to the origin.
origin = skyoffset_frame.origin.spherical
mat1 = rotation_matrix(-skyoffset_frame.rotation, 'x')
mat2 = rotation_matrix(-origin.lat, 'y')
mat3 = rotation_matrix(origin.lon, 'z')
return matrix_product(mat1, mat2, mat3)
@frame_transform_graph.transform(DynamicMatrixTransform, _SkyOffsetFramecls, framecls)
def skyoffset_to_reference(skyoffset_coord, reference_frame):
"""Convert an sky offset frame coordinate to the reference frame"""
# use the forward transform, but just invert it
R = reference_to_skyoffset(reference_frame, skyoffset_coord)
# transpose is the inverse because R is a rotation matrix
return matrix_transpose(R)
_skyoffset_cache[framecls] = _SkyOffsetFramecls
return _SkyOffsetFramecls
class SkyOffsetFrame(BaseCoordinateFrame):
"""
A frame which is relative to some specific position and oriented to match
its frame.
SkyOffsetFrames always have component names for spherical coordinates
of ``lon``/``lat``, *not* the component names for the frame of ``origin``.
This is useful for calculating offsets and dithers in the frame of the sky
relative to an arbitrary position. Coordinates in this frame are both centered on the position specified by the
``origin`` coordinate, *and* they are oriented in the same manner as the
``origin`` frame. E.g., if ``origin`` is `~astropy.coordinates.ICRS`, this
object's ``lat`` will be pointed in the direction of Dec, while ``lon``
will point in the direction of RA.
For more on skyoffset frames, see :ref:`astropy-skyoffset-frames`.
Parameters
----------
representation : `BaseRepresentation` or None
A representation object or None to have no data (or use the other keywords)
origin : `SkyCoord` or low-level coordinate object.
the coordinate which specifies the origin of this frame.
rotation : `~astropy.coordinates.Angle` or `~astropy.units.Quantity` with angle units
The final rotation of the frame about the ``origin``. The sign of
the rotation is the left-hand rule. That is, an object at a
particular position angle in the un-rotated system will be sent to
the positive latitude (z) direction in the final frame.
Notes
-----
``SkyOffsetFrame`` is a factory class. That is, the objects that it
yields are *not* actually objects of class ``SkyOffsetFrame``. Instead,
distinct classes are created on-the-fly for whatever the frame class is
of ``origin``.
"""
rotation = QuantityAttribute(default=0, unit=u.deg)
origin = CoordinateAttribute(default=None, frame=None)
def __new__(cls, *args, **kwargs):
# We don't want to call this method if we've already set up
# an skyoffset frame for this class.
if not (issubclass(cls, SkyOffsetFrame) and cls is not SkyOffsetFrame):
# We get the origin argument, and handle it here.
try:
origin_frame = kwargs['origin']
except KeyError:
raise TypeError("Can't initialize an SkyOffsetFrame without origin= keyword.")
if hasattr(origin_frame, 'frame'):
origin_frame = origin_frame.frame
newcls = make_skyoffset_cls(origin_frame.__class__)
return newcls.__new__(newcls, *args, **kwargs)
# http://stackoverflow.com/questions/19277399/why-does-object-new-work-differently-in-these-three-cases
# See above for why this is necessary. Basically, because some child
# may override __new__, we must override it here to never pass
# arguments to the object.__new__ method.
if super().__new__ is object.__new__:
return super().__new__(cls)
return super().__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.origin is not None and not self.origin.has_data:
raise ValueError('The origin supplied to SkyOffsetFrame has no '
'data.')
if self.has_data and hasattr(self.data, 'lon'):
self.data.lon.wrap_angle = 180*u.deg
|
d69afe8a7a18828f6cf27705ce1cd1336d1803bc95f58663915b3871a3fc1154 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Contains the transformation functions for getting to "observed" systems from CIRS.
Currently that just means AltAz.
"""
import numpy as np
from ... import units as u
from ..baseframe import frame_transform_graph
from ..transformations import FunctionTransformWithFiniteDifference
from ..representation import (SphericalRepresentation,
UnitSphericalRepresentation)
from ... import _erfa as erfa
from .cirs import CIRS
from .altaz import AltAz
from .utils import get_polar_motion, get_dut1utc, get_jd12, PIOVER2
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, AltAz)
def cirs_to_altaz(cirs_coo, altaz_frame):
if np.any(cirs_coo.obstime != altaz_frame.obstime):
# the only frame attribute for the current CIRS is the obstime, but this
# would need to be updated if a future change allowed specifying an
# Earth location algorithm or something
cirs_coo = cirs_coo.transform_to(CIRS(obstime=altaz_frame.obstime))
# we use the same obstime everywhere now that we know they're the same
obstime = cirs_coo.obstime
# if the data are UnitSphericalRepresentation, we can skip the distance calculations
is_unitspherical = (isinstance(cirs_coo.data, UnitSphericalRepresentation) or
cirs_coo.cartesian.x.unit == u.one)
if is_unitspherical:
usrepr = cirs_coo.represent_as(UnitSphericalRepresentation)
cirs_ra = usrepr.lon.to_value(u.radian)
cirs_dec = usrepr.lat.to_value(u.radian)
else:
# compute an "astrometric" ra/dec -i.e., the direction of the
# displacement vector from the observer to the target in CIRS
loccirs = altaz_frame.location.get_itrs(cirs_coo.obstime).transform_to(cirs_coo)
diffrepr = (cirs_coo.cartesian - loccirs.cartesian).represent_as(UnitSphericalRepresentation)
cirs_ra = diffrepr.lon.to_value(u.radian)
cirs_dec = diffrepr.lat.to_value(u.radian)
lon, lat, height = altaz_frame.location.to_geodetic('WGS84')
xp, yp = get_polar_motion(obstime)
# first set up the astrometry context for CIRS<->AltAz
jd1, jd2 = get_jd12(obstime, 'utc')
astrom = erfa.apio13(jd1, jd2,
get_dut1utc(obstime),
lon.to_value(u.radian), lat.to_value(u.radian),
height.to_value(u.m),
xp, yp, # polar motion
# all below are already in correct units because they are QuantityFrameAttribues
altaz_frame.pressure.value,
altaz_frame.temperature.value,
altaz_frame.relative_humidity,
altaz_frame.obswl.value)
az, zen, _, _, _ = erfa.atioq(cirs_ra, cirs_dec, astrom)
if is_unitspherical:
rep = UnitSphericalRepresentation(lat=u.Quantity(PIOVER2 - zen, u.radian, copy=False),
lon=u.Quantity(az, u.radian, copy=False),
copy=False)
else:
# now we get the distance as the cartesian distance from the earth
# location to the coordinate location
locitrs = altaz_frame.location.get_itrs(obstime)
distance = locitrs.separation_3d(cirs_coo)
rep = SphericalRepresentation(lat=u.Quantity(PIOVER2 - zen, u.radian, copy=False),
lon=u.Quantity(az, u.radian, copy=False),
distance=distance,
copy=False)
return altaz_frame.realize_frame(rep)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, AltAz, CIRS)
def altaz_to_cirs(altaz_coo, cirs_frame):
usrepr = altaz_coo.represent_as(UnitSphericalRepresentation)
az = usrepr.lon.to_value(u.radian)
zen = PIOVER2 - usrepr.lat.to_value(u.radian)
lon, lat, height = altaz_coo.location.to_geodetic('WGS84')
xp, yp = get_polar_motion(altaz_coo.obstime)
# first set up the astrometry context for ICRS<->CIRS at the altaz_coo time
jd1, jd2 = get_jd12(altaz_coo.obstime, 'utc')
astrom = erfa.apio13(jd1, jd2,
get_dut1utc(altaz_coo.obstime),
lon.to_value(u.radian), lat.to_value(u.radian),
height.to_value(u.m),
xp, yp, # polar motion
# all below are already in correct units because they are QuantityFrameAttribues
altaz_coo.pressure.value,
altaz_coo.temperature.value,
altaz_coo.relative_humidity,
altaz_coo.obswl.value)
# the 'A' indicates zen/az inputs
cirs_ra, cirs_dec = erfa.atoiq('A', az, zen, astrom)*u.radian
if isinstance(altaz_coo.data, UnitSphericalRepresentation) or altaz_coo.cartesian.x.unit == u.one:
cirs_at_aa_time = CIRS(ra=cirs_ra, dec=cirs_dec, distance=None,
obstime=altaz_coo.obstime)
else:
# treat the output of atoiq as an "astrometric" RA/DEC, so to get the
# actual RA/Dec from the observers vantage point, we have to reverse
# the vector operation of cirs_to_altaz (see there for more detail)
loccirs = altaz_coo.location.get_itrs(altaz_coo.obstime).transform_to(cirs_frame)
astrometric_rep = SphericalRepresentation(lon=cirs_ra, lat=cirs_dec,
distance=altaz_coo.distance)
newrepr = astrometric_rep + loccirs.cartesian
cirs_at_aa_time = CIRS(newrepr, obstime=altaz_coo.obstime)
# this final transform may be a no-op if the obstimes are the same
return cirs_at_aa_time.transform_to(cirs_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, AltAz, AltAz)
def altaz_to_altaz(from_coo, to_frame):
# for now we just implement this through CIRS to make sure we get everything
# covered
return from_coo.transform_to(CIRS(obstime=from_coo.obstime)).transform_to(to_frame)
|
cd0e192b82faa3b478607a275e7cac394ea68bc1291e1c9bb352b2c80e9668ff | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from ... import units as u
from ...utils.decorators import format_doc
from .. import representation as r
from ..baseframe import BaseCoordinateFrame, RepresentationMapping, base_doc
from ..attributes import (Attribute, TimeAttribute,
QuantityAttribute, EarthLocationAttribute)
__all__ = ['AltAz']
_90DEG = 90*u.deg
doc_components = """
az : `Angle`, optional, must be keyword
The Azimuth for this object (``alt`` must also be given and
``representation`` must be None).
alt : `Angle`, optional, must be keyword
The Altitude for this object (``az`` must also be given and
``representation`` must be None).
distance : :class:`~astropy.units.Quantity`, optional, must be keyword
The Distance for this object along the line-of-sight.
pm_az_cosalt : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in azimuth (including the ``cos(alt)`` factor) for
this object (``pm_alt`` must also be given).
pm_alt : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in altitude for this object (``pm_az_cosalt`` must
also be given).
radial_velocity : :class:`~astropy.units.Quantity`, optional, must be keyword
The radial velocity of this object."""
doc_footer = """
Other parameters
----------------
obstime : `~astropy.time.Time`
The time at which the observation is taken. Used for determining the
position and orientation of the Earth.
location : `~astropy.coordinates.EarthLocation`
The location on the Earth. This can be specified either as an
`~astropy.coordinates.EarthLocation` object or as anything that can be
transformed to an `~astropy.coordinates.ITRS` frame.
pressure : `~astropy.units.Quantity`
The atmospheric pressure as an `~astropy.units.Quantity` with pressure
units. This is necessary for performing refraction corrections.
Setting this to 0 (the default) will disable refraction calculations
when transforming to/from this frame.
temperature : `~astropy.units.Quantity`
The ground-level temperature as an `~astropy.units.Quantity` in
deg C. This is necessary for performing refraction corrections.
relative_humidity`` : numeric
The relative humidity as a number from 0 to 1. This is necessary for
performing refraction corrections.
obswl : `~astropy.units.Quantity`
The average wavelength of observations as an `~astropy.units.Quantity`
with length units. This is necessary for performing refraction
corrections.
Notes
-----
The refraction model is based on that implemented in ERFA, which is fast
but becomes inaccurate for altitudes below about 5 degrees. Near and below
altitudes of 0, it can even give meaningless answers, and in this case
transforming to AltAz and back to another frame can give highly discrepent
results. For much better numerical stability, leaving the ``pressure`` at
``0`` (the default), disabling the refraction correction (yielding
"topocentric" horizontal coordinates).
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer)
class AltAz(BaseCoordinateFrame):
"""
A coordinate or frame in the Altitude-Azimuth system (Horizontal
coordinates). Azimuth is oriented East of North (i.e., N=0, E=90 degrees).
This frame is assumed to *include* refraction effects if the ``pressure``
frame attribute is non-zero.
The frame attributes are listed under **Other Parameters**, which are
necessary for transforming from AltAz to some other system.
"""
frame_specific_representation_info = {
r.SphericalRepresentation: [
RepresentationMapping('lon', 'az'),
RepresentationMapping('lat', 'alt')
]
}
default_representation = r.SphericalRepresentation
default_differential = r.SphericalCosLatDifferential
obstime = TimeAttribute(default=None)
location = EarthLocationAttribute(default=None)
pressure = QuantityAttribute(default=0, unit=u.hPa)
temperature = QuantityAttribute(default=0, unit=u.deg_C)
relative_humidity = Attribute(default=0)
obswl = QuantityAttribute(default=1*u.micron, unit=u.micron)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def secz(self):
"""
Secant if the zenith angle for this coordinate, a common estimate of the
airmass.
"""
return 1/np.sin(self.alt)
@property
def zen(self):
"""
The zenith angle for this coordinate
"""
return _90DEG.to(self.alt.unit) - self.alt
# self-transform defined in cirs_observed_transforms.py
|
f5c7c47b4de20d25ba5328831489851416f3710b60a8e8d5a8336a361c56af6a | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from ..baseframe import frame_transform_graph
from ..transformations import DynamicMatrixTransform
from ..matrix_utilities import matrix_product, matrix_transpose
from .fk4 import FK4NoETerms
from .fk5 import FK5
from .utils import EQUINOX_B1950, EQUINOX_J2000
# FK5 to/from FK4 ------------------->
# B1950->J2000 matrix from Murray 1989 A&A 218,325 eqn 28
_B1950_TO_J2000_M = np.array(
[[0.9999256794956877, -0.0111814832204662, -0.0048590038153592],
[0.0111814832391717, 0.9999374848933135, -0.0000271625947142],
[0.0048590037723143, -0.0000271702937440, 0.9999881946023742]])
_FK4_CORR = np.array(
[[-0.0026455262, -1.1539918689, +2.1111346190],
[+1.1540628161, -0.0129042997, +0.0236021478],
[-2.1112979048, -0.0056024448, +0.0102587734]]) * 1.e-6
def _fk4_B_matrix(obstime):
"""
This is a correction term in the FK4 transformations because FK4 is a
rotating system - see Murray 89 eqn 29
"""
# Note this is *julian century*, not besselian
T = (obstime.jyear - 1950.) / 100.
if getattr(T, 'shape', ()):
# Ensure we broadcast possibly arrays of times properly.
T.shape += (1, 1)
return _B1950_TO_J2000_M + _FK4_CORR * T
# This transformation can't be static because the observation date is needed.
@frame_transform_graph.transform(DynamicMatrixTransform, FK4NoETerms, FK5)
def fk4_no_e_to_fk5(fk4noecoord, fk5frame):
# Correction terms for FK4 being a rotating system
B = _fk4_B_matrix(fk4noecoord.obstime)
# construct both precession matricies - if the equinoxes are B1950 and
# J2000, these are just identity matricies
pmat1 = fk4noecoord._precession_matrix(fk4noecoord.equinox, EQUINOX_B1950)
pmat2 = fk5frame._precession_matrix(EQUINOX_J2000, fk5frame.equinox)
return matrix_product(pmat2, B, pmat1)
# This transformation can't be static because the observation date is needed.
@frame_transform_graph.transform(DynamicMatrixTransform, FK5, FK4NoETerms)
def fk5_to_fk4_no_e(fk5coord, fk4noeframe):
# Get transposed version of the rotating correction terms... so with the
# transpose this takes us from FK5/J200 to FK4/B1950
B = matrix_transpose(_fk4_B_matrix(fk4noeframe.obstime))
# construct both precession matricies - if the equinoxes are B1950 and
# J2000, these are just identity matricies
pmat1 = fk5coord._precession_matrix(fk5coord.equinox, EQUINOX_J2000)
pmat2 = fk4noeframe._precession_matrix(EQUINOX_B1950, fk4noeframe.equinox)
return matrix_product(pmat2, B, pmat1)
|
d186499012de99a285cc8ebcd0835971bac35d6958e896a0df93c8e031e18d9a | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import units as u
from ...utils.decorators import format_doc
from ...time import Time
from .. import representation as r
from ..baseframe import (BaseCoordinateFrame, RepresentationMapping,
frame_transform_graph, base_doc)
from ..transformations import AffineTransform
from ..attributes import DifferentialAttribute
from .baseradec import BaseRADecFrame, doc_components as doc_components_radec
from .icrs import ICRS
from .galactic import Galactic
# For speed
J2000 = Time('J2000')
v_bary_Schoenrich2010 = r.CartesianDifferential([11.1, 12.24, 7.25]*u.km/u.s)
__all__ = ['LSR', 'GalacticLSR']
doc_footer_lsr = """
Other parameters
----------------
v_bary : `~astropy.coordinates.representation.CartesianDifferential`
The velocity of the solar system barycenter with respect to the LSR, in
Galactic cartesian velocity components.
"""
@format_doc(base_doc, components=doc_components_radec, footer=doc_footer_lsr)
class LSR(BaseRADecFrame):
r"""A coordinate or frame in the Local Standard of Rest (LSR).
This coordinate frame is axis-aligned and co-spatial with `ICRS`, but has
a velocity offset relative to the solar system barycenter to remove the
peculiar motion of the sun relative to the LSR. Roughly, the LSR is the mean
velocity of the stars in the solar neighborhood, but the precise definition
of which depends on the study. As defined in Schönrich et al. (2010):
"The LSR is the rest frame at the location of the Sun of a star that would
be on a circular orbit in the gravitational potential one would obtain by
azimuthally averaging away non-axisymmetric features in the actual Galactic
potential." No such orbit truly exists, but it is still a commonly used
velocity frame.
We use default values from Schönrich et al. (2010) for the barycentric
velocity relative to the LSR, which is defined in Galactic (right-handed)
cartesian velocity components
:math:`(U, V, W) = (11.1, 12.24, 7.25)~{{\rm km}}~{{\rm s}}^{{-1}}`. These
values are customizable via the ``v_bary`` argument which specifies the
velocity of the solar system barycenter with respect to the LSR.
The frame attributes are listed under **Other Parameters**.
"""
# frame attributes:
v_bary = DifferentialAttribute(default=v_bary_Schoenrich2010,
allowed_classes=[r.CartesianDifferential])
@frame_transform_graph.transform(AffineTransform, ICRS, LSR)
def icrs_to_lsr(icrs_coord, lsr_frame):
v_bary_gal = Galactic(lsr_frame.v_bary.to_cartesian())
v_bary_icrs = v_bary_gal.transform_to(icrs_coord)
v_offset = v_bary_icrs.data.represent_as(r.CartesianDifferential)
offset = r.CartesianRepresentation([0, 0, 0]*u.au, differentials=v_offset)
return None, offset
@frame_transform_graph.transform(AffineTransform, LSR, ICRS)
def lsr_to_icrs(lsr_coord, icrs_frame):
v_bary_gal = Galactic(lsr_coord.v_bary.to_cartesian())
v_bary_icrs = v_bary_gal.transform_to(icrs_frame)
v_offset = v_bary_icrs.data.represent_as(r.CartesianDifferential)
offset = r.CartesianRepresentation([0, 0, 0]*u.au, differentials=-v_offset)
return None, offset
# ------------------------------------------------------------------------------
doc_components_gal = """
l : `Angle`, optional, must be keyword
The Galactic longitude for this object (``b`` must also be given and
``representation`` must be None).
b : `Angle`, optional, must be keyword
The Galactic latitude for this object (``l`` must also be given and
``representation`` must be None).
distance : `~astropy.units.Quantity`, optional, must be keyword
The Distance for this object along the line-of-sight.
(``representation`` must be None).
pm_l_cosb : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Galactic longitude (including the ``cos(b)`` term)
for this object (``pm_b`` must also be given).
pm_b : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Galactic latitude for this object (``pm_l_cosb``
must also be given).
radial_velocity : :class:`~astropy.units.Quantity`, optional, must be keyword
The radial velocity of this object.
"""
@format_doc(base_doc, components=doc_components_gal, footer=doc_footer_lsr)
class GalacticLSR(BaseCoordinateFrame):
r"""A coordinate or frame in the Local Standard of Rest (LSR), axis-aligned
to the `Galactic` frame.
This coordinate frame is axis-aligned and co-spatial with `ICRS`, but has
a velocity offset relative to the solar system barycenter to remove the
peculiar motion of the sun relative to the LSR. Roughly, the LSR is the mean
velocity of the stars in the solar neighborhood, but the precise definition
of which depends on the study. As defined in Schönrich et al. (2010):
"The LSR is the rest frame at the location of the Sun of a star that would
be on a circular orbit in the gravitational potential one would obtain by
azimuthally averaging away non-axisymmetric features in the actual Galactic
potential." No such orbit truly exists, but it is still a commonly used
velocity frame.
We use default values from Schönrich et al. (2010) for the barycentric
velocity relative to the LSR, which is defined in Galactic (right-handed)
cartesian velocity components
:math:`(U, V, W) = (11.1, 12.24, 7.25)~{{\rm km}}~{{\rm s}}^{{-1}}`. These
values are customizable via the ``v_bary`` argument which specifies the
velocity of the solar system barycenter with respect to the LSR.
The frame attributes are listed under **Other Parameters**.
"""
frame_specific_representation_info = {
r.SphericalRepresentation: [
RepresentationMapping('lon', 'l'),
RepresentationMapping('lat', 'b')
]
}
default_representation = r.SphericalRepresentation
default_differential = r.SphericalCosLatDifferential
# frame attributes:
v_bary = DifferentialAttribute(default=v_bary_Schoenrich2010)
@frame_transform_graph.transform(AffineTransform, Galactic, GalacticLSR)
def galactic_to_galacticlsr(galactic_coord, lsr_frame):
v_bary_gal = Galactic(lsr_frame.v_bary.to_cartesian())
v_offset = v_bary_gal.data.represent_as(r.CartesianDifferential)
offset = r.CartesianRepresentation([0, 0, 0]*u.au, differentials=v_offset)
return None, offset
@frame_transform_graph.transform(AffineTransform, GalacticLSR, Galactic)
def galacticlsr_to_galactic(lsr_coord, galactic_frame):
v_bary_gal = Galactic(lsr_coord.v_bary.to_cartesian())
v_offset = v_bary_gal.data.represent_as(r.CartesianDifferential)
offset = r.CartesianRepresentation([0, 0, 0]*u.au, differentials=-v_offset)
return None, offset
|
188ac8bba24b48317f6fa68699a8857f9174904f8eeb69e2ed0b001403ac7043 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ..matrix_utilities import (rotation_matrix,
matrix_product, matrix_transpose)
from ..baseframe import frame_transform_graph
from ..transformations import DynamicMatrixTransform
from .fk5 import FK5
from .fk4 import FK4NoETerms
from .utils import EQUINOX_B1950, EQUINOX_J2000
from .galactic import Galactic
# Galactic to/from FK4/FK5 ----------------------->
# can't be static because the equinox is needed
@frame_transform_graph.transform(DynamicMatrixTransform, FK5, Galactic)
def fk5_to_gal(fk5coord, galframe):
# need precess to J2000 first
pmat = fk5coord._precession_matrix(fk5coord.equinox, EQUINOX_J2000)
mat1 = rotation_matrix(180 - Galactic._lon0_J2000.degree, 'z')
mat2 = rotation_matrix(90 - Galactic._ngp_J2000.dec.degree, 'y')
mat3 = rotation_matrix(Galactic._ngp_J2000.ra.degree, 'z')
return matrix_product(mat1, mat2, mat3, pmat)
@frame_transform_graph.transform(DynamicMatrixTransform, Galactic, FK5)
def _gal_to_fk5(galcoord, fk5frame):
return matrix_transpose(fk5_to_gal(fk5frame, galcoord))
@frame_transform_graph.transform(DynamicMatrixTransform, FK4NoETerms, Galactic)
def fk4_to_gal(fk4coords, galframe):
mat1 = rotation_matrix(180 - Galactic._lon0_B1950.degree, 'z')
mat2 = rotation_matrix(90 - Galactic._ngp_B1950.dec.degree, 'y')
mat3 = rotation_matrix(Galactic._ngp_B1950.ra.degree, 'z')
matprec = fk4coords._precession_matrix(fk4coords.equinox, EQUINOX_B1950)
return matrix_product(mat1, mat2, mat3, matprec)
@frame_transform_graph.transform(DynamicMatrixTransform, Galactic, FK4NoETerms)
def gal_to_fk4(galcoords, fk4frame):
return matrix_transpose(fk4_to_gal(fk4frame, galcoords))
|
2cc24587958b6e5bb0e8b41cd48b925160ec3a185dae69eff9f10b38f4bbb3d3 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import units as u
from ...utils.decorators import format_doc
from ..angles import Angle
from .. import representation as r
from ..baseframe import BaseCoordinateFrame, RepresentationMapping, base_doc
# these are needed for defining the NGP
from .fk5 import FK5
from .fk4 import FK4NoETerms
__all__ = ['Galactic']
doc_components = """
l : `Angle`, optional, must be keyword
The Galactic longitude for this object (``b`` must also be given and
``representation`` must be None).
b : `Angle`, optional, must be keyword
The Galactic latitude for this object (``l`` must also be given and
``representation`` must be None).
distance : `~astropy.units.Quantity`, optional, must be keyword
The Distance for this object along the line-of-sight.
pm_l_cosb : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Galactic longitude (including the ``cos(b)`` term)
for this object (``pm_b`` must also be given).
pm_b : :class:`~astropy.units.Quantity`, optional, must be keyword
The proper motion in Galactic latitude for this object (``pm_l_cosb``
must also be given).
radial_velocity : :class:`~astropy.units.Quantity`, optional, must be keyword
The radial velocity of this object.
"""
doc_footer = """
Notes
-----
.. [1] Blaauw, A.; Gum, C. S.; Pawsey, J. L.; Westerhout, G. (1960), "The
new I.A.U. system of galactic coordinates (1958 revision),"
`MNRAS, Vol 121, pp.123 <http://adsabs.harvard.edu/abs/1960MNRAS.121..123B>`_.
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer)
class Galactic(BaseCoordinateFrame):
"""
A coordinate or frame in the Galactic coordinate system.
This frame is used in a variety of Galactic contexts because it has as its
x-y plane the plane of the Milky Way. The positive x direction (i.e., the
l=0, b=0 direction) points to the center of the Milky Way and the z-axis
points toward the North Galactic Pole (following the IAU's 1958 definition
[1]_). However, unlike the `~astropy.coordinates.Galactocentric` frame, the
*origin* of this frame in 3D space is the solar system barycenter, not
the center of the Milky Way.
"""
frame_specific_representation_info = {
r.SphericalRepresentation: [
RepresentationMapping('lon', 'l'),
RepresentationMapping('lat', 'b')
],
r.CartesianRepresentation: [
RepresentationMapping('x', 'u'),
RepresentationMapping('y', 'v'),
RepresentationMapping('z', 'w')
],
r.CartesianDifferential: [
RepresentationMapping('d_x', 'U', u.km/u.s),
RepresentationMapping('d_y', 'V', u.km/u.s),
RepresentationMapping('d_z', 'W', u.km/u.s)
]
}
default_representation = r.SphericalRepresentation
default_differential = r.SphericalCosLatDifferential
# North galactic pole and zeropoint of l in FK4/FK5 coordinates. Needed for
# transformations to/from FK4/5
# These are from the IAU's definition of galactic coordinates
_ngp_B1950 = FK4NoETerms(ra=192.25*u.degree, dec=27.4*u.degree)
_lon0_B1950 = Angle(123, u.degree)
# These are *not* from Reid & Brunthaler 2004 - instead, they were
# derived by doing:
#
# >>> FK4NoETerms(ra=192.25*u.degree, dec=27.4*u.degree).transform_to(FK5)
#
# This gives better consistency with other codes than using the values
# from Reid & Brunthaler 2004 and the best self-consistency between FK5
# -> Galactic and FK5 -> FK4 -> Galactic. The lon0 angle was found by
# optimizing the self-consistency.
_ngp_J2000 = FK5(ra=192.8594812065348*u.degree, dec=27.12825118085622*u.degree)
_lon0_J2000 = Angle(122.9319185680026, u.degree)
|
7deb275c93689d059e7851fd2b9b39096faf76b07449d041d86a499d9baa8551 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ..matrix_utilities import (rotation_matrix,
matrix_product, matrix_transpose)
from ..baseframe import frame_transform_graph
from ..transformations import DynamicMatrixTransform
from .fk5 import FK5
from .icrs import ICRS
from .utils import EQUINOX_J2000
def _icrs_to_fk5_matrix():
"""
B-matrix from USNO circular 179. Used by the ICRS->FK5 transformation
functions.
"""
eta0 = -19.9 / 3600000.
xi0 = 9.1 / 3600000.
da0 = -22.9 / 3600000.
m1 = rotation_matrix(-eta0, 'x')
m2 = rotation_matrix(xi0, 'y')
m3 = rotation_matrix(da0, 'z')
return matrix_product(m1, m2, m3)
# define this here because it only needs to be computed once
_ICRS_TO_FK5_J2000_MAT = _icrs_to_fk5_matrix()
@frame_transform_graph.transform(DynamicMatrixTransform, ICRS, FK5)
def icrs_to_fk5(icrscoord, fk5frame):
# ICRS is by design very close to J2000 equinox
pmat = fk5frame._precession_matrix(EQUINOX_J2000, fk5frame.equinox)
return matrix_product(pmat, _ICRS_TO_FK5_J2000_MAT)
# can't be static because the equinox is needed
@frame_transform_graph.transform(DynamicMatrixTransform, FK5, ICRS)
def fk5_to_icrs(fk5coord, icrsframe):
# ICRS is by design very close to J2000 equinox
pmat = fk5coord._precession_matrix(fk5coord.equinox, EQUINOX_J2000)
return matrix_product(matrix_transpose(_ICRS_TO_FK5_J2000_MAT), pmat)
|
b369e0f64152b0b9d8567758b5915a85ecede39c5eaf74f6812caa4a4edb7a02 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ...utils.decorators import format_doc
from ..attributes import TimeAttribute
from ..baseframe import base_doc
from .baseradec import doc_components, BaseRADecFrame
from .utils import DEFAULT_OBSTIME
__all__ = ['CIRS']
doc_footer = """
Other parameters
----------------
obstime : `~astropy.time.Time`
The time at which the observation is taken. Used for determining the
position of the Earth and its precession.
"""
@format_doc(base_doc, components=doc_components, footer=doc_footer)
class CIRS(BaseRADecFrame):
"""
A coordinate or frame in the Celestial Intermediate Reference System (CIRS).
The frame attributes are listed under **Other Parameters**.
"""
obstime = TimeAttribute(default=DEFAULT_OBSTIME)
# The "self-transform" is defined in icrs_cirs_transformations.py, because in
# the current implementation it goes through ICRS (like GCRS)
|
0ed1087e66bdc7cef426735e42cd7cca72a74f4a41ea6fc3a7b7fcdf80af60db | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from copy import deepcopy
import numpy as np
from ... import units as u
from ...tests.helper import (catch_warnings,
pytest, quantity_allclose as allclose,
assert_quantity_allclose as assert_allclose)
from ...utils import OrderedDescriptorContainer
from ...utils.compat import NUMPY_LT_1_14
from ...utils.exceptions import AstropyWarning
from .. import representation as r
from ..representation import REPRESENTATION_CLASSES
def setup_function(func):
func.REPRESENTATION_CLASSES_ORIG = deepcopy(REPRESENTATION_CLASSES)
def teardown_function(func):
REPRESENTATION_CLASSES.clear()
REPRESENTATION_CLASSES.update(func.REPRESENTATION_CLASSES_ORIG)
def test_frame_attribute_descriptor():
""" Unit tests of the Attribute descriptor """
from ..attributes import Attribute
class TestAttributes(metaclass=OrderedDescriptorContainer):
attr_none = Attribute()
attr_2 = Attribute(default=2)
attr_3_attr2 = Attribute(default=3, secondary_attribute='attr_2')
attr_none_attr2 = Attribute(default=None, secondary_attribute='attr_2')
attr_none_nonexist = Attribute(default=None, secondary_attribute='nonexist')
t = TestAttributes()
# Defaults
assert t.attr_none is None
assert t.attr_2 == 2
assert t.attr_3_attr2 == 3
assert t.attr_none_attr2 == t.attr_2
assert t.attr_none_nonexist is None # No default and non-existent secondary attr
# Setting values via '_'-prefixed internal vars (as would normally done in __init__)
t._attr_none = 10
assert t.attr_none == 10
t._attr_2 = 20
assert t.attr_2 == 20
assert t.attr_3_attr2 == 3
assert t.attr_none_attr2 == t.attr_2
t._attr_none_attr2 = 40
assert t.attr_none_attr2 == 40
# Make sure setting values via public attribute fails
with pytest.raises(AttributeError) as err:
t.attr_none = 5
assert 'Cannot set frame attribute' in str(err)
def test_frame_subclass_attribute_descriptor():
from ..builtin_frames import FK4
from ..attributes import Attribute, TimeAttribute
from astropy.time import Time
_EQUINOX_B1980 = Time('B1980', scale='tai')
class MyFK4(FK4):
# equinox inherited from FK4, obstime overridden, and newattr is new
obstime = TimeAttribute(default=_EQUINOX_B1980)
newattr = Attribute(default='newattr')
mfk4 = MyFK4()
assert mfk4.equinox.value == 'B1950.000'
assert mfk4.obstime.value == 'B1980.000'
assert mfk4.newattr == 'newattr'
assert set(mfk4.get_frame_attr_names()) == set(['equinox', 'obstime', 'newattr'])
mfk4 = MyFK4(equinox='J1980.0', obstime='J1990.0', newattr='world')
assert mfk4.equinox.value == 'J1980.000'
assert mfk4.obstime.value == 'J1990.000'
assert mfk4.newattr == 'world'
def test_create_data_frames():
from ..builtin_frames import ICRS
# from repr
i1 = ICRS(r.SphericalRepresentation(1*u.deg, 2*u.deg, 3*u.kpc))
i2 = ICRS(r.UnitSphericalRepresentation(lon=1*u.deg, lat=2*u.deg))
# from preferred name
i3 = ICRS(ra=1*u.deg, dec=2*u.deg, distance=3*u.kpc)
i4 = ICRS(ra=1*u.deg, dec=2*u.deg)
assert i1.data.lat == i3.data.lat
assert i1.data.lon == i3.data.lon
assert i1.data.distance == i3.data.distance
assert i2.data.lat == i4.data.lat
assert i2.data.lon == i4.data.lon
# now make sure the preferred names work as properties
assert_allclose(i1.ra, i3.ra)
assert_allclose(i2.ra, i4.ra)
assert_allclose(i1.distance, i3.distance)
with pytest.raises(AttributeError):
i1.ra = [11.]*u.deg
def test_create_orderered_data():
from ..builtin_frames import ICRS, Galactic, AltAz
TOL = 1e-10*u.deg
i = ICRS(1*u.deg, 2*u.deg)
assert (i.ra - 1*u.deg) < TOL
assert (i.dec - 2*u.deg) < TOL
g = Galactic(1*u.deg, 2*u.deg)
assert (g.l - 1*u.deg) < TOL
assert (g.b - 2*u.deg) < TOL
a = AltAz(1*u.deg, 2*u.deg)
assert (a.az - 1*u.deg) < TOL
assert (a.alt - 2*u.deg) < TOL
with pytest.raises(TypeError):
ICRS(1*u.deg, 2*u.deg, 1*u.deg, 2*u.deg)
with pytest.raises(TypeError):
sph = r.SphericalRepresentation(1*u.deg, 2*u.deg, 3*u.kpc)
ICRS(sph, 1*u.deg, 2*u.deg)
def test_create_nodata_frames():
from ..builtin_frames import ICRS, FK4, FK5
i = ICRS()
assert len(i.get_frame_attr_names()) == 0
f5 = FK5()
assert f5.equinox == FK5.get_frame_attr_names()['equinox']
f4 = FK4()
assert f4.equinox == FK4.get_frame_attr_names()['equinox']
# obstime is special because it's a property that uses equinox if obstime is not set
assert f4.obstime in (FK4.get_frame_attr_names()['obstime'],
FK4.get_frame_attr_names()['equinox'])
def test_no_data_nonscalar_frames():
from ..builtin_frames import AltAz
from astropy.time import Time
a1 = AltAz(obstime=Time('2012-01-01') + np.arange(10.) * u.day,
temperature=np.ones((3, 1)) * u.deg_C)
assert a1.obstime.shape == (3, 10)
assert a1.temperature.shape == (3, 10)
assert a1.shape == (3, 10)
with pytest.raises(ValueError) as exc:
AltAz(obstime=Time('2012-01-01') + np.arange(10.) * u.day,
temperature=np.ones((3,)) * u.deg_C)
assert 'inconsistent shapes' in str(exc)
def test_frame_repr():
from ..builtin_frames import ICRS, FK5
i = ICRS()
assert repr(i) == '<ICRS Frame>'
f5 = FK5()
assert repr(f5).startswith('<FK5 Frame (equinox=')
i2 = ICRS(ra=1*u.deg, dec=2*u.deg)
i3 = ICRS(ra=1*u.deg, dec=2*u.deg, distance=3*u.kpc)
assert repr(i2) == ('<ICRS Coordinate: (ra, dec) in deg\n'
' ({})>').format(' 1., 2.' if NUMPY_LT_1_14
else '1., 2.')
assert repr(i3) == ('<ICRS Coordinate: (ra, dec, distance) in (deg, deg, kpc)\n'
' ({})>').format(' 1., 2., 3.' if NUMPY_LT_1_14
else '1., 2., 3.')
# try with arrays
i2 = ICRS(ra=[1.1, 2.1]*u.deg, dec=[2.1, 3.1]*u.deg)
i3 = ICRS(ra=[1.1, 2.1]*u.deg, dec=[-15.6, 17.1]*u.deg, distance=[11., 21.]*u.kpc)
assert repr(i2) == ('<ICRS Coordinate: (ra, dec) in deg\n'
' [{}]>').format('( 1.1, 2.1), ( 2.1, 3.1)'
if NUMPY_LT_1_14 else
'(1.1, 2.1), (2.1, 3.1)')
if NUMPY_LT_1_14:
assert repr(i3) == ('<ICRS Coordinate: (ra, dec, distance) in (deg, deg, kpc)\n'
' [( 1.1, -15.6, 11.), ( 2.1, 17.1, 21.)]>')
else:
assert repr(i3) == ('<ICRS Coordinate: (ra, dec, distance) in (deg, deg, kpc)\n'
' [(1.1, -15.6, 11.), (2.1, 17.1, 21.)]>')
def test_frame_repr_vels():
from ..builtin_frames import ICRS
i = ICRS(ra=1*u.deg, dec=2*u.deg,
pm_ra_cosdec=1*u.marcsec/u.yr, pm_dec=2*u.marcsec/u.yr)
# unit comes out as mas/yr because of the preferred units defined in the
# frame RepresentationMapping
assert repr(i) == ('<ICRS Coordinate: (ra, dec) in deg\n'
' ({0})\n'
' (pm_ra_cosdec, pm_dec) in mas / yr\n'
' ({0})>').format(' 1., 2.' if NUMPY_LT_1_14 else
'1., 2.')
def test_converting_units():
import re
from ..baseframe import RepresentationMapping
from ..builtin_frames import ICRS, FK5
# this is a regular expression that with split (see below) removes what's
# the decimal point to fix rounding problems
rexrepr = re.compile(r'(.*?=\d\.).*?( .*?=\d\.).*?( .*)')
# Use values that aren't subject to rounding down to X.9999...
i2 = ICRS(ra=2.*u.deg, dec=2.*u.deg)
i2_many = ICRS(ra=[2., 4.]*u.deg, dec=[2., -8.1]*u.deg)
# converting from FK5 to ICRS and back changes the *internal* representation,
# but it should still come out in the preferred form
i4 = i2.transform_to(FK5).transform_to(ICRS)
i4_many = i2_many.transform_to(FK5).transform_to(ICRS)
ri2 = ''.join(rexrepr.split(repr(i2)))
ri4 = ''.join(rexrepr.split(repr(i4)))
assert ri2 == ri4
assert i2.data.lon.unit != i4.data.lon.unit # Internal repr changed
ri2_many = ''.join(rexrepr.split(repr(i2_many)))
ri4_many = ''.join(rexrepr.split(repr(i4_many)))
assert ri2_many == ri4_many
assert i2_many.data.lon.unit != i4_many.data.lon.unit # Internal repr changed
# but that *shouldn't* hold if we turn off units for the representation
class FakeICRS(ICRS):
frame_specific_representation_info = {
'spherical': [RepresentationMapping('lon', 'ra', u.hourangle),
RepresentationMapping('lat', 'dec', None),
RepresentationMapping('distance', 'distance')] # should fall back to default of None unit
}
fi = FakeICRS(i4.data)
ri2 = ''.join(rexrepr.split(repr(i2)))
rfi = ''.join(rexrepr.split(repr(fi)))
rfi = re.sub('FakeICRS', 'ICRS', rfi) # Force frame name to match
assert ri2 != rfi
# the attributes should also get the right units
assert i2.dec.unit == i4.dec.unit
# unless no/explicitly given units
assert i2.dec.unit != fi.dec.unit
assert i2.ra.unit != fi.ra.unit
assert fi.ra.unit == u.hourangle
def test_representation_info():
from ..baseframe import RepresentationMapping
from ..builtin_frames import ICRS
class NewICRS1(ICRS):
frame_specific_representation_info = {
r.SphericalRepresentation: [
RepresentationMapping('lon', 'rara', u.hourangle),
RepresentationMapping('lat', 'decdec', u.degree),
RepresentationMapping('distance', 'distance', u.kpc)]
}
i1 = NewICRS1(rara=10*u.degree, decdec=-12*u.deg, distance=1000*u.pc,
pm_rara_cosdecdec=100*u.mas/u.yr,
pm_decdec=17*u.mas/u.yr,
radial_velocity=10*u.km/u.s)
assert allclose(i1.rara, 10*u.deg)
assert i1.rara.unit == u.hourangle
assert allclose(i1.decdec, -12*u.deg)
assert allclose(i1.distance, 1000*u.pc)
assert i1.distance.unit == u.kpc
assert allclose(i1.pm_rara_cosdecdec, 100*u.mas/u.yr)
assert allclose(i1.pm_decdec, 17*u.mas/u.yr)
# this should auto-set the names of UnitSpherical:
i1.set_representation_cls(r.UnitSphericalRepresentation,
s=r.UnitSphericalCosLatDifferential)
assert allclose(i1.rara, 10*u.deg)
assert allclose(i1.decdec, -12*u.deg)
assert allclose(i1.pm_rara_cosdecdec, 100*u.mas/u.yr)
assert allclose(i1.pm_decdec, 17*u.mas/u.yr)
# For backwards compatibility, we also support the string name in the
# representation info dictionary:
class NewICRS2(ICRS):
frame_specific_representation_info = {
'spherical': [
RepresentationMapping('lon', 'ang1', u.hourangle),
RepresentationMapping('lat', 'ang2', u.degree),
RepresentationMapping('distance', 'howfar', u.kpc)]
}
i2 = NewICRS2(ang1=10*u.degree, ang2=-12*u.deg, howfar=1000*u.pc)
assert allclose(i2.ang1, 10*u.deg)
assert i2.ang1.unit == u.hourangle
assert allclose(i2.ang2, -12*u.deg)
assert allclose(i2.howfar, 1000*u.pc)
assert i2.howfar.unit == u.kpc
# Test that the differential kwargs get overridden
class NewICRS3(ICRS):
frame_specific_representation_info = {
r.SphericalCosLatDifferential: [
RepresentationMapping('d_lon_coslat', 'pm_ang1', u.hourangle/u.year),
RepresentationMapping('d_lat', 'pm_ang2'),
RepresentationMapping('d_distance', 'vlos', u.kpc/u.Myr)]
}
i3 = NewICRS3(lon=10*u.degree, lat=-12*u.deg, distance=1000*u.pc,
pm_ang1=1*u.mas/u.yr, pm_ang2=2*u.mas/u.yr,
vlos=100*u.km/u.s)
assert allclose(i3.pm_ang1, 1*u.mas/u.yr)
assert i3.pm_ang1.unit == u.hourangle/u.year
assert allclose(i3.pm_ang2, 2*u.mas/u.yr)
assert allclose(i3.vlos, 100*u.km/u.s)
assert i3.vlos.unit == u.kpc/u.Myr
def test_realizing():
from ..builtin_frames import ICRS, FK5
from ...time import Time
rep = r.SphericalRepresentation(1*u.deg, 2*u.deg, 3*u.kpc)
i = ICRS()
i2 = i.realize_frame(rep)
assert not i.has_data
assert i2.has_data
f = FK5(equinox=Time('J2001', scale='utc'))
f2 = f.realize_frame(rep)
assert not f.has_data
assert f2.has_data
assert f2.equinox == f.equinox
assert f2.equinox != FK5.get_frame_attr_names()['equinox']
# Check that a nicer error message is returned:
with pytest.raises(TypeError) as excinfo:
f.realize_frame(f.representation)
assert ('Class passed as data instead of a representation' in
excinfo.value.args[0])
def test_replicating():
from ..builtin_frames import ICRS, AltAz
from ...time import Time
i = ICRS(ra=[1]*u.deg, dec=[2]*u.deg)
icopy = i.replicate(copy=True)
irepl = i.replicate(copy=False)
i.data._lat[:] = 0*u.deg
assert np.all(i.data.lat == irepl.data.lat)
assert np.all(i.data.lat != icopy.data.lat)
iclone = i.replicate_without_data()
assert i.has_data
assert not iclone.has_data
aa = AltAz(alt=1*u.deg, az=2*u.deg, obstime=Time('J2000'))
aaclone = aa.replicate_without_data(obstime=Time('J2001'))
assert not aaclone.has_data
assert aa.obstime != aaclone.obstime
assert aa.pressure == aaclone.pressure
assert aa.obswl == aaclone.obswl
def test_getitem():
from ..builtin_frames import ICRS
rep = r.SphericalRepresentation(
[1, 2, 3]*u.deg, [4, 5, 6]*u.deg, [7, 8, 9]*u.kpc)
i = ICRS(rep)
assert len(i.ra) == 3
iidx = i[1:]
assert len(iidx.ra) == 2
iidx2 = i[0]
assert iidx2.ra.isscalar
def test_transform():
"""
This test just makes sure the transform architecture works, but does *not*
actually test all the builtin transforms themselves are accurate
"""
from ..builtin_frames import ICRS, FK4, FK5, Galactic
from ...time import Time
i = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg)
f = i.transform_to(FK5)
i2 = f.transform_to(ICRS)
assert i2.data.__class__ == r.UnitSphericalRepresentation
assert_allclose(i.ra, i2.ra)
assert_allclose(i.dec, i2.dec)
i = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg, distance=[5, 6]*u.kpc)
f = i.transform_to(FK5)
i2 = f.transform_to(ICRS)
assert i2.data.__class__ != r.UnitSphericalRepresentation
f = FK5(ra=1*u.deg, dec=2*u.deg, equinox=Time('J2001', scale='utc'))
f4 = f.transform_to(FK4)
f4_2 = f.transform_to(FK4(equinox=f.equinox))
# make sure attributes are copied over correctly
assert f4.equinox == FK4.get_frame_attr_names()['equinox']
assert f4_2.equinox == f.equinox
# make sure self-transforms also work
i = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg)
i2 = i.transform_to(ICRS)
assert_allclose(i.ra, i2.ra)
assert_allclose(i.dec, i2.dec)
f = FK5(ra=1*u.deg, dec=2*u.deg, equinox=Time('J2001', scale='utc'))
f2 = f.transform_to(FK5) # default equinox, so should be *different*
assert f2.equinox == FK5().equinox
with pytest.raises(AssertionError):
assert_allclose(f.ra, f2.ra)
with pytest.raises(AssertionError):
assert_allclose(f.dec, f2.dec)
# finally, check Galactic round-tripping
i1 = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg)
i2 = i1.transform_to(Galactic).transform_to(ICRS)
assert_allclose(i1.ra, i2.ra)
assert_allclose(i1.dec, i2.dec)
def test_transform_to_nonscalar_nodata_frame():
# https://github.com/astropy/astropy/pull/5254#issuecomment-241592353
from ..builtin_frames import ICRS, FK5
from ...time import Time
times = Time('2016-08-23') + np.linspace(0, 10, 12)*u.day
coo1 = ICRS(ra=[[0.], [10.], [20.]]*u.deg,
dec=[[-30.], [30.], [60.]]*u.deg)
coo2 = coo1.transform_to(FK5(equinox=times))
assert coo2.shape == (3, 12)
def test_sep():
from ..builtin_frames import ICRS
i1 = ICRS(ra=0*u.deg, dec=1*u.deg)
i2 = ICRS(ra=0*u.deg, dec=2*u.deg)
sep = i1.separation(i2)
assert sep.deg == 1
i3 = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg, distance=[5, 6]*u.kpc)
i4 = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg, distance=[4, 5]*u.kpc)
sep3d = i3.separation_3d(i4)
assert_allclose(sep3d.to(u.kpc), np.array([1, 1])*u.kpc)
# check that it works even with velocities
i5 = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg, distance=[5, 6]*u.kpc,
pm_ra_cosdec=[1, 2]*u.mas/u.yr, pm_dec=[3, 4]*u.mas/u.yr,
radial_velocity=[5, 6]*u.km/u.s)
i6 = ICRS(ra=[1, 2]*u.deg, dec=[3, 4]*u.deg, distance=[7, 8]*u.kpc,
pm_ra_cosdec=[1, 2]*u.mas/u.yr, pm_dec=[3, 4]*u.mas/u.yr,
radial_velocity=[5, 6]*u.km/u.s)
sep3d = i5.separation_3d(i6)
assert_allclose(sep3d.to(u.kpc), np.array([2, 2])*u.kpc)
def test_time_inputs():
"""
Test validation and conversion of inputs for equinox and obstime attributes.
"""
from ...time import Time
from ..builtin_frames import FK4
c = FK4(1 * u.deg, 2 * u.deg, equinox='J2001.5', obstime='2000-01-01 12:00:00')
assert c.equinox == Time('J2001.5')
assert c.obstime == Time('2000-01-01 12:00:00')
with pytest.raises(ValueError) as err:
c = FK4(1 * u.deg, 2 * u.deg, equinox=1.5)
assert 'Invalid time input' in str(err)
with pytest.raises(ValueError) as err:
c = FK4(1 * u.deg, 2 * u.deg, obstime='hello')
assert 'Invalid time input' in str(err)
# A vector time should work if the shapes match, but we don't automatically
# broadcast the basic data (just like time).
FK4([1, 2] * u.deg, [2, 3] * u.deg, obstime=['J2000', 'J2001'])
with pytest.raises(ValueError) as err:
FK4(1 * u.deg, 2 * u.deg, obstime=['J2000', 'J2001'])
assert 'shape' in str(err)
def test_is_frame_attr_default():
"""
Check that the `is_frame_attr_default` machinery works as expected
"""
from ...time import Time
from ..builtin_frames import FK5
c1 = FK5(ra=1*u.deg, dec=1*u.deg)
c2 = FK5(ra=1*u.deg, dec=1*u.deg, equinox=FK5.get_frame_attr_names()['equinox'])
c3 = FK5(ra=1*u.deg, dec=1*u.deg, equinox=Time('J2001.5'))
assert c1.equinox == c2.equinox
assert c1.equinox != c3.equinox
assert c1.is_frame_attr_default('equinox')
assert not c2.is_frame_attr_default('equinox')
assert not c3.is_frame_attr_default('equinox')
c4 = c1.realize_frame(r.UnitSphericalRepresentation(3*u.deg, 4*u.deg))
c5 = c2.realize_frame(r.UnitSphericalRepresentation(3*u.deg, 4*u.deg))
assert c4.is_frame_attr_default('equinox')
assert not c5.is_frame_attr_default('equinox')
def test_altaz_attributes():
from ...time import Time
from .. import EarthLocation, AltAz
aa = AltAz(1*u.deg, 2*u.deg)
assert aa.obstime is None
assert aa.location is None
aa2 = AltAz(1*u.deg, 2*u.deg, obstime='J2000')
assert aa2.obstime == Time('J2000')
aa3 = AltAz(1*u.deg, 2*u.deg, location=EarthLocation(0*u.deg, 0*u.deg, 0*u.m))
assert isinstance(aa3.location, EarthLocation)
def test_representation():
"""
Test the getter and setter properties for `representation`
"""
from ..builtin_frames import ICRS
# Create the frame object.
icrs = ICRS(ra=1*u.deg, dec=1*u.deg)
data = icrs.data
# Create some representation objects.
icrs_cart = icrs.cartesian
icrs_spher = icrs.spherical
# Testing when `_representation` set to `CartesianRepresentation`.
icrs.representation = r.CartesianRepresentation
assert icrs.representation == r.CartesianRepresentation
assert icrs_cart.x == icrs.x
assert icrs_cart.y == icrs.y
assert icrs_cart.z == icrs.z
assert icrs.data == data
# Testing that an ICRS object in CartesianRepresentation must not have spherical attributes.
for attr in ('ra', 'dec', 'distance'):
with pytest.raises(AttributeError) as err:
getattr(icrs, attr)
assert 'object has no attribute' in str(err)
# Testing when `_representation` set to `CylindricalRepresentation`.
icrs.representation = r.CylindricalRepresentation
assert icrs.representation == r.CylindricalRepresentation
assert icrs.data == data
# Testing setter input using text argument for spherical.
icrs.representation = 'spherical'
assert icrs.representation is r.SphericalRepresentation
assert icrs_spher.lat == icrs.dec
assert icrs_spher.lon == icrs.ra
assert icrs_spher.distance == icrs.distance
assert icrs.data == data
# Testing that an ICRS object in SphericalRepresentation must not have cartesian attributes.
for attr in ('x', 'y', 'z'):
with pytest.raises(AttributeError) as err:
getattr(icrs, attr)
assert 'object has no attribute' in str(err)
# Testing setter input using text argument for cylindrical.
icrs.representation = 'cylindrical'
assert icrs.representation is r.CylindricalRepresentation
assert icrs.data == data
with pytest.raises(ValueError) as err:
icrs.representation = 'WRONG'
assert 'but must be a BaseRepresentation class' in str(err)
with pytest.raises(ValueError) as err:
icrs.representation = ICRS
assert 'but must be a BaseRepresentation class' in str(err)
def test_represent_as():
from ..builtin_frames import ICRS
icrs = ICRS(ra=1*u.deg, dec=1*u.deg)
cart1 = icrs.represent_as('cartesian')
cart2 = icrs.represent_as(r.CartesianRepresentation)
cart1.x == cart2.x
cart1.y == cart2.y
cart1.z == cart2.z
# now try with velocities
icrs = ICRS(ra=0*u.deg, dec=0*u.deg, distance=10*u.kpc,
pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr,
radial_velocity=1*u.km/u.s)
# single string
rep2 = icrs.represent_as('cylindrical')
assert isinstance(rep2, r.CylindricalRepresentation)
assert isinstance(rep2.differentials['s'], r.CylindricalDifferential)
# single class with positional in_frame_units, verify that warning raised
with catch_warnings() as w:
icrs.represent_as(r.CylindricalRepresentation, False)
assert len(w) == 1
assert w[0].category == AstropyWarning
assert 'argument position' in str(w[0].message)
# TODO: this should probably fail in the future once we figure out a better
# workaround for dealing with UnitSphericalRepresentation's with
# RadialDifferential's
# two classes
# rep2 = icrs.represent_as(r.CartesianRepresentation,
# r.SphericalCosLatDifferential)
# assert isinstance(rep2, r.CartesianRepresentation)
# assert isinstance(rep2.differentials['s'], r.SphericalCosLatDifferential)
with pytest.raises(ValueError):
icrs.represent_as('odaigahara')
def test_shorthand_representations():
from ..builtin_frames import ICRS
rep = r.CartesianRepresentation([1, 2, 3]*u.pc)
dif = r.CartesianDifferential([1, 2, 3]*u.km/u.s)
rep = rep.with_differentials(dif)
icrs = ICRS(rep)
sph = icrs.spherical
assert isinstance(sph, r.SphericalRepresentation)
assert isinstance(sph.differentials['s'], r.SphericalDifferential)
sph = icrs.sphericalcoslat
assert isinstance(sph, r.SphericalRepresentation)
assert isinstance(sph.differentials['s'], r.SphericalCosLatDifferential)
def test_dynamic_attrs():
from ..builtin_frames import ICRS
c = ICRS(1*u.deg, 2*u.deg)
assert 'ra' in dir(c)
assert 'dec' in dir(c)
with pytest.raises(AttributeError) as err:
c.blahblah
assert "object has no attribute 'blahblah'" in str(err)
with pytest.raises(AttributeError) as err:
c.ra = 1
assert "Cannot set any frame attribute" in str(err)
c.blahblah = 1
assert c.blahblah == 1
def test_nodata_error():
from ..builtin_frames import ICRS
i = ICRS()
with pytest.raises(ValueError) as excinfo:
i.data
assert 'does not have associated data' in str(excinfo.value)
def test_len0_data():
from ..builtin_frames import ICRS
i = ICRS([]*u.deg, []*u.deg)
assert i.has_data
repr(i)
def test_quantity_attributes():
from ..builtin_frames import GCRS
# make sure we can create a GCRS frame with valid inputs
GCRS(obstime='J2002', obsgeoloc=[1, 2, 3]*u.km, obsgeovel=[4, 5, 6]*u.km/u.s)
# make sure it fails for invalid lovs or vels
with pytest.raises(TypeError):
GCRS(obsgeoloc=[1, 2, 3]) # no unit
with pytest.raises(u.UnitsError):
GCRS(obsgeoloc=[1, 2, 3]*u.km/u.s) # incorrect unit
with pytest.raises(ValueError):
GCRS(obsgeoloc=[1, 3]*u.km) # incorrect shape
def test_eloc_attributes():
from .. import AltAz, ITRS, GCRS, EarthLocation
el = EarthLocation(lon=12.3*u.deg, lat=45.6*u.deg, height=1*u.km)
it = ITRS(r.SphericalRepresentation(lon=12.3*u.deg, lat=45.6*u.deg, distance=1*u.km))
gc = GCRS(ra=12.3*u.deg, dec=45.6*u.deg, distance=6375*u.km)
el1 = AltAz(location=el).location
assert isinstance(el1, EarthLocation)
# these should match *exactly* because the EarthLocation
assert el1.lat == el.lat
assert el1.lon == el.lon
assert el1.height == el.height
el2 = AltAz(location=it).location
assert isinstance(el2, EarthLocation)
# these should *not* match because giving something in Spherical ITRS is
# *not* the same as giving it as an EarthLocation: EarthLocation is on an
# elliptical geoid. So the longitude should match (because flattening is
# only along the z-axis), but latitude should not. Also, height is relative
# to the *surface* in EarthLocation, but the ITRS distance is relative to
# the center of the Earth
assert not allclose(el2.lat, it.spherical.lat)
assert allclose(el2.lon, it.spherical.lon)
assert el2.height < -6000*u.km
el3 = AltAz(location=gc).location
# GCRS inputs implicitly get transformed to ITRS and then onto
# EarthLocation's elliptical geoid. So both lat and lon shouldn't match
assert isinstance(el3, EarthLocation)
assert not allclose(el3.lat, gc.dec)
assert not allclose(el3.lon, gc.ra)
assert np.abs(el3.height) < 500*u.km
def test_equivalent_frames():
from .. import SkyCoord
from ..builtin_frames import ICRS, FK4, FK5, AltAz
i = ICRS()
i2 = ICRS(1*u.deg, 2*u.deg)
assert i.is_equivalent_frame(i)
assert i.is_equivalent_frame(i2)
with pytest.raises(TypeError):
assert i.is_equivalent_frame(10)
with pytest.raises(TypeError):
assert i2.is_equivalent_frame(SkyCoord(i2))
f1 = FK5()
f2 = FK5(1*u.deg, 2*u.deg, equinox='J2000')
f3 = FK5(equinox='J2010')
f4 = FK4(equinox='J2010')
assert f1.is_equivalent_frame(f1)
assert not i.is_equivalent_frame(f1)
assert f1.is_equivalent_frame(f2)
assert not f1.is_equivalent_frame(f3)
assert not f3.is_equivalent_frame(f4)
aa1 = AltAz()
aa2 = AltAz(obstime='J2010')
assert aa2.is_equivalent_frame(aa2)
assert not aa1.is_equivalent_frame(i)
assert not aa1.is_equivalent_frame(aa2)
def test_representation_subclass():
# Regression test for #3354
from ..builtin_frames import FK5
# Normally when instantiating a frame without a distance the frame will try
# and use UnitSphericalRepresentation internally instead of
# SphericalRepresentation.
frame = FK5(representation=r.SphericalRepresentation, ra=32 * u.deg, dec=20 * u.deg)
assert type(frame._data) == r.UnitSphericalRepresentation
assert frame.representation == r.SphericalRepresentation
# If using a SphericalRepresentation class this used to not work, so we
# test here that this is now fixed.
class NewSphericalRepresentation(r.SphericalRepresentation):
attr_classes = r.SphericalRepresentation.attr_classes
frame = FK5(representation=NewSphericalRepresentation, lon=32 * u.deg, lat=20 * u.deg)
assert type(frame._data) == r.UnitSphericalRepresentation
assert frame.representation == NewSphericalRepresentation
# A similar issue then happened in __repr__ with subclasses of
# SphericalRepresentation.
assert repr(frame) == ("<FK5 Coordinate (equinox=J2000.000): (lon, lat) in deg\n"
" ({})>").format(' 32., 20.' if NUMPY_LT_1_14
else '32., 20.')
# A more subtle issue is when specifying a custom
# UnitSphericalRepresentation subclass for the data and
# SphericalRepresentation or a subclass for the representation.
class NewUnitSphericalRepresentation(r.UnitSphericalRepresentation):
attr_classes = r.UnitSphericalRepresentation.attr_classes
def __repr__(self):
return "<NewUnitSphericalRepresentation: spam spam spam>"
frame = FK5(NewUnitSphericalRepresentation(lon=32 * u.deg, lat=20 * u.deg),
representation=NewSphericalRepresentation)
assert repr(frame) == "<FK5 Coordinate (equinox=J2000.000): spam spam spam>"
def test_getitem_representation():
"""
Make sure current representation survives __getitem__ even if different
from data representation.
"""
from ..builtin_frames import ICRS
c = ICRS([1, 1] * u.deg, [2, 2] * u.deg)
c.representation = 'cartesian'
assert c[0].representation is r.CartesianRepresentation
def test_component_error_useful():
"""
Check that a data-less frame gives useful error messages about not having
data when the attributes asked for are possible coordinate components
"""
from ..builtin_frames import ICRS
i = ICRS()
with pytest.raises(ValueError) as excinfo:
i.ra
assert 'does not have associated data' in str(excinfo.value)
with pytest.raises(AttributeError) as excinfo1:
i.foobar
with pytest.raises(AttributeError) as excinfo2:
i.lon # lon is *not* the component name despite being the underlying representation's name
assert "object has no attribute 'foobar'" in str(excinfo1.value)
assert "object has no attribute 'lon'" in str(excinfo2.value)
def test_cache_clear():
from ..builtin_frames import ICRS
i = ICRS(1*u.deg, 2*u.deg)
# Add an in frame units version of the rep to the cache.
repr(i)
assert len(i.cache['representation']) == 2
i.cache.clear()
assert len(i.cache['representation']) == 0
def test_inplace_array():
from ..builtin_frames import ICRS
i = ICRS([[1, 2], [3, 4]]*u.deg, [[10, 20], [30, 40]]*u.deg)
# Add an in frame units version of the rep to the cache.
repr(i)
# Check that repr() has added a rep to the cache
assert len(i.cache['representation']) == 2
# Modify the data
i.data.lon[:, 0] = [100, 200]*u.deg
# Clear the cache
i.cache.clear()
# This will use a second (potentially cached rep)
assert_allclose(i.ra, [[100, 2], [200, 4]]*u.deg)
assert_allclose(i.dec, [[10, 20], [30, 40]]*u.deg)
def test_inplace_change():
from ..builtin_frames import ICRS
i = ICRS(1*u.deg, 2*u.deg)
# Add an in frame units version of the rep to the cache.
repr(i)
# Check that repr() has added a rep to the cache
assert len(i.cache['representation']) == 2
# Modify the data
i.data.lon[()] = 10*u.deg
# Clear the cache
i.cache.clear()
# This will use a second (potentially cached rep)
assert i.ra == 10 * u.deg
assert i.dec == 2 * u.deg
def test_representation_with_multiple_differentials():
from ..builtin_frames import ICRS
dif1 = r.CartesianDifferential([1, 2, 3]*u.km/u.s)
dif2 = r.CartesianDifferential([1, 2, 3]*u.km/u.s**2)
rep = r.CartesianRepresentation([1, 2, 3]*u.pc,
differentials={'s': dif1, 's2': dif2})
# check warning is raised for a scalar
with pytest.raises(ValueError):
ICRS(rep)
def test_representation_arg_backwards_compatibility():
# TODO: this test can be removed when the `representation` argument is
# removed from the BaseCoordinateFrame initializer.
from ..builtin_frames import ICRS
c1 = ICRS(x=1*u.pc, y=2*u.pc, z=3*u.pc,
representation_type=r.CartesianRepresentation)
c2 = ICRS(x=1*u.pc, y=2*u.pc, z=3*u.pc,
representation=r.CartesianRepresentation)
c3 = ICRS(x=1*u.pc, y=2*u.pc, z=3*u.pc,
representation='cartesian')
assert c1.x == c2.x
assert c1.y == c2.y
assert c1.z == c2.z
assert c1.x == c3.x
assert c1.y == c3.y
assert c1.z == c3.z
assert c1.representation == c1.representation_type
with pytest.raises(ValueError):
ICRS(x=1*u.pc, y=2*u.pc, z=3*u.pc,
representation='cartesian',
representation_type='cartesian')
def test_missing_component_error_names():
"""
This test checks that the component names are frame component names, not
representation or differential names, when referenced in an exception raised
when not passing in enough data. For example:
ICRS(ra=10*u.deg)
should state:
TypeError: __init__() missing 1 required positional argument: 'dec'
"""
from ..builtin_frames import ICRS
with pytest.raises(TypeError) as e:
ICRS(ra=150 * u.deg)
assert "missing 1 required positional argument: 'dec'" in str(e)
with pytest.raises(TypeError) as e:
ICRS(ra=150*u.deg, dec=-11*u.deg,
pm_ra=100*u.mas/u.yr, pm_dec=10*u.mas/u.yr)
assert "pm_ra_cosdec" in str(e)
|
d571d2383375120d59e3ab831ca5d6b5b1143af9927e43966d5a2932574c87b0 | """
This file tests the behaviour of subclasses of Representation and Frames
"""
from copy import deepcopy
from collections import OrderedDict
from astropy.coordinates import Longitude, Latitude
from astropy.coordinates.representation import (REPRESENTATION_CLASSES,
SphericalRepresentation,
UnitSphericalRepresentation)
from astropy.coordinates.baseframe import frame_transform_graph
from astropy.coordinates.transformations import FunctionTransform
from astropy.coordinates import ICRS
from astropy.coordinates.baseframe import RepresentationMapping
from .. import representation as r
import astropy.units as u
import astropy.coordinates
# Classes setup, borrowed from SunPy.
# Here we define the classes *inside* the tests to make sure that we can wipe
# the slate clean when the tests have finished running.
def setup_function(func):
func.REPRESENTATION_CLASSES_ORIG = deepcopy(REPRESENTATION_CLASSES)
def teardown_function(func):
REPRESENTATION_CLASSES.clear()
REPRESENTATION_CLASSES.update(func.REPRESENTATION_CLASSES_ORIG)
def test_unit_representation_subclass():
class Longitude180(Longitude):
def __new__(cls, angle, unit=None, wrap_angle=180*u.deg, **kwargs):
self = super().__new__(cls, angle, unit=unit, wrap_angle=wrap_angle,
**kwargs)
return self
class UnitSphericalWrap180Representation(UnitSphericalRepresentation):
attr_classes = OrderedDict([('lon', Longitude180),
('lat', Latitude)])
recommended_units = {'lon': u.deg, 'lat': u.deg}
class SphericalWrap180Representation(SphericalRepresentation):
attr_classes = OrderedDict([('lon', Longitude180),
('lat', Latitude),
('distance', u.Quantity)])
recommended_units = {'lon': u.deg, 'lat': u.deg}
_unit_representation = UnitSphericalWrap180Representation
class MyFrame(ICRS):
default_representation = SphericalWrap180Representation
frame_specific_representation_info = {
'spherical': [
RepresentationMapping('lon', 'ra'),
RepresentationMapping('lat', 'dec')]
}
frame_specific_representation_info['unitsphericalwrap180'] = \
frame_specific_representation_info['sphericalwrap180'] = \
frame_specific_representation_info['spherical']
@frame_transform_graph.transform(FunctionTransform,
MyFrame, astropy.coordinates.ICRS)
def myframe_to_icrs(myframe_coo, icrs):
return icrs.realize_frame(myframe_coo._data)
f = MyFrame(10*u.deg, 10*u.deg)
assert isinstance(f._data, UnitSphericalWrap180Representation)
assert isinstance(f.ra, Longitude180)
g = f.transform_to(astropy.coordinates.ICRS)
assert isinstance(g, astropy.coordinates.ICRS)
assert isinstance(g._data, UnitSphericalWrap180Representation)
frame_transform_graph.remove_transform(MyFrame,
astropy.coordinates.ICRS,
None)
|
693c451ceaa125dee12ff43eea791406151e05935f226b86b94f7e27aab1163a |
import pytest
import numpy as np
from ...time import Time
from ... import units as u
from ...constants import c
from ..builtin_frames import GCRS
from ..earth import EarthLocation
from ..sky_coordinate import SkyCoord
from ..solar_system import (get_body, get_moon, BODY_NAME_TO_KERNEL_SPEC,
_apparent_position_in_true_coordinates,
get_body_barycentric, get_body_barycentric_posvel)
from ..funcs import get_sun
from ...tests.helper import assert_quantity_allclose, quantity_allclose
try:
import jplephem # pylint: disable=W0611
except ImportError:
HAS_JPLEPHEM = False
else:
HAS_JPLEPHEM = True
try:
from skyfield.api import load # pylint: disable=W0611
except ImportError:
HAS_SKYFIELD = False
else:
HAS_SKYFIELD = True
de432s_separation_tolerance_planets = 5*u.arcsec
de432s_separation_tolerance_moon = 5*u.arcsec
de432s_distance_tolerance = 20*u.km
skyfield_angular_separation_tolerance = 1*u.arcsec
skyfield_separation_tolerance = 10*u.km
@pytest.mark.remote_data
@pytest.mark.skipif(str('not HAS_SKYFIELD'))
def test_positions_skyfield():
"""
Test positions against those generated by skyfield.
"""
t = Time('1980-03-25 00:00')
location = None
# skyfield ephemeris
planets = load('de421.bsp')
ts = load.timescale()
mercury, jupiter, moon = planets['mercury'], planets['jupiter barycenter'], planets['moon']
earth = planets['earth']
skyfield_t = ts.from_astropy(t)
if location is not None:
earth = earth.topos(latitude_degrees=location.lat.to_value(u.deg),
longitude_degrees=location.lon.to_value(u.deg),
elevation_m=location.height.to_value(u.m))
skyfield_mercury = earth.at(skyfield_t).observe(mercury).apparent()
skyfield_jupiter = earth.at(skyfield_t).observe(jupiter).apparent()
skyfield_moon = earth.at(skyfield_t).observe(moon).apparent()
if location is not None:
obsgeoloc, obsgeovel = location.get_gcrs_posvel(t)
frame = GCRS(obstime=t, obsgeoloc=obsgeoloc, obsgeovel=obsgeovel)
else:
frame = GCRS(obstime=t)
ra, dec, dist = skyfield_mercury.radec(epoch='date')
skyfield_mercury = SkyCoord(ra.to(u.deg), dec.to(u.deg), distance=dist.to(u.km),
frame=frame)
ra, dec, dist = skyfield_jupiter.radec(epoch='date')
skyfield_jupiter = SkyCoord(ra.to(u.deg), dec.to(u.deg), distance=dist.to(u.km),
frame=frame)
ra, dec, dist = skyfield_moon.radec(epoch='date')
skyfield_moon = SkyCoord(ra.to(u.deg), dec.to(u.deg), distance=dist.to(u.km),
frame=frame)
moon_astropy = get_moon(t, location, ephemeris='de430')
mercury_astropy = get_body('mercury', t, location, ephemeris='de430')
jupiter_astropy = get_body('jupiter', t, location, ephemeris='de430')
# convert to true equator and equinox
jupiter_astropy = _apparent_position_in_true_coordinates(jupiter_astropy)
mercury_astropy = _apparent_position_in_true_coordinates(mercury_astropy)
moon_astropy = _apparent_position_in_true_coordinates(moon_astropy)
assert (moon_astropy.separation(skyfield_moon) <
skyfield_angular_separation_tolerance)
assert (moon_astropy.separation_3d(skyfield_moon) < skyfield_separation_tolerance)
assert (jupiter_astropy.separation(skyfield_jupiter) <
skyfield_angular_separation_tolerance)
assert (jupiter_astropy.separation_3d(skyfield_jupiter) <
skyfield_separation_tolerance)
assert (mercury_astropy.separation(skyfield_mercury) <
skyfield_angular_separation_tolerance)
assert (mercury_astropy.separation_3d(skyfield_mercury) <
skyfield_separation_tolerance)
class TestPositionsGeocentric:
"""
Test positions against those generated by JPL Horizons accessed on
2016-03-28, with refraction turned on.
"""
def setup(self):
self.t = Time('1980-03-25 00:00')
self.frame = GCRS(obstime=self.t)
# Results returned by JPL Horizons web interface
self.horizons = {
'mercury': SkyCoord(ra='22h41m47.78s', dec='-08d29m32.0s',
distance=c*6.323037*u.min, frame=self.frame),
'moon': SkyCoord(ra='07h32m02.62s', dec='+18d34m05.0s',
distance=c*0.021921*u.min, frame=self.frame),
'jupiter': SkyCoord(ra='10h17m12.82s', dec='+12d02m57.0s',
distance=c*37.694557*u.min, frame=self.frame),
'sun': SkyCoord(ra='00h16m31.00s', dec='+01d47m16.9s',
distance=c*8.294858*u.min, frame=self.frame)}
@pytest.mark.parametrize(('body', 'sep_tol', 'dist_tol'),
(('mercury', 7.*u.arcsec, 1000*u.km),
('jupiter', 78.*u.arcsec, 76000*u.km),
('moon', 20.*u.arcsec, 80*u.km),
('sun', 5.*u.arcsec, 11.*u.km)))
def test_erfa_planet(self, body, sep_tol, dist_tol):
"""Test predictions using erfa/plan94.
Accuracies are maximum deviations listed in erfa/plan94.c, for Jupiter and
Mercury, and that quoted in Meeus "Astronomical Algorithms" (1998) for the Moon.
"""
astropy = get_body(body, self.t, ephemeris='builtin')
horizons = self.horizons[body]
# convert to true equator and equinox
astropy = _apparent_position_in_true_coordinates(astropy)
# Assert sky coordinates are close.
assert astropy.separation(horizons) < sep_tol
# Assert distances are close.
assert_quantity_allclose(astropy.distance, horizons.distance,
atol=dist_tol)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
@pytest.mark.parametrize('body', ('mercury', 'jupiter', 'sun'))
def test_de432s_planet(self, body):
astropy = get_body(body, self.t, ephemeris='de432s')
horizons = self.horizons[body]
# convert to true equator and equinox
astropy = _apparent_position_in_true_coordinates(astropy)
# Assert sky coordinates are close.
assert (astropy.separation(horizons) <
de432s_separation_tolerance_planets)
# Assert distances are close.
assert_quantity_allclose(astropy.distance, horizons.distance,
atol=de432s_distance_tolerance)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
def test_de432s_moon(self):
astropy = get_moon(self.t, ephemeris='de432s')
horizons = self.horizons['moon']
# convert to true equator and equinox
astropy = _apparent_position_in_true_coordinates(astropy)
# Assert sky coordinates are close.
assert (astropy.separation(horizons) <
de432s_separation_tolerance_moon)
# Assert distances are close.
assert_quantity_allclose(astropy.distance, horizons.distance,
atol=de432s_distance_tolerance)
class TestPositionKittPeak:
"""
Test positions against those generated by JPL Horizons accessed on
2016-03-28, with refraction turned on.
"""
def setup(self):
kitt_peak = EarthLocation.from_geodetic(lon=-111.6*u.deg,
lat=31.963333333333342*u.deg,
height=2120*u.m)
self.t = Time('2014-09-25T00:00', location=kitt_peak)
obsgeoloc, obsgeovel = kitt_peak.get_gcrs_posvel(self.t)
self.frame = GCRS(obstime=self.t,
obsgeoloc=obsgeoloc, obsgeovel=obsgeovel)
# Results returned by JPL Horizons web interface
self.horizons = {
'mercury': SkyCoord(ra='13h38m58.50s', dec='-13d34m42.6s',
distance=c*7.699020*u.min, frame=self.frame),
'moon': SkyCoord(ra='12h33m12.85s', dec='-05d17m54.4s',
distance=c*0.022054*u.min, frame=self.frame),
'jupiter': SkyCoord(ra='09h09m55.55s', dec='+16d51m57.8s',
distance=c*49.244937*u.min, frame=self.frame)}
@pytest.mark.parametrize(('body', 'sep_tol', 'dist_tol'),
(('mercury', 7.*u.arcsec, 500*u.km),
('jupiter', 78.*u.arcsec, 82000*u.km)))
def test_erfa_planet(self, body, sep_tol, dist_tol):
"""Test predictions using erfa/plan94.
Accuracies are maximum deviations listed in erfa/plan94.c.
"""
# Add uncertainty in position of Earth
dist_tol = dist_tol + 1300 * u.km
astropy = get_body(body, self.t, ephemeris='builtin')
horizons = self.horizons[body]
# convert to true equator and equinox
astropy = _apparent_position_in_true_coordinates(astropy)
# Assert sky coordinates are close.
assert astropy.separation(horizons) < sep_tol
# Assert distances are close.
assert_quantity_allclose(astropy.distance, horizons.distance,
atol=dist_tol)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
@pytest.mark.parametrize('body', ('mercury', 'jupiter'))
def test_de432s_planet(self, body):
astropy = get_body(body, self.t, ephemeris='de432s')
horizons = self.horizons[body]
# convert to true equator and equinox
astropy = _apparent_position_in_true_coordinates(astropy)
# Assert sky coordinates are close.
assert (astropy.separation(horizons) <
de432s_separation_tolerance_planets)
# Assert distances are close.
assert_quantity_allclose(astropy.distance, horizons.distance,
atol=de432s_distance_tolerance)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
def test_de432s_moon(self):
astropy = get_moon(self.t, ephemeris='de432s')
horizons = self.horizons['moon']
# convert to true equator and equinox
astropy = _apparent_position_in_true_coordinates(astropy)
# Assert sky coordinates are close.
assert (astropy.separation(horizons) <
de432s_separation_tolerance_moon)
# Assert distances are close.
assert_quantity_allclose(astropy.distance, horizons.distance,
atol=de432s_distance_tolerance)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
@pytest.mark.parametrize('bodyname', ('mercury', 'jupiter'))
def test_custom_kernel_spec_body(self, bodyname):
"""
Checks that giving a kernel specifier instead of a body name works
"""
coord_by_name = get_body(bodyname, self.t, ephemeris='de432s')
kspec = BODY_NAME_TO_KERNEL_SPEC[bodyname]
coord_by_kspec = get_body(kspec, self.t, ephemeris='de432s')
assert_quantity_allclose(coord_by_name.ra, coord_by_kspec.ra)
assert_quantity_allclose(coord_by_name.dec, coord_by_kspec.dec)
assert_quantity_allclose(coord_by_name.distance, coord_by_kspec.distance)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
@pytest.mark.parametrize('time', (Time('1960-01-12 00:00'),
Time('1980-03-25 00:00'),
Time('2010-10-13 00:00')))
def test_get_sun_consistency(time):
"""
Test that the sun from JPL and the builtin get_sun match
"""
sun_jpl_gcrs = get_body('sun', time, ephemeris='de432s')
builtin_get_sun = get_sun(time)
sep = builtin_get_sun.separation(sun_jpl_gcrs)
assert sep < 0.1*u.arcsec
def test_get_moon_nonscalar_regression():
"""
Test that the builtin ephemeris works with non-scalar times.
See Issue #5069.
"""
times = Time(["2015-08-28 03:30", "2015-09-05 10:30"])
# the following line will raise an Exception if the bug recurs.
get_moon(times, ephemeris='builtin')
def test_barycentric_pos_posvel_same():
# Check that the two routines give identical results.
ep1 = get_body_barycentric('earth', Time('2016-03-20T12:30:00'))
ep2, _ = get_body_barycentric_posvel('earth', Time('2016-03-20T12:30:00'))
assert np.all(ep1.xyz == ep2.xyz)
def test_earth_barycentric_velocity_rough():
# Check that a time near the equinox gives roughly the right result.
ep, ev = get_body_barycentric_posvel('earth', Time('2016-03-20T12:30:00'))
assert_quantity_allclose(ep.xyz, [-1., 0., 0.]*u.AU, atol=0.01*u.AU)
expected = u.Quantity([0.*u.one,
np.cos(23.5*u.deg),
np.sin(23.5*u.deg)]) * -30. * u.km / u.s
assert_quantity_allclose(ev.xyz, expected, atol=1.*u.km/u.s)
def test_earth_barycentric_velocity_multi_d():
# Might as well test it with a multidimensional array too.
t = Time('2016-03-20T12:30:00') + np.arange(8.).reshape(2, 2, 2) * u.yr / 2.
ep, ev = get_body_barycentric_posvel('earth', t)
# note: assert_quantity_allclose doesn't like the shape mismatch.
# this is a problem with np.testing.assert_allclose.
assert quantity_allclose(ep.get_xyz(xyz_axis=-1),
[[-1., 0., 0.], [+1., 0., 0.]]*u.AU,
atol=0.06*u.AU)
expected = u.Quantity([0.*u.one,
np.cos(23.5*u.deg),
np.sin(23.5*u.deg)]) * ([[-30.], [30.]] * u.km / u.s)
assert quantity_allclose(ev.get_xyz(xyz_axis=-1), expected,
atol=2.*u.km/u.s)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
@pytest.mark.parametrize(('body', 'pos_tol', 'vel_tol'),
(('mercury', 1000.*u.km, 1.*u.km/u.s),
('jupiter', 100000.*u.km, 2.*u.km/u.s),
('earth', 10*u.km, 10*u.mm/u.s)))
def test_barycentric_velocity_consistency(body, pos_tol, vel_tol):
# Tolerances are about 1.5 times the rms listed for plan94 and epv00,
# except for Mercury (which nominally is 334 km rms)
t = Time('2016-03-20T12:30:00')
ep, ev = get_body_barycentric_posvel(body, t, ephemeris='builtin')
dp, dv = get_body_barycentric_posvel(body, t, ephemeris='de432s')
assert_quantity_allclose(ep.xyz, dp.xyz, atol=pos_tol)
assert_quantity_allclose(ev.xyz, dv.xyz, atol=vel_tol)
# Might as well test it with a multidimensional array too.
t = Time('2016-03-20T12:30:00') + np.arange(8.).reshape(2, 2, 2) * u.yr / 2.
ep, ev = get_body_barycentric_posvel(body, t, ephemeris='builtin')
dp, dv = get_body_barycentric_posvel(body, t, ephemeris='de432s')
assert_quantity_allclose(ep.xyz, dp.xyz, atol=pos_tol)
assert_quantity_allclose(ev.xyz, dv.xyz, atol=vel_tol)
|
4a9cdf829e7d7174412883251440b59ff5cab6485945e68b1a81effc94215bef | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import pytest
from ... import units as u
from .. import transformations as t
from ..builtin_frames import ICRS, FK5, FK4, FK4NoETerms, Galactic, AltAz
from .. import representation as r
from ..baseframe import frame_transform_graph
from ...tests.helper import (assert_quantity_allclose as assert_allclose,
quantity_allclose, catch_warnings)
from ...time import Time
# Coordinates just for these tests.
class TCoo1(ICRS):
pass
class TCoo2(ICRS):
pass
class TCoo3(ICRS):
pass
def test_transform_classes():
"""
Tests the class-based/OO syntax for creating transforms
"""
tfun = lambda c, f: f.__class__(ra=c.ra, dec=c.dec)
trans1 = t.FunctionTransform(tfun, TCoo1, TCoo2,
register_graph=frame_transform_graph)
c1 = TCoo1(ra=1*u.radian, dec=0.5*u.radian)
c2 = c1.transform_to(TCoo2)
assert_allclose(c2.ra.radian, 1)
assert_allclose(c2.dec.radian, 0.5)
def matfunc(coo, fr):
return [[1, 0, 0],
[0, coo.ra.degree, 0],
[0, 0, 1]]
trans2 = t.DynamicMatrixTransform(matfunc, TCoo1, TCoo2)
trans2.register(frame_transform_graph)
c3 = TCoo1(ra=1*u.deg, dec=2*u.deg)
c4 = c3.transform_to(TCoo2)
assert_allclose(c4.ra.degree, 1)
assert_allclose(c4.ra.degree, 1)
# be sure to unregister the second one - no need for trans1 because it
# already got unregistered when trans2 was created.
trans2.unregister(frame_transform_graph)
def test_transform_decos():
"""
Tests the decorator syntax for creating transforms
"""
c1 = TCoo1(ra=1*u.deg, dec=2*u.deg)
@frame_transform_graph.transform(t.FunctionTransform, TCoo1, TCoo2)
def trans(coo1, f):
return TCoo2(ra=coo1.ra, dec=coo1.dec * 2)
c2 = c1.transform_to(TCoo2)
assert_allclose(c2.ra.degree, 1)
assert_allclose(c2.dec.degree, 4)
c3 = TCoo1(r.CartesianRepresentation(x=1*u.pc, y=1*u.pc, z=2*u.pc))
@frame_transform_graph.transform(t.StaticMatrixTransform, TCoo1, TCoo2)
def matrix():
return [[2, 0, 0],
[0, 1, 0],
[0, 0, 1]]
c4 = c3.transform_to(TCoo2)
assert_allclose(c4.cartesian.x, 2*u.pc)
assert_allclose(c4.cartesian.y, 1*u.pc)
assert_allclose(c4.cartesian.z, 2*u.pc)
def test_shortest_path():
class FakeTransform:
def __init__(self, pri):
self.priority = pri
g = t.TransformGraph()
# cheating by adding graph elements directly that are not classes - the
# graphing algorithm still works fine with integers - it just isn't a valid
# TransformGraph
# the graph looks is a down-going diamond graph with the lower-right slightly
# heavier and a cycle from the bottom to the top
# also, a pair of nodes isolated from 1
g._graph[1][2] = FakeTransform(1)
g._graph[1][3] = FakeTransform(1)
g._graph[2][4] = FakeTransform(1)
g._graph[3][4] = FakeTransform(2)
g._graph[4][1] = FakeTransform(5)
g._graph[5][6] = FakeTransform(1)
path, d = g.find_shortest_path(1, 2)
assert path == [1, 2]
assert d == 1
path, d = g.find_shortest_path(1, 3)
assert path == [1, 3]
assert d == 1
path, d = g.find_shortest_path(1, 4)
print('Cached paths:', g._shortestpaths)
assert path == [1, 2, 4]
assert d == 2
# unreachable
path, d = g.find_shortest_path(1, 5)
assert path is None
assert d == float('inf')
path, d = g.find_shortest_path(5, 6)
assert path == [5, 6]
assert d == 1
def test_sphere_cart():
"""
Tests the spherical <-> cartesian transform functions
"""
from ...utils import NumpyRNGContext
from .. import spherical_to_cartesian, cartesian_to_spherical
x, y, z = spherical_to_cartesian(1, 0, 0)
assert_allclose(x, 1)
assert_allclose(y, 0)
assert_allclose(z, 0)
x, y, z = spherical_to_cartesian(0, 1, 1)
assert_allclose(x, 0)
assert_allclose(y, 0)
assert_allclose(z, 0)
x, y, z = spherical_to_cartesian(5, 0, np.arcsin(4. / 5.))
assert_allclose(x, 3)
assert_allclose(y, 4)
assert_allclose(z, 0)
r, lat, lon = cartesian_to_spherical(0, 1, 0)
assert_allclose(r, 1)
assert_allclose(lat, 0 * u.deg)
assert_allclose(lon, np.pi / 2 * u.rad)
# test round-tripping
with NumpyRNGContext(13579):
x, y, z = np.random.randn(3, 5)
r, lat, lon = cartesian_to_spherical(x, y, z)
x2, y2, z2 = spherical_to_cartesian(r, lat, lon)
assert_allclose(x, x2)
assert_allclose(y, y2)
assert_allclose(z, z2)
def test_transform_path_pri():
"""
This checks that the transformation path prioritization works by
making sure the ICRS -> Gal transformation always goes through FK5
and not FK4.
"""
frame_transform_graph.invalidate_cache()
tpath, td = frame_transform_graph.find_shortest_path(ICRS, Galactic)
assert tpath == [ICRS, FK5, Galactic]
assert td == 2
# but direct from FK4 to Galactic should still be possible
tpath, td = frame_transform_graph.find_shortest_path(FK4, Galactic)
assert tpath == [FK4, FK4NoETerms, Galactic]
assert td == 2
def test_obstime():
"""
Checks to make sure observation time is
accounted for at least in FK4 <-> ICRS transformations
"""
b1950 = Time('B1950', scale='utc')
j1975 = Time('J1975', scale='utc')
fk4_50 = FK4(ra=1*u.deg, dec=2*u.deg, obstime=b1950)
fk4_75 = FK4(ra=1*u.deg, dec=2*u.deg, obstime=j1975)
icrs_50 = fk4_50.transform_to(ICRS)
icrs_75 = fk4_75.transform_to(ICRS)
# now check that the resulting coordinates are *different* - they should be,
# because the obstime is different
assert icrs_50.ra.degree != icrs_75.ra.degree
assert icrs_50.dec.degree != icrs_75.dec.degree
# ------------------------------------------------------------------------------
# Affine transform tests and helpers:
# just acting as a namespace
class transfunc:
rep = r.CartesianRepresentation(np.arange(3)*u.pc)
dif = r.CartesianDifferential(*np.arange(3, 6)*u.pc/u.Myr)
rep0 = r.CartesianRepresentation(np.zeros(3)*u.pc)
@classmethod
def both(cls, coo, fr):
# exchange x <-> z and offset
M = np.array([[0., 0., 1.],
[0., 1., 0.],
[1., 0., 0.]])
return M, cls.rep.with_differentials(cls.dif)
@classmethod
def just_matrix(cls, coo, fr):
# exchange x <-> z and offset
M = np.array([[0., 0., 1.],
[0., 1., 0.],
[1., 0., 0.]])
return M, None
@classmethod
def no_matrix(cls, coo, fr):
return None, cls.rep.with_differentials(cls.dif)
@classmethod
def no_pos(cls, coo, fr):
return None, cls.rep0.with_differentials(cls.dif)
@classmethod
def no_vel(cls, coo, fr):
return None, cls.rep
@pytest.mark.parametrize('transfunc', [transfunc.both, transfunc.no_matrix,
transfunc.no_pos, transfunc.no_vel,
transfunc.just_matrix])
@pytest.mark.parametrize('rep', [
r.CartesianRepresentation(5, 6, 7, unit=u.pc),
r.CartesianRepresentation(5, 6, 7, unit=u.pc,
differentials=r.CartesianDifferential(8, 9, 10,
unit=u.pc/u.Myr)),
r.CartesianRepresentation(5, 6, 7, unit=u.pc,
differentials=r.CartesianDifferential(8, 9, 10,
unit=u.pc/u.Myr))
.represent_as(r.CylindricalRepresentation, r.CylindricalDifferential)
])
def test_affine_transform_succeed(transfunc, rep):
c = TCoo1(rep)
# compute expected output
M, offset = transfunc(c, TCoo2)
_rep = rep.to_cartesian()
diffs = dict([(k, diff.represent_as(r.CartesianDifferential, rep))
for k, diff in rep.differentials.items()])
expected_rep = _rep.with_differentials(diffs)
if M is not None:
expected_rep = expected_rep.transform(M)
expected_pos = expected_rep.without_differentials()
if offset is not None:
expected_pos = expected_pos + offset.without_differentials()
expected_vel = None
if c.data.differentials:
expected_vel = expected_rep.differentials['s']
if offset and offset.differentials:
expected_vel = (expected_vel + offset.differentials['s'])
# register and do the transformation and check against expected
trans = t.AffineTransform(transfunc, TCoo1, TCoo2)
trans.register(frame_transform_graph)
c2 = c.transform_to(TCoo2)
assert quantity_allclose(c2.data.to_cartesian().xyz,
expected_pos.to_cartesian().xyz)
if expected_vel is not None:
diff = c2.data.differentials['s'].to_cartesian(base=c2.data)
assert quantity_allclose(diff.xyz, expected_vel.d_xyz)
trans.unregister(frame_transform_graph)
# these should fail
def transfunc_invalid_matrix(coo, fr):
return np.eye(4), None
# Leaving this open in case we want to add more functions to check for failures
@pytest.mark.parametrize('transfunc', [transfunc_invalid_matrix])
def test_affine_transform_fail(transfunc):
diff = r.CartesianDifferential(8, 9, 10, unit=u.pc/u.Myr)
rep = r.CartesianRepresentation(5, 6, 7, unit=u.pc, differentials=diff)
c = TCoo1(rep)
# register and do the transformation and check against expected
trans = t.AffineTransform(transfunc, TCoo1, TCoo2)
trans.register(frame_transform_graph)
with pytest.raises(ValueError):
c2 = c.transform_to(TCoo2)
trans.unregister(frame_transform_graph)
def test_too_many_differentials():
dif1 = r.CartesianDifferential(*np.arange(3, 6)*u.pc/u.Myr)
dif2 = r.CartesianDifferential(*np.arange(3, 6)*u.pc/u.Myr**2)
rep = r.CartesianRepresentation(np.arange(3)*u.pc,
differentials={'s': dif1, 's2': dif2})
with pytest.raises(ValueError):
c = TCoo1(rep)
# register and do the transformation and check against expected
trans = t.AffineTransform(transfunc.both, TCoo1, TCoo2)
trans.register(frame_transform_graph)
# Check that if frame somehow gets through to transformation, multiple
# differentials are caught
c = TCoo1(rep.without_differentials())
c._data = c._data.with_differentials({'s': dif1, 's2': dif2})
with pytest.raises(ValueError):
c2 = c.transform_to(TCoo2)
trans.unregister(frame_transform_graph)
# A matrix transform of a unit spherical with differentials should work
@pytest.mark.parametrize('rep', [
r.UnitSphericalRepresentation(lon=15*u.degree, lat=-11*u.degree,
differentials=r.SphericalDifferential(d_lon=15*u.mas/u.yr,
d_lat=11*u.mas/u.yr,
d_distance=-110*u.km/u.s)),
r.UnitSphericalRepresentation(lon=15*u.degree, lat=-11*u.degree,
differentials={'s': r.RadialDifferential(d_distance=-110*u.km/u.s)}),
r.SphericalRepresentation(lon=15*u.degree, lat=-11*u.degree,
distance=150*u.pc,
differentials={'s': r.RadialDifferential(d_distance=-110*u.km/u.s)})
])
def test_unit_spherical_with_differentials(rep):
c = TCoo1(rep)
# register and do the transformation and check against expected
trans = t.AffineTransform(transfunc.just_matrix, TCoo1, TCoo2)
trans.register(frame_transform_graph)
c2 = c.transform_to(TCoo2)
assert 's' in rep.differentials
assert isinstance(c2.data.differentials['s'],
rep.differentials['s'].__class__)
if isinstance(rep.differentials['s'], r.RadialDifferential):
assert c2.data.differentials['s'] is rep.differentials['s']
trans.unregister(frame_transform_graph)
# should fail if we have to do offsets
trans = t.AffineTransform(transfunc.both, TCoo1, TCoo2)
trans.register(frame_transform_graph)
with pytest.raises(TypeError):
c.transform_to(TCoo2)
trans.unregister(frame_transform_graph)
def test_vel_transformation_obstime_err():
# TODO: replace after a final decision on PR #6280
from ..sites import get_builtin_sites
diff = r.CartesianDifferential([.1, .2, .3]*u.km/u.s)
rep = r.CartesianRepresentation([1, 2, 3]*u.au, differentials=diff)
loc = get_builtin_sites()['example_site']
aaf = AltAz(obstime='J2010', location=loc)
aaf2 = AltAz(obstime=aaf.obstime + 3*u.day, location=loc)
aaf3 = AltAz(obstime=aaf.obstime + np.arange(3)*u.day, location=loc)
aaf4 = AltAz(obstime=aaf.obstime, location=loc)
aa = aaf.realize_frame(rep)
with pytest.raises(NotImplementedError) as exc:
aa.transform_to(aaf2)
assert 'cannot transform' in exc.value.args[0]
with pytest.raises(NotImplementedError) as exc:
aa.transform_to(aaf3)
assert 'cannot transform' in exc.value.args[0]
aa.transform_to(aaf4)
aa.transform_to(ICRS())
def test_function_transform_with_differentials():
tfun = lambda c, f: f.__class__(ra=c.ra, dec=c.dec)
ftrans = t.FunctionTransform(tfun, TCoo3, TCoo2,
register_graph=frame_transform_graph)
t3 = TCoo3(ra=1*u.deg, dec=2*u.deg, pm_ra_cosdec=1*u.marcsec/u.yr,
pm_dec=1*u.marcsec/u.yr,)
with catch_warnings() as w:
t2 = t3.transform_to(TCoo2)
assert len(w) == 1
assert 'they have been dropped' in str(w[0].message)
def test_frame_override_component_with_attribute():
"""
It was previously possible to define a frame with an attribute with the
same name as a component. We don't want to allow this!
"""
from ..baseframe import BaseCoordinateFrame
from ..attributes import Attribute
class BorkedFrame(BaseCoordinateFrame):
ra = Attribute(default=150)
dec = Attribute(default=150)
def trans_func(coo1, f):
pass
trans = t.FunctionTransform(trans_func, BorkedFrame, ICRS)
with pytest.raises(ValueError) as exc:
trans.register(frame_transform_graph)
assert ('BorkedFrame' in exc.value.args[0] and
"'ra'" in exc.value.args[0] and
"'dec'" in exc.value.args[0])
|
5a5e4c51bd90428cd45ceb8f90d980e9a97234f4c6115efe2213384fe2c35cfe | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from ... import units as u
from .. import (SphericalRepresentation, Longitude, Latitude,
SphericalDifferential)
class TestManipulation():
"""Manipulation of Representation shapes.
Checking that attributes are manipulated correctly.
Even more exhaustive tests are done in time.tests.test_methods
"""
def setup(self):
lon = Longitude(np.arange(0, 24, 4), u.hourangle)
lat = Latitude(np.arange(-90, 91, 30), u.deg)
# With same-sized arrays
self.s0 = SphericalRepresentation(
lon[:, np.newaxis] * np.ones(lat.shape),
lat * np.ones(lon.shape)[:, np.newaxis],
np.ones(lon.shape + lat.shape) * u.kpc)
self.diff = SphericalDifferential(
d_lon=np.ones(self.s0.shape)*u.mas/u.yr,
d_lat=np.ones(self.s0.shape)*u.mas/u.yr,
d_distance=np.ones(self.s0.shape)*u.km/u.s)
self.s0 = self.s0.with_differentials(self.diff)
# With unequal arrays -> these will be broadcasted.
self.s1 = SphericalRepresentation(lon[:, np.newaxis], lat, 1. * u.kpc,
differentials=self.diff)
# For completeness on some tests, also a cartesian one
self.c0 = self.s0.to_cartesian()
def test_ravel(self):
s0_ravel = self.s0.ravel()
assert type(s0_ravel) is type(self.s0)
assert s0_ravel.shape == (self.s0.size,)
assert np.all(s0_ravel.lon == self.s0.lon.ravel())
assert np.may_share_memory(s0_ravel.lon, self.s0.lon)
assert np.may_share_memory(s0_ravel.lat, self.s0.lat)
assert np.may_share_memory(s0_ravel.distance, self.s0.distance)
assert s0_ravel.differentials['s'].shape == (self.s0.size,)
# Since s1 was broadcast, ravel needs to make a copy.
s1_ravel = self.s1.ravel()
assert type(s1_ravel) is type(self.s1)
assert s1_ravel.shape == (self.s1.size,)
assert s1_ravel.differentials['s'].shape == (self.s1.size,)
assert np.all(s1_ravel.lon == self.s1.lon.ravel())
assert not np.may_share_memory(s1_ravel.lat, self.s1.lat)
def test_copy(self):
s0_copy = self.s0.copy()
s0_copy_diff = s0_copy.differentials['s']
assert s0_copy.shape == self.s0.shape
assert np.all(s0_copy.lon == self.s0.lon)
assert np.all(s0_copy.lat == self.s0.lat)
# Check copy was made of internal data.
assert not np.may_share_memory(s0_copy.distance, self.s0.distance)
assert not np.may_share_memory(s0_copy_diff.d_lon, self.diff.d_lon)
def test_flatten(self):
s0_flatten = self.s0.flatten()
s0_diff = s0_flatten.differentials['s']
assert s0_flatten.shape == (self.s0.size,)
assert s0_diff.shape == (self.s0.size,)
assert np.all(s0_flatten.lon == self.s0.lon.flatten())
assert np.all(s0_diff.d_lon == self.diff.d_lon.flatten())
# Flatten always copies.
assert not np.may_share_memory(s0_flatten.distance, self.s0.distance)
assert not np.may_share_memory(s0_diff.d_lon, self.diff.d_lon)
s1_flatten = self.s1.flatten()
assert s1_flatten.shape == (self.s1.size,)
assert np.all(s1_flatten.lon == self.s1.lon.flatten())
assert not np.may_share_memory(s1_flatten.lat, self.s1.lat)
def test_transpose(self):
s0_transpose = self.s0.transpose()
s0_diff = s0_transpose.differentials['s']
assert s0_transpose.shape == (7, 6)
assert s0_diff.shape == s0_transpose.shape
assert np.all(s0_transpose.lon == self.s0.lon.transpose())
assert np.all(s0_diff.d_lon == self.diff.d_lon.transpose())
assert np.may_share_memory(s0_transpose.distance, self.s0.distance)
assert np.may_share_memory(s0_diff.d_lon, self.diff.d_lon)
s1_transpose = self.s1.transpose()
s1_diff = s1_transpose.differentials['s']
assert s1_transpose.shape == (7, 6)
assert s1_diff.shape == s1_transpose.shape
assert np.all(s1_transpose.lat == self.s1.lat.transpose())
assert np.all(s1_diff.d_lon == self.diff.d_lon.transpose())
assert np.may_share_memory(s1_transpose.lat, self.s1.lat)
assert np.may_share_memory(s1_diff.d_lon, self.diff.d_lon)
# Only one check on T, since it just calls transpose anyway.
# Doing it on the CartesianRepresentation just for variety's sake.
c0_T = self.c0.T
assert c0_T.shape == (7, 6)
assert np.all(c0_T.x == self.c0.x.T)
assert np.may_share_memory(c0_T.y, self.c0.y)
def test_diagonal(self):
s0_diagonal = self.s0.diagonal()
s0_diff = s0_diagonal.differentials['s']
assert s0_diagonal.shape == (6,)
assert s0_diff.shape == s0_diagonal.shape
assert np.all(s0_diagonal.lat == self.s0.lat.diagonal())
assert np.all(s0_diff.d_lon == self.diff.d_lon.diagonal())
assert np.may_share_memory(s0_diagonal.lat, self.s0.lat)
assert np.may_share_memory(s0_diff.d_lon, self.diff.d_lon)
def test_swapaxes(self):
s1_swapaxes = self.s1.swapaxes(0, 1)
s1_diff = s1_swapaxes.differentials['s']
assert s1_swapaxes.shape == (7, 6)
assert s1_diff.shape == s1_swapaxes.shape
assert np.all(s1_swapaxes.lat == self.s1.lat.swapaxes(0, 1))
assert np.all(s1_diff.d_lon == self.diff.d_lon.swapaxes(0, 1))
assert np.may_share_memory(s1_swapaxes.lat, self.s1.lat)
assert np.may_share_memory(s1_diff.d_lon, self.diff.d_lon)
def test_reshape(self):
s0_reshape = self.s0.reshape(2, 3, 7)
s0_diff = s0_reshape.differentials['s']
assert s0_reshape.shape == (2, 3, 7)
assert s0_diff.shape == s0_reshape.shape
assert np.all(s0_reshape.lon == self.s0.lon.reshape(2, 3, 7))
assert np.all(s0_reshape.lat == self.s0.lat.reshape(2, 3, 7))
assert np.all(s0_reshape.distance == self.s0.distance.reshape(2, 3, 7))
assert np.may_share_memory(s0_reshape.lon, self.s0.lon)
assert np.may_share_memory(s0_reshape.lat, self.s0.lat)
assert np.may_share_memory(s0_reshape.distance, self.s0.distance)
s1_reshape = self.s1.reshape(3, 2, 7)
s1_diff = s1_reshape.differentials['s']
assert s1_reshape.shape == (3, 2, 7)
assert s1_diff.shape == s1_reshape.shape
assert np.all(s1_reshape.lat == self.s1.lat.reshape(3, 2, 7))
assert np.all(s1_diff.d_lon == self.diff.d_lon.reshape(3, 2, 7))
assert np.may_share_memory(s1_reshape.lat, self.s1.lat)
assert np.may_share_memory(s1_diff.d_lon, self.diff.d_lon)
# For reshape(3, 14), copying is necessary for lon, lat, but not for d
s1_reshape2 = self.s1.reshape(3, 14)
assert s1_reshape2.shape == (3, 14)
assert np.all(s1_reshape2.lon == self.s1.lon.reshape(3, 14))
assert not np.may_share_memory(s1_reshape2.lon, self.s1.lon)
assert s1_reshape2.distance.shape == (3, 14)
assert np.may_share_memory(s1_reshape2.distance, self.s1.distance)
def test_shape_setting(self):
# Shape-setting should be on the object itself, since copying removes
# zero-strides due to broadcasting. We reset the objects at the end.
self.s0.shape = (2, 3, 7)
assert self.s0.shape == (2, 3, 7)
assert self.s0.lon.shape == (2, 3, 7)
assert self.s0.lat.shape == (2, 3, 7)
assert self.s0.distance.shape == (2, 3, 7)
assert self.diff.shape == (2, 3, 7)
assert self.diff.d_lon.shape == (2, 3, 7)
assert self.diff.d_lat.shape == (2, 3, 7)
assert self.diff.d_distance.shape == (2, 3, 7)
# this works with the broadcasting.
self.s1.shape = (2, 3, 7)
assert self.s1.shape == (2, 3, 7)
assert self.s1.lon.shape == (2, 3, 7)
assert self.s1.lat.shape == (2, 3, 7)
assert self.s1.distance.shape == (2, 3, 7)
assert self.s1.distance.strides == (0, 0, 0)
# but this one does not.
oldshape = self.s1.shape
with pytest.raises(AttributeError):
self.s1.shape = (42,)
assert self.s1.shape == oldshape
assert self.s1.lon.shape == oldshape
assert self.s1.lat.shape == oldshape
assert self.s1.distance.shape == oldshape
# Finally, a more complicated one that checks that things get reset
# properly if it is not the first component that fails.
s2 = SphericalRepresentation(self.s1.lon.copy(), self.s1.lat,
self.s1.distance, copy=False)
assert 0 not in s2.lon.strides
assert 0 in s2.lat.strides
with pytest.raises(AttributeError):
s2.shape = (42,)
assert s2.shape == oldshape
assert s2.lon.shape == oldshape
assert s2.lat.shape == oldshape
assert s2.distance.shape == oldshape
assert 0 not in s2.lon.strides
assert 0 in s2.lat.strides
self.setup()
def test_squeeze(self):
s0_squeeze = self.s0.reshape(3, 1, 2, 1, 7).squeeze()
s0_diff = s0_squeeze.differentials['s']
assert s0_squeeze.shape == (3, 2, 7)
assert s0_diff.shape == s0_squeeze.shape
assert np.all(s0_squeeze.lat == self.s0.lat.reshape(3, 2, 7))
assert np.all(s0_diff.d_lon == self.diff.d_lon.reshape(3, 2, 7))
assert np.may_share_memory(s0_squeeze.lat, self.s0.lat)
def test_add_dimension(self):
s0_adddim = self.s0[:, np.newaxis, :]
s0_diff = s0_adddim.differentials['s']
assert s0_adddim.shape == (6, 1, 7)
assert s0_diff.shape == s0_adddim.shape
assert np.all(s0_adddim.lon == self.s0.lon[:, np.newaxis, :])
assert np.all(s0_diff.d_lon == self.diff.d_lon[:, np.newaxis, :])
assert np.may_share_memory(s0_adddim.lat, self.s0.lat)
def test_take(self):
s0_take = self.s0.take((5, 2))
s0_diff = s0_take.differentials['s']
assert s0_take.shape == (2,)
assert s0_diff.shape == s0_take.shape
assert np.all(s0_take.lon == self.s0.lon.take((5, 2)))
assert np.all(s0_diff.d_lon == self.diff.d_lon.take((5, 2)))
def test_broadcast_to(self):
s0_broadcast = self.s0._apply(np.broadcast_to, (3, 6, 7), subok=True)
s0_diff = s0_broadcast.differentials['s']
assert type(s0_broadcast) is type(self.s0)
assert s0_broadcast.shape == (3, 6, 7)
assert s0_diff.shape == s0_broadcast.shape
assert np.all(s0_broadcast.lon == self.s0.lon)
assert np.all(s0_broadcast.lat == self.s0.lat)
assert np.all(s0_broadcast.distance == self.s0.distance)
assert np.may_share_memory(s0_broadcast.lon, self.s0.lon)
assert np.may_share_memory(s0_broadcast.lat, self.s0.lat)
assert np.may_share_memory(s0_broadcast.distance, self.s0.distance)
s1_broadcast = self.s1._apply(np.broadcast_to, shape=(3, 6, 7),
subok=True)
s1_diff = s1_broadcast.differentials['s']
assert s1_broadcast.shape == (3, 6, 7)
assert s1_diff.shape == s1_broadcast.shape
assert np.all(s1_broadcast.lat == self.s1.lat)
assert np.all(s1_broadcast.lon == self.s1.lon)
assert np.all(s1_broadcast.distance == self.s1.distance)
assert s1_broadcast.distance.shape == (3, 6, 7)
assert np.may_share_memory(s1_broadcast.lat, self.s1.lat)
assert np.may_share_memory(s1_broadcast.lon, self.s1.lon)
assert np.may_share_memory(s1_broadcast.distance, self.s1.distance)
# A final test that "may_share_memory" equals "does_share_memory"
# Do this on a copy, to keep self.s0 unchanged.
sc = self.s0.copy()
assert not np.may_share_memory(sc.lon, self.s0.lon)
assert not np.may_share_memory(sc.lat, self.s0.lat)
sc_broadcast = sc._apply(np.broadcast_to, (3, 6, 7), subok=True)
assert np.may_share_memory(sc_broadcast.lon, sc.lon)
# Can only write to copy, not to broadcast version.
sc.lon[0, 0] = 22. * u.hourangle
assert np.all(sc_broadcast.lon[:, 0, 0] == 22. * u.hourangle)
|
32022759f3d78a50cb45a6c6083b2902be3645795fc4fd17c3df8706c24700e3 |
import pytest
import numpy as np
from ...tests.helper import assert_quantity_allclose
from ... import units as u
from ...time import Time
from .. import EarthLocation, SkyCoord, Angle
from ..sites import get_builtin_sites
@pytest.mark.parametrize('kind', ['heliocentric', 'barycentric'])
def test_basic(kind):
t0 = Time('2015-1-1')
loc = get_builtin_sites()['example_site']
sc = SkyCoord(0, 0, unit=u.deg, obstime=t0, location=loc)
rvc0 = sc.radial_velocity_correction(kind)
assert rvc0.shape == ()
assert rvc0.unit.is_equivalent(u.km/u.s)
scs = SkyCoord(0, 0, unit=u.deg, obstime=t0 + np.arange(10)*u.day,
location=loc)
rvcs = scs.radial_velocity_correction(kind)
assert rvcs.shape == (10,)
assert rvcs.unit.is_equivalent(u.km/u.s)
test_input_time = Time(2457244.5, format='jd')
# test_input_loc = EarthLocation.of_site('Cerro Paranal')
# to avoid the network hit we just copy here what that yields
test_input_loc = EarthLocation.from_geodetic(lon=-70.403*u.deg,
lat=-24.6252*u.deg,
height=2635*u.m)
def test_helio_iraf():
"""
Compare the heliocentric correction to the IRAF rvcorrect.
`generate_IRAF_input` function is provided to show how the comparison data
was produced
"""
# this is based on running IRAF with the output of `generate_IRAF_input` below
rvcorr_result = """
# RVCORRECT: Observatory parameters for European Southern Observatory: Paranal
# latitude = -24:37.5
# longitude = 70:24.2
# altitude = 2635
## HJD VOBS VHELIO VLSR VDIURNAL VLUNAR VANNUAL VSOLAR
2457244.50120 0.00 -10.36 -20.35 -0.034 -0.001 -10.325 -9.993
2457244.50025 0.00 -14.20 -23.86 -0.115 -0.004 -14.085 -9.656
2457244.50278 0.00 -2.29 -11.75 0.115 0.004 -2.413 -9.459
2457244.50025 0.00 -14.20 -23.86 -0.115 -0.004 -14.085 -9.656
2457244.49929 0.00 -17.41 -26.30 -0.192 -0.006 -17.214 -8.888
2457244.50317 0.00 -17.19 -17.44 0.078 0.001 -17.269 -0.253
2457244.50348 0.00 2.35 -6.21 0.192 0.006 2.156 -8.560
2457244.49959 0.00 2.13 -15.06 -0.078 -0.000 2.211 -17.194
2457244.49929 0.00 -17.41 -26.30 -0.192 -0.006 -17.214 -8.888
2457244.49835 0.00 -19.84 -27.56 -0.259 -0.008 -19.573 -7.721
2457244.50186 0.00 -24.47 -22.16 -0.038 -0.004 -24.433 2.313
2457244.50470 0.00 -11.11 -8.57 0.221 0.005 -11.332 2.534
2457244.50402 0.00 6.90 -0.38 0.259 0.008 6.629 -7.277
2457244.50051 0.00 11.53 -5.78 0.038 0.004 11.489 -17.311
2457244.49768 0.00 -1.84 -19.37 -0.221 -0.004 -1.612 -17.533
2457244.49835 0.00 -19.84 -27.56 -0.259 -0.008 -19.573 -7.721
2457244.49749 0.00 -21.38 -27.59 -0.315 -0.010 -21.056 -6.209
2457244.50109 0.00 -27.69 -22.90 -0.096 -0.006 -27.584 4.785
2457244.50457 0.00 -17.00 -9.30 0.196 0.003 -17.201 7.704
2457244.50532 0.00 2.62 2.97 0.340 0.009 2.276 0.349
2457244.50277 0.00 16.42 4.67 0.228 0.009 16.178 -11.741
2457244.49884 0.00 13.98 -5.48 -0.056 0.002 14.039 -19.463
2457244.49649 0.00 -2.84 -19.84 -0.297 -0.007 -2.533 -17.000
2457244.49749 0.00 -21.38 -27.59 -0.315 -0.010 -21.056 -6.209
2457244.49675 0.00 -21.97 -26.39 -0.357 -0.011 -21.598 -4.419
2457244.50025 0.00 -29.30 -22.47 -0.149 -0.008 -29.146 6.831
2457244.50398 0.00 -21.55 -9.88 0.146 0.001 -21.700 11.670
2457244.50577 0.00 -3.26 4.00 0.356 0.009 -3.623 7.263
2457244.50456 0.00 14.87 11.06 0.357 0.011 14.497 -3.808
2457244.50106 0.00 22.20 7.14 0.149 0.008 22.045 -15.058
2457244.49732 0.00 14.45 -5.44 -0.146 -0.001 14.600 -19.897
2457244.49554 0.00 -3.84 -19.33 -0.356 -0.008 -3.478 -15.491
2457244.49675 0.00 -21.97 -26.39 -0.357 -0.011 -21.598 -4.419
2457244.49615 0.00 -21.57 -24.00 -0.383 -0.012 -21.172 -2.432
2457244.49942 0.00 -29.36 -20.83 -0.193 -0.009 -29.157 8.527
2457244.50312 0.00 -24.26 -9.75 0.088 -0.001 -24.348 14.511
2457244.50552 0.00 -8.66 4.06 0.327 0.007 -8.996 12.721
2457244.50549 0.00 10.14 14.13 0.413 0.012 9.715 3.994
2457244.50305 0.00 23.35 15.76 0.306 0.011 23.031 -7.586
2457244.49933 0.00 24.78 8.18 0.056 0.006 24.721 -16.601
2457244.49609 0.00 13.77 -5.06 -0.221 -0.003 13.994 -18.832
2457244.49483 0.00 -4.53 -17.77 -0.394 -0.010 -4.131 -13.237
2457244.49615 0.00 -21.57 -24.00 -0.383 -0.012 -21.172 -2.432
2457244.49572 0.00 -20.20 -20.54 -0.392 -0.013 -19.799 -0.335
2457244.49907 0.00 -28.17 -17.30 -0.197 -0.009 -27.966 10.874
2457244.50285 0.00 -22.96 -5.96 0.090 -0.001 -23.048 16.995
2457244.50531 0.00 -7.00 8.16 0.335 0.007 -7.345 15.164
2457244.50528 0.00 12.23 18.47 0.423 0.012 11.795 6.238
2457244.50278 0.00 25.74 20.13 0.313 0.012 25.416 -5.607
2457244.49898 0.00 27.21 12.38 0.057 0.006 27.144 -14.829
2457244.49566 0.00 15.94 -1.17 -0.226 -0.003 16.172 -17.111
2457244.49437 0.00 -2.78 -14.17 -0.403 -0.010 -2.368 -11.387
2457244.49572 0.00 -20.20 -20.54 -0.392 -0.013 -19.799 -0.335
2457244.49548 0.00 -17.94 -16.16 -0.383 -0.012 -17.541 1.776
2457244.49875 0.00 -25.73 -12.99 -0.193 -0.009 -25.525 12.734
2457244.50246 0.00 -20.63 -1.91 0.088 -0.001 -20.716 18.719
2457244.50485 0.00 -5.03 11.90 0.327 0.007 -5.365 16.928
2457244.50482 0.00 13.77 21.97 0.413 0.012 13.347 8.202
2457244.50238 0.00 26.98 23.60 0.306 0.011 26.663 -3.378
2457244.49867 0.00 28.41 16.02 0.056 0.005 28.353 -12.393
2457244.49542 0.00 17.40 2.78 -0.221 -0.003 17.625 -14.625
2457244.49416 0.00 -0.90 -9.93 -0.394 -0.010 -0.499 -9.029
2457244.49548 0.00 -17.94 -16.16 -0.383 -0.012 -17.541 1.776
2457244.49544 0.00 -14.87 -11.06 -0.357 -0.011 -14.497 3.808
2457244.49894 0.00 -22.20 -7.14 -0.149 -0.008 -22.045 15.058
2457244.50268 0.00 -14.45 5.44 0.146 0.001 -14.600 19.897
2457244.50446 0.00 3.84 19.33 0.356 0.008 3.478 15.491
2457244.50325 0.00 21.97 26.39 0.357 0.011 21.598 4.419
2457244.49975 0.00 29.30 22.47 0.149 0.008 29.146 -6.831
2457244.49602 0.00 21.55 9.88 -0.146 -0.001 21.700 -11.670
2457244.49423 0.00 3.26 -4.00 -0.356 -0.009 3.623 -7.263
2457244.49544 0.00 -14.87 -11.06 -0.357 -0.011 -14.497 3.808
2457244.49561 0.00 -11.13 -5.46 -0.315 -0.010 -10.805 5.670
2457244.49921 0.00 -17.43 -0.77 -0.096 -0.006 -17.333 16.664
2457244.50269 0.00 -6.75 12.83 0.196 0.003 -6.949 19.583
2457244.50344 0.00 12.88 25.10 0.340 0.009 12.527 12.227
2457244.50089 0.00 26.67 26.80 0.228 0.009 26.430 0.137
2457244.49696 0.00 24.24 16.65 -0.056 0.002 24.290 -7.584
2457244.49461 0.00 7.42 2.29 -0.297 -0.007 7.719 -5.122
2457244.49561 0.00 -11.13 -5.46 -0.315 -0.010 -10.805 5.670
2457244.49598 0.00 -6.90 0.38 -0.259 -0.008 -6.629 7.277
2457244.49949 0.00 -11.53 5.78 -0.038 -0.004 -11.489 17.311
2457244.50232 0.00 1.84 19.37 0.221 0.004 1.612 17.533
2457244.50165 0.00 19.84 27.56 0.259 0.008 19.573 7.721
2457244.49814 0.00 24.47 22.16 0.038 0.004 24.433 -2.313
2457244.49530 0.00 11.11 8.57 -0.221 -0.005 11.332 -2.534
2457244.49598 0.00 -6.90 0.38 -0.259 -0.008 -6.629 7.277
2457244.49652 0.00 -2.35 6.21 -0.192 -0.006 -2.156 8.560
2457244.50041 0.00 -2.13 15.06 0.078 0.000 -2.211 17.194
2457244.50071 0.00 17.41 26.30 0.192 0.006 17.214 8.888
2457244.49683 0.00 17.19 17.44 -0.078 -0.001 17.269 0.253
2457244.49652 0.00 -2.35 6.21 -0.192 -0.006 -2.156 8.560
2457244.49722 0.00 2.29 11.75 -0.115 -0.004 2.413 9.459
2457244.49975 0.00 14.20 23.86 0.115 0.004 14.085 9.656
2457244.49722 0.00 2.29 11.75 -0.115 -0.004 2.413 9.459
2457244.49805 0.00 6.84 16.77 -0.034 -0.001 6.874 9.935
"""
vhs_iraf = []
for line in rvcorr_result.strip().split('\n'):
if not line.strip().startswith('#'):
vhs_iraf.append(float(line.split()[2]))
vhs_iraf = vhs_iraf*u.km/u.s
targets = SkyCoord(_get_test_input_radecs(), obstime=test_input_time,
location=test_input_loc)
vhs_astropy = targets.radial_velocity_correction('heliocentric')
assert_quantity_allclose(vhs_astropy, vhs_iraf, atol=150*u.m/u.s)
return vhs_astropy, vhs_iraf # for interactively examination
def generate_IRAF_input(writefn=None):
dt = test_input_time.utc.datetime
coos = _get_test_input_radecs()
lines = []
for ra, dec in zip(coos.ra, coos.dec):
rastr = Angle(ra).to_string(u.hour, sep=':')
decstr = Angle(dec).to_string(u.deg, sep=':')
msg = '{yr} {mo} {day} {uth}:{utmin} {ra} {dec}'
lines.append(msg.format(yr=dt.year, mo=dt.month, day=dt.day,
uth=dt.hour, utmin=dt.minute,
ra=rastr, dec=decstr))
if writefn:
with open(writefn, 'w') as f:
for l in lines:
f.write(l)
else:
for l in lines:
print(l)
print('Run IRAF as:\nastutil\nrvcorrect f=<filename> observatory=Paranal')
def _get_test_input_radecs():
ras = []
decs = []
for dec in np.linspace(-85, 85, 15):
nra = int(np.round(10*np.cos(dec*u.deg)).value)
ras1 = np.linspace(-180, 180-1e-6, nra)
ras.extend(ras1)
decs.extend([dec]*len(ras1))
return SkyCoord(ra=ras, dec=decs, unit=u.deg)
def test_barycorr():
# this is the result of calling _get_barycorr_bvcs
barycorr_bvcs = u.Quantity([
-10335.93326096, -14198.47605491, -2237.60012494, -14198.47595363,
-17425.46512587, -17131.70901174, 2424.37095076, 2130.61519166,
-17425.46495779, -19872.50026998, -24442.37091097, -11017.08975893,
6978.0622355, 11547.93333743, -1877.34772637, -19872.50004258,
-21430.08240017, -27669.14280689, -16917.08506807, 2729.57222968,
16476.49569232, 13971.97171764, -2898.04250914, -21430.08212368,
-22028.51337105, -29301.92349394, -21481.13036199, -3147.44828909,
14959.50065514, 22232.91155425, 14412.11903105, -3921.56359768,
-22028.51305781, -21641.01479409, -29373.0512649, -24205.90521765,
-8557.34138828, 10250.50350732, 23417.2299926, 24781.98057941,
13706.17339044, -4627.70005932, -21641.01445812, -20284.92627505,
-28193.91696959, -22908.51624166, -6901.82132125, 12336.45758056,
25804.51614607, 27200.50029664, 15871.21385688, -2882.24738355,
-20284.9259314, -18020.92947805, -25752.96564978, -20585.81957567,
-4937.25573801, 13870.58916957, 27037.31568441, 28402.06636994,
17326.25977035, -1007.62209045, -18020.92914212, -14950.33284575,
-22223.74260839, -14402.94943965, 3930.73265119, 22037.68163353,
29311.09265126, 21490.30070307, 3156.62229843, -14950.33253252,
-11210.53846867, -17449.59867676, -6697.54090389, 12949.11642965,
26696.03999586, 24191.5164355, 7321.50355488, -11210.53819218,
-6968.89359681, -11538.76423011, 1886.51695238, 19881.66902396,
24451.54039956, 11026.26000765, -6968.89336945, -2415.20201758,
-2121.44599781, 17434.63406085, 17140.87871753, -2415.2018495,
2246.76923076, 14207.64513054, 2246.76933194, 6808.40787728],
u.m/u.s)
# this tries the *other* way of calling radial_velocity_correction relative
# to the IRAF tests
targets = _get_test_input_radecs()
bvcs_astropy = targets.radial_velocity_correction(obstime=test_input_time,
location=test_input_loc,
kind='barycentric')
assert_quantity_allclose(bvcs_astropy, barycorr_bvcs, atol=10*u.mm/u.s)
return bvcs_astropy, barycorr_bvcs # for interactively examination
def _get_barycorr_bvcs(coos, loc, injupyter=False):
"""
Gets the barycentric correction of the test data from the
http://astroutils.astronomy.ohio-state.edu/exofast/barycorr.html web site.
Requires the https://github.com/tronsgaard/barycorr python interface to that
site.
Provided to reproduce the test data above, but not required to actually run
the tests.
"""
import barycorr
from ...utils.console import ProgressBar
bvcs = []
for ra, dec in ProgressBar(list(zip(coos.ra.deg, coos.dec.deg)),
ipython_widget=injupyter):
res = barycorr.bvc(test_input_time.utc.jd, ra, dec,
lat=loc.geodetic[1].deg,
lon=loc.geodetic[0].deg,
elevation=loc.geodetic[2].to(u.m).value)
bvcs.append(res)
return bvcs*u.m/u.s
def test_rvcorr_multiple_obstimes_onskycoord():
loc = EarthLocation(-2309223 * u.m, -3695529 * u.m, -4641767 * u.m)
arrtime = Time('2005-03-21 00:00:00') + np.linspace(-1, 1, 10)*u.day
sc = SkyCoord(1*u.deg, 2*u.deg, 100*u.kpc, obstime=arrtime, location=loc)
rvcbary_sc2 = sc.radial_velocity_correction(kind='barycentric')
assert len(rvcbary_sc2) == 10
# check the multiple-obstime and multi- mode
sc = SkyCoord(([1]*10)*u.deg, 2*u.deg, 100*u.kpc,
obstime=arrtime, location=loc)
rvcbary_sc3 = sc.radial_velocity_correction(kind='barycentric')
assert len(rvcbary_sc3) == 10
def test_invalid_argument_combos():
loc = EarthLocation(-2309223 * u.m, -3695529 * u.m, -4641767 * u.m)
time = Time('2005-03-21 00:00:00')
timel = Time('2005-03-21 00:00:00', location=loc)
scwattrs = SkyCoord(1*u.deg, 2*u.deg, obstime=time, location=loc)
scwoattrs = SkyCoord(1*u.deg, 2*u.deg)
scwattrs.radial_velocity_correction()
with pytest.raises(ValueError):
scwattrs.radial_velocity_correction(obstime=time, location=loc)
with pytest.raises(TypeError):
scwoattrs.radial_velocity_correction(obstime=time)
scwoattrs.radial_velocity_correction(obstime=time, location=loc)
with pytest.raises(TypeError):
scwoattrs.radial_velocity_correction()
with pytest.raises(ValueError):
scwattrs.radial_velocity_correction(timel)
|
c2fabe2a00d2d9dd3ca9570f569426e1dc3ac4f8f3d14f97a7f00f37b25bc45b | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from ... import units as u
from .. import Longitude, Latitude, EarthLocation, SkyCoord
# test on frame with most complicated frame attributes.
from ..builtin_frames import ICRS, AltAz, GCRS
from ...time import Time
class TestManipulation():
"""Manipulation of Frame shapes.
Checking that attributes are manipulated correctly.
Even more exhaustive tests are done in time.tests.test_methods
"""
def setup(self):
lon = Longitude(np.arange(0, 24, 4), u.hourangle)
lat = Latitude(np.arange(-90, 91, 30), u.deg)
# With same-sized arrays, no attributes
self.s0 = ICRS(lon[:, np.newaxis] * np.ones(lat.shape),
lat * np.ones(lon.shape)[:, np.newaxis])
# Make an AltAz frame since that has many types of attributes.
# Match one axis with times.
self.obstime = (Time('2012-01-01') +
np.arange(len(lon))[:, np.newaxis] * u.s)
# And another with location.
self.location = EarthLocation(20.*u.deg, lat, 100*u.m)
# Ensure we have a quantity scalar.
self.pressure = 1000 * u.hPa
# As well as an array.
self.temperature = np.random.uniform(
0., 20., size=(lon.size, lat.size)) * u.deg_C
self.s1 = AltAz(az=lon[:, np.newaxis], alt=lat,
obstime=self.obstime,
location=self.location,
pressure=self.pressure,
temperature=self.temperature)
# For some tests, also try a GCRS, since that has representation
# attributes. We match the second dimension (via the location)
self.obsgeoloc, self.obsgeovel = self.location.get_gcrs_posvel(
self.obstime[0, 0])
self.s2 = GCRS(ra=lon[:, np.newaxis], dec=lat,
obstime=self.obstime,
obsgeoloc=self.obsgeoloc,
obsgeovel=self.obsgeovel)
# For completeness, also some tests on an empty frame.
self.s3 = GCRS(obstime=self.obstime,
obsgeoloc=self.obsgeoloc,
obsgeovel=self.obsgeovel)
# And make a SkyCoord
self.sc = SkyCoord(ra=lon[:, np.newaxis], dec=lat, frame=self.s3)
def test_ravel(self):
s0_ravel = self.s0.ravel()
assert s0_ravel.shape == (self.s0.size,)
assert np.all(s0_ravel.data.lon == self.s0.data.lon.ravel())
assert np.may_share_memory(s0_ravel.data.lon, self.s0.data.lon)
assert np.may_share_memory(s0_ravel.data.lat, self.s0.data.lat)
# Since s1 lon, lat were broadcast, ravel needs to make a copy.
s1_ravel = self.s1.ravel()
assert s1_ravel.shape == (self.s1.size,)
assert np.all(s1_ravel.data.lon == self.s1.data.lon.ravel())
assert not np.may_share_memory(s1_ravel.data.lat, self.s1.data.lat)
assert np.all(s1_ravel.obstime == self.s1.obstime.ravel())
assert not np.may_share_memory(s1_ravel.obstime.jd1,
self.s1.obstime.jd1)
assert np.all(s1_ravel.location == self.s1.location.ravel())
assert not np.may_share_memory(s1_ravel.location, self.s1.location)
assert np.all(s1_ravel.temperature == self.s1.temperature.ravel())
assert np.may_share_memory(s1_ravel.temperature, self.s1.temperature)
assert s1_ravel.pressure == self.s1.pressure
s2_ravel = self.s2.ravel()
assert s2_ravel.shape == (self.s2.size,)
assert np.all(s2_ravel.data.lon == self.s2.data.lon.ravel())
assert not np.may_share_memory(s2_ravel.data.lat, self.s2.data.lat)
assert np.all(s2_ravel.obstime == self.s2.obstime.ravel())
assert not np.may_share_memory(s2_ravel.obstime.jd1,
self.s2.obstime.jd1)
# CartesianRepresentation do not allow direct comparisons, as this is
# too tricky to get right in the face of rounding issues. Here, though,
# it cannot be an issue, so we compare the xyz quantities.
assert np.all(s2_ravel.obsgeoloc.xyz == self.s2.obsgeoloc.ravel().xyz)
assert not np.may_share_memory(s2_ravel.obsgeoloc.x,
self.s2.obsgeoloc.x)
s3_ravel = self.s3.ravel()
assert s3_ravel.shape == (42,) # cannot use .size on frame w/o data.
assert np.all(s3_ravel.obstime == self.s3.obstime.ravel())
assert not np.may_share_memory(s3_ravel.obstime.jd1,
self.s3.obstime.jd1)
assert np.all(s3_ravel.obsgeoloc.xyz == self.s3.obsgeoloc.ravel().xyz)
assert not np.may_share_memory(s3_ravel.obsgeoloc.x,
self.s3.obsgeoloc.x)
sc_ravel = self.sc.ravel()
assert sc_ravel.shape == (self.sc.size,)
assert np.all(sc_ravel.data.lon == self.sc.data.lon.ravel())
assert not np.may_share_memory(sc_ravel.data.lat, self.sc.data.lat)
assert np.all(sc_ravel.obstime == self.sc.obstime.ravel())
assert not np.may_share_memory(sc_ravel.obstime.jd1,
self.sc.obstime.jd1)
assert np.all(sc_ravel.obsgeoloc.xyz == self.sc.obsgeoloc.ravel().xyz)
assert not np.may_share_memory(sc_ravel.obsgeoloc.x,
self.sc.obsgeoloc.x)
def test_flatten(self):
s0_flatten = self.s0.flatten()
assert s0_flatten.shape == (self.s0.size,)
assert np.all(s0_flatten.data.lon == self.s0.data.lon.flatten())
# Flatten always copies.
assert not np.may_share_memory(s0_flatten.data.lat, self.s0.data.lat)
s1_flatten = self.s1.flatten()
assert s1_flatten.shape == (self.s1.size,)
assert np.all(s1_flatten.data.lat == self.s1.data.lat.flatten())
assert not np.may_share_memory(s1_flatten.data.lon, self.s1.data.lat)
assert np.all(s1_flatten.obstime == self.s1.obstime.flatten())
assert not np.may_share_memory(s1_flatten.obstime.jd1,
self.s1.obstime.jd1)
assert np.all(s1_flatten.location == self.s1.location.flatten())
assert not np.may_share_memory(s1_flatten.location, self.s1.location)
assert np.all(s1_flatten.temperature == self.s1.temperature.flatten())
assert not np.may_share_memory(s1_flatten.temperature,
self.s1.temperature)
assert s1_flatten.pressure == self.s1.pressure
def test_transpose(self):
s0_transpose = self.s0.transpose()
assert s0_transpose.shape == (7, 6)
assert np.all(s0_transpose.data.lon == self.s0.data.lon.transpose())
assert np.may_share_memory(s0_transpose.data.lat, self.s0.data.lat)
s1_transpose = self.s1.transpose()
assert s1_transpose.shape == (7, 6)
assert np.all(s1_transpose.data.lat == self.s1.data.lat.transpose())
assert np.may_share_memory(s1_transpose.data.lon, self.s1.data.lon)
assert np.all(s1_transpose.obstime == self.s1.obstime.transpose())
assert np.may_share_memory(s1_transpose.obstime.jd1,
self.s1.obstime.jd1)
assert np.all(s1_transpose.location == self.s1.location.transpose())
assert np.may_share_memory(s1_transpose.location, self.s1.location)
assert np.all(s1_transpose.temperature ==
self.s1.temperature.transpose())
assert np.may_share_memory(s1_transpose.temperature,
self.s1.temperature)
assert s1_transpose.pressure == self.s1.pressure
# Only one check on T, since it just calls transpose anyway.
s1_T = self.s1.T
assert s1_T.shape == (7, 6)
assert np.all(s1_T.temperature == self.s1.temperature.T)
assert np.may_share_memory(s1_T.location, self.s1.location)
def test_diagonal(self):
s0_diagonal = self.s0.diagonal()
assert s0_diagonal.shape == (6,)
assert np.all(s0_diagonal.data.lat == self.s0.data.lat.diagonal())
assert np.may_share_memory(s0_diagonal.data.lat, self.s0.data.lat)
def test_swapaxes(self):
s1_swapaxes = self.s1.swapaxes(0, 1)
assert s1_swapaxes.shape == (7, 6)
assert np.all(s1_swapaxes.data.lat == self.s1.data.lat.swapaxes(0, 1))
assert np.may_share_memory(s1_swapaxes.data.lat, self.s1.data.lat)
assert np.all(s1_swapaxes.obstime == self.s1.obstime.swapaxes(0, 1))
assert np.may_share_memory(s1_swapaxes.obstime.jd1,
self.s1.obstime.jd1)
assert np.all(s1_swapaxes.location == self.s1.location.swapaxes(0, 1))
assert s1_swapaxes.location.shape == (7, 6)
assert np.may_share_memory(s1_swapaxes.location, self.s1.location)
assert np.all(s1_swapaxes.temperature ==
self.s1.temperature.swapaxes(0, 1))
assert np.may_share_memory(s1_swapaxes.temperature,
self.s1.temperature)
assert s1_swapaxes.pressure == self.s1.pressure
def test_reshape(self):
s0_reshape = self.s0.reshape(2, 3, 7)
assert s0_reshape.shape == (2, 3, 7)
assert np.all(s0_reshape.data.lon == self.s0.data.lon.reshape(2, 3, 7))
assert np.all(s0_reshape.data.lat == self.s0.data.lat.reshape(2, 3, 7))
assert np.may_share_memory(s0_reshape.data.lon, self.s0.data.lon)
assert np.may_share_memory(s0_reshape.data.lat, self.s0.data.lat)
s1_reshape = self.s1.reshape(3, 2, 7)
assert s1_reshape.shape == (3, 2, 7)
assert np.all(s1_reshape.data.lat == self.s1.data.lat.reshape(3, 2, 7))
assert np.may_share_memory(s1_reshape.data.lat, self.s1.data.lat)
assert np.all(s1_reshape.obstime == self.s1.obstime.reshape(3, 2, 7))
assert np.may_share_memory(s1_reshape.obstime.jd1,
self.s1.obstime.jd1)
assert np.all(s1_reshape.location == self.s1.location.reshape(3, 2, 7))
assert np.may_share_memory(s1_reshape.location, self.s1.location)
assert np.all(s1_reshape.temperature ==
self.s1.temperature.reshape(3, 2, 7))
assert np.may_share_memory(s1_reshape.temperature,
self.s1.temperature)
assert s1_reshape.pressure == self.s1.pressure
# For reshape(3, 14), copying is necessary for lon, lat, location, time
s1_reshape2 = self.s1.reshape(3, 14)
assert s1_reshape2.shape == (3, 14)
assert np.all(s1_reshape2.data.lon == self.s1.data.lon.reshape(3, 14))
assert not np.may_share_memory(s1_reshape2.data.lon, self.s1.data.lon)
assert np.all(s1_reshape2.obstime == self.s1.obstime.reshape(3, 14))
assert not np.may_share_memory(s1_reshape2.obstime.jd1,
self.s1.obstime.jd1)
assert np.all(s1_reshape2.location == self.s1.location.reshape(3, 14))
assert not np.may_share_memory(s1_reshape2.location, self.s1.location)
assert np.all(s1_reshape2.temperature ==
self.s1.temperature.reshape(3, 14))
assert np.may_share_memory(s1_reshape2.temperature,
self.s1.temperature)
assert s1_reshape2.pressure == self.s1.pressure
s2_reshape = self.s2.reshape(3, 2, 7)
assert s2_reshape.shape == (3, 2, 7)
assert np.all(s2_reshape.data.lon == self.s2.data.lon.reshape(3, 2, 7))
assert np.may_share_memory(s2_reshape.data.lat, self.s2.data.lat)
assert np.all(s2_reshape.obstime == self.s2.obstime.reshape(3, 2, 7))
assert np.may_share_memory(s2_reshape.obstime.jd1, self.s2.obstime.jd1)
assert np.all(s2_reshape.obsgeoloc.xyz ==
self.s2.obsgeoloc.reshape(3, 2, 7).xyz)
assert np.may_share_memory(s2_reshape.obsgeoloc.x, self.s2.obsgeoloc.x)
s3_reshape = self.s3.reshape(3, 2, 7)
assert s3_reshape.shape == (3, 2, 7)
assert np.all(s3_reshape.obstime == self.s3.obstime.reshape(3, 2, 7))
assert np.may_share_memory(s3_reshape.obstime.jd1, self.s3.obstime.jd1)
assert np.all(s3_reshape.obsgeoloc.xyz ==
self.s3.obsgeoloc.reshape(3, 2, 7).xyz)
assert np.may_share_memory(s3_reshape.obsgeoloc.x, self.s3.obsgeoloc.x)
sc_reshape = self.sc.reshape(3, 2, 7)
assert sc_reshape.shape == (3, 2, 7)
assert np.all(sc_reshape.data.lon == self.sc.data.lon.reshape(3, 2, 7))
assert np.may_share_memory(sc_reshape.data.lat, self.sc.data.lat)
assert np.all(sc_reshape.obstime == self.sc.obstime.reshape(3, 2, 7))
assert np.may_share_memory(sc_reshape.obstime.jd1, self.sc.obstime.jd1)
assert np.all(sc_reshape.obsgeoloc.xyz ==
self.sc.obsgeoloc.reshape(3, 2, 7).xyz)
assert np.may_share_memory(sc_reshape.obsgeoloc.x, self.sc.obsgeoloc.x)
# For reshape(3, 14), the arrays all need to be copied.
sc_reshape2 = self.sc.reshape(3, 14)
assert sc_reshape2.shape == (3, 14)
assert np.all(sc_reshape2.data.lon == self.sc.data.lon.reshape(3, 14))
assert not np.may_share_memory(sc_reshape2.data.lat,
self.sc.data.lat)
assert np.all(sc_reshape2.obstime == self.sc.obstime.reshape(3, 14))
assert not np.may_share_memory(sc_reshape2.obstime.jd1,
self.sc.obstime.jd1)
assert np.all(sc_reshape2.obsgeoloc.xyz ==
self.sc.obsgeoloc.reshape(3, 14).xyz)
assert not np.may_share_memory(sc_reshape2.obsgeoloc.x,
self.sc.obsgeoloc.x)
def test_squeeze(self):
s0_squeeze = self.s0.reshape(3, 1, 2, 1, 7).squeeze()
assert s0_squeeze.shape == (3, 2, 7)
assert np.all(s0_squeeze.data.lat == self.s0.data.lat.reshape(3, 2, 7))
assert np.may_share_memory(s0_squeeze.data.lat, self.s0.data.lat)
def test_add_dimension(self):
s0_adddim = self.s0[:, np.newaxis, :]
assert s0_adddim.shape == (6, 1, 7)
assert np.all(s0_adddim.data.lon == self.s0.data.lon[:, np.newaxis, :])
assert np.may_share_memory(s0_adddim.data.lat, self.s0.data.lat)
def test_take(self):
s0_take = self.s0.take((5, 2))
assert s0_take.shape == (2,)
assert np.all(s0_take.data.lon == self.s0.data.lon.take((5, 2)))
|
86a51e2f8e1b921a5c71874ccda5f85fa066b1667453ef1fea6239cd01b089d0 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from ... import units as u
from ..builtin_frames import ICRS, Galactic, Galactocentric
from .. import builtin_frames as bf
from ...tests.helper import quantity_allclose
from ..errors import ConvertError
from .. import representation as r
def test_api():
# transform observed Barycentric velocities to full-space Galactocentric
gc_frame = Galactocentric()
icrs = ICRS(ra=151.*u.deg, dec=-16*u.deg, distance=101*u.pc,
pm_ra_cosdec=21*u.mas/u.yr, pm_dec=-71*u.mas/u.yr,
radial_velocity=71*u.km/u.s)
icrs.transform_to(gc_frame)
# transform a set of ICRS proper motions to Galactic
icrs = ICRS(ra=151.*u.deg, dec=-16*u.deg,
pm_ra_cosdec=21*u.mas/u.yr, pm_dec=-71*u.mas/u.yr)
icrs.transform_to(Galactic)
# transform a Barycentric RV to a GSR RV
icrs = ICRS(ra=151.*u.deg, dec=-16*u.deg, distance=1.*u.pc,
pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr,
radial_velocity=71*u.km/u.s)
icrs.transform_to(Galactocentric)
all_kwargs = [
dict(ra=37.4*u.deg, dec=-55.8*u.deg),
dict(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc),
dict(ra=37.4*u.deg, dec=-55.8*u.deg,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr),
dict(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr),
dict(ra=37.4*u.deg, dec=-55.8*u.deg,
radial_velocity=105.7*u.km/u.s),
dict(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc,
radial_velocity=105.7*u.km/u.s),
dict(ra=37.4*u.deg, dec=-55.8*u.deg,
radial_velocity=105.7*u.km/u.s,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr),
dict(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr,
radial_velocity=105.7*u.km/u.s),
# Now test other representation/differential types:
dict(x=100.*u.pc, y=200*u.pc, z=300*u.pc,
representation_type='cartesian'),
dict(x=100.*u.pc, y=200*u.pc, z=300*u.pc,
representation_type=r.CartesianRepresentation),
dict(x=100.*u.pc, y=200*u.pc, z=300*u.pc,
v_x=100.*u.km/u.s, v_y=200*u.km/u.s, v_z=300*u.km/u.s,
representation_type=r.CartesianRepresentation,
differential_type=r.CartesianDifferential),
dict(x=100.*u.pc, y=200*u.pc, z=300*u.pc,
v_x=100.*u.km/u.s, v_y=200*u.km/u.s, v_z=300*u.km/u.s,
representation_type=r.CartesianRepresentation,
differential_type='cartesian'),
]
@pytest.mark.parametrize('kwargs', all_kwargs)
def test_all_arg_options(kwargs):
# Above is a list of all possible valid combinations of arguments.
# Here we do a simple thing and just verify that passing them in, we have
# access to the relevant attributes from the resulting object
icrs = ICRS(**kwargs)
gal = icrs.transform_to(Galactic)
repr_gal = repr(gal)
for k in kwargs:
if k == 'differential_type':
continue
getattr(icrs, k)
if 'pm_ra_cosdec' in kwargs: # should have both
assert 'pm_l_cosb' in repr_gal
assert 'pm_b' in repr_gal
assert 'mas / yr' in repr_gal
if 'radial_velocity' not in kwargs:
assert 'radial_velocity' not in repr_gal
if 'radial_velocity' in kwargs:
assert 'radial_velocity' in repr_gal
assert 'km / s' in repr_gal
if 'pm_ra_cosdec' not in kwargs:
assert 'pm_l_cosb' not in repr_gal
assert 'pm_b' not in repr_gal
@pytest.mark.parametrize('cls,lon,lat', [
[bf.ICRS, 'ra', 'dec'], [bf.FK4, 'ra', 'dec'], [bf.FK4NoETerms, 'ra', 'dec'],
[bf.FK5, 'ra', 'dec'], [bf.GCRS, 'ra', 'dec'], [bf.HCRS, 'ra', 'dec'],
[bf.LSR, 'ra', 'dec'], [bf.CIRS, 'ra', 'dec'], [bf.Galactic, 'l', 'b'],
[bf.AltAz, 'az', 'alt'], [bf.Supergalactic, 'sgl', 'sgb'],
[bf.GalacticLSR, 'l', 'b'], [bf.HeliocentricTrueEcliptic, 'lon', 'lat'],
[bf.GeocentricTrueEcliptic, 'lon', 'lat'],
[bf.BarycentricTrueEcliptic, 'lon', 'lat'],
[bf.PrecessedGeocentric, 'ra', 'dec']
])
def test_expected_arg_names(cls, lon, lat):
kwargs = {lon: 37.4*u.deg, lat: -55.8*u.deg, 'distance': 150*u.pc,
'pm_{0}_cos{1}'.format(lon, lat): -21.2*u.mas/u.yr,
'pm_{0}'.format(lat): 17.1*u.mas/u.yr,
'radial_velocity': 105.7*u.km/u.s}
frame = cls(**kwargs)
# these data are extracted from the vizier copy of XHIP:
# http://vizier.u-strasbg.fr/viz-bin/VizieR-3?-source=+V/137A/XHIP
_xhip_head = """
------ ------------ ------------ -------- -------- ------------ ------------ ------- -------- -------- ------- ------ ------ ------
R D pmRA pmDE Di pmGLon pmGLat RV U V W
HIP AJ2000 (deg) EJ2000 (deg) (mas/yr) (mas/yr) GLon (deg) GLat (deg) st (pc) (mas/yr) (mas/yr) (km/s) (km/s) (km/s) (km/s)
------ ------------ ------------ -------- -------- ------------ ------------ ------- -------- -------- ------- ------ ------ ------
"""[1:-1]
_xhip_data = """
19 000.05331690 +38.30408633 -3.17 -15.37 112.00026470 -23.47789171 247.12 -6.40 -14.33 6.30 7.3 2.0 -17.9
20 000.06295067 +23.52928427 36.11 -22.48 108.02779304 -37.85659811 95.90 29.35 -30.78 37.80 -19.3 16.1 -34.2
21 000.06623581 +08.00723430 61.48 -0.23 101.69697120 -52.74179515 183.68 58.06 -20.23 -11.72 -45.2 -30.9 -1.3
24917 080.09698238 -33.39874984 -4.30 13.40 236.92324669 -32.58047131 107.38 -14.03 -1.15 36.10 -22.4 -21.3 -19.9
59207 182.13915108 +65.34963517 18.17 5.49 130.04157185 51.18258601 56.00 -18.98 -0.49 5.70 1.5 6.1 4.4
87992 269.60730667 +36.87462906 -89.58 72.46 62.98053142 25.90148234 129.60 45.64 105.79 -4.00 -39.5 -15.8 56.7
115110 349.72322473 -28.74087144 48.86 -9.25 23.00447250 -69.52799804 116.87 -8.37 -49.02 15.00 -16.8 -12.2 -23.6
"""[1:-1]
# in principal we could parse the above as a table, but doing it "manually"
# makes this test less tied to Table working correctly
@pytest.mark.parametrize('hip,ra,dec,pmra,pmdec,glon,glat,dist,pmglon,pmglat,rv,U,V,W',
[[float(val) for val in row.split()] for row in _xhip_data.split('\n')])
def test_xhip_galactic(hip, ra, dec, pmra, pmdec, glon, glat, dist, pmglon, pmglat, rv, U, V, W):
i = ICRS(ra*u.deg, dec*u.deg, dist*u.pc,
pm_ra_cosdec=pmra*u.marcsec/u.yr, pm_dec=pmdec*u.marcsec/u.yr,
radial_velocity=rv*u.km/u.s)
g = i.transform_to(Galactic)
# precision is limited by 2-deciimal digit string representation of pms
assert quantity_allclose(g.pm_l_cosb, pmglon*u.marcsec/u.yr, atol=.01*u.marcsec/u.yr)
assert quantity_allclose(g.pm_b, pmglat*u.marcsec/u.yr, atol=.01*u.marcsec/u.yr)
# make sure UVW also makes sense
uvwg = g.cartesian.differentials['s']
# precision is limited by 1-decimal digit string representation of vels
assert quantity_allclose(uvwg.d_x, U*u.km/u.s, atol=.1*u.km/u.s)
assert quantity_allclose(uvwg.d_y, V*u.km/u.s, atol=.1*u.km/u.s)
assert quantity_allclose(uvwg.d_z, W*u.km/u.s, atol=.1*u.km/u.s)
@pytest.mark.parametrize('kwargs,expect_success', [
[dict(ra=37.4*u.deg, dec=-55.8*u.deg), False],
[dict(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc), True],
[dict(ra=37.4*u.deg, dec=-55.8*u.deg,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr), False],
[dict(ra=37.4*u.deg, dec=-55.8*u.deg, radial_velocity=105.7*u.km/u.s), False],
[dict(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc,
radial_velocity=105.7*u.km/u.s), False],
[dict(ra=37.4*u.deg, dec=-55.8*u.deg,
radial_velocity=105.7*u.km/u.s,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr), False],
[dict(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr,
radial_velocity=105.7*u.km/u.s), True]
])
def test_frame_affinetransform(kwargs, expect_success):
"""There are already tests in test_transformations.py that check that
an AffineTransform fails without full-space data, but this just checks that
things work as expected at the frame level as well.
"""
icrs = ICRS(**kwargs)
if expect_success:
gc = icrs.transform_to(Galactocentric)
else:
with pytest.raises(ConvertError):
icrs.transform_to(Galactocentric)
def test_differential_type_arg():
"""
Test passing in an explicit differential class to the initializer or
changing the differential class via set_representation_cls
"""
from ..builtin_frames import ICRS
icrs = ICRS(ra=1*u.deg, dec=60*u.deg,
pm_ra=10*u.mas/u.yr, pm_dec=-11*u.mas/u.yr,
differential_type=r.UnitSphericalDifferential)
assert icrs.pm_ra == 10*u.mas/u.yr
icrs = ICRS(ra=1*u.deg, dec=60*u.deg,
pm_ra=10*u.mas/u.yr, pm_dec=-11*u.mas/u.yr,
differential_type={'s': r.UnitSphericalDifferential})
assert icrs.pm_ra == 10*u.mas/u.yr
icrs = ICRS(ra=1*u.deg, dec=60*u.deg,
pm_ra_cosdec=10*u.mas/u.yr, pm_dec=-11*u.mas/u.yr)
icrs.set_representation_cls(s=r.UnitSphericalDifferential)
assert quantity_allclose(icrs.pm_ra, 20*u.mas/u.yr)
# incompatible representation and differential
with pytest.raises(TypeError):
ICRS(ra=1*u.deg, dec=60*u.deg,
v_x=1*u.km/u.s, v_y=-2*u.km/u.s, v_z=-2*u.km/u.s,
differential_type=r.CartesianDifferential)
# specify both
icrs = ICRS(x=1*u.pc, y=2*u.pc, z=3*u.pc,
v_x=1*u.km/u.s, v_y=2*u.km/u.s, v_z=3*u.km/u.s,
representation=r.CartesianRepresentation,
differential_type=r.CartesianDifferential)
assert icrs.x == 1*u.pc
assert icrs.y == 2*u.pc
assert icrs.z == 3*u.pc
assert icrs.v_x == 1*u.km/u.s
assert icrs.v_y == 2*u.km/u.s
assert icrs.v_z == 3*u.km/u.s
def test_slicing_preserves_differential():
icrs = ICRS(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr,
radial_velocity=105.7*u.km/u.s)
icrs2 = icrs.reshape(1,1)[:1,0]
for name in icrs.representation_component_names.keys():
assert getattr(icrs, name) == getattr(icrs2, name)[0]
for name in icrs.get_representation_component_names('s').keys():
assert getattr(icrs, name) == getattr(icrs2, name)[0]
def test_shorthand_attributes():
# Check that attribute access works
# for array data:
n = 4
icrs1 = ICRS(ra=np.random.uniform(0, 360, n)*u.deg,
dec=np.random.uniform(-90, 90, n)*u.deg,
distance=100*u.pc,
pm_ra_cosdec=np.random.normal(0, 100, n)*u.mas/u.yr,
pm_dec=np.random.normal(0, 100, n)*u.mas/u.yr,
radial_velocity=np.random.normal(0, 100, n)*u.km/u.s)
v = icrs1.velocity
pm = icrs1.proper_motion
assert quantity_allclose(pm[0], icrs1.pm_ra_cosdec)
assert quantity_allclose(pm[1], icrs1.pm_dec)
# for scalar data:
icrs2 = ICRS(ra=37.4*u.deg, dec=-55.8*u.deg, distance=150*u.pc,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr,
radial_velocity=105.7*u.km/u.s)
v = icrs2.velocity
pm = icrs2.proper_motion
assert quantity_allclose(pm[0], icrs2.pm_ra_cosdec)
assert quantity_allclose(pm[1], icrs2.pm_dec)
# check that it fails where we expect:
# no distance
rv = 105.7*u.km/u.s
icrs3 = ICRS(ra=37.4*u.deg, dec=-55.8*u.deg,
pm_ra_cosdec=-21.2*u.mas/u.yr, pm_dec=17.1*u.mas/u.yr,
radial_velocity=rv)
with pytest.raises(ValueError):
icrs3.velocity
icrs3.set_representation_cls('cartesian')
assert hasattr(icrs3, 'radial_velocity')
assert quantity_allclose(icrs3.radial_velocity, rv)
icrs4 = ICRS(x=30*u.pc, y=20*u.pc, z=11*u.pc,
v_x=10*u.km/u.s, v_y=10*u.km/u.s, v_z=10*u.km/u.s,
representation_type=r.CartesianRepresentation,
differential_type=r.CartesianDifferential)
icrs4.radial_velocity
|
838485d1c57a605512fbc2957bbae6656bfae0bb65d700628426d2c98b759037 | # -*- coding: utf-8 -*-
"""
Tests the Angle string formatting capabilities. SkyCoord formatting is in
test_sky_coord
"""
from ..angles import Angle
from ... import units as u
def test_to_string_precision():
# There are already some tests in test_api.py, but this is a regression
# test for the bug in issue #1319 which caused incorrect formatting of the
# seconds for precision=0
angle = Angle(-1.23456789, unit=u.degree)
assert angle.to_string(precision=3) == '-1d14m04.444s'
assert angle.to_string(precision=1) == '-1d14m04.4s'
assert angle.to_string(precision=0) == '-1d14m04s'
angle2 = Angle(-1.23456789, unit=u.hourangle)
assert angle2.to_string(precision=3, unit=u.hour) == '-1h14m04.444s'
assert angle2.to_string(precision=1, unit=u.hour) == '-1h14m04.4s'
assert angle2.to_string(precision=0, unit=u.hour) == '-1h14m04s'
# Regression test for #7141
angle3 = Angle(-0.5, unit=u.degree)
assert angle3.to_string(precision=0, fields=3) == '-0d30m00s'
assert angle3.to_string(precision=0, fields=2) == '-0d30m'
assert angle3.to_string(precision=0, fields=1) == '-1d'
def test_to_string_decimal():
# There are already some tests in test_api.py, but this is a regression
# test for the bug in issue #1323 which caused decimal formatting to not
# work
angle1 = Angle(2., unit=u.degree)
assert angle1.to_string(decimal=True, precision=3) == '2.000'
assert angle1.to_string(decimal=True, precision=1) == '2.0'
assert angle1.to_string(decimal=True, precision=0) == '2'
angle2 = Angle(3., unit=u.hourangle)
assert angle2.to_string(decimal=True, precision=3) == '3.000'
assert angle2.to_string(decimal=True, precision=1) == '3.0'
assert angle2.to_string(decimal=True, precision=0) == '3'
angle3 = Angle(4., unit=u.radian)
assert angle3.to_string(decimal=True, precision=3) == '4.000'
assert angle3.to_string(decimal=True, precision=1) == '4.0'
assert angle3.to_string(decimal=True, precision=0) == '4'
def test_to_string_formats():
a = Angle(1.113355, unit=u.deg)
assert a.to_string(format='latex') == r'$1^\circ06{}^\prime48.078{}^{\prime\prime}$'
assert a.to_string(format='unicode') == '1°06′48.078″'
a = Angle(1.113355, unit=u.hour)
assert a.to_string(format='latex') == r'$1^\mathrm{h}06^\mathrm{m}48.078^\mathrm{s}$'
assert a.to_string(format='unicode') == '1ʰ06ᵐ48.078ˢ'
a = Angle(1.113355, unit=u.radian)
assert a.to_string(format='latex') == r'$1.11336\mathrm{rad}$'
assert a.to_string(format='unicode') == '1.11336rad'
def test_to_string_fields():
a = Angle(1.113355, unit=u.deg)
assert a.to_string(fields=1) == r'1d'
assert a.to_string(fields=2) == r'1d07m'
assert a.to_string(fields=3) == r'1d06m48.078s'
def test_to_string_padding():
a = Angle(0.5653, unit=u.deg)
assert a.to_string(unit='deg', sep=':', pad=True) == r'00:33:55.08'
# Test to make sure negative angles are padded correctly
a = Angle(-0.5653, unit=u.deg)
assert a.to_string(unit='deg', sep=':', pad=True) == r'-00:33:55.08'
def test_sexagesimal_rounding_up():
a = Angle(359.9999999999, unit=u.deg)
assert a.to_string(precision=None) == '360d00m00s'
assert a.to_string(precision=4) == '360d00m00.0000s'
assert a.to_string(precision=5) == '360d00m00.00000s'
assert a.to_string(precision=6) == '360d00m00.000000s'
assert a.to_string(precision=7) == '359d59m59.9999996s'
a = Angle(3.999999, unit=u.deg)
assert a.to_string(fields=2, precision=None) == '4d00m'
assert a.to_string(fields=2, precision=1) == '4d00m'
assert a.to_string(fields=2, precision=5) == '4d00m'
assert a.to_string(fields=1, precision=1) == '4d'
assert a.to_string(fields=1, precision=5) == '4d'
def test_to_string_scalar():
a = Angle(1.113355, unit=u.deg)
assert isinstance(a.to_string(), str)
def test_to_string_radian_with_precision():
"""
Regression test for a bug that caused ``to_string`` to crash for angles in
radians when specifying the precision.
"""
# Check that specifying the precision works
a = Angle(3., unit=u.rad)
assert a.to_string(precision=3, sep='fromunit') == '3.000rad'
def test_sexagesimal_round_down():
a1 = Angle(1, u.deg).to(u.hourangle)
a2 = Angle(2, u.deg)
assert a1.to_string() == '0h04m00s'
assert a2.to_string() == '2d00m00s'
def test_to_string_fields_colon():
a = Angle(1.113355, unit=u.deg)
assert a.to_string(fields=2, sep=':') == '1:07'
assert a.to_string(fields=3, sep=':') == '1:06:48.078'
assert a.to_string(fields=1, sep=':') == '1'
|
96315e735c351352145f5659cf704b739ba87daf8c1e48aef8f9788e893b5257 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from ... import units as u
from ..distances import Distance
from ..builtin_frames import ICRS, FK5, Galactic, AltAz, SkyOffsetFrame
from .. import SkyCoord, EarthLocation
from ...time import Time
from ...tests.helper import assert_quantity_allclose as assert_allclose
@pytest.mark.parametrize("inradec,expectedlatlon, tolsep", [
((45, 45)*u.deg, (0, 0)*u.deg, .001*u.arcsec),
((45, 0)*u.deg, (0, -45)*u.deg, .001*u.arcsec),
((45, 90)*u.deg, (0, 45)*u.deg, .001*u.arcsec),
((46, 45)*u.deg, (1*np.cos(45*u.deg), 0)*u.deg, 16*u.arcsec),
])
def test_skyoffset(inradec, expectedlatlon, tolsep, originradec=(45, 45)*u.deg):
origin = ICRS(*originradec)
skyoffset_frame = SkyOffsetFrame(origin=origin)
skycoord = SkyCoord(*inradec, frame=ICRS)
skycoord_inaf = skycoord.transform_to(skyoffset_frame)
assert hasattr(skycoord_inaf, 'lon')
assert hasattr(skycoord_inaf, 'lat')
expected = SkyCoord(*expectedlatlon, frame=skyoffset_frame)
assert skycoord_inaf.separation(expected) < tolsep
def test_skyoffset_functional_ra():
# we do the 12)[1:-1] business because sometimes machine precision issues
# lead to results that are either ~0 or ~360, which mucks up the final
# comparison and leads to spurious failures. So this just avoids that by
# staying away from the edges
input_ra = np.linspace(0, 360, 12)[1:-1]
input_dec = np.linspace(-90, 90, 12)[1:-1]
icrs_coord = ICRS(ra=input_ra*u.deg,
dec=input_dec*u.deg,
distance=1.*u.kpc)
for ra in np.linspace(0, 360, 24):
# expected rotation
expected = ICRS(ra=np.linspace(0-ra, 360-ra, 12)[1:-1]*u.deg,
dec=np.linspace(-90, 90, 12)[1:-1]*u.deg,
distance=1.*u.kpc)
expected_xyz = expected.cartesian.xyz
# actual transformation to the frame
skyoffset_frame = SkyOffsetFrame(origin=ICRS(ra*u.deg, 0*u.deg))
actual = icrs_coord.transform_to(skyoffset_frame)
actual_xyz = actual.cartesian.xyz
# back to ICRS
roundtrip = actual.transform_to(ICRS)
roundtrip_xyz = roundtrip.cartesian.xyz
# Verify
assert_allclose(actual_xyz, expected_xyz, atol=1E-5*u.kpc)
assert_allclose(icrs_coord.ra, roundtrip.ra, atol=1E-5*u.deg)
assert_allclose(icrs_coord.dec, roundtrip.dec, atol=1E-5*u.deg)
assert_allclose(icrs_coord.distance, roundtrip.distance, atol=1E-5*u.kpc)
def test_skyoffset_functional_dec():
# we do the 12)[1:-1] business because sometimes machine precision issues
# lead to results that are either ~0 or ~360, which mucks up the final
# comparison and leads to spurious failures. So this just avoids that by
# staying away from the edges
input_ra = np.linspace(0, 360, 12)[1:-1]
input_dec = np.linspace(-90, 90, 12)[1:-1]
input_ra_rad = np.deg2rad(input_ra)
input_dec_rad = np.deg2rad(input_dec)
icrs_coord = ICRS(ra=input_ra*u.deg,
dec=input_dec*u.deg,
distance=1.*u.kpc)
# Dec rotations
# Done in xyz space because dec must be [-90,90]
for dec in np.linspace(-90, 90, 13):
# expected rotation
dec_rad = -np.deg2rad(dec)
expected_x = (-np.sin(input_dec_rad) * np.sin(dec_rad) +
np.cos(input_ra_rad) * np.cos(input_dec_rad) * np.cos(dec_rad))
expected_y = (np.sin(input_ra_rad) * np.cos(input_dec_rad))
expected_z = (np.sin(input_dec_rad) * np.cos(dec_rad) +
np.sin(dec_rad) * np.cos(input_ra_rad) * np.cos(input_dec_rad))
expected = SkyCoord(x=expected_x,
y=expected_y,
z=expected_z, unit='kpc', representation='cartesian')
expected_xyz = expected.cartesian.xyz
# actual transformation to the frame
skyoffset_frame = SkyOffsetFrame(origin=ICRS(0*u.deg, dec*u.deg))
actual = icrs_coord.transform_to(skyoffset_frame)
actual_xyz = actual.cartesian.xyz
# back to ICRS
roundtrip = actual.transform_to(ICRS)
# Verify
assert_allclose(actual_xyz, expected_xyz, atol=1E-5*u.kpc)
assert_allclose(icrs_coord.ra, roundtrip.ra, atol=1E-5*u.deg)
assert_allclose(icrs_coord.dec, roundtrip.dec, atol=1E-5*u.deg)
assert_allclose(icrs_coord.distance, roundtrip.distance, atol=1E-5*u.kpc)
def test_skyoffset_functional_ra_dec():
# we do the 12)[1:-1] business because sometimes machine precision issues
# lead to results that are either ~0 or ~360, which mucks up the final
# comparison and leads to spurious failures. So this just avoids that by
# staying away from the edges
input_ra = np.linspace(0, 360, 12)[1:-1]
input_dec = np.linspace(-90, 90, 12)[1:-1]
input_ra_rad = np.deg2rad(input_ra)
input_dec_rad = np.deg2rad(input_dec)
icrs_coord = ICRS(ra=input_ra*u.deg,
dec=input_dec*u.deg,
distance=1.*u.kpc)
for ra in np.linspace(0, 360, 10):
for dec in np.linspace(-90, 90, 5):
# expected rotation
dec_rad = -np.deg2rad(dec)
ra_rad = np.deg2rad(ra)
expected_x = (-np.sin(input_dec_rad) * np.sin(dec_rad) +
np.cos(input_ra_rad) * np.cos(input_dec_rad) * np.cos(dec_rad) * np.cos(ra_rad) +
np.sin(input_ra_rad) * np.cos(input_dec_rad) * np.cos(dec_rad) * np.sin(ra_rad))
expected_y = (np.sin(input_ra_rad) * np.cos(input_dec_rad) * np.cos(ra_rad) -
np.cos(input_ra_rad) * np.cos(input_dec_rad) * np.sin(ra_rad))
expected_z = (np.sin(input_dec_rad) * np.cos(dec_rad) +
np.sin(dec_rad) * np.cos(ra_rad) * np.cos(input_ra_rad) * np.cos(input_dec_rad) +
np.sin(dec_rad) * np.sin(ra_rad) * np.sin(input_ra_rad) * np.cos(input_dec_rad))
expected = SkyCoord(x=expected_x,
y=expected_y,
z=expected_z, unit='kpc', representation='cartesian')
expected_xyz = expected.cartesian.xyz
# actual transformation to the frame
skyoffset_frame = SkyOffsetFrame(origin=ICRS(ra*u.deg, dec*u.deg))
actual = icrs_coord.transform_to(skyoffset_frame)
actual_xyz = actual.cartesian.xyz
# back to ICRS
roundtrip = actual.transform_to(ICRS)
# Verify
assert_allclose(actual_xyz, expected_xyz, atol=1E-5*u.kpc)
assert_allclose(icrs_coord.ra, roundtrip.ra, atol=1E-4*u.deg)
assert_allclose(icrs_coord.dec, roundtrip.dec, atol=1E-5*u.deg)
assert_allclose(icrs_coord.distance, roundtrip.distance, atol=1E-5*u.kpc)
def test_skycoord_skyoffset_frame():
m31 = SkyCoord(10.6847083, 41.26875, frame='icrs', unit=u.deg)
m33 = SkyCoord(23.4621, 30.6599417, frame='icrs', unit=u.deg)
m31_astro = m31.skyoffset_frame()
m31_in_m31 = m31.transform_to(m31_astro)
m33_in_m31 = m33.transform_to(m31_astro)
assert_allclose([m31_in_m31.lon, m31_in_m31.lat], [0, 0]*u.deg, atol=1e-10*u.deg)
assert_allclose([m33_in_m31.lon, m33_in_m31.lat], [11.13135175, -9.79084759]*u.deg)
assert_allclose(m33.separation(m31),
np.hypot(m33_in_m31.lon, m33_in_m31.lat),
atol=.1*u.deg)
# used below in the next parametrized test
m31_sys = [ICRS, FK5, Galactic]
m31_coo = [(10.6847929, 41.2690650), (10.6847929, 41.2690650), (121.1744050, -21.5729360)]
m31_dist = Distance(770, u.kpc)
convert_precision = 1 * u.arcsec
roundtrip_precision = 1e-4 * u.degree
dist_precision = 1e-9 * u.kpc
m31_params = []
for i in range(len(m31_sys)):
for j in range(len(m31_sys)):
if i < j:
m31_params.append((m31_sys[i], m31_sys[j], m31_coo[i], m31_coo[j]))
@pytest.mark.parametrize(('fromsys', 'tosys', 'fromcoo', 'tocoo'), m31_params)
def test_m31_coord_transforms(fromsys, tosys, fromcoo, tocoo):
"""
This tests a variety of coordinate conversions for the Chandra point-source
catalog location of M31 from NED, via SkyOffsetFrames
"""
from_origin = fromsys(fromcoo[0]*u.deg, fromcoo[1]*u.deg,
distance=m31_dist)
from_pos = SkyOffsetFrame(1*u.deg, 1*u.deg, origin=from_origin)
to_origin = tosys(tocoo[0]*u.deg, tocoo[1]*u.deg, distance=m31_dist)
to_astroframe = SkyOffsetFrame(origin=to_origin)
target_pos = from_pos.transform_to(to_astroframe)
assert_allclose(to_origin.separation(target_pos),
np.hypot(from_pos.lon, from_pos.lat),
atol=convert_precision)
roundtrip_pos = target_pos.transform_to(from_pos)
assert_allclose([roundtrip_pos.lon.wrap_at(180*u.deg), roundtrip_pos.lat],
[1.0*u.deg, 1.0*u.deg], atol=convert_precision)
def test_altaz_attribute_transforms():
"""Test transforms between AltAz frames with different attributes."""
el1 = EarthLocation(0*u.deg, 0*u.deg, 0*u.m)
origin1 = AltAz(0 * u.deg, 0*u.deg, obstime=Time("2000-01-01T12:00:00"),
location=el1)
frame1 = SkyOffsetFrame(origin=origin1)
coo1 = SkyCoord(1 * u.deg, 1 * u.deg, frame=frame1)
el2 = EarthLocation(0*u.deg, 0*u.deg, 0*u.m)
origin2 = AltAz(0 * u.deg, 0*u.deg, obstime=Time("2000-01-01T11:00:00"),
location=el2)
frame2 = SkyOffsetFrame(origin=origin2)
coo2 = coo1.transform_to(frame2)
coo2_expected = [1.22522446, 0.70624298] * u.deg
assert_allclose([coo2.lon.wrap_at(180*u.deg), coo2.lat],
coo2_expected, atol=convert_precision)
el3 = EarthLocation(0*u.deg, 90*u.deg, 0*u.m)
origin3 = AltAz(0 * u.deg, 90*u.deg, obstime=Time("2000-01-01T12:00:00"),
location=el3)
frame3 = SkyOffsetFrame(origin=origin3)
coo3 = coo2.transform_to(frame3)
assert_allclose([coo3.lon.wrap_at(180*u.deg), coo3.lat],
[1*u.deg, 1*u.deg], atol=convert_precision)
@pytest.mark.parametrize("rotation, expectedlatlon", [
(0*u.deg, [0, 1]*u.deg),
(180*u.deg, [0, -1]*u.deg),
(90*u.deg, [-1, 0]*u.deg),
(-90*u.deg, [1, 0]*u.deg)
])
def test_rotation(rotation, expectedlatlon):
origin = ICRS(45*u.deg, 45*u.deg)
target = ICRS(45*u.deg, 46*u.deg)
aframe = SkyOffsetFrame(origin=origin, rotation=rotation)
trans = target.transform_to(aframe)
assert_allclose([trans.lon.wrap_at(180*u.deg), trans.lat],
expectedlatlon, atol=1e-10*u.deg)
@pytest.mark.parametrize("rotation, expectedlatlon", [
(0*u.deg, [0, 1]*u.deg),
(180*u.deg, [0, -1]*u.deg),
(90*u.deg, [-1, 0]*u.deg),
(-90*u.deg, [1, 0]*u.deg)
])
def test_skycoord_skyoffset_frame_rotation(rotation, expectedlatlon):
"""Test if passing a rotation argument via SkyCoord works"""
origin = SkyCoord(45*u.deg, 45*u.deg)
target = SkyCoord(45*u.deg, 46*u.deg)
aframe = origin.skyoffset_frame(rotation=rotation)
trans = target.transform_to(aframe)
assert_allclose([trans.lon.wrap_at(180*u.deg), trans.lat],
expectedlatlon, atol=1e-10*u.deg)
def test_skyoffset_names():
origin1 = ICRS(45*u.deg, 45*u.deg)
aframe1 = SkyOffsetFrame(origin=origin1)
assert type(aframe1).__name__ == 'SkyOffsetICRS'
origin2 = Galactic(45*u.deg, 45*u.deg)
aframe2 = SkyOffsetFrame(origin=origin2)
assert type(aframe2).__name__ == 'SkyOffsetGalactic'
def test_skyoffset_origindata():
origin = ICRS()
with pytest.raises(ValueError):
SkyOffsetFrame(origin=origin)
def test_skyoffset_lonwrap():
origin = ICRS(45*u.deg, 45*u.deg)
sc = SkyCoord(190*u.deg, -45*u.deg, frame=SkyOffsetFrame(origin=origin))
assert sc.lon < 180 * u.deg
def test_skyoffset_velocity():
c = ICRS(ra=170.9*u.deg, dec=-78.4*u.deg,
pm_ra_cosdec=74.4134*u.mas/u.yr,
pm_dec=-93.2342*u.mas/u.yr)
skyoffset_frame = SkyOffsetFrame(origin=c)
c_skyoffset = c.transform_to(skyoffset_frame)
assert_allclose(c_skyoffset.pm_lon_coslat, c.pm_ra_cosdec)
assert_allclose(c_skyoffset.pm_lat, c.pm_dec)
@pytest.mark.parametrize("rotation, expectedpmlonlat", [
(0*u.deg, [1, 2]*u.mas/u.yr),
(45*u.deg, [-2**-0.5, 3*2**-0.5]*u.mas/u.yr),
(90*u.deg, [-2, 1]*u.mas/u.yr),
(180*u.deg, [-1, -2]*u.mas/u.yr),
(-90*u.deg, [2, -1]*u.mas/u.yr)
])
def test_skyoffset_velocity_rotation(rotation, expectedpmlonlat):
sc = SkyCoord(ra=170.9*u.deg, dec=-78.4*u.deg,
pm_ra_cosdec=1*u.mas/u.yr,
pm_dec=2*u.mas/u.yr)
c_skyoffset0 = sc.transform_to(sc.skyoffset_frame(rotation=rotation))
assert_allclose(c_skyoffset0.pm_lon_coslat, expectedpmlonlat[0])
assert_allclose(c_skyoffset0.pm_lat, expectedpmlonlat[1])
|
2c5daedd0a84782a72b4ee73a267cdad809943072f33eba4d2b47282bc453c64 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains tests for the name resolve convenience module.
"""
import time
import urllib.request
import pytest
import numpy as np
from ..name_resolve import (get_icrs_coordinates, NameResolveError,
sesame_database, _parse_response, sesame_url)
from ..sky_coordinate import SkyCoord
from ... import units as u
_cached_ngc3642 = dict()
_cached_ngc3642["simbad"] = """# NGC 3642 #Q22523669
#=S=Simbad (via url): 1
%@ 503952
%I.0 NGC 3642
%C.0 LIN
%C.N0 15.15.01.00
%J 170.5750583 +59.0742417 = 11:22:18.01 +59:04:27.2
%V z 1593 0.005327 [0.000060] D 2002LEDA.........0P
%D 1.673 1.657 75 (32767) (I) C 2006AJ....131.1163S
%T 5 =32800000 D 2011A&A...532A..74B
%#B 140
#====Done (2013-Feb-12,16:37:11z)===="""
_cached_ngc3642["vizier"] = """# NGC 3642 #Q22523677
#=V=VizieR (local): 1
%J 170.56 +59.08 = 11:22.2 +59:05
%I.0 {NGC} 3642
#====Done (2013-Feb-12,16:37:42z)===="""
_cached_ngc3642["all"] = """# ngc3642 #Q22523722
#=S=Simbad (via url): 1
%@ 503952
%I.0 NGC 3642
%C.0 LIN
%C.N0 15.15.01.00
%J 170.5750583 +59.0742417 = 11:22:18.01 +59:04:27.2
%V z 1593 0.005327 [0.000060] D 2002LEDA.........0P
%D 1.673 1.657 75 (32767) (I) C 2006AJ....131.1163S
%T 5 =32800000 D 2011A&A...532A..74B
%#B 140
#=V=VizieR (local): 1
%J 170.56 +59.08 = 11:22.2 +59:05
%I.0 {NGC} 3642
#!N=NED : *** Could not access the server ***
#====Done (2013-Feb-12,16:39:48z)===="""
_cached_castor = dict()
_cached_castor["all"] = """# castor #Q22524249
#=S=Simbad (via url): 1
%@ 983633
%I.0 NAME CASTOR
%C.0 **
%C.N0 12.13.00.00
%J 113.649471640 +31.888282216 = 07:34:35.87 +31:53:17.8
%J.E [34.72 25.95 0] A 2007A&A...474..653V
%P -191.45 -145.19 [3.95 2.95 0] A 2007A&A...474..653V
%X 64.12 [3.75] A 2007A&A...474..653V
%S A1V+A2Vm =0.0000D200.0030.0110000000100000 C 2001AJ....122.3466M
%#B 179
#!V=VizieR (local): No table found for: castor
#!N=NED: ****object name not recognized by NED name interpreter
#!N=NED: ***Not recognized by NED: castor
#====Done (2013-Feb-12,16:52:02z)===="""
_cached_castor["simbad"] = """# castor #Q22524495
#=S=Simbad (via url): 1
%@ 983633
%I.0 NAME CASTOR
%C.0 **
%C.N0 12.13.00.00
%J 113.649471640 +31.888282216 = 07:34:35.87 +31:53:17.8
%J.E [34.72 25.95 0] A 2007A&A...474..653V
%P -191.45 -145.19 [3.95 2.95 0] A 2007A&A...474..653V
%X 64.12 [3.75] A 2007A&A...474..653V
%S A1V+A2Vm =0.0000D200.0030.0110000000100000 C 2001AJ....122.3466M
%#B 179
#====Done (2013-Feb-12,17:00:39z)===="""
@pytest.mark.remote_data
def test_names():
# First check that sesame is up
if urllib.request.urlopen("http://cdsweb.u-strasbg.fr/cgi-bin/nph-sesame").getcode() != 200:
pytest.skip("SESAME appears to be down, skipping test_name_resolve.py:test_names()...")
with pytest.raises(NameResolveError):
get_icrs_coordinates("m87h34hhh")
try:
icrs = get_icrs_coordinates("NGC 3642")
except NameResolveError:
ra, dec = _parse_response(_cached_ngc3642["all"])
icrs = SkyCoord(ra=float(ra)*u.degree, dec=float(dec)*u.degree)
icrs_true = SkyCoord(ra="11h 22m 18.014s", dec="59d 04m 27.27s")
# use precision of only 1 decimal here and below because the result can
# change due to Sesame server-side changes.
np.testing.assert_almost_equal(icrs.ra.degree, icrs_true.ra.degree, 1)
np.testing.assert_almost_equal(icrs.dec.degree, icrs_true.dec.degree, 1)
try:
icrs = get_icrs_coordinates("castor")
except NameResolveError:
ra, dec = _parse_response(_cached_castor["all"])
icrs = SkyCoord(ra=float(ra)*u.degree, dec=float(dec)*u.degree)
icrs_true = SkyCoord(ra="07h 34m 35.87s", dec="+31d 53m 17.8s")
np.testing.assert_almost_equal(icrs.ra.degree, icrs_true.ra.degree, 1)
np.testing.assert_almost_equal(icrs.dec.degree, icrs_true.dec.degree, 1)
@pytest.mark.remote_data
@pytest.mark.parametrize(("name", "db_dict"), [('NGC 3642', _cached_ngc3642),
('castor', _cached_castor)])
def test_database_specify(name, db_dict):
# First check that at least some sesame mirror is up
for url in sesame_url.get():
if urllib.request.urlopen(url).getcode() == 200:
break
else:
pytest.skip("All SESAME mirrors appear to be down, skipping "
"test_name_resolve.py:test_database_specify()...")
for db in db_dict.keys():
with sesame_database.set(db):
icrs = SkyCoord.from_name(name)
time.sleep(1)
|
c4e4a252e89619f049fe36cdaec13741426a8fa6011d999424c5ea94ea226f2b | import pickle
import pytest
import numpy as np
from ...coordinates import Longitude
from ... import coordinates as coord
from ...tests.helper import pickle_protocol, check_pickling_recovery # noqa
# Can't test distances without scipy due to cosmology deps
try:
import scipy # pylint: disable=W0611
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
def test_basic():
lon1 = Longitude(1.23, "radian", wrap_angle='180d')
s = pickle.dumps(lon1)
lon2 = pickle.loads(s)
def test_pickle_longitude_wrap_angle():
a = Longitude(1.23, "radian", wrap_angle='180d')
s = pickle.dumps(a)
b = pickle.loads(s)
assert a.rad == b.rad
assert a.wrap_angle == b.wrap_angle
_names = [coord.Angle,
coord.Distance,
coord.DynamicMatrixTransform,
coord.ICRS,
coord.Latitude,
coord.Longitude,
coord.StaticMatrixTransform,
]
_xfail = [False,
not HAS_SCIPY,
True,
True,
False,
True,
False]
_args = [[0.0],
[],
[lambda *args: np.identity(3), coord.ICRS, coord.ICRS],
[0, 0],
[0],
[0],
[np.identity(3), coord.ICRS, coord.ICRS],
]
_kwargs = [{'unit': 'radian'},
{'z': 0.23},
{},
{'unit': ['radian', 'radian']},
{'unit': 'radian'},
{'unit': 'radian'},
{},
]
@pytest.mark.parametrize(("name", "args", "kwargs", "xfail"),
zip(_names, _args, _kwargs, _xfail))
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)
|
46c5a58629db2986d53f15d2e6207cefb29deec677f8d7f290d71ec8ff855395 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from ... import units as u
from ..distances import Distance
from ..builtin_frames import (ICRS, FK5, FK4, FK4NoETerms, Galactic,
Supergalactic, Galactocentric, HCRS, GCRS, LSR)
from .. import SkyCoord
from ...tests.helper import (quantity_allclose as allclose,
assert_quantity_allclose as assert_allclose)
from .. import EarthLocation, CartesianRepresentation
from ...time import Time
# used below in the next parametrized test
m31_sys = [ICRS, FK5, FK4, Galactic]
m31_coo = [(10.6847929, 41.2690650), (10.6847929, 41.2690650), (10.0004738, 40.9952444), (121.1744050, -21.5729360)]
m31_dist = Distance(770, u.kpc)
convert_precision = 1 * u.arcsec
roundtrip_precision = 1e-4 * u.degree
dist_precision = 1e-9 * u.kpc
m31_params = []
for i in range(len(m31_sys)):
for j in range(len(m31_sys)):
if i < j:
m31_params.append((m31_sys[i], m31_sys[j], m31_coo[i], m31_coo[j]))
@pytest.mark.parametrize(('fromsys', 'tosys', 'fromcoo', 'tocoo'), m31_params)
def test_m31_coord_transforms(fromsys, tosys, fromcoo, tocoo):
"""
This tests a variety of coordinate conversions for the Chandra point-source
catalog location of M31 from NED.
"""
coo1 = fromsys(ra=fromcoo[0]*u.deg, dec=fromcoo[1]*u.deg, distance=m31_dist)
coo2 = coo1.transform_to(tosys)
if tosys is FK4:
coo2_prec = coo2.transform_to(FK4(equinox=Time('B1950', scale='utc')))
assert (coo2_prec.spherical.lon - tocoo[0]*u.deg) < convert_precision # <1 arcsec
assert (coo2_prec.spherical.lat - tocoo[1]*u.deg) < convert_precision
else:
assert (coo2.spherical.lon - tocoo[0]*u.deg) < convert_precision # <1 arcsec
assert (coo2.spherical.lat - tocoo[1]*u.deg) < convert_precision
assert coo1.distance.unit == u.kpc
assert coo2.distance.unit == u.kpc
assert m31_dist.unit == u.kpc
assert (coo2.distance - m31_dist) < dist_precision
# check round-tripping
coo1_2 = coo2.transform_to(fromsys)
assert (coo1_2.spherical.lon - fromcoo[0]*u.deg) < roundtrip_precision
assert (coo1_2.spherical.lat - fromcoo[1]*u.deg) < roundtrip_precision
assert (coo1_2.distance - m31_dist) < dist_precision
def test_precession():
"""
Ensures that FK4 and FK5 coordinates precess their equinoxes
"""
j2000 = Time('J2000', scale='utc')
b1950 = Time('B1950', scale='utc')
j1975 = Time('J1975', scale='utc')
b1975 = Time('B1975', scale='utc')
fk4 = FK4(ra=1*u.radian, dec=0.5*u.radian)
assert fk4.equinox.byear == b1950.byear
fk4_2 = fk4.transform_to(FK4(equinox=b1975))
assert fk4_2.equinox.byear == b1975.byear
fk5 = FK5(ra=1*u.radian, dec=0.5*u.radian)
assert fk5.equinox.jyear == j2000.jyear
fk5_2 = fk5.transform_to(FK4(equinox=j1975))
assert fk5_2.equinox.jyear == j1975.jyear
def test_fk5_galactic():
"""
Check that FK5 -> Galactic gives the same as FK5 -> FK4 -> Galactic.
"""
fk5 = FK5(ra=1*u.deg, dec=2*u.deg)
direct = fk5.transform_to(Galactic)
indirect = fk5.transform_to(FK4).transform_to(Galactic)
assert direct.separation(indirect).degree < 1.e-10
direct = fk5.transform_to(Galactic)
indirect = fk5.transform_to(FK4NoETerms).transform_to(Galactic)
assert direct.separation(indirect).degree < 1.e-10
def test_galactocentric():
# when z_sun=0, transformation should be very similar to Galactic
icrs_coord = ICRS(ra=np.linspace(0, 360, 10)*u.deg,
dec=np.linspace(-90, 90, 10)*u.deg,
distance=1.*u.kpc)
g_xyz = icrs_coord.transform_to(Galactic).cartesian.xyz
gc_xyz = icrs_coord.transform_to(Galactocentric(z_sun=0*u.kpc)).cartesian.xyz
diff = np.abs(g_xyz - gc_xyz)
assert allclose(diff[0], 8.3*u.kpc, atol=1E-5*u.kpc)
assert allclose(diff[1:], 0*u.kpc, atol=1E-5*u.kpc)
# generate some test coordinates
g = Galactic(l=[0, 0, 45, 315]*u.deg, b=[-45, 45, 0, 0]*u.deg,
distance=[np.sqrt(2)]*4*u.kpc)
xyz = g.transform_to(Galactocentric(galcen_distance=1.*u.kpc, z_sun=0.*u.pc)).cartesian.xyz
true_xyz = np.array([[0, 0, -1.], [0, 0, 1], [0, 1, 0], [0, -1, 0]]).T*u.kpc
assert allclose(xyz.to(u.kpc), true_xyz.to(u.kpc), atol=1E-5*u.kpc)
# check that ND arrays work
# from Galactocentric to Galactic
x = np.linspace(-10., 10., 100) * u.kpc
y = np.linspace(-10., 10., 100) * u.kpc
z = np.zeros_like(x)
g1 = Galactocentric(x=x, y=y, z=z)
g2 = Galactocentric(x=x.reshape(100, 1, 1), y=y.reshape(100, 1, 1),
z=z.reshape(100, 1, 1))
g1t = g1.transform_to(Galactic)
g2t = g2.transform_to(Galactic)
assert_allclose(g1t.cartesian.xyz, g2t.cartesian.xyz[:, :, 0, 0])
# from Galactic to Galactocentric
l = np.linspace(15, 30., 100) * u.deg
b = np.linspace(-10., 10., 100) * u.deg
d = np.ones_like(l.value) * u.kpc
g1 = Galactic(l=l, b=b, distance=d)
g2 = Galactic(l=l.reshape(100, 1, 1), b=b.reshape(100, 1, 1),
distance=d.reshape(100, 1, 1))
g1t = g1.transform_to(Galactocentric)
g2t = g2.transform_to(Galactocentric)
np.testing.assert_almost_equal(g1t.cartesian.xyz.value,
g2t.cartesian.xyz.value[:, :, 0, 0])
def test_supergalactic():
"""
Check Galactic<->Supergalactic and Galactic<->ICRS conversion.
"""
# Check supergalactic North pole.
npole = Galactic(l=47.37*u.degree, b=+6.32*u.degree)
assert allclose(npole.transform_to(Supergalactic).sgb.deg, +90, atol=1e-9)
# Check the origin of supergalactic longitude.
lon0 = Supergalactic(sgl=0*u.degree, sgb=0*u.degree)
lon0_gal = lon0.transform_to(Galactic)
assert allclose(lon0_gal.l.deg, 137.37, atol=1e-9)
assert allclose(lon0_gal.b.deg, 0, atol=1e-9)
# Test Galactic<->ICRS with some positions that appear in Foley et al. 2008
# (http://adsabs.harvard.edu/abs/2008A%26A...484..143F)
# GRB 021219
supergalactic = Supergalactic(sgl=29.91*u.degree, sgb=+73.72*u.degree)
icrs = SkyCoord('18h50m27s +31d57m17s')
assert supergalactic.separation(icrs) < 0.005 * u.degree
# GRB 030320
supergalactic = Supergalactic(sgl=-174.44*u.degree, sgb=+46.17*u.degree)
icrs = SkyCoord('17h51m36s -25d18m52s')
assert supergalactic.separation(icrs) < 0.005 * u.degree
class TestHCRS():
"""
Check HCRS<->ICRS coordinate conversions.
Uses ICRS Solar positions predicted by get_body_barycentric; with `t1` and
`tarr` as defined below, the ICRS Solar positions were predicted using, e.g.
coord.ICRS(coord.get_body_barycentric(tarr, 'sun')).
"""
def setup(self):
self.t1 = Time("2013-02-02T23:00")
self.t2 = Time("2013-08-02T23:00")
self.tarr = Time(["2013-02-02T23:00", "2013-08-02T23:00"])
self.sun_icrs_scalar = ICRS(ra=244.52984668*u.deg,
dec=-22.36943723*u.deg,
distance=406615.66347377*u.km)
# array of positions corresponds to times in `tarr`
self.sun_icrs_arr = ICRS(ra=[244.52989062, 271.40976248]*u.deg,
dec=[-22.36943605, -25.07431079]*u.deg,
distance=[406615.66347377, 375484.13558956]*u.km)
# corresponding HCRS positions
self.sun_hcrs_t1 = HCRS(CartesianRepresentation([0.0, 0.0, 0.0] * u.km),
obstime=self.t1)
twod_rep = CartesianRepresentation([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]] * u.km)
self.sun_hcrs_tarr = HCRS(twod_rep, obstime=self.tarr)
self.tolerance = 5*u.km
def test_from_hcrs(self):
# test scalar transform
transformed = self.sun_hcrs_t1.transform_to(ICRS())
separation = transformed.separation_3d(self.sun_icrs_scalar)
assert_allclose(separation, 0*u.km, atol=self.tolerance)
# test non-scalar positions and times
transformed = self.sun_hcrs_tarr.transform_to(ICRS())
separation = transformed.separation_3d(self.sun_icrs_arr)
assert_allclose(separation, 0*u.km, atol=self.tolerance)
def test_from_icrs(self):
# scalar positions
transformed = self.sun_icrs_scalar.transform_to(HCRS(obstime=self.t1))
separation = transformed.separation_3d(self.sun_hcrs_t1)
assert_allclose(separation, 0*u.km, atol=self.tolerance)
# nonscalar positions
transformed = self.sun_icrs_arr.transform_to(HCRS(obstime=self.tarr))
separation = transformed.separation_3d(self.sun_hcrs_tarr)
assert_allclose(separation, 0*u.km, atol=self.tolerance)
class TestHelioBaryCentric():
"""
Check GCRS<->Heliocentric and Barycentric coordinate conversions.
Uses the WHT observing site (information grabbed from data/sites.json).
"""
def setup(self):
wht = EarthLocation(342.12*u.deg, 28.758333333333333*u.deg, 2327*u.m)
self.obstime = Time("2013-02-02T23:00")
self.wht_itrs = wht.get_itrs(obstime=self.obstime)
def test_heliocentric(self):
gcrs = self.wht_itrs.transform_to(GCRS(obstime=self.obstime))
helio = gcrs.transform_to(HCRS(obstime=self.obstime))
# Check it doesn't change from previous times.
previous = [-1.02597256e+11, 9.71725820e+10, 4.21268419e+10] * u.m
assert_allclose(helio.cartesian.xyz, previous)
# And that it agrees with SLALIB to within 14km
helio_slalib = [-0.685820296, 0.6495585893, 0.2816005464] * u.au
assert np.sqrt(((helio.cartesian.xyz -
helio_slalib)**2).sum()) < 14. * u.km
def test_barycentric(self):
gcrs = self.wht_itrs.transform_to(GCRS(obstime=self.obstime))
bary = gcrs.transform_to(ICRS())
previous = [-1.02758958e+11, 9.68331109e+10, 4.19720938e+10] * u.m
assert_allclose(bary.cartesian.xyz, previous)
# And that it agrees with SLALIB answer to within 14km
bary_slalib = [-0.6869012079, 0.6472893646, 0.2805661191] * u.au
assert np.sqrt(((bary.cartesian.xyz -
bary_slalib)**2).sum()) < 14. * u.km
def test_lsr_sanity():
# random numbers, but zero velocity in ICRS frame
icrs = ICRS(ra=15.1241*u.deg, dec=17.5143*u.deg, distance=150.12*u.pc,
pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr,
radial_velocity=0*u.km/u.s)
lsr = icrs.transform_to(LSR)
lsr_diff = lsr.data.differentials['s']
cart_lsr_vel = lsr_diff.represent_as(CartesianRepresentation, base=lsr.data)
lsr_vel = ICRS(cart_lsr_vel)
gal_lsr = lsr_vel.transform_to(Galactic).cartesian.xyz
assert allclose(gal_lsr.to(u.km/u.s, u.dimensionless_angles()),
lsr.v_bary.d_xyz)
# moving with LSR velocity
lsr = LSR(ra=15.1241*u.deg, dec=17.5143*u.deg, distance=150.12*u.pc,
pm_ra_cosdec=0*u.mas/u.yr, pm_dec=0*u.mas/u.yr,
radial_velocity=0*u.km/u.s)
icrs = lsr.transform_to(ICRS)
icrs_diff = icrs.data.differentials['s']
cart_vel = icrs_diff.represent_as(CartesianRepresentation, base=icrs.data)
vel = ICRS(cart_vel)
gal_icrs = vel.transform_to(Galactic).cartesian.xyz
assert allclose(gal_icrs.to(u.km/u.s, u.dimensionless_angles()),
-lsr.v_bary.d_xyz)
|
45defb57682f22550846557cf012b2b2f84e52dd16c8d3a95ce43b95dbf17082 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test initalization and other aspects of Angle and subclasses"""
import pytest
import numpy as np
from numpy.testing.utils import assert_allclose, assert_array_equal
from ..angles import Longitude, Latitude, Angle
from ... import units as u
from ..errors import IllegalSecondError, IllegalMinuteError, IllegalHourError
def test_create_angles():
"""
Tests creating and accessing Angle objects
"""
''' The "angle" is a fundamental object. The internal
representation is stored in radians, but this is transparent to the user.
Units *must* be specified rather than a default value be assumed. This is
as much for self-documenting code as anything else.
Angle objects simply represent a single angular coordinate. More specific
angular coordinates (e.g. Longitude, Latitude) are subclasses of Angle.'''
a1 = Angle(54.12412, unit=u.degree)
a2 = Angle("54.12412", unit=u.degree)
a3 = Angle("54:07:26.832", unit=u.degree)
a4 = Angle("54.12412 deg")
a5 = Angle("54.12412 degrees")
a6 = Angle("54.12412°") # because we like Unicode
a7 = Angle((54, 7, 26.832), unit=u.degree)
a8 = Angle("54°07'26.832\"")
# (deg,min,sec) *tuples* are acceptable, but lists/arrays are *not*
# because of the need to eventually support arrays of coordinates
a9 = Angle([54, 7, 26.832], unit=u.degree)
assert_allclose(a9.value, [54, 7, 26.832])
assert a9.unit is u.degree
a10 = Angle(3.60827466667, unit=u.hour)
a11 = Angle("3:36:29.7888000120", unit=u.hour)
a12 = Angle((3, 36, 29.7888000120), unit=u.hour) # *must* be a tuple
# Regression test for #5001
a13 = Angle((3, 36, 29.7888000120), unit='hour')
Angle(0.944644098745, unit=u.radian)
with pytest.raises(u.UnitsError):
Angle(54.12412)
# raises an exception because this is ambiguous
with pytest.raises(u.UnitsError):
Angle(54.12412, unit=u.m)
with pytest.raises(ValueError):
Angle(12.34, unit="not a unit")
a14 = Angle("03h36m29.7888000120") # no trailing 's', but unambiguous
a15 = Angle("5h4m3s") # single digits, no decimal
assert a15.unit == u.hourangle
a16 = Angle("1 d")
a17 = Angle("1 degree")
assert a16.degree == 1
assert a17.degree == 1
a18 = Angle("54 07.4472", unit=u.degree)
a19 = Angle("54:07.4472", unit=u.degree)
a20 = Angle("54d07.4472m", unit=u.degree)
a21 = Angle("3h36m", unit=u.hour)
a22 = Angle("3.6h", unit=u.hour)
a23 = Angle("- 3h", unit=u.hour)
a24 = Angle("+ 3h", unit=u.hour)
# ensure the above angles that should match do
assert a1 == a2 == a3 == a4 == a5 == a6 == a7 == a8 == a18 == a19 == a20
assert_allclose(a1.radian, a2.radian)
assert_allclose(a2.degree, a3.degree)
assert_allclose(a3.radian, a4.radian)
assert_allclose(a4.radian, a5.radian)
assert_allclose(a5.radian, a6.radian)
assert_allclose(a6.radian, a7.radian)
assert_allclose(a10.degree, a11.degree)
assert a11 == a12 == a13 == a14
assert a21 == a22
assert a23 == -a24
# check for illegal ranges / values
with pytest.raises(IllegalSecondError):
a = Angle("12 32 99", unit=u.degree)
with pytest.raises(IllegalMinuteError):
a = Angle("12 99 23", unit=u.degree)
with pytest.raises(IllegalSecondError):
a = Angle("12 32 99", unit=u.hour)
with pytest.raises(IllegalMinuteError):
a = Angle("12 99 23", unit=u.hour)
with pytest.raises(IllegalHourError):
a = Angle("99 25 51.0", unit=u.hour)
with pytest.raises(ValueError):
a = Angle("12 25 51.0xxx", unit=u.hour)
with pytest.raises(ValueError):
a = Angle("12h34321m32.2s")
assert a1 is not None
def test_angle_from_view():
q = np.arange(3.) * u.deg
a = q.view(Angle)
assert type(a) is Angle
assert a.unit is q.unit
assert np.all(a == q)
q2 = np.arange(4) * u.m
with pytest.raises(u.UnitTypeError):
q2.view(Angle)
def test_angle_ops():
"""
Tests operations on Angle objects
"""
# Angles can be added and subtracted. Multiplication and division by a
# scalar is also permitted. A negative operator is also valid. All of
# these operate in a single dimension. Attempting to multiply or divide two
# Angle objects will return a quantity. An exception will be raised if it
# is attempted to store output with a non-angular unit in an Angle [#2718].
a1 = Angle(3.60827466667, unit=u.hour)
a2 = Angle("54:07:26.832", unit=u.degree)
a1 + a2 # creates new Angle object
a1 - a2
-a1
assert_allclose((a1 * 2).hour, 2 * 3.6082746666700003)
assert abs((a1 / 3.123456).hour - 3.60827466667 / 3.123456) < 1e-10
# commutativity
assert (2 * a1).hour == (a1 * 2).hour
a3 = Angle(a1) # makes a *copy* of the object, but identical content as a1
assert_allclose(a1.radian, a3.radian)
assert a1 is not a3
a4 = abs(-a1)
assert a4.radian == a1.radian
a5 = Angle(5.0, unit=u.hour)
assert a5 > a1
assert a5 >= a1
assert a1 < a5
assert a1 <= a5
# check operations with non-angular result give Quantity.
a6 = Angle(45., u.degree)
a7 = a6 * a5
assert type(a7) is u.Quantity
# but those with angular result yield Angle.
# (a9 is regression test for #5327)
a8 = a1 + 1.*u.deg
assert type(a8) is Angle
a9 = 1.*u.deg + a1
assert type(a9) is Angle
with pytest.raises(TypeError):
a6 *= a5
with pytest.raises(TypeError):
a6 *= u.m
with pytest.raises(TypeError):
np.sin(a6, out=a6)
def test_angle_convert():
"""
Test unit conversion of Angle objects
"""
angle = Angle("54.12412", unit=u.degree)
assert_allclose(angle.hour, 3.60827466667)
assert_allclose(angle.radian, 0.944644098745)
assert_allclose(angle.degree, 54.12412)
assert len(angle.hms) == 3
assert isinstance(angle.hms, tuple)
assert angle.hms[0] == 3
assert angle.hms[1] == 36
assert_allclose(angle.hms[2], 29.78879999999947)
# also check that the namedtuple attribute-style access works:
assert angle.hms.h == 3
assert angle.hms.m == 36
assert_allclose(angle.hms.s, 29.78879999999947)
assert len(angle.dms) == 3
assert isinstance(angle.dms, tuple)
assert angle.dms[0] == 54
assert angle.dms[1] == 7
assert_allclose(angle.dms[2], 26.831999999992036)
# also check that the namedtuple attribute-style access works:
assert angle.dms.d == 54
assert angle.dms.m == 7
assert_allclose(angle.dms.s, 26.831999999992036)
assert isinstance(angle.dms[0], float)
assert isinstance(angle.hms[0], float)
# now make sure dms and signed_dms work right for negative angles
negangle = Angle("-54.12412", unit=u.degree)
assert negangle.dms.d == -54
assert negangle.dms.m == -7
assert_allclose(negangle.dms.s, -26.831999999992036)
assert negangle.signed_dms.sign == -1
assert negangle.signed_dms.d == 54
assert negangle.signed_dms.m == 7
assert_allclose(negangle.signed_dms.s, 26.831999999992036)
def test_angle_formatting():
"""
Tests string formatting for Angle objects
"""
'''
The string method of Angle has this signature:
def string(self, unit=DEGREE, decimal=False, sep=" ", precision=5,
pad=False):
The "decimal" parameter defaults to False since if you need to print the
Angle as a decimal, there's no need to use the "format" method (see
above).
'''
angle = Angle("54.12412", unit=u.degree)
# __str__ is the default `format`
assert str(angle) == angle.to_string()
res = 'Angle as HMS: 3h36m29.7888s'
assert "Angle as HMS: {0}".format(angle.to_string(unit=u.hour)) == res
res = 'Angle as HMS: 3:36:29.7888'
assert "Angle as HMS: {0}".format(angle.to_string(unit=u.hour, sep=":")) == res
res = 'Angle as HMS: 3:36:29.79'
assert "Angle as HMS: {0}".format(angle.to_string(unit=u.hour, sep=":",
precision=2)) == res
# Note that you can provide one, two, or three separators passed as a
# tuple or list
res = 'Angle as HMS: 3h36m29.7888s'
assert "Angle as HMS: {0}".format(angle.to_string(unit=u.hour,
sep=("h", "m", "s"),
precision=4)) == res
res = 'Angle as HMS: 3-36|29.7888'
assert "Angle as HMS: {0}".format(angle.to_string(unit=u.hour, sep=["-", "|"],
precision=4)) == res
res = 'Angle as HMS: 3-36-29.7888'
assert "Angle as HMS: {0}".format(angle.to_string(unit=u.hour, sep="-",
precision=4)) == res
res = 'Angle as HMS: 03h36m29.7888s'
assert "Angle as HMS: {0}".format(angle.to_string(unit=u.hour, precision=4,
pad=True)) == res
# Same as above, in degrees
angle = Angle("3 36 29.78880", unit=u.degree)
res = 'Angle as DMS: 3d36m29.7888s'
assert "Angle as DMS: {0}".format(angle.to_string(unit=u.degree)) == res
res = 'Angle as DMS: 3:36:29.7888'
assert "Angle as DMS: {0}".format(angle.to_string(unit=u.degree, sep=":")) == res
res = 'Angle as DMS: 3:36:29.79'
assert "Angle as DMS: {0}".format(angle.to_string(unit=u.degree, sep=":",
precision=2)) == res
# Note that you can provide one, two, or three separators passed as a
# tuple or list
res = 'Angle as DMS: 3d36m29.7888s'
assert "Angle as DMS: {0}".format(angle.to_string(unit=u.degree,
sep=("d", "m", "s"),
precision=4)) == res
res = 'Angle as DMS: 3-36|29.7888'
assert "Angle as DMS: {0}".format(angle.to_string(unit=u.degree, sep=["-", "|"],
precision=4)) == res
res = 'Angle as DMS: 3-36-29.7888'
assert "Angle as DMS: {0}".format(angle.to_string(unit=u.degree, sep="-",
precision=4)) == res
res = 'Angle as DMS: 03d36m29.7888s'
assert "Angle as DMS: {0}".format(angle.to_string(unit=u.degree, precision=4,
pad=True)) == res
res = 'Angle as rad: 0.0629763rad'
assert "Angle as rad: {0}".format(angle.to_string(unit=u.radian)) == res
res = 'Angle as rad decimal: 0.0629763'
assert "Angle as rad decimal: {0}".format(angle.to_string(unit=u.radian, decimal=True)) == res
# check negative angles
angle = Angle(-1.23456789, unit=u.degree)
angle2 = Angle(-1.23456789, unit=u.hour)
assert angle.to_string() == '-1d14m04.4444s'
assert angle.to_string(pad=True) == '-01d14m04.4444s'
assert angle.to_string(unit=u.hour) == '-0h04m56.2963s'
assert angle2.to_string(unit=u.hour, pad=True) == '-01h14m04.4444s'
assert angle.to_string(unit=u.radian, decimal=True) == '-0.0215473'
def test_to_string_vector():
# Regression test for the fact that vectorize doesn't work with Numpy 1.6
assert Angle([1./7., 1./7.], unit='deg').to_string()[0] == "0d08m34.2857s"
assert Angle([1./7.], unit='deg').to_string()[0] == "0d08m34.2857s"
assert Angle(1./7., unit='deg').to_string() == "0d08m34.2857s"
def test_angle_format_roundtripping():
"""
Ensures that the string representation of an angle can be used to create a
new valid Angle.
"""
a1 = Angle(0, unit=u.radian)
a2 = Angle(10, unit=u.degree)
a3 = Angle(0.543, unit=u.degree)
a4 = Angle('1d2m3.4s')
assert Angle(str(a1)).degree == a1.degree
assert Angle(str(a2)).degree == a2.degree
assert Angle(str(a3)).degree == a3.degree
assert Angle(str(a4)).degree == a4.degree
# also check Longitude/Latitude
ra = Longitude('1h2m3.4s')
dec = Latitude('1d2m3.4s')
assert_allclose(Angle(str(ra)).degree, ra.degree)
assert_allclose(Angle(str(dec)).degree, dec.degree)
def test_radec():
"""
Tests creation/operations of Longitude and Latitude objects
"""
'''
Longitude and Latitude are objects that are subclassed from Angle. As with Angle, Longitude
and Latitude can parse any unambiguous format (tuples, formatted strings, etc.).
The intention is not to create an Angle subclass for every possible
coordinate object (e.g. galactic l, galactic b). However, equatorial Longitude/Latitude
are so prevalent in astronomy that it's worth creating ones for these
units. They will be noted as "special" in the docs and use of the just the
Angle class is to be used for other coordinate systems.
'''
with pytest.raises(u.UnitsError):
ra = Longitude("4:08:15.162342") # error - hours or degrees?
with pytest.raises(u.UnitsError):
ra = Longitude("-4:08:15.162342")
# the "smart" initializer allows >24 to automatically do degrees, but the
# Angle-based one does not
# TODO: adjust in 0.3 for whatever behavior is decided on
# ra = Longitude("26:34:15.345634") # unambiguous b/c hours don't go past 24
# assert_allclose(ra.degree, 26.570929342)
with pytest.raises(u.UnitsError):
ra = Longitude("26:34:15.345634")
# ra = Longitude(68)
with pytest.raises(u.UnitsError):
ra = Longitude(68)
with pytest.raises(u.UnitsError):
ra = Longitude(12)
with pytest.raises(ValueError):
ra = Longitude("garbage containing a d and no units")
ra = Longitude("12h43m23s")
assert_allclose(ra.hour, 12.7230555556)
ra = Longitude((56, 14, 52.52), unit=u.degree) # can accept tuples
# TODO: again, fix based on >24 behavior
# ra = Longitude((56,14,52.52))
with pytest.raises(u.UnitsError):
ra = Longitude((56, 14, 52.52))
with pytest.raises(u.UnitsError):
ra = Longitude((12, 14, 52)) # ambiguous w/o units
ra = Longitude((12, 14, 52), unit=u.hour)
ra = Longitude([56, 64, 52.2], unit=u.degree) # ...but not arrays (yet)
# Units can be specified
ra = Longitude("4:08:15.162342", unit=u.hour)
# TODO: this was the "smart" initializer behavior - adjust in 0.3 appropriately
# Where Longitude values are commonly found in hours or degrees, declination is
# nearly always specified in degrees, so this is the default.
# dec = Latitude("-41:08:15.162342")
with pytest.raises(u.UnitsError):
dec = Latitude("-41:08:15.162342")
dec = Latitude("-41:08:15.162342", unit=u.degree) # same as above
def test_negative_zero_dms():
# Test for DMS parser
a = Angle('-00:00:10', u.deg)
assert_allclose(a.degree, -10. / 3600.)
# Unicode minus
a = Angle('−00:00:10', u.deg)
assert_allclose(a.degree, -10. / 3600.)
def test_negative_zero_dm():
# Test for DM parser
a = Angle('-00:10', u.deg)
assert_allclose(a.degree, -10. / 60.)
def test_negative_zero_hms():
# Test for HMS parser
a = Angle('-00:00:10', u.hour)
assert_allclose(a.hour, -10. / 3600.)
def test_negative_zero_hm():
# Test for HM parser
a = Angle('-00:10', u.hour)
assert_allclose(a.hour, -10. / 60.)
def test_negative_sixty_hm():
# Test for HM parser
a = Angle('-00:60', u.hour)
assert_allclose(a.hour, -1.)
def test_plus_sixty_hm():
# Test for HM parser
a = Angle('00:60', u.hour)
assert_allclose(a.hour, 1.)
def test_negative_fifty_nine_sixty_dms():
# Test for DMS parser
a = Angle('-00:59:60', u.deg)
assert_allclose(a.degree, -1.)
def test_plus_fifty_nine_sixty_dms():
# Test for DMS parser
a = Angle('+00:59:60', u.deg)
assert_allclose(a.degree, 1.)
def test_negative_sixty_dms():
# Test for DMS parser
a = Angle('-00:00:60', u.deg)
assert_allclose(a.degree, -1. / 60.)
def test_plus_sixty_dms():
# Test for DMS parser
a = Angle('+00:00:60', u.deg)
assert_allclose(a.degree, 1. / 60.)
def test_angle_to_is_angle():
a = Angle('00:00:60', u.deg)
assert isinstance(a, Angle)
assert isinstance(a.to(u.rad), Angle)
def test_angle_to_quantity():
a = Angle('00:00:60', u.deg)
q = u.Quantity(a)
assert isinstance(q, u.Quantity)
assert q.unit is u.deg
def test_quantity_to_angle():
a = Angle(1.0*u.deg)
assert isinstance(a, Angle)
with pytest.raises(u.UnitsError):
Angle(1.0*u.meter)
a = Angle(1.0*u.hour)
assert isinstance(a, Angle)
assert a.unit is u.hourangle
with pytest.raises(u.UnitsError):
Angle(1.0*u.min)
def test_angle_string():
a = Angle('00:00:60', u.deg)
assert str(a) == '0d01m00s'
a = Angle('-00:00:10', u.hour)
assert str(a) == '-0h00m10s'
a = Angle(3.2, u.radian)
assert str(a) == '3.2rad'
a = Angle(4.2, u.microarcsecond)
assert str(a) == '4.2uarcsec'
a = Angle('1.0uarcsec')
assert a.value == 1.0
assert a.unit == u.microarcsecond
a = Angle("3d")
assert_allclose(a.value, 3.0)
assert a.unit == u.degree
a = Angle('10"')
assert_allclose(a.value, 10.0)
assert a.unit == u.arcsecond
a = Angle("10'")
assert_allclose(a.value, 10.0)
assert a.unit == u.arcminute
def test_angle_repr():
assert 'Angle' in repr(Angle(0, u.deg))
assert 'Longitude' in repr(Longitude(0, u.deg))
assert 'Latitude' in repr(Latitude(0, u.deg))
a = Angle(0, u.deg)
repr(a)
def test_large_angle_representation():
"""Test that angles above 360 degrees can be output as strings,
in repr, str, and to_string. (regression test for #1413)"""
a = Angle(350, u.deg) + Angle(350, u.deg)
a.to_string()
a.to_string(u.hourangle)
repr(a)
repr(a.to(u.hourangle))
str(a)
str(a.to(u.hourangle))
def test_wrap_at_inplace():
a = Angle([-20, 150, 350, 360] * u.deg)
out = a.wrap_at('180d', inplace=True)
assert out is None
assert np.all(a.degree == np.array([-20., 150., -10., 0.]))
def test_latitude():
with pytest.raises(ValueError):
lat = Latitude(['91d', '89d'])
with pytest.raises(ValueError):
lat = Latitude('-91d')
lat = Latitude(['90d', '89d'])
# check that one can get items
assert lat[0] == 90 * u.deg
assert lat[1] == 89 * u.deg
# and that comparison with angles works
assert np.all(lat == Angle(['90d', '89d']))
# check setitem works
lat[1] = 45. * u.deg
assert np.all(lat == Angle(['90d', '45d']))
# but not with values out of range
with pytest.raises(ValueError):
lat[0] = 90.001 * u.deg
with pytest.raises(ValueError):
lat[0] = -90.001 * u.deg
# these should also not destroy input (#1851)
assert np.all(lat == Angle(['90d', '45d']))
# conserve type on unit change (closes #1423)
angle = lat.to('radian')
assert type(angle) is Latitude
# but not on calculations
angle = lat - 190 * u.deg
assert type(angle) is Angle
assert angle[0] == -100 * u.deg
lat = Latitude('80d')
angle = lat / 2.
assert type(angle) is Angle
assert angle == 40 * u.deg
angle = lat * 2.
assert type(angle) is Angle
assert angle == 160 * u.deg
angle = -lat
assert type(angle) is Angle
assert angle == -80 * u.deg
# Test errors when trying to interoperate with longitudes.
with pytest.raises(TypeError) as excinfo:
lon = Longitude(10, 'deg')
lat = Latitude(lon)
assert "A Latitude angle cannot be created from a Longitude angle" in str(excinfo)
with pytest.raises(TypeError) as excinfo:
lon = Longitude(10, 'deg')
lat = Latitude([20], 'deg')
lat[0] = lon
assert "A Longitude angle cannot be assigned to a Latitude angle" in str(excinfo)
# Check we can work around the Lat vs Long checks by casting explicitly to Angle.
lon = Longitude(10, 'deg')
lat = Latitude(Angle(lon))
assert lat.value == 10.0
# Check setitem.
lon = Longitude(10, 'deg')
lat = Latitude([20], 'deg')
lat[0] = Angle(lon)
assert lat.value[0] == 10.0
def test_longitude():
# Default wrapping at 360d with an array input
lon = Longitude(['370d', '88d'])
assert np.all(lon == Longitude(['10d', '88d']))
assert np.all(lon == Angle(['10d', '88d']))
# conserve type on unit change and keep wrap_angle (closes #1423)
angle = lon.to('hourangle')
assert type(angle) is Longitude
assert angle.wrap_angle == lon.wrap_angle
angle = lon[0]
assert type(angle) is Longitude
assert angle.wrap_angle == lon.wrap_angle
angle = lon[1:]
assert type(angle) is Longitude
assert angle.wrap_angle == lon.wrap_angle
# but not on calculations
angle = lon / 2.
assert np.all(angle == Angle(['5d', '44d']))
assert type(angle) is Angle
assert not hasattr(angle, 'wrap_angle')
angle = lon * 2. + 400 * u.deg
assert np.all(angle == Angle(['420d', '576d']))
assert type(angle) is Angle
# Test setting a mutable value and having it wrap
lon[1] = -10 * u.deg
assert np.all(lon == Angle(['10d', '350d']))
# Test wrapping and try hitting some edge cases
lon = Longitude(np.array([0, 0.5, 1.0, 1.5, 2.0]) * np.pi, unit=u.radian)
assert np.all(lon.degree == np.array([0., 90, 180, 270, 0]))
lon = Longitude(np.array([0, 0.5, 1.0, 1.5, 2.0]) * np.pi, unit=u.radian, wrap_angle='180d')
assert np.all(lon.degree == np.array([0., 90, -180, -90, 0]))
# Wrap on setting wrap_angle property (also test auto-conversion of wrap_angle to an Angle)
lon = Longitude(np.array([0, 0.5, 1.0, 1.5, 2.0]) * np.pi, unit=u.radian)
lon.wrap_angle = '180d'
assert np.all(lon.degree == np.array([0., 90, -180, -90, 0]))
lon = Longitude('460d')
assert lon == Angle('100d')
lon.wrap_angle = '90d'
assert lon == Angle('-260d')
# check that if we initialize a longitude with another longitude,
# wrap_angle is kept by default
lon2 = Longitude(lon)
assert lon2.wrap_angle == lon.wrap_angle
# but not if we explicitly set it
lon3 = Longitude(lon, wrap_angle='180d')
assert lon3.wrap_angle == 180 * u.deg
# check for problem reported in #2037 about Longitude initializing to -0
lon = Longitude(0, u.deg)
lonstr = lon.to_string()
assert not lonstr.startswith('-')
# also make sure dtype is correctly conserved
assert Longitude(0, u.deg, dtype=float).dtype == np.dtype(float)
assert Longitude(0, u.deg, dtype=int).dtype == np.dtype(int)
# Test errors when trying to interoperate with latitudes.
with pytest.raises(TypeError) as excinfo:
lat = Latitude(10, 'deg')
lon = Longitude(lat)
assert "A Longitude angle cannot be created from a Latitude angle" in str(excinfo)
with pytest.raises(TypeError) as excinfo:
lat = Latitude(10, 'deg')
lon = Longitude([20], 'deg')
lon[0] = lat
assert "A Latitude angle cannot be assigned to a Longitude angle" in str(excinfo)
# Check we can work around the Lat vs Long checks by casting explicitly to Angle.
lat = Latitude(10, 'deg')
lon = Longitude(Angle(lat))
assert lon.value == 10.0
# Check setitem.
lat = Latitude(10, 'deg')
lon = Longitude([20], 'deg')
lon[0] = Angle(lat)
assert lon.value[0] == 10.0
def test_wrap_at():
a = Angle([-20, 150, 350, 360] * u.deg)
assert np.all(a.wrap_at(360 * u.deg).degree == np.array([340., 150., 350., 0.]))
assert np.all(a.wrap_at(Angle(360, unit=u.deg)).degree == np.array([340., 150., 350., 0.]))
assert np.all(a.wrap_at('360d').degree == np.array([340., 150., 350., 0.]))
assert np.all(a.wrap_at('180d').degree == np.array([-20., 150., -10., 0.]))
assert np.all(a.wrap_at(np.pi * u.rad).degree == np.array([-20., 150., -10., 0.]))
# Test wrapping a scalar Angle
a = Angle('190d')
assert a.wrap_at('180d') == Angle('-170d')
a = Angle(np.arange(-1000.0, 1000.0, 0.125), unit=u.deg)
for wrap_angle in (270, 0.2, 0.0, 360.0, 500, -2000.125):
aw = a.wrap_at(wrap_angle * u.deg)
assert np.all(aw.degree >= wrap_angle - 360.0)
assert np.all(aw.degree < wrap_angle)
aw = a.to(u.rad).wrap_at(wrap_angle * u.deg)
assert np.all(aw.degree >= wrap_angle - 360.0)
assert np.all(aw.degree < wrap_angle)
def test_is_within_bounds():
a = Angle([-20, 150, 350] * u.deg)
assert a.is_within_bounds('0d', '360d') is False
assert a.is_within_bounds(None, '360d') is True
assert a.is_within_bounds(-30 * u.deg, None) is True
a = Angle('-20d')
assert a.is_within_bounds('0d', '360d') is False
assert a.is_within_bounds(None, '360d') is True
assert a.is_within_bounds(-30 * u.deg, None) is True
def test_angle_mismatched_unit():
a = Angle('+6h7m8s', unit=u.degree)
assert_allclose(a.value, 91.78333333333332)
def test_regression_formatting_negative():
# Regression test for a bug that caused:
#
# >>> Angle(-1., unit='deg').to_string()
# '-1d00m-0s'
assert Angle(-0., unit='deg').to_string() == '-0d00m00s'
assert Angle(-1., unit='deg').to_string() == '-1d00m00s'
assert Angle(-0., unit='hour').to_string() == '-0h00m00s'
assert Angle(-1., unit='hour').to_string() == '-1h00m00s'
def test_empty_sep():
a = Angle('05h04m31.93830s')
assert a.to_string(sep='', precision=2, pad=True) == '050431.94'
def test_create_tuple():
"""
Tests creation of an angle with a (d,m,s) or (h,m,s) tuple
"""
a1 = Angle((1, 30, 0), unit=u.degree)
assert a1.value == 1.5
a1 = Angle((1, 30, 0), unit=u.hourangle)
assert a1.value == 1.5
def test_list_of_quantities():
a1 = Angle([1*u.deg, 1*u.hourangle])
assert a1.unit == u.deg
assert_allclose(a1.value, [1, 15])
a2 = Angle([1*u.hourangle, 1*u.deg], u.deg)
assert a2.unit == u.deg
assert_allclose(a2.value, [15, 1])
def test_multiply_divide():
# Issue #2273
a1 = Angle([1, 2, 3], u.deg)
a2 = Angle([4, 5, 6], u.deg)
a3 = a1 * a2
assert_allclose(a3.value, [4, 10, 18])
assert a3.unit == (u.deg * u.deg)
a3 = a1 / a2
assert_allclose(a3.value, [.25, .4, .5])
assert a3.unit == u.dimensionless_unscaled
def test_mixed_string_and_quantity():
a1 = Angle(['1d', 1. * u.deg])
assert_array_equal(a1.value, [1., 1.])
assert a1.unit == u.deg
a2 = Angle(['1d', 1 * u.rad * np.pi, '3d'])
assert_array_equal(a2.value, [1., 180., 3.])
assert a2.unit == u.deg
def test_array_angle_tostring():
aobj = Angle([1, 2], u.deg)
assert aobj.to_string().dtype.kind == 'U'
assert np.all(aobj.to_string() == ['1d00m00s', '2d00m00s'])
def test_wrap_at_without_new():
"""
Regression test for subtle bugs from situations where an Angle is
created via numpy channels that don't do the standard __new__ but instead
depend on array_finalize to set state. Longitude is used because the
bug was in its _wrap_angle not getting initialized correctly
"""
l1 = Longitude([1]*u.deg)
l2 = Longitude([2]*u.deg)
l = np.concatenate([l1, l2])
assert l._wrap_angle is not None
def test__str__():
"""
Check the __str__ method used in printing the Angle
"""
# scalar angle
scangle = Angle('10.2345d')
strscangle = scangle.__str__()
assert strscangle == '10d14m04.2s'
# non-scalar array angles
arrangle = Angle(['10.2345d', '-20d'])
strarrangle = arrangle.__str__()
assert strarrangle == '[10d14m04.2s -20d00m00s]'
# summarizing for large arrays, ... should appear
bigarrangle = Angle(np.ones(10000), u.deg)
assert '...' in bigarrangle.__str__()
def test_repr_latex():
"""
Check the _repr_latex_ method, used primarily by IPython notebooks
"""
# try with both scalar
scangle = Angle(2.1, u.deg)
rlscangle = scangle._repr_latex_()
# and array angles
arrangle = Angle([1, 2.1], u.deg)
rlarrangle = arrangle._repr_latex_()
assert rlscangle == r'$2^\circ06{}^\prime00{}^{\prime\prime}$'
assert rlscangle.split('$')[1] in rlarrangle
# make sure the ... appears for large arrays
bigarrangle = Angle(np.ones(50000)/50000., u.deg)
assert '...' in bigarrangle._repr_latex_()
def test_angle_with_cds_units_enabled():
"""Regression test for #5350
Especially the example in
https://github.com/astropy/astropy/issues/5350#issuecomment-248770151
"""
from ...units import cds
# the problem is with the parser, so remove it temporarily
from ..angle_utilities import _AngleParser
del _AngleParser._parser
with cds.enable():
Angle('5d')
del _AngleParser._parser
Angle('5d')
|
ba8d9e0e0e93fd807ad91f62064b08b618966f6a5a9bd60fa850360e27fde9a3 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the projected separation stuff
"""
import pytest
import numpy as np
from ...tests.helper import assert_quantity_allclose as assert_allclose
from ... import units as u
from ..builtin_frames import ICRS, FK5, Galactic
from .. import Angle, Distance
# lon1, lat1, lon2, lat2 in degrees
coords = [(1, 0, 0, 0),
(0, 1, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1),
(0, 0, 10, 0),
(0, 0, 90, 0),
(0, 0, 180, 0),
(0, 45, 0, -45),
(0, 60, 0, -30),
(-135, -15, 45, 15),
(100, -89, -80, 89),
(0, 0, 0, 0),
(0, 0, 1. / 60., 1. / 60.)]
correct_seps = [1, 1, 1, 1, 10, 90, 180, 90, 90, 180, 180, 0,
0.023570225877234643]
correctness_margin = 2e-10
def test_angsep():
"""
Tests that the angular separation object also behaves correctly.
"""
from ..angle_utilities import angular_separation
# check it both works with floats in radians, Quantities, or Angles
for conv in (np.deg2rad,
lambda x: u.Quantity(x, "deg"),
lambda x: Angle(x, "deg")):
for (lon1, lat1, lon2, lat2), corrsep in zip(coords, correct_seps):
angsep = angular_separation(conv(lon1), conv(lat1),
conv(lon2), conv(lat2))
assert np.fabs(angsep - conv(corrsep)) < conv(correctness_margin)
def test_fk5_seps():
"""
This tests if `separation` works for FK5 objects.
This is a regression test for github issue #891
"""
a = FK5(1.*u.deg, 1.*u.deg)
b = FK5(2.*u.deg, 2.*u.deg)
a.separation(b)
def test_proj_separations():
"""
Test angular separation functionality
"""
c1 = ICRS(ra=0*u.deg, dec=0*u.deg)
c2 = ICRS(ra=0*u.deg, dec=1*u.deg)
sep = c2.separation(c1)
# returns an Angle object
assert isinstance(sep, Angle)
assert sep.degree == 1
assert_allclose(sep.arcminute, 60.)
# these operations have ambiguous interpretations for points on a sphere
with pytest.raises(TypeError):
c1 + c2
with pytest.raises(TypeError):
c1 - c2
ngp = Galactic(l=0*u.degree, b=90*u.degree)
ncp = ICRS(ra=0*u.degree, dec=90*u.degree)
# if there is a defined conversion between the relevant coordinate systems,
# it will be automatically performed to get the right angular separation
assert_allclose(ncp.separation(ngp.transform_to(ICRS)).degree,
ncp.separation(ngp).degree)
# distance from the north galactic pole to celestial pole
assert_allclose(ncp.separation(ngp.transform_to(ICRS)).degree,
62.87174758503201)
def test_3d_separations():
"""
Test 3D separation functionality
"""
c1 = ICRS(ra=1*u.deg, dec=1*u.deg, distance=9*u.kpc)
c2 = ICRS(ra=1*u.deg, dec=1*u.deg, distance=10*u.kpc)
sep3d = c2.separation_3d(c1)
assert isinstance(sep3d, Distance)
assert_allclose(sep3d - 1*u.kpc, 0*u.kpc, atol=1e-12*u.kpc)
|
0f6f0e51386072a198974c1631eb1fac82382f2e26be35a4013c2f0b935775ec | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This is the APE5 coordinates API document re-written to work as a series of test
functions.
Note that new tests for coordinates functionality should generally *not* be
added to this file - instead, add them to other appropriate test modules in
this package, like ``test_sky_coord.py``, ``test_frames.py``, or
``test_representation.py``. This file is instead meant mainly to keep track of
deviations from the original APE5 plan.
"""
import pytest
import numpy as np
from numpy.random import randn
from numpy import testing as npt
from ...tests.helper import (raises, quantity_allclose as allclose,
assert_quantity_allclose as assert_allclose)
from ... import units as u
from ... import time
from ... import coordinates as coords
try:
import scipy # pylint: disable=W0611
except ImportError:
HAS_SCIPY = False
else:
HAS_SCIPY = True
def test_representations_api():
from ..representation import SphericalRepresentation, \
UnitSphericalRepresentation, PhysicsSphericalRepresentation, \
CartesianRepresentation
from ... coordinates import Angle, Longitude, Latitude, Distance
# <-----------------Classes for representation of coordinate data-------------->
# These classes inherit from a common base class and internally contain Quantity
# objects, which are arrays (although they may act as scalars, like numpy's
# length-0 "arrays")
# They can be initialized with a variety of ways that make intuitive sense.
# Distance is optional.
UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg)
UnitSphericalRepresentation(lon=8*u.hourangle, lat=5*u.deg)
SphericalRepresentation(lon=8*u.hourangle, lat=5*u.deg, distance=10*u.kpc)
# In the initial implementation, the lat/lon/distance arguments to the
# initializer must be in order. A *possible* future change will be to allow
# smarter guessing of the order. E.g. `Latitude` and `Longitude` objects can be
# given in any order.
UnitSphericalRepresentation(Longitude(8, u.hour), Latitude(5, u.deg))
SphericalRepresentation(Longitude(8, u.hour), Latitude(5, u.deg), Distance(10, u.kpc))
# Arrays of any of the inputs are fine
UnitSphericalRepresentation(lon=[8, 9]*u.hourangle, lat=[5, 6]*u.deg)
# Default is to copy arrays, but optionally, it can be a reference
UnitSphericalRepresentation(lon=[8, 9]*u.hourangle, lat=[5, 6]*u.deg, copy=False)
# strings are parsed by `Latitude` and `Longitude` constructors, so no need to
# implement parsing in the Representation classes
UnitSphericalRepresentation(lon=Angle('2h6m3.3s'), lat=Angle('0.1rad'))
# Or, you can give `Quantity`s with keywords, and they will be internally
# converted to Angle/Distance
c1 = SphericalRepresentation(lon=8*u.hourangle, lat=5*u.deg, distance=10*u.kpc)
# Can also give another representation object with the `reprobj` keyword.
c2 = SphericalRepresentation.from_representation(c1)
# distance, lat, and lon typically will just match in shape
SphericalRepresentation(lon=[8, 9]*u.hourangle, lat=[5, 6]*u.deg, distance=[10, 11]*u.kpc)
# if the inputs are not the same, if possible they will be broadcast following
# numpy's standard broadcasting rules.
c2 = SphericalRepresentation(lon=[8, 9]*u.hourangle, lat=[5, 6]*u.deg, distance=10*u.kpc)
assert len(c2.distance) == 2
# when they can't be broadcast, it is a ValueError (same as Numpy)
with raises(ValueError):
c2 = UnitSphericalRepresentation(lon=[8, 9, 10]*u.hourangle, lat=[5, 6]*u.deg)
# It's also possible to pass in scalar quantity lists with mixed units. These
# are converted to array quantities following the same rule as `Quantity`: all
# elements are converted to match the first element's units.
c2 = UnitSphericalRepresentation(lon=Angle([8*u.hourangle, 135*u.deg]),
lat=Angle([5*u.deg, (6*np.pi/180)*u.rad]))
assert c2.lat.unit == u.deg and c2.lon.unit == u.hourangle
npt.assert_almost_equal(c2.lon[1].value, 9)
# The Quantity initializer itself can also be used to force the unit even if the
# first element doesn't have the right unit
lon = u.Quantity([120*u.deg, 135*u.deg], u.hourangle)
lat = u.Quantity([(5*np.pi/180)*u.rad, 0.4*u.hourangle], u.deg)
c2 = UnitSphericalRepresentation(lon, lat)
# regardless of how input, the `lat` and `lon` come out as angle/distance
assert isinstance(c1.lat, Angle)
assert isinstance(c1.lat, Latitude) # `Latitude` is an `Angle` subclass
assert isinstance(c1.distance, Distance)
# but they are read-only, as representations are immutable once created
with raises(AttributeError):
c1.lat = Latitude(5, u.deg)
# Note that it is still possible to modify the array in-place, but this is not
# sanctioned by the API, as this would prevent things like caching.
c2.lat[:] = [0] * u.deg # possible, but NOT SUPPORTED
# To address the fact that there are various other conventions for how spherical
# coordinates are defined, other conventions can be included as new classes.
# Later there may be other conventions that we implement - for now just the
# physics convention, as it is one of the most common cases.
c3 = PhysicsSphericalRepresentation(phi=120*u.deg, theta=85*u.deg, r=3*u.kpc)
# first dimension must be length-3 if a lone `Quantity` is passed in.
c1 = CartesianRepresentation(randn(3, 100) * u.kpc)
assert c1.xyz.shape[0] == 3
assert c1.xyz.unit == u.kpc
assert c1.x.shape[0] == 100
assert c1.y.shape[0] == 100
assert c1.z.shape[0] == 100
# can also give each as separate keywords
CartesianRepresentation(x=randn(100)*u.kpc, y=randn(100)*u.kpc, z=randn(100)*u.kpc)
# if the units don't match but are all distances, they will automatically be
# converted to match `x`
xarr, yarr, zarr = randn(3, 100)
c1 = CartesianRepresentation(x=xarr*u.kpc, y=yarr*u.kpc, z=zarr*u.kpc)
c2 = CartesianRepresentation(x=xarr*u.kpc, y=yarr*u.kpc, z=zarr*u.pc)
assert c1.xyz.unit == c2.xyz.unit == u.kpc
assert_allclose((c1.z / 1000) - c2.z, 0*u.kpc, atol=1e-10*u.kpc)
# representations convert into other representations via `represent_as`
srep = SphericalRepresentation(lon=90*u.deg, lat=0*u.deg, distance=1*u.pc)
crep = srep.represent_as(CartesianRepresentation)
assert_allclose(crep.x, 0*u.pc, atol=1e-10*u.pc)
assert_allclose(crep.y, 1*u.pc, atol=1e-10*u.pc)
assert_allclose(crep.z, 0*u.pc, atol=1e-10*u.pc)
# The functions that actually do the conversion are defined via methods on the
# representation classes. This may later be expanded into a full registerable
# transform graph like the coordinate frames, but initially it will be a simpler
# method system
def test_frame_api():
from ..representation import SphericalRepresentation, \
UnitSphericalRepresentation
from ..builtin_frames import ICRS, FK5
# <--------------------Reference Frame/"Low-level" classes--------------------->
# The low-level classes have a dual role: they act as specifiers of coordinate
# frames and they *may* also contain data as one of the representation objects,
# in which case they are the actual coordinate objects themselves.
# They can always accept a representation as a first argument
icrs = ICRS(UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg))
# which is stored as the `data` attribute
assert icrs.data.lat == 5*u.deg
assert icrs.data.lon == 8*u.hourangle
# Frames that require additional information like equinoxs or obstimes get them
# as keyword parameters to the frame constructor. Where sensible, defaults are
# used. E.g., FK5 is almost always J2000 equinox
fk5 = FK5(UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg))
J2000 = time.Time('J2000', scale='utc')
fk5_2000 = FK5(UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg), equinox=J2000)
assert fk5.equinox == fk5_2000.equinox
# the information required to specify the frame is immutable
J2001 = time.Time('J2001', scale='utc')
with raises(AttributeError):
fk5.equinox = J2001
# Similar for the representation data.
with raises(AttributeError):
fk5.data = UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg)
# There is also a class-level attribute that lists the attributes needed to
# identify the frame. These include attributes like `equinox` shown above.
assert all(nm in ('equinox', 'obstime') for nm in fk5.get_frame_attr_names())
# the result of `get_frame_attr_names` is called for particularly in the
# high-level class (discussed below) to allow round-tripping between various
# frames. It is also part of the public API for other similar developer /
# advanced users' use.
# The actual position information is accessed via the representation objects
assert_allclose(icrs.represent_as(SphericalRepresentation).lat, 5*u.deg)
# shorthand for the above
assert_allclose(icrs.spherical.lat, 5*u.deg)
assert icrs.cartesian.z.value > 0
# Many frames have a "default" representation, the one in which they are
# conventionally described, often with a special name for some of the
# coordinates. E.g., most equatorial coordinate systems are spherical with RA and
# Dec. This works simply as a shorthand for the longer form above
assert_allclose(icrs.dec, 5*u.deg)
assert_allclose(fk5.ra, 8*u.hourangle)
assert icrs.representation == SphericalRepresentation
# low-level classes can also be initialized with names valid for that representation
# and frame:
icrs_2 = ICRS(ra=8*u.hour, dec=5*u.deg, distance=1*u.kpc)
assert_allclose(icrs.ra, icrs_2.ra)
# and these are taken as the default if keywords are not given:
# icrs_nokwarg = ICRS(8*u.hour, 5*u.deg, distance=1*u.kpc)
# assert icrs_nokwarg.ra == icrs_2.ra and icrs_nokwarg.dec == icrs_2.dec
# they also are capable of computing on-sky or 3d separations from each other,
# which will be a direct port of the existing methods:
coo1 = ICRS(ra=0*u.hour, dec=0*u.deg)
coo2 = ICRS(ra=0*u.hour, dec=1*u.deg)
# `separation` is the on-sky separation
assert coo1.separation(coo2).degree == 1.0
# while `separation_3d` includes the 3D distance information
coo3 = ICRS(ra=0*u.hour, dec=0*u.deg, distance=1*u.kpc)
coo4 = ICRS(ra=0*u.hour, dec=0*u.deg, distance=2*u.kpc)
assert coo3.separation_3d(coo4).kpc == 1.0
# The next example fails because `coo1` and `coo2` don't have distances
with raises(ValueError):
assert coo1.separation_3d(coo2).kpc == 1.0
# repr/str also shows info, with frame and data
# assert repr(fk5) == ''
def test_transform_api():
from ..representation import UnitSphericalRepresentation
from ..builtin_frames import ICRS, FK5
from ..baseframe import frame_transform_graph, BaseCoordinateFrame
from ..transformations import DynamicMatrixTransform
# <------------------------Transformations------------------------------------->
# Transformation functionality is the key to the whole scheme: they transform
# low-level classes from one frame to another.
# (used below but defined above in the API)
fk5 = FK5(ra=8*u.hour, dec=5*u.deg)
# If no data (or `None`) is given, the class acts as a specifier of a frame, but
# without any stored data.
J2001 = time.Time('J2001', scale='utc')
fk5_J2001_frame = FK5(equinox=J2001)
# if they do not have data, the string instead is the frame specification
assert repr(fk5_J2001_frame) == "<FK5 Frame (equinox=J2001.000)>"
# Note that, although a frame object is immutable and can't have data added, it
# can be used to create a new object that does have data by giving the
# `realize_frame` method a representation:
srep = UnitSphericalRepresentation(lon=8*u.hour, lat=5*u.deg)
fk5_j2001_with_data = fk5_J2001_frame.realize_frame(srep)
assert fk5_j2001_with_data.data is not None
# Now `fk5_j2001_with_data` is in the same frame as `fk5_J2001_frame`, but it
# is an actual low-level coordinate, rather than a frame without data.
# These frames are primarily useful for specifying what a coordinate should be
# transformed *into*, as they are used by the `transform_to` method
# E.g., this snippet precesses the point to the new equinox
newfk5 = fk5.transform_to(fk5_J2001_frame)
assert newfk5.equinox == J2001
# classes can also be given to `transform_to`, which then uses the defaults for
# the frame information:
samefk5 = fk5.transform_to(FK5)
# `fk5` was initialized using default `obstime` and `equinox`, so:
assert_allclose(samefk5.ra, fk5.ra, atol=1e-10*u.deg)
assert_allclose(samefk5.dec, fk5.dec, atol=1e-10*u.deg)
# transforming to a new frame necessarily loses framespec information if that
# information is not applicable to the new frame. This means transforms are not
# always round-trippable:
fk5_2 = FK5(ra=8*u.hour, dec=5*u.deg, equinox=J2001)
ic_trans = fk5_2.transform_to(ICRS)
# `ic_trans` does not have an `equinox`, so now when we transform back to FK5,
# it's a *different* RA and Dec
fk5_trans = ic_trans.transform_to(FK5)
assert not allclose(fk5_2.ra, fk5_trans.ra, rtol=0, atol=1e-10*u.deg)
# But if you explicitly give the right equinox, all is fine
fk5_trans_2 = fk5_2.transform_to(FK5(equinox=J2001))
assert_allclose(fk5_2.ra, fk5_trans_2.ra, rtol=0, atol=1e-10*u.deg)
# Trying to transforming a frame with no data is of course an error:
with raises(ValueError):
FK5(equinox=J2001).transform_to(ICRS)
# To actually define a new transformation, the same scheme as in the
# 0.2/0.3 coordinates framework can be re-used - a graph of transform functions
# connecting various coordinate classes together. The main changes are:
# 1) The transform functions now get the frame object they are transforming the
# current data into.
# 2) Frames with additional information need to have a way to transform between
# objects of the same class, but with different framespecinfo values
# An example transform function:
class SomeNewSystem(BaseCoordinateFrame):
pass
@frame_transform_graph.transform(DynamicMatrixTransform, SomeNewSystem, FK5)
def new_to_fk5(newobj, fk5frame):
ot = newobj.obstime
eq = fk5frame.equinox
# ... build a *cartesian* transform matrix using `eq` that transforms from
# the `newobj` frame as observed at `ot` to FK5 an equinox `eq`
matrix = np.eye(3)
return matrix
# Other options for transform functions include one that simply returns the new
# coordinate object, and one that returns a cartesian matrix but does *not*
# require `newobj` or `fk5frame` - this allows optimization of the transform.
def test_highlevel_api():
J2001 = time.Time('J2001', scale='utc')
# <--------------------------"High-level" class-------------------------------->
# The "high-level" class is intended to wrap the lower-level classes in such a
# way that they can be round-tripped, as well as providing a variety of
# convenience functionality. This document is not intended to show *all* of the
# possible high-level functionality, rather how the high-level classes are
# initialized and interact with the low-level classes
# this creates an object that contains an `ICRS` low-level class, initialized
# identically to the first ICRS example further up.
sc = coords.SkyCoord(coords.SphericalRepresentation(lon=8 * u.hour,
lat=5 * u.deg, distance=1 * u.kpc), frame='icrs')
# Other representations and `system` keywords delegate to the appropriate
# low-level class. The already-existing registry for user-defined coordinates
# will be used by `SkyCoordinate` to figure out what various the `system`
# keyword actually means.
sc = coords.SkyCoord(ra=8 * u.hour, dec=5 * u.deg, frame='icrs')
sc = coords.SkyCoord(l=120 * u.deg, b=5 * u.deg, frame='galactic')
# High-level classes can also be initialized directly from low-level objects
sc = coords.SkyCoord(coords.ICRS(ra=8 * u.hour, dec=5 * u.deg))
# The next example raises an error because the high-level class must always
# have position data.
with pytest.raises(ValueError):
sc = coords.SkyCoord(coords.FK5(equinox=J2001)) # raises ValueError
# similarly, the low-level object can always be accessed
# this is how it's supposed to look, but sometimes the numbers get rounded in
# funny ways
# assert repr(sc.frame) == '<ICRS Coordinate: ra=120.0 deg, dec=5.0 deg>'
rscf = repr(sc.frame)
assert rscf.startswith('<ICRS Coordinate: (ra, dec) in deg')
# and the string representation will be inherited from the low-level class.
# same deal, should loook like this, but different archituectures/ python
# versions may round the numbers differently
# assert repr(sc) == '<SkyCoord (ICRS): ra=120.0 deg, dec=5.0 deg>'
rsc = repr(sc)
assert rsc.startswith('<SkyCoord (ICRS): (ra, dec) in deg')
# Supports a variety of possible complex string formats
sc = coords.SkyCoord('8h00m00s +5d00m00.0s', frame='icrs')
# In the next example, the unit is only needed b/c units are ambiguous. In
# general, we *never* accept ambiguity
sc = coords.SkyCoord('8:00:00 +5:00:00.0', unit=(u.hour, u.deg), frame='icrs')
# The next one would yield length-2 array coordinates, because of the comma
sc = coords.SkyCoord(['8h 5d', '2°2′3″ 0.3rad'], frame='icrs')
# It should also interpret common designation styles as a coordinate
# NOT YET
# sc = coords.SkyCoord('SDSS J123456.89-012345.6', frame='icrs')
# but it should also be possible to provide formats for outputting to strings,
# similar to `Time`. This can be added right away or at a later date.
# transformation is done the same as for low-level classes, which it delegates to
sc_fk5_j2001 = sc.transform_to(coords.FK5(equinox=J2001))
assert sc_fk5_j2001.equinox == J2001
# The key difference is that the high-level class remembers frame information
# necessary for round-tripping, unlike the low-level classes:
sc1 = coords.SkyCoord(ra=8 * u.hour, dec=5 * u.deg, equinox=J2001, frame='fk5')
sc2 = sc1.transform_to('icrs')
# The next assertion succeeds, but it doesn't mean anything for ICRS, as ICRS
# isn't defined in terms of an equinox
assert sc2.equinox == J2001
# But it *is* necessary once we transform to FK5
sc3 = sc2.transform_to('fk5')
assert sc3.equinox == J2001
assert_allclose(sc1.ra, sc3.ra)
# `SkyCoord` will also include the attribute-style access that is in the
# v0.2/0.3 coordinate objects. This will *not* be in the low-level classes
sc = coords.SkyCoord(ra=8 * u.hour, dec=5 * u.deg, frame='icrs')
scgal = sc.galactic
assert str(scgal).startswith('<SkyCoord (Galactic): (l, b)')
# the existing `from_name` and `match_to_catalog_*` methods will be moved to the
# high-level class as convenience functionality.
# in remote-data test below!
# m31icrs = coords.SkyCoord.from_name('M31', frame='icrs')
# assert str(m31icrs) == '<SkyCoord (ICRS) RA=10.68471 deg, Dec=41.26875 deg>'
if HAS_SCIPY:
cat1 = coords.SkyCoord(ra=[1, 2]*u.hr, dec=[3, 4.01]*u.deg, distance=[5, 6]*u.kpc, frame='icrs')
cat2 = coords.SkyCoord(ra=[1, 2, 2.01]*u.hr, dec=[3, 4, 5]*u.deg, distance=[5, 200, 6]*u.kpc, frame='icrs')
idx1, sep2d1, dist3d1 = cat1.match_to_catalog_sky(cat2)
idx2, sep2d2, dist3d2 = cat1.match_to_catalog_3d(cat2)
assert np.any(idx1 != idx2)
# additional convenience functionality for the future should be added as methods
# on `SkyCoord`, *not* the low-level classes.
@pytest.mark.remote_data
def test_highlevel_api_remote():
m31icrs = coords.SkyCoord.from_name('M31', frame='icrs')
m31str = str(m31icrs)
assert m31str.startswith('<SkyCoord (ICRS): (ra, dec) in deg\n (')
assert m31str.endswith(')>')
assert '10.68' in m31str
assert '41.26' in m31str
# The above is essentially a replacement of the below, but tweaked so that
# small/moderate changes in what `from_name` returns don't cause the tests
# to fail
# assert str(m31icrs) == '<SkyCoord (ICRS): (ra, dec) in deg\n (10.6847083, 41.26875)>'
m31fk4 = coords.SkyCoord.from_name('M31', frame='fk4')
assert m31icrs.frame != m31fk4.frame
assert np.abs(m31icrs.ra - m31fk4.ra) > .5*u.deg
|
92962f3e489cc11a3256dd8eab0b169356076e8cd01dfc94b20aff2b75e70b35 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for putting velocity differentials into SkyCoord objects.
Note: the skyoffset velocity tests are in a different file, in
test_skyoffset_transformations.py
"""
import pytest
import numpy as np
from ... import units as u
from ...tests.helper import assert_quantity_allclose
from .. import (SkyCoord, ICRS, SphericalRepresentation, SphericalDifferential,
SphericalCosLatDifferential, CartesianRepresentation,
CartesianDifferential, Galactic, PrecessedGeocentric)
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
def test_creation_frameobjs():
i = ICRS(1*u.deg, 2*u.deg, pm_ra_cosdec=.2*u.mas/u.yr, pm_dec=.1*u.mas/u.yr)
sc = SkyCoord(i)
for attrnm in ['ra', 'dec', 'pm_ra_cosdec', 'pm_dec']:
assert_quantity_allclose(getattr(i, attrnm), getattr(sc, attrnm))
sc_nod = SkyCoord(ICRS(1*u.deg, 2*u.deg))
for attrnm in ['ra', 'dec']:
assert_quantity_allclose(getattr(sc, attrnm), getattr(sc_nod, attrnm))
def test_creation_attrs():
sc1 = SkyCoord(1*u.deg, 2*u.deg,
pm_ra_cosdec=.2*u.mas/u.yr, pm_dec=.1*u.mas/u.yr,
frame='fk5')
assert_quantity_allclose(sc1.ra, 1*u.deg)
assert_quantity_allclose(sc1.dec, 2*u.deg)
assert_quantity_allclose(sc1.pm_ra_cosdec, .2*u.arcsec/u.kyr)
assert_quantity_allclose(sc1.pm_dec, .1*u.arcsec/u.kyr)
sc2 = SkyCoord(1*u.deg, 2*u.deg,
pm_ra=.2*u.mas/u.yr, pm_dec=.1*u.mas/u.yr,
differential_type=SphericalDifferential)
assert_quantity_allclose(sc2.ra, 1*u.deg)
assert_quantity_allclose(sc2.dec, 2*u.deg)
assert_quantity_allclose(sc2.pm_ra, .2*u.arcsec/u.kyr)
assert_quantity_allclose(sc2.pm_dec, .1*u.arcsec/u.kyr)
sc3 = SkyCoord('1:2:3 4:5:6',
pm_ra_cosdec=.2*u.mas/u.yr, pm_dec=.1*u.mas/u.yr,
unit=(u.hour, u.deg))
assert_quantity_allclose(sc3.ra, 1*u.hourangle + 2*u.arcmin*15 + 3*u.arcsec*15)
assert_quantity_allclose(sc3.dec, 4*u.deg + 5*u.arcmin + 6*u.arcsec)
# might as well check with sillier units?
assert_quantity_allclose(sc3.pm_ra_cosdec, 1.2776637006616473e-07 * u.arcmin / u.fortnight)
assert_quantity_allclose(sc3.pm_dec, 6.388318503308237e-08 * u.arcmin / u.fortnight)
def test_creation_copy_basic():
i = ICRS(1*u.deg, 2*u.deg, pm_ra_cosdec=.2*u.mas/u.yr, pm_dec=.1*u.mas/u.yr)
sc = SkyCoord(i)
sc_cpy = SkyCoord(sc)
for attrnm in ['ra', 'dec', 'pm_ra_cosdec', 'pm_dec']:
assert_quantity_allclose(getattr(sc, attrnm), getattr(sc_cpy, attrnm))
def test_creation_copy_rediff():
sc = SkyCoord(1*u.deg, 2*u.deg,
pm_ra=.2*u.mas/u.yr, pm_dec=.1*u.mas/u.yr,
differential_type=SphericalDifferential)
sc_cpy = SkyCoord(sc)
for attrnm in ['ra', 'dec', 'pm_ra', 'pm_dec']:
assert_quantity_allclose(getattr(sc, attrnm), getattr(sc_cpy, attrnm))
sc_newdiff = SkyCoord(sc, differential_type=SphericalCosLatDifferential)
reprepr = sc.represent_as(SphericalRepresentation, SphericalCosLatDifferential)
assert_quantity_allclose(sc_newdiff.pm_ra_cosdec,
reprepr.differentials['s'].d_lon_coslat)
def test_creation_cartesian():
rep = CartesianRepresentation([10, 0., 0.]*u.pc)
dif = CartesianDifferential([0, 100, 0.]*u.pc/u.Myr)
rep = rep.with_differentials(dif)
c = SkyCoord(rep)
sdif = dif.represent_as(SphericalCosLatDifferential, rep)
assert_quantity_allclose(c.pm_ra_cosdec, sdif.d_lon_coslat)
def test_useful_error_missing():
sc_nod = SkyCoord(ICRS(1*u.deg, 2*u.deg))
try:
sc_nod.l
except AttributeError as e:
# this is double-checking the *normal* behavior
msg_l = e.args[0]
try:
sc_nod.pm_dec
except Exception as e:
msg_pm_dec = e.args[0]
assert "has no attribute" in msg_l
assert "has no associated differentials" in msg_pm_dec
# ----------------------Operations on SkyCoords w/ velocities-------------------
# define some fixtires to get baseline coordinates to try operations with
@pytest.fixture(scope="module", params=[(False, False),
(True, False),
(False, True),
(True, True)])
def sc(request):
incldist, inclrv = request.param
args = [1*u.deg, 2*u.deg]
kwargs = dict(pm_dec=1*u.mas/u.yr, pm_ra_cosdec=2*u.mas/u.yr)
if incldist:
kwargs['distance'] = 213.4*u.pc
if inclrv:
kwargs['radial_velocity'] = 61*u.km/u.s
return SkyCoord(*args, **kwargs)
@pytest.fixture(scope="module")
def scmany():
return SkyCoord(ICRS(ra=[1]*100*u.deg, dec=[2]*100*u.deg,
pm_ra_cosdec=np.random.randn(100)*u.mas/u.yr,
pm_dec=np.random.randn(100)*u.mas/u.yr,))
@pytest.fixture(scope="module")
def sc_for_sep():
return SkyCoord(1*u.deg, 2*u.deg,
pm_dec=1*u.mas/u.yr, pm_ra_cosdec=2*u.mas/u.yr)
def test_separation(sc, sc_for_sep):
sc.separation(sc_for_sep)
def test_accessors(sc, scmany):
sc.data.differentials['s']
sph = sc.spherical
gal = sc.galactic
if (sc.data.get_name().startswith('unit') and not
sc.data.differentials['s'].get_name().startswith('unit')):
# this xfail can be eliminated when issue #7028 is resolved
pytest.xfail('.velocity fails if there is an RV but not distance')
sc.velocity
assert isinstance(sph, SphericalRepresentation)
assert gal.data.differentials is not None
scmany[0]
sph = scmany.spherical
gal = scmany.galactic
assert isinstance(sph, SphericalRepresentation)
assert gal.data.differentials is not None
def test_transforms(sc):
trans = sc.transform_to('galactic')
assert isinstance(trans.frame, Galactic)
@pytest.mark.xfail
def test_transforms_diff(sc):
# note that arguably this *should* fail for the no-distance cases: 3D
# information is necessary to truly solve this, hence the xfail
trans = sc.transform_to(PrecessedGeocentric(equinox='B1975'))
assert isinstance(trans.frame, PrecessedGeocentric)
@pytest.mark.skipif(str('not HAS_SCIPY'))
def test_matching(sc, scmany):
# just check that it works and yields something
idx, d2d, d3d = sc.match_to_catalog_sky(scmany)
def test_position_angle(sc, sc_for_sep):
sc.position_angle(sc_for_sep)
def test_constellations(sc):
const = sc.get_constellation()
assert const == 'Pisces'
|
2dc38755a0d7cc0ad33da14ca7457e367eec2f100a26ddbd2c1f034b58769f1c | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from ... import units as u
from ...utils import NumpyRNGContext
def randomly_sample_sphere(ntosample, randomseed=12345):
"""
Generates a set of spherical coordinates uniformly distributed over the
sphere in a way that gives the same answer for the same seed. Also
generates a random distance vector on [0, 1] (no units)
This simply returns (lon, lat, r) instead of a representation to avoid
failures due to the representation module.
"""
with NumpyRNGContext(randomseed):
lat = np.arcsin(np.random.rand(ntosample)*2-1)
lon = np.random.rand(ntosample)*np.pi*2
r = np.random.rand(ntosample)
return lon*u.rad, lat*u.rad, r
|
4efd6bff8c1bdafe5d226af058dc31f77e49a4d1ca19243ab5034577560ca8b1 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import functools
import pytest
import numpy as np
from ... import units as u
from .. import (PhysicsSphericalRepresentation, CartesianRepresentation,
CylindricalRepresentation, SphericalRepresentation,
UnitSphericalRepresentation, SphericalDifferential,
CartesianDifferential, UnitSphericalDifferential,
SphericalCosLatDifferential, UnitSphericalCosLatDifferential,
PhysicsSphericalDifferential, CylindricalDifferential,
RadialRepresentation, RadialDifferential, Longitude, Latitude)
from ..representation import DIFFERENTIAL_CLASSES
from ..angle_utilities import angular_separation
from ...tests.helper import assert_quantity_allclose
def assert_representation_allclose(actual, desired, rtol=1.e-7, atol=None,
**kwargs):
actual_xyz = actual.to_cartesian().get_xyz(xyz_axis=-1)
desired_xyz = desired.to_cartesian().get_xyz(xyz_axis=-1)
actual_xyz, desired_xyz = np.broadcast_arrays(actual_xyz, desired_xyz,
subok=True)
assert_quantity_allclose(actual_xyz, desired_xyz, rtol, atol, **kwargs)
def assert_differential_allclose(actual, desired, rtol=1.e-7, **kwargs):
assert actual.components == desired.components
for component in actual.components:
actual_c = getattr(actual, component)
atol = 1.e-10 * actual_c.unit
assert_quantity_allclose(actual_c, getattr(desired, component),
rtol, atol, **kwargs)
def representation_equal(first, second):
return functools.reduce(np.logical_and,
(getattr(first, component) ==
getattr(second, component)
for component in first.components))
class TestArithmetic():
def setup(self):
# Choose some specific coordinates, for which ``sum`` and ``dot``
# works out nicely.
self.lon = Longitude(np.arange(0, 12.1, 2), u.hourangle)
self.lat = Latitude(np.arange(-90, 91, 30), u.deg)
self.distance = [5., 12., 4., 2., 4., 12., 5.] * u.kpc
self.spherical = SphericalRepresentation(self.lon, self.lat,
self.distance)
self.unit_spherical = self.spherical.represent_as(
UnitSphericalRepresentation)
self.cartesian = self.spherical.to_cartesian()
def test_norm_spherical(self):
norm_s = self.spherical.norm()
assert isinstance(norm_s, u.Quantity)
# Just to be sure, test against getting object arrays.
assert norm_s.dtype.kind == 'f'
assert np.all(norm_s == self.distance)
@pytest.mark.parametrize('representation',
(PhysicsSphericalRepresentation,
CartesianRepresentation,
CylindricalRepresentation))
def test_norm(self, representation):
in_rep = self.spherical.represent_as(representation)
norm_rep = in_rep.norm()
assert isinstance(norm_rep, u.Quantity)
assert_quantity_allclose(norm_rep, self.distance)
def test_norm_unitspherical(self):
norm_rep = self.unit_spherical.norm()
assert norm_rep.unit == u.dimensionless_unscaled
assert np.all(norm_rep == 1. * u.dimensionless_unscaled)
@pytest.mark.parametrize('representation',
(SphericalRepresentation,
PhysicsSphericalRepresentation,
CartesianRepresentation,
CylindricalRepresentation,
UnitSphericalRepresentation))
def test_neg_pos(self, representation):
in_rep = self.cartesian.represent_as(representation)
pos_rep = +in_rep
assert type(pos_rep) is type(in_rep)
assert pos_rep is not in_rep
assert np.all(representation_equal(pos_rep, in_rep))
neg_rep = -in_rep
assert type(neg_rep) is type(in_rep)
assert np.all(neg_rep.norm() == in_rep.norm())
in_rep_xyz = in_rep.to_cartesian().xyz
assert_quantity_allclose(neg_rep.to_cartesian().xyz,
-in_rep_xyz, atol=1.e-10*in_rep_xyz.unit)
def test_mul_div_spherical(self):
s0 = self.spherical / (1. * u.Myr)
assert isinstance(s0, SphericalRepresentation)
assert s0.distance.dtype.kind == 'f'
assert np.all(s0.lon == self.spherical.lon)
assert np.all(s0.lat == self.spherical.lat)
assert np.all(s0.distance == self.distance / (1. * u.Myr))
s1 = (1./u.Myr) * self.spherical
assert isinstance(s1, SphericalRepresentation)
assert np.all(representation_equal(s1, s0))
s2 = self.spherical * np.array([[1.], [2.]])
assert isinstance(s2, SphericalRepresentation)
assert s2.shape == (2, self.spherical.shape[0])
assert np.all(s2.lon == self.spherical.lon)
assert np.all(s2.lat == self.spherical.lat)
assert np.all(s2.distance ==
self.spherical.distance * np.array([[1.], [2.]]))
s3 = np.array([[1.], [2.]]) * self.spherical
assert isinstance(s3, SphericalRepresentation)
assert np.all(representation_equal(s3, s2))
s4 = -self.spherical
assert isinstance(s4, SphericalRepresentation)
assert np.all(s4.lon == self.spherical.lon)
assert np.all(s4.lat == self.spherical.lat)
assert np.all(s4.distance == -self.spherical.distance)
s5 = +self.spherical
assert s5 is not self.spherical
assert np.all(representation_equal(s5, self.spherical))
@pytest.mark.parametrize('representation',
(PhysicsSphericalRepresentation,
CartesianRepresentation,
CylindricalRepresentation))
def test_mul_div(self, representation):
in_rep = self.spherical.represent_as(representation)
r1 = in_rep / (1. * u.Myr)
assert isinstance(r1, representation)
for component in in_rep.components:
in_rep_comp = getattr(in_rep, component)
r1_comp = getattr(r1, component)
if in_rep_comp.unit == self.distance.unit:
assert np.all(r1_comp == in_rep_comp / (1.*u.Myr))
else:
assert np.all(r1_comp == in_rep_comp)
r2 = np.array([[1.], [2.]]) * in_rep
assert isinstance(r2, representation)
assert r2.shape == (2, in_rep.shape[0])
assert_quantity_allclose(r2.norm(),
self.distance * np.array([[1.], [2.]]))
r3 = -in_rep
assert np.all(representation_equal(r3, in_rep * -1.))
with pytest.raises(TypeError):
in_rep * in_rep
with pytest.raises(TypeError):
dict() * in_rep
def test_mul_div_unit_spherical(self):
s1 = self.unit_spherical * self.distance
assert isinstance(s1, SphericalRepresentation)
assert np.all(s1.lon == self.unit_spherical.lon)
assert np.all(s1.lat == self.unit_spherical.lat)
assert np.all(s1.distance == self.spherical.distance)
s2 = self.unit_spherical / u.s
assert isinstance(s2, SphericalRepresentation)
assert np.all(s2.lon == self.unit_spherical.lon)
assert np.all(s2.lat == self.unit_spherical.lat)
assert np.all(s2.distance == 1./u.s)
u3 = -self.unit_spherical
assert isinstance(u3, UnitSphericalRepresentation)
assert_quantity_allclose(u3.lon, self.unit_spherical.lon + 180.*u.deg)
assert np.all(u3.lat == -self.unit_spherical.lat)
assert_quantity_allclose(u3.to_cartesian().xyz,
-self.unit_spherical.to_cartesian().xyz,
atol=1.e-10*u.dimensionless_unscaled)
u4 = +self.unit_spherical
assert isinstance(u4, UnitSphericalRepresentation)
assert u4 is not self.unit_spherical
assert np.all(representation_equal(u4, self.unit_spherical))
def test_add_sub_cartesian(self):
c1 = self.cartesian + self.cartesian
assert isinstance(c1, CartesianRepresentation)
assert c1.x.dtype.kind == 'f'
assert np.all(representation_equal(c1, 2. * self.cartesian))
with pytest.raises(TypeError):
self.cartesian + 10.*u.m
with pytest.raises(u.UnitsError):
self.cartesian + (self.cartesian / u.s)
c2 = self.cartesian - self.cartesian
assert isinstance(c2, CartesianRepresentation)
assert np.all(representation_equal(
c2, CartesianRepresentation(0.*u.m, 0.*u.m, 0.*u.m)))
c3 = self.cartesian - self.cartesian / 2.
assert isinstance(c3, CartesianRepresentation)
assert np.all(representation_equal(c3, self.cartesian / 2.))
@pytest.mark.parametrize('representation',
(PhysicsSphericalRepresentation,
SphericalRepresentation,
CylindricalRepresentation))
def test_add_sub(self, representation):
in_rep = self.cartesian.represent_as(representation)
r1 = in_rep + in_rep
assert isinstance(r1, representation)
expected = 2. * in_rep
for component in in_rep.components:
assert_quantity_allclose(getattr(r1, component),
getattr(expected, component))
with pytest.raises(TypeError):
10.*u.m + in_rep
with pytest.raises(u.UnitsError):
in_rep + (in_rep / u.s)
r2 = in_rep - in_rep
assert isinstance(r2, representation)
assert np.all(representation_equal(
r2.to_cartesian(), CartesianRepresentation(0.*u.m, 0.*u.m, 0.*u.m)))
r3 = in_rep - in_rep / 2.
assert isinstance(r3, representation)
expected = in_rep / 2.
assert_representation_allclose(r3, expected)
def test_add_sub_unit_spherical(self):
s1 = self.unit_spherical + self.unit_spherical
assert isinstance(s1, SphericalRepresentation)
expected = 2. * self.unit_spherical
for component in s1.components:
assert_quantity_allclose(getattr(s1, component),
getattr(expected, component))
with pytest.raises(TypeError):
10.*u.m - self.unit_spherical
with pytest.raises(u.UnitsError):
self.unit_spherical + (self.unit_spherical / u.s)
s2 = self.unit_spherical - self.unit_spherical / 2.
assert isinstance(s2, SphericalRepresentation)
expected = self.unit_spherical / 2.
for component in s2.components:
assert_quantity_allclose(getattr(s2, component),
getattr(expected, component))
@pytest.mark.parametrize('representation',
(CartesianRepresentation,
PhysicsSphericalRepresentation,
SphericalRepresentation,
CylindricalRepresentation))
def test_sum_mean(self, representation):
in_rep = self.spherical.represent_as(representation)
r_sum = in_rep.sum()
assert isinstance(r_sum, representation)
expected = SphericalRepresentation(
90. * u.deg, 0. * u.deg, 14. * u.kpc).represent_as(representation)
for component in expected.components:
exp_component = getattr(expected, component)
assert_quantity_allclose(getattr(r_sum, component),
exp_component,
atol=1e-10*exp_component.unit)
r_mean = in_rep.mean()
assert isinstance(r_mean, representation)
expected = expected / len(in_rep)
for component in expected.components:
exp_component = getattr(expected, component)
assert_quantity_allclose(getattr(r_mean, component),
exp_component,
atol=1e-10*exp_component.unit)
def test_sum_mean_unit_spherical(self):
s_sum = self.unit_spherical.sum()
assert isinstance(s_sum, SphericalRepresentation)
expected = SphericalRepresentation(
90. * u.deg, 0. * u.deg, 3. * u.dimensionless_unscaled)
for component in expected.components:
exp_component = getattr(expected, component)
assert_quantity_allclose(getattr(s_sum, component),
exp_component,
atol=1e-10*exp_component.unit)
s_mean = self.unit_spherical.mean()
assert isinstance(s_mean, SphericalRepresentation)
expected = expected / len(self.unit_spherical)
for component in expected.components:
exp_component = getattr(expected, component)
assert_quantity_allclose(getattr(s_mean, component),
exp_component,
atol=1e-10*exp_component.unit)
@pytest.mark.parametrize('representation',
(CartesianRepresentation,
PhysicsSphericalRepresentation,
SphericalRepresentation,
CylindricalRepresentation))
def test_dot(self, representation):
in_rep = self.cartesian.represent_as(representation)
r_dot_r = in_rep.dot(in_rep)
assert isinstance(r_dot_r, u.Quantity)
assert r_dot_r.shape == in_rep.shape
assert_quantity_allclose(np.sqrt(r_dot_r), self.distance)
r_dot_r_rev = in_rep.dot(in_rep[::-1])
assert isinstance(r_dot_r_rev, u.Quantity)
assert r_dot_r_rev.shape == in_rep.shape
expected = [-25., -126., 2., 4., 2., -126., -25.] * u.kpc**2
assert_quantity_allclose(r_dot_r_rev, expected)
for axis in 'xyz':
project = CartesianRepresentation(*(
(1. if axis == _axis else 0.) * u.dimensionless_unscaled
for _axis in 'xyz'))
assert_quantity_allclose(in_rep.dot(project),
getattr(self.cartesian, axis),
atol=1.*u.upc)
with pytest.raises(TypeError):
in_rep.dot(self.cartesian.xyz)
def test_dot_unit_spherical(self):
u_dot_u = self.unit_spherical.dot(self.unit_spherical)
assert isinstance(u_dot_u, u.Quantity)
assert u_dot_u.shape == self.unit_spherical.shape
assert_quantity_allclose(u_dot_u, 1.*u.dimensionless_unscaled)
cartesian = self.unit_spherical.to_cartesian()
for axis in 'xyz':
project = CartesianRepresentation(*(
(1. if axis == _axis else 0.) * u.dimensionless_unscaled
for _axis in 'xyz'))
assert_quantity_allclose(self.unit_spherical.dot(project),
getattr(cartesian, axis), atol=1.e-10)
@pytest.mark.parametrize('representation',
(CartesianRepresentation,
PhysicsSphericalRepresentation,
SphericalRepresentation,
CylindricalRepresentation))
def test_cross(self, representation):
in_rep = self.cartesian.represent_as(representation)
r_cross_r = in_rep.cross(in_rep)
assert isinstance(r_cross_r, representation)
assert_quantity_allclose(r_cross_r.norm(), 0.*u.kpc**2,
atol=1.*u.mpc**2)
r_cross_r_rev = in_rep.cross(in_rep[::-1])
sep = angular_separation(self.lon, self.lat,
self.lon[::-1], self.lat[::-1])
expected = self.distance * self.distance[::-1] * np.sin(sep)
assert_quantity_allclose(r_cross_r_rev.norm(), expected,
atol=1.*u.mpc**2)
unit_vectors = CartesianRepresentation(
[1., 0., 0.]*u.one,
[0., 1., 0.]*u.one,
[0., 0., 1.]*u.one)[:, np.newaxis]
r_cross_uv = in_rep.cross(unit_vectors)
assert r_cross_uv.shape == (3, 7)
assert_quantity_allclose(r_cross_uv.dot(unit_vectors), 0.*u.kpc,
atol=1.*u.upc)
assert_quantity_allclose(r_cross_uv.dot(in_rep), 0.*u.kpc**2,
atol=1.*u.mpc**2)
zeros = np.zeros(len(in_rep)) * u.kpc
expected = CartesianRepresentation(
u.Quantity((zeros, -self.cartesian.z, self.cartesian.y)),
u.Quantity((self.cartesian.z, zeros, -self.cartesian.x)),
u.Quantity((-self.cartesian.y, self.cartesian.x, zeros)))
# Comparison with spherical is hard since some distances are zero,
# implying the angles are undefined.
r_cross_uv_cartesian = r_cross_uv.to_cartesian()
assert_representation_allclose(r_cross_uv_cartesian,
expected, atol=1.*u.upc)
# A final check, with the side benefit of ensuring __div__ and norm
# work on multi-D representations.
r_cross_uv_by_distance = r_cross_uv / self.distance
uv_sph = unit_vectors.represent_as(UnitSphericalRepresentation)
sep = angular_separation(self.lon, self.lat, uv_sph.lon, uv_sph.lat)
assert_quantity_allclose(r_cross_uv_by_distance.norm(), np.sin(sep),
atol=1e-9)
with pytest.raises(TypeError):
in_rep.cross(self.cartesian.xyz)
def test_cross_unit_spherical(self):
u_cross_u = self.unit_spherical.cross(self.unit_spherical)
assert isinstance(u_cross_u, SphericalRepresentation)
assert_quantity_allclose(u_cross_u.norm(), 0.*u.one, atol=1.e-10*u.one)
u_cross_u_rev = self.unit_spherical.cross(self.unit_spherical[::-1])
assert isinstance(u_cross_u_rev, SphericalRepresentation)
sep = angular_separation(self.lon, self.lat,
self.lon[::-1], self.lat[::-1])
expected = np.sin(sep)
assert_quantity_allclose(u_cross_u_rev.norm(), expected,
atol=1.e-10*u.one)
class TestUnitVectorsAndScales():
@staticmethod
def check_unit_vectors(e):
for v in e.values():
assert type(v) is CartesianRepresentation
assert_quantity_allclose(v.norm(), 1. * u.one)
return e
@staticmethod
def check_scale_factors(sf, rep):
unit = rep.norm().unit
for c, f in sf.items():
assert type(f) is u.Quantity
assert (f.unit * getattr(rep, c).unit).is_equivalent(unit)
def test_spherical(self):
s = SphericalRepresentation(lon=[0., 6., 21.] * u.hourangle,
lat=[0., -30., 85.] * u.deg,
distance=[1, 2, 3] * u.kpc)
e = s.unit_vectors()
self.check_unit_vectors(e)
sf = s.scale_factors()
self.check_scale_factors(sf, s)
s_lon = s + s.distance * 1e-5 * np.cos(s.lat) * e['lon']
assert_quantity_allclose(s_lon.lon, s.lon + 1e-5*u.rad,
atol=1e-10*u.rad)
assert_quantity_allclose(s_lon.lat, s.lat, atol=1e-10*u.rad)
assert_quantity_allclose(s_lon.distance, s.distance)
s_lon2 = s + 1e-5 * u.radian * sf['lon'] * e['lon']
assert_representation_allclose(s_lon2, s_lon)
s_lat = s + s.distance * 1e-5 * e['lat']
assert_quantity_allclose(s_lat.lon, s.lon)
assert_quantity_allclose(s_lat.lat, s.lat + 1e-5*u.rad,
atol=1e-10*u.rad)
assert_quantity_allclose(s_lon.distance, s.distance)
s_lat2 = s + 1.e-5 * u.radian * sf['lat'] * e['lat']
assert_representation_allclose(s_lat2, s_lat)
s_distance = s + 1. * u.pc * e['distance']
assert_quantity_allclose(s_distance.lon, s.lon, atol=1e-10*u.rad)
assert_quantity_allclose(s_distance.lat, s.lat, atol=1e-10*u.rad)
assert_quantity_allclose(s_distance.distance, s.distance + 1.*u.pc)
s_distance2 = s + 1. * u.pc * sf['distance'] * e['distance']
assert_representation_allclose(s_distance2, s_distance)
def test_unit_spherical(self):
s = UnitSphericalRepresentation(lon=[0., 6., 21.] * u.hourangle,
lat=[0., -30., 85.] * u.deg)
e = s.unit_vectors()
self.check_unit_vectors(e)
sf = s.scale_factors()
self.check_scale_factors(sf, s)
s_lon = s + 1e-5 * np.cos(s.lat) * e['lon']
assert_quantity_allclose(s_lon.lon, s.lon + 1e-5*u.rad,
atol=1e-10*u.rad)
assert_quantity_allclose(s_lon.lat, s.lat, atol=1e-10*u.rad)
s_lon2 = s + 1e-5 * u.radian * sf['lon'] * e['lon']
assert_representation_allclose(s_lon2, s_lon)
s_lat = s + 1e-5 * e['lat']
assert_quantity_allclose(s_lat.lon, s.lon)
assert_quantity_allclose(s_lat.lat, s.lat + 1e-5*u.rad,
atol=1e-10*u.rad)
s_lat2 = s + 1.e-5 * u.radian * sf['lat'] * e['lat']
assert_representation_allclose(s_lat2, s_lat)
def test_radial(self):
r = RadialRepresentation(10.*u.kpc)
with pytest.raises(NotImplementedError):
r.unit_vectors()
sf = r.scale_factors()
assert np.all(sf['distance'] == 1.*u.one)
assert np.all(r.norm() == r.distance)
with pytest.raises(TypeError):
r + r
def test_physical_spherical(self):
s = PhysicsSphericalRepresentation(phi=[0., 6., 21.] * u.hourangle,
theta=[90., 120., 5.] * u.deg,
r=[1, 2, 3] * u.kpc)
e = s.unit_vectors()
self.check_unit_vectors(e)
sf = s.scale_factors()
self.check_scale_factors(sf, s)
s_phi = s + s.r * 1e-5 * np.sin(s.theta) * e['phi']
assert_quantity_allclose(s_phi.phi, s.phi + 1e-5*u.rad,
atol=1e-10*u.rad)
assert_quantity_allclose(s_phi.theta, s.theta, atol=1e-10*u.rad)
assert_quantity_allclose(s_phi.r, s.r)
s_phi2 = s + 1e-5 * u.radian * sf['phi'] * e['phi']
assert_representation_allclose(s_phi2, s_phi)
s_theta = s + s.r * 1e-5 * e['theta']
assert_quantity_allclose(s_theta.phi, s.phi)
assert_quantity_allclose(s_theta.theta, s.theta + 1e-5*u.rad,
atol=1e-10*u.rad)
assert_quantity_allclose(s_theta.r, s.r)
s_theta2 = s + 1.e-5 * u.radian * sf['theta'] * e['theta']
assert_representation_allclose(s_theta2, s_theta)
s_r = s + 1. * u.pc * e['r']
assert_quantity_allclose(s_r.phi, s.phi, atol=1e-10*u.rad)
assert_quantity_allclose(s_r.theta, s.theta, atol=1e-10*u.rad)
assert_quantity_allclose(s_r.r, s.r + 1.*u.pc)
s_r2 = s + 1. * u.pc * sf['r'] * e['r']
assert_representation_allclose(s_r2, s_r)
def test_cartesian(self):
s = CartesianRepresentation(x=[1, 2, 3] * u.pc,
y=[2, 3, 4] * u.Mpc,
z=[3, 4, 5] * u.kpc)
e = s.unit_vectors()
sf = s.scale_factors()
for v, expected in zip(e.values(), ([1., 0., 0.] * u.one,
[0., 1., 0.] * u.one,
[0., 0., 1.] * u.one)):
assert np.all(v.get_xyz(xyz_axis=-1) == expected)
for f in sf.values():
assert np.all(f == 1.*u.one)
def test_cylindrical(self):
s = CylindricalRepresentation(rho=[1, 2, 3] * u.pc,
phi=[0., 90., -45.] * u.deg,
z=[3, 4, 5] * u.kpc)
e = s.unit_vectors()
self.check_unit_vectors(e)
sf = s.scale_factors()
self.check_scale_factors(sf, s)
s_rho = s + 1. * u.pc * e['rho']
assert_quantity_allclose(s_rho.rho, s.rho + 1.*u.pc)
assert_quantity_allclose(s_rho.phi, s.phi)
assert_quantity_allclose(s_rho.z, s.z)
s_rho2 = s + 1. * u.pc * sf['rho'] * e['rho']
assert_representation_allclose(s_rho2, s_rho)
s_phi = s + s.rho * 1e-5 * e['phi']
assert_quantity_allclose(s_phi.rho, s.rho)
assert_quantity_allclose(s_phi.phi, s.phi + 1e-5*u.rad)
assert_quantity_allclose(s_phi.z, s.z)
s_phi2 = s + 1e-5 * u.radian * sf['phi'] * e['phi']
assert_representation_allclose(s_phi2, s_phi)
s_z = s + 1. * u.pc * e['z']
assert_quantity_allclose(s_z.rho, s.rho)
assert_quantity_allclose(s_z.phi, s.phi, atol=1e-10*u.rad)
assert_quantity_allclose(s_z.z, s.z + 1.*u.pc)
s_z2 = s + 1. * u.pc * sf['z'] * e['z']
assert_representation_allclose(s_z2, s_z)
@pytest.mark.parametrize('omit_coslat', [False, True], scope='class')
class TestSphericalDifferential():
# these test cases are subclassed for SphericalCosLatDifferential,
# hence some tests depend on omit_coslat.
def _setup(self, omit_coslat):
if omit_coslat:
self.SD_cls = SphericalCosLatDifferential
else:
self.SD_cls = SphericalDifferential
s = SphericalRepresentation(lon=[0., 6., 21.] * u.hourangle,
lat=[0., -30., 85.] * u.deg,
distance=[1, 2, 3] * u.kpc)
self.s = s
self.e = s.unit_vectors()
self.sf = s.scale_factors(omit_coslat=omit_coslat)
def test_name_coslat(self, omit_coslat):
self._setup(omit_coslat)
if omit_coslat:
assert self.SD_cls is SphericalCosLatDifferential
assert self.SD_cls.get_name() == 'sphericalcoslat'
else:
assert self.SD_cls is SphericalDifferential
assert self.SD_cls.get_name() == 'spherical'
assert self.SD_cls.get_name() in DIFFERENTIAL_CLASSES
def test_simple_differentials(self, omit_coslat):
self._setup(omit_coslat)
s, e, sf = self.s, self.e, self.sf
o_lon = self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc)
o_lonc = o_lon.to_cartesian(base=s)
o_lon2 = self.SD_cls.from_cartesian(o_lonc, base=s)
assert_differential_allclose(o_lon, o_lon2)
# simple check by hand for first element.
# lat[0] is 0, so cos(lat) term doesn't matter.
assert_quantity_allclose(o_lonc[0].xyz,
[0., np.pi/180./3600., 0.]*u.kpc)
# check all using unit vectors and scale factors.
s_lon = s + 1.*u.arcsec * sf['lon'] * e['lon']
assert_representation_allclose(o_lonc, s_lon - s, atol=1*u.npc)
s_lon2 = s + o_lon
assert_representation_allclose(s_lon2, s_lon, atol=1*u.npc)
o_lat = self.SD_cls(0.*u.arcsec, 1.*u.arcsec, 0.*u.kpc)
o_latc = o_lat.to_cartesian(base=s)
assert_quantity_allclose(o_latc[0].xyz,
[0., 0., np.pi/180./3600.]*u.kpc,
atol=1.*u.npc)
s_lat = s + 1.*u.arcsec * sf['lat'] * e['lat']
assert_representation_allclose(o_latc, s_lat - s, atol=1*u.npc)
s_lat2 = s + o_lat
assert_representation_allclose(s_lat2, s_lat, atol=1*u.npc)
o_distance = self.SD_cls(0.*u.arcsec, 0.*u.arcsec, 1.*u.mpc)
o_distancec = o_distance.to_cartesian(base=s)
assert_quantity_allclose(o_distancec[0].xyz,
[1e-6, 0., 0.]*u.kpc, atol=1.*u.npc)
s_distance = s + 1.*u.mpc * sf['distance'] * e['distance']
assert_representation_allclose(o_distancec, s_distance - s,
atol=1*u.npc)
s_distance2 = s + o_distance
assert_representation_allclose(s_distance2, s_distance)
def test_differential_arithmetic(self, omit_coslat):
self._setup(omit_coslat)
s = self.s
o_lon = self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc)
o_lon_by_2 = o_lon / 2.
assert_representation_allclose(o_lon_by_2.to_cartesian(s) * 2.,
o_lon.to_cartesian(s), atol=1e-10*u.kpc)
assert_representation_allclose(s + o_lon, s + 2 * o_lon_by_2,
atol=1e-10*u.kpc)
o_lon_rec = o_lon_by_2 + o_lon_by_2
assert_representation_allclose(s + o_lon, s + o_lon_rec,
atol=1e-10*u.kpc)
o_lon_0 = o_lon - o_lon
for c in o_lon_0.components:
assert np.all(getattr(o_lon_0, c) == 0.)
o_lon2 = self.SD_cls(1*u.mas/u.yr, 0*u.mas/u.yr, 0*u.km/u.s)
assert_quantity_allclose(o_lon2.norm(s)[0], 4.74*u.km/u.s,
atol=0.01*u.km/u.s)
assert_representation_allclose(o_lon2.to_cartesian(s) * 1000.*u.yr,
o_lon.to_cartesian(s), atol=1e-10*u.kpc)
s_off = s + o_lon
s_off2 = s + o_lon2 * 1000.*u.yr
assert_representation_allclose(s_off, s_off2, atol=1e-10*u.kpc)
factor = 1e5 * u.radian/u.arcsec
if not omit_coslat:
factor = factor / np.cos(s.lat)
s_off_big = s + o_lon * factor
assert_representation_allclose(
s_off_big, SphericalRepresentation(s.lon + 90.*u.deg, 0.*u.deg,
1e5*s.distance),
atol=5.*u.kpc)
o_lon3c = CartesianRepresentation(0., 4.74047, 0., unit=u.km/u.s)
o_lon3 = self.SD_cls.from_cartesian(o_lon3c, base=s)
expected0 = self.SD_cls(1.*u.mas/u.yr, 0.*u.mas/u.yr, 0.*u.km/u.s)
assert_differential_allclose(o_lon3[0], expected0)
s_off_big2 = s + o_lon3 * 1e5 * u.yr * u.radian/u.mas
assert_representation_allclose(
s_off_big2, SphericalRepresentation(90.*u.deg, 0.*u.deg,
1e5*u.kpc), atol=5.*u.kpc)
with pytest.raises(TypeError):
o_lon - s
with pytest.raises(TypeError):
s.to_cartesian() + o_lon
def test_differential_init_errors(self, omit_coslat):
self._setup(omit_coslat)
s = self.s
with pytest.raises(u.UnitsError):
self.SD_cls(1.*u.arcsec, 0., 0.)
with pytest.raises(TypeError):
self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc,
False, False)
with pytest.raises(TypeError):
self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc,
copy=False, d_lat=0.*u.arcsec)
with pytest.raises(TypeError):
self.SD_cls(1.*u.arcsec, 0.*u.arcsec, 0.*u.kpc,
copy=False, flying='circus')
with pytest.raises(ValueError):
self.SD_cls(np.ones(2)*u.arcsec,
np.zeros(3)*u.arcsec, np.zeros(2)*u.kpc)
with pytest.raises(u.UnitsError):
self.SD_cls(1.*u.arcsec, 1.*u.s, 0.*u.kpc)
with pytest.raises(u.UnitsError):
self.SD_cls(1.*u.kpc, 1.*u.arcsec, 0.*u.kpc)
o = self.SD_cls(1.*u.arcsec, 1.*u.arcsec, 0.*u.km/u.s)
with pytest.raises(u.UnitsError):
o.to_cartesian(s)
with pytest.raises(AttributeError):
o.d_lat = 0.*u.arcsec
with pytest.raises(AttributeError):
del o.d_lat
o = self.SD_cls(1.*u.arcsec, 1.*u.arcsec, 0.*u.km)
with pytest.raises(TypeError):
o.to_cartesian()
c = CartesianRepresentation(10., 0., 0., unit=u.km)
with pytest.raises(TypeError):
self.SD_cls.to_cartesian(c)
with pytest.raises(TypeError):
self.SD_cls.from_cartesian(c)
with pytest.raises(TypeError):
self.SD_cls.from_cartesian(c, SphericalRepresentation)
with pytest.raises(TypeError):
self.SD_cls.from_cartesian(c, c)
@pytest.mark.parametrize('omit_coslat', [False, True], scope='class')
class TestUnitSphericalDifferential():
def _setup(self, omit_coslat):
if omit_coslat:
self.USD_cls = UnitSphericalCosLatDifferential
else:
self.USD_cls = UnitSphericalDifferential
s = UnitSphericalRepresentation(lon=[0., 6., 21.] * u.hourangle,
lat=[0., -30., 85.] * u.deg)
self.s = s
self.e = s.unit_vectors()
self.sf = s.scale_factors(omit_coslat=omit_coslat)
def test_name_coslat(self, omit_coslat):
self._setup(omit_coslat)
if omit_coslat:
assert self.USD_cls is UnitSphericalCosLatDifferential
assert self.USD_cls.get_name() == 'unitsphericalcoslat'
else:
assert self.USD_cls is UnitSphericalDifferential
assert self.USD_cls.get_name() == 'unitspherical'
assert self.USD_cls.get_name() in DIFFERENTIAL_CLASSES
def test_simple_differentials(self, omit_coslat):
self._setup(omit_coslat)
s, e, sf = self.s, self.e, self.sf
o_lon = self.USD_cls(1.*u.arcsec, 0.*u.arcsec)
o_lonc = o_lon.to_cartesian(base=s)
o_lon2 = self.USD_cls.from_cartesian(o_lonc, base=s)
assert_differential_allclose(o_lon, o_lon2)
# simple check by hand for first element
# (lat[0]=0, so works for both normal and CosLat differential)
assert_quantity_allclose(o_lonc[0].xyz,
[0., np.pi/180./3600., 0.]*u.one)
# check all using unit vectors and scale factors.
s_lon = s + 1.*u.arcsec * sf['lon'] * e['lon']
assert type(s_lon) is SphericalRepresentation
assert_representation_allclose(o_lonc, s_lon - s, atol=1e-10*u.one)
s_lon2 = s + o_lon
assert_representation_allclose(s_lon2, s_lon, atol=1e-10*u.one)
o_lat = self.USD_cls(0.*u.arcsec, 1.*u.arcsec)
o_latc = o_lat.to_cartesian(base=s)
assert_quantity_allclose(o_latc[0].xyz,
[0., 0., np.pi/180./3600.]*u.one,
atol=1e-10*u.one)
s_lat = s + 1.*u.arcsec * sf['lat'] * e['lat']
assert type(s_lat) is SphericalRepresentation
assert_representation_allclose(o_latc, s_lat - s, atol=1e-10*u.one)
s_lat2 = s + o_lat
assert_representation_allclose(s_lat2, s_lat, atol=1e-10*u.one)
def test_differential_arithmetic(self, omit_coslat):
self._setup(omit_coslat)
s = self.s
o_lon = self.USD_cls(1.*u.arcsec, 0.*u.arcsec)
o_lon_by_2 = o_lon / 2.
assert type(o_lon_by_2) is self.USD_cls
assert_representation_allclose(o_lon_by_2.to_cartesian(s) * 2.,
o_lon.to_cartesian(s), atol=1e-10*u.one)
s_lon = s + o_lon
s_lon2 = s + 2 * o_lon_by_2
assert type(s_lon) is SphericalRepresentation
assert_representation_allclose(s_lon, s_lon2, atol=1e-10*u.one)
o_lon_rec = o_lon_by_2 + o_lon_by_2
assert type(o_lon_rec) is self.USD_cls
assert representation_equal(o_lon, o_lon_rec)
assert_representation_allclose(s + o_lon, s + o_lon_rec,
atol=1e-10*u.one)
o_lon_0 = o_lon - o_lon
assert type(o_lon_0) is self.USD_cls
for c in o_lon_0.components:
assert np.all(getattr(o_lon_0, c) == 0.)
o_lon2 = self.USD_cls(1.*u.mas/u.yr, 0.*u.mas/u.yr)
kks = u.km/u.kpc/u.s
assert_quantity_allclose(o_lon2.norm(s)[0], 4.74047*kks, atol=1e-4*kks)
assert_representation_allclose(o_lon2.to_cartesian(s) * 1000.*u.yr,
o_lon.to_cartesian(s), atol=1e-10*u.one)
s_off = s + o_lon
s_off2 = s + o_lon2 * 1000.*u.yr
assert_representation_allclose(s_off, s_off2, atol=1e-10*u.one)
factor = 1e5 * u.radian/u.arcsec
if not omit_coslat:
factor = factor / np.cos(s.lat)
s_off_big = s + o_lon * factor
assert_representation_allclose(
s_off_big, SphericalRepresentation(s.lon + 90.*u.deg,
0.*u.deg, 1e5),
atol=5.*u.one)
o_lon3c = CartesianRepresentation(0., 4.74047, 0., unit=kks)
# This looses information!!
o_lon3 = self.USD_cls.from_cartesian(o_lon3c, base=s)
expected0 = self.USD_cls(1.*u.mas/u.yr, 0.*u.mas/u.yr)
assert_differential_allclose(o_lon3[0], expected0)
# Part of motion kept.
part_kept = s.cross(CartesianRepresentation(0, 1, 0, unit=u.one)).norm()
assert_quantity_allclose(o_lon3.norm(s), 4.74047*part_kept*kks,
atol=1e-10*kks)
# (lat[0]=0, so works for both normal and CosLat differential)
s_off_big2 = s + o_lon3 * 1e5 * u.yr * u.radian/u.mas
expected0 = SphericalRepresentation(90.*u.deg, 0.*u.deg,
1e5*u.one)
assert_representation_allclose(s_off_big2[0], expected0, atol=5.*u.one)
def test_differential_init_errors(self, omit_coslat):
self._setup(omit_coslat)
with pytest.raises(u.UnitsError):
self.USD_cls(0.*u.deg, 10.*u.deg/u.yr)
class TestRadialDifferential():
def setup(self):
s = SphericalRepresentation(lon=[0., 6., 21.] * u.hourangle,
lat=[0., -30., 85.] * u.deg,
distance=[1, 2, 3] * u.kpc)
self.s = s
self.r = s.represent_as(RadialRepresentation)
self.e = s.unit_vectors()
self.sf = s.scale_factors()
def test_name(self):
assert RadialDifferential.get_name() == 'radial'
assert RadialDifferential.get_name() in DIFFERENTIAL_CLASSES
def test_simple_differentials(self):
r, s, e, sf = self.r, self.s, self.e, self.sf
o_distance = RadialDifferential(1.*u.mpc)
# Can be applied to RadialRepresentation, though not most useful.
r_distance = r + o_distance
assert_quantity_allclose(r_distance.distance,
r.distance + o_distance.d_distance)
r_distance2 = o_distance + r
assert_quantity_allclose(r_distance2.distance,
r.distance + o_distance.d_distance)
# More sense to apply it relative to spherical representation.
o_distancec = o_distance.to_cartesian(base=s)
assert_quantity_allclose(o_distancec[0].xyz,
[1e-6, 0., 0.]*u.kpc, atol=1.*u.npc)
o_recover = RadialDifferential.from_cartesian(o_distancec, base=s)
assert_quantity_allclose(o_recover.d_distance, o_distance.d_distance)
s_distance = s + 1.*u.mpc * sf['distance'] * e['distance']
assert_representation_allclose(o_distancec, s_distance - s,
atol=1*u.npc)
s_distance2 = s + o_distance
assert_representation_allclose(s_distance2, s_distance)
class TestPhysicsSphericalDifferential():
"""Test copied from SphericalDifferential, so less extensive."""
def setup(self):
s = PhysicsSphericalRepresentation(phi=[0., 90., 315.] * u.deg,
theta=[90., 120., 5.] * u.deg,
r=[1, 2, 3] * u.kpc)
self.s = s
self.e = s.unit_vectors()
self.sf = s.scale_factors()
def test_name(self):
assert PhysicsSphericalDifferential.get_name() == 'physicsspherical'
assert PhysicsSphericalDifferential.get_name() in DIFFERENTIAL_CLASSES
def test_simple_differentials(self):
s, e, sf = self.s, self.e, self.sf
o_phi = PhysicsSphericalDifferential(1*u.arcsec, 0*u.arcsec, 0*u.kpc)
o_phic = o_phi.to_cartesian(base=s)
o_phi2 = PhysicsSphericalDifferential.from_cartesian(o_phic, base=s)
assert_quantity_allclose(o_phi.d_phi, o_phi2.d_phi, atol=1.*u.narcsec)
assert_quantity_allclose(o_phi.d_theta, o_phi2.d_theta,
atol=1.*u.narcsec)
assert_quantity_allclose(o_phi.d_r, o_phi2.d_r, atol=1.*u.npc)
# simple check by hand for first element.
assert_quantity_allclose(o_phic[0].xyz,
[0., np.pi/180./3600., 0.]*u.kpc,
atol=1.*u.npc)
# check all using unit vectors and scale factors.
s_phi = s + 1.*u.arcsec * sf['phi'] * e['phi']
assert_representation_allclose(o_phic, s_phi - s, atol=1e-10*u.kpc)
o_theta = PhysicsSphericalDifferential(0*u.arcsec, 1*u.arcsec, 0*u.kpc)
o_thetac = o_theta.to_cartesian(base=s)
assert_quantity_allclose(o_thetac[0].xyz,
[0., 0., -np.pi/180./3600.]*u.kpc,
atol=1.*u.npc)
s_theta = s + 1.*u.arcsec * sf['theta'] * e['theta']
assert_representation_allclose(o_thetac, s_theta - s, atol=1e-10*u.kpc)
s_theta2 = s + o_theta
assert_representation_allclose(s_theta2, s_theta, atol=1e-10*u.kpc)
o_r = PhysicsSphericalDifferential(0*u.arcsec, 0*u.arcsec, 1*u.mpc)
o_rc = o_r.to_cartesian(base=s)
assert_quantity_allclose(o_rc[0].xyz, [1e-6, 0., 0.]*u.kpc,
atol=1.*u.npc)
s_r = s + 1.*u.mpc * sf['r'] * e['r']
assert_representation_allclose(o_rc, s_r - s, atol=1e-10*u.kpc)
s_r2 = s + o_r
assert_representation_allclose(s_r2, s_r)
def test_differential_init_errors(self):
with pytest.raises(u.UnitsError):
PhysicsSphericalDifferential(1.*u.arcsec, 0., 0.)
class TestCylindricalDifferential():
"""Test copied from SphericalDifferential, so less extensive."""
def setup(self):
s = CylindricalRepresentation(rho=[1, 2, 3] * u.kpc,
phi=[0., 90., 315.] * u.deg,
z=[3, 2, 1] * u.kpc)
self.s = s
self.e = s.unit_vectors()
self.sf = s.scale_factors()
def test_name(self):
assert CylindricalDifferential.get_name() == 'cylindrical'
assert CylindricalDifferential.get_name() in DIFFERENTIAL_CLASSES
def test_simple_differentials(self):
s, e, sf = self.s, self.e, self.sf
o_rho = CylindricalDifferential(1.*u.mpc, 0.*u.arcsec, 0.*u.kpc)
o_rhoc = o_rho.to_cartesian(base=s)
assert_quantity_allclose(o_rhoc[0].xyz, [1.e-6, 0., 0.]*u.kpc)
s_rho = s + 1.*u.mpc * sf['rho'] * e['rho']
assert_representation_allclose(o_rhoc, s_rho - s, atol=1e-10*u.kpc)
s_rho2 = s + o_rho
assert_representation_allclose(s_rho2, s_rho)
o_phi = CylindricalDifferential(0.*u.kpc, 1.*u.arcsec, 0.*u.kpc)
o_phic = o_phi.to_cartesian(base=s)
o_phi2 = CylindricalDifferential.from_cartesian(o_phic, base=s)
assert_quantity_allclose(o_phi.d_rho, o_phi2.d_rho, atol=1.*u.npc)
assert_quantity_allclose(o_phi.d_phi, o_phi2.d_phi, atol=1.*u.narcsec)
assert_quantity_allclose(o_phi.d_z, o_phi2.d_z, atol=1.*u.npc)
# simple check by hand for first element.
assert_quantity_allclose(o_phic[0].xyz,
[0., np.pi/180./3600., 0.]*u.kpc)
# check all using unit vectors and scale factors.
s_phi = s + 1.*u.arcsec * sf['phi'] * e['phi']
assert_representation_allclose(o_phic, s_phi - s, atol=1e-10*u.kpc)
o_z = CylindricalDifferential(0.*u.kpc, 0.*u.arcsec, 1.*u.mpc)
o_zc = o_z.to_cartesian(base=s)
assert_quantity_allclose(o_zc[0].xyz, [0., 0., 1.e-6]*u.kpc)
s_z = s + 1.*u.mpc * sf['z'] * e['z']
assert_representation_allclose(o_zc, s_z - s, atol=1e-10*u.kpc)
s_z2 = s + o_z
assert_representation_allclose(s_z2, s_z)
def test_differential_init_errors(self):
with pytest.raises(u.UnitsError):
CylindricalDifferential(1.*u.pc, 1.*u.arcsec, 3.*u.km/u.s)
class TestCartesianDifferential():
"""Test copied from SphericalDifferential, so less extensive."""
def setup(self):
s = CartesianRepresentation(x=[1, 2, 3] * u.kpc,
y=[2, 3, 1] * u.kpc,
z=[3, 1, 2] * u.kpc)
self.s = s
self.e = s.unit_vectors()
self.sf = s.scale_factors()
def test_name(self):
assert CartesianDifferential.get_name() == 'cartesian'
assert CartesianDifferential.get_name() in DIFFERENTIAL_CLASSES
def test_simple_differentials(self):
s, e, sf = self.s, self.e, self.sf
for d, differential in ( # test different inits while we're at it.
('x', CartesianDifferential(1.*u.pc, 0.*u.pc, 0.*u.pc)),
('y', CartesianDifferential([0., 1., 0.], unit=u.pc)),
('z', CartesianDifferential(np.array([[0., 0., 1.]]) * u.pc,
xyz_axis=1))):
o_c = differential.to_cartesian(base=s)
o_c2 = differential.to_cartesian()
assert np.all(representation_equal(o_c, o_c2))
assert all(np.all(getattr(differential, 'd_'+c) == getattr(o_c, c))
for c in ('x', 'y', 'z'))
differential2 = CartesianDifferential.from_cartesian(o_c)
assert np.all(representation_equal(differential2, differential))
differential3 = CartesianDifferential.from_cartesian(o_c, base=o_c)
assert np.all(representation_equal(differential3, differential))
s_off = s + 1.*u.pc * sf[d] * e[d]
assert_representation_allclose(o_c, s_off - s, atol=1e-10*u.kpc)
s_off2 = s + differential
assert_representation_allclose(s_off2, s_off)
def test_init_failures(self):
with pytest.raises(ValueError):
CartesianDifferential(1.*u.kpc/u.s, 2.*u.kpc)
with pytest.raises(u.UnitsError):
CartesianDifferential(1.*u.kpc/u.s, 2.*u.kpc, 3.*u.kpc)
with pytest.raises(ValueError):
CartesianDifferential(1.*u.kpc, 2.*u.kpc, 3.*u.kpc, xyz_axis=1)
class TestDifferentialConversion():
def setup(self):
self.s = SphericalRepresentation(lon=[0., 6., 21.] * u.hourangle,
lat=[0., -30., 85.] * u.deg,
distance=[1, 2, 3] * u.kpc)
@pytest.mark.parametrize('sd_cls', [SphericalDifferential,
SphericalCosLatDifferential])
def test_represent_as_own_class(self, sd_cls):
so = sd_cls(1.*u.deg, 2.*u.deg, 0.1*u.kpc)
so2 = so.represent_as(sd_cls)
assert so2 is so
def test_represent_other_coslat(self):
s = self.s
coslat = np.cos(s.lat)
so = SphericalDifferential(1.*u.deg, 2.*u.deg, 0.1*u.kpc)
so_coslat = so.represent_as(SphericalCosLatDifferential, base=s)
assert_quantity_allclose(so.d_lon * coslat,
so_coslat.d_lon_coslat)
so2 = so_coslat.represent_as(SphericalDifferential, base=s)
assert np.all(representation_equal(so2, so))
so3 = SphericalDifferential.from_representation(so_coslat, base=s)
assert np.all(representation_equal(so3, so))
so_coslat2 = SphericalCosLatDifferential.from_representation(so, base=s)
assert np.all(representation_equal(so_coslat2, so_coslat))
# Also test UnitSpherical
us = s.represent_as(UnitSphericalRepresentation)
uo = so.represent_as(UnitSphericalDifferential)
uo_coslat = so.represent_as(UnitSphericalCosLatDifferential, base=s)
assert_quantity_allclose(uo.d_lon * coslat,
uo_coslat.d_lon_coslat)
uo2 = uo_coslat.represent_as(UnitSphericalDifferential, base=us)
assert np.all(representation_equal(uo2, uo))
uo3 = UnitSphericalDifferential.from_representation(uo_coslat, base=us)
assert np.all(representation_equal(uo3, uo))
uo_coslat2 = UnitSphericalCosLatDifferential.from_representation(
uo, base=us)
assert np.all(representation_equal(uo_coslat2, uo_coslat))
uo_coslat3 = uo.represent_as(UnitSphericalCosLatDifferential, base=us)
assert np.all(representation_equal(uo_coslat3, uo_coslat))
@pytest.mark.parametrize('sd_cls', [SphericalDifferential,
SphericalCosLatDifferential])
@pytest.mark.parametrize('r_cls', (SphericalRepresentation,
UnitSphericalRepresentation,
PhysicsSphericalRepresentation,
CylindricalRepresentation))
def test_represent_regular_class(self, sd_cls, r_cls):
so = sd_cls(1.*u.deg, 2.*u.deg, 0.1*u.kpc)
r = so.represent_as(r_cls, base=self.s)
c = so.to_cartesian(self.s)
r_check = c.represent_as(r_cls)
assert np.all(representation_equal(r, r_check))
so2 = sd_cls.from_representation(r, base=self.s)
so3 = sd_cls.from_cartesian(r.to_cartesian(), self.s)
assert np.all(representation_equal(so2, so3))
@pytest.mark.parametrize('sd_cls', [SphericalDifferential,
SphericalCosLatDifferential])
def test_convert_physics(self, sd_cls):
# Conversion needs no base for SphericalDifferential, but does
# need one (to get the latitude) for SphericalCosLatDifferential.
if sd_cls is SphericalDifferential:
usd_cls = UnitSphericalDifferential
base_s = base_u = base_p = None
else:
usd_cls = UnitSphericalCosLatDifferential
base_s = self.s[1]
base_u = base_s.represent_as(UnitSphericalRepresentation)
base_p = base_s.represent_as(PhysicsSphericalRepresentation)
so = sd_cls(1.*u.deg, 2.*u.deg, 0.1*u.kpc)
po = so.represent_as(PhysicsSphericalDifferential, base=base_s)
so2 = sd_cls.from_representation(po, base=base_s)
assert_differential_allclose(so, so2)
po2 = PhysicsSphericalDifferential.from_representation(so, base=base_p)
assert_differential_allclose(po, po2)
so3 = po.represent_as(sd_cls, base=base_p)
assert_differential_allclose(so, so3)
s = self.s
p = s.represent_as(PhysicsSphericalRepresentation)
cso = so.to_cartesian(s[1])
cpo = po.to_cartesian(p[1])
assert_representation_allclose(cso, cpo)
assert_representation_allclose(s[1] + so, p[1] + po)
po2 = so.represent_as(PhysicsSphericalDifferential,
base=None if base_s is None else s)
assert_representation_allclose(s + so, p + po2)
suo = usd_cls.from_representation(so)
puo = usd_cls.from_representation(po, base=base_u)
assert_differential_allclose(suo, puo)
suo2 = so.represent_as(usd_cls)
puo2 = po.represent_as(usd_cls, base=base_p)
assert_differential_allclose(suo2, puo2)
assert_differential_allclose(puo, puo2)
sro = RadialDifferential.from_representation(so)
pro = RadialDifferential.from_representation(po)
assert representation_equal(sro, pro)
sro2 = so.represent_as(RadialDifferential)
pro2 = po.represent_as(RadialDifferential)
assert representation_equal(sro2, pro2)
assert representation_equal(pro, pro2)
@pytest.mark.parametrize(
('sd_cls', 'usd_cls'),
[(SphericalDifferential, UnitSphericalDifferential),
(SphericalCosLatDifferential, UnitSphericalCosLatDifferential)])
def test_convert_unit_spherical_radial(self, sd_cls, usd_cls):
s = self.s
us = s.represent_as(UnitSphericalRepresentation)
rs = s.represent_as(RadialRepresentation)
assert_representation_allclose(rs * us, s)
uo = usd_cls(2.*u.deg, 1.*u.deg)
so = uo.represent_as(sd_cls, base=s)
assert_quantity_allclose(so.d_distance, 0.*u.kpc, atol=1.*u.npc)
uo2 = so.represent_as(usd_cls)
assert_representation_allclose(uo.to_cartesian(us),
uo2.to_cartesian(us))
so1 = sd_cls(2.*u.deg, 1.*u.deg, 5.*u.pc)
uo_r = so1.represent_as(usd_cls)
ro_r = so1.represent_as(RadialDifferential)
assert np.all(representation_equal(uo_r, uo))
assert np.all(representation_equal(ro_r, RadialDifferential(5.*u.pc)))
@pytest.mark.parametrize('sd_cls', [SphericalDifferential,
SphericalCosLatDifferential])
def test_convert_cylindrial(self, sd_cls):
s = self.s
so = sd_cls(1.*u.deg, 2.*u.deg, 0.1*u.kpc)
cyo = so.represent_as(CylindricalDifferential, base=s)
cy = s.represent_as(CylindricalRepresentation)
so1 = cyo.represent_as(sd_cls, base=cy)
assert_representation_allclose(so.to_cartesian(s),
so1.to_cartesian(s))
cyo2 = CylindricalDifferential.from_representation(so, base=cy)
assert_representation_allclose(cyo2.to_cartesian(base=cy),
cyo.to_cartesian(base=cy))
so2 = sd_cls.from_representation(cyo2, base=s)
assert_representation_allclose(so.to_cartesian(s),
so2.to_cartesian(s))
@pytest.mark.parametrize('sd_cls', [SphericalDifferential,
SphericalCosLatDifferential])
def test_combinations(self, sd_cls):
if sd_cls is SphericalDifferential:
uo = UnitSphericalDifferential(2.*u.deg, 1.*u.deg)
uo_d_lon = uo.d_lon
else:
uo = UnitSphericalCosLatDifferential(2.*u.deg, 1.*u.deg)
uo_d_lon = uo.d_lon_coslat
ro = RadialDifferential(1.*u.mpc)
so1 = uo + ro
so1c = sd_cls(uo_d_lon, uo.d_lat, ro.d_distance)
assert np.all(representation_equal(so1, so1c))
so2 = uo - ro
so2c = sd_cls(uo_d_lon, uo.d_lat, -ro.d_distance)
assert np.all(representation_equal(so2, so2c))
so3 = so2 + ro
so3c = sd_cls(uo_d_lon, uo.d_lat, 0.*u.kpc)
assert np.all(representation_equal(so3, so3c))
so4 = so1 + ro
so4c = sd_cls(uo_d_lon, uo.d_lat, 2*ro.d_distance)
assert np.all(representation_equal(so4, so4c))
so5 = so1 - uo
so5c = sd_cls(0*u.deg, 0.*u.deg, ro.d_distance)
assert np.all(representation_equal(so5, so5c))
assert_representation_allclose(self.s + (uo+ro), self.s+so1)
@pytest.mark.parametrize('rep,dif', [
[CartesianRepresentation([1, 2, 3]*u.kpc),
CartesianDifferential([.1, .2, .3]*u.km/u.s)],
[SphericalRepresentation(90*u.deg, 0.*u.deg, 14.*u.kpc),
SphericalDifferential(1.*u.deg, 2.*u.deg, 0.1*u.kpc)]
])
def test_arithmetic_with_differentials_fail(rep, dif):
rep = rep.with_differentials(dif)
with pytest.raises(TypeError):
rep + rep
with pytest.raises(TypeError):
rep - rep
with pytest.raises(TypeError):
rep * rep
with pytest.raises(TypeError):
rep / rep
with pytest.raises(TypeError):
10. * rep
with pytest.raises(TypeError):
rep / 10.
with pytest.raises(TypeError):
-rep
|
0f6b94c9dcea14d7f9d67797418fe5c03f4a87b652124881a4deb4bb4165d7b9 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy import testing as npt
from ... import units as u
from ...time import Time
from ..builtin_frames import ICRS, AltAz
from ..builtin_frames.utils import get_jd12
from .. import EarthLocation
from .. import SkyCoord
from ...tests.helper import catch_warnings
from ... import _erfa as erfa
from ...utils import iers
from .utils import randomly_sample_sphere
# These fixtures are used in test_iau_fullstack
@pytest.fixture(scope="function")
def fullstack_icrs():
ra, dec, _ = randomly_sample_sphere(1000)
return ICRS(ra=ra, dec=dec)
@pytest.fixture(scope="function")
def fullstack_fiducial_altaz(fullstack_icrs):
altazframe = AltAz(location=EarthLocation(lat=0*u.deg, lon=0*u.deg, height=0*u.m),
obstime=Time('J2000'))
return fullstack_icrs.transform_to(altazframe)
@pytest.fixture(scope="function", params=['J2000.1', 'J2010'])
def fullstack_times(request):
return Time(request.param)
@pytest.fixture(scope="function", params=[(0, 0, 0), (23, 0, 0), (-70, 0, 0), (0, 100, 0), (23, 0, 3000)])
def fullstack_locations(request):
return EarthLocation(lat=request.param[0]*u.deg, lon=request.param[0]*u.deg,
height=request.param[0]*u.m)
@pytest.fixture(scope="function", params=[(0*u.bar, 0*u.deg_C, 0, 1*u.micron),
(1*u.bar, 0*u.deg_C, 0, 1*u.micron),
(1*u.bar, 10*u.deg_C, 0, 1*u.micron),
(1*u.bar, 0*u.deg_C, .5, 1*u.micron),
(1*u.bar, 0*u.deg_C, 0, 21*u.cm)])
def fullstack_obsconditions(request):
return request.param
def _erfa_check(ira, idec, astrom):
"""
This function does the same thing the astropy layer is supposed to do, but
all in erfa
"""
cra, cdec = erfa.atciq(ira, idec, 0, 0, 0, 0, astrom)
az, zen, ha, odec, ora = erfa.atioq(cra, cdec, astrom)
alt = np.pi/2-zen
cra2, cdec2 = erfa.atoiq('A', az, zen, astrom)
ira2, idec2 = erfa.aticq(cra2, cdec2, astrom)
dct = locals()
del dct['astrom']
return dct
def test_iau_fullstack(fullstack_icrs, fullstack_fiducial_altaz,
fullstack_times, fullstack_locations,
fullstack_obsconditions):
"""
Test the full transform from ICRS <-> AltAz
"""
# create the altaz frame
altazframe = AltAz(obstime=fullstack_times, location=fullstack_locations,
pressure=fullstack_obsconditions[0],
temperature=fullstack_obsconditions[1],
relative_humidity=fullstack_obsconditions[2],
obswl=fullstack_obsconditions[3])
aacoo = fullstack_icrs.transform_to(altazframe)
# compare aacoo to the fiducial AltAz - should always be different
assert np.all(np.abs(aacoo.alt - fullstack_fiducial_altaz.alt) > 50*u.milliarcsecond)
assert np.all(np.abs(aacoo.az - fullstack_fiducial_altaz.az) > 50*u.milliarcsecond)
# if the refraction correction is included, we *only* do the comparisons
# where altitude >5 degrees. The SOFA guides imply that below 5 is where
# where accuracy gets more problematic, and testing reveals that alt<~0
# gives garbage round-tripping, and <10 can give ~1 arcsec uncertainty
if fullstack_obsconditions[0].value == 0:
# but if there is no refraction correction, check everything
msk = slice(None)
tol = 5*u.microarcsecond
else:
msk = aacoo.alt > 5*u.deg
# most of them aren't this bad, but some of those at low alt are offset
# this much. For alt > 10, this is always better than 100 masec
tol = 750*u.milliarcsecond
# now make sure the full stack round-tripping works
icrs2 = aacoo.transform_to(ICRS)
adras = np.abs(fullstack_icrs.ra - icrs2.ra)[msk]
addecs = np.abs(fullstack_icrs.dec - icrs2.dec)[msk]
assert np.all(adras < tol), 'largest RA change is {0} mas, > {1}'.format(np.max(adras.arcsec*1000), tol)
assert np.all(addecs < tol), 'largest Dec change is {0} mas, > {1}'.format(np.max(addecs.arcsec*1000), tol)
# check that we're consistent with the ERFA alt/az result
xp, yp = u.Quantity(iers.IERS_Auto.open().pm_xy(fullstack_times)).to_value(u.radian)
lon = fullstack_locations.geodetic[0].to_value(u.radian)
lat = fullstack_locations.geodetic[1].to_value(u.radian)
height = fullstack_locations.geodetic[2].to_value(u.m)
jd1, jd2 = get_jd12(fullstack_times, 'utc')
astrom, eo = erfa.apco13(jd1, jd2,
fullstack_times.delta_ut1_utc,
lon, lat, height,
xp, yp,
fullstack_obsconditions[0].to_value(u.hPa),
fullstack_obsconditions[1].to_value(u.deg_C),
fullstack_obsconditions[2],
fullstack_obsconditions[3].to_value(u.micron))
erfadct = _erfa_check(fullstack_icrs.ra.rad, fullstack_icrs.dec.rad, astrom)
npt.assert_allclose(erfadct['alt'], aacoo.alt.radian, atol=1e-7)
npt.assert_allclose(erfadct['az'], aacoo.az.radian, atol=1e-7)
def test_fiducial_roudtrip(fullstack_icrs, fullstack_fiducial_altaz):
"""
Test the full transform from ICRS <-> AltAz
"""
aacoo = fullstack_icrs.transform_to(fullstack_fiducial_altaz)
# make sure the round-tripping works
icrs2 = aacoo.transform_to(ICRS)
npt.assert_allclose(fullstack_icrs.ra.deg, icrs2.ra.deg)
npt.assert_allclose(fullstack_icrs.dec.deg, icrs2.dec.deg)
def test_future_altaz():
"""
While this does test the full stack, it is mostly meant to check that a
warning is raised when attempting to get to AltAz in the future (beyond
IERS tables)
"""
from ...utils.exceptions import AstropyWarning
# this is an ugly hack to get the warning to show up even if it has already
# appeared
from ..builtin_frames import utils
if hasattr(utils, '__warningregistry__'):
utils.__warningregistry__.clear()
with catch_warnings() as found_warnings:
location = EarthLocation(lat=0*u.deg, lon=0*u.deg)
t = Time('J2161')
SkyCoord(1*u.deg, 2*u.deg).transform_to(AltAz(location=location, obstime=t))
# check that these message(s) appear among any other warnings. If tests are run with
# --remote-data then the IERS table will be an instance of IERS_Auto which is
# assured of being "fresh". In this case getting times outside the range of the
# table does not raise an exception. Only if using IERS_B (which happens without
# --remote-data, i.e. for all CI testing) do we expect another warning.
messages_to_find = ["Tried to get polar motions for times after IERS data is valid."]
if isinstance(iers.IERS_Auto.iers_table, iers.IERS_B):
messages_to_find.append("(some) times are outside of range covered by IERS table.")
messages_found = [False for _ in messages_to_find]
for w in found_warnings:
if issubclass(w.category, AstropyWarning):
for i, message_to_find in enumerate(messages_to_find):
if message_to_find in str(w.message):
messages_found[i] = True
assert all(messages_found)
|
08bcc472fc10c31d213095012dffa04caa0ef521b10368efcc406058904e932e | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test replacements for ERFA functions atciqz and aticq."""
from itertools import product
import pytest
from ...tests.helper import assert_quantity_allclose as assert_allclose
from ...time import Time
from ... import _erfa as erfa
from .utils import randomly_sample_sphere
from ..builtin_frames.utils import get_jd12, atciqz, aticq
times = [Time("2014-06-25T00:00"), Time(["2014-06-25T00:00", "2014-09-24"])]
ra, dec, _ = randomly_sample_sphere(2)
positions = ((ra[0], dec[0]), (ra, dec))
spacetimes = product(times, positions)
@pytest.mark.parametrize('st', spacetimes)
def test_atciqz_aticq(st):
"""Check replacements against erfa versions for consistency."""
t, pos = st
jd1, jd2 = get_jd12(t, 'tdb')
astrom, _ = erfa.apci13(jd1, jd2)
ra, dec = pos
ra = ra.value
dec = dec.value
assert_allclose(erfa.atciqz(ra, dec, astrom), atciqz(ra, dec, astrom))
assert_allclose(erfa.aticq(ra, dec, astrom), aticq(ra, dec, astrom))
|
4f9ca89869f712ba7dfcaf3453ac695bd4e4c5c561b3a5aa613190345aae156c | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from numpy.testing.utils import assert_allclose, assert_array_equal
from ... import units as u
from ..matrix_utilities import rotation_matrix, angle_axis
def test_rotation_matrix():
assert_array_equal(rotation_matrix(0*u.deg, 'x'), np.eye(3))
assert_allclose(rotation_matrix(90*u.deg, 'y'), [[0, 0, -1],
[0, 1, 0],
[1, 0, 0]], atol=1e-12)
assert_allclose(rotation_matrix(-90*u.deg, 'z'), [[0, -1, 0],
[1, 0, 0],
[0, 0, 1]], atol=1e-12)
assert_allclose(rotation_matrix(45*u.deg, 'x'),
rotation_matrix(45*u.deg, [1, 0, 0]))
assert_allclose(rotation_matrix(125*u.deg, 'y'),
rotation_matrix(125*u.deg, [0, 1, 0]))
assert_allclose(rotation_matrix(-30*u.deg, 'z'),
rotation_matrix(-30*u.deg, [0, 0, 1]))
assert_allclose(np.dot(rotation_matrix(180*u.deg, [1, 1, 0]), [1, 0, 0]),
[0, 1, 0], atol=1e-12)
# make sure it also works for very small angles
assert_allclose(rotation_matrix(0.000001*u.deg, 'x'),
rotation_matrix(0.000001*u.deg, [1, 0, 0]))
def test_angle_axis():
m1 = rotation_matrix(35*u.deg, 'x')
an1, ax1 = angle_axis(m1)
assert an1 - 35*u.deg < 1e-10*u.deg
assert_allclose(ax1, [1, 0, 0])
m2 = rotation_matrix(-89*u.deg, [1, 1, 0])
an2, ax2 = angle_axis(m2)
assert an2 - 89*u.deg < 1e-10*u.deg
assert_allclose(ax2, [-2**-0.5, -2**-0.5, 0])
|
b27fbbf0817de07cc49aceca8e47366d67344142e741989fd70b81c0103701a0 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Regression tests for coordinates-related bugs that don't have an obvious other
place to live
"""
import io
import pytest
import numpy as np
from ... import units as u
from .. import (AltAz, EarthLocation, SkyCoord, get_sun, ICRS, CIRS, ITRS,
GeocentricTrueEcliptic, Longitude, Latitude, GCRS, HCRS,
get_moon, FK4, FK4NoETerms, BaseCoordinateFrame,
QuantityAttribute, SphericalRepresentation,
UnitSphericalRepresentation, CartesianRepresentation)
from ..sites import get_builtin_sites
from ...time import Time
from ...utils import iers
from ...table import Table
from ...tests.helper import assert_quantity_allclose, catch_warnings, quantity_allclose
from .test_matching import HAS_SCIPY, OLDER_SCIPY
try:
import yaml # pylint: disable=W0611
HAS_YAML = True
except ImportError:
HAS_YAML = False
def test_regression_5085():
"""
PR #5085 was put in place to fix the following issue.
Issue: https://github.com/astropy/astropy/issues/5069
At root was the transformation of Ecliptic coordinates with
non-scalar times.
"""
times = Time(["2015-08-28 03:30", "2015-09-05 10:30", "2015-09-15 18:35"])
latitudes = Latitude([3.9807075, -5.00733806, 1.69539491]*u.deg)
longitudes = Longitude([311.79678613, 72.86626741, 199.58698226]*u.deg)
distances = u.Quantity([0.00243266, 0.0025424, 0.00271296]*u.au)
coo = GeocentricTrueEcliptic(lat=latitudes,
lon=longitudes,
distance=distances, equinox=times)
# expected result
ras = Longitude([310.50095400, 314.67109920, 319.56507428]*u.deg)
decs = Latitude([-18.25190443, -17.1556676, -15.71616522]*u.deg)
distances = u.Quantity([1.78309901, 1.710874, 1.61326649]*u.au)
expected_result = GCRS(ra=ras, dec=decs,
distance=distances, obstime="J2000").cartesian.xyz
actual_result = coo.transform_to(GCRS(obstime="J2000")).cartesian.xyz
assert_quantity_allclose(expected_result, actual_result)
def test_regression_3920():
"""
Issue: https://github.com/astropy/astropy/issues/3920
"""
loc = EarthLocation.from_geodetic(0*u.deg, 0*u.deg, 0)
time = Time('2010-1-1')
aa = AltAz(location=loc, obstime=time)
sc = SkyCoord(10*u.deg, 3*u.deg)
assert sc.transform_to(aa).shape == tuple()
# That part makes sense: the input is a scalar so the output is too
sc2 = SkyCoord(10*u.deg, 3*u.deg, 1*u.AU)
assert sc2.transform_to(aa).shape == tuple()
# in 3920 that assert fails, because the shape is (1,)
# check that the same behavior occurs even if transform is from low-level classes
icoo = ICRS(sc.data)
icoo2 = ICRS(sc2.data)
assert icoo.transform_to(aa).shape == tuple()
assert icoo2.transform_to(aa).shape == tuple()
def test_regression_3938():
"""
Issue: https://github.com/astropy/astropy/issues/3938
"""
# Set up list of targets - we don't use `from_name` here to avoid
# remote_data requirements, but it does the same thing
# vega = SkyCoord.from_name('Vega')
vega = SkyCoord(279.23473479*u.deg, 38.78368896*u.deg)
# capella = SkyCoord.from_name('Capella')
capella = SkyCoord(79.17232794*u.deg, 45.99799147*u.deg)
# sirius = SkyCoord.from_name('Sirius')
sirius = SkyCoord(101.28715533*u.deg, -16.71611586*u.deg)
targets = [vega, capella, sirius]
# Feed list of targets into SkyCoord
combined_coords = SkyCoord(targets)
# Set up AltAz frame
time = Time('2012-01-01 00:00:00')
location = EarthLocation('10d', '45d', 0)
aa = AltAz(location=location, obstime=time)
combined_coords.transform_to(aa)
# in 3938 the above yields ``UnitConversionError: '' (dimensionless) and 'pc' (length) are not convertible``
def test_regression_3998():
"""
Issue: https://github.com/astropy/astropy/issues/3998
"""
time = Time('2012-01-01 00:00:00')
assert time.isscalar
sun = get_sun(time)
assert sun.isscalar
# in 3998, the above yields False - `sun` is a length-1 vector
assert sun.obstime is time
def test_regression_4033():
"""
Issue: https://github.com/astropy/astropy/issues/4033
"""
# alb = SkyCoord.from_name('Albireo')
alb = SkyCoord(292.68033548*u.deg, 27.95968007*u.deg)
alb_wdist = SkyCoord(alb, distance=133*u.pc)
# de = SkyCoord.from_name('Deneb')
de = SkyCoord(310.35797975*u.deg, 45.28033881*u.deg)
de_wdist = SkyCoord(de, distance=802*u.pc)
aa = AltAz(location=EarthLocation(lat=45*u.deg, lon=0*u.deg), obstime='2010-1-1')
deaa = de.transform_to(aa)
albaa = alb.transform_to(aa)
alb_wdistaa = alb_wdist.transform_to(aa)
de_wdistaa = de_wdist.transform_to(aa)
# these work fine
sepnod = deaa.separation(albaa)
sepwd = deaa.separation(alb_wdistaa)
assert_quantity_allclose(sepnod, 22.2862*u.deg, rtol=1e-6)
assert_quantity_allclose(sepwd, 22.2862*u.deg, rtol=1e-6)
# parallax should be present when distance added
assert np.abs(sepnod - sepwd) > 1*u.marcsec
# in 4033, the following fail with a recursion error
assert_quantity_allclose(de_wdistaa.separation(alb_wdistaa), 22.2862*u.deg, rtol=1e-3)
assert_quantity_allclose(alb_wdistaa.separation(deaa), 22.2862*u.deg, rtol=1e-3)
@pytest.mark.skipif(not HAS_SCIPY, reason='No Scipy')
@pytest.mark.skipif(OLDER_SCIPY, reason='Scipy too old')
def test_regression_4082():
"""
Issue: https://github.com/astropy/astropy/issues/4082
"""
from .. import search_around_sky, search_around_3d
cat = SkyCoord([10.076, 10.00455], [18.54746, 18.54896], unit='deg')
search_around_sky(cat[0:1], cat, seplimit=u.arcsec * 60, storekdtree=False)
# in the issue, this raises a TypeError
# also check 3d for good measure, although it's not really affected by this bug directly
cat3d = SkyCoord([10.076, 10.00455]*u.deg, [18.54746, 18.54896]*u.deg, distance=[0.1, 1.5]*u.kpc)
search_around_3d(cat3d[0:1], cat3d, 1*u.kpc, storekdtree=False)
def test_regression_4210():
"""
Issue: https://github.com/astropy/astropy/issues/4210
Related PR with actual change: https://github.com/astropy/astropy/pull/4211
"""
crd = SkyCoord(0*u.deg, 0*u.deg, distance=1*u.AU)
ecl = crd.geocentrictrueecliptic
# bug was that "lambda", which at the time was the name of the geocentric
# ecliptic longitude, is a reserved keyword. So this just makes sure the
# new name is are all valid
ecl.lon
# and for good measure, check the other ecliptic systems are all the same
# names for their attributes
from ..builtin_frames import ecliptic
for frame_name in ecliptic.__all__:
eclcls = getattr(ecliptic, frame_name)
eclobj = eclcls(1*u.deg, 2*u.deg, 3*u.AU)
eclobj.lat
eclobj.lon
eclobj.distance
def test_regression_futuretimes_4302():
"""
Checks that an error is not raised for future times not covered by IERS
tables (at least in a simple transform like CIRS->ITRS that simply requires
the UTC<->UT1 conversion).
Relevant comment: https://github.com/astropy/astropy/pull/4302#discussion_r44836531
"""
from ...utils.exceptions import AstropyWarning
# this is an ugly hack to get the warning to show up even if it has already
# appeared
from ..builtin_frames import utils
if hasattr(utils, '__warningregistry__'):
utils.__warningregistry__.clear()
with catch_warnings() as found_warnings:
future_time = Time('2511-5-1')
c = CIRS(1*u.deg, 2*u.deg, obstime=future_time)
c.transform_to(ITRS(obstime=future_time))
if not isinstance(iers.IERS_Auto.iers_table, iers.IERS_Auto):
saw_iers_warnings = False
for w in found_warnings:
if issubclass(w.category, AstropyWarning):
if '(some) times are outside of range covered by IERS table' in str(w.message):
saw_iers_warnings = True
break
assert saw_iers_warnings, 'Never saw IERS warning'
def test_regression_4996():
# this part is the actual regression test
deltat = np.linspace(-12, 12, 1000)*u.hour
times = Time('2012-7-13 00:00:00') + deltat
suncoo = get_sun(times)
assert suncoo.shape == (len(times),)
# and this is an additional test to make sure more complex arrays work
times2 = Time('2012-7-13 00:00:00') + deltat.reshape(10, 20, 5)
suncoo2 = get_sun(times2)
assert suncoo2.shape == times2.shape
# this is intentionally not allclose - they should be *exactly* the same
assert np.all(suncoo.ra.ravel() == suncoo2.ra.ravel())
def test_regression_4293():
"""Really just an extra test on FK4 no e, after finding that the units
were not always taken correctly. This test is against explicitly doing
the transformations on pp170 of Explanatory Supplement to the Astronomical
Almanac (Seidelmann, 2005).
See https://github.com/astropy/astropy/pull/4293#issuecomment-234973086
"""
# Check all over sky, but avoiding poles (note that FK4 did not ignore
# e terms within 10∘ of the poles... see p170 of explan.supp.).
ra, dec = np.meshgrid(np.arange(0, 359, 45), np.arange(-80, 81, 40))
fk4 = FK4(ra.ravel() * u.deg, dec.ravel() * u.deg)
Dc = -0.065838*u.arcsec
Dd = +0.335299*u.arcsec
# Dc * tan(obliquity), as given on p.170
Dctano = -0.028553*u.arcsec
fk4noe_dec = (fk4.dec - (Dd*np.cos(fk4.ra) -
Dc*np.sin(fk4.ra))*np.sin(fk4.dec) -
Dctano*np.cos(fk4.dec))
fk4noe_ra = fk4.ra - (Dc*np.cos(fk4.ra) +
Dd*np.sin(fk4.ra)) / np.cos(fk4.dec)
fk4noe = fk4.transform_to(FK4NoETerms)
# Tolerance here just set to how well the coordinates match, which is much
# better than the claimed accuracy of <1 mas for this first-order in
# v_earth/c approximation.
# Interestingly, if one divides by np.cos(fk4noe_dec) in the ra correction,
# the match becomes good to 2 μas.
assert_quantity_allclose(fk4noe.ra, fk4noe_ra, atol=11.*u.uas, rtol=0)
assert_quantity_allclose(fk4noe.dec, fk4noe_dec, atol=3.*u.uas, rtol=0)
def test_regression_4926():
times = Time('2010-01-1') + np.arange(20)*u.day
green = get_builtin_sites()['greenwich']
# this is the regression test
moon = get_moon(times, green)
# this is an additional test to make sure the GCRS->ICRS transform works for complex shapes
moon.transform_to(ICRS())
# and some others to increase coverage of transforms
moon.transform_to(HCRS(obstime="J2000"))
moon.transform_to(HCRS(obstime=times))
def test_regression_5209():
"check that distances are not lost on SkyCoord init"
time = Time('2015-01-01')
moon = get_moon(time)
new_coord = SkyCoord([moon])
assert_quantity_allclose(new_coord[0].distance, moon.distance)
def test_regression_5133():
N = 1000
np.random.seed(12345)
lon = np.random.uniform(-10, 10, N) * u.deg
lat = np.random.uniform(50, 52, N) * u.deg
alt = np.random.uniform(0, 10., N) * u.km
time = Time('2010-1-1')
objects = EarthLocation.from_geodetic(lon, lat, height=alt)
itrs_coo = objects.get_itrs(time)
homes = [EarthLocation.from_geodetic(lon=-1 * u.deg, lat=52 * u.deg, height=h)
for h in (0, 1000, 10000)*u.km]
altaz_frames = [AltAz(obstime=time, location=h) for h in homes]
altaz_coos = [itrs_coo.transform_to(f) for f in altaz_frames]
# they should all be different
for coo in altaz_coos[1:]:
assert not quantity_allclose(coo.az, coo.az[0])
assert not quantity_allclose(coo.alt, coo.alt[0])
def test_itrs_vals_5133():
time = Time('2010-1-1')
el = EarthLocation.from_geodetic(lon=20*u.deg, lat=45*u.deg, height=0*u.km)
lons = [20, 30, 20]*u.deg
lats = [44, 45, 45]*u.deg
alts = [0, 0, 10]*u.km
coos = [EarthLocation.from_geodetic(lon, lat, height=alt).get_itrs(time)
for lon, lat, alt in zip(lons, lats, alts)]
aaf = AltAz(obstime=time, location=el)
aacs = [coo.transform_to(aaf) for coo in coos]
assert all([coo.isscalar for coo in aacs])
# the ~1 arcsec tolerance is b/c aberration makes it not exact
assert_quantity_allclose(aacs[0].az, 180*u.deg, atol=1*u.arcsec)
assert aacs[0].alt < 0*u.deg
assert aacs[0].distance > 50*u.km
# it should *not* actually be 90 degrees, b/c constant latitude is not
# straight east anywhere except the equator... but should be close-ish
assert_quantity_allclose(aacs[1].az, 90*u.deg, atol=5*u.deg)
assert aacs[1].alt < 0*u.deg
assert aacs[1].distance > 50*u.km
assert_quantity_allclose(aacs[2].alt, 90*u.deg, atol=1*u.arcsec)
assert_quantity_allclose(aacs[2].distance, 10*u.km)
def test_regression_simple_5133():
t = Time('J2010')
obj = EarthLocation(-1*u.deg, 52*u.deg, height=[100., 0.]*u.km)
home = EarthLocation(-1*u.deg, 52*u.deg, height=10.*u.km)
aa = obj.get_itrs(t).transform_to(AltAz(obstime=t, location=home))
# az is more-or-less undefined for straight up or down
assert_quantity_allclose(aa.alt, [90, -90]*u.deg, rtol=1e-5)
assert_quantity_allclose(aa.distance, [90, 10]*u.km)
def test_regression_5743():
sc = SkyCoord([5, 10], [20, 30], unit=u.deg,
obstime=['2017-01-01T00:00', '2017-01-01T00:10'])
assert sc[0].obstime.shape == tuple()
def test_regression_5889_5890():
# ensure we can represent all Representations and transform to ND frames
greenwich = EarthLocation(
*u.Quantity([3980608.90246817, -102.47522911, 4966861.27310067],
unit=u.m))
times = Time("2017-03-20T12:00:00") + np.linspace(-2, 2, 3)*u.hour
moon = get_moon(times, location=greenwich)
targets = SkyCoord([350.7*u.deg, 260.7*u.deg], [18.4*u.deg, 22.4*u.deg])
targs2d = targets[:, np.newaxis]
targs2d.transform_to(moon)
def test_regression_6236():
# sunpy changes its representation upon initialisation of a frame,
# including via `realize_frame`. Ensure this works.
class MyFrame(BaseCoordinateFrame):
default_representation = CartesianRepresentation
my_attr = QuantityAttribute(default=0, unit=u.m)
class MySpecialFrame(MyFrame):
def __init__(self, *args, **kwargs):
_rep_kwarg = kwargs.get('representation', None)
super().__init__(*args, **kwargs)
if not _rep_kwarg:
self.representation = self.default_representation
self._data = self.data.represent_as(self.representation)
rep1 = UnitSphericalRepresentation([0., 1]*u.deg, [2., 3.]*u.deg)
rep2 = SphericalRepresentation([10., 11]*u.deg, [12., 13.]*u.deg,
[14., 15.]*u.kpc)
mf1 = MyFrame(rep1, my_attr=1.*u.km)
mf2 = mf1.realize_frame(rep2)
# Normally, data is stored as is, but the representation gets set to a
# default, even if a different representation instance was passed in.
# realize_frame should do the same. Just in case, check attrs are passed.
assert mf1.data is rep1
assert mf2.data is rep2
assert mf1.representation is CartesianRepresentation
assert mf2.representation is CartesianRepresentation
assert mf2.my_attr == mf1.my_attr
# It should be independent of whether I set the reprensentation explicitly
mf3 = MyFrame(rep1, my_attr=1.*u.km, representation='unitspherical')
mf4 = mf3.realize_frame(rep2)
assert mf3.data is rep1
assert mf4.data is rep2
assert mf3.representation is UnitSphericalRepresentation
assert mf4.representation is CartesianRepresentation
assert mf4.my_attr == mf3.my_attr
# This should be enough to help sunpy, but just to be sure, a test
# even closer to what is done there, i.e., transform the representation.
msf1 = MySpecialFrame(rep1, my_attr=1.*u.km)
msf2 = msf1.realize_frame(rep2)
assert msf1.data is not rep1 # Gets transformed to Cartesian.
assert msf2.data is not rep2
assert type(msf1.data) is CartesianRepresentation
assert type(msf2.data) is CartesianRepresentation
assert msf1.representation is CartesianRepresentation
assert msf2.representation is CartesianRepresentation
assert msf2.my_attr == msf1.my_attr
# And finally a test where the input is not transformed.
msf3 = MySpecialFrame(rep1, my_attr=1.*u.km,
representation='unitspherical')
msf4 = msf3.realize_frame(rep2)
assert msf3.data is rep1
assert msf4.data is not rep2
assert msf3.representation is UnitSphericalRepresentation
assert msf4.representation is CartesianRepresentation
assert msf4.my_attr == msf3.my_attr
@pytest.mark.skipif(not HAS_SCIPY, reason='No Scipy')
@pytest.mark.skipif(OLDER_SCIPY, reason='Scipy too old')
def test_regression_6347():
sc1 = SkyCoord([1, 2]*u.deg, [3, 4]*u.deg)
sc2 = SkyCoord([1.1, 2.1]*u.deg, [3.1, 4.1]*u.deg)
sc0 = sc1[:0]
idx1_10, idx2_10, d2d_10, d3d_10 = sc1.search_around_sky(sc2, 10*u.arcmin)
idx1_1, idx2_1, d2d_1, d3d_1 = sc1.search_around_sky(sc2, 1*u.arcmin)
idx1_0, idx2_0, d2d_0, d3d_0 = sc0.search_around_sky(sc2, 10*u.arcmin)
assert len(d2d_10) == 2
assert len(d2d_0) == 0
assert type(d2d_0) is type(d2d_10)
assert len(d2d_1) == 0
assert type(d2d_1) is type(d2d_10)
@pytest.mark.skipif(not HAS_SCIPY, reason='No Scipy')
@pytest.mark.skipif(OLDER_SCIPY, reason='Scipy too old')
def test_regression_6347_3d():
sc1 = SkyCoord([1, 2]*u.deg, [3, 4]*u.deg, [5, 6]*u.kpc)
sc2 = SkyCoord([1, 2]*u.deg, [3, 4]*u.deg, [5.1, 6.1]*u.kpc)
sc0 = sc1[:0]
idx1_10, idx2_10, d2d_10, d3d_10 = sc1.search_around_3d(sc2, 500*u.pc)
idx1_1, idx2_1, d2d_1, d3d_1 = sc1.search_around_3d(sc2, 50*u.pc)
idx1_0, idx2_0, d2d_0, d3d_0 = sc0.search_around_3d(sc2, 500*u.pc)
assert len(d2d_10) > 0
assert len(d2d_0) == 0
assert type(d2d_0) is type(d2d_10)
assert len(d2d_1) == 0
assert type(d2d_1) is type(d2d_10)
def test_regression_6300():
"""Check that importing old frame attribute names from astropy.coordinates
still works. See comments at end of #6300
"""
from ...utils.exceptions import AstropyDeprecationWarning
from .. import CartesianRepresentation
from .. import (TimeFrameAttribute, QuantityFrameAttribute,
CartesianRepresentationFrameAttribute)
with catch_warnings() as found_warnings:
attr = TimeFrameAttribute(default=Time("J2000"))
for w in found_warnings:
if issubclass(w.category, AstropyDeprecationWarning):
break
else:
assert False, "Deprecation warning not raised"
with catch_warnings() as found_warnings:
attr = QuantityFrameAttribute(default=5*u.km)
for w in found_warnings:
if issubclass(w.category, AstropyDeprecationWarning):
break
else:
assert False, "Deprecation warning not raised"
with catch_warnings() as found_warnings:
attr = CartesianRepresentationFrameAttribute(
default=CartesianRepresentation([5,6,7]*u.kpc))
for w in found_warnings:
if issubclass(w.category, AstropyDeprecationWarning):
break
else:
assert False, "Deprecation warning not raised"
def test_gcrs_itrs_cartesian_repr():
# issue 6436: transformation failed if coordinate representation was
# Cartesian
gcrs = GCRS(CartesianRepresentation((859.07256, -4137.20368, 5295.56871),
unit='km'), representation='cartesian')
gcrs.transform_to(ITRS)
@pytest.mark.skipif('not HAS_YAML')
def test_regression_6446():
# this succeeds even before 6446:
sc1 = SkyCoord([1, 2], [3, 4], unit='deg')
t1 = Table([sc1])
sio1 = io.StringIO()
t1.write(sio1, format='ascii.ecsv')
# but this fails due to the 6446 bug
c1 = SkyCoord(1, 3, unit='deg')
c2 = SkyCoord(2, 4, unit='deg')
sc2 = SkyCoord([c1, c2])
t2 = Table([sc2])
sio2 = io.StringIO()
t2.write(sio2, format='ascii.ecsv')
assert sio1.getvalue() == sio2.getvalue()
def test_regression_6448():
"""
This tests the more narrow problem reported in 6446 that 6448 is meant to
fix. `test_regression_6446` also covers this, but this test is provided
so that this is still tested even if YAML isn't installed.
"""
sc1 = SkyCoord([1, 2], [3, 4], unit='deg')
# this should always succeed even prior to 6448
assert sc1.galcen_v_sun is None
c1 = SkyCoord(1, 3, unit='deg')
c2 = SkyCoord(2, 4, unit='deg')
sc2 = SkyCoord([c1, c2])
# without 6448 this fails
assert sc2.galcen_v_sun is None
def test_regression_6597():
frame_name = 'galactic'
c1 = SkyCoord(1, 3, unit='deg', frame=frame_name)
c2 = SkyCoord(2, 4, unit='deg', frame=frame_name)
sc1 = SkyCoord([c1, c2])
assert sc1.frame.name == frame_name
def test_regression_6597_2():
"""
This tests the more subtle flaw that #6597 indirectly uncovered: that even
in the case that the frames are ra/dec, they still might be the wrong *kind*
"""
frame = FK4(equinox='J1949')
c1 = SkyCoord(1, 3, unit='deg', frame=frame)
c2 = SkyCoord(2, 4, unit='deg', frame=frame)
sc1 = SkyCoord([c1, c2])
assert sc1.frame.name == frame.name
def test_regression_6697():
"""
Test for regression of a bug in get_gcrs_posvel that introduced errors at the 1m/s level.
Comparison data is derived from calculation in PINT
https://github.com/nanograv/PINT/blob/master/pint/erfautils.py
"""
pint_vels = CartesianRepresentation(*(348.63632871, -212.31704928, -0.60154936), unit=u.m/u.s)
location = EarthLocation(*(5327448.9957829, -1718665.73869569, 3051566.90295403), unit=u.m)
t = Time(2458036.161966612, format='jd', scale='utc')
obsgeopos, obsgeovel = location.get_gcrs_posvel(t)
delta = (obsgeovel-pint_vels).norm()
assert delta < 1*u.cm/u.s
|
ba45bafc4ccf56d43bafb9e366abbb703dca6c48a9f3f7e6f3f40aab17a96105 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy import testing as npt
from ...tests.helper import assert_quantity_allclose as assert_allclose
from ... import units as u
from ...utils import minversion
from .. import matching
"""
These are the tests for coordinate matching.
Note that this requires scipy.
"""
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
if HAS_SCIPY and minversion(scipy, '0.12.0', inclusive=False):
OLDER_SCIPY = False
else:
OLDER_SCIPY = True
@pytest.mark.skipif(str('not HAS_SCIPY'))
def test_matching_function():
from .. import ICRS
from ..matching import match_coordinates_3d
# this only uses match_coordinates_3d because that's the actual implementation
cmatch = ICRS([4, 2.1]*u.degree, [0, 0]*u.degree)
ccatalog = ICRS([1, 2, 3, 4]*u.degree, [0, 0, 0, 0]*u.degree)
idx, d2d, d3d = match_coordinates_3d(cmatch, ccatalog)
npt.assert_array_equal(idx, [3, 1])
npt.assert_array_almost_equal(d2d.degree, [0, 0.1])
assert d3d.value[0] == 0
idx, d2d, d3d = match_coordinates_3d(cmatch, ccatalog, nthneighbor=2)
assert np.all(idx == 2)
npt.assert_array_almost_equal(d2d.degree, [1, 0.9])
npt.assert_array_less(d3d.value, 0.02)
@pytest.mark.skipif(str('not HAS_SCIPY'))
def test_matching_function_3d_and_sky():
from .. import ICRS
from ..matching import match_coordinates_3d, match_coordinates_sky
cmatch = ICRS([4, 2.1]*u.degree, [0, 0]*u.degree, distance=[1, 5] * u.kpc)
ccatalog = ICRS([1, 2, 3, 4]*u.degree, [0, 0, 0, 0]*u.degree, distance=[1, 1, 1, 5] * u.kpc)
idx, d2d, d3d = match_coordinates_3d(cmatch, ccatalog)
npt.assert_array_equal(idx, [2, 3])
assert_allclose(d2d, [1, 1.9] * u.deg)
assert np.abs(d3d[0].to_value(u.kpc) - np.radians(1)) < 1e-6
assert np.abs(d3d[1].to_value(u.kpc) - 5*np.radians(1.9)) < 1e-5
idx, d2d, d3d = match_coordinates_sky(cmatch, ccatalog)
npt.assert_array_equal(idx, [3, 1])
assert_allclose(d2d, [0, 0.1] * u.deg)
assert_allclose(d3d, [4, 4.0000019] * u.kpc)
@pytest.mark.parametrize('functocheck, args, defaultkdtname, bothsaved',
[(matching.match_coordinates_3d, [], 'kdtree_3d', False),
(matching.match_coordinates_sky, [], 'kdtree_sky', False),
(matching.search_around_3d, [1*u.kpc], 'kdtree_3d', True),
(matching.search_around_sky, [1*u.deg], 'kdtree_sky', False)
])
@pytest.mark.skipif(str('not HAS_SCIPY'))
def test_kdtree_storage(functocheck, args, defaultkdtname, bothsaved):
from .. import ICRS
def make_scs():
cmatch = ICRS([4, 2.1]*u.degree, [0, 0]*u.degree, distance=[1, 2]*u.kpc)
ccatalog = ICRS([1, 2, 3, 4]*u.degree, [0, 0, 0, 0]*u.degree, distance=[1, 2, 3, 4]*u.kpc)
return cmatch, ccatalog
cmatch, ccatalog = make_scs()
functocheck(cmatch, ccatalog, *args, storekdtree=False)
assert 'kdtree' not in ccatalog.cache
assert defaultkdtname not in ccatalog.cache
cmatch, ccatalog = make_scs()
functocheck(cmatch, ccatalog, *args)
assert defaultkdtname in ccatalog.cache
assert 'kdtree' not in ccatalog.cache
cmatch, ccatalog = make_scs()
functocheck(cmatch, ccatalog, *args, storekdtree=True)
assert 'kdtree' in ccatalog.cache
assert defaultkdtname not in ccatalog.cache
cmatch, ccatalog = make_scs()
assert 'tislit_cheese' not in ccatalog.cache
functocheck(cmatch, ccatalog, *args, storekdtree='tislit_cheese')
assert 'tislit_cheese' in ccatalog.cache
assert defaultkdtname not in ccatalog.cache
assert 'kdtree' not in ccatalog.cache
if bothsaved:
assert 'tislit_cheese' in cmatch.cache
assert defaultkdtname not in cmatch.cache
assert 'kdtree' not in cmatch.cache
else:
assert 'tislit_cheese' not in cmatch.cache
# now a bit of a hacky trick to make sure it at least tries to *use* it
ccatalog.cache['tislit_cheese'] = 1
cmatch.cache['tislit_cheese'] = 1
with pytest.raises(TypeError) as e:
functocheck(cmatch, ccatalog, *args, storekdtree='tislit_cheese')
assert 'KD' in e.value.args[0]
@pytest.mark.skipif(str('not HAS_SCIPY'))
def test_matching_method():
from .. import ICRS, SkyCoord
from ...utils import NumpyRNGContext
from ..matching import match_coordinates_3d, match_coordinates_sky
with NumpyRNGContext(987654321):
cmatch = ICRS(np.random.rand(20) * 360.*u.degree,
(np.random.rand(20) * 180. - 90.)*u.degree)
ccatalog = ICRS(np.random.rand(100) * 360. * u.degree,
(np.random.rand(100) * 180. - 90.)*u.degree)
idx1, d2d1, d3d1 = SkyCoord(cmatch).match_to_catalog_3d(ccatalog)
idx2, d2d2, d3d2 = match_coordinates_3d(cmatch, ccatalog)
npt.assert_array_equal(idx1, idx2)
assert_allclose(d2d1, d2d2)
assert_allclose(d3d1, d3d2)
# should be the same as above because there's no distance, but just make sure this method works
idx1, d2d1, d3d1 = SkyCoord(cmatch).match_to_catalog_sky(ccatalog)
idx2, d2d2, d3d2 = match_coordinates_sky(cmatch, ccatalog)
npt.assert_array_equal(idx1, idx2)
assert_allclose(d2d1, d2d2)
assert_allclose(d3d1, d3d2)
assert len(idx1) == len(d2d1) == len(d3d1) == 20
@pytest.mark.skipif(str('not HAS_SCIPY'))
@pytest.mark.skipif(str('OLDER_SCIPY'))
def test_search_around():
from .. import ICRS, SkyCoord
from ..matching import search_around_sky, search_around_3d
coo1 = ICRS([4, 2.1]*u.degree, [0, 0]*u.degree, distance=[1, 5] * u.kpc)
coo2 = ICRS([1, 2, 3, 4]*u.degree, [0, 0, 0, 0]*u.degree, distance=[1, 1, 1, 5] * u.kpc)
idx1_1deg, idx2_1deg, d2d_1deg, d3d_1deg = search_around_sky(coo1, coo2, 1.01*u.deg)
idx1_0p05deg, idx2_0p05deg, d2d_0p05deg, d3d_0p05deg = search_around_sky(coo1, coo2, 0.05*u.deg)
assert list(zip(idx1_1deg, idx2_1deg)) == [(0, 2), (0, 3), (1, 1), (1, 2)]
assert d2d_1deg[0] == 1.0*u.deg
assert_allclose(d2d_1deg, [1, 0, .1, .9]*u.deg)
assert list(zip(idx1_0p05deg, idx2_0p05deg)) == [(0, 3)]
idx1_1kpc, idx2_1kpc, d2d_1kpc, d3d_1kpc = search_around_3d(coo1, coo2, 1*u.kpc)
idx1_sm, idx2_sm, d2d_sm, d3d_sm = search_around_3d(coo1, coo2, 0.05*u.kpc)
assert list(zip(idx1_1kpc, idx2_1kpc)) == [(0, 0), (0, 1), (0, 2), (1, 3)]
assert list(zip(idx1_sm, idx2_sm)) == [(0, 1), (0, 2)]
assert_allclose(d2d_sm, [2, 1]*u.deg)
# Test for the non-matches, #4877
coo1 = ICRS([4.1, 2.1]*u.degree, [0, 0]*u.degree, distance=[1, 5] * u.kpc)
idx1, idx2, d2d, d3d = search_around_sky(coo1, coo2, 1*u.arcsec)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
idx1, idx2, d2d, d3d = search_around_3d(coo1, coo2, 1*u.m)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
# Test when one or both of the coordinate arrays is empty, #4875
empty = ICRS(ra=[] * u.degree, dec=[] * u.degree, distance=[] * u.kpc)
idx1, idx2, d2d, d3d = search_around_sky(empty, coo2, 1*u.arcsec)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
idx1, idx2, d2d, d3d = search_around_sky(coo1, empty, 1*u.arcsec)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
empty = ICRS(ra=[] * u.degree, dec=[] * u.degree, distance=[] * u.kpc)
idx1, idx2, d2d, d3d = search_around_sky(empty, empty[:], 1*u.arcsec)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
idx1, idx2, d2d, d3d = search_around_3d(empty, coo2, 1*u.m)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
idx1, idx2, d2d, d3d = search_around_3d(coo1, empty, 1*u.m)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
idx1, idx2, d2d, d3d = search_around_3d(empty, empty[:], 1*u.m)
assert idx1.size == idx2.size == d2d.size == d3d.size == 0
assert idx1.dtype == idx2.dtype == np.int
assert d2d.unit == u.deg
assert d3d.unit == u.kpc
# Test that input without distance units results in a
# 'dimensionless_unscaled' unit
cempty = SkyCoord(ra=[], dec=[], unit=u.deg)
idx1, idx2, d2d, d3d = search_around_3d(cempty, cempty[:], 1*u.m)
assert d2d.unit == u.deg
assert d3d.unit == u.dimensionless_unscaled
idx1, idx2, d2d, d3d = search_around_sky(cempty, cempty[:], 1*u.m)
assert d2d.unit == u.deg
assert d3d.unit == u.dimensionless_unscaled
@pytest.mark.skipif(str('not HAS_SCIPY'))
@pytest.mark.skipif(str('OLDER_SCIPY'))
def test_search_around_scalar():
from astropy.coordinates import SkyCoord, Angle
cat = SkyCoord([1, 2, 3], [-30, 45, 8], unit="deg")
target = SkyCoord('1.1 -30.1', unit="deg")
with pytest.raises(ValueError) as excinfo:
cat.search_around_sky(target, Angle('2d'))
# make sure the error message is *specific* to search_around_sky rather than
# generic as reported in #3359
assert 'search_around_sky' in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
cat.search_around_3d(target, Angle('2d'))
assert 'search_around_3d' in str(excinfo.value)
@pytest.mark.skipif(str('not HAS_SCIPY'))
@pytest.mark.skipif(str('OLDER_SCIPY'))
def test_match_catalog_empty():
from astropy.coordinates import SkyCoord
sc1 = SkyCoord(1, 2, unit="deg")
cat0 = SkyCoord([], [], unit="deg")
cat1 = SkyCoord([1.1], [2.1], unit="deg")
cat2 = SkyCoord([1.1, 3], [2.1, 5], unit="deg")
sc1.match_to_catalog_sky(cat2)
sc1.match_to_catalog_3d(cat2)
sc1.match_to_catalog_sky(cat1)
sc1.match_to_catalog_3d(cat1)
with pytest.raises(ValueError) as excinfo:
sc1.match_to_catalog_sky(cat1[0])
assert 'catalog' in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sc1.match_to_catalog_3d(cat1[0])
assert 'catalog' in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sc1.match_to_catalog_sky(cat0)
assert 'catalog' in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sc1.match_to_catalog_3d(cat0)
assert 'catalog' in str(excinfo.value)
|
2389f5ccb5c06258cebb58423a88694d99e0f394ab9729b4cd16cc3538015084 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy import testing as npt
from ... import units as u
from ...time import Time
from ...tests.helper import assert_quantity_allclose as assert_allclose
from .. import (Angle, ICRS, FK4, FK5, Galactic, SkyCoord,
CartesianRepresentation)
from ..angle_utilities import dms_to_degrees, hms_to_hours
def test_angle_arrays():
"""
Test arrays values with Angle objects.
"""
# Tests incomplete
a1 = Angle([0, 45, 90, 180, 270, 360, 720.], unit=u.degree)
npt.assert_almost_equal([0., 45., 90., 180., 270., 360., 720.], a1.value)
a2 = Angle(np.array([-90, -45, 0, 45, 90, 180, 270, 360]), unit=u.degree)
npt.assert_almost_equal([-90, -45, 0, 45, 90, 180, 270, 360],
a2.value)
a3 = Angle(["12 degrees", "3 hours", "5 deg", "4rad"])
npt.assert_almost_equal([12., 45., 5., 229.18311805],
a3.value)
assert a3.unit == u.degree
a4 = Angle(["12 degrees", "3 hours", "5 deg", "4rad"], u.radian)
npt.assert_almost_equal(a4.degree, a3.value)
assert a4.unit == u.radian
a5 = Angle([0, 45, 90, 180, 270, 360], unit=u.degree)
a6 = a5.sum()
npt.assert_almost_equal(a6.value, 945.0)
assert a6.unit is u.degree
with pytest.raises(TypeError):
# Arrays where the elements are Angle objects are not supported -- it's
# really tricky to do correctly, if at all, due to the possibility of
# nesting.
a7 = Angle([a1, a2, a3], unit=u.degree)
a8 = Angle(["04:02:02", "03:02:01", "06:02:01"], unit=u.degree)
npt.assert_almost_equal(a8.value, [4.03388889, 3.03361111, 6.03361111])
a9 = Angle(np.array(["04:02:02", "03:02:01", "06:02:01"]), unit=u.degree)
npt.assert_almost_equal(a9.value, a8.value)
with pytest.raises(u.UnitsError):
a10 = Angle(["04:02:02", "03:02:01", "06:02:01"])
def test_dms():
a1 = Angle([0, 45.5, -45.5], unit=u.degree)
d, m, s = a1.dms
npt.assert_almost_equal(d, [0, 45, -45])
npt.assert_almost_equal(m, [0, 30, -30])
npt.assert_almost_equal(s, [0, 0, -0])
dms = a1.dms
degrees = dms_to_degrees(*dms)
npt.assert_almost_equal(a1.degree, degrees)
a2 = Angle(dms, unit=u.degree)
npt.assert_almost_equal(a2.radian, a1.radian)
def test_hms():
a1 = Angle([0, 11.5, -11.5], unit=u.hour)
h, m, s = a1.hms
npt.assert_almost_equal(h, [0, 11, -11])
npt.assert_almost_equal(m, [0, 30, -30])
npt.assert_almost_equal(s, [0, 0, -0])
hms = a1.hms
hours = hms_to_hours(*hms)
npt.assert_almost_equal(a1.hour, hours)
a2 = Angle(hms, unit=u.hour)
npt.assert_almost_equal(a2.radian, a1.radian)
def test_array_coordinates_creation():
"""
Test creating coordinates from arrays.
"""
c = ICRS(np.array([1, 2])*u.deg, np.array([3, 4])*u.deg)
assert not c.ra.isscalar
with pytest.raises(ValueError):
c = ICRS(np.array([1, 2])*u.deg, np.array([3, 4, 5])*u.deg)
with pytest.raises(ValueError):
c = ICRS(np.array([1, 2, 4, 5])*u.deg, np.array([[3, 4], [5, 6]])*u.deg)
# make sure cartesian initialization also works
cart = CartesianRepresentation(x=[1., 2.]*u.kpc, y=[3., 4.]*u.kpc, z=[5., 6.]*u.kpc)
c = ICRS(cart)
# also ensure strings can be arrays
c = SkyCoord(['1d0m0s', '2h02m00.3s'], ['3d', '4d'])
# but invalid strings cannot
with pytest.raises(ValueError):
c = SkyCoord(Angle(['10m0s', '2h02m00.3s']), Angle(['3d', '4d']))
with pytest.raises(ValueError):
c = SkyCoord(Angle(['1d0m0s', '2h02m00.3s']), Angle(['3x', '4d']))
def test_array_coordinates_distances():
"""
Test creating coordinates from arrays and distances.
"""
# correct way
ICRS(ra=np.array([1, 2])*u.deg, dec=np.array([3, 4])*u.deg, distance=[.1, .2] * u.kpc)
with pytest.raises(ValueError):
# scalar distance and mismatched array coordinates
ICRS(ra=np.array([1, 2, 3])*u.deg, dec=np.array([[3, 4], [5, 6]])*u.deg, distance=2. * u.kpc)
with pytest.raises(ValueError):
# more distance values than coordinates
ICRS(ra=np.array([1, 2])*u.deg, dec=np.array([3, 4])*u.deg, distance=[.1, .2, 3.] * u.kpc)
@pytest.mark.parametrize(('arrshape', 'distance'), [((2, ), None), ((4, 2, 5), None), ((4, 2, 5), 2 * u.kpc)])
def test_array_coordinates_transformations(arrshape, distance):
"""
Test transformation on coordinates with array content (first length-2 1D, then a 3D array)
"""
# M31 coordinates from test_transformations
raarr = np.ones(arrshape) * 10.6847929
decarr = np.ones(arrshape) * 41.2690650
if distance is not None:
distance = np.ones(arrshape) * distance
print(raarr, decarr, distance)
c = ICRS(ra=raarr*u.deg, dec=decarr*u.deg, distance=distance)
g = c.transform_to(Galactic)
assert g.l.shape == arrshape
npt.assert_array_almost_equal(g.l.degree, 121.17440967)
npt.assert_array_almost_equal(g.b.degree, -21.57299631)
if distance is not None:
assert g.distance.unit == c.distance.unit
# now make sure round-tripping works through FK5
c2 = c.transform_to(FK5).transform_to(ICRS)
npt.assert_array_almost_equal(c.ra.radian, c2.ra.radian)
npt.assert_array_almost_equal(c.dec.radian, c2.dec.radian)
assert c2.ra.shape == arrshape
if distance is not None:
assert c2.distance.unit == c.distance.unit
# also make sure it's possible to get to FK4, which uses a direct transform function.
fk4 = c.transform_to(FK4)
npt.assert_array_almost_equal(fk4.ra.degree, 10.0004, decimal=4)
npt.assert_array_almost_equal(fk4.dec.degree, 40.9953, decimal=4)
assert fk4.ra.shape == arrshape
if distance is not None:
assert fk4.distance.unit == c.distance.unit
# now check the reverse transforms run
cfk4 = fk4.transform_to(ICRS)
assert cfk4.ra.shape == arrshape
def test_array_precession():
"""
Ensures that FK5 coordinates as arrays precess their equinoxes
"""
j2000 = Time('J2000', scale='utc')
j1975 = Time('J1975', scale='utc')
fk5 = FK5([1, 1.1]*u.radian, [0.5, 0.6]*u.radian)
assert fk5.equinox.jyear == j2000.jyear
fk5_2 = fk5.transform_to(FK5(equinox=j1975))
assert fk5_2.equinox.jyear == j1975.jyear
npt.assert_array_less(0.05, np.abs(fk5.ra.degree - fk5_2.ra.degree))
npt.assert_array_less(0.05, np.abs(fk5.dec.degree - fk5_2.dec.degree))
def test_array_separation():
c1 = ICRS([0, 0]*u.deg, [0, 0]*u.deg)
c2 = ICRS([1, 2]*u.deg, [0, 0]*u.deg)
npt.assert_array_almost_equal(c1.separation(c2).degree, [1, 2])
c3 = ICRS([0, 3.]*u.deg, [0., 0]*u.deg, distance=[1, 1.] * u.kpc)
c4 = ICRS([1, 1.]*u.deg, [0., 0]*u.deg, distance=[1, 1.] * u.kpc)
# the 3-1 separation should be twice the 0-1 separation, but not *exactly* the same
sep = c3.separation_3d(c4)
sepdiff = sep[1] - (2 * sep[0])
assert abs(sepdiff.value) < 1e-5
assert sepdiff != 0
def test_array_indexing():
ra = np.linspace(0, 360, 10)
dec = np.linspace(-90, 90, 10)
j1975 = Time(1975, format='jyear', scale='utc')
c1 = FK5(ra*u.deg, dec*u.deg, equinox=j1975)
c2 = c1[4]
assert c2.ra.degree == 160
assert c2.dec.degree == -10
c3 = c1[2:5]
assert_allclose(c3.ra, [80, 120, 160] * u.deg)
assert_allclose(c3.dec, [-50, -30, -10] * u.deg)
c4 = c1[np.array([2, 5, 8])]
assert_allclose(c4.ra, [80, 200, 320] * u.deg)
assert_allclose(c4.dec, [-50, 10, 70] * u.deg)
# now make sure the equinox is preserved
assert c2.equinox == c1.equinox
assert c3.equinox == c1.equinox
assert c4.equinox == c1.equinox
def test_array_len():
input_length = [1, 5]
for length in input_length:
ra = np.linspace(0, 360, length)
dec = np.linspace(0, 90, length)
c = ICRS(ra*u.deg, dec*u.deg)
assert len(c) == length
assert c.shape == (length,)
with pytest.raises(TypeError):
c = ICRS(0*u.deg, 0*u.deg)
len(c)
assert c.shape == tuple()
def test_array_eq():
c1 = ICRS([1, 2]*u.deg, [3, 4]*u.deg)
c2 = ICRS([1, 2]*u.deg, [3, 5]*u.deg)
c3 = ICRS([1, 3]*u.deg, [3, 4]*u.deg)
c4 = ICRS([1, 2]*u.deg, [3, 4.2]*u.deg)
assert c1 == c1
assert c1 != c2
assert c1 != c3
assert c1 != c4
|
0b2d441c99eeacd31bddfcb69b6f036c43c6393ece163a19b7ab885531225043 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from copy import deepcopy
from collections import OrderedDict
import pytest
import numpy as np
from numpy.testing import assert_allclose
from ... import units as u
from ...tests.helper import (assert_quantity_allclose as
assert_allclose_quantity, catch_warnings)
from ...utils import isiterable
from ...utils.compat import NUMPY_LT_1_14
from ...utils.exceptions import AstropyDeprecationWarning
from ..angles import Longitude, Latitude, Angle
from ..distances import Distance
from ..representation import (REPRESENTATION_CLASSES,
DIFFERENTIAL_CLASSES,
BaseRepresentation,
SphericalRepresentation,
UnitSphericalRepresentation,
SphericalCosLatDifferential,
CartesianRepresentation,
CylindricalRepresentation,
PhysicsSphericalRepresentation,
CartesianDifferential,
SphericalDifferential,
_combine_xyz)
# Preserve the original REPRESENTATION_CLASSES dict so that importing
# the test file doesn't add a persistent test subclass (LogDRepresentation)
def setup_function(func):
func.REPRESENTATION_CLASSES_ORIG = deepcopy(REPRESENTATION_CLASSES)
def teardown_function(func):
REPRESENTATION_CLASSES.clear()
REPRESENTATION_CLASSES.update(func.REPRESENTATION_CLASSES_ORIG)
class TestSphericalRepresentation:
def test_name(self):
assert SphericalRepresentation.get_name() == 'spherical'
assert SphericalRepresentation.get_name() in REPRESENTATION_CLASSES
def test_empty_init(self):
with pytest.raises(TypeError) as exc:
s = SphericalRepresentation()
def test_init_quantity(self):
s3 = SphericalRepresentation(lon=8 * u.hourangle, lat=5 * u.deg, distance=10 * u.kpc)
assert s3.lon == 8. * u.hourangle
assert s3.lat == 5. * u.deg
assert s3.distance == 10 * u.kpc
assert isinstance(s3.lon, Longitude)
assert isinstance(s3.lat, Latitude)
assert isinstance(s3.distance, Distance)
def test_init_lonlat(self):
s2 = SphericalRepresentation(Longitude(8, u.hour),
Latitude(5, u.deg),
Distance(10, u.kpc))
assert s2.lon == 8. * u.hourangle
assert s2.lat == 5. * u.deg
assert s2.distance == 10. * u.kpc
assert isinstance(s2.lon, Longitude)
assert isinstance(s2.lat, Latitude)
assert isinstance(s2.distance, Distance)
# also test that wrap_angle is preserved
s3 = SphericalRepresentation(Longitude(-90, u.degree,
wrap_angle=180*u.degree),
Latitude(-45, u.degree),
Distance(1., u.Rsun))
assert s3.lon == -90. * u.degree
assert s3.lon.wrap_angle == 180 * u.degree
def test_init_array(self):
s1 = SphericalRepresentation(lon=[8, 9] * u.hourangle,
lat=[5, 6] * u.deg,
distance=[1, 2] * u.kpc)
assert_allclose(s1.lon.degree, [120, 135])
assert_allclose(s1.lat.degree, [5, 6])
assert_allclose(s1.distance.kpc, [1, 2])
assert isinstance(s1.lon, Longitude)
assert isinstance(s1.lat, Latitude)
assert isinstance(s1.distance, Distance)
def test_init_array_nocopy(self):
lon = Longitude([8, 9] * u.hourangle)
lat = Latitude([5, 6] * u.deg)
distance = Distance([1, 2] * u.kpc)
s1 = SphericalRepresentation(lon=lon, lat=lat, distance=distance, copy=False)
lon[:] = [1, 2] * u.rad
lat[:] = [3, 4] * u.arcmin
distance[:] = [8, 9] * u.Mpc
assert_allclose_quantity(lon, s1.lon)
assert_allclose_quantity(lat, s1.lat)
assert_allclose_quantity(distance, s1.distance)
def test_init_float32_array(self):
"""Regression test against #2983"""
lon = Longitude(np.float32([1., 2.]), u.degree)
lat = Latitude(np.float32([3., 4.]), u.degree)
s1 = UnitSphericalRepresentation(lon=lon, lat=lat, copy=False)
assert s1.lon.dtype == np.float32
assert s1.lat.dtype == np.float32
assert s1._values['lon'].dtype == np.float32
assert s1._values['lat'].dtype == np.float32
def test_reprobj(self):
s1 = SphericalRepresentation(lon=8 * u.hourangle, lat=5 * u.deg, distance=10 * u.kpc)
s2 = SphericalRepresentation.from_representation(s1)
assert_allclose_quantity(s2.lon, 8. * u.hourangle)
assert_allclose_quantity(s2.lat, 5. * u.deg)
assert_allclose_quantity(s2.distance, 10 * u.kpc)
def test_broadcasting(self):
s1 = SphericalRepresentation(lon=[8, 9] * u.hourangle,
lat=[5, 6] * u.deg,
distance=10 * u.kpc)
assert_allclose_quantity(s1.lon, [120, 135] * u.degree)
assert_allclose_quantity(s1.lat, [5, 6] * u.degree)
assert_allclose_quantity(s1.distance, [10, 10] * u.kpc)
def test_broadcasting_mismatch(self):
with pytest.raises(ValueError) as exc:
s1 = SphericalRepresentation(lon=[8, 9, 10] * u.hourangle,
lat=[5, 6] * u.deg,
distance=[1, 2] * u.kpc)
assert exc.value.args[0] == "Input parameters lon, lat, and distance cannot be broadcast"
def test_readonly(self):
s1 = SphericalRepresentation(lon=8 * u.hourangle,
lat=5 * u.deg,
distance=1. * u.kpc)
with pytest.raises(AttributeError):
s1.lon = 1. * u.deg
with pytest.raises(AttributeError):
s1.lat = 1. * u.deg
with pytest.raises(AttributeError):
s1.distance = 1. * u.kpc
def test_getitem_len_iterable(self):
s = SphericalRepresentation(lon=np.arange(10) * u.deg,
lat=-np.arange(10) * u.deg,
distance=1 * u.kpc)
s_slc = s[2:8:2]
assert_allclose_quantity(s_slc.lon, [2, 4, 6] * u.deg)
assert_allclose_quantity(s_slc.lat, [-2, -4, -6] * u.deg)
assert_allclose_quantity(s_slc.distance, [1, 1, 1] * u.kpc)
assert len(s) == 10
assert isiterable(s)
def test_getitem_len_iterable_scalar(self):
s = SphericalRepresentation(lon=1 * u.deg,
lat=-2 * u.deg,
distance=3 * u.kpc)
with pytest.raises(TypeError):
s_slc = s[0]
with pytest.raises(TypeError):
len(s)
assert not isiterable(s)
class TestUnitSphericalRepresentation:
def test_name(self):
assert UnitSphericalRepresentation.get_name() == 'unitspherical'
assert UnitSphericalRepresentation.get_name() in REPRESENTATION_CLASSES
def test_empty_init(self):
with pytest.raises(TypeError) as exc:
s = UnitSphericalRepresentation()
def test_init_quantity(self):
s3 = UnitSphericalRepresentation(lon=8 * u.hourangle, lat=5 * u.deg)
assert s3.lon == 8. * u.hourangle
assert s3.lat == 5. * u.deg
assert isinstance(s3.lon, Longitude)
assert isinstance(s3.lat, Latitude)
def test_init_lonlat(self):
s2 = UnitSphericalRepresentation(Longitude(8, u.hour),
Latitude(5, u.deg))
assert s2.lon == 8. * u.hourangle
assert s2.lat == 5. * u.deg
assert isinstance(s2.lon, Longitude)
assert isinstance(s2.lat, Latitude)
def test_init_array(self):
s1 = UnitSphericalRepresentation(lon=[8, 9] * u.hourangle,
lat=[5, 6] * u.deg)
assert_allclose(s1.lon.degree, [120, 135])
assert_allclose(s1.lat.degree, [5, 6])
assert isinstance(s1.lon, Longitude)
assert isinstance(s1.lat, Latitude)
def test_init_array_nocopy(self):
lon = Longitude([8, 9] * u.hourangle)
lat = Latitude([5, 6] * u.deg)
s1 = UnitSphericalRepresentation(lon=lon, lat=lat, copy=False)
lon[:] = [1, 2] * u.rad
lat[:] = [3, 4] * u.arcmin
assert_allclose_quantity(lon, s1.lon)
assert_allclose_quantity(lat, s1.lat)
def test_reprobj(self):
s1 = UnitSphericalRepresentation(lon=8 * u.hourangle, lat=5 * u.deg)
s2 = UnitSphericalRepresentation.from_representation(s1)
assert_allclose_quantity(s2.lon, 8. * u.hourangle)
assert_allclose_quantity(s2.lat, 5. * u.deg)
def test_broadcasting(self):
s1 = UnitSphericalRepresentation(lon=[8, 9] * u.hourangle,
lat=[5, 6] * u.deg)
assert_allclose_quantity(s1.lon, [120, 135] * u.degree)
assert_allclose_quantity(s1.lat, [5, 6] * u.degree)
def test_broadcasting_mismatch(self):
with pytest.raises(ValueError) as exc:
s1 = UnitSphericalRepresentation(lon=[8, 9, 10] * u.hourangle,
lat=[5, 6] * u.deg)
assert exc.value.args[0] == "Input parameters lon and lat cannot be broadcast"
def test_readonly(self):
s1 = UnitSphericalRepresentation(lon=8 * u.hourangle,
lat=5 * u.deg)
with pytest.raises(AttributeError):
s1.lon = 1. * u.deg
with pytest.raises(AttributeError):
s1.lat = 1. * u.deg
def test_getitem(self):
s = UnitSphericalRepresentation(lon=np.arange(10) * u.deg,
lat=-np.arange(10) * u.deg)
s_slc = s[2:8:2]
assert_allclose_quantity(s_slc.lon, [2, 4, 6] * u.deg)
assert_allclose_quantity(s_slc.lat, [-2, -4, -6] * u.deg)
def test_getitem_scalar(self):
s = UnitSphericalRepresentation(lon=1 * u.deg,
lat=-2 * u.deg)
with pytest.raises(TypeError):
s_slc = s[0]
class TestPhysicsSphericalRepresentation:
def test_name(self):
assert PhysicsSphericalRepresentation.get_name() == 'physicsspherical'
assert PhysicsSphericalRepresentation.get_name() in REPRESENTATION_CLASSES
def test_empty_init(self):
with pytest.raises(TypeError) as exc:
s = PhysicsSphericalRepresentation()
def test_init_quantity(self):
s3 = PhysicsSphericalRepresentation(phi=8 * u.hourangle, theta=5 * u.deg, r=10 * u.kpc)
assert s3.phi == 8. * u.hourangle
assert s3.theta == 5. * u.deg
assert s3.r == 10 * u.kpc
assert isinstance(s3.phi, Angle)
assert isinstance(s3.theta, Angle)
assert isinstance(s3.r, Distance)
def test_init_phitheta(self):
s2 = PhysicsSphericalRepresentation(Angle(8, u.hour),
Angle(5, u.deg),
Distance(10, u.kpc))
assert s2.phi == 8. * u.hourangle
assert s2.theta == 5. * u.deg
assert s2.r == 10. * u.kpc
assert isinstance(s2.phi, Angle)
assert isinstance(s2.theta, Angle)
assert isinstance(s2.r, Distance)
def test_init_array(self):
s1 = PhysicsSphericalRepresentation(phi=[8, 9] * u.hourangle,
theta=[5, 6] * u.deg,
r=[1, 2] * u.kpc)
assert_allclose(s1.phi.degree, [120, 135])
assert_allclose(s1.theta.degree, [5, 6])
assert_allclose(s1.r.kpc, [1, 2])
assert isinstance(s1.phi, Angle)
assert isinstance(s1.theta, Angle)
assert isinstance(s1.r, Distance)
def test_init_array_nocopy(self):
phi = Angle([8, 9] * u.hourangle)
theta = Angle([5, 6] * u.deg)
r = Distance([1, 2] * u.kpc)
s1 = PhysicsSphericalRepresentation(phi=phi, theta=theta, r=r, copy=False)
phi[:] = [1, 2] * u.rad
theta[:] = [3, 4] * u.arcmin
r[:] = [8, 9] * u.Mpc
assert_allclose_quantity(phi, s1.phi)
assert_allclose_quantity(theta, s1.theta)
assert_allclose_quantity(r, s1.r)
def test_reprobj(self):
s1 = PhysicsSphericalRepresentation(phi=8 * u.hourangle, theta=5 * u.deg, r=10 * u.kpc)
s2 = PhysicsSphericalRepresentation.from_representation(s1)
assert_allclose_quantity(s2.phi, 8. * u.hourangle)
assert_allclose_quantity(s2.theta, 5. * u.deg)
assert_allclose_quantity(s2.r, 10 * u.kpc)
def test_broadcasting(self):
s1 = PhysicsSphericalRepresentation(phi=[8, 9] * u.hourangle,
theta=[5, 6] * u.deg,
r=10 * u.kpc)
assert_allclose_quantity(s1.phi, [120, 135] * u.degree)
assert_allclose_quantity(s1.theta, [5, 6] * u.degree)
assert_allclose_quantity(s1.r, [10, 10] * u.kpc)
def test_broadcasting_mismatch(self):
with pytest.raises(ValueError) as exc:
s1 = PhysicsSphericalRepresentation(phi=[8, 9, 10] * u.hourangle,
theta=[5, 6] * u.deg,
r=[1, 2] * u.kpc)
assert exc.value.args[0] == "Input parameters phi, theta, and r cannot be broadcast"
def test_readonly(self):
s1 = PhysicsSphericalRepresentation(phi=[8, 9] * u.hourangle,
theta=[5, 6] * u.deg,
r=[10, 20] * u.kpc)
with pytest.raises(AttributeError):
s1.phi = 1. * u.deg
with pytest.raises(AttributeError):
s1.theta = 1. * u.deg
with pytest.raises(AttributeError):
s1.r = 1. * u.kpc
def test_getitem(self):
s = PhysicsSphericalRepresentation(phi=np.arange(10) * u.deg,
theta=np.arange(5, 15) * u.deg,
r=1 * u.kpc)
s_slc = s[2:8:2]
assert_allclose_quantity(s_slc.phi, [2, 4, 6] * u.deg)
assert_allclose_quantity(s_slc.theta, [7, 9, 11] * u.deg)
assert_allclose_quantity(s_slc.r, [1, 1, 1] * u.kpc)
def test_getitem_scalar(self):
s = PhysicsSphericalRepresentation(phi=1 * u.deg,
theta=2 * u.deg,
r=3 * u.kpc)
with pytest.raises(TypeError):
s_slc = s[0]
class TestCartesianRepresentation:
def test_name(self):
assert CartesianRepresentation.get_name() == 'cartesian'
assert CartesianRepresentation.get_name() in REPRESENTATION_CLASSES
def test_empty_init(self):
with pytest.raises(TypeError) as exc:
s = CartesianRepresentation()
def test_init_quantity(self):
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc)
assert s1.x.unit is u.kpc
assert s1.y.unit is u.kpc
assert s1.z.unit is u.kpc
assert_allclose(s1.x.value, 1)
assert_allclose(s1.y.value, 2)
assert_allclose(s1.z.value, 3)
def test_init_singleunit(self):
s1 = CartesianRepresentation(x=1, y=2, z=3, unit=u.kpc)
assert s1.x.unit is u.kpc
assert s1.y.unit is u.kpc
assert s1.z.unit is u.kpc
assert_allclose(s1.x.value, 1)
assert_allclose(s1.y.value, 2)
assert_allclose(s1.z.value, 3)
def test_init_array(self):
s1 = CartesianRepresentation(x=[1, 2, 3] * u.pc,
y=[2, 3, 4] * u.Mpc,
z=[3, 4, 5] * u.kpc)
assert s1.x.unit is u.pc
assert s1.y.unit is u.Mpc
assert s1.z.unit is u.kpc
assert_allclose(s1.x.value, [1, 2, 3])
assert_allclose(s1.y.value, [2, 3, 4])
assert_allclose(s1.z.value, [3, 4, 5])
def test_init_one_array(self):
s1 = CartesianRepresentation(x=[1, 2, 3] * u.pc)
assert s1.x.unit is u.pc
assert s1.y.unit is u.pc
assert s1.z.unit is u.pc
assert_allclose(s1.x.value, 1)
assert_allclose(s1.y.value, 2)
assert_allclose(s1.z.value, 3)
r = np.arange(27.).reshape(3, 3, 3) * u.kpc
s2 = CartesianRepresentation(r, xyz_axis=0)
assert s2.shape == (3, 3)
assert s2.x.unit == u.kpc
assert np.all(s2.x == r[0])
assert np.all(s2.xyz == r)
assert np.all(s2.get_xyz(xyz_axis=0) == r)
s3 = CartesianRepresentation(r, xyz_axis=1)
assert s3.shape == (3, 3)
assert np.all(s3.x == r[:, 0])
assert np.all(s3.y == r[:, 1])
assert np.all(s3.z == r[:, 2])
assert np.all(s3.get_xyz(xyz_axis=1) == r)
s4 = CartesianRepresentation(r, xyz_axis=2)
assert s4.shape == (3, 3)
assert np.all(s4.x == r[:, :, 0])
assert np.all(s4.get_xyz(xyz_axis=2) == r)
s5 = CartesianRepresentation(r, unit=u.pc)
assert s5.x.unit == u.pc
assert np.all(s5.xyz == r)
s6 = CartesianRepresentation(r.value, unit=u.pc, xyz_axis=2)
assert s6.x.unit == u.pc
assert np.all(s6.get_xyz(xyz_axis=2).value == r.value)
def test_init_one_array_size_fail(self):
with pytest.raises(ValueError) as exc:
CartesianRepresentation(x=[1, 2, 3, 4] * u.pc)
assert exc.value.args[0].startswith("too many values to unpack")
def test_init_xyz_but_more_than_one_array_fail(self):
with pytest.raises(ValueError) as exc:
CartesianRepresentation(x=[1, 2, 3] * u.pc, y=[2, 3, 4] * u.pc,
z=[3, 4, 5] * u.pc, xyz_axis=0)
assert 'xyz_axis should only be set' in str(exc)
def test_init_one_array_yz_fail(self):
with pytest.raises(ValueError) as exc:
CartesianRepresentation(x=[1, 2, 3, 4] * u.pc, y=[1, 2] * u.pc)
assert exc.value.args[0] == ("x, y, and z are required to instantiate "
"CartesianRepresentation")
def test_init_array_nocopy(self):
x = [8, 9, 10] * u.pc
y = [5, 6, 7] * u.Mpc
z = [2, 3, 4] * u.kpc
s1 = CartesianRepresentation(x=x, y=y, z=z, copy=False)
x[:] = [1, 2, 3] * u.kpc
y[:] = [9, 9, 8] * u.kpc
z[:] = [1, 2, 1] * u.kpc
assert_allclose_quantity(x, s1.x)
assert_allclose_quantity(y, s1.y)
assert_allclose_quantity(z, s1.z)
def test_reprobj(self):
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc)
s2 = CartesianRepresentation.from_representation(s1)
assert s2.x == 1 * u.kpc
assert s2.y == 2 * u.kpc
assert s2.z == 3 * u.kpc
def test_broadcasting(self):
s1 = CartesianRepresentation(x=[1, 2] * u.kpc, y=[3, 4] * u.kpc, z=5 * u.kpc)
assert s1.x.unit == u.kpc
assert s1.y.unit == u.kpc
assert s1.z.unit == u.kpc
assert_allclose(s1.x.value, [1, 2])
assert_allclose(s1.y.value, [3, 4])
assert_allclose(s1.z.value, [5, 5])
def test_broadcasting_mismatch(self):
with pytest.raises(ValueError) as exc:
s1 = CartesianRepresentation(x=[1, 2] * u.kpc, y=[3, 4] * u.kpc, z=[5, 6, 7] * u.kpc)
assert exc.value.args[0] == "Input parameters x, y, and z cannot be broadcast"
def test_readonly(self):
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc)
with pytest.raises(AttributeError):
s1.x = 1. * u.kpc
with pytest.raises(AttributeError):
s1.y = 1. * u.kpc
with pytest.raises(AttributeError):
s1.z = 1. * u.kpc
def test_xyz(self):
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc)
assert isinstance(s1.xyz, u.Quantity)
assert s1.xyz.unit is u.kpc
assert_allclose(s1.xyz.value, [1, 2, 3])
def test_unit_mismatch(self):
q_len = u.Quantity([1], u.km)
q_nonlen = u.Quantity([1], u.kg)
with pytest.raises(u.UnitsError) as exc:
s1 = CartesianRepresentation(x=q_nonlen, y=q_len, z=q_len)
assert exc.value.args[0] == "x, y, and z should have matching physical types"
with pytest.raises(u.UnitsError) as exc:
s1 = CartesianRepresentation(x=q_len, y=q_nonlen, z=q_len)
assert exc.value.args[0] == "x, y, and z should have matching physical types"
with pytest.raises(u.UnitsError) as exc:
s1 = CartesianRepresentation(x=q_len, y=q_len, z=q_nonlen)
assert exc.value.args[0] == "x, y, and z should have matching physical types"
def test_unit_non_length(self):
s1 = CartesianRepresentation(x=1 * u.kg, y=2 * u.kg, z=3 * u.kg)
s2 = CartesianRepresentation(x=1 * u.km / u.s, y=2 * u.km / u.s, z=3 * u.km / u.s)
banana = u.def_unit('banana')
s3 = CartesianRepresentation(x=1 * banana, y=2 * banana, z=3 * banana)
def test_getitem(self):
s = CartesianRepresentation(x=np.arange(10) * u.m,
y=-np.arange(10) * u.m,
z=3 * u.km)
s_slc = s[2:8:2]
assert_allclose_quantity(s_slc.x, [2, 4, 6] * u.m)
assert_allclose_quantity(s_slc.y, [-2, -4, -6] * u.m)
assert_allclose_quantity(s_slc.z, [3, 3, 3] * u.km)
def test_getitem_scalar(self):
s = CartesianRepresentation(x=1 * u.m,
y=-2 * u.m,
z=3 * u.km)
with pytest.raises(TypeError):
s_slc = s[0]
def test_transform(self):
s1 = CartesianRepresentation(x=[1, 2] * u.kpc, y=[3, 4] * u.kpc, z=[5, 6] * u.kpc)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
s2 = s1.transform(matrix)
assert_allclose(s2.x.value, [1 * 1 + 2 * 3 + 3 * 5, 1 * 2 + 2 * 4 + 3 * 6])
assert_allclose(s2.y.value, [4 * 1 + 5 * 3 + 6 * 5, 4 * 2 + 5 * 4 + 6 * 6])
assert_allclose(s2.z.value, [7 * 1 + 8 * 3 + 9 * 5, 7 * 2 + 8 * 4 + 9 * 6])
assert s2.x.unit is u.kpc
assert s2.y.unit is u.kpc
assert s2.z.unit is u.kpc
class TestCylindricalRepresentation:
def test_name(self):
assert CylindricalRepresentation.get_name() == 'cylindrical'
assert CylindricalRepresentation.get_name() in REPRESENTATION_CLASSES
def test_empty_init(self):
with pytest.raises(TypeError) as exc:
s = CylindricalRepresentation()
def test_init_quantity(self):
s1 = CylindricalRepresentation(rho=1 * u.kpc, phi=2 * u.deg, z=3 * u.kpc)
assert s1.rho.unit is u.kpc
assert s1.phi.unit is u.deg
assert s1.z.unit is u.kpc
assert_allclose(s1.rho.value, 1)
assert_allclose(s1.phi.value, 2)
assert_allclose(s1.z.value, 3)
def test_init_array(self):
s1 = CylindricalRepresentation(rho=[1, 2, 3] * u.pc,
phi=[2, 3, 4] * u.deg,
z=[3, 4, 5] * u.kpc)
assert s1.rho.unit is u.pc
assert s1.phi.unit is u.deg
assert s1.z.unit is u.kpc
assert_allclose(s1.rho.value, [1, 2, 3])
assert_allclose(s1.phi.value, [2, 3, 4])
assert_allclose(s1.z.value, [3, 4, 5])
def test_init_array_nocopy(self):
rho = [8, 9, 10] * u.pc
phi = [5, 6, 7] * u.deg
z = [2, 3, 4] * u.kpc
s1 = CylindricalRepresentation(rho=rho, phi=phi, z=z, copy=False)
rho[:] = [9, 2, 3] * u.kpc
phi[:] = [1, 2, 3] * u.arcmin
z[:] = [-2, 3, 8] * u.kpc
assert_allclose_quantity(rho, s1.rho)
assert_allclose_quantity(phi, s1.phi)
assert_allclose_quantity(z, s1.z)
def test_reprobj(self):
s1 = CylindricalRepresentation(rho=1 * u.kpc, phi=2 * u.deg, z=3 * u.kpc)
s2 = CylindricalRepresentation.from_representation(s1)
assert s2.rho == 1 * u.kpc
assert s2.phi == 2 * u.deg
assert s2.z == 3 * u.kpc
def test_broadcasting(self):
s1 = CylindricalRepresentation(rho=[1, 2] * u.kpc, phi=[3, 4] * u.deg, z=5 * u.kpc)
assert s1.rho.unit == u.kpc
assert s1.phi.unit == u.deg
assert s1.z.unit == u.kpc
assert_allclose(s1.rho.value, [1, 2])
assert_allclose(s1.phi.value, [3, 4])
assert_allclose(s1.z.value, [5, 5])
def test_broadcasting_mismatch(self):
with pytest.raises(ValueError) as exc:
s1 = CylindricalRepresentation(rho=[1, 2] * u.kpc, phi=[3, 4] * u.deg, z=[5, 6, 7] * u.kpc)
assert exc.value.args[0] == "Input parameters rho, phi, and z cannot be broadcast"
def test_readonly(self):
s1 = CylindricalRepresentation(rho=1 * u.kpc,
phi=20 * u.deg,
z=3 * u.kpc)
with pytest.raises(AttributeError):
s1.rho = 1. * u.kpc
with pytest.raises(AttributeError):
s1.phi = 20 * u.deg
with pytest.raises(AttributeError):
s1.z = 1. * u.kpc
def unit_mismatch(self):
q_len = u.Quantity([1], u.kpc)
q_nonlen = u.Quantity([1], u.kg)
with pytest.raises(u.UnitsError) as exc:
s1 = CylindricalRepresentation(rho=q_nonlen, phi=10 * u.deg, z=q_len)
assert exc.value.args[0] == "rho and z should have matching physical types"
with pytest.raises(u.UnitsError) as exc:
s1 = CylindricalRepresentation(rho=q_len, phi=10 * u.deg, z=q_nonlen)
assert exc.value.args[0] == "rho and z should have matching physical types"
def test_getitem(self):
s = CylindricalRepresentation(rho=np.arange(10) * u.pc,
phi=-np.arange(10) * u.deg,
z=1 * u.kpc)
s_slc = s[2:8:2]
assert_allclose_quantity(s_slc.rho, [2, 4, 6] * u.pc)
assert_allclose_quantity(s_slc.phi, [-2, -4, -6] * u.deg)
assert_allclose_quantity(s_slc.z, [1, 1, 1] * u.kpc)
def test_getitem_scalar(self):
s = CylindricalRepresentation(rho=1 * u.pc,
phi=-2 * u.deg,
z=3 * u.kpc)
with pytest.raises(TypeError):
s_slc = s[0]
def test_cartesian_spherical_roundtrip():
s1 = CartesianRepresentation(x=[1, 2000.] * u.kpc,
y=[3000., 4.] * u.pc,
z=[5., 6000.] * u.pc)
s2 = SphericalRepresentation.from_representation(s1)
s3 = CartesianRepresentation.from_representation(s2)
s4 = SphericalRepresentation.from_representation(s3)
assert_allclose_quantity(s1.x, s3.x)
assert_allclose_quantity(s1.y, s3.y)
assert_allclose_quantity(s1.z, s3.z)
assert_allclose_quantity(s2.lon, s4.lon)
assert_allclose_quantity(s2.lat, s4.lat)
assert_allclose_quantity(s2.distance, s4.distance)
def test_cartesian_physics_spherical_roundtrip():
s1 = CartesianRepresentation(x=[1, 2000.] * u.kpc,
y=[3000., 4.] * u.pc,
z=[5., 6000.] * u.pc)
s2 = PhysicsSphericalRepresentation.from_representation(s1)
s3 = CartesianRepresentation.from_representation(s2)
s4 = PhysicsSphericalRepresentation.from_representation(s3)
assert_allclose_quantity(s1.x, s3.x)
assert_allclose_quantity(s1.y, s3.y)
assert_allclose_quantity(s1.z, s3.z)
assert_allclose_quantity(s2.phi, s4.phi)
assert_allclose_quantity(s2.theta, s4.theta)
assert_allclose_quantity(s2.r, s4.r)
def test_spherical_physics_spherical_roundtrip():
s1 = SphericalRepresentation(lon=3 * u.deg, lat=4 * u.deg, distance=3 * u.kpc)
s2 = PhysicsSphericalRepresentation.from_representation(s1)
s3 = SphericalRepresentation.from_representation(s2)
s4 = PhysicsSphericalRepresentation.from_representation(s3)
assert_allclose_quantity(s1.lon, s3.lon)
assert_allclose_quantity(s1.lat, s3.lat)
assert_allclose_quantity(s1.distance, s3.distance)
assert_allclose_quantity(s2.phi, s4.phi)
assert_allclose_quantity(s2.theta, s4.theta)
assert_allclose_quantity(s2.r, s4.r)
assert_allclose_quantity(s1.lon, s4.phi)
assert_allclose_quantity(s1.lat, 90. * u.deg - s4.theta)
assert_allclose_quantity(s1.distance, s4.r)
def test_cartesian_cylindrical_roundtrip():
s1 = CartesianRepresentation(x=np.array([1., 2000.]) * u.kpc,
y=np.array([3000., 4.]) * u.pc,
z=np.array([5., 600.]) * u.cm)
s2 = CylindricalRepresentation.from_representation(s1)
s3 = CartesianRepresentation.from_representation(s2)
s4 = CylindricalRepresentation.from_representation(s3)
assert_allclose_quantity(s1.x, s3.x)
assert_allclose_quantity(s1.y, s3.y)
assert_allclose_quantity(s1.z, s3.z)
assert_allclose_quantity(s2.rho, s4.rho)
assert_allclose_quantity(s2.phi, s4.phi)
assert_allclose_quantity(s2.z, s4.z)
def test_unit_spherical_roundtrip():
s1 = UnitSphericalRepresentation(lon=[10., 30.] * u.deg,
lat=[5., 6.] * u.arcmin)
s2 = CartesianRepresentation.from_representation(s1)
s3 = SphericalRepresentation.from_representation(s2)
s4 = UnitSphericalRepresentation.from_representation(s3)
assert_allclose_quantity(s1.lon, s4.lon)
assert_allclose_quantity(s1.lat, s4.lat)
def test_no_unnecessary_copies():
s1 = UnitSphericalRepresentation(lon=[10., 30.] * u.deg,
lat=[5., 6.] * u.arcmin)
s2 = s1.represent_as(UnitSphericalRepresentation)
assert s2 is s1
assert np.may_share_memory(s1.lon, s2.lon)
assert np.may_share_memory(s1.lat, s2.lat)
s3 = s1.represent_as(SphericalRepresentation)
assert np.may_share_memory(s1.lon, s3.lon)
assert np.may_share_memory(s1.lat, s3.lat)
s4 = s1.represent_as(CartesianRepresentation)
s5 = s4.represent_as(CylindricalRepresentation)
assert np.may_share_memory(s5.z, s4.z)
def test_representation_repr():
r1 = SphericalRepresentation(lon=1 * u.deg, lat=2.5 * u.deg, distance=1 * u.kpc)
assert repr(r1) == ('<SphericalRepresentation (lon, lat, distance) in (deg, deg, kpc)\n'
' ({})>').format(' 1., 2.5, 1.' if NUMPY_LT_1_14
else '1., 2.5, 1.')
r2 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc)
assert repr(r2) == ('<CartesianRepresentation (x, y, z) in kpc\n'
' ({})>').format(' 1., 2., 3.' if NUMPY_LT_1_14
else '1., 2., 3.')
r3 = CartesianRepresentation(x=[1, 2, 3] * u.kpc, y=4 * u.kpc, z=[9, 10, 11] * u.kpc)
if NUMPY_LT_1_14:
assert repr(r3) == ('<CartesianRepresentation (x, y, z) in kpc\n'
' [( 1., 4., 9.), ( 2., 4., 10.), ( 3., 4., 11.)]>')
else:
assert repr(r3) == ('<CartesianRepresentation (x, y, z) in kpc\n'
' [(1., 4., 9.), (2., 4., 10.), (3., 4., 11.)]>')
def test_representation_repr_multi_d():
"""Regression test for #5889."""
cr = CartesianRepresentation(np.arange(27).reshape(3, 3, 3), unit='m')
if NUMPY_LT_1_14:
assert repr(cr) == (
'<CartesianRepresentation (x, y, z) in m\n'
' [[( 0., 9., 18.), ( 1., 10., 19.), ( 2., 11., 20.)],\n'
' [( 3., 12., 21.), ( 4., 13., 22.), ( 5., 14., 23.)],\n'
' [( 6., 15., 24.), ( 7., 16., 25.), ( 8., 17., 26.)]]>')
else:
assert repr(cr) == (
'<CartesianRepresentation (x, y, z) in m\n'
' [[(0., 9., 18.), (1., 10., 19.), (2., 11., 20.)],\n'
' [(3., 12., 21.), (4., 13., 22.), (5., 14., 23.)],\n'
' [(6., 15., 24.), (7., 16., 25.), (8., 17., 26.)]]>')
# This was broken before.
if NUMPY_LT_1_14:
assert repr(cr.T) == (
'<CartesianRepresentation (x, y, z) in m\n'
' [[( 0., 9., 18.), ( 3., 12., 21.), ( 6., 15., 24.)],\n'
' [( 1., 10., 19.), ( 4., 13., 22.), ( 7., 16., 25.)],\n'
' [( 2., 11., 20.), ( 5., 14., 23.), ( 8., 17., 26.)]]>')
else:
assert repr(cr.T) == (
'<CartesianRepresentation (x, y, z) in m\n'
' [[(0., 9., 18.), (3., 12., 21.), (6., 15., 24.)],\n'
' [(1., 10., 19.), (4., 13., 22.), (7., 16., 25.)],\n'
' [(2., 11., 20.), (5., 14., 23.), (8., 17., 26.)]]>')
def test_representation_str():
r1 = SphericalRepresentation(lon=1 * u.deg, lat=2.5 * u.deg, distance=1 * u.kpc)
assert str(r1) == ('( 1., 2.5, 1.) (deg, deg, kpc)' if NUMPY_LT_1_14 else
'(1., 2.5, 1.) (deg, deg, kpc)')
r2 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc)
assert str(r2) == ('( 1., 2., 3.) kpc' if NUMPY_LT_1_14 else
'(1., 2., 3.) kpc')
r3 = CartesianRepresentation(x=[1, 2, 3] * u.kpc, y=4 * u.kpc, z=[9, 10, 11] * u.kpc)
assert str(r3) == ('[( 1., 4., 9.), ( 2., 4., 10.), ( 3., 4., 11.)] kpc'
if NUMPY_LT_1_14 else
'[(1., 4., 9.), (2., 4., 10.), (3., 4., 11.)] kpc')
def test_representation_str_multi_d():
"""Regression test for #5889."""
cr = CartesianRepresentation(np.arange(27).reshape(3, 3, 3), unit='m')
if NUMPY_LT_1_14:
assert str(cr) == (
'[[( 0., 9., 18.), ( 1., 10., 19.), ( 2., 11., 20.)],\n'
' [( 3., 12., 21.), ( 4., 13., 22.), ( 5., 14., 23.)],\n'
' [( 6., 15., 24.), ( 7., 16., 25.), ( 8., 17., 26.)]] m')
else:
assert str(cr) == (
'[[(0., 9., 18.), (1., 10., 19.), (2., 11., 20.)],\n'
' [(3., 12., 21.), (4., 13., 22.), (5., 14., 23.)],\n'
' [(6., 15., 24.), (7., 16., 25.), (8., 17., 26.)]] m')
# This was broken before.
if NUMPY_LT_1_14:
assert str(cr.T) == (
'[[( 0., 9., 18.), ( 3., 12., 21.), ( 6., 15., 24.)],\n'
' [( 1., 10., 19.), ( 4., 13., 22.), ( 7., 16., 25.)],\n'
' [( 2., 11., 20.), ( 5., 14., 23.), ( 8., 17., 26.)]] m')
else:
assert str(cr.T) == (
'[[(0., 9., 18.), (3., 12., 21.), (6., 15., 24.)],\n'
' [(1., 10., 19.), (4., 13., 22.), (7., 16., 25.)],\n'
' [(2., 11., 20.), (5., 14., 23.), (8., 17., 26.)]] m')
def test_subclass_representation():
from ..builtin_frames import ICRS
class Longitude180(Longitude):
def __new__(cls, angle, unit=None, wrap_angle=180 * u.deg, **kwargs):
self = super().__new__(cls, angle, unit=unit, wrap_angle=wrap_angle,
**kwargs)
return self
class SphericalWrap180Representation(SphericalRepresentation):
attr_classes = OrderedDict([('lon', Longitude180),
('lat', Latitude),
('distance', u.Quantity)])
recommended_units = {'lon': u.deg, 'lat': u.deg}
class ICRSWrap180(ICRS):
frame_specific_representation_info = ICRS._frame_specific_representation_info.copy()
frame_specific_representation_info[SphericalWrap180Representation] = \
frame_specific_representation_info[SphericalRepresentation]
default_representation = SphericalWrap180Representation
c = ICRSWrap180(ra=-1 * u.deg, dec=-2 * u.deg, distance=1 * u.m)
assert c.ra.value == -1
assert c.ra.unit is u.deg
assert c.dec.value == -2
assert c.dec.unit is u.deg
def test_minimal_subclass():
# Basically to check what we document works;
# see doc/coordinates/representations.rst
class LogDRepresentation(BaseRepresentation):
attr_classes = OrderedDict([('lon', Longitude),
('lat', Latitude),
('logd', u.Dex)])
def to_cartesian(self):
d = self.logd.physical
x = d * np.cos(self.lat) * np.cos(self.lon)
y = d * np.cos(self.lat) * np.sin(self.lon)
z = d * np.sin(self.lat)
return CartesianRepresentation(x=x, y=y, z=z, copy=False)
@classmethod
def from_cartesian(cls, cart):
s = np.hypot(cart.x, cart.y)
r = np.hypot(s, cart.z)
lon = np.arctan2(cart.y, cart.x)
lat = np.arctan2(cart.z, s)
return cls(lon=lon, lat=lat, logd=u.Dex(r), copy=False)
ld1 = LogDRepresentation(90.*u.deg, 0.*u.deg, 1.*u.dex(u.kpc))
ld2 = LogDRepresentation(lon=90.*u.deg, lat=0.*u.deg, logd=1.*u.dex(u.kpc))
assert np.all(ld1.lon == ld2.lon)
assert np.all(ld1.lat == ld2.lat)
assert np.all(ld1.logd == ld2.logd)
c = ld1.to_cartesian()
assert_allclose_quantity(c.xyz, [0., 10., 0.] * u.kpc, atol=1.*u.npc)
ld3 = LogDRepresentation.from_cartesian(c)
assert np.all(ld3.lon == ld2.lon)
assert np.all(ld3.lat == ld2.lat)
assert np.all(ld3.logd == ld2.logd)
s = ld1.represent_as(SphericalRepresentation)
assert_allclose_quantity(s.lon, ld1.lon)
assert_allclose_quantity(s.distance, 10.*u.kpc)
assert_allclose_quantity(s.lat, ld1.lat)
with pytest.raises(TypeError):
LogDRepresentation(0.*u.deg, 1.*u.deg)
with pytest.raises(TypeError):
LogDRepresentation(0.*u.deg, 1.*u.deg, 1.*u.dex(u.kpc), lon=1.*u.deg)
with pytest.raises(TypeError):
LogDRepresentation(0.*u.deg, 1.*u.deg, 1.*u.dex(u.kpc), True, False)
with pytest.raises(TypeError):
LogDRepresentation(0.*u.deg, 1.*u.deg, 1.*u.dex(u.kpc), foo='bar')
with pytest.raises(ValueError):
# check we cannot redefine an existing class.
class LogDRepresentation(BaseRepresentation):
attr_classes = OrderedDict([('lon', Longitude),
('lat', Latitude),
('logr', u.Dex)])
def test_combine_xyz():
x, y, z = np.arange(27).reshape(3, 9) * u.kpc
xyz = _combine_xyz(x, y, z, xyz_axis=0)
assert xyz.shape == (3, 9)
assert np.all(xyz[0] == x)
assert np.all(xyz[1] == y)
assert np.all(xyz[2] == z)
x, y, z = np.arange(27).reshape(3, 3, 3) * u.kpc
xyz = _combine_xyz(x, y, z, xyz_axis=0)
assert xyz.ndim == 3
assert np.all(xyz[0] == x)
assert np.all(xyz[1] == y)
assert np.all(xyz[2] == z)
xyz = _combine_xyz(x, y, z, xyz_axis=1)
assert xyz.ndim == 3
assert np.all(xyz[:, 0] == x)
assert np.all(xyz[:, 1] == y)
assert np.all(xyz[:, 2] == z)
xyz = _combine_xyz(x, y, z, xyz_axis=-1)
assert xyz.ndim == 3
assert np.all(xyz[..., 0] == x)
assert np.all(xyz[..., 1] == y)
assert np.all(xyz[..., 2] == z)
class TestCartesianRepresentationWithDifferential:
def test_init_differential(self):
diff = CartesianDifferential(d_x=1 * u.km/u.s,
d_y=2 * u.km/u.s,
d_z=3 * u.km/u.s)
# Check that a single differential gets turned into a 1-item dict.
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc,
differentials=diff)
assert s1.x.unit is u.kpc
assert s1.y.unit is u.kpc
assert s1.z.unit is u.kpc
assert len(s1.differentials) == 1
assert s1.differentials['s'] is diff
# can also pass in an explicit dictionary
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc,
differentials={'s': diff})
assert len(s1.differentials) == 1
assert s1.differentials['s'] is diff
# using the wrong key will cause it to fail
with pytest.raises(ValueError):
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc,
differentials={'1 / s2': diff})
# make sure other kwargs are handled properly
s1 = CartesianRepresentation(x=1, y=2, z=3,
differentials=diff, copy=False, unit=u.kpc)
assert len(s1.differentials) == 1
assert s1.differentials['s'] is diff
with pytest.raises(TypeError): # invalid type passed to differentials
CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc,
differentials='garmonbozia')
# make sure differentials can't accept differentials
with pytest.raises(TypeError):
CartesianDifferential(d_x=1 * u.km/u.s, d_y=2 * u.km/u.s,
d_z=3 * u.km/u.s, differentials=diff)
def test_init_differential_compatible(self):
# TODO: more extensive checking of this
# should fail - representation and differential not compatible
diff = SphericalDifferential(d_lon=1 * u.mas/u.yr,
d_lat=2 * u.mas/u.yr,
d_distance=3 * u.km/u.s)
with pytest.raises(TypeError):
CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc,
differentials=diff)
# should succeed - representation and differential are compatible
diff = SphericalCosLatDifferential(d_lon_coslat=1 * u.mas/u.yr,
d_lat=2 * u.mas/u.yr,
d_distance=3 * u.km/u.s)
r1 = SphericalRepresentation(lon=15*u.deg, lat=21*u.deg,
distance=1*u.pc,
differentials=diff)
def test_init_differential_multiple_equivalent_keys(self):
d1 = CartesianDifferential(*[1, 2, 3] * u.km/u.s)
d2 = CartesianDifferential(*[4, 5, 6] * u.km/u.s)
# verify that the check against expected_unit validates against passing
# in two different but equivalent keys
with pytest.raises(ValueError):
r1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc,
differentials={'s': d1, 'yr': d2})
def test_init_array_broadcasting(self):
arr1 = np.arange(8).reshape(4, 2) * u.km/u.s
diff = CartesianDifferential(d_x=arr1, d_y=arr1, d_z=arr1)
# shapes aren't compatible
arr2 = np.arange(27).reshape(3, 9) * u.kpc
with pytest.raises(ValueError):
rep = CartesianRepresentation(x=arr2, y=arr2, z=arr2,
differentials=diff)
arr2 = np.arange(8).reshape(4, 2) * u.kpc
rep = CartesianRepresentation(x=arr2, y=arr2, z=arr2,
differentials=diff)
assert rep.x.unit is u.kpc
assert rep.y.unit is u.kpc
assert rep.z.unit is u.kpc
assert len(rep.differentials) == 1
assert rep.differentials['s'] is diff
assert rep.xyz.shape == rep.differentials['s'].d_xyz.shape
def test_reprobj(self):
# should succeed - representation and differential are compatible
diff = SphericalCosLatDifferential(d_lon_coslat=1 * u.mas/u.yr,
d_lat=2 * u.mas/u.yr,
d_distance=3 * u.km/u.s)
r1 = SphericalRepresentation(lon=15*u.deg, lat=21*u.deg,
distance=1*u.pc,
differentials=diff)
r2 = CartesianRepresentation.from_representation(r1)
assert r2.get_name() == 'cartesian'
assert not r2.differentials
def test_readonly(self):
s1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc)
with pytest.raises(AttributeError): # attribute is not settable
s1.differentials = 'thing'
def test_represent_as(self):
diff = CartesianDifferential(d_x=1 * u.km/u.s,
d_y=2 * u.km/u.s,
d_z=3 * u.km/u.s)
rep1 = CartesianRepresentation(x=1 * u.kpc, y=2 * u.kpc, z=3 * u.kpc,
differentials=diff)
# Only change the representation, drop the differential
new_rep = rep1.represent_as(SphericalRepresentation)
assert new_rep.get_name() == 'spherical'
assert not new_rep.differentials # dropped
# Pass in separate classes for representation, differential
new_rep = rep1.represent_as(SphericalRepresentation,
SphericalCosLatDifferential)
assert new_rep.get_name() == 'spherical'
assert new_rep.differentials['s'].get_name() == 'sphericalcoslat'
# Pass in a dictionary for the differential classes
new_rep = rep1.represent_as(SphericalRepresentation,
{'s': SphericalCosLatDifferential})
assert new_rep.get_name() == 'spherical'
assert new_rep.differentials['s'].get_name() == 'sphericalcoslat'
# make sure represent_as() passes through the differentials
for name in REPRESENTATION_CLASSES:
if name == 'radial':
# TODO: Converting a CartesianDifferential to a
# RadialDifferential fails, even on `master`
continue
new_rep = rep1.represent_as(REPRESENTATION_CLASSES[name],
DIFFERENTIAL_CLASSES[name])
assert new_rep.get_name() == name
assert len(new_rep.differentials) == 1
assert new_rep.differentials['s'].get_name() == name
with pytest.raises(ValueError) as excinfo:
rep1.represent_as('name')
assert 'use frame object' in str(excinfo.value)
def test_getitem(self):
d = CartesianDifferential(d_x=np.arange(10) * u.m/u.s,
d_y=-np.arange(10) * u.m/u.s,
d_z=1. * u.m/u.s)
s = CartesianRepresentation(x=np.arange(10) * u.m,
y=-np.arange(10) * u.m,
z=3 * u.km,
differentials=d)
s_slc = s[2:8:2]
s_dif = s_slc.differentials['s']
assert_allclose_quantity(s_slc.x, [2, 4, 6] * u.m)
assert_allclose_quantity(s_slc.y, [-2, -4, -6] * u.m)
assert_allclose_quantity(s_slc.z, [3, 3, 3] * u.km)
assert_allclose_quantity(s_dif.d_x, [2, 4, 6] * u.m/u.s)
assert_allclose_quantity(s_dif.d_y, [-2, -4, -6] * u.m/u.s)
assert_allclose_quantity(s_dif.d_z, [1, 1, 1] * u.m/u.s)
def test_transform(self):
d1 = CartesianDifferential(d_x=[1, 2] * u.km/u.s,
d_y=[3, 4] * u.km/u.s,
d_z=[5, 6] * u.km/u.s)
r1 = CartesianRepresentation(x=[1, 2] * u.kpc,
y=[3, 4] * u.kpc,
z=[5, 6] * u.kpc,
differentials=d1)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
r2 = r1.transform(matrix)
d2 = r2.differentials['s']
assert_allclose_quantity(d2.d_x, [22., 28]*u.km/u.s)
assert_allclose_quantity(d2.d_y, [49, 64]*u.km/u.s)
assert_allclose_quantity(d2.d_z, [76, 100.]*u.km/u.s)
def test_with_differentials(self):
# make sure with_differential correctly creates a new copy with the same
# differential
cr = CartesianRepresentation([1, 2, 3]*u.kpc)
diff = CartesianDifferential([.1, .2, .3]*u.km/u.s)
cr2 = cr.with_differentials(diff)
assert cr.differentials != cr2.differentials
assert cr2.differentials['s'] is diff
# make sure it works even if a differential is present already
diff2 = CartesianDifferential([.1, .2, .3]*u.m/u.s)
cr3 = CartesianRepresentation([1, 2, 3]*u.kpc, differentials=diff)
cr4 = cr3.with_differentials(diff2)
assert cr4.differentials['s'] != cr3.differentials['s']
assert cr4.differentials['s'] == diff2
# also ensure a *scalar* differential will works
cr5 = cr.with_differentials(diff)
assert len(cr5.differentials) == 1
assert cr5.differentials['s'] == diff
# make sure we don't update the original representation's dict
d1 = CartesianDifferential(*np.random.random((3, 5)), unit=u.km/u.s)
d2 = CartesianDifferential(*np.random.random((3, 5)), unit=u.km/u.s**2)
r1 = CartesianRepresentation(*np.random.random((3, 5)), unit=u.pc,
differentials=d1)
r2 = r1.with_differentials(d2)
assert r1.differentials['s'] is r2.differentials['s']
assert 's2' not in r1.differentials
assert 's2' in r2.differentials
def test_repr_with_differentials():
diff = CartesianDifferential([.1, .2, .3]*u.km/u.s)
cr = CartesianRepresentation([1, 2, 3]*u.kpc, differentials=diff)
assert "has differentials w.r.t.: 's'" in repr(cr)
def test_to_cartesian():
"""
Test that to_cartesian drops the differential.
"""
sd = SphericalDifferential(d_lat=1*u.deg, d_lon=2*u.deg, d_distance=10*u.m)
sr = SphericalRepresentation(lat=1*u.deg, lon=2*u.deg, distance=10*u.m,
differentials=sd)
cart = sr.to_cartesian()
assert cart.get_name() == 'cartesian'
assert not cart.differentials
def test_recommended_units_deprecation():
sr = SphericalRepresentation(lat=1*u.deg, lon=2*u.deg, distance=10*u.m)
with catch_warnings(AstropyDeprecationWarning) as w:
sr.recommended_units
assert 'recommended_units' in str(w[0].message)
with catch_warnings(AstropyDeprecationWarning) as w:
class MyClass(SphericalRepresentation):
attr_classes = SphericalRepresentation.attr_classes
recommended_units = {}
assert 'recommended_units' in str(w[0].message)
|
3211f2cfd4c64f0e091da57e6d98dd9fe131040ce433cb51bffc6c3955ab95e2 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Accuracy tests for GCRS coordinate transformations, primarily to/from AltAz.
"""
import pytest
import numpy as np
from ... import units as u
from ...tests.helper import (quantity_allclose as allclose,
assert_quantity_allclose as assert_allclose)
from ...time import Time
from .. import (EarthLocation, get_sun, ICRS, GCRS, CIRS, ITRS, AltAz,
PrecessedGeocentric, CartesianRepresentation, SkyCoord,
SphericalRepresentation, UnitSphericalRepresentation,
HCRS, HeliocentricTrueEcliptic)
from ..._erfa import epv00
from .utils import randomly_sample_sphere
from ..builtin_frames.utils import get_jd12
from .. import solar_system_ephemeris
try:
import jplephem # pylint: disable=W0611
except ImportError:
HAS_JPLEPHEM = False
else:
HAS_JPLEPHEM = True
def test_icrs_cirs():
"""
Check a few cases of ICRS<->CIRS for consistency.
Also includes the CIRS<->CIRS transforms at different times, as those go
through ICRS
"""
ra, dec, dist = randomly_sample_sphere(200)
inod = ICRS(ra=ra, dec=dec)
iwd = ICRS(ra=ra, dec=dec, distance=dist*u.pc)
cframe1 = CIRS()
cirsnod = inod.transform_to(cframe1) # uses the default time
# first do a round-tripping test
inod2 = cirsnod.transform_to(ICRS)
assert_allclose(inod.ra, inod2.ra)
assert_allclose(inod.dec, inod2.dec)
# now check that a different time yields different answers
cframe2 = CIRS(obstime=Time('J2005', scale='utc'))
cirsnod2 = inod.transform_to(cframe2)
assert not allclose(cirsnod.ra, cirsnod2.ra, rtol=1e-8)
assert not allclose(cirsnod.dec, cirsnod2.dec, rtol=1e-8)
# parallax effects should be included, so with and w/o distance should be different
cirswd = iwd.transform_to(cframe1)
assert not allclose(cirswd.ra, cirsnod.ra, rtol=1e-8)
assert not allclose(cirswd.dec, cirsnod.dec, rtol=1e-8)
# and the distance should transform at least somehow
assert not allclose(cirswd.distance, iwd.distance, rtol=1e-8)
# now check that the cirs self-transform works as expected
cirsnod3 = cirsnod.transform_to(cframe1) # should be a no-op
assert_allclose(cirsnod.ra, cirsnod3.ra)
assert_allclose(cirsnod.dec, cirsnod3.dec)
cirsnod4 = cirsnod.transform_to(cframe2) # should be different
assert not allclose(cirsnod4.ra, cirsnod.ra, rtol=1e-8)
assert not allclose(cirsnod4.dec, cirsnod.dec, rtol=1e-8)
cirsnod5 = cirsnod4.transform_to(cframe1) # should be back to the same
assert_allclose(cirsnod.ra, cirsnod5.ra)
assert_allclose(cirsnod.dec, cirsnod5.dec)
ra, dec, dist = randomly_sample_sphere(200)
icrs_coords = [ICRS(ra=ra, dec=dec), ICRS(ra=ra, dec=dec, distance=dist*u.pc)]
gcrs_frames = [GCRS(), GCRS(obstime=Time('J2005', scale='utc'))]
@pytest.mark.parametrize('icoo', icrs_coords)
def test_icrs_gcrs(icoo):
"""
Check ICRS<->GCRS for consistency
"""
gcrscoo = icoo.transform_to(gcrs_frames[0]) # uses the default time
# first do a round-tripping test
icoo2 = gcrscoo.transform_to(ICRS)
assert_allclose(icoo.distance, icoo2.distance)
assert_allclose(icoo.ra, icoo2.ra)
assert_allclose(icoo.dec, icoo2.dec)
assert isinstance(icoo2.data, icoo.data.__class__)
# now check that a different time yields different answers
gcrscoo2 = icoo.transform_to(gcrs_frames[1])
assert not allclose(gcrscoo.ra, gcrscoo2.ra, rtol=1e-8, atol=1e-10*u.deg)
assert not allclose(gcrscoo.dec, gcrscoo2.dec, rtol=1e-8, atol=1e-10*u.deg)
# now check that the cirs self-transform works as expected
gcrscoo3 = gcrscoo.transform_to(gcrs_frames[0]) # should be a no-op
assert_allclose(gcrscoo.ra, gcrscoo3.ra)
assert_allclose(gcrscoo.dec, gcrscoo3.dec)
gcrscoo4 = gcrscoo.transform_to(gcrs_frames[1]) # should be different
assert not allclose(gcrscoo4.ra, gcrscoo.ra, rtol=1e-8, atol=1e-10*u.deg)
assert not allclose(gcrscoo4.dec, gcrscoo.dec, rtol=1e-8, atol=1e-10*u.deg)
gcrscoo5 = gcrscoo4.transform_to(gcrs_frames[0]) # should be back to the same
assert_allclose(gcrscoo.ra, gcrscoo5.ra, rtol=1e-8, atol=1e-10*u.deg)
assert_allclose(gcrscoo.dec, gcrscoo5.dec, rtol=1e-8, atol=1e-10*u.deg)
# also make sure that a GCRS with a different geoloc/geovel gets a different answer
# roughly a moon-like frame
gframe3 = GCRS(obsgeoloc=[385000., 0, 0]*u.km, obsgeovel=[1, 0, 0]*u.km/u.s)
gcrscoo6 = icoo.transform_to(gframe3) # should be different
assert not allclose(gcrscoo.ra, gcrscoo6.ra, rtol=1e-8, atol=1e-10*u.deg)
assert not allclose(gcrscoo.dec, gcrscoo6.dec, rtol=1e-8, atol=1e-10*u.deg)
icooviag3 = gcrscoo6.transform_to(ICRS) # and now back to the original
assert_allclose(icoo.ra, icooviag3.ra)
assert_allclose(icoo.dec, icooviag3.dec)
@pytest.mark.parametrize('gframe', gcrs_frames)
def test_icrs_gcrs_dist_diff(gframe):
"""
Check that with and without distance give different ICRS<->GCRS answers
"""
gcrsnod = icrs_coords[0].transform_to(gframe)
gcrswd = icrs_coords[1].transform_to(gframe)
# parallax effects should be included, so with and w/o distance should be different
assert not allclose(gcrswd.ra, gcrsnod.ra, rtol=1e-8, atol=1e-10*u.deg)
assert not allclose(gcrswd.dec, gcrsnod.dec, rtol=1e-8, atol=1e-10*u.deg)
# and the distance should transform at least somehow
assert not allclose(gcrswd.distance, icrs_coords[1].distance, rtol=1e-8,
atol=1e-10*u.pc)
def test_cirs_to_altaz():
"""
Check the basic CIRS<->AltAz transforms. More thorough checks implicitly
happen in `test_iau_fullstack`
"""
from .. import EarthLocation
ra, dec, dist = randomly_sample_sphere(200)
cirs = CIRS(ra=ra, dec=dec, obstime='J2000')
crepr = SphericalRepresentation(lon=ra, lat=dec, distance=dist)
cirscart = CIRS(crepr, obstime=cirs.obstime, representation=CartesianRepresentation)
loc = EarthLocation(lat=0*u.deg, lon=0*u.deg, height=0*u.m)
altazframe = AltAz(location=loc, obstime=Time('J2005'))
cirs2 = cirs.transform_to(altazframe).transform_to(cirs)
cirs3 = cirscart.transform_to(altazframe).transform_to(cirs)
# check round-tripping
assert_allclose(cirs.ra, cirs2.ra)
assert_allclose(cirs.dec, cirs2.dec)
assert_allclose(cirs.ra, cirs3.ra)
assert_allclose(cirs.dec, cirs3.dec)
def test_gcrs_itrs():
"""
Check basic GCRS<->ITRS transforms for round-tripping.
"""
ra, dec, _ = randomly_sample_sphere(200)
gcrs = GCRS(ra=ra, dec=dec, obstime='J2000')
gcrs6 = GCRS(ra=ra, dec=dec, obstime='J2006')
gcrs2 = gcrs.transform_to(ITRS).transform_to(gcrs)
gcrs6_2 = gcrs6.transform_to(ITRS).transform_to(gcrs)
assert_allclose(gcrs.ra, gcrs2.ra)
assert_allclose(gcrs.dec, gcrs2.dec)
assert not allclose(gcrs.ra, gcrs6_2.ra)
assert not allclose(gcrs.dec, gcrs6_2.dec)
# also try with the cartesian representation
gcrsc = gcrs.realize_frame(gcrs.data)
gcrsc.representation = CartesianRepresentation
gcrsc2 = gcrsc.transform_to(ITRS).transform_to(gcrsc)
assert_allclose(gcrsc.spherical.lon.deg, gcrsc2.ra.deg)
assert_allclose(gcrsc.spherical.lat, gcrsc2.dec)
def test_cirs_itrs():
"""
Check basic CIRS<->ITRS transforms for round-tripping.
"""
ra, dec, _ = randomly_sample_sphere(200)
cirs = CIRS(ra=ra, dec=dec, obstime='J2000')
cirs6 = CIRS(ra=ra, dec=dec, obstime='J2006')
cirs2 = cirs.transform_to(ITRS).transform_to(cirs)
cirs6_2 = cirs6.transform_to(ITRS).transform_to(cirs) # different obstime
# just check round-tripping
assert_allclose(cirs.ra, cirs2.ra)
assert_allclose(cirs.dec, cirs2.dec)
assert not allclose(cirs.ra, cirs6_2.ra)
assert not allclose(cirs.dec, cirs6_2.dec)
def test_gcrs_cirs():
"""
Check GCRS<->CIRS transforms for round-tripping. More complicated than the
above two because it's multi-hop
"""
ra, dec, _ = randomly_sample_sphere(200)
gcrs = GCRS(ra=ra, dec=dec, obstime='J2000')
gcrs6 = GCRS(ra=ra, dec=dec, obstime='J2006')
gcrs2 = gcrs.transform_to(CIRS).transform_to(gcrs)
gcrs6_2 = gcrs6.transform_to(CIRS).transform_to(gcrs)
assert_allclose(gcrs.ra, gcrs2.ra)
assert_allclose(gcrs.dec, gcrs2.dec)
assert not allclose(gcrs.ra, gcrs6_2.ra)
assert not allclose(gcrs.dec, gcrs6_2.dec)
# now try explicit intermediate pathways and ensure they're all consistent
gcrs3 = gcrs.transform_to(ITRS).transform_to(CIRS).transform_to(ITRS).transform_to(gcrs)
assert_allclose(gcrs.ra, gcrs3.ra)
assert_allclose(gcrs.dec, gcrs3.dec)
gcrs4 = gcrs.transform_to(ICRS).transform_to(CIRS).transform_to(ICRS).transform_to(gcrs)
assert_allclose(gcrs.ra, gcrs4.ra)
assert_allclose(gcrs.dec, gcrs4.dec)
def test_gcrs_altaz():
"""
Check GCRS<->AltAz transforms for round-tripping. Has multiple paths
"""
from .. import EarthLocation
ra, dec, _ = randomly_sample_sphere(1)
gcrs = GCRS(ra=ra[0], dec=dec[0], obstime='J2000')
# check array times sure N-d arrays work
times = Time(np.linspace(2456293.25, 2456657.25, 51) * u.day,
format='jd', scale='utc')
loc = EarthLocation(lon=10 * u.deg, lat=80. * u.deg)
aaframe = AltAz(obstime=times, location=loc)
aa1 = gcrs.transform_to(aaframe)
aa2 = gcrs.transform_to(ICRS).transform_to(CIRS).transform_to(aaframe)
aa3 = gcrs.transform_to(ITRS).transform_to(CIRS).transform_to(aaframe)
# make sure they're all consistent
assert_allclose(aa1.alt, aa2.alt)
assert_allclose(aa1.az, aa2.az)
assert_allclose(aa1.alt, aa3.alt)
assert_allclose(aa1.az, aa3.az)
def test_precessed_geocentric():
assert PrecessedGeocentric().equinox.jd == Time('J2000', scale='utc').jd
gcrs_coo = GCRS(180*u.deg, 2*u.deg, distance=10000*u.km)
pgeo_coo = gcrs_coo.transform_to(PrecessedGeocentric)
assert np.abs(gcrs_coo.ra - pgeo_coo.ra) > 10*u.marcsec
assert np.abs(gcrs_coo.dec - pgeo_coo.dec) > 10*u.marcsec
assert_allclose(gcrs_coo.distance, pgeo_coo.distance)
gcrs_roundtrip = pgeo_coo.transform_to(GCRS)
assert_allclose(gcrs_coo.ra, gcrs_roundtrip.ra)
assert_allclose(gcrs_coo.dec, gcrs_roundtrip.dec)
assert_allclose(gcrs_coo.distance, gcrs_roundtrip.distance)
pgeo_coo2 = gcrs_coo.transform_to(PrecessedGeocentric(equinox='B1850'))
assert np.abs(gcrs_coo.ra - pgeo_coo2.ra) > 1.5*u.deg
assert np.abs(gcrs_coo.dec - pgeo_coo2.dec) > 0.5*u.deg
assert_allclose(gcrs_coo.distance, pgeo_coo2.distance)
gcrs2_roundtrip = pgeo_coo2.transform_to(GCRS)
assert_allclose(gcrs_coo.ra, gcrs2_roundtrip.ra)
assert_allclose(gcrs_coo.dec, gcrs2_roundtrip.dec)
assert_allclose(gcrs_coo.distance, gcrs2_roundtrip.distance)
# shared by parametrized tests below. Some use the whole AltAz, others use just obstime
totest_frames = [AltAz(location=EarthLocation(-90*u.deg, 65*u.deg),
obstime=Time('J2000')), # J2000 is often a default so this might work when others don't
AltAz(location=EarthLocation(120*u.deg, -35*u.deg),
obstime=Time('J2000')),
AltAz(location=EarthLocation(-90*u.deg, 65*u.deg),
obstime=Time('2014-01-01 00:00:00')),
AltAz(location=EarthLocation(-90*u.deg, 65*u.deg),
obstime=Time('2014-08-01 08:00:00')),
AltAz(location=EarthLocation(120*u.deg, -35*u.deg),
obstime=Time('2014-01-01 00:00:00'))
]
MOONDIST = 385000*u.km # approximate moon semi-major orbit axis of moon
MOONDIST_CART = CartesianRepresentation(3**-0.5*MOONDIST, 3**-0.5*MOONDIST, 3**-0.5*MOONDIST)
EARTHECC = 0.017 + 0.005 # roughly earth orbital eccentricity, but with an added tolerance
@pytest.mark.parametrize('testframe', totest_frames)
def test_gcrs_altaz_sunish(testframe):
"""
Sanity-check that the sun is at a reasonable distance from any altaz
"""
sun = get_sun(testframe.obstime)
assert sun.frame.name == 'gcrs'
# the .to(u.au) is not necessary, it just makes the asserts on failure more readable
assert (EARTHECC - 1)*u.au < sun.distance.to(u.au) < (EARTHECC + 1)*u.au
sunaa = sun.transform_to(testframe)
assert (EARTHECC - 1)*u.au < sunaa.distance.to(u.au) < (EARTHECC + 1)*u.au
@pytest.mark.parametrize('testframe', totest_frames)
def test_gcrs_altaz_moonish(testframe):
"""
Sanity-check that an object resembling the moon goes to the right place with
a GCRS->AltAz transformation
"""
moon = GCRS(MOONDIST_CART, obstime=testframe.obstime)
moonaa = moon.transform_to(testframe)
# now check that the distance change is similar to earth radius
assert 1000*u.km < np.abs(moonaa.distance - moon.distance).to(u.au) < 7000*u.km
# now check that it round-trips
moon2 = moonaa.transform_to(moon)
assert_allclose(moon.cartesian.xyz, moon2.cartesian.xyz)
# also should add checks that the alt/az are different for different earth locations
@pytest.mark.parametrize('testframe', totest_frames)
def test_gcrs_altaz_bothroutes(testframe):
"""
Repeat of both the moonish and sunish tests above to make sure the two
routes through the coordinate graph are consistent with each other
"""
sun = get_sun(testframe.obstime)
sunaa_viaicrs = sun.transform_to(ICRS).transform_to(testframe)
sunaa_viaitrs = sun.transform_to(ITRS(obstime=testframe.obstime)).transform_to(testframe)
moon = GCRS(MOONDIST_CART, obstime=testframe.obstime)
moonaa_viaicrs = moon.transform_to(ICRS).transform_to(testframe)
moonaa_viaitrs = moon.transform_to(ITRS(obstime=testframe.obstime)).transform_to(testframe)
assert_allclose(sunaa_viaicrs.cartesian.xyz, sunaa_viaitrs.cartesian.xyz)
assert_allclose(moonaa_viaicrs.cartesian.xyz, moonaa_viaitrs.cartesian.xyz)
@pytest.mark.parametrize('testframe', totest_frames)
def test_cirs_altaz_moonish(testframe):
"""
Sanity-check that an object resembling the moon goes to the right place with
a CIRS<->AltAz transformation
"""
moon = CIRS(MOONDIST_CART, obstime=testframe.obstime)
moonaa = moon.transform_to(testframe)
assert 1000*u.km < np.abs(moonaa.distance - moon.distance).to(u.km) < 7000*u.km
# now check that it round-trips
moon2 = moonaa.transform_to(moon)
assert_allclose(moon.cartesian.xyz, moon2.cartesian.xyz)
@pytest.mark.parametrize('testframe', totest_frames)
def test_cirs_altaz_nodist(testframe):
"""
Check that a UnitSphericalRepresentation coordinate round-trips for the
CIRS<->AltAz transformation.
"""
coo0 = CIRS(UnitSphericalRepresentation(10*u.deg, 20*u.deg), obstime=testframe.obstime)
# check that it round-trips
coo1 = coo0.transform_to(testframe).transform_to(coo0)
assert_allclose(coo0.cartesian.xyz, coo1.cartesian.xyz)
@pytest.mark.parametrize('testframe', totest_frames)
def test_cirs_icrs_moonish(testframe):
"""
check that something like the moon goes to about the right distance from the
ICRS origin when starting from CIRS
"""
moonish = CIRS(MOONDIST_CART, obstime=testframe.obstime)
moonicrs = moonish.transform_to(ICRS)
assert 0.97*u.au < moonicrs.distance < 1.03*u.au
@pytest.mark.parametrize('testframe', totest_frames)
def test_gcrs_icrs_moonish(testframe):
"""
check that something like the moon goes to about the right distance from the
ICRS origin when starting from GCRS
"""
moonish = GCRS(MOONDIST_CART, obstime=testframe.obstime)
moonicrs = moonish.transform_to(ICRS)
assert 0.97*u.au < moonicrs.distance < 1.03*u.au
@pytest.mark.parametrize('testframe', totest_frames)
def test_icrs_gcrscirs_sunish(testframe):
"""
check that the ICRS barycenter goes to about the right distance from various
~geocentric frames (other than testframe)
"""
# slight offset to avoid divide-by-zero errors
icrs = ICRS(0*u.deg, 0*u.deg, distance=10*u.km)
gcrs = icrs.transform_to(GCRS(obstime=testframe.obstime))
assert (EARTHECC - 1)*u.au < gcrs.distance.to(u.au) < (EARTHECC + 1)*u.au
cirs = icrs.transform_to(CIRS(obstime=testframe.obstime))
assert (EARTHECC - 1)*u.au < cirs.distance.to(u.au) < (EARTHECC + 1)*u.au
itrs = icrs.transform_to(ITRS(obstime=testframe.obstime))
assert (EARTHECC - 1)*u.au < itrs.spherical.distance.to(u.au) < (EARTHECC + 1)*u.au
@pytest.mark.parametrize('testframe', totest_frames)
def test_icrs_altaz_moonish(testframe):
"""
Check that something expressed in *ICRS* as being moon-like goes to the
right AltAz distance
"""
# we use epv00 instead of get_sun because get_sun includes aberration
earth_pv_helio, earth_pv_bary = epv00(*get_jd12(testframe.obstime, 'tdb'))
earth_icrs_xyz = earth_pv_bary[0]*u.au
moonoffset = [0, 0, MOONDIST.value]*MOONDIST.unit
moonish_icrs = ICRS(CartesianRepresentation(earth_icrs_xyz + moonoffset))
moonaa = moonish_icrs.transform_to(testframe)
# now check that the distance change is similar to earth radius
assert 1000*u.km < np.abs(moonaa.distance - MOONDIST).to(u.au) < 7000*u.km
def test_gcrs_self_transform_closeby():
"""
Tests GCRS self transform for objects which are nearby and thus
have reasonable parallax.
Moon positions were originally created using JPL DE432s ephemeris.
The two lunar positions (one geocentric, one at a defined location)
are created via a transformation from ICRS to two different GCRS frames.
We test that the GCRS-GCRS self transform can correctly map one GCRS
frame onto the other.
"""
t = Time("2014-12-25T07:00")
moon_geocentric = SkyCoord(GCRS(318.10579159*u.deg,
-11.65281165*u.deg,
365042.64880308*u.km, obstime=t))
# this is the location of the Moon as seen from La Palma
obsgeoloc = [-5592982.59658935, -63054.1948592, 3059763.90102216]*u.m
obsgeovel = [4.59798494, -407.84677071, 0.]*u.m/u.s
moon_lapalma = SkyCoord(GCRS(318.7048445*u.deg,
-11.98761996*u.deg,
369722.8231031*u.km,
obstime=t,
obsgeoloc=obsgeoloc,
obsgeovel=obsgeovel))
transformed = moon_geocentric.transform_to(moon_lapalma.frame)
delta = transformed.separation_3d(moon_lapalma)
assert_allclose(delta, 0.0*u.m, atol=1*u.m)
@pytest.mark.remote_data
@pytest.mark.skipif('not HAS_JPLEPHEM')
def test_ephemerides():
"""
We test that using different ephemerides gives very similar results
for transformations
"""
t = Time("2014-12-25T07:00")
moon = SkyCoord(GCRS(318.10579159*u.deg,
-11.65281165*u.deg,
365042.64880308*u.km, obstime=t))
icrs_frame = ICRS()
hcrs_frame = HCRS(obstime=t)
ecl_frame = HeliocentricTrueEcliptic(equinox=t)
cirs_frame = CIRS(obstime=t)
moon_icrs_builtin = moon.transform_to(icrs_frame)
moon_hcrs_builtin = moon.transform_to(hcrs_frame)
moon_helioecl_builtin = moon.transform_to(ecl_frame)
moon_cirs_builtin = moon.transform_to(cirs_frame)
with solar_system_ephemeris.set('jpl'):
moon_icrs_jpl = moon.transform_to(icrs_frame)
moon_hcrs_jpl = moon.transform_to(hcrs_frame)
moon_helioecl_jpl = moon.transform_to(ecl_frame)
moon_cirs_jpl = moon.transform_to(cirs_frame)
# most transformations should differ by an amount which is
# non-zero but of order milliarcsecs
sep_icrs = moon_icrs_builtin.separation(moon_icrs_jpl)
sep_hcrs = moon_hcrs_builtin.separation(moon_hcrs_jpl)
sep_helioecl = moon_helioecl_builtin.separation(moon_helioecl_jpl)
sep_cirs = moon_cirs_builtin.separation(moon_cirs_jpl)
assert_allclose([sep_icrs, sep_hcrs, sep_helioecl], 0.0*u.deg, atol=10*u.mas)
assert all(sep > 10*u.microarcsecond for sep in (sep_icrs, sep_hcrs, sep_helioecl))
# CIRS should be the same
assert_allclose(sep_cirs, 0.0*u.deg, atol=1*u.microarcsecond)
|
84fbd0e4c43fd3a41c2e94521c386a69526b455058d0beadf2ba86ca7f522406 |
import pytest
from ...tests.helper import assert_quantity_allclose, quantity_allclose
from ... import units as u
from .. import Longitude, Latitude, EarthLocation
from ..sites import get_builtin_sites, get_downloaded_sites, SiteRegistry
def test_builtin_sites():
reg = get_builtin_sites()
greenwich = reg['greenwich']
lon, lat, el = greenwich.to_geodetic()
assert_quantity_allclose(lon, Longitude('0:0:0', unit=u.deg),
atol=10*u.arcsec)
assert_quantity_allclose(lat, Latitude('51:28:40', unit=u.deg),
atol=1*u.arcsec)
assert_quantity_allclose(el, 46*u.m, atol=1*u.m)
names = reg.names
assert 'greenwich' in names
assert 'example_site' in names
with pytest.raises(KeyError) as exc:
reg['nonexistent site']
assert exc.value.args[0] == "Site 'nonexistent site' not in database. Use the 'names' attribute to see available sites."
@pytest.mark.remote_data(source='astropy')
def test_online_sites():
reg = get_downloaded_sites()
keck = reg['keck']
lon, lat, el = keck.to_geodetic()
assert_quantity_allclose(lon, -Longitude('155:28.7', unit=u.deg),
atol=0.001*u.deg)
assert_quantity_allclose(lat, Latitude('19:49.7', unit=u.deg),
atol=0.001*u.deg)
assert_quantity_allclose(el, 4160*u.m, atol=1*u.m)
names = reg.names
assert 'keck' in names
assert 'ctio' in names
with pytest.raises(KeyError) as exc:
reg['nonexistent site']
assert exc.value.args[0] == "Site 'nonexistent site' not in database. Use the 'names' attribute to see available sites."
with pytest.raises(KeyError) as exc:
reg['kec']
assert exc.value.args[0] == "Site 'kec' not in database. Use the 'names' attribute to see available sites. Did you mean one of: 'keck'?'"
@pytest.mark.remote_data(source='astropy')
# this will *try* the online so we have to make it remote_data, even though it
# could fall back on the non-remote version
def test_EarthLocation_basic():
greenwichel = EarthLocation.of_site('greenwich')
lon, lat, el = greenwichel.to_geodetic()
assert_quantity_allclose(lon, Longitude('0:0:0', unit=u.deg),
atol=10*u.arcsec)
assert_quantity_allclose(lat, Latitude('51:28:40', unit=u.deg),
atol=1*u.arcsec)
assert_quantity_allclose(el, 46*u.m, atol=1*u.m)
names = EarthLocation.get_site_names()
assert 'greenwich' in names
assert 'example_site' in names
with pytest.raises(KeyError) as exc:
EarthLocation.of_site('nonexistent site')
assert exc.value.args[0] == "Site 'nonexistent site' not in database. Use EarthLocation.get_site_names to see available sites."
def test_EarthLocation_state_offline():
EarthLocation._site_registry = None
EarthLocation._get_site_registry(force_builtin=True)
assert EarthLocation._site_registry is not None
oldreg = EarthLocation._site_registry
newreg = EarthLocation._get_site_registry()
assert oldreg is newreg
newreg = EarthLocation._get_site_registry(force_builtin=True)
assert oldreg is not newreg
@pytest.mark.remote_data(source='astropy')
def test_EarthLocation_state_online():
EarthLocation._site_registry = None
EarthLocation._get_site_registry(force_download=True)
assert EarthLocation._site_registry is not None
oldreg = EarthLocation._site_registry
newreg = EarthLocation._get_site_registry()
assert oldreg is newreg
newreg = EarthLocation._get_site_registry(force_download=True)
assert oldreg is not newreg
def test_registry():
reg = SiteRegistry()
assert len(reg.names) == 0
names = ['sitea', 'site A']
loc = EarthLocation.from_geodetic(lat=1*u.deg, lon=2*u.deg, height=3*u.km)
reg.add_site(names, loc)
assert len(reg.names) == 2
loc1 = reg['SIteA']
assert loc1 is loc
loc2 = reg['sIte a']
assert loc2 is loc
def test_non_EarthLocation():
"""
A regression test for a typo bug pointed out at the bottom of
https://github.com/astropy/astropy/pull/4042
"""
class EarthLocation2(EarthLocation):
pass
# This lets keeps us from needing to do remote_data
# note that this does *not* mess up the registry for EarthLocation because
# registry is cached on a per-class basis
EarthLocation2._get_site_registry(force_builtin=True)
el2 = EarthLocation2.of_site('greenwich')
assert type(el2) is EarthLocation2
assert el2.info.name == 'Royal Observatory Greenwich'
def check_builtin_matches_remote(download_url=True):
"""
This function checks that the builtin sites registry is consistent with the
remote registry (or a registry at some other location).
Note that current this is *not* run by the testing suite (because it
doesn't start with "test", and is instead meant to be used as a check
before merging changes in astropy-data)
"""
builtin_registry = EarthLocation._get_site_registry(force_builtin=True)
dl_registry = EarthLocation._get_site_registry(force_download=download_url)
in_dl = {}
matches = {}
for name in builtin_registry.names:
in_dl[name] = name in dl_registry
if in_dl[name]:
matches[name] = quantity_allclose(builtin_registry[name], dl_registry[name])
else:
matches[name] = False
if not all(matches.values()):
# this makes sure we actually see which don't match
print("In builtin registry but not in download:")
for name in in_dl:
if not in_dl[name]:
print(' ', name)
print("In both but not the same value:")
for name in matches:
if not matches[name] and in_dl[name]:
print(' ', name, 'builtin:', builtin_registry[name], 'download:', dl_registry[name])
assert False, "Builtin and download registry aren't consistent - failures printed to stdout"
|
f1588d90756a55fac449a59fbf67b37fbecc1839087a459acd966283fd18f282 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for miscellaneous functionality in the `funcs` module
"""
import pytest
import numpy as np
from numpy import testing as npt
from ... import units as u
from ...time import Time
def test_sun():
"""
Test that `get_sun` works and it behaves roughly as it should (in GCRS)
"""
from ..funcs import get_sun
northern_summer_solstice = Time('2010-6-21')
northern_winter_solstice = Time('2010-12-21')
equinox_1 = Time('2010-3-21')
equinox_2 = Time('2010-9-21')
gcrs1 = get_sun(equinox_1)
assert np.abs(gcrs1.dec.deg) < 1
gcrs2 = get_sun(Time([northern_summer_solstice, equinox_2, northern_winter_solstice]))
assert np.all(np.abs(gcrs2.dec - [23.5, 0, -23.5]*u.deg) < 1*u.deg)
def test_concatenate():
from .. import FK5, SkyCoord
from ..funcs import concatenate
fk5 = FK5(1*u.deg, 2*u.deg)
sc = SkyCoord(3*u.deg, 4*u.deg, frame='fk5')
res = concatenate([fk5, sc])
np.testing.assert_allclose(res.ra, [1, 3]*u.deg)
np.testing.assert_allclose(res.dec, [2, 4]*u.deg)
with pytest.raises(TypeError):
concatenate(fk5)
with pytest.raises(TypeError):
concatenate(1*u.deg)
def test_constellations():
from .. import ICRS, FK5, SkyCoord
from ..funcs import get_constellation
inuma = ICRS(9*u.hour, 65*u.deg)
res = get_constellation(inuma)
res_short = get_constellation(inuma, short_name=True)
assert res == 'Ursa Major'
assert res_short == 'UMa'
assert isinstance(res, str) or getattr(res, 'shape', None) == tuple()
# these are taken from the ReadMe for Roman 1987
ras = [9, 23.5, 5.12, 9.4555, 12.8888, 15.6687, 19, 6.2222]
decs = [65, -20, 9.12, -19.9, 22, -12.1234, -40, -81.1234]
shortnames = ['UMa', 'Aqr', 'Ori', 'Hya', 'Com', 'Lib', 'CrA', 'Men']
testcoos = FK5(ras*u.hour, decs*u.deg, equinox='B1950')
npt.assert_equal(get_constellation(testcoos, short_name=True), shortnames)
# test on a SkyCoord, *and* test Boötes, which is special in that it has a
# non-ASCII character
bootest = SkyCoord(15*u.hour, 30*u.deg, frame='icrs')
boores = get_constellation(bootest)
assert boores == u'Boötes'
assert isinstance(boores, str) or getattr(boores, 'shape', None) == tuple()
|
8db9d42f38986f6cfe5efb4d9394f6955637514f889e0aa453357d9d587a8a00 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the SkyCoord class. Note that there are also SkyCoord tests in
test_api_ape5.py
"""
import copy
import pytest
import numpy as np
import numpy.testing as npt
from ... import units as u
from ...tests.helper import (catch_warnings, quantity_allclose,
assert_quantity_allclose as assert_allclose)
from ..representation import REPRESENTATION_CLASSES
from ...coordinates import (ICRS, FK4, FK5, Galactic, SkyCoord, Angle,
SphericalRepresentation, CartesianRepresentation,
UnitSphericalRepresentation, AltAz,
BaseCoordinateFrame, Attribute,
frame_transform_graph, RepresentationMapping)
from ...coordinates import Latitude, EarthLocation
from ...time import Time
from ...utils import minversion, isiterable
from ...utils.compat import NUMPY_LT_1_14
from ...utils.exceptions import AstropyDeprecationWarning
RA = 1.0 * u.deg
DEC = 2.0 * u.deg
C_ICRS = ICRS(RA, DEC)
C_FK5 = C_ICRS.transform_to(FK5)
J2001 = Time('J2001', scale='utc')
def allclose(a, b, rtol=0.0, atol=None):
if atol is None:
atol = 1.e-8 * getattr(a, 'unit', 1.)
return quantity_allclose(a, b, rtol, atol)
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
if HAS_SCIPY and minversion(scipy, '0.12.0', inclusive=False):
OLDER_SCIPY = False
else:
OLDER_SCIPY = True
def test_transform_to():
for frame in (FK5, FK5(equinox=Time('J1975.0')),
FK4, FK4(equinox=Time('J1975.0')),
SkyCoord(RA, DEC, 'fk4', equinox='J1980')):
c_frame = C_ICRS.transform_to(frame)
s_icrs = SkyCoord(RA, DEC, frame='icrs')
s_frame = s_icrs.transform_to(frame)
assert allclose(c_frame.ra, s_frame.ra)
assert allclose(c_frame.dec, s_frame.dec)
assert allclose(c_frame.distance, s_frame.distance)
# set up for parametrized test
rt_sets = []
rt_frames = [ICRS, FK4, FK5, Galactic]
for rt_frame0 in rt_frames:
for rt_frame1 in rt_frames:
for equinox0 in (None, 'J1975.0'):
for obstime0 in (None, 'J1980.0'):
for equinox1 in (None, 'J1975.0'):
for obstime1 in (None, 'J1980.0'):
rt_sets.append((rt_frame0, rt_frame1,
equinox0, equinox1,
obstime0, obstime1))
rt_args = ('frame0', 'frame1', 'equinox0', 'equinox1', 'obstime0', 'obstime1')
@pytest.mark.parametrize(rt_args, rt_sets)
def test_round_tripping(frame0, frame1, equinox0, equinox1, obstime0, obstime1):
"""
Test round tripping out and back using transform_to in every combination.
"""
attrs0 = {'equinox': equinox0, 'obstime': obstime0}
attrs1 = {'equinox': equinox1, 'obstime': obstime1}
# Remove None values
attrs0 = dict((k, v) for k, v in attrs0.items() if v is not None)
attrs1 = dict((k, v) for k, v in attrs1.items() if v is not None)
# Go out and back
sc = SkyCoord(frame0, RA, DEC, **attrs0)
# Keep only frame attributes for frame1
attrs1 = dict((attr, val) for attr, val in attrs1.items()
if attr in frame1.get_frame_attr_names())
sc2 = sc.transform_to(frame1(**attrs1))
# When coming back only keep frame0 attributes for transform_to
attrs0 = dict((attr, val) for attr, val in attrs0.items()
if attr in frame0.get_frame_attr_names())
# also, if any are None, fill in with defaults
for attrnm in frame0.get_frame_attr_names():
if attrs0.get(attrnm, None) is None:
if attrnm == 'obstime' and frame0.get_frame_attr_names()[attrnm] is None:
if 'equinox' in attrs0:
attrs0[attrnm] = attrs0['equinox']
else:
attrs0[attrnm] = frame0.get_frame_attr_names()[attrnm]
sc_rt = sc2.transform_to(frame0(**attrs0))
if frame0 is Galactic:
assert allclose(sc.l, sc_rt.l)
assert allclose(sc.b, sc_rt.b)
else:
assert allclose(sc.ra, sc_rt.ra)
assert allclose(sc.dec, sc_rt.dec)
if equinox0:
assert type(sc.equinox) is Time and sc.equinox == sc_rt.equinox
if obstime0:
assert type(sc.obstime) is Time and sc.obstime == sc_rt.obstime
def test_coord_init_string():
"""
Spherical or Cartesian represenation input coordinates.
"""
sc = SkyCoord('1d 2d')
assert allclose(sc.ra, 1 * u.deg)
assert allclose(sc.dec, 2 * u.deg)
sc = SkyCoord('1d', '2d')
assert allclose(sc.ra, 1 * u.deg)
assert allclose(sc.dec, 2 * u.deg)
sc = SkyCoord('1°2′3″', '2°3′4″')
assert allclose(sc.ra, Angle('1°2′3″'))
assert allclose(sc.dec, Angle('2°3′4″'))
sc = SkyCoord('1°2′3″ 2°3′4″')
assert allclose(sc.ra, Angle('1°2′3″'))
assert allclose(sc.dec, Angle('2°3′4″'))
with pytest.raises(ValueError) as err:
SkyCoord('1d 2d 3d')
assert "Cannot parse first argument data" in str(err)
sc1 = SkyCoord('8 00 00 +5 00 00.0', unit=(u.hour, u.deg), frame='icrs')
assert isinstance(sc1, SkyCoord)
assert allclose(sc1.ra, Angle(120 * u.deg))
assert allclose(sc1.dec, Angle(5 * u.deg))
sc11 = SkyCoord('8h00m00s+5d00m00.0s', unit=(u.hour, u.deg), frame='icrs')
assert isinstance(sc11, SkyCoord)
assert allclose(sc1.ra, Angle(120 * u.deg))
assert allclose(sc1.dec, Angle(5 * u.deg))
sc2 = SkyCoord('8 00 -5 00 00.0', unit=(u.hour, u.deg), frame='icrs')
assert isinstance(sc2, SkyCoord)
assert allclose(sc2.ra, Angle(120 * u.deg))
assert allclose(sc2.dec, Angle(-5 * u.deg))
sc3 = SkyCoord('8 00 -5 00.6', unit=(u.hour, u.deg), frame='icrs')
assert isinstance(sc3, SkyCoord)
assert allclose(sc3.ra, Angle(120 * u.deg))
assert allclose(sc3.dec, Angle(-5.01 * u.deg))
sc4 = SkyCoord('J080000.00-050036.00', unit=(u.hour, u.deg), frame='icrs')
assert isinstance(sc4, SkyCoord)
assert allclose(sc4.ra, Angle(120 * u.deg))
assert allclose(sc4.dec, Angle(-5.01 * u.deg))
sc41 = SkyCoord('J080000+050036', unit=(u.hour, u.deg), frame='icrs')
assert isinstance(sc41, SkyCoord)
assert allclose(sc41.ra, Angle(120 * u.deg))
assert allclose(sc41.dec, Angle(+5.01 * u.deg))
sc5 = SkyCoord('8h00.6m -5d00.6m', unit=(u.hour, u.deg), frame='icrs')
assert isinstance(sc5, SkyCoord)
assert allclose(sc5.ra, Angle(120.15 * u.deg))
assert allclose(sc5.dec, Angle(-5.01 * u.deg))
sc6 = SkyCoord('8h00.6m -5d00.6m', unit=(u.hour, u.deg), frame='fk4')
assert isinstance(sc6, SkyCoord)
assert allclose(sc6.ra, Angle(120.15 * u.deg))
assert allclose(sc6.dec, Angle(-5.01 * u.deg))
sc61 = SkyCoord('8h00.6m-5d00.6m', unit=(u.hour, u.deg), frame='fk4')
assert isinstance(sc61, SkyCoord)
assert allclose(sc6.ra, Angle(120.15 * u.deg))
assert allclose(sc6.dec, Angle(-5.01 * u.deg))
sc61 = SkyCoord('8h00.6-5d00.6', unit=(u.hour, u.deg), frame='fk4')
assert isinstance(sc61, SkyCoord)
assert allclose(sc6.ra, Angle(120.15 * u.deg))
assert allclose(sc6.dec, Angle(-5.01 * u.deg))
sc7 = SkyCoord("J1874221.60+122421.6", unit=u.deg)
assert isinstance(sc7, SkyCoord)
assert allclose(sc7.ra, Angle(187.706 * u.deg))
assert allclose(sc7.dec, Angle(12.406 * u.deg))
with pytest.raises(ValueError):
SkyCoord('8 00 -5 00.6', unit=(u.deg, u.deg), frame='galactic')
def test_coord_init_unit():
"""
Test variations of the unit keyword.
"""
for unit in ('deg', 'deg,deg', ' deg , deg ', u.deg, (u.deg, u.deg),
np.array(['deg', 'deg'])):
sc = SkyCoord(1, 2, unit=unit)
assert allclose(sc.ra, Angle(1 * u.deg))
assert allclose(sc.dec, Angle(2 * u.deg))
for unit in ('hourangle', 'hourangle,hourangle', ' hourangle , hourangle ',
u.hourangle, [u.hourangle, u.hourangle]):
sc = SkyCoord(1, 2, unit=unit)
assert allclose(sc.ra, Angle(15 * u.deg))
assert allclose(sc.dec, Angle(30 * u.deg))
for unit in ('hourangle,deg', (u.hourangle, u.deg)):
sc = SkyCoord(1, 2, unit=unit)
assert allclose(sc.ra, Angle(15 * u.deg))
assert allclose(sc.dec, Angle(2 * u.deg))
for unit in ('deg,deg,deg,deg', [u.deg, u.deg, u.deg, u.deg], None):
with pytest.raises(ValueError) as err:
SkyCoord(1, 2, unit=unit)
assert 'Unit keyword must have one to three unit values' in str(err)
for unit in ('m', (u.m, u.deg), ''):
with pytest.raises(u.UnitsError) as err:
SkyCoord(1, 2, unit=unit)
def test_coord_init_list():
"""
Spherical or Cartesian representation input coordinates.
"""
sc = SkyCoord([('1d', '2d'),
(1 * u.deg, 2 * u.deg),
'1d 2d',
('1°', '2°'),
'1° 2°'], unit='deg')
assert allclose(sc.ra, Angle('1d'))
assert allclose(sc.dec, Angle('2d'))
with pytest.raises(ValueError) as err:
SkyCoord(['1d 2d 3d'])
assert "Cannot parse first argument data" in str(err)
with pytest.raises(ValueError) as err:
SkyCoord([('1d', '2d', '3d')])
assert "Cannot parse first argument data" in str(err)
sc = SkyCoord([1 * u.deg, 1 * u.deg], [2 * u.deg, 2 * u.deg])
assert allclose(sc.ra, Angle('1d'))
assert allclose(sc.dec, Angle('2d'))
with pytest.raises(ValueError) as err:
SkyCoord([1 * u.deg, 2 * u.deg]) # this list is taken as RA w/ missing dec
assert "One or more elements of input sequence does not have a length" in str(err)
def test_coord_init_array():
"""
Input in the form of a list array or numpy array
"""
for a in (['1 2', '3 4'],
[['1', '2'], ['3', '4']],
[[1, 2], [3, 4]]):
sc = SkyCoord(a, unit='deg')
assert allclose(sc.ra - [1, 3] * u.deg, 0 * u.deg)
assert allclose(sc.dec - [2, 4] * u.deg, 0 * u.deg)
sc = SkyCoord(np.array(a), unit='deg')
assert allclose(sc.ra - [1, 3] * u.deg, 0 * u.deg)
assert allclose(sc.dec - [2, 4] * u.deg, 0 * u.deg)
def test_coord_init_representation():
"""
Spherical or Cartesian represenation input coordinates.
"""
coord = SphericalRepresentation(lon=8 * u.deg, lat=5 * u.deg, distance=1 * u.kpc)
sc = SkyCoord(coord, 'icrs')
assert allclose(sc.ra, coord.lon)
assert allclose(sc.dec, coord.lat)
assert allclose(sc.distance, coord.distance)
with pytest.raises(ValueError) as err:
SkyCoord(coord, 'icrs', ra='1d')
assert "conflicts with keyword argument 'ra'" in str(err)
coord = CartesianRepresentation(1 * u.one, 2 * u.one, 3 * u.one)
sc = SkyCoord(coord, 'icrs')
sc_cart = sc.represent_as(CartesianRepresentation)
assert allclose(sc_cart.x, 1.0)
assert allclose(sc_cart.y, 2.0)
assert allclose(sc_cart.z, 3.0)
FRAME_DEPRECATION_WARNING = ("Passing a frame as a positional argument is now "
"deprecated, use the frame= keyword argument "
"instead.")
def test_frame_init():
"""
Different ways of providing the frame.
"""
sc = SkyCoord(RA, DEC, frame='icrs')
assert sc.frame.name == 'icrs'
sc = SkyCoord(RA, DEC, frame=ICRS)
assert sc.frame.name == 'icrs'
with catch_warnings(AstropyDeprecationWarning) as w:
sc = SkyCoord(RA, DEC, 'icrs')
assert sc.frame.name == 'icrs'
assert len(w) == 1
assert str(w[0].message) == FRAME_DEPRECATION_WARNING
with catch_warnings(AstropyDeprecationWarning) as w:
sc = SkyCoord(RA, DEC, ICRS)
assert sc.frame.name == 'icrs'
assert len(w) == 1
assert str(w[0].message) == FRAME_DEPRECATION_WARNING
with catch_warnings(AstropyDeprecationWarning) as w:
sc = SkyCoord('icrs', RA, DEC)
assert sc.frame.name == 'icrs'
assert len(w) == 1
assert str(w[0].message) == FRAME_DEPRECATION_WARNING
with catch_warnings(AstropyDeprecationWarning) as w:
sc = SkyCoord(ICRS, RA, DEC)
assert sc.frame.name == 'icrs'
assert len(w) == 1
assert str(w[0].message) == FRAME_DEPRECATION_WARNING
sc = SkyCoord(sc)
assert sc.frame.name == 'icrs'
sc = SkyCoord(C_ICRS)
assert sc.frame.name == 'icrs'
SkyCoord(C_ICRS, frame='icrs')
assert sc.frame.name == 'icrs'
with pytest.raises(ValueError) as err:
SkyCoord(C_ICRS, frame='galactic')
assert 'Cannot override frame=' in str(err)
def test_attr_inheritance():
"""
When initializing from an existing coord the representation attrs like
equinox should be inherited to the SkyCoord. If there is a conflict
then raise an exception.
"""
sc = SkyCoord(1, 2, frame='icrs', unit='deg', equinox='J1999', obstime='J2001')
sc2 = SkyCoord(sc)
assert sc2.equinox == sc.equinox
assert sc2.obstime == sc.obstime
assert allclose(sc2.ra, sc.ra)
assert allclose(sc2.dec, sc.dec)
assert allclose(sc2.distance, sc.distance)
sc2 = SkyCoord(sc.frame) # Doesn't have equinox there so we get FK4 defaults
assert sc2.equinox != sc.equinox
assert sc2.obstime != sc.obstime
assert allclose(sc2.ra, sc.ra)
assert allclose(sc2.dec, sc.dec)
assert allclose(sc2.distance, sc.distance)
sc = SkyCoord(1, 2, frame='fk4', unit='deg', equinox='J1999', obstime='J2001')
sc2 = SkyCoord(sc)
assert sc2.equinox == sc.equinox
assert sc2.obstime == sc.obstime
assert allclose(sc2.ra, sc.ra)
assert allclose(sc2.dec, sc.dec)
assert allclose(sc2.distance, sc.distance)
sc2 = SkyCoord(sc.frame) # sc.frame has equinox, obstime
assert sc2.equinox == sc.equinox
assert sc2.obstime == sc.obstime
assert allclose(sc2.ra, sc.ra)
assert allclose(sc2.dec, sc.dec)
assert allclose(sc2.distance, sc.distance)
def test_attr_conflicts():
"""
Check conflicts resolution between coordinate attributes and init kwargs.
"""
sc = SkyCoord(1, 2, frame='icrs', unit='deg', equinox='J1999', obstime='J2001')
# OK if attrs both specified but with identical values
SkyCoord(sc, equinox='J1999', obstime='J2001')
# OK because sc.frame doesn't have obstime
SkyCoord(sc.frame, equinox='J1999', obstime='J2100')
# Not OK if attrs don't match
with pytest.raises(ValueError) as err:
SkyCoord(sc, equinox='J1999', obstime='J2002')
assert "Coordinate attribute 'obstime'=" in str(err)
# Same game but with fk4 which has equinox and obstime frame attrs
sc = SkyCoord(1, 2, frame='fk4', unit='deg', equinox='J1999', obstime='J2001')
# OK if attrs both specified but with identical values
SkyCoord(sc, equinox='J1999', obstime='J2001')
# Not OK if SkyCoord attrs don't match
with pytest.raises(ValueError) as err:
SkyCoord(sc, equinox='J1999', obstime='J2002')
assert "Coordinate attribute 'obstime'=" in str(err)
# Not OK because sc.frame has different attrs
with pytest.raises(ValueError) as err:
SkyCoord(sc.frame, equinox='J1999', obstime='J2002')
assert "Coordinate attribute 'obstime'=" in str(err)
def test_frame_attr_getattr():
"""
When accessing frame attributes like equinox, the value should come
from self.frame when that object has the relevant attribute, otherwise
from self.
"""
sc = SkyCoord(1, 2, frame='icrs', unit='deg', equinox='J1999', obstime='J2001')
assert sc.equinox == 'J1999' # Just the raw value (not validated)
assert sc.obstime == 'J2001'
sc = SkyCoord(1, 2, frame='fk4', unit='deg', equinox='J1999', obstime='J2001')
assert sc.equinox == Time('J1999') # Coming from the self.frame object
assert sc.obstime == Time('J2001')
sc = SkyCoord(1, 2, frame='fk4', unit='deg', equinox='J1999')
assert sc.equinox == Time('J1999')
assert sc.obstime == Time('J1999')
def test_to_string():
"""
Basic testing of converting SkyCoord to strings. This just tests
for a single input coordinate and and 1-element list. It does not
test the underlying `Angle.to_string` method itself.
"""
coord = '1h2m3s 1d2m3s'
for wrap in (lambda x: x, lambda x: [x]):
sc = SkyCoord(wrap(coord))
assert sc.to_string() == wrap('15.5125 1.03417')
assert sc.to_string('dms') == wrap('15d30m45s 1d02m03s')
assert sc.to_string('hmsdms') == wrap('01h02m03s +01d02m03s')
with_kwargs = sc.to_string('hmsdms', precision=3, pad=True, alwayssign=True)
assert with_kwargs == wrap('+01h02m03.000s +01d02m03.000s')
def test_seps():
sc1 = SkyCoord(0 * u.deg, 1 * u.deg, frame='icrs')
sc2 = SkyCoord(0 * u.deg, 2 * u.deg, frame='icrs')
sep = sc1.separation(sc2)
assert (sep - 1 * u.deg)/u.deg < 1e-10
with pytest.raises(ValueError):
sc1.separation_3d(sc2)
sc3 = SkyCoord(1 * u.deg, 1 * u.deg, distance=1 * u.kpc, frame='icrs')
sc4 = SkyCoord(1 * u.deg, 1 * u.deg, distance=2 * u.kpc, frame='icrs')
sep3d = sc3.separation_3d(sc4)
assert sep3d == 1 * u.kpc
def test_repr():
sc1 = SkyCoord(0 * u.deg, 1 * u.deg, frame='icrs')
sc2 = SkyCoord(1 * u.deg, 1 * u.deg, frame='icrs', distance=1 * u.kpc)
assert repr(sc1) == ('<SkyCoord (ICRS): (ra, dec) in deg\n'
' ({})>').format(' 0., 1.' if NUMPY_LT_1_14 else
'0., 1.')
assert repr(sc2) == ('<SkyCoord (ICRS): (ra, dec, distance) in (deg, deg, kpc)\n'
' ({})>').format(' 1., 1., 1.' if NUMPY_LT_1_14
else '1., 1., 1.')
sc3 = SkyCoord(0.25 * u.deg, [1, 2.5] * u.deg, frame='icrs')
assert repr(sc3).startswith('<SkyCoord (ICRS): (ra, dec) in deg\n')
sc_default = SkyCoord(0 * u.deg, 1 * u.deg)
assert repr(sc_default) == ('<SkyCoord (ICRS): (ra, dec) in deg\n'
' ({})>').format(' 0., 1.' if NUMPY_LT_1_14
else '0., 1.')
def test_repr_altaz():
sc2 = SkyCoord(1 * u.deg, 1 * u.deg, frame='icrs', distance=1 * u.kpc)
loc = EarthLocation(-2309223 * u.m, -3695529 * u.m, -4641767 * u.m)
time = Time('2005-03-21 00:00:00')
sc4 = sc2.transform_to(AltAz(location=loc, obstime=time))
assert repr(sc4).startswith("<SkyCoord (AltAz: obstime=2005-03-21 00:00:00.000, "
"location=(-2309223.0, -3695529.0, "
"-4641767.0) m, pressure=0.0 hPa, "
"temperature=0.0 deg_C, relative_humidity=0, "
"obswl=1.0 micron): (az, alt, distance) in "
"(deg, deg, m)\n")
def test_ops():
"""
Tests miscellaneous operations like `len`
"""
sc = SkyCoord(0 * u.deg, 1 * u.deg, frame='icrs')
sc_arr = SkyCoord(0 * u.deg, [1, 2] * u.deg, frame='icrs')
sc_empty = SkyCoord([] * u.deg, [] * u.deg, frame='icrs')
assert sc.isscalar
assert not sc_arr.isscalar
assert not sc_empty.isscalar
with pytest.raises(TypeError):
len(sc)
assert len(sc_arr) == 2
assert len(sc_empty) == 0
assert bool(sc)
assert bool(sc_arr)
assert not bool(sc_empty)
assert sc_arr[0].isscalar
assert len(sc_arr[:1]) == 1
# A scalar shouldn't be indexable
with pytest.raises(TypeError):
sc[0:]
# but it should be possible to just get an item
sc_item = sc[()]
assert sc_item.shape == ()
# and to turn it into an array
sc_1d = sc[np.newaxis]
assert sc_1d.shape == (1,)
with pytest.raises(TypeError):
iter(sc)
assert not isiterable(sc)
assert isiterable(sc_arr)
assert isiterable(sc_empty)
it = iter(sc_arr)
assert next(it).dec == sc_arr[0].dec
assert next(it).dec == sc_arr[1].dec
with pytest.raises(StopIteration):
next(it)
def test_none_transform():
"""
Ensure that transforming from a SkyCoord with no frame provided works like
ICRS
"""
sc = SkyCoord(0 * u.deg, 1 * u.deg)
sc_arr = SkyCoord(0 * u.deg, [1, 2] * u.deg)
sc2 = sc.transform_to(ICRS)
assert sc.ra == sc2.ra and sc.dec == sc2.dec
sc5 = sc.transform_to('fk5')
assert sc5.ra == sc2.transform_to('fk5').ra
sc_arr2 = sc_arr.transform_to(ICRS)
sc_arr5 = sc_arr.transform_to('fk5')
npt.assert_array_equal(sc_arr5.ra, sc_arr2.transform_to('fk5').ra)
def test_position_angle():
c1 = SkyCoord(0*u.deg, 0*u.deg)
c2 = SkyCoord(1*u.deg, 0*u.deg)
assert_allclose(c1.position_angle(c2) - 90.0 * u.deg, 0*u.deg)
c3 = SkyCoord(1*u.deg, 0.1*u.deg)
assert c1.position_angle(c3) < 90*u.deg
c4 = SkyCoord(0*u.deg, 1*u.deg)
assert_allclose(c1.position_angle(c4), 0*u.deg)
carr1 = SkyCoord(0*u.deg, [0, 1, 2]*u.deg)
carr2 = SkyCoord([-1, -2, -3]*u.deg, [0.1, 1.1, 2.1]*u.deg)
res = carr1.position_angle(carr2)
assert res.shape == (3,)
assert np.all(res < 360*u.degree)
assert np.all(res > 270*u.degree)
cicrs = SkyCoord(0*u.deg, 0*u.deg, frame='icrs')
cfk5 = SkyCoord(1*u.deg, 0*u.deg, frame='fk5')
# because of the frame transform, it's just a *bit* more than 90 degrees
assert cicrs.position_angle(cfk5) > 90.0 * u.deg
assert cicrs.position_angle(cfk5) < 91.0 * u.deg
def test_position_angle_directly():
"""Regression check for #3800: position_angle should accept floats."""
from ..angle_utilities import position_angle
result = position_angle(10., 20., 10., 20.)
assert result.unit is u.radian
assert result.value == 0.
def test_sep_pa_equivalence():
"""Regression check for bug in #5702.
PA and separation from object 1 to 2 should be consistent with those
from 2 to 1
"""
cfk5 = SkyCoord(1*u.deg, 0*u.deg, frame='fk5')
cfk5B1950 = SkyCoord(1*u.deg, 0*u.deg, frame='fk5', equinox='B1950')
# test with both default and explicit equinox #5722 and #3106
sep_forward = cfk5.separation(cfk5B1950)
sep_backward = cfk5B1950.separation(cfk5)
assert sep_forward != 0 and sep_backward != 0
assert_allclose(sep_forward, sep_backward)
posang_forward = cfk5.position_angle(cfk5B1950)
posang_backward = cfk5B1950.position_angle(cfk5)
assert posang_forward != 0 and posang_backward != 0
assert 179 < (posang_forward - posang_backward).wrap_at(360*u.deg).degree < 181
dcfk5 = SkyCoord(1*u.deg, 0*u.deg, frame='fk5', distance=1*u.pc)
dcfk5B1950 = SkyCoord(1*u.deg, 0*u.deg, frame='fk5', equinox='B1950',
distance=1.*u.pc)
sep3d_forward = dcfk5.separation_3d(dcfk5B1950)
sep3d_backward = dcfk5B1950.separation_3d(dcfk5)
assert sep3d_forward != 0 and sep3d_backward != 0
assert_allclose(sep3d_forward, sep3d_backward)
def test_table_to_coord():
"""
Checks "end-to-end" use of `Table` with `SkyCoord` - the `Quantity`
initializer is the intermediary that translate the table columns into
something coordinates understands.
(Regression test for #1762 )
"""
from ...table import Table, Column
t = Table()
t.add_column(Column(data=[1, 2, 3], name='ra', unit=u.deg))
t.add_column(Column(data=[4, 5, 6], name='dec', unit=u.deg))
c = SkyCoord(t['ra'], t['dec'])
assert allclose(c.ra.to(u.deg), [1, 2, 3] * u.deg)
assert allclose(c.dec.to(u.deg), [4, 5, 6] * u.deg)
def assert_quantities_allclose(coord, q1s, attrs):
"""
Compare two tuples of quantities. This assumes that the values in q1 are of
order(1) and uses atol=1e-13, rtol=0. It also asserts that the units of the
two quantities are the *same*, in order to check that the representation
output has the expected units.
"""
q2s = [getattr(coord, attr) for attr in attrs]
assert len(q1s) == len(q2s)
for q1, q2 in zip(q1s, q2s):
assert q1.shape == q2.shape
assert allclose(q1, q2, rtol=0, atol=1e-13 * q1.unit)
# Sets of inputs corresponding to Galactic frame
base_unit_attr_sets = [
('spherical', u.karcsec, u.karcsec, u.kpc, Latitude, 'l', 'b', 'distance'),
('unitspherical', u.karcsec, u.karcsec, None, Latitude, 'l', 'b', None),
('physicsspherical', u.karcsec, u.karcsec, u.kpc, Angle, 'phi', 'theta', 'r'),
('cartesian', u.km, u.km, u.km, u.Quantity, 'u', 'v', 'w'),
('cylindrical', u.km, u.karcsec, u.km, Angle, 'rho', 'phi', 'z')
]
units_attr_sets = []
for base_unit_attr_set in base_unit_attr_sets:
repr_name = base_unit_attr_set[0]
for representation in (repr_name, REPRESENTATION_CLASSES[repr_name]):
for c1, c2, c3 in ((1, 2, 3), ([1], [2], [3])):
for arrayify in True, False:
if arrayify:
c1 = np.array(c1)
c2 = np.array(c2)
c3 = np.array(c3)
units_attr_sets.append(base_unit_attr_set + (representation, c1, c2, c3))
units_attr_args = ('repr_name', 'unit1', 'unit2', 'unit3', 'cls2', 'attr1', 'attr2', 'attr3', 'representation', 'c1', 'c2', 'c3')
@pytest.mark.parametrize(units_attr_args,
[x for x in units_attr_sets if x[0] != 'unitspherical'])
def test_skycoord_three_components(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3,
representation, c1, c2, c3):
"""
Tests positional inputs using components (COMP1, COMP2, COMP3)
and various representations. Use weird units and Galactic frame.
"""
sc = SkyCoord(Galactic, c1, c2, c3, unit=(unit1, unit2, unit3),
representation=representation)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
(attr1, attr2, attr3))
sc = SkyCoord(1000*c1*u.Unit(unit1/1000), cls2(c2, unit=unit2),
1000*c3*u.Unit(unit3/1000), Galactic,
unit=(unit1, unit2, unit3), representation=representation)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
(attr1, attr2, attr3))
kwargs = {attr3: c3}
sc = SkyCoord(Galactic, c1, c2, unit=(unit1, unit2, unit3),
representation=representation, **kwargs)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
(attr1, attr2, attr3))
kwargs = {attr1: c1, attr2: c2, attr3: c3}
sc = SkyCoord(Galactic, unit=(unit1, unit2, unit3),
representation=representation, **kwargs)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
(attr1, attr2, attr3))
@pytest.mark.parametrize(units_attr_args,
[x for x in units_attr_sets
if x[0] in ('spherical', 'unitspherical')])
def test_skycoord_spherical_two_components(repr_name, unit1, unit2, unit3, cls2,
attr1, attr2, attr3, representation, c1, c2, c3):
"""
Tests positional inputs using components (COMP1, COMP2) for spherical
representations. Use weird units and Galactic frame.
"""
sc = SkyCoord(Galactic, c1, c2, unit=(unit1, unit2),
representation=representation)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2),
(attr1, attr2))
sc = SkyCoord(1000*c1*u.Unit(unit1/1000), cls2(c2, unit=unit2),
Galactic,
unit=(unit1, unit2, unit3), representation=representation)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2),
(attr1, attr2))
kwargs = {attr1: c1, attr2: c2}
sc = SkyCoord(Galactic, unit=(unit1, unit2),
representation=representation, **kwargs)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2),
(attr1, attr2))
@pytest.mark.parametrize(units_attr_args,
[x for x in units_attr_sets if x[0] != 'unitspherical'])
def test_galactic_three_components(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3,
representation, c1, c2, c3):
"""
Tests positional inputs using components (COMP1, COMP2, COMP3)
and various representations. Use weird units and Galactic frame.
"""
sc = Galactic(1000*c1*u.Unit(unit1/1000), cls2(c2, unit=unit2),
1000*c3*u.Unit(unit3/1000), representation=representation)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
(attr1, attr2, attr3))
kwargs = {attr3: c3*unit3}
sc = Galactic(c1*unit1, c2*unit2,
representation=representation, **kwargs)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
(attr1, attr2, attr3))
kwargs = {attr1: c1*unit1, attr2: c2*unit2, attr3: c3*unit3}
sc = Galactic(representation=representation, **kwargs)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2, c3*unit3),
(attr1, attr2, attr3))
@pytest.mark.parametrize(units_attr_args,
[x for x in units_attr_sets
if x[0] in ('spherical', 'unitspherical')])
def test_galactic_spherical_two_components(repr_name, unit1, unit2, unit3, cls2,
attr1, attr2, attr3, representation, c1, c2, c3):
"""
Tests positional inputs using components (COMP1, COMP2) for spherical
representations. Use weird units and Galactic frame.
"""
sc = Galactic(1000*c1*u.Unit(unit1/1000), cls2(c2, unit=unit2), representation=representation)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2), (attr1, attr2))
sc = Galactic(c1*unit1, c2*unit2, representation=representation)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2), (attr1, attr2))
kwargs = {attr1: c1*unit1, attr2: c2*unit2}
sc = Galactic(representation=representation, **kwargs)
assert_quantities_allclose(sc, (c1*unit1, c2*unit2), (attr1, attr2))
@pytest.mark.parametrize(('repr_name', 'unit1', 'unit2', 'unit3', 'cls2', 'attr1', 'attr2', 'attr3'),
[x for x in base_unit_attr_sets if x[0] != 'unitspherical'])
def test_skycoord_coordinate_input(repr_name, unit1, unit2, unit3, cls2, attr1, attr2, attr3):
c1, c2, c3 = 1, 2, 3
sc = SkyCoord([(c1, c2, c3)], unit=(unit1, unit2, unit3), representation=repr_name,
frame='galactic')
assert_quantities_allclose(sc, ([c1]*unit1, [c2]*unit2, [c3]*unit3), (attr1, attr2, attr3))
c1, c2, c3 = 1*unit1, 2*unit2, 3*unit3
sc = SkyCoord([(c1, c2, c3)], representation=repr_name, frame='galactic')
assert_quantities_allclose(sc, ([1]*unit1, [2]*unit2, [3]*unit3), (attr1, attr2, attr3))
def test_skycoord_string_coordinate_input():
sc = SkyCoord('01 02 03 +02 03 04', unit='deg', representation='unitspherical')
assert_quantities_allclose(sc, (Angle('01:02:03', unit='deg'),
Angle('02:03:04', unit='deg')),
('ra', 'dec'))
sc = SkyCoord(['01 02 03 +02 03 04'], unit='deg', representation='unitspherical')
assert_quantities_allclose(sc, (Angle(['01:02:03'], unit='deg'),
Angle(['02:03:04'], unit='deg')),
('ra', 'dec'))
def test_units():
sc = SkyCoord(1, 2, 3, unit='m', representation='cartesian') # All get meters
assert sc.x.unit is u.m
assert sc.y.unit is u.m
assert sc.z.unit is u.m
sc = SkyCoord(1, 2*u.km, 3, unit='m', representation='cartesian') # All get u.m
assert sc.x.unit is u.m
assert sc.y.unit is u.m
assert sc.z.unit is u.m
sc = SkyCoord(1, 2, 3, unit=u.m, representation='cartesian') # All get u.m
assert sc.x.unit is u.m
assert sc.y.unit is u.m
assert sc.z.unit is u.m
sc = SkyCoord(1, 2, 3, unit='m, km, pc', representation='cartesian')
assert_quantities_allclose(sc, (1*u.m, 2*u.km, 3*u.pc), ('x', 'y', 'z'))
with pytest.raises(u.UnitsError) as err:
SkyCoord(1, 2, 3, unit=(u.m, u.m), representation='cartesian')
assert 'should have matching physical types' in str(err)
SkyCoord(1, 2, 3, unit=(u.m, u.km, u.pc), representation='cartesian')
assert_quantities_allclose(sc, (1*u.m, 2*u.km, 3*u.pc), ('x', 'y', 'z'))
@pytest.mark.xfail
def test_units_known_fail():
# should fail but doesn't => corner case oddity
with pytest.raises(u.UnitsError):
SkyCoord(1, 2, 3, unit=u.deg, representation='spherical')
def test_nodata_failure():
with pytest.raises(ValueError):
SkyCoord()
@pytest.mark.parametrize(('mode', 'origin'), [('wcs', 0),
('all', 0),
('all', 1)])
def test_wcs_methods(mode, origin):
from ...wcs import WCS
from ...utils.data import get_pkg_data_contents
from ...wcs.utils import pixel_to_skycoord
header = get_pkg_data_contents('../../wcs/tests/maps/1904-66_TAN.hdr', encoding='binary')
wcs = WCS(header)
ref = SkyCoord(0.1 * u.deg, -89. * u.deg, frame='icrs')
xp, yp = ref.to_pixel(wcs, mode=mode, origin=origin)
# WCS is in FK5 so we need to transform back to ICRS
new = pixel_to_skycoord(xp, yp, wcs, mode=mode, origin=origin).transform_to('icrs')
assert_allclose(new.ra.degree, ref.ra.degree)
assert_allclose(new.dec.degree, ref.dec.degree)
# also try to round-trip with `from_pixel`
scnew = SkyCoord.from_pixel(xp, yp, wcs, mode=mode, origin=origin).transform_to('icrs')
assert_allclose(scnew.ra.degree, ref.ra.degree)
assert_allclose(scnew.dec.degree, ref.dec.degree)
# Also make sure the right type comes out
class SkyCoord2(SkyCoord):
pass
scnew2 = SkyCoord2.from_pixel(xp, yp, wcs, mode=mode, origin=origin)
assert scnew.__class__ is SkyCoord
assert scnew2.__class__ is SkyCoord2
def test_frame_attr_transform_inherit():
"""
Test that frame attributes get inherited as expected during transform.
Driven by #3106.
"""
c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK5)
c2 = c.transform_to(FK4)
assert c2.equinox.value == 'B1950.000'
assert c2.obstime.value == 'B1950.000'
c2 = c.transform_to(FK4(equinox='J1975', obstime='J1980'))
assert c2.equinox.value == 'J1975.000'
assert c2.obstime.value == 'J1980.000'
c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK4)
c2 = c.transform_to(FK5)
assert c2.equinox.value == 'J2000.000'
assert c2.obstime is None
c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK4, obstime='J1980')
c2 = c.transform_to(FK5)
assert c2.equinox.value == 'J2000.000'
assert c2.obstime.value == 'J1980.000'
c = SkyCoord(1 * u.deg, 2 * u.deg, frame=FK4, equinox='J1975', obstime='J1980')
c2 = c.transform_to(FK5)
assert c2.equinox.value == 'J1975.000'
assert c2.obstime.value == 'J1980.000'
c2 = c.transform_to(FK5(equinox='J1990'))
assert c2.equinox.value == 'J1990.000'
assert c2.obstime.value == 'J1980.000'
# The work-around for #5722
c = SkyCoord(1 * u.deg, 2 * u.deg, frame='fk5')
c1 = SkyCoord(1 * u.deg, 2 * u.deg, frame='fk5', equinox='B1950.000')
c2 = c1.transform_to(c)
assert not c2.is_equivalent_frame(c) # counterintuitive, but documented
assert c2.equinox.value == 'B1950.000'
c3 = c1.transform_to(c, merge_attributes=False)
assert c3.equinox.value == 'J2000.000'
assert c3.is_equivalent_frame(c)
def test_deepcopy():
c1 = SkyCoord(1 * u.deg, 2 * u.deg)
c2 = copy.copy(c1)
c3 = copy.deepcopy(c1)
c4 = SkyCoord([1, 2] * u.m, [2, 3] * u.m, [3, 4] * u.m, representation='cartesian', frame='fk5',
obstime='J1999.9', equinox='J1988.8')
c5 = copy.deepcopy(c4)
assert np.all(c5.x == c4.x) # and y and z
assert c5.frame.name == c4.frame.name
assert c5.obstime == c4.obstime
assert c5.equinox == c4.equinox
assert c5.representation == c4.representation
def test_no_copy():
c1 = SkyCoord(np.arange(10.) * u.hourangle, np.arange(20., 30.) * u.deg)
c2 = SkyCoord(c1, copy=False)
# Note: c1.ra and c2.ra will *not* share memory, as these are recalculated
# to be in "preferred" units. See discussion in #4883.
assert np.may_share_memory(c1.data.lon, c2.data.lon)
c3 = SkyCoord(c1, copy=True)
assert not np.may_share_memory(c1.data.lon, c3.data.lon)
def test_immutable():
c1 = SkyCoord(1 * u.deg, 2 * u.deg)
with pytest.raises(AttributeError):
c1.ra = 3.0
c1.foo = 42
assert c1.foo == 42
@pytest.mark.skipif(str('not HAS_SCIPY'))
@pytest.mark.skipif(str('OLDER_SCIPY'))
def test_search_around():
"""
Test the search_around_* methods
Here we don't actually test the values are right, just that the methods of
SkyCoord work. The accuracy tests are in ``test_matching.py``
"""
from ...utils import NumpyRNGContext
with NumpyRNGContext(987654321):
sc1 = SkyCoord(np.random.rand(20) * 360.*u.degree,
(np.random.rand(20) * 180. - 90.)*u.degree)
sc2 = SkyCoord(np.random.rand(100) * 360. * u.degree,
(np.random.rand(100) * 180. - 90.)*u.degree)
sc1ds = SkyCoord(ra=sc1.ra, dec=sc1.dec, distance=np.random.rand(20)*u.kpc)
sc2ds = SkyCoord(ra=sc2.ra, dec=sc2.dec, distance=np.random.rand(100)*u.kpc)
idx1_sky, idx2_sky, d2d_sky, d3d_sky = sc1.search_around_sky(sc2, 10*u.deg)
idx1_3d, idx2_3d, d2d_3d, d3d_3d = sc1ds.search_around_3d(sc2ds, 250*u.pc)
def test_init_with_frame_instance_keyword():
# Frame instance
c1 = SkyCoord(3 * u.deg, 4 * u.deg,
frame=FK5(equinox='J2010'))
assert c1.equinox == Time('J2010')
# Frame instance with data (data gets ignored)
c2 = SkyCoord(3 * u.deg, 4 * u.deg,
frame=FK5(1. * u.deg, 2 * u.deg,
equinox='J2010'))
assert c2.equinox == Time('J2010')
assert allclose(c2.ra.degree, 3)
assert allclose(c2.dec.degree, 4)
# SkyCoord instance
c3 = SkyCoord(3 * u.deg, 4 * u.deg, frame=c1)
assert c3.equinox == Time('J2010')
# Check duplicate arguments
with pytest.raises(ValueError) as exc:
c = SkyCoord(3 * u.deg, 4 * u.deg, frame=FK5(equinox='J2010'), equinox='J2001')
assert exc.value.args[0] == ("cannot specify frame attribute "
"'equinox' directly in SkyCoord "
"since a frame instance was passed in")
def test_init_with_frame_instance_positional():
# Frame instance
with pytest.raises(ValueError) as exc:
c1 = SkyCoord(3 * u.deg, 4 * u.deg, FK5(equinox='J2010'))
assert exc.value.args[0] == ("FK5 instance cannot be passed as a "
"positional argument for the frame, "
"pass it using the frame= keyword "
"instead.")
# Positional frame instance with data raises exception
with pytest.raises(ValueError) as exc:
SkyCoord(3 * u.deg, 4 * u.deg, FK5(1. * u.deg, 2 * u.deg, equinox='J2010'))
assert exc.value.args[0] == ("FK5 instance cannot be passed as a "
"positional argument for the frame, "
"pass it using the frame= keyword "
"instead.")
# Positional SkyCoord instance (for frame) raises exception
with pytest.raises(ValueError) as exc:
SkyCoord(3 * u.deg, 4 * u.deg, SkyCoord(1. * u.deg, 2 * u.deg, equinox='J2010'))
assert exc.value.args[0] == ("SkyCoord instance cannot be passed as a "
"positional argument for the frame, "
"pass it using the frame= keyword "
"instead.")
def test_guess_from_table():
from ...table import Table, Column
from ...utils import NumpyRNGContext
tab = Table()
with NumpyRNGContext(987654321):
tab.add_column(Column(data=np.random.rand(1000), unit='deg', name='RA[J2000]'))
tab.add_column(Column(data=np.random.rand(1000), unit='deg', name='DEC[J2000]'))
sc = SkyCoord.guess_from_table(tab)
npt.assert_array_equal(sc.ra.deg, tab['RA[J2000]'])
npt.assert_array_equal(sc.dec.deg, tab['DEC[J2000]'])
# try without units in the table
tab['RA[J2000]'].unit = None
tab['DEC[J2000]'].unit = None
# should fail if not given explicitly
with pytest.raises(u.UnitsError):
sc2 = SkyCoord.guess_from_table(tab)
# but should work if provided
sc2 = SkyCoord.guess_from_table(tab, unit=u.deg)
npt.assert_array_equal(sc.ra.deg, tab['RA[J2000]'])
npt.assert_array_equal(sc.dec.deg, tab['DEC[J2000]'])
# should fail if two options are available - ambiguity bad!
tab.add_column(Column(data=np.random.rand(1000), name='RA_J1900'))
with pytest.raises(ValueError) as excinfo:
sc3 = SkyCoord.guess_from_table(tab, unit=u.deg)
assert 'J1900' in excinfo.value.args[0] and 'J2000' in excinfo.value.args[0]
# should also fail if user specifies something already in the table, but
# should succeed even if the user has to give one of the components
tab.remove_column('RA_J1900')
with pytest.raises(ValueError):
sc3 = SkyCoord.guess_from_table(tab, ra=tab['RA[J2000]'], unit=u.deg)
oldra = tab['RA[J2000]']
tab.remove_column('RA[J2000]')
sc3 = SkyCoord.guess_from_table(tab, ra=oldra, unit=u.deg)
npt.assert_array_equal(sc3.ra.deg, oldra)
npt.assert_array_equal(sc3.dec.deg, tab['DEC[J2000]'])
# check a few non-ICRS/spherical systems
x, y, z = np.arange(3).reshape(3, 1) * u.pc
l, b = np.arange(2).reshape(2, 1) * u.deg
tabcart = Table([x, y, z], names=('x', 'y', 'z'))
tabgal = Table([b, l], names=('b', 'l'))
sc_cart = SkyCoord.guess_from_table(tabcart, representation='cartesian')
npt.assert_array_equal(sc_cart.x, x)
npt.assert_array_equal(sc_cart.y, y)
npt.assert_array_equal(sc_cart.z, z)
sc_gal = SkyCoord.guess_from_table(tabgal, frame='galactic')
npt.assert_array_equal(sc_gal.l, l)
npt.assert_array_equal(sc_gal.b, b)
# also try some column names that *end* with the attribute name
tabgal['b'].name = 'gal_b'
tabgal['l'].name = 'gal_l'
SkyCoord.guess_from_table(tabgal, frame='galactic')
tabgal['gal_b'].name = 'blob'
tabgal['gal_l'].name = 'central'
with pytest.raises(ValueError):
SkyCoord.guess_from_table(tabgal, frame='galactic')
def test_skycoord_list_creation():
"""
Test that SkyCoord can be created in a reasonable way with lists of SkyCoords
(regression for #2702)
"""
sc = SkyCoord(ra=[1, 2, 3]*u.deg, dec=[4, 5, 6]*u.deg)
sc0 = sc[0]
sc2 = sc[2]
scnew = SkyCoord([sc0, sc2])
assert np.all(scnew.ra == [1, 3]*u.deg)
assert np.all(scnew.dec == [4, 6]*u.deg)
# also check ranges
sc01 = sc[:2]
scnew2 = SkyCoord([sc01, sc2])
assert np.all(scnew2.ra == sc.ra)
assert np.all(scnew2.dec == sc.dec)
# now try with a mix of skycoord, frame, and repr objects
frobj = ICRS(2*u.deg, 5*u.deg)
reprobj = UnitSphericalRepresentation(3*u.deg, 6*u.deg)
scnew3 = SkyCoord([sc0, frobj, reprobj])
assert np.all(scnew3.ra == sc.ra)
assert np.all(scnew3.dec == sc.dec)
# should *fail* if different frame attributes or types are passed in
scfk5_j2000 = SkyCoord(1*u.deg, 4*u.deg, frame='fk5')
with pytest.raises(ValueError):
SkyCoord([sc0, scfk5_j2000])
scfk5_j2010 = SkyCoord(1*u.deg, 4*u.deg, frame='fk5', equinox='J2010')
with pytest.raises(ValueError):
SkyCoord([scfk5_j2000, scfk5_j2010])
# but they should inherit if they're all consistent
scfk5_2_j2010 = SkyCoord(2*u.deg, 5*u.deg, frame='fk5', equinox='J2010')
scfk5_3_j2010 = SkyCoord(3*u.deg, 6*u.deg, frame='fk5', equinox='J2010')
scnew4 = SkyCoord([scfk5_j2010, scfk5_2_j2010, scfk5_3_j2010])
assert np.all(scnew4.ra == sc.ra)
assert np.all(scnew4.dec == sc.dec)
assert scnew4.equinox == Time('J2010')
def test_nd_skycoord_to_string():
c = SkyCoord(np.ones((2, 2)), 1, unit=('deg', 'deg'))
ts = c.to_string()
assert np.all(ts.shape == c.shape)
assert np.all(ts == u'1 1')
def test_equiv_skycoord():
sci1 = SkyCoord(1*u.deg, 2*u.deg, frame='icrs')
sci2 = SkyCoord(1*u.deg, 3*u.deg, frame='icrs')
assert sci1.is_equivalent_frame(sci1)
assert sci1.is_equivalent_frame(sci2)
assert sci1.is_equivalent_frame(ICRS())
assert not sci1.is_equivalent_frame(FK5())
with pytest.raises(TypeError):
sci1.is_equivalent_frame(10)
scf1 = SkyCoord(1*u.deg, 2*u.deg, frame='fk5')
scf2 = SkyCoord(1*u.deg, 2*u.deg, frame='fk5', equinox='J2005')
# obstime is *not* an FK5 attribute, but we still want scf1 and scf3 to come
# to come out different because they're part of SkyCoord
scf3 = SkyCoord(1*u.deg, 2*u.deg, frame='fk5', obstime='J2005')
assert scf1.is_equivalent_frame(scf1)
assert not scf1.is_equivalent_frame(sci1)
assert scf1.is_equivalent_frame(FK5())
assert not scf1.is_equivalent_frame(scf2)
assert scf2.is_equivalent_frame(FK5(equinox='J2005'))
assert not scf3.is_equivalent_frame(scf1)
assert not scf3.is_equivalent_frame(FK5(equinox='J2005'))
def test_constellations():
# the actual test for accuracy is in test_funcs - this is just meant to make
# sure we get sensible answers
sc = SkyCoord(135*u.deg, 65*u.deg)
assert sc.get_constellation() == 'Ursa Major'
assert sc.get_constellation(short_name=True) == 'UMa'
scs = SkyCoord([135]*2*u.deg, [65]*2*u.deg)
npt.assert_equal(scs.get_constellation(), ['Ursa Major']*2)
npt.assert_equal(scs.get_constellation(short_name=True), ['UMa']*2)
@pytest.mark.remote_data
def test_constellations_with_nameresolve():
assert SkyCoord.from_name('And I').get_constellation(short_name=True) == 'And'
# you'd think "And ..." should be in Andromeda. But you'd be wrong.
assert SkyCoord.from_name('And VI').get_constellation() == 'Pegasus'
# maybe it's because And VI isn't really a galaxy?
assert SkyCoord.from_name('And XXII').get_constellation() == 'Pisces'
assert SkyCoord.from_name('And XXX').get_constellation() == 'Cassiopeia'
# ok maybe not
# ok, but at least some of the others do make sense...
assert SkyCoord.from_name('Coma Cluster').get_constellation(short_name=True) == 'Com'
assert SkyCoord.from_name('UMa II').get_constellation() == 'Ursa Major'
assert SkyCoord.from_name('Triangulum Galaxy').get_constellation() == 'Triangulum'
def test_getitem_representation():
"""
Make sure current representation survives __getitem__ even if different
from data representation.
"""
sc = SkyCoord([1, 1] * u.deg, [2, 2] * u.deg)
sc.representation = 'cartesian'
assert sc[0].representation is CartesianRepresentation
def test_spherical_offsets():
i00 = SkyCoord(0*u.arcmin, 0*u.arcmin, frame='icrs')
i01 = SkyCoord(0*u.arcmin, 1*u.arcmin, frame='icrs')
i10 = SkyCoord(1*u.arcmin, 0*u.arcmin, frame='icrs')
i11 = SkyCoord(1*u.arcmin, 1*u.arcmin, frame='icrs')
i22 = SkyCoord(2*u.arcmin, 2*u.arcmin, frame='icrs')
dra, ddec = i00.spherical_offsets_to(i01)
assert_allclose(dra, 0*u.arcmin)
assert_allclose(ddec, 1*u.arcmin)
dra, ddec = i00.spherical_offsets_to(i10)
assert_allclose(dra, 1*u.arcmin)
assert_allclose(ddec, 0*u.arcmin)
dra, ddec = i10.spherical_offsets_to(i01)
assert_allclose(dra, -1*u.arcmin)
assert_allclose(ddec, 1*u.arcmin)
dra, ddec = i11.spherical_offsets_to(i22)
assert_allclose(ddec, 1*u.arcmin)
assert 0*u.arcmin < dra < 1*u.arcmin
fk5 = SkyCoord(0*u.arcmin, 0*u.arcmin, frame='fk5')
with pytest.raises(ValueError):
# different frames should fail
i00.spherical_offsets_to(fk5)
i1deg = ICRS(1*u.deg, 1*u.deg)
dra, ddec = i00.spherical_offsets_to(i1deg)
assert_allclose(dra, 1*u.deg)
assert_allclose(ddec, 1*u.deg)
# make sure an abbreviated array-based version of the above also works
i00s = SkyCoord([0]*4*u.arcmin, [0]*4*u.arcmin, frame='icrs')
i01s = SkyCoord([0]*4*u.arcmin, np.arange(4)*u.arcmin, frame='icrs')
dra, ddec = i00s.spherical_offsets_to(i01s)
assert_allclose(dra, 0*u.arcmin)
assert_allclose(ddec, np.arange(4)*u.arcmin)
def test_frame_attr_changes():
"""
This tests the case where a frame is added with a new frame attribute after
a SkyCoord has been created. This is necessary because SkyCoords get the
attributes set at creation time, but the set of attributes can change as
frames are added or removed from the transform graph. This makes sure that
everything continues to work consistently.
"""
sc_before = SkyCoord(1*u.deg, 2*u.deg, frame='icrs')
assert 'fakeattr' not in dir(sc_before)
class FakeFrame(BaseCoordinateFrame):
fakeattr = Attribute()
# doesn't matter what this does as long as it just puts the frame in the
# transform graph
transset = (ICRS, FakeFrame, lambda c, f: c)
frame_transform_graph.add_transform(*transset)
try:
assert 'fakeattr' in dir(sc_before)
assert sc_before.fakeattr is None
sc_after1 = SkyCoord(1*u.deg, 2*u.deg, frame='icrs')
assert 'fakeattr' in dir(sc_after1)
assert sc_after1.fakeattr is None
sc_after2 = SkyCoord(1*u.deg, 2*u.deg, frame='icrs', fakeattr=1)
assert sc_after2.fakeattr == 1
finally:
frame_transform_graph.remove_transform(*transset)
assert 'fakeattr' not in dir(sc_before)
assert 'fakeattr' not in dir(sc_after1)
assert 'fakeattr' not in dir(sc_after2)
def test_cache_clear_sc():
from .. import SkyCoord
i = SkyCoord(1*u.deg, 2*u.deg)
# Add an in frame units version of the rep to the cache.
repr(i)
assert len(i.cache['representation']) == 2
i.cache.clear()
assert len(i.cache['representation']) == 0
def test_set_attribute_exceptions():
"""Ensure no attrbute for any frame can be set directly.
Though it is fine if the current frame does not have it."""
sc = SkyCoord(1.*u.deg, 2.*u.deg, frame='fk5')
assert hasattr(sc.frame, 'equinox')
with pytest.raises(AttributeError):
sc.equinox = 'B1950'
assert sc.relative_humidity is None
sc.relative_humidity = 0.5
assert sc.relative_humidity == 0.5
assert not hasattr(sc.frame, 'relative_humidity')
def test_extra_attributes():
"""Ensure any extra attributes are dealt with correctly.
Regression test against #5743.
"""
obstime_string = ['2017-01-01T00:00', '2017-01-01T00:10']
obstime = Time(obstime_string)
sc = SkyCoord([5, 10], [20, 30], unit=u.deg, obstime=obstime_string)
assert not hasattr(sc.frame, 'obstime')
assert type(sc.obstime) is Time
assert sc.obstime.shape == (2,)
assert np.all(sc.obstime == obstime)
# ensure equivalency still works for more than one obstime.
assert sc.is_equivalent_frame(sc)
sc_1 = sc[1]
assert sc_1.obstime == obstime[1]
# Transforming to FK4 should use sc.obstime.
sc_fk4 = sc.transform_to('fk4')
assert np.all(sc_fk4.frame.obstime == obstime)
# And transforming back should not loose it.
sc2 = sc_fk4.transform_to('icrs')
assert not hasattr(sc2.frame, 'obstime')
assert np.all(sc2.obstime == obstime)
# Ensure obstime get taken from the SkyCoord if passed in directly.
# (regression test for #5749).
sc3 = SkyCoord([0., 1.], [2., 3.], unit='deg', frame=sc)
assert np.all(sc3.obstime == obstime)
# Finally, check that we can delete such attributes.
del sc3.obstime
assert sc3.obstime is None
def test_apply_space_motion():
# use this 12 year period because it's a multiple of 4 to avoid the quirks
# of leap years while having 2 leap seconds in it
t1 = Time('2000-01-01T00:00')
t2 = Time('2012-01-01T00:00')
# Check a very simple case first:
frame = ICRS(ra=10.*u.deg, dec=0*u.deg,
distance=10.*u.pc,
pm_ra_cosdec=0.1*u.deg/u.yr,
pm_dec=0*u.mas/u.yr,
radial_velocity=0*u.km/u.s)
# Cases that should work (just testing input for now):
c1 = SkyCoord(frame, obstime=t1, pressure=101*u.kPa)
applied1 = c1.apply_space_motion(new_obstime=t2)
applied2 = c1.apply_space_motion(dt=12*u.year)
assert isinstance(applied1.frame, c1.frame.__class__)
assert isinstance(applied2.frame, c1.frame.__class__)
assert_allclose(applied1.ra, applied2.ra)
assert_allclose(applied1.pm_ra, applied2.pm_ra)
assert_allclose(applied1.dec, applied2.dec)
assert_allclose(applied1.distance, applied2.distance)
# ensure any frame attributes that were there before get passed through
assert applied1.pressure == c1.pressure
# there were 2 leap seconds between 2000 and 2010, so the difference in
# the two forms of time evolution should be ~2 sec
adt = np.abs(applied2.obstime - applied1.obstime)
assert 1.9*u.second < adt.to(u.second) < 2.1*u.second
c2 = SkyCoord(frame)
applied3 = c2.apply_space_motion(dt=6*u.year)
assert isinstance(applied3.frame, c1.frame.__class__)
assert applied3.obstime is None
# this should *not* be .6 deg due to space-motion on a sphere, but it
# should be fairly close
assert 0.5*u.deg < applied3.ra-c1.ra < .7*u.deg
# the two cases should only match somewhat due to it being space motion, but
# they should be at least this close
assert quantity_allclose(applied1.ra-c1.ra, (applied3.ra-c1.ra)*2, atol=1e-3*u.deg)
# but *not* this close
assert not quantity_allclose(applied1.ra-c1.ra, (applied3.ra-c1.ra)*2, atol=1e-4*u.deg)
with pytest.raises(ValueError):
c2.apply_space_motion(new_obstime=t2)
def test_custom_frame_skycoord():
# also regression check for the case from #7069
class BlahBleeBlopFrame(BaseCoordinateFrame):
default_representation = SphericalRepresentation
# without a differential, SkyCoord creation fails
# default_differential = SphericalDifferential
_frame_specific_representation_info = {
'spherical': [
RepresentationMapping('lon', 'lon', 'recommended'),
RepresentationMapping('lat', 'lat', 'recommended'),
RepresentationMapping('distance', 'radius', 'recommended')
]
}
SkyCoord(lat=1*u.deg, lon=2*u.deg, frame=BlahBleeBlopFrame)
def test_user_friendly_pm_error():
"""
This checks that a more user-friendly error message is raised for the user
if they pass, e.g., pm_ra instead of pm_ra_cosdec
"""
with pytest.raises(ValueError) as e:
SkyCoord(ra=150*u.deg, dec=-11*u.deg,
pm_ra=100*u.mas/u.yr, pm_dec=10*u.mas/u.yr)
assert 'pm_ra_cosdec' in str(e.value)
with pytest.raises(ValueError) as e:
SkyCoord(l=150*u.deg, b=-11*u.deg,
pm_l=100*u.mas/u.yr, pm_b=10*u.mas/u.yr,
frame='galactic')
assert 'pm_l_cosb' in str(e.value)
# The special error should not turn on here:
with pytest.raises(ValueError) as e:
SkyCoord(x=1*u.pc, y=2*u.pc, z=3*u.pc,
pm_ra=100*u.mas/u.yr, pm_dec=10*u.mas/u.yr,
representation_type='cartesian')
assert 'pm_ra_cosdec' not in str(e.value)
|
1a56fb176fb808046afeb5cbae475b3b1ec0f9cfbd6872d3fe76d23669f71aaf | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This includes tests for the Distance class and related calculations
"""
import pytest
import numpy as np
from numpy import testing as npt
from ... import units as u
from ...tests.helper import quantity_allclose
from .. import Longitude, Latitude, Distance, CartesianRepresentation
from ..builtin_frames import ICRS, Galactic
try:
import scipy # pylint: disable=W0611
except ImportError:
HAS_SCIPY = False
else:
HAS_SCIPY = True
def test_distances():
"""
Tests functionality for Coordinate class distances and cartesian
transformations.
"""
'''
Distances can also be specified, and allow for a full 3D definition of a
coordinate.
'''
# try all the different ways to initialize a Distance
distance = Distance(12, u.parsec)
Distance(40, unit=u.au)
Distance(value=5, unit=u.kpc)
# need to provide a unit
with pytest.raises(u.UnitsError):
Distance(12)
# standard units are pre-defined
npt.assert_allclose(distance.lyr, 39.138765325702551)
npt.assert_allclose(distance.km, 370281309776063.0)
# Coordinate objects can be assigned a distance object, giving them a full
# 3D position
c = Galactic(l=158.558650*u.degree, b=-43.350066*u.degree,
distance=Distance(12, u.parsec))
# or initialize distances via redshifts - this is actually tested in the
# function below that checks for scipy. This is kept here as an example
# c.distance = Distance(z=0.2) # uses current cosmology
# with whatever your preferred cosmology may be
# c.distance = Distance(z=0.2, cosmology=WMAP5)
# Coordinate objects can be initialized with a distance using special
# syntax
c1 = Galactic(l=158.558650*u.deg, b=-43.350066*u.deg, distance=12 * u.kpc)
# Coordinate objects can be instantiated with cartesian coordinates
# Internally they will immediately be converted to two angles + a distance
cart = CartesianRepresentation(x=2 * u.pc, y=4 * u.pc, z=8 * u.pc)
c2 = Galactic(cart)
sep12 = c1.separation_3d(c2)
# returns a *3d* distance between the c1 and c2 coordinates
# not that this does *not*
assert isinstance(sep12, Distance)
npt.assert_allclose(sep12.pc, 12005.784163916317, 10)
'''
All spherical coordinate systems with distances can be converted to
cartesian coordinates.
'''
cartrep2 = c2.cartesian
assert isinstance(cartrep2.x, u.Quantity)
npt.assert_allclose(cartrep2.x.value, 2)
npt.assert_allclose(cartrep2.y.value, 4)
npt.assert_allclose(cartrep2.z.value, 8)
# with no distance, the unit sphere is assumed when converting to cartesian
c3 = Galactic(l=158.558650*u.degree, b=-43.350066*u.degree, distance=None)
unitcart = c3.cartesian
npt.assert_allclose(((unitcart.x**2 + unitcart.y**2 +
unitcart.z**2)**0.5).value, 1.0)
# TODO: choose between these when CartesianRepresentation gets a definite
# decision on whether or not it gets __add__
#
# CartesianRepresentation objects can be added and subtracted, which are
# vector/elementwise they can also be given as arguments to a coordinate
# system
# csum = ICRS(c1.cartesian + c2.cartesian)
csumrep = CartesianRepresentation(c1.cartesian.xyz + c2.cartesian.xyz)
csum = ICRS(csumrep)
npt.assert_allclose(csumrep.x.value, -8.12016610185)
npt.assert_allclose(csumrep.y.value, 3.19380597435)
npt.assert_allclose(csumrep.z.value, -8.2294483707)
npt.assert_allclose(csum.ra.degree, 158.529401774)
npt.assert_allclose(csum.dec.degree, -43.3235825777)
npt.assert_allclose(csum.distance.kpc, 11.9942200501)
@pytest.mark.skipif(str('not HAS_SCIPY'))
def test_distances_scipy():
"""
The distance-related tests that require scipy due to the cosmology
module needing scipy integration routines
"""
from ...cosmology import WMAP5
# try different ways to initialize a Distance
d4 = Distance(z=0.23) # uses default cosmology - as of writing, WMAP7
npt.assert_allclose(d4.z, 0.23, rtol=1e-8)
d5 = Distance(z=0.23, cosmology=WMAP5)
npt.assert_allclose(d5.compute_z(WMAP5), 0.23, rtol=1e-8)
d6 = Distance(z=0.23, cosmology=WMAP5, unit=u.km)
npt.assert_allclose(d6.value, 3.5417046898762366e+22)
def test_distance_change():
ra = Longitude("4:08:15.162342", unit=u.hour)
dec = Latitude("-41:08:15.162342", unit=u.degree)
c1 = ICRS(ra, dec, Distance(1, unit=u.kpc))
oldx = c1.cartesian.x.value
assert (oldx - 0.35284083171901953) < 1e-10
# first make sure distances are immutible
with pytest.raises(AttributeError):
c1.distance = Distance(2, unit=u.kpc)
# now x should increase with a bigger distance increases
c2 = ICRS(ra, dec, Distance(2, unit=u.kpc))
assert c2.cartesian.x.value == oldx * 2
def test_distance_is_quantity():
"""
test that distance behaves like a proper quantity
"""
Distance(2 * u.kpc)
d = Distance([2, 3.1], u.kpc)
assert d.shape == (2,)
a = d.view(np.ndarray)
q = d.view(u.Quantity)
a[0] = 1.2
q.value[1] = 5.4
assert d[0].value == 1.2
assert d[1].value == 5.4
q = u.Quantity(d, copy=True)
q.value[1] = 0
assert q.value[1] == 0
assert d.value[1] != 0
# regression test against #2261
d = Distance([2 * u.kpc, 250. * u.pc])
assert d.unit is u.kpc
assert np.all(d.value == np.array([2., 0.25]))
def test_distmod():
d = Distance(10, u.pc)
assert d.distmod.value == 0
d = Distance(distmod=20)
assert d.distmod.value == 20
assert d.kpc == 100
d = Distance(distmod=-1., unit=u.au)
npt.assert_allclose(d.value, 1301442.9440836983)
with pytest.raises(ValueError):
d = Distance(value=d, distmod=20)
with pytest.raises(ValueError):
d = Distance(z=.23, distmod=20)
# check the Mpc/kpc/pc behavior
assert Distance(distmod=1).unit == u.pc
assert Distance(distmod=11).unit == u.kpc
assert Distance(distmod=26).unit == u.Mpc
assert Distance(distmod=-21).unit == u.AU
# if an array, uses the mean of the log of the distances
assert Distance(distmod=[1, 11, 26]).unit == u.kpc
def test_parallax():
d = Distance(parallax=1*u.arcsecond)
assert d.pc == 1.
with pytest.raises(ValueError):
d = Distance(15*u.pc, parallax=20*u.milliarcsecond)
with pytest.raises(ValueError):
d = Distance(parallax=20*u.milliarcsecond, distmod=20)
# array
plx = [1, 10, 100.]*u.mas
d = Distance(parallax=plx)
assert quantity_allclose(d.pc, [1000., 100., 10.])
assert quantity_allclose(plx, d.parallax)
def test_distance_in_coordinates():
"""
test that distances can be created from quantities and that cartesian
representations come out right
"""
ra = Longitude("4:08:15.162342", unit=u.hour)
dec = Latitude("-41:08:15.162342", unit=u.degree)
coo = ICRS(ra, dec, distance=2*u.kpc)
cart = coo.cartesian
assert isinstance(cart.xyz, u.Quantity)
def test_negative_distance():
""" Test optional kwarg allow_negative """
with pytest.raises(ValueError):
Distance([-2, 3.1], u.kpc)
with pytest.raises(ValueError):
Distance([-2, -3.1], u.kpc)
with pytest.raises(ValueError):
Distance(-2, u.kpc)
d = Distance(-2, u.kpc, allow_negative=True)
assert d.value == -2
def test_distance_comparison():
"""Ensure comparisons of distances work (#2206, #2250)"""
a = Distance(15*u.kpc)
b = Distance(15*u.kpc)
assert a == b
c = Distance(1.*u.Mpc)
assert a < c
def test_distance_to_quantity_when_not_units_of_length():
"""Any operatation that leaves units other than those of length
should turn a distance into a quantity (#2206, #2250)"""
d = Distance(15*u.kpc)
twice = 2.*d
assert isinstance(twice, Distance)
area = 4.*np.pi*d**2
assert area.unit.is_equivalent(u.m**2)
assert not isinstance(area, Distance)
assert type(area) is u.Quantity
|
c81f988ab2b04e532c8fadf5fd2ba3c4e2f023becf0a53dff914ae6e9710a15a | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test initialization of angles not already covered by the API tests"""
import pickle
import pytest
import numpy as np
from ..earth import EarthLocation, ELLIPSOIDS
from ..angles import Longitude, Latitude
from ...tests.helper import quantity_allclose
from ... import units as u
from ...time import Time
from ... import constants
from ..name_resolve import NameResolveError
def allclose_m14(a, b, rtol=1.e-14, atol=None):
if atol is None:
atol = 1.e-14 * getattr(a, 'unit', 1)
return quantity_allclose(a, b, rtol, atol)
def allclose_m8(a, b, rtol=1.e-8, atol=None):
if atol is None:
atol = 1.e-8 * getattr(a, 'unit', 1)
return quantity_allclose(a, b, rtol, atol)
def isclose_m14(val, ref):
return np.array([allclose_m14(v, r) for (v, r) in zip(val, ref)])
def isclose_m8(val, ref):
return np.array([allclose_m8(v, r) for (v, r) in zip(val, ref)])
def vvd(val, valok, dval, func, test, status):
"""Mimic routine of erfa/src/t_erfa_c.c (to help copy & paste)"""
assert quantity_allclose(val, valok * val.unit, atol=dval * val.unit)
def test_gc2gd():
"""Test that we reproduce erfa/src/t_erfa_c.c t_gc2gd"""
x, y, z = (2e6, 3e6, 5.244e6)
status = 0 # help for copy & paste of vvd
location = EarthLocation.from_geocentric(x, y, z, u.m)
e, p, h = location.to_geodetic('WGS84')
e, p, h = e.to(u.radian), p.to(u.radian), h.to(u.m)
vvd(e, 0.98279372324732907, 1e-14, "eraGc2gd", "e2", status)
vvd(p, 0.97160184820607853, 1e-14, "eraGc2gd", "p2", status)
vvd(h, 331.41731754844348, 1e-8, "eraGc2gd", "h2", status)
e, p, h = location.to_geodetic('GRS80')
e, p, h = e.to(u.radian), p.to(u.radian), h.to(u.m)
vvd(e, 0.98279372324732907, 1e-14, "eraGc2gd", "e2", status)
vvd(p, 0.97160184820607853, 1e-14, "eraGc2gd", "p2", status)
vvd(h, 331.41731754844348, 1e-8, "eraGc2gd", "h2", status)
e, p, h = location.to_geodetic('WGS72')
e, p, h = e.to(u.radian), p.to(u.radian), h.to(u.m)
vvd(e, 0.98279372324732907, 1e-14, "eraGc2gd", "e3", status)
vvd(p, 0.97160181811015119, 1e-14, "eraGc2gd", "p3", status)
vvd(h, 333.27707261303181, 1e-8, "eraGc2gd", "h3", status)
def test_gd2gc():
"""Test that we reproduce erfa/src/t_erfa_c.c t_gd2gc"""
e = 3.1 * u.rad
p = -0.5 * u.rad
h = 2500.0 * u.m
status = 0 # help for copy & paste of vvd
location = EarthLocation.from_geodetic(e, p, h, ellipsoid='WGS84')
xyz = tuple(v.to(u.m) for v in location.to_geocentric())
vvd(xyz[0], -5599000.5577049947, 1e-7, "eraGd2gc", "0/1", status)
vvd(xyz[1], 233011.67223479203, 1e-7, "eraGd2gc", "1/1", status)
vvd(xyz[2], -3040909.4706983363, 1e-7, "eraGd2gc", "2/1", status)
location = EarthLocation.from_geodetic(e, p, h, ellipsoid='GRS80')
xyz = tuple(v.to(u.m) for v in location.to_geocentric())
vvd(xyz[0], -5599000.5577260984, 1e-7, "eraGd2gc", "0/2", status)
vvd(xyz[1], 233011.6722356703, 1e-7, "eraGd2gc", "1/2", status)
vvd(xyz[2], -3040909.4706095476, 1e-7, "eraGd2gc", "2/2", status)
location = EarthLocation.from_geodetic(e, p, h, ellipsoid='WGS72')
xyz = tuple(v.to(u.m) for v in location.to_geocentric())
vvd(xyz[0], -5598998.7626301490, 1e-7, "eraGd2gc", "0/3", status)
vvd(xyz[1], 233011.5975297822, 1e-7, "eraGd2gc", "1/3", status)
vvd(xyz[2], -3040908.6861467111, 1e-7, "eraGd2gc", "2/3", status)
class TestInput():
def setup(self):
self.lon = Longitude([0., 45., 90., 135., 180., -180, -90, -45], u.deg,
wrap_angle=180*u.deg)
self.lat = Latitude([+0., 30., 60., +90., -90., -60., -30., 0.], u.deg)
self.h = u.Quantity([0.1, 0.5, 1.0, -0.5, -1.0, +4.2, -11., -.1], u.m)
self.location = EarthLocation.from_geodetic(self.lon, self.lat, self.h)
self.x, self.y, self.z = self.location.to_geocentric()
def test_default_ellipsoid(self):
assert self.location.ellipsoid == EarthLocation._ellipsoid
def test_geo_attributes(self):
assert all(np.all(_1 == _2)
for _1, _2 in zip(self.location.geodetic,
self.location.to_geodetic()))
assert all(np.all(_1 == _2)
for _1, _2 in zip(self.location.geocentric,
self.location.to_geocentric()))
def test_attribute_classes(self):
"""Test that attribute classes are correct (and not EarthLocation)"""
assert type(self.location.x) is u.Quantity
assert type(self.location.y) is u.Quantity
assert type(self.location.z) is u.Quantity
assert type(self.location.lon) is Longitude
assert type(self.location.lat) is Latitude
assert type(self.location.height) is u.Quantity
def test_input(self):
"""Check input is parsed correctly"""
# units of length should be assumed geocentric
geocentric = EarthLocation(self.x, self.y, self.z)
assert np.all(geocentric == self.location)
geocentric2 = EarthLocation(self.x.value, self.y.value, self.z.value,
self.x.unit)
assert np.all(geocentric2 == self.location)
geodetic = EarthLocation(self.lon, self.lat, self.h)
assert np.all(geodetic == self.location)
geodetic2 = EarthLocation(self.lon.to_value(u.degree),
self.lat.to_value(u.degree),
self.h.to_value(u.m))
assert np.all(geodetic2 == self.location)
geodetic3 = EarthLocation(self.lon, self.lat)
assert allclose_m14(geodetic3.lon.value,
self.location.lon.value)
assert allclose_m14(geodetic3.lat.value,
self.location.lat.value)
assert not np.any(isclose_m14(geodetic3.height.value,
self.location.height.value))
geodetic4 = EarthLocation(self.lon, self.lat, self.h[-1])
assert allclose_m14(geodetic4.lon.value,
self.location.lon.value)
assert allclose_m14(geodetic4.lat.value,
self.location.lat.value)
assert allclose_m14(geodetic4.height[-1].value,
self.location.height[-1].value)
assert not np.any(isclose_m14(geodetic4.height[:-1].value,
self.location.height[:-1].value))
# check length unit preservation
geocentric5 = EarthLocation(self.x, self.y, self.z, u.pc)
assert geocentric5.unit is u.pc
assert geocentric5.x.unit is u.pc
assert geocentric5.height.unit is u.pc
assert allclose_m14(geocentric5.x.to_value(self.x.unit), self.x.value)
geodetic5 = EarthLocation(self.lon, self.lat, self.h.to(u.pc))
assert geodetic5.unit is u.pc
assert geodetic5.x.unit is u.pc
assert geodetic5.height.unit is u.pc
assert allclose_m14(geodetic5.x.to_value(self.x.unit), self.x.value)
def test_invalid_input(self):
"""Check invalid input raises exception"""
# incomprehensible by either raises TypeError
with pytest.raises(TypeError):
EarthLocation(self.lon, self.y, self.z)
# wrong units
with pytest.raises(u.UnitsError):
EarthLocation.from_geocentric(self.lon, self.lat, self.lat)
# inconsistent units
with pytest.raises(u.UnitsError):
EarthLocation.from_geocentric(self.h, self.lon, self.lat)
# floats without a unit
with pytest.raises(TypeError):
EarthLocation.from_geocentric(self.x.value, self.y.value,
self.z.value)
# inconsistent shape
with pytest.raises(ValueError):
EarthLocation.from_geocentric(self.x, self.y, self.z[:5])
# inconsistent units
with pytest.raises(u.UnitsError):
EarthLocation.from_geodetic(self.x, self.y, self.z)
# inconsistent shape
with pytest.raises(ValueError):
EarthLocation.from_geodetic(self.lon, self.lat, self.h[:5])
def test_slicing(self):
# test on WGS72 location, so we can check the ellipsoid is passed on
locwgs72 = EarthLocation.from_geodetic(self.lon, self.lat, self.h,
ellipsoid='WGS72')
loc_slice1 = locwgs72[4]
assert isinstance(loc_slice1, EarthLocation)
assert loc_slice1.unit is locwgs72.unit
assert loc_slice1.ellipsoid == locwgs72.ellipsoid == 'WGS72'
assert not loc_slice1.shape
with pytest.raises(TypeError):
loc_slice1[0]
with pytest.raises(IndexError):
len(loc_slice1)
loc_slice2 = locwgs72[4:6]
assert isinstance(loc_slice2, EarthLocation)
assert len(loc_slice2) == 2
assert loc_slice2.unit is locwgs72.unit
assert loc_slice2.ellipsoid == locwgs72.ellipsoid
assert loc_slice2.shape == (2,)
loc_x = locwgs72['x']
assert type(loc_x) is u.Quantity
assert loc_x.shape == locwgs72.shape
assert loc_x.unit is locwgs72.unit
def test_invalid_ellipsoid(self):
# unknown ellipsoid
with pytest.raises(ValueError):
EarthLocation.from_geodetic(self.lon, self.lat, self.h,
ellipsoid='foo')
with pytest.raises(TypeError):
EarthLocation(self.lon, self.lat, self.h, ellipsoid='foo')
with pytest.raises(ValueError):
self.location.ellipsoid = 'foo'
with pytest.raises(ValueError):
self.location.to_geodetic('foo')
@pytest.mark.parametrize('ellipsoid', ELLIPSOIDS)
def test_ellipsoid(self, ellipsoid):
"""Test that different ellipsoids are understood, and differ"""
# check that heights differ for different ellipsoids
# need different tolerance, since heights are relative to ~6000 km
lon, lat, h = self.location.to_geodetic(ellipsoid)
if ellipsoid == self.location.ellipsoid:
assert allclose_m8(h.value, self.h.value)
else:
# Some heights are very similar for some; some lon, lat identical.
assert not np.all(isclose_m8(h.value, self.h.value))
# given lon, lat, height, check that x,y,z differ
location = EarthLocation.from_geodetic(self.lon, self.lat, self.h,
ellipsoid=ellipsoid)
if ellipsoid == self.location.ellipsoid:
assert allclose_m14(location.z.value, self.z.value)
else:
assert not np.all(isclose_m14(location.z.value, self.z.value))
def test_to_value(self):
loc = self.location
loc_ndarray = loc.view(np.ndarray)
assert np.all(loc.value == loc_ndarray)
loc2 = self.location.to(u.km)
loc2_ndarray = np.empty_like(loc_ndarray)
for coo in 'x', 'y', 'z':
loc2_ndarray[coo] = loc_ndarray[coo] / 1000.
assert np.all(loc2.value == loc2_ndarray)
loc2_value = self.location.to_value(u.km)
assert np.all(loc2_value == loc2_ndarray)
def test_pickling():
"""Regression test against #4304."""
el = EarthLocation(0.*u.m, 6000*u.km, 6000*u.km)
s = pickle.dumps(el)
el2 = pickle.loads(s)
assert el == el2
def test_repr_latex():
"""
Regression test for issue #4542
"""
somelocation = EarthLocation(lon='149:3:57.9', lat='-31:16:37.3')
somelocation._repr_latex_()
somelocation2 = EarthLocation(lon=[1., 2.]*u.deg, lat=[-1., 9.]*u.deg)
somelocation2._repr_latex_()
@pytest.mark.remote_data
def test_of_address():
# no match
with pytest.raises(NameResolveError):
EarthLocation.of_address("lkjasdflkja")
# just a location
loc = EarthLocation.of_address("New York, NY")
assert quantity_allclose(loc.lat, 40.7128*u.degree)
assert quantity_allclose(loc.lon, -74.0059*u.degree)
assert np.allclose(loc.height.value, 0.)
# a location and height
loc = EarthLocation.of_address("New York, NY", get_height=True)
assert quantity_allclose(loc.lat, 40.7128*u.degree)
assert quantity_allclose(loc.lon, -74.0059*u.degree)
assert quantity_allclose(loc.height, 10.438659669*u.meter, atol=1.*u.cm)
def test_geodetic_tuple():
lat = 2*u.deg
lon = 10*u.deg
height = 100*u.m
el = EarthLocation.from_geodetic(lat=lat, lon=lon, height=height)
res1 = el.to_geodetic()
res2 = el.geodetic
assert res1.lat == res2.lat and quantity_allclose(res1.lat, lat)
assert res1.lon == res2.lon and quantity_allclose(res1.lon, lon)
assert res1.height == res2.height and quantity_allclose(res1.height, height)
def test_gravitational_redshift():
someloc = EarthLocation(lon=-87.7*u.deg, lat=37*u.deg)
sometime = Time('2017-8-21 18:26:40')
zg0 = someloc.gravitational_redshift(sometime)
# should be of order ~few mm/s change per week
zg_week = someloc.gravitational_redshift(sometime + 7 * u.day)
assert 1.*u.mm/u.s < abs(zg_week - zg0) < 1*u.cm/u.s
# ~cm/s over a half-year
zg_halfyear = someloc.gravitational_redshift(sometime + 0.5 * u.yr)
assert 1*u.cm/u.s < abs(zg_halfyear - zg0) < 1*u.dm/u.s
# but when back to the same time in a year, should be tenths of mm
# even over decades
zg_year = someloc.gravitational_redshift(sometime - 20 * u.year)
assert .1*u.mm/u.s < abs(zg_year - zg0) < 1*u.mm/u.s
# Check mass adjustments.
# If Jupiter and the moon are ignored, effect should be off by ~ .5 mm/s
masses = {'sun': constants.G*constants.M_sun,
'jupiter': 0*constants.G*u.kg,
'moon': 0*constants.G*u.kg}
zg_moonjup = someloc.gravitational_redshift(sometime, masses=masses)
assert .1*u.mm/u.s < abs(zg_moonjup - zg0) < 1*u.mm/u.s
# Check that simply not including the bodies gives the same result.
assert zg_moonjup == someloc.gravitational_redshift(sometime,
bodies=('sun',))
# And that earth can be given, even not as last argument
assert zg_moonjup == someloc.gravitational_redshift(
sometime, bodies=('earth', 'sun',))
# If the earth is also ignored, effect should be off by ~ 20 cm/s
# This also tests the conversion of kg to gravitational units.
masses['earth'] = 0*u.kg
zg_moonjupearth = someloc.gravitational_redshift(sometime, masses=masses)
assert 1*u.dm/u.s < abs(zg_moonjupearth - zg0) < 1*u.m/u.s
# If all masses are zero, redshift should be 0 as well.
masses['sun'] = 0*u.kg
assert someloc.gravitational_redshift(sometime, masses=masses) == 0
with pytest.raises(KeyError):
someloc.gravitational_redshift(sometime, bodies=('saturn',))
with pytest.raises(u.UnitsError):
masses = {'sun': constants.G*constants.M_sun,
'jupiter': constants.G*constants.M_jup,
'moon': 1*u.km, # wrong units!
'earth': constants.G*constants.M_earth}
someloc.gravitational_redshift(sometime, masses=masses)
|
3e564cd9adf7e91cf9e90df9f52e2dc9bc6c713a9869ca23353ea1daff513f91 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from ...tests.helper import quantity_allclose
from ... import units as u
from ... import constants
from ...time import Time
from ..builtin_frames import ICRS, AltAz, LSR, GCRS, Galactic, FK5
from ..baseframe import frame_transform_graph
from ..sites import get_builtin_sites
from .. import (TimeAttribute,
FunctionTransformWithFiniteDifference, get_sun,
CartesianRepresentation, SphericalRepresentation,
CartesianDifferential, SphericalDifferential,
DynamicMatrixTransform)
J2000 = Time('J2000')
@pytest.mark.parametrize("dt, symmetric", [(1*u.second, True),
(1*u.year, True),
(1*u.second, False),
(1*u.year, False)])
def test_faux_lsr(dt, symmetric):
class LSR2(LSR):
obstime = TimeAttribute(default=J2000)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
ICRS, LSR2, finite_difference_dt=dt,
symmetric_finite_difference=symmetric)
def icrs_to_lsr(icrs_coo, lsr_frame):
dt = lsr_frame.obstime - J2000
offset = lsr_frame.v_bary * dt.to(u.second)
return lsr_frame.realize_frame(icrs_coo.data.without_differentials() + offset)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
LSR2, ICRS, finite_difference_dt=dt,
symmetric_finite_difference=symmetric)
def lsr_to_icrs(lsr_coo, icrs_frame):
dt = lsr_frame.obstime - J2000
offset = lsr_frame.v_bary * dt.to(u.second)
return icrs_frame.realize_frame(lsr_coo.data - offset)
ic = ICRS(ra=12.3*u.deg, dec=45.6*u.deg, distance=7.8*u.au,
pm_ra_cosdec=0*u.marcsec/u.yr, pm_dec=0*u.marcsec/u.yr,
radial_velocity=0*u.km/u.s)
lsrc = ic.transform_to(LSR2())
assert quantity_allclose(ic.cartesian.xyz, lsrc.cartesian.xyz)
idiff = ic.cartesian.differentials['s']
ldiff = lsrc.cartesian.differentials['s']
change = (ldiff.d_xyz - idiff.d_xyz).to(u.km/u.s)
totchange = np.sum(change**2)**0.5
assert quantity_allclose(totchange, np.sum(lsrc.v_bary.d_xyz**2)**0.5)
ic2 = ICRS(ra=120.3*u.deg, dec=45.6*u.deg, distance=7.8*u.au,
pm_ra_cosdec=0*u.marcsec/u.yr, pm_dec=10*u.marcsec/u.yr,
radial_velocity=1000*u.km/u.s)
lsrc2 = ic2.transform_to(LSR2())
tot = np.sum(lsrc2.cartesian.differentials['s'].d_xyz**2)**0.5
assert np.abs(tot.to('km/s') - 1000*u.km/u.s) < 20*u.km/u.s
def test_faux_fk5_galactic():
from ..builtin_frames.galactic_transforms import fk5_to_gal, _gal_to_fk5
class Galactic2(Galactic):
pass
dt = 1000*u.s
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
FK5, Galactic2, finite_difference_dt=dt,
symmetric_finite_difference=True,
finite_difference_frameattr_name=None)
def fk5_to_gal2(fk5_coo, gal_frame):
trans = DynamicMatrixTransform(fk5_to_gal, FK5, Galactic2)
return trans(fk5_coo, gal_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
Galactic2, ICRS, finite_difference_dt=dt,
symmetric_finite_difference=True,
finite_difference_frameattr_name=None)
def gal2_to_fk5(gal_coo, fk5_frame):
trans = DynamicMatrixTransform(_gal_to_fk5, Galactic2, FK5)
return trans(gal_coo, fk5_frame)
c1 = FK5(ra=150*u.deg, dec=-17*u.deg, radial_velocity=83*u.km/u.s,
pm_ra_cosdec=-41*u.mas/u.yr, pm_dec=16*u.mas/u.yr,
distance=150*u.pc)
c2 = c1.transform_to(Galactic2)
c3 = c1.transform_to(Galactic)
# compare the matrix and finite-difference calculations
assert quantity_allclose(c2.pm_l_cosb, c3.pm_l_cosb, rtol=1e-4)
assert quantity_allclose(c2.pm_b, c3.pm_b, rtol=1e-4)
def test_gcrs_diffs():
time = Time('J2017')
gf = GCRS(obstime=time)
sung = get_sun(time) # should have very little vhelio
# qtr-year off sun location should be the direction of ~ maximal vhelio
qtrsung = get_sun(time-.25*u.year)
# now we use those essentially as directions where the velocities should
# be either maximal or minimal - with or perpendiculat to Earh's orbit
msungr = CartesianRepresentation(-sung.cartesian.xyz).represent_as(SphericalRepresentation)
suni = ICRS(ra=msungr.lon, dec=msungr.lat, distance=100*u.au,
pm_ra_cosdec=0*u.marcsec/u.yr, pm_dec=0*u.marcsec/u.yr,
radial_velocity=0*u.km/u.s)
qtrsuni = ICRS(ra=qtrsung.ra, dec=qtrsung.dec, distance=100*u.au,
pm_ra_cosdec=0*u.marcsec/u.yr, pm_dec=0*u.marcsec/u.yr,
radial_velocity=0*u.km/u.s)
# Now we transform those parallel- and perpendicular-to Earth's orbit
# directions to GCRS, which should shift the velocity to either include
# the Earth's velocity vector, or not (for parallel and perpendicular,
# respectively).
sung = suni.transform_to(gf)
qtrsung = qtrsuni.transform_to(gf)
# should be high along the ecliptic-not-sun sun axis and
# low along the sun axis
assert np.abs(qtrsung.radial_velocity) > 30*u.km/u.s
assert np.abs(qtrsung.radial_velocity) < 40*u.km/u.s
assert np.abs(sung.radial_velocity) < 1*u.km/u.s
suni2 = sung.transform_to(ICRS)
assert np.all(np.abs(suni2.data.differentials['s'].d_xyz) < 3e-5*u.km/u.s)
qtrisun2 = qtrsung.transform_to(ICRS)
assert np.all(np.abs(qtrisun2.data.differentials['s'].d_xyz) < 3e-5*u.km/u.s)
def test_altaz_diffs():
time = Time('J2015') + np.linspace(-1, 1, 1000)*u.day
loc = get_builtin_sites()['greenwich']
aa = AltAz(obstime=time, location=loc)
icoo = ICRS(np.zeros_like(time)*u.deg, 10*u.deg, 100*u.au,
pm_ra_cosdec=np.zeros_like(time)*u.marcsec/u.yr,
pm_dec=0*u.marcsec/u.yr,
radial_velocity=0*u.km/u.s)
acoo = icoo.transform_to(aa)
# Make sure the change in radial velocity over ~2 days isn't too much
# more than the rotation speed of the Earth - some excess is expected
# because the orbit also shifts the RV, but it should be pretty small
# over this short a time.
assert np.ptp(acoo.radial_velocity)/2 < (2*np.pi*constants.R_earth/u.day)*1.2 # MAGIC NUMBER
cdiff = acoo.data.differentials['s'].represent_as(CartesianDifferential,
acoo.data)
# The "total" velocity should be > c, because the *tangential* velocity
# isn't a True velocity, but rather an induced velocity due to the Earth's
# rotation at a distance of 100 AU
assert np.all(np.sum(cdiff.d_xyz**2, axis=0)**0.5 > constants.c)
_xfail = pytest.mark.xfail
@pytest.mark.parametrize('distance', [1000*u.au,
10*u.pc,
pytest.param(10*u.kpc, marks=_xfail),
pytest.param(100*u.kpc, marks=_xfail)])
# TODO: make these not fail when the
# finite-difference numerical stability
# is improved
def test_numerical_limits(distance):
"""
Tests the numerical stability of the default settings for the finite
difference transformation calculation. This is *known* to fail for at
>~1kpc, but this may be improved in future versions.
"""
time = Time('J2017') + np.linspace(-.5, .5, 100)*u.year
icoo = ICRS(ra=0*u.deg, dec=10*u.deg, distance=distance,
pm_ra_cosdec=0*u.marcsec/u.yr, pm_dec=0*u.marcsec/u.yr,
radial_velocity=0*u.km/u.s)
gcoo = icoo.transform_to(GCRS(obstime=time))
rv = gcoo.radial_velocity.to('km/s')
# if its a lot bigger than this - ~the maximal velocity shift along
# the direction above with a small allowance for noise - finite-difference
# rounding errors have ruined the calculation
assert np.ptp(rv) < 65*u.km/u.s
def diff_info_plot(frame, time):
"""
Useful for plotting a frame with multiple times. *Not* used in the testing
suite per se, but extremely useful for interactive plotting of results from
tests in this module.
"""
from matplotlib import pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(20, 12))
ax1.plot_date(time.plot_date, frame.data.differentials['s'].d_xyz.to(u.km/u.s).T, fmt='-')
ax1.legend(['x', 'y', 'z'])
ax2.plot_date(time.plot_date, np.sum(frame.data.differentials['s'].d_xyz.to(u.km/u.s)**2, axis=0)**0.5, fmt='-')
ax2.set_title('total')
sd = frame.data.differentials['s'].represent_as(SphericalDifferential, frame.data)
ax3.plot_date(time.plot_date, sd.d_distance.to(u.km/u.s), fmt='-')
ax3.set_title('radial')
ax4.plot_date(time.plot_date, sd.d_lat.to(u.marcsec/u.yr), fmt='-', label='lat')
ax4.plot_date(time.plot_date, sd.d_lon.to(u.marcsec/u.yr), fmt='-', label='lon')
return fig
|
38c5480995be655b65616d440014fdd3139a5f496f84b1215d045fd57bd8a6cf | """
This series of functions are used to generate the reference CSV files
used by the accuracy tests. Running this as a comand-line script will
generate them all.
"""
import os
import numpy as np
from ....table import Table, Column
def ref_fk4_no_e_fk4(fnout='fk4_no_e_fk4.csv'):
"""
Accuracy tests for the FK4 (with no E-terms of aberration) to/from FK4
conversion, with arbitrary equinoxes and epoch of observation.
"""
import starlink.Ast as Ast
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the FK4
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to FK4.
ra = np.random.uniform(0., 360., N)
dec = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
ra_fk4ne, dec_fk4ne = [], []
ra_fk4, dec_fk4 = [], []
for i in range(N):
# Set up frames for AST
frame_fk4ne = Ast.SkyFrame('System=FK4-NO-E,Epoch={epoch},Equinox=B1950'.format(epoch=obstime[i]))
frame_fk4 = Ast.SkyFrame('System=FK4,Epoch={epoch},Equinox=B1950'.format(epoch=obstime[i]))
# FK4 to FK4 (no E-terms)
frameset = frame_fk4.convert(frame_fk4ne)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk4ne.append(coords[0, 0])
dec_fk4ne.append(coords[1, 0])
# FK4 (no E-terms) to FK4
frameset = frame_fk4ne.convert(frame_fk4)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk4.append(coords[0, 0])
dec_fk4.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column(name='obstime', data=obstime))
t.add_column(Column(name='ra_in', data=ra))
t.add_column(Column(name='dec_in', data=dec))
t.add_column(Column(name='ra_fk4ne', data=ra_fk4ne))
t.add_column(Column(name='dec_fk4ne', data=dec_fk4ne))
t.add_column(Column(name='ra_fk4', data=ra_fk4))
t.add_column(Column(name='dec_fk4', data=dec_fk4))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')
def ref_fk4_no_e_fk5(fnout='fk4_no_e_fk5.csv'):
"""
Accuracy tests for the FK4 (with no E-terms of aberration) to/from FK5
conversion, with arbitrary equinoxes and epoch of observation.
"""
import starlink.Ast as Ast
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the FK4
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to FK4.
ra = np.random.uniform(0., 360., N)
dec = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
equinox_fk4 = ["B{0:7.2f}".format(x) for x in np.random.uniform(1925., 1975., N)]
equinox_fk5 = ["J{0:7.2f}".format(x) for x in np.random.uniform(1975., 2025., N)]
ra_fk4, dec_fk4 = [], []
ra_fk5, dec_fk5 = [], []
for i in range(N):
# Set up frames for AST
frame_fk4 = Ast.SkyFrame('System=FK4-NO-E,Epoch={epoch},Equinox={equinox_fk4}'.format(epoch=obstime[i], equinox_fk4=equinox_fk4[i]))
frame_fk5 = Ast.SkyFrame('System=FK5,Epoch={epoch},Equinox={equinox_fk5}'.format(epoch=obstime[i], equinox_fk5=equinox_fk5[i]))
# FK4 to FK5
frameset = frame_fk4.convert(frame_fk5)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk5.append(coords[0, 0])
dec_fk5.append(coords[1, 0])
# FK5 to FK4
frameset = frame_fk5.convert(frame_fk4)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk4.append(coords[0, 0])
dec_fk4.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column(name='equinox_fk4', data=equinox_fk4))
t.add_column(Column(name='equinox_fk5', data=equinox_fk5))
t.add_column(Column(name='obstime', data=obstime))
t.add_column(Column(name='ra_in', data=ra))
t.add_column(Column(name='dec_in', data=dec))
t.add_column(Column(name='ra_fk5', data=ra_fk5))
t.add_column(Column(name='dec_fk5', data=dec_fk5))
t.add_column(Column(name='ra_fk4', data=ra_fk4))
t.add_column(Column(name='dec_fk4', data=dec_fk4))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')
def ref_galactic_fk4(fnout='galactic_fk4.csv'):
"""
Accuracy tests for the ICRS (with no E-terms of aberration) to/from FK5
conversion, with arbitrary equinoxes and epoch of observation.
"""
import starlink.Ast as Ast
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the ICRS
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to ICRS.
lon = np.random.uniform(0., 360., N)
lat = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
equinox_fk4 = ["J{0:7.2f}".format(x) for x in np.random.uniform(1975., 2025., N)]
lon_gal, lat_gal = [], []
ra_fk4, dec_fk4 = [], []
for i in range(N):
# Set up frames for AST
frame_gal = Ast.SkyFrame('System=Galactic,Epoch={epoch}'.format(epoch=obstime[i]))
frame_fk4 = Ast.SkyFrame('System=FK4,Epoch={epoch},Equinox={equinox_fk4}'.format(epoch=obstime[i], equinox_fk4=equinox_fk4[i]))
# ICRS to FK5
frameset = frame_gal.convert(frame_fk4)
coords = np.degrees(frameset.tran([[np.radians(lon[i])], [np.radians(lat[i])]]))
ra_fk4.append(coords[0, 0])
dec_fk4.append(coords[1, 0])
# FK5 to ICRS
frameset = frame_fk4.convert(frame_gal)
coords = np.degrees(frameset.tran([[np.radians(lon[i])], [np.radians(lat[i])]]))
lon_gal.append(coords[0, 0])
lat_gal.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column(name='equinox_fk4', data=equinox_fk4))
t.add_column(Column(name='obstime', data=obstime))
t.add_column(Column(name='lon_in', data=lon))
t.add_column(Column(name='lat_in', data=lat))
t.add_column(Column(name='ra_fk4', data=ra_fk4))
t.add_column(Column(name='dec_fk4', data=dec_fk4))
t.add_column(Column(name='lon_gal', data=lon_gal))
t.add_column(Column(name='lat_gal', data=lat_gal))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')
def ref_icrs_fk5(fnout='icrs_fk5.csv'):
"""
Accuracy tests for the ICRS (with no E-terms of aberration) to/from FK5
conversion, with arbitrary equinoxes and epoch of observation.
"""
import starlink.Ast as Ast
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These will be either the ICRS
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to ICRS.
ra = np.random.uniform(0., 360., N)
dec = np.degrees(np.arcsin(np.random.uniform(-1., 1., N)))
# Generate random observation epoch and equinoxes
obstime = ["B{0:7.2f}".format(x) for x in np.random.uniform(1950., 2000., N)]
equinox_fk5 = ["J{0:7.2f}".format(x) for x in np.random.uniform(1975., 2025., N)]
ra_icrs, dec_icrs = [], []
ra_fk5, dec_fk5 = [], []
for i in range(N):
# Set up frames for AST
frame_icrs = Ast.SkyFrame('System=ICRS,Epoch={epoch}'.format(epoch=obstime[i]))
frame_fk5 = Ast.SkyFrame('System=FK5,Epoch={epoch},Equinox={equinox_fk5}'.format(epoch=obstime[i], equinox_fk5=equinox_fk5[i]))
# ICRS to FK5
frameset = frame_icrs.convert(frame_fk5)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_fk5.append(coords[0, 0])
dec_fk5.append(coords[1, 0])
# FK5 to ICRS
frameset = frame_fk5.convert(frame_icrs)
coords = np.degrees(frameset.tran([[np.radians(ra[i])], [np.radians(dec[i])]]))
ra_icrs.append(coords[0, 0])
dec_icrs.append(coords[1, 0])
# Write out table to a CSV file
t = Table()
t.add_column(Column(name='equinox_fk5', data=equinox_fk5))
t.add_column(Column(name='obstime', data=obstime))
t.add_column(Column(name='ra_in', data=ra))
t.add_column(Column(name='dec_in', data=dec))
t.add_column(Column(name='ra_fk5', data=ra_fk5))
t.add_column(Column(name='dec_fk5', data=dec_fk5))
t.add_column(Column(name='ra_icrs', data=ra_icrs))
t.add_column(Column(name='dec_icrs', data=dec_icrs))
f = open(fnout, 'wb')
f.write("# This file was generated with the {0} script, and the reference "
"values were computed using AST\n".format(os.path.basename(__file__)))
t.write(f, format='ascii', delimiter=',')
if __name__ == '__main__':
ref_fk4_no_e_fk4()
ref_fk4_no_e_fk5()
ref_galactic_fk4()
ref_icrs_fk5()
|
5ae8be676dca36a6eee5dc09ab73968e805d8fe579e3db705eb014e46a88c7c9 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from .... import units as u
from ...builtin_frames import Galactic, FK4
from ....time import Time
from ....table import Table
from ...angle_utilities import angular_separation
from ....utils.data import get_pkg_data_contents
# the number of tests to run
from . import N_ACCURACY_TESTS
TOLERANCE = 0.3 # arcseconds
def test_galactic_fk4():
lines = get_pkg_data_contents('galactic_fk4.csv').split('\n')
t = Table.read(lines, format='ascii', delimiter=',', guess=False)
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
diffarcsec1 = []
diffarcsec2 = []
for i in idxs:
# Extract row
r = t[int(i)] # int here is to get around a py 3.x astropy.table bug
# Galactic to FK4
c1 = Galactic(l=r['lon_in']*u.deg, b=r['lat_in']*u.deg)
c2 = c1.transform_to(FK4(equinox=Time(r['equinox_fk4'], scale='utc')))
# Find difference
diff = angular_separation(c2.ra.radian, c2.dec.radian,
np.radians(r['ra_fk4']),
np.radians(r['dec_fk4']))
diffarcsec1.append(np.degrees(diff) * 3600.)
# FK4 to Galactic
c1 = FK4(ra=r['lon_in']*u.deg, dec=r['lat_in']*u.deg,
obstime=Time(r['obstime'], scale='utc'),
equinox=Time(r['equinox_fk4'], scale='utc'))
c2 = c1.transform_to(Galactic)
# Find difference
diff = angular_separation(c2.l.radian, c2.b.radian,
np.radians(r['lon_gal']),
np.radians(r['lat_gal']))
diffarcsec2.append(np.degrees(diff) * 3600.)
np.testing.assert_array_less(diffarcsec1, TOLERANCE)
np.testing.assert_array_less(diffarcsec2, TOLERANCE)
|
568d84ac74357e68c83092c8c7f52cf96966c8e30a00077c30a1f64f1fed05ab | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from .... import units as u
from ...builtin_frames import ICRS, FK5
from ....time import Time
from ....table import Table
from ...angle_utilities import angular_separation
from ....utils.data import get_pkg_data_contents
# the number of tests to run
from . import N_ACCURACY_TESTS
TOLERANCE = 0.03 # arcseconds
def test_icrs_fk5():
lines = get_pkg_data_contents('icrs_fk5.csv').split('\n')
t = Table.read(lines, format='ascii', delimiter=',', guess=False)
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
diffarcsec1 = []
diffarcsec2 = []
for i in idxs:
# Extract row
r = t[int(i)] # int here is to get around a py 3.x astropy.table bug
# ICRS to FK5
c1 = ICRS(ra=r['ra_in']*u.deg, dec=r['dec_in']*u.deg)
c2 = c1.transform_to(FK5(equinox=Time(r['equinox_fk5'], scale='utc')))
# Find difference
diff = angular_separation(c2.ra.radian, c2.dec.radian,
np.radians(r['ra_fk5']),
np.radians(r['dec_fk5']))
diffarcsec1.append(np.degrees(diff) * 3600.)
# FK5 to ICRS
c1 = FK5(ra=r['ra_in']*u.deg, dec=r['dec_in']*u.deg,
equinox=Time(r['equinox_fk5'], scale='utc'))
c2 = c1.transform_to(ICRS)
# Find difference
diff = angular_separation(c2.ra.radian, c2.dec.radian,
np.radians(r['ra_icrs']),
np.radians(r['dec_icrs']))
diffarcsec2.append(np.degrees(diff) * 3600.)
np.testing.assert_array_less(diffarcsec1, TOLERANCE)
np.testing.assert_array_less(diffarcsec2, TOLERANCE)
|
1f027b2fb613d7187bc0d08741c84162bdf6ab9d072da2755cac89dcde34997b | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from .... import units as u
from ...builtin_frames import FK4NoETerms, FK5
from ....time import Time
from ....table import Table
from ...angle_utilities import angular_separation
from ....utils.data import get_pkg_data_contents
# the number of tests to run
from . import N_ACCURACY_TESTS
TOLERANCE = 0.03 # arcseconds
def test_fk4_no_e_fk5():
lines = get_pkg_data_contents('fk4_no_e_fk5.csv').split('\n')
t = Table.read(lines, format='ascii', delimiter=',', guess=False)
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
diffarcsec1 = []
diffarcsec2 = []
for i in idxs:
# Extract row
r = t[int(i)] # int here is to get around a py 3.x astropy.table bug
# FK4NoETerms to FK5
c1 = FK4NoETerms(ra=r['ra_in']*u.deg, dec=r['dec_in']*u.deg,
obstime=Time(r['obstime'], scale='utc'),
equinox=Time(r['equinox_fk4'], scale='utc'))
c2 = c1.transform_to(FK5(equinox=Time(r['equinox_fk5'], scale='utc')))
# Find difference
diff = angular_separation(c2.ra.radian, c2.dec.radian,
np.radians(r['ra_fk5']),
np.radians(r['dec_fk5']))
diffarcsec1.append(np.degrees(diff) * 3600.)
# FK5 to FK4NoETerms
c1 = FK5(ra=r['ra_in']*u.deg, dec=r['dec_in']*u.deg,
equinox=Time(r['equinox_fk5'], scale='utc'))
fk4neframe = FK4NoETerms(obstime=Time(r['obstime'], scale='utc'),
equinox=Time(r['equinox_fk4'], scale='utc'))
c2 = c1.transform_to(fk4neframe)
# Find difference
diff = angular_separation(c2.ra.radian, c2.dec.radian,
np.radians(r['ra_fk4']),
np.radians(r['dec_fk4']))
diffarcsec2.append(np.degrees(diff) * 3600.)
np.testing.assert_array_less(diffarcsec1, TOLERANCE)
np.testing.assert_array_less(diffarcsec2, TOLERANCE)
|
21a690e2f81990c0843743a90cd57a4cb090dd051683f70215c0c7809795e2a8 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from .... import units as u
from ...builtin_frames import FK4NoETerms, FK4
from ....time import Time
from ....table import Table
from ...angle_utilities import angular_separation
from ....utils.data import get_pkg_data_contents
# the number of tests to run
from . import N_ACCURACY_TESTS
# It looks as though SLALIB, which AST relies on, assumes a simplified version
# of the e-terms corretion, so we have to up the tolerance a bit to get things
# to agree.
TOLERANCE = 1.e-5 # arcseconds
def test_fk4_no_e_fk4():
lines = get_pkg_data_contents('fk4_no_e_fk4.csv').split('\n')
t = Table.read(lines, format='ascii', delimiter=',', guess=False)
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
diffarcsec1 = []
diffarcsec2 = []
for i in idxs:
# Extract row
r = t[int(i)] # int here is to get around a py 3.x astropy.table bug
# FK4 to FK4NoETerms
c1 = FK4(ra=r['ra_in']*u.deg, dec=r['dec_in']*u.deg,
obstime=Time(r['obstime'], scale='utc'))
c2 = c1.transform_to(FK4NoETerms)
# Find difference
diff = angular_separation(c2.ra.radian, c2.dec.radian,
np.radians(r['ra_fk4ne']), np.radians(r['dec_fk4ne']))
diffarcsec1.append(np.degrees(diff) * 3600.)
# FK4NoETerms to FK4
c1 = FK4NoETerms(ra=r['ra_in']*u.deg, dec=r['dec_in']*u.deg,
obstime=Time(r['obstime'], scale='utc'))
c2 = c1.transform_to(FK4)
# Find difference
diff = angular_separation(c2.ra.radian, c2.dec.radian,
np.radians(r['ra_fk4']),
np.radians(r['dec_fk4']))
diffarcsec2.append(np.degrees(diff) * 3600.)
np.testing.assert_array_less(diffarcsec1, TOLERANCE)
np.testing.assert_array_less(diffarcsec2, TOLERANCE)
|
66d1e79f1324db75d528bd3a2df805c3b913ee7ad6443cff6610229d07616df2 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Accuracy tests for Ecliptic coordinate systems.
"""
import numpy as np
from ....tests.helper import quantity_allclose
from .... import units as u
from ... import SkyCoord
from ...builtin_frames import FK5, ICRS, GCRS, GeocentricTrueEcliptic, BarycentricTrueEcliptic, HeliocentricTrueEcliptic
from ....constants import R_sun, R_earth
def test_against_pytpm_doc_example():
"""
Check that Astropy's Ecliptic systems give answers consistent with pyTPM
Currently this is only testing against the example given in the pytpm docs
"""
fk5_in = SkyCoord('12h22m54.899s', '15d49m20.57s', frame=FK5(equinox='J2000'))
pytpm_out = BarycentricTrueEcliptic(lon=178.78256462*u.deg,
lat=16.7597002513*u.deg,
equinox='J2000')
astropy_out = fk5_in.transform_to(pytpm_out)
assert pytpm_out.separation(astropy_out) < (1*u.arcsec)
def test_ecliptic_heliobary():
"""
Check that the ecliptic transformations for heliocentric and barycentric
at least more or less make sense
"""
icrs = ICRS(1*u.deg, 2*u.deg, distance=1.5*R_sun)
bary = icrs.transform_to(BarycentricTrueEcliptic)
helio = icrs.transform_to(HeliocentricTrueEcliptic)
# make sure there's a sizable distance shift - in 3d hundreds of km, but
# this is 1D so we allow it to be somewhat smaller
assert np.abs(bary.distance - helio.distance) > 1*u.km
# now make something that's got the location of helio but in bary's frame.
# this is a convenience to allow `separation` to work as expected
helio_in_bary_frame = bary.realize_frame(helio.cartesian)
assert bary.separation(helio_in_bary_frame) > 1*u.arcmin
def test_ecl_geo():
"""
Check that the geocentric version at least gets well away from GCRS. For a
true "accuracy" test we need a comparison dataset that is similar to the
geocentric/GCRS comparison we want to do here. Contributions welcome!
"""
gcrs = GCRS(10*u.deg, 20*u.deg, distance=1.5*R_earth)
gecl = gcrs.transform_to(GeocentricTrueEcliptic)
assert quantity_allclose(gecl.distance, gcrs.distance)
def test_arraytransforms():
"""
Test that transforms to/from ecliptic coordinates work on array coordinates
(not testing for accuracy.)
"""
ra = np.ones((4, ), dtype=float) * u.deg
dec = 2*np.ones((4, ), dtype=float) * u.deg
distance = np.ones((4, ), dtype=float) * u.au
test_icrs = ICRS(ra=ra, dec=dec, distance=distance)
test_gcrs = GCRS(test_icrs.data)
bary_arr = test_icrs.transform_to(BarycentricTrueEcliptic)
assert bary_arr.shape == ra.shape
helio_arr = test_icrs.transform_to(HeliocentricTrueEcliptic)
assert helio_arr.shape == ra.shape
geo_arr = test_gcrs.transform_to(GeocentricTrueEcliptic)
assert geo_arr.shape == ra.shape
# now check that we also can go back the other way without shape problems
bary_icrs = bary_arr.transform_to(ICRS)
assert bary_icrs.shape == test_icrs.shape
helio_icrs = helio_arr.transform_to(ICRS)
assert helio_icrs.shape == test_icrs.shape
geo_gcrs = geo_arr.transform_to(GCRS)
assert geo_gcrs.shape == test_gcrs.shape
def test_roundtrip_scalar():
icrs = ICRS(ra=1*u.deg, dec=2*u.deg, distance=3*u.au)
gcrs = GCRS(icrs.cartesian)
bary = icrs.transform_to(BarycentricTrueEcliptic)
helio = icrs.transform_to(HeliocentricTrueEcliptic)
geo = gcrs.transform_to(GeocentricTrueEcliptic)
bary_icrs = bary.transform_to(ICRS)
helio_icrs = helio.transform_to(ICRS)
geo_gcrs = geo.transform_to(GCRS)
assert quantity_allclose(bary_icrs.cartesian.xyz, icrs.cartesian.xyz)
assert quantity_allclose(helio_icrs.cartesian.xyz, icrs.cartesian.xyz)
assert quantity_allclose(geo_gcrs.cartesian.xyz, gcrs.cartesian.xyz)
|
0170f19bfd38aceb860fca4d518843b2da6472be71b9177c496345a4cc0d60e5 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Accuracy tests for AltAz to ICRS coordinate transformations.
We use "known good" examples computed with other coordinate libraries.
Note that we use very low precision asserts because some people run tests on 32-bit
machines and we want the tests to pass there.
TODO: check if these tests pass on 32-bit machines and implement
higher-precision checks on 64-bit machines.
"""
import pytest
from .... import units as u
from ....time import Time
from ...builtin_frames import AltAz
from ... import EarthLocation
from ... import Angle, SkyCoord
def test_against_hor2eq():
"""Check that Astropy gives consistent results with an IDL hor2eq example.
See : http://idlastro.gsfc.nasa.gov/ftp/pro/astro/hor2eq.pro
Test is against these run outputs, run at 2000-01-01T12:00:00:
# NORMAL ATMOSPHERE CASE
IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=781.0, temp=273.0
Latitude = +31 57 48.0 Longitude = *** 36 00.0
Julian Date = 2451545.000000
Az, El = 17 39 40.4 +37 54 41 (Observer Coords)
Az, El = 17 39 40.4 +37 53 40 (Apparent Coords)
LMST = +11 15 26.5
LAST = +11 15 25.7
Hour Angle = +03 38 30.1 (hh:mm:ss)
Ra, Dec: 07 36 55.6 +15 25 02 (Apparent Coords)
Ra, Dec: 07 36 55.2 +15 25 08 (J2000.0000)
Ra, Dec: 07 36 55.2 +15 25 08 (J2000)
IDL> print, ra, dec
114.23004 15.418818
# NO PRESSURE CASE
IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=0.0, temp=273.0
Latitude = +31 57 48.0 Longitude = *** 36 00.0
Julian Date = 2451545.000000
Az, El = 17 39 40.4 +37 54 41 (Observer Coords)
Az, El = 17 39 40.4 +37 54 41 (Apparent Coords)
LMST = +11 15 26.5
LAST = +11 15 25.7
Hour Angle = +03 38 26.4 (hh:mm:ss)
Ra, Dec: 07 36 59.3 +15 25 31 (Apparent Coords)
Ra, Dec: 07 36 58.9 +15 25 37 (J2000.0000)
Ra, Dec: 07 36 58.9 +15 25 37 (J2000)
IDL> print, ra, dec
114.24554 15.427022
"""
# Observatory position for `kpno` from here:
# http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro
location = EarthLocation(lon=Angle('-111d36.0m'),
lat=Angle('31d57.8m'),
height=2120. * u.m)
obstime = Time(2451545.0, format='jd', scale='ut1')
altaz_frame = AltAz(obstime=obstime, location=location,
temperature=0 * u.deg_C, pressure=0.781 * u.bar)
altaz_frame_noatm = AltAz(obstime=obstime, location=location,
temperature=0 * u.deg_C, pressure=0.0 * u.bar)
altaz = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame)
altaz_noatm = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame_noatm)
radec_frame = 'icrs'
radec_actual = altaz.transform_to(radec_frame)
radec_actual_noatm = altaz_noatm.transform_to(radec_frame)
radec_expected = SkyCoord('07h36m55.2s +15d25m08s', frame=radec_frame)
distance = radec_actual.separation(radec_expected).to('arcsec')
# this comes from running the example hor2eq but with the pressure set to 0
radec_expected_noatm = SkyCoord('07h36m58.9s +15d25m37s', frame=radec_frame)
distance_noatm = radec_actual_noatm.separation(radec_expected_noatm).to('arcsec')
# The baseline difference is ~2.3 arcsec with one atm of pressure. The
# difference is mainly due to the somewhat different atmospheric model that
# hor2eq assumes. This is confirmed by the second test which has the
# atmosphere "off" - the residual difference is small enough to be embedded
# in the assumptions about "J2000" or rounding errors.
assert distance < 5 * u.arcsec
assert distance_noatm < 0.4 * u.arcsec
def test_against_pyephem():
"""Check that Astropy gives consistent results with one PyEphem example.
PyEphem: http://rhodesmill.org/pyephem/
See example input and output here:
https://gist.github.com/zonca/1672906
https://github.com/phn/pytpm/issues/2#issuecomment-3698679
"""
obstime = Time('2011-09-18 08:50:00')
location = EarthLocation(lon=Angle('-109d24m53.1s'),
lat=Angle('33d41m46.0s'),
height=30000. * u.m)
# We are using the default pressure and temperature in PyEphem
# relative_humidity = ?
# obswl = ?
altaz_frame = AltAz(obstime=obstime, location=location,
temperature=15 * u.deg_C, pressure=1.010 * u.bar)
altaz = SkyCoord('6.8927d -60.7665d', frame=altaz_frame)
radec_actual = altaz.transform_to('icrs')
radec_expected = SkyCoord('196.497518d -4.569323d', frame='icrs') # EPHEM
# radec_expected = SkyCoord('196.496220d -4.569390d', frame='icrs') # HORIZON
distance = radec_actual.separation(radec_expected).to('arcsec')
# TODO: why is this difference so large?
# It currently is: 31.45187984720655 arcsec
assert distance < 1e3 * u.arcsec
# Add assert on current Astropy result so that we notice if something changes
radec_expected = SkyCoord('196.495372d -4.560694d', frame='icrs')
distance = radec_actual.separation(radec_expected).to('arcsec')
# Current value: 0.0031402822944751997 arcsec
assert distance < 1 * u.arcsec
def test_against_jpl_horizons():
"""Check that Astropy gives consistent results with the JPL Horizons example.
The input parameters and reference results are taken from this page:
(from the first row of the Results table at the bottom of that page)
http://ssd.jpl.nasa.gov/?horizons_tutorial
"""
obstime = Time('1998-07-28 03:00')
location = EarthLocation(lon=Angle('248.405300d'),
lat=Angle('31.9585d'),
height=2.06 * u.km)
# No atmosphere
altaz_frame = AltAz(obstime=obstime, location=location)
altaz = SkyCoord('143.2970d 2.6223d', frame=altaz_frame)
radec_actual = altaz.transform_to('icrs')
radec_expected = SkyCoord('19h24m55.01s -40d56m28.9s', frame='icrs')
distance = radec_actual.separation(radec_expected).to('arcsec')
# Current value: 0.238111 arcsec
assert distance < 1 * u.arcsec
@pytest.mark.xfail
def test_fk5_equinox_and_epoch_j2000_0_to_topocentric_observed():
"""
http://phn.github.io/pytpm/conversions.html#fk5-equinox-and-epoch-j2000-0-to-topocentric-observed
"""
# Observatory position for `kpno` from here:
# http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro
location = EarthLocation(lon=Angle('-111.598333d'),
lat=Angle('31.956389d'),
height=2093.093 * u.m) # TODO: height correct?
obstime = Time('2010-01-01 12:00:00', scale='utc')
# relative_humidity = ?
# obswl = ?
altaz_frame = AltAz(obstime=obstime, location=location,
temperature=0 * u.deg_C, pressure=0.781 * u.bar)
radec = SkyCoord('12h22m54.899s 15d49m20.57s', frame='fk5')
altaz_actual = radec.transform_to(altaz_frame)
altaz_expected = SkyCoord('264d55m06s 37d54m41s', frame='altaz')
# altaz_expected = SkyCoord('343.586827647d 15.7683070508d', frame='altaz')
# altaz_expected = SkyCoord('133.498195532d 22.0162383595d', frame='altaz')
distance = altaz_actual.separation(altaz_expected)
# print(altaz_actual)
# print(altaz_expected)
# print(distance)
"""TODO: Current output is completely incorrect ... xfailing this test for now.
<SkyCoord (AltAz: obstime=2010-01-01 12:00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron):00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=133.4869896371561 deg, alt=67.97857990957701 deg>
<SkyCoord (AltAz: obstime=None, location=None, pressure=0.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=264.91833333333335 deg, alt=37.91138888888889 deg>
68d02m45.732s
"""
assert distance < 1 * u.arcsec
|
6f84a14db2d22c50175e490e84d3a966c934cc7b90d8cbfc7835611e9cd239df | # Licensed under a 3-clause BSD style license - see PYFITS.rst
import bz2
import gzip
import http.client
import mmap
import operator
import pathlib
import io
import os
import sys
import tempfile
import warnings
import zipfile
import re
from functools import reduce
import numpy as np
from numpy import memmap as Memmap
from .util import (isreadable, iswritable, isfile, fileobj_open, fileobj_name,
fileobj_closed, fileobj_mode, _array_from_file,
_array_to_file, _write_string)
from ...utils.data import download_file, _is_url
from ...utils.decorators import classproperty, deprecated_renamed_argument
from ...utils.exceptions import AstropyUserWarning
# Maps astropy.io.fits-specific file mode names to the appropriate file
# modes to use for the underlying raw files
IO_FITS_MODES = {
'readonly': 'rb',
'copyonwrite': 'rb',
'update': 'rb+',
'append': 'ab+',
'ostream': 'wb',
'denywrite': 'rb'}
# Maps OS-level file modes to the appropriate astropy.io.fits specific mode
# to use when given file objects but no mode specified; obviously in
# IO_FITS_MODES there are overlaps; for example 'readonly' and 'denywrite'
# both require the file to be opened in 'rb' mode. But 'readonly' is the
# default behavior for such files if not otherwise specified.
# Note: 'ab' is only supported for 'ostream' which is output-only.
FILE_MODES = {
'rb': 'readonly', 'rb+': 'update',
'wb': 'ostream', 'wb+': 'update',
'ab': 'ostream', 'ab+': 'append'}
# A match indicates the file was opened in text mode, which is not allowed
TEXT_RE = re.compile(r'^[rwa]((t?\+?)|(\+?t?))$')
# readonly actually uses copyonwrite for mmap so that readonly without mmap and
# with mmap still have to same behavior with regard to updating the array. To
# get a truly readonly mmap use denywrite
# the name 'denywrite' comes from a deprecated flag to mmap() on Linux--it
# should be clarified that 'denywrite' mode is not directly analogous to the
# use of that flag; it was just taken, for lack of anything better, as a name
# that means something like "read only" but isn't readonly.
MEMMAP_MODES = {'readonly': 'c', 'copyonwrite': 'c', 'update': 'r+',
'append': 'c', 'denywrite': 'r'}
# TODO: Eventually raise a warning, and maybe even later disable the use of
# 'copyonwrite' and 'denywrite' modes unless memmap=True. For now, however,
# that would generate too many warnings for too many users. If nothing else,
# wait until the new logging system is in place.
GZIP_MAGIC = b'\x1f\x8b\x08'
PKZIP_MAGIC = b'\x50\x4b\x03\x04'
BZIP2_MAGIC = b'\x42\x5a'
def _normalize_fits_mode(mode):
if mode is not None and mode not in IO_FITS_MODES:
if TEXT_RE.match(mode):
raise ValueError(
"Text mode '{}' not supported: "
"files must be opened in binary mode".format(mode))
new_mode = FILE_MODES.get(mode)
if new_mode not in IO_FITS_MODES:
raise ValueError("Mode '{}' not recognized".format(mode))
mode = new_mode
return mode
class _File:
"""
Represents a FITS file on disk (or in some other file-like object).
"""
@deprecated_renamed_argument('clobber', 'overwrite', '2.0')
def __init__(self, fileobj=None, mode=None, memmap=None, overwrite=False,
cache=True):
self.strict_memmap = bool(memmap)
memmap = True if memmap is None else memmap
if fileobj is None:
self._file = None
self.closed = False
self.binary = True
self.mode = mode
self.memmap = memmap
self.compression = None
self.readonly = False
self.writeonly = False
self.simulateonly = True
self.close_on_error = False
return
else:
self.simulateonly = False
# If fileobj is of type pathlib.Path
if isinstance(fileobj, pathlib.Path):
fileobj = str(fileobj)
elif isinstance(fileobj, bytes):
# Using bytes as filename is tricky, it's deprecated for Windows
# in Python 3.5 (because it could lead to false-positives) but
# was fixed and un-deprecated in Python 3.6.
# However it requires that the bytes object is encoded with the
# file system encoding.
# Probably better to error out and ask for a str object instead.
# TODO: This could be revised when Python 3.5 support is dropped
# See also: https://github.com/astropy/astropy/issues/6789
raise TypeError("names should be `str` not `bytes`.")
# Holds mmap instance for files that use mmap
self._mmap = None
if mode is not None and mode not in IO_FITS_MODES:
raise ValueError("Mode '{}' not recognized".format(mode))
if isfile(fileobj):
objmode = _normalize_fits_mode(fileobj_mode(fileobj))
if mode is not None and mode != objmode:
raise ValueError(
"Requested FITS mode '{}' not compatible with open file "
"handle mode '{}'".format(mode, objmode))
mode = objmode
if mode is None:
mode = 'readonly'
# Handle raw URLs
if (isinstance(fileobj, str) and
mode not in ('ostream', 'append', 'update') and _is_url(fileobj)):
self.name = download_file(fileobj, cache=cache)
# Handle responses from URL requests that have already been opened
elif isinstance(fileobj, http.client.HTTPResponse):
if mode in ('ostream', 'append', 'update'):
raise ValueError(
"Mode {} not supported for HTTPResponse".format(mode))
fileobj = io.BytesIO(fileobj.read())
else:
self.name = fileobj_name(fileobj)
self.closed = False
self.binary = True
self.mode = mode
self.memmap = memmap
# Underlying fileobj is a file-like object, but an actual file object
self.file_like = False
# Should the object be closed on error: see
# https://github.com/astropy/astropy/issues/6168
self.close_on_error = False
# More defaults to be adjusted below as necessary
self.compression = None
self.readonly = False
self.writeonly = False
# Initialize the internal self._file object
if isfile(fileobj):
self._open_fileobj(fileobj, mode, overwrite)
elif isinstance(fileobj, str):
self._open_filename(fileobj, mode, overwrite)
else:
self._open_filelike(fileobj, mode, overwrite)
self.fileobj_mode = fileobj_mode(self._file)
if isinstance(fileobj, gzip.GzipFile):
self.compression = 'gzip'
elif isinstance(fileobj, zipfile.ZipFile):
# Reading from zip files is supported but not writing (yet)
self.compression = 'zip'
elif isinstance(fileobj, bz2.BZ2File):
self.compression = 'bzip2'
if (mode in ('readonly', 'copyonwrite', 'denywrite') or
(self.compression and mode == 'update')):
self.readonly = True
elif (mode == 'ostream' or
(self.compression and mode == 'append')):
self.writeonly = True
# For 'ab+' mode, the pointer is at the end after the open in
# Linux, but is at the beginning in Solaris.
if (mode == 'ostream' or self.compression or
not hasattr(self._file, 'seek')):
# For output stream start with a truncated file.
# For compressed files we can't really guess at the size
self.size = 0
else:
pos = self._file.tell()
self._file.seek(0, 2)
self.size = self._file.tell()
self._file.seek(pos)
if self.memmap:
if not isfile(self._file):
self.memmap = False
elif not self.readonly and not self._mmap_available:
# Test mmap.flush--see
# https://github.com/astropy/astropy/issues/968
self.memmap = False
def __repr__(self):
return '<{}.{} {}>'.format(self.__module__, self.__class__.__name__,
self._file)
# Support the 'with' statement
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def readable(self):
if self.writeonly:
return False
return isreadable(self._file)
def read(self, size=None):
if not hasattr(self._file, 'read'):
raise EOFError
try:
return self._file.read(size)
except OSError:
# On some versions of Python, it appears, GzipFile will raise an
# OSError if you try to read past its end (as opposed to just
# returning '')
if self.compression == 'gzip':
return ''
raise
def readarray(self, size=None, offset=0, dtype=np.uint8, shape=None):
"""
Similar to file.read(), but returns the contents of the underlying
file as a numpy array (or mmap'd array if memmap=True) rather than a
string.
Usually it's best not to use the `size` argument with this method, but
it's provided for compatibility.
"""
if not hasattr(self._file, 'read'):
raise EOFError
if not isinstance(dtype, np.dtype):
dtype = np.dtype(dtype)
if size and size % dtype.itemsize != 0:
raise ValueError('size {} not a multiple of {}'.format(size, dtype))
if isinstance(shape, int):
shape = (shape,)
if not (size or shape):
warnings.warn('No size or shape given to readarray(); assuming a '
'shape of (1,)', AstropyUserWarning)
shape = (1,)
if size and not shape:
shape = (size // dtype.itemsize,)
if size and shape:
actualsize = np.prod(shape) * dtype.itemsize
if actualsize > size:
raise ValueError('size {} is too few bytes for a {} array of '
'{}'.format(size, shape, dtype))
elif actualsize < size:
raise ValueError('size {} is too many bytes for a {} array of '
'{}'.format(size, shape, dtype))
filepos = self._file.tell()
try:
if self.memmap:
if self._mmap is None:
# Instantiate Memmap array of the file offset at 0 (so we
# can return slices of it to offset anywhere else into the
# file)
memmap = Memmap(self._file, mode=MEMMAP_MODES[self.mode],
dtype=np.uint8)
# Now we immediately discard the memmap array; we are
# really just using it as a factory function to instantiate
# the mmap object in a convenient way (may later do away
# with this usage)
self._mmap = memmap.base
# Prevent dorking with self._memmap._mmap by memmap.__del__
# in Numpy 1.6 (see
# https://github.com/numpy/numpy/commit/dcc355a0b179387eeba10c95baf2e1eb21d417c7)
memmap._mmap = None
del memmap
return np.ndarray(shape=shape, dtype=dtype, offset=offset,
buffer=self._mmap)
else:
count = reduce(operator.mul, shape)
self._file.seek(offset)
data = _array_from_file(self._file, dtype, count)
data.shape = shape
return data
finally:
# Make sure we leave the file in the position we found it; on
# some platforms (e.g. Windows) mmaping a file handle can also
# reset its file pointer
self._file.seek(filepos)
def writable(self):
if self.readonly:
return False
return iswritable(self._file)
def write(self, string):
if hasattr(self._file, 'write'):
_write_string(self._file, string)
def writearray(self, array):
"""
Similar to file.write(), but writes a numpy array instead of a string.
Also like file.write(), a flush() or close() may be needed before
the file on disk reflects the data written.
"""
if hasattr(self._file, 'write'):
_array_to_file(array, self._file)
def flush(self):
if hasattr(self._file, 'flush'):
self._file.flush()
def seek(self, offset, whence=0):
if not hasattr(self._file, 'seek'):
return
self._file.seek(offset, whence)
pos = self._file.tell()
if self.size and pos > self.size:
warnings.warn('File may have been truncated: actual file length '
'({}) is smaller than the expected size ({})'
.format(self.size, pos), AstropyUserWarning)
def tell(self):
if not hasattr(self._file, 'tell'):
raise EOFError
return self._file.tell()
def truncate(self, size=None):
if hasattr(self._file, 'truncate'):
self._file.truncate(size)
def close(self):
"""
Close the 'physical' FITS file.
"""
if hasattr(self._file, 'close'):
self._file.close()
self._maybe_close_mmap()
# Set self._memmap to None anyways since no new .data attributes can be
# loaded after the file is closed
self._mmap = None
self.closed = True
self.close_on_error = False
def _maybe_close_mmap(self, refcount_delta=0):
"""
When mmap is in use these objects hold a reference to the mmap of the
file (so there is only one, shared by all HDUs that reference this
file).
This will close the mmap if there are no arrays referencing it.
"""
if (self._mmap is not None and
sys.getrefcount(self._mmap) == 2 + refcount_delta):
self._mmap.close()
self._mmap = None
def _overwrite_existing(self, overwrite, fileobj, closed):
"""Overwrite an existing file if ``overwrite`` is ``True``, otherwise
raise an OSError. The exact behavior of this method depends on the
_File object state and is only meant for use within the ``_open_*``
internal methods.
"""
# The file will be overwritten...
if ((self.file_like and hasattr(fileobj, 'len') and fileobj.len > 0) or
(os.path.exists(self.name) and os.path.getsize(self.name) != 0)):
if overwrite:
if self.file_like and hasattr(fileobj, 'truncate'):
fileobj.truncate(0)
else:
if not closed:
fileobj.close()
os.remove(self.name)
else:
raise OSError("File {!r} already exists.".format(self.name))
def _try_read_compressed(self, obj_or_name, magic, mode, ext=''):
"""Attempt to determine if the given file is compressed"""
if ext == '.gz' or magic.startswith(GZIP_MAGIC):
# Handle gzip files
kwargs = dict(mode=IO_FITS_MODES[mode])
if isinstance(obj_or_name, str):
kwargs['filename'] = obj_or_name
else:
kwargs['fileobj'] = obj_or_name
self._file = gzip.GzipFile(**kwargs)
self.compression = 'gzip'
elif ext == '.zip' or magic.startswith(PKZIP_MAGIC):
# Handle zip files
self._open_zipfile(self.name, mode)
self.compression = 'zip'
elif ext == '.bz2' or magic.startswith(BZIP2_MAGIC):
# Handle bzip2 files
if mode in ['update', 'append']:
raise OSError("update and append modes are not supported "
"with bzip2 files")
# bzip2 only supports 'w' and 'r' modes
bzip2_mode = 'w' if mode == 'ostream' else 'r'
self._file = bz2.BZ2File(obj_or_name, mode=bzip2_mode)
self.compression = 'bzip2'
return self.compression is not None
def _open_fileobj(self, fileobj, mode, overwrite):
"""Open a FITS file from a file object (including compressed files)."""
closed = fileobj_closed(fileobj)
fmode = fileobj_mode(fileobj) or IO_FITS_MODES[mode]
if mode == 'ostream':
self._overwrite_existing(overwrite, fileobj, closed)
if not closed:
self._file = fileobj
elif isfile(fileobj):
self._file = fileobj_open(self.name, IO_FITS_MODES[mode])
# Attempt to determine if the file represented by the open file object
# is compressed
try:
# We need to account for the possibility that the underlying file
# handle may have been opened with either 'ab' or 'ab+', which
# means that the current file position is at the end of the file.
if mode in ['ostream', 'append']:
self._file.seek(0)
magic = self._file.read(4)
# No matter whether the underlying file was opened with 'ab' or
# 'ab+', we need to return to the beginning of the file in order
# to properly process the FITS header (and handle the possibility
# of a compressed file).
self._file.seek(0)
except (OSError,OSError):
return
self._try_read_compressed(fileobj, magic, mode)
def _open_filelike(self, fileobj, mode, overwrite):
"""Open a FITS file from a file-like object, i.e. one that has
read and/or write methods.
"""
self.file_like = True
self._file = fileobj
if fileobj_closed(fileobj):
raise OSError("Cannot read from/write to a closed file-like "
"object ({!r}).".format(fileobj))
if isinstance(fileobj, zipfile.ZipFile):
self._open_zipfile(fileobj, mode)
# We can bypass any additional checks at this point since now
# self._file points to the temp file extracted from the zip
return
# If there is not seek or tell methods then set the mode to
# output streaming.
if (not hasattr(self._file, 'seek') or
not hasattr(self._file, 'tell')):
self.mode = mode = 'ostream'
if mode == 'ostream':
self._overwrite_existing(overwrite, fileobj, False)
# Any "writeable" mode requires a write() method on the file object
if (self.mode in ('update', 'append', 'ostream') and
not hasattr(self._file, 'write')):
raise OSError("File-like object does not have a 'write' "
"method, required for mode '{}'.".format(self.mode))
# Any mode except for 'ostream' requires readability
if self.mode != 'ostream' and not hasattr(self._file, 'read'):
raise OSError("File-like object does not have a 'read' "
"method, required for mode {!r}.".format(self.mode))
def _open_filename(self, filename, mode, overwrite):
"""Open a FITS file from a filename string."""
if mode == 'ostream':
self._overwrite_existing(overwrite, None, True)
if os.path.exists(self.name):
with fileobj_open(self.name, 'rb') as f:
magic = f.read(4)
else:
magic = b''
ext = os.path.splitext(self.name)[1]
if not self._try_read_compressed(self.name, magic, mode, ext=ext):
self._file = fileobj_open(self.name, IO_FITS_MODES[mode])
self.close_on_error = True
# Make certain we're back at the beginning of the file
# BZ2File does not support seek when the file is open for writing, but
# when opening a file for write, bz2.BZ2File always truncates anyway.
if not (isinstance(self._file, bz2.BZ2File) and mode == 'ostream'):
self._file.seek(0)
@classproperty(lazy=True)
def _mmap_available(cls):
"""Tests that mmap, and specifically mmap.flush works. This may
be the case on some uncommon platforms (see
https://github.com/astropy/astropy/issues/968).
If mmap.flush is found not to work, ``self.memmap = False`` is
set and a warning is issued.
"""
tmpfd, tmpname = tempfile.mkstemp()
try:
# Windows does not allow mappings on empty files
os.write(tmpfd, b' ')
os.fsync(tmpfd)
try:
mm = mmap.mmap(tmpfd, 1, access=mmap.ACCESS_WRITE)
except OSError as exc:
warnings.warn('Failed to create mmap: {}; mmap use will be '
'disabled'.format(str(exc)), AstropyUserWarning)
del exc
return False
try:
mm.flush()
except OSError:
warnings.warn('mmap.flush is unavailable on this platform; '
'using mmap in writeable mode will be disabled',
AstropyUserWarning)
return False
finally:
mm.close()
finally:
os.close(tmpfd)
os.remove(tmpname)
return True
def _open_zipfile(self, fileobj, mode):
"""Limited support for zipfile.ZipFile objects containing a single
a file. Allows reading only for now by extracting the file to a
tempfile.
"""
if mode in ('update', 'append'):
raise OSError(
"Writing to zipped fits files is not currently "
"supported")
if not isinstance(fileobj, zipfile.ZipFile):
zfile = zipfile.ZipFile(fileobj)
close = True
else:
zfile = fileobj
close = False
namelist = zfile.namelist()
if len(namelist) != 1:
raise OSError(
"Zip files with multiple members are not supported.")
self._file = tempfile.NamedTemporaryFile(suffix='.fits')
self._file.write(zfile.read(namelist[0]))
if close:
zfile.close()
# We just wrote the contents of the first file in the archive to a new
# temp file, which now serves as our underlying file object. So it's
# necessary to reset the position back to the beginning
self._file.seek(0)
|
b36d779f3ab9aca99fc3bddf61076370d65c68f6fe35d986a29146d8c8c41560 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import re
import warnings
from collections import OrderedDict
from .. import registry as io_registry
from ... import units as u
from ...table import Table, serialize, meta, Column, MaskedColumn
from ...table.table import has_info_class
from ...time import Time
from ...utils.exceptions import AstropyUserWarning
from ...utils.data_info import MixinInfo, serialize_context_as
from . import HDUList, TableHDU, BinTableHDU, GroupsHDU
from .column import KEYWORD_NAMES
from .convenience import table_to_hdu
from .hdu.hdulist import fitsopen as fits_open
from .util import first
# FITS file signature as per RFC 4047
FITS_SIGNATURE = (b"\x53\x49\x4d\x50\x4c\x45\x20\x20\x3d\x20\x20\x20\x20\x20"
b"\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20"
b"\x20\x54")
# Keywords to remove for all tables that are read in
REMOVE_KEYWORDS = ['XTENSION', 'BITPIX', 'NAXIS', 'NAXIS1', 'NAXIS2',
'PCOUNT', 'GCOUNT', 'TFIELDS', 'THEAP']
# Column-specific keywords regex
COLUMN_KEYWORD_REGEXP = '(' + '|'.join(KEYWORD_NAMES) + ')[0-9]+'
def is_column_keyword(keyword):
return re.match(COLUMN_KEYWORD_REGEXP, keyword) is not None
def is_fits(origin, filepath, fileobj, *args, **kwargs):
"""
Determine whether `origin` is a FITS file.
Parameters
----------
origin : str or readable file-like object
Path or file object containing a potential FITS file.
Returns
-------
is_fits : bool
Returns `True` if the given file is a FITS file.
"""
if fileobj is not None:
pos = fileobj.tell()
sig = fileobj.read(30)
fileobj.seek(pos)
return sig == FITS_SIGNATURE
elif filepath is not None:
if filepath.lower().endswith(('.fits', '.fits.gz', '.fit', '.fit.gz',
'.fts', '.fts.gz')):
return True
elif isinstance(args[0], (HDUList, TableHDU, BinTableHDU, GroupsHDU)):
return True
else:
return False
def _decode_mixins(tbl):
"""Decode a Table ``tbl`` that has astropy Columns + appropriate meta-data into
the corresponding table with mixin columns (as appropriate).
"""
# If available read in __serialized_columns__ meta info which is stored
# in FITS COMMENTS between two sentinels.
try:
i0 = tbl.meta['comments'].index('--BEGIN-ASTROPY-SERIALIZED-COLUMNS--')
i1 = tbl.meta['comments'].index('--END-ASTROPY-SERIALIZED-COLUMNS--')
except (ValueError, KeyError):
return tbl
# The YAML data are split into COMMENT cards, with lines longer than 70
# characters being split with a continuation character \ (backslash).
# Strip the backslashes and join together.
continuation_line = False
lines = []
for line in tbl.meta['comments'][i0 + 1:i1]:
if continuation_line:
lines[-1] = lines[-1] + line[:70]
else:
lines.append(line[:70])
continuation_line = len(line) == 71
del tbl.meta['comments'][i0:i1 + 1]
if not tbl.meta['comments']:
del tbl.meta['comments']
info = meta.get_header_from_yaml(lines)
# Add serialized column information to table meta for use in constructing mixins
tbl.meta['__serialized_columns__'] = info['meta']['__serialized_columns__']
# Use the `datatype` attribute info to update column attributes that are
# NOT already handled via standard FITS column keys (name, dtype, unit).
for col in info['datatype']:
for attr in ['format', 'description', 'meta']:
if attr in col:
setattr(tbl[col['name']].info, attr, col[attr])
# Construct new table with mixins, using tbl.meta['__serialized_columns__']
# as guidance.
tbl = serialize._construct_mixins_from_columns(tbl)
return tbl
def read_table_fits(input, hdu=None, astropy_native=False, memmap=False,
character_as_bytes=True):
"""
Read a Table object from an FITS file
If the ``astropy_native`` argument is ``True``, then input FITS columns
which are representations of an astropy core object will be converted to
that class and stored in the ``Table`` as "mixin columns". Currently this
is limited to FITS columns which adhere to the FITS Time standard, in which
case they will be converted to a `~astropy.time.Time` column in the output
table.
Parameters
----------
input : str or file-like object or compatible `astropy.io.fits` HDU object
If a string, the filename to read the table from. If a file object, or
a compatible HDU object, the object to extract the table from. The
following `astropy.io.fits` HDU objects can be used as input:
- :class:`~astropy.io.fits.hdu.table.TableHDU`
- :class:`~astropy.io.fits.hdu.table.BinTableHDU`
- :class:`~astropy.io.fits.hdu.table.GroupsHDU`
- :class:`~astropy.io.fits.hdu.hdulist.HDUList`
hdu : int or str, optional
The HDU to read the table from.
astropy_native : bool, optional
Read in FITS columns as native astropy objects where possible instead
of standard Table Column objects. Default is False.
memmap : bool, optional
Whether to use memory mapping, which accesses data on disk as needed. If
you are only accessing part of the data, this is often more efficient.
If you want to access all the values in the table, and you are able to
fit the table in memory, you may be better off leaving memory mapping
off. However, if your table would not fit in memory, you should set this
to `True`.
character_as_bytes : bool, optional
If `True`, string columns are stored as Numpy byte arrays (dtype ``S``)
and are converted on-the-fly to unicode strings when accessing
individual elements. If you need to use Numpy unicode arrays (dtype
``U``) internally, you should set this to `False`, but note that this
will use more memory. If set to `False`, string columns will not be
memory-mapped even if ``memmap`` is `True`.
"""
if isinstance(input, HDUList):
# Parse all table objects
tables = OrderedDict()
for ihdu, hdu_item in enumerate(input):
if isinstance(hdu_item, (TableHDU, BinTableHDU, GroupsHDU)):
tables[ihdu] = hdu_item
if len(tables) > 1:
if hdu is None:
warnings.warn("hdu= was not specified but multiple tables"
" are present, reading in first available"
" table (hdu={0})".format(first(tables)),
AstropyUserWarning)
hdu = first(tables)
# hdu might not be an integer, so we first need to convert it
# to the correct HDU index
hdu = input.index_of(hdu)
if hdu in tables:
table = tables[hdu]
else:
raise ValueError("No table found in hdu={0}".format(hdu))
elif len(tables) == 1:
table = tables[first(tables)]
else:
raise ValueError("No table found")
elif isinstance(input, (TableHDU, BinTableHDU, GroupsHDU)):
table = input
else:
hdulist = fits_open(input, character_as_bytes=character_as_bytes,
memmap=memmap)
try:
return read_table_fits(hdulist, hdu=hdu,
astropy_native=astropy_native)
finally:
hdulist.close()
# Check if table is masked
masked = any(col.null is not None for col in table.columns)
# TODO: in future, it may make more sense to do this column-by-column,
# rather than via the structured array.
# In the loop below we access the data using data[col.name] rather than
# col.array to make sure that the data is scaled correctly if needed.
data = table.data
columns = []
for col in data.columns:
# Set column data
if masked:
column = MaskedColumn(data=data[col.name], name=col.name, copy=False)
if col.null is not None:
column.set_fill_value(col.null)
column.mask[column.data == col.null] = True
else:
column = Column(data=data[col.name], name=col.name, copy=False)
# Copy over units
if col.unit is not None:
column.unit = u.Unit(col.unit, format='fits', parse_strict='silent')
columns.append(column)
# Create Table object
t = Table(columns, masked=masked, copy=False)
# TODO: deal properly with unsigned integers
hdr = table.header
if astropy_native:
# Avoid circular imports, and also only import if necessary.
from .fitstime import fits_to_time
hdr = fits_to_time(hdr, t)
for key, value, comment in hdr.cards:
if key in ['COMMENT', 'HISTORY']:
# Convert to io.ascii format
if key == 'COMMENT':
key = 'comments'
if key in t.meta:
t.meta[key].append(value)
else:
t.meta[key] = [value]
elif key in t.meta: # key is duplicate
if isinstance(t.meta[key], list):
t.meta[key].append(value)
else:
t.meta[key] = [t.meta[key], value]
elif is_column_keyword(key) or key in REMOVE_KEYWORDS:
pass
else:
t.meta[key] = value
# TODO: implement masking
# Decode any mixin columns that have been stored as standard Columns.
t = _decode_mixins(t)
return t
def _encode_mixins(tbl):
"""Encode a Table ``tbl`` that may have mixin columns to a Table with only
astropy Columns + appropriate meta-data to allow subsequent decoding.
"""
# Determine if information will be lost without serializing meta. This is hardcoded
# to the set difference between column info attributes and what FITS can store
# natively (name, dtype, unit). See _get_col_attributes() in table/meta.py for where
# this comes from.
info_lost = any(any(getattr(col.info, attr, None) not in (None, {})
for attr in ('format', 'description', 'meta'))
for col in tbl.itercols())
# If PyYAML is not available then check to see if there are any mixin cols
# that *require* YAML serialization. FITS already has support for Time,
# Quantity, so if those are the only mixins the proceed without doing the
# YAML bit, for backward compatibility (i.e. not requiring YAML to write
# Time or Quantity). In this case other mixin column meta (e.g.
# description or meta) will be silently dropped, consistent with astropy <=
# 2.0 behavior.
try:
import yaml
except ImportError:
for col in tbl.itercols():
if (has_info_class(col, MixinInfo) and
col.__class__ not in (u.Quantity, Time)):
raise TypeError("cannot write type {} column '{}' "
"to FITS without PyYAML installed."
.format(col.__class__.__name__, col.info.name))
else:
if info_lost:
warnings.warn("table contains column(s) with defined 'format',"
" 'description', or 'meta' info attributes. These"
" will be dropped unless you install PyYAML.",
AstropyUserWarning)
return tbl
# Convert the table to one with no mixins, only Column objects. This adds
# meta data which is extracted with meta.get_yaml_from_table. This ignores
# Time-subclass columns and leave them in the table so that the downstream
# FITS Time handling does the right thing.
with serialize_context_as('fits'):
encode_tbl = serialize._represent_mixins_as_columns(
tbl, exclude_classes=(Time,))
# If the encoded table is unchanged then there were no mixins. But if there
# is column metadata (format, description, meta) that would be lost, then
# still go through the serialized columns machinery.
if encode_tbl is tbl and not info_lost:
return tbl
# Get the YAML serialization of information describing the table columns.
# This is re-using ECSV code that combined existing table.meta with with
# the extra __serialized_columns__ key. For FITS the table.meta is handled
# by the native FITS connect code, so don't include that in the YAML
# output.
ser_col = '__serialized_columns__'
# encode_tbl might not have a __serialized_columns__ key if there were no mixins,
# but machinery below expects it to be available, so just make an empty dict.
encode_tbl.meta.setdefault(ser_col, {})
tbl_meta_copy = encode_tbl.meta.copy()
try:
encode_tbl.meta = {ser_col: encode_tbl.meta[ser_col]}
meta_yaml_lines = meta.get_yaml_from_table(encode_tbl)
finally:
encode_tbl.meta = tbl_meta_copy
del encode_tbl.meta[ser_col]
if 'comments' not in encode_tbl.meta:
encode_tbl.meta['comments'] = []
encode_tbl.meta['comments'].append('--BEGIN-ASTROPY-SERIALIZED-COLUMNS--')
for line in meta_yaml_lines:
# Split line into 70 character chunks for COMMENT cards
idxs = list(range(0, len(line) + 70, 70))
lines = [line[i0:i1] + '\\' for i0, i1 in zip(idxs[:-1], idxs[1:])]
lines[-1] = lines[-1][:-1]
encode_tbl.meta['comments'].extend(lines)
encode_tbl.meta['comments'].append('--END-ASTROPY-SERIALIZED-COLUMNS--')
return encode_tbl
def write_table_fits(input, output, overwrite=False):
"""
Write a Table object to a FITS file
Parameters
----------
input : Table
The table to write out.
output : str
The filename to write the table to.
overwrite : bool
Whether to overwrite any existing file without warning.
"""
# Encode any mixin columns into standard Columns.
input = _encode_mixins(input)
table_hdu = table_to_hdu(input, character_as_bytes=True)
# Check if output file already exists
if isinstance(output, str) and os.path.exists(output):
if overwrite:
os.remove(output)
else:
raise OSError("File exists: {0}".format(output))
table_hdu.writeto(output)
io_registry.register_reader('fits', Table, read_table_fits)
io_registry.register_writer('fits', Table, write_table_fits)
io_registry.register_identifier('fits', Table, is_fits)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.