Exemple #1
0
def scenario3():
    np.random.seed(7)
    # Simple SIR model.
    sampler = Sampler()
    n_days = 365 * 1
    population_size = 500_000
    I_initial = 500
    copenhagen = Region('Copenhagen',
                        population_size,
                        sampler,
                        I_initial,
                        cyclical=2.5)
    country = Country([copenhagen])

    np.random.seed(7)
    result = simulate(country, n_days=n_days)
    Plotter.plot_SIR(result)
    plt.legend()
    plt.xlabel('Days')
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '3_SEIR_periodic.png'), dpi=300)
    plt.show()

    np.random.seed(7)
    result = repeat_simulate(country, n_repeats=n_repeats, n_days=n_days)
    Plotter.plot_intervals(result['I_crit'].copy(), plot_median=False)
    plt.plot(result['I_crit'][0], '--k', label='Example path', lw=0.5)
    plt.xlabel('Days')
    plt.ylabel('# Hospitalized')
    plt.hlines(copenhagen.population_size * 0.0005, *plt.xlim())
    plt.legend()
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '3_SEIR_periodic_hospitalized.png'),
                dpi=300)
    plt.show()

    sampler = Sampler()
    n_days = 365 * 4
    population_size = 500_000
    I_initial = 500
    copenhagen = Region('Copenhagen',
                        population_size,
                        sampler,
                        I_initial,
                        cyclical=2.5)
    country = Country([copenhagen])

    np.random.seed(7)
    result = repeat_simulate(country, n_repeats=n_repeats, n_days=n_days)
    Plotter.plot_intervals(result['I_crit'].copy(), plot_median=False)
    plt.plot(result['I_crit'][0], '--k', label='Example path', lw=0.5)
    plt.xlabel('Days')
    plt.ylabel('# Hospitalized')
    plt.hlines(copenhagen.population_size * 0.0005, *plt.xlim())
    plt.legend()
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path,
                             '3_SEIR_periodic_hospitalized_long.png'),
                dpi=300)
    plt.show()
    def gameSetting(self):

        self.vaccineList = list()
        self.countryInfectedList = list()
        self.countryCuredList = list()
        self.countryList = list()
        self.countryCuredStr = ""
        self.numVaccine = 3
        self.numCountry = 5
        self.numCountryInfected = 5
        self.numCountryCured = 0
        self.totalInfectIncrease = 0
        self.totalCured = 0

        southKorea = Country("South Korea", 1500, 300)
        china = Country("China", 3000, 800)
        japan = Country("Japan", 2000, 500)
        US = Country("US", 2500, 750)
        germany = Country("Germany", 2200, 1000)
        self.countryInfectedList.append(southKorea)
        self.countryInfectedList.append(china)
        self.countryInfectedList.append(japan)
        self.countryInfectedList.append(US)
        self.countryInfectedList.append(germany)
        self.countryList = self.countryInfectedList

        vac1 = Vaccine("vaccine 1", 25.0)
        vac2 = Vaccine("vaccine 2", 50.0)
        vac3 = Vaccine("vaccine 3", 100.0)
        self.vaccineList.append(vac1)
        self.vaccineList.append(vac2)
        self.vaccineList.append(vac3)
Exemple #3
0
def reset_DB():
  conn = get_connection()

  Reservation.drop_table(conn)
  Client.drop_table(conn)
  Room.drop_table(conn)
  Hotel.drop_table(conn)
  Country.drop_table(conn)

  Country.reset_table(conn)
  Hotel.reset_table(conn)
  Room.reset_table(conn)
  Client.reset_table(conn)
  Reservation.reset_table(conn)
Exemple #4
0
    def load_dict_countries_states_cities(countries, glb):

        dict_countries = dict()
        dict_cities = dict()

        for country_name in countries:
            country = Country(country_name)
            dict_countries[country_name] = country

        data = funs.load_pkl_file('flt_location_data.pkl')

        data = [(ci, co, st, a2, a3, p, lat, lon)
                for (ci, co, st, a2, a3, p, lat, lon) in data
                if co in countries]

        #        print dict_countries['mexico'].dict_states
        for (ci, co, st, a2, a3, p, lat, lon) in data:
            try:  # Neglect locations where the corresponding countries are not in the list
                if co:
                    co = co.lower()
                    country = dict_countries[co]
                    if ci:
                        city = City(ci, (lat, lon))
                        city.co_name = country.name
                        dict_cities[city.latlong] = city
                    if st:
                        if not country.dict_states.has_key(st):
                            country.dict_states[st] = State(st)
                        state = country.dict_states[st]
                        state.co_name = country.name
                        city.st_name = st
                        state.dict_cities[city.latlong] = city


#                    dict_city_keywords[city.latlong] = dict()
            except:
                pass

        for co_name, country in dict_countries.items():
            #            print co_name
            for st_name, state in country.dict_states.items():
                print st_name
                state.update_latlong(
                )  # calcualte the center of the cities in the state as the state location
                state.build_city_neighborhood_graph()
                state.kdtree = None
            country.update_cities(
            )  # merge cities in states into a single dictionary
            country.build_state_neighborhood_graph(
            )  # built based on k nearest neighbors
            country.kdtree = None

        dict_states = dict()
        for co_name, country in dict_countries.items():
            for st_name, state in country.dict_states.items():
                dict_states[(co_name, st_name)] = state

        return dict_countries, dict_states, dict_cities
