def main(porb): """Solve the CVRP problem.""" # Instantiate the data problem. file_name = "assignment.xls" info, trunks = get_parameters(file_name) trunk = trunks[0] infomation = info[prob] loc = infomation["location"] dist = get_distance(infomation["location"]) data = create_data_model(infomation, dist, trunk) # Create the routing index manager. manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot']) # Create Routing Model. routing = pywrapcp.RoutingModel(manager) # Create and register a transit callback. def distance_callback(from_index, to_index): """Returns the distance between the two nodes.""" # Convert from routing variable Index to distance matrix NodeIndex. from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return data['distance_matrix'][from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(distance_callback) # Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # Add Capacity constraint. def demand_callback(from_index): """Returns the demand of the node.""" # Convert from routing variable Index to demands NodeIndex. from_node = manager.IndexToNode(from_index) return data['demands'][from_node] demand_callback_index = routing.RegisterUnaryTransitCallback( demand_callback) routing.AddDimensionWithVehicleCapacity( demand_callback_index, 0, # null capacity slack data['vehicle_capacities'], # vehicle maximum capacities True, # start cumul to zero 'Capacity') # Setting first solution heuristic. search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) # Solve the problem. assignment = routing.SolveWithParameters(search_parameters) # Print solution on console. if assignment: print_solution(data, manager, routing, assignment, loc)
def distance(self) -> float: if self.is_found: return get_distance(self.departure.airport.location, self.destination.airport.location) else: return 1
def filter_address_file(filename, addresses): tree = ET.parse(filename) root = tree.getroot() overall_count = 0 filtered_count = 0 village = get_village_from_filename(filename) bounds = get_boundaries([filename]) has_local_addresses = None streets = None place_exists = None for node in root.findall('node'): overall_count += 1 tags = {} filtered = False for tag in node.findall('tag'): tags[tag.get("k")] = tag.get("v") has_fixme = "fixme" in tags if "addr:street" in tags: street = tags["addr:street"] else: street = tags["addr:place"] try: street = normalize_streetname(street) except ValueError: error_file = open("invalid_characters.txt", "a+") error_file.write("%s %s\n" % (street, str(tags))) error_file.close() housenumber = tags["addr:housenumber"].lower() if street in addresses: if has_local_addresses is None: has_local_addresses = True if housenumber in addresses[street]: p1 = (float(node.get("lat")), float(node.get("lon"))) for adr in addresses[street][housenumber]: p2 = (float(adr["lat"]), float(adr["lon"])) dist = get_distance(p1, p2) if dist < 150: if ("city" in adr and adr["city"] != tags["addr:city"] and dist > 50 and "".join(c for c in adr["city"].lower() if c.isalnum()) != village): # if city is set and differs (but isn't the village name) use higher threshold fixme = "ähnliche Adresse in %dm Entfernung (addr:city = '%s' statt '%s')" % ( dist, adr["city"], tags["addr:city"]) add_fixme(node, BevFixme.SIMILAR_ADR, fixme) has_fixme = True continue root.remove(node) filtered = True filtered_count += 1 break else: fixme = "ähnliche Adresse in %dm Entfernung" % dist has_fixme = add_fixme(node, BevFixme.SIMILAR_ADR, fixme) else: if SANITY_CHECKS and has_local_addresses is None: has_local_addresses = len( overpass.get_existing_addresses(*bounds)) > 0 if SANITY_CHECKS and not (filtered or has_fixme): if has_local_addresses and len( overpass.get_existing_addresses_around( node.get("lat"), node.get("lon"))) > 0: has_fixme = add_fixme(node, BevFixme.CLOSE_ADR) continue if not "addr:place" in tags: # check streetname / distance if streets is None: streets = overpass.get_streets_by_name(*bounds, street) if len(streets[0]) == 0: if place_exists is None: place_exists = overpass.place_exists(*bounds, street) if place_exists: has_fixme = add_fixme(node, BevFixme.ADDR_PLACE_NEEDED) else: if has_local_addresses or overpass.streets_exist( *bounds): has_fixme = add_fixme(node, BevFixme.STREET_NOT_FOUND) else: has_fixme = add_fixme(node, BevFixme.NO_STREET_FOUND) continue else: # get nearest way ways, nodes = streets nearest_way = None nearest_node = None min_dist = None for way in ways: for i in range(len(way.nodes)): #calculate distance to every node p1 = (float(node.get("lat")), float(node.get("lon"))) p2 = (float(way.nodes[i].lat), float(way.nodes[i].lon)) dist = get_distance(p1, p2) if min_dist is None or dist < min_dist: min_dist = dist nearest_node = i nearest_way = way nearest_node_tuple = (nearest_way.nodes[nearest_node].lat, nearest_way.nodes[nearest_node].lon) address_location = (node.get("lat"), node.get("lon")) if nearest_node > 0: # check distance to way n-1 -> n previous_node_tuple = (nearest_way.nodes[nearest_node - 1].lat, nearest_way.nodes[nearest_node - 1].lon) dist = get_cross_track_distance( previous_node_tuple, nearest_node_tuple, address_location) if min_dist is None or dist < min_dist: min_dist = dist if nearest_node < len(nearest_way.nodes) - 1: # check distance to way n -> n+1 next_node_tuple = (nearest_way.nodes[nearest_node + 1].lat, nearest_way.nodes[nearest_node + 1].lon) dist = get_cross_track_distance( nearest_node_tuple, next_node_tuple, address_location) if min_dist is None or dist < min_dist: min_dist = dist if min_dist > 150: has_fixme = add_fixme( node, BevFixme.DISTANT_STREET, "Straße weit entfernt (%dm)" % min_dist) #if not has_fixme: #if not overpass.is_building_nearby(node.get("lat"), node.get("lon")): #has_fixme = add_fixme(node, BevFixme.NO_OSM_BUILDING) directory, filename = os.path.split(os.path.abspath(filename)) filtered_directory = "%s%s" % (directory, FILTERED_SUFFIX) if not os.path.exists(filtered_directory): os.mkdir(filtered_directory) filtered_filename = "%s%s.osm" % (filename[:-4], FILTERED_SUFFIX) filtered_path = os.path.join(filtered_directory, filtered_filename) if not root.find('node') is None: tree.write(filtered_path) elif os.path.exists(filtered_path): os.remove(filtered_path) # TODO: directory empty? return filtered_count, overall_count
print(chromosome_best, inse) print(Tour) plt1 = plot(chromosome_best, inse, location) name1 = 'n={}_res_min={}.jpg'.format(len(dist) - 1, Fit[-1]) plt1.savefig("E:\\SIGS\\Courses\\物流地理信息系统\\作业\\期末作业\\GA_result\\n={}\\". format(len(dist) - 1) + name1) if __name__ == "__main__": start = time.clock() #long running #do something other file_name = "assignment.xls" info, trunks = get_parameters(file_name) prob = 2 infomation = info[prob] trunk = trunks[0] dist = get_distance(infomation["location"]) NUM_OF_CUSTOMER = len(infomation["location"]) - 1 location = info[prob]["location"] POPULATION_SIZE = 100 GA(infomation, trunk, dist) end = time.clock() file_t = open( 'E:\\SIGS\\Courses\\物流地理信息系统\\作业\\期末作业\\GA_result\\n=80\\Tour.txt', mode='a') file_t.write('\nCPU time: {}s'.format(end - start)) file_t.close() print("CPU time:{} s".format(end - start))
pagerank = graph.pagerank(directed=False,weights=weights) print 'compute unweighted degree' degree = graph.degree() print 'compute weighed degree' strength = graph.strength(weights=weights) print 'compute average distance between a business and its neighbors' neighbors = graph.neighborhood() for index,bus in enumerate(business_list): iter_distances = [] point1 = array([[business_info[bus]['lat'],business_info[bus]['lon']]]) for neighbor in neighbors[index]: point2 = array([[business_info[graph.vs[neighbor]['name']]['lat'],business_info[graph.vs[neighbor]['name']]['lon']]]) dist = get_distance(point1,point2)[0] iter_distances.append(dist) distances.append(mean(iter_distances)) print 'computing edge distances ' for edge in graph.es: point1 = array([[business_info[graph.vs[edge.source]['name']]['lat'],business_info[graph.vs[edge.source]['name']]['lon']]]) point2 = array([[business_info[graph.vs[edge.target]['name']]['lat'],business_info[graph.vs[edge.target]['name']]['lon']]]) edge_distances.append(get_distance(point1,point2)[0]) p_values =[] p_u_values = [] d_values = [] d_u_values = [] lats = [] lons = []
def get_distance(point1, point2): return haversine.get_distance(point1, point2)