code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
import omega as om
if use_lowlevel:
out_vals = do_figure9_calc_lowlevel(shlib_path, **kwargs)
else:
out_vals = do_figure9_calc_highlevel(shlib_path, **kwargs)
freqs = out_vals[:,OUT_VAL_FREQ]
tot_ints = out_vals[:,OUT_VAL_OINT] + out_vals[:,OUT_VAL_XINT]
pos = (tot_ints > ... | def make_figure9_plot(shlib_path, use_lowlevel=True, **kwargs) | Reproduce Figure 9 of the Fleischman & Kuznetsov (2010) paper, using our
low-level interfaces. Uses OmegaPlot, of course.
Input parameters, etc., come from the file ``Flare071231a.pro`` that is
distributed with the paper’s Supplementary Data archive.
Invoke with something like::
from pwkit impo... | 4.511658 | 4.752298 | 0.949363 |
inst = (cls(shlib_path)
.set_thermal_background(2.1e7, 3e9)
.set_bfield(48)
.set_edist_powerlaw(0.016, 4.0, 3.7, 5e9/3)
.set_freqs(100, 0.5, 50)
.set_hybrid_parameters(12, 12)
.set_ignore_q_terms(False)
.set_obs_angle(5... | def new_for_fk10_fig9(cls, shlib_path) | Create a calculator initialized to reproduce Figure 9 from FK10.
This is mostly to provide a handy way to create a new
:class:`Calculator` instance that is initialized with reasonable
values for all of its parameters. | 7.415474 | 7.482756 | 0.991008 |
if not (B_G > 0):
raise ValueError('must have B_G > 0; got %r' % (B_G,))
self.in_vals[IN_VAL_B] = B_G
return self | def set_bfield(self, B_G) | Set the strength of the local magnetic field.
**Call signature**
*B_G*
The magnetic field strength, in Gauss
Returns
*self* for convenience in chaining. | 5.852808 | 6.44511 | 0.908101 |
if not (s0 > 0):
raise ValueError('must have s0 > 0; got %r' % (s0,))
B0 = 2 * np.pi * cgs.me * cgs.c * self.in_vals[IN_VAL_FREQ0] / (cgs.e * s0)
self.in_vals[IN_VAL_B] = B0
return self | def set_bfield_for_s0(self, s0) | Set B to probe a certain harmonic number.
**Call signature**
*s0*
The harmonic number to probe at the lowest frequency
Returns
*self* for convenience in chaining.
This just proceeds from the relation ``nu = s nu_c = s e B / 2 pi m_e
c``. Since *s* and *nu* ... | 5.022758 | 5.030212 | 0.998518 |
if not (emin_mev >= 0):
raise ValueError('must have emin_mev >= 0; got %r' % (emin_mev,))
if not (emax_mev >= emin_mev):
raise ValueError('must have emax_mev >= emin_mev; got %r, %r' % (emax_mev, emin_mev))
if not (delta >= 0):
raise ValueError('must ... | def set_edist_powerlaw(self, emin_mev, emax_mev, delta, ne_cc) | Set the energy distribution function to a power law.
**Call signature**
*emin_mev*
The minimum energy of the distribution, in MeV
*emax_mev*
The maximum energy of the distribution, in MeV
*delta*
The power-law index of the distribution
*ne_cc*
... | 1.850551 | 1.898197 | 0.974899 |
if not (gmin >= 1):
raise ValueError('must have gmin >= 1; got %r' % (gmin,))
if not (gmax >= gmin):
raise ValueError('must have gmax >= gmin; got %r, %r' % (gmax, gmin))
if not (delta >= 0):
raise ValueError('must have delta >= 0; got %r, %r' % (delt... | def set_edist_powerlaw_gamma(self, gmin, gmax, delta, ne_cc) | Set the energy distribution function to a power law in the Lorentz factor
**Call signature**
*gmin*
The minimum Lorentz factor of the distribution
*gmax*
The maximum Lorentz factor of the distribution
*delta*
The power-law index of the distribution
... | 2.130253 | 2.218893 | 0.960052 |
if not (f_lo_ghz >= 0):
raise ValueError('must have f_lo_ghz >= 0; got %r' % (f_lo_ghz,))
if not (f_hi_ghz >= f_lo_ghz):
raise ValueError('must have f_hi_ghz >= f_lo_ghz; got %r, %r' % (f_hi_ghz, f_lo_ghz))
if not n >= 1:
raise ValueError('must have n... | def set_freqs(self, n, f_lo_ghz, f_hi_ghz) | Set the frequency grid on which to perform the calculations.
**Call signature**
*n*
The number of frequency points to sample.
*f_lo_ghz*
The lowest frequency to sample, in GHz.
*f_hi_ghz*
The highest frequency to sample, in GHz.
Returns
*... | 2.191966 | 2.240527 | 0.978326 |
self.in_vals[IN_VAL_FCCR] = s_C
self.in_vals[IN_VAL_FWHCR] = s_WH
self.in_vals[IN_VAL_RENORMFLAG] = 1 if do_renorm else 0
return self | def set_hybrid_parameters(self, s_C, s_WH, do_renorm=True) | Set the hybrid/renormalization control parameters.
**Call signature**
*s_C*
The harmonic number above which the continuous approximation
is used (with special behavior; see below).
*s_WH*
The harmonic number above which the Wild-Hill BEssel function
appr... | 4.115705 | 4.293926 | 0.958495 |
self.in_vals[IN_VAL_THETA] = theta_rad * 180 / np.pi # rad => deg
return self | def set_obs_angle(self, theta_rad) | Set the observer angle relative to the field.
**Call signature**
*theta_rad*
The angle between the ray path and the local magnetic field,
in radians.
Returns
*self* for convenience in chaining. | 8.952537 | 13.123049 | 0.682199 |
if not (f_ghz >= 0):
raise ValueError('must have f_lo_ghz >= 0; got %r' % (f_lo_ghz,))
self.in_vals[IN_VAL_NFREQ] = 1
self.in_vals[IN_VAL_FREQ0] = f_ghz * 1e9 # GHz -> Hz
self.in_vals[IN_VAL_LOGDFREQ] = 1.0
return self | def set_one_freq(self, f_ghz) | Set the code to calculate results at just one frequency.
**Call signature**
*f_ghz*
The frequency to sample, in GHz.
Returns
*self* for convenience in chaining. | 4.519219 | 4.6443 | 0.973068 |
self.in_vals[IN_VAL_PADIST] = PADIST_GLC
self.in_vals[IN_VAL_LCBDY] = boundary_rad * 180 / np.pi # rad => deg
self.in_vals[IN_VAL_DELTAMU] = expwidth
return self | def set_padist_gaussian_loss_cone(self, boundary_rad, expwidth) | Set the pitch-angle distribution to a Gaussian loss cone.
**Call signature**
*boundary_rad*
The angle inside which there are no losses, in radians.
*expwidth*
The characteristic width of the Gaussian loss profile
*in direction-cosine units*.
Returns
... | 6.34945 | 6.300457 | 1.007776 |
if not (T_K >= 0):
raise ValueError('must have T_K >= 0; got %r' % (T_K,))
if not (nth_cc >= 0):
raise ValueError('must have nth_cc >= 0; got %r, %r' % (nth_cc,))
self.in_vals[IN_VAL_T0] = T_K
self.in_vals[IN_VAL_N0] = nth_cc
return self | def set_thermal_background(self, T_K, nth_cc) | Set the properties of the background thermal plasma.
**Call signature**
*T_K*
The temperature of the background plasma, in Kelvin.
*nth_cc*
The number density of thermal electrons, in cm^-3.
Returns
*self* for convenience in chaining.
Note that th... | 2.979187 | 3.397512 | 0.876873 |
if not (n >= 2):
raise ValueError('must have n >= 2; got %r' % (n,))
self.in_vals[IN_VAL_INTEG_METH] = n + 1
return self | def set_trapezoidal_integration(self, n) | Set the code to use trapezoidal integration.
**Call signature**
*n*
Use this many nodes
Returns
*self* for convenience in chaining. | 8.900754 | 9.909593 | 0.898196 |
j_O, alpha_O, j_X, alpha_X = self.find_rt_coefficients(depth0=depth0)
j_I = j_O + j_X
alpha_I = 0.5 * (alpha_O + alpha_X) # uhh... right?
return (j_I, alpha_I) | def find_rt_coefficients_tot_intens(self, depth0=None) | Figure out total-intensity emission and absorption coefficients for the
current parameters.
**Argument**
*depth0* (default None)
A first guess to use for a good integration depth, in cm. If None,
the most recent value is used.
**Return value**
A tuple ``(j... | 4.074497 | 3.380502 | 1.205293 |
try:
return io.open (*args, **kwargs)
except IOError as e:
if e.errno == 2:
return None
raise | def try_open (*args, **kwargs) | Simply a wrapper for io.open(), unless an IOError with errno=2 (ENOENT) is
raised, in which case None is retured. | 2.811952 | 2.000793 | 1.405419 |
from os.path import join
base = join (*baseparts)
def path_func (*args):
return join (base, *args)
return path_func | def make_path_func (*baseparts) | Return a function that joins paths onto some base directory. | 3.506816 | 3.027941 | 1.158152 |
from os.path import join
i = 0
alen = len (args)
while i < alen and (args[i] == '' or args[i] == '.'):
i += 1
if i == alen:
return '.'
return join (*args[i:]) | def djoin (*args) | dotless' join, for nicer paths. | 3.127298 | 2.810573 | 1.112691 |
from os.path import isabs, dirname, relpath, abspath
if isabs (source):
os.symlink (source, dest)
elif isabs (dest):
os.symlink (abspath (source), dest)
else:
os.symlink (relpath (source, dirname (dest)), dest) | def rellink (source, dest) | Create a symbolic link to path *source* from path *dest*. If either
*source* or *dest* is an absolute path, the link from *dest* will point to
the absolute path of *source*. Otherwise, the link to *source* from *dest*
will be a relative link. | 2.750879 | 2.726352 | 1.008996 |
if parents:
from os.path import dirname
parent = dirname (path)
if len (parent) and parent != path:
ensure_dir (parent, True)
try:
os.mkdir (path)
except OSError as e:
if e.errno == 17: # EEXIST
return True
raise
return False | def ensure_dir (path, parents=False) | Returns a boolean indicating whether the directory already existed. Will
attempt to create parent directories if *parents* is True. | 2.742201 | 2.78412 | 0.984944 |
try:
os.symlink (src, dst)
except OSError as e:
if e.errno == 17: # EEXIST
return True
raise
return False | def ensure_symlink (src, dst) | Ensure the existence of a symbolic link pointing to src named dst. Returns
a boolean indicating whether the symlink already existed. | 2.681084 | 2.457268 | 1.091084 |
from os import path
from glob import glob
text = text_type (self)
if user:
text = path.expanduser (text)
if vars:
text = path.expandvars (text)
if glob:
results = glob (text)
if len (results) == 1:
... | def expand (self, user=False, vars=False, glob=False, resolve=False) | Return a new :class:`Path` with various expansions performed. All
expansions are disabled by default but can be enabled by passing in
true values in the keyword arguments.
user : bool (default False)
Expand ``~`` and ``~user`` home-directory constructs. If a username is
unmatched or ``$HOME`` is unset, no cha... | 3.069854 | 3.261378 | 0.941275 |
return self.__class__ (str (self).format (*args, **kwargs)) | def format (self, *args, **kwargs) | Return a new path formed by calling :meth:`str.format` on the
textualization of this path. | 7.295123 | 5.345829 | 1.364638 |
if mode == 'textual':
return self.parent
if mode == 'resolved':
return self.resolve ().parent
if mode == 'naive':
from os.path import pardir
if not len (self.parts):
return self.__class__ (pardir)
if all (p =... | def get_parent (self, mode='naive') | Get the path of this path’s parent directory.
Unlike the :attr:`parent` attribute, this function can correctly
ascend into parent directories if *self* is ``"."`` or a sequence of
``".."``. The precise way in which it handles these kinds of paths,
however, depends on the *mode* paramete... | 4.612673 | 3.558486 | 1.296246 |
if self.is_absolute ():
return self
from os.path import relpath
other = self.__class__ (other)
return self.__class__ (relpath (text_type (self), text_type (other))) | def make_relative (self, other) | Return a new path that is the equivalent of this one relative to the path
*other*. Unlike :meth:`relative_to`, this will not throw an error if *self* is
not a sub-path of *other*; instead, it will use ``..`` to build a relative
path. This can result in invalid relative paths if *other* contains ... | 4.15139 | 3.996774 | 1.038685 |
if hasattr (os, 'scandir'):
scandir = os.scandir
else:
from scandir import scandir
return scandir (path_type (self)) | def scandir (self) | Iteratively scan this path, assuming it’s a directory. This requires and
uses the :mod:`scandir` module.
`scandir` is different than `iterdir` because it generates `DirEntry`
items rather than Path instances. DirEntry objects have their
properties filled from the directory info itself, ... | 3.986732 | 5.402451 | 0.737949 |
# shutil.copyfile() doesn't let the destination be a directory, so we
# have to manage that possibility ourselves.
import shutil
dest = Path (dest)
if dest.is_dir ():
dest = dest / self.name
if preserve == 'none':
shutil.copyfile (str(s... | def copy_to (self, dest, preserve='mode') | Copy this path — as a file — to another *dest*.
The *preserve* argument specifies which meta-properties of the file
should be preserved:
``none``
Only copy the file data.
``mode``
Copy the data and the file mode (permissions, etc).
``all``
Preserve... | 3.101571 | 2.983605 | 1.039538 |
if parents:
p = self.parent
if p == self:
return False # can never create root; avoids loop when parents=True
p.ensure_dir (mode, True)
made_it = False
try:
self.mkdir (mode)
made_it = True
except OSEr... | def ensure_dir (self, mode=0o777, parents=False) | Ensure that this path exists as a directory.
This function calls :meth:`mkdir` on this path, but does not raise an
exception if it already exists. It does raise an exception if this
path exists but is not a directory. If the directory is created,
*mode* is used to set the permissions of... | 4.455729 | 4.704087 | 0.947204 |
return self.parent.ensure_dir (mode, parents) | def ensure_parent (self, mode=0o777, parents=False) | Ensure that this path's *parent* directory exists.
Returns a boolean whether the parent directory was created. Will
attempt to create superior parent directories if *parents* is true. | 10.320161 | 12.310499 | 0.838322 |
if want not in ('handle', 'path'):
raise ValueError ('unrecognized make_tempfile() "want" mode %r' % (want,))
if resolution not in ('unlink', 'try_unlink', 'keep', 'overwrite'):
raise ValueError ('unrecognized make_tempfile() "resolution" mode %r' % (resolution,))
... | def make_tempfile (self, want='handle', resolution='try_unlink', suffix='', **kwargs) | Get a context manager that creates and cleans up a uniquely-named temporary
file with a name similar to this path.
This function returns a context manager that creates a secure
temporary file with a path similar to *self*. In particular, if
``str(self)`` is something like ``foo/bar``, t... | 3.560311 | 3.166721 | 1.124289 |
target = self.__class__ (target)
if force:
self.try_unlink ()
if self.is_absolute ():
target = target.absolute () # force absolute link
return self.symlink_to (target.make_relative (self.parent)) | def rellink_to (self, target, force=False) | Make this path a symlink pointing to the given *target*, generating the
proper relative path using :meth:`make_relative`. This gives different
behavior than :meth:`symlink_to`. For instance, ``Path
('a/b').symlink_to ('c')`` results in ``a/b`` pointing to the path
``c``, whereas :meth:`rellink_to` results in it poi... | 6.803318 | 5.627076 | 1.209033 |
import shutil
if errors == 'ignore':
ignore_errors = True
onerror = None
elif errors == 'warn':
ignore_errors = False
from .cli import warn
def onerror (func, path, exc_info):
warn ('couldn\'t rmtree %s: in %s... | def rmtree (self, errors='warn') | Recursively delete this directory and its contents. The *errors* keyword
specifies how errors are handled:
"warn" (the default)
Print a warning to standard error.
"ignore"
Ignore errors. | 3.936335 | 4.67157 | 0.842615 |
try:
self.unlink ()
return True
except OSError as e:
if e.errno == 2:
return False # ENOENT
raise | def try_unlink (self) | Try to unlink this path. If it doesn't exist, no error is returned. Returns
a boolean indicating whether the path was really unlinked. | 3.830561 | 3.550326 | 1.078932 |
try:
return self.open (**kwargs)
except IOError as e:
if e.errno == 2:
if null_if_noexist:
import io, os
return io.open (os.devnull, **kwargs)
return None
raise | def try_open (self, null_if_noexist=False, **kwargs) | Call :meth:`Path.open` on this path (passing *kwargs*) and return the
result. If the file doesn't exist, the behavior depends on
*null_if_noexist*. If it is false (the default), ``None`` is returned.
Otherwise, :data:`os.devnull` is opened and returned. | 2.815623 | 2.914641 | 0.966027 |
from pandas import HDFStore
return HDFStore (text_type (self), mode=mode, **kwargs) | def as_hdf_store (self, mode='r', **kwargs) | Return the path as an opened :class:`pandas.HDFStore` object. Note that the
:class:`HDFStore` constructor unconditionally prints messages to
standard output when opening and closing files, so use of this
function will pollute your program’s standard output. The *kwargs* are
forwarded to ... | 7.164693 | 8.017852 | 0.893593 |
from astropy.io import ascii
return ascii.read (text_type (self), **kwargs) | def read_astropy_ascii (self, **kwargs) | Open as an ASCII table, returning a :class:`astropy.table.Table` object.
Keyword arguments are passed to :func:`astropy.io.ascii.open`; valid
ones likely include:
- ``names = <list>`` (column names)
- ``format`` ('basic', 'cds', 'csv', 'ipac', ...)
- ``guess = True`` (guess tabl... | 5.491808 | 10.209166 | 0.537929 |
from astropy.io import fits
return fits.open (text_type (self), **kwargs) | def read_fits (self, **kwargs) | Open as a FITS file, returning a :class:`astropy.io.fits.HDUList` object.
Keyword arguments are passed to :func:`astropy.io.fits.open`; valid
ones likely include:
- ``mode = 'readonly'`` (or "update", "append", "denywrite", "ostream")
- ``memmap = None``
- ``save_backup = False`... | 7.30499 | 10.914328 | 0.669303 |
from astropy.io import fits
from .numutil import fits_recarray_to_data_frame as frtdf
with fits.open (text_type (self), mode='readonly', **kwargs) as hdulist:
return frtdf (hdulist[hdu].data, drop_nonscalar_ok=drop_nonscalar_ok) | def read_fits_bintable (self, hdu=1, drop_nonscalar_ok=True, **kwargs) | Open as a FITS file, read in a binary table, and return it as a
:class:`pandas.DataFrame`, converted with
:func:`pkwit.numutil.fits_recarray_to_data_frame`. The *hdu* argument
specifies which HDU to read, with its default 1 indicating the first
FITS extension. The *drop_nonscalar_ok* arg... | 4.146242 | 3.090585 | 1.341572 |
# This one needs special handling because of the "key" and path input.
import pandas
return pandas.read_hdf (text_type (self), key, **kwargs) | def read_hdf (self, key, **kwargs) | Open as an HDF5 file using :mod:`pandas` and return the item stored under
the key *key*. *kwargs* are passed to :func:`pandas.read_hdf`. | 16.220352 | 15.002247 | 1.081195 |
if typed:
from .tinifile import read_stream
else:
from .inifile import read_stream
try:
with self.open ('rb') as f:
for item in read_stream (f):
yield item
except IOError as e:
if e.errno != 2 o... | def read_inifile (self, noexistok=False, typed=False) | Open assuming an “ini-file” format and return a generator yielding data
records using either :func:`pwkit.inifile.read_stream` (if *typed* is
false) or :func:`pwkit.tinifile.read_stream` (if it’s true). The
latter version is designed to work with numerical data using the
:mod:`pwkit.msmt... | 4.001721 | 2.642349 | 1.514456 |
import json
with self.open (mode=mode) as f:
return json.load (f, **kwargs) | def read_json (self, mode='rt', **kwargs) | Use the :mod:`json` module to read in this file as a JSON-formatted data
structure. Keyword arguments are passed to :func:`json.load`. Returns the
read-in data structure. | 4.224514 | 4.094632 | 1.03172 |
try:
with self.open (mode=mode, **kwargs) as f:
for line in f:
yield line
except IOError as e:
if e.errno != 2 or not noexistok:
raise | def read_lines (self, mode='rt', noexistok=False, **kwargs) | Generate a sequence of lines from the file pointed to by this path, by
opening as a regular file and iterating over it. The lines therefore
contain their newline characters. If *noexistok*, a nonexistent file
will result in an empty sequence rather than an exception. *kwargs*
are passed ... | 2.494642 | 2.283222 | 1.092597 |
import numpy as np
with self.open ('rb') as f:
return np.load (f, **kwargs) | def read_numpy (self, **kwargs) | Read this path into a :class:`numpy.ndarray` using :func:`numpy.load`.
*kwargs* are passed to :func:`numpy.load`; they likely are:
mmap_mode : None, 'r+', 'r', 'w+', 'c'
Load the array using memory-mapping
allow_pickle : bool = True
Whether Pickle-format data are allowed; potential securi... | 4.401948 | 5.960371 | 0.738536 |
import numpy as np
if dfcols is not None:
kwargs['unpack'] = True
retval = np.loadtxt (text_type (self), **kwargs)
if dfcols is not None:
import pandas as pd
if isinstance (dfcols, six.string_types):
dfcols = dfcols.split ()... | def read_numpy_text (self, dfcols=None, **kwargs) | Read this path into a :class:`numpy.ndarray` as a text file using
:func:`numpy.loadtxt`. In normal conditions the returned array is
two-dimensional, with the first axis spanning the rows in the file and
the second axis columns (but see the *unpack* and *dfcols* keywords).
If *dfcols* is... | 3.440266 | 3.74815 | 0.917857 |
import pandas
reader = getattr (pandas, 'read_' + format, None)
if not callable (reader):
raise PKError ('unrecognized Pandas format %r: no function pandas.read_%s',
format, format)
with self.open ('rb') as f:
return reader (f... | def read_pandas (self, format='table', **kwargs) | Read using :mod:`pandas`. The function ``pandas.read_FORMAT`` is called
where ``FORMAT`` is set from the argument *format*. *kwargs* are
passed to this function. Supported formats likely include
``clipboard``, ``csv``, ``excel``, ``fwf``, ``gbq``, ``html``,
``json``, ``msgpack``, ``pickl... | 5.192407 | 5.255872 | 0.987925 |
gen = self.read_pickles ()
value = gen.next ()
gen.close ()
return value | def read_pickle (self) | Open the file, unpickle one object from it using :mod:`pickle`, and return
it. | 7.851038 | 7.454253 | 1.053229 |
try:
import cPickle as pickle
except ImportError:
import pickle
with self.open (mode='rb') as f:
while True:
try:
obj = pickle.load (f)
except EOFError:
break
yie... | def read_pickles (self) | Generate a sequence of objects by opening the path and unpickling items
until EOF is reached. | 2.743119 | 2.376533 | 1.154253 |
with self.open (mode='rt', encoding=encoding, errors=errors, newline=newline) as f:
return f.read() | def read_text(self, encoding=None, errors=None, newline=None) | Read this path as one large chunk of text.
This function reads in the entire file as one big piece of text and
returns it. The *encoding*, *errors*, and *newline* keywords are
passed to :meth:`open`.
This is not a good way to read files unless you know for sure that they
are sm... | 3.101168 | 4.155713 | 0.746242 |
import pytoml
with self.open (mode='rt', encoding=encoding, errors=errors, newline=newline) as f:
return pytoml.load (f, **kwargs) | def read_toml(self, encoding=None, errors=None, newline=None, **kwargs) | Read this path as a TOML document.
The `TOML <https://github.com/toml-lang/toml>`_ parsing is done with
the :mod:`pytoml` module. The *encoding*, *errors*, and *newline*
keywords are passed to :meth:`open`. The remaining *kwargs* are passed
to :meth:`toml.load`.
Returns the dec... | 3.579534 | 4.77708 | 0.749314 |
import yaml
with self.open (mode='rt', encoding=encoding, errors=errors, newline=newline) as f:
return yaml.load (f, **kwargs) | def read_yaml (self, encoding=None, errors=None, newline=None, **kwargs) | Read this path as a YAML document.
The YAML parsing is done with the :mod:`yaml` module. The *encoding*,
*errors*, and *newline* keywords are passed to :meth:`open`. The
remaining *kwargs* are passed to :meth:`yaml.load`.
Returns the decoded data structure. | 2.97677 | 4.116288 | 0.723169 |
try:
import cPickle as pickle
except ImportError:
import pickle
with self.open (mode='wb') as f:
for obj in objs:
pickle.dump (obj, f) | def write_pickles (self, objs) | *objs* must be iterable. Write each of its values to this path in sequence
using :mod:`cPickle`. | 3.113443 | 2.633498 | 1.182246 |
import yaml
with self.open (mode='wt', encoding=encoding, errors=errors, newline=newline) as f:
return yaml.dump (data, stream=f, **kwargs) | def write_yaml (self, data, encoding=None, errors=None, newline=None, **kwargs) | Read *data* to this path as a YAML document.
The *encoding*, *errors*, and *newline* keywords are passed to
:meth:`open`. The remaining *kwargs* are passed to :meth:`yaml.dump`. | 3.020133 | 3.448044 | 0.875897 |
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 contain attribute %s' %... | def enumeration (cls) | 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... | 3.039512 | 3.00085 | 1.012884 |
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:
raise ValueError ('input must have only scalar columns')
... | def fits_recarray_to_data_frame (recarray, drop_nonscalar_ok=True) | 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... | 4.21558 | 4.116651 | 1.024032 |
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 ())
data = np.array (column)
i... | def data_frame_to_astropy_table (dataframe) | 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`. | 4.185092 | 4.289254 | 0.975716 |
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 'utf8') (pager.stdin)
df.to_string (enc, **kwargs)
... | def page_data_frame (df, pager_argv=['less'], **kwargs) | 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
... | 2.827036 | 2.787298 | 1.014257 |
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 ('values must be in nondecreasing order')
... | def slice_around_gaps (values, maxgap) | 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. | 3.808832 | 3.743688 | 1.017401 |
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 = gapslice.indices (l)
num_elements = stop - start
... | def slice_evenly_with_gaps (values, target_len, maxgap) | 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... | 3.468152 | 3.529324 | 0.982668 |
subds = [df.iloc[idx] for idx in chunk_slicers]
subds = [sd for sd in subds if sd.shape[0] >= min_points_per_chunk]
chunked = df.__class__ ({nchunk_colname: np.zeros (len (subds), dtype=np.int)})
# Some future-proofing: allow possibility of different ways of mapping
# from a column giving a v... | def reduce_data_frame (df, chunk_slicers,
avg_cols=(),
uavg_cols=(),
minmax_cols=(),
nchunk_colname='nchunk',
uncert_prefix='u',
min_points_per_chunk=3) | Reduce" a DataFrame by collapsing rows in grouped chunks. Returns another
DataFrame with similar columns but fewer rows.
Arguments:
df
The input :class:`pandas.DataFrame`.
chunk_slicers
An iterable that returns values that are used to slice *df* with its
:meth:`pandas.DataFrame.iloc`... | 2.745761 | 2.741887 | 1.001413 |
return reduce_data_frame (df,
slice_evenly_with_gaps (df[valcol], target_len, maxgap),
**kwargs) | 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`. | 3.673032 | 5.277505 | 0.695979 |
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 keyword argument '%s'"
... | def usmooth (window, uncerts, *data, **kwargs) | 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... | 4.648641 | 4.518886 | 1.028714 |
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:
if col == ucol:
res[col] = n... | def dfsmooth (window, df, ucol, k=None) | 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 ... | 4.70789 | 4.694938 | 1.002759 |
from scipy.optimize import newton
from .parallel import make_parallel_helper
phelp = make_parallel_helper (parallel)
if not isinstance (par_args, tuple):
raise ValueError ('par_args must be a tuple')
if not isinstance (simple_args, tuple):
raise ValueError ('simple_args must ... | def parallel_newton (func, x0, fprime=None, par_args=(), simple_args=(), tol=1.48e-8,
maxiter=50, parallel=True, **kwargs) | A parallelized version of :func:`scipy.optimize.newton`.
Arguments:
func
The function to search for zeros, called as ``f(x, [*par_args...], [*simple_args...])``.
x0
The initial point for the zero search.
fprime
(Optional) The first derivative of *func*, called the same way.
par_a... | 2.932982 | 2.790702 | 1.050984 |
from scipy.integrate import quad
from .parallel import make_parallel_helper
phelp = make_parallel_helper (parallel)
if not isinstance (par_args, tuple):
raise ValueError ('par_args must be a tuple')
if not isinstance (simple_args, tuple):
raise ValueError ('simple_args must b... | def parallel_quad (func, a, b, par_args=(), simple_args=(), parallel=True, **kwargs) | A parallelized version of :func:`scipy.integrate.quad`.
Arguments are:
func
The function to integrate, called as ``f(x, [*par_args...], [*simple_args...])``.
a
The lower limit(s) of integration.
b
The upper limits(s) of integration.
par_args
Tuple of additional parallelized... | 2.785048 | 2.716882 | 1.02509 |
return weighted_mean (df[df.columns[0]], df[df.columns[1]], **kwargs) | def weighted_mean_df (df, **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)``. | 3.802036 | 3.940977 | 0.964744 |
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) | def weighted_variance (x, weights) | 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)``. | 3.505872 | 3.275908 | 1.070198 |
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 | def unit_tophat_ee (x) | Tophat function on the unit interval, left-exclusive and right-exclusive.
Returns 1 if 0 < x < 1, 0 otherwise. | 3.30894 | 2.866599 | 1.154309 |
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.asarray (x)
x1 = np.atleast_1d... | def make_tophat_ee (lower, upper) | Return a ufunc-like tophat function on the defined range, left-exclusive
and right-exclusive. Returns 1 if lower < x < upper, 0 otherwise. | 2.683529 | 2.27724 | 1.178413 |
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.asarray (x)
x1 = np.atleast_1d... | def make_tophat_ei (lower, upper) | Return a ufunc-like tophat function on the defined range, left-exclusive
and right-inclusive. Returns 1 if lower < x <= upper, 0 otherwise. | 2.675676 | 2.286618 | 1.170146 |
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.asarray (x)
x1 = np.atleast_1d... | def make_tophat_ie (lower, upper) | Return a ufunc-like tophat function on the defined range, left-inclusive
and right-exclusive. Returns 1 if lower <= x < upper, 0 otherwise. | 2.614918 | 2.281048 | 1.146367 |
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.asarray (x)
x1 = np.atleast_1d... | def make_tophat_ii (lower, upper) | Return a ufunc-like tophat function on the defined range, left-inclusive
and right-inclusive. Returns 1 if lower < x < upper, 0 otherwise. | 2.637999 | 2.345657 | 1.124631 |
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 == 0:
return np.asscalar... | def make_step_lcont (transition) | Return a ufunc-like step function that is left-continuous. Returns 1 if
x > transition, 0 otherwise. | 3.464222 | 2.781773 | 1.245329 |
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 == 0:
return np.asscala... | def make_step_rcont (transition) | Return a ufunc-like step function that is right-continuous. Returns 1 if
x >= transition, 0 otherwise. | 3.575964 | 2.749276 | 1.300693 |
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 = norm
sub_models.append(component)
if total_model is None... | def make_fixed_temp_multi_apec(kTs, name_template='apec%d', norm=None) | 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... | 3.092841 | 2.530288 | 1.222328 |
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]
expanded[i,f:f+n] = rmf.mat... | def expand_rmf_matrix(rmf) | 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... | 2.796714 | 2.889909 | 0.967752 |
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,
header = None,
)
return ARF1D(dar... | def derive_identity_arf(name, arf) | 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... | 5.157491 | 5.050156 | 1.021254 |
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)) | def get_source_qq_data(id=None) | 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... | 7.471965 | 4.104873 | 1.820267 |
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)) | def get_bkg_qq_data(id=None, bkg_id=None) | 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... | 3.805822 | 3.104695 | 1.225828 |
import omega as om
kev = np.asarray(kev)
obs = np.asarray(obs)
mdl = np.asarray(mdl)
c_obs = np.cumsum(obs)
c_mdl = np.cumsum(mdl)
mx = max(c_obs[-1], c_mdl[-1])
p = om.RectPlot()
p.addXY([0, mx], [0, mx], '1:1')
p.addXY(c_mdl, c_obs, key_text)
# HACK: this range of ... | def make_qq_plot(kev, obs, mdl, unit, key_text) | Make a quantile-quantile plot comparing events and a model.
*kev*
A 1D, sorted array of event energy bins measured in keV.
*obs*
A 1D array giving the number or rate of events in each bin.
*mdl*
A 1D array giving the modeled number or rate of events in each bin.
*unit*
Text desc... | 3.292402 | 3.124631 | 1.053693 |
import omega as om
p = om.RectPlot()
p.addXY([0, 1.], [0, 1.], '1:1')
for index, array in enumerate(arrays):
kev, obs, mdl = array
c_obs = np.cumsum(obs)
c_mdl = np.cumsum(mdl)
mx = 0.5 * (c_obs[-1] + c_mdl[-1])
c_obs /= mx
c_mdl /= mx
p.a... | def make_multi_qq_plots(arrays, key_text) | Make a quantile-quantile plot comparing multiple sets of events and models.
*arrays*
X.
*key_text*
Text describing the quantile-quantile comparison quantity; will be
shown on the plot legend.
Returns:
An :class:`omega.RectPlot` instance.
*TODO*: nothing about this is Sherpa-spe... | 3.860969 | 3.70759 | 1.041369 |
import omega as om
model_x = np.concatenate((model_plot.xlo, [model_plot.xhi[-1]]))
model_x[0] = max(model_x[0], xmin_clamp)
model_y = np.concatenate((model_plot.y, [0.]))
# Sigh, sometimes Sherpa gives us bad values.
is_bad = ~np.isfinite(model_y)
if is_bad.sum():
from .cli i... | def make_spectrum_plot(model_plot, data_plot, desc, xmin_clamp=0.01,
min_valid_x=None, max_valid_x=None) | Make a plot of a spectral model and data.
*model_plot*
A model plot object returned by Sherpa from a call like `ui.get_model_plot()`
or `ui.get_bkg_model_plot()`.
*data_plot*
A data plot object returned by Sherpa from a call like `ui.get_source_plot()`
or `ui.get_bkg_plot()`.
*desc*... | 3.24246 | 3.045639 | 1.064624 |
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:', local_filename, url)
return False
# w... | def download_file(local_filename, url, clobber=False) | Download the given file. Clobber overwrites file if exists. | 2.425623 | 2.401602 | 1.010002 |
with open(local_filename, 'w') as json_file:
json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': '))) | def download_json(local_filename, url, clobber=False) | Download the given JSON file, and pretty-print before we output it. | 2.004331 | 1.918758 | 1.044598 |
# This could be more efficient, but whatever. This lets us share code with
# the ndshow module.
clipper = Clipper ()
clipper.alloc_buffer (data)
clipper.set_tile_size ()
clipper.dmin = cmin if cmin is not None else data.min ()
clipper.dmax = cmax if cmax is not None else data.max ()
... | def data_to_argb32 (data, cmin=None, cmax=None, stretch='linear', cmap='black_to_blue') | Turn arbitrary data values into ARGB32 colors.
There are three steps to this process: clipping the data values to a
maximum and minimum; stretching the spacing between those values; and
converting their amplitudes into colors with some kind of color map.
`data` - Input data; can (and should) be a M... | 3.374933 | 3.157413 | 1.068892 |
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
stride = cairo.ImageSurface.format_stride_for_wi... | def data_to_imagesurface (data, **kwargs) | 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... | 2.915306 | 2.764492 | 1.054554 |
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"
"{} file doesn't exist.\n{} environmen... | def get_token(filename=TOKEN_PATH, envvar=TOKEN_ENVVAR) | Returns pipeline_token for API
Tries local file first, then env variable | 3.159491 | 2.552388 | 1.237857 |
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] += 1
nbyant[i2] +=... | def stats (self, antnames) | XXX may be out of date. | 2.380331 | 2.323385 | 1.02451 |
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:
section.set_o... | def read_stream (stream) | Python 3 compat note: we're assuming `stream` gives bytes not unicode. | 2.242888 | 2.20844 | 1.015599 |
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)
print ('[%s]' % s, file=stream)
for k in sort... | def write_stream (stream, holders, defaultsection=None) | 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... | 3.178289 | 3.219474 | 0.987208 |
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) | def write (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... | 2.089062 | 2.944651 | 0.709443 |
chunk = None
key = None
data = None
misclines = []
for fullline in instream:
line = fullline.split ('#', 1)[0]
m = sectionre.match (line)
if m is not None:
# New chunk
if chunk is not None:
if key is not None:
... | def mutate_stream (instream, outstream) | Python 3 compat note: we're assuming `stream` gives bytes not unicode. | 2.31776 | 2.295007 | 1.009914 |
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.selectcal (**selectcals)
cp.plotoptions (**plotoptions)
cp.plot (xaxis, yaxis)
if show_gui:
import py... | def in_casapy (helper, caltable=None, selectcals={}, plotoptions={},
xaxis=None, yaxis=None, figfile=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.001917 | 4.900254 | 1.020746 |
n, m = a.shape
# Compute the packed Q and R matrix information.
packed, pmut, rdiag, acnorm = \
_manual_qr_factor_packed(a, dtype)
# Now we unpack. Start with the R matrix, which is easy: we just
# have to piece it together from the strict lower triangle of 'a'
# and the diagona... | def _qr_factor_full(a, dtype=np.float) | Compute the QR factorization of a matrix, with pivoting.
Parameters:
a - An n-by-m arraylike, m >= n.
dtype - (optional) The data type to use for computations.
Default is np.float.
Returns:
q - An m-by-m orthogonal matrix (q q^T = ident)
r - An n-by-m upper triangular matrix
pmut - An n-element perm... | 5.417876 | 4.924774 | 1.100127 |
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_full(a)
bqt = np.dot(b, q.T)
x, s = _manu... | def _qrd_solve_full(a, b, ddiag, dtype=np.float) | 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... | 3.851754 | 3.456886 | 1.114226 |
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, )
q, r, pmut = _qr_factor_full(a)
bqt = np.dot(b, q.T)
par, x = _lm_solve(r, pmut, ddiag, bqt, delta, par0,
... | def _lm_solve_full(a, b, ddiag, delta, par0, dtype=np.float) | Compute the Levenberg-Marquardt parameter and solution vector.
Parameters:
a - n-by-m matrix, m >= n (only the n-by-n component is used)
b - n-by-n matrix
ddiag - n-vector, diagonal elements of D
delta - positive scalar, specifies scale of enorm(Dx)
par0 - positive scalar, initial estimate of the LM parameter... | 4.214601 | 3.372724 | 1.249613 |
# This routine could save an allocation by operating on r in-place,
# which might be worthwhile for large n, and is what the original
# Fortran does.
n = r.shape[1]
assert r.shape[0] >= n
r = r.copy()
# Form the inverse of R in the full lower triangle of R.
jrank = -1
abstol ... | def _calc_covariance(r, pmut, tol=1e-14) | Calculate the covariance matrix of the fitted parameters
Parameters:
r - n-by-n matrix, the full upper triangle of R
pmut - n-vector, defines the permutation of R
tol - scalar, relative column scale for determining rank
deficiency. Default 1e-14.
Returns:
cov - n-by-n matrix, the covariance matrix C
Give... | 3.094523 | 2.995209 | 1.033158 |
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)
for i in range(n):
jac[i,i] += 1
guess = np.one... | def _lmder1_linear_full_rank(n, m, factor, target_fnorm1, target_fnorm2) | A full-rank linear function (lmder test #1) | 5.120584 | 5.012173 | 1.02163 |
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):
jac.fill(0)
for i in range(1, n - 1):
for j in range(1, m - 1):
... | def _lmder1_linear_r1zcr(n, m, factor, target_fnorm1, target_fnorm2, target_params) | A rank-1 linear function with zero columns and rows (lmder test #3) | 3.200814 | 3.227188 | 0.991828 |
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.491934955050e+01, 0.13400630... | def _lmder1_rosenbrock() | Rosenbrock function (lmder test #4) | 4.236321 | 4.226707 | 1.002275 |
tpi = 2 * np.pi
def func(params, vec):
if params[0] == 0:
tmp1 = np.copysign(0.25, params[1])
elif params[0] > 0:
tmp1 = np.arctan(params[1] / params[0]) / tpi
else:
tmp1 = np.arctan(params[1] / params[0]) / tpi + 0.5
tmp2 = np.sqrt(para... | def _lmder1_helical_valley() | Helical valley function (lmder test #5) | 2.496571 | 2.490801 | 1.002317 |
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)
jac[0,0] = 1
jac[0,3... | def _lmder1_powell_singular() | 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. | 2.121236 | 2.119474 | 1.000831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.