Exemple #5
0
 def processSingleDataPoint(self, latitude, longitude):
     location = Location(latitude, longitude)
     try:
         data = self._gmaps.reverse_geocode(
             (location.latitude, location.longitude))
         for addressItem in data[0]['address_components']:
             if 'street_number' in addressItem['types']:
                 location.number = addressItem['long_name']
             elif 'sublocality_level_1' in addressItem['types']:
                 location.district = addressItem['long_name']
             elif 'administrative_area_level_2' in addressItem['types']:
                 location.city = addressItem['long_name']
             elif 'country' in addressItem['types']:
                 country = Country(addressItem['long_name'])
             elif 'administrative_area_level_1' in addressItem['types']:
                 state = State(addressItem['long_name'],
                               addressItem['short_name'])
             elif 'postal_code' in addressItem['types']:
                 location.zipcode = addressItem['long_name']
             elif 'route' in addressItem['types']:
                 location.address = addressItem['long_name']
         state.country = country
         location.state = state
         return location
     except Exception as e:
         print(e)
         return []
Exemple #6
0
 def __init__(self, continentFileName, countryFileName):  #open the file
     cDictionary = dict()
     catalogue = []  #create the variables
     fileContinent = open(continentFileName, "r")
     allContentinContinent = fileContinent.readlines()
     for line in allContentinContinent:
         line = line.strip("\n")
         line = line.split(",")
         cDictionary[str(line[0])] = line[1]
     cDictionary.pop("Country")
     self._cDictionary = cDictionary
     #create the dictionary
     fileCountry = open(countryFileName, "r")
     allContentinCountry = fileCountry.readlines()
     for line in allContentinCountry:
         line = line.strip("\n")
         line = line.split("|")
         if line[0] == "Country":
             continue
         else:
             temp = Country(line[0], line[1], line[2],
                            self._cDictionary[line[0]])
             catalogue.append(temp)
     self._catalogue = catalogue
     #create the catalogue within which the element is country class object
     fileContinent.close()
     fileCountry.close()
 def get(self, path):
     try:
         print('CountryHandler')
         print(self.request.uri)
         print(self.get_argument('key'))
         #val = urllib.parse.unquote(self.get_argument('key'))
         val = tornado.escape.url_unescape(self.get_argument('key'))
         print('val is ' + val)
         referer = self.request.headers.get('Referer')
         try:
             lang = re.search(r'-(.*)\..*', referer).group(1)
         except:
             lang = 'cn'
         if Country.isCountry(val):
             print('content country is ' + val)
             self.write(getCitiesFromCountry(val, lang))
         else:
             print('404 not found ' + val)
             self.write('{"link":"http://' + self.request.host +
                        '/html/404.html"}')
         print(
             '===========================================================')
     except Exception as e:
         print('EXCEPTION FROM CountryHandler get:')
         print(e)
Exemple #8
0
def readFromFile():
    fileName = "countries/countries.txt"
    with open(fileName, "r") as myFile:
        for line in myFile.readlines():
            lines = line.split(",")
            country = Country(lines[0], lines[1])
            print('{} (pop {:,d})'.format(country.name,
                                          int(country.population)))
Exemple #9
0
def readFile():
    file = open("currency_details.txt" ,encoding="utf8");
    for line in file:
        print(line)
        data = line.split(",");
        c = Country(data[0], data[1], data[2])
        cList.append(c);
    file.close();
Exemple #10
0
def country_init(x):
    """自定义你的国家"""
    init_input = "请输入" + str(x) + "国的"
    nuclear_lock = input("\n" + init_input + "核能上限: ")
    ice_lock = input("\n" + init_input + "可燃冰上限: ")
    creature_lock = input("\n" + init_input + "生物质能上限: ")
    oil_lock = input("\n" + init_input + "石油上限: ")
    coal_lock = input("\n" + init_input + "煤上限: ")
    x = Country(nuclear_lock, ice_lock, creature_lock, oil_lock, coal_lock)
 def get(self, path):
     try:
         print('POICountryHandler')
         print(self.request.uri)
         self.write(Country.getAllCountries())
         print(
             '===========================================================')
     except Exception as e:
         print('EXCEPTION FROM POICountryHandler get:')
         print(e)
