def insert_before_value(self, value, x): ''' This function is used to add element before given value params: value: any type x : any type ''' if self.head is None: raise Exception("List has no items") new_node = Node(value) # if first node has matched condition if self.head.data == x: new_node.next = self.head self.head = new_node return prev = self.head while prev: if prev.next.data == x: break prev = prev.next if prev is None: raise Exception("{} not exists in list".format(x)) new_node.next = prev.next prev.next = new_node
def _build_tree(x, y, f, random_state, root=Node(), depth=0): """ Build a decision tree for a given data. """ n_samples = len(y) # 1st base case : empty arrays. if n_samples == 0: return counts = np.bincount(y) n_classes = np.count_nonzero(counts) # 2nd base case : all node's labels are equal. if n_classes <= 1: return Leaf(y[0]) # 3rd base case : maximum depth or minimum sample size reached. if depth >= f.max_depth != -1 or n_samples <= f.min_samples_split != -1: return Leaf(counts.argmax()) # Train this node ... root.train(x, y, f.n_rounds, random_state) # ... and use it to split x z = root.split(x) assert z is not None # Recursive calls. root.left = _build_tree(x[~z], y[~z], f, random_state, Node(), depth + 1) root.right = _build_tree(x[z], y[z], f, random_state, Node(), depth + 1) return root
def test_add_child(self): update_queue = set() parent = Node(randomPK, update_queue) childPK = randomPK + 1 old_sync_hash = parent.get_sync_hash() child = Node(childPK, set()) parent.add_child(child) new_sync_hash = parent.get_sync_hash() self.assertEqual(child._parent, parent) self.assertIn(child, parent._children) self.assertEqual(parent._number_of_children(), 1) for x in sum((old_sync_hash, new_sync_hash), ()): if x != DEFAULT_HASH_VALUE: self.assertTrue(check_valid_hash(x)) self.assertTrue(TestNodeCore.check_sync_hash_old_new(old_sync_hash, new_sync_hash, False, True, False)) with self.assertRaises(NotImplementedError): parent.remove_child(childPK) # update_queue should have only parent added. self.assertSetEqual(parent._update_hash_queue, set([parent._pk, child._pk]))
def __init__(self, name='CLK%d', period=1,state=0): Node.__init__(self, name) self.add_output('CLK') self.initperiod = period self.period = period self.initstate = state self.state = None
def push(self, value): ''' This function is used to add element at the beginning params: value: any type ''' new_node = Node(value) new_node.next = self.head self.head = new_node return
def init_snake(self): # 左上方开始 snake = Snake() head_node = Node(img_path=GameConfig.snake_head_img) tail_node = Node(img_path=GameConfig.snake_tail_img) head_point = Point(1, 0) tail_point = Point(0, 0) snake.set_head(node=head_node, point=head_point) snake.set_tail(node=tail_node, point=tail_point) self.snake = snake
def test_beam_init(self): n1 = Node(0., 0., 0.) n2 = Node(10., 10., 0.) b1 = Beam(n1, n2) b1.properties['Area'] = 0.1 * 0.1 self.assertAlmostEqual(b1.length(), sqrt(200.)) self.assertAlmostEqual(b1.volume(), 0.01 * sqrt(200.)) self.assertTrue(b1.sizeOfEM() == 12)
def _recursive_populate(self, root, value): if value > root.value: if root.rchild is None: root.rchild = Node(value) else: self._recursive_populate(root.rchild, value) else: if root.lchild is None: root.lchild = Node(value) else: self._recursive_populate(root.lchild, value)
def create(list): if len(list) == 0: return None head = Node(value=list[0]) node = head for i in list[1:]: next = Node(value=i) node.next = next node = next return head
def reset_food(self): if self.food_images: food_img_path = self.food_images.pop() food_img = Node(img_path=food_img_path) else: self.food_images = self.get_food_imgs() # 重新吃所有图片 food_img_path = self.food_images.pop() food_img = Node(img_path=food_img_path) point = self.find_point() food = Food(node=food_img, point=point) self.food = food
def test_beam_transform(self): n1 = Node(0., 0., 0.) n2 = Node(10., 10., 0.) b1 = Beam(n1, n2) T = b1.calcT() p0 = np.dot(T, (0., 0., 0.)) self.almostEqual(p0, (0., 0., 0.)) p1 = np.dot(T, (10., 10., 0.)) self.almostEqual(p1, (sqrt(200.), 0., 0.))
def append(head, value): if not head: head = Node(value=value) return head node = head while node.next: node = node.next node.next = Node(value=value) return head
def timeslice(self, time): Node.timeslice(self,time) ev = self.event_available('IN',time) if ev: newstate = int(not ev.state) ev.set_processed() else: newstate = int(not self.in_port_states['IN']) if self.out_port_states['OUT'] != newstate: self.send_state_change('OUT',newstate, time) self.timeslice_updatestates(time)
def parse(self, shellLog): activeNodes=[] try: f = open(shellLog.discovery_log, 'r').readlines() for i in range(0, len(f)): node = Node() node.ip_addr = f[i].split(";")[0] node.mac_addr = f[i].split(";")[5] node.manufacturer_name = f[i].split(";")[6].split('\n')[0] node.node_status = NODE_STATUS.UP activeNodes.append(node) return activeNodes except Exception, msg: raise ParserFailed(msg)
def make_decision_split_node(node, feature_indices): """ :param node: Node Node to be split :param feature_indices: array-like of shape (D_try, ) Contains feature indices to be considered in the present split :return: tuple Tuple of left and right children nodes (to be placed on the stack) """ n, D = node.data.shape # Find best feature j (among 'feature_indices') and best threshold t for the split e_min = 1e100 j_min, t_min = 0, 0 for j in feature_indices: # Remove duplicate features dj = np.sort(np.unique(node.data[:, j])) # Compute candidate thresholds tj = (dj[1:] + dj[:-1]) / 2 # Compute Gini-impurity of resulting children nodes for each candidate threshold for t in tj: left_indices = node.data[:, j] <= t nl = np.sum(node.data[:, j] <= t) ll = node.labels[left_indices] el = nl * (1 - np.sum(np.square(np.bincount(ll) / nl))) nr = n - nl # lr = node.labels[node.data[:, j] > t] lr = node.labels[~left_indices] er = nr * (1 - np.sum(np.square(np.bincount(lr) / nr))) if el + er < e_min: e_min = el + er j_min = j t_min = t # Create children left = Node() right = Node() # Initialize 'left' and 'right' with the data subsets and labels # according to the optimal split found above left.data = node.data[node.data[:, j_min] <= t_min, :] left.labels = node.labels[node.data[:, j_min] <= t_min] right.data = node.data[node.data[:, j_min] > t_min, :] right.labels = node.labels[node.data[:, j_min] > t_min] node.left = left node.right = right node.feature = j_min node.threshold = t_min return left, right
def test_node_creation(self): node = Node(randomPK, set()) self.assertEqual(node._pk, randomPK) self.assertIsNone(node._parent) self.assertSetEqual(node._update_hash_queue ,set([node._pk])) self.assertListEqual(node._children, [])
def ucb_score(config: AlphaZeroConfig, parent: Node, child: Node): ''' The score for a node is based on its value, plus an exploration bonus based on the prior. ''' pb_c = math.log((parent.visit_count + config.pb_c_base + 1) / config.pb_c_base) + config.pb_c_init pb_c *= math.sqrt(parent.visit_count) / (child.visit_count + 1) # Classic UCB # pb_c = 1 * np.sqrt(np.log(parent.visit_count) / child.visit_count) if child.visit_count > 0 else float('inf') # XXX pi_hat influences the search priority prior_score = pb_c * child.prior # XXX Should we use V_hat during testing? Maybe we should just use true terminal values. This way, value prediction is really used only for training (features). # NOTE: we are choosing a good move for the player of the parent node and each node returns the ego-centric value value_score = child.sampled_value( ) if child.is_first_player == parent.is_first_player else ( 0 - child.sampled_value()) return prior_score + value_score
def addNode(self, elem): """ Add a new node with the specified value. :param elem: the node value. :return: the create node. """ newNode = Node(elem, elem) self.nextId += 1 return newNode
def test_get_children_chance_nodes(self): node = Node() node.board_string = '' node.board = card_to_string.string_to_cards(node.board_string) node.street = 0 node.num_bets = 0 node.current_player = constants.players.P1 node.bets = arg.IntTensor([1, 1]).to(arg.device) children = tree_builder.get_children_chance_nodes(node) for child in children: pass
def timeslice(self, time): timepass = time - self.lastslice lastslice = self.lastslice Node.timeslice(self, time) if self.state is None: self.state = self.initstate self.send_state_change('CLK', self.state, time) else: period = self.period while (timepass): period = period - 1 timepass = timepass - 1 if period == 0: self.state = int(not self.state) self.send_state_change('CLK', self.state, lastslice + (time - timepass)) period = self.initperiod self.period = period
def test_build_tree(self): params = TreeParams() params.root_node = Node() params.root_node.board = card_to_string.string_to_cards('') params.root_node.board_string = '' params.root_node.street = 0 params.root_node.current_player = constants.players.P1 params.root_node.bets = arg.IntTensor([1, 1]).to(arg.device) root = tree_builder.build_tree(params) tree_visulizer.draw_tree(root)
def build_tree(self, params): root = Node() root.street = params.root_node.street root.bets = params.root_node.bets.clone() root.current_player = params.root_node.current_player root.board = params.root_node.board.clone() root.board_string = params.root_node.board_string self.build_tree_dfs(root) return root
def get_children_chance_nodes(self, parent_node): children = [] next_boards = card_tools.get_second_round_boards() for board in next_boards: chance_node = Node(parent_node) chance_node.current_player = constants.players.P1 chance_node.street = parent_node.street + 1 chance_node.board = board chance_node.board_string = card_to_string.cards_to_string(board) chance_node.num_bets = 0 chance_node.action = chance_node.board_string children.append(chance_node) return children
def test_setting_getting_deleting_data(self): node = Node(randomPK, set()) self.assertDictEqual(node._info._data_holder, {}) for k, v in temp_info.iteritems(): setattr(node, k, v) self.assertEqual(getattr(node, k), v) node.abc = 124 self.assertEqual(node.abc, 124) node.abc += 1 self.assertEqual(node.abc, 125) del node.abc with self.assertRaises(AttributeError): temp = node.abc new_node = Node(randomPK, set(), **temp_info) for k,v in temp_info.iteritems(): self.assertEqual(getattr(new_node, k), v)
def handleNODE(self, fh, line): if self.step > 0: raise FEError('*NODE should be placed before all step definitions') nset = None nsetdat = set() # check for nset definition for part in line.parts: part = part.upper() if part.startswith("NSET="): _, nset = part.split("=") else: raise ParserError(line, '*NODE definition malformed!') # loop until EOF or new keyword line = self.nextline(fh) while not line.keyword and not line is EmptyLine: nid = self.parse_int(line.parts[0], minimum=1) if nid in self.nodemap: raise FEError("Nodes #%d redefined" % nid) # add to set if not nset is None: nsetdat.add(nid) # fetch coordinates x, y, z = 0., 0., 0. coords = line.parts[1:] ll = len(coords) if ll == 1: x = float(coords[0]) elif ll == 2: x, y = map(float, coords) elif ll == 3: x, y, z = map(float, coords) else: raise ParserError(line, '*NODE definition malformed!') self.nodemap[nid] = Node(x, y, z) # get next line line = self.nextline(fh) # Save or update nset if not nset is None: if nset in self.nset: self.nset[nset] += nsetdat else: self.nset[nset] = nsetdat return line
def timeslice(self, time): Node.timeslice(self, time) A = self.in_port_states['A'] B = self.in_port_states['B'] aevent = self.event_available('A',time) bevent = self.event_available('B',time) if aevent: aevent.set_processed() A = aevent.state if self.in_events.has_key('B'): bevent.set_processed() B = bevent.state result = self.operator(A, B) if result != self.lastout: self.lastout = result self.send_state_change('OUT', result, time) self.timeslice_updatestates(time)
def evaluate(node: Node, game: Game, network: Network, use_cpu: bool = False): ''' We use the neural network to obtain a value and policy prediction. ''' ego_rep = game.ego_board_representation() ego_value, ego_policy_logits = network.single_inference(ego_rep, use_cpu=use_cpu) # Transform ego-centric to absolute is_first_player = game.is_first_player_turn() value = game.ego2abs_value(is_first_player, ego_value) policy_logits = game.ego2abs_policy(is_first_player, ego_policy_logits) # Expand the node. node.is_first_player = is_first_player # print('eval', '%0.2f' % policy_logits.max()) policy = {a: math.exp(policy_logits[a]) for a in game.legal_actions()} policy_sum = sum(policy.values()) for action, p in policy.items(): node.children[action] = Node(p / policy_sum) # node.children[action] = Node(0) return value
def insert(head, index, value): if index < 0: return head if not head and index > 0: return head if index == 0: new = Node(value=value) new.next = head head = new return head node = head prev = None step = 0 while node and step < index: prev = node node = node.next step += 1 if not node: return head next = prev.next new = Node(value=value) prev.next = new new.next = next return head
def sum_linked_lists(root1, root2): num1 = 0 mult = 1 while root1 is not None: num1 += root1.data * mult root1 = root1.next mult *= 10 num2 = 0 mult = 1 while root2 is not None: num2 += root2.data * mult root2 = root2.next mult *= 10 result = num1 + num2 print "%s + %s = %s" % (num1, num2, result) result_list = None for x in str(result)[::-1]: if result_list is None: result_list = Node(x) else: result_list.append_to_tail(x) return result_list
def insert_after_value(self, value, x): ''' This function is used to add element after given value params: value: any type x : any type ''' if self.head is None: raise Exception("List has no items") new_node = Node(value) current = self.head while current: if current.data == x: break current = current.next if current is None: raise Exception("{} not exists in list".format(x)) new_node.next = current.next current.next = new_node
def put(self, key, val): # 如存在,先删除 if key in self.key2val: self.key2val[key]=val if len(self.key2val) >= self.cap: self.__remove_min_freq_key() self.key2val[key]=val self.key2freq[key]=1 self.freq2keys.setdefault(1,LRUCache()) self.freq2keys[1].add_last(Node(key,val)) self.min_freq=1
def test_build_tree(self): params = TreeParams() params.root_node = Node() params.root_node.board = card_to_string.string_to_cards('') params.root_node.board_string = '' params.root_node.street = 0 params.root_node.current_player = constants.players.P1 params.root_node.bets = arg.IntTensor([1, 1]).to(arg.device) root = tree_builder.build_tree(params) self.terminal_node = 0 self.chacne_node = 0 self.else_node = 0 self.dfs(root)
def a_star_search(start, goal, problem, safe_states): """ Find the list of actions to perform on the start state to reach the goal state through optimal path with least cost. Args: start: tuple - (x,y). Start state of the agent goal: tuple - (x,y). Goal state to reach. problem: 2d list of characters - [['m','p'],['s','p']]. Problem with terrain as characters. safe_states: Returns: string. Sequence of actions to take on start state to reach the goal state. """ explored = set() frontier = [] # push the start node to the frontier heappush(frontier, Node(0, 0, start, None, None)) while True: # if all nodes in the frontier are explored and path is not found, then # there exists no path. if len(frontier) == 0: return [], sys.maxsize # select state with least cost from frontier node = heappop(frontier) # print(node.state) # goal test the current node goal_node = goal_test(node, goal, frontier) if goal_node: # get the solution(seq. of actions) return get_solution(goal_node) # add state to explored set explored.add(node.state) # get the list of all possible actions on the state actions = find_actions(len(problem) - 1, node.state, problem) # expand a node and generate children for action in actions: # generate a child node by applying actions to the current state child = generate_child(problem, goal, node, action) if child is not None: # check if child is already explored or present in frontier and # (Ref: Line 144)replace the frontier node with child if the child has lower cost if child.state not in explored and child not in frontier: # add node with current state and path cost to reach the node from # the start state to the frontier # if the safeStates passed from the plan is in the frontier then only it will consider it if (len(safe_states) == 0) or (child.state in safe_states) or (child.state == goal): heappush(frontier, child)
class TestNodeClass(unittest.TestCase): """Class to test common behavior of all nodes""" def setUp(self): (public_key, private_key) = rsa.newkeys(512) self.node = Node(public_key, private_key) self.node_mapping = {str(public_key): self.node} def test_set_mapping(self): self.node.set_node_mapping(dict(self.node_mapping)) # node is supposed to remove its own mapping from dictionary self.assertEqual(self.node.node_mapping, {}) def test_method_name(self): # call method here # assert that the expected result is the case pass def test_node_in_network(self): actual = self.node.is_node_in_network(self.node.public_key) self.assertTrue(self.node_mapping, actual) def test_sign_message(self): # Encoding our message into bits using .encode() message = 'Test Message'.encode() # Ciphertext that takes a message and makes a node sign the message cipher = self.node.sign_message(message) # plaintext that uses decryption with the private key on the cipher text # Cannot test for encryption equality, because random seed makes encryption results different plaintxt = rsa.decrypt(cipher, self.node._private_key) # tested if node signs message properly self.assertEqual(message, plaintxt, 'Node did not sign message properly')
def append(self, value): ''' This function is used to add element at the end of list params: value: any type ''' new_node = Node(value) if self.head is None: self.head = new_node return current = self.head while current.next: current = current.next current.next = new_node return
def test_hash_changes_on_setting_getting_deleting_data(self): node = Node(randomPK, set()) old_hash = node.get_hash() node.abc = "abc" new_hash = node.get_hash() self.assertTrue(check_valid_hash(new_hash)) self.assertNotEqual(old_hash, new_hash) temp = node.abc old_hash, new_hash = new_hash, node.get_hash() self.assertEqual(new_hash, old_hash) del node.abc new_hash = node.get_hash() self.assertTrue(check_valid_hash(new_hash)) self.assertNotEqual(old_hash, new_hash)
def __init__(self, name='GATE%d'): Node.__init__(self, name) self.add_input('A') self.add_input('B') self.add_output('OUT') self.lastout = 0
def __init__(self, name='NOT%d'): Node.__init__(self, name) self.add_input('IN') self.add_output('OUT')
root1 = root1.next mult *= 10 num2 = 0 mult = 1 while root2 is not None: num2 += root2.data * mult root2 = root2.next mult *= 10 result = num1 + num2 print "%s + %s = %s" % (num1, num2, result) result_list = None for x in str(result)[::-1]: if result_list is None: result_list = Node(x) else: result_list.append_to_tail(x) return result_list root1 = Node(3) root1.append_to_tail(1) root1.append_to_tail(5) root1.append_to_tail(6) root2 = Node(5) root2.append_to_tail(9) root2.append_to_tail(2) result = sum_linked_lists(root1, root2) print_nodes(result)
from base import Node, print_nodes def remove_duplicates(root): n = root prev = None d = {} while n is not None: if n.data in d: prev.next = n.next else: d[n.data] = 1 prev = n n = n.next root = Node(4) root.append_to_tail(5) root.append_to_tail(8) root.append_to_tail(7) root.append_to_tail(8) root.append_to_tail(10) root.append_to_tail(8) root.append_to_tail(10) print_nodes(root) remove_duplicates(root) print_nodes(root)
def test_node_gets_present_time_as_updated_time_on_insertion(self): now = time_now() node = Node(0, set(), **temp_info) self.assertAlmostEqual(now, node.get_update_time(), places=0)
def test_hash_and_queue_changes_in_a_complex_tree(self): update_queue = set() root = Node(randomPK, update_queue) root_child1 = Node(getRandomPK(), update_queue) root_child2 = Node(getRandomPK(), update_queue) root_child1_child1 = Node(getRandomPK(), update_queue) root_child1_child2 = Node(getRandomPK(), update_queue) root_child2_child1 = Node(getRandomPK(), update_queue) root_child2_child2 = Node(getRandomPK(), update_queue) root_child1_child1_child1 = Node(getRandomPK(), update_queue) all_nodes = [locals()[x] for x in locals().keys() if 'root' in x] # Each new node announces its presence in the update queue self.assertSetEqual(update_queue, set([x._pk for x in all_nodes])) update_queue = set() for x in all_nodes: x._update_hash_queue = update_queue #start creating relationships old_root_hash = root.get_sync_hash() old_root_child1_hash = root_child1.get_sync_hash() root.add_child(root_child1) self.assertSetEqual(update_queue, set([root._pk, root_child1._pk])) new_root_hash = root.get_sync_hash() new_root_child1_hash = root_child1.get_sync_hash() self.assertTrue(TestNodeCore.check_sync_hash_old_new(old_root_hash, new_root_hash, False, True, False)) self.assertTrue(TestNodeCore.check_sync_hash_old_new(old_root_child1_hash, new_root_child1_hash, True, True, True)) root_child1.add_child(root_child1_child1) self.assertSetEqual(update_queue, set([root._pk, root_child1._pk, root_child1_child1._pk])) root.add_child(root_child2) self.assertSetEqual(update_queue, set([root._pk, root_child1._pk, root_child1_child1._pk, root_child2._pk])) #create complete relationship root_child1.add_child(root_child1_child2) root_child2.add_child(root_child2_child1) root_child2.add_child(root_child2_child2) root_child1_child1.add_child(root_child1_child1_child1) self.assertEqual(root._number_of_children(), 2) self.assertEqual(root_child1._number_of_children(), 2) self.assertEqual(root_child2._number_of_children(), 2) self.assertEqual(root_child1_child1._number_of_children(), 1) self.assertEqual(root_child1_child2._number_of_children(), 0) self.assertEqual(root_child2_child1._number_of_children(), 0) self.assertEqual(root_child2_child2._number_of_children(), 0) self.assertEqual(len(update_queue), 8) self.assertIn(root_child1_child1_child1, root_child1_child1._children) # test that changing a child's description, changes its hash and adds self # pk in the update queue update_queue.remove(root_child2_child2._pk) old_sync_hash = root_child2_child2.get_sync_hash() root_child2_child2.something = "Sometihng" new_sync_hash = root_child2_child2.get_sync_hash() self.assertIn(root_child2_child2._pk, update_queue) self.assertTrue(TestNodeCore.check_sync_hash_old_new( old_sync_hash, new_sync_hash, False, False, True))
from base import Node, print_nodes def find_loop_start(node): nodes = {} while node is not None: if node not in nodes: nodes[node] = 1 else: return node node = node.next root = Node('A') root.append_to_tail('B') root.append_to_tail('C') root.append_to_tail('D') root.append_to_tail('E') root.next.next.next.next.next = root.next.next loop_start = find_loop_start(root) print loop_start.data
def __init__(self, name='PKG%d'): Node.__init__(self,name) self.contents = list()
def find_nth_to_last(root, nth): if root is None or nth < 0: return None p2 = root for x in xrange(0, nth): p2 = p2.next if p2 is None: return None p1 = root while p2.next is not None: p1 = p1.next p2 = p2.next return p1 root = Node(0) root.append_to_tail(1) root.append_to_tail(2) root.append_to_tail(3) root.append_to_tail(4) root.append_to_tail(5) root.append_to_tail(6) root.append_to_tail(7) root.append_to_tail(8) root.append_to_tail(9) print_nodes(root) nth = 2 node = find_nth_to_last(root, nth) print "%s to last: %s" % (nth, node.data)
def timeslice(self, time): Node.timeslice(self, time) for node in self.contents: node.timeslice(time)