def getOr(x, y): global count nodeXinitial = x.getInitial() nodeXfinal = x.getFinal() nodeYinitial = y.getInitial() nodeYfinal = y.getFinal() nodeXinitial.category = 'incremental' nodeXfinal.category = 'incremental' nodeYinitial.category = 'incremental' nodeYfinal.category = 'incremental' for y in y.getNodes(): x.addNode(y) node_initial = Node(count, 'initial') count += 1 node_final = Node(count, 'final') count += 1 node_initial.addEdge(Edge(node_initial, nodeXinitial, 'ε')) node_initial.addEdge(Edge(node_initial, nodeYinitial, 'ε')) nodeXfinal.addEdge(Edge(nodeXfinal, node_final, 'ε')) nodeYfinal.addEdge(Edge(nodeYfinal, node_final, 'ε')) x.addNode(node_initial) x.addNode(node_final) return x
def parse_agatz(n): path = './data/instances_agatz/uniform' files = [ join(path, f) for f in listdir(path) if isfile(join(path, f)) and f[:-4].split('-')[-1] == 'n{}'.format(n) ] instances = list() counter = 0 for f in files: counter += 1 with open(f, 'r') as data: data = data.readlines() alpha = round(float(data[1]) / float(data[3]), 1) (depot_x, depot_y, _) = data[7].split(' ') depot = Node(1, float(depot_x), float(depot_y)) nodes = [depot] node_id = 1 for i in data[9:]: node_id += 1 (x, y, _) = i.split(' ') node = Node(node_id, float(x), float(y)) nodes.append(node) instance = Instance(counter, nodes, alpha) instance.compute_travel_times() instances.append(instance) return instances
def get_or(x, y): global count node_xinitial = x.get_initial() node_xfinal = x.get_final() node_yinitial = y.get_initial() node_yfinal = y.get_final() node_xinitial.category = 'incremental' node_xfinal.category = 'incremental' node_yinitial.category = 'incremental' node_yfinal.category = 'incremental' for y in y.nodes: x.add_node(y) node_initial = Node(count, 'initial') count += 1 node_final = Node(count, 'final') count += 1 node_initial.add_edge(Edge(node_initial, node_xinitial, EMPTY_STATE)) node_initial.add_edge(Edge(node_initial, node_yinitial, EMPTY_STATE)) node_xfinal.add_edge(Edge(node_xfinal, node_final, EMPTY_STATE)) node_yfinal.add_edge(Edge(node_yfinal, node_final, EMPTY_STATE)) x.add_node(node_initial) x.add_node(node_final) return x
def push(self, value): if self.has_space(): item = Node(value) item.set_next_node(self.top_item) self.top_item = item self.size += 1 else: print("No more room!")
def _createProgram(): root = Node("=") root.left = Node("y") root.right = Node("+") root.right.left = Node("y") root.right.right = Node("3") return Program(root)
def testComputeFitnessDOA(self): root = Node("=") root.left = Node("x") root.right = Node("4") program = Program(root) fitness = FitCurveProblem.computeFitness(program) self.assertEqual(fitness, 0.019999999732933336)
def testComputeFitnessLow(self): root = Node("=") root.left = Node("y") root.right = Node("4") program = Program(root) fitness = FitCurveProblem.computeFitness(program) self.assertEqual(fitness, 8.14518041038435)
def run(self, assignments, maxOperations=1000, maxTime=1000): results = dict(assignments) try: Node.evaluate(self.root, results) except Exception as e: print "Error evaluating program: {0}".format(self.toString()) raise e return results
def testRunSelfReferencingVariable(self): root = Node("=") root.left = Node("y") root.right = Node("+") root.right.left = Node("y") root.right.right = Node("3") program = Program(root) result = program.run({"y": 2}) self.assertEqual(result["y"], 5)
def testComputeFitnessHigh(self): root = Node("=") root.left = Node("y") root.right = Node("+") root.right.left = Node("x") root.right.right = Node("4") program = Program(root) fitness = FitCurveProblem.computeFitness(program) self.assertEqual(fitness, 100)
def prepend(self, item): """Insert the given item at the head of this linked list. Runtime = 0(1). """ new_node = Node(item) if self.is_empty(): self.head = new_node self.tail = new_node else: new_node.next = self.head self.head = new_node
def testReplaceRoot(self): node = Node("1") node.left = Node("2") node.right = Node("3") node.left.left = Node("4") value = Node("5") node = Node.replace(node, node, value) self.assertEqual(node.value, "5") self.assertIsNone(node.left) self.assertIsNone(node.right)
def testRun(self): root = Node("=") root.left = Node("y") root.right = Node("+") root.right.left = Node("x") root.right.right = Node("4") program = Program(root) result = program.run({"x": 3}) self.assertEqual(result["x"], 3) self.assertEqual(result["y"], 7)
def getGraphLetter(letter): global count graph = Graph() node1 = Node(count, 'initial') count += 1 node2 = Node(count, 'final') count += 1 node1.addEdge(Edge(node1, node2, letter)) graph.addNode(node1) graph.addNode(node2) return getInitialFinal(graph)
def get_graph_letter(letter): global count graph = Graph() node1 = Node(count, 'initial') count += 1 node2 = Node(count, 'final') count += 1 node1.add_edge(Edge(node1, node2, letter)) graph.add_node(node1) graph.add_node(node2) return get_initial_final(graph)
def mutate(self): for program in self.programs: for node in Node.traverseInOrder(program.root): if random.random() < self.MUTATION_PROBABILITY: if node.isTerminal(): node.value = self._createTerminalNode(self.problem).value else: node.value = self._createOperatorNode(self.problem).value
def run(n, alpha, seed=0): np.random.seed(seed) pos = dict( zip([i + 1 for i in range(n)], list(map(tuple, np.random.random([n, 2]) * 100)))) pos[n + 1] = pos[1] nodes = [Node(i, pos[i][0], pos[i][1]) for i in range(1, n + 1) ] + [Node(n + 1, pos[n + 1][0], pos[n + 1][1])] truck_travel_time = {(i, j): int(np.sqrt((i.x - j.x)**2 + (i.y - j.y)**2) * 10) for i in nodes for j in nodes if i != j} drone_travel_time = { a: truck_travel_time[a] / alpha for a in truck_travel_time } return nodes, truck_travel_time, drone_travel_time
def mutate(self): for program in self.programs: for node in Node.traverseInOrder(program.root): if random.random() < self.MUTATION_PROBABILITY: if node.isTerminal(): node.value = self._createTerminalNode( self.problem).value else: node.value = self._createOperatorNode( self.problem).value
def get_initial_final(graph): global count initial = graph.get_initial() initial.category = 'incremental' final = graph.get_final() final.category = 'incremental' node_initial = Node(count, 'initial') count += 1 node_initial.add_edge(Edge(node_initial, initial, EMPTY_STATE)) node_final = Node(count, 'final') count += 1 final.add_edge(Edge(final, node_final, EMPTY_STATE)) graph.add_node(node_initial) graph.add_node(node_final) return graph
def test_linking_nodes(self): node1 = Node('A') node2 = Node('B') node3 = Node('C') # Link nodes together node1.next = node2 node2.next = node3 # Node links should be transitive assert node1.next is node2 # One link assert node1.next.next is node3 # Two links
def __init__(self, data, width, height, stop): self.map = [] self.width = width self.height = height index = 0 for d in data: x = index % self.width y = height - 1 - (index // self.width) point = Point(x, y) h = (abs(stop.x - point.x) + abs(stop.y - point.y)) * 10 node = Node(point, h) if d == -1: node.setBlock() self.map.append(node) index += 1
class QuadTree: def __init__(self, threshold): self.threshold = threshold self.root = Node(0, 0, 10, 10, None) def add_point(self, x, y): self.root.add_point(x, y) def get_points(self): self.root.get_points() def subdivide(self): recursive_subdivide(self.root, self.threshold) def graph(self): fig = plt.figure(figsize=(12, 8)) plt.title("Quadtree") ax = fig.add_subplot(111) c = find_children(self.root) print(f"Number of segments: {len(c)}") areas = set() for el in c: areas.add(el.width * el.height) print(f"Minimum segment area: {min(areas)}") for n in c: ax.add_patch( patches.Rectangle((n.x, n.y), n.width, n.height, fill=False)) x = [point.x for point in self.root.points] y = [point.y for point in self.root.points] c = [point.data['color'] for point in self.root.points] red_patch = patches.Patch(color='red', label='Gas Station') blue_patch = patches.Patch(color='blue', label='Police') yellow_patch = patches.Patch(color='yellow', label='Hospital') plt.legend(handles=[red_patch, blue_patch, yellow_patch]) plt.scatter(x, y, c=c) plt.show() return
def recursive_subdivide(node, k): if len(node.points) <= k: return w_ = float(node.width / 2) h_ = float(node.height / 2) p = contains(node.x, node.y, w_, h_, node.points) x1 = Node(node.x, node.y, w_, h_, p) recursive_subdivide(x1, k) p = contains(node.x, node.y + h_, w_, h_, node.points) x2 = Node(node.x, node.y + h_, w_, h_, p) recursive_subdivide(x2, k) p = contains(node.x + w_, node.y, w_, h_, node.points) x3 = Node(node.x + w_, node.y, w_, h_, p) recursive_subdivide(x3, k) p = contains(node.x + w_, node.y + h_, w_, h_, node.points) x4 = Node(node.x + w_, node.y + h_, w_, h_, p) recursive_subdivide(x4, k) node.children = [x1, x2, x3, x4]
def huffmanEncode(S, f, length): H = MinHeap(length) # create priority queue using a MinHeap n = len(f) for i in range(0, n): # insert all the values into the Heap H.ops += 1 H.insert(S[i], f[i]) for k in range(n, 2*n-1): H.ops += 1 i = H.deletemin() # get min value j = H.deletemin() # get min value s = i[1] + j[1] # find their frequency sum # create a node with the information of two min values and their sum z = Node(s, i[0], i[1], j[0], j[1]) H.insert(z, s) # insert new node into the queue. # run codebook on the heap to generate the optimal encodings return H.ops, codebook(H)
def mate(self, program): childA = Node.copy(self.root) childB = Node.copy(program.root) nodeA = random.choice(Node.traverseInOrder(childA)) nodeB = random.choice(Node.traverseInOrder(childB)) childA = Node.replace(childA, nodeA, nodeB) childB = Node.replace(childB, nodeB, nodeA) return [Program(childA), Program(childB)]
def findNodes(lines, keys): nodes = Nodes() i = 0 while i < (len(lines)): line = lines[i].strip() if "<node" in line: lat, lon, id = 0, 0, 0 id = __getNodeIdFromLine(line) while "</node" not in line: i += 1 line = lines[i].strip() if keys["lat"] in line: lat = __getFloatFromLine(line) if keys["lon"] in line: lon = __getFloatFromLine(line) nodes.addNode(Node(id, lat, lon)) i += 1 return (nodes)
def getInitialFinal(graph): global count initial = graph.getInitial() initial.category = 'incremental' final = graph.getFinal() final.category = 'incremental' node_initial = Node(count, 'initial') count += 1 node_initial.addEdge(Edge(node_initial, initial, 'ε')) node_final = Node(count, 'final') count += 1 node_final.addEdge(Edge(final, node_final, 'ε')) graph.addNode(node_initial) graph.addNode(node_final) return graph
def append(self, item): """Insert the given item at the tail of this linked list. Runtime = O(1) - linear """ new_node = Node(item) # First we check if we have any nodes to begin with. if self.is_empty(): # If self.head is None, it means there are no nodes in self # this means the new_node will both represent both the head # and the tail. self.head = new_node self.tail = new_node # The first node that is appended is the head, the last is the tail. # The 'head' is the first first node, the 'tail' is the last node. else: # Point tail to new_node. self.tail.next = new_node self.tail = new_node
def getCline(x): global count nodeXinitial = x.getInitial() nodeXinitial.category = 'incremental' nodeXfinal = x.getFinal() nodeXfinal.category = 'incremental' nodeXfinal.addEdge(Edge(nodeXfinal, nodeXinitial, 'ε')) node_initial = Node(count, 'initial') count += 1 node_final = Node(count, 'final') count += 1 node_initial.addEdge(Edge(node_initial, nodeXinitial, 'ε')) node_initial.addEdge(Edge(node_initial, node_final, 'ε')) nodeXfinal.addEdge(Edge(nodeXfinal, node_final, 'ε')) x.addNode(node_initial) x.addNode(node_final) return x
def get_cline(x): global count node_xinitial = x.get_initial() node_xinitial.category = 'incremental' node_xfinal = x.get_final() node_xfinal.category = 'incremental' node_xfinal.add_edge(Edge(node_xfinal, node_xinitial, EMPTY_STATE)) node_initial = Node(count, 'initial') count += 1 node_final = Node(count, 'final') count += 1 node_initial.add_edge(Edge(node_initial, node_xinitial, EMPTY_STATE)) node_initial.add_edge(Edge(node_initial, node_final, EMPTY_STATE)) node_xfinal.add_edge(Edge(node_xfinal, node_final, EMPTY_STATE)) x.add_node(node_initial) x.add_node(node_final) return x
from classes.node import Node from classes.tree import TreeNode, Tree tree = Tree() nodes = {} # load taxonomy data to dictionary print("Loading nodes from file") with open('taxdump/nodes.dmp') as f: for line in f: formatted_input = line.split('\t|\t') nodes[formatted_input[0]] = Node(formatted_input) print("Loading completed") # function to get a node path from the dictionary def getPath(id): if id not in nodes: return [] currentNode = nodes[id] res = [currentNode.tax_id] while (currentNode.tax_id != currentNode.parent_id): res.append(currentNode.parent_id) currentNode = nodes[currentNode.parent_id] return res # function to find lca based on a dictionary list def find_lca(n1, n2): n1_path = getPath(n1) n2_path = getPath(n2)
def testIsVariablePositive(self): self.assertTrue(Node("x").isVariable()) self.assertTrue(Node("xx").isVariable()) self.assertTrue(Node("x4").isVariable())
def testIsVariableNegative(self): self.assertFalse(Node("3").isVariable()) self.assertFalse(Node("3.5").isVariable()) self.assertFalse(Node("=").isVariable())
def test_init(self): data = 'ABC' node = Node(data) # Initializer should add instance properties assert node.data is data assert node.next is None
def toString(self): return "{0} [{1} nodes]".format(Node.toString(self.root), len(Node.traverseInOrder(self.root)))