Exemple #12
0
 def addCountry(self, countryName, countryPopulation, countryArea,
                countryContinent):
     if countryName in self._cDictionary.keys():
         return False
     else:
         temp2 = Country(countryName, countryPopulation, countryArea,
                         countryContinent)
         self._catalogue.append(temp2)
         (self._cDictionary)[countryName] = countryContinent
         ###
         return True
    def get(self, path):
        try:
            print('SearchHandler')
            print(self.request.uri)
            print(self.get_argument('key'))
            #val = urllib.parse.unquote(self.get_argument('key'))
            val = tornado.escape.url_unescape(self.get_argument('key'))

            #bytesString = val.encode(encoding="utf-8")
            #decodestr = base64.b64decode(bytesString)
            #print('aaaaaaaaaaaaaaaaa')
            #print(len(decodestr.decode()))  # 'hello world'
            #print('bbbbbbbbbbbbbbbbb')
            #if len(decodestr.decode()) != 0:
            #val = decodestr.decode()

            # remove ';' from val if exists
            # otherwise, 'select * from mytable where mycolumn = abc;def' will produce an error coming from 'def', which can't be caught by try...catch...
            val = val.replace(";", "")
            if not val:
                return
            matchDefense = patternDefense.match(val)
            if matchDefense:
                # WARNING!!!
                # someone is trying to do web injection attacks
                self.write(
                    '{"link":"https://image.baidu.com/search/detail?ct=503316480&z=&tn=baiduimagedetail&ipn=d&word=%E6%89%93%E5%87%BB%E9%BB%91%E5%AE%A2&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=-1&cs=623464961,1255249105&os=4288987045,2593232107&simid=3471060388,531993260&pn=1&rn=1&di=35735023170&ln=1963&fr=&fmq=1497945237455_R&fm=result&ic=0&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&is=0,0&istype=2&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=http%3A%2F%2Fwww.17waihui.com%2Fuploadfile%2F2015%2F0720%2F20150720034036427.jpg&rpstart=0&rpnum=0&adpicid=0&ctd=1497945272672^3_1173X680%1"}'
                )
                return
            print('key is ' + val)
            msg = urllib.parse.quote(val)
            head = self.request.headers.get('Origin')
            head = head if head else ("http://" + self.request.host)
            # for search
            # when user is searching some word somewhere, the frontend doesn't know which page should be loaded
            if Country.isCountry(val):
                print('link to new page: country is ' + val)
                self.write('{"link":"http://' + self.request.host +
                           '/html/country.html?' + msg + '"}')
            elif City.isCity(val):
                print('link to new page: city is ' + val)
                self.write('{"link":"http://' + self.request.host +
                           '/html/city.html?' + msg + '"}')
            else:
                self.write('{"link":"http://' + self.request.host +
                           '/html/404.html"}')
                print('404 not found ' + val)
            print(
                '===========================================================')
        except Exception as e:
            print('EXCEPTION FROM SearchHandler get:')
            print(e)
    def movement_data(self):
        files = glob.glob("resources/mobilityData/*.json")

        for file_path in files:
            with open(file_path) as file:
                data = file.read()
                raw = json.loads(data)

                for entry in raw:
                    if not entry["country"] in self.countries:
                        self.countries[entry["country"]] = Country(
                            entry["country"])

                    self.countries[entry["country"]].add_movement(entry)
    def load_dict_countries_states_cities(countries, glb):
    
        dict_countries = dict()
        dict_cities = dict()
    
        for country_name in countries:
            country = Country(country_name)
            dict_countries[country_name] = country
    
        data = funs.load_pkl_file('flt_location_data.pkl')
        
        data = [(ci, co, st, a2, a3, p, lat, lon) for (ci, co, st, a2, a3, p, lat, lon) in data if co in countries]
    
#        print dict_countries['mexico'].dict_states
        for (ci, co, st, a2, a3, p, lat, lon) in data:
            try: # Neglect locations where the corresponding countries are not in the list
                if co:
                    co = co.lower()
                    country = dict_countries[co]
                    if ci:
                        city = City(ci, (lat,lon))
                        city.co_name = country.name
                        dict_cities[city.latlong] = city
                    if st:
                        if not country.dict_states.has_key(st):
                            country.dict_states[st] = State(st)
                        state = country.dict_states[st]
                        state.co_name = country.name
                        city.st_name = st
                        state.dict_cities[city.latlong] = city
#                    dict_city_keywords[city.latlong] = dict()
            except:
                pass

        for co_name, country in dict_countries.items():
#            print co_name
            for st_name, state in country.dict_states.items():
                print st_name
                state.update_latlong() # calcualte the center of the cities in the state as the state location
                state.build_city_neighborhood_graph()
                state.kdtree = None
            country.update_cities() # merge cities in states into a single dictionary
            country.build_state_neighborhood_graph() # built based on k nearest neighbors
            country.kdtree = None

        dict_states = dict()
        for co_name, country in dict_countries.items():
            for st_name, state in country.dict_states.items():
                dict_states[(co_name, st_name)] = state
    
        return dict_countries, dict_states, dict_cities
