def __init__(self,nr_people,nr_homes,nr_workplaces,nr_socialplaces,city_size,percentage,contagiosity,immunity_step): self.nr_people = nr_people # number of citizens self.nr_homes = nr_homes # number of homes self.nr_workplaces = nr_workplaces # number of work_places self.nr_socialplaces = nr_socialplaces # number of social places self.city_size = city_size # the spatial dimension of the city self.percentage = percentage # the approximate percentage of infected people at the beginning self.contagiosity = contagiosity # the probability that you get infected if you are close to an infected person for a timestep self.immunity_step = immunity_step #increase of immunity per step for the infected; it is chosen such that it is smaller than 1/(number of steps per day), so the infected person does not heal over one day self.alpha = 10 # let it be! :D self.live_cam = True # True: shows every one at every time step, False: no over of the city self.live_stat = False #updates the graph of information every timestep. If False, it only shows the change after each commute or shift self.my_city = city(self.nr_people, self.nr_homes, self.nr_workplaces, self.nr_socialplaces, self.city_size, self.percentage, self.contagiosity, self.immunity_step, self.alpha, 0, self.live_cam, self.live_stat) # a duplicate of the city where no ones is sick and the disease is not contagiose self.healthy_city = city(self.nr_people, self.nr_homes, self.nr_workplaces, self.nr_socialplaces, self.city_size, 0, 0, self.immunity_step, self.alpha, 0, False, False) # create the population, assigning None to most of the attributions self.volk = create_citizens(self.my_city) seed_the_disease(self.my_city, self.volk) # create the houses of the city self.home = create_buildings(self.my_city, 'home') # create the work_places of the city self.work_place = create_buildings(self.my_city, 'work') # create the socialplaces of the city and assign people to them self.social_place = create_buildings(self.my_city, 'social_place') [self.volk, self.home] = assign_volk_to_buildings_and_vice_versa(self.volk, self.home) [self.volk, self.work_place] = assign_volk_to_buildings_and_vice_versa(self.volk, self.work_place) [self.volk, self.social_place] = assign_volk_to_buildings_and_vice_versa(self.volk, self.social_place)
def create_city(owa_id, iata, city_name = None, replace_entity = True): """ Create a city object and the assotiated IOT agent. Keyword arguments: cityOwmId -- the city id of openweathermap iata -- the IATA code of the city cityName (optional) -- The name of the city being stored in iot agent. Default is the name being stored in openweathermap. Returns: The created city object """ IOT_ACTIVE_ATTRIBUTES = city_definitions.IOT_ACTIVE_ATTRIBUTES IOT_COMMANDS = city_definitions.IOT_COMMANDS logger = logging.getLogger(__name__) the_city = city(owa_id,iata) # get some information for the static attributes associated to this city from the from openweathermap dict_owm_json = the_city.get_owm_json() latitude = dict_owm_json['coord']['lat'] longitude = dict_owm_json['coord']['lon'] if not city_name: city_name = dict_owm_json['name'] country = dict_owm_json['sys']['country'] iot_static_attributes = [('Position', 'geo:point',"{},{}".format(latitude, longitude)), ('Countrycode', 'string', country), ('Name', 'string', city_name)] device = { "device_id" : DEVICE_BASISNAME_MQTT + iata, "entity_name" : DEVICE_BASISNAME_CONTEXTBROKER + iata, "entity_type" : "Weather_Measuring_Station", "transport" : "MQTT", "attributes" : [{ "object_id" : a_id, "name" : a_name, "type" : a_type } for (a_id, a_name, a_type) in IOT_ACTIVE_ATTRIBUTES], "commands" : [{ "object_id" : a_id, "name" : a_name, "type" : a_type } for (a_id, a_name, a_type) in IOT_COMMANDS], "static_attributes" : [{ "name" : a_id, "type" : a_name, "value" : a_type } for a_id, a_name, a_type in iot_static_attributes] } device_list = {"devices" : [device]} delete_iot_agent(iata) delete_contextbroker_entity(iata, delete = replace_entity) # create the iot Agent logger.info("{}: Create IOT agent.".format(iata)) response = requests.post(IOT_AGENT_URL, json = device_list, headers = {'Fiware-Service': FIWARE_SERVICE, 'Fiware-ServicePath' : FIWARE_SERVICE_PATH}) if 201 == response.status_code: logger.info ("{}: IOT agent has been created!".format(iata)) else: logger.error("{}: IOT agent could not be created. Http error code: {}".format(iata, response.status_code)) # update the context broker logger.info("{}: Update city".format(iata)) if the_city.put_mqtt_json(city.convert_owm_to_mqtt(dict_owm_json)): logger.info("{}: Update sucessfully finished".format(iata)) else: logger.error("{}: city could not be updated".format(iata)) return the_city
def _add_cities(self): self.city_count = self.props.get(int, 'city_count') if self.city_count == 0 or self.city_max_pop == 0: self.city_count = self.city_count or max( int(self.props.get(int, 'city', 'min_count')), int( sround( int( pow(self.pop, self.props.get(float, 'city', 'auto_power')) / self.props.get(int, 'city', 'auto_divider')), 2))) self.city_max_pop = int(sround(self.pop // 3, 2)) self.city_min_pop = int(sround((self.pop - self.city_max_pop) // \ int(self.city_count * self.props.get(float, 'city', 'min_size_multiplier')), 2)) #print(f'!!! {self.city_count=} {self.city_max_pop=} {self.city_min_pop=}') else: self.city_max_pop, self.city_min_pop = self.props.get( int, 'city', 'max_pop'), self.props.get(int, 'city', 'min_pop') self.cities = [] pops = reciprocal(self.city_count, self.city_min_pop, self.city_max_pop, self.pop).get() for i, pop in enumerate(pops): location = self.geometry.random_location() c = city(f'C{len(self.cities)}', location, pop, self) self.cities.append(c) done = False while not done: done = True for c1, c2 in itertools.combinations(self.cities, 2): if c1.touches(c2): c2.location = self.geometry.random_location() done = False
def get_city_by_name(name): """ Create a city object. The IOT agent must already exist. Keyword arguments: cityName -- The name of the city being stored in iot agent and found it openweathermap and in IATA database. Returns: The created city object """ return city(*get_city_owm_id_and_iata(name))
def make_cities(n): '''Creates 10201 umbers from which 50 are randomly picked out''' nums = range(10201) points = random.sample(nums, n) cities = [] for i in points: cities.append(city(i)) return cities
def __init__(self): self.index = 0 # index in the population self.home = coordinates() # initial location self.pos = coordinates() # current location self.community = city() # current city/village self.state = 'S' # current diseased state # self.alive = True # whether he is alive self.in_city = True # if he's in a city (vs village) self.timeout = 0 # counting variable self.will_die = False # if hospitalized, will they die? self.will_h = False # if infected, will they go to the hospital? self.family = [] # list of family indices
def set_inputs(self, size, percentages, empty_percent, n_traits=2, min_rate=0.3, max_rate=1, n_neighs=0): if self.screen_type == "Neighbourhoods": self.city = city_neigh(size, n_neighs, percentages, empty_percent, n_traits, min_rate, max_rate) else: self.city = city(size, percentages, empty_percent, n_traits, min_rate, max_rate)
def __init__(self, width = 500, height = 200, days = 50, pop_size = 3, num_cities = 1, num_villages = 1): self.width = width # width of map self.height = height # height of map self.days = days # number of days to simulate self.pop_size = pop_size # population size self.grid = [[[] for i in range(self.width)] for j in range(self.height)] # store list of population indices at each grid cell self.grid_home = [[[] for i in range(self.width)] for j in range(self.height)] self.pop = [person() for i in range(self.pop_size)] self.cities = [city(self.width, self.height, 20) for i in range(num_cities)] # list of probabilities self.travel_prob = 0.2 self.home_prob = 0.5 # chance go home each timestep self.non_local_prob = 0.1 # chance for non-local travel self.fam_size_a = 3 self.fam_size_b = 6
def create_city(self, pos): c = city(pos) area = self.map.get_at_area(pos) c.area = area.name c.id = self.generate_id(self.cities) self.cities[c.id] = c self.last_created_city = c area.cities.append(c.id) for i in self.modules.values() : if hasattr(i,'city_created') : i.city_created(c) #roads.add_city(pos[0], pos[1], c.id) return c
def __init__( self, out, screen, tile_size, generator ): #avoid our attribute management system self.recurse_attributes = False self.screen = screen self.window = screen.get_size() self.tile_size = tile_size self.tile_dim = ( self.window[0]/tile_size[0], self.window[1]/tile_size[1] ) self.window = ( self.tile_dim[0] * tile_size[0], self.tile_dim[1] * tile_size[1] ) self.start_rect = Rect( (0,0), tile_size) self.ts = ts = tile_size self.hts = hts = (ts[0]/2, ts[1]/2) self.areas = [ [ area.area( vector3( x*ts[0] + hts[0], y*ts[1] + hts[1], 0 ), ts, potential = resource.resource( food = generator(x, y), wood = generator(x, y), gold = generator(x, y), stone = generator(x, y) ) ) for y in range( self.tile_dim[1] ) ] for x in range( self.tile_dim[0] ) ] self.cities = [ city.city( vector3( x + (hts[0]-5) * random.random(), y + (hts[1]-5) * random.random(), 0.0 ), out, area = self.get_area_at( x/ts[0], y/ts[1] ) ) for x in range(0, self.window[0], hts[0]) for y in range(0, self.window[1], ts[1]) ]
def start(): #load city data city_dict = city.city().getCity_Dictionary() while True: #input cityname for query cityname = raw_input("Enter city name, Enter 'Q' quit") # print input, city_dict[input] if cityname in city_dict.keys(): citycode = city_dict[cityname] w = Weather(cityname, citycode) data = w.getDataByURL(w.cityurl) w.parseWeatherData(data) elif cityname == 'Q': exit(1) else: print u'you input not china city' continue
#initialize pygame pygame.init() screen = pygame.display.set_mode( (800,600), 0, 24 ) screen.fill( (0,0,0) ) #create information display structures out = output.output( screen, 14 ) world = grid.grid( out, screen, (64,64), random_generator(36, 64) ) #create the factions area = world.get_area_at( 0, 0 ) area.faction_control[0] = 100 Thragg = world.cities[0] = city.city(area.pos, out, faction_ident=0, population=100, name="Thragg", area=area) orcs = faction.faction( 0, out, name = "orcs", cities = [ Thragg ], areas = world.linearize() ) orcs.preprocess() area = world.get_area_at( world.tile_dim[0]-1, world.tile_dim[1]-1 ) area.faction_control[1] = 100 Detroit = world.cities[ len(world.cities)-1 ] = city.city(area.pos, out, faction_ident=1, population=100,
def jobspider(city_code, city, provence): # 最大爬取页数 MAX_PAGE = 30 for i in range(1, MAX_PAGE + 1): job_signal = city + str(i) # print(job_signal) if job_signal in grouped.size().index: continue else: try: html = get_page(i, city_code) # ------------ 解析数据 --------------- parse(html, city, provence, i) print('-' * 100) time.sleep(random.randint(0, 3)) except Exception: break if __name__ == '__main__': # 获取市ID citylist = city.city() for city in citylist: city_code = city[0] provence = city[1] city = city[2] # 职位爬虫 jobspider(city_code, city, provence) # -----------------
def __init__(self, width = 70, height = 70, days = 500, pop_size = 1000, var = [], density = []): self.width = width # width of map self.height = height # height of map self.days = days # number of days to simulate self.pop_size = pop_size # population size self.num_cities = len(var) self.city_den = copy.deepcopy(density) self.grid = [[[] for j in range(self.width)] for i in range(self.height)] # store list of population indices at each grid cell self.grid_home = [[[] for j in range(self.width)] for i in range(self.height)] self.pop = [person() for i in range(self.pop_size)] self.cities = [city(self.width, self.height, var[i], density[i]) for i in range(self.num_cities)] #for i in range(self.num_cities): # print self.cities[i].loc.x, self.cities[i].loc.y self.R = [0 for i in range(self.pop_size)] self.repro = 0 # TODO: list of probabilities - maybe change this? self.travel_prob = 0.2 self.home_prob = 0.5 # chance go home each timestep self.non_local_prob = 0.5 # chance for non-local travel self.fam_size_a = 3 self.fam_size_b = 6 # CONTACT RATES self.b_fam = 0.1 self.b_com = 0.006 self.b_fun = 0.2 # funeral contact rate # PROBABILITIES self.i_mortality = 0.5 self.h_prob = 0.233 #0.248 self.h_mortality = 0.5 # TIMEOUTS self.incubation_time = 11 self.i_death_time = 8 # use random timeout, [7,9] self.i_death_time_a = 7 self.i_death_time_b = 9 self.funeral_time = 2.01 # use constant, 2 self.funeral_time_c = 2 self.r_time = 10 # use constant, 15 self.pre_h_time = 4.5 #4.6 # use random timeout, 1-5 self.pre_h_time_a = 3 self.pre_h_time_b = 6 self.h_recover_time = 5.5 # use random timeout, 13-18 self.h_recover_time_a = 5 self.h_recover_time_b = 6 self.h_death_time = 3.51 # use random timeout, 8-12 self.h_death_time_a = 3 self.h_death_time_b = 4 # count number infected in each way self.funeral_count = 0 self.family_count = 0 self.comm_count = 0 self.numberoffunerals = 0 self.num = [0 for i in range(7)] # total number in each state SEIHRFD for i in range(7): if i == 0: self.num[i] = self.pop_size else: self.num[i] = 0 self.numlist = [[] for i in range(7)]
def testCity(self): outstr = city('sandiego', 'chile') self.assertEqual(outstr, 'Sandiego Chile - population 5,000,000')
import pygame import person import city import matplotlib.pyplot as plt width = 800 length = 800 WHITE = [255, 255, 255] BLACK = [0, 0, 0] milan = city.city(N=100, simulation_timer=15000, show=True) milan.run_simulation() data = milan.results plt.plot(data[0]) plt.plot(data[1]) plt.plot(data[2]) plt.legend(['fine', 'sick', 'healed']) plt.xlabel('time') plt.ylabel('number of individuals') plt.show()
def create_city_from_a_cookbook(inputfilename): print('# inputfile: ' + inputfilename + '\n') inputfile = open(inputfilename, 'r') random_seed = int(inputfile.readline().split()[0]) # the random seed print('# random seed: ' + str(random_seed) + '\n') nr_people = int(inputfile.readline().split()[0]) # number of citizens print('# nr_people: ' + str(nr_people) + '\n') nr_homes = int(inputfile.readline().split()[0]) # number of homes print('# nr_homes: ' + str(nr_homes) + '\n') nr_workplaces = int( inputfile.readline().split()[0]) # number of work_places print('# nr_workplaces: ' + str(nr_workplaces) + '\n') nr_socialplaces = int( inputfile.readline().split()[0]) # number of social places print('# nr_socialplaces: ' + str(nr_socialplaces) + '\n') city_size = int( inputfile.readline().split()[0]) # the spatial dimension of the city print('# city_size: ' + str(city_size) + '\n') percentage = float( inputfile.readline().split() [0]) # the approximate percentage of infected people at the beginning print('# percentage: ' + str(percentage) + '\n') contagiosity = float( inputfile.readline().split()[0] ) # the probability that you get infected if you are close to an infected person for a timestep inputfile.readline().split()[0] print('# contagiosity: ' + str(contagiosity) + '\n') immunity_step = float( inputfile.readline().split()[0] ) #increase of immunity per step for the infected; it is chosen such that it is smaller than 1/(number of steps per day), so the infected person does not heal over one day print('# immunity_step: ' + str(immunity_step) + '\n') alpha = float(inputfile.readline().split()[0]) # let it be! :D print('# alpha: ' + str(alpha) + '\n') # True: shows every one at every time step, False: no over of the city live_cam = inputfile.readline().strip().split()[0] if (live_cam == 'False'): live_cam = False else: live_cam = True print('# live_cam: ' + str(live_cam) + '\n') # True:updates the graph of information every timestep. If False, it only shows the change after each commute or shift live_stat = inputfile.readline().strip().split()[0] if (live_stat == 'False'): live_stat = False else: live_stat = True print('# live_stat: ' + str(live_stat) + '\n') # True: completely mutes the graphical outputs mute = inputfile.readline().strip().split()[0] if (mute == 'False'): mute = False else: mute = True print('# mute: ' + str(mute) + '\n') max_individual_sociality = int( inputfile.readline().split() [0]) # maximum number of social places that one can go print('# max_individual_sociality: ' + str(max_individual_sociality) + '\n') random.seed(random_seed) np.random.seed(random_seed) my_city = city(nr_people, nr_homes, nr_workplaces, nr_socialplaces, city_size, percentage, contagiosity, immunity_step, alpha, 0, live_cam, live_stat, mute, max_individual_sociality) return my_city