signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def setUp(self): | self.random_arr = np.array(<EOL>[<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, ... | Setup test data for continuous data | f11451:c0:m0 |
def setUp(self): | self.arr = np.array(([<NUM_LIT:1>] * <NUM_LIT:20>) + ([<NUM_LIT:2>] * <NUM_LIT:20>) + ([<NUM_LIT:3>] * <NUM_LIT:20>))<EOL>self.ndarr = np.array(([<NUM_LIT:2>, <NUM_LIT:3>] * <NUM_LIT:20>) + ([<NUM_LIT:2>, <NUM_LIT:4>] * <NUM_LIT:20>) + ([<NUM_LIT:3>, <NUM_LIT:4>] * <NUM_LIT>)+ [<NUM_LIT:2>, <NUM_LIT:3>]).reshape(<NUM_L... | Setup test data that contains a surrogate | f11453:c1:m0 |
def setUp(self): | arr = np.array(([<NUM_LIT:1>] * <NUM_LIT:5>) + ([<NUM_LIT:2>] * <NUM_LIT:5>))<EOL>ndarr = np.array(([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>] * <NUM_LIT:5>) + ([<NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:3>] * <NUM_LIT:5>)).reshape(<NUM_LIT:10>, <NUM_LIT:3>)<EOL>self.tree = CHAID.Tree.from_numpy(ndarr, arr, min_child_node_size=<... | Set up for tree generation tests | f11453:c2:m0 |
def setUp(self): | self.arr = np.array(([<NUM_LIT:1>] * <NUM_LIT:15>) + ([<NUM_LIT:2>] * <NUM_LIT:15>))<EOL>self.wt = np.array(([<NUM_LIT:1.0>] * <NUM_LIT:15>) + ([<NUM_LIT>] * <NUM_LIT:15>))<EOL>self.ndarr = np.array(([<NUM_LIT:2>, <NUM_LIT:3>] * <NUM_LIT:20>) + ([<NUM_LIT:2>, <NUM_LIT:5>] * <NUM_LIT:20>) + ([<NUM_LIT:3>, <NUM_LIT:4>] *... | Setup test data for bug fixes | f11453:c4:m0 |
def setUp(self): | self.arr = np.array(([<NUM_LIT:1>] * <NUM_LIT:15>) + ([<NUM_LIT:2>] * <NUM_LIT:15>))<EOL>self.wt = np.array(([<NUM_LIT:1.0>] * <NUM_LIT:15>) + ([<NUM_LIT>] * <NUM_LIT:15>))<EOL>self.ndarr = np.array(([<NUM_LIT:2>, <NUM_LIT:3>] * <NUM_LIT:20>) + ([<NUM_LIT:2>, <NUM_LIT:5>] * <NUM_LIT:20>) + ([<NUM_LIT:3>, <NUM_LIT:4>] *... | Setup test data for bug fixes | f11453:c5:m0 |
def setUp(self): | self.random_arr = np.array(<EOL>[<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, ... | Setup test data for continuous data | f11453:c6:m0 |
def setUp(self): | self.region = np.array([<EOL><NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>,<EOL><NUM_LIT:1>, <NUM_LIT:1>, <... | Setup data for test case | f11453:c7:m0 |
def list_unordered_equal(list_a, list_b): | if islist(list_a) and islist(list_b):<EOL><INDENT>list_a = [str_ndlist(item_a) for item_a in list_a]<EOL>list_b = [str_ndlist(item_b) for item_b in list_b]<EOL>list_a.sort()<EOL>list_b.sort()<EOL>return len(list_a) == len(list_b) and all(list_unordered_equal(*item) for item in zip(list_a, list_b))<EOL><DEDENT>else:<EOL... | Compares the unordered contents of two nd lists | f11454:m2 |
def list_ordered_equal(list_a, list_b): | if islist(list_a) and islist(list_b):<EOL><INDENT>list_a = [item_a for item_a in list_a]<EOL>list_b = [item_b for item_b in list_b]<EOL>return len(list_a) == len(list_b) and all(list_ordered_equal(*item) for item in zip(list_a, list_b))<EOL><DEDENT>else:<EOL><INDENT>return list_a == list_b or (isnan(list_a) and isnan(l... | Compares the unordered contents of two nd lists | f11454:m3 |
def best_cat_brute_force_split(self, ind, dep): | split = Split(None, None, None, None, <NUM_LIT:0>)<EOL>all_dep = np.unique(dep.arr)<EOL>for i, ind_var in enumerate(ind):<EOL><INDENT>ind_var = ind_var.deep_copy()<EOL>unique = np.unique(ind_var.arr)<EOL>freq = {}<EOL>if dep.weights is None:<EOL><INDENT>for col in unique:<EOL><INDENT>counts = np.unique(np.compress(ind_... | determine best categorical variable split using brute force | f11455:m0 |
def setUp(self): | arr = np.array([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:3>])<EOL>self.orig = CHAID.OrdinalColumn(arr)<EOL>self.copy = self.orig.deep_copy()<EOL> | Setup for copy tests | f11456:c0:m0 |
def setUp(self): | arr = np.array([<NUM_LIT:1.0>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>self.col = CHAID.OrdinalColumn(arr)<EOL> | Setup for grouping tests | f11456:c1:m0 |
def setUp(self): | arr = np.array(<EOL>[<NUM_LIT:1.0>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, None],<EOL>dtype=object<EOL>)<EOL>self.col = CHAID.OrdinalColumn(arr)<EOL> | Setup for grouping tests | f11456:c2:m0 |
def setUp(self): | arr = np.array([<NUM_LIT:1.0>, <NUM_LIT>, nan, <NUM_LIT>, <NUM_LIT>, nan, <NUM_LIT>, <NUM_LIT>, nan, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>self.col = CHAID.OrdinalColumn(arr)<EOL> | Setup for grouping tests | f11456:c3:m0 |
def setUp(self): | arr_with_nan = np.array([<NUM_LIT:1.0>, <NUM_LIT>, nan, <NUM_LIT>, <NUM_LIT>, nan, <NUM_LIT>])<EOL>self.col_with_nan = CHAID.OrdinalColumn(arr_with_nan, {<NUM_LIT:1.0>: '<STR_LIT>', <NUM_LIT>: '<STR_LIT>', <NUM_LIT>: '<STR_LIT>'})<EOL> | Setup for tests | f11456:c4:m0 |
def setUp(self): | <EOL>arr = np.array(['<STR_LIT>', '<STR_LIT>'])<EOL>self.orig = CHAID.NominalColumn(arr)<EOL>self.copy = self.orig.deep_copy()<EOL> | Setup for copy tests | f11457:c0:m0 |
def __init__(self, independent_columns, dependent_column, config={}): | self.max_depth = config.get('<STR_LIT>', <NUM_LIT:2>)<EOL>self.min_parent_node_size = config.get('<STR_LIT>', <NUM_LIT:30>)<EOL>self.vectorised_array = independent_columns<EOL>self.data_size = dependent_column.arr.shape[<NUM_LIT:0>]<EOL>self.node_count = <NUM_LIT:0><EOL>self._tree_store = None<EOL>self.observed = depen... | Init method to derive the tree from the columns constructing it
Parameters
----------
independent_columns : array<Column>
an array of CHAID columns
dependent_column : Column
a single CHAID column to use as the dependent variable
config: Dict
{
alpha_merge=0.05,
max_depth=2,
min_pare... | f11458:c0:m0 |
@staticmethod<EOL><INDENT>def from_numpy(ndarr, arr, alpha_merge=<NUM_LIT>, max_depth=<NUM_LIT:2>, min_parent_node_size=<NUM_LIT:30>,<EOL>min_child_node_size=<NUM_LIT:30>, split_titles=None, split_threshold=<NUM_LIT:0>, weights=None,<EOL>variable_types=None, dep_variable_type='<STR_LIT>'):<DEDENT> | vectorised_array = []<EOL>variable_types = variable_types or ['<STR_LIT>'] * ndarr.shape[<NUM_LIT:1>]<EOL>for ind, col_type in enumerate(variable_types):<EOL><INDENT>title = None<EOL>if split_titles is not None: title = split_titles[ind]<EOL>if col_type == '<STR_LIT>':<EOL><INDENT>col = OrdinalColumn(ndarr[:, ind], nam... | Create a CHAID object from numpy
Parameters
----------
ndarr : numpy.ndarray
non-aggregated 2-dimensional array containing
independent variables on the veritcal axis and (usually)
respondent level data on the horizontal axis
arr : numpy.ndarray
1-dimensional array of the dependent variable associated w... | f11458:c0:m1 |
def build_tree(self): | self._tree_store = []<EOL>self.node(np.arange(<NUM_LIT:0>, self.data_size, dtype=np.int), self.vectorised_array, self.observed)<EOL> | Build chaid tree | f11458:c0:m2 |
@staticmethod<EOL><INDENT>def from_pandas_df(df, i_variables, d_variable, alpha_merge=<NUM_LIT>, max_depth=<NUM_LIT:2>,<EOL>min_parent_node_size=<NUM_LIT:30>, min_child_node_size=<NUM_LIT:30>, split_threshold=<NUM_LIT:0>,<EOL>weight=None, dep_variable_type='<STR_LIT>'):<DEDENT> | ind_df = df[list(i_variables.keys())]<EOL>ind_values = ind_df.values<EOL>dep_values = df[d_variable].values<EOL>weights = df[weight] if weight is not None else None<EOL>return Tree.from_numpy(ind_values, dep_values, alpha_merge, max_depth, min_parent_node_size,<EOL>min_child_node_size, list(ind_df.columns.values), spli... | Helper method to pre-process a pandas data frame in order to run CHAID
analysis
Parameters
----------
df : pandas.DataFrame
the dataframe with the dependent and independent variables in which
to slice from
i_variables : dict
dict of instance variable names with their variable types. Supported
variable ... | f11458:c0:m4 |
def node(self, rows, ind, dep, depth=<NUM_LIT:0>, parent=None, parent_decisions=None): | depth += <NUM_LIT:1><EOL>if self.max_depth < depth:<EOL><INDENT>terminal_node = Node(choices=parent_decisions, node_id=self.node_count,<EOL>parent=parent, indices=rows, dep_v=dep)<EOL>self._tree_store.append(terminal_node)<EOL>self.node_count += <NUM_LIT:1><EOL>terminal_node.split.invalid_reason = InvalidSplitReason.MA... | internal method to create a node in the tree | f11458:c0:m5 |
def generate_best_split(self, ind, dep): | return self._stats.best_split(ind, dep)<EOL> | internal method to generate the best split | f11458:c0:m6 |
def to_tree(self): | tree = TreeLibTree()<EOL>for node in self:<EOL><INDENT>tree.create_node(node, node.node_id, parent=node.parent)<EOL><DEDENT>return tree<EOL> | returns a TreeLib tree | f11458:c0:m7 |
def __iter__(self): | return iter(self.tree_store)<EOL> | Function to allow nodes to be iterated over | f11458:c0:m8 |
def get_node(self, node_id): | return self.tree_store[node_id]<EOL> | Returns the node with the given id
Parameters
----------
node_id : integer
Find the node with this ID | f11458:c0:m10 |
def print_tree(self): | self.to_tree().show(line_type='<STR_LIT:ascii>')<EOL> | prints the tree out | f11458:c0:m11 |
def node_predictions(self): | pred = np.zeros(self.data_size)<EOL>for node in self:<EOL><INDENT>if node.is_terminal:<EOL><INDENT>pred[node.indices] = node.node_id<EOL><DEDENT><DEDENT>return pred<EOL> | Determines which rows fall into which node | f11458:c0:m12 |
def model_predictions(self): | if isinstance(self.observed, ContinuousColumn):<EOL><INDENT>return ValueError("<STR_LIT>")<EOL><DEDENT>pred = np.zeros(self.data_size).astype('<STR_LIT:object>')<EOL>for node in self:<EOL><INDENT>if node.is_terminal:<EOL><INDENT>pred[node.indices] = max(node.members, key=node.members.get)<EOL><DEDENT><DEDENT>return pre... | Determines the highest frequency of
categorical dependent variable in the
terminal node where that row fell | f11458:c0:m14 |
def risk(self): | return <NUM_LIT:1> - self.accuracy()<EOL> | Calculates the fraction of risk associated
with the model predictions | f11458:c0:m15 |
def accuracy(self): | sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr])<EOL>return float((self.model_predictions() == sub_observed).sum()) / self.data_size<EOL> | Calculates the accuracy of the tree by comparing
the model predictions to the dataset
(TP + TN) / (TP + TN + FP + FN) == (T / (T + F)) | f11458:c0:m16 |
def main(): | parser = argparse.ArgumentParser(description='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT:file>')<EOL>parser.add_argument('<STR_LIT>', nargs=<NUM_LIT:1>)<EOL>parser.add_argument('<STR_LIT>', type=str)<EOL>var = parser.add_argument_group('<STR_LIT>')<EOL>var.add_argument('<STR_LIT>', nargs='<STR_LIT:*>... | Entry point when module is run from command line | f11460:m0 |
@property<EOL><INDENT>def type(self):<DEDENT> | raise NotImplementedError<EOL> | Returns a string representing the type | f11461:c0:m5 |
def deep_copy(self): | raise NotImplementedError<EOL> | Returns a deep copy | f11461:c0:m6 |
def bell_set(self, collection, ordinal=False): | if len(collection) == <NUM_LIT:1>:<EOL><INDENT>yield [ collection ]<EOL>return<EOL><DEDENT>first = collection[<NUM_LIT:0>]<EOL>for smaller in self.bell_set(collection[<NUM_LIT:1>:]):<EOL><INDENT>for n, subset in enumerate(smaller):<EOL><INDENT>if not ordinal or (ordinal and is_sorted(smaller[:n] + [[ first ] + subset] ... | Calculates the Bell set | f11461:c0:m7 |
def deep_copy(self): | return NominalColumn(self.arr, metadata=self.metadata, name=self.name,<EOL>missing_id=self._missing_id, substitute=False, weights=self.weights)<EOL> | Returns a deep copy. | f11461:c1:m1 |
def substitute_values(self, vect): | try:<EOL><INDENT>unique = np.unique(vect)<EOL><DEDENT>except:<EOL><INDENT>unique = set(vect)<EOL><DEDENT>unique = [<EOL>x for x in unique if not isinstance(x, float) or not isnan(x)<EOL>]<EOL>arr = np.copy(vect)<EOL>for new_id, value in enumerate(unique):<EOL><INDENT>np.place(arr, arr==value, new_id)<EOL>self.metadata[... | Internal method to substitute integers into the vector, and construct
metadata to convert back to the original vector.
np.nan is always given -1, all other objects are given integers in
order of apperence.
Parameters
----------
vect : np.array
the vector in which to substitute values in | f11461:c1:m2 |
@property<EOL><INDENT>def type(self):<DEDENT> | return '<STR_LIT>'<EOL> | Returns a string representing the type | f11461:c1:m9 |
def deep_copy(self): | return OrdinalColumn(self.arr, metadata=self.metadata, name=self.name,<EOL>missing_id=self._missing_id, substitute=True,<EOL>groupings=self._groupings, weights=self.weights)<EOL> | Returns a deep copy. | f11461:c2:m2 |
@property<EOL><INDENT>def type(self):<DEDENT> | return '<STR_LIT>'<EOL> | Returns a string representing the type | f11461:c2:m9 |
def deep_copy(self): | return ContinuousColumn(self.arr, metadata=self.metadata, missing_id=self._missing_id, weights=self.weights)<EOL> | Returns a deep copy. | f11461:c3:m1 |
@property<EOL><INDENT>def type(self):<DEDENT> | return '<STR_LIT>'<EOL> | Returns a string representing the type | f11461:c3:m4 |
def chisquare(n_ij, weighted): | if weighted:<EOL><INDENT>m_ij = n_ij / n_ij<EOL>nan_mask = np.isnan(m_ij)<EOL>m_ij[nan_mask] = <NUM_LIT> <EOL>w_ij = m_ij<EOL>n_ij_col_sum = n_ij.sum(axis=<NUM_LIT:1>)<EOL>n_ij_row_sum = n_ij.sum(axis=<NUM_LIT:0>)<EOL>alpha, beta, eps = (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>while eps > <NUM_LIT>:<EOL><INDENT>alp... | Calculates the chisquare for a matrix of ind_v x dep_v
for the unweighted and SPSS weighted case | f11462:m0 |
def best_split(self, ind, dep): | if isinstance(dep, ContinuousColumn):<EOL><INDENT>return self.best_con_split(ind, dep)<EOL><DEDENT>else:<EOL><INDENT>return self.best_cat_heuristic_split(ind, dep)<EOL><DEDENT> | determine which splitting function to apply | f11462:c0:m1 |
def best_cat_heuristic_split(self, ind, dep): | split = Split(None, None, None, None, <NUM_LIT:0>)<EOL>min_child_node_size = self.min_child_node_size<EOL>all_dep = np.unique(dep.arr)<EOL>if len(all_dep) == <NUM_LIT:1>:<EOL><INDENT>split.invalid_reason = InvalidSplitReason.PURE_NODE<EOL>return split<EOL><DEDENT>elif len(dep.arr) < min_child_node_size and dep.weights ... | determine best categorical variable split using heuristic methods | f11462:c0:m2 |
def best_con_split(self, ind, dep): | split = Split(None, None, None, None, <NUM_LIT:0>)<EOL>is_normal = stats.normaltest(self.dep_population)[<NUM_LIT:1>] > <NUM_LIT><EOL>sig_test = stats.bartlett if is_normal else stats.levene<EOL>response_set = dep.arr<EOL>if dep.weights is not None:<EOL><INDENT>response_set = dep.arr * dep.weights<EOL><DEDENT>for i, in... | determine best continuous variable split | f11462:c0:m3 |
def sub_split_values(self, sub): | for i, arr in enumerate(self.splits):<EOL><INDENT>self.split_map[i] = [sub.get(x, x) for x in arr]<EOL><DEDENT>for split in self.surrogates:<EOL><INDENT>split.sub_split_values(sub)<EOL><DEDENT> | Substitutes the splits with other values into the split_map | f11464:c0:m1 |
def name_columns(self, sub): | if self.column_id is not None and len(sub) > self.column_id:<EOL><INDENT>self.split_name = sub[self.column_id]<EOL><DEDENT>for split in self.surrogates:<EOL><INDENT>split.name_columns(sub)<EOL><DEDENT> | Substitutes the split column index with a human readable string | f11464:c0:m2 |
def get_version(): | version_regex = re.compile(<EOL>'<STR_LIT>'<EOL>)<EOL>here = path.abspath(path.dirname(__file__))<EOL>init_location = path.join(here, "<STR_LIT>")<EOL>with open(init_location) as init_file:<EOL><INDENT>for line in init_file:<EOL><INDENT>match = version_regex.search(line)<EOL><DEDENT><DEDENT>if not match:<EOL><INDENT>ra... | Read version from __init__.py | f11468:m0 |
def dictproduct(d): | for p in itertools.product(*d.values()):<EOL><INDENT>yield dict(zip(d.keys(), p))<EOL><DEDENT> | enhance itertools product to process values of dicts
example:
d = {'a':[1,2],'b':[3,4]}
then list(dictproduct(d)) ==
[{'a':1,'b':3}, {'a':1,'b':4}, {'a':2,'b':3}, {'a':2,'b':4}] | f11473:m0 |
def __init__(self, A, b,<EOL>M=None,<EOL>Minv=None,<EOL>Ml=None,<EOL>Mr=None,<EOL>ip_B=None,<EOL>normal=None,<EOL>self_adjoint=False,<EOL>positive_definite=False,<EOL>exact_solution=None<EOL>): | self.N = N = len(b)<EOL>'''<STR_LIT>'''<EOL>shape = (N, N)<EOL>self.A = utils.get_linearoperator(shape, A)<EOL>self.M = utils.get_linearoperator(shape, M)<EOL>self.Minv = utils.get_linearoperator(shape, Minv)<EOL>self.Ml = utils.get_linearoperator(shape, Ml)<EOL>self.Mr = utils.get_linearoperator(shape, Mr)<EOL>self.Ml... | r'''Representation of a (preconditioned) linear system.
Represents a linear system
.. math::
Ax=b
or a preconditioned linear system
.. math::
M M_l A M_r y = M M_l b
\quad\text{with}\quad x=M_r y.
:param A: a linear operator on :math:`\mathbb{... | f11474:c0:m0 |
def get_residual(self, z, compute_norm=False): | if z is None:<EOL><INDENT>if compute_norm:<EOL><INDENT>return self.MMlb, self.Mlb, self.MMlb_norm<EOL><DEDENT>return self.MMlb, self.Mlb<EOL><DEDENT>r = self.b - self.A*z<EOL>Mlr = self.Ml*r<EOL>MMlr = self.M*Mlr<EOL>if compute_norm:<EOL><INDENT>return MMlr, Mlr, utils.norm(Mlr, MMlr, ip_B=self.ip_B)<EOL><DEDENT>return... | r'''Compute residual.
For a given :math:`z\in\mathbb{C}^N`, the residual
.. math::
r = M M_l ( b - A z )
is computed. If ``compute_norm == True``, then also the absolute
residual norm
.. math::
\| M M_l (b-Az)\|_{M^{-1}}
is computed.
:p... | f11474:c0:m1 |
def get_ip_Minv_B(self): | if not isinstance(self.M, utils.IdentityLinearOperator):<EOL><INDENT>if isinstance(self.Minv, utils.IdentityLinearOperator):<EOL><INDENT>raise utils.ArgumentError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if isinstance(self.ip_B, utils.LinearOperator):<EOL><INDENT>return self.Minv*self.ip_B<EOL><DEDENT>else:<EOL><I... | Returns the inner product that is implicitly used with the positive
definite preconditioner ``M``. | f11474:c0:m2 |
def __init__(self, linear_system,<EOL>x0=None,<EOL>tol=<NUM_LIT>,<EOL>maxiter=None,<EOL>explicit_residual=False,<EOL>store_arnoldi=False,<EOL>dtype=None<EOL>): | <EOL>if not isinstance(linear_system, LinearSystem):<EOL><INDENT>raise utils.ArgumentError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self.linear_system = linear_system<EOL>N = linear_system.N<EOL>self.maxiter = N if maxiter is None else maxiter<EOL>self.flat_vecs, (self.x0,) = utils.shape_vecs(x0)<EOL>self.explicit_resi... | r'''Init standard attributes and perform checks.
All Krylov subspace solvers in this module are applied to a
:py:class:`LinearSystem`. The specific methods may impose further
restrictions on the operators
:param linear_system: a :py:class:`LinearSystem`.
:param x0: (optional) ... | f11474:c3:m0 |
def _get_initial_guess(self, x0): | return x0<EOL> | Get initial guess.
Can be overridden by derived classes in order to preprocess the
initial guess. | f11474:c3:m1 |
def _get_initial_residual(self, x0): | return self.linear_system.get_residual(x0, compute_norm=True)<EOL> | Compute the residual and its norm.
See :py:meth:`krypy.linsys.LinearSystem.get_residual` for return
values. | f11474:c3:m2 |
def _get_xk(self, yk): | if yk is not None:<EOL><INDENT>return self.x0 + self.linear_system.Mr * yk<EOL><DEDENT>return self.x0<EOL> | Compute approximate solution from initial guess and approximate
solution of the preconditioned linear system. | f11474:c3:m3 |
def _finalize_iteration(self, yk, resnorm): | self.xk = None<EOL>if self.linear_system.exact_solution is not None:<EOL><INDENT>self.xk = self._get_xk(yk)<EOL>self.errnorms.append(utils.norm(<EOL>self.linear_system.exact_solution - self.xk,<EOL>ip_B=self.linear_system.ip_B))<EOL><DEDENT>rkn = None<EOL>if self.explicit_residual orresnorm/self.linear_system.MMlb_norm... | Compute solution, error norm and residual norm if required.
:return: the residual norm or ``None``. | f11474:c3:m4 |
@staticmethod<EOL><INDENT>def operations(nsteps):<DEDENT> | raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL> | Returns the number of operations needed for nsteps of the solver.
:param nsteps: number of steps.
:returns: a dictionary with the same keys as the timings parameter.
Each value is the number of operations of the corresponding type for
``nsteps`` iterations of the method. | f11474:c3:m6 |
def _solve(self): | raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL> | Abstract method that solves the linear system. | f11474:c3:m7 |
def __init__(self, linear_system, **kwargs): | if not linear_system.self_adjoint ornot linear_system.positive_definite:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>super(Cg, self).__init__(linear_system, **kwargs)<EOL> | All parameters of :py:class:`_KrylovSolver` are valid in this solver.
Note the restrictions on ``M``, ``Ml``, ``A``, ``Mr`` and ``ip_B``
above. | f11474:c4:m0 |
@staticmethod<EOL><INDENT>def operations(nsteps):<DEDENT> | return {'<STR_LIT:A>': <NUM_LIT:1> + nsteps,<EOL>'<STR_LIT:M>': <NUM_LIT:2> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:2> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:1> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:2> + <NUM_LIT:2>*nsteps,<EOL>'<STR_LIT>': <NUM_LIT:2> + <NUM_LIT:2>*nsteps<EOL>}<EOL> | Returns the number of operations needed for nsteps of CG | f11474:c4:m3 |
def __init__(self, linear_system, ortho='<STR_LIT>', **kwargs): | if not linear_system.self_adjoint:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self.ortho = ortho<EOL>super(Minres, self).__init__(linear_system, **kwargs)<EOL> | All parameters of :py:class:`_KrylovSolver` are valid in this solver.
Note the restrictions on ``M``, ``Ml``, ``A``, ``Mr`` and ``ip_B``
above. | f11474:c5:m0 |
@staticmethod<EOL><INDENT>def operations(nsteps):<DEDENT> | return {'<STR_LIT:A>': <NUM_LIT:1> + nsteps,<EOL>'<STR_LIT:M>': <NUM_LIT:2> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:2> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:1> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:2> + <NUM_LIT:2>*nsteps,<EOL>'<STR_LIT>': <NUM_LIT:4> + <NUM_LIT:8>*nsteps<EOL>}<EOL> | Returns the number of operations needed for nsteps of MINRES | f11474:c5:m3 |
def __init__(self, linear_system, ortho='<STR_LIT>', **kwargs): | self.ortho = ortho<EOL>super(Gmres, self).__init__(linear_system, **kwargs)<EOL> | All parameters of :py:class:`_KrylovSolver` are valid in this solver. | f11474:c6:m0 |
@staticmethod<EOL><INDENT>def operations(nsteps):<DEDENT> | return {'<STR_LIT:A>': <NUM_LIT:1> + nsteps,<EOL>'<STR_LIT:M>': <NUM_LIT:2> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:2> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:1> + nsteps,<EOL>'<STR_LIT>': <NUM_LIT:2> + nsteps + nsteps*(nsteps+<NUM_LIT:1>)/<NUM_LIT:2>,<EOL>'<STR_LIT>': <NUM_LIT:4> + <NUM_LIT:2>*nsteps + nsteps*(nsteps+<NUM_LIT... | Returns the number of operations needed for nsteps of GMRES | f11474:c6:m4 |
def __init__(self, Solver, linear_system, max_restarts=<NUM_LIT:0>, **kwargs): | <EOL>self.xk = None<EOL>kwargs = dict(kwargs)<EOL>self.resnorms = [numpy.Inf]<EOL>if linear_system.exact_solution is not None:<EOL><INDENT>self.errnorms = [numpy.Inf]<EOL><DEDENT>restart = <NUM_LIT:0><EOL>while restart == <NUM_LIT:0> orself.resnorms[-<NUM_LIT:1>] > tol and restart <= max_restarts:<EOL><INDENT>try:<EOL>... | :param max_restarts: the maximum number of restarts. The maximum
number of iterations is ``(max_restarts+1)*maxiter``. | f11474:c7:m0 |
def find_common_dtype(*args): | dtypes = []<EOL>for arg in args:<EOL><INDENT>if type(arg) is numpy.ndarray orisspmatrix(arg) orisinstance(arg, LinearOperator):<EOL><INDENT>if hasattr(arg, '<STR_LIT>'):<EOL><INDENT>dtypes.append(arg.dtype)<EOL><DEDENT>else:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>% arg.__repr__)<EOL><DEDENT><DEDENT><DEDENT>return nu... | Returns common dtype of numpy and scipy objects.
Recognizes ndarray, spmatrix and LinearOperator. All other objects are
ignored (most notably None). | f11476:m0 |
def shape_vec(x): | return numpy.reshape(x, (x.shape[<NUM_LIT:0>], <NUM_LIT:1>))<EOL> | Take a (n,) ndarray and return it as (n,1) ndarray. | f11476:m1 |
def shape_vecs(*args): | ret_args = []<EOL>flat_vecs = True<EOL>for arg in args:<EOL><INDENT>if type(arg) is numpy.ndarray:<EOL><INDENT>if len(arg.shape) == <NUM_LIT:1>:<EOL><INDENT>arg = shape_vec(arg)<EOL><DEDENT>else:<EOL><INDENT>flat_vecs = False<EOL><DEDENT><DEDENT>ret_args.append(arg)<EOL><DEDENT>return flat_vecs, ret_args<EOL> | Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``.
Recognizes ndarrays and ignores all others. | f11476:m2 |
def ip_euclid(X, Y): | return numpy.dot(X.T.conj(), Y)<EOL> | Euclidean inner product.
numpy.vdot only works for vectors and numpy.dot does not use the conjugate
transpose.
:param X: numpy array with ``shape==(N,m)``
:param Y: numpy array with ``shape==(N,n)``
:return: numpy array :math:`X^* Y` with ``shape==(m,n)``. | f11476:m3 |
def inner(X, Y, ip_B=None): | if ip_B is None or isinstance(ip_B, IdentityLinearOperator):<EOL><INDENT>return numpy.dot(X.T.conj(), Y)<EOL><DEDENT>(N, m) = X.shape<EOL>(_, n) = Y.shape<EOL>try:<EOL><INDENT>B = get_linearoperator((N, N), ip_B)<EOL><DEDENT>except TypeError:<EOL><INDENT>return ip_B(X, Y)<EOL><DEDENT>if m > n:<EOL><INDENT>return numpy.... | Euclidean and non-Euclidean inner product.
numpy.vdot only works for vectors and numpy.dot does not use the conjugate
transpose.
:param X: numpy array with ``shape==(N,m)``
:param Y: numpy array with ``shape==(N,n)``
:param ip_B: (optional) May be one of the following
* ``None``: Euclidea... | f11476:m4 |
def norm_squared(x, Mx=None, inner_product=ip_euclid): | assert(len(x.shape) == <NUM_LIT:2>)<EOL>if Mx is None:<EOL><INDENT>rho = inner_product(x, x)<EOL><DEDENT>else:<EOL><INDENT>assert(len(Mx.shape) == <NUM_LIT:2>)<EOL>rho = inner_product(x, Mx)<EOL><DEDENT>if rho.shape == (<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>if abs(rho[<NUM_LIT:0>, <NUM_LIT:0>].imag) > abs(rho[<NUM_LIT... | Compute the norm^2 w.r.t. to a given scalar product. | f11476:m5 |
def norm(x, y=None, ip_B=None): | <EOL>if y is None and (ip_B is None<EOL>or isinstance(ip_B, IdentityLinearOperator)):<EOL><INDENT>return numpy.linalg.norm(x, <NUM_LIT:2>)<EOL><DEDENT>if y is None:<EOL><INDENT>y = x<EOL><DEDENT>ip = inner(x, y, ip_B=ip_B)<EOL>nrm_diag = numpy.linalg.norm(numpy.diag(ip), <NUM_LIT:2>)<EOL>nrm_diag_imag = numpy.linalg.no... | r'''Compute norm (Euclidean and non-Euclidean).
:param x: a 2-dimensional ``numpy.array``.
:param y: a 2-dimensional ``numpy.array``.
:param ip_B: see :py:meth:`inner`.
Compute :math:`\sqrt{\langle x,y\rangle}` where the inner product is
defined via ``ip_B``. | f11476:m6 |
def get_linearoperator(shape, A, timer=None): | ret = None<EOL>import scipy.sparse.linalg as scipylinalg<EOL>if isinstance(A, LinearOperator):<EOL><INDENT>ret = A<EOL><DEDENT>elif A is None:<EOL><INDENT>ret = IdentityLinearOperator(shape)<EOL><DEDENT>elif isinstance(A, numpy.ndarray) or isspmatrix(A):<EOL><INDENT>ret = MatrixLinearOperator(A)<EOL><DEDENT>elif isinst... | Enhances aslinearoperator if A is None. | f11476:m7 |
def orthonormality(V, ip_B=None): | return norm(numpy.eye(V.shape[<NUM_LIT:1>]) - inner(V, V, ip_B=ip_B))<EOL> | Measure orthonormality of given basis.
:param V: a matrix :math:`V=[v_1,\ldots,v_n]` with ``shape==(N,n)``.
:param ip_B: (optional) the inner product to use, see :py:meth:`inner`.
:return: :math:`\\| I_n - \\langle V,V \\rangle \\|_2`. | f11476:m9 |
def arnoldi_res(A, V, H, ip_B=None): | N = V.shape[<NUM_LIT:0>]<EOL>invariant = H.shape[<NUM_LIT:0>] == H.shape[<NUM_LIT:1>]<EOL>A = get_linearoperator((N, N), A)<EOL>if invariant:<EOL><INDENT>res = A*V - numpy.dot(V, H)<EOL><DEDENT>else:<EOL><INDENT>res = A*V[:, :-<NUM_LIT:1>] - numpy.dot(V, H)<EOL><DEDENT>return norm(res, ip_B=ip_B)<EOL> | Measure Arnoldi residual.
:param A: a linear operator that can be used with scipy's aslinearoperator
with ``shape==(N,N)``.
:param V: Arnoldi basis matrix with ``shape==(N,n)``.
:param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with
``shape==(n,n-1)`` or :math:`H_n` with ``shape=... | f11476:m10 |
def qr(X, ip_B=None, reorthos=<NUM_LIT:1>): | if ip_B is None and X.shape[<NUM_LIT:1>] > <NUM_LIT:0>:<EOL><INDENT>return scipy.linalg.qr(X, mode='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>(N, k) = X.shape<EOL>Q = X.copy()<EOL>R = numpy.zeros((k, k), dtype=X.dtype)<EOL>for i in range(k):<EOL><INDENT>for reortho in range(reorthos+<NUM_LIT:1>):<EOL><INDENT>for j in r... | QR factorization with customizable inner product.
:param X: array with ``shape==(N,k)``
:param ip_B: (optional) inner product, see :py:meth:`inner`.
:param reorthos: (optional) numer of reorthogonalizations. Defaults to
1 (i.e. 2 runs of modified Gram-Schmidt) which should be enough in most
cas... | f11476:m11 |
def angles(F, G, ip_B=None, compute_vectors=False): | <EOL>reverse = False<EOL>if F.shape[<NUM_LIT:1>] < G.shape[<NUM_LIT:1>]:<EOL><INDENT>reverse = True<EOL>F, G = G, F<EOL><DEDENT>QF, _ = qr(F, ip_B=ip_B)<EOL>QG, _ = qr(G, ip_B=ip_B)<EOL>if G.shape[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>theta = numpy.ones(F.shape[<NUM_LIT:1>])*numpy.pi/<NUM_LIT:2><EOL>U = QF<EOL>V = Q... | Principal angles between two subspaces.
This algorithm is based on algorithm 6.2 in `Knyazev, Argentati. Principal
angles between subspaces in an A-based scalar product: algorithms and
perturbation estimates. 2002.` This algorithm can also handle small angles
(in contrast to the naive cosine-based svd ... | f11476:m12 |
def hegedus(A, b, x0, M=None, Ml=None, ip_B=None): | N = len(b)<EOL>shape = (N, N)<EOL>A = get_linearoperator(shape, A)<EOL>M = get_linearoperator(shape, M)<EOL>Ml = get_linearoperator(shape, Ml)<EOL>MlAx0 = Ml*(A*x0)<EOL>z = M*MlAx0<EOL>znorm2 = inner(z, MlAx0, ip_B=ip_B)<EOL>if znorm2 <= <NUM_LIT>:<EOL><INDENT>return numpy.zeros((N, <NUM_LIT:1>))<EOL><DEDENT>gamma = in... | Rescale initial guess appropriately (Hegedüs trick).
The Hegedüs trick rescales the initial guess to :math:`\\gamma_{\\min} x_0`
such that
.. math ::
\\|r_0\\|_{M^{-1}}
= \\| M M_l (b - A \\gamma_{\\min} x_0) \\|_{M^{-1}}
= \\min_{\\gamma\\in\\mathbb{C}}
\\| M M_l (b - A \\gamma... | f11476:m13 |
def arnoldi_projected(H, P, k, ortho='<STR_LIT>'): | n = H.shape[<NUM_LIT:1>]<EOL>dtype = find_common_dtype(H, P)<EOL>invariant = H.shape[<NUM_LIT:0>] == n<EOL>hlast = <NUM_LIT:0> if invariant else H[-<NUM_LIT:1>, -<NUM_LIT:1>]<EOL>H = get_linearoperator((n, n), H if invariant else H[:-<NUM_LIT:1>, :])<EOL>P = get_linearoperator((n, n), P)<EOL>v = P * numpy.eye(n, <NUM_L... | Compute (perturbed) Arnoldi relation for projected operator.
Assume that you have computed an Arnoldi relation
.. math ::
A V_n = V_{n+1} \\underline{H}_n
where :math:`V_{n+1}\\in\\mathbb{C}^{N,n+1}` has orthogonal columns
(with respect to an inner product :math:`\\langle\\cdot,\\cdot\\rangl... | f11476:m15 |
def ritz(H, V=None, hermitian=False, type='<STR_LIT>'): | <EOL>n = H.shape[<NUM_LIT:1>]<EOL>if V is not None and V.shape[<NUM_LIT:1>] != H.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>if not H.shape[<NUM_LIT:0>] in [n, n+<NUM_LIT:1>]:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>symmres = numpy.linalg.norm(H[:n, :] - H[:n, :].T.conj... | Compute several kinds of Ritz pairs from an Arnoldi/Lanczos relation.
This function computes Ritz, harmonic Ritz or improved harmonic Ritz values
and vectors with respect to the Krylov subspace :math:`K_n(A,v)` from the
extended Hessenberg matrix :math:`\\underline{H}_n` generated with n
iterations the... | f11476:m16 |
def strakos(n, l_min=<NUM_LIT:0.1>, l_max=<NUM_LIT:100>, rho=<NUM_LIT>): | d = [l_min + (i-<NUM_LIT:1>)*<NUM_LIT:1.>/(n-<NUM_LIT:1>)*(l_max-l_min)*(rho**(n-i))<EOL>for i in range(<NUM_LIT:1>, n+<NUM_LIT:1>)]<EOL>return numpy.diag(d)<EOL> | Return the Strakoš matrix.
See [Str92]_. | f11476:m18 |
def gap(lamda, sigma, mode='<STR_LIT>'): | <EOL>if numpy.isscalar(lamda):<EOL><INDENT>lamda = [lamda]<EOL><DEDENT>lamda = numpy.array(lamda)<EOL>if numpy.isscalar(sigma):<EOL><INDENT>sigma = [sigma]<EOL><DEDENT>sigma = numpy.array(sigma)<EOL>if not numpy.isreal(lamda).all() or not numpy.isreal(sigma).all():<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDE... | Compute spectral gap.
Useful for eigenvalue/eigenvector bounds. Computes the gap
:math:`\delta\geq 0` between two sets of real numbers ``lamda`` and
``sigma``. The gap can be computed in several ways and may not exist, see
the ``mode`` parameter.
:param lamda: a non-empty set
:math:`\Lambda=... | f11476:m19 |
def bound_perturbed_gmres(pseudo, p, epsilon, deltas): | if not numpy.all(numpy.array(deltas) > epsilon):<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>bound = []<EOL>for delta in deltas:<EOL><INDENT>paths = pseudo.contour_paths(delta)<EOL>vertices = paths.vertices()<EOL>supremum = numpy.max(numpy.abs(p(vertices)))<EOL>bound.append(epsilon/(delta-epsilon)<EOL>* pa... | Compute GMRES perturbation bound based on pseudospectrum
Computes the GMRES bound from [SifEM13]_. | f11476:m20 |
def get_residual_norms(H, self_adjoint=False): | H = H.copy()<EOL>n_, n = H.shape<EOL>y = numpy.eye(n_, <NUM_LIT:1>, dtype=H.dtype)<EOL>resnorms = [<NUM_LIT:1.>]<EOL>for i in range(n_-<NUM_LIT:1>):<EOL><INDENT>G = Givens(H[i:i+<NUM_LIT:2>, [i]])<EOL>if self_adjoint:<EOL><INDENT>H[i:i+<NUM_LIT:2>, i:i+<NUM_LIT:3>] = G.apply(H[i:i+<NUM_LIT:2>, i:i+<NUM_LIT:3>])<EOL><DE... | Compute relative residual norms from Hessenberg matrix.
It is assumed that the initial guess is chosen as zero. | f11476:m21 |
def __init__(self, x): | <EOL>if len(x.shape) != <NUM_LIT:2> or x.shape[<NUM_LIT:1>] != <NUM_LIT:1>:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>v = x.copy()<EOL>gamma = numpy.asscalar(v[<NUM_LIT:0>])<EOL>v[<NUM_LIT:0>] = <NUM_LIT:1><EOL>if x.shape[<NUM_LIT:0>] == <NUM_LIT:1>:<EOL><INDENT>sigma = <NUM_LIT:0><EOL>xnorm = numpy.abs(... | Compute Householder transformation for given vector.
Initialize Householder transformation :math:`H` such that
:math:`Hx = \\alpha \|x\|_2 e_1` with :math:`|\\alpha|=1`
The algorithm is a combination of Algorithm 5.1.1 on page 236
and the treatment of the complex case in Section 5.1.13... | f11476:c6:m0 |
def apply(self, x): | <EOL>if len(x.shape) != <NUM_LIT:2>:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>if self.beta == <NUM_LIT:0>:<EOL><INDENT>return x<EOL><DEDENT>return x - self.beta * self.v * numpy.dot(self.v.T.conj(), x)<EOL> | Apply Householder transformation to vector x.
Applies the Householder transformation efficiently to the given vector. | f11476:c6:m1 |
def matrix(self): | n = self.v.shape[<NUM_LIT:0>]<EOL>return numpy.eye(n, n) - self.beta * numpy.dot(self.v, self.v.T.conj())<EOL> | Build matrix representation of Householder transformation.
Builds the matrix representation
:math:`H = I - \\beta vv^*`.
**Use with care!** This routine may be helpful for testing purposes but
should not be used in production codes for high dimensions since
the resulting matrix... | f11476:c6:m2 |
def __init__(self, x): | <EOL>if x.shape != (<NUM_LIT:2>, <NUM_LIT:1>):<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>a = numpy.asscalar(x[<NUM_LIT:0>])<EOL>b = numpy.asscalar(x[<NUM_LIT:1>])<EOL>if numpy.isreal(x).all():<EOL><INDENT>a = numpy.real(a)<EOL>b = numpy.real(b)<EOL>c, s = blas.drotg(a, b)<EOL><DEDENT>else:<EOL><INDENT>c,... | Compute Givens rotation for provided vector x.
Computes Givens rotation
:math:`G=\\begin{bmatrix}c&s\\\\-\\overline{s}&c\\end{bmatrix}`
such that
:math:`Gx=\\begin{bmatrix}r\\\\0\\end{bmatrix}`. | f11476:c7:m0 |
def apply(self, x): | return numpy.dot(self.G, x)<EOL> | Apply Givens rotation to vector x. | f11476:c7:m1 |
def __init__(self, X,<EOL>Y=None,<EOL>ip_B=None,<EOL>orthogonalize=True,<EOL>iterations=<NUM_LIT:2><EOL>): | <EOL>self.ip_B = ip_B<EOL>if iterations < <NUM_LIT:1>:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>self.orthogonalize = orthogonalize<EOL>self.iterations = iterations<EOL>Y = X if Y is None else Y <EOL>if len(X.shape) != <NUM_LIT:2>:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>if X.shape != ... | Generic projection.
This class can represent any projection (orthogonal and oblique)
on a N-dimensional Hilbert space. A projection is a linear operator
:math:`P` with :math:`P^2=P`. A projection is uniquely defined by its
range :math:`\\mathcal{V}:=\\operatorname{range}(P)` and its ker... | f11476:c8:m0 |
def _apply(self, a, return_Ya=False): | <EOL>if self.V.shape[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>Pa = numpy.zeros(a.shape)<EOL>if return_Ya:<EOL><INDENT>return Pa, numpy.zeros((<NUM_LIT:0>, a.shape[<NUM_LIT:1>]))<EOL><DEDENT>return Pa<EOL><DEDENT>c = inner(self.W, a, ip_B=self.ip_B)<EOL>if return_Ya:<EOL><INDENT>Ya = c.copy()<EOL>if self.WR is not None:... | r'''Single application of the projection.
:param a: array with ``a.shape==(N,m)``.
:param return_inner: (optional) should the inner product
:math:`\langle Y,a\rangle` be returned?
:return:
* :math:`P_{\mathcal{X},\mathcal{Y}^\perp} a =
X \langle Y,X\rangle^{-1} ... | f11476:c8:m1 |
def apply(self, a, return_Ya=False): | <EOL>if self.V.shape[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>Pa = numpy.zeros(a.shape)<EOL>if return_Ya:<EOL><INDENT>return Pa, numpy.zeros((<NUM_LIT:0>, a.shape[<NUM_LIT:1>]))<EOL><DEDENT>return Pa<EOL><DEDENT>if return_Ya:<EOL><INDENT>x, Ya = self._apply(a, return_Ya=return_Ya)<EOL><DEDENT>else:<EOL><INDENT>x = self... | r"""Apply the projection to an array.
The computation is carried out without explicitly forming the
matrix corresponding to the projection (which would be an array with
``shape==(N,N)``).
See also :py:meth:`_apply`. | f11476:c8:m3 |
def apply_complement(self, a, return_Ya=False): | <EOL>if self.V.shape[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>if return_Ya:<EOL><INDENT>return a.copy(), numpy.zeros((<NUM_LIT:0>, a.shape[<NUM_LIT:1>]))<EOL><DEDENT>return a.copy()<EOL><DEDENT>if return_Ya:<EOL><INDENT>x, Ya = self._apply(a, return_Ya=True)<EOL><DEDENT>else:<EOL><INDENT>x = self._apply(a)<EOL><DEDENT>... | Apply the complementary projection to an array.
:param z: array with ``shape==(N,m)``.
:return: :math:`P_{\\mathcal{Y}^\\perp,\\mathcal{X}}z =
z - P_{\\mathcal{X},\\mathcal{Y}^\\perp} z`. | f11476:c8:m5 |
def operator(self): | <EOL>if self.V.shape[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>N = self.V.shape[<NUM_LIT:0>]<EOL>return ZeroLinearOperator((N, N))<EOL><DEDENT>return self._get_operator(self.apply, self.apply_adj)<EOL> | Get a ``LinearOperator`` corresponding to apply().
:return: a LinearOperator that calls apply(). | f11476:c8:m8 |
def operator_complement(self): | <EOL>if self.V.shape[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>N = self.V.shape[<NUM_LIT:0>]<EOL>return IdentityLinearOperator((N, N))<EOL><DEDENT>return self._get_operator(self.apply_complement,<EOL>self.apply_complement_adj)<EOL> | Get a ``LinearOperator`` corresponding to apply_complement().
:return: a LinearOperator that calls apply_complement(). | f11476:c8:m9 |
def matrix(self): | return self.apply(numpy.eye(self.V.shape[<NUM_LIT:0>]))<EOL> | Builds matrix representation of projection.
Builds the matrix representation
:math:`P = X \\langle Y,X\\rangle^{-1} \\langle Y, I_N\\rangle`.
**Use with care!** This routine may be helpful for testing purposes but
should not be used in production codes for high dimensions since
... | f11476:c8:m10 |
def __init__(self, A, v,<EOL>maxiter=None,<EOL>ortho='<STR_LIT>',<EOL>M=None,<EOL>Mv=None,<EOL>Mv_norm=None,<EOL>ip_B=None<EOL>): | N = v.shape[<NUM_LIT:0>]<EOL>self.A = get_linearoperator((N, N), A)<EOL>self.maxiter = N if maxiter is None else maxiter<EOL>self.ortho = ortho<EOL>self.M = get_linearoperator((N, N), M)<EOL>if isinstance(self.M, IdentityLinearOperator):<EOL><INDENT>self.M = None<EOL><DEDENT>self.ip_B = ip_B<EOL>self.dtype = find_commo... | Arnoldi algorithm.
Computes V and H such that :math:`AV_n=V_{n+1}\\underline{H}_n`. If
the Krylov subspace becomes A-invariant then V and H are truncated such
that :math:`AV_n = V_n H_n`.
:param A: a linear operator that can be used with scipy's
aslinearoperator with ``shape... | f11476:c9:m0 |
def advance(self): | if self.iter >= self.maxiter:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>if self.invariant:<EOL><INDENT>raise ArgumentError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>N = self.V.shape[<NUM_LIT:0>]<EOL>k = self.iter<EOL>Av = self.A * self.V[:, [k]]<EOL>if self.ortho == '<STR_LIT>':<EOL><INDENT>for j in range... | Carry out one iteration of Arnoldi. | f11476:c9:m1 |
def get(self, key): | if key in self and len(self[key]) > <NUM_LIT:0>:<EOL><INDENT>return min(self[key])<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT> | Return timings for `key`. Returns 0 if not present. | f11476:c11:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.