""" import numpy as np __all__ = ('reference_angle', 'reference_angle_deg', 'wrapped_angle', 'wrapped_angle_deg') def reference_angle(a): """Convert an angle to a reference angle between -pi and pi.""" a = np.mod(a, 2 * np.pi) return np.where(a <= np.pi, a, a - 2 * np.pi) def reference_angle_deg(a): """Convert an angle to a reference angle between -180 and 180 degrees.""" a = np.mod(a, 360) return np.where(a <= 180, a, a - 360) def wrapped_angle(a): """Convert an angle to a reference angle between 0 and 2*pi.""" return np.mod(a, 2 * np.pi) def wrapped_angle_deg(a): """Convert an angle to a reference angle between 0 and 2*pi.""" return np.mod(a, 360) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.plot.angle')
def iterlines(file, start_message=start_msg, stop_message=stop_msg): """Iterate over non-emtpy lines in a file.""" is_tty = os.isatty(file.fileno()) if is_tty: print(start_message, file=sys.stderr) while True: # Read a line. line = file.readline() if not line: # If we reached EOF, then exit. break # Strip off the trailing newline and any whitespace. line = line.strip() # Emit the line if it is not empty. if line: yield line if is_tty: print(stop_message, file=sys.stderr) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.tool')
if moc: return m elif distances: return tuple(np.asarray(m[name]) for name in DEFAULT_NESTED_NAMES), m.meta else: return np.asarray(m[DEFAULT_NESTED_NAMES[0]]), m.meta if __name__ == '__main__': import os nside = 128 npix = hp.nside2npix(nside) prob = np.random.random(npix) prob /= sum(prob) write_sky_map('test.fits.gz', prob, objid='FOOBAR 12345', gps_time=1049492268.25, creator=os.path.basename(__file__), url='http://www.youtube.com/watch?v=0ccKPSVQcFk', origin='LIGO Scientific Collaboration', runtime=21.5) print(read_sky_map('test.fits.gz')) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.fits')
# option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from __future__ import absolute_import import os import pkgutil import six __all__ = () # Import all symbols from all submodules of this module. for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]): six.exec_('from . import {0};' '__all__ += getattr({0}, "__all__", ());' 'from .{0} import *'.format(module)) del module # Clean up del os, pkgutil, six from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.events')
from lalinference.bayestar.deprecation import warn warn('ligo.skymap.bayestar')
_openers = {'a': _open_a, 'r': _open_r, 'w': _open_w} def open(string, mode): if string in {'-', '/dev/stdin', '/dev/stdout'}: raise ValueError('Cannot open stdin/stdout as an SQLite database') try: opener = _openers[mode] except KeyError: raise ValueError('Invalid mode "{}". Must be one of "{}".'.format( mode, ''.join(_openers.keys()))) try: return opener(string) except (OSError, sqlite3.Error) as e: raise OSError('Failed to open database {}: {}'.format(string, e)) def get_filename(connection): """Get the name of the file associated with an SQLite connection""" result = connection.execute('pragma database_list').fetchall() try: (_, _, filename), = result except ValueError: raise RuntimeError('Expected exactly one attached database') return filename from lalinference.bayestar.deprecation import warn warn('ligo.skymap.util.sqlite')
class GraceDBEventSource(EventSource): def __init__(self, graceids, client=None): if client is None: from ligo.gracedb.rest import GraceDb client = GraceDb() self._client = client self._graceids = graceids def __iter__(self): return iter(self._graceids) def __getitem__(self, graceid): coinc_file = self._client.files(graceid, 'coinc.xml') psd_file = self._client.files(graceid, 'psd.xml.gz') event, = LigoLWEventSource(coinc_file, psd_file=psd_file, coinc_def=None).values() return event def __len__(self): try: return len(self._graceids) except TypeError: raise NotImplementedError open = GraceDBEventSource from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.events.gracedb')
# from __future__ import division """ Functions for predicting timing accuracy of matched filters. """ import logging import numpy as np import lal import lalsimulation from scipy import interpolate from scipy import linalg from lalinference.bayestar.deprecation import warn warn('ligo.skymap.bayestar.filter') log = logging.getLogger('BAYESTAR') _noise_psd_funcs = {} class vectorize_swig_psd_func(object): """Create a vectorized Numpy function from a SWIG-wrapped PSD function. SWIG does not provide enough information for Numpy to determine the number of input arguments, so we can't just use np.vectorize.""" def __init__(self, str): self.__func = getattr(lalsimulation, str + 'Ptr') self.__npyfunc = np.frompyfunc(getattr(lalsimulation, str), 1, 1)
if moc: return m elif distances: return tuple( np.asarray(m[name]) for name in DEFAULT_NESTED_NAMES), m.meta else: return np.asarray(m[DEFAULT_NESTED_NAMES[0]]), m.meta if __name__ == '__main__': import os nside = 128 npix = hp.nside2npix(nside) prob = np.random.random(npix) prob /= sum(prob) write_sky_map( 'test.fits.gz', prob, objid='FOOBAR 12345', gps_time=1049492268.25, creator=os.path.basename(__file__), url='http://www.youtube.com/watch?v=0ccKPSVQcFk', origin='LIGO Scientific Collaboration', runtime=21.5) print(read_sky_map('test.fits.gz')) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.fits')
@abstractproperty def zerolag_time(self): """Time on arrival in zero-lag data, without time slides applied (float, GPS)""" raise NotImplementedError @abstractproperty def psd(self): """PSD (REAL8FrequencySeries)""" raise NotImplementedError @property def snr_series(self): """SNR time series (COMPLEX8TimeSeries)""" return None __str_keys = ('detector', 'snr', 'phase', 'time') def __str__(self): keys = self.__str_keys if self.time != self.zerolag_time: keys += ('zerolag_time', ) return _fmt(self, keys) __repr__ = __str__ from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.events.base')
value = self._phase if value is not None and self._invert_phases: value *= -1 return value @property def time(self): return self._time @property def zerolag_time(self): return self._zerolag_time @property def psd(self): return self._source._psds_for_file(self._psd_file)[self._detector] @property def snr_series(self): value = self._snr_series if self._invert_phases and value is not None: value = lal.CutCOMPLEX8TimeSeries(value, 0, len(value.data.data)) value.data.data = value.data.data.conj() return value open = LigoLWEventSource from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.events.ligolw')
def MagicEventSource(f, *args, **kwargs): """ Read events from either HDF or LIGO-LW files. The format is determined using the POSIX `file` command, which determines the file by looking for 'magic' byte strings (hence the name of this module). """ if isinstance(f, h5py.File): opener = hdf.open elif isinstance(f, sqlite3.Connection): opener = sqlite.open elif isinstance(f, LIGO_LW): opener = ligolw.open else: filetype = _get_file_type(f) if filetype == b'Hierarchical Data Format (version 5) data': opener = hdf.open elif filetype.startswith(b'SQLite 3.x database'): opener = sqlite.open elif filetype.startswith(b'XML') or filetype.startswith(b'gzip'): opener = ligolw.open else: raise IOError('Unknown file format') return opener(f, *args, **kwargs) open = MagicEventSource from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.events.magic')
def set_xlim(self, *args, **kwargs): Axes.set_xlim(self, 0., 2*np.pi) Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0) def _get_core_transform(self, resolution): return Affine2D().translate(-np.pi, 0.).scale(-1, 1) + super( AstroLambertAxes, self)._get_core_transform(resolution) class RaFormatter(Formatter): # Copied from matplotlib.geo.GeoAxes.ThetaFormatter and modified def __init__(self, round_to=1.0): self._round_to = round_to def __call__(self, x, pos=None): hours = (x / np.pi) * 12. hours = round(15 * hours / self._round_to) * self._round_to / 15 return r"%0.0f$^\mathrm{h}$" % hours def set_longitude_grid(self, degrees): # Copied from matplotlib.geo.GeoAxes.set_longitude_grid and modified number = (360.0 / degrees) + 1 self.xaxis.set_major_locator( FixedLocator( np.linspace(0, 2*np.pi, number, True)[1:-1])) self.xaxis.set_major_formatter(self.RaFormatter(degrees)) projection_registry.register(AstroLambertAxes) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.plot.allsky')
__all__ = () for name in ['cylon']: # Read in color map RGB data. try: with pkg_resources.resource_stream(__name__, name + '.csv') as f: data = np.loadtxt(f, delimiter=',') except IOError as e: warnings.warn('Failed to load "{0}" colormap'.format(name)) continue # Create color map. cmap = colors.LinearSegmentedColormap.from_list(name, data) # Assign in module. locals().update({name: cmap}) # Register with Matplotlib. cm.register_cmap(cmap=cmap) # Generate reversed color map. name += '_r' data = data[::-1] cmap = colors.LinearSegmentedColormap.from_list(name, data) # Assign in module. locals().update({name: cmap}) # Register with Matplotlib. cm.register_cmap(cmap=cmap) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.plot.cmap')
import numpy as np __all__ = ('reference_angle', 'reference_angle_deg', 'wrapped_angle', 'wrapped_angle_deg') def reference_angle(a): """Convert an angle to a reference angle between -pi and pi.""" a = np.mod(a, 2 * np.pi) return np.where(a <= np.pi, a, a - 2 * np.pi) def reference_angle_deg(a): """Convert an angle to a reference angle between -180 and 180 degrees.""" a = np.mod(a, 360) return np.where(a <= 180, a, a - 360) def wrapped_angle(a): """Convert an angle to a reference angle between 0 and 2*pi.""" return np.mod(a, 2 * np.pi) def wrapped_angle_deg(a): """Convert an angle to a reference angle between 0 and 2*pi.""" return np.mod(a, 360) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.plot.angle')
self.source = source self.base_event = base_event @property def singles(self): disabled_detectors = self.source.disabled_detectors if self.source.raises: detectors = {s.detector for s in self.base_event.singles} if not detectors & disabled_detectors: raise DetectorDisabledError( 'Disabling detectors {{{}}} would have no effect on this ' 'event with detectors {{{}}}'.format( ' '.join(disabled_detectors), ' '.join(detectors))) if not detectors - disabled_detectors: raise DetectorDisabledError( 'Disabling detectors {{{}}} would exclude all data for ' 'this event with detectors {{{}}}'.format( ' '.join(disabled_detectors), ' '.join(detectors))) return tuple(s for s in self.base_event.singles if s.detector not in disabled_detectors) @property def template_args(self): return self.base_event.template_args open = DetectorDisabledEventSource from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.events.detector_disabled')
from glue.ligolw import dbtables from ...util import sqlite from .ligolw import LigoLWEventSource __all__ = ('SQLiteEventSource', ) class SQLiteEventSource(LigoLWEventSource): def __init__(self, f, *args, **kwargs): if isinstance(f, sqlite3.Connection): db = f filename = sqlite.get_filename(f) else: if hasattr(f, 'read'): filename = f.name f.close() else: filename = f db = sqlite.open(filename, 'r') super(SQLiteEventSource, self).__init__(dbtables.get_xml(db), *args, **kwargs) self._fallbackpath = os.path.dirname(filename) if filename else None open = SQLiteEventSource from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.events.sqlite')
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Plotting classes and methods """ from __future__ import absolute_import import os import pkgutil import six __all__ = () # Import all symbols from all submodules of this module. for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]): six.exec_('from . import {0};' '__all__ += getattr({0}, "__all__", ());' 'from .{0} import *'.format(module)) del module # Clean up del os, pkgutil, six from lalinference.bayestar.deprecation import warn warn('ligo.skymap.plot')
# Move order of magnitude text into last label. ticklabels = [label.get_text() for label in axis.get_ticklabels()] # Avoid putting two '$' next to each other if we are in tex mode. if usetex: fmt = '{{{0}}}{{{1}}}' else: fmt = u'{0}{1}' ticklabels[-1] = fmt.format(ticklabels[-1], formatter.get_offset()) axis.set_ticklabels(ticklabels) last_ticklabel = axis.get_ticklabels()[-1] last_ticklabel.set_horizontalalignment('left') # Draw edges in colorbar bands to correct thin white bands that # appear in buggy PDF viewers. See: # https://github.com/matplotlib/matplotlib/pull/1301 cb.solids.set_edgecolor("face") # Done. return cb def outline_text(ax): """Add a white outline to all text to make it stand out from the background.""" effects = [patheffects.withStroke(linewidth=2, foreground='w')] for artist in ax.findobj(text.Text): artist.set_path_effects(effects) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.plot.healpix')
if 'vary' not in column.meta: if np.all(column[0] == column[1:]): column.meta['vary'] = FIXED else: column.meta['vary'] = OUTPUT # Reconstruct table attributes. for colname, column in tuple(table.columns.items()): if column.meta['vary'] == FIXED: np.testing.assert_array_equal( column[1:], column[0], 'Column {0} is a fixed column, but ' 'its values are not identical'.format(column.name)) table.meta[colname] = column[0] del table[colname] for i, column in enumerate(table.columns.values()): table.meta['FIELD_{0}_VARY'.format(i)] = column.meta['vary'] table.write(filename, format='hdf5', **kwargs) if metadata: with h5py.File(filename) as hdf: for internal_path, attributes in metadata.items(): for key, value in attributes.items(): try: hdf[internal_path].attrs[key] = value except KeyError: raise KeyError( 'Unable to set metadata {0}[{1}] = {2}'.format( internal_path, key, value)) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io.hdf5')
# option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from __future__ import absolute_import import os import pkgutil import six __all__ = () # Import all symbols from all submodules of this module. for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]): six.exec_('from . import {0};' '__all__ += getattr({0}, "__all__", ());' 'from .{0} import *'.format(module)) del module # Clean up del os, pkgutil, six from lalinference.bayestar.deprecation import warn warn('ligo.skymap.io')
# You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # """ Convenience function to produce a sky map from LIGO-LW rows. """ import numpy as np from astropy.table import Column, Table from astropy import units as u from .. import moc from .. import healpix_tree from lalinference.bayestar.deprecation import warn warn('ligo.skymap.bayestar') def rasterize(skymap): skymap = Table(moc.rasterize(skymap), meta=skymap.meta) skymap.rename_column('PROBDENSITY', 'PROB') skymap['PROB'] *= 4 * np.pi / len(skymap) skymap['PROB'].unit = u.pixel**-1 return skymap def derasterize(skymap): skymap.rename_column('PROB', 'PROBDENSITY') skymap['PROBDENSITY'] *= len(skymap) / (4 * np.pi) skymap['PROBDENSITY'].unit = u.steradian**-1 nside, _, ipix, _, _, value = zip(*healpix_tree.reconstruct_nested(skymap))
os.close(tmpfid) shutil.copy2(src, tmpdst) os.rename(tmpdst, dst) except: os.remove(tmpdst) raise else: raise def rm_f(filename): """Remove a file, or be silent if the file does not exist, like `rm -f`.""" try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: raise @contextlib.contextmanager def TemporaryDirectory(suffix='', prefix='tmp', dir=None, delete=True): try: dir = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir) yield dir finally: if delete: shutil.rmtree(dir) from lalinference.bayestar.deprecation import warn warn('ligo.skymap.util.file')