def test_SearchNotPossible_ShouldReturnFalse(self): ValidationUtility.set_up_test_method('impossible', Node((2, 0, 0)), Node((0, 0, 0))) result = ValidationUtility.a_star_controller.search_path() self.assertFalse(result)
def g(self, current_link: Link, current_node: Node, child_node: Node): """ Calculate the cost/ distance from start to the child node. :param current_link: Current link from the current node to the child node. :param current_node: Current parent node. :param child_node: Child node of the current node. :return: Whether the g score could be set or not. """ # No link to the neighbor room, link can be blasted # Blasting a hole in a wall with a tritanium-blaster costs 3 minutes, can be used in all # directions expect up if current_link is None: if not self.is_cheaper(current_node, child_node, 3): return False child_node.g = current_node.g + 3 child_node.regeneration_time = current_node.regeneration_time - 3 child_node.tritanium_blaster = current_node.tritanium_blaster - 1 child_node.energy_units = current_node.energy_units child_node.parent_link_type = 'wall or ground blasted' return True # Path with or without a drone if self.is_open(current_node, child_node, current_link): return True # Door costs 2 minutes if self.is_door(current_node, child_node, current_link): return True # Up the ladder costs 2 minutes # Down costs 1/2 minute if self.is_ladder(current_node, child_node, current_link): return True return False
def start(args): """ Start the import and path calculation. """ # Set the start node start_node = Node((15, -4, 6)) dest_node = Node((0, 0, 0)) # End node is the center of the cube # Read the data from the csv file file_controller = FileController() logging.info('Importing data from %s...', args.import_path) links, nodes = file_controller.import_file(args.import_path, start_node, dest_node) logging.info('Successfully imported data from %s!', args.import_path) # Calculate the path a_star_controller = AStarController(links, nodes, start_node, dest_node) logging.info('Starting path search...') start_time = time.perf_counter() cheapest_path = a_star_controller.search_path() end_time = time.perf_counter() if cheapest_path: logging.info('Cheapest path successfully found in %.3f ms!' % ((end_time - start_time) * 1000)) if args.export_path: logging.info('Exporting result to: %s' % args.export_path) file_controller.export_file(args.export_path, cheapest_path) logging.info('Result successfully exported!') sys.exit(0) else: logging.fatal('Cheapest path could not be found.') sys.exit(1)
def testDoubleAssignment(self): node1 = Node() node2 = Node() node1.set_data("BLAHBLAH") node2.set_data("ARRRRGHH") self.assertNotEquals(node1.get_data(),node2.get_data(), "Global variables don't cause issues.")
def test_DestroyWithBlaster_ShouldCostOne(self): ValidationUtility.set_up_test_method('destroy', Node((0, 0, 0)), Node((0, 0, 0))) expected = 1 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].g # get the final cost self.assertEqual(expected, actual)
def test_BlastWall_ShouldCostThree(self): ValidationUtility.set_up_test_method('blasting', Node((1, 0, 0)), Node((0, 0, 0))) # cost 3 to blast through wall # cost 1 to destroy expected = 4 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].g # get the final cost self.assertEqual(expected, actual)
def test_Door_ShouldCostTwo(self): ValidationUtility.set_up_test_method('simple_links', Node((1, 0, 0)), Node((0, 0, 0))) # cost 2 through door # cost 1 to destroy expected = 3 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].g # get the final cost self.assertEqual(expected, actual)
def test_LadderDown_ShouldCostPointFive(self): ValidationUtility.set_up_test_method('simple_links', Node((0, 0, 1)), Node((0, 0, 0))) # cost 0.5 through ladder down # cost 1 to destroy expected = 1.5 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].g # get the final cost self.assertEqual(expected, actual)
def test_UseEnergy_ShouldReduceEnergyCount(self): ValidationUtility.set_up_test_method('energy', Node((2, 0, 0)), Node((0, 0, 0)), energy=2) expected = 0 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].energy_units # get the final energy unit count self.assertEqual(expected, actual)
def test_Search_ShouldTakeCheaperPath(self): ValidationUtility.set_up_test_method('cheapest', Node((2, 0, 0)), Node((0, 0, 0))) # cheaper.csv has shortest path of cost 6 # cost 3 through open doors # cost 2 through closed door # cost 1 to destroy expected = 12 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].g # get the final cost self.assertEqual(expected, actual)
def testValidPath(self): for i in range(0,10): node = Node() node.set_data(str(i)) self.graph.nodes.append(node) for i in range(0,8): edge = Edge() edge.set_info(self.graph.nodes[i],self.graph.nodes[i+1],i) self.graph.edges.append(edge) valid_path = self.graph.is_valid_path(self.graph.nodes[:-1]) self.assertTrue(valid_path)
def test_RegenerationLadderUp_ShouldReduceRegenerationTimeByTwo(self): ValidationUtility.set_up_test_method('regeneration_ladder_up', Node((1, 0, -1)), Node((0, 0, 0))) # regeneration time at 5 # ladder up takes 2 # destroy takes 1 expected = 2 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].regeneration_time # get the final cost self.assertEqual(expected, actual)
def test_RegenerationOpen_ShouldReduceRegenerationTimeByOne(self): ValidationUtility.set_up_test_method('regeneration_open', Node((1, 1, 0)), Node((0, 0, 0))) # regeneration time at 5 # open takes 1 # destroy takes 1 expected = 3 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].regeneration_time # get the final cost self.assertEqual(expected, actual)
def test_EnergyCooldown_ShouldRegardCooldownOfFive(self): ValidationUtility.set_up_test_method('energy', Node((2, 0, 0)), Node((0, 0, 0))) # cost 3 through sentinel hallway # cost 5 for cooldown (wait) # cost 3 through sentinel hallway # cost 1 to destroy expected = 12 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].g # get the final cost self.assertEqual(expected, actual)
def test_UseBlaster_ShouldReduceBlasterCount(self): ValidationUtility.set_up_test_method('blasting', Node((1, 0, 0)), Node((0, 0, 0)), blaster=1) expected = 0 result = ValidationUtility.a_star_controller.search_path() actual = result[ len(result) - 1].tritanium_blaster # get the final tritanium blaster count self.assertEqual(expected, actual)
def test_LeastResistance_ShouldHaveTwelveEnergyUnits(self): ValidationUtility.set_up_test_method('least_resistance', Node( (3, 0, 0)), Node((0, 0, 0))) # least_resistance.csv has shortest path of cost 13 # path with least resistance is door (5x2) and open (1x1) # path of same length is sentinel(3)-wait(5)-sentinel(3) # energy_units should be unchanged because path of least resistance is taken expected = 12 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].energy_units # get the final cost self.assertEqual(expected, actual)
def test_RegenerationBlastWall_ShouldReduceRegenerationTimeByThree(self): ValidationUtility.set_up_test_method('regeneration_blasting', Node((2, 0, 0)), Node((0, 0, 0))) # regeneration time at 5 # blast wall takes 3 # destroy takes 1 expected = 1 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].regeneration_time # get the final cost self.assertEqual(expected, actual)
def import_file(self, import_path, start_node: Node, dest_node: Node): """ Read the csv file from the given import path. :param start_node: Start node of the graph. :param dest_node: Destination node of the graph. :param import_path: Path to the csv file. :return: Links and nodes from the csv file. """ # If the import path is not valid, exit if not self.is_path_valid(import_path): sys.exit(2) # Add the start and dest nodes to the nodes list self.nodes.append(start_node) self.nodes.append(dest_node) # Starting the import with open(import_path) as csv_file: # Iterate through each row reader = csv.reader(csv_file, delimiter=';') for i, row in enumerate(reader): if i == 0: continue # Get the nodes node1 = Node( (int(row[0] or '0'), int(row[1] or '0'), int(row[2] or '0'))) node2 = Node( (int(row[3] or '0'), int(row[4] or '0'), int(row[5] or '0'))) # Add the nodes, if they haven't been added yet found_node = next( (node for node in self.nodes if node1 == node), None) if found_node: node1 = found_node else: self.nodes.append(node1) found_node = next( (node for node in self.nodes if node2 == node), None) if found_node: node2 = found_node else: self.nodes.append(node2) # Add the link self.links.append( Link(node1, node2, int(row[6] or '0'), int(row[7] or '0'), int(row[8] or '0'), int(row[9] or '0'))) # Print the file if debug is enabled self.print_file() return self.links, self.nodes
def is_ladder(self, current_node: Node, child_node: Node, current_link: Link): """ Check whether the link is a ladder and the path is cheaper. Up the ladder costs 2 minutes. Down costs 1/2 minute. :param current_node: The current node. :param child_node: The child node of the current node. :param current_link: The link from the current to the child node. :return: Whether the link is a ladder and cheaper or not. """ if current_link.is_ladder: # Check if the ladder has been went up or down if current_node.position[2] <= child_node.position[2]: if not self.is_cheaper(current_node, child_node, 2, energy_unit_cost=2): return False child_node.g = current_node.g + 2 child_node.regeneration_time = current_node.regeneration_time - 2 child_node.parent_link_type = 'ladder up' else: if not self.is_cheaper(current_node, child_node, 0.5, energy_unit_cost=2): return False child_node.g = current_node.g + 0.5 child_node.regeneration_time = current_node.regeneration_time - 0.5 child_node.parent_link_type = 'ladder down' child_node.tritanium_blaster = current_node.tritanium_blaster child_node.energy_units = current_node.energy_units return True return False
def test_RegenerationLadderDown_ShouldReduceRegenerationTimeByPointFive( self): ValidationUtility.set_up_test_method('regeneration_ladder_down', Node((1, 0, 1)), Node((0, 0, 0))) # regeneration time at 5 # ladder down takes 0.5 # destroy takes 1 expected = 3.5 result = ValidationUtility.a_star_controller.search_path() actual = result[len(result) - 1].regeneration_time # get the final cost self.assertEqual(expected, actual)
def __init__(self, fw_code, set_of_coordinate_pairs, speed): self.nodes = [] self.bridges = [] self.locks = [] self.fw_code = fw_code if speed is None or math.isnan(speed) or speed == 0: speed = 13 self.speed = speed * 1000 / 60 GlobalVars.fairway_section_dict[self.fw_code] = self tmp = [] for coordinate_pairs in set_of_coordinate_pairs: for coordinates in coordinate_pairs: coordinates_tuple = (coordinates[0], coordinates[1]) if coordinates_tuple not in tmp: tmp.append(coordinates_tuple) for coordinates in tmp: lon = coordinates[0] lat = coordinates[1] x, y = lon, lat node = Node(x, y) GlobalVars.node_x_min = min(x, GlobalVars.node_x_min) GlobalVars.node_x_max = max(x, GlobalVars.node_x_max) GlobalVars.node_y_min = min(y, GlobalVars.node_y_min) GlobalVars.node_y_max = max(y, GlobalVars.node_y_max) self.nodes.append(node)
def node_add(): if request.json: if ("node" in request.json) and ('name' not in request.json.get('node') or 'description' not in request.json.get('node')): return make_response(400, 6, "name and description json fields required") else: node_json = request.json.get('node') node_description = node_json['description'] node_name = node_json['name'] else: return make_response(400, 6, "Invalid request data") node = Node(name=node_name) node.ownerId = g.user.id node.description = node_description db_node = Node.query.filter(Node.name == node_name, Node.ownerId == g.user.id).first() if db_node: if request.method == 'PUT': node_remove(db_node.id) else: return make_response(409, 1, str("user " + g.user.username + ' already have node ' + node_name)) try: db.session.add(node) db.session.commit() except exc.SQLAlchemyError: return make_response(500, 2, "Database exception") return jsonify({'hypermedia': { 'self': { 'resource': str('/api/node/' + str(node.id)), 'method': 'GET' }, 'replace': { 'resource': str('/api/node/' + str(node.id)), 'method': 'PUT' }, 'delete': { 'resource': str('/api/node/delete/' + str(node.id)), 'method': 'DELETE' } }, 'message': 'Created.'}), 201
def __init__(self, fw_code, length, width, coordinates_pair): Node.__init__(self, coordinates_pair[0], coordinates_pair[1]) self.fw_code = fw_code self.left = None self.right = None self.key_in = {} self.wait_in = {} self.key_out = None self.side = left self.length = length self.width = width self.waiting = False self.packer = newPacker(sort_algo=SORT_NONE, pack_algo=SkylineBl, rotation=False) # GuillotineBssfSas self.packer.add_bin(self.width, self.length) self.packer.pack() # Get the fairway section this belongs to if self.fw_code not in GlobalVars.fairway_section_dict: print("We have problem here..") insertion_idx = -1 min_distance = float('inf') fairway_section = GlobalVars.fairway_section_dict.get(self.fw_code) for idx, fairway_section_node in enumerate(fairway_section.nodes): distance = Utilities.haversine( [self.y, self.x], [fairway_section_node.y, fairway_section_node.x]) if distance < min_distance: min_distance = distance insertion_idx = idx if min_distance == 0: fairway_section.nodes[insertion_idx] = self else: # Append add the best index if insertion_idx >= len(fairway_section.nodes) - 1: insertion_idx = insertion_idx - 1 fairway_section.nodes.insert(insertion_idx + 1, self)
def is_finished(self, current_node: Node): """ Finish if the current node is the destination node. :param current_node: The current node. :return: If the path has been found or not, if so, return the cheapest path. """ if current_node == self.dest_node: # Destroying the vinculum costs 5 minutes, with a tritanium-blaster 1 minute if current_node.tritanium_blaster >= 1: current_node.g = current_node.g + 1 current_node.f = current_node.g + current_node.h current_node.tritanium_blaster = current_node.tritanium_blaster - 1 current_node.regeneration_time = current_node.regeneration_time - 1 else: current_node.g = current_node.g + 5 current_node.f = current_node.g + current_node.h current_node.regeneration_time = current_node.regeneration_time - 5 # Reconstruct the path path = self.reconstruct_path(current_node) for node in path: logging.debug(node) logging.info('Destination reached, final cost: %f' % current_node.g) return path return False
def h(self, child_node: Node): """ Estimate the cost of the cheapest path from the next node to the destination node. Calculate the heuristic. :param child_node: Child node from where the heuristic should be calculated. """ (x1, y1, z1) = child_node.position (x2, y2, z2) = self.dest_node.position child_node.h = abs(x1 - x2) + abs(y1 - y2) + abs(z1 - z2)
def is_door(self, current_node: Node, child_node: Node, current_link: Link): """ Check whether the link is a door and the path is cheaper. Door costs 2 minutes. :param current_node: The current node. :param child_node: The child node of the current node. :param current_link: The link from the current to the child node. :return: Whether the link is a door and cheaper or not. """ if current_link.is_door: if not self.is_cheaper(current_node, child_node, 2): return False child_node.g = current_node.g + 2 child_node.regeneration_time = current_node.regeneration_time - 2 child_node.tritanium_blaster = current_node.tritanium_blaster child_node.energy_units = current_node.energy_units child_node.parent_link_type = 'door' return True return False
def testDijikstra(self): nodes = self.graph.nodes edges = self.graph.edges for i in range (0,7): node = Node() node.set_data(str(i)) self.graph.nodes.append(node) for i in range (1,7): edge = Edge() self.graph.edges.append(edge) edges[0].set_info(nodes[0],nodes[3],2) edges[1].set_info(nodes[0],nodes[2],6) edges[2].set_info(nodes[1],nodes[2],3) edges[3].set_info(nodes[1],nodes[3],1) edges[4].set_info(nodes[2],nodes[3],1) edges[5].set_info(nodes[2],nodes[4],4) edges[6].set_info(nodes[3],nodes[4],6) edgelist = self.graph.dijikstra(nodes[0],nodes[4]) correct_edgelist = [edges[0],edges[3],edges[4],edges[5]]
def __init__(self, fw_code, movable, height, coordinates_pair): Node.__init__(self, coordinates_pair[0], coordinates_pair[1]) self.fw_code = fw_code self.left = None self.right = None self.state = closed self.order = None self.moving = None self.movable = movable if height is None or math.isnan(height): height = 0 self.height = height / 100 # Get the fairway section this belongs to if self.fw_code not in GlobalVars.fairway_section_dict: print("We have problem here..") insertion_idx = -1 min_distance = float('inf') fairway_section = GlobalVars.fairway_section_dict.get(self.fw_code) for idx, fairway_section_node in enumerate(fairway_section.nodes): distance = Utilities.haversine( [self.y, self.x], [fairway_section_node.y, fairway_section_node.x]) if distance < min_distance: min_distance = distance insertion_idx = idx if min_distance == 0: fairway_section.nodes[insertion_idx] = self else: # Append add the best index if insertion_idx >= len(fairway_section.nodes) - 1: insertion_idx = insertion_idx - 1 fairway_section.nodes.insert(insertion_idx + 1, self)
def testAddEdge(self): source = Node() source.set_data("BLECH") target = Node() target.set_data("ARGHH") self.graph.add_edge(source,target,1000) edge = self.graph.edges[0] self.assertEquals(edge.get_source().get_data(),"BLECH") self.assertEquals(edge.get_target().get_data(),"ARGHH")
def main(): nodes = setup_nodes() transitions = setup_initial_transitions(nodes) learned_transitions = [] walked_transitions = [] # Start at Arad current_node = Node.get_node_by_value("Lugoj", nodes) # Steps while (not (objective_function(current_node, nodes))): new_transition = step_function(current_node, learned_transitions, transitions) walked_transitions.append(new_transition) current_node = new_transition.to current_node.already_walked = new_transition.weight - current_node.heuristic print("\n") Transition.print_transitions_array(walked_transitions)
def testFindEdge(self): source = Node() source.set_data("BLACK") target = Node() target.set_data("WHITE") self.graph.add_edge(source,target,1) edge = self.graph.find_edge(source,target) sourcedata = edge.get_source().get_data() targetdata = edge.get_target().get_data() self.assertEquals(sourcedata,"BLACK") self.assertEquals(targetdata,"WHITE")
& (FieldBody.deleted == FieldDataSetStatus.deleted) & (FieldBody.language == FieldDataSetStatus.language) & (FieldBody.delta == FieldDataSetStatus.delta) ) bodyCount = ( FieldBody.select() .join(FieldDataSetStatus, on=condition1) .where(FieldDataSetStatus.field_dataset_status_value == "4") .count() ) print ("bodyCount: " + str(bodyCount)) # 取得總數 Node condition2 = Node.nid == FieldDataSetStatus.entity_id nodeCount = ( Node.select() .join(FieldDataSetStatus, on=condition2) .where(Node.type == "metadataset" | FieldDataSetStatus.field_dataset_status_value == "4") .count() ) print ("nodeCount: " + str(nodeCount)) world_list = [] num = 1000 # field_data_body i = 1 total_page = bodyCount / num + 1 # total_page = 1 while i < total_page + 1: print ("field_data_body Now Page: " + str(i)) page = getPage(i, num, FieldBody) for mesg in page:
from model.Node import Node __author__ = 'johnnytsai' page = Node.select().where(Node.type == "metadataset").paginate(1, 1000) for mesg in page: print mesg.title
import numpy as np from model.Tetramino import Tetramino from model.Node import Node node_representation = np.array( [ [1, 1], [1, 1] ] ) initial_node = Node(node_representation) initial_node.next_node = initial_node class SquareTetramino(Tetramino): def __init__(self): super().__init__(initial_node)
def merge_nodes(mine: TscnFile, theirs: TscnFile, result: TscnFile, resolution: Callable[[str, Printable, Printable], Resolution]): # We start at the root node and work down the tree of each file # we tree to keep node order as is as far as possible. assert len(mine.nodes) > 0, "MINE file has no node. This is invalid." assert len(theirs.nodes) > 0, "THEIRS file has no node. This is invalid." # Now we need to partition up the nodes so we can do a comparison between them and start the merging partitions: list[NodePartition] = partition_nodes(mine.nodes, theirs.nodes) # Now we can walk the partitions and merge if necessary for partition in partitions: if partition.is_only_mine: # node exists only on my side, so we can just add it to the result for my_node, _ in partition.nodes: result.nodes.append(my_node) elif partition.is_only_theirs: # node exists only on their side, so we can just add it to the result for _, their_node in partition.nodes: result.nodes.append(their_node) else: # node exists on both sides and we need to merge it for my_node, their_node in partition.nodes: if not my_node.represents_same_thing(their_node): # If the two nodes represent different things, there is no way to merge them as the properties are # dependent on the type of the node and therefore merging properties of two different # types together just makes not any sense. Therefore in this case the only thing # we can do is ask which of the both nodes we would like to have. decision = resolution( "The same node has different types/scripts. " "This cannot be merged. Which node should I take?", my_node, their_node) if decision == Resolution.MINE: result.nodes.append(my_node) elif decision == Resolution.THEIRS: result.nodes.append(their_node) else: assert False, "Unexpected input." else: # The nodes represent the same thing. Now we can compare their properties and build a result node. result_node = Node(my_node.type, my_node.name, my_node.parent, my_node.instance, my_node.instance_placeholder) properties: DiffResult[tuple[str, Value]] = diff_bag_properties( my_node, their_node) # Stuff that is same in both nodes, goes to the result for (key, value), _ in properties.same: result_node.set_property(key, value) # Stuff that is in my node only, also goes into the result for key, value in properties.only_in_mine: result_node.set_property(key, value) # Stuff that is in their node only, also goes into the result for key, value in properties.only_in_theirs: result_node.set_property(key, value) # Stuff that is different in both needs to be decided upon for (key, my_value), (_, their_value) in properties.different: decision = resolution( f"Node {result_node.full_path_reference().to_string()} -> " f"Property \"{key}\" is different in both sides. " f"Which one should I take?", my_value, their_value) if decision == Resolution.MINE: result_node.set_property(key, my_value) elif decision == Resolution.THEIRS: result_node.set_property(key, their_value) else: assert False, "Unexpected input." result.nodes.append(result_node)
import numpy as np from model.Tetramino import Tetramino from model.Node import Node up_node_representation = np.array([[0, 1, 1], [1, 1, 0]]) down_node_representation = np.array([ [1, 0], [1, 1], [0, 1], ]) up_node = Node(up_node_representation) down_node = Node(down_node_representation) up_node.next_node = down_node down_node.next_node = up_node class STetramino(Tetramino): def __init__(self): super().__init__(up_node)
def testAssignment(self): node = Node() node.set_data("BLARGH") self.assertEquals(node.get_data(), "BLARGH","Assignment worked.")