def create_family_tree(): ## Create the family tree tree = Tree() tree.create_node("Harry", "harry") # root node tree.create_node("Jane", "jane", parent="harry") tree.create_node("Bill", "bill", parent="harry") tree.create_node("Diane", "diane", parent="jane") tree.create_node("Mary", "mary", parent="diane") tree.create_node("Mark", "mark", parent="jane") return tree
class openstackData(): def __init__(self): self.resources = Tree() self.resources.create_node('CMS', 'CMS') def insert_resource(self, tag, parent, os_data=None, vsd_data=None, vsc_data=None, vrs_data=None, user_data=None): self.resources.create_node(tag, tag, parent=parent, os_data=os_data, vrs_data=vrs_data, vsd_data=vsd_data, vsc_data=vsc_data, user_data=user_data) def print_openstackData(self): self.resources.show(line_type="ascii-em") def delete_resource(self, tag): resp = self.resources.remove_node(tag) if resp < 1: raise Exception("Resource removal failed.") def get_resource(self, tag): resp = self.resources.get_node(tag) if not isinstance(resp, Node): raise Exception("Returned node is not of type Node") return resp def get_children_resources(self, tag): resp = self.resources.children(tag) if not isinstance(resp, list): raise Exception("Did not get a list") return resp def is_resource_present(self, tag): resp = self.resources.contains(tag) return resp def move_resource(self, tag, new_parent): self.resources.move_node(tag, new_parent) def update_resource(self, tag, os_data=None, vsd_data=None, vsc_data=None, vrs_data=None, user_data=None): self.resources.update_node(tag, os_data=os_data, vsd_data=vsd_data, vsc_data=vsc_data, vrs_data=vrs_data, user_data=user_data)
print(','.join([tree[node].tag for node in tree.expand_tree()])) example("All family members (with identifiers) but Diane's sub-family:") tree.show(idhidden=False, filter=lambda x: x.identifier != 'diane') example("Let me introduce Diane family only:") sub_t = tree.subtree('diane') sub_t.show() example("Children of Diane:") for child in tree.is_branch('diane'): print(tree[child].tag) example("New members join Jill's family:") new_tree = Tree() new_tree.create_node("n1", 1) # root node new_tree.create_node("n2", 2, parent=1) new_tree.create_node("n3", 3, parent=1) tree.paste('bill', new_tree) tree.show() example("They leave after a while:") tree.remove_node(1) tree.show() example("Now Mary moves to live with grandfather Harry:") tree.move_node('mary', 'harry') tree.show() example("A big family for Mark to send message to the oldest Harry:") print(','.join([tree[node].tag for node in tree.rsearch('mark')]))
class Search: def __init__ (self, init_str, arg, cost_flag): self.cost_flag = cost_flag self.tree = Tree() self.arg = arg init_state = State(0,0,init_str) self.length = len(init_str) #length of puzzle used for making moves #data structure for BFS is a Queue import Queue class for L if arg == "BFS": self.L = Queue() self.L.put(init_state) else: if arg not in ["DFS","UCS","A-STAR","GS"]: arg = "DFS" #if not a valid search default to DFS self.L = [init_state] #only BFS uses Queue every other search will use a list self.expanded = [] #list of expanded states self.cur_tree_id = 1 #unique tree id per state added to the tree self.tree.create_node(init_state.string,init_state.tid) #creates the root node of the search tree # returns the needed node from structure L # in GS,UCS,A-STAR it requires a min heap. # use a list but sort the list by the given f-costs # UCS : "cost to of a path(number of moves)" # A-STAR : "path cost + number of tiles misplaced" # GS : "number of tiles misplaced" # since list does not have a remove from front # reverse the sorted list and pop. def get(self): if isinstance(self.L, Queue): state = self.L.get() elif isinstance(self.L, list): if self.arg == "UCS": self.L.sort(key = lambda n: (n.cost, n.tid), reverse=True) elif self.arg == "A-STAR": self.L.sort(key = lambda n: ((n.cost + n.num_misplaced),n.tid), reverse=True) #returns lowest f cost where f(n)=h(n) elif self.arg == "GS": self.L.sort(key = lambda n: (n.num_misplaced,n.tid), reverse=True) state = self.L.pop() return state def put(self,state): if isinstance(self.L, Queue): self.L.put(state) elif isinstance(self.L, list): self.L.append(state) def is_empty(self): if isinstance(self.L, Queue): return self.L.empty() elif isinstance(self.L, list): return not bool(self.L) #bool ([]) returns false # generic search will handle all searches # the node to chosen for the search will depend on the get method def search(self): while not self.is_empty(): node = self.get() if self.is_goal(node): break else: self.expand(node) self.path_to_goal(node) def expand(self,state): if not self.is_in_expanded(state): self.expanded.append(state) # for i in range(self.length): if self.cost_flag: #cost will be the steps for x cost = abs(state.string.index("x") - i) else: cost = state.cost + 1 #total path cost successor = State(self.cur_tree_id,cost, state.string) #create a copy of node to apply move then add to L and tree self.cur_tree_id += 1 if i != state.string.index('x'): #don't move x into itself successor.move(i) self.put(successor) #put state into data structure L self.add_to_tree(successor,state) def is_in_expanded (self, state): # checks expanded if a state as already been exanded return state in self.expanded def is_goal (self, state): # returns true if state as no misplaced tiles return not bool(state.num_misplaced) def add_to_tree (self, state, parent): self.tree.create_node(state.string, state.tid, parent=parent.tid) def path_to_goal (self, goal): node = self.tree[goal.tid] move_list = [node] while not node.is_root(): node = self.tree[node.bpointer] move_list.append(node) #reverse move_list because first node is the goal and you want first node to be root Path(root->goal) move_list = list(reversed(move_list)) print "board movements start at the left index 0 " print "example initial wxb step 1: move 0 xwb" print "step 0: ", move_list[0].tag for i in range(1, len(move_list)): print "step %i: " % i, "move %i"% move_list[i].tag.index("x"), move_list[i].tag
class DecisionTree(object): ATTRIBUTE_VALUES = ['duza', 'mala', 'srednia'] def __init__(self): self.decision_tree = Tree() def create_identifier(self, *args): return ':'.join(args) def count_all_attr_entropy(self, maly, sredni, duzy): maly_count = count_attr_entropy(*maly) srednia_count = count_attr_entropy(*sredni) duzy_count = count_attr_entropy(*duzy) return math.fabs(sum([maly_count, srednia_count, duzy_count])) def entropy_counter(self, atrr_names, training_data=None): train_zipped = zip(*training_data) result_bools = train_zipped.pop(len(train_zipped)-1) train_length = len(train_zipped[0]) mala_true_count = 0 sred_true_count = 0 duza_true_count = 0 mala_false_count = 0 sred_false_count = 0 duza_false_count = 0 slownik = {} for nr, x in enumerate(train_zipped): slownik[atrr_names.get(nr)] = zip(x, result_bools) results = {} for nr, value in enumerate(slownik.values()): name = atrr_names.get(nr) mala_true_count = value.count(('mala', True)) sred_true_count = value.count(('srednia', True)) duza_true_count = value.count(('duza', True)) mala_false_count = value.count(('mala', False)) sred_false_count = value.count(('srednia', False)) duza_false_count = value.count(('duza', False)) mala_count = float(mala_true_count+mala_false_count) sred_count = float(sred_true_count+sred_false_count) duza_count = float(duza_true_count+duza_false_count) mala_propability = ( 0 if not mala_count else mala_true_count/mala_count ) sred_propability = ( 0 if not sred_count else sred_true_count/sred_count ) duza_propability = ( 0 if not duza_count else duza_true_count/duza_count ) entropy = {} entropy['mala'] = count_entropy(mala_propability) entropy['srednia'] = count_entropy(sred_propability) entropy['duza'] = count_entropy(duza_propability) attr_entropy = self.count_all_attr_entropy( (mala_count/train_length, mala_propability), (sred_count/train_length, sred_propability), (duza_count/train_length, duza_propability) ) results[name] = { entropy['mala']: 'mala', entropy['srednia']: 'srednia', entropy['duza']: 'duza', } return results, attr_entropy def get_lower_entropy(self, counted_attribs, attr_names=None): if not attr_names: return None counted_attribs, comp_entropy = counted_attribs min_value = 1, '_', '_' for key in counted_attribs.keys(): value_dict = counted_attribs[key] if isinstance(value_dict, dict): new_value = min(value_dict.keys()) if new_value < min_value[0]: min_value = ( new_value, key, counted_attribs[key].get(new_value), ) return min_value, comp_entropy def generate_tree( self, parent=None, atrr_names=None, training_data=None ): if not atrr_names: return self.decision_tree counted_attribs = self.entropy_counter( atrr_names=atrr_names, training_data=training_data ) lower_entropy, comp_entropy = self.get_lower_entropy( counted_attribs, attr_names=atrr_names ) if not lower_entropy: return self.decision_tree ATTRIBUTE_NAMES = {atrr_names[value]: value for value in atrr_names} entropy, attribute_name, attribute_value = lower_entropy attribute_line = ATTRIBUTE_NAMES.pop(attribute_name) if not self.decision_tree.nodes: root = self.create_identifier(attribute_name, attribute_name) self.decision_tree.create_node( name=attribute_name, identifier=root ) for attr_value in self.ATTRIBUTE_VALUES: name = self.create_identifier(attribute_name, attr_value) self.decision_tree.create_node( name=name, identifier=name, parent=root ) if attr_value != attribute_value: victory = self.create_identifier( attribute_name, attr_value, 'True' ) self.decision_tree.create_node( name=victory, identifier=victory, parent=name ) parent = self.create_identifier(attribute_name, attribute_value) elif parent: if entropy < comp_entropy: for attr_value in self.ATTRIBUTE_VALUES: name = self.create_identifier(attribute_name, attr_value) self.decision_tree.create_node( name=name, identifier=name, parent=parent ) if attr_value != attribute_value: victory = self.create_identifier( attribute_name, attr_value, 'True' ) self.decision_tree.create_node( name=victory, identifier=victory, parent=name ) else: atrr_names.pop(attribute_name) self.generate_tree( self.decision_tree, parent=parent, atrr_names=atrr_names, training_data=training_data ) parent = self.create_identifier(attribute_name, attribute_value) atrr_names.pop(attribute_line) new_attr_names = {} for nr, value in enumerate(atrr_names.values()): new_attr_names[nr] = value new_training_data = [ filter( lambda i: i != 'nie', [ y if nr != attribute_line else 'nie' for nr, y in enumerate(x) ] ) for x in training_data ] if len(new_training_data) > 1: self.generate_tree( parent=parent, atrr_names=new_attr_names, training_data=new_training_data ) return self.decision_tree
if new_score >= current_score: break else: current_score = new_score if __name__ == "__main__": file_name = sys.argv[1] tree = Tree() r = c = -1 #build initial tree with open(file_name, 'r') as fp: lines = fp.readlines() r, c = map(int, lines[0].split()) current_row = 0 tree.create_node(identifier="root") for line in lines[1:]: tree.create_node(LineMarker(current_row), identifier=current_row, parent="root") current_col = 0 for ch in line: if ch == '#': tree.create_node(SquareCommand(current_row, current_col, 0), parent=current_row) current_col += 1 current_row += 1 #print(tree) #try reduce optimize(tree, r)
# self.__identifier = (str(uuid.uuid1()) if identifier is None else # sanitize_id(str(identifier))) # self.name = name # self.expanded = expanded # self.__bpointer = None # self.__fpointer = [] def preorder_dfs(root): if root is None: return if __name__ == '__main__': tree = Tree() tree.create_node("F", "F") # root node tree.create_node("B", "B", parent="F") tree.create_node("A", "A", parent="B") tree.create_node("D", "D", parent="B") tree.create_node("C", "C", parent="D") tree.create_node("E", "E", parent="D") tree.create_node("G", "G", parent="F") tree.create_node("I", "I", parent="G") tree.create_node("H", "H", parent="I") tree.show("F") print("=" * 80) root = tree["F"] print(root.name)
class DecisionTree(object): ATTRIBUTE_VALUES = ['duza', 'mala', 'srednia'] def __init__(self): self.decision_tree = Tree() def create_identifier(self, *args): return ':'.join(args) def count_all_attr_entropy(self, maly, sredni, duzy): maly_count = count_attr_entropy(*maly) srednia_count = count_attr_entropy(*sredni) duzy_count = count_attr_entropy(*duzy) return math.fabs(sum([maly_count, srednia_count, duzy_count])) def entropy_counter(self, atrr_names, training_data=None): train_zipped = zip(*training_data) result_bools = train_zipped.pop(len(train_zipped) - 1) train_length = len(train_zipped[0]) mala_true_count = 0 sred_true_count = 0 duza_true_count = 0 mala_false_count = 0 sred_false_count = 0 duza_false_count = 0 slownik = {} for nr, x in enumerate(train_zipped): slownik[atrr_names.get(nr)] = zip(x, result_bools) results = {} for nr, value in enumerate(slownik.values()): name = atrr_names.get(nr) mala_true_count = value.count(('mala', True)) sred_true_count = value.count(('srednia', True)) duza_true_count = value.count(('duza', True)) mala_false_count = value.count(('mala', False)) sred_false_count = value.count(('srednia', False)) duza_false_count = value.count(('duza', False)) mala_count = float(mala_true_count + mala_false_count) sred_count = float(sred_true_count + sred_false_count) duza_count = float(duza_true_count + duza_false_count) mala_propability = (0 if not mala_count else mala_true_count / mala_count) sred_propability = (0 if not sred_count else sred_true_count / sred_count) duza_propability = (0 if not duza_count else duza_true_count / duza_count) entropy = {} entropy['mala'] = count_entropy(mala_propability) entropy['srednia'] = count_entropy(sred_propability) entropy['duza'] = count_entropy(duza_propability) attr_entropy = self.count_all_attr_entropy( (mala_count / train_length, mala_propability), (sred_count / train_length, sred_propability), (duza_count / train_length, duza_propability)) results[name] = { entropy['mala']: 'mala', entropy['srednia']: 'srednia', entropy['duza']: 'duza', } return results, attr_entropy def get_lower_entropy(self, counted_attribs, attr_names=None): if not attr_names: return None counted_attribs, comp_entropy = counted_attribs min_value = 1, '_', '_' for key in counted_attribs.keys(): value_dict = counted_attribs[key] if isinstance(value_dict, dict): new_value = min(value_dict.keys()) if new_value < min_value[0]: min_value = ( new_value, key, counted_attribs[key].get(new_value), ) return min_value, comp_entropy def generate_tree(self, parent=None, atrr_names=None, training_data=None): if not atrr_names: return self.decision_tree counted_attribs = self.entropy_counter(atrr_names=atrr_names, training_data=training_data) lower_entropy, comp_entropy = self.get_lower_entropy( counted_attribs, attr_names=atrr_names) if not lower_entropy: return self.decision_tree ATTRIBUTE_NAMES = {atrr_names[value]: value for value in atrr_names} entropy, attribute_name, attribute_value = lower_entropy attribute_line = ATTRIBUTE_NAMES.pop(attribute_name) if not self.decision_tree.nodes: root = self.create_identifier(attribute_name, attribute_name) self.decision_tree.create_node(name=attribute_name, identifier=root) for attr_value in self.ATTRIBUTE_VALUES: name = self.create_identifier(attribute_name, attr_value) self.decision_tree.create_node(name=name, identifier=name, parent=root) if attr_value != attribute_value: victory = self.create_identifier(attribute_name, attr_value, 'True') self.decision_tree.create_node(name=victory, identifier=victory, parent=name) parent = self.create_identifier(attribute_name, attribute_value) elif parent: if entropy < comp_entropy: for attr_value in self.ATTRIBUTE_VALUES: name = self.create_identifier(attribute_name, attr_value) self.decision_tree.create_node(name=name, identifier=name, parent=parent) if attr_value != attribute_value: victory = self.create_identifier( attribute_name, attr_value, 'True') self.decision_tree.create_node(name=victory, identifier=victory, parent=name) else: atrr_names.pop(attribute_name) self.generate_tree(self.decision_tree, parent=parent, atrr_names=atrr_names, training_data=training_data) parent = self.create_identifier(attribute_name, attribute_value) atrr_names.pop(attribute_line) new_attr_names = {} for nr, value in enumerate(atrr_names.values()): new_attr_names[nr] = value new_training_data = [ filter(lambda i: i != 'nie', [ y if nr != attribute_line else 'nie' for nr, y in enumerate(x) ]) for x in training_data ] if len(new_training_data) > 1: self.generate_tree(parent=parent, atrr_names=new_attr_names, training_data=new_training_data) return self.decision_tree