code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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.listdi...
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 the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: from pwkit.environments.casa import...
4.752545
4.42952
1.072926
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...
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 output Errors can only be detected by looking at the output. Example:: from pwkit.environments.casa import tasks for line in tasks.listobs('myda...
8.577786
8.663565
0.990099
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 )
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 (integer, default 3) The number of digits of decimal precision in the seconds portion of the returned string Returns A string representing the input argument in CAS...
2.188352
2.271182
0.96353
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
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 image file. The output image format will be inferred from the extension of *figfile*. Example:: from pwkit.environments.casa import tasks tasks.pl...
5.935578
5.876881
1.009988
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. r...
def latexify(obj, **kwargs)
Render an object in LaTeX appropriately.
3.146104
3.064204
1.026728
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)
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 point. This gives nice alignment of numbers in a table.
3.042477
2.836829
1.072492
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)
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 return value should span three columns. The first column ends just before the decimal point in the main number value, if it has one. It has no separation from the second column. The ...
8.166535
7.440315
1.097606
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): ret...
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 should span three columns. The first column is the limit indicator: <, >, ~, etc. The second column is the whole part of the value, up until just before the decimal point. The thi...
5.223787
5.221245
1.000487
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: ...
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 tab width to assume. Please don't monkey with it. mode='rt' The file open mode (passed to io.open()). noexistok=False If True and the file is missing, treat...
4.877704
4.959061
0.983594
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 ...
def write (stream, items, fieldnames, tabwidth=8)
Write a typed tabular text file to the specified stream. Arguments: stream The destination stream. items An iterable of items to write. Two passes have to be made over the items (to discover the needed column widths), so this will be saved into a list. fieldnames Either a...
3.102428
3.12654
0.992288
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 = i...
def vizread (descpath, descsection, tabpath, tabwidth=8, **kwargs)
Read a headerless tabular text file into a stream of Holders. Arguments: descpath The path of the table description ini file. descsection The section in the description file to use. tabpath The path to the actual table data. tabwidth=8 The tab width to assume. Please don't ...
4.332414
3.785105
1.144596
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 c...
def _broadcast_shapes(s1, s2)
Given array shapes `s1` and `s2`, compute the shape of the array that would result from broadcasting them together.
1.936277
1.841722
1.05134
"Accesses :attr:`value` and :attr:`uncert` as a :class:`pwkit.msmt.Uval`." from .msmt import Uval return Uval.from_norm(self.value, self.uncert)
def uval(self)
Accesses :attr:`value` and :attr:`uncert` as a :class:`pwkit.msmt.Uval`.
9.038985
3.295828
2.742554
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 se...
def set_data(self, data, invsigma=None)
Set the data to be modeled. Returns *self*.
2.974121
3.081249
0.965232
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.punce...
def print_soln(self)
Print information about the model solution.
2.603622
2.57486
1.01117
import omega as om modelx = np.asarray(modelx) if modelx.shape != self.data.shape: raise ValueError('modelx and data arrays must have same shape') modely = self.mfunc(modelx) sigmas = self.invsigma**-1 # TODO: handle invsigma = 0 vb = om.layout.VBo...
def plot(self, modelx, dlines=False, xmin=None, xmax=None, ymin=None, ymax=None, **kwargs)
Plot the data and model (requires `omega`). This assumes that `data` is 1D and that `mfunc` takes one argument that should be treated as the X variable.
5.599304
5.51383
1.015502
"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')
def show_corr(self)
Show the parameter correlation matrix with `pwkit.ndshow_gtk3`.
9.082827
3.980686
2.281724
from .lmmin import Problem self.func = func self._args = args self.pnames = list(pnames) self.lm_prob = Problem(len(self.pnames)) return self
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 convention:: def func(param_vec, *args): modeled_data = { do something using param_vec } return modeled_data This function creates the :class:`...
7.239512
4.698961
1.540662
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)
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 following convention:: def func(param0, param1, ..., paramN, *args): modeled_data = { do something using the parameters } return modeled_data ...
3.795556
3.868987
0.981021
params = np.array(params, dtype=np.float, ndmin=1) from functools import partial return partial(self.func, params)
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 provided when the function is called. For this model, the returned function is the application of :func:`functools.partial` to the :attr:`func` property of this object.
4.209063
5.429115
0.775276
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(),...
def solve(self, guess)
Solve for the parameters, using an initial guess. This uses the Levenberg-Marquardt optimizer described in :mod:`pwkit.lmmin`. Returns *self*.
4.999784
4.98566
1.002833
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) re...
def as_nonlinear(self, params=None)
Return a `Model` equivalent to this object. The nonlinear solver is less efficient, but lets you freeze parameters, compute uncertainties, etc. If the `params` argument is provided, solve() will be called on the returned object with those parameters. If it is `None` and this object has ...
6.431026
5.284118
1.217048
from .lmmin import check_derivative return check_derivative(self.component.npar, self.data.size, self.lm_model, self.lm_deriv, guess)
def debug_derivative(self, guess)
returns (explicit, auto)
10.757903
10.731732
1.002439
plat = self._platform def path (*args): return os.path.join (self._installdir, *args) env['CALDB'] = b'http://heasarc.gsfc.nasa.gov/FTP/caldb' env['CALDBCONFIG'] = path ('caldb.config') env['CALDBALIAS'] = path ('alias_config.fits') env['HEADAS'] =...
def modify_environment (self, env)
The headas-init.sh script generates its variables in a bit of a funky way -- it runs a script that generates a list of settings. These are their transcriptions.
4.342233
4.313756
1.006601
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
def files(self)
Returns the URLs of all files attached to posts in the thread.
4.147393
3.206307
1.293511
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
def thumbs(self)
Returns the URLs of all thumbnails in the thread.
4.096972
3.696455
1.108352
if self.topic.has_file: yield self.topic.file.filename for reply in self.replies: if reply.has_file: yield reply.file.filename
def filenames(self)
Returns the filenames of all files attached to posts in the thread.
4.335788
3.356807
1.291641
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
def thumbnames(self)
Returns the filenames of all thumbnails in the thread.
4.58481
4.282933
1.070484
if self.topic.has_file: yield self.topic.file for reply in self.replies: if reply.has_file: yield reply.file
def file_objects(self)
Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread.
4.67687
3.58511
1.304526
# 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 connecti...
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 many new posts have been fetched.
3.046592
2.787632
1.092896
if args is None: import sys args = sys.argv[1:] parsed = Holder() for arg in args: if arg[0] == '+': for kw in arg[1:].split(','): parsed.set_one(kw, True) # avoid analogous -a,b,c syntax because it gets confused with -a --help, etc. ...
def basic(args=None)
Parse the string list *args* as a set of keyword arguments in a very simple-minded way, splitting on equals signs. Returns a :class:`pwkit.Holder` instance with attributes set to strings. The form ``+foo`` is mapped to setting ``foo = True`` on the :class:`pwkit.Holder` instance. If *args* is ``None``, ...
4.275548
3.302942
1.294466
if args is None: import sys args = sys.argv[1:] seen = set() for arg in args: t = arg.split('=', 1) if len(t) < 2: raise KwargvError('don\'t know what to do with argument "%s"', arg) kw, val = t k...
def parse(self, args=None)
Parse textual keywords as described by this class’s attributes, and update this instance’s attributes with the parsed values. *args* is a list of strings; if ``None``, it defaults to ``sys.argv[1:]``. Returns *self* for convenience. Raises :exc:`KwargvError` if invalid keywords are encou...
3.067713
2.993676
1.024731
from .cli import die try: return self.parse(args) except KwargvError as e: die(e)
def parse_or_die(self, args=None)
Like :meth:`ParseKeywords.parse`, but calls :func:`pkwit.cli.die` if a :exc:`KwargvError` is raised, printing the exception text. Returns *self* for convenience.
7.814667
3.022652
2.585367
# 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 * lo...
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. Parameters: freq - Observation frequency in MHz. year - Year of observation. May be floating-point. Returns: s, flux in Jy.
9.302899
8.142315
1.142537
year = float (year) models['CasA'] = lambda f: cas_a (f, year)
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 Cas A's emission.
11.364157
9.519609
1.193763
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...
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.
3.876458
3.639311
1.065163
import numpy as np, sys from correct_ant_posns import correct_ant_posns info = correct_ant_posns(vis, False) if len(info) != 3 or info[0] != 0 or not len(info[1]): helper.die('failed to fetch VLA antenna positions; got %r', info) antenna = info[1] parameter = info[2] with ope...
def in_casapy(helper, vis=None)
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.
5.452755
5.796782
0.940652
from scipy.special import erfc return np.sqrt (-2 * np.log (erfc (nsigma / np.sqrt (2))))
def sigmascale (nsigma)
Say we take a Gaussian bivariate and convert the parameters of the distribution to an ellipse (major, minor, PA). By what factor should we scale those axes to make the area of the ellipse correspond to the n-sigma confidence interval? Negative or zero values result in NaN.
4.779761
4.869473
0.981577
rv = np.sqrt (-2 * np.log (1 - cl)) rv[np.where (cl <= 0)] = np.nan return rv
def clscale (cl)
Say we take a Gaussian bivariate and convert the parameters of the distribution to an ellipse (major, minor, PA). By what factor should we scale those axes to make the area of the ellipse correspond to the confidence interval CL? (I.e. 0 < CL < 1)
5.143773
6.371304
0.807334
# See CfA notebook #1 pp. 129-133. _bivcheck (sx, sy, cxy) from numpy import arctan2, sqrt sx2, sy2, cxy2 = sx**2, sy**2, cxy**2 pa = 0.5 * arctan2 (2 * cxy, sx2 - sy2) h = sqrt ((sx2 - sy2)**2 + 4*cxy2) t = 2 * (sx2 * sy2 - cxy2) / (sx2 + sy2 - h) if t < 0: raise ValueEr...
def bivell (sx, sy, cxy)
Given the parameters of a Gaussian bivariate distribution, compute the parameters for the equivalent 2D Gaussian in ellipse form (major, minor, pa). Inputs: * sx: standard deviation (not variance) of x var * sy: standard deviation (not variance) of y var * cxy: covariance (not correlation coef...
3.367334
3.097407
1.087146
_bivcheck (sx, sy, cxy) from numpy import pi, sqrt t = (sx * sy)**2 - cxy**2 if t <= 0: raise ValueError ('covariance just barely out of bounds ' '(sx=%.10e, sy=%.10e, cxy=%.10e, cxy/sxsy=%.16f)' % (sx, sy, cxy, cxy / (sx * sy))) retu...
def bivnorm (sx, sy, cxy)
Given the parameters of a Gaussian bivariate distribution, compute the correct normalization for the equivalent 2D Gaussian. It's 1 / (2 pi sqrt (sx**2 sy**2 - cxy**2). This function adds a lot of sanity checking. Inputs: * sx: standard deviation (not variance) of x var * sy: standard deviation (n...
4.810017
5.484377
0.87704
_bivcheck (sx, sy, cxy) sx2, sy2, cxy2 = sx**2, sy**2, cxy**2 t = 1. / (sx2 * sy2 - cxy2) if t <= 0: raise ValueError ('covariance just barely out of bounds ' '(sx=%.10e, sy=%.10e, cxy=%.10e, cxy/sxsy=%.16f)' % (sx, sy, cxy, cxy / (sx * s...
def bivabc (sx, sy, cxy)
Compute nontrivial parameters for evaluating a bivariate distribution as a 2D Gaussian. Inputs: * sx: standard deviation (not variance) of x var * sy: standard deviation (not variance) of y var * cxy: covariance (not correlation coefficient) of x and y Returns: (a, b, c), where z = k exp (ax² + bx...
3.713791
4.015862
0.924781
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: ...
def databiv (xy, coordouter=False, **kwargs)
Compute the main parameters of a bivariate distribution from data. The parameters are returned in the same format as used in the rest of this module. * xy: a 2D data array of shape (2, nsamp) or (nsamp, 2) * coordouter: if True, the coordinate axis is the outer axis; i.e. the shape is (2, nsamp)....
2.512035
2.284655
1.099525
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)
def bivrandom (x0, y0, sx, sy, cxy, size=None)
Compute random values distributed according to the specified bivariate distribution. Inputs: * x0: the center of the x distribution (i.e. its intended mean) * y0: the center of the y distribution * sx: standard deviation (not variance) of x var * sy: standard deviation (not variance) of y var ...
3.178498
3.36494
0.944593
_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)
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 convolution. I'm sure this is worked out in a ton of places, but I got the equations from Pineau+ (2011A&A...527A.126P). Returns: (sx_c, sy_c, cxy_c), the parameters of the convolved distribution...
1.795515
2.04336
0.878707
_ellcheck (mjr, mnr, pa) from numpy import cos, sin ct, st = cos (th), sin (th) cp, sp = cos (pa), sin (pa) x = mjr * cp * ct - mnr * sp * st y = mjr * sp * ct + mnr * cp * st return x, y
def ellpoint (mjr, mnr, pa, th)
Compute a point on an ellipse parametrically. Inputs: * mjr: major axis (sigma not FWHM) of the ellipse * mnr: minor axis (sigma not FWHM) of the ellipse * pa: position angle (from +x to +y) of the ellipse, radians * th: the parameter, 0 <= th < 2pi: the eccentric anomaly Returns: (x, y) th m...
2.648271
3.095042
0.855649
_ellcheck (mjr, mnr, pa) dx, dy = x - x0, y - y0 c, s = np.cos (pa), np.sin (pa) a = c * dx + s * dy b = -s * dx + c * dy return (a / mjr)**2 + (b / mnr)**2
def elld2 (x0, y0, mjr, mnr, pa, x, y)
Given an 2D Gaussian expressed as an ellipse (major, minor, pa), compute a "squared distance parameter" such that z = exp (-0.5 * d2) Inputs: * x0: position of Gaussian center on x axis * y0: position of Gaussian center on y axis * mjr: major axis (sigma not FWHM) of the Gaussian * mnr...
2.693424
3.533936
0.76216
_ellcheck (mjr, mnr, pa) cpa, spa = np.cos (pa), np.sin (pa) q = np.asarray ([[cpa, -spa], [spa, cpa]]) cov = np.dot (q, np.dot (np.diag ([mjr**2, mnr**2]), q.T)) sx = np.sqrt (cov[0,0]) sy = np.sqrt (cov[1,1]) cxy = cov[0,1] return _bivcheck (sx, sy, cxy)
def ellbiv (mjr, mnr, pa)
Given a 2D Gaussian expressed as an ellipse (major, minor, pa), compute the equivalent parameters for a Gaussian bivariate distribution. We assume that the ellipse is normalized so that the functions evaluate identicall for major = minor. Inputs: * mjr: major axis (sigma not FWHM) of the Gaussian ...
3.257749
3.665732
0.888704
_ellcheck (mjr, mnr, pa) cpa, spa = np.cos (pa), np.sin (pa) mjrm2, mnrm2 = mjr**-2, mnr**-2 a = -0.5 * (cpa**2 * mjrm2 + spa**2 * mnrm2) c = -0.5 * (spa**2 * mjrm2 + cpa**2 * mnrm2) b = cpa * spa * (mnrm2 - mjrm2) return _abccheck (a, b, c)
def ellabc (mjr, mnr, pa)
Given a 2D Gaussian expressed as an ellipse (major, minor, pa), compute the nontrivial parameters for its evaluation. * mjr: major axis (sigma not FWHM) of the Gaussian * mnr: minor axis (sigma not FWHM) of the Gaussian * pa: position angle (from +x to +y) of the Gaussian, radians Returns: (a, b, ...
3.171601
3.647024
0.869641
# 1. We need to rotate the frame so that ellipse 1 lies on the X axis. theta = -np.arctan2 (dy, dx) # 2. We also need to express these rotated ellipses in "biv" format. sx0, sy0, cxy0 = ellbiv (mjr0, mnr0, pa0 + theta) sx1, sy1, cxy1 = ellbiv (mjr1, mnr1, pa1 + theta) # 3. Their convoluti...
def double_ell_distance (mjr0, mnr0, pa0, mjr1, mnr1, pa1, dx, dy)
Given two ellipses separated by *dx* and *dy*, compute their separation in terms of σ. Based on Pineau et al (2011A&A...527A.126P). The "0" ellipse is taken to be centered at (0, 0), while the "1" ellipse is centered at (dx, dy).
4.789203
4.615139
1.037716
_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))
def ellplot (mjr, mnr, pa)
Utility for debugging.
4.080813
4.114813
0.991737
from numpy import arctan2, sqrt bad = _abccheck (a, b, c) pa = 0.5 * arctan2 (b, a - c) t1 = np.sqrt ((a - c)**2 + b**2) t2 = -t1 - a - c bad |= (t2 <= 0) mjr = t2**-0.5 t2 = t1 - a - c bad |= (t2 <= 0) mnr = t2**-0.5 w = np.where (bad) mjr[w] = np.nan mnr[w]...
def abcell (a, b, c)
Given the nontrivial parameters for evaluation a 2D Gaussian as a polynomial, compute the equivalent ellipse parameters (major, minor, pa) Inputs: (a, b, c), where z = exp (ax² + bxy + cy²) Returns: * mjr: major axis (sigma not FWHM) of the Gaussian * mnr: minor axis (sigma not FWHM) of the Gauss...
4.183322
3.528167
1.185693
_abccheck (a, b, c) dx, dy = x - x0, y - y0 return -2 * (a * dx**2 + b * dx * dy + c * dy**2)
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 (-0.5 * d2) Inputs: * x0: position of Gaussian center on x axis * y0: position of Gaussian center on y axis * a: such that z = exp (ax² + bxy + cy²) * b: see abov...
3.650297
4.335837
0.84189
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 o...
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 Hermitian generalized eigenvalue problem This function robustly solves the Hermetian generalized eigenvalue problem ``A v = lambda B v`` in the case that B is not strictly positive definite. When B is strictly positive-definite, the result is equivalent to scipy.linalg.eigh() within ...
2.784837
3.132185
0.889104
# 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_compone...
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 sparse matrix, (n_samples, n_samples) The precomputed adjacency matrix Returns ------- P : ndarray, (n_featur...
3.79213
4.035402
0.939715
'''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 \ isinstance(arg, Li...
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).
4.766478
2.439317
1.954021
'''Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``. Recognizes ndarrays and ignores all others.''' ret_args = [] flat_vecs = True for arg in args: if type(arg) is numpy.ndarray: if len(arg.shape) == 1: arg = shape_vec(arg) else: ...
def shape_vecs(*args)
Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``. Recognizes ndarrays and ignores all others.
4.477834
2.532073
1.768446
'''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 following * ``None``: E...
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 following * ``None``: Euclidea...
4.801283
1.580038
3.038715
'''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 abs(rho[0, 0].imag) > abs(rho[0, 0])*1e-10 or rho[0, 0...
def norm_squared(x, Mx=None, inner_product=ip_euclid)
Compute the norm^2 w.r.t. to a given scalar product.
3.60257
3.161006
1.139691
r'''Compute norm (Euclidean and non-Euclidean). :param x: a 2-dimensional ``numpy.array``. :param y: a 2-dimensional ``numpy.array``. :param ip_B: see :py:meth:`inner`. Compute :math:`\sqrt{\langle x,y\rangle}` where the inner product is defined via ``ip_B``. ''' # Euclidean inner prod...
def norm(x, y=None, ip_B=None)
r'''Compute norm (Euclidean and non-Euclidean). :param x: a 2-dimensional ``numpy.array``. :param y: a 2-dimensional ``numpy.array``. :param ip_B: see :py:meth:`inner`. Compute :math:`\sqrt{\langle x,y\rangle}` where the inner product is defined via ``ip_B``.
3.310318
2.252181
1.469828
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): ...
def get_linearoperator(shape, A, timer=None)
Enhances aslinearoperator if A is None.
2.871167
2.857134
1.004911
return norm(numpy.eye(V.shape[1]) - inner(V, V, ip_B=ip_B))
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: (optional) the inner product to use, see :py:meth:`inner`. :return: :math:`\\| I_n - \\langle V,V \\rangle \\|_2`.
4.838157
5.00308
0.967036
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)
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)``. :param V: Arnoldi basis matrix with ``shape==(N,n)``. :param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with ``shape==(n,n-1)`` or :math:`H_n` with ``shape=...
4.258715
3.878379
1.098066
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): ...
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 product, see :py:meth:`inner`. :param reorthos: (optional) numer of reorthogonalizations. Defaults to 1 (i.e. 2 runs of modified Gram-Schmidt) which should be enough in most cas...
2.278141
2.234239
1.01965
N = len(b) shape = (N, N) A = get_linearoperator(shape, A) M = get_linearoperator(shape, M) Ml = get_linearoperator(shape, Ml) MlAx0 = Ml*(A*x0) z = M*MlAx0 znorm2 = inner(z, MlAx0, ip_B=ip_B) if znorm2 <= 1e-15: return numpy.zeros((N, 1)) gamma = inner(z, Ml*b, ip_...
def hegedus(A, b, x0, M=None, Ml=None, ip_B=None)
Rescale initial guess appropriately (Hegedüs trick). The Hegedüs trick rescales the initial guess to :math:`\\gamma_{\\min} x_0` such that .. math :: \\|r_0\\|_{M^{-1}} = \\| M M_l (b - A \\gamma_{\\min} x_0) \\|_{M^{-1}} = \\min_{\\gamma\\in\\mathbb{C}} \\| M M_l (b - A \\gamma...
3.683407
3.466711
1.062508
d = [l_min + (i-1)*1./(n-1)*(l_max-l_min)*(rho**(n-i)) for i in range(1, n+1)] return numpy.diag(d)
def strakos(n, l_min=0.1, l_max=100, rho=0.9)
Return the Strakoš matrix. See [Str92]_.
3.82761
4.211195
0.908913
# 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...
def gap(lamda, sigma, mode='individual')
Compute spectral gap. Useful for eigenvalue/eigenvector bounds. Computes the gap :math:`\delta\geq 0` between two sets of real numbers ``lamda`` and ``sigma``. The gap can be computed in several ways and may not exist, see the ``mode`` parameter. :param lamda: a non-empty set :math:`\Lambda=...
2.605928
2.430401
1.072221
'''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 = [] for delta in deltas: # get boundary paths ...
def bound_perturbed_gmres(pseudo, p, epsilon, deltas)
Compute GMRES perturbation bound based on pseudospectrum Computes the GMRES bound from [SifEM13]_.
7.280986
4.937137
1.474739
'''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:i+2, [i]]) if self_adjoint: ...
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.
3.016863
2.480267
1.216346
# 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)
def apply(self, x)
Apply Householder transformation to vector x. Applies the Householder transformation efficiently to the given vector.
4.782529
4.950663
0.966038
n = self.v.shape[0] return numpy.eye(n, n) - self.beta * numpy.dot(self.v, self.v.T.conj())
def matrix(self)
Build matrix representation of Householder transformation. Builds the matrix representation :math:`H = I - \\beta vv^*`. **Use with care!** This routine may be helpful for testing purposes but should not be used in production codes for high dimensions since the resulting matrix...
5.236419
3.408218
1.536409
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}^\perp} a = X \langle Y,X\rang...
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}^\perp} a = X \langle Y,X\rangle^{-1} ...
4.040078
2.315294
1.744952
# 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.Q.dot(scipy.linalg.solve...
def _apply_adj(self, a)
Single application of the adjoint projection.
5.941753
4.984541
1.192036
r # 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: ...
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 the projection (which would be an array with ``shape==(N,N)``). See also :py:meth:`_apply`.
3.846622
3.876315
0.99234
# 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: ...
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_{\\mathcal{Y}^\\perp,\\mathcal{X}}z = z - P_{\\mathcal{X},\\mathcal{Y}^\\perp} z`.
3.562381
4.065685
0.876207
# is projection the zero operator? if self.V.shape[1] == 0: N = self.V.shape[0] return ZeroLinearOperator((N, N)) return self._get_operator(self.apply, self.apply_adj)
def operator(self)
Get a ``LinearOperator`` corresponding to apply(). :return: a LinearOperator that calls apply().
8.02759
7.250243
1.107217
# is projection the zero operator? --> complement is identity if self.V.shape[1] == 0: N = self.V.shape[0] return IdentityLinearOperator((N, N)) return self._get_operator(self.apply_complement, self.apply_complement_adj)
def operator_complement(self)
Get a ``LinearOperator`` corresponding to apply_complement(). :return: a LinearOperator that calls apply_complement().
8.681416
8.086563
1.073561
'''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
def get(self, key)
Return timings for `key`. Returns 0 if not present.
5.933174
3.053544
1.943045
'''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
def get_ops(self, ops)
Return timings for dictionary ops holding the operation names as keys and the number of applications as values.
9.962518
2.851213
3.494134
'''Returns the distance to other (0 if intersection is nonempty).''' if self & other: return 0 return numpy.max([other.left-self.right, self.left-other.right])
def distance(self, other)
Returns the distance to other (0 if intersection is nonempty).
9.135179
4.02508
2.269564
'''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 interval.left > 0] ...
def min_pos(self)
Returns minimal positive value or None.
5.407763
4.582348
1.180129
'''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 interval.right < 0] ...
def max_neg(self)
Returns maximum negative value or None.
5.091372
4.598412
1.107202
'''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(), self.min_pos()] ...
def min_abs(self)
Returns minimum absolute value.
6.401976
6.226854
1.028124
'''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()]))
def max_abs(self)
Returns maximum absolute value.
7.943118
7.626197
1.041557
'''Return step at which bound falls below tolerance. ''' return 2 * numpy.log(tol/2.)/numpy.log(self.base)
def get_step(self, tol)
Return step at which bound falls below tolerance.
14.30343
7.442192
1.921938
'''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 function that is contained in ...
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 function that is contained in the interva...
10.890224
2.155344
5.052662
alarm_day = alarm_time = alarm_attempts = song = [] for line in open(alarm_config, "r"): line = line.lstrip() if line.startswith("DAY"): alarm_day = line[4:].split() if line.startswith("ALARM_TIME"): alarm_time = line[11:].split() if line.startswith("...
def config()
Reading config file in $HOME directory /home/user/.alarm/config
2.730123
2.555636
1.068276
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...
def errors(self)
Check for usage errors
2.553434
2.486854
1.026773
self.errors() try: alarm_day_name = calendar.day_name[calendar.weekday( self.now.year, self.now.month, int(self.alarm_day))] except ValueError: pass self.alarm_time.insert(0, self.alarm_day) self.alarm_time = ":".join(self.alarm_ti...
def start(self)
All the work going on here. To the Authority the right day and time format and finding the correct path of the file. The Application requires Mplayer to play the alarm sound. Please read which sounds are supported in page: http://web.njit.edu/all_topics/Prog_Lang_Docs/html/mplayer/format...
3.964455
3.864958
1.025743
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) sys.stdout.flush()
def position(self, x, y, text)
ANSI Escape sequences http://ascii-table.com/ansi-escape-sequences.php
2.19768
2.365177
0.929182
'''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.subset_evaluator.evaluate(ritz, _subs...
def _get_best_subset(self, ritz)
Return candidate set with smallest goal functional.
4.142834
3.990932
1.038062
cmd_name = command.name self.add_command(command) self.default_cmd_name = cmd_name
def set_default_command(self, command)
Sets a command function as the default command.
4.507097
4.210132
1.070536
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 M_l (b-Az)\|_{M^{-1}} is computed. ...
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 M_l (b-Az)\|_{M^{-1}} is computed. :p...
5.309097
2.26014
2.349013
'''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( 'Mi...
def get_ip_Minv_B(self)
Returns the inner product that is implicitly used with the positive definite preconditioner ``M``.
5.63182
3.566879
1.578921
'''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
def _get_xk(self, yk)
Compute approximate solution from initial guess and approximate solution of the preconditioned linear system.
11.840405
4.941868
2.395937
'''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 = self._get_xk(yk) self.errnorms....
def _finalize_iteration(self, yk, resnorm)
Compute solution, error norm and residual norm if required. :return: the residual norm or ``None``.
4.210227
3.895878
1.080688
'''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*nsteps + nsteps*(nsteps+...
def operations(nsteps)
Returns the number of operations needed for nsteps of GMRES
4.918868
4.051697
1.214027
'''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.LinearSystem` that is about to be solved. :param vector_factory: (optional) see descripti...
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.LinearSystem` that is about to be solved. :param vector_factory: (optional) see description in const...
4.478902
2.818214
1.58927
h = func() h.update(string) return h.hexdigest()
def compute_hash(func, string)
compute hash of string using given hash function
4.197461
3.65721
1.147722
''' 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]
def get_local_serial()
Retrieves the serial number from the executing host. For example, 'C02NT43PFY14'
7.944442
3.336908
2.38078