Exemple #16
0
def build_simple_six_map():

    my_map = Map()
    gradient_of_randomness = [0, 15, 30, 80, 90, 100]
    random.shuffle(gradient_of_randomness)
    Player1 = Player('ai_player', my_map, gradient_of_randomness[0])
    Player2 = Player('player2', my_map, gradient_of_randomness[1])
    Player3 = Player('player3', my_map, gradient_of_randomness[2])
    Player4 = Player('player4', my_map, gradient_of_randomness[3])
    Player5 = Player('player5', my_map, gradient_of_randomness[4])
    Player6 = Player('player6', my_map, gradient_of_randomness[5])
    Player1.resetPlayerIndex()
    Player_list = my_map.getPlayerList()
    ireland = Country('ireland', my_map, 5, 5, (1, 2, 3))
    scotland = Country('scotland', my_map, 7, 5, (0, 2, 10))
    wales = Country('wales', my_map, 7, 6, (2, 2, 3))
    france = Country('france', my_map, 6, 7, (2, 2, 3))
    england = Country('england', my_map, 6, 6, (0, 2, 10))
    ni = Country('NI', my_map, 5, 6, (1, 2, 3))
    Country_list = my_map.nodes()
    my_map.makeNeighbours(england, ireland)
    my_map.makeNeighbours(ni, ireland)
    my_map.makeNeighbours(scotland, wales)
    my_map.makeNeighbours(england, wales)
    my_map.makeNeighbours(england, scotland)
    my_map.makeNeighbours(ireland, scotland)
    my_map.makeNeighbours(wales, france)
    #ireland.setRuler(Player1)
    index_list = [0, 1, 2, 3, 4, 5]
    random.shuffle(index_list)
    counter = 0
    while counter < len(Country_list):

        if counter % len(index_list) == 0:
            random.shuffle(index_list)
        Player_list[index_list[counter % len(index_list)]].addCountry(
            Country_list[counter])

        counter += 1

    #Player1.addCountry(ireland)
    #Player1.addCountry(ni)
    #Player2.addCountry(england)
    #Player3.addCountry(scotland)
    #Player3.addCountry(wales)
    #Player2.addCountry(france)

    #for node in my_map.nodes():
    #  node.setSoldiers(random.randint(1,6))
    for i in range(16):
        for player in Player_list:
            player.place_random_soldier()

    return my_map
    def case_date(self):
        file_path = resources / "train.csv"

        with open(file_path) as file:
            reader = csv.DictReader(file, delimiter=",", quotechar='"')

            for row in reader:
                entry = {
                    "Region": row["Province_State"],
                    "Cases": float(row["ConfirmedCases"]),
                    "Fatalities": float(row["Fatalities"])
                }

                if (row['Country_Region']) in self.countries:
                    self.countries[row['Country_Region']].add_cases(
                        row['Date'], entry)
                else:
                    self.countries[row['Country_Region']] = Country(
                        row['Country_Region'])
                    self.countries[row['Country_Region']].add_cases(
                        row['Date'], entry)
Exemple #18
0
def scenario1():
    np.random.seed(7)
    # Simple SIR model.
    sampler = Sampler(crit_prob=0.0,
                      symp_prob=1.0,
                      fraction_symp_out=1.0,
                      incubation=False)
    # We have S -> I_symp -> R
    # We get an R0 of 6.86*4.67416*0.04 = 1.28259
    # (Only true for memoryless? i.e. because we can just multiply by avg. sympt time.)

    population_size = 500_000
    I_initial = 5_000
    copenhagen = Region('Copenhagen', population_size, sampler, I_initial)
    country = Country([copenhagen])

    contageon_probs = [0.03, 0.04, 0.06, 0.10]
    fig, axs = plt.subplots(1,
                            len(contageon_probs),
                            squeeze=True,
                            sharey='row',
                            figsize=(12, 4.5))
    for ax, contageon_prob in zip(axs, contageon_probs):
        sampler.contagion_prob = contageon_prob
        result = simulate(country)
        Plotter.plot_SIR(result, ax=ax)
        ax.set_title(f'$p={contageon_prob:.2f}$')
        ax.set_xlabel('Days')
    ax.set_xlabel('')
    ax.legend(['I', 'S', 'R'],
              loc='upper center',
              bbox_to_anchor=(0.5, -0.17),
              fancybox=False,
              shadow=False,
              ncol=3)
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])
    # fig.legend(['S', 'I', 'R'], bbox_to_anchor=(2, 0), loc='lower right')
    # plt.subplots_adjust(left=0.07, right=0.93, wspace=0.25, hspace=0.35)
    plt.savefig(os.path.join(plot_path, '1_SIR.png'), dpi=300)
    plt.show()
Exemple #19
0
def scenario4():
    # High death rate
    sampler = Sampler(death_prob=1.0,
                      crit_prob=1.0,
                      symp_prob=1.0,
                      contagion_prob=0.0228)
    #  6.86*4.67416*0.04 = 1.28259
    n_days = 5000
    population_size = 500_000
    I_initial = 5_000
    copenhagen = Region('Copenhagen', population_size, sampler, I_initial)
    country = Country([copenhagen])

    np.random.seed(7)
    result = simulate(country, n_days=n_days)
    Plotter.plot_SIR(result)
    plt.legend()
    plt.xlabel('Days')
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '4_DEATH.png'), dpi=300)
    plt.show()

    np.random.seed(7)
    result = repeat_simulate(country, n_repeats=n_repeats, n_days=n_days)
    Plotter.plot_intervals(
        (result['R_dead'] / copenhagen.population_size).copy() * 100,
        plot_median=False)
    plt.plot((result['R_dead'] / copenhagen.population_size)[0] * 100,
             '--k',
             label='Example path',
             lw=0.5)
    plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter())
    plt.xlabel('Days')
    plt.ylabel('% Dead')
    plt.hlines(100, *plt.xlim())
    plt.legend()
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '4_DEATH_deaths.png'), dpi=300)
    plt.show()
Exemple #20
0
def main(args):
    name = ""
    population = 0
    action = 0
    # This creates a directory if there isn't one
    # FileIOHelper.createDir()
    # This creates a file if there isn't one
    # FileIOHelper.createOurFile()
    while not action == 3:
        print("\n\nWelcome to the Countries Maintenance Application!")
        print("1 - See the list of countries\n2 - Add a country\n3 - Exit\n")
        action = Validator.getInt("Enter a number: ", 1, 3)
        if action == 1:
            FileIOHelper.readFromFile()
        elif action == 2:
            country = Validator.getString("Enter country: ")
            population = Validator.getInteger("Enter population: ")
            new_country = Country(country, population)
            FileIOHelper.writeToFile(new_country)
        else:
            print("Buh-bye!")
            break
