signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def get_ops(self, ops):
|
time = <NUM_LIT:0.><EOL>for op, count in ops.items():<EOL><INDENT>time += self.get(op) * count<EOL><DEDENT>return time<EOL>
|
Return timings for dictionary ops holding the operation names as
keys and the number of applications as values.
|
f11476:c11:m2
|
def __and__(self, other):
|
left = numpy.max([self.left, other.left])<EOL>right = numpy.min([self.right, other.right])<EOL>if left <= right:<EOL><INDENT>return Interval(left, right)<EOL><DEDENT>return None<EOL>
|
Return intersection interval or None
|
f11476:c22:m1
|
def __or__(self, other):
|
if self & other:<EOL><INDENT>left = numpy.min([self.left, other.left])<EOL>right = numpy.max([self.right, other.right])<EOL>return Interval(left, right)<EOL><DEDENT>return None<EOL>
|
Return union of intervals if they intersect or None.
|
f11476:c22:m2
|
def contains(self, alpha):
|
return self.left <= alpha and alpha <= self.right<EOL>
|
Returns True if alpha is an element of the interval.
|
f11476:c22:m4
|
def distance(self, other):
|
if self & other:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return numpy.max([other.left-self.right, self.left-other.right])<EOL>
|
Returns the distance to other (0 if intersection is nonempty).
|
f11476:c22:m5
|
def min_pos(self):
|
if self.__len__() == <NUM_LIT:0>:<EOL><INDENT>return ArgumentError('<STR_LIT>')<EOL><DEDENT>if self.contains(<NUM_LIT:0>):<EOL><INDENT>return None<EOL><DEDENT>positive = [interval for interval in self.intervals<EOL>if interval.left > <NUM_LIT:0>]<EOL>if len(positive) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return numpy.min(list(map(lambda i: i.left, positive)))<EOL>
|
Returns minimal positive value or None.
|
f11476:c23:m9
|
def max_neg(self):
|
if self.__len__() == <NUM_LIT:0>:<EOL><INDENT>return ArgumentError('<STR_LIT>')<EOL><DEDENT>if self.contains(<NUM_LIT:0>):<EOL><INDENT>return None<EOL><DEDENT>negative = [interval for interval in self.intervals<EOL>if interval.right < <NUM_LIT:0>]<EOL>if len(negative) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return numpy.max(list(map(lambda i: i.right, negative)))<EOL>
|
Returns maximum negative value or None.
|
f11476:c23:m10
|
def min_abs(self):
|
if self.__len__() == <NUM_LIT:0>:<EOL><INDENT>return ArgumentError('<STR_LIT>')<EOL><DEDENT>if self.contains(<NUM_LIT:0>):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return numpy.min([numpy.abs(val)<EOL>for val in [self.max_neg(), self.min_pos()]<EOL>if val is not None])<EOL>
|
Returns minimum absolute value.
|
f11476:c23:m11
|
def max_abs(self):
|
if self.__len__() == <NUM_LIT:0>:<EOL><INDENT>return ArgumentError('<STR_LIT>')<EOL><DEDENT>return numpy.max(numpy.abs([self.max(), self.min()]))<EOL>
|
Returns maximum absolute value.
|
f11476:c23:m12
|
def __init__(self, evals, exclude_zeros=False):
|
if isinstance(evals, Intervals):<EOL><INDENT>evals = [evals.min(), evals.max()]<EOL>if evals[<NUM_LIT:0>] <= <NUM_LIT:0>:<EOL><INDENT>raise AssumptionError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if len(evals) == <NUM_LIT:0>:<EOL><INDENT>raise AssumptionError('<STR_LIT>')<EOL><DEDENT>if not numpy.isreal(evals).all():<EOL><INDENT>raise AssumptionError('<STR_LIT>')<EOL><DEDENT>evals = numpy.sort(numpy.array(evals, dtype=numpy.float))<EOL>evals /= evals[-<NUM_LIT:1>]<EOL>if exclude_zeros is False and not (evals > <NUM_LIT>).all():<EOL><INDENT>raise AssumptionError(<EOL>'<STR_LIT>')<EOL><DEDENT>assert(evals[<NUM_LIT:0>] > -<NUM_LIT>)<EOL>kappa = <NUM_LIT:1>/numpy.min(evals[evals > <NUM_LIT>])<EOL>self.base = (numpy.sqrt(kappa)-<NUM_LIT:1>) / (numpy.sqrt(kappa)+<NUM_LIT:1>)<EOL>
|
Initialize with array/list of eigenvalues or Intervals object.
|
f11476:c24:m0
|
def eval_step(self, step):
|
return <NUM_LIT:2> * self.base**step<EOL>
|
Evaluate bound for given step.
|
f11476:c24:m1
|
def get_step(self, tol):
|
return numpy.log(tol/<NUM_LIT>)/numpy.log(self.base)<EOL>
|
Return step at which bound falls below tolerance.
|
f11476:c24:m2
|
def __new__(cls, evals):
|
pos = False<EOL>if isinstance(evals, Intervals):<EOL><INDENT>if evals.min() > <NUM_LIT:0>:<EOL><INDENT>pos = True<EOL><DEDENT><DEDENT>elif (numpy.array(evals) > -<NUM_LIT>).all():<EOL><INDENT>pos = True<EOL><DEDENT>if pos:<EOL><INDENT>return BoundCG(evals)<EOL><DEDENT>return super(BoundMinres, cls).__new__(cls)<EOL>
|
Use BoundCG if all eigenvalues are non-negative.
|
f11476:c25:m0
|
def __init__(self, evals):
|
if isinstance(evals, Intervals):<EOL><INDENT>if evals.contains(<NUM_LIT:0>):<EOL><INDENT>raise AssumptionError(<EOL>'<STR_LIT>')<EOL><DEDENT>evals = [val for val in [evals.min(), evals.max_neg(),<EOL>evals.min_pos(), evals.max()]<EOL>if val is not None]<EOL><DEDENT>if len(evals) == <NUM_LIT:0>:<EOL><INDENT>raise AssumptionError('<STR_LIT>')<EOL><DEDENT>if not numpy.isreal(evals).all():<EOL><INDENT>raise AssumptionError('<STR_LIT>')<EOL><DEDENT>evals = numpy.sort(numpy.array(evals, dtype=numpy.float))<EOL>evals /= numpy.max(numpy.abs(evals))<EOL>negative = evals < -<NUM_LIT><EOL>positive = evals > <NUM_LIT><EOL>lambda_1 = numpy.min(evals[negative])<EOL>lambda_s = numpy.max(evals[negative])<EOL>lambda_t = numpy.min(evals[positive])<EOL>lambda_N = numpy.max(evals[positive])<EOL>a = numpy.sqrt(numpy.abs(lambda_1*lambda_N))<EOL>b = numpy.sqrt(numpy.abs(lambda_s*lambda_t))<EOL>self.base = (a-b) / (a+b)<EOL>
|
Initialize with array/list of eigenvalues or Intervals object.
|
f11476:c25:m1
|
def eval_step(self, step):
|
return <NUM_LIT:2> * self.base**numpy.floor(step/<NUM_LIT>)<EOL>
|
Evaluate bound for given step.
|
f11476:c25:m2
|
def get_step(self, tol):
|
return <NUM_LIT:2> * numpy.log(tol/<NUM_LIT>)/numpy.log(self.base)<EOL>
|
Return step at which bound falls below tolerance.
|
f11476:c25:m3
|
def __init__(self, roots):
|
<EOL>roots = numpy.asarray(roots)<EOL>if len(roots.shape) != <NUM_LIT:1>:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>self.roots = roots<EOL>
|
r'''A polynomial with specified roots and p(0)=1.
Represents the polynomial
.. math::
p(\lambda) = \prod_{i=1}^n \left(1-\frac{\lambda}{\theta_i}\right).
:param roots: array with roots :math:`\theta_1,\dots,\theta_n` of the
polynomial and ``roots.shape==(n,)``.
|
f11476:c26:m0
|
def minmax_candidates(self):
|
from numpy.polynomial import Polynomial as P<EOL>p = P.fromroots(self.roots)<EOL>return p.deriv(<NUM_LIT:1>).roots()<EOL>
|
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 interval.
|
f11476:c26:m1
|
def __call__(self, points):
|
<EOL>p = numpy.asarray(points)<EOL>if len(p.shape) > <NUM_LIT:1>:<EOL><INDENT>raise ArgumentError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>n = self.roots.shape[<NUM_LIT:0>]<EOL>vals = <NUM_LIT:1> - p/self.roots.reshape(n, <NUM_LIT:1>)<EOL>for j in range(vals.shape[<NUM_LIT:1>]):<EOL><INDENT>sort_tmp = numpy.argsort(numpy.abs(vals[:, j]))<EOL>sort = numpy.zeros((n,), dtype=numpy.int)<EOL>mid = int(numpy.ceil(float(n)/<NUM_LIT:2>))<EOL>sort[::<NUM_LIT:2>] = sort_tmp[:mid]<EOL>sort[<NUM_LIT:1>::<NUM_LIT:2>] = sort_tmp[mid:][::-<NUM_LIT:1>]<EOL>vals[:, j] = vals[sort, j]<EOL><DEDENT>vals = numpy.prod(vals, axis=<NUM_LIT:0>)<EOL>if numpy.isscalar(points):<EOL><INDENT>return numpy.asscalar(vals)<EOL><DEDENT>return vals<EOL>
|
Evaluate polyonmial at given points.
:param points: a point :math:`x` or array of points
:math:`x_1,\dots,x_m` with ``points.shape==(m,)``.
:returns: :math:`p(x)` or array of shape ``(m,)`` with
:math:`p(x_1),\dots,p(x_m)`.
|
f11476:c26:m2
|
def __init__(self, DeflatedSolver,<EOL>vector_factory=None<EOL>):
|
self._DeflatedSolver = DeflatedSolver<EOL>self._vector_factory = vector_factory<EOL>self.timings = utils.Timings()<EOL>'''<STR_LIT>'''<EOL>self.last_solver = None<EOL>'''<STR_LIT>'''<EOL>
|
Initialize recycling solver base.
:param DeflatedSolver: a deflated solver from
:py:mod:`~krypy.deflation`.
:param vector_factory: (optional) An instance of a subclass of
:py:class:`krypy.recycling.factories._DeflationVectorFactory`
that constructs deflation vectors for recycling. Defaults to `None`
which means that no recycling is used.
Also the following strings are allowed as shortcuts:
* ``'RitzApproxKrylov'``: uses the approximate Krylov subspace bound
evaluator :py:class:`krypy.recycling.evaluators.RitzApproxKrylov`.
* ``'RitzAprioriCg'``: uses the CG :math:`\kappa`-bound
(:py:class:`krypy.utils.BoundCG`) as an a priori bound with
:py:class:`krypy.recycling.evaluators.RitzApriori`.
* ``'RitzAprioriMinres'``: uses the MINRES bound
(:py:class:`krypy.utils.BoundMinres`) as an a priori bound with
:py:class:`krypy.recycling.evaluators.RitzApriori`.
After a run of the provided ``DeflatedSolver`` via :py:meth:`solve`,
the resulting instance of the ``DeflatedSolver`` is available in the
attribute ``last_solver``.
|
f11477:c0:m0
|
def solve(self, linear_system,<EOL>vector_factory=None,<EOL>*args, **kwargs):
|
<EOL>if not isinstance(linear_system, linsys.TimedLinearSystem):<EOL><INDENT>linear_system = linsys.ConvertedTimedLinearSystem(linear_system)<EOL><DEDENT>with self.timings['<STR_LIT>']:<EOL><INDENT>if vector_factory is None:<EOL><INDENT>vector_factory = self._vector_factory<EOL><DEDENT>if vector_factory == '<STR_LIT>':<EOL><INDENT>vector_factory = factories.RitzFactory(<EOL>subset_evaluator=evaluators.RitzApproxKrylov()<EOL>)<EOL><DEDENT>elif vector_factory == '<STR_LIT>':<EOL><INDENT>vector_factory = factories.RitzFactory(<EOL>subset_evaluator=evaluators.RitzApriori(<EOL>Bound=utils.BoundCG<EOL>)<EOL>)<EOL><DEDENT>elif vector_factory == '<STR_LIT>':<EOL><INDENT>vector_factory = factories.RitzFactory(<EOL>subset_evaluator=evaluators.RitzApriori(<EOL>Bound=utils.BoundMinres<EOL>)<EOL>)<EOL><DEDENT>if self.last_solver is None or vector_factory is None:<EOL><INDENT>U = numpy.zeros((linear_system.N, <NUM_LIT:0>))<EOL><DEDENT>else:<EOL><INDENT>U = vector_factory.get(self.last_solver)<EOL><DEDENT><DEDENT>with self.timings['<STR_LIT>']:<EOL><INDENT>self.last_solver = self._DeflatedSolver(linear_system,<EOL>U=U,<EOL>store_arnoldi=True,<EOL>*args, **kwargs)<EOL><DEDENT>return self.last_solver<EOL>
|
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 constructor.
All remaining arguments are passed to the ``DeflatedSolver``.
:returns: instance of ``DeflatedSolver`` which was used to obtain the
approximate solution. The approximate solution is available under the
attribute ``xk``.
|
f11477:c0:m1
|
def get(self, solver):
|
raise NotImplementedError('<STR_LIT>')<EOL>
|
Get deflation vectors.
:returns: numpy.array of shape ``(N,k)``
|
f11478:c0:m0
|
def __init__(self,<EOL>subset_evaluator,<EOL>subsets_generator=None,<EOL>mode='<STR_LIT>',<EOL>print_results=None<EOL>):
|
if subsets_generator is None:<EOL><INDENT>subsets_generator = generators.RitzSmall()<EOL><DEDENT>self.subsets_generator = subsets_generator<EOL>self.subset_evaluator = subset_evaluator<EOL>self.mode = mode<EOL>self.print_results = print_results<EOL>
|
Factory of Ritz vectors for automatic recycling.
:param subset_evaluator: an instance of
:py:class:`~krypy.recycling.evaluators._RitzSubsetEvaluator` that
evaluates a proposed subset of Ritz vectors for deflation.
:param subsets_generator: (optional) an instance of
:py:class:`~krypy.recycling.generators._RitzSubsetsGenerator` that
generates lists of subsets of Ritz vectors for deflation.
:param print_results: (optional) may be one of the following:
* `None`: nothing is printed.
* `'number'`: the number of selected deflation vectors is printed.
* `'values'`: the Ritz values corresponding to the selected Ritz
vectors are printed.
* `'timings'`: the timings of all evaluated subsets of Ritz vectors
are printed.
|
f11478:c1:m0
|
def _get_best_subset(self, ritz):
|
<EOL>overall_evaluations = {}<EOL>def evaluate(_subset, _evaluations):<EOL><INDENT>try:<EOL><INDENT>_evaluations[_subset] =self.subset_evaluator.evaluate(ritz, _subset)<EOL><DEDENT>except utils.AssumptionError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>current_subset = frozenset()<EOL>evaluate(current_subset, overall_evaluations)<EOL>while True:<EOL><INDENT>remaining_subset = set(range(len(ritz.values))).difference(current_subset)<EOL>subsets = self.subsets_generator.generate(ritz, remaining_subset)<EOL>if len(subsets) == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>evaluations = {}<EOL>for subset in subsets:<EOL><INDENT>eval_subset = current_subset.union(subset)<EOL>evaluate(eval_subset, evaluations)<EOL><DEDENT>if len(evaluations) > <NUM_LIT:0>:<EOL><INDENT>current_subset = min(evaluations, key=evaluations.get)<EOL><DEDENT>else:<EOL><INDENT>resnorms = [numpy.sum(ritz.resnorms[list(subset)])<EOL>for subset in subsets]<EOL>subset = subsets[numpy.argmin(resnorms)]<EOL>current_subset = current_subset.union(subset)<EOL><DEDENT>overall_evaluations.update(evaluations)<EOL><DEDENT>if len(overall_evaluations) > <NUM_LIT:0>:<EOL><INDENT>selection = list(min(overall_evaluations,<EOL>key=overall_evaluations.get))<EOL><DEDENT>else:<EOL><INDENT>selection = []<EOL><DEDENT>if self.print_results == '<STR_LIT>':<EOL><INDENT>print('<STR_LIT>'<EOL>.format(len(selection)))<EOL><DEDENT>elif self.print_results == '<STR_LIT>':<EOL><INDENT>print('<STR_LIT>'<EOL>.format(len(selection)) + '<STR_LIT>'<EOL>+ ('<STR_LIT:U+002CU+0020>'.join([str(el) for el in ritz.values[selection]])))<EOL><DEDENT>elif self.print_results == '<STR_LIT>':<EOL><INDENT>import operator<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>for subset, time in sorted(overall_evaluations.items(),<EOL>key=operator.itemgetter(<NUM_LIT:1>)):<EOL><INDENT>print('<STR_LIT>'.format(time)<EOL>+ '<STR_LIT:U+002CU+0020>'.join([str(el)<EOL>for el in ritz.values[list(subset)]]))<EOL><DEDENT><DEDENT>elif self.print_results is None:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise utils.ArgumentError(<EOL>'<STR_LIT>'<EOL>.format(self.print_results)<EOL>+ '<STR_LIT>')<EOL><DEDENT>return selection<EOL>
|
Return candidate set with smallest goal functional.
|
f11478:c1:m2
|
def __init__(self, mode='<STR_LIT>', n_vectors=<NUM_LIT:0>, which='<STR_LIT>'):
|
self.mode = mode<EOL>self.n_vectors = n_vectors<EOL>self.which = which<EOL>
|
Selects a fixed number of Ritz or harmonic Ritz vectors
with respect to a prescribed criterion.
:param mode: See ``mode`` parameter of
:py:class:`~krypy.deflation.Ritz`.
:param n_vectors: number of vectors that are chosen. Actual number of
deflation vectors may be lower if the number of Ritz pairs is less
than ``n_vectors``.
:param which: the ``n_vectors`` Ritz vectors are chosen such that the
corresponding Ritz values are the ones with
* ``lm``: largest magnitude.
* ``sm``: smallest magnitude.
* ``lr``: largest real part.
* ``sr``: smallest real part.
* ``li``: largest imaginary part.
* ``si``: smallest imaginary part.
* ``smallest_res``: smallest Ritz residual norms.
|
f11478:c2:m0
|
def __init__(self, factories):
|
self._factories = factories<EOL>
|
Combine a list of factories.
:param factories: a list of factories derived from
:py:class:`_DeflationVectorFactory`.
|
f11478:c3:m0
|
def evaluate(self, ritz, subset):
|
raise NotImplementedError('<STR_LIT>')<EOL>
|
Returns a list of subsets with indices of Ritz vectors that are
considered for deflation.
|
f11479:c0:m0
|
def __init__(self,<EOL>Bound,<EOL>tol=None,<EOL>strategy='<STR_LIT>',<EOL>deflweight=<NUM_LIT:1.0><EOL>):
|
self.Bound = Bound<EOL>self.tol = tol<EOL>self.strategy = strategy<EOL>self.deflweight = deflweight<EOL>
|
Evaluates a choice of Ritz vectors with an a-priori bound for
self-adjoint problems.
:param Bound: the a-priori bound which is used for estimating the
convergence behavior.
:param tol: (optional) the tolerance for the stopping criterion, see
:py:class:`~krypy.linsys._KrylovSolver`. If `None` is provided
(default), then the tolerance is retrieved from
`ritz._deflated_solver.tol` in the call to :py:meth:`evaluate`.
:param strategy: (optional) the following strategies are available
* `simple`: (default) uses the Ritz values that are complementary to
the deflated ones for the evaluation of the bound.
* `intervals`: uses intervals around the Ritz values that are
considered with `simple`. The intervals incorporate possible
changes in the operators.
|
f11479:c1:m0
|
@staticmethod<EOL><INDENT>def _estimate_eval_intervals(ritz, indices, indices_remaining,<EOL>eps_min=<NUM_LIT:0>,<EOL>eps_max=<NUM_LIT:0>,<EOL>eps_res=None):<DEDENT>
|
if len(indices) == <NUM_LIT:0>:<EOL><INDENT>return utils.Intervals(<EOL>[utils.Interval(mu-resnorm, mu+resnorm)<EOL>for mu, resnorm in zip(ritz.values, ritz.resnorms)])<EOL><DEDENT>if len(ritz.values) == len(indices):<EOL><INDENT>raise utils.AssumptionError(<EOL>'<STR_LIT>')<EOL><DEDENT>if eps_res is None:<EOL><INDENT>eps_res = numpy.max(numpy.abs([eps_min, eps_max]))<EOL><DEDENT>delta_sel = numpy.linalg.norm(ritz.resnorms[indices], <NUM_LIT:2>)<EOL>delta_non_sel = numpy.linalg.norm(ritz.resnorms[indices_remaining], <NUM_LIT:2>)<EOL>delta = utils.gap(ritz.values[indices],<EOL>ritz.values[indices_remaining])<EOL>mu_ints = utils.Intervals(<EOL>[utils.Interval(mu+eps_min, mu+eps_max)<EOL>for mu in ritz.values[indices]])<EOL>mu_min = mu_ints.min_abs()<EOL>if delta_sel + eps_max - eps_min >= delta:<EOL><INDENT>raise utils.AssumptionError(<EOL>'<STR_LIT>'<EOL>+ '<STR_LIT>'.format(<EOL>delta_sel + delta_non_sel + eps_max - eps_min,<EOL>delta)<EOL>)<EOL><DEDENT>if mu_min == <NUM_LIT:0>:<EOL><INDENT>raise utils.AssumptionError('<STR_LIT>')<EOL><DEDENT>eta = (delta_sel+eps_res)**<NUM_LIT:2> * (<EOL><NUM_LIT:1>/(delta-eps_max+eps_min)<EOL>+ <NUM_LIT:1>/mu_min<EOL>)<EOL>left = eps_min - eta<EOL>right = eps_max + eta<EOL>return utils.Intervals(<EOL>[utils.Interval(mu+left, mu+right)<EOL>for mu in ritz.values[indices_remaining]])<EOL>
|
Estimate evals based on eval inclusion theorem + heuristic.
:returns: Intervals object with inclusion intervals for eigenvalues
|
f11479:c1:m2
|
def __init__(self,<EOL>mode='<STR_LIT>',<EOL>tol=None,<EOL>pseudospectra=False,<EOL>bound_pseudo_kwargs=None,<EOL>deflweight=<NUM_LIT:1.0>):
|
self._arnoldifyer = None<EOL>self.mode = mode<EOL>self.tol = tol<EOL>self.pseudospectra = pseudospectra<EOL>if bound_pseudo_kwargs is None:<EOL><INDENT>bound_pseudo_kwargs = {}<EOL><DEDENT>self.bound_pseudo_kwargs = bound_pseudo_kwargs<EOL>self.deflweight = deflweight<EOL>
|
Evaluates a choice of Ritz vectors with a tailored approximate
Krylov subspace method.
:param mode: (optional) determines how the number of iterations
is estimated. Must be one of the following:
* ``extrapolate`` (default): use the iteration count where the
extrapolation of the smallest residual reduction over all steps
drops below the tolerance.
* ``direct``: use the iteration count where the predicted residual
bound drops below the tolerance. May result in severe
underestimation if ``pseudospectra==False``.
:param pseudospectra: (optional) should pseudospectra be computed
for the given problem? With ``pseudospectra=True``, a prediction
may not be possible due to unfulfilled assumptions for the
computation of the pseudospectral bound.
:param bound_pseudo_kwargs: (optional) a dictionary with arguments
that are passed to :py:meth:`~krypy.deflation.bound_pseudo`.
:param deflweight: (optional) see
:py:meth:`~krypy._DeflationMixin.estimate_time`. Defaults to 1.
|
f11479:c2:m0
|
def generate(self, ritz, remaining_subset):
|
raise NotImplementedError('<STR_LIT>')<EOL>
|
Returns a list of subsets with indices of Ritz vectors that are
considered for deflation.
|
f11481:c0:m0
|
def bound_pseudo(arnoldifyer, Wt,<EOL>g_norm=<NUM_LIT:0.>,<EOL>G_norm=<NUM_LIT:0.>,<EOL>GW_norm=<NUM_LIT:0.>,<EOL>WGW_norm=<NUM_LIT:0.>,<EOL>tol=<NUM_LIT>,<EOL>pseudo_type='<STR_LIT>',<EOL>pseudo_kwargs=None,<EOL>delta_n=<NUM_LIT:20>,<EOL>terminate_factor=<NUM_LIT:1.><EOL>):
|
if pseudo_kwargs is None:<EOL><INDENT>pseudo_kwargs = {}<EOL><DEDENT>Hh, Rh, q_norm, vdiff_norm, PWAW_norm = arnoldifyer.get(Wt)<EOL>ls_orig = arnoldifyer._deflated_solver.linear_system<EOL>k = Wt.shape[<NUM_LIT:1>]<EOL>if k > <NUM_LIT:0>:<EOL><INDENT>WAW = Wt.T.conj().dot(arnoldifyer.J.dot(arnoldifyer.L.dot(Wt)))<EOL>sigma_min = numpy.min(scipy.linalg.svdvals(WAW))<EOL>if sigma_min <= WGW_norm:<EOL><INDENT>raise utils.AssumptionError(<EOL>'<STR_LIT>')<EOL><DEDENT>eta = GW_norm/(sigma_min - WGW_norm)<EOL><DEDENT>else:<EOL><INDENT>eta = <NUM_LIT:0.><EOL><DEDENT>b_norm = ls_orig.MMlb_norm<EOL>beta = PWAW_norm*(eta*(b_norm + g_norm) + g_norm) + vdiff_norm<EOL>if g_norm >= b_norm:<EOL><INDENT>raise utils.AssumptionError(<EOL>'<STR_LIT>')<EOL><DEDENT>ls_small = linsys.LinearSystem(Hh,<EOL>numpy.eye(Hh.shape[<NUM_LIT:0>], <NUM_LIT:1>) * q_norm,<EOL>normal=ls_orig.normal,<EOL>self_adjoint=ls_orig.self_adjoint,<EOL>positive_definite=ls_orig.positive_definite<EOL>)<EOL>Solver = type(arnoldifyer._deflated_solver)<EOL>if issubclass(Solver, linsys.Minres) or issubclass(Solver, linsys.Gmres):<EOL><INDENT>aresnorms = utils.get_residual_norms(Hh,<EOL>self_adjoint=ls_orig.self_adjoint)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>solver = Solver(ls_small, tol=tol, maxiter=Hh.shape[<NUM_LIT:0>])<EOL><DEDENT>except utils.ConvergenceError as e:<EOL><INDENT>solver = e.solver<EOL><DEDENT>aresnorms = numpy.array(solver.resnorms)<EOL><DEDENT>aresnorms = aresnorms * q_norm<EOL>if pseudo_type == '<STR_LIT>':<EOL><INDENT>return aresnorms / (b_norm - g_norm)<EOL><DEDENT>evals, evecs = scipy.linalg.eig(Hh)<EOL>if ls_small.self_adjoint:<EOL><INDENT>evals = numpy.real(evals)<EOL><DEDENT>Hh_norm = numpy.linalg.norm(Hh, <NUM_LIT:2>)<EOL>def _auto():<EOL><INDENT>'''<STR_LIT>'''<EOL>if numpy.linalg.norm(Hh-Hh.T.conj(), <NUM_LIT:2>) < <NUM_LIT>*Hh_norm:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if numpy.linalg.cond(evecs, <NUM_LIT:2>) < <NUM_LIT:1>+<NUM_LIT>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'<EOL><DEDENT>if pseudo_type == '<STR_LIT>':<EOL><INDENT>pseudo_type = _auto()<EOL><DEDENT>delta_max = <NUM_LIT>*numpy.max(numpy.abs(evals))<EOL>from scipy.linalg import svd<EOL>_, Rhsvd, _ = svd(Rh[:, :<NUM_LIT:1>])<EOL>delta_min = PWAW_norm*(eta*(Hh_norm + G_norm) + G_norm) + numpy.max(Rhsvd)<EOL>if delta_min == <NUM_LIT:0>:<EOL><INDENT>delta_min = <NUM_LIT><EOL><DEDENT>import pseudopy<EOL>if not ls_small.normal:<EOL><INDENT>pseudo = pseudopy.NonnormalAuto(Hh, delta_min*<NUM_LIT>, delta_max*<NUM_LIT>,<EOL>**pseudo_kwargs)<EOL><DEDENT>elif not ls_small.self_adjoint:<EOL><INDENT>pseudo = pseudopy.NormalEvals(evals)<EOL><DEDENT>else:<EOL><INDENT>pseudo = None<EOL><DEDENT>bounds = [aresnorms[<NUM_LIT:0>]]<EOL>for i in range(<NUM_LIT:1>, len(aresnorms)):<EOL><INDENT>if issubclass(Solver, linsys.Cg):<EOL><INDENT>roots = scipy.linalg.eigvalsh(Hh[:i, :i])<EOL><DEDENT>else:<EOL><INDENT>HhQ, HhR = scipy.linalg.qr(Hh[:i+<NUM_LIT:1>, :i], mode='<STR_LIT>')<EOL>roots_inv = scipy.linalg.eigvals(HhQ[:i, :].T.conj(), HhR)<EOL>roots = <NUM_LIT:1.>/roots_inv[numpy.abs(roots_inv) > <NUM_LIT>]<EOL><DEDENT>if ls_small.self_adjoint:<EOL><INDENT>roots = numpy.real(roots)<EOL><DEDENT>p = utils.NormalizedRootsPolynomial(roots)<EOL>if ls_small.self_adjoint:<EOL><INDENT>p_minmax_candidates = p.minmax_candidates()<EOL><DEDENT>aresnorm = aresnorms[i]<EOL>from scipy.linalg import svd<EOL>_, Rhsvd, _ = svd(Rh[:, :i])<EOL>Rhnrm = numpy.max(Rhsvd)<EOL>epsilon = PWAW_norm*(eta*(Hh_norm + G_norm) + G_norm)+ Rhnrm<EOL>if epsilon == <NUM_LIT:0>:<EOL><INDENT>epsilon = <NUM_LIT><EOL><DEDENT>if pseudo_type == '<STR_LIT>':<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>if epsilon >= delta_max:<EOL><INDENT>break<EOL><DEDENT>delta_log_range = numpy.linspace(numpy.log10(<NUM_LIT>*epsilon),<EOL>numpy.log10(delta_max),<EOL>delta_n+<NUM_LIT:2><EOL>)[<NUM_LIT:0>:-<NUM_LIT:1>]<EOL>def compute_pseudo(delta_log):<EOL><INDENT>delta = <NUM_LIT:10>**delta_log<EOL>if ls_small.self_adjoint:<EOL><INDENT>pseudo_intervals = utils.Intervals(<EOL>[utils.Interval(ev-delta, ev+delta) for ev in evals])<EOL>candidates = []<EOL>for candidate in p_minmax_candidates:<EOL><INDENT>if pseudo_intervals.contains(candidate):<EOL><INDENT>candidates.append(candidate)<EOL><DEDENT><DEDENT>all_candidates = numpy.r_[pseudo_intervals.get_endpoints(),<EOL>numpy.array(candidates)]<EOL>polymax = numpy.max(numpy.abs(p(all_candidates)))<EOL>pseudolen = <NUM_LIT:2> * delta<EOL><DEDENT>else:<EOL><INDENT>pseudo_path = pseudo.contour_paths(delta)<EOL>pseudolen = pseudo_path.length()<EOL>if pseudolen > <NUM_LIT:0>:<EOL><INDENT>polymax = numpy.max(numpy.abs(p(pseudo_path.vertices())))<EOL><DEDENT>else:<EOL><INDENT>polymax = numpy.Inf<EOL><DEDENT><DEDENT>return pseudolen/(<NUM_LIT:2>*numpy.pi*delta)* (epsilon/(delta-epsilon)*(q_norm + beta) + beta)* polymax<EOL><DEDENT>from scipy.optimize import minimize_scalar<EOL>opt_res = minimize_scalar(compute_pseudo,<EOL>bounds=(delta_log_range[<NUM_LIT:0>],<EOL>delta_log_range[-<NUM_LIT:1>]),<EOL>method='<STR_LIT>',<EOL>options={'<STR_LIT>': delta_n}<EOL>)<EOL>min_val = opt_res.fun<EOL>boundval = aresnorm + min_val<EOL>if i > <NUM_LIT:1> and boundval/bounds[-<NUM_LIT:1>] > terminate_factor:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>bounds.append(numpy.min([boundval, bounds[-<NUM_LIT:1>]]))<EOL><DEDENT><DEDENT>return numpy.array(bounds) / (b_norm - g_norm)<EOL>
|
r'''Bound residual norms of next deflated system.
:param arnoldifyer: an instance of
:py:class:`~krypy.deflation.Arnoldifyer`.
:param Wt: coefficients :math:`\tilde{W}\in\mathbb{C}^{n+d,k}` of the
considered deflation vectors :math:`W` for the basis :math:`[V,U]`
where ``V=last_solver.V`` and ``U=last_P.U``, i.e.,
:math:`W=[V,U]\tilde{W}` and
:math:`\mathcal{W}=\operatorname{colspan}(W)`. Must fulfill
:math:`\tilde{W}^*\tilde{W}=I_k`.
:param g_norm: norm :math:`\|g\|` of difference :math:`g=c-b` of
right hand sides. Has to fulfill :math:`\|g\|<\|b\|`.
:param G_norm: norm :math:`\|G\|` of difference
:math:`G=B-A` of operators.
:param GW_norm: Norm :math:`\|G|_{\mathcal{W}}\|` of difference
:math:`G=B-A` of operators restricted to :math:`\mathcal{W}`.
:param WGW_norm: Norm :math:`\|\langle W,GW\rangle\|_2`.
:param pseudo_type: One of
* ``'auto'``: determines if :math:`\hat{H}` is non-normal, normal or
Hermitian and uses the corresponding mode (see other options below).
* ``'nonnormal'``: the pseudospectrum of the Hessenberg matrix
:math:`\hat{H}` is used (involves one computation of a pseudospectrum)
* ``'normal'``: the pseudospectrum of :math:`\hat{H}` is computed
efficiently by the union of circles around the eigenvalues.
* ``'hermitian'``: the pseudospectrum of :math:`\hat{H}` is computed
efficiently by the union of intervals around the eigenvalues.
* ``'contain'``: the pseudospectrum of the extended Hessenberg matrix
:math:`\begin{bmatrix}\hat{H}\\S_i\end{bmatrix}` is used
(pseudospectrum has to be re computed for each iteration).
* ``'omit'``: do not compute the pseudospectrum at all and just use the
residual bounds from the approximate Krylov subspace.
:param pseudo_kwargs: (optional) arguments that are passed to the method
that computes the pseudospectrum.
:param terminate_factor: (optional) terminate the computation if the ratio
of two subsequent residual norms is larger than the provided factor.
Defaults to 1.
|
f11482:m0
|
def __init__(self, linear_system, U, **kwargs):
|
raise NotImplementedError('<STR_LIT>')<EOL>
|
Abstract base class of a projection for deflation.
:param A: the :py:class:`~krypy.linsys.LinearSystem`.
:param U: basis of the deflation space with ``U.shape == (N, d)``.
All parameters of :py:class:`~krypy.utils.Projection` are valid except
``X`` and ``Y``.
|
f11482:c0:m0
|
def __init__(self, linear_system, U, qr_reorthos=<NUM_LIT:0>, **kwargs):
|
<EOL>self.linear_system = linear_system<EOL>(N, d) = U.shape<EOL>U, _ = utils.qr(U, ip_B=linear_system.get_ip_Minv_B(),<EOL>reorthos=qr_reorthos)<EOL>self.U = U<EOL>'''<STR_LIT>'''<EOL>self.AU = linear_system.MlAMr*U<EOL>'''<STR_LIT>'''<EOL>self._MAU = None<EOL>super(_Projection, self).__init__(self.AU, self.U,<EOL>ip_B=linear_system.ip_B,<EOL>**kwargs)<EOL>
|
Oblique projection for left deflation.
|
f11482:c1:m0
|
def correct(self, z):
|
c = self.linear_system.Ml*(<EOL>self.linear_system.b - self.linear_system.A*z)<EOL>c = utils.inner(self.W, c, ip_B=self.ip_B)<EOL>if self.Q is not None and self.R is not None:<EOL><INDENT>c = scipy.linalg.solve_triangular(self.R, self.Q.T.conj().dot(c))<EOL><DEDENT>if self.WR is not self.VR:<EOL><INDENT>c = self.WR.dot(scipy.linalg.solve_triangular(self.VR, c))<EOL><DEDENT>return z + self.W.dot(c)<EOL>
|
Correct the given approximate solution ``z`` with respect to the
linear system ``linear_system`` and the deflation space defined by
``U``.
|
f11482:c1:m1
|
@property<EOL><INDENT>def MAU(self):<DEDENT>
|
if self._MAU is None:<EOL><INDENT>self._MAU = self.linear_system.M * self.AU<EOL><DEDENT>return self._MAU<EOL>
|
Result of preconditioned operator to deflation space, i.e.,
:math:`MM_lAM_rU`.
|
f11482:c1:m2
|
def _apply_projection(self, Av):
|
PAv, UAv = self.projection.apply_complement(Av, return_Ya=True)<EOL>self.C = numpy.c_[self.C, UAv]<EOL>return PAv<EOL>
|
Apply the projection and store inner product.
:param v: the vector resulting from an application of :math:`M_lAM_r`
to the current Arnoldi vector. (CG needs special treatment, here).
|
f11482:c2:m2
|
def _get_initial_residual(self, x0):
|
if x0 is None:<EOL><INDENT>Mlr = self.linear_system.Mlb<EOL><DEDENT>else:<EOL><INDENT>r = self.linear_system.b - self.linear_system.A*x0<EOL>Mlr = self.linear_system.Ml*r<EOL><DEDENT>PMlr, self.UMlr = self.projection.apply_complement(Mlr, return_Ya=True)<EOL>MPMlr = self.linear_system.M*PMlr<EOL>MPMlr_norm = utils.norm(PMlr, MPMlr, ip_B=self.linear_system.ip_B)<EOL>return MPMlr, PMlr, MPMlr_norm<EOL>
|
Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`.
|
f11482:c2:m3
|
@property<EOL><INDENT>def B_(self):<DEDENT>
|
(n_, n) = self.H.shape<EOL>ls = self.linear_system<EOL>if self._B_ is None or self._B_.shape[<NUM_LIT:1>] < n_:<EOL><INDENT>if ls.self_adjoint:<EOL><INDENT>self._B_ = self.C.T.conj()<EOL>if n_ > n:<EOL><INDENT>self._B_ = numpy.r_[self._B_,<EOL>utils.inner(self.V[:, [-<NUM_LIT:1>]],<EOL>self.projection.AU,<EOL>ip_B=ls.ip_B)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._B_ = utils.inner(self.V, self.projection.AU,<EOL>ip_B=ls.ip_B)<EOL><DEDENT><DEDENT>return self._B_<EOL>
|
r''':math:`\underline{B}=\langle V_{n+1},M_lAM_rU\rangle`.
This property is obtained from :math:`C` if the operator is
self-adjoint. Otherwise, the inner products have to be formed
explicitly.
|
f11482:c2:m5
|
def estimate_time(self, nsteps, ndefl, deflweight=<NUM_LIT:1.0>):
|
<EOL>solver_ops = self.operations(nsteps)<EOL>proj_ops = {'<STR_LIT:A>': ndefl,<EOL>'<STR_LIT:M>': ndefl,<EOL>'<STR_LIT>': ndefl,<EOL>'<STR_LIT>': ndefl,<EOL>'<STR_LIT>': (ndefl*(ndefl+<NUM_LIT:1>)/<NUM_LIT:2><EOL>+ ndefl**<NUM_LIT:2> + <NUM_LIT:2>*ndefl*solver_ops['<STR_LIT>']),<EOL>'<STR_LIT>': (ndefl*(ndefl+<NUM_LIT:1>)/<NUM_LIT:2> + ndefl*ndefl<EOL>+ (<NUM_LIT:2>*ndefl+<NUM_LIT:2>)*solver_ops['<STR_LIT>'])<EOL>}<EOL>if not isinstance(self.linear_system, linsys.TimedLinearSystem):<EOL><INDENT>raise utils.RuntimeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>timings = self.linear_system.timings<EOL>return (timings.get_ops(solver_ops)<EOL>+ deflweight*timings.get_ops(proj_ops))<EOL>
|
Estimate time needed to run nsteps iterations with deflation
Uses timings from :py:attr:`linear_system` if it is an instance of
:py:class:`~krypy.linsys.TimedLinearSystem`. Otherwise, an
:py:class:`~krypy.utils.OtherError`
is raised.
:param nsteps: number of iterations.
:param ndefl: number of deflation vectors.
:param deflweight: (optional) the time for the setup and application of
the projection for deflation is multiplied by this factor. This can
be used as a counter measure for the evaluation of Ritz vectors.
Defaults to 1.
|
f11482:c2:m6
|
def _apply_projection(self, Av):
|
PAv, UAp = self.projection.apply_complement(Av, return_Ya=True)<EOL>self._UAps.append(UAp)<EOL>c = UAp.copy()<EOL>rhos = self.rhos<EOL>if self.iter > <NUM_LIT:0>:<EOL><INDENT>c -= (<NUM_LIT:1> + rhos[-<NUM_LIT:1>]/rhos[-<NUM_LIT:2>])*self._UAps[-<NUM_LIT:2>]<EOL><DEDENT>if self.iter > <NUM_LIT:1>:<EOL><INDENT>c += rhos[-<NUM_LIT:2>]/rhos[-<NUM_LIT:3>]*self._UAps[-<NUM_LIT:3>]<EOL><DEDENT>c *= ((-<NUM_LIT:1>)**self.iter) / numpy.sqrt(rhos[-<NUM_LIT:1>])<EOL>if self.iter > <NUM_LIT:0>:<EOL><INDENT>c -= numpy.sqrt(rhos[-<NUM_LIT:2>]/rhos[-<NUM_LIT:1>]) * self.C[:, [-<NUM_LIT:1>]]<EOL><DEDENT>self.C = numpy.c_[self.C, c]<EOL>return PAv<EOL>
|
r'''Computes :math:`\langle C,M_lAM_rV_n\rangle` efficiently with a
three-term recurrence.
|
f11482:c3:m1
|
def __init__(self, deflated_solver):
|
self._deflated_solver = deflated_solver<EOL>H = deflated_solver.H<EOL>B_ = deflated_solver.B_<EOL>C = deflated_solver.C<EOL>E = deflated_solver.E<EOL>V = deflated_solver.V<EOL>U = deflated_solver.projection.U<EOL>AU = deflated_solver.projection.AU<EOL>ls = deflated_solver.linear_system<EOL>MAU = deflated_solver.projection.MAU<EOL>n_, n = self.n_, self.n = H.shape<EOL>d = self.d = deflated_solver.projection.U.shape[<NUM_LIT:1>]<EOL>EinvC = numpy.linalg.solve(E, C) if d > <NUM_LIT:0> else numpy.zeros((<NUM_LIT:0>, n))<EOL>self.L = numpy.bmat([[H, numpy.zeros((n_, d))],<EOL>[EinvC, numpy.eye(d)]])<EOL>self.J = numpy.bmat([[numpy.eye(n, n_), B_[:n, :]],<EOL>[numpy.zeros((d, n_)), E]])<EOL>self.M = numpy.bmat([[H[:n, :n]<EOL>+ B_[:n, :].dot(EinvC),<EOL>B_[:n, :]],<EOL>[C, E]])<EOL>self.A_norm = numpy.linalg.norm(self.M, <NUM_LIT:2>)<EOL>if d > <NUM_LIT:0>:<EOL><INDENT>Q, R, P = scipy.linalg.qr(MAU - U.dot(E) - V.dot(B_),<EOL>mode='<STR_LIT>', pivoting=True)<EOL>P_inv = numpy.argsort(P)<EOL>l = (numpy.abs(numpy.diag(R)) > <NUM_LIT>*self.A_norm).sum()<EOL>Q1 = Q[:, :l]<EOL>self.R12 = R[:l, P_inv]<EOL>Q1, Rt = utils.qr(Q1, ip_B=ls.get_ip_Minv_B())<EOL>self.R12 = Rt.dot(self.R12)<EOL>self.N = numpy.c_[numpy.eye(l+n_-n, n_-n),<EOL>numpy.r_[B_[n:, :],<EOL>self.R12]<EOL>].dot(<EOL>numpy.bmat([[numpy.zeros((d+n_-n, n)),<EOL>numpy.eye(d+n_-n)]]))<EOL><DEDENT>else:<EOL><INDENT>Q1 = numpy.zeros((U.shape[<NUM_LIT:0>], <NUM_LIT:0>))<EOL>self.R12 = numpy.zeros((<NUM_LIT:0>, <NUM_LIT:0>))<EOL>self.N = numpy.bmat([[numpy.zeros((n_-n, n)),<EOL>numpy.eye(n_-n, n_-n)]])<EOL><DEDENT>self.Z = numpy.c_[V[:, n:], Q1]<EOL>
|
r'''Obtain Arnoldi relations for approximate deflated Krylov subspaces.
:param deflated_solver: an instance of a deflated solver.
|
f11482:c6:m0
|
def get(self, Wt, full=False):
|
n = self.n<EOL>n_ = self.n_<EOL>d = self.d<EOL>k = Wt.shape[<NUM_LIT:1>]<EOL>if k > <NUM_LIT:0>:<EOL><INDENT>Wto, _ = scipy.linalg.qr(Wt)<EOL>Wt = Wto[:, :k]<EOL>Wto = Wto[:, k:]<EOL><DEDENT>else:<EOL><INDENT>Wto = numpy.eye(Wt.shape[<NUM_LIT:0>])<EOL><DEDENT>deflated_solver = self._deflated_solver<EOL>Pt = utils.Projection(self.L.dot(Wt), self.J.T.conj().dot(Wt)).operator_complement()<EOL>if d > <NUM_LIT:0>:<EOL><INDENT>qt = Pt*(numpy.r_[[[deflated_solver.MMlr0_norm]],<EOL>numpy.zeros((self.n_-<NUM_LIT:1>, <NUM_LIT:1>)),<EOL>numpy.linalg.solve(deflated_solver.E,<EOL>deflated_solver.UMlr)])<EOL><DEDENT>else:<EOL><INDENT>qt = Pt*(numpy.r_[[[deflated_solver.MMlr0_norm]],<EOL>numpy.zeros((self.n_-<NUM_LIT:1>, <NUM_LIT:1>))])<EOL><DEDENT>q = Wto.T.conj().dot(self.J.dot(qt))<EOL>Q = utils.House(q)<EOL>q_norm = Q.xnorm<EOL>WtoQ = Q.apply(Wto.T.conj()).T.conj()<EOL>from scipy.linalg import hessenberg<EOL>Hh, T = hessenberg(<EOL>Q.apply(Wto.T.conj().dot(self.J).dot(Pt*(self.L.dot(WtoQ)))),<EOL>calc_q=True)<EOL>QT = Q.apply(T)<EOL>Rh = self.N.dot(Pt*self.L.dot(Wto.dot(QT)))<EOL>vdiff = self.N.dot(qt)<EOL>vdiff_norm = <NUM_LIT:0> if vdiff.size == <NUM_LIT:0> else numpy.linalg.norm(vdiff, <NUM_LIT:2>)<EOL>if k > <NUM_LIT:0>:<EOL><INDENT>Y = numpy.bmat([[numpy.eye(n_), deflated_solver.B_],<EOL>[numpy.zeros((d, n_)), deflated_solver.E],<EOL>[numpy.zeros((self.R12.shape[<NUM_LIT:0>], n_)), self.R12]])<EOL>YL_Q, _ = scipy.linalg.qr(Y.dot(self.L.dot(Wt)), mode='<STR_LIT>')<EOL>WX = Wt.T.conj().dot(numpy.r_[YL_Q[:n, :],<EOL>YL_Q[n_:n_+d, :]])<EOL>PWAW_norm = <NUM_LIT:1.>/numpy.min(scipy.linalg.svdvals(WX))<EOL><DEDENT>else:<EOL><INDENT>PWAW_norm = <NUM_LIT:1.><EOL><DEDENT>if full:<EOL><INDENT>Vh = numpy.c_[deflated_solver.V[:, :n],<EOL>deflated_solver.projection.U].dot(Wto.dot(QT))<EOL>ip_Minv_B = deflated_solver.linear_system.get_ip_Minv_B()<EOL>def _apply_F(x):<EOL><INDENT>'''<STR_LIT>'''<EOL>return -(self.Z.dot(Rh.dot(utils.inner(Vh, x,<EOL>ip_B=ip_Minv_B)))<EOL>+ Vh.dot(Rh.T.conj().dot(utils.inner(self.Z, x,<EOL>ip_B=ip_Minv_B)))<EOL>)<EOL><DEDENT>F = utils.LinearOperator((Vh.shape[<NUM_LIT:0>], Vh.shape[<NUM_LIT:0>]),<EOL>dtype=deflated_solver.dtype,<EOL>dot=_apply_F<EOL>)<EOL>return Hh, Rh, q_norm, vdiff_norm, PWAW_norm, Vh, F<EOL><DEDENT>return Hh, Rh, q_norm, vdiff_norm, PWAW_norm<EOL>
|
r'''Get Arnoldi relation for a deflation subspace choice.
:param Wt: the coefficients :math:`\tilde{W}` of the deflation vectors
in the basis :math:`[V_n,U]` with ``Wt.shape == (n+d, k)``, i.e., the
deflation vectors are :math:`W=[V_n,U]\tilde{W}`. Must fulfill
:math:`\tilde{W}^*\tilde{W}=I_k`.
:param full: (optional) should the full Arnoldi
basis and the full perturbation be returned? Defaults to ``False``.
:return:
* ``Hh``: the Hessenberg matrix with ``Hh.shape == (n+d-k, n+d-k)``.
* ``Rh``: the perturbation core matrix with
``Rh.shape == (l, n+d-k)``.
* ``q_norm``: norm :math:`\|q\|_2`.
* ``vdiff_norm``: the norm of the difference of the initial vectors
:math:`\tilde{v}-\hat{v}`.
* ``PWAW_norm``: norm of the projection
:math:`P_{\mathcal{W}^\perp,A\mathcal{W}}`.
* ``Vh``: (if ``full == True``) the Arnoldi basis with ``Vh.shape ==
(N, n+d-k)``.
* ``F``: (if ``full == True``) the perturbation matrix
:math:`F=-Z\hat{R}\hat{V}_n^* - \hat{V}_n\hat{R}^*Z^*`.
|
f11482:c6:m1
|
def __init__(self, deflated_solver, mode='<STR_LIT>'):
|
self._deflated_solver = deflated_solver<EOL>linear_system = deflated_solver.linear_system<EOL>self.values = None<EOL>'''<STR_LIT>'''<EOL>self.coeffs = None<EOL>'''<STR_LIT>'''<EOL>H_ = deflated_solver.H<EOL>(n_, n) = H_.shape<EOL>H = H_[:n, :n]<EOL>projection = deflated_solver.projection<EOL>m = projection.U.shape[<NUM_LIT:1>]<EOL>I = numpy.eye<EOL>O = numpy.zeros<EOL>if n+m == <NUM_LIT:0>:<EOL><INDENT>self.values = numpy.zeros((<NUM_LIT:0>,))<EOL>self.coeffs = numpy.zeros((<NUM_LIT:0>,))<EOL>self.resnorms = numpy.zeros((<NUM_LIT:0>,))<EOL>return<EOL><DEDENT>if isinstance(projection, ObliqueProjection):<EOL><INDENT>E = deflated_solver.E<EOL>C = deflated_solver.C<EOL>if m > <NUM_LIT:0>:<EOL><INDENT>EinvC = numpy.linalg.solve(E, C)<EOL><DEDENT>else:<EOL><INDENT>EinvC = C<EOL><DEDENT>B_ = deflated_solver.B_<EOL>B = B_[:n, :]<EOL>M = numpy.bmat([[H + B.dot(EinvC), B],<EOL>[C, E]])<EOL>F = utils.inner(projection.AU, projection.MAU,<EOL>ip_B=linear_system.ip_B)<EOL>S = numpy.bmat([[I(n_), B_, O((n_, m))],<EOL>[B_.T.conj(), F, E],<EOL>[O((m, n_)), E.T.conj(), I(m)]])<EOL>eig = scipy.linalg.eigh if linear_system.self_adjointelse scipy.linalg.eig<EOL>if mode == '<STR_LIT>':<EOL><INDENT>self.values, self.coeffs = eig(M)<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>L = numpy.bmat([[H_, O((n_, m))],<EOL>[EinvC, I(m)]])<EOL>K = numpy.bmat([[I(n_), B_],<EOL>[B_.T.conj(), F]])<EOL>sigmas, self.coeffs = eig(M.T.conj(),<EOL>L.T.conj().dot(K.dot(L)))<EOL>self.values = numpy.zeros(m+n, dtype=sigmas.dtype)<EOL>zero = numpy.abs(sigmas) < numpy.finfo(float).eps<EOL>self.values[~zero] = <NUM_LIT:1.>/sigmas[~zero]<EOL>self.values[zero] = numpy.Inf<EOL><DEDENT>else:<EOL><INDENT>raise utils.ArgumentError(<EOL>'<STR_LIT>'.format(mode)<EOL>+ '<STR_LIT>')<EOL><DEDENT>for i in range(n+m):<EOL><INDENT>self.coeffs[:, [i]] /= numpy.linalg.norm(self.coeffs[:, [i]],<EOL><NUM_LIT:2>)<EOL><DEDENT>self.resnorms = numpy.zeros(m+n)<EOL>'''<STR_LIT>'''<EOL>for i in range(n+m):<EOL><INDENT>mu = self.values[i]<EOL>y = self.coeffs[:, [i]]<EOL>G = numpy.bmat([[H_ - mu*I(n_, n), O((n_, m))],<EOL>[EinvC, I(m)],<EOL>[O((m, n)), -mu*I(m)]])<EOL>Gy = G.dot(y)<EOL>resnorm2 = Gy.T.conj().dot(S.dot(Gy))<EOL>self.resnorms[i] = numpy.sqrt(numpy.abs(resnorm2))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise utils.ArgumentError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>
|
Compute Ritz pairs from a deflated Krylov subspace method.
:param deflated_solver: an instance of a deflated solver.
:param mode: (optional)
* ``ritz`` (default): compute Ritz pairs.
* ``harmonic``: compute harmonic Ritz pairs.
|
f11482:c7:m0
|
def get_vectors(self, indices=None):
|
H_ = self._deflated_solver.H<EOL>(n_, n) = H_.shape<EOL>coeffs = self.coeffs if indices is None else self.coeffs[:, indices]<EOL>return numpy.c_[self._deflated_solver.V[:, :n],<EOL>self._deflated_solver.projection.U].dot(coeffs)<EOL>
|
Compute Ritz vectors.
|
f11482:c7:m1
|
def get_explicit_residual(self, indices=None):
|
ritz_vecs = self.get_vectors(indices)<EOL>return self._deflated_solver.linear_system.MlAMr * ritz_vecs- ritz_vecs * self.values<EOL>
|
Explicitly computes the Ritz residual.
|
f11482:c7:m2
|
def get_explicit_resnorms(self, indices=None):
|
res = self.get_explicit_residual(indices)<EOL>linear_system = self._deflated_solver.linear_system<EOL>Mres = linear_system.M * res<EOL>resnorms = numpy.zeros(res.shape[<NUM_LIT:1>])<EOL>for i in range(resnorms.shape[<NUM_LIT:0>]):<EOL><INDENT>resnorms[i] = utils.norm(res[:, [i]], Mres[:, [i]],<EOL>ip_B=linear_system.ip_B)<EOL><DEDENT>return resnorms<EOL>
|
Explicitly computes the Ritz residual norms.
|
f11482:c7:m3
|
def somewhat_fun_method(self):
|
return '<STR_LIT>'<EOL>
|
LULZ
|
f11485:c0:m0
|
def somewhat_fun_method(self):
|
return '<STR_LIT>'<EOL>
|
LULZ
|
f11486:c0:m0
|
def some_method(self):
|
return '<STR_LIT>'<EOL>
|
Super Class Docs
|
f11487:c0:m0
|
@overrides<EOL><INDENT>def some_method(self):<DEDENT>
|
return <NUM_LIT:1><EOL>
|
Subber
|
f11487:c2:m0
|
def some_method(self):
|
return '<STR_LIT>'<EOL>
|
Super Class Docs
|
f11488:c0:m0
|
def overrides(method):
|
for super_class in _get_base_classes(sys._getframe(<NUM_LIT:2>), method.__globals__):<EOL><INDENT>if hasattr(super_class, method.__name__):<EOL><INDENT>super_method = getattr(super_class, method.__name__)<EOL>if hasattr(super_method, "<STR_LIT>"):<EOL><INDENT>finalized = getattr(super_method, "<STR_LIT>")<EOL>if finalized:<EOL><INDENT>raise AssertionError('<STR_LIT>' %<EOL>method.__name__)<EOL><DEDENT><DEDENT>if not method.__doc__:<EOL><INDENT>method.__doc__ = super_method.__doc__<EOL><DEDENT>return method<EOL><DEDENT><DEDENT>raise AssertionError('<STR_LIT>' %<EOL>method.__name__)<EOL>
|
Decorator to indicate that the decorated method overrides a method in
superclass.
The decorator code is executed while loading class. Using this method
should have minimal runtime performance implications.
This is based on my idea about how to do this and fwc:s highly improved
algorithm for the implementation fwc:s
algorithm : http://stackoverflow.com/a/14631397/308189
my answer : http://stackoverflow.com/a/8313042/308189
How to use:
from overrides import overrides
class SuperClass(object):
def method(self):
return 2
class SubClass(SuperClass):
@overrides
def method(self):
return 1
:raises AssertionError if no match in super classes for the method name
:return method with possibly added (if the method doesn't have one)
docstring from super class
|
f11490:m0
|
def _get_base_class_names(frame):
|
co, lasti = frame.f_code, frame.f_lasti<EOL>code = co.co_code<EOL>extends = []<EOL>for (op, oparg) in op_stream(code, lasti):<EOL><INDENT>if op in dis.hasconst:<EOL><INDENT>if type(co.co_consts[oparg]) == str:<EOL><INDENT>extends = []<EOL><DEDENT><DEDENT>elif op in dis.hasname:<EOL><INDENT>if dis.opname[op] == '<STR_LIT>':<EOL><INDENT>extends.append(('<STR_LIT:name>', co.co_names[oparg]))<EOL><DEDENT>if dis.opname[op] == '<STR_LIT>':<EOL><INDENT>extends.append(('<STR_LIT>', co.co_names[oparg]))<EOL><DEDENT>if dis.opname[op] == '<STR_LIT>':<EOL><INDENT>extends.append(('<STR_LIT:name>', co.co_names[oparg]))<EOL><DEDENT><DEDENT><DEDENT>items = []<EOL>previous_item = []<EOL>for t, s in extends:<EOL><INDENT>if t == '<STR_LIT:name>':<EOL><INDENT>if previous_item:<EOL><INDENT>items.append(previous_item)<EOL><DEDENT>previous_item = [s]<EOL><DEDENT>else:<EOL><INDENT>previous_item += [s]<EOL><DEDENT><DEDENT>if previous_item:<EOL><INDENT>items.append(previous_item)<EOL><DEDENT>return items<EOL>
|
Get baseclass names from the code object
|
f11490:m2
|
def final(method):
|
setattr(method, "<STR_LIT>", True)<EOL>return method<EOL>
|
Decorator to indicate that the decorated method is finalized and cannot be overridden.
The decorator code is executed while loading class. Using this method
should have minimal runtime performance implications.
Currently, only methods with @overrides are checked.
How to use:
from overrides import final
class SuperClass(object):
@final
def method(self):
return 2
class SubClass(SuperClass):
@overrides
def method(self): #causes an error
return 1
:raises AssertionError if there exists a match in sub classes for the method name
:return method
|
f11491:m0
|
def get_dummy_request():
|
request = RequestFactory().get("<STR_LIT:/>", HTTP_HOST='<STR_LIT>')<EOL>request.session = {}<EOL>request.user = AnonymousUser()<EOL>return request<EOL>
|
Returns a Request instance.
|
f11493:m0
|
@register.simple_tag(takes_context=True)<EOL>def staff_toolbar(context):
|
request = context['<STR_LIT>']<EOL>if not request.user.is_staff:<EOL><INDENT>return u'<STR_LIT>'<EOL><DEDENT>toolbar_html = toolbar_root(request, context)<EOL>return format_html(u'<STR_LIT>', toolbar_html)<EOL>
|
Display the staff toolbar
:param context:
:type context:
:return:
:rtype:
|
f11495:m0
|
@register.simple_tag(takes_context=True)<EOL>def set_staff_object(context, object):
|
request = context['<STR_LIT>']<EOL>request.staff_object = object<EOL>return u'<STR_LIT>'<EOL>
|
Assign an object to be the "main object" of this page.
Example::
{% set_staff_object page %}
|
f11495:m1
|
@register.tag<EOL>def set_staff_url(parser, token):
|
nodelist = parser.parse(('<STR_LIT>',))<EOL>parser.delete_first_token()<EOL>return AdminUrlNode(nodelist)<EOL>
|
Assign an URL to be the "admin link" of this page.
Example::
{% set_staff_url %}{% url 'admin:fluent_pages_page_change' page.id %}{% end_set_staff_url %}
|
f11495:m2
|
def get_staff_url(self):
|
object = self.get_staff_object()<EOL>if object is not None:<EOL><INDENT>return reverse(admin_urlname(object._meta, '<STR_LIT>'), args=(object.pk,))<EOL><DEDENT>model = _get_view_model(self)<EOL>if model is not None:<EOL><INDENT>return reverse(admin_urlname(object._meta, '<STR_LIT>'))<EOL><DEDENT>return None<EOL>
|
Return the Admin URL for the current view.
By default, it uses the :func:`get_staff_object` function to base the URL on.
|
f11497:c0:m1
|
def get_toolbar_root():
|
global _toolbar_root<EOL>if _toolbar_root is None:<EOL><INDENT>items = [load_toolbar_item(item) for item in appsettings.STAFF_TOOLBAR_ITEMS]<EOL>_toolbar_root = RootNode(*items)<EOL><DEDENT>return _toolbar_root<EOL>
|
Init on demand.
:rtype: RootNode
|
f11498:m0
|
def load_toolbar_item(import_path, *args, **kwargs):
|
if isinstance(import_path, (tuple, list)):<EOL><INDENT>children = [load_toolbar_item(path) for path in import_path]<EOL>return Group(*children)<EOL><DEDENT>elif isinstance(import_path, basestring):<EOL><INDENT>symbol = _import_symbol(import_path, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>symbol = import_path<EOL><DEDENT>if inspect.isclass(symbol):<EOL><INDENT>symbol = symbol(*args, **kwargs)<EOL><DEDENT>if not callable(symbol):<EOL><INDENT>raise ImproperlyConfigured("<STR_LIT>".format(import_path, '<STR_LIT>'))<EOL><DEDENT>return symbol<EOL>
|
Load an item in the toolbar
:param import_path: the dotted python path to class or function.
:param args: For classes, any arguments to pass to the constructor.
:param kwargs: For classes, any keyword arguments to pass to the constructor.
|
f11498:m1
|
def _import_symbol(import_path, setting_name):
|
mod_name, class_name = import_path.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>try:<EOL><INDENT>mod = import_module(mod_name)<EOL>cls = getattr(mod, class_name)<EOL><DEDENT>except ImportError as e:<EOL><INDENT>__, __, exc_traceback = sys.exc_info()<EOL>frames = traceback.extract_tb(exc_traceback)<EOL>if len(frames) > <NUM_LIT:1>:<EOL><INDENT>raise <EOL><DEDENT>raise ImproperlyConfigured("<STR_LIT>".format(setting_name, import_path))<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ImproperlyConfigured("<STR_LIT>".format(setting_name, import_path))<EOL><DEDENT>return cls<EOL>
|
Import a class or function by name.
|
f11498:m2
|
def toolbar_title(title):
|
return LazyToolbarItem('<STR_LIT>', title)<EOL>
|
Define a title to be included in the toolbar.
|
f11500:m0
|
def toolbar_literal(title):
|
return LazyToolbarItem('<STR_LIT>', title)<EOL>
|
Define a literal text to be included in the toolbar.
|
f11500:m1
|
def toolbar_item(callable_path, *args, **kwargs):
|
return LazyToolbarItem(callable_path, *args, **kwargs)<EOL>
|
Defining a toolbar item in the settings that also received arguments.
It won't be loaded until the toolbar is actually rendered.
|
f11500:m2
|
def toolbar_link(url, title):
|
return LazyToolbarItem('<STR_LIT>', url=url, title=title)<EOL>
|
Define a link to be included in the toolbar.
|
f11500:m3
|
def get_object(context):
|
object = None<EOL>view = context.get('<STR_LIT>')<EOL>if view:<EOL><INDENT>object = getattr(view, '<STR_LIT:object>', None)<EOL><DEDENT>if object is None:<EOL><INDENT>object = context.get('<STR_LIT:object>', None)<EOL><DEDENT>return object<EOL>
|
Get an object from the context or view.
|
f11501:m0
|
def __call__(self, request, context):
|
rows = self.get_rows(request, context)<EOL>return self.render(rows)<EOL>
|
Render the group
|
f11501:c2:m1
|
def get_rows(self, request, context):
|
from staff_toolbar.loading import load_toolbar_item<EOL>rows = []<EOL>for i, hook in enumerate(self.children):<EOL><INDENT>if isinstance(hook, (basestring, tuple, list)):<EOL><INDENT>hook = load_toolbar_item(hook)<EOL>self.children[i] = hook<EOL><DEDENT>html = hook(request, context)<EOL>if not html:<EOL><INDENT>continue<EOL><DEDENT>rows.append(html)<EOL><DEDENT>return rows<EOL>
|
Get all rows as HTML
|
f11501:c2:m2
|
def render(self, rows):
|
if not rows:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>li_tags = mark_safe(u"<STR_LIT:\n>".join(format_html(u'<STR_LIT>', force_text(row)) for row in rows))<EOL>if self.title:<EOL><INDENT>return format_html(u'<STR_LIT>', self.title, li_tags)<EOL><DEDENT>else:<EOL><INDENT>return format_html(u'<STR_LIT>', li_tags)<EOL><DEDENT>
|
Join the HTML rows.
|
f11501:c2:m3
|
def send_login_code(self, code, context, **kwargs):
|
from_number = self.from_number or getattr(settings, '<STR_LIT>')<EOL>sms_content = render_to_string(self.template_name, context)<EOL>self.twilio_client.messages.create(<EOL>to=code.user.phone_number,<EOL>from_=from_number,<EOL>body=sms_content<EOL>)<EOL>
|
Send a login code via SMS
|
f11528:c0:m1
|
def rest(f):
|
@wraps(f)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>ret = f(*args, **kwargs)<EOL>if ret is None:<EOL><INDENT>response = '<STR_LIT>', <NUM_LIT><EOL><DEDENT>elif isinstance(ret, current_app.response_class):<EOL><INDENT>response = ret<EOL><DEDENT>elif isinstance(ret, tuple):<EOL><INDENT>if isinstance(ret[<NUM_LIT:1>], basestring):<EOL><INDENT>response = jsonify(msg=ret[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>response = jsonify(**ret[<NUM_LIT:1>])<EOL><DEDENT>response.status_code = ret[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>response = jsonify(**ret)<EOL><DEDENT>return response<EOL><DEDENT>return wrapper<EOL>
|
Decorator for simple REST endpoints.
Functions must return one of these values:
- a dict to jsonify
- nothing for an empty 204 response
- a tuple containing a status code and a dict to jsonify
|
f11533:m6
|
@classmethod<EOL><INDENT>def by_col(cls, df, cols, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
if outvals is None:<EOL><INDENT>outvals = []<EOL>outvals.extend(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>pvalue = '<STR_LIT>'<EOL><DEDENT>return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,<EOL>outvals=outvals, stat=cls,<EOL>swapname='<STR_LIT>', **stat_kws)<EOL>
|
Function to compute a Join_Count statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_join_count'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Join_Count statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Join_Count statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Join_Count statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Join_Count class in pysal.esda
|
f11545:c0:m4
|
@property<EOL><INDENT>def _statistic(self):<DEDENT>
|
return self.C<EOL>
|
a standardized accessor for esda statistics
|
f11553:c0:m1
|
@classmethod<EOL><INDENT>def by_col(cls, df, cols, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,<EOL>outvals=outvals, stat=cls,<EOL>swapname=cls.__name__.lower(), **stat_kws)<EOL>
|
Function to compute a Geary statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, with default configurations,
the derived columns will be named like 'column_geary' and 'column_p_sim'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Geary statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Geary statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Geary statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
Notes
-----
Technical details and derivations can be found in :cite:`cliff81`.
|
f11553:c0:m4
|
def _univariate_handler(df, cols, stat=None, w=None, inplace=True,<EOL>pvalue = '<STR_LIT>', outvals = None, swapname='<STR_LIT>', **kwargs):
|
<EOL>if not inplace:<EOL><INDENT>new_df = df.copy()<EOL>_univariate_handler(new_df, cols, stat=stat, w=w, pvalue=pvalue,<EOL>inplace=True, outvals=outvals,<EOL>swapname=swapname, **kwargs)<EOL>return new_df<EOL><DEDENT>if w is None:<EOL><INDENT>for name in df._metadata:<EOL><INDENT>this_obj = df.__dict__.get(name)<EOL>if isinstance(this_obj, W):<EOL><INDENT>w = this_obj<EOL><DEDENT><DEDENT><DEDENT>if w is None:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if outvals is None:<EOL><INDENT>outvals = []<EOL><DEDENT>outvals.insert(<NUM_LIT:0>,'<STR_LIT>')<EOL>if pvalue.lower() in ['<STR_LIT:all>', '<STR_LIT>', '<STR_LIT:*>']:<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if pvalue is not '<STR_LIT>':<EOL><INDENT>outvals.append('<STR_LIT>'+pvalue.lower())<EOL><DEDENT>if isinstance(cols, str):<EOL><INDENT>cols = [cols]<EOL><DEDENT>def column_stat(column):<EOL><INDENT>return stat(column.values, w=w, **kwargs)<EOL><DEDENT>stat_objs = df[cols].apply(column_stat)<EOL>for col in cols:<EOL><INDENT>stat_obj = stat_objs[col]<EOL>y = kwargs.get('<STR_LIT:y>')<EOL>if y is not None:<EOL><INDENT>col += '<STR_LIT:->' + y.name<EOL><DEDENT>outcols = ['<STR_LIT:_>'.join((col, val)) for val in outvals]<EOL>for colname, attname in zip(outcols, outvals):<EOL><INDENT>df[colname] = stat_obj.__getattribute__(attname)<EOL><DEDENT><DEDENT>if swapname is not '<STR_LIT>':<EOL><INDENT>df.columns = [_swap_ending(col, swapname) if col.endswith('<STR_LIT>') else col<EOL>for col in df.columns]<EOL><DEDENT>
|
Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
the dataframe containing columns to compute the descriptive
statistics
cols : string or list of strings
one or more names of columns in `df` to use to compute
exploratory descriptive statistics.
stat : callable
a function that takes data as a first argument and any number
of configuration keyword arguments and returns an object
encapsulating the exploratory statistic results
w : pysal.weights.W
the spatial weights object corresponding to the dataframe
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
|
f11554:m0
|
def _bivariate_handler(df, x, y=None, w=None, inplace=True, pvalue='<STR_LIT>',<EOL>outvals=None, **kwargs):
|
real_swapname = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>if isinstance(y, str):<EOL><INDENT>y = [y]<EOL><DEDENT>if isinstance(x, str):<EOL><INDENT>x = [x]<EOL><DEDENT>if not inplace:<EOL><INDENT>new_df = df.copy()<EOL>_bivariate_handler(new_df, x, y=y, w=w, inplace=True,<EOL>swapname=real_swapname,<EOL>pvalue=pvalue, outvals=outvals, **kwargs)<EOL>return new_df<EOL><DEDENT>if y is None:<EOL><INDENT>y = x<EOL><DEDENT>for xi,yi in _it.product(x,y):<EOL><INDENT>if xi == yi:<EOL><INDENT>continue<EOL><DEDENT>_univariate_handler(df, cols=xi, w=w, y=df[yi], inplace=True,<EOL>pvalue=pvalue, outvals=outvals, swapname='<STR_LIT>', **kwargs)<EOL><DEDENT>if real_swapname is not '<STR_LIT>':<EOL><INDENT>df.columns = [_swap_ending(col, real_swapname)<EOL>if col.endswith('<STR_LIT>')<EOL>else col for col in df.columns]<EOL><DEDENT>
|
Compute a descriptive bivariate statistic over two sets of columns, `x` and
`y`, contained in `df`.
Parameters
----------
df : pandas.DataFrame
dataframe in which columns `x` and `y` are contained
x : string or list of strings
one or more column names to use as variates in the bivariate
statistics
y : string or list of strings
one or more column names to use as variates in the bivariate
statistics
w : pysal.weights.W
spatial weights object corresponding to the dataframe `df`
inplace : bool
a flag denoting whether to add the statistic to the dataframe
in memory, or to construct a copy of the dataframe and append
the results to the copy
pvalue : string
the name of the pvalue on the results object wanted
outvals : list of strings
names of attributes of the dataframe to attempt to flatten
into a column
swapname : string
suffix to replace generic identifier with. Each caller of this
function should set this to a unique column suffix
**kwargs : optional keyword arguments
options that are passed directly to the statistic
|
f11554:m1
|
def _swap_ending(s, ending, delim='<STR_LIT:_>'):
|
parts = [x for x in s.split(delim)[:-<NUM_LIT:1>] if x != '<STR_LIT>']<EOL>parts.append(ending)<EOL>return delim.join(parts)<EOL>
|
Replace the ending of a string, delimited into an arbitrary
number of chunks by `delim`, with the ending provided
Parameters
----------
s : string
string to replace endings
ending : string
string used to replace ending of `s`
delim : string
string that splits s into one or more parts
Returns
-------
new string where the final chunk of `s`, delimited by `delim`, is replaced
with `ending`.
|
f11554:m2
|
@property<EOL><INDENT>def _statistic(self):<DEDENT>
|
return self.G<EOL>
|
Standardized accessor for esda statistics
|
f11555:c0:m3
|
@classmethod<EOL><INDENT>def by_col(cls, df, cols, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,<EOL>outvals=outvals, stat=cls,<EOL>swapname=cls.__name__.lower(), **stat_kws)<EOL>
|
Function to compute a G statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named 'column_g'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the G statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
G statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the G statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the G class in pysal.esda
|
f11555:c0:m4
|
@property<EOL><INDENT>def _statistic(self):<DEDENT>
|
return self.Gs<EOL>
|
Standardized accessor for esda statistics
|
f11555:c1:m4
|
@classmethod<EOL><INDENT>def by_col(cls, df, cols, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,<EOL>outvals=outvals, stat=cls,<EOL>swapname=cls.__name__.lower(), **stat_kws)<EOL>
|
Function to compute a G_Local statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named 'column_g_local'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the G_Local statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
G_Local statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the G_Local statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the G_Local class in pysal.esda
|
f11555:c1:m5
|
def flatten(l, unique=True):
|
l = reduce(lambda x, y: x + y, l)<EOL>if not unique:<EOL><INDENT>return list(l)<EOL><DEDENT>return list(set(l))<EOL>
|
flatten a list of lists
Parameters
----------
l : list
of lists
unique : boolean
whether or not only unique items are wanted (default=True)
Returns
-------
list
of single items
Examples
--------
Creating a sample list whose elements are lists of integers
>>> l = [[1, 2], [3, 4, ], [5, 6]]
Applying flatten function
>>> flatten(l)
[1, 2, 3, 4, 5, 6]
|
f11556:m0
|
def weighted_median(d, w):
|
dtype = [('<STR_LIT:w>', '<STR_LIT:%s>' % w.dtype), ('<STR_LIT:v>', '<STR_LIT:%s>' % d.dtype)]<EOL>d_w = np.array(list(zip(w, d)), dtype=dtype)<EOL>d_w.sort(order='<STR_LIT:v>')<EOL>reordered_w = d_w['<STR_LIT:w>'].cumsum()<EOL>cumsum_threshold = reordered_w[-<NUM_LIT:1>] * <NUM_LIT:1.0> / <NUM_LIT:2><EOL>median_inx = (reordered_w >= cumsum_threshold).nonzero()[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>if reordered_w[median_inx] == cumsum_threshold and len(d) - <NUM_LIT:1> > median_inx:<EOL><INDENT>return np.sort(d)[median_inx:median_inx + <NUM_LIT:2>].mean()<EOL><DEDENT>return np.sort(d)[median_inx]<EOL>
|
A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
d and w are arranged in the same order
Returns
-------
float
median of d
Examples
--------
Creating an array including five integers.
We will get the median of these integers.
>>> d = np.array([5,4,3,1,2])
Creating another array including weight values for the above integers.
The median of d will be decided with a consideration to these weight
values.
>>> w = np.array([10, 22, 9, 2, 5])
Applying weighted_median function
>>> weighted_median(d, w)
4
|
f11556:m1
|
def sum_by_n(d, w, n):
|
t = len(d)<EOL>h = t // n <EOL>d = d * w<EOL>return np.array([sum(d[i: i + h]) for i in range(<NUM_LIT:0>, t, h)])<EOL>
|
A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weighting
n : integer
the number of groups
t = c*n (c is a constant)
Returns
-------
: array
(n, 1), an array with summarized values
Examples
--------
Creating an array including four integers.
We will compute weighted means for every two elements.
>>> d = np.array([10, 9, 20, 30])
Here is another array with the weight values for d's elements.
>>> w = np.array([0.5, 0.1, 0.3, 0.8])
We specify the number of groups for which the weighted mean is computed.
>>> n = 2
Applying sum_by_n function
>>> sum_by_n(d, w, n)
array([ 5.9, 30. ])
|
f11556:m2
|
def crude_age_standardization(e, b, n):
|
r = e * <NUM_LIT:1.0> / b<EOL>b_by_n = sum_by_n(b, <NUM_LIT:1.0>, n)<EOL>age_weight = b * <NUM_LIT:1.0> / b_by_n.repeat(len(e) // n)<EOL>return sum_by_n(r, age_weight, n)<EOL>
|
A utility function to compute rate through crude age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
n : integer
the number of spatial units
Notes
-----
e and b are arranged in the same order
Returns
-------
: array
(n, 1), age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
Specifying the number of regions.
>>> n = 2
Applying crude_age_standardization function to e and b
>>> crude_age_standardization(e, b, n)
array([0.2375 , 0.26666667])
|
f11556:m3
|
def direct_age_standardization(e, b, s, n, alpha=<NUM_LIT>):
|
age_weight = (<NUM_LIT:1.0> / b) * (s * <NUM_LIT:1.0> / sum_by_n(s, <NUM_LIT:1.0>, n).repeat(len(s) // n))<EOL>adjusted_r = sum_by_n(e, age_weight, n)<EOL>var_estimate = sum_by_n(e, np.square(age_weight), n)<EOL>g_a = np.square(adjusted_r) / var_estimate<EOL>g_b = var_estimate / adjusted_r<EOL>k = [age_weight[i:i + len(b) // n].max() for i in range(<NUM_LIT:0>, len(b),<EOL>len(b) // n)]<EOL>g_a_k = np.square(adjusted_r + k) / (var_estimate + np.square(k))<EOL>g_b_k = (var_estimate + np.square(k)) / (adjusted_r + k)<EOL>summed_b = sum_by_n(b, <NUM_LIT:1.0>, n)<EOL>res = []<EOL>for i in range(len(adjusted_r)):<EOL><INDENT>if adjusted_r[i] == <NUM_LIT:0>:<EOL><INDENT>upper = <NUM_LIT:0.5> * chi2.ppf(<NUM_LIT:1> - <NUM_LIT:0.5> * alpha)<EOL>lower = <NUM_LIT:0.0><EOL><DEDENT>else:<EOL><INDENT>lower = gamma.ppf(<NUM_LIT:0.5> * alpha, g_a[i], scale=g_b[i])<EOL>upper = gamma.ppf(<NUM_LIT:1> - <NUM_LIT:0.5> * alpha, g_a_k[i], scale=g_b_k[i])<EOL><DEDENT>res.append((adjusted_r[i], lower, upper))<EOL><DEDENT>return res<EOL>
|
A utility function to compute rate through direct age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s : array
(n*h, 1), standard population for each age group across n spatial units
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, and s are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rates and confidence intervals
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([1000, 1000, 1100, 900, 1000, 900, 1100, 900])
For direct age standardization, we also need the data for standard population.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., population distribution for Arizona and California).
Another array including standard population is created.
>>> s = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying direct_age_standardization function to e and b
>>> a, b = [i[0] for i in direct_age_standardization(e, b, s, n)]
>>> round(a, 4)
0.0237
>>> round(b, 4)
0.0267
|
f11556:m4
|
def indirect_age_standardization(e, b, s_e, s_b, n, alpha=<NUM_LIT>):
|
smr = standardized_mortality_ratio(e, b, s_e, s_b, n)<EOL>s_r_all = sum(s_e * <NUM_LIT:1.0>) / sum(s_b * <NUM_LIT:1.0>)<EOL>adjusted_r = s_r_all * smr<EOL>e_by_n = sum_by_n(e, <NUM_LIT:1.0>, n)<EOL>log_smr = np.log(smr)<EOL>log_smr_sd = <NUM_LIT:1.0> / np.sqrt(e_by_n)<EOL>norm_thres = norm.ppf(<NUM_LIT:1> - <NUM_LIT:0.5> * alpha)<EOL>log_smr_lower = log_smr - norm_thres * log_smr_sd<EOL>log_smr_upper = log_smr + norm_thres * log_smr_sd<EOL>smr_lower = np.exp(log_smr_lower) * s_r_all<EOL>smr_upper = np.exp(log_smr_upper) * s_r_all<EOL>res = list(zip(adjusted_r, smr_lower, smr_upper))<EOL>return res<EOL>
|
A utility function to compute rate through indirect age standardization
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s_e : array
(n*h, 1), event variable measured for each age group across n spatial units in a standard population
s_b : array
(n*h, 1), population variable measured for each age group across n spatial units in a standard population
n : integer
the number of spatial units
alpha : float
significance level for confidence interval
Notes
-----
e, b, s_e, and s_b are arranged in the same order
Returns
-------
list
a list of n tuples; a tuple has a rate and its lower and upper limits
age standardized rate
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
For indirect age standardization, we also need the data for standard population and event.
Standard population is a reference population-at-risk (e.g., population distribution for the U.S.)
whose age distribution can be used as a benchmarking point for comparing age distributions
across regions (e.g., popoulation distribution for Arizona and California).
When the same concept is applied to the event variable,
we call it standard event (e.g., the number of cancer patients in the U.S.).
Two additional arrays including standard population and event are created.
>>> s_e = np.array([100, 45, 120, 100, 50, 30, 200, 80])
>>> s_b = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying indirect_age_standardization function to e and b
>>> [i[0] for i in indirect_age_standardization(e, b, s_e, s_b, n)]
[0.23723821989528798, 0.2610803324099723]
|
f11556:m5
|
def standardized_mortality_ratio(e, b, s_e, s_b, n):
|
s_r = s_e * <NUM_LIT:1.0> / s_b<EOL>e_by_n = sum_by_n(e, <NUM_LIT:1.0>, n)<EOL>expected = sum_by_n(b, s_r, n)<EOL>smr = e_by_n * <NUM_LIT:1.0> / expected<EOL>return smr<EOL>
|
A utility function to compute standardized mortality ratio (SMR).
Parameters
----------
e : array
(n*h, 1), event variable measured for each age group across n spatial units
b : array
(n*h, 1), population at risk variable measured for each age group across n spatial units
s_e : array
(n*h, 1), event variable measured for each age group across n spatial units in a standard population
s_b : array
(n*h, 1), population variable measured for each age group across n spatial units in a standard population
n : integer
the number of spatial units
Notes
-----
e, b, s_e, and s_b are arranged in the same order
Returns
-------
array
(nx1)
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
To compute standardized mortality ratio (SMR),
we need two additional arrays for standard population and event.
Creating s_e and s_b for standard event and population, respectively.
>>> s_e = np.array([100, 45, 120, 100, 50, 30, 200, 80])
>>> s_b = np.array([1000, 900, 1000, 900, 1000, 900, 1000, 900])
Specifying the number of regions.
>>> n = 2
Applying indirect_age_standardization function to e and b
>>> a, b = standardized_mortality_ratio(e, b, s_e, s_b, n)
>>> round(a, 4)
2.4869
>>> round(b, 4)
2.7368
|
f11556:m6
|
def choynowski(e, b, n, threshold=None):
|
e_by_n = sum_by_n(e, <NUM_LIT:1.0>, n)<EOL>b_by_n = sum_by_n(b, <NUM_LIT:1.0>, n)<EOL>r_by_n = sum(e_by_n) * <NUM_LIT:1.0> / sum(b_by_n)<EOL>expected = r_by_n * b_by_n<EOL>p = []<EOL>for index, i in enumerate(e_by_n):<EOL><INDENT>if i <= expected[index]:<EOL><INDENT>p.append(poisson.cdf(i, expected[index]))<EOL><DEDENT>else:<EOL><INDENT>p.append(<NUM_LIT:1> - poisson.cdf(i - <NUM_LIT:1>, expected[index]))<EOL><DEDENT><DEDENT>if threshold:<EOL><INDENT>p = [i if i < threshold else <NUM_LIT:0.0> for i in p]<EOL><DEDENT>return np.array(p)<EOL>
|
Choynowski map probabilities [Choynowski1959]_ .
Parameters
----------
e : array(n*h, 1)
event variable measured for each age group across n spatial units
b : array(n*h, 1)
population at risk variable measured for each age group across n spatial units
n : integer
the number of spatial units
threshold : float
Returns zero for any p-value greater than threshold
Notes
-----
e and b are arranged in the same order
Returns
-------
: array (nx1)
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 2 regions in each of which 4 age groups are available.
The first 4 values are event values for 4 age groups in the region 1,
and the next 4 values are for 4 age groups in the region 2.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same two regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
Specifying the number of regions.
>>> n = 2
Applying indirect_age_standardization function to e and b
>>> a,b = choynowski(e, b, n)
>>> round(a, 3)
0.304
>>> round(b, 3)
0.294
|
f11556:m7
|
def assuncao_rate(e, b):
|
y = e * <NUM_LIT:1.0> / b<EOL>e_sum, b_sum = sum(e), sum(b)<EOL>ebi_b = e_sum * <NUM_LIT:1.0> / b_sum<EOL>s2 = sum(b * ((y - ebi_b) ** <NUM_LIT:2>)) / b_sum<EOL>ebi_a = s2 - ebi_b / (float(b_sum) / len(e))<EOL>ebi_v = ebi_a + ebi_b / b<EOL>return (y - ebi_b) / np.sqrt(ebi_v)<EOL>
|
The standardized rates where the mean and stadard deviation used for
the standardization are those of Empirical Bayes rate estimates
The standardized rates resulting from this function are used to compute
Moran's I corrected for rate variables [Choynowski1959]_ .
Parameters
----------
e : array(n, 1)
event variable measured at n spatial units
b : array(n, 1)
population at risk variable measured at n spatial units
Notes
-----
e and b are arranged in the same order
Returns
-------
: array (nx1)
Examples
--------
Creating an array of an event variable (e.g., the number of cancer patients)
for 8 regions.
>>> e = np.array([30, 25, 25, 15, 33, 21, 30, 20])
Creating another array of a population-at-risk variable (e.g., total population)
for the same 8 regions.
The order for entering values is the same as the case of e.
>>> b = np.array([100, 100, 110, 90, 100, 90, 110, 90])
Computing the rates
>>> assuncao_rate(e, b)[:4]
array([ 1.03843594, -0.04099089, -0.56250375, -1.73061861])
|
f11556:m8
|
@classmethod<EOL><INDENT>def by_col(cls, df, e,b, inplace=False, **kwargs):<DEDENT>
|
if not inplace:<EOL><INDENT>new = df.copy()<EOL>cls.by_col(new, e, b, inplace=True, **kwargs)<EOL>return new<EOL><DEDENT>if isinstance(e, str):<EOL><INDENT>e = [e]<EOL><DEDENT>if isinstance(b, str):<EOL><INDENT>b = [b]<EOL><DEDENT>if len(b) == <NUM_LIT:1> and len(e) > <NUM_LIT:1>:<EOL><INDENT>b = b * len(e)<EOL><DEDENT>try:<EOL><INDENT>assert len(e) == len(b)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>for ei, bi in zip(e,b):<EOL><INDENT>ename = ei<EOL>bname = bi<EOL>ei = df[ename]<EOL>bi = df[bname]<EOL>outcol = '<STR_LIT:_>'.join(('<STR_LIT:->'.join((ename, bname)), cls.__name__.lower()))<EOL>df[outcol] = cls(ei, bi, **kwargs).r<EOL><DEDENT>
|
Compute smoothing by columns in a dataframe.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
the name or names of columns containing event variables to be
smoothed
b : string or list of strings
the name or names of columns containing the population
variables to be smoothed
inplace : bool
a flag denoting whether to output a copy of `df` with the
relevant smoothed columns appended, or to append the columns
directly to `df` itself.
**kwargs: optional keyword arguments
optional keyword options that are passed directly to the
smoother.
Returns
---------
a copy of `df` containing the columns. Or, if `inplace`, this returns
None, but implicitly adds columns to `df`.
|
f11556:c0:m1
|
@classmethod<EOL><INDENT>def by_col(cls, df, e,b, w=None, inplace=False, **kwargs):<DEDENT>
|
if not inplace:<EOL><INDENT>new = df.copy()<EOL>cls.by_col(new, e, b, w=w, inplace=True, **kwargs)<EOL>return new<EOL><DEDENT>if isinstance(e, str):<EOL><INDENT>e = [e]<EOL><DEDENT>if isinstance(b, str):<EOL><INDENT>b = [b]<EOL><DEDENT>if w is None:<EOL><INDENT>found = False<EOL>for k in df._metadata:<EOL><INDENT>w = df.__dict__.get(w, None)<EOL>if isinstance(w, W):<EOL><INDENT>found = True<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if isinstance(w, W):<EOL><INDENT>w = [w] * len(e)<EOL><DEDENT>if len(b) == <NUM_LIT:1> and len(e) > <NUM_LIT:1>:<EOL><INDENT>b = b * len(e)<EOL><DEDENT>try:<EOL><INDENT>assert len(e) == len(b)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>for ei, bi, wi in zip(e, b, w):<EOL><INDENT>ename = ei<EOL>bname = bi<EOL>ei = df[ename]<EOL>bi = df[bname]<EOL>outcol = '<STR_LIT:_>'.join(('<STR_LIT:->'.join((ename, bname)), cls.__name__.lower()))<EOL>df[outcol] = cls(ei, bi, w=wi, **kwargs).r<EOL><DEDENT>
|
Compute smoothing by columns in a dataframe.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
the name or names of columns containing event variables to be
smoothed
b : string or list of strings
the name or names of columns containing the population
variables to be smoothed
w : pysal.weights.W or list of pysal.weights.W
the spatial weights object or objects to use with the
event-population pairs. If not provided and a weights object
is in the dataframe's metadata, that weights object will be
used.
inplace : bool
a flag denoting whether to output a copy of `df` with the
relevant smoothed columns appended, or to append the columns
directly to `df` itself.
**kwargs: optional keyword arguments
optional keyword options that are passed directly to the
smoother.
Returns
---------
a copy of `df` containing the columns. Or, if `inplace`, this returns
None, but implicitly adds columns to `df`.
|
f11556:c3:m1
|
@_requires('<STR_LIT>')<EOL><INDENT>@classmethod<EOL>def by_col(cls, df, e,b, w=None, s=None, **kwargs):<DEDENT>
|
if s is None:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>import pandas as pd<EOL>if isinstance(e, str):<EOL><INDENT>e = [e]<EOL><DEDENT>if isinstance(b, str):<EOL><INDENT>b = [b]<EOL><DEDENT>if isinstance(s, str):<EOL><INDENT>s = [s]<EOL><DEDENT>if w is None:<EOL><INDENT>found = False<EOL>for k in df._metadata:<EOL><INDENT>w = df.__dict__.get(w, None)<EOL>if isinstance(w, W):<EOL><INDENT>found = True<EOL>break<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if isinstance(w, W):<EOL><INDENT>w = [w] * len(e)<EOL><DEDENT>if not all(isinstance(wi, W) for wi in w):<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>b = b * len(e) if len(b) == <NUM_LIT:1> and len(e) > <NUM_LIT:1> else b<EOL>s = s * len(e) if len(s) == <NUM_LIT:1> and len(e) > <NUM_LIT:1> else s<EOL>try:<EOL><INDENT>assert len(e) == len(b)<EOL>assert len(e) == len(s)<EOL>assert len(e) == len(w)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>rdf = []<EOL>max_len = <NUM_LIT:0><EOL>for ei, bi, wi, si in zip(e, b, w, s):<EOL><INDENT>ename = ei<EOL>bname = bi<EOL>h = len(ei) // wi.n<EOL>outcol = '<STR_LIT:_>'.join(('<STR_LIT:->'.join((ename, bname)), cls.__name__.lower()))<EOL>this_r = cls(df[ei], df[bi], w=wi, s=df[si], **kwargs).r<EOL>max_len = <NUM_LIT:0> if len(this_r) > max_len else max_len<EOL>rdf.append((outcol, this_r.tolist()))<EOL><DEDENT>padded = (r[<NUM_LIT:1>] + [None] * max_len for r in rdf)<EOL>rdf = list(zip((r[<NUM_LIT:0>] for r in rdf), padded))<EOL>rdf = pd.DataFrame.from_items(rdf)<EOL>return rdf<EOL>
|
Compute smoothing by columns in a dataframe.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
the name or names of columns containing event variables to be
smoothed
b : string or list of strings
the name or names of columns containing the population
variables to be smoothed
w : pysal.weights.W or list of pysal.weights.W
the spatial weights object or objects to use with the
event-population pairs. If not provided and a weights object
is in the dataframe's metadata, that weights object will be
used.
s : string or list of strings
the name or names of columns to use as a standard population
variable for the events `e` and at-risk populations `b`.
inplace : bool
a flag denoting whether to output a copy of `df` with the
relevant smoothed columns appended, or to append the columns
directly to `df` itself.
**kwargs: optional keyword arguments
optional keyword options that are passed directly to the
smoother.
Returns
---------
a copy of `df` containing the columns. Or, if `inplace`, this returns
None, but implicitly adds columns to `df`.
|
f11556:c7:m1
|
@_requires('<STR_LIT>')<EOL><INDENT>@classmethod<EOL>def by_col(cls, df, e, b, x_grid, y_grid, geom_col='<STR_LIT>', **kwargs):<DEDENT>
|
import pandas as pd<EOL>if isinstance(e, str):<EOL><INDENT>e = [e]<EOL><DEDENT>if isinstance(b, str):<EOL><INDENT>b = [b]<EOL><DEDENT>if len(e) > len(b):<EOL><INDENT>b = b * len(e)<EOL><DEDENT>if isinstance(x_grid, (int, float)):<EOL><INDENT>x_grid = [x_grid] * len(e)<EOL><DEDENT>if isinstance(y_grid, (int, float)):<EOL><INDENT>y_grid = [y_grid] * len(e)<EOL><DEDENT>bbox = get_bounding_box(df[geom_col])<EOL>bbox = [[bbox.left, bbox.lower], [bbox.right, bbox.upper]]<EOL>data = get_points_array(df[geom_col])<EOL>res = []<EOL>for ename, bname, xgi, ygi in zip(e, b, x_grid, y_grid):<EOL><INDENT>r = cls(bbox, data, df[ename], df[bname], xgi, ygi, **kwargs)<EOL>grid = np.asarray(r.grid).reshape(-<NUM_LIT:1>,<NUM_LIT:2>)<EOL>name = '<STR_LIT:_>'.join(('<STR_LIT:->'.join((ename, bname)), cls.__name__.lower()))<EOL>colnames = ('<STR_LIT:_>'.join((name, suffix)) for suffix in ['<STR_LIT:X>', '<STR_LIT:Y>', '<STR_LIT:R>'])<EOL>items = [(name, col) for name,col in zip(colnames, [grid[:,<NUM_LIT:0>],<EOL>grid[:,<NUM_LIT:1>],<EOL>r.r])]<EOL>res.append(pd.DataFrame.from_items(items))<EOL><DEDENT>outdf = pd.concat(res)<EOL>return outdf<EOL>
|
Compute smoothing by columns in a dataframe. The bounding box and point
information is computed from the geometry column.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
the name or names of columns containing event variables to be
smoothed
b : string or list of strings
the name or names of columns containing the population
variables to be smoothed
x_grid : integer
number of grid cells to use along the x-axis
y_grid : integer
number of grid cells to use along the y-axis
geom_col: string
the name of the column in the dataframe containing the
geometry information.
**kwargs: optional keyword arguments
optional keyword options that are passed directly to the
smoother.
Returns
---------
a new dataframe of dimension (x_grid*y_grid, 3), containing the
coordinates of the grid cells and the rates associated with those grid
cells.
|
f11556:c10:m1
|
@_requires('<STR_LIT>')<EOL><INDENT>@classmethod<EOL>def by_col(cls, df, e, b, t=None, geom_col='<STR_LIT>', inplace=False, **kwargs):<DEDENT>
|
import pandas as pd<EOL>if not inplace:<EOL><INDENT>new = df.copy()<EOL>cls.by_col(new, e, b, t=t, geom_col=geom_col, inplace=True, **kwargs)<EOL>return new<EOL><DEDENT>import pandas as pd<EOL>if isinstance(e, str):<EOL><INDENT>e = [e]<EOL><DEDENT>if isinstance(b, str):<EOL><INDENT>b = [b]<EOL><DEDENT>if len(e) > len(b):<EOL><INDENT>b = b * len(e)<EOL><DEDENT>data = get_points_array(df[geom_col])<EOL>w = kwargs.pop('<STR_LIT:w>', None)<EOL>if w is None:<EOL><INDENT>found = False<EOL>for k in df._metadata:<EOL><INDENT>w = df.__dict__.get(w, None)<EOL>if isinstance(w, W):<EOL><INDENT>found = True<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>k = kwargs.pop('<STR_LIT:k>', <NUM_LIT:5>)<EOL>t = kwargs.pop('<STR_LIT:t>', <NUM_LIT:3>)<EOL>angle = kwargs.pop('<STR_LIT>', <NUM_LIT>)<EOL>edgecor = kwargs.pop('<STR_LIT>', False)<EOL>hbt = Headbanging_Triples(data, w, k=k, t=t, angle=angle,<EOL>edgecor=edgecor)<EOL>res = []<EOL>for ename, bname in zip(e, b):<EOL><INDENT>r = cls(df[ename], df[bname], hbt, **kwargs).r<EOL>name = '<STR_LIT:_>'.join(('<STR_LIT:->'.join((ename, bname)), cls.__name__.lower()))<EOL>df[name] = r<EOL><DEDENT>
|
Compute smoothing by columns in a dataframe. The bounding box and point
information is computed from the geometry column.
Parameters
-----------
df : pandas.DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
the name or names of columns containing event variables to be
smoothed
b : string or list of strings
the name or names of columns containing the population
variables to be smoothed
t : Headbanging_Triples instance or list of Headbanging_Triples
list of headbanging triples instances. If not provided, this
is computed from the geometry column of the dataframe.
geom_col: string
the name of the column in the dataframe containing the
geometry information.
inplace : bool
a flag denoting whether to output a copy of `df` with the
relevant smoothed columns appended, or to append the columns
directly to `df` itself.
**kwargs: optional keyword arguments
optional keyword options that are passed directly to the
smoother.
Returns
---------
a new dataframe containing the smoothed Headbanging Median Rates for the
event/population pairs. If done inplace, there is no return value and
`df` is modified in place.
|
f11556:c12:m4
|
@property<EOL><INDENT>def p_sim(self):<DEDENT>
|
return self.p_sim_g<EOL>
|
new name to fit with Moran module
|
f11558:c0:m2
|
def Moran_BV_matrix(variables, w, permutations=<NUM_LIT:0>, varnames=None):
|
try:<EOL><INDENT>import pandas<EOL>if isinstance(variables, pandas.DataFrame):<EOL><INDENT>varnames = pandas.Index.tolist(variables.columns)<EOL>variables_n = []<EOL>for var in varnames:<EOL><INDENT>variables_n.append(variables[str(var)].values)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>variables_n = variables<EOL><DEDENT><DEDENT>except ImportError:<EOL><INDENT>variables_n = variables<EOL><DEDENT>results = _Moran_BV_Matrix_array(variables=variables_n, w=w,<EOL>permutations=permutations,<EOL>varnames=varnames)<EOL>return results<EOL>
|
Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w : W
a spatial weights object
permutations : int
number of permutations
varnames : list, optional if variables is an array
Strings for variable names. Will add an
attribute to `Moran_BV` objects in results needed for plotting
in `splot` or `.plot()`. Default =None.
Note: If variables is a `pandas.DataFrame` varnames
will automatically be generated
Returns
-------
results : dictionary
(i, j) is the key for the pair of variables, values are
the Moran_BV objects.
Examples
--------
open dbf
>>> import libpysal
>>> f = libpysal.io.open(libpysal.examples.get_path("sids2.dbf"))
pull of selected variables from dbf and create numpy arrays for each
>>> varnames = ['SIDR74', 'SIDR79', 'NWR74', 'NWR79']
>>> vars = [np.array(f.by_col[var]) for var in varnames]
create a contiguity matrix from an external gal file
>>> w = libpysal.io.open(libpysal.examples.get_path("sids2.gal")).read()
create an instance of Moran_BV_matrix
>>> from esda.moran import Moran_BV_matrix
>>> res = Moran_BV_matrix(vars, w, varnames = varnames)
check values
>>> round(res[(0, 1)].I,7)
0.1936261
>>> round(res[(3, 0)].I,7)
0.3770138
|
f11560:m0
|
def _Moran_BV_Matrix_array(variables, w, permutations=<NUM_LIT:0>, varnames=None):
|
if varnames is None:<EOL><INDENT>varnames = ['<STR_LIT>'.format(i) for i in range(k)]<EOL><DEDENT>k = len(variables)<EOL>rk = list(range(<NUM_LIT:0>, k - <NUM_LIT:1>))<EOL>results = {}<EOL>for i in rk:<EOL><INDENT>for j in range(i + <NUM_LIT:1>, k):<EOL><INDENT>y1 = variables[i]<EOL>y2 = variables[j]<EOL>results[i, j] = Moran_BV(y1, y2, w, permutations=permutations)<EOL>results[j, i] = Moran_BV(y2, y1, w, permutations=permutations)<EOL>results[i, j].varnames = {'<STR_LIT:x>': varnames[i], '<STR_LIT:y>': varnames[j]}<EOL>results[j, i].varnames = {'<STR_LIT:x>': varnames[j], '<STR_LIT:y>': varnames[i]}<EOL><DEDENT><DEDENT>return results<EOL>
|
Base calculation for MORAN_BV_Matrix
|
f11560:m1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.