text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def excepthook (self, etype, evalue, etb):
"""Handle an uncaught exception. We always forward the exception on to whatever `sys.excepthook` was present upon setu... |
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,
# so we use os.getpid ().
signal.signal ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_nu_b(b):
"""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. ... |
return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_freefree_snu_ujy(ne, t, width, elongation, dist, ghz):
"""Calculate a flux density from pure free-free emission. """ |
hz = ghz * 1e9
eta = calc_freefree_eta(ne, t, hz)
kappa = calc_freefree_kappa(ne, t, hz)
snu = calc_snu(eta, kappa, width, elongation, dist)
ujy = snu * cgs.jypercgs * 1e6
return ujy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def concat(invises, outvis, timesort=False):
"""Concatenate visibility measurement sets. invises (list of str) Paths to the input measurement sets outvis (str) P... |
tb = util.tools.table()
ms = util.tools.ms()
if os.path.exists(outvis):
raise RuntimeError('output "%s" already exists' % outvis)
for invis in invises:
if not os.path.isdir(invis):
raise RuntimeError('input "%s" does not exist' % invis)
tb.open(b(invises[0]))
tb.c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delcal(mspath):
"""Delete the ``MODEL_DATA`` and ``CORRECTED_DATA`` columns from a measurement set. mspath (str) The path to the MS to modify Example:: from ... |
wantremove = 'MODEL_DATA CORRECTED_DATA'.split()
tb = util.tools.table()
tb.open(b(mspath), nomodify=False)
cols = frozenset(tb.colnames())
toremove = [b(c) for c in wantremove if c in cols]
if len(toremove):
tb.removecols(toremove)
tb.close()
# We want to return a `str` type, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delmod_cli(argv, alter_logger=True):
"""Command-line access to ``delmod`` functionality. The ``delmod`` task deletes "on-the-fly" model information from a Me... |
check_usage(delmod_doc, argv, usageifnoargs=True)
if alter_logger:
util.logger()
cb = util.tools.calibrater()
for mspath in argv[1:]:
cb.open(b(mspath), addcorr=False, addmodel=False)
cb.delmod(otf=True, scr=False)
cb.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extractbpflags(calpath, deststream):
"""Make a flags file out of a bandpass calibration table calpath (str) The path to the bandpass calibration table destst... |
tb = util.tools.table()
tb.open(b(os.path.join(calpath, 'ANTENNA')))
antnames = tb.getcol(b'NAME')
tb.close()
tb.open(b(calpath))
try:
t = tb.getkeyword(b'VisCal')
except RuntimeError:
raise PKError('no "VisCal" keyword in %s; it doesn\'t seem to be a '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flagmanager_cli(argv, alter_logger=True):
"""Command-line access to ``flagmanager`` functionality. The ``flagmanager`` task manages tables of flags associate... |
check_usage(flagmanager_doc, argv, usageifnoargs=True)
if len(argv) < 3:
wrong_usage(flagmanager_doc, 'expect at least a mode and an MS name')
mode = argv[1]
ms = argv[2]
if alter_logger:
if mode == 'list':
util.logger('info')
elif mode == 'delete':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image2fits(mspath, fitspath, velocity=False, optical=False, bitpix=-32, minpix=0, maxpix=-1, overwrite=False, dropstokes=False, stokeslast=True, history=True,... |
ia = util.tools.image()
ia.open(b(mspath))
ia.tofits(outfile=b(fitspath), velocity=velocity, optical=optical, bitpix=bitpix,
minpix=minpix, maxpix=maxpix, overwrite=overwrite, dropstokes=dropstokes,
stokeslast=stokeslast, history=history, **kwargs)
ia.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def importalma(asdm, ms):
"""Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path t... |
from .scripting import CasapyScript
script = os.path.join(os.path.dirname(__file__), 'cscript_importalma.py')
with CasapyScript(script, asdm=asdm, ms=ms) as cs:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def importevla(asdm, ms):
"""Convert an EVLA low-level SDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to... |
from .scripting import CasapyScript
# Here's the best way I can figure to find the recommended value of tbuff
#(= 1.5 * integration time). Obviously you might have different
# integration times in the dataset and such, and we're just going to
# ignore that possibility.
bdfstem = os.listdir(os... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listobs(vis):
"""Textually describe the contents of a measurement set. vis (str) The path to the dataset. Returns A generator of lines of human-readable outp... |
def inner_list(sink):
try:
ms = util.tools.ms()
ms.open(vis)
ms.summary(verbose=True)
ms.close()
except Exception as e:
sink.post(b'listobs failed: %s' % e, priority=b'SEVERE')
for line in util.forkandlog(inner_list):
info = l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mjd2date(mjd, precision=3):
"""Convert an MJD to a data string in the format used by CASA. mjd (numeric) An MJD value in the UTC timescale. precision (intege... |
from astropy.time import Time
dt = Time(mjd, format='mjd', scale='utc').to_datetime()
fracsec = ('%.*f' % (precision, 1e-6 * dt.microsecond)).split('.')[1]
return '%04d/%02d/%02d/%02d:%02d:%02d.%s' % (
dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, fracsec
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plotants(vis, figfile):
"""Plot the physical layout of the antennas described in the MS. vis (str) Path to the input dataset figfile (str) Path to the output... |
from .scripting import CasapyScript
script = os.path.join(os.path.dirname(__file__), 'cscript_plotants.py')
with CasapyScript(script, vis=vis, figfile=figfile) as cs:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def latexify(obj, **kwargs):
"""Render an object in LaTeX appropriately. """ |
if hasattr(obj, '__pk_latex__'):
return obj.__pk_latex__(**kwargs)
if isinstance(obj, text_type):
from .unicode_to_latex import unicode_to_latex
return unicode_to_latex(obj)
if isinstance(obj, bool):
# isinstance(True, int) = True, so gotta handle this first.
raise... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def latexify_n2col(x, nplaces=None, **kwargs):
"""Render a number into LaTeX in a 2-column format, where the columns split immediately to the left of the decimal... |
if nplaces is not None:
t = '%.*f' % (nplaces, x)
else:
t = '%f' % x
if '.' not in t:
return '$%s$ &' % t
left, right = t.split('.')
return '$%s$ & $.%s$' % (left, right) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def latexify_u3col(obj, **kwargs):
"""Convert an object to special LaTeX for uncertainty tables. This conversion is meant for uncertain values in a table. The re... |
if hasattr(obj, '__pk_latex_u3col__'):
return obj.__pk_latex_u3col__(**kwargs)
# TODO: there are reasonable ways to format many basic types, but I'm not
# going to implement them until I need to.
raise ValueError('can\'t LaTeXify %r in 3-column uncertain format' % obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def latexify_l3col(obj, **kwargs):
"""Convert an object to special LaTeX for limit tables. This conversion is meant for limit values in a table. The return value... |
if hasattr(obj, '__pk_latex_l3col__'):
return obj.__pk_latex_l3col__(**kwargs)
if isinstance(obj, bool):
# isinstance(True, int) = True, so gotta handle this first.
raise ValueError('no well-defined l3col LaTeXification of bool %r' % obj)
if isinstance(obj, float):
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read (path, tabwidth=8, **kwargs):
"""Read a typed tabular text file into a stream of Holders. Arguments: path The path of the file to read. tabwidth=8 The t... |
datamode = False
fixedcols = {}
for text in _trimmedlines (path, **kwargs):
text = text.expandtabs (tabwidth)
if datamode:
# table row
h = Holder ()
h.set (**fixedcols)
for name, cslice, parser in info:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write (stream, items, fieldnames, tabwidth=8):
"""Write a typed tabular text file to the specified stream. Arguments: stream The destination stream. items An... |
if isinstance (fieldnames, six.string_types):
fieldnames = fieldnames.split ()
maxlens = [0] * len (fieldnames)
# We have to make two passes, so listify:
items = list (items)
# pass 1: get types and maximum lengths for each record. Pad by 1 to
# ensure there's at least one space betw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vizread (descpath, descsection, tabpath, tabwidth=8, **kwargs):
"""Read a headerless tabular text file into a stream of Holders. Arguments: descpath The path... |
from .inifile import read as iniread
cols = []
for i in iniread (descpath):
if i.section != descsection:
continue
for field, desc in six.iteritems (i.__dict__):
if field == 'section':
continue
a = desc.split ()
idx0 = int (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _broadcast_shapes(s1, s2):
"""Given array shapes `s1` and `s2`, compute the shape of the array that would result from broadcasting them together.""" |
n1 = len(s1)
n2 = len(s2)
n = max(n1, n2)
res = [1] * n
for i in range(n):
if i >= n1:
c1 = 1
else:
c1 = s1[n1-1-i]
if i >= n2:
c2 = 1
else:
c2 = s2[n2-1-i]
if c1 == 1:
rc = c2
elif c2 ==... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_data(self, data, invsigma=None):
"""Set the data to be modeled. Returns *self*. """ |
self.data = np.array(data, dtype=np.float, ndmin=1)
if invsigma is None:
self.invsigma = np.ones(self.data.shape)
else:
i = np.array(invsigma, dtype=np.float)
self.invsigma = np.broadcast_arrays(self.data, i)[1] # allow scalar invsigma
if self.invsi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_soln(self):
"""Print information about the model solution.""" |
lmax = reduce(max,(len(x) for x in self.pnames), len('r chi sq'))
if self.puncerts is None:
for pn, val in zip(self.pnames, self.params):
print('%s: %14g' % (pn.rjust(lmax), val))
else:
for pn, val, err in zip(self.pnames, self.params, self.puncerts):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def show_corr(self):
"Show the parameter correlation matrix with `pwkit.ndshow_gtk3`."
from .ndshow_gtk3 import view
d = np.diag(self.covar) ** -0.5
corr = self.covar * d[np.newaxis,:] * d[:,np.newaxis]
view(corr, title='Correlation Matrix') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_func(self, func, pnames, args=()):
"""Set the model function to use an efficient but tedious calling convention. The function should obey the following c... |
from .lmmin import Problem
self.func = func
self._args = args
self.pnames = list(pnames)
self.lm_prob = Problem(len(self.pnames))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_simple_func(self, func, args=()):
"""Set the model function to use a simple but somewhat inefficient calling convention. The function should obey the fol... |
code = get_function_code(func)
npar = code.co_argcount - len(args)
pnames = code.co_varnames[:npar]
def wrapper(params, *args):
return func(*(tuple(params) + args))
return self.set_func(wrapper, pnames, args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_frozen_func(self, params):
"""Returns a model function frozen to the specified parameter values. Any remaining arguments are left free and must be provi... |
params = np.array(params, dtype=np.float, ndmin=1)
from functools import partial
return partial(self.func, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve(self, guess):
"""Solve for the parameters, using an initial guess. This uses the Levenberg-Marquardt optimizer described in :mod:`pwkit.lmmin`. Returns... |
guess = np.array(guess, dtype=np.float, ndmin=1)
f = self.func
args = self._args
def lmfunc(params, vec):
vec[:] = f(params, *args).flatten()
self.lm_prob.set_residual_func(self.data.flatten(),
self.invsigma.flatten(),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_nonlinear(self, params=None):
"""Return a `Model` equivalent to this object. The nonlinear solver is less efficient, but lets you freeze parameters, compu... |
if params is None:
params = self.params
nlm = Model(None, self.data, self.invsigma)
nlm.set_func(lambda p, x: npoly.polyval(x, p),
self.pnames,
args=(self.x,))
if params is not None:
nlm.solve(params)
return nlm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files(self):
"""Returns the URLs of all files attached to posts in the thread.""" |
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thumbs(self):
"""Returns the URLs of all thumbnails in the thread.""" |
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filenames(self):
"""Returns the filenames of all files attached to posts in the thread.""" |
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thumbnames(self):
"""Returns the filenames of all thumbnails in the thread.""" |
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, force=False):
"""Fetch new posts from the server. Arguments: force (bool):
Force a thread update, even if thread has 404'd. Returns: int: How m... |
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
# random connection error... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cas_a (freq_mhz, year):
"""Return the flux of Cas A given a frequency and the year of observation. Based on the formula given in Baars et al., 1977. Paramete... |
# The snu rule is right out of Baars et al. The dnu is corrected
# for the frequency being measured in MHz, not GHz.
snu = 10. ** (5.745 - 0.770 * np.log10 (freq_mhz)) # Jy
dnu = 0.01 * (0.07 - 0.30 * np.log10 (freq_mhz)) # percent per yr.
loss = (1 - dnu) ** (year - 1980.)
return snu * loss |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_cas_a (year):
"""Insert an entry for Cas A into the table of models. Need to specify the year of the observations to account for the time variation of C... |
year = float (year)
models['CasA'] = lambda f: cas_a (f, year) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_from_vla_obs (src, Lband, Cband):
"""Add an entry into the models table for a source based on L-band and C-band flux densities. """ |
if src in models:
raise PKError ('already have a model for ' + src)
fL = np.log10 (1425)
fC = np.log10 (4860)
lL = np.log10 (Lband)
lC = np.log10 (Cband)
A = (lL - lC) / (fL - fC)
B = lL - A * fL
def fluxdens (freq_mhz):
return 10. ** (A * np.log10 (freq_mhz) + B)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def databiv (xy, coordouter=False, **kwargs):
"""Compute the main parameters of a bivariate distribution from data. The parameters are returned in the same forma... |
xy = np.asarray (xy)
if xy.ndim != 2:
raise ValueError ('"xy" must be a 2D array')
if coordouter:
if xy.shape[0] != 2:
raise ValueError ('if "coordouter" is True, first axis of "xy" '
'must have size 2')
else:
if xy.shape[1] != 2:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bivrandom (x0, y0, sx, sy, cxy, size=None):
"""Compute random values distributed according to the specified bivariate distribution. Inputs: * x0: the center ... |
from numpy.random import multivariate_normal as mvn
p0 = np.asarray ([x0, y0])
cov = np.asarray ([[sx**2, cxy],
[cxy, sy**2]])
return mvn (p0, cov, size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bivconvolve (sx_a, sy_a, cxy_a, sx_b, sy_b, cxy_b):
"""Given two independent bivariate distributions, compute a bivariate distribution corresponding to their... |
_bivcheck (sx_a, sy_a, cxy_a)
_bivcheck (sx_b, sy_b, cxy_b)
sx_c = np.sqrt (sx_a**2 + sx_b**2)
sy_c = np.sqrt (sy_a**2 + sy_b**2)
cxy_c = cxy_a + cxy_b
return _bivcheck (sx_c, sy_c, cxy_c) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ellplot (mjr, mnr, pa):
"""Utility for debugging.""" |
_ellcheck (mjr, mnr, pa)
import omega as om
th = np.linspace (0, 2 * np.pi, 200)
x, y = ellpoint (mjr, mnr, pa, th)
return om.quickXY (x, y, 'mjr=%f mnr=%f pa=%f' %
(mjr, mnr, pa * 180 / np.pi)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abcd2 (x0, y0, a, b, c, x, y):
"""Given an 2D Gaussian expressed as the ABC polynomial coefficients, compute a "squared distance parameter" such that z = exp... |
_abccheck (a, b, c)
dx, dy = x - x0, y - y0
return -2 * (a * dx**2 + b * dx * dy + c * dy**2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eigh_robust(a, b=None, eigvals=None, eigvals_only=False, overwrite_a=False, overwrite_b=False, turbo=True, check_finite=True):
"""Robustly solve the Hermitia... |
kwargs = dict(eigvals=eigvals, eigvals_only=eigvals_only,
turbo=turbo, check_finite=check_finite,
overwrite_a=overwrite_a, overwrite_b=overwrite_b)
# Check for easy case first:
if b is None:
return linalg.eigh(a, **kwargs)
# Compute eigendecomposition of b
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_projection(self, X, W):
"""Compute the LPP projection matrix Parameters X : array_like, (n_samples, n_features) The input data W : array_like or spa... |
# TODO: check W input; handle sparse case
X = check_array(X)
D = np.diag(W.sum(1))
L = D - W
evals, evecs = eigh_robust(np.dot(X.T, np.dot(L, X)),
np.dot(X.T, np.dot(D, X)),
eigvals=(0, self.n_components - 1)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find_common_dtype(*args):
'''Returns common dtype of numpy and scipy objects.
Recognizes ndarray, spmatrix and LinearOperator. All other objects are
ignored (most notably None).'''
dtypes = []
for arg in args:
if type(arg) is numpy.ndarray or \
isspmatrix(arg) or \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inner(X, Y, ip_B=None):
'''Euclidean and non-Euclidean inner product.
numpy.vdot only works for vectors and numpy.dot does not use the conjugate
transpose.
:param X: numpy array with ``shape==(N,m)``
:param Y: numpy array with ``shape==(N,n)``
:param ip_B: (optional) May be one of the foll... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def norm_squared(x, Mx=None, inner_product=ip_euclid):
'''Compute the norm^2 w.r.t. to a given scalar product.'''
assert(len(x.shape) == 2)
if Mx is None:
rho = inner_product(x, x)
else:
assert(len(Mx.shape) == 2)
rho = inner_product(x, Mx)
if rho.shape == (1, 1):
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_linearoperator(shape, A, timer=None):
"""Enhances aslinearoperator if A is None.""" |
ret = None
import scipy.sparse.linalg as scipylinalg
if isinstance(A, LinearOperator):
ret = A
elif A is None:
ret = IdentityLinearOperator(shape)
elif isinstance(A, numpy.ndarray) or isspmatrix(A):
ret = MatrixLinearOperator(A)
elif isinstance(A, numpy.matrix):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def orthonormality(V, ip_B=None):
"""Measure orthonormality of given basis. :param V: a matrix :math:`V=[v_1,\ldots,v_n]` with ``shape==(N,n)``. :param ip_B: (op... |
return norm(numpy.eye(V.shape[1]) - inner(V, V, ip_B=ip_B)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arnoldi_res(A, V, H, ip_B=None):
"""Measure Arnoldi residual. :param A: a linear operator that can be used with scipy's aslinearoperator with ``shape==(N,N)`... |
N = V.shape[0]
invariant = H.shape[0] == H.shape[1]
A = get_linearoperator((N, N), A)
if invariant:
res = A*V - numpy.dot(V, H)
else:
res = A*V[:, :-1] - numpy.dot(V, H)
return norm(res, ip_B=ip_B) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qr(X, ip_B=None, reorthos=1):
"""QR factorization with customizable inner product. :param X: array with ``shape==(N,k)`` :param ip_B: (optional) inner produc... |
if ip_B is None and X.shape[1] > 0:
return scipy.linalg.qr(X, mode='economic')
else:
(N, k) = X.shape
Q = X.copy()
R = numpy.zeros((k, k), dtype=X.dtype)
for i in range(k):
for reortho in range(reorthos+1):
for j in range(i):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angles(F, G, ip_B=None, compute_vectors=False):
"""Principal angles between two subspaces. This algorithm is based on algorithm 6.2 in `Knyazev, Argentati. P... |
# make sure that F.shape[1]>=G.shape[1]
reverse = False
if F.shape[1] < G.shape[1]:
reverse = True
F, G = G, F
QF, _ = qr(F, ip_B=ip_B)
QG, _ = qr(G, ip_B=ip_B)
# one or both matrices empty? (enough to check G here)
if G.shape[1] == 0:
theta = numpy.ones(F.shape[1]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gap(lamda, sigma, mode='individual'):
"""Compute spectral gap. Useful for eigenvalue/eigenvector bounds. Computes the gap :math:`\delta\geq 0` between two se... |
# sanitize input
if numpy.isscalar(lamda):
lamda = [lamda]
lamda = numpy.array(lamda)
if numpy.isscalar(sigma):
sigma = [sigma]
sigma = numpy.array(sigma)
if not numpy.isreal(lamda).all() or not numpy.isreal(sigma).all():
raise ArgumentError('complex spectra not yet imp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bound_perturbed_gmres(pseudo, p, epsilon, deltas):
'''Compute GMRES perturbation bound based on pseudospectrum
Computes the GMRES bound from [SifEM13]_.
'''
if not numpy.all(numpy.array(deltas) > epsilon):
raise ArgumentError('all deltas have to be greater than epsilon')
bound = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_residual_norms(H, self_adjoint=False):
'''Compute relative residual norms from Hessenberg matrix.
It is assumed that the initial guess is chosen as zero.'''
H = H.copy()
n_, n = H.shape
y = numpy.eye(n_, 1, dtype=H.dtype)
resnorms = [1.]
for i in range(n_-1):
G = Givens(H[i:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, x):
"""Apply Householder transformation to vector x. Applies the Householder transformation efficiently to the given vector. """ |
# make sure that x is a (N,*) matrix
if len(x.shape) != 2:
raise ArgumentError('x is not a matrix of shape (N,*)')
if self.beta == 0:
return x
return x - self.beta * self.v * numpy.dot(self.v.T.conj(), x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matrix(self):
"""Build matrix representation of Householder transformation. Builds the matrix representation :math:`H = I - \\beta vv^*`. **Use with care!** ... |
n = self.v.shape[0]
return numpy.eye(n, n) - self.beta * numpy.dot(self.v, self.v.T.conj()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _apply(self, a, return_Ya=False):
r'''Single application of the projection.
:param a: array with ``a.shape==(N,m)``.
:param return_inner: (optional) should the inner product
:math:`\langle Y,a\rangle` be returned?
:return:
* :math:`P_{\mathcal{X},\mathcal{Y}^\pe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _apply_adj(self, a):
# is projection the zero operator?
if self.V.shape[1] == 0:
return numpy.zeros(a.shape)
'''Single application of the adjoint projection.'''
c = inner(self.V, a, ip_B=self.ip_B)
if self.Q is not None and self.R is not None:
c = self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, a, return_Ya=False):
r"""Apply the projection to an array. The computation is carried out without explicitly forming the matrix corresponding to ... |
# is projection the zero operator?
if self.V.shape[1] == 0:
Pa = numpy.zeros(a.shape)
if return_Ya:
return Pa, numpy.zeros((0, a.shape[1]))
return Pa
if return_Ya:
x, Ya = self._apply(a, return_Ya=return_Ya)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_complement(self, a, return_Ya=False):
"""Apply the complementary projection to an array. :param z: array with ``shape==(N,m)``. :return: :math:`P_{\\ma... |
# is projection the zero operator? --> complement is identity
if self.V.shape[1] == 0:
if return_Ya:
return a.copy(), numpy.zeros((0, a.shape[1]))
return a.copy()
if return_Ya:
x, Ya = self._apply(a, return_Ya=True)
else:
x... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self, key):
'''Return timings for `key`. Returns 0 if not present.'''
if key in self and len(self[key]) > 0:
return min(self[key])
else:
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_ops(self, ops):
'''Return timings for dictionary ops holding the operation names as
keys and the number of applications as values.'''
time = 0.
for op, count in ops.items():
time += self.get(op) * count
return time |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def min_pos(self):
'''Returns minimal positive value or None.'''
if self.__len__() == 0:
return ArgumentError('empty set has no minimum positive value.')
if self.contains(0):
return None
positive = [interval for interval in self.intervals
if in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def max_neg(self):
'''Returns maximum negative value or None.'''
if self.__len__() == 0:
return ArgumentError('empty set has no maximum negative value.')
if self.contains(0):
return None
negative = [interval for interval in self.intervals
if in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def min_abs(self):
'''Returns minimum absolute value.'''
if self.__len__() == 0:
return ArgumentError('empty set has no minimum absolute value.')
if self.contains(0):
return 0
return numpy.min([numpy.abs(val)
for val in [self.max_neg(), s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def max_abs(self):
'''Returns maximum absolute value.'''
if self.__len__() == 0:
return ArgumentError('empty set has no maximum absolute value.')
return numpy.max(numpy.abs([self.max(), self.min()])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_step(self, tol):
'''Return step at which bound falls below tolerance. '''
return 2 * numpy.log(tol/2.)/numpy.log(self.base) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def minmax_candidates(self):
'''Get points where derivative is zero.
Useful for computing the extrema of the polynomial over an interval if
the polynomial has real roots. In this case, the maximum is attained
for one of the interval endpoints or a point from the result of this
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def errors(self):
""" Check for usage errors """ |
try:
self.now = datetime.datetime.now()
if len(self.alarm_day) < 2 or len(self.alarm_day) > 2:
print("error: day: usage 'DD' such us '0%s' not '%s'" % (
self.alarm_day, self.alarm_day))
self.RUN_ALARM = False
if int(self.al... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_best_subset(self, ritz):
'''Return candidate set with smallest goal functional.'''
# (c,\omega(c)) for all considered subsets c
overall_evaluations = {}
def evaluate(_subset, _evaluations):
try:
_evaluations[_subset] = \
self.sub... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_default_command(self, command):
"""Sets a command function as the default command.""" |
cmd_name = command.name
self.add_command(command)
self.default_cmd_name = cmd_name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_residual(self, z, compute_norm=False):
r'''Compute residual.
For a given :math:`z\in\mathbb{C}^N`, the residual
.. math::
r = M M_l ( b - A z )
is computed. If ``compute_norm == True``, then also the absolute
residual norm
.. math::
\| M ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_ip_Minv_B(self):
'''Returns the inner product that is implicitly used with the positive
definite preconditioner ``M``.'''
if not isinstance(self.M, utils.IdentityLinearOperator):
if isinstance(self.Minv, utils.IdentityLinearOperator):
raise utils.ArgumentError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_xk(self, yk):
'''Compute approximate solution from initial guess and approximate
solution of the preconditioned linear system.'''
if yk is not None:
return self.x0 + self.linear_system.Mr * yk
return self.x0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _finalize_iteration(self, yk, resnorm):
'''Compute solution, error norm and residual norm if required.
:return: the residual norm or ``None``.
'''
self.xk = None
# compute error norm if asked for
if self.linear_system.exact_solution is not None:
self.xk =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def operations(nsteps):
'''Returns the number of operations needed for nsteps of GMRES'''
return {'A': 1 + nsteps,
'M': 2 + nsteps,
'Ml': 2 + nsteps,
'Mr': 1 + nsteps,
'ip_B': 2 + nsteps + nsteps*(nsteps+1)/2,
'axpy': 4 + 2*... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def solve(self, linear_system,
vector_factory=None,
*args, **kwargs):
'''Solve the given linear system with recycling.
The provided `vector_factory` determines which vectors are used for
deflation.
:param linear_system: the :py:class:`~krypy.linsys.LinearSys... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_hash(func, string):
"""compute hash of string using given hash function""" |
h = func()
h.update(string)
return h.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_local_serial():
''' Retrieves the serial number from the executing host.
For example, 'C02NT43PFY14'
'''
return [x for x in [subprocess.Popen("system_profiler SPHardwareDataType |grep -v tray |awk '/Serial/ {print $4}'", shell=True, stdout=subprocess.PIPE).communicate()[0].strip()] if x] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _estimate_eval_intervals(ritz, indices, indices_remaining,
eps_min=0,
eps_max=0,
eps_res=None):
'''Estimate evals based on eval inclusion theorem + heuristic.
:returns: Intervals object with inclusion... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def correct(self, z):
'''Correct the given approximate solution ``z`` with respect to the
linear system ``linear_system`` and the deflation space defined by
``U``.'''
c = self.linear_system.Ml*(
self.linear_system.b - self.linear_system.A*z)
c = utils.inner(self.W, c,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _apply_projection(self, Av):
'''Apply the projection and store inner product.
:param v: the vector resulting from an application of :math:`M_lAM_r`
to the current Arnoldi vector. (CG needs special treatment, here).
'''
PAv, UAv = self.projection.apply_complement(Av, return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_initial_residual(self, x0):
'''Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`.
'''
if x0 is None:
Mlr = self.linear_system.Mlb
else:
r = self.linear_system.b - self.linear_system.A*x0
Mlr = self.linear_system.Ml*... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def estimate_time(self, nsteps, ndefl, deflweight=1.0):
'''Estimate time needed to run nsteps iterations with deflation
Uses timings from :py:attr:`linear_system` if it is an instance of
:py:class:`~krypy.linsys.TimedLinearSystem`. Otherwise, an
:py:class:`~krypy.utils.OtherError`
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_vectors(self, indices=None):
'''Compute Ritz vectors.'''
H_ = self._deflated_solver.H
(n_, n) = H_.shape
coeffs = self.coeffs if indices is None else self.coeffs[:, indices]
return numpy.c_[self._deflated_solver.V[:, :n],
self._deflated_solver.proj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_explicit_residual(self, indices=None):
'''Explicitly computes the Ritz residual.'''
ritz_vecs = self.get_vectors(indices)
return self._deflated_solver.linear_system.MlAMr * ritz_vecs \
- ritz_vecs * self.values |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_explicit_resnorms(self, indices=None):
'''Explicitly computes the Ritz residual norms.'''
res = self.get_explicit_residual(indices)
# apply preconditioner
linear_system = self._deflated_solver.linear_system
Mres = linear_system.M * res
# compute norms
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transform_data(self, data):
'''Transform Pandas Timeseries into JSON format
Parameters
----------
data: DataFrame or Series
Pandas DataFrame or Series must have datetime index
Returns
-------
JSON to object.json_data
Example
----... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _build_graph(self):
'''Build Rickshaw graph syntax with all data'''
# Set palette colors if necessary
if not self.colors:
self.palette = self.env.get_template('palette.js')
self.template_vars.update({'palette': self.palette.render()})
self.colors = {x['na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_chart(self, html_path='index.html', data_path='data.json',
js_path='rickshaw.min.js', css_path='rickshaw.min.css',
html_prefix=''):
'''Save bearcart output to HTML and JSON.
Parameters
----------
html_path: string, default 'index.html... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_expire(self, y = 2999, mon = 12, d = 28, h = 23, min_ = 59, s = 59):
"""This method is used to change the expire date of a group - y is the year between ... |
if type(y) is not int or type(mon) is not int or type(d) is not int or \
type(h) is not int or type(min_) is not int or type(s) is not int:
raise KPError("Date variables must be integers")
elif y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or \
h > 23 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_entry(self, title='', image=1, url='', username='', password='', comment='', y=2999, mon=12, d=28, h=23, min_=59, s=59):
"""This method creates an ent... |
return self.db.create_entry(self, title, image, url, username,
password, comment, y, mon, d, h, min_, s) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_title(self, title = None):
"""This method is used to change an entry title. A new title string is needed. """ |
if title is None or type(title) is not str:
raise KPError("Need a new title.")
else:
self.title = title
self.last_mod = datetime.now().replace(microsecond=0)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_image(self, image = None):
"""This method is used to set the image number. image must be an unsigned int. """ |
if image is None or type(image) is not int:
raise KPError("Need a new image number")
else:
self.image = image
self.last_mod = datetime.now().replace(microsecond=0)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_url(self, url = None):
"""This method is used to set the url. url must be a string. """ |
if url is None or type(url) is not str:
raise KPError("Need a new image number")
else:
self.url = url
self.last_mod = datetime.now().replace(microsecond=0)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_username(self, username = None):
"""This method is used to set the username. username must be a string. """ |
if username is None or type(username) is not str:
raise KPError("Need a new image number")
else:
self.username = username
self.last_mod = datetime.now().replace(microsecond=0)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_password(self, password = None):
"""This method is used to set the password. password must be a string. """ |
if password is None or type(password) is not str:
raise KPError("Need a new image number")
else:
self.password = password
self.last_mod = datetime.now().replace(microsecond=0)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_comment(self, comment = None):
"""This method is used to the the comment. comment must be a string. """ |
if comment is None or type(comment) is not str:
raise KPError("Need a new image number")
else:
self.comment = comment
self.last_mod = datetime.now().replace(microsecond=0)
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.