Exemple #21
0
def parse_json(json_in):
    country_result = []
    country_dict = dict()

    """
         Adds a country to the dictionary if it does not already exist
    """
    for p in json_in['partners']:
        employee = Partner(p)
        if employee.country not in country_dict:
            country_dict[employee.country] = dict()

        """
            Sets an employee under the subdictionary to hold the available dates
        """
        for available in employee.dates_available:
            if available not in country_dict[employee.country]:
                country_dict[employee.country][available] = set()
            country_dict[employee.country][available].add(employee)


        for country, dates in country_dict.items():
            sorted_dates = sorted(dates.keys())
            min_attendees = 0
            min_days = None
            max_attendees = set()

            """
                Parses all date formats to a readable form that can be used to compare. This is how to find two
                dates that are consecutive
            """
            for i in range(len(sorted_dates[:-1])):

                current_date = sorted_dates[i]
                current_tomorrow = sorted_dates[i+1]
                current_date_formatted = parse(current_date)
                current_tomorrow_formatted = parse(current_tomorrow)

                date_attendees = dates[current_date]
                tomorrow_attendees = dates[current_tomorrow]

                if current_tomorrow_formatted - current_date_formatted != datetime.timedelta(1):
                    continue
                attendees = date_attendees & tomorrow_attendees
                attend_total = len(attendees)

                """
                    Sets a new date if the total number of attendees for a given date is greater than the already
                    existing max date
                """
                if attend_total > min_attendees:
                    min_attendees = attend_total
                    min_days = current_date
                    max_attendees = attendees
            """
                Creates Country objects to hold the correct format able to be put into JSON
            """
            country = Country()
            country.name = country
            if min_attendees > 0:
                country.final_start_date = min_attendees
            for attendee in max_attendees:
                country.add(attendee)
            country_result.append(country)
            return country_result
Exemple #22
0
def addCountry():
    name = Validator.inputCountry("Enter country name: ")
    population = Validator.inputPopulation("enter country population: ")
    country = Country(name, population)
    countries.append(country)
Exemple #23
0
from Validator import Validator
from Country import Country

china = Country("China", 1415045928)
egypt = Country("Egypt", 99375741)
italy = Country("Italy", 59290969)
turkey = Country("Turkey", 81916871)
russia = Country("Russia", 144500000)
india = Country("India", 1339000000)
canada = Country("Canada", 36710000)
australia = Country("Australia", 24600000)
germany = Country("Germany", 82790000)

countries = [
    china, egypt, italy, turkey, russia, india, canada, australia, germany
]


def printCountries():
    for country in countries:
        country.displayCountry()


def addCountry():
    name = Validator.inputCountry("Enter country name: ")
    population = Validator.inputPopulation("enter country population: ")
    country = Country(name, population)
    countries.append(country)


