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>, <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>, <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>, <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>, <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>, <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>)<EOL>self.normal_arr = np.array([<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT> , <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT> , <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT>]<EOL>)<EOL>self.wt = np.array(([<NUM_LIT:1.0>] * <NUM_LIT>) + ([<NUM_LIT>] * <NUM_LIT>))<EOL>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>] * <NUM_LIT>) + [<NUM_LIT:2>, <NUM_LIT:3>] + [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:5>] * <NUM_LIT> + [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>] * <NUM_LIT>).reshape(<NUM_LIT>, <NUM_LIT:4>)<EOL>self.ndarr = [CHAID.NominalColumn(ndarr[:, i]) for i in range(ndarr.shape[<NUM_LIT:1>])]<EOL>self.stats_random_data = CHAID.Stats(<NUM_LIT:0.5>, <NUM_LIT:10>, <NUM_LIT>, self.random_arr)<EOL>self.stats_normal_data = CHAID.Stats(<NUM_LIT:0.5>, <NUM_LIT:10>, <NUM_LIT>, self.normal_arr)<EOL>
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_LIT>, <NUM_LIT:2>)<EOL>
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=<NUM_LIT:0>)<EOL>
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>] * <NUM_LIT>) + [<NUM_LIT:2>, <NUM_LIT:3>]).reshape(<NUM_LIT:30>, <NUM_LIT:4>)<EOL>self.string_ndarr = np.array(([u'<STR_LIT>', u'<STR_LIT>'] * <NUM_LIT:20>) + ([u'<STR_LIT>', u'<STR_LIT>'] * <NUM_LIT:20>) + ([u'<STR_LIT>', u'<STR_LIT>'] * <NUM_LIT>) + [u'<STR_LIT>', u'<STR_LIT>']).reshape(<NUM_LIT:30>, <NUM_LIT:4>)<EOL>
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>] * <NUM_LIT>) + [<NUM_LIT:2>, <NUM_LIT:3>]).reshape(<NUM_LIT:30>, <NUM_LIT:4>)<EOL>
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>, <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>, <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>, <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>, <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>, <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>)<EOL>self.normal_arr = np.array([<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT> , <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT> , <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT> ,<EOL><NUM_LIT> , <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT> , <NUM_LIT>, <NUM_LIT>]<EOL>)<EOL>self.wt = np.array(([<NUM_LIT:1.0>] * <NUM_LIT>) + ([<NUM_LIT>] * <NUM_LIT>))<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>] * <NUM_LIT>) + [<NUM_LIT:2>, <NUM_LIT:3>] + [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:5>] * <NUM_LIT> + [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>] * <NUM_LIT>).reshape(<NUM_LIT>, <NUM_LIT:4>)<EOL>
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>, <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:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>,<EOL><NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>])<EOL>self.age = np.array([<EOL><NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:3>,<EOL><NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:3>, <NUM_LIT:2>,<EOL><NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:3>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:4>])<EOL>self.gender = np.array([<EOL><NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:2>,<EOL><NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>,<EOL><NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>])<EOL>self.lover = np.array(['<STR_LIT>'] * <NUM_LIT> + ['<STR_LIT>'] * <NUM_LIT>)<EOL>self.tree = CHAID.Tree.from_numpy(<EOL>np.vstack([self.region, self.age, self.gender]).transpose(),<EOL>self.lover,<EOL>alpha_merge=<NUM_LIT><EOL>)<EOL>
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><INDENT>return list_a == list_b or (isinstance(float, str) and isnan(list_a) and isnan(list_b))<EOL><DEDENT>
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(list_b))<EOL><DEDENT>
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_var.arr == col, dep.arr), return_counts=True)<EOL>freq[col] = cl.defaultdict(int)<EOL>freq[col].update(np.transpose(counts))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for col in unique:<EOL><INDENT>counts = np.unique(np.compress(ind_var.arr == col, dep.arr), return_counts=True)<EOL>freq[col] = cl.defaultdict(int)<EOL>for dep_v in all_dep:<EOL><INDENT>freq[col][dep_v] = dep.weights[(ind_var.arr == col) * (dep.arr == dep_v)].sum()<EOL><DEDENT><DEDENT><DEDENT>if len(list(ind_var.possible_groupings())) == <NUM_LIT:0>:<EOL><INDENT>split.invalid_reason = InvalidSplitReason.PURE_NODE<EOL><DEDENT>choice, highest_p_join, split_chi, dof = None, None, None, None<EOL>for comb in ind_var.all_combinations():<EOL><INDENT>freqs = [ sum( [ cl.Counter(freq[key]) for key in c ], cl.Counter()) for c in comb ]<EOL>if sum([ (sum(x.values()) < self.min_child_node_size) for x in freqs ] ) > <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>keys = set(sum([ list(f.keys()) for f in freqs ], []))<EOL>n_ij = np.array(<EOL>[ [ col.get(k, <NUM_LIT:0>) for k in keys ] for col in freqs ]<EOL>)<EOL>chi, p_split, dof = chisquare(n_ij, dep.weights is not None)<EOL>if (choice is None or p_split < highest_p_join or (p_split == highest_p_join and chi > split_chi)) and p_split < self.alpha_merge:<EOL><INDENT>choice, highest_p_join, split_chi = comb, p_split, chi<EOL><DEDENT><DEDENT>temp_split = Split(i, choice, split_chi, highest_p_join, dof, split_name=ind_var.name)<EOL>better_split = (not split.valid() or p_split < split.p or (p_split == split.p and chi > split.score)) and choice is not None<EOL>if better_split: split, temp_split = temp_split, split<EOL>if split.valid() and choice is not None:<EOL><INDENT>chi_threshold = self.split_threshold * split.score<EOL>if temp_split.valid() and temp_split.score >= chi_threshold:<EOL><INDENT>for sur in temp_split.surrogates:<EOL><INDENT>if sur.column_id != i and sur.score >= chi_threshold:<EOL><INDENT>split.surrogates.append(sur)<EOL><DEDENT><DEDENT>temp_split.surrogates = []<EOL>split.surrogates.append(temp_split)<EOL><DEDENT>split.sub_split_values(ind[split.column_id].metadata)<EOL><DEDENT><DEDENT>return split<EOL>
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 = dependent_column<EOL>self._stats = Stats(<EOL>config.get('<STR_LIT>', <NUM_LIT>),<EOL>config.get('<STR_LIT>', <NUM_LIT:30>),<EOL>config.get('<STR_LIT>', <NUM_LIT:0>),<EOL>dependent_column.arr<EOL>)<EOL>
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_parent_node_size=30, min_child_node_size=30, split_threshold=0 }
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], name=title)<EOL><DEDENT>elif col_type == '<STR_LIT>':<EOL><INDENT>col = NominalColumn(ndarr[:, ind], name=title)<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>' + col_type)<EOL><DEDENT>vectorised_array.append(col)<EOL><DEDENT>if dep_variable_type == '<STR_LIT>':<EOL><INDENT>observed = NominalColumn(arr, weights=weights)<EOL><DEDENT>elif dep_variable_type == '<STR_LIT>':<EOL><INDENT>observed = ContinuousColumn(arr, weights=weights)<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>' + dep_variable_type)<EOL><DEDENT>config = { '<STR_LIT>': alpha_merge, '<STR_LIT>': max_depth, '<STR_LIT>': min_parent_node_size,<EOL>'<STR_LIT>': min_child_node_size, '<STR_LIT>': split_threshold }<EOL>return Tree(vectorised_array, observed, config)<EOL>
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 with ndarr alpha_merge : float the threshold value in which to create a split (default 0.05) max_depth : float the threshold value for the maximum number of levels after the root node in the tree (default 2) min_parent_node_size : float the threshold value of the number of respondents that the node must contain (default 30) split_titles : array-like array of names for the independent variables in the data variable_types : array-like or dict array of variable types, or dict of column names to variable types. Supported variable types are the strings 'nominal' or 'ordinal' in lower case
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), split_threshold, weights,<EOL>list(i_variables.values()), dep_variable_type)<EOL>
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 types are the strings 'nominal' or 'ordinal' in lower case d_variable : string the name of the dependent variable in the dataframe alpha_merge : float the threshold value in which to create a split (default 0.05) max_depth : float the threshold value for the maximum number of levels after the root node in the tree (default 2) split_threshold : float the variation in chi-score such that surrogate splits are created (default 0) min_parent_node_size : float the threshold value of the number of respondents that the node must contain (default 30) min_child_node_size : float the threshold value of the number of respondents that each child node must contain (default 30) weight : array-like the respondent weights. If passed, weighted chi-square calculation is run dep_variable_type : str the type of dependent variable. Supported variable types are 'categorical' or 'continuous'
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.MAX_DEPTH<EOL>return self._tree_store<EOL><DEDENT>split = self._stats.best_split(ind, dep)<EOL>node = Node(choices=parent_decisions, node_id=self.node_count, indices=rows, dep_v=dep,<EOL>parent=parent, split=split)<EOL>self._tree_store.append(node)<EOL>parent = self.node_count<EOL>self.node_count += <NUM_LIT:1><EOL>if not split.valid():<EOL><INDENT>return self._tree_store<EOL><DEDENT>for index, choices in enumerate(split.splits):<EOL><INDENT>correct_rows = np.in1d(ind[split.column_id].arr, choices)<EOL>dep_slice = dep[correct_rows]<EOL>ind_slice = [vect[correct_rows] for vect in ind]<EOL>row_slice = rows[correct_rows]<EOL>if self.min_parent_node_size < len(dep_slice.arr):<EOL><INDENT>self.node(row_slice, ind_slice, dep_slice, depth=depth, parent=parent,<EOL>parent_decisions=split.split_map[index])<EOL><DEDENT>else:<EOL><INDENT>terminal_node = Node(choices=split.split_map[index], node_id=self.node_count,<EOL>parent=parent, indices=row_slice, dep_v=dep_slice)<EOL>terminal_node.split.invalid_reason = InvalidSplitReason.MIN_PARENT_NODE_SIZE<EOL>self._tree_store.append(terminal_node)<EOL>self.node_count += <NUM_LIT:1><EOL><DEDENT><DEDENT>return self._tree_store<EOL>
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 pred<EOL>
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:*>', help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>var.add_argument('<STR_LIT>', type=str, nargs='<STR_LIT:*>',<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', type=str, help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', type=int, help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', type=int, help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', type=int, help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', type=float, help='<STR_LIT>')<EOL>group = parser.add_mutually_exclusive_group(required=False)<EOL>group.add_argument('<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>group.add_argument('<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>group.add_argument('<STR_LIT>', action='<STR_LIT:store_true>')<EOL>group.add_argument('<STR_LIT>', action='<STR_LIT:store_true>', help='<STR_LIT>')<EOL>group.add_argument('<STR_LIT>', type=str, help='<STR_LIT>')<EOL>nspace = parser.parse_args()<EOL>if nspace.file[-<NUM_LIT:4>:] == '<STR_LIT>':<EOL><INDENT>data = pd.read_csv(nspace.file)<EOL><DEDENT>elif nspace.file[-<NUM_LIT:4>:] == '<STR_LIT>':<EOL><INDENT>import savReaderWriter as spss<EOL>raw_data = spss.SavReader(nspace.file, returnHeader=True)<EOL>raw_data_list = list(raw_data)<EOL>data = pd.DataFrame(raw_data_list)<EOL>data = data.rename(columns=data.loc[<NUM_LIT:0>]).iloc[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>config = {}<EOL>if nspace.max_depth:<EOL><INDENT>config['<STR_LIT>'] = nspace.max_depth<EOL><DEDENT>if nspace.alpha_merge:<EOL><INDENT>config['<STR_LIT>'] = nspace.alpha_merge<EOL><DEDENT>if nspace.min_parent_node_size:<EOL><INDENT>config['<STR_LIT>'] = nspace.min_parent_node_size<EOL><DEDENT>if nspace.min_child_node_size:<EOL><INDENT>config['<STR_LIT>'] = nspace.min_child_node_size<EOL><DEDENT>if nspace.weights:<EOL><INDENT>config['<STR_LIT>'] = nspace.weights<EOL><DEDENT>if nspace.dependent_variable_type:<EOL><INDENT>config['<STR_LIT>'] = nspace.dependent_variable_type<EOL><DEDENT>ordinal = nspace.ordinal_variables or []<EOL>nominal = nspace.nominal_variables or []<EOL>independent_variables = nominal + ordinal<EOL>types = dict(zip(nominal + ordinal, ['<STR_LIT>'] * len(nominal) + ['<STR_LIT>'] * len(ordinal)))<EOL>if len(independent_variables) == <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>')<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>tree = Tree.from_pandas_df(data, types, nspace.dependent_variable[<NUM_LIT:0>],<EOL>**config)<EOL>if nspace.export or nspace.export_path:<EOL><INDENT>tree.render(nspace.export_path, True)<EOL><DEDENT>if nspace.classify:<EOL><INDENT>predictions = pd.Series(tree.node_predictions())<EOL>predictions.name = '<STR_LIT>'<EOL>data = pd.concat([data, predictions], axis=<NUM_LIT:1>)<EOL>print(data.to_csv())<EOL><DEDENT>elif nspace.predict:<EOL><INDENT>predictions = pd.Series(tree.model_predictions())<EOL>predictions.name = '<STR_LIT>'<EOL>data = pd.concat([data, predictions], axis=<NUM_LIT:1>)<EOL>print(data.to_csv())<EOL><DEDENT>elif nspace.rules:<EOL><INDENT>print('<STR_LIT:\n>'.join(str(x) for x in tree.classification_rules()))<EOL><DEDENT>else:<EOL><INDENT>tree.print_tree()<EOL>print('<STR_LIT>', tree.accuracy())<EOL><DEDENT>
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] + smaller[n+<NUM_LIT:1>:], self._nan)):<EOL><INDENT>yield smaller[:n] + [[ first ] + subset] + smaller[n+<NUM_LIT:1>:]<EOL><DEDENT><DEDENT>if not ordinal or (ordinal and is_sorted([ [ first ] ] + smaller, self._nan)):<EOL><INDENT>yield [ [ first ] ] + smaller<EOL><DEDENT><DEDENT>
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[new_id] = value<EOL><DEDENT>arr = arr.astype(np.float)<EOL>np.place(arr, np.isnan(arr), -<NUM_LIT:1>)<EOL>self.arr = arr<EOL>if -<NUM_LIT:1> in arr:<EOL><INDENT>self.metadata[-<NUM_LIT:1>] = self._missing_id<EOL><DEDENT>
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>alpha = alpha * np.vstack(n_ij_col_sum / m_ij.sum(axis=<NUM_LIT:1>))<EOL>beta = n_ij_row_sum / (alpha * w_ij).sum(axis=<NUM_LIT:0>)<EOL>eps = np.max(np.absolute(w_ij * alpha * beta - m_ij))<EOL>m_ij = w_ij * alpha * beta<EOL><DEDENT><DEDENT>else:<EOL><INDENT>m_ij = (np.vstack(n_ij.sum(axis=<NUM_LIT:1>)) * n_ij.sum(axis=<NUM_LIT:0>)) / n_ij.sum().astype(float)<EOL><DEDENT>dof = (n_ij.shape[<NUM_LIT:0>] - <NUM_LIT:1>) * (n_ij.shape[<NUM_LIT:1>] - <NUM_LIT:1>)<EOL>chi, p_val = stats.chisquare(n_ij, f_exp=m_ij, ddof=n_ij.size - <NUM_LIT:1> - dof, axis=None)<EOL>return (chi, p_val, dof)<EOL>
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 is None:<EOL><INDENT>split.invalid_reason = InvalidSplitReason.MIN_CHILD_NODE_SIZE<EOL>return split<EOL><DEDENT>elif dep.weights is not None and len(dep.weights) < min_child_node_size:<EOL><INDENT>split.invalid_reason = InvalidSplitReason.PURE_NODE<EOL>return split<EOL><DEDENT>for i, ind_var in enumerate(ind):<EOL><INDENT>split.invalid_reason = None <EOL>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_var.arr == col, dep.arr), return_counts=True)<EOL>freq[col] = cl.defaultdict(int)<EOL>freq[col].update(np.transpose(counts))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for col in unique:<EOL><INDENT>counts = np.unique(np.compress(ind_var.arr == col, dep.arr), return_counts=True)<EOL>freq[col] = cl.defaultdict(int)<EOL>for dep_v in all_dep:<EOL><INDENT>freq[col][dep_v] = dep.weights[(ind_var.arr == col) * (dep.arr == dep_v)].sum()<EOL><DEDENT><DEDENT><DEDENT>if dep.weights is not None:<EOL><INDENT>row_count = dep.weights.sum()<EOL><DEDENT>else:<EOL><INDENT>row_count = len(dep.arr)<EOL><DEDENT>if len(list(ind_var.possible_groupings())) == <NUM_LIT:0>:<EOL><INDENT>split.invalid_reason = InvalidSplitReason.PURE_NODE<EOL><DEDENT>while next(ind_var.possible_groupings(), None) is not None:<EOL><INDENT>choice, highest_p_join, split_chi = None, None, None<EOL>for comb in ind_var.possible_groupings():<EOL><INDENT>col1_freq = freq[comb[<NUM_LIT:0>]]<EOL>col2_freq = freq[comb[<NUM_LIT:1>]]<EOL>keys = set(col1_freq.keys()).union(col2_freq.keys())<EOL>n_ij = np.array([<EOL>[col1_freq.get(k, <NUM_LIT:0>) for k in keys],<EOL>[col2_freq.get(k, <NUM_LIT:0>) for k in keys]<EOL>])<EOL>other_splits = row_count - n_ij.sum()<EOL>if other_splits < min_child_node_size and other_splits != <NUM_LIT:0>:<EOL><INDENT>p_split, dof, chi = <NUM_LIT:1>, NaN, NaN<EOL>continue<EOL><DEDENT>if n_ij.shape[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>p_split, dof, chi = <NUM_LIT:1>, NaN, NaN<EOL>choice = comb<EOL>break<EOL><DEDENT>else:<EOL><INDENT>chi, p_split, dof = chisquare(n_ij, dep.weights is not None)<EOL><DEDENT>if choice is None or p_split > highest_p_join or (p_split == highest_p_join and chi > split_chi):<EOL><INDENT>choice, highest_p_join, split_chi = comb, p_split, chi<EOL><DEDENT><DEDENT>sufficient_split = not highest_p_join or highest_p_join < self.alpha_merge<EOL>if not sufficient_split:<EOL><INDENT>split.invalid_reason = InvalidSplitReason.ALPHA_MERGE<EOL><DEDENT>elif (n_ij.sum(axis=<NUM_LIT:1>) < min_child_node_size).any():<EOL><INDENT>split.invalid_reason = InvalidSplitReason.MIN_CHILD_NODE_SIZE<EOL><DEDENT>else:<EOL><INDENT>n_ij = np.array([<EOL>[f[dep_val] for dep_val in all_dep] for f in freq.values()<EOL>])<EOL>dof = (n_ij.shape[<NUM_LIT:0>] - <NUM_LIT:1>) * (n_ij.shape[<NUM_LIT:1>] - <NUM_LIT:1>)<EOL>chi, p_split, dof = chisquare(n_ij, dep.weights is not None)<EOL>temp_split = Split(i, ind_var.groups(), chi, p_split, dof, split_name=ind_var.name)<EOL>better_split = not split.valid() or p_split < split.p or (p_split == split.p and chi > split.score)<EOL>if better_split:<EOL><INDENT>split, temp_split = temp_split, split<EOL><DEDENT>chi_threshold = self.split_threshold * split.score<EOL>if temp_split.valid() and temp_split.score >= chi_threshold:<EOL><INDENT>for sur in temp_split.surrogates:<EOL><INDENT>if sur.column_id != i and sur.score >= chi_threshold:<EOL><INDENT>split.surrogates.append(sur)<EOL><DEDENT><DEDENT>temp_split.surrogates = []<EOL>split.surrogates.append(temp_split)<EOL><DEDENT>break<EOL><DEDENT>if choice is None:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>ind_var.group(choice[<NUM_LIT:0>], choice[<NUM_LIT:1>])<EOL>for val, count in freq[choice[<NUM_LIT:1>]].items():<EOL><INDENT>freq[choice[<NUM_LIT:0>]][val] += count<EOL><DEDENT>del freq[choice[<NUM_LIT:1>]]<EOL><DEDENT><DEDENT><DEDENT>if split.valid():<EOL><INDENT>split.sub_split_values(ind[split.column_id].metadata)<EOL><DEDENT>return split<EOL>
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, ind_var in enumerate(ind):<EOL><INDENT>ind_var = ind_var.deep_copy()<EOL>unique = np.unique(ind_var.arr)<EOL>keyed_set = {}<EOL>for col in unique:<EOL><INDENT>matched_elements = np.compress(ind_var.arr == col, response_set)<EOL>keyed_set[col] = matched_elements<EOL><DEDENT>while next(ind_var.possible_groupings(), None) is not None:<EOL><INDENT>choice, highest_p_join, split_score = None, None, None<EOL>for comb in ind_var.possible_groupings():<EOL><INDENT>col1_keyed_set = keyed_set[comb[<NUM_LIT:0>]]<EOL>col2_keyed_set = keyed_set[comb[<NUM_LIT:1>]]<EOL>dof = len(np.concatenate((col1_keyed_set, col2_keyed_set))) - <NUM_LIT:2><EOL>score, p_split = sig_test(col1_keyed_set, col2_keyed_set)<EOL>if choice is None or p_split > highest_p_join or (p_split == highest_p_join and score > split_score):<EOL><INDENT>choice, highest_p_join, split_score = comb, p_split, score<EOL><DEDENT><DEDENT>sufficient_split = highest_p_join < self.alpha_merge and all(<EOL>len(node_v) >= self.min_child_node_size for node_v in keyed_set.values()<EOL>)<EOL>invalid_reason = None<EOL>sufficient_split = highest_p_join < self.alpha_merge<EOL>if not sufficient_split: invalid_reason = InvalidSplitReason.ALPHA_MERGE<EOL>sufficient_split = sufficient_split and all(<EOL>len(node_v) >= self.min_child_node_size for node_v in keyed_set.values()<EOL>)<EOL>if not sufficient_split: invalid_reason = InvalidSplitReason.MIN_CHILD_NODE_SIZE<EOL>if sufficient_split and len(keyed_set.values()) > <NUM_LIT:1>:<EOL><INDENT>dof = len(np.concatenate(list(keyed_set.values()))) - <NUM_LIT:2><EOL>score, p_split = sig_test(*keyed_set.values())<EOL>temp_split = Split(i, ind_var.groups(), score, p_split, dof, split_name=ind_var.name)<EOL>better_split = not split.valid() or p_split < split.p or (p_split == split.p and score > split.score)<EOL>if better_split:<EOL><INDENT>split, temp_split = temp_split, split<EOL><DEDENT>score_threshold = self.split_threshold * split.score<EOL>if temp_split.valid() and temp_split.score >= score_threshold:<EOL><INDENT>for sur in temp_split.surrogates:<EOL><INDENT>if sur.column_id != i and sur.score >= score_threshold:<EOL><INDENT>split.surrogates.append(sur)<EOL><DEDENT><DEDENT>temp_split.surrogates = []<EOL>split.surrogates.append(temp_split)<EOL><DEDENT>break<EOL><DEDENT>else:<EOL><INDENT>split.invalid_reason = invalid_reason<EOL><DEDENT>ind_var.group(choice[<NUM_LIT:0>], choice[<NUM_LIT:1>])<EOL>keyed_set[choice[<NUM_LIT:0>]] = np.concatenate((keyed_set[choice[<NUM_LIT:1>]], keyed_set[choice[<NUM_LIT:0>]]))<EOL>del keyed_set[choice[<NUM_LIT:1>]]<EOL><DEDENT><DEDENT>if split.valid():<EOL><INDENT>split.sub_split_values(ind[split.column_id].metadata)<EOL><DEDENT>return split<EOL>
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>raise Exception(<EOL>"<STR_LIT>".format(init_location)<EOL>)<EOL><DEDENT>return match.group('<STR_LIT:version>')<EOL>
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.MlAMr = self.Ml*self.A*self.Mr<EOL>try:<EOL><INDENT>self.ip_B = utils.get_linearoperator(shape, ip_B)<EOL><DEDENT>except TypeError:<EOL><INDENT>self.ip_B = ip_B<EOL><DEDENT>self.flat_vecs, (self.b, self.exact_solution) =utils.shape_vecs(b, exact_solution)<EOL>self.self_adjoint = self_adjoint<EOL>if self_adjoint:<EOL><INDENT>if normal is not None and not normal:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>normal = True<EOL><DEDENT>if normal is None:<EOL><INDENT>normal = False<EOL><DEDENT>self.normal = normal<EOL>self.positive_definite = positive_definite<EOL>if self_adjoint and not normal:<EOL><INDENT>raise utils.ArgumentError('<STR_LIT>')<EOL><DEDENT>self.dtype = utils.find_common_dtype(self.A, self.b, self.M,<EOL>self.Ml, self.Mr, self.ip_B)<EOL>self.Mlb = self.Ml*self.b<EOL>self.MMlb = self.M*self.Mlb<EOL>self.MMlb_norm = utils.norm(self.Mlb, self.MMlb, ip_B=self.ip_B)<EOL>'''<STR_LIT>'''<EOL>
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{C}^N` (has to be compatible with :py:meth:`~krypy.utils.get_linearoperator`). :param b: the right hand side in :math:`\mathbb{C}^N`, i.e., ``b.shape == (N, 1)``. :param M: (optional) a self-adjoint and positive definite preconditioner, linear operator on :math:`\mathbb{C}^N` with respect to the inner product defined by ``ip_B``. This preconditioner changes the inner product to :math:`\langle x,y\rangle_M = \langle Mx,y\rangle` where :math:`\langle \cdot,\cdot\rangle` is the inner product defined by the parameter ``ip_B``. Defaults to the identity. :param Minv: (optional) the inverse of the preconditioner provided by ``M``. This operator is needed, e.g., for orthonormalizing vectors for the computation of Ritz vectors in deflated methods. :param Ml: (optional) left preconditioner, linear operator on :math:`\mathbb{C}^N`. Defaults to the identity. :param Mr: (optional) right preconditioner, linear operator on :math:`\mathbb{C}^N`. Defaults to the identity. :param ip_B: (optional) defines the inner product, see :py:meth:`~krypy.utils.inner`. :param normal: (bool, optional) Is :math:`M_l A M_r` normal in the inner product defined by ``ip_B``? Defaults to ``False``. :param self_adjoint: (bool, optional) Is :math:`M_l A M_r` self-adjoint in the inner product defined by ``ip_B``? ``self_adjoint=True`` also sets ``normal=True``. Defaults to ``False``. :param positive_definite: (bool, optional) Is :math:`M_l A M_r` positive (semi-)definite with respect to the inner product defined by ``ip_B``? Defaults to ``False``. :param exact_solution: (optional) If an exact solution :math:`x` is known, it can be provided as a ``numpy.array`` with ``exact_solution.shape == (N,1)``. Then error norms can be computed (for debugging or research purposes). Defaults to ``None``.
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 MMlr, Mlr<EOL>
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. :param z: approximate solution with ``z.shape == (N, 1)``. :param compute_norm: (bool, optional) pass ``True`` if also the norm of the residual should be computed.
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><INDENT>return lambda x, y: self.ip_B(x, self.Minv*y)<EOL><DEDENT><DEDENT>return self.ip_B<EOL>
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_residual = explicit_residual<EOL>self.store_arnoldi = store_arnoldi<EOL>self.x0 = self._get_initial_guess(self.x0)<EOL>self.MMlr0, self.Mlr0, self.MMlr0_norm =self._get_initial_residual(self.x0)<EOL>if self.x0 is None:<EOL><INDENT>self.x0 = numpy.zeros((N, <NUM_LIT:1>))<EOL><DEDENT>self.tol = tol<EOL>self.xk = None<EOL>'''<STR_LIT>'''<EOL>self.dtype = numpy.find_common_type([linear_system.dtype,<EOL>self.x0.dtype,<EOL>dtype<EOL>], [])<EOL>self.MlAMr = linear_system.MlAMr<EOL>self.iter = <NUM_LIT:0><EOL>'''<STR_LIT>'''<EOL>self.resnorms = []<EOL>'''<STR_LIT>'''<EOL>if self.linear_system.MMlb_norm == <NUM_LIT:0>:<EOL><INDENT>self.xk = self.x0 = numpy.zeros((N, <NUM_LIT:1>))<EOL>self.resnorms.append(<NUM_LIT:0.>)<EOL><DEDENT>else:<EOL><INDENT>self.resnorms.append(self.MMlr0_norm/self.linear_system.MMlb_norm)<EOL><DEDENT>if self.linear_system.exact_solution is not None:<EOL><INDENT>self.errnorms = []<EOL>'''<STR_LIT>'''<EOL>self.errnorms.append(utils.norm(<EOL>self.linear_system.exact_solution - self._get_xk(None),<EOL>ip_B=self.linear_system.ip_B))<EOL><DEDENT>self._solve()<EOL>self._finalize()<EOL>
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) the initial guess to use. Defaults to zero vector. Unless you have a good reason to use a nonzero initial guess you should use the zero vector, cf. chapter 5.8.3 in *Liesen, Strakos. Krylov subspace methods. 2013*. See also :py:meth:`~krypy.utils.hegedus`. :param tol: (optional) the tolerance for the stopping criterion with respect to the relative residual norm: .. math:: \frac{ \| M M_l (b-A (x_0+M_r y_k))\|_{M^{-1}} } { \|M M_l b\|_{M^{-1}}} \leq \text{tol} :param maxiter: (optional) maximum number of iterations. Defaults to N. :param explicit_residual: (optional) if set to ``False`` (default), the updated residual norm from the used method is used in each iteration. If set to ``True``, the residual is computed explicitly in each iteration and thus requires an additional application of ``M``, ``Ml``, ``A`` and ``Mr`` in each iteration. :param store_arnoldi: (optional) if set to ``True`` then the computed Arnoldi basis and the Hessenberg matrix are set as attributes ``V`` and ``H`` on the returned object. If ``M`` is not ``None``, then also ``P`` is set where ``V=M*P``. Defaults to ``False``. If the method is based on the Lanczos method (e.g., :py:class:`Cg` or :py:class:`Minres`), then ``H`` is real, symmetric and tridiagonal. :param dtype: (optional) an optional dtype that is used to determine the dtype for the Arnoldi/Lanczos basis and matrix. Upon convergence, the instance contains the following attributes: * ``xk``: the approximate solution :math:`x_k`. * ``resnorms``: relative residual norms of all iterations, see parameter ``tol``. * ``errnorms``: the error norms of all iterations if ``exact_solution`` was provided. * ``V``, ``H`` and ``P`` if ``store_arnoldi==True``, see ``store_arnoldi`` If the solver does not converge, a :py:class:`~krypy.utils.ConvergenceError` is thrown which can be used to examine the misconvergence.
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 <= self.tolor self.iter+<NUM_LIT:1> == self.maxiter:<EOL><INDENT>if self.xk is None:<EOL><INDENT>self.xk = self._get_xk(yk)<EOL><DEDENT>_, _, rkn = self.linear_system.get_residual(self.xk,<EOL>compute_norm=True)<EOL>self.resnorms.append(rkn/self.linear_system.MMlb_norm)<EOL>if self.resnorms[-<NUM_LIT:1>] > self.tol:<EOL><INDENT>if self.iter+<NUM_LIT:1> == self.maxiter:<EOL><INDENT>self._finalize()<EOL>raise utils.ConvergenceError(<EOL>('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>.format(self.maxiter, self.resnorms[-<NUM_LIT:1>]), self)<EOL><DEDENT>elif not self.explicit_residualand resnorm/self.linear_system.MMlb_norm <= self.tol:<EOL><INDENT>warnings.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(resnorm, self.tol, self.resnorms[-<NUM_LIT:1>]))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.resnorms.append(resnorm/self.linear_system.MMlb_norm)<EOL><DEDENT>return rkn<EOL>
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:1>)/<NUM_LIT:2><EOL>}<EOL>
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><INDENT>if self.xk is not None:<EOL><INDENT>kwargs.update({'<STR_LIT>': self.xk})<EOL><DEDENT>sol = Solver(linear_system, **kwargs)<EOL><DEDENT>except utils.ConvergenceError as e:<EOL><INDENT>sol = e.solver<EOL><DEDENT>self.xk = sol.xk<EOL>tol = sol.tol<EOL>del self.resnorms[-<NUM_LIT:1>]<EOL>self.resnorms += sol.resnorms<EOL>if linear_system.exact_solution is not None:<EOL><INDENT>del self.errnorms[-<NUM_LIT:1>]<EOL>self.errnorms += sol.errnorms<EOL><DEDENT>restart += <NUM_LIT:1><EOL><DEDENT>if self.resnorms[-<NUM_LIT:1>] > tol:<EOL><INDENT>raise utils.ConvergenceError(<EOL>'<STR_LIT>'.format(max_restarts),<EOL>self)<EOL><DEDENT>
: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 numpy.find_common_type(dtypes, [])<EOL>
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.dot((B*X).T.conj(), Y)<EOL><DEDENT>else:<EOL><INDENT>return numpy.dot(X.T.conj(), B*Y)<EOL><DEDENT>
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``: Euclidean inner product. * a self-adjoint and positive definite operator :math:`B` (as ``numpy.array`` or ``LinearOperator``). Then :math:`X^*B Y` is returned. * a callable which takes 2 arguments X and Y and returns :math:`\\langle X,Y\\rangle`. **Caution:** a callable should only be used if necessary. The choice potentially has an impact on the round-off behavior, e.g. of projections. :return: numpy array :math:`\\langle X,Y\\rangle` with ``shape==(m,n)``.
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:0>, <NUM_LIT:0>])*<NUM_LIT> or rho[<NUM_LIT:0>, <NUM_LIT:0>].real < <NUM_LIT:0.0>:<EOL><INDENT>raise InnerProductError(('<STR_LIT>'<EOL>'<STR_LIT>') % rho[<NUM_LIT:0>, <NUM_LIT:0>])<EOL><DEDENT><DEDENT>return numpy.linalg.norm(rho, <NUM_LIT:2>)<EOL>
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.norm(numpy.imag(numpy.diag(ip)), <NUM_LIT:2>)<EOL>if nrm_diag_imag > nrm_diag*<NUM_LIT>:<EOL><INDENT>raise InnerProductError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(nrm_diag_imag/nrm_diag))<EOL><DEDENT>return numpy.sqrt(numpy.linalg.norm(ip, <NUM_LIT:2>))<EOL>
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 isinstance(A, numpy.matrix):<EOL><INDENT>ret = MatrixLinearOperator(numpy.atleast_2d(numpy.asarray(A)))<EOL><DEDENT>elif isinstance(A, scipylinalg.LinearOperator):<EOL><INDENT>if not hasattr(A, '<STR_LIT>'):<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>ret = LinearOperator(A.shape, dot=A.matvec, dot_adj=A.rmatvec,<EOL>dtype=A.dtype)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if A is not None and not isinstance(A, IdentityLinearOperator)and timer is not None:<EOL><INDENT>ret = TimedLinearOperator(ret, timer)<EOL><DEDENT>if shape != ret.shape:<EOL><INDENT>raise LinearOperatorError('<STR_LIT>')<EOL><DEDENT>return ret<EOL>
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==(n,n)`` (if the Arnoldi basis spans an A-invariant subspace). :param ip_B: (optional) the inner product to use, see :py:meth:`inner`. :returns: either :math:`\\|AV_{n-1} - V_n \\underline{H}_{n-1}\\|` or :math:`\\|A V_n - V_n H_n\\|` (in the invariant case).
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 range(i):<EOL><INDENT>alpha = inner(Q[:, [j]], Q[:, [i]], ip_B=ip_B)[<NUM_LIT:0>, <NUM_LIT:0>]<EOL>R[j, i] += alpha<EOL>Q[:, [i]] -= alpha * Q[:, [j]]<EOL><DEDENT><DEDENT>R[i, i] = norm(Q[:, [i]], ip_B=ip_B)<EOL>if R[i, i] >= <NUM_LIT>:<EOL><INDENT>Q[:, [i]] /= R[i, i]<EOL><DEDENT><DEDENT>return Q, R<EOL><DEDENT>
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 cases (TODO: add reference). :return: Q, R where :math:`X=QR` with :math:`\\langle Q,Q \\rangle=I_k` and R upper triangular.
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 = QG<EOL><DEDENT>else:<EOL><INDENT>Y, s, Z = scipy.linalg.svd(inner(QF, QG, ip_B=ip_B))<EOL>Vcos = numpy.dot(QG, Z.T.conj())<EOL>n_large = numpy.flatnonzero((s**<NUM_LIT:2>) < <NUM_LIT:0.5>).shape[<NUM_LIT:0>]<EOL>n_small = s.shape[<NUM_LIT:0>] - n_large<EOL>theta = numpy.r_[<EOL>numpy.arccos(s[n_small:]), <EOL>numpy.ones(F.shape[<NUM_LIT:1>]-G.shape[<NUM_LIT:1>])*numpy.pi/<NUM_LIT:2>]<EOL>if compute_vectors:<EOL><INDENT>Ucos = numpy.dot(QF, Y)<EOL>U = Ucos[:, n_small:]<EOL>V = Vcos[:, n_small:]<EOL><DEDENT>if n_small > <NUM_LIT:0>:<EOL><INDENT>RG = Vcos[:, :n_small]<EOL>S = RG - numpy.dot(QF, inner(QF, RG, ip_B=ip_B))<EOL>_, R = qr(S, ip_B=ip_B)<EOL>Y, u, Z = scipy.linalg.svd(R)<EOL>theta = numpy.r_[<EOL>numpy.arcsin(u[::-<NUM_LIT:1>][:n_small]),<EOL>theta]<EOL>if compute_vectors:<EOL><INDENT>RF = Ucos[:, :n_small]<EOL>Vsin = numpy.dot(RG, Z.T.conj())<EOL>Usin = numpy.dot(RF, numpy.dot(<EOL>numpy.diag(<NUM_LIT:1>/s[:n_small]),<EOL>numpy.dot(Z.T.conj(), numpy.diag(s[:n_small]))))<EOL>U = numpy.c_[Usin, U]<EOL>V = numpy.c_[Vsin, V]<EOL><DEDENT><DEDENT><DEDENT>if compute_vectors:<EOL><INDENT>if reverse:<EOL><INDENT>U, V = V, U<EOL><DEDENT>return theta, U, V<EOL><DEDENT>else:<EOL><INDENT>return theta<EOL><DEDENT>
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 algorithm). :param F: array with ``shape==(N,k)``. :param G: array with ``shape==(N,l)``. :param ip_B: (optional) angles are computed with respect to this inner product. See :py:meth:`inner`. :param compute_vectors: (optional) if set to ``False`` then only the angles are returned (default). If set to ``True`` then also the principal vectors are returned. :return: * ``theta`` if ``compute_vectors==False`` * ``theta, U, V`` if ``compute_vectors==True`` where * ``theta`` is the array with ``shape==(max(k,l),)`` containing the principal angles :math:`0\\leq\\theta_1\\leq\\ldots\\leq\\theta_{\\max\\{k,l\\}}\\leq \\frac{\\pi}{2}`. * ``U`` are the principal vectors from F with :math:`\\langle U,U \\rangle=I_k`. * ``V`` are the principal vectors from G with :math:`\\langle V,V \\rangle=I_l`. The principal angles and vectors fulfill the relation :math:`\\langle U,V \\rangle = \ \\begin{bmatrix} \ \\cos(\\Theta) & 0_{m,l-m} \\\\ \ 0_{k-m,m} & 0_{k-m,l-m} \ \\end{bmatrix}` where :math:`m=\\min\\{k,l\\}` and :math:`\\cos(\\Theta)=\\operatorname{diag}(\\cos(\\theta_1),\\ldots,\\cos(\\theta_m))`. Furthermore, :math:`\\theta_{m+1}=\\ldots=\\theta_{\\max\\{k,l\\}}=\\frac{\\pi}{2}`.
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 = inner(z, Ml*b, ip_B=ip_B) / znorm2<EOL>return gamma*x0<EOL>
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 x_0) \\|_{M^{-1}} \\leq \\| M M_l b \\|_{M^{-1}}. This is achieved by :math:`\\gamma_{\\min} = \\frac{\\langle z, M M_l b \\rangle_{M^{-1}}}{\\|z\\|_{M^{-1}}^2}` for :math:`z=M M_l A x_0` because then :math:`r_0=P_{z^\\perp}b`. (Note that the right hand side of formula (5.8.16) in [LieS13]_ has to be complex conjugated.) The parameters are the parameters you want to pass to :py:meth:`~krypy.linsys.gmres`, :py:meth:`~krypy.linsys.minres` or :py:meth:`~krypy.linsys.cg`. :return: the adapted initial guess with the above property.
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_LIT:1>)<EOL>maxiter = n-k+<NUM_LIT:1><EOL>F = numpy.zeros((<NUM_LIT:1>, maxiter), dtype=dtype)<EOL>PH = lambda x: P*(H*x)<EOL>PH = LinearOperator((n, n), dtype, PH)<EOL>_arnoldi = Arnoldi(PH, v, maxiter=maxiter, ortho=ortho)<EOL>while _arnoldi.iter < _arnoldi.maxiter and not _arnoldi.invariant:<EOL><INDENT>u, _ = _arnoldi.get_last()<EOL>F[<NUM_LIT:0>, _arnoldi.iter] = hlast * u[-<NUM_LIT:1>, <NUM_LIT:0>]<EOL>_arnoldi.advance()<EOL><DEDENT>U, G = _arnoldi.get()<EOL>return U, G, F[[<NUM_LIT:0>], :_arnoldi.iter]<EOL>
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\\rangle`) and :math:`\\underline{H}_n\\in\\mathbb{C}^{n+1,n}` is an extended upper Hessenberg matrix. For :math:`k<n` you choose full rank matrices :math:`X\\in\\mathbb{C}^{n-1,k}` and :math:`Y\\in\\mathbb{C}^{n,k}` and define :math:`\\tilde{X}:=A V_{n_1}X = V_n \\underline{H}_{n-1} X` and :math:`\\tilde{Y}:=V_n Y` such that :math:`\\langle \\tilde{Y}, \\tilde{X} \\rangle = Y^*\\underline{H}_{n-1} X` is invertible. Then the projections :math:`P` and :math:`\\tilde{P}` characterized by * :math:`\\tilde{P}x = x - \\tilde{X} \\langle \\tilde{Y},\\tilde{X} \\rangle^{-1} \\langle\\tilde{Y},x\\rangle` * :math:`P = I - \\underline{H}_{n-1}X (Y^*\\underline{H}_{n-1}X)^{-1}Y^*` are well defined and :math:`\\tilde{P}V_{n+1} = [V_n P, v_{n+1}]` holds. This method computes for :math:`i<n-k` the Arnoldi relation .. math :: (\\tilde{P}A + E_i) W_i = W_{i+1} \\underline{G}_i where :math:`W_{i+1}=V_n U_{i+1}` has orthogonal columns with respect to :math:`\\langle\\cdot,\\cdot\\rangle`, :math:`\\underline{G}_i` is an extended upper Hessenberg matrix and :math:`E_i x = v_{n+1} F_i \\langle W_i,x\\rangle` with :math:`F_i=[f_1,\ldots,f_i]\\in\\mathbb{C}^{1,i}`. The perturbed Arnoldi relation can also be generated with the operator :math:`P_{V_n} \\tilde{P} A`: .. math :: P_{V_n} \\tilde{P} A W_i = W_{i+1} \\underline{G}_i. In a sense the perturbed Arnoldi relation is the best prediction for the behavior of the Krylov subspace :math:`K_i(\\tilde{P}A,\\tilde{P}v_1)` that can be generated only with the data from :math:`K_{n+1}(A,v_1)` and without carrying out further matrix-vector multiplications with A. :param H: the extended upper Hessenberg matrix :math:`\\underline{H}_n` with ``shape==(n+1,n)``. :param P: the projection :math:`P:\\mathbb{C}^n\\longrightarrow\\mathbb{C}^n` (has to be compatible with :py:meth:`get_linearoperator`). :param k: the dimension of the null space of P. :returns: U, G, F where * U is the coefficient matrix :math:`U_{i+1}` with ``shape==(n,i+1)``, * G is the extended upper Hessenberg matrix :math:`\\underline{G}_i` with ``shape==(i+1,i)``, * F is the error matrix :math:`F_i` with ``shape==(1,i)``.
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())<EOL>if hermitian and symmres >= <NUM_LIT>:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>.format(symmres))<EOL><DEDENT>eig = scipy.linalg.eigh if hermitian else scipy.linalg.eig<EOL>if type == '<STR_LIT>':<EOL><INDENT>theta, U = eig(H[:n, :])<EOL>beta = <NUM_LIT:0> if H.shape[<NUM_LIT:0>] == n else H[-<NUM_LIT:1>, -<NUM_LIT:1>]<EOL>resnorm = numpy.abs(beta * U[-<NUM_LIT:1>, :])<EOL><DEDENT>elif type == '<STR_LIT>':<EOL><INDENT>theta, U = eig(H[:n, :].T.conj(), numpy.dot(H.T.conj(), H))<EOL>theta = <NUM_LIT:1>/theta<EOL>resnorm = []<EOL>for i in range(n):<EOL><INDENT>U[:, i] /= numpy.linalg.norm(U[:, i], <NUM_LIT:2>)<EOL>resi = numpy.dot(H, U[:, i])<EOL>if resi.dtype != numpy.complex and theta.dtype == numpy.complex:<EOL><INDENT>resi = numpy.array(resi, dtype=numpy.complex)<EOL><DEDENT>resi[:n] -= theta[i]*U[:, i]<EOL>resnorm.append(numpy.linalg.norm(resi, <NUM_LIT:2>))<EOL><DEDENT>resnorm = numpy.array(resnorm)<EOL><DEDENT>elif type == '<STR_LIT>':<EOL><INDENT>theta, U = eig(H[:n, :].T.conj(), numpy.dot(H.T.conj(), H))<EOL>rho = []<EOL>for i in range(n):<EOL><INDENT>U[:, i] /= numpy.linalg.norm(U[:, i], <NUM_LIT:2>)<EOL>rho.append(numpy.dot(U[:, i].T.conj(),<EOL>numpy.dot(H[:n, :], U[:, i])))<EOL><DEDENT>theta = numpy.array(rho)<EOL>resnorm = []<EOL>for i in range(n):<EOL><INDENT>resi = numpy.dot(H, U[:, i])<EOL>resi[:n] -= theta[i]*U[:, i]<EOL>resnorm.append(numpy.linalg.norm(resi, <NUM_LIT:2>))<EOL><DEDENT>resnorm = numpy.array(resnorm)<EOL>pass<EOL><DEDENT>else:<EOL><INDENT>raise ArgumentError('<STR_LIT>'.format(type))<EOL><DEDENT>if V is not None:<EOL><INDENT>return theta, U, resnorm, numpy.dot(V[:, :n], U)<EOL><DEDENT>return theta, U, resnorm<EOL>
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 Arnoldi algorithm applied to A and v. :param H: Hessenberg matrix from Arnoldi/Lanczos algorithm. :param V: (optional) Arnoldi/Lanczos vectors, :math:`V\\in\\mathbb{C}^{N,n+1}`. If provided, the Ritz vectors are also returned. The Arnoldi vectors have to form an orthonormal basis with respect to an inner product. **Caution:** if you are using the Lanzcos or Gram-Schmidt Arnoldi algorithm without reorthogonalization, then the orthonormality of the basis is usually lost. For accurate results it is advisable to use the Householder Arnoldi (``ortho='house'``) or modified Gram-Schmidt with reorthogonalization (``ortho='dmgs'``). :param hermitian: (optional) if set to ``True`` the matrix :math:`H_n` must be Hermitian. A Hermitian matrix :math:`H_n` allows for faster and often more accurate computation of Ritz pairs. :param type: (optional) type of Ritz pairs, may be one of ``'ritz'``, ``'harmonic'`` or ``'harmonic_like'``. Two choices of Ritz pairs fit in the following description: `Given two n-dimensional subspaces` :math:`X,Y\subseteq \\mathbb{C}^N`, `find a basis` :math:`z_1,\ldots,z_n` `of` :math:`X` `and` :math:`\\theta_1,\ldots,\\theta_n\\in\\mathbb{C}` such that :math:`A z_i - \\theta_i z_i \\perp Y` for all :math:`i\\in\{1,\ldots,n\}`. In this setting the choices are * ``'ritz'``: regular Ritz pairs, i.e. :math:`X=Y=K_n(A,v)`. * ``'harmonic'``: harmonic Ritz pairs, i.e. :math:`X=K_n(A,v)` and :math:`Y=AK_n(A,v)`. * ``'harmonic_improved'``: the returned vectors ``U`` (and ``V``, if requested) are the same as with ``type='harmonic'``. The ``theta`` array contains the improved Ritz values :math:`\\theta_i = u_i^* H_n u_i`, cf. section 2 in *Morgan, Zeng. Harmonic Projection Methods for Large Non-symmetric Eigenvalue Problems. 1998.* It can be shown that the residual norm of improved Ritz pairs is always less than or equal to the residual norm of the harmonic Ritz pairs. However, the improved Ritz pairs do not fit into the framework above since the orthogonality condition is lost. :return: * If V is not ``None`` then ``theta, U, resnorm, Z`` is returned. * If V is ``None`` then ``theta, U, resnorm`` is returned. Where * ``theta`` are the Ritz values :math:`[\\theta_1,\ldots,\\theta_n]`. * ``U`` are the coefficients of the Ritz vectors in the Arnoldi basis, i.e. :math:`z_i=Vu_i` where :math:`u_i` is the i-th column of U. * ``resnorm`` is a residual norm vector. * ``Z`` are the actual Ritz vectors, i.e. ``Z=dot(V,U)``.
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><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>return numpy.min(numpy.abs(numpy.reshape(lamda, (len(lamda), <NUM_LIT:1>))<EOL>- numpy.reshape(sigma, (<NUM_LIT:1>, len(sigma)))))<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>lamda_min, lamda_max = numpy.min(lamda), numpy.max(lamda)<EOL>sigma_lo = sigma <= lamda_min<EOL>sigma_hi = sigma >= lamda_max<EOL>if not numpy.all(sigma_lo + sigma_hi):<EOL><INDENT>return None<EOL><DEDENT>delta = numpy.Infinity<EOL>if numpy.any(sigma_lo):<EOL><INDENT>delta = lamda_min - numpy.max(sigma[sigma_lo])<EOL><DEDENT>if numpy.any(sigma_hi):<EOL><INDENT>delta = numpy.min([delta, numpy.min(sigma[sigma_hi]) - lamda_max])<EOL><DEDENT>return delta<EOL><DEDENT>
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=\{\lambda_1,\ldots,\lambda_n\}` given as a single real number or a list or ``numpy.array`` with real numbers. :param sigma: a non-empty set :math:`\Sigma=\{\sigma_1,\ldots,\sigma_m\}`. See ``lamda``. :param mode: (optional). Defines how the gap should be computed. May be one of * ``'individual'`` (default): :math:`\delta=\min_{\substack{i\in\{1,\ldots,n\}\\\\j\in\{1,\ldots,m\}}} |\lambda_i - \sigma_j|`. With this mode, the gap is always be defined. * ``'interval'``: determine the maximal :math:`\delta` such that :math:`\Sigma\subset\mathbb{R}\setminus[\min_{\lambda\in\Lambda}\lambda-\delta,\max_{\lambda\in\Lambda}\lambda+\delta]`. If the gap does not exists, ``None`` is returned. :return: :math:`\delta` or ``None``.
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>* paths.length()/(<NUM_LIT:2>*numpy.pi*delta)<EOL>* supremum)<EOL><DEDENT>return bound<EOL>
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><DEDENT>else:<EOL><INDENT>H[i:i+<NUM_LIT:2>, i:] = G.apply(H[i:i+<NUM_LIT:2>, i:])<EOL><DEDENT>y[i:i+<NUM_LIT:2>] = G.apply(y[i:i+<NUM_LIT:2>])<EOL>resnorms.append(numpy.abs(y[i+<NUM_LIT:1>, <NUM_LIT:0>]))<EOL><DEDENT>if n_ == n:<EOL><INDENT>resnorms.append(<NUM_LIT:0.>)<EOL><DEDENT>return numpy.array(resnorms)<EOL>
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(gamma)<EOL>beta = <NUM_LIT:0><EOL>alpha = <NUM_LIT:1> if gamma == <NUM_LIT:0> else gamma/xnorm<EOL><DEDENT>else:<EOL><INDENT>sigma = numpy.linalg.norm(v[<NUM_LIT:1>:], <NUM_LIT:2>)<EOL>xnorm = numpy.sqrt(numpy.abs(gamma)**<NUM_LIT:2>+sigma**<NUM_LIT:2>)<EOL>if sigma == <NUM_LIT:0>:<EOL><INDENT>beta = <NUM_LIT:0><EOL>xnorm = numpy.abs(gamma)<EOL>alpha = <NUM_LIT:1> if gamma == <NUM_LIT:0> else gamma/xnorm<EOL><DEDENT>else:<EOL><INDENT>beta = <NUM_LIT:2><EOL>if gamma == <NUM_LIT:0>:<EOL><INDENT>v[<NUM_LIT:0>] = -sigma<EOL>alpha = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>v[<NUM_LIT:0>] = gamma + gamma/numpy.abs(gamma) * xnorm<EOL>alpha = - gamma/numpy.abs(gamma)<EOL><DEDENT><DEDENT><DEDENT>self.xnorm = xnorm<EOL>self.v = v/numpy.sqrt(numpy.abs(v[<NUM_LIT:0>])**<NUM_LIT:2> + sigma**<NUM_LIT:2>)<EOL>self.alpha = alpha<EOL>self.beta = beta<EOL>
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 on page 243 in Golub, Van Loan. Matrix computations. Fourth Edition. 2013.
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 is dense.
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, s = blas.zrotg(a, b)<EOL><DEDENT>self.c = c<EOL>self.s = s<EOL>self.r = c*a + s*b<EOL>self.G = numpy.array([[c, s], [-numpy.conj(s), c]])<EOL>
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 != Y.shape:<EOL><INDENT>raise ArgumentError('<STR_LIT>')<EOL><DEDENT>if X.shape[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>self.V = self.W = numpy.zeros(X.shape)<EOL>self.VR = self.WR = self.Q = self.R = None<EOL>return<EOL><DEDENT>if orthogonalize:<EOL><INDENT>self.V, self.VR = qr(X, ip_B=ip_B)<EOL><DEDENT>else:<EOL><INDENT>self.V = X<EOL>self.VR = None<EOL><DEDENT>if Y is X and orthogonalize: <EOL><INDENT>self.W, self.WR = self.V, self.VR<EOL>self.Q, self.R = None, None<EOL><DEDENT>else: <EOL><INDENT>if orthogonalize:<EOL><INDENT>self.W, self.WR = qr(Y, ip_B=ip_B)<EOL><DEDENT>else:<EOL><INDENT>self.W = Y<EOL>self.WR = None<EOL><DEDENT>M = inner(self.W, self.V, ip_B=ip_B)<EOL>self.Q, self.R = scipy.linalg.qr(M)<EOL><DEDENT>
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 kernel :math:`\\mathcal{W}:=\\operatorname{ker}(P)`; this projection is called :math:`P_{\\mathcal{V},\\mathcal{W}}`. Let X and Y be two full rank arrays with ``shape==(N,k)`` and let :math:`\\mathcal{X}\\oplus\\mathcal{Y}^\\perp=\\mathbb{C}^N` where :math:`\\mathcal{X}:=\\operatorname{colspan}(X)` and :math:`\\mathcal{Y}:=\\operatorname{colspan}(Y)`. Then this class constructs the projection :math:`P_{\\mathcal{X},\\mathcal{Y}^\\perp}`. The requirement :math:`\\mathcal{X}\\oplus\\mathcal{Y}^\\perp=\\mathbb{C}^N` is equivalent to ``\\langle X,Y\\rangle`` being nonsingular. :param X: array with ``shape==(N,k)`` and :math:`\\operatorname{rank}(X)=k`. :param Y: (optional) ``None`` or array with ``shape==(N,k)`` and :math:`\\operatorname{rank}(X)=k`. If Y is ``None`` then Y is set to X which means that the resulting projection is orthogonal. :param ip_B: (optional) inner product, see :py:meth:`inner`. ``None``, a ``numpy.array`` or a ``LinearOperator`` is preferred due to the applicability of the proposed algorithms in [Ste11]_, see below. :param orthogonalize: (optional) `True` orthogonalizes the bases provided in `X` and `Y` with respect to the inner product defined by `ip_B`. Defaults to `True` as the orthogonalization is suggested by the round-off error analysis in [Ste11]_. :param iterations: (optional) number of applications of the projection. It was suggested in [Ste11]_ to use 2 iterations (default) in order to achieve high accuracy ("twice is enough" as in the orthogonal case). This projection class makes use of the round-off error analysis of oblique projections in the work of Stewart [Ste11]_ and implements the algorithms that are considered as the most stable ones (e.g., the XQRY representation in [Ste11]_).
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:<EOL><INDENT>Ya = self.WR.T.conj().dot(Ya)<EOL><DEDENT><DEDENT>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>Pa = self.V.dot(c)<EOL>if return_Ya:<EOL><INDENT>return Pa, Ya<EOL><DEDENT>return Pa<EOL>
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} \langle Y, a\rangle`. * :math:`\langle Y,a\rangle` if ``return_inner==True``.
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._apply(a)<EOL><DEDENT>for i in range(self.iterations-<NUM_LIT:1>):<EOL><INDENT>z = a - x<EOL>w = self._apply(z)<EOL>x = x + w<EOL><DEDENT>if return_Ya:<EOL><INDENT>return x, Ya<EOL><DEDENT>return x<EOL>
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>z = a - x<EOL>for i in range(self.iterations-<NUM_LIT:1>):<EOL><INDENT>w = self._apply(z)<EOL>z = z - w<EOL><DEDENT>if return_Ya:<EOL><INDENT>return z, Ya<EOL><DEDENT>return z<EOL>
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 the resulting matrix is dense.
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_common_dtype(A, v, M)<EOL>self.iter = <NUM_LIT:0><EOL>self.V = numpy.zeros((N, self.maxiter+<NUM_LIT:1>), dtype=self.dtype)<EOL>if self.M is not None:<EOL><INDENT>self.P = numpy.zeros((N, self.maxiter+<NUM_LIT:1>), dtype=self.dtype)<EOL><DEDENT>self.H = numpy.zeros((self.maxiter+<NUM_LIT:1>, self.maxiter),<EOL>dtype=self.dtype)<EOL>self.invariant = False<EOL>if ortho == '<STR_LIT>':<EOL><INDENT>if (self.M is not None<EOL>and not isinstance(self.M, IdentityLinearOperator)) or(not isinstance(self.ip_B, IdentityLinearOperator) and<EOL>self.ip_B is not None):<EOL><INDENT>raise ArgumentError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self.houses = [House(v)]<EOL>self.vnorm = numpy.linalg.norm(v, <NUM_LIT:2>)<EOL><DEDENT>elif ortho in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>self.reorthos = <NUM_LIT:0><EOL>if ortho == '<STR_LIT>':<EOL><INDENT>self.reorthos = <NUM_LIT:1><EOL><DEDENT>if self.M is not None:<EOL><INDENT>p = v<EOL>if Mv is None:<EOL><INDENT>v = self.M*p<EOL><DEDENT>else:<EOL><INDENT>v = Mv<EOL><DEDENT>if Mv_norm is None:<EOL><INDENT>self.vnorm = norm(p, v, ip_B=ip_B)<EOL><DEDENT>else:<EOL><INDENT>self.vnorm = Mv_norm<EOL><DEDENT>if self.vnorm > <NUM_LIT:0>:<EOL><INDENT>self.P[:, [<NUM_LIT:0>]] = p / self.vnorm<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if Mv_norm is None:<EOL><INDENT>self.vnorm = norm(v, ip_B=ip_B)<EOL><DEDENT>else:<EOL><INDENT>self.vnorm = Mv_norm<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ArgumentError(<EOL>'<STR_LIT>'.format(ortho)<EOL>+ '<STR_LIT>')<EOL><DEDENT>if self.vnorm > <NUM_LIT:0>:<EOL><INDENT>self.V[:, [<NUM_LIT:0>]] = v / self.vnorm<EOL><DEDENT>else:<EOL><INDENT>self.invariant = True<EOL><DEDENT>
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==(N,N)``. :param v: the initial vector with ``shape==(N,1)``. :param maxiter: (optional) maximal number of iterations. Default: N. :param ortho: (optional) orthogonalization algorithm: may be one of * ``'mgs'``: modified Gram-Schmidt (default). * ``'dmgs'``: double Modified Gram-Schmidt. * ``'lanczos'``: Lanczos short recurrence. * ``'house'``: Householder. :param M: (optional) a self-adjoint and positive definite preconditioner. If ``M`` is provided, then also a second basis :math:`P_n` is constructed such that :math:`V_n=MP_n`. This is of importance in preconditioned methods. ``M`` has to be ``None`` if ``ortho=='house'`` (see ``B``). :param ip_B: (optional) defines the inner product to use. See :py:meth:`inner`. ``ip_B`` has to be ``None`` if ``ortho=='house'``. It's unclear to me (andrenarchy), how a variant of the Householder QR algorithm can be used with a non-Euclidean inner product. Compare http://math.stackexchange.com/questions/433644/is-householder-orthogonalization-qr-practicable-for-non-euclidean-inner-products
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(k+<NUM_LIT:1>):<EOL><INDENT>Av[j:] = self.houses[j].apply(Av[j:])<EOL>Av[j] *= numpy.conj(self.houses[j].alpha)<EOL><DEDENT>if k+<NUM_LIT:1> < N:<EOL><INDENT>house = House(Av[k+<NUM_LIT:1>:])<EOL>self.houses.append(house)<EOL>Av[k+<NUM_LIT:1>:] = house.apply(Av[k+<NUM_LIT:1>:]) * numpy.conj(house.alpha)<EOL>self.H[:k+<NUM_LIT:2>, [k]] = Av[:k+<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>self.H[:k+<NUM_LIT:1>, [k]] = Av[:k+<NUM_LIT:1>]<EOL><DEDENT>self.H[k+<NUM_LIT:1>, k] = numpy.abs(self.H[k+<NUM_LIT:1>, k])<EOL>if self.H[k+<NUM_LIT:1>, k] / numpy.linalg.norm(self.H[:k+<NUM_LIT:2>, :k+<NUM_LIT:1>], <NUM_LIT:2>)<= <NUM_LIT>:<EOL><INDENT>self.invariant = True<EOL><DEDENT>else:<EOL><INDENT>vnew = numpy.zeros((N, <NUM_LIT:1>), dtype=self.dtype)<EOL>vnew[k+<NUM_LIT:1>] = <NUM_LIT:1><EOL>for j in range(k+<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>vnew[j:] = self.houses[j].apply(vnew[j:])<EOL><DEDENT>self.V[:, [k+<NUM_LIT:1>]] = vnew * self.houses[-<NUM_LIT:1>].alpha<EOL><DEDENT><DEDENT>else:<EOL><INDENT>start = <NUM_LIT:0><EOL>if self.ortho == '<STR_LIT>':<EOL><INDENT>start = k<EOL>if k > <NUM_LIT:0>:<EOL><INDENT>self.H[k-<NUM_LIT:1>, k] = self.H[k, k-<NUM_LIT:1>]<EOL>if self.M is not Noneand not isinstance(self.M, IdentityLinearOperator):<EOL><INDENT>Av -= self.H[k, k-<NUM_LIT:1>] * self.P[:, [k-<NUM_LIT:1>]]<EOL><DEDENT>else:<EOL><INDENT>Av -= self.H[k, k-<NUM_LIT:1>] * self.V[:, [k-<NUM_LIT:1>]]<EOL><DEDENT><DEDENT><DEDENT>for reortho in range(self.reorthos+<NUM_LIT:1>):<EOL><INDENT>for j in range(start, k+<NUM_LIT:1>):<EOL><INDENT>alpha = inner(self.V[:, [j]], Av, ip_B=self.ip_B)[<NUM_LIT:0>, <NUM_LIT:0>]<EOL>if self.ortho == '<STR_LIT>':<EOL><INDENT>if abs(alpha.imag) > <NUM_LIT>:<EOL><INDENT>warnings.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(self.iter, abs(alpha.imag)))<EOL><DEDENT>alpha = alpha.real<EOL><DEDENT>self.H[j, k] += alpha<EOL>if self.M is not None:<EOL><INDENT>Av -= alpha * self.P[:, [j]]<EOL><DEDENT>else:<EOL><INDENT>Av -= alpha * self.V[:, [j]]<EOL><DEDENT><DEDENT><DEDENT>if self.M is not None:<EOL><INDENT>MAv = self.M * Av<EOL>self.H[k+<NUM_LIT:1>, k] = norm(Av, MAv, ip_B=self.ip_B)<EOL><DEDENT>else:<EOL><INDENT>self.H[k+<NUM_LIT:1>, k] = norm(Av, ip_B=self.ip_B)<EOL><DEDENT>if self.H[k+<NUM_LIT:1>, k] / numpy.linalg.norm(self.H[:k+<NUM_LIT:2>, :k+<NUM_LIT:1>], <NUM_LIT:2>)<= <NUM_LIT>:<EOL><INDENT>self.invariant = True<EOL><DEDENT>else:<EOL><INDENT>if self.M is not None:<EOL><INDENT>self.P[:, [k+<NUM_LIT:1>]] = Av / self.H[k+<NUM_LIT:1>, k]<EOL>self.V[:, [k+<NUM_LIT:1>]] = MAv / self.H[k+<NUM_LIT:1>, k]<EOL><DEDENT>else:<EOL><INDENT>self.V[:, [k+<NUM_LIT:1>]] = Av / self.H[k+<NUM_LIT:1>, k]<EOL><DEDENT><DEDENT><DEDENT>self.iter += <NUM_LIT:1><EOL>
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