radio_beam-0.3.2/0000755000077000000240000000000013531324214013615 5ustar adamstaff00000000000000radio_beam-0.3.2/CHANGES.rst0000644000077000000240000000150113433267342015425 0ustar adamstaff000000000000000.3.2 (unreleased) ------------------ - none yet 0.3.1 (2019-02-20) ------------------ - Set mult/div for convolution/deconvolution in `Beam` and `Beams`. The `==` and `!=` operators also work with `Beams` now. (https://github.com/radio-astro-tools/radio-beam/pull/75) - Added common beam operations to `Beams`. (https://github.com/radio-astro-tools/radio-beam/pull/67) - Fix PA usage for plotting and kernel routines. (https://github.com/radio-astro-tools/radio-beam/pull/65) 0.2 (2017-10-25) ---------------- - Changed repo name to `radio-beam` from `radio_beam`. (https://github.com/radio-astro-tools/radio-beam/pull/59) - Enhancement: Added support for multiple beams through the `Beams` class. (https://github.com/radio-astro-tools/radio-beam/pull/51) 0.1 (2017-09-08) ---------------- First release radio_beam-0.3.2/LICENSE.rst0000644000077000000240000000273313174164704015447 0ustar adamstaff00000000000000Copyright (c) 2016, radio-astro-tools developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. radio_beam-0.3.2/PKG-INFO0000644000077000000240000000061113531324214014710 0ustar adamstaff00000000000000Metadata-Version: 1.0 Name: radio_beam Version: 0.3.2 Summary: Radio Beam object for use with astropy Home-page: http://radio_beam.readthedocs.org Author: Adam Leroy, Adam Ginsburg, Erik Rosolowsky, Tom Robitaille, and Eric Koch Author-email: adam.g.ginsburg@gmail.com, koch.eric.w@gmail.com License: BSD Description: This is an Astropy affiliated package. Platform: UNKNOWN radio_beam-0.3.2/README.md0000644000077000000240000000105313126401607015075 0ustar adamstaff00000000000000Radio Beam: Tools for Beam IO and Manipulation ============================================== Radio Beam is a simple toolkit for reading beam information from FITS headers and manipulating beams. Some example applications include: * Convolution and deconvolution * Unit conversion (Jy to/from K) [Basic Documentation](https://github.com/radio-astro-tools/radio_beam/blob/master/docs/index.rst) is available. [![Build Status](https://travis-ci.org/radio-astro-tools/radio_beam.svg?branch=master)](https://travis-ci.org/radio-astro-tools/radio_beam) radio_beam-0.3.2/ah_bootstrap.py0000644000077000000240000011076013516112474016667 0ustar adamstaff00000000000000""" This bootstrap module contains code for ensuring that the astropy_helpers package will be importable by the time the setup.py script runs. It also includes some workarounds to ensure that a recent-enough version of setuptools is being used for the installation. This module should be the first thing imported in the setup.py of distributions that make use of the utilities in astropy_helpers. If the distribution ships with its own copy of astropy_helpers, this module will first attempt to import from the shipped copy. However, it will also check PyPI to see if there are any bug-fix releases on top of the current version that may be useful to get past platform-specific bugs that have been fixed. When running setup.py, use the ``--offline`` command-line option to disable the auto-upgrade checks. When this module is imported or otherwise executed it automatically calls a main function that attempts to read the project's setup.cfg file, which it checks for a configuration section called ``[ah_bootstrap]`` the presences of that section, and options therein, determine the next step taken: If it contains an option called ``auto_use`` with a value of ``True``, it will automatically call the main function of this module called `use_astropy_helpers` (see that function's docstring for full details). Otherwise no further action is taken and by default the system-installed version of astropy-helpers will be used (however, ``ah_bootstrap.use_astropy_helpers`` may be called manually from within the setup.py script). This behavior can also be controlled using the ``--auto-use`` and ``--no-auto-use`` command-line flags. For clarity, an alias for ``--no-auto-use`` is ``--use-system-astropy-helpers``, and we recommend using the latter if needed. Additional options in the ``[ah_boostrap]`` section of setup.cfg have the same names as the arguments to `use_astropy_helpers`, and can be used to configure the bootstrap script when ``auto_use = True``. See https://github.com/astropy/astropy-helpers for more details, and for the latest version of this module. """ import contextlib import errno import io import locale import os import re import subprocess as sp import sys from distutils import log from distutils.debug import DEBUG try: from ConfigParser import ConfigParser, RawConfigParser except ImportError: from configparser import ConfigParser, RawConfigParser import pkg_resources from setuptools import Distribution from setuptools.package_index import PackageIndex # This is the minimum Python version required for astropy-helpers __minimum_python_version__ = (2, 7) if sys.version_info[0] < 3: _str_types = (str, unicode) _text_type = unicode PY3 = False else: _str_types = (str, bytes) _text_type = str PY3 = True # TODO: Maybe enable checking for a specific version of astropy_helpers? DIST_NAME = 'astropy-helpers' PACKAGE_NAME = 'astropy_helpers' if PY3: UPPER_VERSION_EXCLUSIVE = None else: UPPER_VERSION_EXCLUSIVE = '3' # Defaults for other options DOWNLOAD_IF_NEEDED = True INDEX_URL = 'https://pypi.python.org/simple' USE_GIT = True OFFLINE = False AUTO_UPGRADE = True # A list of all the configuration options and their required types CFG_OPTIONS = [ ('auto_use', bool), ('path', str), ('download_if_needed', bool), ('index_url', str), ('use_git', bool), ('offline', bool), ('auto_upgrade', bool) ] # Start off by parsing the setup.cfg file SETUP_CFG = ConfigParser() if os.path.exists('setup.cfg'): try: SETUP_CFG.read('setup.cfg') except Exception as e: if DEBUG: raise log.error( "Error reading setup.cfg: {0!r}\n{1} will not be " "automatically bootstrapped and package installation may fail." "\n{2}".format(e, PACKAGE_NAME, _err_help_msg)) # We used package_name in the package template for a while instead of name if SETUP_CFG.has_option('metadata', 'name'): parent_package = SETUP_CFG.get('metadata', 'name') elif SETUP_CFG.has_option('metadata', 'package_name'): parent_package = SETUP_CFG.get('metadata', 'package_name') else: parent_package = None if SETUP_CFG.has_option('options', 'python_requires'): python_requires = SETUP_CFG.get('options', 'python_requires') # The python_requires key has a syntax that can be parsed by SpecifierSet # in the packaging package. However, we don't want to have to depend on that # package, so instead we can use setuptools (which bundles packaging). We # have to add 'python' to parse it with Requirement. from pkg_resources import Requirement req = Requirement.parse('python' + python_requires) # We want the Python version as a string, which we can get from the platform module import platform python_version = platform.python_version() if not req.specifier.contains(python_version): if parent_package is None: print("ERROR: Python {} is required by this package".format(req.specifier)) else: print("ERROR: Python {} is required by {}".format(req.specifier, parent_package)) sys.exit(1) if sys.version_info < __minimum_python_version__: if parent_package is None: print("ERROR: Python {} or later is required by astropy-helpers".format( __minimum_python_version__)) else: print("ERROR: Python {} or later is required by astropy-helpers for {}".format( __minimum_python_version__, parent_package)) sys.exit(1) # What follows are several import statements meant to deal with install-time # issues with either missing or misbehaving pacakges (including making sure # setuptools itself is installed): # Check that setuptools 1.0 or later is present from distutils.version import LooseVersion try: import setuptools assert LooseVersion(setuptools.__version__) >= LooseVersion('1.0') except (ImportError, AssertionError): print("ERROR: setuptools 1.0 or later is required by astropy-helpers") sys.exit(1) # typing as a dependency for 1.6.1+ Sphinx causes issues when imported after # initializing submodule with ah_boostrap.py # See discussion and references in # https://github.com/astropy/astropy-helpers/issues/302 try: import typing # noqa except ImportError: pass # Note: The following import is required as a workaround to # https://github.com/astropy/astropy-helpers/issues/89; if we don't import this # module now, it will get cleaned up after `run_setup` is called, but that will # later cause the TemporaryDirectory class defined in it to stop working when # used later on by setuptools try: import setuptools.py31compat # noqa except ImportError: pass # matplotlib can cause problems if it is imported from within a call of # run_setup(), because in some circumstances it will try to write to the user's # home directory, resulting in a SandboxViolation. See # https://github.com/matplotlib/matplotlib/pull/4165 # Making sure matplotlib, if it is available, is imported early in the setup # process can mitigate this (note importing matplotlib.pyplot has the same # issue) try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot except: # Ignore if this fails for *any* reason* pass # End compatibility imports... class _Bootstrapper(object): """ Bootstrapper implementation. See ``use_astropy_helpers`` for parameter documentation. """ def __init__(self, path=None, index_url=None, use_git=None, offline=None, download_if_needed=None, auto_upgrade=None): if path is None: path = PACKAGE_NAME if not (isinstance(path, _str_types) or path is False): raise TypeError('path must be a string or False') if PY3 and not isinstance(path, _text_type): fs_encoding = sys.getfilesystemencoding() path = path.decode(fs_encoding) # path to unicode self.path = path # Set other option attributes, using defaults where necessary self.index_url = index_url if index_url is not None else INDEX_URL self.offline = offline if offline is not None else OFFLINE # If offline=True, override download and auto-upgrade if self.offline: download_if_needed = False auto_upgrade = False self.download = (download_if_needed if download_if_needed is not None else DOWNLOAD_IF_NEEDED) self.auto_upgrade = (auto_upgrade if auto_upgrade is not None else AUTO_UPGRADE) # If this is a release then the .git directory will not exist so we # should not use git. git_dir_exists = os.path.exists(os.path.join(os.path.dirname(__file__), '.git')) if use_git is None and not git_dir_exists: use_git = False self.use_git = use_git if use_git is not None else USE_GIT # Declared as False by default--later we check if astropy-helpers can be # upgraded from PyPI, but only if not using a source distribution (as in # the case of import from a git submodule) self.is_submodule = False @classmethod def main(cls, argv=None): if argv is None: argv = sys.argv config = cls.parse_config() config.update(cls.parse_command_line(argv)) auto_use = config.pop('auto_use', False) bootstrapper = cls(**config) if auto_use: # Run the bootstrapper, otherwise the setup.py is using the old # use_astropy_helpers() interface, in which case it will run the # bootstrapper manually after reconfiguring it. bootstrapper.run() return bootstrapper @classmethod def parse_config(cls): if not SETUP_CFG.has_section('ah_bootstrap'): return {} config = {} for option, type_ in CFG_OPTIONS: if not SETUP_CFG.has_option('ah_bootstrap', option): continue if type_ is bool: value = SETUP_CFG.getboolean('ah_bootstrap', option) else: value = SETUP_CFG.get('ah_bootstrap', option) config[option] = value return config @classmethod def parse_command_line(cls, argv=None): if argv is None: argv = sys.argv config = {} # For now we just pop recognized ah_bootstrap options out of the # arg list. This is imperfect; in the unlikely case that a setup.py # custom command or even custom Distribution class defines an argument # of the same name then we will break that. However there's a catch22 # here that we can't just do full argument parsing right here, because # we don't yet know *how* to parse all possible command-line arguments. if '--no-git' in argv: config['use_git'] = False argv.remove('--no-git') if '--offline' in argv: config['offline'] = True argv.remove('--offline') if '--auto-use' in argv: config['auto_use'] = True argv.remove('--auto-use') if '--no-auto-use' in argv: config['auto_use'] = False argv.remove('--no-auto-use') if '--use-system-astropy-helpers' in argv: config['auto_use'] = False argv.remove('--use-system-astropy-helpers') return config def run(self): strategies = ['local_directory', 'local_file', 'index'] dist = None # First, remove any previously imported versions of astropy_helpers; # this is necessary for nested installs where one package's installer # is installing another package via setuptools.sandbox.run_setup, as in # the case of setup_requires for key in list(sys.modules): try: if key == PACKAGE_NAME or key.startswith(PACKAGE_NAME + '.'): del sys.modules[key] except AttributeError: # Sometimes mysterious non-string things can turn up in # sys.modules continue # Check to see if the path is a submodule self.is_submodule = self._check_submodule() for strategy in strategies: method = getattr(self, 'get_{0}_dist'.format(strategy)) dist = method() if dist is not None: break else: raise _AHBootstrapSystemExit( "No source found for the {0!r} package; {0} must be " "available and importable as a prerequisite to building " "or installing this package.".format(PACKAGE_NAME)) # This is a bit hacky, but if astropy_helpers was loaded from a # directory/submodule its Distribution object gets a "precedence" of # "DEVELOP_DIST". However, in other cases it gets a precedence of # "EGG_DIST". However, when activing the distribution it will only be # placed early on sys.path if it is treated as an EGG_DIST, so always # do that dist = dist.clone(precedence=pkg_resources.EGG_DIST) # Otherwise we found a version of astropy-helpers, so we're done # Just active the found distribution on sys.path--if we did a # download this usually happens automatically but it doesn't hurt to # do it again # Note: Adding the dist to the global working set also activates it # (makes it importable on sys.path) by default. try: pkg_resources.working_set.add(dist, replace=True) except TypeError: # Some (much) older versions of setuptools do not have the # replace=True option here. These versions are old enough that all # bets may be off anyways, but it's easy enough to work around just # in case... if dist.key in pkg_resources.working_set.by_key: del pkg_resources.working_set.by_key[dist.key] pkg_resources.working_set.add(dist) @property def config(self): """ A `dict` containing the options this `_Bootstrapper` was configured with. """ return dict((optname, getattr(self, optname)) for optname, _ in CFG_OPTIONS if hasattr(self, optname)) def get_local_directory_dist(self): """ Handle importing a vendored package from a subdirectory of the source distribution. """ if not os.path.isdir(self.path): return log.info('Attempting to import astropy_helpers from {0} {1!r}'.format( 'submodule' if self.is_submodule else 'directory', self.path)) dist = self._directory_import() if dist is None: log.warn( 'The requested path {0!r} for importing {1} does not ' 'exist, or does not contain a copy of the {1} ' 'package.'.format(self.path, PACKAGE_NAME)) elif self.auto_upgrade and not self.is_submodule: # A version of astropy-helpers was found on the available path, but # check to see if a bugfix release is available on PyPI upgrade = self._do_upgrade(dist) if upgrade is not None: dist = upgrade return dist def get_local_file_dist(self): """ Handle importing from a source archive; this also uses setup_requires but points easy_install directly to the source archive. """ if not os.path.isfile(self.path): return log.info('Attempting to unpack and import astropy_helpers from ' '{0!r}'.format(self.path)) try: dist = self._do_download(find_links=[self.path]) except Exception as e: if DEBUG: raise log.warn( 'Failed to import {0} from the specified archive {1!r}: ' '{2}'.format(PACKAGE_NAME, self.path, str(e))) dist = None if dist is not None and self.auto_upgrade: # A version of astropy-helpers was found on the available path, but # check to see if a bugfix release is available on PyPI upgrade = self._do_upgrade(dist) if upgrade is not None: dist = upgrade return dist def get_index_dist(self): if not self.download: log.warn('Downloading {0!r} disabled.'.format(DIST_NAME)) return None log.warn( "Downloading {0!r}; run setup.py with the --offline option to " "force offline installation.".format(DIST_NAME)) try: dist = self._do_download() except Exception as e: if DEBUG: raise log.warn( 'Failed to download and/or install {0!r} from {1!r}:\n' '{2}'.format(DIST_NAME, self.index_url, str(e))) dist = None # No need to run auto-upgrade here since we've already presumably # gotten the most up-to-date version from the package index return dist def _directory_import(self): """ Import astropy_helpers from the given path, which will be added to sys.path. Must return True if the import succeeded, and False otherwise. """ # Return True on success, False on failure but download is allowed, and # otherwise raise SystemExit path = os.path.abspath(self.path) # Use an empty WorkingSet rather than the man # pkg_resources.working_set, since on older versions of setuptools this # will invoke a VersionConflict when trying to install an upgrade ws = pkg_resources.WorkingSet([]) ws.add_entry(path) dist = ws.by_key.get(DIST_NAME) if dist is None: # We didn't find an egg-info/dist-info in the given path, but if a # setup.py exists we can generate it setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): # We use subprocess instead of run_setup from setuptools to # avoid segmentation faults - see the following for more details: # https://github.com/cython/cython/issues/2104 sp.check_output([sys.executable, 'setup.py', 'egg_info'], cwd=path) for dist in pkg_resources.find_distributions(path, True): # There should be only one... return dist return dist def _do_download(self, version='', find_links=None): if find_links: allow_hosts = '' index_url = None else: allow_hosts = None index_url = self.index_url # Annoyingly, setuptools will not handle other arguments to # Distribution (such as options) before handling setup_requires, so it # is not straightforward to programmatically augment the arguments which # are passed to easy_install class _Distribution(Distribution): def get_option_dict(self, command_name): opts = Distribution.get_option_dict(self, command_name) if command_name == 'easy_install': if find_links is not None: opts['find_links'] = ('setup script', find_links) if index_url is not None: opts['index_url'] = ('setup script', index_url) if allow_hosts is not None: opts['allow_hosts'] = ('setup script', allow_hosts) return opts if version: req = '{0}=={1}'.format(DIST_NAME, version) else: if UPPER_VERSION_EXCLUSIVE is None: req = DIST_NAME else: req = '{0}<{1}'.format(DIST_NAME, UPPER_VERSION_EXCLUSIVE) attrs = {'setup_requires': [req]} # NOTE: we need to parse the config file (e.g. setup.cfg) to make sure # it honours the options set in the [easy_install] section, and we need # to explicitly fetch the requirement eggs as setup_requires does not # get honored in recent versions of setuptools: # https://github.com/pypa/setuptools/issues/1273 try: context = _verbose if DEBUG else _silence with context(): dist = _Distribution(attrs=attrs) try: dist.parse_config_files(ignore_option_errors=True) dist.fetch_build_eggs(req) except TypeError: # On older versions of setuptools, ignore_option_errors # doesn't exist, and the above two lines are not needed # so we can just continue pass # If the setup_requires succeeded it will have added the new dist to # the main working_set return pkg_resources.working_set.by_key.get(DIST_NAME) except Exception as e: if DEBUG: raise msg = 'Error retrieving {0} from {1}:\n{2}' if find_links: source = find_links[0] elif index_url != INDEX_URL: source = index_url else: source = 'PyPI' raise Exception(msg.format(DIST_NAME, source, repr(e))) def _do_upgrade(self, dist): # Build up a requirement for a higher bugfix release but a lower minor # release (so API compatibility is guaranteed) next_version = _next_version(dist.parsed_version) req = pkg_resources.Requirement.parse( '{0}>{1},<{2}'.format(DIST_NAME, dist.version, next_version)) package_index = PackageIndex(index_url=self.index_url) upgrade = package_index.obtain(req) if upgrade is not None: return self._do_download(version=upgrade.version) def _check_submodule(self): """ Check if the given path is a git submodule. See the docstrings for ``_check_submodule_using_git`` and ``_check_submodule_no_git`` for further details. """ if (self.path is None or (os.path.exists(self.path) and not os.path.isdir(self.path))): return False if self.use_git: return self._check_submodule_using_git() else: return self._check_submodule_no_git() def _check_submodule_using_git(self): """ Check if the given path is a git submodule. If so, attempt to initialize and/or update the submodule if needed. This function makes calls to the ``git`` command in subprocesses. The ``_check_submodule_no_git`` option uses pure Python to check if the given path looks like a git submodule, but it cannot perform updates. """ cmd = ['git', 'submodule', 'status', '--', self.path] try: log.info('Running `{0}`; use the --no-git option to disable git ' 'commands'.format(' '.join(cmd))) returncode, stdout, stderr = run_cmd(cmd) except _CommandNotFound: # The git command simply wasn't found; this is most likely the # case on user systems that don't have git and are simply # trying to install the package from PyPI or a source # distribution. Silently ignore this case and simply don't try # to use submodules return False stderr = stderr.strip() if returncode != 0 and stderr: # Unfortunately the return code alone cannot be relied on, as # earlier versions of git returned 0 even if the requested submodule # does not exist # This is a warning that occurs in perl (from running git submodule) # which only occurs with a malformatted locale setting which can # happen sometimes on OSX. See again # https://github.com/astropy/astropy/issues/2749 perl_warning = ('perl: warning: Falling back to the standard locale ' '("C").') if not stderr.strip().endswith(perl_warning): # Some other unknown error condition occurred log.warn('git submodule command failed ' 'unexpectedly:\n{0}'.format(stderr)) return False # Output of `git submodule status` is as follows: # # 1: Status indicator: '-' for submodule is uninitialized, '+' if # submodule is initialized but is not at the commit currently indicated # in .gitmodules (and thus needs to be updated), or 'U' if the # submodule is in an unstable state (i.e. has merge conflicts) # # 2. SHA-1 hash of the current commit of the submodule (we don't really # need this information but it's useful for checking that the output is # correct) # # 3. The output of `git describe` for the submodule's current commit # hash (this includes for example what branches the commit is on) but # only if the submodule is initialized. We ignore this information for # now _git_submodule_status_re = re.compile( r'^(?P[+-U ])(?P[0-9a-f]{40}) ' r'(?P\S+)( .*)?$') # The stdout should only contain one line--the status of the # requested submodule m = _git_submodule_status_re.match(stdout) if m: # Yes, the path *is* a git submodule self._update_submodule(m.group('submodule'), m.group('status')) return True else: log.warn( 'Unexpected output from `git submodule status`:\n{0}\n' 'Will attempt import from {1!r} regardless.'.format( stdout, self.path)) return False def _check_submodule_no_git(self): """ Like ``_check_submodule_using_git``, but simply parses the .gitmodules file to determine if the supplied path is a git submodule, and does not exec any subprocesses. This can only determine if a path is a submodule--it does not perform updates, etc. This function may need to be updated if the format of the .gitmodules file is changed between git versions. """ gitmodules_path = os.path.abspath('.gitmodules') if not os.path.isfile(gitmodules_path): return False # This is a minimal reader for gitconfig-style files. It handles a few of # the quirks that make gitconfig files incompatible with ConfigParser-style # files, but does not support the full gitconfig syntax (just enough # needed to read a .gitmodules file). gitmodules_fileobj = io.StringIO() # Must use io.open for cross-Python-compatible behavior wrt unicode with io.open(gitmodules_path) as f: for line in f: # gitconfig files are more flexible with leading whitespace; just # go ahead and remove it line = line.lstrip() # comments can start with either # or ; if line and line[0] in (':', ';'): continue gitmodules_fileobj.write(line) gitmodules_fileobj.seek(0) cfg = RawConfigParser() try: cfg.readfp(gitmodules_fileobj) except Exception as exc: log.warn('Malformatted .gitmodules file: {0}\n' '{1} cannot be assumed to be a git submodule.'.format( exc, self.path)) return False for section in cfg.sections(): if not cfg.has_option(section, 'path'): continue submodule_path = cfg.get(section, 'path').rstrip(os.sep) if submodule_path == self.path.rstrip(os.sep): return True return False def _update_submodule(self, submodule, status): if status == ' ': # The submodule is up to date; no action necessary return elif status == '-': if self.offline: raise _AHBootstrapSystemExit( "Cannot initialize the {0} submodule in --offline mode; " "this requires being able to clone the submodule from an " "online repository.".format(submodule)) cmd = ['update', '--init'] action = 'Initializing' elif status == '+': cmd = ['update'] action = 'Updating' if self.offline: cmd.append('--no-fetch') elif status == 'U': raise _AHBootstrapSystemExit( 'Error: Submodule {0} contains unresolved merge conflicts. ' 'Please complete or abandon any changes in the submodule so that ' 'it is in a usable state, then try again.'.format(submodule)) else: log.warn('Unknown status {0!r} for git submodule {1!r}. Will ' 'attempt to use the submodule as-is, but try to ensure ' 'that the submodule is in a clean state and contains no ' 'conflicts or errors.\n{2}'.format(status, submodule, _err_help_msg)) return err_msg = None cmd = ['git', 'submodule'] + cmd + ['--', submodule] log.warn('{0} {1} submodule with: `{2}`'.format( action, submodule, ' '.join(cmd))) try: log.info('Running `{0}`; use the --no-git option to disable git ' 'commands'.format(' '.join(cmd))) returncode, stdout, stderr = run_cmd(cmd) except OSError as e: err_msg = str(e) else: if returncode != 0: err_msg = stderr if err_msg is not None: log.warn('An unexpected error occurred updating the git submodule ' '{0!r}:\n{1}\n{2}'.format(submodule, err_msg, _err_help_msg)) class _CommandNotFound(OSError): """ An exception raised when a command run with run_cmd is not found on the system. """ def run_cmd(cmd): """ Run a command in a subprocess, given as a list of command-line arguments. Returns a ``(returncode, stdout, stderr)`` tuple. """ try: p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE) # XXX: May block if either stdout or stderr fill their buffers; # however for the commands this is currently used for that is # unlikely (they should have very brief output) stdout, stderr = p.communicate() except OSError as e: if DEBUG: raise if e.errno == errno.ENOENT: msg = 'Command not found: `{0}`'.format(' '.join(cmd)) raise _CommandNotFound(msg, cmd) else: raise _AHBootstrapSystemExit( 'An unexpected error occurred when running the ' '`{0}` command:\n{1}'.format(' '.join(cmd), str(e))) # Can fail of the default locale is not configured properly. See # https://github.com/astropy/astropy/issues/2749. For the purposes under # consideration 'latin1' is an acceptable fallback. try: stdio_encoding = locale.getdefaultlocale()[1] or 'latin1' except ValueError: # Due to an OSX oddity locale.getdefaultlocale() can also crash # depending on the user's locale/language settings. See: # http://bugs.python.org/issue18378 stdio_encoding = 'latin1' # Unlikely to fail at this point but even then let's be flexible if not isinstance(stdout, _text_type): stdout = stdout.decode(stdio_encoding, 'replace') if not isinstance(stderr, _text_type): stderr = stderr.decode(stdio_encoding, 'replace') return (p.returncode, stdout, stderr) def _next_version(version): """ Given a parsed version from pkg_resources.parse_version, returns a new version string with the next minor version. Examples ======== >>> _next_version(pkg_resources.parse_version('1.2.3')) '1.3.0' """ if hasattr(version, 'base_version'): # New version parsing from setuptools >= 8.0 if version.base_version: parts = version.base_version.split('.') else: parts = [] else: parts = [] for part in version: if part.startswith('*'): break parts.append(part) parts = [int(p) for p in parts] if len(parts) < 3: parts += [0] * (3 - len(parts)) major, minor, micro = parts[:3] return '{0}.{1}.{2}'.format(major, minor + 1, 0) class _DummyFile(object): """A noop writeable object.""" errors = '' # Required for Python 3.x encoding = 'utf-8' def write(self, s): pass def flush(self): pass @contextlib.contextmanager def _verbose(): yield @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() exception_occurred = False try: yield except: exception_occurred = True # Go ahead and clean up so that exception handling can work normally sys.stdout = old_stdout sys.stderr = old_stderr raise if not exception_occurred: sys.stdout = old_stdout sys.stderr = old_stderr _err_help_msg = """ If the problem persists consider installing astropy_helpers manually using pip (`pip install astropy_helpers`) or by manually downloading the source archive, extracting it, and installing by running `python setup.py install` from the root of the extracted source code. """ class _AHBootstrapSystemExit(SystemExit): def __init__(self, *args): if not args: msg = 'An unknown problem occurred bootstrapping astropy_helpers.' else: msg = args[0] msg += '\n' + _err_help_msg super(_AHBootstrapSystemExit, self).__init__(msg, *args[1:]) BOOTSTRAPPER = _Bootstrapper.main() def use_astropy_helpers(**kwargs): """ Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- path : str or None, optional A filesystem path relative to the root of the project's source code that should be added to `sys.path` so that `astropy_helpers` can be imported from that path. If the path is a git submodule it will automatically be initialized and/or updated. The path may also be to a ``.tar.gz`` archive of the astropy_helpers source distribution. In this case the archive is automatically unpacked and made temporarily available on `sys.path` as a ``.egg`` archive. If `None` skip straight to downloading. download_if_needed : bool, optional If the provided filesystem path is not found an attempt will be made to download astropy_helpers from PyPI. It will then be made temporarily available on `sys.path` as a ``.egg`` archive (using the ``setup_requires`` feature of setuptools. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. index_url : str, optional If provided, use a different URL for the Python package index than the main PyPI server. use_git : bool, optional If `False` no git commands will be used--this effectively disables support for git submodules. If the ``--no-git`` option is given at the command line the value of this argument is overridden to `False`. auto_upgrade : bool, optional By default, when installing a package from a non-development source distribution ah_boostrap will try to automatically check for patch releases to astropy-helpers on PyPI and use the patched version over any bundled versions. Setting this to `False` will disable that functionality. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. offline : bool, optional If `False` disable all actions that require an internet connection, including downloading packages from the package index and fetching updates to any git submodule. Defaults to `True`. """ global BOOTSTRAPPER config = BOOTSTRAPPER.config config.update(**kwargs) # Create a new bootstrapper with the updated configuration and run it BOOTSTRAPPER = _Bootstrapper(**config) BOOTSTRAPPER.run() radio_beam-0.3.2/astropy_helpers/0000755000077000000240000000000013531324214017040 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/.travis.yml0000644000077000000240000000615413516112504021157 0ustar adamstaff00000000000000# We set the language to c because python isn't supported on the MacOS X nodes # on Travis. However, the language ends up being irrelevant anyway, since we # install Python ourselves using conda. language: c os: - osx - linux # Setting sudo to false opts in to Travis-CI container-based builds. sudo: false env: matrix: - PYTHON_VERSION=2.7 EVENT_TYPE='push pull_request cron' - PYTHON_VERSION=3.4 SETUPTOOLS_VERSION=20 - PYTHON_VERSION=3.5 - PYTHON_VERSION=3.6 - PYTHON_VERSION=3.7 SETUPTOOLS_VERSION=dev DEBUG=True CONDA_DEPENDENCIES='sphinx cython numpy six pytest-cov' EVENT_TYPE='push pull_request cron' global: - CONDA_DEPENDENCIES="setuptools sphinx cython numpy" - PIP_DEPENDENCIES="coveralls pytest-cov" - EVENT_TYPE='push pull_request' matrix: include: - os: linux env: PYTHON_VERSION=3.6 SPHINX_VERSION='>1.6' - os: linux env: PYTHON_VERSION=3.6 PIP_DEPENDENCIES='git+https://github.com/sphinx-doc/sphinx.git#egg=sphinx coveralls pytest-cov' CONDA_DEPENDENCIES="setuptools cython numpy" - os: linux env: PYTHON_VERSION=3.5 SPHINX_VERSION='<1.4' - os: linux env: PYTHON_VERSION=3.5 SPHINX_VERSION='<1.5' SETUPTOOLS_VERSION=27 - os: linux env: PYTHON_VERSION=3.6 SPHINX_VERSION='<1.6' SETUPTOOLS_VERSION=27 # Test without installing numpy beforehand to make sure everything works # without assuming numpy is already installed - os: linux env: PYTHON_VERSION=3.6 CONDA_DEPENDENCIES='sphinx cython six pytest-cov' # Uncomment the following if there are issues in setuptools that we # can't work around quickly - otherwise leave uncommented so that # we notice when things go wrong. # # allow_failures: # - env: PYTHON_VERSION=3.6 SETUPTOOLS_VERSION=dev DEBUG=True # CONDA_DEPENDENCIES='sphinx cython numpy six pytest-cov' # EVENT_TYPE='push pull_request cron' install: - git clone git://github.com/astropy/ci-helpers.git - source ci-helpers/travis/setup_conda.sh # We cannot install the developer version of setuptools using pip because # pip tries to remove the previous version of setuptools before the # installation is complete, which causes issues. Instead, we just install # setuptools manually. - if [[ $SETUPTOOLS_VERSION == dev ]]; then git clone http://github.com/pypa/setuptools.git; cd setuptools; python bootstrap.py; python setup.py install; cd ..; fi before_script: # Some of the tests use git commands that require a user to be configured - git config --global user.name "A U Thor" - git config --global user.email "author@example.com" script: # Use full path for coveragerc; see issue #193 - py.test --cov astropy_helpers --cov-config $(pwd)/astropy_helpers/tests/coveragerc astropy_helpers # In conftest.py we produce a .coverage.subprocess that contains coverage # statistics for sub-processes, so we combine it with the main one here. - mv .coverage .coverage.main - coverage combine .coverage.main .coverage.subprocess - coverage report after_success: - coveralls --rcfile=astropy_helpers/tests/coveragerc radio_beam-0.3.2/astropy_helpers/CHANGES.rst0000644000077000000240000004272313516112504020652 0ustar adamstaff00000000000000astropy-helpers Changelog ************************* 2.0.9 (2019-02-22) ------------------ - Updated bundled version of sphinx-automodapi to v0.10. [#439] - Updated bundled sphinx extensions version to sphinx-astropy v1.1.1. [#454] - Include package name in error message for Python version in ``ah_bootstrap.py``. [#441] 2.0.8 (2018-12-04) ------------------ - Fixed compatibility with Sphinx 1.8+. [#428] - Fixed error that occurs when installing a package in an environment where ``numpy`` is not already installed. [#404] - Updated bundled version of sphinx-automodapi to v0.9. [#422] - Updated bundled version of numpydoc to v0.8.0. [#423] 2.0.7 (2018-06-01) ------------------ - Removing ez_setup.py file and requiring setuptools 1.0 or later. [#384] 2.0.6 (2018-02-24) ------------------ - Avoid deprecation warning due to ``exclude=`` keyword in ``setup.py``. [#379] 2.0.5 (2018-02-22) ------------------ - Fix segmentation faults that occurred when the astropy-helpers submodule was first initialized in packages that also contained Cython code. [#375] 2.0.4 (2018-02-09) ------------------ - Support dotted package names as namespace packages in generate_version_py. [#370] - Fix compatibility with setuptools 36.x and above. [#372] - Fix false negative in add_openmp_flags_if_available when measuring code coverage with gcc. [#374] 2.0.3 (2018-01-20) ------------------ - Make sure that astropy-helpers 3.x.x is not downloaded on Python 2. [#363] - The bundled version of sphinx-automodapi has been updated to v0.7. [#365] - Add --auto-use and --no-auto-use command-line flags to match the ``auto_use`` configuration option, and add an alias ``--use-system-astropy-helpers`` for ``--no-auto-use``. [#366] 2.0.2 (2017-10-13) ------------------ - Added new helper function add_openmp_flags_if_available that can add OpenMP compilation flags to a C/Cython extension if needed. [#346] - Update numpydoc to v0.7. [#343] - The function ``get_git_devstr`` now returns ``'0'`` instead of ``None`` when no git repository is present. This allows generation of development version strings that are in a format that ``setuptools`` expects (e.g. "1.1.3.dev0" instead of "1.1.3.dev"). [#330] - It is now possible to override generated timestamps to make builds reproducible by setting the ``SOURCE_DATE_EPOCH`` environment variable [#341] - Mark Sphinx extensions as parallel-safe. [#344] - Switch to using mathjax instead of imgmath for local builds. [#342] - Deprecate ``exclude`` parameter of various functions in setup_helpers since it could not work as intended. Add new function ``add_exclude_packages`` to provide intended behavior. [#331] - Allow custom Sphinx doctest extension to recognize and process standard doctest directives ``testsetup`` and ``doctest``. [#335] 2.0.1 (2017-07-28) ------------------ - Fix compatibility with Sphinx <1.5. [#326] 2.0 (2017-07-06) ---------------- - Add support for package that lies in a subdirectory. [#249] - Removing ``compat.subprocess``. [#298] - Python 3.3 is no longer supported. [#300] - The 'automodapi' Sphinx extension (and associated dependencies) has now been moved to a standalone package which can be found at https://github.com/astropy/sphinx-automodapi - this is now bundled in astropy-helpers under astropy_helpers.extern.automodapi for convenience. Version shipped with astropy-helpers is v0.6. [#278, #303, #309, #323] - The ``numpydoc`` Sphinx extension has now been moved to ``astropy_helpers.extern``. [#278] - Fix ``build_docs`` error catching, so it doesn't hide Sphinx errors. [#292] - Fix compatibility with Sphinx 1.6. [#318] - Updating ez_setup.py to the last version before it's removal. [#321] 1.3.1 (2017-03-18) ------------------ - Fixed the missing button to hide output in documentation code blocks. [#287] - Fixed bug when ``build_docs`` when running with the clean (-l) option. [#289] - Add alternative location for various intersphinx inventories to fall back to. [#293] 1.3 (2016-12-16) ---------------- - ``build_sphinx`` has been deprecated in favor of the ``build_docs`` command. [#246] - Force the use of Cython's old ``build_ext`` command. A new ``build_ext`` command was added in Cython 0.25, but it does not work with astropy-helpers currently. [#261] 1.2 (2016-06-18) ---------------- - Added sphinx configuration value ``automodsumm_inherited_members``. If ``True`` this will include members that are inherited from a base class in the generated API docs. Defaults to ``False`` which matches the previous behavior. [#215] - Fixed ``build_sphinx`` to recognize builds that succeeded but have output *after* the "build succeeded." statement. This only applies when ``--warnings-returncode`` is given (which is primarily relevant for Travis documentation builds). [#223] - Fixed ``build_sphinx`` the sphinx extensions to not output a spurious warning for sphinx versions > 1.4. [#229] - Add Python version dependent local sphinx inventories that contain otherwise missing references. [#216] - ``astropy_helpers`` now require Sphinx 1.3 or later. [#226] 1.1.2 (2016-03-9) ----------------- - The CSS for the sphinx documentation was altered to prevent some text overflow problems. [#217] 1.1.1 (2015-12-23) ------------------ - Fixed crash in build with ``AttributeError: cython_create_listing`` with older versions of setuptools. [#209, #210] 1.1 (2015-12-10) ---------------- - The original ``AstropyTest`` class in ``astropy_helpers``, which implements the ``setup.py test`` command, is deprecated in favor of moving the implementation of that command closer to the actual Astropy test runner in ``astropy.tests``. Now a dummy ``test`` command is provided solely for informing users that they need ``astropy`` installed to run the tests (however, the previous, now deprecated implementation is still provided and continues to work with older versions of Astropy). See the related issue for more details. [#184] - Added a useful new utility function to ``astropy_helpers.utils`` called ``find_data_files``. This is similar to the ``find_packages`` function in setuptools in that it can be used to search a package for data files (matching a pattern) that can be passed to the ``package_data`` argument for ``setup()``. See the docstring to ``astropy_helpers.utils.find_data_files`` for more details. [#42] - The ``astropy_helpers`` module now sets the global ``_ASTROPY_SETUP_`` flag upon import (from within a ``setup.py``) script, so it's not necessary to have this in the ``setup.py`` script explicitly. If in doubt though, there's no harm in setting it twice. Putting it in ``astropy_helpers`` just ensures that any other imports that occur during build will have this flag set. [#191] - It is now possible to use Cython as a ``setup_requires`` build requirement, and still build Cython extensions even if Cython wasn't available at the beginning of the build processes (that is, is automatically downloaded via setuptools' processing of ``setup_requires``). [#185] - Moves the ``adjust_compiler`` check into the ``build_ext`` command itself, so it's only used when actually building extension modules. This also deprecates the stand-alone ``adjust_compiler`` function. [#76] - When running the ``build_sphinx`` / ``build_docs`` command with the ``-w`` option, the output from Sphinx is streamed as it runs instead of silently buffering until the doc build is complete. [#197] 1.0.7 (unreleased) ------------------ - Fix missing import in ``astropy_helpers/utils.py``. [#196] 1.0.6 (2015-12-04) ------------------ - Fixed bug where running ``./setup.py build_sphinx`` could return successfully even when the build was not successful (and should have returned a non-zero error code). [#199] 1.0.5 (2015-10-02) ------------------ - Fixed a regression in the ``./setup.py test`` command that was introduced in v1.0.4. 1.0.4 (2015-10-02) ------------------ - Fixed issue with the sphinx documentation css where the line numbers for code blocks were not aligned with the code. [#179, #180] - Fixed crash that could occur when trying to build Cython extension modules when Cython isn't installed. Normally this still results in a failed build, but was supposed to provide a useful error message rather than crash outright (this was a regression introduced in v1.0.3). [#181] - Fixed a crash that could occur on Python 3 when a working C compiler isn't found. [#182] - Quieted warnings about deprecated Numpy API in Cython extensions, when building Cython extensions against Numpy >= 1.7. [#183, #186] - Improved support for py.test >= 2.7--running the ``./setup.py test`` command now copies all doc pages into the temporary test directory as well, so that all test files have a "common root directory". [#189, #190] 1.0.3 (2015-07-22) ------------------ - Added workaround for sphinx-doc/sphinx#1843, a but in Sphinx which prevented descriptor classes with a custom metaclass from being documented correctly. [#158] - Added an alias for the ``./setup.py build_sphinx`` command as ``./setup.py build_docs`` which, to a new contributor, should hopefully be less cryptic. [#161] - The fonts in graphviz diagrams now match the font of the HTML content. [#169] - When the documentation is built on readthedocs.org, MathJax will be used for math rendering. When built elsewhere, the "pngmath" extension is still used for math rendering. [#170] - Fix crash when importing astropy_helpers when running with ``python -OO`` [#171] - The ``build`` and ``build_ext`` stages now correctly recognize the presence of C++ files in Cython extensions (previously only vanilla C worked). [#173] 1.0.2 (2015-04-02) ------------------ - Various fixes enabling the astropy-helpers Sphinx build command and Sphinx extensions to work with Sphinx 1.3. [#148] - More improvement to the ability to handle multiple versions of astropy-helpers being imported in the same Python interpreter session in the (somewhat rare) case of nested installs. [#147] - To better support high resolution displays, use SVG for the astropy logo and linkout image, falling back to PNGs for browsers that support it. [#150, #151] - Improve ``setup_helpers.get_compiler_version`` to work with more compilers, and to return more info. This will help fix builds of Astropy on less common compilers, like Sun C. [#153] 1.0.1 (2015-03-04) ------------------ - Released in concert with v0.4.8 to address the same issues. 0.4.8 (2015-03-04) ------------------ - Improved the ``ah_bootstrap`` script's ability to override existing installations of astropy-helpers with new versions in the context of installing multiple packages simultaneously within the same Python interpreter (e.g. when one package has in its ``setup_requires`` another package that uses a different version of astropy-helpers. [#144] - Added a workaround to an issue in matplotlib that can, in rare cases, lead to a crash when installing packages that import matplotlib at build time. [#144] 1.0 (2015-02-17) ---------------- - Added new pre-/post-command hook points for ``setup.py`` commands. Now any package can define code to run before and/or after any ``setup.py`` command without having to manually subclass that command by adding ``pre__hook`` and ``post__hook`` callables to the package's ``setup_package.py`` module. See the PR for more details. [#112] - The following objects in the ``astropy_helpers.setup_helpers`` module have been relocated: - ``get_dummy_distribution``, ``get_distutils_*``, ``get_compiler_option``, ``add_command_option``, ``is_distutils_display_option`` -> ``astropy_helpers.distutils_helpers`` - ``should_build_with_cython``, ``generate_build_ext_command`` -> ``astropy_helpers.commands.build_ext`` - ``AstropyBuildPy`` -> ``astropy_helpers.commands.build_py`` - ``AstropyBuildSphinx`` -> ``astropy_helpers.commands.build_sphinx`` - ``AstropyInstall`` -> ``astropy_helpers.commands.install`` - ``AstropyInstallLib`` -> ``astropy_helpers.commands.install_lib`` - ``AstropyRegister`` -> ``astropy_helpers.commands.register`` - ``get_pkg_version_module`` -> ``astropy_helpers.version_helpers`` - ``write_if_different``, ``import_file``, ``get_numpy_include_path`` -> ``astropy_helpers.utils`` All of these are "soft" deprecations in the sense that they are still importable from ``astropy_helpers.setup_helpers`` for now, and there is no (easy) way to produce deprecation warnings when importing these objects from ``setup_helpers`` rather than directly from the modules they are defined in. But please consider updating any imports to these objects. [#110] - Use of the ``astropy.sphinx.ext.astropyautosummary`` extension is deprecated for use with Sphinx < 1.2. Instead it should suffice to remove this extension for the ``extensions`` list in your ``conf.py`` and add the stock ``sphinx.ext.autosummary`` instead. [#131] 0.4.7 (2015-02-17) ------------------ - Fixed incorrect/missing git hash being added to the generated ``version.py`` when creating a release. [#141] 0.4.6 (2015-02-16) ------------------ - Fixed problems related to the automatically generated _compiler module not being created properly. [#139] 0.4.5 (2015-02-11) ------------------ - Fixed an issue where ah_bootstrap.py could blow up when astropy_helper's version number is 1.0. - Added a workaround for documentation of properties in the rare case where the class's metaclass has a property of the same name. [#130] - Fixed an issue on Python 3 where importing a package using astropy-helper's generated version.py module would crash when the current working directory is an empty git repository. [#114, #137] - Fixed an issue where the "revision count" appended to .dev versions by the generated version.py did not accurately reflect the revision count for the package it belongs to, and could be invalid if the current working directory is an unrelated git repository. [#107, #137] - Likewise, fixed a confusing warning message that could occur in the same circumstances as the above issue. [#121, #137] 0.4.4 (2014-12-31) ------------------ - More improvements for building the documentation using Python 3.x. [#100] - Additional minor fixes to Python 3 support. [#115] - Updates to support new test features in Astropy [#92, #106] 0.4.3 (2014-10-22) ------------------ - The generated ``version.py`` file now preserves the git hash of installed copies of the package as well as when building a source distribution. That is, the git hash of the changeset that was installed/released is preserved. [#87] - In smart resolver add resolution for class links when they exist in the intersphinx inventory, but not the mapping of the current package (e.g. when an affiliated package uses an astropy core class of which "actual" and "documented" location differs) [#88] - Fixed a bug that could occur when running ``setup.py`` for the first time in a repository that uses astropy-helpers as a submodule: ``AttributeError: 'NoneType' object has no attribute 'mkdtemp'`` [#89] - Fixed a bug where optional arguments to the ``doctest-skip`` Sphinx directive were sometimes being left in the generated documentation output. [#90] - Improved support for building the documentation using Python 3.x. [#96] - Avoid error message if .git directory is not present. [#91] 0.4.2 (2014-08-09) ------------------ - Fixed some CSS issues in generated API docs. [#69] - Fixed the warning message that could be displayed when generating a version number with some older versions of git. [#77] - Fixed automodsumm to work with new versions of Sphinx (>= 1.2.2). [#80] 0.4.1 (2014-08-08) ------------------ - Fixed git revision count on systems with git versions older than v1.7.2. [#70] - Fixed display of warning text when running a git command fails (previously the output of stderr was not being decoded properly). [#70] - The ``--offline`` flag to ``setup.py`` understood by ``ah_bootstrap.py`` now also prevents git from going online to fetch submodule updates. [#67] - The Sphinx extension for converting issue numbers to links in the changelog now supports working on arbitrary pages via a new ``conf.py`` setting: ``changelog_links_docpattern``. By default it affects the ``changelog`` and ``whatsnew`` pages in one's Sphinx docs. [#61] - Fixed crash that could result from users with missing/misconfigured locale settings. [#58] - The font used for code examples in the docs is now the system-defined ``monospace`` font, rather than ``Minaco``, which is not available on all platforms. [#50] 0.4 (2014-07-15) ---------------- - Initial release of astropy-helpers. See `APE4 `_ for details of the motivation and design of this package. - The ``astropy_helpers`` package replaces the following modules in the ``astropy`` package: - ``astropy.setup_helpers`` -> ``astropy_helpers.setup_helpers`` - ``astropy.version_helpers`` -> ``astropy_helpers.version_helpers`` - ``astropy.sphinx`` - > ``astropy_helpers.sphinx`` These modules should be considered deprecated in ``astropy``, and any new, non-critical changes to those modules will be made in ``astropy_helpers`` instead. Affiliated packages wishing to make use those modules (as in the Astropy package-template) should use the versions from ``astropy_helpers`` instead, and include the ``ah_bootstrap.py`` script in their project, for bootstrapping the ``astropy_helpers`` package in their setup.py script. radio_beam-0.3.2/astropy_helpers/CONTRIBUTING.md0000644000077000000240000000216512711231150021270 0ustar adamstaff00000000000000Contributing to astropy-helpers =============================== The guidelines for contributing to ``astropy-helpers`` are generally the same as the [contributing guidelines for the astropy core package](http://github.com/astropy/astropy/blob/master/CONTRIBUTING.md). Basically, report relevant issues in the ``astropy-helpers`` issue tracker, and we welcome pull requests that broadly follow the [Astropy coding guidelines](http://docs.astropy.org/en/latest/development/codeguide.html). The key subtlety lies in understanding the relationship between ``astropy`` and ``astropy-helpers``. This package contains the build, installation, and documentation tools used by astropy. It also includes support for the ``setup.py test`` command, though Astropy is still required for this to function (it does not currently include the full Astropy test runner). So issues or improvements to that functionality should be addressed in this package. Any other aspect of the [astropy core package](http://github.com/astropy/astropy) (or any other package that uses ``astropy-helpers``) should be addressed in the github repository for that package. radio_beam-0.3.2/astropy_helpers/LICENSE.rst0000644000077000000240000000272312711231150020653 0ustar adamstaff00000000000000Copyright (c) 2014, Astropy Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Astropy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. radio_beam-0.3.2/astropy_helpers/MANIFEST.in0000644000077000000240000000025413516112504020577 0ustar adamstaff00000000000000include README.rst include CHANGES.rst include LICENSE.rst recursive-include licenses * include ah_bootstrap.py exclude *.pyc *.o prune build prune astropy_helpers/tests radio_beam-0.3.2/astropy_helpers/README.rst0000644000077000000240000000503313234725027020537 0ustar adamstaff00000000000000astropy-helpers =============== * Stable versions: https://pypi.org/project/astropy-helpers/ * Development version, issue tracker: https://github.com/astropy/astropy-helpers This project provides a Python package, ``astropy_helpers``, which includes many build, installation, and documentation-related tools used by the Astropy project, but packaged separately for use by other projects that wish to leverage this work. The motivation behind this package and details of its implementation are in the accepted `Astropy Proposal for Enhancement (APE) 4 `_. The ``astropy_helpers.extern`` sub-module includes modules developed elsewhere that are bundled here for convenience. At the moment, this consists of the following two sphinx extensions: * `numpydoc `_, a Sphinx extension developed as part of the Numpy project. This is used to parse docstrings in Numpy format * `sphinx-automodapi `_, a Sphinx extension developed as part of the Astropy project. This used to be developed directly in ``astropy-helpers`` but is now a standalone package. Issues with these sub-modules should be reported in their respective repositories, and we will regularly update the bundled versions to reflect the latest released versions. ``astropy_helpers`` includes a special "bootstrap" module called ``ah_bootstrap.py`` which is intended to be used by a project's setup.py in order to ensure that the ``astropy_helpers`` package is available for build/installation. This is similar to the ``ez_setup.py`` module that is shipped with some projects to bootstrap `setuptools `_. As described in APE4, the version numbers for ``astropy_helpers`` follow the corresponding major/minor version of the `astropy core package `_, but with an independent sequence of micro (bugfix) version numbers. Hence, the initial release is 0.4, in parallel with Astropy v0.4, which will be the first version of Astropy to use ``astropy-helpers``. For examples of how to implement ``astropy-helpers`` in a project, see the ``setup.py`` and ``setup.cfg`` files of the `Affiliated package template `_. .. image:: https://travis-ci.org/astropy/astropy-helpers.svg :target: https://travis-ci.org/astropy/astropy-helpers .. image:: https://coveralls.io/repos/astropy/astropy-helpers/badge.svg :target: https://coveralls.io/r/astropy/astropy-helpers radio_beam-0.3.2/astropy_helpers/ah_bootstrap.py0000644000077000000240000011076013516112504022104 0ustar adamstaff00000000000000""" This bootstrap module contains code for ensuring that the astropy_helpers package will be importable by the time the setup.py script runs. It also includes some workarounds to ensure that a recent-enough version of setuptools is being used for the installation. This module should be the first thing imported in the setup.py of distributions that make use of the utilities in astropy_helpers. If the distribution ships with its own copy of astropy_helpers, this module will first attempt to import from the shipped copy. However, it will also check PyPI to see if there are any bug-fix releases on top of the current version that may be useful to get past platform-specific bugs that have been fixed. When running setup.py, use the ``--offline`` command-line option to disable the auto-upgrade checks. When this module is imported or otherwise executed it automatically calls a main function that attempts to read the project's setup.cfg file, which it checks for a configuration section called ``[ah_bootstrap]`` the presences of that section, and options therein, determine the next step taken: If it contains an option called ``auto_use`` with a value of ``True``, it will automatically call the main function of this module called `use_astropy_helpers` (see that function's docstring for full details). Otherwise no further action is taken and by default the system-installed version of astropy-helpers will be used (however, ``ah_bootstrap.use_astropy_helpers`` may be called manually from within the setup.py script). This behavior can also be controlled using the ``--auto-use`` and ``--no-auto-use`` command-line flags. For clarity, an alias for ``--no-auto-use`` is ``--use-system-astropy-helpers``, and we recommend using the latter if needed. Additional options in the ``[ah_boostrap]`` section of setup.cfg have the same names as the arguments to `use_astropy_helpers`, and can be used to configure the bootstrap script when ``auto_use = True``. See https://github.com/astropy/astropy-helpers for more details, and for the latest version of this module. """ import contextlib import errno import io import locale import os import re import subprocess as sp import sys from distutils import log from distutils.debug import DEBUG try: from ConfigParser import ConfigParser, RawConfigParser except ImportError: from configparser import ConfigParser, RawConfigParser import pkg_resources from setuptools import Distribution from setuptools.package_index import PackageIndex # This is the minimum Python version required for astropy-helpers __minimum_python_version__ = (2, 7) if sys.version_info[0] < 3: _str_types = (str, unicode) _text_type = unicode PY3 = False else: _str_types = (str, bytes) _text_type = str PY3 = True # TODO: Maybe enable checking for a specific version of astropy_helpers? DIST_NAME = 'astropy-helpers' PACKAGE_NAME = 'astropy_helpers' if PY3: UPPER_VERSION_EXCLUSIVE = None else: UPPER_VERSION_EXCLUSIVE = '3' # Defaults for other options DOWNLOAD_IF_NEEDED = True INDEX_URL = 'https://pypi.python.org/simple' USE_GIT = True OFFLINE = False AUTO_UPGRADE = True # A list of all the configuration options and their required types CFG_OPTIONS = [ ('auto_use', bool), ('path', str), ('download_if_needed', bool), ('index_url', str), ('use_git', bool), ('offline', bool), ('auto_upgrade', bool) ] # Start off by parsing the setup.cfg file SETUP_CFG = ConfigParser() if os.path.exists('setup.cfg'): try: SETUP_CFG.read('setup.cfg') except Exception as e: if DEBUG: raise log.error( "Error reading setup.cfg: {0!r}\n{1} will not be " "automatically bootstrapped and package installation may fail." "\n{2}".format(e, PACKAGE_NAME, _err_help_msg)) # We used package_name in the package template for a while instead of name if SETUP_CFG.has_option('metadata', 'name'): parent_package = SETUP_CFG.get('metadata', 'name') elif SETUP_CFG.has_option('metadata', 'package_name'): parent_package = SETUP_CFG.get('metadata', 'package_name') else: parent_package = None if SETUP_CFG.has_option('options', 'python_requires'): python_requires = SETUP_CFG.get('options', 'python_requires') # The python_requires key has a syntax that can be parsed by SpecifierSet # in the packaging package. However, we don't want to have to depend on that # package, so instead we can use setuptools (which bundles packaging). We # have to add 'python' to parse it with Requirement. from pkg_resources import Requirement req = Requirement.parse('python' + python_requires) # We want the Python version as a string, which we can get from the platform module import platform python_version = platform.python_version() if not req.specifier.contains(python_version): if parent_package is None: print("ERROR: Python {} is required by this package".format(req.specifier)) else: print("ERROR: Python {} is required by {}".format(req.specifier, parent_package)) sys.exit(1) if sys.version_info < __minimum_python_version__: if parent_package is None: print("ERROR: Python {} or later is required by astropy-helpers".format( __minimum_python_version__)) else: print("ERROR: Python {} or later is required by astropy-helpers for {}".format( __minimum_python_version__, parent_package)) sys.exit(1) # What follows are several import statements meant to deal with install-time # issues with either missing or misbehaving pacakges (including making sure # setuptools itself is installed): # Check that setuptools 1.0 or later is present from distutils.version import LooseVersion try: import setuptools assert LooseVersion(setuptools.__version__) >= LooseVersion('1.0') except (ImportError, AssertionError): print("ERROR: setuptools 1.0 or later is required by astropy-helpers") sys.exit(1) # typing as a dependency for 1.6.1+ Sphinx causes issues when imported after # initializing submodule with ah_boostrap.py # See discussion and references in # https://github.com/astropy/astropy-helpers/issues/302 try: import typing # noqa except ImportError: pass # Note: The following import is required as a workaround to # https://github.com/astropy/astropy-helpers/issues/89; if we don't import this # module now, it will get cleaned up after `run_setup` is called, but that will # later cause the TemporaryDirectory class defined in it to stop working when # used later on by setuptools try: import setuptools.py31compat # noqa except ImportError: pass # matplotlib can cause problems if it is imported from within a call of # run_setup(), because in some circumstances it will try to write to the user's # home directory, resulting in a SandboxViolation. See # https://github.com/matplotlib/matplotlib/pull/4165 # Making sure matplotlib, if it is available, is imported early in the setup # process can mitigate this (note importing matplotlib.pyplot has the same # issue) try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot except: # Ignore if this fails for *any* reason* pass # End compatibility imports... class _Bootstrapper(object): """ Bootstrapper implementation. See ``use_astropy_helpers`` for parameter documentation. """ def __init__(self, path=None, index_url=None, use_git=None, offline=None, download_if_needed=None, auto_upgrade=None): if path is None: path = PACKAGE_NAME if not (isinstance(path, _str_types) or path is False): raise TypeError('path must be a string or False') if PY3 and not isinstance(path, _text_type): fs_encoding = sys.getfilesystemencoding() path = path.decode(fs_encoding) # path to unicode self.path = path # Set other option attributes, using defaults where necessary self.index_url = index_url if index_url is not None else INDEX_URL self.offline = offline if offline is not None else OFFLINE # If offline=True, override download and auto-upgrade if self.offline: download_if_needed = False auto_upgrade = False self.download = (download_if_needed if download_if_needed is not None else DOWNLOAD_IF_NEEDED) self.auto_upgrade = (auto_upgrade if auto_upgrade is not None else AUTO_UPGRADE) # If this is a release then the .git directory will not exist so we # should not use git. git_dir_exists = os.path.exists(os.path.join(os.path.dirname(__file__), '.git')) if use_git is None and not git_dir_exists: use_git = False self.use_git = use_git if use_git is not None else USE_GIT # Declared as False by default--later we check if astropy-helpers can be # upgraded from PyPI, but only if not using a source distribution (as in # the case of import from a git submodule) self.is_submodule = False @classmethod def main(cls, argv=None): if argv is None: argv = sys.argv config = cls.parse_config() config.update(cls.parse_command_line(argv)) auto_use = config.pop('auto_use', False) bootstrapper = cls(**config) if auto_use: # Run the bootstrapper, otherwise the setup.py is using the old # use_astropy_helpers() interface, in which case it will run the # bootstrapper manually after reconfiguring it. bootstrapper.run() return bootstrapper @classmethod def parse_config(cls): if not SETUP_CFG.has_section('ah_bootstrap'): return {} config = {} for option, type_ in CFG_OPTIONS: if not SETUP_CFG.has_option('ah_bootstrap', option): continue if type_ is bool: value = SETUP_CFG.getboolean('ah_bootstrap', option) else: value = SETUP_CFG.get('ah_bootstrap', option) config[option] = value return config @classmethod def parse_command_line(cls, argv=None): if argv is None: argv = sys.argv config = {} # For now we just pop recognized ah_bootstrap options out of the # arg list. This is imperfect; in the unlikely case that a setup.py # custom command or even custom Distribution class defines an argument # of the same name then we will break that. However there's a catch22 # here that we can't just do full argument parsing right here, because # we don't yet know *how* to parse all possible command-line arguments. if '--no-git' in argv: config['use_git'] = False argv.remove('--no-git') if '--offline' in argv: config['offline'] = True argv.remove('--offline') if '--auto-use' in argv: config['auto_use'] = True argv.remove('--auto-use') if '--no-auto-use' in argv: config['auto_use'] = False argv.remove('--no-auto-use') if '--use-system-astropy-helpers' in argv: config['auto_use'] = False argv.remove('--use-system-astropy-helpers') return config def run(self): strategies = ['local_directory', 'local_file', 'index'] dist = None # First, remove any previously imported versions of astropy_helpers; # this is necessary for nested installs where one package's installer # is installing another package via setuptools.sandbox.run_setup, as in # the case of setup_requires for key in list(sys.modules): try: if key == PACKAGE_NAME or key.startswith(PACKAGE_NAME + '.'): del sys.modules[key] except AttributeError: # Sometimes mysterious non-string things can turn up in # sys.modules continue # Check to see if the path is a submodule self.is_submodule = self._check_submodule() for strategy in strategies: method = getattr(self, 'get_{0}_dist'.format(strategy)) dist = method() if dist is not None: break else: raise _AHBootstrapSystemExit( "No source found for the {0!r} package; {0} must be " "available and importable as a prerequisite to building " "or installing this package.".format(PACKAGE_NAME)) # This is a bit hacky, but if astropy_helpers was loaded from a # directory/submodule its Distribution object gets a "precedence" of # "DEVELOP_DIST". However, in other cases it gets a precedence of # "EGG_DIST". However, when activing the distribution it will only be # placed early on sys.path if it is treated as an EGG_DIST, so always # do that dist = dist.clone(precedence=pkg_resources.EGG_DIST) # Otherwise we found a version of astropy-helpers, so we're done # Just active the found distribution on sys.path--if we did a # download this usually happens automatically but it doesn't hurt to # do it again # Note: Adding the dist to the global working set also activates it # (makes it importable on sys.path) by default. try: pkg_resources.working_set.add(dist, replace=True) except TypeError: # Some (much) older versions of setuptools do not have the # replace=True option here. These versions are old enough that all # bets may be off anyways, but it's easy enough to work around just # in case... if dist.key in pkg_resources.working_set.by_key: del pkg_resources.working_set.by_key[dist.key] pkg_resources.working_set.add(dist) @property def config(self): """ A `dict` containing the options this `_Bootstrapper` was configured with. """ return dict((optname, getattr(self, optname)) for optname, _ in CFG_OPTIONS if hasattr(self, optname)) def get_local_directory_dist(self): """ Handle importing a vendored package from a subdirectory of the source distribution. """ if not os.path.isdir(self.path): return log.info('Attempting to import astropy_helpers from {0} {1!r}'.format( 'submodule' if self.is_submodule else 'directory', self.path)) dist = self._directory_import() if dist is None: log.warn( 'The requested path {0!r} for importing {1} does not ' 'exist, or does not contain a copy of the {1} ' 'package.'.format(self.path, PACKAGE_NAME)) elif self.auto_upgrade and not self.is_submodule: # A version of astropy-helpers was found on the available path, but # check to see if a bugfix release is available on PyPI upgrade = self._do_upgrade(dist) if upgrade is not None: dist = upgrade return dist def get_local_file_dist(self): """ Handle importing from a source archive; this also uses setup_requires but points easy_install directly to the source archive. """ if not os.path.isfile(self.path): return log.info('Attempting to unpack and import astropy_helpers from ' '{0!r}'.format(self.path)) try: dist = self._do_download(find_links=[self.path]) except Exception as e: if DEBUG: raise log.warn( 'Failed to import {0} from the specified archive {1!r}: ' '{2}'.format(PACKAGE_NAME, self.path, str(e))) dist = None if dist is not None and self.auto_upgrade: # A version of astropy-helpers was found on the available path, but # check to see if a bugfix release is available on PyPI upgrade = self._do_upgrade(dist) if upgrade is not None: dist = upgrade return dist def get_index_dist(self): if not self.download: log.warn('Downloading {0!r} disabled.'.format(DIST_NAME)) return None log.warn( "Downloading {0!r}; run setup.py with the --offline option to " "force offline installation.".format(DIST_NAME)) try: dist = self._do_download() except Exception as e: if DEBUG: raise log.warn( 'Failed to download and/or install {0!r} from {1!r}:\n' '{2}'.format(DIST_NAME, self.index_url, str(e))) dist = None # No need to run auto-upgrade here since we've already presumably # gotten the most up-to-date version from the package index return dist def _directory_import(self): """ Import astropy_helpers from the given path, which will be added to sys.path. Must return True if the import succeeded, and False otherwise. """ # Return True on success, False on failure but download is allowed, and # otherwise raise SystemExit path = os.path.abspath(self.path) # Use an empty WorkingSet rather than the man # pkg_resources.working_set, since on older versions of setuptools this # will invoke a VersionConflict when trying to install an upgrade ws = pkg_resources.WorkingSet([]) ws.add_entry(path) dist = ws.by_key.get(DIST_NAME) if dist is None: # We didn't find an egg-info/dist-info in the given path, but if a # setup.py exists we can generate it setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): # We use subprocess instead of run_setup from setuptools to # avoid segmentation faults - see the following for more details: # https://github.com/cython/cython/issues/2104 sp.check_output([sys.executable, 'setup.py', 'egg_info'], cwd=path) for dist in pkg_resources.find_distributions(path, True): # There should be only one... return dist return dist def _do_download(self, version='', find_links=None): if find_links: allow_hosts = '' index_url = None else: allow_hosts = None index_url = self.index_url # Annoyingly, setuptools will not handle other arguments to # Distribution (such as options) before handling setup_requires, so it # is not straightforward to programmatically augment the arguments which # are passed to easy_install class _Distribution(Distribution): def get_option_dict(self, command_name): opts = Distribution.get_option_dict(self, command_name) if command_name == 'easy_install': if find_links is not None: opts['find_links'] = ('setup script', find_links) if index_url is not None: opts['index_url'] = ('setup script', index_url) if allow_hosts is not None: opts['allow_hosts'] = ('setup script', allow_hosts) return opts if version: req = '{0}=={1}'.format(DIST_NAME, version) else: if UPPER_VERSION_EXCLUSIVE is None: req = DIST_NAME else: req = '{0}<{1}'.format(DIST_NAME, UPPER_VERSION_EXCLUSIVE) attrs = {'setup_requires': [req]} # NOTE: we need to parse the config file (e.g. setup.cfg) to make sure # it honours the options set in the [easy_install] section, and we need # to explicitly fetch the requirement eggs as setup_requires does not # get honored in recent versions of setuptools: # https://github.com/pypa/setuptools/issues/1273 try: context = _verbose if DEBUG else _silence with context(): dist = _Distribution(attrs=attrs) try: dist.parse_config_files(ignore_option_errors=True) dist.fetch_build_eggs(req) except TypeError: # On older versions of setuptools, ignore_option_errors # doesn't exist, and the above two lines are not needed # so we can just continue pass # If the setup_requires succeeded it will have added the new dist to # the main working_set return pkg_resources.working_set.by_key.get(DIST_NAME) except Exception as e: if DEBUG: raise msg = 'Error retrieving {0} from {1}:\n{2}' if find_links: source = find_links[0] elif index_url != INDEX_URL: source = index_url else: source = 'PyPI' raise Exception(msg.format(DIST_NAME, source, repr(e))) def _do_upgrade(self, dist): # Build up a requirement for a higher bugfix release but a lower minor # release (so API compatibility is guaranteed) next_version = _next_version(dist.parsed_version) req = pkg_resources.Requirement.parse( '{0}>{1},<{2}'.format(DIST_NAME, dist.version, next_version)) package_index = PackageIndex(index_url=self.index_url) upgrade = package_index.obtain(req) if upgrade is not None: return self._do_download(version=upgrade.version) def _check_submodule(self): """ Check if the given path is a git submodule. See the docstrings for ``_check_submodule_using_git`` and ``_check_submodule_no_git`` for further details. """ if (self.path is None or (os.path.exists(self.path) and not os.path.isdir(self.path))): return False if self.use_git: return self._check_submodule_using_git() else: return self._check_submodule_no_git() def _check_submodule_using_git(self): """ Check if the given path is a git submodule. If so, attempt to initialize and/or update the submodule if needed. This function makes calls to the ``git`` command in subprocesses. The ``_check_submodule_no_git`` option uses pure Python to check if the given path looks like a git submodule, but it cannot perform updates. """ cmd = ['git', 'submodule', 'status', '--', self.path] try: log.info('Running `{0}`; use the --no-git option to disable git ' 'commands'.format(' '.join(cmd))) returncode, stdout, stderr = run_cmd(cmd) except _CommandNotFound: # The git command simply wasn't found; this is most likely the # case on user systems that don't have git and are simply # trying to install the package from PyPI or a source # distribution. Silently ignore this case and simply don't try # to use submodules return False stderr = stderr.strip() if returncode != 0 and stderr: # Unfortunately the return code alone cannot be relied on, as # earlier versions of git returned 0 even if the requested submodule # does not exist # This is a warning that occurs in perl (from running git submodule) # which only occurs with a malformatted locale setting which can # happen sometimes on OSX. See again # https://github.com/astropy/astropy/issues/2749 perl_warning = ('perl: warning: Falling back to the standard locale ' '("C").') if not stderr.strip().endswith(perl_warning): # Some other unknown error condition occurred log.warn('git submodule command failed ' 'unexpectedly:\n{0}'.format(stderr)) return False # Output of `git submodule status` is as follows: # # 1: Status indicator: '-' for submodule is uninitialized, '+' if # submodule is initialized but is not at the commit currently indicated # in .gitmodules (and thus needs to be updated), or 'U' if the # submodule is in an unstable state (i.e. has merge conflicts) # # 2. SHA-1 hash of the current commit of the submodule (we don't really # need this information but it's useful for checking that the output is # correct) # # 3. The output of `git describe` for the submodule's current commit # hash (this includes for example what branches the commit is on) but # only if the submodule is initialized. We ignore this information for # now _git_submodule_status_re = re.compile( r'^(?P[+-U ])(?P[0-9a-f]{40}) ' r'(?P\S+)( .*)?$') # The stdout should only contain one line--the status of the # requested submodule m = _git_submodule_status_re.match(stdout) if m: # Yes, the path *is* a git submodule self._update_submodule(m.group('submodule'), m.group('status')) return True else: log.warn( 'Unexpected output from `git submodule status`:\n{0}\n' 'Will attempt import from {1!r} regardless.'.format( stdout, self.path)) return False def _check_submodule_no_git(self): """ Like ``_check_submodule_using_git``, but simply parses the .gitmodules file to determine if the supplied path is a git submodule, and does not exec any subprocesses. This can only determine if a path is a submodule--it does not perform updates, etc. This function may need to be updated if the format of the .gitmodules file is changed between git versions. """ gitmodules_path = os.path.abspath('.gitmodules') if not os.path.isfile(gitmodules_path): return False # This is a minimal reader for gitconfig-style files. It handles a few of # the quirks that make gitconfig files incompatible with ConfigParser-style # files, but does not support the full gitconfig syntax (just enough # needed to read a .gitmodules file). gitmodules_fileobj = io.StringIO() # Must use io.open for cross-Python-compatible behavior wrt unicode with io.open(gitmodules_path) as f: for line in f: # gitconfig files are more flexible with leading whitespace; just # go ahead and remove it line = line.lstrip() # comments can start with either # or ; if line and line[0] in (':', ';'): continue gitmodules_fileobj.write(line) gitmodules_fileobj.seek(0) cfg = RawConfigParser() try: cfg.readfp(gitmodules_fileobj) except Exception as exc: log.warn('Malformatted .gitmodules file: {0}\n' '{1} cannot be assumed to be a git submodule.'.format( exc, self.path)) return False for section in cfg.sections(): if not cfg.has_option(section, 'path'): continue submodule_path = cfg.get(section, 'path').rstrip(os.sep) if submodule_path == self.path.rstrip(os.sep): return True return False def _update_submodule(self, submodule, status): if status == ' ': # The submodule is up to date; no action necessary return elif status == '-': if self.offline: raise _AHBootstrapSystemExit( "Cannot initialize the {0} submodule in --offline mode; " "this requires being able to clone the submodule from an " "online repository.".format(submodule)) cmd = ['update', '--init'] action = 'Initializing' elif status == '+': cmd = ['update'] action = 'Updating' if self.offline: cmd.append('--no-fetch') elif status == 'U': raise _AHBootstrapSystemExit( 'Error: Submodule {0} contains unresolved merge conflicts. ' 'Please complete or abandon any changes in the submodule so that ' 'it is in a usable state, then try again.'.format(submodule)) else: log.warn('Unknown status {0!r} for git submodule {1!r}. Will ' 'attempt to use the submodule as-is, but try to ensure ' 'that the submodule is in a clean state and contains no ' 'conflicts or errors.\n{2}'.format(status, submodule, _err_help_msg)) return err_msg = None cmd = ['git', 'submodule'] + cmd + ['--', submodule] log.warn('{0} {1} submodule with: `{2}`'.format( action, submodule, ' '.join(cmd))) try: log.info('Running `{0}`; use the --no-git option to disable git ' 'commands'.format(' '.join(cmd))) returncode, stdout, stderr = run_cmd(cmd) except OSError as e: err_msg = str(e) else: if returncode != 0: err_msg = stderr if err_msg is not None: log.warn('An unexpected error occurred updating the git submodule ' '{0!r}:\n{1}\n{2}'.format(submodule, err_msg, _err_help_msg)) class _CommandNotFound(OSError): """ An exception raised when a command run with run_cmd is not found on the system. """ def run_cmd(cmd): """ Run a command in a subprocess, given as a list of command-line arguments. Returns a ``(returncode, stdout, stderr)`` tuple. """ try: p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE) # XXX: May block if either stdout or stderr fill their buffers; # however for the commands this is currently used for that is # unlikely (they should have very brief output) stdout, stderr = p.communicate() except OSError as e: if DEBUG: raise if e.errno == errno.ENOENT: msg = 'Command not found: `{0}`'.format(' '.join(cmd)) raise _CommandNotFound(msg, cmd) else: raise _AHBootstrapSystemExit( 'An unexpected error occurred when running the ' '`{0}` command:\n{1}'.format(' '.join(cmd), str(e))) # Can fail of the default locale is not configured properly. See # https://github.com/astropy/astropy/issues/2749. For the purposes under # consideration 'latin1' is an acceptable fallback. try: stdio_encoding = locale.getdefaultlocale()[1] or 'latin1' except ValueError: # Due to an OSX oddity locale.getdefaultlocale() can also crash # depending on the user's locale/language settings. See: # http://bugs.python.org/issue18378 stdio_encoding = 'latin1' # Unlikely to fail at this point but even then let's be flexible if not isinstance(stdout, _text_type): stdout = stdout.decode(stdio_encoding, 'replace') if not isinstance(stderr, _text_type): stderr = stderr.decode(stdio_encoding, 'replace') return (p.returncode, stdout, stderr) def _next_version(version): """ Given a parsed version from pkg_resources.parse_version, returns a new version string with the next minor version. Examples ======== >>> _next_version(pkg_resources.parse_version('1.2.3')) '1.3.0' """ if hasattr(version, 'base_version'): # New version parsing from setuptools >= 8.0 if version.base_version: parts = version.base_version.split('.') else: parts = [] else: parts = [] for part in version: if part.startswith('*'): break parts.append(part) parts = [int(p) for p in parts] if len(parts) < 3: parts += [0] * (3 - len(parts)) major, minor, micro = parts[:3] return '{0}.{1}.{2}'.format(major, minor + 1, 0) class _DummyFile(object): """A noop writeable object.""" errors = '' # Required for Python 3.x encoding = 'utf-8' def write(self, s): pass def flush(self): pass @contextlib.contextmanager def _verbose(): yield @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() exception_occurred = False try: yield except: exception_occurred = True # Go ahead and clean up so that exception handling can work normally sys.stdout = old_stdout sys.stderr = old_stderr raise if not exception_occurred: sys.stdout = old_stdout sys.stderr = old_stderr _err_help_msg = """ If the problem persists consider installing astropy_helpers manually using pip (`pip install astropy_helpers`) or by manually downloading the source archive, extracting it, and installing by running `python setup.py install` from the root of the extracted source code. """ class _AHBootstrapSystemExit(SystemExit): def __init__(self, *args): if not args: msg = 'An unknown problem occurred bootstrapping astropy_helpers.' else: msg = args[0] msg += '\n' + _err_help_msg super(_AHBootstrapSystemExit, self).__init__(msg, *args[1:]) BOOTSTRAPPER = _Bootstrapper.main() def use_astropy_helpers(**kwargs): """ Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- path : str or None, optional A filesystem path relative to the root of the project's source code that should be added to `sys.path` so that `astropy_helpers` can be imported from that path. If the path is a git submodule it will automatically be initialized and/or updated. The path may also be to a ``.tar.gz`` archive of the astropy_helpers source distribution. In this case the archive is automatically unpacked and made temporarily available on `sys.path` as a ``.egg`` archive. If `None` skip straight to downloading. download_if_needed : bool, optional If the provided filesystem path is not found an attempt will be made to download astropy_helpers from PyPI. It will then be made temporarily available on `sys.path` as a ``.egg`` archive (using the ``setup_requires`` feature of setuptools. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. index_url : str, optional If provided, use a different URL for the Python package index than the main PyPI server. use_git : bool, optional If `False` no git commands will be used--this effectively disables support for git submodules. If the ``--no-git`` option is given at the command line the value of this argument is overridden to `False`. auto_upgrade : bool, optional By default, when installing a package from a non-development source distribution ah_boostrap will try to automatically check for patch releases to astropy-helpers on PyPI and use the patched version over any bundled versions. Setting this to `False` will disable that functionality. If the ``--offline`` option is given at the command line the value of this argument is overridden to `False`. offline : bool, optional If `False` disable all actions that require an internet connection, including downloading packages from the package index and fetching updates to any git submodule. Defaults to `True`. """ global BOOTSTRAPPER config = BOOTSTRAPPER.config config.update(**kwargs) # Create a new bootstrapper with the updated configuration and run it BOOTSTRAPPER = _Bootstrapper(**config) BOOTSTRAPPER.run() radio_beam-0.3.2/astropy_helpers/appveyor.yml0000644000077000000240000000266013516112504021434 0ustar adamstaff00000000000000# AppVeyor.com is a Continuous Integration service to build and run tests under # Windows environment: global: PYTHON: "C:\\conda" MINICONDA_VERSION: "latest" CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\ci-helpers\\appveyor\\windows_sdk.cmd" PYTHON_ARCH: "64" # needs to be set for CMD_IN_ENV to succeed. If a mix # of 32 bit and 64 bit builds are needed, move this # to the matrix section. # babel 2.0 is known to break on Windows: # https://github.com/python-babel/babel/issues/174 CONDA_DEPENDENCIES: "numpy Cython sphinx pytest babel!=2.0 setuptools" matrix: - PYTHON_VERSION: "2.7" - PYTHON_VERSION: "3.4" - PYTHON_VERSION: "3.5" - PYTHON_VERSION: "3.6" - PYTHON_VERSION: "3.7" matrix: fast_finish: true allow_failures: - PYTHON_VERSION: "2.7" platform: -x64 install: # Set up ci-helpers - "git clone git://github.com/astropy/ci-helpers.git" - "powershell ci-helpers/appveyor/install-miniconda.ps1" - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" - "activate test" # Some of the tests use git commands that require a user to be configured - git config --global user.name "A U Thor" - git config --global user.email "author@example.com" # Not a .NET project, we build the package in the install step instead build: false test_script: - "%CMD_IN_ENV% py.test astropy_helpers" radio_beam-0.3.2/astropy_helpers/astropy_helpers/0000755000077000000240000000000013531324214022263 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/__init__.py0000644000077000000240000000345412711231150024375 0ustar adamstaff00000000000000try: from .version import version as __version__ from .version import githash as __githash__ except ImportError: __version__ = '' __githash__ = '' # If we've made it as far as importing astropy_helpers, we don't need # ah_bootstrap in sys.modules anymore. Getting rid of it is actually necessary # if the package we're installing has a setup_requires of another package that # uses astropy_helpers (and possibly a different version at that) # See https://github.com/astropy/astropy/issues/3541 import sys if 'ah_bootstrap' in sys.modules: del sys.modules['ah_bootstrap'] # Note, this is repeated from ah_bootstrap.py, but is here too in case this # astropy-helpers was upgraded to from an older version that did not have this # check in its ah_bootstrap. # matplotlib can cause problems if it is imported from within a call of # run_setup(), because in some circumstances it will try to write to the user's # home directory, resulting in a SandboxViolation. See # https://github.com/matplotlib/matplotlib/pull/4165 # Making sure matplotlib, if it is available, is imported early in the setup # process can mitigate this (note importing matplotlib.pyplot has the same # issue) try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot except: # Ignore if this fails for *any* reason* pass import os # Ensure that all module-level code in astropy or other packages know that # we're in setup mode: if ('__main__' in sys.modules and hasattr(sys.modules['__main__'], '__file__')): filename = os.path.basename(sys.modules['__main__'].__file__) if filename.rstrip('co') == 'setup.py': if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins builtins._ASTROPY_SETUP_ = True del filename radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/0000755000077000000240000000000013531324214024064 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/__init__.py0000644000077000000240000000000012711231150026156 0ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/_dummy.py0000644000077000000240000000557412711231150025736 0ustar adamstaff00000000000000""" Provides a base class for a 'dummy' setup.py command that has no functionality (probably due to a missing requirement). This dummy command can raise an exception when it is run, explaining to the user what dependencies must be met to use this command. The reason this is at all tricky is that we want the command to be able to provide this message even when the user passes arguments to the command. If we don't know ahead of time what arguments the command can take, this is difficult, because distutils does not allow unknown arguments to be passed to a setup.py command. This hacks around that restriction to provide a useful error message even when a user passes arguments to the dummy implementation of a command. Use this like: try: from some_dependency import SetupCommand except ImportError: from ._dummy import _DummyCommand class SetupCommand(_DummyCommand): description = \ 'Implementation of SetupCommand from some_dependency; ' 'some_dependency must be installed to run this command' # This is the message that will be raised when a user tries to # run this command--define it as a class attribute. error_msg = \ "The 'setup_command' command requires the some_dependency " "package to be installed and importable." """ import sys from setuptools import Command from distutils.errors import DistutilsArgError from textwrap import dedent class _DummyCommandMeta(type): """ Causes an exception to be raised on accessing attributes of a command class so that if ``./setup.py command_name`` is run with additional command-line options we can provide a useful error message instead of the default that tells users the options are unrecognized. """ def __init__(cls, name, bases, members): if bases == (Command, object): # This is the _DummyCommand base class, presumably return if not hasattr(cls, 'description'): raise TypeError( "_DummyCommand subclass must have a 'description' " "attribute.") if not hasattr(cls, 'error_msg'): raise TypeError( "_DummyCommand subclass must have an 'error_msg' " "attribute.") def __getattribute__(cls, attr): if attr in ('description', 'error_msg'): # Allow cls.description to work so that `./setup.py # --help-commands` still works return super(_DummyCommandMeta, cls).__getattribute__(attr) raise DistutilsArgError(cls.error_msg) if sys.version_info[0] < 3: exec(dedent(""" class _DummyCommand(Command, object): __metaclass__ = _DummyCommandMeta """)) else: exec(dedent(""" class _DummyCommand(Command, object, metaclass=_DummyCommandMeta): pass """)) radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/_test_compat.py0000644000077000000240000002671213174167363027144 0ustar adamstaff00000000000000""" Old implementation of ``./setup.py test`` command. This has been moved to astropy.tests as of Astropy v1.1.0, but a copy of the implementation is kept here for backwards compatibility. """ from __future__ import absolute_import, unicode_literals import inspect import os import shutil import subprocess import sys import tempfile from setuptools import Command from ..compat import _fix_user_options PY3 = sys.version_info[0] == 3 class AstropyTest(Command, object): 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.'), ('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.') ] user_options = _fix_user_options(user_options) 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 = False 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 # Most of the test runner arguments have the same name as attributes on # this command class, with one exception (for now) _test_runner_arg_attr_map = { 'verbose': 'verbose_results' } 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 def get_attr(arg): attr = self._test_runner_arg_attr_map.get(arg, arg) return getattr(self, attr) test_args = filter(lambda arg: hasattr(self, arg), self._get_test_runner_args()) test_args = ', '.join('{0}={1!r}'.format(arg, get_attr(arg)) for arg in test_args) if PY3: set_flag = "import builtins; builtins._ASTROPY_TEST_ = True" else: set_flag = "import __builtin__; __builtin__._ASTROPY_TEST_ = True" cmd = ('{cmd_pre}{0}; import {1.package_name}, sys; result = ' '{1.package_name}.test({test_args}); {cmd_post}' 'sys.exit(result)') return cmd.format(set_flag, self, cmd_pre=cmd_pre, cmd_post=cmd_post, test_args=test_args) def _validate_required_deps(self): """ This method checks that any required modules are installed before running the tests. """ try: import astropy # noqa except ImportError: raise ImportError( "The 'test' command requires the astropy package to be " "installed and importable.") def run(self): """ Run the tests! """ # Ensure there is a doc path if self.docs_path is None: if os.path.exists('docs'): self.docs_path = os.path.abspath('docs') # Build a testing install of the package self._build_temp_install() # Ensure all required packages are installed self._validate_required_deps() # 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 # On Python 3.x prior to 3.3, the creation of .pyc files # is not atomic. py.test jumps through some hoops to make # this work by parsing import statements and carefully # importing files atomically. However, it can't detect # when __import__ is used, so its carefulness still fails. # The solution here (admittedly a bit of a hack), is to # turn off the generation of .pyc files altogether by # passing the `-B` switch to `python`. This does mean # that each core will have to compile .py file to bytecode # itself, rather than getting lucky and borrowing the work # already done by another core. Compilation is an # insignificant fraction of total testing time, though, so # it's probably not worth worrying about. retcode = subprocess.call([sys.executable, '-B', '-c', cmd], cwd=self.testing_path, close_fds=False) finally: # Remove temporary directory shutil.rmtree(self.tmp_dir) raise SystemExit(retcode) def _build_temp_install(self): """ Build the package and copy the build to a temporary directory for the purposes of testing this avoids creating pyc and __pycache__ directories inside the build directory """ self.reinitialize_command('build', inplace=True) self.run_command('build') build_cmd = self.get_finalized_command('build') new_path = os.path.abspath(build_cmd.build_lib) # 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) self.testing_path = os.path.join(self.tmp_dir, os.path.basename(new_path)) shutil.copytree(new_path, self.testing_path) new_docs_path = os.path.join(self.tmp_dir, 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.tmp_dir) 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 # noqa 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') # We create a coveragerc that is specific to the version # of Python we're running, so that we can mark branches # as being specifically for Python 2 or Python 3 with open(coveragerc, 'r') as fd: coveragerc_content = fd.read() if PY3: ignore_python_version = '2' else: ignore_python_version = '3' coveragerc_content = coveragerc_content.replace( "{ignore_python_version}", ignore_python_version).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 def _get_test_runner_args(self): """ A hack to determine what arguments are supported by the package's test() function. In the future there should be a more straightforward API to determine this (really it should be determined by the ``TestRunner`` class for whatever version of Astropy is in use). """ if PY3: import builtins builtins._ASTROPY_TEST_ = True else: import __builtin__ __builtin__._ASTROPY_TEST_ = True try: pkg = __import__(self.package_name) if not hasattr(pkg, 'test'): raise ImportError( 'package {0} does not have a {0}.test() function as ' 'required by the Astropy test runner'.format(self.package_name)) argspec = inspect.getargspec(pkg.test) return argspec.args finally: if PY3: del builtins._ASTROPY_TEST_ else: del __builtin__._ASTROPY_TEST_ radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/build_ext.py0000644000077000000240000004651113516112504026424 0ustar adamstaff00000000000000import errno import os import re import shlex import shutil import subprocess import sys import textwrap from distutils import log, ccompiler, sysconfig from distutils.core import Extension from distutils.ccompiler import get_default_compiler from setuptools.command.build_ext import build_ext as SetuptoolsBuildExt from ..utils import get_numpy_include_path, invalidate_caches, classproperty from ..version_helpers import get_pkg_version_module def should_build_with_cython(package, release=None): """Returns the previously used Cython version (or 'unknown' if not previously built) if Cython should be used to build extension modules from pyx files. If the ``release`` parameter is not specified an attempt is made to determine the release flag from `astropy.version`. """ try: version_module = __import__(package + '.cython_version', fromlist=['release', 'cython_version']) except ImportError: version_module = None if release is None and version_module is not None: try: release = version_module.release except AttributeError: pass try: cython_version = version_module.cython_version except AttributeError: cython_version = 'unknown' # Only build with Cython if, of course, Cython is installed, we're in a # development version (i.e. not release) or the Cython-generated source # files haven't been created yet (cython_version == 'unknown'). The latter # case can happen even when release is True if checking out a release tag # from the repository have_cython = False try: import Cython # noqa have_cython = True except ImportError: pass if have_cython and (not release or cython_version == 'unknown'): return cython_version else: return False _compiler_versions = {} def get_compiler_version(compiler): if compiler in _compiler_versions: return _compiler_versions[compiler] # Different flags to try to get the compiler version # TODO: It might be worth making this configurable to support # arbitrary odd compilers; though all bets may be off in such # cases anyway flags = ['--version', '--Version', '-version', '-Version', '-v', '-V'] def try_get_version(flag): process = subprocess.Popen( shlex.split(compiler, posix=('win' not in sys.platform)) + [flag], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode != 0: return 'unknown' output = stdout.strip().decode('latin-1') # Safest bet if not output: # Some compilers return their version info on stderr output = stderr.strip().decode('latin-1') if not output: output = 'unknown' return output for flag in flags: version = try_get_version(flag) if version != 'unknown': break # Cache results to speed up future calls _compiler_versions[compiler] = version return version # TODO: I think this can be reworked without having to create the class # programmatically. def generate_build_ext_command(packagename, release): """ Creates a custom 'build_ext' command that allows for manipulating some of the C extension options at build time. We use a function to build the class since the base class for build_ext may be different depending on certain build-time parameters (for example, we may use Cython's build_ext instead of the default version in distutils). Uses the default distutils.command.build_ext by default. """ class build_ext(SetuptoolsBuildExt, object): package_name = packagename is_release = release _user_options = SetuptoolsBuildExt.user_options[:] _boolean_options = SetuptoolsBuildExt.boolean_options[:] _help_options = SetuptoolsBuildExt.help_options[:] force_rebuild = False _broken_compiler_mapping = [ ('i686-apple-darwin[0-9]*-llvm-gcc-4.2', 'clang') ] # Warning: Spaghetti code ahead. # During setup.py, the setup_helpers module needs the ability to add # items to a command's user_options list. At this stage we don't know # whether or not we can build with Cython, and so don't know for sure # what base class will be used for build_ext; nevertheless we want to # be able to provide a list to add options into. # # Later, once setup() has been called we should have all build # dependencies included via setup_requires available. distutils needs # to be able to access the user_options as a *class* attribute before # the class has been initialized, but we do need to be able to # enumerate the options for the correct base class at that point @classproperty def user_options(cls): from distutils import core if core._setup_distribution is None: # We haven't gotten into setup() yet, and the Distribution has # not yet been initialized return cls._user_options return cls._final_class.user_options @classproperty def boolean_options(cls): # Similar to user_options above from distutils import core if core._setup_distribution is None: # We haven't gotten into setup() yet, and the Distribution has # not yet been initialized return cls._boolean_options return cls._final_class.boolean_options @classproperty def help_options(cls): # Similar to user_options above from distutils import core if core._setup_distribution is None: # We haven't gotten into setup() yet, and the Distribution has # not yet been initialized return cls._help_options return cls._final_class.help_options @classproperty(lazy=True) def _final_class(cls): """ Late determination of what the build_ext base class should be, depending on whether or not Cython is available. """ uses_cython = should_build_with_cython(cls.package_name, cls.is_release) if uses_cython: # We need to decide late on whether or not to use Cython's # build_ext (since Cython may not be available earlier in the # setup.py if it was brought in via setup_requires) try: from Cython.Distutils.old_build_ext import old_build_ext as base_cls except ImportError: from Cython.Distutils import build_ext as base_cls else: base_cls = SetuptoolsBuildExt # Create and return an instance of a new class based on this class # using one of the above possible base classes def merge_options(attr): base = getattr(base_cls, attr) ours = getattr(cls, '_' + attr) all_base = set(opt[0] for opt in base) return base + [opt for opt in ours if opt[0] not in all_base] boolean_options = (base_cls.boolean_options + [opt for opt in cls._boolean_options if opt not in base_cls.boolean_options]) members = dict(cls.__dict__) members.update({ 'user_options': merge_options('user_options'), 'help_options': merge_options('help_options'), 'boolean_options': boolean_options, 'uses_cython': uses_cython, }) # Update the base class for the original build_ext command build_ext.__bases__ = (base_cls, object) # Create a new class for the existing class, but now with the # appropriate base class depending on whether or not to use Cython. # Ensure that object is one of the bases to make a new-style class. return type(cls.__name__, (build_ext,), members) def __new__(cls, *args, **kwargs): # By the time the command is actually instantialized, the # Distribution instance for the build has been instantiated, which # means setup_requires has been processed--now we can determine # what base class we can use for the actual build, and return an # instance of a build_ext command that uses that base class (right # now the options being Cython.Distutils.build_ext, or the stock # setuptools build_ext) new_cls = super(build_ext, cls._final_class).__new__( cls._final_class) # Since the new cls is not a subclass of the original cls, we must # manually call its __init__ new_cls.__init__(*args, **kwargs) return new_cls def finalize_options(self): # Add a copy of the _compiler.so module as well, but only if there # are in fact C modules to compile (otherwise there's no reason to # include a record of the compiler used) # Note, self.extensions may not be set yet, but # self.distribution.ext_modules is where any extension modules # passed to setup() can be found self._adjust_compiler() extensions = self.distribution.ext_modules if extensions: build_py = self.get_finalized_command('build_py') package_dir = build_py.get_package_dir(packagename) src_path = os.path.relpath( os.path.join(os.path.dirname(__file__), 'src')) shutil.copy(os.path.join(src_path, 'compiler.c'), os.path.join(package_dir, '_compiler.c')) ext = Extension(self.package_name + '._compiler', [os.path.join(package_dir, '_compiler.c')]) extensions.insert(0, ext) super(build_ext, self).finalize_options() # Generate if self.uses_cython: try: from Cython import __version__ as cython_version except ImportError: # This shouldn't happen if we made it this far cython_version = None if (cython_version is not None and cython_version != self.uses_cython): self.force_rebuild = True # Update the used cython version self.uses_cython = cython_version # Regardless of the value of the '--force' option, force a rebuild # if the debug flag changed from the last build if self.force_rebuild: self.force = True def run(self): # For extensions that require 'numpy' in their include dirs, # replace 'numpy' with the actual paths np_include = None for extension in self.extensions: if 'numpy' in extension.include_dirs: if np_include is None: np_include = get_numpy_include_path() idx = extension.include_dirs.index('numpy') extension.include_dirs.insert(idx, np_include) extension.include_dirs.remove('numpy') self._check_cython_sources(extension) super(build_ext, self).run() # Update cython_version.py if building with Cython try: cython_version = get_pkg_version_module( packagename, fromlist=['cython_version'])[0] except (AttributeError, ImportError): cython_version = 'unknown' if self.uses_cython and self.uses_cython != cython_version: build_py = self.get_finalized_command('build_py') package_dir = build_py.get_package_dir(packagename) cython_py = os.path.join(package_dir, 'cython_version.py') with open(cython_py, 'w') as f: f.write('# Generated file; do not modify\n') f.write('cython_version = {0!r}\n'.format(self.uses_cython)) if os.path.isdir(self.build_lib): # The build/lib directory may not exist if the build_py # command was not previously run, which may sometimes be # the case self.copy_file(cython_py, os.path.join(self.build_lib, cython_py), preserve_mode=False) invalidate_caches() def _adjust_compiler(self): """ This function detects broken compilers and switches to another. If the environment variable CC is explicitly set, or a compiler is specified on the commandline, no override is performed -- the purpose here is to only override a default compiler. The specific compilers with problems are: * The default compiler in XCode-4.2, llvm-gcc-4.2, segfaults when compiling wcslib. The set of broken compilers can be updated by changing the compiler_mapping variable. It is a list of 2-tuples where the first in the pair is a regular expression matching the version of the broken compiler, and the second is the compiler to change to. """ if 'CC' in os.environ: # Check that CC is not set to llvm-gcc-4.2 c_compiler = os.environ['CC'] try: version = get_compiler_version(c_compiler) except OSError: msg = textwrap.dedent( """ The C compiler set by the CC environment variable: {compiler:s} cannot be found or executed. """.format(compiler=c_compiler)) log.warn(msg) sys.exit(1) for broken, fixed in self._broken_compiler_mapping: if re.match(broken, version): msg = textwrap.dedent( """Compiler specified by CC environment variable ({compiler:s}:{version:s}) will fail to compile {pkg:s}. Please set CC={fixed:s} and try again. You can do this, for example, by running: CC={fixed:s} python setup.py where is the command you ran. """.format(compiler=c_compiler, version=version, pkg=self.package_name, fixed=fixed)) log.warn(msg) sys.exit(1) # If C compiler is set via CC, and isn't broken, we are good to go. We # should definitely not try accessing the compiler specified by # ``sysconfig.get_config_var('CC')`` lower down, because this may fail # if the compiler used to compile Python is missing (and maybe this is # why the user is setting CC). For example, the official Python 2.7.3 # MacOS X binary was compiled with gcc-4.2, which is no longer available # in XCode 4. return if self.compiler is not None: # At this point, self.compiler will be set only if a compiler # was specified in the command-line or via setup.cfg, in which # case we don't do anything return compiler_type = ccompiler.get_default_compiler() if compiler_type == 'unix': # We have to get the compiler this way, as this is the one that is # used if os.environ['CC'] is not set. It is actually read in from # the Python Makefile. Note that this is not necessarily the same # compiler as returned by ccompiler.new_compiler() c_compiler = sysconfig.get_config_var('CC') try: version = get_compiler_version(c_compiler) except OSError: msg = textwrap.dedent( """ The C compiler used to compile Python {compiler:s}, and which is normally used to compile C extensions, is not available. You can explicitly specify which compiler to use by setting the CC environment variable, for example: CC=gcc python setup.py or if you are using MacOS X, you can try: CC=clang python setup.py """.format(compiler=c_compiler)) log.warn(msg) sys.exit(1) for broken, fixed in self._broken_compiler_mapping: if re.match(broken, version): os.environ['CC'] = fixed break def _check_cython_sources(self, extension): """ Where relevant, make sure that the .c files associated with .pyx modules are present (if building without Cython installed). """ # Determine the compiler we'll be using if self.compiler is None: compiler = get_default_compiler() else: compiler = self.compiler # Replace .pyx with C-equivalents, unless c files are missing for jdx, src in enumerate(extension.sources): base, ext = os.path.splitext(src) pyxfn = base + '.pyx' cfn = base + '.c' cppfn = base + '.cpp' if not os.path.isfile(pyxfn): continue if self.uses_cython: extension.sources[jdx] = pyxfn else: if os.path.isfile(cfn): extension.sources[jdx] = cfn elif os.path.isfile(cppfn): extension.sources[jdx] = cppfn else: msg = ( 'Could not find C/C++ file {0}.(c/cpp) for Cython ' 'file {1} when building extension {2}. Cython ' 'must be installed to build from a git ' 'checkout.'.format(base, pyxfn, extension.name)) raise IOError(errno.ENOENT, msg, cfn) # Current versions of Cython use deprecated Numpy API features # the use of which produces a few warnings when compiling. # These additional flags should squelch those warnings. # TODO: Feel free to remove this if/when a Cython update # removes use of the deprecated Numpy API if compiler == 'unix': extension.extra_compile_args.extend([ '-Wp,-w', '-Wno-unused-function']) return build_ext radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/build_py.py0000644000077000000240000000265612711231150026251 0ustar adamstaff00000000000000from setuptools.command.build_py import build_py as SetuptoolsBuildPy from ..utils import _get_platlib_dir class AstropyBuildPy(SetuptoolsBuildPy): user_options = SetuptoolsBuildPy.user_options[:] boolean_options = SetuptoolsBuildPy.boolean_options[:] def finalize_options(self): # Update build_lib settings from the build command to always put # build files in platform-specific subdirectories of build/, even # for projects with only pure-Python source (this is desirable # specifically for support of multiple Python version). build_cmd = self.get_finalized_command('build') platlib_dir = _get_platlib_dir(build_cmd) build_cmd.build_purelib = platlib_dir build_cmd.build_lib = platlib_dir self.build_lib = platlib_dir SetuptoolsBuildPy.finalize_options(self) def run_2to3(self, files, doctests=False): # Filter the files to exclude things that shouldn't be 2to3'd skip_2to3 = self.distribution.skip_2to3 filtered_files = [] for filename in files: for package in skip_2to3: if filename[len(self.build_lib) + 1:].startswith(package): break else: filtered_files.append(filename) SetuptoolsBuildPy.run_2to3(self, filtered_files, doctests) def run(self): # first run the normal build_py SetuptoolsBuildPy.run(self) radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/build_sphinx.py0000644000077000000240000002526713516112504027142 0ustar adamstaff00000000000000from __future__ import print_function import inspect import os import pkgutil import re import shutil import subprocess import sys import textwrap import warnings from distutils import log from distutils.cmd import DistutilsOptionError import sphinx from sphinx.setup_command import BuildDoc as SphinxBuildDoc from ..utils import minversion, AstropyDeprecationWarning PY3 = sys.version_info[0] >= 3 class AstropyBuildDocs(SphinxBuildDoc): """ A version of the ``build_docs`` command that uses the version of Astropy that is built by the setup ``build`` command, rather than whatever is installed on the system. To build docs against the installed version, run ``make html`` in the ``astropy/docs`` directory. This also automatically creates the docs/_static directories--this is needed because GitHub won't create the _static dir because it has no tracked files. """ description = 'Build Sphinx documentation for Astropy environment' user_options = SphinxBuildDoc.user_options[:] user_options.append( ('warnings-returncode', 'w', 'Parses the sphinx output and sets the return code to 1 if there ' 'are any warnings. Note that this will cause the sphinx log to ' 'only update when it completes, rather than continuously as is ' 'normally the case.')) user_options.append( ('clean-docs', 'l', 'Completely clean previous builds, including ' 'automodapi-generated files before building new ones')) user_options.append( ('no-intersphinx', 'n', 'Skip intersphinx, even if conf.py says to use it')) user_options.append( ('open-docs-in-browser', 'o', 'Open the docs in a browser (using the webbrowser module) if the ' 'build finishes successfully.')) boolean_options = SphinxBuildDoc.boolean_options[:] boolean_options.append('warnings-returncode') boolean_options.append('clean-docs') boolean_options.append('no-intersphinx') boolean_options.append('open-docs-in-browser') _self_iden_rex = re.compile(r"self\.([^\d\W][\w]+)", re.UNICODE) def initialize_options(self): SphinxBuildDoc.initialize_options(self) self.clean_docs = False self.no_intersphinx = False self.open_docs_in_browser = False self.warnings_returncode = False def finalize_options(self): # We need to make sure this is set before finalize_options otherwise # the default is set to build/sphinx. We also need the absolute path # as in some Sphinx versions, the path is otherwise interpreted as # docs/docs/_build. if self.build_dir is None: self.build_dir = os.path.abspath('docs/_build') else: self.build_dir = os.path.abspath(self.build_dir) SphinxBuildDoc.finalize_options(self) # Clear out previous sphinx builds, if requested if self.clean_docs: dirstorm = [os.path.join(self.source_dir, 'api'), os.path.join(self.source_dir, 'generated')] if self.build_dir is None: dirstorm.append('docs/_build') else: dirstorm.append(self.build_dir) for d in dirstorm: if os.path.isdir(d): log.info('Cleaning directory ' + d) shutil.rmtree(d) else: log.info('Not cleaning directory ' + d + ' because ' 'not present or not a directory') def run(self): # TODO: Break this method up into a few more subroutines and # document them better import webbrowser if PY3: from urllib.request import pathname2url else: from urllib import pathname2url # This is used at the very end of `run` to decide if sys.exit should # be called. If it's None, it won't be. retcode = None # If possible, create the _static dir if self.build_dir is not None: # the _static dir should be in the same place as the _build dir # for Astropy basedir, subdir = os.path.split(self.build_dir) if subdir == '': # the path has a trailing /... basedir, subdir = os.path.split(basedir) staticdir = os.path.join(basedir, '_static') if os.path.isfile(staticdir): raise DistutilsOptionError( 'Attempted to build_docs in a location where' + staticdir + 'is a file. Must be a directory.') self.mkpath(staticdir) # Now make sure Astropy is built and determine where it was built build_cmd = self.reinitialize_command('build') build_cmd.inplace = 0 self.run_command('build') build_cmd = self.get_finalized_command('build') build_cmd_path = os.path.abspath(build_cmd.build_lib) ah_importer = pkgutil.get_importer('astropy_helpers') if ah_importer is None: ah_path = '.' else: ah_path = os.path.abspath(ah_importer.path) # Now generate the source for and spawn a new process that runs the # command. This is needed to get the correct imports for the built # version runlines, runlineno = inspect.getsourcelines(SphinxBuildDoc.run) subproccode = textwrap.dedent(""" from sphinx.setup_command import * os.chdir({srcdir!r}) sys.path.insert(0, {build_cmd_path!r}) sys.path.insert(0, {ah_path!r}) """).format(build_cmd_path=build_cmd_path, ah_path=ah_path, srcdir=self.source_dir) # runlines[1:] removes 'def run(self)' on the first line subproccode += textwrap.dedent(''.join(runlines[1:])) # All "self.foo" in the subprocess code needs to be replaced by the # values taken from the current self in *this* process subproccode = self._self_iden_rex.split(subproccode) for i in range(1, len(subproccode), 2): iden = subproccode[i] val = getattr(self, iden) if iden.endswith('_dir'): # Directories should be absolute, because the `chdir` call # in the new process moves to a different directory subproccode[i] = repr(os.path.abspath(val)) else: subproccode[i] = repr(val) subproccode = ''.join(subproccode) optcode = textwrap.dedent(""" class Namespace(object): pass self = Namespace() self.pdb = {pdb!r} self.verbosity = {verbosity!r} self.traceback = {traceback!r} """).format(pdb=getattr(self, 'pdb', False), verbosity=getattr(self, 'verbosity', 0), traceback=getattr(self, 'traceback', False)) subproccode = optcode + subproccode # This is a quick gross hack, but it ensures that the code grabbed from # SphinxBuildDoc.run will work in Python 2 if it uses the print # function if minversion(sphinx, '1.3'): subproccode = 'from __future__ import print_function' + subproccode if self.no_intersphinx: # the confoverrides variable in sphinx.setup_command.BuildDoc can # be used to override the conf.py ... but this could well break # if future versions of sphinx change the internals of BuildDoc, # so remain vigilant! subproccode = subproccode.replace( 'confoverrides = {}', 'confoverrides = {\'intersphinx_mapping\':{}}') log.debug('Starting subprocess of {0} with python code:\n{1}\n' '[CODE END])'.format(sys.executable, subproccode)) # To return the number of warnings, we need to capture stdout. This # prevents a continuous updating at the terminal, but there's no # apparent way around this. if self.warnings_returncode: proc = subprocess.Popen([sys.executable, '-c', subproccode], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) retcode = 1 with proc.stdout: for line in iter(proc.stdout.readline, b''): line = line.strip(b'\r\n') print(line.decode('utf-8')) if 'build succeeded.' == line.decode('utf-8'): retcode = 0 # Poll to set proc.retcode proc.wait() if retcode != 0: if os.environ.get('TRAVIS', None) == 'true': # this means we are in the travis build, so customize # the message appropriately. msg = ('The build_docs travis build FAILED ' 'because sphinx issued documentation ' 'warnings (scroll up to see the warnings).') else: # standard failure message msg = ('build_docs returning a non-zero exit ' 'code because sphinx issued documentation ' 'warnings.') log.warn(msg) else: proc = subprocess.Popen([sys.executable], stdin=subprocess.PIPE) proc.communicate(subproccode.encode('utf-8')) if proc.returncode == 0: if self.open_docs_in_browser: if self.builder == 'html': absdir = os.path.abspath(self.builder_target_dir) index_path = os.path.join(absdir, 'index.html') fileurl = 'file://' + pathname2url(index_path) webbrowser.open(fileurl) else: log.warn('open-docs-in-browser option was given, but ' 'the builder is not html! Ignoring.') else: log.warn('Sphinx Documentation subprocess failed with return ' 'code ' + str(proc.returncode)) retcode = proc.returncode if retcode is not None: # this is potentially dangerous in that there might be something # after the call to `setup` in `setup.py`, and exiting here will # prevent that from running. But there's no other apparent way # to signal what the return code should be. sys.exit(retcode) class AstropyBuildSphinx(AstropyBuildDocs): # pragma: no cover description = 'deprecated alias to the build_docs command' def run(self): warnings.warn( 'The "build_sphinx" command is now deprecated. Use' '"build_docs" instead.', AstropyDeprecationWarning) AstropyBuildDocs.run(self) radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/install.py0000644000077000000240000000074612711231150026106 0ustar adamstaff00000000000000from setuptools.command.install import install as SetuptoolsInstall from ..utils import _get_platlib_dir class AstropyInstall(SetuptoolsInstall): user_options = SetuptoolsInstall.user_options[:] boolean_options = SetuptoolsInstall.boolean_options[:] def finalize_options(self): build_cmd = self.get_finalized_command('build') platlib_dir = _get_platlib_dir(build_cmd) self.build_lib = platlib_dir SetuptoolsInstall.finalize_options(self) radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/install_lib.py0000644000077000000240000000100012711231150026714 0ustar adamstaff00000000000000from setuptools.command.install_lib import install_lib as SetuptoolsInstallLib from ..utils import _get_platlib_dir class AstropyInstallLib(SetuptoolsInstallLib): user_options = SetuptoolsInstallLib.user_options[:] boolean_options = SetuptoolsInstallLib.boolean_options[:] def finalize_options(self): build_cmd = self.get_finalized_command('build') platlib_dir = _get_platlib_dir(build_cmd) self.build_dir = platlib_dir SetuptoolsInstallLib.finalize_options(self) radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/register.py0000644000077000000240000000454712711231150026267 0ustar adamstaff00000000000000from setuptools.command.register import register as SetuptoolsRegister class AstropyRegister(SetuptoolsRegister): """Extends the built in 'register' command to support a ``--hidden`` option to make the registered version hidden on PyPI by default. The result of this is that when a version is registered as "hidden" it can still be downloaded from PyPI, but it does not show up in the list of actively supported versions under http://pypi.python.org/pypi/astropy, and is not set as the most recent version. Although this can always be set through the web interface it may be more convenient to be able to specify via the 'register' command. Hidden may also be considered a safer default when running the 'register' command, though this command uses distutils' normal behavior if the ``--hidden`` option is omitted. """ user_options = SetuptoolsRegister.user_options + [ ('hidden', None, 'mark this release as hidden on PyPI by default') ] boolean_options = SetuptoolsRegister.boolean_options + ['hidden'] def initialize_options(self): SetuptoolsRegister.initialize_options(self) self.hidden = False def build_post_data(self, action): data = SetuptoolsRegister.build_post_data(self, action) if action == 'submit' and self.hidden: data['_pypi_hidden'] = '1' return data def _set_config(self): # The original register command is buggy--if you use .pypirc with a # server-login section *at all* the repository you specify with the -r # option will be overwritten with either the repository in .pypirc or # with the default, # If you do not have a .pypirc using the -r option will just crash. # Way to go distutils # If we don't set self.repository back to a default value _set_config # can crash if there was a user-supplied value for this option; don't # worry, we'll get the real value back afterwards self.repository = 'pypi' SetuptoolsRegister._set_config(self) options = self.distribution.get_option_dict('register') if 'repository' in options: source, value = options['repository'] # Really anything that came from setup.cfg or the command line # should override whatever was in .pypirc self.repository = value radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/setup_package.py0000644000077000000240000000017013060356620027252 0ustar adamstaff00000000000000from os.path import join def get_package_data(): return {'astropy_helpers.commands': [join('src', 'compiler.c')]} radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/src/0000755000077000000240000000000013531324214024653 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/src/compiler.c0000644000077000000240000000573112711231150026632 0ustar adamstaff00000000000000#include /*************************************************************************** * Macros for determining the compiler version. * * These are borrowed from boost, and majorly abridged to include only * the compilers we care about. ***************************************************************************/ #ifndef PY3K #if PY_MAJOR_VERSION >= 3 #define PY3K 1 #else #define PY3K 0 #endif #endif #define STRINGIZE(X) DO_STRINGIZE(X) #define DO_STRINGIZE(X) #X #if defined __clang__ /* Clang C++ emulates GCC, so it has to appear early. */ # define COMPILER "Clang version " __clang_version__ #elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC) /* Intel */ # if defined(__INTEL_COMPILER) # define INTEL_VERSION __INTEL_COMPILER # elif defined(__ICL) # define INTEL_VERSION __ICL # elif defined(__ICC) # define INTEL_VERSION __ICC # elif defined(__ECC) # define INTEL_VERSION __ECC # endif # define COMPILER "Intel C compiler version " STRINGIZE(INTEL_VERSION) #elif defined(__GNUC__) /* gcc */ # define COMPILER "GCC version " __VERSION__ #elif defined(__SUNPRO_CC) /* Sun Workshop Compiler */ # define COMPILER "Sun compiler version " STRINGIZE(__SUNPRO_CC) #elif defined(_MSC_VER) /* Microsoft Visual C/C++ Must be last since other compilers define _MSC_VER for compatibility as well */ # if _MSC_VER < 1200 # define COMPILER_VERSION 5.0 # elif _MSC_VER < 1300 # define COMPILER_VERSION 6.0 # elif _MSC_VER == 1300 # define COMPILER_VERSION 7.0 # elif _MSC_VER == 1310 # define COMPILER_VERSION 7.1 # elif _MSC_VER == 1400 # define COMPILER_VERSION 8.0 # elif _MSC_VER == 1500 # define COMPILER_VERSION 9.0 # elif _MSC_VER == 1600 # define COMPILER_VERSION 10.0 # else # define COMPILER_VERSION _MSC_VER # endif # define COMPILER "Microsoft Visual C++ version " STRINGIZE(COMPILER_VERSION) #else /* Fallback */ # define COMPILER "Unknown compiler" #endif /*************************************************************************** * Module-level ***************************************************************************/ struct module_state { /* The Sun compiler can't handle empty structs */ #if defined(__SUNPRO_C) || defined(_MSC_VER) int _dummy; #endif }; #if PY3K static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_compiler", NULL, sizeof(struct module_state), NULL, NULL, NULL, NULL, NULL }; #define INITERROR return NULL PyMODINIT_FUNC PyInit__compiler(void) #else #define INITERROR return PyMODINIT_FUNC init_compiler(void) #endif { PyObject* m; #if PY3K m = PyModule_Create(&moduledef); #else m = Py_InitModule3("_compiler", NULL, NULL); #endif if (m == NULL) INITERROR; PyModule_AddStringConstant(m, "compiler", COMPILER); #if PY3K return m; #endif } radio_beam-0.3.2/astropy_helpers/astropy_helpers/commands/test.py0000644000077000000240000000252413174167363025435 0ustar adamstaff00000000000000""" Different implementations of the ``./setup.py test`` command depending on what's locally available. If Astropy v1.1.0.dev or later is available it should be possible to import AstropyTest from ``astropy.tests.command``. If ``astropy`` can be imported but not ``astropy.tests.command`` (i.e. an older version of Astropy), we can use the backwards-compat implementation of the command. If Astropy can't be imported at all then there is a skeleton implementation that allows users to at least discover the ``./setup.py test`` command and learn that they need Astropy to run it. """ # Previously these except statements caught only ImportErrors, but there are # some other obscure exceptional conditions that can occur when importing # astropy.tests (at least on older versions) that can cause these imports to # fail try: import astropy # noqa try: from astropy.tests.command import AstropyTest except Exception: from ._test_compat import AstropyTest except Exception: # No astropy at all--provide the dummy implementation from ._dummy import _DummyCommand class AstropyTest(_DummyCommand): command_name = 'test' description = 'Run the tests for this package' error_msg = ( "The 'test' command requires the astropy package to be " "installed and importable.") radio_beam-0.3.2/astropy_helpers/astropy_helpers/compat/0000755000077000000240000000000013531324214023546 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/compat/__init__.py0000644000077000000240000000056012711231150025653 0ustar adamstaff00000000000000def _fix_user_options(options): """ This is for Python 2.x and 3.x compatibility. distutils expects Command options to all be byte strings on Python 2 and Unicode strings on Python 3. """ 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] radio_beam-0.3.2/astropy_helpers/astropy_helpers/conftest.py0000644000077000000240000000315713516112504024470 0ustar adamstaff00000000000000# This file contains settings for pytest that are specific to astropy-helpers. # Since we run many of the tests in sub-processes, we need to collect coverage # data inside each subprocess and then combine it into a single .coverage file. # To do this we set up a list which run_setup appends coverage objects to. # This is not intended to be used by packages other than astropy-helpers. import os from collections import defaultdict try: from coverage import CoverageData except ImportError: HAS_COVERAGE = False else: HAS_COVERAGE = True if HAS_COVERAGE: SUBPROCESS_COVERAGE = [] def pytest_configure(config): if HAS_COVERAGE: SUBPROCESS_COVERAGE[:] = [] def pytest_unconfigure(config): if HAS_COVERAGE: # We create an empty coverage data object combined_cdata = CoverageData() lines = defaultdict(list) for cdata in SUBPROCESS_COVERAGE: # For each CoverageData object, we go through all the files and # change the filename from one which might be a temporary path # to the local filename. We then only keep files that actually # exist. for filename in cdata.measured_files(): try: pos = filename.rindex('astropy_helpers') except ValueError: continue short_filename = filename[pos:] if os.path.exists(short_filename): lines[os.path.abspath(short_filename)].extend(cdata.lines(filename)) combined_cdata.add_lines(lines) combined_cdata.write_file('.coverage.subprocess') radio_beam-0.3.2/astropy_helpers/astropy_helpers/distutils_helpers.py0000644000077000000240000001736213174167363026431 0ustar adamstaff00000000000000""" This module contains various utilities for introspecting the distutils module and the setup process. Some of these utilities require the `astropy_helpers.setup_helpers.register_commands` function to be called first, as it will affect introspection of setuptools command-line arguments. Other utilities in this module do not have that restriction. """ import os import sys from distutils import ccompiler, log from distutils.dist import Distribution from distutils.errors import DistutilsError from .utils import silence # This function, and any functions that call it, require the setup in # `astropy_helpers.setup_helpers.register_commands` to be run first. def get_dummy_distribution(): """ Returns a distutils Distribution object used to instrument the setup environment before calling the actual setup() function. """ from .setup_helpers import _module_state if _module_state['registered_commands'] is None: raise RuntimeError( 'astropy_helpers.setup_helpers.register_commands() must be ' 'called before using ' 'astropy_helpers.setup_helpers.get_dummy_distribution()') # Pre-parse the Distutils command-line options and config files to if # the option is set. dist = Distribution({'script_name': os.path.basename(sys.argv[0]), 'script_args': sys.argv[1:]}) dist.cmdclass.update(_module_state['registered_commands']) with silence(): try: dist.parse_config_files() dist.parse_command_line() except (DistutilsError, AttributeError, SystemExit): # Let distutils handle DistutilsErrors itself AttributeErrors can # get raise for ./setup.py --help SystemExit can be raised if a # display option was used, for example pass return dist def get_distutils_option(option, commands): """ Returns the value of the given distutils option. Parameters ---------- option : str The name of the option commands : list of str The list of commands on which this option is available Returns ------- val : str or None the value of the given distutils option. If the option is not set, returns None. """ dist = get_dummy_distribution() for cmd in commands: cmd_opts = dist.command_options.get(cmd) if cmd_opts is not None and option in cmd_opts: return cmd_opts[option][1] else: return None def get_distutils_build_option(option): """ Returns the value of the given distutils build option. Parameters ---------- option : str The name of the option Returns ------- val : str or None The value of the given distutils build option. If the option is not set, returns None. """ return get_distutils_option(option, ['build', 'build_ext', 'build_clib']) def get_distutils_install_option(option): """ Returns the value of the given distutils install option. Parameters ---------- option : str The name of the option Returns ------- val : str or None The value of the given distutils build option. If the option is not set, returns None. """ return get_distutils_option(option, ['install']) def get_distutils_build_or_install_option(option): """ Returns the value of the given distutils build or install option. Parameters ---------- option : str The name of the option Returns ------- val : str or None The value of the given distutils build or install option. If the option is not set, returns None. """ return get_distutils_option(option, ['build', 'build_ext', 'build_clib', 'install']) def get_compiler_option(): """ Determines the compiler that will be used to build extension modules. Returns ------- compiler : str The compiler option specified for the build, build_ext, or build_clib command; or the default compiler for the platform if none was specified. """ compiler = get_distutils_build_option('compiler') if compiler is None: return ccompiler.get_default_compiler() return compiler def add_command_option(command, name, doc, is_bool=False): """ Add a custom option to a setup command. Issues a warning if the option already exists on that command. Parameters ---------- command : str The name of the command as given on the command line name : str The name of the build option doc : str A short description of the option, for the `--help` message is_bool : bool, optional When `True`, the option is a boolean option and doesn't require an associated value. """ dist = get_dummy_distribution() cmdcls = dist.get_command_class(command) if (hasattr(cmdcls, '_astropy_helpers_options') and name in cmdcls._astropy_helpers_options): return attr = name.replace('-', '_') if hasattr(cmdcls, attr): raise RuntimeError( '{0!r} already has a {1!r} class attribute, barring {2!r} from ' 'being usable as a custom option name.'.format(cmdcls, attr, name)) for idx, cmd in enumerate(cmdcls.user_options): if cmd[0] == name: log.warn('Overriding existing {0!r} option ' '{1!r}'.format(command, name)) del cmdcls.user_options[idx] if name in cmdcls.boolean_options: cmdcls.boolean_options.remove(name) break cmdcls.user_options.append((name, None, doc)) if is_bool: cmdcls.boolean_options.append(name) # Distutils' command parsing requires that a command object have an # attribute with the same name as the option (with '-' replaced with '_') # in order for that option to be recognized as valid setattr(cmdcls, attr, None) # This caches the options added through add_command_option so that if it is # run multiple times in the same interpreter repeated adds are ignored # (this way we can still raise a RuntimeError if a custom option overrides # a built-in option) if not hasattr(cmdcls, '_astropy_helpers_options'): cmdcls._astropy_helpers_options = set([name]) else: cmdcls._astropy_helpers_options.add(name) def get_distutils_display_options(): """ Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form display option arguments, including the - or -- """ short_display_opts = set('-' + o[1] for o in Distribution.display_options if o[1]) long_display_opts = set('--' + o[0] for o in Distribution.display_options) # Include -h and --help which are not explicitly listed in # Distribution.display_options (as they are handled by optparse) short_display_opts.add('-h') long_display_opts.add('--help') # This isn't the greatest approach to hardcode these commands. # However, there doesn't seem to be a good way to determine # whether build *will be* run as part of the command at this # phase. display_commands = set([ 'clean', 'register', 'setopt', 'saveopts', 'egg_info', 'alias']) return short_display_opts.union(long_display_opts.union(display_commands)) def is_distutils_display_option(): """ Returns True if sys.argv contains any of the distutils display options such as --version or --name. """ display_options = get_distutils_display_options() return bool(set(sys.argv[1:]).intersection(display_options)) radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/0000755000077000000240000000000013531324214023570 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/__init__.py0000644000077000000240000000111513174167363025714 0ustar adamstaff00000000000000# The ``astropy_helpers.extern`` sub-module includes modules developed elsewhere # that are bundled here for convenience. At the moment, this consists of the # following two sphinx extensions: # # * `numpydoc `_, a Sphinx extension # developed as part of the Numpy project. This is used to parse docstrings # in Numpy format # # * `sphinx-automodapi `_, a Sphinx # developed as part of the Astropy project. This used to be developed directly # in ``astropy-helpers`` but is now a standalone package. radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/0000755000077000000240000000000013531324214025732 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/__init__.py0000644000077000000240000000002513516112504030040 0ustar adamstaff00000000000000__version__ = '0.10' radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/autodoc_enhancements.py0000644000077000000240000001242613516112504032477 0ustar adamstaff00000000000000""" Miscellaneous enhancements to help autodoc along. """ import inspect import sys import types import sphinx from distutils.version import LooseVersion from sphinx.ext.autodoc import AttributeDocumenter, ModuleDocumenter from sphinx.util.inspect import isdescriptor if sys.version_info[0] == 3: class_types = (type,) else: class_types = (type, types.ClassType) SPHINX_LT_15 = (LooseVersion(sphinx.__version__) < LooseVersion('1.5')) MethodDescriptorType = type(type.__subclasses__) # See # https://github.com/astropy/astropy-helpers/issues/116#issuecomment-71254836 # for further background on this. def type_object_attrgetter(obj, attr, *defargs): """ This implements an improved attrgetter for type objects (i.e. classes) that can handle class attributes that are implemented as properties on a metaclass. Normally `getattr` on a class with a `property` (say, "foo"), would return the `property` object itself. However, if the class has a metaclass which *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find the "foo" property on the metaclass and resolve it. For the purposes of autodoc we just want to document the "foo" property defined on the class, not on the metaclass. For example:: >>> class Meta(type): ... @property ... def foo(cls): ... return 'foo' ... >>> class MyClass(metaclass=Meta): ... @property ... def foo(self): ... \"\"\"Docstring for MyClass.foo property.\"\"\" ... return 'myfoo' ... >>> getattr(MyClass, 'foo') 'foo' >>> type_object_attrgetter(MyClass, 'foo') >>> type_object_attrgetter(MyClass, 'foo').__doc__ 'Docstring for MyClass.foo property.' The last line of the example shows the desired behavior for the purposes of autodoc. """ for base in obj.__mro__: if attr in base.__dict__: if isinstance(base.__dict__[attr], property): # Note, this should only be used for properties--for any other # type of descriptor (classmethod, for example) this can mess # up existing expectations of what getattr(cls, ...) returns return base.__dict__[attr] break return getattr(obj, attr, *defargs) if SPHINX_LT_15: # Provided to work around a bug in Sphinx # See https://github.com/sphinx-doc/sphinx/pull/1843 class AttributeDocumenter(AttributeDocumenter): @classmethod def can_document_member(cls, member, membername, isattr, parent): non_attr_types = cls.method_types + class_types + \ (MethodDescriptorType,) isdatadesc = isdescriptor(member) and not \ isinstance(member, non_attr_types) and not \ type(member).__name__ == "instancemethod" # That last condition addresses an obscure case of C-defined # methods using a deprecated type in Python 3, that is not # otherwise exported anywhere by Python return isdatadesc or (not isinstance(parent, ModuleDocumenter) and not inspect.isroutine(member) and not isinstance(member, class_types)) def setup(app): # Must have the autodoc extension set up first so we can override it app.setup_extension('sphinx.ext.autodoc') # Need to import this too since it re-registers all the documenter types # =_= import sphinx.ext.autosummary.generate app.add_autodoc_attrgetter(type, type_object_attrgetter) if sphinx.version_info < (1, 4, 2): # this is a really ugly hack to supress a warning that sphinx 1.4 # generates when overriding an existing directive (which is *desired* # behavior here). As of sphinx v1.4.2, this has been fixed: # https://github.com/sphinx-doc/sphinx/issues/2451 # But we leave it in for 1.4.0/1.4.1 . But if the "needs_sphinx" is # eventually updated to >= 1.4.2, this should be removed entirely (in # favor of the line in the "else" clause) _oldwarn = app._warning _oldwarncount = app._warncount try: try: # *this* is in a try/finally because we don't want to force six as # a real dependency. In sphinx 1.4, six is a prerequisite, so # there's no issue. But in older sphinxes this may not be true... # but the inderlying warning is absent anyway so we let it slide. from six import StringIO app._warning = StringIO() except ImportError: pass app.add_autodocumenter(AttributeDocumenter) finally: app._warning = _oldwarn app._warncount = _oldwarncount else: suppress_warnigns_orig = app.config.suppress_warnings[:] if 'app.add_directive' not in app.config.suppress_warnings: app.config.suppress_warnings.append('app.add_directive') try: app.add_autodocumenter(AttributeDocumenter) finally: app.config.suppress_warnings = suppress_warnigns_orig return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/automodapi.py0000644000077000000240000003677313516112504030466 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This directive takes a single argument that must be a module or package. It will produce a block of documentation that includes the docstring for the package, an :ref:`automodsumm` directive, and an :ref:`automod-diagram` if there are any classes in the module. If only the main docstring of the module/package is desired in the documentation, use `automodule`_ instead of `automodapi`_. It accepts the following options: * ``:include-all-objects:`` If present, include not just functions and classes, but all objects. This includes variables, for which a possible docstring after the variable definition will be shown. * ``:no-inheritance-diagram:`` If present, the inheritance diagram will not be shown even if the module/package has classes. * ``:skip: str`` This option results in the specified object being skipped, that is the object will *not* be included in the generated documentation. This option may appear any number of times to skip multiple objects. * ``:no-main-docstr:`` If present, the docstring for the module/package will not be generated. The function and class tables will still be used, however. * ``:headings: str`` Specifies the characters (in one string) used as the heading levels used for the generated section. This must have at least 2 characters (any after 2 will be ignored). This also *must* match the rest of the documentation on this page for sphinx to be happy. Defaults to "-^", which matches the convention used for Python's documentation, assuming the automodapi call is inside a top-level section (which usually uses '='). * ``:no-heading:`` If specified do not create a top level heading for the section. That is, do not create a title heading with text like "packagename Package". The actual docstring for the package/module will still be shown, though, unless ``:no-main-docstr:`` is given. * ``:allowed-package-names: str`` Specifies the packages that functions/classes documented here are allowed to be from, as comma-separated list of package names. If not given, only objects that are actually in a subpackage of the package currently being documented are included. * ``:inherited-members:`` / ``:no-inherited-members:`` The global sphinx configuration option ``automodsumm_inherited_members`` decides if members that a class inherits from a base class are included in the generated documentation. The option ``:inherited-members:`` or ``:no-inherited-members:`` allows the user to overrride the global setting. This extension also adds three sphinx configuration options: * ``automodapi_toctreedirnm`` This must be a string that specifies the name of the directory the automodsumm generated documentation ends up in. This directory path should be relative to the documentation root (e.g., same place as ``index.rst``). Defaults to ``'api'``. * ``automodapi_writereprocessed`` Should be a bool, and if `True`, will cause `automodapi`_ to write files with any `automodapi`_ sections replaced with the content Sphinx processes after `automodapi`_ has run. The output files are not actually used by sphinx, so this option is only for figuring out the cause of sphinx warnings or other debugging. Defaults to `False`. * ``automodsumm_inherited_members`` Should be a bool and if ``True`` members that a class inherits from a base class are included in the generated documentation. Defaults to ``False``. .. _automodule: http://sphinx-doc.org/latest/ext/autodoc.html?highlight=automodule#directive-automodule """ # Implementation note: # The 'automodapi' directive is not actually implemented as a docutils # directive. Instead, this extension searches for the 'automodapi' text in # all sphinx documents, and replaces it where necessary from a template built # into this extension. This is necessary because automodsumm (and autosummary) # use the "builder-inited" event, which comes before the directives are # actually built. import inspect import io import os import re import sys from .utils import find_mod_objs if sys.version_info[0] == 3: text_type = str else: text_type = unicode automod_templ_modheader = """ {modname} {pkgormod} {modhds}{pkgormodhds} {automoduleline} """ automod_templ_classes = """ Classes {clshds} .. automodsumm:: {modname} :classes-only: {clsfuncoptions} """ automod_templ_funcs = """ Functions {funchds} .. automodsumm:: {modname} :functions-only: {clsfuncoptions} """ automod_templ_vars = """ Variables {otherhds} .. automodsumm:: {modname} :variables-only: {clsfuncoptions} """ automod_templ_inh = """ Class Inheritance Diagram {clsinhsechds} .. automod-diagram:: {modname} :private-bases: :parts: 1 {allowedpkgnms} {skip} """ _automodapirex = re.compile(r'^(?:\.\.\s+automodapi::\s*)([A-Za-z0-9_.]+)' r'\s*$((?:\n\s+:[a-zA-Z_\-]+:.*$)*)', flags=re.MULTILINE) # the last group of the above regex is intended to go into finall with the below _automodapiargsrex = re.compile(r':([a-zA-Z_\-]+):(.*)$', flags=re.MULTILINE) def automodapi_replace(sourcestr, app, dotoctree=True, docname=None, warnings=True): """ Replaces `sourcestr`'s entries of ".. automdapi::" with the automodapi template form based on provided options. This is used with the sphinx event 'source-read' to replace `automodapi`_ entries before sphinx actually processes them, as automodsumm needs the code to be present to generate stub documentation. Parameters ---------- sourcestr : str The string with sphinx source to be checked for automodapi replacement. app : `sphinx.application.Application` The sphinx application. dotoctree : bool If `True`, a ":toctree:" option will be added in the ".. automodsumm::" sections of the template, pointing to the appropriate "generated" directory based on the Astropy convention (e.g. in ``docs/api``) docname : str The name of the file for this `sourcestr` (if known - if not, it can be `None`). If not provided and `dotoctree` is `True`, the generated files may end up in the wrong place. warnings : bool If `False`, all warnings that would normally be issued are silenced. Returns ------- newstr :str The string with automodapi entries replaced with the correct sphinx markup. """ spl = _automodapirex.split(sourcestr) if len(spl) > 1: # automodsumm is in this document # Use app.srcdir because api folder should be inside source folder not # at folder where sphinx is run. if dotoctree: toctreestr = ':toctree: ' api_dir = os.path.join(app.srcdir, app.config.automodapi_toctreedirnm) if docname is None: doc_path = '.' else: doc_path = os.path.join(app.srcdir, docname) toctreestr += os.path.relpath(api_dir, os.path.dirname(doc_path)) else: toctreestr = '' newstrs = [spl[0]] for grp in range(len(spl) // 3): modnm = spl[grp * 3 + 1] # find where this is in the document for warnings if docname is None: location = None else: location = (docname, spl[0].count('\n')) # initialize default options toskip = [] inhdiag = maindocstr = top_head = True hds = '-^' allowedpkgnms = [] allowothers = False # look for actual options unknownops = [] inherited_members = None for opname, args in _automodapiargsrex.findall(spl[grp * 3 + 2]): if opname == 'skip': toskip.append(args.strip()) elif opname == 'no-inheritance-diagram': inhdiag = False elif opname == 'no-main-docstr': maindocstr = False elif opname == 'headings': hds = args elif opname == 'no-heading': top_head = False elif opname == 'allowed-package-names': allowedpkgnms.append(args.strip()) elif opname == 'inherited-members': inherited_members = True elif opname == 'no-inherited-members': inherited_members = False elif opname == 'include-all-objects': allowothers = True else: unknownops.append(opname) # join all the allowedpkgnms if len(allowedpkgnms) == 0: allowedpkgnms = '' onlylocals = True else: allowedpkgnms = ':allowed-package-names: ' + ','.join(allowedpkgnms) onlylocals = allowedpkgnms # get the two heading chars if len(hds) < 2: msg = 'Not enough headings (got {0}, need 2), using default -^' if warnings: app.warn(msg.format(len(hds)), location) hds = '-^' h1, h2 = hds.lstrip()[:2] # tell sphinx that the remaining args are invalid. if len(unknownops) > 0 and app is not None: opsstrs = ','.join(unknownops) msg = 'Found additional options ' + opsstrs + ' in automodapi.' if warnings: app.warn(msg, location) ispkg, hascls, hasfuncs, hasother = _mod_info( modnm, toskip, onlylocals=onlylocals) # add automodule directive only if no-main-docstr isn't present if maindocstr: automodline = '.. automodule:: {modname}'.format(modname=modnm) else: automodline = '' if top_head: newstrs.append(automod_templ_modheader.format( modname=modnm, modhds=h1 * len(modnm), pkgormod='Package' if ispkg else 'Module', pkgormodhds=h1 * (8 if ispkg else 7), automoduleline=automodline)) # noqa else: newstrs.append(automod_templ_modheader.format( modname='', modhds='', pkgormod='', pkgormodhds='', automoduleline=automodline)) # construct the options for the class/function sections # start out indented at 4 spaces, but need to keep the indentation. clsfuncoptions = [] if toctreestr: clsfuncoptions.append(toctreestr) if toskip: clsfuncoptions.append(':skip: ' + ','.join(toskip)) if allowedpkgnms: clsfuncoptions.append(allowedpkgnms) if hascls: # This makes no sense unless there are classes. if inherited_members is True: clsfuncoptions.append(':inherited-members:') if inherited_members is False: clsfuncoptions.append(':no-inherited-members:') clsfuncoptionstr = '\n '.join(clsfuncoptions) if hasfuncs: newstrs.append(automod_templ_funcs.format( modname=modnm, funchds=h2 * 9, clsfuncoptions=clsfuncoptionstr)) if hascls: newstrs.append(automod_templ_classes.format( modname=modnm, clshds=h2 * 7, clsfuncoptions=clsfuncoptionstr)) if allowothers and hasother: newstrs.append(automod_templ_vars.format( modname=modnm, otherhds=h2 * 9, clsfuncoptions=clsfuncoptionstr)) if inhdiag and hascls: # add inheritance diagram if any classes are in the module if toskip: clsskip = ':skip: ' + ','.join(toskip) else: clsskip = '' diagram_entry = automod_templ_inh.format( modname=modnm, clsinhsechds=h2 * 25, allowedpkgnms=allowedpkgnms, skip=clsskip) diagram_entry = diagram_entry.replace(' \n', '') newstrs.append(diagram_entry) newstrs.append(spl[grp * 3 + 3]) newsourcestr = ''.join(newstrs) if app.config.automodapi_writereprocessed: # sometimes they are unicode, sometimes not, depending on how # sphinx has processed things if isinstance(newsourcestr, text_type): ustr = newsourcestr else: ustr = newsourcestr.decode(app.config.source_encoding) if docname is None: with io.open(os.path.join(app.srcdir, 'unknown.automodapi'), 'a', encoding='utf8') as f: f.write(u'\n**NEW DOC**\n\n') f.write(ustr) else: env = app.builder.env # Determine the filename associated with this doc (specifically # the extension) filename = docname + os.path.splitext(env.doc2path(docname))[1] filename += '.automodapi' with io.open(os.path.join(app.srcdir, filename), 'w', encoding='utf8') as f: f.write(ustr) return newsourcestr else: return sourcestr def _mod_info(modname, toskip=[], onlylocals=True): """ Determines if a module is a module or a package and whether or not it has classes or functions. """ hascls = hasfunc = hasother = False for localnm, fqnm, obj in zip(*find_mod_objs(modname, onlylocals=onlylocals)): if localnm not in toskip: hascls = hascls or inspect.isclass(obj) hasfunc = hasfunc or inspect.isroutine(obj) hasother = hasother or (not inspect.isclass(obj) and not inspect.isroutine(obj)) if hascls and hasfunc and hasother: break # find_mod_objs has already imported modname # TODO: There is probably a cleaner way to do this, though this is pretty # reliable for all Python versions for most cases that we care about. pkg = sys.modules[modname] ispkg = (hasattr(pkg, '__file__') and isinstance(pkg.__file__, str) and os.path.split(pkg.__file__)[1].startswith('__init__.py')) return ispkg, hascls, hasfunc, hasother def process_automodapi(app, docname, source): source[0] = automodapi_replace(source[0], app, True, docname) def setup(app): app.setup_extension('sphinx.ext.autosummary') # Note: we use __name__ here instead of just writing the module name in # case this extension is bundled into another package from . import automodsumm app.setup_extension(automodsumm.__name__) app.connect('source-read', process_automodapi) app.add_config_value('automodapi_toctreedirnm', 'api', True) app.add_config_value('automodapi_writereprocessed', False, True) return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/automodsumm.py0000644000077000000240000006547613516112504030700 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This directive will produce an "autosummary"-style table for public attributes of a specified module. See the `sphinx.ext.autosummary`_ extension for details on this process. The main difference from the `autosummary`_ directive is that `autosummary`_ requires manually inputting all attributes that appear in the table, while this captures the entries automatically. This directive requires a single argument that must be a module or package. It also accepts any options supported by the `autosummary`_ directive- see `sphinx.ext.autosummary`_ for details. It also accepts some additional options: * ``:classes-only:`` If present, the autosummary table will only contain entries for classes. This cannot be used at the same time with ``:functions-only:`` or ``:variables-only:``. * ``:functions-only:`` If present, the autosummary table will only contain entries for functions. This cannot be used at the same time with ``:classes-only:`` or ``:variables-only:``. * ``:variables-only:`` If present, the autosummary table will only contain entries for variables (everything except functions and classes). This cannot be used at the same time with ``:classes-only:`` or ``:functions-only:``. * ``:skip: obj1, [obj2, obj3, ...]`` If present, specifies that the listed objects should be skipped and not have their documentation generated, nor be included in the summary table. * ``:allowed-package-names: pkgormod1, [pkgormod2, pkgormod3, ...]`` Specifies the packages that functions/classes documented here are allowed to be from, as comma-separated list of package names. If not given, only objects that are actually in a subpackage of the package currently being documented are included. * ``:inherited-members:`` or ``:no-inherited-members:`` The global sphinx configuration option ``automodsumm_inherited_members`` decides if members that a class inherits from a base class are included in the generated documentation. The flags ``:inherited-members:`` or ``:no-inherited-members:`` allows overrriding this global setting. This extension also adds two sphinx configuration options: * ``automodsumm_writereprocessed`` Should be a bool, and if ``True``, will cause `automodsumm`_ to write files with any ``automodsumm`` sections replaced with the content Sphinx processes after ``automodsumm`` has run. The output files are not actually used by sphinx, so this option is only for figuring out the cause of sphinx warnings or other debugging. Defaults to ``False``. * ``automodsumm_inherited_members`` Should be a bool and if ``True``, will cause `automodsumm`_ to document class members that are inherited from a base class. This value can be overriden for any particular automodsumm directive by including the ``:inherited-members:`` or ``:no-inherited-members:`` options. Defaults to ``False``. .. _sphinx.ext.autosummary: http://sphinx-doc.org/latest/ext/autosummary.html .. _autosummary: http://sphinx-doc.org/latest/ext/autosummary.html#directive-autosummary .. _automod-diagram: automod-diagram directive ========================= This directive will produce an inheritance diagram like that of the `sphinx.ext.inheritance_diagram`_ extension. This directive requires a single argument that must be a module or package. It accepts no options. .. note:: Like 'inheritance-diagram', 'automod-diagram' requires `graphviz `_ to generate the inheritance diagram. .. _sphinx.ext.inheritance_diagram: http://sphinx-doc.org/latest/ext/inheritance.html """ import abc import inspect import os import re import io from distutils.version import LooseVersion from sphinx import __version__ from sphinx.ext.autosummary import Autosummary from sphinx.ext.inheritance_diagram import InheritanceDiagram from docutils.parsers.rst.directives import flag from .utils import find_mod_objs, cleanup_whitespace __all__ = ['Automoddiagram', 'Automodsumm', 'automodsumm_to_autosummary_lines', 'generate_automodsumm_docs', 'process_automodsumm_generation'] SPHINX_LT_16 = LooseVersion(__version__) < LooseVersion('1.6') SPHINX_LT_17 = LooseVersion(__version__) < LooseVersion('1.7') def _str_list_converter(argument): """ A directive option conversion function that converts the option into a list of strings. Used for 'skip' option. """ if argument is None: return [] else: return [s.strip() for s in argument.split(',')] class Automodsumm(Autosummary): required_arguments = 1 optional_arguments = 0 final_argument_whitespace = False has_content = False option_spec = dict(Autosummary.option_spec) option_spec['functions-only'] = flag option_spec['classes-only'] = flag option_spec['variables-only'] = flag option_spec['skip'] = _str_list_converter option_spec['allowed-package-names'] = _str_list_converter option_spec['inherited-members'] = flag option_spec['no-inherited-members'] = flag def run(self): env = self.state.document.settings.env modname = self.arguments[0] try: self.warnings[:] = [] except AttributeError: self.warnings = [] nodelist = [] try: localnames, fqns, objs = find_mod_objs(modname) except ImportError: self.warn("Couldn't import module " + modname) return self.warnings try: # set self.content to trick the autosummary internals. # Be sure to respect functions-only and classes-only. funconly = 'functions-only' in self.options clsonly = 'classes-only' in self.options varonly = 'variables-only' in self.options if [clsonly, funconly, varonly].count(True) > 1: self.warning('more than one of functions-only, classes-only, ' 'or variables-only defined. Ignoring.') clsonly = funconly = varonly = False skipnames = [] if 'skip' in self.options: option_skipnames = set(self.options['skip']) for lnm in localnames: if lnm in option_skipnames: option_skipnames.remove(lnm) skipnames.append(lnm) if len(option_skipnames) > 0: self.warn('Tried to skip objects {objs} in module {mod}, ' 'but they were not present. Ignoring.' .format(objs=option_skipnames, mod=modname)) if funconly: cont = [] for nm, obj in zip(localnames, objs): if nm not in skipnames and inspect.isroutine(obj): cont.append(nm) elif clsonly: cont = [] for nm, obj in zip(localnames, objs): if nm not in skipnames and inspect.isclass(obj): cont.append(nm) elif varonly: cont = [] for nm, obj in zip(localnames, objs): if nm not in skipnames and not (inspect.isclass(obj) or inspect.isroutine(obj)): cont.append(nm) else: cont = [nm for nm in localnames if nm not in skipnames] self.content = cont # for some reason, even though ``currentmodule`` is substituted in, # sphinx doesn't necessarily recognize this fact. So we just force # it internally, and that seems to fix things env.temp_data['py:module'] = modname env.ref_context['py:module'] = modname # can't use super because Sphinx/docutils has trouble return # super(Autosummary,self).run() nodelist.extend(Autosummary.run(self)) return self.warnings + nodelist finally: # has_content = False for the Automodsumm self.content = [] def get_items(self, names): self.genopt['imported-members'] = True return Autosummary.get_items(self, names) # <-------------------automod-diagram stuff-----------------------------------> class Automoddiagram(InheritanceDiagram): option_spec = dict(InheritanceDiagram.option_spec) option_spec['allowed-package-names'] = _str_list_converter option_spec['skip'] = _str_list_converter def run(self): try: ols = self.options.get('allowed-package-names', []) ols = True if len(ols) == 0 else ols # if none are given, assume only local nms, objs = find_mod_objs(self.arguments[0], onlylocals=ols)[1:] except ImportError: self.warnings = [] self.warn("Couldn't import module " + self.arguments[0]) return self.warnings # Check if some classes should be skipped skip = self.options.get('skip', []) clsnms = [] for n, o in zip(nms, objs): if n.split('.')[-1] in skip: continue if inspect.isclass(o): clsnms.append(n) oldargs = self.arguments try: if len(clsnms) > 0: self.arguments = [' '.join(clsnms)] return InheritanceDiagram.run(self) finally: self.arguments = oldargs # <---------------------automodsumm generation stuff--------------------------> def process_automodsumm_generation(app): env = app.builder.env filestosearch = [] for docname in env.found_docs: filename = env.doc2path(docname) if os.path.isfile(filename): filestosearch.append(docname + os.path.splitext(filename)[1]) liness = [] for sfn in filestosearch: lines = automodsumm_to_autosummary_lines(sfn, app) liness.append(lines) if app.config.automodsumm_writereprocessed: if lines: # empty list means no automodsumm entry is in the file outfn = os.path.join(app.srcdir, sfn) + '.automodsumm' with open(outfn, 'w') as f: for l in lines: f.write(l) f.write('\n') for sfn, lines in zip(filestosearch, liness): suffix = os.path.splitext(sfn)[1] if len(lines) > 0: generate_automodsumm_docs( lines, sfn, app=app, builder=app.builder, suffix=suffix, base_path=app.srcdir, inherited_members=app.config.automodsumm_inherited_members) # _automodsummrex = re.compile(r'^(\s*)\.\. automodsumm::\s*([A-Za-z0-9_.]+)\s*' # r'\n\1(\s*)(\S|$)', re.MULTILINE) _lineendrex = r'(?:\n|$)' _hdrex = r'^\n?(\s*)\.\. automodsumm::\s*(\S+)\s*' + _lineendrex _oprex1 = r'(?:\1(\s+)\S.*' + _lineendrex + ')' _oprex2 = r'(?:\1\4\S.*' + _lineendrex + ')' _automodsummrex = re.compile(_hdrex + '(' + _oprex1 + '?' + _oprex2 + '*)', re.MULTILINE) def automodsumm_to_autosummary_lines(fn, app): """ Generates lines from a file with an "automodsumm" entry suitable for feeding into "autosummary". Searches the provided file for `automodsumm` directives and returns a list of lines specifying the `autosummary` commands for the modules requested. This does *not* return the whole file contents - just an autosummary section in place of any :automodsumm: entries. Note that any options given for `automodsumm` are also included in the generated `autosummary` section. Parameters ---------- fn : str The name of the file to search for `automodsumm` entries. app : sphinx.application.Application The sphinx Application object Returns ------- lines : list of str Lines for all `automodsumm` entries with the entries replaced by `autosummary` and the module's members added. """ fullfn = os.path.join(app.builder.env.srcdir, fn) with io.open(fullfn, encoding='utf8') as fr: # Note: we use __name__ here instead of just writing the module name in # case this extension is bundled into another package from . import automodapi try: extensions = app.extensions except AttributeError: # Sphinx <1.6 extensions = app._extensions if automodapi.__name__ in extensions: # Must do the automodapi on the source to get the automodsumm # that might be in there docname = os.path.splitext(fn)[0] filestr = automodapi.automodapi_replace(fr.read(), app, True, docname, False) else: filestr = fr.read() spl = _automodsummrex.split(filestr) # 0th entry is the stuff before the first automodsumm line indent1s = spl[1::5] mods = spl[2::5] opssecs = spl[3::5] indent2s = spl[4::5] remainders = spl[5::5] # only grab automodsumm sections and convert them to autosummary with the # entries for all the public objects newlines = [] # loop over all automodsumms in this document for i, (i1, i2, modnm, ops, rem) in enumerate(zip(indent1s, indent2s, mods, opssecs, remainders)): allindent = i1 + (' ' if i2 is None else i2) # filter out functions-only, classes-only, and ariables-only # options if present. oplines = ops.split('\n') toskip = [] allowedpkgnms = [] funcsonly = clssonly = varsonly = False for i, ln in reversed(list(enumerate(oplines))): if ':functions-only:' in ln: funcsonly = True del oplines[i] if ':classes-only:' in ln: clssonly = True del oplines[i] if ':variables-only:' in ln: varsonly = True del oplines[i] if ':skip:' in ln: toskip.extend(_str_list_converter(ln.replace(':skip:', ''))) del oplines[i] if ':allowed-package-names:' in ln: allowedpkgnms.extend(_str_list_converter(ln.replace(':allowed-package-names:', ''))) del oplines[i] if [funcsonly, clssonly, varsonly].count(True) > 1: msg = ('Defined more than one of functions-only, classes-only, ' 'and variables-only. Skipping this directive.') lnnum = sum([spl[j].count('\n') for j in range(i * 5 + 1)]) app.warn('[automodsumm]' + msg, (fn, lnnum)) continue # Use the currentmodule directive so we can just put the local names # in the autosummary table. Note that this doesn't always seem to # actually "take" in Sphinx's eyes, so in `Automodsumm.run`, we have to # force it internally, as well. newlines.extend([i1 + '.. currentmodule:: ' + modnm, '', '.. autosummary::']) newlines.extend(oplines) ols = True if len(allowedpkgnms) == 0 else allowedpkgnms for nm, fqn, obj in zip(*find_mod_objs(modnm, onlylocals=ols)): if nm in toskip: continue if funcsonly and not inspect.isroutine(obj): continue if clssonly and not inspect.isclass(obj): continue if varsonly and (inspect.isclass(obj) or inspect.isroutine(obj)): continue newlines.append(allindent + nm) # add one newline at the end of the autosummary block newlines.append('') return newlines def generate_automodsumm_docs(lines, srcfn, app=None, suffix='.rst', base_path=None, builder=None, template_dir=None, inherited_members=False): """ This function is adapted from `sphinx.ext.autosummary.generate.generate_autosummmary_docs` to generate source for the automodsumm directives that should be autosummarized. Unlike generate_autosummary_docs, this function is called one file at a time. """ from sphinx.jinja2glue import BuiltinTemplateLoader from sphinx.ext.autosummary import import_by_name, get_documenter from sphinx.util.osutil import ensuredir from sphinx.util.inspect import safe_getattr from jinja2 import FileSystemLoader, TemplateNotFound from jinja2.sandbox import SandboxedEnvironment from .utils import find_autosummary_in_lines_for_automodsumm as find_autosummary_in_lines if SPHINX_LT_16: info = app.info warn = app.warn else: from sphinx.util import logging logger = logging.getLogger(__name__) info = logger.info warn = logger.warning # info('[automodsumm] generating automodsumm for: ' + srcfn) # Create our own templating environment - here we use Astropy's # templates rather than the default autosummary templates, in order to # allow docstrings to be shown for methods. template_dirs = [os.path.join(os.path.dirname(__file__), 'templates'), os.path.join(base_path, '_templates')] if builder is not None: # allow the user to override the templates template_loader = BuiltinTemplateLoader() template_loader.init(builder, dirs=template_dirs) else: if template_dir: template_dirs.insert(0, template_dir) template_loader = FileSystemLoader(template_dirs) template_env = SandboxedEnvironment(loader=template_loader) # read # items = find_autosummary_in_files(sources) items = find_autosummary_in_lines(lines, filename=srcfn) if len(items) > 0: msg = '[automodsumm] {1}: found {0} automodsumm entries to generate' info(msg.format(len(items), srcfn)) # gennms = [item[0] for item in items] # if len(gennms) > 20: # gennms = gennms[:10] + ['...'] + gennms[-10:] # info('[automodsumm] generating autosummary for: ' + ', '.join(gennms)) # remove possible duplicates items = list(set(items)) # keep track of new files new_files = [] # write for name, path, template_name, inherited_mem in sorted(items): if path is None: # The corresponding autosummary:: directive did not have # a :toctree: option continue path = os.path.abspath(os.path.join(base_path, path)) ensuredir(path) try: import_by_name_values = import_by_name(name) except ImportError as e: warn('[automodsumm] failed to import %r: %s' % (name, e)) continue # if block to accommodate Sphinx's v1.2.2 and v1.2.3 respectively if len(import_by_name_values) == 3: name, obj, parent = import_by_name_values elif len(import_by_name_values) == 4: name, obj, parent, module_name = import_by_name_values fn = os.path.join(path, name + suffix) # skip it if it exists if os.path.isfile(fn): continue new_files.append(fn) f = open(fn, 'w') try: if SPHINX_LT_17: doc = get_documenter(obj, parent) else: doc = get_documenter(app, obj, parent) if template_name is not None: template = template_env.get_template(template_name) else: tmplstr = 'autosummary_core/%s.rst' try: template = template_env.get_template(tmplstr % doc.objtype) except TemplateNotFound: template = template_env.get_template(tmplstr % 'base') def get_members_mod(obj, typ, include_public=[]): """ typ = None -> all """ items = [] for name in dir(obj): try: if SPHINX_LT_17: documenter = get_documenter(safe_getattr(obj, name), obj) else: documenter = get_documenter(app, safe_getattr(obj, name), obj) except AttributeError: continue if typ is None or documenter.objtype == typ: items.append(name) public = [x for x in items if x in include_public or not x.startswith('_')] return public, items def get_members_class(obj, typ, include_public=[], include_base=False): """ typ = None -> all include_base -> include attrs that are from a base class """ items = [] # using dir gets all of the attributes, including the elements # from the base class, otherwise use __slots__ or __dict__ if include_base: names = dir(obj) else: # Classes deriving from an ABC using the `abc` module will # have an empty `__slots__` attribute in Python 3, unless # other slots were declared along the inheritance chain. If # the ABC-derived class has empty slots, we'll use the # class `__dict__` instead. declares_slots = ( hasattr(obj, '__slots__') and not (type(obj) is abc.ABCMeta and len(obj.__slots__) == 0) ) if declares_slots: names = tuple(getattr(obj, '__slots__')) else: names = getattr(obj, '__dict__').keys() for name in names: try: if SPHINX_LT_17: documenter = get_documenter(safe_getattr(obj, name), obj) else: documenter = get_documenter(app, safe_getattr(obj, name), obj) except AttributeError: continue if typ is None or documenter.objtype == typ: items.append(name) public = [x for x in items if x in include_public or not x.startswith('_')] return public, items ns = {} if doc.objtype == 'module': ns['members'] = get_members_mod(obj, None) ns['functions'], ns['all_functions'] = \ get_members_mod(obj, 'function') ns['classes'], ns['all_classes'] = \ get_members_mod(obj, 'class') ns['exceptions'], ns['all_exceptions'] = \ get_members_mod(obj, 'exception') elif doc.objtype == 'class': if inherited_mem is not None: # option set in this specifc directive include_base = inherited_mem else: # use default value include_base = inherited_members api_class_methods = ['__init__', '__call__'] ns['members'] = get_members_class(obj, None, include_base=include_base) ns['methods'], ns['all_methods'] = \ get_members_class(obj, 'method', api_class_methods, include_base=include_base) ns['attributes'], ns['all_attributes'] = \ get_members_class(obj, 'attribute', include_base=include_base) ns['methods'].sort() ns['attributes'].sort() parts = name.split('.') if doc.objtype in ('method', 'attribute'): mod_name = '.'.join(parts[:-2]) cls_name = parts[-2] obj_name = '.'.join(parts[-2:]) ns['class'] = cls_name else: mod_name, obj_name = '.'.join(parts[:-1]), parts[-1] ns['fullname'] = name ns['module'] = mod_name ns['objname'] = obj_name ns['name'] = parts[-1] ns['objtype'] = doc.objtype ns['underline'] = len(obj_name) * '=' # We now check whether a file for reference footnotes exists for # the module being documented. We first check if the # current module is a file or a directory, as this will give a # different path for the reference file. For example, if # documenting astropy.wcs then the reference file is at # ../wcs/references.txt, while if we are documenting # astropy.config.logging_helper (which is at # astropy/config/logging_helper.py) then the reference file is set # to ../config/references.txt if '.' in mod_name: mod_name_dir = mod_name.replace('.', '/').split('/', 1)[1] else: mod_name_dir = mod_name if not os.path.isdir(os.path.join(base_path, mod_name_dir)) \ and os.path.isdir(os.path.join(base_path, mod_name_dir.rsplit('/', 1)[0])): mod_name_dir = mod_name_dir.rsplit('/', 1)[0] # We then have to check whether it exists, and if so, we pass it # to the template. if os.path.exists(os.path.join(base_path, mod_name_dir, 'references.txt')): # An important subtlety here is that the path we pass in has # to be relative to the file being generated, so we have to # figure out the right number of '..'s ndirsback = path.replace(base_path, '').count('/') ref_file_rel_segments = ['..'] * ndirsback ref_file_rel_segments.append(mod_name_dir) ref_file_rel_segments.append('references.txt') ns['referencefile'] = os.path.join(*ref_file_rel_segments) rendered = template.render(**ns) f.write(cleanup_whitespace(rendered)) finally: f.close() def setup(app): # need autodoc fixes # Note: we use __name__ here instead of just writing the module name in # case this extension is bundled into another package from . import autodoc_enhancements app.setup_extension(autodoc_enhancements.__name__) # need inheritance-diagram for automod-diagram app.setup_extension('sphinx.ext.inheritance_diagram') app.add_directive('automod-diagram', Automoddiagram) app.add_directive('automodsumm', Automodsumm) app.connect('builder-inited', process_automodsumm_generation) app.add_config_value('automodsumm_writereprocessed', False, True) app.add_config_value('automodsumm_inherited_members', False, 'env') return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/smart_resolver.py0000644000077000000240000001002013516112504031344 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ The classes in the astropy docs are documented by their API location, which is not necessarily where they are defined in the source. This causes a problem when certain automated features of the doc build, such as the inheritance diagrams or the `Bases` list of a class reference a class by its canonical location rather than its "user" location. In the `autodoc-process-docstring` event, a mapping from the actual name to the API name is maintained. Later, in the `missing-reference` event, unresolved references are looked up in this dictionary and corrected if possible. """ from docutils.nodes import literal, reference def process_docstring(app, what, name, obj, options, lines): if isinstance(obj, type): env = app.env if not hasattr(env, 'class_name_mapping'): env.class_name_mapping = {} mapping = env.class_name_mapping mapping[obj.__module__ + '.' + obj.__name__] = name def merge_mapping(app, env, docnames, env_other): if not hasattr(env_other, 'class_name_mapping'): return if not hasattr(env, 'class_name_mapping'): env.class_name_mapping = {} env.class_name_mapping.update(env_other.class_name_mapping) def missing_reference_handler(app, env, node, contnode): if not hasattr(env, 'class_name_mapping'): env.class_name_mapping = {} mapping = env.class_name_mapping reftype = node['reftype'] reftarget = node['reftarget'] if reftype in ('obj', 'class', 'exc', 'meth'): reftarget = node['reftarget'] suffix = '' if reftarget not in mapping: if '.' in reftarget: front, suffix = reftarget.rsplit('.', 1) else: suffix = reftarget if suffix.startswith('_') and not suffix.startswith('__'): # If this is a reference to a hidden class or method, # we can't link to it, but we don't want to have a # nitpick warning. return node[0].deepcopy() if reftype in ('obj', 'meth') and '.' in reftarget: if front in mapping: reftarget = front suffix = '.' + suffix if (reftype in ('class', ) and '.' in reftarget and reftarget not in mapping): if '.' in front: reftarget, _ = front.rsplit('.', 1) suffix = '.' + suffix reftarget = reftarget + suffix prefix = reftarget.rsplit('.')[0] inventory = env.intersphinx_named_inventory if (reftarget not in mapping and prefix in inventory): if reftarget in inventory[prefix]['py:class']: newtarget = inventory[prefix]['py:class'][reftarget][2] if not node['refexplicit'] and \ '~' not in node.rawsource: contnode = literal(text=reftarget) newnode = reference('', '', internal=True) newnode['reftitle'] = reftarget newnode['refuri'] = newtarget newnode.append(contnode) return newnode if reftarget in mapping: newtarget = mapping[reftarget] + suffix if not node['refexplicit'] and '~' not in node.rawsource: contnode = literal(text=newtarget) newnode = env.domains['py'].resolve_xref( env, node['refdoc'], app.builder, 'class', newtarget, node, contnode) if newnode is not None: newnode['reftitle'] = reftarget return newnode def setup(app): app.connect('autodoc-process-docstring', process_docstring) app.connect('missing-reference', missing_reference_handler) app.connect('env-merge-info', merge_mapping) return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/0000755000077000000240000000000013531324214027730 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/autosummary_core/0000755000077000000240000000000013531324214033326 5ustar adamstaff00000000000000././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/autosummary_core/base.rstradio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/autosummary_core/base.r0000644000077000000240000000025213174167363034437 0ustar adamstaff00000000000000{% if referencefile %} .. include:: {{ referencefile }} {% endif %} {{ objname }} {{ underline }} .. currentmodule:: {{ module }} .. auto{{ objtype }}:: {{ objname }} ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/autosummary_core/class.rstradio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/autosummary_core/class.0000644000077000000240000000221113174167363034445 0ustar adamstaff00000000000000{% if referencefile %} .. include:: {{ referencefile }} {% endif %} {{ objname }} {{ underline }} .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} :show-inheritance: {% if '__init__' in methods %} {% set caught_result = methods.remove('__init__') %} {% endif %} {% block attributes_summary %} {% if attributes %} .. rubric:: Attributes Summary .. autosummary:: {% for item in attributes %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% block methods_summary %} {% if methods %} .. rubric:: Methods Summary .. autosummary:: {% for item in methods %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% block attributes_documentation %} {% if attributes %} .. rubric:: Attributes Documentation {% for item in attributes %} .. autoattribute:: {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block methods_documentation %} {% if methods %} .. rubric:: Methods Documentation {% for item in methods %} .. automethod:: {{ item }} {%- endfor %} {% endif %} {% endblock %} ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/autosummary_core/module.rstradio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/templates/autosummary_core/module0000644000077000000240000000127713174167363034562 0ustar adamstaff00000000000000{% if referencefile %} .. include:: {{ referencefile }} {% endif %} {{ objname }} {{ underline }} .. automodule:: {{ fullname }} {% block functions %} {% if functions %} .. rubric:: Functions .. autosummary:: {% for item in functions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block classes %} {% if classes %} .. rubric:: Classes .. autosummary:: {% for item in classes %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block exceptions %} {% if exceptions %} .. rubric:: Exceptions .. autosummary:: {% for item in exceptions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/automodapi/utils.py0000644000077000000240000001574413174167363027474 0ustar adamstaff00000000000000import inspect import sys import re import os from warnings import warn from sphinx.ext.autosummary.generate import find_autosummary_in_docstring if sys.version_info[0] >= 3: def iteritems(dictionary): return dictionary.items() else: def iteritems(dictionary): return dictionary.iteritems() # We use \n instead of os.linesep because even on Windows, the generated files # use \n as the newline character. SPACE_NEWLINE = ' \n' SINGLE_NEWLINE = '\n' DOUBLE_NEWLINE = '\n\n' TRIPLE_NEWLINE = '\n\n\n' def cleanup_whitespace(text): """ Make sure there are never more than two consecutive newlines, and that there are no trailing whitespaces. """ # Get rid of overall leading/trailing whitespace text = text.strip() + '\n' # Get rid of trailing whitespace on each line while SPACE_NEWLINE in text: text = text.replace(SPACE_NEWLINE, SINGLE_NEWLINE) # Avoid too many consecutive newlines while TRIPLE_NEWLINE in text: text = text.replace(TRIPLE_NEWLINE, DOUBLE_NEWLINE) return text 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 beginwith '_' or are not in `__all__`). Parameters ---------- modname : str The name of the module to search. onlylocals : bool If True, only attributes that are either members of `modname` OR one of its modules or subpackages will be included. 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.misc.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) """ __import__(modname) mod = sys.modules[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: valids = [fqn.startswith(modname) 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 def find_autosummary_in_lines_for_automodsumm(lines, module=None, filename=None): """Find out what items appear in autosummary:: directives in the given lines. Returns a list of (name, toctree, template, inherited_members) where *name* is a name of an object and *toctree* the :toctree: path of the corresponding autosummary directive (relative to the root of the file name), *template* the value of the :template: option, and *inherited_members* is the value of the :inherited-members: option. *toctree*, *template*, and *inherited_members* are ``None`` if the directive does not have the corresponding options set. .. note:: This is a slightly modified version of ``sphinx.ext.autosummary.generate.find_autosummary_in_lines`` which recognizes the ``inherited-members`` option. """ autosummary_re = re.compile(r'^(\s*)\.\.\s+autosummary::\s*') automodule_re = re.compile( r'^\s*\.\.\s+automodule::\s*([A-Za-z0-9_.]+)\s*$') module_re = re.compile( r'^\s*\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') autosummary_item_re = re.compile(r'^\s+(~?[_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$') template_arg_re = re.compile(r'^\s+:template:\s*(.*?)\s*$') inherited_members_arg_re = re.compile(r'^\s+:inherited-members:\s*$') no_inherited_members_arg_re = re.compile(r'^\s+:no-inherited-members:\s*$') documented = [] toctree = None template = None inherited_members = None current_module = module in_autosummary = False base_indent = "" for line in lines: if in_autosummary: m = toctree_arg_re.match(line) if m: toctree = m.group(1) if filename: toctree = os.path.join(os.path.dirname(filename), toctree) continue m = template_arg_re.match(line) if m: template = m.group(1).strip() continue m = inherited_members_arg_re.match(line) if m: inherited_members = True continue m = no_inherited_members_arg_re.match(line) if m: inherited_members = False continue if line.strip().startswith(':'): warn(line) continue # skip options m = autosummary_item_re.match(line) if m: name = m.group(1).strip() if name.startswith('~'): name = name[1:] if current_module and \ not name.startswith(current_module + '.'): name = "%s.%s" % (current_module, name) documented.append((name, toctree, template, inherited_members)) continue if not line.strip() or line.startswith(base_indent + " "): continue in_autosummary = False m = autosummary_re.match(line) if m: in_autosummary = True base_indent = m.group(1) toctree = None template = None inherited_members = None continue m = automodule_re.search(line) if m: current_module = m.group(1).strip() # recurse into the automodule docstring documented.extend(find_autosummary_in_docstring( current_module, filename=filename)) continue m = module_re.match(line) if m: current_module = m.group(2) continue return documented radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/numpydoc/0000755000077000000240000000000013531324214025426 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/numpydoc/__init__.py0000644000077000000240000000030213516112504027532 0ustar adamstaff00000000000000from __future__ import division, absolute_import, print_function __version__ = '0.8.0' def setup(app, *args, **kwargs): from .numpydoc import setup return setup(app, *args, **kwargs) radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/numpydoc/docscrape.py0000644000077000000240000004540613516112504027754 0ustar adamstaff00000000000000"""Extract reference documentation from the NumPy source tree. """ from __future__ import division, absolute_import, print_function import inspect import textwrap import re import pydoc from warnings import warn import collections import copy import sys def strip_blank_lines(l): "Remove leading and trailing blank lines from a list of lines" while l and not l[0].strip(): del l[0] while l and not l[-1].strip(): del l[-1] return l class Reader(object): """A line-based string reader. """ def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data, list): self._str = data else: self._str = data.split('\n') # store string as list of lines self.reset() def __getitem__(self, n): return self._str[n] def reset(self): self._l = 0 # current line nr def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return '' def seek_next_non_empty_line(self): for l in self[self._l:]: if l.strip(): break else: self._l += 1 def eof(self): return self._l >= len(self._str) def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start:self._l] self._l += 1 if self.eof(): return self[start:self._l+1] return [] def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty) def read_to_next_unindented_line(self): def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line))) return self.read_to_condition(is_unindented) def peek(self, n=0): if self._l + n < len(self._str): return self[self._l + n] else: return '' def is_empty(self): return not ''.join(self._str).strip() class ParseError(Exception): def __str__(self): message = self.args[0] if hasattr(self, 'docstring'): message = "%s in %r" % (message, self.docstring) return message class NumpyDocString(collections.Mapping): """Parses a numpydoc string to an abstract representation Instances define a mapping from section title to structured data. """ sections = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Yields': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], 'Notes': [], 'Warnings': [], 'References': '', 'Examples': '', 'index': {} } def __init__(self, docstring, config={}): orig_docstring = docstring docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = copy.deepcopy(self.sections) try: self._parse() except ParseError as e: e.docstring = orig_docstring raise def __getitem__(self, key): return self._parsed_data[key] def __setitem__(self, key, val): if key not in self._parsed_data: self._error_location("Unknown section %s" % key, error=False) else: self._parsed_data[key] = val def __iter__(self): return iter(self._parsed_data) def __len__(self): return len(self._parsed_data) def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) def _strip(self, doc): i = 0 j = 0 for i, line in enumerate(doc): if line.strip(): break for j, line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc)-j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self, content): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) desc = strip_blank_lines(desc) params.append((arg_name, arg_type, desc)) return params _name_rgx = re.compile(r"^\s*(:(?P\w+):" r"`(?P(?:~\w+\.)?[a-zA-Z0-9_.-]+)`|" r" (?P[a-zA-Z0-9_.-]+))\s*", re.X) def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ParseError("%s is not a item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): if func.strip(): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): continue break if summary is not None: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() sections = list(self._read_sections()) section_names = set([section for section, content in sections]) has_returns = 'Returns' in section_names has_yields = 'Yields' in section_names # We could do more tests, but we are not. Arbitrarily. if has_returns and has_yields: msg = 'Docstring contains both a Returns and Yields section.' raise ValueError(msg) for (section, content) in sections: if not section.startswith('..'): section = (s.capitalize() for s in section.split(' ')) section = ' '.join(section) if self.get(section): self._error_location("The section %s appears twice" % section) if section in ('Parameters', 'Returns', 'Yields', 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content def _error_location(self, msg, error=True): if hasattr(self, '_obj'): # we know where the docs came from: try: filename = inspect.getsourcefile(self._obj) except TypeError: filename = None msg = msg + (" in the docstring of %s in %s." % (self._obj, filename)) if error: raise ValueError(msg) else: warn(msg) # string conversion routines def _str_header(self, name, symbol='-'): return [name, len(name)*symbol] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*', '\*')] + [''] else: return [''] def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return [] def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param, param_type, desc in self[name]: if param_type: out += ['%s : %s' % (param, param_type)] else: out += [param] if desc and ''.join(desc).strip(): out += self._str_indent(desc) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") last_had_desc = True for func, desc, role in self['See Also']: if role: link = ':%s:`%s`' % (role, func) elif func_role: link = ':%s:`%s`' % (func_role, func) else: link = "`%s`_" % func if desc or last_had_desc: out += [''] out += [link] else: out[-1] += ", %s" % link if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += [''] return out def _str_index(self): idx = self['index'] out = [] out += ['.. index:: %s' % idx.get('default', '')] for section, references in idx.items(): if section == 'default': continue out += [' :%s: %s' % (section, ', '.join(references))] return out def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Returns', 'Yields', 'Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes', 'References', 'Examples'): out += self._str_section(s) for param_list in ('Attributes', 'Methods'): out += self._str_param_list(param_list) out += self._str_index() return '\n'.join(out) def indent(str, indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") def header(text, style='-'): return text + '\n' + style*len(text) + '\n' class FunctionDoc(NumpyDocString): def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: try: signature = str(inspect.signature(func)) except (AttributeError, ValueError): # try to read signature, backward compat for older Python if sys.version_info[0] >= 3: argspec = inspect.getfullargspec(func) else: argspec = inspect.getargspec(func) signature = inspect.formatargspec(*argspec) signature = '%s%s' % (func_name, signature.replace('*', '\*')) except TypeError: signature = '%s()' % func_name self['Signature'] = signature def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, '__call__', self._f.__init__) else: func = self._f return func, func_name def __str__(self): out = '' func, func_name = self.get_func() signature = self['Signature'].replace('*', '\*') roles = {'func': 'function', 'meth': 'method'} if self._role: if self._role not in roles: print("Warning: invalid role %s" % self._role) out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''), func_name) out += super(FunctionDoc, self).__str__(func_role=self._role) return out class ClassDoc(NumpyDocString): extra_public_methods = ['__call__'] def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config={}): if not inspect.isclass(cls) and cls is not None: raise ValueError("Expected a class or None, but got %r" % cls) self._cls = cls self.show_inherited_members = config.get( 'show_inherited_class_members', True) if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename if doc is None: if cls is None: raise ValueError("No class or documentation string given") doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) if config.get('show_class_members', True): def splitlines_x(s): if not s: return [] else: return s.splitlines() for field, items in [('Methods', self.methods), ('Attributes', self.properties)]: if not self[field]: doc_list = [] for name in sorted(items): try: doc_item = pydoc.getdoc(getattr(self._cls, name)) doc_list.append((name, '', splitlines_x(doc_item))) except AttributeError: pass # method doesn't exist self[field] = doc_list @property def methods(self): if self._cls is None: return [] return [name for name, func in inspect.getmembers(self._cls) if ((not name.startswith('_') or name in self.extra_public_methods) and isinstance(func, collections.Callable) and self._is_show_member(name))] @property def properties(self): if self._cls is None: return [] return [name for name, func in inspect.getmembers(self._cls) if (not name.startswith('_') and (func is None or isinstance(func, property) or inspect.isdatadescriptor(func)) and self._is_show_member(name))] def _is_show_member(self, name): if self.show_inherited_members: return True # show all class members if name not in self._cls.__dict__: return False # class member is inherited, we do not show it return True radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/numpydoc/docscrape_sphinx.py0000644000077000000240000003547013516112504031345 0ustar adamstaff00000000000000from __future__ import division, absolute_import, print_function import sys import re import inspect import textwrap import pydoc import collections import os from jinja2 import FileSystemLoader from jinja2.sandbox import SandboxedEnvironment import sphinx from sphinx.jinja2glue import BuiltinTemplateLoader from .docscrape import NumpyDocString, FunctionDoc, ClassDoc if sys.version_info[0] >= 3: sixu = lambda s: s else: sixu = lambda s: unicode(s, 'unicode_escape') IMPORT_MATPLOTLIB_RE = r'\b(import +matplotlib|from +matplotlib +import)\b' class SphinxDocString(NumpyDocString): def __init__(self, docstring, config={}): NumpyDocString.__init__(self, docstring, config=config) self.load_config(config) def load_config(self, config): self.use_plots = config.get('use_plots', False) self.use_blockquotes = config.get('use_blockquotes', False) self.class_members_toctree = config.get('class_members_toctree', True) self.template = config.get('template', None) if self.template is None: template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')] template_loader = FileSystemLoader(template_dirs) template_env = SandboxedEnvironment(loader=template_loader) self.template = template_env.get_template('numpydoc_docstring.rst') # string conversion routines def _str_header(self, name, symbol='`'): return ['.. rubric:: ' + name, ''] def _str_field_list(self, name): return [':' + name + ':'] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): return [''] if self['Signature']: return ['``%s``' % self['Signature']] + [''] else: return [''] def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Extended Summary'] + [''] def _str_returns(self, name='Returns'): typed_fmt = '**%s** : %s' untyped_fmt = '**%s**' out = [] if self[name]: out += self._str_field_list(name) out += [''] for param, param_type, desc in self[name]: if param_type: out += self._str_indent([typed_fmt % (param.strip(), param_type)]) else: out += self._str_indent([untyped_fmt % param.strip()]) if desc and self.use_blockquotes: out += [''] elif not desc: desc = ['..'] out += self._str_indent(desc, 8) out += [''] return out def _process_param(self, param, desc, fake_autosummary): """Determine how to display a parameter Emulates autosummary behavior if fake_autosummary Parameters ---------- param : str The name of the parameter desc : list of str The parameter description as given in the docstring. This is ignored when autosummary logic applies. fake_autosummary : bool If True, autosummary-style behaviour will apply for params that are attributes of the class and have a docstring. Returns ------- display_param : str The marked up parameter name for display. This may include a link to the corresponding attribute's own documentation. desc : list of str A list of description lines. This may be identical to the input ``desc``, if ``autosum is None`` or ``param`` is not a class attribute, or it will be a summary of the class attribute's docstring. Notes ----- This does not have the autosummary functionality to display a method's signature, and hence is not used to format methods. It may be complicated to incorporate autosummary's signature mangling, as it relies on Sphinx's plugin mechanism. """ param = param.strip() # XXX: If changing the following, please check the rendering when param # ends with '_', e.g. 'word_' # See https://github.com/numpy/numpydoc/pull/144 display_param = '**%s**' % param if not fake_autosummary: return display_param, desc param_obj = getattr(self._obj, param, None) if not (callable(param_obj) or isinstance(param_obj, property) or inspect.isgetsetdescriptor(param_obj)): param_obj = None obj_doc = pydoc.getdoc(param_obj) if not (param_obj and obj_doc): return display_param, desc prefix = getattr(self, '_name', '') if prefix: autosum_prefix = '~%s.' % prefix link_prefix = '%s.' % prefix else: autosum_prefix = '' link_prefix = '' # Referenced object has a docstring display_param = ':obj:`%s <%s%s>`' % (param, link_prefix, param) if obj_doc: # Overwrite desc. Take summary logic of autosummary desc = re.split('\n\s*\n', obj_doc.strip(), 1)[0] # XXX: Should this have DOTALL? # It does not in autosummary m = re.search(r"^([A-Z].*?\.)(?:\s|$)", ' '.join(desc.split())) if m: desc = m.group(1).strip() else: desc = desc.partition('\n')[0] desc = desc.split('\n') return display_param, desc def _str_param_list(self, name, fake_autosummary=False): """Generate RST for a listing of parameters or similar Parameter names are displayed as bold text, and descriptions are in blockquotes. Descriptions may therefore contain block markup as well. Parameters ---------- name : str Section name (e.g. Parameters) fake_autosummary : bool When True, the parameter names may correspond to attributes of the object beign documented, usually ``property`` instances on a class. In this case, names will be linked to fuller descriptions. Returns ------- rst : list of str """ out = [] if self[name]: out += self._str_field_list(name) out += [''] for param, param_type, desc in self[name]: display_param, desc = self._process_param(param, desc, fake_autosummary) if param_type: out += self._str_indent(['%s : %s' % (display_param, param_type)]) else: out += self._str_indent([display_param]) if desc and self.use_blockquotes: out += [''] elif not desc: # empty definition desc = ['..'] out += self._str_indent(desc, 8) out += [''] return out @property def _obj(self): if hasattr(self, '_cls'): return self._cls elif hasattr(self, '_f'): return self._f return None def _str_member_list(self, name): """ Generate a member listing, autosummary:: table where possible, and a table where not. """ out = [] if self[name]: out += ['.. rubric:: %s' % name, ''] prefix = getattr(self, '_name', '') if prefix: prefix = '~%s.' % prefix autosum = [] others = [] for param, param_type, desc in self[name]: param = param.strip() # Check if the referenced member can have a docstring or not param_obj = getattr(self._obj, param, None) if not (callable(param_obj) or isinstance(param_obj, property) or inspect.isdatadescriptor(param_obj)): param_obj = None if param_obj and pydoc.getdoc(param_obj): # Referenced object has a docstring autosum += [" %s%s" % (prefix, param)] else: others.append((param, param_type, desc)) if autosum: out += ['.. autosummary::'] if self.class_members_toctree: out += [' :toctree:'] out += [''] + autosum if others: maxlen_0 = max(3, max([len(x[0]) + 4 for x in others])) hdr = sixu("=") * maxlen_0 + sixu(" ") + sixu("=") * 10 fmt = sixu('%%%ds %%s ') % (maxlen_0,) out += ['', '', hdr] for param, param_type, desc in others: desc = sixu(" ").join(x.strip() for x in desc).strip() if param_type: desc = "(%s) %s" % (param_type, desc) out += [fmt % ("**" + param.strip() + "**", desc)] out += [hdr] out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) content = textwrap.dedent("\n".join(self[name])).split("\n") out += content out += [''] return out def _str_see_also(self, func_role): out = [] if self['See Also']: see_also = super(SphinxDocString, self)._str_see_also(func_role) out = ['.. seealso::', ''] out += self._str_indent(see_also[2:]) return out def _str_warnings(self): out = [] if self['Warnings']: out = ['.. warning::', ''] out += self._str_indent(self['Warnings']) out += [''] return out def _str_index(self): idx = self['index'] out = [] if len(idx) == 0: return out out += ['.. index:: %s' % idx.get('default', '')] for section, references in idx.items(): if section == 'default': continue elif section == 'refguide': out += [' single: %s' % (', '.join(references))] else: out += [' %s: %s' % (section, ','.join(references))] out += [''] return out def _str_references(self): out = [] if self['References']: out += self._str_header('References') if isinstance(self['References'], str): self['References'] = [self['References']] out.extend(self['References']) out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it if sphinx.__version__ >= "0.6": out += ['.. only:: latex', ''] else: out += ['.. latexonly::', ''] items = [] for line in self['References']: m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] return out def _str_examples(self): examples_str = "\n".join(self['Examples']) if (self.use_plots and re.search(IMPORT_MATPLOTLIB_RE, examples_str) and 'plot::' not in examples_str): out = [] out += self._str_header('Examples') out += ['.. plot::', ''] out += self._str_indent(self['Examples']) out += [''] return out else: return self._str_section('Examples') def __str__(self, indent=0, func_role="obj"): ns = { 'signature': self._str_signature(), 'index': self._str_index(), 'summary': self._str_summary(), 'extended_summary': self._str_extended_summary(), 'parameters': self._str_param_list('Parameters'), 'returns': self._str_returns('Returns'), 'yields': self._str_returns('Yields'), 'other_parameters': self._str_param_list('Other Parameters'), 'raises': self._str_param_list('Raises'), 'warns': self._str_param_list('Warns'), 'warnings': self._str_warnings(), 'see_also': self._str_see_also(func_role), 'notes': self._str_section('Notes'), 'references': self._str_references(), 'examples': self._str_examples(), 'attributes': self._str_param_list('Attributes', fake_autosummary=True), 'methods': self._str_member_list('Methods'), } ns = dict((k, '\n'.join(v)) for k, v in ns.items()) rendered = self.template.render(**ns) return '\n'.join(self._str_indent(rendered.split('\n'), indent)) class SphinxFunctionDoc(SphinxDocString, FunctionDoc): def __init__(self, obj, doc=None, config={}): self.load_config(config) FunctionDoc.__init__(self, obj, doc=doc, config=config) class SphinxClassDoc(SphinxDocString, ClassDoc): def __init__(self, obj, doc=None, func_doc=None, config={}): self.load_config(config) ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config) class SphinxObjDoc(SphinxDocString): def __init__(self, obj, doc=None, config={}): self._f = obj self.load_config(config) SphinxDocString.__init__(self, doc, config=config) def get_doc_object(obj, what=None, doc=None, config={}, builder=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif isinstance(obj, collections.Callable): what = 'function' else: what = 'object' template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')] if builder is not None: template_loader = BuiltinTemplateLoader() template_loader.init(builder, dirs=template_dirs) else: template_loader = FileSystemLoader(template_dirs) template_env = SandboxedEnvironment(loader=template_loader) config['template'] = template_env.get_template('numpydoc_docstring.rst') if what == 'class': return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxObjDoc(obj, doc, config=config) radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/numpydoc/numpydoc.py0000644000077000000240000002620313516112504027641 0ustar adamstaff00000000000000""" ======== numpydoc ======== Sphinx extension that handles docstrings in the Numpy standard format. [1] It will: - Convert Parameters etc. sections to field lists. - Convert See Also section to a See also entry. - Renumber references. - Extract the signature from the docstring, if it can't be determined otherwise. .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt """ from __future__ import division, absolute_import, print_function import sys import re import pydoc import inspect import collections import hashlib from docutils.nodes import citation, Text import sphinx from sphinx.addnodes import pending_xref, desc_content if sphinx.__version__ < '1.0.1': raise RuntimeError("Sphinx 1.0.1 or newer is required") from .docscrape_sphinx import get_doc_object, SphinxDocString from . import __version__ if sys.version_info[0] >= 3: sixu = lambda s: s else: sixu = lambda s: unicode(s, 'unicode_escape') HASH_LEN = 12 def rename_references(app, what, name, obj, options, lines): # decorate reference numbers so that there are no duplicates # these are later undecorated in the doctree, in relabel_references references = set() for line in lines: line = line.strip() m = re.match(sixu('^.. \\[(%s)\\]') % app.config.numpydoc_citation_re, line, re.I) if m: references.add(m.group(1)) if references: # we use a hash to mangle the reference name to avoid invalid names sha = hashlib.sha256() sha.update(name.encode('utf8')) prefix = 'R' + sha.hexdigest()[:HASH_LEN] for r in references: new_r = prefix + '-' + r for i, line in enumerate(lines): lines[i] = lines[i].replace(sixu('[%s]_') % r, sixu('[%s]_') % new_r) lines[i] = lines[i].replace(sixu('.. [%s]') % r, sixu('.. [%s]') % new_r) def _ascend(node, cls): while node and not isinstance(node, cls): node = node.parent return node def relabel_references(app, doc): # Change 'hash-ref' to 'ref' in label text for citation_node in doc.traverse(citation): if _ascend(citation_node, desc_content) is None: # no desc node in ancestry -> not in a docstring # XXX: should we also somehow check it's in a References section? continue label_node = citation_node[0] prefix, _, new_label = label_node[0].astext().partition('-') assert len(prefix) == HASH_LEN + 1 new_text = Text(new_label) label_node.replace(label_node[0], new_text) for id in citation_node['backrefs']: ref = doc.ids[id] ref_text = ref[0] # Sphinx has created pending_xref nodes with [reftext] text. def matching_pending_xref(node): return (isinstance(node, pending_xref) and node[0].astext() == '[%s]' % ref_text) for xref_node in ref.parent.traverse(matching_pending_xref): xref_node.replace(xref_node[0], Text('[%s]' % new_text)) ref.replace(ref_text, new_text.copy()) DEDUPLICATION_TAG = ' !! processed by numpydoc !!' def mangle_docstrings(app, what, name, obj, options, lines): if DEDUPLICATION_TAG in lines: return cfg = {'use_plots': app.config.numpydoc_use_plots, 'use_blockquotes': app.config.numpydoc_use_blockquotes, 'show_class_members': app.config.numpydoc_show_class_members, 'show_inherited_class_members': app.config.numpydoc_show_inherited_class_members, 'class_members_toctree': app.config.numpydoc_class_members_toctree} u_NL = sixu('\n') if what == 'module': # Strip top title pattern = '^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*' title_re = re.compile(sixu(pattern), re.I | re.S) lines[:] = title_re.sub(sixu(''), u_NL.join(lines)).split(u_NL) else: doc = get_doc_object(obj, what, u_NL.join(lines), config=cfg, builder=app.builder) if sys.version_info[0] >= 3: doc = str(doc) else: doc = unicode(doc) lines[:] = doc.split(u_NL) if (app.config.numpydoc_edit_link and hasattr(obj, '__name__') and obj.__name__): if hasattr(obj, '__module__'): v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__)) else: v = dict(full_name=obj.__name__) lines += [sixu(''), sixu('.. htmlonly::'), sixu('')] lines += [sixu(' %s') % x for x in (app.config.numpydoc_edit_link % v).split("\n")] # call function to replace reference numbers so that there are no # duplicates rename_references(app, what, name, obj, options, lines) lines += ['..', DEDUPLICATION_TAG] def mangle_signature(app, what, name, obj, options, sig, retann): # Do not try to inspect classes that don't define `__init__` if (inspect.isclass(obj) and (not hasattr(obj, '__init__') or 'initializes x; see ' in pydoc.getdoc(obj.__init__))): return '', '' if not (isinstance(obj, collections.Callable) or hasattr(obj, '__argspec_is_invalid_')): return if not hasattr(obj, '__doc__'): return doc = SphinxDocString(pydoc.getdoc(obj)) sig = doc['Signature'] or getattr(obj, '__text_signature__', None) if sig: sig = re.sub(sixu("^[^(]*"), sixu(""), sig) return sig, sixu('') def setup(app, get_doc_object_=get_doc_object): if not hasattr(app, 'add_config_value'): return # probably called by nose, better bail out global get_doc_object get_doc_object = get_doc_object_ app.connect('autodoc-process-docstring', mangle_docstrings) app.connect('autodoc-process-signature', mangle_signature) app.connect('doctree-read', relabel_references) app.add_config_value('numpydoc_edit_link', None, False) app.add_config_value('numpydoc_use_plots', None, False) app.add_config_value('numpydoc_use_blockquotes', None, False) app.add_config_value('numpydoc_show_class_members', True, True) app.add_config_value('numpydoc_show_inherited_class_members', True, True) app.add_config_value('numpydoc_class_members_toctree', True, True) app.add_config_value('numpydoc_citation_re', '[a-z0-9_.-]+', True) # Extra mangling domains app.add_domain(NumpyPythonDomain) app.add_domain(NumpyCDomain) app.setup_extension('sphinx.ext.autosummary') metadata = {'version': __version__, 'parallel_read_safe': True} return metadata # ------------------------------------------------------------------------------ # Docstring-mangling domains # ------------------------------------------------------------------------------ from docutils.statemachine import ViewList from sphinx.domains.c import CDomain from sphinx.domains.python import PythonDomain class ManglingDomainBase(object): directive_mangling_map = {} def __init__(self, *a, **kw): super(ManglingDomainBase, self).__init__(*a, **kw) self.wrap_mangling_directives() def wrap_mangling_directives(self): for name, objtype in list(self.directive_mangling_map.items()): self.directives[name] = wrap_mangling_directive( self.directives[name], objtype) class NumpyPythonDomain(ManglingDomainBase, PythonDomain): name = 'np' directive_mangling_map = { 'function': 'function', 'class': 'class', 'exception': 'class', 'method': 'function', 'classmethod': 'function', 'staticmethod': 'function', 'attribute': 'attribute', } indices = [] class NumpyCDomain(ManglingDomainBase, CDomain): name = 'np-c' directive_mangling_map = { 'function': 'function', 'member': 'attribute', 'macro': 'function', 'type': 'class', 'var': 'object', } def match_items(lines, content_old): """Create items for mangled lines. This function tries to match the lines in ``lines`` with the items (source file references and line numbers) in ``content_old``. The ``mangle_docstrings`` function changes the actual docstrings, but doesn't keep track of where each line came from. The manging does many operations on the original lines, which are hard to track afterwards. Many of the line changes come from deleting or inserting blank lines. This function tries to match lines by ignoring blank lines. All other changes (such as inserting figures or changes in the references) are completely ignored, so the generated line numbers will be off if ``mangle_docstrings`` does anything non-trivial. This is a best-effort function and the real fix would be to make ``mangle_docstrings`` actually keep track of the ``items`` together with the ``lines``. Examples -------- >>> lines = ['', 'A', '', 'B', ' ', '', 'C', 'D'] >>> lines_old = ['a', '', '', 'b', '', 'c'] >>> items_old = [('file1.py', 0), ('file1.py', 1), ('file1.py', 2), ... ('file2.py', 0), ('file2.py', 1), ('file2.py', 2)] >>> content_old = ViewList(lines_old, items=items_old) >>> match_items(lines, content_old) # doctest: +NORMALIZE_WHITESPACE [('file1.py', 0), ('file1.py', 0), ('file2.py', 0), ('file2.py', 0), ('file2.py', 2), ('file2.py', 2), ('file2.py', 2), ('file2.py', 2)] >>> # first 2 ``lines`` are matched to 'a', second 2 to 'b', rest to 'c' >>> # actual content is completely ignored. Notes ----- The algorithm tries to match any line in ``lines`` with one in ``lines_old``. It skips over all empty lines in ``lines_old`` and assigns this line number to all lines in ``lines``, unless a non-empty line is found in ``lines`` in which case it goes to the next line in ``lines_old``. """ items_new = [] lines_old = content_old.data items_old = content_old.items j = 0 for i, line in enumerate(lines): # go to next non-empty line in old: # line.strip() checks whether the string is all whitespace while j < len(lines_old) - 1 and not lines_old[j].strip(): j += 1 items_new.append(items_old[j]) if line.strip() and j < len(lines_old) - 1: j += 1 assert(len(items_new) == len(lines)) return items_new def wrap_mangling_directive(base_directive, objtype): class directive(base_directive): def run(self): env = self.state.document.settings.env name = None if self.arguments: m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0]) name = m.group(2).strip() if not name: name = self.arguments[0] lines = list(self.content) mangle_docstrings(env.app, objtype, name, None, None, lines) if self.content: items = match_items(lines, self.content) self.content = ViewList(lines, items=items, parent=self.content.parent) return base_directive.run(self) return directive radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/numpydoc/templates/0000755000077000000240000000000013531324214027424 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/numpydoc/templates/numpydoc_docstring.rst0000644000077000000240000000032613174167433034104 0ustar adamstaff00000000000000{{index}} {{summary}} {{extended_summary}} {{parameters}} {{returns}} {{yields}} {{other_parameters}} {{raises}} {{warns}} {{warnings}} {{see_also}} {{notes}} {{references}} {{examples}} {{attributes}} {{methods}} radio_beam-0.3.2/astropy_helpers/astropy_helpers/extern/setup_package.py0000644000077000000240000000027513174167433026774 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return {'astropy_helpers.extern': ['automodapi/templates/*/*.rst', 'numpydoc/templates/*.rst']} radio_beam-0.3.2/astropy_helpers/astropy_helpers/git_helpers.py0000644000077000000240000001450113234725027025152 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for retrieving revision information from a project's git repository. """ # Do not remove the following comment; it is used by # astropy_helpers.version_helpers to determine the beginning of the code in # this module # BEGIN import locale import os import subprocess import warnings def _decode_stdio(stream): try: stdio_encoding = locale.getdefaultlocale()[1] or 'utf-8' except ValueError: stdio_encoding = 'utf-8' try: text = stream.decode(stdio_encoding) except UnicodeDecodeError: # Final fallback text = stream.decode('latin1') return text def update_git_devstr(version, path=None): """ Updates the git revision string if and only if the path is being imported directly from a git working copy. This ensures that the revision number in the version string is accurate. """ try: # Quick way to determine if we're in git or not - returns '' if not devstr = get_git_devstr(sha=True, show_warning=False, path=path) except OSError: return version if not devstr: # Probably not in git so just pass silently return version if 'dev' in version: # update to the current git revision version_base = version.split('.dev', 1)[0] devstr = get_git_devstr(sha=False, show_warning=False, path=path) return version_base + '.dev' + devstr else: # otherwise it's already the true/release version return version def get_git_devstr(sha=False, show_warning=True, path=None): """ Determines the number of revisions in this repository. Parameters ---------- sha : bool If True, the full SHA1 hash will be returned. Otherwise, the total count of commits in the repository will be used as a "revision number". show_warning : bool If True, issue a warning if git returns an error code, otherwise errors pass silently. path : str or None If a string, specifies the directory to look in to find the git repository. If `None`, the current working directory is used, and must be the root of the git repository. If given a filename it uses the directory containing that file. Returns ------- devversion : str Either a string with the revision number (if `sha` is False), the SHA1 hash of the current commit (if `sha` is True), or an empty string if git version info could not be identified. """ if path is None: path = os.getcwd() if not os.path.isdir(path): path = os.path.abspath(os.path.dirname(path)) if sha: # Faster for getting just the hash of HEAD cmd = ['rev-parse', 'HEAD'] else: cmd = ['rev-list', '--count', 'HEAD'] def run_git(cmd): try: p = subprocess.Popen(['git'] + cmd, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdout, stderr = p.communicate() except OSError as e: if show_warning: warnings.warn('Error running git: ' + str(e)) return (None, b'', b'') if p.returncode == 128: if show_warning: warnings.warn('No git repository present at {0!r}! Using ' 'default dev version.'.format(path)) return (p.returncode, b'', b'') if p.returncode == 129: if show_warning: warnings.warn('Your git looks old (does it support {0}?); ' 'consider upgrading to v1.7.2 or ' 'later.'.format(cmd[0])) return (p.returncode, stdout, stderr) elif p.returncode != 0: if show_warning: warnings.warn('Git failed while determining revision ' 'count: {0}'.format(_decode_stdio(stderr))) return (p.returncode, stdout, stderr) return p.returncode, stdout, stderr returncode, stdout, stderr = run_git(cmd) if not sha and returncode == 128: # git returns 128 if the command is not run from within a git # repository tree. In this case, a warning is produced above but we # return the default dev version of '0'. return '0' elif not sha and returncode == 129: # git returns 129 if a command option failed to parse; in # particular this could happen in git versions older than 1.7.2 # where the --count option is not supported # Also use --abbrev-commit and --abbrev=0 to display the minimum # number of characters needed per-commit (rather than the full hash) cmd = ['rev-list', '--abbrev-commit', '--abbrev=0', 'HEAD'] returncode, stdout, stderr = run_git(cmd) # Fall back on the old method of getting all revisions and counting # the lines if returncode == 0: return str(stdout.count(b'\n')) else: return '' elif sha: return _decode_stdio(stdout)[:40] else: return _decode_stdio(stdout).strip() # This function is tested but it is only ever executed within a subprocess when # creating a fake package, so it doesn't get picked up by coverage metrics. def _get_repo_path(pathname, levels=None): # pragma: no cover """ Given a file or directory name, determine the root of the git repository this path is under. If given, this won't look any higher than ``levels`` (that is, if ``levels=0`` then the given path must be the root of the git repository and is returned if so. Returns `None` if the given path could not be determined to belong to a git repo. """ if os.path.isfile(pathname): current_dir = os.path.abspath(os.path.dirname(pathname)) elif os.path.isdir(pathname): current_dir = os.path.abspath(pathname) else: return None current_level = 0 while levels is None or current_level <= levels: if os.path.exists(os.path.join(current_dir, '.git')): return current_dir current_level += 1 if current_dir == os.path.dirname(current_dir): break current_dir = os.path.dirname(current_dir) return None radio_beam-0.3.2/astropy_helpers/astropy_helpers/openmp_helpers.py0000644000077000000240000000611113516112504025654 0ustar adamstaff00000000000000# This module defines functions that can be used to check whether OpenMP is # available and if so what flags to use. To use this, import the # add_openmp_flags_if_available function in a setup_package.py file where you # are defining your extensions: # # from astropy_helpers.openmp_helpers import add_openmp_flags_if_available # # then call it with a single extension as the only argument: # # add_openmp_flags_if_available(extension) # # this will add the OpenMP flags if available. from __future__ import absolute_import, print_function import os import sys import glob import tempfile import subprocess from distutils import log from distutils.ccompiler import new_compiler from distutils.sysconfig import customize_compiler from distutils.errors import CompileError, LinkError from .distutils_helpers import get_compiler_option __all__ = ['add_openmp_flags_if_available'] CCODE = """ #include #include int main(void) { #pragma omp parallel printf("nthreads=%d\\n", omp_get_num_threads()); return 0; } """ def add_openmp_flags_if_available(extension): """ Add OpenMP compilation flags, if available (if not a warning will be printed to the console and no flags will be added) Returns `True` if the flags were added, `False` otherwise. """ ccompiler = new_compiler() customize_compiler(ccompiler) tmp_dir = tempfile.mkdtemp() start_dir = os.path.abspath('.') if get_compiler_option() == 'msvc': compile_flag = '-openmp' link_flag = '' else: compile_flag = '-fopenmp' link_flag = '-fopenmp' try: os.chdir(tmp_dir) with open('test_openmp.c', 'w') as f: f.write(CCODE) os.mkdir('objects') # Compile, link, and run test program ccompiler.compile(['test_openmp.c'], output_dir='objects', extra_postargs=[compile_flag]) ccompiler.link_executable(glob.glob(os.path.join('objects', '*' + ccompiler.obj_extension)), 'test_openmp', extra_postargs=[link_flag]) output = subprocess.check_output('./test_openmp').decode(sys.stdout.encoding or 'utf-8').splitlines() if 'nthreads=' in output[0]: nthreads = int(output[0].strip().split('=')[1]) if len(output) == nthreads: using_openmp = True else: log.warn("Unexpected number of lines from output of test OpenMP " "program (output was {0})".format(output)) using_openmp = False else: log.warn("Unexpected output from test OpenMP " "program (output was {0})".format(output)) using_openmp = False except (CompileError, LinkError): using_openmp = False finally: os.chdir(start_dir) if using_openmp: log.info("Compiling Cython extension with OpenMP support") extension.extra_compile_args.append(compile_flag) extension.extra_link_args.append(link_flag) else: log.warn("Cannot compile Cython extension with OpenMP, reverting to non-parallel code") return using_openmp radio_beam-0.3.2/astropy_helpers/astropy_helpers/setup_helpers.py0000644000077000000240000006636013516112504025532 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains a number of utilities for use during setup/build/packaging that are useful to astropy as a whole. """ from __future__ import absolute_import, print_function import collections import os import re import subprocess import sys import traceback import warnings from distutils import log from distutils.dist import Distribution from distutils.errors import DistutilsOptionError, DistutilsModuleError from distutils.core import Extension from distutils.core import Command from distutils.command.sdist import sdist as DistutilsSdist from setuptools import find_packages as _find_packages from .distutils_helpers import (add_command_option, get_compiler_option, get_dummy_distribution, get_distutils_build_option, get_distutils_build_or_install_option) from .version_helpers import get_pkg_version_module from .utils import (walk_skip_hidden, import_file, extends_doc, resolve_name, AstropyDeprecationWarning) from .commands.build_ext import generate_build_ext_command from .commands.build_py import AstropyBuildPy from .commands.install import AstropyInstall from .commands.install_lib import AstropyInstallLib from .commands.register import AstropyRegister from .commands.test import AstropyTest # These imports are not used in this module, but are included for backwards # compat with older versions of this module from .utils import get_numpy_include_path, write_if_different # noqa from .commands.build_ext import should_build_with_cython, get_compiler_version # noqa _module_state = {'registered_commands': None, 'have_sphinx': False, 'package_cache': None, 'exclude_packages': set(), 'excludes_too_late': False} try: import sphinx # noqa _module_state['have_sphinx'] = True except ValueError as e: # This can occur deep in the bowels of Sphinx's imports by way of docutils # and an occurrence of this bug: http://bugs.python.org/issue18378 # In this case sphinx is effectively unusable if 'unknown locale' in e.args[0]: log.warn( "Possible misconfiguration of one of the environment variables " "LC_ALL, LC_CTYPES, LANG, or LANGUAGE. For an example of how to " "configure your system's language environment on OSX see " "http://blog.remibergsma.com/2012/07/10/" "setting-locales-correctly-on-mac-osx-terminal-application/") except ImportError: pass except SyntaxError: # occurs if markupsafe is recent version, which doesn't support Python 3.2 pass PY3 = sys.version_info[0] >= 3 # This adds a new keyword to the setup() function Distribution.skip_2to3 = [] def adjust_compiler(package): """ This function detects broken compilers and switches to another. If the environment variable CC is explicitly set, or a compiler is specified on the commandline, no override is performed -- the purpose here is to only override a default compiler. The specific compilers with problems are: * The default compiler in XCode-4.2, llvm-gcc-4.2, segfaults when compiling wcslib. The set of broken compilers can be updated by changing the compiler_mapping variable. It is a list of 2-tuples where the first in the pair is a regular expression matching the version of the broken compiler, and the second is the compiler to change to. """ warnings.warn( 'Direct use of the adjust_compiler function in setup.py is ' 'deprecated and can be removed from your setup.py. This ' 'functionality is now incorporated directly into the build_ext ' 'command.', AstropyDeprecationWarning) def get_debug_option(packagename): """ Determines if the build is in debug mode. Returns ------- debug : bool True if the current build was started with the debug option, False otherwise. """ try: current_debug = get_pkg_version_module(packagename, fromlist=['debug'])[0] except (ImportError, AttributeError): current_debug = None # Only modify the debug flag if one of the build commands was explicitly # run (i.e. not as a sub-command of something else) dist = get_dummy_distribution() if any(cmd in dist.commands for cmd in ['build', 'build_ext']): debug = bool(get_distutils_build_option('debug')) else: debug = bool(current_debug) if current_debug is not None and current_debug != debug: build_ext_cmd = dist.get_command_class('build_ext') build_ext_cmd.force_rebuild = True return debug def add_exclude_packages(excludes): if _module_state['excludes_too_late']: raise RuntimeError( "add_package_excludes must be called before all other setup helper " "functions in order to properly handle excluded packages") _module_state['exclude_packages'].update(set(excludes)) def register_commands(package, version, release, srcdir='.'): if _module_state['registered_commands'] is not None: return _module_state['registered_commands'] if _module_state['have_sphinx']: try: from .commands.build_sphinx import (AstropyBuildSphinx, AstropyBuildDocs) except ImportError: AstropyBuildSphinx = AstropyBuildDocs = FakeBuildSphinx else: AstropyBuildSphinx = AstropyBuildDocs = FakeBuildSphinx _module_state['registered_commands'] = registered_commands = { 'test': generate_test_command(package), # Use distutils' sdist because it respects package_data. # setuptools/distributes sdist requires duplication of information in # MANIFEST.in 'sdist': DistutilsSdist, # The exact form of the build_ext command depends on whether or not # we're building a release version 'build_ext': generate_build_ext_command(package, release), # We have a custom build_py to generate the default configuration file 'build_py': AstropyBuildPy, # Since install can (in some circumstances) be run without # first building, we also need to override install and # install_lib. See #2223 'install': AstropyInstall, 'install_lib': AstropyInstallLib, 'register': AstropyRegister, 'build_sphinx': AstropyBuildSphinx, 'build_docs': AstropyBuildDocs } # Need to override the __name__ here so that the commandline options are # presented as being related to the "build" command, for example; normally # this wouldn't be necessary since commands also have a command_name # attribute, but there is a bug in distutils' help display code that it # uses __name__ instead of command_name. Yay distutils! for name, cls in registered_commands.items(): cls.__name__ = name # Add a few custom options; more of these can be added by specific packages # later for option in [ ('use-system-libraries', "Use system libraries whenever possible", True)]: add_command_option('build', *option) add_command_option('install', *option) add_command_hooks(registered_commands, srcdir=srcdir) return registered_commands def add_command_hooks(commands, srcdir='.'): """ Look through setup_package.py modules for functions with names like ``pre__hook`` and ``post__hook`` where ```` is the name of a ``setup.py`` command (e.g. build_ext). If either hook is present this adds a wrapped version of that command to the passed in ``commands`` `dict`. ``commands`` may be pre-populated with other custom distutils command classes that should be wrapped if there are hooks for them (e.g. `AstropyBuildPy`). """ hook_re = re.compile(r'^(pre|post)_(.+)_hook$') # Distutils commands have a method of the same name, but it is not a # *classmethod* (which probably didn't exist when distutils was first # written) def get_command_name(cmdcls): if hasattr(cmdcls, 'command_name'): return cmdcls.command_name else: return cmdcls.__name__ packages = filter_packages(find_packages(srcdir)) dist = get_dummy_distribution() hooks = collections.defaultdict(dict) for setuppkg in iter_setup_packages(srcdir, packages): for name, obj in vars(setuppkg).items(): match = hook_re.match(name) if not match: continue hook_type = match.group(1) cmd_name = match.group(2) if hook_type not in hooks[cmd_name]: hooks[cmd_name][hook_type] = [] hooks[cmd_name][hook_type].append((setuppkg.__name__, obj)) for cmd_name, cmd_hooks in hooks.items(): commands[cmd_name] = generate_hooked_command( cmd_name, dist.get_command_class(cmd_name), cmd_hooks) def generate_hooked_command(cmd_name, cmd_cls, hooks): """ Returns a generated subclass of ``cmd_cls`` that runs the pre- and post-command hooks for that command before and after the ``cmd_cls.run`` method. """ def run(self, orig_run=cmd_cls.run): self.run_command_hooks('pre_hooks') orig_run(self) self.run_command_hooks('post_hooks') return type(cmd_name, (cmd_cls, object), {'run': run, 'run_command_hooks': run_command_hooks, 'pre_hooks': hooks.get('pre', []), 'post_hooks': hooks.get('post', [])}) def run_command_hooks(cmd_obj, hook_kind): """Run hooks registered for that command and phase. *cmd_obj* is a finalized command object; *hook_kind* is either 'pre_hook' or 'post_hook'. """ hooks = getattr(cmd_obj, hook_kind, None) if not hooks: return for modname, hook in hooks: if isinstance(hook, str): try: hook_obj = resolve_name(hook) except ImportError as exc: raise DistutilsModuleError( 'cannot find hook {0}: {1}'.format(hook, exc)) else: hook_obj = hook if not callable(hook_obj): raise DistutilsOptionError('hook {0!r} is not callable' % hook) log.info('running {0} from {1} for {2} command'.format( hook_kind.rstrip('s'), modname, cmd_obj.get_command_name())) try: hook_obj(cmd_obj) except Exception: log.error('{0} command hook {1} raised an exception: %s\n'.format( hook_obj.__name__, cmd_obj.get_command_name())) log.error(traceback.format_exc()) sys.exit(1) def generate_test_command(package_name): """ Creates a custom 'test' command for the given package which sets the command's ``package_name`` class attribute to the name of the package being tested. """ return type(package_name.title() + 'Test', (AstropyTest,), {'package_name': package_name}) def update_package_files(srcdir, extensions, package_data, packagenames, package_dirs): """ This function is deprecated and maintained for backward compatibility with affiliated packages. Affiliated packages should update their setup.py to use `get_package_info` instead. """ info = get_package_info(srcdir) extensions.extend(info['ext_modules']) package_data.update(info['package_data']) packagenames = list(set(packagenames + info['packages'])) package_dirs.update(info['package_dir']) def get_package_info(srcdir='.', exclude=()): """ Collates all of the information for building all subpackages and returns a dictionary of keyword arguments that can be passed directly to `distutils.setup`. The purpose of this function is to allow subpackages to update the arguments to the package's ``setup()`` function in its setup.py script, rather than having to specify all extensions/package data directly in the ``setup.py``. See Astropy's own ``setup.py`` for example usage and the Astropy development docs for more details. This function obtains that information by iterating through all packages in ``srcdir`` and locating a ``setup_package.py`` module. This module can contain the following functions: ``get_extensions()``, ``get_package_data()``, ``get_build_options()``, ``get_external_libraries()``, and ``requires_2to3()``. Each of those functions take no arguments. - ``get_extensions`` returns a list of `distutils.extension.Extension` objects. - ``get_package_data()`` returns a dict formatted as required by the ``package_data`` argument to ``setup()``. - ``get_build_options()`` returns a list of tuples describing the extra build options to add. - ``get_external_libraries()`` returns a list of libraries that can optionally be built using external dependencies. - ``get_entry_points()`` returns a dict formatted as required by the ``entry_points`` argument to ``setup()``. - ``requires_2to3()`` should return `True` when the source code requires `2to3` processing to run on Python 3.x. If ``requires_2to3()`` is missing, it is assumed to return `True`. """ ext_modules = [] packages = [] package_data = {} package_dir = {} skip_2to3 = [] if exclude: warnings.warn( "Use of the exclude parameter is no longer supported since it does " "not work as expected. Use add_exclude_packages instead. Note that " "it must be called prior to any other calls from setup helpers.", AstropyDeprecationWarning) # Use the find_packages tool to locate all packages and modules packages = filter_packages(find_packages(srcdir, exclude=exclude)) # Update package_dir if the package lies in a subdirectory if srcdir != '.': package_dir[''] = srcdir # For each of the setup_package.py modules, extract any # information that is needed to install them. The build options # are extracted first, so that their values will be available in # subsequent calls to `get_extensions`, etc. for setuppkg in iter_setup_packages(srcdir, packages): if hasattr(setuppkg, 'get_build_options'): options = setuppkg.get_build_options() for option in options: add_command_option('build', *option) if hasattr(setuppkg, 'get_external_libraries'): libraries = setuppkg.get_external_libraries() for library in libraries: add_external_library(library) if hasattr(setuppkg, 'requires_2to3'): requires_2to3 = setuppkg.requires_2to3() else: requires_2to3 = True if not requires_2to3: skip_2to3.append( os.path.dirname(setuppkg.__file__)) for setuppkg in iter_setup_packages(srcdir, packages): # get_extensions must include any Cython extensions by their .pyx # filename. if hasattr(setuppkg, 'get_extensions'): ext_modules.extend(setuppkg.get_extensions()) if hasattr(setuppkg, 'get_package_data'): package_data.update(setuppkg.get_package_data()) # Locate any .pyx files not already specified, and add their extensions in. # The default include dirs include numpy to facilitate numerical work. ext_modules.extend(get_cython_extensions(srcdir, packages, ext_modules, ['numpy'])) # Now remove extensions that have the special name 'skip_cython', as they # exist Only to indicate that the cython extensions shouldn't be built for i, ext in reversed(list(enumerate(ext_modules))): if ext.name == 'skip_cython': del ext_modules[i] # On Microsoft compilers, we need to pass the '/MANIFEST' # commandline argument. This was the default on MSVC 9.0, but is # now required on MSVC 10.0, but it doesn't seem to hurt to add # it unconditionally. if get_compiler_option() == 'msvc': for ext in ext_modules: ext.extra_link_args.append('/MANIFEST') return { 'ext_modules': ext_modules, 'packages': packages, 'package_dir': package_dir, 'package_data': package_data, 'skip_2to3': skip_2to3 } def iter_setup_packages(srcdir, packages): """ A generator that finds and imports all of the ``setup_package.py`` modules in the source packages. Returns ------- modgen : generator A generator that yields (modname, mod), where `mod` is the module and `modname` is the module name for the ``setup_package.py`` modules. """ for packagename in packages: package_parts = packagename.split('.') package_path = os.path.join(srcdir, *package_parts) setup_package = os.path.relpath( os.path.join(package_path, 'setup_package.py')) if os.path.isfile(setup_package): module = import_file(setup_package, name=packagename + '.setup_package') yield module def iter_pyx_files(package_dir, package_name): """ A generator that yields Cython source files (ending in '.pyx') in the source packages. Returns ------- pyxgen : generator A generator that yields (extmod, fullfn) where `extmod` is the full name of the module that the .pyx file would live in based on the source directory structure, and `fullfn` is the path to the .pyx file. """ for dirpath, dirnames, filenames in walk_skip_hidden(package_dir): for fn in filenames: if fn.endswith('.pyx'): fullfn = os.path.relpath(os.path.join(dirpath, fn)) # Package must match file name extmod = '.'.join([package_name, fn[:-4]]) yield (extmod, fullfn) break # Don't recurse into subdirectories def get_cython_extensions(srcdir, packages, prevextensions=tuple(), extincludedirs=None): """ Looks for Cython files and generates Extensions if needed. Parameters ---------- srcdir : str Path to the root of the source directory to search. prevextensions : list of `~distutils.core.Extension` objects The extensions that are already defined. Any .pyx files already here will be ignored. extincludedirs : list of str or None Directories to include as the `include_dirs` argument to the generated `~distutils.core.Extension` objects. Returns ------- exts : list of `~distutils.core.Extension` objects The new extensions that are needed to compile all .pyx files (does not include any already in `prevextensions`). """ # Vanilla setuptools and old versions of distribute include Cython files # as .c files in the sources, not .pyx, so we cannot simply look for # existing .pyx sources in the previous sources, but we should also check # for .c files with the same remaining filename. So we look for .pyx and # .c files, and we strip the extension. prevsourcepaths = [] ext_modules = [] for ext in prevextensions: for s in ext.sources: if s.endswith(('.pyx', '.c', '.cpp')): sourcepath = os.path.realpath(os.path.splitext(s)[0]) prevsourcepaths.append(sourcepath) for package_name in packages: package_parts = package_name.split('.') package_path = os.path.join(srcdir, *package_parts) for extmod, pyxfn in iter_pyx_files(package_path, package_name): sourcepath = os.path.realpath(os.path.splitext(pyxfn)[0]) if sourcepath not in prevsourcepaths: ext_modules.append(Extension(extmod, [pyxfn], include_dirs=extincludedirs)) return ext_modules class DistutilsExtensionArgs(collections.defaultdict): """ A special dictionary whose default values are the empty list. This is useful for building up a set of arguments for `distutils.Extension` without worrying whether the entry is already present. """ def __init__(self, *args, **kwargs): def default_factory(): return [] super(DistutilsExtensionArgs, self).__init__( default_factory, *args, **kwargs) def update(self, other): for key, val in other.items(): self[key].extend(val) def pkg_config(packages, default_libraries, executable='pkg-config'): """ Uses pkg-config to update a set of distutils Extension arguments to include the flags necessary to link against the given packages. If the pkg-config lookup fails, default_libraries is applied to libraries. Parameters ---------- packages : list of str A list of pkg-config packages to look up. default_libraries : list of str A list of library names to use if the pkg-config lookup fails. Returns ------- config : dict A dictionary containing keyword arguments to `distutils.Extension`. These entries include: - ``include_dirs``: A list of include directories - ``library_dirs``: A list of library directories - ``libraries``: A list of libraries - ``define_macros``: A list of macro defines - ``undef_macros``: A list of macros to undefine - ``extra_compile_args``: A list of extra arguments to pass to the compiler """ flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries', '-D': 'define_macros', '-U': 'undef_macros'} command = "{0} --libs --cflags {1}".format(executable, ' '.join(packages)), result = DistutilsExtensionArgs() try: pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) output = pipe.communicate()[0].strip() except subprocess.CalledProcessError as e: lines = [ ("{0} failed. This may cause the build to fail below." .format(executable)), " command: {0}".format(e.cmd), " returncode: {0}".format(e.returncode), " output: {0}".format(e.output) ] log.warn('\n'.join(lines)) result['libraries'].extend(default_libraries) else: if pipe.returncode != 0: lines = [ "pkg-config could not lookup up package(s) {0}.".format( ", ".join(packages)), "This may cause the build to fail below." ] log.warn('\n'.join(lines)) result['libraries'].extend(default_libraries) else: for token in output.split(): # It's not clear what encoding the output of # pkg-config will come to us in. It will probably be # some combination of pure ASCII (for the compiler # flags) and the filesystem encoding (for any argument # that includes directories or filenames), but this is # just conjecture, as the pkg-config documentation # doesn't seem to address it. arg = token[:2].decode('ascii') value = token[2:].decode(sys.getfilesystemencoding()) if arg in flag_map: if arg == '-D': value = tuple(value.split('=', 1)) result[flag_map[arg]].append(value) else: result['extra_compile_args'].append(value) return result def add_external_library(library): """ Add a build option for selecting the internal or system copy of a library. Parameters ---------- library : str The name of the library. If the library is `foo`, the build option will be called `--use-system-foo`. """ for command in ['build', 'build_ext', 'install']: add_command_option(command, str('use-system-' + library), 'Use the system {0} library'.format(library), is_bool=True) def use_system_library(library): """ Returns `True` if the build configuration indicates that the given library should use the system copy of the library rather than the internal one. For the given library `foo`, this will be `True` if `--use-system-foo` or `--use-system-libraries` was provided at the commandline or in `setup.cfg`. Parameters ---------- library : str The name of the library Returns ------- use_system : bool `True` if the build should use the system copy of the library. """ return ( get_distutils_build_or_install_option('use_system_{0}'.format(library)) or get_distutils_build_or_install_option('use_system_libraries')) @extends_doc(_find_packages) def find_packages(where='.', exclude=(), invalidate_cache=False): """ This version of ``find_packages`` caches previous results to speed up subsequent calls. Use ``invalide_cache=True`` to ignore cached results from previous ``find_packages`` calls, and repeat the package search. """ if exclude: warnings.warn( "Use of the exclude parameter is no longer supported since it does " "not work as expected. Use add_exclude_packages instead. Note that " "it must be called prior to any other calls from setup helpers.", AstropyDeprecationWarning) # Calling add_exclude_packages after this point will have no effect _module_state['excludes_too_late'] = True if not invalidate_cache and _module_state['package_cache'] is not None: return _module_state['package_cache'] packages = _find_packages( where=where, exclude=list(_module_state['exclude_packages'])) _module_state['package_cache'] = packages return packages def filter_packages(packagenames): """ Removes some packages from the package list that shouldn't be installed on the current version of Python. """ if PY3: exclude = '_py2' else: exclude = '_py3' return [x for x in packagenames if not x.endswith(exclude)] class FakeBuildSphinx(Command): """ A dummy build_sphinx command that is called if Sphinx is not installed and displays a relevant error message """ # user options inherited from sphinx.setup_command.BuildDoc user_options = [ ('fresh-env', 'E', ''), ('all-files', 'a', ''), ('source-dir=', 's', ''), ('build-dir=', None, ''), ('config-dir=', 'c', ''), ('builder=', 'b', ''), ('project=', None, ''), ('version=', None, ''), ('release=', None, ''), ('today=', None, ''), ('link-index', 'i', '')] # user options appended in astropy.setup_helpers.AstropyBuildSphinx user_options.append(('warnings-returncode', 'w', '')) user_options.append(('clean-docs', 'l', '')) user_options.append(('no-intersphinx', 'n', '')) user_options.append(('open-docs-in-browser', 'o', '')) def initialize_options(self): try: raise RuntimeError("Sphinx and its dependencies must be installed " "for build_docs.") except: log.error('error: Sphinx and its dependencies must be installed ' 'for build_docs.') sys.exit(1) radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/0000755000077000000240000000000013531324214023574 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/__init__.py0000644000077000000240000000066513174167363025731 0ustar adamstaff00000000000000""" This package contains utilities and extensions for the Astropy sphinx documentation. In particular, the `astropy.sphinx.conf` should be imported by the sphinx ``conf.py`` file for affiliated packages that wish to make use of the Astropy documentation format. Note that some sphinx extensions which are bundled as-is (numpydoc and sphinx-automodapi) are included in astropy_helpers.extern rather than astropy_helpers.sphinx.ext. """ radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/conf.py0000644000077000000240000002721713516112504025104 0ustar adamstaff00000000000000# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # # Astropy shared Sphinx settings. These settings are shared between # astropy itself and affiliated packages. # # Note that not all possible configuration values are present in this file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import warnings from os import path import sphinx from distutils.version import LooseVersion # -- General configuration ---------------------------------------------------- # The version check in Sphinx itself can only compare the major and # minor parts of the version number, not the micro. To do a more # specific version check, call check_sphinx_version("x.y.z.") from # your project's conf.py needs_sphinx = '1.3' on_rtd = os.environ.get('READTHEDOCS', None) == 'True' def check_sphinx_version(expected_version): sphinx_version = LooseVersion(sphinx.__version__) expected_version = LooseVersion(expected_version) if sphinx_version < expected_version: raise RuntimeError( "At least Sphinx version {0} is required to build this " "documentation. Found {1}.".format( expected_version, sphinx_version)) # Configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('https://docs.python.org/3/', (None, 'http://data.astropy.org/intersphinx/python3.inv')), 'pythonloc': ('http://docs.python.org/', path.abspath(path.join(path.dirname(__file__), 'local/python3_local_links.inv'))), 'numpy': ('https://docs.scipy.org/doc/numpy/', (None, 'http://data.astropy.org/intersphinx/numpy.inv')), 'scipy': ('https://docs.scipy.org/doc/scipy/reference/', (None, 'http://data.astropy.org/intersphinx/scipy.inv')), 'matplotlib': ('http://matplotlib.org/', (None, 'http://data.astropy.org/intersphinx/matplotlib.inv')), 'astropy': ('http://docs.astropy.org/en/stable/', None), 'h5py': ('http://docs.h5py.org/en/stable/', None)} if sys.version_info[0] == 2: intersphinx_mapping['python'] = ( 'https://docs.python.org/2/', (None, 'http://data.astropy.org/intersphinx/python2.inv')) intersphinx_mapping['pythonloc'] = ( 'http://docs.python.org/', path.abspath(path.join(path.dirname(__file__), 'local/python2_local_links.inv'))) # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # The reST default role (used for this markup: `text`) to use for all # documents. Set to the "smart" one. default_role = 'obj' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # This is added to the end of RST files - a good place to put substitutions to # be used globally. rst_epilog = """ .. _Astropy: http://astropy.org """ # A list of warning types to suppress arbitrary warning messages. We mean to # override directives in astropy_helpers.sphinx.ext.autodoc_enhancements, # thus need to ignore those warning. This can be removed once the patch gets # released in upstream Sphinx (https://github.com/sphinx-doc/sphinx/pull/1843). # Suppress the warnings requires Sphinx v1.4.2 suppress_warnings = ['app.add_directive', ] # -- Project information ------------------------------------------------------ # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. #pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Settings for extensions and extension options ---------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.viewcode', 'astropy_helpers.extern.numpydoc', 'astropy_helpers.extern.automodapi.automodapi', 'astropy_helpers.extern.automodapi.smart_resolver', 'astropy_helpers.sphinx.ext.tocdepthfix', 'astropy_helpers.sphinx.ext.doctest', 'astropy_helpers.sphinx.ext.changelog_links'] if not on_rtd and LooseVersion(sphinx.__version__) < LooseVersion('1.4'): extensions.append('sphinx.ext.pngmath') else: extensions.append('sphinx.ext.mathjax') try: import matplotlib.sphinxext.plot_directive extensions += [matplotlib.sphinxext.plot_directive.__name__] # AttributeError is checked here in case matplotlib is installed but # Sphinx isn't. Note that this module is imported by the config file # generator, even if we're not building the docs. except (ImportError, AttributeError): warnings.warn( "matplotlib's plot_directive could not be imported. " + "Inline plots will not be included in the output") # Don't show summaries of the members in each class along with the # class' docstring numpydoc_show_class_members = False autosummary_generate = True automodapi_toctreedirnm = 'api' # Class documentation should contain *both* the class docstring and # the __init__ docstring autoclass_content = "both" # Render inheritance diagrams in SVG graphviz_output_format = "svg" graphviz_dot_args = [ '-Nfontsize=10', '-Nfontname=Helvetica Neue, Helvetica, Arial, sans-serif', '-Efontsize=10', '-Efontname=Helvetica Neue, Helvetica, Arial, sans-serif', '-Gfontsize=10', '-Gfontname=Helvetica Neue, Helvetica, Arial, sans-serif' ] # -- Options for HTML output ------------------------------------------------- # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [path.abspath(path.join(path.dirname(__file__), 'themes'))] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'bootstrap-astropy' # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': ['localtoc.html'], 'search': [], 'genindex': [], 'py-modindex': [], } # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # included in the bootstrap-astropy theme html_favicon = path.join(html_theme_path[0], html_theme, 'static', 'astropy_logo.ico') # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%d %b %Y' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # -- Options for LaTeX output ------------------------------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. latex_toplevel_sectioning = 'part' # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False latex_elements = {} # Additional stuff for the LaTeX preamble. latex_elements['preamble'] = r""" % Use a more modern-looking monospace font \usepackage{inconsolata} % The enumitem package provides unlimited nesting of lists and enums. % Sphinx may use this in the future, in which case this can be removed. % See https://bitbucket.org/birkenfeld/sphinx/issue/777/latex-output-too-deeply-nested \usepackage{enumitem} \setlistdepth{15} % In the parameters section, place a newline after the Parameters % header. (This is stolen directly from Numpy's conf.py, since it % affects Numpy-style docstrings). \usepackage{expdlist} \let\latexdescription=\description \def\description{\latexdescription{}{} \breaklabel} % Support the superscript Unicode numbers used by the "unicode" units % formatter \DeclareUnicodeCharacter{2070}{\ensuremath{^0}} \DeclareUnicodeCharacter{00B9}{\ensuremath{^1}} \DeclareUnicodeCharacter{00B2}{\ensuremath{^2}} \DeclareUnicodeCharacter{00B3}{\ensuremath{^3}} \DeclareUnicodeCharacter{2074}{\ensuremath{^4}} \DeclareUnicodeCharacter{2075}{\ensuremath{^5}} \DeclareUnicodeCharacter{2076}{\ensuremath{^6}} \DeclareUnicodeCharacter{2077}{\ensuremath{^7}} \DeclareUnicodeCharacter{2078}{\ensuremath{^8}} \DeclareUnicodeCharacter{2079}{\ensuremath{^9}} \DeclareUnicodeCharacter{207B}{\ensuremath{^-}} \DeclareUnicodeCharacter{00B0}{\ensuremath{^{\circ}}} \DeclareUnicodeCharacter{2032}{\ensuremath{^{\prime}}} \DeclareUnicodeCharacter{2033}{\ensuremath{^{\prime\prime}}} % Make the "warning" and "notes" sections use a sans-serif font to % make them stand out more. \renewenvironment{notice}[2]{ \def\py@noticetype{#1} \csname py@noticestart@#1\endcsname \textsf{\textbf{#2}} }{\csname py@noticeend@\py@noticetype\endcsname} """ # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # -- Options for the linkcheck builder ---------------------------------------- # A timeout value, in seconds, for the linkcheck builder linkcheck_timeout = 60 radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/ext/0000755000077000000240000000000013531324214024374 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/ext/__init__.py0000644000077000000240000000010213174167363026513 0ustar adamstaff00000000000000from __future__ import division, absolute_import, print_function radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/ext/changelog_links.py0000644000077000000240000000617113516112504030102 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This sphinx extension makes the issue numbers in the changelog into links to GitHub issues. """ from __future__ import print_function import re from distutils.version import LooseVersion from docutils.nodes import Text, reference from sphinx import __version__ SPHINX_LT_16 = LooseVersion(__version__) < LooseVersion('1.6') BLOCK_PATTERN = re.compile('\[#.+\]', flags=re.DOTALL) ISSUE_PATTERN = re.compile('#[0-9]+') def process_changelog_links(app, doctree, docname): for rex in app.changelog_links_rexes: if rex.match(docname): break else: # if the doc doesn't match any of the changelog regexes, don't process return if SPHINX_LT_16: info = app.info else: from sphinx.util import logging info = logging.getLogger(__name__).info info('[changelog_links] Adding changelog links to "{0}"'.format(docname)) for item in doctree.traverse(): if not isinstance(item, Text): continue # We build a new list of items to replace the current item. If # a link is found, we need to use a 'reference' item. children = [] # First cycle through blocks of issues (delimited by []) then # iterate inside each one to find the individual issues. prev_block_end = 0 for block in BLOCK_PATTERN.finditer(item): block_start, block_end = block.start(), block.end() children.append(Text(item[prev_block_end:block_start])) block = item[block_start:block_end] prev_end = 0 for m in ISSUE_PATTERN.finditer(block): start, end = m.start(), m.end() children.append(Text(block[prev_end:start])) issue_number = block[start:end] refuri = app.config.github_issues_url + issue_number[1:] children.append(reference(text=issue_number, name=issue_number, refuri=refuri)) prev_end = end prev_block_end = block_end # If no issues were found, this adds the whole item, # otherwise it adds the remaining text. children.append(Text(block[prev_end:block_end])) # If no blocks were found, this adds the whole item, otherwise # it adds the remaining text. children.append(Text(item[prev_block_end:])) # Replace item by the new list of items we have generated, # which may contain links. item.parent.replace(item, children) def setup_patterns_rexes(app): app.changelog_links_rexes = [re.compile(pat) for pat in app.config.changelog_links_docpattern] def setup(app): app.connect('doctree-resolved', process_changelog_links) app.connect('builder-inited', setup_patterns_rexes) app.add_config_value('github_issues_url', None, True) app.add_config_value('changelog_links_docpattern', ['.*changelog.*', 'whatsnew/.*'], True) return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/ext/doctest.py0000644000077000000240000000364113174167433026432 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This is a set of three directives that allow us to insert metadata about doctests into the .rst files so the testing framework knows which tests to skip. This is quite different from the doctest extension in Sphinx itself, which actually does something. For astropy, all of the testing is centrally managed from py.test and Sphinx is not used for running tests. """ import re from docutils.nodes import literal_block from docutils.parsers.rst import Directive class DoctestSkipDirective(Directive): has_content = True def run(self): # Check if there is any valid argument, and skip it. Currently only # 'win32' is supported in astropy.tests.pytest_plugins. if re.match('win32', self.content[0]): self.content = self.content[2:] code = '\n'.join(self.content) return [literal_block(code, code)] class DoctestOmitDirective(Directive): has_content = True def run(self): # Simply do not add any content when this directive is encountered return [] class DoctestRequiresDirective(DoctestSkipDirective): # This is silly, but we really support an unbounded number of # optional arguments optional_arguments = 64 def setup(app): app.add_directive('doctest-requires', DoctestRequiresDirective) app.add_directive('doctest-skip', DoctestSkipDirective) app.add_directive('doctest-skip-all', DoctestSkipDirective) app.add_directive('doctest', DoctestSkipDirective) # Code blocks that use this directive will not appear in the generated # documentation. This is intended to hide boilerplate code that is only # useful for testing documentation using doctest, but does not actually # belong in the documentation itself. app.add_directive('testsetup', DoctestOmitDirective) return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/ext/edit_on_github.py0000644000077000000240000001346413174167433027754 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This extension makes it easy to edit documentation on github. It adds links associated with each docstring that go to the corresponding view source page on Github. From there, the user can push the "Edit" button, edit the docstring, and submit a pull request. It has the following configuration options (to be set in the project's ``conf.py``): * ``edit_on_github_project`` The name of the github project, in the form "username/projectname". * ``edit_on_github_branch`` The name of the branch to edit. If this is a released version, this should be a git tag referring to that version. For a dev version, it often makes sense for it to be "master". It may also be a git hash. * ``edit_on_github_source_root`` The location within the source tree of the root of the Python package. Defaults to "lib". * ``edit_on_github_doc_root`` The location within the source tree of the root of the documentation source. Defaults to "doc", but it may make sense to set it to "doc/source" if the project uses a separate source directory. * ``edit_on_github_docstring_message`` The phrase displayed in the links to edit a docstring. Defaults to "[edit on github]". * ``edit_on_github_page_message`` The phrase displayed in the links to edit a RST page. Defaults to "[edit this page on github]". * ``edit_on_github_help_message`` The phrase displayed as a tooltip on the edit links. Defaults to "Push the Edit button on the next page" * ``edit_on_github_skip_regex`` When the path to the .rst file matches this regular expression, no "edit this page on github" link will be added. Defaults to ``"_.*"``. """ import inspect import os import re import sys from docutils import nodes from sphinx import addnodes def import_object(modname, name): """ Import the object given by *modname* and *name* and return it. If not found, or the import fails, returns None. """ try: __import__(modname) mod = sys.modules[modname] obj = mod for part in name.split('.'): obj = getattr(obj, part) return obj except: return None def get_url_base(app): return 'http://github.com/%s/tree/%s/' % ( app.config.edit_on_github_project, app.config.edit_on_github_branch) def doctree_read(app, doctree): # Get the configuration parameters if app.config.edit_on_github_project == 'REQUIRED': raise ValueError( "The edit_on_github_project configuration variable must be " "provided in the conf.py") source_root = app.config.edit_on_github_source_root url = get_url_base(app) docstring_message = app.config.edit_on_github_docstring_message # Handle the docstring-editing links for objnode in doctree.traverse(addnodes.desc): if objnode.get('domain') != 'py': continue names = set() for signode in objnode: if not isinstance(signode, addnodes.desc_signature): continue modname = signode.get('module') if not modname: continue fullname = signode.get('fullname') if fullname in names: # only one link per name, please continue names.add(fullname) obj = import_object(modname, fullname) anchor = None if obj is not None: try: lines, lineno = inspect.getsourcelines(obj) except: pass else: anchor = '#L%d' % lineno if anchor: real_modname = inspect.getmodule(obj).__name__ path = '%s%s%s.py%s' % ( url, source_root, real_modname.replace('.', '/'), anchor) onlynode = addnodes.only(expr='html') onlynode += nodes.reference( reftitle=app.config.edit_on_github_help_message, refuri=path) onlynode[0] += nodes.inline( '', '', nodes.raw('', ' ', format='html'), nodes.Text(docstring_message), classes=['edit-on-github', 'viewcode-link']) signode += onlynode def html_page_context(app, pagename, templatename, context, doctree): if (templatename == 'page.html' and not re.match(app.config.edit_on_github_skip_regex, pagename)): doc_root = app.config.edit_on_github_doc_root if doc_root != '' and not doc_root.endswith('/'): doc_root += '/' doc_path = os.path.relpath(doctree.get('source'), app.builder.srcdir) url = get_url_base(app) page_message = app.config.edit_on_github_page_message context['edit_on_github'] = url + doc_root + doc_path context['edit_on_github_page_message'] = page_message def setup(app): app.add_config_value('edit_on_github_project', 'REQUIRED', True) app.add_config_value('edit_on_github_branch', 'master', True) app.add_config_value('edit_on_github_source_root', 'lib', True) app.add_config_value('edit_on_github_doc_root', 'doc', True) app.add_config_value('edit_on_github_docstring_message', '[edit on github]', True) app.add_config_value('edit_on_github_page_message', 'Edit This Page on Github', True) app.add_config_value('edit_on_github_help_message', 'Push the Edit button on the next page', True) app.add_config_value('edit_on_github_skip_regex', '_.*', True) app.connect('doctree-read', doctree_read) app.connect('html-page-context', html_page_context) return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/ext/tocdepthfix.py0000644000077000000240000000137013174167433027303 0ustar adamstaff00000000000000from sphinx import addnodes def fix_toc_entries(app, doctree): # Get the docname; I don't know why this isn't just passed in to the # callback # This seems a bit unreliable as it's undocumented, but it's not "private" # either: docname = app.builder.env.temp_data['docname'] if app.builder.env.metadata[docname].get('tocdepth', 0) != 0: # We need to reprocess any TOC nodes in the doctree and make sure all # the files listed in any TOCs are noted for treenode in doctree.traverse(addnodes.toctree): app.builder.env.note_toctree(docname, treenode) def setup(app): app.connect('doctree-read', fix_toc_entries) return {'parallel_read_safe': True, 'parallel_write_safe': True} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/local/0000755000077000000240000000000013531324214024666 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/local/python2_local_links.inv0000644000077000000240000000106213060356620031363 0ustar adamstaff00000000000000# Sphinx inventory version 2 # Project: Python # Version: 2.7 and 3.5 # The remainder of this file should be compressed using zlib. x=O0@w Z!nU bw+1rpKïIiQeI˽w8g"Wf ʬxK%lS(ϭ1 k&Qrp)ɐ.Bi۠3H]a)_ZI>dH, _M_"撠bvIzЀ82b;!I,=Wh_'l!Q%^B#Ô }inuD#e³\:{tu;/wxy. !nX{0BzoH /LxA&UXS{⮸5ߣ\RBiJF?radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/local/python3_local_links.txt0000644000077000000240000000540413060356620031413 0ustar adamstaff00000000000000# Sphinx inventory version 2 # Project: Python # Version: 2.7 and 3.5 # The remainder of this file should be compressed using zlib. # python2 only links cPickle py:module -1 2/library/pickle.html#module-cPickle - unicode py:function -1 2/library/functions.html#unicode - bsddb py:module -1 2/library/bsddb.html#module-bsddb - dict.has_key py:method -1 2/library/stdtypes.html#dict.has_key - dict.iteritems py:method -1 2/library/stdtypes.html#dict.iteritems - dict.iterkeys py:method -1 2/library/stdtypes.html#dict.iterkeys - dict.itervalues py:method -1 2/library/stdtypes.html#dict.itervalues - urllib2.urlopen py:function -1 2/library/urllib2.html#urllib2.urlopen - # python3 print() py:function -1 3/library/functions.html#print - # python3 collections.abc collections.Container py:class -1 3/library/collections.abc.html#collections.abc.Container - collections.Hashable py:class -1 3/library/collections.abc.html#collections.abc.Hashable - collections.Sized py:class -1 3/library/collections.abc.html#collections.abc.Sized - collections.Callable py:class -1 3/library/collections.abc.html#collections.abc.Callable - collections.Iterable py:class -1 3/library/collections.abc.html#collections.abc.Iterable - collections.Iterator py:class -1 3/library/collections.abc.html#collections.abc.Iterator - collections.Generator py:class -1 3/library/collections.abc.html#collections.abc.Generator - collections.Sequence py:class -1 3/library/collections.abc.html#collections.abc.Sequence - collections.MutableSequence py:class -1 3/library/collections.abc.html#collections.abc.MutableSequence - collections.ByteString py:class -1 3/library/collections.abc.html#collections.abc.ByteString - collections.Set py:class -1 3/library/collections.abc.html#collections.abc.Set - collections.MutableSet py:class -1 3/library/collections.abc.html#collections.abc.MutableSet - collections.Mapping py:class -1 3/library/collections.abc.html#collections.abc.Mapping - collections.MutableMapping py:class -1 3/library/collections.abc.html#collections.abc.MutableMapping - collections.MappingView py:class -1 3/library/collections.abc.html#collections.abc.MappingView - collections.ItemsView py:class -1 3/library/collections.abc.html#collections.abc.ItemsView - collections.KeysView py:class -1 3/library/collections.abc.html#collections.abc.KeysView - collections.ValuesView py:class -1 3/library/collections.abc.html#collections.abc.ValuesView - collections.Awaitable py:class -1 3/library/collections.abc.html#collections.abc.Awaitable - collections.Coroutine py:class -1 3/library/collections.abc.html#collections.abc.Coroutine - collections.AsyncIterable py:class -1 3/library/collections.abc.html#collections.abc.AsyncIterable - collections.AsyncIterator py:class -1 3/library/collections.abc.html#collections.abc.AsyncIterator - radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/setup_package.py0000644000077000000240000000044413174167363027000 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): # Install the theme files return { 'astropy_helpers.sphinx': [ 'local/*.inv', 'themes/bootstrap-astropy/*.*', 'themes/bootstrap-astropy/static/*.*']} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/0000755000077000000240000000000013531324214025061 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/0000755000077000000240000000000013531324214030575 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/globaltoc.html0000644000077000000240000000011112711231150033415 0ustar adamstaff00000000000000

Table of Contents

{{ toctree(maxdepth=-1, titles_only=true) }} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/layout.html0000644000077000000240000000655112711231150033002 0ustar adamstaff00000000000000{% extends "basic/layout.html" %} {# Collapsible sidebar script from default/layout.html in Sphinx #} {% set script_files = script_files + ['_static/sidebar.js'] %} {# Add the google webfonts needed for the logo #} {% block extrahead %} {% if not embedded %}{% endif %} {% endblock %} {% block header %}
{{ theme_logotext1 }}{{ theme_logotext2 }}{{ theme_logotext3 }}
  • Index
  • Modules
  • {% block sidebarsearch %} {% include "searchbox.html" %} {% endblock %}
{% endblock %} {% block relbar1 %} {% endblock %} {# Silence the bottom relbar. #} {% block relbar2 %}{% endblock %} {%- block footer %}

{%- if edit_on_github %} {{ edit_on_github_page_message }}   {%- endif %} {%- if show_source and has_source and sourcename %} {{ _('Page Source') }} {%- endif %}   Back to Top

{%- if show_copyright %} {%- if hasdoc('copyright') %} {% trans path=pathto('copyright'), copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %}
{%- else %} {% trans copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %}
{%- endif %} {%- endif %} {%- if show_sphinx %} {% trans sphinx_version=sphinx_version|e %}Created using Sphinx {{ sphinx_version }}.{% endtrans %}   {%- endif %} {%- if last_updated %} {% trans last_updated=last_updated|e %}Last built {{ last_updated }}.{% endtrans %}
{%- endif %}

{%- endblock %} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/localtoc.html0000644000077000000240000000004212711231150033252 0ustar adamstaff00000000000000

Page Contents

{{ toc }} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/searchbox.html0000644000077000000240000000042012711231150033430 0ustar adamstaff00000000000000{%- if pagename != "search" %}
{%- endif %} radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/0000755000077000000240000000000013531324214032064 5ustar adamstaff00000000000000././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_linkout.svgradio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_link0000644000077000000240000001212112711231150034515 0ustar adamstaff00000000000000 ././@LongLink0000000000000000000000000000015700000000000011220 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_linkout_20.pngradio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_link0000644000077000000240000000327512711231150034527 0ustar adamstaff00000000000000PNG  IHDR[8A bKGD oFFsvek pHYs B(x vpAg\@0IDATXi_SϘ+jfF BHXbOέ}-ZAb$iV#TZCՖ IiUd;?)*Orsyss!LO`[=`3|;1`{Ͷﱽv]mX=lyZjs@30l<,ݒ @+60S϶Gmo t% `4 pX<,1:`R~qP`.0kWJs¶@R>)Nt$S`6p6pTm5Hs8{@` J:v=%``/9`/i~\`b{H7KB݀"Ɠof:/hR' J\"`n*[! `'I} o9#g6 l}mh[lOe~tgE;nkmϳ=^KQ&~* N Nx l30L-'w~u O lOm)ީ`"ױakٚs\"5ߟ[m,fB 9{g[ؓ'(8}';aq^{N:l_q-HZ"x.5kO|[86_Y?-B6m8wDqkׅ (eY5$ʯwdz"D%iZMh1/ѪbmZ۟0] V-_پ9냲1K%)AB089l *N' M/o;GcJ=IÁe:T6ܝ}ʳP F76J}K h,aSΌV`%XU [IWE԰K ? |LYerZJ*<3E X1r=$.C*3^p+7 (! sPf %   i# #"""" yu =!"""""""""""""""""""!!! $$$$$$"m8T%!$$$$$###""""###$$$$$$##$$#!' &j'(&&&&!Nim5 %&&&%%$##""""""##$$%&&&&&&&&%&3)%(*)))(%'IUq'!')((('&#("DPkpmNj!C&"%&'(((((((&'9 +*+*++)*Qo%%++++*'$"Gt}/R'&))******''U+;-.---,)Vt]z('----,$F?`)),,,,,,.,.t@//0000- :z1(0/./,+Zw#L'./////0.-I0%021110/bH)1221.8xTs+/100011/2$@3n3533318Ek,243418q103222320@ 2666655Dl @/65540t\~?e1\,X,X2]?fZ}u335555644X8 5:88877@j08888.Rx:eE1*-..-*0C3]jl168778855:O9<:::8 BM3;:;7O^@/49:::99984.6/]Mu39999;88<{;=<<<;9hc<:<<<2xOy65<=<<<<<<<<<<92 Af!S9;;;<=9;'=?@??=?k7g5>>>;Mc89?>>>>>>>>>>>>?>7:[=<>>>@>>ABBAA?B#[9AAA:U F9A@@@>:6557;?@@@@A;=e>o>@@@AB?<BDCCCADT>CCC9Ev7CCC>4DBssj0f>:BBBBC; FC@BBBDBBhUEGEEEBFOAEED@Y?FC9&a?r?BEEEE=$_4kCDDDDEB@ FJHHHEIxMDGGF OIE?H_bHEGGGEE\EEGGGIDJ4ILJJJGLtNGJJHZpB= ]]BIIIJA ` PGIIIKHJxLNLLLIN{ RILLJ\r;.h+iGKKKHNo5pJKKKKKLOPNNNLOYJNNMR5nFMNNNF9unMKMMMOLPQQQQORbJPPPH\NPPPI!gPNPPPRPRQTSSQT'mJSSSJ}ANRRRM`TPRRRTPV}UVUUSTfFOTUUQ9{_NTTTP Z~VQTTTVRVPWYWWVU0w _SWWVXS:}jPVVVTYj ]SVVVXVZ"X\YYYW^-vQYYYR;bQ9hSYYYWZbeWXXX[Xf X]\\\ZZ~z^W\[[WdOXKNVV[[[Y\e dY[[[^[f_]_^^]\*x<X]^^\_d)wT[Yt4Y]]]Zar`Z]]]`]b<`c```^]oY```][B?ZY`W"ve]___\h`\___b]mbdbbbba/i[abbaZ_;ryWoW[ab_]pYabbb]rb_aaad_Uewdgeeed`yo\bdddc_ZYZ\addda]G9_dddd\(|ebdddgdg%fjggggep3c_fgggfffffff_cGcefffe`GZeefffifihkiiihe5g'}e`dfghhgeabwj5chhhhd p&fghhhkhj0knkkkkjeNi=| qhdflv0Xddjkkkkd*khjjjjmknmpnnnnmgSm_ex|nkmmmmjmlqllmmmmpku%mrpppppoiD~ tkoonjki.#mnoooororgpuqrrrrqljsoqqps~ttnoqqqqqrn`tvuttttttqsR:ortttm%nb0rrssssusryx1vzwwwwwwvup {WTxquuuvs vpsuvvvvvyuw/x[w|yxxxxyyxwtv+ht2wswxxxxxq7vxxwwwyxw|x~{zzzzzzzzzxwux)-)|uwxzzz{{{{v Ovyyyyyz|w|H {~}}}}||||||||{{{z{{{||||||||||wPy{}||||}}z~~~~~~~~~~~~~~~y!}~~~~~}7}b/n;]+u %gL@Mxs&G#Vs]<T%qss wP70W7 &id 8iuE ( @ d W ,uJ>P&:K bs\n +!!!0J +%%%%ps(%%%%%%%%%%%$$$"5+0***>^@_))))$GyPl 1)))))'....0Xv...C{3---*$3#333Xy2228_#N22227t777O77O`K6 =;eJ6667O:<;I;;;@;;;;;;P@;::U@@@Crj@@(^C???????? Fs???ASADDgAtDDjM|DD7lHyDDDTNCCDIII|)fIIW QHHHx\HHHF!MMMo6sMM#e8sLL^LLLMcRRR\YQQhQQQQQQOVVV"mVVcUUUUUUS\l[[ZjZZz[ZZZ]YYWa*___r___G^*y^^^^^^[acchnccce({lccdAcccbbb_i_hhhHqhgggg mhgg zggggfkllljQ8G#llkVkkkip]qqqqN7ppp~tpppowtuuuu~ut ysttttv'y{yyyyy|@lqJ yyyy|yyyw}5~~~~~~~~~~~}}}}"P}}}}{<Ds6i %3a _$;$lw&(0 \&2$1e1i9E Bl{;O " )C!" &&k' g~g##-MTn[tGc<!''&(1+'&Ne!5XE$.*3d411&Mp@e*5187F;g&(X4\2) @Ms1^188D>;8iK2;,C G9,FE=>UB@[>O3j@^S7WO=DC5KFb@]+iJ@oKLIpQNPP W?|?3s YOPVU#n"nFvcD"mbTQ]v__~QdeUL"rhZYa:b^GOUdFR1VB!vU0 ja_q fmgwvb`hQaabjhgnHomt rdr]hqmrzqtXt xjQnytgzwu ~3^eFvqVrwx +}|{{||||'}~s, 6 >4 L;s 9qf$(  * mcmU#1 4E 16G\  'HU'+#!lKi!$0PUAC$v 3 D;->%>4$4"" R6;AJRT0aIx B UW7U-MRX_5A Tt\tOCBNYl-XNKWWG\IVdmd@Nudy_ou%umQ{}qvCU|Pvv totUH NZ: Ul*././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_logo.svgradio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_logo0000644000077000000240000001103212711231150034520 0ustar adamstaff00000000000000 ././@LongLink0000000000000000000000000000015400000000000011215 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_logo_32.pngradio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_logo0000644000077000000240000000353412711231150034530 0ustar adamstaff00000000000000PNG  IHDR szzsBIT|d pHYstEXtSoftwarewww.inkscape.org<IDATXŗPT?cP  FUBȘ&diI# JhC2nj5tw:۪5Sƪڡ%ZF2VkJF`(Jdqa., ?3gsϏΞ\_ɕ#Hl 2pZ8ԯKLW;ACȋh4z>$?#hJ~`;&y#D b0¤u2RqKJr'7<6.´;`2ҋ@&a$`+Ɲ1WB], w.rM|rh?G6Bm"GïK0#&: WBa˰mL6p+Δxti@D1;z v7zCrׇE9,_Ghby; !,eUėAlO-^;V~;MKxUZK%:L剜"9Tr3WCWa89`p4XW;KxBjwɥׇ.WLD_e5w`DzFG;z9?@ghI^ UԳMl+ās%bZKo@`!8o)!pu4W;U00i'@V \}> u  bdǑY>rzc0iI,\1DX )ׇ__m cB3߬|f̃I.K;NAq!~*r8g)Bď߅;!*'#DrdN;Ql |( Xj[`aPy* ؗԥhbO 9el 0Hia29HRe 5*@)}˱ cU5aIr m0JnARPrj&5+ޝAL:KA\ e'_໩lg'm/!7|p7zT@50 K޹g@/fHN|ׯ@b b8Xl,yf} ڠU; )U1obS j~¦aS2!&A8/ 7hu.@0D=_oo nI/ I70Fާ&%,*}t {#$'@tbʾ?uO j&DK -T㎉E4| )p,;!7ÿ3i06XԾ8nBSjOENi 0-g<0c&T@e] K . ;z硳-TR[t:iy脷,,4EBY8{Z5FAK]?upjL,<" ^?aRe AO/YHKC}K7ټV='N h@$.:4}rsFp"jw^qo?%f$2H̀O675E)iנس\oF̄*j{YUIܹ !bQ[Ǣ&X])WHT] 텟A֭`ЇuWXq;dgڱ "20֯зka:ob3u2p!}rn,TjN$9L࿡k{rAMP*ari.i[ hШ7O$0 ˕Lg$33 G.8<IENDB`././@LongLink0000000000000000000000000000015600000000000011217 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/bootstrap-astropy.cssradio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/bootstrap-as0000644000077000000240000002744312711231150034432 0ustar adamstaff00000000000000/*! * Bootstrap v1.4.0 * * Copyright 2011 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Heavily modified by Kyle Barbary for the AstroPy Project for use with Sphinx. */ @import url("basic.css"); body { background-color: #ffffff; margin: 0; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 13px; font-weight: normal; line-height: 18px; color: #404040; } /* Hyperlinks ----------------------------------------------------------------*/ a { color: #0069d6; text-decoration: none; line-height: inherit; font-weight: inherit; } a:hover { color: #00438a; text-decoration: underline; } /* Typography ----------------------------------------------------------------*/ h1,h2,h3,h4,h5,h6 { color: #404040; margin: 0.7em 0 0 0; line-height: 1.5em; } h1 { font-size: 24px; margin: 0; } h2 { font-size: 21px; line-height: 1.2em; margin: 1em 0 0.5em 0; border-bottom: 1px solid #404040; } h3 { font-size: 18px; } h4 { font-size: 16px; } h5 { font-size: 14px; } h6 { font-size: 13px; text-transform: uppercase; } p { font-size: 13px; font-weight: normal; line-height: 18px; margin-top: 0px; margin-bottom: 9px; } ul, ol { margin-left: 0; padding: 0 0 0 25px; } ul ul, ul ol, ol ol, ol ul { margin-bottom: 0; } ul { list-style: disc; } ol { list-style: decimal; } li { line-height: 18px; color: #404040; } ul.unstyled { list-style: none; margin-left: 0; } dl { margin-bottom: 18px; } dl dt, dl dd { line-height: 18px; } dl dd { margin-left: 9px; } hr { margin: 20px 0 19px; border: 0; border-bottom: 1px solid #eee; } strong { font-style: inherit; font-weight: bold; } em { font-style: italic; font-weight: inherit; line-height: inherit; } .muted { color: #bfbfbf; } address { display: block; line-height: 18px; margin-bottom: 18px; } code, pre { padding: 0 3px 2px; font-family: monospace; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } tt { font-family: monospace; } code { padding: 1px 3px; } pre { display: block; padding: 8.5px; margin: 0 0 18px; line-height: 18px; border: 1px solid #ddd; border: 1px solid rgba(0, 0, 0, 0.12); -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; white-space: pre; word-wrap: break-word; } img { margin: 9px 0; } /* format inline code with a rounded box */ tt, code { margin: 0 2px; padding: 0 5px; border: 1px solid #ddd; border: 1px solid rgba(0, 0, 0, 0.12); border-radius: 3px; } code.xref, a code { margin: 0; padding: 0 1px 0 1px; background-color: none; border: none; } /* all code has same box background color, even in headers */ h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt, h1 code, h2 code, h3 code, h4 code, h5 code, h6 code, pre, code, tt { background-color: #f8f8f8; } /* override box for links & other sphinx-specifc stuff */ tt.xref, a tt, tt.descname, tt.descclassname { padding: 0 1px 0 1px; border: none; } /* override box for related bar at the top of the page */ .related tt { border: none; padding: 0 1px 0 1px; background-color: transparent; font-weight: bold; } th { background-color: #dddddd; } .viewcode-back { font-family: sans-serif; } div.viewcode-block:target { background-color: #f4debf; border-top: 1px solid #ac9; border-bottom: 1px solid #ac9; } table.docutils { border-spacing: 5px; border-collapse: separate; } /* Topbar --------------------------------------------------------------------*/ div.topbar { height: 40px; position: absolute; top: 0; left: 0; right: 0; z-index: 10000; padding: 0px 10px; background-color: #222; background-color: #222222; background-repeat: repeat-x; background-image: -khtml-gradient(linear, left top, left bottom, from(#333333), to(#222222)); background-image: -moz-linear-gradient(top, #333333, #222222); background-image: -ms-linear-gradient(top, #333333, #222222); background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #333333), color-stop(100%, #222222)); background-image: -webkit-linear-gradient(top, #333333, #222222); background-image: -o-linear-gradient(top, #333333, #222222); background-image: linear-gradient(top, #333333, #222222); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0); overflow: auto; } div.topbar a.brand { font-family: 'Source Sans Pro', sans-serif; font-size: 26px; color: #ffffff; font-weight: 600; text-decoration: none; float: left; display: block; height: 32px; padding: 8px 12px 0px 45px; margin-left: -10px; background: transparent url("astropy_logo_32.png") no-repeat 10px 4px; background-image: url("astropy_logo.svg"), none; background-size: 32px 32px; } #logotext1 { } #logotext2 { font-weight:200; color: #ff5000; } #logotext3 { font-weight:200; } div.topbar .brand:hover, div.topbar ul li a.homelink:hover { background-color: #333; background-color: rgba(255, 255, 255, 0.05); } div.topbar ul { font-size: 110%; list-style: none; margin: 0; padding: 0 0 0 10px; float: right; color: #bfbfbf; text-align: center; text-decoration: none; height: 100%; } div.topbar ul li { float: left; display: inline; height: 30px; margin: 5px; padding: 0px; } div.topbar ul li a { color: #bfbfbf; text-decoration: none; padding: 5px; display: block; height: auto; text-align: center; vertical-align: middle; border-radius: 4px; } div.topbar ul li a:hover { color: #ffffff; text-decoration: none; } div.topbar ul li a.homelink { width: 112px; display: block; height: 20px; padding: 5px 0px; background: transparent url("astropy_linkout_20.png") no-repeat 10px 5px; background-image: url("astropy_linkout.svg"), none; background-size: 91px 20px; } div.topbar form { text-align: left; margin: 0 0 0 5px; position: relative; filter: alpha(opacity=100); -khtml-opacity: 1; -moz-opacity: 1; opacity: 1; } div.topbar input { background-color: #444; background-color: rgba(255, 255, 255, 0.3); font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: normal; font-weight: 13px; line-height: 1; padding: 4px 9px; color: #ffffff; color: rgba(255, 255, 255, 0.75); border: 1px solid #111; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none; transition: none; } div.topbar input:-moz-placeholder { color: #e6e6e6; } div.topbar input::-webkit-input-placeholder { color: #e6e6e6; } div.topbar input:hover { background-color: #bfbfbf; background-color: rgba(255, 255, 255, 0.5); color: #ffffff; } div.topbar input:focus, div.topbar input.focused { outline: 0; background-color: #ffffff; color: #404040; text-shadow: 0 1px 0 #ffffff; border: 0; padding: 5px 10px; -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); } /* Relation bar (breadcrumbs, prev, next) ------------------------------------*/ div.related { height: 21px; width: auto; margin: 0 10px; position: absolute; top: 42px; clear: both; left: 0; right: 0; z-index: 10000; font-size: 100%; vertical-align: middle; background-color: #fff; border-bottom: 1px solid #bbb; } div.related ul { padding: 0; margin: 0; } /* Footer --------------------------------------------------------------------*/ footer { display: block; margin: 10px 10px 0px; padding: 10px 0 0 0; border-top: 1px solid #bbb; } .pull-right { float: right; width: 30em; text-align: right; } /* Sphinx sidebar ------------------------------------------------------------*/ div.sphinxsidebar { font-size: inherit; border-radius: 3px; background-color: #eee; border: 1px solid #bbb; word-wrap: break-word; /* overflow-wrap is the canonical name for word-wrap in the CSS3 text draft. We include it here mainly for future-proofing. */ overflow-wrap: break-word; } div.sphinxsidebarwrapper { padding: 0px 0px 0px 5px; } div.sphinxsidebar h3 { font-family: 'Trebuchet MS', sans-serif; font-size: 1.4em; font-weight: normal; margin: 5px 0px 0px 5px; padding: 0; line-height: 1.6em; } div.sphinxsidebar h4 { font-family: 'Trebuchet MS', sans-serif; font-size: 1.3em; font-weight: normal; margin: 5px 0 0 0; padding: 0; } div.sphinxsidebar p { } div.sphinxsidebar p.topless { margin: 5px 10px 10px 10px; } div.sphinxsidebar ul { margin: 0px 0px 0px 5px; padding: 0; } div.sphinxsidebar ul ul { margin-left: 15px; list-style-type: disc; } /* If showing the global TOC (toctree), color the current page differently */ div.sphinxsidebar a.current { color: #404040; } div.sphinxsidebar a.current:hover { color: #404040; } /* document, documentwrapper, body, bodywrapper ----------------------------- */ div.document { margin-top: 72px; margin-left: 10px; margin-right: 10px; } div.documentwrapper { float: left; width: 100%; } div.body { background-color: #ffffff; padding: 0 0 0px 20px; } div.bodywrapper { margin: 0 0 0 230px; max-width: 55em; } /* Header links ------------------------------------------------------------- */ a.headerlink { font-size: 0.8em; padding: 0 4px 0 4px; text-decoration: none; } a.headerlink:hover { background-color: #0069d6; color: white; text-docoration: none; } /* Admonitions and warnings ------------------------------------------------- */ /* Shared by admonitions and warnings */ div.admonition, div.warning { padding: 0px; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } div.admonition p, div.warning p { margin: 0.5em 1em 0.5em 1em; padding: 0; } div.admonition pre, div.warning pre { margin: 0.4em 1em 0.4em 1em; } div.admonition p.admonition-title, div.warning p.admonition-title { margin: 0; padding: 0.1em 0 0.1em 0.5em; color: white; font-weight: bold; font-size: 1.1em; } div.admonition ul, div.admonition ol, div.warning ul, div.warning ol { margin: 0.1em 0.5em 0.5em 3em; padding: 0; } /* Admonitions only */ div.admonition { border: 1px solid #609060; background-color: #e9ffe9; } div.admonition p.admonition-title { background-color: #70A070; } /* Warnings only */ div.warning { border: 1px solid #900000; background-color: #ffe9e9; } div.warning p.admonition-title { background-color: #b04040; } /* Figures ------------------------------------------------------------------ */ .figure.align-center { clear: none; } /* This is a div for containing multiple figures side-by-side, for use with * .. container:: figures */ div.figures { border: 1px solid #CCCCCC; background-color: #F8F8F8; margin: 1em; text-align: center; } div.figures .figure { clear: none; float: none; display: inline-block; border: none; margin-left: 0.5em; margin-right: 0.5em; } .field-list th { white-space: nowrap; } table.field-list { border-spacing: 0px; margin-left: 1px; border-left: 5px solid rgb(238, 238, 238) !important; } table.field-list th.field-name { display: inline-block; padding: 1px 8px 1px 5px; white-space: nowrap; background-color: rgb(238, 238, 238); border-radius: 0 3px 3px 0; -webkit-border-radius: 0 3px 3px 0; } ././@LongLink0000000000000000000000000000014600000000000011216 Lustar 00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/copybutton.jsradio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/copybutton.j0000644000077000000240000000532113154310745034453 0ustar adamstaff00000000000000$(document).ready(function() { /* Add a [>>>] button on the top-right corner of code samples to hide * the >>> and ... prompts and the output and thus make the code * copyable. */ var div = $('.highlight-python .highlight,' + '.highlight-python3 .highlight,' + '.highlight-default .highlight') var pre = div.find('pre'); // get the styles from the current theme pre.parent().parent().css('position', 'relative'); var hide_text = 'Hide the prompts and output'; var show_text = 'Show the prompts and output'; var border_width = pre.css('border-top-width'); var border_style = pre.css('border-top-style'); var border_color = pre.css('border-top-color'); var button_styles = { 'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0', 'border-color': border_color, 'border-style': border_style, 'border-width': border_width, 'color': border_color, 'text-size': '75%', 'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em', 'border-radius': '0 3px 0 0' } // create and add the button to all the code blocks that contain >>> div.each(function(index) { var jthis = $(this); if (jthis.find('.gp').length > 0) { var button = $('>>>'); button.css(button_styles) button.attr('title', hide_text); button.data('hidden', 'false'); jthis.prepend(button); } // tracebacks (.gt) contain bare text elements that need to be // wrapped in a span to work with .nextUntil() (see later) jthis.find('pre:has(.gt)').contents().filter(function() { return ((this.nodeType == 3) && (this.data.trim().length > 0)); }).wrap(''); }); // define the behavior of the button when it's clicked $('.copybutton').click(function(e){ e.preventDefault(); var button = $(this); if (button.data('hidden') === 'false') { // hide the code output button.parent().find('.go, .gp, .gt').hide(); button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden'); button.css('text-decoration', 'line-through'); button.attr('title', show_text); button.data('hidden', 'true'); } else { // show the code output button.parent().find('.go, .gp, .gt').show(); button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible'); button.css('text-decoration', 'none'); button.attr('title', hide_text); button.data('hidden', 'false'); } }); }); radio_beam-0.3.2/astropy_helpers/astropy_helpers/sphinx/themes/bootstrap-astropy/static/sidebar.js0000644000077000000240000001155312711231150034033 0ustar adamstaff00000000000000/* * sidebar.js * ~~~~~~~~~~ * * This script makes the Sphinx sidebar collapsible. * * .sphinxsidebar contains .sphinxsidebarwrapper. This script adds * in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton * used to collapse and expand the sidebar. * * When the sidebar is collapsed the .sphinxsidebarwrapper is hidden * and the width of the sidebar and the margin-left of the document * are decreased. When the sidebar is expanded the opposite happens. * This script saves a per-browser/per-session cookie used to * remember the position of the sidebar among the pages. * Once the browser is closed the cookie is deleted and the position * reset to the default (expanded). * * :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ $(function() { // global elements used by the functions. // the 'sidebarbutton' element is defined as global after its // creation, in the add_sidebar_button function var bodywrapper = $('.bodywrapper'); var sidebar = $('.sphinxsidebar'); var sidebarwrapper = $('.sphinxsidebarwrapper'); // for some reason, the document has no sidebar; do not run into errors if (!sidebar.length) return; // original margin-left of the bodywrapper and width of the sidebar // with the sidebar expanded var bw_margin_expanded = bodywrapper.css('margin-left'); var ssb_width_expanded = sidebar.width(); // margin-left of the bodywrapper and width of the sidebar // with the sidebar collapsed var bw_margin_collapsed = 12; var ssb_width_collapsed = 12; // custom colors var dark_color = '#404040'; var light_color = '#505050'; function sidebar_is_collapsed() { return sidebarwrapper.is(':not(:visible)'); } function toggle_sidebar() { if (sidebar_is_collapsed()) expand_sidebar(); else collapse_sidebar(); } function collapse_sidebar() { sidebarwrapper.hide(); sidebar.css('width', ssb_width_collapsed); bodywrapper.css('margin-left', bw_margin_collapsed); sidebarbutton.css({ 'margin-left': '-1px', 'height': bodywrapper.height(), 'border-radius': '3px' }); sidebarbutton.find('span').text('»'); sidebarbutton.attr('title', _('Expand sidebar')); document.cookie = 'sidebar=collapsed'; } function expand_sidebar() { bodywrapper.css('margin-left', bw_margin_expanded); sidebar.css('width', ssb_width_expanded); sidebarwrapper.show(); sidebarbutton.css({ 'margin-left': ssb_width_expanded - 12, 'height': bodywrapper.height(), 'border-radius': '0px 3px 3px 0px' }); sidebarbutton.find('span').text('«'); sidebarbutton.attr('title', _('Collapse sidebar')); document.cookie = 'sidebar=expanded'; } function add_sidebar_button() { sidebarwrapper.css({ 'float': 'left', 'margin-right': '0', 'width': ssb_width_expanded - 18 }); // create the button sidebar.append('
«
'); var sidebarbutton = $('#sidebarbutton'); // find the height of the viewport to center the '<<' in the page var viewport_height; if (window.innerHeight) viewport_height = window.innerHeight; else viewport_height = $(window).height(); var sidebar_offset = sidebar.offset().top; var sidebar_height = Math.max(bodywrapper.height(), sidebar.height()); sidebarbutton.find('span').css({ 'font-family': '"Lucida Grande",Arial,sans-serif', 'display': 'block', 'top': Math.min(viewport_height/2, sidebar_height/2 + sidebar_offset) - 10, 'width': 12, 'position': 'fixed', 'text-align': 'center' }); sidebarbutton.click(toggle_sidebar); sidebarbutton.attr('title', _('Collapse sidebar')); sidebarbutton.css({ 'color': '#FFFFFF', 'background-color': light_color, 'border': '1px solid ' + light_color, 'border-radius': '0px 3px 3px 0px', 'font-size': '1.2em', 'cursor': 'pointer', 'height': sidebar_height, 'padding-top': '1px', 'margin': '-1px', 'margin-left': ssb_width_expanded - 12 }); sidebarbutton.hover( function () { $(this).css('background-color', dark_color); }, function () { $(this).css('background-color', light_color); } ); } function set_position_from_cookie() { if (!document.cookie) return; var items = document.cookie.split(';'); for(var k=0; k= 7: eggs = glob.glob(os.path.join(path, '.eggs', '*.egg')) else: eggs = glob.glob('*.egg') return eggs radio_beam-0.3.2/astropy_helpers/astropy_helpers/tests/test_git_helpers.py0000644000077000000240000002013213516112504027341 0ustar adamstaff00000000000000import glob import imp import os import pkgutil import re import sys import tarfile import pytest from warnings import catch_warnings from . import reset_setup_helpers, reset_distutils_log # noqa from . import run_cmd, run_setup, cleanup_import from astropy_helpers.git_helpers import get_git_devstr PY3 = sys.version_info[0] == 3 if PY3: _text_type = str else: _text_type = unicode # noqa _DEV_VERSION_RE = re.compile(r'\d+\.\d+(?:\.\d+)?\.dev(\d+)') ASTROPY_HELPERS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) TEST_VERSION_SETUP_PY = """\ #!/usr/bin/env python import sys from setuptools import setup NAME = 'apyhtest_eva' VERSION = {version!r} RELEASE = 'dev' not in VERSION sys.path.insert(0, r'{astropy_helpers_path}') from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py if not RELEASE: VERSION += get_git_devstr(False) generate_version_py(NAME, VERSION, RELEASE, False, uses_git=not RELEASE) setup(name=NAME, version=VERSION, packages=['apyhtest_eva']) """ TEST_VERSION_INIT = """\ try: from .version import version as __version__ from .version import githash as __githash__ except ImportError: __version__ = __githash__ = '' """ @pytest.fixture def version_test_package(tmpdir, request): def make_test_package(version='42.42.dev'): test_package = tmpdir.mkdir('test_package') test_package.join('setup.py').write( TEST_VERSION_SETUP_PY.format(version=version, astropy_helpers_path=ASTROPY_HELPERS_PATH)) test_package.mkdir('apyhtest_eva').join('__init__.py').write(TEST_VERSION_INIT) with test_package.as_cwd(): run_cmd('git', ['init']) run_cmd('git', ['add', '--all']) run_cmd('git', ['commit', '-m', 'test package']) if '' in sys.path: sys.path.remove('') sys.path.insert(0, '') def finalize(): cleanup_import('apyhtest_eva') request.addfinalizer(finalize) return test_package return make_test_package def test_update_git_devstr(version_test_package, capsys): """Tests that the commit number in the package's version string updates after git commits even without re-running setup.py. """ # We have to call version_test_package to actually create the package test_pkg = version_test_package() with test_pkg.as_cwd(): run_setup('setup.py', ['--version']) stdout, stderr = capsys.readouterr() version = stdout.strip() m = _DEV_VERSION_RE.match(version) assert m, ( "Stdout did not match the version string pattern:" "\n\n{0}\n\nStderr:\n\n{1}".format(stdout, stderr)) revcount = int(m.group(1)) import apyhtest_eva assert apyhtest_eva.__version__ == version # Make a silly git commit with open('.test', 'w'): pass run_cmd('git', ['add', '.test']) run_cmd('git', ['commit', '-m', 'test']) import apyhtest_eva.version imp.reload(apyhtest_eva.version) # Previously this checked packagename.__version__, but in order for that to # be updated we also have to re-import _astropy_init which could be tricky. # Checking directly that the packagename.version module was updated is # sufficient: m = _DEV_VERSION_RE.match(apyhtest_eva.version.version) assert m assert int(m.group(1)) == revcount + 1 # This doesn't test astropy_helpers.get_helpers.update_git_devstr directly # since a copy of that function is made in packagename.version (so that it # can work without astropy_helpers installed). In order to get test # coverage on the actual astropy_helpers copy of that function just call it # directly and compare to the value in packagename from astropy_helpers.git_helpers import update_git_devstr newversion = update_git_devstr(version, path=str(test_pkg)) assert newversion == apyhtest_eva.version.version def test_version_update_in_other_repos(version_test_package, tmpdir): """ Regression test for https://github.com/astropy/astropy-helpers/issues/114 and for https://github.com/astropy/astropy-helpers/issues/107 """ test_pkg = version_test_package() with test_pkg.as_cwd(): run_setup('setup.py', ['build']) # Add the path to the test package to sys.path for now sys.path.insert(0, str(test_pkg)) try: import apyhtest_eva m = _DEV_VERSION_RE.match(apyhtest_eva.__version__) assert m correct_revcount = int(m.group(1)) with tmpdir.as_cwd(): testrepo = tmpdir.mkdir('testrepo') testrepo.chdir() # Create an empty git repo run_cmd('git', ['init']) import apyhtest_eva.version imp.reload(apyhtest_eva.version) m = _DEV_VERSION_RE.match(apyhtest_eva.version.version) assert m assert int(m.group(1)) == correct_revcount correct_revcount = int(m.group(1)) # Add several commits--more than the revcount for the apyhtest_eva package for idx in range(correct_revcount + 5): test_filename = '.test' + str(idx) testrepo.ensure(test_filename) run_cmd('git', ['add', test_filename]) run_cmd('git', ['commit', '-m', 'A message']) import apyhtest_eva.version imp.reload(apyhtest_eva.version) m = _DEV_VERSION_RE.match(apyhtest_eva.version.version) assert m assert int(m.group(1)) == correct_revcount correct_revcount = int(m.group(1)) finally: sys.path.remove(str(test_pkg)) @pytest.mark.parametrize('version', ['1.0.dev', '1.0']) def test_installed_git_version(version_test_package, version, tmpdir, capsys): """ Test for https://github.com/astropy/astropy-helpers/issues/87 Ensures that packages installed with astropy_helpers have a correct copy of the git hash of the installed commit. """ # To test this, it should suffice to build a source dist, unpack it # somewhere outside the git repository, and then do a build and import # from the build directory--no need to "install" as such test_pkg = version_test_package(version) with test_pkg.as_cwd(): run_setup('setup.py', ['build']) try: import apyhtest_eva githash = apyhtest_eva.__githash__ assert githash and isinstance(githash, _text_type) # Ensure that it does in fact look like a git hash and not some # other arbitrary string assert re.match(r'[0-9a-f]{40}', githash) finally: cleanup_import('apyhtest_eva') run_setup('setup.py', ['sdist', '--dist-dir=dist', '--formats=gztar']) tgzs = glob.glob(os.path.join('dist', '*.tar.gz')) assert len(tgzs) == 1 tgz = test_pkg.join(tgzs[0]) build_dir = tmpdir.mkdir('build_dir') tf = tarfile.open(str(tgz), mode='r:gz') tf.extractall(str(build_dir)) with build_dir.as_cwd(): pkg_dir = glob.glob('apyhtest_eva-*')[0] os.chdir(pkg_dir) with catch_warnings(record=True) as w: run_setup('setup.py', ['build']) try: import apyhtest_eva loader = pkgutil.get_loader('apyhtest_eva') # Ensure we are importing the 'packagename' that was just unpacked # into the build_dir assert loader.get_filename().startswith(str(build_dir)) assert apyhtest_eva.__githash__ == githash finally: cleanup_import('apyhtest_eva') def test_get_git_devstr(tmpdir): dirpath = str(tmpdir) warn_msg = "No git repository present at" # Verify as much as possible, but avoid dealing with paths on windows if not sys.platform.startswith('win'): warn_msg += " '{}'".format(dirpath) with catch_warnings(record=True) as w: devstr = get_git_devstr(path=dirpath) assert devstr == '0' assert len(w) == 1 assert str(w[0].message).startswith(warn_msg) radio_beam-0.3.2/astropy_helpers/astropy_helpers/tests/test_openmp_helpers.py0000644000077000000240000000232013174167433030066 0ustar adamstaff00000000000000import os import sys from copy import deepcopy from distutils.core import Extension from ..openmp_helpers import add_openmp_flags_if_available from ..setup_helpers import _module_state, register_commands IS_TRAVIS_LINUX = os.environ.get('TRAVIS_OS_NAME', None) == 'linux' IS_APPVEYOR = os.environ.get('APPVEYOR', None) == 'True' PY3_LT_35 = sys.version_info[0] == 3 and sys.version_info[1] < 5 _state = None def setup_function(function): global state state = deepcopy(_module_state) def teardown_function(function): _module_state.clear() _module_state.update(state) def test_add_openmp_flags_if_available(): register_commands('openmp_testing', '0.0', False) using_openmp = add_openmp_flags_if_available(Extension('test', [])) # Make sure that on Travis (Linux) and AppVeyor OpenMP does get used (for # MacOS X usually it will not work but this will depend on the compiler). # Having this is useful because we'll find out if OpenMP no longer works # for any reason on platforms on which it does work at the time of writing. # OpenMP doesn't work on Python 3.x where x<5 on AppVeyor though. if IS_TRAVIS_LINUX or (IS_APPVEYOR and not PY3_LT_35): assert using_openmp radio_beam-0.3.2/astropy_helpers/astropy_helpers/tests/test_setup_helpers.py0000644000077000000240000004445413516112504027733 0ustar adamstaff00000000000000import os import sys import stat import shutil import imp import contextlib import pytest from textwrap import dedent from setuptools import Distribution from ..setup_helpers import get_package_info, register_commands from ..commands import build_ext from . import reset_setup_helpers, reset_distutils_log # noqa from . import run_setup, cleanup_import ASTROPY_HELPERS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) # Determine whether we're in a PY2 environment without using six USING_PY2 = sys.version_info < (3,0,0) def _extension_test_package(tmpdir, request, extension_type='c', include_numpy=False): """Creates a simple test package with an extension module.""" test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('apyhtest_eva').ensure('__init__.py') # TODO: It might be later worth making this particular test package into a # reusable fixture for other build_ext tests if extension_type in ('c', 'both'): # A minimal C extension for testing test_pkg.join('apyhtest_eva', 'unit01.c').write(dedent("""\ #include #ifndef PY3K #if PY_MAJOR_VERSION >= 3 #define PY3K 1 #else #define PY3K 0 #endif #endif #if PY3K static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "unit01", NULL, -1, NULL }; PyMODINIT_FUNC PyInit_unit01(void) { return PyModule_Create(&moduledef); } #else PyMODINIT_FUNC initunit01(void) { Py_InitModule3("unit01", NULL, NULL); } #endif """)) if extension_type in ('pyx', 'both'): # A minimal Cython extension for testing test_pkg.join('apyhtest_eva', 'unit02.pyx').write(dedent("""\ print("Hello cruel angel.") """)) if extension_type == 'c': extensions = ['unit01.c'] elif extension_type == 'pyx': extensions = ['unit02.pyx'] elif extension_type == 'both': extensions = ['unit01.c', 'unit02.pyx'] include_dirs = ['numpy'] if include_numpy else [] extensions_list = [ "Extension('apyhtest_eva.{0}', [join('apyhtest_eva', '{1}')], include_dirs={2})".format( os.path.splitext(extension)[0], extension, include_dirs) for extension in extensions] test_pkg.join('apyhtest_eva', 'setup_package.py').write(dedent("""\ from setuptools import Extension from os.path import join def get_extensions(): return [{0}] """.format(', '.join(extensions_list)))) test_pkg.join('setup.py').write(dedent("""\ import sys from os.path import join from setuptools import setup sys.path.insert(0, r'{astropy_helpers_path}') from astropy_helpers.setup_helpers import register_commands from astropy_helpers.setup_helpers import get_package_info from astropy_helpers.version_helpers import generate_version_py if '--no-cython' in sys.argv: from astropy_helpers.commands import build_ext build_ext.should_build_with_cython = lambda *args: False sys.argv.remove('--no-cython') NAME = 'apyhtest_eva' VERSION = '0.1' RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) generate_version_py(NAME, VERSION, RELEASE, False, False) package_info = get_package_info() setup( name=NAME, version=VERSION, cmdclass=cmdclassd, **package_info ) """.format(astropy_helpers_path=ASTROPY_HELPERS_PATH))) if '' in sys.path: sys.path.remove('') sys.path.insert(0, '') def finalize(): cleanup_import('apyhtest_eva') request.addfinalizer(finalize) return test_pkg @pytest.fixture def extension_test_package(tmpdir, request): return _extension_test_package(tmpdir, request, extension_type='both') @pytest.fixture def c_extension_test_package(tmpdir, request): # Check whether numpy is installed in the test environment # For Python2 compatibility we need to do this hack rather than using # importlib.util.find_spec without the try/except try: has_numpy = bool(imp.find_module('numpy')) except ImportError: has_numpy = False return _extension_test_package(tmpdir, request, extension_type='c', include_numpy=has_numpy) @pytest.fixture def pyx_extension_test_package(tmpdir, request): return _extension_test_package(tmpdir, request, extension_type='pyx') def test_cython_autoextensions(tmpdir): """ Regression test for https://github.com/astropy/astropy-helpers/pull/19 Ensures that Cython extensions in sub-packages are discovered and built only once. """ # Make a simple test package test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('yoda').mkdir('luke') test_pkg.ensure('yoda', '__init__.py') test_pkg.ensure('yoda', 'luke', '__init__.py') test_pkg.join('yoda', 'luke', 'dagobah.pyx').write( """def testfunc(): pass""") # Required, currently, for get_package_info to work register_commands('yoda', '0.0', False, srcdir=str(test_pkg)) package_info = get_package_info(str(test_pkg)) assert len(package_info['ext_modules']) == 1 assert package_info['ext_modules'][0].name == 'yoda.luke.dagobah' def test_compiler_module(capsys, c_extension_test_package): """ Test ensuring that the compiler module is built and installed for packages that have extension modules. """ test_pkg = c_extension_test_package install_temp = test_pkg.mkdir('install_temp') with test_pkg.as_cwd(): # This is one of the simplest ways to install just a package into a # test directory run_setup('setup.py', ['install', '--single-version-externally-managed', '--install-lib={0}'.format(install_temp), '--record={0}'.format(install_temp.join('record.txt'))]) stdout, stderr = capsys.readouterr() assert "No git repository present at" in stderr with install_temp.as_cwd(): import apyhtest_eva # Make sure we imported the apyhtest_eva package from the correct place dirname = os.path.abspath(os.path.dirname(apyhtest_eva.__file__)) assert dirname == str(install_temp.join('apyhtest_eva')) import apyhtest_eva._compiler import apyhtest_eva.version assert apyhtest_eva.version.compiler == apyhtest_eva._compiler.compiler assert apyhtest_eva.version.compiler != 'unknown' def test_no_cython_buildext(capsys, c_extension_test_package, monkeypatch): """ Regression test for https://github.com/astropy/astropy-helpers/pull/35 This tests the custom build_ext command installed by astropy_helpers when used with a project that has no Cython extensions (but does have one or more normal C extensions). """ test_pkg = c_extension_test_package with test_pkg.as_cwd(): run_setup('setup.py', ['build_ext', '--inplace', '--no-cython']) stdout, stderr = capsys.readouterr() assert "No git repository present at" in stderr sys.path.insert(0, str(test_pkg)) try: import apyhtest_eva.unit01 dirname = os.path.abspath(os.path.dirname(apyhtest_eva.unit01.__file__)) assert dirname == str(test_pkg.join('apyhtest_eva')) finally: sys.path.remove(str(test_pkg)) def test_missing_cython_c_files(capsys, pyx_extension_test_package, monkeypatch): """ Regression test for https://github.com/astropy/astropy-helpers/pull/181 Test failure mode when building a package that has Cython modules, but where Cython is not installed and the generated C files are missing. """ test_pkg = pyx_extension_test_package with test_pkg.as_cwd(): run_setup('setup.py', ['build_ext', '--inplace', '--no-cython']) stdout, stderr = capsys.readouterr() assert "No git repository present at" in stderr msg = ('Could not find C/C++ file ' '{0}.(c/cpp)'.format('apyhtest_eva/unit02'.replace('/', os.sep))) assert msg in stderr @pytest.mark.parametrize('mode', ['cli', 'cli-w', 'deprecated', 'cli-l']) def test_build_docs(capsys, tmpdir, mode): """ Test for build_docs """ test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('mypackage') test_pkg.join('mypackage').join('__init__.py').write(dedent("""\ def test_function(): pass class A(): pass class B(A): pass """)) test_pkg.mkdir('docs') docs = test_pkg.join('docs') autosummary = docs.mkdir('_templates').mkdir('autosummary') autosummary.join('base.rst').write('{% extends "autosummary_core/base.rst" %}') autosummary.join('class.rst').write('{% extends "autosummary_core/class.rst" %}') autosummary.join('module.rst').write('{% extends "autosummary_core/module.rst" %}') docs_dir = test_pkg.join('docs') docs_dir.join('conf.py').write(dedent("""\ import sys sys.path.insert(0, r'{0}') import warnings with warnings.catch_warnings(): # ignore matplotlib warning warnings.simplefilter("ignore") from astropy_helpers.sphinx.conf import * exclude_patterns.append('_templates') """.format(ASTROPY_HELPERS_PATH))) docs_dir.join('index.rst').write(dedent("""\ .. automodapi:: mypackage :no-inheritance-diagram: """)) test_pkg.join('setup.py').write(dedent("""\ import sys sys.path.insert(0, r'{astropy_helpers_path}') from os.path import join from setuptools import setup, Extension from astropy_helpers.setup_helpers import register_commands, get_package_info NAME = 'mypackage' VERSION = 0.1 RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) setup( name=NAME, version=VERSION, cmdclass=cmdclassd, **get_package_info() ) """.format(astropy_helpers_path=ASTROPY_HELPERS_PATH))) with test_pkg.as_cwd(): if mode == 'cli': run_setup('setup.py', ['build_docs']) elif mode == 'cli-w': run_setup('setup.py', ['build_docs', '-w']) elif mode == 'cli-l': run_setup('setup.py', ['build_docs', '-l']) elif mode == 'deprecated': run_setup('setup.py', ['build_sphinx']) stdout, stderr = capsys.readouterr() assert 'AstropyDeprecationWarning' in stderr assert os.path.exists(docs_dir.join('_build', 'html', 'index.html').strpath) def test_command_hooks(tmpdir, capsys): """A basic test for pre- and post-command hooks.""" test_pkg = tmpdir.mkdir('test_pkg') test_pkg.mkdir('_welltall_') test_pkg.join('_welltall_', '__init__.py').ensure() # Create a setup_package module with a couple of command hooks in it test_pkg.join('_welltall_', 'setup_package.py').write(dedent("""\ def pre_build_hook(cmd_obj): print('Hello build!') def post_build_hook(cmd_obj): print('Goodbye build!') """)) # A simple setup.py for the test package--running register_commands should # discover and enable the command hooks test_pkg.join('setup.py').write(dedent("""\ import sys from os.path import join from setuptools import setup, Extension sys.path.insert(0, r'{astropy_helpers_path}') from astropy_helpers.setup_helpers import register_commands, get_package_info NAME = '_welltall_' VERSION = 0.1 RELEASE = True cmdclassd = register_commands(NAME, VERSION, RELEASE) setup( name=NAME, version=VERSION, cmdclass=cmdclassd ) """.format(astropy_helpers_path=ASTROPY_HELPERS_PATH))) with test_pkg.as_cwd(): try: run_setup('setup.py', ['build']) finally: cleanup_import('_welltall_') stdout, stderr = capsys.readouterr() want = dedent("""\ running build running pre_hook from _welltall_.setup_package for build command Hello build! running post_hook from _welltall_.setup_package for build command Goodbye build! """).strip() assert want in stdout.replace('\r\n', '\n').replace('\r', '\n') def test_adjust_compiler(monkeypatch, tmpdir): """ Regression test for https://github.com/astropy/astropy-helpers/issues/182 """ from distutils import ccompiler, sysconfig class MockLog(object): def __init__(self): self.messages = [] def warn(self, message): self.messages.append(message) good = tmpdir.join('gcc-good') good.write(dedent("""\ #!{python} import sys print('gcc 4.10') sys.exit(0) """.format(python=sys.executable))) good.chmod(stat.S_IRUSR | stat.S_IEXEC) # A "compiler" that reports itself to be a version of Apple's llvm-gcc # which is broken bad = tmpdir.join('gcc-bad') bad.write(dedent("""\ #!{python} import sys print('i686-apple-darwin-llvm-gcc-4.2') sys.exit(0) """.format(python=sys.executable))) bad.chmod(stat.S_IRUSR | stat.S_IEXEC) # A "compiler" that doesn't even know its identity (this reproduces the bug # in #182) ugly = tmpdir.join('gcc-ugly') ugly.write(dedent("""\ #!{python} import sys sys.exit(1) """.format(python=sys.executable))) ugly.chmod(stat.S_IRUSR | stat.S_IEXEC) # Scripts with shebang lines don't work implicitly in Windows when passed # to subprocess.Popen, so... if 'win' in sys.platform: good = ' '.join((sys.executable, str(good))) bad = ' '.join((sys.executable, str(bad))) ugly = ' '.join((sys.executable, str(ugly))) dist = Distribution({}) cmd_cls = build_ext.generate_build_ext_command('astropy', False) cmd = cmd_cls(dist) adjust_compiler = cmd._adjust_compiler @contextlib.contextmanager def test_setup(): log = MockLog() monkeypatch.setattr(build_ext, 'log', log) yield log monkeypatch.undo() @contextlib.contextmanager def compiler_setter_with_environ(compiler): monkeypatch.setenv('CC', compiler) with test_setup() as log: yield log monkeypatch.undo() @contextlib.contextmanager def compiler_setter_with_sysconfig(compiler): monkeypatch.setattr(ccompiler, 'get_default_compiler', lambda: 'unix') monkeypatch.setattr(sysconfig, 'get_config_var', lambda v: compiler) old_cc = os.environ.get('CC') if old_cc is not None: del os.environ['CC'] with test_setup() as log: yield log monkeypatch.undo() monkeypatch.undo() monkeypatch.undo() if old_cc is not None: os.environ['CC'] = old_cc compiler_setters = (compiler_setter_with_environ, compiler_setter_with_sysconfig) for compiler_setter in compiler_setters: with compiler_setter(str(good)): # Should have no side-effects adjust_compiler() with compiler_setter(str(ugly)): # Should just pass without complaint, since we can't determine # anything about the compiler anyways adjust_compiler() # In the following tests we check the log messages just to ensure that the # failures occur on the correct code paths for these cases with compiler_setter_with_environ(str(bad)) as log: with pytest.raises(SystemExit): adjust_compiler() assert len(log.messages) == 1 assert 'will fail to compile' in log.messages[0] with compiler_setter_with_sysconfig(str(bad)): adjust_compiler() assert 'CC' in os.environ and os.environ['CC'] == 'clang' with compiler_setter_with_environ('bogus') as log: with pytest.raises(SystemExit): # Missing compiler? adjust_compiler() assert len(log.messages) == 1 assert 'cannot be found or executed' in log.messages[0] with compiler_setter_with_sysconfig('bogus') as log: with pytest.raises(SystemExit): # Missing compiler? adjust_compiler() assert len(log.messages) == 1 assert 'The C compiler used to compile Python' in log.messages[0] def test_invalid_package_exclusion(tmpdir, capsys): module_name = 'foobar' setup_header = dedent("""\ import sys from os.path import join from setuptools import setup, Extension sys.path.insert(0, r'{astropy_helpers_path}') from astropy_helpers.setup_helpers import register_commands, \\ get_package_info, add_exclude_packages NAME = {module_name!r} VERSION = 0.1 RELEASE = True """.format(module_name=module_name, astropy_helpers_path=ASTROPY_HELPERS_PATH)) setup_footer = dedent("""\ setup( name=NAME, version=VERSION, cmdclass=cmdclassd, **package_info ) """) # Test error when using add_package_excludes out of order error_commands = dedent("""\ cmdclassd = register_commands(NAME, VERSION, RELEASE) package_info = get_package_info() add_exclude_packages(['tests*']) """) error_pkg = tmpdir.mkdir('error_pkg') error_pkg.join('setup.py').write( setup_header + error_commands + setup_footer) with error_pkg.as_cwd(): run_setup('setup.py', ['build']) stdout, stderr = capsys.readouterr() assert "RuntimeError" in stderr # Test warning when using deprecated exclude parameter warn_commands = dedent("""\ cmdclassd = register_commands(NAME, VERSION, RELEASE) package_info = get_package_info(exclude=['test*']) """) warn_pkg = tmpdir.mkdir('warn_pkg') warn_pkg.join('setup.py').write( setup_header + warn_commands + setup_footer) with warn_pkg.as_cwd(): run_setup('setup.py', ['build']) stdout, stderr = capsys.readouterr() assert 'AstropyDeprecationWarning' in stderr radio_beam-0.3.2/astropy_helpers/astropy_helpers/tests/test_utils.py0000644000077000000240000000135712711231150026177 0ustar adamstaff00000000000000import os from ..utils import find_data_files def test_find_data_files(tmpdir): data = tmpdir.mkdir('data') sub1 = data.mkdir('sub1') sub2 = data.mkdir('sub2') sub3 = sub1.mkdir('sub3') for directory in (data, sub1, sub2, sub3): filename = directory.join('data.dat').strpath with open(filename, 'w') as f: f.write('test') filenames = find_data_files(data.strpath, '**/*.dat') filenames = sorted(os.path.relpath(x, data.strpath) for x in filenames) assert filenames[0] == os.path.join('data.dat') assert filenames[1] == os.path.join('sub1', 'data.dat') assert filenames[2] == os.path.join('sub1', 'sub3', 'data.dat') assert filenames[3] == os.path.join('sub2', 'data.dat') radio_beam-0.3.2/astropy_helpers/astropy_helpers/utils.py0000644000077000000240000006476513234725027024026 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, unicode_literals import contextlib import functools import imp import inspect import os import sys import glob import textwrap import types import warnings try: from importlib import machinery as import_machinery # Python 3.2 does not have SourceLoader if not hasattr(import_machinery, 'SourceLoader'): import_machinery = None except ImportError: import_machinery = None # Python 3.3's importlib caches filesystem reads for faster imports in the # general case. But sometimes it's necessary to manually invalidate those # caches so that the import system can pick up new generated files. See # https://github.com/astropy/astropy/issues/820 if sys.version_info[:2] >= (3, 3): from importlib import invalidate_caches else: def invalidate_caches(): return None # Python 2/3 compatibility if sys.version_info[0] < 3: string_types = (str, unicode) # noqa else: string_types = (str,) # Note: The following Warning subclasses are simply copies of the Warnings in # Astropy of the same names. 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 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. """ def _get_platlib_dir(cmd): """ Given a build command, return the name of the appropriate platform-specific build subdirectory directory (e.g. build/lib.linux-x86_64-2.7) """ plat_specifier = '.{0}-{1}'.format(cmd.plat_name, sys.version[0:3]) return os.path.join(cmd.build_base, 'lib' + plat_specifier) def get_numpy_include_path(): """ Gets the path to the numpy headers. """ # We need to go through this nonsense in case setuptools # downloaded and installed Numpy for us as part of the build or # install, since Numpy may still think it's in "setup mode", when # in fact we're ready to use it to build astropy now. if sys.version_info[0] >= 3: import builtins if hasattr(builtins, '__NUMPY_SETUP__'): del builtins.__NUMPY_SETUP__ import imp import numpy imp.reload(numpy) else: import __builtin__ if hasattr(__builtin__, '__NUMPY_SETUP__'): del __builtin__.__NUMPY_SETUP__ import numpy reload(numpy) try: numpy_include = numpy.get_include() except AttributeError: numpy_include = numpy.get_numpy_include() return numpy_include class _DummyFile(object): """A noop writeable object.""" errors = '' # Required for Python 3.x def write(self, s): pass def flush(self): 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() exception_occurred = False try: yield except: exception_occurred = True # Go ahead and clean up so that exception handling can work normally sys.stdout = old_stdout sys.stderr = old_stderr raise if not exception_occurred: sys.stdout = old_stdout sys.stderr = old_stderr 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) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): 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 def write_if_different(filename, data): """Write `data` to `filename`, if the content of the file is different. Parameters ---------- filename : str The file name to be written to. data : bytes The data to be written to `filename`. """ assert isinstance(data, bytes) if os.path.exists(filename): with open(filename, 'rb') as fd: original_data = fd.read() else: original_data = None if original_data != data: with open(filename, 'wb') as fd: fd.write(data) def import_file(filename, name=None): """ Imports a module from a single file as if it doesn't belong to a particular package. The returned module will have the optional ``name`` if given, or else a name generated from the filename. """ # Specifying a traditional dot-separated fully qualified name here # results in a number of "Parent module 'astropy' not found while # handling absolute import" warnings. Using the same name, the # namespaces of the modules get merged together. So, this # generates an underscore-separated name which is more likely to # be unique, and it doesn't really matter because the name isn't # used directly here anyway. mode = 'U' if sys.version_info[0] < 3 else 'r' if name is None: basename = os.path.splitext(filename)[0] name = '_'.join(os.path.relpath(basename).split(os.sep)[1:]) if import_machinery: loader = import_machinery.SourceFileLoader(name, filename) mod = loader.load_module() else: with open(filename, mode) as fd: mod = imp.load_module(name, fd, filename, ('.py', mode, 1)) return mod def resolve_name(name): """Resolve a name like ``module.object`` to an object and return it. Raise `ImportError` if the module or name is not found. """ parts = name.split('.') cursor = len(parts) - 1 module_name = parts[:cursor] attr_name = parts[-1] while cursor > 0: try: ret = __import__('.'.join(module_name), fromlist=[attr_name]) break except ImportError: if cursor == 0: raise cursor -= 1 module_name = parts[:cursor] attr_name = parts[cursor] ret = '' for part in parts[cursor:]: try: ret = getattr(ret, part) except AttributeError: raise ImportError(name) return ret if sys.version_info[0] >= 3: def iteritems(dictionary): return dictionary.items() else: def iteritems(dictionary): return dictionary.iteritems() def extends_doc(extended_func): """ A function decorator for use when wrapping an existing function but adding additional functionality. This copies the docstring from the original function, and appends to it (along with a newline) the docstring of the wrapper function. Examples -------- >>> def foo(): ... '''Hello.''' ... >>> @extends_doc(foo) ... def bar(): ... '''Goodbye.''' ... >>> print(bar.__doc__) Hello. Goodbye. """ def decorator(func): if not (extended_func.__doc__ is None or func.__doc__ is None): func.__doc__ = '\n\n'.join([extended_func.__doc__.rstrip('\n'), func.__doc__.lstrip('\n')]) return func return decorator # Duplicated from astropy.utils.decorators.deprecated # When fixing issues in this function fix them in astropy first, then # port the fixes over to astropy-helpers def deprecated(since, message='', name='', alternative='', pending=False, obj_type=None): """ Used to mark a function or class as deprecated. To mark an attribute as deprecated, use `deprecated_attribute`. Parameters ---------- since : str The release at which this API became deprecated. This is required. message : str, optional Override the default deprecation message. The format specifier ``func`` may be used for the name of the function, and ``alternative`` may be used in the deprecation message to insert the name of an alternative to the deprecated function. ``obj_type`` may be used to insert a friendly name for the type of object being deprecated. name : str, optional The name of the deprecated function or class; if not provided the name is automatically determined from the passed in function or class, though this is useful in the case of renamed functions, where the new function is just assigned to the name of the deprecated function. For example:: def new_function(): ... oldFunction = new_function alternative : str, optional An alternative function or class name that the user may use in place of the deprecated object. The deprecation warning will tell the user about this alternative if provided. pending : bool, optional If True, uses a AstropyPendingDeprecationWarning instead of a AstropyDeprecationWarning. obj_type : str, optional The type of this object, if the automatically determined one needs to be overridden. """ method_types = (classmethod, staticmethod, types.MethodType) def deprecate_doc(old_doc, message): """ Returns a given docstring with a deprecation message prepended to it. """ if not old_doc: old_doc = '' old_doc = textwrap.dedent(old_doc).strip('\n') new_doc = (('\n.. deprecated:: %(since)s' '\n %(message)s\n\n' % {'since': since, 'message': message.strip()}) + old_doc) if not old_doc: # This is to prevent a spurious 'unexpected unindent' warning from # docutils when the original docstring was blank. new_doc += r'\ ' return new_doc def get_function(func): """ Given a function or classmethod (or other function wrapper type), get the function object. """ if isinstance(func, method_types): func = func.__func__ return func def deprecate_function(func, message): """ Returns a wrapped function that displays an ``AstropyDeprecationWarning`` when it is called. """ if isinstance(func, method_types): func_wrapper = type(func) else: func_wrapper = lambda f: f func = get_function(func) def deprecated_func(*args, **kwargs): if pending: category = AstropyPendingDeprecationWarning else: category = AstropyDeprecationWarning warnings.warn(message, category, stacklevel=2) return func(*args, **kwargs) # If this is an extension function, we can't call # functools.wraps on it, but we normally don't care. # This crazy way to get the type of a wrapper descriptor is # straight out of the Python 3.3 inspect module docs. if type(func) != type(str.__dict__['__add__']): deprecated_func = functools.wraps(func)(deprecated_func) deprecated_func.__doc__ = deprecate_doc( deprecated_func.__doc__, message) return func_wrapper(deprecated_func) def deprecate_class(cls, message): """ Returns a wrapper class with the docstrings updated and an __init__ function that will raise an ``AstropyDeprectationWarning`` warning when called. """ # Creates a new class with the same name and bases as the # original class, but updates the dictionary with a new # docstring and a wrapped __init__ method. __module__ needs # to be manually copied over, since otherwise it will be set # to *this* module (astropy.utils.misc). # This approach seems to make Sphinx happy (the new class # looks enough like the original class), and works with # extension classes (which functools.wraps does not, since # it tries to modify the original class). # We need to add a custom pickler or you'll get # Can't pickle : it's not found as ... # errors. Picklability is required for any class that is # documented by Sphinx. members = cls.__dict__.copy() members.update({ '__doc__': deprecate_doc(cls.__doc__, message), '__init__': deprecate_function(get_function(cls.__init__), message), }) return type(cls.__name__, cls.__bases__, members) def deprecate(obj, message=message, name=name, alternative=alternative, pending=pending): if obj_type is None: if isinstance(obj, type): obj_type_name = 'class' elif inspect.isfunction(obj): obj_type_name = 'function' elif inspect.ismethod(obj) or isinstance(obj, method_types): obj_type_name = 'method' else: obj_type_name = 'object' else: obj_type_name = obj_type if not name: name = get_function(obj).__name__ altmessage = '' if not message or type(message) == type(deprecate): if pending: message = ('The %(func)s %(obj_type)s will be deprecated in a ' 'future version.') else: message = ('The %(func)s %(obj_type)s is deprecated and may ' 'be removed in a future version.') if alternative: altmessage = '\n Use %s instead.' % alternative message = ((message % { 'func': name, 'name': name, 'alternative': alternative, 'obj_type': obj_type_name}) + altmessage) if isinstance(obj, type): return deprecate_class(obj, message) else: return deprecate_function(obj, message) if type(message) == type(deprecate): return deprecate(message) return deprecate def deprecated_attribute(name, since, message=None, alternative=None, pending=False): """ Used to mark a public attribute as deprecated. This creates a property that will warn when the given attribute name is accessed. To prevent the warning (i.e. for internal code), use the private name for the attribute by prepending an underscore (i.e. ``self._name``). Parameters ---------- name : str The name of the deprecated attribute. since : str The release at which this API became deprecated. This is required. message : str, optional Override the default deprecation message. The format specifier ``name`` may be used for the name of the attribute, and ``alternative`` may be used in the deprecation message to insert the name of an alternative to the deprecated function. alternative : str, optional An alternative attribute that the user may use in place of the deprecated attribute. The deprecation warning will tell the user about this alternative if provided. pending : bool, optional If True, uses a AstropyPendingDeprecationWarning instead of a AstropyDeprecationWarning. Examples -------- :: class MyClass: # Mark the old_name as deprecated old_name = misc.deprecated_attribute('old_name', '0.1') def method(self): self._old_name = 42 """ private_name = '_' + name @deprecated(since, name=name, obj_type='attribute') def get(self): return getattr(self, private_name) @deprecated(since, name=name, obj_type='attribute') def set(self, val): setattr(self, private_name, val) @deprecated(since, name=name, obj_type='attribute') def delete(self): delattr(self, private_name) return property(get, set, delete) 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, string_types): 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('.'.join([module.__name__, version_path])) try: from pkg_resources import parse_version except ImportError: from distutils.version import LooseVersion as parse_version if inclusive: return parse_version(have_version) >= parse_version(version) else: return parse_version(have_version) > parse_version(version) # Copy of the classproperty decorator from astropy.utils.decorators class classproperty(property): """ Similar to `property`, but allows class-level properties. That is, a property whose getter is like a `classmethod`. The wrapped method may explicitly use the `classmethod` decorator (which must become before this decorator), or the `classmethod` may be omitted (it is implicit through use of this decorator). .. note:: classproperty only works for *read-only* properties. It does not currently allow writeable/deleteable properties, due to subtleties of how Python descriptors work. In order to implement such properties on a class a metaclass for that class must be implemented. Parameters ---------- fget : callable The function that computes the value of this property (in particular, the function when this is used as a decorator) a la `property`. doc : str, optional The docstring for the property--by default inherited from the getter function. lazy : bool, optional If True, caches the value returned by the first call to the getter function, so that it is only called once (used for lazy evaluation of an attribute). This is analogous to `lazyproperty`. The ``lazy`` argument can also be used when `classproperty` is used as a decorator (see the third example below). When used in the decorator syntax this *must* be passed in as a keyword argument. Examples -------- :: >>> class Foo(object): ... _bar_internal = 1 ... @classproperty ... def bar(cls): ... return cls._bar_internal + 1 ... >>> Foo.bar 2 >>> foo_instance = Foo() >>> foo_instance.bar 2 >>> foo_instance._bar_internal = 2 >>> foo_instance.bar # Ignores instance attributes 2 As previously noted, a `classproperty` is limited to implementing read-only attributes:: >>> class Foo(object): ... _bar_internal = 1 ... @classproperty ... def bar(cls): ... return cls._bar_internal ... @bar.setter ... def bar(cls, value): ... cls._bar_internal = value ... Traceback (most recent call last): ... NotImplementedError: classproperty can only be read-only; use a metaclass to implement modifiable class-level properties When the ``lazy`` option is used, the getter is only called once:: >>> class Foo(object): ... @classproperty(lazy=True) ... def bar(cls): ... print("Performing complicated calculation") ... return 1 ... >>> Foo.bar Performing complicated calculation 1 >>> Foo.bar 1 If a subclass inherits a lazy `classproperty` the property is still re-evaluated for the subclass:: >>> class FooSub(Foo): ... pass ... >>> FooSub.bar Performing complicated calculation 1 >>> FooSub.bar 1 """ def __new__(cls, fget=None, doc=None, lazy=False): if fget is None: # Being used as a decorator--return a wrapper that implements # decorator syntax def wrapper(func): return cls(func, lazy=lazy) return wrapper return super(classproperty, cls).__new__(cls) def __init__(self, fget, doc=None, lazy=False): self._lazy = lazy if lazy: self._cache = {} fget = self._wrap_fget(fget) super(classproperty, self).__init__(fget=fget, doc=doc) # There is a buglet in Python where self.__doc__ doesn't # get set properly on instances of property subclasses if # the doc argument was used rather than taking the docstring # from fget if doc is not None: self.__doc__ = doc def __get__(self, obj, objtype=None): if self._lazy and objtype in self._cache: return self._cache[objtype] if objtype is not None: # The base property.__get__ will just return self here; # instead we pass objtype through to the original wrapped # function (which takes the class as its sole argument) val = self.fget.__wrapped__(objtype) else: val = super(classproperty, self).__get__(obj, objtype=objtype) if self._lazy: if objtype is None: objtype = obj.__class__ self._cache[objtype] = val return val def getter(self, fget): return super(classproperty, self).getter(self._wrap_fget(fget)) def setter(self, fset): raise NotImplementedError( "classproperty can only be read-only; use a metaclass to " "implement modifiable class-level properties") def deleter(self, fdel): raise NotImplementedError( "classproperty can only be read-only; use a metaclass to " "implement modifiable class-level properties") @staticmethod def _wrap_fget(orig_fget): if isinstance(orig_fget, classmethod): orig_fget = orig_fget.__func__ # Using stock functools.wraps instead of the fancier version # found later in this module, which is overkill for this purpose @functools.wraps(orig_fget) def fget(obj): return orig_fget(obj.__class__) # Set the __wrapped__ attribute manually for support on Python 2 fget.__wrapped__ = orig_fget return fget def find_data_files(package, pattern): """ Include files matching ``pattern`` inside ``package``. Parameters ---------- package : str The package inside which to look for data files pattern : str Pattern (glob-style) to match for the data files (e.g. ``*.dat``). This supports the Python 3.5 ``**``recursive syntax. For example, ``**/*.fits`` matches all files ending with ``.fits`` recursively. Only one instance of ``**`` can be included in the pattern. """ if sys.version_info[:2] >= (3, 5): return glob.glob(os.path.join(package, pattern), recursive=True) else: if '**' in pattern: start, end = pattern.split('**') if end.startswith(('/', os.sep)): end = end[1:] matches = glob.glob(os.path.join(package, start, end)) for root, dirs, files in os.walk(os.path.join(package, start)): for dirname in dirs: matches += glob.glob(os.path.join(root, dirname, end)) return matches else: return glob.glob(os.path.join(package, pattern)) radio_beam-0.3.2/astropy_helpers/astropy_helpers/version.py0000644000077000000240000000104112711231151024312 0ustar adamstaff00000000000000# Autogenerated by Astropy-affiliated package astropy_helpers's setup.py on 2016-04-30 18:32:09.694914 from __future__ import unicode_literals import datetime version = "1.1" githash = "829410b24435ee678dbff3bf0eede5e1af993c39" major = 1 minor = 1 bugfix = 0 release = True timestamp = datetime.datetime(2016, 4, 30, 18, 32, 9, 694914) debug = False try: from ._compiler import compiler except ImportError: compiler = "unknown" try: from .cython_version import cython_version except ImportError: cython_version = "unknown" radio_beam-0.3.2/astropy_helpers/astropy_helpers/version_helpers.py0000644000077000000240000002346313516112504026054 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Utilities for generating the version string for Astropy (or an affiliated package) and the version.py module, which contains version info for the package. Within the generated astropy.version module, the `major`, `minor`, and `bugfix` variables hold the respective parts of the version number (bugfix is '0' if absent). The `release` variable is True if this is a release, and False if this is a development version of astropy. For the actual version string, use:: from astropy.version import version or:: from astropy import __version__ """ from __future__ import division import datetime import imp import os import pkgutil import sys import time from distutils import log import pkg_resources from . import git_helpers from .distutils_helpers import is_distutils_display_option from .utils import invalidate_caches PY3 = sys.version_info[0] == 3 def _version_split(version): """ Split a version string into major, minor, and bugfix numbers. If any of those numbers are missing the default is zero. Any pre/post release modifiers are ignored. Examples ======== >>> _version_split('1.2.3') (1, 2, 3) >>> _version_split('1.2') (1, 2, 0) >>> _version_split('1.2rc1') (1, 2, 0) >>> _version_split('1') (1, 0, 0) >>> _version_split('') (0, 0, 0) """ parsed_version = pkg_resources.parse_version(version) if hasattr(parsed_version, 'base_version'): # New version parsing for setuptools >= 8.0 if parsed_version.base_version: parts = [int(part) for part in parsed_version.base_version.split('.')] else: parts = [] else: parts = [] for part in parsed_version: if part.startswith('*'): # Ignore any .dev, a, b, rc, etc. break parts.append(int(part)) if len(parts) < 3: parts += [0] * (3 - len(parts)) # In principle a version could have more parts (like 1.2.3.4) but we only # support .. return tuple(parts[:3]) # This is used by setup.py to create a new version.py - see that file for # details. Note that the imports have to be absolute, since this is also used # by affiliated packages. _FROZEN_VERSION_PY_TEMPLATE = """ # Autogenerated by {packagetitle}'s setup.py on {timestamp!s} UTC from __future__ import unicode_literals import datetime {header} major = {major} minor = {minor} bugfix = {bugfix} release = {rel} timestamp = {timestamp!r} debug = {debug} astropy_helpers_version = "{ahver}" try: from ._compiler import compiler except ImportError: compiler = "unknown" try: from .cython_version import cython_version except ImportError: cython_version = "unknown" """[1:] _FROZEN_VERSION_PY_WITH_GIT_HEADER = """ {git_helpers} _packagename = "{packagename}" _last_generated_version = "{verstr}" _last_githash = "{githash}" # Determine where the source code for this module # lives. If __file__ is not a filesystem path then # it is assumed not to live in a git repo at all. if _get_repo_path(__file__, levels=len(_packagename.split('.'))): version = update_git_devstr(_last_generated_version, path=__file__) githash = get_git_devstr(sha=True, show_warning=False, path=__file__) or _last_githash else: # The file does not appear to live in a git repo so don't bother # invoking git version = _last_generated_version githash = _last_githash """[1:] _FROZEN_VERSION_PY_STATIC_HEADER = """ version = "{verstr}" githash = "{githash}" """[1:] def _get_version_py_str(packagename, version, githash, release, debug, uses_git=True): try: from astropy_helpers import __version__ as ahver except ImportError: ahver = "unknown" epoch = int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) timestamp = datetime.datetime.utcfromtimestamp(epoch) major, minor, bugfix = _version_split(version) if packagename.lower() == 'astropy': packagetitle = 'Astropy' else: packagetitle = 'Astropy-affiliated package ' + packagename header = '' if uses_git: header = _generate_git_header(packagename, version, githash) elif not githash: # _generate_git_header will already generate a new git has for us, but # for creating a new version.py for a release (even if uses_git=False) # we still need to get the githash to include in the version.py # See https://github.com/astropy/astropy-helpers/issues/141 githash = git_helpers.get_git_devstr(sha=True, show_warning=True) if not header: # If _generate_git_header fails it returns an empty string header = _FROZEN_VERSION_PY_STATIC_HEADER.format(verstr=version, githash=githash) return _FROZEN_VERSION_PY_TEMPLATE.format(packagetitle=packagetitle, timestamp=timestamp, header=header, major=major, minor=minor, bugfix=bugfix, ahver=ahver, rel=release, debug=debug) def _generate_git_header(packagename, version, githash): """ Generates a header to the version.py module that includes utilities for probing the git repository for updates (to the current git hash, etc.) These utilities should only be available in development versions, and not in release builds. If this fails for any reason an empty string is returned. """ loader = pkgutil.get_loader(git_helpers) source = loader.get_source(git_helpers.__name__) or '' source_lines = source.splitlines() if not source_lines: log.warn('Cannot get source code for astropy_helpers.git_helpers; ' 'git support disabled.') return '' idx = 0 for idx, line in enumerate(source_lines): if line.startswith('# BEGIN'): break git_helpers_py = '\n'.join(source_lines[idx + 1:]) if PY3: verstr = version else: # In Python 2 don't pass in a unicode string; otherwise verstr will # be represented with u'' syntax which breaks on Python 3.x with x # < 3. This is only an issue when developing on multiple Python # versions at once verstr = version.encode('utf8') new_githash = git_helpers.get_git_devstr(sha=True, show_warning=False) if new_githash: githash = new_githash return _FROZEN_VERSION_PY_WITH_GIT_HEADER.format( git_helpers=git_helpers_py, packagename=packagename, verstr=verstr, githash=githash) def generate_version_py(packagename, version, release=None, debug=None, uses_git=True, srcdir='.'): """Regenerate the version.py module if necessary.""" try: version_module = get_pkg_version_module(packagename) try: last_generated_version = version_module._last_generated_version except AttributeError: last_generated_version = version_module.version try: last_githash = version_module._last_githash except AttributeError: last_githash = version_module.githash current_release = version_module.release current_debug = version_module.debug except ImportError: version_module = None last_generated_version = None last_githash = None current_release = None current_debug = None if release is None: # Keep whatever the current value is, if it exists release = bool(current_release) if debug is None: # Likewise, keep whatever the current value is, if it exists debug = bool(current_debug) package_srcdir = os.path.join(srcdir, *packagename.split('.')) version_py = os.path.join(package_srcdir, 'version.py') if (last_generated_version != version or current_release != release or current_debug != debug): if '-q' not in sys.argv and '--quiet' not in sys.argv: log.set_threshold(log.INFO) if is_distutils_display_option(): # Always silence unnecessary log messages when display options are # being used log.set_threshold(log.WARN) log.info('Freezing version number to {0}'.format(version_py)) with open(version_py, 'w') as f: # This overwrites the actual version.py f.write(_get_version_py_str(packagename, version, last_githash, release, debug, uses_git=uses_git)) invalidate_caches() if version_module: imp.reload(version_module) def get_pkg_version_module(packagename, fromlist=None): """Returns the package's .version module generated by `astropy_helpers.version_helpers.generate_version_py`. Raises an ImportError if the version module is not found. If ``fromlist`` is an iterable, return a tuple of the members of the version module corresponding to the member names given in ``fromlist``. Raises an `AttributeError` if any of these module members are not found. """ if not fromlist: # Due to a historical quirk of Python's import implementation, # __import__ will not return submodules of a package if 'fromlist' is # empty. # TODO: For Python 3.1 and up it may be preferable to use importlib # instead of the __import__ builtin return __import__(packagename + '.version', fromlist=['']) else: mod = __import__(packagename + '.version', fromlist=fromlist) return tuple(getattr(mod, member) for member in fromlist) radio_beam-0.3.2/astropy_helpers/astropy_helpers.egg-info/0000755000077000000240000000000013531324214023755 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/astropy_helpers.egg-info/PKG-INFO0000644000077000000240000000562612711231152025060 0ustar adamstaff00000000000000Metadata-Version: 1.1 Name: astropy-helpers Version: 1.1 Summary: Utilities for building and installing Astropy, Astropy affiliated packages, and their respective documentation. Home-page: http://astropy.org Author: The Astropy Developers Author-email: astropy.team@gmail.com License: BSD Download-URL: http://pypi.python.org/packages/source/a/astropy-helpers/astropy-helpers-1.1.tar.gz Description: astropy-helpers =============== This project provides a Python package, ``astropy_helpers``, which includes many build, installation, and documentation-related tools used by the Astropy project, but packaged separately for use by other projects that wish to leverage this work. The motivation behind this package and details of its implementation are in the accepted `Astropy Proposal for Enhancement (APE) 4 `_. ``astropy_helpers`` includes a special "bootstrap" module called ``ah_bootstrap.py`` which is intended to be used by a project's setup.py in order to ensure that the ``astropy_helpers`` package is available for build/installation. This is similar to the ``ez_setup.py`` module that is shipped with some projects to bootstrap `setuptools `_. As described in APE4, the version numbers for ``astropy_helpers`` follow the corresponding major/minor version of the `astropy core package `_, but with an independent sequence of micro (bugfix) version numbers. Hence, the initial release is 0.4, in parallel with Astropy v0.4, which will be the first version of Astropy to use ``astropy-helpers``. For examples of how to implement ``astropy-helpers`` in a project, see the ``setup.py`` and ``setup.cfg`` files of the `Affiliated package template `_. .. image:: https://travis-ci.org/astropy/astropy-helpers.png :target: https://travis-ci.org/astropy/astropy-helpers .. image:: https://coveralls.io/repos/astropy/astropy-helpers/badge.png :target: https://coveralls.io/r/astropy/astropy-helpers Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Framework :: Setuptools Plugin Classifier: Framework :: Sphinx :: Extension Classifier: Framework :: Sphinx :: Theme Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Build Tools Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Archiving :: Packaging radio_beam-0.3.2/astropy_helpers/astropy_helpers.egg-info/SOURCES.txt0000644000077000000240000000654012711231152025643 0ustar adamstaff00000000000000CHANGES.rst LICENSE.rst MANIFEST.in README.rst ah_bootstrap.py ez_setup.py setup.cfg setup.py astropy_helpers/__init__.py astropy_helpers/distutils_helpers.py astropy_helpers/git_helpers.py astropy_helpers/setup_helpers.py astropy_helpers/test_helpers.py astropy_helpers/utils.py astropy_helpers/version.py astropy_helpers/version_helpers.py astropy_helpers.egg-info/PKG-INFO astropy_helpers.egg-info/SOURCES.txt astropy_helpers.egg-info/dependency_links.txt astropy_helpers.egg-info/not-zip-safe astropy_helpers.egg-info/top_level.txt astropy_helpers/commands/__init__.py astropy_helpers/commands/_dummy.py astropy_helpers/commands/_test_compat.py astropy_helpers/commands/build_ext.py astropy_helpers/commands/build_py.py astropy_helpers/commands/build_sphinx.py astropy_helpers/commands/install.py astropy_helpers/commands/install_lib.py astropy_helpers/commands/register.py astropy_helpers/commands/setup_package.py astropy_helpers/commands/test.py astropy_helpers/commands/src/compiler.c astropy_helpers/compat/__init__.py astropy_helpers/compat/subprocess.py astropy_helpers/sphinx/__init__.py astropy_helpers/sphinx/conf.py astropy_helpers/sphinx/setup_package.py astropy_helpers/sphinx/ext/__init__.py astropy_helpers/sphinx/ext/astropyautosummary.py astropy_helpers/sphinx/ext/autodoc_enhancements.py astropy_helpers/sphinx/ext/automodapi.py astropy_helpers/sphinx/ext/automodsumm.py astropy_helpers/sphinx/ext/changelog_links.py astropy_helpers/sphinx/ext/comment_eater.py astropy_helpers/sphinx/ext/compiler_unparse.py astropy_helpers/sphinx/ext/docscrape.py astropy_helpers/sphinx/ext/docscrape_sphinx.py astropy_helpers/sphinx/ext/doctest.py astropy_helpers/sphinx/ext/edit_on_github.py astropy_helpers/sphinx/ext/numpydoc.py astropy_helpers/sphinx/ext/phantom_import.py astropy_helpers/sphinx/ext/smart_resolver.py astropy_helpers/sphinx/ext/tocdepthfix.py astropy_helpers/sphinx/ext/traitsdoc.py astropy_helpers/sphinx/ext/utils.py astropy_helpers/sphinx/ext/viewcode.py astropy_helpers/sphinx/ext/templates/autosummary_core/base.rst astropy_helpers/sphinx/ext/templates/autosummary_core/class.rst astropy_helpers/sphinx/ext/templates/autosummary_core/module.rst astropy_helpers/sphinx/ext/tests/__init__.py astropy_helpers/sphinx/ext/tests/test_autodoc_enhancements.py astropy_helpers/sphinx/ext/tests/test_automodapi.py astropy_helpers/sphinx/ext/tests/test_automodsumm.py astropy_helpers/sphinx/ext/tests/test_docscrape.py astropy_helpers/sphinx/ext/tests/test_utils.py astropy_helpers/sphinx/local/python3links.inv astropy_helpers/sphinx/themes/bootstrap-astropy/globaltoc.html astropy_helpers/sphinx/themes/bootstrap-astropy/layout.html astropy_helpers/sphinx/themes/bootstrap-astropy/localtoc.html astropy_helpers/sphinx/themes/bootstrap-astropy/searchbox.html astropy_helpers/sphinx/themes/bootstrap-astropy/theme.conf astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_linkout.svg astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_linkout_20.png astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_logo.ico astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_logo.svg astropy_helpers/sphinx/themes/bootstrap-astropy/static/astropy_logo_32.png astropy_helpers/sphinx/themes/bootstrap-astropy/static/bootstrap-astropy.css astropy_helpers/sphinx/themes/bootstrap-astropy/static/copybutton.js astropy_helpers/sphinx/themes/bootstrap-astropy/static/sidebar.jsradio_beam-0.3.2/astropy_helpers/astropy_helpers.egg-info/dependency_links.txt0000644000077000000240000000000112711231152030020 0ustar adamstaff00000000000000 radio_beam-0.3.2/astropy_helpers/astropy_helpers.egg-info/not-zip-safe0000644000077000000240000000000112711231152026200 0ustar adamstaff00000000000000 radio_beam-0.3.2/astropy_helpers/astropy_helpers.egg-info/top_level.txt0000644000077000000240000000002012711231152026474 0ustar adamstaff00000000000000astropy_helpers radio_beam-0.3.2/astropy_helpers/licenses/0000755000077000000240000000000013531324214020645 5ustar adamstaff00000000000000radio_beam-0.3.2/astropy_helpers/licenses/LICENSE_ASTROSCRAPPY.rst0000644000077000000240000000315413174167433024511 0ustar adamstaff00000000000000# The OpenMP helpers include code heavily adapted from astroscrappy, released # under the following license: # # Copyright (c) 2015, Curtis McCully # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this # list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # * Neither the name of the Astropy Team nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. radio_beam-0.3.2/astropy_helpers/licenses/LICENSE_COPYBUTTON.rst0000644000077000000240000000471112711231150024245 0ustar adamstaff00000000000000Copyright 2014 Python Software Foundation License: PSF PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- . 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. . 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. . 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. . 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. . 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. . 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. . 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. . 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. radio_beam-0.3.2/astropy_helpers/licenses/LICENSE_NUMPYDOC.rst0000644000077000000240000001350712711231150024000 0ustar adamstaff00000000000000------------------------------------------------------------------------------- The files - numpydoc.py - docscrape.py - docscrape_sphinx.py - phantom_import.py have the following license: Copyright (C) 2008 Stefan van der Walt , Pauli Virtanen Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The files - compiler_unparse.py - comment_eater.py - traitsdoc.py have the following license: This software is OSI Certified Open Source Software. OSI Certified is a certification mark of the Open Source Initiative. Copyright (c) 2006, Enthought, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Enthought, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The file - plot_directive.py originates from Matplotlib (http://matplotlib.sf.net/) which has the following license: Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved. 1. This LICENSE AGREEMENT is between John D. Hunter (“JDH”), and the Individual or Organization (“Licensee”) accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib 0.98.3 alone or in any derivative version, provided, however, that JDH’s License Agreement and JDH’s notice of copyright, i.e., “Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved” are retained in matplotlib 0.98.3 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 0.98.3 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib 0.98.3. 4. JDH is making matplotlib 0.98.3 available to Licensee on an “AS IS” basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB 0.98.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 0.98.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB 0.98.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib 0.98.3, Licensee agrees to be bound by the terms and conditions of this License Agreement. radio_beam-0.3.2/astropy_helpers/setup.cfg0000644000077000000240000000015313060356620020663 0ustar adamstaff00000000000000[tool:pytest] norecursedirs = .tox astropy_helpers/tests/package_template python_functions = test_ radio_beam-0.3.2/astropy_helpers/setup.py0000755000077000000240000000364013516112504020560 0ustar adamstaff00000000000000#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import ah_bootstrap import pkg_resources from setuptools import setup from astropy_helpers.setup_helpers import (register_commands, get_package_info, add_exclude_packages) from astropy_helpers.version_helpers import generate_version_py NAME = 'astropy_helpers' VERSION = '2.0.9' RELEASE = 'dev' not in VERSION generate_version_py(NAME, VERSION, RELEASE, False, uses_git=not RELEASE) # Use the updated version including the git rev count from astropy_helpers.version import version as VERSION add_exclude_packages(['astropy_helpers.tests']) cmdclass = register_commands(NAME, VERSION, RELEASE) # This package actually doesn't use the Astropy test command del cmdclass['test'] setup( name=pkg_resources.safe_name(NAME), # astropy_helpers -> astropy-helpers version=VERSION, description='Utilities for building and installing Astropy, Astropy ' 'affiliated packages, and their respective documentation.', author='The Astropy Developers', author_email='astropy.team@gmail.com', license='BSD', url=' https://github.com/astropy/astropy-helpers', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Framework :: Setuptools Plugin', 'Framework :: Sphinx :: Extension', 'Framework :: Sphinx :: Theme', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Archiving :: Packaging' ], cmdclass=cmdclass, zip_safe=False, **get_package_info() ) radio_beam-0.3.2/docs/0000755000077000000240000000000013531324214014545 5ustar adamstaff00000000000000radio_beam-0.3.2/docs/Makefile0000644000077000000240000001116412711230751016211 0ustar adamstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest #This is needed with git because git doesn't create a dir if it's empty $(shell [ -d "_static" ] || mkdir -p _static) help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR) -rm -rf api html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Astropy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Astropy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Astropy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Astropy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." radio_beam-0.3.2/docs/_templates/0000755000077000000240000000000013531324214016702 5ustar adamstaff00000000000000radio_beam-0.3.2/docs/_templates/autosummary/0000755000077000000240000000000013531324214021270 5ustar adamstaff00000000000000radio_beam-0.3.2/docs/_templates/autosummary/base.rst0000644000077000000240000000037212711230751022737 0ustar adamstaff00000000000000{% extends "autosummary_core/base.rst" %} {# The template this is inherited from is in astropy/sphinx/ext/templates/autosummary_core. If you want to modify this template, it is strongly recommended that you still inherit from the astropy template. #}radio_beam-0.3.2/docs/_templates/autosummary/class.rst0000644000077000000240000000037312711230751023133 0ustar adamstaff00000000000000{% extends "autosummary_core/class.rst" %} {# The template this is inherited from is in astropy/sphinx/ext/templates/autosummary_core. If you want to modify this template, it is strongly recommended that you still inherit from the astropy template. #}radio_beam-0.3.2/docs/_templates/autosummary/module.rst0000644000077000000240000000037412711230751023314 0ustar adamstaff00000000000000{% extends "autosummary_core/module.rst" %} {# The template this is inherited from is in astropy/sphinx/ext/templates/autosummary_core. If you want to modify this template, it is strongly recommended that you still inherit from the astropy template. #}radio_beam-0.3.2/docs/api.rst0000644000077000000240000000045013375416612016061 0ustar adamstaff00000000000000API Documentation ================= .. automodapi:: radio_beam :no-inheritance-diagram: :inherited-members: .. automodapi:: radio_beam.commonbeam :no-inheritance-diagram: :no-inherited-members: .. automodapi:: radio_beam.utils :no-inheritance-diagram: :no-inherited-members: radio_beam-0.3.2/docs/commonbeam.rst0000644000077000000240000001013213375416612017423 0ustar adamstaff00000000000000.. _com_beam: Finding the smallest common beam ================================ radio-beam implements an exact solution for sets of 2 beams and an approximate method---`the Khachiyan algorithm `_---for larger sets. The former case is straightforward to compute as the beams can be transformed into a space where the larger beam is circular to find the overlap area (`~radio_beam.commonbeam.common_2beams`). Our implementation borrows from the implementation in `CASA `_ (see `here `__). Note that CASA uses this method for sets of beams larger than 2 by iterating through the beams and comparing each beam to the largest beam from the previous iterations. However, this approach is not guaranteed to find the minimum enclosing beam. For sets of more than two beams, finding the smallest common beam is a convex optimization problem equivalent to finding the minimum enclosed ellipse for a set of ellipses centered on the origin (`Boyd & Vandenberghe `_, see `example `_ in Sec 8.4.1). To avoid having radio-beam depend on convex optimization libraries, we implement the Khachiyan algorithm as an approximate method for finding the minimum ellipse. This algorithm finds the minimum ellipse that encloses the convex hull of a set of points (`Khachiyan & Todd 1993 `_, `Todd & Yildirim 2005 `_). By sampling a points on the boundaries of the beams in the set, we create a set of points whose convex hull is used to find the common beam. The implementation in radio-beam is adapted from `a generalized python implementation `_ and `the original matlab version `_ written by Nima Moshtagh (see accompanying paper `here `__). Could not find common beam to deconvolve all beams ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You may encounter the error "Could not find common beam to deconvolve all beams." This occurs because the Khachiyan algorithm has converged to within the allowed tolerance with a solution marginally *smaller* than the enclosing ellipse. There are two ways to fix this issue: 1. **Changing the tolerance.** - The default tolerance for convergence of the Khachiyan algorithm (`~radio_beam.commonbeam.getMinVolEllipse`) is `tolerance=1e-5`. This tolerance can be changed in `~radio_beam.Beams.common_beam` by specifying a new tolerance. Convergence may be met by either increasing or decreasing the tolerance; it depends on having the algorithm not step within the minimum enclosing ellipse, leading to the error. Note that decreasing the tolerance by an order of magnitude will require an order of magnitude more iterations for the algorithm to converge. 2. **Changing epsilon** - A second parameter `epsilon` controls the points sampled at the edges of the beams in the set (`~radio_beam.commonbeam.ellipse_edges`), which are used in the Khachiyan algorithm. `epsilon` is the fraction beyond the true edge of the ellipse that points will be sampled at. For example, the default value of `epsilon=1e-3` will sample points 0.1% larger than the edge of the ellipse. Increasing `epsilon` ensures that a valid common beam can be found, avoiding the tolerance issue, but will result in overestimating the common beam area. For most radio data sets, where the beam is oversampled by :math:`\sim\3\mbox{--}5}` pixels, moderate increases in `epsilon` will increase the common beam area far less than a pixel area, making the overestimation negligible. We recommend testing different values of tolerance to find convergence, and if the error persists, to then slowly increase epsilon until a valid common beam is found. radio_beam-0.3.2/docs/conf.py0000644000077000000240000001422013516112474016051 0ustar adamstaff00000000000000# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # # Astropy documentation build configuration file. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this file. # # All configuration values have a default. Some values are defined in # the global Astropy configuration which is loaded here before anything else. # See astropy.sphinx.conf for which values are set there. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('..')) # IMPORTANT: the above commented section was generated by sphinx-quickstart, but # is *NOT* appropriate for astropy or Astropy affiliated packages. It is left # commented out with this explanation to make it clear why this should not be # done. If the sys.path entry above is added, when the astropy.sphinx.conf # import occurs, it will import the *source* version of astropy instead of the # version installed (if invoked as "make html" or directly with sphinx), or the # version in the build directory (if "python setup.py build_sphinx" is used). # Thus, any C-extensions that are needed to build the documentation will *not* # be accessible, and the documentation will not build correctly. import datetime import os import sys try: import astropy_helpers except ImportError: # Building from inside the docs/ directory? if os.path.basename(os.getcwd()) == 'docs': a_h_path = os.path.abspath(os.path.join('..', 'astropy_helpers')) if os.path.isdir(a_h_path): sys.path.insert(1, a_h_path) # Load all of the global Astropy configuration from astropy_helpers.sphinx.conf import * # Get configuration information from setup.cfg try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser conf = ConfigParser() conf.read([os.path.join(os.path.dirname(__file__), '..', 'setup.cfg')]) setup_cfg = dict(conf.items('metadata')) # -- General configuration ---------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.2' # To perform a Sphinx version check that needs to be more specific than # major.minor, call `check_sphinx_version("x.y.z")` here. # check_sphinx_version("1.2.1") # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns.append('_templates') # This is added to the end of RST files - a good place to put substitutions to # be used globally. rst_epilog += """ """ # -- Project information ------------------------------------------------------ # This does not *have* to match the package name, but typically does project = setup_cfg['package_name'] author = setup_cfg['author'] copyright = '{0}, {1}'.format( datetime.datetime.now().year, setup_cfg['author']) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. PACKAGENAME = setup_cfg['package_name'].replace("-","_") __import__(PACKAGENAME) package = sys.modules[PACKAGENAME] # The short X.Y version. version = package.__version__.split('-', 1)[0] # The full version, including alpha/beta/rc tags. release = package.__version__ # -- Options for HTML output --------------------------------------------------- # A NOTE ON HTML THEMES # The global astropy configuration uses a custom theme, 'bootstrap-astropy', # which is installed along with astropy. A different theme can be used or # the options for this theme can be modified by overriding some of the # variables set in the global configuration. The variables set in the # global configuration are listed below, commented out. # Add any paths that contain custom themes here, relative to this directory. # To use a different custom theme, add the directory containing the theme. #html_theme_path = [] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. To override the custom theme, set this to the # name of a builtin theme or the name of a custom theme in html_theme_path. #html_theme = None # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = '' # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '' # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". html_title = '{0} v{1}'.format(project, release) # Output file base name for HTML help builder. htmlhelp_basename = project + 'doc' # -- Options for LaTeX output -------------------------------------------------- # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [('index', project + '.tex', project + u' Documentation', author, 'manual')] # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [('index', project.lower(), project + u' Documentation', [author], 1)] ## -- Options for the edit_on_github extension ---------------------------------------- if eval(setup_cfg.get('edit_on_github')): extensions += ['astropy_helpers.sphinx.ext.edit_on_github'] versionmod = __import__(PACKAGENAME + '.version') edit_on_github_project = setup_cfg['github_project'] if versionmod.version.release: edit_on_github_branch = "v" + versionmod.version.version else: edit_on_github_branch = "master" edit_on_github_source_root = "" edit_on_github_doc_root = "docs" radio_beam-0.3.2/docs/convolution_kernels.rst0000644000077000000240000000521013375416612021411 0ustar adamstaff00000000000000.. _convkernels: Making convolution kernels ========================== `~radio_beam.Beam` can produce two types of kernels: a Gaussian (`~radio_beam.Beam.as_kernel`) and a top-hat (`~radio_beam.Beam.as_tophat_kernel`). As an example, consider the elliptical beam:: >>> import astropy.units as u >>> from radio_beam import Beam >>> my_beam = Beam(3*u.arcsec, 1.5*u.arcsec, 60*u.deg) Gaussian ^^^^^^^^ `~radio_beam.Beam.as_kernel` will return an elliptical Gaussian kernel given the angular size of a pixel:: >>> pix_scale = 0.5 * u.arcsec >>> gauss_kern = my_beam.as_kernel(pix_scale) `gauss_kern` will be a `~radio_beam.beam.EllipticalGaussian2DKernel` object and has the same methods, attributes and keyword arguments as `Kernel2D `__ in astropy's convolution package. These keyword arguments can be passed to `~radio_beam.Beam.as_kernel`. See the `astropy documentation `_ for more information on convolution kernels. Top-Hat ^^^^^^^ `~radio_beam.Beam.as_tophat_kernel` returns an elliptical top-hat kernel scales to have the same area as a Gaussian kernel within the FWHM. Similar to the Gaussian kernel, only the pixel scale needs to be given:: >>> tophat_kern = my_beam.as_tophat_kernel(pix_scale) `tophat_kern` is a `~radio_beam.beam.EllipticalTophat2DKernel` object, also derived from `Kernel2D `__ in astropy's convolution package. Keyword arguments can be passed to `~radio_beam.Beam.as_tophat_kernel`. The values in the kernel are normalized to unity, and it is suitable for convolution. However, the top-hat kernel is also useful for masking purposes, in which case a boolean version of the kernel is useful. To make a boolean version, we need to access the array in the kernel object and look for non-zero values:: >>> tophat_kern_bool = tophat_kern.array > 0 `tophat_kern_bool` is suitable for use with morphological operations, such as those in `scipy.ndimage `_. Convolution kernels from multiple beams ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From a `~radio_beam.Beams` object, a convolution kernel can be made for each beam in the set by slicing:: >>> from radio_beam import Beams >>> from astropy.io import fits >>> bin_hdu = fits.open('file.fits')[1] # doctest: +SKIP >>> beams = Beams.from_fits_bintable(bin_hdu) # doctest: +SKIP >>> beams[0].as_kernel(pix_scale) # doctest: +SKIP radio_beam-0.3.2/docs/index.rst0000644000077000000240000000436713375416612016432 0ustar adamstaff00000000000000Radio Beam ========== A tool for manipulating and utilizing two dimensional gaussian beams within the `astropy `__ framework. Examples -------- Read a beam from a fits header:: >>> from radio_beam import Beam >>> from astropy.io import fits >>> header = fits.getheader('file.fits') # doctest: +SKIP >>> my_beam = Beam.from_fits_header(header) # doctest: +SKIP >>> print(my_beam) # doctest: +SKIP Beam: BMAJ=0.038652855902928 arcsec BMIN=0.032841067761183604 arcsec BPA=32.29655838013 deg Create a beam from scratch:: >>> from astropy import units as u >>> my_beam = Beam(0.5*u.arcsec) Use a beam for Jy -> K conversion:: >>> (1*u.Jy).to(u.K, u.brightness_temperature(my_beam, 25*u.GHz)) # doctest: +FLOAT_CMP Convolve with another beam:: >>> my_asymmetric_beam = Beam(0.75*u.arcsec, 0.25*u.arcsec, 0*u.deg) >>> my_other_asymmetric_beam = Beam(0.75*u.arcsec, 0.25*u.arcsec, 90*u.deg) >>> my_asymmetric_beam.convolve(my_other_asymmetric_beam) # doctest: +SKIP Beam: BMAJ=0.790569415042 arcsec BMIN=0.790569415042 arcsec BPA=45.0 deg Deconvolve another beam:: >>> my_big_beam = Beam(1.0*u.arcsec, 1.0*u.arcsec, 0*u.deg) >>> my_little_beam = Beam(0.5*u.arcsec, 0.5*u.arcsec, 0*u.deg) >>> my_big_beam.deconvolve(my_little_beam) # doctest: +SKIP Beam: BMAJ=0.866025403784 arcsec BMIN=0.866025403784 arcsec BPA=0.0 deg Read a table of beams:: >>> from radio_beam import Beams >>> from astropy.io import fits >>> bin_hdu = fits.open('file.fits')[1] # doctest: +SKIP >>> beams = Beams.from_fits_bintable(bin_hdu) # doctest: +SKIP Create a table of beams:: >>> my_beams = Beams([1.5, 1.3] * u.arcsec, [1., 1.2] * u.arcsec, [0, 50] * u.deg) Find the largest beam in the set:: >>> my_beams.largest_beam() Beam: BMAJ=1.3 arcsec BMIN=1.2 arcsec BPA=50.0 deg Find the smallest common beam for the set (see :ref:`here ` for more on common beams):: >>> my_beams.common_beam() # doctest: +SKIP Beam: BMAJ=1.50671729431 arcsec BMIN=1.25695643792 arcsec BPA=6.69089813778 deg Getting started ^^^^^^^^^^^^^^^ .. toctree:: :maxdepth: 2 install.rst commonbeam.rst convolution_kernels.rst api.rst radio_beam-0.3.2/docs/install.rst0000644000077000000240000000347313516112474016762 0ustar adamstaff00000000000000Installing ``spectral-cube`` ============================ Requirements ------------ This package has the following dependencies: * `Python `_ 2.7 or later (Python 3.x is supported) * `Numpy `_ 1.8 or later * `Astropy `__ 1.0 or later * `six `__ Installation ------------ To install the latest stable release, you can type:: pip install radio-beam or you can download the latest tar file from `PyPI `_ and install it using:: python setup.py install Developer version ----------------- If you want to install the latest developer version of the spectral cube code, you can do so from the git repository:: git clone https://github.com/radio-astro-tools/radio-beam.git cd radio-beam python setup.py install You may need to add the ``--user`` option to the last line `if you do not have root access `_. You can also install the latest developer version in a single line with pip:: pip install git+https://github.com/radio-astro-tools/radio-beam.git Installing into CASA -------------------- Installing packages in CASA is fairly straightforward. The process is described `here `_. In short, you can do the following: First, we need to make sure `pip `__ is installed. Start up CASA as normal, and type:: CASA <1>: from setuptools.command import easy_install CASA <2>: easy_install.main(['--user', 'pip']) Now, quit CASA and re-open it, then type the following to install ``radio-beam``:: CASA <1>: import pip CASA <2>: pip.main(['install', 'radio-beam', '--user']) radio_beam-0.3.2/docs/make.bat0000644000077000000240000001064112711230751016155 0ustar adamstaff00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Astropy.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Astropy.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end radio_beam-0.3.2/docs/nitpick-exceptions0000644000077000000240000000005613375416612020323 0ustar adamstaff00000000000000py:obj radio_beam,commonbeam.transform_ellipseradio_beam-0.3.2/docs/rtd-pip-requirements0000644000077000000240000000022413375320132020567 0ustar adamstaff00000000000000-e git+http://github.com/astropy/astropy-helpers.git#egg=astropy_helpers numpy=1.15 Cython -e git+http://github.com/astropy/astropy.git#egg=astropy radio_beam-0.3.2/radio_beam/0000755000077000000240000000000013531324214015677 5ustar adamstaff00000000000000radio_beam-0.3.2/radio_beam/__init__.py0000644000077000000240000000115613174212732020017 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This is an Astropy affiliated package. """ # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # For egg_info test builds to pass, put package imports here. if not _ASTROPY_SETUP_: from .beam import Beam, EllipticalGaussian2DKernel, \ EllipticalTophat2DKernel from .multiple_beams import Beams radio_beam-0.3.2/radio_beam/_astropy_init.py0000644000077000000240000001223112711230751021134 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst __all__ = ['__version__', '__githash__', 'test'] # this indicates whether or not we are in the package's setup.py try: _ASTROPY_SETUP_ except NameError: from sys import version_info if version_info[0] >= 3: import builtins else: import __builtin__ as builtins builtins._ASTROPY_SETUP_ = False try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' # set up the test command def _get_test_runner(): import os from astropy.tests.helper import TestRunner return TestRunner(os.path.dirname(__file__)) def test(package=None, test_path=None, args=None, plugins=None, verbose=False, pastebin=None, remote_data=False, pep8=False, pdb=False, coverage=False, open_files=False, **kwargs): """ Run the tests using `py.test `__. A proper set of arguments is constructed and passed to `pytest.main`_. .. _py.test: http://pytest.org/latest/ .. _pytest.main: http://pytest.org/latest/builtin.html#pytest.main Parameters ---------- package : str, optional 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 : 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. args : str, optional Additional arguments to be passed to pytest.main_ in the ``args`` keyword argument. plugins : list, optional Plugins to be passed to pytest.main_ in the ``plugins`` keyword argument. verbose : bool, optional Convenience option to turn on verbose output from py.test_. Passing True is the same as specifying ``'-v'`` in ``args``. 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. remote_data : bool, optional Controls whether to run tests marked with @remote_data. These tests use online data and are not run by default. Set to True to run these tests. pep8 : bool, optional Turn on PEP8 checking via the `pytest-pep8 plugin `_ and disable normal tests. Same as specifying ``'--pep8 -k pep8'`` in ``args``. pdb : bool, optional Turn on PDB post-mortem analysis for failing tests. Same as specifying ``'--pdb'`` in ``args``. coverage : bool, optional Generate a test coverage report. The result will be placed in the directory htmlcov. open_files : bool, optional Fail when any tests leave files open. Off by default, because this adds extra run time to the test suite. Requires the `psutil `_ package. 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 installed. Only available when using Astropy 0.3 or later. kwargs Any additional keywords passed into this function will be passed on to the astropy test runner. This allows use of test-related functionality implemented in later versions of astropy without explicitly updating the package template. """ test_runner = _get_test_runner() return test_runner.run_tests( package=package, test_path=test_path, args=args, plugins=plugins, verbose=verbose, pastebin=pastebin, remote_data=remote_data, pep8=pep8, pdb=pdb, coverage=coverage, open_files=open_files, **kwargs) if not _ASTROPY_SETUP_: import os from warnings import warn from astropy import config # add these here so we only need to cleanup the namespace at the end config_dir = None if not os.environ.get('ASTROPY_SKIP_CONFIG_UPDATE', False): config_dir = os.path.dirname(__file__) config_template = os.path.join(config_dir, __package__ + ".cfg") if os.path.isfile(config_template): try: config.configuration.update_default_config( __package__, config_dir, version=__version__) except TypeError as orig_error: try: config.configuration.update_default_config( __package__, config_dir) except config.configuration.ConfigurationDefaultMissingError as e: wmsg = (e.args[0] + " Cannot install default profile. If you are " "importing from source, this is expected.") warn(config.configuration.ConfigurationDefaultMissingWarning(wmsg)) del e except: raise orig_error radio_beam-0.3.2/radio_beam/beam.py0000644000077000000240000006435213520605403017167 0ustar adamstaff00000000000000import six from astropy import units as u from astropy.io import fits from astropy import constants from astropy import wcs import numpy as np import warnings # Imports for the custom kernels from astropy.modeling.models import Ellipse2D, Gaussian2D from astropy.convolution import Kernel2D from astropy.convolution.kernels import _round_up_to_odd_integer from .utils import deconvolve, convolve, RadioBeamDeprecationWarning # Conversion between a twod Gaussian FWHM**2 and effective area FWHM_TO_AREA = 2*np.pi/(8*np.log(2)) SIGMA_TO_FWHM = np.sqrt(8*np.log(2)) class NoBeamException(Exception): pass def _to_area(major,minor): return (major * minor * FWHM_TO_AREA).to(u.sr) unit_format = {u.deg: r'\\circ', u.arcsec: "''", u.arcmin: "'"} class Beam(u.Quantity): """ An object to handle single radio beams. """ def __new__(cls, major=None, minor=None, pa=None, area=None, default_unit=u.arcsec, meta=None): """ Create a new Gaussian beam Parameters ---------- major : :class:`~astropy.units.Quantity` with angular equivalency The FWHM major axis minor : :class:`~astropy.units.Quantity` with angular equivalency The FWHM minor axis pa : :class:`~astropy.units.Quantity` with angular equivalency The beam position angle area : :class:`~astropy.units.Quantity` with steradian equivalency The area of the beam. This is an alternative to specifying the major/minor/PA, and will create those values assuming a circular Gaussian beam. default_unit : :class:`~astropy.units.Unit` The unit to impose on major, minor if they are specified as floats """ # improve to some kwargs magic later # error checking # ... given an area make a round beam assuming it is Gaussian if area is not None: if major is not None: raise ValueError("Can only specify one of {major,minor,pa} " "and {area}") rad = np.sqrt(area/(2*np.pi)) * u.deg major = rad * SIGMA_TO_FWHM minor = rad * SIGMA_TO_FWHM pa = 0.0 * u.deg # give specified values priority if major is not None: if u.deg.is_equivalent(major): major = major else: warnings.warn("Assuming major axis has been specified in degrees") major = major * u.deg if minor is not None: if u.deg.is_equivalent(minor): minor = minor else: warnings.warn("Assuming minor axis has been specified in degrees") minor = minor * u.deg if pa is not None: if u.deg.is_equivalent(pa): pa = pa else: warnings.warn("Assuming position angle has been specified in degrees") pa = pa * u.deg else: pa = 0.0 * u.deg # some sensible defaults if minor is None: minor = major if minor > major: raise ValueError("Minor axis greater than major axis.") self = super(Beam, cls).__new__(cls, _to_area(major,minor).value, u.sr) self._major = major self._minor = minor self._pa = pa self.default_unit = default_unit if meta is None: self.meta = {} elif isinstance(meta, dict): self.meta = meta else: raise TypeError("metadata must be a dictionary") return self @classmethod def from_fits_bintable(cls, bintable, tolerance=0.01): """ Instantiate a single beam from a bintable from a CASA-produced image HDU. The beams in the BinTableHDU will be averaged to form a single beam. Parameters ---------- bintable : fits.BinTableHDU The table data containing the beam information tolerance : float The fractional tolerance on the beam size to include when averaging to a single beam Returns ------- beam : Beam A new beam object that is the average of the table beams """ from astropy.stats import circmean bmaj = bintable.data['BMAJ'] bmin = bintable.data['BMIN'] bpa = bintable.data['BPA'] if np.any(np.isnan(bmaj) | np.isnan(bmin) | np.isnan(bpa)): raise ValueError("NaN beam encountered.") for par in (bmin,bmaj): par_mean = par.mean() if (par.max() > par_mean*(1+tolerance)) or (par.min() restoration: 1.34841 by 0.830715 (arcsec) # at pa 82.8827 (deg) casaline = None for line in hdr['HISTORY']: if ('restoration' in line) and ('arcsec' in line): casaline = line #assert precedence for CASA style over AIPS # this is a dubious choice if casaline is not None: bmaj = float(casaline.split()[2]) * u.arcsec bmin = float(casaline.split()[4]) * u.arcsec bpa = float(casaline.split()[8]) * u.deg return cls(major=bmaj, minor=bmin, pa=bpa) elif aipsline is not None: bmaj = float(aipsline.split()[3]) * u.deg bmin = float(aipsline.split()[5]) * u.deg bpa = float(aipsline.split()[7]) * u.deg return cls(major=bmaj, minor=bmin, pa=bpa) else: return None @classmethod def from_casa_image(cls, imagename): ''' Instantiate beam from a CASA image. ** Must be run in a CASA environment! ** Parameters ---------- imagename : str Name of CASA image. ''' try: import casac except ImportError: raise ImportError("Could not import CASA (casac) and therefore" " cannot read CASA .image files") ia.open(imagename) beam_props = ia.restoringbeam() ia.close() beam_keys = ["major", "minor", "positionangle"] if not all([True for key in beam_keys if key in beam_props]): raise ValueError("The image does not contain complete beam " "information. Check the output of " "ia.restoringbeam().") major = beam_props["major"]["value"] * \ u.Unit(beam_props["major"]["unit"]) minor = beam_props["minor"]["value"] * \ u.Unit(beam_props["minor"]["unit"]) pa = beam_props["positionangle"]["value"] * \ u.Unit(beam_props["positionangle"]["unit"]) return cls(major=major, minor=minor, pa=pa) def attach_to_header(self, header, copy=True): ''' Attach the beam information to the provided header. Parameters ---------- header : astropy.io.fits.header.Header Header to add/update beam info. copy : bool, optional Returns a copy of the inputted header with the beam information. Returns ------- copy_header : astropy.io.fits.header.Header Copy of the input header with the updated beam info when `copy=True`. ''' if copy: header = header.copy() header.update(self.to_header_keywords()) return header def __repr__(self): return "Beam: BMAJ={0} BMIN={1} BPA={2}".format(self.major.to(self.default_unit),self.minor.to(self.default_unit),self.pa.to(u.deg)) def __repr_html__(self): return "Beam: BMAJ={0} BMIN={1} BPA={2}".format(self.major.to(self.default_unit),self.minor.to(self.default_unit),self.pa.to(u.deg)) def _repr_latex_(self): return "Beam: BMAJ=${0}^{{{fmt}}}$ BMIN=${1}^{{{fmt}}}$ BPA=${2}^\\circ$".format(self.major.to(self.default_unit).value, self.minor.to(self.default_unit).value, self.pa.to(u.deg).value, fmt = unit_format[self.default_unit]) def __str__(self): return self.__repr__() def convolve(self, other): """ Convolve one beam with another. Parameters ---------- other : `Beam` The beam to convolve with Returns ------- new_beam : `Beam` The convolved Beam """ new_major, new_minor, new_pa = convolve(self, other) return Beam(major=new_major, minor=new_minor, pa=new_pa) def __mul__(self, other): return self.convolve(other) # Does division do the same? Or what? Doesn't have to be defined. def __sub__(self, other): warnings.warn("Subtraction-as-deconvolution is deprecated. " "Use division instead.", RadioBeamDeprecationWarning) return self.deconvolve(other) def __truediv__(self, other): return self.deconvolve(other) def deconvolve(self, other, failure_returns_pointlike=False): """ Deconvolve a beam from another Parameters ---------- other : `Beam` The beam to deconvolve from this beam failure_returns_pointlike : bool Option to return a pointlike beam (i.e., one with major=minor=0) if the second beam is larger than the first. Otherwise, a ValueError will be raised Returns ------- new_beam : `Beam` The convolved Beam Raises ------ failure : ValueError If the second beam is larger than the first, the default behavior is to raise an exception. This can be overridden with failure_returns_pointlike """ new_major, new_minor, new_pa = \ deconvolve(self, other, failure_returns_pointlike=failure_returns_pointlike) return Beam(major=new_major, minor=new_minor, pa=new_pa) def __eq__(self, other): # Catch floating point issues atol_deg = 1e-12 * u.deg this_pa = self.pa.to(u.deg) % (180.0 * u.deg) other_pa = other.pa.to(u.deg) % (180.0 * u.deg) if self.iscircular(): equal_pa = True else: equal_pa = True if np.abs(this_pa - other_pa) < atol_deg else False equal_maj = np.abs(self.major - other.major) < atol_deg equal_min = np.abs(self.minor - other.minor) < atol_deg if equal_maj and equal_min and equal_pa: return True else: return False def __ne__(self, other): return not self.__eq__(other) # Is it astropy convention to access properties through methods? @property def sr(self): return _to_area(self.major,self.minor) @property def major(self): """ Beam FWHM Major Axis """ return self._major @property def minor(self): """ Beam FWHM Minor Axis """ return self._minor @property def pa(self): return self._pa @property def isfinite(self): return ((self.major > 0) & (self.minor > 0) & np.isfinite(self.major) & np.isfinite(self.minor) & np.isfinite(self.pa)) def iscircular(self, rtol=1e-6): frac_diff = (self.major - self.minor).to(u.deg) / self.major.to(u.deg) return frac_diff <= rtol def beam_projected_area(self, distance): """ Return the beam area in pc^2 (or equivalent) given a distance """ return self.sr*(distance**2)/u.sr def jtok_equiv(self, freq): ''' Return conversion function between Jy/beam to K at the specified frequency. The function can be used with the usual astropy.units conversion: >>> beam = Beam.from_fits_header("header.fits") # doctest: +SKIP >>> (1.0*u.Jy).to(u.K, beam.jtok_equiv(1.4*u.GHz)) # doctest: +SKIP Parameters ---------- freq : astropy.units.quantity.Quantity Frequency to calculate conversion. Returns ------- u.brightness_temperature ''' if not isinstance(freq, u.quantity.Quantity): raise TypeError("freq must be a Quantity object. " "Try 'freq*u.Hz' or another equivalent unit.") try: return u.brightness_temperature(beam_area=self.sr, frequency=freq) except TypeError: # old astropy used ordered arguments return u.brightness_temperature(self.sr, freq) def jtok(self, freq, value=1.0*u.Jy): """ Return the conversion for the given value between Jy/beam to K at the specified frequency. Unlike :meth:`jtok_equiv`, the output is the numerical value that converts the units, without any attached unit. Parameters ---------- freq : astropy.units.quantity.Quantity Frequency to calculate conversion. value : astropy.units.quantity.Quantity Value (in Jy or an equivalent unit) to convert to K. Returns ------- value : float Value converted to K. """ return value.to(u.K, self.jtok_equiv(freq)) def ellipse_to_plot(self, xcen, ycen, pixscale): """ Return a matplotlib ellipse for plotting Parameters ---------- xcen : int Center pixel in the x-direction. ycen : int Center pixel in the y-direction. pixscale : `~astropy.units.Quantity` Conversion from degrees to pixels. Returns ------- ~matplotlib.patches.Ellipse Ellipse patch object centered on the given pixel coordinates. """ from matplotlib.patches import Ellipse return Ellipse((xcen, ycen), width=(self.major.to(u.deg) / pixscale).to(u.dimensionless_unscaled).value, height=(self.minor.to(u.deg) / pixscale).to(u.dimensionless_unscaled).value, # PA is 90 deg offset from x-y axes by convention # (it is angle from NCP) angle=(self.pa+90*u.deg).to(u.deg).value) def as_kernel(self, pixscale, **kwargs): """ Returns an elliptical Gaussian kernel of the beam. .. warning:: This method is not aware of any misalignment between pixel and world coordinates. Parameters ---------- pixscale : `~astropy.units.Quantity` Conversion from angular to pixel size. kwargs : passed to EllipticalGaussian2DKernel """ # do something here involving matrices # need to rotate the kernel into the wcs pixel space, kinda... # at the least, need to rescale the kernel axes into pixels stddev_maj = (self.major.to(u.deg)/(pixscale.to(u.deg) * SIGMA_TO_FWHM)).decompose() stddev_min = (self.minor.to(u.deg)/(pixscale.to(u.deg) * SIGMA_TO_FWHM)).decompose() # position angle is defined as CCW from north # "angle" is conventionally defined as CCW from "west". # Therefore, add 90 degrees angle = (90*u.deg+self.pa).to(u.radian).value, return EllipticalGaussian2DKernel(stddev_maj.value, stddev_min.value, angle, **kwargs) def as_tophat_kernel(self, pixscale, **kwargs): ''' Returns an elliptical Tophat kernel of the beam. The area has been scaled to match the 2D Gaussian area: .. math:: \\begin{array}{ll} A_{\\mathrm{Gauss}} = 2\\pi\\sigma_{\\mathrm{Gauss}}^{2} A_{\\mathrm{Tophat}} = \\pi\\sigma_{\\mathrm{Tophat}}^{2} \\sigma_{\\mathrm{Tophat}} = \\sqrt{2}\\sigma_{\\mathrm{Gauss}} \\end{array} .. warning:: This method is not aware of any misalignment between pixel and world coordinates. Parameters ---------- pixscale : float deg -> pixels **kwargs : passed to EllipticalTophat2DKernel ''' # Based on Gaussian to Tophat area conversion # A_gaussian = 2 * pi * sigma^2 / (sqrt(8*log(2))^2 # A_tophat = pi * r^2 # pi r^2 = 2 * pi * sigma^2 / (sqrt(8*log(2))^2 # r = sqrt(2)/sqrt(8*log(2)) * sigma gauss_to_top = np.sqrt(2) maj_eff = gauss_to_top * self.major.to(u.deg) / \ (pixscale * SIGMA_TO_FWHM) min_eff = gauss_to_top * self.minor.to(u.deg) / \ (pixscale * SIGMA_TO_FWHM) # position angle is defined as CCW from north # "angle" is conventionally defined as CCW from "west". # Therefore, add 90 degrees angle = (90*u.deg+self.pa).to(u.radian).value, return EllipticalTophat2DKernel(maj_eff.value, min_eff.value, angle, **kwargs) def to_header_keywords(self): return {'BMAJ': self.major.to(u.deg).value, 'BMIN': self.minor.to(u.deg).value, 'BPA': self.pa.to(u.deg).value, } # Beam.__doc__ = Beam.__doc__ + Beam.__new__.__doc__ def mywcs_to_platescale(mywcs): pix_area = wcs.utils.proj_plane_pixel_area(mywcs) return pix_area**0.5 class EllipticalGaussian2DKernel(Kernel2D): """ 2D Elliptical Gaussian filter kernel. The Gaussian filter is a filter with great smoothing properties. It is isotropic and does not produce artifacts. Parameters ---------- stddev_maj : float Standard deviation of the Gaussian kernel in direction 1 stddev_min : float Standard deviation of the Gaussian kernel in direction 1 position_angle : float Position angle of the elliptical gaussian x_size : odd int, optional Size in x direction of the kernel array. Default = support_scaling * stddev. y_size : odd int, optional Size in y direction of the kernel array. Default = support_scaling * stddev. support_scaling : int The amount to scale the stddev to determine the size of the kernel mode : str, optional One of the following discretization modes: * 'center' (default) Discretize model by taking the value at the center of the bin. * 'linear_interp' Discretize model by performing a bilinear interpolation between the values at the corners of the bin. * 'oversample' Discretize model by taking the average on an oversampled grid. * 'integrate' Discretize model by integrating the model over the bin. factor : number, optional Factor of oversampling. Default factor = 10. See Also -------- Box2DKernel, Tophat2DKernel, MexicanHat2DKernel, Ring2DKernel, TrapezoidDisk2DKernel, AiryDisk2DKernel, Gaussian2DKernel, EllipticalTophat2DKernel Examples -------- Kernel response: .. plot:: :include-source: import matplotlib.pyplot as plt from radio_beam import EllipticalGaussian2DKernel gaussian_2D_kernel = EllipticalGaussian2DKernel(10, 5, np.pi/4) plt.imshow(gaussian_2D_kernel, interpolation='none', origin='lower') plt.xlabel('x [pixels]') plt.ylabel('y [pixels]') plt.colorbar() plt.show() """ _separable = True _is_bool = False def __init__(self, stddev_maj, stddev_min, position_angle, support_scaling=8, **kwargs): self._model = Gaussian2D(1. / (2 * np.pi * stddev_maj * stddev_min), 0, 0, x_stddev=stddev_maj, y_stddev=stddev_min, theta=position_angle) try: from astropy.modeling.utils import ellipse_extent except ImportError: raise NotImplementedError("EllipticalGaussian2DKernel requires" " astropy 1.1b1 or greater.") max_extent = \ np.max(ellipse_extent(stddev_maj, stddev_min, position_angle)) self._default_size = \ _round_up_to_odd_integer(support_scaling * 2 * max_extent) super(EllipticalGaussian2DKernel, self).__init__(**kwargs) self._truncation = np.abs(1. - 1 / self._array.sum()) class EllipticalTophat2DKernel(Kernel2D): """ 2D Elliptical Tophat filter kernel. The Tophat filter can produce artifacts when applied repeatedly on the same data. Parameters ---------- stddev_maj : float Standard deviation of the Gaussian kernel in direction 1 stddev_min : float Standard deviation of the Gaussian kernel in direction 1 position_angle : float Position angle of the elliptical gaussian x_size : odd int, optional Size in x direction of the kernel array. Default = support_scaling * stddev. y_size : odd int, optional Size in y direction of the kernel array. Default = support_scaling * stddev. support_scaling : int The amount to scale the stddev to determine the size of the kernel mode : str, optional One of the following discretization modes: * 'center' (default) Discretize model by taking the value at the center of the bin. * 'linear_interp' Discretize model by performing a bilinear interpolation between the values at the corners of the bin. * 'oversample' Discretize model by taking the average on an oversampled grid. * 'integrate' Discretize model by integrating the model over the bin. factor : number, optional Factor of oversampling. Default factor = 10. See Also -------- Box2DKernel, Tophat2DKernel, MexicanHat2DKernel, Ring2DKernel, TrapezoidDisk2DKernel, AiryDisk2DKernel, Gaussian2DKernel, EllipticalGaussian2DKernel Examples -------- Kernel response: .. plot:: :include-source: import matplotlib.pyplot as plt from radio_beam import EllipticalTophat2DKernel tophat_2D_kernel = EllipticalTophat2DKernel(10, 5, np.pi/4) plt.imshow(tophat_2D_kernel, interpolation='none', origin='lower') plt.xlabel('x [pixels]') plt.ylabel('y [pixels]') plt.colorbar() plt.show() """ _is_bool = True def __init__(self, stddev_maj, stddev_min, position_angle, support_scaling=1, **kwargs): self._model = Ellipse2D(1. / (np.pi * stddev_maj * stddev_min), 0, 0, stddev_maj, stddev_min, position_angle) try: from astropy.modeling.utils import ellipse_extent except ImportError: raise NotImplementedError("EllipticalTophat2DKernel requires" " astropy 1.1b1 or greater.") max_extent = \ np.max(ellipse_extent(stddev_maj, stddev_min, position_angle)) self._default_size = \ _round_up_to_odd_integer(support_scaling * 2 * max_extent) super(EllipticalTophat2DKernel, self).__init__(**kwargs) self._truncation = 0 radio_beam-0.3.2/radio_beam/commonbeam.py0000644000077000000240000004253413375416612020410 0ustar adamstaff00000000000000 import numpy as np import astropy.units as u try: from scipy import optimize as opt from scipy.spatial import ConvexHull HAS_SCIPY = True except ImportError: HAS_SCIPY = False from .beam import Beam from .utils import BeamError, transform_ellipse __all__ = ['commonbeam', 'common_2beams', 'getMinVolEllipse', 'common_manybeams_mve'] def commonbeam(beams, method='pts', **method_kwargs): ''' Use analytic method if there are only two beams. Otherwise use constrained optimization to find the common beam. ''' if beams.size == 1: return beams[0] elif fits_in_largest(beams): return beams.largest_beam() else: if beams.size == 2: try: return common_2beams(beams) # Sometimes this method can fail. Use the many beam solution in # this case except (ValueError, BeamError): pass if method == 'pts': return common_manybeams_mve(beams, **method_kwargs) elif method == 'opt': return common_manybeams_opt(beams, **method_kwargs) else: raise ValueError("method must be 'pts' or 'opt'.") def common_2beams(beams): ''' Find a common beam from a `Beams` object with 2 beams. This function is based on the CASA implementation `ia.commonbeam`. Note that the solution is only valid for 2 beams. Parameters ---------- beams : `~radio_beam.Beams` Beams object with 2 beams. Returns ------- common_beam : `~radio_beam.Beam` The smallest common beam in the set of beams. ''' # This code is based on the implementation in CASA: # https://open-bitbucket.nrao.edu/projects/CASA/repos/casa/browse/code/imageanalysis/ImageAnalysis/CasaImageBeamSet.cc if beams.size != 2: raise BeamError("This method is only valid for two beams.") if (~beams.isfinite).all(): raise BeamError("All beams in the object are invalid.") large_beam = beams.largest_beam() large_major = large_beam.major.to(u.arcsec) large_minor = large_beam.minor.to(u.arcsec) if beams.argmax() == 0: small_beam = beams[1] else: small_beam = beams[0] small_major = small_beam.major.to(u.arcsec) small_minor = small_beam.minor.to(u.arcsec) # Case where they're already equal if small_beam == large_beam: return large_beam deconv_beam = \ large_beam.deconvolve(small_beam, failure_returns_pointlike=True) # Larger beam can be deconvolved. It is already the smallest common beam if deconv_beam.isfinite: return large_beam # If the smaller beam is a circle, the minor axis is the circle radius if small_beam.iscircular(): common_beam = Beam(large_beam.major, small_beam.major, large_beam.pa) return common_beam # Wrap angle about 0 to pi. pa_diff = ((small_beam.pa.to(u.rad).value - large_beam.pa.to(u.rad).value + np.pi / 2. + np.pi) % np.pi - np.pi / 2.) * u.rad # If the difference is pi / 2, the larger major is set to the # new major and the minor is the other major. if np.isclose(np.abs(pa_diff).value, np.pi / 2.): larger_major = large_beam.major >= small_beam.major major = large_major if larger_major else small_major minor = small_major if larger_major else small_major pa = large_beam.pa if larger_major else small_beam.pa conv_beam = Beam(major=major, minor=minor, pa=pa) return conv_beam else: # Transform to coordinates where large_beam is circular major_comb = np.sqrt(large_major * small_major) p = major_comb / large_major q = major_comb / large_minor # Transform beam into the same coordinates, and rotate so its # major axis is along the x axis. trans_major_sc, trans_minor_sc, trans_pa_sc = \ transform_ellipse(small_major, small_minor, pa_diff, p, q) # The transformed minor axis is major_comb, as defined in CASA trans_minor_sc = major_comb # Return beam to the original coordinates, still rotated with # the major along the x axis trans_major_unsc, trans_minor_unsc, trans_pa_unsc = \ transform_ellipse(trans_major_sc, trans_minor_sc, trans_pa_sc, 1 / p, 1 / q) # Lastly, rotate the PA to the enclosing ellipse trans_major = trans_major_unsc.to(u.arcsec) trans_minor = trans_minor_unsc.to(u.arcsec) trans_pa = trans_pa_unsc + large_beam.pa # The minor axis becomes an issue when checking against the smaller # beam from deconvolution. Adding a tiny fraction makes the deconvolved # beam JUST larger than zero (~1e-7). epsilon = 100 * np.finfo(trans_major.dtype).eps * trans_major.unit trans_beam = Beam(major=trans_major + epsilon, minor=trans_minor + epsilon, pa=trans_pa) # Ensure this beam can now be deconvolved deconv_large_beam = \ trans_beam.deconvolve(large_beam, failure_returns_pointlike=True) deconv_prob_beam = \ trans_beam.deconvolve(small_beam, failure_returns_pointlike=True) if not deconv_large_beam.isfinite or not deconv_prob_beam.isfinite: raise BeamError("Failed to find common beam that both beams can " "be deconvolved by.") # Taken from CASA implementation, but by adding epsilon, this shouldn't # be needed # Scale the enclosing ellipse by a small factor until it does. # can_deconv = False # num = 0 # while not can_deconv: # deconv_large_beam = \ # trans_beam.deconvolve(large_beam, # failure_returns_pointlike=True) # deconv_prob_beam = \ # trans_beam.deconvolve(small_beam, # failure_returns_pointlike=True) # if (not deconv_large_beam.isfinite or not deconv_prob_beam.isfinite): # scale_factor = 1.001 # trans_beam = Beam(major=trans_major * scale_factor, # minor=trans_minor * scale_factor, # pa=trans_pa) # else: # can_deconv = True # if num == 10: # break # num += 1 common_beam = trans_beam return common_beam def boundingcircle(bmaj, bmin, bpa): thisone = np.argmax(bmaj) # PA really shouldn't matter here. But the minimization performed better # in some cases with a non-zero PA. Presumably this is b/c the PA of the # common beam is affected more by the beam with the largest major axis. return bmaj[thisone], bmaj[thisone], bpa[thisone] def PtoA(bmaj, bmin, bpa): ''' Express the ellipse parameters into `center-form `_. ''' A = np.zeros((2, 2)) A[0, 0] = np.cos(bpa)**2 / bmaj**2 + np.sin(bpa)**2 / bmin**2 A[1, 0] = np.cos(bpa) * np.sin(bpa) * (1 / bmaj**2 - 1 / bmin**2) A[0, 1] = A[1, 0] A[1, 1] = np.sin(bpa)**2 / bmaj**2 + np.cos(bpa)**2 / bmin**2 return A def BinsideA(B, A): try: np.linalg.cholesky(B - A) return True except np.linalg.LinAlgError: return False def myobjective_regularized(p, bmajvec, bminvec, bpavec): # Force bmaj > bmin if p[0] < p[1]: return 1e30 # We can safely assume the common major axis is at most the # largest major axis in the set if (p[0] <= bmajvec).any(): return 1e30 A = PtoA(*p) test = np.zeros_like(bmajvec) for idx, (bmx, bmn, bp) in enumerate(zip(bmajvec, bminvec, bpavec)): test[idx] = BinsideA(PtoA(bmx, bmn, bp), A) obj = 1 / np.linalg.det(A) if np.all(test): return obj else: return obj * 1e30 def common_manybeams_opt(beams, p0=None, opt_method='Nelder-Mead', optdict={'maxiter': 5000, 'ftol': 1e-14, 'maxfev': 5000}, verbose=False, brute=False, brute_steps=40): ''' Optimize the common beam solution by maximizing the determinant of the common beam. ..note:: This method is experimental and requires further testing. Parameters ---------- beams : `~radio_beam.Beams` Beams object. p0 : tuple, optional Initial guess parameters (`major, minor, pa`). opt_method : str, optional Optimization method to use. See `~scipy.optimize.minimize`. The default of Nelder-Mead is the only method we have had some success with. optdict : dict, optional Dictionary parameters passed to `~scipy.optimize.minimize`. verbose : bool, optional Print the full output from `~scipy.optimize.minimize`. brute : bool, optional Use `~scipy.optimize.brute` to find the optimal solution. brute_steps : int, optional Number of positions to sample in each parameter (3). Returns ------- com_beam : `~radio_beam.Beam` Common beam. ''' raise NotImplementedError("This method is not fully tested. Remove this " "line for testing purposes.") if not HAS_SCIPY: raise ImportError("common_manybeams_opt requires scipy.optimize.") bmaj = beams.major.value bmin = beams.minor.value bpa = beams.pa.to(u.rad).value if p0 is None: p0 = boundingcircle(bmaj, bmin, bpa) # It seems to help to make the initial guess slightly larger p0 = (1.1 * p0[0], 1.1 * p0[1], p0[2]) if brute: maj_range = [beams.major.max(), 1.5 * beams.major.max()] maj_step = (maj_range[1] - maj_range[0]) / brute_steps min_range = [beams.minor.min(), 1.5 * beams.major.max()] min_step = (min_range[1] - min_range[0]) / brute_steps rranges = (slice(maj_range[0], maj_range[1], maj_step), slice(min_range[0], min_range[1], min_step), slice(0, 179.9, 180. / brute_steps)) result = opt.brute(myobjective_regularized, rranges, args=(bmaj, bmin, bpa), full_output=True, finish=opt.fmin) params = result[0] else: result = opt.minimize(myobjective_regularized, p0, method=opt_method, args=(bmaj, bmin, bpa), options=optdict, tol=1e-14) params = result.x if verbose: print(result.viewitems()) if not result.success: raise Warning("Optimization failed") com_beam = Beam(params[0] * beams.major.unit, params[1] * beams.major.unit, (params[2] % np.pi) * u.rad) # Test if it deconvolves all if not fits_in_largest(beams, com_beam): raise BeamError("Could not find common beam to deconvolve all beams.") return com_beam def fits_in_largest(beams, large_beam=None): ''' Test if all beams can be deconvolved by the largest beam ''' if large_beam is None: large_beam = beams.largest_beam() for beam in beams: if large_beam == beam: continue deconv_beam = large_beam.deconvolve(beam, failure_returns_pointlike=True) if not deconv_beam.isfinite: return False return True def getMinVolEllipse(P, tolerance=1e-5, maxiter=1e5): """ Use the Khachiyan Algorithm to compute that minimum volume ellipsoid. For the purposes of finding a common beam, there is an added check that requires the center to be within the tolerance range. Adapted code from: https://github.com/minillinim/ellipsoid/blob/master/ellipsoid.py That implementation relies on the original work by Nima Moshtagh: http://www.mathworks.com/matlabcentral/fileexchange/9542 and an alternate python version from: http://cctbx.sourceforge.net/current/python/scitbx.math.minimum_covering_ellipsoid.html Parameters ---------- P : `~numpy.ndarray` Points to compute solution. tolerance : float, optional Allowed error range in the Khachiyan Algorithm. Decreasing the tolerance by an order of magnitude requires an order of magnitude more iterations to converge. maxiter : int, optional Maximum iterations. Returns ------- center : `~numpy.ndarray` Center point of the ellipse. Is required to be smaller than the tolerance. radii : `~numpy.ndarray` Radii of the ellipse. rotation : `~numpy.ndarray` Rotation matrix of the ellipse. """ N, d = P.shape d = float(d) # Q will be our working array Q = np.vstack([np.copy(P.T), np.ones(N)]) QT = Q.T # initializations err = 1.0 u = np.ones(N) / N # Khachiyan Algorithm i = 0 while err > tolerance: V = np.dot(Q, np.dot(np.diag(u), QT)) # M the diagonal vector of an NxN matrix M = np.diag(np.dot(QT, np.dot(np.linalg.inv(V), Q))) j = np.argmax(M) maximum = M[j] step_size = (maximum - d - 1.0) / ((d + 1.0) * (maximum - 1.0)) new_u = (1.0 - step_size) * u err = np.linalg.norm(new_u - u) if err <= tolerance: break new_u[j] += step_size u = new_u i += 1 if i == maxiter: raise ValueError("Reached maximum iterations without converging." " Try increasing the tolerance.") # center of the ellipse center = np.atleast_2d(np.dot(P.T, u)) # For our purposes, the centre should always be very small center_square = np.outer(center, center) if not (center_square < tolerance**2).any(): raise ValueError("The solved centre ({0}) is larger than the tolerance" " ({1}). Check the input data.".format(center, tolerance)) # the A matrix for the ellipse A = np.linalg.inv(np.dot(P.T, np.dot(np.diag(u), P)) - center_square) / d # ellip_vals = np.dot(P - center, np.dot(A, (P - center).T)) # assert (ellip_vals <= 1. + tolerance).all() # Get the values we'd like to return U, s, rotation = np.linalg.svd(A) radii = 1.0 / np.sqrt(s) radii *= 1. + tolerance return center, radii, rotation def ellipse_edges(beam, npts=300, epsilon=1e-3): ''' Return the edge points of the beam. Parameters ---------- beam : `~radio_beam.Beam` Beam object. npts : int, optional Number of samples. epsilon : float Increase the radii of the ellipse by 1 + epsilon. This is to ensure that `getMinVolEllipse` returns a marginally deconvolvable beam to within the error tolerance. Returns ------- pts : `~numpy.ndarray` The x, y coordinates of the ellipse edge. ''' bpa = beam.pa.to(u.rad).value major = beam.major.to(u.deg).value * (1. + epsilon) minor = beam.minor.to(u.deg).value * (1. + epsilon) phi = np.linspace(0, 2 * np.pi, npts) x = major * np.cos(phi) y = minor * np.sin(phi) xr = x * np.cos(bpa) - y * np.sin(bpa) yr = x * np.sin(bpa) + y * np.cos(bpa) pts = np.vstack([xr, yr]) return pts def common_manybeams_mve(beams, tolerance=1e-4, nsamps=200, epsilon=5e-4): ''' Calculate a common beam size using the Khachiyan Algorithm to find the minimum enclosing ellipse from all beam edges. Parameters ---------- beams : `~radio_beam.Beams` Beams object. tolerance : float, optional Allowed error range in the Khachiyan Algorithm. Decreasing the tolerance by an order of magnitude requires an order of magnitude more iterations to converge. nsamps : int, optional Number of edge points to sample from each beam. epsilon : float, optional Increase the radii of each beam by a factor of 1 + epsilon to ensure the common beam can marginally be deconvolved for all beams. Small deviations result from the finite sampling of points and the choice of the tolerance. Returns ------- com_beam : `~radio_beam.Beam` The common beam for all beams in the set. ''' if not HAS_SCIPY: raise ImportError("common_manybeams_mve requires scipy.optimize.") pts = [] for beam in beams: pts.append(ellipse_edges(beam, nsamps, epsilon=epsilon)) all_pts = np.hstack(pts).T # Now find the outer edges of the convex hull. hull = ConvexHull(all_pts) edge_pts = all_pts[hull.vertices] center, radii, rotation = \ getMinVolEllipse(edge_pts, tolerance=tolerance) # The rotation matrix is coming out as: # ((sin theta, cos theta) # (cos theta, - sin theta)) pa = np.arctan2(- rotation[0, 0], rotation[1, 0]) * u.rad if pa.value == -np.pi or pa.value == np.pi: pa = 0.0 * u.rad com_beam = Beam(major=radii.max() * u.deg, minor=radii.min() * u.deg, pa=pa) if not fits_in_largest(beams, com_beam): raise BeamError("Could not find common beam to deconvolve all beams.") return com_beam radio_beam-0.3.2/radio_beam/conftest.py0000644000077000000240000000355713420163703020111 0ustar adamstaff00000000000000# this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the source tree. from astropy.version import version as astropy_version if astropy_version < '3.0': # With older versions of Astropy, we actually need to import the pytest # plugins themselves in order to make them discoverable by pytest. from astropy.tests.pytest_plugins import * else: # As of Astropy 3.0, the pytest plugins provided by Astropy are # automatically made available when Astropy is installed. This means it's # not necessary to import them here, but we still need to import global # variables that are used for configuration. from astropy.tests.plugins.display import PYTEST_HEADER_MODULES, TESTED_VERSIONS from astropy.tests.helper import enable_deprecations_as_exceptions ## Uncomment the following line to treat all DeprecationWarnings as ## exceptions # enable_deprecations_as_exceptions() ## Uncomment and customize the following lines to add/remove entries ## from the list of packages for which version numbers are displayed ## when running the tests # try: # PYTEST_HEADER_MODULES['Astropy'] = 'astropy' # PYTEST_HEADER_MODULES['scikit-image'] = 'skimage' # del PYTEST_HEADER_MODULES['h5py'] # except NameError: # needed to support Astropy < 1.0 # pass ## Uncomment the following lines to display the version number of the ## package rather than the version number of Astropy in the top line when ## running the tests. # import os # ## This is to figure out the affiliated package version, rather than ## using Astropy's # from . import version # # try: # packagename = os.path.basename(os.path.dirname(__file__)) # TESTED_VERSIONS[packagename] = version.version # except NameError: # Needed to support Astropy <= 1.0.0 # pass radio_beam-0.3.2/radio_beam/cython_version.py0000644000077000000240000000007313531324073021325 0ustar adamstaff00000000000000# Generated file; do not modify cython_version = '0.29.11' radio_beam-0.3.2/radio_beam/multiple_beams.py0000644000077000000240000003457113516112474021273 0ustar adamstaff00000000000000import six from astropy import units as u from astropy.io import fits from astropy import constants from astropy import wcs import numpy as np import warnings from .beam import Beam, _to_area, SIGMA_TO_FWHM from .commonbeam import commonbeam from .utils import InvalidBeamOperationError class Beams(u.Quantity): """ An object to handle a set of radio beams for a data cube. """ def __new__(cls, major=None, minor=None, pa=None, areas=None, default_unit=u.arcsec, meta=None, beams=None): """ Create a new set of Gaussian beams Parameters ---------- major : :class:`~astropy.units.Quantity` with angular equivalency The FWHM major axes minor : :class:`~astropy.units.Quantity` with angular equivalency The FWHM minor axes pa : :class:`~astropy.units.Quantity` with angular equivalency The beam position angles area : :class:`~astropy.units.Quantity` with steradian equivalency The area of the beams. This is an alternative to specifying the major/minor/PA, and will create those values assuming a circular Gaussian beam. default_unit : :class:`~astropy.units.Unit` The unit to impose on major, minor if they are specified as floats beams : List of :class:`~radio_beam.Beam` objects List of individual `Beam` objects. The resulting `Beams` object will have major and minor axes in degrees. """ # improve to some kwargs magic later # error checking if beams is not None: major = [beam.major.to(u.deg).value for beam in beams] * u.deg minor = [beam.major.to(u.deg).value for beam in beams] * u.deg pa = [beam.pa.to(u.deg).value for beam in beams] * u.deg # ... given an area make a round beam assuming it is Gaussian if areas is not None: rad = np.sqrt(areas / (2 * np.pi)) * u.deg major = rad * SIGMA_TO_FWHM minor = rad * SIGMA_TO_FWHM pa = np.zeros_like(areas) * u.deg # give specified values priority if major is not None: if u.deg.is_equivalent(major.unit): pass else: warnings.warn("Assuming major axes has been specified in degrees") major = major * u.deg if minor is not None: if u.deg.is_equivalent(minor.unit): pass else: warnings.warn("Assuming minor axes has been specified in degrees") minor = minor * u.deg if pa is not None: if len(pa) != len(major): raise ValueError("Number of position angles must match number of major axis lengths") if u.deg.is_equivalent(pa.unit): pass else: warnings.warn("Assuming position angles has been specified in degrees") pa = pa * u.deg else: pa = np.zeros_like(major.value) * u.deg # some sensible defaults if minor is None: minor = major elif len(minor) != len(major): raise ValueError("Minor and major axes must have same number of values") if np.any(minor > major): raise ValueError("Minor axis greater than major axis.") self = super(Beams, cls).__new__(cls, value=_to_area(major, minor).value, unit=u.sr) self.major = major self.minor = minor self.pa = pa self.default_unit = default_unit if meta is None: self.meta = [{}]*len(self) else: self.meta = meta return self @property def meta(self): return self._meta @meta.setter def meta(self, value): if len(value) == len(self): self._meta = value else: raise TypeError("metadata must be a list of dictionaries") def __len__(self): return len(self.major) @property def isfinite(self): return ((self.major > 0) & (self.minor > 0) & np.isfinite(self.major) & np.isfinite(self.minor) & np.isfinite(self.pa)) def __getslice__(self, start, stop, increment=None): return self.__getitem__(slice(start, stop, increment)) def __getitem__(self, view): if isinstance(view, (int, np.int64)): return Beam(major=self.major[view], minor=self.minor[view], pa=self.pa[view], meta=self.meta[view]) elif isinstance(view, slice): return Beams(major=self.major[view], minor=self.minor[view], pa=self.pa[view], meta=self.meta[view]) elif isinstance(view, np.ndarray): if view.dtype.name != 'bool': raise ValueError("If using an array to index beams, it must " "be a boolean array.") return Beams(major=self.major[view], minor=self.minor[view], pa=self.pa[view], meta=[x for ii,x in zip(view, self.meta) if ii]) else: raise ValueError("Invalid slice") def __array_finalize__(self, obj): # 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) if isinstance(obj, Beams): # Multiplication and division should change the area, # but not the PA or major/minor ratio self.major = obj.major self.minor = obj.minor self.pa = obj.pa self.meta = obj.meta # 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. Note that `obj` can be an # ndarray which doesn't have a `__dict__`. if 'info' in getattr(obj, '__dict__', ()): self.info = obj.info @property def sr(self): return _to_area(self.major, self.minor) @classmethod def from_fits_bintable(cls, bintable): """ Instantiate a Beams list from a bintable from a CASA-produced image HDU. Parameters ---------- bintable : fits.BinTableHDU The table data containing the beam information Returns ------- beams : Beams A new Beams object """ major = u.Quantity(bintable.data['BMAJ'], u.arcsec) minor = u.Quantity(bintable.data['BMIN'], u.arcsec) pa = u.Quantity(bintable.data['BPA'], u.deg) meta = [{key: row[key] for key in bintable.columns.names if key not in ('BMAJ', 'BPA', 'BMIN')} for row in bintable.data] return cls(major=major, minor=minor, pa=pa, meta=meta) @classmethod def from_casa_image(cls, imagename): ''' Instantiate beams from a CASA image. Cannot currently handle beams for different polarizations. ** Must be run in a CASA environment! ** Parameters ---------- imagename : str Name of CASA image. ''' try: import casac except ImportError: raise ImportError("Could not import CASA (casac) and therefore" " cannot read CASA .image files") ia.open(imagename) beam_props = ia.restoringbeam() ia.close() nchans = beam_props['nChannels'] # Assuming there is always a 0th channel... maj_unit = u.Unit(beam_props['beams']['*0']['*0']['major']['unit']) min_unit = u.Unit(beam_props['beams']['*0']['*0']['minor']['unit']) pa_unit = u.Unit(beam_props['beams']['*0']['*0']['positionangle']['unit']) major = np.empty((nchans)) * maj_unit minor = np.empty((nchans)) * min_unit pa = np.empty((nchans)) * pa_unit for chan in range(nchans): chan_name = '*{}'.format(chan) chanbeam_props = beam_props['beams'][chan_name]['*0'] # Can CASA have mixes of units between channels? Let's test just # in case assert maj_unit == u.Unit(chanbeam_props['major']['unit']) assert min_unit == u.Unit(chanbeam_props['minor']['unit']) assert pa_unit == u.Unit(chanbeam_props['positionangle']['unit']) major[chan] = chanbeam_props['major']['value'] * maj_unit minor[chan] = chanbeam_props['minor']['value'] * min_unit pa[chan] = chanbeam_props['positionangle']['value'] * pa_unit return cls(major=major, minor=minor, pa=pa) def average_beam(self, includemask=None, raise_for_nan=True): """ Average the beam major, minor, and PA attributes. This is usually a dumb thing to do! """ warnings.warn("Do not use the average beam for convolution! Use the" " smallest common beam from `Beams.common_beam()`.") from astropy.stats import circmean if includemask is None: includemask = self.isfinite else: includemask = np.logical_and(includemask, self.isfinite) new_beam = Beam(major=self.major[includemask].mean(), minor=self.minor[includemask].mean(), pa=circmean(self.pa[includemask], weights=(self.major / self.minor)[includemask])) if raise_for_nan and np.any(np.isnan(new_beam)): raise ValueError("NaNs after averaging. This is a bug.") return new_beam def largest_beam(self, includemask=None): """ Returns the largest beam (by area) in a list of beams. """ if includemask is None: includemask = self.isfinite else: includemask = np.logical_and(includemask, self.isfinite) largest_idx = (self.major * self.minor)[includemask].argmax() new_beam = Beam(major=self.major[includemask][largest_idx], minor=self.minor[includemask][largest_idx], pa=self.pa[includemask][largest_idx]) return new_beam def smallest_beam(self, includemask=None): """ Returns the smallest beam (by area) in a list of beams. """ if includemask is None: includemask = self.isfinite else: includemask = np.logical_and(includemask, self.isfinite) largest_idx = (self.major * self.minor)[includemask].argmin() new_beam = Beam(major=self.major[includemask][largest_idx], minor=self.minor[includemask][largest_idx], pa=self.pa[includemask][largest_idx]) return new_beam def extrema_beams(self, includemask=None): return [self.smallest_beam(includemask), self.largest_beam(includemask)] def common_beam(self, includemask=None, method='pts', **kwargs): ''' Return the smallest common beam size. For set of two beams, the solution is solved analytically. All larger sets solve for the minimum volume ellipse using the `Khachiyan Algorithm `_, where the convex hull of the set of ellipse edges is used to find the boundaries of the set. Parameters ---------- includemask : `~numpy.ndarray`, optional Boolean mask. method : {'pts'}, optional Many beam method. Only `pts` is currently available. kwargs : Passed to `~radio_beam.commonbeam`. ''' return commonbeam(self if includemask is None else self[includemask], method=method, **kwargs) def __iter__(self): for i in range(len(self)): yield self[i] def __mul__(self, other): # Other must be a single beam. Assume multiplying is convolving # as set of beams with a given beam if not isinstance(other, Beam): raise InvalidBeamOperationError("Multiplication is defined as a " "convolution of the set of beams " "with a given beam. Must be " "multiplied with a Beam object.") return Beams(beams=[beam * other for beam in self]) def __truediv__(self, other): # Other must be a single beam. Assume dividing is deconvolving # as set of beams with a given beam if not isinstance(other, Beam): raise InvalidBeamOperationError("Division is defined as a " "deconvolution of the set of beams" " with a given beam. Must be " "divided by a Beam object.") return Beams(beams=[beam / other for beam in self]) def __add__(self, other): raise InvalidBeamOperationError("Addition of a set of Beams " "is not defined.") def __sub__(self, other): raise InvalidBeamOperationError("Addition of a set of Beams " "is not defined.") def __eq__(self, other): # other should be a single beam, or a another Beams object if isinstance(other, Beam): return np.array([beam == other for beam in self]) elif isinstance(other, Beams): # These should have the same size. if not self.size == other.size: raise InvalidBeamOperationError("Beams objects must have the " "same shape to test " "equality.") return np.all([beam == other_beam for beam, other_beam in zip(self, other)]) else: raise InvalidBeamOperationError("Must test equality with a Beam" " or Beams object.") def __ne__(self, other): eq_out = self.__eq__(other) # If other is a Beam, will get array back if isinstance(eq_out, np.ndarray): return ~eq_out # If other is a Beams, will get boolean back else: return not eq_out radio_beam-0.3.2/radio_beam/tests/0000755000077000000240000000000013531324214017041 5ustar adamstaff00000000000000radio_beam-0.3.2/radio_beam/tests/__init__.py0000644000077000000240000000017112711230751021152 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This packages contains affiliated package tests. """ radio_beam-0.3.2/radio_beam/tests/coveragerc0000644000077000000240000000140012711230751021100 0ustar adamstaff00000000000000[run] source = {packagename} omit = {packagename}/_astropy_init* {packagename}/conftest* {packagename}/cython_version* {packagename}/setup_package* {packagename}/*/setup_package* {packagename}/*/*/setup_package* {packagename}/tests/* {packagename}/*/tests/* {packagename}/*/*/tests/* {packagename}/version* [report] exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain about packages we have installed except ImportError # Don't complain if tests don't hit assertions raise AssertionError raise NotImplementedError # Don't complain about script hooks def main\(.*\): # Ignore branches that don't pertain to this version of Python pragma: py{ignore_python_version}radio_beam-0.3.2/radio_beam/tests/data/0000755000077000000240000000000013531324214017752 5ustar adamstaff00000000000000radio_beam-0.3.2/radio_beam/tests/data/NGC0925.bima.mmom0.fits.gz0000644000077000000240000000565312711230751024154 0ustar adamstaff000000000000007VNGC0925.bima.mmom0.fitsksLǿJKfKC\BC3VIv(1 XI|>v 庻sοt`:Aۮ>~`83Û%}vWuቘgx3#0@^ɔ]?p1Y-^LZol_O8ë3a{2V#jD"Iia1ލ։y$FB<a1Ig8Rսwƚ*?e:7ZOg6ن6!pX5_I1ՍGGi!jIwP־k U.B+A_PC,迈78}!I ɸ*W)J_Ȼ֒RQu41$!CIg̈ >&XǶ /S$ߴ^oQ{ľmRyԒ$$0pB~w9N%VquAc9I//AWzxn5oN qjAĠb ZGuVOC ~& sok#P)O[׀^H} z7mwjR㡍{[$Fj׸˷x1ĉ?p#+2gf8 SIw/,hc, 8$]&?cށp)o8#Իd9e xxSޫm [YEx0 f|cĻe~ KDp`/X/mkj&8瑓s9^>~uo`y'{z3s-)y[S,aO>q5֪ 5&՘1x+<'_7Ziqd5 y;Cƒa6N Ncvr $Ahm6y)/6fňڛB|=yl{MCNѦ/G/.wg'_׿׼3sfNv|->ޤFg9~|چ+$уl2Fīxݖw~%7'@";+uNYy<}P1 %H^xgA/BI% ݜ2o>H=@ES\sƤ@?HoP#^w|v uM #+]#LlKm${GФN$ÝnMFmFmіSC{radio_beam-0.3.2/radio_beam/tests/data/NGC0925.bima.mmom0.image.tar.gz0000644000077000000240000001525613047103144025054 0ustar adamstaff00000000000000#Xly)K~XeV|㟒MQwG%l!Ӕ-Y2q"O;([YE-Yv,Ȓ k [%/tـhyt'Or>}-MNs A *5)T5.VU:8 39#9q8>oa +0-`, Jy5PWUZҬz+a/ v;!Eo{Ȋ 7Ǡ>[9Е翴PYӫ&&|o1n*n,9`>g] y*k!YrAT}GDlwW]_XQ1L¹%iɨ;Տv[8m䆋 4gXNi=qzZ]sFE6JV{ 4۝Tb*(               oo               be~*Lg:әt3l?ƃ?      x-6  blr#=p'|qص*F]8kw\{'C>Qڟ{ka~U{\`oq>׾Aބ1x^pkƸ #t;jeʟnG^iGݎZg;j݁ӁZ;P}m_@ցZyjVjӉ;QSt'jЉZ=ӉZ҉c7=fJf+Q܌Zf7xP]...l\j]t&ovV+׍ZźQnJF~J7 փhjQ_=ճ=VA׃mEzQE^^l^KK뽨}[P[P-ճ[p}>>,7PVӇZ}>>~*ߏZV/VOV_GM^GW>Z@ VjaU޺V,ۊZ}z+j孨՟lEn+ jDfQ+Q_DDM~w{_OQmmUfjnC> ~goڎZ۱v綣VvQCUt:3Z}|jjjC7|oV;PU|juqjs>uX~n'jU߉Z=za'j՝8wV;Qaa#ض2ZՆQkèɯ V_0ja*pjuԪpjU-v.k؅&>ez˜_܅z.'<]צ{#`rԽU=}7`];`]F;ڟ܍೿kϮAo/`oq:^_ًi/ݽ}>vƵ_Ib;c?6+ۏ=c۞0} C}_;i0?:wU><}î`9 j3&{]3A+]s.8]6{}8tpl9>L0ՙèyø/a/}{`l>?Ǐ`O=#1 mQa/Ϗb =}=cxgqQ\1ܯ.c_= ?<cFB#gF0W#8O`/lG#FqObEݞEm<c}<@AAAAAAq`YFϵx&          7rR6ȪTUtdYXP%& CZHK|ܬ) "YR;]&Yvj)Lf l 62/kL Ɖ5i!MىSI&\adٙi.#INLK뵚)3E7,骪_M|3QSZ%WQUJ0%2S}TU Bp>.t5F\h\7S|0/+_+WeaZz=u",N3BtƮ`e=+cIiuÐUɲ@B6w*6aW_5x?ڼZ[虉f#g$MS*3kn]nzrTL1b>N1~ lXbz\K9kOvىڼXK9+-ʬ!-LM#g"2gl>=ЇF?)&qJyJ%ŤMwMGʅ))ĒbRRnIXRH$<ݒ$%"<ݓ")WHy!B)?O CC*t=O;%1oQjr\.]'9s[%3=leIBayS*C,3aw`H7v%n*z(,QUgO8rB$7V鲸k쁱9UKjE&Te+5f^ FQ**+U9vnhpmeVQk)O]b2Y:+f2l֚WzdU]z,鰡0Q WXݨnr6hh} 4T6t.Yvx$NbѦ). 㑰o9S4EO*W,^L Č9όGbb,㹞tt"RS{Ó$񬴡#sI\DŽ KaK0Wp!n']]Tj뻫sL1x~iJӌQ1nw>ˇdox+b3Oe 5O3>26ѨqbIypV|睩ߪ?s4*eDrM5jC^W%L5'`$RU^g>gYHDb's,ϻ qxPS ?[*WT>CX;+v 'c'x&Y.?%ao`pys[eJ<%Rb)oܬ(X ss)>$b!Wa), 9+= };mz3d'rjDB4ȏK 8^r ޭpXLLu 2|_ L=M8B=U\KYEI.OBS(x.9qkBbwHFٔAVi,w+rՐe3;Q:STK撵˕-u&Oɰ҄< q5J&W<=jzjP8 J^h1fK csmլ2T*m|ž79US,I焇1MPKN\spB)i:dRuI7ƭvt3eMȎSu`:W$ٌ)6yɸj1e̤˜"IpV.T%\ZHMBYMM],g!!y95'dw}MRW%CydtU֤:xpqG                     bc,#g:UKUq5Th>1m10s1Nr`-4LK2 ȆR^o;W@Sd4I8ћW%Esk:),7][l;WYM6MWXD88- op/۾tdɕnQ{XTHj~4.yƍ*mpzWS/7_HBmKpY5G<+g<;U?جXω$04{ =:7dG`\sR1.Z"Xֿ(;7;>E7mN}mmPYMs[l̺{{š[Z?#1z=4{sr%-~?LuSQ[_g8zKx[_z.]pפ[\=o Nunבּ-V_|,0=x|^`oXn<]isYv{ov)f}t]yvc۟YBCvB^a볦lˆ ` m+hղYen[Q_ͭOV`ݷñ/Vvp[;- Jens=z5YP?NeZ76xox?ca I66|ᦆ/lxڻ6(id2;oyo޼G1n枟9p0̅SLhd!̃=}Je%WṆyu'{!Ӵ.Kt9 zH^_x* }(&qܟNz 'Jc岴bp(~>S׿^<ڞ} \Vvʲ{\n鉒T |6val[ۘYEձ%[5$U`QpVZT-Vqyc/Η4{Le8pAS9jhRZ9i6^S^ke^ rO(`d܆_sf zllm دj(٢L`)KYS:ŐG{/?0DQ',5xO#_=~=kY<Ƅf'ٚkR"!- >':؁l$Sÿ2'Z׫ެOCtYL~Lj'j>^\Yy~S^m Rs9`O)T߯LCbɛ*;A/g_.u(섫xX (⾷Nz߹C4o5Dn+DքD8)9?Cs3p} jKDv Mu^vYf6 BMv5uC+CE*천A7 HTlzQ71SN<|AҢ"/T"{D@܊k4b݊]UqL>/poUc](ͨpWULLIb9::1S/MY㛩N]d[>y0 ؈?~zR93uM+FRoo01 HᏁ*h>#9;N?]C*GaVFxzP[h&߉8N&X,>Gm{?I': 3(7`1D"\[rtwvϓ_o j%5i@|Y, '^ٓXC?'x5gKK/ _lUMܨu]A|BP}17^M?^N0vثoeG{;.O @ @ @ @ Ü&radio_beam-0.3.2/radio_beam/tests/data/header_aips.hdr0000644000077000000240000004200213174164704022724 0ustar adamstaff00000000000000SIMPLE = T / BITPIX = -32 / NAXIS = 2 / NAXIS1 = 2707 / NAXIS2 = 2707 / EXTEND = T /Tables following main image BLOCKED = T /Tape may be blocked OBJECT = 'omega_ce' /Source name TELESCOP= 'ATCA ' / INSTRUME= ' ' / OBSERVER= '' / DATE-OBS= '2010-01-22' /Obs start date YYYY-MM-DD DATE-MAP= '2016-07-20' /Last processing date YYYY-MM-DD BSCALE = 1.00000000000E+00 /REAL = TAPE * BSCALE + BZERO BZERO = 0.00000000000E+00 / BUNIT = 'Jy/beam ' /Units of flux EQUINOX = 2.000000000E+03 /Epoch of RA DEC VELREF = 259 />256 RADIO, 1 LSR 2 HEL 3 OBS ALTRVAL = -6.85933178146E+07 /Altenate FREQ/VEL ref value ALTRPIX = 1.000000000E+00 /Altenate FREQ/VEL ref pixel OBSRA = 2.01691208348E+02 /Antenna pointing RA OBSDEC = -4.74768611168E+01 /Antenna pointing DEC DATAMAX = 3.216996155E+02 /Maximum pixel value DATAMIN = -6.924145508E+01 /Minimum pixel value CTYPE1 = 'RA---SIN' / CRVAL1 = 2.01691208348E+02 / CDELT1 = -9.166666860E-05 / CRPIX1 = 1.356000000E+03 / CROTA1 = 0.000000000E+00 / CTYPE2 = 'DEC--SIN' / CRVAL2 = -4.74768611168E+01 / CDELT2 = 9.166666860E-05 / CRPIX2 = 1.356000000E+03 / CROTA2 = 0.000000000E+00 / HISTORY / History of input map 1 HISTORY -------------------------------------------------------------------- HISTORY /Begin "HISTORY" information found in fits tape header by IMLOD HISTORY EXTEND = T / File may contain extensions HISTORY IRAF-TLM= '2015-07-27T09:00:19' / Time of last modification HISTORY BTYPE = 'Intensity' HISTORY RADESYS = 'FK5 ' HISTORY LONPOLE = 1.800000000000E+02 HISTORY LATPOLE = -4.747686111680E+01 HISTORY PC01_01 = 1.000000000000E+00 HISTORY PC02_01 = 0.000000000000E+00 HISTORY PC03_01 = 0.000000000000E+00 HISTORY PC04_01 = 0.000000000000E+00 HISTORY PC01_02 = 0.000000000000E+00 HISTORY PC02_02 = 1.000000000000E+00 HISTORY PC03_02 = 0.000000000000E+00 HISTORY PC04_02 = 0.000000000000E+00 HISTORY PC01_03 = 0.000000000000E+00 HISTORY PC02_03 = 0.000000000000E+00 HISTORY PC03_03 = 1.000000000000E+00 HISTORY PC04_03 = 0.000000000000E+00 HISTORY PC01_04 = 0.000000000000E+00 HISTORY PC02_04 = 0.000000000000E+00 HISTORY PC03_04 = 0.000000000000E+00 HISTORY PC04_04 = 1.000000000000E+00 HISTORY CUNIT1 = 'deg ' HISTORY CUNIT2 = 'deg ' HISTORY CUNIT3 = 'Hz ' HISTORY CUNIT4 = ' ' HISTORY PV2_1 = 0.000000000000E+00 HISTORY PV2_2 = 0.000000000000E+00 HISTORY RESTFRQ = 4.475999873410E+09 /Rest Frequency (Hz) HISTORY SPECSYS = 'TOPOCENT' /Spectral reference frame HISTORY casacore non-standard usage: 4 LSD, 5 GEO, 6 SOU, 7 GAL HISTORY TIMESYS = 'UTC ' HISTORY OBSGEO-X= -4.750915837000E+06 HISTORY OBSGEO-Y= 2.792906182000E+06 HISTORY OBSGEO-Z= -3.200483747000E+06 HISTORY WCSDIM = 4 HISTORY CD1_1 = -9.1666666666670E-5 HISTORY CD2_2 = 9.16666666666702E-5 HISTORY CD3_3 = 2049241561.325 HISTORY CD4_4 = 1. HISTORY LTV1 = -1205. HISTORY LTV2 = -1205. HISTORY LTM1_1 = 1. HISTORY LTM2_2 = 1. HISTORY LTM3_3 = 1. HISTORY LTM4_4 = 1. HISTORY WAXMAP01= '1 0 2 0 0 0 0 0 ' HISTORY WAT0_001= 'system=image' HISTORY WAT1_001= 'wtype=sin axtype=ra' HISTORY WAT2_001= 'wtype=sin axtype=dec' HISTORY WAT3_001= 'label=freq' HISTORY WAT4_001= 'label=stokes' HISTORY /END FITS tape header "HISTORY" information HISTORY -------------------------------------------------------------------- HISTORY IMLOD OUTNAME ='WCEN_LOW ' OUTCLASS ='ICLN ' HISTORY IMLOD OUTSEQ = 0 INTAPE = 1 OUTDISK= 1 HISTORY IMLOD INFILE = 'PWD:wcen/wcen_atca_5500_pbcor_c.fits ' HISTORY IMLOD RELEASE = '31DEC14' HISTORY / History of input map 2 HISTORY -------------------------------------------------------------------- HISTORY /Begin "HISTORY" information found in fits tape header by IMLOD HISTORY EXTEND = T /Tables following main image HISTORY BLOCKED = T /Tape may be blocked HISTORY / IEEE not-a-number used for blanked f.p. pixels HISTORY -------------------------------------------------------------------- HISTORY /Begin "HISTORY" information found in fits tape header by IMLOD HISTORY EXTEND = T / File may contain extensions HISTORY IRAF-TLM= '2015-07-27T09:11:10' / Time of last modification HISTORY BTYPE = 'Intensity' HISTORY RADESYS = 'FK5 ' HISTORY LONPOLE = 1.800000000000E+02 HISTORY LATPOLE = -4.747808335040E+01 HISTORY PC01_01 = 1.000000000000E+00 HISTORY PC02_01 = 0.000000000000E+00 HISTORY PC03_01 = 0.000000000000E+00 HISTORY PC04_01 = 0.000000000000E+00 HISTORY PC01_02 = 0.000000000000E+00 HISTORY PC02_02 = 1.000000000000E+00 HISTORY PC03_02 = 0.000000000000E+00 HISTORY PC04_02 = 0.000000000000E+00 HISTORY PC01_03 = 0.000000000000E+00 HISTORY PC02_03 = 0.000000000000E+00 HISTORY PC03_03 = 1.000000000000E+00 HISTORY PC04_03 = 0.000000000000E+00 HISTORY PC01_04 = 0.000000000000E+00 HISTORY PC02_04 = 0.000000000000E+00 HISTORY PC03_04 = 0.000000000000E+00 HISTORY PC04_04 = 1.000000000000E+00 HISTORY CUNIT1 = 'deg ' HISTORY CUNIT2 = 'deg ' HISTORY CUNIT3 = 'Hz ' HISTORY CUNIT4 = ' ' HISTORY PV2_1 = 0.000000000000E+00 HISTORY PV2_2 = 0.000000000000E+00 HISTORY RESTFRQ = 7.975999774420E+09 /Rest Frequency (Hz) HISTORY SPECSYS = 'TOPOCENT' /Spectral reference frame HISTORY casacore non-standard usage: 4 LSD, 5 GEO, 6 SOU, 7 GAL HISTORY TIMESYS = 'UTC ' HISTORY OBSGEO-X= -4.750915837000E+06 HISTORY OBSGEO-Y= 2.792906182000E+06 HISTORY OBSGEO-Z= -3.200483747000E+06 HISTORY WCSDIM = 4 HISTORY CD1_1 = -6.6666666666670E-5 HISTORY CD2_2 = 6.66666666666701E-5 HISTORY CD3_3 = 2049361403.91 HISTORY CD4_4 = 1. HISTORY LTV1 = -784. HISTORY LTV2 = -784. HISTORY LTM1_1 = 1. HISTORY LTM2_2 = 1. HISTORY LTM3_3 = 1. HISTORY LTM4_4 = 1. HISTORY WAXMAP01= '1 0 2 0 0 0 0 0 ' HISTORY WAT0_001= 'system=image' HISTORY WAT1_001= 'wtype=sin axtype=ra' HISTORY WAT2_001= 'wtype=sin axtype=dec' HISTORY WAT3_001= 'label=freq' HISTORY WAT4_001= 'label=stokes' HISTORY /END FITS tape header "HISTORY" information HISTORY -------------------------------------------------------------------- HISTORY IMLOD OUTNAME ='WCENUP ' OUTCLASS ='ICLN ' HISTORY IMLOD OUTSEQ = 0 INTAPE = 1 OUTDISK= 1 HISTORY IMLOD INFILE = 'PWD:wcen_atca_9000_pbcor_c.fits ' HISTORY IMLOD RELEASE = '31DEC14' HISTORY CONVL RELEASE ='31DEC14 ' /********* Start 16-JUL-2016 18:59:57 HISTORY CONVL INNAME='WCENUP ' INCLASS='ICLN ' HISTORY CONVL INSEQ= 1 INDISK= 1 HISTORY CONVL OUTNAME='WCEN_CONV ' OUTCLASS='CONVL ' HISTORY CONVL OUTSEQ= 1 OUTDISK= 1 HISTORY CONVL BLC= 1. 1. 1. 1. 1. 1. 1./BLC HISTORY CONVL TRC= 2275. 2275. 1. 1. 1. 1. 1./TRC HISTORY CONVL FACTOR= 2.23193E+00 / Units scaling factor HISTORY CONVL BMAJ= 2.9700 BMIN= 1.6500 BPA= -15.1/Output beam HISTORY CONVL / plane 1 conv with 2.17968 x 1.23466 at 168.0 HISTORY CONVL OPCODE=' ' /Operation requested HISTORY CONVL DOBLANK = 1 / Blanks restored after FFT HISTORY OHGEO RELEASE ='31DEC14 ' /********* Start 16-JUL-2016 19:00:16 HISTORY OHGEO INNAME ='WCEN_CONV' HISTORY OHGEO INCLASS ='CONVL' HISTORY OHGEO INSEQ = 1 HISTORY OHGEO INDISK = 1 HISTORY OHGEO IN2NAME ='WCENLOW' HISTORY OHGEO IN2CLASS ='ICLN' HISTORY OHGEO IN2SEQ = 1 HISTORY OHGEO IN2DISK = 1 HISTORY OHGEO REWEIGHT( 1) = 1.00000E+00 HISTORY OHGEO REWEIGHT( 2) = 3.33400E-01 HISTORY OHGEO APARM( 9) = 1.00000E+00 HISTORY FITTP DATAOUT = 'PWD:wcen_up_ohgeo.fits' / data written to disk file HISTORY /END FITS tape header "HISTORY" information HISTORY -------------------------------------------------------------------- HISTORY IMLOD OUTNAME ='WCEN_OHGEO ' OUTCLASS ='ICLN ' HISTORY IMLOD OUTSEQ = 0 INTAPE = 1 OUTDISK= 1 HISTORY IMLOD INFILE = 'PWD:wcen/wcen_up_ohgeo.fits ' HISTORY IMLOD RELEASE = '31DEC14' HISTORY / End of old histories HISTORY COMB RELEASE='31DEC14 ' HISTORY COMB INNAME='WCEN_LOW ' INCLASS='ICLN ' HISTORY COMB INSEQ= 1 INDISK= 1 HISTORY COMB IN2NAME='WCEN_OHGEO ' IN2CLASS='ICLN ' HISTORY COMB IN2SEQ= 1 IN2DISK= 1 HISTORY COMB OUTNAME='WCEN_ST ' OUTCLASS='MEAN ' HISTORY COMB OUTSEQ= 1 OUTDISK= 1 HISTORY COMB USERID= 5 HISTORY COMB CTYPE='MEAN' /Mean HISTORY COMB BLC= 1 1 1 1 1 1 1 / Bottom left corner HISTORY COMB TRC= 2707 2707 1 1 1 1 1 / Top right corner HISTORY COMB A(1)= 6.9856E-01 A(2)= 3.0144E-01 HISTORY COMB / Undefined pixels magic-value blanked HISTORY FITTP DATAOUT = 'PWD:wcen/wcen_stacked.fits' / data written to disk file ORIGIN = 'AIPSmacbook-pro 31DEC14' / DATE = '2016-07-20' / File written on Greenwich yyyy-mm-dd HISTORY AIPS IMNAME='WCEN_ST ' IMCLASS='MEAN ' IMSEQ= 1 / HISTORY AIPS USERNO= 5 / COMMENT FITS (Flexible Image Transport System) format is defined in 'Astronomy COMMENT and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H HISTORY AIPS CLEAN BMAJ= 8.2477E-04 BMIN= 4.5736E-04 BPA= -15.06 HISTORY AIPS CLEAN NITER= 0 PRODUCT=0 / DIRTY MAP END radio_beam-0.3.2/radio_beam/tests/data/header_jybeam.hdr0000644000077000000240000000670212711405077023243 0ustar adamstaff00000000000000SIMPLE = T / Written by IDL: Fri Feb 20 13:46:36 2009 BITPIX = -32 / NAXIS = 4 / NAXIS1 = 1884 / NAXIS2 = 2606 / NAXIS3 = 200 // NAXIS4 = 1 / EXTEND = T / BSCALE = 1.00000000000E+00 / BZERO = 0.00000000000E+00 / BLANK = -1 / TELESCOP= 'VLA ' / CDELT1 = -5.55555561268E-04 / CRPIX1 = 1.37300000000E+03 / CRVAL1 = 2.31837500515E+01 / CTYPE1 = 'RA---SIN' / CDELT2 = 5.55555561268E-04 / CRPIX2 = 1.15200000000E+03 / CRVAL2 = 3.05765277962E+01 / CTYPE2 = 'DEC--SIN' / CDELT3 = 1.28821496879E+03 / CRPIX3 = 1.00000000000E+00 / CRVAL3 = -3.21214698632E+05 / CTYPE3 = 'VELO-HEL' / CDELT4 = 1.00000000000E+00 / CRPIX4 = 1.00000000000E+00 / CRVAL4 = 1.00000000000E+00 / CTYPE4 = 'STOKES ' / DATE-OBS= '1998-06-18T16:30:25.4' / RESTFREQ= 1.42040571841E+09 / CELLSCAL= 'CONSTANT' / BUNIT = 'JY/BEAM ' / EPOCH = 2.00000000000E+03 / OBJECT = 'M33 ' / OBSERVER= 'AT206 ' / VOBS = -2.57256763070E+01 / LTYPE = 'channel ' / LSTART = 2.15000000000E+02 / LWIDTH = 1.00000000000E+00 / LSTEP = 1.00000000000E+00 / BTYPE = 'intensity' / DATAMIN = -6.57081836835E-03 / DATAMAX = 1.52362231165E-02 / BMAJ = 0.0002777777777777778 BMIN = 0.0002777777777777778 BPA = 0.0 radio_beam-0.3.2/radio_beam/tests/data/m33_beams_bintable.fits.gz0000644000077000000240000002460313174212732024702 0ustar adamstaff00000000000000%Ym33_beams_bintable.fits1 1F7B1B@H;,l$ۻv b|x`9TY[R)yMGmG:ڣiJ#A]{o!Oy!Sij8u !B=o0mLUi. uZ"0(q*utV(`1Ъң{}wk;wRf;1:G ?g0o?yΣR9^ōg "oP6N~8cU28}(t=upl@%"B&B(ig"H d*s6۸{V]IZP-j _1Bvӓ٦0^`5$~`8e`kIyu<*D4WZ.k!뵐.Kd&NZmk'A[@oڝ!^~?_dp)  A08 AB 5n,0Ӹt!ػ.w?{νu{9W}ɜޣ|}>2YD6vQYv6das1]}ⲫ`gʖ= |K5s~X㖖+-3r];v#ް9\Nv)l-./;6W lEa$+lc,;>Wuֆ᪲[MV [.+-#[Cvl )l1od{=[% [arlkػ]G,fFeց%eKx֗{C6K Un 1gXiن!k#H]n,vn"Meco3YvesY?ll {5`rrXqq)okك6`p[-AfA X5~w]+(;vsw߽,l/=";sOQ l7YnM5v-#-a0Pv l-؃Q7lU)[{˶l9=?zmqփ}*?d|߾'Yqo_>aA`Cq/= {ιaOٰs/DTvdnaEG852ݞȪd䔞 Zv'W#vVFN9뭓Sz.-k]5)=&1Sf1S=mvUF6Y+l_Y6ǹ`A ~aɘ=wˈMe=2bgߑ`빗dLϚϲM<Gև+;F̒~F|V'%a8Yk5d +N} |+)U6_v߰7e)]2w=ܻdq2~=2dʞ5K'{6ߜw>+1y+egt]gޠJ#2:=&k-{\FN t9#(lOC˨s:EHF>q5`VggeY޾s /e#+_n FF]?:~`\t|cޠ3a)V؀q{x;M>:^: ?߈ozs)Υފwn<A-JM svصuD]BS#΃S#钐oD7}lnXFЈo7tho۹ibEV'MV!MSu!MSu$MSu$95syGDE`,'ɳ_+XPO#'\CWO|yϧ+~[{+Ru,e]WWOXڿ#Kan{+\܀ `c_j؈LW$=@DWyi Hў&~""yCW<T""}#2_ڧeW wLW}~[.oߧ_pa3헇ӈBH~LWo?]+'~+3L{gXGŵ`͞OW\V'˽6_qiMQMQxoޥ}gzL7ܾL7EkgW7ul}k䭈o21dD7 ,7jɈo9ز2%|S";5_B]M 7귈o8j[uwe+`0o!FMUæe)ⲭugԓԗqWyo@7Eh{D"Jaw¨#aA=IM {gU~[пQGSLE"ϴu69MQ81vS7ڎqo<%M- kq/(RWFj_8ryDWvk fm?_h;"2+$+ڶw/;d~ۦ2_!xv7f$_Z2_!f_:mLWo[5%eu_ ^.tnpBEOW(h$5DDWj%"V>XDWX~@qB]~ڋP {=8_Ef˓gZk܋/OZ8_ϗ:9<,߆<1ӺL L'V[#<}E k$)<_BX 0_~%p(o9ݟ/3I/O?L'ϴyj;d7Q`o";5&a aG"agM< YDτ짹 b5Ce L2-yy&5w3M\E7AּL&Mgg-M|nJ~n]чG׷? X,;6}jT7q0ޢ biQnT7Anlz/]_T7AԎ\kT7A-4obsHxٰ&裚robMثM{1WQįaO;N7+c28}J+ܫ a7`fe-8yiAESk܋o<'  ]]m^tNu/a'c'z\C7N.L61HƩ}JÚ+=t,x㗇,_qz즽KT7ND9?x㧇l5c/;z fe[o|uX5{Tl:śn`ͨ/GDGMo jG/QfUeqz&r [&|7E.MƩÚ"Y7N6~+ ĨoL7>=6?߃RE\Bӻ4dT7N8G`o9rJc9EC{>Q_5;'Q_xkr.wu{To㹍r.z_9rKdPc}^3ܹ2_ةO3宇qU/wMQ56x>_,XL#41x)}ˑS^r,9Ɲd}T>Cx2_Ҹ{րmFEa[a9WL#Vr^/ކ}rèL7S?s_nGˑSKÄc2Sda e"uϧ#48ؐs#K  !O'a7ce {aWc. c7.toZ9vM7F6^cjq2;!d|ƈZoV.50fc c`;cƜc) ;y1z}'6m%m [=ϝ}cԘ gDϚƯaQyaq- >Fa>޹Q(5R}赢QjGQkFSG߯_λxAId藢7a:W7J}_${&6QoD}0 }(d?7(9;o|?1 oUO7J=^}iT7JR?9?ݺ]7Jު?)oU}ZT7JMXo޾F)ۤF c`=vkFS|Qb~_e GGIX{Lb<%o{tQrJ&_K؆"z0ШoRkFdl?–FWvnPF(e)uQVS_G2_X{Mz>_Q {/{o~eO׫˒Sp _aث2_RsYrJ2_R{y=`w9N%@9N%]+e)u\C=vL%·}e® ~T] ˖;eKa ڽaYrO]L]&<_jT9k^YrJޮЃՕ:W Ce,9^/aadW`12HuLe)u+b2_9 sL~\_9شϐ/1LIa=a2Lmg\!fjߔ2LE!fj_p/C>8_:13;N!fjt/C` t| yv@9 vL!fj:C`g/C5jڠcͨ/S/Co_\_޾M6ݟ/CW[8_f!+_޾vz=k2Qخ1_޾vfMbkl.߅mc4yv0ctLw]5՘/M=TAaK‚q wbL&Ԯ [k> /1_<آi5n[L}\_ޥc:_/ų[y/EN/ET'^_~u#aR./8Nj=-ʜ<ԡ /ER}@vL"~xΰkKgp/Q})Luoا)L\ւ\_jU؉2_P=|=w@1_j=X[71w~}yV.\_\VFe{oFoիz#s:ܓo092"{T|10ZL7LV,{ޓwdeaQü+>*w1̗aۗbwx o {ox6~aabN}0ybL7*y %~n {) 3C<+q P 3"oUz!jϧ|a% QTQC=o>gC7DR|@ ͅ`> : Ѱ gXwo cZ7DV8Kr ѻT,3C{-޹!j\C7DN){$L7D*@6C9o޾<^CGL7so룷yv_y_`O+73x={W7? 9^o??Xb_oP~L7)'[\7xXoq Q~r۞oxyizиo}ysJưVOv.1 3Az؏wςm\6+a]C7xl Cq }aN눸opa__mq犯e?E\7H] ۗ}q uXهߕaeE R;N7,8 }w٠L7sZolTrq{¿&aOo){k /˨1,E۽j²Wb,?R,bJo إY7@o_v{ ;=n8=oXʎtovXצ o5Rϧ ߿Cq9loVL7@V[wEquXN m\-7uXF 0u}gwM3X1-S\7@Tko`]د\W7ea߸grϼzҏd~_?}w)5f!0_簌J\WOV<ϥi+2_?uXOI?7_?uXS+? N?;|6tq_yc.p]_?1SzEO̔kq2_?1SzsLiצ'fJe.X+tK4.H>SΑE_F3xÂ幍gJW\O?SLOVLO\in%>^5D6Kc ϧ'Fͫxw%}{\HK%.%JO)0/K %x&KCG%^}ɋ2_:/AN)yLKSJ䔒|ح_*X%JG<>%7i%%߾ d% ;{KSJN%)%8W >JeD9䔒Wğ`UƖ/u *o *oef]C0Rlظ/,_bEFO .K~'%\WGj~n,˿_/~˿ b{radio_beam-0.3.2/radio_beam/tests/data/m83.moment0.fits.gz0000644000077000000240000002044512711230751023253 0ustar adamstaff00000000000000bVm83.moment0.fits}SFƿFg83HKRpaFؒ+z]ɖlٺo1Ɠpǵ]{i<}݉h[^Cm_ޝLC-򵷧K-lolm?ioNN?zg֢癳?^j<] 4nIvnztyr;7`zvhgg;N;53 )}p?;U Ν8fE9;vFJ%E_߭?Sfotī>m jkf;?p.l='3QGG޽q9'\{"xe;V[]\^ mv =~%~Z{z(_iw\9_%791#?:VZ`Ft 䧟O?n?3\Ke1mlpr7=--g? r;ujg^yr9 魘rJNޠ+䍄O΂3^4Os񛈲:~R OLK\g$Z7k\}eP)J 1s< #;-fCXk{r'g(9`0'K*Ol/JēY%oOynW *-"i`D{I?~N'^.Oo۟<`64?ݜyt>/|Fi{>SiZۮWpGo#L߮GR߶|{>y#G>!<+/|#W8]#G>az>BxQ ?30+{ؑ'1tdƹw=O}=6߼ߖuqE79lXܮ!tљ/Se~M4kRwUZmml{7h@yHˬ񛩾Q(~!P}y}q"Nx]?op}*^I^nMnKOP޸;' |\הT>1OLߕ^׌fֵlkV]k׵N]ֵ^] cNo_KߞY^9a?[YBxR_%<[%ޕnh}Σ]Ixkfks~}{`oӷk{o9/#c : <~84Σ'hI<~ Aʇ^uIqmgEy^u?<83Σh?< ܟ3ΣO}gGYAiHyqmgGV֧_x b .홞r.#"<~ VyehҎ1i{gD9jng]Gw9Ex|]Gw9UGw15UGw9UQ]5}.#X滝K"jgj.#*?R]5}*O5Uj|]).#绊<|]Gwq}|Gw9U]Gw9Ex|W]>.c nD?;/%\o#_~됾ŝ<^~1kݨyk?Z<gqPcqqF;qn /}3&Nû~O_̵,D3\h*Sީ7q(V?&c9sY38wK/W'-|oɾ3{pc7>3̝0BAQ`Gۼ,n`aX˫GX;j׋Y^r{ {ړGgDh|eX˕IyXDxE>gyF[||g%}-ﲼu7+طV ʞ굻v^kз3Ve7Ӆn{}fzFkˮw^2t8~''ϧ/fF6_Ʌ_?,qV,oAQZJVݪ>9+U^<[l! /w?d'VG>dy`Sg _kQ+ܴMэiihCGQ=!/w<Hs=MZ~6/4nX[Wx )-Y \}E!k/ '>Fq#&7eT/Sb)o⇓/pY.ˁ? R[qɓW׮Y0ylx ߬D=K+9y{ݍ+ywB@׃X(sA ~sP_F2;A^xG~?sXK q1ü+7xz1wWz4:VO:ϱʋS q?~ q1}璗/Et+kie7]“N6{Z? _޿/yeB}LQ 07׋F>(1F!7rF17 yL8~wof~X~z 7\~zYx~2Eb}0KF~/oA}Lz?bKoTy?"x~AoTy?"V^ȯ-7 yL8~-~7~y~Bo~/</y}ۜmTmks=kYޗ?zAH G8HfoUR#&HBڔ5}o'`MNG妬:pmpGYAۯyqy Ǐ7Σퟍ ToO^߯2>wopUS?3; o©G>zյZm1)o1ވw]Y?>̪K .>UHK5H!+,yq$+oS<}3[K}oyߺxW6X<~=l^ߕnk`.۹"hyd~GX{]GwGw[Gw"WwʛF򻈾]Dy~Gw ?g%]Kߧx]L_u/ô/ƣ]2~Q.ƣ]GwGw1b+6<4Cb=#ݿG‡xœa<~ T_qfɣkޯ8ur`6],ouDm_Igt,qXrIO " |9烚4`:Z;arƒls"*lld k!ug(|-ɇkYxuȩA͐G`[͎.^ %fE2~\TYwEBķ ??"?;H~ז*)BO{%.k@;ߑo&3d:q{7U;h !RR1/g/y#s($r$-|oR^}G!e!& ,!p_@>LvcҿK_$!;#{+%\Z銾#al{g'߁Sn$ou쩼+ir@3}Ӷgnuo[͎|Zk:MkߌoO.GXx=uFNKq!O ӎ)7烋V[ \>b>w1 joXȬѹ[FwioX|{v%yM>[Z}%%3Oތӱ 7vWOt$ir'h?y /|8ƻ7'7ֱ3^Z+7Yjy\dNLJڵ?F᤼5Ep~{xqx^ Y> IӬ,_~yq}m-P);YXv*/ĭz/JSI zGjgI׭zx_7x<̅: WOyП+x=e/%9q&(f†[ul/F.\Leh@-LyE!UTxWMXNfXȳ-qbV'ҷ%N# ='@-qb8q>qp{8N|ӕĉmWDm';azV>PYͶ.m7}2I^wE eߤ_Ͽ_}Uק?h%}_r{)&yR!}74,}4-'$ZzW̅_݂>cu7i/c7NJǯ<<`sh.Gjh}׍!5зdRWu$d@sradio_beam-0.3.2/radio_beam/tests/data/ngc0925_na.fits.gz0000644000077000000240000001343712711230751023036 0ustar adamstaff00000000000000eVngc0925_na.fits sJǿݪk'1ы]*V$֭ H,$>~{f$! (YHLOw_X *B(☠ ֣ZFm2Fn,jj<}_Lh4)|]<+d?dsaXkӶZ;ѡM <anO.9jkBwѿiy ?Wv55/b/5A`B A|OFw=5/ޠ9VGxQO嵕Z(p.ZIvaMFjC>QJ1^O!sT_z+{jצKm50/O^e;ܬ{o'^u8h"oHAm˻W#s`~/jk+Qw<7o.%#~DNFJ,'2Hgw2W}߄GӾzYpA-qoi~7qh<^=/=r=HA4yt{=r5 >D<+8Y_s2 [`\Ҝ%w:ZП 4]SlpYH ;jKL)s oop7+<8M /2__tCG?6vc#Fik?٫DG'P%FWek6^S_t/?0KW0nxrmhJܾ jfeI H;0$HRHR2`TixS{2^=ZI !_ۓ7zH߰N*Xl7F =pދO.c\$F E6U2͗Dhn'6Hu_셟/fY,c]ZCeԻoj! CژI'PD@7e҅K}ݲ<8+á?e>Aj?>xB (^3.0 _zJs(^2= 1,J@OKyOyotӧ)&R,?{ǧW# 2&XO%,nA gxܚTb|z&K7s cnaZ0֤1‡ql4ڤ9˕^+r@"2f鑚b7R2& ܅!ㄴ UR ^ε~|_ε~`=wARyhL+ DYGbѺg./|ҫ ~\_tn.{u4lHEdTzo W1>C<-Mw>ad|߰?z41S7ݾ{-muA6ߙ70UZ|XpwMvf:>H2ƃ$މ{(6AÔ0M`h.fn_s Ɗ :QG*^ܸDu {"K%CAz|mwwOq"k4=*xd4㑰7=O!OawuRrIhhѼ3IOF7/ )9W:c:{f‚vY3ɐ&tx~t!ي .B=ȃ򁬾sOdmxΑw}?\$Q";-`_'Ԕ"b,XؿUTs.S/"t|/}Mv+/Ÿ%e8"lj ./x!Se'd_/~f(a̶SYQZBJ*uhv+yc2v=;ZO~(q/r4<CM.0 "~v=WnؘTA=J<덽+%Q} '48|Zנ/%=%jx+ӗNK%%u&u%8hAЗB_H_r4/%QK/Y6$}{IЗo%ї}bzCxЗüB_8/ } 9%З^߹?5M_B_9SS[_2to7FH$﵏HrRAB #ܜ/j?@_ ^Dy Y|z~Vv2E-ȣ @}OmDQI+_HnF ɏϕP=:dM_̹ay;v~" GxWmOD/H;ϣeg=;4vVd='@O+3YLل`o즪;Sc ҹͪQW7Q7K+f7Л!>+\)9DA ~Ӈ3;5c>//C gϻzlje& ToAY/*1S¼B/zWE h2^W/.go^<(^=d?׋*j_IzBOX  =a# =y w z'}@ S~s~}=zQ+{.o~zzOҋE Akҋ dKlO/lzj]%ӋJsЋ>\E^^T3~^ԟ ?>Z/}=uzQzB/ZEh{e}>aGayo=Wx^$Qb5c_J/*4jЋC K>,KvyF#G%װpi컋dP>ȜljjˣMw@/h3iQ,3@)sGxq崃x-wO寯O<پRߟ֟&jQ?łNEmenFxBz},MݚєŲ7ZC+E?{]S߂~S\h&&Ҟ'Z =kzք}ZēEk$?=[B}"_("_("_("_(UqG8?N{{H~ET wlV4yX<ڍ}ܺUxz6m|u&=^B_M8o0jz/ {5cuޥ=!R} tt(r3Ok I{^1v*Marqsn9y6H|T-ycR2+ΉG`;4\q̭}|0cN3p{Yas.lwow ql'Tj׺#ϭe_<'~vyS PX_ƹאH)An. ;x'wFGoI3܍]o£Dwϙ'sI9y՜yy|yˇ74nDK8IehIx}m ڰ, $Pι!}q*֭뱤G?G݌K'yχU-[Et|Mt> aF \y7Q1H(W[>~sQ; %>h}wnr>C3JbG;3TQǑ {׸:'PGXA-L5c=\^v`$>ùxl7@WOK<5W !p*k,rVf$HGk;#lu/\"{׀&DyJX=G`yy[XBQpyoG;\um2%"l?Ĝy=ˏȪ47.taZoxysכl?Hi3+(^: yy/{˯^"%'*3 ^!Bl덹-[Y8Yd,v;3"Trvihñntݤ1;Ro4RoQ me#UK*cn_-t2 9}F/pl}K5^hi=gXnba!ވ57]vwdf4'), ('BMIN', '>f4'), ('BPA', '>f4'), ('CHAN', '>i4'), ('POL', '>i4')]) beams['BMIN'] = [0.1,0.1001,0.09999,0.099999] # arcseconds beams['BMAJ'] = [0.2,0.2001,0.1999,0.19999] beams['BPA'] = [45.1,45.101,45.102,45.099] # degrees beams['CHAN'] = [0,0,0,0] beams['POL'] = [0,0,0,0] beams = fits.BinTableHDU(beams) beam = Beam.from_fits_bintable(beams) npt.assert_almost_equal(beam.minor.to(u.arcsec).value, 0.10002226, decimal=4) npt.assert_almost_equal(beam.major.to(u.arcsec).value, 0.19999751, decimal=4) npt.assert_almost_equal(beam.pa.to(u.deg).value, 45.10050065568665, decimal=4) @pytest.mark.skipif("not HAS_CASA") def test_from_casa_image(): # Extract from tar import tarfile fname_tar = data_path("NGC0925.bima.mmom0.image.tar.gz") tar = tarfile.open(fname_tar) tar.extractall(path=data_dir) tar.close() fname = data_path("NGC0925.bima.mmom0.image") bima_casa_beam = Beam.from_casa_image(fname) def test_attach_to_header(): fname = data_path("NGC0925.bima.mmom0.fits.gz") hdr = fits.getheader(fname) hdr_copy = hdr.copy() del hdr_copy["BMAJ"], hdr_copy["BMIN"], hdr_copy["BPA"] bima_beam = Beam.from_fits_header(fname) new_hdr = bima_beam.attach_to_header(hdr_copy) npt.assert_equal(new_hdr["BMAJ"], hdr["BMAJ"]) npt.assert_equal(new_hdr["BMIN"], hdr["BMIN"]) npt.assert_equal(new_hdr["BPA"], hdr["BPA"]) def test_beam_projected_area(): distance = 250 * u.pc major = 0.1 * u.rad beam = Beam(major, major, 30 * u.deg) beam_sr = (major**2 * 2 * np.pi / (8 * np.log(2))).to(u.sr) assert_quantity_allclose(beam_sr.value * distance ** 2, beam.beam_projected_area(distance)) def test_jtok(): major = 0.1 * u.rad beam = Beam(major, major, 30 * u.deg) freq = 1.42 * u.GHz conv_factor = u.brightness_temperature(beam.sr, freq) assert_quantity_allclose((1 * u.Jy).to(u.K, equivalencies=conv_factor), beam.jtok(freq)) def test_jtok_equiv(): major = 0.1 * u.rad beam = Beam(major, major, 30 * u.deg) freq = 1.42 * u.GHz conv_factor = u.brightness_temperature(beam.sr, freq) conv_beam_factor = beam.jtok_equiv(freq) assert_quantity_allclose((1 * u.Jy).to(u.K, equivalencies=conv_factor), (1 * u.Jy).to(u.K, equivalencies=conv_beam_factor)) assert_quantity_allclose((1 * u.K).to(u.Jy, equivalencies=conv_factor), (1 * u.K).to(u.Jy, equivalencies=conv_beam_factor)) def test_convolution(): # equations from: # https://github.com/pkgw/carma-miriad/blob/CVSHEAD/src/subs/gaupar.for # (github checkin of MIRIAD, code by Sault) major1 = 1 * u.deg minor1 = 0.5 * u.deg pa1 = 0.0 * u.deg beam1 = Beam(major1, minor1, pa1) major2 = 1 * u.deg minor2 = 0.75 * u.deg pa2 = 90.0 * u.deg beam2 = Beam(major2, minor2, pa2) alpha = (major1 * np.cos(pa1))**2 + (minor1 * np.sin(pa1))**2 + \ (major2 * np.cos(pa2))**2 + (minor2 * np.sin(pa2))**2 beta = (major1 * np.sin(pa1))**2 + (minor1 * np.cos(pa1))**2 + \ (major2 * np.sin(pa2))**2 + (minor2 * np.cos(pa2))**2 gamma = 2 * ((minor1**2 - major1**2) * np.sin(pa1) * np.cos(pa1) + (minor2**2 - major2**2) * np.sin(pa2) * np.cos(pa2)) s = alpha + beta t = np.sqrt((alpha - beta)**2 + gamma**2) conv_major = np.sqrt(0.5 * (s + t)) conv_minor = np.sqrt(0.5 * (s - t)) conv_pa = 0.5 * np.arctan2(- gamma, alpha - beta) conv_beam = beam1.convolve(beam2) assert_quantity_allclose(conv_major, conv_beam.major) assert_quantity_allclose(conv_minor, conv_beam.minor) assert_quantity_allclose(conv_pa, conv_beam.pa) def test_deconvolution(): # equations from: # https://github.com/pkgw/carma-miriad/blob/CVSHEAD/src/subs/gaupar.for # (github checkin of MIRIAD, code by Sault) major1 = 2.0 * u.deg minor1 = 1.0 * u.deg pa1 = 45.0 * u.deg beam1 = Beam(major1, minor1, pa1) major2 = 1 * u.deg minor2 = 0.5 * u.deg pa2 = 0.0 * u.deg beam2 = Beam(major2, minor2, pa2) alpha = (major1 * np.cos(pa1))**2 + (minor1 * np.sin(pa1))**2 - \ (major2 * np.cos(pa2))**2 - (minor2 * np.sin(pa2))**2 beta = (major1 * np.sin(pa1))**2 + (minor1 * np.cos(pa1))**2 - \ (major2 * np.sin(pa2))**2 - (minor2 * np.cos(pa2))**2 gamma = 2 * ((minor1**2 - major1**2) * np.sin(pa1) * np.cos(pa1) + (minor2**2 - major2**2) * np.sin(pa2) * np.cos(pa2)) s = alpha + beta t = np.sqrt((alpha - beta)**2 + gamma**2) deconv_major = np.sqrt(0.5 * (s + t)) deconv_minor = np.sqrt(0.5 * (s - t)) deconv_pa = 0.5 * np.arctan2(- gamma, alpha - beta) deconv_beam = beam1.deconvolve(beam2) assert_quantity_allclose(deconv_major, deconv_beam.major) assert_quantity_allclose(deconv_minor, deconv_beam.minor) assert_quantity_allclose(deconv_pa, deconv_beam.pa) def test_conv_deconv(): beam1 = Beam(10. * u.arcsec, 5. * u.arcsec, 30. * u.deg) beam2 = Beam(5. * u.arcsec, 3. * u.arcsec, 120. * u.deg) beam3 = beam1.convolve(beam2) assert beam2 == beam3.deconvolve(beam1) assert beam1 == beam3.deconvolve(beam2) assert beam1.convolve(beam2) == beam2.convolve(beam1) # Test multiplication and subtraction (i.e., convolution and deconvolution) # subtraction-as-deconvolution is deprecated. Check that one of the gives # the warning with warnings.catch_warnings(record=True) as w: assert beam2 == beam3 - beam1 assert len(w) == 1 assert w[0].category == RadioBeamDeprecationWarning assert str(w[0].message) == ("Subtraction-as-deconvolution is deprecated. " "Use division instead.") # Dividing should give the same thing assert beam2 == beam3 / beam1 assert beam1 == beam3 / beam2 assert beam3 == beam1 * beam2 @pytest.mark.parametrize(('major', 'minor', 'pa', 'return_pointlike'), [[maj, min, pa, ret] for maj, min, pa, ret in product([10], np.arange(1, 11), np.linspace(0, 180, 10), [True, False])]) def test_deconv_pointlike(major, minor, pa, return_pointlike): beam1 = Beam(major * u.arcsec, major * u.arcsec, pa * u.deg) if return_pointlike: point_beam = Beam(0 * u.deg, 0 * u.deg, 0 * u.deg) point_beam == beam1.deconvolve(beam1, failure_returns_pointlike=True) else: try: beam1.deconvolve(beam1, failure_returns_pointlike=False) except ValueError: pass def test_isfinite(): beam1 = Beam(10. * u.arcsec, 5. * u.arcsec, 30. * u.deg) assert beam1.isfinite # raises an exception because major < minor #beam2 = Beam(-10. * u.arcsec, 5. * u.arcsec, 30. * u.deg) #assert not beam2.isfinite beam3 = Beam(10. * u.arcsec, -5. * u.arcsec, 30. * u.deg) assert not beam3.isfinite @pytest.mark.parametrize(("major", "minor", "pa"), [(10, 10, 60), (10, 10, -120), (10, 10, -300), (10, 10, 240), (10, 10, 59), (10, 10, -121)]) def test_beam_equal(major, minor, pa): beam1 = Beam(10 * u.deg, 10 * u.deg, 60 * u.deg) beam2 = Beam(major * u.deg, minor * u.deg, pa * u.deg) assert beam1 == beam2 assert not beam1 != beam2 @pytest.mark.parametrize(("major", "minor", "pa"), [(10, 8, 60), (10, 8, -120), (10, 8, 240)]) def test_beam_equal_noncirc(major, minor, pa): ''' Beams with PA +/- 180 deg are equal ''' beam1 = Beam(10 * u.deg, 8 * u.deg, 60 * u.deg) beam2 = Beam(major * u.deg, minor * u.deg, pa * u.deg) assert beam1 == beam2 assert not beam1 != beam2 @pytest.mark.parametrize(("major", "minor", "pa"), [(10, 8, 60), (12, 10, 60), (12, 10, 59)]) def test_beam_not_equal(major, minor, pa): beam1 = Beam(10 * u.deg, 10 * u.deg, 60 * u.deg) beam2 = Beam(major * u.deg, minor * u.deg, pa * u.deg) assert beam1 != beam2 def test_from_aips_issue43(): """ regression test for issue 43 """ aips_fname = data_path("header_aips.hdr") aips_hdr = fits.Header.fromtextfile(aips_fname) aips_beam_hdr = Beam.from_fits_header(aips_hdr) npt.assert_almost_equal(aips_beam_hdr.pa.value, -15.06) def test_small_beam_convolution(): # regression test for #68 beam1 = Beam((0.1*u.arcsec).to(u.deg), (0.00001*u.arcsec).to(u.deg), 30*u.deg) beam2 = Beam((0.3*u.arcsec).to(u.deg), (0.00001*u.arcsec).to(u.deg), 120*u.deg) conv = beam1.convolve(beam2) np.testing.assert_almost_equal(conv.pa.to(u.deg).value, -60) def test_major_minor_swap(): with pytest.raises(ValueError) as exc: beam1 = Beam(minor=10. * u.arcsec, major=5. * u.arcsec, pa=30. * u.deg) assert "Minor axis greater than major axis." in exc.value.args[0] radio_beam-0.3.2/radio_beam/tests/test_beams.py0000644000077000000240000004544113516112474021557 0ustar adamstaff00000000000000import numpy as np import numpy.testing as npt from astropy import units as u from astropy.io import fits import warnings import pytest from ..multiple_beams import Beams from ..beam import Beam from ..commonbeam import common_2beams, common_manybeams_mve from ..utils import InvalidBeamOperationError from .test_beam import data_path def symm_beams_for_tests(): majors = [1, 1, 1, 2, 3, 4] * u.arcsec minors = majors pas = [0] * 6 * u.deg return Beams(major=majors, minor=minors, pa=pas), majors, minors, pas def asymm_beams_for_tests(): majors = [1, 1, 1, 2, 3, 4] * u.arcsec minors = majors / 2. pas = [-36, 20, 80, 41, -82, 11] * u.deg return Beams(major=majors, minor=minors, pa=pas), majors, minors, pas def load_commonbeam_comparisons(): common_beams = np.loadtxt(data_path("commonbeam_CASA_comparison.csv"), delimiter=',') return common_beams def test_beam_areas(): beams, majors = symm_beams_for_tests()[:2] areas = 2 * np.pi / (8 * np.log(2)) * (majors.to(u.rad)**2).to(u.sr) assert np.all(areas.value == beams.sr.value) assert np.all(beams.value == beams.sr.value) def test_beams_from_fits_bintable(): fname = data_path("m33_beams_bintable.fits.gz") bintable = fits.open(fname)[1] beams = Beams.from_fits_bintable(bintable) assert (beams.major.value == bintable.data['BMAJ']).all() assert (beams.minor.value == bintable.data['BMIN']).all() assert (beams.pa.value == bintable.data['BPA']).all() def test_beams_from_list_of_beam(): beams, majors = symm_beams_for_tests()[:2] new_beams = Beams(beams=[beam for beam in beams]) assert beams == new_beams def test_beams_equality_beams(): beams, majors = symm_beams_for_tests()[:2] assert beams == beams assert not beams != beams abeams, amajors = asymm_beams_for_tests()[:2] assert not (beams == abeams) assert beams != abeams def test_beams_equality_beam(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) beam = Beam(1 * u.arcsec) assert np.all(beams == beam) assert not np.any(beams != beam) @pytest.mark.xfail(raises=InvalidBeamOperationError, strict=True) def test_beams_equality_fail(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) beams == 2 @pytest.mark.xfail(raises=InvalidBeamOperationError, strict=True) def test_beams_notequality_fail(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) beams != 2 @pytest.mark.xfail(raises=InvalidBeamOperationError, strict=True) def test_beams_equality_fail_shape(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) assert np.all(beams == beams[1:]) @pytest.mark.xfail(raises=InvalidBeamOperationError, strict=True) def test_beams_add_fail(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) beams + 2 @pytest.mark.xfail(raises=InvalidBeamOperationError, strict=True) def test_beams_sub_fail(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) beams - 2 @pytest.mark.xfail(raises=InvalidBeamOperationError, strict=True) def test_beams_mult_fail(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) beams * 2 @pytest.mark.xfail(raises=InvalidBeamOperationError, strict=True) def test_beams_div_fail(): # Test whether all are equal to a single beam beams = Beams([1.] * 5 * u.arcsec) beams / 2 def test_beams_mult_convolution(): beams, majors = asymm_beams_for_tests()[:2] beam = Beam(1 * u.arcsec) conv_beams = beams * beam individ_conv_beams = [beam_i.convolve(beam) for beam_i in beams] new_beams = Beams(beams=individ_conv_beams) assert conv_beams == new_beams def test_beams_div_deconvolution(): beams, majors = asymm_beams_for_tests()[:2] beam = Beam(0.25 * u.arcsec) deconv_beams = beams / beam individ_deconv_beams = [beam_i.deconvolve(beam) for beam_i in beams] new_beams = Beams(beams=individ_deconv_beams) assert deconv_beams == new_beams def test_indexing(): beams, majors = symm_beams_for_tests()[:2] assert hasattr(beams[slice(0, 3)], 'major') assert np.all(beams[slice(0, 3)].major.value == majors[:3].value) assert np.all(beams[slice(0, 3)].minor.value == majors[:3].value) assert hasattr(beams[:3], 'major') assert np.all(beams[:3].major.value == majors[:3].value) assert np.all(beams[:3].minor.value == majors[:3].value) assert hasattr(beams[3], 'major') assert beams[3].major.value == 2 assert beams[3].minor.value == 2 assert isinstance(beams[4], Beam) # Also test int64 chan = np.int64(3) assert hasattr(beams[chan], 'major') assert beams[chan].major.value == 2 assert beams[chan].minor.value == 2 assert isinstance(beams[chan], Beam) mask = np.array([True, False, True, False, True, True], dtype='bool') assert hasattr(beams[mask], 'major') assert np.all(beams[mask].major.value == majors[mask].value) def test_average_beams(): beams, majors = symm_beams_for_tests()[:2] assert np.all(beams.average_beam().major.value == majors.mean().value) mask = np.array([True, False, True, False, True, True], dtype='bool') assert np.all(beams[mask].average_beam().major.value == majors[mask].mean().value) @pytest.mark.parametrize(("beams", "majors", "minors", "pas"), [symm_beams_for_tests(), asymm_beams_for_tests()]) def test_largest_beams(beams, majors, minors, pas): assert beams.largest_beam().major.value == majors.max().value assert beams.largest_beam().minor.value == minors.max().value # Slice the object mask = np.array([True, False, True, False, True, True], dtype='bool') assert beams[mask].largest_beam().major.value == majors[mask].max().value assert beams[mask].largest_beam().minor.value == minors[mask].max().value # Apply a mask only for the operation assert beams.largest_beam(mask).major.value == majors[mask].max().value assert beams.largest_beam(mask).minor.value == minors[mask].max().value @pytest.mark.parametrize(("beams", "majors", "minors", "pas"), [symm_beams_for_tests(), asymm_beams_for_tests()]) def test_smallest_beams(beams, majors, minors, pas): assert beams.smallest_beam().major.value == majors.min().value assert beams.smallest_beam().minor.value == minors.min().value # Slice the object mask = np.array([True, False, True, False, True, True], dtype='bool') assert beams[mask].smallest_beam().major.value == majors[mask].min().value assert beams[mask].smallest_beam().minor.value == minors[mask].min().value # Apply a mask only for the operation assert beams.smallest_beam(mask).major.value == majors[mask].min().value assert beams.smallest_beam(mask).minor.value == minors[mask].min().value @pytest.mark.parametrize(("beams", "majors", "minors", "pas"), [symm_beams_for_tests(), asymm_beams_for_tests()]) def test_extrema_beams(beams, majors, minors, pas): extrema = beams.extrema_beams() assert extrema[0].major.value == majors.min().value assert extrema[0].minor.value == minors.min().value assert extrema[1].major.value == majors.max().value assert extrema[1].minor.value == minors.max().value # Slice the object mask = np.array([True, False, True, False, True, True], dtype='bool') extrema = beams[mask].extrema_beams() assert extrema[0].major.value == majors[mask].min().value assert extrema[0].minor.value == minors[mask].min().value assert extrema[1].major.value == majors[mask].max().value assert extrema[1].minor.value == minors[mask].max().value # Apply a mask only for the operation extrema = beams.extrema_beams(mask) assert extrema[0].major.value == majors[mask].min().value assert extrema[0].minor.value == minors[mask].min().value assert extrema[1].major.value == majors[mask].max().value assert extrema[1].minor.value == minors[mask].max().value @pytest.mark.parametrize("majors", [[1, 1, 1, 2, np.NaN, 4], [0, 1, 1, 2, 3, 4]]) def test_beams_with_invalid(majors): majors = np.asarray(majors) * u.arcsec beams = Beams(major=majors) # Average assert beams.average_beam().major.value == np.nanmean( majors[np.nonzero(majors)]).value # Largest assert beams.largest_beam().major.value == np.nanmax(majors).value # Smallest assert beams.smallest_beam().major.value == np.nanmin( majors[np.nonzero(majors)]).value # Extrema extrema = beams.extrema_beams() assert extrema[0].major.value == np.nanmin( majors[np.nonzero(majors)]).value assert extrema[1].major.value == np.nanmax(majors).value # Additional masking mask = np.array([True, False, True, False, True, True], dtype='bool') if np.isnan(majors).any(): bad_mask = np.isfinite(majors) else: bad_mask = majors.value != 0 combined_mask = np.logical_and(mask, bad_mask) # Average assert beams[mask].average_beam().major.value == np.nanmean( majors[combined_mask]).value # Largest assert beams[mask].largest_beam().major.value == np.nanmax( majors[combined_mask]).value # Smallest assert beams[mask].smallest_beam().major.value == np.nanmin( majors[combined_mask]).value # Extrema extrema = beams[mask].extrema_beams() assert extrema[0].major.value == np.nanmin(majors[combined_mask]).value assert extrema[1].major.value == np.nanmax(majors[combined_mask]).value def test_beams_iter(): beams, majors = symm_beams_for_tests()[:2] # Ensure iterating through yields the same as slicing for i, beam in enumerate(beams): assert beam == beams[i] # @pytest.mark.parametrize('comp_vals', # [vals for vals in load_commonbeam_comparisons()]) # def test_commonbeam_casa_compare(comp_vals): # # These are the common beam parameters assuming 2 beams: # # 1) 3"x3" # # 2) 4"x2.5", varying the PA in 1 deg increments from 0 to 179 deg # # See data/generate_commonbeam_table.py # pa, com_major, com_minor, com_pa = comp_vals # beams = Beams(major=[3, 4] * u.arcsec, minor=[3, 2.5] * u.arcsec, # pa=[0, pa] * u.deg) # common_beam = beams.common_beam() # # npt.assert_almost_equal(common_beam.major.value, com_major) # # npt.assert_almost_equal(common_beam.minor.value, com_minor) # npt.assert_almost_equal(common_beam.pa.to(u.deg).value, com_pa) # npt.assert_almost_equal(common_beam.pa.to(u.deg).value, pa) def test_common_beam_smallcircular(): ''' Simple solution if the smallest beam is circular with a radius larger: Major axis is from the largest beam, minor axis is the radius of the smaller, and the PA is from the largest beam. ''' for pa in [0., 18., 68., 122.]: beams = Beams(major=[3, 4] * u.arcsec, minor=[3, 2.5] * u.arcsec, pa=[0, pa] * u.deg) targ_beam = Beam(4 * u.arcsec, 3 * u.arcsec, pa * u.deg) assert targ_beam == beams.common_beam() def test_commonbeam_notlargest(): beams = Beams(major=[3, 4] * u.arcsec, minor=[3, 2.5] * u.arcsec) target_beam = Beam(major=4 * u.arcsec, minor=3 * u.arcsec) assert beams.common_beam() == target_beam def test_commonbeam_largest(): ''' commonbeam is the largest in this set. ''' beams, majors = symm_beams_for_tests()[:2] assert beams.common_beam() == beams.largest_beam() # With masking mask = np.array([True, False, True, True, True, False], dtype='bool') assert beams[mask].common_beam() == beams[mask].largest_beam() assert beams.common_beam(mask) == beams.largest_beam(mask) # Implements the same test suite used in CASA def casa_commonbeam_suite(): cases = [] # https://open-bitbucket.nrao.edu/projects/CASA/repos/casa/browse/code/imageanalysis/ImageAnalysis/test/tCasaImageBeamSet.cc # In some cases, I find smaller common beams than are listed in the CASA # tests. The values for the CASA tests are commented out. # 1 cases.append((Beams(major=[4] * 2 * u.arcsec, minor=[2] * 2 * u.arcsec, pa=[0, 60] * u.deg), Beam(major=4.4812 * u.arcsec, minor=3.2883 * u.arcsec, pa=30.0 * u.deg))) # Beam(major=4.4856 * u.arcsec, minor=3.2916 * u.arcsec, # pa=30.0 * u.deg))) # 2 cases.append((Beams(major=[4] * 2 * u.arcsec, minor=[2] * 2 * u.arcsec, pa=[20, 80] * u.deg), Beam(major=4.4812 * u.arcsec, minor=3.2883 * u.arcsec, pa=50.0 * u.deg))) # Beam(major=4.4856 * u.arcsec, minor=3.2916 * u.arcsec, # pa=50.0 * u.deg))) # 3 cases.append((Beams(major=[4] * 2 * u.arcsec, minor=[2] * 2 * u.arcsec, pa=[1, 89] * u.deg), Beam(major=4.042 * u.arcsec, minor=3.958 * u.arcsec, pa=45.0 * u.deg))) # 4 cases.append((Beams(major=[4] * 2 * u.arcsec, minor=[2] * 2 * u.arcsec, pa=[0, 90] * u.deg), Beam(major=4 * u.arcsec, minor=4 * u.arcsec, pa=0.0 * u.deg))) # 5 cases.append((Beams(major=[4, 1.5] * u.arcsec, minor=[2, 1] * u.arcsec, pa=[0, 90] * u.deg), Beam(major=4 * u.arcsec, minor=2 * u.arcsec, pa=0.0 * u.deg))) # 6 cases.append((Beams(major=[8, 4] * u.arcsec, minor=[1, 1] * u.arcsec, pa=[0, 20] * u.deg), Beam(major=8.3684 * u.arcsec, minor=1.6253 * u.arcsec, pa=2.7679 * u.deg))) # Beam(major=8.377 * u.arcsec, minor=1.628 * u.arcsec, # pa=2.7679 * u.deg))) # 7 cases.append((Beams(major=[4, 8] * u.arcsec, minor=[1, 1] * u.arcsec, pa=[0, 20] * u.deg), Beam(major=8.369 * u.arcsec, minor=1.626 * u.arcsec, pa=17.232 * u.deg))) # 10 cases.append((Beams(major=[4, 1] * u.arcsec, minor=[2, 1] * u.arcsec, pa=[0, 0] * u.deg), Beam(major=4 * u.arcsec, minor=2 * u.arcsec, pa=0.0 * u.deg))) return cases @pytest.mark.parametrize(("beams", "target_beam"), casa_commonbeam_suite()) def test_commonbeam_angleoffset(beams, target_beam): # https://open-bitbucket.nrao.edu/projects/CASA/repos/casa/browse/code/imageanalysis/ImageAnalysis/test/tCasaImageBeamSet.cc#447 common_beam = beams.common_beam() # Order shouldn't matter common_beam_rev = beams[::-1].common_beam() assert common_beam == common_beam_rev npt.assert_allclose(common_beam.major.value, target_beam.major.value, rtol=1e-3) npt.assert_allclose(common_beam.minor.value, target_beam.minor.value, rtol=1e-3) npt.assert_allclose(common_beam.pa.to(u.deg).value, target_beam.pa.value, rtol=1e-3) def casa_commonbeam_suite_multiple(): cases = [] # 8 cases.append((Beams(major=[4] * 4 * u.arcsec, minor=[2] * 4 * u.arcsec, pa=[0, 60, 20, 40] * u.deg), Beam(major=4.48904471492 * u.arcsec, minor=3.28268221138 * u.arcsec, pa=30.0001561178 * u.deg))) # This is the beam size in the CASA tests. The MVE method finds a slightly # smaller beam area, so that's what is tested against above and below. # Beam(major=4.485 * u.arcsec, minor=3.291 * u.arcsec, # pa=30 * u.deg))) # 9 cases.append((Beams(major=[4] * 4 * u.arcsec, minor=[2] * 4 * u.arcsec, pa=[0, 20, 40, 60] * u.deg), Beam(major=4.48904471492 * u.arcsec, minor=3.28268221138 * u.arcsec, pa=30.0001561178 * u.deg))) return cases @pytest.mark.parametrize(("beams", "target_beam"), casa_commonbeam_suite_multiple()) def test_commonbeam_multiple(beams, target_beam): # https://open-bitbucket.nrao.edu/projects/CASA/repos/casa/browse/code/imageanalysis/ImageAnalysis/test/tCasaImageBeamSet.cc#447 common_beam = beams.common_beam(epsilon=1e-4) # The above should be using the MVE method common_beam_check = common_manybeams_mve(beams, epsilon=1e-4) assert common_beam == common_beam_check npt.assert_almost_equal(common_beam.major.to(u.arcsec).value, target_beam.major.value, decimal=6) npt.assert_almost_equal(common_beam.minor.to(u.arcsec).value, target_beam.minor.value, decimal=6) npt.assert_almost_equal(common_beam.pa.to(u.deg).value, target_beam.pa.value, decimal=6) @pytest.mark.parametrize(("beams", "target_beam"), casa_commonbeam_suite()) def test_commonbeam_methods(beams, target_beam): epsilon = 5e-4 tolerance = 1e-4 two_beam_method = common_2beams(beams) many_beam_method = common_manybeams_mve(beams, epsilon=epsilon, tolerance=tolerance) # Good to ~5x the given epsilon npt.assert_allclose(two_beam_method.major.to(u.arcsec).value, many_beam_method.major.to(u.arcsec).value, rtol=3e-3) npt.assert_allclose(two_beam_method.minor.to(u.arcsec).value, many_beam_method.minor.to(u.arcsec).value, rtol=3e-3) # Only test if the beam is circ_check = not two_beam_method.iscircular(rtol=3e-3) or \ not many_beam_method.iscircular(rtol=3e-3) if circ_check: # The pa can be sensitive to small changes so give it a larger # acceptable tolerance range. npt.assert_allclose(two_beam_method.pa.to(u.deg).value, many_beam_method.pa.to(u.deg).value, rtol=5e-3) def test_catch_common_beam_opt(): ''' The optimization method is close to working, but requires more testing. Ensure it cannot be used. ''' beams = Beams(major=[4] * 4 * u.arcsec, minor=[2] * 4 * u.arcsec, pa=[0, 20, 40, 60] * u.deg) with pytest.raises(NotImplementedError): beams.common_beam(method='opt') def test_major_minor_swap(): with pytest.raises(ValueError) as exc: beams = Beams(minor=[10.,5.] * u.arcsec, major=[5., 5.] * u.arcsec, pa=[30., 60.] * u.deg) assert "Minor axis greater than major axis." in exc.value.args[0] radio_beam-0.3.2/radio_beam/tests/test_kernels.py0000644000077000000240000000266412730445735022141 0ustar adamstaff00000000000000# Licensed under a 3-clause BSD style license - see LICENSE.rst from .. import beam as radio_beam from astropy import units as u import numpy.testing as npt import numpy as np import pytest from pkg_resources import parse_version from astropy.version import version SIGMA_TO_FWHM = radio_beam.SIGMA_TO_FWHM min_astropy_version = parse_version("1.1") @pytest.mark.skipif(parse_version(version) < min_astropy_version, reason="Must have astropy version >1.1") def test_gauss_kernel(): fake_beam = radio_beam.Beam(10) # Let pixscale be 0.1 deg/pix kernel = fake_beam.as_kernel(0.1*u.deg) direct_kernel = \ radio_beam.EllipticalGaussian2DKernel(100. / SIGMA_TO_FWHM, 100. / SIGMA_TO_FWHM, 0.0) npt.assert_allclose(kernel.array, direct_kernel.array) @pytest.mark.skipif(parse_version(version) < min_astropy_version, reason="Must have astropy version >1.1") def test_tophat_kernel(): fake_beam = radio_beam.Beam(10) # Let pixscale be 0.1 deg/pix kernel = fake_beam.as_tophat_kernel(0.1*u.deg) direct_kernel = \ radio_beam.EllipticalTophat2DKernel(100. / (SIGMA_TO_FWHM/np.sqrt(2)), 100. / (SIGMA_TO_FWHM/np.sqrt(2)), 0.0) npt.assert_allclose(kernel.array, direct_kernel.array) radio_beam-0.3.2/radio_beam/utils.py0000644000077000000240000001563013420163703017417 0ustar adamstaff00000000000000 import numpy as np import astropy.units as u class BeamError(Exception): """docstring for BeamError""" pass class InvalidBeamOperationError(Exception): pass class RadioBeamDeprecationWarning(Warning): pass def deconvolve(beam, other, failure_returns_pointlike=False): """ Deconvolve a beam from another Parameters ---------- beam : `Beam` The defined beam. other : `Beam` The beam to deconvolve from this beam failure_returns_pointlike : bool Option to return a pointlike beam (i.e., one with major=minor=0) if the second beam is larger than the first. Otherwise, a ValueError will be raised Returns ------- new_beam : `Beam` The convolved Beam Raises ------ failure : ValueError If the second beam is larger than the first, the default behavior is to raise an exception. This can be overridden with failure_returns_pointlike """ # blame: https://github.com/pkgw/carma-miriad/blob/CVSHEAD/src/subs/gaupar.for # (githup checkin of MIRIAD, code by Sault) # rename to shorter variables for readability maj1, min1, pa1 = beam.major, beam.minor, beam.pa maj2, min2, pa2 = other.major, other.minor, other.pa cos, sin = np.cos, np.sin alpha = ((maj1 * cos(pa1))**2 + (min1 * sin(pa1))**2 - (maj2 * cos(pa2))**2 - (min2 * sin(pa2))**2) beta = ((maj1 * sin(pa1))**2 + (min1 * cos(pa1))**2 - (maj2 * sin(pa2))**2 - (min2 * cos(pa2))**2) gamma = 2 * ((min1**2 - maj1**2) * sin(pa1) * cos(pa1) - (min2**2 - maj2**2) * sin(pa2) * cos(pa2)) s = alpha + beta t = np.sqrt((alpha - beta)**2 + gamma**2) # identify the smallest resolution axes = np.array([maj1.to(u.deg).value, min1.to(u.deg).value, maj2.to(u.deg).value, min2.to(u.deg).value]) * u.deg limit = np.min(axes) limit = 0.1 * limit * limit # Deal with floating point issues atol_t = np.finfo(t.dtype).eps * t.unit # To deconvolve, the beam must satisfy: # alpha < 0 alpha_cond = alpha.to(u.arcsec**2).value + np.finfo(alpha.dtype).eps < 0 # beta < 0 beta_cond = beta.to(u.arcsec**2).value + np.finfo(beta.dtype).eps < 0 # s < t st_cond = s < t + atol_t if alpha_cond or beta_cond or st_cond: if failure_returns_pointlike: return 0 * maj1.unit, 0 * min1.unit, 0 * pa1.unit else: raise ValueError("Beam could not be deconvolved") else: new_major = np.sqrt(0.5 * (s + t)) new_minor = np.sqrt(0.5 * (s - t)) # absolute tolerance needs to be <<1 microarcsec if np.isclose(((abs(gamma) + abs(alpha - beta))**0.5).to(u.arcsec).value, 1e-7): new_pa = 0.0 else: new_pa = 0.5 * np.arctan2(-1. * gamma, alpha - beta) # In the limiting case, the axes can be zero to within precision # Add the precision level onto each axis so a deconvolvable beam # is always has beam.isfinite == True new_major += np.finfo(new_major.dtype).eps * new_major.unit new_minor += np.finfo(new_minor.dtype).eps * new_minor.unit return new_major, new_minor, new_pa def convolve(beam, other): """ Convolve one beam with another. Parameters ---------- other : `Beam` The beam to convolve with Returns ------- new_beam : `Beam` The convolved Beam """ # blame: https://github.com/pkgw/carma-miriad/blob/CVSHEAD/src/subs/gaupar.for # (github checkin of MIRIAD, code by Sault) alpha = ((beam.major * np.cos(beam.pa))**2 + (beam.minor * np.sin(beam.pa))**2 + (other.major * np.cos(other.pa))**2 + (other.minor * np.sin(other.pa))**2) beta = ((beam.major * np.sin(beam.pa))**2 + (beam.minor * np.cos(beam.pa))**2 + (other.major * np.sin(other.pa))**2 + (other.minor * np.cos(other.pa))**2) gamma = (2 * ((beam.minor**2 - beam.major**2) * np.sin(beam.pa) * np.cos(beam.pa) + (other.minor**2 - other.major**2) * np.sin(other.pa) * np.cos(other.pa))) s = alpha + beta t = np.sqrt((alpha - beta)**2 + gamma**2) new_major = np.sqrt(0.5 * (s + t)) new_minor = np.sqrt(0.5 * (s - t)) # absolute tolerance needs to be <<1 microarcsec if np.isclose(((abs(gamma) + abs(alpha - beta))**0.5).to(u.arcsec).value, 1e-7): new_pa = 0.0 * u.deg else: new_pa = 0.5 * np.arctan2(-1. * gamma, alpha - beta) return new_major, new_minor, new_pa def transform_ellipse(major, minor, pa, x_scale, y_scale): ''' Transform an ellipse by scaling in the x and y axes. Parameters ---------- major : `~astropy.units.Quantity` Major axis. minor : `~astropy.units.Quantity` Minor axis. pa : `~astropy.units.Quantity` PA of the major axis. x_scale : float x axis scaling factor. y_scale : float y axis scaling factor. Returns ------- trans_major : `~astropy.units.Quantity` Major axis in the transformed frame. trans_minor : `~astropy.units.Quantity` Minor axis in the transformed frame. trans_pa : `~astropy.units.Quantity` PA of the major axis in the transformed frame. ''' # This code is based on the implementation in CASA: # https://open-bitbucket.nrao.edu/projects/CASA/repos/casa/browse/code/imageanalysis/ImageAnalysis/CasaImageBeamSet.cc major = major.to(u.arcsec) minor = minor.to(u.arcsec) pa = pa.to(u.rad) cospa = np.cos(pa) sinpa = np.sin(pa) cos2pa = cospa**2 sin2pa = sinpa**2 major2 = major**2 minor2 = minor**2 a = (cos2pa / major2) + (sin2pa / minor2) b = -2 * cospa * sinpa * (major2**-1 - minor2**-1) c = (sin2pa / major2) + (cos2pa / minor2) x2_scale = x_scale**2 y2_scale = y_scale**2 r = a / x2_scale s = b**2 / (4 * x2_scale * y2_scale) t = c / y2_scale udiff = r - t u2 = udiff**2 f1 = u2 + 4 * s f2 = np.sqrt(f1) * np.abs(udiff) j1 = (f2 + f1) / f1 / 2 j2 = (f1 - f2) / f1 / 2 k1 = (j1 * r + j1 * t - t) / (2 * j1 - 1) k2 = (j2 * r + j2 * t - t) / (2 * j2 - 1) c1 = np.sqrt(k1)**-1 c2 = np.sqrt(k2)**-1 pa_sign = 1 if pa.value >= 0 else -1 if c1 == c2: # Transformed to a circle trans_major = 1 / c1 trans_minor = trans_major trans_pa = 0 elif c1 > c2: # c1 and c2 are the major and minor axes; use j1 to get PA trans_major = c1 trans_minor = c2 trans_pa = pa_sign * np.arccos(np.sqrt(j1)) else: # Opposite case where the axes are switched; get PA from j2 trans_major = c2 trans_minor = c1 trans_pa = pa_sign * np.arccos(np.sqrt(j2)) return trans_major, trans_minor, trans_pa radio_beam-0.3.2/radio_beam/version.py0000644000077000000240000001626313531324213017745 0ustar adamstaff00000000000000# Autogenerated by Astropy-affiliated package radio_beam's setup.py on 2019-08-27 22:02:51 UTC from __future__ import unicode_literals import datetime import locale import os import subprocess import warnings def _decode_stdio(stream): try: stdio_encoding = locale.getdefaultlocale()[1] or 'utf-8' except ValueError: stdio_encoding = 'utf-8' try: text = stream.decode(stdio_encoding) except UnicodeDecodeError: # Final fallback text = stream.decode('latin1') return text def update_git_devstr(version, path=None): """ Updates the git revision string if and only if the path is being imported directly from a git working copy. This ensures that the revision number in the version string is accurate. """ try: # Quick way to determine if we're in git or not - returns '' if not devstr = get_git_devstr(sha=True, show_warning=False, path=path) except OSError: return version if not devstr: # Probably not in git so just pass silently return version if 'dev' in version: # update to the current git revision version_base = version.split('.dev', 1)[0] devstr = get_git_devstr(sha=False, show_warning=False, path=path) return version_base + '.dev' + devstr else: # otherwise it's already the true/release version return version def get_git_devstr(sha=False, show_warning=True, path=None): """ Determines the number of revisions in this repository. Parameters ---------- sha : bool If True, the full SHA1 hash will be returned. Otherwise, the total count of commits in the repository will be used as a "revision number". show_warning : bool If True, issue a warning if git returns an error code, otherwise errors pass silently. path : str or None If a string, specifies the directory to look in to find the git repository. If `None`, the current working directory is used, and must be the root of the git repository. If given a filename it uses the directory containing that file. Returns ------- devversion : str Either a string with the revision number (if `sha` is False), the SHA1 hash of the current commit (if `sha` is True), or an empty string if git version info could not be identified. """ if path is None: path = os.getcwd() if not os.path.isdir(path): path = os.path.abspath(os.path.dirname(path)) if sha: # Faster for getting just the hash of HEAD cmd = ['rev-parse', 'HEAD'] else: cmd = ['rev-list', '--count', 'HEAD'] def run_git(cmd): try: p = subprocess.Popen(['git'] + cmd, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdout, stderr = p.communicate() except OSError as e: if show_warning: warnings.warn('Error running git: ' + str(e)) return (None, b'', b'') if p.returncode == 128: if show_warning: warnings.warn('No git repository present at {0!r}! Using ' 'default dev version.'.format(path)) return (p.returncode, b'', b'') if p.returncode == 129: if show_warning: warnings.warn('Your git looks old (does it support {0}?); ' 'consider upgrading to v1.7.2 or ' 'later.'.format(cmd[0])) return (p.returncode, stdout, stderr) elif p.returncode != 0: if show_warning: warnings.warn('Git failed while determining revision ' 'count: {0}'.format(_decode_stdio(stderr))) return (p.returncode, stdout, stderr) return p.returncode, stdout, stderr returncode, stdout, stderr = run_git(cmd) if not sha and returncode == 128: # git returns 128 if the command is not run from within a git # repository tree. In this case, a warning is produced above but we # return the default dev version of '0'. return '0' elif not sha and returncode == 129: # git returns 129 if a command option failed to parse; in # particular this could happen in git versions older than 1.7.2 # where the --count option is not supported # Also use --abbrev-commit and --abbrev=0 to display the minimum # number of characters needed per-commit (rather than the full hash) cmd = ['rev-list', '--abbrev-commit', '--abbrev=0', 'HEAD'] returncode, stdout, stderr = run_git(cmd) # Fall back on the old method of getting all revisions and counting # the lines if returncode == 0: return str(stdout.count(b'\n')) else: return '' elif sha: return _decode_stdio(stdout)[:40] else: return _decode_stdio(stdout).strip() # This function is tested but it is only ever executed within a subprocess when # creating a fake package, so it doesn't get picked up by coverage metrics. def _get_repo_path(pathname, levels=None): # pragma: no cover """ Given a file or directory name, determine the root of the git repository this path is under. If given, this won't look any higher than ``levels`` (that is, if ``levels=0`` then the given path must be the root of the git repository and is returned if so. Returns `None` if the given path could not be determined to belong to a git repo. """ if os.path.isfile(pathname): current_dir = os.path.abspath(os.path.dirname(pathname)) elif os.path.isdir(pathname): current_dir = os.path.abspath(pathname) else: return None current_level = 0 while levels is None or current_level <= levels: if os.path.exists(os.path.join(current_dir, '.git')): return current_dir current_level += 1 if current_dir == os.path.dirname(current_dir): break current_dir = os.path.dirname(current_dir) return None _packagename = "radio_beam" _last_generated_version = "0.3.2" _last_githash = "e7f08218451189db6bd9a342ee195c6a4f4de1f2" # Determine where the source code for this module # lives. If __file__ is not a filesystem path then # it is assumed not to live in a git repo at all. if _get_repo_path(__file__, levels=len(_packagename.split('.'))): version = update_git_devstr(_last_generated_version, path=__file__) githash = get_git_devstr(sha=True, show_warning=False, path=__file__) or _last_githash else: # The file does not appear to live in a git repo so don't bother # invoking git version = _last_generated_version githash = _last_githash major = 0 minor = 3 bugfix = 2 release = True timestamp = datetime.datetime(2019, 8, 27, 22, 2, 51) debug = False astropy_helpers_version = "1.1" try: from ._compiler import compiler except ImportError: compiler = "unknown" try: from .cython_version import cython_version except ImportError: cython_version = "unknown" radio_beam-0.3.2/setup.cfg0000644000077000000240000000134613420163703015443 0ustar adamstaff00000000000000[build_sphinx] source-dir = docs build-dir = docs/_build all_files = 1 [upload_docs] upload-dir = docs/_build/html show-response = 1 [tool:pytest] minversion = 2.2 norecursedirs = build docs/_build doctest_plus = enabled addopts = -p no:warnings [ah_bootstrap] auto_use = True [metadata] package_name = radio-beam description = Radio Beam object for use with astropy long_description = This package provides tools for working with beams in radio data. author = Adam Leroy, Adam Ginsburg, Erik Rosolowsky, Tom Robitaille, and Eric Koch author_email = adam.g.ginsburg@gmail.com, koch.eric.w@gmail.com license = BSD url = http://radio_beam.readthedocs.org edit_on_github = False github_project = radio-astro-tools/radio-beam [entry_points] radio_beam-0.3.2/setup.py0000644000077000000240000001011613531324152015327 0ustar adamstaff00000000000000#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import glob import os import sys import ah_bootstrap from setuptools import setup #A dirty hack to get around some early import/configurations ambiguities if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins builtins._ASTROPY_SETUP_ = True from astropy_helpers.setup_helpers import ( register_commands, adjust_compiler, get_debug_option, get_package_info) from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py # Get some values from the setup.cfg try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser conf = ConfigParser() conf.read(['setup.cfg']) metadata = dict(conf.items('metadata')) PACKAGENAME = metadata.get('package_name', 'packagename').replace('-', '_') DESCRIPTION = metadata.get('description', 'Astropy affiliated package') AUTHOR = metadata.get('author', '') AUTHOR_EMAIL = metadata.get('author_email', '') LICENSE = metadata.get('license', 'unknown') URL = metadata.get('url', 'http://astropy.org') # Get the long description from the package's docstring __import__(PACKAGENAME) package = sys.modules[PACKAGENAME] LONG_DESCRIPTION = package.__doc__ # Store the package name in a built-in variable so it's easy # to get from other parts of the setup infrastructure builtins._ASTROPY_PACKAGE_NAME_ = PACKAGENAME # VERSION should be PEP386 compatible (http://www.python.org/dev/peps/pep-0386) VERSION = '0.3.2' # Indicates if this version is a release version RELEASE = 'dev' not in VERSION if not RELEASE: VERSION += get_git_devstr(False) # Populate the dict of setup command overrides; this should be done before # invoking any other functionality from distutils since it can potentially # modify distutils' behavior. cmdclassd = register_commands(PACKAGENAME, VERSION, RELEASE) # Adjust the compiler in case the default on this platform is to use a # broken one. adjust_compiler(PACKAGENAME) # Freeze build information in version.py generate_version_py(PACKAGENAME, VERSION, RELEASE, get_debug_option(PACKAGENAME)) # Treat everything in scripts except README.rst as a script to be installed scripts = [fname for fname in glob.glob(os.path.join('scripts', '*')) if os.path.basename(fname) != 'README.rst'] # Get configuration information from all of the various subpackages. # See the docstring for setup_helpers.update_package_files for more # details. package_info = get_package_info() # Add the project-global data package_info['package_data'].setdefault(PACKAGENAME, []) package_info['package_data'][PACKAGENAME].append('data/*') # Define entry points for command-line scripts entry_points = {'console_scripts': []} entry_point_list = conf.items('entry_points') for entry_point in entry_point_list: entry_points['console_scripts'].append('{0} = {1}'.format(entry_point[0], entry_point[1])) # Include all .c files, recursively, including those generated by # Cython, since we can not do this in MANIFEST.in with a "dynamic" # directory name. c_files = [] for root, dirs, files in os.walk(PACKAGENAME): for filename in files: if filename.endswith('.c'): c_files.append( os.path.join( os.path.relpath(root, PACKAGENAME), filename)) package_info['package_data'][PACKAGENAME].extend(c_files) # Note that requires and provides should not be included in the call to # ``setup``, since these are now deprecated. See this link for more details: # https://groups.google.com/forum/#!topic/astropy-dev/urYO8ckB2uM setup(name=PACKAGENAME, version=VERSION, description=DESCRIPTION, scripts=scripts, install_requires=['astropy', 'numpy>=1.8.0', 'six'], author=AUTHOR, author_email=AUTHOR_EMAIL, license=LICENSE, url=URL, long_description=LONG_DESCRIPTION, cmdclass=cmdclassd, zip_safe=False, use_2to3=True, entry_points=entry_points, **package_info )