def test_execute(self): n = 50 adjacencyMatrix = getPlanarGraph(n) network = Network(adjacencyMatrix) # sprawdzenie metody alg = PlanarMIS(network) alg.execute() # sprawdzanie: # standardowo jak w MIS for node in network.ndList: if node.memory['is_in_final_MIS'] == True: for neigh in node.neighbors: self.failIf(network.ndList[neigh].memory['is_in_final_MIS'] == True) # jesli wezel jest zdominowany, to fail jesli ma w swoim otoczeniu same zdominowane wezly elif node.memory['is_in_final_MIS'] == False: neigh_states = [network.ndList[neigh].memory['is_in_final_MIS'] for neigh in node.neighbors] self.failIf(all([state == False for state in neigh_states])) # jesli wezel nie jest ani dominatorem ani zdominownay, to fail else: self.fail("nieprawidlowy stan wezla")
def entropy_rate(weighted_adj_matrix, stat_dist=None, base=2, print_prefix=''): print(print_prefix + 'calc entropy rate') if stat_dist is None: stat_dist = stationary_dist(weighted_adj_matrix) assert not np.any(stat_dist < 0) assert np.isclose(stat_dist.sum(), 1.) # assert np.all(weighted_adj_matrix.sum(axis=0) > 0) if scipy.sparse.issparse(weighted_adj_matrix): if not isinstance(weighted_adj_matrix, csc_matrix): weighted_adj_matrix = weighted_adj_matrix.tocsc() get_col = weighted_adj_matrix.getcol col_entropy = (get_col(i).data for i in xrange(weighted_adj_matrix.shape[0])) col_entropy = np.array(map(lambda x: stats.entropy(x, base=base), col_entropy)).flatten() else: col_entropy = np.array(stats.entropy(weighted_adj_matrix, base=base)).flatten() stat_dist = np.array(stat_dist).flatten() assert stat_dist.shape == col_entropy.shape col_entropy *= stat_dist finite_elements = np.isfinite(col_entropy) if not all(finite_elements): print(print_prefix + 'WARN: entropy rate contains not finite elements. (inf, nan)') rate = np.sum(col_entropy[finite_elements]) if not np.isfinite(rate): print(print_prefix + 'entropy rate not finite') exit() return rate
def v(self, formula, world): if type(formula) == Atom: return formula in self.val[world] elif type(formula) == Not: return not self.v(formula.child, world) elif type(formula) == Or: return any(self.v(child, world) for child in formula.children) elif type(formula) == And: return all(self.v(child, world) for child in formula.children) elif type(formula) == Imp: return not self.v(formula.leftChild, world) or self.v( formula.rightChild, world) elif type(formula) == Iff: return self.v(formula.leftChild, world) is self.v( formula.rightChild, world) elif type(formula) == modalLogic.K: nodes = [] for i in range(len(self.nodeList)): if self.rel[formula.agent][self.nodeList.index(world)][i] == 1: nodes.append(self.nodeList[i]) # print("All worlds reachable from", world," by agent", formula.agent, ": ", nodes) return all(self.v(formula.child, k) for k in nodes) elif type(formula) == modalLogic.M: nodes = [] for i in range(len(self.nodeList)): if self.rel[formula.agent][self.nodeList.index(world)][i] == 1: nodes.append(self.nodeList[i]) # print("All worlds reachable from", world," by agent", formula.agent, ": ", nodes) return any(self.v(formula.child, k) for k in nodes) #What happens when #a. world vanishes upon updating #b. all worlds vanish upon updating elif type(formula) == O: self.updateModel(formula.observation) if world in self.nodeList: return self.v(formula.child, world) else: return True print( 'The observation does not hold true for any of the worlds in the model, and so the expression evaluates to True by default!' )
def print_dict_table(data, cols=None, rows=None, index_name='', shorten_values=-1, values_unit='', empty_val='-', title=None, cell_spacing_char=' ', spacing=4): if isinstance(data, dict) and all( [isinstance(i, dict) for i in data.values()]): cols = sorted(data.keys()) if cols is None else cols cols = [str(i) for i in cols] rows = sorted(set(j for i in data.values() for j in i.keys())) if rows is None else rows col_width = {col_name: len(col_name) + spacing for col_name in cols} col_width[index_name] = max(max([len(i) + spacing for i in rows]), len(index_name) + spacing) table_data = [] for col_name in cols: for row_id, row_name in enumerate(rows): try: value = str(data[col_name] [row_name])[:shorten_values] + values_unit except: value = str(empty_val) col_width[col_name] = max(col_width[col_name], len(value) + spacing) if len(table_data) <= row_id: table_data.append([]) table_data[row_id].append(value) for col_id, col_name in enumerate(cols): for row_id, row_name in enumerate(rows): table_data[row_id][col_id] = str( table_data[row_id][col_id]).center(col_width[col_name], cell_spacing_char[0]) table_width = sum(col_width.values()) + len(col_width) - 1 if not title is None: print str(title).center(table_width, '=') print_line = index_name.center(col_width[index_name]) for col_name in cols: print_line += '|' + col_name.center(col_width[col_name]) print print_line print_line = '-' * col_width[index_name] for idx, col_name in enumerate(cols): print_line += '+' print_line += '-' * col_width[col_name] print print_line for row_idx, i in enumerate(table_data): print_line = rows[row_idx].center(col_width[index_name]) for col_idx, colname in enumerate(cols): print_line += '|' + table_data[row_idx][col_idx] print print_line print '=' * table_width
def test_executeWithoutJoiningSubgraphs(self): n = 10 adjacencyMatrix = getPlanarGraph(n) network = Network(adjacencyMatrix) # sprawdzenie metody alg = PlanarMIS(network) alg._executeWithoutJoiningSubgraphs() # sprawdzanie: # po kolei dla kazdego poddrzewa # poddrzew bedzie mniej niz n/2 for i in range(n/2): for node in network.ndList: # fail jesli wezel nie ma nadal przydzielonego poddrzewa self.failIf(not node.memory.has_key('tree_num')) # wybieranie tylko wezlow z podgrafu nr i if node.memory['tree_num'] != i: continue # fail jesli sasiedzi wezla sa z innego poddrzewa neighbors = node.memory['neighbors_cp'] for neigh in neighbors: sub = network.ndList[neigh].memory['tree_num'] if sub != i: print 'wezel: ', node.ID, 'sasiad:', neigh self.drawGraph(network.ndList, adjacencyMatrix) self.fail('podgraf mial byc nr ' + str(i)+ ' a jest '+ str(sub)) # self.failIf(sub != i) # jesli wezel jest dominatorem, to fail jesli jego sasiad tez jest if node.memory['state_subgraph'] == 'dominator': for neigh in neighbors: self.failIf(network.ndList[neigh].memory['state_subgraph'] == 'dominator') # jesli wezel jest zdominowany, to fail jesli ma w swoim otoczeniu same zdominowane wezly elif node.memory['state_subgraph'] == 'dominated': neigh_states = [network.ndList[neigh].memory['state_subgraph'] for neigh in neighbors] self.failIf(all([state == 'dominated' for state in neigh_states])) # jesli wezel nie jest ani dominatorem ani zdominownay, to fail else: self.fail("nieprawidlowy stan wezla:", node.memory['state_subgraph'])
def is_refactor(lines, revision, file, refactorings): candidates = refactorings[(refactorings.sha == revision) & (refactorings.file == file)] l = [list(range(begin, end + 1)) for begin, end in zip(candidates.begin, candidates.end)] l_flat = [item for sublist in l for item in sublist] l_flat = set(l_flat) # print("%s: %str: " % (file, str(l_flat))) # because all([]) evaluates to true if len(l_flat) == 0: return False is_refactor = all(line_num in l_flat for line_num in lines) return is_refactor
def checkIfMISisCorrect(self, nodesList): for node in nodesList: # stany wszystkich sasiadow states = [nodesList[neigh].memory['state'] for neigh in node.neighbors] if node.memory['state'] == 'not_in_MIS': # fail jesli wszystkie wezly tez nie sa w MIS if all( [ state == 'not_in_MIS' for state in states ] ): self.fail('all states are \'not in MIS\'') # pass elif node.memory['state'] == 'in_MIS': self.failIf(any([state == 'in_MIS' for state in states])) else: self.fail('nieprawidlowy stan')
def sequential_to_parallel_count_max(seq_path_list): max_changes = 0 path_list = copy.deepcopy(seq_path_list) longest = len(max(path_list, key=len)) # For each node, which particle ended up here? resting_place = {} # location # : particle # for i in range(len(path_list)): resting_place[path_list[i][-1]] = i #util.list_print(path_list) #print(resting_place) # Remember whether we have seen this node yet have_seen = [False for i in range(len(path_list))] j = 0 while not all(have_seen): for i, seq_path in enumerate(path_list): #print("j = {}, i = {}".format(j, i)) if j < len(seq_path): cur_loc = seq_path[j] if not have_seen[cur_loc]: # Perform the cut-and-paste op if necessary if j + 1 < len(seq_path): path_list[resting_place[cur_loc]] += seq_path[j + 1:] if len(path_list[resting_place[cur_loc]]) > longest: longest = len(path_list[resting_place[cur_loc]]) max_changes += 1 path_list[i] = seq_path[:j + 1] # Update resting places temp = resting_place[seq_path[-1]] resting_place[seq_path[-1]] = resting_place[cur_loc] resting_place[cur_loc] = temp have_seen[cur_loc] = True #parallel_path_list[i].append(cur_loc) j += 1 #util.int_list_print(seq_path_list) #print() #util.int_list_print(path_list) return path_list, (max_changes)
def add_poly_fit(data, deg=2, col_name=0, predict=10, best=2): prefix = 'poly fit ' if isinstance(data, pd.Series): data = pd.DataFrame(columns=[col_name], data=data) value_idx = np.invert(np.isnan(data[col_name])) x = list(data.index[value_idx]) y = list(data[col_name][value_idx]) y_mean = np.mean(y) y_std = np.std(y) trans_y_back = lambda x: [(i * y_std) + y_mean for i in x] y = (np.array(y) - y_mean) / y_std if len(x) != len(y) or len(x) < 2: print_f('WARNING: poly fit got no input') print_f('len x:', len(x)) print_f('len y:', len(y)) return used_mapping = False data_index_set = set(data.index) if all((isinstance(i, datetime.date) for i in x)): used_mapping = True x = [i.toordinal() for i in x] diffs = [x[i + 1] - x[i] for i in xrange(len(x) - 1)] diff = np.min(diffs) / 2 predict_idx = list(x) if isinstance(predict, int) and predict > 0: for i in xrange(predict * 2): predict_idx.append(predict_idx[-1] + diff) if not isinstance(deg, list): deg = [deg] aic_values = np.zeros(len(deg)) aic = lambda rss, n, k: n * np.log(float(rss) / n) + 2 * k for deg_idx, current_degree in enumerate(deg): data_set_name = prefix + str(current_degree) if isinstance(best, int) and 0 < best < len(deg): fitted_function, residuals, rank, singular_values, rcond = np.polyfit( x, y, current_degree, full=True) aic_values[deg_idx] = aic((residuals).sum(), len(x), current_degree + 1) else: fitted_function = np.polyfit(x, y, current_degree) fitted_function = np.poly1d(fitted_function) predicted_y = trans_y_back(np.polyval(fitted_function, predict_idx)) if used_mapping: tmp_idx = [ datetime.date.fromordinal(int(round(i))) for i in predict_idx ] else: tmp_idx = predict_idx fitted_frame = pd.Series(data=predicted_y, index=tmp_idx) all_index = sorted(data_index_set | set(tmp_idx)) data = data.reindex(all_index) data[data_set_name] = fitted_frame if isinstance(best, int) and 0 < best < len(deg): print_f('aic_values', aic_values) filtered_deg, aic_values = zip( *filter(lambda x: not np.isinf(x[1]), zip(deg, aic_values))) aic_values = np.array(aic_values) print_f('filtered aic_values', aic_values) print_f('filteder deg:', filtered_deg) aic_trans = np.exp(-0.5 * aic_values) aic_prob = aic_trans / aic_trans.sum() print_f('aic_probs', aic_prob) sorted_deg, sorted_aic = zip(*sorted( zip(filtered_deg, aic_prob), key=lambda x: x[1], reverse=True)) best_data = [data[prefix + str(i)] for i in sorted_deg[:best]] for i in deg: col_name_to_drop = prefix + str(i) data.drop(col_name_to_drop, axis=1, inplace=True) for idx, i in enumerate(sorted_deg[:best]): col_name = prefix + str(i) data[col_name] = best_data[idx] return data
def indicator_constraint(ploidy, max_likelihood_vafs, loci): count_alleles = Counter(list(chain(*loci))) return all([ count_alleles[idx] == max_likelihood_vafs[idx] * len(loci) * ploidy for locus in loci for idx in locus ])