def byCountry():
Exemple #24
0
def scenario2():
    # SEIR model.
    sampler = Sampler()  # crit_prob=0.0, symp_prob=1.0, fraction_symp_out=1.0
    # We have S -> E (latent/incubation period) -> I_symp -> R

    population_size = 500_000
    I_initial = 500
    copenhagen = Region('Copenhagen', population_size, sampler, I_initial)
    country = Country([copenhagen])

    contageon_probs = [0.02, 0.025, 0.04, 0.05]
    average_people_mets = [4, 5, 6.86, 10]
    symp_people_out = [0.0, 0.1, 0.5, 1]

    fig, axs = plt.subplots(1,
                            len(contageon_probs),
                            squeeze=True,
                            sharey='row',
                            figsize=(12, 4))
    for i, (ax, contageon_prob) in enumerate(zip(axs, contageon_probs)):
        sampler.contagion_prob = contageon_prob
        np.random.seed(7)
        result = simulate(country)
        Plotter.plot_SIR(result, ax=ax)
        ax.set_title(f'$p={contageon_prob:.3f}$')
        ax.set_xlabel('Days')
        if i == len(contageon_probs) - 1:
            ax.legend(['I', 'S', 'Recovered', 'Dead'],
                      loc='upper center',
                      bbox_to_anchor=(1.5, 1),
                      fancybox=False,
                      shadow=False,
                      ncol=1)
        if i == 2:
            ax.set_title(f'$\\bf p={contageon_prob:.3f}$')
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '2_SEIR_hygene.png'), dpi=300)
    plt.show()

    fig, axs = plt.subplots(1,
                            len(contageon_probs),
                            squeeze=True,
                            sharey='row',
                            figsize=(12, 4))
    for i, (ax, contageon_prob) in enumerate(zip(axs, contageon_probs)):
        sampler.contagion_prob = contageon_prob
        np.random.seed(7)
        result = repeat_simulate(country, n_repeats=n_repeats)
        Plotter.plot_intervals(result['I_crit'],
                               ax=ax,
                               colorbar=i == len(contageon_probs) - 1)
        ax.set_title(f'$p={contageon_prob:.3f}$')
        ax.set_xlabel('Days')
        if i == 0:
            ax.set_ylabel('# Hospitalized ($I_{crit}$)')
        if i == 2:
            ax.set_title(f'$\\bf p={contageon_prob:.3f}$')
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '2_SEIR_hygene_hospitalized.png'),
                dpi=300)
    plt.show()

    sampler.contagion_prob = 0.04  # Set back to default
    fig, axs = plt.subplots(1,
                            len(average_people_mets),
                            squeeze=True,
                            sharey='row',
                            figsize=(12, 4))
    for i, (ax,
            avg_people_met_pr_day) in enumerate(zip(axs, average_people_mets)):
        sampler.avg_people_met_pr_day = avg_people_met_pr_day
        np.random.seed(7)
        result = simulate(country)
        Plotter.plot_SIR(result, ax=ax)
        ax.set_title(f'$Avg. met ={avg_people_met_pr_day:.2f}$')
        if i == 2:
            ax.set_title(f'$\\bf Avg. met ={avg_people_met_pr_day:.2f}$')
        ax.set_xlabel('Days')
        if i == len(average_people_mets) - 1:
            ax.legend(['I', 'S', 'Recovered', 'Dead'],
                      loc='upper center',
                      bbox_to_anchor=(1.5, 1),
                      fancybox=False,
                      shadow=False,
                      ncol=1)
    plt.tight_layout()  # rect=[0, 0.03, 1, 0.95]
    plt.savefig(os.path.join(plot_path, '2_SEIR_distancing.png'), dpi=300)
    plt.show()

    fig, axs = plt.subplots(1,
                            len(contageon_probs),
                            squeeze=True,
                            sharey='row',
                            figsize=(12, 4))
    for i, (ax,
            avg_people_met_pr_day) in enumerate(zip(axs, average_people_mets)):
        sampler.avg_people_met_pr_day = avg_people_met_pr_day
        np.random.seed(7)
        result = repeat_simulate(country, n_repeats=n_repeats)
        Plotter.plot_intervals(result['I_crit'],
                               ax=ax,
                               colorbar=i == len(contageon_probs) - 1)
        ax.set_title(f'$Avg. met ={avg_people_met_pr_day:.2f}$')
        ax.set_xlabel('Days')
        if i == 0:
            ax.set_ylabel('# Hospitalized')
        if i == 2:
            ax.set_title(f'$\\bf Avg. met ={avg_people_met_pr_day:.2f}$')
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '2_SEIR_distancing_hospitalized.png'),
                dpi=300)
    plt.show()

    sampler.avg_people_met_pr_day = 6.86  # Set back to default
    fig, axs = plt.subplots(1,
                            len(symp_people_out),
                            squeeze=True,
                            sharey='row',
                            figsize=(12, 4))
    for i, (ax, fraction_symp_out) in enumerate(zip(axs, symp_people_out)):
        sampler.fraction_symp_out = fraction_symp_out
        np.random.seed(7)
        result = simulate(country)
        Plotter.plot_SIR(result, ax=ax)
        ax.set_title(f'$p_o ={fraction_symp_out * 100:.1f}$%')
        if i == 1:
            ax.set_title(f'$\\bf p_o ={fraction_symp_out * 100:.1f}\%$')
        ax.set_xlabel('Days')
        if i == len(symp_people_out) - 1:
            ax.legend(['I', 'S', 'Recovered', 'Dead'],
                      loc='upper center',
                      bbox_to_anchor=(1.5, 1),
                      fancybox=False,
                      shadow=False,
                      ncol=1)
    plt.tight_layout()  # rect=[0, 0.03, 1, 0.95]
    plt.savefig(os.path.join(plot_path, '2_SEIR_symp_out.png'), dpi=300)
    plt.show()

    fig, axs = plt.subplots(1,
                            len(symp_people_out),
                            squeeze=True,
                            sharey='row',
                            figsize=(12, 4))
    for i, (ax, fraction_symp_out) in enumerate(zip(axs, symp_people_out)):
        sampler.fraction_symp_out = fraction_symp_out
        np.random.seed(7)
        result = repeat_simulate(country, n_repeats=n_repeats)
        Plotter.plot_intervals(result['I_crit'],
                               ax=ax,
                               colorbar=i == len(contageon_probs) - 1)
        ax.set_title(f'$p_o ={fraction_symp_out * 100:.1f}$%')
        ax.set_xlabel('Days')
        if i == 0:
            ax.set_ylabel('# Hospitalized')
        if i == 1:
            ax.set_title(f'$\\bf p_o ={fraction_symp_out * 100:.1f}\%$')
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '2_SEIR_symp_out_hospitalized.png'),
                dpi=300)
    plt.show()

    if False:  # 2D grid plots
        fig, axs = plt.subplots(len(average_people_mets),
                                len(contageon_probs),
                                squeeze=False,
                                sharey='row',
                                sharex='col',
                                figsize=(12, 12))
        for j, axs2 in enumerate(axs):
            for i, ax in enumerate(axs2):
                contageon_prob = contageon_probs[i]
                average_people_met = average_people_mets[j]
                sampler.contagion_prob = contageon_prob
                sampler.avg_people_met_pr_day = average_people_met
                result = simulate(country)
                Plotter.plot_SIR(result, ax=ax)
                if j == 0:
                    ax.set_title(f'$p={contageon_prob:.2f}$')
                if j == len(average_people_mets) - 1:
                    ax.set_xlabel('Days')
                    if i == 1:
                        ax.legend(['I', 'S', 'Recovered', 'Dead'],
                                  loc='lower left',
                                  bbox_to_anchor=(0.5, -0.54, 2, .102),
                                  fancybox=False,
                                  shadow=False,
                                  ncol=4)
                if i == 0:
                    ax.set_ylabel(f'$Avg. met. ={average_people_met:.2f}$')

        plt.savefig(os.path.join(plot_path, '2_SEIR.png'), dpi=300)
        plt.show()
