def get_random_logic_formula(): alphabet = get_logic_alphabet() options = ['fariable', 'implies', 'not'] options_weights = [0.75, 0.125, 0.125] chosen = choice(options, p=options_weights) if chosen == 'fariable': indexes = range(0, 10000) weights = [] for i in indexes: weights.append(0.5**(i + 1)) index = choice(indexes, p=weights) return Node(alphabet[chosen], index=index) elif chosen == 'implies': child_1 = get_random_logic_formula() child_2 = get_random_logic_formula() children = [child_1, child_2] return Node(alphabet[chosen], children) elif chosen == 'not': children = [get_random_logic_formula()] return Node(alphabet[chosen], children)
def append(self, new_node): existing_node = self.node_dictionary.get(new_node.name, None) # We already have this node in our tree, use append existing function if existing_node is not None: # noinspection PyTypeChecker self.__append_existing(new_node, existing_node) return # New node came in with a non-empty parent parameter if new_node.parent != "": new_node_parent = self.node_dictionary.get(new_node.parent, None) # New node came in with existing parent if new_node_parent is not None: new_node_parent.append(child=new_node.name) self.node_dictionary[new_node_parent.name] = new_node_parent # New node came in with unknown parent else: root_parent = self.node_dictionary[self.root_node_name] new_parent_node = Node(new_node.parent) new_parent_node.append(child=new_node.name, parent=root_parent.name) root_parent.append(child=new_parent_node.name) self.node_dictionary[root_parent.name] = root_parent self.node_dictionary[new_parent_node.name] = new_parent_node if len(new_node.children) > 0: for child_node_name in new_node.children: existing_child_node = self.node_dictionary.get(child_node_name, None) if existing_child_node is not None: existing_child_node_parent = self.node_dictionary.get(existing_child_node.parent, None) existing_child_node_parent.remove_child(existing_child_node) existing_child_node.append(parent=new_node.name) self.node_dictionary[existing_child_node.name] = existing_child_node else: self.append(Node(child_node_name)) new_node_parent = self.node_dictionary.get(new_node.parent, None) if new_node_parent is None: # New node does not already exist, and does not have a parent root_parent = self.node_dictionary[self.root_node_name] new_node.parent = root_parent.name root_parent.append(child=new_node.name) self.node_dictionary[root_parent.name] = root_parent # Add the new node to the dictionary self.node_dictionary[new_node.name] = new_node
def handle_none_arg(arg, root): arg_id = arg['id'] optional = arg['optional'] new_node = Node(arg_id, '') root.add_to_leaves(new_node) if optional: optional_node = Node(None, None, True) root.add_to_leaves(optional_node) root.finalize_iteration()
def generate_default_tree(root): node1 = Node(uuid4().int, 'node1', parent=root, parent_id=root.id) node2 = Node(uuid4().int, 'node2', parent=node1, parent_id=node1.id) node3 = Node(uuid4().int, 'node3', parent=node2, parent_id=node2.id) node4 = Node(uuid4().int, 'node4', parent=node3, parent_id=node3.id) node5 = Node(uuid4().int, 'node5', parent=node4, parent_id=node4.id) node6 = Node(uuid4().int, 'node6', parent=node1, parent_id=node1.id) node7 = Node(uuid4().int, 'node7', parent=node6, parent_id=node6.id) node8 = Node(uuid4().int, 'node8', parent=node7, parent_id=node7.id) node9 = Node(uuid4().int, 'node9', parent=node8, parent_id=node8.id) node10 = Node(uuid4().int, 'node10', parent=node9, parent_id=node9.id) return root
def handle_fixed_arg(arg, root): arg_id = arg['id'] optional = arg['optional'] val = arg['values']['value'] new_node = Node(arg_id, val) root.add_to_leaves(new_node) if optional: optional_node = Node(None, None, True) root.add_to_leaves(optional_node) root.finalize_iteration()
def handle_array_arg(arg, root): arg_id = arg['id'] optional = arg['optional'] val_array = arg['values']['array'] for val in val_array: new_node = Node(arg_id, val) root.add_to_leaves(new_node) if optional: optional_node = Node(None, None, True) root.add_to_leaves(optional_node) root.finalize_iteration()
def to_node(string, alphabet): symbol = False index = -1 children = [] if len(string): drawing = string[0] for alphabet_symbol in alphabet.values(): if alphabet_symbol.drawing == drawing: symbol = alphabet_symbol if symbol: if len(string) > 1 and string[1] == '_': index = get_index(string) if index == -1: return False children_as_strings = get_children(string) if children_as_strings: for child_as_string in children_as_strings: children.append(to_node(child_as_string, alphabet)) return Node(symbol, children, index) return False
def handle_step_arg(arg, root): arg_id = arg['id'] optional = arg['optional'] val_init = arg['values']['from'] val_end = arg['values']['to'] val_step = arg['values']['step'] for val in range(val_init, val_end + 1, val_step): new_node = Node(arg_id, val) root.add_to_leaves(new_node) if optional: optional_node = Node(None, None, True) root.add_to_leaves(optional_node) root.finalize_iteration()
def __init__(self, node_dictionary=None): # Mutable default argument if node_dictionary is None: node_dictionary = {self.root_node_name: Node(self.root_node_name)} self.node_dictionary = node_dictionary
def __append_existing(self, new_node, existing_node): # All existing nodes will have a parent, there's no way to add a node without a parent being set existing_parent = self.node_dictionary.get(existing_node.parent, None) # New node came in with a non-empty parent parameter if new_node.parent != "": new_node_parent = self.node_dictionary.get(existing_node.parent, None) # We know the parent already and should switch parents if new_node_parent is not None: existing_parent.remove_child(existing_node) self.node_dictionary[existing_parent.name] = existing_parent # Recursively add new parent new_node_new_parent = Node(new_node.parent) new_node_new_parent.append(child=new_node.name) self.append(new_node_new_parent) # The new node has children, merge old children with new children if len(new_node.children) > 0: # Make sure the new children exist, add them if not for child_name in new_node.children: child = self.node_dictionary.get(child_name, None) if child is None: self.append(Node(child_name)) else: existing_child_parent = self.node_dictionary.get( child.parent, None) existing_child_parent.remove_child(child) child.append(parent=new_node.name) self.node_dictionary[child.name] = child # Add old children to new children new_node.children += existing_node.children # Existing node append without specifying new parent should keep old parent if new_node.parent == "": new_node.parent = existing_node.parent # Add node to dictionary self.node_dictionary[existing_node.name] = new_node
def insert(self, val) -> bool: curr = self.__root prev = None while curr: prev = curr if val > curr.val: curr = curr.right elif val <= curr.val: curr = curr.left if val > prev.val: prev.right = Node(val) return True else: prev.left = Node(val) return True return False
def __append_existing(self, new_node, existing_node): # All existing nodes will have a parent, there's no way to add a node without a parent being set existing_parent = self.node_dictionary.get(existing_node.parent, None) # New node came in with a non-empty parent parameter if new_node.parent != "": new_node_parent = self.node_dictionary.get(existing_node.parent, None) # We know the parent already and should switch parents if new_node_parent is not None: existing_parent.remove_child(existing_node) self.node_dictionary[existing_parent.name] = existing_parent # Recursively add new parent new_node_new_parent = Node(new_node.parent) new_node_new_parent.append(child=new_node.name) self.append(new_node_new_parent) # The new node has children, merge old children with new children if len(new_node.children) > 0: # Make sure the new children exist, add them if not for child_name in new_node.children: child = self.node_dictionary.get(child_name, None) if child is None: self.append(Node(child_name)) else: existing_child_parent = self.node_dictionary.get(child.parent, None) existing_child_parent.remove_child(child) child.append(parent=new_node.name) self.node_dictionary[child.name] = child # Add old children to new children new_node.children += existing_node.children # Existing node append without specifying new parent should keep old parent if new_node.parent == "": new_node.parent = existing_node.parent # Add node to dictionary self.node_dictionary[existing_node.name] = new_node
def get_children(children: []) -> [Node]: nodes = [] for child in children: nodes.append( Node(child["question"], child["typical_answer"], [[preprocess(x[0]), preprocess(x[1])] for x in child["solutions"]], get_children(child["children"]))) return nodes
class Tree: def __init__(self, root=None): if root!=None: self.root = root else: self.root = Node() def __call__(self, *args, **kwargs): return self.root(*args, **kwargs) def __str__(self): return str(self.root) def traverse(self): return self.root.traverse()
def build_tree(self, params): self.bet_sizing = params['bet_sizing'] self.limit_to_street = params['limit_to_street'] root = Node() root.current_player = params['current_player'] root.street = params['street'] root.board = params['board'].clone() root.bets = params['bets'].clone() self._build_tree_dfs(root) return root
def train(self, x: np.ndarray, y: np.ndarray): """ Train the Decision Tree on input data :param x: Matrix with rows as observations and columns as features. :param y: A single column matrix with the same number of rows as the input parameter x """ assert (x.shape[0] == y.shape[0]) assert (y.shape[1] == 1) self.head = Node(data=x, labels=y, max_depth=self.max_depth, min_node_points=self.min_node_points) self.trained = True
def create_node( self, parent_id: Optional[int], value: str, node_id: int = None, children: Tuple[Node] = tuple(), is_deleted: bool = False, ): node_id = node_id if node_id else uuid4().int parent_node = self.get_node_by_id(parent_id) parent_node = parent_node if parent_node else self.tree new_node = Node( node_id, value=value, parent_id=parent_id, parent=parent_node, children=children, is_deleted=parent_node.is_deleted, ) return new_node
class TestNodeMethods(unittest.TestCase): def setUp(self): # Tree from the task self.parent = Node(5) new_node1 = Node(3) new_node2 = Node(2) new_node3 = Node(5) new_node1.set_left_node(new_node2) new_node1.set_right_node(new_node3) self.parent.set_left_node(new_node1) new_node4 = Node(7) new_node4.set_left_node(Node(1)) new_node5 = Node(0) new_node5.set_left_node(Node(2)) new_node6 = Node(8) new_node6.set_right_node(Node(5)) new_node5.set_right_node(new_node6) new_node4.set_right_node(new_node5) self.parent.set_right_node(new_node4) def test_count(self): self.assertEqual(self.parent.get_count(), 10) def test_sum(self): self.assertEqual(self.parent.get_sum(), 38) def test_avg(self): self.assertEqual(self.parent.get_avg(), 3.8) def test_median(self): self.assertEqual(self.parent.get_median(), 4)
def append(self, new_node): existing_node = self.node_dictionary.get(new_node.name, None) # We already have this node in our tree, use append existing function if existing_node is not None: # noinspection PyTypeChecker self.__append_existing(new_node, existing_node) return # New node came in with a non-empty parent parameter if new_node.parent != "": new_node_parent = self.node_dictionary.get(new_node.parent, None) # New node came in with existing parent if new_node_parent is not None: new_node_parent.append(child=new_node.name) self.node_dictionary[new_node_parent.name] = new_node_parent # New node came in with unknown parent else: root_parent = self.node_dictionary[self.root_node_name] new_parent_node = Node(new_node.parent) new_parent_node.append(child=new_node.name, parent=root_parent.name) root_parent.append(child=new_parent_node.name) self.node_dictionary[root_parent.name] = root_parent self.node_dictionary[new_parent_node.name] = new_parent_node if len(new_node.children) > 0: for child_node_name in new_node.children: existing_child_node = self.node_dictionary.get( child_node_name, None) if existing_child_node is not None: existing_child_node_parent = self.node_dictionary.get( existing_child_node.parent, None) existing_child_node_parent.remove_child( existing_child_node) existing_child_node.append(parent=new_node.name) self.node_dictionary[ existing_child_node.name] = existing_child_node else: self.append(Node(child_node_name)) new_node_parent = self.node_dictionary.get(new_node.parent, None) if new_node_parent is None: # New node does not already exist, and does not have a parent root_parent = self.node_dictionary[self.root_node_name] new_node.parent = root_parent.name root_parent.append(child=new_node.name) self.node_dictionary[root_parent.name] = root_parent # Add the new node to the dictionary self.node_dictionary[new_node.name] = new_node
def __init__(self, root=None): if root!=None: self.root = root else: self.root = Node()
def __init__(self): self.tree = Node(1, 'root')
def search_BFS(initial_state, solution): solved = False visited_nodes = [] edge_nodes = [] initial_node = Node(initial_state) edge_nodes.append(initial_node) while (not solved) and len(edge_nodes) != 0: node = edge_nodes.pop(0) visited_nodes.append(node) if node.get_data() == solution: solved = True print("Node to return " + str(node)) return node else: data_node = node.get_data() # L son = [data_node[1], data_node[0], data_node[2], data_node[3]] left_son = Node(son) if not left_son.in_list(visited_nodes) and not left_son.in_list( edge_nodes): edge_nodes.append(left_son) # C son = [data_node[0], data_node[2], data_node[1], data_node[3]] central_son = Node(son) if not central_son.in_list( visited_nodes) and not central_son.in_list(edge_nodes): edge_nodes.append(central_son) # R son = [data_node[0], data_node[1], data_node[3], data_node[2]] right_son = Node(son) if not right_son.in_list(visited_nodes) and not right_son.in_list( edge_nodes): edge_nodes.append(right_son) node.set_children([left_son, central_son, right_son])
def create_tree(data): if data is None: return value = data[len(data) // 2] left_array = data[:len(data) // 2] if len(data) > 1 else None right_array = data[(len(data) // 2) + 1:] if len(data) > 1 else None return Node(value=value, left=create_tree(left_array), right=create_tree(right_array))
def initTree(): node2231 = Node(2231) node2232 = Node(2232) node2233 = Node(2233) node2131 = Node(2131) node21 = Node(21) node22 = Node(22) node21.set_children([node2131]) node22.set_children([node2231, node2232, node2233]) node1 = Node(1) node1.set_children([node21, node22]) tree = NTree(node1) tree.setRoot_node(node1) return tree
def _get_children_of_player(self, parent_node): assert (parent_node.current_player != constants.chance_player) children = [] # ?? # fold fold_node = Node() fold_node.node_type = constants.terminal_fold_node fold_node.terminal = True fold_node.current_player = 1 - parent_node.current_player fold_node.street = parent_node.street fold_node.board = parent_node.board fold_node.board_string = parent_node.board_string fold_node.bets = parent_node.bets.clone() children.append(fold_node) # check/transition call/terminal call is_check, is_transition_call, is_terminal_call = False, False, False # check - parent bets equal and first player to act, first round have no check node if parent_node.bets[0] == parent_node.bets[ 1] and parent_node.current_player == constants.p1_player: is_check = True # transition call # 1. PREFLOP round: # second player(p1) call at a equal bet # player call to a larger bet, and the bet is not BB, not all-in # 2. FLOP,TURN round, # second player(p2) call at a equal bet # player call to a larger bet, and the bet is not all-in if parent_node.street < Round.RIVER: if parent_node.street == Round.PREFLOP: cp = parent_node.current_player if parent_node.bets[0] == parent_node.bets[ 1] and cp == constants.p1_player: is_transition_call = True elif parent_node.bets[cp] < parent_node.bets[ 1 - cp] and arguments.stack > parent_node.bets[ 1 - cp] > arguments.BB: is_transition_call = True else: # FLOP, TURN cp = parent_node.current_player if parent_node.bets[0] == parent_node.bets[ 1] and cp == constants.p2_player: is_transition_call = True elif parent_node.bets[cp] < parent_node.bets[ 1 - cp] < arguments.stack: is_transition_call = True # terminal call if parent_node.street == Round.RIVER: cp = parent_node.current_player if parent_node.bets[0] == parent_node.bets[ 1] and cp == constants.p2_player: is_terminal_call = True elif parent_node.bets[cp] < parent_node.bets[1 - cp]: is_terminal_call = True FLAG = [is_check, is_transition_call, is_terminal_call] assert (FLAG.count(True) == 1) if is_check: check_node = Node() check_node.node_type = constants.check_node check_node.terminal = False check_node.current_player = 1 - parent_node.current_player check_node.street = parent_node.street check_node.board = parent_node.board check_node.board_string = parent_node.board_string check_node.bets = parent_node.bets.clone() children.append(check_node) elif is_transition_call: assert (False) chance_node = Node() chance_node.terminal = self.limit_to_street # terminal chance_node.node_type = constants.chance_node chance_node.street = parent_node.street chance_node.board = parent_node.board chance_node.board_string = parent_node.board_string chance_node.current_player = constants.chance_player chance_node.bets = parent_node.bets.clone().fill_( parent_node.bets.max()) children.append(chance_node) elif is_terminal_call: terminal_call_node = Node() terminal_call_node.node_type = constants.terminal_call_node terminal_call_node.terminal = True terminal_call_node.current_player = 1 - parent_node.current_player terminal_call_node.board = parent_node.board terminal_call_node.board_string = parent_node.board_string terminal_call_node.bets = parent_node.bets.clone().fill_( parent_node.bets.max()) children.append(terminal_call_node) else: raise Exception assert ([is_check, is_transition_call, is_terminal_call].count(True) == 1) # bet actions possible_bets = self.bet_sizing.get_possible_bets(parent_node) if possible_bets.dim() != 0: assert (possible_bets.size(1) == 2) for i in range(possible_bets.size(0)): child = Node() child.terminal = False child.node_type = constants.inner_node child.parent = parent_node child.current_player = 1 - parent_node.current_player child.street = parent_node.street child.board = parent_node.board child.board_string = parent_node.board_string child.bets = possible_bets[i] if child.bets[0] == 9000 == child.bets[1]: print("!!!") children.append(child) return children
def decode(address: str) -> Node: with open(address, "r") as f: json_in = json.loads(f.read()) node = Node(json_in["question"], json_in["typical_answer"], None, get_children(json_in["children"])) return node
def __init__(self,val): __root = Node(val)
def setUp(self): # Tree from the task self.parent = Node(5) new_node1 = Node(3) new_node2 = Node(2) new_node3 = Node(5) new_node1.set_left_node(new_node2) new_node1.set_right_node(new_node3) self.parent.set_left_node(new_node1) new_node4 = Node(7) new_node4.set_left_node(Node(1)) new_node5 = Node(0) new_node5.set_left_node(Node(2)) new_node6 = Node(8) new_node6.set_right_node(Node(5)) new_node5.set_right_node(new_node6) new_node4.set_right_node(new_node5) self.parent.set_right_node(new_node4)
def create_node(operation_array): # construct of this node # created_node = Node(0,0,0) while len(operation_array) > 1: # run the entire list eliminating parenthesis for i in range(len(operation_array)): if isinstance(operation_array[i], list): new_node = create_node(operation_array[i]) operation_array[i] = new_node # print(operation_array) # if everything is on the same level (no parenthesis exist) ocurrences = 0 for value in operation_array: if isinstance(value, list): ocurrences += 1 # nth loop after everything is either node or same level if ocurrences == 0: current_ops = [] # get all the operands in this level for i in range(len(operation_array)): if not isinstance(operation_array[i], Node): if operation_array[i] in operators: current_ops.append([operation_array[i], i]) # select the hightest precedence one and build the tree from it highest = current_ops[0] for value in current_ops[::-1]: if precedence[value[0]] >= precedence[highest[0]]: highest = value # check if its bin or un curr_type = op_type[highest[0]] if curr_type == 'bin': # get next and previous value and build node l_value = copy.deepcopy(operation_array[highest[1] - 1]) r_value = copy.deepcopy(operation_array[highest[1] + 1]) # current spot in the list spot = highest[1] - 1 # pop from original array the values of both operands and the operator operation_array.pop(highest[1] + 1) operation_array.pop(highest[1]) operation_array.pop(highest[1] - 1) node = Node(l_value, r_value, 0) node.add_operation(highest[0]) operation_array.insert(spot, node) if curr_type == 'un': # get previous vaue and build node r_value = operation_array[highest[1] - 1] # current spot in the list spot = highest[1] - 1 operation_array.pop(highest[1]) operation_array.pop(highest[1] - 1) node = Node(0, r_value, 0) node.add_operation(highest[0]) operation_array.insert(spot, node) return operation_array[0]
from tree.node import Node node = Node() print('Empty node') print(node) print('Set value to 5') node.set_value(5) print(node) print('Create new node with value 3') node2 = Node(3) print(node2) print('Set node with value 3 as left node of the old one') node.set_left_node(node2) print(node) print('Parent node values') print('Sum: ', node.get_sum()) print('Avg: ', node.get_avg()) print('Count: ', node.get_count()) print('Median: ', node.get_median()) print() print('New node values') print('Sum: ', node2.get_sum())
if test['directory']['relativeToRoot']: jar_dir += test['directory']['path'] else: jar_dir = test['directory']['path'] jar = os.path.join(jar_dir, test['jar']) class_name = test['className'] meta = { "id": test_id, "resultsFile": test['resultsFile'], "args": [] } # benchmark metadata root_node = Node() for arg in test['args']: if "omitInCSV" not in arg: meta["args"].append({ "arg": arg['id'], # arg value can be read in java Config with this id "column": arg['name'] }) value_type = arg['values']['type'] if value_type in value_handlers: value_handlers[value_type](arg, root_node) root_node.finalize_iteration() leaf_nodes = [] root_node.collect_leaf_nodes(leaf_nodes)
from tree.node import Node # from tree.traversals import in_order_traversal, post_order_traversal, pre_order_traversal, level_order_traversal # from tree.height_of_tree import get_height # from tree.count_leaves import get_leaves # from tree.children_sum_property import is_sum_property # from tree.mirror_tree import mirror from tree.check_balanced_tree import is_balanced, is_balance_optimised if __name__ == '__main__': tree = Node(7) left = Node(5) right = Node(2) tree.left = left tree.right = right leftleft = Node(2) left.left = leftleft leftright = Node(3) left.right = leftright rightleft = Node(2) right.left = rightleft rightright = Node(7) right.right = rightright leftleftleft = Node(2) left.left.left = leftleftleft # print("-------------In Order Traversal-------------") # in_order_traversal(tree) # print("\n-------------Post Order Traversal-------------") # post_order_traversal(tree) # print("\n-------------Pre Order Traversal-------------") # pre_order_traversal(tree) # print("\n-------------Level Order Traversal-------------")