def a_star(start, goal='Bucharest'): """ Retorna uma lista com o caminho de start até goal segundo o algoritmo A* """ # Cria uma fila prioritária onde os primeiros elementos sempre serão as possibilidades de rota mais curtas. queue = PriorityQueue(priority_asc=False) # Instancia o ponto de partida utilizando a estrutura City. start_city = City(start) # Adiciona o ponto de partida à fila prioritária. # Como o grau de prioridade não foi informado, será considerado O. queue.push(start_city.get_estimated_total_cost(), start_city) # Obtém-se a cidade com maior prioridade de ser expandida, que nesse momento ainda é o ponto inicial. city = queue.pop() # Enquanto a cidade prioritária não for o destino, continuaremos no laço. while city.is_name(goal) is False: # Expande as próximas cidades a partir da cidade atual. for next_city in dists.dists[city.name]: # Cria um novo ponto a partir do nome da próxima cidade, do custo de locomoção e da rota feita até aqui. new_city = City(name=next_city[0], cost=next_city[1], route_made=city.route_made) # Adiciona o ponto à fila prioritária dando o custo estimado até o destino como grau de prioridade. queue.push(new_city.get_estimated_total_cost(), new_city) # Atualiza a cidade a ser analisada pela próxima iteração. city = queue.pop() # Retorna uma lista contendo a melhor rota return [p.name for p in city.route_made]
def test_builder(): toulouse = City('Toulouse', 'fr', 'C', 35) assert toulouse.name == 'Toulouse' assert toulouse.country == 'fr' empty_city = City('', '', '', '') assert empty_city.name == '' assert empty_city.country == ''
def test_is_summer(): toulouse = City('Toulouse', 'fr', 'C', 35) assert Weather(toulouse, "2028-06-12T00:08:29Z").is_summer() assert Weather(toulouse, "2028-08-12T00:08:29Z").is_summer() assert Weather(toulouse, "2028-09-12T00:08:29Z").is_summer() assert not Weather(toulouse, "2028-11-12T00:08:29Z").is_summer() sydney = City('Sydney', 'au', 'B', 12) assert Weather(sydney, "2028-11-12T00:08:29Z").is_summer() assert Weather(sydney, "2028-12-12T00:08:29Z").is_summer() assert Weather(sydney, "2028-02-12T00:08:29Z").is_summer() assert not Weather(sydney, "2028-08-12T00:08:29Z").is_summer()
def getCityDetails(url): try: result = getRequest(url) if(result['response']['numFound'] > 0): city = result['response']['docs'] if(city != None): src = City(city[0]['ID'], city[0]['Name']) return src print("Location not found") return City(0, "Location not found") except Exception as e: print(e)
def create_graph(max_distance, min_population): graph = nx.Graph() data_frame = data.get_cities_data(min_population) nodes = set( map( lambda x: City(x.Country, x.City, x.Population, round( x.Latitude, 2), round(x.Longitude, 2)), data_frame.itertuples())) cuadrantes = [] for i in range(36): cuadrantes.append([]) for j in range(18): cuadrantes[i].append([]) for node in nodes: x, y = node.cuadrante() cuadrantes[x][y].append(node) nodes_aux = nodes.copy() edges = set() for node in nodes: nodes_aux.remove(node) edges = edges | set( map( lambda x: (node, x, distance_between_cities(node, x)), filter( lambda x: distance_between_cities(node, x) <= max_distance, nodes_aux))) graph.add_nodes_from(nodes) graph.add_weighted_edges_from(edges) return graph
def init(): ORIGINAL_COUNT = 50 #初始感染数量 BROAD_RATE = 0.8 #被传染概率 PROTECTION_RATE = 0.001 # 保护措施增长率(连续)(影响BROAD_RATE和u) EXPOSED_TIME = 5 #平均潜伏时间 HOSPITAL_RECEIVE_TIME = 3 #平均医院收治时间 CURE_TIME = 10 #平均治疗时间 IMMUNED_TIME = 30 #平均免疫期时间 DEATH_RATE = 0.01/(CURE_TIME+10*HOSPITAL_RECEIVE_TIME) #每日死亡概率 BED_COUNT = 1000 #医院床位 SAFETY_DIST = 50 #安全距离 FLUCTUATION = 4 #各参数与平均值之间的波动 u = 1 #流动意向 PERSON_COUNT = 10000 #城市内人数 can_exposed_infect = False # 潜伏期能否感染他人 recovered_included = True # 是否有免疫期 city = City(0, 0) pool = PeoplePool(PERSON_COUNT, city, BROAD_RATE, PROTECTION_RATE, DEATH_RATE, EXPOSED_TIME, IMMUNED_TIME, \ HOSPITAL_RECEIVE_TIME, CURE_TIME, SAFETY_DIST, u, FLUCTUATION, \ can_exposed_infect, recovered_included) hos = Hospital(BED_COUNT) for i in range(ORIGINAL_COUNT): idx = np.random.randint(0, PERSON_COUNT) pool.peoples[idx].status = 1 pool.peoples[idx].infected_time = 0 return city, pool, hos
def __init__(self): spi = busio.SPI(clock=board.SCK_1, MISO=board.MISO_1, MOSI=board.MOSI_1) #ADCs use second SPI port of RPi cs = digitalio.DigitalInOut(board.D16) mcp = MCP.MCP3008(spi, cs) self.pi = pigpio.pi() self.NUM_NEOPIXELS = 118 self.pixels = neopixel.NeoPixel(board.D12, self.NUM_NEOPIXELS, auto_write=False) self.reservoir = Reservoir(self.pixels) self.windmills = Windmills(self.pi, mcp) self.solarPanels = SolarPanels(mcp) self.city = City(self.pixels) self.fuelCell = FuelCell(self.pixels, self.pi) self.distributionMiddle = DistributionLine(self.pixels, 101, 4) self.distributionRight = DistributionLine(self.pixels, 105, 5, True) self.transmissionLine = TransmissionLines(self.pixels) self.wattownSign = WattownSign(self.pixels) self.substation = Substation(self.pixels) self.stopEvent = threading.Event() self.stopEvent.clear() super().__init__()
def astar(departure, destination, heuristic, nameHeuristic): cityStart = cityDic[departure] cityEnd = cityDic[destination] result = str(nameHeuristic) + "\n------------------------\n" frontiere = [] history = [] frontiere.append(cityStart) while len(frontiere) > 0: result += "front : " + str(frontiere) + "\n" city = frontiere.pop(0) history.append(city.name) result += "hist : " + str(history) + "\n" if city.name == cityEnd.name: result += "\nNombre de ville visiter: " + str(len(history))+ "\ndistance parcouru : " + str(city.d) + " km\n" +"\nChemin :\n" + city.parcours() + "\n" return result nextCities = city.getConnection() for c in nextCities: newCity = City(c.name, c.x, c.y, city) newCity.d = city.d + int(cityConnection[city.name][newCity.name]) newCity.h += heuristic(city, newCity) newCity.listConnection = cityDic[c.name].listConnection if (newCity not in frontiere) and (c.name not in history): frontiere.append(newCity) frontiere.sort() result += str(nameHeuristic) + "\n------------------------\nNo solution" return result
def collectdata(): global currentcategories try: db = DB() initdriver() city = City() while city.nextcity(db, driver) is not None: prod_namelist = set() for suburl, categories in city.category_pages.items(): driver.get(baseurl + suburl) currentcategories = categories scrolltoend() products = driver.find_elements( By.XPATH, "//li[starts-with(@id,'product_')]") print(len(products)) for product in products: if (product.get_attribute("class") == "featured-product" or "display:none" in product.get_attribute("style") or len(product.text) < 5): continue try: details = parseproduct(product) if (details['prod_name'] not in prod_namelist): prod_namelist.add(details['prod_name']) db.insertproduct(details, currentcategories) except Exception as e: print("---------------------------------------") print(e) print("---------------------------------------") continue time.sleep(10) finally: driver.close() db.conn.close()
def set_data_from_arr(data_arr): provinces_dict = {} cities_arr = [] for city_dict in data_arr: city = City() city.set_city_from_dict(city_dict) city.get_total_scene_points() city.get_total_type_points() print(city.city_name) cities_arr.append(city) if city.city_province not in provinces_dict.keys(): province = Province() province.province_name = city.city_province else: province = provinces_dict[city.city_province] province.add_city(city) if (city.city_name == '路凼填海区'): print('1', city.city_device_types_distribution) provinces_dict.update({province.province_name: province}) if (city.city_name == '路凼填海区'): print('2', city.city_device_types_distribution) for city in cities_arr: if (city.city_name == '路凼填海区'): print('3', city.city_device_types_distribution) return cities_arr, provinces_dict
def __init__(self): self.state = State() self.city = City() self.ninja = Ninja(self.city) self.badguys = self.get_badguys() self.hide_sword() self.hide_healths()
def load_from_file_e(self, file_name): f = open(file_name, "r") n = int(f.readline()) self.__graph['num_nodes'] = n cities = [] for i in range(n): line = f.readline() elements = line.split(" ") c = City(i, float(elements[1]), float(elements[2])) cities.append(c) initial_pheromone = float(f.readline()) # matrix with all edges edges = [[None] * n for _ in range(n)] for i in range(n): for j in range(i + 1, n): edges[i][j] = edges[j][i] = Edge(cities[i], cities[j], initial_pheromone) self.__graph['edges'] = edges size = int(f.readline()) gen = int(f.readline()) rho = float(f.readline()) phe_dep = float(f.readline()) alpha = float(f.readline()) beta = float(f.readline()) self.__aco_params = {'col_size': size, 'gen': gen, 'initial_pheromone': initial_pheromone, 'rho': rho, 'pheromone_deposit_weight': phe_dep, 'alpha': alpha, 'beta': beta } f.close()
def __init__(self): # ゲームの設定 self.name = "05_example" pyxel.init(256, 256, caption=self.name, scale=2, fps=15) pyxel.load("my_resource.pyxres") scale = int(256/16) self.map = City(16, 16) # int(pyxel.width), int(pyxel.height/8)) self.map.data = np.ones((self.map.h, self.map.w), dtype=np.int) self.map.data[2:-2, 2:-2] = 0 self.map.data[6:-6, 6:-6] = 1 self.map.data[:, 4] = 0 self.map.data[5, :] = 0 self.real_size_map = copy.deepcopy(self.map.data ) # 自キャラの初期化 x = int(np.random.rand() * self.map.w) y = int(np.random.rand() * self.map.h) while self.map.data[y, x] != 0: x = int(np.random.rand() * self.map.w) y = int(np.random.rand() * self.map.h) c = 11 self.ego = Vehicle(x, y, c) # 実行 pyxel.run(self.update, self.draw)
def test_berlin(): city_name, station_id, station_name, lang = getCityFromString("Berlin") assert (city_name == "Berlin" and lang == "de" and station_id == "4563") city = City(city_name, station_id, station_name, lang) img = city.defaultGraph() with open("tests/berlin.png", "wb") as f: f.write(img.read()) f.close()
def test_koeln(): city_name, station_id, station_name, lang = getCityFromString("Köln") assert (city_name == "Köln" and lang == "de" and station_id == "4298") city = City(city_name, station_id, station_name, lang) img = city.defaultGraph() with open("tests/cologne.png", "wb") as f: f.write(img.read()) f.close()
def __init__(self, geocoder): self.local_time = LocalTime(geocoder) self.sun = Sun(geocoder) self.artwork = Artwork() self.city = City(geocoder) self.commute = Commute(geocoder) self.calendar = GoogleCalendar(geocoder) self.everyone = Everyone(geocoder)
def __init__(self): self.cities = [City(i) for i in range(N_CITIES)] self.goodMarket = GoodMarket() self.forexMarket = ForexMarket() self.calendar = Calendar()
def test_varsovie(): city_name, station_id, station_name, lang = getCityFromString("Varsovie") assert (city_name == "Varsovie" and lang == "fr" and station_id == "209") city = City(city_name, station_id, station_name, lang) img = city.defaultGraph() with open("tests/varsovie.png", "wb") as f: f.write(img.read()) f.close()
def CreateMap(): order = [i for i in range(totalCities)] for n in range(totalCities): temp = City(random.randint(1, mapSize), random.randint(1, mapSize)) map.append(temp) for x in range(0, popSize): population.append([]) random.shuffle(order) population[x] = list(order)
def init_with_coordinates_file(self, input_path): input_file = open(input_path, "r") self.cities_file_count = int(input_file.readline()) for index, line in enumerate(input_file): coord_list = line.split(" ") coord_list[1] = coord_list[1].split("\n")[0] new_city = City(int(coord_list[0]), int(coord_list[1]), index) self.add_city(new_city) input_file.close()
def test_zarago(): city_name, station_id, station_name, lang = getCityFromString( "Zaragoza please") assert (city_name == "Zaragoza" and lang == "en" and station_id == "238") city = City(city_name, station_id, station_name, lang) img = city.defaultGraph() with open("tests/zaragoza.png", "wb") as f: f.write(img.read()) f.close()
def ReadCityData(fileName): cities = [] with open(fileName, "r") as file: for line in file: line = line.split() if line: line = [int(i) for i in line] #converts elements to integers cities.append(City(line[0], line[1], line[2])) return cities
def __init__(self): # ゲームの設定 self.name = "03_example" self.state = State.START self.header = 32 #[pix] pyxel.init(96, 96, caption=self.name, scale=4, fps=15, palette=[0x000000, 0x1D2B53, 0x7E2553, 0x008751, 0xAB5236, 0x5F574F, 0xC2C3C7, 0xFFF1E8, 0xFF004D, 0xFFA300, 0xFFEC27, 0x00E436, 0x29ADFF, 0x83769C, 0xFF77A8, 0xFFCCAA]) # self.waiting_count = 7 # [frames] self.count = 0 # 画面遷移用カウンタ self.num_got_items = 0 self.max_items = 1e10 # これだけ獲得したら次の画面へ self.total_score = 0 # 運んだ量 # 地図の初期化 self.map = City(pyxel.width, pyxel.height-self.header) self.num_col_rooms = 3 self.num_row_rooms = 3 self.corrider_width = 1 self.map.create_map_dungeon(num_col_rooms=self.num_col_rooms, num_row_rooms=self.num_row_rooms, corrider_width=self.corrider_width, max_room_size_ratio=0.7, min_room_size_ratio=0.2 ) self.map.set_start() # 自キャラの初期化 self.num_vehicles = 4 self.cars = [] start_points = self.map.get_free_space(num=self.num_vehicles) for idx, xy in enumerate(start_points): x = xy[1] y = xy[0] v = Vehicle(x, y, 11) self.cars.append(v) self.map.occupancuy[y, x] = True for car in self.cars: print(self.map.dumpings.items()) if car.loaded: # print(self.map.dumpings.items()) car.dest = random.choice(list(self.map.dumpings.items())) # (idx, (y, x)) # キャラの目的地 # print("dest:===>") # print(car.dest) else: car.dest = random.choice(list(self.map.loadings.items())) # (idx, (y, x)) # キャラの目的地 # print("dest:===>") # print(car.dest) # 実行 pyxel.run(self.update, self.draw)
def __init__(self, city, boundingCircuit=False): """ This class __init__ method will crate a new city where: - Nodes are the same as the street network of the input city plus the four nodes describing the effective bounding box - Ways are each one a closed minimal circuit, a block If boundingCircuit=False it won't add the circuit drawing the full city bounding box, otherwise will add it as one more circuit. """ # Create the new blocks city, initially empty. streetsBB = city.getStreetsBoundingBox() c = ( streetsBB[0]+((streetsBB[2]-streetsBB[0])/2) , streetsBB[1]+((streetsBB[3]-streetsBB[1])/2) ) self.blocksCity = City.City( centerPos=c ) # Create a copy of the input city adding the bounding box as ways bc = BC.BoundCity(city) boundedCity = bc.getBoundCity() # Create a dictionary of intersection nodes circuits already found. # For each intersection node Id (dictionary key) it stores a list of circuit ways passing through it already found self.intNodeCircuitsFound_d = {} intNodes = boundedCity.getIntersectionNodes() for intN in intNodes: # get intersection nodes neighbors (just nodes) intNeigs = boundedCity.getNodeNeigNodes(intN) intNeigNs = [ x[0] for x in intNeigs ] # remove duplicates intNeigSet = set(intNeigNs) if len(intNeigSet)>2: self.intNodeCircuitsFound_d[intN]=[] # For each intersection node: for intN in self.intNodeCircuitsFound_d.keys(): # Get intersection node circuits already found intCircuitsFound = self.getIntCircuitsFound(intN,boundedCity) # Get new circuits from intersection node, not the found before intNCircuits = self.getIntCircuits(intN,boundedCity,intCircuitsFound) # Add circuits as ways in blocksCity and also to the intNodeCircuitsFound_d self.addCircuits(intNCircuits,boundedCity) if not boundingCircuit: # We have to delete the circuit drawing the full city bounding box. # Get four bounding box corner nodes: cornerBLn = self.blocksCity.getPointNearestNodeCloserThan(streetsBB[0],streetsBB[1]) cornerBRn = self.blocksCity.getPointNearestNodeCloserThan(streetsBB[0],streetsBB[3]) cornerTLn = self.blocksCity.getPointNearestNodeCloserThan(streetsBB[2],streetsBB[1]) cornerTRn = self.blocksCity.getPointNearestNodeCloserThan(streetsBB[2],streetsBB[3]) # Remove that way (circuit) that passes through all bounding box corners. bbFound = False i = 0 ways_l = self.blocksCity.getWays_d().keys() while (not bbFound) and (i<len(ways_l)): if (cornerBLn in self.blocksCity.getWayNodes(ways_l[i])) and (cornerBRn in self.blocksCity.getWayNodes(ways_l[i])) and (cornerTLn in self.blocksCity.getWayNodes(ways_l[i])) and (cornerTRn in self.blocksCity.getWayNodes(ways_l[i])): bbFound = True self.blocksCity.removeWay(ways_l[i]) else: pass i += 1
def test_plama(): city_name, station_id, station_name, lang = getCityFromString( "Palma de mallorca bitte") assert (city_name == "Palma de Mallorca" and lang == "de" and station_id == "3918") city = City(city_name, station_id, station_name, lang) img = city.defaultGraph() with open("tests/parlma.png", "wb") as f: f.write(img.read()) f.close()
def load_cities(cities_list): # load cities from the sorted by population file file = open("cities_population.txt", "r") for line in file: line = line.strip() values = line.split(",") city = City(None, values[0], None, values[1], values[2], values[3]) cities_list.append(city) file.close()
async def weather(ctx, language, name): channel = ctx.author.voice.channel city = City(name) data = city.getData() if language == "en": await text2Speech(language, data, ctx, channel) elif language == "tr": data = city.getName() + " şehrinde hava " + str( city.convert(city.getTemp())) + "derece." await text2Speech(language, data, ctx, channel)
def test_constructor(self): name = "Fooville" population = 10_000 demand = 100_000_000 plants = (NuclearPlant(1, 1), ) city = City(name, population, demand, plants) self.assertEqual(city.name, name) self.assertEqual(city.population, population) self.assertEqual(city.demand, demand) self.assertEqual(city.plants, plants)
def __init__(self): self.player = player.Player("Player 1", 20) self.city = City( self.player, World(self.player, [ World_Tile(enemy.Simple_Enemy(), False), World_Tile(enemy.Medium_Enemy(), False), World_Tile(enemy.Hard_Enemy(), False), World_Tile(enemy.Endboss(), True) ]))
def run_game(): pygame.init() # Set screen width and height 255 size = (800,650) screen = pygame.display.set_mode(size) sky = pygame.image.load('images/sky.png') city = City(screen) pygame.display.set_caption('Template') # Create object ai_settings = Settings() ship = Ship(screen,ai_settings) clouds = Group() aliens = Group() bullets = Group() clock = pygame.time.Clock() while True: # --- Main event loop # --- Game logic # --- Clearing the screen screen.blit(sky,(0,0)) # --- Update the game gf.check_events(ai_settings,screen,ship,bullets) ship.update(ai_settings,screen) city.update() city.blitme() gf.create_cloud(screen,clouds) gf.update_clouds(screen,clouds) clouds.draw(screen) gf.create_aliens(screen,aliens,city) gf.update_aliens(screen,aliens,ship) aliens.draw(screen) bullets.draw(screen) ship.blitme() # --- Updating the screen pygame.display.flip() # --- Limit to 60 FPS clock.tick(60)