Exemple #25
0
def scenario5():
    # Control variables
    np.random.seed(7)
    sampler = Sampler()  # (symp_prob=0.98, crit_prob=0.98, death_prob=0.1)
    n_days = 50
    population_size = 5_000
    I_initial = 100
    copenhagen = Region('Copenhagen', population_size, sampler, I_initial)
    country = Country([copenhagen])

    np.random.seed(7)
    result = simulate(country, n_days=n_days)
    Plotter.plot_SIR(result)
    plt.legend()
    plt.xlabel('Days')
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '5_CONTROL.png'), dpi=300)
    plt.show()

    np.random.seed(7)
    result = repeat_simulate(country, n_repeats=n_repeats, n_days=n_days)
    Plotter.plot_intervals(result['R_dead'].copy(), plot_median=False)
    plt.plot(result['R_dead'][0], '--k', label='Example path', lw=0.5)
    plt.xlabel('Days')
    plt.ylabel('# Dead')
    # plt.hlines(copenhagen.population_size * 0.0005, *plt.xlim())
    plt.legend()
    plt.tight_layout()
    plt.savefig(os.path.join(plot_path, '5_CONTROL_DEATH_2500.png'), dpi=300)
    plt.show()

    def control(x, control_variable, mu_control=None):
        # mu_control = np.mean(control_variable)
        # fx = f(x)
        variances = np.cov(x, control_variable)

        # print('Control correlation:', np.corrcoef(x, control_variable)[1, 0])
        c = -variances[0, 1] / variances[1, 1]
        return x + c * (control_variable - mu_control)

    def confidence_interval(sample):
        mean, var, _ = stats.bayes_mvs(sample)
        return dict(x=mean.statistic, xerr=mean.minmax[1] - mean.statistic)

    x = 'max_R_dead'
    plt.errorbar(y=-1,
                 **confidence_interval(result[x]),
                 lw=1,
                 fmt='o',
                 capsize=10)

    for i, (control_var, mu) in enumerate(
            zip(Region.control_variates, [
                sampler.avg_time_inc, sampler.avg_time_symp,
                sampler.avg_time_symp, sampler.avg_time_crit,
                sampler.symp_prob, sampler.crit_prob, sampler.death_prob
            ])):
        control_result = control(result[x], result[control_var], mu)
        plt.errorbar(y=i,
                     **confidence_interval(control_result),
                     lw=1,
                     fmt='o',
                     capsize=10,
                     label=control_var)
    plt.yticks(range(-1, len(Region.control_variates)),
               labels=['Without control'] + Region.control_variates)

    plt.savefig(os.path.join(plot_path, '5_CONTROL_DEATH_control.png'),
                dpi=300)
    plt.show()

    pass
Exemple #26
0
from Country import Country

countries = []
# Question 1a, implement a constructor
for line in open('country.txt'):
    countries.append(Country(line))

# Question 1b, implement a printit method
for country in countries:
    country.printit()

    # Question 1c, implement string overloading
    print country

    # Question 1d, implement a getter function for population
    print country,
    print country.population

# Question 1e, overload + and -
print "Before:", countries[20].population
countries[20] += 10
print "After adding 10:", countries[20].population

countries[20] = countries[20] - 3
print "After subtracting 3:", countries[20].population

print
# Check that the __add__ worked
first = countries[0]
Neverland = first + 100
if Neverland.population == first.population:
    if centroids:
        plt.scatter(*zip(*centroids))

    plt.axis('scaled')
    plt.show()


if __name__ == '__main__':
    import sys
    args = sys.argv[1:]
    nCentroids = 128
    nRandomSamples = 4
    if not args:
        print(__file__, '<country> [nCentroids=128] [nRandomSamples=4]')
    else:
        country = args.pop(0)
        if args: nCentroids = int(args.pop(0))
        if args: nRandomSamples = int(args.pop(0))

        from Country import Country
        country = Country(country)
        if country:
            from Centroids import Centroids
            centroids = Centroids(nCentroids, country)

            from GeoTaxi import GeoTaxi
            polies = GeoTaxi(country, centroids)

            MatPlot_GeoTaxi(polies, centroids)
                       func=np.stack)

    results = []
    for _ in tqdm(range(n_repeats),
                  desc='Repeating simulations',
                  unit='simulations'):
        results.append(simulate(country, n_days, False))
    results = collate(results, func=np.stack)

    return results


if __name__ == "__main__":
    ### SINGLE SIMULATION
    copenhagen = Region('Copenhagen', population_size, sampler, I_initial)
    country = Country([copenhagen], hospital_beds)
    result = simulate(country)

    if plot_data:
        # %% Plotting
        Plotter.plot_fatalities(result['R_dead'])
        plt.show()

        if SIR:
            sick_people_on_hospital_fraction = 0.1
            Plotter.plot_hospitalized_people(
                result['I_symp'] * sick_people_on_hospital_fraction,
                hospital_beds)
        else:
            Plotter.plot_hospitalized_people(result['I_crit'], hospital_beds)
        plt.show()
