hash
stringlengths
64
64
content
stringlengths
0
1.51M
5e84a031c0b3f4163e9d1f66a99faf4e272736bcd366411d8ab2d957c2e2e1a1
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Utilities for generating new Python code at runtime.""" import inspect import itertools import keyword import os import re import textwrap from .introspection import find_current_module __all__ = ['make_function_with_signature'] _ARGNAME_RE = re.compile(r'^[A-Za-z][A-Za-z_]*') """ Regular expression used my make_func which limits the allowed argument names for the created function. Only valid Python variable names in the ASCII range and not beginning with '_' are allowed, currently. """ def make_function_with_signature(func, args=(), kwargs={}, varargs=None, varkwargs=None, name=None): """ Make a new function from an existing function but with the desired signature. The desired signature must of course be compatible with the arguments actually accepted by the input function. The ``args`` are strings that should be the names of the positional arguments. ``kwargs`` can map names of keyword arguments to their default values. It may be either a ``dict`` or a list of ``(keyword, default)`` tuples. If ``varargs`` is a string it is added to the positional arguments as ``*<varargs>``. Likewise ``varkwargs`` can be the name for a variable keyword argument placeholder like ``**<varkwargs>``. If not specified the name of the new function is taken from the original function. Otherwise, the ``name`` argument can be used to specify a new name. Note, the names may only be valid Python variable names. """ pos_args = [] key_args = [] if isinstance(kwargs, dict): iter_kwargs = kwargs.items() else: iter_kwargs = iter(kwargs) # Check that all the argument names are valid for item in itertools.chain(args, iter_kwargs): if isinstance(item, tuple): argname = item[0] key_args.append(item) else: argname = item pos_args.append(item) if keyword.iskeyword(argname) or not _ARGNAME_RE.match(argname): raise SyntaxError('invalid argument name: {0}'.format(argname)) for item in (varargs, varkwargs): if item is not None: if keyword.iskeyword(item) or not _ARGNAME_RE.match(item): raise SyntaxError('invalid argument name: {0}'.format(item)) def_signature = [', '.join(pos_args)] if varargs: def_signature.append(', *{0}'.format(varargs)) call_signature = def_signature[:] if name is None: name = func.__name__ global_vars = {'__{0}__func'.format(name): func} local_vars = {} # Make local variables to handle setting the default args for idx, item in enumerate(key_args): key, value = item default_var = '_kwargs{0}'.format(idx) local_vars[default_var] = value def_signature.append(', {0}={1}'.format(key, default_var)) call_signature.append(', {0}={0}'.format(key)) if varkwargs: def_signature.append(', **{0}'.format(varkwargs)) call_signature.append(', **{0}'.format(varkwargs)) def_signature = ''.join(def_signature).lstrip(', ') call_signature = ''.join(call_signature).lstrip(', ') mod = find_current_module(2) frm = inspect.currentframe().f_back if mod: filename = mod.__file__ modname = mod.__name__ if filename.endswith('.pyc'): filename = os.path.splitext(filename)[0] + '.py' else: filename = '<string>' modname = '__main__' # Subtract 2 from the line number since the length of the template itself # is two lines. Therefore we have to subtract those off in order for the # pointer in tracebacks from __{name}__func to point to the right spot. lineno = frm.f_lineno - 2 # The lstrip is in case there were *no* positional arguments (a rare case) # in any context this will actually be used... template = textwrap.dedent("""{0}\ def {name}({sig1}): return __{name}__func({sig2}) """.format('\n' * lineno, name=name, sig1=def_signature, sig2=call_signature)) code = compile(template, filename, 'single') eval(code, global_vars, local_vars) new_func = local_vars[name] new_func.__module__ = modname new_func.__doc__ = func.__doc__ return new_func
33f59fda24a074bb22b500845802ee0ac897c5065681fe05145ea7f729bb16e6
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for console input and output. """ import codecs import locale import re import math import multiprocessing import os import struct import sys import threading import time try: import fcntl import termios import signal _CAN_RESIZE_TERMINAL = True except ImportError: _CAN_RESIZE_TERMINAL = False from .. import conf from .misc import isiterable from .decorators import classproperty __all__ = [ 'isatty', 'color_print', 'human_time', 'human_file_size', 'ProgressBar', 'Spinner', 'print_code_line', 'ProgressBarOrSpinner', 'terminal_size'] _DEFAULT_ENCODING = 'utf-8' class _IPython: """Singleton class given access to IPython streams, etc.""" @classproperty def get_ipython(cls): try: from IPython import get_ipython except ImportError: pass return get_ipython @classproperty def OutStream(cls): if not hasattr(cls, '_OutStream'): cls._OutStream = None try: cls.get_ipython() except NameError: return None try: from ipykernel.iostream import OutStream except ImportError: try: from IPython.zmq.iostream import OutStream except ImportError: from IPython import version_info if version_info[0] >= 4: return None try: from IPython.kernel.zmq.iostream import OutStream except ImportError: return None cls._OutStream = OutStream return cls._OutStream @classproperty def ipyio(cls): if not hasattr(cls, '_ipyio'): try: from IPython.utils import io except ImportError: cls._ipyio = None else: cls._ipyio = io return cls._ipyio @classproperty def IOStream(cls): if cls.ipyio is None: return None else: return cls.ipyio.IOStream @classmethod def get_stream(cls, stream): return getattr(cls.ipyio, stream) def _get_stdout(stderr=False): """ This utility function contains the logic to determine what streams to use by default for standard out/err. Typically this will just return `sys.stdout`, but it contains additional logic for use in IPython on Windows to determine the correct stream to use (usually ``IPython.util.io.stdout`` but only if sys.stdout is a TTY). """ if stderr: stream = 'stderr' else: stream = 'stdout' sys_stream = getattr(sys, stream) if not isatty(sys_stream) or _IPython.OutStream is None: return sys_stream # Our system stream is an atty and we're in ipython. ipyio_stream = _IPython.get_stream(stream) if ipyio_stream is not None and isatty(ipyio_stream): # Use the IPython console output stream return ipyio_stream else: # sys.stdout was set to some other non-TTY stream (a file perhaps) # so just use it directly return sys_stream def isatty(file): """ Returns `True` if ``file`` is a tty. Most built-in Python file-like objects have an `isatty` member, but some user-defined types may not, so this assumes those are not ttys. """ if (multiprocessing.current_process().name != 'MainProcess' or threading.current_thread().getName() != 'MainThread'): return False if hasattr(file, 'isatty'): return file.isatty() # Use two isinstance calls to only evaluate IOStream when necessary. if (_IPython.OutStream is None or (not isinstance(file, _IPython.OutStream) and not isinstance(file, _IPython.IOStream))): return False # File is an IPython OutStream or IOStream. Check whether: # - File name is 'stdout'; or # - File wraps a Console if getattr(file, 'name', None) == 'stdout': return True if hasattr(file, 'stream'): # On Windows, in IPython 2 the standard I/O streams will wrap # pyreadline.Console objects if pyreadline is available; this should # be considered a TTY. try: from pyreadline.console import Console as PyreadlineConsole except ImportError: return False return isinstance(file.stream, PyreadlineConsole) return False def terminal_size(file=None): """ Returns a tuple (height, width) containing the height and width of the terminal. This function will look for the width in height in multiple areas before falling back on the width and height in astropy's configuration. """ if file is None: file = _get_stdout() try: s = struct.pack(str("HHHH"), 0, 0, 0, 0) x = fcntl.ioctl(file, termios.TIOCGWINSZ, s) (lines, width, xpixels, ypixels) = struct.unpack(str("HHHH"), x) if lines > 12: lines -= 6 if width > 10: width -= 1 if lines <= 0 or width <= 0: raise Exception('unable to get terminal size') return (lines, width) except Exception: try: # see if POSIX standard variables will work return (int(os.environ.get('LINES')), int(os.environ.get('COLUMNS'))) except TypeError: # fall back on configuration variables, or if not # set, (25, 80) lines = conf.max_lines width = conf.max_width if lines is None: lines = 25 if width is None: width = 80 return lines, width def _color_text(text, color): """ Returns a string wrapped in ANSI color codes for coloring the text in a terminal:: colored_text = color_text('Here is a message', 'blue') This won't actually effect the text until it is printed to the terminal. Parameters ---------- text : str The string to return, bounded by the color codes. color : str An ANSI terminal color name. Must be one of: black, red, green, brown, blue, magenta, cyan, lightgrey, default, darkgrey, lightred, lightgreen, yellow, lightblue, lightmagenta, lightcyan, white, or '' (the empty string). """ color_mapping = { 'black': '0;30', 'red': '0;31', 'green': '0;32', 'brown': '0;33', 'blue': '0;34', 'magenta': '0;35', 'cyan': '0;36', 'lightgrey': '0;37', 'default': '0;39', 'darkgrey': '1;30', 'lightred': '1;31', 'lightgreen': '1;32', 'yellow': '1;33', 'lightblue': '1;34', 'lightmagenta': '1;35', 'lightcyan': '1;36', 'white': '1;37'} if sys.platform == 'win32' and _IPython.OutStream is None: # On Windows do not colorize text unless in IPython return text color_code = color_mapping.get(color, '0;39') return '\033[{0}m{1}\033[0m'.format(color_code, text) def _decode_preferred_encoding(s): """Decode the supplied byte string using the preferred encoding for the locale (`locale.getpreferredencoding`) or, if the default encoding is invalid, fall back first on utf-8, then on latin-1 if the message cannot be decoded with utf-8. """ enc = locale.getpreferredencoding() try: try: return s.decode(enc) except LookupError: enc = _DEFAULT_ENCODING return s.decode(enc) except UnicodeDecodeError: return s.decode('latin-1') def _write_with_fallback(s, write, fileobj): """Write the supplied string with the given write function like ``write(s)``, but use a writer for the locale's preferred encoding in case of a UnicodeEncodeError. Failing that attempt to write with 'utf-8' or 'latin-1'. """ if (_IPython.IOStream is not None and isinstance(fileobj, _IPython.IOStream)): # If the output stream is an IPython.utils.io.IOStream object that's # not going to be very helpful to us since it doesn't raise any # exceptions when an error occurs writing to its underlying stream. # There's no advantage to us using IOStream.write directly though; # instead just write directly to its underlying stream: write = fileobj.stream.write try: write(s) return write except UnicodeEncodeError: # Let's try the next approach... pass enc = locale.getpreferredencoding() try: Writer = codecs.getwriter(enc) except LookupError: Writer = codecs.getwriter(_DEFAULT_ENCODING) f = Writer(fileobj) write = f.write try: write(s) return write except UnicodeEncodeError: Writer = codecs.getwriter('latin-1') f = Writer(fileobj) write = f.write # If this doesn't work let the exception bubble up; I'm out of ideas write(s) return write def color_print(*args, end='\n', **kwargs): """ Prints colors and styles to the terminal uses ANSI escape sequences. :: color_print('This is the color ', 'default', 'GREEN', 'green') Parameters ---------- positional args : str The positional arguments come in pairs (*msg*, *color*), where *msg* is the string to display and *color* is the color to display it in. *color* is an ANSI terminal color name. Must be one of: black, red, green, brown, blue, magenta, cyan, lightgrey, default, darkgrey, lightred, lightgreen, yellow, lightblue, lightmagenta, lightcyan, white, or '' (the empty string). file : writeable file-like object, optional Where to write to. Defaults to `sys.stdout`. If file is not a tty (as determined by calling its `isatty` member, if one exists), no coloring will be included. end : str, optional The ending of the message. Defaults to ``\\n``. The end will be printed after resetting any color or font state. """ file = kwargs.get('file', _get_stdout()) write = file.write if isatty(file) and conf.use_color: for i in range(0, len(args), 2): msg = args[i] if i + 1 == len(args): color = '' else: color = args[i + 1] if color: msg = _color_text(msg, color) # Some file objects support writing unicode sensibly on some Python # versions; if this fails try creating a writer using the locale's # preferred encoding. If that fails too give up. write = _write_with_fallback(msg, write, file) write(end) else: for i in range(0, len(args), 2): msg = args[i] write(msg) write(end) def strip_ansi_codes(s): """ Remove ANSI color codes from the string. """ return re.sub('\033\\[([0-9]+)(;[0-9]+)*m', '', s) def human_time(seconds): """ Returns a human-friendly time string that is always exactly 6 characters long. Depending on the number of seconds given, can be one of:: 1w 3d 2d 4h 1h 5m 1m 4s 15s Will be in color if console coloring is turned on. Parameters ---------- seconds : int The number of seconds to represent Returns ------- time : str A human-friendly representation of the given number of seconds that is always exactly 6 characters. """ units = [ ('y', 60 * 60 * 24 * 7 * 52), ('w', 60 * 60 * 24 * 7), ('d', 60 * 60 * 24), ('h', 60 * 60), ('m', 60), ('s', 1), ] seconds = int(seconds) if seconds < 60: return ' {0:2d}s'.format(seconds) for i in range(len(units) - 1): unit1, limit1 = units[i] unit2, limit2 = units[i + 1] if seconds >= limit1: return '{0:2d}{1}{2:2d}{3}'.format( seconds // limit1, unit1, (seconds % limit1) // limit2, unit2) return ' ~inf' def human_file_size(size): """ Returns a human-friendly string representing a file size that is 2-4 characters long. For example, depending on the number of bytes given, can be one of:: 256b 64k 1.1G Parameters ---------- size : int The size of the file (in bytes) Returns ------- size : str A human-friendly representation of the size of the file """ if hasattr(size, 'unit'): # Import units only if necessary because the import takes a # significant time [#4649] from .. import units as u size = u.Quantity(size, u.byte).value suffixes = ' kMGTPEZY' if size == 0: num_scale = 0 else: num_scale = int(math.floor(math.log(size) / math.log(1000))) if num_scale > 7: suffix = '?' else: suffix = suffixes[num_scale] num_scale = int(math.pow(1000, num_scale)) value = size / num_scale str_value = str(value) if suffix == ' ': str_value = str_value[:str_value.index('.')] elif str_value[2] == '.': str_value = str_value[:2] else: str_value = str_value[:3] return "{0:>3s}{1}".format(str_value, suffix) class _mapfunc(object): """ A function wrapper to support ProgressBar.map(). """ def __init__(self, func): self._func = func def __call__(self, i_arg): i, arg = i_arg return i, self._func(arg) class ProgressBar: """ A class to display a progress bar in the terminal. It is designed to be used either with the ``with`` statement:: with ProgressBar(len(items)) as bar: for item in enumerate(items): bar.update() or as a generator:: for item in ProgressBar(items): item.process() """ def __init__(self, total_or_items, ipython_widget=False, file=None): """ Parameters ---------- total_or_items : int or sequence If an int, the number of increments in the process being tracked. If a sequence, the items to iterate over. ipython_widget : bool, optional If `True`, the progress bar will display as an IPython notebook widget. file : writable file-like object, optional The file to write the progress bar to. Defaults to `sys.stdout`. If ``file`` is not a tty (as determined by calling its `isatty` member, if any, or special case hacks to detect the IPython console), the progress bar will be completely silent. """ if file is None: file = _get_stdout() if not ipython_widget and not isatty(file): self.update = self._silent_update self._silent = True else: self._silent = False if isiterable(total_or_items): self._items = iter(total_or_items) self._total = len(total_or_items) else: try: self._total = int(total_or_items) except TypeError: raise TypeError("First argument must be int or sequence") else: self._items = iter(range(self._total)) self._file = file self._start_time = time.time() self._human_total = human_file_size(self._total) self._ipython_widget = ipython_widget self._signal_set = False if not ipython_widget: self._should_handle_resize = ( _CAN_RESIZE_TERMINAL and self._file.isatty()) self._handle_resize() if self._should_handle_resize: signal.signal(signal.SIGWINCH, self._handle_resize) self._signal_set = True self.update(0) def _handle_resize(self, signum=None, frame=None): terminal_width = terminal_size(self._file)[1] self._bar_length = terminal_width - 37 def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if not self._silent: if exc_type is None: self.update(self._total) self._file.write('\n') self._file.flush() if self._signal_set: signal.signal(signal.SIGWINCH, signal.SIG_DFL) def __iter__(self): return self def __next__(self): try: rv = next(self._items) except StopIteration: self.__exit__(None, None, None) raise else: self.update() return rv def update(self, value=None): """ Update progress bar via the console or notebook accordingly. """ # Update self.value if value is None: value = self._current_value + 1 self._current_value = value # Choose the appropriate environment if self._ipython_widget: self._update_ipython_widget(value) else: self._update_console(value) def _update_console(self, value=None): """ Update the progress bar to the given value (out of the total given to the constructor). """ if self._total == 0: frac = 1.0 else: frac = float(value) / float(self._total) file = self._file write = file.write if frac > 1: bar_fill = int(self._bar_length) else: bar_fill = int(float(self._bar_length) * frac) write('\r|') color_print('=' * bar_fill, 'blue', file=file, end='') if bar_fill < self._bar_length: color_print('>', 'green', file=file, end='') write('-' * (self._bar_length - bar_fill - 1)) write('|') if value >= self._total: t = time.time() - self._start_time prefix = ' ' elif value <= 0: t = None prefix = '' else: t = ((time.time() - self._start_time) * (1.0 - frac)) / frac prefix = ' ETA ' write(' {0:>4s}/{1:>4s}'.format( human_file_size(value), self._human_total)) write(' ({:>6.2%})'.format(frac)) write(prefix) if t is not None: write(human_time(t)) self._file.flush() def _update_ipython_widget(self, value=None): """ Update the progress bar to the given value (out of a total given to the constructor). This method is for use in the IPython notebook 2+. """ # Create and display an empty progress bar widget, # if none exists. if not hasattr(self, '_widget'): # Import only if an IPython widget, i.e., widget in iPython NB from IPython import version_info if version_info[0] < 4: from IPython.html import widgets self._widget = widgets.FloatProgressWidget() else: _IPython.get_ipython() from ipywidgets import widgets self._widget = widgets.FloatProgress() from IPython.display import display display(self._widget) self._widget.value = 0 # Calculate percent completion, and update progress bar frac = (value/self._total) self._widget.value = frac * 100 self._widget.description = ' ({:>6.2%})'.format(frac) def _silent_update(self, value=None): pass @classmethod def map(cls, function, items, multiprocess=False, file=None, step=100, ipython_widget=False): """ Does a `map` operation while displaying a progress bar with percentage complete. The map operation may run on arbitrary order on the items, but the results are returned in sequential order. :: def work(i): print(i) ProgressBar.map(work, range(50)) Parameters ---------- function : function Function to call for each step items : sequence Sequence where each element is a tuple of arguments to pass to *function*. multiprocess : bool, optional If `True`, use the `multiprocessing` module to distribute each task to a different processor core. ipython_widget : bool, optional If `True`, the progress bar will display as an IPython notebook widget. file : writeable file-like object, optional The file to write the progress bar to. Defaults to `sys.stdout`. If ``file`` is not a tty (as determined by calling its `isatty` member, if any), the scrollbar will be completely silent. step : int, optional Update the progress bar at least every *step* steps (default: 100). If ``multiprocess`` is `True`, this will affect the size of the chunks of ``items`` that are submitted as separate tasks to the process pool. A large step size may make the job complete faster if ``items`` is very long. """ if multiprocess: function = _mapfunc(function) items = list(enumerate(items)) results = cls.map_unordered(function, items, multiprocess=multiprocess, file=file, step=step, ipython_widget=ipython_widget) if multiprocess: _, results = zip(*sorted(results)) results = list(results) return results @classmethod def map_unordered(cls, function, items, multiprocess=False, file=None, step=100, ipython_widget=False): """ Does a `map` operation while displaying a progress bar with percentage complete. The map operation may run on arbitrary order on the items, and the results may be returned in arbitrary order. :: def work(i): print(i) ProgressBar.map(work, range(50)) Parameters ---------- function : function Function to call for each step items : sequence Sequence where each element is a tuple of arguments to pass to *function*. multiprocess : bool, optional If `True`, use the `multiprocessing` module to distribute each task to a different processor core. ipython_widget : bool, optional If `True`, the progress bar will display as an IPython notebook widget. file : writeable file-like object, optional The file to write the progress bar to. Defaults to `sys.stdout`. If ``file`` is not a tty (as determined by calling its `isatty` member, if any), the scrollbar will be completely silent. step : int, optional Update the progress bar at least every *step* steps (default: 100). If ``multiprocess`` is `True`, this will affect the size of the chunks of ``items`` that are submitted as separate tasks to the process pool. A large step size may make the job complete faster if ``items`` is very long. """ results = [] if file is None: file = _get_stdout() with cls(len(items), ipython_widget=ipython_widget, file=file) as bar: if bar._ipython_widget: chunksize = step else: default_step = max(int(float(len(items)) / bar._bar_length), 1) chunksize = min(default_step, step) if not multiprocess: for i, item in enumerate(items): results.append(function(item)) if (i % chunksize) == 0: bar.update(i) else: p = multiprocessing.Pool() for i, result in enumerate( p.imap_unordered(function, items, chunksize=chunksize)): bar.update(i) results.append(result) p.close() p.join() return results class Spinner: """ A class to display a spinner in the terminal. It is designed to be used with the ``with`` statement:: with Spinner("Reticulating splines", "green") as s: for item in enumerate(items): s.next() """ _default_unicode_chars = "◓◑◒◐" _default_ascii_chars = "-/|\\" def __init__(self, msg, color='default', file=None, step=1, chars=None): """ Parameters ---------- msg : str The message to print color : str, optional An ANSI terminal color name. Must be one of: black, red, green, brown, blue, magenta, cyan, lightgrey, default, darkgrey, lightred, lightgreen, yellow, lightblue, lightmagenta, lightcyan, white. file : writeable file-like object, optional The file to write the spinner to. Defaults to `sys.stdout`. If ``file`` is not a tty (as determined by calling its `isatty` member, if any, or special case hacks to detect the IPython console), the spinner will be completely silent. step : int, optional Only update the spinner every *step* steps chars : str, optional The character sequence to use for the spinner """ if file is None: file = _get_stdout() self._msg = msg self._color = color self._file = file self._step = step if chars is None: if conf.unicode_output: chars = self._default_unicode_chars else: chars = self._default_ascii_chars self._chars = chars self._silent = not isatty(file) def _iterator(self): chars = self._chars index = 0 file = self._file write = file.write flush = file.flush try_fallback = True while True: write('\r') color_print(self._msg, self._color, file=file, end='') write(' ') try: if try_fallback: write = _write_with_fallback(chars[index], write, file) else: write(chars[index]) except UnicodeError: # If even _write_with_fallback failed for any reason just give # up on trying to use the unicode characters chars = self._default_ascii_chars write(chars[index]) try_fallback = False # No good will come of using this again flush() yield for i in range(self._step): yield index = (index + 1) % len(chars) def __enter__(self): if self._silent: return self._silent_iterator() else: return self._iterator() def __exit__(self, exc_type, exc_value, traceback): file = self._file write = file.write flush = file.flush if not self._silent: write('\r') color_print(self._msg, self._color, file=file, end='') if exc_type is None: color_print(' [Done]', 'green', file=file) else: color_print(' [Failed]', 'red', file=file) flush() def _silent_iterator(self): color_print(self._msg, self._color, file=self._file, end='') self._file.flush() while True: yield class ProgressBarOrSpinner: """ A class that displays either a `ProgressBar` or `Spinner` depending on whether the total size of the operation is known or not. It is designed to be used with the ``with`` statement:: if file.has_length(): length = file.get_length() else: length = None bytes_read = 0 with ProgressBarOrSpinner(length) as bar: while file.read(blocksize): bytes_read += blocksize bar.update(bytes_read) """ def __init__(self, total, msg, color='default', file=None): """ Parameters ---------- total : int or None If an int, the number of increments in the process being tracked and a `ProgressBar` is displayed. If `None`, a `Spinner` is displayed. msg : str The message to display above the `ProgressBar` or alongside the `Spinner`. color : str, optional The color of ``msg``, if any. Must be an ANSI terminal color name. Must be one of: black, red, green, brown, blue, magenta, cyan, lightgrey, default, darkgrey, lightred, lightgreen, yellow, lightblue, lightmagenta, lightcyan, white. file : writable file-like object, optional The file to write the to. Defaults to `sys.stdout`. If ``file`` is not a tty (as determined by calling its `isatty` member, if any), only ``msg`` will be displayed: the `ProgressBar` or `Spinner` will be silent. """ if file is None: file = _get_stdout() if total is None or not isatty(file): self._is_spinner = True self._obj = Spinner(msg, color=color, file=file) else: self._is_spinner = False color_print(msg, color, file=file) self._obj = ProgressBar(total, file=file) def __enter__(self): self._iter = self._obj.__enter__() return self def __exit__(self, exc_type, exc_value, traceback): return self._obj.__exit__(exc_type, exc_value, traceback) def update(self, value): """ Update the progress bar to the given value (out of the total given to the constructor. """ if self._is_spinner: next(self._iter) else: self._obj.update(value) def print_code_line(line, col=None, file=None, tabwidth=8, width=70): """ Prints a line of source code, highlighting a particular character position in the line. Useful for displaying the context of error messages. If the line is more than ``width`` characters, the line is truncated accordingly and '…' characters are inserted at the front and/or end. It looks like this:: there_is_a_syntax_error_here : ^ Parameters ---------- line : unicode The line of code to display col : int, optional The character in the line to highlight. ``col`` must be less than ``len(line)``. file : writeable file-like object, optional Where to write to. Defaults to `sys.stdout`. tabwidth : int, optional The number of spaces per tab (``'\\t'``) character. Default is 8. All tabs will be converted to spaces to ensure that the caret lines up with the correct column. width : int, optional The width of the display, beyond which the line will be truncated. Defaults to 70 (this matches the default in the standard library's `textwrap` module). """ if file is None: file = _get_stdout() if conf.unicode_output: ellipsis = '…' else: ellipsis = '...' write = file.write if col is not None: if col >= len(line): raise ValueError('col must be less the the line lenght.') ntabs = line[:col].count('\t') col += ntabs * (tabwidth - 1) line = line.rstrip('\n') line = line.replace('\t', ' ' * tabwidth) if col is not None and col > width: new_col = min(width // 2, len(line) - col) offset = col - new_col line = line[offset + len(ellipsis):] width -= len(ellipsis) new_col = col col -= offset color_print(ellipsis, 'darkgrey', file=file, end='') if len(line) > width: write(line[:width - len(ellipsis)]) color_print(ellipsis, 'darkgrey', file=file) else: write(line) write('\n') if col is not None: write(' ' * col) color_print('^', 'red', file=file) # The following four Getch* classes implement unbuffered character reading from # stdin on Windows, linux, MacOSX. This is taken directly from ActiveState # Code Recipes: # http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/ # class Getch: """Get a single character from standard input without screen echo. Returns ------- char : str (one character) """ def __init__(self): try: self.impl = _GetchWindows() except ImportError: try: self.impl = _GetchMacCarbon() except (ImportError, AttributeError): self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty # pylint: disable=W0611 import sys # pylint: disable=W0611 # import termios now or else you'll get the Unix # version on the Mac import termios # pylint: disable=W0611 def __call__(self): import sys import tty import termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt # pylint: disable=W0611 def __call__(self): import msvcrt return msvcrt.getch() class _GetchMacCarbon: """ A function which returns the current ASCII key that is down; if no ASCII key is down, the null string is returned. The page http://www.mactech.com/macintosh-c/chap02-1.html was very helpful in figuring out how to do this. """ def __init__(self): import Carbon Carbon.Evt # see if it has this (in Unix, it doesn't) def __call__(self): import Carbon if Carbon.Evt.EventAvail(0x0008)[0] == 0: # 0x0008 is the keyDownMask return '' else: # # The event contains the following info: # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] # # The message (msg) contains the ASCII char which is # extracted with the 0x000000FF charCodeMask; this # number is converted to an ASCII character with chr() and # returned # (what, msg, when, where, mod) = Carbon.Evt.GetNextEvent(0x0008)[1] return chr(msg & 0x000000FF)
85f6245280a8df4012bdb07f27586dd751db6d80339023ec24fcc599c22e4947
""" A simple class to manage a piece of global science state. See :ref:`config-developer` for more details. """ __all__ = ['ScienceState'] class ScienceState: """ Science state subclasses are used to manage global items that can affect science results. Subclasses will generally override `validate` to convert from any of the acceptable inputs (such as strings) to the appropriate internal objects, and set an initial value to the ``_value`` member so it has a default. Examples -------- :: class MyState(ScienceState): @classmethod def validate(cls, value): if value not in ('A', 'B', 'C'): raise ValueError("Must be one of A, B, C") return value """ def __init__(self): raise RuntimeError( "This class is a singleton. Do not instantiate.") @classmethod def get(cls): """ Get the current science state value. """ return cls.validate(cls._value) @classmethod def set(cls, value): """ Set the current science state value. """ class _Context: def __init__(self, parent, value): self._value = value self._parent = parent def __enter__(self): pass def __exit__(self, type, value, tb): self._parent._value = self._value def __repr__(self): return ('<ScienceState {0}: {1!r}>' .format(self._parent.__name__, self._parent._value)) ctx = _Context(cls, cls._value) value = cls.validate(value) cls._value = value return ctx @classmethod def validate(cls, value): """ Validate the value and convert it to its native type, if necessary. """ return value
8d1b79a6ca67012280ca4a0012f6baadded13ad5f0ae1113a37a2c250be5836d
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ A module containing specialized collection classes. """ class HomogeneousList(list): """ A subclass of list that contains only elements of a given type or types. If an item that is not of the specified type is added to the list, a `TypeError` is raised. """ def __init__(self, types, values=[]): """ Parameters ---------- types : sequence of types The types to accept. values : sequence, optional An initial set of values. """ self._types = types super().__init__() self.extend(values) def _assert(self, x): if not isinstance(x, self._types): raise TypeError( "homogeneous list must contain only objects of " "type '{}'".format(self._types)) def __iadd__(self, other): self.extend(other) return self def __setitem__(self, idx, value): if isinstance(idx, slice): value = list(value) for item in value: self._assert(item) else: self._assert(value) return super().__setitem__(idx, value) def append(self, x): self._assert(x) return super().append(x) def insert(self, i, x): self._assert(x) return super().insert(i, x) def extend(self, x): for item in x: self._assert(item) super().append(item)
299561406172ebdaa27e5487ca3ada4b24337a0b3fa538f5e69afa96afc76fc2
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Functions related to Python runtime introspection.""" import inspect import re import types import importlib __all__ = ['resolve_name', 'minversion', 'find_current_module', 'isinstancemethod'] __doctest_skip__ = ['find_current_module'] def resolve_name(name, *additional_parts): """Resolve a name like ``module.object`` to an object and return it. This ends up working like ``from module import object`` but is easier to deal with than the `__import__` builtin and supports digging into submodules. Parameters ---------- name : `str` A dotted path to a Python object--that is, the name of a function, class, or other object in a module with the full path to that module, including parent modules, separated by dots. Also known as the fully qualified name of the object. additional_parts : iterable, optional If more than one positional arguments are given, those arguments are automatically dotted together with ``name``. Examples -------- >>> resolve_name('astropy.utils.introspection.resolve_name') <function resolve_name at 0x...> >>> resolve_name('astropy', 'utils', 'introspection', 'resolve_name') <function resolve_name at 0x...> Raises ------ `ImportError` If the module or named object is not found. """ additional_parts = '.'.join(additional_parts) if additional_parts: name = name + '.' + additional_parts parts = name.split('.') if len(parts) == 1: # No dots in the name--just a straight up module import cursor = 1 fromlist = [] else: cursor = len(parts) - 1 fromlist = [parts[-1]] module_name = parts[:cursor] while cursor > 0: try: ret = __import__(str('.'.join(module_name)), fromlist=fromlist) break except ImportError: if cursor == 0: raise cursor -= 1 module_name = parts[:cursor] fromlist = [parts[cursor]] ret = '' for part in parts[cursor:]: try: ret = getattr(ret, part) except AttributeError: raise ImportError(name) return ret def minversion(module, version, inclusive=True, version_path='__version__'): """ Returns `True` if the specified Python module satisfies a minimum version requirement, and `False` if not. By default this uses `pkg_resources.parse_version` to do the version comparison if available. Otherwise it falls back on `distutils.version.LooseVersion`. Parameters ---------- module : module or `str` An imported module of which to check the version, or the name of that module (in which case an import of that module is attempted-- if this fails `False` is returned). version : `str` The version as a string that this module must have at a minimum (e.g. ``'0.12'``). inclusive : `bool` The specified version meets the requirement inclusively (i.e. ``>=``) as opposed to strictly greater than (default: `True`). version_path : `str` A dotted attribute path to follow in the module for the version. Defaults to just ``'__version__'``, which should work for most Python modules. Examples -------- >>> import astropy >>> minversion(astropy, '0.4.4') True """ if isinstance(module, types.ModuleType): module_name = module.__name__ elif isinstance(module, str): module_name = module try: module = resolve_name(module_name) except ImportError: return False else: raise ValueError('module argument must be an actual imported ' 'module, or the import name of the module; ' 'got {0!r}'.format(module)) if '.' not in version_path: have_version = getattr(module, version_path) else: have_version = resolve_name(module.__name__, version_path) try: from pkg_resources import parse_version except ImportError: from distutils.version import LooseVersion as parse_version # LooseVersion raises a TypeError when strings like dev, rc1 are part # of the version number. Match the dotted numbers only. Regex taken # from PEP440, https://www.python.org/dev/peps/pep-0440/, Appendix B expr = '^([1-9]\\d*!)?(0|[1-9]\\d*)(\\.(0|[1-9]\\d*))*' m = re.match(expr, version) if m: version = m.group(0) if inclusive: return parse_version(have_version) >= parse_version(version) else: return parse_version(have_version) > parse_version(version) def find_current_module(depth=1, finddiff=False): """ Determines the module/package from which this function is called. This function has two modes, determined by the ``finddiff`` option. it will either simply go the requested number of frames up the call stack (if ``finddiff`` is False), or it will go up the call stack until it reaches a module that is *not* in a specified set. Parameters ---------- depth : int Specifies how far back to go in the call stack (0-indexed, so that passing in 0 gives back `astropy.utils.misc`). finddiff : bool or list If False, the returned ``mod`` will just be ``depth`` frames up from the current frame. Otherwise, the function will start at a frame ``depth`` up from current, and continue up the call stack to the first module that is *different* from those in the provided list. In this case, ``finddiff`` can be a list of modules or modules names. Alternatively, it can be True, which will use the module ``depth`` call stack frames up as the module the returned module most be different from. Returns ------- mod : module or None The module object or None if the package cannot be found. The name of the module is available as the ``__name__`` attribute of the returned object (if it isn't None). Raises ------ ValueError If ``finddiff`` is a list with an invalid entry. Examples -------- The examples below assume that there are two modules in a package named ``pkg``. ``mod1.py``:: def find1(): from astropy.utils import find_current_module print find_current_module(1).__name__ def find2(): from astropy.utils import find_current_module cmod = find_current_module(2) if cmod is None: print 'None' else: print cmod.__name__ def find_diff(): from astropy.utils import find_current_module print find_current_module(0,True).__name__ ``mod2.py``:: def find(): from .mod1 import find2 find2() With these modules in place, the following occurs:: >>> from pkg import mod1, mod2 >>> from astropy.utils import find_current_module >>> mod1.find1() pkg.mod1 >>> mod1.find2() None >>> mod2.find() pkg.mod2 >>> find_current_module(0) <module 'astropy.utils.misc' from 'astropy/utils/misc.py'> >>> mod1.find_diff() pkg.mod1 """ frm = inspect.currentframe() for i in range(depth): frm = frm.f_back if frm is None: return None if finddiff: currmod = inspect.getmodule(frm) if finddiff is True: diffmods = [currmod] else: diffmods = [] for fd in finddiff: if inspect.ismodule(fd): diffmods.append(fd) elif isinstance(fd, str): diffmods.append(importlib.import_module(fd)) elif fd is True: diffmods.append(currmod) else: raise ValueError('invalid entry in finddiff') while frm: frmb = frm.f_back modb = inspect.getmodule(frmb) if modb not in diffmods: return modb frm = frmb else: return inspect.getmodule(frm) def find_mod_objs(modname, onlylocals=False): """ Returns all the public attributes of a module referenced by name. .. note:: The returned list *not* include subpackages or modules of ``modname``, nor does it include private attributes (those that begin with '_' or are not in `__all__`). Parameters ---------- modname : str The name of the module to search. onlylocals : bool or list of str If `True`, only attributes that are either members of ``modname`` OR one of its modules or subpackages will be included. If it is a list of strings, those specify the possible packages that will be considered "local". Returns ------- localnames : list of str A list of the names of the attributes as they are named in the module ``modname`` . fqnames : list of str A list of the full qualified names of the attributes (e.g., ``astropy.utils.introspection.find_mod_objs``). For attributes that are simple variables, this is based on the local name, but for functions or classes it can be different if they are actually defined elsewhere and just referenced in ``modname``. objs : list of objects A list of the actual attributes themselves (in the same order as the other arguments) """ mod = resolve_name(modname) if hasattr(mod, '__all__'): pkgitems = [(k, mod.__dict__[k]) for k in mod.__all__] else: pkgitems = [(k, mod.__dict__[k]) for k in dir(mod) if k[0] != '_'] # filter out modules and pull the names and objs out ismodule = inspect.ismodule localnames = [k for k, v in pkgitems if not ismodule(v)] objs = [v for k, v in pkgitems if not ismodule(v)] # fully qualified names can be determined from the object's module fqnames = [] for obj, lnm in zip(objs, localnames): if hasattr(obj, '__module__') and hasattr(obj, '__name__'): fqnames.append(obj.__module__ + '.' + obj.__name__) else: fqnames.append(modname + '.' + lnm) if onlylocals: if onlylocals is True: onlylocals = [modname] valids = [any(fqn.startswith(nm) for nm in onlylocals) for fqn in fqnames] localnames = [e for i, e in enumerate(localnames) if valids[i]] fqnames = [e for i, e in enumerate(fqnames) if valids[i]] objs = [e for i, e in enumerate(objs) if valids[i]] return localnames, fqnames, objs # Note: I would have preferred call this is_instancemethod, but this naming is # for consistency with other functions in the `inspect` module def isinstancemethod(cls, obj): """ Returns `True` if the given object is an instance method of the class it is defined on (as opposed to a `staticmethod` or a `classmethod`). This requires both the class the object is a member of as well as the object itself in order to make this determination. Parameters ---------- cls : `type` The class on which this method was defined. obj : `object` A member of the provided class (the membership is not checked directly, but this function will always return `False` if the given object is not a member of the given class). Examples -------- >>> class MetaClass(type): ... def a_classmethod(cls): pass ... >>> class MyClass(metaclass=MetaClass): ... def an_instancemethod(self): pass ... ... @classmethod ... def another_classmethod(cls): pass ... ... @staticmethod ... def a_staticmethod(): pass ... >>> isinstancemethod(MyClass, MyClass.a_classmethod) False >>> isinstancemethod(MyClass, MyClass.another_classmethod) False >>> isinstancemethod(MyClass, MyClass.a_staticmethod) False >>> isinstancemethod(MyClass, MyClass.an_instancemethod) True """ return _isinstancemethod(cls, obj) def _isinstancemethod(cls, obj): if not isinstance(obj, types.FunctionType): return False # Unfortunately it seems the easiest way to get to the original # staticmethod object is to look in the class's __dict__, though we # also need to look up the MRO in case the method is not in the given # class's dict name = obj.__name__ for basecls in cls.mro(): # This includes cls if name in basecls.__dict__: return not isinstance(basecls.__dict__[name], staticmethod) # This shouldn't happen, though this is the most sensible response if # it does. raise AttributeError(name)
f0a2513e77469f1f85421a4b4074485cab695e9ecb1e043354823674c7b7cab8
# Licensed under a 3-clause BSD style license - see LICENSE.rst """General purpose timer related functions.""" # STDLIB import time import warnings from collections import Iterable, OrderedDict from functools import partial, wraps # THIRD-PARTY import numpy as np # LOCAL from .. import units as u from .. import log from .. import modeling from .exceptions import AstropyUserWarning __all__ = ['timefunc', 'RunTimePredictor'] __doctest_skip__ = ['timefunc'] def timefunc(num_tries=1, verbose=True): """Decorator to time a function or method. Parameters ---------- num_tries : int, optional Number of calls to make. Timer will take the average run time. verbose : bool, optional Extra log information. Returns ------- tt : float Average run time in seconds. result Output(s) from the function. Examples -------- To add timer to time `numpy.log` for 100 times with verbose output:: import numpy as np from astropy.utils.timer import timefunc @timefunc(100) def timed_log(x): return np.log(x) To run the decorated function above: >>> t, y = timed_log(100) INFO: timed_log took 9.29832458496e-06 s on AVERAGE for 100 call(s). [...] >>> t 9.298324584960938e-06 >>> y 4.6051701859880918 """ def real_decorator(function): @wraps(function) def wrapper(*args, **kwargs): ts = time.time() for i in range(num_tries): result = function(*args, **kwargs) te = time.time() tt = (te - ts) / num_tries if verbose: # pragma: no cover log.info('{0} took {1} s on AVERAGE for {2} call(s).'.format( function.__name__, tt, num_tries)) return tt, result return wrapper return real_decorator class RunTimePredictor: """Class to predict run time. .. note:: Only predict for single varying numeric input parameter. Parameters ---------- func : function Function to time. args : tuple Fixed positional argument(s) for the function. kwargs : dict Fixed keyword argument(s) for the function. Examples -------- >>> from astropy.utils.timer import RunTimePredictor Set up a predictor for :math:`10^{x}`: >>> p = RunTimePredictor(pow, 10) Give it baseline data to use for prediction and get the function output values: >>> p.time_func(range(10, 1000, 200)) >>> for input, result in sorted(p.results.items()): ... print("pow(10, {0})\\n{1}".format(input, result)) pow(10, 10) 10000000000 pow(10, 210) 10000000000... pow(10, 410) 10000000000... pow(10, 610) 10000000000... pow(10, 810) 10000000000... Fit a straight line assuming :math:`\\text{arg}^{1}` relationship (coefficients are returned): >>> p.do_fit() # doctest: +SKIP array([1.16777420e-05, 1.00135803e-08]) Predict run time for :math:`10^{5000}`: >>> p.predict_time(5000) # doctest: +SKIP 6.174564361572262e-05 Plot the prediction: >>> p.plot(xlabeltext='Power of 10') # doctest: +SKIP .. image:: /_static/timer_prediction_pow10.png :width: 450px :alt: Example plot from `astropy.utils.timer.RunTimePredictor` When the changing argument is not the last, e.g., :math:`x^{2}`, something like this might work: >>> p = RunTimePredictor(lambda x: pow(x, 2)) >>> p.time_func([2, 3, 5]) >>> sorted(p.results.items()) [(2, 4), (3, 9), (5, 25)] """ def __init__(self, func, *args, **kwargs): self._funcname = func.__name__ self._pfunc = partial(func, *args, **kwargs) self._cache_good = OrderedDict() self._cache_bad = [] self._cache_est = OrderedDict() self._cache_out = OrderedDict() self._fit_func = None self._power = None @property def results(self): """Function outputs from `time_func`. A dictionary mapping input arguments (fixed arguments are not included) to their respective output values. """ return self._cache_out @timefunc(num_tries=1, verbose=False) def _timed_pfunc(self, arg): """Run partial func once for single arg and time it.""" return self._pfunc(arg) def _cache_time(self, arg): """Cache timing results without repetition.""" if arg not in self._cache_good and arg not in self._cache_bad: try: result = self._timed_pfunc(arg) except Exception as e: warnings.warn(str(e), AstropyUserWarning) self._cache_bad.append(arg) else: self._cache_good[arg] = result[0] # Run time self._cache_out[arg] = result[1] # Function output def time_func(self, arglist): """Time the partial function for a list of single args and store run time in a cache. This forms a baseline for the prediction. This also stores function outputs in `results`. Parameters ---------- arglist : list of numbers List of input arguments to time. """ if not isinstance(arglist, Iterable): arglist = [arglist] # Preserve arglist order for arg in arglist: self._cache_time(arg) # FUTURE: Implement N^x * O(log(N)) fancy fitting. def do_fit(self, model=None, fitter=None, power=1, min_datapoints=3): """Fit a function to the lists of arguments and their respective run time in the cache. By default, this does a linear least-square fitting to a straight line on run time w.r.t. argument values raised to the given power, and returns the optimal intercept and slope. Parameters ---------- model : `astropy.modeling.Model` Model for the expected trend of run time (Y-axis) w.r.t. :math:`\\text{arg}^{\\text{power}}` (X-axis). If `None`, will use `~astropy.modeling.polynomial.Polynomial1D` with ``degree=1``. fitter : `astropy.modeling.fitting.Fitter` Fitter for the given model to extract optimal coefficient values. If `None`, will use `~astropy.modeling.fitting.LinearLSQFitter`. power : int, optional Power of values to fit. min_datapoints : int, optional Minimum number of data points required for fitting. They can be built up with `time_func`. Returns ------- a : array-like Fitted `~astropy.modeling.FittableModel` parameters. Raises ------ ValueError Insufficient data points for fitting. ModelsError Invalid model or fitter. """ # Reset related attributes self._power = power self._cache_est = OrderedDict() x_arr = np.array(list(self._cache_good.keys())) if x_arr.size < min_datapoints: raise ValueError('requires {0} points but has {1}'.format( min_datapoints, x_arr.size)) if model is None: model = modeling.models.Polynomial1D(1) elif not isinstance(model, modeling.core.Model): raise modeling.fitting.ModelsError( '{0} is not a model.'.format(model)) if fitter is None: fitter = modeling.fitting.LinearLSQFitter() elif not isinstance(fitter, modeling.fitting.Fitter): raise modeling.fitting.ModelsError( '{0} is not a fitter.'.format(fitter)) self._fit_func = fitter( model, x_arr**power, list(self._cache_good.values())) return self._fit_func.parameters def predict_time(self, arg): """Predict run time for given argument. If prediction is already cached, cached value is returned. Parameters ---------- arg : number Input argument to predict run time for. Returns ------- t_est : float Estimated run time for given argument. Raises ------ RuntimeError No fitted data for prediction. """ if arg in self._cache_est: t_est = self._cache_est[arg] else: if self._fit_func is None: raise RuntimeError('no fitted data for prediction') t_est = self._fit_func(arg**self._power) self._cache_est[arg] = t_est return t_est def plot(self, xscale='linear', yscale='linear', xlabeltext='args', save_as=''): # pragma: no cover """Plot prediction. .. note:: Uses `matplotlib <http://matplotlib.org/>`_. Parameters ---------- xscale, yscale : {'linear', 'log', 'symlog'} Scaling for `matplotlib.axes.Axes`. xlabeltext : str, optional Text for X-label. save_as : str, optional Save plot as given filename. Raises ------ RuntimeError Insufficient data for plotting. """ import matplotlib.pyplot as plt # Actual data x_arr = sorted(self._cache_good) y_arr = np.array([self._cache_good[x] for x in x_arr]) if len(x_arr) <= 1: raise RuntimeError('insufficient data for plotting') # Auto-ranging qmean = y_arr.mean() * u.second for cur_u in (u.minute, u.second, u.millisecond, u.microsecond, u.nanosecond): val = qmean.to_value(cur_u) if 1000 > val >= 1: break y_arr = (y_arr * u.second).to_value(cur_u) fig, ax = plt.subplots() ax.plot(x_arr, y_arr, 'kx-', label='Actual') # Fitted data if self._fit_func is not None: x_est = list(self._cache_est.keys()) y_est = (np.array(list(self._cache_est.values())) * u.second).to_value(cur_u) ax.scatter(x_est, y_est, marker='o', c='r', label='Predicted') x_fit = np.array(sorted(x_arr + x_est)) y_fit = (self._fit_func(x_fit**self._power) * u.second).to_value(cur_u) ax.plot(x_fit, y_fit, 'b--', label='Fit') ax.set_xscale(xscale) ax.set_yscale(yscale) ax.set_xlabel(xlabeltext) ax.set_ylabel('Run time ({})'.format(cur_u.to_string())) ax.set_title(self._funcname) ax.legend(loc='best', numpoints=1) plt.draw() if save_as: plt.savefig(save_as)
3e42210fef752e6c90b95d2593d68bc60cee14ceafff115073fc3afa4ce738d4
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains helper functions and classes for handling metadata. """ from ..utils import wraps import warnings import collections from collections import OrderedDict from copy import deepcopy import numpy as np from ..utils.exceptions import AstropyWarning from ..utils.misc import dtype_bytes_or_chars __all__ = ['MergeConflictError', 'MergeConflictWarning', 'MERGE_STRATEGIES', 'common_dtype', 'MergePlus', 'MergeNpConcatenate', 'MergeStrategy', 'MergeStrategyMeta', 'enable_merge_strategies', 'merge', 'MetaData'] class MergeConflictError(TypeError): pass class MergeConflictWarning(AstropyWarning): pass MERGE_STRATEGIES = [] def common_dtype(arrs): """ Use numpy to find the common dtype for a list of ndarrays. Only allow arrays within the following fundamental numpy data types: ``np.bool_``, ``np.object_``, ``np.number``, ``np.character``, ``np.void`` Parameters ---------- arrs : list of ndarray objects Arrays for which to find the common dtype Returns ------- dtype_str : str String representation of dytpe (dtype ``str`` attribute) """ def dtype(arr): return getattr(arr, 'dtype', np.dtype('O')) np_types = (np.bool_, np.object_, np.number, np.character, np.void) uniq_types = set(tuple(issubclass(dtype(arr).type, np_type) for np_type in np_types) for arr in arrs) if len(uniq_types) > 1: # Embed into the exception the actual list of incompatible types. incompat_types = [dtype(arr).name for arr in arrs] tme = MergeConflictError('Arrays have incompatible types {0}' .format(incompat_types)) tme._incompat_types = incompat_types raise tme arrs = [np.empty(1, dtype=dtype(arr)) for arr in arrs] # For string-type arrays need to explicitly fill in non-zero # values or the final arr_common = .. step is unpredictable. for i, arr in enumerate(arrs): if arr.dtype.kind in ('S', 'U'): arrs[i] = [(u'0' if arr.dtype.kind == 'U' else b'0') * dtype_bytes_or_chars(arr.dtype)] arr_common = np.array([arr[0] for arr in arrs]) return arr_common.dtype.str class MergeStrategyMeta(type): """ Metaclass that registers MergeStrategy subclasses into the MERGE_STRATEGIES registry. """ def __new__(mcls, name, bases, members): cls = super().__new__(mcls, name, bases, members) # Wrap ``merge`` classmethod to catch any exception and re-raise as # MergeConflictError. if 'merge' in members and isinstance(members['merge'], classmethod): orig_merge = members['merge'].__func__ @wraps(orig_merge) def merge(cls, left, right): try: return orig_merge(cls, left, right) except Exception as err: raise MergeConflictError(err) cls.merge = classmethod(merge) # Register merging class (except for base MergeStrategy class) if 'types' in members: types = members['types'] if isinstance(types, tuple): types = [types] for left, right in reversed(types): MERGE_STRATEGIES.insert(0, (left, right, cls)) return cls class MergeStrategy(metaclass=MergeStrategyMeta): """ Base class for defining a strategy for merging metadata from two sources, left and right, into a single output. The primary functionality for the class is the ``merge(cls, left, right)`` class method. This takes ``left`` and ``right`` side arguments and returns a single merged output. The first class attribute is ``types``. This is defined as a list of (left_types, right_types) tuples that indicate for which input types the merge strategy applies. In determining whether to apply this merge strategy to a pair of (left, right) objects, a test is done: ``isinstance(left, left_types) and isinstance(right, right_types)``. For example:: types = [(np.ndarray, np.ndarray), # Two ndarrays (np.ndarray, (list, tuple)), # ndarray and (list or tuple) ((list, tuple), np.ndarray)] # (list or tuple) and ndarray As a convenience, ``types`` can be defined as a single two-tuple instead of a list of two-tuples, e.g. ``types = (np.ndarray, np.ndarray)``. The other class attribute is ``enabled``, which defaults to ``False`` in the base class. By defining a subclass of ``MergeStrategy`` the new merge strategy is automatically registered to be available for use in merging. However, by default the new merge strategy is *not enabled*. This prevents inadvertently changing the behavior of unrelated code that is performing metadata merge operations. In most cases (particularly in library code that others might use) it is recommended to leave custom strategies disabled and use the `~astropy.utils.metadata.enable_merge_strategies` context manager to locally enable the desired strategies. However, if one is confident that the new strategy will not produce unexpected behavior, then one can globally enable it by setting the ``enabled`` class attribute to ``True``. Examples -------- Here we define a custom merge strategy that takes an int or float on the left and right sides and returns a list with the two values. >>> from astropy.utils.metadata import MergeStrategy >>> class MergeNumbersAsList(MergeStrategy): ... types = ((int, float), (int, float)) # (left_types, right_types) ... ... @classmethod ... def merge(cls, left, right): ... return [left, right] """ # Set ``enabled = True`` to globally enable applying this merge strategy. # This is not generally recommended. enabled = False # types = [(left_types, right_types), ...] class MergePlus(MergeStrategy): """ Merge ``left`` and ``right`` objects using the plus operator. This merge strategy is globally enabled by default. """ types = [(list, list), (tuple, tuple)] enabled = True @classmethod def merge(cls, left, right): return left + right class MergeNpConcatenate(MergeStrategy): """ Merge ``left`` and ``right`` objects using np.concatenate. This merge strategy is globally enabled by default. This will upcast a list or tuple to np.ndarray and the output is always ndarray. """ types = [(np.ndarray, np.ndarray), (np.ndarray, (list, tuple)), ((list, tuple), np.ndarray)] enabled = True @classmethod def merge(cls, left, right): left, right = np.asanyarray(left), np.asanyarray(right) common_dtype([left, right]) # Ensure left and right have compatible dtype return np.concatenate([left, right]) def _both_isinstance(left, right, cls): return isinstance(left, cls) and isinstance(right, cls) def _not_equal(left, right): try: return bool(left != right) except Exception: return True class _EnableMergeStrategies: def __init__(self, *merge_strategies): self.merge_strategies = merge_strategies self.orig_enabled = {} for left_type, right_type, merge_strategy in MERGE_STRATEGIES: if issubclass(merge_strategy, merge_strategies): self.orig_enabled[merge_strategy] = merge_strategy.enabled merge_strategy.enabled = True def __enter__(self): pass def __exit__(self, type, value, tb): for merge_strategy, enabled in self.orig_enabled.items(): merge_strategy.enabled = enabled def enable_merge_strategies(*merge_strategies): """ Context manager to temporarily enable one or more custom metadata merge strategies. Examples -------- Here we define a custom merge strategy that takes an int or float on the left and right sides and returns a list with the two values. >>> from astropy.utils.metadata import MergeStrategy >>> class MergeNumbersAsList(MergeStrategy): ... types = ((int, float), # left side types ... (int, float)) # right side types ... @classmethod ... def merge(cls, left, right): ... return [left, right] By defining this class the merge strategy is automatically registered to be available for use in merging. However, by default new merge strategies are *not enabled*. This prevents inadvertently changing the behavior of unrelated code that is performing metadata merge operations. In order to use the new merge strategy, use this context manager as in the following example:: >>> from astropy.table import Table, vstack >>> from astropy.utils.metadata import enable_merge_strategies >>> t1 = Table([[1]], names=['a']) >>> t2 = Table([[2]], names=['a']) >>> t1.meta = {'m': 1} >>> t2.meta = {'m': 2} >>> with enable_merge_strategies(MergeNumbersAsList): ... t12 = vstack([t1, t2]) >>> t12.meta['m'] [1, 2] One can supply further merge strategies as additional arguments to the context manager. As a convenience, the enabling operation is actually done by checking whether the registered strategies are subclasses of the context manager arguments. This means one can define a related set of merge strategies and then enable them all at once by enabling the base class. As a trivial example, *all* registered merge strategies can be enabled with:: >>> with enable_merge_strategies(MergeStrategy): ... t12 = vstack([t1, t2]) Parameters ---------- merge_strategies : one or more `~astropy.utils.metadata.MergeStrategy` args Merge strategies that will be enabled. """ return _EnableMergeStrategies(*merge_strategies) def _warn_str_func(key, left, right): out = ('Cannot merge meta key {0!r} types {1!r}' ' and {2!r}, choosing {0}={3!r}' .format(key, type(left), type(right), right)) return out def _error_str_func(key, left, right): out = ('Cannot merge meta key {0!r} ' 'types {1!r} and {2!r}' .format(key, type(left), type(right))) return out def merge(left, right, merge_func=None, metadata_conflicts='warn', warn_str_func=_warn_str_func, error_str_func=_error_str_func): """ Merge the ``left`` and ``right`` metadata objects. This is a simplistic and limited implementation at this point. """ if not _both_isinstance(left, right, dict): raise MergeConflictError('Can only merge two dict-based objects') out = deepcopy(left) for key, val in right.items(): # If no conflict then insert val into out dict and continue if key not in out: out[key] = deepcopy(val) continue # There is a conflict that must be resolved if _both_isinstance(left[key], right[key], dict): out[key] = merge(left[key], right[key], merge_func, metadata_conflicts=metadata_conflicts) else: try: if merge_func is None: for left_type, right_type, merge_cls in MERGE_STRATEGIES: if not merge_cls.enabled: continue if (isinstance(left[key], left_type) and isinstance(right[key], right_type)): out[key] = merge_cls.merge(left[key], right[key]) break else: raise MergeConflictError else: out[key] = merge_func(left[key], right[key]) except MergeConflictError: # Pick the metadata item that is not None, or they are both not # None, then if they are equal, there is no conflict, and if # they are different, there is a conflict and we pick the one # on the right (or raise an error). if left[key] is None: # This may not seem necessary since out[key] gets set to # right[key], but not all objects support != which is # needed for one of the if clauses. out[key] = right[key] elif right[key] is None: out[key] = left[key] elif _not_equal(left[key], right[key]): if metadata_conflicts == 'warn': warnings.warn(warn_str_func(key, left[key], right[key]), MergeConflictWarning) elif metadata_conflicts == 'error': raise MergeConflictError(error_str_func(key, left[key], right[key])) elif metadata_conflicts != 'silent': raise ValueError('metadata_conflicts argument must be one ' 'of "silent", "warn", or "error"') out[key] = right[key] else: out[key] = right[key] return out class MetaData: """ A descriptor for classes that have a ``meta`` property. This can be set to any valid `~collections.Mapping`. Parameters ---------- doc : `str`, optional Documentation for the attribute of the class. Default is ``""``. .. versionadded:: 1.2 copy : `bool`, optional If ``True`` the the value is deepcopied before setting, otherwise it is saved as reference. Default is ``True``. .. versionadded:: 1.2 """ def __init__(self, doc="", copy=True): self.__doc__ = doc self.copy = copy def __get__(self, instance, owner): if instance is None: return self if not hasattr(instance, '_meta'): instance._meta = OrderedDict() return instance._meta def __set__(self, instance, value): if value is None: instance._meta = OrderedDict() else: if isinstance(value, collections.Mapping): if self.copy: instance._meta = deepcopy(value) else: instance._meta = value else: raise TypeError("meta attribute must be dict-like")
29f20420bd6ec82d1c540d728960eafde8f6f93b804c1dba358a234916ba7ec2
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This subpackage contains developer-oriented utilities used by Astropy. Public functions and classes in this subpackage are safe to be used by other packages, but this subpackage is for utilities that are primarily of use for developers or to implement python hacks. This subpackage also includes the `astropy.utils.compat` package, which houses utilities that provide compatibility and bugfixes across all versions of Python that Astropy supports. """ from .codegen import * from .decorators import * from .introspection import * from .misc import *
04903eb06db93262f78a0a43174eba919ef8d532cc5bbbc4597c47546d1524d0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains errors/exceptions and warnings of general use for astropy. Exceptions that are specific to a given subpackage should *not* be here, but rather in the particular subpackage. """ class AstropyWarning(Warning): """ The base warning class from which all Astropy warnings should inherit. Any warning inheriting from this class is handled by the Astropy logger. """ class AstropyUserWarning(UserWarning, AstropyWarning): """ The primary warning class for Astropy. Use this if you do not need a specific sub-class. """ class AstropyDeprecationWarning(AstropyWarning): """ A warning class to indicate a deprecated feature. """ class AstropyPendingDeprecationWarning(PendingDeprecationWarning, AstropyWarning): """ A warning class to indicate a soon-to-be deprecated feature. """ class AstropyBackwardsIncompatibleChangeWarning(AstropyWarning): """ A warning class indicating a change in astropy that is incompatible with previous versions. The suggested procedure is to issue this warning for the version in which the change occurs, and remove it for all following versions. """ class _NoValue: """Special keyword value. This class may be used as the default value assigned to a deprecated keyword in order to check if it has been given a user defined value. """ def __repr__(self): return 'astropy.utils.exceptions.NoValue' NoValue = _NoValue()
5a7fce6fd927d827ce02f7cd8453b40bd564940c7c92025811a573eb798ada44
# Licensed under a 3-clause BSD style license - see LICENSE.rst from distutils.core import Extension from os.path import dirname, join, relpath ASTROPY_UTILS_ROOT = dirname(__file__) def get_extensions(): return [ Extension('astropy.utils._compiler', [relpath(join(ASTROPY_UTILS_ROOT, 'src', 'compiler.c'))]) ] def get_package_data(): # Installs the testing data files return { 'astropy.utils.tests': [ 'data/test_package/*.py', 'data/test_package/data/*.txt', 'data/*.dat', 'data/*.txt', 'data/*.gz', 'data/*.bz2', 'data/*.xz', 'data/.hidden_file.txt', 'data/*.cfg'], 'astropy.utils.iers': [ 'data/ReadMe.eopc04_IAU2000', 'data/ReadMe.finals2000A', 'data/eopc04_IAU2000.62-now', 'tests/finals2000A-2016-04-30-test', 'tests/finals2000A-2016-02-30-test', 'tests/iers_a_excerpt'] }
659133687499762bbd6380dd38c0603518b927c1959a00cb9bab05e7e2d4d538
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """This module contains functions and methods that relate to the DataInfo class which provides a container for informational attributes as well as summary info methods. A DataInfo object is attached to the Quantity, SkyCoord, and Time classes in astropy. Here it allows those classes to be used in Tables and uniformly carry table column attributes such as name, format, dtype, meta, and description. """ # Note: these functions and classes are tested extensively in astropy table # tests via their use in providing mixin column info, and in # astropy/tests/test_info for providing table and column info summary data. import os import re import sys import weakref import warnings from io import StringIO from copy import deepcopy from functools import partial from collections import OrderedDict from contextlib import contextmanager import numpy as np from . import metadata __all__ = ['data_info_factory', 'dtype_info_name', 'BaseColumnInfo', 'DataInfo', 'MixinInfo', 'ParentDtypeInfo'] # Tuple of filterwarnings kwargs to ignore when calling info IGNORE_WARNINGS = (dict(category=RuntimeWarning, message='All-NaN|' 'Mean of empty slice|Degrees of freedom <= 0'),) STRING_TYPE_NAMES = {(False, 'S'): 'str', # not PY3 (False, 'U'): 'unicode', (True, 'S'): 'bytes', # PY3 (True, 'U'): 'str'} @contextmanager def serialize_context_as(context): """Set context for serialization. This will allow downstream code to understand the context in which a column is being serialized. Objects like Time or SkyCoord will have different default serialization representations depending on context. Parameters ---------- context : str Context name, e.g. 'fits', 'hdf5', 'ecsv', 'yaml' """ old_context = BaseColumnInfo._serialize_context BaseColumnInfo._serialize_context = context yield BaseColumnInfo._serialize_context = old_context def dtype_info_name(dtype): """Return a human-oriented string name of the ``dtype`` arg. This can be use by astropy methods that present type information about a data object. The output is mostly equivalent to ``dtype.name`` which takes the form <type_name>[B] where <type_name> is like ``int`` or ``bool`` and [B] is an optional number of bits which gets included only for numeric types. For bytes, string and unicode types, the output is shown below, where <N> is the number of characters. This representation corresponds to the Python type that matches the dtype:: Numpy S<N> U<N> Python bytes<N> str<N> Parameters ---------- dtype : str, np.dtype, type Input dtype as an object that can be converted via np.dtype() Returns ------- dtype_info_name : str String name of ``dtype`` """ dtype = np.dtype(dtype) if dtype.kind in ('S', 'U'): length = re.search(r'(\d+)', dtype.str).group(1) type_name = STRING_TYPE_NAMES[(True, dtype.kind)] out = type_name + length else: out = dtype.name return out def data_info_factory(names, funcs): """ Factory to create a function that can be used as an ``option`` for outputting data object summary information. Examples -------- >>> from astropy.utils.data_info import data_info_factory >>> from astropy.table import Column >>> c = Column([4., 3., 2., 1.]) >>> mystats = data_info_factory(names=['min', 'median', 'max'], ... funcs=[np.min, np.median, np.max]) >>> c.info(option=mystats) min = 1.0 median = 2.5 max = 4.0 n_bad = 0 length = 4 Parameters ---------- names : list List of information attribute names funcs : list List of functions that compute the corresponding information attribute Returns ------- func : function Function that can be used as a data info option """ def func(dat): outs = [] for name, func in zip(names, funcs): try: if isinstance(func, str): out = getattr(dat, func)() else: out = func(dat) except Exception: outs.append('--') else: outs.append(str(out)) return OrderedDict(zip(names, outs)) return func def _get_obj_attrs_map(obj, attrs): """ Get the values for object ``attrs`` and return as a dict. This ignores any attributes that are None and in Py2 converts any unicode attribute names or values to str. In the context of serializing the supported core astropy classes this conversion will succeed and results in more succinct and less python-specific YAML. """ out = {} for attr in attrs: val = getattr(obj, attr, None) if val is not None: out[attr] = val return out def _get_data_attribute(dat, attr=None): """ Get a data object attribute for the ``attributes`` info summary method """ if attr == 'class': val = type(dat).__name__ elif attr == 'dtype': val = dtype_info_name(dat.info.dtype) elif attr == 'shape': datshape = dat.shape[1:] val = datshape if datshape else '' else: val = getattr(dat.info, attr) if val is None: val = '' return str(val) class DataInfo: """ Descriptor that data classes use to add an ``info`` attribute for storing data attributes in a uniform and portable way. Note that it *must* be called ``info`` so that the DataInfo() object can be stored in the ``instance`` using the ``info`` key. Because owner_cls.x is a descriptor, Python doesn't use __dict__['x'] normally, and the descriptor can safely store stuff there. Thanks to http://nbviewer.ipython.org/urls/ gist.github.com/ChrisBeaumont/5758381/raw/descriptor_writeup.ipynb for this trick that works for non-hashable classes. Parameters ---------- bound : bool If True this is a descriptor attribute in a class definition, else it is a DataInfo() object that is bound to a data object instance. Default is False. """ _stats = ['mean', 'std', 'min', 'max'] attrs_from_parent = set() attr_names = set(['name', 'unit', 'dtype', 'format', 'description', 'meta']) _attrs_no_copy = set() _info_summary_attrs = ('dtype', 'shape', 'unit', 'format', 'description', 'class') _represent_as_dict_attrs = () _parent = None def __init__(self, bound=False): # If bound to a data object instance then create the dict of attributes # which stores the info attribute values. if bound: self._attrs = dict((attr, None) for attr in self.attr_names) def __get__(self, instance, owner_cls): if instance is None: # This is an unbound descriptor on the class info = self info._parent_cls = owner_cls else: info = instance.__dict__.get('info') if info is None: info = instance.__dict__['info'] = self.__class__(bound=True) info._parent = instance return info def __set__(self, instance, value): if instance is None: # This is an unbound descriptor on the class raise ValueError('cannot set unbound descriptor') if isinstance(value, DataInfo): info = instance.__dict__['info'] = self.__class__(bound=True) for attr in info.attr_names - info.attrs_from_parent - info._attrs_no_copy: info._attrs[attr] = deepcopy(getattr(value, attr)) else: raise TypeError('info must be set with a DataInfo instance') def __getstate__(self): return self._attrs def __setstate__(self, state): self._attrs = state def __getattr__(self, attr): if attr.startswith('_'): return super().__getattribute__(attr) if attr in self.attrs_from_parent: return getattr(self._parent, attr) try: value = self._attrs[attr] except KeyError: super().__getattribute__(attr) # Generate AttributeError # Weak ref for parent table if attr == 'parent_table' and callable(value): value = value() # Mixins have a default dtype of Object if nothing else was set if attr == 'dtype' and value is None: value = np.dtype('O') return value def __setattr__(self, attr, value): propobj = getattr(self.__class__, attr, None) # If attribute is taken from parent properties and there is not a # class property (getter/setter) for this attribute then set # attribute directly in parent. if attr in self.attrs_from_parent and not isinstance(propobj, property): setattr(self._parent, attr, value) return # Check if there is a property setter and use it if possible. if isinstance(propobj, property): if propobj.fset is None: raise AttributeError("can't set attribute") propobj.fset(self, value) return # Private attr names get directly set if attr.startswith('_'): super().__setattr__(attr, value) return # Finally this must be an actual data attribute that this class is handling. if attr not in self.attr_names: raise AttributeError("attribute must be one of {0}".format(self.attr_names)) if attr == 'parent_table': value = None if value is None else weakref.ref(value) self._attrs[attr] = value def _represent_as_dict(self): """Get the values for the parent ``attrs`` and return as a dict.""" return _get_obj_attrs_map(self._parent, self._represent_as_dict_attrs) def _construct_from_dict(self, map): return self._parent_cls(**map) info_summary_attributes = staticmethod( data_info_factory(names=_info_summary_attrs, funcs=[partial(_get_data_attribute, attr=attr) for attr in _info_summary_attrs])) # No nan* methods in numpy < 1.8 info_summary_stats = staticmethod( data_info_factory(names=_stats, funcs=[getattr(np, 'nan' + stat) for stat in _stats])) def __call__(self, option='attributes', out=''): """ Write summary information about data object to the ``out`` filehandle. By default this prints to standard output via sys.stdout. The ``option`` argument specifies what type of information to include. This can be a string, a function, or a list of strings or functions. Built-in options are: - ``attributes``: data object attributes like ``dtype`` and ``format`` - ``stats``: basic statistics: min, mean, and max If a function is specified then that function will be called with the data object as its single argument. The function must return an OrderedDict containing the information attributes. If a list is provided then the information attributes will be appended for each of the options, in order. Examples -------- >>> from astropy.table import Column >>> c = Column([1, 2], unit='m', dtype='int32') >>> c.info() dtype = int32 unit = m class = Column n_bad = 0 length = 2 >>> c.info(['attributes', 'stats']) dtype = int32 unit = m class = Column mean = 1.5 std = 0.5 min = 1 max = 2 n_bad = 0 length = 2 Parameters ---------- option : str, function, list of (str or function) Info option, defaults to 'attributes'. out : file-like object, None Output destination, defaults to sys.stdout. If None then the OrderedDict with information attributes is returned Returns ------- info : OrderedDict if out==None else None """ if out == '': out = sys.stdout dat = self._parent info = OrderedDict() name = dat.info.name if name is not None: info['name'] = name options = option if isinstance(option, (list, tuple)) else [option] for option in options: if isinstance(option, str): if hasattr(self, 'info_summary_' + option): option = getattr(self, 'info_summary_' + option) else: raise ValueError('option={0} is not an allowed information type' .format(option)) with warnings.catch_warnings(): for ignore_kwargs in IGNORE_WARNINGS: warnings.filterwarnings('ignore', **ignore_kwargs) info.update(option(dat)) if hasattr(dat, 'mask'): n_bad = np.count_nonzero(dat.mask) else: try: n_bad = np.count_nonzero(np.isinf(dat) | np.isnan(dat)) except Exception: n_bad = 0 info['n_bad'] = n_bad try: info['length'] = len(dat) except TypeError: pass if out is None: return info for key, val in info.items(): if val != '': out.write('{0} = {1}'.format(key, val) + os.linesep) def __repr__(self): if self._parent is None: return super().__repr__() out = StringIO() self.__call__(out=out) return out.getvalue() class BaseColumnInfo(DataInfo): """ Base info class for anything that can be a column in an astropy Table. There are at least two classes that inherit from this: ColumnInfo: for native astropy Column / MaskedColumn objects MixinInfo: for mixin column objects Note that this class is defined here so that mixins can use it without importing the table package. """ attr_names = DataInfo.attr_names.union(['parent_table', 'indices']) _attrs_no_copy = set(['parent_table']) # Context for serialization. This can be set temporarily via # ``serialize_context_as(context)`` context manager to allow downstream # code to understand the context in which a column is being serialized. # Typical values are 'fits', 'hdf5', 'ecsv', 'yaml'. Objects like Time or # SkyCoord will have different default serialization representations # depending on context. _serialize_context = None def __init__(self, bound=False): super().__init__(bound=bound) # If bound to a data object instance then add a _format_funcs dict # for caching functions for print formatting. if bound: self._format_funcs = {} def iter_str_vals(self): """ This is a mixin-safe version of Column.iter_str_vals. """ col = self._parent if self.parent_table is None: from ..table.column import FORMATTER as formatter else: formatter = self.parent_table.formatter _pformat_col_iter = formatter._pformat_col_iter for str_val in _pformat_col_iter(col, -1, False, False, {}): yield str_val def adjust_indices(self, index, value, col_len): ''' Adjust info indices after column modification. Parameters ---------- index : slice, int, list, or ndarray Element(s) of column to modify. This parameter can be a single row number, a list of row numbers, an ndarray of row numbers, a boolean ndarray (a mask), or a column slice. value : int, list, or ndarray New value(s) to insert col_len : int Length of the column ''' if not self.indices: return if isinstance(index, slice): # run through each key in slice t = index.indices(col_len) keys = list(range(*t)) elif isinstance(index, np.ndarray) and index.dtype.kind == 'b': # boolean mask keys = np.where(index)[0] else: # single int keys = [index] value = np.atleast_1d(value) # turn array(x) into array([x]) if value.size == 1: # repeat single value value = list(value) * len(keys) for key, val in zip(keys, value): for col_index in self.indices: col_index.replace(key, self.name, val) def slice_indices(self, col_slice, item, col_len): ''' Given a sliced object, modify its indices to correctly represent the slice. Parameters ---------- col_slice : Column or mixin Sliced object item : slice, list, or ndarray Slice used to create col_slice col_len : int Length of original object ''' from ..table.sorted_array import SortedArray if not getattr(self, '_copy_indices', True): # Necessary because MaskedArray will perform a shallow copy col_slice.info.indices = [] return col_slice elif isinstance(item, slice): col_slice.info.indices = [x[item] for x in self.indices] elif self.indices: if isinstance(item, np.ndarray) and item.dtype.kind == 'b': # boolean mask item = np.where(item)[0] threshold = 0.6 # Empirical testing suggests that recreating a BST/RBT index is # more effective than relabelling when less than ~60% of # the total number of rows are involved, and is in general # more effective for SortedArray. small = len(item) <= 0.6 * col_len col_slice.info.indices = [] for index in self.indices: if small or isinstance(index, SortedArray): new_index = index.get_slice(col_slice, item) else: new_index = deepcopy(index) new_index.replace_rows(item) col_slice.info.indices.append(new_index) return col_slice @staticmethod def merge_cols_attributes(cols, metadata_conflicts, name, attrs): """ Utility method to merge and validate the attributes ``attrs`` for the input table columns ``cols``. Note that ``dtype`` and ``shape`` attributes are handled specially. These should not be passed in ``attrs`` but will always be in the returned dict of merged attributes. Parameters ---------- cols : list List of input Table column objects metadata_conflicts : str ('warn'|'error'|'silent') How to handle metadata conflicts name : str Output column name attrs : list List of attribute names to be merged Returns ------- attrs : dict of merged attributes """ from ..table.np_utils import TableMergeError def warn_str_func(key, left, right): out = ("In merged column '{}' the '{}' attribute does not match " "({} != {}). Using {} for merged output" .format(name, key, left, right, right)) return out def getattrs(col): return {attr: getattr(col.info, attr) for attr in attrs if getattr(col.info, attr, None) is not None} out = getattrs(cols[0]) for col in cols[1:]: out = metadata.merge(out, getattrs(col), metadata_conflicts=metadata_conflicts, warn_str_func=warn_str_func) # Output dtype is the superset of all dtypes in in_cols out['dtype'] = metadata.common_dtype(cols) # Make sure all input shapes are the same uniq_shapes = set(col.shape[1:] for col in cols) if len(uniq_shapes) != 1: raise TableMergeError('columns have different shapes') out['shape'] = uniq_shapes.pop() return out class MixinInfo(BaseColumnInfo): def __setattr__(self, attr, value): # For mixin columns that live within a table, rename the column in the # table when setting the name attribute. This mirrors the same # functionality in the BaseColumn class. if attr == 'name' and self.parent_table is not None: from ..table.np_utils import fix_column_name new_name = fix_column_name(value) # Ensure col name is numpy compatible self.parent_table.columns._rename_column(self.name, new_name) super().__setattr__(attr, value) class ParentDtypeInfo(MixinInfo): """Mixin that gets info.dtype from parent""" attrs_from_parent = set(['dtype']) # dtype and unit taken from parent
19aa58446b2c6841dd4f4f8893aba2ef36a8d954f0e028fc6ddb470697bf6bf2
"""Utilities and extensions for use with `argparse`.""" import os import argparse def directory(arg): """ An argument type (for use with the ``type=`` argument to `argparse.ArgumentParser.add_argument` which determines if the argument is an existing directory (and returns the absolute path). """ if not isinstance(arg, str) and os.path.isdir(arg): raise argparse.ArgumentTypeError( "{0} is not a directory or does not exist (the directory must " "be created first)".format(arg)) return os.path.abspath(arg) def readable_directory(arg): """ An argument type (for use with the ``type=`` argument to `argparse.ArgumentParser.add_argument` which determines if the argument is a directory that exists and is readable (and returns the absolute path). """ arg = directory(arg) if not os.access(arg, os.R_OK): raise argparse.ArgumentTypeError( "{0} exists but is not readable with its current " "permissions".format(arg)) return arg def writeable_directory(arg): """ An argument type (for use with the ``type=`` argument to `argparse.ArgumentParser.add_argument` which determines if the argument is a directory that exists and is writeable (and returns the absolute path). """ arg = directory(arg) if not os.access(arg, os.W_OK): raise argparse.ArgumentTypeError( "{0} exists but is not writeable with its current " "permissions".format(arg)) return arg
9fcdc3b66a27bf11054bb5a90bcda555580b3f2eb78c4243c53df66d371daecc
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains helper functions for accessing, downloading, and caching data files. """ import atexit import contextlib import fnmatch import hashlib import os import io import pathlib import shutil import socket import sys import time import urllib.request import urllib.error import urllib.parse import shelve from tempfile import NamedTemporaryFile, gettempdir from warnings import warn from .. import config as _config from ..utils.exceptions import AstropyWarning from ..utils.introspection import find_current_module, resolve_name __all__ = [ 'Conf', 'conf', 'get_readable_fileobj', 'get_file_contents', 'get_pkg_data_fileobj', 'get_pkg_data_filename', 'get_pkg_data_contents', 'get_pkg_data_fileobjs', 'get_pkg_data_filenames', 'compute_hash', 'clear_download_cache', 'CacheMissingWarning', 'get_free_space_in_dir', 'check_free_space_in_dir', 'download_file', 'download_files_in_parallel', 'is_url_in_cache', 'get_cached_urls'] _dataurls_to_alias = {} class Conf(_config.ConfigNamespace): """ Configuration parameters for `astropy.utils.data`. """ dataurl = _config.ConfigItem( 'http://data.astropy.org/', 'Primary URL for astropy remote data site.') dataurl_mirror = _config.ConfigItem( 'http://www.astropy.org/astropy-data/', 'Mirror URL for astropy remote data site.') remote_timeout = _config.ConfigItem( 10., 'Time to wait for remote data queries (in seconds).', aliases=['astropy.coordinates.name_resolve.name_resolve_timeout']) compute_hash_block_size = _config.ConfigItem( 2 ** 16, # 64K 'Block size for computing MD5 file hashes.') download_block_size = _config.ConfigItem( 2 ** 16, # 64K 'Number of bytes of remote data to download per step.') download_cache_lock_attempts = _config.ConfigItem( 5, 'Number of times to try to get the lock ' + 'while accessing the data cache before giving up.') delete_temporary_downloads_at_exit = _config.ConfigItem( True, 'If True, temporary download files created when the cache is ' 'inaccessible will be deleted at the end of the python session.') conf = Conf() class CacheMissingWarning(AstropyWarning): """ This warning indicates the standard cache directory is not accessible, with the first argument providing the warning message. If args[1] is present, it is a filename indicating the path to a temporary file that was created to store a remote data download in the absence of the cache. """ def _is_url(string): """ Test whether a string is a valid URL Parameters ---------- string : str The string to test """ url = urllib.parse.urlparse(string) # we can't just check that url.scheme is not an empty string, because # file paths in windows would return a non-empty scheme (e.g. e:\\ # returns 'e'). return url.scheme.lower() in ['http', 'https', 'ftp', 'sftp', 'ssh', 'file'] def _is_inside(path, parent_path): # We have to try realpath too to avoid issues with symlinks, but we leave # abspath because some systems like debian have the absolute path (with no # symlinks followed) match, but the real directories in different # locations, so need to try both cases. return os.path.abspath(path).startswith(os.path.abspath(parent_path)) \ or os.path.realpath(path).startswith(os.path.realpath(parent_path)) @contextlib.contextmanager def get_readable_fileobj(name_or_obj, encoding=None, cache=False, show_progress=True, remote_timeout=None): """ Given a filename, pathlib.Path object or a readable file-like object, return a context manager that yields a readable file-like object. This supports passing filenames, URLs, and readable file-like objects, any of which can be compressed in gzip, bzip2 or lzma (xz) if the appropriate compression libraries are provided by the Python installation. Notes ----- This function is a context manager, and should be used for example as:: with get_readable_fileobj('file.dat') as f: contents = f.read() Parameters ---------- name_or_obj : str or file-like object The filename of the file to access (if given as a string), or the file-like object to access. If a file-like object, it must be opened in binary mode. encoding : str, optional When `None` (default), returns a file-like object with a ``read`` method that returns `str` (``unicode``) objects, using `locale.getpreferredencoding` as an encoding. This matches the default behavior of the built-in `open` when no ``mode`` argument is provided. When ``'binary'``, returns a file-like object where its ``read`` method returns `bytes` objects. When another string, it is the name of an encoding, and the file-like object's ``read`` method will return `str` (``unicode``) objects, decoded from binary using the given encoding. cache : bool, optional Whether to cache the contents of remote URLs. show_progress : bool, optional Whether to display a progress bar if the file is downloaded from a remote server. Default is `True`. remote_timeout : float Timeout for remote requests in seconds (default is the configurable `astropy.utils.data.Conf.remote_timeout`, which is 3s by default) Returns ------- file : readable file-like object """ # close_fds is a list of file handles created by this function # that need to be closed. We don't want to always just close the # returned file handle, because it may simply be the file handle # passed in. In that case it is not the responsibility of this # function to close it: doing so could result in a "double close" # and an "invalid file descriptor" exception. PATH_TYPES = (str, pathlib.Path) close_fds = [] delete_fds = [] if remote_timeout is None: # use configfile default remote_timeout = conf.remote_timeout # Get a file object to the content if isinstance(name_or_obj, PATH_TYPES): # name_or_obj could be a Path object if pathlib is available name_or_obj = str(name_or_obj) is_url = _is_url(name_or_obj) if is_url: name_or_obj = download_file( name_or_obj, cache=cache, show_progress=show_progress, timeout=remote_timeout) fileobj = io.FileIO(name_or_obj, 'r') if is_url and not cache: delete_fds.append(fileobj) close_fds.append(fileobj) else: fileobj = name_or_obj # Check if the file object supports random access, and if not, # then wrap it in a BytesIO buffer. It would be nicer to use a # BufferedReader to avoid reading loading the whole file first, # but that is not compatible with streams or urllib2.urlopen # objects on Python 2.x. if not hasattr(fileobj, 'seek'): fileobj = io.BytesIO(fileobj.read()) # Now read enough bytes to look at signature signature = fileobj.read(4) fileobj.seek(0) if signature[:3] == b'\x1f\x8b\x08': # gzip import struct try: import gzip fileobj_new = gzip.GzipFile(fileobj=fileobj, mode='rb') fileobj_new.read(1) # need to check that the file is really gzip except (OSError, EOFError, struct.error): # invalid gzip file fileobj.seek(0) fileobj_new.close() else: fileobj_new.seek(0) fileobj = fileobj_new elif signature[:3] == b'BZh': # bzip2 try: import bz2 except ImportError: for fd in close_fds: fd.close() raise ValueError( ".bz2 format files are not supported since the Python " "interpreter does not include the bz2 module") try: # bz2.BZ2File does not support file objects, only filenames, so we # need to write the data to a temporary file with NamedTemporaryFile("wb", delete=False) as tmp: tmp.write(fileobj.read()) tmp.close() fileobj_new = bz2.BZ2File(tmp.name, mode='rb') fileobj_new.read(1) # need to check that the file is really bzip2 except OSError: # invalid bzip2 file fileobj.seek(0) fileobj_new.close() # raise else: fileobj_new.seek(0) close_fds.append(fileobj_new) fileobj = fileobj_new elif signature[:3] == b'\xfd7z': # xz try: import lzma fileobj_new = lzma.LZMAFile(fileobj, mode='rb') fileobj_new.read(1) # need to check that the file is really xz except ImportError: for fd in close_fds: fd.close() raise ValueError( ".xz format files are not supported since the Python " "interpreter does not include the lzma module.") except (OSError, EOFError) as e: # invalid xz file fileobj.seek(0) fileobj_new.close() # should we propagate this to the caller to signal bad content? # raise ValueError(e) else: fileobj_new.seek(0) fileobj = fileobj_new # By this point, we have a file, io.FileIO, gzip.GzipFile, bz2.BZ2File # or lzma.LZMAFile instance opened in binary mode (that is, read # returns bytes). Now we need to, if requested, wrap it in a # io.TextIOWrapper so read will return unicode based on the # encoding parameter. needs_textio_wrapper = encoding != 'binary' if needs_textio_wrapper: # A bz2.BZ2File can not be wrapped by a TextIOWrapper, # so we decompress it to a temporary file and then # return a handle to that. try: import bz2 except ImportError: pass else: if isinstance(fileobj, bz2.BZ2File): tmp = NamedTemporaryFile("wb", delete=False) data = fileobj.read() tmp.write(data) tmp.close() delete_fds.append(tmp) fileobj = io.FileIO(tmp.name, 'r') close_fds.append(fileobj) fileobj = io.BufferedReader(fileobj) fileobj = io.TextIOWrapper(fileobj, encoding=encoding) # Ensure that file is at the start - io.FileIO will for # example not always be at the start: # >>> import io # >>> f = open('test.fits', 'rb') # >>> f.read(4) # 'SIMP' # >>> f.seek(0) # >>> fileobj = io.FileIO(f.fileno()) # >>> fileobj.tell() # 4096L fileobj.seek(0) try: yield fileobj finally: for fd in close_fds: fd.close() for fd in delete_fds: os.remove(fd.name) def get_file_contents(*args, **kwargs): """ Retrieves the contents of a filename or file-like object. See the `get_readable_fileobj` docstring for details on parameters. Returns ------- content The content of the file (as requested by ``encoding``). """ with get_readable_fileobj(*args, **kwargs) as f: return f.read() @contextlib.contextmanager def get_pkg_data_fileobj(data_name, package=None, encoding=None, cache=True): """ Retrieves a data file from the standard locations for the package and provides the file as a file-like object that reads bytes. Parameters ---------- data_name : str Name/location of the desired data file. One of the following: * The name of a data file included in the source distribution. The path is relative to the module calling this function. For example, if calling from ``astropy.pkname``, use ``'data/file.dat'`` to get the file in ``astropy/pkgname/data/file.dat``. Double-dots can be used to go up a level. In the same example, use ``'../data/file.dat'`` to get ``astropy/data/file.dat``. * If a matching local file does not exist, the Astropy data server will be queried for the file. * A hash like that produced by `compute_hash` can be requested, prefixed by 'hash/' e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash will first be searched for locally, and if not found, the Astropy data server will be queried. package : str, optional If specified, look for a file relative to the given package, rather than the default of looking relative to the calling module's package. encoding : str, optional When `None` (default), returns a file-like object with a ``read`` method returns `str` (``unicode``) objects, using `locale.getpreferredencoding` as an encoding. This matches the default behavior of the built-in `open` when no ``mode`` argument is provided. When ``'binary'``, returns a file-like object where its ``read`` method returns `bytes` objects. When another string, it is the name of an encoding, and the file-like object's ``read`` method will return `str` (``unicode``) objects, decoded from binary using the given encoding. cache : bool If True, the file will be downloaded and saved locally or the already-cached local copy will be accessed. If False, the file-like object will directly access the resource (e.g. if a remote URL is accessed, an object like that from `urllib.request.urlopen` is returned). Returns ------- fileobj : file-like An object with the contents of the data file available via ``read`` function. Can be used as part of a ``with`` statement, automatically closing itself after the ``with`` block. Raises ------ urllib2.URLError, urllib.error.URLError If a remote file cannot be found. OSError If problems occur writing or reading a local file. Examples -------- This will retrieve a data file and its contents for the `astropy.wcs` tests:: >>> from astropy.utils.data import get_pkg_data_fileobj >>> with get_pkg_data_fileobj('data/3d_cd.hdr', ... package='astropy.wcs.tests') as fobj: ... fcontents = fobj.read() ... This next example would download a data file from the astropy data server because the ``allsky/allsky_rosat.fits`` file is not present in the source distribution. It will also save the file locally so the next time it is accessed it won't need to be downloaded.:: >>> from astropy.utils.data import get_pkg_data_fileobj >>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits', ... encoding='binary') as fobj: # doctest: +REMOTE_DATA ... fcontents = fobj.read() ... Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done] This does the same thing but does *not* cache it locally:: >>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits', ... encoding='binary', cache=False) as fobj: # doctest: +REMOTE_DATA ... fcontents = fobj.read() ... Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done] See Also -------- get_pkg_data_contents : returns the contents of a file or url as a bytes object get_pkg_data_filename : returns a local name for a file containing the data """ datafn = _find_pkg_data_path(data_name, package=package) if os.path.isdir(datafn): raise OSError("Tried to access a data file that's actually " "a package data directory") elif os.path.isfile(datafn): # local file with get_readable_fileobj(datafn, encoding=encoding) as fileobj: yield fileobj else: # remote file all_urls = (conf.dataurl, conf.dataurl_mirror) for url in all_urls: try: with get_readable_fileobj(url + data_name, encoding=encoding, cache=cache) as fileobj: # We read a byte to trigger any URLErrors fileobj.read(1) fileobj.seek(0) yield fileobj break except urllib.error.URLError: pass else: urls = '\n'.join(' - {0}'.format(url) for url in all_urls) raise urllib.error.URLError("Failed to download {0} from the following " "repositories:\n\n{1}".format(data_name, urls)) def get_pkg_data_filename(data_name, package=None, show_progress=True, remote_timeout=None): """ Retrieves a data file from the standard locations for the package and provides a local filename for the data. This function is similar to `get_pkg_data_fileobj` but returns the file *name* instead of a readable file-like object. This means that this function must always cache remote files locally, unlike `get_pkg_data_fileobj`. Parameters ---------- data_name : str Name/location of the desired data file. One of the following: * The name of a data file included in the source distribution. The path is relative to the module calling this function. For example, if calling from ``astropy.pkname``, use ``'data/file.dat'`` to get the file in ``astropy/pkgname/data/file.dat``. Double-dots can be used to go up a level. In the same example, use ``'../data/file.dat'`` to get ``astropy/data/file.dat``. * If a matching local file does not exist, the Astropy data server will be queried for the file. * A hash like that produced by `compute_hash` can be requested, prefixed by 'hash/' e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash will first be searched for locally, and if not found, the Astropy data server will be queried. package : str, optional If specified, look for a file relative to the given package, rather than the default of looking relative to the calling module's package. show_progress : bool, optional Whether to display a progress bar if the file is downloaded from a remote server. Default is `True`. remote_timeout : float Timeout for the requests in seconds (default is the configurable `astropy.utils.data.Conf.remote_timeout`, which is 3s by default) Raises ------ urllib2.URLError, urllib.error.URLError If a remote file cannot be found. OSError If problems occur writing or reading a local file. Returns ------- filename : str A file path on the local file system corresponding to the data requested in ``data_name``. Examples -------- This will retrieve the contents of the data file for the `astropy.wcs` tests:: >>> from astropy.utils.data import get_pkg_data_filename >>> fn = get_pkg_data_filename('data/3d_cd.hdr', ... package='astropy.wcs.tests') >>> with open(fn) as f: ... fcontents = f.read() ... This retrieves a data file by hash either locally or from the astropy data server:: >>> from astropy.utils.data import get_pkg_data_filename >>> fn = get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28') # doctest: +SKIP >>> with open(fn) as f: ... fcontents = f.read() ... See Also -------- get_pkg_data_contents : returns the contents of a file or url as a bytes object get_pkg_data_fileobj : returns a file-like object with the data """ if remote_timeout is None: # use configfile default remote_timeout = conf.remote_timeout if data_name.startswith('hash/'): # first try looking for a local version if a hash is specified hashfn = _find_hash_fn(data_name[5:]) if hashfn is None: all_urls = (conf.dataurl, conf.dataurl_mirror) for url in all_urls: try: return download_file(url + data_name, cache=True, show_progress=show_progress, timeout=remote_timeout) except urllib.error.URLError: pass urls = '\n'.join(' - {0}'.format(url) for url in all_urls) raise urllib.error.URLError("Failed to download {0} from the following " "repositories:\n\n{1}\n\n".format(data_name, urls)) else: return hashfn else: fs_path = os.path.normpath(data_name) datafn = _find_pkg_data_path(fs_path, package=package) if os.path.isdir(datafn): raise OSError("Tried to access a data file that's actually " "a package data directory") elif os.path.isfile(datafn): # local file return datafn else: # remote file all_urls = (conf.dataurl, conf.dataurl_mirror) for url in all_urls: try: return download_file(url + data_name, cache=True, show_progress=show_progress, timeout=remote_timeout) except urllib.error.URLError: pass urls = '\n'.join(' - {0}'.format(url) for url in all_urls) raise urllib.error.URLError("Failed to download {0} from the following " "repositories:\n\n{1}".format(data_name, urls)) def get_pkg_data_contents(data_name, package=None, encoding=None, cache=True): """ Retrieves a data file from the standard locations and returns its contents as a bytes object. Parameters ---------- data_name : str Name/location of the desired data file. One of the following: * The name of a data file included in the source distribution. The path is relative to the module calling this function. For example, if calling from ``astropy.pkname``, use ``'data/file.dat'`` to get the file in ``astropy/pkgname/data/file.dat``. Double-dots can be used to go up a level. In the same example, use ``'../data/file.dat'`` to get ``astropy/data/file.dat``. * If a matching local file does not exist, the Astropy data server will be queried for the file. * A hash like that produced by `compute_hash` can be requested, prefixed by 'hash/' e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash will first be searched for locally, and if not found, the Astropy data server will be queried. * A URL to some other file. package : str, optional If specified, look for a file relative to the given package, rather than the default of looking relative to the calling module's package. encoding : str, optional When `None` (default), returns a file-like object with a ``read`` method that returns `str` (``unicode``) objects, using `locale.getpreferredencoding` as an encoding. This matches the default behavior of the built-in `open` when no ``mode`` argument is provided. When ``'binary'``, returns a file-like object where its ``read`` method returns `bytes` objects. When another string, it is the name of an encoding, and the file-like object's ``read`` method will return `str` (``unicode``) objects, decoded from binary using the given encoding. cache : bool If True, the file will be downloaded and saved locally or the already-cached local copy will be accessed. If False, the file-like object will directly access the resource (e.g. if a remote URL is accessed, an object like that from `urllib.request.urlopen` is returned). Returns ------- contents : bytes The complete contents of the file as a bytes object. Raises ------ urllib2.URLError, urllib.error.URLError If a remote file cannot be found. OSError If problems occur writing or reading a local file. See Also -------- get_pkg_data_fileobj : returns a file-like object with the data get_pkg_data_filename : returns a local name for a file containing the data """ with get_pkg_data_fileobj(data_name, package=package, encoding=encoding, cache=cache) as fd: contents = fd.read() return contents def get_pkg_data_filenames(datadir, package=None, pattern='*'): """ Returns the path of all of the data files in a given directory that match a given glob pattern. Parameters ---------- datadir : str Name/location of the desired data files. One of the following: * The name of a directory included in the source distribution. The path is relative to the module calling this function. For example, if calling from ``astropy.pkname``, use ``'data'`` to get the files in ``astropy/pkgname/data``. * Remote URLs are not currently supported. package : str, optional If specified, look for a file relative to the given package, rather than the default of looking relative to the calling module's package. pattern : str, optional A UNIX-style filename glob pattern to match files. See the `glob` module in the standard library for more information. By default, matches all files. Returns ------- filenames : iterator of str Paths on the local filesystem in *datadir* matching *pattern*. Examples -------- This will retrieve the contents of the data file for the `astropy.wcs` tests:: >>> from astropy.utils.data import get_pkg_data_filenames >>> for fn in get_pkg_data_filenames('maps', 'astropy.wcs.tests', ... '*.hdr'): ... with open(fn) as f: ... fcontents = f.read() ... """ path = _find_pkg_data_path(datadir, package=package) if os.path.isfile(path): raise OSError( "Tried to access a data directory that's actually " "a package data file") elif os.path.isdir(path): for filename in os.listdir(path): if fnmatch.fnmatch(filename, pattern): yield os.path.join(path, filename) else: raise OSError("Path not found") def get_pkg_data_fileobjs(datadir, package=None, pattern='*', encoding=None): """ Returns readable file objects for all of the data files in a given directory that match a given glob pattern. Parameters ---------- datadir : str Name/location of the desired data files. One of the following: * The name of a directory included in the source distribution. The path is relative to the module calling this function. For example, if calling from ``astropy.pkname``, use ``'data'`` to get the files in ``astropy/pkgname/data`` * Remote URLs are not currently supported package : str, optional If specified, look for a file relative to the given package, rather than the default of looking relative to the calling module's package. pattern : str, optional A UNIX-style filename glob pattern to match files. See the `glob` module in the standard library for more information. By default, matches all files. encoding : str, optional When `None` (default), returns a file-like object with a ``read`` method that returns `str` (``unicode``) objects, using `locale.getpreferredencoding` as an encoding. This matches the default behavior of the built-in `open` when no ``mode`` argument is provided. When ``'binary'``, returns a file-like object where its ``read`` method returns `bytes` objects. When another string, it is the name of an encoding, and the file-like object's ``read`` method will return `str` (``unicode``) objects, decoded from binary using the given encoding. Returns ------- fileobjs : iterator of file objects File objects for each of the files on the local filesystem in *datadir* matching *pattern*. Examples -------- This will retrieve the contents of the data file for the `astropy.wcs` tests:: >>> from astropy.utils.data import get_pkg_data_filenames >>> for fd in get_pkg_data_fileobjs('maps', 'astropy.wcs.tests', ... '*.hdr'): ... fcontents = fd.read() ... """ for fn in get_pkg_data_filenames(datadir, package=package, pattern=pattern): with get_readable_fileobj(fn, encoding=encoding) as fd: yield fd def compute_hash(localfn): """ Computes the MD5 hash for a file. The hash for a data file is used for looking up data files in a unique fashion. This is of particular use for tests; a test may require a particular version of a particular file, in which case it can be accessed via hash to get the appropriate version. Typically, if you wish to write a test that requires a particular data file, you will want to submit that file to the astropy data servers, and use e.g. ``get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28')``, but with the hash for your file in place of the hash in the example. Parameters ---------- localfn : str The path to the file for which the hash should be generated. Returns ------- md5hash : str The hex digest of the MD5 hash for the contents of the ``localfn`` file. """ with open(localfn, 'rb') as f: h = hashlib.md5() block = f.read(conf.compute_hash_block_size) while block: h.update(block) block = f.read(conf.compute_hash_block_size) return h.hexdigest() def _find_pkg_data_path(data_name, package=None): """ Look for data in the source-included data directories and return the path. """ if package is None: module = find_current_module(1, finddiff=['astropy.utils.data', 'contextlib']) if module is None: # not called from inside an astropy package. So just pass name # through return data_name if not hasattr(module, '__package__') or not module.__package__: # The __package__ attribute may be missing or set to None; see # PEP-366, also astropy issue #1256 if '.' in module.__name__: package = module.__name__.rpartition('.')[0] else: package = module.__name__ else: package = module.__package__ else: module = resolve_name(package) rootpkgname = package.partition('.')[0] rootpkg = resolve_name(rootpkgname) module_path = os.path.dirname(module.__file__) path = os.path.join(module_path, data_name) root_dir = os.path.dirname(rootpkg.__file__) if not _is_inside(path, root_dir): raise RuntimeError("attempted to get a local data file outside " "of the {} tree.".format(rootpkgname)) return path def _find_hash_fn(hash): """ Looks for a local file by hash - returns file name if found and a valid file, otherwise returns None. """ try: dldir, urlmapfn = _get_download_cache_locs() except OSError as e: msg = 'Could not access cache directory to search for data file: ' warn(CacheMissingWarning(msg + str(e))) return None hashfn = os.path.join(dldir, hash) if os.path.isfile(hashfn): return hashfn else: return None def get_free_space_in_dir(path): """ Given a path to a directory, returns the amount of free space (in bytes) on that filesystem. Parameters ---------- path : str The path to a directory Returns ------- bytes : int The amount of free space on the partition that the directory is on. """ if sys.platform.startswith('win'): import ctypes free_bytes = ctypes.c_ulonglong(0) retval = ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes)) if retval == 0: raise OSError('Checking free space on {!r} failed ' 'unexpectedly.'.format(path)) return free_bytes.value else: stat = os.statvfs(path) return stat.f_bavail * stat.f_frsize def check_free_space_in_dir(path, size): """ Determines if a given directory has enough space to hold a file of a given size. Raises an OSError if the file would be too large. Parameters ---------- path : str The path to a directory size : int A proposed filesize (in bytes) Raises ------- OSError : There is not enough room on the filesystem """ from ..utils.console import human_file_size space = get_free_space_in_dir(path) if space < size: raise OSError( "Not enough free space in '{0}' " "to download a {1} file".format( path, human_file_size(size))) def download_file(remote_url, cache=False, show_progress=True, timeout=None): """ Accepts a URL, downloads and optionally caches the result returning the filename, with a name determined by the file's MD5 hash. If ``cache=True`` and the file is present in the cache, just returns the filename. Parameters ---------- remote_url : str The URL of the file to download cache : bool, optional Whether to use the cache show_progress : bool, optional Whether to display a progress bar during the download (default is `True`) timeout : float, optional The timeout, in seconds. Otherwise, use `astropy.utils.data.Conf.remote_timeout`. Returns ------- local_path : str Returns the local path that the file was download to. Raises ------ urllib2.URLError, urllib.error.URLError Whenever there's a problem getting the remote file. """ from ..utils.console import ProgressBarOrSpinner if timeout is None: timeout = conf.remote_timeout missing_cache = False if cache: try: dldir, urlmapfn = _get_download_cache_locs() except OSError as e: msg = 'Remote data cache could not be accessed due to ' estr = '' if len(e.args) < 1 else (': ' + str(e)) warn(CacheMissingWarning(msg + e.__class__.__name__ + estr)) cache = False missing_cache = True # indicates that the cache is missing to raise a warning later url_key = remote_url # Check if URL is Astropy data server, which has alias, and cache it. if (url_key.startswith(conf.dataurl) and conf.dataurl not in _dataurls_to_alias): with urllib.request.urlopen(conf.dataurl, timeout=timeout) as remote: _dataurls_to_alias[conf.dataurl] = [conf.dataurl, remote.geturl()] try: if cache: # We don't need to acquire the lock here, since we are only reading with shelve.open(urlmapfn) as url2hash: if url_key in url2hash: return url2hash[url_key] # If there is a cached copy from mirror, use it. else: for cur_url in _dataurls_to_alias.get(conf.dataurl, []): if url_key.startswith(cur_url): url_mirror = url_key.replace(cur_url, conf.dataurl_mirror) if url_mirror in url2hash: return url2hash[url_mirror] with urllib.request.urlopen(remote_url, timeout=timeout) as remote: # keep a hash to rename the local file to the hashed name hash = hashlib.md5() info = remote.info() if 'Content-Length' in info: try: size = int(info['Content-Length']) except ValueError: size = None else: size = None if size is not None: check_free_space_in_dir(gettempdir(), size) if cache: check_free_space_in_dir(dldir, size) if show_progress: progress_stream = sys.stdout else: progress_stream = io.StringIO() dlmsg = "Downloading {0}".format(remote_url) with ProgressBarOrSpinner(size, dlmsg, file=progress_stream) as p: with NamedTemporaryFile(delete=False) as f: try: bytes_read = 0 block = remote.read(conf.download_block_size) while block: f.write(block) hash.update(block) bytes_read += len(block) p.update(bytes_read) block = remote.read(conf.download_block_size) except BaseException: if os.path.exists(f.name): os.remove(f.name) raise if cache: _acquire_download_cache_lock() try: with shelve.open(urlmapfn) as url2hash: # We check now to see if another process has # inadvertently written the file underneath us # already if url_key in url2hash: return url2hash[url_key] local_path = os.path.join(dldir, hash.hexdigest()) shutil.move(f.name, local_path) url2hash[url_key] = local_path finally: _release_download_cache_lock() else: local_path = f.name if missing_cache: msg = ('File downloaded to temporary location due to problem ' 'with cache directory and will not be cached.') warn(CacheMissingWarning(msg, local_path)) if conf.delete_temporary_downloads_at_exit: global _tempfilestodel _tempfilestodel.append(local_path) except urllib.error.URLError as e: if hasattr(e, 'reason') and hasattr(e.reason, 'errno') and e.reason.errno == 8: e.reason.strerror = e.reason.strerror + '. requested URL: ' + remote_url e.reason.args = (e.reason.errno, e.reason.strerror) raise e except socket.timeout as e: # this isn't supposed to happen, but occasionally a socket.timeout gets # through. It's supposed to be caught in `urrlib2` and raised in this # way, but for some reason in mysterious circumstances it doesn't. So # we'll just re-raise it here instead raise urllib.error.URLError(e) return local_path def is_url_in_cache(url_key): """ Check if a download from ``url_key`` is in the cache. Parameters ---------- url_key : string The URL retrieved Returns ------- in_cache : bool `True` if a download from ``url_key`` is in the cache """ # The code below is modified from astropy.utils.data.download_file() try: dldir, urlmapfn = _get_download_cache_locs() except OSError as e: msg = 'Remote data cache could not be accessed due to ' estr = '' if len(e.args) < 1 else (': ' + str(e)) warn(CacheMissingWarning(msg + e.__class__.__name__ + estr)) return False with shelve.open(urlmapfn) as url2hash: if url_key in url2hash: return True return False def _do_download_files_in_parallel(args): return download_file(*args) def download_files_in_parallel(urls, cache=True, show_progress=True, timeout=None): """ Downloads multiple files in parallel from the given URLs. Blocks until all files have downloaded. The result is a list of local file paths corresponding to the given urls. Parameters ---------- urls : list of str The URLs to retrieve. cache : bool, optional Whether to use the cache (default is `True`). .. versionchanged:: 3.0 The default was changed to ``True`` and setting it to ``False`` will print a Warning and set it to ``True`` again, because the function will not work properly without cache. show_progress : bool, optional Whether to display a progress bar during the download (default is `True`) timeout : float, optional Timeout for each individual requests in seconds (default is the configurable `astropy.utils.data.Conf.remote_timeout`). Returns ------- paths : list of str The local file paths corresponding to the downloaded URLs. """ from .console import ProgressBar if timeout is None: timeout = conf.remote_timeout if not cache: # See issue #6662, on windows won't work because the files are removed # again before they can be used. On *NIX systems it will behave as if # cache was set to True because multiprocessing cannot insert the items # in the list of to-be-removed files. warn("Disabling the cache does not work because of multiprocessing, it " "will be set to ``True``. You may need to manually remove the " "cached files afterwards.", AstropyWarning) cache = True if show_progress: progress = sys.stdout else: progress = io.BytesIO() # Combine duplicate URLs combined_urls = list(set(urls)) combined_paths = ProgressBar.map( _do_download_files_in_parallel, [(x, cache, False, timeout) for x in combined_urls], file=progress, multiprocess=True) paths = [] for url in urls: paths.append(combined_paths[combined_urls.index(url)]) return paths # This is used by download_file and _deltemps to determine the files to delete # when the interpreter exits _tempfilestodel = [] @atexit.register def _deltemps(): global _tempfilestodel if _tempfilestodel is not None: while len(_tempfilestodel) > 0: fn = _tempfilestodel.pop() if os.path.isfile(fn): os.remove(fn) def clear_download_cache(hashorurl=None): """ Clears the data file cache by deleting the local file(s). Parameters ---------- hashorurl : str or None If None, the whole cache is cleared. Otherwise, either specifies a hash for the cached file that is supposed to be deleted, or a URL that should be removed from the cache if present. """ try: dldir, urlmapfn = _get_download_cache_locs() except OSError as e: msg = 'Not clearing data cache - cache inacessable due to ' estr = '' if len(e.args) < 1 else (': ' + str(e)) warn(CacheMissingWarning(msg + e.__class__.__name__ + estr)) return _acquire_download_cache_lock() try: if hashorurl is None: # dldir includes both the download files and the urlmapfn. This structure # is required since we cannot know a priori the actual file name corresponding # to the shelve map named urlmapfn. if os.path.exists(dldir): shutil.rmtree(dldir) else: with shelve.open(urlmapfn) as url2hash: filepath = os.path.join(dldir, hashorurl) if not _is_inside(filepath, dldir): raise RuntimeError("attempted to use clear_download_cache on" " a path outside the data cache directory") hash_key = hashorurl if os.path.exists(filepath): for k, v in url2hash.items(): if v == filepath: del url2hash[k] os.unlink(filepath) elif hash_key in url2hash: filepath = url2hash[hash_key] del url2hash[hash_key] if os.path.exists(filepath): # Make sure the filepath still actually exists (perhaps user removed it) os.unlink(filepath) # Otherwise could not find file or url, but no worries. # Clearing download cache just makes sure that the file or url # is no longer in the cache regardless of starting condition. finally: # the lock will be gone if rmtree was used above, but release otherwise if os.path.exists(os.path.join(dldir, 'lock')): _release_download_cache_lock() def _get_download_cache_locs(): """ Finds the path to the data cache directory and makes them if they don't exist. Returns ------- datadir : str The path to the data cache directory. shelveloc : str The path to the shelve object that stores the cache info. """ from ..config.paths import get_cache_dir # datadir includes both the download files and the shelveloc. This structure # is required since we cannot know a priori the actual file name corresponding # to the shelve map named shelveloc. (The backend can vary and is allowed to # do whatever it wants with the filename. Filename munging can and does happen # in practice). py_version = 'py' + str(sys.version_info.major) datadir = os.path.join(get_cache_dir(), 'download', py_version) shelveloc = os.path.join(datadir, 'urlmap') if not os.path.exists(datadir): try: os.makedirs(datadir) except OSError as e: if not os.path.exists(datadir): raise elif not os.path.isdir(datadir): msg = 'Data cache directory {0} is not a directory' raise OSError(msg.format(datadir)) if os.path.isdir(shelveloc): msg = 'Data cache shelve object location {0} is a directory' raise OSError(msg.format(shelveloc)) return datadir, shelveloc # the cache directory must be locked before any writes are performed. Same for # the hash shelve, so this should be used for both. def _acquire_download_cache_lock(): """ Uses the lock directory method. This is good because `mkdir` is atomic at the system call level, so it's thread-safe. """ lockdir = os.path.join(_get_download_cache_locs()[0], 'lock') for i in range(conf.download_cache_lock_attempts): try: os.mkdir(lockdir) # write the pid of this process for informational purposes with open(os.path.join(lockdir, 'pid'), 'w') as f: f.write(str(os.getpid())) except OSError: time.sleep(1) else: return msg = ("Unable to acquire lock for cache directory ({0} exists). " "You may need to delete the lock if the python interpreter wasn't " "shut down properly.") raise RuntimeError(msg.format(lockdir)) def _release_download_cache_lock(): lockdir = os.path.join(_get_download_cache_locs()[0], 'lock') if os.path.isdir(lockdir): # if the pid file is present, be sure to remove it pidfn = os.path.join(lockdir, 'pid') if os.path.exists(pidfn): os.remove(pidfn) os.rmdir(lockdir) else: msg = 'Error releasing lock. "{0}" either does not exist or is not ' +\ 'a directory.' raise RuntimeError(msg.format(lockdir)) def get_cached_urls(): """ Get the list of URLs in the cache. Especially useful for looking up what files are stored in your cache when you don't have internet access. Returns ------- cached_urls : list List of cached URLs. """ # The code below is modified from astropy.utils.data.download_file() try: dldir, urlmapfn = _get_download_cache_locs() except OSError as e: msg = 'Remote data cache could not be accessed due to ' estr = '' if len(e.args) < 1 else (': ' + str(e)) warn(CacheMissingWarning(msg + e.__class__.__name__ + estr)) return False with shelve.open(urlmapfn) as url2hash: return list(url2hash.keys())
8ae05a98090d689915915b9010180e2548d49361e3702d3a624e4868b2b2bbdb
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ A "grab bag" of relatively small general-purpose utilities that don't have a clear module/package to live in. """ import abc import contextlib import difflib import inspect import json import os import signal import sys import traceback import unicodedata import locale import threading import re import urllib.request from itertools import zip_longest from contextlib import contextmanager from collections import defaultdict, OrderedDict __all__ = ['isiterable', 'silence', 'format_exception', 'NumpyRNGContext', 'find_api_page', 'is_path_hidden', 'walk_skip_hidden', 'JsonCustomEncoder', 'indent', 'InheritDocstrings', 'OrderedDescriptor', 'OrderedDescriptorContainer', 'set_locale', 'ShapedLikeNDArray', 'check_broadcast', 'IncompatibleShapeError', 'dtype_bytes_or_chars'] def isiterable(obj): """Returns `True` if the given object is iterable.""" try: iter(obj) return True except TypeError: return False def indent(s, shift=1, width=4): """Indent a block of text. The indentation is applied to each line.""" indented = '\n'.join(' ' * (width * shift) + l if l else '' for l in s.splitlines()) if s[-1] == '\n': indented += '\n' return indented class _DummyFile: """A noop writeable object.""" def write(self, s): pass @contextlib.contextmanager def silence(): """A context manager that silences sys.stdout and sys.stderr.""" old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = _DummyFile() sys.stderr = _DummyFile() yield sys.stdout = old_stdout sys.stderr = old_stderr def format_exception(msg, *args, **kwargs): """ Given an exception message string, uses new-style formatting arguments ``{filename}``, ``{lineno}``, ``{func}`` and/or ``{text}`` to fill in information about the exception that occurred. For example: try: 1/0 except: raise ZeroDivisionError( format_except('A divide by zero occurred in {filename} at ' 'line {lineno} of function {func}.')) Any additional positional or keyword arguments passed to this function are also used to format the message. .. note:: This uses `sys.exc_info` to gather up the information needed to fill in the formatting arguments. Since `sys.exc_info` is not carried outside a handled exception, it's not wise to use this outside of an ``except`` clause - if it is, this will substitute '<unkown>' for the 4 formatting arguments. """ tb = traceback.extract_tb(sys.exc_info()[2], limit=1) if len(tb) > 0: filename, lineno, func, text = tb[0] else: filename = lineno = func = text = '<unknown>' return msg.format(*args, filename=filename, lineno=lineno, func=func, text=text, **kwargs) class NumpyRNGContext: """ A context manager (for use with the ``with`` statement) that will seed the numpy random number generator (RNG) to a specific value, and then restore the RNG state back to whatever it was before. This is primarily intended for use in the astropy testing suit, but it may be useful in ensuring reproducibility of Monte Carlo simulations in a science context. Parameters ---------- seed : int The value to use to seed the numpy RNG Examples -------- A typical use case might be:: with NumpyRNGContext(<some seed value you pick>): from numpy import random randarr = random.randn(100) ... run your test using `randarr` ... #Any code using numpy.random at this indent level will act just as it #would have if it had been before the with statement - e.g. whatever #the default seed is. """ def __init__(self, seed): self.seed = seed def __enter__(self): from numpy import random self.startstate = random.get_state() random.seed(self.seed) def __exit__(self, exc_type, exc_value, traceback): from numpy import random random.set_state(self.startstate) def find_api_page(obj, version=None, openinbrowser=True, timeout=None): """ Determines the URL of the API page for the specified object, and optionally open that page in a web browser. .. note:: You must be connected to the internet for this to function even if ``openinbrowser`` is `False`, unless you provide a local version of the documentation to ``version`` (e.g., ``file:///path/to/docs``). Parameters ---------- obj The object to open the docs for or its fully-qualified name (as a str). version : str The doc version - either a version number like '0.1', 'dev' for the development/latest docs, or a URL to point to a specific location that should be the *base* of the documentation. Defaults to latest if you are on aren't on a release, otherwise, the version you are on. openinbrowser : bool If `True`, the `webbrowser` package will be used to open the doc page in a new web browser window. timeout : number, optional The number of seconds to wait before timing-out the query to the astropy documentation. If not given, the default python stdlib timeout will be used. Returns ------- url : str The loaded URL Raises ------ ValueError If the documentation can't be found """ import webbrowser from zlib import decompress if (not isinstance(obj, str) and hasattr(obj, '__module__') and hasattr(obj, '__name__')): obj = obj.__module__ + '.' + obj.__name__ elif inspect.ismodule(obj): obj = obj.__name__ if version is None: from .. import version if version.release: version = 'v' + version.version else: version = 'dev' if '://' in version: if version.endswith('index.html'): baseurl = version[:-10] elif version.endswith('/'): baseurl = version else: baseurl = version + '/' elif version == 'dev' or version == 'latest': baseurl = 'http://devdocs.astropy.org/' else: baseurl = 'http://docs.astropy.org/en/{vers}/'.format(vers=version) if timeout is None: uf = urllib.request.urlopen(baseurl + 'objects.inv') else: uf = urllib.request.urlopen(baseurl + 'objects.inv', timeout=timeout) try: oiread = uf.read() # need to first read/remove the first four lines, which have info before # the compressed section with the actual object inventory idx = -1 headerlines = [] for _ in range(4): oldidx = idx idx = oiread.index(b'\n', oldidx + 1) headerlines.append(oiread[(oldidx+1):idx].decode('utf-8')) # intersphinx version line, project name, and project version ivers, proj, vers, compr = headerlines if 'The remainder of this file is compressed using zlib' not in compr: raise ValueError('The file downloaded from {0} does not seem to be' 'the usual Sphinx objects.inv format. Maybe it ' 'has changed?'.format(baseurl + 'objects.inv')) compressed = oiread[(idx+1):] finally: uf.close() decompressed = decompress(compressed).decode('utf-8') resurl = None for l in decompressed.strip().splitlines(): ls = l.split() name = ls[0] loc = ls[3] if loc.endswith('$'): loc = loc[:-1] + name if name == obj: resurl = baseurl + loc break if resurl is None: raise ValueError('Could not find the docs for the object {obj}'.format(obj=obj)) elif openinbrowser: webbrowser.open(resurl) return resurl def signal_number_to_name(signum): """ Given an OS signal number, returns a signal name. If the signal number is unknown, returns ``'UNKNOWN'``. """ # Since these numbers and names are platform specific, we use the # builtin signal module and build a reverse mapping. signal_to_name_map = dict((k, v) for v, k in signal.__dict__.items() if v.startswith('SIG')) return signal_to_name_map.get(signum, 'UNKNOWN') if sys.platform == 'win32': import ctypes def _has_hidden_attribute(filepath): """ Returns True if the given filepath has the hidden attribute on MS-Windows. Based on a post here: http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection """ if isinstance(filepath, bytes): filepath = filepath.decode(sys.getfilesystemencoding()) try: attrs = ctypes.windll.kernel32.GetFileAttributesW(filepath) result = bool(attrs & 2) and attrs != -1 except AttributeError: result = False return result else: def _has_hidden_attribute(filepath): return False def is_path_hidden(filepath): """ Determines if a given file or directory is hidden. Parameters ---------- filepath : str The path to a file or directory Returns ------- hidden : bool Returns `True` if the file is hidden """ name = os.path.basename(os.path.abspath(filepath)) if isinstance(name, bytes): is_dotted = name.startswith(b'.') else: is_dotted = name.startswith('.') return is_dotted or _has_hidden_attribute(filepath) def walk_skip_hidden(top, onerror=None, followlinks=False): """ A wrapper for `os.walk` that skips hidden files and directories. This function does not have the parameter ``topdown`` from `os.walk`: the directories must always be recursed top-down when using this function. See also -------- os.walk : For a description of the parameters """ for root, dirs, files in os.walk( top, topdown=True, onerror=onerror, followlinks=followlinks): # These lists must be updated in-place so os.walk will skip # hidden directories dirs[:] = [d for d in dirs if not is_path_hidden(d)] files[:] = [f for f in files if not is_path_hidden(f)] yield root, dirs, files class JsonCustomEncoder(json.JSONEncoder): """Support for data types that JSON default encoder does not do. This includes: * Numpy array or number * Complex number * Set * Bytes * astropy.UnitBase * astropy.Quantity Examples -------- >>> import json >>> import numpy as np >>> from astropy.utils.misc import JsonCustomEncoder >>> json.dumps(np.arange(3), cls=JsonCustomEncoder) '[0, 1, 2]' """ def default(self, obj): from .. import units as u import numpy as np if isinstance(obj, u.Quantity): return dict(value=obj.value, unit=obj.unit.to_string()) if isinstance(obj, (np.number, np.ndarray)): return obj.tolist() elif isinstance(obj, complex): return [obj.real, obj.imag] elif isinstance(obj, set): return list(obj) elif isinstance(obj, bytes): # pragma: py3 return obj.decode() elif isinstance(obj, (u.UnitBase, u.FunctionUnitBase)): if obj == u.dimensionless_unscaled: obj = 'dimensionless_unit' else: return obj.to_string() return json.JSONEncoder.default(self, obj) def strip_accents(s): """ Remove accents from a Unicode string. This helps with matching "ångström" to "angstrom", for example. """ return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') def did_you_mean(s, candidates, n=3, cutoff=0.8, fix=None): """ When a string isn't found in a set of candidates, we can be nice to provide a list of alternatives in the exception. This convenience function helps to format that part of the exception. Parameters ---------- s : str candidates : sequence of str or dict of str keys n : int The maximum number of results to include. See `difflib.get_close_matches`. cutoff : float In the range [0, 1]. Possibilities that don't score at least that similar to word are ignored. See `difflib.get_close_matches`. fix : callable A callable to modify the results after matching. It should take a single string and return a sequence of strings containing the fixed matches. Returns ------- message : str Returns the string "Did you mean X, Y, or Z?", or the empty string if no alternatives were found. """ if isinstance(s, str): s = strip_accents(s) s_lower = s.lower() # Create a mapping from the lower case name to all capitalization # variants of that name. candidates_lower = {} for candidate in candidates: candidate_lower = candidate.lower() candidates_lower.setdefault(candidate_lower, []) candidates_lower[candidate_lower].append(candidate) # The heuristic here is to first try "singularizing" the word. If # that doesn't match anything use difflib to find close matches in # original, lower and upper case. if s_lower.endswith('s') and s_lower[:-1] in candidates_lower: matches = [s_lower[:-1]] else: matches = difflib.get_close_matches( s_lower, candidates_lower, n=n, cutoff=cutoff) if len(matches): capitalized_matches = set() for match in matches: capitalized_matches.update(candidates_lower[match]) matches = capitalized_matches if fix is not None: mapped_matches = [] for match in matches: mapped_matches.extend(fix(match)) matches = mapped_matches matches = list(set(matches)) matches = sorted(matches) if len(matches) == 1: matches = matches[0] else: matches = (', '.join(matches[:-1]) + ' or ' + matches[-1]) return 'Did you mean {0}?'.format(matches) return '' class InheritDocstrings(type): """ This metaclass makes methods of a class automatically have their docstrings filled in from the methods they override in the base class. If the class uses multiple inheritance, the docstring will be chosen from the first class in the bases list, in the same way as methods are normally resolved in Python. If this results in selecting the wrong docstring, the docstring will need to be explicitly included on the method. For example:: >>> from astropy.utils.misc import InheritDocstrings >>> class A(metaclass=InheritDocstrings): ... def wiggle(self): ... "Wiggle the thingamajig" ... pass >>> class B(A): ... def wiggle(self): ... pass >>> B.wiggle.__doc__ u'Wiggle the thingamajig' """ def __init__(cls, name, bases, dct): def is_public_member(key): return ( (key.startswith('__') and key.endswith('__') and len(key) > 4) or not key.startswith('_')) for key, val in dct.items(): if (inspect.isfunction(val) and is_public_member(key) and val.__doc__ is None): for base in cls.__mro__[1:]: super_method = getattr(base, key, None) if super_method is not None: val.__doc__ = super_method.__doc__ break super().__init__(name, bases, dct) class OrderedDescriptor(metaclass=abc.ABCMeta): """ Base class for descriptors whose order in the class body should be preserved. Intended for use in concert with the `OrderedDescriptorContainer` metaclass. Subclasses of `OrderedDescriptor` must define a value for a class attribute called ``_class_attribute_``. This is the name of a class attribute on the *container* class for these descriptors, which will be set to an `~collections.OrderedDict` at class creation time. This `~collections.OrderedDict` will contain a mapping of all class attributes that were assigned instances of the `OrderedDescriptor` subclass, to the instances themselves. See the documentation for `OrderedDescriptorContainer` for a concrete example. Optionally, subclasses of `OrderedDescriptor` may define a value for a class attribute called ``_name_attribute_``. This should be the name of an attribute on instances of the subclass. When specified, during creation of a class containing these descriptors, the name attribute on each instance will be set to the name of the class attribute it was assigned to on the class. .. note:: Although this class is intended for use with *descriptors* (i.e. classes that define any of the ``__get__``, ``__set__``, or ``__delete__`` magic methods), this base class is not itself a descriptor, and technically this could be used for classes that are not descriptors too. However, use with descriptors is the original intended purpose. """ # This id increments for each OrderedDescriptor instance created, so they # are always ordered in the order they were created. Class bodies are # guaranteed to be executed from top to bottom. Not sure if this is # thread-safe though. _nextid = 1 @property @abc.abstractmethod def _class_attribute_(self): """ Subclasses should define this attribute to the name of an attribute on classes containing this subclass. That attribute will contain the mapping of all instances of that `OrderedDescriptor` subclass defined in the class body. If the same descriptor needs to be used with different classes, each with different names of this attribute, multiple subclasses will be needed. """ _name_attribute_ = None """ Subclasses may optionally define this attribute to specify the name of an attribute on instances of the class that should be filled with the instance's attribute name at class creation time. """ def __init__(self, *args, **kwargs): # The _nextid attribute is shared across all subclasses so that # different subclasses of OrderedDescriptors can be sorted correctly # between themselves self.__order = OrderedDescriptor._nextid OrderedDescriptor._nextid += 1 super().__init__() def __lt__(self, other): """ Defined for convenient sorting of `OrderedDescriptor` instances, which are defined to sort in their creation order. """ if (isinstance(self, OrderedDescriptor) and isinstance(other, OrderedDescriptor)): try: return self.__order < other.__order except AttributeError: raise RuntimeError( 'Could not determine ordering for {0} and {1}; at least ' 'one of them is not calling super().__init__ in its ' '__init__.'.format(self, other)) else: return NotImplemented class OrderedDescriptorContainer(type): """ Classes should use this metaclass if they wish to use `OrderedDescriptor` attributes, which are class attributes that "remember" the order in which they were defined in the class body. Every subclass of `OrderedDescriptor` has an attribute called ``_class_attribute_``. For example, if we have .. code:: python class ExampleDecorator(OrderedDescriptor): _class_attribute_ = '_examples_' Then when a class with the `OrderedDescriptorContainer` metaclass is created, it will automatically be assigned a class attribute ``_examples_`` referencing an `~collections.OrderedDict` containing all instances of ``ExampleDecorator`` defined in the class body, mapped to by the names of the attributes they were assigned to. When subclassing a class with this metaclass, the descriptor dict (i.e. ``_examples_`` in the above example) will *not* contain descriptors inherited from the base class. That is, this only works by default with decorators explicitly defined in the class body. However, the subclass *may* define an attribute ``_inherit_decorators_`` which lists `OrderedDescriptor` classes that *should* be added from base classes. See the examples section below for an example of this. Examples -------- >>> from astropy.utils import OrderedDescriptor, OrderedDescriptorContainer >>> class TypedAttribute(OrderedDescriptor): ... \"\"\" ... Attributes that may only be assigned objects of a specific type, ... or subclasses thereof. For some reason we care about their order. ... \"\"\" ... ... _class_attribute_ = 'typed_attributes' ... _name_attribute_ = 'name' ... # A default name so that instances not attached to a class can ... # still be repr'd; useful for debugging ... name = '<unbound>' ... ... def __init__(self, type): ... # Make sure not to forget to call the super __init__ ... super().__init__() ... self.type = type ... ... def __get__(self, obj, objtype=None): ... if obj is None: ... return self ... if self.name in obj.__dict__: ... return obj.__dict__[self.name] ... else: ... raise AttributeError(self.name) ... ... def __set__(self, obj, value): ... if not isinstance(value, self.type): ... raise ValueError('{0}.{1} must be of type {2!r}'.format( ... obj.__class__.__name__, self.name, self.type)) ... obj.__dict__[self.name] = value ... ... def __delete__(self, obj): ... if self.name in obj.__dict__: ... del obj.__dict__[self.name] ... else: ... raise AttributeError(self.name) ... ... def __repr__(self): ... if isinstance(self.type, tuple) and len(self.type) > 1: ... typestr = '({0})'.format( ... ', '.join(t.__name__ for t in self.type)) ... else: ... typestr = self.type.__name__ ... return '<{0}(name={1}, type={2})>'.format( ... self.__class__.__name__, self.name, typestr) ... Now let's create an example class that uses this ``TypedAttribute``:: >>> class Point2D(metaclass=OrderedDescriptorContainer): ... x = TypedAttribute((float, int)) ... y = TypedAttribute((float, int)) ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... >>> p1 = Point2D(1.0, 2.0) >>> p1.x 1.0 >>> p1.y 2.0 >>> p2 = Point2D('a', 'b') # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValueError: Point2D.x must be of type (float, int>) We see that ``TypedAttribute`` works more or less as advertised, but there's nothing special about that. Let's see what `OrderedDescriptorContainer` did for us:: >>> Point2D.typed_attributes OrderedDict([('x', <TypedAttribute(name=x, type=(float, int))>), ('y', <TypedAttribute(name=y, type=(float, int))>)]) If we create a subclass, it does *not* by default add inherited descriptors to ``typed_attributes``:: >>> class Point3D(Point2D): ... z = TypedAttribute((float, int)) ... >>> Point3D.typed_attributes OrderedDict([('z', <TypedAttribute(name=z, type=(float, int))>)]) However, if we specify ``_inherit_descriptors_`` from ``Point2D`` then it will do so:: >>> class Point3D(Point2D): ... _inherit_descriptors_ = (TypedAttribute,) ... z = TypedAttribute((float, int)) ... >>> Point3D.typed_attributes OrderedDict([('x', <TypedAttribute(name=x, type=(float, int))>), ('y', <TypedAttribute(name=y, type=(float, int))>), ('z', <TypedAttribute(name=z, type=(float, int))>)]) .. note:: Hopefully it is clear from these examples that this construction also allows a class of type `OrderedDescriptorContainer` to use multiple different `OrderedDescriptor` classes simultaneously. """ _inherit_descriptors_ = () def __init__(cls, cls_name, bases, members): descriptors = defaultdict(list) seen = set() inherit_descriptors = () descr_bases = {} for mro_cls in cls.__mro__: for name, obj in mro_cls.__dict__.items(): if name in seen: # Checks if we've already seen an attribute of the given # name (if so it will override anything of the same name in # any base class) continue seen.add(name) if (not isinstance(obj, OrderedDescriptor) or (inherit_descriptors and not isinstance(obj, inherit_descriptors))): # The second condition applies when checking any # subclasses, to see if we can inherit any descriptors of # the given type from subclasses (by default inheritance is # disabled unless the class has _inherit_descriptors_ # defined) continue if obj._name_attribute_ is not None: setattr(obj, obj._name_attribute_, name) # Don't just use the descriptor's class directly; instead go # through its MRO and find the class on which _class_attribute_ # is defined directly. This way subclasses of some # OrderedDescriptor *may* override _class_attribute_ and have # its own _class_attribute_, but by default all subclasses of # some OrderedDescriptor are still grouped together # TODO: It might be worth clarifying this in the docs if obj.__class__ not in descr_bases: for obj_cls_base in obj.__class__.__mro__: if '_class_attribute_' in obj_cls_base.__dict__: descr_bases[obj.__class__] = obj_cls_base descriptors[obj_cls_base].append((obj, name)) break else: # Make sure to put obj first for sorting purposes obj_cls_base = descr_bases[obj.__class__] descriptors[obj_cls_base].append((obj, name)) if not getattr(mro_cls, '_inherit_descriptors_', False): # If _inherit_descriptors_ is undefined then we don't inherit # any OrderedDescriptors from any of the base classes, and # there's no reason to continue through the MRO break else: inherit_descriptors = mro_cls._inherit_descriptors_ for descriptor_cls, instances in descriptors.items(): instances.sort() instances = OrderedDict((key, value) for value, key in instances) setattr(cls, descriptor_cls._class_attribute_, instances) super().__init__(cls_name, bases, members) LOCALE_LOCK = threading.Lock() @contextmanager def set_locale(name): """ Context manager to temporarily set the locale to ``name``. An example is setting locale to "C" so that the C strtod() function will use "." as the decimal point to enable consistent numerical string parsing. Note that one cannot nest multiple set_locale() context manager statements as this causes a threading lock. This code taken from https://stackoverflow.com/questions/18593661/how-do-i-strftime-a-date-object-in-a-different-locale. Parameters ========== name : str Locale name, e.g. "C" or "fr_FR". """ name = str(name) with LOCALE_LOCK: saved = locale.setlocale(locale.LC_ALL) if saved == name: # Don't do anything if locale is already the requested locale yield else: try: locale.setlocale(locale.LC_ALL, name) yield finally: locale.setlocale(locale.LC_ALL, saved) class ShapedLikeNDArray(metaclass=abc.ABCMeta): """Mixin class to provide shape-changing methods. The class proper is assumed to have some underlying data, which are arrays or array-like structures. It must define a ``shape`` property, which gives the shape of those data, as well as an ``_apply`` method that creates a new instance in which a `~numpy.ndarray` method has been applied to those. Furthermore, for consistency with `~numpy.ndarray`, it is recommended to define a setter for the ``shape`` property, which, like the `~numpy.ndarray.shape` property allows in-place reshaping the internal data (and, unlike the ``reshape`` method raises an exception if this is not possible). This class also defines default implementations for ``ndim`` and ``size`` properties, calculating those from the ``shape``. These can be overridden by subclasses if there are faster ways to obtain those numbers. """ # Note to developers: if new methods are added here, be sure to check that # they work properly with the classes that use this, such as Time and # BaseRepresentation, i.e., look at their ``_apply`` methods and add # relevant tests. This is particularly important for methods that imply # copies rather than views of data (see the special-case treatment of # 'flatten' in Time). @property @abc.abstractmethod def shape(self): """The shape of the instance and underlying arrays.""" @abc.abstractmethod def _apply(method, *args, **kwargs): """Create a new instance, with ``method`` applied to underlying data. The method is any of the shape-changing methods for `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those picking particular elements (``__getitem__``, ``take``, etc.). It will be applied to the underlying arrays (e.g., ``jd1`` and ``jd2`` in `~astropy.time.Time`), with the results used to create a new instance. Parameters ---------- method : str Method to be applied to the instance's internal data arrays. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. """ @property def ndim(self): """The number of dimensions of the instance and underlying arrays.""" return len(self.shape) @property def size(self): """The size of the object, as calculated from its shape.""" size = 1 for sh in self.shape: size *= sh return size @property def isscalar(self): return self.shape == () def __len__(self): if self.isscalar: raise TypeError("Scalar {0!r} object has no len()" .format(self.__class__.__name__)) return self.shape[0] def __bool__(self): """Any instance should evaluate to True, except when it is empty.""" return self.size > 0 def __getitem__(self, item): try: return self._apply('__getitem__', item) except IndexError: if self.isscalar: raise TypeError('scalar {0!r} object is not subscriptable.' .format(self.__class__.__name__)) else: raise def __iter__(self): if self.isscalar: raise TypeError('scalar {0!r} object is not iterable.' .format(self.__class__.__name__)) # We cannot just write a generator here, since then the above error # would only be raised once we try to use the iterator, rather than # upon its definition using iter(self). def self_iter(): for idx in range(len(self)): yield self[idx] return self_iter() def copy(self, *args, **kwargs): """Return an instance containing copies of the internal data. Parameters are as for :meth:`~numpy.ndarray.copy`. """ return self._apply('copy', *args, **kwargs) def reshape(self, *args, **kwargs): """Returns an instance containing the same data with a new shape. Parameters are as for :meth:`~numpy.ndarray.reshape`. Note that it is not always possible to change the shape of an array without copying the data (see :func:`~numpy.reshape` documentation). If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute (note: this may not be implemented for all classes using ``ShapedLikeNDArray``). """ return self._apply('reshape', *args, **kwargs) def ravel(self, *args, **kwargs): """Return an instance with the array collapsed into one dimension. Parameters are as for :meth:`~numpy.ndarray.ravel`. Note that it is not always possible to unravel an array without copying the data. If you want an error to be raise if the data is copied, you should should assign shape ``(-1,)`` to the shape attribute. """ return self._apply('ravel', *args, **kwargs) def flatten(self, *args, **kwargs): """Return a copy with the array collapsed into one dimension. Parameters are as for :meth:`~numpy.ndarray.flatten`. """ return self._apply('flatten', *args, **kwargs) def transpose(self, *args, **kwargs): """Return an instance with the data transposed. Parameters are as for :meth:`~numpy.ndarray.transpose`. All internal data are views of the data of the original. """ return self._apply('transpose', *args, **kwargs) @property def T(self): """Return an instance with the data transposed. Parameters are as for :attr:`~numpy.ndarray.T`. All internal data are views of the data of the original. """ if self.ndim < 2: return self else: return self.transpose() def swapaxes(self, *args, **kwargs): """Return an instance with the given axes interchanged. Parameters are as for :meth:`~numpy.ndarray.swapaxes`: ``axis1, axis2``. All internal data are views of the data of the original. """ return self._apply('swapaxes', *args, **kwargs) def diagonal(self, *args, **kwargs): """Return an instance with the specified diagonals. Parameters are as for :meth:`~numpy.ndarray.diagonal`. All internal data are views of the data of the original. """ return self._apply('diagonal', *args, **kwargs) def squeeze(self, *args, **kwargs): """Return an instance with single-dimensional shape entries removed Parameters are as for :meth:`~numpy.ndarray.squeeze`. All internal data are views of the data of the original. """ return self._apply('squeeze', *args, **kwargs) def take(self, indices, axis=None, mode='raise'): """Return a new instance formed from the elements at the given indices. Parameters are as for :meth:`~numpy.ndarray.take`, except that, obviously, no output array can be given. """ return self._apply('take', indices, axis=axis, mode=mode) class IncompatibleShapeError(ValueError): def __init__(self, shape_a, shape_a_idx, shape_b, shape_b_idx): super().__init__(shape_a, shape_a_idx, shape_b, shape_b_idx) def check_broadcast(*shapes): """ Determines whether two or more Numpy arrays can be broadcast with each other based on their shape tuple alone. Parameters ---------- *shapes : tuple All shapes to include in the comparison. If only one shape is given it is passed through unmodified. If no shapes are given returns an empty `tuple`. Returns ------- broadcast : `tuple` If all shapes are mutually broadcastable, returns a tuple of the full broadcast shape. """ if len(shapes) == 0: return () elif len(shapes) == 1: return shapes[0] reversed_shapes = (reversed(shape) for shape in shapes) full_shape = [] for dims in zip_longest(*reversed_shapes, fillvalue=1): max_dim = 1 max_dim_idx = None for idx, dim in enumerate(dims): if dim == 1: continue if max_dim == 1: # The first dimension of size greater than 1 max_dim = dim max_dim_idx = idx elif dim != max_dim: raise IncompatibleShapeError( shapes[max_dim_idx], max_dim_idx, shapes[idx], idx) full_shape.append(max_dim) return tuple(full_shape[::-1]) def dtype_bytes_or_chars(dtype): """ Parse the number out of a dtype.str value like '<U5' or '<f8'. See #5819 for discussion on the need for this function for getting the number of characters corresponding to a string dtype. Parameters ---------- dtype : numpy dtype object Input dtype Returns ------- bytes_or_chars : int or None Bits (for numeric types) or characters (for string types) """ match = re.search(r'(\d+)$', dtype.str) out = int(match.group(1)) if match else None return out
f88a53718225b85da742cac0b2115fc65cf2a2ccea081d86b5448319c49002a4
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handle loading six package from system or from the bundled copy """ import imp from distutils.version import StrictVersion _SIX_MIN_VERSION = StrictVersion('1.10.0') # Update this to prevent Astropy from using its bundled copy of six # (but only if some other version of at least _SIX_MIN_VERSION can # be provided) _SIX_SEARCH_PATH = ['astropy.extern.bundled.six', 'six'] def _find_module(name, path=None): """ Alternative to `imp.find_module` that can also search in subpackages. """ parts = name.split('.') for part in parts: if path is not None: path = [path] fh, path, descr = imp.find_module(part, path) return fh, path, descr def _import_six(search_path=_SIX_SEARCH_PATH): for mod_name in search_path: try: mod_info = _find_module(mod_name) except ImportError: continue mod = imp.load_module(__name__, *mod_info) try: if StrictVersion(mod.__version__) >= _SIX_MIN_VERSION: break except (AttributeError, ValueError): # Attribute error if the six module isn't what it should be and # doesn't have a .__version__; ValueError if the version string # exists but is somehow bogus/unparseable continue else: raise ImportError( "Astropy requires the 'six' module of minimum version {0}; " "normally this is bundled with the astropy package so if you get " "this warning consult the packager of your Astropy " "distribution.".format(_SIX_MIN_VERSION)) _import_six()
a0ebf94694e1b9041eb99b9eb9cb66cfd954947d06cd53e9b3c1509358a0a6aa
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os def get_package_data(): paths = [os.path.join('js', '*.js'), os.path.join('css', '*.css')] return {'astropy.extern': paths}
131ce5a64bb9fae13ab946e090a9d9b9c4e10438846254db93928fd9b067773e
""" Normalization class for Matplotlib that can be used to produce colorbars. """ import numpy as np from numpy import ma from .interval import (PercentileInterval, AsymmetricPercentileInterval, ManualInterval, MinMaxInterval, BaseInterval) from .stretch import (LinearStretch, SqrtStretch, PowerStretch, LogStretch, AsinhStretch, BaseStretch) try: import matplotlib # pylint: disable=W0611 from matplotlib.colors import Normalize except ImportError: class Normalize: def __init__(self, *args, **kwargs): raise ImportError('matplotlib is required in order to use this ' 'class.') __all__ = ['ImageNormalize', 'simple_norm'] __doctest_requires__ = {'*': ['matplotlib']} class ImageNormalize(Normalize): """ Normalization class to be used with Matplotlib. Parameters ---------- data : `~numpy.ndarray`, optional The image array. This input is used only if ``interval`` is also input. ``data`` and ``interval`` are used to compute the vmin and/or vmax values only if ``vmin`` or ``vmax`` are not input. interval : `~astropy.visualization.BaseInterval` subclass instance, optional The interval object to apply to the input ``data`` to determine the ``vmin`` and ``vmax`` values. This input is used only if ``data`` is also input. ``data`` and ``interval`` are used to compute the vmin and/or vmax values only if ``vmin`` or ``vmax`` are not input. vmin, vmax : float The minimum and maximum levels to show for the data. The ``vmin`` and ``vmax`` inputs override any calculated values from the ``interval`` and ``data`` inputs. stretch : `~astropy.visualization.BaseStretch` subclass instance, optional The stretch object to apply to the data. The default is `~astropy.visualization.LinearStretch`. clip : bool, optional If `True` (default), data values outside the [0:1] range are clipped to the [0:1] range. """ def __init__(self, data=None, interval=None, vmin=None, vmax=None, stretch=LinearStretch(), clip=False): # this super call checks for matplotlib super().__init__(vmin=vmin, vmax=vmax, clip=clip) self.vmin = vmin self.vmax = vmax if data is not None and interval is not None: _vmin, _vmax = interval.get_limits(data) if self.vmin is None: self.vmin = _vmin if self.vmax is None: self.vmax = _vmax if stretch is not None and not isinstance(stretch, BaseStretch): raise TypeError('stretch must be an instance of a BaseStretch ' 'subclass') self.stretch = stretch if interval is not None and not isinstance(interval, BaseInterval): raise TypeError('interval must be an instance of a BaseInterval ' 'subclass') self.interval = interval self.inverse_stretch = stretch.inverse self.clip = clip def __call__(self, values, clip=None): if clip is None: clip = self.clip if isinstance(values, ma.MaskedArray): if clip: mask = False else: mask = values.mask values = values.filled(self.vmax) else: mask = False # Make sure scalars get broadcast to 1-d if np.isscalar(values): values = np.array([values], dtype=float) else: # copy because of in-place operations after values = np.array(values, copy=True, dtype=float) # Set default values for vmin and vmax if not specified self.autoscale_None(values) # Normalize based on vmin and vmax np.subtract(values, self.vmin, out=values) np.true_divide(values, self.vmax - self.vmin, out=values) # Clip to the 0 to 1 range if self.clip: values = np.clip(values, 0., 1., out=values) # Stretch values values = self.stretch(values, out=values, clip=False) # Convert to masked array for matplotlib return ma.array(values, mask=mask) def inverse(self, values): # Find unstretched values in range 0 to 1 values_norm = self.inverse_stretch(values, clip=False) # Scale to original range return values_norm * (self.vmax - self.vmin) + self.vmin def simple_norm(data, stretch='linear', power=1.0, asinh_a=0.1, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None, clip=True): """ Return a Normalization class that can be used for displaying images with Matplotlib. This function enables only a subset of image stretching functions available in `~astropy.visualization.mpl_normalize.ImageNormalize`. This function is used by the ``astropy.visualization.scripts.fits2bitmap`` script. Parameters ---------- data : `~numpy.ndarray` The image array. stretch : {'linear', 'sqrt', 'power', log', 'asinh'}, optional The stretch function to apply to the image. The default is 'linear'. power : float, optional The power index for ``stretch='power'``. The default is 1.0. asinh_a : float, optional For ``stretch='asinh'``, the value where the asinh curve transitions from linear to logarithmic behavior, expressed as a fraction of the normalized image. Must be in the range between 0 and 1. The default is 0.1. min_cut : float, optional The pixel value of the minimum cut level. Data values less than ``min_cut`` will set to ``min_cut`` before stretching the image. The default is the image minimum. ``min_cut`` overrides ``min_percent``. max_cut : float, optional The pixel value of the maximum cut level. Data values greater than ``min_cut`` will set to ``min_cut`` before stretching the image. The default is the image maximum. ``max_cut`` overrides ``max_percent``. min_percent : float, optional The percentile value used to determine the pixel value of minimum cut level. The default is 0.0. ``min_percent`` overrides ``percent``. max_percent : float, optional The percentile value used to determine the pixel value of maximum cut level. The default is 100.0. ``max_percent`` overrides ``percent``. percent : float, optional The percentage of the image values used to determine the pixel values of the minimum and maximum cut levels. The lower cut level will set at the ``(100 - percent) / 2`` percentile, while the upper cut level will be set at the ``(100 + percent) / 2`` percentile. The default is 100.0. ``percent`` is ignored if either ``min_percent`` or ``max_percent`` is input. clip : bool, optional If `True` (default), data values outside the [0:1] range are clipped to the [0:1] range. Returns ------- result : `ImageNormalize` instance An `ImageNormalize` instance that can be used for displaying images with Matplotlib. """ if percent is not None: interval = PercentileInterval(percent) elif min_percent is not None or max_percent is not None: interval = AsymmetricPercentileInterval(min_percent or 0., max_percent or 100.) elif min_cut is not None or max_cut is not None: interval = ManualInterval(min_cut, max_cut) else: interval = MinMaxInterval() if stretch == 'linear': stretch = LinearStretch() elif stretch == 'sqrt': stretch = SqrtStretch() elif stretch == 'power': stretch = PowerStretch(power) elif stretch == 'log': stretch = LogStretch() elif stretch == 'asinh': stretch = AsinhStretch(asinh_a) else: raise ValueError('Unknown stretch: {0}.'.format(stretch)) vmin, vmax = interval.get_limits(data) return ImageNormalize(vmin=vmin, vmax=vmax, stretch=stretch, clip=clip)
13d205d55822cdff646031abb07281cc01d9a97c2ad890fa7088030a9fe036c3
# Licensed under a 3-clause BSD style license - see LICENSE.rst from .hist import * from .interval import * from .mpl_normalize import * from .mpl_style import * from .stretch import * from .transform import * from .units import * from .lupton_rgb import *
05ff8868d3e60549bd538d29de9611d6a96f21e19fd3752a48ba91336424eda9
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Combine 3 images to produce a properly-scaled RGB image following Lupton et al. (2004). The three images must be aligned and have the same pixel scale and size. For details, see : http://adsabs.harvard.edu/abs/2004PASP..116..133L """ import numpy as np from . import ZScaleInterval __all__ = ['make_lupton_rgb'] def compute_intensity(image_r, image_g=None, image_b=None): """ Return a naive total intensity from the red, blue, and green intensities. Parameters ---------- image_r : `~numpy.ndarray` Intensity of image to be mapped to red; or total intensity if ``image_g`` and ``image_b`` are None. image_g : `~numpy.ndarray`, optional Intensity of image to be mapped to green. image_b : `~numpy.ndarray`, optional Intensity of image to be mapped to blue. Returns ------- intensity : `~numpy.ndarray` Total intensity from the red, blue and green intensities, or ``image_r`` if green and blue images are not provided. """ if image_g is None or image_b is None: if not (image_g is None and image_b is None): raise ValueError("please specify either a single image " "or red, green, and blue images.") return image_r intensity = (image_r + image_g + image_b)/3.0 # Repack into whatever type was passed to us return np.asarray(intensity, dtype=image_r.dtype) class Mapping: """ Baseclass to map red, blue, green intensities into uint8 values. Parameters ---------- minimum : float or sequence(3) Intensity that should be mapped to black (a scalar or array for R, G, B). image : `~numpy.ndarray`, optional An image used to calculate some parameters of some mappings. """ def __init__(self, minimum=None, image=None): self._uint8Max = float(np.iinfo(np.uint8).max) try: len(minimum) except TypeError: minimum = 3*[minimum] if len(minimum) != 3: raise ValueError("please provide 1 or 3 values for minimum.") self.minimum = minimum self._image = np.asarray(image) def make_rgb_image(self, image_r, image_g, image_b): """ Convert 3 arrays, image_r, image_g, and image_b into an 8-bit RGB image. Parameters ---------- image_r : `~numpy.ndarray` Image to map to red. image_g : `~numpy.ndarray` Image to map to green. image_b : `~numpy.ndarray` Image to map to blue. Returns ------- RGBimage : `~numpy.ndarray` RGB (integer, 8-bits per channel) color image as an NxNx3 numpy array. """ image_r = np.asarray(image_r) image_g = np.asarray(image_g) image_b = np.asarray(image_b) if (image_r.shape != image_g.shape) or (image_g.shape != image_b.shape): msg = "The image shapes must match. r: {}, g: {} b: {}" raise ValueError(msg.format(image_r.shape, image_g.shape, image_b.shape)) return np.dstack(self._convert_images_to_uint8(image_r, image_g, image_b)).astype(np.uint8) def intensity(self, image_r, image_g, image_b): """ Return the total intensity from the red, blue, and green intensities. This is a naive computation, and may be overridden by subclasses. Parameters ---------- image_r : `~numpy.ndarray` Intensity of image to be mapped to red; or total intensity if ``image_g`` and ``image_b`` are None. image_g : `~numpy.ndarray`, optional Intensity of image to be mapped to green. image_b : `~numpy.ndarray`, optional Intensity of image to be mapped to blue. Returns ------- intensity : `~numpy.ndarray` Total intensity from the red, blue and green intensities, or ``image_r`` if green and blue images are not provided. """ return compute_intensity(image_r, image_g, image_b) def map_intensity_to_uint8(self, I): """ Return an array which, when multiplied by an image, returns that image mapped to the range of a uint8, [0, 255] (but not converted to uint8). The intensity is assumed to have had minimum subtracted (as that can be done per-band). Parameters ---------- I : `~numpy.ndarray` Intensity to be mapped. Returns ------- mapped_I : `~numpy.ndarray` ``I`` mapped to uint8 """ with np.errstate(invalid='ignore', divide='ignore'): return np.clip(I, 0, self._uint8Max) def _convert_images_to_uint8(self, image_r, image_g, image_b): """Use the mapping to convert images image_r, image_g, and image_b to a triplet of uint8 images""" image_r = image_r - self.minimum[0] # n.b. makes copy image_g = image_g - self.minimum[1] image_b = image_b - self.minimum[2] fac = self.map_intensity_to_uint8(self.intensity(image_r, image_g, image_b)) image_rgb = [image_r, image_g, image_b] for c in image_rgb: c *= fac c[c < 0] = 0 # individual bands can still be < 0, even if fac isn't pixmax = self._uint8Max r0, g0, b0 = image_rgb # copies -- could work row by row to minimise memory usage with np.errstate(invalid='ignore', divide='ignore'): # n.b. np.where can't and doesn't short-circuit for i, c in enumerate(image_rgb): c = np.where(r0 > g0, np.where(r0 > b0, np.where(r0 >= pixmax, c*pixmax/r0, c), np.where(b0 >= pixmax, c*pixmax/b0, c)), np.where(g0 > b0, np.where(g0 >= pixmax, c*pixmax/g0, c), np.where(b0 >= pixmax, c*pixmax/b0, c))).astype(np.uint8) c[c > pixmax] = pixmax image_rgb[i] = c return image_rgb class LinearMapping(Mapping): """ A linear map map of red, blue, green intensities into uint8 values. A linear stretch from [minimum, maximum]. If one or both are omitted use image min and/or max to set them. Parameters ---------- minimum : float Intensity that should be mapped to black (a scalar or array for R, G, B). maximum : float Intensity that should be mapped to white (a scalar). """ def __init__(self, minimum=None, maximum=None, image=None): if minimum is None or maximum is None: if image is None: raise ValueError("you must provide an image if you don't " "set both minimum and maximum") if minimum is None: minimum = image.min() if maximum is None: maximum = image.max() Mapping.__init__(self, minimum=minimum, image=image) self.maximum = maximum if maximum is None: self._range = None else: if maximum == minimum: raise ValueError("minimum and maximum values must not be equal") self._range = float(maximum - minimum) def map_intensity_to_uint8(self, I): with np.errstate(invalid='ignore', divide='ignore'): # n.b. np.where can't and doesn't short-circuit return np.where(I <= 0, 0, np.where(I >= self._range, self._uint8Max/I, self._uint8Max/self._range)) class AsinhMapping(Mapping): """ A mapping for an asinh stretch (preserving colours independent of brightness) x = asinh(Q (I - minimum)/stretch)/Q This reduces to a linear stretch if Q == 0 See http://adsabs.harvard.edu/abs/2004PASP..116..133L Parameters ---------- minimum : float Intensity that should be mapped to black (a scalar or array for R, G, B). stretch : float The linear stretch of the image. Q : float The asinh softening parameter. """ def __init__(self, minimum, stretch, Q=8): Mapping.__init__(self, minimum) epsilon = 1.0/2**23 # 32bit floating point machine epsilon; sys.float_info.epsilon is 64bit if abs(Q) < epsilon: Q = 0.1 else: Qmax = 1e10 if Q > Qmax: Q = Qmax frac = 0.1 # gradient estimated using frac*stretch is _slope self._slope = frac*self._uint8Max/np.arcsinh(frac*Q) self._soften = Q/float(stretch) def map_intensity_to_uint8(self, I): with np.errstate(invalid='ignore', divide='ignore'): # n.b. np.where can't and doesn't short-circuit return np.where(I <= 0, 0, np.arcsinh(I*self._soften)*self._slope/I) class AsinhZScaleMapping(AsinhMapping): """ A mapping for an asinh stretch, estimating the linear stretch by zscale. x = asinh(Q (I - z1)/(z2 - z1))/Q Parameters ---------- image1 : `~numpy.ndarray` or a list of arrays The image to analyse, or a list of 3 images to be converted to an intensity image. image2 : `~numpy.ndarray`, optional the second image to analyse (must be specified with image3). image3 : `~numpy.ndarray`, optional the third image to analyse (must be specified with image2). Q : float, optional The asinh softening parameter. Default is 8. pedestal : float or sequence(3), optional The value, or array of 3 values, to subtract from the images; or None. Notes ----- pedestal, if not None, is removed from the images when calculating the zscale stretch, and added back into Mapping.minimum[] """ def __init__(self, image1, image2=None, image3=None, Q=8, pedestal=None): """ """ if image2 is None or image3 is None: if not (image2 is None and image3 is None): raise ValueError("please specify either a single image " "or three images.") image = [image1] else: image = [image1, image2, image3] if pedestal is not None: try: len(pedestal) except TypeError: pedestal = 3*[pedestal] if len(pedestal) != 3: raise ValueError("please provide 1 or 3 pedestals.") image = list(image) # needs to be mutable for i, im in enumerate(image): if pedestal[i] != 0.0: image[i] = im - pedestal[i] # n.b. a copy else: pedestal = len(image)*[0.0] image = compute_intensity(*image) zscale_limits = ZScaleInterval().get_limits(image) zscale = LinearMapping(*zscale_limits, image=image) stretch = zscale.maximum - zscale.minimum[0] # zscale.minimum is always a triple minimum = zscale.minimum for i, level in enumerate(pedestal): minimum[i] += level AsinhMapping.__init__(self, minimum, stretch, Q) self._image = image def make_lupton_rgb(image_r, image_g, image_b, minimum=0, stretch=5, Q=8, filename=None): """ Return a Red/Green/Blue color image from up to 3 images using an asinh stretch. The input images can be int or float, and in any range or bit-depth. For a more detailed look at the use of this method, see the document :ref:`astropy-visualization-rgb`. Parameters ---------- image_r : `~numpy.ndarray` Image to map to red. image_g : `~numpy.ndarray` Image to map to green. image_b : `~numpy.ndarray` Image to map to blue. minimum : float Intensity that should be mapped to black (a scalar or array for R, G, B). stretch : float The linear stretch of the image. Q : float The asinh softening parameter. filename: str Write the resulting RGB image to a file (file type determined from extension). Returns ------- rgb : `~numpy.ndarray` RGB (integer, 8-bits per channel) color image as an NxNx3 numpy array. """ asinhMap = AsinhMapping(minimum, stretch, Q) rgb = asinhMap.make_rgb_image(image_r, image_g, image_b) if filename: import matplotlib.image matplotlib.image.imsave(filename, rgb, origin='lower') return rgb
7c5f18f0515170ce20f5ce2735258550eb835fbfa63709386da68645918d6009
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Classes that deal with computing intervals from arrays of values based on various criteria. """ import abc import numpy as np from ..utils.misc import InheritDocstrings from .transform import BaseTransform __all__ = ['BaseInterval', 'ManualInterval', 'MinMaxInterval', 'AsymmetricPercentileInterval', 'PercentileInterval', 'ZScaleInterval'] class BaseInterval(BaseTransform, metaclass=InheritDocstrings): """ Base class for the interval classes, which, when called with an array of values, return an interval computed following different algorithms. """ @abc.abstractmethod def get_limits(self, values): """ Return the minimum and maximum value in the interval based on the values provided. Parameters ---------- values : `~numpy.ndarray` The image values. Returns ------- vmin, vmax : float The mininium and maximum image value in the interval. """ def __call__(self, values, clip=True, out=None): """ Transform values using this interval. Parameters ---------- values : array-like The input values. clip : bool, optional If `True` (default), values outside the [0:1] range are clipped to the [0:1] range. out : `~numpy.ndarray`, optional If specified, the output values will be placed in this array (typically used for in-place calculations). Returns ------- result : `~numpy.ndarray` The transformed values. """ vmin, vmax = self.get_limits(values) if out is None: values = np.subtract(values, float(vmin)) else: if out.dtype.kind != 'f': raise TypeError('Can only do in-place scaling for ' 'floating-point arrays') values = np.subtract(values, float(vmin), out=out) if (vmax - vmin) != 0: np.true_divide(values, vmax - vmin, out=values) if clip: np.clip(values, 0., 1., out=values) return values class ManualInterval(BaseInterval): """ Interval based on user-specified values. Parameters ---------- vmin : float, optional The minimum value in the scaling. Defaults to the image minimum (ignoring NaNs) vmax : float, optional The maximum value in the scaling. Defaults to the image maximum (ignoring NaNs) """ def __init__(self, vmin=None, vmax=None): self.vmin = vmin self.vmax = vmax def get_limits(self, values): vmin = np.nanmin(values) if self.vmin is None else self.vmin vmax = np.nanmax(values) if self.vmax is None else self.vmax return vmin, vmax class MinMaxInterval(BaseInterval): """ Interval based on the minimum and maximum values in the data. """ def get_limits(self, values): return np.min(values), np.max(values) class AsymmetricPercentileInterval(BaseInterval): """ Interval based on a keeping a specified fraction of pixels (can be asymmetric). Parameters ---------- lower_percentile : float The lower percentile below which to ignore pixels. upper_percentile : float The upper percentile above which to ignore pixels. n_samples : int, optional Maximum number of values to use. If this is specified, and there are more values in the dataset as this, then values are randomly sampled from the array (with replacement). """ def __init__(self, lower_percentile, upper_percentile, n_samples=None): self.lower_percentile = lower_percentile self.upper_percentile = upper_percentile self.n_samples = n_samples def get_limits(self, values): # Make sure values is a Numpy array values = np.asarray(values).ravel() # If needed, limit the number of samples. We sample with replacement # since this is much faster. if self.n_samples is not None and values.size > self.n_samples: values = np.random.choice(values, self.n_samples) # Filter out invalid values (inf, nan) values = values[np.isfinite(values)] # Determine values at percentiles vmin, vmax = np.percentile(values, (self.lower_percentile, self.upper_percentile)) return vmin, vmax class PercentileInterval(AsymmetricPercentileInterval): """ Interval based on a keeping a specified fraction of pixels. Parameters ---------- percentile : float The fraction of pixels to keep. The same fraction of pixels is eliminated from both ends. n_samples : int, optional Maximum number of values to use. If this is specified, and there are more values in the dataset as this, then values are randomly sampled from the array (with replacement). """ def __init__(self, percentile, n_samples=None): lower_percentile = (100 - percentile) * 0.5 upper_percentile = 100 - lower_percentile super().__init__( lower_percentile, upper_percentile, n_samples=n_samples) class ZScaleInterval(BaseInterval): """ Interval based on IRAF's zscale. http://iraf.net/forum/viewtopic.php?showtopic=134139 Original implementation: https://trac.stsci.edu/ssb/stsci_python/browser/stsci_python/trunk/numdisplay/lib/stsci/numdisplay/zscale.py?rev=19347 Licensed under a 3-clause BSD style license (see AURA_LICENSE.rst). Parameters ---------- nsamples : int, optional The number of points in the array to sample for determining scaling factors. Defaults to 1000. contrast : float, optional The scaling factor (between 0 and 1) for determining the minimum and maximum value. Larger values increase the difference between the minimum and maximum values used for display. Defaults to 0.25. max_reject : float, optional If more than ``max_reject * npixels`` pixels are rejected, then the returned values are the minimum and maximum of the data. Defaults to 0.5. min_npixels : int, optional If less than ``min_npixels`` pixels are rejected, then the returned values are the minimum and maximum of the data. Defaults to 5. krej : float, optional The number of sigma used for the rejection. Defaults to 2.5. max_iterations : int, optional The maximum number of iterations for the rejection. Defaults to 5. """ def __init__(self, nsamples=1000, contrast=0.25, max_reject=0.5, min_npixels=5, krej=2.5, max_iterations=5): self.nsamples = nsamples self.contrast = contrast self.max_reject = max_reject self.min_npixels = min_npixels self.krej = krej self.max_iterations = max_iterations def get_limits(self, values): # Sample the image values = np.asarray(values) values = values[np.isfinite(values)] stride = int(max(1.0, values.size / self.nsamples)) samples = values[::stride][:self.nsamples] samples.sort() npix = len(samples) vmin = samples[0] vmax = samples[-1] # Fit a line to the sorted array of samples minpix = max(self.min_npixels, int(npix * self.max_reject)) x = np.arange(npix) ngoodpix = npix last_ngoodpix = npix + 1 # Bad pixels mask used in k-sigma clipping badpix = np.zeros(npix, dtype=bool) # Kernel used to dilate the bad pixels mask ngrow = max(1, int(npix * 0.01)) kernel = np.ones(ngrow, dtype=bool) for niter in range(self.max_iterations): if ngoodpix >= last_ngoodpix or ngoodpix < minpix: break fit = np.polyfit(x, samples, deg=1, w=(~badpix).astype(int)) fitted = np.poly1d(fit)(x) # Subtract fitted line from the data array flat = samples - fitted # Compute the k-sigma rejection threshold threshold = self.krej * flat[~badpix].std() # Detect and reject pixels further than k*sigma from the # fitted line badpix[(flat < - threshold) | (flat > threshold)] = True # Convolve with a kernel of length ngrow badpix = np.convolve(badpix, kernel, mode='same') last_ngoodpix = ngoodpix ngoodpix = np.sum(~badpix) slope, intercept = fit if ngoodpix >= minpix: if self.contrast > 0: slope = slope / self.contrast center_pixel = (npix - 1) // 2 median = np.median(samples) vmin = max(vmin, median - (center_pixel - 1) * slope) vmax = min(vmax, median + (npix - center_pixel) * slope) return vmin, vmax
e38116d304a67be1a02ed55b378ff72f2907a4a020be24947efd0525f5f8170a
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np __doctest_skip__ = ['quantity_support'] def quantity_support(format='latex_inline'): """ Enable support for plotting `astropy.units.Quantity` instances in matplotlib. May be (optionally) used with a ``with`` statement. >>> import matplotlib.pyplot as plt >>> from astropy import units as u >>> from astropy import visualization >>> with visualization.quantity_support(): ... plt.figure() ... plt.plot([1, 2, 3] * u.m) [...] ... plt.plot([101, 125, 150] * u.cm) [...] ... plt.draw() Parameters ---------- format : `astropy.units.format.Base` instance or str The name of a format or a formatter object. If not provided, defaults to ``latex_inline``. """ from .. import units as u from matplotlib import units from matplotlib import ticker def rad_fn(x, pos=None): n = int((x / np.pi) * 2.0 + 0.25) if n == 0: return '0' elif n == 1: return 'π/2' elif n == 2: return 'π' elif n % 2 == 0: return '{0}π'.format(n / 2) else: return '{0}π/2'.format(n) class MplQuantityConverter(units.ConversionInterface): def __init__(self): if u.Quantity not in units.registry: units.registry[u.Quantity] = self self._remove = True else: self._remove = False @staticmethod def axisinfo(unit, axis): if unit == u.radian: return units.AxisInfo( majloc=ticker.MultipleLocator(base=np.pi/2), majfmt=ticker.FuncFormatter(rad_fn), label=unit.to_string(), ) elif unit == u.degree: return units.AxisInfo( majloc=ticker.AutoLocator(), majfmt=ticker.FormatStrFormatter('%i°'), label=unit.to_string(), ) elif unit is not None: return units.AxisInfo(label=unit.to_string(format)) return None @staticmethod def convert(val, unit, axis): if isinstance(val, u.Quantity): return val.to_value(unit) else: return val @staticmethod def default_units(x, axis): if hasattr(x, 'unit'): return x.unit return None def __enter__(self): return self def __exit__(self, type, value, tb): if self._remove: del units.registry[u.Quantity] return MplQuantityConverter()
b0abdc7bd893ff5f0027ebc04a7c69251f3b874e8d97960398add4ba110763b9
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module contains dictionaries that can be used to set a matplotlib # plotting style. It is no longer documented/recommended as of Astropy v3.0 # but is kept here for backward-compatibility. from ..utils import minversion # This returns False if matplotlib cannot be imported MATPLOTLIB_GE_1_5 = minversion('matplotlib', '1.5') __all__ = ['astropy_mpl_style_1', 'astropy_mpl_style'] # Version 1 astropy plotting style for matplotlib astropy_mpl_style_1 = { # Lines 'lines.linewidth': 1.7, 'lines.antialiased': True, # Patches 'patch.linewidth': 1.0, 'patch.facecolor': '#348ABD', 'patch.edgecolor': '#CCCCCC', 'patch.antialiased': True, # Images 'image.cmap': 'gist_heat', 'image.origin': 'upper', # Font 'font.size': 12.0, # Axes 'axes.facecolor': '#FFFFFF', 'axes.edgecolor': '#AAAAAA', 'axes.linewidth': 1.0, 'axes.grid': True, 'axes.titlesize': 'x-large', 'axes.labelsize': 'large', 'axes.labelcolor': 'k', 'axes.axisbelow': True, # Ticks 'xtick.major.size': 0, 'xtick.minor.size': 0, 'xtick.major.pad': 6, 'xtick.minor.pad': 6, 'xtick.color': '#565656', 'xtick.direction': 'in', 'ytick.major.size': 0, 'ytick.minor.size': 0, 'ytick.major.pad': 6, 'ytick.minor.pad': 6, 'ytick.color': '#565656', 'ytick.direction': 'in', # Legend 'legend.fancybox': True, 'legend.loc': 'best', # Figure 'figure.figsize': [8, 6], 'figure.facecolor': '1.0', 'figure.edgecolor': '0.50', 'figure.subplot.hspace': 0.5, # Other 'savefig.dpi': 72, } color_cycle = ['#348ABD', # blue '#7A68A6', # purple '#A60628', # red '#467821', # green '#CF4457', # pink '#188487', # turquoise '#E24A33'] # orange if MATPLOTLIB_GE_1_5: # This is a dependency of matplotlib, so should be present. from cycler import cycler astropy_mpl_style_1['axes.prop_cycle'] = cycler('color', color_cycle) else: astropy_mpl_style_1['axes.color_cycle'] = color_cycle astropy_mpl_style = astropy_mpl_style_1 """The most recent version of the astropy plotting style."""
0abfe19ddf39a968ebbbe3cdf511b78225808bfa3da39354da2c59731f05e534
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from inspect import signature from ..stats import histogram __all__ = ['hist'] def hist(x, bins=10, ax=None, **kwargs): """Enhanced histogram function This is a histogram function that enables the use of more sophisticated algorithms for determining bins. Aside from the ``bins`` argument allowing a string specified how bins are computed, the parameters are the same as pylab.hist(). This function was ported from astroML: http://astroML.org/ Parameters ---------- x : array_like array of data to be histogrammed bins : int or list or str (optional) If bins is a string, then it must be one of: - 'blocks' : use bayesian blocks for dynamic bin widths - 'knuth' : use Knuth's rule to determine bins - 'scott' : use Scott's rule to determine bins - 'freedman' : use the Freedman-diaconis rule to determine bins ax : Axes instance (optional) specify the Axes on which to draw the histogram. If not specified, then the current active axes will be used. **kwargs : other keyword arguments are described in ``plt.hist()``. Notes ----- Return values are the same as for ``plt.hist()`` See Also -------- astropy.stats.histogram """ # arguments of np.histogram should be passed to astropy.stats.histogram arglist = list(signature(np.histogram).parameters.keys())[1:] np_hist_kwds = dict((key, kwargs[key]) for key in arglist if key in kwargs) hist, bins = histogram(x, bins, **np_hist_kwds) if ax is None: # optional dependency; only import if strictly needed. import matplotlib.pyplot as plt ax = plt.gca() return ax.hist(x, bins, **kwargs)
6b6965debc48a24995e759e834954177a67be52af0259c37fe4cd51c3626581f
# Licensed under a 3-clause BSD style license - see LICENSE.rst __all__ = ['BaseTransform', 'CompositeTransform'] class BaseTransform: """ A transformation object. This is used to construct transformations such as scaling, stretching, and so on. """ def __add__(self, other): return CompositeTransform(other, self) class CompositeTransform(BaseTransform): """ A combination of two transforms. Parameters ---------- transform_1 : :class:`astropy.visualization.BaseTransform` The first transform to apply. transform_2 : :class:`astropy.visualization.BaseTransform` The second transform to apply. """ def __init__(self, transform_1, transform_2): super().__init__() self.transform_1 = transform_1 self.transform_2 = transform_2 def __call__(self, values, clip=True): return self.transform_2(self.transform_1(values, clip=clip), clip=clip) @property def inverse(self): return CompositeTransform(self.transform_2.inverse, self.transform_1.inverse)
1171f796d0900a9059332b5be21dfc91794d138d510f32b2b0f8d0a759131c52
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Classes that deal with stretching, i.e. mapping a range of [0:1] values onto another set of [0:1] values with a transformation """ import numpy as np from ..utils.misc import InheritDocstrings from .transform import BaseTransform __all__ = ["BaseStretch", "LinearStretch", "SqrtStretch", "PowerStretch", "PowerDistStretch", "SquaredStretch", "LogStretch", "AsinhStretch", "SinhStretch", "HistEqStretch", "ContrastBiasStretch"] def _logn(n, x, out=None): """Calculate the log base n of x.""" # We define this because numpy.lib.scimath.logn doesn't support out= if out is None: return np.log(x) / np.log(n) else: np.log(x, out=out) np.true_divide(out, np.log(n), out=out) return out def _prepare(values, clip=True, out=None): """ Prepare the data by optionally clipping and copying, and return the array that should be subsequently used for in-place calculations. """ if clip: return np.clip(values, 0., 1., out=out) else: if out is None: return np.array(values, copy=True) else: out[:] = np.asarray(values) return out class BaseStretch(BaseTransform, metaclass=InheritDocstrings): """ Base class for the stretch classes, which, when called with an array of values in the range [0:1], return an transformed array of values, also in the range [0:1]. """ def __call__(self, values, clip=True, out=None): """ Transform values using this stretch. Parameters ---------- values : array-like The input values, which should already be normalized to the [0:1] range. clip : bool, optional If `True` (default), values outside the [0:1] range are clipped to the [0:1] range. out : `~numpy.ndarray`, optional If specified, the output values will be placed in this array (typically used for in-place calculations). Returns ------- result : `~numpy.ndarray` The transformed values. """ @property def inverse(self): """A stretch object that performs the inverse operation.""" class LinearStretch(BaseStretch): """ A linear stretch. The stretch is given by: .. math:: y = x """ def __call__(self, values, clip=True, out=None): return _prepare(values, clip=clip, out=out) @property def inverse(self): """A stretch object that performs the inverse operation.""" return LinearStretch() class SqrtStretch(BaseStretch): r""" A square root stretch. The stretch is given by: .. math:: y = \sqrt{x} """ def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.sqrt(values, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return PowerStretch(2) class PowerStretch(BaseStretch): r""" A power stretch. The stretch is given by: .. math:: y = x^a Parameters ---------- a : float The power index (see the above formula). """ def __init__(self, a): super().__init__() self.power = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.power(values, self.power, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return PowerStretch(1. / self.power) class PowerDistStretch(BaseStretch): r""" An alternative power stretch. The stretch is given by: .. math:: y = \frac{a^x - 1}{a - 1} Parameters ---------- a : float, optional The ``a`` parameter used in the above formula. Default is 1000. ``a`` cannot be set to 1. """ def __init__(self, a=1000.0): if a == 1: # singularity raise ValueError("a cannot be set to 1") super().__init__() self.exp = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.power(self.exp, values, out=values) np.subtract(values, 1, out=values) np.true_divide(values, self.exp - 1.0, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return InvertedPowerDistStretch(a=self.exp) class InvertedPowerDistStretch(BaseStretch): r""" Inverse transformation for `~astropy.image.scaling.PowerDistStretch`. The stretch is given by: .. math:: y = \frac{\log(y (a-1) + 1)}{\log a} Parameters ---------- a : float, optional The ``a`` parameter used in the above formula. Default is 1000. ``a`` cannot be set to 1. """ def __init__(self, a=1000.0): if a == 1: # singularity raise ValueError("a cannot be set to 1") super().__init__() self.exp = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.multiply(values, self.exp - 1.0, out=values) np.add(values, 1, out=values) _logn(self.exp, values, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return PowerDistStretch(a=self.exp) class SquaredStretch(PowerStretch): r""" A convenience class for a power stretch of 2. The stretch is given by: .. math:: y = x^2 """ def __init__(self): super().__init__(2) @property def inverse(self): """A stretch object that performs the inverse operation.""" return SqrtStretch() class LogStretch(BaseStretch): r""" A log stretch. The stretch is given by: .. math:: y = \frac{\log{(a x + 1)}}{\log{(a + 1)}}. Parameters ---------- a : float The ``a`` parameter used in the above formula. Default is 1000. """ def __init__(self, a=1000.0): super().__init__() self.exp = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.multiply(values, self.exp, out=values) np.add(values, 1., out=values) np.log(values, out=values) np.true_divide(values, np.log(self.exp + 1.), out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return InvertedLogStretch(self.exp) class InvertedLogStretch(BaseStretch): r""" Inverse transformation for `~astropy.image.scaling.LogStretch`. The stretch is given by: .. math:: y = \frac{e^{y} (a + 1) -1}{a} Parameters ---------- a : float, optional The ``a`` parameter used in the above formula. Default is 1000. """ def __init__(self, a): super().__init__() self.exp = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.multiply(values, np.log(self.exp + 1.), out=values) np.exp(values, out=values) np.subtract(values, 1., out=values) np.true_divide(values, self.exp, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return LogStretch(self.exp) class AsinhStretch(BaseStretch): r""" An asinh stretch. The stretch is given by: .. math:: y = \frac{{\rm asinh}(x / a)}{{\rm asinh}(1 / a)}. Parameters ---------- a : float, optional The ``a`` parameter used in the above formula. The value of this parameter is where the asinh curve transitions from linear to logarithmic behavior, expressed as a fraction of the normalized image. Must be in the range between 0 and 1. Default is 0.1 """ def __init__(self, a=0.1): super().__init__() self.a = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.true_divide(values, self.a, out=values) np.arcsinh(values, out=values) np.true_divide(values, np.arcsinh(1. / self.a), out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return SinhStretch(a=1. / np.arcsinh(1. / self.a)) class SinhStretch(BaseStretch): r""" A sinh stretch. The stretch is given by: .. math:: y = \frac{{\rm sinh}(x / a)}{{\rm sinh}(1 / a)} Parameters ---------- a : float, optional The ``a`` parameter used in the above formula. Default is 1/3. """ def __init__(self, a=1./3.): super().__init__() self.a = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.true_divide(values, self.a, out=values) np.sinh(values, out=values) np.true_divide(values, np.sinh(1. / self.a), out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return AsinhStretch(a=1. / np.sinh(1. / self.a)) class HistEqStretch(BaseStretch): """ A histogram equalization stretch. Parameters ---------- data : array-like The data defining the equalization. values : array-like, optional The input image values, which should already be normalized to the [0:1] range. """ def __init__(self, data, values=None): # Assume data is not necessarily normalized at this point self.data = np.sort(data.ravel()) vmin = self.data.min() vmax = self.data.max() self.data = (self.data - vmin) / (vmax - vmin) # Compute relative position of each pixel if values is None: self.values = np.linspace(0., 1., len(self.data)) else: self.values = values def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) values[:] = np.interp(values, self.data, self.values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return InvertedHistEqStretch(self.data, values=self.values) class InvertedHistEqStretch(BaseStretch): """ Inverse transformation for `~astropy.image.scaling.HistEqStretch`. Parameters ---------- data : array-like The data defining the equalization. values : array-like, optional The input image values, which should already be normalized to the [0:1] range. """ def __init__(self, data, values=None): self.data = data if values is None: self.values = np.linspace(0., 1., len(self.data)) else: self.values = values def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) values[:] = np.interp(values, self.values, self.data) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return HistEqStretch(self.data, values=self.values) class ContrastBiasStretch(BaseStretch): r""" A stretch that takes into account contrast and bias. The stretch is given by: .. math:: y = (x - {\rm bias}) * {\rm contrast} + 0.5 and the output values are clipped to the [0:1] range. Parameters ---------- contrast : float The contrast parameter (see the above formula). bias : float The bias parameter (see the above formula). """ def __init__(self, contrast, bias): super().__init__() self.contrast = contrast self.bias = bias def __call__(self, values, clip=True, out=None): # As a special case here, we only clip *after* the # transformation since it does not map [0:1] to [0:1] values = _prepare(values, clip=False, out=out) np.subtract(values, self.bias, out=values) np.multiply(values, self.contrast, out=values) np.add(values, 0.5, out=values) if clip: np.clip(values, 0, 1, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return InvertedContrastBiasStretch(self.contrast, self.bias) class InvertedContrastBiasStretch(BaseStretch): """ Inverse transformation for ContrastBiasStretch. Parameters ---------- contrast : float The contrast parameter (see `~astropy.visualization.ConstrastBiasStretch). bias : float The bias parameter (see `~astropy.visualization.ConstrastBiasStretch). """ def __init__(self, contrast, bias): super().__init__() self.contrast = contrast self.bias = bias def __call__(self, values, clip=True, out=None): # As a special case here, we only clip *after* the # transformation since it does not map [0:1] to [0:1] values = _prepare(values, clip=False, out=out) np.subtract(values, 0.5, out=values) np.true_divide(values, self.contrast, out=values) np.add(values, self.bias, out=values) if clip: np.clip(values, 0, 1, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return ContrastBiasStretch(self.contrast, self.bias)
fb0c2f215cb928a11ea34cc823a7593256d34509ed0f4c610f4cca5f3d90b669
# Licensed under a 3-clause BSD style license - see LICENSE.rst from copy import deepcopy from inspect import signature from itertools import islice import warnings from ..utils import wraps from ..utils.exceptions import AstropyUserWarning from .nddata import NDData __all__ = ['support_nddata'] # All supported properties are optional except "data" which is mandatory! SUPPORTED_PROPERTIES = ['data', 'uncertainty', 'mask', 'meta', 'unit', 'wcs', 'flags'] def support_nddata(_func=None, accepts=NDData, repack=False, returns=None, keeps=None, **attribute_argument_mapping): """Decorator to wrap functions that could accept an NDData instance with its properties passed as function arguments. Parameters ---------- _func : callable, None, optional The function to decorate or ``None`` if used as factory. The first positional argument should be ``data`` and take a numpy array. It is possible to overwrite the name, see ``attribute_argument_mapping`` argument. Default is ``None``. accepts : cls, optional The class or subclass of ``NDData`` that should be unpacked before calling the function. Default is ``NDData`` repack : bool, optional Should be ``True`` if the return should be converted to the input class again after the wrapped function call. Default is ``False``. .. note:: Must be ``True`` if either one of ``returns`` or ``keeps`` is specified. returns : iterable, None, optional An iterable containing strings which returned value should be set on the class. For example if a function returns data and mask, this should be ``['data', 'mask']``. If ``None`` assume the function only returns one argument: ``'data'``. Default is ``None``. .. note:: Must be ``None`` if ``repack=False``. keeps : iterable. None, optional An iterable containing strings that indicate which values should be copied from the original input to the returned class. If ``None`` assume that no attributes are copied. Default is ``None``. .. note:: Must be ``None`` if ``repack=False``. attribute_argument_mapping : Keyword parameters that optionally indicate which function argument should be interpreted as which attribute on the input. By default it assumes the function takes a ``data`` argument as first argument, but if the first argument is called ``input`` one should pass ``support_nddata(..., data='input')`` to the function. Returns ------- decorator_factory or decorated_function : callable If ``_func=None`` this returns a decorator, otherwise it returns the decorated ``_func``. Notes ----- If properties of ``NDData`` are set but have no corresponding function argument a Warning is shown. If a property is set of the ``NDData`` are set and an explicit argument is given, the explicitly given argument is used and a Warning is shown. The supported properties are: - ``mask`` - ``unit`` - ``wcs`` - ``meta`` - ``uncertainty`` - ``flags`` Examples -------- This function takes a Numpy array for the data, and some WCS information with the ``wcs`` keyword argument:: def downsample(data, wcs=None): # downsample data and optionally WCS here pass However, you might have an NDData instance that has the ``wcs`` property set and you would like to be able to call the function with ``downsample(my_nddata)`` and have the WCS information, if present, automatically be passed to the ``wcs`` keyword argument. This decorator can be used to make this possible:: @support_nddata def downsample(data, wcs=None): # downsample data and optionally WCS here pass This function can now either be called as before, specifying the data and WCS separately, or an NDData instance can be passed to the ``data`` argument. """ if (returns is not None or keeps is not None) and not repack: raise ValueError('returns or keeps should only be set if repack=True.') elif returns is None and repack: raise ValueError('returns should be set if repack=True.') else: # Use empty lists for returns and keeps so we don't need to check # if any of those is None later on. if returns is None: returns = [] if keeps is None: keeps = [] # Short version to avoid the long variable name later. attr_arg_map = attribute_argument_mapping if any(keep in returns for keep in keeps): raise ValueError("cannot specify the same attribute in `returns` and " "`keeps`.") all_returns = returns + keeps def support_nddata_decorator(func): # Find out args and kwargs func_args, func_kwargs = [], [] sig = signature(func).parameters for param_name, param in sig.items(): if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD): raise ValueError("func may not have *args or **kwargs.") try: if param.default == param.empty: func_args.append(param_name) else: func_kwargs.append(param_name) # The comparison to param.empty may fail if the default is a # numpy array or something similar. So if the comparison fails then # it's quite obvious that there was a default and it should be # appended to the "func_kwargs". except ValueError as exc: if ('The truth value of an array with more than one element ' 'is ambiguous.') in str(exc): func_kwargs.append(param_name) else: raise # First argument should be data if not func_args or func_args[0] != attr_arg_map.get('data', 'data'): raise ValueError("Can only wrap functions whose first positional " "argument is `{0}`" "".format(attr_arg_map.get('data', 'data'))) @wraps(func) def wrapper(data, *args, **kwargs): unpack = isinstance(data, accepts) input_data = data ignored = [] if not unpack and isinstance(data, NDData): raise TypeError("Only NDData sub-classes that inherit from {0}" " can be used by this function" "".format(accepts.__name__)) # If data is an NDData instance, we can try and find properties # that can be passed as kwargs. if unpack: # We loop over a list of pre-defined properties for prop in islice(SUPPORTED_PROPERTIES, 1, None): # We only need to do something if the property exists on # the NDData object try: value = getattr(data, prop) except AttributeError: continue # Skip if the property exists but is None or empty. if prop == 'meta' and not value: continue elif value is None: continue # Warn if the property is set but not used by the function. propmatch = attr_arg_map.get(prop, prop) if propmatch not in func_kwargs: ignored.append(prop) continue # Check if the property was explicitly given and issue a # Warning if it is. if propmatch in kwargs: # If it's in the func_args it's trivial but if it was # in the func_kwargs we need to compare it to the # default. # Comparison to the default is done by comparing their # identity, this works because defaults in function # signatures are only created once and always reference # the same item. # FIXME: Python interns some values, for example the # integers from -5 to 255 (any maybe some other types # as well). In that case the default is # indistinguishable from an explicitly passed kwarg # and it won't notice that and use the attribute of the # NDData. if (propmatch in func_args or (propmatch in func_kwargs and (kwargs[propmatch] is not sig[propmatch].default))): warnings.warn( "Property {0} has been passed explicitly and " "as an NDData property{1}, using explicitly " "specified value" "".format(propmatch, '' if prop == propmatch else ' ' + prop), AstropyUserWarning) continue # Otherwise use the property as input for the function. kwargs[propmatch] = value # Finally, replace data by the data attribute data = data.data if ignored: warnings.warn("The following attributes were set on the " "data object, but will be ignored by the " "function: " + ", ".join(ignored), AstropyUserWarning) result = func(data, *args, **kwargs) if unpack and repack: # If there are multiple required returned arguments make sure # the result is a tuple (because we don't want to unpack # numpy arrays or compare their length, never!) and has the # same length. if len(returns) > 1: if (not isinstance(result, tuple) or len(returns) != len(result)): raise ValueError("Function did not return the " "expected number of arguments.") elif len(returns) == 1: result = [result] if keeps is not None: for keep in keeps: result.append(deepcopy(getattr(input_data, keep))) resultdata = result[all_returns.index('data')] resultkwargs = {ret: res for ret, res in zip(all_returns, result) if ret != 'data'} return input_data.__class__(resultdata, **resultkwargs) else: return result return wrapper # If _func is set, this means that the decorator was used without # parameters so we have to return the result of the # support_nddata_decorator decorator rather than the decorator itself if _func is not None: return support_nddata_decorator(_func) else: return support_nddata_decorator
7e6f0186b4d61278a1a70ab055b5827f5ef23896c7e376434efce07293ab5acd
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module implements the base NDDataBase class. from abc import ABCMeta, abstractmethod __all__ = ['NDDataBase'] class NDDataBase(metaclass=ABCMeta): """Base metaclass that defines the interface for N-dimensional datasets with associated meta information used in ``astropy``. All properties and ``__init__`` have to be overridden in subclasses. See `NDData` for a subclass that defines this interface on `numpy.ndarray`-like ``data``. """ @abstractmethod def __init__(self): pass @property @abstractmethod def data(self): """The stored dataset. """ pass @property @abstractmethod def mask(self): """Mask for the dataset. Masks should follow the ``numpy`` convention that **valid** data points are marked by ``False`` and **invalid** ones with ``True``. """ return None @property @abstractmethod def unit(self): """Unit for the dataset. """ return None @property @abstractmethod def wcs(self): """World coordinate system (WCS) for the dataset. """ return None @property @abstractmethod def meta(self): """Additional meta information about the dataset. Should be `dict`-like. """ return None @property @abstractmethod def uncertainty(self): """Uncertainty in the dataset. Should have an attribute ``uncertainty_type`` that defines what kind of uncertainty is stored, such as ``"std"`` for standard deviation or ``"var"`` for variance. """ return None
b7733432be3aa6d7f548514e6a43889f3a7cba7f64c40a88390f60dcbc105a7b
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from abc import ABCMeta, abstractmethod from copy import deepcopy import weakref # from ..utils.compat import ignored from .. import log from ..units import Unit, Quantity __all__ = ['MissingDataAssociationException', 'IncompatibleUncertaintiesException', 'NDUncertainty', 'StdDevUncertainty', 'UnknownUncertainty'] class IncompatibleUncertaintiesException(Exception): """This exception should be used to indicate cases in which uncertainties with two different classes can not be propagated. """ class MissingDataAssociationException(Exception): """This exception should be used to indicate that an uncertainty instance has not been associated with a parent `~astropy.nddata.NDData` object. """ class NDUncertainty(metaclass=ABCMeta): """This is the metaclass for uncertainty classes used with `NDData`. Parameters ---------- array : any type, optional The array or value (the parameter name is due to historical reasons) of the uncertainty. `numpy.ndarray`, `~astropy.units.Quantity` or `NDUncertainty` subclasses are recommended. If the `array` is `list`-like or `numpy.ndarray`-like it will be cast to a plain `numpy.ndarray`. Default is ``None``. unit : `~astropy.units.Unit` or str, optional Unit for the uncertainty ``array``. Strings that can be converted to a `~astropy.units.Unit` are allowed. Default is ``None``. copy : `bool`, optional Indicates whether to save the `array` as a copy. ``True`` copies it before saving, while ``False`` tries to save every parameter as reference. Note however that it is not always possible to save the input as reference. Default is ``True``. Raises ------ IncompatibleUncertaintiesException If given another `NDUncertainty`-like class as ``array`` if their ``uncertainty_type`` is different. """ def __init__(self, array=None, copy=True, unit=None): if isinstance(array, NDUncertainty): # Given an NDUncertainty class or subclass check that the type # is the same. if array.uncertainty_type != self.uncertainty_type: raise IncompatibleUncertaintiesException # Check if two units are given and take the explicit one then. if (unit is not None and unit != array._unit): # TODO : Clarify it (see NDData.init for same problem)? log.info("overwriting Uncertainty's current " "unit with specified unit.") elif array._unit is not None: unit = array.unit array = array.array elif isinstance(array, Quantity): # Check if two units are given and take the explicit one then. if (unit is not None and array.unit is not None and unit != array.unit): log.info("overwriting Quantity's current " "unit with specified unit.") elif array.unit is not None: unit = array.unit array = array.value if unit is None: self._unit = None else: self._unit = Unit(unit) if copy: array = deepcopy(array) unit = deepcopy(unit) self.array = array self.parent_nddata = None # no associated NDData - until it is set! @property @abstractmethod def uncertainty_type(self): """`str` : Short description of the type of uncertainty. Defined as abstract property so subclasses *have* to override this. """ return None @property def supports_correlated(self): """`bool` : Supports uncertainty propagation with correlated \ uncertainties? .. versionadded:: 1.2 """ return False @property def array(self): """`numpy.ndarray` : the uncertainty's value. """ return self._array @array.setter def array(self, value): if isinstance(value, (list, np.ndarray)): value = np.array(value, subok=False, copy=False) self._array = value @property def unit(self): """`~astropy.units.Unit` : The unit of the uncertainty, if any. Even though it is not enforced the unit should be convertible to the ``parent_nddata`` unit. Otherwise uncertainty propagation might give wrong results. If the unit is not set the unit of the parent will be returned. """ if self._unit is None: if (self._parent_nddata is None or self.parent_nddata.unit is None): return None else: return self.parent_nddata.unit return self._unit @property def parent_nddata(self): """`NDData` : reference to `NDData` instance with this uncertainty. In case the reference is not set uncertainty propagation will not be possible since propagation might need the uncertain data besides the uncertainty. """ message = "uncertainty is not associated with an NDData object" try: if self._parent_nddata is None: raise MissingDataAssociationException(message) else: # The NDData is saved as weak reference so we must call it # to get the object the reference points to. if isinstance(self._parent_nddata, weakref.ref): return self._parent_nddata() else: log.info("parent_nddata should be a weakref to an NDData " "object.") return self._parent_nddata except AttributeError: raise MissingDataAssociationException(message) @parent_nddata.setter def parent_nddata(self, value): if value is not None and not isinstance(value, weakref.ref): # Save a weak reference on the uncertainty that points to this # instance of NDData. Direct references should NOT be used: # https://github.com/astropy/astropy/pull/4799#discussion_r61236832 value = weakref.ref(value) self._parent_nddata = value def __repr__(self): prefix = self.__class__.__name__ + '(' try: body = np.array2string(self.array, separator=', ', prefix=prefix) except AttributeError: # In case it wasn't possible to use array2string body = str(self.array) return ''.join([prefix, body, ')']) def __getitem__(self, item): """Normal slicing on the array, keep the unit and return a reference. """ return self.__class__(self.array[item], unit=self.unit, copy=False) def propagate(self, operation, other_nddata, result_data, correlation): """Calculate the resulting uncertainty given an operation on the data. .. versionadded:: 1.2 Parameters ---------- operation : callable The operation that is performed on the `NDData`. Supported are `numpy.add`, `numpy.subtract`, `numpy.multiply` and `numpy.true_divide` (or `numpy.divide`). other_nddata : `NDData` instance The second operand in the arithmetic operation. result_data : `~astropy.units.Quantity` or `numpy.ndarray` The result of the arithmetic operations on the data. correlation : `numpy.ndarray` or number The correlation (rho) is defined between the uncertainties in sigma_AB = sigma_A * sigma_B * rho. A value of ``0`` means uncorrelated operands. Returns ------- resulting_uncertainty : `NDUncertainty` instance Another instance of the same `NDUncertainty` subclass containing the uncertainty of the result. Raises ------ ValueError If the ``operation`` is not supported or if correlation is not zero but the subclass does not support correlated uncertainties. Notes ----- First this method checks if a correlation is given and the subclass implements propagation with correlated uncertainties. Then the second uncertainty is converted (or an Exception is raised) to the same class in order to do the propagation. Then the appropriate propagation method is invoked and the result is returned. """ # Check if the subclass supports correlation if not self.supports_correlated: if isinstance(correlation, np.ndarray) or correlation != 0: raise ValueError("{0} does not support uncertainty propagation" " with correlation." "".format(self.__class__.__name__)) # Get the other uncertainty (and convert it to a matching one) other_uncert = self._convert_uncertainty(other_nddata.uncertainty) if operation.__name__ == 'add': result = self._propagate_add(other_uncert, result_data, correlation) elif operation.__name__ == 'subtract': result = self._propagate_subtract(other_uncert, result_data, correlation) elif operation.__name__ == 'multiply': result = self._propagate_multiply(other_uncert, result_data, correlation) elif operation.__name__ in ['true_divide', 'divide']: result = self._propagate_divide(other_uncert, result_data, correlation) else: raise ValueError('unsupported operation') return self.__class__(result, copy=False) def _convert_uncertainty(self, other_uncert): """Checks if the uncertainties are compatible for propagation. Checks if the other uncertainty is `NDUncertainty`-like and if so verify that the uncertainty_type is equal. If the latter is not the case try returning ``self.__class__(other_uncert)``. Parameters ---------- other_uncert : `NDUncertainty` subclass The other uncertainty. Returns ------- other_uncert : `NDUncertainty` subclass but converted to a compatible `NDUncertainty` subclass if possible and necessary. Raises ------ IncompatibleUncertaintiesException: If the other uncertainty cannot be converted to a compatible `NDUncertainty` subclass. """ if isinstance(other_uncert, NDUncertainty): if self.uncertainty_type == other_uncert.uncertainty_type: return other_uncert else: return self.__class__(other_uncert) else: raise IncompatibleUncertaintiesException @abstractmethod def _propagate_add(self, other_uncert, result_data, correlation): return None @abstractmethod def _propagate_subtract(self, other_uncert, result_data, correlation): return None @abstractmethod def _propagate_multiply(self, other_uncert, result_data, correlation): return None @abstractmethod def _propagate_divide(self, other_uncert, result_data, correlation): return None class UnknownUncertainty(NDUncertainty): """This class implements any unknown uncertainty type. The main purpose of having an unknown uncertainty class is to prevent uncertainty propagation. Parameters ---------- args, kwargs : see `NDUncertainty` """ @property def supports_correlated(self): """`False` : Uncertainty propagation is *not* possible for this class. """ return False @property def uncertainty_type(self): """``"unknown"`` : `UnknownUncertainty` implements any unknown \ uncertainty type. """ return 'unknown' def _convert_uncertainty(self, other_uncert): """Raise an Exception because unknown uncertainty types cannot implement propagation. """ msg = "Uncertainties of unknown type cannot be propagated." raise IncompatibleUncertaintiesException(msg) def _propagate_add(self, other_uncert, result_data, correlation): """Not possible for unknown uncertainty types. """ return None def _propagate_subtract(self, other_uncert, result_data, correlation): return None def _propagate_multiply(self, other_uncert, result_data, correlation): return None def _propagate_divide(self, other_uncert, result_data, correlation): return None class StdDevUncertainty(NDUncertainty): """Standard deviation uncertainty assuming first order gaussian error propagation. This class implements uncertainty propagation for ``addition``, ``subtraction``, ``multiplication`` and ``division`` with other instances of `StdDevUncertainty`. The class can handle if the uncertainty has a unit that differs from (but is convertible to) the parents `NDData` unit. The unit of the resulting uncertainty will have the same unit as the resulting data. Also support for correlation is possible but requires the correlation as input. It cannot handle correlation determination itself. Parameters ---------- args, kwargs : see `NDUncertainty` Examples -------- `StdDevUncertainty` should always be associated with an `NDData`-like instance, either by creating it during initialization:: >>> from astropy.nddata import NDData, StdDevUncertainty >>> ndd = NDData([1,2,3], ... uncertainty=StdDevUncertainty([0.1, 0.1, 0.1])) >>> ndd.uncertainty # doctest: +FLOAT_CMP StdDevUncertainty([0.1, 0.1, 0.1]) or by setting it manually on the `NDData` instance:: >>> ndd.uncertainty = StdDevUncertainty([0.2], unit='m', copy=True) >>> ndd.uncertainty # doctest: +FLOAT_CMP StdDevUncertainty([0.2]) the uncertainty ``array`` can also be set directly:: >>> ndd.uncertainty.array = 2 >>> ndd.uncertainty StdDevUncertainty(2) .. note:: The unit will not be displayed. """ @property def supports_correlated(self): """`True` : `StdDevUncertainty` allows to propagate correlated \ uncertainties. ``correlation`` must be given, this class does not implement computing it by itself. """ return True @property def uncertainty_type(self): """``"std"`` : `StdDevUncertainty` implements standard deviation. """ return 'std' def _convert_uncertainty(self, other_uncert): if isinstance(other_uncert, StdDevUncertainty): return other_uncert else: raise IncompatibleUncertaintiesException def _propagate_add(self, other_uncert, result_data, correlation): if self.array is None: # Formula: sigma = dB if other_uncert.unit is not None and ( result_data.unit != other_uncert.unit): # If the other uncertainty has a unit and this unit differs # from the unit of the result convert it to the results unit return (other_uncert.array * other_uncert.unit).to( result_data.unit).value else: # Copy the result because _propagate will not copy it but for # arithmetic operations users will expect copies. return deepcopy(other_uncert.array) elif other_uncert.array is None: # Formula: sigma = dA if self.unit is not None and self.unit != self.parent_nddata.unit: # If the uncertainty has a different unit than the result we # need to convert it to the results unit. return self.unit.to(result_data.unit, self.array) else: # Copy the result because _propagate will not copy it but for # arithmetic operations users will expect copies. return deepcopy(self.array) else: # Formula: sigma = sqrt(dA**2 + dB**2 + 2*cor*dA*dB) # Calculate: dA (this) and dB (other) if self.unit != other_uncert.unit: # In case the two uncertainties (or data) have different units # we need to use quantity operations. The case where only one # has a unit and the other doesn't is not possible with # addition and would have raised an exception in the data # computation this = self.array * self.unit other = other_uncert.array * other_uncert.unit else: # Since both units are the same or None we can just use # numpy operations this = self.array other = other_uncert.array # Determine the result depending on the correlation if isinstance(correlation, np.ndarray) or correlation != 0: corr = 2 * correlation * this * other result = np.sqrt(this**2 + other**2 + corr) else: result = np.sqrt(this**2 + other**2) if isinstance(result, Quantity): # In case we worked with quantities we need to return the # uncertainty that has the same unit as the resulting data. # Note that this call is fast if the units are the same. return result.to_value(result_data.unit) else: return result def _propagate_subtract(self, other_uncert, result_data, correlation): # Since the formulas are equivalent to addition you should look at the # explanations provided in _propagate_add if self.array is None: if other_uncert.unit is not None and ( result_data.unit != other_uncert.unit): return (other_uncert.array * other_uncert.unit).to( result_data.unit).value else: return deepcopy(other_uncert.array) elif other_uncert.array is None: if self.unit is not None and self.unit != self.parent_nddata.unit: return self.unit.to(result_data.unit, self.array) else: return deepcopy(self.array) else: # Formula: sigma = sqrt(dA**2 + dB**2 - 2*cor*dA*dB) if self.unit != other_uncert.unit: this = self.array * self.unit other = other_uncert.array * other_uncert.unit else: this = self.array other = other_uncert.array if isinstance(correlation, np.ndarray) or correlation != 0: corr = 2 * correlation * this * other # The only difference to addition is that the correlation is # subtracted. result = np.sqrt(this**2 + other**2 - corr) else: result = np.sqrt(this**2 + other**2) if isinstance(result, Quantity): return result.to_value(result_data.unit) else: return result def _propagate_multiply(self, other_uncert, result_data, correlation): # For multiplication we don't need the result as quantity if isinstance(result_data, Quantity): result_data = result_data.value if self.array is None: # Formula: sigma = |A| * dB # We want the result to have the same unit as the parent, so we # only need to convert the unit of the other uncertainty if it is # different from its data's unit. if other_uncert.unit != other_uncert.parent_nddata.unit: other = (other_uncert.array * other_uncert.unit).to( other_uncert.parent_nddata.unit).value else: other = other_uncert.array return np.abs(self.parent_nddata.data * other) elif other_uncert.array is None: # Formula: sigma = dA * |B| # Just the reversed case if self.unit != self.parent_nddata.unit: this = (self.array * self.unit).to( self.parent_nddata.unit).value else: this = self.array return np.abs(other_uncert.parent_nddata.data * this) else: # Formula: sigma = |AB|*sqrt((dA/A)**2+(dB/B)**2+2*dA/A*dB/B*cor) # This formula is not very handy since it generates NaNs for every # zero in A and B. So we rewrite it: # Formula: sigma = sqrt((dA*B)**2 + (dB*A)**2 + (2 * cor * ABdAdB)) # Calculate: dA * B (left) if self.unit != self.parent_nddata.unit: # To get the unit right we need to convert the unit of # each uncertainty to the same unit as it's parent left = ((self.array * self.unit).to( self.parent_nddata.unit).value * other_uncert.parent_nddata.data) else: left = self.array * other_uncert.parent_nddata.data # Calculate: dB * A (right) if other_uncert.unit != other_uncert.parent_nddata.unit: right = ((other_uncert.array * other_uncert.unit).to( other_uncert.parent_nddata.unit).value * self.parent_nddata.data) else: right = other_uncert.array * self.parent_nddata.data if isinstance(correlation, np.ndarray) or correlation != 0: corr = (2 * correlation * left * right) return np.sqrt(left**2 + right**2 + corr) else: return np.sqrt(left**2 + right**2) def _propagate_divide(self, other_uncert, result_data, correlation): # For division we don't need the result as quantity if isinstance(result_data, Quantity): result_data = result_data.value if self.array is None: # Formula: sigma = |(A / B) * (dB / B)| # Calculate: dB / B (right) if other_uncert.unit != other_uncert.parent_nddata.unit: # We need (dB / B) to be dimensionless so we convert # (if necessary) dB to the same unit as B right = ((other_uncert.array * other_uncert.unit).to( other_uncert.parent_nddata.unit).value / other_uncert.parent_nddata.data) else: right = (other_uncert.array / other_uncert.parent_nddata.data) return np.abs(result_data * right) elif other_uncert.array is None: # Formula: sigma = dA / |B|. # Calculate: dA if self.unit != self.parent_nddata.unit: # We need to convert dA to the unit of A to have a result that # matches the resulting data's unit. left = (self.array * self.unit).to( self.parent_nddata.unit).value else: left = self.array return np.abs(left / other_uncert.parent_nddata.data) else: # Formula: sigma = |A/B|*sqrt((dA/A)**2+(dB/B)**2-2*dA/A*dB/B*cor) # As with multiplication this formula creates NaNs where A is zero. # So I'll rewrite it again: # => sigma = sqrt((dA/B)**2 + (AdB/B**2)**2 - 2*cor*AdAdB/B**3) # So we need to calculate dA/B in the same units as the result # and the dimensionless dB/B to get a resulting uncertainty with # the same unit as the data. # Calculate: dA/B (left) if self.unit != self.parent_nddata.unit: left = ((self.array * self.unit).to( self.parent_nddata.unit).value / other_uncert.parent_nddata.data) else: left = self.array / other_uncert.parent_nddata.data # Calculate: dB/B (right) if other_uncert.unit != other_uncert.parent_nddata.unit: right = ((other_uncert.array * other_uncert.unit).to( other_uncert.parent_nddata.unit).value / other_uncert.parent_nddata.data) * result_data else: right = (result_data * other_uncert.array / other_uncert.parent_nddata.data) if isinstance(correlation, np.ndarray) or correlation != 0: corr = 2 * correlation * left * right # This differs from multiplication because the correlation # term needs to be subtracted return np.sqrt(left**2 + right**2 - corr) else: return np.sqrt(left**2 + right**2)
4088547764692288bd0f788d383e49af7e88f113750aecb614a8d41157fd519e
# Licensed under a 3-clause BSD style license - see LICENSE.rst from collections import OrderedDict import numpy as np from ..utils.misc import isiterable __all__ = ['FlagCollection'] class FlagCollection(OrderedDict): """ The purpose of this class is to provide a dictionary for containing arrays of flags for the `NDData` class. Flags should be stored in Numpy arrays that have the same dimensions as the parent data, so the `FlagCollection` class adds shape checking to an ordered dictionary class. The `FlagCollection` should be initialized like an `~collections.OrderedDict`, but with the addition of a ``shape=`` keyword argument used to pass the NDData shape. """ def __init__(self, *args, **kwargs): if 'shape' in kwargs: self.shape = kwargs.pop('shape') if not isiterable(self.shape): raise ValueError("FlagCollection shape should be " "an iterable object") else: raise Exception("FlagCollection should be initialized with " "the shape of the data") OrderedDict.__init__(self, *args, **kwargs) def __setitem__(self, item, value, **kwargs): if isinstance(value, np.ndarray): if value.shape == self.shape: OrderedDict.__setitem__(self, item, value, **kwargs) else: raise ValueError("flags array shape {0} does not match data " "shape {1}".format(value.shape, self.shape)) else: raise TypeError("flags should be given as a Numpy array")
c055a75e98e0a7124e60b85bc9dfce1598f4e344a582bd4dd42b4cca744b6d49
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module implements the base NDData class. import numpy as np from copy import deepcopy from .nddata_base import NDDataBase from .nduncertainty import NDUncertainty, UnknownUncertainty from .. import log from ..units import Unit, Quantity from ..utils.metadata import MetaData __all__ = ['NDData'] _meta_doc = """`dict`-like : Additional meta information about the dataset.""" class NDData(NDDataBase): """ A container for `numpy.ndarray`-based datasets, using the `~astropy.nddata.NDDataBase` interface. The key distinction from raw `numpy.ndarray` is the presence of additional metadata such as uncertainty, mask, unit, a coordinate system and/or a dictionary containing further meta information. This class *only* provides a container for *storing* such datasets. For further functionality take a look at the ``See also`` section. Parameters ----------- data : `numpy.ndarray`-like or `NDData`-like The dataset. uncertainty : any type, optional Uncertainty in the dataset. Should have an attribute ``uncertainty_type`` that defines what kind of uncertainty is stored, for example ``"std"`` for standard deviation or ``"var"`` for variance. A metaclass defining such an interface is `NDUncertainty` - but isn't mandatory. If the uncertainty has no such attribute the uncertainty is stored as `UnknownUncertainty`. Defaults to ``None``. mask : any type, optional Mask for the dataset. Masks should follow the ``numpy`` convention that **valid** data points are marked by ``False`` and **invalid** ones with ``True``. Defaults to ``None``. wcs : any type, optional World coordinate system (WCS) for the dataset. Default is ``None``. meta : `dict`-like object, optional Additional meta information about the dataset. If no meta is provided an empty `collections.OrderedDict` is created. Default is ``None``. unit : `~astropy.units.Unit`-like or str, optional Unit for the dataset. Strings that can be converted to a `~astropy.units.Unit` are allowed. Default is ``None``. copy : `bool`, optional Indicates whether to save the arguments as copy. ``True`` copies every attribute before saving it while ``False`` tries to save every parameter as reference. Note however that it is not always possible to save the input as reference. Default is ``False``. .. versionadded:: 1.2 Raises ------ TypeError In case ``data`` or ``meta`` don't meet the restrictions. Notes ----- Each attribute can be accessed through the homonymous instance attribute: ``data`` in a `NDData` object can be accessed through the `data` attribute:: >>> from astropy.nddata import NDData >>> nd = NDData([1,2,3]) >>> nd.data array([1, 2, 3]) Given a conflicting implicit and an explicit parameter during initialization, for example the ``data`` is a `~astropy.units.Quantity` and the unit parameter is not ``None``, then the implicit parameter is replaced (without conversion) by the explicit one and a warning is issued:: >>> import numpy as np >>> import astropy.units as u >>> q = np.array([1,2,3,4]) * u.m >>> nd2 = NDData(q, unit=u.cm) INFO: overwriting Quantity's current unit with specified unit. [astropy.nddata.nddata] >>> nd2.data # doctest: +FLOAT_CMP array([1., 2., 3., 4.]) >>> nd2.unit Unit("cm") See also -------- NDDataRef NDDataArray """ # Instead of a custom property use the MetaData descriptor also used for # Tables. It will check if the meta is dict-like or raise an exception. meta = MetaData(doc=_meta_doc, copy=False) def __init__(self, data, uncertainty=None, mask=None, wcs=None, meta=None, unit=None, copy=False): # Rather pointless since the NDDataBase does not implement any setting # but before the NDDataBase did call the uncertainty # setter. But if anyone wants to alter this behaviour again the call # to the superclass NDDataBase should be in here. super().__init__() # Check if data is any type from which to collect some implicitly # passed parameters. if isinstance(data, NDData): # don't use self.__class__ (issue #4137) # Of course we need to check the data because subclasses with other # init-logic might be passed in here. We could skip these # tests if we compared for self.__class__ but that has other # drawbacks. # Comparing if there is an explicit and an implicit unit parameter. # If that is the case use the explicit one and issue a warning # that there might be a conflict. In case there is no explicit # unit just overwrite the unit parameter with the NDData.unit # and proceed as if that one was given as parameter. Same for the # other parameters. if (unit is not None and data.unit is not None and unit != data.unit): log.info("overwriting NDData's current " "unit with specified unit.") elif data.unit is not None: unit = data.unit if uncertainty is not None and data.uncertainty is not None: log.info("overwriting NDData's current " "uncertainty with specified uncertainty.") elif data.uncertainty is not None: uncertainty = data.uncertainty if mask is not None and data.mask is not None: log.info("overwriting NDData's current " "mask with specified mask.") elif data.mask is not None: mask = data.mask if wcs is not None and data.wcs is not None: log.info("overwriting NDData's current " "wcs with specified wcs.") elif data.wcs is not None: wcs = data.wcs if meta is not None and data.meta is not None: log.info("overwriting NDData's current " "meta with specified meta.") elif data.meta is not None: meta = data.meta data = data.data else: if hasattr(data, 'mask') and hasattr(data, 'data'): # Separating data and mask if mask is not None: log.info("overwriting Masked Objects's current " "mask with specified mask.") else: mask = data.mask # Just save the data for further processing, we could be given # a masked Quantity or something else entirely. Better to check # it first. data = data.data if isinstance(data, Quantity): if unit is not None and unit != data.unit: log.info("overwriting Quantity's current " "unit with specified unit.") else: unit = data.unit data = data.value # Quick check on the parameters if they match the requirements. if (not hasattr(data, 'shape') or not hasattr(data, '__getitem__') or not hasattr(data, '__array__')): # Data doesn't look like a numpy array, try converting it to # one. data = np.array(data, subok=True, copy=False) # Another quick check to see if what we got looks like an array # rather than an object (since numpy will convert a # non-numerical/non-string inputs to an array of objects). if data.dtype == 'O': raise TypeError("could not convert data to numpy array.") if unit is not None: unit = Unit(unit) if copy: # Data might have been copied before but no way of validating # without another variable. data = deepcopy(data) mask = deepcopy(mask) wcs = deepcopy(wcs) meta = deepcopy(meta) uncertainty = deepcopy(uncertainty) # Actually - copying the unit is unnecessary but better safe # than sorry :-) unit = deepcopy(unit) # Store the attributes self._data = data self.mask = mask self._wcs = wcs self.meta = meta # TODO: Make this call the setter sometime self._unit = unit # Call the setter for uncertainty to further check the uncertainty self.uncertainty = uncertainty def __str__(self): return str(self.data) def __repr__(self): prefix = self.__class__.__name__ + '(' body = np.array2string(self.data, separator=', ', prefix=prefix) return ''.join([prefix, body, ')']) @property def data(self): """ `~numpy.ndarray`-like : The stored dataset. """ return self._data @property def mask(self): """ any type : Mask for the dataset, if any. Masks should follow the ``numpy`` convention that valid data points are marked by ``False`` and invalid ones with ``True``. """ return self._mask @mask.setter def mask(self, value): self._mask = value @property def unit(self): """ `~astropy.units.Unit` : Unit for the dataset, if any. """ return self._unit @property def wcs(self): """ any type : A world coordinate system (WCS) for the dataset, if any. """ return self._wcs @property def uncertainty(self): """ any type : Uncertainty in the dataset, if any. Should have an attribute ``uncertainty_type`` that defines what kind of uncertainty is stored, such as ``'std'`` for standard deviation or ``'var'`` for variance. A metaclass defining such an interface is `~astropy.nddata.NDUncertainty` but isn't mandatory. """ return self._uncertainty @uncertainty.setter def uncertainty(self, value): if value is not None: # There is one requirements on the uncertainty: That # it has an attribute 'uncertainty_type'. # If it does not match this requirement convert it to an unknown # uncertainty. if not hasattr(value, 'uncertainty_type'): log.info('uncertainty should have attribute uncertainty_type.') value = UnknownUncertainty(value, copy=False) # If it is a subclass of NDUncertainty we must set the # parent_nddata attribute. (#4152) if isinstance(value, NDUncertainty): # In case the uncertainty already has a parent create a new # instance because we need to assume that we don't want to # steal the uncertainty from another NDData object if value._parent_nddata is not None: value = value.__class__(value, copy=False) # Then link it to this NDData instance (internally this needs # to be saved as weakref but that's done by NDUncertainty # setter). value.parent_nddata = self self._uncertainty = value
045b64842f3bb755954f51b9fdf1e64827c72e9ed6fd940fbbe84078cb092254
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ The `astropy.nddata` subpackage provides the `~astropy.nddata.NDData` class and related tools to manage n-dimensional array-based data (e.g. CCD images, IFU Data, grid-based simulation data, ...). This is more than just `numpy.ndarray` objects, because it provides metadata that cannot be easily provided by a single array. """ from .nddata import * from .nddata_base import * from .nddata_withmixins import * from .nduncertainty import * from .flag_collection import * from .decorators import * from .mixins.ndarithmetic import * from .mixins.ndslicing import * from .mixins.ndio import * from .compat import * from .utils import * from .ccddata import * from .. import config as _config class Conf(_config.ConfigNamespace): """ Configuration parameters for `astropy.nddata`. """ warn_unsupported_correlated = _config.ConfigItem( True, 'Whether to issue a warning if `~astropy.nddata.NDData` arithmetic ' 'is performed with uncertainties and the uncertainties do not ' 'support the propagation of correlated uncertainties.' ) warn_setting_unit_directly = _config.ConfigItem( True, 'Whether to issue a warning when the `~astropy.nddata.NDData` unit ' 'attribute is changed from a non-``None`` value to another value ' 'that data values/uncertainties are not scaled with the unit change.' ) conf = Conf()
8aff5abd366abdcbb6dd88b2a5062dcbd460efb806db89a340601ea89f70bdf7
# Licensed under a 3-clause BSD style license - see LICENSE.rst """This module implements the base CCDData class.""" import numpy as np from .compat import NDDataArray from .nduncertainty import StdDevUncertainty, NDUncertainty from ..io import fits, registry from .. import units as u from .. import log from ..wcs import WCS from ..utils.decorators import sharedmethod __all__ = ['CCDData', 'fits_ccddata_reader', 'fits_ccddata_writer'] # Global value which can turn on/off the unit requirements when creating a # CCDData. Should be used with care because several functions actually break # if the unit is None! _config_ccd_requires_unit = True def _arithmetic(op): """Decorator factory which temporarly disables the need for a unit when creating a new CCDData instance. The final result must have a unit. Parameters ---------- op : function The function to apply. Supported are: - ``np.add`` - ``np.subtract`` - ``np.multiply`` - ``np.true_divide`` Notes ----- Should only be used on CCDData ``add``, ``subtract``, ``divide`` or ``multiply`` because only these methods from NDArithmeticMixin are overwritten. """ def decorator(func): def inner(self, operand, operand2=None, **kwargs): global _config_ccd_requires_unit _config_ccd_requires_unit = False result = self._prepare_then_do_arithmetic(op, operand, operand2, **kwargs) # Wrap it again as CCDData so it checks the final unit. _config_ccd_requires_unit = True return result.__class__(result) inner.__doc__ = ("See `astropy.nddata.NDArithmeticMixin.{}`." "".format(func.__name__)) return sharedmethod(inner) return decorator class CCDData(NDDataArray): """A class describing basic CCD data. The CCDData class is based on the NDData object and includes a data array, uncertainty frame, mask frame, flag frame, meta data, units, and WCS information for a single CCD image. Parameters ----------- data : `~astropy.nddata.CCDData`-like or `numpy.ndarray`-like The actual data contained in this `~astropy.nddata.CCDData` object. Note that the data will always be saved by *reference*, so you should make a copy of the ``data`` before passing it in if that's the desired behavior. uncertainty : `~astropy.nddata.StdDevUncertainty`, `numpy.ndarray` or \ None, optional Uncertainties on the data. Default is ``None``. mask : `numpy.ndarray` or None, optional Mask for the data, given as a boolean Numpy array with a shape matching that of the data. The values must be `False` where the data is *valid* and `True` when it is not (like Numpy masked arrays). If ``data`` is a numpy masked array, providing ``mask`` here will causes the mask from the masked array to be ignored. Default is ``None``. flags : `numpy.ndarray` or `~astropy.nddata.FlagCollection` or None, \ optional Flags giving information about each pixel. These can be specified either as a Numpy array of any type with a shape matching that of the data, or as a `~astropy.nddata.FlagCollection` instance which has a shape matching that of the data. Default is ``None``. wcs : `~astropy.wcs.WCS` or None, optional WCS-object containing the world coordinate system for the data. Default is ``None``. meta : dict-like object or None, optional Metadata for this object. "Metadata" here means all information that is included with this object but not part of any other attribute of this particular object, e.g. creation date, unique identifier, simulation parameters, exposure time, telescope name, etc. unit : `~astropy.units.Unit` or str, optional The units of the data. Default is ``None``. .. warning:: If the unit is ``None`` or not otherwise specified it will raise a ``ValueError`` Raises ------ ValueError If the ``uncertainty`` or ``mask`` inputs cannot be broadcast (e.g., match shape) onto ``data``. Methods ------- read(\\*args, \\**kwargs) ``Classmethod`` to create an CCDData instance based on a ``FITS`` file. This method uses :func:`fits_ccddata_reader` with the provided parameters. write(\\*args, \\**kwargs) Writes the contents of the CCDData instance into a new ``FITS`` file. This method uses :func:`fits_ccddata_writer` with the provided parameters. Notes ----- `~astropy.nddata.CCDData` objects can be easily converted to a regular Numpy array using `numpy.asarray`. For example:: >>> from astropy.nddata import CCDData >>> import numpy as np >>> x = CCDData([1,2,3], unit='adu') >>> np.asarray(x) array([1, 2, 3]) This is useful, for example, when plotting a 2D image using matplotlib. >>> from astropy.nddata import CCDData >>> from matplotlib import pyplot as plt # doctest: +SKIP >>> x = CCDData([[1,2,3], [4,5,6]], unit='adu') >>> plt.imshow(x) # doctest: +SKIP """ def __init__(self, *args, **kwd): if 'meta' not in kwd: kwd['meta'] = kwd.pop('header', None) if 'header' in kwd: raise ValueError("can't have both header and meta.") super().__init__(*args, **kwd) # Check if a unit is set. This can be temporarly disabled by the # _CCDDataUnit contextmanager. if _config_ccd_requires_unit and self.unit is None: raise ValueError("a unit for CCDData must be specified.") @property def data(self): return self._data @data.setter def data(self, value): self._data = value @property def wcs(self): return self._wcs @wcs.setter def wcs(self, value): self._wcs = value @property def unit(self): return self._unit @unit.setter def unit(self, value): self._unit = u.Unit(value) @property def header(self): return self._meta @header.setter def header(self, value): self.meta = value @property def uncertainty(self): return self._uncertainty @uncertainty.setter def uncertainty(self, value): if value is not None: if isinstance(value, NDUncertainty): if getattr(value, '_parent_nddata', None) is not None: value = value.__class__(value, copy=False) self._uncertainty = value elif isinstance(value, np.ndarray): if value.shape != self.shape: raise ValueError("uncertainty must have same shape as " "data.") self._uncertainty = StdDevUncertainty(value) log.info("array provided for uncertainty; assuming it is a " "StdDevUncertainty.") else: raise TypeError("uncertainty must be an instance of a " "NDUncertainty object or a numpy array.") self._uncertainty.parent_nddata = self else: self._uncertainty = value def to_hdu(self, hdu_mask='MASK', hdu_uncertainty='UNCERT', hdu_flags=None, wcs_relax=True): """Creates an HDUList object from a CCDData object. Parameters ---------- hdu_mask, hdu_uncertainty, hdu_flags : str or None, optional If it is a string append this attribute to the HDUList as `~astropy.io.fits.ImageHDU` with the string as extension name. Flags are not supported at this time. If ``None`` this attribute is not appended. Default is ``'MASK'`` for mask, ``'UNCERT'`` for uncertainty and ``None`` for flags. wcs_relax : bool Value of the ``relax`` parameter to use in converting the WCS to a FITS header using `~astropy.wcs.WCS.to_header`. The common ``CTYPE`` ``RA---TAN-SIP`` and ``DEC--TAN-SIP`` requires ``relax=True`` for the ``-SIP`` part of the ``CTYPE`` to be preserved. Raises ------- ValueError - If ``self.mask`` is set but not a `numpy.ndarray`. - If ``self.uncertainty`` is set but not a `~astropy.nddata.StdDevUncertainty`. - If ``self.uncertainty`` is set but has another unit then ``self.data``. NotImplementedError Saving flags is not supported. Returns ------- hdulist : `~astropy.io.fits.HDUList` """ if isinstance(self.header, fits.Header): # Copy here so that we can modify the HDU header by adding WCS # information without changing the header of the CCDData object. header = self.header.copy() else: # Because _insert_in_metadata_fits_safe is written as a method # we need to create a dummy CCDData instance to hold the FITS # header we are constructing. This probably indicates that # _insert_in_metadata_fits_safe should be rewritten in a more # sensible way... dummy_ccd = CCDData([1], meta=fits.Header(), unit="adu") for k, v in self.header.items(): dummy_ccd._insert_in_metadata_fits_safe(k, v) header = dummy_ccd.header if self.unit is not u.dimensionless_unscaled: header['bunit'] = self.unit.to_string() if self.wcs: # Simply extending the FITS header with the WCS can lead to # duplicates of the WCS keywords; iterating over the WCS # header should be safer. # # Turns out if I had read the io.fits.Header.extend docs more # carefully, I would have realized that the keywords exist to # avoid duplicates and preserve, as much as possible, the # structure of the commentary cards. # # Note that until astropy/astropy#3967 is closed, the extend # will fail if there are comment cards in the WCS header but # not header. wcs_header = self.wcs.to_header(relax=wcs_relax) header.extend(wcs_header, useblanks=False, update=True) hdus = [fits.PrimaryHDU(self.data, header)] if hdu_mask and self.mask is not None: # Always assuming that the mask is a np.ndarray (check that it has # a 'shape'). if not hasattr(self.mask, 'shape'): raise ValueError('only a numpy.ndarray mask can be saved.') # Convert boolean mask to uint since io.fits cannot handle bool. hduMask = fits.ImageHDU(self.mask.astype(np.uint8), name=hdu_mask) hdus.append(hduMask) if hdu_uncertainty and self.uncertainty is not None: # We need to save some kind of information which uncertainty was # used so that loading the HDUList can infer the uncertainty type. # No idea how this can be done so only allow StdDevUncertainty. if self.uncertainty.__class__.__name__ != 'StdDevUncertainty': raise ValueError('only StdDevUncertainty can be saved.') # Assuming uncertainty is an StdDevUncertainty save just the array # this might be problematic if the Uncertainty has a unit differing # from the data so abort for different units. This is important for # astropy > 1.2 if (hasattr(self.uncertainty, 'unit') and self.uncertainty.unit is not None and self.uncertainty.unit != self.unit): raise ValueError('saving uncertainties with a unit differing' 'from the data unit is not supported.') hduUncert = fits.ImageHDU(self.uncertainty.array, name=hdu_uncertainty) hdus.append(hduUncert) if hdu_flags and self.flags: raise NotImplementedError('adding the flags to a HDU is not ' 'supported at this time.') hdulist = fits.HDUList(hdus) return hdulist def copy(self): """ Return a copy of the CCDData object. """ return self.__class__(self, copy=True) add = _arithmetic(np.add)(NDDataArray.add) subtract = _arithmetic(np.subtract)(NDDataArray.subtract) multiply = _arithmetic(np.multiply)(NDDataArray.multiply) divide = _arithmetic(np.true_divide)(NDDataArray.divide) def _insert_in_metadata_fits_safe(self, key, value): """ Insert key/value pair into metadata in a way that FITS can serialize. Parameters ---------- key : str Key to be inserted in dictionary. value : str or None Value to be inserted. Notes ----- This addresses a shortcoming of the FITS standard. There are length restrictions on both the ``key`` (8 characters) and ``value`` (72 characters) in the FITS standard. There is a convention for handling long keywords and a convention for handling long values, but the two conventions cannot be used at the same time. This addresses that case by checking the length of the ``key`` and ``value`` and, if necessary, shortening the key. """ if len(key) > 8 and len(value) > 72: short_name = key[:8] self.meta['HIERARCH {0}'.format(key.upper())] = ( short_name, "Shortened name for {}".format(key)) self.meta[short_name] = value else: self.meta[key] = value # This needs to be importable by the tests... _KEEP_THESE_KEYWORDS_IN_HEADER = [ 'JD-OBS', 'MJD-OBS', 'DATE-OBS' ] def _generate_wcs_and_update_header(hdr): """ Generate a WCS object from a header and remove the WCS-specific keywords from the header. Parameters ---------- hdr : astropy.io.fits.header or other dict-like Returns ------- new_header, wcs """ # Try constructing a WCS object. try: wcs = WCS(hdr) except Exception as exc: # Normally WCS only raises Warnings and doesn't fail but in rare # cases (malformed header) it could fail... log.info('An exception happened while extracting WCS informations from ' 'the Header.\n{}: {}'.format(type(exc).__name__, str(exc))) return hdr, None # Test for success by checking to see if the wcs ctype has a non-empty # value, return None for wcs if ctype is empty. if not wcs.wcs.ctype[0]: return (hdr, None) new_hdr = hdr.copy() # If the keywords below are in the header they are also added to WCS. # It seems like they should *not* be removed from the header, though. wcs_header = wcs.to_header(relax=True) for k in wcs_header: if k not in _KEEP_THESE_KEYWORDS_IN_HEADER: new_hdr.remove(k, ignore_missing=True) return (new_hdr, wcs) def fits_ccddata_reader(filename, hdu=0, unit=None, hdu_uncertainty='UNCERT', hdu_mask='MASK', hdu_flags=None, **kwd): """ Generate a CCDData object from a FITS file. Parameters ---------- filename : str Name of fits file. hdu : int, optional FITS extension from which CCDData should be initialized. If zero and and no data in the primary extension, it will search for the first extension with data. The header will be added to the primary header. Default is ``0``. unit : `~astropy.units.Unit`, optional Units of the image data. If this argument is provided and there is a unit for the image in the FITS header (the keyword ``BUNIT`` is used as the unit, if present), this argument is used for the unit. Default is ``None``. hdu_uncertainty : str or None, optional FITS extension from which the uncertainty should be initialized. If the extension does not exist the uncertainty of the CCDData is ``None``. Default is ``'UNCERT'``. hdu_mask : str or None, optional FITS extension from which the mask should be initialized. If the extension does not exist the mask of the CCDData is ``None``. Default is ``'MASK'``. hdu_flags : str or None, optional Currently not implemented. Default is ``None``. kwd : Any additional keyword parameters are passed through to the FITS reader in :mod:`astropy.io.fits`; see Notes for additional discussion. Notes ----- FITS files that contained scaled data (e.g. unsigned integer images) will be scaled and the keywords used to manage scaled data in :mod:`astropy.io.fits` are disabled. """ unsupport_open_keywords = { 'do_not_scale_image_data': 'Image data must be scaled.', 'scale_back': 'Scale information is not preserved.' } for key, msg in unsupport_open_keywords.items(): if key in kwd: prefix = 'unsupported keyword: {0}.'.format(key) raise TypeError(' '.join([prefix, msg])) with fits.open(filename, **kwd) as hdus: hdr = hdus[hdu].header if hdu_uncertainty is not None and hdu_uncertainty in hdus: uncertainty = StdDevUncertainty(hdus[hdu_uncertainty].data) else: uncertainty = None if hdu_mask is not None and hdu_mask in hdus: # Mask is saved as uint but we want it to be boolean. mask = hdus[hdu_mask].data.astype(np.bool_) else: mask = None if hdu_flags is not None and hdu_flags in hdus: raise NotImplementedError('loading flags is currently not ' 'supported.') # search for the first instance with data if # the primary header is empty. if hdu == 0 and hdus[hdu].data is None: for i in range(len(hdus)): if hdus.fileinfo(i)['datSpan'] > 0: hdu = i comb_hdr = hdus[hdu].header.copy() # Add header values from the primary header that aren't # present in the extension header. comb_hdr.extend(hdr, unique=True) hdr = comb_hdr log.info("first HDU with data is extension " "{0}.".format(hdu)) break if 'bunit' in hdr: fits_unit_string = hdr['bunit'] # patch to handle FITS files using ADU for the unit instead of the # standard version of 'adu' if fits_unit_string.strip().lower() == 'adu': fits_unit_string = fits_unit_string.lower() else: fits_unit_string = None if unit is not None and fits_unit_string: log.info("using the unit {0} passed to the FITS reader instead of " "the unit {1} in the FITS file.".format(unit, fits_unit_string)) use_unit = unit or fits_unit_string hdr, wcs = _generate_wcs_and_update_header(hdr) ccd_data = CCDData(hdus[hdu].data, meta=hdr, unit=use_unit, mask=mask, uncertainty=uncertainty, wcs=wcs) return ccd_data def fits_ccddata_writer(ccd_data, filename, hdu_mask='MASK', hdu_uncertainty='UNCERT', hdu_flags=None, **kwd): """ Write CCDData object to FITS file. Parameters ---------- filename : str Name of file. hdu_mask, hdu_uncertainty, hdu_flags : str or None, optional If it is a string append this attribute to the HDUList as `~astropy.io.fits.ImageHDU` with the string as extension name. Flags are not supported at this time. If ``None`` this attribute is not appended. Default is ``'MASK'`` for mask, ``'UNCERT'`` for uncertainty and ``None`` for flags. kwd : All additional keywords are passed to :py:mod:`astropy.io.fits` Raises ------- ValueError - If ``self.mask`` is set but not a `numpy.ndarray`. - If ``self.uncertainty`` is set but not a `~astropy.nddata.StdDevUncertainty`. - If ``self.uncertainty`` is set but has another unit then ``self.data``. NotImplementedError Saving flags is not supported. """ hdu = ccd_data.to_hdu(hdu_mask=hdu_mask, hdu_uncertainty=hdu_uncertainty, hdu_flags=hdu_flags) hdu.writeto(filename, **kwd) with registry.delay_doc_updates(CCDData): registry.register_reader('fits', CCDData, fits_ccddata_reader) registry.register_writer('fits', CCDData, fits_ccddata_writer) registry.register_identifier('fits', CCDData, fits.connect.is_fits) try: CCDData.read.__doc__ = fits_ccddata_reader.__doc__ except AttributeError: CCDData.read.__func__.__doc__ = fits_ccddata_reader.__doc__ try: CCDData.write.__doc__ = fits_ccddata_writer.__doc__ except AttributeError: CCDData.write.__func__.__doc__ = fits_ccddata_writer.__doc__
0a8478a941809b2acb423274acc96468cb955cf6f84ec126bf807ba662640c55
# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return {'astropy.nddata.tests': ['data/*.fits']}
5a08fc56dbac243bc68d3740f377ee68361a543de89919cc836c7e958cca3e51
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module includes helper functions for array operations. """ from copy import deepcopy import numpy as np from .decorators import support_nddata from .. import units as u from ..coordinates import SkyCoord from ..utils import lazyproperty from ..wcs.utils import skycoord_to_pixel, proj_plane_pixel_scales __all__ = ['extract_array', 'add_array', 'subpixel_indices', 'overlap_slices', 'block_reduce', 'block_replicate', 'NoOverlapError', 'PartialOverlapError', 'Cutout2D'] class NoOverlapError(ValueError): '''Raised when determining the overlap of non-overlapping arrays.''' pass class PartialOverlapError(ValueError): '''Raised when arrays only partially overlap.''' pass def _round(a): '''Always round up. ``np.round`` cannot be used here, because it rounds .5 to the nearest even number. ''' return int(np.floor(a + 0.5)) def _offset(a): '''Offset by 0.5 for an even array. For an array with an odd number of elements, the center is symmetric, e.g. for 3 elements, it's center +/-1 elements, but for four elements it's center -2 / +1 This function introduces that offset. ''' if np.mod(a, 2) == 0: return -0.5 else: return 0. def overlap_slices(large_array_shape, small_array_shape, position, mode='partial'): """ Get slices for the overlapping part of a small and a large array. Given a certain position of the center of the small array, with respect to the large array, tuples of slices are returned which can be used to extract, add or subtract the small array at the given position. This function takes care of the correct behavior at the boundaries, where the small array is cut of appropriately. Integer positions are at the pixel centers. Parameters ---------- large_array_shape : tuple or int The shape of the large array (for 1D arrays, this can be an `int`). small_array_shape : tuple or int The shape of the small array (for 1D arrays, this can be an `int`). See the ``mode`` keyword for additional details. position : tuple of numbers or number The position of the small array's center with respect to the large array. The pixel coordinates should be in the same order as the array shape. Integer positions are at the pixel centers. For any axis where ``small_array_shape`` is even, the position is rounded up, e.g. extracting two elements with a center of ``1`` will define the extracted region as ``[0, 1]``. mode : {'partial', 'trim', 'strict'}, optional In ``'partial'`` mode, a partial overlap of the small and the large array is sufficient. The ``'trim'`` mode is similar to the ``'partial'`` mode, but ``slices_small`` will be adjusted to return only the overlapping elements. In the ``'strict'`` mode, the small array has to be fully contained in the large array, otherwise an `~astropy.nddata.utils.PartialOverlapError` is raised. In all modes, non-overlapping arrays will raise a `~astropy.nddata.utils.NoOverlapError`. Returns ------- slices_large : tuple of slices A tuple of slice objects for each axis of the large array, such that ``large_array[slices_large]`` extracts the region of the large array that overlaps with the small array. slices_small : slice A tuple of slice objects for each axis of the small array, such that ``small_array[slices_small]`` extracts the region that is inside the large array. """ if mode not in ['partial', 'trim', 'strict']: raise ValueError('Mode can be only "partial", "trim", or "strict".') if np.isscalar(small_array_shape): small_array_shape = (small_array_shape, ) if np.isscalar(large_array_shape): large_array_shape = (large_array_shape, ) if np.isscalar(position): position = (position, ) if len(small_array_shape) != len(large_array_shape): raise ValueError('"large_array_shape" and "small_array_shape" must ' 'have the same number of dimensions.') if len(small_array_shape) != len(position): raise ValueError('"position" must have the same number of dimensions ' 'as "small_array_shape".') # Get edge coordinates edges_min = [_round(pos + 0.5 - small_shape / 2. + _offset(small_shape)) for (pos, small_shape) in zip(position, small_array_shape)] edges_max = [_round(pos + 0.5 + small_shape / 2. + _offset(small_shape)) for (pos, small_shape) in zip(position, small_array_shape)] for e_max in edges_max: if e_max <= 0: raise NoOverlapError('Arrays do not overlap.') for e_min, large_shape in zip(edges_min, large_array_shape): if e_min >= large_shape: raise NoOverlapError('Arrays do not overlap.') if mode == 'strict': for e_min in edges_min: if e_min < 0: raise PartialOverlapError('Arrays overlap only partially.') for e_max, large_shape in zip(edges_max, large_array_shape): if e_max >= large_shape: raise PartialOverlapError('Arrays overlap only partially.') # Set up slices slices_large = tuple(slice(max(0, edge_min), min(large_shape, edge_max)) for (edge_min, edge_max, large_shape) in zip(edges_min, edges_max, large_array_shape)) if mode == 'trim': slices_small = tuple(slice(0, slc.stop - slc.start) for slc in slices_large) else: slices_small = tuple(slice(max(0, -edge_min), min(large_shape - edge_min, edge_max - edge_min)) for (edge_min, edge_max, large_shape) in zip(edges_min, edges_max, large_array_shape)) return slices_large, slices_small def extract_array(array_large, shape, position, mode='partial', fill_value=np.nan, return_position=False): """ Extract a smaller array of the given shape and position from a larger array. Parameters ---------- array_large : `~numpy.ndarray` The array from which to extract the small array. shape : tuple or int The shape of the extracted array (for 1D arrays, this can be an `int`). See the ``mode`` keyword for additional details. position : tuple of numbers or number The position of the small array's center with respect to the large array. The pixel coordinates should be in the same order as the array shape. Integer positions are at the pixel centers (for 1D arrays, this can be a number). mode : {'partial', 'trim', 'strict'}, optional The mode used for extracting the small array. For the ``'partial'`` and ``'trim'`` modes, a partial overlap of the small array and the large array is sufficient. For the ``'strict'`` mode, the small array has to be fully contained within the large array, otherwise an `~astropy.nddata.utils.PartialOverlapError` is raised. In all modes, non-overlapping arrays will raise a `~astropy.nddata.utils.NoOverlapError`. In ``'partial'`` mode, positions in the small array that do not overlap with the large array will be filled with ``fill_value``. In ``'trim'`` mode only the overlapping elements are returned, thus the resulting small array may be smaller than the requested ``shape``. fill_value : number, optional If ``mode='partial'``, the value to fill pixels in the extracted small array that do not overlap with the input ``array_large``. ``fill_value`` must have the same ``dtype`` as the ``array_large`` array. return_position : boolean, optional If `True`, return the coordinates of ``position`` in the coordinate system of the returned array. Returns ------- array_small : `~numpy.ndarray` The extracted array. new_position : tuple If ``return_position`` is true, this tuple will contain the coordinates of the input ``position`` in the coordinate system of ``array_small``. Note that for partially overlapping arrays, ``new_position`` might actually be outside of the ``array_small``; ``array_small[new_position]`` might give wrong results if any element in ``new_position`` is negative. Examples -------- We consider a large array with the shape 11x10, from which we extract a small array of shape 3x5: >>> import numpy as np >>> from astropy.nddata.utils import extract_array >>> large_array = np.arange(110).reshape((11, 10)) >>> extract_array(large_array, (3, 5), (7, 7)) array([[65, 66, 67, 68, 69], [75, 76, 77, 78, 79], [85, 86, 87, 88, 89]]) """ if np.isscalar(shape): shape = (shape, ) if np.isscalar(position): position = (position, ) if mode not in ['partial', 'trim', 'strict']: raise ValueError("Valid modes are 'partial', 'trim', and 'strict'.") large_slices, small_slices = overlap_slices(array_large.shape, shape, position, mode=mode) extracted_array = array_large[large_slices] if return_position: new_position = [i - s.start for i, s in zip(position, large_slices)] # Extracting on the edges is presumably a rare case, so treat special here if (extracted_array.shape != shape) and (mode == 'partial'): extracted_array = np.zeros(shape, dtype=array_large.dtype) extracted_array[:] = fill_value extracted_array[small_slices] = array_large[large_slices] if return_position: new_position = [i + s.start for i, s in zip(new_position, small_slices)] if return_position: return extracted_array, tuple(new_position) else: return extracted_array def add_array(array_large, array_small, position): """ Add a smaller array at a given position in a larger array. Parameters ---------- array_large : `~numpy.ndarray` Large array. array_small : `~numpy.ndarray` Small array to add. position : tuple Position of the small array's center, with respect to the large array. Coordinates should be in the same order as the array shape. Returns ------- new_array : `~numpy.ndarray` The new array formed from the sum of ``array_large`` and ``array_small``. Notes ----- The addition is done in-place. Examples -------- We consider a large array of zeros with the shape 5x5 and a small array of ones with a shape of 3x3: >>> import numpy as np >>> from astropy.nddata.utils import add_array >>> large_array = np.zeros((5, 5)) >>> small_array = np.ones((3, 3)) >>> add_array(large_array, small_array, (1, 2)) # doctest: +FLOAT_CMP array([[0., 1., 1., 1., 0.], [0., 1., 1., 1., 0.], [0., 1., 1., 1., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) """ # Check if large array is really larger if all(large_shape > small_shape for (large_shape, small_shape) in zip(array_large.shape, array_small.shape)): large_slices, small_slices = overlap_slices(array_large.shape, array_small.shape, position) array_large[large_slices] += array_small[small_slices] return array_large else: raise ValueError("Can't add array. Small array too large.") def subpixel_indices(position, subsampling): """ Convert decimal points to indices, given a subsampling factor. This discards the integer part of the position and uses only the decimal place, and converts this to a subpixel position depending on the subsampling specified. The center of a pixel corresponds to an integer position. Parameters ---------- position : `~numpy.ndarray` or array-like Positions in pixels. subsampling : int Subsampling factor per pixel. Returns ------- indices : `~numpy.ndarray` The integer subpixel indices corresponding to the input positions. Examples -------- If no subsampling is used, then the subpixel indices returned are always 0: >>> from astropy.nddata.utils import subpixel_indices >>> subpixel_indices([1.2, 3.4, 5.6], 1) # doctest: +FLOAT_CMP array([0., 0., 0.]) If instead we use a subsampling of 2, we see that for the two first values (1.1 and 3.4) the subpixel position is 1, while for 5.6 it is 0. This is because the values of 1, 3, and 6 lie in the center of pixels, and 1.1 and 3.4 lie in the left part of the pixels and 5.6 lies in the right part. >>> subpixel_indices([1.2, 3.4, 5.5], 2) # doctest: +FLOAT_CMP array([1., 1., 0.]) """ # Get decimal points fractions = np.modf(np.asanyarray(position) + 0.5)[0] return np.floor(fractions * subsampling) @support_nddata def block_reduce(data, block_size, func=np.sum): """ Downsample a data array by applying a function to local blocks. If ``data`` is not perfectly divisible by ``block_size`` along a given axis then the data will be trimmed (from the end) along that axis. Parameters ---------- data : array_like The data to be resampled. block_size : int or array_like (int) The integer block size along each axis. If ``block_size`` is a scalar and ``data`` has more than one dimension, then ``block_size`` will be used for for every axis. func : callable, optional The method to use to downsample the data. Must be a callable that takes in a `~numpy.ndarray` along with an ``axis`` keyword, which defines the axis along which the function is applied. The default is `~numpy.sum`, which provides block summation (and conserves the data sum). Returns ------- output : array-like The resampled data. Examples -------- >>> import numpy as np >>> from astropy.nddata.utils import block_reduce >>> data = np.arange(16).reshape(4, 4) >>> block_reduce(data, 2) # doctest: +SKIP array([[10, 18], [42, 50]]) >>> block_reduce(data, 2, func=np.mean) # doctest: +SKIP array([[ 2.5, 4.5], [ 10.5, 12.5]]) """ from skimage.measure import block_reduce data = np.asanyarray(data) block_size = np.atleast_1d(block_size) if data.ndim > 1 and len(block_size) == 1: block_size = np.repeat(block_size, data.ndim) if len(block_size) != data.ndim: raise ValueError('`block_size` must be a scalar or have the same ' 'length as `data.shape`') block_size = np.array([int(i) for i in block_size]) size_resampled = np.array(data.shape) // block_size size_init = size_resampled * block_size # trim data if necessary for i in range(data.ndim): if data.shape[i] != size_init[i]: data = data.swapaxes(0, i) data = data[:size_init[i]] data = data.swapaxes(0, i) return block_reduce(data, tuple(block_size), func=func) @support_nddata def block_replicate(data, block_size, conserve_sum=True): """ Upsample a data array by block replication. Parameters ---------- data : array_like The data to be block replicated. block_size : int or array_like (int) The integer block size along each axis. If ``block_size`` is a scalar and ``data`` has more than one dimension, then ``block_size`` will be used for for every axis. conserve_sum : bool, optional If `True` (the default) then the sum of the output block-replicated data will equal the sum of the input ``data``. Returns ------- output : array_like The block-replicated data. Examples -------- >>> import numpy as np >>> from astropy.nddata.utils import block_replicate >>> data = np.array([[0., 1.], [2., 3.]]) >>> block_replicate(data, 2) # doctest: +FLOAT_CMP array([[0. , 0. , 0.25, 0.25], [0. , 0. , 0.25, 0.25], [0.5 , 0.5 , 0.75, 0.75], [0.5 , 0.5 , 0.75, 0.75]]) >>> block_replicate(data, 2, conserve_sum=False) # doctest: +FLOAT_CMP array([[0., 0., 1., 1.], [0., 0., 1., 1.], [2., 2., 3., 3.], [2., 2., 3., 3.]]) """ data = np.asanyarray(data) block_size = np.atleast_1d(block_size) if data.ndim > 1 and len(block_size) == 1: block_size = np.repeat(block_size, data.ndim) if len(block_size) != data.ndim: raise ValueError('`block_size` must be a scalar or have the same ' 'length as `data.shape`') for i in range(data.ndim): data = np.repeat(data, block_size[i], axis=i) if conserve_sum: data = data / float(np.prod(block_size)) return data class Cutout2D: """ Create a cutout object from a 2D array. The returned object will contain a 2D cutout array. If ``copy=False`` (default), the cutout array is a view into the original ``data`` array, otherwise the cutout array will contain a copy of the original data. If a `~astropy.wcs.WCS` object is input, then the returned object will also contain a copy of the original WCS, but updated for the cutout array. For example usage, see :ref:`cutout_images`. .. warning:: The cutout WCS object does not currently handle cases where the input WCS object contains distortion lookup tables described in the `FITS WCS distortion paper <http://www.atnf.csiro.au/people/mcalabre/WCS/dcs_20040422.pdf>`__. Parameters ---------- data : `~numpy.ndarray` The 2D data array from which to extract the cutout array. position : tuple or `~astropy.coordinates.SkyCoord` The position of the cutout array's center with respect to the ``data`` array. The position can be specified either as a ``(x, y)`` tuple of pixel coordinates or a `~astropy.coordinates.SkyCoord`, in which case ``wcs`` is a required input. size : int, array-like, `~astropy.units.Quantity` The size of the cutout array along each axis. If ``size`` is a scalar number or a scalar `~astropy.units.Quantity`, then a square cutout of ``size`` will be created. If ``size`` has two elements, they should be in ``(ny, nx)`` order. Scalar numbers in ``size`` are assumed to be in units of pixels. ``size`` can also be a `~astropy.units.Quantity` object or contain `~astropy.units.Quantity` objects. Such `~astropy.units.Quantity` objects must be in pixel or angular units. For all cases, ``size`` will be converted to an integer number of pixels, rounding the the nearest integer. See the ``mode`` keyword for additional details on the final cutout size. .. note:: If ``size`` is in angular units, the cutout size is converted to pixels using the pixel scales along each axis of the image at the ``CRPIX`` location. Projection and other non-linear distortions are not taken into account. wcs : `~astropy.wcs.WCS`, optional A WCS object associated with the input ``data`` array. If ``wcs`` is not `None`, then the returned cutout object will contain a copy of the updated WCS for the cutout data array. mode : {'trim', 'partial', 'strict'}, optional The mode used for creating the cutout data array. For the ``'partial'`` and ``'trim'`` modes, a partial overlap of the cutout array and the input ``data`` array is sufficient. For the ``'strict'`` mode, the cutout array has to be fully contained within the ``data`` array, otherwise an `~astropy.nddata.utils.PartialOverlapError` is raised. In all modes, non-overlapping arrays will raise a `~astropy.nddata.utils.NoOverlapError`. In ``'partial'`` mode, positions in the cutout array that do not overlap with the ``data`` array will be filled with ``fill_value``. In ``'trim'`` mode only the overlapping elements are returned, thus the resulting cutout array may be smaller than the requested ``shape``. fill_value : number, optional If ``mode='partial'``, the value to fill pixels in the cutout array that do not overlap with the input ``data``. ``fill_value`` must have the same ``dtype`` as the input ``data`` array. copy : bool, optional If `False` (default), then the cutout data will be a view into the original ``data`` array. If `True`, then the cutout data will hold a copy of the original ``data`` array. Attributes ---------- data : 2D `~numpy.ndarray` The 2D cutout array. shape : 2 tuple The ``(ny, nx)`` shape of the cutout array. shape_input : 2 tuple The ``(ny, nx)`` shape of the input (original) array. input_position_cutout : 2 tuple The (unrounded) ``(x, y)`` position with respect to the cutout array. input_position_original : 2 tuple The original (unrounded) ``(x, y)`` input position (with respect to the original array). slices_original : 2 tuple of slice objects A tuple of slice objects for the minimal bounding box of the cutout with respect to the original array. For ``mode='partial'``, the slices are for the valid (non-filled) cutout values. slices_cutout : 2 tuple of slice objects A tuple of slice objects for the minimal bounding box of the cutout with respect to the cutout array. For ``mode='partial'``, the slices are for the valid (non-filled) cutout values. xmin_original, ymin_original, xmax_original, ymax_original : float The minimum and maximum ``x`` and ``y`` indices of the minimal rectangular region of the cutout array with respect to the original array. For ``mode='partial'``, the bounding box indices are for the valid (non-filled) cutout values. These values are the same as those in `bbox_original`. xmin_cutout, ymin_cutout, xmax_cutout, ymax_cutout : float The minimum and maximum ``x`` and ``y`` indices of the minimal rectangular region of the cutout array with respect to the cutout array. For ``mode='partial'``, the bounding box indices are for the valid (non-filled) cutout values. These values are the same as those in `bbox_cutout`. wcs : `~astropy.wcs.WCS` or `None` A WCS object associated with the cutout array if a ``wcs`` was input. Examples -------- >>> import numpy as np >>> from astropy.nddata.utils import Cutout2D >>> from astropy import units as u >>> data = np.arange(20.).reshape(5, 4) >>> cutout1 = Cutout2D(data, (2, 2), (3, 3)) >>> print(cutout1.data) # doctest: +FLOAT_CMP [[ 5. 6. 7.] [ 9. 10. 11.] [13. 14. 15.]] >>> print(cutout1.center_original) (2.0, 2.0) >>> print(cutout1.center_cutout) (1.0, 1.0) >>> print(cutout1.origin_original) (1, 1) >>> cutout2 = Cutout2D(data, (2, 2), 3) >>> print(cutout2.data) # doctest: +FLOAT_CMP [[ 5. 6. 7.] [ 9. 10. 11.] [13. 14. 15.]] >>> size = u.Quantity([3, 3], u.pixel) >>> cutout3 = Cutout2D(data, (0, 0), size) >>> print(cutout3.data) # doctest: +FLOAT_CMP [[0. 1.] [4. 5.]] >>> cutout4 = Cutout2D(data, (0, 0), (3 * u.pixel, 3)) >>> print(cutout4.data) # doctest: +FLOAT_CMP [[0. 1.] [4. 5.]] >>> cutout5 = Cutout2D(data, (0, 0), (3, 3), mode='partial') >>> print(cutout5.data) # doctest: +FLOAT_CMP [[nan nan nan] [nan 0. 1.] [nan 4. 5.]] """ def __init__(self, data, position, size, wcs=None, mode='trim', fill_value=np.nan, copy=False): if isinstance(position, SkyCoord): if wcs is None: raise ValueError('wcs must be input if position is a ' 'SkyCoord') position = skycoord_to_pixel(position, wcs, mode='all') # (x, y) if np.isscalar(size): size = np.repeat(size, 2) # special handling for a scalar Quantity if isinstance(size, u.Quantity): size = np.atleast_1d(size) if len(size) == 1: size = np.repeat(size, 2) if len(size) > 2: raise ValueError('size must have at most two elements') shape = np.zeros(2).astype(int) pixel_scales = None # ``size`` can have a mixture of int and Quantity (and even units), # so evaluate each axis separately for axis, side in enumerate(size): if not isinstance(side, u.Quantity): shape[axis] = int(np.round(size[axis])) # pixels else: if side.unit == u.pixel: shape[axis] = int(np.round(side.value)) elif side.unit.physical_type == 'angle': if wcs is None: raise ValueError('wcs must be input if any element ' 'of size has angular units') if pixel_scales is None: pixel_scales = u.Quantity( proj_plane_pixel_scales(wcs), wcs.wcs.cunit[axis]) shape[axis] = int(np.round( (side / pixel_scales[axis]).decompose())) else: raise ValueError('shape can contain Quantities with only ' 'pixel or angular units') data = np.asanyarray(data) # reverse position because extract_array and overlap_slices # use (y, x), but keep the input position pos_yx = position[::-1] cutout_data, input_position_cutout = extract_array( data, tuple(shape), pos_yx, mode=mode, fill_value=fill_value, return_position=True) if copy: cutout_data = np.copy(cutout_data) self.data = cutout_data self.input_position_cutout = input_position_cutout[::-1] # (x, y) slices_original, slices_cutout = overlap_slices( data.shape, shape, pos_yx, mode=mode) self.slices_original = slices_original self.slices_cutout = slices_cutout self.shape = self.data.shape self.input_position_original = position self.shape_input = shape ((self.ymin_original, self.ymax_original), (self.xmin_original, self.xmax_original)) = self.bbox_original ((self.ymin_cutout, self.ymax_cutout), (self.xmin_cutout, self.xmax_cutout)) = self.bbox_cutout # the true origin pixel of the cutout array, including any # filled cutout values self._origin_original_true = ( self.origin_original[0] - self.slices_cutout[1].start, self.origin_original[1] - self.slices_cutout[0].start) if wcs is not None: self.wcs = deepcopy(wcs) self.wcs.wcs.crpix -= self._origin_original_true else: self.wcs = None def to_original_position(self, cutout_position): """ Convert an ``(x, y)`` position in the cutout array to the original ``(x, y)`` position in the original large array. Parameters ---------- cutout_position : tuple The ``(x, y)`` pixel position in the cutout array. Returns ------- original_position : tuple The corresponding ``(x, y)`` pixel position in the original large array. """ return tuple(cutout_position[i] + self.origin_original[i] for i in [0, 1]) def to_cutout_position(self, original_position): """ Convert an ``(x, y)`` position in the original large array to the ``(x, y)`` position in the cutout array. Parameters ---------- original_position : tuple The ``(x, y)`` pixel position in the original large array. Returns ------- cutout_position : tuple The corresponding ``(x, y)`` pixel position in the cutout array. """ return tuple(original_position[i] - self.origin_original[i] for i in [0, 1]) def plot_on_original(self, ax=None, fill=False, **kwargs): """ Plot the cutout region on a matplotlib Axes instance. Parameters ---------- ax : `matplotlib.axes.Axes` instance, optional If `None`, then the current `matplotlib.axes.Axes` instance is used. fill : bool, optional Set whether to fill the cutout patch. The default is `False`. kwargs : optional Any keyword arguments accepted by `matplotlib.patches.Patch`. Returns ------- ax : `matplotlib.axes.Axes` instance The matplotlib Axes instance constructed in the method if ``ax=None``. Otherwise the output ``ax`` is the same as the input ``ax``. """ import matplotlib.pyplot as plt import matplotlib.patches as mpatches kwargs['fill'] = fill if ax is None: ax = plt.gca() height, width = self.shape hw, hh = width / 2., height / 2. pos_xy = self.position_original - np.array([hw, hh]) patch = mpatches.Rectangle(pos_xy, width, height, 0., **kwargs) ax.add_patch(patch) return ax @staticmethod def _calc_center(slices): """ Calculate the center position. The center position will be fractional for even-sized arrays. For ``mode='partial'``, the central position is calculated for the valid (non-filled) cutout values. """ return tuple(0.5 * (slices[i].start + slices[i].stop - 1) for i in [1, 0]) @staticmethod def _calc_bbox(slices): """ Calculate a minimal bounding box in the form ``((ymin, ymax), (xmin, xmax))``. Note these are pixel locations, not slice indices. For ``mode='partial'``, the bounding box indices are for the valid (non-filled) cutout values. """ # (stop - 1) to return the max pixel location, not the slice index return ((slices[0].start, slices[0].stop - 1), (slices[1].start, slices[1].stop - 1)) @lazyproperty def origin_original(self): """ The ``(x, y)`` index of the origin pixel of the cutout with respect to the original array. For ``mode='partial'``, the origin pixel is calculated for the valid (non-filled) cutout values. """ return (self.slices_original[1].start, self.slices_original[0].start) @lazyproperty def origin_cutout(self): """ The ``(x, y)`` index of the origin pixel of the cutout with respect to the cutout array. For ``mode='partial'``, the origin pixel is calculated for the valid (non-filled) cutout values. """ return (self.slices_cutout[1].start, self.slices_cutout[0].start) @lazyproperty def position_original(self): """ The ``(x, y)`` position index (rounded to the nearest pixel) in the original array. """ return (_round(self.input_position_original[0]), _round(self.input_position_original[1])) @lazyproperty def position_cutout(self): """ The ``(x, y)`` position index (rounded to the nearest pixel) in the cutout array. """ return (_round(self.input_position_cutout[0]), _round(self.input_position_cutout[1])) @lazyproperty def center_original(self): """ The central ``(x, y)`` position of the cutout array with respect to the original array. For ``mode='partial'``, the central position is calculated for the valid (non-filled) cutout values. """ return self._calc_center(self.slices_original) @lazyproperty def center_cutout(self): """ The central ``(x, y)`` position of the cutout array with respect to the cutout array. For ``mode='partial'``, the central position is calculated for the valid (non-filled) cutout values. """ return self._calc_center(self.slices_cutout) @lazyproperty def bbox_original(self): """ The bounding box ``((ymin, ymax), (xmin, xmax))`` of the minimal rectangular region of the cutout array with respect to the original array. For ``mode='partial'``, the bounding box indices are for the valid (non-filled) cutout values. """ return self._calc_bbox(self.slices_original) @lazyproperty def bbox_cutout(self): """ The bounding box ``((ymin, ymax), (xmin, xmax))`` of the minimal rectangular region of the cutout array with respect to the cutout array. For ``mode='partial'``, the bounding box indices are for the valid (non-filled) cutout values. """ return self._calc_bbox(self.slices_cutout)
9aaf4a56b98688be4b7355e0d6f5f3d82456884b0ac613ee6bb7d331076991a3
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This module contains a class equivalent to pre-1.0 NDData. import numpy as np from ..units import UnitsError, UnitConversionError, Unit from .. import log from .nddata import NDData from .nduncertainty import NDUncertainty from .mixins.ndslicing import NDSlicingMixin from .mixins.ndarithmetic import NDArithmeticMixin from .mixins.ndio import NDIOMixin from .flag_collection import FlagCollection __all__ = ['NDDataArray'] class NDDataArray(NDArithmeticMixin, NDSlicingMixin, NDIOMixin, NDData): """ An ``NDData`` object with arithmetic. This class is functionally equivalent to ``NDData`` in astropy versions prior to 1.0. The key distinction from raw numpy arrays is the presence of additional metadata such as uncertainties, a mask, units, flags, and/or a coordinate system. Parameters ----------- data : `~numpy.ndarray` or `NDData` The actual data contained in this `NDData` object. Not that this will always be copies by *reference* , so you should make copy the ``data`` before passing it in if that's the desired behavior. uncertainty : `~astropy.nddata.NDUncertainty`, optional Uncertainties on the data. mask : `~numpy.ndarray`-like, optional Mask for the data, given as a boolean Numpy array or any object that can be converted to a boolean Numpy array with a shape matching that of the data. The values must be ``False`` where the data is *valid* and ``True`` when it is not (like Numpy masked arrays). If ``data`` is a numpy masked array, providing ``mask`` here will causes the mask from the masked array to be ignored. flags : `~numpy.ndarray`-like or `~astropy.nddata.FlagCollection`, optional Flags giving information about each pixel. These can be specified either as a Numpy array of any type (or an object which can be converted to a Numpy array) with a shape matching that of the data, or as a `~astropy.nddata.FlagCollection` instance which has a shape matching that of the data. wcs : undefined, optional WCS-object containing the world coordinate system for the data. .. warning:: This is not yet defind because the discussion of how best to represent this class's WCS system generically is still under consideration. For now just leave it as None meta : `dict`-like object, optional Metadata for this object. "Metadata" here means all information that is included with this object but not part of any other attribute of this particular object. e.g., creation date, unique identifier, simulation parameters, exposure time, telescope name, etc. unit : `~astropy.units.UnitBase` instance or str, optional The units of the data. Raises ------ ValueError : If the `uncertainty` or `mask` inputs cannot be broadcast (e.g., match shape) onto ``data``. """ def __init__(self, data, *args, flags=None, **kwargs): # Initialize with the parent... super().__init__(data, *args, **kwargs) # ...then reset uncertainty to force it to go through the # setter logic below. In base NDData all that is done is to # set self._uncertainty to whatever uncertainty is passed in. self.uncertainty = self._uncertainty # Same thing for mask. self.mask = self._mask # Initial flags because it is no longer handled in NDData # or NDDataBase. if isinstance(data, NDDataArray): if flags is None: flags = data.flags else: log.info("Overwriting NDDataArrays's current " "flags with specified flags") self.flags = flags # Implement uncertainty as NDUncertainty to support propagation of # uncertainties in arithmetic operations @property def uncertainty(self): return self._uncertainty @uncertainty.setter def uncertainty(self, value): if value is not None: if isinstance(value, NDUncertainty): class_name = self.__class__.__name__ if self.unit and value._unit: try: scaling = (1 * value._unit).to(self.unit) except UnitsError: raise UnitConversionError( 'Cannot convert unit of uncertainty to unit of ' '{0} object.'.format(class_name)) value.array *= scaling elif not self.unit and value._unit: # Raise an error if uncertainty has unit and data does not raise ValueError("Cannot assign an uncertainty with unit " "to {0} without " "a unit".format(class_name)) self._uncertainty = value self._uncertainty.parent_nddata = self else: raise TypeError("Uncertainty must be an instance of " "a NDUncertainty object") else: self._uncertainty = value # Override unit so that we can add a setter. @property def unit(self): return self._unit @unit.setter def unit(self, value): from . import conf try: if self._unit is not None and conf.warn_setting_unit_directly: log.info('Setting the unit directly changes the unit without ' 'updating the data or uncertainty. Use the ' '.convert_unit_to() method to change the unit and ' 'scale values appropriately.') except AttributeError: # raised if self._unit has not been set yet, in which case the # warning is irrelevant pass if value is None: self._unit = None else: self._unit = Unit(value) # Implement mask in a way that converts nicely to a numpy masked array @property def mask(self): if self._mask is np.ma.nomask: return None else: return self._mask @mask.setter def mask(self, value): # Check that value is not either type of null mask. if (value is not None) and (value is not np.ma.nomask): mask = np.array(value, dtype=np.bool_, copy=False) if mask.shape != self.data.shape: raise ValueError("dimensions of mask do not match data") else: self._mask = mask else: # internal representation should be one numpy understands self._mask = np.ma.nomask @property def shape(self): """ shape tuple of this object's data. """ return self.data.shape @property def size(self): """ integer size of this object's data. """ return self.data.size @property def dtype(self): """ `numpy.dtype` of this object's data. """ return self.data.dtype @property def ndim(self): """ integer dimensions of this object's data """ return self.data.ndim @property def flags(self): return self._flags @flags.setter def flags(self, value): if value is not None: if isinstance(value, FlagCollection): if value.shape != self.shape: raise ValueError("dimensions of FlagCollection does not match data") else: self._flags = value else: flags = np.array(value, copy=False) if flags.shape != self.shape: raise ValueError("dimensions of flags do not match data") else: self._flags = flags else: self._flags = value def __array__(self): """ This allows code that requests a Numpy array to use an NDData object as a Numpy array. """ if self.mask is not None: return np.ma.masked_array(self.data, self.mask) else: return np.array(self.data) def __array_prepare__(self, array, context=None): """ This ensures that a masked array is returned if self is masked. """ if self.mask is not None: return np.ma.masked_array(array, self.mask) else: return array def convert_unit_to(self, unit, equivalencies=[]): """ Returns a new `NDData` object whose values have been converted to a new unit. Parameters ---------- unit : `astropy.units.UnitBase` instance or str The unit to convert to. equivalencies : list of equivalence pairs, optional A list of equivalence pairs to try if the units are not directly convertible. See :ref:`unit_equivalencies`. Returns ------- result : `~astropy.nddata.NDData` The resulting dataset Raises ------ UnitsError If units are inconsistent. """ if self.unit is None: raise ValueError("No unit specified on source data") data = self.unit.to(unit, self.data, equivalencies=equivalencies) if self.uncertainty is not None: uncertainty_values = self.unit.to(unit, self.uncertainty.array, equivalencies=equivalencies) # should work for any uncertainty class uncertainty = self.uncertainty.__class__(uncertainty_values) else: uncertainty = None if self.mask is not None: new_mask = self.mask.copy() else: new_mask = None # Call __class__ in case we are dealing with an inherited type result = self.__class__(data, uncertainty=uncertainty, mask=new_mask, wcs=self.wcs, meta=self.meta, unit=unit) return result
8d1e51fff71704051e8dd5571178f6f889e5814a46e27e5de5d181a533dab62f
# Licensed under a 3-clause BSD style license - see LICENSE.rst try: # The ERFA wrappers are not guaranteed available at setup time from .core import * except ImportError: if not _ASTROPY_SETUP_: raise
a6c802ea2c89a4232cc6c6569300b6320a68e4e7ea2bb49aea0fb5bec446ae8a
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module's main purpose is to act as a script to create new versions of erfa.c when ERFA is updated (or this generator is enhanced). `Jinja2 <http://jinja.pocoo.org/>`_ must be installed for this module/script to function. Note that this does *not* currently automate the process of creating structs or dtypes for those structs. They should be added manually in the template file. """ # note that we do *not* use unicode_literals here, because that makes the # generated code's strings have u'' in them on py 2.x import re import os.path from collections import OrderedDict ctype_to_dtype = {'double': "numpy.double", 'int': "numpy.intc", 'eraASTROM': "dt_eraASTROM", 'eraLDBODY': "dt_eraLDBODY", 'char': "numpy.dtype('S1')", 'const char': "numpy.dtype('S16')", } NDIMS_REX = re.compile(re.escape("numpy.dtype([('fi0', '.*', <(.*)>)])").replace(r'\.\*', '.*').replace(r'\<', '(').replace(r'\>', ')')) class FunctionDoc: def __init__(self, doc): self.doc = doc.replace("**", " ").replace("/*\n", "").replace("*/", "") self.__input = None self.__output = None self.__ret_info = None @property def input(self): if self.__input is None: self.__input = [] result = re.search("Given([^\n]*):\n(.+?) \n", self.doc, re.DOTALL) if result is not None: __input = result.group(2) for i in __input.split("\n"): arg_doc = ArgumentDoc(i) if arg_doc.name is not None: self.__input.append(arg_doc) result = re.search("Given and returned([^\n]*):\n(.+?) \n", self.doc, re.DOTALL) if result is not None: __input = result.group(2) for i in __input.split("\n"): arg_doc = ArgumentDoc(i) if arg_doc.name is not None: self.__input.append(arg_doc) return self.__input @property def output(self): if self.__output is None: self.__output = [] result = re.search("Returned([^\n]*):\n(.+?) \n", self.doc, re.DOTALL) if result is not None: __output = result.group(2) for i in __output.split("\n"): arg_doc = ArgumentDoc(i) if arg_doc.name is not None: self.__output.append(arg_doc) result = re.search("Given and returned([^\n]*):\n(.+?) \n", self.doc, re.DOTALL) if result is not None: __output = result.group(2) for i in __output.split("\n"): arg_doc = ArgumentDoc(i) if arg_doc.name is not None: self.__output.append(arg_doc) return self.__output @property def ret_info(self): if self.__ret_info is None: ret_info = [] result = re.search("Returned \\(function value\\)([^\n]*):\n(.+?) \n", self.doc, re.DOTALL) if result is not None: ret_info.append(ReturnDoc(result.group(2))) if len(ret_info) == 0: self.__ret_info = '' elif len(ret_info) == 1: self.__ret_info = ret_info[0] else: raise ValueError("Multiple C return sections found in this doc:\n" + self.doc) return self.__ret_info def __repr__(self): return self.doc.replace(" \n", "\n") class ArgumentDoc: def __init__(self, doc): match = re.search("^ +([^ ]+)[ ]+([^ ]+)[ ]+(.+)", doc) if match is not None: self.name = match.group(1) self.type = match.group(2) self.doc = match.group(3) else: self.name = None self.type = None self.doc = None def __repr__(self): return " {0:15} {1:15} {2}".format(self.name, self.type, self.doc) class Argument: def __init__(self, definition, doc): self.doc = doc self.__inout_state = None self.ctype, ptr_name_arr = definition.strip().rsplit(" ", 1) if "*" == ptr_name_arr[0]: self.is_ptr = True name_arr = ptr_name_arr[1:] else: self.is_ptr = False name_arr = ptr_name_arr if "[]" in ptr_name_arr: self.is_ptr = True name_arr = name_arr[:-2] if "[" in name_arr: self.name, arr = name_arr.split("[", 1) self.shape = tuple([int(size) for size in arr[:-1].split("][")]) else: self.name = name_arr self.shape = () @property def inout_state(self): if self.__inout_state is None: self.__inout_state = '' for i in self.doc.input: if self.name in i.name.split(','): self.__inout_state = 'in' for o in self.doc.output: if self.name in o.name.split(','): if self.__inout_state == 'in': self.__inout_state = 'inout' else: self.__inout_state = 'out' return self.__inout_state @property def ctype_ptr(self): if (self.is_ptr) | (len(self.shape) > 0): return self.ctype+" *" else: return self.ctype @property def name_in_broadcast(self): if len(self.shape) > 0: return "{0}_in[...{1}]".format(self.name, ",0"*len(self.shape)) else: return "{0}_in".format(self.name) @property def name_out_broadcast(self): if len(self.shape) > 0: return "{0}_out[...{1}]".format(self.name, ",0"*len(self.shape)) else: return "{0}_out".format(self.name) @property def dtype(self): return ctype_to_dtype[self.ctype] @property def ndim(self): return len(self.shape) @property def cshape(self): return ''.join(['[{0}]'.format(s) for s in self.shape]) @property def name_for_call(self): if self.is_ptr: return '_'+self.name else: return '*_'+self.name def __repr__(self): return "Argument('{0}', name='{1}', ctype='{2}', inout_state='{3}')".format(self.definition, self.name, self.ctype, self.inout_state) class ReturnDoc: def __init__(self, doc): self.doc = doc self.infoline = doc.split('\n')[0].strip() self.type = self.infoline.split()[0] self.descr = self.infoline.split()[1] if self.descr.startswith('status'): self.statuscodes = statuscodes = {} code = None for line in doc[doc.index(':')+1:].split('\n'): ls = line.strip() if ls != '': if ' = ' in ls: code, msg = ls.split(' = ') if code != 'else': code = int(code) statuscodes[code] = msg elif code is not None: statuscodes[code] += ls else: self.statuscodes = None def __repr__(self): return "Return value, type={0:15}, {1}, {2}".format(self.type, self.descr, self.doc) class Return: def __init__(self, ctype, doc): self.name = 'c_retval' self.name_out_broadcast = self.name+"_out" self.inout_state = 'stat' if ctype == 'int' else 'ret' self.ctype = ctype self.ctype_ptr = ctype self.shape = () self.doc = doc def __repr__(self): return "Return(name='{0}', ctype='{1}', inout_state='{2}')".format(self.name, self.ctype, self.inout_state) @property def dtype(self): return ctype_to_dtype[self.ctype] @property def nd_dtype(self): """ This if the return type has a multi-dimensional output, like double[3][3] """ return "'fi0'" in self.dtype @property def doc_info(self): return self.doc.ret_info class Function: """ A class representing a C function. Parameters ---------- name : str The name of the function source_path : str Either a directory, which means look for the function in a stand-alone file (like for the standard ERFA distribution), or a file, which means look for the function in that file (as for the astropy-packaged single-file erfa.c). match_line : str, optional If given, searching of the source file will skip until it finds a line matching this string, and start from there. """ def __init__(self, name, source_path, match_line=None): self.name = name self.pyname = name.split('era')[-1].lower() self.filename = self.pyname+".c" if os.path.isdir(source_path): self.filepath = os.path.join(os.path.normpath(source_path), self.filename) else: self.filepath = source_path with open(self.filepath) as f: if match_line: line = f.readline() while line != '': if line.startswith(match_line): filecontents = '\n' + line + f.read() break line = f.readline() else: msg = ('Could not find the match_line "{0}" in ' 'the source file "{1}"') raise ValueError(msg.format(match_line, self.filepath)) else: filecontents = f.read() pattern = r"\n([^\n]+{0} ?\([^)]+\)).+?(/\*.+?\*/)".format(name) p = re.compile(pattern, flags=re.DOTALL | re.MULTILINE) search = p.search(filecontents) self.cfunc = " ".join(search.group(1).split()) self.doc = FunctionDoc(search.group(2)) self.args = [] for arg in re.search(r"\(([^)]+)\)", self.cfunc).group(1).split(', '): self.args.append(Argument(arg, self.doc)) self.ret = re.search("^(.*){0}".format(name), self.cfunc).group(1).strip() if self.ret != 'void': self.args.append(Return(self.ret, self.doc)) def args_by_inout(self, inout_filter, prop=None, join=None): """ Gives all of the arguments and/or returned values, depending on whether they are inputs, outputs, etc. The value for `inout_filter` should be a string containing anything that arguments' `inout_state` attribute produces. Currently, that can be: * "in" : input * "out" : output * "inout" : something that's could be input or output (e.g. a struct) * "ret" : the return value of the C function * "stat" : the return value of the C function if it is a status code It can also be a "|"-separated string giving inout states to OR together. """ result = [] for arg in self.args: if arg.inout_state in inout_filter.split('|'): if prop is None: result.append(arg) else: result.append(getattr(arg, prop)) if join is not None: return join.join(result) else: return result def __repr__(self): return "Function(name='{0}', pyname='{1}', filename='{2}', filepath='{3}')".format(self.name, self.pyname, self.filename, self.filepath) class Constant: def __init__(self, name, value, doc): self.name = name.replace("ERFA_", "") self.value = value.replace("ERFA_", "") self.doc = doc class ExtraFunction(Function): """ An "extra" function - e.g. one not following the SOFA/ERFA standard format. Parameters ---------- cname : str The name of the function in C prototype : str The prototype for the function (usually derived from the header) pathfordoc : str The path to a file that contains the prototype, with the documentation as a multiline string *before* it. """ def __init__(self, cname, prototype, pathfordoc): self.name = cname self.pyname = cname.split('era')[-1].lower() self.filepath, self.filename = os.path.split(pathfordoc) self.prototype = prototype.strip() if prototype.endswith('{') or prototype.endswith(';'): self.prototype = prototype[:-1].strip() incomment = False lastcomment = None with open(pathfordoc, 'r') as f: for l in f: if incomment: if l.lstrip().startswith('*/'): incomment = False lastcomment = ''.join(lastcomment) else: if l.startswith('**'): l = l[2:] lastcomment.append(l) else: if l.lstrip().startswith('/*'): incomment = True lastcomment = [] if l.startswith(self.prototype): self.doc = lastcomment break else: raise ValueError('Did not find prototype {} in file ' '{}'.format(self.prototype, pathfordoc)) self.args = [] argset = re.search(r"{0}\(([^)]+)?\)".format(self.name), self.prototype).group(1) if argset is not None: for arg in argset.split(', '): self.args.append(Argument(arg, self.doc)) self.ret = re.match("^(.*){0}".format(self.name), self.prototype).group(1).strip() if self.ret != 'void': self.args.append(Return(self.ret, self.doc)) def __repr__(self): r = super().__repr__() if r.startswith('Function'): r = 'Extra' + r return r def main(srcdir, outfn, templateloc, verbose=True): from jinja2 import Environment, FileSystemLoader if verbose: print_ = lambda *args, **kwargs: print(*args, **kwargs) else: print_ = lambda *args, **kwargs: None # Prepare the jinja2 templating environment env = Environment(loader=FileSystemLoader(templateloc)) def prefix(a_list, pre): return [pre+'{0}'.format(an_element) for an_element in a_list] def postfix(a_list, post): return ['{0}'.format(an_element)+post for an_element in a_list] def surround(a_list, pre, post): return [pre+'{0}'.format(an_element)+post for an_element in a_list] env.filters['prefix'] = prefix env.filters['postfix'] = postfix env.filters['surround'] = surround erfa_c_in = env.get_template('core.c.templ') erfa_py_in = env.get_template('core.py.templ') # Extract all the ERFA function names from erfa.h if os.path.isdir(srcdir): erfahfn = os.path.join(srcdir, 'erfa.h') multifilserc = True else: erfahfn = os.path.join(os.path.split(srcdir)[0], 'erfa.h') multifilserc = False with open(erfahfn, "r") as f: erfa_h = f.read() funcs = OrderedDict() section_subsection_functions = re.findall(r'/\* (\w*)/(\w*) \*/\n(.*?)\n\n', erfa_h, flags=re.DOTALL | re.MULTILINE) for section, subsection, functions in section_subsection_functions: print_("{0}.{1}".format(section, subsection)) if ((section == "Astronomy") or (subsection == "AngleOps") or (subsection == "SphericalCartesian") or (subsection == "MatrixVectorProducts")): func_names = re.findall(r' (\w+)\(.*?\);', functions, flags=re.DOTALL) for name in func_names: print_("{0}.{1}.{2}...".format(section, subsection, name)) if multifilserc: # easy because it just looks in the file itself funcs[name] = Function(name, srcdir) else: # Have to tell it to look for a declaration matching # the start of the header declaration, otherwise it # might find a *call* of the function instead of the # definition for line in functions.split(r'\n'): if name in line: # [:-1] is to remove trailing semicolon, and # splitting on '(' is because the header and # C files don't necessarily have to match # argument names and line-breaking or # whitespace match_line = line[:-1].split('(')[0] funcs[name] = Function(name, srcdir, match_line) break else: raise ValueError("A name for a C file wasn't " "found in the string that " "spawned it. This should be " "impossible!") funcs = list(funcs.values()) # Extract all the ERFA constants from erfam.h erfamhfn = os.path.join(srcdir, 'erfam.h') with open(erfamhfn, 'r') as f: erfa_m_h = f.read() constants = [] for chunk in erfa_m_h.split("\n\n"): result = re.findall(r"#define (ERFA_\w+?) (.+?)$", chunk, flags=re.DOTALL | re.MULTILINE) if result: doc = re.findall(r"/\* (.+?) \*/\n", chunk, flags=re.DOTALL) for (name, value) in result: constants.append(Constant(name, value, doc)) # TODO: re-enable this when const char* return values and non-status code integer rets are possible # #Add in any "extra" functions from erfaextra.h # erfaextrahfn = os.path.join(srcdir, 'erfaextra.h') # with open(erfaextrahfn, 'r') as f: # for l in f: # ls = l.strip() # match = re.match('.* (era.*)\(', ls) # if match: # print_("Extra: {0} ...".format(match.group(1))) # funcs.append(ExtraFunction(match.group(1), ls, erfaextrahfn)) print_("Rendering template") erfa_c = erfa_c_in.render(funcs=funcs) erfa_py = erfa_py_in.render(funcs=funcs, constants=constants) if outfn is not None: outfn_c = os.path.splitext(outfn)[0] + ".c" print_("Saving to", outfn, 'and', outfn_c) with open(outfn, "w") as f: f.write(erfa_py) with open(outfn_c, "w") as f: f.write(erfa_c) print_("Done!") return erfa_c, erfa_py, funcs DEFAULT_ERFA_LOC = os.path.join(os.path.split(__file__)[0], '../../cextern/erfa') DEFAULT_TEMPLATE_LOC = os.path.split(__file__)[0] if __name__ == '__main__': from argparse import ArgumentParser ap = ArgumentParser() ap.add_argument('srcdir', default=DEFAULT_ERFA_LOC, nargs='?', help='Directory where the ERFA c and header files ' 'can be found or to a single erfa.c file ' '(which must be in the same directory as ' 'erfa.h). Defaults to the builtin astropy ' 'erfa: "{0}"'.format(DEFAULT_ERFA_LOC)) ap.add_argument('-o', '--output', default='core.py', help='The output filename. This is the name for only the ' 'pure-python output, the C part will have the ' 'same name but with a ".c" extension.') ap.add_argument('-t', '--template-loc', default=DEFAULT_TEMPLATE_LOC, help='the location where the "core.c.templ" ' 'template can be found.') ap.add_argument('-q', '--quiet', action='store_false', dest='verbose', help='Suppress output normally printed to stdout.') args = ap.parse_args() main(args.srcdir, args.output, args.template_loc)
8fd36b492cbee8454f9cbee7fd14dbb5892d80cc2e2a04325e905b9d67feb423
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import glob from distutils import log from distutils.extension import Extension from astropy_helpers import setup_helpers from astropy_helpers.version_helpers import get_pkg_version_module ERFAPKGDIR = os.path.relpath(os.path.dirname(__file__)) ERFA_SRC = os.path.abspath(os.path.join(ERFAPKGDIR, '..', '..', 'cextern', 'erfa')) SRC_FILES = glob.glob(os.path.join(ERFA_SRC, '*')) SRC_FILES += [os.path.join(ERFAPKGDIR, filename) for filename in ['core.py.templ', 'core.c.templ', 'erfa_generator.py']] GEN_FILES = [os.path.join(ERFAPKGDIR, 'core.py'), os.path.join(ERFAPKGDIR, 'core.c')] def pre_build_py_hook(cmd_obj): preprocess_source() def pre_build_ext_hook(cmd_obj): preprocess_source() def pre_sdist_hook(cmd_obj): preprocess_source() def preprocess_source(): # Generating the ERFA wrappers should only be done if needed. This also # ensures that it is not done for any release tarball since those will # include core.py and core.c. if all(os.path.exists(filename) for filename in GEN_FILES): # Determine modification times erfa_mtime = max(os.path.getmtime(filename) for filename in SRC_FILES) gen_mtime = min(os.path.getmtime(filename) for filename in GEN_FILES) version = get_pkg_version_module('astropy') if gen_mtime > erfa_mtime: # If generated source is recent enough, don't update return elif version.release: # or, if we're on a release, issue a warning, but go ahead and use # the wrappers anyway log.warn('WARNING: The autogenerated wrappers in astropy._erfa ' 'seem to be older than the source templates used to ' 'create them. Because this is a release version we will ' 'use them anyway, but this might be a sign of some sort ' 'of version mismatch or other tampering. Or it might just ' 'mean you moved some files around or otherwise ' 'accidentally changed timestamps.') return # otherwise rebuild the autogenerated files # If jinja2 isn't present, then print a warning and use existing files try: import jinja2 # pylint: disable=W0611 except ImportError: log.warn("WARNING: jinja2 could not be imported, so the existing " "ERFA core.py and core.c files will be used") return name = 'erfa_generator' filename = os.path.join(ERFAPKGDIR, 'erfa_generator.py') try: from importlib import machinery as import_machinery loader = import_machinery.SourceFileLoader(name, filename) gen = loader.load_module() except ImportError: import imp gen = imp.load_source(name, filename) gen.main(gen.DEFAULT_ERFA_LOC, os.path.join(ERFAPKGDIR, 'core.py'), gen.DEFAULT_TEMPLATE_LOC, verbose=False) def get_extensions(): sources = [os.path.join(ERFAPKGDIR, "core.c")] include_dirs = ['numpy'] libraries = [] if setup_helpers.use_system_library('erfa'): libraries.append('erfa') else: # get all of the .c files in the cextern/erfa directory erfafns = os.listdir(ERFA_SRC) sources.extend(['cextern/erfa/'+fn for fn in erfafns if fn.endswith('.c')]) include_dirs.append('cextern/erfa') erfa_ext = Extension( name="astropy._erfa._core", sources=sources, include_dirs=include_dirs, libraries=libraries, language="c",) return [erfa_ext] def get_external_libraries(): return ['erfa']
ed0831132c31d356d8a553e0e77a8845908e345ce33a94bcd684a87dc3e72ab8
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ .. _wcslib: http://www.atnf.csiro.au/people/mcalabre/WCS/wcslib/index.html .. _distortion paper: http://www.atnf.csiro.au/people/mcalabre/WCS/dcs_20040422.pdf .. _SIP: http://irsa.ipac.caltech.edu/data/SPITZER/docs/files/spitzer/shupeADASS.pdf .. _FITS WCS standard: https://fits.gsfc.nasa.gov/fits_wcs.html `astropy.wcs` contains utilities for managing World Coordinate System (WCS) transformations in FITS files. These transformations map the pixel locations in an image to their real-world units, such as their position on the sky sphere. It performs three separate classes of WCS transformations: - Core WCS, as defined in the `FITS WCS standard`_, based on Mark Calabretta's `wcslib`_. See `~astropy.wcs.Wcsprm`. - Simple Imaging Polynomial (`SIP`_) convention. See `~astropy.wcs.Sip`. - table lookup distortions as defined in WCS `distortion paper`_. See `~astropy.wcs.DistortionLookupTable`. Each of these transformations can be used independently or together in a standard pipeline. """ try: # Not guaranteed available at setup time from .wcs import * from . import utils except ImportError: if not _ASTROPY_SETUP_: raise def get_include(): """ Get the path to astropy.wcs's C header files. """ import os return os.path.join(os.path.dirname(__file__), "include")
c3d6fdb8592c828c9798928a53c34479ce97a51704c97b552887dc1e33304725
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ astropy.wcs-specific utilities for generating boilerplate in docstrings. """ __all__ = ['TWO_OR_THREE_ARGS', 'RETURNS', 'ORIGIN', 'RA_DEC_ORDER'] def _fix(content, indent=0): lines = content.split('\n') indent = '\n' + ' ' * indent return indent.join(lines) def TWO_OR_MORE_ARGS(naxis, indent=0): return _fix( """args : flexible There are two accepted forms for the positional arguments: - 2 arguments: An *N* x *{0}* array of coordinates, and an *origin*. - more than 2 arguments: An array for each axis, followed by an *origin*. These arrays must be broadcastable to one another. Here, *origin* is the coordinate in the upper left corner of the image. In FITS and Fortran standards, this is 1. In Numpy and C standards this is 0. """.format(naxis), indent) def RETURNS(out_type, indent=0): return _fix("""result : array Returns the {0}. If the input was a single array and origin, a single array is returned, otherwise a tuple of arrays is returned.""".format(out_type), indent) def ORIGIN(indent=0): return _fix( """ origin : int Specifies the origin of pixel values. The Fortran and FITS standards use an origin of 1. Numpy and C use array indexing with origin at 0. """, indent) def RA_DEC_ORDER(indent=0): return _fix( """ ra_dec_order : bool, optional When `True` will ensure that world coordinates are always given and returned in as (*ra*, *dec*) pairs, regardless of the order of the axes specified by the in the ``CTYPE`` keywords. Default is `False`. """, indent)
84009b489b3969e03a8f39075818ee1d874f3042b594bdf033a8ed38dca4715d
# Licensed under a 3-clause BSD style license - see LICENSE.rst CONTACT = "Michael Droettboom" EMAIL = "[email protected]" import io from os.path import join import os.path import shutil import sys from distutils.core import Extension from distutils.dep_util import newer_group from astropy_helpers import setup_helpers from astropy_helpers.distutils_helpers import get_distutils_build_option WCSROOT = os.path.relpath(os.path.dirname(__file__)) WCSVERSION = "5.18" def b(s): return s.encode('ascii') def string_escape(s): s = s.decode('ascii').encode('ascii', 'backslashreplace') s = s.replace(b'\n', b'\\n') s = s.replace(b'\0', b'\\0') return s.decode('ascii') def determine_64_bit_int(): """ The only configuration parameter needed at compile-time is how to specify a 64-bit signed integer. Python's ctypes module can get us that information. If we can't be absolutely certain, we default to "long long int", which is correct on most platforms (x86, x86_64). If we find platforms where this heuristic doesn't work, we may need to hardcode for them. """ try: try: import ctypes except ImportError: raise ValueError() if ctypes.sizeof(ctypes.c_longlong) == 8: return "long long int" elif ctypes.sizeof(ctypes.c_long) == 8: return "long int" elif ctypes.sizeof(ctypes.c_int) == 8: return "int" else: raise ValueError() except ValueError: return "long long int" def write_wcsconfig_h(paths): """ Writes out the wcsconfig.h header with local configuration. """ h_file = io.StringIO() h_file.write(""" /* The bundled version has WCSLIB_VERSION */ #define HAVE_WCSLIB_VERSION 1 /* WCSLIB library version number. */ #define WCSLIB_VERSION {0} /* 64-bit integer data type. */ #define WCSLIB_INT64 {1} /* Windows needs some other defines to prevent inclusion of wcsset() which conflicts with wcslib's wcsset(). These need to be set on code that *uses* astropy.wcs, in addition to astropy.wcs itself. */ #if defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) || defined (__MINGW64__) #ifndef YY_NO_UNISTD_H #define YY_NO_UNISTD_H #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _NO_OLDNAMES #define _NO_OLDNAMES #endif #ifndef NO_OLDNAMES #define NO_OLDNAMES #endif #ifndef __STDC__ #define __STDC__ 1 #endif #endif """.format(WCSVERSION, determine_64_bit_int())) content = h_file.getvalue().encode('ascii') for path in paths: setup_helpers.write_if_different(path, content) ###################################################################### # GENERATE DOCSTRINGS IN C def generate_c_docstrings(): from astropy.wcs import docstrings docstrings = docstrings.__dict__ keys = [ key for key, val in docstrings.items() if not key.startswith('__') and isinstance(val, str)] keys.sort() docs = {} for key in keys: docs[key] = docstrings[key].encode('utf8').lstrip() + b'\0' h_file = io.StringIO() h_file.write("""/* DO NOT EDIT! This file is autogenerated by astropy/wcs/setup_package.py. To edit its contents, edit astropy/wcs/docstrings.py */ #ifndef __DOCSTRINGS_H__ #define __DOCSTRINGS_H__ """) for key in keys: val = docs[key] h_file.write('extern char doc_{0}[{1}];\n'.format(key, len(val))) h_file.write("\n#endif\n\n") setup_helpers.write_if_different( join(WCSROOT, 'include', 'astropy_wcs', 'docstrings.h'), h_file.getvalue().encode('utf-8')) c_file = io.StringIO() c_file.write("""/* DO NOT EDIT! This file is autogenerated by astropy/wcs/setup_package.py. To edit its contents, edit astropy/wcs/docstrings.py The weirdness here with strncpy is because some C compilers, notably MSVC, do not support string literals greater than 256 characters. */ #include <string.h> #include "astropy_wcs/docstrings.h" """) for key in keys: val = docs[key] c_file.write('char doc_{0}[{1}] = {{\n'.format(key, len(val))) for i in range(0, len(val), 12): section = val[i:i+12] c_file.write(' ') c_file.write(''.join('0x{0:02x}, '.format(x) for x in section)) c_file.write('\n') c_file.write(" };\n\n") setup_helpers.write_if_different( join(WCSROOT, 'src', 'docstrings.c'), c_file.getvalue().encode('utf-8')) def get_wcslib_cfg(cfg, wcslib_files, include_paths): from astropy.version import debug cfg['include_dirs'].append('numpy') cfg['define_macros'].extend([ ('ECHO', None), ('WCSTRIG_MACRO', None), ('ASTROPY_WCS_BUILD', None), ('_GNU_SOURCE', None)]) if (not setup_helpers.use_system_library('wcslib') or sys.platform == 'win32'): write_wcsconfig_h(include_paths) wcslib_path = join("cextern", "wcslib") # Path to wcslib wcslib_cpath = join(wcslib_path, "C") # Path to wcslib source files cfg['sources'].extend(join(wcslib_cpath, x) for x in wcslib_files) cfg['include_dirs'].append(wcslib_cpath) else: wcsconfig_h_path = join(WCSROOT, 'include', 'wcsconfig.h') if os.path.exists(wcsconfig_h_path): os.unlink(wcsconfig_h_path) cfg.update(setup_helpers.pkg_config(['wcslib'], ['wcs'])) if debug: cfg['define_macros'].append(('DEBUG', None)) cfg['undef_macros'].append('NDEBUG') if (not sys.platform.startswith('sun') and not sys.platform == 'win32'): cfg['extra_compile_args'].extend(["-fno-inline", "-O0", "-g"]) else: # Define ECHO as nothing to prevent spurious newlines from # printing within the libwcs parser cfg['define_macros'].append(('NDEBUG', None)) cfg['undef_macros'].append('DEBUG') if sys.platform == 'win32': # These are written into wcsconfig.h, but that file is not # used by all parts of wcslib. cfg['define_macros'].extend([ ('YY_NO_UNISTD_H', None), ('_CRT_SECURE_NO_WARNINGS', None), ('_NO_OLDNAMES', None), # for mingw32 ('NO_OLDNAMES', None), # for mingw64 ('__STDC__', None) # for MSVC ]) if sys.platform.startswith('linux'): cfg['define_macros'].append(('HAVE_SINCOS', None)) # Squelch a few compilation warnings in WCSLIB if setup_helpers.get_compiler_option() in ('unix', 'mingw32'): if not get_distutils_build_option('debug'): cfg['extra_compile_args'].extend([ '-Wno-strict-prototypes', '-Wno-unused-function', '-Wno-unused-value', '-Wno-uninitialized']) def get_extensions(): generate_c_docstrings() ###################################################################### # DISTUTILS SETUP cfg = setup_helpers.DistutilsExtensionArgs() wcslib_files = [ # List of wcslib files to compile 'flexed/wcsbth.c', 'flexed/wcspih.c', 'flexed/wcsulex.c', 'flexed/wcsutrn.c', 'cel.c', 'dis.c', 'lin.c', 'log.c', 'prj.c', 'spc.c', 'sph.c', 'spx.c', 'tab.c', 'wcs.c', 'wcserr.c', 'wcsfix.c', 'wcshdr.c', 'wcsprintf.c', 'wcsunits.c', 'wcsutil.c' ] wcslib_config_paths = [ join(WCSROOT, 'include', 'astropy_wcs', 'wcsconfig.h'), join(WCSROOT, 'include', 'wcsconfig.h') ] get_wcslib_cfg(cfg, wcslib_files, wcslib_config_paths) cfg['include_dirs'].append(join(WCSROOT, "include")) astropy_wcs_files = [ # List of astropy.wcs files to compile 'distortion.c', 'distortion_wrap.c', 'docstrings.c', 'pipeline.c', 'pyutil.c', 'astropy_wcs.c', 'astropy_wcs_api.c', 'sip.c', 'sip_wrap.c', 'str_list_proxy.c', 'unit_list_proxy.c', 'util.c', 'wcslib_wrap.c', 'wcslib_tabprm_wrap.c'] cfg['sources'].extend(join(WCSROOT, 'src', x) for x in astropy_wcs_files) cfg['sources'] = [str(x) for x in cfg['sources']] cfg = dict((str(key), val) for key, val in cfg.items()) return [Extension(str('astropy.wcs._wcs'), **cfg)] def get_package_data(): # Installs the testing data files api_files = [ 'astropy_wcs.h', 'astropy_wcs_api.h', 'distortion.h', 'isnan.h', 'pipeline.h', 'pyutil.h', 'sip.h', 'util.h', 'wcsconfig.h', ] api_files = [join('include', 'astropy_wcs', x) for x in api_files] api_files.append(join('include', 'astropy_wcs_api.h')) wcslib_headers = [ 'cel.h', 'lin.h', 'prj.h', 'spc.h', 'spx.h', 'tab.h', 'wcs.h', 'wcserr.h', 'wcsmath.h', 'wcsprintf.h', ] if not setup_helpers.use_system_library('wcslib'): for header in wcslib_headers: source = join('cextern', 'wcslib', 'C', header) dest = join('astropy', 'wcs', 'include', 'wcslib', header) if newer_group([source], dest, 'newer'): shutil.copy(source, dest) api_files.append(join('include', 'wcslib', header)) return { str('astropy.wcs.tests'): ['data/*.hdr', 'data/*.fits', 'data/*.txt', 'data/*.fits.gz', 'maps/*.hdr', 'spectra/*.hdr', 'extension/*.c'], str('astropy.wcs'): api_files, } def get_external_libraries(): return ['wcslib']
faea432f172953f216c5cd889ea0aa5ae943460adea4d4360d0df48935492bc1
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from .. import units as u from .wcs import WCS, WCSSUB_CELESTIAL __doctest_skip__ = ['wcs_to_celestial_frame', 'celestial_frame_to_wcs'] __all__ = ['add_stokes_axis_to_wcs', 'celestial_frame_to_wcs', 'wcs_to_celestial_frame', 'proj_plane_pixel_scales', 'proj_plane_pixel_area', 'is_proj_plane_distorted', 'non_celestial_pixel_scales', 'skycoord_to_pixel', 'pixel_to_skycoord', 'custom_wcs_to_frame_mappings', 'custom_frame_to_wcs_mappings'] def add_stokes_axis_to_wcs(wcs, add_before_ind): """ Add a new Stokes axis that is uncorrelated with any other axes. Parameters ---------- wcs : `~astropy.wcs.WCS` The WCS to add to add_before_ind : int Index of the WCS to insert the new Stokes axis in front of. To add at the end, do add_before_ind = wcs.wcs.naxis The beginning is at position 0. Returns ------- A new `~astropy.wcs.WCS` instance with an additional axis """ inds = [i + 1 for i in range(wcs.wcs.naxis)] inds.insert(add_before_ind, 0) newwcs = wcs.sub(inds) newwcs.wcs.ctype[add_before_ind] = 'STOKES' newwcs.wcs.cname[add_before_ind] = 'STOKES' return newwcs def _wcs_to_celestial_frame_builtin(wcs): # Import astropy.coordinates here to avoid circular imports from ..coordinates import FK4, FK4NoETerms, FK5, ICRS, Galactic # Import astropy.time here otherwise setup.py fails before extensions are compiled from ..time import Time # Keep only the celestial part of the axes wcs = wcs.sub([WCSSUB_CELESTIAL]) if wcs.wcs.lng == -1 or wcs.wcs.lat == -1: return None radesys = wcs.wcs.radesys if np.isnan(wcs.wcs.equinox): equinox = None else: equinox = wcs.wcs.equinox xcoord = wcs.wcs.ctype[0][:4] ycoord = wcs.wcs.ctype[1][:4] # Apply logic from FITS standard to determine the default radesys if radesys == '' and xcoord == 'RA--' and ycoord == 'DEC-': if equinox is None: radesys = "ICRS" elif equinox < 1984.: radesys = "FK4" else: radesys = "FK5" if radesys == 'FK4': if equinox is not None: equinox = Time(equinox, format='byear') frame = FK4(equinox=equinox) elif radesys == 'FK4-NO-E': if equinox is not None: equinox = Time(equinox, format='byear') frame = FK4NoETerms(equinox=equinox) elif radesys == 'FK5': if equinox is not None: equinox = Time(equinox, format='jyear') frame = FK5(equinox=equinox) elif radesys == 'ICRS': frame = ICRS() else: if xcoord == 'GLON' and ycoord == 'GLAT': frame = Galactic() else: frame = None return frame def _celestial_frame_to_wcs_builtin(frame, projection='TAN'): # Import astropy.coordinates here to avoid circular imports from ..coordinates import BaseRADecFrame, FK4, FK4NoETerms, FK5, ICRS, Galactic # Create a 2-dimensional WCS wcs = WCS(naxis=2) if isinstance(frame, BaseRADecFrame): xcoord = 'RA--' ycoord = 'DEC-' if isinstance(frame, ICRS): wcs.wcs.radesys = 'ICRS' elif isinstance(frame, FK4NoETerms): wcs.wcs.radesys = 'FK4-NO-E' wcs.wcs.equinox = frame.equinox.byear elif isinstance(frame, FK4): wcs.wcs.radesys = 'FK4' wcs.wcs.equinox = frame.equinox.byear elif isinstance(frame, FK5): wcs.wcs.radesys = 'FK5' wcs.wcs.equinox = frame.equinox.jyear else: return None elif isinstance(frame, Galactic): xcoord = 'GLON' ycoord = 'GLAT' else: return None wcs.wcs.ctype = [xcoord + '-' + projection, ycoord + '-' + projection] return wcs WCS_FRAME_MAPPINGS = [[_wcs_to_celestial_frame_builtin]] FRAME_WCS_MAPPINGS = [[_celestial_frame_to_wcs_builtin]] class custom_wcs_to_frame_mappings: def __init__(self, mappings=[]): if hasattr(mappings, '__call__'): mappings = [mappings] WCS_FRAME_MAPPINGS.append(mappings) def __enter__(self): pass def __exit__(self, type, value, tb): WCS_FRAME_MAPPINGS.pop() # Backward-compatibility custom_frame_mappings = custom_wcs_to_frame_mappings class custom_frame_to_wcs_mappings: def __init__(self, mappings=[]): if hasattr(mappings, '__call__'): mappings = [mappings] FRAME_WCS_MAPPINGS.append(mappings) def __enter__(self): pass def __exit__(self, type, value, tb): FRAME_WCS_MAPPINGS.pop() def wcs_to_celestial_frame(wcs): """ For a given WCS, return the coordinate frame that matches the celestial component of the WCS. Parameters ---------- wcs : :class:`~astropy.wcs.WCS` instance The WCS to find the frame for Returns ------- frame : :class:`~astropy.coordinates.baseframe.BaseCoordinateFrame` subclass instance An instance of a :class:`~astropy.coordinates.baseframe.BaseCoordinateFrame` subclass instance that best matches the specified WCS. Notes ----- To extend this function to frames not defined in astropy.coordinates, you can write your own function which should take a :class:`~astropy.wcs.WCS` instance and should return either an instance of a frame, or `None` if no matching frame was found. You can register this function temporarily with:: >>> from astropy.wcs.utils import wcs_to_celestial_frame, custom_wcs_to_frame_mappings >>> with custom_wcs_to_frame_mappings(my_function): ... wcs_to_celestial_frame(...) """ for mapping_set in WCS_FRAME_MAPPINGS: for func in mapping_set: frame = func(wcs) if frame is not None: return frame raise ValueError("Could not determine celestial frame corresponding to " "the specified WCS object") def celestial_frame_to_wcs(frame, projection='TAN'): """ For a given coordinate frame, return the corresponding WCS object. Note that the returned WCS object has only the elements corresponding to coordinate frames set (e.g. ctype, equinox, radesys). Parameters ---------- frame : :class:`~astropy.coordinates.baseframe.BaseCoordinateFrame` subclass instance An instance of a :class:`~astropy.coordinates.baseframe.BaseCoordinateFrame` subclass instance for which to find the WCS projection : str Projection code to use in ctype, if applicable Returns ------- wcs : :class:`~astropy.wcs.WCS` instance The corresponding WCS object Examples -------- :: >>> from astropy.wcs.utils import celestial_frame_to_wcs >>> from astropy.coordinates import FK5 >>> frame = FK5(equinox='J2010') >>> wcs = celestial_frame_to_wcs(frame) >>> wcs.to_header() WCSAXES = 2 / Number of coordinate axes CRPIX1 = 0.0 / Pixel coordinate of reference point CRPIX2 = 0.0 / Pixel coordinate of reference point CDELT1 = 1.0 / [deg] Coordinate increment at reference point CDELT2 = 1.0 / [deg] Coordinate increment at reference point CUNIT1 = 'deg' / Units of coordinate increment and value CUNIT2 = 'deg' / Units of coordinate increment and value CTYPE1 = 'RA---TAN' / Right ascension, gnomonic projection CTYPE2 = 'DEC--TAN' / Declination, gnomonic projection CRVAL1 = 0.0 / [deg] Coordinate value at reference point CRVAL2 = 0.0 / [deg] Coordinate value at reference point LONPOLE = 180.0 / [deg] Native longitude of celestial pole LATPOLE = 0.0 / [deg] Native latitude of celestial pole RADESYS = 'FK5' / Equatorial coordinate system EQUINOX = 2010.0 / [yr] Equinox of equatorial coordinates Notes ----- To extend this function to frames not defined in astropy.coordinates, you can write your own function which should take a :class:`~astropy.coordinates.baseframe.BaseCoordinateFrame` subclass instance and a projection (given as a string) and should return either a WCS instance, or `None` if the WCS could not be determined. You can register this function temporarily with:: >>> from astropy.wcs.utils import celestial_frame_to_wcs, custom_frame_to_wcs_mappings >>> with custom_frame_to_wcs_mappings(my_function): ... celestial_frame_to_wcs(...) """ for mapping_set in FRAME_WCS_MAPPINGS: for func in mapping_set: wcs = func(frame, projection=projection) if wcs is not None: return wcs raise ValueError("Could not determine WCS corresponding to the specified " "coordinate frame.") def proj_plane_pixel_scales(wcs): """ For a WCS returns pixel scales along each axis of the image pixel at the ``CRPIX`` location once it is projected onto the "plane of intermediate world coordinates" as defined in `Greisen & Calabretta 2002, A&A, 395, 1061 <http://adsabs.harvard.edu/abs/2002A%26A...395.1061G>`_. .. note:: This function is concerned **only** about the transformation "image plane"->"projection plane" and **not** about the transformation "celestial sphere"->"projection plane"->"image plane". Therefore, this function ignores distortions arising due to non-linear nature of most projections. .. note:: In order to compute the scales corresponding to celestial axes only, make sure that the input `~astropy.wcs.WCS` object contains celestial axes only, e.g., by passing in the `~astropy.wcs.WCS.celestial` WCS object. Parameters ---------- wcs : `~astropy.wcs.WCS` A world coordinate system object. Returns ------- scale : `~numpy.ndarray` A vector (`~numpy.ndarray`) of projection plane increments corresponding to each pixel side (axis). The units of the returned results are the same as the units of `~astropy.wcs.Wcsprm.cdelt`, `~astropy.wcs.Wcsprm.crval`, and `~astropy.wcs.Wcsprm.cd` for the celestial WCS and can be obtained by inquiring the value of `~astropy.wcs.Wcsprm.cunit` property of the input `~astropy.wcs.WCS` WCS object. See Also -------- astropy.wcs.utils.proj_plane_pixel_area """ return np.sqrt((wcs.pixel_scale_matrix**2).sum(axis=0, dtype=float)) def proj_plane_pixel_area(wcs): """ For a **celestial** WCS (see `astropy.wcs.WCS.celestial`) returns pixel area of the image pixel at the ``CRPIX`` location once it is projected onto the "plane of intermediate world coordinates" as defined in `Greisen & Calabretta 2002, A&A, 395, 1061 <http://adsabs.harvard.edu/abs/2002A%26A...395.1061G>`_. .. note:: This function is concerned **only** about the transformation "image plane"->"projection plane" and **not** about the transformation "celestial sphere"->"projection plane"->"image plane". Therefore, this function ignores distortions arising due to non-linear nature of most projections. .. note:: In order to compute the area of pixels corresponding to celestial axes only, this function uses the `~astropy.wcs.WCS.celestial` WCS object of the input ``wcs``. This is different from the `~astropy.wcs.utils.proj_plane_pixel_scales` function that computes the scales for the axes of the input WCS itself. Parameters ---------- wcs : `~astropy.wcs.WCS` A world coordinate system object. Returns ------- area : float Area (in the projection plane) of the pixel at ``CRPIX`` location. The units of the returned result are the same as the units of the `~astropy.wcs.Wcsprm.cdelt`, `~astropy.wcs.Wcsprm.crval`, and `~astropy.wcs.Wcsprm.cd` for the celestial WCS and can be obtained by inquiring the value of `~astropy.wcs.Wcsprm.cunit` property of the `~astropy.wcs.WCS.celestial` WCS object. Raises ------ ValueError Pixel area is defined only for 2D pixels. Most likely the `~astropy.wcs.Wcsprm.cd` matrix of the `~astropy.wcs.WCS.celestial` WCS is not a square matrix of second order. Notes ----- Depending on the application, square root of the pixel area can be used to represent a single pixel scale of an equivalent square pixel whose area is equal to the area of a generally non-square pixel. See Also -------- astropy.wcs.utils.proj_plane_pixel_scales """ psm = wcs.celestial.pixel_scale_matrix if psm.shape != (2, 2): raise ValueError("Pixel area is defined only for 2D pixels.") return np.abs(np.linalg.det(psm)) def is_proj_plane_distorted(wcs, maxerr=1.0e-5): r""" For a WCS returns `False` if square image (detector) pixels stay square when projected onto the "plane of intermediate world coordinates" as defined in `Greisen & Calabretta 2002, A&A, 395, 1061 <http://adsabs.harvard.edu/abs/2002A%26A...395.1061G>`_. It will return `True` if transformation from image (detector) coordinates to the focal plane coordinates is non-orthogonal or if WCS contains non-linear (e.g., SIP) distortions. .. note:: Since this function is concerned **only** about the transformation "image plane"->"focal plane" and **not** about the transformation "celestial sphere"->"focal plane"->"image plane", this function ignores distortions arising due to non-linear nature of most projections. Let's denote by *C* either the original or the reconstructed (from ``PC`` and ``CDELT``) CD matrix. `is_proj_plane_distorted` verifies that the transformation from image (detector) coordinates to the focal plane coordinates is orthogonal using the following check: .. math:: \left \| \frac{C \cdot C^{\mathrm{T}}} {| det(C)|} - I \right \|_{\mathrm{max}} < \epsilon . Parameters ---------- wcs : `~astropy.wcs.WCS` World coordinate system object maxerr : float, optional Accuracy to which the CD matrix, **normalized** such that :math:`|det(CD)|=1`, should be close to being an orthogonal matrix as described in the above equation (see :math:`\epsilon`). Returns ------- distorted : bool Returns `True` if focal (projection) plane is distorted and `False` otherwise. """ cwcs = wcs.celestial return (not _is_cd_orthogonal(cwcs.pixel_scale_matrix, maxerr) or _has_distortion(cwcs)) def _is_cd_orthogonal(cd, maxerr): shape = cd.shape if not (len(shape) == 2 and shape[0] == shape[1]): raise ValueError("CD (or PC) matrix must be a 2D square matrix.") pixarea = np.abs(np.linalg.det(cd)) if (pixarea == 0.0): raise ValueError("CD (or PC) matrix is singular.") # NOTE: Technically, below we should use np.dot(cd, np.conjugate(cd.T)) # However, I am not aware of complex CD/PC matrices... I = np.dot(cd, cd.T) / pixarea cd_unitary_err = np.amax(np.abs(I - np.eye(shape[0]))) return (cd_unitary_err < maxerr) def non_celestial_pixel_scales(inwcs): """ Calculate the pixel scale along each axis of a non-celestial WCS, for example one with mixed spectral and spatial axes. Parameters ---------- inwcs : `~astropy.wcs.WCS` The world coordinate system object. Returns ------- scale : `numpy.ndarray` The pixel scale along each axis. """ if inwcs.is_celestial: raise ValueError("WCS is celestial, use celestial_pixel_scales instead") pccd = inwcs.pixel_scale_matrix if np.allclose(np.extract(1-np.eye(*pccd.shape), pccd), 0): return np.abs(np.diagonal(pccd))*u.deg else: raise ValueError("WCS is rotated, cannot determine consistent pixel scales") def _has_distortion(wcs): """ `True` if contains any SIP or image distortion components. """ return any(getattr(wcs, dist_attr) is not None for dist_attr in ['cpdis1', 'cpdis2', 'det2im1', 'det2im2', 'sip']) # TODO: in future, we should think about how the following two functions can be # integrated better into the WCS class. def skycoord_to_pixel(coords, wcs, origin=0, mode='all'): """ Convert a set of SkyCoord coordinates into pixels. Parameters ---------- coords : `~astropy.coordinates.SkyCoord` The coordinates to convert. wcs : `~astropy.wcs.WCS` The WCS transformation to use. origin : int Whether to return 0 or 1-based pixel coordinates. mode : 'all' or 'wcs' Whether to do the transformation including distortions (``'all'``) or only including only the core WCS transformation (``'wcs'``). Returns ------- xp, yp : `numpy.ndarray` The pixel coordinates See Also -------- astropy.coordinates.SkyCoord.from_pixel """ if _has_distortion(wcs) and wcs.naxis != 2: raise ValueError("Can only handle WCS with distortions for 2-dimensional WCS") # Keep only the celestial part of the axes, also re-orders lon/lat wcs = wcs.sub([WCSSUB_CELESTIAL]) if wcs.naxis != 2: raise ValueError("WCS should contain celestial component") # Check which frame the WCS uses frame = wcs_to_celestial_frame(wcs) # Check what unit the WCS needs xw_unit = u.Unit(wcs.wcs.cunit[0]) yw_unit = u.Unit(wcs.wcs.cunit[1]) # Convert positions to frame coords = coords.transform_to(frame) # Extract longitude and latitude. We first try and use lon/lat directly, # but if the representation is not spherical or unit spherical this will # fail. We should then force the use of the unit spherical # representation. We don't do that directly to make sure that we preserve # custom lon/lat representations if available. try: lon = coords.data.lon.to(xw_unit) lat = coords.data.lat.to(yw_unit) except AttributeError: lon = coords.spherical.lon.to(xw_unit) lat = coords.spherical.lat.to(yw_unit) # Convert to pixel coordinates if mode == 'all': xp, yp = wcs.all_world2pix(lon.value, lat.value, origin) elif mode == 'wcs': xp, yp = wcs.wcs_world2pix(lon.value, lat.value, origin) else: raise ValueError("mode should be either 'all' or 'wcs'") return xp, yp def pixel_to_skycoord(xp, yp, wcs, origin=0, mode='all', cls=None): """ Convert a set of pixel coordinates into a `~astropy.coordinates.SkyCoord` coordinate. Parameters ---------- xp, yp : float or `numpy.ndarray` The coordinates to convert. wcs : `~astropy.wcs.WCS` The WCS transformation to use. origin : int Whether to return 0 or 1-based pixel coordinates. mode : 'all' or 'wcs' Whether to do the transformation including distortions (``'all'``) or only including only the core WCS transformation (``'wcs'``). cls : class or None The class of object to create. Should be a `~astropy.coordinates.SkyCoord` subclass. If None, defaults to `~astropy.coordinates.SkyCoord`. Returns ------- coords : Whatever ``cls`` is (a subclass of `~astropy.coordinates.SkyCoord`) The celestial coordinates See Also -------- astropy.coordinates.SkyCoord.from_pixel """ # Import astropy.coordinates here to avoid circular imports from ..coordinates import SkyCoord, UnitSphericalRepresentation # we have to do this instead of actually setting the default to SkyCoord # because importing SkyCoord at the module-level leads to circular # dependencies. if cls is None: cls = SkyCoord if _has_distortion(wcs) and wcs.naxis != 2: raise ValueError("Can only handle WCS with distortions for 2-dimensional WCS") # Keep only the celestial part of the axes, also re-orders lon/lat wcs = wcs.sub([WCSSUB_CELESTIAL]) if wcs.naxis != 2: raise ValueError("WCS should contain celestial component") # Check which frame the WCS uses frame = wcs_to_celestial_frame(wcs) # Check what unit the WCS gives lon_unit = u.Unit(wcs.wcs.cunit[0]) lat_unit = u.Unit(wcs.wcs.cunit[1]) # Convert pixel coordinates to celestial coordinates if mode == 'all': lon, lat = wcs.all_pix2world(xp, yp, origin) elif mode == 'wcs': lon, lat = wcs.wcs_pix2world(xp, yp, origin) else: raise ValueError("mode should be either 'all' or 'wcs'") # Add units to longitude/latitude lon = lon * lon_unit lat = lat * lat_unit # Create a SkyCoord-like object data = UnitSphericalRepresentation(lon=lon, lat=lat) coords = cls(frame.realize_frame(data)) return coords
687f6500bb8853d61bfd95e99f92cacccb159e218af3efc6e1dadca5283b5622
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Under the hood, there are 3 separate classes that perform different parts of the transformation: - `~astropy.wcs.Wcsprm`: Is a direct wrapper of the core WCS functionality in `wcslib`_. (This includes TPV and TPD polynomial distortion, but not SIP distortion). - `~astropy.wcs.Sip`: Handles polynomial distortion as defined in the `SIP`_ convention. - `~astropy.wcs.DistortionLookupTable`: Handles `distortion paper`_ lookup tables. Additionally, the class `WCS` aggregates all of these transformations together in a pipeline: - Detector to image plane correction (by a pair of `~astropy.wcs.DistortionLookupTable` objects). - `SIP`_ distortion correction (by an underlying `~astropy.wcs.Sip` object) - `distortion paper`_ table-lookup correction (by a pair of `~astropy.wcs.DistortionLookupTable` objects). - `wcslib`_ WCS transformation (by a `~astropy.wcs.Wcsprm` object) """ # STDLIB import copy import io import itertools import os import re import textwrap import warnings import builtins # THIRD-PARTY import numpy as np # LOCAL from .. import log from ..io import fits from . import _docutil as __ try: from . import _wcs except ImportError: if not _ASTROPY_SETUP_: raise else: _wcs = None from ..utils.compat import possible_filename from ..utils.exceptions import AstropyWarning, AstropyUserWarning, AstropyDeprecationWarning __all__ = ['FITSFixedWarning', 'WCS', 'find_all_wcs', 'DistortionLookupTable', 'Sip', 'Tabprm', 'Wcsprm', 'WCSBase', 'validate', 'WcsError', 'SingularMatrixError', 'InconsistentAxisTypesError', 'InvalidTransformError', 'InvalidCoordinateError', 'NoSolutionError', 'InvalidSubimageSpecificationError', 'NoConvergence', 'NonseparableSubimageCoordinateSystemError', 'NoWcsKeywordsFoundError', 'InvalidTabularParametersError'] __doctest_skip__ = ['WCS.all_world2pix'] if _wcs is not None: _parsed_version = _wcs.__version__.split('.') if int(_parsed_version[0]) == 5 and int(_parsed_version[1]) < 8: raise ImportError( "astropy.wcs is built with wcslib {0}, but only versions 5.8 and " "later on the 5.x series are known to work. The version of wcslib " "that ships with astropy may be used.") if not _wcs._sanity_check(): raise RuntimeError( "astropy.wcs did not pass its sanity check for your build " "on your platform.") WCSBase = _wcs._Wcs DistortionLookupTable = _wcs.DistortionLookupTable Sip = _wcs.Sip Wcsprm = _wcs.Wcsprm Tabprm = _wcs.Tabprm WcsError = _wcs.WcsError SingularMatrixError = _wcs.SingularMatrixError InconsistentAxisTypesError = _wcs.InconsistentAxisTypesError InvalidTransformError = _wcs.InvalidTransformError InvalidCoordinateError = _wcs.InvalidCoordinateError NoSolutionError = _wcs.NoSolutionError InvalidSubimageSpecificationError = _wcs.InvalidSubimageSpecificationError NonseparableSubimageCoordinateSystemError = _wcs.NonseparableSubimageCoordinateSystemError NoWcsKeywordsFoundError = _wcs.NoWcsKeywordsFoundError InvalidTabularParametersError = _wcs.InvalidTabularParametersError # Copy all the constants from the C extension into this module's namespace for key, val in _wcs.__dict__.items(): if key.startswith(('WCSSUB', 'WCSHDR', 'WCSHDO')): locals()[key] = val __all__.append(key) else: WCSBase = object Wcsprm = object DistortionLookupTable = object Sip = object Tabprm = object WcsError = None SingularMatrixError = None InconsistentAxisTypesError = None InvalidTransformError = None InvalidCoordinateError = None NoSolutionError = None InvalidSubimageSpecificationError = None NonseparableSubimageCoordinateSystemError = None NoWcsKeywordsFoundError = None InvalidTabularParametersError = None # Additional relax bit flags WCSHDO_SIP = 0x80000 # Regular expression defining SIP keyword It matches keyword that starts with A # or B, optionally followed by P, followed by an underscore then a number in # range of 0-19, followed by an underscore and another number in range of 0-19. # Keyword optionally ends with a capital letter. SIP_KW = re.compile('''^[AB]P?_1?[0-9]_1?[0-9][A-Z]?$''') def _parse_keysel(keysel): keysel_flags = 0 if keysel is not None: for element in keysel: if element.lower() == 'image': keysel_flags |= _wcs.WCSHDR_IMGHEAD elif element.lower() == 'binary': keysel_flags |= _wcs.WCSHDR_BIMGARR elif element.lower() == 'pixel': keysel_flags |= _wcs.WCSHDR_PIXLIST else: raise ValueError( "keysel must be a list of 'image', 'binary' " + "and/or 'pixel'") else: keysel_flags = -1 return keysel_flags class NoConvergence(Exception): """ An error class used to report non-convergence and/or divergence of numerical methods. It is used to report errors in the iterative solution used by the :py:meth:`~astropy.wcs.WCS.all_world2pix`. Attributes ---------- best_solution : `numpy.ndarray` Best solution achieved by the numerical method. accuracy : `numpy.ndarray` Accuracy of the ``best_solution``. niter : `int` Number of iterations performed by the numerical method to compute ``best_solution``. divergent : None, `numpy.ndarray` Indices of the points in ``best_solution`` array for which the solution appears to be divergent. If the solution does not diverge, ``divergent`` will be set to `None`. slow_conv : None, `numpy.ndarray` Indices of the solutions in ``best_solution`` array for which the solution failed to converge within the specified maximum number of iterations. If there are no non-converging solutions (i.e., if the required accuracy has been achieved for all input data points) then ``slow_conv`` will be set to `None`. """ def __init__(self, *args, best_solution=None, accuracy=None, niter=None, divergent=None, slow_conv=None, **kwargs): super().__init__(*args) self.best_solution = best_solution self.accuracy = accuracy self.niter = niter self.divergent = divergent self.slow_conv = slow_conv if kwargs: warnings.warn("Function received unexpected arguments ({}) these " "are ignored but will raise an Exception in the " "future.".format(list(kwargs)), AstropyDeprecationWarning) class FITSFixedWarning(AstropyWarning): """ The warning raised when the contents of the FITS header have been modified to be standards compliant. """ pass class WCS(WCSBase): """WCS objects perform standard WCS transformations, and correct for `SIP`_ and `distortion paper`_ table-lookup transformations, based on the WCS keywords and supplementary data read from a FITS file. Parameters ---------- header : astropy.io.fits header object, Primary HDU, Image HDU, string, dict-like, or None, optional If *header* is not provided or None, the object will be initialized to default values. fobj : An astropy.io.fits file (hdulist) object, optional It is needed when header keywords point to a `distortion paper`_ lookup table stored in a different extension. key : str, optional The name of a particular WCS transform to use. This may be either ``' '`` or ``'A'``-``'Z'`` and corresponds to the ``\"a\"`` part of the ``CTYPEia`` cards. *key* may only be provided if *header* is also provided. minerr : float, optional The minimum value a distortion correction must have in order to be applied. If the value of ``CQERRja`` is smaller than *minerr*, the corresponding distortion is not applied. relax : bool or int, optional Degree of permissiveness: - `True` (default): Admit all recognized informal extensions of the WCS standard. - `False`: Recognize only FITS keywords defined by the published WCS standard. - `int`: a bit field selecting specific extensions to accept. See :ref:`relaxread` for details. naxis : int or sequence, optional Extracts specific coordinate axes using :meth:`~astropy.wcs.Wcsprm.sub`. If a header is provided, and *naxis* is not ``None``, *naxis* will be passed to :meth:`~astropy.wcs.Wcsprm.sub` in order to select specific axes from the header. See :meth:`~astropy.wcs.Wcsprm.sub` for more details about this parameter. keysel : sequence of flags, optional A sequence of flags used to select the keyword types considered by wcslib. When ``None``, only the standard image header keywords are considered (and the underlying wcspih() C function is called). To use binary table image array or pixel list keywords, *keysel* must be set. Each element in the list should be one of the following strings: - 'image': Image header keywords - 'binary': Binary table image array keywords - 'pixel': Pixel list keywords Keywords such as ``EQUIna`` or ``RFRQna`` that are common to binary table image arrays and pixel lists (including ``WCSNna`` and ``TWCSna``) are selected by both 'binary' and 'pixel'. colsel : sequence of int, optional A sequence of table column numbers used to restrict the WCS transformations considered to only those pertaining to the specified columns. If `None`, there is no restriction. fix : bool, optional When `True` (default), call `~astropy.wcs.Wcsprm.fix` on the resulting object to fix any non-standard uses in the header. `FITSFixedWarning` Warnings will be emitted if any changes were made. translate_units : str, optional Specify which potentially unsafe translations of non-standard unit strings to perform. By default, performs none. See `WCS.fix` for more information about this parameter. Only effective when ``fix`` is `True`. Raises ------ MemoryError Memory allocation failed. ValueError Invalid key. KeyError Key not found in FITS header. ValueError Lookup table distortion present in the header but *fobj* was not provided. Notes ----- 1. astropy.wcs supports arbitrary *n* dimensions for the core WCS (the transformations handled by WCSLIB). However, the `distortion paper`_ lookup table and `SIP`_ distortions must be two dimensional. Therefore, if you try to create a WCS object where the core WCS has a different number of dimensions than 2 and that object also contains a `distortion paper`_ lookup table or `SIP`_ distortion, a `ValueError` exception will be raised. To avoid this, consider using the *naxis* kwarg to select two dimensions from the core WCS. 2. The number of coordinate axes in the transformation is not determined directly from the ``NAXIS`` keyword but instead from the highest of: - ``NAXIS`` keyword - ``WCSAXESa`` keyword - The highest axis number in any parameterized WCS keyword. The keyvalue, as well as the keyword, must be syntactically valid otherwise it will not be considered. If none of these keyword types is present, i.e. if the header only contains auxiliary WCS keywords for a particular coordinate representation, then no coordinate description is constructed for it. The number of axes, which is set as the ``naxis`` member, may differ for different coordinate representations of the same image. 3. When the header includes duplicate keywords, in most cases the last encountered is used. 4. `~astropy.wcs.Wcsprm.set` is called immediately after construction, so any invalid keywords or transformations will be raised by the constructor, not when subsequently calling a transformation method. """ def __init__(self, header=None, fobj=None, key=' ', minerr=0.0, relax=True, naxis=None, keysel=None, colsel=None, fix=True, translate_units='', _do_set=True): close_fds = [] if header is None: if naxis is None: naxis = 2 wcsprm = _wcs.Wcsprm(header=None, key=key, relax=relax, naxis=naxis) self.naxis = wcsprm.naxis # Set some reasonable defaults. det2im = (None, None) cpdis = (None, None) sip = None else: keysel_flags = _parse_keysel(keysel) if isinstance(header, (str, bytes)): try: is_path = (possible_filename(header) and os.path.exists(header)) except (OSError, ValueError): is_path = False if is_path: if fobj is not None: raise ValueError( "Can not provide both a FITS filename to " "argument 1 and a FITS file object to argument 2") fobj = fits.open(header) close_fds.append(fobj) header = fobj[0].header elif isinstance(header, fits.hdu.image._ImageBaseHDU): header = header.header elif not isinstance(header, fits.Header): try: # Accept any dict-like object orig_header = header header = fits.Header() for dict_key in orig_header.keys(): header[dict_key] = orig_header[dict_key] except TypeError: raise TypeError( "header must be a string, an astropy.io.fits.Header " "object, or a dict-like object") if isinstance(header, fits.Header): header_string = header.tostring().rstrip() else: header_string = header # Importantly, header is a *copy* of the passed-in header # because we will be modifying it if isinstance(header_string, str): header_bytes = header_string.encode('ascii') header_string = header_string else: header_bytes = header_string header_string = header_string.decode('ascii') try: tmp_header = fits.Header.fromstring(header_string) self._remove_sip_kw(tmp_header) tmp_header_bytes = tmp_header.tostring().rstrip() if isinstance(tmp_header_bytes, str): tmp_header_bytes = tmp_header_bytes.encode('ascii') tmp_wcsprm = _wcs.Wcsprm(header=tmp_header_bytes, key=key, relax=relax, keysel=keysel_flags, colsel=colsel, warnings=False) except _wcs.NoWcsKeywordsFoundError: est_naxis = 0 else: if naxis is not None: try: tmp_wcsprm.sub(naxis) except ValueError: pass est_naxis = tmp_wcsprm.naxis else: est_naxis = 2 header = fits.Header.fromstring(header_string) if est_naxis == 0: est_naxis = 2 self.naxis = est_naxis det2im = self._read_det2im_kw(header, fobj, err=minerr) cpdis = self._read_distortion_kw( header, fobj, dist='CPDIS', err=minerr) sip = self._read_sip_kw(header, wcskey=key) self._remove_sip_kw(header) header_string = header.tostring() header_string = header_string.replace('END' + ' ' * 77, '') if isinstance(header_string, str): header_bytes = header_string.encode('ascii') header_string = header_string else: header_bytes = header_string header_string = header_string.decode('ascii') try: wcsprm = _wcs.Wcsprm(header=header_bytes, key=key, relax=relax, keysel=keysel_flags, colsel=colsel) except _wcs.NoWcsKeywordsFoundError: # The header may have SIP or distortions, but no core # WCS. That isn't an error -- we want a "default" # (identity) core Wcs transformation in that case. if colsel is None: wcsprm = _wcs.Wcsprm(header=None, key=key, relax=relax, keysel=keysel_flags, colsel=colsel) else: raise if naxis is not None: wcsprm = wcsprm.sub(naxis) self.naxis = wcsprm.naxis if (wcsprm.naxis != 2 and (det2im[0] or det2im[1] or cpdis[0] or cpdis[1] or sip)): raise ValueError( """ FITS WCS distortion paper lookup tables and SIP distortions only work in 2 dimensions. However, WCSLIB has detected {0} dimensions in the core WCS keywords. To use core WCS in conjunction with FITS WCS distortion paper lookup tables or SIP distortion, you must select or reduce these to 2 dimensions using the naxis kwarg. """.format(wcsprm.naxis)) header_naxis = header.get('NAXIS', None) if header_naxis is not None and header_naxis < wcsprm.naxis: warnings.warn( "The WCS transformation has more axes ({0:d}) than the " "image it is associated with ({1:d})".format( wcsprm.naxis, header_naxis), FITSFixedWarning) self._get_naxis(header) WCSBase.__init__(self, sip, cpdis, wcsprm, det2im) if fix: self.fix(translate_units=translate_units) if _do_set: self.wcs.set() for fd in close_fds: fd.close() def __copy__(self): new_copy = self.__class__() WCSBase.__init__(new_copy, self.sip, (self.cpdis1, self.cpdis2), self.wcs, (self.det2im1, self.det2im2)) new_copy.__dict__.update(self.__dict__) return new_copy def __deepcopy__(self, memo): from copy import deepcopy new_copy = self.__class__() new_copy.naxis = deepcopy(self.naxis, memo) WCSBase.__init__(new_copy, deepcopy(self.sip, memo), (deepcopy(self.cpdis1, memo), deepcopy(self.cpdis2, memo)), deepcopy(self.wcs, memo), (deepcopy(self.det2im1, memo), deepcopy(self.det2im2, memo))) for key, val in self.__dict__.items(): new_copy.__dict__[key] = deepcopy(val, memo) return new_copy def copy(self): """ Return a shallow copy of the object. Convenience method so user doesn't have to import the :mod:`copy` stdlib module. .. warning:: Use `deepcopy` instead of `copy` unless you know why you need a shallow copy. """ return copy.copy(self) def deepcopy(self): """ Return a deep copy of the object. Convenience method so user doesn't have to import the :mod:`copy` stdlib module. """ return copy.deepcopy(self) def sub(self, axes=None): copy = self.deepcopy() copy.wcs = self.wcs.sub(axes) copy.naxis = copy.wcs.naxis return copy if _wcs is not None: sub.__doc__ = _wcs.Wcsprm.sub.__doc__ def _fix_scamp(self): """ Remove SCAMP's PVi_m distortion parameters if SIP distortion parameters are also present. Some projects (e.g., Palomar Transient Factory) convert SCAMP's distortion parameters (which abuse the PVi_m cards) to SIP. However, wcslib gets confused by the presence of both SCAMP and SIP distortion parameters. See https://github.com/astropy/astropy/issues/299. """ # Nothing to be done if no WCS attached if self.wcs is None: return # Nothing to be done if no PV parameters attached pv = self.wcs.get_pv() if not pv: return # Nothing to be done if axes don't use SIP distortion parameters if self.sip is None: return # Nothing to be done if any radial terms are present... # Loop over list to find any radial terms. # Certain values of the `j' index are used for storing # radial terms; refer to Equation (1) in # <http://web.ipac.caltech.edu/staff/shupe/reprints/SIP_to_PV_SPIE2012.pdf>. pv = np.asarray(pv) # Loop over distinct values of `i' index for i in set(pv[:, 0]): # Get all values of `j' index for this value of `i' index js = set(pv[:, 1][pv[:, 0] == i]) # Find max value of `j' index max_j = max(js) for j in (3, 11, 23, 39): if j < max_j and j in js: return self.wcs.set_pv([]) warnings.warn("Removed redundant SCAMP distortion parameters " + "because SIP parameters are also present", FITSFixedWarning) def fix(self, translate_units='', naxis=None): """ Perform the fix operations from wcslib, and warn about any changes it has made. Parameters ---------- translate_units : str, optional Specify which potentially unsafe translations of non-standard unit strings to perform. By default, performs none. Although ``"S"`` is commonly used to represent seconds, its translation to ``"s"`` is potentially unsafe since the standard recognizes ``"S"`` formally as Siemens, however rarely that may be used. The same applies to ``"H"`` for hours (Henry), and ``"D"`` for days (Debye). This string controls what to do in such cases, and is case-insensitive. - If the string contains ``"s"``, translate ``"S"`` to ``"s"``. - If the string contains ``"h"``, translate ``"H"`` to ``"h"``. - If the string contains ``"d"``, translate ``"D"`` to ``"d"``. Thus ``''`` doesn't do any unsafe translations, whereas ``'shd'`` does all of them. naxis : int array[naxis], optional Image axis lengths. If this array is set to zero or ``None``, then `~astropy.wcs.Wcsprm.cylfix` will not be invoked. """ if self.wcs is not None: self._fix_scamp() fixes = self.wcs.fix(translate_units, naxis) for key, val in fixes.items(): if val != "No change": warnings.warn( ("'{0}' made the change '{1}'."). format(key, val), FITSFixedWarning) def calc_footprint(self, header=None, undistort=True, axes=None, center=True): """ Calculates the footprint of the image on the sky. A footprint is defined as the positions of the corners of the image on the sky after all available distortions have been applied. Parameters ---------- header : `~astropy.io.fits.Header` object, optional Used to get ``NAXIS1`` and ``NAXIS2`` header and axes are mutually exclusive, alternative ways to provide the same information. undistort : bool, optional If `True`, take SIP and distortion lookup table into account axes : length 2 sequence ints, optional If provided, use the given sequence as the shape of the image. Otherwise, use the ``NAXIS1`` and ``NAXIS2`` keywords from the header that was used to create this `WCS` object. center : bool, optional If `True` use the center of the pixel, otherwise use the corner. Returns ------- coord : (4, 2) array of (*x*, *y*) coordinates. The order is clockwise starting with the bottom left corner. """ if axes is not None: naxis1, naxis2 = axes else: if header is None: try: # classes that inherit from WCS and define naxis1/2 # do not require a header parameter naxis1 = self._naxis1 naxis2 = self._naxis2 except AttributeError: warnings.warn("Need a valid header in order to calculate footprint\n", AstropyUserWarning) return None else: naxis1 = header.get('NAXIS1', None) naxis2 = header.get('NAXIS2', None) if naxis1 is None or naxis2 is None: raise ValueError( "Image size could not be determined.") if center: corners = np.array([[1, 1], [1, naxis2], [naxis1, naxis2], [naxis1, 1]], dtype=np.float64) else: corners = np.array([[0.5, 0.5], [0.5, naxis2 + 0.5], [naxis1 + 0.5, naxis2 + 0.5], [naxis1 + 0.5, 0.5]], dtype=np.float64) if undistort: return self.all_pix2world(corners, 1) else: return self.wcs_pix2world(corners, 1) def _read_det2im_kw(self, header, fobj, err=0.0): """ Create a `distortion paper`_ type lookup table for detector to image plane correction. """ if fobj is None: return (None, None) if not isinstance(fobj, fits.HDUList): return (None, None) try: axiscorr = header[str('AXISCORR')] d2imdis = self._read_d2im_old_format(header, fobj, axiscorr) return d2imdis except KeyError: pass dist = 'D2IMDIS' d_kw = 'D2IM' err_kw = 'D2IMERR' tables = {} for i in range(1, self.naxis + 1): d_error = header.get(err_kw + str(i), 0.0) if d_error < err: tables[i] = None continue distortion = dist + str(i) if distortion in header: dis = header[distortion].lower() if dis == 'lookup': del header[distortion] assert isinstance(fobj, fits.HDUList), ('An astropy.io.fits.HDUList' 'is required for Lookup table distortion.') dp = (d_kw + str(i)).strip() dp_extver_key = dp + str('.EXTVER') if dp_extver_key in header: d_extver = header[dp_extver_key] del header[dp_extver_key] else: d_extver = 1 dp_axis_key = dp + str('.AXIS.{0:d}').format(i) if i == header[dp_axis_key]: d_data = fobj[str('D2IMARR'), d_extver].data else: d_data = (fobj[str('D2IMARR'), d_extver].data).transpose() del header[dp_axis_key] d_header = fobj[str('D2IMARR'), d_extver].header d_crpix = (d_header.get(str('CRPIX1'), 0.0), d_header.get(str('CRPIX2'), 0.0)) d_crval = (d_header.get(str('CRVAL1'), 0.0), d_header.get(str('CRVAL2'), 0.0)) d_cdelt = (d_header.get(str('CDELT1'), 1.0), d_header.get(str('CDELT2'), 1.0)) d_lookup = DistortionLookupTable(d_data, d_crpix, d_crval, d_cdelt) tables[i] = d_lookup else: warnings.warn('Polynomial distortion is not implemented.\n', AstropyUserWarning) for key in list(header): if key.startswith(dp + str('.')): del header[key] else: tables[i] = None if not tables: return (None, None) else: return (tables.get(1), tables.get(2)) def _read_d2im_old_format(self, header, fobj, axiscorr): warnings.warn("The use of ``AXISCORR`` for D2IM correction has been deprecated." "`~astropy.wcs` will read in files with ``AXISCORR`` but ``to_fits()`` will write " "out files without it.", AstropyDeprecationWarning) cpdis = [None, None] crpix = [0., 0.] crval = [0., 0.] cdelt = [1., 1.] try: d2im_data = fobj[(str('D2IMARR'), 1)].data except KeyError: return (None, None) except AttributeError: return (None, None) d2im_data = np.array([d2im_data]) d2im_hdr = fobj[(str('D2IMARR'), 1)].header naxis = d2im_hdr[str('NAXIS')] for i in range(1, naxis + 1): crpix[i - 1] = d2im_hdr.get(str('CRPIX') + str(i), 0.0) crval[i - 1] = d2im_hdr.get(str('CRVAL') + str(i), 0.0) cdelt[i - 1] = d2im_hdr.get(str('CDELT') + str(i), 1.0) cpdis = DistortionLookupTable(d2im_data, crpix, crval, cdelt) if axiscorr == 1: return (cpdis, None) elif axiscorr == 2: return (None, cpdis) else: warnings.warn("Expected AXISCORR to be 1 or 2", AstropyUserWarning) return (None, None) def _write_det2im(self, hdulist): """ Writes a `distortion paper`_ type lookup table to the given `astropy.io.fits.HDUList`. """ if self.det2im1 is None and self.det2im2 is None: return dist = 'D2IMDIS' d_kw = 'D2IM' err_kw = 'D2IMERR' def write_d2i(num, det2im): if det2im is None: return str('{0}{1:d}').format(dist, num), hdulist[0].header[str('{0}{1:d}').format(dist, num)] = ( 'LOOKUP', 'Detector to image correction type') hdulist[0].header[str('{0}{1:d}.EXTVER').format(d_kw, num)] = ( num, 'Version number of WCSDVARR extension') hdulist[0].header[str('{0}{1:d}.NAXES').format(d_kw, num)] = ( len(det2im.data.shape), 'Number of independent variables in d2im function') for i in range(det2im.data.ndim): hdulist[0].header[str('{0}{1:d}.AXIS.{2:d}').format(d_kw, num, i + 1)] = ( i + 1, 'Axis number of the jth independent variable in a d2im function') image = fits.ImageHDU(det2im.data, name=str('D2IMARR')) header = image.header header[str('CRPIX1')] = (det2im.crpix[0], 'Coordinate system reference pixel') header[str('CRPIX2')] = (det2im.crpix[1], 'Coordinate system reference pixel') header[str('CRVAL1')] = (det2im.crval[0], 'Coordinate system value at reference pixel') header[str('CRVAL2')] = (det2im.crval[1], 'Coordinate system value at reference pixel') header[str('CDELT1')] = (det2im.cdelt[0], 'Coordinate increment along axis') header[str('CDELT2')] = (det2im.cdelt[1], 'Coordinate increment along axis') image.ver = int(hdulist[0].header[str('{0}{1:d}.EXTVER').format(d_kw, num)]) hdulist.append(image) write_d2i(1, self.det2im1) write_d2i(2, self.det2im2) def _read_distortion_kw(self, header, fobj, dist='CPDIS', err=0.0): """ Reads `distortion paper`_ table-lookup keywords and data, and returns a 2-tuple of `~astropy.wcs.DistortionLookupTable` objects. If no `distortion paper`_ keywords are found, ``(None, None)`` is returned. """ if isinstance(header, (str, bytes)): return (None, None) if dist == 'CPDIS': d_kw = str('DP') err_kw = str('CPERR') else: d_kw = str('DQ') err_kw = str('CQERR') tables = {} for i in range(1, self.naxis + 1): d_error_key = err_kw + str(i) if d_error_key in header: d_error = header[d_error_key] del header[d_error_key] else: d_error = 0.0 if d_error < err: tables[i] = None continue distortion = dist + str(i) if distortion in header: dis = header[distortion].lower() del header[distortion] if dis == 'lookup': if not isinstance(fobj, fits.HDUList): raise ValueError('an astropy.io.fits.HDUList is ' 'required for Lookup table distortion.') dp = (d_kw + str(i)).strip() dp_extver_key = dp + str('.EXTVER') if dp_extver_key in header: d_extver = header[dp_extver_key] del header[dp_extver_key] else: d_extver = 1 dp_axis_key = dp + str('.AXIS.{0:d}'.format(i)) if i == header[dp_axis_key]: d_data = fobj[str('WCSDVARR'), d_extver].data else: d_data = (fobj[str('WCSDVARR'), d_extver].data).transpose() del header[dp_axis_key] d_header = fobj[str('WCSDVARR'), d_extver].header d_crpix = (d_header.get(str('CRPIX1'), 0.0), d_header.get(str('CRPIX2'), 0.0)) d_crval = (d_header.get(str('CRVAL1'), 0.0), d_header.get(str('CRVAL2'), 0.0)) d_cdelt = (d_header.get(str('CDELT1'), 1.0), d_header.get(str('CDELT2'), 1.0)) d_lookup = DistortionLookupTable(d_data, d_crpix, d_crval, d_cdelt) tables[i] = d_lookup for key in list(header): if key.startswith(dp + str('.')): del header[key] else: warnings.warn('Polynomial distortion is not implemented.\n', AstropyUserWarning) else: tables[i] = None if not tables: return (None, None) else: return (tables.get(1), tables.get(2)) def _write_distortion_kw(self, hdulist, dist='CPDIS'): """ Write out `distortion paper`_ keywords to the given `fits.HDUList`. """ if self.cpdis1 is None and self.cpdis2 is None: return if dist == 'CPDIS': d_kw = str('DP') err_kw = str('CPERR') else: d_kw = str('DQ') err_kw = str('CQERR') def write_dist(num, cpdis): if cpdis is None: return hdulist[0].header[str('{0}{1:d}').format(dist, num)] = ( 'LOOKUP', 'Prior distortion function type') hdulist[0].header[str('{0}{1:d}.EXTVER').format(d_kw, num)] = ( num, 'Version number of WCSDVARR extension') hdulist[0].header[str('{0}{1:d}.NAXES').format(d_kw, num)] = ( len(cpdis.data.shape), 'Number of independent variables in distortion function') for i in range(cpdis.data.ndim): hdulist[0].header[str('{0}{1:d}.AXIS.{2:d}').format(d_kw, num, i + 1)] = ( i + 1, 'Axis number of the jth independent variable in a distortion function') image = fits.ImageHDU(cpdis.data, name=str('WCSDVARR')) header = image.header header[str('CRPIX1')] = (cpdis.crpix[0], 'Coordinate system reference pixel') header[str('CRPIX2')] = (cpdis.crpix[1], 'Coordinate system reference pixel') header[str('CRVAL1')] = (cpdis.crval[0], 'Coordinate system value at reference pixel') header[str('CRVAL2')] = (cpdis.crval[1], 'Coordinate system value at reference pixel') header[str('CDELT1')] = (cpdis.cdelt[0], 'Coordinate increment along axis') header[str('CDELT2')] = (cpdis.cdelt[1], 'Coordinate increment along axis') image.ver = int(hdulist[0].header[str('{0}{1:d}.EXTVER').format(d_kw, num)]) hdulist.append(image) write_dist(1, self.cpdis1) write_dist(2, self.cpdis2) def _remove_sip_kw(self, header): """ Remove SIP information from a header. """ # Never pass SIP coefficients to wcslib # CTYPE must be passed with -SIP to wcslib for key in (m.group() for m in map(SIP_KW.match, list(header)) if m is not None): del header[key] def _read_sip_kw(self, header, wcskey=""): """ Reads `SIP`_ header keywords and returns a `~astropy.wcs.Sip` object. If no `SIP`_ header keywords are found, ``None`` is returned. """ if isinstance(header, (str, bytes)): # TODO: Parse SIP from a string without pyfits around return None if str("A_ORDER") in header and header[str('A_ORDER')] > 1: if str("B_ORDER") not in header: raise ValueError( "A_ORDER provided without corresponding B_ORDER " "keyword for SIP distortion") m = int(header[str("A_ORDER")]) a = np.zeros((m + 1, m + 1), np.double) for i in range(m + 1): for j in range(m - i + 1): key = str("A_{0}_{1}").format(i, j) if key in header: a[i, j] = header[key] del header[key] m = int(header[str("B_ORDER")]) if m > 1: b = np.zeros((m + 1, m + 1), np.double) for i in range(m + 1): for j in range(m - i + 1): key = str("B_{0}_{1}").format(i, j) if key in header: b[i, j] = header[key] del header[key] else: a = None b = None del header[str('A_ORDER')] del header[str('B_ORDER')] ctype = [header['CTYPE{0}{1}'.format(nax, wcskey)] for nax in range(1, self.naxis + 1)] if any(not ctyp.endswith('-SIP') for ctyp in ctype): message = """ Inconsistent SIP distortion information is present in the FITS header and the WCS object: SIP coefficients were detected, but CTYPE is missing a "-SIP" suffix. astropy.wcs is using the SIP distortion coefficients, therefore the coordinates calculated here might be incorrect. If you do not want to apply the SIP distortion coefficients, please remove the SIP coefficients from the FITS header or the WCS object. As an example, if the image is already distortion-corrected (e.g., drizzled) then distortion components should not apply and the SIP coefficients should be removed. While the SIP distortion coefficients are being applied here, if that was indeed the intent, for consistency please append "-SIP" to the CTYPE in the FITS header or the WCS object. """ log.info(message) elif str("B_ORDER") in header and header[str('B_ORDER')] > 1: raise ValueError( "B_ORDER provided without corresponding A_ORDER " + "keyword for SIP distortion") else: a = None b = None if str("AP_ORDER") in header and header[str('AP_ORDER')] > 1: if str("BP_ORDER") not in header: raise ValueError( "AP_ORDER provided without corresponding BP_ORDER " "keyword for SIP distortion") m = int(header[str("AP_ORDER")]) ap = np.zeros((m + 1, m + 1), np.double) for i in range(m + 1): for j in range(m - i + 1): key = str("AP_{0}_{1}").format(i, j) if key in header: ap[i, j] = header[key] del header[key] m = int(header[str("BP_ORDER")]) if m > 1: bp = np.zeros((m + 1, m + 1), np.double) for i in range(m + 1): for j in range(m - i + 1): key = str("BP_{0}_{1}").format(i, j) if key in header: bp[i, j] = header[key] del header[key] else: ap = None bp = None del header[str('AP_ORDER')] del header[str('BP_ORDER')] elif str("BP_ORDER") in header and header[str('BP_ORDER')] > 1: raise ValueError( "BP_ORDER provided without corresponding AP_ORDER " "keyword for SIP distortion") else: ap = None bp = None if a is None and b is None and ap is None and bp is None: return None if str("CRPIX1{0}".format(wcskey)) not in header or str("CRPIX2{0}".format(wcskey)) not in header: raise ValueError( "Header has SIP keywords without CRPIX keywords") crpix1 = header.get("CRPIX1{0}".format(wcskey)) crpix2 = header.get("CRPIX2{0}".format(wcskey)) return Sip(a, b, ap, bp, (crpix1, crpix2)) def _write_sip_kw(self): """ Write out SIP keywords. Returns a dictionary of key-value pairs. """ if self.sip is None: return {} keywords = {} def write_array(name, a): if a is None: return size = a.shape[0] keywords[str('{0}_ORDER').format(name)] = size - 1 for i in range(size): for j in range(size - i): if a[i, j] != 0.0: keywords[ str('{0}_{1:d}_{2:d}').format(name, i, j)] = a[i, j] write_array(str('A'), self.sip.a) write_array(str('B'), self.sip.b) write_array(str('AP'), self.sip.ap) write_array(str('BP'), self.sip.bp) return keywords def _denormalize_sky(self, sky): if self.wcs.lngtyp != 'RA': raise ValueError( "WCS does not have longitude type of 'RA', therefore " + "(ra, dec) data can not be used as input") if self.wcs.lattyp != 'DEC': raise ValueError( "WCS does not have longitude type of 'DEC', therefore " + "(ra, dec) data can not be used as input") if self.wcs.naxis == 2: if self.wcs.lng == 0 and self.wcs.lat == 1: return sky elif self.wcs.lng == 1 and self.wcs.lat == 0: # Reverse the order of the columns return sky[:, ::-1] else: raise ValueError( "WCS does not have longitude and latitude celestial " + "axes, therefore (ra, dec) data can not be used as input") else: if self.wcs.lng < 0 or self.wcs.lat < 0: raise ValueError( "WCS does not have both longitude and latitude " "celestial axes, therefore (ra, dec) data can not be " + "used as input") out = np.zeros((sky.shape[0], self.wcs.naxis)) out[:, self.wcs.lng] = sky[:, 0] out[:, self.wcs.lat] = sky[:, 1] return out def _normalize_sky(self, sky): if self.wcs.lngtyp != 'RA': raise ValueError( "WCS does not have longitude type of 'RA', therefore " + "(ra, dec) data can not be returned") if self.wcs.lattyp != 'DEC': raise ValueError( "WCS does not have longitude type of 'DEC', therefore " + "(ra, dec) data can not be returned") if self.wcs.naxis == 2: if self.wcs.lng == 0 and self.wcs.lat == 1: return sky elif self.wcs.lng == 1 and self.wcs.lat == 0: # Reverse the order of the columns return sky[:, ::-1] else: raise ValueError( "WCS does not have longitude and latitude celestial " "axes, therefore (ra, dec) data can not be returned") else: if self.wcs.lng < 0 or self.wcs.lat < 0: raise ValueError( "WCS does not have both longitude and latitude celestial " "axes, therefore (ra, dec) data can not be returned") out = np.empty((sky.shape[0], 2)) out[:, 0] = sky[:, self.wcs.lng] out[:, 1] = sky[:, self.wcs.lat] return out def _array_converter(self, func, sky, *args, ra_dec_order=False): """ A helper function to support reading either a pair of arrays or a single Nx2 array. """ def _return_list_of_arrays(axes, origin): try: axes = np.broadcast_arrays(*axes) except ValueError: raise ValueError( "Coordinate arrays are not broadcastable to each other") xy = np.hstack([x.reshape((x.size, 1)) for x in axes]) if ra_dec_order and sky == 'input': xy = self._denormalize_sky(xy) output = func(xy, origin) if ra_dec_order and sky == 'output': output = self._normalize_sky(output) return (output[:, 0].reshape(axes[0].shape), output[:, 1].reshape(axes[0].shape)) return [output[:, i].reshape(axes[0].shape) for i in range(output.shape[1])] def _return_single_array(xy, origin): if xy.shape[-1] != self.naxis: raise ValueError( "When providing two arguments, the array must be " "of shape (N, {0})".format(self.naxis)) if ra_dec_order and sky == 'input': xy = self._denormalize_sky(xy) result = func(xy, origin) if ra_dec_order and sky == 'output': result = self._normalize_sky(result) return result if len(args) == 2: try: xy, origin = args xy = np.asarray(xy) origin = int(origin) except Exception: raise TypeError( "When providing two arguments, they must be " "(coords[N][{0}], origin)".format(self.naxis)) if self.naxis == 1 and len(xy.shape) == 1: return _return_list_of_arrays([xy], origin) return _return_single_array(xy, origin) elif len(args) == self.naxis + 1: axes = args[:-1] origin = args[-1] try: axes = [np.asarray(x) for x in axes] origin = int(origin) except Exception: raise TypeError( "When providing more than two arguments, they must be " + "a 1-D array for each axis, followed by an origin.") return _return_list_of_arrays(axes, origin) raise TypeError( "WCS projection has {0} dimensions, so expected 2 (an Nx{0} array " "and the origin argument) or {1} arguments (the position in each " "dimension, and the origin argument). Instead, {2} arguments were " "given.".format( self.naxis, self.naxis + 1, len(args))) def all_pix2world(self, *args, **kwargs): return self._array_converter( self._all_pix2world, 'output', *args, **kwargs) all_pix2world.__doc__ = """ Transforms pixel coordinates to world coordinates. Performs all of the following in series: - Detector to image plane correction (if present in the FITS file) - `SIP`_ distortion correction (if present in the FITS file) - `distortion paper`_ table-lookup correction (if present in the FITS file) - `wcslib`_ "core" WCS transformation Parameters ---------- {0} For a transformation that is not two-dimensional, the two-argument form must be used. {1} Returns ------- {2} Notes ----- The order of the axes for the result is determined by the ``CTYPEia`` keywords in the FITS header, therefore it may not always be of the form (*ra*, *dec*). The `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`, `~astropy.wcs.Wcsprm.lattyp` and `~astropy.wcs.Wcsprm.lngtyp` members can be used to determine the order of the axes. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. ValueError Invalid coordinate transformation parameters. ValueError x- and y-coordinate arrays are not the same size. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. """.format(__.TWO_OR_MORE_ARGS('naxis', 8), __.RA_DEC_ORDER(8), __.RETURNS('sky coordinates, in degrees', 8)) def wcs_pix2world(self, *args, **kwargs): if self.wcs is None: raise ValueError("No basic WCS settings were created.") return self._array_converter( lambda xy, o: self.wcs.p2s(xy, o)['world'], 'output', *args, **kwargs) wcs_pix2world.__doc__ = """ Transforms pixel coordinates to world coordinates by doing only the basic `wcslib`_ transformation. No `SIP`_ or `distortion paper`_ table lookup correction is applied. To perform distortion correction, see `~astropy.wcs.WCS.all_pix2world`, `~astropy.wcs.WCS.sip_pix2foc`, `~astropy.wcs.WCS.p4_pix2foc`, or `~astropy.wcs.WCS.pix2foc`. Parameters ---------- {0} For a transformation that is not two-dimensional, the two-argument form must be used. {1} Returns ------- {2} Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. ValueError Invalid coordinate transformation parameters. ValueError x- and y-coordinate arrays are not the same size. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. Notes ----- The order of the axes for the result is determined by the ``CTYPEia`` keywords in the FITS header, therefore it may not always be of the form (*ra*, *dec*). The `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`, `~astropy.wcs.Wcsprm.lattyp` and `~astropy.wcs.Wcsprm.lngtyp` members can be used to determine the order of the axes. """.format(__.TWO_OR_MORE_ARGS('naxis', 8), __.RA_DEC_ORDER(8), __.RETURNS('world coordinates, in degrees', 8)) def _all_world2pix(self, world, origin, tolerance, maxiter, adaptive, detect_divergence, quiet): # ############################################################ # # DESCRIPTION OF THE NUMERICAL METHOD ## # ############################################################ # In this section I will outline the method of solving # the inverse problem of converting world coordinates to # pixel coordinates (*inverse* of the direct transformation # `all_pix2world`) and I will summarize some of the aspects # of the method proposed here and some of the issues of the # original `all_world2pix` (in relation to this method) # discussed in https://github.com/astropy/astropy/issues/1977 # A more detailed discussion can be found here: # https://github.com/astropy/astropy/pull/2373 # # # ### Background ### # # # I will refer here to the [SIP Paper] # (http://fits.gsfc.nasa.gov/registry/sip/SIP_distortion_v1_0.pdf). # According to this paper, the effect of distortions as # described in *their* equation (1) is: # # (1) x = CD*(u+f(u)), # # where `x` is a *vector* of "intermediate spherical # coordinates" (equivalent to (x,y) in the paper) and `u` # is a *vector* of "pixel coordinates", and `f` is a vector # function describing geometrical distortions # (see equations 2 and 3 in SIP Paper. # However, I prefer to use `w` for "intermediate world # coordinates", `x` for pixel coordinates, and assume that # transformation `W` performs the **linear** # (CD matrix + projection onto celestial sphere) part of the # conversion from pixel coordinates to world coordinates. # Then we can re-write (1) as: # # (2) w = W*(x+f(x)) = T(x) # # In `astropy.wcs.WCS` transformation `W` is represented by # the `wcs_pix2world` member, while the combined ("total") # transformation (linear part + distortions) is performed by # `all_pix2world`. Below I summarize the notations and their # equivalents in `astropy.wcs.WCS`: # # | Equation term | astropy.WCS/meaning | # | ------------- | ---------------------------- | # | `x` | pixel coordinates | # | `w` | world coordinates | # | `W` | `wcs_pix2world()` | # | `W^{-1}` | `wcs_world2pix()` | # | `T` | `all_pix2world()` | # | `x+f(x)` | `pix2foc()` | # # # ### Direct Solving of Equation (2) ### # # # In order to find the pixel coordinates that correspond to # given world coordinates `w`, it is necessary to invert # equation (2): `x=T^{-1}(w)`, or solve equation `w==T(x)` # for `x`. However, this approach has the following # disadvantages: # 1. It requires unnecessary transformations (see next # section). # 2. It is prone to "RA wrapping" issues as described in # https://github.com/astropy/astropy/issues/1977 # (essentially because `all_pix2world` may return points with # a different phase than user's input `w`). # # # ### Description of the Method Used here ### # # # By applying inverse linear WCS transformation (`W^{-1}`) # to both sides of equation (2) and introducing notation `x'` # (prime) for the pixels coordinates obtained from the world # coordinates by applying inverse *linear* WCS transformation # ("focal plane coordinates"): # # (3) x' = W^{-1}(w) # # we obtain the following equation: # # (4) x' = x+f(x), # # or, # # (5) x = x'-f(x) # # This equation is well suited for solving using the method # of fixed-point iterations # (http://en.wikipedia.org/wiki/Fixed-point_iteration): # # (6) x_{i+1} = x'-f(x_i) # # As an initial value of the pixel coordinate `x_0` we take # "focal plane coordinate" `x'=W^{-1}(w)=wcs_world2pix(w)`. # We stop iterations when `|x_{i+1}-x_i|<tolerance`. We also # consider the process to be diverging if # `|x_{i+1}-x_i|>|x_i-x_{i-1}|` # **when** `|x_{i+1}-x_i|>=tolerance` (when current # approximation is close to the true solution, # `|x_{i+1}-x_i|>|x_i-x_{i-1}|` may be due to rounding errors # and we ignore such "divergences" when # `|x_{i+1}-x_i|<tolerance`). It may appear that checking for # `|x_{i+1}-x_i|<tolerance` in order to ignore divergence is # unnecessary since the iterative process should stop anyway, # however, the proposed implementation of this iterative # process is completely vectorized and, therefore, we may # continue iterating over *some* points even though they have # converged to within a specified tolerance (while iterating # over other points that have not yet converged to # a solution). # # In order to efficiently implement iterative process (6) # using available methods in `astropy.wcs.WCS`, we add and # subtract `x_i` from the right side of equation (6): # # (7) x_{i+1} = x'-(x_i+f(x_i))+x_i = x'-pix2foc(x_i)+x_i, # # where `x'=wcs_world2pix(w)` and it is computed only *once* # before the beginning of the iterative process (and we also # set `x_0=x'`). By using `pix2foc` at each iteration instead # of `all_pix2world` we get about 25% increase in performance # (by not performing the linear `W` transformation at each # step) and we also avoid the "RA wrapping" issue described # above (by working in focal plane coordinates and avoiding # pix->world transformations). # # As an added benefit, the process converges to the correct # solution in just one iteration when distortions are not # present (compare to # https://github.com/astropy/astropy/issues/1977 and # https://github.com/astropy/astropy/pull/2294): in this case # `pix2foc` is the identical transformation # `x_i=pix2foc(x_i)` and from equation (7) we get: # # x' = x_0 = wcs_world2pix(w) # x_1 = x' - pix2foc(x_0) + x_0 = x' - pix2foc(x') + x' = x' # = wcs_world2pix(w) = x_0 # => # |x_1-x_0| = 0 < tolerance (with tolerance > 0) # # However, for performance reasons, it is still better to # avoid iterations altogether and return the exact linear # solution (`wcs_world2pix`) right-away when non-linear # distortions are not present by checking that attributes # `sip`, `cpdis1`, `cpdis2`, `det2im1`, and `det2im2` are # *all* `None`. # # # ### Outline of the Algorithm ### # # # While the proposed code is relatively long (considering # the simplicity of the algorithm), this is due to: 1) # checking if iterative solution is necessary at all; 2) # checking for divergence; 3) re-implementation of the # completely vectorized algorithm as an "adaptive" vectorized # algorithm (for cases when some points diverge for which we # want to stop iterations). In my tests, the adaptive version # of the algorithm is about 50% slower than non-adaptive # version for all HST images. # # The essential part of the vectorized non-adaptive algorithm # (without divergence and other checks) can be described # as follows: # # pix0 = self.wcs_world2pix(world, origin) # pix = pix0.copy() # 0-order solution # # for k in range(maxiter): # # find correction to the previous solution: # dpix = self.pix2foc(pix, origin) - pix0 # # # compute norm (L2) of the correction: # dn = np.linalg.norm(dpix, axis=1) # # # apply correction: # pix -= dpix # # # check convergence: # if np.max(dn) < tolerance: # break # # return pix # # Here, the input parameter `world` can be a `MxN` array # where `M` is the number of coordinate axes in WCS and `N` # is the number of points to be converted simultaneously to # image coordinates. # # # ### IMPORTANT NOTE: ### # # If, in the future releases of the `~astropy.wcs`, # `pix2foc` will not apply all the required distortion # corrections then in the code below, calls to `pix2foc` will # have to be replaced with # wcs_world2pix(all_pix2world(pix_list, origin), origin) # # ############################################################ # # INITIALIZE ITERATIVE PROCESS: ## # ############################################################ # initial approximation (linear WCS based only) pix0 = self.wcs_world2pix(world, origin) # Check that an iterative solution is required at all # (when any of the non-CD-matrix-based corrections are # present). If not required return the initial # approximation (pix0). if self.sip is None and \ self.cpdis1 is None and self.cpdis2 is None and \ self.det2im1 is None and self.det2im2 is None: # No non-WCS corrections detected so # simply return initial approximation: return pix0 pix = pix0.copy() # 0-order solution # initial correction: dpix = self.pix2foc(pix, origin) - pix0 # Update initial solution: pix -= dpix # Norm (L2) squared of the correction: dn = np.sum(dpix*dpix, axis=1) dnprev = dn.copy() # if adaptive else dn tol2 = tolerance**2 # Prepare for iterative process k = 1 ind = None inddiv = None # Turn off numpy runtime warnings for 'invalid' and 'over': old_invalid = np.geterr()['invalid'] old_over = np.geterr()['over'] np.seterr(invalid='ignore', over='ignore') # ############################################################ # # NON-ADAPTIVE ITERATIONS: ## # ############################################################ if not adaptive: # Fixed-point iterations: while (np.nanmax(dn) >= tol2 and k < maxiter): # Find correction to the previous solution: dpix = self.pix2foc(pix, origin) - pix0 # Compute norm (L2) squared of the correction: dn = np.sum(dpix*dpix, axis=1) # Check for divergence (we do this in two stages # to optimize performance for the most common # scenario when successive approximations converge): if detect_divergence: divergent = (dn >= dnprev) if np.any(divergent): # Find solutions that have not yet converged: slowconv = (dn >= tol2) inddiv, = np.where(divergent & slowconv) if inddiv.shape[0] > 0: # Update indices of elements that # still need correction: conv = (dn < dnprev) iconv = np.where(conv) # Apply correction: dpixgood = dpix[iconv] pix[iconv] -= dpixgood dpix[iconv] = dpixgood # For the next iteration choose # non-divergent points that have not yet # converged to the requested accuracy: ind, = np.where(slowconv & conv) pix0 = pix0[ind] dnprev[ind] = dn[ind] k += 1 # Switch to adaptive iterations: adaptive = True break # Save current correction magnitudes for later: dnprev = dn # Apply correction: pix -= dpix k += 1 # ############################################################ # # ADAPTIVE ITERATIONS: ## # ############################################################ if adaptive: if ind is None: ind, = np.where(np.isfinite(pix).all(axis=1)) pix0 = pix0[ind] # "Adaptive" fixed-point iterations: while (ind.shape[0] > 0 and k < maxiter): # Find correction to the previous solution: dpixnew = self.pix2foc(pix[ind], origin) - pix0 # Compute norm (L2) of the correction: dnnew = np.sum(np.square(dpixnew), axis=1) # Bookeeping of corrections: dnprev[ind] = dn[ind].copy() dn[ind] = dnnew if detect_divergence: # Find indices of pixels that are converging: conv = (dnnew < dnprev[ind]) iconv = np.where(conv) iiconv = ind[iconv] # Apply correction: dpixgood = dpixnew[iconv] pix[iiconv] -= dpixgood dpix[iiconv] = dpixgood # Find indices of solutions that have not yet # converged to the requested accuracy # AND that do not diverge: subind, = np.where((dnnew >= tol2) & conv) else: # Apply correction: pix[ind] -= dpixnew dpix[ind] = dpixnew # Find indices of solutions that have not yet # converged to the requested accuracy: subind, = np.where(dnnew >= tol2) # Choose solutions that need more iterations: ind = ind[subind] pix0 = pix0[subind] k += 1 # ############################################################ # # FINAL DETECTION OF INVALID, DIVERGING, ## # # AND FAILED-TO-CONVERGE POINTS ## # ############################################################ # Identify diverging and/or invalid points: invalid = ((~np.all(np.isfinite(pix), axis=1)) & (np.all(np.isfinite(world), axis=1))) # When detect_divergence==False, dnprev is outdated # (it is the norm of the very first correction). # Still better than nothing... inddiv, = np.where(((dn >= tol2) & (dn >= dnprev)) | invalid) if inddiv.shape[0] == 0: inddiv = None # Identify points that did not converge within 'maxiter' # iterations: if k >= maxiter: ind, = np.where((dn >= tol2) & (dn < dnprev) & (~invalid)) if ind.shape[0] == 0: ind = None else: ind = None # Restore previous numpy error settings: np.seterr(invalid=old_invalid, over=old_over) # ############################################################ # # RAISE EXCEPTION IF DIVERGING OR TOO SLOWLY CONVERGING ## # # DATA POINTS HAVE BEEN DETECTED: ## # ############################################################ if (ind is not None or inddiv is not None) and not quiet: if inddiv is None: raise NoConvergence( "'WCS.all_world2pix' failed to " "converge to the requested accuracy after {:d} " "iterations.".format(k), best_solution=pix, accuracy=np.abs(dpix), niter=k, slow_conv=ind, divergent=None) else: raise NoConvergence( "'WCS.all_world2pix' failed to " "converge to the requested accuracy.\n" "After {0:d} iterations, the solution is diverging " "at least for one input point." .format(k), best_solution=pix, accuracy=np.abs(dpix), niter=k, slow_conv=ind, divergent=inddiv) return pix def all_world2pix(self, *args, tolerance=1e-4, maxiter=20, adaptive=False, detect_divergence=True, quiet=False, **kwargs): if self.wcs is None: raise ValueError("No basic WCS settings were created.") return self._array_converter( lambda *args, **kwargs: self._all_world2pix( *args, tolerance=tolerance, maxiter=maxiter, adaptive=adaptive, detect_divergence=detect_divergence, quiet=quiet), 'input', *args, **kwargs ) all_world2pix.__doc__ = """ all_world2pix(*arg, accuracy=1.0e-4, maxiter=20, adaptive=False, detect_divergence=True, quiet=False) Transforms world coordinates to pixel coordinates, using numerical iteration to invert the full forward transformation `~astropy.wcs.WCS.all_pix2world` with complete distortion model. Parameters ---------- {0} For a transformation that is not two-dimensional, the two-argument form must be used. {1} tolerance : float, optional (Default = 1.0e-4) Tolerance of solution. Iteration terminates when the iterative solver estimates that the "true solution" is within this many pixels current estimate, more specifically, when the correction to the solution found during the previous iteration is smaller (in the sense of the L2 norm) than ``tolerance``. maxiter : int, optional (Default = 20) Maximum number of iterations allowed to reach a solution. quiet : bool, optional (Default = False) Do not throw :py:class:`NoConvergence` exceptions when the method does not converge to a solution with the required accuracy within a specified number of maximum iterations set by ``maxiter`` parameter. Instead, simply return the found solution. Other Parameters ---------------- adaptive : bool, optional (Default = False) Specifies whether to adaptively select only points that did not converge to a solution within the required accuracy for the next iteration. Default is recommended for HST as well as most other instruments. .. note:: The :py:meth:`all_world2pix` uses a vectorized implementation of the method of consecutive approximations (see ``Notes`` section below) in which it iterates over *all* input points *regardless* until the required accuracy has been reached for *all* input points. In some cases it may be possible that *almost all* points have reached the required accuracy but there are only a few of input data points for which additional iterations may be needed (this depends mostly on the characteristics of the geometric distortions for a given instrument). In this situation it may be advantageous to set ``adaptive`` = `True` in which case :py:meth:`all_world2pix` will continue iterating *only* over the points that have not yet converged to the required accuracy. However, for the HST's ACS/WFC detector, which has the strongest distortions of all HST instruments, testing has shown that enabling this option would lead to a about 50-100% penalty in computational time (depending on specifics of the image, geometric distortions, and number of input points to be converted). Therefore, for HST and possibly instruments, it is recommended to set ``adaptive`` = `False`. The only danger in getting this setting wrong will be a performance penalty. .. note:: When ``detect_divergence`` is `True`, :py:meth:`all_world2pix` will automatically switch to the adaptive algorithm once divergence has been detected. detect_divergence : bool, optional (Default = True) Specifies whether to perform a more detailed analysis of the convergence to a solution. Normally :py:meth:`all_world2pix` may not achieve the required accuracy if either the ``tolerance`` or ``maxiter`` arguments are too low. However, it may happen that for some geometric distortions the conditions of convergence for the the method of consecutive approximations used by :py:meth:`all_world2pix` may not be satisfied, in which case consecutive approximations to the solution will diverge regardless of the ``tolerance`` or ``maxiter`` settings. When ``detect_divergence`` is `False`, these divergent points will be detected as not having achieved the required accuracy (without further details). In addition, if ``adaptive`` is `False` then the algorithm will not know that the solution (for specific points) is diverging and will continue iterating and trying to "improve" diverging solutions. This may result in ``NaN`` or ``Inf`` values in the return results (in addition to a performance penalties). Even when ``detect_divergence`` is `False`, :py:meth:`all_world2pix`, at the end of the iterative process, will identify invalid results (``NaN`` or ``Inf``) as "diverging" solutions and will raise :py:class:`NoConvergence` unless the ``quiet`` parameter is set to `True`. When ``detect_divergence`` is `True`, :py:meth:`all_world2pix` will detect points for which current correction to the coordinates is larger than the correction applied during the previous iteration **if** the requested accuracy **has not yet been achieved**. In this case, if ``adaptive`` is `True`, these points will be excluded from further iterations and if ``adaptive`` is `False`, :py:meth:`all_world2pix` will automatically switch to the adaptive algorithm. Thus, the reported divergent solution will be the latest converging solution computed immediately *before* divergence has been detected. .. note:: When accuracy has been achieved, small increases in current corrections may be possible due to rounding errors (when ``adaptive`` is `False`) and such increases will be ignored. .. note:: Based on our testing using HST ACS/WFC images, setting ``detect_divergence`` to `True` will incur about 5-20% performance penalty with the larger penalty corresponding to ``adaptive`` set to `True`. Because the benefits of enabling this feature outweigh the small performance penalty, especially when ``adaptive`` = `False`, it is recommended to set ``detect_divergence`` to `True`, unless extensive testing of the distortion models for images from specific instruments show a good stability of the numerical method for a wide range of coordinates (even outside the image itself). .. note:: Indices of the diverging inverse solutions will be reported in the ``divergent`` attribute of the raised :py:class:`NoConvergence` exception object. Returns ------- {2} Notes ----- The order of the axes for the input world array is determined by the ``CTYPEia`` keywords in the FITS header, therefore it may not always be of the form (*ra*, *dec*). The `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`, `~astropy.wcs.Wcsprm.lattyp`, and `~astropy.wcs.Wcsprm.lngtyp` members can be used to determine the order of the axes. Using the method of fixed-point iterations approximations we iterate starting with the initial approximation, which is computed using the non-distortion-aware :py:meth:`wcs_world2pix` (or equivalent). The :py:meth:`all_world2pix` function uses a vectorized implementation of the method of consecutive approximations and therefore it is highly efficient (>30x) when *all* data points that need to be converted from sky coordinates to image coordinates are passed at *once*. Therefore, it is advisable, whenever possible, to pass as input a long array of all points that need to be converted to :py:meth:`all_world2pix` instead of calling :py:meth:`all_world2pix` for each data point. Also see the note to the ``adaptive`` parameter. Raises ------ NoConvergence The method did not converge to a solution to the required accuracy within a specified number of maximum iterations set by the ``maxiter`` parameter. To turn off this exception, set ``quiet`` to `True`. Indices of the points for which the requested accuracy was not achieved (if any) will be listed in the ``slow_conv`` attribute of the raised :py:class:`NoConvergence` exception object. See :py:class:`NoConvergence` documentation for more details. MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. ValueError Invalid coordinate transformation parameters. ValueError x- and y-coordinate arrays are not the same size. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. Examples -------- >>> import astropy.io.fits as fits >>> import astropy.wcs as wcs >>> import numpy as np >>> import os >>> filename = os.path.join(wcs.__path__[0], 'tests/data/j94f05bgq_flt.fits') >>> hdulist = fits.open(filename) >>> w = wcs.WCS(hdulist[('sci',1)].header, hdulist) >>> hdulist.close() >>> ra, dec = w.all_pix2world([1,2,3], [1,1,1], 1) >>> print(ra) # doctest: +FLOAT_CMP [ 5.52645627 5.52649663 5.52653698] >>> print(dec) # doctest: +FLOAT_CMP [-72.05171757 -72.05171276 -72.05170795] >>> radec = w.all_pix2world([[1,1], [2,1], [3,1]], 1) >>> print(radec) # doctest: +FLOAT_CMP [[ 5.52645627 -72.05171757] [ 5.52649663 -72.05171276] [ 5.52653698 -72.05170795]] >>> x, y = w.all_world2pix(ra, dec, 1) >>> print(x) # doctest: +FLOAT_CMP [ 1.00000238 2.00000237 3.00000236] >>> print(y) # doctest: +FLOAT_CMP [ 0.99999996 0.99999997 0.99999997] >>> xy = w.all_world2pix(radec, 1) >>> print(xy) # doctest: +FLOAT_CMP [[ 1.00000238 0.99999996] [ 2.00000237 0.99999997] [ 3.00000236 0.99999997]] >>> xy = w.all_world2pix(radec, 1, maxiter=3, ... tolerance=1.0e-10, quiet=False) Traceback (most recent call last): ... NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy. After 3 iterations, the solution is diverging at least for one input point. >>> # Now try to use some diverging data: >>> divradec = w.all_pix2world([[1.0, 1.0], ... [10000.0, 50000.0], ... [3.0, 1.0]], 1) >>> print(divradec) # doctest: +FLOAT_CMP [[ 5.52645627 -72.05171757] [ 7.15976932 -70.8140779 ] [ 5.52653698 -72.05170795]] >>> # First, turn detect_divergence on: >>> try: # doctest: +FLOAT_CMP ... xy = w.all_world2pix(divradec, 1, maxiter=20, ... tolerance=1.0e-4, adaptive=False, ... detect_divergence=True, ... quiet=False) ... except wcs.wcs.NoConvergence as e: ... print("Indices of diverging points: {{0}}" ... .format(e.divergent)) ... print("Indices of poorly converging points: {{0}}" ... .format(e.slow_conv)) ... print("Best solution:\\n{{0}}".format(e.best_solution)) ... print("Achieved accuracy:\\n{{0}}".format(e.accuracy)) Indices of diverging points: [1] Indices of poorly converging points: None Best solution: [[ 1.00000238e+00 9.99999965e-01] [ -1.99441636e+06 1.44309097e+06] [ 3.00000236e+00 9.99999966e-01]] Achieved accuracy: [[ 6.13968380e-05 8.59638593e-07] [ 8.59526812e+11 6.61713548e+11] [ 6.09398446e-05 8.38759724e-07]] >>> raise e Traceback (most recent call last): ... NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy. After 5 iterations, the solution is diverging at least for one input point. >>> # This time turn detect_divergence off: >>> try: # doctest: +FLOAT_CMP ... xy = w.all_world2pix(divradec, 1, maxiter=20, ... tolerance=1.0e-4, adaptive=False, ... detect_divergence=False, ... quiet=False) ... except wcs.wcs.NoConvergence as e: ... print("Indices of diverging points: {{0}}" ... .format(e.divergent)) ... print("Indices of poorly converging points: {{0}}" ... .format(e.slow_conv)) ... print("Best solution:\\n{{0}}".format(e.best_solution)) ... print("Achieved accuracy:\\n{{0}}".format(e.accuracy)) Indices of diverging points: [1] Indices of poorly converging points: None Best solution: [[ 1.00000009 1. ] [ nan nan] [ 3.00000009 1. ]] Achieved accuracy: [[ 2.29417358e-06 3.21222995e-08] [ nan nan] [ 2.27407877e-06 3.13005639e-08]] >>> raise e Traceback (most recent call last): ... NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy. After 6 iterations, the solution is diverging at least for one input point. """.format(__.TWO_OR_MORE_ARGS('naxis', 8), __.RA_DEC_ORDER(8), __.RETURNS('pixel coordinates', 8)) def wcs_world2pix(self, *args, **kwargs): if self.wcs is None: raise ValueError("No basic WCS settings were created.") return self._array_converter( lambda xy, o: self.wcs.s2p(xy, o)['pixcrd'], 'input', *args, **kwargs) wcs_world2pix.__doc__ = """ Transforms world coordinates to pixel coordinates, using only the basic `wcslib`_ WCS transformation. No `SIP`_ or `distortion paper`_ table lookup transformation is applied. Parameters ---------- {0} For a transformation that is not two-dimensional, the two-argument form must be used. {1} Returns ------- {2} Notes ----- The order of the axes for the input world array is determined by the ``CTYPEia`` keywords in the FITS header, therefore it may not always be of the form (*ra*, *dec*). The `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`, `~astropy.wcs.Wcsprm.lattyp` and `~astropy.wcs.Wcsprm.lngtyp` members can be used to determine the order of the axes. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. ValueError Invalid coordinate transformation parameters. ValueError x- and y-coordinate arrays are not the same size. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. """.format(__.TWO_OR_MORE_ARGS('naxis', 8), __.RA_DEC_ORDER(8), __.RETURNS('pixel coordinates', 8)) def pix2foc(self, *args): return self._array_converter(self._pix2foc, None, *args) pix2foc.__doc__ = """ Convert pixel coordinates to focal plane coordinates using the `SIP`_ polynomial distortion convention and `distortion paper`_ table-lookup correction. The output is in absolute pixel coordinates, not relative to ``CRPIX``. Parameters ---------- {0} Returns ------- {1} Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.TWO_OR_MORE_ARGS('2', 8), __.RETURNS('focal coordinates', 8)) def p4_pix2foc(self, *args): return self._array_converter(self._p4_pix2foc, None, *args) p4_pix2foc.__doc__ = """ Convert pixel coordinates to focal plane coordinates using `distortion paper`_ table-lookup correction. The output is in absolute pixel coordinates, not relative to ``CRPIX``. Parameters ---------- {0} Returns ------- {1} Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.TWO_OR_MORE_ARGS('2', 8), __.RETURNS('focal coordinates', 8)) def det2im(self, *args): return self._array_converter(self._det2im, None, *args) det2im.__doc__ = """ Convert detector coordinates to image plane coordinates using `distortion paper`_ table-lookup correction. The output is in absolute pixel coordinates, not relative to ``CRPIX``. Parameters ---------- {0} Returns ------- {1} Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.TWO_OR_MORE_ARGS('2', 8), __.RETURNS('pixel coordinates', 8)) def sip_pix2foc(self, *args): if self.sip is None: if len(args) == 2: return args[0] elif len(args) == 3: return args[:2] else: raise TypeError("Wrong number of arguments") return self._array_converter(self.sip.pix2foc, None, *args) sip_pix2foc.__doc__ = """ Convert pixel coordinates to focal plane coordinates using the `SIP`_ polynomial distortion convention. The output is in pixel coordinates, relative to ``CRPIX``. FITS WCS `distortion paper`_ table lookup correction is not applied, even if that information existed in the FITS file that initialized this :class:`~astropy.wcs.WCS` object. To correct for that, use `~astropy.wcs.WCS.pix2foc` or `~astropy.wcs.WCS.p4_pix2foc`. Parameters ---------- {0} Returns ------- {1} Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.TWO_OR_MORE_ARGS('2', 8), __.RETURNS('focal coordinates', 8)) def sip_foc2pix(self, *args): if self.sip is None: if len(args) == 2: return args[0] elif len(args) == 3: return args[:2] else: raise TypeError("Wrong number of arguments") return self._array_converter(self.sip.foc2pix, None, *args) sip_foc2pix.__doc__ = """ Convert focal plane coordinates to pixel coordinates using the `SIP`_ polynomial distortion convention. FITS WCS `distortion paper`_ table lookup distortion correction is not applied, even if that information existed in the FITS file that initialized this `~astropy.wcs.WCS` object. Parameters ---------- {0} Returns ------- {1} Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.TWO_OR_MORE_ARGS('2', 8), __.RETURNS('pixel coordinates', 8)) def to_fits(self, relax=False, key=None): """ Generate an `astropy.io.fits.HDUList` object with all of the information stored in this object. This should be logically identical to the input FITS file, but it will be normalized in a number of ways. See `to_header` for some warnings about the output produced. Parameters ---------- relax : bool or int, optional Degree of permissiveness: - `False` (default): Write all extensions that are considered to be safe and recommended. - `True`: Write all recognized informal extensions of the WCS standard. - `int`: a bit field selecting specific extensions to write. See :ref:`relaxwrite` for details. key : str The name of a particular WCS transform to use. This may be either ``' '`` or ``'A'``-``'Z'`` and corresponds to the ``"a"`` part of the ``CTYPEia`` cards. Returns ------- hdulist : `astropy.io.fits.HDUList` """ header = self.to_header(relax=relax, key=key) hdu = fits.PrimaryHDU(header=header) hdulist = fits.HDUList(hdu) self._write_det2im(hdulist) self._write_distortion_kw(hdulist) return hdulist def to_header(self, relax=None, key=None): """Generate an `astropy.io.fits.Header` object with the basic WCS and SIP information stored in this object. This should be logically identical to the input FITS file, but it will be normalized in a number of ways. .. warning:: This function does not write out FITS WCS `distortion paper`_ information, since that requires multiple FITS header data units. To get a full representation of everything in this object, use `to_fits`. Parameters ---------- relax : bool or int, optional Degree of permissiveness: - `False` (default): Write all extensions that are considered to be safe and recommended. - `True`: Write all recognized informal extensions of the WCS standard. - `int`: a bit field selecting specific extensions to write. See :ref:`relaxwrite` for details. If the ``relax`` keyword argument is not given and any keywords were omitted from the output, an `~astropy.utils.exceptions.AstropyWarning` is displayed. To override this, explicitly pass a value to ``relax``. key : str The name of a particular WCS transform to use. This may be either ``' '`` or ``'A'``-``'Z'`` and corresponds to the ``"a"`` part of the ``CTYPEia`` cards. Returns ------- header : `astropy.io.fits.Header` Notes ----- The output header will almost certainly differ from the input in a number of respects: 1. The output header only contains WCS-related keywords. In particular, it does not contain syntactically-required keywords such as ``SIMPLE``, ``NAXIS``, ``BITPIX``, or ``END``. 2. Deprecated (e.g. ``CROTAn``) or non-standard usage will be translated to standard (this is partially dependent on whether ``fix`` was applied). 3. Quantities will be converted to the units used internally, basically SI with the addition of degrees. 4. Floating-point quantities may be given to a different decimal precision. 5. Elements of the ``PCi_j`` matrix will be written if and only if they differ from the unit matrix. Thus, if the matrix is unity then no elements will be written. 6. Additional keywords such as ``WCSAXES``, ``CUNITia``, ``LONPOLEa`` and ``LATPOLEa`` may appear. 7. The original keycomments will be lost, although `to_header` tries hard to write meaningful comments. 8. Keyword order may be changed. """ # default precision for numerical WCS keywords precision = WCSHDO_P14 display_warning = False if relax is None: display_warning = True relax = False if relax not in (True, False): do_sip = relax & WCSHDO_SIP relax &= ~WCSHDO_SIP else: do_sip = relax relax = WCSHDO_all if relax is True else WCSHDO_safe relax = precision | relax if self.wcs is not None: if key is not None: orig_key = self.wcs.alt self.wcs.alt = key header_string = self.wcs.to_header(relax) header = fits.Header.fromstring(header_string) keys_to_remove = ["", " ", "COMMENT"] for kw in keys_to_remove: if kw in header: del header[kw] else: header = fits.Header() if do_sip and self.sip is not None: if self.wcs is not None and any(not ctyp.endswith('-SIP') for ctyp in self.wcs.ctype): self._fix_ctype(header, add_sip=True) for kw, val in self._write_sip_kw().items(): header[kw] = val if not do_sip and self.wcs is not None and any(self.wcs.ctype) and self.sip is not None: # This is called when relax is not False or WCSHDO_SIP # The default case of ``relax=None`` is handled further in the code. header = self._fix_ctype(header, add_sip=False) if display_warning: full_header = self.to_header(relax=True, key=key) missing_keys = [] for kw, val in full_header.items(): if kw not in header: missing_keys.append(kw) if len(missing_keys): warnings.warn( "Some non-standard WCS keywords were excluded: {0} " "Use the ``relax`` kwarg to control this.".format( ', '.join(missing_keys)), AstropyWarning) # called when ``relax=None`` # This is different from the case of ``relax=False``. if any(self.wcs.ctype) and self.sip is not None: header = self._fix_ctype(header, add_sip=False, log_message=False) # Finally reset the key. This must be called after ``_fix_ctype``. if key is not None: self.wcs.alt = orig_key return header def _fix_ctype(self, header, add_sip=True, log_message=True): """ Parameters ---------- header : `~astropy.io.fits.Header` FITS header. add_sip : bool Flag indicating whether "-SIP" should be added or removed from CTYPE keywords. Remove "-SIP" from CTYPE when writing out a header with relax=False. This needs to be done outside ``to_header`` because ``to_header`` runs twice when ``relax=False`` and the second time ``relax`` is set to ``True`` to display the missing keywords. If the user requested SIP distortion to be written out add "-SIP" to CTYPE if it is missing. """ _add_sip_to_ctype = """ Inconsistent SIP distortion information is present in the current WCS: SIP coefficients were detected, but CTYPE is missing "-SIP" suffix, therefore the current WCS is internally inconsistent. Because relax has been set to True, the resulting output WCS will have "-SIP" appended to CTYPE in order to make the header internally consistent. However, this may produce incorrect astrometry in the output WCS, if in fact the current WCS is already distortion-corrected. Therefore, if current WCS is already distortion-corrected (eg, drizzled) then SIP distortion components should not apply. In that case, for a WCS that is already distortion-corrected, please remove the SIP coefficients from the header. """ if log_message: if add_sip: log.info(_add_sip_to_ctype) for i in range(1, self.naxis+1): # strip() must be called here to cover the case of alt key= " " kw = 'CTYPE{0}{1}'.format(i, self.wcs.alt).strip() if kw in header: if add_sip: val = header[kw].strip("-SIP") + "-SIP" else: val = header[kw].strip("-SIP") header[kw] = val else: continue return header def to_header_string(self, relax=None): """ Identical to `to_header`, but returns a string containing the header cards. """ return str(self.to_header(relax)) def footprint_to_file(self, filename='footprint.reg', color='green', width=2, coordsys=None): """ Writes out a `ds9`_ style regions file. It can be loaded directly by `ds9`_. Parameters ---------- filename : str, optional Output file name - default is ``'footprint.reg'`` color : str, optional Color to use when plotting the line. width : int, optional Width of the region line. coordsys : str, optional Coordinate system. If not specified (default), the ``radesys`` value is used. For all possible values, see http://ds9.si.edu/doc/ref/region.html#RegionFileFormat """ comments = ('# Region file format: DS9 version 4.0 \n' '# global color=green font="helvetica 12 bold ' 'select=1 highlite=1 edit=1 move=1 delete=1 ' 'include=1 fixed=0 source\n') coordsys = coordsys or self.wcs.radesys if coordsys not in ('PHYSICAL', 'IMAGE', 'FK4', 'B1950', 'FK5', 'J2000', 'GALACTIC', 'ECLIPTIC', 'ICRS', 'LINEAR', 'AMPLIFIER', 'DETECTOR'): raise ValueError("Coordinate system '{}' is not supported. A valid" " one can be given with the 'coordsys' argument." .format(coordsys)) with open(filename, mode='w') as f: f.write(comments) f.write('{}\n'.format(coordsys)) f.write('polygon(') self.calc_footprint().tofile(f, sep=',') f.write(') # color={0}, width={1:d} \n'.format(color, width)) @property def _naxis1(self): return self._naxis[0] @_naxis1.setter def _naxis1(self, value): self._naxis[0] = value @property def _naxis2(self): return self._naxis[1] @_naxis2.setter def _naxis2(self, value): self._naxis[1] = value def _get_naxis(self, header=None): _naxis = [] if (header is not None and not isinstance(header, (str, bytes))): for naxis in itertools.count(1): try: _naxis.append(header['NAXIS{}'.format(naxis)]) except KeyError: break if len(_naxis) == 0: _naxis = [0, 0] elif len(_naxis) == 1: _naxis.append(0) self._naxis = _naxis def printwcs(self): print(repr(self)) def __repr__(self): ''' Return a short description. Simply porting the behavior from the `printwcs()` method. ''' description = ["WCS Keywords\n", "Number of WCS axes: {0!r}".format(self.naxis)] sfmt = ' : ' + "".join(["{"+"{0}".format(i)+"!r} " for i in range(self.naxis)]) keywords = ['CTYPE', 'CRVAL', 'CRPIX'] values = [self.wcs.ctype, self.wcs.crval, self.wcs.crpix] for keyword, value in zip(keywords, values): description.append(keyword+sfmt.format(*value)) if hasattr(self.wcs, 'pc'): for i in range(self.naxis): s = '' for j in range(self.naxis): s += ''.join(['PC', str(i+1), '_', str(j+1), ' ']) s += sfmt description.append(s.format(*self.wcs.pc[i])) s = 'CDELT' + sfmt description.append(s.format(*self.wcs.cdelt)) elif hasattr(self.wcs, 'cd'): for i in range(self.naxis): s = '' for j in range(self.naxis): s += "".join(['CD', str(i+1), '_', str(j+1), ' ']) s += sfmt description.append(s.format(*self.wcs.cd[i])) description.append('NAXIS : {}'.format(' '.join(map(str, self._naxis)))) return '\n'.join(description) def get_axis_types(self): """ Similar to `self.wcsprm.axis_types <astropy.wcs.Wcsprm.axis_types>` but provides the information in a more Python-friendly format. Returns ------- result : list of dicts Returns a list of dictionaries, one for each axis, each containing attributes about the type of that axis. Each dictionary has the following keys: - 'coordinate_type': - None: Non-specific coordinate type. - 'stokes': Stokes coordinate. - 'celestial': Celestial coordinate (including ``CUBEFACE``). - 'spectral': Spectral coordinate. - 'scale': - 'linear': Linear axis. - 'quantized': Quantized axis (``STOKES``, ``CUBEFACE``). - 'non-linear celestial': Non-linear celestial axis. - 'non-linear spectral': Non-linear spectral axis. - 'logarithmic': Logarithmic axis. - 'tabular': Tabular axis. - 'group' - Group number, e.g. lookup table number - 'number' - For celestial axes: - 0: Longitude coordinate. - 1: Latitude coordinate. - 2: ``CUBEFACE`` number. - For lookup tables: - the axis number in a multidimensional table. ``CTYPEia`` in ``"4-3"`` form with unrecognized algorithm code will generate an error. """ if self.wcs is None: raise AttributeError( "This WCS object does not have a wcsprm object.") coordinate_type_map = { 0: None, 1: 'stokes', 2: 'celestial', 3: 'spectral'} scale_map = { 0: 'linear', 1: 'quantized', 2: 'non-linear celestial', 3: 'non-linear spectral', 4: 'logarithmic', 5: 'tabular'} result = [] for axis_type in self.wcs.axis_types: subresult = {} coordinate_type = (axis_type // 1000) % 10 subresult['coordinate_type'] = coordinate_type_map[coordinate_type] scale = (axis_type // 100) % 10 subresult['scale'] = scale_map[scale] group = (axis_type // 10) % 10 subresult['group'] = group number = axis_type % 10 subresult['number'] = number result.append(subresult) return result def __reduce__(self): """ Support pickling of WCS objects. This is done by serializing to an in-memory FITS file and dumping that as a string. """ hdulist = self.to_fits(relax=True) buffer = io.BytesIO() hdulist.writeto(buffer) return (__WCS_unpickle__, (self.__class__, self.__dict__, buffer.getvalue(),)) def dropaxis(self, dropax): """ Remove an axis from the WCS. Parameters ---------- wcs : `~astropy.wcs.WCS` The WCS with naxis to be chopped to naxis-1 dropax : int The index of the WCS to drop, counting from 0 (i.e., python convention, not FITS convention) Returns ------- A new `~astropy.wcs.WCS` instance with one axis fewer """ inds = list(range(self.wcs.naxis)) inds.pop(dropax) # axis 0 has special meaning to sub # if wcs.wcs.ctype == ['RA','DEC','VLSR'], you want # wcs.sub([1,2]) to get 'RA','DEC' back return self.sub([i+1 for i in inds]) def swapaxes(self, ax0, ax1): """ Swap axes in a WCS. Parameters ---------- wcs : `~astropy.wcs.WCS` The WCS to have its axes swapped ax0 : int ax1 : int The indices of the WCS to be swapped, counting from 0 (i.e., python convention, not FITS convention) Returns ------- A new `~astropy.wcs.WCS` instance with the same number of axes, but two swapped """ inds = list(range(self.wcs.naxis)) inds[ax0], inds[ax1] = inds[ax1], inds[ax0] return self.sub([i+1 for i in inds]) def reorient_celestial_first(self): """ Reorient the WCS such that the celestial axes are first, followed by the spectral axis, followed by any others. Assumes at least celestial axes are present. """ return self.sub([WCSSUB_CELESTIAL, WCSSUB_SPECTRAL, WCSSUB_STOKES]) def slice(self, view, numpy_order=True): """ Slice a WCS instance using a Numpy slice. The order of the slice should be reversed (as for the data) compared to the natural WCS order. Parameters ---------- view : tuple A tuple containing the same number of slices as the WCS system. The ``step`` method, the third argument to a slice, is not presently supported. numpy_order : bool Use numpy order, i.e. slice the WCS so that an identical slice applied to a numpy array will slice the array and WCS in the same way. If set to `False`, the WCS will be sliced in FITS order, meaning the first slice will be applied to the *last* numpy index but the *first* WCS axis. Returns ------- wcs_new : `~astropy.wcs.WCS` A new resampled WCS axis """ if hasattr(view, '__len__') and len(view) > self.wcs.naxis: raise ValueError("Must have # of slices <= # of WCS axes") elif not hasattr(view, '__len__'): # view MUST be an iterable view = [view] if not all(isinstance(x, slice) for x in view): raise ValueError("Cannot downsample a WCS with indexing. Use " "wcs.sub or wcs.dropaxis if you want to remove " "axes.") wcs_new = self.deepcopy() for i, iview in enumerate(view): if iview.step is not None and iview.step < 0: raise NotImplementedError("Reversing an axis is not " "implemented.") if numpy_order: wcs_index = self.wcs.naxis - 1 - i else: wcs_index = i if iview.step is not None and iview.start is None: # Slice from "None" is equivalent to slice from 0 (but one # might want to downsample, so allow slices with # None,None,step or None,stop,step) iview = slice(0, iview.stop, iview.step) if iview.start is not None: if iview.step not in (None, 1): crpix = self.wcs.crpix[wcs_index] cdelt = self.wcs.cdelt[wcs_index] # equivalently (keep this comment so you can compare eqns): # wcs_new.wcs.crpix[wcs_index] = # (crpix - iview.start)*iview.step + 0.5 - iview.step/2. crp = ((crpix - iview.start - 1.)/iview.step + 0.5 + 1./iview.step/2.) wcs_new.wcs.crpix[wcs_index] = crp wcs_new.wcs.cdelt[wcs_index] = cdelt * iview.step else: wcs_new.wcs.crpix[wcs_index] -= iview.start try: # range requires integers but the other attributes can also # handle arbitary values, so this needs to be in a try/except. nitems = len(builtins.range(self._naxis[wcs_index])[iview]) except TypeError as exc: if 'indices must be integers' not in str(exc): raise warnings.warn("NAXIS{0} attribute is not updated because at " "least one indix ('{1}') is no integer." "".format(wcs_index, iview), AstropyUserWarning) else: wcs_new._naxis[wcs_index] = nitems return wcs_new def __getitem__(self, item): # "getitem" is a shortcut for self.slice; it is very limited # there is no obvious and unambiguous interpretation of wcs[1,2,3] # We COULD allow wcs[1] to link to wcs.sub([2]) # (wcs[i] -> wcs.sub([i+1]) return self.slice(item) def __iter__(self): # Having __getitem__ makes Python think WCS is iterable. However, # Python first checks whether __iter__ is present, so we can raise an # exception here. raise TypeError("'{0}' object is not iterable".format(self.__class__.__name__)) @property def axis_type_names(self): """ World names for each coordinate axis Returns ------- A list of names along each axis """ names = list(self.wcs.cname) types = self.wcs.ctype for i in range(len(names)): if len(names[i]) > 0: continue names[i] = types[i].split('-')[0] return names @property def celestial(self): """ A copy of the current WCS with only the celestial axes included """ return self.sub([WCSSUB_CELESTIAL]) @property def is_celestial(self): return self.has_celestial and self.naxis == 2 @property def has_celestial(self): try: return self.celestial.naxis == 2 except InconsistentAxisTypesError: return False @property def pixel_scale_matrix(self): try: cdelt = np.matrix(np.diag(self.wcs.get_cdelt())) pc = np.matrix(self.wcs.get_pc()) except InconsistentAxisTypesError: try: # for non-celestial axes, get_cdelt doesn't work cdelt = np.matrix(self.wcs.cd) * np.matrix(np.diag(self.wcs.cdelt)) except AttributeError: cdelt = np.matrix(np.diag(self.wcs.cdelt)) try: pc = np.matrix(self.wcs.pc) except AttributeError: pc = 1 pccd = np.array(cdelt * pc) return pccd def _as_mpl_axes(self): """ Compatibility hook for Matplotlib and WCSAxes. With this method, one can do: from astropy.wcs import WCS import matplotlib.pyplot as plt wcs = WCS('filename.fits') fig = plt.figure() ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=wcs) ... and this will generate a plot with the correct WCS coordinates on the axes. """ from ..visualization.wcsaxes import WCSAxes return WCSAxes, {'wcs': self} def __WCS_unpickle__(cls, dct, fits_data): """ Unpickles a WCS object from a serialized FITS string. """ self = cls.__new__(cls) self.__dict__.update(dct) buffer = io.BytesIO(fits_data) hdulist = fits.open(buffer) WCS.__init__(self, hdulist[0].header, hdulist) return self def find_all_wcs(header, relax=True, keysel=None, fix=True, translate_units='', _do_set=True): """ Find all the WCS transformations in the given header. Parameters ---------- header : str or astropy.io.fits header object. relax : bool or int, optional Degree of permissiveness: - `True` (default): Admit all recognized informal extensions of the WCS standard. - `False`: Recognize only FITS keywords defined by the published WCS standard. - `int`: a bit field selecting specific extensions to accept. See :ref:`relaxread` for details. keysel : sequence of flags, optional A list of flags used to select the keyword types considered by wcslib. When ``None``, only the standard image header keywords are considered (and the underlying wcspih() C function is called). To use binary table image array or pixel list keywords, *keysel* must be set. Each element in the list should be one of the following strings: - 'image': Image header keywords - 'binary': Binary table image array keywords - 'pixel': Pixel list keywords Keywords such as ``EQUIna`` or ``RFRQna`` that are common to binary table image arrays and pixel lists (including ``WCSNna`` and ``TWCSna``) are selected by both 'binary' and 'pixel'. fix : bool, optional When `True` (default), call `~astropy.wcs.Wcsprm.fix` on the resulting objects to fix any non-standard uses in the header. `FITSFixedWarning` warnings will be emitted if any changes were made. translate_units : str, optional Specify which potentially unsafe translations of non-standard unit strings to perform. By default, performs none. See `WCS.fix` for more information about this parameter. Only effective when ``fix`` is `True`. Returns ------- wcses : list of `WCS` objects """ if isinstance(header, (str, bytes)): header_string = header elif isinstance(header, fits.Header): header_string = header.tostring() else: raise TypeError( "header must be a string or astropy.io.fits.Header object") keysel_flags = _parse_keysel(keysel) if isinstance(header_string, str): header_bytes = header_string.encode('ascii') else: header_bytes = header_string wcsprms = _wcs.find_all_wcs(header_bytes, relax, keysel_flags) result = [] for wcsprm in wcsprms: subresult = WCS(fix=False, _do_set=False) subresult.wcs = wcsprm result.append(subresult) if fix: subresult.fix(translate_units) if _do_set: subresult.wcs.set() return result def validate(source): """ Prints a WCS validation report for the given FITS file. Parameters ---------- source : str path, readable file-like object or `astropy.io.fits.HDUList` object The FITS file to validate. Returns ------- results : WcsValidateResults instance The result is returned as nested lists. The first level corresponds to the HDUs in the given file. The next level has an entry for each WCS found in that header. The special subclass of list will pretty-print the results as a table when printed. """ class _WcsValidateWcsResult(list): def __init__(self, key): self._key = key def __repr__(self): result = [" WCS key '{0}':".format(self._key or ' ')] if len(self): for entry in self: for i, line in enumerate(entry.splitlines()): if i == 0: initial_indent = ' - ' else: initial_indent = ' ' result.extend( textwrap.wrap( line, initial_indent=initial_indent, subsequent_indent=' ')) else: result.append(" No issues.") return '\n'.join(result) class _WcsValidateHduResult(list): def __init__(self, hdu_index, hdu_name): self._hdu_index = hdu_index self._hdu_name = hdu_name list.__init__(self) def __repr__(self): if len(self): if self._hdu_name: hdu_name = ' ({0})'.format(self._hdu_name) else: hdu_name = '' result = ['HDU {0}{1}:'.format(self._hdu_index, hdu_name)] for wcs in self: result.append(repr(wcs)) return '\n'.join(result) return '' class _WcsValidateResults(list): def __repr__(self): result = [] for hdu in self: content = repr(hdu) if len(content): result.append(content) return '\n\n'.join(result) global __warningregistry__ if isinstance(source, fits.HDUList): hdulist = source else: hdulist = fits.open(source) results = _WcsValidateResults() for i, hdu in enumerate(hdulist): hdu_results = _WcsValidateHduResult(i, hdu.name) results.append(hdu_results) with warnings.catch_warnings(record=True) as warning_lines: wcses = find_all_wcs( hdu.header, relax=_wcs.WCSHDR_reject, fix=False, _do_set=False) for wcs in wcses: wcs_results = _WcsValidateWcsResult(wcs.wcs.alt) hdu_results.append(wcs_results) try: del __warningregistry__ except NameError: pass with warnings.catch_warnings(record=True) as warning_lines: warnings.resetwarnings() warnings.simplefilter( "always", FITSFixedWarning, append=True) try: WCS(hdu.header, key=wcs.wcs.alt or ' ', relax=_wcs.WCSHDR_reject, fix=True, _do_set=False) except WcsError as e: wcs_results.append(str(e)) wcs_results.extend([str(x.message) for x in warning_lines]) return results
b8e6f496bdc83e1cb70f3f25768e7f79529c88fb3b68d172ed4930a098838ea8
# Licensed under a 3-clause BSD style license - see LICENSE.rst # It gets to be really tedious to type long docstrings in ANSI C # syntax (since multi-line string literals are not valid). # Therefore, the docstrings are written here in doc/docstrings.py, # which are then converted by setup.py into docstrings.h, which is # included by pywcs.c from . import _docutil as __ a = """ ``double array[a_order+1][a_order+1]`` Focal plane transformation matrix. The `SIP`_ ``A_i_j`` matrix used for pixel to focal plane transformation. Its values may be changed in place, but it may not be resized, without creating a new `~astropy.wcs.Sip` object. """ a_order = """ ``int`` (read-only) Order of the polynomial (``A_ORDER``). """ all_pix2world = """ all_pix2world(pixcrd, origin) -> ``double array[ncoord][nelem]`` Transforms pixel coordinates to world coordinates. Does the following: - Detector to image plane correction (if present) - SIP distortion correction (if present) - FITS WCS distortion correction (if present) - wcslib "core" WCS transformation The first three (the distortion corrections) are done in parallel. Parameters ---------- pixcrd : double array[ncoord][nelem] Array of pixel coordinates. {0} Returns ------- world : double array[ncoord][nelem] Returns an array of world coordinates. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. ValueError Invalid coordinate transformation parameters. ValueError x- and y-coordinate arrays are not the same size. InvalidTransformError Invalid coordinate transformation. InvalidTransformError Ill-conditioned coordinate transformation parameters. """.format(__.ORIGIN()) alt = """ ``str`` Character code for alternate coordinate descriptions. For example, the ``"a"`` in keyword names such as ``CTYPEia``. This is a space character for the primary coordinate description, or one of the 26 upper-case letters, A-Z. """ ap = """ ``double array[ap_order+1][ap_order+1]`` Focal plane to pixel transformation matrix. The `SIP`_ ``AP_i_j`` matrix used for focal plane to pixel transformation. Its values may be changed in place, but it may not be resized, without creating a new `~astropy.wcs.Sip` object. """ ap_order = """ ``int`` (read-only) Order of the polynomial (``AP_ORDER``). """ axis_types = """ ``int array[naxis]`` An array of four-digit type codes for each axis. - First digit (i.e. 1000s): - 0: Non-specific coordinate type. - 1: Stokes coordinate. - 2: Celestial coordinate (including ``CUBEFACE``). - 3: Spectral coordinate. - Second digit (i.e. 100s): - 0: Linear axis. - 1: Quantized axis (``STOKES``, ``CUBEFACE``). - 2: Non-linear celestial axis. - 3: Non-linear spectral axis. - 4: Logarithmic axis. - 5: Tabular axis. - Third digit (i.e. 10s): - 0: Group number, e.g. lookup table number - The fourth digit is used as a qualifier depending on the axis type. - For celestial axes: - 0: Longitude coordinate. - 1: Latitude coordinate. - 2: ``CUBEFACE`` number. - For lookup tables: the axis number in a multidimensional table. ``CTYPEia`` in ``"4-3"`` form with unrecognized algorithm code will have its type set to -1 and generate an error. """ b = """ ``double array[b_order+1][b_order+1]`` Pixel to focal plane transformation matrix. The `SIP`_ ``B_i_j`` matrix used for pixel to focal plane transformation. Its values may be changed in place, but it may not be resized, without creating a new `~astropy.wcs.Sip` object. """ b_order = """ ``int`` (read-only) Order of the polynomial (``B_ORDER``). """ bounds_check = """ bounds_check(pix2world, world2pix) Enable/disable bounds checking. Parameters ---------- pix2world : bool, optional When `True`, enable bounds checking for the pixel-to-world (p2x) transformations. Default is `True`. world2pix : bool, optional When `True`, enable bounds checking for the world-to-pixel (s2x) transformations. Default is `True`. Notes ----- Note that by default (without calling `bounds_check`) strict bounds checking is enabled. """ bp = """ ``double array[bp_order+1][bp_order+1]`` Focal plane to pixel transformation matrix. The `SIP`_ ``BP_i_j`` matrix used for focal plane to pixel transformation. Its values may be changed in place, but it may not be resized, without creating a new `~astropy.wcs.Sip` object. """ bp_order = """ ``int`` (read-only) Order of the polynomial (``BP_ORDER``). """ cd = """ ``double array[naxis][naxis]`` The ``CDi_ja`` linear transformation matrix. For historical compatibility, three alternate specifications of the linear transformations are available in wcslib. The canonical ``PCi_ja`` with ``CDELTia``, ``CDi_ja``, and the deprecated ``CROTAia`` keywords. Although the latter may not formally co-exist with ``PCi_ja``, the approach here is simply to ignore them if given in conjunction with ``PCi_ja``. `~astropy.wcs.Wcsprm.has_pc`, `~astropy.wcs.Wcsprm.has_cd` and `~astropy.wcs.Wcsprm.has_crota` can be used to determine which of these alternatives are present in the header. These alternate specifications of the linear transformation matrix are translated immediately to ``PCi_ja`` by `~astropy.wcs.Wcsprm.set` and are nowhere visible to the lower-level routines. In particular, `~astropy.wcs.Wcsprm.set` resets `~astropy.wcs.Wcsprm.cdelt` to unity if ``CDi_ja`` is present (and no ``PCi_ja``). If no ``CROTAia`` is associated with the latitude axis, `~astropy.wcs.Wcsprm.set` reverts to a unity ``PCi_ja`` matrix. """ cdelt = """ ``double array[naxis]`` Coordinate increments (``CDELTia``) for each coord axis. If a ``CDi_ja`` linear transformation matrix is present, a warning is raised and `~astropy.wcs.Wcsprm.cdelt` is ignored. The ``CDi_ja`` matrix may be deleted by:: del wcs.wcs.cd An undefined value is represented by NaN. """ cdfix = """ cdfix() Fix erroneously omitted ``CDi_ja`` keywords. Sets the diagonal element of the ``CDi_ja`` matrix to unity if all ``CDi_ja`` keywords associated with a given axis were omitted. According to Paper I, if any ``CDi_ja`` keywords at all are given in a FITS header then those not given default to zero. This results in a singular matrix with an intersecting row and column of zeros. Returns ------- success : int Returns ``0`` for success; ``-1`` if no change required. """ cel_offset = """ ``boolean`` Is there an offset? If `True`, an offset will be applied to ``(x, y)`` to force ``(x, y) = (0, 0)`` at the fiducial point, (phi_0, theta_0). Default is `False`. """ celfix = """ Translates AIPS-convention celestial projection types, ``-NCP`` and ``-GLS``. Returns ------- success : int Returns ``0`` for success; ``-1`` if no change required. """ cname = """ ``list of strings`` A list of the coordinate axis names, from ``CNAMEia``. """ colax = """ ``int array[naxis]`` An array recording the column numbers for each axis in a pixel list. """ colnum = """ ``int`` Column of FITS binary table associated with this WCS. Where the coordinate representation is associated with an image-array column in a FITS binary table, this property may be used to record the relevant column number. It should be set to zero for an image header or pixel list. """ compare = """ compare(other, cmp=0, tolerance=0.0) Compare two Wcsprm objects for equality. Parameters ---------- other : Wcsprm The other Wcsprm object to compare to. cmp : int, optional A bit field controlling the strictness of the comparison. When 0, (the default), all fields must be identical. The following constants may be or'ed together to loosen the comparison. - ``WCSCOMPARE_ANCILLARY``: Ignores ancillary keywords that don't change the WCS transformation, such as ``DATE-OBS`` or ``EQUINOX``. - ``WCSCOMPARE_TILING``: Ignore integral differences in ``CRPIXja``. This is the 'tiling' condition, where two WCSes cover different regions of the same map projection and align on the same map grid. - ``WCSCOMPARE_CRPIX``: Ignore any differences at all in ``CRPIXja``. The two WCSes cover different regions of the same map projection but may not align on the same grid map. Overrides ``WCSCOMPARE_TILING``. tolerance : float, optional The amount of tolerance required. For example, for a value of 1e-6, all floating-point values in the objects must be equal to the first 6 decimal places. The default value of 0.0 implies exact equality. Returns ------- equal : bool """ convert = """ convert(array) Perform the unit conversion on the elements of the given *array*, returning an array of the same shape. """ coord = """ ``double array[K_M]...[K_2][K_1][M]`` The tabular coordinate array. Has the dimensions:: (K_M, ... K_2, K_1, M) (see `~astropy.wcs.Tabprm.K`) i.e. with the `M` dimension varying fastest so that the `M` elements of a coordinate vector are stored contiguously in memory. """ copy = """ Creates a deep copy of the WCS object. """ cpdis1 = """ `~astropy.wcs.DistortionLookupTable` The pre-linear transformation distortion lookup table, ``CPDIS1``. """ cpdis2 = """ `~astropy.wcs.DistortionLookupTable` The pre-linear transformation distortion lookup table, ``CPDIS2``. """ crder = """ ``double array[naxis]`` The random error in each coordinate axis, ``CRDERia``. An undefined value is represented by NaN. """ crota = """ ``double array[naxis]`` ``CROTAia`` keyvalues for each coordinate axis. For historical compatibility, three alternate specifications of the linear transformations are available in wcslib. The canonical ``PCi_ja`` with ``CDELTia``, ``CDi_ja``, and the deprecated ``CROTAia`` keywords. Although the latter may not formally co-exist with ``PCi_ja``, the approach here is simply to ignore them if given in conjunction with ``PCi_ja``. `~astropy.wcs.Wcsprm.has_pc`, `~astropy.wcs.Wcsprm.has_cd` and `~astropy.wcs.Wcsprm.has_crota` can be used to determine which of these alternatives are present in the header. These alternate specifications of the linear transformation matrix are translated immediately to ``PCi_ja`` by `~astropy.wcs.Wcsprm.set` and are nowhere visible to the lower-level routines. In particular, `~astropy.wcs.Wcsprm.set` resets `~astropy.wcs.Wcsprm.cdelt` to unity if ``CDi_ja`` is present (and no ``PCi_ja``). If no ``CROTAia`` is associated with the latitude axis, `~astropy.wcs.Wcsprm.set` reverts to a unity ``PCi_ja`` matrix. """ crpix = """ ``double array[naxis]`` Coordinate reference pixels (``CRPIXja``) for each pixel axis. """ crval = """ ``double array[naxis]`` Coordinate reference values (``CRVALia``) for each coordinate axis. """ crval_tabprm = """ ``double array[M]`` Index values for the reference pixel for each of the tabular coord axes. """ csyer = """ ``double array[naxis]`` The systematic error in the coordinate value axes, ``CSYERia``. An undefined value is represented by NaN. """ ctype = """ ``list of strings[naxis]`` List of ``CTYPEia`` keyvalues. The `~astropy.wcs.Wcsprm.ctype` keyword values must be in upper case and there must be zero or one pair of matched celestial axis types, and zero or one spectral axis. """ cubeface = """ ``int`` Index into the ``pixcrd`` (pixel coordinate) array for the ``CUBEFACE`` axis. This is used for quadcube projections where the cube faces are stored on a separate axis. The quadcube projections (``TSC``, ``CSC``, ``QSC``) may be represented in FITS in either of two ways: - The six faces may be laid out in one plane and numbered as follows:: 0 4 3 2 1 4 3 2 5 Faces 2, 3 and 4 may appear on one side or the other (or both). The world-to-pixel routines map faces 2, 3 and 4 to the left but the pixel-to-world routines accept them on either side. - The ``COBE`` convention in which the six faces are stored in a three-dimensional structure using a ``CUBEFACE`` axis indexed from 0 to 5 as above. These routines support both methods; `~astropy.wcs.Wcsprm.set` determines which is being used by the presence or absence of a ``CUBEFACE`` axis in `~astropy.wcs.Wcsprm.ctype`. `~astropy.wcs.Wcsprm.p2s` and `~astropy.wcs.Wcsprm.s2p` translate the ``CUBEFACE`` axis representation to the single plane representation understood by the lower-level projection routines. """ cunit = """ ``list of astropy.UnitBase[naxis]`` List of ``CUNITia`` keyvalues as `astropy.units.UnitBase` instances. These define the units of measurement of the ``CRVALia``, ``CDELTia`` and ``CDi_ja`` keywords. As ``CUNITia`` is an optional header keyword, `~astropy.wcs.Wcsprm.cunit` may be left blank but otherwise is expected to contain a standard units specification as defined by WCS Paper I. `~astropy.wcs.Wcsprm.unitfix` is available to translate commonly used non-standard units specifications but this must be done as a separate step before invoking `~astropy.wcs.Wcsprm.set`. For celestial axes, if `~astropy.wcs.Wcsprm.cunit` is not blank, `~astropy.wcs.Wcsprm.set` uses ``wcsunits`` to parse it and scale `~astropy.wcs.Wcsprm.cdelt`, `~astropy.wcs.Wcsprm.crval`, and `~astropy.wcs.Wcsprm.cd` to decimal degrees. It then resets `~astropy.wcs.Wcsprm.cunit` to ``"deg"``. For spectral axes, if `~astropy.wcs.Wcsprm.cunit` is not blank, `~astropy.wcs.Wcsprm.set` uses ``wcsunits`` to parse it and scale `~astropy.wcs.Wcsprm.cdelt`, `~astropy.wcs.Wcsprm.crval`, and `~astropy.wcs.Wcsprm.cd` to SI units. It then resets `~astropy.wcs.Wcsprm.cunit` accordingly. `~astropy.wcs.Wcsprm.set` ignores `~astropy.wcs.Wcsprm.cunit` for other coordinate types; `~astropy.wcs.Wcsprm.cunit` may be used to label coordinate values. """ cylfix = """ cylfix() Fixes WCS keyvalues for malformed cylindrical projections. Returns ------- success : int Returns ``0`` for success; ``-1`` if no change required. """ data = """ ``float array`` The array data for the `~astropy.wcs.DistortionLookupTable`. """ data_wtbarr = """ ``double array`` The array data for the BINTABLE. """ dateavg = """ ``string`` Representative mid-point of the date of observation. In ISO format, ``yyyy-mm-ddThh:mm:ss``. See also -------- astropy.wcs.Wcsprm.dateobs """ dateobs = """ ``string`` Start of the date of observation. In ISO format, ``yyyy-mm-ddThh:mm:ss``. See also -------- astropy.wcs.Wcsprm.dateavg """ datfix = """ datfix() Translates the old ``DATE-OBS`` date format to year-2000 standard form ``(yyyy-mm-ddThh:mm:ss)`` and derives ``MJD-OBS`` from it if not already set. Alternatively, if `~astropy.wcs.Wcsprm.mjdobs` is set and `~astropy.wcs.Wcsprm.dateobs` isn't, then `~astropy.wcs.Wcsprm.datfix` derives `~astropy.wcs.Wcsprm.dateobs` from it. If both are set but disagree by more than half a day then `ValueError` is raised. Returns ------- success : int Returns ``0`` for success; ``-1`` if no change required. """ delta = """ ``double array[M]`` (read-only) Interpolated indices into the coord array. Array of interpolated indices into the coordinate array such that Upsilon_m, as defined in Paper III, is equal to (`~astropy.wcs.Tabprm.p0` [m] + 1) + delta[m]. """ det2im = """ Convert detector coordinates to image plane coordinates. """ det2im1 = """ A `~astropy.wcs.DistortionLookupTable` object for detector to image plane correction in the *x*-axis. """ det2im2 = """ A `~astropy.wcs.DistortionLookupTable` object for detector to image plane correction in the *y*-axis. """ dims = """ ``int array[ndim]`` (read-only) The dimensions of the tabular array `~astropy.wcs.Wtbarr.data`. """ DistortionLookupTable = """ DistortionLookupTable(*table*, *crpix*, *crval*, *cdelt*) Represents a single lookup table for a `distortion paper`_ transformation. Parameters ---------- table : 2-dimensional array The distortion lookup table. crpix : 2-tuple The distortion array reference pixel crval : 2-tuple The image array pixel coordinate cdelt : 2-tuple The grid step size """ equinox = """ ``double`` The equinox associated with dynamical equatorial or ecliptic coordinate systems. ``EQUINOXa`` (or ``EPOCH`` in older headers). Not applicable to ICRS equatorial or ecliptic coordinates. An undefined value is represented by NaN. """ extlev = """ ``int`` (read-only) ``EXTLEV`` identifying the binary table extension. """ extnam = """ ``str`` (read-only) ``EXTNAME`` identifying the binary table extension. """ extrema = """ ``double array[K_M]...[K_2][2][M]`` (read-only) An array recording the minimum and maximum value of each element of the coordinate vector in each row of the coordinate array, with the dimensions:: (K_M, ... K_2, 2, M) (see `~astropy.wcs.Tabprm.K`). The minimum is recorded in the first element of the compressed K_1 dimension, then the maximum. This array is used by the inverse table lookup function to speed up table searches. """ extver = """ ``int`` (read-only) ``EXTVER`` identifying the binary table extension. """ find_all_wcs = """ find_all_wcs(relax=0, keysel=0) Find all WCS transformations in the header. Parameters ---------- header : str The raw FITS header data. relax : bool or int Degree of permissiveness: - `False`: Recognize only FITS keywords defined by the published WCS standard. - `True`: Admit all recognized informal extensions of the WCS standard. - `int`: a bit field selecting specific extensions to accept. See :ref:`relaxread` for details. keysel : sequence of flags Used to restrict the keyword types considered: - ``WCSHDR_IMGHEAD``: Image header keywords. - ``WCSHDR_BIMGARR``: Binary table image array. - ``WCSHDR_PIXLIST``: Pixel list keywords. If zero, there is no restriction. If -1, `wcspih` is called, rather than `wcstbh`. Returns ------- wcs_list : list of `~astropy.wcs.Wcsprm` objects """ fix = """ fix(translate_units='', naxis=0) Applies all of the corrections handled separately by `~astropy.wcs.Wcsprm.datfix`, `~astropy.wcs.Wcsprm.unitfix`, `~astropy.wcs.Wcsprm.celfix`, `~astropy.wcs.Wcsprm.spcfix`, `~astropy.wcs.Wcsprm.cylfix` and `~astropy.wcs.Wcsprm.cdfix`. Parameters ---------- translate_units : str, optional Specify which potentially unsafe translations of non-standard unit strings to perform. By default, performs all. Although ``"S"`` is commonly used to represent seconds, its translation to ``"s"`` is potentially unsafe since the standard recognizes ``"S"`` formally as Siemens, however rarely that may be used. The same applies to ``"H"`` for hours (Henry), and ``"D"`` for days (Debye). This string controls what to do in such cases, and is case-insensitive. - If the string contains ``"s"``, translate ``"S"`` to ``"s"``. - If the string contains ``"h"``, translate ``"H"`` to ``"h"``. - If the string contains ``"d"``, translate ``"D"`` to ``"d"``. Thus ``''`` doesn't do any unsafe translations, whereas ``'shd'`` does all of them. naxis : int array[naxis], optional Image axis lengths. If this array is set to zero or ``None``, then `~astropy.wcs.Wcsprm.cylfix` will not be invoked. Returns ------- status : dict Returns a dictionary containing the following keys, each referring to a status string for each of the sub-fix functions that were called: - `~astropy.wcs.Wcsprm.cdfix` - `~astropy.wcs.Wcsprm.datfix` - `~astropy.wcs.Wcsprm.unitfix` - `~astropy.wcs.Wcsprm.celfix` - `~astropy.wcs.Wcsprm.spcfix` - `~astropy.wcs.Wcsprm.cylfix` """ get_offset = """ get_offset(x, y) -> (x, y) Returns the offset as defined in the distortion lookup table. Returns ------- coordinate : coordinate pair The offset from the distortion table for pixel point (*x*, *y*). """ get_cdelt = """ get_cdelt() -> double array[naxis] Coordinate increments (``CDELTia``) for each coord axis. Returns the ``CDELT`` offsets in read-only form. Unlike the `~astropy.wcs.Wcsprm.cdelt` property, this works even when the header specifies the linear transformation matrix in one of the alternative ``CDi_ja`` or ``CROTAia`` forms. This is useful when you want access to the linear transformation matrix, but don't care how it was specified in the header. """ get_pc = """ get_pc() -> double array[naxis][naxis] Returns the ``PC`` matrix in read-only form. Unlike the `~astropy.wcs.Wcsprm.pc` property, this works even when the header specifies the linear transformation matrix in one of the alternative ``CDi_ja`` or ``CROTAia`` forms. This is useful when you want access to the linear transformation matrix, but don't care how it was specified in the header. """ get_ps = """ get_ps() -> list of tuples Returns ``PSi_ma`` keywords for each *i* and *m*. Returns ------- ps : list of tuples Returned as a list of tuples of the form (*i*, *m*, *value*): - *i*: int. Axis number, as in ``PSi_ma``, (i.e. 1-relative) - *m*: int. Parameter number, as in ``PSi_ma``, (i.e. 0-relative) - *value*: string. Parameter value. See also -------- astropy.wcs.Wcsprm.set_ps : Set ``PSi_ma`` values """ get_pv = """ get_pv() -> list of tuples Returns ``PVi_ma`` keywords for each *i* and *m*. Returns ------- Returned as a list of tuples of the form (*i*, *m*, *value*): - *i*: int. Axis number, as in ``PVi_ma``, (i.e. 1-relative) - *m*: int. Parameter number, as in ``PVi_ma``, (i.e. 0-relative) - *value*: string. Parameter value. See also -------- astropy.wcs.Wcsprm.set_pv : Set ``PVi_ma`` values Notes ----- Note that, if they were not given, `~astropy.wcs.Wcsprm.set` resets the entries for ``PVi_1a``, ``PVi_2a``, ``PVi_3a``, and ``PVi_4a`` for longitude axis *i* to match (``phi_0``, ``theta_0``), the native longitude and latitude of the reference point given by ``LONPOLEa`` and ``LATPOLEa``. """ has_cd = """ has_cd() -> bool Returns `True` if ``CDi_ja`` is present. ``CDi_ja`` is an alternate specification of the linear transformation matrix, maintained for historical compatibility. Matrix elements in the IRAF convention are equivalent to the product ``CDi_ja = CDELTia * PCi_ja``, but the defaults differ from that of the ``PCi_ja`` matrix. If one or more ``CDi_ja`` keywords are present then all unspecified ``CDi_ja`` default to zero. If no ``CDi_ja`` (or ``CROTAia``) keywords are present, then the header is assumed to be in ``PCi_ja`` form whether or not any ``PCi_ja`` keywords are present since this results in an interpretation of ``CDELTia`` consistent with the original FITS specification. While ``CDi_ja`` may not formally co-exist with ``PCi_ja``, it may co-exist with ``CDELTia`` and ``CROTAia`` which are to be ignored. See also -------- astropy.wcs.Wcsprm.cd : Get the raw ``CDi_ja`` values. """ has_cdi_ja = """ has_cdi_ja() -> bool Alias for `~astropy.wcs.Wcsprm.has_cd`. Maintained for backward compatibility. """ has_crota = """ has_crota() -> bool Returns `True` if ``CROTAia`` is present. ``CROTAia`` is an alternate specification of the linear transformation matrix, maintained for historical compatibility. In the AIPS convention, ``CROTAia`` may only be associated with the latitude axis of a celestial axis pair. It specifies a rotation in the image plane that is applied *after* the ``CDELTia``; any other ``CROTAia`` keywords are ignored. ``CROTAia`` may not formally co-exist with ``PCi_ja``. ``CROTAia`` and ``CDELTia`` may formally co-exist with ``CDi_ja`` but if so are to be ignored. See also -------- astropy.wcs.Wcsprm.crota : Get the raw ``CROTAia`` values """ has_crotaia = """ has_crotaia() -> bool Alias for `~astropy.wcs.Wcsprm.has_crota`. Maintained for backward compatibility. """ has_pc = """ has_pc() -> bool Returns `True` if ``PCi_ja`` is present. ``PCi_ja`` is the recommended way to specify the linear transformation matrix. See also -------- astropy.wcs.Wcsprm.pc : Get the raw ``PCi_ja`` values """ has_pci_ja = """ has_pci_ja() -> bool Alias for `~astropy.wcs.Wcsprm.has_pc`. Maintained for backward compatibility. """ i = """ ``int`` (read-only) Image axis number. """ imgpix_matrix = """ ``double array[2][2]`` (read-only) Inverse of the ``CDELT`` or ``PC`` matrix. Inverse containing the product of the ``CDELTia`` diagonal matrix and the ``PCi_ja`` matrix. """ is_unity = """ is_unity() -> bool Returns `True` if the linear transformation matrix (`~astropy.wcs.Wcsprm.cd`) is unity. """ K = """ ``int array[M]`` (read-only) The lengths of the axes of the coordinate array. An array of length `M` whose elements record the lengths of the axes of the coordinate array and of each indexing vector. """ kind = """ ``str`` (read-only) Character identifying the wcstab array type: - ``'c'``: coordinate array, - ``'i'``: index vector. """ lat = """ ``int`` (read-only) The index into the world coord array containing latitude values. """ latpole = """ ``double`` The native latitude of the celestial pole, ``LATPOLEa`` (deg). """ lattyp = """ ``string`` (read-only) Celestial axis type for latitude. For example, "RA", "DEC", "GLON", "GLAT", etc. extracted from "RA--", "DEC-", "GLON", "GLAT", etc. in the first four characters of ``CTYPEia`` but with trailing dashes removed. """ lng = """ ``int`` (read-only) The index into the world coord array containing longitude values. """ lngtyp = """ ``string`` (read-only) Celestial axis type for longitude. For example, "RA", "DEC", "GLON", "GLAT", etc. extracted from "RA--", "DEC-", "GLON", "GLAT", etc. in the first four characters of ``CTYPEia`` but with trailing dashes removed. """ lonpole = """ ``double`` The native longitude of the celestial pole. ``LONPOLEa`` (deg). """ M = """ ``int`` (read-only) Number of tabular coordinate axes. """ m = """ ``int`` (read-only) Array axis number for index vectors. """ map = """ ``int array[M]`` Association between axes. A vector of length `~astropy.wcs.Tabprm.M` that defines the association between axis *m* in the *M*-dimensional coordinate array (1 <= *m* <= *M*) and the indices of the intermediate world coordinate and world coordinate arrays. When the intermediate and world coordinate arrays contain the full complement of coordinate elements in image-order, as will usually be the case, then ``map[m-1] == i-1`` for axis *i* in the *N*-dimensional image (1 <= *i* <= *N*). In terms of the FITS keywords:: map[PVi_3a - 1] == i - 1. However, a different association may result if the intermediate coordinates, for example, only contains a (relevant) subset of intermediate world coordinate elements. For example, if *M* == 1 for an image with *N* > 1, it is possible to fill the intermediate coordinates with the relevant coordinate element with ``nelem`` set to 1. In this case ``map[0] = 0`` regardless of the value of *i*. """ mix = """ mix(mixpix, mixcel, vspan, vstep, viter, world, pixcrd, origin) Given either the celestial longitude or latitude plus an element of the pixel coordinate, solves for the remaining elements by iterating on the unknown celestial coordinate element using `~astropy.wcs.Wcsprm.s2p`. Parameters ---------- mixpix : int Which element on the pixel coordinate is given. mixcel : int Which element of the celestial coordinate is given. If *mixcel* = ``1``, celestial longitude is given in ``world[self.lng]``, latitude returned in ``world[self.lat]``. If *mixcel* = ``2``, celestial latitude is given in ``world[self.lat]``, longitude returned in ``world[self.lng]``. vspan : pair of floats Solution interval for the celestial coordinate, in degrees. The ordering of the two limits is irrelevant. Longitude ranges may be specified with any convenient normalization, for example ``(-120,+120)`` is the same as ``(240,480)``, except that the solution will be returned with the same normalization, i.e. lie within the interval specified. vstep : float Step size for solution search, in degrees. If ``0``, a sensible, although perhaps non-optimal default will be used. viter : int If a solution is not found then the step size will be halved and the search recommenced. *viter* controls how many times the step size is halved. The allowed range is 5 - 10. world : double array[naxis] World coordinate elements. ``world[self.lng]`` and ``world[self.lat]`` are the celestial longitude and latitude, in degrees. Which is given and which returned depends on the value of *mixcel*. All other elements are given. The results will be written to this array in-place. pixcrd : double array[naxis]. Pixel coordinates. The element indicated by *mixpix* is given and the remaining elements will be written in-place. {0} Returns ------- result : dict Returns a dictionary with the following keys: - *phi* (double array[naxis]) - *theta* (double array[naxis]) - Longitude and latitude in the native coordinate system of the projection, in degrees. - *imgcrd* (double array[naxis]) - Image coordinate elements. ``imgcrd[self.lng]`` and ``imgcrd[self.lat]`` are the projected *x*- and *y*-coordinates, in decimal degrees. - *world* (double array[naxis]) - Another reference to the *world* argument passed in. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. InvalidCoordinateError Invalid world coordinate. NoSolutionError No solution found in the specified interval. See also -------- astropy.wcs.Wcsprm.lat, astropy.wcs.Wcsprm.lng Get the axes numbers for latitude and longitude Notes ----- Initially, the specified solution interval is checked to see if it's a \"crossing\" interval. If it isn't, a search is made for a crossing solution by iterating on the unknown celestial coordinate starting at the upper limit of the solution interval and decrementing by the specified step size. A crossing is indicated if the trial value of the pixel coordinate steps through the value specified. If a crossing interval is found then the solution is determined by a modified form of \"regula falsi\" division of the crossing interval. If no crossing interval was found within the specified solution interval then a search is made for a \"non-crossing\" solution as may arise from a point of tangency. The process is complicated by having to make allowance for the discontinuities that occur in all map projections. Once one solution has been determined others may be found by subsequent invocations of `~astropy.wcs.Wcsprm.mix` with suitably restricted solution intervals. Note the circumstance that arises when the solution point lies at a native pole of a projection in which the pole is represented as a finite curve, for example the zenithals and conics. In such cases two or more valid solutions may exist but `~astropy.wcs.Wcsprm.mix` only ever returns one. Because of its generality, `~astropy.wcs.Wcsprm.mix` is very compute-intensive. For compute-limited applications, more efficient special-case solvers could be written for simple projections, for example non-oblique cylindrical projections. """.format(__.ORIGIN()) mjdavg = """ ``double`` Modified Julian Date corresponding to ``DATE-AVG``. ``(MJD = JD - 2400000.5)``. An undefined value is represented by NaN. See also -------- astropy.wcs.Wcsprm.mjdobs """ mjdobs = """ ``double`` Modified Julian Date corresponding to ``DATE-OBS``. ``(MJD = JD - 2400000.5)``. An undefined value is represented by NaN. See also -------- astropy.wcs.Wcsprm.mjdavg """ name = """ ``string`` The name given to the coordinate representation ``WCSNAMEa``. """ naxis = """ ``int`` (read-only) The number of axes (pixel and coordinate). Given by the ``NAXIS`` or ``WCSAXESa`` keyvalues. The number of coordinate axes is determined at parsing time, and can not be subsequently changed. It is determined from the highest of the following: 1. ``NAXIS`` 2. ``WCSAXESa`` 3. The highest axis number in any parameterized WCS keyword. The keyvalue, as well as the keyword, must be syntactically valid otherwise it will not be considered. If none of these keyword types is present, i.e. if the header only contains auxiliary WCS keywords for a particular coordinate representation, then no coordinate description is constructed for it. This value may differ for different coordinate representations of the same image. """ nc = """ ``int`` (read-only) Total number of coord vectors in the coord array. Total number of coordinate vectors in the coordinate array being the product K_1 * K_2 * ... * K_M. """ ndim = """ ``int`` (read-only) Expected dimensionality of the wcstab array. """ obsgeo = """ ``double array[3]`` Location of the observer in a standard terrestrial reference frame. ``OBSGEO-X``, ``OBSGEO-Y``, ``OBSGEO-Z`` (in meters). An undefined value is represented by NaN. """ p0 = """ ``int array[M]`` Interpolated indices into the coordinate array. Vector of length `~astropy.wcs.Tabprm.M` of interpolated indices into the coordinate array such that Upsilon_m, as defined in Paper III, is equal to ``(p0[m] + 1) + delta[m]``. """ p2s = """ p2s(pixcrd, origin) Converts pixel to world coordinates. Parameters ---------- pixcrd : double array[ncoord][nelem] Array of pixel coordinates. {0} Returns ------- result : dict Returns a dictionary with the following keys: - *imgcrd*: double array[ncoord][nelem] - Array of intermediate world coordinates. For celestial axes, ``imgcrd[][self.lng]`` and ``imgcrd[][self.lat]`` are the projected *x*-, and *y*-coordinates, in pseudo degrees. For spectral axes, ``imgcrd[][self.spec]`` is the intermediate spectral coordinate, in SI units. - *phi*: double array[ncoord] - *theta*: double array[ncoord] - Longitude and latitude in the native coordinate system of the projection, in degrees. - *world*: double array[ncoord][nelem] - Array of world coordinates. For celestial axes, ``world[][self.lng]`` and ``world[][self.lat]`` are the celestial longitude and latitude, in degrees. For spectral axes, ``world[][self.spec]`` is the intermediate spectral coordinate, in SI units. - *stat*: int array[ncoord] - Status return value for each coordinate. ``0`` for success, ``1+`` for invalid pixel coordinate. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. ValueError *x*- and *y*-coordinate arrays are not the same size. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. See also -------- astropy.wcs.Wcsprm.lat, astropy.wcs.Wcsprm.lng Definition of the latitude and longitude axes """.format(__.ORIGIN()) p4_pix2foc = """ p4_pix2foc(*pixcrd, origin*) -> double array[ncoord][nelem] Convert pixel coordinates to focal plane coordinates using `distortion paper`_ lookup-table correction. Parameters ---------- pixcrd : double array[ncoord][nelem]. Array of pixel coordinates. {0} Returns ------- foccrd : double array[ncoord][nelem] Returns an array of focal plane coordinates. Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.ORIGIN()) pc = """ ``double array[naxis][naxis]`` The ``PCi_ja`` (pixel coordinate) transformation matrix. The order is:: [[PC1_1, PC1_2], [PC2_1, PC2_2]] For historical compatibility, three alternate specifications of the linear transformations are available in wcslib. The canonical ``PCi_ja`` with ``CDELTia``, ``CDi_ja``, and the deprecated ``CROTAia`` keywords. Although the latter may not formally co-exist with ``PCi_ja``, the approach here is simply to ignore them if given in conjunction with ``PCi_ja``. `~astropy.wcs.Wcsprm.has_pc`, `~astropy.wcs.Wcsprm.has_cd` and `~astropy.wcs.Wcsprm.has_crota` can be used to determine which of these alternatives are present in the header. These alternate specifications of the linear transformation matrix are translated immediately to ``PCi_ja`` by `~astropy.wcs.Wcsprm.set` and are nowhere visible to the lower-level routines. In particular, `~astropy.wcs.Wcsprm.set` resets `~astropy.wcs.Wcsprm.cdelt` to unity if ``CDi_ja`` is present (and no ``PCi_ja``). If no ``CROTAia`` is associated with the latitude axis, `~astropy.wcs.Wcsprm.set` reverts to a unity ``PCi_ja`` matrix. """ phi0 = """ ``double`` The native latitude of the fiducial point. The point whose celestial coordinates are given in ``ref[1:2]``. If undefined (NaN) the initialization routine, `~astropy.wcs.Wcsprm.set`, will set this to a projection-specific default. See also -------- astropy.wcs.Wcsprm.theta0 """ pix2foc = """ pix2foc(*pixcrd, origin*) -> double array[ncoord][nelem] Perform both `SIP`_ polynomial and `distortion paper`_ lookup-table correction in parallel. Parameters ---------- pixcrd : double array[ncoord][nelem] Array of pixel coordinates. {0} Returns ------- foccrd : double array[ncoord][nelem] Returns an array of focal plane coordinates. Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.ORIGIN()) piximg_matrix = """ ``double array[2][2]`` (read-only) Matrix containing the product of the ``CDELTia`` diagonal matrix and the ``PCi_ja`` matrix. """ print_contents = """ print_contents() Print the contents of the `~astropy.wcs.Wcsprm` object to stdout. Probably only useful for debugging purposes, and may be removed in the future. To get a string of the contents, use `repr`. """ print_contents_tabprm = """ print_contents() Print the contents of the `~astropy.wcs.Tabprm` object to stdout. Probably only useful for debugging purposes, and may be removed in the future. To get a string of the contents, use `repr`. """ radesys = """ ``string`` The equatorial or ecliptic coordinate system type, ``RADESYSa``. """ restfrq = """ ``double`` Rest frequency (Hz) from ``RESTFRQa``. An undefined value is represented by NaN. """ restwav = """ ``double`` Rest wavelength (m) from ``RESTWAVa``. An undefined value is represented by NaN. """ row = """ ``int`` (read-only) Table row number. """ s2p = """ s2p(world, origin) Transforms world coordinates to pixel coordinates. Parameters ---------- world : double array[ncoord][nelem] Array of world coordinates, in decimal degrees. {0} Returns ------- result : dict Returns a dictionary with the following keys: - *phi*: double array[ncoord] - *theta*: double array[ncoord] - Longitude and latitude in the native coordinate system of the projection, in degrees. - *imgcrd*: double array[ncoord][nelem] - Array of intermediate world coordinates. For celestial axes, ``imgcrd[][self.lng]`` and ``imgcrd[][self.lat]`` are the projected *x*-, and *y*-coordinates, in pseudo \"degrees\". For quadcube projections with a ``CUBEFACE`` axis, the face number is also returned in ``imgcrd[][self.cubeface]``. For spectral axes, ``imgcrd[][self.spec]`` is the intermediate spectral coordinate, in SI units. - *pixcrd*: double array[ncoord][nelem] - Array of pixel coordinates. Pixel coordinates are zero-based. - *stat*: int array[ncoord] - Status return value for each coordinate. ``0`` for success, ``1+`` for invalid pixel coordinate. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. See also -------- astropy.wcs.Wcsprm.lat, astropy.wcs.Wcsprm.lng Definition of the latitude and longitude axes """.format(__.ORIGIN()) sense = """ ``int array[M]`` +1 if monotonically increasing, -1 if decreasing. A vector of length `~astropy.wcs.Tabprm.M` whose elements indicate whether the corresponding indexing vector is monotonically increasing (+1), or decreasing (-1). """ set = """ set() Sets up a WCS object for use according to information supplied within it. Note that this routine need not be called directly; it will be invoked by `~astropy.wcs.Wcsprm.p2s` and `~astropy.wcs.Wcsprm.s2p` if necessary. Some attributes that are based on other attributes (such as `~astropy.wcs.Wcsprm.lattyp` on `~astropy.wcs.Wcsprm.ctype`) may not be correct until after `~astropy.wcs.Wcsprm.set` is called. `~astropy.wcs.Wcsprm.set` strips off trailing blanks in all string members. `~astropy.wcs.Wcsprm.set` recognizes the ``NCP`` projection and converts it to the equivalent ``SIN`` projection and it also recognizes ``GLS`` as a synonym for ``SFL``. It does alias translation for the AIPS spectral types (``FREQ-LSR``, ``FELO-HEL``, etc.) but without changing the input header keywords. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. """ set_tabprm = """ set() Allocates memory for work arrays. Also sets up the class according to information supplied within it. Note that this routine need not be called directly; it will be invoked by functions that need it. Raises ------ MemoryError Memory allocation failed. InvalidTabularParameters Invalid tabular parameters. """ set_ps = """ set_ps(ps) Sets ``PSi_ma`` keywords for each *i* and *m*. Parameters ---------- ps : sequence of tuples The input must be a sequence of tuples of the form (*i*, *m*, *value*): - *i*: int. Axis number, as in ``PSi_ma``, (i.e. 1-relative) - *m*: int. Parameter number, as in ``PSi_ma``, (i.e. 0-relative) - *value*: string. Parameter value. See also -------- astropy.wcs.Wcsprm.get_ps """ set_pv = """ set_pv(pv) Sets ``PVi_ma`` keywords for each *i* and *m*. Parameters ---------- pv : list of tuples The input must be a sequence of tuples of the form (*i*, *m*, *value*): - *i*: int. Axis number, as in ``PVi_ma``, (i.e. 1-relative) - *m*: int. Parameter number, as in ``PVi_ma``, (i.e. 0-relative) - *value*: float. Parameter value. See also -------- astropy.wcs.Wcsprm.get_pv """ sip = """ Get/set the `~astropy.wcs.Sip` object for performing `SIP`_ distortion correction. """ Sip = """ Sip(*a, b, ap, bp, crpix*) The `~astropy.wcs.Sip` class performs polynomial distortion correction using the `SIP`_ convention in both directions. Parameters ---------- a : double array[m+1][m+1] The ``A_i_j`` polynomial for pixel to focal plane transformation. Its size must be (*m* + 1, *m* + 1) where *m* = ``A_ORDER``. b : double array[m+1][m+1] The ``B_i_j`` polynomial for pixel to focal plane transformation. Its size must be (*m* + 1, *m* + 1) where *m* = ``B_ORDER``. ap : double array[m+1][m+1] The ``AP_i_j`` polynomial for pixel to focal plane transformation. Its size must be (*m* + 1, *m* + 1) where *m* = ``AP_ORDER``. bp : double array[m+1][m+1] The ``BP_i_j`` polynomial for pixel to focal plane transformation. Its size must be (*m* + 1, *m* + 1) where *m* = ``BP_ORDER``. crpix : double array[2] The reference pixel. Notes ----- Shupe, D. L., M. Moshir, J. Li, D. Makovoz and R. Narron. 2005. "The SIP Convention for Representing Distortion in FITS Image Headers." ADASS XIV. """ sip_foc2pix = """ sip_foc2pix(*foccrd, origin*) -> double array[ncoord][nelem] Convert focal plane coordinates to pixel coordinates using the `SIP`_ polynomial distortion convention. Parameters ---------- foccrd : double array[ncoord][nelem] Array of focal plane coordinates. {0} Returns ------- pixcrd : double array[ncoord][nelem] Returns an array of pixel coordinates. Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.ORIGIN()) sip_pix2foc = """ sip_pix2foc(*pixcrd, origin*) -> double array[ncoord][nelem] Convert pixel coordinates to focal plane coordinates using the `SIP`_ polynomial distortion convention. Parameters ---------- pixcrd : double array[ncoord][nelem] Array of pixel coordinates. {0} Returns ------- foccrd : double array[ncoord][nelem] Returns an array of focal plane coordinates. Raises ------ MemoryError Memory allocation failed. ValueError Invalid coordinate transformation parameters. """.format(__.ORIGIN()) spcfix = """ spcfix() -> int Translates AIPS-convention spectral coordinate types. {``FREQ``, ``VELO``, ``FELO``}-{``OBS``, ``HEL``, ``LSR``} (e.g. ``FREQ-LSR``, ``VELO-OBS``, ``FELO-HEL``) Returns ------- success : int Returns ``0`` for success; ``-1`` if no change required. """ spec = """ ``int`` (read-only) The index containing the spectral axis values. """ specsys = """ ``string`` Spectral reference frame (standard of rest), ``SPECSYSa``. See also -------- astropy.wcs.Wcsprm.ssysobs, astropy.wcs.Wcsprm.velosys """ sptr = """ sptr(ctype, i=-1) Translates the spectral axis in a WCS object. For example, a ``FREQ`` axis may be translated into ``ZOPT-F2W`` and vice versa. Parameters ---------- ctype : str Required spectral ``CTYPEia``, maximum of 8 characters. The first four characters are required to be given and are never modified. The remaining four, the algorithm code, are completely determined by, and must be consistent with, the first four characters. Wildcarding may be used, i.e. if the final three characters are specified as ``\"???\"``, or if just the eighth character is specified as ``\"?\"``, the correct algorithm code will be substituted and returned. i : int Index of the spectral axis (0-relative). If ``i < 0`` (or not provided), it will be set to the first spectral axis identified from the ``CTYPE`` keyvalues in the FITS header. Raises ------ MemoryError Memory allocation failed. SingularMatrixError Linear transformation matrix is singular. InconsistentAxisTypesError Inconsistent or unrecognized coordinate axis types. ValueError Invalid parameter value. InvalidTransformError Invalid coordinate transformation parameters. InvalidTransformError Ill-conditioned coordinate transformation parameters. InvalidSubimageSpecificationError Invalid subimage specification (no spectral axis). """ ssysobs = """ ``string`` Spectral reference frame. The spectral reference frame in which there is no differential variation in the spectral coordinate across the field-of-view, ``SSYSOBSa``. See also -------- astropy.wcs.Wcsprm.specsys, astropy.wcs.Wcsprm.velosys """ ssyssrc = """ ``string`` Spectral reference frame for redshift. The spectral reference frame (standard of rest) in which the redshift was measured, ``SSYSSRCa``. """ sub = """ sub(axes) Extracts the coordinate description for a subimage from a `~astropy.wcs.WCS` object. The world coordinate system of the subimage must be separable in the sense that the world coordinates at any point in the subimage must depend only on the pixel coordinates of the axes extracted. In practice, this means that the ``PCi_ja`` matrix of the original image must not contain non-zero off-diagonal terms that associate any of the subimage axes with any of the non-subimage axes. `sub` can also add axes to a wcsprm object. The new axes will be created using the defaults set by the Wcsprm constructor which produce a simple, unnamed, linear axis with world coordinates equal to the pixel coordinate. These default values can be changed before invoking `set`. Parameters ---------- axes : int or a sequence. - If an int, include the first *N* axes in their original order. - If a sequence, may contain a combination of image axis numbers (1-relative) or special axis identifiers (see below). Order is significant; ``axes[0]`` is the axis number of the input image that corresponds to the first axis in the subimage, etc. Use an axis number of 0 to create a new axis using the defaults. - If ``0``, ``[]`` or ``None``, do a deep copy. Coordinate axes types may be specified using either strings or special integer constants. The available types are: - ``'longitude'`` / ``WCSSUB_LONGITUDE``: Celestial longitude - ``'latitude'`` / ``WCSSUB_LATITUDE``: Celestial latitude - ``'cubeface'`` / ``WCSSUB_CUBEFACE``: Quadcube ``CUBEFACE`` axis - ``'spectral'`` / ``WCSSUB_SPECTRAL``: Spectral axis - ``'stokes'`` / ``WCSSUB_STOKES``: Stokes axis - ``'celestial'`` / ``WCSSUB_CELESTIAL``: An alias for the combination of ``'longitude'``, ``'latitude'`` and ``'cubeface'``. Returns ------- new_wcs : `~astropy.wcs.WCS` object Raises ------ MemoryError Memory allocation failed. InvalidSubimageSpecificationError Invalid subimage specification (no spectral axis). NonseparableSubimageCoordinateSystem Non-separable subimage coordinate system. Notes ----- Combinations of subimage axes of particular types may be extracted in the same order as they occur in the input image by combining the integer constants with the 'binary or' (``|``) operator. For example:: wcs.sub([WCSSUB_LONGITUDE | WCSSUB_LATITUDE | WCSSUB_SPECTRAL]) would extract the longitude, latitude, and spectral axes in the same order as the input image. If one of each were present, the resulting object would have three dimensions. For convenience, ``WCSSUB_CELESTIAL`` is defined as the combination ``WCSSUB_LONGITUDE | WCSSUB_LATITUDE | WCSSUB_CUBEFACE``. The codes may also be negated to extract all but the types specified, for example:: wcs.sub([ WCSSUB_LONGITUDE, WCSSUB_LATITUDE, WCSSUB_CUBEFACE, -(WCSSUB_SPECTRAL | WCSSUB_STOKES)]) The last of these specifies all axis types other than spectral or Stokes. Extraction is done in the order specified by ``axes``, i.e. a longitude axis (if present) would be extracted first (via ``axes[0]``) and not subsequently (via ``axes[3]``). Likewise for the latitude and cubeface axes in this example. The number of dimensions in the returned object may be less than or greater than the length of ``axes``. However, it will never exceed the number of axes in the input image. """ tab = """ ``list of Tabprm`` Tabular coordinate objects. A list of tabular coordinate objects associated with this WCS. """ Tabprm = """ A class to store the information related to tabular coordinates, i.e., coordinates that are defined via a lookup table. This class can not be constructed directly from Python, but instead is returned from `~astropy.wcs.Wcsprm.tab`. """ theta0 = """ ``double`` The native longitude of the fiducial point. The point whose celestial coordinates are given in ``ref[1:2]``. If undefined (NaN) the initialization routine, `~astropy.wcs.Wcsprm.set`, will set this to a projection-specific default. See also -------- astropy.wcs.Wcsprm.phi0 """ to_header = """ to_header(relax=False) `to_header` translates a WCS object into a FITS header. The details of the header depends on context: - If the `~astropy.wcs.Wcsprm.colnum` member is non-zero then a binary table image array header will be produced. - Otherwise, if the `~astropy.wcs.Wcsprm.colax` member is set non-zero then a pixel list header will be produced. - Otherwise, a primary image or image extension header will be produced. The output header will almost certainly differ from the input in a number of respects: 1. The output header only contains WCS-related keywords. In particular, it does not contain syntactically-required keywords such as ``SIMPLE``, ``NAXIS``, ``BITPIX``, or ``END``. 2. Deprecated (e.g. ``CROTAn``) or non-standard usage will be translated to standard (this is partially dependent on whether ``fix`` was applied). 3. Quantities will be converted to the units used internally, basically SI with the addition of degrees. 4. Floating-point quantities may be given to a different decimal precision. 5. Elements of the ``PCi_j`` matrix will be written if and only if they differ from the unit matrix. Thus, if the matrix is unity then no elements will be written. 6. Additional keywords such as ``WCSAXES``, ``CUNITia``, ``LONPOLEa`` and ``LATPOLEa`` may appear. 7. The original keycomments will be lost, although `~astropy.wcs.Wcsprm.to_header` tries hard to write meaningful comments. 8. Keyword order may be changed. Keywords can be translated between the image array, binary table, and pixel lists forms by manipulating the `~astropy.wcs.Wcsprm.colnum` or `~astropy.wcs.Wcsprm.colax` members of the `~astropy.wcs.WCS` object. Parameters ---------- relax : bool or int Degree of permissiveness: - `False`: Recognize only FITS keywords defined by the published WCS standard. - `True`: Admit all recognized informal extensions of the WCS standard. - `int`: a bit field selecting specific extensions to write. See :ref:`relaxwrite` for details. Returns ------- header : str Raw FITS header as a string. """ ttype = """ ``str`` (read-only) ``TTYPEn`` identifying the column of the binary table that contains the wcstab array. """ unitfix = """ unitfix(translate_units='') Translates non-standard ``CUNITia`` keyvalues. For example, ``DEG`` -> ``deg``, also stripping off unnecessary whitespace. Parameters ---------- translate_units : str, optional Do potentially unsafe translations of non-standard unit strings. Although ``\"S\"`` is commonly used to represent seconds, its recognizes ``\"S\"`` formally as Siemens, however rarely that may be translation to ``\"s\"`` is potentially unsafe since the standard used. The same applies to ``\"H\"`` for hours (Henry), and ``\"D\"`` for days (Debye). This string controls what to do in such cases, and is case-insensitive. - If the string contains ``\"s\"``, translate ``\"S\"`` to ``\"s\"``. - If the string contains ``\"h\"``, translate ``\"H\"`` to ``\"h\"``. - If the string contains ``\"d\"``, translate ``\"D\"`` to ``\"d\"``. Thus ``''`` doesn't do any unsafe translations, whereas ``'shd'`` does all of them. Returns ------- success : int Returns ``0`` for success; ``-1`` if no change required. """ velangl = """ ``double`` Velocity angle. The angle in degrees that should be used to decompose an observed velocity into radial and transverse components. An undefined value is represented by NaN. """ velosys = """ ``double`` Relative radial velocity. The relative radial velocity (m/s) between the observer and the selected standard of rest in the direction of the celestial reference coordinate, ``VELOSYSa``. An undefined value is represented by NaN. See also -------- astropy.wcs.Wcsprm.specsys, astropy.wcs.Wcsprm.ssysobs """ velref = """ ``int`` AIPS velocity code. From ``VELREF`` keyword. """ wcs = """ A `~astropy.wcs.Wcsprm` object to perform the basic `wcslib`_ WCS transformation. """ Wcs = """ Wcs(*sip, cpdis, wcsprm, det2im*) Wcs objects amalgamate basic WCS (as provided by `wcslib`_), with `SIP`_ and `distortion paper`_ operations. To perform all distortion corrections and WCS transformation, use ``all_pix2world``. Parameters ---------- sip : `~astropy.wcs.Sip` object or `None` cpdis : A pair of `~astropy.wcs.DistortionLookupTable` objects, or ``(None, None)``. wcsprm : `~astropy.wcs.Wcsprm` object det2im : A pair of `~astropy.wcs.DistortionLookupTable` objects, or ``(None, None)``. """ Wcsprm = """ Wcsprm(header=None, key=' ', relax=False, naxis=2, keysel=0, colsel=None) `~astropy.wcs.Wcsprm` performs the core WCS transformations. .. note:: The members of this object correspond roughly to the key/value pairs in the FITS header. However, they are adjusted and normalized in a number of ways that make performing the WCS transformation easier. Therefore, they can not be relied upon to get the original values in the header. For that, use `astropy.io.fits.Header` directly. The FITS header parsing enforces correct FITS "keyword = value" syntax with regard to the equals sign occurring in columns 9 and 10. However, it does recognize free-format character (NOST 100-2.0, Sect. 5.2.1), integer (Sect. 5.2.3), and floating-point values (Sect. 5.2.4) for all keywords. Parameters ---------- header : An `astropy.io.fits.Header`, string, or `None`. If ``None``, the object will be initialized to default values. key : str, optional The key referring to a particular WCS transform in the header. This may be either ``' '`` or ``'A'``-``'Z'`` and corresponds to the ``\"a\"`` part of ``\"CTYPEia\"``. (*key* may only be provided if *header* is also provided.) relax : bool or int, optional Degree of permissiveness: - `False`: Recognize only FITS keywords defined by the published WCS standard. - `True`: Admit all recognized informal extensions of the WCS standard. - `int`: a bit field selecting specific extensions to accept. See :ref:`relaxread` for details. naxis : int, optional The number of world coordinates axes for the object. (*naxis* may only be provided if *header* is `None`.) keysel : sequence of flag bits, optional Vector of flag bits that may be used to restrict the keyword types considered: - ``WCSHDR_IMGHEAD``: Image header keywords. - ``WCSHDR_BIMGARR``: Binary table image array. - ``WCSHDR_PIXLIST``: Pixel list keywords. If zero, there is no restriction. If -1, the underlying wcslib function ``wcspih()`` is called, rather than ``wcstbh()``. colsel : sequence of int A sequence of table column numbers used to restrict the keywords considered. `None` indicates no restriction. Raises ------ MemoryError Memory allocation failed. ValueError Invalid key. KeyError Key not found in FITS header. """ Wtbarr = """ Classes to construct coordinate lookup tables from a binary table extension (BINTABLE). This class can not be constructed directly from Python, but instead is returned from `~astropy.wcs.Wcsprm.wtb`. """ zsource = """ ``double`` The redshift, ``ZSOURCEa``, of the source. An undefined value is represented by NaN. """ WcsError = """ Base class of all invalid WCS errors. """ SingularMatrix = """ SingularMatrixError() The linear transformation matrix is singular. """ InconsistentAxisTypes = """ InconsistentAxisTypesError() The WCS header inconsistent or unrecognized coordinate axis type(s). """ InvalidTransform = """ InvalidTransformError() The WCS transformation is invalid, or the transformation parameters are invalid. """ InvalidCoordinate = """ InvalidCoordinateError() One or more of the world coordinates is invalid. """ NoSolution = """ NoSolutionError() No solution can be found in the given interval. """ InvalidSubimageSpecification = """ InvalidSubimageSpecificationError() The subimage specification is invalid. """ NonseparableSubimageCoordinateSystem = """ NonseparableSubimageCoordinateSystemError() Non-separable subimage coordinate system. """ NoWcsKeywordsFound = """ NoWcsKeywordsFoundError() No WCS keywords were found in the given header. """ InvalidTabularParameters = """ InvalidTabularParametersError() The given tabular parameters are invalid. """
50bf4573c518b9a1b1ab74cd7341b285efbd06f2fef45f2395a3af90ca47e715
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ The astropy.time package provides functionality for manipulating times and dates. Specific emphasis is placed on supporting time scales (e.g. UTC, TAI, UT1) and time representations (e.g. JD, MJD, ISO 8601) that are used in astronomy. """ import copy import operator from datetime import datetime import numpy as np from ..utils.compat import NUMPY_LT_1_11_2 from .. import units as u, constants as const from .. import _erfa as erfa from ..units import UnitConversionError from ..utils import ShapedLikeNDArray from ..utils.compat.misc import override__dir__ from ..utils.data_info import MixinInfo, data_info_factory from .utils import day_frac from .formats import (TIME_FORMATS, TIME_DELTA_FORMATS, TimeJD, TimeUnique, TimeAstropyTime, TimeDatetime) # Import TimeFromEpoch to avoid breaking code that followed the old example of # making a custom timescale in the documentation. from .formats import TimeFromEpoch # pylint: disable=W0611 __all__ = ['Time', 'TimeDelta', 'TIME_SCALES', 'TIME_DELTA_SCALES', 'ScaleValueError', 'OperandTypeError', 'TimeInfo'] TIME_SCALES = ('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc') MULTI_HOPS = {('tai', 'tcb'): ('tt', 'tdb'), ('tai', 'tcg'): ('tt',), ('tai', 'ut1'): ('utc',), ('tai', 'tdb'): ('tt',), ('tcb', 'tcg'): ('tdb', 'tt'), ('tcb', 'tt'): ('tdb',), ('tcb', 'ut1'): ('tdb', 'tt', 'tai', 'utc'), ('tcb', 'utc'): ('tdb', 'tt', 'tai'), ('tcg', 'tdb'): ('tt',), ('tcg', 'ut1'): ('tt', 'tai', 'utc'), ('tcg', 'utc'): ('tt', 'tai'), ('tdb', 'ut1'): ('tt', 'tai', 'utc'), ('tdb', 'utc'): ('tt', 'tai'), ('tt', 'ut1'): ('tai', 'utc'), ('tt', 'utc'): ('tai',), } GEOCENTRIC_SCALES = ('tai', 'tt', 'tcg') BARYCENTRIC_SCALES = ('tcb', 'tdb') ROTATIONAL_SCALES = ('ut1',) TIME_DELTA_TYPES = dict((scale, scales) for scales in (GEOCENTRIC_SCALES, BARYCENTRIC_SCALES, ROTATIONAL_SCALES) for scale in scales) TIME_DELTA_SCALES = TIME_DELTA_TYPES.keys() # For time scale changes, we need L_G and L_B, which are stored in erfam.h as # /* L_G = 1 - d(TT)/d(TCG) */ # define ERFA_ELG (6.969290134e-10) # /* L_B = 1 - d(TDB)/d(TCB), and TDB (s) at TAI 1977/1/1.0 */ # define ERFA_ELB (1.550519768e-8) # These are exposed in erfa as erfa.ELG and erfa.ELB. # Implied: d(TT)/d(TCG) = 1-L_G # and d(TCG)/d(TT) = 1/(1-L_G) = 1 + (1-(1-L_G))/(1-L_G) = 1 + L_G/(1-L_G) # scale offsets as second = first + first * scale_offset[(first,second)] SCALE_OFFSETS = {('tt', 'tai'): None, ('tai', 'tt'): None, ('tcg', 'tt'): -erfa.ELG, ('tt', 'tcg'): erfa.ELG / (1. - erfa.ELG), ('tcg', 'tai'): -erfa.ELG, ('tai', 'tcg'): erfa.ELG / (1. - erfa.ELG), ('tcb', 'tdb'): -erfa.ELB, ('tdb', 'tcb'): erfa.ELB / (1. - erfa.ELB)} # triple-level dictionary, yay! SIDEREAL_TIME_MODELS = { 'mean': { 'IAU2006': {'function': erfa.gmst06, 'scales': ('ut1', 'tt')}, 'IAU2000': {'function': erfa.gmst00, 'scales': ('ut1', 'tt')}, 'IAU1982': {'function': erfa.gmst82, 'scales': ('ut1',)}}, 'apparent': { 'IAU2006A': {'function': erfa.gst06a, 'scales': ('ut1', 'tt')}, 'IAU2000A': {'function': erfa.gst00a, 'scales': ('ut1', 'tt')}, 'IAU2000B': {'function': erfa.gst00b, 'scales': ('ut1',)}, 'IAU1994': {'function': erfa.gst94, 'scales': ('ut1',)}}} class TimeInfo(MixinInfo): """ Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information. """ attrs_from_parent = set(['unit']) # unit is read-only and None attr_names = MixinInfo.attr_names | {'serialize_method'} _supports_indexing = True # The usual tuple of attributes needed for serialization is replaced # by a property, since Time can be serialized different ways. _represent_as_dict_extra_attrs = ('format', 'scale', 'precision', 'in_subfmt', 'out_subfmt', 'location', '_delta_ut1_utc', '_delta_tdb_tt') mask_val = np.ma.masked @property def _represent_as_dict_attrs(self): method = self.serialize_method[self._serialize_context] if method == 'formatted_value': out = ('value',) elif method == 'jd1_jd2': out = ('jd1', 'jd2') else: raise ValueError("serialize method must be 'formatted_value' or 'jd1_jd2'") return out + self._represent_as_dict_extra_attrs def __init__(self, bound=False): super().__init__(bound) # If bound to a data object instance then create the dict of attributes # which stores the info attribute values. if bound: # Specify how to serialize this object depending on context. # If ``True`` for a context, then use formatted ``value`` attribute # (e.g. the ISO time string). If ``False`` then use float jd1 and jd2. self.serialize_method = {'fits': 'jd1_jd2', 'ecsv': 'formatted_value', 'hdf5': 'jd1_jd2', 'yaml': 'jd1_jd2', None: 'jd1_jd2'} @property def unit(self): return None info_summary_stats = staticmethod( data_info_factory(names=MixinInfo._stats, funcs=[getattr(np, stat) for stat in MixinInfo._stats])) # When Time has mean, std, min, max methods: # funcs = [lambda x: getattr(x, stat)() for stat_name in MixinInfo._stats]) def _construct_from_dict_base(self, map): if 'jd1' in map and 'jd2' in map: format = map.pop('format') map['format'] = 'jd' map['val'] = map.pop('jd1') map['val2'] = map.pop('jd2') else: format = map['format'] map['val'] = map.pop('value') out = self._parent_cls(**map) out.format = format return out def _construct_from_dict(self, map): delta_ut1_utc = map.pop('_delta_ut1_utc', None) delta_tdb_tt = map.pop('_delta_tdb_tt', None) out = self._construct_from_dict_base(map) if delta_ut1_utc is not None: out._delta_ut1_utc = delta_ut1_utc if delta_tdb_tt is not None: out._delta_tdb_tt = delta_tdb_tt return out class TimeDeltaInfo(TimeInfo): _represent_as_dict_extra_attrs = ('format', 'scale') def _construct_from_dict(self, map): return self._construct_from_dict_base(map) class Time(ShapedLikeNDArray): """ Represent and manipulate times and dates for astronomy. A `Time` object is initialized with one or more times in the ``val`` argument. The input times in ``val`` must conform to the specified ``format`` and must correspond to the specified time ``scale``. The optional ``val2`` time input should be supplied only for numeric input formats (e.g. JD) where very high precision (better than 64-bit precision) is required. The allowed values for ``format`` can be listed with:: >>> list(Time.FORMATS) ['jd', 'mjd', 'decimalyear', 'unix', 'cxcsec', 'gps', 'plot_date', 'datetime', 'iso', 'isot', 'yday', 'fits', 'byear', 'jyear', 'byear_str', 'jyear_str'] Parameters ---------- val : sequence, ndarray, number, str, bytes, or `~astropy.time.Time` object Value(s) to initialize the time or times. Bytes are decoded as ascii. val2 : sequence, ndarray, or number; optional Value(s) to initialize the time or times. Only used for numerical input, to help preserve precision. format : str, optional Format of input value(s) scale : str, optional Time scale of input value(s), must be one of the following: ('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc') precision : int, optional Digits of precision in string representation of time in_subfmt : str, optional Subformat for inputting string times out_subfmt : str, optional Subformat for outputting string times location : `~astropy.coordinates.EarthLocation` or tuple, optional If given as an tuple, it should be able to initialize an an EarthLocation instance, i.e., either contain 3 items with units of length for geocentric coordinates, or contain a longitude, latitude, and an optional height for geodetic coordinates. Can be a single location, or one for each input time. copy : bool, optional Make a copy of the input values """ SCALES = TIME_SCALES """List of time scales""" FORMATS = TIME_FORMATS """Dict of time formats""" # Make sure that reverse arithmetic (e.g., TimeDelta.__rmul__) # gets called over the __mul__ of Numpy arrays. __array_priority__ = 20000 # Declare that Time can be used as a Table column by defining the # attribute where column attributes will be stored. _astropy_column_attrs = None def __new__(cls, val, val2=None, format=None, scale=None, precision=None, in_subfmt=None, out_subfmt=None, location=None, copy=False): if isinstance(val, cls): self = val.replicate(format=format, copy=copy) else: self = super().__new__(cls) return self def __getnewargs__(self): return (self._time,) def __init__(self, val, val2=None, format=None, scale=None, precision=None, in_subfmt=None, out_subfmt=None, location=None, copy=False): if location is not None: from ..coordinates import EarthLocation if isinstance(location, EarthLocation): self.location = location else: self.location = EarthLocation(*location) else: self.location = None if isinstance(val, Time): # Update _time formatting parameters if explicitly specified if precision is not None: self._time.precision = precision if in_subfmt is not None: self._time.in_subfmt = in_subfmt if out_subfmt is not None: self._time.out_subfmt = out_subfmt if scale is not None: self._set_scale(scale) else: self._init_from_vals(val, val2, format, scale, copy, precision, in_subfmt, out_subfmt) if self.location is not None and (self.location.size > 1 and self.location.shape != self.shape): try: # check the location can be broadcast to self's shape. self.location = np.broadcast_to(self.location, self.shape, subok=True) except Exception: raise ValueError('The location with shape {0} cannot be ' 'broadcast against time with shape {1}. ' 'Typically, either give a single location or ' 'one for each time.' .format(self.location.shape, self.shape)) def _init_from_vals(self, val, val2, format, scale, copy, precision=None, in_subfmt=None, out_subfmt=None): """ Set the internal _format, scale, and _time attrs from user inputs. This handles coercion into the correct shapes and some basic input validation. """ if precision is None: precision = 3 if in_subfmt is None: in_subfmt = '*' if out_subfmt is None: out_subfmt = '*' # Coerce val into an array val = _make_array(val, copy) # If val2 is not None, ensure consistency if val2 is not None: val2 = _make_array(val2, copy) try: np.broadcast(val, val2) except ValueError: raise ValueError('Input val and val2 have inconsistent shape; ' 'they cannot be broadcast together.') if scale is not None: if not (isinstance(scale, str) and scale.lower() in self.SCALES): raise ScaleValueError("Scale {0!r} is not in the allowed scales " "{1}".format(scale, sorted(self.SCALES))) # If either of the input val, val2 are masked arrays then # find the masked elements and fill them. mask, val, val2 = _check_for_masked_and_fill(val, val2) # Parse / convert input values into internal jd1, jd2 based on format self._time = self._get_time_fmt(val, val2, format, scale, precision, in_subfmt, out_subfmt) self._format = self._time.name # If any inputs were masked then masked jd2 accordingly. From above # routine ``mask`` must be either Python bool False or an bool ndarray # with shape broadcastable to jd2. if mask is not False: mask = np.broadcast_to(mask, self._time.jd2.shape) self._time.jd2[mask] = np.nan def _get_time_fmt(self, val, val2, format, scale, precision, in_subfmt, out_subfmt): """ Given the supplied val, val2, format and scale try to instantiate the corresponding TimeFormat class to convert the input values into the internal jd1 and jd2. If format is `None` and the input is a string-type or object array then guess available formats and stop when one matches. """ if format is None and val.dtype.kind in ('S', 'U', 'O'): formats = [(name, cls) for name, cls in self.FORMATS.items() if issubclass(cls, TimeUnique)] err_msg = ('any of the formats where the format keyword is ' 'optional {0}'.format([name for name, cls in formats])) # AstropyTime is a pseudo-format that isn't in the TIME_FORMATS registry, # but try to guess it at the end. formats.append(('astropy_time', TimeAstropyTime)) elif not (isinstance(format, str) and format.lower() in self.FORMATS): if format is None: raise ValueError("No time format was given, and the input is " "not unique") else: raise ValueError("Format {0!r} is not one of the allowed " "formats {1}".format(format, sorted(self.FORMATS))) else: formats = [(format, self.FORMATS[format])] err_msg = 'the format class {0}'.format(format) for format, FormatClass in formats: try: return FormatClass(val, val2, scale, precision, in_subfmt, out_subfmt) except UnitConversionError: raise except (ValueError, TypeError): pass else: raise ValueError('Input values did not match {0}'.format(err_msg)) @classmethod def now(cls): """ Creates a new object corresponding to the instant in time this method is called. .. note:: "Now" is determined using the `~datetime.datetime.utcnow` function, so its accuracy and precision is determined by that function. Generally that means it is set by the accuracy of your system clock. Returns ------- nowtime A new `Time` object (or a subclass of `Time` if this is called from such a subclass) at the current time. """ # call `utcnow` immediately to be sure it's ASAP dtnow = datetime.utcnow() return cls(val=dtnow, format='datetime', scale='utc') info = TimeInfo() @property def writeable(self): return self._time.jd1.flags.writeable & self._time.jd2.flags.writeable @writeable.setter def writeable(self, value): self._time.jd1.flags.writeable = value self._time.jd2.flags.writeable = value @property def format(self): """ Get or set time format. The format defines the way times are represented when accessed via the ``.value`` attribute. By default it is the same as the format used for initializing the `Time` instance, but it can be set to any other value that could be used for initialization. These can be listed with:: >>> list(Time.FORMATS) ['jd', 'mjd', 'decimalyear', 'unix', 'cxcsec', 'gps', 'plot_date', 'datetime', 'iso', 'isot', 'yday', 'fits', 'byear', 'jyear', 'byear_str', 'jyear_str'] """ return self._format @format.setter def format(self, format): """Set time format""" if format not in self.FORMATS: raise ValueError('format must be one of {0}' .format(list(self.FORMATS))) format_cls = self.FORMATS[format] # If current output subformat is not in the new format then replace # with default '*' if hasattr(format_cls, 'subfmts'): subfmt_names = [subfmt[0] for subfmt in format_cls.subfmts] if self.out_subfmt not in subfmt_names: self.out_subfmt = '*' self._time = format_cls(self._time.jd1, self._time.jd2, self._time._scale, self.precision, in_subfmt=self.in_subfmt, out_subfmt=self.out_subfmt, from_jd=True) self._format = format def __repr__(self): return ("<{0} object: scale='{1}' format='{2}' value={3}>" .format(self.__class__.__name__, self.scale, self.format, getattr(self, self.format))) def __str__(self): return str(getattr(self, self.format)) @property def scale(self): """Time scale""" return self._time.scale def _set_scale(self, scale): """ This is the key routine that actually does time scale conversions. This is not public and not connected to the read-only scale property. """ if scale == self.scale: return if scale not in self.SCALES: raise ValueError("Scale {0!r} is not in the allowed scales {1}" .format(scale, sorted(self.SCALES))) # Determine the chain of scale transformations to get from the current # scale to the new scale. MULTI_HOPS contains a dict of all # transformations (xforms) that require intermediate xforms. # The MULTI_HOPS dict is keyed by (sys1, sys2) in alphabetical order. xform = (self.scale, scale) xform_sort = tuple(sorted(xform)) multi = MULTI_HOPS.get(xform_sort, ()) xforms = xform_sort[:1] + multi + xform_sort[-1:] # If we made the reverse xform then reverse it now. if xform_sort != xform: xforms = tuple(reversed(xforms)) # Transform the jd1,2 pairs through the chain of scale xforms. jd1, jd2 = self._time.jd1, self._time.jd2_filled for sys1, sys2 in zip(xforms[:-1], xforms[1:]): # Some xforms require an additional delta_ argument that is # provided through Time methods. These values may be supplied by # the user or computed based on available approximations. The # get_delta_ methods are available for only one combination of # sys1, sys2 though the property applies for both xform directions. args = [jd1, jd2] for sys12 in ((sys1, sys2), (sys2, sys1)): dt_method = '_get_delta_{0}_{1}'.format(*sys12) try: get_dt = getattr(self, dt_method) except AttributeError: pass else: args.append(get_dt(jd1, jd2)) break conv_func = getattr(erfa, sys1 + sys2) jd1, jd2 = conv_func(*args) if self.masked: jd2[self.mask] = np.nan self._time = self.FORMATS[self.format](jd1, jd2, scale, self.precision, self.in_subfmt, self.out_subfmt, from_jd=True) @property def precision(self): """ Decimal precision when outputting seconds as floating point (int value between 0 and 9 inclusive). """ return self._time.precision @precision.setter def precision(self, val): del self.cache if not isinstance(val, int) or val < 0 or val > 9: raise ValueError('precision attribute must be an int between ' '0 and 9') self._time.precision = val @property def in_subfmt(self): """ Unix wildcard pattern to select subformats for parsing string input times. """ return self._time.in_subfmt @in_subfmt.setter def in_subfmt(self, val): del self.cache if not isinstance(val, str): raise ValueError('in_subfmt attribute must be a string') self._time.in_subfmt = val @property def out_subfmt(self): """ Unix wildcard pattern to select subformats for outputting times. """ return self._time.out_subfmt @out_subfmt.setter def out_subfmt(self, val): del self.cache if not isinstance(val, str): raise ValueError('out_subfmt attribute must be a string') self._time.out_subfmt = val @property def shape(self): """The shape of the time instances. Like `~numpy.ndarray.shape`, can be set to a new shape by assigning a tuple. Note that if different instances share some but not all underlying data, setting the shape of one instance can make the other instance unusable. Hence, it is strongly recommended to get new, reshaped instances with the ``reshape`` method. Raises ------ AttributeError If the shape of the ``jd1``, ``jd2``, ``location``, ``delta_ut1_utc``, or ``delta_tdb_tt`` attributes cannot be changed without the arrays being copied. For these cases, use the `Time.reshape` method (which copies any arrays that cannot be reshaped in-place). """ return self._time.jd1.shape @shape.setter def shape(self, shape): del self.cache # We have to keep track of arrays that were already reshaped, # since we may have to return those to their original shape if a later # shape-setting fails. reshaped = [] oldshape = self.shape # In-place reshape of data/attributes. Need to access _time.jd1/2 not # self.jd1/2 because the latter are not guaranteed to be the actual # data, and in fact should not be directly changeable from the public # API. for obj, attr in ((self._time, 'jd1'), (self._time, 'jd2'), (self, '_delta_ut1_utc'), (self, '_delta_tdb_tt'), (self, 'location')): val = getattr(obj, attr, None) if val is not None and val.size > 1: try: val.shape = shape except AttributeError: for val2 in reshaped: val2.shape = oldshape raise else: reshaped.append(val) def _shaped_like_input(self, value): out = value if not self._time.jd1.shape and not np.ma.is_masked(value): out = value.item() return out @property def jd1(self): """ First of the two doubles that internally store time value(s) in JD. """ jd1 = self._time.mask_if_needed(self._time.jd1) return self._shaped_like_input(jd1) @property def jd2(self): """ Second of the two doubles that internally store time value(s) in JD. """ jd2 = self._time.mask_if_needed(self._time.jd2) return self._shaped_like_input(jd2) @property def value(self): """Time value(s) in current format""" # The underlying way to get the time values for the current format is: # self._shaped_like_input(self._time.to_value(parent=self)) # This is done in __getattr__. By calling getattr(self, self.format) # the ``value`` attribute is cached. return getattr(self, self.format) @property def masked(self): return self._time.masked @property def mask(self): return self._time.mask def _make_value_equivalent(self, item, value): """Coerce setitem value into an equivalent Time object""" # If there is a vector location then broadcast to the Time shape # and then select with ``item`` if self.location is not None and self.location.shape: self_location = np.broadcast_to(self.location, self.shape, subok=True)[item] else: self_location = self.location if isinstance(value, Time): # Make sure locations are compatible. Location can be either None or # a Location object. if self_location is None and value.location is None: match = True elif ((self_location is None and value.location is not None) or (self_location is not None and value.location is None)): match = False else: match = np.all(self_location == value.location) if not match: raise ValueError('cannot set to Time with different location: ' 'expected location={} and ' 'got location={}' .format(self_location, value.location)) else: try: value = self.__class__(value, scale=self.scale, location=self_location) except Exception: try: value = self.__class__(value, scale=self.scale, format=self.format, location=self_location) except Exception as err: raise ValueError('cannot convert value to a compatible Time object: {}' .format(err)) return value def __setitem__(self, item, value): if not self.writeable: if self.shape: raise ValueError('{} object is read-only. Make a ' 'copy() or set "writeable" attribute to True.' .format(self.__class__.__name__)) else: raise ValueError('scalar {} object is read-only.' .format(self.__class__.__name__)) # Any use of setitem results in immediate cache invalidation del self.cache # Setting invalidates transform deltas for attr in ('_delta_tdb_tt', '_delta_ut1_utc'): if hasattr(self, attr): delattr(self, attr) if value in (np.ma.masked, np.nan): self._time.jd2[item] = np.nan return value = self._make_value_equivalent(item, value) # Finally directly set the jd1/2 values. Locations are known to match. if self.scale is not None: value = getattr(value, self.scale) self._time.jd1[item] = value._time.jd1 self._time.jd2[item] = value._time.jd2 def light_travel_time(self, skycoord, kind='barycentric', location=None, ephemeris=None): """Light travel time correction to the barycentre or heliocentre. The frame transformations used to calculate the location of the solar system barycentre and the heliocentre rely on the erfa routine epv00, which is consistent with the JPL DE405 ephemeris to an accuracy of 11.2 km, corresponding to a light travel time of 4 microseconds. The routine assumes the source(s) are at large distance, i.e., neglects finite-distance effects. Parameters ---------- skycoord : `~astropy.coordinates.SkyCoord` The sky location to calculate the correction for. kind : str, optional ``'barycentric'`` (default) or ``'heliocentric'`` location : `~astropy.coordinates.EarthLocation`, optional The location of the observatory to calculate the correction for. If no location is given, the ``location`` attribute of the Time object is used ephemeris : str, optional Solar system ephemeris to use (e.g., 'builtin', 'jpl'). By default, use the one set with ``astropy.coordinates.solar_system_ephemeris.set``. For more information, see `~astropy.coordinates.solar_system_ephemeris`. Returns ------- time_offset : `~astropy.time.TimeDelta` The time offset between the barycentre or Heliocentre and Earth, in TDB seconds. Should be added to the original time to get the time in the Solar system barycentre or the Heliocentre. """ if kind.lower() not in ('barycentric', 'heliocentric'): raise ValueError("'kind' parameter must be one of 'heliocentric' " "or 'barycentric'") if location is None: if self.location is None: raise ValueError('An EarthLocation needs to be set or passed ' 'in to calculate bary- or heliocentric ' 'corrections') location = self.location from ..coordinates import (UnitSphericalRepresentation, CartesianRepresentation, HCRS, ICRS, GCRS, solar_system_ephemeris) # ensure sky location is ICRS compatible if not skycoord.is_transformable_to(ICRS()): raise ValueError("Given skycoord is not transformable to the ICRS") # get location of observatory in ITRS coordinates at this Time try: itrs = location.get_itrs(obstime=self) except Exception: raise ValueError("Supplied location does not have a valid `get_itrs` method") with solar_system_ephemeris.set(ephemeris): if kind.lower() == 'heliocentric': # convert to heliocentric coordinates, aligned with ICRS cpos = itrs.transform_to(HCRS(obstime=self)).cartesian.xyz else: # first we need to convert to GCRS coordinates with the correct # obstime, since ICRS coordinates have no frame time gcrs_coo = itrs.transform_to(GCRS(obstime=self)) # convert to barycentric (BCRS) coordinates, aligned with ICRS cpos = gcrs_coo.transform_to(ICRS()).cartesian.xyz # get unit ICRS vector to star spos = (skycoord.icrs.represent_as(UnitSphericalRepresentation). represent_as(CartesianRepresentation).xyz) # Move X,Y,Z to last dimension, to enable possible broadcasting below. cpos = np.rollaxis(cpos, 0, cpos.ndim) spos = np.rollaxis(spos, 0, spos.ndim) # calculate light travel time correction tcor_val = (spos * cpos).sum(axis=-1) / const.c return TimeDelta(tcor_val, scale='tdb') def sidereal_time(self, kind, longitude=None, model=None): """Calculate sidereal time. Parameters --------------- kind : str ``'mean'`` or ``'apparent'``, i.e., accounting for precession only, or also for nutation. longitude : `~astropy.units.Quantity`, `str`, or `None`; optional The longitude on the Earth at which to compute the sidereal time. Can be given as a `~astropy.units.Quantity` with angular units (or an `~astropy.coordinates.Angle` or `~astropy.coordinates.Longitude`), or as a name of an observatory (currently, only ``'greenwich'`` is supported, equivalent to 0 deg). If `None` (default), the ``lon`` attribute of the Time object is used. model : str or `None`; optional Precession (and nutation) model to use. The available ones are: - {0}: {1} - {2}: {3} If `None` (default), the last (most recent) one from the appropriate list above is used. Returns ------- sidereal time : `~astropy.coordinates.Longitude` Sidereal time as a quantity with units of hourangle """ # docstring is formatted below from ..coordinates import Longitude if kind.lower() not in SIDEREAL_TIME_MODELS.keys(): raise ValueError('The kind of sidereal time has to be {0}'.format( ' or '.join(sorted(SIDEREAL_TIME_MODELS.keys())))) available_models = SIDEREAL_TIME_MODELS[kind.lower()] if model is None: model = sorted(available_models.keys())[-1] else: if model.upper() not in available_models: raise ValueError( 'Model {0} not implemented for {1} sidereal time; ' 'available models are {2}' .format(model, kind, sorted(available_models.keys()))) if longitude is None: if self.location is None: raise ValueError('No longitude is given but the location for ' 'the Time object is not set.') longitude = self.location.lon elif longitude == 'greenwich': longitude = Longitude(0., u.degree, wrap_angle=180.*u.degree) else: # sanity check on input longitude = Longitude(longitude, u.degree, wrap_angle=180.*u.degree) gst = self._erfa_sidereal_time(available_models[model.upper()]) return Longitude(gst + longitude, u.hourangle) if isinstance(sidereal_time.__doc__, str): sidereal_time.__doc__ = sidereal_time.__doc__.format( 'apparent', sorted(SIDEREAL_TIME_MODELS['apparent'].keys()), 'mean', sorted(SIDEREAL_TIME_MODELS['mean'].keys())) def _erfa_sidereal_time(self, model): """Calculate a sidereal time using a IAU precession/nutation model.""" from ..coordinates import Longitude erfa_function = model['function'] erfa_parameters = [getattr(getattr(self, scale)._time, jd_part) for scale in model['scales'] for jd_part in ('jd1', 'jd2_filled')] sidereal_time = erfa_function(*erfa_parameters) if self.masked: sidereal_time[self.mask] = np.nan return Longitude(sidereal_time, u.radian).to(u.hourangle) def copy(self, format=None): """ Return a fully independent copy the Time object, optionally changing the format. If ``format`` is supplied then the time format of the returned Time object will be set accordingly, otherwise it will be unchanged from the original. In this method a full copy of the internal time arrays will be made. The internal time arrays are normally not changeable by the user so in most cases the ``replicate()`` method should be used. Parameters ---------- format : str, optional Time format of the copy. Returns ------- tm : Time object Copy of this object """ return self._apply('copy', format=format) def replicate(self, format=None, copy=False): """ Return a replica of the Time object, optionally changing the format. If ``format`` is supplied then the time format of the returned Time object will be set accordingly, otherwise it will be unchanged from the original. If ``copy`` is set to `True` then a full copy of the internal time arrays will be made. By default the replica will use a reference to the original arrays when possible to save memory. The internal time arrays are normally not changeable by the user so in most cases it should not be necessary to set ``copy`` to `True`. The convenience method copy() is available in which ``copy`` is `True` by default. Parameters ---------- format : str, optional Time format of the replica. copy : bool, optional Return a true copy instead of using references where possible. Returns ------- tm : Time object Replica of this object """ return self._apply('copy' if copy else 'replicate', format=format) def _apply(self, method, *args, format=None, **kwargs): """Create a new time object, possibly applying a method to the arrays. Parameters ---------- method : str or callable If string, can be 'replicate' or the name of a relevant `~numpy.ndarray` method. In the former case, a new time instance with unchanged internal data is created, while in the latter the method is applied to the internal ``jd1`` and ``jd2`` arrays, as well as to possible ``location``, ``_delta_ut1_utc``, and ``_delta_tdb_tt`` arrays. If a callable, it is directly applied to the above arrays. Examples: 'copy', '__getitem__', 'reshape', `~numpy.broadcast_to`. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. If the ``format`` keyword argument is present, this will be used as the Time format of the replica. Examples -------- Some ways this is used internally:: copy : ``_apply('copy')`` replicate : ``_apply('replicate')`` reshape : ``_apply('reshape', new_shape)`` index or slice : ``_apply('__getitem__', item)`` broadcast : ``_apply(np.broadcast, shape=new_shape)`` """ new_format = self.format if format is None else format if callable(method): apply_method = lambda array: method(array, *args, **kwargs) else: if method == 'replicate': apply_method = None else: apply_method = operator.methodcaller(method, *args, **kwargs) jd1, jd2 = self._time.jd1, self._time.jd2 if apply_method: jd1 = apply_method(jd1) jd2 = apply_method(jd2) # Get a new instance of our class and set its attributes directly. tm = super().__new__(self.__class__) tm._time = TimeJD(jd1, jd2, self.scale, self.precision, self.in_subfmt, self.out_subfmt, from_jd=True) # Optional ndarray attributes. for attr in ('_delta_ut1_utc', '_delta_tdb_tt', 'location', 'precision', 'in_subfmt', 'out_subfmt'): try: val = getattr(self, attr) except AttributeError: continue if apply_method: # Apply the method to any value arrays (though skip if there is # only a single element and the method would return a view, # since in that case nothing would change). if getattr(val, 'size', 1) > 1: val = apply_method(val) elif method == 'copy' or method == 'flatten': # flatten should copy also for a single element array, but # we cannot use it directly for array scalars, since it # always returns a one-dimensional array. So, just copy. val = copy.copy(val) setattr(tm, attr, val) # Copy other 'info' attr only if it has actually been defined. # See PR #3898 for further explanation and justification, along # with Quantity.__array_finalize__ if 'info' in self.__dict__: tm.info = self.info # Make the new internal _time object corresponding to the format # in the copy. If the format is unchanged this process is lightweight # and does not create any new arrays. if new_format not in tm.FORMATS: raise ValueError('format must be one of {0}' .format(list(tm.FORMATS))) NewFormat = tm.FORMATS[new_format] tm._time = NewFormat(tm._time.jd1, tm._time.jd2, tm._time._scale, tm.precision, tm.in_subfmt, tm.out_subfmt, from_jd=True) tm._format = new_format return tm def __copy__(self): """ Overrides the default behavior of the `copy.copy` function in the python stdlib to behave like `Time.copy`. Does *not* make a copy of the JD arrays - only copies by reference. """ return self.replicate() def __deepcopy__(self, memo): """ Overrides the default behavior of the `copy.deepcopy` function in the python stdlib to behave like `Time.copy`. Does make a copy of the JD arrays. """ return self.copy() def _advanced_index(self, indices, axis=None, keepdims=False): """Turn argmin, argmax output into an advanced index. Argmin, argmax output contains indices along a given axis in an array shaped like the other dimensions. To use this to get values at the correct location, a list is constructed in which the other axes are indexed sequentially. For ``keepdims`` is ``True``, the net result is the same as constructing an index grid with ``np.ogrid`` and then replacing the ``axis`` item with ``indices`` with its shaped expanded at ``axis``. For ``keepdims`` is ``False``, the result is the same but with the ``axis`` dimension removed from all list entries. For ``axis`` is ``None``, this calls :func:`~numpy.unravel_index`. Parameters ---------- indices : array Output of argmin or argmax. axis : int or None axis along which argmin or argmax was used. keepdims : bool Whether to construct indices that keep or remove the axis along which argmin or argmax was used. Default: ``False``. Returns ------- advanced_index : list of arrays Suitable for use as an advanced index. """ if axis is None: return np.unravel_index(indices, self.shape) ndim = self.ndim if axis < 0: axis = axis + ndim if keepdims and indices.ndim < self.ndim: indices = np.expand_dims(indices, axis) return [(indices if i == axis else np.arange(s).reshape( (1,)*(i if keepdims or i < axis else i-1) + (s,) + (1,)*(ndim-i-(1 if keepdims or i > axis else 2)))) for i, s in enumerate(self.shape)] def argmin(self, axis=None, out=None): """Return indices of the minimum values along the given axis. This is similar to :meth:`~numpy.ndarray.argmin`, but adapted to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is used. See :func:`~numpy.argmin` for detailed documentation. """ # first get the minimum at normal precision. jd = self.jd1 + self.jd2 if NUMPY_LT_1_11_2: # MaskedArray.min ignores keepdims so do it by hand approx = np.min(jd, axis) if axis is not None: approx = np.expand_dims(approx, axis) else: approx = np.min(jd, axis, keepdims=True) # Approx is very close to the true minimum, and by subtracting it at # full precision, all numbers near 0 can be represented correctly, # so we can be sure we get the true minimum. # The below is effectively what would be done for # dt = (self - self.__class__(approx, format='jd')).jd # which translates to: # approx_jd1, approx_jd2 = day_frac(approx, 0.) # dt = (self.jd1 - approx_jd1) + (self.jd2 - approx_jd2) dt = (self.jd1 - approx) + self.jd2 return dt.argmin(axis, out) def argmax(self, axis=None, out=None): """Return indices of the maximum values along the given axis. This is similar to :meth:`~numpy.ndarray.argmax`, but adapted to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is used. See :func:`~numpy.argmax` for detailed documentation. """ # For procedure, see comment on argmin. jd = self.jd1 + self.jd2 if NUMPY_LT_1_11_2: # MaskedArray.max ignores keepdims so do it by hand (numpy <= 1.10) approx = np.max(jd, axis) if axis is not None: approx = np.expand_dims(approx, axis) else: approx = np.max(jd, axis, keepdims=True) dt = (self.jd1 - approx) + self.jd2 return dt.argmax(axis, out) def argsort(self, axis=-1): """Returns the indices that would sort the time array. This is similar to :meth:`~numpy.ndarray.argsort`, but adapted to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is used, and that corresponding attributes are copied. Internally, it uses :func:`~numpy.lexsort`, and hence no sort method can be chosen. """ jd_approx = self.jd jd_remainder = (self - self.__class__(jd_approx, format='jd')).jd if axis is None: return np.lexsort((jd_remainder.ravel(), jd_approx.ravel())) else: return np.lexsort(keys=(jd_remainder, jd_approx), axis=axis) def min(self, axis=None, out=None, keepdims=False): """Minimum along a given axis. This is similar to :meth:`~numpy.ndarray.min`, but adapted to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is used, and that corresponding attributes are copied. Note that the ``out`` argument is present only for compatibility with ``np.min``; since `Time` instances are immutable, it is not possible to have an actual ``out`` to store the result in. """ if out is not None: raise ValueError("Since `Time` instances are immutable, ``out`` " "cannot be set to anything but ``None``.") return self[self._advanced_index(self.argmin(axis), axis, keepdims)] def max(self, axis=None, out=None, keepdims=False): """Maximum along a given axis. This is similar to :meth:`~numpy.ndarray.max`, but adapted to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is used, and that corresponding attributes are copied. Note that the ``out`` argument is present only for compatibility with ``np.max``; since `Time` instances are immutable, it is not possible to have an actual ``out`` to store the result in. """ if out is not None: raise ValueError("Since `Time` instances are immutable, ``out`` " "cannot be set to anything but ``None``.") return self[self._advanced_index(self.argmax(axis), axis, keepdims)] def ptp(self, axis=None, out=None, keepdims=False): """Peak to peak (maximum - minimum) along a given axis. This is similar to :meth:`~numpy.ndarray.ptp`, but adapted to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is used. Note that the ``out`` argument is present only for compatibility with `~numpy.ptp`; since `Time` instances are immutable, it is not possible to have an actual ``out`` to store the result in. """ if out is not None: raise ValueError("Since `Time` instances are immutable, ``out`` " "cannot be set to anything but ``None``.") return (self.max(axis, keepdims=keepdims) - self.min(axis, keepdims=keepdims)) def sort(self, axis=-1): """Return a copy sorted along the specified axis. This is similar to :meth:`~numpy.ndarray.sort`, but internally uses indexing with :func:`~numpy.lexsort` to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is kept, and that corresponding attributes are properly sorted and copied as well. Parameters ---------- axis : int or None Axis to be sorted. If ``None``, the flattened array is sorted. By default, sort over the last axis. """ return self[self._advanced_index(self.argsort(axis), axis, keepdims=True)] @property def cache(self): """ Return the cache associated with this instance. """ return self._time.cache @cache.deleter def cache(self): del self._time.cache def __getattr__(self, attr): """ Get dynamic attributes to output format or do timescale conversion. """ if attr in self.SCALES and self.scale is not None: cache = self.cache['scale'] if attr not in cache: if attr == self.scale: tm = self else: tm = self.replicate() tm._set_scale(attr) if tm.shape: # Prevent future modification of cached array-like object tm.writeable = False cache[attr] = tm return cache[attr] elif attr in self.FORMATS: cache = self.cache['format'] if attr not in cache: if attr == self.format: tm = self else: tm = self.replicate(format=attr) value = tm._shaped_like_input(tm._time.to_value(parent=tm)) cache[attr] = value return cache[attr] elif attr in TIME_SCALES: # allowed ones done above (self.SCALES) if self.scale is None: raise ScaleValueError("Cannot convert TimeDelta with " "undefined scale to any defined scale.") else: raise ScaleValueError("Cannot convert {0} with scale " "'{1}' to scale '{2}'" .format(self.__class__.__name__, self.scale, attr)) else: # Should raise AttributeError return self.__getattribute__(attr) @override__dir__ def __dir__(self): result = set(self.SCALES) result.update(self.FORMATS) return result def _match_shape(self, val): """ Ensure that `val` is matched to length of self. If val has length 1 then broadcast, otherwise cast to double and make sure shape matches. """ val = _make_array(val, copy=True) # be conservative and copy if val.size > 1 and val.shape != self.shape: try: # check the value can be broadcast to the shape of self. val = np.broadcast_to(val, self.shape, subok=True) except Exception: raise ValueError('Attribute shape must match or be ' 'broadcastable to that of Time object. ' 'Typically, give either a single value or ' 'one for each time.') return val def get_delta_ut1_utc(self, iers_table=None, return_status=False): """Find UT1 - UTC differences by interpolating in IERS Table. Parameters ---------- iers_table : ``astropy.utils.iers.IERS`` table, optional Table containing UT1-UTC differences from IERS Bulletins A and/or B. If `None`, use default version (see ``astropy.utils.iers``) return_status : bool Whether to return status values. If `False` (default), iers raises `IndexError` if any time is out of the range covered by the IERS table. Returns ------- ut1_utc : float or float array UT1-UTC, interpolated in IERS Table status : int or int array Status values (if ``return_status=`True```):: ``astropy.utils.iers.FROM_IERS_B`` ``astropy.utils.iers.FROM_IERS_A`` ``astropy.utils.iers.FROM_IERS_A_PREDICTION`` ``astropy.utils.iers.TIME_BEFORE_IERS_RANGE`` ``astropy.utils.iers.TIME_BEYOND_IERS_RANGE`` Notes ----- In normal usage, UT1-UTC differences are calculated automatically on the first instance ut1 is needed. Examples -------- To check in code whether any times are before the IERS table range:: >>> from astropy.utils.iers import TIME_BEFORE_IERS_RANGE >>> t = Time(['1961-01-01', '2000-01-01'], scale='utc') >>> delta, status = t.get_delta_ut1_utc(return_status=True) >>> status == TIME_BEFORE_IERS_RANGE array([ True, False]...) """ if iers_table is None: from ..utils.iers import IERS iers_table = IERS.open() return iers_table.ut1_utc(self.utc, return_status=return_status) # Property for ERFA DUT arg = UT1 - UTC def _get_delta_ut1_utc(self, jd1=None, jd2=None): """ Get ERFA DUT arg = UT1 - UTC. This getter takes optional jd1 and jd2 args because it gets called that way when converting time scales. If delta_ut1_utc is not yet set, this will interpolate them from the the IERS table. """ # Sec. 4.3.1: the arg DUT is the quantity delta_UT1 = UT1 - UTC in # seconds. It is obtained from tables published by the IERS. if not hasattr(self, '_delta_ut1_utc'): from ..utils.iers import IERS_Auto iers_table = IERS_Auto.open() # jd1, jd2 are normally set (see above), except if delta_ut1_utc # is access directly; ensure we behave as expected for that case if jd1 is None: self_utc = self.utc jd1, jd2 = self_utc._time.jd1, self_utc._time.jd2_filled scale = 'utc' else: scale = self.scale # interpolate UT1-UTC in IERS table delta = iers_table.ut1_utc(jd1, jd2) # if we interpolated using UT1 jds, we may be off by one # second near leap seconds (and very slightly off elsewhere) if scale == 'ut1': # calculate UTC using the offset we got; the ERFA routine # is tolerant of leap seconds, so will do this right jd1_utc, jd2_utc = erfa.ut1utc(jd1, jd2, delta) # calculate a better estimate using the nearly correct UTC delta = iers_table.ut1_utc(jd1_utc, jd2_utc) self._set_delta_ut1_utc(delta) return self._delta_ut1_utc def _set_delta_ut1_utc(self, val): del self.cache if hasattr(val, 'to'): # Matches Quantity but also TimeDelta. val = val.to(u.second).value val = self._match_shape(val) self._delta_ut1_utc = val # Note can't use @property because _get_delta_tdb_tt is explicitly # called with the optional jd1 and jd2 args. delta_ut1_utc = property(_get_delta_ut1_utc, _set_delta_ut1_utc) """UT1 - UTC time scale offset""" # Property for ERFA DTR arg = TDB - TT def _get_delta_tdb_tt(self, jd1=None, jd2=None): if not hasattr(self, '_delta_tdb_tt'): # If jd1 and jd2 are not provided (which is the case for property # attribute access) then require that the time scale is TT or TDB. # Otherwise the computations here are not correct. if jd1 is None or jd2 is None: if self.scale not in ('tt', 'tdb'): raise ValueError('Accessing the delta_tdb_tt attribute ' 'is only possible for TT or TDB time ' 'scales') else: jd1 = self._time.jd1 jd2 = self._time.jd2_filled # First go from the current input time (which is either # TDB or TT) to an approximate UT1. Since TT and TDB are # pretty close (few msec?), assume TT. Similarly, since the # UT1 terms are very small, use UTC instead of UT1. njd1, njd2 = erfa.tttai(jd1, jd2) njd1, njd2 = erfa.taiutc(njd1, njd2) # subtract 0.5, so UT is fraction of the day from midnight ut = day_frac(njd1 - 0.5, njd2)[1] if self.location is None: from ..coordinates import EarthLocation location = EarthLocation.from_geodetic(0., 0., 0.) else: location = self.location # Geodetic params needed for d_tdb_tt() lon = location.lon rxy = np.hypot(location.x, location.y) z = location.z self._delta_tdb_tt = erfa.dtdb( jd1, jd2, ut, lon.to_value(u.radian), rxy.to_value(u.km), z.to_value(u.km)) return self._delta_tdb_tt def _set_delta_tdb_tt(self, val): del self.cache if hasattr(val, 'to'): # Matches Quantity but also TimeDelta. val = val.to(u.second).value val = self._match_shape(val) self._delta_tdb_tt = val # Note can't use @property because _get_delta_tdb_tt is explicitly # called with the optional jd1 and jd2 args. delta_tdb_tt = property(_get_delta_tdb_tt, _set_delta_tdb_tt) """TDB - TT time scale offset""" def __sub__(self, other): if not isinstance(other, Time): try: other = TimeDelta(other) except Exception: raise OperandTypeError(self, other, '-') # Tdelta - something is dealt with in TimeDelta, so we have # T - Tdelta = T # T - T = Tdelta other_is_delta = isinstance(other, TimeDelta) # we need a constant scale to calculate, which is guaranteed for # TimeDelta, but not for Time (which can be UTC) if other_is_delta: # T - Tdelta out = self.replicate() if self.scale in other.SCALES: if other.scale not in (out.scale, None): other = getattr(other, out.scale) else: out._set_scale(other.scale if other.scale is not None else 'tai') # remove attributes that are invalidated by changing time for attr in ('_delta_ut1_utc', '_delta_tdb_tt'): if hasattr(out, attr): delattr(out, attr) else: # T - T self_time = (self._time if self.scale in TIME_DELTA_SCALES else self.tai._time) # set up TimeDelta, subtraction to be done shortly out = TimeDelta(self_time.jd1, self_time.jd2, format='jd', scale=self_time.scale) if other.scale != out.scale: other = getattr(other, out.scale) jd1 = out._time.jd1 - other._time.jd1 jd2 = out._time.jd2 - other._time.jd2 out._time.jd1, out._time.jd2 = day_frac(jd1, jd2) if other_is_delta: # Go back to left-side scale if needed out._set_scale(self.scale) return out def __add__(self, other): if not isinstance(other, Time): try: other = TimeDelta(other) except Exception: raise OperandTypeError(self, other, '+') # Tdelta + something is dealt with in TimeDelta, so we have # T + Tdelta = T # T + T = error if not isinstance(other, TimeDelta): raise OperandTypeError(self, other, '+') # ideally, we calculate in the scale of the Time item, since that is # what we want the output in, but this may not be possible, since # TimeDelta cannot be converted arbitrarily out = self.replicate() if self.scale in other.SCALES: if other.scale not in (out.scale, None): other = getattr(other, out.scale) else: out._set_scale(other.scale if other.scale is not None else 'tai') # remove attributes that are invalidated by changing time for attr in ('_delta_ut1_utc', '_delta_tdb_tt'): if hasattr(out, attr): delattr(out, attr) jd1 = out._time.jd1 + other._time.jd1 jd2 = out._time.jd2 + other._time.jd2 out._time.jd1, out._time.jd2 = day_frac(jd1, jd2) # Go back to left-side scale if needed out._set_scale(self.scale) return out def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): out = self.__sub__(other) return -out def _time_difference(self, other, op=None): """If other is of same class as self, return difference in self.scale. Otherwise, raise OperandTypeError. """ if other.__class__ is not self.__class__: try: other = self.__class__(other, scale=self.scale) except Exception: raise OperandTypeError(self, other, op) if(self.scale is not None and self.scale not in other.SCALES or other.scale is not None and other.scale not in self.SCALES): raise TypeError("Cannot compare TimeDelta instances with scales " "'{0}' and '{1}'".format(self.scale, other.scale)) if self.scale is not None and other.scale is not None: other = getattr(other, self.scale) return (self.jd1 - other.jd1) + (self.jd2 - other.jd2) def __lt__(self, other): return self._time_difference(other, '<') < 0. def __le__(self, other): return self._time_difference(other, '<=') <= 0. def __eq__(self, other): """ If other is an incompatible object for comparison, return `False`. Otherwise, return `True` if the time difference between self and other is zero. """ try: diff = self._time_difference(other) except OperandTypeError: return False return diff == 0. def __ne__(self, other): """ If other is an incompatible object for comparison, return `True`. Otherwise, return `False` if the time difference between self and other is zero. """ try: diff = self._time_difference(other) except OperandTypeError: return True return diff != 0. def __gt__(self, other): return self._time_difference(other, '>') > 0. def __ge__(self, other): return self._time_difference(other, '>=') >= 0. def to_datetime(self, timezone=None): tm = self.replicate(format='datetime') return tm._shaped_like_input(tm._time.to_value(timezone)) to_datetime.__doc__ = TimeDatetime.to_value.__doc__ class TimeDelta(Time): """ Represent the time difference between two times. A TimeDelta object is initialized with one or more times in the ``val`` argument. The input times in ``val`` must conform to the specified ``format``. The optional ``val2`` time input should be supplied only for numeric input formats (e.g. JD) where very high precision (better than 64-bit precision) is required. The allowed values for ``format`` can be listed with:: >>> list(TimeDelta.FORMATS) ['sec', 'jd'] Note that for time differences, the scale can be among three groups: geocentric ('tai', 'tt', 'tcg'), barycentric ('tcb', 'tdb'), and rotational ('ut1'). Within each of these, the scales for time differences are the same. Conversion between geocentric and barycentric is possible, as there is only a scale factor change, but one cannot convert to or from 'ut1', as this requires knowledge of the actual times, not just their difference. For a similar reason, 'utc' is not a valid scale for a time difference: a UTC day is not always 86400 seconds. Parameters ---------- val : sequence, ndarray, number, or `~astropy.time.TimeDelta` object Value(s) to initialize the time difference(s). val2 : numpy ndarray, list, str, or number; optional Additional values, as needed to preserve precision. format : str, optional Format of input value(s) scale : str, optional Time scale of input value(s), must be one of the following values: ('tdb', 'tt', 'ut1', 'tcg', 'tcb', 'tai'). If not given (or ``None``), the scale is arbitrary; when added or subtracted from a ``Time`` instance, it will be used without conversion. copy : bool, optional Make a copy of the input values """ SCALES = TIME_DELTA_SCALES """List of time delta scales.""" FORMATS = TIME_DELTA_FORMATS """Dict of time delta formats.""" info = TimeDeltaInfo() def __init__(self, val, val2=None, format=None, scale=None, copy=False): if isinstance(val, TimeDelta): if scale is not None: self._set_scale(scale) else: if format is None: try: val = val.to(u.day) if val2 is not None: val2 = val2.to(u.day) except Exception: raise ValueError('Only Quantities with Time units can ' 'be used to initiate {0} instances .' .format(self.__class__.__name__)) format = 'jd' self._init_from_vals(val, val2, format, scale, copy) if scale is not None: self.SCALES = TIME_DELTA_TYPES[scale] def replicate(self, *args, **kwargs): out = super().replicate(*args, **kwargs) out.SCALES = self.SCALES return out def _set_scale(self, scale): """ This is the key routine that actually does time scale conversions. This is not public and not connected to the read-only scale property. """ if scale == self.scale: return if scale not in self.SCALES: raise ValueError("Scale {0!r} is not in the allowed scales {1}" .format(scale, sorted(self.SCALES))) # For TimeDelta, there can only be a change in scale factor, # which is written as time2 - time1 = scale_offset * time1 scale_offset = SCALE_OFFSETS[(self.scale, scale)] if scale_offset is None: self._time.scale = scale else: jd1, jd2 = self._time.jd1, self._time.jd2 offset1, offset2 = day_frac(jd1, jd2, factor=scale_offset) self._time = self.FORMATS[self.format]( jd1 + offset1, jd2 + offset2, scale, self.precision, self.in_subfmt, self.out_subfmt, from_jd=True) def __add__(self, other): # only deal with TimeDelta + TimeDelta if isinstance(other, Time): if not isinstance(other, TimeDelta): return other.__add__(self) else: try: other = TimeDelta(other) except Exception: raise OperandTypeError(self, other, '+') # the scales should be compatible (e.g., cannot convert TDB to TAI) if(self.scale is not None and self.scale not in other.SCALES or other.scale is not None and other.scale not in self.SCALES): raise TypeError("Cannot add TimeDelta instances with scales " "'{0}' and '{1}'".format(self.scale, other.scale)) # adjust the scale of other if the scale of self is set (or no scales) if self.scale is not None or other.scale is None: out = self.replicate() if other.scale is not None: other = getattr(other, self.scale) else: out = other.replicate() jd1 = self._time.jd1 + other._time.jd1 jd2 = self._time.jd2 + other._time.jd2 out._time.jd1, out._time.jd2 = day_frac(jd1, jd2) return out def __sub__(self, other): # only deal with TimeDelta - TimeDelta if isinstance(other, Time): if not isinstance(other, TimeDelta): raise OperandTypeError(self, other, '-') else: try: other = TimeDelta(other) except Exception: raise OperandTypeError(self, other, '-') # the scales should be compatible (e.g., cannot convert TDB to TAI) if(self.scale is not None and self.scale not in other.SCALES or other.scale is not None and other.scale not in self.SCALES): raise TypeError("Cannot subtract TimeDelta instances with scales " "'{0}' and '{1}'".format(self.scale, other.scale)) # adjust the scale of other if the scale of self is set (or no scales) if self.scale is not None or other.scale is None: out = self.replicate() if other.scale is not None: other = getattr(other, self.scale) else: out = other.replicate() jd1 = self._time.jd1 - other._time.jd1 jd2 = self._time.jd2 - other._time.jd2 out._time.jd1, out._time.jd2 = day_frac(jd1, jd2) return out def __neg__(self): """Negation of a `TimeDelta` object.""" new = self.copy() new._time.jd1 = -self._time.jd1 new._time.jd2 = -self._time.jd2 return new def __abs__(self): """Absolute value of a `TimeDelta` object.""" jd1, jd2 = self._time.jd1, self._time.jd2 negative = jd1 + jd2 < 0 new = self.copy() new._time.jd1 = np.where(negative, -jd1, jd1) new._time.jd2 = np.where(negative, -jd2, jd2) return new def __mul__(self, other): """Multiplication of `TimeDelta` objects by numbers/arrays.""" # check needed since otherwise the self.jd1 * other multiplication # would enter here again (via __rmul__) if isinstance(other, Time): raise OperandTypeError(self, other, '*') try: # convert to straight float if dimensionless quantity other = other.to(1) except Exception: pass try: jd1, jd2 = day_frac(self.jd1, self.jd2, factor=other) out = TimeDelta(jd1, jd2, format='jd', scale=self.scale) except Exception as err: # try downgrading self to a quantity try: return self.to(u.day) * other except Exception: raise err if self.format != 'jd': out = out.replicate(format=self.format) return out def __rmul__(self, other): """Multiplication of numbers/arrays with `TimeDelta` objects.""" return self.__mul__(other) def __div__(self, other): """Division of `TimeDelta` objects by numbers/arrays.""" return self.__truediv__(other) def __rdiv__(self, other): """Division by `TimeDelta` objects of numbers/arrays.""" return self.__rtruediv__(other) def __truediv__(self, other): """Division of `TimeDelta` objects by numbers/arrays.""" # cannot do __mul__(1./other) as that looses precision try: other = other.to(1) except Exception: pass try: # convert to straight float if dimensionless quantity jd1, jd2 = day_frac(self.jd1, self.jd2, divisor=other) out = TimeDelta(jd1, jd2, format='jd', scale=self.scale) except Exception as err: # try downgrading self to a quantity try: return self.to(u.day) / other except Exception: raise err if self.format != 'jd': out = out.replicate(format=self.format) return out def __rtruediv__(self, other): """Division by `TimeDelta` objects of numbers/arrays.""" return other / self.to(u.day) def to(self, *args, **kwargs): return u.Quantity(self._time.jd1 + self._time.jd2, u.day).to(*args, **kwargs) def _make_value_equivalent(self, item, value): """Coerce setitem value into an equivalent TimeDelta object""" if not isinstance(value, TimeDelta): try: value = self.__class__(value, scale=self.scale) except Exception: try: value = self.__class__(value, scale=self.scale, format=self.format) except Exception as err: raise ValueError('cannot convert value to a compatible TimeDelta ' 'object: {}'.format(err)) return value class ScaleValueError(Exception): pass def _make_array(val, copy=False): """ Take ``val`` and convert/reshape to an array. If ``copy`` is `True` then copy input values. Returns ------- val : ndarray Array version of ``val``. """ val = np.array(val, copy=copy, subok=True) # Allow only float64, string or object arrays as input # (object is for datetime, maybe add more specific test later?) # This also ensures the right byteorder for float64 (closes #2942). if not (val.dtype == np.float64 or val.dtype.kind in 'OSUa'): val = np.asanyarray(val, dtype=np.float64) return val def _check_for_masked_and_fill(val, val2): """ If ``val`` or ``val2`` are masked arrays then fill them and cast to ndarray. Returns a mask corresponding to the logical-or of masked elements in ``val`` and ``val2``. If neither is masked then the return ``mask`` is ``None``. If either ``val`` or ``val2`` are masked then they are replaced with filled versions of themselves. Parameters ---------- val : ndarray or MaskedArray Input val val2 : ndarray or MaskedArray Input val2 Returns ------- mask, val, val2: ndarray or None Mask: (None or bool ndarray), val, val2: ndarray """ def get_as_filled_ndarray(mask, val): """ Fill the given MaskedArray ``val`` from the first non-masked element in the array. This ensures that upstream Time initialization will succeed. Note that nothing happens if there are no masked elements. """ fill_value = None if np.any(val.mask): # Final mask is the logical-or of inputs mask = mask | val.mask # First unmasked element. If all elements are masked then # use fill_value=None from above which will use val.fill_value. # As long as the user has set this appropriately then all will # be fine. val_unmasked = val.compressed() # 1-d ndarray of unmasked values if len(val_unmasked) > 0: fill_value = val_unmasked[0] # Fill the input ``val``. If fill_value is None then this just returns # an ndarray view of val (no copy). val = val.filled(fill_value) return mask, val mask = False if isinstance(val, np.ma.MaskedArray): mask, val = get_as_filled_ndarray(mask, val) if isinstance(val2, np.ma.MaskedArray): mask, val2 = get_as_filled_ndarray(mask, val2) return mask, val, val2 class OperandTypeError(TypeError): def __init__(self, left, right, op=None): op_string = '' if op is None else ' for {0}'.format(op) super().__init__( "Unsupported operand type(s){0}: " "'{1}' and '{2}'".format(op_string, left.__class__.__name__, right.__class__.__name__))
a3c5e37f7199380d0243f348fc06b5553214b7a71a429636412c8f77f9f03ec0
# Licensed under a 3-clause BSD style license - see LICENSE.rst from .formats import * from .core import *
ee3290b62e1ef54c315362e5d6e336dabb108d3b3044cbee9a54e14cfb1e782a
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """Time utilities. In particular, routines to do basic arithmetic on numbers represented by two doubles, using the procedure of Shewchuk, 1997, Discrete & Computational Geometry 18(3):305-363 -- http://www.cs.berkeley.edu/~jrs/papers/robustr.pdf """ import numpy as np def day_frac(val1, val2, factor=1., divisor=1.): """ Return the sum of ``val1`` and ``val2`` as two float64s, an integer part and the fractional remainder. If ``factor`` is not 1.0 then multiply the sum by ``factor``. If ``divisor`` is not 1.0 then divide the sum by ``divisor``. The arithmetic is all done with exact floating point operations so no precision is lost to rounding error. This routine assumes the sum is less than about 1e16, otherwise the ``frac`` part will be greater than 1.0. Returns ------- day, frac : float64 Integer and fractional part of val1 + val2. """ # Add val1 and val2 exactly, returning the result as two float64s. # The first is the approximate sum (with some floating point error) # and the second is the error of the float64 sum. sum12, err12 = two_sum(val1, val2) if np.any(factor != 1.): sum12, carry = two_product(sum12, factor) carry += err12 * factor sum12, err12 = two_sum(sum12, carry) if np.any(divisor != 1.): q1 = sum12 / divisor p1, p2 = two_product(q1, divisor) d1, d2 = two_sum(sum12, -p1) d2 += err12 d2 -= p2 q2 = (d1 + d2) / divisor # 3-part float fine here; nothing can be lost sum12, err12 = two_sum(q1, q2) # get integer fraction day = np.round(sum12) extra, frac = two_sum(sum12, -day) frac += extra + err12 return day, frac def two_sum(a, b): """ Add ``a`` and ``b`` exactly, returning the result as two float64s. The first is the approximate sum (with some floating point error) and the second is the error of the float64 sum. Using the procedure of Shewchuk, 1997, Discrete & Computational Geometry 18(3):305-363 http://www.cs.berkeley.edu/~jrs/papers/robustr.pdf Returns ------- sum, err : float64 Approximate sum of a + b and the exact floating point error """ x = a + b eb = x - a eb = b - eb ea = x - b ea = a - ea return x, ea + eb def two_product(a, b): """ Multiple ``a`` and ``b`` exactly, returning the result as two float64s. The first is the approximate product (with some floating point error) and the second is the error of the float64 product. Uses the procedure of Shewchuk, 1997, Discrete & Computational Geometry 18(3):305-363 http://www.cs.berkeley.edu/~jrs/papers/robustr.pdf Returns ------- prod, err : float64 Approximate product a * b and the exact floating point error """ x = a * b ah, al = split(a) bh, bl = split(b) y1 = ah * bh y = x - y1 y2 = al * bh y -= y2 y3 = ah * bl y -= y3 y4 = al * bl y = y4 - y return x, y def split(a): """ Split float64 in two aligned parts. Uses the procedure of Shewchuk, 1997, Discrete & Computational Geometry 18(3):305-363 http://www.cs.berkeley.edu/~jrs/papers/robustr.pdf """ c = 134217729. * a # 2**27+1. abig = c - a ah = c - abig al = a - ah return ah, al
010f5ae304e453501cb5889f35faac8aca55953fe720522f260e2574686c1e37
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import fnmatch import time import re import datetime from collections import OrderedDict, defaultdict import numpy as np from ..utils.decorators import lazyproperty from .. import units as u from .. import _erfa as erfa from .utils import day_frac, two_sum __all__ = ['TimeFormat', 'TimeJD', 'TimeMJD', 'TimeFromEpoch', 'TimeUnix', 'TimeCxcSec', 'TimeGPS', 'TimeDecimalYear', 'TimePlotDate', 'TimeUnique', 'TimeDatetime', 'TimeString', 'TimeISO', 'TimeISOT', 'TimeFITS', 'TimeYearDayTime', 'TimeEpochDate', 'TimeBesselianEpoch', 'TimeJulianEpoch', 'TimeDeltaFormat', 'TimeDeltaSec', 'TimeDeltaJD', 'TimeEpochDateString', 'TimeBesselianEpochString', 'TimeJulianEpochString', 'TIME_FORMATS', 'TIME_DELTA_FORMATS', 'TimezoneInfo'] __doctest_skip__ = ['TimePlotDate'] # These both get filled in at end after TimeFormat subclasses defined. # Use an OrderedDict to fix the order in which formats are tried. # This ensures, e.g., that 'isot' gets tried before 'fits'. TIME_FORMATS = OrderedDict() TIME_DELTA_FORMATS = OrderedDict() # Translations between deprecated FITS timescales defined by # Rots et al. 2015, A&A 574:A36, and timescales used here. FITS_DEPRECATED_SCALES = {'TDT': 'tt', 'ET': 'tt', 'GMT': 'utc', 'UT': 'utc', 'IAT': 'tai'} def _regexify_subfmts(subfmts): """ Iterate through each of the sub-formats and try substituting simple regular expressions for the strptime codes for year, month, day-of-month, hour, minute, second. If no % characters remain then turn the final string into a compiled regex. This assumes time formats do not have a % in them. This is done both to speed up parsing of strings and to allow mixed formats where strptime does not quite work well enough. """ new_subfmts = [] for subfmt_tuple in subfmts: subfmt_in = subfmt_tuple[1] for strptime_code, regex in (('%Y', r'(?P<year>\d\d\d\d)'), ('%m', r'(?P<mon>\d{1,2})'), ('%d', r'(?P<mday>\d{1,2})'), ('%H', r'(?P<hour>\d{1,2})'), ('%M', r'(?P<min>\d{1,2})'), ('%S', r'(?P<sec>\d{1,2})')): subfmt_in = subfmt_in.replace(strptime_code, regex) if '%' not in subfmt_in: subfmt_tuple = (subfmt_tuple[0], re.compile(subfmt_in + '$'), subfmt_tuple[2]) new_subfmts.append(subfmt_tuple) return tuple(new_subfmts) class TimeFormatMeta(type): """ Metaclass that adds `TimeFormat` and `TimeDeltaFormat` to the `TIME_FORMATS` and `TIME_DELTA_FORMATS` registries, respectively. """ _registry = TIME_FORMATS def __new__(mcls, name, bases, members): cls = super().__new__(mcls, name, bases, members) # Register time formats that have a name, but leave out astropy_time since # it is not a user-accessible format and is only used for initialization into # a different format. if 'name' in members and cls.name != 'astropy_time': mcls._registry[cls.name] = cls if 'subfmts' in members: cls.subfmts = _regexify_subfmts(members['subfmts']) return cls class TimeFormat(metaclass=TimeFormatMeta): """ Base class for time representations. Parameters ---------- val1 : numpy ndarray, list, number, str, or bytes Values to initialize the time or times. Bytes are decoded as ascii. val2 : numpy ndarray, list, or number; optional Value(s) to initialize the time or times. Only used for numerical input, to help preserve precision. scale : str Time scale of input value(s) precision : int Precision for seconds as floating point in_subfmt : str Select subformat for inputting string times out_subfmt : str Select subformat for outputting string times from_jd : bool If true then val1, val2 are jd1, jd2 """ def __init__(self, val1, val2, scale, precision, in_subfmt, out_subfmt, from_jd=False): self.scale = scale # validation of scale done later with _check_scale self.precision = precision self.in_subfmt = in_subfmt self.out_subfmt = out_subfmt if from_jd: self.jd1 = val1 self.jd2 = val2 else: val1, val2 = self._check_val_type(val1, val2) self.set_jds(val1, val2) def __len__(self): return len(self.jd1) @property def scale(self): """Time scale""" self._scale = self._check_scale(self._scale) return self._scale @scale.setter def scale(self, val): self._scale = val def mask_if_needed(self, value): if self.masked: value = np.ma.array(value, mask=self.mask, copy=False) return value @property def mask(self): if 'mask' not in self.cache: self.cache['mask'] = np.isnan(self.jd2) if self.cache['mask'].shape: self.cache['mask'].flags.writeable = False return self.cache['mask'] @property def masked(self): if 'masked' not in self.cache: self.cache['masked'] = bool(np.any(self.mask)) return self.cache['masked'] @property def jd2_filled(self): return np.nan_to_num(self.jd2) if self.masked else self.jd2 @lazyproperty def cache(self): """ Return the cache associated with this instance. """ return defaultdict(dict) def _check_val_type(self, val1, val2): """Input value validation, typically overridden by derived classes""" # val1 cannot contain nan, but val2 can contain nan ok1 = val1.dtype == np.double and np.all(np.isfinite(val1)) ok2 = val2 is None or (val2.dtype == np.double and not np.any(np.isinf(val2))) if not (ok1 and ok2): raise TypeError('Input values for {0} class must be finite doubles' .format(self.name)) if getattr(val1, 'unit', None) is not None: # Possibly scaled unit any quantity-likes should be converted to _unit = u.CompositeUnit(getattr(self, 'unit', 1.), [u.day], [1]) val1 = u.Quantity(val1, copy=False).to_value(_unit) if val2 is not None: val2 = u.Quantity(val2, copy=False).to_value(_unit) elif getattr(val2, 'unit', None) is not None: raise TypeError('Cannot mix float and Quantity inputs') if val2 is None: val2 = np.zeros_like(val1) def asarray_or_scalar(val): """ Remove ndarray subclasses since for jd1/jd2 we want a pure ndarray or a Python or numpy scalar. """ return np.asarray(val) if isinstance(val, np.ndarray) else val return asarray_or_scalar(val1), asarray_or_scalar(val2) def _check_scale(self, scale): """ Return a validated scale value. If there is a class attribute 'scale' then that defines the default / required time scale for this format. In this case if a scale value was provided that needs to match the class default, otherwise return the class default. Otherwise just make sure that scale is in the allowed list of scales. Provide a different error message if `None` (no value) was supplied. """ if hasattr(self.__class__, 'epoch_scale') and scale is None: scale = self.__class__.epoch_scale if scale is None: scale = 'utc' # Default scale as of astropy 0.4 if scale not in TIME_SCALES: raise ScaleValueError("Scale value '{0}' not in " "allowed values {1}" .format(scale, TIME_SCALES)) return scale def set_jds(self, val1, val2): """ Set internal jd1 and jd2 from val1 and val2. Must be provided by derived classes. """ raise NotImplementedError def to_value(self, parent=None): """ Return time representation from internal jd1 and jd2. This is the base method that ignores ``parent`` and requires that subclasses implement the ``value`` property. Subclasses that require ``parent`` or have other optional args for ``to_value`` should compute and return the value directly. """ return self.mask_if_needed(self.value) @property def value(self): raise NotImplementedError class TimeJD(TimeFormat): """ Julian Date time format. This represents the number of days since the beginning of the Julian Period. For example, 2451544.5 in JD is midnight on January 1, 2000. """ name = 'jd' def set_jds(self, val1, val2): self._check_scale(self._scale) # Validate scale. self.jd1, self.jd2 = day_frac(val1, val2) @property def value(self): return self.jd1 + self.jd2 class TimeMJD(TimeFormat): """ Modified Julian Date time format. This represents the number of days since midnight on November 17, 1858. For example, 51544.0 in MJD is midnight on January 1, 2000. """ name = 'mjd' def set_jds(self, val1, val2): # TODO - this routine and vals should be Cythonized to follow the ERFA # convention of preserving precision by adding to the larger of the two # values in a vectorized operation. But in most practical cases the # first one is probably biggest. self._check_scale(self._scale) # Validate scale. jd1, jd2 = day_frac(val1, val2) jd1 += erfa.DJM0 # erfa.DJM0=2400000.5 (from erfam.h) self.jd1, self.jd2 = day_frac(jd1, jd2) @property def value(self): return (self.jd1 - erfa.DJM0) + self.jd2 class TimeDecimalYear(TimeFormat): """ Time as a decimal year, with integer values corresponding to midnight of the first day of each year. For example 2000.5 corresponds to the ISO time '2000-07-02 00:00:00'. """ name = 'decimalyear' def set_jds(self, val1, val2): self._check_scale(self._scale) # Validate scale. sum12, err12 = two_sum(val1, val2) iy_start = np.trunc(sum12).astype(int) extra, y_frac = two_sum(sum12, -iy_start) y_frac += extra + err12 val = (val1 + val2).astype(np.double) iy_start = np.trunc(val).astype(int) imon = np.ones_like(iy_start) iday = np.ones_like(iy_start) ihr = np.zeros_like(iy_start) imin = np.zeros_like(iy_start) isec = np.zeros_like(y_frac) # Possible enhancement: use np.unique to only compute start, stop # for unique values of iy_start. scale = self.scale.upper().encode('ascii') jd1_start, jd2_start = erfa.dtf2d(scale, iy_start, imon, iday, ihr, imin, isec) jd1_end, jd2_end = erfa.dtf2d(scale, iy_start + 1, imon, iday, ihr, imin, isec) t_start = Time(jd1_start, jd2_start, scale=self.scale, format='jd') t_end = Time(jd1_end, jd2_end, scale=self.scale, format='jd') t_frac = t_start + (t_end - t_start) * y_frac self.jd1, self.jd2 = day_frac(t_frac.jd1, t_frac.jd2) @property def value(self): scale = self.scale.upper().encode('ascii') iy_start, ims, ids, ihmsfs = erfa.d2dtf(scale, 0, # precision=0 self.jd1, self.jd2_filled) imon = np.ones_like(iy_start) iday = np.ones_like(iy_start) ihr = np.zeros_like(iy_start) imin = np.zeros_like(iy_start) isec = np.zeros_like(self.jd1) # Possible enhancement: use np.unique to only compute start, stop # for unique values of iy_start. scale = self.scale.upper().encode('ascii') jd1_start, jd2_start = erfa.dtf2d(scale, iy_start, imon, iday, ihr, imin, isec) jd1_end, jd2_end = erfa.dtf2d(scale, iy_start + 1, imon, iday, ihr, imin, isec) dt = (self.jd1 - jd1_start) + (self.jd2 - jd2_start) dt_end = (jd1_end - jd1_start) + (jd2_end - jd2_start) decimalyear = iy_start + dt / dt_end return decimalyear class TimeFromEpoch(TimeFormat): """ Base class for times that represent the interval from a particular epoch as a floating point multiple of a unit time interval (e.g. seconds or days). """ def __init__(self, val1, val2, scale, precision, in_subfmt, out_subfmt, from_jd=False): self.scale = scale # Initialize the reference epoch (a single time defined in subclasses) epoch = Time(self.epoch_val, self.epoch_val2, scale=self.epoch_scale, format=self.epoch_format) self.epoch = epoch # Now create the TimeFormat object as normal super().__init__(val1, val2, scale, precision, in_subfmt, out_subfmt, from_jd) def set_jds(self, val1, val2): """ Initialize the internal jd1 and jd2 attributes given val1 and val2. For an TimeFromEpoch subclass like TimeUnix these will be floats giving the effective seconds since an epoch time (e.g. 1970-01-01 00:00:00). """ # Form new JDs based on epoch time + time from epoch (converted to JD). # One subtlety that might not be obvious is that 1.000 Julian days in # UTC can be 86400 or 86401 seconds. For the TimeUnix format the # assumption is that every day is exactly 86400 seconds, so this is, in # principle, doing the math incorrectly, *except* that it matches the # definition of Unix time which does not include leap seconds. # note: use divisor=1./self.unit, since this is either 1 or 1/86400, # and 1/86400 is not exactly representable as a float64, so multiplying # by that will cause rounding errors. (But inverting it as a float64 # recovers the exact number) day, frac = day_frac(val1, val2, divisor=1. / self.unit) jd1 = self.epoch.jd1 + day jd2 = self.epoch.jd2 + frac # Create a temporary Time object corresponding to the new (jd1, jd2) in # the epoch scale (e.g. UTC for TimeUnix) then convert that to the # desired time scale for this object. # # A known limitation is that the transform from self.epoch_scale to # self.scale cannot involve any metadata like lat or lon. try: tm = getattr(Time(jd1, jd2, scale=self.epoch_scale, format='jd'), self.scale) except Exception as err: raise ScaleValueError("Cannot convert from '{0}' epoch scale '{1}'" "to specified scale '{2}', got error:\n{3}" .format(self.name, self.epoch_scale, self.scale, err)) self.jd1, self.jd2 = day_frac(tm._time.jd1, tm._time.jd2) def to_value(self, parent=None): # Make sure that scale is the same as epoch scale so we can just # subtract the epoch and convert if self.scale != self.epoch_scale: if parent is None: raise ValueError('cannot compute value without parent Time object') tm = getattr(parent, self.epoch_scale) jd1, jd2 = tm._time.jd1, tm._time.jd2 else: jd1, jd2 = self.jd1, self.jd2 time_from_epoch = ((jd1 - self.epoch.jd1) + (jd2 - self.epoch.jd2)) / self.unit return self.mask_if_needed(time_from_epoch) value = property(to_value) class TimeUnix(TimeFromEpoch): """ Unix time: seconds from 1970-01-01 00:00:00 UTC. For example, 946684800.0 in Unix time is midnight on January 1, 2000. NOTE: this quantity is not exactly unix time and differs from the strict POSIX definition by up to 1 second on days with a leap second. POSIX unix time actually jumps backward by 1 second at midnight on leap second days while this class value is monotonically increasing at 86400 seconds per UTC day. """ name = 'unix' unit = 1.0 / erfa.DAYSEC # in days (1 day == 86400 seconds) epoch_val = '1970-01-01 00:00:00' epoch_val2 = None epoch_scale = 'utc' epoch_format = 'iso' class TimeCxcSec(TimeFromEpoch): """ Chandra X-ray Center seconds from 1998-01-01 00:00:00 TT. For example, 63072064.184 is midnight on January 1, 2000. """ name = 'cxcsec' unit = 1.0 / erfa.DAYSEC # in days (1 day == 86400 seconds) epoch_val = '1998-01-01 00:00:00' epoch_val2 = None epoch_scale = 'tt' epoch_format = 'iso' class TimeGPS(TimeFromEpoch): """GPS time: seconds from 1980-01-06 00:00:00 UTC For example, 630720013.0 is midnight on January 1, 2000. Notes ===== This implementation is strictly a representation of the number of seconds (including leap seconds) since midnight UTC on 1980-01-06. GPS can also be considered as a time scale which is ahead of TAI by a fixed offset (to within about 100 nanoseconds). For details, see http://tycho.usno.navy.mil/gpstt.html """ name = 'gps' unit = 1.0 / erfa.DAYSEC # in days (1 day == 86400 seconds) epoch_val = '1980-01-06 00:00:19' # above epoch is the same as Time('1980-01-06 00:00:00', scale='utc').tai epoch_val2 = None epoch_scale = 'tai' epoch_format = 'iso' class TimePlotDate(TimeFromEpoch): """ Matplotlib `~matplotlib.pyplot.plot_date` input: 1 + number of days from 0001-01-01 00:00:00 UTC This can be used directly in the matplotlib `~matplotlib.pyplot.plot_date` function:: >>> import matplotlib.pyplot as plt >>> jyear = np.linspace(2000, 2001, 20) >>> t = Time(jyear, format='jyear', scale='utc') >>> plt.plot_date(t.plot_date, jyear) >>> plt.gcf().autofmt_xdate() # orient date labels at a slant >>> plt.draw() For example, 730120.0003703703 is midnight on January 1, 2000. """ # This corresponds to the zero reference time for matplotlib plot_date(). # Note that TAI and UTC are equivalent at the reference time. name = 'plot_date' unit = 1.0 epoch_val = 1721424.5 # Time('0001-01-01 00:00:00', scale='tai').jd - 1 epoch_val2 = None epoch_scale = 'utc' epoch_format = 'jd' class TimeUnique(TimeFormat): """ Base class for time formats that can uniquely create a time object without requiring an explicit format specifier. This class does nothing but provide inheritance to identify a class as unique. """ class TimeAstropyTime(TimeUnique): """ Instantiate date from an Astropy Time object (or list thereof). This is purely for instantiating from a Time object. The output format is the same as the first time instance. """ name = 'astropy_time' def __new__(cls, val1, val2, scale, precision, in_subfmt, out_subfmt, from_jd=False): """ Use __new__ instead of __init__ to output a class instance that is the same as the class of the first Time object in the list. """ val1_0 = val1.flat[0] if not (isinstance(val1_0, Time) and all(type(val) is type(val1_0) for val in val1.flat)): raise TypeError('Input values for {0} class must all be same ' 'astropy Time type.'.format(cls.name)) if scale is None: scale = val1_0.scale if val1.shape: vals = [getattr(val, scale)._time for val in val1] jd1 = np.concatenate([np.atleast_1d(val.jd1) for val in vals]) jd2 = np.concatenate([np.atleast_1d(val.jd2) for val in vals]) else: val = getattr(val1_0, scale)._time jd1, jd2 = val.jd1, val.jd2 OutTimeFormat = val1_0._time.__class__ self = OutTimeFormat(jd1, jd2, scale, precision, in_subfmt, out_subfmt, from_jd=True) return self class TimeDatetime(TimeUnique): """ Represent date as Python standard library `~datetime.datetime` object Example:: >>> from astropy.time import Time >>> from datetime import datetime >>> t = Time(datetime(2000, 1, 2, 12, 0, 0), scale='utc') >>> t.iso '2000-01-02 12:00:00.000' >>> t.tt.datetime datetime.datetime(2000, 1, 2, 12, 1, 4, 184000) """ name = 'datetime' def _check_val_type(self, val1, val2): # Note: don't care about val2 for this class if not all(isinstance(val, datetime.datetime) for val in val1.flat): raise TypeError('Input values for {0} class must be ' 'datetime objects'.format(self.name)) return val1, None def set_jds(self, val1, val2): """Convert datetime object contained in val1 to jd1, jd2""" # Iterate through the datetime objects, getting year, month, etc. iterator = np.nditer([val1, None, None, None, None, None, None], flags=['refs_ok'], op_dtypes=[object] + 5*[np.intc] + [np.double]) for val, iy, im, id, ihr, imin, dsec in iterator: dt = val.item() if dt.tzinfo is not None: dt = (dt - dt.utcoffset()).replace(tzinfo=None) iy[...] = dt.year im[...] = dt.month id[...] = dt.day ihr[...] = dt.hour imin[...] = dt.minute dsec[...] = dt.second + dt.microsecond / 1e6 jd1, jd2 = erfa.dtf2d(self.scale.upper().encode('ascii'), *iterator.operands[1:]) self.jd1, self.jd2 = day_frac(jd1, jd2) def to_value(self, timezone=None, parent=None): """ Convert to (potentially timezone-aware) `~datetime.datetime` object. If ``timezone`` is not ``None``, return a timezone-aware datetime object. Parameters ---------- timezone : {`~datetime.tzinfo`, None} (optional) If not `None`, return timezone-aware datetime. Returns ------- `~datetime.datetime` If ``timezone`` is not ``None``, output will be timezone-aware. """ if timezone is not None: if self._scale != 'utc': raise ScaleValueError("scale is {}, must be 'utc' when timezone " "is supplied.".format(self._scale)) # Rather than define a value property directly, we have a function, # since we want to be able to pass in timezone information. scale = self.scale.upper().encode('ascii') iys, ims, ids, ihmsfs = erfa.d2dtf(scale, 6, # 6 for microsec self.jd1, self.jd2_filled) ihrs = ihmsfs[..., 0] imins = ihmsfs[..., 1] isecs = ihmsfs[..., 2] ifracs = ihmsfs[..., 3] iterator = np.nditer([iys, ims, ids, ihrs, imins, isecs, ifracs, None], flags=['refs_ok'], op_dtypes=7*[iys.dtype] + [object]) for iy, im, id, ihr, imin, isec, ifracsec, out in iterator: if isec >= 60: raise ValueError('Time {} is within a leap second but datetime ' 'does not support leap seconds' .format((iy, im, id, ihr, imin, isec, ifracsec))) if timezone is not None: out[...] = datetime.datetime(iy, im, id, ihr, imin, isec, ifracsec, tzinfo=TimezoneInfo()).astimezone(timezone) else: out[...] = datetime.datetime(iy, im, id, ihr, imin, isec, ifracsec) return self.mask_if_needed(iterator.operands[-1]) value = property(to_value) class TimezoneInfo(datetime.tzinfo): """ Subclass of the `~datetime.tzinfo` object, used in the to_datetime method to specify timezones. It may be safer in most cases to use a timezone database package like pytz rather than defining your own timezones - this class is mainly a workaround for users without pytz. """ @u.quantity_input(utc_offset=u.day, dst=u.day) def __init__(self, utc_offset=0*u.day, dst=0*u.day, tzname=None): """ Parameters ---------- utc_offset : `~astropy.units.Quantity` (optional) Offset from UTC in days. Defaults to zero. dst : `~astropy.units.Quantity` (optional) Daylight Savings Time offset in days. Defaults to zero (no daylight savings). tzname : string, `None` (optional) Name of timezone Examples -------- >>> from datetime import datetime >>> from astropy.time import TimezoneInfo # Specifies a timezone >>> import astropy.units as u >>> utc = TimezoneInfo() # Defaults to UTC >>> utc_plus_one_hour = TimezoneInfo(utc_offset=1*u.hour) # UTC+1 >>> dt_aware = datetime(2000, 1, 1, 0, 0, 0, tzinfo=utc_plus_one_hour) >>> print(dt_aware) 2000-01-01 00:00:00+01:00 >>> print(dt_aware.astimezone(utc)) 1999-12-31 23:00:00+00:00 """ if utc_offset == 0 and dst == 0 and tzname is None: tzname = 'UTC' self._utcoffset = datetime.timedelta(utc_offset.to_value(u.day)) self._tzname = tzname self._dst = datetime.timedelta(dst.to_value(u.day)) def utcoffset(self, dt): return self._utcoffset def tzname(self, dt): return str(self._tzname) def dst(self, dt): return self._dst class TimeString(TimeUnique): """ Base class for string-like time representations. This class assumes that anything following the last decimal point to the right is a fraction of a second. This is a reference implementation can be made much faster with effort. """ def _check_val_type(self, val1, val2): # Note: don't care about val2 for these classes if val1.dtype.kind not in ('S', 'U'): raise TypeError('Input values for {0} class must be strings' .format(self.name)) return val1, None def parse_string(self, timestr, subfmts): """Read time from a single string, using a set of possible formats.""" # Datetime components required for conversion to JD by ERFA, along # with the default values. components = ('year', 'mon', 'mday', 'hour', 'min', 'sec') defaults = (None, 1, 1, 0, 0, 0) # Assume that anything following "." on the right side is a # floating fraction of a second. try: idot = timestr.rindex('.') except Exception: fracsec = 0.0 else: timestr, fracsec = timestr[:idot], timestr[idot:] fracsec = float(fracsec) for _, strptime_fmt_or_regex, _ in subfmts: if isinstance(strptime_fmt_or_regex, str): try: tm = time.strptime(timestr, strptime_fmt_or_regex) except ValueError: continue else: vals = [getattr(tm, 'tm_' + component) for component in components] else: tm = re.match(strptime_fmt_or_regex, timestr) if tm is None: continue tm = tm.groupdict() vals = [int(tm.get(component, default)) for component, default in zip(components, defaults)] # Add fractional seconds vals[-1] = vals[-1] + fracsec return vals else: raise ValueError('Time {0} does not match {1} format' .format(timestr, self.name)) def set_jds(self, val1, val2): """Parse the time strings contained in val1 and set jd1, jd2""" # Select subformats based on current self.in_subfmt subfmts = self._select_subfmts(self.in_subfmt) # Be liberal in what we accept: convert bytes to ascii. # Here .item() is needed for arrays with entries of unequal length, # to strip trailing 0 bytes. to_string = (str if val1.dtype.kind == 'U' else lambda x: str(x.item(), encoding='ascii')) iterator = np.nditer([val1, None, None, None, None, None, None], op_dtypes=[val1.dtype] + 5*[np.intc] + [np.double]) for val, iy, im, id, ihr, imin, dsec in iterator: val = to_string(val) iy[...], im[...], id[...], ihr[...], imin[...], dsec[...] = ( self.parse_string(val, subfmts)) jd1, jd2 = erfa.dtf2d(self.scale.upper().encode('ascii'), *iterator.operands[1:]) self.jd1, self.jd2 = day_frac(jd1, jd2) def str_kwargs(self): """ Generator that yields a dict of values corresponding to the calendar date and time for the internal JD values. """ scale = self.scale.upper().encode('ascii'), iys, ims, ids, ihmsfs = erfa.d2dtf(scale, self.precision, self.jd1, self.jd2_filled) # Get the str_fmt element of the first allowed output subformat _, _, str_fmt = self._select_subfmts(self.out_subfmt)[0] if '{yday:' in str_fmt: has_yday = True else: has_yday = False yday = None ihrs = ihmsfs[..., 0] imins = ihmsfs[..., 1] isecs = ihmsfs[..., 2] ifracs = ihmsfs[..., 3] for iy, im, id, ihr, imin, isec, ifracsec in np.nditer( [iys, ims, ids, ihrs, imins, isecs, ifracs]): if has_yday: yday = datetime.datetime(iy, im, id).timetuple().tm_yday yield {'year': int(iy), 'mon': int(im), 'day': int(id), 'hour': int(ihr), 'min': int(imin), 'sec': int(isec), 'fracsec': int(ifracsec), 'yday': yday} def format_string(self, str_fmt, **kwargs): """Write time to a string using a given format. By default, just interprets str_fmt as a format string, but subclasses can add to this. """ return str_fmt.format(**kwargs) @property def value(self): # Select the first available subformat based on current # self.out_subfmt subfmts = self._select_subfmts(self.out_subfmt) _, _, str_fmt = subfmts[0] # TODO: fix this ugly hack if self.precision > 0 and str_fmt.endswith('{sec:02d}'): str_fmt += '.{fracsec:0' + str(self.precision) + 'd}' # Try to optimize this later. Can't pre-allocate because length of # output could change, e.g. year rolls from 999 to 1000. outs = [] for kwargs in self.str_kwargs(): outs.append(str(self.format_string(str_fmt, **kwargs))) return np.array(outs).reshape(self.jd1.shape) def _select_subfmts(self, pattern): """ Return a list of subformats where name matches ``pattern`` using fnmatch. """ fnmatchcase = fnmatch.fnmatchcase subfmts = [x for x in self.subfmts if fnmatchcase(x[0], pattern)] if len(subfmts) == 0: raise ValueError('No subformats match {0}'.format(pattern)) return subfmts class TimeISO(TimeString): """ ISO 8601 compliant date-time format "YYYY-MM-DD HH:MM:SS.sss...". For example, 2000-01-01 00:00:00.000 is midnight on January 1, 2000. The allowed subformats are: - 'date_hms': date + hours, mins, secs (and optional fractional secs) - 'date_hm': date + hours, mins - 'date': date """ name = 'iso' subfmts = (('date_hms', '%Y-%m-%d %H:%M:%S', # XXX To Do - use strftime for output ?? '{year:d}-{mon:02d}-{day:02d} {hour:02d}:{min:02d}:{sec:02d}'), ('date_hm', '%Y-%m-%d %H:%M', '{year:d}-{mon:02d}-{day:02d} {hour:02d}:{min:02d}'), ('date', '%Y-%m-%d', '{year:d}-{mon:02d}-{day:02d}')) def parse_string(self, timestr, subfmts): # Handle trailing 'Z' for UTC time if timestr.endswith('Z'): if self.scale != 'utc': raise ValueError("Time input terminating in 'Z' must have " "scale='UTC'") timestr = timestr[:-1] return super().parse_string(timestr, subfmts) class TimeISOT(TimeISO): """ ISO 8601 compliant date-time format "YYYY-MM-DDTHH:MM:SS.sss...". This is the same as TimeISO except for a "T" instead of space between the date and time. For example, 2000-01-01T00:00:00.000 is midnight on January 1, 2000. The allowed subformats are: - 'date_hms': date + hours, mins, secs (and optional fractional secs) - 'date_hm': date + hours, mins - 'date': date """ name = 'isot' subfmts = (('date_hms', '%Y-%m-%dT%H:%M:%S', '{year:d}-{mon:02d}-{day:02d}T{hour:02d}:{min:02d}:{sec:02d}'), ('date_hm', '%Y-%m-%dT%H:%M', '{year:d}-{mon:02d}-{day:02d}T{hour:02d}:{min:02d}'), ('date', '%Y-%m-%d', '{year:d}-{mon:02d}-{day:02d}')) class TimeYearDayTime(TimeISO): """ Year, day-of-year and time as "YYYY:DOY:HH:MM:SS.sss...". The day-of-year (DOY) goes from 001 to 365 (366 in leap years). For example, 2000:001:00:00:00.000 is midnight on January 1, 2000. The allowed subformats are: - 'date_hms': date + hours, mins, secs (and optional fractional secs) - 'date_hm': date + hours, mins - 'date': date """ name = 'yday' subfmts = (('date_hms', '%Y:%j:%H:%M:%S', '{year:d}:{yday:03d}:{hour:02d}:{min:02d}:{sec:02d}'), ('date_hm', '%Y:%j:%H:%M', '{year:d}:{yday:03d}:{hour:02d}:{min:02d}'), ('date', '%Y:%j', '{year:d}:{yday:03d}')) class TimeFITS(TimeString): """ FITS format: "[±Y]YYYY-MM-DD[THH:MM:SS[.sss]][(SCALE[(REALIZATION)])]". ISOT with two extensions: - Can give signed five-digit year (mostly for negative years); - A possible time scale (and realization) appended in parentheses. Note: FITS supports some deprecated names for timescales; these are translated to the formal names upon initialization. Furthermore, any specific realization information is stored only as long as the time scale is not changed. The allowed subformats are: - 'date_hms': date + hours, mins, secs (and optional fractional secs) - 'date': date - 'longdate_hms': as 'date_hms', but with signed 5-digit year - 'longdate': as 'date', but with signed 5-digit year See Rots et al., 2015, A&A 574:A36 (arXiv:1409.7583). """ name = 'fits' subfmts = ( ('date_hms', (r'(?P<year>\d{4})-(?P<mon>\d\d)-(?P<mday>\d\d)T' r'(?P<hour>\d\d):(?P<min>\d\d):(?P<sec>\d\d(\.\d*)?)'), '{year:04d}-{mon:02d}-{day:02d}T{hour:02d}:{min:02d}:{sec:02d}'), ('date', r'(?P<year>\d{4})-(?P<mon>\d\d)-(?P<mday>\d\d)', '{year:04d}-{mon:02d}-{day:02d}'), ('longdate_hms', (r'(?P<year>[+-]\d{5})-(?P<mon>\d\d)-(?P<mday>\d\d)T' r'(?P<hour>\d\d):(?P<min>\d\d):(?P<sec>\d\d(\.\d*)?)'), '{year:+06d}-{mon:02d}-{day:02d}T{hour:02d}:{min:02d}:{sec:02d}'), ('longdate', r'(?P<year>[+-]\d{5})-(?P<mon>\d\d)-(?P<mday>\d\d)', '{year:+06d}-{mon:02d}-{day:02d}')) # Add the regex that parses the scale and possible realization. subfmts = tuple( (subfmt[0], subfmt[1] + r'(\((?P<scale>\w+)(\((?P<realization>\w+)\))?\))?', subfmt[2]) for subfmt in subfmts) _fits_scale = None _fits_realization = None def parse_string(self, timestr, subfmts): """Read time and set scale according to trailing scale codes.""" # Try parsing with any of the allowed sub-formats. for _, regex, _ in subfmts: tm = re.match(regex, timestr) if tm: break else: raise ValueError('Time {0} does not match {1} format' .format(timestr, self.name)) tm = tm.groupdict() if tm['scale'] is not None: # If a scale was given, translate from a possible deprecated # timescale identifier to the scale used by Time. fits_scale = tm['scale'].upper() scale = FITS_DEPRECATED_SCALES.get(fits_scale, fits_scale.lower()) if scale not in TIME_SCALES: raise ValueError("Scale {0!r} is not in the allowed scales {1}" .format(scale, sorted(TIME_SCALES))) # If no scale was given in the initialiser, set the scale to # that given in the string. Also store a possible realization, # so we can round-trip (as long as no scale changes are made). fits_realization = (tm['realization'].upper() if tm['realization'] else None) if self._fits_scale is None: self._fits_scale = fits_scale self._fits_realization = fits_realization if self._scale is None: self._scale = scale if (scale != self.scale or fits_scale != self._fits_scale or fits_realization != self._fits_realization): raise ValueError("Input strings for {0} class must all " "have consistent time scales." .format(self.name)) return [int(tm['year']), int(tm['mon']), int(tm['mday']), int(tm.get('hour', 0)), int(tm.get('min', 0)), float(tm.get('sec', 0.))] def format_string(self, str_fmt, **kwargs): """Format time-string: append the scale to the normal ISOT format.""" time_str = super().format_string(str_fmt, **kwargs) if self._fits_scale and self._fits_realization: return '{0}({1}({2}))'.format(time_str, self._fits_scale, self._fits_realization) else: return '{0}({1})'.format(time_str, self._scale.upper()) @property def value(self): """Convert times to strings, using signed 5 digit if necessary.""" if 'long' not in self.out_subfmt: # If we have times before year 0 or after year 9999, we can # output only in a "long" format, using signed 5-digit years. jd = self.jd1 + self.jd2 if jd.min() < 1721425.5 or jd.max() >= 5373484.5: self.out_subfmt = 'long' + self.out_subfmt return super().value class TimeEpochDate(TimeFormat): """ Base class for support floating point Besselian and Julian epoch dates """ def set_jds(self, val1, val2): self._check_scale(self._scale) # validate scale. epoch_to_jd = getattr(erfa, self.epoch_to_jd) jd1, jd2 = epoch_to_jd(val1 + val2) self.jd1, self.jd2 = day_frac(jd1, jd2) @property def value(self): jd_to_epoch = getattr(erfa, self.jd_to_epoch) return jd_to_epoch(self.jd1, self.jd2) class TimeBesselianEpoch(TimeEpochDate): """Besselian Epoch year as floating point value(s) like 1950.0""" name = 'byear' epoch_to_jd = 'epb2jd' jd_to_epoch = 'epb' def _check_val_type(self, val1, val2): """Input value validation, typically overridden by derived classes""" if hasattr(val1, 'to') and hasattr(val1, 'unit'): raise ValueError("Cannot use Quantities for 'byear' format, " "as the interpretation would be ambiguous. " "Use float with Besselian year instead. ") return super()._check_val_type(val1, val2) class TimeJulianEpoch(TimeEpochDate): """Julian Epoch year as floating point value(s) like 2000.0""" name = 'jyear' unit = erfa.DJY # 365.25, the Julian year, for conversion to quantities epoch_to_jd = 'epj2jd' jd_to_epoch = 'epj' class TimeEpochDateString(TimeString): """ Base class to support string Besselian and Julian epoch dates such as 'B1950.0' or 'J2000.0' respectively. """ def set_jds(self, val1, val2): epoch_prefix = self.epoch_prefix # Be liberal in what we accept: convert bytes to ascii. to_string = (str if val1.dtype.kind == 'U' else lambda x: str(x.item(), encoding='ascii')) iterator = np.nditer([val1, None], op_dtypes=[val1.dtype, np.double]) for val, years in iterator: try: time_str = to_string(val) epoch_type, year_str = time_str[0], time_str[1:] year = float(year_str) if epoch_type.upper() != epoch_prefix: raise ValueError except (IndexError, ValueError, UnicodeEncodeError): raise ValueError('Time {0} does not match {1} format' .format(time_str, self.name)) else: years[...] = year self._check_scale(self._scale) # validate scale. epoch_to_jd = getattr(erfa, self.epoch_to_jd) jd1, jd2 = epoch_to_jd(iterator.operands[-1]) self.jd1, self.jd2 = day_frac(jd1, jd2) @property def value(self): jd_to_epoch = getattr(erfa, self.jd_to_epoch) years = jd_to_epoch(self.jd1, self.jd2) # Use old-style format since it is a factor of 2 faster str_fmt = self.epoch_prefix + '%.' + str(self.precision) + 'f' outs = [str_fmt % year for year in years.flat] return np.array(outs).reshape(self.jd1.shape) class TimeBesselianEpochString(TimeEpochDateString): """Besselian Epoch year as string value(s) like 'B1950.0'""" name = 'byear_str' epoch_to_jd = 'epb2jd' jd_to_epoch = 'epb' epoch_prefix = 'B' class TimeJulianEpochString(TimeEpochDateString): """Julian Epoch year as string value(s) like 'J2000.0'""" name = 'jyear_str' epoch_to_jd = 'epj2jd' jd_to_epoch = 'epj' epoch_prefix = 'J' class TimeDeltaFormatMeta(TimeFormatMeta): _registry = TIME_DELTA_FORMATS class TimeDeltaFormat(TimeFormat, metaclass=TimeDeltaFormatMeta): """Base class for time delta representations""" def _check_scale(self, scale): """ Check that the scale is in the allowed list of scales, or is `None` """ if scale is not None and scale not in TIME_DELTA_SCALES: raise ScaleValueError("Scale value '{0}' not in " "allowed values {1}" .format(scale, TIME_DELTA_SCALES)) return scale def set_jds(self, val1, val2): self._check_scale(self._scale) # Validate scale. self.jd1, self.jd2 = day_frac(val1, val2, divisor=1./self.unit) @property def value(self): return (self.jd1 + self.jd2) / self.unit class TimeDeltaSec(TimeDeltaFormat): """Time delta in SI seconds""" name = 'sec' unit = 1. / erfa.DAYSEC # for quantity input class TimeDeltaJD(TimeDeltaFormat): """Time delta in Julian days (86400 SI seconds)""" name = 'jd' unit = 1. from .core import Time, TIME_SCALES, TIME_DELTA_SCALES, ScaleValueError
f70d081b536f685fd13fe69b0eeffefdd97407ca466efe657d93fd71eeab769c
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst __all__ = ['quantity_input'] import inspect from ..utils.decorators import wraps from ..utils.misc import isiterable from .core import Unit, UnitsError, add_enabled_equivalencies from .physical import _unit_physical_mapping def _get_allowed_units(targets): """ From a list of target units (either as strings or unit objects) and physical types, return a list of Unit objects. """ allowed_units = [] for target in targets: try: # unit passed in as a string target_unit = Unit(target) except ValueError: try: # See if the function writer specified a physical type physical_type_id = _unit_physical_mapping[target] except KeyError: # Function argument target is invalid raise ValueError("Invalid unit or physical type '{0}'." .format(target)) # get unit directly from physical type id target_unit = Unit._from_physical_type_id(physical_type_id) allowed_units.append(target_unit) return allowed_units def _validate_arg_value(param_name, func_name, arg, targets, equivalencies): """ Validates the object passed in to the wrapped function, ``arg``, with target unit or physical type, ``target``. """ allowed_units = _get_allowed_units(targets) for allowed_unit in allowed_units: try: is_equivalent = arg.unit.is_equivalent(allowed_unit, equivalencies=equivalencies) if is_equivalent: break except AttributeError: # Either there is no .unit or no .is_equivalent if hasattr(arg, "unit"): error_msg = "a 'unit' attribute without an 'is_equivalent' method" else: error_msg = "no 'unit' attribute" raise TypeError("Argument '{0}' to function '{1}' has {2}. " "You may want to pass in an astropy Quantity instead." .format(param_name, func_name, error_msg)) else: if len(targets) > 1: raise UnitsError("Argument '{0}' to function '{1}' must be in units" " convertible to one of: {2}." .format(param_name, func_name, [str(targ) for targ in targets])) else: raise UnitsError("Argument '{0}' to function '{1}' must be in units" " convertible to '{2}'." .format(param_name, func_name, str(targets[0]))) class QuantityInput: @classmethod def as_decorator(cls, func=None, **kwargs): r""" A decorator for validating the units of arguments to functions. Unit specifications can be provided as keyword arguments to the decorator, or by using function annotation syntax. Arguments to the decorator take precedence over any function annotations present. A `~astropy.units.UnitsError` will be raised if the unit attribute of the argument is not equivalent to the unit specified to the decorator or in the annotation. If the argument has no unit attribute, i.e. it is not a Quantity object, a `ValueError` will be raised. Where an equivalency is specified in the decorator, the function will be executed with that equivalency in force. Notes ----- The checking of arguments inside variable arguments to a function is not supported (i.e. \*arg or \**kwargs). Examples -------- .. code-block:: python import astropy.units as u @u.quantity_input(myangle=u.arcsec) def myfunction(myangle): return myangle**2 .. code-block:: python import astropy.units as u @u.quantity_input def myfunction(myangle: u.arcsec): return myangle**2 Also you can specify a return value annotation, which will cause the function to always return a `~astropy.units.Quantity` in that unit. .. code-block:: python import astropy.units as u @u.quantity_input def myfunction(myangle: u.arcsec) -> u.deg**2: return myangle**2 Using equivalencies:: import astropy.units as u @u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy()) def myfunction(myenergy): return myenergy**2 """ self = cls(**kwargs) if func is not None and not kwargs: return self(func) else: return self def __init__(self, func=None, **kwargs): self.equivalencies = kwargs.pop('equivalencies', []) self.decorator_kwargs = kwargs def __call__(self, wrapped_function): # Extract the function signature for the function we are wrapping. wrapped_signature = inspect.signature(wrapped_function) # Define a new function to return in place of the wrapped one @wraps(wrapped_function) def wrapper(*func_args, **func_kwargs): # Bind the arguments to our new function to the signature of the original. bound_args = wrapped_signature.bind(*func_args, **func_kwargs) # Iterate through the parameters of the original signature for param in wrapped_signature.parameters.values(): # We do not support variable arguments (*args, **kwargs) if param.kind in (inspect.Parameter.VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL): continue # Catch the (never triggered) case where bind relied on a default value. if param.name not in bound_args.arguments and param.default is not param.empty: bound_args.arguments[param.name] = param.default # Get the value of this parameter (argument to new function) arg = bound_args.arguments[param.name] # Get target unit or physical type, either from decorator kwargs # or annotations if param.name in self.decorator_kwargs: targets = self.decorator_kwargs[param.name] else: targets = param.annotation # If the targets is empty, then no target units or physical # types were specified so we can continue to the next arg if targets is inspect.Parameter.empty: continue # If the argument value is None, and the default value is None, # pass through the None even if there is a target unit if arg is None and param.default is None: continue # Here, we check whether multiple target unit/physical type's # were specified in the decorator/annotation, or whether a # single string (unit or physical type) or a Unit object was # specified if isinstance(targets, str) or not isiterable(targets): valid_targets = [targets] # Check for None in the supplied list of allowed units and, if # present and the passed value is also None, ignore. elif None in targets: if arg is None: continue else: valid_targets = [t for t in targets if t is not None] else: valid_targets = targets # Now we loop over the allowed units/physical types and validate # the value of the argument: _validate_arg_value(param.name, wrapped_function.__name__, arg, valid_targets, self.equivalencies) # Call the original function with any equivalencies in force. with add_enabled_equivalencies(self.equivalencies): return_ = wrapped_function(*func_args, **func_kwargs) if wrapped_signature.return_annotation is not inspect.Signature.empty: return return_.to(wrapped_signature.return_annotation) else: return return_ return wrapper quantity_input = QuantityInput.as_decorator
6788ec87c476eae976198a64ffa49cc009095c8f147dcf3d97c2ee5e020db45d
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines colloquially used Imperial units. They are available in the `astropy.units.imperial` namespace, but not in the top-level `astropy.units` namespace, e.g.:: >>> import astropy.units as u >>> mph = u.imperial.mile / u.hour >>> mph Unit("mi / h") To include them in `~astropy.units.UnitBase.compose` and the results of `~astropy.units.UnitBase.find_equivalent_units`, do:: >>> import astropy.units as u >>> u.imperial.enable() # doctest: +SKIP """ from .core import UnitBase, def_unit from . import si _ns = globals() ########################################################################### # LENGTH def_unit(['inch'], 2.54 * si.cm, namespace=_ns, doc="International inch") def_unit(['ft', 'foot'], 12 * inch, namespace=_ns, doc="International foot") def_unit(['yd', 'yard'], 3 * ft, namespace=_ns, doc="International yard") def_unit(['mi', 'mile'], 5280 * ft, namespace=_ns, doc="International mile") def_unit(['mil', 'thou'], 0.001 * inch, namespace=_ns, doc="Thousandth of an inch") def_unit(['nmi', 'nauticalmile', 'NM'], 1852 * si.m, namespace=_ns, doc="Nautical mile") def_unit(['fur', 'furlong'], 660 * ft, namespace=_ns, doc="Furlong") ########################################################################### # AREAS def_unit(['ac', 'acre'], 43560 * ft ** 2, namespace=_ns, doc="International acre") ########################################################################### # VOLUMES def_unit(['gallon'], si.liter / 0.264172052, namespace=_ns, doc="U.S. liquid gallon") def_unit(['quart'], gallon / 4, namespace=_ns, doc="U.S. liquid quart") def_unit(['pint'], quart / 2, namespace=_ns, doc="U.S. liquid pint") def_unit(['cup'], pint / 2, namespace=_ns, doc="U.S. customary cup") def_unit(['foz', 'fluid_oz', 'fluid_ounce'], cup / 8, namespace=_ns, doc="U.S. fluid ounce") def_unit(['tbsp', 'tablespoon'], foz / 2, namespace=_ns, doc="U.S. customary tablespoon") def_unit(['tsp', 'teaspoon'], tbsp / 3, namespace=_ns, doc="U.S. customary teaspoon") ########################################################################### # MASS def_unit(['oz', 'ounce'], 28.349523125 * si.g, namespace=_ns, doc="International avoirdupois ounce: mass") def_unit(['lb', 'lbm', 'pound'], 16 * oz, namespace=_ns, doc="International avoirdupois pound: mass") def_unit(['st', 'stone'], 14 * lb, namespace=_ns, doc="International avoirdupois stone: mass") def_unit(['ton'], 2000 * lb, namespace=_ns, doc="International avoirdupois ton: mass") def_unit(['slug'], 32.174049 * lb, namespace=_ns, doc="slug: mass") ########################################################################### # SPEED def_unit(['kn', 'kt', 'knot', 'NMPH'], nmi / si.h, namespace=_ns, doc="nautical unit of speed: 1 nmi per hour") ########################################################################### # FORCE def_unit('lbf', slug * ft * si.s**-2, namespace=_ns, doc="Pound: force") def_unit(['kip', 'kilopound'], 1000 * lbf, namespace=_ns, doc="Kilopound: force") ########################################################################## # ENERGY def_unit(['BTU', 'btu'], 1.05505585 * si.kJ, namespace=_ns, doc="British thermal unit") def_unit(['cal', 'calorie'], 4.184 * si.J, namespace=_ns, doc="Thermochemical calorie: pre-SI metric unit of energy") def_unit(['kcal', 'Cal', 'Calorie', 'kilocal', 'kilocalorie'], 1000 * cal, namespace=_ns, doc="Calorie: colloquial definition of Calorie") ########################################################################## # PRESSURE def_unit('psi', lbf * inch ** -2, namespace=_ns, doc="Pound per square inch: pressure") ########################################################################### # POWER # Imperial units def_unit(['hp', 'horsepower'], si.W / 0.00134102209, namespace=_ns, doc="Electrical horsepower") ########################################################################### # TEMPERATURE def_unit(['deg_F', 'Fahrenheit'], namespace=_ns, doc='Degrees Fahrenheit', format={'latex': r'{}^{\circ}F', 'unicode': '°F'}) ########################################################################### # CLEANUP del UnitBase del def_unit ########################################################################### # 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 Imperial 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 Imperial 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))
ab0750b6b603468d21f9302ee9d542964a9b329a68985b6d9c9889cdf04fd830
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines units used in the CDS format, both the units defined in `Centre de Données astronomiques de Strasbourg <http://cds.u-strasbg.fr/>`_ `Standards for Astronomical Catalogues 2.0 <http://cds.u-strasbg.fr/doc/catstd-3.2.htx>`_ format and the `complete set of supported units <http://vizier.u-strasbg.fr/cgi-bin/Unit>`_. This format is used by VOTable up to version 1.2. These units are not available in the top-level `astropy.units` namespace. To use these units, you must import the `astropy.units.cds` module:: >>> from astropy.units import cds >>> q = 10. * cds.lyr # doctest: +SKIP To include them in `~astropy.units.UnitBase.compose` and the results of `~astropy.units.UnitBase.find_equivalent_units`, do:: >>> from astropy.units import cds >>> cds.enable() # doctest: +SKIP """ _ns = globals() def _initialize_module(): # Local imports to avoid polluting top-level namespace import numpy as np from . import core from .. import units as u from ..constants import si as _si # The CDS format also supports power-of-2 prefixes as defined here: # http://physics.nist.gov/cuu/Units/binary.html prefixes = core.si_prefixes + core.binary_prefixes # CDS only uses the short prefixes prefixes = [(short, short, factor) for (short, long, factor) in prefixes] # The following units are defined in alphabetical order, directly from # here: http://vizier.u-strasbg.fr/cgi-bin/Unit mapping = [ (['A'], u.A, "Ampere"), (['a'], u.a, "year", ['P']), (['a0'], _si.a0, "Bohr radius"), (['al'], u.lyr, "Light year", ['c', 'd']), (['lyr'], u.lyr, "Light year"), (['alpha'], _si.alpha, "Fine structure constant"), ((['AA', 'Å'], ['Angstrom', 'Angstroem']), u.AA, "Angstrom"), (['arcm', 'arcmin'], u.arcminute, "minute of arc"), (['arcs', 'arcsec'], u.arcsecond, "second of arc"), (['atm'], _si.atm, "atmosphere"), (['AU', 'au'], u.au, "astronomical unit"), (['bar'], u.bar, "bar"), (['barn'], u.barn, "barn"), (['bit'], u.bit, "bit"), (['byte'], u.byte, "byte"), (['C'], u.C, "Coulomb"), (['c'], _si.c, "speed of light", ['p']), (['cal'], 4.1854 * u.J, "calorie"), (['cd'], u.cd, "candela"), (['ct'], u.ct, "count"), (['D'], u.D, "Debye (dipole)"), (['d'], u.d, "Julian day", ['c']), ((['deg', '°'], ['degree']), u.degree, "degree"), (['dyn'], u.dyn, "dyne"), (['e'], _si.e, "electron charge", ['m']), (['eps0'], _si.eps0, "electric constant"), (['erg'], u.erg, "erg"), (['eV'], u.eV, "electron volt"), (['F'], u.F, "Farad"), (['G'], _si.G, "Gravitation constant"), (['g'], u.g, "gram"), (['gauss'], u.G, "Gauss"), (['geoMass', 'Mgeo'], u.M_earth, "Earth mass"), (['H'], u.H, "Henry"), (['h'], u.h, "hour", ['p']), (['hr'], u.h, "hour"), (['\\h'], _si.h, "Planck constant"), (['Hz'], u.Hz, "Hertz"), (['inch'], 0.0254 * u.m, "inch"), (['J'], u.J, "Joule"), (['JD'], u.d, "Julian day", ['M']), (['jovMass', 'Mjup'], u.M_jup, "Jupiter mass"), (['Jy'], u.Jy, "Jansky"), (['K'], u.K, "Kelvin"), (['k'], _si.k_B, "Boltzmann"), (['l'], u.l, "litre", ['a']), (['lm'], u.lm, "lumen"), (['Lsun', 'solLum'], u.solLum, "solar luminosity"), (['lx'], u.lx, "lux"), (['m'], u.m, "meter"), (['mag'], u.mag, "magnitude"), (['me'], _si.m_e, "electron mass"), (['min'], u.minute, "minute"), (['MJD'], u.d, "Julian day"), (['mmHg'], 133.322387415 * u.Pa, "millimeter of mercury"), (['mol'], u.mol, "mole"), (['mp'], _si.m_p, "proton mass"), (['Msun', 'solMass'], u.solMass, "solar mass"), ((['mu0', 'µ0'], []), _si.mu0, "magnetic constant"), (['muB'], _si.muB, "Bohr magneton"), (['N'], u.N, "Newton"), (['Ohm'], u.Ohm, "Ohm"), (['Pa'], u.Pa, "Pascal"), (['pc'], u.pc, "parsec"), (['ph'], u.ph, "photon"), (['pi'], u.Unit(np.pi), "π"), (['pix'], u.pix, "pixel"), (['ppm'], u.Unit(1e-6), "parts per million"), (['R'], _si.R, "gas constant"), (['rad'], u.radian, "radian"), (['Rgeo'], _si.R_earth, "Earth equatorial radius"), (['Rjup'], _si.R_jup, "Jupiter equatorial radius"), (['Rsun', 'solRad'], u.solRad, "solar radius"), (['Ry'], u.Ry, "Rydberg"), (['S'], u.S, "Siemens"), (['s', 'sec'], u.s, "second"), (['sr'], u.sr, "steradian"), (['Sun'], u.Sun, "solar unit"), (['T'], u.T, "Tesla"), (['t'], 1e3 * u.kg, "metric tonne", ['c']), (['u'], _si.u, "atomic mass", ['da', 'a']), (['V'], u.V, "Volt"), (['W'], u.W, "Watt"), (['Wb'], u.Wb, "Weber"), (['yr'], u.a, "year"), ] for entry in mapping: if len(entry) == 3: names, unit, doc = entry excludes = [] else: names, unit, doc, excludes = entry core.def_unit(names, unit, prefixes=prefixes, namespace=_ns, doc=doc, exclude_prefixes=excludes) core.def_unit(['µas'], u.microarcsecond, doc="microsecond of arc", namespace=_ns) core.def_unit(['mas'], u.milliarcsecond, doc="millisecond of arc", namespace=_ns) core.def_unit(['---'], u.dimensionless_unscaled, doc="dimensionless and unscaled", namespace=_ns) core.def_unit(['%'], u.percent, doc="percent", namespace=_ns) # The Vizier "standard" defines this in units of "kg s-3", but # that may not make a whole lot of sense, so here we just define # it as its own new disconnected unit. core.def_unit(['Crab'], prefixes=prefixes, namespace=_ns, doc="Crab (X-ray) flux") _initialize_module() ########################################################################### # 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 CDS units so they appear in results of `~astropy.units.UnitBase.find_equivalent_units` and `~astropy.units.UnitBase.compose`. This will disable all of the "default" `astropy.units` units, since there are some namespace clashes between the two. This may be used with the ``with`` statement to enable CDS units only temporarily. """ # Local import to avoid cyclical import from .core import set_enabled_units # Local import to avoid polluting namespace import inspect return set_enabled_units(inspect.getmodule(enable))
6bc080b4767391365d78381917a9a9977a5de63909c656fa7686af3c90a53581
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # The idea for this module (but no code) was borrowed from the # quantities (http://pythonhosted.org/quantities/) package. """Helper functions for Quantity. In particular, this implements the logic that determines scaling and result units for a given ufunc, given input units. """ from fractions import Fraction import numpy as np from .core import (UnitsError, UnitConversionError, UnitTypeError, dimensionless_unscaled, get_current_unit_registry) def _d(unit): if unit is None: return dimensionless_unscaled else: return unit def get_converter(from_unit, to_unit): """Like Unit._get_converter, except returns None if no scaling is needed, i.e., if the inferred scale is unity.""" try: scale = from_unit._to(to_unit) except UnitsError: return from_unit._apply_equivalencies( from_unit, to_unit, get_current_unit_registry().equivalencies) except AttributeError: raise UnitTypeError("Unit '{0}' cannot be converted to '{1}'" .format(from_unit, to_unit)) if scale == 1.: return None else: return lambda val: scale * val def get_converters_and_unit(f, unit1, unit2): converters = [None, None] # By default, we try adjusting unit2 to unit1, so that the result will # be unit1 as well. But if there is no second unit, we have to try # adjusting unit1 (to dimensionless, see below). if unit2 is None: if unit1 is None: # No units for any input -- e.g., np.add(a1, a2, out=q) return converters, dimensionless_unscaled changeable = 0 # swap units. unit2 = unit1 unit1 = None elif unit2 is unit1: # ensure identical units is fast ("==" is slow, so avoid that). return converters, unit1 else: changeable = 1 # Try to get a converter from unit2 to unit1. if unit1 is None: try: converters[changeable] = get_converter(unit2, dimensionless_unscaled) except UnitsError: # special case: would be OK if unitless number is zero, inf, nan converters[1-changeable] = False return converters, unit2 else: return converters, dimensionless_unscaled else: try: converters[changeable] = get_converter(unit2, unit1) except UnitsError: raise UnitConversionError( "Can only apply '{0}' function to quantities " "with compatible dimensions" .format(f.__name__)) return converters, unit1 def can_have_arbitrary_unit(value): """Test whether the items in value can have arbitrary units Numbers whose value does not change upon a unit change, i.e., zero, infinity, or not-a-number Parameters ---------- value : number or array Returns ------- `True` if each member is either zero or not finite, `False` otherwise """ return np.all(np.logical_or(np.equal(value, 0.), ~np.isfinite(value))) # SINGLE ARGUMENT UFUNC HELPERS # # The functions below take a single argument, which is the quantity upon which # the ufunc is being used. The output of the helper function should be two # values: a list with a single converter to be used to scale the input before # it is being passed to the ufunc (or None if no conversion is needed), and # the unit the output will be in. def helper_onearg_test(f, unit): return ([None], None) def helper_invariant(f, unit): return ([None], _d(unit)) def helper_sqrt(f, unit): return ([None], unit ** Fraction(1, 2) if unit is not None else dimensionless_unscaled) def helper_square(f, unit): return ([None], unit ** 2 if unit is not None else dimensionless_unscaled) def helper_reciprocal(f, unit): return ([None], unit ** -1 if unit is not None else dimensionless_unscaled) def helper_cbrt(f, unit): return ([None], (unit ** Fraction(1, 3) if unit is not None else dimensionless_unscaled)) def helper_modf(f, unit): if unit is None: return [None], (dimensionless_unscaled, dimensionless_unscaled) try: return ([get_converter(unit, dimensionless_unscaled)], (dimensionless_unscaled, dimensionless_unscaled)) except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "dimensionless quantities" .format(f.__name__)) def helper__ones_like(f, unit): return [None], dimensionless_unscaled def helper_dimensionless_to_dimensionless(f, unit): if unit is None: return [None], dimensionless_unscaled try: return ([get_converter(unit, dimensionless_unscaled)], dimensionless_unscaled) except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "dimensionless quantities" .format(f.__name__)) def helper_dimensionless_to_radian(f, unit): from .si import radian if unit is None: return [None], radian try: return [get_converter(unit, dimensionless_unscaled)], radian except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "dimensionless quantities" .format(f.__name__)) def helper_degree_to_radian(f, unit): from .si import degree, radian try: return [get_converter(unit, degree)], radian except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "quantities with angle units" .format(f.__name__)) def helper_radian_to_degree(f, unit): from .si import degree, radian try: return [get_converter(unit, radian)], degree except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "quantities with angle units" .format(f.__name__)) def helper_radian_to_dimensionless(f, unit): from .si import radian try: return [get_converter(unit, radian)], dimensionless_unscaled except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "quantities with angle units" .format(f.__name__)) def helper_frexp(f, unit): if not unit.is_unity(): raise UnitTypeError("Can only apply '{0}' function to " "unscaled dimensionless quantities" .format(f.__name__)) return [None], (None, None) # TWO ARGUMENT UFUNC HELPERS # # The functions below take a two arguments. The output of the helper function # should be two values: a tuple of two converters to be used to scale the # inputs before being passed to the ufunc (None if no conversion is needed), # and the unit the output will be in. def helper_multiplication(f, unit1, unit2): return [None, None], _d(unit1) * _d(unit2) def helper_division(f, unit1, unit2): return [None, None], _d(unit1) / _d(unit2) def helper_power(f, unit1, unit2): # TODO: find a better way to do this, currently need to signal that one # still needs to raise power of unit1 in main code if unit2 is None: return [None, None], False try: return [None, get_converter(unit2, dimensionless_unscaled)], False except UnitsError: raise UnitTypeError("Can only raise something to a " "dimensionless quantity") def helper_ldexp(f, unit1, unit2): if unit2 is not None: raise TypeError("Cannot use ldexp with a quantity " "as second argument.") else: return [None, None], _d(unit1) def helper_copysign(f, unit1, unit2): # if first arg is not a quantity, just return plain array if unit1 is None: return [None, None], None else: return [None, None], unit1 def helper_heaviside(f, unit1, unit2): try: converter2 = (get_converter(unit2, dimensionless_unscaled) if unit2 is not None else None) except UnitsError: raise UnitTypeError("Can only apply 'heaviside' function with a " "dimensionless second argument.") return ([None, converter2], dimensionless_unscaled) def helper_two_arg_dimensionless(f, unit1, unit2): try: converter1 = (get_converter(unit1, dimensionless_unscaled) if unit1 is not None else None) converter2 = (get_converter(unit2, dimensionless_unscaled) if unit2 is not None else None) except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "dimensionless quantities" .format(f.__name__)) return ([converter1, converter2], dimensionless_unscaled) # This used to be a separate function that just called get_converters_and_unit. # Using it directly saves a few us; keeping the clearer name. helper_twoarg_invariant = get_converters_and_unit def helper_twoarg_comparison(f, unit1, unit2): converters, _ = get_converters_and_unit(f, unit1, unit2) return converters, None def helper_twoarg_invtrig(f, unit1, unit2): from .si import radian converters, _ = get_converters_and_unit(f, unit1, unit2) return converters, radian def helper_twoarg_floor_divide(f, unit1, unit2): converters, _ = get_converters_and_unit(f, unit1, unit2) return converters, dimensionless_unscaled def helper_divmod(f, unit1, unit2): converters, result_unit = get_converters_and_unit(f, unit1, unit2) return converters, (dimensionless_unscaled, result_unit) def helper_degree_to_dimensionless(f, unit): from .si import degree try: return [get_converter(unit, degree)], dimensionless_unscaled except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "quantities with angle units" .format(f.__name__)) def helper_degree_minute_second_to_radian(f, unit1, unit2, unit3): from .si import degree, arcmin, arcsec, radian try: return [get_converter(unit1, degree), get_converter(unit2, arcmin), get_converter(unit3, arcsec)], radian except UnitsError: raise UnitTypeError("Can only apply '{0}' function to " "quantities with angle units" .format(f.__name__)) # list of ufuncs: # http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs UFUNC_HELPERS = {} UNSUPPORTED_UFUNCS = { np.bitwise_and, np.bitwise_or, np.bitwise_xor, np.invert, np.left_shift, np.right_shift, np.logical_and, np.logical_or, np.logical_xor, np.logical_not} for name in 'isnat', 'gcd', 'lcm': # isnat was introduced in numpy 1.14, gcd+lcm in 1.15 ufunc = getattr(np, name, None) if isinstance(ufunc, np.ufunc): UNSUPPORTED_UFUNCS |= {ufunc} # SINGLE ARGUMENT UFUNCS # ufuncs that return a boolean and do not care about the unit onearg_test_ufuncs = (np.isfinite, np.isinf, np.isnan, np.sign, np.signbit) for ufunc in onearg_test_ufuncs: UFUNC_HELPERS[ufunc] = helper_onearg_test # ufuncs that return a value with the same unit as the input invariant_ufuncs = (np.absolute, np.fabs, np.conj, np.conjugate, np.negative, np.spacing, np.rint, np.floor, np.ceil, np.trunc) for ufunc in invariant_ufuncs: UFUNC_HELPERS[ufunc] = helper_invariant # positive was added in numpy 1.13 if isinstance(getattr(np, 'positive', None), np.ufunc): UFUNC_HELPERS[np.positive] = helper_invariant # ufuncs that require dimensionless input and and give dimensionless output dimensionless_to_dimensionless_ufuncs = (np.exp, np.expm1, np.exp2, np.log, np.log10, np.log2, np.log1p) for ufunc in dimensionless_to_dimensionless_ufuncs: UFUNC_HELPERS[ufunc] = helper_dimensionless_to_dimensionless # ufuncs that require dimensionless input and give output in radians dimensionless_to_radian_ufuncs = (np.arccos, np.arcsin, np.arctan, np.arccosh, np.arcsinh, np.arctanh) for ufunc in dimensionless_to_radian_ufuncs: UFUNC_HELPERS[ufunc] = helper_dimensionless_to_radian # ufuncs that require input in degrees and give output in radians degree_to_radian_ufuncs = (np.radians, np.deg2rad) for ufunc in degree_to_radian_ufuncs: UFUNC_HELPERS[ufunc] = helper_degree_to_radian # ufuncs that require input in radians and give output in degrees radian_to_degree_ufuncs = (np.degrees, np.rad2deg) for ufunc in radian_to_degree_ufuncs: UFUNC_HELPERS[ufunc] = helper_radian_to_degree # ufuncs that require input in radians and give dimensionless output radian_to_dimensionless_ufuncs = (np.cos, np.sin, np.tan, np.cosh, np.sinh, np.tanh) for ufunc in radian_to_dimensionless_ufuncs: UFUNC_HELPERS[ufunc] = helper_radian_to_dimensionless # ufuncs handled as special cases UFUNC_HELPERS[np.sqrt] = helper_sqrt UFUNC_HELPERS[np.square] = helper_square UFUNC_HELPERS[np.reciprocal] = helper_reciprocal UFUNC_HELPERS[np.cbrt] = helper_cbrt UFUNC_HELPERS[np.core.umath._ones_like] = helper__ones_like UFUNC_HELPERS[np.modf] = helper_modf UFUNC_HELPERS[np.frexp] = helper_frexp # TWO ARGUMENT UFUNCS # two argument ufuncs that require dimensionless input and and give # dimensionless output two_arg_dimensionless_ufuncs = (np.logaddexp, np.logaddexp2) for ufunc in two_arg_dimensionless_ufuncs: UFUNC_HELPERS[ufunc] = helper_two_arg_dimensionless # two argument ufuncs that return a value with the same unit as the input twoarg_invariant_ufuncs = (np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.fmin, np.fmax, np.nextafter, np.remainder, np.mod, np.fmod) for ufunc in twoarg_invariant_ufuncs: UFUNC_HELPERS[ufunc] = helper_twoarg_invariant # two argument ufuncs that need compatible inputs and return a boolean twoarg_comparison_ufuncs = (np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal, np.equal) for ufunc in twoarg_comparison_ufuncs: UFUNC_HELPERS[ufunc] = helper_twoarg_comparison # two argument ufuncs that do inverse trigonometry twoarg_invtrig_ufuncs = (np.arctan2,) # another private function in numpy; use getattr in case it disappears if isinstance(getattr(np.core.umath, '_arg', None), np.ufunc): twoarg_invtrig_ufuncs += (np.core.umath._arg,) for ufunc in twoarg_invtrig_ufuncs: UFUNC_HELPERS[ufunc] = helper_twoarg_invtrig # ufuncs handled as special cases UFUNC_HELPERS[np.multiply] = helper_multiplication UFUNC_HELPERS[np.divide] = helper_division UFUNC_HELPERS[np.true_divide] = helper_division UFUNC_HELPERS[np.power] = helper_power UFUNC_HELPERS[np.ldexp] = helper_ldexp UFUNC_HELPERS[np.copysign] = helper_copysign UFUNC_HELPERS[np.floor_divide] = helper_twoarg_floor_divide # heaviside only was added in numpy 1.13 if isinstance(getattr(np, 'heaviside', None), np.ufunc): UFUNC_HELPERS[np.heaviside] = helper_heaviside # float_power was added in numpy 1.12 if isinstance(getattr(np, 'float_power', None), np.ufunc): UFUNC_HELPERS[np.float_power] = helper_power # divmod only was added in numpy 1.13 if isinstance(getattr(np, 'divmod', None), np.ufunc): UFUNC_HELPERS[np.divmod] = helper_divmod # UFUNCS FROM SCIPY.SPECIAL # available ufuncs in this module are at # https://docs.scipy.org/doc/scipy/reference/special.html try: import scipy.special as sps except ImportError: pass else: # ufuncs that require dimensionless input and give dimensionless output dimensionless_to_dimensionless_sps_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, sps.j0, sps.j1, sps.y0, sps.y1, sps.i0, sps.i0e, sps.i1, sps.i1e, sps.k0, sps.k0e, sps.k1, sps.k1e, sps.itj0y0, sps.it2j0y0, sps.iti0k0, sps.it2i0k0) for ufunc in dimensionless_to_dimensionless_sps_ufuncs: UFUNC_HELPERS[ufunc] = helper_dimensionless_to_dimensionless # ufuncs that require input in degrees and give dimensionless output degree_to_dimensionless_sps_ufuncs = ( sps.cosdg, sps.sindg, sps.tandg, sps.cotdg) for ufunc in degree_to_dimensionless_sps_ufuncs: UFUNC_HELPERS[ufunc] = helper_degree_to_dimensionless # ufuncs that require 2 dimensionless inputs and give dimensionless output. # note: sps.jv and sps.jn are aliases in some scipy versions, which will # cause the same key to be written twice, but since both are handled by the # same helper there is no harm done. two_arg_dimensionless_sps_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) for ufunc in two_arg_dimensionless_sps_ufuncs: UFUNC_HELPERS[ufunc] = helper_two_arg_dimensionless # ufuncs handled as special cases UFUNC_HELPERS[sps.cbrt] = helper_cbrt UFUNC_HELPERS[sps.radian] = helper_degree_minute_second_to_radian def converters_and_unit(function, method, *args): """Determine the required converters and the unit of the ufunc result. Converters are functions required to convert to a ufunc's expected unit, e.g., radian for np.sin; or to ensure units of two inputs are consistent, e.g., for np.add. In these examples, the unit of the result would be dimensionless_unscaled for np.sin, and the same consistent unit for np.add. Parameters ---------- function : `~numpy.ufunc` Numpy universal function method : str Method with which the function is evaluated, e.g., '__call__', 'reduce', etc. *args : Quantity or other ndarray subclass Input arguments to the function Raises ------ TypeError : when the specified function cannot be used with Quantities (e.g., np.logical_or), or when the routine does not know how to handle the specified function (in which case an issue should be raised on https://github.com/astropy/astropy). UnitTypeError : when the conversion to the required (or consistent) units is not possible. """ # Check whether we support this ufunc, by getting the helper function # (defined above) which returns a list of function(s) that convert the # input(s) to the unit required for the ufunc, as well as the unit the # result will have (a tuple of units if there are multiple outputs). try: ufunc_helper = UFUNC_HELPERS[function] except KeyError: if function in UNSUPPORTED_UFUNCS: raise TypeError("Cannot use function '{0}' with quantities" .format(function.__name__)) else: raise TypeError("Unknown ufunc {0}. Please raise issue on " "https://github.com/astropy/astropy" .format(function.__name__)) if method == '__call__' or (method == 'outer' and function.nin == 2): # Find out the units of the arguments passed to the ufunc; usually, # at least one is a quantity, but for two-argument ufuncs, the second # could also be a Numpy array, etc. These are given unit=None. units = [getattr(arg, 'unit', None) for arg in args] # Determine possible conversion functions, and the result unit. converters, result_unit = ufunc_helper(function, *units) if any(converter is False for converter in converters): # for two-argument ufuncs with a quantity and a non-quantity, # the quantity normally needs to be dimensionless, *except* # if the non-quantity can have arbitrary unit, i.e., when it # is all zero, infinity or NaN. In that case, the non-quantity # can just have the unit of the quantity # (this allows, e.g., `q > 0.` independent of unit) maybe_arbitrary_arg = args[converters.index(False)] try: if can_have_arbitrary_unit(maybe_arbitrary_arg): converters = [None, None] else: raise UnitsError("Can only apply '{0}' function to " "dimensionless quantities when other " "argument is not a quantity (unless the " "latter is all zero/infinity/nan)" .format(function.__name__)) except TypeError: # _can_have_arbitrary_unit failed: arg could not be compared # with zero or checked to be finite. Then, ufunc will fail too. raise TypeError("Unsupported operand type(s) for ufunc {0}: " "'{1}' and '{2}'" .format(function.__name__, args[0].__class__.__name__, args[1].__class__.__name__)) # In the case of np.power and np.float_power, the unit itself needs to # be modified by an amount that depends on one of the input values, # so we need to treat this as a special case. # TODO: find a better way to deal with this. if result_unit is False: if units[0] is None or units[0] == dimensionless_unscaled: result_unit = dimensionless_unscaled else: if units[1] is None: p = args[1] else: p = args[1].to(dimensionless_unscaled).value try: result_unit = units[0] ** p except ValueError as exc: # Changing the unit does not work for, e.g., array-shaped # power, but this is OK if we're (scaled) dimensionless. try: converters[0] = units[0]._get_converter( dimensionless_unscaled) except UnitConversionError: raise exc else: result_unit = dimensionless_unscaled else: # methods for which the unit should stay the same nin = function.nin unit = getattr(args[0], 'unit', None) if method == 'at' and nin <= 2: if nin == 1: units = [unit] else: units = [unit, getattr(args[2], 'unit', None)] converters, result_unit = ufunc_helper(function, *units) # ensure there is no 'converter' for indices (2nd argument) converters.insert(1, None) elif method in {'reduce', 'accumulate', 'reduceat'} and nin == 2: converters, result_unit = ufunc_helper(function, unit, unit) converters = converters[:1] if method == 'reduceat': # add 'scale' for indices (2nd argument) converters += [None] else: if method in {'reduce', 'accumulate', 'reduceat', 'outer'} and nin != 2: raise ValueError("{0} only supported for binary functions" .format(method)) raise TypeError("Unexpected ufunc method {0}. If this should " "work, please raise an issue on" "https://github.com/astropy/astropy" .format(method)) # for all but __call__ method, scaling is not allowed if unit is not None and result_unit is None: raise TypeError("Cannot use '{1}' method on ufunc {0} with a " "Quantity instance as the result is not a " "Quantity.".format(function.__name__, method)) if (converters[0] is not None or (unit is not None and unit is not result_unit and (not result_unit.is_equivalent(unit) or result_unit.to(unit) != 1.))): raise UnitsError("Cannot use '{1}' method on ufunc {0} with a " "Quantity instance as it would change the unit." .format(function.__name__, method)) return converters, result_unit def check_output(output, unit, inputs, function=None): """Check that function output can be stored in the output array given. Parameters ---------- output : array or `~astropy.units.Quantity` or tuple Array that should hold the function output (or tuple of such arrays). unit : `~astropy.units.Unit` or None, or tuple Unit that the output will have, or `None` for pure numbers (should be tuple of same if output is a tuple of outputs). inputs : tuple Any input arguments. These should be castable to the output. function : callable The function that will be producing the output. If given, used to give a more informative error message. Returns ------- arrays : `~numpy.ndarray` view of ``output`` (or tuple of such views). Raises ------ UnitTypeError : If ``unit`` is inconsistent with the class of ``output`` TypeError : If the ``inputs`` cannot be cast safely to ``output``. """ if isinstance(output, tuple): return tuple(check_output(output_, unit_, inputs, function) for output_, unit_ in zip(output, unit)) # ``None`` indicates no actual array is needed. This can happen, e.g., # with np.modf(a, out=(None, b)). if output is None: return None if hasattr(output, '__quantity_subclass__'): # Check that we're not trying to store a plain Numpy array or a # Quantity with an inconsistent unit (e.g., not angular for Angle). if unit is None: raise TypeError("Cannot store non-quantity output{0} in {1} " "instance".format( (" from {0} function".format(function.__name__) if function is not None else ""), type(output))) if output.__quantity_subclass__(unit)[0] is not type(output): raise UnitTypeError( "Cannot store output with unit '{0}'{1} " "in {2} instance. Use {3} instance instead." .format(unit, (" from {0} function".format(function.__name__) if function is not None else ""), type(output), output.__quantity_subclass__(unit)[0])) # Turn into ndarray, so we do not loop into array_wrap/array_ufunc # if the output is used to store results of a function. output = output.view(np.ndarray) else: # output is not a Quantity, so cannot obtain a unit. if not (unit is None or unit is dimensionless_unscaled): raise UnitTypeError("Cannot store quantity with dimension " "{0}in a non-Quantity instance." .format("" if function is None else "resulting from {0} function " .format(function.__name__))) # check we can handle the dtype (e.g., that we are not int # when float is required). if not np.can_cast(np.result_type(*inputs), output.dtype, casting='same_kind'): raise TypeError("Arguments cannot be cast safely to inplace " "output with dtype={0}".format(output.dtype)) return output
7a831eaa86e8cfcfc12cf3862bafcb3ae4b168950c7d61dcd365577744da5796
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Core units classes and functions """ import inspect import operator import textwrap import warnings import numpy as np from ..utils.decorators import lazyproperty from ..utils.exceptions import AstropyWarning from ..utils.misc import isiterable, InheritDocstrings from .utils import (is_effectively_unity, sanitize_scale, validate_power, resolve_fractions) from . import format as unit_format __all__ = [ 'UnitsError', 'UnitsWarning', 'UnitConversionError', 'UnitTypeError', 'UnitBase', 'NamedUnit', 'IrreducibleUnit', 'Unit', 'CompositeUnit', 'PrefixUnit', 'UnrecognizedUnit', 'def_unit', 'get_current_unit_registry', 'set_enabled_units', 'add_enabled_units', 'set_enabled_equivalencies', 'add_enabled_equivalencies', 'dimensionless_unscaled', 'one'] def _flatten_units_collection(items): """ Given a list of sequences, modules or dictionaries of units, or single units, return a flat set of all the units found. """ if not isinstance(items, list): items = [items] result = set() for item in items: if isinstance(item, UnitBase): result.add(item) else: if isinstance(item, dict): units = item.values() elif inspect.ismodule(item): units = vars(item).values() elif isiterable(item): units = item else: continue for unit in units: if isinstance(unit, UnitBase): result.add(unit) return result def _normalize_equivalencies(equivalencies): """ Normalizes equivalencies, ensuring each is a 4-tuple of the form:: (from_unit, to_unit, forward_func, backward_func) Parameters ---------- equivalencies : list of equivalency pairs Raises ------ ValueError if an equivalency cannot be interpreted """ if equivalencies is None: return [] normalized = [] for i, equiv in enumerate(equivalencies): if len(equiv) == 2: funit, tunit = equiv a = b = lambda x: x elif len(equiv) == 3: funit, tunit, a = equiv b = a elif len(equiv) == 4: funit, tunit, a, b = equiv else: raise ValueError( "Invalid equivalence entry {0}: {1!r}".format(i, equiv)) if not (funit is Unit(funit) and (tunit is None or tunit is Unit(tunit)) and callable(a) and callable(b)): raise ValueError( "Invalid equivalence entry {0}: {1!r}".format(i, equiv)) normalized.append((funit, tunit, a, b)) return normalized class _UnitRegistry: """ Manages a registry of the enabled units. """ def __init__(self, init=[], equivalencies=[]): if isinstance(init, _UnitRegistry): # If passed another registry we don't need to rebuild everything. # but because these are mutable types we don't want to create # conflicts so everything needs to be copied. self._equivalencies = init._equivalencies.copy() self._all_units = init._all_units.copy() self._registry = init._registry.copy() self._non_prefix_units = init._non_prefix_units.copy() # The physical type is a dictionary containing sets as values. # All of these must be copied otherwise we could alter the old # registry. self._by_physical_type = {k: v.copy() for k, v in init._by_physical_type.items()} else: self._reset_units() self._reset_equivalencies() self.add_enabled_units(init) self.add_enabled_equivalencies(equivalencies) def _reset_units(self): self._all_units = set() self._non_prefix_units = set() self._registry = {} self._by_physical_type = {} def _reset_equivalencies(self): self._equivalencies = set() @property def registry(self): return self._registry @property def all_units(self): return self._all_units @property def non_prefix_units(self): return self._non_prefix_units def set_enabled_units(self, units): """ Sets the units enabled in the unit registry. These units are searched when using `UnitBase.find_equivalent_units`, for example. Parameters ---------- units : list of sequences, dicts, or modules containing units, or units This is a list of things in which units may be found (sequences, dicts or modules), or units themselves. The entire set will be "enabled" for searching through by methods like `UnitBase.find_equivalent_units` and `UnitBase.compose`. """ self._reset_units() return self.add_enabled_units(units) def add_enabled_units(self, units): """ Adds to the set of units enabled in the unit registry. These units are searched when using `UnitBase.find_equivalent_units`, for example. Parameters ---------- units : list of sequences, dicts, or modules containing units, or units This is a list of things in which units may be found (sequences, dicts or modules), or units themselves. The entire set will be added to the "enabled" set for searching through by methods like `UnitBase.find_equivalent_units` and `UnitBase.compose`. """ units = _flatten_units_collection(units) for unit in units: # Loop through all of the names first, to ensure all of them # are new, then add them all as a single "transaction" below. for st in unit._names: if (st in self._registry and unit != self._registry[st]): raise ValueError( "Object with name {0!r} already exists in namespace. " "Filter the set of units to avoid name clashes before " "enabling them.".format(st)) for st in unit._names: self._registry[st] = unit self._all_units.add(unit) if not isinstance(unit, PrefixUnit): self._non_prefix_units.add(unit) hash = unit._get_physical_type_id() self._by_physical_type.setdefault(hash, set()).add(unit) def get_units_with_physical_type(self, unit): """ Get all units in the registry with the same physical type as the given unit. Parameters ---------- unit : UnitBase instance """ return self._by_physical_type.get(unit._get_physical_type_id(), set()) @property def equivalencies(self): return list(self._equivalencies) def set_enabled_equivalencies(self, equivalencies): """ Sets the equivalencies enabled in the unit registry. These equivalencies are used if no explicit equivalencies are given, both in unit conversion and in finding equivalent units. This is meant in particular for allowing angles to be dimensionless. Use with care. Parameters ---------- equivalencies : list of equivalent pairs E.g., as returned by `~astropy.units.equivalencies.dimensionless_angles`. """ self._reset_equivalencies() return self.add_enabled_equivalencies(equivalencies) def add_enabled_equivalencies(self, equivalencies): """ Adds to the set of equivalencies enabled in the unit registry. These equivalencies are used if no explicit equivalencies are given, both in unit conversion and in finding equivalent units. This is meant in particular for allowing angles to be dimensionless. Use with care. Parameters ---------- equivalencies : list of equivalent pairs E.g., as returned by `~astropy.units.equivalencies.dimensionless_angles`. """ # pre-normalize list to help catch mistakes equivalencies = _normalize_equivalencies(equivalencies) self._equivalencies |= set(equivalencies) class _UnitContext: def __init__(self, init=[], equivalencies=[]): _unit_registries.append( _UnitRegistry(init=init, equivalencies=equivalencies)) def __enter__(self): pass def __exit__(self, type, value, tb): _unit_registries.pop() _unit_registries = [_UnitRegistry()] def get_current_unit_registry(): return _unit_registries[-1] def set_enabled_units(units): """ Sets the units enabled in the unit registry. These units are searched when using `UnitBase.find_equivalent_units`, for example. This may be used either permanently, or as a context manager using the ``with`` statement (see example below). Parameters ---------- units : list of sequences, dicts, or modules containing units, or units This is a list of things in which units may be found (sequences, dicts or modules), or units themselves. The entire set will be "enabled" for searching through by methods like `UnitBase.find_equivalent_units` and `UnitBase.compose`. Examples -------- >>> from astropy import units as u >>> with u.set_enabled_units([u.pc]): ... u.m.find_equivalent_units() ... Primary name | Unit definition | Aliases [ pc | 3.08568e+16 m | parsec , ] >>> u.m.find_equivalent_units() Primary name | Unit definition | Aliases [ AU | 1.49598e+11 m | au, astronomical_unit , Angstrom | 1e-10 m | AA, angstrom , cm | 0.01 m | centimeter , earthRad | 6.3781e+06 m | R_earth, Rearth , jupiterRad | 7.1492e+07 m | R_jup, Rjup, R_jupiter, Rjupiter , lyr | 9.46073e+15 m | lightyear , m | irreducible | meter , micron | 1e-06 m | , pc | 3.08568e+16 m | parsec , solRad | 6.957e+08 m | R_sun, Rsun , ] """ # get a context with a new registry, using equivalencies of the current one context = _UnitContext( equivalencies=get_current_unit_registry().equivalencies) # in this new current registry, enable the units requested get_current_unit_registry().set_enabled_units(units) return context def add_enabled_units(units): """ Adds to the set of units enabled in the unit registry. These units are searched when using `UnitBase.find_equivalent_units`, for example. This may be used either permanently, or as a context manager using the ``with`` statement (see example below). Parameters ---------- units : list of sequences, dicts, or modules containing units, or units This is a list of things in which units may be found (sequences, dicts or modules), or units themselves. The entire set will be added to the "enabled" set for searching through by methods like `UnitBase.find_equivalent_units` and `UnitBase.compose`. Examples -------- >>> from astropy import units as u >>> from astropy.units import imperial >>> with u.add_enabled_units(imperial): ... u.m.find_equivalent_units() ... Primary name | Unit definition | Aliases [ AU | 1.49598e+11 m | au, astronomical_unit , Angstrom | 1e-10 m | AA, angstrom , cm | 0.01 m | centimeter , earthRad | 6.3781e+06 m | R_earth, Rearth , ft | 0.3048 m | foot , fur | 201.168 m | furlong , inch | 0.0254 m | , jupiterRad | 7.1492e+07 m | R_jup, Rjup, R_jupiter, Rjupiter , lyr | 9.46073e+15 m | lightyear , m | irreducible | meter , mi | 1609.34 m | mile , micron | 1e-06 m | , mil | 2.54e-05 m | thou , nmi | 1852 m | nauticalmile, NM , pc | 3.08568e+16 m | parsec , solRad | 6.957e+08 m | R_sun, Rsun , yd | 0.9144 m | yard , ] """ # get a context with a new registry, which is a copy of the current one context = _UnitContext(get_current_unit_registry()) # in this new current registry, enable the further units requested get_current_unit_registry().add_enabled_units(units) return context def set_enabled_equivalencies(equivalencies): """ Sets the equivalencies enabled in the unit registry. These equivalencies are used if no explicit equivalencies are given, both in unit conversion and in finding equivalent units. This is meant in particular for allowing angles to be dimensionless. Use with care. Parameters ---------- equivalencies : list of equivalent pairs E.g., as returned by `~astropy.units.equivalencies.dimensionless_angles`. Examples -------- Exponentiation normally requires dimensionless quantities. To avoid problems with complex phases:: >>> from astropy import units as u >>> with u.set_enabled_equivalencies(u.dimensionless_angles()): ... phase = 0.5 * u.cycle ... np.exp(1j*phase) # doctest: +SKIP <Quantity -1. +1.22464680e-16j> """ # doctest skipped as the complex number formatting changed in numpy 1.14. # # get a context with a new registry, using all units of the current one context = _UnitContext(get_current_unit_registry()) # in this new current registry, enable the equivalencies requested get_current_unit_registry().set_enabled_equivalencies(equivalencies) return context def add_enabled_equivalencies(equivalencies): """ Adds to the equivalencies enabled in the unit registry. These equivalencies are used if no explicit equivalencies are given, both in unit conversion and in finding equivalent units. This is meant in particular for allowing angles to be dimensionless. Since no equivalencies are enabled by default, generally it is recommended to use `set_enabled_equivalencies`. Parameters ---------- equivalencies : list of equivalent pairs E.g., as returned by `~astropy.units.equivalencies.dimensionless_angles`. """ # get a context with a new registry, which is a copy of the current one context = _UnitContext(get_current_unit_registry()) # in this new current registry, enable the further equivalencies requested get_current_unit_registry().add_enabled_equivalencies(equivalencies) return context class UnitsError(Exception): """ The base class for unit-specific exceptions. """ class UnitScaleError(UnitsError, ValueError): """ Used to catch the errors involving scaled units, which are not recognized by FITS format. """ pass class UnitConversionError(UnitsError, ValueError): """ Used specifically for errors related to converting between units or interpreting units in terms of other units. """ class UnitTypeError(UnitsError, TypeError): """ Used specifically for errors in setting to units not allowed by a class. E.g., would be raised if the unit of an `~astropy.coordinates.Angle` instances were set to a non-angular unit. """ class UnitsWarning(AstropyWarning): """ The base class for unit-specific warnings. """ class UnitBase(metaclass=InheritDocstrings): """ Abstract base class for units. Most of the arithmetic operations on units are defined in this base class. Should not be instantiated by users directly. """ # Make sure that __rmul__ of units gets called over the __mul__ of Numpy # arrays to avoid element-wise multiplication. __array_priority__ = 1000 def __deepcopy__(self, memo): # This may look odd, but the units conversion will be very # broken after deep-copying if we don't guarantee that a given # physical unit corresponds to only one instance return self 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 unit_format.Latex.to_string(self) def __bytes__(self): """Return string representation for unit""" return unit_format.Generic.to_string(self).encode('unicode_escape') def __str__(self): """Return string representation for unit""" return unit_format.Generic.to_string(self) def __repr__(self): string = unit_format.Generic.to_string(self) return 'Unit("{0}")'.format(string) def _get_physical_type_id(self): """ Returns an identifier that uniquely identifies the physical type of this unit. It is comprised of the bases and powers of this unit, without the scale. Since it is hashable, it is useful as a dictionary key. """ unit = self.decompose() r = zip([x.name for x in unit.bases], unit.powers) # bases and powers are already sorted in a unique way # r.sort() r = tuple(r) return r @property def names(self): """ Returns all of the names associated with this unit. """ raise AttributeError( "Can not get names from unnamed units. " "Perhaps you meant to_string()?") @property def name(self): """ Returns the canonical (short) name associated with this unit. """ raise AttributeError( "Can not get names from unnamed units. " "Perhaps you meant to_string()?") @property def aliases(self): """ Returns the alias (long) names for this unit. """ raise AttributeError( "Can not get aliases from unnamed units. " "Perhaps you meant to_string()?") @property def scale(self): """ Return the scale of the unit. """ return 1.0 @property def bases(self): """ Return the bases of the unit. """ return [self] @property def powers(self): """ Return the powers of the unit. """ return [1] def to_string(self, format=unit_format.Generic): """ Output the unit in the given format as a string. 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. """ f = unit_format.get_format(format) return f.to_string(self) def __format__(self, format_spec): """Try to format units using a formatter.""" try: return self.to_string(format=format_spec) except ValueError: return format(str(self), format_spec) @staticmethod def _normalize_equivalencies(equivalencies): """ Normalizes equivalencies, ensuring each is a 4-tuple of the form:: (from_unit, to_unit, forward_func, backward_func) Parameters ---------- equivalencies : list of equivalency pairs, or `None` Returns ------- A normalized list, including possible global defaults set by, e.g., `set_enabled_equivalencies`, except when `equivalencies`=`None`, in which case the returned list is always empty. Raises ------ ValueError if an equivalency cannot be interpreted """ normalized = _normalize_equivalencies(equivalencies) if equivalencies is not None: normalized += get_current_unit_registry().equivalencies return normalized def __pow__(self, p): return CompositeUnit(1, [self], [p]) def __div__(self, m): if isinstance(m, (bytes, str)): m = Unit(m) if isinstance(m, UnitBase): if m.is_unity(): return self return CompositeUnit(1, [self, m], [1, -1], _error_check=False) try: # Cannot handle this as Unit, re-try as Quantity from .quantity import Quantity return Quantity(1, self) / m except TypeError: return NotImplemented def __rdiv__(self, m): if isinstance(m, (bytes, str)): return Unit(m) / self try: # Cannot handle this as Unit. Here, m cannot be a Quantity, # so we make it into one, fasttracking when it does not have a # unit, for the common case of <array> / <unit>. from .quantity import Quantity if hasattr(m, 'unit'): result = Quantity(m) result /= self return result else: return Quantity(m, self**(-1)) except TypeError: return NotImplemented __truediv__ = __div__ __rtruediv__ = __rdiv__ def __mul__(self, m): if isinstance(m, (bytes, str)): m = Unit(m) if isinstance(m, UnitBase): if m.is_unity(): return self elif self.is_unity(): return m return CompositeUnit(1, [self, m], [1, 1], _error_check=False) # Cannot handle this as Unit, re-try as Quantity. try: from .quantity import Quantity return Quantity(1, self) * m except TypeError: return NotImplemented def __rmul__(self, m): if isinstance(m, (bytes, str)): return Unit(m) * self # Cannot handle this as Unit. Here, m cannot be a Quantity, # so we make it into one, fasttracking when it does not have a unit # for the common case of <array> * <unit>. try: from .quantity import Quantity if hasattr(m, 'unit'): result = Quantity(m) result *= self return result else: return Quantity(m, self) except TypeError: return NotImplemented def __hash__(self): # This must match the hash used in CompositeUnit for a unit # with only one base and no scale or power. return hash((str(self.scale), self.name, str('1'))) def __eq__(self, other): if self is other: return True try: other = Unit(other, parse_strict='silent') except (ValueError, UnitsError, TypeError): return False # Other is Unit-like, but the test below requires it is a UnitBase # instance; if it is not, give up (so that other can try). if not isinstance(other, UnitBase): return NotImplemented try: return is_effectively_unity(self._to(other)) except UnitsError: return False def __ne__(self, other): return not (self == other) def __le__(self, other): scale = self._to(Unit(other)) return scale <= 1. or is_effectively_unity(scale) def __ge__(self, other): scale = self._to(Unit(other)) return scale >= 1. or is_effectively_unity(scale) def __lt__(self, other): return not (self >= other) def __gt__(self, other): return not (self <= other) def __neg__(self): return self * -1. 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 possible global defaults set by, e.g., `set_enabled_equivalencies`. Use `None` to turn off all equivalencies. Returns ------- bool """ equivalencies = self._normalize_equivalencies(equivalencies) if isinstance(other, tuple): return any(self.is_equivalent(u, equivalencies=equivalencies) for u in other) other = Unit(other, parse_strict='silent') return self._is_equivalent(other, equivalencies) def _is_equivalent(self, other, equivalencies=[]): """Returns `True` if this unit is equivalent to `other`. See `is_equivalent`, except that a proper Unit object should be given (i.e., no string) and that the equivalency list should be normalized using `_normalize_equivalencies`. """ if isinstance(other, UnrecognizedUnit): return False if (self._get_physical_type_id() == other._get_physical_type_id()): return True elif len(equivalencies): unit = self.decompose() other = other.decompose() for a, b, forward, backward in equivalencies: if b is None: # after canceling, is what's left convertible # to dimensionless (according to the equivalency)? try: (other/unit).decompose([a]) return True except Exception: pass else: if(a._is_equivalent(unit) and b._is_equivalent(other) or b._is_equivalent(unit) and a._is_equivalent(other)): return True return False def _apply_equivalencies(self, unit, other, equivalencies): """ Internal function (used from `_get_converter`) to apply equivalence pairs. """ def make_converter(scale1, func, scale2): def convert(v): return func(_condition_arg(v) / scale1) * scale2 return convert for funit, tunit, a, b in equivalencies: if tunit is None: try: ratio_in_funit = (other.decompose() / unit.decompose()).decompose([funit]) return make_converter(ratio_in_funit.scale, a, 1.) except UnitsError: pass else: try: scale1 = funit._to(unit) scale2 = tunit._to(other) return make_converter(scale1, a, scale2) except UnitsError: pass try: scale1 = tunit._to(unit) scale2 = funit._to(other) return make_converter(scale1, b, scale2) except UnitsError: pass def get_err_str(unit): unit_str = unit.to_string('unscaled') physical_type = unit.physical_type if physical_type != 'unknown': unit_str = "'{0}' ({1})".format( unit_str, physical_type) else: unit_str = "'{0}'".format(unit_str) return unit_str unit_str = get_err_str(unit) other_str = get_err_str(other) raise UnitConversionError( "{0} and {1} are not convertible".format( unit_str, other_str)) def _get_converter(self, other, equivalencies=[]): other = Unit(other) # First see if it is just a scaling. try: scale = self._to(other) except UnitsError: pass else: return lambda val: scale * _condition_arg(val) # if that doesn't work, maybe we can do it with equivalencies? try: return self._apply_equivalencies( self, other, self._normalize_equivalencies(equivalencies)) except UnitsError as exc: # Last hope: maybe other knows how to do it? # We assume the equivalencies have the unit itself as first item. # TODO: maybe better for other to have a `_back_converter` method? if hasattr(other, 'equivalencies'): for funit, tunit, a, b in other.equivalencies: if other is funit: try: return lambda v: b(self._get_converter( tunit, equivalencies=equivalencies)(v)) except Exception: pass raise exc def _to(self, other): """ Returns the scale to the specified unit. See `to`, except that a Unit object should be given (i.e., no string), and that all defaults are used, i.e., no equivalencies and value=1. """ # There are many cases where we just want to ensure a Quantity is # of a particular unit, without checking whether it's already in # a particular unit. If we're being asked to convert from a unit # to itself, we can short-circuit all of this. if self is other: return 1.0 # Don't presume decomposition is possible; e.g., # conversion to function units is through equivalencies. if isinstance(other, UnitBase): self_decomposed = self.decompose() other_decomposed = other.decompose() # Check quickly whether equivalent. This is faster than # `is_equivalent`, because it doesn't generate the entire # physical type list of both units. In other words it "fails # fast". if(self_decomposed.powers == other_decomposed.powers and all(self_base is other_base for (self_base, other_base) in zip(self_decomposed.bases, other_decomposed.bases))): return self_decomposed.scale / other_decomposed.scale raise UnitConversionError( "'{0!r}' is not a scaled version of '{1!r}'".format(self, other)) def to(self, other, value=1.0, equivalencies=[]): """ Return the converted values in the specified unit. Parameters ---------- other : unit 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 addition to possible global defaults set by, e.g., `set_enabled_equivalencies`. Use `None` to turn off all equivalencies. Returns ------- values : scalar or array Converted value(s). Input value sequences are returned as numpy arrays. Raises ------ UnitsError If units are inconsistent """ return self._get_converter(other, equivalencies=equivalencies)(value) def in_units(self, other, value=1.0, equivalencies=[]): """ Alias for `to` for backward compatibility with pynbody. """ return self.to( other, value=value, equivalencies=equivalencies) def decompose(self, bases=set()): """ Return a unit object composed of only irreducible units. Parameters ---------- bases : sequence of UnitBase, optional The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a `UnitsError` if it's not possible to do so. Returns ------- unit : CompositeUnit object New object containing only irreducible unit objects. """ raise NotImplementedError() def _compose(self, equivalencies=[], namespace=[], max_depth=2, depth=0, cached_results=None): def is_final_result(unit): # Returns True if this result contains only the expected # units for base in unit.bases: if base not in namespace: return False return True unit = self.decompose() key = hash(unit) cached = cached_results.get(key) if cached is not None: if isinstance(cached, Exception): raise cached return cached # Prevent too many levels of recursion # And special case for dimensionless unit if depth >= max_depth: cached_results[key] = [unit] return [unit] # Make a list including all of the equivalent units units = [unit] for funit, tunit, a, b in equivalencies: if tunit is not None: if self._is_equivalent(funit): scale = funit.decompose().scale / unit.scale units.append(Unit(a(1.0 / scale) * tunit).decompose()) elif self._is_equivalent(tunit): scale = tunit.decompose().scale / unit.scale units.append(Unit(b(1.0 / scale) * funit).decompose()) else: if self._is_equivalent(funit): units.append(Unit(unit.scale)) # Store partial results partial_results = [] # Store final results that reduce to a single unit or pair of # units if len(unit.bases) == 0: final_results = [set([unit]), set()] else: final_results = [set(), set()] for tunit in namespace: tunit_decomposed = tunit.decompose() for u in units: # If the unit is a base unit, look for an exact match # to one of the bases of the target unit. If found, # factor by the same power as the target unit's base. # This allows us to factor out fractional powers # without needing to do an exhaustive search. if len(tunit_decomposed.bases) == 1: for base, power in zip(u.bases, u.powers): if tunit_decomposed._is_equivalent(base): tunit = tunit ** power tunit_decomposed = tunit_decomposed ** power break composed = (u / tunit_decomposed).decompose() factored = composed * tunit len_bases = len(composed.bases) if is_final_result(factored) and len_bases <= 1: final_results[len_bases].add(factored) else: partial_results.append( (len_bases, composed, tunit)) # Do we have any minimal results? for final_result in final_results: if len(final_result): results = final_results[0].union(final_results[1]) cached_results[key] = results return results partial_results.sort(key=operator.itemgetter(0)) # ...we have to recurse and try to further compose results = [] for len_bases, composed, tunit in partial_results: try: composed_list = composed._compose( equivalencies=equivalencies, namespace=namespace, max_depth=max_depth, depth=depth + 1, cached_results=cached_results) except UnitsError: composed_list = [] for subcomposed in composed_list: results.append( (len(subcomposed.bases), subcomposed, tunit)) if len(results): results.sort(key=operator.itemgetter(0)) min_length = results[0][0] subresults = set() for len_bases, composed, tunit in results: if len_bases > min_length: break else: factored = composed * tunit if is_final_result(factored): subresults.add(factored) if len(subresults): cached_results[key] = subresults return subresults if not is_final_result(self): result = UnitsError( "Cannot represent unit {0} in terms of the given " "units".format(self)) cached_results[key] = result raise result cached_results[key] = [self] return [self] def compose(self, equivalencies=[], units=None, max_depth=2, include_prefix_units=None): """ Return the simplest possible composite unit(s) that represent the given unit. Since there may be multiple equally simple compositions of the unit, a list of units is always returned. Parameters ---------- equivalencies : list of equivalence pairs, optional A list of equivalence pairs to also list. See :ref:`unit_equivalencies`. This list is in addition to possible global defaults set by, e.g., `set_enabled_equivalencies`. Use `None` to turn off all equivalencies. units : set of units to compose to, optional If not provided, any known units may be used to compose into. Otherwise, ``units`` is a dict, module or sequence containing the units to compose into. max_depth : int, optional The maximum recursion depth to use when composing into composite units. include_prefix_units : bool, optional When `True`, include prefixed units in the result. Default is `True` if a sequence is passed in to ``units``, `False` otherwise. Returns ------- units : list of `CompositeUnit` A list of candidate compositions. These will all be equally simple, but it may not be possible to automatically determine which of the candidates are better. """ # if units parameter is specified and is a sequence (list|tuple), # include_prefix_units is turned on by default. Ex: units=[u.kpc] if include_prefix_units is None: include_prefix_units = isinstance(units, (list, tuple)) # Pre-normalize the equivalencies list equivalencies = self._normalize_equivalencies(equivalencies) # The namespace of units to compose into should be filtered to # only include units with bases in common with self, otherwise # they can't possibly provide useful results. Having too many # destination units greatly increases the search space. def has_bases_in_common(a, b): if len(a.bases) == 0 and len(b.bases) == 0: return True for ab in a.bases: for bb in b.bases: if ab == bb: return True return False def has_bases_in_common_with_equiv(unit, other): if has_bases_in_common(unit, other): return True for funit, tunit, a, b in equivalencies: if tunit is not None: if unit._is_equivalent(funit): if has_bases_in_common(tunit.decompose(), other): return True elif unit._is_equivalent(tunit): if has_bases_in_common(funit.decompose(), other): return True else: if unit._is_equivalent(funit): if has_bases_in_common(dimensionless_unscaled, other): return True return False def filter_units(units): filtered_namespace = set() for tunit in units: if (isinstance(tunit, UnitBase) and (include_prefix_units or not isinstance(tunit, PrefixUnit)) and has_bases_in_common_with_equiv( decomposed, tunit.decompose())): filtered_namespace.add(tunit) return filtered_namespace decomposed = self.decompose() if units is None: units = filter_units(self._get_units_with_same_physical_type( equivalencies=equivalencies)) if len(units) == 0: units = get_current_unit_registry().non_prefix_units elif isinstance(units, dict): units = set(filter_units(units.values())) elif inspect.ismodule(units): units = filter_units(vars(units).values()) else: units = filter_units(_flatten_units_collection(units)) def sort_results(results): if not len(results): return [] # Sort the results so the simplest ones appear first. # Simplest is defined as "the minimum sum of absolute # powers" (i.e. the fewest bases), and preference should # be given to results where the sum of powers is positive # and the scale is exactly equal to 1.0 results = list(results) results.sort(key=lambda x: np.abs(x.scale)) results.sort(key=lambda x: np.sum(np.abs(x.powers))) results.sort(key=lambda x: np.sum(x.powers) < 0.0) results.sort(key=lambda x: not is_effectively_unity(x.scale)) last_result = results[0] filtered = [last_result] for result in results[1:]: if str(result) != str(last_result): filtered.append(result) last_result = result return filtered return sort_results(self._compose( equivalencies=equivalencies, namespace=units, max_depth=max_depth, depth=0, cached_results={})) def to_system(self, system): """ Converts this unit into ones belonging to the given system. Since more than one result may be possible, a list is always returned. Parameters ---------- system : module The module that defines the unit system. Commonly used ones include `astropy.units.si` and `astropy.units.cgs`. To use your own module it must contain unit objects and a sequence member named ``bases`` containing the base units of the system. Returns ------- units : list of `CompositeUnit` The list is ranked so that units containing only the base units of that system will appear first. """ bases = set(system.bases) def score(compose): # In case that compose._bases has no elements we return # 'np.inf' as 'score value'. It does not really matter which # number we would return. This case occurs for instance for # dimensionless quantities: compose_bases = compose.bases if len(compose_bases) == 0: return np.inf else: sum = 0 for base in compose_bases: if base in bases: sum += 1 return sum / float(len(compose_bases)) x = self.decompose(bases=bases) composed = x.compose(units=system) composed = sorted(composed, key=score, reverse=True) return composed @lazyproperty def si(self): """ Returns a copy of the current `Unit` instance in SI units. """ from . import si return self.to_system(si)[0] @lazyproperty def cgs(self): """ Returns a copy of the current `Unit` instance with CGS units. """ from . import cgs return self.to_system(cgs)[0] @property def physical_type(self): """ Return the physical type on the unit. Examples -------- >>> from astropy import units as u >>> print(u.m.physical_type) length """ from . import physical return physical.get_physical_type(self) def _get_units_with_same_physical_type(self, equivalencies=[]): """ Return a list of registered units with the same physical type as this unit. This function is used by Quantity to add its built-in conversions to equivalent units. This is a private method, since end users should be encouraged to use the more powerful `compose` and `find_equivalent_units` methods (which use this under the hood). Parameters ---------- equivalencies : list of equivalence pairs, optional A list of equivalence pairs to also pull options from. See :ref:`unit_equivalencies`. It must already be normalized using `_normalize_equivalencies`. """ unit_registry = get_current_unit_registry() units = set(unit_registry.get_units_with_physical_type(self)) for funit, tunit, a, b in equivalencies: if tunit is not None: if self.is_equivalent(funit) and tunit not in units: units.update( unit_registry.get_units_with_physical_type(tunit)) if self._is_equivalent(tunit) and funit not in units: units.update( unit_registry.get_units_with_physical_type(funit)) else: if self.is_equivalent(funit): units.add(dimensionless_unscaled) return units class EquivalentUnitsList(list): """ A class to handle pretty-printing the result of `find_equivalent_units`. """ def __repr__(self): if len(self) == 0: return "[]" else: lines = [] for u in self: irred = u.decompose().to_string() if irred == u.name: irred = "irreducible" lines.append((u.name, irred, ', '.join(u.aliases))) lines.sort() lines.insert(0, ('Primary name', 'Unit definition', 'Aliases')) widths = [0, 0, 0] for line in lines: for i, col in enumerate(line): widths[i] = max(widths[i], len(col)) f = " {{0:<{0}s}} | {{1:<{1}s}} | {{2:<{2}s}}".format(*widths) lines = [f.format(*line) for line in lines] lines = (lines[0:1] + ['['] + ['{0} ,'.format(x) for x in lines[1:]] + [']']) return '\n'.join(lines) def find_equivalent_units(self, equivalencies=[], units=None, include_prefix_units=False): """ Return a list of all the units that are the same type as ``self``. Parameters ---------- equivalencies : list of equivalence pairs, optional A list of equivalence pairs to also list. See :ref:`unit_equivalencies`. Any list given, including an empty one, supercedes global defaults that may be in effect (as set by `set_enabled_equivalencies`) units : set of units to search in, optional If not provided, all defined units will be searched for equivalencies. Otherwise, may be a dict, module or sequence containing the units to search for equivalencies. include_prefix_units : bool, optional When `True`, include prefixed units in the result. Default is `False`. Returns ------- units : list of `UnitBase` A list of unit objects that match ``u``. A subclass of `list` (``EquivalentUnitsList``) is returned that pretty-prints the list of units when output. """ results = self.compose( equivalencies=equivalencies, units=units, max_depth=1, include_prefix_units=include_prefix_units) results = set( x.bases[0] for x in results if len(x.bases) == 1) return self.EquivalentUnitsList(results) def is_unity(self): """ Returns `True` if the unit is unscaled and dimensionless. """ return False class NamedUnit(UnitBase): """ The base class of units that have a name. Parameters ---------- st : str, list of str, 2-tuple The name of the unit. If a list of strings, the first element is the canonical (short) name, and the rest of the elements are aliases. If a tuple of lists, the first element is a list of short names, and the second element is a list of long names; all but the first short name are considered "aliases". Each name *should* be a valid Python identifier to make it easy to access, but this is not required. namespace : dict, optional When provided, inject the unit, and all of its aliases, in the given namespace dictionary. If a unit by the same name is already in the namespace, a ValueError is raised. doc : str, optional A docstring describing the unit. format : dict, optional A mapping to format-specific representations of this unit. For example, for the ``Ohm`` unit, it might be nice to have it displayed as ``\\Omega`` by the ``latex`` formatter. In that case, `format` argument should be set to:: {'latex': r'\\Omega'} Raises ------ ValueError If any of the given unit names are already in the registry. ValueError If any of the given unit names are not valid Python tokens. """ def __init__(self, st, doc=None, format=None, namespace=None): UnitBase.__init__(self) if isinstance(st, (bytes, str)): self._names = [st] self._short_names = [st] self._long_names = [] elif isinstance(st, tuple): if not len(st) == 2: raise ValueError("st must be string, list or 2-tuple") self._names = st[0] + [n for n in st[1] if n not in st[0]] if not len(self._names): raise ValueError("must provide at least one name") self._short_names = st[0][:] self._long_names = st[1][:] else: if len(st) == 0: raise ValueError( "st list must have at least one entry") self._names = st[:] self._short_names = [st[0]] self._long_names = st[1:] if format is None: format = {} self._format = format if doc is None: doc = self._generate_doc() else: doc = textwrap.dedent(doc) doc = textwrap.fill(doc) self.__doc__ = doc self._inject(namespace) def _generate_doc(self): """ Generate a docstring for the unit if the user didn't supply one. This is only used from the constructor and may be overridden in subclasses. """ names = self.names if len(self.names) > 1: return "{1} ({0})".format(*names[:2]) else: return names[0] def get_format_name(self, format): """ Get a name for this unit that is specific to a particular format. Uses the dictionary passed into the `format` kwarg in the constructor. Parameters ---------- format : str The name of the format Returns ------- name : str The name of the unit for the given format. """ return self._format.get(format, self.name) @property def names(self): """ Returns all of the names associated with this unit. """ return self._names @property def name(self): """ Returns the canonical (short) name associated with this unit. """ return self._names[0] @property def aliases(self): """ Returns the alias (long) names for this unit. """ return self._names[1:] @property def short_names(self): """ Returns all of the short names associated with this unit. """ return self._short_names @property def long_names(self): """ Returns all of the long names associated with this unit. """ return self._long_names def _inject(self, namespace=None): """ Injects the unit, and all of its aliases, in the given namespace dictionary. """ if namespace is None: return # Loop through all of the names first, to ensure all of them # are new, then add them all as a single "transaction" below. for name in self._names: if name in namespace and self != namespace[name]: raise ValueError( "Object with name {0!r} already exists in " "given namespace ({1!r}).".format( name, namespace[name])) for name in self._names: namespace[name] = self def _recreate_irreducible_unit(cls, names, registered): """ This is used to reconstruct units when passed around by multiprocessing. """ registry = get_current_unit_registry().registry if names[0] in registry: # If in local registry return that object. return registry[names[0]] else: # otherwise, recreate the unit. unit = cls(names) if registered: # If not in local registry but registered in origin registry, # enable unit in local registry. get_current_unit_registry().add_enabled_units([unit]) return unit class IrreducibleUnit(NamedUnit): """ Irreducible units are the units that all other units are defined in terms of. Examples are meters, seconds, kilograms, amperes, etc. There is only once instance of such a unit per type. """ def __reduce__(self): # When IrreducibleUnit objects are passed to other processes # over multiprocessing, they need to be recreated to be the # ones already in the subprocesses' namespace, not new # objects, or they will be considered "unconvertible". # Therefore, we have a custom pickler/unpickler that # understands how to recreate the Unit on the other side. registry = get_current_unit_registry().registry return (_recreate_irreducible_unit, (self.__class__, list(self.names), self.name in registry), self.__dict__) @property def represents(self): """The unit that this named unit represents. For an irreducible unit, that is always itself. """ return self def decompose(self, bases=set()): if len(bases) and self not in bases: for base in bases: try: scale = self._to(base) except UnitsError: pass else: if is_effectively_unity(scale): return base else: return CompositeUnit(scale, [base], [1], _error_check=False) raise UnitConversionError( "Unit {0} can not be decomposed into the requested " "bases".format(self)) return self class UnrecognizedUnit(IrreducibleUnit): """ A unit that did not parse correctly. This allows for roundtripping it as a string, but no unit operations actually work on it. Parameters ---------- st : str The name of the unit. """ # For UnrecognizedUnits, we want to use "standard" Python # pickling, not the special case that is used for # IrreducibleUnits. __reduce__ = object.__reduce__ def __repr__(self): return "UnrecognizedUnit({0})".format(str(self)) def __bytes__(self): return self.name.encode('ascii', 'replace') def __str__(self): return self.name def to_string(self, format=None): return self.name def _unrecognized_operator(self, *args, **kwargs): raise ValueError( "The unit {0!r} is unrecognized, so all arithmetic operations " "with it are invalid.".format(self.name)) __pow__ = __div__ = __rdiv__ = __truediv__ = __rtruediv__ = __mul__ = \ __rmul__ = __lt__ = __gt__ = __le__ = __ge__ = __neg__ = \ _unrecognized_operator def __eq__(self, other): other = Unit(other, parse_strict='silent') return isinstance(other, UnrecognizedUnit) and self.name == other.name def __ne__(self, other): return not (self == other) def is_equivalent(self, other, equivalencies=None): self._normalize_equivalencies(equivalencies) return self == other def _get_converter(self, other, equivalencies=None): self._normalize_equivalencies(equivalencies) raise ValueError( "The unit {0!r} is unrecognized. It can not be converted " "to other units.".format(self.name)) def get_format_name(self, format): return self.name def is_unity(self): return False class _UnitMetaClass(InheritDocstrings): """ This metaclass exists because the Unit constructor should sometimes return instances that already exist. This "overrides" the constructor before the new instance is actually created, so we can return an existing one. """ def __call__(self, s, represents=None, format=None, namespace=None, doc=None, parse_strict='raise'): # Short-circuit if we're already a unit if hasattr(s, '_get_physical_type_id'): return s # turn possible Quantity input for s or represents into a Unit from .quantity import Quantity if isinstance(represents, Quantity): if is_effectively_unity(represents.value): represents = represents.unit else: # cannot use _error_check=False: scale may be effectively unity represents = CompositeUnit(represents.value * represents.unit.scale, bases=represents.unit.bases, powers=represents.unit.powers) if isinstance(s, Quantity): if is_effectively_unity(s.value): s = s.unit else: s = CompositeUnit(s.value * s.unit.scale, bases=s.unit.bases, powers=s.unit.powers) # now decide what we really need to do; define derived Unit? if isinstance(represents, UnitBase): # This has the effect of calling the real __new__ and # __init__ on the Unit class. return super().__call__( s, represents, format=format, namespace=namespace, doc=doc) # or interpret a Quantity (now became unit), string or number? if isinstance(s, UnitBase): return s elif isinstance(s, (bytes, str)): if len(s.strip()) == 0: # Return the NULL unit return dimensionless_unscaled if format is None: format = unit_format.Generic f = unit_format.get_format(format) if isinstance(s, bytes): s = s.decode('ascii') try: return f.parse(s) except Exception as e: if parse_strict == 'silent': pass else: # Deliberately not issubclass here. Subclasses # should use their name. if f is not unit_format.Generic: format_clause = f.name + ' ' else: format_clause = '' msg = ("'{0}' did not parse as {1}unit: {2}" .format(s, format_clause, str(e))) if parse_strict == 'raise': raise ValueError(msg) elif parse_strict == 'warn': warnings.warn(msg, UnitsWarning) else: raise ValueError("'parse_strict' must be 'warn', " "'raise' or 'silent'") return UnrecognizedUnit(s) elif isinstance(s, (int, float, np.floating, np.integer)): return CompositeUnit(s, [], []) elif s is None: raise TypeError("None is not a valid Unit") else: raise TypeError("{0} can not be converted to a Unit".format(s)) class Unit(NamedUnit, metaclass=_UnitMetaClass): """ The main unit class. There are a number of different ways to construct a Unit, but always returns a `UnitBase` instance. If the arguments refer to an already-existing unit, that existing unit instance is returned, rather than a new one. - From a string:: Unit(s, format=None, parse_strict='silent') Construct from a string representing a (possibly compound) unit. The optional `format` keyword argument specifies the format the string is in, by default ``"generic"``. For a description of the available formats, see `astropy.units.format`. The optional ``parse_strict`` keyword controls what happens when an unrecognized unit string is passed in. It may be one of the following: - ``'raise'``: (default) raise a ValueError exception. - ``'warn'``: emit a Warning, and return an `UnrecognizedUnit` instance. - ``'silent'``: return an `UnrecognizedUnit` instance. - From a number:: Unit(number) Creates a dimensionless unit. - From a `UnitBase` instance:: Unit(unit) Returns the given unit unchanged. - From `None`:: Unit() Returns the null unit. - The last form, which creates a new `Unit` is described in detail below. Parameters ---------- st : str or list of str The name of the unit. If a list, the first element is the canonical (short) name, and the rest of the elements are aliases. represents : UnitBase instance The unit that this named unit represents. doc : str, optional A docstring describing the unit. format : dict, optional A mapping to format-specific representations of this unit. For example, for the ``Ohm`` unit, it might be nice to have it displayed as ``\\Omega`` by the ``latex`` formatter. In that case, `format` argument should be set to:: {'latex': r'\\Omega'} namespace : dictionary, optional When provided, inject the unit (and all of its aliases) into the given namespace. Raises ------ ValueError If any of the given unit names are already in the registry. ValueError If any of the given unit names are not valid Python tokens. """ def __init__(self, st, represents=None, doc=None, format=None, namespace=None): represents = Unit(represents) self._represents = represents NamedUnit.__init__(self, st, namespace=namespace, doc=doc, format=format) @property def represents(self): """The unit that this named unit represents.""" return self._represents def decompose(self, bases=set()): return self._represents.decompose(bases=bases) def is_unity(self): return self._represents.is_unity() def __hash__(self): return hash(self.name) + hash(self._represents) @classmethod def _from_physical_type_id(cls, physical_type_id): # get string bases and powers from the ID tuple bases = [cls(base) for base, _ in physical_type_id] powers = [power for _, power in physical_type_id] if len(physical_type_id) == 1 and powers[0] == 1: unit = bases[0] else: unit = CompositeUnit(1, bases, powers) return unit class PrefixUnit(Unit): """ A unit that is simply a SI-prefixed version of another unit. For example, ``mm`` is a `PrefixUnit` of ``.001 * m``. The constructor is the same as for `Unit`. """ class CompositeUnit(UnitBase): """ Create a composite unit using expressions of previously defined units. Direct use of this class is not recommended. Instead use the factory function `Unit` and arithmetic operators to compose units. Parameters ---------- scale : number A scaling factor for the unit. bases : sequence of `UnitBase` A sequence of units this unit is composed of. powers : sequence of numbers A sequence of powers (in parallel with ``bases``) for each of the base units. """ def __init__(self, scale, bases, powers, decompose=False, decompose_bases=set(), _error_check=True): # There are many cases internal to astropy.units where we # already know that all the bases are Unit objects, and the # powers have been validated. In those cases, we can skip the # error checking for performance reasons. When the private # kwarg `_error_check` is False, the error checking is turned # off. if _error_check: scale = sanitize_scale(scale) for base in bases: if not isinstance(base, UnitBase): raise TypeError( "bases must be sequence of UnitBase instances") powers = [validate_power(p) for p in powers] self._scale = scale self._bases = bases self._powers = powers self._decomposed_cache = None self._expand_and_gather(decompose=decompose, bases=decompose_bases) self._hash = None def __repr__(self): if len(self._bases): return super().__repr__() else: if self._scale != 1.0: return 'Unit(dimensionless with a scale of {0})'.format( self._scale) else: return 'Unit(dimensionless)' def __hash__(self): if self._hash is None: parts = ([str(self._scale)] + [x.name for x in self._bases] + [str(x) for x in self._powers]) self._hash = hash(tuple(parts)) return self._hash @property def scale(self): """ Return the scale of the composite unit. """ return self._scale @property def bases(self): """ Return the bases of the composite unit. """ return self._bases @property def powers(self): """ Return the powers of the composite unit. """ return self._powers def _expand_and_gather(self, decompose=False, bases=set()): def add_unit(unit, power, scale): if unit not in bases: for base in bases: try: scale *= unit._to(base) ** power except UnitsError: pass else: unit = base break if unit in new_parts: a, b = resolve_fractions(new_parts[unit], power) new_parts[unit] = a + b else: new_parts[unit] = power return scale new_parts = {} scale = self.scale for b, p in zip(self.bases, self.powers): if decompose and b not in bases: b = b.decompose(bases=bases) if isinstance(b, CompositeUnit): scale *= b._scale ** p for b_sub, p_sub in zip(b._bases, b._powers): a, b = resolve_fractions(p_sub, p) scale = add_unit(b_sub, a * b, scale) else: scale = add_unit(b, p, scale) new_parts = [x for x in new_parts.items() if x[1] != 0] new_parts.sort(key=lambda x: (-x[1], getattr(x[0], 'name', ''))) self._bases = [x[0] for x in new_parts] self._powers = [validate_power(x[1]) for x in new_parts] self._scale = sanitize_scale(scale) def __copy__(self): """ For compatibility with python copy module. """ return CompositeUnit(self._scale, self._bases[:], self._powers[:]) def decompose(self, bases=set()): if len(bases) == 0 and self._decomposed_cache is not None: return self._decomposed_cache for base in self.bases: if (not isinstance(base, IrreducibleUnit) or (len(bases) and base not in bases)): break else: if len(bases) == 0: self._decomposed_cache = self return self x = CompositeUnit(self.scale, self.bases, self.powers, decompose=True, decompose_bases=bases) if len(bases) == 0: self._decomposed_cache = x return x def is_unity(self): unit = self.decompose() return len(unit.bases) == 0 and unit.scale == 1.0 si_prefixes = [ (['Y'], ['yotta'], 1e24), (['Z'], ['zetta'], 1e21), (['E'], ['exa'], 1e18), (['P'], ['peta'], 1e15), (['T'], ['tera'], 1e12), (['G'], ['giga'], 1e9), (['M'], ['mega'], 1e6), (['k'], ['kilo'], 1e3), (['h'], ['hecto'], 1e2), (['da'], ['deka', 'deca'], 1e1), (['d'], ['deci'], 1e-1), (['c'], ['centi'], 1e-2), (['m'], ['milli'], 1e-3), (['u'], ['micro'], 1e-6), (['n'], ['nano'], 1e-9), (['p'], ['pico'], 1e-12), (['f'], ['femto'], 1e-15), (['a'], ['atto'], 1e-18), (['z'], ['zepto'], 1e-21), (['y'], ['yocto'], 1e-24) ] binary_prefixes = [ (['Ki'], ['kibi'], 2. ** 10), (['Mi'], ['mebi'], 2. ** 20), (['Gi'], ['gibi'], 2. ** 30), (['Ti'], ['tebi'], 2. ** 40), (['Pi'], ['pebi'], 2. ** 50), (['Ei'], ['exbi'], 2. ** 60) ] def _add_prefixes(u, excludes=[], namespace=None, prefixes=False): """ Set up all of the standard metric prefixes for a unit. This function should not be used directly, but instead use the `prefixes` kwarg on `def_unit`. Parameters ---------- excludes : list of str, optional Any prefixes to exclude from creation to avoid namespace collisions. namespace : dict, optional When provided, inject the unit (and all of its aliases) into the given namespace dictionary. prefixes : list, optional When provided, it is a list of prefix definitions of the form: (short_names, long_tables, factor) """ if prefixes is True: prefixes = si_prefixes elif prefixes is False: prefixes = [] for short, full, factor in prefixes: names = [] format = {} for prefix in short: if prefix in excludes: continue for alias in u.short_names: names.append(prefix + alias) # This is a hack to use Greek mu as a prefix # for some formatters. if prefix == 'u': format['latex'] = r'\mu ' + u.get_format_name('latex') format['unicode'] = 'μ' + u.get_format_name('unicode') for key, val in u._format.items(): format.setdefault(key, prefix + val) for prefix in full: if prefix in excludes: continue for alias in u.long_names: names.append(prefix + alias) if len(names): PrefixUnit(names, CompositeUnit(factor, [u], [1], _error_check=False), namespace=namespace, format=format) def def_unit(s, represents=None, doc=None, format=None, prefixes=False, exclude_prefixes=[], namespace=None): """ Factory function for defining new units. Parameters ---------- s : str or list of str The name of the unit. If a list, the first element is the canonical (short) name, and the rest of the elements are aliases. represents : UnitBase instance, optional The unit that this named unit represents. If not provided, a new `IrreducibleUnit` is created. doc : str, optional A docstring describing the unit. format : dict, optional A mapping to format-specific representations of this unit. For example, for the ``Ohm`` unit, it might be nice to have it displayed as ``\\Omega`` by the ``latex`` formatter. In that case, `format` argument should be set to:: {'latex': r'\\Omega'} prefixes : bool or list, optional When `True`, generate all of the SI prefixed versions of the unit as well. For example, for a given unit ``m``, will generate ``mm``, ``cm``, ``km``, etc. When a list, it is a list of prefix definitions of the form: (short_names, long_tables, factor) Default is `False`. This function always returns the base unit object, even if multiple scaled versions of the unit were created. exclude_prefixes : list of str, optional If any of the SI prefixes need to be excluded, they may be listed here. For example, ``Pa`` can be interpreted either as "petaannum" or "Pascal". Therefore, when defining the prefixes for ``a``, ``exclude_prefixes`` should be set to ``["P"]``. namespace : dict, optional When provided, inject the unit (and all of its aliases and prefixes), into the given namespace dictionary. Returns ------- unit : `UnitBase` object The newly-defined unit, or a matching unit that was already defined. """ if represents is not None: result = Unit(s, represents, namespace=namespace, doc=doc, format=format) else: result = IrreducibleUnit( s, namespace=namespace, doc=doc, format=format) if prefixes: _add_prefixes(result, excludes=exclude_prefixes, namespace=namespace, prefixes=prefixes) return result def _condition_arg(value): """ Validate value is acceptable for conversion purposes. Will convert into an array if not a scalar, and can be converted into an array Parameters ---------- value : int or float value, or sequence of such values Returns ------- Scalar value or numpy array Raises ------ ValueError If value is not as expected """ if isinstance(value, (float, int, complex)): return value if isinstance(value, np.ndarray) and value.dtype.kind in ['i', 'f', 'c']: return value avalue = np.array(value) if avalue.dtype.kind not in ['i', 'f', 'c']: raise ValueError("Value not scalar compatible or convertible to " "an int, float, or complex array") return avalue dimensionless_unscaled = CompositeUnit(1, [], [], _error_check=False) # Abbreviation of the above, see #1980 one = dimensionless_unscaled # Maintain error in old location for backward compatibility # TODO: Is this still needed? Should there be a deprecation warning? unit_format.fits.UnitScaleError = UnitScaleError
b9c21d05b91041941137420d546ad8e7662543c8e876163c164a1fbfe7a3b85a
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This subpackage contains classes and functions for defining and converting between different physical units. This code is adapted from the `pynbody <https://github.com/pynbody/pynbody>`_ units module written by Andrew Pontzen, who has granted the Astropy project permission to use the code under a BSD license. """ from .core import * from .quantity import * from .decorators import * from . import si from . import cgs from . import astrophys from .function import units as function_units from .si import * from .astrophys import * from .cgs import * from .physical import * from .function.units import * from .equivalencies import * from .function.core import * from .function.logarithmic import * from .function import magnitude_zero_points del bases # Enable the set of default units. This notably does *not* include # Imperial units. set_enabled_units([si, cgs, astrophys, function_units])
5150bf1925ed74c36f8610b5a7d9248655995468b75889200fcc501e93e0d314
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines the astrophysics-specific units. They are also available in the `astropy.units` namespace. """ from . import si from ..constants import si as _si from .core import (UnitBase, def_unit, si_prefixes, binary_prefixes, set_enabled_units) # To ensure si units of the constants can be interpreted. set_enabled_units([si]) import numpy as _numpy _ns = globals() ########################################################################### # LENGTH def_unit((['AU', 'au'], ['astronomical_unit']), _si.au, namespace=_ns, prefixes=True, doc="astronomical unit: approximately the mean Earth--Sun " "distance.") def_unit(['pc', 'parsec'], _si.pc, namespace=_ns, prefixes=True, doc="parsec: approximately 3.26 light-years.") def_unit(['solRad', 'R_sun', 'Rsun'], _si.R_sun, namespace=_ns, doc="Solar radius", prefixes=False, format={'latex': r'R_{\odot}', 'unicode': 'R⊙'}) def_unit(['jupiterRad', 'R_jup', 'Rjup', 'R_jupiter', 'Rjupiter'], _si.R_jup, namespace=_ns, prefixes=False, doc="Jupiter radius", # LaTeX jupiter symbol requires wasysym format={'latex': r'R_{\rm J}', 'unicode': 'R♃'}) def_unit(['earthRad', 'R_earth', 'Rearth'], _si.R_earth, namespace=_ns, prefixes=False, doc="Earth radius", # LaTeX earth symbol requires wasysym format={'latex': r'R_{\oplus}', 'unicode': 'R⊕'}) def_unit(['lyr', 'lightyear'], (_si.c * si.yr).to(si.m), namespace=_ns, prefixes=True, doc="Light year") ########################################################################### # AREAS def_unit(['barn', 'barn'], 10 ** -28 * si.m ** 2, namespace=_ns, prefixes=True, doc="barn: unit of area used in HEP") ########################################################################### # ANGULAR MEASUREMENTS def_unit(['cycle', 'cy'], 2.0 * _numpy.pi * si.rad, namespace=_ns, prefixes=False, doc="cycle: angular measurement, a full turn or rotation") ########################################################################### # MASS def_unit(['solMass', 'M_sun', 'Msun'], _si.M_sun, namespace=_ns, prefixes=False, doc="Solar mass", format={'latex': r'M_{\odot}', 'unicode': 'M⊙'}) def_unit(['jupiterMass', 'M_jup', 'Mjup', 'M_jupiter', 'Mjupiter'], _si.M_jup, namespace=_ns, prefixes=False, doc="Jupiter mass", # LaTeX jupiter symbol requires wasysym format={'latex': r'M_{\rm J}', 'unicode': 'M♃'}) def_unit(['earthMass', 'M_earth', 'Mearth'], _si.M_earth, namespace=_ns, prefixes=False, doc="Earth mass", # LaTeX earth symbol requires wasysym format={'latex': r'M_{\oplus}', 'unicode': 'M⊕'}) def_unit(['M_p'], _si.m_p, namespace=_ns, doc="Proton mass", format={'latex': r'M_{p}', 'unicode': 'Mₚ'}) def_unit(['M_e'], _si.m_e, namespace=_ns, doc="Electron mass", format={'latex': r'M_{e}', 'unicode': 'Mₑ'}) # Unified atomic mass unit def_unit(['u', 'Da', 'Dalton'], _si.u, namespace=_ns, prefixes=True, exclude_prefixes=['a', 'da'], doc="Unified atomic mass unit") ########################################################################## # ENERGY # Here, explicitly convert the planck constant to 'eV s' since the constant # can override that to give a more precise value that takes into account # covariances between e and h. Eventually, this may also be replaced with # just `_si.Ryd.to(eV)`. def_unit(['Ry', 'rydberg'], (_si.Ryd * _si.c * _si.h.to(si.eV * si.s)).to(si.eV), namespace=_ns, prefixes=True, doc="Rydberg: Energy of a photon whose wavenumber is the Rydberg " "constant", format={'latex': r'R_{\infty}', 'unicode': 'R∞'}) ########################################################################### # ILLUMINATION def_unit(['solLum', 'L_sun', 'Lsun'], _si.L_sun, namespace=_ns, prefixes=False, doc="Solar luminance", format={'latex': r'L_{\odot}', 'unicode': 'L⊙'}) ########################################################################### # SPECTRAL DENSITY def_unit((['ph', 'photon'], ['photon']), format={'ogip': 'photon', 'vounit': 'photon'}, namespace=_ns, prefixes=True) def_unit(['Jy', 'Jansky', 'jansky'], 1e-26 * si.W / si.m ** 2 / si.Hz, namespace=_ns, prefixes=True, doc="Jansky: spectral flux density") def_unit(['R', 'Rayleigh', 'rayleigh'], (1e10 / (4 * _numpy.pi)) * ph * si.m ** -2 * si.s ** -1 * si.sr ** -1, namespace=_ns, prefixes=True, doc="Rayleigh: photon flux") ########################################################################### # MISCELLANEOUS # Some of these are very FITS-specific and perhaps considered a mistake. # Maybe they should be moved into the FITS format class? # TODO: This is defined by the FITS standard as "relative to the sun". # Is that mass, volume, what? def_unit(['Sun'], namespace=_ns) ########################################################################### # EVENTS def_unit((['ct', 'count'], ['count']), format={'fits': 'count', 'ogip': 'count', 'vounit': 'count'}, namespace=_ns, prefixes=True, exclude_prefixes=['p']) def_unit((['pix', 'pixel'], ['pixel']), format={'ogip': 'pixel', 'vounit': 'pixel'}, namespace=_ns, prefixes=True) ########################################################################### # MISCELLANEOUS def_unit(['chan'], namespace=_ns, prefixes=True) def_unit(['bin'], namespace=_ns, prefixes=True) def_unit((['vox', 'voxel'], ['voxel']), format={'fits': 'voxel', 'ogip': 'voxel', 'vounit': 'voxel'}, namespace=_ns, prefixes=True) def_unit((['bit', 'b'], ['bit']), namespace=_ns, prefixes=si_prefixes + binary_prefixes) def_unit((['byte', 'B'], ['byte']), 8 * bit, namespace=_ns, format={'vounit': 'byte'}, prefixes=si_prefixes + binary_prefixes, exclude_prefixes=['d']) def_unit(['adu'], namespace=_ns, prefixes=True) def_unit(['beam'], namespace=_ns, prefixes=True) def_unit(['electron'], doc="Number of electrons", namespace=_ns, format={'latex': r'e^{-}', 'unicode': 'e⁻'}) ########################################################################### # CLEANUP del UnitBase del def_unit del si ########################################################################### # 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())
b51df8024d38d6753c46210c340641005da690ad54737e6ff6aac55afaff16b0
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Defines physical unit names. This module is not intended for use by user code directly. Instead, the physical unit name of a `Unit` can be obtained using its `ptype` property. """ from . import core from . import si from . import astrophys from . import cgs from . import imperial __all__ = ['def_physical_type', 'get_physical_type'] _physical_unit_mapping = {} _unit_physical_mapping = {} def def_physical_type(unit, name): """ Adds a new physical unit mapping. Parameters ---------- unit : `~astropy.units.UnitBase` instance The unit to map from. name : str The physical name of the unit. """ r = unit._get_physical_type_id() if r in _physical_unit_mapping: raise ValueError( "{0!r} ({1!r}) already defined as {2!r}".format( r, name, _physical_unit_mapping[r])) _physical_unit_mapping[r] = name _unit_physical_mapping[name] = r def get_physical_type(unit): """ Given a unit, returns the name of the physical quantity it represents. If it represents an unknown physical quantity, ``"unknown"`` is returned. Parameters ---------- unit : `~astropy.units.UnitBase` instance The unit to lookup Returns ------- physical : str The name of the physical quantity, or unknown if not known. """ r = unit._get_physical_type_id() return _physical_unit_mapping.get(r, 'unknown') for unit, name in [ (core.Unit(1), 'dimensionless'), (si.m, 'length'), (si.m ** 2, 'area'), (si.m ** 3, 'volume'), (si.s, 'time'), (si.rad, 'angle'), (si.sr, 'solid angle'), (si.m / si.s, 'speed'), (si.m / si.s ** 2, 'acceleration'), (si.Hz, 'frequency'), (si.g, 'mass'), (si.mol, 'amount of substance'), (si.K, 'temperature'), (si.deg_C, 'temperature'), (imperial.deg_F, 'temperature'), (si.N, 'force'), (si.J, 'energy'), (si.Pa, 'pressure'), (si.W, 'power'), (si.kg / si.m ** 3, 'mass density'), (si.m ** 3 / si.kg, 'specific volume'), (si.mol / si.m ** 3, 'molar volume'), (si.kg * si.m / si.s, 'momentum/impulse'), (si.kg * si.m ** 2 / si.s, 'angular momentum'), (si.rad / si.s, 'angular speed'), (si.rad / si.s ** 2, 'angular acceleration'), (si.g / (si.m * si.s), 'dynamic viscosity'), (si.m ** 2 / si.s, 'kinematic viscosity'), (si.m ** -1, 'wavenumber'), (si.A, 'electrical current'), (si.C, 'electrical charge'), (si.V, 'electrical potential'), (si.Ohm, 'electrical resistance'), (si.S, 'electrical conductance'), (si.F, 'electrical capacitance'), (si.C * si.m, 'electrical dipole moment'), (si.A / si.m ** 2, 'electrical current density'), (si.V / si.m, 'electrical field strength'), (si.C / si.m ** 2, 'electrical flux density'), (si.C / si.m ** 3, 'electrical charge density'), (si.F / si.m, 'permittivity'), (si.Wb, 'magnetic flux'), (si.T, 'magnetic flux density'), (si.A / si.m, 'magnetic field strength'), (si.H / si.m, 'electromagnetic field strength'), (si.H, 'inductance'), (si.cd, 'luminous intensity'), (si.lm, 'luminous flux'), (si.lx, 'luminous emittence/illuminance'), (si.W / si.sr, 'radiant intensity'), (si.cd / si.m ** 2, 'luminance'), (astrophys.Jy, 'spectral flux density'), (cgs.erg / si.angstrom / si.cm ** 2 / si.s, 'spectral flux density wav'), (astrophys.photon / si.Hz / si.cm ** 2 / si.s, 'photon flux density'), (astrophys.photon / si.AA / si.cm ** 2 / si.s, 'photon flux density wav'), (astrophys.R, 'photon flux'), (astrophys.bit, 'data quantity'), (astrophys.bit / si.s, 'bandwidth'), (cgs.Franklin, 'electrical charge (ESU)'), (cgs.statampere, 'electrical current (ESU)'), (cgs.Biot, 'electrical current (EMU)'), (cgs.abcoulomb, 'electrical charge (EMU)') ]: def_physical_type(unit, name)
912cf6d1104ff23ab398a28eb3c6a74d60733e05fdd649603a6aaad7930fa3d9
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Miscellaneous utilities for `astropy.units`. None of the functions in the module are meant for use outside of the package. """ import numbers import io import re from fractions import Fraction import numpy as np from numpy import finfo _float_finfo = finfo(float) # take float here to ensure comparison with another float is fast # give a little margin since often multiple calculations happened _JUST_BELOW_UNITY = float(1.-4.*_float_finfo.epsneg) _JUST_ABOVE_UNITY = float(1.+4.*_float_finfo.eps) def _get_first_sentence(s): """ Get the first sentence from a string and remove any carriage returns. """ x = re.match(r".*?\S\.\s", s) if x is not None: s = x.group(0) return s.replace('\n', ' ') def _iter_unit_summary(namespace): """ Generates the ``(unit, doc, represents, aliases, prefixes)`` tuple used to format the unit summary docs in `generate_unit_summary`. """ from . import core # Get all of the units, and keep track of which ones have SI # prefixes units = [] has_prefixes = set() for key, val in namespace.items(): # Skip non-unit items if not isinstance(val, core.UnitBase): continue # Skip aliases if key != val.name: continue if isinstance(val, core.PrefixUnit): # This will return the root unit that is scaled by the prefix # attached to it has_prefixes.add(val._represents.bases[0].name) else: units.append(val) # Sort alphabetically, case insensitive units.sort(key=lambda x: x.name.lower()) for unit in units: doc = _get_first_sentence(unit.__doc__).strip() represents = '' if isinstance(unit, core.Unit): represents = ":math:`{0}`".format( unit._represents.to_string('latex')[1:-1]) aliases = ', '.join('``{0}``'.format(x) for x in unit.aliases) yield (unit, doc, represents, aliases, 'Yes' if unit.name in has_prefixes else 'No') def generate_unit_summary(namespace): """ Generates a summary of units from a given namespace. This is used to generate the docstring for the modules that define the actual units. Parameters ---------- namespace : dict A namespace containing units. Returns ------- docstring : str A docstring containing a summary table of the units. """ docstring = io.StringIO() docstring.write(""" .. list-table:: Available Units :header-rows: 1 :widths: 10 20 20 20 1 * - Unit - Description - Represents - Aliases - SI Prefixes """) for unit_summary in _iter_unit_summary(namespace): docstring.write(""" * - ``{0}`` - {1} - {2} - {3} - {4} """.format(*unit_summary)) return docstring.getvalue() def generate_prefixonly_unit_summary(namespace): """ Generates table entries for units in a namespace that are just prefixes without the base unit. Note that this is intended to be used *after* `generate_unit_summary` and therefore does not include the table header. Parameters ---------- namespace : dict A namespace containing units that are prefixes but do *not* have the base unit in their namespace. Returns ------- docstring : str A docstring containing a summary table of the units. """ from . import PrefixUnit faux_namespace = {} for nm, unit in namespace.items(): if isinstance(unit, PrefixUnit): base_unit = unit.represents.bases[0] faux_namespace[base_unit.name] = base_unit docstring = io.StringIO() for unit_summary in _iter_unit_summary(faux_namespace): docstring.write(""" * - Prefixes for ``{0}`` - {1} prefixes - {2} - {3} - Only """.format(*unit_summary)) return docstring.getvalue() def is_effectively_unity(value): # value is *almost* always real, except, e.g., for u.mag**0.5, when # it will be complex. Use try/except to ensure normal case is fast try: return _JUST_BELOW_UNITY <= value <= _JUST_ABOVE_UNITY except TypeError: # value is complex return (_JUST_BELOW_UNITY <= value.real <= _JUST_ABOVE_UNITY and _JUST_BELOW_UNITY <= value.imag + 1 <= _JUST_ABOVE_UNITY) def sanitize_scale(scale): if is_effectively_unity(scale): return 1.0 if np.iscomplex(scale): # scale is complex if scale == 0.0: return 0.0 if abs(scale.real) > abs(scale.imag): if is_effectively_unity(scale.imag/scale.real + 1): scale = scale.real else: if is_effectively_unity(scale.real/scale.imag + 1): scale = complex(0., scale.imag) return scale def validate_power(p, support_tuples=False): """Convert a power to a floating point value, an integer, or a Fraction. If a fractional power can be represented exactly as a floating point number, convert it to a float, to make the math much faster; otherwise, retain it as a `fractions.Fraction` object to avoid losing precision. Conversely, if the value is indistinguishable from a rational number with a low-numbered denominator, convert to a Fraction object. Parameters ---------- p : float, int, Rational, Fraction Power to be converted """ if isinstance(p, (numbers.Rational, Fraction)): denom = p.denominator if denom == 1: p = int(p.numerator) # This is bit-twiddling hack to see if the integer is a # power of two elif (denom & (denom - 1)) == 0: p = float(p) else: try: p = float(p) except Exception: if not np.isscalar(p): raise ValueError("Quantities and Units may only be raised " "to a scalar power") else: raise if (p % 1.0) == 0.0: # Denominators of 1 can just be integers. p = int(p) elif (p * 8.0) % 1.0 == 0.0: # Leave alone if the denominator is exactly 2, 4 or 8, since this # can be perfectly represented as a float, which means subsequent # operations are much faster. pass else: # Convert floats indistinguishable from a rational to Fraction. # Here, we do not need to test values that are divisors of a higher # number, such as 3, since it is already addressed by 6. for i in (10, 9, 7, 6): scaled = p * float(i) if((scaled + 4. * _float_finfo.eps) % 1.0 < 8. * _float_finfo.eps): p = Fraction(int(round(scaled)), i) break return p def resolve_fractions(a, b): """ If either input is a Fraction, convert the other to a Fraction. This ensures that any operation involving a Fraction will use rational arithmetic and preserve precision. """ a_is_fraction = isinstance(a, Fraction) b_is_fraction = isinstance(b, Fraction) if a_is_fraction and not b_is_fraction: b = Fraction(b) elif not a_is_fraction and b_is_fraction: a = Fraction(a) return a, b def quantity_asanyarray(a, dtype=None): from .quantity import Quantity if not isinstance(a, np.ndarray) and not np.isscalar(a) and any(isinstance(x, Quantity) for x in a): return Quantity(a, dtype=dtype) else: return np.asanyarray(a, dtype=dtype)
7b8da1ec271399651d2059db06f63125d185cab8010bd3d4fcac3ad7c0089824
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module defines the `Quantity` object, which represents a number with some associated units. `Quantity` objects support operations like ordinary numbers, but will deal with unit conversions internally. """ # Standard library import re import numbers from fractions import Fraction import warnings import numpy as np # AstroPy from .core import (Unit, dimensionless_unscaled, get_current_unit_registry, UnitBase, UnitsError, UnitTypeError) from .utils import is_effectively_unity from .format.latex import Latex from ..utils.compat import NUMPY_LT_1_13, NUMPY_LT_1_14 from ..utils.compat.misc import override__dir__ from ..utils.exceptions import AstropyDeprecationWarning from ..utils.misc import isiterable, InheritDocstrings from ..utils.data_info import ParentDtypeInfo from .. import config as _config from .quantity_helper import (converters_and_unit, can_have_arbitrary_unit, check_output) __all__ = ["Quantity", "SpecificTypeQuantity", "QuantityInfoBase", "QuantityInfo"] # We don't want to run doctests in the docstrings we inherit from Numpy __doctest_skip__ = ['Quantity.*'] _UNIT_NOT_INITIALISED = "(Unit not initialised)" _UFUNCS_FILTER_WARNINGS = {np.arcsin, np.arccos, np.arccosh, np.arctanh} class Conf(_config.ConfigNamespace): """ Configuration parameters for Quantity """ latex_array_threshold = _config.ConfigItem(100, 'The maximum size an array Quantity can be before its LaTeX ' 'representation for IPython gets "summarized" (meaning only the first ' 'and last few elements are shown with "..." between). Setting this to a ' 'negative number means that the value will instead be whatever numpy ' 'gets from get_printoptions.') conf = Conf() class QuantityIterator: """ Flat iterator object to iterate over Quantities A `QuantityIterator` iterator is returned by ``q.flat`` for any Quantity ``q``. It allows iterating over the array as if it were a 1-D array, either in a for-loop or by calling its `next` method. Iteration is done in C-contiguous style, with the last index varying the fastest. The iterator can also be indexed using basic slicing or advanced indexing. See Also -------- Quantity.flatten : Returns a flattened copy of an array. Notes ----- `QuantityIterator` is inspired by `~numpy.ma.core.MaskedIterator`. It is not exported by the `~astropy.units` module. Instead of instantiating a `QuantityIterator` directly, use `Quantity.flat`. """ def __init__(self, q): self._quantity = q self._dataiter = q.view(np.ndarray).flat def __iter__(self): return self def __getitem__(self, indx): out = self._dataiter.__getitem__(indx) # For single elements, ndarray.flat.__getitem__ returns scalars; these # need a new view as a Quantity. if isinstance(out, type(self._quantity)): return out else: return self._quantity._new_view(out) def __setitem__(self, index, value): self._dataiter[index] = self._quantity._to_own_unit(value) def __next__(self): """ Return the next value, or raise StopIteration. """ out = next(self._dataiter) # ndarray.flat._dataiter returns scalars, so need a view as a Quantity. return self._quantity._new_view(out) next = __next__ class QuantityInfoBase(ParentDtypeInfo): # This is on a base class rather than QuantityInfo directly, so that # it can be used for EarthLocationInfo yet make clear that that class # should not be considered a typical Quantity subclass by Table. attrs_from_parent = {'dtype', 'unit'} # dtype and unit taken from parent _supports_indexing = True @staticmethod def default_format(val): return '{0.value:}'.format(val) @staticmethod def possible_string_format_functions(format_): """Iterate through possible string-derived format functions. A string can either be a format specifier for the format built-in, a new-style format string, or an old-style format string. This method is overridden in order to suppress printing the unit in each row since it is already at the top in the column header. """ yield lambda format_, val: format(val.value, format_) yield lambda format_, val: format_.format(val.value) yield lambda format_, val: format_ % val.value class QuantityInfo(QuantityInfoBase): """ Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information. """ _represent_as_dict_attrs = ('value', 'unit') def _construct_from_dict(self, map): # Need to pop value because different Quantity subclasses use # different first arg name for the value. :-( value = map.pop('value') return self._parent_cls(value, **map) def new_like(self, cols, length, metadata_conflicts='warn', name=None): """ Return a new Quantity instance which is consistent with the input ``cols`` and has ``length`` rows. This is intended for creating an empty column object whose elements can be set in-place for table operations like join or vstack. Parameters ---------- cols : list List of input columns length : int Length of the output column object metadata_conflicts : str ('warn'|'error'|'silent') How to handle metadata conflicts name : str Output column name Returns ------- col : Quantity (or subclass) Empty instance of this class consistent with ``cols`` """ # Get merged info attributes like shape, dtype, format, description, etc. attrs = self.merge_cols_attributes(cols, metadata_conflicts, name, ('meta', 'format', 'description')) # Make an empty quantity using the unit of the last one. shape = (length,) + attrs.pop('shape') dtype = attrs.pop('dtype') # Use zeros so we do not get problems for Quantity subclasses such # as Longitude and Latitude, which cannot take arbitrary values. data = np.zeros(shape=shape, dtype=dtype) # Get arguments needed to reconstruct class map = {key: (data if key == 'value' else getattr(cols[-1], key)) for key in self._represent_as_dict_attrs} map['copy'] = False out = self._construct_from_dict(map) # Set remaining info attributes for attr, value in attrs.items(): setattr(out.info, attr, value) return out class Quantity(np.ndarray, metaclass=InheritDocstrings): """A `~astropy.units.Quantity` represents a number with some associated unit. Parameters ---------- value : number, `~numpy.ndarray`, `Quantity` object (sequence), str The numerical value of this quantity in the units given by unit. If a `Quantity` or sequence of them (or any other valid object with a ``unit`` attribute), creates a new `Quantity` object, converting to `unit` units as needed. If a string, it is converted to a number or `Quantity`, depending on whether a unit is present. unit : `~astropy.units.UnitBase` instance, str An object that represents the unit associated with the input value. Must be an `~astropy.units.UnitBase` object or a string parseable by the :mod:`~astropy.units` package. 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`. This parameter is ignored if the input is a `Quantity` and ``copy=False``. subok : bool, optional If `False` (default), the returned array will be forced to be a `Quantity`. Otherwise, `Quantity` subclasses will be passed through, or a subclass appropriate for the unit will be used (such as `~astropy.units.Dex` for ``u.dex(u.AA)``). 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 `Quantity` and ``copy=False``. Raises ------ TypeError If the value provided is not a Python numeric type. TypeError If the unit provided is not either a :class:`~astropy.units.Unit` object or a parseable string unit. Notes ----- Quantities can also be created by multiplying a number or array with a :class:`~astropy.units.Unit`. See http://docs.astropy.org/en/latest/units/ """ # Need to set a class-level default for _equivalencies, or # Constants can not initialize properly _equivalencies = [] # Default unit for initialization; can be overridden by subclasses, # possibly to `None` to indicate there is no default unit. _default_unit = dimensionless_unscaled # Ensures views have an undefined unit. _unit = None __array_priority__ = 10000 def __new__(cls, value, unit=None, dtype=None, copy=True, order=None, subok=False, ndmin=0): if unit is not None: # convert unit first, to avoid multiple string->unit conversions unit = Unit(unit) # if we allow subclasses, allow a class from the unit. if subok: qcls = getattr(unit, '_quantity_class', cls) if issubclass(qcls, cls): cls = qcls # optimize speed for Quantity with no dtype given, copy=False if isinstance(value, Quantity): if unit is not None and unit is not value.unit: value = value.to(unit) # the above already makes a copy (with float dtype) copy = False if type(value) is not cls and not (subok and isinstance(value, cls)): value = value.view(cls) if dtype is None: if not copy: return value if not np.can_cast(np.float32, value.dtype): dtype = float return np.array(value, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin) # Maybe str, or list/tuple of Quantity? If so, this may set value_unit. # To ensure array remains fast, we short-circuit it. value_unit = None if not isinstance(value, np.ndarray): if isinstance(value, str): # The first part of the regex string matches any integer/float; # the second parts adds possible trailing .+-, which will break # the float function below and ensure things like 1.2.3deg # will not work. pattern = (r'\s*[+-]?' r'((\d+\.?\d*)|(\.\d+)|([nN][aA][nN])|' r'([iI][nN][fF]([iI][nN][iI][tT][yY]){0,1}))' r'([eE][+-]?\d+)?' r'[.+-]?') v = re.match(pattern, value) unit_string = None try: value = float(v.group()) except Exception: raise TypeError('Cannot parse "{0}" as a {1}. It does not ' 'start with a number.' .format(value, cls.__name__)) unit_string = v.string[v.end():].strip() if unit_string: value_unit = Unit(unit_string) if unit is None: unit = value_unit # signal no conversion needed below. elif (isiterable(value) and len(value) > 0 and all(isinstance(v, Quantity) for v in value)): # Convert all quantities to the same unit. if unit is None: unit = value[0].unit value = [q.to_value(unit) for q in value] value_unit = unit # signal below that conversion has been done if value_unit is None: # If the value has a `unit` attribute and if not None # (for Columns with uninitialized unit), treat it like a quantity. value_unit = getattr(value, 'unit', None) if value_unit is None: # Default to dimensionless for no (initialized) unit attribute. if unit is None: unit = cls._default_unit value_unit = unit # signal below that no conversion is needed else: try: value_unit = Unit(value_unit) except Exception as exc: raise TypeError("The unit attribute {0!r} of the input could " "not be parsed as an astropy Unit, raising " "the following exception:\n{1}" .format(value.unit, exc)) if unit is None: unit = value_unit elif unit is not value_unit: copy = False # copy will be made in conversion at end value = np.array(value, dtype=dtype, copy=copy, order=order, subok=False, ndmin=ndmin) # check that array contains numbers or long int objects if (value.dtype.kind in 'OSU' and not (value.dtype.kind == 'O' and isinstance(value.item(() if value.ndim == 0 else 0), numbers.Number))): raise TypeError("The value must be a valid Python or " "Numpy numeric type.") # by default, cast any integer, boolean, etc., to float if dtype is None and (not np.can_cast(np.float32, value.dtype) or value.dtype.kind == 'O'): value = value.astype(float) value = value.view(cls) value._set_unit(value_unit) if unit is value_unit: return value else: # here we had non-Quantity input that had a "unit" attribute # with a unit different from the desired one. So, convert. return value.to(unit) def __array_finalize__(self, obj): # If we're a new object or viewing an ndarray, nothing has to be done. if obj is None or obj.__class__ is np.ndarray: return # If our unit is not set and obj has a valid one, use it. if self._unit is None: unit = getattr(obj, '_unit', None) if unit is not None: self._set_unit(unit) # Copy info if the original had `info` defined. Because of the way the # DataInfo works, `'info' in obj.__dict__` is False until the # `info` attribute is accessed or set. if 'info' in obj.__dict__: self.info = obj.info def __array_prepare__(self, obj, context=None): # This method gets called by Numpy whenever a ufunc is called on the # array. The object passed in ``obj`` is an empty version of the # output array which we can e.g. change to an array sub-class, add # attributes to, etc. After this is called, then the ufunc is called # and the values in this empty array are set. # In principle, this should not be needed any more in numpy >= 1.13, # but it is still called in some np.linalg modules. # If no context is set, just return the input if context is None: return obj # Find out which ufunc is being used function = context[0] args = context[1][:function.nin] # determine required converter functions -- to bring the unit of the # input to that expected (e.g., radian for np.sin), or to get # consistent units between two inputs (e.g., in np.add) -- # and the unit of the result converters, result_unit = converters_and_unit(function, '__call__', *args) if function.nout > 1: result_unit = result_unit[context[2]] # We now prepare the output object if self is obj: # this happens if the output object is self, which happens # for in-place operations such as q1 += q2 # Check that we're not trying to store a plain Numpy array or a # Quantity with an inconsistent unit (e.g., not angular for Angle), # and that we can handle the type (e.g., that we are not int when # float is required). check_output(obj, result_unit, (args + tuple( (np.float16 if converter and converter(1.) % 1. != 0. else np.int8) for converter in converters)), function=function) result = self # no view needed since already a Quantity. # in principle, if self is also an argument, it could be rescaled # here, since it won't be needed anymore. But maybe not change # inputs before the calculation even if they will get destroyed else: # normal case: set up output as a Quantity result = self._new_view(obj, result_unit) # We now need to treat the case where the inputs have to be converted - # the issue is that we can't actually convert the inputs since that # would be changing the objects passed to the ufunc, which would not # be expected by the user. if any(converters): # If self is both output and input (which happens for in-place # operations), input will get overwritten with junk. To avoid # that, hide it in a new object if self is obj and any(self is arg for arg in args): # but with two outputs it would become unhidden too soon # [ie., np.modf(q1, q1, other)]. Bail. if context[2] < function.nout - 1: raise TypeError("Cannot apply multi-output {0} function " "to quantities with in-place replacement " "of an input by any but the last output." .format(function.__name__)) # If self is already contiguous, we don't need to do # an additional copy back into the original array, so # we store it in `result._result`. Otherwise, we # store it in `result._contiguous`. `__array_wrap__` # knows how to handle putting either form back into # the original array. if self.flags['C_CONTIGUOUS']: result = self.copy() result._result = self else: result._contiguous = self.copy() # ensure we remember the converter functions we need result._converters = converters if function in _UFUNCS_FILTER_WARNINGS: # Filter out RuntimeWarning's caused by the ufunc being called on # the unscaled quantity first (e.g., np.arcsin(15*u.pc/u.kpc)) self._catch_warnings = warnings.catch_warnings() self._catch_warnings.__enter__() warnings.filterwarnings('ignore', message='invalid value encountered in', category=RuntimeWarning) # unit output will get (setting _unit could prematurely change input # if obj is self, which happens for in-place operations; see above) result._result_unit = result_unit return result def __array_wrap__(self, obj, context=None): if context is None: # Methods like .squeeze() created a new `ndarray` and then call # __array_wrap__ to turn the array into self's subclass. return self._new_view(obj) else: # with context defined, we are continuing after a ufunc evaluation. if hasattr(obj, '_result_unit'): result_unit = obj._result_unit del obj._result_unit else: result_unit = None # We now need to re-calculate quantities for which the input # needed to be scaled. if hasattr(obj, '_converters'): converters = obj._converters del obj._converters if hasattr(self, '_catch_warnings'): self._catch_warnings.__exit__() del self._catch_warnings # For in-place operations, input will get overwritten with # junk. To avoid that, we hid it in a new object in # __array_prepare__ and retrieve it here. if hasattr(obj, '_result'): obj = obj._result elif hasattr(obj, '_contiguous'): obj[()] = obj._contiguous del obj._contiguous # take array view to which output can be written without # getting back here obj_array = obj.view(np.ndarray) # Find out which ufunc was called and with which inputs function = context[0] args = context[1][:function.nin] # Set the inputs, rescaling as necessary inputs = [] for arg, converter in zip(args, converters): if converter: inputs.append(converter(arg.value)) else: # with no conversion, input can be non-Quantity. inputs.append(getattr(arg, 'value', arg)) # For output arrays that require scaling, we can reuse the # output array to perform the scaling in place, as long as the # array is not integral. Here, we set the obj_array to `None` # when it cannot be used to store the scaled result. # Use a try/except, since np.result_type can fail, which would # break the wrapping #4770. try: tmp_dtype = np.result_type(*inputs) # Catch the appropriate exceptions: TypeError or ValueError in # case the result_type raised an Exception, i.e. inputs is list except (TypeError, ValueError): obj_array = None else: # Explicitly check if it can store the result. if not (result_unit is None or np.can_cast(tmp_dtype, obj_array.dtype)): obj_array = None # Re-compute the output using the ufunc if context[2] == 0: inputs.append(obj_array) else: inputs += [None, obj_array] out = function(*inputs) if obj_array is None: if function.nout > 1: out = out[context[2]] obj = self._new_view(out, result_unit) if result_unit is None: # return a plain array return obj.view(np.ndarray) elif obj is self: # all OK now, so set unit. obj._set_unit(result_unit) return obj else: return obj def __array_ufunc__(self, function, method, *inputs, **kwargs): """Wrap numpy ufuncs, taking care of units. Parameters ---------- function : callable ufunc to wrap. method : str Ufunc method: ``__call__``, ``at``, ``reduce``, etc. inputs : tuple Input arrays. kwargs : keyword arguments As passed on, with ``out`` containing possible quantity output. Returns ------- result : `~astropy.units.Quantity` Results of the ufunc, with the unit set properly. """ # Determine required conversion functions -- to bring the unit of the # input to that expected (e.g., radian for np.sin), or to get # consistent units between two inputs (e.g., in np.add) -- # and the unit of the result (or tuple of units for nout > 1). converters, unit = converters_and_unit(function, method, *inputs) out = kwargs.get('out', None) # Avoid loop back by turning any Quantity output into array views. if out is not None: # If pre-allocated output is used, check it is suitable. # This also returns array view, to ensure we don't loop back. if function.nout == 1: out = out[0] out_array = check_output(out, unit, inputs, function=function) # Ensure output argument remains a tuple. kwargs['out'] = (out_array,) if function.nout == 1 else out_array # Same for inputs, but here also convert if necessary. arrays = [(converter(input_.value) if converter else getattr(input_, 'value', input_)) for input_, converter in zip(inputs, converters)] # Call our superclass's __array_ufunc__ result = super().__array_ufunc__(function, method, *arrays, **kwargs) # If unit is None, a plain array is expected (e.g., comparisons), which # means we're done. # We're also done if the result was None (for method 'at') or # NotImplemented, which can happen if other inputs/outputs override # __array_ufunc__; hopefully, they can then deal with us. if unit is None or result is None or result is NotImplemented: return result return self._result_as_quantity(result, unit, out) def _result_as_quantity(self, result, unit, out): """Turn result into a quantity with the given unit. If no output is given, it will take a view of the array as a quantity, and set the unit. If output is given, those should be quantity views of the result arrays, and the function will just set the unit. Parameters ---------- result : `~numpy.ndarray` or tuple of `~numpy.ndarray` Array(s) which need to be turned into quantity. unit : `~astropy.units.Unit` or None Unit for the quantities to be returned (or `None` if the result should not be a quantity). Should be tuple if result is a tuple. out : `~astropy.units.Quantity` or None Possible output quantity. Should be `None` or a tuple if result is a tuple. Returns ------- out : `~astropy.units.Quantity` With units set. """ if isinstance(result, tuple): if out is None: out = (None,) * len(result) return tuple(self._result_as_quantity(result_, unit_, out_) for (result_, unit_, out_) in zip(result, unit, out)) if out is None: # View the result array as a Quantity with the proper unit. return result if unit is None else self._new_view(result, unit) # For given output, just set the unit. We know the unit is not None and # the output is of the correct Quantity subclass, as it was passed # through check_output. out._set_unit(unit) return out def __quantity_subclass__(self, unit): """ Overridden by subclasses to change what kind of view is created based on the output unit of an operation. Parameters ---------- unit : UnitBase The unit for which the appropriate class should be returned Returns ------- tuple : - `Quantity` subclass - bool: True if subclasses of the given class are ok """ return Quantity, True def _new_view(self, obj=None, unit=None): """ Create a Quantity view of some array-like input, and set the unit By default, return a view of ``obj`` of the same class as ``self`` and with the same unit. Subclasses can override the type of class for a given unit using ``__quantity_subclass__``, and can ensure properties other than the unit are copied using ``__array_finalize__``. If the given unit defines a ``_quantity_class`` of which ``self`` is not an instance, a view using this class is taken. Parameters ---------- obj : ndarray or scalar, optional The array to create a view of. If obj is a numpy or python scalar, it will be converted to an array scalar. By default, ``self`` is converted. unit : `UnitBase`, or anything convertible to a :class:`~astropy.units.Unit`, optional The unit of the resulting object. It is used to select a subclass, and explicitly assigned to the view if given. If not given, the subclass and unit will be that of ``self``. Returns ------- view : Quantity subclass """ # Determine the unit and quantity subclass that we need for the view. if unit is None: unit = self.unit quantity_subclass = self.__class__ else: # In principle, could gain time by testing unit is self.unit # as well, and then quantity_subclass = self.__class__, but # Constant relies on going through `__quantity_subclass__`. unit = Unit(unit) quantity_subclass = getattr(unit, '_quantity_class', Quantity) if isinstance(self, quantity_subclass): quantity_subclass, subok = self.__quantity_subclass__(unit) if subok: quantity_subclass = self.__class__ # We only want to propagate information from ``self`` to our new view, # so obj should be a regular array. By using ``np.array``, we also # convert python and numpy scalars, which cannot be viewed as arrays # and thus not as Quantity either, to zero-dimensional arrays. # (These are turned back into scalar in `.value`) # Note that for an ndarray input, the np.array call takes only double # ``obj.__class is np.ndarray``. So, not worth special-casing. if obj is None: obj = self.view(np.ndarray) else: obj = np.array(obj, copy=False) # Take the view, set the unit, and update possible other properties # such as ``info``, ``wrap_angle`` in `Longitude`, etc. view = obj.view(quantity_subclass) view._set_unit(unit) view.__array_finalize__(self) return view def _set_unit(self, unit): """Set the unit. This is used anywhere the unit is set or modified, i.e., in the initilizer, in ``__imul__`` and ``__itruediv__`` for in-place multiplication and division by another unit, as well as in ``__array_finalize__`` for wrapping up views. For Quantity, it just sets the unit, but subclasses can override it to check that, e.g., a unit is consistent. """ if not isinstance(unit, UnitBase): # Trying to go through a string ensures that, e.g., Magnitudes with # dimensionless physical unit become Quantity with units of mag. unit = Unit(str(unit), parse_strict='silent') if not isinstance(unit, UnitBase): raise UnitTypeError( "{0} instances require {1} units, not {2} instances." .format(type(self).__name__, UnitBase, type(unit))) self._unit = unit def __deepcopy__(self, memo): # If we don't define this, ``copy.deepcopy(quantity)`` will # return a bare Numpy array. return self.copy() def __reduce__(self): # patch to pickle Quantity objects (ndarray subclasses), see # http://www.mail-archive.com/[email protected]/msg02446.html object_state = list(super().__reduce__()) object_state[2] = (object_state[2], self.__dict__) return tuple(object_state) def __setstate__(self, state): # patch to unpickle Quantity objects (ndarray subclasses), see # http://www.mail-archive.com/[email protected]/msg02446.html nd_state, own_state = state super().__setstate__(nd_state) self.__dict__.update(own_state) info = QuantityInfo() def _to_value(self, unit, equivalencies=[]): """Helper method for to and to_value.""" if equivalencies == []: equivalencies = self._equivalencies return self.unit.to(unit, self.view(np.ndarray), equivalencies=equivalencies) def to(self, unit, equivalencies=[]): """ Return a new `~astropy.units.Quantity` object with the specified unit. Parameters ---------- unit : `~astropy.units.UnitBase` instance, str An object that represents the unit to convert to. Must be an `~astropy.units.UnitBase` object or a string parseable by the `~astropy.units` package. equivalencies : list of equivalence pairs, optional A list of equivalence pairs to try if the units are not directly convertible. See :ref:`unit_equivalencies`. If not provided or ``[]``, class default equivalencies will be used (none for `~astropy.units.Quantity`, but may be set for subclasses) If `None`, no equivalencies will be applied at all, not even any set globally or within a context. See also -------- to_value : get the numerical value in a given unit. """ # We don't use `to_value` below since we always want to make a copy # and don't want to slow down this method (esp. the scalar case). unit = Unit(unit) return self._new_view(self._to_value(unit, equivalencies), unit) def to_value(self, unit=None, equivalencies=[]): """ The numerical value, possibly in a different unit. Parameters ---------- unit : `~astropy.units.UnitBase` instance or str, optional The unit in which the value should be given. If not given or `None`, use the current unit. equivalencies : list of equivalence pairs, optional A list of equivalence pairs to try if the units are not directly convertible (see :ref:`unit_equivalencies`). If not provided or ``[]``, class default equivalencies will be used (none for `~astropy.units.Quantity`, but may be set for subclasses). If `None`, no equivalencies will be applied at all, not even any set globally or within a context. Returns ------- value : `~numpy.ndarray` or scalar The value in the units specified. For arrays, this will be a view of the data if no unit conversion was necessary. See also -------- to : Get a new instance in a different unit. """ if unit is None or unit is self.unit: value = self.view(np.ndarray) else: unit = Unit(unit) # We want a view if the unit does not change. One could check # with "==", but that calculates the scale that we need anyway. # TODO: would be better for `unit.to` to have an in-place flag. try: scale = self.unit._to(unit) except Exception: # Short-cut failed; try default (maybe equivalencies help). value = self._to_value(unit, equivalencies) else: value = self.view(np.ndarray) if not is_effectively_unity(scale): # not in-place! value = value * scale return value if self.shape else value.item() value = property(to_value, doc="""The numerical value of this instance. See also -------- to_value : Get the numerical value in a given unit. """) @property def unit(self): """ A `~astropy.units.UnitBase` object representing the unit of this quantity. """ return self._unit @property def equivalencies(self): """ A list of equivalencies that will be applied by default during unit conversions. """ return self._equivalencies @property def si(self): """ Returns a copy of the current `Quantity` instance with SI units. The value of the resulting object will be scaled. """ si_unit = self.unit.si return self._new_view(self.value * si_unit.scale, si_unit / si_unit.scale) @property def cgs(self): """ Returns a copy of the current `Quantity` instance with CGS units. The value of the resulting object will be scaled. """ cgs_unit = self.unit.cgs return self._new_view(self.value * cgs_unit.scale, cgs_unit / cgs_unit.scale) @property def isscalar(self): """ True if the `value` of this quantity is a scalar, or False if it is an array-like object. .. note:: This is subtly different from `numpy.isscalar` in that `numpy.isscalar` returns False for a zero-dimensional array (e.g. ``np.array(1)``), while this is True for quantities, since quantities cannot represent true numpy scalars. """ return not self.shape # This flag controls whether convenience conversion members, such # as `q.m` equivalent to `q.to_value(u.m)` are available. This is # not turned on on Quantity itself, but is on some subclasses of # Quantity, such as `astropy.coordinates.Angle`. _include_easy_conversion_members = False @override__dir__ def __dir__(self): """ Quantities are able to directly convert to other units that have the same physical type. This function is implemented in order to make autocompletion still work correctly in IPython. """ if not self._include_easy_conversion_members: return [] extra_members = set() equivalencies = Unit._normalize_equivalencies(self.equivalencies) for equivalent in self.unit._get_units_with_same_physical_type( equivalencies): extra_members.update(equivalent.names) return extra_members def __getattr__(self, attr): """ Quantities are able to directly convert to other units that have the same physical type. """ if not self._include_easy_conversion_members: raise AttributeError( "'{0}' object has no '{1}' member".format( self.__class__.__name__, attr)) def get_virtual_unit_attribute(): registry = get_current_unit_registry().registry to_unit = registry.get(attr, None) if to_unit is None: return None try: return self.unit.to( to_unit, self.value, equivalencies=self.equivalencies) except UnitsError: return None value = get_virtual_unit_attribute() if value is None: raise AttributeError( "{0} instance has no attribute '{1}'".format( self.__class__.__name__, attr)) else: return value # Equality (return False if units do not match) needs to be handled # explicitly for numpy >=1.9, since it no longer traps errors. def __eq__(self, other): try: try: return super().__eq__(other) except DeprecationWarning: # We treat the DeprecationWarning separately, since it may # mask another Exception. But we do not want to just use # np.equal, since super's __eq__ treats recarrays correctly. return np.equal(self, other) except UnitsError: return False except TypeError: return NotImplemented def __ne__(self, other): try: try: return super().__ne__(other) except DeprecationWarning: return np.not_equal(self, other) except UnitsError: return True except TypeError: return NotImplemented # Arithmetic operations def __mul__(self, other): """ Multiplication between `Quantity` objects and other objects.""" if isinstance(other, (UnitBase, str)): try: return self._new_view(self.copy(), other * self.unit) except UnitsError: # let other try to deal with it return NotImplemented return super().__mul__(other) def __imul__(self, other): """In-place multiplication between `Quantity` objects and others.""" if isinstance(other, (UnitBase, str)): self._set_unit(other * self.unit) return self return super().__imul__(other) def __rmul__(self, other): """ Right Multiplication between `Quantity` objects and other objects. """ return self.__mul__(other) def __truediv__(self, other): """ Division between `Quantity` objects and other objects.""" if isinstance(other, (UnitBase, str)): try: return self._new_view(self.copy(), self.unit / other) except UnitsError: # let other try to deal with it return NotImplemented return super().__truediv__(other) def __itruediv__(self, other): """Inplace division between `Quantity` objects and other objects.""" if isinstance(other, (UnitBase, str)): self._set_unit(self.unit / other) return self return super().__itruediv__(other) def __rtruediv__(self, other): """ Right Division between `Quantity` objects and other objects.""" if isinstance(other, (UnitBase, str)): return self._new_view(1. / self.value, other / self.unit) return super().__rtruediv__(other) def __div__(self, other): """ Division between `Quantity` objects. """ return self.__truediv__(other) def __idiv__(self, other): """ Division between `Quantity` objects. """ return self.__itruediv__(other) def __rdiv__(self, other): """ Division between `Quantity` objects. """ return self.__rtruediv__(other) if not hasattr(np, 'divmod'): # NUMPY_LT_1_13 # In numpy 1.13, divmod goes via a ufunc and thus works without change. def __divmod__(self, other): other_value = self._to_own_unit(other) result_tuple = divmod(self.value, other_value) return (self._new_view(result_tuple[0], dimensionless_unscaled), self._new_view(result_tuple[1])) def __pow__(self, other): if isinstance(other, Fraction): # Avoid getting object arrays by raising the value to a Fraction. return self._new_view(self.value ** float(other), self.unit ** other) return super().__pow__(other) # For Py>=3.5 def __matmul__(self, other, reverse=False): result_unit = self.unit * getattr(other, 'unit', dimensionless_unscaled) result_array = np.matmul(self.value, getattr(other, 'value', other)) return self._new_view(result_array, result_unit) def __rmatmul__(self, other): result_unit = self.unit * getattr(other, 'unit', dimensionless_unscaled) result_array = np.matmul(getattr(other, 'value', other), self.value) return self._new_view(result_array, result_unit) if NUMPY_LT_1_13: # Pre-numpy 1.13, there was no np.positive ufunc and the copy done # by ndarray did not properly work for scalar quantities. def __pos__(self): """Plus the quantity.""" return self.copy() else: # In numpy 1.13, a np.positive ufunc exists, but ndarray.__pos__ # does not yet go through it, so we still need to define it, to allow # subclasses to override it inside __array_ufunc__. # Presumably, this can eventually be removed. def __pos__(self): """Plus the quantity.""" return np.positive(self) # other overrides of special functions def __hash__(self): return hash(self.value) ^ hash(self.unit) def __iter__(self): if self.isscalar: raise TypeError( "'{cls}' object with a scalar value is not iterable" .format(cls=self.__class__.__name__)) # Otherwise return a generator def quantity_iter(): for val in self.value: yield self._new_view(val) return quantity_iter() def __getitem__(self, key): try: out = super().__getitem__(key) except IndexError: # We want zero-dimensional Quantity objects to behave like scalars, # so they should raise a TypeError rather than an IndexError. if self.isscalar: raise TypeError( "'{cls}' object with a scalar value does not support " "indexing".format(cls=self.__class__.__name__)) else: raise # For single elements, ndarray.__getitem__ returns scalars; these # need a new view as a Quantity. if type(out) is not type(self): out = self._new_view(out) return out def __setitem__(self, i, value): # update indices in info if the info property has been accessed # (in which case 'info' in self.__dict__ is True; this is guaranteed # to be the case if we're part of a table). if not self.isscalar and 'info' in self.__dict__: self.info.adjust_indices(i, value, len(self)) self.view(np.ndarray).__setitem__(i, self._to_own_unit(value)) # __contains__ is OK def __bool__(self): """Quantities should always be treated as non-False; there is too much potential for ambiguity otherwise. """ warnings.warn('The truth value of a Quantity is ambiguous. ' 'In the future this will raise a ValueError.', AstropyDeprecationWarning) return True def __len__(self): if self.isscalar: raise TypeError("'{cls}' object with a scalar value has no " "len()".format(cls=self.__class__.__name__)) else: return len(self.value) # Numerical types def __float__(self): try: return float(self.to_value(dimensionless_unscaled)) except (UnitsError, TypeError): raise TypeError('only dimensionless scalar quantities can be ' 'converted to Python scalars') def __int__(self): try: return int(self.to_value(dimensionless_unscaled)) except (UnitsError, TypeError): raise TypeError('only dimensionless scalar quantities can be ' 'converted to Python scalars') def __index__(self): # for indices, we do not want to mess around with scaling at all, # so unlike for float, int, we insist here on unscaled dimensionless try: assert self.unit.is_unity() return self.value.__index__() except Exception: raise TypeError('only integer dimensionless scalar quantities ' 'can be converted to a Python index') @property def _unitstr(self): if self.unit is None: unitstr = _UNIT_NOT_INITIALISED else: unitstr = str(self.unit) if unitstr: unitstr = ' ' + unitstr return unitstr # Display # TODO: we may want to add a hook for dimensionless quantities? def __str__(self): return '{0}{1:s}'.format(self.value, self._unitstr) def __repr__(self): prefixstr = '<' + self.__class__.__name__ + ' ' sep = ',' if NUMPY_LT_1_14 else ', ' arrstr = np.array2string(self.view(np.ndarray), separator=sep, prefix=prefixstr) return '{0}{1}{2:s}>'.format(prefixstr, arrstr, self._unitstr) def _repr_latex_(self): """ Generate a latex representation of the quantity and its unit. The behavior of this function can be altered via the `numpy.set_printoptions` function and its various keywords. The exception to this is the ``threshold`` keyword, which is controlled via the ``[units.quantity]`` configuration item ``latex_array_threshold``. This is treated separately because the numpy default of 1000 is too big for most browsers to handle. Returns ------- lstr A LaTeX string with the contents of this Quantity """ # need to do try/finally because "threshold" cannot be overridden # with array2string pops = np.get_printoptions() format_spec = '.{}g'.format(pops['precision']) def float_formatter(value): return Latex.format_exponential_notation(value, format_spec=format_spec) try: formatter = {'float_kind': float_formatter} if conf.latex_array_threshold > -1: np.set_printoptions(threshold=conf.latex_array_threshold, formatter=formatter) # the view is needed for the scalar case - value might be float if NUMPY_LT_1_14: # style deprecated in 1.14 latex_value = np.array2string( self.view(np.ndarray), style=(float_formatter if self.dtype.kind == 'f' else repr), max_line_width=np.inf, separator=',~') else: latex_value = np.array2string( self.view(np.ndarray), max_line_width=np.inf, separator=',~') latex_value = latex_value.replace('...', r'\dots') finally: np.set_printoptions(**pops) # Format unit # [1:-1] strips the '$' on either side needed for math mode latex_unit = (self.unit._repr_latex_()[1:-1] # note this is unicode if self.unit is not None else _UNIT_NOT_INITIALISED) return r'${0} \; {1}$'.format(latex_value, latex_unit) def __format__(self, format_spec): """ Format quantities using the new-style python formatting codes as specifiers for the number. If the format specifier correctly applies itself to the value, then it is used to format only the value. If it cannot be applied to the value, then it is applied to the whole string. """ try: value = format(self.value, format_spec) full_format_spec = "s" except ValueError: value = self.value full_format_spec = format_spec return format("{0}{1:s}".format(value, self._unitstr), full_format_spec) def decompose(self, bases=[]): """ Generates a new `Quantity` with the units decomposed. Decomposed units have only irreducible units in them (see `astropy.units.UnitBase.decompose`). Parameters ---------- bases : sequence of UnitBase, optional The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a `~astropy.units.UnitsError` if it's not possible to do so. Returns ------- newq : `~astropy.units.Quantity` A new object equal to this quantity with units decomposed. """ return self._decompose(False, bases=bases) def _decompose(self, allowscaledunits=False, bases=[]): """ Generates a new `Quantity` with the units decomposed. Decomposed units have only irreducible units in them (see `astropy.units.UnitBase.decompose`). Parameters ---------- allowscaledunits : bool If True, the resulting `Quantity` may have a scale factor associated with it. If False, any scaling in the unit will be subsumed into the value of the resulting `Quantity` bases : sequence of UnitBase, optional The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a `~astropy.units.UnitsError` if it's not possible to do so. Returns ------- newq : `~astropy.units.Quantity` A new object equal to this quantity with units decomposed. """ new_unit = self.unit.decompose(bases=bases) # Be careful here because self.value usually is a view of self; # be sure that the original value is not being modified. if not allowscaledunits and hasattr(new_unit, 'scale'): new_value = self.value * new_unit.scale new_unit = new_unit / new_unit.scale return self._new_view(new_value, new_unit) else: return self._new_view(self.copy(), new_unit) # These functions need to be overridden to take into account the units # Array conversion # http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#array-conversion def item(self, *args): return self._new_view(super().item(*args)) def tolist(self): raise NotImplementedError("cannot make a list of Quantities. Get " "list of values with q.value.list()") def _to_own_unit(self, value, check_precision=True): try: _value = value.to_value(self.unit) except AttributeError: # We're not a Quantity, so let's try a more general conversion. # Plain arrays will be converted to dimensionless in the process, # but anything with a unit attribute will use that. try: _value = Quantity(value).to_value(self.unit) except UnitsError as exc: # last chance: if this was not something with a unit # and is all 0, inf, or nan, we treat it as arbitrary unit. if (not hasattr(value, 'unit') and can_have_arbitrary_unit(value)): _value = value else: raise exc if check_precision: value_dtype = getattr(value, 'dtype', None) if self.dtype != value_dtype: self_dtype_array = np.array(_value, self.dtype) value_dtype_array = np.array(_value, dtype=value_dtype, copy=False) if not np.all(np.logical_or(self_dtype_array == value_dtype_array, np.isnan(value_dtype_array))): raise TypeError("cannot convert value type to array type " "without precision loss") return _value def itemset(self, *args): if len(args) == 0: raise ValueError("itemset must have at least one argument") self.view(np.ndarray).itemset(*(args[:-1] + (self._to_own_unit(args[-1]),))) def tostring(self, order='C'): raise NotImplementedError("cannot write Quantities to string. Write " "array with q.value.tostring(...).") def tofile(self, fid, sep="", format="%s"): raise NotImplementedError("cannot write Quantities to file. Write " "array with q.value.tofile(...)") def dump(self, file): raise NotImplementedError("cannot dump Quantities to file. Write " "array with q.value.dump()") def dumps(self): raise NotImplementedError("cannot dump Quantities to string. Write " "array with q.value.dumps()") # astype, byteswap, copy, view, getfield, setflags OK as is def fill(self, value): self.view(np.ndarray).fill(self._to_own_unit(value)) # Shape manipulation: resize cannot be done (does not own data), but # shape, transpose, swapaxes, flatten, ravel, squeeze all OK. Only # the flat iterator needs to be overwritten, otherwise single items are # returned as numbers. @property def flat(self): """A 1-D iterator over the Quantity array. This returns a ``QuantityIterator`` instance, which behaves the same as the `~numpy.flatiter` instance returned by `~numpy.ndarray.flat`, and is similar to, but not a subclass of, Python's built-in iterator object. """ return QuantityIterator(self) @flat.setter def flat(self, value): y = self.ravel() y[:] = value # Item selection and manipulation # take, repeat, sort, compress, diagonal OK def put(self, indices, values, mode='raise'): self.view(np.ndarray).put(indices, self._to_own_unit(values), mode) def choose(self, choices, out=None, mode='raise'): raise NotImplementedError("cannot choose based on quantity. Choose " "using array with q.value.choose(...)") # ensure we do not return indices as quantities def argsort(self, axis=-1, kind='quicksort', order=None): return self.view(np.ndarray).argsort(axis=axis, kind=kind, order=order) def searchsorted(self, v, *args, **kwargs): return np.searchsorted(np.array(self), self._to_own_unit(v, check_precision=False), *args, **kwargs) # avoid numpy 1.6 problem def argmax(self, axis=None, out=None): return self.view(np.ndarray).argmax(axis, out=out) def argmin(self, axis=None, out=None): return self.view(np.ndarray).argmin(axis, out=out) # Calculation -- override ndarray methods to take into account units. # We use the corresponding numpy functions to evaluate the results, since # the methods do not always allow calling with keyword arguments. # For instance, np.array([0.,2.]).clip(a_min=0., a_max=1.) gives # TypeError: 'a_max' is an invalid keyword argument for this function. def _wrap_function(self, function, *args, unit=None, out=None, **kwargs): """Wrap a numpy function that processes self, returning a Quantity. Parameters ---------- function : callable Numpy function to wrap. args : positional arguments Any positional arguments to the function beyond the first argument (which will be set to ``self``). kwargs : keyword arguments Keyword arguments to the function. If present, the following arguments are treated specially: unit : `~astropy.units.Unit` Unit of the output result. If not given, the unit of ``self``. out : `~astropy.units.Quantity` A Quantity instance in which to store the output. Notes ----- Output should always be assigned via a keyword argument, otherwise no proper account of the unit is taken. Returns ------- out : `~astropy.units.Quantity` Result of the function call, with the unit set properly. """ if unit is None: unit = self.unit # Ensure we don't loop back by turning any Quantity into array views. args = (self.value,) + tuple((arg.value if isinstance(arg, Quantity) else arg) for arg in args) if out is not None: # If pre-allocated output is used, check it is suitable. # This also returns array view, to ensure we don't loop back. arrays = tuple(arg for arg in args if isinstance(arg, np.ndarray)) kwargs['out'] = check_output(out, unit, arrays, function=function) # Apply the function and turn it back into a Quantity. result = function(*args, **kwargs) return self._result_as_quantity(result, unit, out) def clip(self, a_min, a_max, out=None): return self._wrap_function(np.clip, self._to_own_unit(a_min), self._to_own_unit(a_max), out=out) def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): return self._wrap_function(np.trace, offset, axis1, axis2, dtype, out=out) 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**2) def std(self, axis=None, dtype=None, out=None, ddof=0): return self._wrap_function(np.std, axis, dtype, out=out, ddof=ddof) def mean(self, axis=None, dtype=None, out=None): return self._wrap_function(np.mean, axis, dtype, out=out) def ptp(self, axis=None, out=None): return self._wrap_function(np.ptp, axis, out=out) def round(self, decimals=0, out=None): return self._wrap_function(np.round, decimals, out=out) def max(self, axis=None, out=None, keepdims=False): return self._wrap_function(np.max, axis, out=out, keepdims=keepdims) def min(self, axis=None, out=None, keepdims=False): return self._wrap_function(np.min, axis, out=out, keepdims=keepdims) def sum(self, axis=None, dtype=None, out=None, keepdims=False): return self._wrap_function(np.sum, axis, dtype, out=out, keepdims=keepdims) def prod(self, axis=None, dtype=None, out=None, keepdims=False): if not self.unit.is_unity(): raise ValueError("cannot use prod on scaled or " "non-dimensionless Quantity arrays") return self._wrap_function(np.prod, axis, dtype, out=out, keepdims=keepdims) def dot(self, b, out=None): result_unit = self.unit * getattr(b, 'unit', dimensionless_unscaled) return self._wrap_function(np.dot, b, out=out, unit=result_unit) def cumsum(self, axis=None, dtype=None, out=None): return self._wrap_function(np.cumsum, axis, dtype, out=out) def cumprod(self, axis=None, dtype=None, out=None): if not self.unit.is_unity(): raise ValueError("cannot use cumprod on scaled or " "non-dimensionless Quantity arrays") return self._wrap_function(np.cumprod, axis, dtype, out=out) # Calculation: override methods that do not make sense. def all(self, axis=None, out=None): raise NotImplementedError("cannot evaluate truth value of quantities. " "Evaluate array with q.value.all(...)") def any(self, axis=None, out=None): raise NotImplementedError("cannot evaluate truth value of quantities. " "Evaluate array with q.value.any(...)") # Calculation: numpy functions that can be overridden with methods. def diff(self, n=1, axis=-1): return self._wrap_function(np.diff, n, axis) def ediff1d(self, to_end=None, to_begin=None): return self._wrap_function(np.ediff1d, to_end, to_begin) def nansum(self, axis=None, out=None, keepdims=False): return self._wrap_function(np.nansum, axis, out=out, keepdims=keepdims) def insert(self, obj, values, axis=None): """ Insert values along the given axis before the given indices and return a new `~astropy.units.Quantity` object. This is a thin wrapper around the `numpy.insert` function. Parameters ---------- obj : int, slice or sequence of ints Object that defines the index or indices before which ``values`` is inserted. values : array-like Values to insert. If the type of ``values`` is different from that of quantity, ``values`` is converted to the matching type. ``values`` should be shaped so that it can be broadcast appropriately The unit of ``values`` must be consistent with this quantity. axis : int, optional Axis along which to insert ``values``. If ``axis`` is None then the quantity array is flattened before insertion. Returns ------- out : `~astropy.units.Quantity` A copy of quantity with ``values`` inserted. Note that the insertion does not occur in-place: a new quantity array is returned. Examples -------- >>> import astropy.units as u >>> q = [1, 2] * u.m >>> q.insert(0, 50 * u.cm) <Quantity [ 0.5, 1., 2.] m> >>> q = [[1, 2], [3, 4]] * u.m >>> q.insert(1, [10, 20] * u.m, axis=0) <Quantity [[ 1., 2.], [ 10., 20.], [ 3., 4.]] m> >>> q.insert(1, 10 * u.m, axis=1) <Quantity [[ 1., 10., 2.], [ 3., 10., 4.]] m> """ out_array = np.insert(self.value, obj, self._to_own_unit(values), axis) return self._new_view(out_array) class SpecificTypeQuantity(Quantity): """Superclass for Quantities of specific physical type. Subclasses of these work just like :class:`~astropy.units.Quantity`, except that they are for specific physical types (and may have methods that are only appropriate for that type). Astropy examples are :class:`~astropy.coordinates.Angle` and :class:`~astropy.coordinates.Distance` At a minimum, subclasses should set ``_equivalent_unit`` to the unit associated with the physical type. """ # The unit for the specific physical type. Instances can only be created # with units that are equivalent to this. _equivalent_unit = None # The default unit used for views. Even with `None`, views of arrays # without units are possible, but will have an uninitalized unit. _unit = None # Default unit for initialization through the constructor. _default_unit = None # ensure that we get precedence over our superclass. __array_priority__ = Quantity.__array_priority__ + 10 def __quantity_subclass__(self, unit): if unit.is_equivalent(self._equivalent_unit): return type(self), True else: return super().__quantity_subclass__(unit)[0], False def _set_unit(self, unit): if unit is None or not unit.is_equivalent(self._equivalent_unit): raise UnitTypeError( "{0} instances require units equivalent to '{1}'" .format(type(self).__name__, self._equivalent_unit) + (", but no unit was given." if unit is None else ", so cannot set it to '{0}'.".format(unit))) super()._set_unit(unit)
a1094edb71bd0130c16b3df31ee6148ba85165dbb06ee16b467627149dc4db06
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines the SI units. They are also available in the `astropy.units` namespace. """ from ..constants import si as _si from .core import UnitBase, Unit, def_unit import numpy as _numpy _ns = globals() ########################################################################### # DIMENSIONLESS def_unit(['percent', 'pct'], Unit(0.01), namespace=_ns, prefixes=False, doc="percent: one hundredth of unity, factor 0.01", format={'generic': '%', 'console': '%', 'cds': '%', 'latex': r'\%', 'unicode': '%'}) ########################################################################### # LENGTH def_unit(['m', 'meter'], namespace=_ns, prefixes=True, doc="meter: base unit of length in SI") def_unit(['micron'], um, namespace=_ns, doc="micron: alias for micrometer (um)", format={'latex': r'\mu m', 'unicode': 'μm'}) def_unit(['Angstrom', 'AA', 'angstrom'], 0.1 * nm, namespace=_ns, doc="ångström: 10 ** -10 m", format={'latex': r'\mathring{A}', 'unicode': 'Å', 'vounit': 'Angstrom'}) ########################################################################### # VOLUMES def_unit((['l', 'L'], ['liter']), 1000 * cm ** 3.0, namespace=_ns, prefixes=True, format={'latex': r'\mathcal{l}', 'unicode': 'ℓ'}, doc="liter: metric unit of volume") ########################################################################### # ANGULAR MEASUREMENTS def_unit(['rad', 'radian'], namespace=_ns, prefixes=True, doc="radian: angular measurement of the ratio between the length " "on an arc and its radius") def_unit(['deg', 'degree'], _numpy.pi / 180.0 * rad, namespace=_ns, prefixes=True, doc="degree: angular measurement 1/360 of full rotation", format={'latex': r'{}^{\circ}', 'unicode': '°'}) def_unit(['hourangle'], 15.0 * deg, namespace=_ns, prefixes=False, doc="hour angle: angular measurement with 24 in a full circle", format={'latex': r'{}^{h}', 'unicode': 'ʰ'}) def_unit(['arcmin', 'arcminute'], 1.0 / 60.0 * deg, namespace=_ns, prefixes=True, doc="arc minute: angular measurement", format={'latex': r'{}^{\prime}', 'unicode': '′'}) def_unit(['arcsec', 'arcsecond'], 1.0 / 3600.0 * deg, namespace=_ns, prefixes=True, doc="arc second: angular measurement") # These special formats should only be used for the non-prefix versions arcsec._format = {'latex': r'{}^{\prime\prime}', 'unicode': '″'} def_unit(['mas'], 0.001 * arcsec, namespace=_ns, doc="milli arc second: angular measurement") def_unit(['uas'], 0.000001 * arcsec, namespace=_ns, doc="micro arc second: angular measurement", format={'latex': r'\mu as', 'unicode': 'μas'}) def_unit(['sr', 'steradian'], rad ** 2, namespace=_ns, prefixes=True, doc="steradian: unit of solid angle in SI") ########################################################################### # TIME def_unit(['s', 'second'], namespace=_ns, prefixes=True, exclude_prefixes=['a'], doc="second: base unit of time in SI.") def_unit(['min', 'minute'], 60 * s, prefixes=True, namespace=_ns) def_unit(['h', 'hour', 'hr'], 3600 * s, namespace=_ns, prefixes=True, exclude_prefixes=['p']) def_unit(['d', 'day'], 24 * h, namespace=_ns, prefixes=True, exclude_prefixes=['c', 'y']) def_unit(['sday'], 86164.09053 * s, namespace=_ns, doc="Sidereal day (sday) is the time of one rotation of the Earth.") def_unit(['wk', 'week'], 7 * day, namespace=_ns) def_unit(['fortnight'], 2 * wk, namespace=_ns) def_unit(['a', 'annum'], 365.25 * d, namespace=_ns, prefixes=True, exclude_prefixes=['P']) def_unit(['yr', 'year'], 365.25 * d, namespace=_ns, prefixes=True) ########################################################################### # FREQUENCY def_unit(['Hz', 'Hertz', 'hertz'], 1 / s, namespace=_ns, prefixes=True, doc="Frequency") ########################################################################### # MASS def_unit(['kg', 'kilogram'], namespace=_ns, doc="kilogram: base unit of mass in SI.") def_unit(['g', 'gram'], 1.0e-3 * kg, namespace=_ns, prefixes=True, exclude_prefixes=['k', 'kilo']) def_unit(['t', 'tonne'], 1000 * kg, namespace=_ns, doc="Metric tonne") ########################################################################### # AMOUNT OF SUBSTANCE def_unit(['mol', 'mole'], namespace=_ns, prefixes=True, doc="mole: amount of a chemical substance in SI.") ########################################################################### # TEMPERATURE def_unit( ['K', 'Kelvin'], namespace=_ns, prefixes=True, doc="Kelvin: temperature with a null point at absolute zero.") def_unit( ['deg_C', 'Celsius'], namespace=_ns, doc='Degrees Celsius', format={'latex': r'{}^{\circ}C', 'unicode': '°C'}) ########################################################################### # FORCE def_unit(['N', 'Newton', 'newton'], kg * m * s ** -2, namespace=_ns, prefixes=True, doc="Newton: force") ########################################################################## # ENERGY def_unit(['J', 'Joule', 'joule'], N * m, namespace=_ns, prefixes=True, doc="Joule: energy") def_unit(['eV', 'electronvolt'], _si.e.value * J, namespace=_ns, prefixes=True, doc="Electron Volt") ########################################################################## # PRESSURE def_unit(['Pa', 'Pascal', 'pascal'], J * m ** -3, namespace=_ns, prefixes=True, doc="Pascal: pressure") def_unit(['bar'], 1e5 * Pa, namespace=_ns, doc="bar: pressure") ########################################################################### # POWER def_unit(['W', 'Watt', 'watt'], J / s, namespace=_ns, prefixes=True, doc="Watt: power") ########################################################################### # ELECTRICAL def_unit(['A', 'ampere', 'amp'], namespace=_ns, prefixes=True, doc="ampere: base unit of electric current in SI") def_unit(['C', 'coulomb'], A * s, namespace=_ns, prefixes=True, doc="coulomb: electric charge") def_unit(['V', 'Volt', 'volt'], J * C ** -1, namespace=_ns, prefixes=True, doc="Volt: electric potential or electromotive force") def_unit((['Ohm', 'ohm'], ['Ohm']), V * A ** -1, namespace=_ns, prefixes=True, doc="Ohm: electrical resistance", format={'latex': r'\Omega', 'unicode': 'Ω'}) def_unit(['S', 'Siemens', 'siemens'], A * V ** -1, namespace=_ns, prefixes=True, doc="Siemens: electrical conductance") def_unit(['F', 'Farad', 'farad'], C * V ** -1, namespace=_ns, prefixes=True, doc="Farad: electrical capacitance") ########################################################################### # MAGNETIC def_unit(['Wb', 'Weber', 'weber'], V * s, namespace=_ns, prefixes=True, doc="Weber: magnetic flux") def_unit(['T', 'Tesla', 'tesla'], Wb * m ** -2, namespace=_ns, prefixes=True, doc="Tesla: magnetic flux density") def_unit(['H', 'Henry', 'henry'], Wb * A ** -1, namespace=_ns, prefixes=True, doc="Henry: inductance") ########################################################################### # ILLUMINATION def_unit(['cd', 'candela'], namespace=_ns, prefixes=True, doc="candela: base unit of luminous intensity in SI") def_unit(['lm', 'lumen'], cd * sr, namespace=_ns, prefixes=True, doc="lumen: luminous flux") def_unit(['lx', 'lux'], lm * m ** -2, namespace=_ns, prefixes=True, doc="lux: luminous emittence") ########################################################################### # RADIOACTIVITY def_unit(['Bq', 'becquerel'], Hz, namespace=_ns, prefixes=False, doc="becquerel: unit of radioactivity") def_unit(['Ci', 'curie'], Bq * 3.7e10, namespace=_ns, prefixes=False, doc="curie: unit of radioactivity") ########################################################################### # BASES bases = set([m, s, kg, A, cd, rad, K, mol]) ########################################################################### # CLEANUP del UnitBase del Unit del def_unit ########################################################################### # 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())
54883c28ada7e386c882b4e18bc6726bf2a8292ccefc473eb7f13af21a71dd35
# Licensed under a 3-clause BSD style license - see LICENSE.rst """A set of standard astronomical equivalencies.""" # THIRD-PARTY import numpy as np import warnings # LOCAL from ..constants import si as _si from . import si from . import cgs from . import astrophys from .function import units as function_units from . import dimensionless_unscaled from .core import UnitsError, Unit __all__ = ['parallax', 'spectral', 'spectral_density', 'doppler_radio', 'doppler_optical', 'doppler_relativistic', 'mass_energy', 'brightness_temperature', 'beam_angular_area', 'dimensionless_angles', 'logarithmic', 'temperature', 'temperature_energy', 'molar_mass_amu', 'pixel_scale', 'plate_scale'] def dimensionless_angles(): """Allow angles to be equivalent to dimensionless (with 1 rad = 1 m/m = 1). It is special compared to other equivalency pairs in that it allows this independent of the power to which the angle is raised, and independent of whether it is part of a more complicated unit. """ return [(si.radian, None)] def logarithmic(): """Allow logarithmic units to be converted to dimensionless fractions""" return [ (dimensionless_unscaled, function_units.dex, np.log10, lambda x: 10.**x) ] def parallax(): """ Returns a list of equivalence pairs that handle the conversion between parallax angle and distance. """ return [ (si.arcsecond, astrophys.parsec, lambda x: 1. / x) ] def spectral(): """ Returns a list of equivalence pairs that handle spectral wavelength, wave number, frequency, and energy equivalences. Allows conversions between wavelength units, wave number units, frequency units, and energy units as they relate to light. There are two types of wave number: * spectroscopic - :math:`1 / \\lambda` (per meter) * angular - :math:`2 \\pi / \\lambda` (radian per meter) """ hc = _si.h.value * _si.c.value two_pi = 2.0 * np.pi inv_m_spec = si.m ** -1 inv_m_ang = si.radian / si.m return [ (si.m, si.Hz, lambda x: _si.c.value / x), (si.m, si.J, lambda x: hc / x), (si.Hz, si.J, lambda x: _si.h.value * x, lambda x: x / _si.h.value), (si.m, inv_m_spec, lambda x: 1.0 / x), (si.Hz, inv_m_spec, lambda x: x / _si.c.value, lambda x: _si.c.value * x), (si.J, inv_m_spec, lambda x: x / hc, lambda x: hc * x), (inv_m_spec, inv_m_ang, lambda x: x * two_pi, lambda x: x / two_pi), (si.m, inv_m_ang, lambda x: two_pi / x), (si.Hz, inv_m_ang, lambda x: two_pi * x / _si.c.value, lambda x: _si.c.value * x / two_pi), (si.J, inv_m_ang, lambda x: x * two_pi / hc, lambda x: hc * x / two_pi) ] def spectral_density(wav, factor=None): """ Returns a list of equivalence pairs that handle spectral density with regard to wavelength and frequency. Parameters ---------- wav : `~astropy.units.Quantity` `~astropy.units.Quantity` associated with values being converted (e.g., wavelength or frequency). Notes ----- The ``factor`` argument is left for backward-compatibility with the syntax ``spectral_density(unit, factor)`` but users are encouraged to use ``spectral_density(factor * unit)`` instead. """ from .core import UnitBase if isinstance(wav, UnitBase): if factor is None: raise ValueError( 'If `wav` is specified as a unit, `factor` should be set') wav = factor * wav # Convert to Quantity c_Aps = _si.c.to_value(si.AA / si.s) # Angstrom/s h_cgs = _si.h.cgs.value # erg * s hc = c_Aps * h_cgs # flux density f_la = cgs.erg / si.angstrom / si.cm ** 2 / si.s f_nu = cgs.erg / si.Hz / si.cm ** 2 / si.s nu_f_nu = cgs.erg / si.cm ** 2 / si.s la_f_la = nu_f_nu phot_f_la = astrophys.photon / (si.cm ** 2 * si.s * si.AA) phot_f_nu = astrophys.photon / (si.cm ** 2 * si.s * si.Hz) # luminosity density L_nu = cgs.erg / si.s / si.Hz L_la = cgs.erg / si.s / si.angstrom nu_L_nu = cgs.erg / si.s la_L_la = nu_L_nu phot_L_la = astrophys.photon / (si.s * si.AA) phot_L_nu = astrophys.photon / (si.s * si.Hz) def converter(x): return x * (wav.to_value(si.AA, spectral()) ** 2 / c_Aps) def iconverter(x): return x / (wav.to_value(si.AA, spectral()) ** 2 / c_Aps) def converter_f_nu_to_nu_f_nu(x): return x * wav.to_value(si.Hz, spectral()) def iconverter_f_nu_to_nu_f_nu(x): return x / wav.to_value(si.Hz, spectral()) def converter_f_la_to_la_f_la(x): return x * wav.to_value(si.AA, spectral()) def iconverter_f_la_to_la_f_la(x): return x / wav.to_value(si.AA, spectral()) def converter_phot_f_la_to_f_la(x): return hc * x / wav.to_value(si.AA, spectral()) def iconverter_phot_f_la_to_f_la(x): return x * wav.to_value(si.AA, spectral()) / hc def converter_phot_f_la_to_f_nu(x): return h_cgs * x * wav.to_value(si.AA, spectral()) def iconverter_phot_f_la_to_f_nu(x): return x / (wav.to_value(si.AA, spectral()) * h_cgs) def converter_phot_f_la_phot_f_nu(x): return x * wav.to_value(si.AA, spectral()) ** 2 / c_Aps def iconverter_phot_f_la_phot_f_nu(x): return c_Aps * x / wav.to_value(si.AA, spectral()) ** 2 converter_phot_f_nu_to_f_nu = converter_phot_f_la_to_f_la iconverter_phot_f_nu_to_f_nu = iconverter_phot_f_la_to_f_la def converter_phot_f_nu_to_f_la(x): return x * hc * c_Aps / wav.to_value(si.AA, spectral()) ** 3 def iconverter_phot_f_nu_to_f_la(x): return x * wav.to_value(si.AA, spectral()) ** 3 / (hc * c_Aps) # for luminosity density converter_L_nu_to_nu_L_nu = converter_f_nu_to_nu_f_nu iconverter_L_nu_to_nu_L_nu = iconverter_f_nu_to_nu_f_nu converter_L_la_to_la_L_la = converter_f_la_to_la_f_la iconverter_L_la_to_la_L_la = iconverter_f_la_to_la_f_la converter_phot_L_la_to_L_la = converter_phot_f_la_to_f_la iconverter_phot_L_la_to_L_la = iconverter_phot_f_la_to_f_la converter_phot_L_la_to_L_nu = converter_phot_f_la_to_f_nu iconverter_phot_L_la_to_L_nu = iconverter_phot_f_la_to_f_nu converter_phot_L_la_phot_L_nu = converter_phot_f_la_phot_f_nu iconverter_phot_L_la_phot_L_nu = iconverter_phot_f_la_phot_f_nu converter_phot_L_nu_to_L_nu = converter_phot_f_nu_to_f_nu iconverter_phot_L_nu_to_L_nu = iconverter_phot_f_nu_to_f_nu converter_phot_L_nu_to_L_la = converter_phot_f_nu_to_f_la iconverter_phot_L_nu_to_L_la = iconverter_phot_f_nu_to_f_la return [ # flux (f_la, f_nu, converter, iconverter), (f_nu, nu_f_nu, converter_f_nu_to_nu_f_nu, iconverter_f_nu_to_nu_f_nu), (f_la, la_f_la, converter_f_la_to_la_f_la, iconverter_f_la_to_la_f_la), (phot_f_la, f_la, converter_phot_f_la_to_f_la, iconverter_phot_f_la_to_f_la), (phot_f_la, f_nu, converter_phot_f_la_to_f_nu, iconverter_phot_f_la_to_f_nu), (phot_f_la, phot_f_nu, converter_phot_f_la_phot_f_nu, iconverter_phot_f_la_phot_f_nu), (phot_f_nu, f_nu, converter_phot_f_nu_to_f_nu, iconverter_phot_f_nu_to_f_nu), (phot_f_nu, f_la, converter_phot_f_nu_to_f_la, iconverter_phot_f_nu_to_f_la), # luminosity (L_la, L_nu, converter, iconverter), (L_nu, nu_L_nu, converter_L_nu_to_nu_L_nu, iconverter_L_nu_to_nu_L_nu), (L_la, la_L_la, converter_L_la_to_la_L_la, iconverter_L_la_to_la_L_la), (phot_L_la, L_la, converter_phot_L_la_to_L_la, iconverter_phot_L_la_to_L_la), (phot_L_la, L_nu, converter_phot_L_la_to_L_nu, iconverter_phot_L_la_to_L_nu), (phot_L_la, phot_L_nu, converter_phot_L_la_phot_L_nu, iconverter_phot_L_la_phot_L_nu), (phot_L_nu, L_nu, converter_phot_L_nu_to_L_nu, iconverter_phot_L_nu_to_L_nu), (phot_L_nu, L_la, converter_phot_L_nu_to_L_la, iconverter_phot_L_nu_to_L_la), ] def doppler_radio(rest): r""" Return the equivalency pairs for the radio convention for velocity. The radio convention for the relation between velocity and frequency is: :math:`V = c \frac{f_0 - f}{f_0} ; f(V) = f_0 ( 1 - V/c )` Parameters ---------- rest : `~astropy.units.Quantity` Any quantity supported by the standard spectral equivalencies (wavelength, energy, frequency, wave number). References ---------- `NRAO site defining the conventions <http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html>`_ Examples -------- >>> import astropy.units as u >>> CO_restfreq = 115.27120*u.GHz # rest frequency of 12 CO 1-0 in GHz >>> radio_CO_equiv = u.doppler_radio(CO_restfreq) >>> measured_freq = 115.2832*u.GHz >>> radio_velocity = measured_freq.to(u.km/u.s, equivalencies=radio_CO_equiv) >>> radio_velocity # doctest: +FLOAT_CMP <Quantity -31.209092088877583 km / s> """ assert_is_spectral_unit(rest) ckms = _si.c.to_value('km/s') def to_vel_freq(x): restfreq = rest.to_value(si.Hz, equivalencies=spectral()) return (restfreq-x) / (restfreq) * ckms def from_vel_freq(x): restfreq = rest.to_value(si.Hz, equivalencies=spectral()) voverc = x/ckms return restfreq * (1-voverc) def to_vel_wav(x): restwav = rest.to_value(si.AA, spectral()) return (x-restwav) / (x) * ckms def from_vel_wav(x): restwav = rest.to_value(si.AA, spectral()) return restwav * ckms / (ckms-x) def to_vel_en(x): resten = rest.to_value(si.eV, equivalencies=spectral()) return (resten-x) / (resten) * ckms def from_vel_en(x): resten = rest.to_value(si.eV, equivalencies=spectral()) voverc = x/ckms return resten * (1-voverc) return [(si.Hz, si.km/si.s, to_vel_freq, from_vel_freq), (si.AA, si.km/si.s, to_vel_wav, from_vel_wav), (si.eV, si.km/si.s, to_vel_en, from_vel_en), ] def doppler_optical(rest): r""" Return the equivalency pairs for the optical convention for velocity. The optical convention for the relation between velocity and frequency is: :math:`V = c \frac{f_0 - f}{f } ; f(V) = f_0 ( 1 + V/c )^{-1}` Parameters ---------- rest : `~astropy.units.Quantity` Any quantity supported by the standard spectral equivalencies (wavelength, energy, frequency, wave number). References ---------- `NRAO site defining the conventions <http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html>`_ Examples -------- >>> import astropy.units as u >>> CO_restfreq = 115.27120*u.GHz # rest frequency of 12 CO 1-0 in GHz >>> optical_CO_equiv = u.doppler_optical(CO_restfreq) >>> measured_freq = 115.2832*u.GHz >>> optical_velocity = measured_freq.to(u.km/u.s, equivalencies=optical_CO_equiv) >>> optical_velocity # doctest: +FLOAT_CMP <Quantity -31.20584348799674 km / s> """ assert_is_spectral_unit(rest) ckms = _si.c.to_value('km/s') def to_vel_freq(x): restfreq = rest.to_value(si.Hz, equivalencies=spectral()) return ckms * (restfreq-x) / x def from_vel_freq(x): restfreq = rest.to_value(si.Hz, equivalencies=spectral()) voverc = x/ckms return restfreq / (1+voverc) def to_vel_wav(x): restwav = rest.to_value(si.AA, spectral()) return ckms * (x/restwav-1) def from_vel_wav(x): restwav = rest.to_value(si.AA, spectral()) voverc = x/ckms return restwav * (1+voverc) def to_vel_en(x): resten = rest.to_value(si.eV, equivalencies=spectral()) return ckms * (resten-x) / x def from_vel_en(x): resten = rest.to_value(si.eV, equivalencies=spectral()) voverc = x/ckms return resten / (1+voverc) return [(si.Hz, si.km/si.s, to_vel_freq, from_vel_freq), (si.AA, si.km/si.s, to_vel_wav, from_vel_wav), (si.eV, si.km/si.s, to_vel_en, from_vel_en), ] def doppler_relativistic(rest): r""" Return the equivalency pairs for the relativistic convention for velocity. The full relativistic convention for the relation between velocity and frequency is: :math:`V = c \frac{f_0^2 - f^2}{f_0^2 + f^2} ; f(V) = f_0 \frac{\left(1 - (V/c)^2\right)^{1/2}}{(1+V/c)}` Parameters ---------- rest : `~astropy.units.Quantity` Any quantity supported by the standard spectral equivalencies (wavelength, energy, frequency, wave number). References ---------- `NRAO site defining the conventions <http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html>`_ Examples -------- >>> import astropy.units as u >>> CO_restfreq = 115.27120*u.GHz # rest frequency of 12 CO 1-0 in GHz >>> relativistic_CO_equiv = u.doppler_relativistic(CO_restfreq) >>> measured_freq = 115.2832*u.GHz >>> relativistic_velocity = measured_freq.to(u.km/u.s, equivalencies=relativistic_CO_equiv) >>> relativistic_velocity # doctest: +FLOAT_CMP <Quantity -31.207467619351537 km / s> >>> measured_velocity = 1250 * u.km/u.s >>> relativistic_frequency = measured_velocity.to(u.GHz, equivalencies=relativistic_CO_equiv) >>> relativistic_frequency # doctest: +FLOAT_CMP <Quantity 114.79156866993588 GHz> >>> relativistic_wavelength = measured_velocity.to(u.mm, equivalencies=relativistic_CO_equiv) >>> relativistic_wavelength # doctest: +FLOAT_CMP <Quantity 2.6116243681798923 mm> """ assert_is_spectral_unit(rest) ckms = _si.c.to_value('km/s') def to_vel_freq(x): restfreq = rest.to_value(si.Hz, equivalencies=spectral()) return (restfreq**2-x**2) / (restfreq**2+x**2) * ckms def from_vel_freq(x): restfreq = rest.to_value(si.Hz, equivalencies=spectral()) voverc = x/ckms return restfreq * ((1-voverc) / (1+(voverc)))**0.5 def to_vel_wav(x): restwav = rest.to_value(si.AA, spectral()) return (x**2-restwav**2) / (restwav**2+x**2) * ckms def from_vel_wav(x): restwav = rest.to_value(si.AA, spectral()) voverc = x/ckms return restwav * ((1+voverc) / (1-voverc))**0.5 def to_vel_en(x): resten = rest.to_value(si.eV, spectral()) return (resten**2-x**2) / (resten**2+x**2) * ckms def from_vel_en(x): resten = rest.to_value(si.eV, spectral()) voverc = x/ckms return resten * ((1-voverc) / (1+(voverc)))**0.5 return [(si.Hz, si.km/si.s, to_vel_freq, from_vel_freq), (si.AA, si.km/si.s, to_vel_wav, from_vel_wav), (si.eV, si.km/si.s, to_vel_en, from_vel_en), ] def molar_mass_amu(): """ Returns the equivalence between amu and molar mass. """ return [ (si.g/si.mol, astrophys.u) ] def mass_energy(): """ Returns a list of equivalence pairs that handle the conversion between mass and energy. """ return [(si.kg, si.J, lambda x: x * _si.c.value ** 2, lambda x: x / _si.c.value ** 2), (si.kg / si.m ** 2, si.J / si.m ** 2, lambda x: x * _si.c.value ** 2, lambda x: x / _si.c.value ** 2), (si.kg / si.m ** 3, si.J / si.m ** 3, lambda x: x * _si.c.value ** 2, lambda x: x / _si.c.value ** 2), (si.kg / si.s, si.J / si.s, lambda x: x * _si.c.value ** 2, lambda x: x / _si.c.value ** 2), ] def brightness_temperature(frequency, beam_area=None): r""" Defines the conversion between Jy/sr and "brightness temperature", :math:`T_B`, in Kelvins. The brightness temperature is a unit very commonly used in radio astronomy. See, e.g., "Tools of Radio Astronomy" (Wilson 2009) eqn 8.16 and eqn 8.19 (these pages are available on `google books <http://books.google.com/books?id=9KHw6R8rQEMC&pg=PA179&source=gbs_toc_r&cad=4#v=onepage&q&f=false>`__). :math:`T_B \equiv S_\nu / \left(2 k \nu^2 / c^2 \right)` If the input is in Jy/beam or Jy (assuming it came from a single beam), the beam area is essential for this computation: the brightness temperature is inversely proportional to the beam area. Parameters ---------- frequency : `~astropy.units.Quantity` with spectral units The observed ``spectral`` equivalent `~astropy.units.Unit` (e.g., frequency or wavelength). The variable is named 'frequency' because it is more commonly used in radio astronomy. BACKWARD COMPATIBILITY NOTE: previous versions of the brightness temperature equivalency used the keyword ``disp``, which is no longer supported. beam_area : angular area equivalent Beam area in angular units, i.e. steradian equivalent Examples -------- Arecibo C-band beam:: >>> import numpy as np >>> from astropy import units as u >>> beam_sigma = 50*u.arcsec >>> beam_area = 2*np.pi*(beam_sigma)**2 >>> freq = 5*u.GHz >>> equiv = u.brightness_temperature(freq) >>> (1*u.Jy/beam_area).to(u.K, equivalencies=equiv) # doctest: +FLOAT_CMP <Quantity 3.526295144567176 K> VLA synthetic beam:: >>> bmaj = 15*u.arcsec >>> bmin = 15*u.arcsec >>> fwhm_to_sigma = 1./(8*np.log(2))**0.5 >>> beam_area = 2.*np.pi*(bmaj*bmin*fwhm_to_sigma**2) >>> freq = 5*u.GHz >>> equiv = u.brightness_temperature(freq) >>> (u.Jy/beam_area).to(u.K, equivalencies=equiv) # doctest: +FLOAT_CMP <Quantity 217.2658703625732 K> Any generic surface brightness: >>> surf_brightness = 1e6*u.MJy/u.sr >>> surf_brightness.to(u.K, equivalencies=u.brightness_temperature(500*u.GHz)) # doctest: +FLOAT_CMP <Quantity 130.1931904778803 K> """ if frequency.unit.is_equivalent(si.sr): if not beam_area.unit.is_equivalent(si.Hz): raise ValueError("The inputs to `brightness_temperature` are " "frequency and angular area.") warnings.warn("The inputs to `brightness_temperature` have changed. " "Frequency is now the first input, and angular area " "is the second, optional input.", DeprecationWarning) frequency, beam_area = beam_area, frequency nu = frequency.to(si.GHz, spectral()) if beam_area is not None: beam = beam_area.to_value(si.sr) def convert_Jy_to_K(x_jybm): factor = (2 * _si.k_B * si.K * nu**2 / _si.c**2).to(astrophys.Jy).value return (x_jybm / beam / factor) def convert_K_to_Jy(x_K): factor = (astrophys.Jy / (2 * _si.k_B * nu**2 / _si.c**2)).to(si.K).value return (x_K * beam / factor) return [(astrophys.Jy, si.K, convert_Jy_to_K, convert_K_to_Jy), (astrophys.Jy/astrophys.beam, si.K, convert_Jy_to_K, convert_K_to_Jy) ] else: def convert_JySr_to_K(x_jysr): factor = (2 * _si.k_B * si.K * nu**2 / _si.c**2).to(astrophys.Jy).value return (x_jysr / factor) def convert_K_to_JySr(x_K): factor = (astrophys.Jy / (2 * _si.k_B * nu**2 / _si.c**2)).to(si.K).value return (x_K / factor) # multiplied by 1x for 1 steradian return [(astrophys.Jy/si.sr, si.K, convert_JySr_to_K, convert_K_to_JySr)] def beam_angular_area(beam_area): """ Convert between the ``beam`` unit, which is commonly used to express the area of a radio telescope resolution element, and an area on the sky. This equivalency also supports direct conversion between ``Jy/beam`` and ``Jy/steradian`` units, since that is a common operation. Parameters ---------- beam_area : angular area equivalent The area of the beam in angular area units (e.g., steradians) """ return [(astrophys.beam, Unit(beam_area)), (astrophys.beam**-1, Unit(beam_area)**-1), (astrophys.Jy/astrophys.beam, astrophys.Jy/Unit(beam_area)), ] def temperature(): """Convert between Kelvin, Celsius, and Fahrenheit here because Unit and CompositeUnit cannot do addition or subtraction properly. """ from .imperial import deg_F return [ (si.K, si.deg_C, lambda x: x - 273.15, lambda x: x + 273.15), (si.deg_C, deg_F, lambda x: x * 1.8 + 32.0, lambda x: (x - 32.0) / 1.8), (si.K, deg_F, lambda x: (x - 273.15) * 1.8 + 32.0, lambda x: ((x - 32.0) / 1.8) + 273.15)] def temperature_energy(): """Convert between Kelvin and keV(eV) to an equivalent amount.""" return [ (si.K, si.eV, lambda x: x / (_si.e.value / _si.k_B.value), lambda x: x * (_si.e.value / _si.k_B.value))] def assert_is_spectral_unit(value): try: value.to(si.Hz, spectral()) except (AttributeError, UnitsError) as ex: raise UnitsError("The 'rest' value must be a spectral equivalent " "(frequency, wavelength, or energy).") def pixel_scale(pixscale): """ Convert between pixel distances (in units of ``pix``) and angular units, given a particular ``pixscale``. Parameters ---------- pixscale : `~astropy.units.Quantity` The pixel scale either in units of angle/pixel or pixel/angle. """ if pixscale.unit.is_equivalent(si.arcsec/astrophys.pix): pixscale_val = pixscale.to_value(si.radian/astrophys.pix) elif pixscale.unit.is_equivalent(astrophys.pix/si.arcsec): pixscale_val = (1/pixscale).to_value(si.radian/astrophys.pix) else: raise UnitsError("The pixel scale must be in angle/pixel or " "pixel/angle") return [(astrophys.pix, si.radian, lambda px: px*pixscale_val, lambda rad: rad/pixscale_val)] def plate_scale(platescale): """ Convert between lengths (to be interpreted as lengths in the focal plane) and angular units with a specified ``platescale``. Parameters ---------- platescale : `~astropy.units.Quantity` The pixel scale either in units of distance/pixel or distance/angle. """ if platescale.unit.is_equivalent(si.arcsec/si.m): platescale_val = platescale.to_value(si.radian/si.m) elif platescale.unit.is_equivalent(si.m/si.arcsec): platescale_val = (1/platescale).to_value(si.radian/si.m) else: raise UnitsError("The pixel scale must be in angle/distance or " "distance/angle") return [(si.m, si.radian, lambda d: d*platescale_val, lambda rad: rad/platescale_val)]
48921bf628672772221f1eca1d7ef60f1adbd10d05570acc3585cea35228e72a
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains convenience functions for retrieving solar system ephemerides from jplephem. """ from urllib.parse import urlparse from collections import OrderedDict import numpy as np from .sky_coordinate import SkyCoord from ..utils.data import download_file from ..utils.decorators import classproperty from ..utils.state import ScienceState from ..utils import indent from .. import units as u from .. import _erfa as erfa from ..constants import c as speed_of_light from .representation import CartesianRepresentation from .orbital_elements import calc_moon from .builtin_frames import GCRS, ICRS from .builtin_frames.utils import get_jd12 __all__ = ["get_body", "get_moon", "get_body_barycentric", "get_body_barycentric_posvel", "solar_system_ephemeris"] DEFAULT_JPL_EPHEMERIS = 'de430' """List of kernel pairs needed to calculate positions of a given object.""" BODY_NAME_TO_KERNEL_SPEC = OrderedDict( (('sun', [(0, 10)]), ('mercury', [(0, 1), (1, 199)]), ('venus', [(0, 2), (2, 299)]), ('earth-moon-barycenter', [(0, 3)]), ('earth', [(0, 3), (3, 399)]), ('moon', [(0, 3), (3, 301)]), ('mars', [(0, 4)]), ('jupiter', [(0, 5)]), ('saturn', [(0, 6)]), ('uranus', [(0, 7)]), ('neptune', [(0, 8)]), ('pluto', [(0, 9)])) ) """Indices to the plan94 routine for the given object.""" PLAN94_BODY_NAME_TO_PLANET_INDEX = OrderedDict( (('mercury', 1), ('venus', 2), ('earth-moon-barycenter', 3), ('mars', 4), ('jupiter', 5), ('saturn', 6), ('uranus', 7), ('neptune', 8))) _EPHEMERIS_NOTE = """ You can either give an explicit ephemeris or use a default, which is normally a built-in ephemeris that does not require ephemeris files. To change the default to be the JPL ephemeris:: >>> from astropy.coordinates import solar_system_ephemeris >>> solar_system_ephemeris.set('jpl') # doctest: +SKIP Use of any JPL ephemeris requires the jplephem package (https://pypi.python.org/pypi/jplephem). If needed, the ephemeris file will be downloaded (and cached). One can check which bodies are covered by a given ephemeris using:: >>> solar_system_ephemeris.bodies ('earth', 'sun', 'moon', 'mercury', 'venus', 'earth-moon-barycenter', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune') """[1:-1] class solar_system_ephemeris(ScienceState): """Default ephemerides for calculating positions of Solar-System bodies. This can be one of the following:: - 'builtin': polynomial approximations to the orbital elements. - 'de430' or 'de432s': short-cuts for recent JPL dynamical models. - 'jpl': Alias for the default JPL ephemeris (currently, 'de430'). - URL: (str) The url to a SPK ephemeris in SPICE binary (.bsp) format. - `None`: Ensure an Exception is raised without an explicit ephemeris. The default is 'builtin', which uses the ``epv00`` and ``plan94`` routines from the ``erfa`` implementation of the Standards Of Fundamental Astronomy library. Notes ----- Any file required will be downloaded (and cached) when the state is set. The default Satellite Planet Kernel (SPK) file from NASA JPL (de430) is ~120MB, and covers years ~1550-2650 CE [1]_. The smaller de432s file is ~10MB, and covers years 1950-2050 [2]_. Older versions of the JPL ephemerides (such as the widely used de200) can be used via their URL [3]_. .. [1] http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/aareadme_de430-de431.txt .. [2] http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/aareadme_de432s.txt .. [3] http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/a_old_versions/ """ _value = 'builtin' _kernel = None @classmethod def validate(cls, value): # make no changes if value is None if value is None: return cls._value # Set up Kernel; if the file is not in cache, this will download it. cls.get_kernel(value) return value @classmethod def get_kernel(cls, value): # ScienceState only ensures the `_value` attribute is up to date, # so we need to be sure any kernel returned is consistent. if cls._kernel is None or cls._kernel.origin != value: if cls._kernel is not None: cls._kernel.daf.file.close() cls._kernel = None kernel = _get_kernel(value) if kernel is not None: kernel.origin = value cls._kernel = kernel return cls._kernel @classproperty def kernel(cls): return cls.get_kernel(cls._value) @classproperty def bodies(cls): if cls._value is None: return None if cls._value.lower() == 'builtin': return (('earth', 'sun', 'moon') + tuple(PLAN94_BODY_NAME_TO_PLANET_INDEX.keys())) else: return tuple(BODY_NAME_TO_KERNEL_SPEC.keys()) def _get_kernel(value): """ Try importing jplephem, download/retrieve from cache the Satellite Planet Kernel corresponding to the given ephemeris. """ if value is None or value.lower() == 'builtin': return None if value.lower() == 'jpl': value = DEFAULT_JPL_EPHEMERIS if value.lower() in ('de430', 'de432s'): value = ('http://naif.jpl.nasa.gov/pub/naif/generic_kernels' '/spk/planets/{:s}.bsp'.format(value.lower())) else: try: urlparse(value) except Exception: raise ValueError('{} was not one of the standard strings and ' 'could not be parsed as a URL'.format(value)) try: from jplephem.spk import SPK except ImportError: raise ImportError("Solar system JPL ephemeris calculations require " "the jplephem package " "(https://pypi.python.org/pypi/jplephem)") return SPK.open(download_file(value, cache=True)) def _get_body_barycentric_posvel(body, time, ephemeris=None, get_velocity=True): """Calculate the barycentric position (and velocity) of a solar system body. Parameters ---------- body : str or other The solar system body for which to calculate positions. Can also be a kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL kernel. time : `~astropy.time.Time` Time of observation. ephemeris : str, optional Ephemeris to use. By default, use the one set with ``astropy.coordinates.solar_system_ephemeris.set`` get_velocity : bool, optional Whether or not to calculate the velocity as well as the position. Returns ------- position : `~astropy.coordinates.CartesianRepresentation` or tuple Barycentric (ICRS) position or tuple of position and velocity. Notes ----- No velocity can be calculated with the built-in ephemeris for the Moon. Whether or not velocities are calculated makes little difference for the built-in ephemerides, but for most JPL ephemeris files, the execution time roughly doubles. """ if ephemeris is None: ephemeris = solar_system_ephemeris.get() if ephemeris is None: raise ValueError(_EPHEMERIS_NOTE) kernel = solar_system_ephemeris.kernel else: kernel = _get_kernel(ephemeris) jd1, jd2 = get_jd12(time, 'tdb') if kernel is None: body = body.lower() earth_pv_helio, earth_pv_bary = erfa.epv00(jd1, jd2) if body == 'earth': body_pv_bary = earth_pv_bary elif body == 'moon': if get_velocity: raise KeyError("the Moon's velocity cannot be calculated with " "the '{0}' ephemeris.".format(ephemeris)) return calc_moon(time).cartesian else: sun_pv_bary = earth_pv_bary - earth_pv_helio if body == 'sun': body_pv_bary = sun_pv_bary else: try: body_index = PLAN94_BODY_NAME_TO_PLANET_INDEX[body] except KeyError: raise KeyError("{0}'s position and velocity cannot be " "calculated with the '{1}' ephemeris." .format(body, ephemeris)) body_pv_helio = erfa.plan94(jd1, jd2, body_index) body_pv_bary = body_pv_helio + sun_pv_bary body_pos_bary = CartesianRepresentation( body_pv_bary[..., 0, :], unit=u.au, xyz_axis=-1, copy=False) if get_velocity: body_vel_bary = CartesianRepresentation( body_pv_bary[..., 1, :], unit=u.au/u.day, xyz_axis=-1, copy=False) else: if isinstance(body, str): # Look up kernel chain for JPL ephemeris, based on name try: kernel_spec = BODY_NAME_TO_KERNEL_SPEC[body.lower()] except KeyError: raise KeyError("{0}'s position cannot be calculated with " "the {1} ephemeris.".format(body, ephemeris)) else: # otherwise, assume the user knows what their doing and intentionally # passed in a kernel chain kernel_spec = body # jplephem cannot handle multi-D arrays, so convert to 1D here. jd1_shape = getattr(jd1, 'shape', ()) if len(jd1_shape) > 1: jd1, jd2 = jd1.ravel(), jd2.ravel() # Note that we use the new jd1.shape here to create a 1D result array. # It is reshaped below. body_posvel_bary = np.zeros((2 if get_velocity else 1, 3) + getattr(jd1, 'shape', ())) for pair in kernel_spec: spk = kernel[pair] if spk.data_type == 3: # Type 3 kernels contain both position and velocity. posvel = spk.compute(jd1, jd2) if get_velocity: body_posvel_bary += posvel.reshape(body_posvel_bary.shape) else: body_posvel_bary[0] += posvel[:4] else: # spk.generate first yields the position and then the # derivative. If no velocities are desired, body_posvel_bary # has only one element and thus the loop ends after a single # iteration, avoiding the velocity calculation. for body_p_or_v, p_or_v in zip(body_posvel_bary, spk.generate(jd1, jd2)): body_p_or_v += p_or_v body_posvel_bary.shape = body_posvel_bary.shape[:2] + jd1_shape body_pos_bary = CartesianRepresentation(body_posvel_bary[0], unit=u.km, copy=False) if get_velocity: body_vel_bary = CartesianRepresentation(body_posvel_bary[1], unit=u.km/u.day, copy=False) return (body_pos_bary, body_vel_bary) if get_velocity else body_pos_bary def get_body_barycentric_posvel(body, time, ephemeris=None): """Calculate the barycentric position and velocity of a solar system body. Parameters ---------- body : str or other The solar system body for which to calculate positions. Can also be a kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL kernel. time : `~astropy.time.Time` Time of observation. ephemeris : str, optional Ephemeris to use. By default, use the one set with ``astropy.coordinates.solar_system_ephemeris.set`` Returns ------- position, velocity : tuple of `~astropy.coordinates.CartesianRepresentation` Tuple of barycentric (ICRS) position and velocity. See also -------- get_body_barycentric : to calculate position only. This is faster by about a factor two for JPL kernels, but has no speed advantage for the built-in ephemeris. Notes ----- The velocity cannot be calculated for the Moon. To just get the position, use :func:`~astropy.coordinates.get_body_barycentric`. """ return _get_body_barycentric_posvel(body, time, ephemeris) get_body_barycentric_posvel.__doc__ += indent(_EPHEMERIS_NOTE)[4:] def get_body_barycentric(body, time, ephemeris=None): """Calculate the barycentric position of a solar system body. Parameters ---------- body : str or other The solar system body for which to calculate positions. Can also be a kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL kernel. time : `~astropy.time.Time` Time of observation. ephemeris : str, optional Ephemeris to use. By default, use the one set with ``astropy.coordinates.solar_system_ephemeris.set`` Returns ------- position : `~astropy.coordinates.CartesianRepresentation` Barycentric (ICRS) position of the body in cartesian coordinates See also -------- get_body_barycentric_posvel : to calculate both position and velocity. Notes ----- """ return _get_body_barycentric_posvel(body, time, ephemeris, get_velocity=False) get_body_barycentric.__doc__ += indent(_EPHEMERIS_NOTE)[4:] def _get_apparent_body_position(body, time, ephemeris): """Calculate the apparent position of body ``body`` relative to Earth. This corrects for the light-travel time to the object. Parameters ---------- body : str or other The solar system body for which to calculate positions. Can also be a kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL kernel. time : `~astropy.time.Time` Time of observation. ephemeris : str, optional Ephemeris to use. By default, use the one set with ``~astropy.coordinates.solar_system_ephemeris.set`` Returns ------- cartesian_position : `~astropy.coordinates.CartesianRepresentation` Barycentric (ICRS) apparent position of the body in cartesian coordinates """ if ephemeris is None: ephemeris = solar_system_ephemeris.get() # builtin ephemeris and moon is a special case, with no need to account for # light travel time, since this is already included in the Meeus algorithm # used. if ephemeris == 'builtin' and body.lower() == 'moon': return get_body_barycentric(body, time, ephemeris) # Calculate position given approximate light travel time. delta_light_travel_time = 20. * u.s emitted_time = time light_travel_time = 0. * u.s earth_loc = get_body_barycentric('earth', time, ephemeris) while np.any(np.fabs(delta_light_travel_time) > 1.0e-8*u.s): body_loc = get_body_barycentric(body, emitted_time, ephemeris) earth_distance = (body_loc - earth_loc).norm() delta_light_travel_time = (light_travel_time - earth_distance/speed_of_light) light_travel_time = earth_distance/speed_of_light emitted_time = time - light_travel_time return get_body_barycentric(body, emitted_time, ephemeris) _get_apparent_body_position.__doc__ += indent(_EPHEMERIS_NOTE)[4:] def get_body(body, time, location=None, ephemeris=None): """ Get a `~astropy.coordinates.SkyCoord` for a solar system body as observed from a location on Earth in the `~astropy.coordinates.GCRS` reference system. Parameters ---------- body : str or other The solar system body for which to calculate positions. Can also be a kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL kernel. time : `~astropy.time.Time` Time of observation. location : `~astropy.coordinates.EarthLocation`, optional Location of observer on the Earth. If not given, will be taken from ``time`` (if not present, a geocentric observer will be assumed). ephemeris : str, optional Ephemeris to use. If not given, use the one set with ``astropy.coordinates.solar_system_ephemeris.set`` (which is set to 'builtin' by default). Returns ------- skycoord : `~astropy.coordinates.SkyCoord` GCRS Coordinate for the body Notes ----- """ if location is None: location = time.location cartrep = _get_apparent_body_position(body, time, ephemeris) icrs = ICRS(cartrep) if location is not None: obsgeoloc, obsgeovel = location.get_gcrs_posvel(time) gcrs = icrs.transform_to(GCRS(obstime=time, obsgeoloc=obsgeoloc, obsgeovel=obsgeovel)) else: gcrs = icrs.transform_to(GCRS(obstime=time)) return SkyCoord(gcrs) get_body.__doc__ += indent(_EPHEMERIS_NOTE)[4:] def get_moon(time, location=None, ephemeris=None): """ Get a `~astropy.coordinates.SkyCoord` for the Earth's Moon as observed from a location on Earth in the `~astropy.coordinates.GCRS` reference system. Parameters ---------- time : `~astropy.time.Time` Time of observation location : `~astropy.coordinates.EarthLocation` Location of observer on the Earth. If none is supplied, taken from ``time`` (if not present, a geocentric observer will be assumed). ephemeris : str, optional Ephemeris to use. If not given, use the one set with ``astropy.coordinates.solar_system_ephemeris.set`` (which is set to 'builtin' by default). Returns ------- skycoord : `~astropy.coordinates.SkyCoord` GCRS Coordinate for the Moon Notes ----- """ return get_body('moon', time, location=location, ephemeris=ephemeris) get_moon.__doc__ += indent(_EPHEMERIS_NOTE)[4:] def _apparent_position_in_true_coordinates(skycoord): """ Convert Skycoord in GCRS frame into one in which RA and Dec are defined w.r.t to the true equinox and poles of the Earth """ jd1, jd2 = get_jd12(skycoord.obstime, 'tt') _, _, _, _, _, _, _, rbpn = erfa.pn00a(jd1, jd2) return SkyCoord(skycoord.frame.realize_frame( skycoord.cartesian.transform(rbpn)))
cb0e4d2b6ca097da8d53f9ff3afe57e2e43f9ffa4acd1699cb4a28e3c5e16d3c
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst ''' This module defines custom errors and exceptions used in astropy.coordinates. ''' from ..utils.exceptions import AstropyWarning __all__ = ['RangeError', 'BoundsError', 'IllegalHourError', 'IllegalMinuteError', 'IllegalSecondError', 'ConvertError', 'IllegalHourWarning', 'IllegalMinuteWarning', 'IllegalSecondWarning', 'UnknownSiteException'] class RangeError(ValueError): """ Raised when some part of an angle is out of its valid range. """ class BoundsError(RangeError): """ Raised when an angle is outside of its user-specified bounds. """ class IllegalHourError(RangeError): """ Raised when an hour value is not in the range [0,24). Parameters ---------- hour : int, float Examples -------- .. code-block:: python if not 0 <= hr < 24: raise IllegalHourError(hour) """ def __init__(self, hour): self.hour = hour def __str__(self): return "An invalid value for 'hours' was found ('{0}'); must be in the range [0,24).".format(self.hour) class IllegalHourWarning(AstropyWarning): """ Raised when an hour value is 24. Parameters ---------- hour : int, float """ def __init__(self, hour, alternativeactionstr=None): self.hour = hour self.alternativeactionstr = alternativeactionstr def __str__(self): message = "'hour' was found to be '{0}', which is not in range (-24, 24).".format(self.hour) if self.alternativeactionstr is not None: message += ' ' + self.alternativeactionstr return message class IllegalMinuteError(RangeError): """ Raised when an minute value is not in the range [0,60]. Parameters ---------- minute : int, float Examples -------- .. code-block:: python if not 0 <= min < 60: raise IllegalMinuteError(minute) """ def __init__(self, minute): self.minute = minute def __str__(self): return "An invalid value for 'minute' was found ('{0}'); should be in the range [0,60).".format(self.minute) class IllegalMinuteWarning(AstropyWarning): """ Raised when a minute value is 60. Parameters ---------- minute : int, float """ def __init__(self, minute, alternativeactionstr=None): self.minute = minute self.alternativeactionstr = alternativeactionstr def __str__(self): message = "'minute' was found to be '{0}', which is not in range [0,60).".format(self.minute) if self.alternativeactionstr is not None: message += ' ' + self.alternativeactionstr return message class IllegalSecondError(RangeError): """ Raised when an second value (time) is not in the range [0,60]. Parameters ---------- second : int, float Examples -------- .. code-block:: python if not 0 <= sec < 60: raise IllegalSecondError(second) """ def __init__(self, second): self.second = second def __str__(self): return "An invalid value for 'second' was found ('{0}'); should be in the range [0,60).".format(self.second) class IllegalSecondWarning(AstropyWarning): """ Raised when a second value is 60. Parameters ---------- second : int, float """ def __init__(self, second, alternativeactionstr=None): self.second = second self.alternativeactionstr = alternativeactionstr def __str__(self): message = "'second' was found to be '{0}', which is not in range [0,60).".format(self.second) if self.alternativeactionstr is not None: message += ' ' + self.alternativeactionstr return message # TODO: consider if this should be used to `units`? class UnitsError(ValueError): """ Raised if units are missing or invalid. """ class ConvertError(Exception): """ Raised if a coordinate system cannot be converted to another """ class UnknownSiteException(KeyError): def __init__(self, site, attribute, close_names=None): message = "Site '{0}' not in database. Use {1} to see available sites.".format(site, attribute) if close_names: message += " Did you mean one of: '{0}'?'".format("', '".join(close_names)) self.site = site self.attribute = attribute self.close_names = close_names return super().__init__(message)
fb19f5cdbb75298b33439af8e94a135134ae1d9e92196ba74e3f6d2426431131
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains utililies used for constructing rotation matrices. """ from functools import reduce import numpy as np from .. import units as u from .angles import Angle def matrix_product(*matrices): """Matrix multiply all arguments together. Arguments should have dimension 2 or larger. Larger dimensional objects are interpreted as stacks of matrices residing in the last two dimensions. This function mostly exists for readability: using `~numpy.matmul` directly, one would have ``matmul(matmul(m1, m2), m3)``, etc. For even better readability, one might consider using `~numpy.matrix` for the arguments (so that one could write ``m1 * m2 * m3``), but then it is not possible to handle stacks of matrices. Once only python >=3.5 is supported, this function can be replaced by ``m1 @ m2 @ m3``. """ return reduce(np.matmul, matrices) def matrix_transpose(matrix): """Transpose a matrix or stack of matrices by swapping the last two axes. This function mostly exists for readability; seeing ``.swapaxes(-2, -1)`` it is not that obvious that one does a transpose. Note that one cannot use `~numpy.ndarray.T`, as this transposes all axes and thus does not work for stacks of matrices. """ return matrix.swapaxes(-2, -1) def rotation_matrix(angle, axis='z', unit=None): """ Generate matrices for rotation by some angle around some axis. Parameters ---------- angle : convertible to `Angle` The amount of rotation the matrices should represent. Can be an array. axis : str, or array-like Either ``'x'``, ``'y'``, ``'z'``, or a (x,y,z) specifying the axis to rotate about. If ``'x'``, ``'y'``, or ``'z'``, the rotation sense is counterclockwise looking down the + axis (e.g. positive rotations obey left-hand-rule). If given as an array, the last dimension should be 3; it will be broadcast against ``angle``. unit : UnitBase, optional If ``angle`` does not have associated units, they are in this unit. If neither are provided, it is assumed to be degrees. Returns ------- rmat : `numpy.matrix` A unitary rotation matrix. """ if unit is None: unit = u.degree angle = Angle(angle, unit=unit) s = np.sin(angle) c = np.cos(angle) # use optimized implementations for x/y/z try: i = 'xyz'.index(axis) except TypeError: axis = np.asarray(axis) axis = axis / np.sqrt((axis * axis).sum(axis=-1, keepdims=True)) R = (axis[..., np.newaxis] * axis[..., np.newaxis, :] * (1. - c)[..., np.newaxis, np.newaxis]) for i in range(0, 3): R[..., i, i] += c a1 = (i + 1) % 3 a2 = (i + 2) % 3 R[..., a1, a2] += axis[..., i] * s R[..., a2, a1] -= axis[..., i] * s else: a1 = (i + 1) % 3 a2 = (i + 2) % 3 R = np.zeros(angle.shape + (3, 3)) R[..., i, i] = 1. R[..., a1, a1] = c R[..., a1, a2] = s R[..., a2, a1] = -s R[..., a2, a2] = c return R def angle_axis(matrix): """ Angle of rotation and rotation axis for a given rotation matrix. Parameters ---------- matrix : array-like A 3 x 3 unitary rotation matrix (or stack of matrices). Returns ------- angle : `Angle` The angle of rotation. axis : array The (normalized) axis of rotation (with last dimension 3). """ m = np.asanyarray(matrix) if m.shape[-2:] != (3, 3): raise ValueError('matrix is not 3x3') axis = np.zeros(m.shape[:-1]) axis[..., 0] = m[..., 2, 1] - m[..., 1, 2] axis[..., 1] = m[..., 0, 2] - m[..., 2, 0] axis[..., 2] = m[..., 1, 0] - m[..., 0, 1] r = np.sqrt((axis * axis).sum(-1, keepdims=True)) angle = np.arctan2(r[..., 0], m[..., 0, 0] + m[..., 1, 1] + m[..., 2, 2] - 1.) return Angle(angle, u.radian), -axis / r
3127ebca0d0d42515657270590cef55fc0315a4aaab0e94e32efcc78b4e8f609
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This subpackage contains classes and functions for celestial coordinates of astronomical objects. It also contains a framework for conversions between coordinate systems. """ from .errors import * from .angles import * from .baseframe import * from .attributes import * from .distances import * from .earth import * from .transformations import * from .builtin_frames import * from .name_resolve import * from .matching import * from .representation import * from .sky_coordinate import * from .funcs import * from .calculation import * from .solar_system import * # This is for backwards-compatibility -- can be removed in v3.0 when the # deprecation warnings are removed from .attributes import (TimeFrameAttribute, QuantityFrameAttribute, CartesianRepresentationFrameAttribute) __doc__ += builtin_frames._transform_graph_docs + """ .. note:: The ecliptic coordinate systems (added in Astropy v1.1) have not been extensively tested for accuracy or consistency with other implementations of ecliptic coordinates. We welcome contributions to add such testing, but in the meantime, users who depend on consistency with other implementations may wish to check test inputs against good datasets before using Astropy's ecliptic coordinates. """
ee22ee7b96b8f340053f77c7ccee92c9cec20fe4c0baa0e79e0f9a19bfe32bce
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains functions for matching coordinate catalogs. """ import numpy as np from .representation import UnitSphericalRepresentation from .. import units as u from . import Angle __all__ = ['match_coordinates_3d', 'match_coordinates_sky', 'search_around_3d', 'search_around_sky'] def match_coordinates_3d(matchcoord, catalogcoord, nthneighbor=1, storekdtree='kdtree_3d'): """ Finds the nearest 3-dimensional matches of a coordinate or coordinates in a set of catalog coordinates. This finds the 3-dimensional closest neighbor, which is only different from the on-sky distance if ``distance`` is set in either ``matchcoord`` or ``catalogcoord``. Parameters ---------- matchcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The coordinate(s) to match to the catalog. catalogcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The base catalog in which to search for matches. Typically this will be a coordinate object that is an array (i.e., ``catalogcoord.isscalar == False``) nthneighbor : int, optional Which closest neighbor to search for. Typically ``1`` is desired here, as that is correct for matching one set of coordinates to another. The next likely use case is ``2``, for matching a coordinate catalog against *itself* (``1`` is inappropriate because each point will find itself as the closest match). storekdtree : bool or str, optional If a string, will store the KD-Tree used for the computation in the ``catalogcoord``, as in ``catalogcoord.cache`` with the provided name. This dramatically speeds up subsequent calls with the same catalog. If False, the KD-Tree is discarded after use. Returns ------- idx : integer array Indices into ``catalogcoord`` to get the matched points for each ``matchcoord``. Shape matches ``matchcoord``. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the closest match for each ``matchcoord`` and the ``matchcoord``. Shape matches ``matchcoord``. dist3d : `~astropy.units.Quantity` The 3D distance between the closest match for each ``matchcoord`` and the ``matchcoord``. Shape matches ``matchcoord``. Notes ----- This function requires `SciPy <https://www.scipy.org/>`_ to be installed or it will fail. """ if catalogcoord.isscalar or len(catalogcoord) < 1: raise ValueError('The catalog for coordinate matching cannot be a ' 'scalar or length-0.') kdt = _get_cartesian_kdtree(catalogcoord, storekdtree) # make sure coordinate systems match matchcoord = matchcoord.transform_to(catalogcoord) # make sure units match catunit = catalogcoord.cartesian.x.unit matchxyz = matchcoord.cartesian.xyz.to(catunit) matchflatxyz = matchxyz.reshape((3, np.prod(matchxyz.shape) // 3)) dist, idx = kdt.query(matchflatxyz.T, nthneighbor) if nthneighbor > 1: # query gives 1D arrays if k=1, 2D arrays otherwise dist = dist[:, -1] idx = idx[:, -1] sep2d = catalogcoord[idx].separation(matchcoord) return idx.reshape(matchxyz.shape[1:]), sep2d, dist.reshape(matchxyz.shape[1:]) * catunit def match_coordinates_sky(matchcoord, catalogcoord, nthneighbor=1, storekdtree='kdtree_sky'): """ Finds the nearest on-sky matches of a coordinate or coordinates in a set of catalog coordinates. This finds the on-sky closest neighbor, which is only different from the 3-dimensional match if ``distance`` is set in either ``matchcoord`` or ``catalogcoord``. Parameters ---------- matchcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The coordinate(s) to match to the catalog. catalogcoord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The base catalog in which to search for matches. Typically this will be a coordinate object that is an array (i.e., ``catalogcoord.isscalar == False``) nthneighbor : int, optional Which closest neighbor to search for. Typically ``1`` is desired here, as that is correct for matching one set of coordinates to another. The next likely use case is ``2``, for matching a coordinate catalog against *itself* (``1`` is inappropriate because each point will find itself as the closest match). storekdtree : bool or str, optional If a string, will store the KD-Tree used for the computation in the ``catalogcoord`` in ``catalogcoord.cache`` with the provided name. This dramatically speeds up subsequent calls with the same catalog. If False, the KD-Tree is discarded after use. Returns ------- idx : integer array Indices into ``catalogcoord`` to get the matched points for each ``matchcoord``. Shape matches ``matchcoord``. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the closest match for each ``matchcoord`` and the ``matchcoord``. Shape matches ``matchcoord``. dist3d : `~astropy.units.Quantity` The 3D distance between the closest match for each ``matchcoord`` and the ``matchcoord``. Shape matches ``matchcoord``. If either ``matchcoord`` or ``catalogcoord`` don't have a distance, this is the 3D distance on the unit sphere, rather than a true distance. Notes ----- This function requires `SciPy <https://www.scipy.org/>`_ to be installed or it will fail. """ if catalogcoord.isscalar or len(catalogcoord) < 1: raise ValueError('The catalog for coordinate matching cannot be a ' 'scalar or length-0.') # send to catalog frame newmatch = matchcoord.transform_to(catalogcoord) # strip out distance info match_urepr = newmatch.data.represent_as(UnitSphericalRepresentation) newmatch_u = newmatch.realize_frame(match_urepr) cat_urepr = catalogcoord.data.represent_as(UnitSphericalRepresentation) newcat_u = catalogcoord.realize_frame(cat_urepr) # Check for a stored KD-tree on the passed-in coordinate. Normally it will # have a distinct name from the "3D" one, so it's safe to use even though # it's based on UnitSphericalRepresentation. storekdtree = catalogcoord.cache.get(storekdtree, storekdtree) idx, sep2d, sep3d = match_coordinates_3d(newmatch_u, newcat_u, nthneighbor, storekdtree) # sep3d is *wrong* above, because the distance information was removed, # unless one of the catalogs doesn't have a real distance if not (isinstance(catalogcoord.data, UnitSphericalRepresentation) or isinstance(newmatch.data, UnitSphericalRepresentation)): sep3d = catalogcoord[idx].separation_3d(newmatch) # update the kdtree on the actual passed-in coordinate if isinstance(storekdtree, str): catalogcoord.cache[storekdtree] = newcat_u.cache[storekdtree] elif storekdtree is True: # the old backwards-compatible name catalogcoord.cache['kdtree'] = newcat_u.cache['kdtree'] return idx, sep2d, sep3d def search_around_3d(coords1, coords2, distlimit, storekdtree='kdtree_3d'): """ Searches for pairs of points that are at least as close as a specified distance in 3D space. This is intended for use on coordinate objects with arrays of coordinates, not scalars. For scalar coordinates, it is better to use the ``separation_3d`` methods. Parameters ---------- coords1 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The first set of coordinates, which will be searched for matches from ``coords2`` within ``seplimit``. Cannot be a scalar coordinate. coords2 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The second set of coordinates, which will be searched for matches from ``coords1`` within ``seplimit``. Cannot be a scalar coordinate. distlimit : `~astropy.units.Quantity` with distance units The physical radius to search within. storekdtree : bool or str, optional If a string, will store the KD-Tree used in the search with the name ``storekdtree`` in ``coords2.cache``. This speeds up subsequent calls to this function. If False, the KD-Trees are not saved. Returns ------- idx1 : integer array Indices into ``coords1`` that matches to the corresponding element of ``idx2``. Shape matches ``idx2``. idx2 : integer array Indices into ``coords2`` that matches to the corresponding element of ``idx1``. Shape matches ``idx1``. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the coordinates. Shape matches ``idx1`` and ``idx2``. dist3d : `~astropy.units.Quantity` The 3D distance between the coordinates. Shape matches ``idx1`` and ``idx2``. The unit is that of ``coords1``. Notes ----- This function requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be installed or it will fail. If you are using this function to search in a catalog for matches around specific points, the convention is for ``coords2`` to be the catalog, and ``coords1`` are the points to search around. While these operations are mathematically the same if ``coords1`` and ``coords2`` are flipped, some of the optimizations may work better if this convention is obeyed. In the current implementation, the return values are always sorted in the same order as the ``coords1`` (so ``idx1`` is in ascending order). This is considered an implementation detail, though, so it could change in a future release. """ if not distlimit.isscalar: raise ValueError('distlimit must be a scalar in search_around_3d') if coords1.isscalar or coords2.isscalar: raise ValueError('One of the inputs to search_around_3d is a scalar. ' 'search_around_3d is intended for use with array ' 'coordinates, not scalars. Instead, use ' '``coord1.separation_3d(coord2) < distlimit`` to find ' 'the coordinates near a scalar coordinate.') if len(coords1) == 0 or len(coords2) == 0: # Empty array input: return empty match return (np.array([], dtype=int), np.array([], dtype=int), Angle([], u.deg), u.Quantity([], coords1.distance.unit)) kdt2 = _get_cartesian_kdtree(coords2, storekdtree) cunit = coords2.cartesian.x.unit # we convert coord1 to match coord2's frame. We do it this way # so that if the conversion does happen, the KD tree of coord2 at least gets # saved. (by convention, coord2 is the "catalog" if that makes sense) coords1 = coords1.transform_to(coords2) kdt1 = _get_cartesian_kdtree(coords1, storekdtree, forceunit=cunit) # this is the *cartesian* 3D distance that corresponds to the given angle d = distlimit.to_value(cunit) idxs1 = [] idxs2 = [] for i, matches in enumerate(kdt1.query_ball_tree(kdt2, d)): for match in matches: idxs1.append(i) idxs2.append(match) idxs1 = np.array(idxs1, dtype=int) idxs2 = np.array(idxs2, dtype=int) if idxs1.size == 0: d2ds = Angle([], u.deg) d3ds = u.Quantity([], coords1.distance.unit) else: d2ds = coords1[idxs1].separation(coords2[idxs2]) d3ds = coords1[idxs1].separation_3d(coords2[idxs2]) return idxs1, idxs2, d2ds, d3ds def search_around_sky(coords1, coords2, seplimit, storekdtree='kdtree_sky'): """ Searches for pairs of points that have an angular separation at least as close as a specified angle. This is intended for use on coordinate objects with arrays of coordinates, not scalars. For scalar coordinates, it is better to use the ``separation`` methods. Parameters ---------- coords1 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The first set of coordinates, which will be searched for matches from ``coords2`` within ``seplimit``. Cannot be a scalar coordinate. coords2 : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The second set of coordinates, which will be searched for matches from ``coords1`` within ``seplimit``. Cannot be a scalar coordinate. seplimit : `~astropy.units.Quantity` with angle units The on-sky separation to search within. storekdtree : bool or str, optional If a string, will store the KD-Tree used in the search with the name ``storekdtree`` in ``coords2.cache``. This speeds up subsequent calls to this function. If False, the KD-Trees are not saved. Returns ------- idx1 : integer array Indices into ``coords1`` that matches to the corresponding element of ``idx2``. Shape matches ``idx2``. idx2 : integer array Indices into ``coords2`` that matches to the corresponding element of ``idx1``. Shape matches ``idx1``. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the coordinates. Shape matches ``idx1`` and ``idx2``. dist3d : `~astropy.units.Quantity` The 3D distance between the coordinates. Shape matches ``idx1`` and ``idx2``; the unit is that of ``coords1``. If either ``coords1`` or ``coords2`` don't have a distance, this is the 3D distance on the unit sphere, rather than a physical distance. Notes ----- This function requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be installed or it will fail. In the current implementation, the return values are always sorted in the same order as the ``coords1`` (so ``idx1`` is in ascending order). This is considered an implementation detail, though, so it could change in a future release. """ if not seplimit.isscalar: raise ValueError('seplimit must be a scalar in search_around_sky') if coords1.isscalar or coords2.isscalar: raise ValueError('One of the inputs to search_around_sky is a scalar. ' 'search_around_sky is intended for use with array ' 'coordinates, not scalars. Instead, use ' '``coord1.separation(coord2) < seplimit`` to find the ' 'coordinates near a scalar coordinate.') if len(coords1) == 0 or len(coords2) == 0: # Empty array input: return empty match if coords2.distance.unit == u.dimensionless_unscaled: distunit = u.dimensionless_unscaled else: distunit = coords1.distance.unit return (np.array([], dtype=int), np.array([], dtype=int), Angle([], u.deg), u.Quantity([], distunit)) # we convert coord1 to match coord2's frame. We do it this way # so that if the conversion does happen, the KD tree of coord2 at least gets # saved. (by convention, coord2 is the "catalog" if that makes sense) coords1 = coords1.transform_to(coords2) # strip out distance info urepr1 = coords1.data.represent_as(UnitSphericalRepresentation) ucoords1 = coords1.realize_frame(urepr1) kdt1 = _get_cartesian_kdtree(ucoords1, storekdtree) if storekdtree and coords2.cache.get(storekdtree): # just use the stored KD-Tree kdt2 = coords2.cache[storekdtree] else: # strip out distance info urepr2 = coords2.data.represent_as(UnitSphericalRepresentation) ucoords2 = coords2.realize_frame(urepr2) kdt2 = _get_cartesian_kdtree(ucoords2, storekdtree) if storekdtree: # save the KD-Tree in coords2, *not* ucoords2 coords2.cache['kdtree' if storekdtree is True else storekdtree] = kdt2 # this is the *cartesian* 3D distance that corresponds to the given angle r = (2 * np.sin(Angle(seplimit) / 2.0)).value idxs1 = [] idxs2 = [] for i, matches in enumerate(kdt1.query_ball_tree(kdt2, r)): for match in matches: idxs1.append(i) idxs2.append(match) idxs1 = np.array(idxs1, dtype=int) idxs2 = np.array(idxs2, dtype=int) if idxs1.size == 0: if coords2.distance.unit == u.dimensionless_unscaled: distunit = u.dimensionless_unscaled else: distunit = coords1.distance.unit d2ds = Angle([], u.deg) d3ds = u.Quantity([], distunit) else: d2ds = coords1[idxs1].separation(coords2[idxs2]) try: d3ds = coords1[idxs1].separation_3d(coords2[idxs2]) except ValueError: # they don't have distances, so we just fall back on the cartesian # distance, computed from d2ds d3ds = 2 * np.sin(d2ds / 2.0) return idxs1, idxs2, d2ds, d3ds def _get_cartesian_kdtree(coord, attrname_or_kdt='kdtree', forceunit=None): """ This is a utility function to retrieve (and build/cache, if necessary) a 3D cartesian KD-Tree from various sorts of astropy coordinate objects. Parameters ---------- coord : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The coordinates to build the KD-Tree for. attrname_or_kdt : bool or str or KDTree If a string, will store the KD-Tree used for the computation in the ``coord``, in ``coord.cache`` with the provided name. If given as a KD-Tree, it will just be used directly. forceunit : unit or None If a unit, the cartesian coordinates will convert to that unit before being put in the KD-Tree. If None, whatever unit it's already in will be used Returns ------- kdt : `~scipy.spatial.cKDTree` or `~scipy.spatial.KDTree` The KD-Tree representing the 3D cartesian representation of the input coordinates. """ from warnings import warn # without scipy this will immediately fail from scipy import spatial try: KDTree = spatial.cKDTree except Exception: warn('C-based KD tree not found, falling back on (much slower) ' 'python implementation') KDTree = spatial.KDTree if attrname_or_kdt is True: # backwards compatibility for pre v0.4 attrname_or_kdt = 'kdtree' # figure out where any cached KDTree might be if isinstance(attrname_or_kdt, str): kdt = coord.cache.get(attrname_or_kdt, None) if kdt is not None and not isinstance(kdt, KDTree): raise TypeError('The `attrname_or_kdt` "{0}" is not a scipy KD tree!'.format(attrname_or_kdt)) elif isinstance(attrname_or_kdt, KDTree): kdt = attrname_or_kdt attrname_or_kdt = None elif not attrname_or_kdt: kdt = None else: raise TypeError('Invalid `attrname_or_kdt` argument for KD-Tree:' + str(attrname_or_kdt)) if kdt is None: # need to build the cartesian KD-tree for the catalog if forceunit is None: cartxyz = coord.cartesian.xyz else: cartxyz = coord.cartesian.xyz.to(forceunit) flatxyz = cartxyz.reshape((3, np.prod(cartxyz.shape) // 3)) kdt = KDTree(flatxyz.value.T) if attrname_or_kdt: # cache the kdtree in `coord` coord.cache[attrname_or_kdt] = kdt return kdt
3dcb5ca4341829e4859d1daa2f1dc755c63f0183514e5031e9fed841a2118fc6
import re import copy import warnings import collections import numpy as np from .. import _erfa as erfa from ..utils.compat.misc import override__dir__ from ..units import Unit, IrreducibleUnit from .. import units as u from ..constants import c as speed_of_light from ..wcs.utils import skycoord_to_pixel, pixel_to_skycoord from ..utils.exceptions import AstropyDeprecationWarning from ..utils.data_info import MixinInfo from ..utils import ShapedLikeNDArray from ..time import Time from .distances import Distance from .angles import Angle from .baseframe import (BaseCoordinateFrame, frame_transform_graph, GenericFrame, _get_repr_cls, _get_diff_cls, _normalize_representation_type) from .builtin_frames import ICRS, SkyOffsetFrame from .representation import (BaseRepresentation, SphericalRepresentation, UnitSphericalRepresentation, SphericalDifferential) __all__ = ['SkyCoord', 'SkyCoordInfo'] PLUS_MINUS_RE = re.compile(r'(\+|\-)') J_PREFIXED_RA_DEC_RE = re.compile( r"""J # J prefix ([0-9]{6,7}\.?[0-9]{0,2}) # RA as HHMMSS.ss or DDDMMSS.ss, optional decimal digits ([\+\-][0-9]{6}\.?[0-9]{0,2})\s*$ # Dec as DDMMSS.ss, optional decimal digits """, re.VERBOSE) class SkyCoordInfo(MixinInfo): """ Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information. """ attrs_from_parent = set(['unit']) # Unit is read-only _supports_indexing = False @staticmethod def default_format(val): repr_data = val.info._repr_data formats = ['{0.' + compname + '.value:}' for compname in repr_data.components] return ','.join(formats).format(repr_data) @property def unit(self): repr_data = self._repr_data unit = ','.join(str(getattr(repr_data, comp).unit) or 'None' for comp in repr_data.components) return unit @property def _repr_data(self): if self._parent is None: return None sc = self._parent if (issubclass(sc.representation_type, SphericalRepresentation) and isinstance(sc.data, UnitSphericalRepresentation)): repr_data = sc.represent_as(sc.data.__class__, in_frame_units=True) else: repr_data = sc.represent_as(sc.representation_type, in_frame_units=True) return repr_data def _represent_as_dict(self): obj = self._parent attrs = (list(obj.representation_component_names) + list(frame_transform_graph.frame_attributes.keys())) # Don't output distance if it is all unitless 1.0 if 'distance' in attrs and np.all(obj.distance == 1.0): attrs.remove('distance') self._represent_as_dict_attrs = attrs out = super()._represent_as_dict() out['representation_type'] = obj.representation_type.get_name() out['frame'] = obj.frame.name # Note that obj.info.unit is a fake composite unit (e.g. 'deg,deg,None' # or None,None,m) and is not stored. The individual attributes have # units. return out class SkyCoord(ShapedLikeNDArray): """High-level object providing a flexible interface for celestial coordinate representation, manipulation, and transformation between systems. The `SkyCoord` class accepts a wide variety of inputs for initialization. At a minimum these must provide one or more celestial coordinate values with unambiguous units. Inputs may be scalars or lists/tuples/arrays, yielding scalar or array coordinates (can be checked via ``SkyCoord.isscalar``). Typically one also specifies the coordinate frame, though this is not required. The general pattern for spherical representations is:: SkyCoord(COORD, [FRAME], keyword_args ...) SkyCoord(LON, LAT, [FRAME], keyword_args ...) SkyCoord(LON, LAT, [DISTANCE], frame=FRAME, unit=UNIT, keyword_args ...) SkyCoord([FRAME], <lon_attr>=LON, <lat_attr>=LAT, keyword_args ...) It is also possible to input coordinate values in other representations such as cartesian or cylindrical. In this case one includes the keyword argument ``representation_type='cartesian'`` (for example) along with data in ``x``, ``y``, and ``z``. Examples -------- The examples below illustrate common ways of initializing a `SkyCoord` object. For a complete description of the allowed syntax see the full coordinates documentation. First some imports:: >>> from astropy.coordinates import SkyCoord # High-level coordinates >>> from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames >>> from astropy.coordinates import Angle, Latitude, Longitude # Angles >>> import astropy.units as u The coordinate values and frame specification can now be provided using positional and keyword arguments:: >>> c = SkyCoord(10, 20, unit="deg") # defaults to ICRS frame >>> c = SkyCoord([1, 2, 3], [-30, 45, 8], "icrs", unit="deg") # 3 coords >>> coords = ["1:12:43.2 +1:12:43", "1 12 43.2 +1 12 43"] >>> c = SkyCoord(coords, FK4, unit=(u.deg, u.hourangle), obstime="J1992.21") >>> c = SkyCoord("1h12m43.2s +1d12m43s", Galactic) # Units from string >>> c = SkyCoord("galactic", l="1h12m43.2s", b="+1d12m43s") >>> ra = Longitude([1, 2, 3], unit=u.deg) # Could also use Angle >>> dec = np.array([4.5, 5.2, 6.3]) * u.deg # Astropy Quantity >>> c = SkyCoord(ra, dec, frame='icrs') >>> c = SkyCoord(ICRS, ra=ra, dec=dec, obstime='2001-01-02T12:34:56') >>> c = FK4(1 * u.deg, 2 * u.deg) # Uses defaults for obstime, equinox >>> c = SkyCoord(c, obstime='J2010.11', equinox='B1965') # Override defaults >>> c = SkyCoord(w=0, u=1, v=2, unit='kpc', frame='galactic', ... representation_type='cartesian') >>> c = SkyCoord([ICRS(ra=1*u.deg, dec=2*u.deg), ICRS(ra=3*u.deg, dec=4*u.deg)]) Velocity components (proper motions or radial velocities) can also be provided in a similar manner:: >>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, radial_velocity=10*u.km/u.s) >>> c = SkyCoord(ra=1*u.deg, dec=2*u.deg, pm_ra_cosdec=2*u.mas/u.yr, pm_dec=1*u.mas/u.yr) As shown, the frame can be a `~astropy.coordinates.BaseCoordinateFrame` class or the corresponding string alias. The frame classes that are built in to astropy are `ICRS`, `FK5`, `FK4`, `FK4NoETerms`, and `Galactic`. The string aliases are simply lower-case versions of the class name, and allow for creating a `SkyCoord` object and transforming frames without explicitly importing the frame classes. Parameters ---------- frame : `~astropy.coordinates.BaseCoordinateFrame` class or string, optional Type of coordinate frame this `SkyCoord` should represent. Defaults to to ICRS if not given or given as None. unit : `~astropy.units.Unit`, string, or tuple of :class:`~astropy.units.Unit` or str, optional Units for supplied ``LON`` and ``LAT`` values, respectively. If only one unit is supplied then it applies to both ``LON`` and ``LAT``. obstime : valid `~astropy.time.Time` initializer, optional Time of observation equinox : valid `~astropy.time.Time` initializer, optional Coordinate frame equinox representation_type : str or Representation class Specifies the representation, e.g. 'spherical', 'cartesian', or 'cylindrical'. This affects the positional args and other keyword args which must correspond to the given representation. copy : bool, optional If `True` (default), a copy of any coordinate data is made. This argument can only be passed in as a keyword argument. **keyword_args Other keyword arguments as applicable for user-defined coordinate frames. Common options include: ra, dec : valid `~astropy.coordinates.Angle` initializer, optional RA and Dec for frames where ``ra`` and ``dec`` are keys in the frame's ``representation_component_names``, including `ICRS`, `FK5`, `FK4`, and `FK4NoETerms`. pm_ra_cosdec, pm_dec : `~astropy.units.Quantity`, optional Proper motion components, in angle per time units. l, b : valid `~astropy.coordinates.Angle` initializer, optional Galactic ``l`` and ``b`` for for frames where ``l`` and ``b`` are keys in the frame's ``representation_component_names``, including the `Galactic` frame. pm_l_cosb, pm_b : `~astropy.units.Quantity`, optional Proper motion components in the `Galactic` frame, in angle per time units. x, y, z : float or `~astropy.units.Quantity`, optional Cartesian coordinates values u, v, w : float or `~astropy.units.Quantity`, optional Cartesian coordinates values for the Galactic frame. radial_velocity : `~astropy.units.Quantity`, optional The component of the velocity along the line-of-sight (i.e., the radial direction), in velocity units. """ # Declare that SkyCoord can be used as a Table column by defining the # info property. info = SkyCoordInfo() def __init__(self, *args, copy=True, **kwargs): # Parse the args and kwargs to assemble a sanitized and validated # kwargs dict for initializing attributes for this object and for # creating the internal self._sky_coord_frame object args = list(args) # Make it mutable kwargs = self._parse_inputs(args, kwargs) frame = kwargs['frame'] frame_attr_names = frame.get_frame_attr_names() # these are frame attributes set on this SkyCoord but *not* a part of # the frame object this SkyCoord contains self._extra_frameattr_names = set() for attr in kwargs: if (attr not in frame_attr_names and attr in frame_transform_graph.frame_attributes): # Setting it will also validate it. setattr(self, attr, kwargs[attr]) coord_kwargs = {} component_names = frame.representation_component_names component_names.update(frame.get_representation_component_names('s')) # TODO: deprecate representation, remove this in future _normalize_representation_type(kwargs) if 'representation_type' in kwargs: coord_kwargs['representation_type'] = _get_repr_cls( kwargs['representation_type']) if 'differential_type' in kwargs: coord_kwargs['differential_type'] = _get_diff_cls(kwargs['differential_type']) for attr, value in kwargs.items(): if value is not None and (attr in component_names or attr in frame_attr_names): coord_kwargs[attr] = value # Finally make the internal coordinate object. self._sky_coord_frame = frame.__class__(copy=copy, **coord_kwargs) if not self._sky_coord_frame.has_data: raise ValueError('Cannot create a SkyCoord without data') @property def frame(self): return self._sky_coord_frame @property def representation_type(self): return self.frame.representation_type @representation_type.setter def representation_type(self, value): self.frame.representation_type = value # TODO: deprecate these in future @property def representation(self): return self.frame.representation @representation.setter def representation(self, value): self.frame.representation = value @property def shape(self): return self.frame.shape def _apply(self, method, *args, **kwargs): """Create a new instance, applying a method to the underlying data. In typical usage, the method is any of the shape-changing methods for `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those picking particular elements (``__getitem__``, ``take``, etc.), which are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be applied to the underlying arrays in the representation (e.g., ``x``, ``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`), as well as to any frame attributes that have a shape, with the results used to create a new instance. Internally, it is also used to apply functions to the above parts (in particular, `~numpy.broadcast_to`). Parameters ---------- method : str or callable If str, it is the name of a method that is applied to the internal ``components``. If callable, the function is applied. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. """ def apply_method(value): if isinstance(value, ShapedLikeNDArray): return value._apply(method, *args, **kwargs) else: if callable(method): return method(value, *args, **kwargs) else: return getattr(value, method)(*args, **kwargs) # create a new but empty instance, and copy over stuff new = super().__new__(self.__class__) new._sky_coord_frame = self._sky_coord_frame._apply(method, *args, **kwargs) new._extra_frameattr_names = self._extra_frameattr_names.copy() for attr in self._extra_frameattr_names: value = getattr(self, attr) if getattr(value, 'size', 1) > 1: value = apply_method(value) elif method == 'copy' or method == 'flatten': # flatten should copy also for a single element array, but # we cannot use it directly for array scalars, since it # always returns a one-dimensional array. So, just copy. value = copy.copy(value) setattr(new, '_' + attr, value) # Copy other 'info' attr only if it has actually been defined. # See PR #3898 for further explanation and justification, along # with Quantity.__array_finalize__ if 'info' in self.__dict__: new.info = self.info return new def _parse_inputs(self, args, kwargs): """ Assemble a validated and sanitized keyword args dict for instantiating a SkyCoord and coordinate object from the provided `args`, and `kwargs`. """ valid_kwargs = {} # Put the SkyCoord attributes like frame, equinox, obstime, location # into valid_kwargs dict. `Frame` could come from args or kwargs, so # set valid_kwargs['frame'] accordingly. The others must be specified # by keyword args or else get a None default. Pop them off of kwargs # in the process. frame = valid_kwargs['frame'] = _get_frame(args, kwargs) # TODO: possibly remove the below. The representation/differential # information should *already* be stored in the frame object, as it is # extracted in _get_frame. So it may be redundent to include it below. # TODO: deprecate representation, remove this in future _normalize_representation_type(kwargs) if 'representation_type' in kwargs: valid_kwargs['representation_type'] = _get_repr_cls( kwargs.pop('representation_type')) if 'differential_type' in kwargs: valid_kwargs['differential_type'] = _get_diff_cls( kwargs.pop('differential_type')) for attr in frame_transform_graph.frame_attributes: if attr in kwargs: valid_kwargs[attr] = kwargs.pop(attr) # Get units units = _get_representation_component_units(args, kwargs) # Grab any frame-specific attr names like `ra` or `l` or `distance` from # kwargs and migrate to valid_kwargs. valid_kwargs.update(_get_representation_attrs(frame, units, kwargs)) # Error if anything is still left in kwargs if kwargs: # The next few lines add a more user-friendly error message to a # common and confusing situation when the user specifies, e.g., # `pm_ra` when they really should be passing `pm_ra_cosdec`. The # extra error should only turn on when the positional representation # is spherical, and when the component 'pm_<lon>' is passed. pm_message = '' if frame.representation_type == SphericalRepresentation: frame_names = list(frame.get_representation_component_names().keys()) lon_name = frame_names[0] lat_name = frame_names[1] if 'pm_{0}'.format(lon_name) in list(kwargs.keys()): pm_message = ('\n\n By default, most frame classes expect ' 'the longitudinal proper motion to include ' 'the cos(latitude) term, named ' '`pm_{0}_cos{1}`. Did you mean to pass in ' 'this component?' .format(lon_name, lat_name)) raise ValueError('Unrecognized keyword argument(s) {0}{1}' .format(', '.join("'{0}'".format(key) for key in kwargs), pm_message)) # Finally deal with the unnamed args. This figures out what the arg[0] # is and returns a dict with appropriate key/values for initializing # frame class. Note that differentials are *never* valid args, only # kwargs. So they are not accounted for here (unless they're in a frame # or SkyCoord object) if args: if len(args) == 1: # One arg which must be a coordinate. In this case # coord_kwargs will contain keys like 'ra', 'dec', 'distance' # along with any frame attributes like equinox or obstime which # were explicitly specified in the coordinate object (i.e. non-default). coord_kwargs = _parse_coordinate_arg(args[0], frame, units, kwargs) # Copy other 'info' attr only if it has actually been defined. if 'info' in getattr(args[0], '__dict__', ()): self.info = args[0].info elif len(args) <= 3: frame_attr_names = frame.representation_component_names.keys() repr_attr_names = frame.representation_component_names.values() coord_kwargs = {} for arg, frame_attr_name, repr_attr_name, unit in zip(args, frame_attr_names, repr_attr_names, units): attr_class = frame.representation.attr_classes[repr_attr_name] coord_kwargs[frame_attr_name] = attr_class(arg, unit=unit) else: raise ValueError('Must supply no more than three positional arguments, got {}' .format(len(args))) # Copy the coord_kwargs into the final valid_kwargs dict. For each # of the coord_kwargs ensure that there is no conflict with a value # specified by the user in the original kwargs. for attr, coord_value in coord_kwargs.items(): if (attr in valid_kwargs and valid_kwargs[attr] is not None and np.any(valid_kwargs[attr] != coord_value)): raise ValueError("Coordinate attribute '{0}'={1!r} conflicts with " "keyword argument '{0}'={2!r}" .format(attr, coord_value, valid_kwargs[attr])) valid_kwargs[attr] = coord_value return valid_kwargs def transform_to(self, frame, merge_attributes=True): """Transform this coordinate to a new frame. The precise frame transformed to depends on ``merge_attributes``. If `False`, the destination frame is used exactly as passed in. But this is often not quite what one wants. E.g., suppose one wants to transform an ICRS coordinate that has an obstime attribute to FK4; in this case, one likely would want to use this information. Thus, the default for ``merge_attributes`` is `True`, in which the precedence is as follows: (1) explicitly set (i.e., non-default) values in the destination frame; (2) explicitly set values in the source; (3) default value in the destination frame. Note that in either case, any explicitly set attributes on the source `SkyCoord` that are not part of the destination frame's definition are kept (stored on the resulting `SkyCoord`), and thus one can round-trip (e.g., from FK4 to ICRS to FK4 without loosing obstime). Parameters ---------- frame : str, `BaseCoordinateFrame` class or instance, or `SkyCoord` instance The frame to transform this coordinate into. If a `SkyCoord`, the underlying frame is extracted, and all other information ignored. merge_attributes : bool, optional Whether the default attributes in the destination frame are allowed to be overridden by explicitly set attributes in the source (see note above; default: `True`). Returns ------- coord : `SkyCoord` A new object with this coordinate represented in the `frame` frame. Raises ------ ValueError If there is no possible transformation route. """ from astropy.coordinates.errors import ConvertError frame_kwargs = {} # Frame name (string) or frame class? Coerce into an instance. try: frame = _get_frame_class(frame)() except Exception: pass if isinstance(frame, SkyCoord): frame = frame.frame # Change to underlying coord frame instance if isinstance(frame, BaseCoordinateFrame): new_frame_cls = frame.__class__ # Get frame attributes, allowing defaults to be overridden by # explicitly set attributes of the source if ``merge_attributes``. for attr in frame_transform_graph.frame_attributes: self_val = getattr(self, attr, None) frame_val = getattr(frame, attr, None) if (frame_val is not None and not (merge_attributes and frame.is_frame_attr_default(attr))): frame_kwargs[attr] = frame_val elif (self_val is not None and not self.is_frame_attr_default(attr)): frame_kwargs[attr] = self_val elif frame_val is not None: frame_kwargs[attr] = frame_val else: raise ValueError('Transform `frame` must be a frame name, class, or instance') # Get the composite transform to the new frame trans = frame_transform_graph.get_transform(self.frame.__class__, new_frame_cls) if trans is None: raise ConvertError('Cannot transform from {0} to {1}' .format(self.frame.__class__, new_frame_cls)) # Make a generic frame which will accept all the frame kwargs that # are provided and allow for transforming through intermediate frames # which may require one or more of those kwargs. generic_frame = GenericFrame(frame_kwargs) # Do the transformation, returning a coordinate frame of the desired # final type (not generic). new_coord = trans(self.frame, generic_frame) # Finally make the new SkyCoord object from the `new_coord` and # remaining frame_kwargs that are not frame_attributes in `new_coord`. for attr in (set(new_coord.get_frame_attr_names()) & set(frame_kwargs.keys())): frame_kwargs.pop(attr) return self.__class__(new_coord, **frame_kwargs) def apply_space_motion(self, new_obstime=None, dt=None): """ Compute the position of the source represented by this coordinate object to a new time using the velocities stored in this object and assuming linear space motion (including relativistic corrections). This is sometimes referred to as an "epoch transformation." The initial time before the evolution is taken from the ``obstime`` attribute of this coordinate. Note that this method currently does not support evolving coordinates where the *frame* has an ``obstime`` frame attribute, so the ``obstime`` is only used for storing the before and after times, not actually as an attribute of the frame. Alternatively, if ``dt`` is given, an ``obstime`` need not be provided at all. Parameters ---------- new_obstime : `~astropy.time.Time`, optional The time at which to evolve the position to. Requires that the ``obstime`` attribute be present on this frame. dt : `~astropy.units.Quantity`, `~astropy.time.TimeDelta`, optional An amount of time to evolve the position of the source. Cannot be given at the same time as ``new_obstime``. Returns ------- new_coord : `SkyCoord` A new coordinate object with the evolved location of this coordinate at the new time. ``obstime`` will be set on this object to the new time only if ``self`` also has ``obstime``. """ if (new_obstime is None and dt is None or new_obstime is not None and dt is not None): raise ValueError("You must specify one of `new_obstime` or `dt`, " "but not both.") # Validate that we have velocity info if 's' not in self.frame.data.differentials: raise ValueError('SkyCoord requires velocity data to evolve the ' 'position.') if 'obstime' in self.frame.frame_attributes: raise NotImplementedError("Updating the coordinates in a frame " "with explicit time dependence is " "currently not supported. If you would " "like this functionality, please open an " "issue on github:\n" "https://github.com/astropy/astropy") if new_obstime is not None and self.obstime is None: # If no obstime is already on this object, raise an error if a new # obstime is passed: we need to know the time / epoch at which the # the position / velocity were measured initially raise ValueError('This object has no associated `obstime`. ' 'apply_space_motion() must receive a time ' 'difference, `dt`, and not a new obstime.') # Compute t1 and t2, the times used in the starpm call, which *only* # uses them to compute a delta-time t1 = self.obstime if dt is None: # self.obstime is not None and new_obstime is not None b/c of above # checks t2 = new_obstime else: # new_obstime is definitely None b/c of the above checks if t1 is None: # MAGIC NUMBER: if the current SkyCoord object has no obstime, # assume J2000 to do the dt offset. This is not actually used # for anything except a delta-t in starpm, so it's OK that it's # not necessarily the "real" obstime t1 = Time('J2000') new_obstime = None # we don't actually know the inital obstime t2 = t1 + dt else: t2 = t1 + dt new_obstime = t2 # starpm wants tdb time t1 = t1.tdb t2 = t2.tdb # proper motion in RA should not include the cos(dec) term, see the # erfa function eraStarpv, comment (4). So we convert to the regular # spherical differentials. icrsrep = self.icrs.represent_as(SphericalRepresentation, SphericalDifferential) icrsvel = icrsrep.differentials['s'] try: plx = icrsrep.distance.to_value(u.arcsecond, u.parallax()) except u.UnitConversionError: # No distance: set to 0 by starpm convention plx = 0. try: rv = icrsvel.d_distance.to_value(u.km/u.s) except u.UnitConversionError: # No RV rv = 0. starpm = erfa.starpm(icrsrep.lon.radian, icrsrep.lat.radian, icrsvel.d_lon.to_value(u.radian/u.yr), icrsvel.d_lat.to_value(u.radian/u.yr), plx, rv, t1.jd1, t1.jd2, t2.jd1, t2.jd2) icrs2 = ICRS(ra=u.Quantity(starpm[0], u.radian, copy=False), dec=u.Quantity(starpm[1], u.radian, copy=False), pm_ra=u.Quantity(starpm[2], u.radian/u.yr, copy=False), pm_dec=u.Quantity(starpm[3], u.radian/u.yr, copy=False), distance=Distance(parallax=starpm[4] * u.arcsec, copy=False), radial_velocity=u.Quantity(starpm[5], u.km/u.s, copy=False), differential_type=SphericalDifferential) # Update the obstime of the returned SkyCoord, and need to carry along # the frame attributes frattrs = {attrnm: getattr(self, attrnm) for attrnm in self._extra_frameattr_names} frattrs['obstime'] = new_obstime return self.__class__(icrs2, **frattrs).transform_to(self.frame) def __getattr__(self, attr): """ Overrides getattr to return coordinates that this can be transformed to, based on the alias attr in the master transform graph. """ if '_sky_coord_frame' in self.__dict__: if self.frame.name == attr: return self # Should this be a deepcopy of self? # Anything in the set of all possible frame_attr_names is handled # here. If the attr is relevant for the current frame then delegate # to self.frame otherwise get it from self._<attr>. if attr in frame_transform_graph.frame_attributes: if attr in self.frame.get_frame_attr_names(): return getattr(self.frame, attr) else: return getattr(self, '_' + attr, None) # Some attributes might not fall in the above category but still # are available through self._sky_coord_frame. if not attr.startswith('_') and hasattr(self._sky_coord_frame, attr): return getattr(self._sky_coord_frame, attr) # Try to interpret as a new frame for transforming. frame_cls = frame_transform_graph.lookup_name(attr) if frame_cls is not None and self.frame.is_transformable_to(frame_cls): return self.transform_to(attr) # Fail raise AttributeError("'{0}' object has no attribute '{1}'" .format(self.__class__.__name__, attr)) def __setattr__(self, attr, val): # This is to make anything available through __getattr__ immutable if '_sky_coord_frame' in self.__dict__: if self.frame.name == attr: raise AttributeError("'{0}' is immutable".format(attr)) if not attr.startswith('_') and hasattr(self._sky_coord_frame, attr): setattr(self._sky_coord_frame, attr, val) return frame_cls = frame_transform_graph.lookup_name(attr) if frame_cls is not None and self.frame.is_transformable_to(frame_cls): raise AttributeError("'{0}' is immutable".format(attr)) if attr in frame_transform_graph.frame_attributes: # All possible frame attributes can be set, but only via a private # variable. See __getattr__ above. super().__setattr__('_' + attr, val) # Validate it frame_transform_graph.frame_attributes[attr].__get__(self) # And add to set of extra attributes self._extra_frameattr_names |= {attr} else: # Otherwise, do the standard Python attribute setting super().__setattr__(attr, val) def __delattr__(self, attr): # mirror __setattr__ above if '_sky_coord_frame' in self.__dict__: if self.frame.name == attr: raise AttributeError("'{0}' is immutable".format(attr)) if not attr.startswith('_') and hasattr(self._sky_coord_frame, attr): delattr(self._sky_coord_frame, attr) return frame_cls = frame_transform_graph.lookup_name(attr) if frame_cls is not None and self.frame.is_transformable_to(frame_cls): raise AttributeError("'{0}' is immutable".format(attr)) if attr in frame_transform_graph.frame_attributes: # All possible frame attributes can be deleted, but need to remove # the corresponding private variable. See __getattr__ above. super().__delattr__('_' + attr) # Also remove it from the set of extra attributes self._extra_frameattr_names -= {attr} else: # Otherwise, do the standard Python attribute setting super().__delattr__(attr) @override__dir__ def __dir__(self): """ Override the builtin `dir` behavior to include: - Transforms available by aliases - Attribute / methods of the underlying self.frame object """ # determine the aliases that this can be transformed to. dir_values = set() for name in frame_transform_graph.get_names(): frame_cls = frame_transform_graph.lookup_name(name) if self.frame.is_transformable_to(frame_cls): dir_values.add(name) # Add public attributes of self.frame dir_values.update(set(attr for attr in dir(self.frame) if not attr.startswith('_'))) # Add all possible frame attributes dir_values.update(frame_transform_graph.frame_attributes.keys()) return dir_values def __repr__(self): clsnm = self.__class__.__name__ coonm = self.frame.__class__.__name__ frameattrs = self.frame._frame_attrs_repr() if frameattrs: frameattrs = ': ' + frameattrs data = self.frame._data_repr() if data: data = ': ' + data return '<{clsnm} ({coonm}{frameattrs}){data}>'.format(**locals()) def to_string(self, style='decimal', **kwargs): """ A string representation of the coordinates. The default styles definitions are:: 'decimal': 'lat': {'decimal': True, 'unit': "deg"} 'lon': {'decimal': True, 'unit': "deg"} 'dms': 'lat': {'unit': "deg"} 'lon': {'unit': "deg"} 'hmsdms': 'lat': {'alwayssign': True, 'pad': True, 'unit': "deg"} 'lon': {'pad': True, 'unit': "hour"} See :meth:`~astropy.coordinates.Angle.to_string` for details and keyword arguments (the two angles forming the coordinates are are both :class:`~astropy.coordinates.Angle` instances). Keyword arguments have precedence over the style defaults and are passed to :meth:`~astropy.coordinates.Angle.to_string`. Parameters ---------- style : {'hmsdms', 'dms', 'decimal'} The formatting specification to use. These encode the three most common ways to represent coordinates. The default is `decimal`. kwargs Keyword args passed to :meth:`~astropy.coordinates.Angle.to_string`. """ sph_coord = self.frame.represent_as(SphericalRepresentation) styles = {'hmsdms': {'lonargs': {'unit': u.hour, 'pad': True}, 'latargs': {'unit': u.degree, 'pad': True, 'alwayssign': True}}, 'dms': {'lonargs': {'unit': u.degree}, 'latargs': {'unit': u.degree}}, 'decimal': {'lonargs': {'unit': u.degree, 'decimal': True}, 'latargs': {'unit': u.degree, 'decimal': True}} } lonargs = {} latargs = {} if style in styles: lonargs.update(styles[style]['lonargs']) latargs.update(styles[style]['latargs']) else: raise ValueError('Invalid style. Valid options are: {0}'.format(",".join(styles))) lonargs.update(kwargs) latargs.update(kwargs) if np.isscalar(sph_coord.lon.value): coord_string = (sph_coord.lon.to_string(**lonargs) + " " + sph_coord.lat.to_string(**latargs)) else: coord_string = [] for lonangle, latangle in zip(sph_coord.lon.ravel(), sph_coord.lat.ravel()): coord_string += [(lonangle.to_string(**lonargs) + " " + latangle.to_string(**latargs))] if len(sph_coord.shape) > 1: coord_string = np.array(coord_string).reshape(sph_coord.shape) return coord_string def is_equivalent_frame(self, other): """ Checks if this object's frame as the same as that of the ``other`` object. To be the same frame, two objects must be the same frame class and have the same frame attributes. For two `SkyCoord` objects, *all* of the frame attributes have to match, not just those relevant for the object's frame. Parameters ---------- other : SkyCoord or BaseCoordinateFrame The other object to check. Returns ------- isequiv : bool True if the frames are the same, False if not. Raises ------ TypeError If ``other`` isn't a `SkyCoord` or a `BaseCoordinateFrame` or subclass. """ if isinstance(other, BaseCoordinateFrame): return self.frame.is_equivalent_frame(other) elif isinstance(other, SkyCoord): if other.frame.name != self.frame.name: return False for fattrnm in frame_transform_graph.frame_attributes: if np.any(getattr(self, fattrnm) != getattr(other, fattrnm)): return False return True else: # not a BaseCoordinateFrame nor a SkyCoord object raise TypeError("Tried to do is_equivalent_frame on something that " "isn't frame-like") # High-level convenience methods def separation(self, other): """ Computes on-sky separation between this coordinate and another. .. note:: If the ``other`` coordinate object is in a different frame, it is first transformed to the frame of this object. This can lead to unintutive behavior if not accounted for. Particularly of note is that ``self.separation(other)`` and ``other.separation(self)`` may not give the same answer in this case. For more on how to use this (and related) functionality, see the examples in :doc:`/coordinates/matchsep`. Parameters ---------- other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The coordinate to get the separation to. Returns ------- sep : `~astropy.coordinates.Angle` The on-sky separation between this and the ``other`` coordinate. Notes ----- The separation is calculated using the Vincenty formula, which is stable at all locations, including poles and antipodes [1]_. .. [1] https://en.wikipedia.org/wiki/Great-circle_distance """ from . import Angle from .angle_utilities import angular_separation if not self.is_equivalent_frame(other): try: other = other.transform_to(self, merge_attributes=False) except TypeError: raise TypeError('Can only get separation to another SkyCoord ' 'or a coordinate frame with data') lon1 = self.spherical.lon lat1 = self.spherical.lat lon2 = other.spherical.lon lat2 = other.spherical.lat # Get the separation as a Quantity, convert to Angle in degrees sep = angular_separation(lon1, lat1, lon2, lat2) return Angle(sep, unit=u.degree) def separation_3d(self, other): """ Computes three dimensional separation between this coordinate and another. For more on how to use this (and related) functionality, see the examples in :doc:`/coordinates/matchsep`. Parameters ---------- other : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The coordinate to get the separation to. Returns ------- sep : `~astropy.coordinates.Distance` The real-space distance between these two coordinates. Raises ------ ValueError If this or the other coordinate do not have distances. """ if not self.is_equivalent_frame(other): try: other = other.transform_to(self, merge_attributes=False) except TypeError: raise TypeError('Can only get separation to another SkyCoord ' 'or a coordinate frame with data') if issubclass(self.data.__class__, UnitSphericalRepresentation): raise ValueError('This object does not have a distance; cannot ' 'compute 3d separation.') if issubclass(other.data.__class__, UnitSphericalRepresentation): raise ValueError('The other object does not have a distance; ' 'cannot compute 3d separation.') return Distance((self.cartesian - other.cartesian).norm()) def spherical_offsets_to(self, tocoord): r""" Computes angular offsets to go *from* this coordinate *to* another. Parameters ---------- tocoord : `~astropy.coordinates.BaseCoordinateFrame` The coordinate to offset to. Returns ------- lon_offset : `~astropy.coordinates.Angle` The angular offset in the longitude direction (i.e., RA for equatorial coordinates). lat_offset : `~astropy.coordinates.Angle` The angular offset in the latitude direction (i.e., Dec for equatorial coordinates). Raises ------ ValueError If the ``tocoord`` is not in the same frame as this one. This is different from the behavior of the `separation`/`separation_3d` methods because the offset components depend critically on the specific choice of frame. Notes ----- This uses the sky offset frame machinery, and hence will produce a new sky offset frame if one does not already exist for this object's frame class. See Also -------- separation : for the *total* angular offset (not broken out into components) """ if not self.is_equivalent_frame(tocoord): raise ValueError('Tried to use spherical_offsets_to with two non-matching frames!') aframe = self.skyoffset_frame() acoord = tocoord.transform_to(aframe) dlon = acoord.spherical.lon.view(Angle) dlat = acoord.spherical.lat.view(Angle) return dlon, dlat def match_to_catalog_sky(self, catalogcoord, nthneighbor=1): """ Finds the nearest on-sky matches of this coordinate in a set of catalog coordinates. For more on how to use this (and related) functionality, see the examples in :doc:`/coordinates/matchsep`. Parameters ---------- catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The base catalog in which to search for matches. Typically this will be a coordinate object that is an array (i.e., ``catalogcoord.isscalar == False``) nthneighbor : int, optional Which closest neighbor to search for. Typically ``1`` is desired here, as that is correct for matching one set of coordinates to another. The next likely use case is ``2``, for matching a coordinate catalog against *itself* (``1`` is inappropriate because each point will find itself as the closest match). Returns ------- idx : integer array Indices into ``catalogcoord`` to get the matched points for each of this object's coordinates. Shape matches this object. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the closest match for each element in this object in ``catalogcoord``. Shape matches this object. dist3d : `~astropy.units.Quantity` The 3D distance between the closest match for each element in this object in ``catalogcoord``. Shape matches this object. Unless both this and ``catalogcoord`` have associated distances, this quantity assumes that all sources are at a distance of 1 (dimensionless). Notes ----- This method requires `SciPy <https://www.scipy.org/>`_ to be installed or it will fail. See Also -------- astropy.coordinates.match_coordinates_sky SkyCoord.match_to_catalog_3d """ from .matching import match_coordinates_sky if (isinstance(catalogcoord, (SkyCoord, BaseCoordinateFrame)) and catalogcoord.has_data): self_in_catalog_frame = self.transform_to(catalogcoord) else: raise TypeError('Can only get separation to another SkyCoord or a ' 'coordinate frame with data') res = match_coordinates_sky(self_in_catalog_frame, catalogcoord, nthneighbor=nthneighbor, storekdtree='_kdtree_sky') return res def match_to_catalog_3d(self, catalogcoord, nthneighbor=1): """ Finds the nearest 3-dimensional matches of this coordinate to a set of catalog coordinates. This finds the 3-dimensional closest neighbor, which is only different from the on-sky distance if ``distance`` is set in this object or the ``catalogcoord`` object. For more on how to use this (and related) functionality, see the examples in :doc:`/coordinates/matchsep`. Parameters ---------- catalogcoord : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The base catalog in which to search for matches. Typically this will be a coordinate object that is an array (i.e., ``catalogcoord.isscalar == False``) nthneighbor : int, optional Which closest neighbor to search for. Typically ``1`` is desired here, as that is correct for matching one set of coordinates to another. The next likely use case is ``2``, for matching a coordinate catalog against *itself* (``1`` is inappropriate because each point will find itself as the closest match). Returns ------- idx : integer array Indices into ``catalogcoord`` to get the matched points for each of this object's coordinates. Shape matches this object. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the closest match for each element in this object in ``catalogcoord``. Shape matches this object. dist3d : `~astropy.units.Quantity` The 3D distance between the closest match for each element in this object in ``catalogcoord``. Shape matches this object. Notes ----- This method requires `SciPy <https://www.scipy.org/>`_ to be installed or it will fail. See Also -------- astropy.coordinates.match_coordinates_3d SkyCoord.match_to_catalog_sky """ from .matching import match_coordinates_3d if (isinstance(catalogcoord, (SkyCoord, BaseCoordinateFrame)) and catalogcoord.has_data): self_in_catalog_frame = self.transform_to(catalogcoord) else: raise TypeError('Can only get separation to another SkyCoord or a ' 'coordinate frame with data') res = match_coordinates_3d(self_in_catalog_frame, catalogcoord, nthneighbor=nthneighbor, storekdtree='_kdtree_3d') return res def search_around_sky(self, searcharoundcoords, seplimit): """ Searches for all coordinates in this object around a supplied set of points within a given on-sky separation. This is intended for use on `~astropy.coordinates.SkyCoord` objects with coordinate arrays, rather than a scalar coordinate. For a scalar coordinate, it is better to use `~astropy.coordinates.SkyCoord.separation`. For more on how to use this (and related) functionality, see the examples in :doc:`/coordinates/matchsep`. Parameters ---------- searcharoundcoords : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The coordinates to search around to try to find matching points in this `SkyCoord`. This should be an object with array coordinates, not a scalar coordinate object. seplimit : `~astropy.units.Quantity` with angle units The on-sky separation to search within. Returns ------- idxsearcharound : integer array Indices into ``self`` that matches to the corresponding element of ``idxself``. Shape matches ``idxself``. idxself : integer array Indices into ``searcharoundcoords`` that matches to the corresponding element of ``idxsearcharound``. Shape matches ``idxsearcharound``. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the coordinates. Shape matches ``idxsearcharound`` and ``idxself``. dist3d : `~astropy.units.Quantity` The 3D distance between the coordinates. Shape matches ``idxsearcharound`` and ``idxself``. Notes ----- This method requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be installed or it will fail. In the current implementation, the return values are always sorted in the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is in ascending order). This is considered an implementation detail, though, so it could change in a future release. See Also -------- astropy.coordinates.search_around_sky SkyCoord.search_around_3d """ from .matching import search_around_sky return search_around_sky(searcharoundcoords, self, seplimit, storekdtree='_kdtree_sky') def search_around_3d(self, searcharoundcoords, distlimit): """ Searches for all coordinates in this object around a supplied set of points within a given 3D radius. This is intended for use on `~astropy.coordinates.SkyCoord` objects with coordinate arrays, rather than a scalar coordinate. For a scalar coordinate, it is better to use `~astropy.coordinates.SkyCoord.separation_3d`. For more on how to use this (and related) functionality, see the examples in :doc:`/coordinates/matchsep`. Parameters ---------- searcharoundcoords : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The coordinates to search around to try to find matching points in this `SkyCoord`. This should be an object with array coordinates, not a scalar coordinate object. distlimit : `~astropy.units.Quantity` with distance units The physical radius to search within. Returns ------- idxsearcharound : integer array Indices into ``self`` that matches to the corresponding element of ``idxself``. Shape matches ``idxself``. idxself : integer array Indices into ``searcharoundcoords`` that matches to the corresponding element of ``idxsearcharound``. Shape matches ``idxsearcharound``. sep2d : `~astropy.coordinates.Angle` The on-sky separation between the coordinates. Shape matches ``idxsearcharound`` and ``idxself``. dist3d : `~astropy.units.Quantity` The 3D distance between the coordinates. Shape matches ``idxsearcharound`` and ``idxself``. Notes ----- This method requires `SciPy <https://www.scipy.org/>`_ (>=0.12.0) to be installed or it will fail. In the current implementation, the return values are always sorted in the same order as the ``searcharoundcoords`` (so ``idxsearcharound`` is in ascending order). This is considered an implementation detail, though, so it could change in a future release. See Also -------- astropy.coordinates.search_around_3d SkyCoord.search_around_sky """ from .matching import search_around_3d return search_around_3d(searcharoundcoords, self, distlimit, storekdtree='_kdtree_3d') def position_angle(self, other): """ Computes the on-sky position angle (East of North) between this `SkyCoord` and another. Parameters ---------- other : `SkyCoord` The other coordinate to compute the position angle to. It is treated as the "head" of the vector of the position angle. Returns ------- pa : `~astropy.coordinates.Angle` The (positive) position angle of the vector pointing from ``self`` to ``other``. If either ``self`` or ``other`` contain arrays, this will be an array following the appropriate `numpy` broadcasting rules. Examples -------- >>> c1 = SkyCoord(0*u.deg, 0*u.deg) >>> c2 = SkyCoord(1*u.deg, 0*u.deg) >>> c1.position_angle(c2).degree 90.0 >>> c3 = SkyCoord(1*u.deg, 1*u.deg) >>> c1.position_angle(c3).degree # doctest: +FLOAT_CMP 44.995636455344844 """ from . import angle_utilities if not self.is_equivalent_frame(other): try: other = other.transform_to(self, merge_attributes=False) except TypeError: raise TypeError('Can only get position_angle to another ' 'SkyCoord or a coordinate frame with data') slat = self.represent_as(UnitSphericalRepresentation).lat slon = self.represent_as(UnitSphericalRepresentation).lon olat = other.represent_as(UnitSphericalRepresentation).lat olon = other.represent_as(UnitSphericalRepresentation).lon return angle_utilities.position_angle(slon, slat, olon, olat) def skyoffset_frame(self, rotation=None): """ Returns the sky offset frame with this `SkyCoord` at the origin. Returns ------- astrframe : `~astropy.coordinates.SkyOffsetFrame` A sky offset frame of the same type as this `SkyCoord` (e.g., if this object has an ICRS coordinate, the resulting frame is SkyOffsetICRS, with the origin set to this object) 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. """ return SkyOffsetFrame(origin=self, rotation=rotation) def get_constellation(self, short_name=False, constellation_list='iau'): """ Determines the constellation(s) of the coordinates this `SkyCoord` contains. Parameters ---------- short_name : bool If True, the returned names are the IAU-sanctioned abbreviated names. Otherwise, full names for the constellations are used. constellation_list : str The set of constellations to use. Currently only ``'iau'`` is supported, meaning the 88 "modern" constellations endorsed by the IAU. Returns ------- constellation : str or string array If this is a scalar coordinate, returns the name of the constellation. If it is an array `SkyCoord`, it returns an array of names. Notes ----- To determine which constellation a point on the sky is in, this first precesses to B1875, and then uses the Delporte boundaries of the 88 modern constellations, as tabulated by `Roman 1987 <http://cdsarc.u-strasbg.fr/viz-bin/Cat?VI/42>`_. See Also -------- astropy.coordinates.get_constellation """ from .funcs import get_constellation # because of issue #7028, the conversion to a PrecessedGeocentric # system fails in some cases. Work around is to drop the velocities. # they are not needed here since only position infromation is used extra_frameattrs = {nm: getattr(self, nm) for nm in self._extra_frameattr_names} novel = SkyCoord(self.realize_frame(self.data.without_differentials()), **extra_frameattrs) return get_constellation(novel, short_name, constellation_list) # the simpler version below can be used when gh-issue #7028 is resolved #return get_constellation(self, short_name, constellation_list) # WCS pixel to/from sky conversions def to_pixel(self, wcs, origin=0, mode='all'): """ Convert this coordinate to pixel coordinates using a `~astropy.wcs.WCS` object. Parameters ---------- wcs : `~astropy.wcs.WCS` The WCS to use for convert origin : int Whether to return 0 or 1-based pixel coordinates. mode : 'all' or 'wcs' Whether to do the transformation including distortions (``'all'``) or only including only the core WCS transformation (``'wcs'``). Returns ------- xp, yp : `numpy.ndarray` The pixel coordinates See Also -------- astropy.wcs.utils.skycoord_to_pixel : the implementation of this method """ return skycoord_to_pixel(self, wcs=wcs, origin=origin, mode=mode) @classmethod def from_pixel(cls, xp, yp, wcs, origin=0, mode='all'): """ Create a new `SkyCoord` from pixel coordinates using an `~astropy.wcs.WCS` object. Parameters ---------- xp, yp : float or `numpy.ndarray` The coordinates to convert. wcs : `~astropy.wcs.WCS` The WCS to use for convert origin : int Whether to return 0 or 1-based pixel coordinates. mode : 'all' or 'wcs' Whether to do the transformation including distortions (``'all'``) or only including only the core WCS transformation (``'wcs'``). Returns ------- coord : an instance of this class A new object with sky coordinates corresponding to the input ``xp`` and ``yp``. See Also -------- to_pixel : to do the inverse operation astropy.wcs.utils.pixel_to_skycoord : the implementation of this method """ return pixel_to_skycoord(xp, yp, wcs=wcs, origin=origin, mode=mode, cls=cls) def radial_velocity_correction(self, kind='barycentric', obstime=None, location=None): """ Compute the correction required to convert a radial velocity at a given time and place on the Earth's Surface to a barycentric or heliocentric velocity. Parameters ---------- kind : str The kind of velocity correction. Must be 'barycentric' or 'heliocentric'. obstime : `~astropy.time.Time` or None, optional The time at which to compute the correction. If `None`, the ``obstime`` frame attribute on the `SkyCoord` will be used. location : `~astropy.coordinates.EarthLocation` or None, optional The observer location at which to compute the correction. If `None`, the ``location`` frame attribute on the passed-in ``obstime`` will be used, and if that is None, the ``location`` frame attribute on the `SkyCoord` will be used. Raises ------ ValueError If either ``obstime`` or ``location`` are passed in (not ``None``) when the frame attribute is already set on this `SkyCoord`. TypeError If ``obstime`` or ``location`` aren't provided, either as arguments or as frame attributes. Returns ------- vcorr : `~astropy.units.Quantity` with velocity units The correction with a positive sign. I.e., *add* this to an observed radial velocity to get the barycentric (or heliocentric) velocity. If m/s precision or better is needed, see the notes below. Notes ----- The barycentric correction is calculated to higher precision than the heliocentric correction and includes additional physics (e.g time dilation). Use barycentric corrections if m/s precision is required. The algorithm here is sufficient to perform corrections at the mm/s level, but care is needed in application. Strictly speaking, the barycentric correction is multiplicative and should be applied as:: sc = SkyCoord(1*u.deg, 2*u.deg) vcorr = sc.rv_correction(kind='barycentric', obstime=t, location=loc) rv = rv + vcorr + rv * vcorr / consts.c If your target is nearby and/or has finite proper motion you may need to account for terms arising from this. See Wright & Eastmann (2014) for details. The default is for this method to use the builtin ephemeris for computing the sun and earth location. Other ephemerides can be chosen by setting the `~astropy.coordinates.solar_system_ephemeris` variable, either directly or via ``with`` statement. For example, to use the JPL ephemeris, do:: sc = SkyCoord(1*u.deg, 2*u.deg) with coord.solar_system_ephemeris.set('jpl'): rv += sc.rv_correction(obstime=t, location=loc) """ # has to be here to prevent circular imports from .solar_system import get_body_barycentric_posvel, get_body_barycentric # location validation timeloc = getattr(obstime, 'location', None) if location is None: if self.location is not None: location = self.location if timeloc is not None: raise ValueError('`location` cannot be in both the ' 'passed-in `obstime` and this `SkyCoord` ' 'because it is ambiguous which is meant ' 'for the radial_velocity_correction.') elif timeloc is not None: location = timeloc else: raise TypeError('Must provide a `location` to ' 'radial_velocity_correction, either as a ' 'SkyCoord frame attribute, as an attribute on ' 'the passed in `obstime`, or in the method ' 'call.') elif self.location is not None or timeloc is not None: raise ValueError('Cannot compute radial velocity correction if ' '`location` argument is passed in and there is ' 'also a `location` attribute on this SkyCoord or ' 'the passed-in `obstime`.') # obstime validation if obstime is None: obstime = self.obstime if obstime is None: raise TypeError('Must provide an `obstime` to ' 'radial_velocity_correction, either as a ' 'SkyCoord frame attribute or in the method ' 'call.') elif self.obstime is not None: raise ValueError('Cannot compute radial velocity correction if ' '`obstime` argument is passed in and it is ' 'inconsistent with the `obstime` frame ' 'attribute on the SkyCoord') pos_earth, v_earth = get_body_barycentric_posvel('earth', obstime) if kind == 'barycentric': v_origin_to_earth = v_earth elif kind == 'heliocentric': v_sun = get_body_barycentric_posvel('sun', obstime)[1] v_origin_to_earth = v_earth - v_sun else: raise ValueError("`kind` argument to radial_velocity_correction must " "be 'barycentric' or 'heliocentric', but got " "'{}'".format(kind)) gcrs_p, gcrs_v = location.get_gcrs_posvel(obstime) # transforming to GCRS is not the correct thing to do here, since we don't want to # include aberration (or light deflection)? Instead, only apply parallax if necessary if self.data.__class__ is UnitSphericalRepresentation: targcart = self.icrs.cartesian else: # skycoord has distances so apply parallax obs_icrs_cart = pos_earth + gcrs_p icrs_cart = self.icrs.cartesian targcart = icrs_cart - obs_icrs_cart targcart /= targcart.norm() if kind == 'barycentric': beta_obs = (v_origin_to_earth + gcrs_v) / speed_of_light gamma_obs = 1 / np.sqrt(1 - beta_obs.norm()**2) gr = location.gravitational_redshift(obstime) # barycentric redshift according to eq 28 in Wright & Eastmann (2014), # neglecting Shapiro delay and effects of the star's own motion zb = gamma_obs * (1 + targcart.dot(beta_obs)) / (1 + gr/speed_of_light) - 1 return zb * speed_of_light else: # do a simpler correction ignoring time dilation and gravitational redshift # this is adequate since Heliocentric corrections shouldn't be used if # cm/s precision is required. return targcart.dot(v_origin_to_earth + gcrs_v) # Table interactions @classmethod def guess_from_table(cls, table, **coord_kwargs): r""" A convenience method to create and return a new `SkyCoord` from the data in an astropy Table. This method matches table columns that start with the case-insensitive names of the the components of the requested frames, if they are also followed by a non-alphanumeric character. It will also match columns that *end* with the component name if a non-alphanumeric character is *before* it. For example, the first rule means columns with names like ``'RA[J2000]'`` or ``'ra'`` will be interpreted as ``ra`` attributes for `~astropy.coordinates.ICRS` frames, but ``'RAJ2000'`` or ``'radius'`` are *not*. Similarly, the second rule applied to the `~astropy.coordinates.Galactic` frame means that a column named ``'gal_l'`` will be used as the the ``l`` component, but ``gall`` or ``'fill'`` will not. The definition of alphanumeric here is based on Unicode's definition of alphanumeric, except without ``_`` (which is normally considered alphanumeric). So for ASCII, this means the non-alphanumeric characters are ``<space>_!"#$%&'()*+,-./\:;<=>?@[]^`{|}~``). Parameters ---------- table : astropy.Table The table to load data from. coord_kwargs Any additional keyword arguments are passed directly to this class's constructor. Returns ------- newsc : same as this class The new `SkyCoord` (or subclass) object. """ inital_frame = coord_kwargs.get('frame') frame = _get_frame([], coord_kwargs) coord_kwargs['frame'] = inital_frame comp_kwargs = {} for comp_name in frame.representation_component_names: # this matches things like 'ra[...]'' but *not* 'rad'. # note that the "_" must be in there explicitly, because # "alphanumeric" usually includes underscores. starts_with_comp = comp_name + r'(\W|\b|_)' # this part matches stuff like 'center_ra', but *not* # 'aura' ends_with_comp = r'.*(\W|\b|_)' + comp_name + r'\b' # the final regex ORs together the two patterns rex = re.compile('(' + starts_with_comp + ')|(' + ends_with_comp + ')', re.IGNORECASE | re.UNICODE) for col_name in table.colnames: if rex.match(col_name): if comp_name in comp_kwargs: oldname = comp_kwargs[comp_name].name msg = ('Found at least two matches for component "{0}"' ': "{1}" and "{2}". Cannot continue with this ' 'ambiguity.') raise ValueError(msg.format(comp_name, oldname, col_name)) comp_kwargs[comp_name] = table[col_name] for k, v in comp_kwargs.items(): if k in coord_kwargs: raise ValueError('Found column "{0}" in table, but it was ' 'already provided as "{1}" keyword to ' 'guess_from_table function.'.format(v.name, k)) else: coord_kwargs[k] = v return cls(**coord_kwargs) # Name resolve @classmethod def from_name(cls, name, frame='icrs'): """ Given a name, query the CDS name resolver to attempt to retrieve coordinate information for that object. The search database, sesame url, and query timeout can be set through configuration items in ``astropy.coordinates.name_resolve`` -- see docstring for `~astropy.coordinates.get_icrs_coordinates` for more information. Parameters ---------- name : str The name of the object to get coordinates for, e.g. ``'M42'``. frame : str or `BaseCoordinateFrame` class or instance The frame to transform the object to. Returns ------- coord : SkyCoord Instance of the SkyCoord class. """ from .name_resolve import get_icrs_coordinates icrs_coord = get_icrs_coordinates(name) icrs_sky_coord = cls(icrs_coord) if frame in ('icrs', icrs_coord.__class__): return icrs_sky_coord else: return icrs_sky_coord.transform_to(frame) # <----------------Private utility functions below here-------------------------> def _get_frame_class(frame): """ Get a frame class from the input `frame`, which could be a frame name string, or frame class. """ import inspect if isinstance(frame, str): frame_names = frame_transform_graph.get_names() if frame not in frame_names: raise ValueError('Coordinate frame {0} not in allowed values {1}' .format(frame, sorted(frame_names))) frame_cls = frame_transform_graph.lookup_name(frame) elif inspect.isclass(frame) and issubclass(frame, BaseCoordinateFrame): frame_cls = frame else: raise ValueError('Coordinate frame must be a frame name or frame class') return frame_cls def _get_frame(args, kwargs): """ Determine the coordinate frame from input SkyCoord args and kwargs. This modifies args and/or kwargs in-place to remove the item that provided `frame`. It also infers the frame if an input coordinate was provided and checks for conflicts. This allows for frame to be specified as a string like 'icrs' or a frame class like ICRS, but not an instance ICRS() since the latter could have non-default representation attributes which would require a three-way merge. """ frame = kwargs.pop('frame', None) if frame is None and len(args) > 1: # We do not allow frames to be passed as positional arguments if data # is passed separately from frame. for arg in args: if isinstance(arg, (SkyCoord, BaseCoordinateFrame)): raise ValueError("{0} instance cannot be passed as a positional " "argument for the frame, pass it using the " "frame= keyword instead.".format(arg.__class__.__name__)) # If the frame is an instance or SkyCoord, we split up the attributes and # make it into a class. if isinstance(frame, SkyCoord): # Copy any extra attributes if they are not explicitly given. for attr in frame._extra_frameattr_names: kwargs.setdefault(attr, getattr(frame, attr)) frame = frame.frame if isinstance(frame, BaseCoordinateFrame): for attr in frame.get_frame_attr_names(): if attr in kwargs: raise ValueError("cannot specify frame attribute '{0}' directly in SkyCoord since a frame instance was passed in".format(attr)) else: kwargs[attr] = getattr(frame, attr) frame = frame.__class__ if frame is not None: # Frame was provided as kwarg so validate and coerce into corresponding frame. frame_cls = _get_frame_class(frame) frame_specified_explicitly = True else: # Look for the frame in args for arg in args: try: frame_cls = _get_frame_class(arg) frame_specified_explicitly = True except ValueError: pass else: args.remove(arg) warnings.warn("Passing a frame as a positional argument is now " "deprecated, use the frame= keyword argument " "instead.", AstropyDeprecationWarning) break else: # Not in args nor kwargs - default to icrs frame_cls = ICRS frame_specified_explicitly = False # Check that the new frame doesn't conflict with existing coordinate frame # if a coordinate is supplied in the args list. If the frame still had not # been set by this point and a coordinate was supplied, then use that frame. for arg in args: # this catches the "single list passed in" case. For that case we want # to allow the first argument to set the class. That's OK because # _parse_coordinate_arg goes and checks that the frames match between # the first and all the others if (isinstance(arg, (collections.Sequence, np.ndarray)) and len(args) == 1 and len(arg) > 0): arg = arg[0] coord_frame_obj = coord_frame_cls = None if isinstance(arg, BaseCoordinateFrame): coord_frame_obj = arg elif isinstance(arg, SkyCoord): coord_frame_obj = arg.frame if coord_frame_obj is not None: coord_frame_cls = coord_frame_obj.__class__ frame_diff = coord_frame_obj.get_representation_cls('s') if frame_diff is not None: # we do this check because otherwise if there's no default # differential (i.e. it is None), the code below chokes. but # None still gets through if the user *requests* it kwargs.setdefault('differential_type', frame_diff) if coord_frame_cls is not None: if not frame_specified_explicitly: frame_cls = coord_frame_cls elif frame_cls is not coord_frame_cls: raise ValueError("Cannot override frame='{0}' of input coordinate with " "new frame='{1}'. Instead transform the coordinate." .format(coord_frame_cls.__name__, frame_cls.__name__)) frame_cls_kwargs = {} # TODO: deprecate representation, remove this in future _normalize_representation_type(kwargs) if 'representation_type' in kwargs: frame_cls_kwargs['representation_type'] = _get_repr_cls( kwargs['representation_type']) if 'differential_type' in kwargs: frame_cls_kwargs['differential_type'] = _get_diff_cls( kwargs['differential_type']) return frame_cls(**frame_cls_kwargs) def _get_representation_component_units(args, kwargs): """ Get the unit from kwargs for the *representation* components (not the differentials). """ if 'unit' not in kwargs: units = [None, None, None] else: units = kwargs.pop('unit') if isinstance(units, str): units = [x.strip() for x in units.split(',')] # Allow for input like unit='deg' or unit='m' if len(units) == 1: units = [units[0], units[0], units[0]] elif isinstance(units, (Unit, IrreducibleUnit)): units = [units, units, units] try: units = [(Unit(x) if x else None) for x in units] units.extend(None for x in range(3 - len(units))) if len(units) > 3: raise ValueError() except Exception: raise ValueError('Unit keyword must have one to three unit values as ' 'tuple or comma-separated string') return units def _parse_coordinate_arg(coords, frame, units, init_kwargs): """ Single unnamed arg supplied. This must be: - Coordinate frame with data - Representation - SkyCoord - List or tuple of: - String which splits into two values - Iterable with two values - SkyCoord, frame, or representation objects. Returns a dict mapping coordinate attribute names to values (or lists of values) """ is_scalar = False # Differentiate between scalar and list input valid_kwargs = {} # Returned dict of lon, lat, and distance (optional) frame_attr_names = list(frame.representation_component_names.keys()) repr_attr_names = list(frame.representation_component_names.values()) repr_attr_classes = list(frame.representation.attr_classes.values()) n_attr_names = len(repr_attr_names) # Turn a single string into a list of strings for convenience if isinstance(coords, str): is_scalar = True coords = [coords] if isinstance(coords, (SkyCoord, BaseCoordinateFrame)): # Note that during parsing of `frame` it is checked that any coordinate # args have the same frame as explicitly supplied, so don't worry here. if not coords.has_data: raise ValueError('Cannot initialize from a frame without coordinate data') data = coords.data.represent_as(frame.representation_type) values = [] # List of values corresponding to representation attrs repr_attr_name_to_drop = [] for repr_attr_name in repr_attr_names: # If coords did not have an explicit distance then don't include in initializers. if (isinstance(coords.data, UnitSphericalRepresentation) and repr_attr_name == 'distance'): repr_attr_name_to_drop.append(repr_attr_name) continue # Get the value from `data` in the eventual representation values.append(getattr(data, repr_attr_name)) # drop the ones that were skipped because they were distances for nametodrop in repr_attr_name_to_drop: nameidx = repr_attr_names.index(nametodrop) del repr_attr_names[nameidx] del units[nameidx] del frame_attr_names[nameidx] del repr_attr_classes[nameidx] if coords.data.differentials and 's' in coords.data.differentials: orig_vel = coords.data.differentials['s'] vel = coords.data.represent_as(frame.representation, frame.get_representation_cls('s')).differentials['s'] for frname, reprname in frame.get_representation_component_names('s').items(): if (reprname == 'd_distance' and not hasattr(orig_vel, reprname) and 'unit' in orig_vel.get_name()): continue values.append(getattr(vel, reprname)) units.append(None) frame_attr_names.append(frname) repr_attr_names.append(reprname) repr_attr_classes.append(vel.attr_classes[reprname]) for attr in frame_transform_graph.frame_attributes: value = getattr(coords, attr, None) use_value = (isinstance(coords, SkyCoord) or attr not in coords._attr_names_with_defaults) if use_value and value is not None: valid_kwargs[attr] = value elif isinstance(coords, BaseRepresentation): if coords.differentials and 's' in coords.differentials: diffs = frame.get_representation_cls('s') data = coords.represent_as(frame.representation_type, diffs) values = [getattr(data, repr_attr_name) for repr_attr_name in repr_attr_names] for frname, reprname in frame.get_representation_component_names('s').items(): values.append(getattr(data.differentials['s'], reprname)) units.append(None) frame_attr_names.append(frname) repr_attr_names.append(reprname) repr_attr_classes.append(data.differentials['s'].attr_classes[reprname]) else: data = coords.represent_as(frame.representation) values = [getattr(data, repr_attr_name) for repr_attr_name in repr_attr_names] elif (isinstance(coords, np.ndarray) and coords.dtype.kind in 'if' and coords.ndim == 2 and coords.shape[1] <= 3): # 2-d array of coordinate values. Handle specially for efficiency. values = coords.transpose() # Iterates over repr attrs elif isinstance(coords, (collections.Sequence, np.ndarray)): # Handles list-like input. vals = [] is_ra_dec_representation = ('ra' in frame.representation_component_names and 'dec' in frame.representation_component_names) coord_types = (SkyCoord, BaseCoordinateFrame, BaseRepresentation) if any(isinstance(coord, coord_types) for coord in coords): # this parsing path is used when there are coordinate-like objects # in the list - instead of creating lists of values, we create # SkyCoords from the list elements and then combine them. scs = [SkyCoord(coord, **init_kwargs) for coord in coords] # Check that all frames are equivalent for sc in scs[1:]: if not sc.is_equivalent_frame(scs[0]): raise ValueError("List of inputs don't have equivalent " "frames: {0} != {1}".format(sc, scs[0])) # Now use the first to determine if they are all UnitSpherical allunitsphrepr = isinstance(scs[0].data, UnitSphericalRepresentation) # get the frame attributes from the first coord in the list, because # from the above we know it matches all the others. First copy over # the attributes that are in the frame itself, then copy over any # extras in the SkyCoord for fattrnm in scs[0].frame.frame_attributes: valid_kwargs[fattrnm] = getattr(scs[0].frame, fattrnm) for fattrnm in scs[0]._extra_frameattr_names: valid_kwargs[fattrnm] = getattr(scs[0], fattrnm) # Now combine the values, to be used below values = [] for data_attr_name, repr_attr_name in zip(frame_attr_names, repr_attr_names): if allunitsphrepr and repr_attr_name == 'distance': # if they are *all* UnitSpherical, don't give a distance continue data_vals = [] for sc in scs: data_val = getattr(sc, data_attr_name) data_vals.append(data_val.reshape(1,) if sc.isscalar else data_val) concat_vals = np.concatenate(data_vals) # Hack because np.concatenate doesn't fully work with Quantity if isinstance(concat_vals, u.Quantity): concat_vals._unit = data_val.unit values.append(concat_vals) else: # none of the elements are "frame-like" # turn into a list of lists like [[v1_0, v2_0, v3_0], ... [v1_N, v2_N, v3_N]] for coord in coords: if isinstance(coord, str): coord1 = coord.split() if len(coord1) == 6: coord = (' '.join(coord1[:3]), ' '.join(coord1[3:])) elif is_ra_dec_representation: coord = _parse_ra_dec(coord) else: coord = coord1 vals.append(coord) # Assumes coord is a sequence at this point # Do some basic validation of the list elements: all have a length and all # lengths the same try: n_coords = sorted(set(len(x) for x in vals)) except Exception: raise ValueError('One or more elements of input sequence does not have a length') if len(n_coords) > 1: raise ValueError('Input coordinate values must have same number of elements, found {0}' .format(n_coords)) n_coords = n_coords[0] # Must have no more coord inputs than representation attributes if n_coords > n_attr_names: raise ValueError('Input coordinates have {0} values but ' 'representation {1} only accepts {2}' .format(n_coords, frame.representation_type.get_name(), n_attr_names)) # Now transpose vals to get [(v1_0 .. v1_N), (v2_0 .. v2_N), (v3_0 .. v3_N)] # (ok since we know it is exactly rectangular). (Note: can't just use zip(*values) # because Longitude et al distinguishes list from tuple so [a1, a2, ..] is needed # while (a1, a2, ..) doesn't work. values = [list(x) for x in zip(*vals)] if is_scalar: values = [x[0] for x in values] else: raise ValueError('Cannot parse coordinates from first argument') # Finally we have a list of values from which to create the keyword args # for the frame initialization. Validate by running through the appropriate # class initializer and supply units (which might be None). try: for frame_attr_name, repr_attr_class, value, unit in zip( frame_attr_names, repr_attr_classes, values, units): valid_kwargs[frame_attr_name] = repr_attr_class(value, unit=unit, copy=False) except Exception as err: raise ValueError('Cannot parse first argument data "{0}" for attribute ' '{1}'.format(value, frame_attr_name), err) return valid_kwargs def _get_representation_attrs(frame, units, kwargs): """ Find instances of the "representation attributes" for specifying data for this frame. Pop them off of kwargs, run through the appropriate class constructor (to validate and apply unit), and put into the output valid_kwargs. "Representation attributes" are the frame-specific aliases for the underlying data values in the representation, e.g. "ra" for "lon" for many equatorial spherical representations, or "w" for "x" in the cartesian representation of Galactic. This also gets any *differential* kwargs, because they go into the same frame initializer later on. """ frame_attr_names = frame.representation_component_names.keys() repr_attr_classes = frame.representation_type.attr_classes.values() valid_kwargs = {} for frame_attr_name, repr_attr_class, unit in zip(frame_attr_names, repr_attr_classes, units): value = kwargs.pop(frame_attr_name, None) if value is not None: valid_kwargs[frame_attr_name] = repr_attr_class(value, unit=unit) # also check the differentials. They aren't included in the units keyword, # so we only look for the names. differential_type = frame.differential_type if differential_type is not None: for frame_name, repr_name in frame.get_representation_component_names('s').items(): diff_attr_class = differential_type.attr_classes[repr_name] value = kwargs.pop(frame_name, None) if value is not None: valid_kwargs[frame_name] = diff_attr_class(value) return valid_kwargs def _parse_ra_dec(coord_str): """ Parse RA and Dec values from a coordinate string. Currently the following formats are supported: * space separated 6-value format * space separated <6-value format, this requires a plus or minus sign separation between RA and Dec * sign separated format * JHHMMSS.ss+DDMMSS.ss format, with up to two optional decimal digits * JDDDMMSS.ss+DDMMSS.ss format, with up to two optional decimal digits Parameters ---------- coord_str : str Coordinate string to parse. Returns ------- coord : str or list of str Parsed coordinate values. """ if isinstance(coord_str, str): coord1 = coord_str.split() else: # This exception should never be raised from SkyCoord raise TypeError('coord_str must be a single str') if len(coord1) == 6: coord = (' '.join(coord1[:3]), ' '.join(coord1[3:])) elif len(coord1) > 2: coord = PLUS_MINUS_RE.split(coord_str) coord = (coord[0], ' '.join(coord[1:])) elif len(coord1) == 1: match_j = J_PREFIXED_RA_DEC_RE.match(coord_str) if match_j: coord = match_j.groups() if len(coord[0].split('.')[0]) == 7: coord = ('{0} {1} {2}'. format(coord[0][0:3], coord[0][3:5], coord[0][5:]), '{0} {1} {2}'. format(coord[1][0:3], coord[1][3:5], coord[1][5:])) else: coord = ('{0} {1} {2}'. format(coord[0][0:2], coord[0][2:4], coord[0][4:]), '{0} {1} {2}'. format(coord[1][0:3], coord[1][3:5], coord[1][5:])) else: coord = PLUS_MINUS_RE.split(coord_str) coord = (coord[0], ' '.join(coord[1:])) else: coord = coord1 return coord
3d57bd82039526075c5eadcc77189cb2da0f1f123527ecd81ac945b636f65877
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst _tabversion = '3.8' _lextokens = set(('UINT', 'SIMPLE_UNIT', 'DEGREE', 'MINUTE', 'HOUR', 'COLON', 'UFLOAT', 'SIGN', 'SECOND')) _lexreflags = 0 _lexliterals = '' _lexstateinfo = {'INITIAL': 'inclusive'} _lexstatere = {'INITIAL': [('(?P<t_UFLOAT>((\\d+\\.\\d*)|(\\.\\d+))([eE][+-−]?\\d+)?)|(?P<t_UINT>\\d+)|(?P<t_SIGN>[+−-])|(?P<t_SIMPLE_UNIT>(?:karcsec)|(?:uarcsec)|(?:Earcmin)|(?:Zdeg)|(?:crad)|(?:cycle)|(?:hectoradian)|(?:Yarcmin)|(?:kiloarcsecond)|(?:zeptoarcminute)|(?:adeg)|(?:darcmin)|(?:ddeg)|(?:exaradian)|(?:parcsec)|(?:yoctoradian)|(?:arcsecond)|(?:petadegree)|(?:petaarcminute)|(?:microarcsecond)|(?:mas)|(?:parcmin)|(?:hdeg)|(?:narcmin)|(?:attodegree)|(?:kilodegree)|(?:zettaradian)|(?:fdeg)|(?:zeptoradian)|(?:microradian)|(?:Gdeg)|(?:hectodegree)|(?:attoarcsecond)|(?:Marcmin)|(?:exadegree)|(?:femtodegree)|(?:yottaradian)|(?:pdeg)|(?:zarcmin)|(?:kiloarcminute)|(?:urad)|(?:teraarcsecond)|(?:nrad)|(?:carcsec)|(?:Pdeg)|(?:Yrad)|(?:yrad)|(?:picoarcsecond)|(?:aarcsec)|(?:dekaradian)|(?:Zrad)|(?:femtoradian)|(?:yarcsec)|(?:arcmin)|(?:arcsec)|(?:yottadegree)|(?:drad)|(?:dekadegree)|(?:zdeg)|(?:zeptoarcsecond)|(?:farcmin)|(?:Parcmin)|(?:decaarcminute)|(?:nanoarcminute)|(?:nanoarcsecond)|(?:Tdeg)|(?:decaarcsecond)|(?:nanodegree)|(?:farcsec)|(?:femtoarcminute)|(?:microdegree)|(?:deciarcsecond)|(?:deciarcminute)|(?:attoradian)|(?:dadeg)|(?:decidegree)|(?:hectoarcminute)|(?:milliarcsecond)|(?:femtoarcsecond)|(?:megaarcminute)|(?:yoctoarcminute)|(?:zrad)|(?:hectoarcsecond)|(?:frad)|(?:centiarcsecond)|(?:carcmin)|(?:Garcmin)|(?:decadegree)|(?:Grad)|(?:petaarcsecond)|(?:gigaarcsecond)|(?:megaradian)|(?:Tarcsec)|(?:Prad)|(?:zettadegree)|(?:yottaarcminute)|(?:mrad)|(?:yottaarcsecond)|(?:exaarcminute)|(?:harcmin)|(?:dekaarcsecond)|(?:cy)|(?:ndeg)|(?:teraradian)|(?:teradegree)|(?:Zarcsec)|(?:gigadegree)|(?:Mdeg)|(?:Mrad)|(?:centiarcminute)|(?:uarcmin)|(?:picoradian)|(?:radian)|(?:ydeg)|(?:milliarcminute)|(?:deciradian)|(?:narcsec)|(?:Trad)|(?:picodegree)|(?:yoctodegree)|(?:zettaarcminute)|(?:daarcmin)|(?:arcminute)|(?:yarcmin)|(?:kdeg)|(?:Earcsec)|(?:Edeg)|(?:harcsec)|(?:rad)|(?:centidegree)|(?:Garcsec)|(?:marcsec)|(?:megaarcsecond)|(?:attoarcminute)|(?:cdeg)|(?:Erad)|(?:kiloradian)|(?:daarcsec)|(?:Parcsec)|(?:megadegree)|(?:millidegree)|(?:centiradian)|(?:uas)|(?:teraarcminute)|(?:prad)|(?:yoctoarcsecond)|(?:hrad)|(?:picoarcminute)|(?:petaradian)|(?:Marcsec)|(?:marcmin)|(?:Tarcmin)|(?:zeptodegree)|(?:Yarcsec)|(?:gigaarcminute)|(?:Zarcmin)|(?:arad)|(?:karcmin)|(?:darcsec)|(?:exaarcsecond)|(?:nanoradian)|(?:udeg)|(?:zarcsec)|(?:Ydeg)|(?:decaradian)|(?:milliradian)|(?:aarcmin)|(?:zettaarcsecond)|(?:darad)|(?:microarcminute)|(?:mdeg)|(?:dekaarcminute)|(?:krad)|(?:gigaradian))|(?P<t_MINUTE>m(in(ute(s)?)?)?|′|\\\'|ᵐ)|(?P<t_SECOND>s(ec(ond(s)?)?)?|″|\\"|ˢ)|(?P<t_DEGREE>d(eg(ree(s)?)?)?|°)|(?P<t_HOUR>hour(s)?|h(r)?|ʰ)|(?P<t_COLON>:)', [None, ('t_UFLOAT', 'UFLOAT'), None, None, None, None, ('t_UINT', 'UINT'), ('t_SIGN', 'SIGN'), ('t_SIMPLE_UNIT', 'SIMPLE_UNIT'), (None, 'MINUTE'), None, None, None, (None, 'SECOND'), None, None, None, (None, 'DEGREE'), None, None, None, (None, 'HOUR'), None, None, (None, 'COLON')])]} _lexstateignore = {'INITIAL': ' '} _lexstateerrorf = {'INITIAL': 't_error'} _lexstateeoff = {}
f13b284e1b4af4b5f637e038a57a4161a37c203f8fa67fd8b725c21bc19d50d3
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Currently the only site accessible without internet access is the Royal Greenwich Observatory, as an example (and for testing purposes). In future releases, a canonical set of sites may be bundled into astropy for when the online registry is unavailable. Additions or corrections to the observatory list can be submitted via Pull Request to the [astropy-data GitHub repository](https://github.com/astropy/astropy-data), updating the ``location.json`` file. """ import json from difflib import get_close_matches from collections import Mapping from ..utils.data import get_pkg_data_contents, get_file_contents from .earth import EarthLocation from .errors import UnknownSiteException from .. import units as u class SiteRegistry(Mapping): """ A bare-bones registry of EarthLocation objects. This acts as a mapping (dict-like object) but with the important caveat that it's always transforms its inputs to lower-case. So keys are always all lower-case, and even if you ask for something that's got mixed case, it will be interpreted as the all lower-case version. """ def __init__(self): # the keys to this are always lower-case self._lowercase_names_to_locations = {} # these can be whatever case is appropriate self._names = [] def __getitem__(self, site_name): """ Returns an EarthLocation for a known site in this registry. Parameters ---------- site_name : str Name of the observatory (case-insensitive). Returns ------- site : `~astropy.coordinates.EarthLocation` The location of the observatory. """ if site_name.lower() not in self._lowercase_names_to_locations: # If site name not found, find close matches and suggest them in error close_names = get_close_matches(site_name, self._lowercase_names_to_locations) close_names = sorted(close_names, key=len) raise UnknownSiteException(site_name, "the 'names' attribute", close_names=close_names) return self._lowercase_names_to_locations[site_name.lower()] def __len__(self): return len(self._lowercase_names_to_locations) def __iter__(self): return iter(self._lowercase_names_to_locations) def __contains__(self, site_name): return site_name.lower() in self._lowercase_names_to_locations @property def names(self): """ The names in this registry. Note that these are *not* exactly the same as the keys: keys are always lower-case, while `names` is what you should use for the actual readable names (which may be case-sensitive) Returns ------- site : list of str The names of the sites in this registry """ return sorted(self._names) def add_site(self, names, locationobj): """ Adds a location to the registry. Parameters ---------- names : list of str All the names this site should go under locationobj : `~astropy.coordinates.EarthLocation` The actual site object """ for name in names: self._lowercase_names_to_locations[name.lower()] = locationobj self._names.append(name) @classmethod def from_json(cls, jsondb): reg = cls() for site in jsondb: site_info = jsondb[site] location = EarthLocation.from_geodetic(site_info['longitude'] * u.Unit(site_info['longitude_unit']), site_info['latitude'] * u.Unit(site_info['latitude_unit']), site_info['elevation'] * u.Unit(site_info['elevation_unit'])) location.info.name = site_info['name'] reg.add_site([site] + site_info['aliases'], location) reg._loaded_jsondb = jsondb return reg def get_builtin_sites(): """ Load observatory database from data/observatories.json and parse them into a SiteRegistry. """ jsondb = json.loads(get_pkg_data_contents('data/sites.json')) return SiteRegistry.from_json(jsondb) def get_downloaded_sites(jsonurl=None): """ Load observatory database from data.astropy.org and parse into a SiteRegistry """ # we explicitly set the encoding because the default is to leave it set by # the users' locale, which may fail if it's not matched to the sites.json if jsonurl is None: content = get_pkg_data_contents('coordinates/sites.json', encoding='UTF-8') else: content = get_file_contents(jsonurl, encoding='UTF-8') jsondb = json.loads(content) return SiteRegistry.from_json(jsondb)
fcac04cd6c40af0e586bd6d5d8f1e744ac0f97d33b04512caefa95058b693acd
""" In this module, we define the coordinate representation classes, which are used to represent low-level cartesian, spherical, cylindrical, and other coordinates. """ import abc import functools import operator from collections import OrderedDict import inspect import warnings import numpy as np import astropy.units as u from .angles import Angle, Longitude, Latitude from .distances import Distance from ..utils import ShapedLikeNDArray, classproperty from ..utils import deprecated_attribute from ..utils.exceptions import AstropyDeprecationWarning from ..utils.misc import InheritDocstrings from ..utils.compat import NUMPY_LT_1_12, NUMPY_LT_1_14 __all__ = ["BaseRepresentationOrDifferential", "BaseRepresentation", "CartesianRepresentation", "SphericalRepresentation", "UnitSphericalRepresentation", "RadialRepresentation", "PhysicsSphericalRepresentation", "CylindricalRepresentation", "BaseDifferential", "CartesianDifferential", "BaseSphericalDifferential", "BaseSphericalCosLatDifferential", "SphericalDifferential", "SphericalCosLatDifferential", "UnitSphericalDifferential", "UnitSphericalCosLatDifferential", "RadialDifferential", "CylindricalDifferential", "PhysicsSphericalDifferential"] # Module-level dict mapping representation string alias names to classes. # This is populated by the metaclass init so all representation and differential # classes get registered automatically. REPRESENTATION_CLASSES = {} DIFFERENTIAL_CLASSES = {} # recommended_units deprecation message; if the attribute is removed later, # also remove its use in BaseFrame._get_representation_info. _recommended_units_deprecation = """ The 'recommended_units' attribute is deprecated since 3.0 and may be removed in a future version. Its main use, of representing angles in degrees in frames, is now done automatically in frames. Further overrides are discouraged but can be done using a frame's ``frame_specific_representation_info``. """ def _array2string(values, prefix=''): # Mimic numpy >=1.12 array2string, in which structured arrays are # typeset taking into account all printoptions. kwargs = {'separator': ', ', 'prefix': prefix} if NUMPY_LT_1_12: # pragma: no cover # Mimic StructureFormat from numpy >=1.12 assuming float-only data. from numpy.core.arrayprint import FloatFormat opts = np.get_printoptions() format_functions = [FloatFormat(np.atleast_1d(values[component]).ravel(), precision=opts['precision'], suppress_small=opts['suppress']) for component in values.dtype.names] def fmt(x): return '({})'.format(', '.join(format_function(field) for field, format_function in zip(x, format_functions))) # Before 1.12, structures arrays were set as "numpystr", # so that is the formmater we need to replace. kwargs['formatter'] = {'numpystr': fmt} kwargs['style'] = fmt else: kwargs['formatter'] = {} if NUMPY_LT_1_14: # in 1.14, style is no longer used (and deprecated) kwargs['style'] = repr return np.array2string(values, **kwargs) def _combine_xyz(x, y, z, xyz_axis=0): """ Combine components ``x``, ``y``, ``z`` into a single Quantity array. Parameters ---------- x, y, z : `~astropy.units.Quantity` The individual x, y, and z components. xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- xyz : `~astropy.units.Quantity` With dimension 3 along ``xyz_axis``, i.e., using the default of ``0``, the shape will be ``(3,) + x.shape``. """ # Add new axis in x, y, z so one can concatenate them around it. # NOTE: just use np.stack once our minimum numpy version is 1.10. result_ndim = x.ndim + 1 if not -result_ndim <= xyz_axis < result_ndim: raise IndexError('xyz_axis {0} out of bounds [-{1}, {1})' .format(xyz_axis, result_ndim)) if xyz_axis < 0: xyz_axis += result_ndim # Get x, y, z to the same units (this is very fast for identical units) # since np.concatenate cannot deal with quantity. cls = x.__class__ y = cls(y, x.unit, copy=False) z = cls(z, x.unit, copy=False) sh = x.shape sh = sh[:xyz_axis] + (1,) + sh[xyz_axis:] xyz_value = np.concatenate([c.reshape(sh).value for c in (x, y, z)], axis=xyz_axis) return cls(xyz_value, unit=x.unit, copy=False) class BaseRepresentationOrDifferential(ShapedLikeNDArray): """3D coordinate representations and differentials. Parameters ---------- comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass The components of the 3D point or differential. The names are the keys and the subclasses the values of the ``attr_classes`` attribute. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ # Ensure multiplication/division with ndarray or Quantity doesn't lead to # object arrays. __array_priority__ = 50000 def __init__(self, *args, **kwargs): # make argument a list, so we can pop them off. args = list(args) components = self.components attrs = [] for component in components: try: attrs.append(args.pop(0) if args else kwargs.pop(component)) except KeyError: raise TypeError('__init__() missing 1 required positional ' 'argument: {0!r}'.format(component)) copy = args.pop(0) if args else kwargs.pop('copy', True) if args: raise TypeError('unexpected arguments: {0}'.format(args)) if kwargs: for component in components: if component in kwargs: raise TypeError("__init__() got multiple values for " "argument {0!r}".format(component)) raise TypeError('unexpected keyword arguments: {0}'.format(kwargs)) # Pass attributes through the required initializing classes. attrs = [self.attr_classes[component](attr, copy=copy) for component, attr in zip(components, attrs)] try: attrs = np.broadcast_arrays(*attrs, subok=True) except ValueError: if len(components) <= 2: c_str = ' and '.join(components) else: c_str = ', '.join(components[:2]) + ', and ' + components[2] raise ValueError("Input parameters {0} cannot be broadcast" .format(c_str)) # Set private attributes for the attributes. (If not defined explicitly # on the class, the metaclass will define properties to access these.) for component, attr in zip(components, attrs): setattr(self, '_' + component, attr) @classmethod def get_name(cls): """Name of the representation or differential. In lower case, with any trailing 'representation' or 'differential' removed. (E.g., 'spherical' for `~astropy.coordinates.SphericalRepresentation` or `~astropy.coordinates.SphericalDifferential`.) """ name = cls.__name__.lower() if name.endswith('representation'): name = name[:-14] elif name.endswith('differential'): name = name[:-12] return name # The two methods that any subclass has to define. @classmethod @abc.abstractmethod def from_cartesian(cls, other): """Create a representation of this class from a supplied Cartesian one. Parameters ---------- other : `CartesianRepresentation` The representation to turn into this class Returns ------- representation : object of this class A new representation of this class's type. """ # Note: the above docstring gets overridden for differentials. raise NotImplementedError() @abc.abstractmethod def to_cartesian(self): """Convert the representation to its Cartesian form. Note that any differentials get dropped. Returns ------- cartrepr : `CartesianRepresentation` The representation in Cartesian form. """ # Note: the above docstring gets overridden for differentials. raise NotImplementedError() @property def components(self): """A tuple with the in-order names of the coordinate components.""" return tuple(self.attr_classes) def _apply(self, method, *args, **kwargs): """Create a new representation or differential with ``method`` applied to the component data. In typical usage, the method is any of the shape-changing methods for `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those picking particular elements (``__getitem__``, ``take``, etc.), which are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`), with the results used to create a new instance. Internally, it is also used to apply functions to the components (in particular, `~numpy.broadcast_to`). Parameters ---------- method : str or callable If str, it is the name of a method that is applied to the internal ``components``. If callable, the function is applied. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. """ if callable(method): apply_method = lambda array: method(array, *args, **kwargs) else: apply_method = operator.methodcaller(method, *args, **kwargs) new = super().__new__(self.__class__) for component in self.components: setattr(new, '_' + component, apply_method(getattr(self, component))) return new @property def shape(self): """The shape of the instance and underlying arrays. Like `~numpy.ndarray.shape`, can be set to a new shape by assigning a tuple. Note that if different instances share some but not all underlying data, setting the shape of one instance can make the other instance unusable. Hence, it is strongly recommended to get new, reshaped instances with the ``reshape`` method. Raises ------ AttributeError If the shape of any of the components cannot be changed without the arrays being copied. For these cases, use the ``reshape`` method (which copies any arrays that cannot be reshaped in-place). """ return getattr(self, self.components[0]).shape @shape.setter def shape(self, shape): # We keep track of arrays that were already reshaped since we may have # to return those to their original shape if a later shape-setting # fails. (This can happen since coordinates are broadcast together.) reshaped = [] oldshape = self.shape for component in self.components: val = getattr(self, component) if val.size > 1: try: val.shape = shape except AttributeError: for val2 in reshaped: val2.shape = oldshape raise else: reshaped.append(val) # Required to support multiplication and division, and defined by the base # representation and differential classes. @abc.abstractmethod def _scale_operation(self, op, *args): raise NotImplementedError() def __mul__(self, other): return self._scale_operation(operator.mul, other) def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): return self._scale_operation(operator.truediv, other) def __div__(self, other): # pragma: py2 return self._scale_operation(operator.truediv, other) def __neg__(self): return self._scale_operation(operator.neg) # Follow numpy convention and make an independent copy. def __pos__(self): return self.copy() # Required to support addition and subtraction, and defined by the base # representation and differential classes. @abc.abstractmethod def _combine_operation(self, op, other, reverse=False): raise NotImplementedError() def __add__(self, other): return self._combine_operation(operator.add, other) def __radd__(self, other): return self._combine_operation(operator.add, other, reverse=True) def __sub__(self, other): return self._combine_operation(operator.sub, other) def __rsub__(self, other): return self._combine_operation(operator.sub, other, reverse=True) # The following are used for repr and str @property def _values(self): """Turn the coordinates into a record array with the coordinate values. The record array fields will have the component names. """ coo_items = [(c, getattr(self, c)) for c in self.components] result = np.empty(self.shape, [(c, coo.dtype) for c, coo in coo_items]) for c, coo in coo_items: result[c] = coo.value return result @property def _units(self): """Return a dictionary with the units of the coordinate components.""" return dict([(component, getattr(self, component).unit) for component in self.components]) @property def _unitstr(self): units_set = set(self._units.values()) if len(units_set) == 1: unitstr = units_set.pop().to_string() else: unitstr = '({0})'.format( ', '.join([self._units[component].to_string() for component in self.components])) return unitstr def __str__(self): return '{0} {1:s}'.format(_array2string(self._values), self._unitstr) def __repr__(self): prefixstr = ' ' arrstr = _array2string(self._values, prefix=prefixstr) diffstr = '' if getattr(self, 'differentials', None): diffstr = '\n (has differentials w.r.t.: {0})'.format( ', '.join([repr(key) for key in self.differentials.keys()])) unitstr = ('in ' + self._unitstr) if self._unitstr else '[dimensionless]' return '<{0} ({1}) {2:s}\n{3}{4}{5}>'.format( self.__class__.__name__, ', '.join(self.components), unitstr, prefixstr, arrstr, diffstr) def _make_getter(component): """Make an attribute getter for use in a property. Parameters ---------- component : str The name of the component that should be accessed. This assumes the actual value is stored in an attribute of that name prefixed by '_'. """ # This has to be done in a function to ensure the reference to component # is not lost/redirected. component = '_' + component def get_component(self): return getattr(self, component) return get_component # Need to also subclass ABCMeta rather than type, so that this meta class can # be combined with a ShapedLikeNDArray subclass (which is an ABC). Without it: # "TypeError: metaclass conflict: the metaclass of a derived class must be a # (non-strict) subclass of the metaclasses of all its bases" class MetaBaseRepresentation(InheritDocstrings, abc.ABCMeta): def __init__(cls, name, bases, dct): super().__init__(name, bases, dct) # Register representation name (except for BaseRepresentation) if cls.__name__ == 'BaseRepresentation': return if 'attr_classes' not in dct: raise NotImplementedError('Representations must have an ' '"attr_classes" class attribute.') if 'recommended_units' in dct: warnings.warn(_recommended_units_deprecation, AstropyDeprecationWarning) # Ensure we don't override the property that warns about the # deprecation, but that the value remains the same. dct.setdefault('_recommended_units', dct.pop('recommended_units')) repr_name = cls.get_name() if repr_name in REPRESENTATION_CLASSES: raise ValueError("Representation class {0} already defined" .format(repr_name)) REPRESENTATION_CLASSES[repr_name] = cls # define getters for any component that does not yet have one. for component in cls.attr_classes: if not hasattr(cls, component): setattr(cls, component, property(_make_getter(component), doc=("The '{0}' component of the points(s)." .format(component)))) class BaseRepresentation(BaseRepresentationOrDifferential, metaclass=MetaBaseRepresentation): """Base for representing a point in a 3D coordinate system. Parameters ---------- comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass The components of the 3D points. The names are the keys and the subclasses the values of the ``attr_classes`` attribute. differentials : dict, `BaseDifferential`, optional Any differential classes that should be associated with this representation. The input must either be a single `BaseDifferential` subclass instance, or a dictionary with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. Notes ----- All representation classes should subclass this base representation class, and define an ``attr_classes`` attribute, an `~collections.OrderedDict` which maps component names to the class that creates them. They must also define a ``to_cartesian`` method and a ``from_cartesian`` class method. By default, transformations are done via the cartesian system, but classes that want to define a smarter transformation path can overload the ``represent_as`` method. If one wants to use an associated differential class, one should also define ``unit_vectors`` and ``scale_factors`` methods (see those methods for details). """ recommended_units = deprecated_attribute('recommended_units', since='3.0') _recommended_units = {} def __init__(self, *args, differentials=None, **kwargs): # Handle any differentials passed in. super().__init__(*args, **kwargs) self._differentials = self._validate_differentials(differentials) def _validate_differentials(self, differentials): """ Validate that the provided differentials are appropriate for this representation and recast/reshape as necessary and then return. Note that this does *not* set the differentials on ``self._differentials``, but rather leaves that for the caller. """ # Now handle the actual validation of any specified differential classes if differentials is None: differentials = dict() elif isinstance(differentials, BaseDifferential): # We can't handle auto-determining the key for this combo if (isinstance(differentials, RadialDifferential) and isinstance(self, UnitSphericalRepresentation)): raise ValueError("To attach a RadialDifferential to a " "UnitSphericalRepresentation, you must supply " "a dictionary with an appropriate key.") key = differentials._get_deriv_key(self) differentials = {key: differentials} for key in differentials: try: diff = differentials[key] except TypeError: raise TypeError("'differentials' argument must be a " "dictionary-like object") diff._check_base(self) if (isinstance(diff, RadialDifferential) and isinstance(self, UnitSphericalRepresentation)): # We trust the passing of a key for a RadialDifferential # attached to a UnitSphericalRepresentation because it will not # have a paired component name (UnitSphericalRepresentation has # no .distance) to automatically determine the expected key pass else: expected_key = diff._get_deriv_key(self) if key != expected_key: raise ValueError("For differential object '{0}', expected " "unit key = '{1}' but received key = '{2}'" .format(repr(diff), expected_key, key)) # For now, we are very rigid: differentials must have the same shape # as the representation. This makes it easier to handle __getitem__ # and any other shape-changing operations on representations that # have associated differentials if diff.shape != self.shape: # TODO: message of IncompatibleShapeError is not customizable, # so use a valueerror instead? raise ValueError("Shape of differentials must be the same " "as the shape of the representation ({0} vs " "{1})".format(diff.shape, self.shape)) return differentials def _raise_if_has_differentials(self, op_name): """ Used to raise a consistent exception for any operation that is not supported when a representation has differentials attached. """ if self.differentials: raise TypeError("Operation '{0}' is not supported when " "differentials are attached to a {1}." .format(op_name, self.__class__.__name__)) @property def _compatible_differentials(self): return [DIFFERENTIAL_CLASSES[self.get_name()]] @property def differentials(self): """A dictionary of differential class instances. The keys of this dictionary must be a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. """ return self._differentials # We do not make unit_vectors and scale_factors abstract methods, since # they are only necessary if one also defines an associated Differential. # Also, doing so would break pre-differential representation subclasses. def unit_vectors(self): r"""Cartesian unit vectors in the direction of each component. Given unit vectors :math:`\hat{e}_c` and scale factors :math:`f_c`, a change in one component of :math:`\delta c` corresponds to a change in representation of :math:`\delta c \times f_c \times \hat{e}_c`. Returns ------- unit_vectors : dict of `CartesianRepresentation` The keys are the component names. """ raise NotImplementedError("{} has not implemented unit vectors" .format(type(self))) def scale_factors(self): r"""Scale factors for each component's direction. Given unit vectors :math:`\hat{e}_c` and scale factors :math:`f_c`, a change in one component of :math:`\delta c` corresponds to a change in representation of :math:`\delta c \times f_c \times \hat{e}_c`. Returns ------- scale_factors : dict of `~astropy.units.Quantity` The keys are the component names. """ raise NotImplementedError("{} has not implemented scale factors." .format(type(self))) def _re_represent_differentials(self, new_rep, differential_class): """Re-represent the differentials to the specified classes. This returns a new dictionary with the same keys but with the attached differentials converted to the new differential classes. """ if differential_class is None: return dict() if not self.differentials and differential_class: raise ValueError("No differentials associated with this " "representation!") elif (len(self.differentials) == 1 and inspect.isclass(differential_class) and issubclass(differential_class, BaseDifferential)): # TODO: is there a better way to do this? differential_class = { list(self.differentials.keys())[0]: differential_class } elif set(differential_class.keys()) != set(self.differentials.keys()): ValueError("Desired differential classes must be passed in " "as a dictionary with keys equal to a string " "representation of the unit of the derivative " "for each differential stored with this " "representation object ({0})" .format(self.differentials)) new_diffs = dict() for k in self.differentials: diff = self.differentials[k] try: new_diffs[k] = diff.represent_as(differential_class[k], base=self) except Exception: if (differential_class[k] not in new_rep._compatible_differentials): raise TypeError("Desired differential class {0} is not " "compatible with the desired " "representation class {1}" .format(differential_class[k], new_rep.__class__)) else: raise return new_diffs def represent_as(self, other_class, differential_class=None): """Convert coordinates to another representation. If the instance is of the requested class, it is returned unmodified. By default, conversion is done via cartesian coordinates. Parameters ---------- other_class : `~astropy.coordinates.BaseRepresentation` subclass The type of representation to turn the coordinates into. differential_class : dict of `~astropy.coordinates.BaseDifferential`, optional Classes in which the differentials should be represented. Can be a single class if only a single differential is attached, otherwise it should be a `dict` keyed by the same keys as the differentials. """ if other_class is self.__class__ and not differential_class: return self.without_differentials() else: if isinstance(other_class, str): raise ValueError("Input to a representation's represent_as " "must be a class, not a string. For " "strings, use frame objects") # The default is to convert via cartesian coordinates new_rep = other_class.from_cartesian(self.to_cartesian()) new_rep._differentials = self._re_represent_differentials( new_rep, differential_class) return new_rep def with_differentials(self, differentials): """ Create a new representation with the same positions as this representation, but with these new differentials. Differential keys that already exist in this object's differential dict are overwritten. Parameters ---------- differentials : Sequence of `~astropy.coordinates.BaseDifferential` The differentials for the new representation to have. Returns ------- newrepr A copy of this representation, but with the ``differentials`` as its differentials. """ if not differentials: return self args = [getattr(self, component) for component in self.components] # We shallow copy the differentials dictionary so we don't update the # current object's dictionary when adding new keys new_rep = self.__class__(*args, differentials=self.differentials.copy(), copy=False) new_rep._differentials.update( new_rep._validate_differentials(differentials)) return new_rep def without_differentials(self): """Return a copy of the representation without attached differentials. Returns ------- newrepr A shallow copy of this representation, without any differentials. If no differentials were present, no copy is made. """ if not self._differentials: return self args = [getattr(self, component) for component in self.components] return self.__class__(*args, copy=False) @classmethod def from_representation(cls, representation): """Create a new instance of this representation from another one. Parameters ---------- representation : `~astropy.coordinates.BaseRepresentation` instance The presentation that should be converted to this class. """ return representation.represent_as(cls) def _apply(self, method, *args, **kwargs): """Create a new representation with ``method`` applied to the component data. This is not a simple inherit from ``BaseRepresentationOrDifferential`` because we need to call ``._apply()`` on any associated differential classes. See docstring for `BaseRepresentationOrDifferential._apply`. Parameters ---------- method : str or callable If str, it is the name of a method that is applied to the internal ``components``. If callable, the function is applied. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. """ rep = super()._apply(method, *args, **kwargs) rep._differentials = dict( [(k, diff._apply(method, *args, **kwargs)) for k, diff in self._differentials.items()]) return rep def _scale_operation(self, op, *args): """Scale all non-angular components, leaving angular ones unchanged. Parameters ---------- op : `~operator` callable Operator to apply (e.g., `~operator.mul`, `~operator.neg`, etc. *args Any arguments required for the operator (typically, what is to be multiplied with, divided by). """ self._raise_if_has_differentials(op.__name__) results = [] for component, cls in self.attr_classes.items(): value = getattr(self, component) if issubclass(cls, Angle): results.append(value) else: results.append(op(value, *args)) # try/except catches anything that cannot initialize the class, such # as operations that returned NotImplemented or a representation # instead of a quantity (as would happen for, e.g., rep * rep). try: return self.__class__(*results) except Exception: return NotImplemented def _combine_operation(self, op, other, reverse=False): """Combine two representation. By default, operate on the cartesian representations of both. Parameters ---------- op : `~operator` callable Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc. other : `~astropy.coordinates.BaseRepresentation` instance The other representation. reverse : bool Whether the operands should be reversed (e.g., as we got here via ``self.__rsub__`` because ``self`` is a subclass of ``other``). """ self._raise_if_has_differentials(op.__name__) result = self.to_cartesian()._combine_operation(op, other, reverse) if result is NotImplemented: return NotImplemented else: return self.from_cartesian(result) # We need to override this setter to support differentials @BaseRepresentationOrDifferential.shape.setter def shape(self, shape): orig_shape = self.shape # See: https://stackoverflow.com/questions/3336767/ for an example BaseRepresentationOrDifferential.shape.fset(self, shape) # also try to perform shape-setting on any associated differentials try: for k in self.differentials: self.differentials[k].shape = shape except Exception: BaseRepresentationOrDifferential.shape.fset(self, orig_shape) for k in self.differentials: self.differentials[k].shape = orig_shape raise def norm(self): """Vector norm. The norm is the standard Frobenius norm, i.e., the square root of the sum of the squares of all components with non-angular units. Note that any associated differentials will be dropped during this operation. Returns ------- norm : `astropy.units.Quantity` Vector norm, with the same shape as the representation. """ return np.sqrt(functools.reduce( operator.add, (getattr(self, component)**2 for component, cls in self.attr_classes.items() if not issubclass(cls, Angle)))) def mean(self, *args, **kwargs): """Vector mean. Averaging is done by converting the representation to cartesian, and taking the mean of the x, y, and z components. The result is converted back to the same representation as the input. Refer to `~numpy.mean` for full documentation of the arguments, noting that ``axis`` is the entry in the ``shape`` of the representation, and that the ``out`` argument cannot be used. Returns ------- mean : representation Vector mean, in the same representation as that of the input. """ self._raise_if_has_differentials('mean') return self.from_cartesian(self.to_cartesian().mean(*args, **kwargs)) def sum(self, *args, **kwargs): """Vector sum. Adding is done by converting the representation to cartesian, and summing the x, y, and z components. The result is converted back to the same representation as the input. Refer to `~numpy.sum` for full documentation of the arguments, noting that ``axis`` is the entry in the ``shape`` of the representation, and that the ``out`` argument cannot be used. Returns ------- sum : representation Vector sum, in the same representation as that of the input. """ self._raise_if_has_differentials('sum') return self.from_cartesian(self.to_cartesian().sum(*args, **kwargs)) def dot(self, other): """Dot product of two representations. The calculation is done by converting both ``self`` and ``other`` to `~astropy.coordinates.CartesianRepresentation`. Note that any associated differentials will be dropped during this operation. Parameters ---------- other : `~astropy.coordinates.BaseRepresentation` The representation to take the dot product with. Returns ------- dot_product : `~astropy.units.Quantity` The sum of the product of the x, y, and z components of the cartesian representations of ``self`` and ``other``. """ return self.to_cartesian().dot(other) def cross(self, other): """Vector cross product of two representations. The calculation is done by converting both ``self`` and ``other`` to `~astropy.coordinates.CartesianRepresentation`, and converting the result back to the type of representation of ``self``. Parameters ---------- other : representation The representation to take the cross product with. Returns ------- cross_product : representation With vectors perpendicular to both ``self`` and ``other``, in the same type of representation as ``self``. """ self._raise_if_has_differentials('cross') return self.from_cartesian(self.to_cartesian().cross(other)) class CartesianRepresentation(BaseRepresentation): """ Representation of points in 3D cartesian coordinates. Parameters ---------- x, y, z : `~astropy.units.Quantity` or array The x, y, and z coordinates of the point(s). If ``x``, ``y``, and ``z`` have different shapes, they should be broadcastable. If not quantity, ``unit`` should be set. If only ``x`` is given, it is assumed that it contains an array with the 3 coordinates stored along ``xyz_axis``. unit : `~astropy.units.Unit` or str If given, the coordinates will be converted to this unit (or taken to be in this unit if not given. xyz_axis : int, optional The axis along which the coordinates are stored when a single array is provided rather than distinct ``x``, ``y``, and ``z`` (default: 0). differentials : dict, `CartesianDifferential`, optional Any differential classes that should be associated with this representation. The input must either be a single `CartesianDifferential` instance, or a dictionary of `CartesianDifferential` s with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ attr_classes = OrderedDict([('x', u.Quantity), ('y', u.Quantity), ('z', u.Quantity)]) def __init__(self, x, y=None, z=None, unit=None, xyz_axis=None, differentials=None, copy=True): if y is None and z is None: if xyz_axis is not None and xyz_axis != 0: x = np.rollaxis(x, xyz_axis, 0) x, y, z = x elif xyz_axis is not None: raise ValueError("xyz_axis should only be set if x, y, and z are " "in a single array passed in through x, " "i.e., y and z should not be not given.") elif (y is None and z is not None) or (y is not None and z is None): raise ValueError("x, y, and z are required to instantiate {0}" .format(self.__class__.__name__)) if unit is not None: x = u.Quantity(x, unit, copy=copy, subok=True) y = u.Quantity(y, unit, copy=copy, subok=True) z = u.Quantity(z, unit, copy=copy, subok=True) copy = False super().__init__(x, y, z, copy=copy, differentials=differentials) if not (self._x.unit.physical_type == self._y.unit.physical_type == self._z.unit.physical_type): raise u.UnitsError("x, y, and z should have matching physical types") def unit_vectors(self): l = np.broadcast_to(1.*u.one, self.shape, subok=True) o = np.broadcast_to(0.*u.one, self.shape, subok=True) return OrderedDict( (('x', CartesianRepresentation(l, o, o, copy=False)), ('y', CartesianRepresentation(o, l, o, copy=False)), ('z', CartesianRepresentation(o, o, l, copy=False)))) def scale_factors(self): l = np.broadcast_to(1.*u.one, self.shape, subok=True) return OrderedDict((('x', l), ('y', l), ('z', l))) def get_xyz(self, xyz_axis=0): """Return a vector array of the x, y, and z coordinates. Parameters ---------- xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- xyz : `~astropy.units.Quantity` With dimension 3 along ``xyz_axis``. """ return _combine_xyz(self._x, self._y, self._z, xyz_axis=xyz_axis) xyz = property(get_xyz) @classmethod def from_cartesian(cls, other): return other def to_cartesian(self): return self def transform(self, matrix): """ Transform the cartesian coordinates using a 3x3 matrix. This returns a new representation and does not modify the original one. Any differentials attached to this representation will also be transformed. Parameters ---------- matrix : `~numpy.ndarray` A 3x3 transformation matrix, such as a rotation matrix. Examples -------- We can start off by creating a cartesian representation object: >>> from astropy import units as u >>> from astropy.coordinates import CartesianRepresentation >>> rep = CartesianRepresentation([1, 2] * u.pc, ... [2, 3] * u.pc, ... [3, 4] * u.pc) We now create a rotation matrix around the z axis: >>> from astropy.coordinates.matrix_utilities import rotation_matrix >>> rotation = rotation_matrix(30 * u.deg, axis='z') Finally, we can apply this transformation: >>> rep_new = rep.transform(rotation) >>> rep_new.xyz # doctest: +FLOAT_CMP <Quantity [[ 1.8660254 , 3.23205081], [ 1.23205081, 1.59807621], [ 3. , 4. ]] pc> """ # Avoid doing gratuitous np.array for things that look like arrays. try: matrix_shape = matrix.shape except AttributeError: matrix = np.array(matrix) matrix_shape = matrix.shape if matrix_shape[-2:] != (3, 3): raise ValueError("tried to do matrix multiplication with an array " "that doesn't end in 3x3") # TODO: since this is likely to be a widely used function in coordinate # transforms, it should be optimized (for example in Cython). # Get xyz once since it's an expensive operation oldxyz = self.xyz # Note that neither dot nor einsum handles Quantity properly, so we use # the arrays and put the unit back in the end. if self.isscalar and not matrix_shape[:-2]: # a fast path for scalar coordinates. newxyz = matrix.dot(oldxyz.value) else: # Matrix multiply all pmat items and coordinates, broadcasting the # remaining dimensions. if np.__version__ == '1.14.0': # there is a bug in numpy v1.14.0 (fixed in 1.14.1) that causes # this einsum call to break with the default of optimize=True # see https://github.com/astropy/astropy/issues/7051 newxyz = np.einsum('...ij,j...->i...', matrix, oldxyz.value, optimize=False) else: newxyz = np.einsum('...ij,j...->i...', matrix, oldxyz.value) newxyz = u.Quantity(newxyz, oldxyz.unit, copy=False) # Handle differentials attached to this representation if self.differentials: # TODO: speed this up going via d.d_xyz. new_diffs = dict( (k, d.from_cartesian(d.to_cartesian().transform(matrix))) for k, d in self.differentials.items()) else: new_diffs = None return self.__class__(*newxyz, copy=False, differentials=new_diffs) def _combine_operation(self, op, other, reverse=False): self._raise_if_has_differentials(op.__name__) try: other_c = other.to_cartesian() except Exception: return NotImplemented first, second = ((self, other_c) if not reverse else (other_c, self)) return self.__class__(*(op(getattr(first, component), getattr(second, component)) for component in first.components)) def mean(self, *args, **kwargs): """Vector mean. Returns a new CartesianRepresentation instance with the means of the x, y, and z components. Refer to `~numpy.mean` for full documentation of the arguments, noting that ``axis`` is the entry in the ``shape`` of the representation, and that the ``out`` argument cannot be used. """ self._raise_if_has_differentials('mean') return self._apply('mean', *args, **kwargs) def sum(self, *args, **kwargs): """Vector sum. Returns a new CartesianRepresentation instance with the sums of the x, y, and z components. Refer to `~numpy.sum` for full documentation of the arguments, noting that ``axis`` is the entry in the ``shape`` of the representation, and that the ``out`` argument cannot be used. """ self._raise_if_has_differentials('sum') return self._apply('sum', *args, **kwargs) def dot(self, other): """Dot product of two representations. Note that any associated differentials will be dropped during this operation. Parameters ---------- other : representation If not already cartesian, it is converted. Returns ------- dot_product : `~astropy.units.Quantity` The sum of the product of the x, y, and z components of ``self`` and ``other``. """ try: other_c = other.to_cartesian() except Exception: raise TypeError("cannot only take dot product with another " "representation, not a {0} instance." .format(type(other))) return functools.reduce(operator.add, (getattr(self, component) * getattr(other_c, component) for component in self.components)) def cross(self, other): """Cross product of two representations. Parameters ---------- other : representation If not already cartesian, it is converted. Returns ------- cross_product : `~astropy.coordinates.CartesianRepresentation` With vectors perpendicular to both ``self`` and ``other``. """ self._raise_if_has_differentials('cross') try: other_c = other.to_cartesian() except Exception: raise TypeError("cannot only take cross product with another " "representation, not a {0} instance." .format(type(other))) return self.__class__(self.y * other_c.z - self.z * other_c.y, self.z * other_c.x - self.x * other_c.z, self.x * other_c.y - self.y * other_c.x) class UnitSphericalRepresentation(BaseRepresentation): """ Representation of points on a unit sphere. Parameters ---------- lon, lat : `~astropy.units.Quantity` or str The longitude and latitude of the point(s), in angular units. The latitude should be between -90 and 90 degrees, and the longitude will be wrapped to an angle between 0 and 360 degrees. These can also be instances of `~astropy.coordinates.Angle`, `~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`. differentials : dict, `BaseDifferential`, optional Any differential classes that should be associated with this representation. The input must either be a single `BaseDifferential` instance (see `._compatible_differentials` for valid types), or a dictionary of of differential instances with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ attr_classes = OrderedDict([('lon', Longitude), ('lat', Latitude)]) @classproperty def _dimensional_representation(cls): return SphericalRepresentation def __init__(self, lon, lat, differentials=None, copy=True): super().__init__(lon, lat, differentials=differentials, copy=copy) @property def _compatible_differentials(self): return [UnitSphericalDifferential, UnitSphericalCosLatDifferential, SphericalDifferential, SphericalCosLatDifferential, RadialDifferential] # Could let the metaclass define these automatically, but good to have # a bit clearer docstrings. @property def lon(self): """ The longitude of the point(s). """ return self._lon @property def lat(self): """ The latitude of the point(s). """ return self._lat def unit_vectors(self): sinlon, coslon = np.sin(self.lon), np.cos(self.lon) sinlat, coslat = np.sin(self.lat), np.cos(self.lat) return OrderedDict( (('lon', CartesianRepresentation(-sinlon, coslon, 0., copy=False)), ('lat', CartesianRepresentation(-sinlat*coslon, -sinlat*sinlon, coslat, copy=False)))) def scale_factors(self, omit_coslat=False): sf_lat = np.broadcast_to(1./u.radian, self.shape, subok=True) sf_lon = sf_lat if omit_coslat else np.cos(self.lat) / u.radian return OrderedDict((('lon', sf_lon), ('lat', sf_lat))) def to_cartesian(self): """ Converts spherical polar coordinates to 3D rectangular cartesian coordinates. """ x = np.cos(self.lat) * np.cos(self.lon) y = np.cos(self.lat) * np.sin(self.lon) z = np.sin(self.lat) return CartesianRepresentation(x=x, y=y, z=z, copy=False) @classmethod def from_cartesian(cls, cart): """ Converts 3D rectangular cartesian coordinates to spherical polar coordinates. """ s = np.hypot(cart.x, cart.y) lon = np.arctan2(cart.y, cart.x) lat = np.arctan2(cart.z, s) return cls(lon=lon, lat=lat, copy=False) def represent_as(self, other_class, differential_class=None): # Take a short cut if the other class is a spherical representation # TODO: this could be optimized to shortcut even if a differential_class # is passed in, using the ._re_represent_differentials() method if inspect.isclass(other_class) and not differential_class: if issubclass(other_class, PhysicsSphericalRepresentation): return other_class(phi=self.lon, theta=90 * u.deg - self.lat, r=1.0, copy=False) elif issubclass(other_class, SphericalRepresentation): return other_class(lon=self.lon, lat=self.lat, distance=1.0, copy=False) return super().represent_as(other_class, differential_class) def __mul__(self, other): self._raise_if_has_differentials('multiplication') return self._dimensional_representation(lon=self.lon, lat=self.lat, distance=1. * other) def __truediv__(self, other): self._raise_if_has_differentials('division') return self._dimensional_representation(lon=self.lon, lat=self.lat, distance=1. / other) def __neg__(self): self._raise_if_has_differentials('negation') return self.__class__(self.lon + 180. * u.deg, -self.lat, copy=False) def norm(self): """Vector norm. The norm is the standard Frobenius norm, i.e., the square root of the sum of the squares of all components with non-angular units, which is always unity for vectors on the unit sphere. Returns ------- norm : `~astropy.units.Quantity` Dimensionless ones, with the same shape as the representation. """ return u.Quantity(np.ones(self.shape), u.dimensionless_unscaled, copy=False) def _combine_operation(self, op, other, reverse=False): self._raise_if_has_differentials(op.__name__) result = self.to_cartesian()._combine_operation(op, other, reverse) if result is NotImplemented: return NotImplemented else: return self._dimensional_representation.from_cartesian(result) def mean(self, *args, **kwargs): """Vector mean. The representation is converted to cartesian, the means of the x, y, and z components are calculated, and the result is converted to a `~astropy.coordinates.SphericalRepresentation`. Refer to `~numpy.mean` for full documentation of the arguments, noting that ``axis`` is the entry in the ``shape`` of the representation, and that the ``out`` argument cannot be used. """ self._raise_if_has_differentials('mean') return self._dimensional_representation.from_cartesian( self.to_cartesian().mean(*args, **kwargs)) def sum(self, *args, **kwargs): """Vector sum. The representation is converted to cartesian, the sums of the x, y, and z components are calculated, and the result is converted to a `~astropy.coordinates.SphericalRepresentation`. Refer to `~numpy.sum` for full documentation of the arguments, noting that ``axis`` is the entry in the ``shape`` of the representation, and that the ``out`` argument cannot be used. """ self._raise_if_has_differentials('sum') return self._dimensional_representation.from_cartesian( self.to_cartesian().sum(*args, **kwargs)) def cross(self, other): """Cross product of two representations. The calculation is done by converting both ``self`` and ``other`` to `~astropy.coordinates.CartesianRepresentation`, and converting the result back to `~astropy.coordinates.SphericalRepresentation`. Parameters ---------- other : representation The representation to take the cross product with. Returns ------- cross_product : `~astropy.coordinates.SphericalRepresentation` With vectors perpendicular to both ``self`` and ``other``. """ self._raise_if_has_differentials('cross') return self._dimensional_representation.from_cartesian( self.to_cartesian().cross(other)) class RadialRepresentation(BaseRepresentation): """ Representation of the distance of points from the origin. Note that this is mostly intended as an internal helper representation. It can do little else but being used as a scale in multiplication. Parameters ---------- distance : `~astropy.units.Quantity` The distance of the point(s) from the origin. differentials : dict, `BaseDifferential`, optional Any differential classes that should be associated with this representation. The input must either be a single `BaseDifferential` instance (see `._compatible_differentials` for valid types), or a dictionary of of differential instances with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ attr_classes = OrderedDict([('distance', u.Quantity)]) def __init__(self, distance, differentials=None, copy=True): super().__init__(distance, copy=copy, differentials=differentials) @property def distance(self): """ The distance from the origin to the point(s). """ return self._distance def unit_vectors(self): """Cartesian unit vectors are undefined for radial representation.""" raise NotImplementedError('Cartesian unit vectors are undefined for ' '{0} instances'.format(self.__class__)) def scale_factors(self): l = np.broadcast_to(1.*u.one, self.shape, subok=True) return OrderedDict((('distance', l),)) def to_cartesian(self): """Cannot convert radial representation to cartesian.""" raise NotImplementedError('cannot convert {0} instance to cartesian.' .format(self.__class__)) @classmethod def from_cartesian(cls, cart): """ Converts 3D rectangular cartesian coordinates to radial coordinate. """ return cls(distance=cart.norm(), copy=False) def _scale_operation(self, op, *args): self._raise_if_has_differentials(op.__name__) return op(self.distance, *args) def norm(self): """Vector norm. Just the distance itself. Returns ------- norm : `~astropy.units.Quantity` Dimensionless ones, with the same shape as the representation. """ return self.distance def _combine_operation(self, op, other, reverse=False): return NotImplemented class SphericalRepresentation(BaseRepresentation): """ Representation of points in 3D spherical coordinates. Parameters ---------- lon, lat : `~astropy.units.Quantity` The longitude and latitude of the point(s), in angular units. The latitude should be between -90 and 90 degrees, and the longitude will be wrapped to an angle between 0 and 360 degrees. These can also be instances of `~astropy.coordinates.Angle`, `~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`. distance : `~astropy.units.Quantity` The distance to the point(s). If the distance is a length, it is passed to the :class:`~astropy.coordinates.Distance` class, otherwise it is passed to the :class:`~astropy.units.Quantity` class. differentials : dict, `BaseDifferential`, optional Any differential classes that should be associated with this representation. The input must either be a single `BaseDifferential` instance (see `._compatible_differentials` for valid types), or a dictionary of of differential instances with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ attr_classes = OrderedDict([('lon', Longitude), ('lat', Latitude), ('distance', u.Quantity)]) _unit_representation = UnitSphericalRepresentation def __init__(self, lon, lat, distance, differentials=None, copy=True): super().__init__(lon, lat, distance, copy=copy, differentials=differentials) if self._distance.unit.physical_type == 'length': self._distance = self._distance.view(Distance) @property def _compatible_differentials(self): return [UnitSphericalDifferential, UnitSphericalCosLatDifferential, SphericalDifferential, SphericalCosLatDifferential, RadialDifferential] @property def lon(self): """ The longitude of the point(s). """ return self._lon @property def lat(self): """ The latitude of the point(s). """ return self._lat @property def distance(self): """ The distance from the origin to the point(s). """ return self._distance def unit_vectors(self): sinlon, coslon = np.sin(self.lon), np.cos(self.lon) sinlat, coslat = np.sin(self.lat), np.cos(self.lat) return OrderedDict( (('lon', CartesianRepresentation(-sinlon, coslon, 0., copy=False)), ('lat', CartesianRepresentation(-sinlat*coslon, -sinlat*sinlon, coslat, copy=False)), ('distance', CartesianRepresentation(coslat*coslon, coslat*sinlon, sinlat, copy=False)))) def scale_factors(self, omit_coslat=False): sf_lat = self.distance / u.radian sf_lon = sf_lat if omit_coslat else sf_lat * np.cos(self.lat) sf_distance = np.broadcast_to(1.*u.one, self.shape, subok=True) return OrderedDict((('lon', sf_lon), ('lat', sf_lat), ('distance', sf_distance))) def represent_as(self, other_class, differential_class=None): # Take a short cut if the other class is a spherical representation # TODO: this could be optimized to shortcut even if a differential_class # is passed in, using the ._re_represent_differentials() method if inspect.isclass(other_class) and not differential_class: if issubclass(other_class, PhysicsSphericalRepresentation): return other_class(phi=self.lon, theta=90 * u.deg - self.lat, r=self.distance, copy=False) elif issubclass(other_class, UnitSphericalRepresentation): return other_class(lon=self.lon, lat=self.lat, copy=False) return super().represent_as(other_class, differential_class) def to_cartesian(self): """ Converts spherical polar coordinates to 3D rectangular cartesian coordinates. """ # We need to convert Distance to Quantity to allow negative values. if isinstance(self.distance, Distance): d = self.distance.view(u.Quantity) else: d = self.distance 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): """ Converts 3D rectangular cartesian coordinates to spherical polar coordinates. """ 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, distance=r, copy=False) def norm(self): """Vector norm. The norm is the standard Frobenius norm, i.e., the square root of the sum of the squares of all components with non-angular units. For spherical coordinates, this is just the absolute value of the distance. Returns ------- norm : `astropy.units.Quantity` Vector norm, with the same shape as the representation. """ return np.abs(self.distance) class PhysicsSphericalRepresentation(BaseRepresentation): """ Representation of points in 3D spherical coordinates (using the physics convention of using ``phi`` and ``theta`` for azimuth and inclination from the pole). Parameters ---------- phi, theta : `~astropy.units.Quantity` or str The azimuth and inclination of the point(s), in angular units. The inclination should be between 0 and 180 degrees, and the azimuth will be wrapped to an angle between 0 and 360 degrees. These can also be instances of `~astropy.coordinates.Angle`. If ``copy`` is False, `phi` will be changed inplace if it is not between 0 and 360 degrees. r : `~astropy.units.Quantity` The distance to the point(s). If the distance is a length, it is passed to the :class:`~astropy.coordinates.Distance` class, otherwise it is passed to the :class:`~astropy.units.Quantity` class. differentials : dict, `PhysicsSphericalDifferential`, optional Any differential classes that should be associated with this representation. The input must either be a single `PhysicsSphericalDifferential` instance, or a dictionary of of differential instances with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ attr_classes = OrderedDict([('phi', Angle), ('theta', Angle), ('r', u.Quantity)]) def __init__(self, phi, theta, r, differentials=None, copy=True): super().__init__(phi, theta, r, copy=copy, differentials=differentials) # Wrap/validate phi/theta if copy: self._phi = self._phi.wrap_at(360 * u.deg) else: # necessary because the above version of `wrap_at` has to be a copy self._phi.wrap_at(360 * u.deg, inplace=True) if np.any(self._theta < 0.*u.deg) or np.any(self._theta > 180.*u.deg): raise ValueError('Inclination angle(s) must be within ' '0 deg <= angle <= 180 deg, ' 'got {0}'.format(theta.to(u.degree))) if self._r.unit.physical_type == 'length': self._r = self._r.view(Distance) @property def phi(self): """ The azimuth of the point(s). """ return self._phi @property def theta(self): """ The elevation of the point(s). """ return self._theta @property def r(self): """ The distance from the origin to the point(s). """ return self._r def unit_vectors(self): sinphi, cosphi = np.sin(self.phi), np.cos(self.phi) sintheta, costheta = np.sin(self.theta), np.cos(self.theta) return OrderedDict( (('phi', CartesianRepresentation(-sinphi, cosphi, 0., copy=False)), ('theta', CartesianRepresentation(costheta*cosphi, costheta*sinphi, -sintheta, copy=False)), ('r', CartesianRepresentation(sintheta*cosphi, sintheta*sinphi, costheta, copy=False)))) def scale_factors(self): r = self.r / u.radian sintheta = np.sin(self.theta) l = np.broadcast_to(1.*u.one, self.shape, subok=True) return OrderedDict((('phi', r * sintheta), ('theta', r), ('r', l))) def represent_as(self, other_class, differential_class=None): # Take a short cut if the other class is a spherical representation # TODO: this could be optimized to shortcut even if a differential_class # is passed in, using the ._re_represent_differentials() method if inspect.isclass(other_class) and not differential_class: if issubclass(other_class, SphericalRepresentation): return other_class(lon=self.phi, lat=90 * u.deg - self.theta, distance=self.r) elif issubclass(other_class, UnitSphericalRepresentation): return other_class(lon=self.phi, lat=90 * u.deg - self.theta) return super().represent_as(other_class, differential_class) def to_cartesian(self): """ Converts spherical polar coordinates to 3D rectangular cartesian coordinates. """ # We need to convert Distance to Quantity to allow negative values. if isinstance(self.r, Distance): d = self.r.view(u.Quantity) else: d = self.r x = d * np.sin(self.theta) * np.cos(self.phi) y = d * np.sin(self.theta) * np.sin(self.phi) z = d * np.cos(self.theta) return CartesianRepresentation(x=x, y=y, z=z, copy=False) @classmethod def from_cartesian(cls, cart): """ Converts 3D rectangular cartesian coordinates to spherical polar coordinates. """ s = np.hypot(cart.x, cart.y) r = np.hypot(s, cart.z) phi = np.arctan2(cart.y, cart.x) theta = np.arctan2(s, cart.z) return cls(phi=phi, theta=theta, r=r, copy=False) def norm(self): """Vector norm. The norm is the standard Frobenius norm, i.e., the square root of the sum of the squares of all components with non-angular units. For spherical coordinates, this is just the absolute value of the radius. Returns ------- norm : `astropy.units.Quantity` Vector norm, with the same shape as the representation. """ return np.abs(self.r) class CylindricalRepresentation(BaseRepresentation): """ Representation of points in 3D cylindrical coordinates. Parameters ---------- rho : `~astropy.units.Quantity` The distance from the z axis to the point(s). phi : `~astropy.units.Quantity` or str The azimuth of the point(s), in angular units, which will be wrapped to an angle between 0 and 360 degrees. This can also be instances of `~astropy.coordinates.Angle`, z : `~astropy.units.Quantity` The z coordinate(s) of the point(s) differentials : dict, `CylindricalDifferential`, optional Any differential classes that should be associated with this representation. The input must either be a single `CylindricalDifferential` instance, or a dictionary of of differential instances with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be ``'s'`` for seconds, indicating that the derivative is a time derivative. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ attr_classes = OrderedDict([('rho', u.Quantity), ('phi', Angle), ('z', u.Quantity)]) def __init__(self, rho, phi, z, differentials=None, copy=True): super().__init__(rho, phi, z, copy=copy, differentials=differentials) if not self._rho.unit.is_equivalent(self._z.unit): raise u.UnitsError("rho and z should have matching physical types") @property def rho(self): """ The distance of the point(s) from the z-axis. """ return self._rho @property def phi(self): """ The azimuth of the point(s). """ return self._phi @property def z(self): """ The height of the point(s). """ return self._z def unit_vectors(self): sinphi, cosphi = np.sin(self.phi), np.cos(self.phi) l = np.broadcast_to(1., self.shape) return OrderedDict( (('rho', CartesianRepresentation(cosphi, sinphi, 0, copy=False)), ('phi', CartesianRepresentation(-sinphi, cosphi, 0, copy=False)), ('z', CartesianRepresentation(0, 0, l, unit=u.one, copy=False)))) def scale_factors(self): rho = self.rho / u.radian l = np.broadcast_to(1.*u.one, self.shape, subok=True) return OrderedDict((('rho', l), ('phi', rho), ('z', l))) @classmethod def from_cartesian(cls, cart): """ Converts 3D rectangular cartesian coordinates to cylindrical polar coordinates. """ rho = np.hypot(cart.x, cart.y) phi = np.arctan2(cart.y, cart.x) z = cart.z return cls(rho=rho, phi=phi, z=z, copy=False) def to_cartesian(self): """ Converts cylindrical polar coordinates to 3D rectangular cartesian coordinates. """ x = self.rho * np.cos(self.phi) y = self.rho * np.sin(self.phi) z = self.z return CartesianRepresentation(x=x, y=y, z=z, copy=False) class MetaBaseDifferential(InheritDocstrings, abc.ABCMeta): """Set default ``attr_classes`` and component getters on a Differential. For these, the components are those of the base representation prefixed by 'd_', and the class is `~astropy.units.Quantity`. """ def __init__(cls, name, bases, dct): super().__init__(name, bases, dct) # Don't do anything for base helper classes. if cls.__name__ in ('BaseDifferential', 'BaseSphericalDifferential', 'BaseSphericalCosLatDifferential'): return if 'base_representation' not in dct: raise NotImplementedError('Differential representations must have a' '"base_representation" class attribute.') # If not defined explicitly, create attr_classes. if not hasattr(cls, 'attr_classes'): base_attr_classes = cls.base_representation.attr_classes cls.attr_classes = OrderedDict([('d_' + c, u.Quantity) for c in base_attr_classes]) if 'recommended_units' in dct: warnings.warn(_recommended_units_deprecation, AstropyDeprecationWarning) # Ensure we don't override the property that warns about the # deprecation, but that the value remains the same. dct.setdefault('_recommended_units', dct.pop('recommended_units')) repr_name = cls.get_name() if repr_name in DIFFERENTIAL_CLASSES: raise ValueError("Differential class {0} already defined" .format(repr_name)) DIFFERENTIAL_CLASSES[repr_name] = cls # If not defined explicitly, create properties for the components. for component in cls.attr_classes: if not hasattr(cls, component): setattr(cls, component, property(_make_getter(component), doc=("Component '{0}' of the Differential." .format(component)))) class BaseDifferential(BaseRepresentationOrDifferential, metaclass=MetaBaseDifferential): r"""A base class representing differentials of representations. These represent differences or derivatives along each component. E.g., for physics spherical coordinates, these would be :math:`\delta r, \delta \theta, \delta \phi`. Parameters ---------- d_comp1, d_comp2, d_comp3 : `~astropy.units.Quantity` or subclass The components of the 3D differentials. The names are the keys and the subclasses the values of the ``attr_classes`` attribute. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. Notes ----- All differential representation classes should subclass this base class, and define an ``base_representation`` attribute with the class of the regular `~astropy.coordinates.BaseRepresentation` for which differential coordinates are provided. This will set up a default ``attr_classes`` instance with names equal to the base component names prefixed by ``d_``, and all classes set to `~astropy.units.Quantity`, plus properties to access those, and a default ``__init__`` for initialization. """ recommended_units = deprecated_attribute('recommended_units', since='3.0') _recommended_units = {} @classmethod def _check_base(cls, base): if cls not in base._compatible_differentials: raise TypeError("Differential class {0} is not compatible with the " "base (representation) class {1}" .format(cls, base.__class__)) def _get_deriv_key(self, base): """Given a base (representation instance), determine the unit of the derivative by removing the representation unit from the component units of this differential. """ # This check is just a last resort so we don't return a strange unit key # from accidentally passing in the wrong base. self._check_base(base) for name in base.components: comp = getattr(base, name) d_comp = getattr(self, 'd_{0}'.format(name), None) if d_comp is not None: d_unit = comp.unit / d_comp.unit # Get the si unit without a scale by going via Quantity; # `.si` causes the scale to be included in the value. return str(u.Quantity(1., d_unit).si.unit) else: raise RuntimeError("Invalid representation-differential match! Not " "sure how we got into this state.") @classmethod def _get_base_vectors(cls, base): """Get unit vectors and scale factors from base. Parameters ---------- base : instance of ``self.base_representation`` The points for which the unit vectors and scale factors should be retrieved. Returns ------- unit_vectors : dict of `CartesianRepresentation` In the directions of the coordinates of base. scale_factors : dict of `~astropy.units.Quantity` Scale factors for each of the coordinates Raises ------ TypeError : if the base is not of the correct type """ cls._check_base(base) return base.unit_vectors(), base.scale_factors() def to_cartesian(self, base): """Convert the differential to 3D rectangular cartesian coordinates. Parameters ---------- base : instance of ``self.base_representation`` The points for which the differentials are to be converted: each of the components is multiplied by its unit vectors and scale factors. Returns ------- This object as a `CartesianDifferential` """ base_e, base_sf = self._get_base_vectors(base) return functools.reduce( operator.add, (getattr(self, d_c) * base_sf[c] * base_e[c] for d_c, c in zip(self.components, base.components))) @classmethod def from_cartesian(cls, other, base): """Convert the differential from 3D rectangular cartesian coordinates to the desired class. Parameters ---------- other : The object to convert into this differential. base : instance of ``self.base_representation`` The points for which the differentials are to be converted: each of the components is multiplied by its unit vectors and scale factors. Returns ------- A new differential object that is this class' type. """ base_e, base_sf = cls._get_base_vectors(base) return cls(*(other.dot(e / base_sf[component]) for component, e in base_e.items()), copy=False) def represent_as(self, other_class, base): """Convert coordinates to another representation. If the instance is of the requested class, it is returned unmodified. By default, conversion is done via cartesian coordinates. Parameters ---------- other_class : `~astropy.coordinates.BaseRepresentation` subclass The type of representation to turn the coordinates into. base : instance of ``self.base_representation``, optional Base relative to which the differentials are defined. If the other class is a differential representation, the base will be converted to its ``base_representation``. """ if other_class is self.__class__: return self # The default is to convert via cartesian coordinates. self_cartesian = self.to_cartesian(base) if issubclass(other_class, BaseDifferential): base = base.represent_as(other_class.base_representation) return other_class.from_cartesian(self_cartesian, base) else: return other_class.from_cartesian(self_cartesian) @classmethod def from_representation(cls, representation, base): """Create a new instance of this representation from another one. Parameters ---------- representation : `~astropy.coordinates.BaseRepresentation` instance The presentation that should be converted to this class. base : instance of ``cls.base_representation`` The base relative to which the differentials will be defined. If the representation is a differential itself, the base will be converted to its ``base_representation`` to help convert it. """ if isinstance(representation, BaseDifferential): cartesian = representation.to_cartesian( base.represent_as(representation.base_representation)) else: cartesian = representation.to_cartesian() return cls.from_cartesian(cartesian, base) def _scale_operation(self, op, *args): """Scale all components. Parameters ---------- op : `~operator` callable Operator to apply (e.g., `~operator.mul`, `~operator.neg`, etc. *args Any arguments required for the operator (typically, what is to be multiplied with, divided by). """ scaled_attrs = [op(getattr(self, c), *args) for c in self.components] return self.__class__(*scaled_attrs, copy=False) def _combine_operation(self, op, other, reverse=False): """Combine two differentials, or a differential with a representation. If ``other`` is of the same differential type as ``self``, the components will simply be combined. If ``other`` is a representation, it will be used as a base for which to evaluate the differential, and the result is a new representation. Parameters ---------- op : `~operator` callable Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc. other : `~astropy.coordinates.BaseRepresentation` instance The other differential or representation. reverse : bool Whether the operands should be reversed (e.g., as we got here via ``self.__rsub__`` because ``self`` is a subclass of ``other``). """ if isinstance(self, type(other)): first, second = (self, other) if not reverse else (other, self) return self.__class__(*[op(getattr(first, c), getattr(second, c)) for c in self.components]) else: try: self_cartesian = self.to_cartesian(other) except TypeError: return NotImplemented return other._combine_operation(op, self_cartesian, not reverse) def __sub__(self, other): # avoid "differential - representation". if isinstance(other, BaseRepresentation): return NotImplemented return super().__sub__(other) def norm(self, base=None): """Vector norm. The norm is the standard Frobenius norm, i.e., the square root of the sum of the squares of all components with non-angular units. Parameters ---------- base : instance of ``self.base_representation`` Base relative to which the differentials are defined. This is required to calculate the physical size of the differential for all but cartesian differentials. Returns ------- norm : `astropy.units.Quantity` Vector norm, with the same shape as the representation. """ return self.to_cartesian(base).norm() class CartesianDifferential(BaseDifferential): """Differentials in of points in 3D cartesian coordinates. Parameters ---------- d_x, d_y, d_z : `~astropy.units.Quantity` or array The x, y, and z coordinates of the differentials. If ``d_x``, ``d_y``, and ``d_z`` have different shapes, they should be broadcastable. If not quantities, ``unit`` should be set. If only ``d_x`` is given, it is assumed that it contains an array with the 3 coordinates stored along ``xyz_axis``. unit : `~astropy.units.Unit` or str If given, the differentials will be converted to this unit (or taken to be in this unit if not given. xyz_axis : int, optional The axis along which the coordinates are stored when a single array is provided instead of distinct ``d_x``, ``d_y``, and ``d_z`` (default: 0). copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = CartesianRepresentation def __init__(self, d_x, d_y=None, d_z=None, unit=None, xyz_axis=None, copy=True): if d_y is None and d_z is None: if xyz_axis is not None and xyz_axis != 0: d_x = np.rollaxis(d_x, xyz_axis, 0) d_x, d_y, d_z = d_x elif xyz_axis is not None: raise ValueError("xyz_axis should only be set if d_x, d_y, and d_z " "are in a single array passed in through d_x, " "i.e., d_y and d_z should not be not given.") elif ((d_y is None and d_z is not None) or (d_y is not None and d_z is None)): raise ValueError("d_x, d_y, and d_z are required to instantiate {0}" .format(self.__class__.__name__)) if unit is not None: d_x = u.Quantity(d_x, unit, copy=copy, subok=True) d_y = u.Quantity(d_y, unit, copy=copy, subok=True) d_z = u.Quantity(d_z, unit, copy=copy, subok=True) copy = False super().__init__(d_x, d_y, d_z, copy=copy) if not (self._d_x.unit.is_equivalent(self._d_y.unit) and self._d_x.unit.is_equivalent(self._d_z.unit)): raise u.UnitsError('d_x, d_y and d_z should have equivalent units.') def to_cartesian(self, base=None): return CartesianRepresentation(*[getattr(self, c) for c in self.components]) @classmethod def from_cartesian(cls, other, base=None): return cls(*[getattr(other, c) for c in other.components]) def get_d_xyz(self, xyz_axis=0): """Return a vector array of the x, y, and z coordinates. Parameters ---------- xyz_axis : int, optional The axis in the final array along which the x, y, z components should be stored (default: 0). Returns ------- xyz : `~astropy.units.Quantity` With dimension 3 along ``xyz_axis``. """ return _combine_xyz(self._d_x, self._d_y, self._d_z, xyz_axis=xyz_axis) d_xyz = property(get_d_xyz) class BaseSphericalDifferential(BaseDifferential): def _d_lon_coslat(self, base): """Convert longitude differential d_lon to d_lon_coslat. Parameters ---------- base : instance of ``cls.base_representation`` The base from which the latitude will be taken. """ self._check_base(base) return self.d_lon * np.cos(base.lat) @classmethod def _get_d_lon(cls, d_lon_coslat, base): """Convert longitude differential d_lon_coslat to d_lon. Parameters ---------- d_lon_coslat : `~astropy.units.Quantity` Longitude differential that includes ``cos(lat)``. base : instance of ``cls.base_representation`` The base from which the latitude will be taken. """ cls._check_base(base) return d_lon_coslat / np.cos(base.lat) def _combine_operation(self, op, other, reverse=False): """Combine two differentials, or a differential with a representation. If ``other`` is of the same differential type as ``self``, the components will simply be combined. If both are different parts of a `~astropy.coordinates.SphericalDifferential` (e.g., a `~astropy.coordinates.UnitSphericalDifferential` and a `~astropy.coordinates.RadialDifferential`), they will combined appropriately. If ``other`` is a representation, it will be used as a base for which to evaluate the differential, and the result is a new representation. Parameters ---------- op : `~operator` callable Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc. other : `~astropy.coordinates.BaseRepresentation` instance The other differential or representation. reverse : bool Whether the operands should be reversed (e.g., as we got here via ``self.__rsub__`` because ``self`` is a subclass of ``other``). """ if (isinstance(other, BaseSphericalDifferential) and not isinstance(self, type(other)) or isinstance(other, RadialDifferential)): all_components = set(self.components) | set(other.components) first, second = (self, other) if not reverse else (other, self) result_args = {c: op(getattr(first, c, 0.), getattr(second, c, 0.)) for c in all_components} return SphericalDifferential(**result_args) return super()._combine_operation(op, other, reverse) class UnitSphericalDifferential(BaseSphericalDifferential): """Differential(s) of points on a unit sphere. Parameters ---------- d_lon, d_lat : `~astropy.units.Quantity` The longitude and latitude of the differentials. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = UnitSphericalRepresentation @classproperty def _dimensional_differential(cls): return SphericalDifferential def __init__(self, d_lon, d_lat, copy=True): super().__init__(d_lon, d_lat, copy=copy) if not self._d_lon.unit.is_equivalent(self._d_lat.unit): raise u.UnitsError('d_lon and d_lat should have equivalent units.') def to_cartesian(self, base): if isinstance(base, SphericalRepresentation): scale = base.distance elif isinstance(base, PhysicsSphericalRepresentation): scale = base.r else: return super().to_cartesian(base) base = base.represent_as(UnitSphericalRepresentation) return scale * super().to_cartesian(base) def represent_as(self, other_class, base=None): # Only have enough information to represent other unit-spherical. if issubclass(other_class, UnitSphericalCosLatDifferential): return other_class(self._d_lon_coslat(base), self.d_lat) return super().represent_as(other_class, base) @classmethod def from_representation(cls, representation, base=None): # All spherical differentials can be done without going to Cartesian, # though CosLat needs base for the latitude. if isinstance(representation, SphericalDifferential): return cls(representation.d_lon, representation.d_lat) elif isinstance(representation, (SphericalCosLatDifferential, UnitSphericalCosLatDifferential)): d_lon = cls._get_d_lon(representation.d_lon_coslat, base) return cls(d_lon, representation.d_lat) elif isinstance(representation, PhysicsSphericalDifferential): return cls(representation.d_phi, -representation.d_theta) return super().from_representation(representation, base) class SphericalDifferential(BaseSphericalDifferential): """Differential(s) of points in 3D spherical coordinates. Parameters ---------- d_lon, d_lat : `~astropy.units.Quantity` The differential longitude and latitude. d_distance : `~astropy.units.Quantity` The differential distance. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = SphericalRepresentation _unit_differential = UnitSphericalDifferential def __init__(self, d_lon, d_lat, d_distance, copy=True): super().__init__(d_lon, d_lat, d_distance, copy=copy) if not self._d_lon.unit.is_equivalent(self._d_lat.unit): raise u.UnitsError('d_lon and d_lat should have equivalent units.') def represent_as(self, other_class, base=None): # All spherical differentials can be done without going to Cartesian, # though CosLat needs base for the latitude. if issubclass(other_class, UnitSphericalDifferential): return other_class(self.d_lon, self.d_lat) elif issubclass(other_class, RadialDifferential): return other_class(self.d_distance) elif issubclass(other_class, SphericalCosLatDifferential): return other_class(self._d_lon_coslat(base), self.d_lat, self.d_distance) elif issubclass(other_class, UnitSphericalCosLatDifferential): return other_class(self._d_lon_coslat(base), self.d_lat) elif issubclass(other_class, PhysicsSphericalDifferential): return other_class(self.d_lon, -self.d_lat, self.d_distance) else: return super().represent_as(other_class, base) @classmethod def from_representation(cls, representation, base=None): # Other spherical differentials can be done without going to Cartesian, # though CosLat needs base for the latitude. if isinstance(representation, SphericalCosLatDifferential): d_lon = cls._get_d_lon(representation.d_lon_coslat, base) return cls(d_lon, representation.d_lat, representation.d_distance) elif isinstance(representation, PhysicsSphericalDifferential): return cls(representation.d_phi, -representation.d_theta, representation.d_r) return super().from_representation(representation, base) class BaseSphericalCosLatDifferential(BaseDifferential): """Differtials from points on a spherical base representation. With cos(lat) assumed to be included in the longitude differential. """ @classmethod def _get_base_vectors(cls, base): """Get unit vectors and scale factors from (unit)spherical base. Parameters ---------- base : instance of ``self.base_representation`` The points for which the unit vectors and scale factors should be retrieved. Returns ------- unit_vectors : dict of `CartesianRepresentation` In the directions of the coordinates of base. scale_factors : dict of `~astropy.units.Quantity` Scale factors for each of the coordinates. The scale factor for longitude does not include the cos(lat) factor. Raises ------ TypeError : if the base is not of the correct type """ cls._check_base(base) return base.unit_vectors(), base.scale_factors(omit_coslat=True) def _d_lon(self, base): """Convert longitude differential with cos(lat) to one without. Parameters ---------- base : instance of ``cls.base_representation`` The base from which the latitude will be taken. """ self._check_base(base) return self.d_lon_coslat / np.cos(base.lat) @classmethod def _get_d_lon_coslat(cls, d_lon, base): """Convert longitude differential d_lon to d_lon_coslat. Parameters ---------- d_lon : `~astropy.units.Quantity` Value of the longitude differential without ``cos(lat)``. base : instance of ``cls.base_representation`` The base from which the latitude will be taken. """ cls._check_base(base) return d_lon * np.cos(base.lat) def _combine_operation(self, op, other, reverse=False): """Combine two differentials, or a differential with a representation. If ``other`` is of the same differential type as ``self``, the components will simply be combined. If both are different parts of a `~astropy.coordinates.SphericalDifferential` (e.g., a `~astropy.coordinates.UnitSphericalDifferential` and a `~astropy.coordinates.RadialDifferential`), they will combined appropriately. If ``other`` is a representation, it will be used as a base for which to evaluate the differential, and the result is a new representation. Parameters ---------- op : `~operator` callable Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc. other : `~astropy.coordinates.BaseRepresentation` instance The other differential or representation. reverse : bool Whether the operands should be reversed (e.g., as we got here via ``self.__rsub__`` because ``self`` is a subclass of ``other``). """ if (isinstance(other, BaseSphericalCosLatDifferential) and not isinstance(self, type(other)) or isinstance(other, RadialDifferential)): all_components = set(self.components) | set(other.components) first, second = (self, other) if not reverse else (other, self) result_args = {c: op(getattr(first, c, 0.), getattr(second, c, 0.)) for c in all_components} return SphericalCosLatDifferential(**result_args) return super()._combine_operation(op, other, reverse) class UnitSphericalCosLatDifferential(BaseSphericalCosLatDifferential): """Differential(s) of points on a unit sphere. Parameters ---------- d_lon_coslat, d_lat : `~astropy.units.Quantity` The longitude and latitude of the differentials. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = UnitSphericalRepresentation attr_classes = OrderedDict([('d_lon_coslat', u.Quantity), ('d_lat', u.Quantity)]) @classproperty def _dimensional_differential(cls): return SphericalCosLatDifferential def __init__(self, d_lon_coslat, d_lat, copy=True): super().__init__(d_lon_coslat, d_lat, copy=copy) if not self._d_lon_coslat.unit.is_equivalent(self._d_lat.unit): raise u.UnitsError('d_lon_coslat and d_lat should have equivalent ' 'units.') def to_cartesian(self, base): if isinstance(base, SphericalRepresentation): scale = base.distance elif isinstance(base, PhysicsSphericalRepresentation): scale = base.r else: return super().to_cartesian(base) base = base.represent_as(UnitSphericalRepresentation) return scale * super().to_cartesian(base) def represent_as(self, other_class, base=None): # Only have enough information to represent other unit-spherical. if issubclass(other_class, UnitSphericalDifferential): return other_class(self._d_lon(base), self.d_lat) return super().represent_as(other_class, base) @classmethod def from_representation(cls, representation, base=None): # All spherical differentials can be done without going to Cartesian, # though w/o CosLat needs base for the latitude. if isinstance(representation, SphericalCosLatDifferential): return cls(representation.d_lon_coslat, representation.d_lat) elif isinstance(representation, (SphericalDifferential, UnitSphericalDifferential)): d_lon_coslat = cls._get_d_lon_coslat(representation.d_lon, base) return cls(d_lon_coslat, representation.d_lat) elif isinstance(representation, PhysicsSphericalDifferential): d_lon_coslat = cls._get_d_lon_coslat(representation.d_phi, base) return cls(d_lon_coslat, -representation.d_theta) return super().from_representation(representation, base) class SphericalCosLatDifferential(BaseSphericalCosLatDifferential): """Differential(s) of points in 3D spherical coordinates. Parameters ---------- d_lon_coslat, d_lat : `~astropy.units.Quantity` The differential longitude (with cos(lat) included) and latitude. d_distance : `~astropy.units.Quantity` The differential distance. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = SphericalRepresentation _unit_differential = UnitSphericalCosLatDifferential attr_classes = OrderedDict([('d_lon_coslat', u.Quantity), ('d_lat', u.Quantity), ('d_distance', u.Quantity)]) def __init__(self, d_lon_coslat, d_lat, d_distance, copy=True): super().__init__(d_lon_coslat, d_lat, d_distance, copy=copy) if not self._d_lon_coslat.unit.is_equivalent(self._d_lat.unit): raise u.UnitsError('d_lon_coslat and d_lat should have equivalent ' 'units.') def represent_as(self, other_class, base=None): # All spherical differentials can be done without going to Cartesian, # though some need base for the latitude to remove cos(lat). if issubclass(other_class, UnitSphericalCosLatDifferential): return other_class(self.d_lon_coslat, self.d_lat) elif issubclass(other_class, RadialDifferential): return other_class(self.d_distance) elif issubclass(other_class, SphericalDifferential): return other_class(self._d_lon(base), self.d_lat, self.d_distance) elif issubclass(other_class, UnitSphericalDifferential): return other_class(self._d_lon(base), self.d_lat) elif issubclass(other_class, PhysicsSphericalDifferential): return other_class(self._d_lon(base), -self.d_lat, self.d_distance) return super().represent_as(other_class, base) @classmethod def from_representation(cls, representation, base=None): # Other spherical differentials can be done without going to Cartesian, # though we need base for the latitude to remove coslat. if isinstance(representation, SphericalDifferential): d_lon_coslat = cls._get_d_lon_coslat(representation.d_lon, base) return cls(d_lon_coslat, representation.d_lat, representation.d_distance) elif isinstance(representation, PhysicsSphericalDifferential): d_lon_coslat = cls._get_d_lon_coslat(representation.d_phi, base) return cls(d_lon_coslat, -representation.d_theta, representation.d_r) return super().from_representation(representation, base) class RadialDifferential(BaseDifferential): """Differential(s) of radial distances. Parameters ---------- d_distance : `~astropy.units.Quantity` The differential distance. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = RadialRepresentation def to_cartesian(self, base): return self.d_distance * base.represent_as( UnitSphericalRepresentation).to_cartesian() @classmethod def from_cartesian(cls, other, base): return cls(other.dot(base.represent_as(UnitSphericalRepresentation)), copy=False) @classmethod def from_representation(cls, representation, base=None): if isinstance(representation, (SphericalDifferential, SphericalCosLatDifferential)): return cls(representation.d_distance) elif isinstance(representation, PhysicsSphericalDifferential): return cls(representation.d_r) else: return super().from_representation(representation, base) def _combine_operation(self, op, other, reverse=False): if isinstance(other, self.base_representation): if reverse: first, second = other.distance, self.d_distance else: first, second = self.d_distance, other.distance return other.__class__(op(first, second), copy=False) elif isinstance(other, (BaseSphericalDifferential, BaseSphericalCosLatDifferential)): all_components = set(self.components) | set(other.components) first, second = (self, other) if not reverse else (other, self) result_args = {c: op(getattr(first, c, 0.), getattr(second, c, 0.)) for c in all_components} return SphericalDifferential(**result_args) else: return super()._combine_operation(op, other, reverse) class PhysicsSphericalDifferential(BaseDifferential): """Differential(s) of 3D spherical coordinates using physics convention. Parameters ---------- d_phi, d_theta : `~astropy.units.Quantity` The differential azimuth and inclination. d_r : `~astropy.units.Quantity` The differential radial distance. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = PhysicsSphericalRepresentation def __init__(self, d_phi, d_theta, d_r, copy=True): super().__init__(d_phi, d_theta, d_r, copy=copy) if not self._d_phi.unit.is_equivalent(self._d_theta.unit): raise u.UnitsError('d_phi and d_theta should have equivalent ' 'units.') def represent_as(self, other_class, base=None): # All spherical differentials can be done without going to Cartesian, # though CosLat needs base for the latitude. For those, explicitly # do the equivalent of self._d_lon_coslat in SphericalDifferential. if issubclass(other_class, SphericalDifferential): return other_class(self.d_phi, -self.d_theta, self.d_r) elif issubclass(other_class, UnitSphericalDifferential): return other_class(self.d_phi, -self.d_theta) elif issubclass(other_class, SphericalCosLatDifferential): self._check_base(base) d_lon_coslat = self.d_phi * np.sin(base.theta) return other_class(d_lon_coslat, -self.d_theta, self.d_r) elif issubclass(other_class, UnitSphericalCosLatDifferential): self._check_base(base) d_lon_coslat = self.d_phi * np.sin(base.theta) return other_class(d_lon_coslat, -self.d_theta) elif issubclass(other_class, RadialDifferential): return other_class(self.d_r) return super().represent_as(other_class, base) @classmethod def from_representation(cls, representation, base=None): # Other spherical differentials can be done without going to Cartesian, # though we need base for the latitude to remove coslat. For that case, # do the equivalent of cls._d_lon in SphericalDifferential. if isinstance(representation, SphericalDifferential): return cls(representation.d_lon, -representation.d_lat, representation.d_distance) elif isinstance(representation, SphericalCosLatDifferential): cls._check_base(base) d_phi = representation.d_lon_coslat / np.sin(base.theta) return cls(d_phi, -representation.d_lat, representation.d_distance) return super().from_representation(representation, base) class CylindricalDifferential(BaseDifferential): """Differential(s) of points in cylindrical coordinates. Parameters ---------- d_rho : `~astropy.units.Quantity` The differential cylindrical radius. d_phi : `~astropy.units.Quantity` The differential azimuth. d_z : `~astropy.units.Quantity` The differential height. copy : bool, optional If `True` (default), arrays will be copied rather than referenced. """ base_representation = CylindricalRepresentation def __init__(self, d_rho, d_phi, d_z, copy=False): super().__init__(d_rho, d_phi, d_z, copy=copy) if not self._d_rho.unit.is_equivalent(self._d_z.unit): raise u.UnitsError("d_rho and d_z should have equivalent units.")
23826b6f9965ffcd5d2e49544acc399d0aa689f430bb4a418a451a1793c4abc2
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains convenience functions for getting a coordinate object for a named object by querying SESAME and getting the first returned result. Note that this is intended to be a convenience, and is very simple. If you need precise coordinates for an object you should find the appropriate reference for that measurement and input the coordinates manually. """ # Standard library import os import re import socket import urllib.request import urllib.parse import urllib.error # Astropy from .. import units as u from .sky_coordinate import SkyCoord from ..utils import data from ..utils.state import ScienceState __all__ = ["get_icrs_coordinates"] class sesame_url(ScienceState): """ The URL(s) to Sesame's web-queryable database. """ _value = ["http://cdsweb.u-strasbg.fr/cgi-bin/nph-sesame/", "http://vizier.cfa.harvard.edu/viz-bin/nph-sesame/"] @classmethod def validate(cls, value): # TODO: Implement me return value class sesame_database(ScienceState): """ This specifies the default database that SESAME will query when using the name resolve mechanism in the coordinates subpackage. Default is to search all databases, but this can be 'all', 'simbad', 'ned', or 'vizier'. """ _value = 'all' @classmethod def validate(cls, value): if value not in ['all', 'simbad', 'ned', 'vizier']: raise ValueError("Unknown database '{0}'".format(value)) return value class NameResolveError(Exception): pass def _parse_response(resp_data): """ Given a string response from SESAME, parse out the coordinates by looking for a line starting with a J, meaning ICRS J2000 coordinates. Parameters ---------- resp_data : str The string HTTP response from SESAME. Returns ------- ra : str The string Right Ascension parsed from the HTTP response. dec : str The string Declination parsed from the HTTP response. """ pattr = re.compile(r"%J\s*([0-9\.]+)\s*([\+\-\.0-9]+)") matched = pattr.search(resp_data.decode('utf-8')) if matched is None: return None, None else: ra, dec = matched.groups() return ra, dec def get_icrs_coordinates(name): """ Retrieve an ICRS object by using an online name resolving service to retrieve coordinates for the specified name. By default, this will search all available databases until a match is found. If you would like to specify the database, use the science state ``astropy.coordinates.name_resolve.sesame_database``. You can also specify a list of servers to use for querying Sesame using the science state ``astropy.coordinates.name_resolve.sesame_url``. This will try each one in order until a valid response is returned. By default, this list includes the main Sesame host and a mirror at vizier. The configuration item `astropy.utils.data.Conf.remote_timeout` controls the number of seconds to wait for a response from the server before giving up. Parameters ---------- name : str The name of the object to get coordinates for, e.g. ``'M42'``. Returns ------- coord : `astropy.coordinates.ICRS` object The object's coordinates in the ICRS frame. """ database = sesame_database.get() # The web API just takes the first letter of the database name db = database.upper()[0] # Make sure we don't have duplicates in the url list urls = [] domains = [] for url in sesame_url.get(): domain = urllib.parse.urlparse(url).netloc # Check for duplicates if domain not in domains: domains.append(domain) # Add the query to the end of the url, add to url list fmt_url = os.path.join(url, "{db}?{name}") fmt_url = fmt_url.format(name=urllib.parse.quote(name), db=db) urls.append(fmt_url) exceptions = [] for url in urls: try: # Retrieve ascii name resolve data from CDS resp = urllib.request.urlopen(url, timeout=data.conf.remote_timeout) resp_data = resp.read() break except urllib.error.URLError as e: exceptions.append(e) continue except socket.timeout as e: # There are some cases where urllib2 does not catch socket.timeout # especially while receiving response data on an already previously # working request exceptions.append(e) continue # All Sesame URL's failed... else: messages = ["{url}: {e.reason}".format(url=url, e=e) for url, e in zip(urls, exceptions)] raise NameResolveError("All Sesame queries failed. Unable to " "retrieve coordinates. See errors per URL " "below: \n {}".format("\n".join(messages))) ra, dec = _parse_response(resp_data) if ra is None and dec is None: if db == "A": err = "Unable to find coordinates for name '{0}'".format(name) else: err = "Unable to find coordinates for name '{0}' in database {1}"\ .format(name, database) raise NameResolveError(err) # Return SkyCoord object sc = SkyCoord(ra=ra, dec=dec, unit=(u.degree, u.degree), frame='icrs') return sc
445cd520bccd61624a756d53330807513bfbb48cbba0715cb0c2f3bcb8be6172
# -*- coding: utf-8 -*- # 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. """ This module contains utility functions that are for internal use in astropy.coordinates.angles. Mainly they are conversions from one format of data to another. """ import os from warnings import warn import numpy as np from .errors import (IllegalHourWarning, IllegalHourError, IllegalMinuteWarning, IllegalMinuteError, IllegalSecondWarning, IllegalSecondError) from ..utils import format_exception from .. import units as u class _AngleParser: """ Parses the various angle formats including: * 01:02:30.43 degrees * 1 2 0 hours * 1°2′3″ * 1d2m3s * -1h2m3s This class should not be used directly. Use `parse_angle` instead. """ def __init__(self): # TODO: in principle, the parser should be invalidated if we change unit # system (from CDS to FITS, say). Might want to keep a link to the # unit_registry used, and regenerate the parser/lexer if it changes. # Alternatively, perhaps one should not worry at all and just pre- # generate the parser for each release (as done for unit formats). # For some discussion of this problem, see # https://github.com/astropy/astropy/issues/5350#issuecomment-248770151 if '_parser' not in _AngleParser.__dict__: _AngleParser._parser, _AngleParser._lexer = self._make_parser() @classmethod def _get_simple_unit_names(cls): simple_units = set( u.radian.find_equivalent_units(include_prefix_units=True)) simple_unit_names = set() # We filter out degree and hourangle, since those are treated # separately. for unit in simple_units: if unit != u.deg and unit != u.hourangle: simple_unit_names.update(unit.names) return list(simple_unit_names) @classmethod def _make_parser(cls): from ..extern.ply import lex, yacc # List of token names. tokens = ( 'SIGN', 'UINT', 'UFLOAT', 'COLON', 'DEGREE', 'HOUR', 'MINUTE', 'SECOND', 'SIMPLE_UNIT' ) # NOTE THE ORDERING OF THESE RULES IS IMPORTANT!! # Regular expression rules for simple tokens def t_UFLOAT(t): r'((\d+\.\d*)|(\.\d+))([eE][+-−]?\d+)?' # The above includes Unicode "MINUS SIGN" \u2212. It is # important to include the hyphen last, or the regex will # treat this as a range. t.value = float(t.value.replace('−', '-')) return t def t_UINT(t): r'\d+' t.value = int(t.value) return t def t_SIGN(t): r'[+−-]' # The above include Unicode "MINUS SIGN" \u2212. It is # important to include the hyphen last, or the regex will # treat this as a range. if t.value == '+': t.value = 1.0 else: t.value = -1.0 return t def t_SIMPLE_UNIT(t): t.value = u.Unit(t.value) return t t_SIMPLE_UNIT.__doc__ = '|'.join( '(?:{0})'.format(x) for x in cls._get_simple_unit_names()) t_COLON = ':' t_DEGREE = r'd(eg(ree(s)?)?)?|°' t_HOUR = r'hour(s)?|h(r)?|ʰ' t_MINUTE = r'm(in(ute(s)?)?)?|′|\'|ᵐ' t_SECOND = r's(ec(ond(s)?)?)?|″|\"|ˢ' # A string containing ignored characters (spaces) t_ignore = ' ' # Error handling rule def t_error(t): raise ValueError( "Invalid character at col {0}".format(t.lexpos)) # Build the lexer lexer = lex.lex(optimize=True, lextab='angle_lextab', outputdir=os.path.dirname(__file__)) def p_angle(p): ''' angle : hms | dms | arcsecond | arcminute | simple ''' 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_ufloat(p): ''' ufloat : UFLOAT | UINT ''' p[0] = float(p[1]) def p_colon(p): ''' colon : sign UINT COLON ufloat | sign UINT COLON UINT COLON ufloat ''' if len(p) == 5: p[0] = (p[1] * p[2], p[4]) elif len(p) == 7: p[0] = (p[1] * p[2], p[4], p[6]) def p_spaced(p): ''' spaced : sign UINT ufloat | sign UINT UINT ufloat ''' if len(p) == 4: p[0] = (p[1] * p[2], p[3]) elif len(p) == 5: p[0] = (p[1] * p[2], p[3], p[4]) def p_generic(p): ''' generic : colon | spaced | sign UFLOAT | sign UINT ''' if len(p) == 2: p[0] = p[1] else: p[0] = p[1] * p[2] def p_hms(p): ''' hms : sign UINT HOUR | sign UINT HOUR ufloat | sign UINT HOUR UINT MINUTE | sign UINT HOUR UFLOAT MINUTE | sign UINT HOUR UINT MINUTE ufloat | sign UINT HOUR UINT MINUTE ufloat SECOND | generic HOUR ''' if len(p) == 3: p[0] = (p[1], u.hourangle) elif len(p) == 4: p[0] = (p[1] * p[2], u.hourangle) elif len(p) in (5, 6): p[0] = ((p[1] * p[2], p[4]), u.hourangle) elif len(p) in (7, 8): p[0] = ((p[1] * p[2], p[4], p[6]), u.hourangle) def p_dms(p): ''' dms : sign UINT DEGREE | sign UINT DEGREE ufloat | sign UINT DEGREE UINT MINUTE | sign UINT DEGREE UFLOAT MINUTE | sign UINT DEGREE UINT MINUTE ufloat | sign UINT DEGREE UINT MINUTE ufloat SECOND | generic DEGREE ''' if len(p) == 3: p[0] = (p[1], u.degree) elif len(p) == 4: p[0] = (p[1] * p[2], u.degree) elif len(p) in (5, 6): p[0] = ((p[1] * p[2], p[4]), u.degree) elif len(p) in (7, 8): p[0] = ((p[1] * p[2], p[4], p[6]), u.degree) def p_simple(p): ''' simple : generic | generic SIMPLE_UNIT ''' if len(p) == 2: p[0] = (p[1], None) else: p[0] = (p[1], p[2]) def p_arcsecond(p): ''' arcsecond : generic SECOND ''' p[0] = (p[1], u.arcsecond) def p_arcminute(p): ''' arcminute : generic MINUTE ''' p[0] = (p[1], u.arcminute) def p_error(p): raise ValueError parser = yacc.yacc(debug=False, tabmodule='angle_parsetab', outputdir=os.path.dirname(__file__), write_tables=True) return parser, lexer def parse(self, angle, unit, debug=False): try: found_angle, found_unit = self._parser.parse( angle, lexer=self._lexer, debug=debug) except ValueError as e: if str(e): raise ValueError("{0} in angle {1!r}".format( str(e), angle)) else: raise ValueError( "Syntax error parsing angle {0!r}".format(angle)) if unit is None and found_unit is None: raise u.UnitsError("No unit specified") return found_angle, found_unit def _check_hour_range(hrs): """ Checks that the given value is in the range (-24, 24). """ if np.any(np.abs(hrs) == 24.): warn(IllegalHourWarning(hrs, 'Treating as 24 hr')) elif np.any(hrs < -24.) or np.any(hrs > 24.): raise IllegalHourError(hrs) def _check_minute_range(m): """ Checks that the given value is in the range [0,60]. If the value is equal to 60, then a warning is raised. """ if np.any(m == 60.): warn(IllegalMinuteWarning(m, 'Treating as 0 min, +1 hr/deg')) elif np.any(m < -60.) or np.any(m > 60.): # "Error: minutes not in range [-60,60) ({0}).".format(min)) raise IllegalMinuteError(m) def _check_second_range(sec): """ Checks that the given value is in the range [0,60]. If the value is equal to 60, then a warning is raised. """ if np.any(sec == 60.): warn(IllegalSecondWarning(sec, 'Treating as 0 sec, +1 min')) elif sec is None: pass elif np.any(sec < -60.) or np.any(sec > 60.): # "Error: seconds not in range [-60,60) ({0}).".format(sec)) raise IllegalSecondError(sec) def check_hms_ranges(h, m, s): """ Checks that the given hour, minute and second are all within reasonable range. """ _check_hour_range(h) _check_minute_range(m) _check_second_range(s) return None def parse_angle(angle, unit=None, debug=False): """ Parses an input string value into an angle value. Parameters ---------- angle : str A string representing the angle. May be in one of the following forms: * 01:02:30.43 degrees * 1 2 0 hours * 1°2′3″ * 1d2m3s * -1h2m3s unit : `~astropy.units.UnitBase` instance, optional The unit used to interpret the string. If ``unit`` is not provided, the unit must be explicitly represented in the string, either at the end or as number separators. debug : bool, optional If `True`, print debugging information from the parser. Returns ------- value, unit : tuple ``value`` is the value as a floating point number or three-part tuple, and ``unit`` is a `Unit` instance which is either the unit passed in or the one explicitly mentioned in the input string. """ return _AngleParser().parse(angle, unit, debug=debug) def degrees_to_dms(d): """ Convert a floating-point degree value into a ``(degree, arcminute, arcsecond)`` tuple. """ sign = np.copysign(1.0, d) (df, d) = np.modf(np.abs(d)) # (degree fraction, degree) (mf, m) = np.modf(df * 60.) # (minute fraction, minute) s = mf * 60. return np.floor(sign * d), sign * np.floor(m), sign * s def dms_to_degrees(d, m, s=None): """ Convert degrees, arcminute, arcsecond to a float degrees value. """ _check_minute_range(m) _check_second_range(s) # determine sign sign = np.copysign(1.0, d) try: d = np.floor(np.abs(d)) if s is None: m = np.abs(m) s = 0 else: m = np.floor(np.abs(m)) s = np.abs(s) except ValueError: raise ValueError(format_exception( "{func}: dms values ({1[0]},{2[1]},{3[2]}) could not be " "converted to numbers.", d, m, s)) return sign * (d + m / 60. + s / 3600.) def hms_to_hours(h, m, s=None): """ Convert hour, minute, second to a float hour value. """ check_hms_ranges(h, m, s) # determine sign sign = np.copysign(1.0, h) try: h = np.floor(np.abs(h)) if s is None: m = np.abs(m) s = 0 else: m = np.floor(np.abs(m)) s = np.abs(s) except ValueError: raise ValueError(format_exception( "{func}: HMS values ({1[0]},{2[1]},{3[2]}) could not be " "converted to numbers.", h, m, s)) return sign * (h + m / 60. + s / 3600.) def hms_to_degrees(h, m, s): """ Convert hour, minute, second to a float degrees value. """ return hms_to_hours(h, m, s) * 15. def hms_to_radians(h, m, s): """ Convert hour, minute, second to a float radians value. """ return u.degree.to(u.radian, hms_to_degrees(h, m, s)) def hms_to_dms(h, m, s): """ Convert degrees, arcminutes, arcseconds to an ``(hour, minute, second)`` tuple. """ return degrees_to_dms(hms_to_degrees(h, m, s)) def hours_to_decimal(h): """ Convert any parseable hour value into a float value. """ from . import angles return angles.Angle(h, unit=u.hourangle).hour def hours_to_radians(h): """ Convert an angle in Hours to Radians. """ return u.hourangle.to(u.radian, h) def hours_to_hms(h): """ Convert an floating-point hour value into an ``(hour, minute, second)`` tuple. """ sign = np.copysign(1.0, h) (hf, h) = np.modf(np.abs(h)) # (degree fraction, degree) (mf, m) = np.modf(hf * 60.0) # (minute fraction, minute) s = mf * 60.0 return (np.floor(sign * h), sign * np.floor(m), sign * s) def radians_to_degrees(r): """ Convert an angle in Radians to Degrees. """ return u.radian.to(u.degree, r) def radians_to_hours(r): """ Convert an angle in Radians to Hours. """ return u.radian.to(u.hourangle, r) def radians_to_hms(r): """ Convert an angle in Radians to an ``(hour, minute, second)`` tuple. """ hours = radians_to_hours(r) return hours_to_hms(hours) def radians_to_dms(r): """ Convert an angle in Radians to an ``(degree, arcminute, arcsecond)`` tuple. """ degrees = u.radian.to(u.degree, r) return degrees_to_dms(degrees) def sexagesimal_to_string(values, precision=None, pad=False, sep=(':',), fields=3): """ Given an already separated tuple of sexagesimal values, returns a string. See `hours_to_string` and `degrees_to_string` for a higher-level interface to this functionality. """ # Check to see if values[0] is negative, using np.copysign to handle -0 sign = np.copysign(1.0, values[0]) # If the coordinates are negative, we need to take the absolute values. # We use np.abs because abs(-0) is -0 # TODO: Is this true? (MHvK, 2018-02-01: not on my system) values = [np.abs(value) for value in values] if pad: if sign == -1: pad = 3 else: pad = 2 else: pad = 0 if not isinstance(sep, tuple): sep = tuple(sep) if fields < 1 or fields > 3: raise ValueError( "fields must be 1, 2, or 3") if not sep: # empty string, False, or None, etc. sep = ('', '', '') elif len(sep) == 1: if fields == 3: sep = sep + (sep[0], '') elif fields == 2: sep = sep + ('', '') else: sep = ('', '', '') elif len(sep) == 2: sep = sep + ('',) elif len(sep) != 3: raise ValueError( "Invalid separator specification for converting angle to string.") # Simplify the expression based on the requested precision. For # example, if the seconds will round up to 60, we should convert # it to 0 and carry upwards. If the field is hidden (by the # fields kwarg) we round up around the middle, 30.0. if precision is None: rounding_thresh = 60.0 - (10.0 ** -4) else: rounding_thresh = 60.0 - (10.0 ** -precision) if fields == 3 and values[2] >= rounding_thresh: values[2] = 0.0 values[1] += 1.0 elif fields < 3 and values[2] >= 30.0: values[1] += 1.0 if fields >= 2 and values[1] >= 60.0: values[1] = 0.0 values[0] += 1.0 elif fields < 2 and values[1] >= 30.0: values[0] += 1.0 literal = [] last_value = '' literal.append('{0:0{pad}.0f}{sep[0]}') if fields >= 2: literal.append('{1:02d}{sep[1]}') if fields == 3: if precision is None: last_value = '{0:.4f}'.format(abs(values[2])) last_value = last_value.rstrip('0').rstrip('.') else: last_value = '{0:.{precision}f}'.format( abs(values[2]), precision=precision) if len(last_value) == 1 or last_value[1] == '.': last_value = '0' + last_value literal.append('{last_value}{sep[2]}') literal = ''.join(literal) return literal.format(np.copysign(values[0], sign), int(values[1]), values[2], sep=sep, pad=pad, last_value=last_value) def hours_to_string(h, precision=5, pad=False, sep=('h', 'm', 's'), fields=3): """ Takes a decimal hour value and returns a string formatted as hms with separator specified by the 'sep' parameter. ``h`` must be a scalar. """ h, m, s = hours_to_hms(h) return sexagesimal_to_string((h, m, s), precision=precision, pad=pad, sep=sep, fields=fields) def degrees_to_string(d, precision=5, pad=False, sep=':', fields=3): """ Takes a decimal hour value and returns a string formatted as dms with separator specified by the 'sep' parameter. ``d`` must be a scalar. """ d, m, s = degrees_to_dms(d) return sexagesimal_to_string((d, m, s), precision=precision, pad=pad, sep=sep, fields=fields) def angular_separation(lon1, lat1, lon2, lat2): """ Angular separation between two points on a sphere. Parameters ---------- lon1, lat1, lon2, lat2 : `Angle`, `~astropy.units.Quantity` or float Longitude and latitude of the two points. Quantities should be in angular units; floats in radians. Returns ------- angular separation : `~astropy.units.Quantity` or float Type depends on input; `Quantity` in angular units, or float in radians. Notes ----- The angular separation is calculated using the Vincenty formula [1]_, which is slightly more complex and computationally expensive than some alternatives, but is stable at at all distances, including the poles and antipodes. .. [1] https://en.wikipedia.org/wiki/Great-circle_distance """ sdlon = np.sin(lon2 - lon1) cdlon = np.cos(lon2 - lon1) slat1 = np.sin(lat1) slat2 = np.sin(lat2) clat1 = np.cos(lat1) clat2 = np.cos(lat2) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np.arctan2(np.hypot(num1, num2), denominator) def position_angle(lon1, lat1, lon2, lat2): """ Position Angle (East of North) between two points on a sphere. Parameters ---------- lon1, lat1, lon2, lat2 : `Angle`, `~astropy.units.Quantity` or float Longitude and latitude of the two points. Quantities should be in angular units; floats in radians. Returns ------- pa : `~astropy.coordinates.Angle` The (positive) position angle of the vector pointing from position 1 to position 2. If any of the angles are arrays, this will contain an array following the appropriate `numpy` broadcasting rules. """ from .angles import Angle deltalon = lon2 - lon1 colat = np.cos(lat2) x = np.sin(lat2) * np.cos(lat1) - colat * np.sin(lat1) * np.cos(deltalon) y = np.sin(deltalon) * colat return Angle(np.arctan2(y, x), u.radian).wrap_at(360*u.deg)
d7d904bfe5c982549f608d285422f0f7e71cff82a36979dca6980bea9e5def1c
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains a general framework for defining graphs of transformations between coordinates, suitable for either spatial coordinates or more generalized coordinate systems. The fundamental idea is that each class is a node in the transformation graph, and transitions from one node to another are defined as functions (or methods) wrapped in transformation objects. This module also includes more specific transformation classes for celestial/spatial coordinate frames, generally focused around matrix-style transformations that are typically how the algorithms are defined. """ import heapq import inspect import subprocess from warnings import warn from abc import ABCMeta, abstractmethod from collections import defaultdict, OrderedDict from contextlib import suppress from inspect import signature import numpy as np from .. import units as u from ..utils.exceptions import AstropyWarning from .representation import REPRESENTATION_CLASSES __all__ = ['TransformGraph', 'CoordinateTransform', 'FunctionTransform', 'BaseAffineTransform', 'AffineTransform', 'StaticMatrixTransform', 'DynamicMatrixTransform', 'FunctionTransformWithFiniteDifference', 'CompositeTransform'] def frame_attrs_from_set(frame_set): """ A `dict` of all the attributes of all frame classes in this `TransformGraph`. Broken out of the class so this can be called on a temporary frame set to validate new additions to the transform graph before actually adding them. """ result = {} for frame_cls in frame_set: result.update(frame_cls.frame_attributes) return result def frame_comps_from_set(frame_set): """ A `set` of all component names every defined within any frame class in this `TransformGraph`. Broken out of the class so this can be called on a temporary frame set to validate new additions to the transform graph before actually adding them. """ result = set() for frame_cls in frame_set: rep_info = frame_cls._frame_specific_representation_info for mappings in rep_info.values(): for rep_map in mappings: result.update([rep_map.framename]) return result class TransformGraph: """ A graph representing the paths between coordinate frames. """ def __init__(self): self._graph = defaultdict(dict) self.invalidate_cache() # generates cache entries @property def _cached_names(self): if self._cached_names_dct is None: self._cached_names_dct = dct = {} for c in self.frame_set: nm = getattr(c, 'name', None) if nm is not None: dct[nm] = c return self._cached_names_dct @property def frame_set(self): """ A `set` of all the frame classes present in this `TransformGraph`. """ if self._cached_frame_set is None: self._cached_frame_set = set() for a in self._graph: self._cached_frame_set.add(a) for b in self._graph[a]: self._cached_frame_set.add(b) return self._cached_frame_set.copy() @property def frame_attributes(self): """ A `dict` of all the attributes of all frame classes in this `TransformGraph`. """ if self._cached_frame_attributes is None: self._cached_frame_attributes = frame_attrs_from_set(self.frame_set) return self._cached_frame_attributes @property def frame_component_names(self): """ A `set` of all component names every defined within any frame class in this `TransformGraph`. """ if self._cached_component_names is None: self._cached_component_names = frame_comps_from_set(self.frame_set) return self._cached_component_names def invalidate_cache(self): """ Invalidates the cache that stores optimizations for traversing the transform graph. This is called automatically when transforms are added or removed, but will need to be called manually if weights on transforms are modified inplace. """ self._cached_names_dct = None self._cached_frame_set = None self._cached_frame_attributes = None self._cached_component_names = None self._shortestpaths = {} self._composite_cache = {} def add_transform(self, fromsys, tosys, transform): """ Add a new coordinate transformation to the graph. Parameters ---------- fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. transform : CoordinateTransform or similar callable The transformation object. Typically a `CoordinateTransform` object, although it may be some other callable that is called with the same signature. Raises ------ TypeError If ``fromsys`` or ``tosys`` are not classes or ``transform`` is not callable. """ if not inspect.isclass(fromsys): raise TypeError('fromsys must be a class') if not inspect.isclass(tosys): raise TypeError('tosys must be a class') if not callable(transform): raise TypeError('transform must be callable') frame_set = self.frame_set.copy() frame_set.add(fromsys) frame_set.add(tosys) # Now we check to see if any attributes on the proposed frames override # *any* component names, which we can't allow for some of the logic in # the SkyCoord initializer to work attrs = set(frame_attrs_from_set(frame_set).keys()) comps = frame_comps_from_set(frame_set) invalid_attrs = attrs.intersection(comps) if invalid_attrs: invalid_frames = set() for attr in invalid_attrs: if attr in fromsys.frame_attributes: invalid_frames.update([fromsys]) if attr in tosys.frame_attributes: invalid_frames.update([tosys]) raise ValueError("Frame(s) {0} contain invalid attribute names: {1}" "\nFrame attributes can not conflict with *any* of" " the frame data component names (see" " `frame_transform_graph.frame_component_names`)." .format(list(invalid_frames), invalid_attrs)) self._graph[fromsys][tosys] = transform self.invalidate_cache() def remove_transform(self, fromsys, tosys, transform): """ Removes a coordinate transform from the graph. Parameters ---------- fromsys : class or `None` The coordinate frame *class* to start from. If `None`, ``transform`` will be searched for and removed (``tosys`` must also be `None`). tosys : class or `None` The coordinate frame *class* to transform into. If `None`, ``transform`` will be searched for and removed (``fromsys`` must also be `None`). transform : callable or `None` The transformation object to be removed or `None`. If `None` and ``tosys`` and ``fromsys`` are supplied, there will be no check to ensure the correct object is removed. """ if fromsys is None or tosys is None: if not (tosys is None and fromsys is None): raise ValueError('fromsys and tosys must both be None if either are') if transform is None: raise ValueError('cannot give all Nones to remove_transform') # search for the requested transform by brute force and remove it for a in self._graph: agraph = self._graph[a] for b in agraph: if b is transform: del agraph[b] break else: raise ValueError('Could not find transform {0} in the ' 'graph'.format(transform)) else: if transform is None: self._graph[fromsys].pop(tosys, None) else: curr = self._graph[fromsys].get(tosys, None) if curr is transform: self._graph[fromsys].pop(tosys) else: raise ValueError('Current transform from {0} to {1} is not ' '{2}'.format(fromsys, tosys, transform)) self.invalidate_cache() def find_shortest_path(self, fromsys, tosys): """ Computes the shortest distance along the transform graph from one system to another. Parameters ---------- fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. Returns ------- path : list of classes or `None` The path from ``fromsys`` to ``tosys`` as an in-order sequence of classes. This list includes *both* ``fromsys`` and ``tosys``. Is `None` if there is no possible path. distance : number The total distance/priority from ``fromsys`` to ``tosys``. If priorities are not set this is the number of transforms needed. Is ``inf`` if there is no possible path. """ inf = float('inf') # special-case the 0 or 1-path if tosys is fromsys: if tosys not in self._graph[fromsys]: # Means there's no transform necessary to go from it to itself. return [tosys], 0 if tosys in self._graph[fromsys]: # this will also catch the case where tosys is fromsys, but has # a defined transform. t = self._graph[fromsys][tosys] return [fromsys, tosys], float(t.priority if hasattr(t, 'priority') else 1) # otherwise, need to construct the path: if fromsys in self._shortestpaths: # already have a cached result fpaths = self._shortestpaths[fromsys] if tosys in fpaths: return fpaths[tosys] else: return None, inf # use Dijkstra's algorithm to find shortest path in all other cases nodes = [] # first make the list of nodes for a in self._graph: if a not in nodes: nodes.append(a) for b in self._graph[a]: if b not in nodes: nodes.append(b) if fromsys not in nodes or tosys not in nodes: # fromsys or tosys are isolated or not registered, so there's # certainly no way to get from one to the other return None, inf edgeweights = {} # construct another graph that is a dict of dicts of priorities # (used as edge weights in Dijkstra's algorithm) for a in self._graph: edgeweights[a] = aew = {} agraph = self._graph[a] for b in agraph: aew[b] = float(agraph[b].priority if hasattr(agraph[b], 'priority') else 1) # entries in q are [distance, count, nodeobj, pathlist] # count is needed because in py 3.x, tie-breaking fails on the nodes. # this way, insertion order is preserved if the weights are the same q = [[inf, i, n, []] for i, n in enumerate(nodes) if n is not fromsys] q.insert(0, [0, -1, fromsys, []]) # this dict will store the distance to node from ``fromsys`` and the path result = {} # definitely starts as a valid heap because of the insert line; from the # node to itself is always the shortest distance while len(q) > 0: d, orderi, n, path = heapq.heappop(q) if d == inf: # everything left is unreachable from fromsys, just copy them to # the results and jump out of the loop result[n] = (None, d) for d, orderi, n, path in q: result[n] = (None, d) break else: result[n] = (path, d) path.append(n) if n not in edgeweights: # this is a system that can be transformed to, but not from. continue for n2 in edgeweights[n]: if n2 not in result: # already visited # find where n2 is in the heap for i in range(len(q)): if q[i][2] == n2: break else: raise ValueError('n2 not in heap - this should be impossible!') newd = d + edgeweights[n][n2] if newd < q[i][0]: q[i][0] = newd q[i][3] = list(path) heapq.heapify(q) # cache for later use self._shortestpaths[fromsys] = result return result[tosys] def get_transform(self, fromsys, tosys): """ Generates and returns the `CompositeTransform` for a transformation between two coordinate systems. Parameters ---------- fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. Returns ------- trans : `CompositeTransform` or `None` If there is a path from ``fromsys`` to ``tosys``, this is a transform object for that path. If no path could be found, this is `None`. Notes ----- This function always returns a `CompositeTransform`, because `CompositeTransform` is slightly more adaptable in the way it can be called than other transform classes. Specifically, it takes care of intermediate steps of transformations in a way that is consistent with 1-hop transformations. """ if not inspect.isclass(fromsys): raise TypeError('fromsys is not a class') if not inspect.isclass(tosys): raise TypeError('tosys is not a class') path, distance = self.find_shortest_path(fromsys, tosys) if path is None: return None transforms = [] currsys = fromsys for p in path[1:]: # first element is fromsys so we skip it transforms.append(self._graph[currsys][p]) currsys = p fttuple = (fromsys, tosys) if fttuple not in self._composite_cache: comptrans = CompositeTransform(transforms, fromsys, tosys, register_graph=False) self._composite_cache[fttuple] = comptrans return self._composite_cache[fttuple] def lookup_name(self, name): """ Tries to locate the coordinate class with the provided alias. Parameters ---------- name : str The alias to look up. Returns ------- coordcls The coordinate class corresponding to the ``name`` or `None` if no such class exists. """ return self._cached_names.get(name, None) def get_names(self): """ Returns all available transform names. They will all be valid arguments to `lookup_name`. Returns ------- nms : list The aliases for coordinate systems. """ return list(self._cached_names.keys()) def to_dot_graph(self, priorities=True, addnodes=[], savefn=None, savelayout='plain', saveformat=None, color_edges=True): """ Converts this transform graph to the graphviz_ DOT format. Optionally saves it (requires `graphviz`_ be installed and on your path). .. _graphviz: http://www.graphviz.org/ Parameters ---------- priorities : bool If `True`, show the priority values for each transform. Otherwise, the will not be included in the graph. addnodes : sequence of str Additional coordinate systems to add (this can include systems already in the transform graph, but they will only appear once). savefn : `None` or str The file name to save this graph to or `None` to not save to a file. savelayout : str The graphviz program to use to layout the graph (see graphviz_ for details) or 'plain' to just save the DOT graph content. Ignored if ``savefn`` is `None`. saveformat : str The graphviz output format. (e.g. the ``-Txxx`` option for the command line program - see graphviz docs for details). Ignored if ``savefn`` is `None`. color_edges : bool Color the edges between two nodes (frames) based on the type of transform. ``FunctionTransform``: red, ``StaticMatrixTransform``: blue, ``DynamicMatrixTransform``: green. Returns ------- dotgraph : str A string with the DOT format graph. """ nodes = [] # find the node names for a in self._graph: if a not in nodes: nodes.append(a) for b in self._graph[a]: if b not in nodes: nodes.append(b) for node in addnodes: if node not in nodes: nodes.append(node) nodenames = [] invclsaliases = dict([(v, k) for k, v in self._cached_names.items()]) for n in nodes: if n in invclsaliases: nodenames.append('{0} [shape=oval label="{0}\\n`{1}`"]'.format(n.__name__, invclsaliases[n])) else: nodenames.append(n.__name__ + '[ shape=oval ]') edgenames = [] # Now the edges for a in self._graph: agraph = self._graph[a] for b in agraph: transform = agraph[b] pri = transform.priority if hasattr(transform, 'priority') else 1 color = trans_to_color[transform.__class__] if color_edges else 'black' edgenames.append((a.__name__, b.__name__, pri, color)) # generate simple dot format graph lines = ['digraph AstropyCoordinateTransformGraph {'] lines.append('; '.join(nodenames) + ';') for enm1, enm2, weights, color in edgenames: labelstr_fmt = '[ {0} {1} ]' if priorities: priority_part = 'label = "{0}"'.format(weights) else: priority_part = '' color_part = 'color = "{0}"'.format(color) labelstr = labelstr_fmt.format(priority_part, color_part) lines.append('{0} -> {1}{2};'.format(enm1, enm2, labelstr)) lines.append('') lines.append('overlap=false') lines.append('}') dotgraph = '\n'.join(lines) if savefn is not None: if savelayout == 'plain': with open(savefn, 'w') as f: f.write(dotgraph) else: args = [savelayout] if saveformat is not None: args.append('-T' + saveformat) proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate(dotgraph) if proc.returncode != 0: raise OSError('problem running graphviz: \n' + stderr) with open(savefn, 'w') as f: f.write(stdout) return dotgraph def to_networkx_graph(self): """ Converts this transform graph into a networkx graph. .. note:: You must have the `networkx <http://networkx.lanl.gov/>`_ package installed for this to work. Returns ------- nxgraph : `networkx.Graph <http://networkx.lanl.gov/reference/classes.graph.html>`_ This `TransformGraph` as a `networkx.Graph`_. """ import networkx as nx nxgraph = nx.Graph() # first make the nodes for a in self._graph: if a not in nxgraph: nxgraph.add_node(a) for b in self._graph[a]: if b not in nxgraph: nxgraph.add_node(b) # Now the edges for a in self._graph: agraph = self._graph[a] for b in agraph: transform = agraph[b] pri = transform.priority if hasattr(transform, 'priority') else 1 color = trans_to_color[transform.__class__] nxgraph.add_edge(a, b, weight=pri, color=color) return nxgraph def transform(self, transcls, fromsys, tosys, priority=1, **kwargs): """ A function decorator for defining transformations. .. note:: If decorating a static method of a class, ``@staticmethod`` should be added *above* this decorator. Parameters ---------- transcls : class The class of the transformation object to create. fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : number The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. Additional keyword arguments are passed into the ``transcls`` constructor. Returns ------- deco : function A function that can be called on another function as a decorator (see example). Notes ----- This decorator assumes the first argument of the ``transcls`` initializer accepts a callable, and that the second and third are ``fromsys`` and ``tosys``. If this is not true, you should just initialize the class manually and use `add_transform` instead of using this decorator. Examples -------- :: graph = TransformGraph() class Frame1(BaseCoordinateFrame): ... class Frame2(BaseCoordinateFrame): ... @graph.transform(FunctionTransform, Frame1, Frame2) def f1_to_f2(f1_obj): ... do something with f1_obj ... return f2_obj """ def deco(func): # this doesn't do anything directly with the transform because # ``register_graph=self`` stores it in the transform graph # automatically transcls(func, fromsys, tosys, priority=priority, register_graph=self, **kwargs) return func return deco # <-------------------Define the builtin transform classes--------------------> class CoordinateTransform(metaclass=ABCMeta): """ An object that transforms a coordinate from one system to another. Subclasses must implement `__call__` with the provided signature. They should also call this superclass's ``__init__`` in their ``__init__``. Parameters ---------- fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : number The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. register_graph : `TransformGraph` or `None` A graph to register this transformation with on creation, or `None` to leave it unregistered. """ def __init__(self, fromsys, tosys, priority=1, register_graph=None): if not inspect.isclass(fromsys): raise TypeError('fromsys must be a class') if not inspect.isclass(tosys): raise TypeError('tosys must be a class') self.fromsys = fromsys self.tosys = tosys self.priority = float(priority) if register_graph: # this will do the type-checking when it adds to the graph self.register(register_graph) else: if not inspect.isclass(fromsys) or not inspect.isclass(tosys): raise TypeError('fromsys and tosys must be classes') self.overlapping_frame_attr_names = overlap = [] if (hasattr(fromsys, 'get_frame_attr_names') and hasattr(tosys, 'get_frame_attr_names')): # the if statement is there so that non-frame things might be usable # if it makes sense for from_nm in fromsys.get_frame_attr_names(): if from_nm in tosys.get_frame_attr_names(): overlap.append(from_nm) def register(self, graph): """ Add this transformation to the requested Transformation graph, replacing anything already connecting these two coordinates. Parameters ---------- graph : a TransformGraph object The graph to register this transformation with. """ graph.add_transform(self.fromsys, self.tosys, self) def unregister(self, graph): """ Remove this transformation from the requested transformation graph. Parameters ---------- graph : a TransformGraph object The graph to unregister this transformation from. Raises ------ ValueError If this is not currently in the transform graph. """ graph.remove_transform(self.fromsys, self.tosys, self) @abstractmethod def __call__(self, fromcoord, toframe): """ Does the actual coordinate transformation from the ``fromsys`` class to the ``tosys`` class. Parameters ---------- fromcoord : fromsys object An object of class matching ``fromsys`` that is to be transformed. toframe : object An object that has the attributes necessary to fully specify the frame. That is, it must have attributes with names that match the keys of the dictionary that ``tosys.get_frame_attr_names()`` returns. Typically this is of class ``tosys``, but it *might* be some other class as long as it has the appropriate attributes. Returns ------- tocoord : tosys object The new coordinate after the transform has been applied. """ class FunctionTransform(CoordinateTransform): """ A coordinate transformation defined by a function that accepts a coordinate object and returns the transformed coordinate object. Parameters ---------- func : callable The transformation function. Should have a call signature ``func(formcoord, toframe)``. Note that, unlike `CoordinateTransform.__call__`, ``toframe`` is assumed to be of type ``tosys`` for this function. fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : number The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. register_graph : `TransformGraph` or `None` A graph to register this transformation with on creation, or `None` to leave it unregistered. Raises ------ TypeError If ``func`` is not callable. ValueError If ``func`` cannot accept two arguments. """ def __init__(self, func, fromsys, tosys, priority=1, register_graph=None): if not callable(func): raise TypeError('func must be callable') with suppress(TypeError): sig = signature(func) kinds = [x.kind for x in sig.parameters.values()] if (len(x for x in kinds if x == sig.POSITIONAL_ONLY) != 2 and sig.VAR_POSITIONAL not in kinds): raise ValueError('provided function does not accept two arguments') self.func = func super().__init__(fromsys, tosys, priority=priority, register_graph=register_graph) def __call__(self, fromcoord, toframe): res = self.func(fromcoord, toframe) if not isinstance(res, self.tosys): raise TypeError('the transformation function yielded {0} but ' 'should have been of type {1}'.format(res, self.tosys)) if fromcoord.data.differentials and not res.data.differentials: warn("Applied a FunctionTransform to a coordinate frame with " "differentials, but the FunctionTransform does not handle " "differentials, so they have been dropped.", AstropyWarning) return res class FunctionTransformWithFiniteDifference(FunctionTransform): r""" A coordinate transformation that works like a `FunctionTransform`, but computes velocity shifts based on the finite-difference relative to one of the frame attributes. Note that the transform function should *not* change the differential at all in this case, as any differentials will be overridden. When a differential is in the from coordinate, the finite difference calculation has two components. The first part is simple the existing differential, but re-orientation (using finite-difference techniques) to point in the direction the velocity vector has in the *new* frame. The second component is the "induced" velocity. That is, the velocity intrinsic to the frame itself, estimated by shifting the frame using the ``finite_difference_frameattr_name`` frame attribute a small amount (``finite_difference_dt``) in time and re-calculating the position. Parameters ---------- finite_difference_frameattr_name : str or None The name of the frame attribute on the frames to use for the finite difference. Both the to and the from frame will be checked for this attribute, but only one needs to have it. If None, no velocity component induced from the frame itself will be included - only the re-orientation of any exsiting differential. finite_difference_dt : `~astropy.units.Quantity` or callable If a quantity, this is the size of the differential used to do the finite difference. If a callable, should accept ``(fromcoord, toframe)`` and return the ``dt`` value. symmetric_finite_difference : bool If True, the finite difference is computed as :math:`\frac{x(t + \Delta t / 2) - x(t + \Delta t / 2)}{\Delta t}`, or if False, :math:`\frac{x(t + \Delta t) - x(t)}{\Delta t}`. The latter case has slightly better performance (and more stable finite difference behavior). All other parameters are identical to the initializer for `FunctionTransform`. """ def __init__(self, func, fromsys, tosys, priority=1, register_graph=None, finite_difference_frameattr_name='obstime', finite_difference_dt=1*u.second, symmetric_finite_difference=True): super().__init__(func, fromsys, tosys, priority, register_graph) self.finite_difference_frameattr_name = finite_difference_frameattr_name self.finite_difference_dt = finite_difference_dt self.symmetric_finite_difference = symmetric_finite_difference @property def finite_difference_frameattr_name(self): return self._finite_difference_frameattr_name @finite_difference_frameattr_name.setter def finite_difference_frameattr_name(self, value): if value is None: self._diff_attr_in_fromsys = self._diff_attr_in_tosys = False else: diff_attr_in_fromsys = value in self.fromsys.frame_attributes diff_attr_in_tosys = value in self.tosys.frame_attributes if diff_attr_in_fromsys or diff_attr_in_tosys: self._diff_attr_in_fromsys = diff_attr_in_fromsys self._diff_attr_in_tosys = diff_attr_in_tosys else: raise ValueError('Frame attribute name {} is not a frame ' 'attribute of {} or {}'.format(value, self.fromsys, self.tosys)) self._finite_difference_frameattr_name = value def __call__(self, fromcoord, toframe): from .representation import (CartesianRepresentation, CartesianDifferential) supcall = self.func if fromcoord.data.differentials: # this is the finite difference case if callable(self.finite_difference_dt): dt = self.finite_difference_dt(fromcoord, toframe) else: dt = self.finite_difference_dt halfdt = dt/2 from_diffless = fromcoord.realize_frame(fromcoord.data.without_differentials()) reprwithoutdiff = supcall(from_diffless, toframe) # first we use the existing differential to compute an offset due to # the already-existing velocity, but in the new frame fromcoord_cart = fromcoord.cartesian if self.symmetric_finite_difference: fwdxyz = (fromcoord_cart.xyz + fromcoord_cart.differentials['s'].d_xyz*halfdt) fwd = supcall(fromcoord.realize_frame(CartesianRepresentation(fwdxyz)), toframe) backxyz = (fromcoord_cart.xyz - fromcoord_cart.differentials['s'].d_xyz*halfdt) back = supcall(fromcoord.realize_frame(CartesianRepresentation(backxyz)), toframe) else: fwdxyz = (fromcoord_cart.xyz + fromcoord_cart.differentials['s'].d_xyz*dt) fwd = supcall(fromcoord.realize_frame(CartesianRepresentation(fwdxyz)), toframe) back = reprwithoutdiff diffxyz = (fwd.cartesian - back.cartesian).xyz / dt # now we compute the "induced" velocities due to any movement in # the frame itself over time attrname = self.finite_difference_frameattr_name if attrname is not None: if self.symmetric_finite_difference: if self._diff_attr_in_fromsys: kws = {attrname: getattr(from_diffless, attrname) + halfdt} from_diffless_fwd = from_diffless.replicate(**kws) else: from_diffless_fwd = from_diffless if self._diff_attr_in_tosys: kws = {attrname: getattr(toframe, attrname) + halfdt} fwd_frame = toframe.replicate_without_data(**kws) else: fwd_frame = toframe fwd = supcall(from_diffless_fwd, fwd_frame) if self._diff_attr_in_fromsys: kws = {attrname: getattr(from_diffless, attrname) - halfdt} from_diffless_back = from_diffless.replicate(**kws) else: from_diffless_back = from_diffless if self._diff_attr_in_tosys: kws = {attrname: getattr(toframe, attrname) - halfdt} back_frame = toframe.replicate_without_data(**kws) else: back_frame = toframe back = supcall(from_diffless_back, back_frame) else: if self._diff_attr_in_fromsys: kws = {attrname: getattr(from_diffless, attrname) + dt} from_diffless_fwd = from_diffless.replicate(**kws) else: from_diffless_fwd = from_diffless if self._diff_attr_in_tosys: kws = {attrname: getattr(toframe, attrname) + dt} fwd_frame = toframe.replicate_without_data(**kws) else: fwd_frame = toframe fwd = supcall(from_diffless_fwd, fwd_frame) back = reprwithoutdiff diffxyz += (fwd.cartesian - back.cartesian).xyz / dt newdiff = CartesianDifferential(diffxyz) reprwithdiff = reprwithoutdiff.data.to_cartesian().with_differentials(newdiff) return reprwithoutdiff.realize_frame(reprwithdiff) else: return supcall(fromcoord, toframe) class BaseAffineTransform(CoordinateTransform): """Base class for common functionality between the ``AffineTransform``-type subclasses. This base class is needed because ``AffineTransform`` and the matrix transform classes share the ``_apply_transform()`` method, but have different ``__call__()`` methods. ``StaticMatrixTransform`` passes in a matrix stored as a class attribute, and both of the matrix transforms pass in ``None`` for the offset. Hence, user subclasses would likely want to subclass this (rather than ``AffineTransform``) if they want to provide alternative transformations using this machinery. """ def _apply_transform(self, fromcoord, matrix, offset): from .representation import (UnitSphericalRepresentation, CartesianDifferential, SphericalDifferential, SphericalCosLatDifferential, RadialDifferential) data = fromcoord.data has_velocity = 's' in data.differentials # list of unit differentials _unit_diffs = (SphericalDifferential._unit_differential, SphericalCosLatDifferential._unit_differential) unit_vel_diff = (has_velocity and isinstance(data.differentials['s'], _unit_diffs)) rad_vel_diff = (has_velocity and isinstance(data.differentials['s'], RadialDifferential)) # Some initial checking to short-circuit doing any re-representation if # we're going to fail anyways: if isinstance(data, UnitSphericalRepresentation) and offset is not None: raise TypeError("Position information stored on coordiante frame " "is insufficient to do a full-space position " "transformation (representation class: {0})" .format(data.__class__)) elif (has_velocity and (unit_vel_diff or rad_vel_diff) and offset is not None and 's' in offset.differentials): # Coordinate has a velocity, but it is not a full-space velocity # that we need to do a velocity offset raise TypeError("Velocity information stored on coordinate frame " "is insufficient to do a full-space velocity " "transformation (differential class: {0})" .format(data.differentials['s'].__class__)) elif len(data.differentials) > 1: # We should never get here because the frame initializer shouldn't # allow more differentials, but this just adds protection for # subclasses that somehow skip the checks raise ValueError("Representation passed to AffineTransform contains" " multiple associated differentials. Only a single" " differential with velocity units is presently" " supported (differentials: {0})." .format(str(data.differentials))) # If the representation is a UnitSphericalRepresentation, and this is # just a MatrixTransform, we have to try to turn the differential into a # Unit version of the differential (if no radial velocity) or a # sphericaldifferential with zero proper motion (if only a radial # velocity) so that the matrix operation works if (has_velocity and isinstance(data, UnitSphericalRepresentation) and not unit_vel_diff and not rad_vel_diff): # retrieve just velocity differential unit_diff = data.differentials['s'].represent_as( data.differentials['s']._unit_differential, data) data = data.with_differentials({'s': unit_diff}) # updates key # If it's a RadialDifferential, we flat-out ignore the differentials # This is because, by this point (past the validation above), we can # only possibly be doing a rotation-only transformation, and that # won't change the radial differential. We later add it back in elif rad_vel_diff: data = data.without_differentials() # Convert the representation and differentials to cartesian without # having them attached to a frame rep = data.to_cartesian() diffs = dict([(k, diff.represent_as(CartesianDifferential, data)) for k, diff in data.differentials.items()]) rep = rep.with_differentials(diffs) # Only do transform if matrix is specified. This is for speed in # transformations that only specify an offset (e.g., LSR) if matrix is not None: # Note: this applies to both representation and differentials rep = rep.transform(matrix) # TODO: if we decide to allow arithmetic between representations that # contain differentials, this can be tidied up if offset is not None: newrep = (rep.without_differentials() + offset.without_differentials()) else: newrep = rep.without_differentials() # We need a velocity (time derivative) and, for now, are strict: the # representation can only contain a velocity differential and no others. if has_velocity and not rad_vel_diff: veldiff = rep.differentials['s'] # already in Cartesian form if offset is not None and 's' in offset.differentials: veldiff = veldiff + offset.differentials['s'] newrep = newrep.with_differentials({'s': veldiff}) if isinstance(fromcoord.data, UnitSphericalRepresentation): # Special-case this because otherwise the return object will think # it has a valid distance with the default return (a # CartesianRepresentation instance) if has_velocity and not unit_vel_diff and not rad_vel_diff: # We have to first represent as the Unit types we converted to, # then put the d_distance information back in to the # differentials and re-represent as their original forms newdiff = newrep.differentials['s'] _unit_cls = fromcoord.data.differentials['s']._unit_differential newdiff = newdiff.represent_as(_unit_cls, newrep) kwargs = dict([(comp, getattr(newdiff, comp)) for comp in newdiff.components]) kwargs['d_distance'] = fromcoord.data.differentials['s'].d_distance diffs = {'s': fromcoord.data.differentials['s'].__class__( copy=False, **kwargs)} elif has_velocity and unit_vel_diff: newdiff = newrep.differentials['s'].represent_as( fromcoord.data.differentials['s'].__class__, newrep) diffs = {'s': newdiff} else: diffs = newrep.differentials newrep = newrep.represent_as(fromcoord.data.__class__) # drops diffs newrep = newrep.with_differentials(diffs) elif has_velocity and unit_vel_diff: # Here, we're in the case where the representation is not # UnitSpherical, but the differential *is* one of the UnitSpherical # types. We have to convert back to that differential class or the # resulting frame will think it has a valid radial_velocity. This # can probably be cleaned up: we currently have to go through the # dimensional version of the differential before representing as the # unit differential so that the units work out (the distance length # unit shouldn't appear in the resulting proper motions) diff_cls = fromcoord.data.differentials['s'].__class__ newrep = newrep.represent_as(fromcoord.data.__class__, diff_cls._dimensional_differential) newrep = newrep.represent_as(fromcoord.data.__class__, diff_cls) # We pulled the radial differential off of the representation # earlier, so now we need to put it back. But, in order to do that, we # have to turn the representation into a repr that is compatible with # having a RadialDifferential if has_velocity and rad_vel_diff: newrep = newrep.represent_as(fromcoord.data.__class__) newrep = newrep.with_differentials( {'s': fromcoord.data.differentials['s']}) return newrep class AffineTransform(BaseAffineTransform): """ A coordinate transformation specified as a function that yields a 3 x 3 cartesian transformation matrix and a tuple of displacement vectors. See `~astropy.coordinates.builtin_frames.galactocentric.Galactocentric` for an example. Parameters ---------- transform_func : callable A callable that has the signature ``transform_func(fromcoord, toframe)`` and returns: a (3, 3) matrix that operates on ``fromcoord`` in a Cartesian representation, and a ``CartesianRepresentation`` with (optionally) an attached velocity ``CartesianDifferential`` to represent a translation and offset in velocity to apply after the matrix operation. fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : number The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. register_graph : `TransformGraph` or `None` A graph to register this transformation with on creation, or `None` to leave it unregistered. Raises ------ TypeError If ``transform_func`` is not callable """ def __init__(self, transform_func, fromsys, tosys, priority=1, register_graph=None): if not callable(transform_func): raise TypeError('transform_func is not callable') self.transform_func = transform_func super().__init__(fromsys, tosys, priority=priority, register_graph=register_graph) def __call__(self, fromcoord, toframe): M, vec = self.transform_func(fromcoord, toframe) newrep = self._apply_transform(fromcoord, M, vec) return toframe.realize_frame(newrep) class StaticMatrixTransform(BaseAffineTransform): """ A coordinate transformation defined as a 3 x 3 cartesian transformation matrix. This is distinct from DynamicMatrixTransform in that this kind of matrix is independent of frame attributes. That is, it depends *only* on the class of the frame. Parameters ---------- matrix : array-like or callable A 3 x 3 matrix for transforming 3-vectors. In most cases will be unitary (although this is not strictly required). If a callable, will be called *with no arguments* to get the matrix. fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : number The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. register_graph : `TransformGraph` or `None` A graph to register this transformation with on creation, or `None` to leave it unregistered. Raises ------ ValueError If the matrix is not 3 x 3 """ def __init__(self, matrix, fromsys, tosys, priority=1, register_graph=None): if callable(matrix): matrix = matrix() self.matrix = np.array(matrix) if self.matrix.shape != (3, 3): raise ValueError('Provided matrix is not 3 x 3') super().__init__(fromsys, tosys, priority=priority, register_graph=register_graph) def __call__(self, fromcoord, toframe): newrep = self._apply_transform(fromcoord, self.matrix, None) return toframe.realize_frame(newrep) class DynamicMatrixTransform(BaseAffineTransform): """ A coordinate transformation specified as a function that yields a 3 x 3 cartesian transformation matrix. This is similar to, but distinct from StaticMatrixTransform, in that the matrix for this class might depend on frame attributes. Parameters ---------- matrix_func : callable A callable that has the signature ``matrix_func(fromcoord, toframe)`` and returns a 3 x 3 matrix that converts ``fromcoord`` in a cartesian representation to the new coordinate system. fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : number The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. register_graph : `TransformGraph` or `None` A graph to register this transformation with on creation, or `None` to leave it unregistered. Raises ------ TypeError If ``matrix_func`` is not callable """ def __init__(self, matrix_func, fromsys, tosys, priority=1, register_graph=None): if not callable(matrix_func): raise TypeError('matrix_func is not callable') self.matrix_func = matrix_func def _transform_func(fromcoord, toframe): return self.matrix_func(fromcoord, toframe), None super().__init__(fromsys, tosys, priority=priority, register_graph=register_graph) def __call__(self, fromcoord, toframe): M = self.matrix_func(fromcoord, toframe) newrep = self._apply_transform(fromcoord, M, None) return toframe.realize_frame(newrep) class CompositeTransform(CoordinateTransform): """ A transformation constructed by combining together a series of single-step transformations. Note that the intermediate frame objects are constructed using any frame attributes in ``toframe`` or ``fromframe`` that overlap with the intermediate frame (``toframe`` favored over ``fromframe`` if there's a conflict). Any frame attributes that are not present use the defaults. Parameters ---------- transforms : sequence of `CoordinateTransform` objects The sequence of transformations to apply. fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : number The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. register_graph : `TransformGraph` or `None` A graph to register this transformation with on creation, or `None` to leave it unregistered. collapse_static_mats : bool If `True`, consecutive `StaticMatrixTransform` will be collapsed into a single transformation to speed up the calculation. """ def __init__(self, transforms, fromsys, tosys, priority=1, register_graph=None, collapse_static_mats=True): super().__init__(fromsys, tosys, priority=priority, register_graph=register_graph) if collapse_static_mats: transforms = self._combine_statics(transforms) self.transforms = tuple(transforms) def _combine_statics(self, transforms): """ Combines together sequences of `StaticMatrixTransform`s into a single transform and returns it. """ newtrans = [] for currtrans in transforms: lasttrans = newtrans[-1] if len(newtrans) > 0 else None if (isinstance(lasttrans, StaticMatrixTransform) and isinstance(currtrans, StaticMatrixTransform)): combinedmat = np.dot(lasttrans.matrix, currtrans.matrix) newtrans[-1] = StaticMatrixTransform(combinedmat, lasttrans.fromsys, currtrans.tosys) else: newtrans.append(currtrans) return newtrans def __call__(self, fromcoord, toframe): curr_coord = fromcoord for t in self.transforms: # build an intermediate frame with attributes taken from either # `fromframe`, or if not there, `toframe`, or if not there, use # the defaults # TODO: caching this information when creating the transform may # speed things up a lot frattrs = {} for inter_frame_attr_nm in t.tosys.get_frame_attr_names(): if hasattr(toframe, inter_frame_attr_nm): attr = getattr(toframe, inter_frame_attr_nm) frattrs[inter_frame_attr_nm] = attr elif hasattr(fromcoord, inter_frame_attr_nm): attr = getattr(fromcoord, inter_frame_attr_nm) frattrs[inter_frame_attr_nm] = attr curr_toframe = t.tosys(**frattrs) curr_coord = t(curr_coord, curr_toframe) # this is safe even in the case where self.transforms is empty, because # coordinate objects are immutible, so copying is not needed return curr_coord # map class names to colorblind-safe colors trans_to_color = OrderedDict() trans_to_color[AffineTransform] = '#555555' # gray trans_to_color[FunctionTransform] = '#783001' # dark red-ish/brown trans_to_color[FunctionTransformWithFiniteDifference] = '#d95f02' # red-ish trans_to_color[StaticMatrixTransform] = '#7570b3' # blue-ish trans_to_color[DynamicMatrixTransform] = '#1b9e77' # green-ish
dedea3bb4b2d2fe07615730d26ab075fbd3d026d2216b15e0c2855afc11427fe
# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return {'astropy.coordinates.tests.accuracy': ['*.csv'], 'astropy.coordinates': ['data/*.dat', 'data/sites.json']}
798809da668b19516dad126da8e91cd0929855535ce5c79eef2b3331ba85e8a4
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains the classes and utility functions for distance and cartesian coordinates. """ import numpy as np from .. import units as u from .angles import Angle __all__ = ['Distance'] __doctest_requires__ = {'*': ['scipy.integrate']} class Distance(u.SpecificTypeQuantity): """ A one-dimensional distance. This can be initialized in one of four ways: * A distance ``value`` (array or float) and a ``unit`` * A `~astropy.units.Quantity` object * A redshift and (optionally) a cosmology. * Providing a distance modulus Parameters ---------- value : scalar or `~astropy.units.Quantity`. The value of this distance. unit : `~astropy.units.UnitBase` The units for this distance, *if* ``value`` is not a `~astropy.units.Quantity`. Must have dimensions of distance. z : float A redshift for this distance. It will be converted to a distance by computing the luminosity distance for this redshift given the cosmology specified by ``cosmology``. Must be given as a keyword argument. cosmology : ``Cosmology`` or `None` A cosmology that will be used to compute the distance from ``z``. If `None`, the current cosmology will be used (see `astropy.cosmology` for details). distmod : float or `~astropy.units.Quantity` The distance modulus for this distance. Note that if ``unit`` is not provided, a guess will be made at the unit between AU, pc, kpc, and Mpc. parallax : `~astropy.units.Quantity` or `~astropy.coordinates.Angle` The parallax in angular units. dtype : `~numpy.dtype`, optional See `~astropy.units.Quantity`. copy : bool, optional See `~astropy.units.Quantity`. order : {'C', 'F', 'A'}, optional See `~astropy.units.Quantity`. subok : bool, optional See `~astropy.units.Quantity`. ndmin : int, optional See `~astropy.units.Quantity`. allow_negative : bool, optional Whether to allow negative distances (which are possible is some cosmologies). Default: ``False``. Raises ------ `~astropy.units.UnitsError` If the ``unit`` is not a distance. ValueError If value specified is less than 0 and ``allow_negative=False``. If ``z`` is provided with a ``unit`` or ``cosmology`` is provided when ``z`` is *not* given, or ``value`` is given as well as ``z``. Examples -------- >>> from astropy import units as u >>> from astropy import cosmology >>> from astropy.cosmology import WMAP5, WMAP7 >>> cosmology.set_current(WMAP7) >>> d1 = Distance(10, u.Mpc) >>> d2 = Distance(40, unit=u.au) >>> d3 = Distance(value=5, unit=u.kpc) >>> d4 = Distance(z=0.23) >>> d5 = Distance(z=0.23, cosmology=WMAP5) >>> d6 = Distance(distmod=24.47) >>> d7 = Distance(Distance(10 * u.Mpc)) >>> d8 = Distance(parallax=21.34*u.mas) """ _equivalent_unit = u.m _include_easy_conversion_members = True def __new__(cls, value=None, unit=None, z=None, cosmology=None, distmod=None, parallax=None, dtype=None, copy=True, order=None, subok=False, ndmin=0, allow_negative=False): if z is not None: if value is not None or distmod is not None: raise ValueError('Should given only one of `value`, `z` ' 'or `distmod` in Distance constructor.') if cosmology is None: from ..cosmology import default_cosmology cosmology = default_cosmology.get() value = cosmology.luminosity_distance(z) # Continue on to take account of unit and other arguments # but a copy is already made, so no longer necessary copy = False else: if cosmology is not None: raise ValueError('A `cosmology` was given but `z` was not ' 'provided in Distance constructor') value_msg = ('Should given only one of `value`, `z`, `distmod`, or ' '`parallax` in Distance constructor.') n_not_none = np.sum([x is not None for x in [value, z, distmod, parallax]]) if n_not_none > 1: raise ValueError(value_msg) if distmod is not None: value = cls._distmod_to_pc(distmod) if unit is None: # if the unit is not specified, guess based on the mean of # the log of the distance meanlogval = np.log10(value.value).mean() if meanlogval > 6: unit = u.Mpc elif meanlogval > 3: unit = u.kpc elif meanlogval < -3: # ~200 AU unit = u.AU else: unit = u.pc # Continue on to take account of unit and other arguments # but a copy is already made, so no longer necessary copy = False elif parallax is not None: value = parallax.to(u.pc, equivalencies=u.parallax()).value unit = u.pc # Continue on to take account of unit and other arguments # but a copy is already made, so no longer necessary copy = False elif value is None: raise ValueError('None of `value`, `z`, `distmod`, or ' '`parallax` were given to Distance ' 'constructor') # now we have arguments like for a Quantity, so let it do the work distance = super().__new__( cls, value, unit, dtype=dtype, copy=copy, order=order, subok=subok, ndmin=ndmin) if not allow_negative and np.any(distance.value < 0): raise ValueError("Distance must be >= 0. Use the argument " "'allow_negative=True' to allow negative values.") return distance @property def z(self): """Short for ``self.compute_z()``""" return self.compute_z() def compute_z(self, cosmology=None): """ The redshift for this distance assuming its physical distance is a luminosity distance. Parameters ---------- cosmology : ``Cosmology`` or `None` The cosmology to assume for this calculation, or `None` to use the current cosmology (see `astropy.cosmology` for details). Returns ------- z : float The redshift of this distance given the provided ``cosmology``. """ if cosmology is None: from ..cosmology import default_cosmology cosmology = default_cosmology.get() from ..cosmology import z_at_value return z_at_value(cosmology.luminosity_distance, self, ztol=1.e-10) @property def distmod(self): """The distance modulus as a `~astropy.units.Quantity`""" val = 5. * np.log10(self.to_value(u.pc)) - 5. return u.Quantity(val, u.mag, copy=False) @classmethod def _distmod_to_pc(cls, dm): dm = u.Quantity(dm, u.mag) return cls(10 ** ((dm.value + 5) / 5.), u.pc, copy=False) @property def parallax(self): """The parallax angle as an `~astropy.coordinates.Angle` object""" return Angle(self.to(u.milliarcsecond, u.parallax())) def _convert_to_and_validate_length_unit(unit, allow_dimensionless=False): """ raises UnitsError if not a length unit """ try: unit = u.Unit(unit) assert (unit.is_equivalent(u.kpc) or allow_dimensionless and unit == u.dimensionless_unscaled) except (TypeError, AssertionError): raise u.UnitsError('Unit "{0}" is not a length type'.format(unit)) return unit
a5a361ccbc7e2e74fc6aaf2c39abf96adb1bfe38aa9fa31b11f95dcc1596748b
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains convenience functions for coordinate-related functionality. This is generally just wrapping around the object-oriented coordinates framework, but it is useful for some users who are used to more functional interfaces. """ import numpy as np from .. import units as u from ..constants import c from .. import _erfa as erfa from ..io import ascii from ..utils import isiterable, data from .sky_coordinate import SkyCoord from .builtin_frames import GCRS, PrecessedGeocentric from .representation import SphericalRepresentation, CartesianRepresentation from .builtin_frames.utils import get_jd12 __all__ = ['cartesian_to_spherical', 'spherical_to_cartesian', 'get_sun', 'concatenate', 'get_constellation'] def cartesian_to_spherical(x, y, z): """ Converts 3D rectangular cartesian coordinates to spherical polar coordinates. Note that the resulting angles are latitude/longitude or elevation/azimuthal form. I.e., the origin is along the equator rather than at the north pole. .. note:: This function simply wraps functionality provided by the `~astropy.coordinates.CartesianRepresentation` and `~astropy.coordinates.SphericalRepresentation` classes. In general, for both performance and readability, we suggest using these classes directly. But for situations where a quick one-off conversion makes sense, this function is provided. Parameters ---------- x : scalar, array-like, or `~astropy.units.Quantity` The first cartesian coordinate. y : scalar, array-like, or `~astropy.units.Quantity` The second cartesian coordinate. z : scalar, array-like, or `~astropy.units.Quantity` The third cartesian coordinate. Returns ------- r : `~astropy.units.Quantity` The radial coordinate (in the same units as the inputs). lat : `~astropy.units.Quantity` The latitude in radians lon : `~astropy.units.Quantity` The longitude in radians """ if not hasattr(x, 'unit'): x = x * u.dimensionless_unscaled if not hasattr(y, 'unit'): y = y * u.dimensionless_unscaled if not hasattr(z, 'unit'): z = z * u.dimensionless_unscaled cart = CartesianRepresentation(x, y, z) sph = cart.represent_as(SphericalRepresentation) return sph.distance, sph.lat, sph.lon def spherical_to_cartesian(r, lat, lon): """ Converts spherical polar coordinates to rectangular cartesian coordinates. Note that the input angles should be in latitude/longitude or elevation/azimuthal form. I.e., the origin is along the equator rather than at the north pole. .. note:: This is a low-level function used internally in `astropy.coordinates`. It is provided for users if they really want to use it, but it is recommended that you use the `astropy.coordinates` coordinate systems. Parameters ---------- r : scalar, array-like, or `~astropy.units.Quantity` The radial coordinate (in the same units as the inputs). lat : scalar, array-like, or `~astropy.units.Quantity` The latitude (in radians if array or scalar) lon : scalar, array-like, or `~astropy.units.Quantity` The longitude (in radians if array or scalar) Returns ------- x : float or array The first cartesian coordinate. y : float or array The second cartesian coordinate. z : float or array The third cartesian coordinate. """ if not hasattr(r, 'unit'): r = r * u.dimensionless_unscaled if not hasattr(lat, 'unit'): lat = lat * u.radian if not hasattr(lon, 'unit'): lon = lon * u.radian sph = SphericalRepresentation(distance=r, lat=lat, lon=lon) cart = sph.represent_as(CartesianRepresentation) return cart.x, cart.y, cart.z def get_sun(time): """ Determines the location of the sun at a given time (or times, if the input is an array `~astropy.time.Time` object), in geocentric coordinates. Parameters ---------- time : `~astropy.time.Time` The time(s) at which to compute the location of the sun. Returns ------- newsc : `~astropy.coordinates.SkyCoord` The location of the sun as a `~astropy.coordinates.SkyCoord` in the `~astropy.coordinates.GCRS` frame. Notes ----- The algorithm for determining the sun/earth relative position is based on the simplified version of VSOP2000 that is part of ERFA. Compared to JPL's ephemeris, it should be good to about 4 km (in the Sun-Earth vector) from 1900-2100 C.E., 8 km for the 1800-2200 span, and perhaps 250 km over the 1000-3000. """ earth_pv_helio, earth_pv_bary = erfa.epv00(*get_jd12(time, 'tdb')) # We have to manually do aberration because we're outputting directly into # GCRS earth_p = earth_pv_helio[..., 0, :] earth_v = earth_pv_bary[..., 1, :] # convert barycentric velocity to units of c, but keep as array for passing in to erfa earth_v /= c.to_value(u.au/u.d) dsun = np.sqrt(np.sum(earth_p**2, axis=-1)) invlorentz = (1-np.sum(earth_v**2, axis=-1))**0.5 properdir = erfa.ab(earth_p/dsun.reshape(dsun.shape + (1,)), -earth_v, dsun, invlorentz) cartrep = CartesianRepresentation(x=-dsun*properdir[..., 0] * u.AU, y=-dsun*properdir[..., 1] * u.AU, z=-dsun*properdir[..., 2] * u.AU) return SkyCoord(cartrep, frame=GCRS(obstime=time)) def concatenate(coords): """ Combine multiple coordinate objects into a single `~astropy.coordinates.SkyCoord`. "Coordinate objects" here mean frame objects with data, `~astropy.coordinates.SkyCoord`, or representation objects. Currently, they must all be in the same frame, but in a future version this may be relaxed to allow inhomogenous sequences of objects. Parameters ---------- coords : sequence of coordinate objects The objects to concatenate Returns ------- cskycoord : SkyCoord A single sky coordinate with its data set to the concatenation of all the elements in ``coords`` """ if getattr(coords, 'isscalar', False) or not isiterable(coords): raise TypeError('The argument to concatenate must be iterable') return SkyCoord(coords) # global dictionary that caches repeatedly-needed info for get_constellation _constellation_data = {} def get_constellation(coord, short_name=False, constellation_list='iau'): """ Determines the constellation(s) a given coordinate object contains. Parameters ---------- coord : coordinate object The object to determine the constellation of. short_name : bool If True, the returned names are the IAU-sanctioned abbreviated names. Otherwise, full names for the constellations are used. constellation_list : str The set of constellations to use. Currently only ``'iau'`` is supported, meaning the 88 "modern" constellations endorsed by the IAU. Returns ------- constellation : str or string array If ``coords`` contains a scalar coordinate, returns the name of the constellation. If it is an array coordinate object, it returns an array of names. Notes ----- To determine which constellation a point on the sky is in, this precesses to B1875, and then uses the Delporte boundaries of the 88 modern constellations, as tabulated by `Roman 1987 <http://cdsarc.u-strasbg.fr/viz-bin/Cat?VI/42>`_. """ if constellation_list != 'iau': raise ValueError("only 'iau' us currently supported for constellation_list") # read the data files and cache them if they haven't been already if not _constellation_data: cdata = data.get_pkg_data_contents('data/constellation_data_roman87.dat') ctable = ascii.read(cdata, names=['ral', 'rau', 'decl', 'name']) cnames = data.get_pkg_data_contents('data/constellation_names.dat', encoding='UTF8') cnames_short_to_long = dict([(l[:3], l[4:]) for l in cnames.split('\n') if not l.startswith('#')]) cnames_long = np.array([cnames_short_to_long[nm] for nm in ctable['name']]) _constellation_data['ctable'] = ctable _constellation_data['cnames_long'] = cnames_long else: ctable = _constellation_data['ctable'] cnames_long = _constellation_data['cnames_long'] isscalar = coord.isscalar # if it is geocentric, we reproduce the frame but with the 1875 equinox, # which is where the constellations are defined constel_coord = coord.transform_to(PrecessedGeocentric(equinox='B1875')) if isscalar: rah = constel_coord.ra.ravel().hour decd = constel_coord.dec.ravel().deg else: rah = constel_coord.ra.hour decd = constel_coord.dec.deg constellidx = -np.ones(len(rah), dtype=int) notided = constellidx == -1 # should be all for i, row in enumerate(ctable): msk = (row['ral'] < rah) & (rah < row['rau']) & (decd > row['decl']) constellidx[notided & msk] = i notided = constellidx == -1 if np.sum(notided) == 0: break else: raise ValueError('Could not find constellation for coordinates {0}'.format(constel_coord[notided])) if short_name: names = ctable['name'][constellidx] else: names = cnames_long[constellidx] if isscalar: return names[0] else: return names
5f9f0e7a9d235aab16ed512b231e5ff1999418823991f61a2167ff5299f2c155
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Framework and base classes for coordinate frames/"low-level" coordinate classes. """ # Standard library import abc import copy import inspect from collections import namedtuple, OrderedDict, defaultdict import warnings # Dependencies import numpy as np # Project from ..utils.compat.misc import override__dir__ from ..utils.decorators import lazyproperty, format_doc from ..utils.exceptions import AstropyWarning from .. import units as u from ..utils import (OrderedDescriptorContainer, ShapedLikeNDArray, check_broadcast) from .transformations import TransformGraph from . import representation as r from .angles import Angle from .attributes import Attribute # Import old names for Attributes so we don't break backwards-compatibility # (some users rely on them being here, although that is not encouraged, as this # is not the public API location -- see attributes.py). from .attributes import ( TimeFrameAttribute, QuantityFrameAttribute, EarthLocationAttribute, CoordinateAttribute, CartesianRepresentationFrameAttribute) # pylint: disable=W0611 __all__ = ['BaseCoordinateFrame', 'frame_transform_graph', 'GenericFrame', 'RepresentationMapping'] # the graph used for all transformations between frames frame_transform_graph = TransformGraph() def _get_repr_cls(value): """ Return a valid representation class from ``value`` or raise exception. """ if value in r.REPRESENTATION_CLASSES: value = r.REPRESENTATION_CLASSES[value] elif (not isinstance(value, type) or not issubclass(value, r.BaseRepresentation)): raise ValueError( 'Representation is {0!r} but must be a BaseRepresentation class ' 'or one of the string aliases {1}'.format( value, list(r.REPRESENTATION_CLASSES))) return value def _get_diff_cls(value): """ Return a valid differential class from ``value`` or raise exception. As originally created, this is only used in the SkyCoord initializer, so if that is refactored, this function my no longer be necessary. """ if value in r.DIFFERENTIAL_CLASSES: value = r.DIFFERENTIAL_CLASSES[value] elif (not isinstance(value, type) or not issubclass(value, r.BaseDifferential)): raise ValueError( 'Differential is {0!r} but must be a BaseDifferential class ' 'or one of the string aliases {1}'.format( value, list(r.DIFFERENTIAL_CLASSES))) return value def _get_repr_classes(base, **differentials): """Get valid representation and differential classes. Parameters ---------- base : str or `~astropy.coordinates.BaseRepresentation` subclass class for the representation of the base coordinates. If a string, it is looked up among the known representation classes. **differentials : dict of str or `~astropy.coordinates.BaseDifferentials` Keys are like for normal differentials, i.e., 's' for a first derivative in time, etc. If an item is set to `None`, it will be guessed from the base class. Returns ------- repr_classes : dict of subclasses The base class is keyed by 'base'; the others by the keys of ``diffferentials``. """ base = _get_repr_cls(base) repr_classes = {'base': base} for name, differential_type in differentials.items(): if differential_type == 'base': # We don't want to fail for this case. differential_type = r.DIFFERENTIAL_CLASSES.get(base.get_name(), None) elif differential_type in r.DIFFERENTIAL_CLASSES: differential_type = r.DIFFERENTIAL_CLASSES[differential_type] elif (differential_type is not None and (not isinstance(differential_type, type) or not issubclass(differential_type, r.BaseDifferential))): raise ValueError( 'Differential is {0!r} but must be a BaseDifferential class ' 'or one of the string aliases {1}'.format( differential_type, list(r.DIFFERENTIAL_CLASSES))) repr_classes[name] = differential_type return repr_classes def _normalize_representation_type(kwargs): """ This is added for backwards compatibility: if the user specifies the old-style argument ``representation``, add it back in to the kwargs dict as ``representation_type``. """ if 'representation' in kwargs: if 'representation_type' in kwargs: raise ValueError("Both `representation` and `representation_type` " "were passed to a frame initializer. Please use " "only `representation_type` (`representation` is " "now pending deprecation).") kwargs['representation_type'] = kwargs.pop('representation') # Need to subclass ABCMeta as well, so that this meta class can be combined # with ShapedLikeNDArray below (which is an ABC); without it, one gets # "TypeError: metaclass conflict: the metaclass of a derived class must be a # (non-strict) subclass of the metaclasses of all its bases" class FrameMeta(OrderedDescriptorContainer, abc.ABCMeta): def __new__(mcls, name, bases, members): if 'default_representation' in members: default_repr = members.pop('default_representation') found_default_repr = True else: default_repr = None found_default_repr = False if 'default_differential' in members: default_diff = members.pop('default_differential') found_default_diff = True else: default_diff = None found_default_diff = False if 'frame_specific_representation_info' in members: repr_info = members.pop('frame_specific_representation_info') found_repr_info = True else: repr_info = None found_repr_info = False # somewhat hacky, but this is the best way to get the MRO according to # https://mail.python.org/pipermail/python-list/2002-December/167861.html tmp_cls = super().__new__(mcls, name, bases, members) # now look through the whole MRO for the class attributes, raw for # frame_attr_names, and leading underscore for others for m in (c.__dict__ for c in tmp_cls.__mro__): if not found_default_repr and '_default_representation' in m: default_repr = m['_default_representation'] found_default_repr = True if not found_default_diff and '_default_differential' in m: default_diff = m['_default_differential'] found_default_diff = True if (not found_repr_info and '_frame_specific_representation_info' in m): # create a copy of the dict so we don't mess with the contents repr_info = m['_frame_specific_representation_info'].copy() found_repr_info = True if found_default_repr and found_default_diff and found_repr_info: break else: raise ValueError( 'Could not find all expected BaseCoordinateFrame class ' 'attributes. Are you mis-using FrameMeta?') # Unless overridden via `frame_specific_representation_info`, velocity # name defaults are (see also docstring for BaseCoordinateFrame): # * ``pm_{lon}_cos{lat}``, ``pm_{lat}`` for # `SphericalCosLatDifferential` proper motion components # * ``pm_{lon}``, ``pm_{lat}`` for `SphericalDifferential` proper # motion components # * ``radial_velocity`` for any `d_distance` component # * ``v_{x,y,z}`` for `CartesianDifferential` velocity components # where `{lon}` and `{lat}` are the frame names of the angular # components. if repr_info is None: repr_info = {} # the tuple() call below is necessary because if it is not there, # the iteration proceeds in a difficult-to-predict manner in the # case that one of the class objects hash is such that it gets # revisited by the iteration. The tuple() call prevents this by # making the items iterated over fixed regardless of how the dict # changes for cls_or_name in tuple(repr_info.keys()): if isinstance(cls_or_name, str): # TODO: this provides a layer of backwards compatibility in # case the key is a string, but now we want explicit classes. cls = _get_repr_cls(cls_or_name) repr_info[cls] = repr_info.pop(cls_or_name) # The default spherical names are 'lon' and 'lat' repr_info.setdefault(r.SphericalRepresentation, [RepresentationMapping('lon', 'lon'), RepresentationMapping('lat', 'lat')]) sph_component_map = {m.reprname: m.framename for m in repr_info[r.SphericalRepresentation]} repr_info.setdefault(r.SphericalCosLatDifferential, [ RepresentationMapping( 'd_lon_coslat', 'pm_{lon}_cos{lat}'.format(**sph_component_map), u.mas/u.yr), RepresentationMapping('d_lat', 'pm_{lat}'.format(**sph_component_map), u.mas/u.yr), RepresentationMapping('d_distance', 'radial_velocity', u.km/u.s) ]) repr_info.setdefault(r.SphericalDifferential, [ RepresentationMapping('d_lon', 'pm_{lon}'.format(**sph_component_map), u.mas/u.yr), RepresentationMapping('d_lat', 'pm_{lat}'.format(**sph_component_map), u.mas/u.yr), RepresentationMapping('d_distance', 'radial_velocity', u.km/u.s) ]) repr_info.setdefault(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)]) # Unit* classes should follow the same naming conventions # TODO: this adds some unnecessary mappings for the Unit classes, so # this could be cleaned up, but in practice doesn't seem to have any # negative side effects repr_info.setdefault(r.UnitSphericalRepresentation, repr_info[r.SphericalRepresentation]) repr_info.setdefault(r.UnitSphericalCosLatDifferential, repr_info[r.SphericalCosLatDifferential]) repr_info.setdefault(r.UnitSphericalDifferential, repr_info[r.SphericalDifferential]) # Make read-only properties for the frame class attributes that should # be read-only to make them immutable after creation. # We copy attributes instead of linking to make sure there's no # accidental cross-talk between classes mcls.readonly_prop_factory(members, 'default_representation', default_repr) mcls.readonly_prop_factory(members, 'default_differential', default_diff) mcls.readonly_prop_factory(members, 'frame_specific_representation_info', copy.deepcopy(repr_info)) # now set the frame name as lower-case class name, if it isn't explicit if 'name' not in members: members['name'] = name.lower() return super().__new__(mcls, name, bases, members) @staticmethod def readonly_prop_factory(members, attr, value): private_attr = '_' + attr def getter(self): return getattr(self, private_attr) members[private_attr] = value members[attr] = property(getter) _RepresentationMappingBase = \ namedtuple('RepresentationMapping', ('reprname', 'framename', 'defaultunit')) class RepresentationMapping(_RepresentationMappingBase): """ This `~collections.namedtuple` is used with the ``frame_specific_representation_info`` attribute to tell frames what attribute names (and default units) to use for a particular representation. ``reprname`` and ``framename`` should be strings, while ``defaultunit`` can be either an astropy unit, the string ``'recommended'`` (to use whatever the representation's ``recommended_units`` is), or None (to indicate that no unit mapping should be done). """ def __new__(cls, reprname, framename, defaultunit='recommended'): # this trick just provides some defaults return super().__new__(cls, reprname, framename, defaultunit) base_doc = """{__doc__} Parameters ---------- data : `BaseRepresentation` subclass instance A representation object or ``None`` to have no data (or use the coordinate component arguments, see below). {components} representation_type : `BaseRepresentation` subclass, str, optional A representation class or string name of a representation class. This sets the expected input representation class, thereby changing the expected keyword arguments for the data passed in. For example, passing ``representation_type='cartesian'`` will make the classes expect position data with cartesian names, i.e. ``x, y, z`` in most cases. differential_type : `BaseDifferential` subclass, str, dict, optional A differential class or dictionary of differential classes (currently only a velocity differential with key 's' is supported). This sets the expected input differential class, thereby changing the expected keyword arguments of the data passed in. For example, passing ``differential_type='cartesian'`` will make the classes expect velocity data with the argument names ``v_x, v_y, v_z``. copy : bool, optional If `True` (default), make copies of the input coordinate arrays. Can only be passed in as a keyword argument. {footer} """ _components = """ *args, **kwargs Coordinate components, with names that depend on the subclass. """ @format_doc(base_doc, components=_components, footer="") class BaseCoordinateFrame(ShapedLikeNDArray, metaclass=FrameMeta): """ The base class for coordinate frames. This class is intended to be subclassed to create instances of specific systems. Subclasses can implement the following attributes: * `default_representation` A subclass of `~astropy.coordinates.BaseRepresentation` that will be treated as the default representation of this frame. This is the representation assumed by default when the frame is created. * `default_differential` A subclass of `~astropy.coordinates.BaseDifferential` that will be treated as the default differential class of this frame. This is the differential class assumed by default when the frame is created. * `~astropy.coordinates.Attribute` class attributes Frame attributes such as ``FK4.equinox`` or ``FK4.obstime`` are defined using a descriptor class. See the narrative documentation or built-in classes code for details. * `frame_specific_representation_info` A dictionary mapping the name or class of a representation to a list of `~astropy.coordinates.RepresentationMapping` objects that tell what names and default units should be used on this frame for the components of that representation. Unless overridden via `frame_specific_representation_info`, velocity name defaults are: * ``pm_{lon}_cos{lat}``, ``pm_{lat}`` for `SphericalCosLatDifferential` proper motion components * ``pm_{lon}``, ``pm_{lat}`` for `SphericalDifferential` proper motion components * ``radial_velocity`` for any ``d_distance`` component * ``v_{x,y,z}`` for `CartesianDifferential` velocity components where ``{lon}`` and ``{lat}`` are the frame names of the angular components. """ default_representation = None default_differential = None # Specifies special names and units for representation and differential # attributes. frame_specific_representation_info = {} _inherit_descriptors_ = (Attribute,) frame_attributes = OrderedDict() # Default empty frame_attributes dict def __init__(self, *args, copy=True, representation_type=None, differential_type=None, **kwargs): self._attr_names_with_defaults = [] # This is here for backwards compatibility. It should be possible # to use either the kwarg representation_type, or representation. # TODO: In future versions, we will raise a deprecation warning here: if representation_type is not None: kwargs['representation_type'] = representation_type _normalize_representation_type(kwargs) representation_type = kwargs.pop('representation_type', representation_type) if representation_type is not None or differential_type is not None: if representation_type is None: representation_type = self.default_representation if (inspect.isclass(differential_type) and issubclass(differential_type, r.BaseDifferential)): # TODO: assumes the differential class is for the velocity # differential differential_type = {'s': differential_type} elif isinstance(differential_type, str): # TODO: assumes the differential class is for the velocity # differential diff_cls = r.DIFFERENTIAL_CLASSES[differential_type] differential_type = {'s': diff_cls} elif differential_type is None: if representation_type == self.default_representation: differential_type = {'s': self.default_differential} else: differential_type = {'s': 'base'} # see set_representation_cls() self.set_representation_cls(representation_type, **differential_type) # if not set below, this is a frame with no data representation_data = None differential_data = None args = list(args) # need to be able to pop them if (len(args) > 0) and (isinstance(args[0], r.BaseRepresentation) or args[0] is None): representation_data = args.pop(0) if len(args) > 0: raise TypeError( 'Cannot create a frame with both a representation object ' 'and other positional arguments') if representation_data is not None: diffs = representation_data.differentials differential_data = diffs.get('s', None) if ((differential_data is None and len(diffs) > 0) or (differential_data is not None and len(diffs) > 1)): raise ValueError('Multiple differentials are associated ' 'with the representation object passed in ' 'to the frame initializer. Only a single ' 'velocity differential is supported. Got: ' '{0}'.format(diffs)) elif self.representation_type: representation_cls = self.get_representation_cls() # Get any representation data passed in to the frame initializer # using keyword or positional arguments for the component names repr_kwargs = {} for nmkw, nmrep in self.representation_component_names.items(): if len(args) > 0: # first gather up positional args repr_kwargs[nmrep] = args.pop(0) elif nmkw in kwargs: repr_kwargs[nmrep] = kwargs.pop(nmkw) # special-case the Spherical->UnitSpherical if no `distance` # TODO: possibly generalize this somehow? if repr_kwargs: if repr_kwargs.get('distance', True) is None: del repr_kwargs['distance'] if (issubclass(representation_cls, r.SphericalRepresentation) and 'distance' not in repr_kwargs): representation_cls = representation_cls._unit_representation try: representation_data = representation_cls(copy=copy, **repr_kwargs) except TypeError as e: # this except clause is here to make the names of the # attributes more human-readable. Without this the names # come from the representation instead of the frame's # attribute names. msg = str(e) names = self.get_representation_component_names() for frame_name, repr_name in names.items(): msg = msg.replace(repr_name, frame_name) msg = msg.replace('__init__()', '{0}()'.format(self.__class__.__name__)) e.args = (msg,) raise # Now we handle the Differential data: # Get any differential data passed in to the frame initializer # using keyword or positional arguments for the component names differential_cls = self.get_representation_cls('s') diff_component_names = self.get_representation_component_names('s') diff_kwargs = {} for nmkw, nmrep in diff_component_names.items(): if len(args) > 0: # first gather up positional args diff_kwargs[nmrep] = args.pop(0) elif nmkw in kwargs: diff_kwargs[nmrep] = kwargs.pop(nmkw) if diff_kwargs: if (hasattr(differential_cls, '_unit_differential') and 'd_distance' not in diff_kwargs): differential_cls = differential_cls._unit_differential elif len(diff_kwargs) == 1 and 'd_distance' in diff_kwargs: differential_cls = r.RadialDifferential try: differential_data = differential_cls(copy=copy, **diff_kwargs) except TypeError as e: # this except clause is here to make the names of the # attributes more human-readable. Without this the names # come from the representation instead of the frame's # attribute names. msg = str(e) names = self.get_representation_component_names('s') for frame_name, repr_name in names.items(): msg = msg.replace(repr_name, frame_name) msg = msg.replace('__init__()', '{0}()'.format(self.__class__.__name__)) e.args = (msg,) raise if len(args) > 0: raise TypeError( '{0}.__init__ had {1} remaining unhandled arguments'.format( self.__class__.__name__, len(args))) if representation_data is None and differential_data is not None: raise ValueError("Cannot pass in differential component data " "without positional (representation) data.") if differential_data: self._data = representation_data.with_differentials( {'s': differential_data}) else: self._data = representation_data # possibly None. values = {} for fnm, fdefault in self.get_frame_attr_names().items(): # Read-only frame attributes are defined as FrameAttribue # descriptors which are not settable, so set 'real' attributes as # the name prefaced with an underscore. if fnm in kwargs: value = kwargs.pop(fnm) setattr(self, '_' + fnm, value) # Validate attribute by getting it. If the instance has data, # this also checks its shape is OK. If not, we do it below. values[fnm] = getattr(self, fnm) else: setattr(self, '_' + fnm, fdefault) self._attr_names_with_defaults.append(fnm) if kwargs: raise TypeError( 'Coordinate frame got unexpected keywords: {0}'.format( list(kwargs))) # We do ``is None`` because self._data might evaluate to false for # empty arrays or data == 0 if self._data is None: # No data: we still need to check that any non-scalar attributes # have consistent shapes. Collect them for all attributes with # size > 1 (which should be array-like and thus have a shape). shapes = {fnm: value.shape for fnm, value in values.items() if getattr(value, 'size', 1) > 1} if shapes: if len(shapes) > 1: try: self._no_data_shape = check_broadcast(*shapes.values()) except ValueError: raise ValueError( "non-scalar attributes with inconsistent " "shapes: {0}".format(shapes)) # Above, we checked that it is possible to broadcast all # shapes. By getting and thus validating the attributes, # we verify that the attributes can in fact be broadcast. for fnm in shapes: getattr(self, fnm) else: self._no_data_shape = shapes.popitem()[1] else: self._no_data_shape = () else: # This makes the cache keys backwards-compatible, but also adds # support for having differentials attached to the frame data # representation object. if 's' in self._data.differentials: # TODO: assumes a velocity unit differential key = (self._data.__class__.__name__, self._data.differentials['s'].__class__.__name__, False) else: key = (self._data.__class__.__name__, False) # Set up representation cache. self.cache['representation'][key] = self._data @lazyproperty def cache(self): """ Cache for this frame, a dict. It stores anything that should be computed from the coordinate data (*not* from the frame attributes). This can be used in functions to store anything that might be expensive to compute but might be re-used by some other function. E.g.:: if 'user_data' in myframe.cache: data = myframe.cache['user_data'] else: myframe.cache['user_data'] = data = expensive_func(myframe.lat) If in-place modifications are made to the frame data, the cache should be cleared:: myframe.cache.clear() """ return defaultdict(dict) @property def data(self): """ The coordinate data for this object. If this frame has no data, an `ValueError` will be raised. Use `has_data` to check if data is present on this frame object. """ if self._data is None: raise ValueError('The frame object "{0!r}" does not have ' 'associated data'.format(self)) return self._data @property def has_data(self): """ True if this frame has `data`, False otherwise. """ return self._data is not None @property def shape(self): return self.data.shape if self.has_data else self._no_data_shape # We have to override the ShapedLikeNDArray definitions, since our shape # does not have to be that of the data. def __len__(self): return len(self.data) def __bool__(self): return self.has_data and self.size > 0 @property def size(self): return self.data.size @property def isscalar(self): return self.has_data and self.data.isscalar @classmethod def get_frame_attr_names(cls): return OrderedDict((name, getattr(cls, name)) for name in cls.frame_attributes) def get_representation_cls(self, which='base'): """The class used for part of this frame's data. Parameters ---------- which : ('base', 's', `None`) The class of which part to return. 'base' means the class used to represent the coordinates; 's' the first derivative to time, i.e., the class representing the proper motion and/or radial velocity. If `None`, return a dict with both. Returns ------- representation : `~astropy.coordinates.BaseRepresentation` or `~astropy.coordinates.BaseDifferential`. """ if not hasattr(self, '_representation'): self._representation = {'base': self.default_representation, 's': self.default_differential} if which is not None: return self._representation[which] else: return self._representation def set_representation_cls(self, base=None, s='base'): """Set representation and/or differential class for this frame's data. Parameters ---------- base : str, `~astropy.coordinates.BaseRepresentation` subclass, optional The name or subclass to use to represent the coordinate data. s : `~astropy.coordinates.BaseDifferential` subclass, optional The differential subclass to use to represent any velocities, such as proper motion and radial velocity. If equal to 'base', which is the default, it will be inferred from the representation. If `None`, the representation will drop any differentials. """ if base is None: base = self._representation['base'] self._representation = _get_repr_classes(base=base, s=s) representation_type = property( fget=get_representation_cls, fset=set_representation_cls, doc="""The representation class used for this frame's data. This will be a subclass from `~astropy.coordinates.BaseRepresentation`. Can also be *set* using the string name of the representation. If you wish to set an explicit differential class (rather than have it be inferred), use the ``set_represenation_cls`` method. """) @property def differential_type(self): """ The differential used for this frame's data. This will be a subclass from `~astropy.coordinates.BaseDifferential`. For simultaneous setting of representation and differentials, see the ``set_represenation_cls`` method. """ return self.get_representation_cls('s') @differential_type.setter def differential_type(self, value): self.set_representation_cls(s=value) # TODO: deprecate these? @property def representation(self): return self.representation_type @representation.setter def representation(self, value): self.representation_type = value @classmethod def _get_representation_info(cls): # This exists as a class method only to support handling frame inputs # without units, which are deprecated and will be removed. This can be # moved into the representation_info property at that time. repr_attrs = {} for repr_diff_cls in (list(r.REPRESENTATION_CLASSES.values()) + list(r.DIFFERENTIAL_CLASSES.values())): repr_attrs[repr_diff_cls] = {'names': [], 'units': []} for c, c_cls in repr_diff_cls.attr_classes.items(): repr_attrs[repr_diff_cls]['names'].append(c) # TODO: when "recommended_units" is removed, just directly use # the default part here. rec_unit = repr_diff_cls._recommended_units.get( c, u.deg if issubclass(c_cls, Angle) else None) repr_attrs[repr_diff_cls]['units'].append(rec_unit) for repr_diff_cls, mappings in cls._frame_specific_representation_info.items(): # take the 'names' and 'units' tuples from repr_attrs, # and then use the RepresentationMapping objects # to update as needed for this frame. nms = repr_attrs[repr_diff_cls]['names'] uns = repr_attrs[repr_diff_cls]['units'] comptomap = dict([(m.reprname, m) for m in mappings]) for i, c in enumerate(repr_diff_cls.attr_classes.keys()): if c in comptomap: mapp = comptomap[c] nms[i] = mapp.framename # need the isinstance because otherwise if it's a unit it # will try to compare to the unit string representation if not (isinstance(mapp.defaultunit, str) and mapp.defaultunit == 'recommended'): uns[i] = mapp.defaultunit # else we just leave it as recommended_units says above # Convert to tuples so that this can't mess with frame internals repr_attrs[repr_diff_cls]['names'] = tuple(nms) repr_attrs[repr_diff_cls]['units'] = tuple(uns) return repr_attrs @property def representation_info(self): """ A dictionary with the information of what attribute names for this frame apply to particular representations. """ return self._get_representation_info() def get_representation_component_names(self, which='base'): out = OrderedDict() repr_or_diff_cls = self.get_representation_cls(which) if repr_or_diff_cls is None: return out data_names = repr_or_diff_cls.attr_classes.keys() repr_names = self.representation_info[repr_or_diff_cls]['names'] for repr_name, data_name in zip(repr_names, data_names): out[repr_name] = data_name return out def get_representation_component_units(self, which='base'): out = OrderedDict() repr_or_diff_cls = self.get_representation_cls(which) if repr_or_diff_cls is None: return out repr_attrs = self.representation_info[repr_or_diff_cls] repr_names = repr_attrs['names'] repr_units = repr_attrs['units'] for repr_name, repr_unit in zip(repr_names, repr_units): if repr_unit: out[repr_name] = repr_unit return out representation_component_names = property(get_representation_component_names) representation_component_units = property(get_representation_component_units) def _replicate(self, data, copy=False, **kwargs): """Base for replicating a frame, with possibly different attributes. Produces a new instance of the frame using the attributes of the old frame (unless overridden) and with the data given. Parameters ---------- data : `~astropy.coordinates.BaseRepresentation` or `None` Data to use in the new frame instance. If `None`, it will be a data-less frame. copy : bool, optional Whether data and the attributes on the old frame should be copied (default), or passed on by reference. **kwargs Any attributes that should be overridden. """ # This is to provide a slightly nicer error message if the user tries # to use frame_obj.representation instead of frame_obj.data to get the # underlying representation object [e.g., #2890] if inspect.isclass(data): raise TypeError('Class passed as data instead of a representation ' 'instance. If you called frame.representation, this' ' returns the representation class. frame.data ' 'returns the instantiated object - you may want to ' ' use this instead.') if copy and data is not None: data = data.copy() for attr in self.get_frame_attr_names(): if (attr not in self._attr_names_with_defaults and attr not in kwargs): value = getattr(self, attr) if copy: value = value.copy() kwargs[attr] = value return self.__class__(data, copy=False, **kwargs) def replicate(self, copy=False, **kwargs): """ Return a replica of the frame, optionally with new frame attributes. The replica is a new frame object that has the same data as this frame object and with frame attributes overriden if they are provided as extra keyword arguments to this method. If ``copy`` is set to `True` then a copy of the internal arrays will be made. Otherwise the replica will use a reference to the original arrays when possible to save memory. The internal arrays are normally not changeable by the user so in most cases it should not be necessary to set ``copy`` to `True`. Parameters ---------- copy : bool, optional If True, the resulting object is a copy of the data. When False, references are used where possible. This rule also applies to the frame attributes. Any additional keywords are treated as frame attributes to be set on the new frame object. Returns ------- frameobj : same as this frame Replica of this object, but possibly with new frame attributes. """ return self._replicate(self.data, copy=copy, **kwargs) def replicate_without_data(self, copy=False, **kwargs): """ Return a replica without data, optionally with new frame attributes. The replica is a new frame object without data but with the same frame attributes as this object, except where overriden by extra keyword arguments to this method. The ``copy`` keyword determines if the frame attributes are truly copied vs being references (which saves memory for cases where frame attributes are large). This method is essentially the converse of `realize_frame`. Parameters ---------- copy : bool, optional If True, the resulting object has copies of the frame attributes. When False, references are used where possible. Any additional keywords are treated as frame attributes to be set on the new frame object. Returns ------- frameobj : same as this frame Replica of this object, but without data and possibly with new frame attributes. """ return self._replicate(None, copy=copy, **kwargs) def realize_frame(self, representation_type): """ Generates a new frame *with new data* from another frame (which may or may not have data). Roughly speaking, the converse of `replicate_without_data`. Parameters ---------- representation_type : `BaseRepresentation` The representation to use as the data for the new frame. Returns ------- frameobj : same as this frame A new object with the same frame attributes as this one, but with the ``representation`` as the data. """ return self._replicate(representation_type) def represent_as(self, base, s='base', in_frame_units=False): """ Generate and return a new representation of this frame's `data` as a Representation object. Note: In order to make an in-place change of the representation of a Frame or SkyCoord object, set the ``representation`` attribute of that object to the desired new representation, or use the ``set_representation_cls`` method to also set the differential. Parameters ---------- base : subclass of BaseRepresentation or string The type of representation to generate. Must be a *class* (not an instance), or the string name of the representation class. s : subclass of `~astropy.coordinates.BaseDifferential`, str, optional Class in which any velocities should be represented. Must be a *class* (not an instance), or the string name of the differential class. If equal to 'base' (default), inferred from the base class. If `None`, all velocity information is dropped. in_frame_units : bool, keyword only Force the representation units to match the specified units particular to this frame Returns ------- newrep : BaseRepresentation-derived object A new representation object of this frame's `data`. Raises ------ AttributeError If this object had no `data` Examples -------- >>> from astropy import units as u >>> from astropy.coordinates import SkyCoord, CartesianRepresentation >>> coord = SkyCoord(0*u.deg, 0*u.deg) >>> coord.represent_as(CartesianRepresentation) # doctest: +FLOAT_CMP <CartesianRepresentation (x, y, z) [dimensionless] (1., 0., 0.)> >>> coord.representation = CartesianRepresentation >>> coord # doctest: +FLOAT_CMP <SkyCoord (ICRS): (x, y, z) [dimensionless] (1., 0., 0.)> """ # For backwards compatibility (because in_frame_units used to be the # 2nd argument), we check to see if `new_differential` is a boolean. If # it is, we ignore the value of `new_differential` and warn about the # position change if isinstance(s, bool): warnings.warn("The argument position for `in_frame_units` in " "`represent_as` has changed. Use as a keyword " "argument if needed.", AstropyWarning) in_frame_units = s s = 'base' # In the future, we may want to support more differentials, in which # case one probably needs to define **kwargs above and use it here. # But for now, we only care about the velocity. repr_classes = _get_repr_classes(base=base, s=s) representation_cls = repr_classes['base'] # We only keep velocity information if 's' in self.data.differentials: differential_cls = repr_classes['s'] elif s is None or s == 'base': differential_cls = None else: raise TypeError('Frame data has no associated differentials ' '(i.e. the frame has no velocity data) - ' 'represent_as() only accepts a new ' 'representation.') if differential_cls: cache_key = (representation_cls.__name__, differential_cls.__name__, in_frame_units) else: cache_key = (representation_cls.__name__, in_frame_units) cached_repr = self.cache['representation'].get(cache_key) if not cached_repr: if differential_cls: # TODO NOTE: only supports a single differential data = self.data.represent_as(representation_cls, differential_cls) diff = data.differentials['s'] # TODO: assumes velocity else: data = self.data.represent_as(representation_cls) # If the new representation is known to this frame and has a defined # set of names and units, then use that. new_attrs = self.representation_info.get(representation_cls) if new_attrs and in_frame_units: datakwargs = dict((comp, getattr(data, comp)) for comp in data.components) for comp, new_attr_unit in zip(data.components, new_attrs['units']): if new_attr_unit: datakwargs[comp] = datakwargs[comp].to(new_attr_unit) data = data.__class__(copy=False, **datakwargs) if differential_cls: # the original differential data_diff = self.data.differentials['s'] # If the new differential is known to this frame and has a # defined set of names and units, then use that. new_attrs = self.representation_info.get(differential_cls) if new_attrs and in_frame_units: diffkwargs = dict((comp, getattr(diff, comp)) for comp in diff.components) for comp, new_attr_unit in zip(diff.components, new_attrs['units']): # Some special-casing to treat a situation where the # input data has a UnitSphericalDifferential or a # RadialDifferential. It is re-represented to the # frame's differential class (which might be, e.g., a # dimensional Differential), so we don't want to try to # convert the empty component units if (isinstance(data_diff, (r.UnitSphericalDifferential, r.UnitSphericalCosLatDifferential)) and comp not in data_diff.__class__.attr_classes): continue elif (isinstance(data_diff, r.RadialDifferential) and comp not in data_diff.__class__.attr_classes): continue if new_attr_unit and hasattr(diff, comp): diffkwargs[comp] = diffkwargs[comp].to(new_attr_unit) diff = diff.__class__(copy=False, **diffkwargs) # Here we have to bypass using with_differentials() because # it has a validation check. But because # .representation_type and .differential_type don't point to # the original classes, if the input differential is a # RadialDifferential, it usually gets turned into a # SphericalCosLatDifferential (or whatever the default is) # with strange units for the d_lon and d_lat attributes. # This then causes the dictionary key check to fail (i.e. # comparison against `diff._get_deriv_key()`) data._differentials.update({'s': diff}) self.cache['representation'][cache_key] = data return self.cache['representation'][cache_key] def transform_to(self, new_frame): """ Transform this object's coordinate data to a new frame. Parameters ---------- new_frame : class or frame object or SkyCoord object The frame to transform this coordinate frame into. Returns ------- transframe A new object with the coordinate data represented in the ``newframe`` system. Raises ------ ValueError If there is no possible transformation route. """ from .errors import ConvertError if self._data is None: raise ValueError('Cannot transform a frame with no data') if (getattr(self.data, 'differentials', None) and hasattr(self, 'obstime') and hasattr(new_frame, 'obstime') and np.any(self.obstime != new_frame.obstime)): raise NotImplementedError('You cannot transform a frame that has ' 'velocities to another frame at a ' 'different obstime. If you think this ' 'should (or should not) be possible, ' 'please comment at https://github.com/astropy/astropy/issues/6280') if inspect.isclass(new_frame): # Use the default frame attributes for this class new_frame = new_frame() if hasattr(new_frame, '_sky_coord_frame'): # Input new_frame is not a frame instance or class and is most # likely a SkyCoord object. new_frame = new_frame._sky_coord_frame trans = frame_transform_graph.get_transform(self.__class__, new_frame.__class__) if trans is None: if new_frame is self.__class__: # no special transform needed, but should update frame info return new_frame.realize_frame(self.data) msg = 'Cannot transform from {0} to {1}' raise ConvertError(msg.format(self.__class__, new_frame.__class__)) return trans(self, new_frame) def is_transformable_to(self, new_frame): """ Determines if this coordinate frame can be transformed to another given frame. Parameters ---------- new_frame : class or frame object The proposed frame to transform into. Returns ------- transformable : bool or str `True` if this can be transformed to ``new_frame``, `False` if not, or the string 'same' if ``new_frame`` is the same system as this object but no transformation is defined. Notes ----- A return value of 'same' means the transformation will work, but it will just give back a copy of this object. The intended usage is:: if coord.is_transformable_to(some_unknown_frame): coord2 = coord.transform_to(some_unknown_frame) This will work even if ``some_unknown_frame`` turns out to be the same frame class as ``coord``. This is intended for cases where the frame is the same regardless of the frame attributes (e.g. ICRS), but be aware that it *might* also indicate that someone forgot to define the transformation between two objects of the same frame class but with different attributes. """ new_frame_cls = new_frame if inspect.isclass(new_frame) else new_frame.__class__ trans = frame_transform_graph.get_transform(self.__class__, new_frame_cls) if trans is None: if new_frame_cls is self.__class__: return 'same' else: return False else: return True def is_frame_attr_default(self, attrnm): """ Determine whether or not a frame attribute has its value because it's the default value, or because this frame was created with that value explicitly requested. Parameters ---------- attrnm : str The name of the attribute to check. Returns ------- isdefault : bool True if the attribute ``attrnm`` has its value by default, False if it was specified at creation of this frame. """ return attrnm in self._attr_names_with_defaults def is_equivalent_frame(self, other): """ Checks if this object is the same frame as the ``other`` object. To be the same frame, two objects must be the same frame class and have the same frame attributes. Note that it does *not* matter what, if any, data either object has. Parameters ---------- other : BaseCoordinateFrame the other frame to check Returns ------- isequiv : bool True if the frames are the same, False if not. Raises ------ TypeError If ``other`` isn't a `BaseCoordinateFrame` or subclass. """ if self.__class__ == other.__class__: for frame_attr_name in self.get_frame_attr_names(): if np.any(getattr(self, frame_attr_name) != getattr(other, frame_attr_name)): return False return True elif not isinstance(other, BaseCoordinateFrame): raise TypeError("Tried to do is_equivalent_frame on something that " "isn't a frame") else: return False def __repr__(self): frameattrs = self._frame_attrs_repr() data_repr = self._data_repr() if frameattrs: frameattrs = ' ({0})'.format(frameattrs) if data_repr: return '<{0} Coordinate{1}: {2}>'.format(self.__class__.__name__, frameattrs, data_repr) else: return '<{0} Frame{1}>'.format(self.__class__.__name__, frameattrs) def _data_repr(self): """Returns a string representation of the coordinate data.""" if not self.has_data: return '' if self.representation: if (issubclass(self.representation, r.SphericalRepresentation) and isinstance(self.data, r.UnitSphericalRepresentation)): rep_cls = self.data.__class__ else: rep_cls = self.representation if 's' in self.data.differentials: dif_cls = self.get_representation_cls('s') dif_data = self.data.differentials['s'] if isinstance(dif_data, (r.UnitSphericalDifferential, r.UnitSphericalCosLatDifferential, r.RadialDifferential)): dif_cls = dif_data.__class__ else: dif_cls = None data = self.represent_as(rep_cls, dif_cls, in_frame_units=True) data_repr = repr(data) for nmpref, nmrepr in self.representation_component_names.items(): data_repr = data_repr.replace(nmrepr, nmpref) else: data = self.data data_repr = repr(self.data) if data_repr.startswith('<' + data.__class__.__name__): # remove both the leading "<" and the space after the name, as well # as the trailing ">" data_repr = data_repr[(len(data.__class__.__name__) + 2):-1] else: data_repr = 'Data:\n' + data_repr if 's' in self.data.differentials: data_repr_spl = data_repr.split('\n') if 'has differentials' in data_repr_spl[-1]: diffrepr = repr(data.differentials['s']).split('\n') if diffrepr[0].startswith('<'): diffrepr[0] = ' ' + ' '.join(diffrepr[0].split(' ')[1:]) for frm_nm, rep_nm in self.get_representation_component_names('s').items(): diffrepr[0] = diffrepr[0].replace(rep_nm, frm_nm) if diffrepr[-1].endswith('>'): diffrepr[-1] = diffrepr[-1][:-1] data_repr_spl[-1] = '\n'.join(diffrepr) data_repr = '\n'.join(data_repr_spl) return data_repr def _frame_attrs_repr(self): """ Returns a string representation of the frame's attributes, if any. """ return ', '.join([attrnm + '=' + str(getattr(self, attrnm)) for attrnm in self.get_frame_attr_names()]) def _apply(self, method, *args, **kwargs): """Create a new instance, applying a method to the underlying data. In typical usage, the method is any of the shape-changing methods for `~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those picking particular elements (``__getitem__``, ``take``, etc.), which are all defined in `~astropy.utils.misc.ShapedLikeNDArray`. It will be applied to the underlying arrays in the representation (e.g., ``x``, ``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`), as well as to any frame attributes that have a shape, with the results used to create a new instance. Internally, it is also used to apply functions to the above parts (in particular, `~numpy.broadcast_to`). Parameters ---------- method : str or callable If str, it is the name of a method that is applied to the internal ``components``. If callable, the function is applied. args : tuple Any positional arguments for ``method``. kwargs : dict Any keyword arguments for ``method``. """ def apply_method(value): if isinstance(value, ShapedLikeNDArray): return value._apply(method, *args, **kwargs) else: if callable(method): return method(value, *args, **kwargs) else: return getattr(value, method)(*args, **kwargs) new = super().__new__(self.__class__) if hasattr(self, '_representation'): new._representation = self._representation.copy() new._attr_names_with_defaults = self._attr_names_with_defaults.copy() for attr in self.frame_attributes: _attr = '_' + attr if attr in self._attr_names_with_defaults: setattr(new, _attr, getattr(self, _attr)) else: value = getattr(self, _attr) if getattr(value, 'size', 1) > 1: value = apply_method(value) elif method == 'copy' or method == 'flatten': # flatten should copy also for a single element array, but # we cannot use it directly for array scalars, since it # always returns a one-dimensional array. So, just copy. value = copy.copy(value) setattr(new, _attr, value) if self.has_data: new._data = apply_method(self.data) else: new._data = None shapes = [getattr(new, '_' + attr).shape for attr in new.frame_attributes if (attr not in new._attr_names_with_defaults and getattr(getattr(new, '_' + attr), 'size', 1) > 1)] if shapes: new._no_data_shape = (check_broadcast(*shapes) if len(shapes) > 1 else shapes[0]) else: new._no_data_shape = () return new @override__dir__ def __dir__(self): """ Override the builtin `dir` behavior to include representation names. TODO: dynamic representation transforms (i.e. include cylindrical et al.). """ dir_values = set(self.representation_component_names) dir_values |= set(self.get_representation_component_names('s')) return dir_values def __getattr__(self, attr): """ Allow access to attributes on the representation and differential as found via ``self.get_representation_component_names``. TODO: We should handle dynamic representation transforms here (e.g., `.cylindrical`) instead of defining properties as below. """ # attr == '_representation' is likely from the hasattr() test in the # representation property which is used for # self.representation_component_names. # # Prevent infinite recursion here. if attr.startswith('_'): return self.__getattribute__(attr) # Raise AttributeError. repr_names = self.representation_component_names if attr in repr_names: if self._data is None: self.data # this raises the "no data" error by design - doing it # this way means we don't have to replicate the error message here rep = self.represent_as(self.representation_type, in_frame_units=True) val = getattr(rep, repr_names[attr]) return val diff_names = self.get_representation_component_names('s') if attr in diff_names: if self._data is None: self.data # see above. # TODO: this doesn't work for the case when there is only # unitspherical information. The differential_type gets set to the # default_differential, which expects full information, so the # units don't work out rep = self.represent_as(in_frame_units=True, **self.get_representation_cls(None)) val = getattr(rep.differentials['s'], diff_names[attr]) return val return self.__getattribute__(attr) # Raise AttributeError. def __setattr__(self, attr, value): # Don't slow down access of private attributes! if not attr.startswith('_'): if hasattr(self, 'representation_info'): repr_attr_names = set() for representation_attr in self.representation_info.values(): repr_attr_names.update(representation_attr['names']) if attr in repr_attr_names: raise AttributeError( 'Cannot set any frame attribute {0}'.format(attr)) super().__setattr__(attr, value) def separation(self, other): """ Computes on-sky separation between this coordinate and another. .. note:: If the ``other`` coordinate object is in a different frame, it is first transformed to the frame of this object. This can lead to unintutive behavior if not accounted for. Particularly of note is that ``self.separation(other)`` and ``other.separation(self)`` may not give the same answer in this case. Parameters ---------- other : `~astropy.coordinates.BaseCoordinateFrame` The coordinate to get the separation to. Returns ------- sep : `~astropy.coordinates.Angle` The on-sky separation between this and the ``other`` coordinate. Notes ----- The separation is calculated using the Vincenty formula, which is stable at all locations, including poles and antipodes [1]_. .. [1] https://en.wikipedia.org/wiki/Great-circle_distance """ from .angle_utilities import angular_separation from .angles import Angle self_unit_sph = self.represent_as(r.UnitSphericalRepresentation) other_transformed = other.transform_to(self) other_unit_sph = other_transformed.represent_as(r.UnitSphericalRepresentation) # Get the separation as a Quantity, convert to Angle in degrees sep = angular_separation(self_unit_sph.lon, self_unit_sph.lat, other_unit_sph.lon, other_unit_sph.lat) return Angle(sep, unit=u.degree) def separation_3d(self, other): """ Computes three dimensional separation between this coordinate and another. Parameters ---------- other : `~astropy.coordinates.BaseCoordinateFrame` The coordinate system to get the distance to. Returns ------- sep : `~astropy.coordinates.Distance` The real-space distance between these two coordinates. Raises ------ ValueError If this or the other coordinate do not have distances. """ from .distances import Distance if issubclass(self.data.__class__, r.UnitSphericalRepresentation): raise ValueError('This object does not have a distance; cannot ' 'compute 3d separation.') # do this first just in case the conversion somehow creates a distance other_in_self_system = other.transform_to(self) if issubclass(other_in_self_system.__class__, r.UnitSphericalRepresentation): raise ValueError('The other object does not have a distance; ' 'cannot compute 3d separation.') # drop the differentials to ensure they don't do anything odd in the # subtraction self_car = self.data.without_differentials().represent_as(r.CartesianRepresentation) other_car = other_in_self_system.data.without_differentials().represent_as(r.CartesianRepresentation) return Distance((self_car - other_car).norm()) @property def cartesian(self): """ Shorthand for a cartesian representation of the coordinates in this object. """ # TODO: if representations are updated to use a full transform graph, # the representation aliases should not be hard-coded like this return self.represent_as('cartesian', in_frame_units=True) @property def spherical(self): """ Shorthand for a spherical representation of the coordinates in this object. """ # TODO: if representations are updated to use a full transform graph, # the representation aliases should not be hard-coded like this return self.represent_as('spherical', in_frame_units=True) @property def sphericalcoslat(self): """ Shorthand for a spherical representation of the positional data and a `SphericalCosLatDifferential` for the velocity data in this object. """ # TODO: if representations are updated to use a full transform graph, # the representation aliases should not be hard-coded like this return self.represent_as('spherical', 'sphericalcoslat', in_frame_units=True) @property def velocity(self): """ Shorthand for retrieving the Cartesian space-motion as a `CartesianDifferential` object. This is equivalent to calling ``self.cartesian.differentials['s']``. """ if 's' not in self.data.differentials: raise ValueError('Frame has no associated velocity (Differential) ' 'data information.') try: v = self.cartesian.differentials['s'] except Exception as e: raise ValueError('Could not retrieve a Cartesian velocity. Your ' 'frame must include velocity information for this ' 'to work.') return v @property def proper_motion(self): """ Shorthand for the two-dimensional proper motion as a `~astropy.units.Quantity` object with angular velocity units. In the returned `~astropy.units.Quantity`, ``axis=0`` is the longitude/latitude dimension so that ``.proper_motion[0]`` is the longitudinal proper motion and ``.proper_motion[1]`` is latitudinal. The longitudinal proper motion already includes the cos(latitude) term. """ if 's' not in self.data.differentials: raise ValueError('Frame has no associated velocity (Differential) ' 'data information.') sph = self.represent_as('spherical', 'sphericalcoslat', in_frame_units=True) pm_lon = sph.differentials['s'].d_lon_coslat pm_lat = sph.differentials['s'].d_lat return np.stack((pm_lon.value, pm_lat.to(pm_lon.unit).value), axis=0) * pm_lon.unit @property def radial_velocity(self): """ Shorthand for the radial or line-of-sight velocity as a `~astropy.units.Quantity` object. """ if 's' not in self.data.differentials: raise ValueError('Frame has no associated velocity (Differential) ' 'data information.') sph = self.represent_as('spherical', in_frame_units=True) return sph.differentials['s'].d_distance class GenericFrame(BaseCoordinateFrame): """ A frame object that can't store data but can hold any arbitrary frame attributes. Mostly useful as a utility for the high-level class to store intermediate frame attributes. Parameters ---------- frame_attrs : dict A dictionary of attributes to be used as the frame attributes for this frame. """ name = None # it's not a "real" frame so it doesn't have a name def __init__(self, frame_attrs): self.frame_attributes = OrderedDict() for name, default in frame_attrs.items(): self.frame_attributes[name] = Attribute(default) setattr(self, '_' + name, default) super().__init__(None) def __getattr__(self, name): if '_' + name in self.__dict__: return getattr(self, '_' + name) else: raise AttributeError('no {0}'.format(name)) def __setattr__(self, name, value): if name in self.get_frame_attr_names(): raise AttributeError("can't set frame attribute '{0}'".format(name)) else: super().__setattr__(name, value)
3dfd36d3b798b8196bea52e498dc572042160f5394b27bfad9f0a199f3f9fad7
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains convenience functions implementing some of the algorithms contained within Jean Meeus, 'Astronomical Algorithms', second edition, 1998, Willmann-Bell. """ import numpy as np from numpy.polynomial.polynomial import polyval from .. import units as u from .. import _erfa as erfa from . import ICRS, SkyCoord, GeocentricTrueEcliptic from .builtin_frames.utils import get_jd12 __all__ = ["calc_moon"] # Meeus 1998: table 47.A # D M M' F l r _MOON_L_R = ( (0, 0, 1, 0, 6288774, -20905355), (2, 0, -1, 0, 1274027, -3699111), (2, 0, 0, 0, 658314, -2955968), (0, 0, 2, 0, 213618, -569925), (0, 1, 0, 0, -185116, 48888), (0, 0, 0, 2, -114332, -3149), (2, 0, -2, 0, 58793, 246158), (2, -1, -1, 0, 57066, -152138), (2, 0, 1, 0, 53322, -170733), (2, -1, 0, 0, 45758, -204586), (0, 1, -1, 0, -40923, -129620), (1, 0, 0, 0, -34720, 108743), (0, 1, 1, 0, -30383, 104755), (2, 0, 0, -2, 15327, 10321), (0, 0, 1, 2, -12528, 0), (0, 0, 1, -2, 10980, 79661), (4, 0, -1, 0, 10675, -34782), (0, 0, 3, 0, 10034, -23210), (4, 0, -2, 0, 8548, -21636), (2, 1, -1, 0, -7888, 24208), (2, 1, 0, 0, -6766, 30824), (1, 0, -1, 0, -5163, -8379), (1, 1, 0, 0, 4987, -16675), (2, -1, 1, 0, 4036, -12831), (2, 0, 2, 0, 3994, -10445), (4, 0, 0, 0, 3861, -11650), (2, 0, -3, 0, 3665, 14403), (0, 1, -2, 0, -2689, -7003), (2, 0, -1, 2, -2602, 0), (2, -1, -2, 0, 2390, 10056), (1, 0, 1, 0, -2348, 6322), (2, -2, 0, 0, 2236, -9884), (0, 1, 2, 0, -2120, 5751), (0, 2, 0, 0, -2069, 0), (2, -2, -1, 0, 2048, -4950), (2, 0, 1, -2, -1773, 4130), (2, 0, 0, 2, -1595, 0), (4, -1, -1, 0, 1215, -3958), (0, 0, 2, 2, -1110, 0), (3, 0, -1, 0, -892, 3258), (2, 1, 1, 0, -810, 2616), (4, -1, -2, 0, 759, -1897), (0, 2, -1, 0, -713, -2117), (2, 2, -1, 0, -700, 2354), (2, 1, -2, 0, 691, 0), (2, -1, 0, -2, 596, 0), (4, 0, 1, 0, 549, -1423), (0, 0, 4, 0, 537, -1117), (4, -1, 0, 0, 520, -1571), (1, 0, -2, 0, -487, -1739), (2, 1, 0, -2, -399, 0), (0, 0, 2, -2, -381, -4421), (1, 1, 1, 0, 351, 0), (3, 0, -2, 0, -340, 0), (4, 0, -3, 0, 330, 0), (2, -1, 2, 0, 327, 0), (0, 2, 1, 0, -323, 1165), (1, 1, -1, 0, 299, 0), (2, 0, 3, 0, 294, 0), (2, 0, -1, -2, 0, 8752) ) # Meeus 1998: table 47.B # D M M' F b _MOON_B = ( (0, 0, 0, 1, 5128122), (0, 0, 1, 1, 280602), (0, 0, 1, -1, 277693), (2, 0, 0, -1, 173237), (2, 0, -1, 1, 55413), (2, 0, -1, -1, 46271), (2, 0, 0, 1, 32573), (0, 0, 2, 1, 17198), (2, 0, 1, -1, 9266), (0, 0, 2, -1, 8822), (2, -1, 0, -1, 8216), (2, 0, -2, -1, 4324), (2, 0, 1, 1, 4200), (2, 1, 0, -1, -3359), (2, -1, -1, 1, 2463), (2, -1, 0, 1, 2211), (2, -1, -1, -1, 2065), (0, 1, -1, -1, -1870), (4, 0, -1, -1, 1828), (0, 1, 0, 1, -1794), (0, 0, 0, 3, -1749), (0, 1, -1, 1, -1565), (1, 0, 0, 1, -1491), (0, 1, 1, 1, -1475), (0, 1, 1, -1, -1410), (0, 1, 0, -1, -1344), (1, 0, 0, -1, -1335), (0, 0, 3, 1, 1107), (4, 0, 0, -1, 1021), (4, 0, -1, 1, 833), # second column (0, 0, 1, -3, 777), (4, 0, -2, 1, 671), (2, 0, 0, -3, 607), (2, 0, 2, -1, 596), (2, -1, 1, -1, 491), (2, 0, -2, 1, -451), (0, 0, 3, -1, 439), (2, 0, 2, 1, 422), (2, 0, -3, -1, 421), (2, 1, -1, 1, -366), (2, 1, 0, 1, -351), (4, 0, 0, 1, 331), (2, -1, 1, 1, 315), (2, -2, 0, -1, 302), (0, 0, 1, 3, -283), (2, 1, 1, -1, -229), (1, 1, 0, -1, 223), (1, 1, 0, 1, 223), (0, 1, -2, -1, -220), (2, 1, -1, -1, -220), (1, 0, 1, 1, -185), (2, -1, -2, -1, 181), (0, 1, 2, 1, -177), (4, 0, -2, -1, 176), (4, -1, -1, -1, 166), (1, 0, 1, -1, -164), (4, 0, 1, -1, 132), (1, 0, -1, -1, -119), (4, -1, 0, -1, 115), (2, -2, 0, 1, 107) ) """ Coefficients of polynomials for various terms: Lc : Mean longitude of Moon, w.r.t mean Equinox of date D : Mean elongation of the Moon M: Sun's mean anomaly Mc : Moon's mean anomaly F : Moon's argument of latitude (mean distance of Moon from its ascending node). """ _coLc = (2.18316448e+02, 4.81267881e+05, -1.57860000e-03, 1.85583502e-06, -1.53388349e-08) _coD = (2.97850192e+02, 4.45267111e+05, -1.88190000e-03, 1.83194472e-06, -8.84447000e-09) _coM = (3.57529109e+02, 3.59990503e+04, -1.53600000e-04, 4.08329931e-08) _coMc = (1.34963396e+02, 4.77198868e+05, 8.74140000e-03, 1.43474081e-05, -6.79717238e-08) _coF = (9.32720950e+01, 4.83202018e+05, -3.65390000e-03, -2.83607487e-07, 1.15833246e-09) _coA1 = (119.75, 131.849) _coA2 = (53.09, 479264.290) _coA3 = (313.45, 481266.484) _coE = (1.0, -0.002516, -0.0000074) def calc_moon(t): """ Lunar position model ELP2000-82 of (Chapront-Touze' and Chapront, 1983, 124, 50) This is the simplified version of Jean Meeus, Astronomical Algorithms, second edition, 1998, Willmann-Bell. Meeus claims approximate accuracy of 10" in longitude and 4" in latitude, with no specified time range. Tests against JPL ephemerides show accuracy of 10 arcseconds and 50 km over the date range CE 1950-2050. Parameters ----------- t : `~astropy.time.Time` Time of observation. Returns -------- skycoord : `~astropy.coordinates.SkyCoord` ICRS Coordinate for the body """ # number of centuries since J2000.0. # This should strictly speaking be in Ephemeris Time, but TDB or TT # will introduce error smaller than intrinsic accuracy of algorithm. T = (t.tdb.jyear-2000.0)/100. # constants that are needed for all calculations Lc = u.Quantity(polyval(T, _coLc), u.deg) D = u.Quantity(polyval(T, _coD), u.deg) M = u.Quantity(polyval(T, _coM), u.deg) Mc = u.Quantity(polyval(T, _coMc), u.deg) F = u.Quantity(polyval(T, _coF), u.deg) A1 = u.Quantity(polyval(T, _coA1), u.deg) A2 = u.Quantity(polyval(T, _coA2), u.deg) A3 = u.Quantity(polyval(T, _coA3), u.deg) E = polyval(T, _coE) suml = sumr = 0.0 for DNum, MNum, McNum, FNum, LFac, RFac in _MOON_L_R: corr = E ** abs(MNum) suml += LFac*corr*np.sin(D*DNum+M*MNum+Mc*McNum+F*FNum) sumr += RFac*corr*np.cos(D*DNum+M*MNum+Mc*McNum+F*FNum) sumb = 0.0 for DNum, MNum, McNum, FNum, BFac in _MOON_B: corr = E ** abs(MNum) sumb += BFac*corr*np.sin(D*DNum+M*MNum+Mc*McNum+F*FNum) suml += (3958*np.sin(A1) + 1962*np.sin(Lc-F) + 318*np.sin(A2)) sumb += (-2235*np.sin(Lc) + 382*np.sin(A3) + 175*np.sin(A1-F) + 175*np.sin(A1+F) + 127*np.sin(Lc-Mc) - 115*np.sin(Lc+Mc)) # ensure units suml = suml*u.microdegree sumb = sumb*u.microdegree # nutation of longitude jd1, jd2 = get_jd12(t, 'tt') nut, _ = erfa.nut06a(jd1, jd2) nut = nut*u.rad # calculate ecliptic coordinates lon = Lc + suml + nut lat = sumb dist = (385000.56+sumr/1000)*u.km # Meeus algorithm gives GeocentricTrueEcliptic coordinates ecliptic_coo = GeocentricTrueEcliptic(lon, lat, distance=dist, equinox=t) return SkyCoord(ecliptic_coo.transform_to(ICRS))
7ee98ad08bbf2679c3662425250d601b7c56b343d8b91a44d09e04d1f6fa0229
# Licensed under a 3-clause BSD style license - see LICENSE.rst from warnings import warn import collections import socket import json import urllib.request import urllib.error import urllib.parse import numpy as np from .. import units as u from .. import constants as consts from ..units.quantity import QuantityInfoBase from ..utils.exceptions import AstropyUserWarning from ..utils.compat.numpycompat import NUMPY_LT_1_12 from .angles import Longitude, Latitude from .representation import CartesianRepresentation, CartesianDifferential from .errors import UnknownSiteException from ..utils import data, deprecated try: # Not guaranteed available at setup time. from .. import _erfa as erfa except ImportError: if not _ASTROPY_SETUP_: raise __all__ = ['EarthLocation'] GeodeticLocation = collections.namedtuple('GeodeticLocation', ['lon', 'lat', 'height']) # Available ellipsoids (defined in erfam.h, with numbers exposed in erfa). ELLIPSOIDS = ('WGS84', 'GRS80', 'WGS72') OMEGA_EARTH = u.Quantity(7.292115855306589e-5, 1./u.s) """ Rotational velocity of Earth. In UT1 seconds, this would be 2 pi / (24 * 3600), but we need the value in SI seconds. See Explanatory Supplement to the Astronomical Almanac, ed. P. Kenneth Seidelmann (1992), University Science Books. """ def _check_ellipsoid(ellipsoid=None, default='WGS84'): if ellipsoid is None: ellipsoid = default if ellipsoid not in ELLIPSOIDS: raise ValueError('Ellipsoid {0} not among known ones ({1})' .format(ellipsoid, ELLIPSOIDS)) return ellipsoid def _get_json_result(url, err_str): # need to do this here to prevent a series of complicated circular imports from .name_resolve import NameResolveError try: # Retrieve JSON response from Google maps API resp = urllib.request.urlopen(url, timeout=data.conf.remote_timeout) resp_data = json.loads(resp.read().decode('utf8')) except urllib.error.URLError as e: # This catches a timeout error, see: # http://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python if isinstance(e.reason, socket.timeout): raise NameResolveError(err_str.format(msg="connection timed out")) else: raise NameResolveError(err_str.format(msg=e.reason)) except socket.timeout: # There are some cases where urllib2 does not catch socket.timeout # especially while receiving response data on an already previously # working request raise NameResolveError(err_str.format(msg="connection timed out")) results = resp_data.get('results', []) if not results: raise NameResolveError(err_str.format(msg="no results returned")) if resp_data.get('status', None) != 'OK': raise NameResolveError(err_str.format(msg="unknown failure with Google maps API")) return results class EarthLocationInfo(QuantityInfoBase): """ Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information. """ _represent_as_dict_attrs = ('x', 'y', 'z', 'ellipsoid') def _construct_from_dict(self, map): # Need to pop ellipsoid off and update post-instantiation. This is # on the to-fix list in #4261. ellipsoid = map.pop('ellipsoid') out = self._parent_cls(**map) out.ellipsoid = ellipsoid return out def new_like(self, cols, length, metadata_conflicts='warn', name=None): """ Return a new EarthLocation instance which is consistent with the input ``cols`` and has ``length`` rows. This is intended for creating an empty column object whose elements can be set in-place for table operations like join or vstack. Parameters ---------- cols : list List of input columns length : int Length of the output column object metadata_conflicts : str ('warn'|'error'|'silent') How to handle metadata conflicts name : str Output column name Returns ------- col : EarthLocation (or subclass) Empty instance of this class consistent with ``cols`` """ # Very similar to QuantityInfo.new_like, but the creation of the # map is different enough that this needs its own rouinte. # Get merged info attributes shape, dtype, format, description. attrs = self.merge_cols_attributes(cols, metadata_conflicts, name, ('meta', 'format', 'description')) # The above raises an error if the dtypes do not match, but returns # just the string representation, which is not useful, so remove. attrs.pop('dtype') # Make empty EarthLocation using the dtype and unit of the last column. # Use zeros so we do not get problems for possible conversion to # geodetic coordinates. shape = (length,) + attrs.pop('shape') data = u.Quantity(np.zeros(shape=shape, dtype=cols[0].dtype), unit=cols[0].unit, copy=False) # Get arguments needed to reconstruct class map = {key: (data[key] if key in 'xyz' else getattr(cols[-1], key)) for key in self._represent_as_dict_attrs} out = self._construct_from_dict(map) # Set remaining info attributes for attr, value in attrs.items(): setattr(out.info, attr, value) return out class EarthLocation(u.Quantity): """ Location on the Earth. Initialization is first attempted assuming geocentric (x, y, z) coordinates are given; if that fails, another attempt is made assuming geodetic coordinates (longitude, latitude, height above a reference ellipsoid). When using the geodetic forms, Longitudes are measured increasing to the east, so west longitudes are negative. Internally, the coordinates are stored as geocentric. To ensure a specific type of coordinates is used, use the corresponding class methods (`from_geocentric` and `from_geodetic`) or initialize the arguments with names (``x``, ``y``, ``z`` for geocentric; ``lon``, ``lat``, ``height`` for geodetic). See the class methods for details. Notes ----- This class fits into the coordinates transformation framework in that it encodes a position on the `~astropy.coordinates.ITRS` frame. To get a proper `~astropy.coordinates.ITRS` object from this object, use the ``itrs`` property. """ _ellipsoid = 'WGS84' _location_dtype = np.dtype({'names': ['x', 'y', 'z'], 'formats': [np.float64]*3}) _array_dtype = np.dtype((np.float64, (3,))) info = EarthLocationInfo() def __new__(cls, *args, **kwargs): # TODO: needs copy argument and better dealing with inputs. if (len(args) == 1 and len(kwargs) == 0 and isinstance(args[0], EarthLocation)): return args[0].copy() try: self = cls.from_geocentric(*args, **kwargs) except (u.UnitsError, TypeError) as exc_geocentric: try: self = cls.from_geodetic(*args, **kwargs) except Exception as exc_geodetic: raise TypeError('Coordinates could not be parsed as either ' 'geocentric or geodetic, with respective ' 'exceptions "{0}" and "{1}"' .format(exc_geocentric, exc_geodetic)) return self @classmethod def from_geocentric(cls, x, y, z, unit=None): """ Location on Earth, initialized from geocentric coordinates. Parameters ---------- x, y, z : `~astropy.units.Quantity` or array-like Cartesian coordinates. If not quantities, ``unit`` should be given. unit : `~astropy.units.UnitBase` object or None Physical unit of the coordinate values. If ``x``, ``y``, and/or ``z`` are quantities, they will be converted to this unit. Raises ------ astropy.units.UnitsError If the units on ``x``, ``y``, and ``z`` do not match or an invalid unit is given. ValueError If the shapes of ``x``, ``y``, and ``z`` do not match. TypeError If ``x`` is not a `~astropy.units.Quantity` and no unit is given. """ if unit is None: try: unit = x.unit except AttributeError: raise TypeError("Geocentric coordinates should be Quantities " "unless an explicit unit is given.") else: unit = u.Unit(unit) if unit.physical_type != 'length': raise u.UnitsError("Geocentric coordinates should be in " "units of length.") try: x = u.Quantity(x, unit, copy=False) y = u.Quantity(y, unit, copy=False) z = u.Quantity(z, unit, copy=False) except u.UnitsError: raise u.UnitsError("Geocentric coordinate units should all be " "consistent.") x, y, z = np.broadcast_arrays(x, y, z) struc = np.empty(x.shape, cls._location_dtype) struc['x'], struc['y'], struc['z'] = x, y, z return super().__new__(cls, struc, unit, copy=False) @classmethod def from_geodetic(cls, lon, lat, height=0., ellipsoid=None): """ Location on Earth, initialized from geodetic coordinates. Parameters ---------- lon : `~astropy.coordinates.Longitude` or float Earth East longitude. Can be anything that initialises an `~astropy.coordinates.Angle` object (if float, in degrees). lat : `~astropy.coordinates.Latitude` or float Earth latitude. Can be anything that initialises an `~astropy.coordinates.Latitude` object (if float, in degrees). height : `~astropy.units.Quantity` or float, optional Height above reference ellipsoid (if float, in meters; default: 0). ellipsoid : str, optional Name of the reference ellipsoid to use (default: 'WGS84'). Available ellipsoids are: 'WGS84', 'GRS80', 'WGS72'. Raises ------ astropy.units.UnitsError If the units on ``lon`` and ``lat`` are inconsistent with angular ones, or that on ``height`` with a length. ValueError If ``lon``, ``lat``, and ``height`` do not have the same shape, or if ``ellipsoid`` is not recognized as among the ones implemented. Notes ----- For the conversion to geocentric coordinates, the ERFA routine ``gd2gc`` is used. See https://github.com/liberfa/erfa """ ellipsoid = _check_ellipsoid(ellipsoid, default=cls._ellipsoid) lon = Longitude(lon, u.degree, wrap_angle=180*u.degree, copy=False) lat = Latitude(lat, u.degree, copy=False) # don't convert to m by default, so we can use the height unit below. if not isinstance(height, u.Quantity): height = u.Quantity(height, u.m, copy=False) # convert to float in units required for erfa routine, and ensure # all broadcast to same shape, and are at least 1-dimensional. _lon, _lat, _height = np.broadcast_arrays(lon.to_value(u.radian), lat.to_value(u.radian), height.to_value(u.m)) # get geocentric coordinates. Have to give one-dimensional array. xyz = erfa.gd2gc(getattr(erfa, ellipsoid), _lon.ravel(), _lat.ravel(), _height.ravel()) self = xyz.view(cls._location_dtype, cls).reshape(_lon.shape) self._unit = u.meter self._ellipsoid = ellipsoid return self.to(height.unit) @classmethod def of_site(cls, site_name): """ Return an object of this class for a known observatory/site by name. This is intended as a quick convenience function to get basic site information, not a fully-featured exhaustive registry of observatories and all their properties. .. note:: When this function is called, it will attempt to download site information from the astropy data server. If you would like a site to be added, issue a pull request to the `astropy-data repository <https://github.com/astropy/astropy-data>`_ . If a site cannot be found in the registry (i.e., an internet connection is not available), it will fall back on a built-in list, In the future, this bundled list might include a version-controlled list of canonical observatories extracted from the online version, but it currently only contains the Greenwich Royal Observatory as an example case. Parameters ---------- site_name : str Name of the observatory (case-insensitive). Returns ------- site : This class (a `~astropy.coordinates.EarthLocation` or subclass) The location of the observatory. See Also -------- get_site_names : the list of sites that this function can access """ registry = cls._get_site_registry() try: el = registry[site_name] except UnknownSiteException as e: raise UnknownSiteException(e.site, 'EarthLocation.get_site_names', close_names=e.close_names) if cls is el.__class__: return el else: newel = cls.from_geodetic(*el.to_geodetic()) newel.info.name = el.info.name return newel @classmethod def of_address(cls, address, get_height=False): """ Return an object of this class for a given address by querying the Google maps geocoding API. This is intended as a quick convenience function to get fast access to locations. In the background, this just issues a query to the Google maps geocoding API. It is not meant to be abused! Google uses IP-based query limiting and will ban your IP if you send more than a few thousand queries per hour [1]_. .. warning:: If the query returns more than one location (e.g., searching on ``address='springfield'``), this function will use the **first** returned location. Parameters ---------- address : str The address to get the location for. As per the Google maps API, this can be a fully specified street address (e.g., 123 Main St., New York, NY) or a city name (e.g., Danbury, CT), or etc. get_height : bool (optional) Use the retrieved location to perform a second query to the Google maps elevation API to retrieve the height of the input address [2]_. Returns ------- location : This class (a `~astropy.coordinates.EarthLocation` or subclass) The location of the input address. References ---------- .. [1] https://developers.google.com/maps/documentation/geocoding/intro .. [2] https://developers.google.com/maps/documentation/elevation/intro """ pars = urllib.parse.urlencode({'address': address}) geo_url = "https://maps.googleapis.com/maps/api/geocode/json?{0}".format(pars) # get longitude and latitude location err_str = ("Unable to retrieve coordinates for address '{address}'; {{msg}}" .format(address=address)) geo_result = _get_json_result(geo_url, err_str=err_str) loc = geo_result[0]['geometry']['location'] if get_height: pars = {'locations': '{lat:.8f},{lng:.8f}'.format(lat=loc['lat'], lng=loc['lng'])} pars = urllib.parse.urlencode(pars) ele_url = "https://maps.googleapis.com/maps/api/elevation/json?{0}".format(pars) err_str = ("Unable to retrieve elevation for address '{address}'; {{msg}}" .format(address=address)) ele_result = _get_json_result(ele_url, err_str=err_str) height = ele_result[0]['elevation']*u.meter else: height = 0. return cls.from_geodetic(lon=loc['lng']*u.degree, lat=loc['lat']*u.degree, height=height) @classmethod def get_site_names(cls): """ Get list of names of observatories for use with `~astropy.coordinates.EarthLocation.of_site`. .. note:: When this function is called, it will first attempt to download site information from the astropy data server. If it cannot (i.e., an internet connection is not available), it will fall back on the list included with astropy (which is a limited and dated set of sites). If you think a site should be added, issue a pull request to the `astropy-data repository <https://github.com/astropy/astropy-data>`_ . Returns ------- names : list of str List of valid observatory names See Also -------- of_site : Gets the actual location object for one of the sites names this returns. """ return cls._get_site_registry().names @classmethod def _get_site_registry(cls, force_download=False, force_builtin=False): """ Gets the site registry. The first time this either downloads or loads from the data file packaged with astropy. Subsequent calls will use the cached version unless explicitly overridden. Parameters ---------- force_download : bool or str If not False, force replacement of the cached registry with a downloaded version. If a str, that will be used as the URL to download from (if just True, the default URL will be used). force_builtin : bool If True, load from the data file bundled with astropy and set the cache to that. returns ------- reg : astropy.coordinates.sites.SiteRegistry """ if force_builtin and force_download: raise ValueError('Cannot have both force_builtin and force_download True') if force_builtin: reg = cls._site_registry = get_builtin_sites() else: reg = getattr(cls, '_site_registry', None) if force_download or not reg: try: if isinstance(force_download, str): reg = get_downloaded_sites(force_download) else: reg = get_downloaded_sites() except OSError: if force_download: raise msg = ('Could not access the online site list. Falling ' 'back on the built-in version, which is rather ' 'limited. If you want to retry the download, do ' '{0}._get_site_registry(force_download=True)') warn(AstropyUserWarning(msg.format(cls.__name__))) reg = get_builtin_sites() cls._site_registry = reg return reg @property def ellipsoid(self): """The default ellipsoid used to convert to geodetic coordinates.""" return self._ellipsoid @ellipsoid.setter def ellipsoid(self, ellipsoid): self._ellipsoid = _check_ellipsoid(ellipsoid) @property def geodetic(self): """Convert to geodetic coordinates for the default ellipsoid.""" return self.to_geodetic() def to_geodetic(self, ellipsoid=None): """Convert to geodetic coordinates. Parameters ---------- ellipsoid : str, optional Reference ellipsoid to use. Default is the one the coordinates were initialized with. Available are: 'WGS84', 'GRS80', 'WGS72' Returns ------- (lon, lat, height) : tuple The tuple contains instances of `~astropy.coordinates.Longitude`, `~astropy.coordinates.Latitude`, and `~astropy.units.Quantity` Raises ------ ValueError if ``ellipsoid`` is not recognized as among the ones implemented. Notes ----- For the conversion to geodetic coordinates, the ERFA routine ``gc2gd`` is used. See https://github.com/liberfa/erfa """ ellipsoid = _check_ellipsoid(ellipsoid, default=self.ellipsoid) self_array = self.to(u.meter).view(self._array_dtype, np.ndarray) lon, lat, height = erfa.gc2gd(getattr(erfa, ellipsoid), self_array) return GeodeticLocation( Longitude(lon * u.radian, u.degree, wrap_angle=180.*u.degree, copy=False), Latitude(lat * u.radian, u.degree, copy=False), u.Quantity(height * u.meter, self.unit, copy=False)) @property @deprecated('2.0', alternative='`lon`', obj_type='property') def longitude(self): """Longitude of the location, for the default ellipsoid.""" return self.geodetic[0] @property def lon(self): """Longitude of the location, for the default ellipsoid.""" return self.geodetic[0] @property @deprecated('2.0', alternative='`lat`', obj_type='property') def latitude(self): """Latitude of the location, for the default ellipsoid.""" return self.geodetic[1] @property def lat(self): """Longitude of the location, for the default ellipsoid.""" return self.geodetic[1] @property def height(self): """Height of the location, for the default ellipsoid.""" return self.geodetic[2] # mostly for symmetry with geodetic and to_geodetic. @property def geocentric(self): """Convert to a tuple with X, Y, and Z as quantities""" return self.to_geocentric() def to_geocentric(self): """Convert to a tuple with X, Y, and Z as quantities""" return (self.x, self.y, self.z) def get_itrs(self, obstime=None): """ Generates an `~astropy.coordinates.ITRS` object with the location of this object at the requested ``obstime``. Parameters ---------- obstime : `~astropy.time.Time` or None The ``obstime`` to apply to the new `~astropy.coordinates.ITRS`, or if None, the default ``obstime`` will be used. Returns ------- itrs : `~astropy.coordinates.ITRS` The new object in the ITRS frame """ # Broadcast for a single position at multiple times, but don't attempt # to be more general here. if obstime and self.size == 1 and obstime.size > 1: self = np.broadcast_to(self, obstime.shape, subok=True) # do this here to prevent a series of complicated circular imports from .builtin_frames import ITRS return ITRS(x=self.x, y=self.y, z=self.z, obstime=obstime) itrs = property(get_itrs, doc="""An `~astropy.coordinates.ITRS` object with for the location of this object at the default ``obstime``.""") def get_gcrs(self, obstime): """GCRS position with velocity at ``obstime`` as a GCRS coordinate. Parameters ---------- obstime : `~astropy.time.Time` The ``obstime`` to calculate the GCRS position/velocity at. Returns -------- gcrs : `~astropy.coordinates.GCRS` instance With velocity included. """ # do this here to prevent a series of complicated circular imports from .builtin_frames import GCRS itrs = self.get_itrs(obstime) # Assume the observatory itself is fixed on the ground. # We do a direct assignment rather than an update to avoid validation # and creation of a new object. zeros = np.broadcast_to(0. * u.km / u.s, (3,) + itrs.shape, subok=True) itrs.data.differentials['s'] = CartesianDifferential(zeros) return itrs.transform_to(GCRS(obstime=obstime)) def get_gcrs_posvel(self, obstime): """ Calculate the GCRS position and velocity of this object at the requested ``obstime``. Parameters ---------- obstime : `~astropy.time.Time` The ``obstime`` to calculate the GCRS position/velocity at. Returns -------- obsgeoloc : `~astropy.coordinates.CartesianRepresentation` The GCRS position of the object obsgeovel : `~astropy.coordinates.CartesianRepresentation` The GCRS velocity of the object """ # GCRS position gcrs_data = self.get_gcrs(obstime).data obsgeopos = gcrs_data.without_differentials() obsgeovel = gcrs_data.differentials['s'].to_cartesian() return obsgeopos, obsgeovel def gravitational_redshift(self, obstime, bodies=['sun', 'jupiter', 'moon'], masses={}): """Return the gravitational redshift at this EarthLocation. Calculates the gravitational redshift, of order 3 m/s, due to the requested solar system bodies. Parameters ---------- obstime : `~astropy.time.Time` The ``obstime`` to calculate the redshift at. bodies : iterable, optional The bodies (other than the Earth) to include in the redshift calculation. List elements should be any body name `get_body_barycentric` accepts. Defaults to Jupiter, the Sun, and the Moon. Earth is always included (because the class represents an *Earth* location). masses : dict of str to Quantity, optional The mass or gravitational parameters (G * mass) to assume for the bodies requested in ``bodies``. Can be used to override the defaults for the Sun, Jupiter, the Moon, and the Earth, or to pass in masses for other bodies. Returns -------- redshift : `~astropy.units.Quantity` Gravitational redshift in velocity units at given obstime. """ # needs to be here to avoid circular imports from .solar_system import get_body_barycentric bodies = list(bodies) # Ensure earth is included and last in the list. if 'earth' in bodies: bodies.remove('earth') bodies.append('earth') _masses = {'sun': consts.GM_sun, 'jupiter': consts.GM_jup, 'moon': consts.G * 7.34767309e22*u.kg, 'earth': consts.GM_earth} _masses.update(masses) GMs = [] M_GM_equivalency = (u.kg, u.Unit(consts.G * u.kg)) for body in bodies: try: GMs.append(_masses[body].to(u.m**3/u.s**2, [M_GM_equivalency])) except KeyError as exc: raise KeyError('body "{}" does not have a mass!'.format(body)) except u.UnitsError as exc: exc.args += ('"masses" argument values must be masses or ' 'gravitational parameters',) raise positions = [get_body_barycentric(name, obstime) for name in bodies] # Calculate distances to objects other than earth. distances = [(pos - positions[-1]).norm() for pos in positions[:-1]] # Append distance from Earth's center for Earth's contribution. distances.append(CartesianRepresentation(self.geocentric).norm()) # Get redshifts due to all objects. redshifts = [-GM / consts.c / distance for (GM, distance) in zip(GMs, distances)] # Reverse order of summing, to go from small to big, and to get # "earth" first, which gives m/s as unit. return sum(redshifts[::-1]) @property def x(self): """The X component of the geocentric coordinates.""" return self['x'] @property def y(self): """The Y component of the geocentric coordinates.""" return self['y'] @property def z(self): """The Z component of the geocentric coordinates.""" return self['z'] def __getitem__(self, item): result = super().__getitem__(item) if result.dtype is self.dtype: return result.view(self.__class__) else: return result.view(u.Quantity) def __array_finalize__(self, obj): super().__array_finalize__(obj) if hasattr(obj, '_ellipsoid'): self._ellipsoid = obj._ellipsoid def __len__(self): if self.shape == (): raise IndexError('0-d EarthLocation arrays cannot be indexed') else: return super().__len__() def _to_value(self, unit, equivalencies=[]): """Helper method for to and to_value.""" # Conversion to another unit in both ``to`` and ``to_value`` goes # via this routine. To make the regular quantity routines work, we # temporarily turn the structured array into a regular one. array_view = self.view(self._array_dtype, np.ndarray) if equivalencies == []: equivalencies = self._equivalencies new_array = self.unit.to(unit, array_view, equivalencies=equivalencies) return new_array.view(self.dtype).reshape(self.shape) if NUMPY_LT_1_12: def __repr__(self): # Use the numpy >=1.12 way to format structured arrays. from .representation import _array2string prefixstr = '<' + self.__class__.__name__ + ' ' arrstr = _array2string(self.view(np.ndarray), prefix=prefixstr) return '{0}{1}{2:s}>'.format(prefixstr, arrstr, self._unitstr) # need to do this here at the bottom to avoid circular dependencies from .sites import get_builtin_sites, get_downloaded_sites
686ce540769fad2b1a4d0964f1b44dbe442c3abbd1e33b6a04cb24c7c45c481c
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains the fundamental classes used for representing coordinates in astropy. """ import math from collections import namedtuple import numpy as np from . import angle_utilities as util from .. import units as u from ..utils import isiterable __all__ = ['Angle', 'Latitude', 'Longitude'] # these are used by the `hms` and `dms` attributes hms_tuple = namedtuple('hms_tuple', ('h', 'm', 's')) dms_tuple = namedtuple('dms_tuple', ('d', 'm', 's')) signed_dms_tuple = namedtuple('signed_dms_tuple', ('sign', 'd', 'm', 's')) class Angle(u.SpecificTypeQuantity): """ One or more angular value(s) with units equivalent to radians or degrees. An angle can be specified either as an array, scalar, tuple (see below), string, `~astropy.units.Quantity` or another :class:`~astropy.coordinates.Angle`. The input parser is flexible and supports a variety of formats:: Angle('10.2345d') Angle(['10.2345d', '-20d']) Angle('1:2:30.43 degrees') Angle('1 2 0 hours') Angle(np.arange(1, 8), unit=u.deg) Angle('1°2′3″') Angle('1d2m3.4s') Angle('-1h2m3s') Angle('-1h2.5m') Angle('-1:2.5', unit=u.deg) Angle((10, 11, 12), unit='hourangle') # (h, m, s) Angle((-1, 2, 3), unit=u.deg) # (d, m, s) Angle(10.2345 * u.deg) Angle(Angle(10.2345 * u.deg)) Parameters ---------- angle : `~numpy.array`, scalar, `~astropy.units.Quantity`, :class:`~astropy.coordinates.Angle` The angle value. If a tuple, will be interpreted as ``(h, m, s)`` or ``(d, m, s)`` depending on ``unit``. If a string, it will be interpreted following the rules described above. If ``angle`` is a sequence or array of strings, the resulting values will be in the given ``unit``, or if `None` is provided, the unit will be taken from the first given value. unit : `~astropy.units.UnitBase`, str, optional The unit of the value specified for the angle. This may be any string that `~astropy.units.Unit` understands, but it is better to give an actual unit object. Must be an angular unit. dtype : `~numpy.dtype`, optional See `~astropy.units.Quantity`. copy : bool, optional See `~astropy.units.Quantity`. Raises ------ `~astropy.units.UnitsError` If a unit is not provided or it is not an angular unit. """ _equivalent_unit = u.radian _include_easy_conversion_members = True def __new__(cls, angle, unit=None, dtype=None, copy=True): if not isinstance(angle, u.Quantity): if unit is not None: unit = cls._convert_unit_to_angle_unit(u.Unit(unit)) if isinstance(angle, tuple): angle = cls._tuple_to_float(angle, unit) elif isinstance(angle, str): angle, angle_unit = util.parse_angle(angle, unit) if angle_unit is None: angle_unit = unit if isinstance(angle, tuple): angle = cls._tuple_to_float(angle, angle_unit) if angle_unit is not unit: # Possible conversion to `unit` will be done below. angle = u.Quantity(angle, angle_unit, copy=False) elif (isiterable(angle) and not (isinstance(angle, np.ndarray) and angle.dtype.kind not in 'SUVO')): angle = [Angle(x, unit, copy=False) for x in angle] return super().__new__(cls, angle, unit, dtype=dtype, copy=copy) @staticmethod def _tuple_to_float(angle, unit): """ Converts an angle represented as a 3-tuple or 2-tuple into a floating point number in the given unit. """ # TODO: Numpy array of tuples? if unit == u.hourangle: return util.hms_to_hours(*angle) elif unit == u.degree: return util.dms_to_degrees(*angle) else: raise u.UnitsError("Can not parse '{0}' as unit '{1}'" .format(angle, unit)) @staticmethod def _convert_unit_to_angle_unit(unit): return u.hourangle if unit is u.hour else unit def _set_unit(self, unit): super()._set_unit(self._convert_unit_to_angle_unit(unit)) @property def hour(self): """ The angle's value in hours (read-only property). """ return self.hourangle @property def hms(self): """ The angle's value in hours, as a named tuple with ``(h, m, s)`` members. (This is a read-only property.) """ return hms_tuple(*util.hours_to_hms(self.hourangle)) @property def dms(self): """ The angle's value in degrees, as a named tuple with ``(d, m, s)`` members. (This is a read-only property.) """ return dms_tuple(*util.degrees_to_dms(self.degree)) @property def signed_dms(self): """ The angle's value in degrees, as a named tuple with ``(sign, d, m, s)`` members. The ``d``, ``m``, ``s`` are thus always positive, and the sign of the angle is given by ``sign``. (This is a read-only property.) This is primarily intended for use with `dms` to generate string representations of coordinates that are correct for negative angles. """ return signed_dms_tuple(np.sign(self.degree), *util.degrees_to_dms(np.abs(self.degree))) def to_string(self, unit=None, decimal=False, sep='fromunit', precision=None, alwayssign=False, pad=False, fields=3, format=None): """ A string representation of the angle. Parameters ---------- unit : `~astropy.units.UnitBase`, optional Specifies the unit. Must be an angular unit. If not provided, the unit used to initialize the angle will be used. decimal : bool, optional If `True`, a decimal representation will be used, otherwise the returned string will be in sexagesimal form. sep : str, optional The separator between numbers in a sexagesimal representation. E.g., if it is ':', the result is ``'12:41:11.1241'``. Also accepts 2 or 3 separators. E.g., ``sep='hms'`` would give the result ``'12h41m11.1241s'``, or sep='-:' would yield ``'11-21:17.124'``. Alternatively, the special string 'fromunit' means 'dms' if the unit is degrees, or 'hms' if the unit is hours. precision : int, optional The level of decimal precision. If ``decimal`` is `True`, this is the raw precision, otherwise it gives the precision of the last place of the sexagesimal representation (seconds). If `None`, or not provided, the number of decimal places is determined by the value, and will be between 0-8 decimal places as required. alwayssign : bool, optional If `True`, include the sign no matter what. If `False`, only include the sign if it is negative. pad : bool, optional If `True`, include leading zeros when needed to ensure a fixed number of characters for sexagesimal representation. fields : int, optional Specifies the number of fields to display when outputting sexagesimal notation. For example: - fields == 1: ``'5d'`` - fields == 2: ``'5d45m'`` - fields == 3: ``'5d45m32.5s'`` By default, all fields are displayed. format : str, optional The format of the result. If not provided, an unadorned string is returned. Supported values are: - 'latex': Return a LaTeX-formatted string - 'unicode': Return a string containing non-ASCII unicode characters, such as the degree symbol Returns ------- strrepr : str or array A string representation of the angle. If the angle is an array, this will be an array with a unicode dtype. """ if unit is None: unit = self.unit else: unit = self._convert_unit_to_angle_unit(u.Unit(unit)) separators = { None: { u.degree: 'dms', u.hourangle: 'hms'}, 'latex': { u.degree: [r'^\circ', r'{}^\prime', r'{}^{\prime\prime}'], u.hourangle: [r'^\mathrm{h}', r'^\mathrm{m}', r'^\mathrm{s}']}, 'unicode': { u.degree: '°′″', u.hourangle: 'ʰᵐˢ'} } if sep == 'fromunit': if format not in separators: raise ValueError("Unknown format '{0}'".format(format)) seps = separators[format] if unit in seps: sep = seps[unit] # Create an iterator so we can format each element of what # might be an array. if unit is u.degree: if decimal: values = self.degree if precision is not None: func = ("{0:0." + str(precision) + "f}").format else: func = '{0:g}'.format else: if sep == 'fromunit': sep = 'dms' values = self.degree func = lambda x: util.degrees_to_string( x, precision=precision, sep=sep, pad=pad, fields=fields) elif unit is u.hourangle: if decimal: values = self.hour if precision is not None: func = ("{0:0." + str(precision) + "f}").format else: func = '{0:g}'.format else: if sep == 'fromunit': sep = 'hms' values = self.hour func = lambda x: util.hours_to_string( x, precision=precision, sep=sep, pad=pad, fields=fields) elif unit.is_equivalent(u.radian): if decimal: values = self.to_value(unit) if precision is not None: func = ("{0:1." + str(precision) + "f}").format else: func = "{0:g}".format elif sep == 'fromunit': values = self.to_value(unit) unit_string = unit.to_string(format=format) if format == 'latex': unit_string = unit_string[1:-1] if precision is not None: def plain_unit_format(val): return ("{0:0." + str(precision) + "f}{1}").format( val, unit_string) func = plain_unit_format else: def plain_unit_format(val): return "{0:g}{1}".format(val, unit_string) func = plain_unit_format else: raise ValueError( "'{0}' can not be represented in sexagesimal " "notation".format( unit.name)) else: raise u.UnitsError( "The unit value provided is not an angular unit.") def do_format(val): s = func(float(val)) if alwayssign and not s.startswith('-'): s = '+' + s if format == 'latex': s = '${0}$'.format(s) return s format_ufunc = np.vectorize(do_format, otypes=['U']) result = format_ufunc(values) if result.ndim == 0: result = result[()] return result def wrap_at(self, wrap_angle, inplace=False): """ Wrap the `Angle` object at the given ``wrap_angle``. This method forces all the angle values to be within a contiguous 360 degree range so that ``wrap_angle - 360d <= angle < wrap_angle``. By default a new Angle object is returned, but if the ``inplace`` argument is `True` then the `Angle` object is wrapped in place and nothing is returned. For instance:: >>> from astropy.coordinates import Angle >>> import astropy.units as u >>> a = Angle([-20.0, 150.0, 350.0] * u.deg) >>> a.wrap_at(360 * u.deg).degree # Wrap into range 0 to 360 degrees # doctest: +FLOAT_CMP array([340., 150., 350.]) >>> a.wrap_at('180d', inplace=True) # Wrap into range -180 to 180 degrees # doctest: +FLOAT_CMP >>> a.degree # doctest: +FLOAT_CMP array([-20., 150., -10.]) Parameters ---------- wrap_angle : str, `Angle`, angular `~astropy.units.Quantity` Specifies a single value for the wrap angle. This can be any object that can initialize an `Angle` object, e.g. ``'180d'``, ``180 * u.deg``, or ``Angle(180, unit=u.deg)``. inplace : bool If `True` then wrap the object in place instead of returning a new `Angle` Returns ------- out : Angle or `None` If ``inplace is False`` (default), return new `Angle` object with angles wrapped accordingly. Otherwise wrap in place and return `None`. """ wrap_angle = Angle(wrap_angle) # Convert to an Angle wrapped = np.mod(self - wrap_angle, 360.0 * u.deg) - (360.0 * u.deg - wrap_angle) if inplace: self[()] = wrapped else: return wrapped def is_within_bounds(self, lower=None, upper=None): """ Check if all angle(s) satisfy ``lower <= angle < upper`` If ``lower`` is not specified (or `None`) then no lower bounds check is performed. Likewise ``upper`` can be left unspecified. For example:: >>> from astropy.coordinates import Angle >>> import astropy.units as u >>> a = Angle([-20, 150, 350] * u.deg) >>> a.is_within_bounds('0d', '360d') False >>> a.is_within_bounds(None, '360d') True >>> a.is_within_bounds(-30 * u.deg, None) True Parameters ---------- lower : str, `Angle`, angular `~astropy.units.Quantity`, `None` Specifies lower bound for checking. This can be any object that can initialize an `Angle` object, e.g. ``'180d'``, ``180 * u.deg``, or ``Angle(180, unit=u.deg)``. upper : str, `Angle`, angular `~astropy.units.Quantity`, `None` Specifies upper bound for checking. This can be any object that can initialize an `Angle` object, e.g. ``'180d'``, ``180 * u.deg``, or ``Angle(180, unit=u.deg)``. Returns ------- is_within_bounds : bool `True` if all angles satisfy ``lower <= angle < upper`` """ ok = True if lower is not None: ok &= np.all(Angle(lower) <= self) if ok and upper is not None: ok &= np.all(self < Angle(upper)) return bool(ok) def __str__(self): if self.isscalar: return str(self.to_string()) else: return np.array2string(self, formatter={'all': lambda x: x.to_string()}) def _repr_latex_(self): if self.isscalar: return self.to_string(format='latex') else: # Need to do a magic incantation to convert to str. Regular str # or array2string causes all backslashes to get doubled. return np.array2string(self, formatter={'all': lambda x: x.to_string(format='latex')}) def _no_angle_subclass(obj): """Return any Angle subclass objects as an Angle objects. This is used to ensure that Latitute and Longitude change to Angle objects when they are used in calculations (such as lon/2.) """ if isinstance(obj, tuple): return tuple(_no_angle_subclass(_obj) for _obj in obj) return obj.view(Angle) if isinstance(obj, Angle) else obj class Latitude(Angle): """ Latitude-like angle(s) which must be in the range -90 to +90 deg. A Latitude object is distinguished from a pure :class:`~astropy.coordinates.Angle` by virtue of being constrained so that:: -90.0 * u.deg <= angle(s) <= +90.0 * u.deg Any attempt to set a value outside that range will result in a `ValueError`. The input angle(s) can be specified either as an array, list, scalar, tuple (see below), string, :class:`~astropy.units.Quantity` or another :class:`~astropy.coordinates.Angle`. The input parser is flexible and supports all of the input formats supported by :class:`~astropy.coordinates.Angle`. Parameters ---------- angle : array, list, scalar, `~astropy.units.Quantity`, `Angle`. The angle value(s). If a tuple, will be interpreted as ``(h, m, s)`` or ``(d, m, s)`` depending on ``unit``. If a string, it will be interpreted following the rules described for :class:`~astropy.coordinates.Angle`. If ``angle`` is a sequence or array of strings, the resulting values will be in the given ``unit``, or if `None` is provided, the unit will be taken from the first given value. unit : :class:`~astropy.units.UnitBase`, str, optional The unit of the value specified for the angle. This may be any string that `~astropy.units.Unit` understands, but it is better to give an actual unit object. Must be an angular unit. Raises ------ `~astropy.units.UnitsError` If a unit is not provided or it is not an angular unit. `TypeError` If the angle parameter is an instance of :class:`~astropy.coordinates.Longitude`. """ def __new__(cls, angle, unit=None, **kwargs): # Forbid creating a Lat from a Long. if isinstance(angle, Longitude): raise TypeError("A Latitude angle cannot be created from a Longitude angle") self = super().__new__(cls, angle, unit=unit, **kwargs) self._validate_angles() return self def _validate_angles(self, angles=None): """Check that angles are between -90 and 90 degrees. If not given, the check is done on the object itself""" # Convert the lower and upper bounds to the "native" unit of # this angle. This limits multiplication to two values, # rather than the N values in `self.value`. Also, the # comparison is performed on raw arrays, rather than Quantity # objects, for speed. if angles is None: angles = self lower = u.degree.to(angles.unit, -90.0) upper = u.degree.to(angles.unit, 90.0) if np.any(angles.value < lower) or np.any(angles.value > upper): raise ValueError('Latitude angle(s) must be within -90 deg <= angle <= 90 deg, ' 'got {0}'.format(angles.to(u.degree))) def __setitem__(self, item, value): # Forbid assigning a Long to a Lat. if isinstance(value, Longitude): raise TypeError("A Longitude angle cannot be assigned to a Latitude angle") # first check bounds self._validate_angles(value) super().__setitem__(item, value) # Any calculation should drop to Angle def __array_wrap__(self, obj, context=None): obj = super().__array_wrap__(obj, context=context) return _no_angle_subclass(obj) def __array_ufunc__(self, *args, **kwargs): results = super().__array_ufunc__(*args, **kwargs) return _no_angle_subclass(results) class LongitudeInfo(u.QuantityInfo): _represent_as_dict_attrs = u.QuantityInfo._represent_as_dict_attrs + ('wrap_angle',) class Longitude(Angle): """ Longitude-like angle(s) which are wrapped within a contiguous 360 degree range. A ``Longitude`` object is distinguished from a pure :class:`~astropy.coordinates.Angle` by virtue of a ``wrap_angle`` property. The ``wrap_angle`` specifies that all angle values represented by the object will be in the range:: wrap_angle - 360 * u.deg <= angle(s) < wrap_angle The default ``wrap_angle`` is 360 deg. Setting ``wrap_angle=180 * u.deg`` would instead result in values between -180 and +180 deg. Setting the ``wrap_angle`` attribute of an existing ``Longitude`` object will result in re-wrapping the angle values in-place. The input angle(s) can be specified either as an array, list, scalar, tuple, string, :class:`~astropy.units.Quantity` or another :class:`~astropy.coordinates.Angle`. The input parser is flexible and supports all of the input formats supported by :class:`~astropy.coordinates.Angle`. Parameters ---------- angle : array, list, scalar, `~astropy.units.Quantity`, :class:`~astropy.coordinates.Angle` The angle value(s). If a tuple, will be interpreted as ``(h, m s)`` or ``(d, m, s)`` depending on ``unit``. If a string, it will be interpreted following the rules described for :class:`~astropy.coordinates.Angle`. If ``angle`` is a sequence or array of strings, the resulting values will be in the given ``unit``, or if `None` is provided, the unit will be taken from the first given value. unit : :class:`~astropy.units.UnitBase`, str, optional The unit of the value specified for the angle. This may be any string that `~astropy.units.Unit` understands, but it is better to give an actual unit object. Must be an angular unit. wrap_angle : :class:`~astropy.coordinates.Angle` or equivalent, or None Angle at which to wrap back to ``wrap_angle - 360 deg``. If ``None`` (default), it will be taken to be 360 deg unless ``angle`` has a ``wrap_angle`` attribute already (i.e., is a ``Longitude``), in which case it will be taken from there. Raises ------ `~astropy.units.UnitsError` If a unit is not provided or it is not an angular unit. `TypeError` If the angle parameter is an instance of :class:`~astropy.coordinates.Latitude`. """ _wrap_angle = None _default_wrap_angle = Angle(360 * u.deg) info = LongitudeInfo() def __new__(cls, angle, unit=None, wrap_angle=None, **kwargs): # Forbid creating a Long from a Lat. if isinstance(angle, Latitude): raise TypeError("A Longitude angle cannot be created from " "a Latitude angle.") self = super().__new__(cls, angle, unit=unit, **kwargs) if wrap_angle is None: wrap_angle = getattr(angle, 'wrap_angle', self._default_wrap_angle) self.wrap_angle = wrap_angle return self def __setitem__(self, item, value): # Forbid assigning a Lat to a Long. if isinstance(value, Latitude): raise TypeError("A Latitude angle cannot be assigned to a Longitude angle") super().__setitem__(item, value) self._wrap_internal() def _wrap_internal(self): """ Wrap the internal values in the Longitude object. Using the :meth:`~astropy.coordinates.Angle.wrap_at` method causes recursion. """ # Convert the wrap angle and 360 degrees to the native unit of # this Angle, then do all the math on raw Numpy arrays rather # than Quantity objects for speed. a360 = u.degree.to(self.unit, 360.0) wrap_angle = self.wrap_angle.to_value(self.unit) wrap_angle_floor = wrap_angle - a360 self_angle = self.value # Do the wrapping, but only if any angles need to be wrapped if np.any(self_angle < wrap_angle_floor) or np.any(self_angle >= wrap_angle): wrapped = np.mod(self_angle - wrap_angle, a360) + wrap_angle_floor value = u.Quantity(wrapped, self.unit) super().__setitem__((), value) @property def wrap_angle(self): return self._wrap_angle @wrap_angle.setter def wrap_angle(self, value): self._wrap_angle = Angle(value) self._wrap_internal() def __array_finalize__(self, obj): super().__array_finalize__(obj) self._wrap_angle = getattr(obj, '_wrap_angle', self._default_wrap_angle) # Any calculation should drop to Angle def __array_wrap__(self, obj, context=None): obj = super().__array_wrap__(obj, context=context) return _no_angle_subclass(obj) def __array_ufunc__(self, *args, **kwargs): results = super().__array_ufunc__(*args, **kwargs) return _no_angle_subclass(results)
ea3763baa66f3ea363789f5390e0b219cd66e715b0744f58435d2bf82dfcdb24
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # Dependencies import numpy as np import warnings # Project from .. import units as u from ..utils.exceptions import AstropyDeprecationWarning from ..utils import OrderedDescriptor, ShapedLikeNDArray __all__ = ['Attribute', 'TimeAttribute', 'QuantityAttribute', 'EarthLocationAttribute', 'CoordinateAttribute', 'CartesianRepresentationAttribute', 'DifferentialAttribute'] class Attribute(OrderedDescriptor): """A non-mutable data descriptor to hold a frame attribute. This class must be used to define frame attributes (e.g. ``equinox`` or ``obstime``) that are included in a frame class definition. Examples -------- The `~astropy.coordinates.FK4` class uses the following class attributes:: class FK4(BaseCoordinateFrame): equinox = TimeAttribute(default=_EQUINOX_B1950) obstime = TimeAttribute(default=None, secondary_attribute='equinox') This means that ``equinox`` and ``obstime`` are available to be set as keyword arguments when creating an ``FK4`` class instance and are then accessible as instance attributes. The instance value for the attribute must be stored in ``'_' + <attribute_name>`` by the frame ``__init__`` method. Note in this example that ``equinox`` and ``obstime`` are time attributes and use the ``TimeAttributeFrame`` class. This subclass overrides the ``convert_input`` method to validate and convert inputs into a ``Time`` object. Parameters ---------- default : object Default value for the attribute if not provided secondary_attribute : str Name of a secondary instance attribute which supplies the value if ``default is None`` and no value was supplied during initialization. """ _class_attribute_ = 'frame_attributes' _name_attribute_ = 'name' name = '<unbound>' def __init__(self, default=None, secondary_attribute=''): self.default = default self.secondary_attribute = secondary_attribute super().__init__() def convert_input(self, value): """ Validate the input ``value`` and convert to expected attribute class. The base method here does nothing, but subclasses can implement this as needed. The method should catch any internal exceptions and raise ValueError with an informative message. The method returns the validated input along with a boolean that indicates whether the input value was actually converted. If the input value was already the correct type then the ``converted`` return value should be ``False``. Parameters ---------- value : object Input value to be converted. Returns ------- output_value The ``value`` converted to the correct type (or just ``value`` if ``converted`` is False) converted : bool True if the conversion was actually performed, False otherwise. Raises ------ ValueError If the input is not valid for this attribute. """ return value, False def __get__(self, instance, frame_cls=None): if instance is None: out = self.default else: out = getattr(instance, '_' + self.name, self.default) if out is None: out = getattr(instance, self.secondary_attribute, self.default) out, converted = self.convert_input(out) if instance is not None: instance_shape = getattr(instance, 'shape', None) if instance_shape is not None and (getattr(out, 'size', 1) > 1 and out.shape != instance_shape): # If the shapes do not match, try broadcasting. try: if isinstance(out, ShapedLikeNDArray): out = out._apply(np.broadcast_to, shape=instance_shape, subok=True) else: out = np.broadcast_to(out, instance_shape, subok=True) except ValueError: # raise more informative exception. raise ValueError( "attribute {0} should be scalar or have shape {1}, " "but is has shape {2} and could not be broadcast." .format(self.name, instance_shape, out.shape)) converted = True if converted: setattr(instance, '_' + self.name, out) return out def __set__(self, instance, val): raise AttributeError('Cannot set frame attribute') class TimeAttribute(Attribute): """ Frame attribute descriptor for quantities that are Time objects. See the `~astropy.coordinates.Attribute` API doc for further information. Parameters ---------- default : object Default value for the attribute if not provided secondary_attribute : str Name of a secondary instance attribute which supplies the value if ``default is None`` and no value was supplied during initialization. """ def convert_input(self, value): """ Convert input value to a Time object and validate by running through the Time constructor. Also check that the input was a scalar. Parameters ---------- value : object Input value to be converted. Returns ------- out, converted : correctly-typed object, boolean Tuple consisting of the correctly-typed object and a boolean which indicates if conversion was actually performed. Raises ------ ValueError If the input is not valid for this attribute. """ from ..time import Time if value is None: return None, False if isinstance(value, Time): out = value converted = False else: try: out = Time(value) except Exception as err: raise ValueError( 'Invalid time input {0}={1!r}\n{2}'.format(self.name, value, err)) converted = True # Set attribute as read-only for arrays (not allowed by numpy # for array scalars) if out.shape: out.writeable = False return out, converted class CartesianRepresentationAttribute(Attribute): """ A frame attribute that is a CartesianRepresentation with specified units. Parameters ---------- default : object Default value for the attribute if not provided secondary_attribute : str Name of a secondary instance attribute which supplies the value if ``default is None`` and no value was supplied during initialization. unit : unit object or None Name of a unit that the input will be converted into. If None, no unit-checking or conversion is performed """ def __init__(self, default=None, secondary_attribute='', unit=None): super().__init__(default, secondary_attribute) self.unit = unit def convert_input(self, value): """ Checks that the input is a CartesianRepresentation with the correct unit, or the special value ``[0, 0, 0]``. Parameters ---------- value : object Input value to be converted. Returns ------- out, converted : correctly-typed object, boolean Tuple consisting of the correctly-typed object and a boolean which indicates if conversion was actually performed. Raises ------ ValueError If the input is not valid for this attribute. """ if (isinstance(value, list) and len(value) == 3 and all(v == 0 for v in value) and self.unit is not None): return CartesianRepresentation(np.zeros(3) * self.unit), True else: # is it a CartesianRepresentation with correct unit? if hasattr(value, 'xyz') and value.xyz.unit == self.unit: return value, False converted = True # if it's a CartesianRepresentation, get the xyz Quantity value = getattr(value, 'xyz', value) if not hasattr(value, 'unit'): raise TypeError('tried to set a {0} with something that does ' 'not have a unit.' .format(self.__class__.__name__)) value = value.to(self.unit) # now try and make a CartesianRepresentation. cartrep = CartesianRepresentation(value, copy=False) return cartrep, converted class QuantityAttribute(Attribute): """ A frame attribute that is a quantity with specified units and shape (optionally). Parameters ---------- default : object Default value for the attribute if not provided secondary_attribute : str Name of a secondary instance attribute which supplies the value if ``default is None`` and no value was supplied during initialization. unit : unit object or None Name of a unit that the input will be converted into. If None, no unit-checking or conversion is performed shape : tuple or None If given, specifies the shape the attribute must be """ def __init__(self, default=None, secondary_attribute='', unit=None, shape=None): super().__init__(default, secondary_attribute) self.unit = unit self.shape = shape def convert_input(self, value): """ Checks that the input is a Quantity with the necessary units (or the special value ``0``). Parameters ---------- value : object Input value to be converted. Returns ------- out, converted : correctly-typed object, boolean Tuple consisting of the correctly-typed object and a boolean which indicates if conversion was actually performed. Raises ------ ValueError If the input is not valid for this attribute. """ if np.all(value == 0) and self.unit is not None: return u.Quantity(np.zeros(self.shape), self.unit), True else: if not hasattr(value, 'unit'): raise TypeError('Tried to set a QuantityAttribute with ' 'something that does not have a unit.') oldvalue = value value = u.Quantity(oldvalue, self.unit, copy=False) if self.shape is not None and value.shape != self.shape: raise ValueError('The provided value has shape "{0}", but ' 'should have shape "{1}"'.format(value.shape, self.shape)) converted = oldvalue is not value return value, converted class EarthLocationAttribute(Attribute): """ A frame attribute that can act as a `~astropy.coordinates.EarthLocation`. It can be created as anything that can be transformed to the `~astropy.coordinates.ITRS` frame, but always presents as an `EarthLocation` when accessed after creation. Parameters ---------- default : object Default value for the attribute if not provided secondary_attribute : str Name of a secondary instance attribute which supplies the value if ``default is None`` and no value was supplied during initialization. """ def convert_input(self, value): """ Checks that the input is a Quantity with the necessary units (or the special value ``0``). Parameters ---------- value : object Input value to be converted. Returns ------- out, converted : correctly-typed object, boolean Tuple consisting of the correctly-typed object and a boolean which indicates if conversion was actually performed. Raises ------ ValueError If the input is not valid for this attribute. """ if value is None: return None, False elif isinstance(value, EarthLocation): return value, False else: # we have to do the import here because of some tricky circular deps from .builtin_frames import ITRS if not hasattr(value, 'transform_to'): raise ValueError('"{0}" was passed into an ' 'EarthLocationAttribute, but it does not have ' '"transform_to" method'.format(value)) itrsobj = value.transform_to(ITRS) return itrsobj.earth_location, True class CoordinateAttribute(Attribute): """ A frame attribute which is a coordinate object. It can be given as a low-level frame class *or* a `~astropy.coordinates.SkyCoord`, but will always be converted to the low-level frame class when accessed. Parameters ---------- frame : a coordinate frame class The type of frame this attribute can be default : object Default value for the attribute if not provided secondary_attribute : str Name of a secondary instance attribute which supplies the value if ``default is None`` and no value was supplied during initialization. """ def __init__(self, frame, default=None, secondary_attribute=''): self._frame = frame super().__init__(default, secondary_attribute) def convert_input(self, value): """ Checks that the input is a SkyCoord with the necessary units (or the special value ``None``). Parameters ---------- value : object Input value to be converted. Returns ------- out, converted : correctly-typed object, boolean Tuple consisting of the correctly-typed object and a boolean which indicates if conversion was actually performed. Raises ------ ValueError If the input is not valid for this attribute. """ if value is None: return None, False elif isinstance(value, self._frame): return value, False else: if not hasattr(value, 'transform_to'): raise ValueError('"{0}" was passed into a ' 'CoordinateAttribute, but it does not have ' '"transform_to" method'.format(value)) transformedobj = value.transform_to(self._frame) if hasattr(transformedobj, 'frame'): transformedobj = transformedobj.frame return transformedobj, True class DifferentialAttribute(Attribute): """A frame attribute which is a differential instance. The optional ``allowed_classes`` argument allows specifying a restricted set of valid differential classes to check the input against. Otherwise, any `~astropy.coordinates.BaseDifferential` subclass instance is valid. Parameters ---------- default : object Default value for the attribute if not provided allowed_classes : tuple, optional A list of allowed differential classes for this attribute to have. secondary_attribute : str Name of a secondary instance attribute which supplies the value if ``default is None`` and no value was supplied during initialization. """ def __init__(self, default=None, allowed_classes=None, secondary_attribute=''): if allowed_classes is not None: self.allowed_classes = tuple(allowed_classes) else: self.allowed_classes = BaseDifferential super().__init__(default, secondary_attribute) def convert_input(self, value): """ Checks that the input is a differential object and is one of the allowed class types. Parameters ---------- value : object Input value. Returns ------- out, converted : correctly-typed object, boolean Tuple consisting of the correctly-typed object and a boolean which indicates if conversion was actually performed. Raises ------ ValueError If the input is not valid for this attribute. """ if not isinstance(value, self.allowed_classes): raise TypeError('Tried to set a DifferentialAttribute with ' 'an unsupported Differential type {0}. Allowed ' 'classes are: {1}' .format(value.__class__, self.allowed_classes)) return value, True # Backwards-compatibility: these are the only classes that were previously # released in v1.3 class FrameAttribute(Attribute): def __init__(self, *args, **kwargs): warnings.warn("FrameAttribute has been renamed to Attribute.", AstropyDeprecationWarning) super().__init__(*args, **kwargs) class TimeFrameAttribute(TimeAttribute): def __init__(self, *args, **kwargs): warnings.warn("TimeFrameAttribute has been renamed to TimeAttribute.", AstropyDeprecationWarning) super().__init__(*args, **kwargs) class QuantityFrameAttribute(QuantityAttribute): def __init__(self, *args, **kwargs): warnings.warn("QuantityFrameAttribute has been renamed to " "QuantityAttribute.", AstropyDeprecationWarning) super().__init__(*args, **kwargs) class CartesianRepresentationFrameAttribute(CartesianRepresentationAttribute): def __init__(self, *args, **kwargs): warnings.warn("CartesianRepresentationFrameAttribute has been renamed " "to CartesianRepresentationAttribute.", AstropyDeprecationWarning) super().__init__(*args, **kwargs) # do this here to prevent a series of complicated circular imports from .earth import EarthLocation from .representation import CartesianRepresentation, BaseDifferential
ebb3001f081675aef04ce751a07b39b47c3b37829dfa22e3e6b8a3fdbb114c3d
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # Standard library import re import textwrap from datetime import datetime from xml.dom.minidom import parse from urllib.request import urlopen # Third-party from .. import time as atime from ..utils.console import color_print, _color_text from . import get_sun __all__ = [] class HumanError(ValueError): pass class CelestialError(ValueError): pass def get_sign(dt): """ """ if ((int(dt.month) == 12 and int(dt.day) >= 22)or(int(dt.month) == 1 and int(dt.day) <= 19)): zodiac_sign = "capricorn" elif ((int(dt.month) == 1 and int(dt.day) >= 20)or(int(dt.month) == 2 and int(dt.day) <= 17)): zodiac_sign = "aquarius" elif ((int(dt.month) == 2 and int(dt.day) >= 18)or(int(dt.month) == 3 and int(dt.day) <= 19)): zodiac_sign = "pisces" elif ((int(dt.month) == 3 and int(dt.day) >= 20)or(int(dt.month) == 4 and int(dt.day) <= 19)): zodiac_sign = "aries" elif ((int(dt.month) == 4 and int(dt.day) >= 20)or(int(dt.month) == 5 and int(dt.day) <= 20)): zodiac_sign = "taurus" elif ((int(dt.month) == 5 and int(dt.day) >= 21)or(int(dt.month) == 6 and int(dt.day) <= 20)): zodiac_sign = "gemini" elif ((int(dt.month) == 6 and int(dt.day) >= 21)or(int(dt.month) == 7 and int(dt.day) <= 22)): zodiac_sign = "cancer" elif ((int(dt.month) == 7 and int(dt.day) >= 23)or(int(dt.month) == 8 and int(dt.day) <= 22)): zodiac_sign = "leo" elif ((int(dt.month) == 8 and int(dt.day) >= 23)or(int(dt.month) == 9 and int(dt.day) <= 22)): zodiac_sign = "virgo" elif ((int(dt.month) == 9 and int(dt.day) >= 23)or(int(dt.month) == 10 and int(dt.day) <= 22)): zodiac_sign = "libra" elif ((int(dt.month) == 10 and int(dt.day) >= 23)or(int(dt.month) == 11 and int(dt.day) <= 21)): zodiac_sign = "scorpio" elif ((int(dt.month) == 11 and int(dt.day) >= 22)or(int(dt.month) == 12 and int(dt.day) <= 21)): zodiac_sign = "sagittarius" return zodiac_sign _VALID_SIGNS = ["capricorn", "aquarius", "pisces", "aries", "taurus", "gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius"] # Some of the constellation names map to different astrological "sign names". # Astrologers really needs to talk to the IAU... _CONST_TO_SIGNS = {'capricornus': 'capricorn', 'scorpius': 'scorpio'} def horoscope(birthday, corrected=True): """ Enter your birthday as an `astropy.time.Time` object and receive a mystical horoscope about things to come. Parameter --------- birthday : `astropy.time.Time` Your birthday as a `datetime.datetime` or `astropy.time.Time` object. corrected : bool Whether to account for the precession of the Earth instead of using the ancient Greek dates for the signs. After all, you do want your *real* horoscope, not a cheap inaccurate approximation, right? Returns ------- Infinite wisdom, condensed into astrologically precise prose. Notes ----- This function was implemented on April 1. Take note of that date. """ special_words = { '([sS]tar[s^ ]*)': 'yellow', '([yY]ou[^ ]*)': 'magenta', '([pP]lay[^ ]*)': 'blue', '([hH]eart)': 'red', '([fF]ate)': 'lightgreen', } birthday = atime.Time(birthday) today = datetime.now() if corrected: zodiac_sign = get_sun(birthday).get_constellation().lower() zodiac_sign = _CONST_TO_SIGNS.get(zodiac_sign, zodiac_sign) if zodiac_sign not in _VALID_SIGNS: raise HumanError('On your birthday the sun was in {}, which is not ' 'a sign of the zodiac. You must not exist. Or ' 'maybe you can settle for ' 'corrected=False.'.format(zodiac_sign.title())) else: zodiac_sign = get_sign(birthday.to_datetime()) url = "http://www.findyourfate.com/rss/dailyhoroscope-feed.php?sign={sign}&id=45" f = urlopen(url.format(sign=zodiac_sign.capitalize())) try: # urlopen in py2 is not a decorator doc = parse(f) item = doc.getElementsByTagName('item')[0] desc = item.getElementsByTagName('description')[0].childNodes[0].nodeValue except Exception: raise CelestialError("Invalid response from celestial gods (failed to load horoscope).") finally: f.close() print("*"*79) color_print("Horoscope for {} on {}:".format(zodiac_sign.capitalize(), today.strftime("%Y-%m-%d")), 'green') print("*"*79) for block in textwrap.wrap(desc, 79): split_block = block.split() for i, word in enumerate(split_block): for re_word in special_words.keys(): match = re.search(re_word, word) if match is None: continue split_block[i] = _color_text(match.groups()[0], special_words[re_word]) print(" ".join(split_block)) def inject_horoscope(): import astropy astropy._yourfuture = horoscope inject_horoscope()
31e08749c83acd528b0774e877277ff0f157efc03be09a216ab606b230565a29
# 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 = 'DA395940D76FFEB6A68EA2DB16FC015D' _lr_action_items = {'UINT':([0,2,10,12,19,20,22,23,35,36,38,],[-7,12,-6,19,25,27,29,32,25,25,25,]),'MINUTE':([4,6,8,12,13,19,21,24,25,26,27,28,29,31,32,34,40,],[16,-14,-15,-17,-16,-9,-12,-8,-9,-13,-9,-10,36,37,38,39,-11,]),'COLON':([12,27,],[20,35,]),'$end':([1,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,21,22,23,24,25,26,27,28,29,30,31,32,33,34,36,37,38,39,40,41,42,43,44,],[-4,-1,-32,-5,-14,-2,-15,-3,0,-17,-16,-33,-31,-35,-24,-34,-9,-12,-25,-18,-8,-9,-13,-9,-10,-9,-26,-8,-9,-19,-8,-27,-28,-20,-21,-11,-29,-22,-30,-23,]),'SIMPLE_UNIT':([4,6,8,12,13,19,21,24,25,26,27,28,40,],[14,-14,-15,-17,-16,-9,-12,-8,-9,-13,-9,-10,-11,]),'DEGREE':([4,6,8,12,13,19,21,24,25,26,27,28,40,],[15,-14,-15,22,-16,-9,-12,-8,-9,-13,-9,-10,-11,]),'UFLOAT':([0,2,10,12,19,20,22,23,35,36,38,],[-7,13,-6,24,24,24,31,34,24,24,24,]),'HOUR':([4,6,8,12,13,19,21,24,25,26,27,28,40,],[17,-14,-15,23,-16,-9,-12,-8,-9,-13,-9,-10,-11,]),'SECOND':([4,6,8,12,13,19,21,24,25,26,27,28,40,41,42,],[18,-14,-15,-17,-16,-9,-12,-8,-9,-13,-9,-10,-11,43,44,]),'SIGN':([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 = {'ufloat':([12,19,20,22,23,35,36,38,],[21,26,28,30,33,40,41,42,]),'generic':([0,],[4,]),'arcminute':([0,],[1,]),'simple':([0,],[5,]),'sign':([0,],[2,]),'colon':([0,],[6,]),'dms':([0,],[7,]),'hms':([0,],[3,]),'spaced':([0,],[8,]),'angle':([0,],[11,]),'arcsecond':([0,],[9,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> angle","S'",1,None,None,None), ('angle -> hms','angle',1,'p_angle','angle_utilities.py',134), ('angle -> dms','angle',1,'p_angle','angle_utilities.py',135), ('angle -> arcsecond','angle',1,'p_angle','angle_utilities.py',136), ('angle -> arcminute','angle',1,'p_angle','angle_utilities.py',137), ('angle -> simple','angle',1,'p_angle','angle_utilities.py',138), ('sign -> SIGN','sign',1,'p_sign','angle_utilities.py',144), ('sign -> <empty>','sign',0,'p_sign','angle_utilities.py',145), ('ufloat -> UFLOAT','ufloat',1,'p_ufloat','angle_utilities.py',154), ('ufloat -> UINT','ufloat',1,'p_ufloat','angle_utilities.py',155), ('colon -> sign UINT COLON ufloat','colon',4,'p_colon','angle_utilities.py',161), ('colon -> sign UINT COLON UINT COLON ufloat','colon',6,'p_colon','angle_utilities.py',162), ('spaced -> sign UINT ufloat','spaced',3,'p_spaced','angle_utilities.py',171), ('spaced -> sign UINT UINT ufloat','spaced',4,'p_spaced','angle_utilities.py',172), ('generic -> colon','generic',1,'p_generic','angle_utilities.py',181), ('generic -> spaced','generic',1,'p_generic','angle_utilities.py',182), ('generic -> sign UFLOAT','generic',2,'p_generic','angle_utilities.py',183), ('generic -> sign UINT','generic',2,'p_generic','angle_utilities.py',184), ('hms -> sign UINT HOUR','hms',3,'p_hms','angle_utilities.py',193), ('hms -> sign UINT HOUR ufloat','hms',4,'p_hms','angle_utilities.py',194), ('hms -> sign UINT HOUR UINT MINUTE','hms',5,'p_hms','angle_utilities.py',195), ('hms -> sign UINT HOUR UFLOAT MINUTE','hms',5,'p_hms','angle_utilities.py',196), ('hms -> sign UINT HOUR UINT MINUTE ufloat','hms',6,'p_hms','angle_utilities.py',197), ('hms -> sign UINT HOUR UINT MINUTE ufloat SECOND','hms',7,'p_hms','angle_utilities.py',198), ('hms -> generic HOUR','hms',2,'p_hms','angle_utilities.py',199), ('dms -> sign UINT DEGREE','dms',3,'p_dms','angle_utilities.py',212), ('dms -> sign UINT DEGREE ufloat','dms',4,'p_dms','angle_utilities.py',213), ('dms -> sign UINT DEGREE UINT MINUTE','dms',5,'p_dms','angle_utilities.py',214), ('dms -> sign UINT DEGREE UFLOAT MINUTE','dms',5,'p_dms','angle_utilities.py',215), ('dms -> sign UINT DEGREE UINT MINUTE ufloat','dms',6,'p_dms','angle_utilities.py',216), ('dms -> sign UINT DEGREE UINT MINUTE ufloat SECOND','dms',7,'p_dms','angle_utilities.py',217), ('dms -> generic DEGREE','dms',2,'p_dms','angle_utilities.py',218), ('simple -> generic','simple',1,'p_simple','angle_utilities.py',231), ('simple -> generic SIMPLE_UNIT','simple',2,'p_simple','angle_utilities.py',232), ('arcsecond -> generic SECOND','arcsecond',2,'p_arcsecond','angle_utilities.py',241), ('arcminute -> generic MINUTE','arcminute',2,'p_arcminute','angle_utilities.py',247), ]
4df7ad700321b972abef569f9d60b3dc0c29bbcf946c8c719f2f0d00ae158731
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains standard functions for earth orientation, such as precession and nutation. This module is (currently) not intended to be part of the public API, but is instead primarily for internal use in `coordinates` """ import numpy as np from ..time import Time from .. import units as u from .matrix_utilities import rotation_matrix, matrix_product, matrix_transpose jd1950 = Time('B1950', scale='tai').jd jd2000 = Time('J2000', scale='utc').jd _asecperrad = u.radian.to(u.arcsec) def eccentricity(jd): """ Eccentricity of the Earth's orbit at the requested Julian Date. Parameters ---------- jd : scalar or array-like Julian date at which to compute the eccentricity returns ------- eccentricity : scalar or array The eccentricity (or array of eccentricities) References ---------- * Explanatory Supplement to the Astronomical Almanac: P. Kenneth Seidelmann (ed), University Science Books (1992). """ T = (jd - jd1950) / 36525.0 p = (-0.000000126, - 0.00004193, 0.01673011) return np.polyval(p, T) def mean_lon_of_perigee(jd): """ Computes the mean longitude of perigee of the Earth's orbit at the requested Julian Date. Parameters ---------- jd : scalar or array-like Julian date at which to compute the mean longitude of perigee returns ------- mean_lon_of_perigee : scalar or array Mean longitude of perigee in degrees (or array of mean longitudes) References ---------- * Explanatory Supplement to the Astronomical Almanac: P. Kenneth Seidelmann (ed), University Science Books (1992). """ T = (jd - jd1950) / 36525.0 p = (0.012, 1.65, 6190.67, 1015489.951) return np.polyval(p, T) / 3600. def obliquity(jd, algorithm=2006): """ Computes the obliquity of the Earth at the requested Julian Date. Parameters ---------- jd : scalar or array-like Julian date at which to compute the obliquity algorithm : int Year of algorithm based on IAU adoption. Can be 2006, 2000 or 1980. The 2006 algorithm is mentioned in Circular 179, but the canonical reference for the IAU adoption is apparently Hilton et al. 06 is composed of the 1980 algorithm with a precession-rate correction due to the 2000 precession models, and a description of the 1980 algorithm can be found in the Explanatory Supplement to the Astronomical Almanac. returns ------- obliquity : scalar or array Mean obliquity in degrees (or array of obliquities) References ---------- * Hilton, J. et al., 2006, Celest.Mech.Dyn.Astron. 94, 351. 2000 * USNO Circular 179 * Explanatory Supplement to the Astronomical Almanac: P. Kenneth Seidelmann (ed), University Science Books (1992). """ T = (jd - jd2000) / 36525.0 if algorithm == 2006: p = (-0.0000000434, -0.000000576, 0.00200340, -0.0001831, -46.836769, 84381.406) corr = 0 elif algorithm == 2000: p = (0.001813, -0.00059, -46.8150, 84381.448) corr = -0.02524 * T elif algorithm == 1980: p = (0.001813, -0.00059, -46.8150, 84381.448) corr = 0 else: raise ValueError('invalid algorithm year for computing obliquity') return (np.polyval(p, T) + corr) / 3600. # TODO: replace this with SOFA equivalent def precession_matrix_Capitaine(fromepoch, toepoch): """ Computes the precession matrix from one Julian epoch to another. The exact method is based on Capitaine et al. 2003, which should match the IAU 2006 standard. Parameters ---------- fromepoch : `~astropy.time.Time` The epoch to precess from. toepoch : `~astropy.time.Time` The epoch to precess to. Returns ------- pmatrix : 3x3 array Precession matrix to get from ``fromepoch`` to ``toepoch`` References ---------- USNO Circular 179 """ mat_fromto2000 = matrix_transpose( _precess_from_J2000_Capitaine(fromepoch.jyear)) mat_2000toto = _precess_from_J2000_Capitaine(toepoch.jyear) return np.dot(mat_2000toto, mat_fromto2000) def _precess_from_J2000_Capitaine(epoch): """ Computes the precession matrix from J2000 to the given Julian Epoch. Expression from from Capitaine et al. 2003 as expressed in the USNO Circular 179. This should match the IAU 2006 standard from SOFA. Parameters ---------- epoch : scalar The epoch as a Julian year number (e.g. J2000 is 2000.0) """ T = (epoch - 2000.0) / 100.0 # from USNO circular pzeta = (-0.0000003173, -0.000005971, 0.01801828, 0.2988499, 2306.083227, 2.650545) pz = (-0.0000002904, -0.000028596, 0.01826837, 1.0927348, 2306.077181, -2.650545) ptheta = (-0.0000001274, -0.000007089, -0.04182264, -0.4294934, 2004.191903, 0) zeta = np.polyval(pzeta, T) / 3600.0 z = np.polyval(pz, T) / 3600.0 theta = np.polyval(ptheta, T) / 3600.0 return matrix_product(rotation_matrix(-z, 'z'), rotation_matrix(theta, 'y'), rotation_matrix(-zeta, 'z')) def _precession_matrix_besselian(epoch1, epoch2): """ Computes the precession matrix from one Besselian epoch to another using Newcomb's method. ``epoch1`` and ``epoch2`` are in Besselian year numbers. """ # tropical years t1 = (epoch1 - 1850.0) / 1000.0 t2 = (epoch2 - 1850.0) / 1000.0 dt = t2 - t1 zeta1 = 23035.545 + t1 * 139.720 + 0.060 * t1 * t1 zeta2 = 30.240 - 0.27 * t1 zeta3 = 17.995 pzeta = (zeta3, zeta2, zeta1, 0) zeta = np.polyval(pzeta, dt) / 3600 z1 = 23035.545 + t1 * 139.720 + 0.060 * t1 * t1 z2 = 109.480 + 0.39 * t1 z3 = 18.325 pz = (z3, z2, z1, 0) z = np.polyval(pz, dt) / 3600 theta1 = 20051.12 - 85.29 * t1 - 0.37 * t1 * t1 theta2 = -42.65 - 0.37 * t1 theta3 = -41.8 ptheta = (theta3, theta2, theta1, 0) theta = np.polyval(ptheta, dt) / 3600 return matrix_product(rotation_matrix(-z, 'z'), rotation_matrix(theta, 'y'), rotation_matrix(-zeta, 'z')) def _load_nutation_data(datastr, seriestype): """ Loads nutation series from data stored in string form. Seriestype can be 'lunisolar' or 'planetary' """ if seriestype == 'lunisolar': dtypes = [('nl', int), ('nlp', int), ('nF', int), ('nD', int), ('nOm', int), ('ps', float), ('pst', float), ('pc', float), ('ec', float), ('ect', float), ('es', float)] elif seriestype == 'planetary': dtypes = [('nl', int), ('nF', int), ('nD', int), ('nOm', int), ('nme', int), ('nve', int), ('nea', int), ('nma', int), ('nju', int), ('nsa', int), ('nur', int), ('nne', int), ('npa', int), ('sp', int), ('cp', int), ('se', int), ('ce', int)] else: raise ValueError('requested invalid nutation series type') lines = [l for l in datastr.split('\n') if not l.startswith('#') if not l.strip() == ''] lists = [[] for _ in dtypes] for l in lines: for i, e in enumerate(l.split(' ')): lists[i].append(dtypes[i][1](e)) return np.rec.fromarrays(lists, names=[e[0] for e in dtypes]) _nut_data_00b = """ #l lprime F D Omega longitude_sin longitude_sin*t longitude_cos obliquity_cos obliquity_cos*t,obliquity_sin 0 0 0 0 1 -172064161.0 -174666.0 33386.0 92052331.0 9086.0 15377.0 0 0 2 -2 2 -13170906.0 -1675.0 -13696.0 5730336.0 -3015.0 -4587.0 0 0 2 0 2 -2276413.0 -234.0 2796.0 978459.0 -485.0 1374.0 0 0 0 0 2 2074554.0 207.0 -698.0 -897492.0 470.0 -291.0 0 1 0 0 0 1475877.0 -3633.0 11817.0 73871.0 -184.0 -1924.0 0 1 2 -2 2 -516821.0 1226.0 -524.0 224386.0 -677.0 -174.0 1 0 0 0 0 711159.0 73.0 -872.0 -6750.0 0.0 358.0 0 0 2 0 1 -387298.0 -367.0 380.0 200728.0 18.0 318.0 1 0 2 0 2 -301461.0 -36.0 816.0 129025.0 -63.0 367.0 0 -1 2 -2 2 215829.0 -494.0 111.0 -95929.0 299.0 132.0 0 0 2 -2 1 128227.0 137.0 181.0 -68982.0 -9.0 39.0 -1 0 2 0 2 123457.0 11.0 19.0 -53311.0 32.0 -4.0 -1 0 0 2 0 156994.0 10.0 -168.0 -1235.0 0.0 82.0 1 0 0 0 1 63110.0 63.0 27.0 -33228.0 0.0 -9.0 -1 0 0 0 1 -57976.0 -63.0 -189.0 31429.0 0.0 -75.0 -1 0 2 2 2 -59641.0 -11.0 149.0 25543.0 -11.0 66.0 1 0 2 0 1 -51613.0 -42.0 129.0 26366.0 0.0 78.0 -2 0 2 0 1 45893.0 50.0 31.0 -24236.0 -10.0 20.0 0 0 0 2 0 63384.0 11.0 -150.0 -1220.0 0.0 29.0 0 0 2 2 2 -38571.0 -1.0 158.0 16452.0 -11.0 68.0 0 -2 2 -2 2 32481.0 0.0 0.0 -13870.0 0.0 0.0 -2 0 0 2 0 -47722.0 0.0 -18.0 477.0 0.0 -25.0 2 0 2 0 2 -31046.0 -1.0 131.0 13238.0 -11.0 59.0 1 0 2 -2 2 28593.0 0.0 -1.0 -12338.0 10.0 -3.0 -1 0 2 0 1 20441.0 21.0 10.0 -10758.0 0.0 -3.0 2 0 0 0 0 29243.0 0.0 -74.0 -609.0 0.0 13.0 0 0 2 0 0 25887.0 0.0 -66.0 -550.0 0.0 11.0 0 1 0 0 1 -14053.0 -25.0 79.0 8551.0 -2.0 -45.0 -1 0 0 2 1 15164.0 10.0 11.0 -8001.0 0.0 -1.0 0 2 2 -2 2 -15794.0 72.0 -16.0 6850.0 -42.0 -5.0 0 0 -2 2 0 21783.0 0.0 13.0 -167.0 0.0 13.0 1 0 0 -2 1 -12873.0 -10.0 -37.0 6953.0 0.0 -14.0 0 -1 0 0 1 -12654.0 11.0 63.0 6415.0 0.0 26.0 -1 0 2 2 1 -10204.0 0.0 25.0 5222.0 0.0 15.0 0 2 0 0 0 16707.0 -85.0 -10.0 168.0 -1.0 10.0 1 0 2 2 2 -7691.0 0.0 44.0 3268.0 0.0 19.0 -2 0 2 0 0 -11024.0 0.0 -14.0 104.0 0.0 2.0 0 1 2 0 2 7566.0 -21.0 -11.0 -3250.0 0.0 -5.0 0 0 2 2 1 -6637.0 -11.0 25.0 3353.0 0.0 14.0 0 -1 2 0 2 -7141.0 21.0 8.0 3070.0 0.0 4.0 0 0 0 2 1 -6302.0 -11.0 2.0 3272.0 0.0 4.0 1 0 2 -2 1 5800.0 10.0 2.0 -3045.0 0.0 -1.0 2 0 2 -2 2 6443.0 0.0 -7.0 -2768.0 0.0 -4.0 -2 0 0 2 1 -5774.0 -11.0 -15.0 3041.0 0.0 -5.0 2 0 2 0 1 -5350.0 0.0 21.0 2695.0 0.0 12.0 0 -1 2 -2 1 -4752.0 -11.0 -3.0 2719.0 0.0 -3.0 0 0 0 -2 1 -4940.0 -11.0 -21.0 2720.0 0.0 -9.0 -1 -1 0 2 0 7350.0 0.0 -8.0 -51.0 0.0 4.0 2 0 0 -2 1 4065.0 0.0 6.0 -2206.0 0.0 1.0 1 0 0 2 0 6579.0 0.0 -24.0 -199.0 0.0 2.0 0 1 2 -2 1 3579.0 0.0 5.0 -1900.0 0.0 1.0 1 -1 0 0 0 4725.0 0.0 -6.0 -41.0 0.0 3.0 -2 0 2 0 2 -3075.0 0.0 -2.0 1313.0 0.0 -1.0 3 0 2 0 2 -2904.0 0.0 15.0 1233.0 0.0 7.0 0 -1 0 2 0 4348.0 0.0 -10.0 -81.0 0.0 2.0 1 -1 2 0 2 -2878.0 0.0 8.0 1232.0 0.0 4.0 0 0 0 1 0 -4230.0 0.0 5.0 -20.0 0.0 -2.0 -1 -1 2 2 2 -2819.0 0.0 7.0 1207.0 0.0 3.0 -1 0 2 0 0 -4056.0 0.0 5.0 40.0 0.0 -2.0 0 -1 2 2 2 -2647.0 0.0 11.0 1129.0 0.0 5.0 -2 0 0 0 1 -2294.0 0.0 -10.0 1266.0 0.0 -4.0 1 1 2 0 2 2481.0 0.0 -7.0 -1062.0 0.0 -3.0 2 0 0 0 1 2179.0 0.0 -2.0 -1129.0 0.0 -2.0 -1 1 0 1 0 3276.0 0.0 1.0 -9.0 0.0 0.0 1 1 0 0 0 -3389.0 0.0 5.0 35.0 0.0 -2.0 1 0 2 0 0 3339.0 0.0 -13.0 -107.0 0.0 1.0 -1 0 2 -2 1 -1987.0 0.0 -6.0 1073.0 0.0 -2.0 1 0 0 0 2 -1981.0 0.0 0.0 854.0 0.0 0.0 -1 0 0 1 0 4026.0 0.0 -353.0 -553.0 0.0 -139.0 0 0 2 1 2 1660.0 0.0 -5.0 -710.0 0.0 -2.0 -1 0 2 4 2 -1521.0 0.0 9.0 647.0 0.0 4.0 -1 1 0 1 1 1314.0 0.0 0.0 -700.0 0.0 0.0 0 -2 2 -2 1 -1283.0 0.0 0.0 672.0 0.0 0.0 1 0 2 2 1 -1331.0 0.0 8.0 663.0 0.0 4.0 -2 0 2 2 2 1383.0 0.0 -2.0 -594.0 0.0 -2.0 -1 0 0 0 2 1405.0 0.0 4.0 -610.0 0.0 2.0 1 1 2 -2 2 1290.0 0.0 0.0 -556.0 0.0 0.0 """[1:-1] _nut_data_00b = _load_nutation_data(_nut_data_00b, 'lunisolar') # TODO: replace w/SOFA equivalent def nutation_components2000B(jd): """ Computes nutation components following the IAU 2000B specification Parameters ---------- jd : scalar epoch at which to compute the nutation components as a JD Returns ------- eps : float epsilon in radians dpsi : float dpsi in radians deps : float depsilon in raidans """ epsa = np.radians(obliquity(jd, 2000)) t = (jd - jd2000) / 36525 # Fundamental (Delaunay) arguments from Simon et al. (1994) via SOFA # Mean anomaly of moon el = ((485868.249036 + 1717915923.2178 * t) % 1296000) / _asecperrad # Mean anomaly of sun elp = ((1287104.79305 + 129596581.0481 * t) % 1296000) / _asecperrad # Mean argument of the latitude of Moon F = ((335779.526232 + 1739527262.8478 * t) % 1296000) / _asecperrad # Mean elongation of the Moon from Sun D = ((1072260.70369 + 1602961601.2090 * t) % 1296000) / _asecperrad # Mean longitude of the ascending node of Moon Om = ((450160.398036 + -6962890.5431 * t) % 1296000) / _asecperrad # compute nutation series using array loaded from data directory dat = _nut_data_00b arg = dat.nl * el + dat.nlp * elp + dat.nF * F + dat.nD * D + dat.nOm * Om sarg = np.sin(arg) carg = np.cos(arg) p1u_asecperrad = _asecperrad * 1e7 # 0.1 microasrcsecperrad dpsils = np.sum((dat.ps + dat.pst * t) * sarg + dat.pc * carg) / p1u_asecperrad depsls = np.sum((dat.ec + dat.ect * t) * carg + dat.es * sarg) / p1u_asecperrad # fixed offset in place of planetary tersm m_asecperrad = _asecperrad * 1e3 # milliarcsec per rad dpsipl = -0.135 / m_asecperrad depspl = 0.388 / m_asecperrad return epsa, dpsils + dpsipl, depsls + depspl # all in radians def nutation_matrix(epoch): """ Nutation matrix generated from nutation components. Matrix converts from mean coordinate to true coordinate as r_true = M * r_mean """ # TODO: implement higher precision 2006/2000A model if requested/needed epsa, dpsi, deps = nutation_components2000B(epoch.jd) # all in radians return matrix_product(rotation_matrix(-(epsa + deps), 'x', False), rotation_matrix(-dpsi, 'z', False), rotation_matrix(epsa, 'x', False))
84a7e9c91a3eedcecd8a48690673cd4212459d94a6582cfc2004a3b23e367580
# Licensed under a 3-clause BSD style license - see LICENSE.rst import contextlib import pathlib import re import sys from collections import OrderedDict from operator import itemgetter import numpy as np __all__ = ['register_reader', 'register_writer', 'register_identifier', 'identify_format', 'get_reader', 'get_writer', 'read', 'write', 'get_formats', 'IORegistryError', 'delay_doc_updates'] __doctest_skip__ = ['register_identifier'] _readers = OrderedDict() _writers = OrderedDict() _identifiers = OrderedDict() PATH_TYPES = (str, pathlib.Path) class IORegistryError(Exception): """Custom error for registry clashes. """ pass # If multiple formats are added to one class the update of the docs is quite # expensive. Classes for which the doc update is temporarly delayed are added # to this set. _delayed_docs_classes = set() @contextlib.contextmanager def delay_doc_updates(cls): """Contextmanager to disable documentation updates when registering reader and writer. The documentation is only built once when the contextmanager exits. .. versionadded:: 1.3 Parameters ---------- cls : class Class for which the documentation updates should be delayed. Notes ----- Registering mutliple readers and writers can cause significant overhead because the documentation of the corresponding ``read`` and ``write`` methods are build every time. .. warning:: This contextmanager is experimental and may be replaced by a more general approach. Examples -------- see for example the source code of ``astropy.table.__init__``. """ _delayed_docs_classes.add(cls) yield _delayed_docs_classes.discard(cls) _update__doc__(cls, 'read') _update__doc__(cls, 'write') def get_formats(data_class=None, readwrite=None): """ Get the list of registered I/O formats as a Table. Parameters ---------- data_class : classobj, optional Filter readers/writer to match data class (default = all classes). readwrite : str or None, optional Search only for readers (``"Read"``) or writers (``"Write"``). If None search for both. Default is None. .. versionadded:: 1.3 Returns ------- format_table : Table Table of available I/O formats. """ from ..table import Table format_classes = sorted(set(_readers) | set(_writers), key=itemgetter(0)) rows = [] for format_class in format_classes: if (data_class is not None and not _is_best_match( data_class, format_class[1], format_classes)): continue has_read = 'Yes' if format_class in _readers else 'No' has_write = 'Yes' if format_class in _writers else 'No' has_identify = 'Yes' if format_class in _identifiers else 'No' # Check if this is a short name (e.g. 'rdb') which is deprecated in # favor of the full 'ascii.rdb'. ascii_format_class = ('ascii.' + format_class[0], format_class[1]) deprecated = 'Yes' if ascii_format_class in format_classes else '' rows.append((format_class[1].__name__, format_class[0], has_read, has_write, has_identify, deprecated)) if readwrite is not None: if readwrite == 'Read': rows = [row for row in rows if row[2] == 'Yes'] elif readwrite == 'Write': rows = [row for row in rows if row[3] == 'Yes'] else: raise ValueError('unrecognized value for "readwrite": {0}.\n' 'Allowed are "Read" and "Write" and None.') # Sorting the list of tuples is much faster than sorting it after the table # is created. (#5262) if rows: # Indices represent "Data Class", "Deprecated" and "Format". data = list(zip(*sorted(rows, key=itemgetter(0, 5, 1)))) else: data = None format_table = Table(data, names=('Data class', 'Format', 'Read', 'Write', 'Auto-identify', 'Deprecated')) if not np.any(format_table['Deprecated'] == 'Yes'): format_table.remove_column('Deprecated') return format_table def _update__doc__(data_class, readwrite): """ Update the docstring to include all the available readers / writers for the ``data_class.read`` or ``data_class.write`` functions (respectively). """ FORMATS_TEXT = 'The available built-in formats are:' # Get the existing read or write method and its docstring class_readwrite_func = getattr(data_class, readwrite) if not isinstance(class_readwrite_func.__doc__, str): # No docstring--could just be test code, or possibly code compiled # without docstrings return lines = class_readwrite_func.__doc__.splitlines() # Find the location of the existing formats table if it exists sep_indices = [ii for ii, line in enumerate(lines) if FORMATS_TEXT in line] if sep_indices: # Chop off the existing formats table, including the initial blank line chop_index = sep_indices[0] lines = lines[:chop_index] # Find the minimum indent, skipping the first line because it might be odd matches = [re.search(r'(\S)', line) for line in lines[1:]] left_indent = ' ' * min(match.start() for match in matches if match) # Get the available unified I/O formats for this class # Include only formats that have a reader, and drop the 'Data class' column format_table = get_formats(data_class, readwrite.capitalize()) format_table.remove_column('Data class') # Get the available formats as a table, then munge the output of pformat() # a bit and put it into the docstring. new_lines = format_table.pformat(max_lines=-1, max_width=80) table_rst_sep = re.sub('-', '=', new_lines[1]) new_lines[1] = table_rst_sep new_lines.insert(0, table_rst_sep) new_lines.append(table_rst_sep) # Check for deprecated names and include a warning at the end. if 'Deprecated' in format_table.colnames: new_lines.extend(['', 'Deprecated format names like ``aastex`` will be ' 'removed in a future version. Use the full ', 'name (e.g. ``ascii.aastex``) instead.']) new_lines = [FORMATS_TEXT, ''] + new_lines lines.extend([left_indent + line for line in new_lines]) # Depending on Python version and whether class_readwrite_func is # an instancemethod or classmethod, one of the following will work. try: class_readwrite_func.__doc__ = '\n'.join(lines) except AttributeError: class_readwrite_func.__func__.__doc__ = '\n'.join(lines) def register_reader(data_format, data_class, function, force=False): """ Register a reader function. Parameters ---------- data_format : str The data format identifier. This is the string that will be used to specify the data type when reading. data_class : classobj The class of the object that the reader produces. function : function The function to read in a data object. force : bool, optional Whether to override any existing function if already present. Default is ``False``. """ if not (data_format, data_class) in _readers or force: _readers[(data_format, data_class)] = function else: raise IORegistryError("Reader for format '{0}' and class '{1}' is " 'already defined' ''.format(data_format, data_class.__name__)) if data_class not in _delayed_docs_classes: _update__doc__(data_class, 'read') def unregister_reader(data_format, data_class): """ Unregister a reader function Parameters ---------- data_format : str The data format identifier. data_class : classobj The class of the object that the reader produces. """ if (data_format, data_class) in _readers: _readers.pop((data_format, data_class)) else: raise IORegistryError("No reader defined for format '{0}' and class '{1}'" ''.format(data_format, data_class.__name__)) if data_class not in _delayed_docs_classes: _update__doc__(data_class, 'read') def register_writer(data_format, data_class, function, force=False): """ Register a table writer function. Parameters ---------- data_format : str The data format identifier. This is the string that will be used to specify the data type when writing. data_class : classobj The class of the object that can be written. function : function The function to write out a data object. force : bool, optional Whether to override any existing function if already present. Default is ``False``. """ if not (data_format, data_class) in _writers or force: _writers[(data_format, data_class)] = function else: raise IORegistryError("Writer for format '{0}' and class '{1}' is " 'already defined' ''.format(data_format, data_class.__name__)) if data_class not in _delayed_docs_classes: _update__doc__(data_class, 'write') def unregister_writer(data_format, data_class): """ Unregister a writer function Parameters ---------- data_format : str The data format identifier. data_class : classobj The class of the object that can be written. """ if (data_format, data_class) in _writers: _writers.pop((data_format, data_class)) else: raise IORegistryError("No writer defined for format '{0}' and class '{1}'" ''.format(data_format, data_class.__name__)) if data_class not in _delayed_docs_classes: _update__doc__(data_class, 'write') def register_identifier(data_format, data_class, identifier, force=False): """ Associate an identifier function with a specific data type. Parameters ---------- data_format : str The data format identifier. This is the string that is used to specify the data type when reading/writing. data_class : classobj The class of the object that can be written. identifier : function A function that checks the argument specified to `read` or `write` to determine whether the input can be interpreted as a table of type ``data_format``. This function should take the following arguments: - ``origin``: A string ``"read"`` or ``"write"`` identifying whether the file is to be opened for reading or writing. - ``path``: The path to the file. - ``fileobj``: An open file object to read the file's contents, or `None` if the file could not be opened. - ``*args``: Positional arguments for the `read` or `write` function. - ``**kwargs``: Keyword arguments for the `read` or `write` function. One or both of ``path`` or ``fileobj`` may be `None`. If they are both `None`, the identifier will need to work from ``args[0]``. The function should return True if the input can be identified as being of format ``data_format``, and False otherwise. force : bool, optional Whether to override any existing function if already present. Default is ``False``. Examples -------- To set the identifier based on extensions, for formats that take a filename as a first argument, you can do for example:: >>> def my_identifier(*args, **kwargs): ... return isinstance(args[0], str) and args[0].endswith('.tbl') >>> register_identifier('ipac', Table, my_identifier) """ if not (data_format, data_class) in _identifiers or force: _identifiers[(data_format, data_class)] = identifier else: raise IORegistryError("Identifier for format '{0}' and class '{1}' is " 'already defined'.format(data_format, data_class.__name__)) def unregister_identifier(data_format, data_class): """ Unregister an identifier function Parameters ---------- data_format : str The data format identifier. data_class : classobj The class of the object that can be read/written. """ if (data_format, data_class) in _identifiers: _identifiers.pop((data_format, data_class)) else: raise IORegistryError("No identifier defined for format '{0}' and class" " '{1}'".format(data_format, data_class.__name__)) def identify_format(origin, data_class_required, path, fileobj, args, kwargs): """Loop through identifiers to see which formats match. Parameters ---------- origin : str A string ``"read`` or ``"write"`` identifying whether the file is to be opened for reading or writing. data_class_required : object The specified class for the result of `read` or the class that is to be written. path : str, other path object or None The path to the file or None. fileobj : File object or None. An open file object to read the file's contents, or ``None`` if the file could not be opened. args : sequence Positional arguments for the `read` or `write` function. Note that these must be provided as sequence. kwargs : dict-like Keyword arguments for the `read` or `write` function. Note that this parameter must be `dict`-like. Returns ------- valid_formats : list List of matching formats. """ valid_formats = [] for data_format, data_class in _identifiers: if _is_best_match(data_class_required, data_class, _identifiers): if _identifiers[(data_format, data_class)]( origin, path, fileobj, *args, **kwargs): valid_formats.append(data_format) return valid_formats def _get_format_table_str(data_class, readwrite): format_table = get_formats(data_class, readwrite=readwrite) format_table.remove_column('Data class') format_table_str = '\n'.join(format_table.pformat(max_lines=-1)) return format_table_str def get_reader(data_format, data_class): """Get reader for ``data_format``. Parameters ---------- data_format : str The data format identifier. This is the string that is used to specify the data type when reading/writing. data_class : classobj The class of the object that can be written. Returns ------- reader : callable The registered reader function for this format and class. """ readers = [(fmt, cls) for fmt, cls in _readers if fmt == data_format] for reader_format, reader_class in readers: if _is_best_match(data_class, reader_class, readers): return _readers[(reader_format, reader_class)] else: format_table_str = _get_format_table_str(data_class, 'Read') raise IORegistryError( "No reader defined for format '{0}' and class '{1}'.\nThe " "available formats are:\n{2}".format( data_format, data_class.__name__, format_table_str)) def get_writer(data_format, data_class): """Get writer for ``data_format``. Parameters ---------- data_format : str The data format identifier. This is the string that is used to specify the data type when reading/writing. data_class : classobj The class of the object that can be written. Returns ------- writer : callable The registered writer function for this format and class. """ writers = [(fmt, cls) for fmt, cls in _writers if fmt == data_format] for writer_format, writer_class in writers: if _is_best_match(data_class, writer_class, writers): return _writers[(writer_format, writer_class)] else: format_table_str = _get_format_table_str(data_class, 'Write') raise IORegistryError( "No writer defined for format '{0}' and class '{1}'.\nThe " "available formats are:\n{2}".format( data_format, data_class.__name__, format_table_str)) def read(cls, *args, format=None, **kwargs): """ Read in data. The arguments passed to this method depend on the format. """ ctx = None try: if format is None: path = None fileobj = None if len(args): if isinstance(args[0], PATH_TYPES): from ..utils.data import get_readable_fileobj # path might be a pathlib.Path object if isinstance(args[0], pathlib.Path): args = (str(args[0]),) + args[1:] path = args[0] try: ctx = get_readable_fileobj(args[0], encoding='binary') fileobj = ctx.__enter__() except OSError: raise except Exception: fileobj = None else: args = [fileobj] + list(args[1:]) elif hasattr(args[0], 'read'): path = None fileobj = args[0] format = _get_valid_format( 'read', cls, path, fileobj, args, kwargs) reader = get_reader(format, cls) data = reader(*args, **kwargs) if not isinstance(data, cls): if issubclass(cls, data.__class__): # User has read with a subclass where only the parent class is # registered. This returns the parent class, so try coercing # to desired subclass. try: data = cls(data) except Exception: raise TypeError('could not convert reader output to {0} ' 'class.'.format(cls.__name__)) else: raise TypeError("reader should return a {0} instance" "".format(cls.__name__)) finally: if ctx is not None: ctx.__exit__(*sys.exc_info()) return data def write(data, *args, format=None, **kwargs): """ Write out data. The arguments passed to this method depend on the format. """ if format is None: path = None fileobj = None if len(args): if isinstance(args[0], PATH_TYPES): # path might be a pathlib.Path object if isinstance(args[0], pathlib.Path): args = (str(args[0]),) + args[1:] path = args[0] fileobj = None elif hasattr(args[0], 'read'): path = None fileobj = args[0] format = _get_valid_format( 'write', data.__class__, path, fileobj, args, kwargs) writer = get_writer(format, data.__class__) writer(data, *args, **kwargs) def _is_best_match(class1, class2, format_classes): """ Determine if class2 is the "best" match for class1 in the list of classes. It is assumed that (class2 in classes) is True. class2 is the the best match if: - ``class1`` is a subclass of ``class2`` AND - ``class2`` is the nearest ancestor of ``class1`` that is in classes (which includes the case that ``class1 is class2``) """ if issubclass(class1, class2): classes = {cls for fmt, cls in format_classes} for parent in class1.__mro__: if parent is class2: # class2 is closest registered ancestor return True if parent in classes: # class2 was superceded return False return False def _get_valid_format(mode, cls, path, fileobj, args, kwargs): """ Returns the first valid format that can be used to read/write the data in question. Mode can be either 'read' or 'write'. """ valid_formats = identify_format(mode, cls, path, fileobj, args, kwargs) if len(valid_formats) == 0: format_table_str = _get_format_table_str(cls, mode.capitalize()) raise IORegistryError("Format could not be identified.\n" "The available formats are:\n" "{0}".format(format_table_str)) elif len(valid_formats) > 1: raise IORegistryError( "Format is ambiguous - options are: {0}".format( ', '.join(sorted(valid_formats, key=itemgetter(0))))) return valid_formats[0]
3514095323b3408a50df99f844f2b1a0a82a8ad14728f0e62e08263a1fbaf3a3
""" Implements the wrapper for the Astropy test runner in the form of the ``./setup.py test`` distutils command. """ import os import glob import shutil import subprocess import sys import tempfile from setuptools import Command class FixRemoteDataOption(type): """ This metaclass is used to catch cases where the user is running the tests with --remote-data. We've now changed the --remote-data option so that it takes arguments, but we still want --remote-data to work as before and to enable all remote tests. With this metaclass, we can modify sys.argv before distutils/setuptools try to parse the command-line options. """ def __init__(cls, name, bases, dct): try: idx = sys.argv.index('--remote-data') except ValueError: pass else: sys.argv[idx] = '--remote-data=any' try: idx = sys.argv.index('-R') except ValueError: pass else: sys.argv[idx] = '-R=any' return super(FixRemoteDataOption, cls).__init__(name, bases, dct) class AstropyTest(Command, metaclass=FixRemoteDataOption): description = 'Run the tests for this package' user_options = [ ('package=', 'P', "The name of a specific package to test, e.g. 'io.fits' or 'utils'. " "If nothing is specified, all default tests are run."), ('test-path=', 't', 'Specify a test location by path. If a relative path to a .py file, ' 'it is relative to the built package, so e.g., a leading "astropy/" ' 'is necessary. If a relative path to a .rst file, it is relative to ' 'the directory *below* the --docs-path directory, so a leading ' '"docs/" is usually necessary. May also be an absolute path.'), ('verbose-results', 'V', 'Turn on verbose output from pytest.'), ('plugins=', 'p', 'Plugins to enable when running pytest.'), ('pastebin=', 'b', "Enable pytest pastebin output. Either 'all' or 'failed'."), ('args=', 'a', 'Additional arguments to be passed to pytest.'), ('remote-data=', 'R', 'Run tests that download remote data. Should be ' 'one of none/astropy/any (defaults to none).'), ('pep8', '8', 'Enable PEP8 checking and disable regular tests. ' 'Requires the pytest-pep8 plugin.'), ('pdb', 'd', 'Start the interactive Python debugger on errors.'), ('coverage', 'c', 'Create a coverage report. Requires the coverage package.'), ('open-files', 'o', 'Fail if any tests leave files open. Requires the ' 'psutil package.'), ('parallel=', 'j', 'Run the tests in parallel on the specified number of ' 'CPUs. If negative, all the cores on the machine will be ' 'used. Requires the pytest-xdist plugin.'), ('docs-path=', None, 'The path to the documentation .rst files. If not provided, and ' 'the current directory contains a directory called "docs", that ' 'will be used.'), ('skip-docs', None, "Don't test the documentation .rst files."), ('repeat=', None, 'How many times to repeat each test (can be used to check for ' 'sporadic failures).'), ('temp-root=', None, 'The root directory in which to create the temporary testing files. ' 'If unspecified the system default is used (e.g. /tmp) as explained ' 'in the documentation for tempfile.mkstemp.') ] package_name = '' def initialize_options(self): self.package = None self.test_path = None self.verbose_results = False self.plugins = None self.pastebin = None self.args = None self.remote_data = 'none' self.pep8 = False self.pdb = False self.coverage = False self.open_files = False self.parallel = 0 self.docs_path = None self.skip_docs = False self.repeat = None self.temp_root = None def finalize_options(self): # Normally we would validate the options here, but that's handled in # run_tests pass def generate_testing_command(self): """ Build a Python script to run the tests. """ cmd_pre = '' # Commands to run before the test function cmd_post = '' # Commands to run after the test function if self.coverage: pre, post = self._generate_coverage_commands() cmd_pre += pre cmd_post += post set_flag = "import builtins; builtins._ASTROPY_TEST_ = True" cmd = ('{cmd_pre}{0}; import {1.package_name}, sys; result = (' '{1.package_name}.test(' 'package={1.package!r}, ' 'test_path={1.test_path!r}, ' 'args={1.args!r}, ' 'plugins={1.plugins!r}, ' 'verbose={1.verbose_results!r}, ' 'pastebin={1.pastebin!r}, ' 'remote_data={1.remote_data!r}, ' 'pep8={1.pep8!r}, ' 'pdb={1.pdb!r}, ' 'open_files={1.open_files!r}, ' 'parallel={1.parallel!r}, ' 'docs_path={1.docs_path!r}, ' 'skip_docs={1.skip_docs!r}, ' 'add_local_eggs_to_path=True, ' # see _build_temp_install below 'repeat={1.repeat!r})); ' '{cmd_post}' 'sys.exit(result)') return cmd.format(set_flag, self, cmd_pre=cmd_pre, cmd_post=cmd_post) def run(self): """ Run the tests! """ # Install the runtime dependencies. if self.distribution.install_requires: self.distribution.fetch_build_eggs(self.distribution.install_requires) # Ensure there is a doc path if self.docs_path is None: cfg_docs_dir = self.distribution.get_option_dict('build_docs').get('source_dir', None) # Some affiliated packages use this. # See astropy/package-template#157 if cfg_docs_dir is not None and os.path.exists(cfg_docs_dir[1]): self.docs_path = os.path.abspath(cfg_docs_dir[1]) # fall back on a default path of "docs" elif os.path.exists('docs'): # pragma: no cover self.docs_path = os.path.abspath('docs') # Build a testing install of the package self._build_temp_install() # Install the test dependencies # NOTE: we do this here after _build_temp_install because there is # a weird but which occurs if psutil is installed in this way before # astropy is built, Cython can have segmentation fault. Strange, eh? if self.distribution.tests_require: self.distribution.fetch_build_eggs(self.distribution.tests_require) # Copy any additional dependencies that may have been installed via # tests_requires or install_requires. We then pass the # add_local_eggs_to_path=True option to package.test() to make sure the # eggs get included in the path. if os.path.exists('.eggs'): shutil.copytree('.eggs', os.path.join(self.testing_path, '.eggs')) # Run everything in a try: finally: so that the tmp dir gets deleted. try: # Construct this modules testing command cmd = self.generate_testing_command() # Run the tests in a subprocess--this is necessary since # new extension modules may have appeared, and this is the # easiest way to set up a new environment testproc = subprocess.Popen( [sys.executable, '-c', cmd], cwd=self.testing_path, close_fds=False) retcode = testproc.wait() except KeyboardInterrupt: import signal # If a keyboard interrupt is handled, pass it to the test # subprocess to prompt pytest to initiate its teardown testproc.send_signal(signal.SIGINT) retcode = testproc.wait() finally: # Remove temporary directory shutil.rmtree(self.tmp_dir) raise SystemExit(retcode) def _build_temp_install(self): """ Install the package and to a temporary directory for the purposes of testing. This allows us to test the install command, include the entry points, and also avoids creating pyc and __pycache__ directories inside the build directory """ # On OSX the default path for temp files is under /var, but in most # cases on OSX /var is actually a symlink to /private/var; ensure we # dereference that link, because py.test is very sensitive to relative # paths... tmp_dir = tempfile.mkdtemp(prefix=self.package_name + '-test-', dir=self.temp_root) self.tmp_dir = os.path.realpath(tmp_dir) # We now install the package to the temporary directory. We do this # rather than build and copy because this will ensure that e.g. entry # points work. self.reinitialize_command('install') install_cmd = self.distribution.get_command_obj('install') install_cmd.prefix = self.tmp_dir self.run_command('install') # We now get the path to the site-packages directory that was created # inside self.tmp_dir install_cmd = self.get_finalized_command('install') self.testing_path = install_cmd.install_lib # Ideally, docs_path is set properly in run(), but if it is still # not set here, do not pretend it is, otherwise bad things happen. # See astropy/package-template#157 if self.docs_path is not None: new_docs_path = os.path.join(self.testing_path, os.path.basename(self.docs_path)) shutil.copytree(self.docs_path, new_docs_path) self.docs_path = new_docs_path shutil.copy('setup.cfg', self.testing_path) def _generate_coverage_commands(self): """ This method creates the post and pre commands if coverage is to be generated """ if self.parallel != 0: raise ValueError( "--coverage can not be used with --parallel") try: import coverage # pylint: disable=W0611 except ImportError: raise ImportError( "--coverage requires that the coverage package is " "installed.") # Don't use get_pkg_data_filename here, because it # requires importing astropy.config and thus screwing # up coverage results for those packages. coveragerc = os.path.join( self.testing_path, self.package_name, 'tests', 'coveragerc') with open(coveragerc, 'r') as fd: coveragerc_content = fd.read() coveragerc_content = coveragerc_content.replace( "{packagename}", self.package_name) tmp_coveragerc = os.path.join(self.tmp_dir, 'coveragerc') with open(tmp_coveragerc, 'wb') as tmp: tmp.write(coveragerc_content.encode('utf-8')) cmd_pre = ( 'import coverage; ' 'cov = coverage.coverage(data_file="{0}", config_file="{1}"); ' 'cov.start();'.format( os.path.abspath(".coverage"), tmp_coveragerc)) cmd_post = ( 'cov.stop(); ' 'from astropy.tests.helper import _save_coverage; ' '_save_coverage(cov, result, "{0}", "{1}");'.format( os.path.abspath('.'), self.testing_path)) return cmd_pre, cmd_post
73cb84d9665a83ab4af90e18393e507d75a9f66c47b2ba17b2ba12d8de22c505
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module is included only for backwards compatibility. Packages that want to use these variables should now import them directly from `astropy.tests.plugins.display` (although eventually it may be possible to configure them within setup.cfg). TODO: This entire module should eventually be removed once backwards compatibility is no longer supported. """ import warnings from ..utils.exceptions import AstropyDeprecationWarning from .helper import enable_deprecations_as_exceptions from .plugins.display import PYTEST_HEADER_MODULES, TESTED_VERSIONS _warning_message = "The module `astropy.tests.pytest_plugins has been " \ "deprecated. The variables `PYTEST_HEADER_MODULES` and `TESTED_VERSIONS`" \ "should now be imported from `astropy.tests.plugins.display`. The function " \ "`enable_deprecations_as_exceptions` should be imported from " \ "`astropy.tests.helper`" # Unfortunately, pytest does not display warning messages that occur within # conftest files, which is where these variables are imported by most packages. warnings.warn(_warning_message, AstropyDeprecationWarning)
2a7784b155ea6b5268bd954bb46cf5da42f5de95b7d967f44fdd3aed5bc97483
# Licensed under a 3-clause BSD style license - see LICENSE.rst import importlib import sys import warnings import pytest from .helper import catch_warnings from .. import log from ..logger import LoggingError, conf from ..utils.exceptions import AstropyWarning, AstropyUserWarning # Save original values of hooks. These are not the system values, but the # already overwritten values since the logger already gets imported before # this file gets executed. _excepthook = sys.__excepthook__ _showwarning = warnings.showwarning try: ip = get_ipython() except NameError: ip = None def setup_function(function): # Reset modules to default importlib.reload(warnings) importlib.reload(sys) # Reset internal original hooks log._showwarning_orig = None log._excepthook_orig = None # Set up the logger log._set_defaults() # Reset hooks if log.warnings_logging_enabled(): log.disable_warnings_logging() if log.exception_logging_enabled(): log.disable_exception_logging() teardown_module = setup_function def test_warnings_logging_disable_no_enable(): with pytest.raises(LoggingError) as e: log.disable_warnings_logging() assert e.value.args[0] == 'Warnings logging has not been enabled' def test_warnings_logging_enable_twice(): log.enable_warnings_logging() with pytest.raises(LoggingError) as e: log.enable_warnings_logging() assert e.value.args[0] == 'Warnings logging has already been enabled' def test_warnings_logging_overridden(): log.enable_warnings_logging() warnings.showwarning = lambda: None with pytest.raises(LoggingError) as e: log.disable_warnings_logging() assert e.value.args[0] == 'Cannot disable warnings logging: warnings.showwarning was not set by this logger, or has been overridden' def test_warnings_logging(): # Without warnings logging with catch_warnings() as warn_list: with log.log_to_list() as log_list: warnings.warn("This is a warning", AstropyUserWarning) assert len(log_list) == 0 assert len(warn_list) == 1 assert warn_list[0].message.args[0] == "This is a warning" # With warnings logging with catch_warnings() as warn_list: log.enable_warnings_logging() with log.log_to_list() as log_list: warnings.warn("This is a warning", AstropyUserWarning) log.disable_warnings_logging() assert len(log_list) == 1 assert len(warn_list) == 0 assert log_list[0].levelname == 'WARNING' assert log_list[0].message.startswith('This is a warning') assert log_list[0].origin == 'astropy.tests.test_logger' # With warnings logging (differentiate between Astropy and non-Astropy) with catch_warnings() as warn_list: log.enable_warnings_logging() with log.log_to_list() as log_list: warnings.warn("This is a warning", AstropyUserWarning) warnings.warn("This is another warning, not from Astropy") log.disable_warnings_logging() assert len(log_list) == 1 assert len(warn_list) == 1 assert log_list[0].levelname == 'WARNING' assert log_list[0].message.startswith('This is a warning') assert log_list[0].origin == 'astropy.tests.test_logger' assert warn_list[0].message.args[0] == "This is another warning, not from Astropy" # Without warnings logging with catch_warnings() as warn_list: with log.log_to_list() as log_list: warnings.warn("This is a warning", AstropyUserWarning) assert len(log_list) == 0 assert len(warn_list) == 1 assert warn_list[0].message.args[0] == "This is a warning" def test_warnings_logging_with_custom_class(): class CustomAstropyWarningClass(AstropyWarning): pass # With warnings logging with catch_warnings() as warn_list: log.enable_warnings_logging() with log.log_to_list() as log_list: warnings.warn("This is a warning", CustomAstropyWarningClass) log.disable_warnings_logging() assert len(log_list) == 1 assert len(warn_list) == 0 assert log_list[0].levelname == 'WARNING' assert log_list[0].message.startswith('CustomAstropyWarningClass: This is a warning') assert log_list[0].origin == 'astropy.tests.test_logger' def test_warning_logging_with_io_votable_warning(): from ..io.votable.exceptions import W02, vo_warn with catch_warnings() as warn_list: log.enable_warnings_logging() with log.log_to_list() as log_list: vo_warn(W02, ('a', 'b')) log.disable_warnings_logging() assert len(log_list) == 1 assert len(warn_list) == 0 assert log_list[0].levelname == 'WARNING' x = log_list[0].message.startswith(("W02: ?:?:?: W02: a attribute 'b' is " "invalid. Must be a standard XML id")) assert x assert log_list[0].origin == 'astropy.tests.test_logger' def test_import_error_in_warning_logging(): """ Regression test for https://github.com/astropy/astropy/issues/2671 This test actually puts a goofy fake module into ``sys.modules`` to test this problem. """ class FakeModule: def __getattr__(self, attr): raise ImportError('_showwarning should ignore any exceptions ' 'here') log.enable_warnings_logging() sys.modules['<test fake module>'] = FakeModule() try: warnings.showwarning(AstropyWarning('Regression test for #2671'), AstropyWarning, '<this is only a test>', 1) finally: del sys.modules['<test fake module>'] def test_exception_logging_disable_no_enable(): with pytest.raises(LoggingError) as e: log.disable_exception_logging() assert e.value.args[0] == 'Exception logging has not been enabled' def test_exception_logging_enable_twice(): log.enable_exception_logging() with pytest.raises(LoggingError) as e: log.enable_exception_logging() assert e.value.args[0] == 'Exception logging has already been enabled' # You can't really override the exception handler in IPython this way, so # this test doesn't really make sense in the IPython context. @pytest.mark.skipif(str("ip is not None")) def test_exception_logging_overridden(): log.enable_exception_logging() sys.excepthook = lambda etype, evalue, tb: None with pytest.raises(LoggingError) as e: log.disable_exception_logging() assert e.value.args[0] == 'Cannot disable exception logging: sys.excepthook was not set by this logger, or has been overridden' @pytest.mark.xfail(str("ip is not None")) def test_exception_logging(): # Without exception logging try: with log.log_to_list() as log_list: raise Exception("This is an Exception") except Exception as exc: sys.excepthook(*sys.exc_info()) assert exc.args[0] == "This is an Exception" else: assert False # exception should have been raised assert len(log_list) == 0 # With exception logging try: log.enable_exception_logging() with log.log_to_list() as log_list: raise Exception("This is an Exception") except Exception as exc: sys.excepthook(*sys.exc_info()) assert exc.args[0] == "This is an Exception" else: assert False # exception should have been raised assert len(log_list) == 1 assert log_list[0].levelname == 'ERROR' assert log_list[0].message.startswith('Exception: This is an Exception') assert log_list[0].origin == 'astropy.tests.test_logger' # Without exception logging log.disable_exception_logging() try: with log.log_to_list() as log_list: raise Exception("This is an Exception") except Exception as exc: sys.excepthook(*sys.exc_info()) assert exc.args[0] == "This is an Exception" else: assert False # exception should have been raised assert len(log_list) == 0 @pytest.mark.xfail(str("ip is not None")) def test_exception_logging_origin(): # The point here is to get an exception raised from another location # and make sure the error's origin is reported correctly from ..utils.collections import HomogeneousList l = HomogeneousList(int) try: log.enable_exception_logging() with log.log_to_list() as log_list: l.append('foo') except TypeError as exc: sys.excepthook(*sys.exc_info()) assert exc.args[0].startswith( "homogeneous list must contain only objects of type ") else: assert False assert len(log_list) == 1 assert log_list[0].levelname == 'ERROR' assert log_list[0].message.startswith( "TypeError: homogeneous list must contain only objects of type ") assert log_list[0].origin == 'astropy.utils.collections' @pytest.mark.xfail(True, reason="Infinite recursion on Python 3.5+, probably a real issue") @pytest.mark.xfail(str("ip is not None")) def test_exception_logging_argless_exception(): """ Regression test for a crash that occurred on Python 3 when logging an exception that was instantiated with no arguments (no message, etc.) Regression test for https://github.com/astropy/astropy/pull/4056 """ try: log.enable_exception_logging() with log.log_to_list() as log_list: raise Exception() except Exception as exc: sys.excepthook(*sys.exc_info()) else: assert False # exception should have been raised assert len(log_list) == 1 assert log_list[0].levelname == 'ERROR' assert log_list[0].message == 'Exception [astropy.tests.test_logger]' assert log_list[0].origin == 'astropy.tests.test_logger' @pytest.mark.parametrize(('level'), [None, 'DEBUG', 'INFO', 'WARN', 'ERROR']) def test_log_to_list(level): orig_level = log.level try: if level is not None: log.setLevel(level) with log.log_to_list() as log_list: log.error("Error message") log.warning("Warning message") log.info("Information message") log.debug("Debug message") finally: log.setLevel(orig_level) if level is None: # The log level *should* be set to whatever it was in the config level = conf.log_level # Check list length if level == 'DEBUG': assert len(log_list) == 4 elif level == 'INFO': assert len(log_list) == 3 elif level == 'WARN': assert len(log_list) == 2 elif level == 'ERROR': assert len(log_list) == 1 # Check list content assert log_list[0].levelname == 'ERROR' assert log_list[0].message.startswith('Error message') assert log_list[0].origin == 'astropy.tests.test_logger' if len(log_list) >= 2: assert log_list[1].levelname == 'WARNING' assert log_list[1].message.startswith('Warning message') assert log_list[1].origin == 'astropy.tests.test_logger' if len(log_list) >= 3: assert log_list[2].levelname == 'INFO' assert log_list[2].message.startswith('Information message') assert log_list[2].origin == 'astropy.tests.test_logger' if len(log_list) >= 4: assert log_list[3].levelname == 'DEBUG' assert log_list[3].message.startswith('Debug message') assert log_list[3].origin == 'astropy.tests.test_logger' def test_log_to_list_level(): with log.log_to_list(filter_level='ERROR') as log_list: log.error("Error message") log.warning("Warning message") assert len(log_list) == 1 and log_list[0].levelname == 'ERROR' def test_log_to_list_origin1(): with log.log_to_list(filter_origin='astropy.tests') as log_list: log.error("Error message") log.warning("Warning message") assert len(log_list) == 2 def test_log_to_list_origin2(): with log.log_to_list(filter_origin='astropy.wcs') as log_list: log.error("Error message") log.warning("Warning message") assert len(log_list) == 0 @pytest.mark.parametrize(('level'), [None, 'DEBUG', 'INFO', 'WARN', 'ERROR']) def test_log_to_file(tmpdir, level): local_path = tmpdir.join('test.log') log_file = local_path.open('wb') log_path = str(local_path.realpath()) orig_level = log.level try: if level is not None: log.setLevel(level) with log.log_to_file(log_path): log.error("Error message") log.warning("Warning message") log.info("Information message") log.debug("Debug message") log_file.close() finally: log.setLevel(orig_level) log_file = local_path.open('rb') log_entries = log_file.readlines() log_file.close() if level is None: # The log level *should* be set to whatever it was in the config level = conf.log_level # Check list length if level == 'DEBUG': assert len(log_entries) == 4 elif level == 'INFO': assert len(log_entries) == 3 elif level == 'WARN': assert len(log_entries) == 2 elif level == 'ERROR': assert len(log_entries) == 1 # Check list content assert eval(log_entries[0].strip())[-3:] == ( 'astropy.tests.test_logger', 'ERROR', 'Error message') if len(log_entries) >= 2: assert eval(log_entries[1].strip())[-3:] == ( 'astropy.tests.test_logger', 'WARNING', 'Warning message') if len(log_entries) >= 3: assert eval(log_entries[2].strip())[-3:] == ( 'astropy.tests.test_logger', 'INFO', 'Information message') if len(log_entries) >= 4: assert eval(log_entries[3].strip())[-3:] == ( 'astropy.tests.test_logger', 'DEBUG', 'Debug message') def test_log_to_file_level(tmpdir): local_path = tmpdir.join('test.log') log_file = local_path.open('wb') log_path = str(local_path.realpath()) with log.log_to_file(log_path, filter_level='ERROR'): log.error("Error message") log.warning("Warning message") log_file.close() log_file = local_path.open('rb') log_entries = log_file.readlines() log_file.close() assert len(log_entries) == 1 assert eval(log_entries[0].strip())[-2:] == ( 'ERROR', 'Error message') def test_log_to_file_origin1(tmpdir): local_path = tmpdir.join('test.log') log_file = local_path.open('wb') log_path = str(local_path.realpath()) with log.log_to_file(log_path, filter_origin='astropy.tests'): log.error("Error message") log.warning("Warning message") log_file.close() log_file = local_path.open('rb') log_entries = log_file.readlines() log_file.close() assert len(log_entries) == 2 def test_log_to_file_origin2(tmpdir): local_path = tmpdir.join('test.log') log_file = local_path.open('wb') log_path = str(local_path.realpath()) with log.log_to_file(log_path, filter_origin='astropy.wcs'): log.error("Error message") log.warning("Warning message") log_file.close() log_file = local_path.open('rb') log_entries = log_file.readlines() log_file.close() assert len(log_entries) == 0
405ccccf29369ba6b8d77a86add0590980e6dc66c9feba4317118fa49c554ebf
"""Implements the Astropy TestRunner which is a thin wrapper around py.test.""" import inspect import os import glob import copy import shlex import sys import tempfile import warnings import importlib from collections import OrderedDict from importlib.util import find_spec from ..config.paths import set_temp_config, set_temp_cache from ..utils import wraps, find_current_module from ..utils.exceptions import AstropyWarning, AstropyDeprecationWarning __all__ = ['TestRunner', 'TestRunnerBase', 'keyword'] def _has_test_dependencies(): # pragma: no cover # Using the test runner will not work without these dependencies, but # pytest-openfiles is optional, so it's not listed here. required = ['pytest', 'pytest_remotedata', 'pytest_doctestplus'] for module in required: spec = find_spec(module) # Checking loader accounts for packages that were uninstalled if spec is None or spec.loader is None: return False return True class keyword: """ A decorator to mark a method as keyword argument for the ``TestRunner``. Parameters ---------- default_value : `object` The default value for the keyword argument. (Default: `None`) priority : `int` keyword argument methods are executed in order of descending priority. """ def __init__(self, default_value=None, priority=0): self.default_value = default_value self.priority = priority def __call__(self, f): def keyword(*args, **kwargs): return f(*args, **kwargs) keyword._default_value = self.default_value keyword._priority = self.priority # Set __doc__ explicitly here rather than using wraps because we want # to keep the function name as keyword so we can inspect it later. keyword.__doc__ = f.__doc__ return keyword class TestRunnerBase: """ The base class for the TestRunner. A test runner can be constructed by creating a subclass of this class and defining 'keyword' methods. These are methods that have the `~astropy.tests.runner.keyword` decorator, these methods are used to construct allowed keyword arguments to the `~astropy.tests.runner.TestRunnerBase.run_tests` method as a way to allow customization of individual keyword arguments (and associated logic) without having to re-implement the whole `~astropy.tests.runner.TestRunnerBase.run_tests` method. Examples -------- A simple keyword method:: class MyRunner(TestRunnerBase): @keyword('default_value'): def spam(self, spam, kwargs): \"\"\" spam : `str` The parameter description for the run_tests docstring. \"\"\" # Return value must be a list with a CLI parameter for pytest. return ['--spam={}'.format(spam)] """ def __init__(self, base_path): self.base_path = os.path.abspath(base_path) def __new__(cls, *args, **kwargs): # Before constructing the class parse all the methods that have been # decorated with ``keyword``. # The objective of this method is to construct a default set of keyword # arguments to the ``run_tests`` method. It does this by inspecting the # methods of the class for functions with the name ``keyword`` which is # the name of the decorator wrapping function. Once it has created this # dictionary, it also formats the docstring of ``run_tests`` to be # comprised of the docstrings for the ``keyword`` methods. # To add a keyword argument to the ``run_tests`` method, define a new # method decorated with ``@keyword`` and with the ``self, name, kwargs`` # signature. # Get all 'function' members as the wrapped methods are functions functions = inspect.getmembers(cls, predicate=inspect.isfunction) # Filter out anything that's not got the name 'keyword' keywords = filter(lambda func: func[1].__name__ == 'keyword', functions) # Sort all keywords based on the priority flag. sorted_keywords = sorted(keywords, key=lambda x: x[1]._priority, reverse=True) cls.keywords = OrderedDict() doc_keywords = "" for name, func in sorted_keywords: # Here we test if the function has been overloaded to return # NotImplemented which is the way to disable arguments on # subclasses. If it has been disabled we need to remove it from the # default keywords dict. We do it in the try except block because # we do not have access to an instance of the class, so this is # going to error unless the method is just doing `return # NotImplemented`. try: # Second argument is False, as it is normally a bool. # The other two are placeholders for objects. if func(None, False, None) is NotImplemented: continue except Exception: pass # Construct the default kwargs dict and docstring cls.keywords[name] = func._default_value if func.__doc__: doc_keywords += ' '*8 doc_keywords += func.__doc__.strip() doc_keywords += '\n\n' cls.run_tests.__doc__ = cls.RUN_TESTS_DOCSTRING.format(keywords=doc_keywords) return super(TestRunnerBase, cls).__new__(cls) def _generate_args(self, **kwargs): # Update default values with passed kwargs # but don't modify the defaults keywords = copy.deepcopy(self.keywords) keywords.update(kwargs) # Iterate through the keywords (in order of priority) args = [] for keyword in keywords.keys(): func = getattr(self, keyword) result = func(keywords[keyword], keywords) # Allow disabling of options in a subclass if result is NotImplemented: raise TypeError("run_tests() got an unexpected keyword argument {}".format(keyword)) # keyword methods must return a list if not isinstance(result, list): raise TypeError("{} keyword method must return a list".format(keyword)) args += result return args RUN_TESTS_DOCSTRING = \ """ Run the tests for the package. Parameters ---------- {keywords} See Also -------- pytest.main : This method builds arguments for and then calls this function. """ def run_tests(self, **kwargs): # The following option will include eggs inside a .eggs folder in # sys.path when running the tests. This is possible so that when # runnning python setup.py test, test dependencies installed via e.g. # tests_requires are available here. This is not an advertised option # since it is only for internal use if kwargs.pop('add_local_eggs_to_path', False): # Add each egg to sys.path individually for egg in glob.glob(os.path.join('.eggs', '*.egg')): sys.path.insert(0, egg) # We now need to force reload pkg_resources in case any pytest # plugins were added above, so that their entry points are picked up import pkg_resources importlib.reload(pkg_resources) if not _has_test_dependencies(): # pragma: no cover msg = "Test dependencies are missing. You should install the 'pytest-astropy' package." raise RuntimeError(msg) # The docstring for this method is defined as a class variable. # This allows it to be built for each subclass in __new__. # Don't import pytest until it's actually needed to run the tests import pytest # Raise error for undefined kwargs allowed_kwargs = set(self.keywords.keys()) passed_kwargs = set(kwargs.keys()) if not passed_kwargs.issubset(allowed_kwargs): wrong_kwargs = list(passed_kwargs.difference(allowed_kwargs)) raise TypeError("run_tests() got an unexpected keyword argument {}".format(wrong_kwargs[0])) args = self._generate_args(**kwargs) if 'plugins' not in self.keywords or self.keywords['plugins'] is None: self.keywords['plugins'] = [] # Make plugins available to test runner without registering them self.keywords['plugins'].extend([ 'astropy.tests.plugins.display', 'astropy.tests.plugins.config' ]) # override the config locations to not make a new directory nor use # existing cache or config astropy_config = tempfile.mkdtemp('astropy_config') astropy_cache = tempfile.mkdtemp('astropy_cache') # Have to use nested with statements for cross-Python support # Note, using these context managers here is superfluous if the # config_dir or cache_dir options to py.test are in use, but it's # also harmless to nest the contexts with set_temp_config(astropy_config, delete=True): with set_temp_cache(astropy_cache, delete=True): return pytest.main(args=args, plugins=self.keywords['plugins']) @classmethod def make_test_runner_in(cls, path): """ Constructs a `TestRunner` to run in the given path, and returns a ``test()`` function which takes the same arguments as `TestRunner.run_tests`. The returned ``test()`` function will be defined in the module this was called from. This is used to implement the ``astropy.test()`` function (or the equivalent for affiliated packages). """ runner = cls(path) @wraps(runner.run_tests, ('__doc__',), exclude_args=('self',)) def test(**kwargs): return runner.run_tests(**kwargs) module = find_current_module(2) if module is not None: test.__module__ = module.__name__ # A somewhat unusual hack, but delete the attached __wrapped__ # attribute--although this is normally used to tell if the function # was wrapped with wraps, on some version of Python this is also # used to determine the signature to display in help() which is # not useful in this case. We don't really care in this case if the # function was wrapped either if hasattr(test, '__wrapped__'): del test.__wrapped__ return test class TestRunner(TestRunnerBase): """ A test runner for astropy tests """ # Increase priority so this warning is displayed first. @keyword(priority=1000) def coverage(self, coverage, kwargs): if coverage: warnings.warn( "The coverage option is ignored on run_tests, since it " "can not be made to work in that context. Use " "'python setup.py test --coverage' instead.", AstropyWarning) return [] # test_path depends on self.package_path so make sure this runs before # test_path. @keyword(priority=1) def package(self, package, kwargs): """ package : str, optional The name of a specific package to test, e.g. 'io.fits' or 'utils'. If nothing is specified all default Astropy tests are run. """ if package is None: self.package_path = self.base_path else: self.package_path = os.path.join(self.base_path, package.replace('.', os.path.sep)) if not os.path.isdir(self.package_path): raise ValueError('Package not found: {0}'.format(package)) if not kwargs['test_path']: return [self.package_path] return [] @keyword() def test_path(self, test_path, kwargs): """ test_path : str, optional Specify location to test by path. May be a single file or directory. Must be specified absolutely or relative to the calling directory. """ all_args = [] # Ensure that the package kwarg has been run. self.package(kwargs['package'], kwargs) if test_path: base, ext = os.path.splitext(test_path) if ext in ('.rst', ''): if kwargs['docs_path'] is None: # This shouldn't happen from "python setup.py test" raise ValueError( "Can not test .rst files without a docs_path " "specified.") abs_docs_path = os.path.abspath(kwargs['docs_path']) abs_test_path = os.path.abspath( os.path.join(abs_docs_path, os.pardir, test_path)) common = os.path.commonprefix((abs_docs_path, abs_test_path)) if os.path.exists(abs_test_path) and common == abs_docs_path: # Turn on the doctest_rst plugin all_args.append('--doctest-rst') test_path = abs_test_path if not (os.path.isdir(test_path) or ext in ('.py', '.rst')): raise ValueError("Test path must be a directory or a path to " "a .py or .rst file") return all_args + [test_path] return [] @keyword() def args(self, args, kwargs): """ args : str, optional Additional arguments to be passed to ``pytest.main`` in the ``args`` keyword argument. """ if args: return shlex.split(args, posix=not sys.platform.startswith('win')) return [] @keyword() def plugins(self, plugins, kwargs): """ plugins : list, optional Plugins to be passed to ``pytest.main`` in the ``plugins`` keyword argument. """ return [] @keyword() def verbose(self, verbose, kwargs): """ verbose : bool, optional Convenience option to turn on verbose output from py.test. Passing True is the same as specifying ``-v`` in ``args``. """ if verbose: return ['-v'] return [] @keyword() def pastebin(self, pastebin, kwargs): """ pastebin : ('failed', 'all', None), optional Convenience option for turning on py.test pastebin output. Set to 'failed' to upload info for failed tests, or 'all' to upload info for all tests. """ if pastebin is not None: if pastebin in ['failed', 'all']: return ['--pastebin={0}'.format(pastebin)] else: raise ValueError("pastebin should be 'failed' or 'all'") return [] @keyword(default_value='none') def remote_data(self, remote_data, kwargs): """ remote_data : {'none', 'astropy', 'any'}, optional Controls whether to run tests marked with @pytest.mark.remote_data. This can be set to run no tests with remote data (``none``), only ones that use data from http://data.astropy.org (``astropy``), or all tests that use remote data (``any``). The default is ``none``. """ if remote_data is True: remote_data = 'any' elif remote_data is False: remote_data = 'none' elif remote_data not in ('none', 'astropy', 'any'): warnings.warn("The remote_data option should be one of " "none/astropy/any (found {0}). For backward-compatibility, " "assuming 'any', but you should change the option to be " "one of the supported ones to avoid issues in " "future.".format(remote_data), AstropyDeprecationWarning) remote_data = 'any' return ['--remote-data={0}'.format(remote_data)] @keyword() def pep8(self, pep8, kwargs): """ pep8 : bool, optional Turn on PEP8 checking via the pytest-pep8 plugin and disable normal tests. Same as specifying ``--pep8 -k pep8`` in ``args``. """ if pep8: try: import pytest_pep8 # pylint: disable=W0611 except ImportError: raise ImportError('PEP8 checking requires pytest-pep8 plugin: ' 'http://pypi.python.org/pypi/pytest-pep8') else: return ['--pep8', '-k', 'pep8'] return [] @keyword() def pdb(self, pdb, kwargs): """ pdb : bool, optional Turn on PDB post-mortem analysis for failing tests. Same as specifying ``--pdb`` in ``args``. """ if pdb: return ['--pdb'] return [] @keyword() def open_files(self, open_files, kwargs): """ open_files : bool, optional Fail when any tests leave files open. Off by default, because this adds extra run time to the test suite. Requires the ``psutil`` package. """ if open_files: if kwargs['parallel'] != 0: raise SystemError( "open file detection may not be used in conjunction with " "parallel testing.") try: import psutil # pylint: disable=W0611 except ImportError: raise SystemError( "open file detection requested, but psutil package " "is not installed.") return ['--open-files'] print("Checking for unclosed files") return [] @keyword(0) def parallel(self, parallel, kwargs): """ parallel : int, optional When provided, run the tests in parallel on the specified number of CPUs. If parallel is negative, it will use the all the cores on the machine. Requires the ``pytest-xdist`` plugin. """ if parallel != 0: try: from xdist import plugin # noqa except ImportError: raise SystemError( "running tests in parallel requires the pytest-xdist package") return ['-n', str(parallel)] return [] @keyword() def docs_path(self, docs_path, kwargs): """ docs_path : str, optional The path to the documentation .rst files. """ if docs_path is not None and not kwargs['skip_docs']: if kwargs['package'] is not None: docs_path = os.path.join( docs_path, kwargs['package'].replace('.', os.path.sep)) if not os.path.exists(docs_path): warnings.warn( "Can not test .rst docs, since docs path " "({0}) does not exist.".format(docs_path)) docs_path = None if docs_path and not kwargs['skip_docs'] and not kwargs['test_path']: return [docs_path, '--doctest-rst'] return [] @keyword() def skip_docs(self, skip_docs, kwargs): """ skip_docs : `bool`, optional When `True`, skips running the doctests in the .rst files. """ # Skip docs is a bool used by docs_path only. return [] @keyword() def repeat(self, repeat, kwargs): """ repeat : `int`, optional If set, specifies how many times each test should be run. This is useful for diagnosing sporadic failures. """ if repeat: return ['--repeat={0}'.format(repeat)] return [] # Override run_tests for astropy-specific fixes def run_tests(self, **kwargs): # This prevents cyclical import problems that make it # impossible to test packages that define Table types on their # own. from ..table import Table # pylint: disable=W0611 return super(TestRunner, self).run_tests(**kwargs)
2a115ddce0861b7f2083906e13be2b5e3ad38bc42614db852ff9aada7443ce45
# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return { 'astropy.tests': ['coveragerc'], }
2b1018b9248842d86917337db9a73f1c3a0c0ddbe988ec73fb901a314444ccb1
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides the tools used to internally run the astropy test suite from the installed astropy. It makes use of the `pytest` testing framework. """ import os import sys import types import pickle import warnings import functools import pytest try: # Import pkg_resources to prevent it from issuing warnings upon being # imported from within py.test. See # https://github.com/astropy/astropy/pull/537 for a detailed explanation. import pkg_resources # pylint: disable=W0611 except ImportError: pass from ..utils.exceptions import (AstropyDeprecationWarning, AstropyPendingDeprecationWarning) # For backward-compatibility with affiliated packages from .runner import TestRunner # pylint: disable=W0611 __all__ = ['raises', 'enable_deprecations_as_exceptions', 'remote_data', 'treat_deprecations_as_exceptions', 'catch_warnings', 'assert_follows_unicode_guidelines', 'quantity_allclose', 'assert_quantity_allclose', 'check_pickling_recovery', 'pickle_protocol', 'generic_recursive_equality_test'] # pytest marker to mark tests which get data from the web # This is being maintained for backwards compatibility remote_data = pytest.mark.remote_data # distutils expects options to be Unicode strings def _fix_user_options(options): def to_str_or_none(x): if x is None: return None return str(x) return [tuple(to_str_or_none(x) for x in y) for y in options] def _save_coverage(cov, result, rootdir, testing_path): """ This method is called after the tests have been run in coverage mode to cleanup and then save the coverage data and report. """ from ..utils.console import color_print if result != 0: return # The coverage report includes the full path to the temporary # directory, so we replace all the paths with the true source # path. Note that this will not work properly for packages that still # rely on 2to3. try: # Coverage 4.0: _harvest_data has been renamed to get_data, the # lines dict is private cov.get_data() except AttributeError: # Coverage < 4.0 cov._harvest_data() lines = cov.data.lines else: lines = cov.data._lines for key in list(lines.keys()): new_path = os.path.relpath( os.path.realpath(key), os.path.realpath(testing_path)) new_path = os.path.abspath( os.path.join(rootdir, new_path)) lines[new_path] = lines.pop(key) color_print('Saving coverage data in .coverage...', 'green') cov.save() color_print('Saving HTML coverage report in htmlcov...', 'green') cov.html_report(directory=os.path.join(rootdir, 'htmlcov')) class raises: """ A decorator to mark that a test should raise a given exception. Use as follows:: @raises(ZeroDivisionError) def test_foo(): x = 1/0 This can also be used a context manager, in which case it is just an alias for the ``pytest.raises`` context manager (because the two have the same name this help avoid confusion by being flexible). """ # pep-8 naming exception -- this is a decorator class def __init__(self, exc): self._exc = exc self._ctx = None def __call__(self, func): @functools.wraps(func) def run_raises_test(*args, **kwargs): pytest.raises(self._exc, func, *args, **kwargs) return run_raises_test def __enter__(self): self._ctx = pytest.raises(self._exc) return self._ctx.__enter__() def __exit__(self, *exc_info): return self._ctx.__exit__(*exc_info) _deprecations_as_exceptions = False _include_astropy_deprecations = True _modules_to_ignore_on_import = set([ 'compiler', # A deprecated stdlib module used by py.test 'scipy', 'pygments', 'ipykernel', 'IPython', # deprecation warnings for async and await 'setuptools']) _warnings_to_ignore_entire_module = set([]) _warnings_to_ignore_by_pyver = { (3, 5): set([ # py.test reads files with the 'U' flag, which is # deprecated. r"'U' mode is deprecated", # py.test raised this warning in inspect on Python 3.5. # See https://github.com/pytest-dev/pytest/pull/1009 # Keeping it since e.g. lxml as of 3.8.0 is still calling getargspec() r"inspect\.getargspec\(\) is deprecated, use " r"inspect\.signature\(\) instead"]), (3, 6): set([ # py.test reads files with the 'U' flag, which is # deprecated. r"'U' mode is deprecated", # inspect raises this slightly different warning on Python 3.6. # Keeping it since e.g. lxml as of 3.8.0 is still calling getargspec() r"inspect\.getargspec\(\) is deprecated, use " r"inspect\.signature\(\) or inspect\.getfullargspec\(\)"])} def enable_deprecations_as_exceptions(include_astropy_deprecations=True, modules_to_ignore_on_import=[], warnings_to_ignore_entire_module=[], warnings_to_ignore_by_pyver={}): """ Turn on the feature that turns deprecations into exceptions. Parameters ---------- include_astropy_deprecations : bool If set to `True`, ``AstropyDeprecationWarning`` and ``AstropyPendingDeprecationWarning`` are also turned into exceptions. modules_to_ignore_on_import : list of str List of additional modules that generate deprecation warnings on import, which are to be ignored. By default, these are already included: ``compiler``, ``scipy``, ``pygments``, ``ipykernel``, and ``setuptools``. warnings_to_ignore_entire_module : list of str List of modules with deprecation warnings to ignore completely, not just during import. If ``include_astropy_deprecations=True`` is given, ``AstropyDeprecationWarning`` and ``AstropyPendingDeprecationWarning`` are also ignored for the modules. warnings_to_ignore_by_pyver : dict Dictionary mapping tuple of ``(major, minor)`` Python version to a list of deprecation warning messages to ignore. This is in addition of those already ignored by default (see ``_warnings_to_ignore_by_pyver`` values). """ global _deprecations_as_exceptions _deprecations_as_exceptions = True global _include_astropy_deprecations _include_astropy_deprecations = include_astropy_deprecations global _modules_to_ignore_on_import _modules_to_ignore_on_import.update(modules_to_ignore_on_import) global _warnings_to_ignore_entire_module _warnings_to_ignore_entire_module.update(warnings_to_ignore_entire_module) global _warnings_to_ignore_by_pyver for key, val in warnings_to_ignore_by_pyver.items(): if key in _warnings_to_ignore_by_pyver: _warnings_to_ignore_by_pyver[key].update(val) else: _warnings_to_ignore_by_pyver[key] = set(val) def treat_deprecations_as_exceptions(): """ Turn all DeprecationWarnings (which indicate deprecated uses of Python itself or Numpy, but not within Astropy, where we use our own deprecation warning class) into exceptions so that we find out about them early. This completely resets the warning filters and any "already seen" warning state. """ # First, totally reset the warning state. The modules may change during # this iteration thus we copy the original state to a list to iterate # on. See https://github.com/astropy/astropy/pull/5513. for module in list(sys.modules.values()): # We don't want to deal with six.MovedModules, only "real" # modules. if (isinstance(module, types.ModuleType) and hasattr(module, '__warningregistry__')): del module.__warningregistry__ if not _deprecations_as_exceptions: return warnings.resetwarnings() # Hide the next couple of DeprecationWarnings warnings.simplefilter('ignore', DeprecationWarning) # Here's the wrinkle: a couple of our third-party dependencies # (py.test and scipy) are still using deprecated features # themselves, and we'd like to ignore those. Fortunately, those # show up only at import time, so if we import those things *now*, # before we turn the warnings into exceptions, we're golden. for m in _modules_to_ignore_on_import: try: __import__(m) except ImportError: pass # Now, start over again with the warning filters warnings.resetwarnings() # Now, turn DeprecationWarnings into exceptions _all_warns = [DeprecationWarning] # Only turn astropy deprecation warnings into exceptions if requested if _include_astropy_deprecations: _all_warns += [AstropyDeprecationWarning, AstropyPendingDeprecationWarning] for w in _all_warns: warnings.filterwarnings("error", ".*", w) # This ignores all deprecation warnings from given module(s), # not just on import, for use of Astropy affiliated packages. for m in _warnings_to_ignore_entire_module: for w in _all_warns: warnings.filterwarnings('ignore', category=w, module=m) for v in _warnings_to_ignore_by_pyver: if sys.version_info[:2] == v: for s in _warnings_to_ignore_by_pyver[v]: warnings.filterwarnings("ignore", s, DeprecationWarning) class catch_warnings(warnings.catch_warnings): """ A high-powered version of warnings.catch_warnings to use for testing and to make sure that there is no dependence on the order in which the tests are run. This completely blitzes any memory of any warnings that have appeared before so that all warnings will be caught and displayed. ``*args`` is a set of warning classes to collect. If no arguments are provided, all warnings are collected. Use as follows:: with catch_warnings(MyCustomWarning) as w: do.something.bad() assert len(w) > 0 """ def __init__(self, *classes): super(catch_warnings, self).__init__(record=True) self.classes = classes def __enter__(self): warning_list = super(catch_warnings, self).__enter__() treat_deprecations_as_exceptions() if len(self.classes) == 0: warnings.simplefilter('always') else: warnings.simplefilter('ignore') for cls in self.classes: warnings.simplefilter('always', cls) return warning_list def __exit__(self, type, value, traceback): treat_deprecations_as_exceptions() class ignore_warnings(catch_warnings): """ This can be used either as a context manager or function decorator to ignore all warnings that occur within a function or block of code. An optional category option can be supplied to only ignore warnings of a certain category or categories (if a list is provided). """ def __init__(self, category=None): super(ignore_warnings, self).__init__() if isinstance(category, type) and issubclass(category, Warning): self.category = [category] else: self.category = category def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): # Originally this just reused self, but that doesn't work if the # function is called more than once so we need to make a new # context manager instance for each call with self.__class__(category=self.category): return func(*args, **kwargs) return wrapper def __enter__(self): retval = super(ignore_warnings, self).__enter__() if self.category is not None: for category in self.category: warnings.simplefilter('ignore', category) else: warnings.simplefilter('ignore') return retval def assert_follows_unicode_guidelines( x, roundtrip=None): """ Test that an object follows our Unicode policy. See "Unicode guidelines" in the coding guidelines. Parameters ---------- x : object The instance to test roundtrip : module, optional When provided, this namespace will be used to evaluate ``repr(x)`` and ensure that it roundtrips. It will also ensure that ``__bytes__(x)`` roundtrip. If not provided, no roundtrip testing will be performed. """ from .. import conf with conf.set_temp('unicode_output', False): bytes_x = bytes(x) unicode_x = str(x) repr_x = repr(x) assert isinstance(bytes_x, bytes) bytes_x.decode('ascii') assert isinstance(unicode_x, str) unicode_x.encode('ascii') assert isinstance(repr_x, str) if isinstance(repr_x, bytes): repr_x.decode('ascii') else: repr_x.encode('ascii') if roundtrip is not None: assert x.__class__(bytes_x) == x assert x.__class__(unicode_x) == x assert eval(repr_x, roundtrip) == x with conf.set_temp('unicode_output', True): bytes_x = bytes(x) unicode_x = str(x) repr_x = repr(x) assert isinstance(bytes_x, bytes) bytes_x.decode('ascii') assert isinstance(unicode_x, str) assert isinstance(repr_x, str) if isinstance(repr_x, bytes): repr_x.decode('ascii') else: repr_x.encode('ascii') if roundtrip is not None: assert x.__class__(bytes_x) == x assert x.__class__(unicode_x) == x assert eval(repr_x, roundtrip) == x @pytest.fixture(params=[0, 1, -1]) def pickle_protocol(request): """ Fixture to run all the tests for protocols 0 and 1, and -1 (most advanced). (Originally from astropy.table.tests.test_pickle) """ return request.param def generic_recursive_equality_test(a, b, class_history): """ Check if the attributes of a and b are equal. Then, check if the attributes of the attributes are equal. """ dict_a = a.__dict__ dict_b = b.__dict__ for key in dict_a: assert key in dict_b,\ "Did not pickle {0}".format(key) if hasattr(dict_a[key], '__eq__'): eq = (dict_a[key] == dict_b[key]) if '__iter__' in dir(eq): eq = (False not in eq) assert eq, "Value of {0} changed by pickling".format(key) if hasattr(dict_a[key], '__dict__'): if dict_a[key].__class__ in class_history: # attempt to prevent infinite recursion pass else: new_class_history = [dict_a[key].__class__] new_class_history.extend(class_history) generic_recursive_equality_test(dict_a[key], dict_b[key], new_class_history) def check_pickling_recovery(original, protocol): """ Try to pickle an object. If successful, make sure the object's attributes survived pickling and unpickling. """ f = pickle.dumps(original, protocol=protocol) unpickled = pickle.loads(f) class_history = [original.__class__] generic_recursive_equality_test(original, unpickled, class_history) def assert_quantity_allclose(actual, desired, rtol=1.e-7, atol=None, **kwargs): """ Raise an assertion if two objects are not equal up to desired tolerance. This is a :class:`~astropy.units.Quantity`-aware version of :func:`numpy.testing.assert_allclose`. """ import numpy as np np.testing.assert_allclose(*_unquantify_allclose_arguments(actual, desired, rtol, atol), **kwargs) def quantity_allclose(a, b, rtol=1.e-5, atol=None, **kwargs): """ Returns True if two arrays are element-wise equal within a tolerance. This is a :class:`~astropy.units.Quantity`-aware version of :func:`numpy.allclose`. """ import numpy as np return np.allclose(*_unquantify_allclose_arguments(a, b, rtol, atol), **kwargs) def _unquantify_allclose_arguments(actual, desired, rtol, atol): from .. import units as u actual = u.Quantity(actual, subok=True, copy=False) desired = u.Quantity(desired, subok=True, copy=False) try: desired = desired.to(actual.unit) except u.UnitsError: raise u.UnitsError("Units for 'desired' ({0}) and 'actual' ({1}) " "are not convertible" .format(desired.unit, actual.unit)) if atol is None: # by default, we assume an absolute tolerance of 0 atol = u.Quantity(0) else: atol = u.Quantity(atol, subok=True, copy=False) try: atol = atol.to(actual.unit) except u.UnitsError: raise u.UnitsError("Units for 'atol' ({0}) and 'actual' ({1}) " "are not convertible" .format(atol.unit, actual.unit)) rtol = u.Quantity(rtol, subok=True, copy=False) try: rtol = rtol.to(u.dimensionless_unscaled) except Exception: raise u.UnitsError("`rtol` should be dimensionless") return actual.value, desired.value, rtol.value, atol.value
129c37a6211e764d0ee0173f0b05cdb162d59169cff4e3e9c2ac0f997ed64694
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') def ignore_matplotlibrc(func): # This is a decorator for tests that use matplotlib but not pytest-mpl # (which already handles rcParams) @wraps(func) def wrapper(*args, **kwargs): with plt.style.context({}, after_reset=True): return func(*args, **kwargs) return wrapper
764720ca5eb566100d7c4ab7a6cf4e6bd965521d1e16e6632c150dc5aa28e703
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This is retained only for backwards compatibility. Affiliated packages should no longer import ``disable_internet`` from ``astropy.tests``. It is now available from ``pytest_remotedata``. However, this is not the recommended mechanism for controlling access to remote data in tests. Instead, packages should make use of decorators provided by the pytest_remotedata plugin: - ``@pytest.mark.remote_data`` for tests that require remote data access - ``@pytest.mark.internet_off`` for tests that should only run when remote data access is disabled. Remote data access for the test suite is controlled by the ``--remote-data`` command line flag. This is either passed to ``pytest`` directly or to the ``setup.py test`` command. TODO: This module should eventually be removed once backwards compatibility is no longer supported. """ from warnings import warn from ..utils.exceptions import AstropyDeprecationWarning warn("The ``disable_internet`` module is no longer provided by astropy. It " "is now available as ``pytest_remotedata.disable_internet``. However, " "developers are encouraged to avoid using this module directly. See " "<https://docs.astropy.org/en/latest/whatsnew/3.0.html#pytest-plugins> " "for more information.", AstropyDeprecationWarning) try: # This should only be necessary during testing, in which case the test # package must be installed anyway. from pytest_remotedata.disable_internet import * except ImportError: pass
5c96aae81722034e1a5cd7e3a62430c52febcedf052d6fd426b26154778928c4
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Astronomical and physics constants in SI units. See :mod:`astropy.constants` for a complete listing of constants defined in Astropy. """ import numpy as np from .constant import Constant # ASTRONOMICAL CONSTANTS class IAU2012(Constant): default_reference = 'IAU 2012' _registry = {} _has_incompatible_units = set() # DISTANCE # Astronomical Unit au = IAU2012('au', "Astronomical Unit", 1.49597870700e11, 'm', 0.0, "IAU 2012 Resolution B2", system='si') # Parsec pc = IAU2012('pc', "Parsec", au.value / np.tan(np.radians(1. / 3600.)), 'm', au.uncertainty / np.tan(np.radians(1. / 3600.)), "Derived from au", system='si') # Kiloparsec kpc = IAU2012('kpc', "Kiloparsec", 1000. * au.value / np.tan(np.radians(1. / 3600.)), 'm', 1000. * au.uncertainty / np.tan(np.radians(1. / 3600.)), "Derived from au", system='si') # Luminosity L_bol0 = IAU2012('L_bol0', "Luminosity for absolute bolometric magnitude 0", 3.0128e28, "W", 0.0, "IAU 2015 Resolution B 2", system='si') # SOLAR QUANTITIES # Solar luminosity L_sun = IAU2012('L_sun', "Solar luminosity", 3.846e26, 'W', 0.0005e26, "Allen's Astrophysical Quantities 4th Ed.", system='si') # Solar mass M_sun = IAU2012('M_sun', "Solar mass", 1.9891e30, 'kg', 0.00005e30, "Allen's Astrophysical Quantities 4th Ed.", system='si') # Solar radius R_sun = IAU2012('R_sun', "Solar radius", 6.95508e8, 'm', 0.00026e8, "Allen's Astrophysical Quantities 4th Ed.", system='si') # OTHER SOLAR SYSTEM QUANTITIES # Jupiter mass M_jup = IAU2012('M_jup', "Jupiter mass", 1.8987e27, 'kg', 0.00005e27, "Allen's Astrophysical Quantities 4th Ed.", system='si') # Jupiter equatorial radius R_jup = IAU2012('R_jup', "Jupiter equatorial radius", 7.1492e7, 'm', 0.00005e7, "Allen's Astrophysical Quantities 4th Ed.", system='si') # Earth mass M_earth = IAU2012('M_earth', "Earth mass", 5.9742e24, 'kg', 0.00005e24, "Allen's Astrophysical Quantities 4th Ed.", system='si') # Earth equatorial radius R_earth = IAU2012('R_earth', "Earth equatorial radius", 6.378136e6, 'm', 0.0000005e6, "Allen's Astrophysical Quantities 4th Ed.", system='si')
d7151215de768d393c09a4b5abe77239df6b075f660ed38ad7fcfc16022c002b
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Astronomical and physics constants in SI units. See :mod:`astropy.constants` for a complete listing of constants defined in Astropy. """ import numpy as np from .constant import Constant, EMConstant # PHYSICAL CONSTANTS class CODATA2014(Constant): default_reference = 'CODATA 2014' _registry = {} _has_incompatible_units = set() class EMCODATA2014(CODATA2014, EMConstant): _registry = CODATA2014._registry h = CODATA2014('h', "Planck constant", 6.626070040e-34, 'J s', 0.000000081e-34, system='si') hbar = CODATA2014('hbar', "Reduced Planck constant", 1.054571800e-34, 'J s', 0.000000013e-34, system='si') k_B = CODATA2014('k_B', "Boltzmann constant", 1.38064852e-23, 'J / (K)', 0.00000079e-23, system='si') c = CODATA2014('c', "Speed of light in vacuum", 299792458., 'm / (s)', 0.0, system='si') G = CODATA2014('G', "Gravitational constant", 6.67408e-11, 'm3 / (kg s2)', 0.00031e-11, system='si') g0 = CODATA2014('g0', "Standard acceleration of gravity", 9.80665, 'm / s2', 0.0, system='si') m_p = CODATA2014('m_p', "Proton mass", 1.672621898e-27, 'kg', 0.000000021e-27, system='si') m_n = CODATA2014('m_n', "Neutron mass", 1.674927471e-27, 'kg', 0.000000021e-27, system='si') m_e = CODATA2014('m_e', "Electron mass", 9.10938356e-31, 'kg', 0.00000011e-31, system='si') u = CODATA2014('u', "Atomic mass", 1.660539040e-27, 'kg', 0.000000020e-27, system='si') sigma_sb = CODATA2014('sigma_sb', "Stefan-Boltzmann constant", 5.670367e-8, 'W / (K4 m2)', 0.000013e-8, system='si') e = EMCODATA2014('e', 'Electron charge', 1.6021766208e-19, 'C', 0.0000000098e-19, system='si') eps0 = EMCODATA2014('eps0', 'Electric constant', 8.854187817e-12, 'F/m', 0.0, system='si') N_A = CODATA2014('N_A', "Avogadro's number", 6.022140857e23, '1 / (mol)', 0.000000074e23, system='si') R = CODATA2014('R', "Gas constant", 8.3144598, 'J / (K mol)', 0.0000048, system='si') Ryd = CODATA2014('Ryd', 'Rydberg constant', 10973731.568508, '1 / (m)', 0.000065, system='si') a0 = CODATA2014('a0', "Bohr radius", 0.52917721067e-10, 'm', 0.00000000012e-10, system='si') muB = CODATA2014('muB', "Bohr magneton", 927.4009994e-26, 'J/T', 0.00002e-26, system='si') alpha = CODATA2014('alpha', "Fine-structure constant", 7.2973525664e-3, '', 0.0000000017e-3, system='si') atm = CODATA2014('atm', "Standard atmosphere", 101325, 'Pa', 0.0, system='si') mu0 = CODATA2014('mu0', "Magnetic constant", 4.0e-7 * np.pi, 'N/A2', 0.0, system='si') sigma_T = CODATA2014('sigma_T', "Thomson scattering cross-section", 0.66524587158e-28, 'm2', 0.00000000091e-28, system='si') b_wien = CODATA2014('b_wien', 'Wien wavelength displacement law constant', 2.8977729e-3, 'm K', 00.0000017e-3, system='si') # cgs constants # Only constants that cannot be converted directly from S.I. are defined here. e_esu = EMCODATA2014(e.abbrev, e.name, e.value * c.value * 10.0, 'statC', e.uncertainty * c.value * 10.0, system='esu') e_emu = EMCODATA2014(e.abbrev, e.name, e.value / 10, 'abC', e.uncertainty / 10, system='emu') e_gauss = EMCODATA2014(e.abbrev, e.name, e.value * c.value * 10.0, 'Fr', e.uncertainty * c.value * 10.0, system='gauss')
8422048da6508d633e96dcbc4b116a79cd1be82ac05af650dcf9749cf5c0aa6b
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Contains astronomical and physical constants for use in Astropy or other places. A typical use case might be:: >>> from astropy.constants import c, m_e >>> # ... define the mass of something you want the rest energy of as m ... >>> m = m_e >>> E = m * c**2 >>> E.to('MeV') # doctest: +FLOAT_CMP <Quantity 0.510998927603161 MeV> """ import inspect from contextlib import contextmanager # Hack to make circular imports with units work try: from .. import units del units except ImportError: pass from .constant import Constant, EMConstant # noqa from . import si # noqa from . import cgs # noqa from . import codata2014, iau2015 # noqa from . import utils as _utils # for updating the constants module docstring _lines = [ 'The following constants are available:\n', '========== ============== ================ =========================', ' Name Value Unit Description', '========== ============== ================ =========================', ] # NOTE: Update this when default changes. _utils._set_c(codata2014, iau2015, inspect.getmodule(inspect.currentframe()), not_in_module_only=True, doclines=_lines, set_class=True) _lines.append(_lines[1]) if __doc__ is not None: __doc__ += '\n'.join(_lines) # TODO: Re-implement in a way that is more consistent with astropy.units. # See https://github.com/astropy/astropy/pull/7008 discussions. @contextmanager def set_enabled_constants(modname): """ Context manager to temporarily set values in the ``constants`` namespace to an older version. See :ref:`astropy-constants-prior` for usage. Parameters ---------- modname : {'astropyconst13'} Name of the module containing an older version. """ # Re-import here because these were deleted from namespace on init. import inspect import warnings from . import utils as _utils # NOTE: Update this when default changes. if modname == 'astropyconst13': from .astropyconst13 import codata2010 as codata from .astropyconst13 import iau2012 as iaudata else: raise ValueError( 'Context manager does not currently handle {}'.format(modname)) module = inspect.getmodule(inspect.currentframe()) # Ignore warnings about "Constant xxx already has a definition..." with warnings.catch_warnings(): warnings.simplefilter('ignore') _utils._set_c(codata, iaudata, module, not_in_module_only=False, set_class=True) try: yield finally: with warnings.catch_warnings(): warnings.simplefilter('ignore') # NOTE: Update this when default changes. _utils._set_c(codata2014, iau2015, module, not_in_module_only=False, set_class=True) # Clean up namespace del inspect del contextmanager del _utils del _lines
a98708e9b40932300529e6ff8b9ce0bbf6df894ddc9c3d9ffdeacbe62a3c7152
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Astronomical and physics constants in SI units. See :mod:`astropy.constants` for a complete listing of constants defined in Astropy. """ import numpy as np from .constant import Constant, EMConstant # PHYSICAL CONSTANTS class CODATA2010(Constant): default_reference = 'CODATA 2010' _registry = {} _has_incompatible_units = set() def __new__(cls, abbrev, name, value, unit, uncertainty, reference=default_reference, system=None): return super().__new__( cls, abbrev, name, value, unit, uncertainty, reference, system) class EMCODATA2010(CODATA2010, EMConstant): _registry = CODATA2010._registry h = CODATA2010('h', "Planck constant", 6.62606957e-34, 'J s', 0.00000029e-34, system='si') hbar = CODATA2010('hbar', "Reduced Planck constant", h.value * 0.5 / np.pi, 'J s', h.uncertainty * 0.5 / np.pi, h.reference, system='si') k_B = CODATA2010('k_B', "Boltzmann constant", 1.3806488e-23, 'J / (K)', 0.0000013e-23, system='si') c = CODATA2010('c', "Speed of light in vacuum", 2.99792458e8, 'm / (s)', 0., system='si') G = CODATA2010('G', "Gravitational constant", 6.67384e-11, 'm3 / (kg s2)', 0.00080e-11, system='si') g0 = CODATA2010('g0', "Standard acceleration of gravity", 9.80665, 'm / s2', 0.0, system='si') m_p = CODATA2010('m_p', "Proton mass", 1.672621777e-27, 'kg', 0.000000074e-27, system='si') m_n = CODATA2010('m_n', "Neutron mass", 1.674927351e-27, 'kg', 0.000000074e-27, system='si') m_e = CODATA2010('m_e', "Electron mass", 9.10938291e-31, 'kg', 0.00000040e-31, system='si') u = CODATA2010('u', "Atomic mass", 1.660538921e-27, 'kg', 0.000000073e-27, system='si') sigma_sb = CODATA2010('sigma_sb', "Stefan-Boltzmann constant", 5.670373e-8, 'W / (K4 m2)', 0.000021e-8, system='si') e = EMCODATA2010('e', 'Electron charge', 1.602176565e-19, 'C', 0.000000035e-19, system='si') eps0 = EMCODATA2010('eps0', 'Electric constant', 8.854187817e-12, 'F/m', 0.0, system='si') N_A = CODATA2010('N_A', "Avogadro's number", 6.02214129e23, '1 / (mol)', 0.00000027e23, system='si') R = CODATA2010('R', "Gas constant", 8.3144621, 'J / (K mol)', 0.0000075, system='si') Ryd = CODATA2010('Ryd', 'Rydberg constant', 10973731.568539, '1 / (m)', 0.000055, system='si') a0 = CODATA2010('a0', "Bohr radius", 0.52917721092e-10, 'm', 0.00000000017e-10, system='si') muB = CODATA2010('muB', "Bohr magneton", 927.400968e-26, 'J/T', 0.00002e-26, system='si') alpha = CODATA2010('alpha', "Fine-structure constant", 7.2973525698e-3, '', 0.0000000024e-3, system='si') atm = CODATA2010('atm', "Standard atmosphere", 101325, 'Pa', 0.0, system='si') mu0 = CODATA2010('mu0', "Magnetic constant", 4.0e-7 * np.pi, 'N/A2', 0.0, system='si') sigma_T = CODATA2010('sigma_T', "Thomson scattering cross-section", 0.6652458734e-28, 'm2', 0.0000000013e-28, system='si') b_wien = Constant('b_wien', 'Wien wavelength displacement law constant', 2.8977721e-3, 'm K', 0.0000026e-3, 'CODATA 2010', system='si') # cgs constants # Only constants that cannot be converted directly from S.I. are defined here. e_esu = EMCODATA2010(e.abbrev, e.name, e.value * c.value * 10.0, 'statC', e.uncertainty * c.value * 10.0, system='esu') e_emu = EMCODATA2010(e.abbrev, e.name, e.value / 10, 'abC', e.uncertainty / 10, system='emu') e_gauss = EMCODATA2010(e.abbrev, e.name, e.value * c.value * 10.0, 'Fr', e.uncertainty * c.value * 10.0, system='gauss')
9547dcedb4c8e705412c4dc9900c379a5ce9218ded7bc87daee2eea7c29df6e4
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Astronomical and physics constants for Astropy v1.3 and earlier. See :mod:`astropy.constants` for a complete listing of constants defined in Astropy. """ import inspect from . import utils as _utils from . import codata2010, iau2012 _utils._set_c(codata2010, iau2012, inspect.getmodule(inspect.currentframe())) # Clean up namespace del inspect del _utils
8160b661c19685069d4c326fea1e9091605a79ffdc67957f4f1ffc25afb0e1bb
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Astronomical and physics constants in SI units. See :mod:`astropy.constants` for a complete listing of constants defined in Astropy. """ import numpy as np from .constant import Constant from .codata2014 import G # ASTRONOMICAL CONSTANTS class IAU2015(Constant): default_reference = 'IAU 2015' _registry = {} _has_incompatible_units = set() # DISTANCE # Astronomical Unit au = IAU2015('au', "Astronomical Unit", 1.49597870700e11, 'm', 0.0, "IAU 2012 Resolution B2", system='si') # Parsec pc = IAU2015('pc', "Parsec", au.value / np.tan(np.radians(1. / 3600.)), 'm', au.uncertainty / np.tan(np.radians(1. / 3600.)), "Derived from au", system='si') # Kiloparsec kpc = IAU2015('kpc', "Kiloparsec", 1000. * au.value / np.tan(np.radians(1. / 3600.)), 'm', 1000. * au.uncertainty / np.tan(np.radians(1. / 3600.)), "Derived from au", system='si') # Luminosity L_bol0 = IAU2015('L_bol0', "Luminosity for absolute bolometric magnitude 0", 3.0128e28, "W", 0.0, "IAU 2015 Resolution B 2", system='si') # SOLAR QUANTITIES # Solar luminosity L_sun = IAU2015('L_sun', "Nominal solar luminosity", 3.828e26, 'W', 0.0, "IAU 2015 Resolution B 3", system='si') # Solar mass parameter GM_sun = IAU2015('GM_sun', 'Nominal solar mass parameter', 1.3271244e20, 'm3 / (s2)', 0.0, "IAU 2015 Resolution B 3", system='si') # Solar mass (derived from mass parameter and gravitational constant) M_sun = IAU2015('M_sun', "Solar mass", GM_sun.value / G.value, 'kg', ((G.uncertainty / G.value) * (GM_sun.value / G.value)), "IAU 2015 Resolution B 3 + CODATA 2014", system='si') # Solar radius R_sun = IAU2015('R_sun', "Nominal solar radius", 6.957e8, 'm', 0.0, "IAU 2015 Resolution B 3", system='si') # OTHER SOLAR SYSTEM QUANTITIES # Jupiter mass parameter GM_jup = IAU2015('GM_jup', 'Nominal Jupiter mass parameter', 1.2668653e17, 'm3 / (s2)', 0.0, "IAU 2015 Resolution B 3", system='si') # Jupiter mass (derived from mass parameter and gravitational constant) M_jup = IAU2015('M_jup', "Jupiter mass", GM_jup.value / G.value, 'kg', ((G.uncertainty / G.value) * (GM_jup.value / G.value)), "IAU 2015 Resolution B 3 + CODATA 2014", system='si') # Jupiter equatorial radius R_jup = IAU2015('R_jup', "Nominal Jupiter equatorial radius", 7.1492e7, 'm', 0.0, "IAU 2015 Resolution B 3", system='si') # Earth mass parameter GM_earth = IAU2015('GM_earth', 'Nominal Earth mass parameter', 3.986004e14, 'm3 / (s2)', 0.0, "IAU 2015 Resolution B 3", system='si') # Earth mass (derived from mass parameter and gravitational constant) M_earth = IAU2015('M_earth', "Earth mass", GM_earth.value / G.value, 'kg', ((G.uncertainty / G.value) * (GM_earth.value / G.value)), "IAU 2015 Resolution B 3 + CODATA 2014", system='si') # Earth equatorial radius R_earth = IAU2015('R_earth', "Nominal Earth equatorial radius", 6.3781e6, 'm', 0.0, "IAU 2015 Resolution B 3", system='si')
3c887bb764ca200aa1a037c7c5dc08a14aa209badd24b86081a8b2bd59f9e82d
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Astronomical and physics constants for Astropy v2.0. See :mod:`astropy.constants` for a complete listing of constants defined in Astropy. """ import inspect from . import utils as _utils from . import codata2014, iau2015 _utils._set_c(codata2014, iau2015, inspect.getmodule(inspect.currentframe())) # Clean up namespace del inspect del _utils
23da9068839b5173829f67bfb88de75bf61fd418e7e85421f8c6d9393393c537
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Utility functions for ``constants`` sub-package.""" import itertools __all__ = [] def _get_c(codata, iaudata, module, not_in_module_only=True): """ Generator to return a Constant object. Parameters ---------- codata, iaudata : obj Modules containing CODATA and IAU constants of interest. module : obj Namespace module of interest. not_in_module_only : bool If ``True``, ignore constants that are already in the namespace of ``module``. Returns ------- _c : Constant Constant object to process. """ from .constant import Constant for _nm, _c in itertools.chain(sorted(vars(codata).items()), sorted(vars(iaudata).items())): if not isinstance(_c, Constant): continue elif (not not_in_module_only) or (_c.abbrev not in module.__dict__): yield _c def _set_c(codata, iaudata, module, not_in_module_only=True, doclines=None, set_class=False): """ Set constants in a given module namespace. Parameters ---------- codata, iaudata : obj Modules containing CODATA and IAU constants of interest. module : obj Namespace module to modify with the given ``codata`` and ``iaudata``. not_in_module_only : bool If ``True``, constants that are already in the namespace of ``module`` will not be modified. doclines : list or `None` If a list is given, this list will be modified in-place to include documentation of modified constants. This can be used to update docstring of ``module``. set_class : bool Namespace of ``module`` is populated with ``_c.__class__`` instead of just ``_c`` from :func:`_get_c`. """ for _c in _get_c(codata, iaudata, module, not_in_module_only=not_in_module_only): if set_class: value = _c.__class__(_c.abbrev, _c.name, _c.value, _c._unit_string, _c.uncertainty, _c.reference) else: value = _c setattr(module, _c.abbrev, value) if doclines is not None: doclines.append('{0:^10} {1:^14.9g} {2:^16} {3}'.format( _c.abbrev, _c.value, _c._unit_string, _c.name))