code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def enumeration (cls):
from pwkit import unicode_to_str
name = cls.__name__
pickle_compat = getattr (cls, '__pickle_compat__', False)
def __unicode__ (self):
return '<enumeration holder %s>' % name
def getattr_error (self, attr):
raise AttributeError ('enumeration %s does not ... | A very simple decorator for creating enumerations. Unlike Python 3.4
enumerations, this just gives a way to use a class declaration to create
an immutable object containing only the values specified in the class.
If the attribute ``__pickle_compat__`` is set to True in the decorated
class, the resultin... |
def fits_recarray_to_data_frame (recarray, drop_nonscalar_ok=True):
from pandas import DataFrame
def normalize ():
for column in recarray.columns:
n = column.name
d = recarray[n]
if d.ndim != 1:
if not drop_nonscalar_ok:
rais... | Convert a FITS data table, stored as a Numpy record array, into a Pandas
DataFrame object. By default, non-scalar columns are discarded, but if
*drop_nonscalar_ok* is False then a :exc:`ValueError` is raised. Column
names are lower-cased. Example::
from pwkit import io, numutil
hdu_list = io.Pa... |
def data_frame_to_astropy_table (dataframe):
from astropy.utils import OrderedDict
from astropy.table import Table, Column, MaskedColumn
from astropy.extern import six
out = OrderedDict()
for name in dataframe.columns:
column = dataframe[name]
mask = np.array (column.isnull ()... | This is a backport of the Astropy method
:meth:`astropy.table.table.Table.from_pandas`. It converts a Pandas
:class:`pandas.DataFrame` object to an Astropy
:class:`astropy.table.Table`. |
def page_data_frame (df, pager_argv=['less'], **kwargs):
import codecs, subprocess, sys
pager = subprocess.Popen (pager_argv, shell=False,
stdin=subprocess.PIPE,
close_fds=True)
try:
enc = codecs.getwriter (sys.stdout.encoding or 'ut... | Render a DataFrame as text and send it to a terminal pager program (e.g.
`less`), so that one can browse a full table conveniently.
df
The DataFrame to view
pager_argv: default ``['less']``
A list of strings passed to :class:`subprocess.Popen` that launches
the pager program
kwargs
... |
def slice_around_gaps (values, maxgap):
if not (maxgap > 0):
# above test catches NaNs, other weird cases
raise ValueError ('maxgap must be positive; got %r' % maxgap)
values = np.asarray (values)
delta = values[1:] - values[:-1]
if np.any (delta < 0):
raise ValueError ('v... | Given an ordered array of values, generate a set of slices that traverse
all of the values. Within each slice, no gap between adjacent values is
larger than `maxgap`. In other words, these slices break the array into
chunks separated by gaps of size larger than maxgap. |
def slice_evenly_with_gaps (values, target_len, maxgap):
if not (target_len > 0):
raise ValueError ('target_len must be positive; got %r' % target_len)
values = np.asarray (values)
l = values.size
for gapslice in slice_around_gaps (values, maxgap):
start, stop, ignored_stride = ga... | Given an ordered array of values, generate a set of slices that traverse
all of the values. Each slice contains about `target_len` items. However,
no slice contains a gap larger than `maxgap`, so a slice may contain only
a single item (if it is surrounded on both sides by a large gap). If a
non-gapped r... |
def reduce_data_frame_evenly_with_gaps (df, valcol, target_len, maxgap, **kwargs):
Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`.
"""
return reduce_dat... | Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`. |
def usmooth (window, uncerts, *data, **kwargs):
window = np.asarray (window)
uncerts = np.asarray (uncerts)
# Hacky keyword argument handling because you can't write "def foo (*args,
# k=0)".
k = kwargs.pop ('k', None)
if len (kwargs):
raise TypeError ("smooth() got an unexpected... | Smooth data series according to a window, weighting based on uncertainties.
Arguments:
window
The smoothing window.
uncerts
An array of uncertainties used to weight the smoothing.
data
One or more data series, of the same size as *uncerts*.
k = None
If specified, only every... |
def dfsmooth (window, df, ucol, k=None):
import pandas as pd
if k is None:
k = window.size
conv = lambda q, r: np.convolve (q, r, mode='valid')
w = df[ucol] ** -2
invcw = 1. / conv (w, window)
# XXX: we're not smoothing the index.
res = {}
for col in df.columns:
... | Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* that contains the uncertainties to weight
by.
k = None
If ... |
def weighted_mean_df (df, **kwargs):
return weighted_mean (df[df.columns[0]], df[df.columns[1]], **kwargs) | The same as :func:`weighted_mean`, except the argument is expected to be a
two-column :class:`pandas.DataFrame` whose first column gives the data
values and second column gives their uncertainties. Returns
``(weighted_mean, uncertainty_in_mean)``. |
def weighted_variance (x, weights):
n = len (x)
if n < 3:
raise ValueError ('cannot calculate meaningful variance of fewer '
'than three samples')
wt_mean = np.average (x, weights=weights)
return np.average (np.square (x - wt_mean), weights=weights) * n / (n - 1) | Return the variance of a weighted sample.
The weighted sample mean is calculated and subtracted off, so the returned
variance is upweighted by ``n / (n - 1)``. If the sample mean is known to
be zero, you should just compute ``np.average (x**2, weights=weights)``. |
def unit_tophat_ee (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)
r = ((0 < x1) & (x1 < 1)).astype (x.dtype)
if x.ndim == 0:
return np.asscalar (r)
return r | Tophat function on the unit interval, left-exclusive and right-exclusive.
Returns 1 if 0 < x < 1, 0 otherwise. |
def make_tophat_ee (lower, upper):
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ee (x):
x = np.asa... | Return a ufunc-like tophat function on the defined range, left-exclusive
and right-exclusive. Returns 1 if lower < x < upper, 0 otherwise. |
def make_tophat_ei (lower, upper):
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ei (x):
x = np.asa... | Return a ufunc-like tophat function on the defined range, left-exclusive
and right-inclusive. Returns 1 if lower < x <= upper, 0 otherwise. |
def make_tophat_ie (lower, upper):
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ie (x):
x = np.asa... | Return a ufunc-like tophat function on the defined range, left-inclusive
and right-exclusive. Returns 1 if lower <= x < upper, 0 otherwise. |
def make_tophat_ii (lower, upper):
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not np.isfinite (upper):
raise ValueError ('"upper" argument must be finite number; got %r' % upper)
def range_tophat_ii (x):
x = np.asa... | Return a ufunc-like tophat function on the defined range, left-inclusive
and right-inclusive. Returns 1 if lower < x < upper, 0 otherwise. |
def make_step_lcont (transition):
if not np.isfinite (transition):
raise ValueError ('"transition" argument must be finite number; got %r' % transition)
def step_lcont (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)
r = (x1 > transition).astype (x.dtype)
if x.ndim ==... | Return a ufunc-like step function that is left-continuous. Returns 1 if
x > transition, 0 otherwise. |
def make_step_rcont (transition):
if not np.isfinite (transition):
raise ValueError ('"transition" argument must be finite number; got %r' % transition)
def step_rcont (x):
x = np.asarray (x)
x1 = np.atleast_1d (x)
r = (x1 >= transition).astype (x.dtype)
if x.ndim =... | Return a ufunc-like step function that is right-continuous. Returns 1 if
x >= transition, 0 otherwise. |
def make_fixed_temp_multi_apec(kTs, name_template='apec%d', norm=None):
total_model = None
sub_models = []
for i, kT in enumerate(kTs):
component = ui.xsapec(name_template % i)
component.kT = kT
ui.freeze(component.kT)
if norm is not None:
component.norm = n... | Create a model summing multiple APEC components at fixed temperatures.
*kTs*
An iterable of temperatures for the components, in keV.
*name_template* = 'apec%d'
A template to use for the names of each component; it is string-formatted
with the 0-based component number as an argument.
*norm... |
def expand_rmf_matrix(rmf):
n_chan = rmf.e_min.size
n_energy = rmf.n_grp.size
expanded = np.zeros((n_energy, n_chan))
mtx_ofs = 0
grp_ofs = 0
for i in range(n_energy):
for j in range(rmf.n_grp[i]):
f = rmf.f_chan[grp_ofs]
n = rmf.n_chan[grp_ofs]
... | Expand an RMF matrix stored in compressed form.
*rmf*
An RMF object as might be returned by ``sherpa.astro.ui.get_rmf()``.
Returns:
A non-sparse RMF matrix.
The Response Matrix Function (RMF) of an X-ray telescope like Chandra can
be stored in a sparse format as defined in `OGIP Calibratio... |
def derive_identity_arf(name, arf):
from sherpa.astro.data import DataARF
from sherpa.astro.instrument import ARF1D
darf = DataARF(
name,
arf.energ_lo,
arf.energ_hi,
np.ones(arf.specresp.shape),
arf.bin_lo,
arf.bin_hi,
arf.exposure,
heade... | Create an "identity" ARF that has uniform sensitivity.
*name*
The name of the ARF object to be created; passed to Sherpa.
*arf*
An existing ARF object on which to base this one.
Returns:
A new ARF1D object that has a uniform spectral response vector.
In many X-ray observations, the r... |
def get_source_qq_data(id=None):
sdata = ui.get_data(id=id)
kev = sdata.get_x()
obs_data = sdata.counts
model_data = ui.get_model(id=id)(kev)
return np.vstack((kev, obs_data, model_data)) | Get data for a quantile-quantile plot of the source data and model.
*id*
The dataset id for which to get the data; defaults if unspecified.
Returns:
An ndarray of shape ``(3, npts)``. The first slice is the energy axis in
keV; the second is the observed values in each bin (counts, or rate, or... |
def get_bkg_qq_data(id=None, bkg_id=None):
bdata = ui.get_bkg(id=id, bkg_id=bkg_id)
kev = bdata.get_x()
obs_data = bdata.counts
model_data = ui.get_bkg_model(id=id, bkg_id=bkg_id)(kev)
return np.vstack((kev, obs_data, model_data)) | Get data for a quantile-quantile plot of the background data and model.
*id*
The dataset id for which to get the data; defaults if unspecified.
*bkg_id*
The identifier of the background; defaults if unspecified.
Returns:
An ndarray of shape ``(3, npts)``. The first slice is the energy axi... |
def download_file(local_filename, url, clobber=False):
dir_name = os.path.dirname(local_filename)
mkdirs(dir_name)
if clobber or not os.path.exists(local_filename):
i = requests.get(url)
# if not exists
if i.status_code == 404:
print('Failed to download file:', loc... | Download the given file. Clobber overwrites file if exists. |
def download_json(local_filename, url, clobber=False):
with open(local_filename, 'w') as json_file:
json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': '))) | Download the given JSON file, and pretty-print before we output it. |
def data_to_imagesurface (data, **kwargs):
import cairo
data = np.atleast_2d (data)
if data.ndim != 2:
raise ValueError ('input array may not have more than 2 dimensions')
argb32 = data_to_argb32 (data, **kwargs)
format = cairo.FORMAT_ARGB32
height, width = argb32.shape
strid... | Turn arbitrary data values into a Cairo ImageSurface.
The method and arguments are the same as data_to_argb32, except that the
data array will be treated as 2D, and higher dimensionalities are not
allowed. The return value is a Cairo ImageSurface object.
Combined with the write_to_png() method on Imag... |
def get_token(filename=TOKEN_PATH, envvar=TOKEN_ENVVAR):
if os.path.isfile(filename):
with open(filename) as token_file:
token = token_file.readline().strip()
else:
token = os.environ.get(envvar)
if not token:
raise ValueError("No token found.\n"
... | Returns pipeline_token for API
Tries local file first, then env variable |
def stats (self, antnames):
nbyant = np.zeros (self.nants, dtype=np.int)
sum = np.zeros (self.nants, dtype=np.complex)
sumsq = np.zeros (self.nants)
q = np.abs (self.normvis - 1)
for i in range (self.nsamps):
i1, i2 = self.blidxs[i]
nbyant[i1] +=... | XXX may be out of date. |
def read_stream (stream):
section = None
key = None
data = None
for fullline in stream:
line = fullline.split ('#', 1)[0]
m = sectionre.match (line)
if m is not None:
# New section
if section is not None:
if key is not None:
... | Python 3 compat note: we're assuming `stream` gives bytes not unicode. |
def write_stream (stream, holders, defaultsection=None):
anybefore = False
for h in holders:
if anybefore:
print ('', file=stream)
s = h.get ('section', defaultsection)
if s is None:
raise ValueError ('cannot determine section name for item <%s>' % h)
... | Very simple writing in ini format. The simple stringification of each value
in each Holder is printed, and no escaping is performed. (This is most
relevant for multiline values or ones containing pound signs.) `None` values are
skipped.
Arguments:
stream
A text stream to write to.
holder... |
def write (stream_or_path, holders, **kwargs):
if isinstance (stream_or_path, six.string_types):
return write_stream (io.open (stream_or_path, 'wt'), holders, **kwargs)
else:
return write_stream (stream_or_path, holders, **kwargs) | Very simple writing in ini format. The simple stringification of each value
in each Holder is printed, and no escaping is performed. (This is most
relevant for multiline values or ones containing pound signs.) `None` values are
skipped.
Arguments:
stream
A text stream to write to.
holder... |
def in_casapy (helper, caltable=None, selectcals={}, plotoptions={},
xaxis=None, yaxis=None, figfile=None):
if caltable is None:
raise ValueError ('caltable')
show_gui = (figfile is None)
cp = helper.casans.cp
helper.casans.tp.setgui (show_gui)
cp.open (caltable)
cp... | This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting. |
def _qrd_solve_full(a, b, ddiag, dtype=np.float):
a = np.asarray(a, dtype)
b = np.asarray(b, dtype)
ddiag = np.asarray(ddiag, dtype)
n, m = a.shape
assert m >= n
assert b.shape == (m, )
assert ddiag.shape == (n, )
# The computation is straightforward.
q, r, pmut = _qr_factor... | Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n supplementary matrix s.
pmut - n-element permutation vector defining the permutati... |
def _lmder1_linear_full_rank(n, m, factor, target_fnorm1, target_fnorm2):
def func(params, vec):
s = params.sum()
temp = 2. * s / m + 1
vec[:] = -temp
vec[:params.size] += params
def jac(params, jac):
# jac.shape = (n, m) by LMDER standards
jac.fill(-2. / m... | A full-rank linear function (lmder test #1) |
def _lmder1_linear_r1zcr(n, m, factor, target_fnorm1, target_fnorm2, target_params):
def func(params, vec):
s = 0
for j in range(1, n - 1):
s += (j + 1) * params[j]
for i in range(m):
vec[i] = i * s - 1
vec[m-1] = -1
def jac(params, jac):
ja... | A rank-1 linear function with zero columns and rows (lmder test #3) |
def _lmder1_rosenbrock():
def func(params, vec):
vec[0] = 10 * (params[1] - params[0]**2)
vec[1] = 1 - params[0]
def jac(params, jac):
jac[0,0] = -20 * params[0]
jac[0,1] = -1
jac[1,0] = 10
jac[1,1] = 0
guess = np.asfarray([-1.2, 1])
norm1s = [0.49... | Rosenbrock function (lmder test #4) |
def _lmder1_powell_singular():
def func(params, vec):
vec[0] = params[0] + 10 * params[1]
vec[1] = np.sqrt(5) * (params[2] - params[3])
vec[2] = (params[1] - 2 * params[2])**2
vec[3] = np.sqrt(10) * (params[0] - params[3])**2
def jac(params, jac):
jac.fill(0)
... | Powell's singular function (lmder test #6). Don't run this as a
test, since it just zooms to zero parameters. The precise results
depend a lot on nitty-gritty rounding and tolerances and things. |
def _lmder1_freudenstein_roth():
def func(params, vec):
vec[0] = -13 + params[0] + ((5 - params[1]) * params[1] - 2) * params[1]
vec[1] = -29 + params[0] + ((1 + params[1]) * params[1] - 14) * params[1]
def jac(params, jac):
jac[0] = 1
jac[1,0] = params[1] * (10 - 3 * para... | Freudenstein and Roth function (lmder1 test #7) |
def _lmder1_meyer():
y3 = np.asarray([3.478e4, 2.861e4, 2.365e4, 1.963e4, 1.637e4, 1.372e4, 1.154e4,
9.744e3, 8.261e3, 7.03e3, 6.005e3, 5.147e3, 4.427e3, 3.82e3,
3.307e3, 2.872e3])
def func(params, vec):
temp = 5 * (np.arange(16) + 1) + 45 + params[2]
... | Meyer function (lmder1 test #10) |
def p_side(self, idx, sidedness):
dsideval = _dside_names.get(sidedness)
if dsideval is None:
raise ValueError('unrecognized sidedness "%s"' % sidedness)
p = self._pinfob
p[idx] = (p[idx] & ~PI_M_SIDE) | dsideval
return self | Acceptable values for *sidedness* are "auto", "pos",
"neg", and "two". |
def is_strict_subclass (value, klass):
return (isinstance (value, type) and
issubclass (value, klass) and
value is not klass) | Check that `value` is a subclass of `klass` but that it is not actually
`klass`. Unlike issubclass(), does not raise an exception if `value` is
not a type. |
def invoke_tool (namespace, tool_class=None):
import sys
from .. import cli
cli.propagate_sigint ()
cli.unicode_stdio ()
cli.backtrace_on_usr1 ()
if tool_class is None:
for value in itervalues (namespace):
if is_strict_subclass (value, Multitool):
if too... | Invoke a tool and exit.
`namespace` is a namespace-type dict from which the tool is initialized.
It should contain exactly one value that is a `Multitool` subclass, and
this subclass will be instantiated and populated (see
`Multitool.populate()`) using the other items in the namespace. Instances
an... |
def invoke_with_usage (self, args, **kwargs):
argv0 = kwargs['argv0']
usage = self._usage (argv0)
argv = [argv0] + args
uina = 'long' if self.help_if_no_args else False
check_usage (usage, argv, usageifnoargs=uina)
try:
return self.invoke (args, **kw... | Invoke the command with standardized usage-help processing. Same calling
convention as `Command.invoke()`. |
def get_arg_parser (self, **kwargs):
import argparse
ap = argparse.ArgumentParser (
prog = kwargs['argv0'],
description = self.summary,
)
return ap | Return an instance of `argparse.ArgumentParser` used to process
this tool's command-line arguments. |
def invoke_with_usage (self, args, **kwargs):
ap = self.get_arg_parser (**kwargs)
args = ap.parse_args (args)
return self.invoke (args, **kwargs) | Invoke the command with standardized usage-help processing. Same
calling convention as `Command.invoke()`, except here *args* is an
un-parsed list of strings. |
def register (self, cmd):
if cmd.name is None:
raise ValueError ('no name set for Command object %r' % cmd)
if cmd.name in self.commands:
raise ValueError ('a command named "%s" has already been '
'registered' % cmd.name)
self.comma... | Register a new command with the tool. 'cmd' is expected to be an instance
of `Command`, although here only the `cmd.name` attribute is
investigated. Multiple commands with the same name are not allowed to
be registered. Returns 'self'. |
def populate (self, values):
for value in values:
if isinstance (value, Command):
self.register (value)
elif is_strict_subclass (value, Command) and getattr (value, 'name') is not None:
self.register (value ())
return self | Register multiple new commands by investigating the iterable `values`. For
each item in `values`, instances of `Command` are registered, and
subclasses of `Command` are instantiated (with no arguments passed to
the constructor) and registered. Other kinds of values are ignored.
Returns '... |
def invoke_command (self, cmd, args, **kwargs):
new_kwargs = kwargs.copy ()
new_kwargs['argv0'] = kwargs['argv0'] + ' ' + cmd.name
new_kwargs['parent'] = self
new_kwargs['parent_kwargs'] = kwargs
return cmd.invoke_with_usage (args, **new_kwargs) | This function mainly exists to be overridden by subclasses. |
def commandline (self, argv):
self.invoke_with_usage (argv[1:],
tool=self,
argv0=self.cli_name) | Run as if invoked from the command line. 'argv' is a Unix-style list of
arguments, where the zeroth item is the program name (which is ignored
here). Usage help is printed if deemed appropriate (e.g., no arguments
are given). This function always terminates with an exception, with
the ex... |
def cited_names_from_aux_file(stream):
cited = set()
for line in stream:
if not line.startswith(r'\citation{'):
continue
line = line.rstrip()
if line[-1] != '}':
continue # should issue a warning or something
entries = line[10:-1]
for name... | Parse a LaTeX ".aux" file and generate a list of names cited according to
LaTeX ``\\citation`` commands. Repeated names are generated only once. The
argument should be a opened I/O stream. |
def merge_bibtex_collections(citednames, maindict, extradicts, allow_missing=False):
allrecords = {}
for ed in extradicts:
allrecords.update(ed)
allrecords.update(maindict)
missing = []
from collections import OrderedDict
records = OrderedDict()
from itertools import chain
... | There must be a way to be efficient and stream output instead of loading
everything into memory at once, but, meh.
Note that we augment `citednames` with all of the names in `maindict`. The
intention is that if we've gone to the effort of getting good data for
some record, we don't want to trash it if ... |
def write_bibtex_dict(stream, entries):
from bibtexparser.bwriter import BibTexWriter
writer = BibTexWriter()
writer.indent = ' '
writer.entry_separator = ''
first = True
for rec in entries:
if first:
first = False
else:
stream.write(b'\n')
... | bibtexparser.write converts the entire database to one big string and
writes it out in one go. I'm sure it will always all fit in RAM but some
things just will not stand. |
def merge_bibtex_with_aux(auxpath, mainpath, extradir, parse=get_bibtex_dict, allow_missing=False):
auxpath = Path(auxpath)
mainpath = Path(mainpath)
extradir = Path(extradir)
with auxpath.open('rt') as aux:
citednames = sorted(cited_names_from_aux_file(aux))
main = mainpath.try_open(... | Merge multiple BibTeX files into a single homogeneously-formatted output,
using a LaTeX .aux file to know which records are worth paying attention
to.
The file identified by `mainpath` will be overwritten with the new .bib
contents. This function is intended to be used in a version-control
context.... |
def just_smart_bibtools(bib_style, aux, bib):
extradir = Path('.bibtex')
extradir.ensure_dir(parents=True)
bib_export(bib_style, aux, extradir / 'ZZ_bibtools.bib',
no_tool_ok=True, quiet=True, ignore_missing=True)
merge_bibtex_with_aux(aux, bib, extradir) | Tectonic has taken over most of the features that this tool used to provide,
but here's a hack to keep my smart .bib file generation working. |
def in_casapy (helper, asdm=None, ms=None):
if asdm is None:
raise ValueError ('asdm')
if ms is None:
raise ValueError ('ms')
helper.casans.importasdm (
asdm = asdm,
vis = ms,
asis = 'Antenna Station Receiver Source CalAtmosphere CalWVR CorrelatorMode SBSummary'... | This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting. |
def bp_to_aap (bp):
ap1, ap2 = bp
if ap1 < 0:
raise ValueError ('first antpol %d is negative' % ap1)
if ap2 < 0:
raise ValueError ('second antpol %d is negative' % ap2)
pol = _fpol_to_pol[((ap1 & 0x7) << 4) + (ap2 & 0x7)]
if pol == 0xFF:
raise ValueError ('no CASA pola... | Converts a basepol into a tuple of (ant1, ant2, pol). |
def aap_to_bp (ant1, ant2, pol):
if ant1 < 0:
raise ValueError ('first antenna is below 0: %s' % ant1)
if ant2 < ant1:
raise ValueError ('second antenna is below first: %s' % ant2)
if pol < 1 or pol > 12:
raise ValueError ('illegal polarization code %s' % pol)
fps = _pol_t... | Create a basepol from antenna numbers and a CASA polarization code. |
def postproc (stats_result):
n, mean, scat = stats_result
mean *= 180 / np.pi # rad => deg
scat /= n # variance-of-samples => variance-of-mean
scat **= 0.5 # variance => stddev
scat *= 180 / np.pi # rad => deg
return mean, scat | Simple helper to postprocess angular outputs from StatsCollectors in the
way we want. |
def postproc_mask (stats_result):
n, mean, scat = stats_result
ok = np.isfinite (mean)
n = n[ok]
mean = mean[ok]
scat = scat[ok]
mean *= 180 / np.pi # rad => deg
scat /= n # variance-of-samples => variance-of-mean
scat **= 0.5 # variance => stddev
scat *= 180 / np.pi # rad => ... | Simple helper to postprocess angular outputs from StatsCollectors in the
way we want. |
def finish (self, keyset, mask=True):
n_us = len (self._keymap)
# By definition (for now), wt >= 1 everywhere, so we don't need to
# worry about div-by-zero.
wt_us = self._m0[:n_us]
mean_us = self._m1[:n_us] / wt_us
var_us = self._m2[:n_us] / wt_us - mean_us**2
... | Returns (weights, means, variances), where:
weights
ndarray of number of samples per key
means
computed mean value for each key
variances
computed variance for each key |
def _finish_timeslot (self):
for fpol, aps in self.ap_by_fpol.items ():
aps = sorted (aps)
nap = len (aps)
for i1, ap1 in enumerate (aps):
for i2 in range (i1, nap):
ap2 = aps[i2]
bp1 = (ap1, ap2)
... | We have loaded in all of the visibilities in one timeslot. We can now
compute the phase closure triples.
XXX: we should only process independent triples. Are we??? |
def _process_sample (self, ap1, ap2, ap3, triple, tflags):
# Frequency-resolved:
np.divide (triple, np.abs (triple), triple)
phase = np.angle (triple)
self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap1, phase, tflags + 0.)
self.ap_spec_stats_by_ddid[self.cur_ddid].acc... | We have computed one independent phase closure triple in one timeslot. |
def dftphotom_cli(argv):
check_usage(dftphotom_doc, argv, usageifnoargs=True)
cfg = Config().parse(argv[1:])
util.logger(cfg.loglevel)
dftphotom(cfg) | Command-line access to the :func:`dftphotom` algorithm.
This function implements the behavior of the command-line ``casatask
dftphotom`` tool, wrapped up into a single callable function. The argument
*argv* is a list of command-line arguments, in Unix style where the zeroth
item is the name of the comm... |
def download_links(self, dir_path):
links = self.links
if not path.exists(dir_path):
makedirs(dir_path)
for i, url in enumerate(links):
if 'start' in self.cseargs:
i += int(self.cseargs['start'])
ext = self.cseargs['fileType']
ext = '.html' if ext == '' else '.' + ext
... | Download web pages or images from search result links.
Args:
dir_path (str):
Path of directory to save downloads of :class:`api.results`.links |
def get_values(self, k, v):
metadata = self.metadata
values = []
if metadata != None:
if k in metadata:
for metav in metadata[k]:
if v in metav:
values.append(metav[v])
return values | Get a list of values from the key value metadata attribute.
Args:
k (str):
Key in :class:`api.results`.metadata
v (str):
Values from each item in the key of :class:`api.results`.metadata
Returns:
A list containing all the ``v`` values in the ``k`` key for the :class:... |
def preview(self, n=10, k='items', kheader='displayLink', klink='link', kdescription='snippet'):
if 'searchType' in self.cseargs:
searchType = self.cseargs['searchType']
else:
searchType = None
items = self.metadata[k]
# (cse_print) Print results
for i, kv in enumerate(items[:n])... | Print a preview of the search results.
Args:
n (int):
Maximum number of search results to preview
k (str):
Key in :class:`api.results`.metadata to preview
kheader (str):
Key in :class:`api.results`.metadata[``k``] to use as the header
klink (str):
Key in ... |
def save_links(self, file_path):
data = '\n'.join(self.links)
with open(file_path, 'w') as out_file:
out_file.write(data) | Saves a text file of the search result links.
Saves a text file of the search result links, where each link
is saved in a new line. An example is provided below::
http://www.google.ca
http://www.gmail.com
Args:
file_path (str):
Path to the text file to save links ... |
def save_metadata(self, file_path):
data = self.metadata
with open(file_path, 'w') as out_file:
json.dump(data, out_file) | Saves a json file of the search result metadata.
Saves a json file of the search result metadata from :class:`api.results`.metadata.
Args:
file_path (str):
Path to the json file to save metadata to. |
def bcj_from_spt (spt):
return np.where ((spt >= 0) & (spt <= 10),
1.53 + 0.148 * spt - 0.0105 * spt**2,
np.nan) | Calculate a bolometric correction constant for a J band magnitude based on
a spectral type, using the fit of Wilking+ (1999AJ....117..469W).
spt - Numerical spectral type. M0=0, M9=9, L0=10, ...
Returns: the correction `bcj` such that `m_bol = j_abs + bcj`, or NaN if
`spt` is out of range.
Valid ... |
def bck_from_spt (spt):
# NOTE: the way np.piecewise() is implemented, the last 'true' value in
# the condition list is the one that takes precedence. This motivates the
# construction of our condition list.
#
# XXX: I've restructured the implementation; this needs testing!
spt = np.asfar... | Calculate a bolometric correction constant for a J band magnitude based on
a spectral type, using the fits of Wilking+ (1999AJ....117..469W), Dahn+
(2002AJ....124.1170D), and Nakajima+ (2004ApJ...607..499N).
spt - Numerical spectral type. M0=0, M9=9, L0=10, ...
Returns: the correction `bck` such that ... |
def lbol_from_spt_dist_mag (sptnum, dist_pc, jmag, kmag, format='cgs'):
bcj = bcj_from_spt (sptnum)
bck = bck_from_spt (sptnum)
n = np.zeros (sptnum.shape, dtype=np.int)
app_mbol = np.zeros (sptnum.shape)
w = np.isfinite (bcj) & np.isfinite (jmag)
app_mbol[w] += jmag[w] + bcj[w]
n[w] ... | Estimate a UCD's bolometric luminosity given some basic parameters.
sptnum: the spectral type as a number; 8 -> M8; 10 -> L0 ; 20 -> T0
Valid values range between 0 and 30, ie M0 to Y0.
dist_pc: distance to the object in parsecs
jmag: object's J-band magnitude or NaN (*not* None) if unavailable
k... |
def mass_from_j (j_abs):
j_abs = np.asfarray (j_abs)
return np.piecewise (j_abs,
[j_abs > 11,
j_abs <= 11,
j_abs < 5.5],
[0.1 * cgs.msun,
_delfosse_mass_from_j_helper,
... | Estimate mass in cgs from absolute J magnitude, using the relationship of
Delfosse+ (2000A&A...364..217D).
j_abs - The absolute J magnitude.
Returns: the estimated mass in grams.
If j_abs > 11, a fixed result of 0.1 Msun is returned. Values of j_abs <
5.5 are illegal and get NaN. There is a disco... |
def load_bcah98_mass_radius (tablelines, metallicity=0, heliumfrac=0.275,
age_gyr=5., age_tol=0.05):
mdata, rdata = [], []
for line in tablelines:
a = line.strip ().split ()
thismetallicity = float (a[0])
if thismetallicity != metallicity:
... | Load mass and radius from the main data table for the famous models of
Baraffe+ (1998A&A...337..403B).
tablelines
An iterable yielding lines from the table data file.
I've named the file '1998A&A...337..403B_tbl1-3.dat'
in some repositories (it's about 150K, not too bad).
metallicity
... |
def mk_radius_from_mass_bcah98 (*args, **kwargs):
from scipy.interpolate import UnivariateSpline
m, r = load_bcah98_mass_radius (*args, **kwargs)
spl = UnivariateSpline (m, r, s=1)
# This allows us to do range-checking with either scalars or vectors with
# minimal gymnastics.
@numutil.broa... | Create a function that maps (sub)stellar mass to radius, based on the
famous models of Baraffe+ (1998A&A...337..403B).
tablelines
An iterable yielding lines from the table data file.
I've named the file '1998A&A...337..403B_tbl1-3.dat'
in some repositories (it's about 150K, not too bad).
... |
def tauc_from_mass (mass_g):
m = mass_g / cgs.msun
return np.piecewise (m,
[m < 1.3,
m < 0.82,
m < 0.65,
m < 0.1],
[lambda x: 61.7 - 44.7 * x,
25.,
... | Estimate the convective turnover time from mass, using the method described
in Cook+ (2014ApJ...785...10C).
mass_g - UCD mass in grams.
Returns: the convective turnover timescale in seconds.
Masses larger than 1.3 Msun are out of range and yield NaN. If the mass is
<0.1 Msun, the turnover time is... |
def serial_ppmap(func, fixed_arg, var_arg_iter):
return [func(i, fixed_arg, x) for i, x in enumerate(var_arg_iter)] | A serial implementation of the "partially-pickling map" function returned
by the :meth:`ParallelHelper.get_ppmap` interface. Its arguments are:
*func*
A callable taking three arguments and returning a Pickle-able value.
*fixed_arg*
Any value, even one that is not pickle-able.
*var_arg_iter*... |
def multiprocessing_ppmap_worker(in_queue, out_queue, func, fixed_arg):
while True:
i, var_arg = in_queue.get()
if i is None:
break
out_queue.put((i, func(i, fixed_arg, var_arg))) | Worker for the :mod:`multiprocessing` ppmap implementation. Strongly
derived from code posted on StackExchange by "klaus se":
`<http://stackoverflow.com/a/16071616/3760486>`_. |
def map(self, func, iterable, chunksize=None):
# The key magic is that we must call r.get() with a timeout, because a
# Condition.wait() without a timeout swallows KeyboardInterrupts.
r = self.map_async(func, iterable, chunksize)
while True:
try:
ret... | Equivalent of `map` built-in, without swallowing KeyboardInterrupt.
func
The function to apply to the items.
iterable
An iterable of items that will have `func` applied to them. |
def _ppmap(self, func, fixed_arg, var_arg_iter):
n_procs = self.pool_kwargs.get('processes')
if n_procs is None:
# Logic copied from multiprocessing.pool.Pool.__init__()
try:
from multiprocessing import cpu_count
n_procs = cpu_count()
... | The multiprocessing implementation of the partially-Pickling "ppmap"
function. This doesn't use a Pool like map() does, because the whole
problem is that Pool chokes on un-Pickle-able values. Strongly derived
from code posted on StackExchange by "klaus se":
`<http://stackoverflow.com/a/1... |
def fmthours (radians, norm='wrap', precision=3, seps='::'):
return _fmtsexagesimal (radians * R2H, norm, 24, seps, precision=precision) | Format an angle as sexagesimal hours in a string.
Arguments are:
radians
The angle, in radians.
norm (default "wrap")
The normalization mode, used for angles outside of the standard range
of 0 to 2π. If "none", the value is formatted ignoring any potential
problems. If "wrap", it i... |
def fmtdeglon (radians, norm='wrap', precision=2, seps='::'):
return _fmtsexagesimal (radians * R2D, norm, 360, seps, precision=precision) | Format a longitudinal angle as sexagesimal degrees in a string.
Arguments are:
radians
The angle, in radians.
norm (default "wrap")
The normalization mode, used for angles outside of the standard range
of 0 to 2π. If "none", the value is formatted ignoring any potential
problems. I... |
def fmtradec (rarad, decrad, precision=2, raseps='::', decseps='::', intersep=' '):
return (fmthours (rarad, precision=precision + 1, seps=raseps) +
text_type (intersep) +
fmtdeglat (decrad, precision=precision, seps=decseps)) | Format equatorial coordinates in a single sexagesimal string.
Returns a string of the RA/lon coordinate, formatted as sexagesimal hours,
then *intersep*, then the Dec/lat coordinate, formatted as degrees. This
yields something like "12:34:56.78 -01:23:45.6". Arguments are:
rarad
The right ascens... |
def parsehours (hrstr):
hr = _parsesexagesimal (hrstr, 'hours', False)
if hr >= 24:
raise ValueError ('illegal hour specification: ' + hrstr)
return hr * H2R | Parse a string formatted as sexagesimal hours into an angle.
This function converts a textual representation of an angle, measured in
hours, into a floating point value measured in radians. The format of
*hrstr* is very limited: it may not have leading or trailing whitespace,
and the components of the ... |
def parsedeglat (latstr):
deg = _parsesexagesimal (latstr, 'latitude', True)
if abs (deg) > 90:
raise ValueError ('illegal latitude specification: ' + latstr)
return deg * D2R | Parse a latitude formatted as sexagesimal degrees into an angle.
This function converts a textual representation of a latitude, measured in
degrees, into a floating point value measured in radians. The format of
*latstr* is very limited: it may not have leading or trailing whitespace,
and the component... |
def sphdist (lat1, lon1, lat2, lon2):
cd = np.cos (lon2 - lon1)
sd = np.sin (lon2 - lon1)
c2 = np.cos (lat2)
c1 = np.cos (lat1)
s2 = np.sin (lat2)
s1 = np.sin (lat1)
a = np.sqrt ((c2 * sd)**2 + (c1 * s2 - s1 * c2 * cd)**2)
b = s1 * s2 + c1 * c2 * cd
return np.arctan2 (a, b) | Calculate the distance between two locations on a sphere.
lat1
The latitude of the first location.
lon1
The longitude of the first location.
lat2
The latitude of the second location.
lon2
The longitude of the second location.
Returns the separation in radians. All arguments... |
def parang (hourangle, declination, latitude):
return -np.arctan2 (-np.sin (hourangle),
np.cos (declination) * np.tan (latitude)
- np.sin (declination) * np.cos (hourangle)) | Calculate the parallactic angle of a sky position.
This computes the parallactic angle of a sky position expressed in terms
of an hour angle and declination. Arguments:
hourangle
The hour angle of the location on the sky.
declination
The declination of the location on the sky.
latitude... |
def load_skyfield_data():
import os.path
from astropy.config import paths
from skyfield.api import Loader
cache_dir = os.path.join(paths.get_cache_dir(), 'pwkit')
loader = Loader(cache_dir)
planets = loader('de421.bsp')
ts = loader.timescale()
return planets, ts | Load data files used in Skyfield. This will download files from the
internet if they haven't been downloaded before.
Skyfield downloads files to the current directory by default, which is not
ideal. Here we abuse astropy and use its cache directory to cache the data
files per-user. If we start download... |
def get_2mass_epoch (tmra, tmdec, debug=False):
import codecs
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
postdata = b'''-mime=csv
-source=2MASS
-out=_q,JD
-c=%.6f %.6f
-c.eq=J2000''' % (tmra * R2D, tmdec * R2D)
jd = None
for lin... | Given a 2MASS position, look up the epoch when it was observed.
This function uses the CDS Vizier web service to look up information in
the 2MASS point source database. Arguments are:
tmra
The source's J2000 right ascension, in radians.
tmdec
The source's J2000 declination, in radians.
... |
def get_simbad_astrometry_info (ident, items=_simbaditems, debug=False):
import codecs
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
s ... | Fetch astrometric information from the Simbad web service.
Given the name of a source as known to the CDS Simbad service, this
function looks up its positional information and returns it in a
dictionary. In most cases you should use an :class:`AstrometryInfo` object
and its :meth:`~AstrometryInfo.fill_... |
def predict_without_uncertainties(self, mjd, complain=True):
import sys
self.verify(complain=complain)
planets, ts = load_skyfield_data() # might download stuff from the internet
earth = planets['earth']
t = ts.tdb(jd = mjd + 2400000.5)
# "Best" position. The ... | Predict the object position at a given MJD.
The return value is a tuple ``(ra, dec)``, in radians, giving the
predicted position of the object at *mjd*. Unlike :meth:`predict`, the
astrometric uncertainties are ignored. This function is therefore
deterministic but potentially misleading... |
def print_prediction (self, ptup, precision=2):
from . import ellipses
bestra, bestdec, maj, min, pa = ptup
f = ellipses.sigmascale (1)
maj *= R2A
min *= R2A
pa *= R2D
print_ ('position =', fmtradec (bestra, bestdec, precision=precision))
print_... | Print a summary of a predicted position.
The argument *ptup* is a tuple returned by :meth:`predict`. It is
printed to :data:`sys.stdout` in a reasonable format that uses Unicode
characters. |
def unicode_stdio ():
if six.PY3:
return
enc = sys.stdin.encoding or 'utf-8'
sys.stdin = codecs.getreader (enc) (sys.stdin)
enc = sys.stdout.encoding or enc
sys.stdout = codecs.getwriter (enc) (sys.stdout)
enc = sys.stderr.encoding or enc
sys.stderr = codecs.getwriter (enc) (sy... | Make sure that the standard I/O streams accept Unicode.
In Python 2, the standard I/O streams accept bytes, not Unicode
characters. This means that in principle every Unicode string that we want
to output should be encoded to utf-8 before print()ing. But Python 2.X has
a hack where, if the output is a ... |
def backtrace_on_usr1 ():
import signal
try:
signal.signal (signal.SIGUSR1, _print_backtrace_signal_handler)
except Exception as e:
warn ('failed to set up Python backtraces on SIGUSR1: %s', e) | Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
Note, however, that the Python interpreter does not invoke Pytho... |
def die (fmt, *args):
if not len (args):
raise SystemExit ('error: ' + text_type (fmt))
raise SystemExit ('error: ' + (fmt % args)) | Raise a :exc:`SystemExit` exception with a formatted error message.
:arg str fmt: a format string
:arg args: arguments to the format string
If *args* is empty, a :exc:`SystemExit` exception is raised with the
argument ``'error: ' + str (fmt)``. Otherwise, the string component is
``fmt % args``. If... |
def pop_option (ident, argv=None):
if argv is None:
from sys import argv
if len (ident) == 1:
ident = '-' + ident
else:
ident = '--' + ident
found = ident in argv
if found:
argv.remove (ident)
return found | A lame routine for grabbing command-line arguments. Returns a boolean
indicating whether the option was present. If it was, it's removed from
the argument string. Because of the lame behavior, options can't be
combined, and non-boolean options aren't supported. Operates on sys.argv
by default.
Note... |
def show_usage (docstring, short, stream, exitcode):
if stream is None:
from sys import stdout as stream
if not short:
print ('Usage:', docstring.strip (), file=stream)
else:
intext = False
for l in docstring.splitlines ():
if intext:
if not ... | Print program usage information and exit.
:arg str docstring: the program help text
This function just prints *docstring* and exits. In most cases, the
function :func:`check_usage` should be used: it automatically checks
:data:`sys.argv` for a sole "-h" or "--help" argument and invokes this
functi... |
def check_usage (docstring, argv=None, usageifnoargs=False):
if argv is None:
from sys import argv
if len (argv) == 1 and usageifnoargs:
show_usage (docstring, (usageifnoargs != 'long'), None, 0)
if len (argv) == 2 and argv[1] in ('-h', '--help'):
show_usage (docstring, False, ... | Check if the program has been run with a --help argument; if so,
print usage information and exit.
:arg str docstring: the program help text
:arg argv: the program arguments; taken as :data:`sys.argv` if
given as :const:`None` (the default). (Note that this implies
``argv[0]`` should be the... |
def wrong_usage (docstring, *rest):
intext = False
if len (rest) == 0:
detail = 'invalid command-line arguments'
elif len (rest) == 1:
detail = rest[0]
else:
detail = rest[0] % tuple (rest[1:])
print ('error:', detail, '\n', file=sys.stderr) # extra NL
show_usage (... | Print a message indicating invalid command-line arguments and exit with an
error code.
:arg str docstring: the program help text
:arg rest: an optional specific error message
This function is intended for small programs launched from the command
line. The intention is for the program help informat... |
def excepthook (self, etype, evalue, etb):
self.inner_excepthook (etype, evalue, etb)
if issubclass (etype, KeyboardInterrupt):
# Don't try this at home, kids. On some systems os.kill (0, ...)
# signals our entire progress group, which is not what we want,
#... | Handle an uncaught exception. We always forward the exception on to
whatever `sys.excepthook` was present upon setup. However, if the
exception is a KeyboardInterrupt, we additionally kill ourselves with
an uncaught SIGINT, so that invoking programs know what happened. |
def calc_nu_b(b):
return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c) | Calculate the cyclotron frequency in Hz given a magnetic field strength in Gauss.
This is in cycles per second not radians per second; i.e. there is a 2π in
the denominator: ν_B = e B / (2π m_e c) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.