Exemple #29
0
logging.basicConfig(format='%(levelname)s: %(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)

SAMPLES_DIR = './samples'
BY_CITIES_FILE = os.path.join(SAMPLES_DIR, 'by.json')
PL_CITIES_FILE = os.path.join(SAMPLES_DIR, 'pl.json')
LV_CITIES_FILE = os.path.join(SAMPLES_DIR, 'lv.json')
LT_CITIES_FILE = os.path.join(SAMPLES_DIR, 'lt.json')
UA_CITIES_FILE = os.path.join(SAMPLES_DIR, 'ua.json')
NAMES_FILE = os.path.join(SAMPLES_DIR, 'namelist.json')

NATIONALITIES = ['Belarusian', 'Polish', 'Latvian',
                 'Lithuanian', 'Ukrainian']


by_coordinates = Country(BY_CITIES_FILE)
pl_coordinates = Country(PL_CITIES_FILE)
lv_coordinates = Country(LV_CITIES_FILE)
lt_coordinates = Country(LT_CITIES_FILE)
ua_coordinates = Country(UA_CITIES_FILE)

NATIONAL_COORDINATES = {
    NATIONALITIES[0]: by_coordinates,
    NATIONALITIES[1]: pl_coordinates,
    NATIONALITIES[2]: lv_coordinates,
    NATIONALITIES[3]: lt_coordinates,
    NATIONALITIES[4]: ua_coordinates
}

uniq_names = get_uniq_names(NAMES_FILE)
Exemple #30
0
from Countries import Countries
from Cities import Cities
from Relation import Relation
from GRAPHMENU import Graphmenu
import pickle

with open('Relation.pickle', 'rb') as f:
    ER = pickle.load(f)

with open('Cities.pickle', 'rb') as f:
    Cities = pickle.load(f)

with open('Countries.pickle', 'rb') as f:
    Countries = pickle.load(f)

cntr1 = Country("Ukraine")
cntr2 = Country("Mongolia")
cntr3 = Country("Romania")

ct1 = City("Kyiv", 100000000)
ct2 = City("Chernihiv", 1000000000)
ct3 = City("Zhashkiv", 100000000)
ct4 = City("Ulan-Bator", 100)
ct5 = City("Gurguleshti", 1000)
ct6 = City("Bucharest", 10000)

Cntrs = Countries()

Cntrs.add(cntr1)
Cntrs.add(cntr2)
Cntrs.add(cntr3)
Exemple #31
0
def get_data(web_driver):
    try:
        table_class = web_driver.find_elements_by_class_name(
            "el-table__body-wrapper")[0]
    except:
        print("[-]: Cannot find table class.")

    try:
        table_rows = table_class.find_elements_by_class_name("el-table__row")
    except:
        print("[-]: Cannot find table rows.")

    countries_list = []

    for country_index, table_row in enumerate(table_rows):
        country = Country()
        country.rank = country_index
        country.name = table_row.find_elements_by_xpath(
            ".//td[1]/div[1]/a/span")[0].get_attribute(
                "textContent")  # For hidden Data
        country.conv19_new = table_row.find_elements_by_xpath(
            ".//td[2]/div[1]/span")[0].get_attribute("textContent")
        country.conv19_all = table_row.find_elements_by_xpath(
            ".//td[3]/div[1]/span")[0].get_attribute("textContent")
        country.conv19_current = table_row.find_elements_by_xpath(
            ".//td[4]/div[1]/span")[0].get_attribute("textContent")
        country.conv19_cure_new = table_row.find_elements_by_xpath(
            ".//td[5]/div[1]/span")[0].get_attribute("textContent")
        country.conv19_cure = table_row.find_elements_by_xpath(
            ".//td[6]/div[1]/span")[0].get_attribute("textContent")
        country.conv19_cure_rate = table_row.find_elements_by_xpath(
            ".//td[7]/div[1]/span")[0].get_attribute("textContent")
        country.death_new = table_row.find_elements_by_xpath(
            ".//td[8]/div[1]/span")[0].get_attribute("textContent")
        country.death_all = table_row.find_elements_by_xpath(
            ".//td[9]/div[1]/span")[0].get_attribute("textContent")
        country.death_rate = table_row.find_elements_by_xpath(
            ".//td[10]/div[1]/span")[0].get_attribute("textContent")
        country.conv19_rate = table_row.find_elements_by_xpath(
            ".//td[11]/div[1]/span")[0].get_attribute("textContent")
        country.peoples = table_row.find_elements_by_xpath(
            ".//td[12]/div[1]/span")[0].get_attribute("textContent")
        country.peoples_density = table_row.find_elements_by_xpath(
            ".//td[13]/div[1]/span")[0].get_attribute("textContent")
        country.gdp = table_row.find_elements_by_xpath(
            ".//td[14]/div[1]/span")[0].get_attribute("textContent")
        country.gdp_per = table_row.find_elements_by_xpath(
            ".//td[15]/div[1]/span")[0].get_attribute("textContent")
        print(country.rank, country.name)
        countries_list.append(country)

    return countries_list