예제 #1
0
def plotdata():
    try:
        country = data.get()
        country = country.strip()
        country = country.replace(" ", ",").split(",")
        countries = []
        for x in country:
            countries.append(x)
        df = pd.read_csv(
            'https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv',
            parse_dates=['Date'])
        df = df[df['Country'].isin(countries)]
        #Creating a Summary Column
        df['Cases'] = df[['Confirmed', 'Recovered', 'Deaths']].sum(axis=1)
        #Restructuring our Data
        df = df.pivot(index='Date', columns='Country', values='Cases')
        countries = list(df.columns)
        covid = df.reset_index('Date')
        covid.set_index(['Date'], inplace=True)
        covid.columns = countries
        #Calculating Rates per 100,000
        populations = {}
        for i in countries:
            c = CountryInfo(i)
            populations[i] = c.population()
        percap = covid.copy()
        for country in list(percap.columns):
            percap[country] = percap[country] / populations[country] * 100000
        #Generating Colours
        colors = {}
        k = 0
        col = ['#045275', '#089099', '#DC3977', '#7C1D6F', '#7CCBA2']
        for i in countries:
            colors[i] = col[k]
            k += 1
        plt.style.use('fivethirtyeight')
        percapplot = percap.plot(figsize=(12, 8),
                                 color=list(colors.values()),
                                 linewidth=5,
                                 legend=False)
        percapplot.grid(color='#d4d4d4')
        percapplot.set_xlabel('Month', color='brown')
        percapplot.set_ylabel('# of Cases per 100,000 People', color='brown')
        for country in list(colors.keys()):
            percapplot.text(x=percap.index[-1],
                            y=percap[country].max(),
                            color=colors[country],
                            s=country,
                            weight='bold')
        percapplot.text(
            x=percap.index[2],
            y=percap.max().max() + 45,
            s=
            "Covid-19 Comparison Graph Between Countries \nIncludes Current Cases, Recoveries, and Deaths",
            fontsize=18,
            color='brown',
            alpha=.75)
        plt.show()
    except Exception as e:
        print("Country data not present ")
예제 #2
0
def getPopulation(country):
    try:
        country = CountryInfo(country)
        popoulation = country.population()
    except:
        popoulation = 10000000
    return popoulation
예제 #3
0
def population(message):
    message = message.replace('!population ', '')
    message = message.replace('!population', '')
    if message == '':
        return 'Please specify country.'
    else:
        countryinfo = CountryInfo(message)
        message = message.replace(message[0], message[0].upper())
        message = message.replace(message[1:], message[1:].lower())
        return "The population of " + message + " is " + str(
            countryinfo.population() + ".")
예제 #4
0
def get_country_population_and_continent(country: str, ) -> Tuple[int, str]:
    try:
        country_translated = (country if country
                              not in COUNTRIES_TRANSLATE_TO_COUNTRYINFO.keys()
                              else COUNTRIES_TRANSLATE_TO_COUNTRYINFO[country])

        country_translated_info = CountryInfo(country_translated)
        population = country_translated_info.population()
        continent = country_translated_info.region()
    except KeyError:
        population, continent = -1, FILLNA

    return population, continent
예제 #5
0
def country_info(country_name):
    d = []
    country = CountryInfo(country_name)
    d.append(["name", country.name().capitalize()])
    d.append(["capital", country.capital().capitalize()])
    d.append(["region", country.region().capitalize()])
    d.append(["currency", country.currencies()])
    d.append(["area", country.area()])
    d.append(["population", country.population()])
    d.append(["languages", country.languages()])
    d.append(["borders", country.borders()])
    d.append(["calling code", country.calling_codes()])
    d.append(["lat/long", country.capital_latlng()])
    d.append(["code", country.iso(2)])
    return d
예제 #6
0
def main():
    try:
        start_date = date(2020, 3, 1)
        end_date = date(2020, 10, 2)
        delta = timedelta(days=1)
        while start_date <= end_date:  
            day = start_date.strftime("%Y-%m-%d")  
            print ("Downloading " + day)    
            url = "https://api.covid19tracking.narrativa.com/api/" + day
            r = requests.get(url)
            data = r.json()    
            start_date += delta

            for day in data['dates']:
                for country in data['dates'][day]['countries']:
                    try:
                        country_info = CountryInfo(country)
                        country_iso_3 = country_info.iso(3)
                        population = country_info.population()
                    except Exception as e:
                        print("Error with " + country)
                        country_iso_3 = country
                        population = None
                        infection_rate=0
                        print(e)

                    if population != None:
                        try:
                            infection_rate=getInfectionRate(data['dates'][day]['countries'][country]['today_confirmed'], population)
                        except:
                            infection_rate=0

                    result_data = data['dates'][day]['countries'][country]
                    del result_data['regions']
                    result_data['timestamp'] = result_data.pop('date')
                    result_data.update(
                                timestamp=datetime.strptime(day, "%Y-%m-%d"),
                                country_iso_3=country_iso_3,
                                population=population,
                                infection_rate=infection_rate,
                                )

                    save_elasticsearch_es('covid-19-live-global',result_data)
    except Exception as e:
        print(e)
예제 #7
0
def getVariableBetaForecast(df_location,
							location,
							x_days,
							forecast_size,
							mortality_rate = 0.01,
							disease_duration = 14):

	location_key = location.lower().replace(' ','_')
	country = CountryInfo(location)
	population = country.population()

	x_num = df_location[location_key].iloc[0]
	df_location = df_location[location_key]

	num_days = df_location.shape[0]
	full_t = np.linspace(0, num_days, num_days)	
	full_loc = df_location
	r0_list = []

	t, best_D, best_I, best_R, best_r0 = getBestFit(df_location.head(forecast_size), 
													x_num,
													population,
													mortality_rate = mortality_rate,
													disease_duration = disease_duration)
	
	full_D = best_D
	full_I = best_I
	r0_list.append(best_r0)

	remain_days = num_days-forecast_size
	while remain_days > 2*forecast_size:
		df_location = df_location.tail(remain_days+1)
		print_bool = False
		if (remain_days-forecast_size + 1) < 2*forecast_size:
			print ("Best I = ", best_I.iloc[-1])
			print ("Best R = ", best_R.iloc[-1])
			print_bool = True
		t, best_D, best_I, best_R, best_r0 = getBestFit(df_location.head(forecast_size),
													x_num,
													population,
													mortality_rate = mortality_rate,
													disease_duration = disease_duration,
													first_pass=False, 
													I_in=best_I.iloc[-1],
													R_in=best_R.iloc[-1],
													print_bool=print_bool)

		full_D = pd.concat([full_D, best_D.tail(forecast_size-1)], ignore_index=True,axis=0)
		full_I = pd.concat([full_I, best_I.tail(forecast_size-1)], ignore_index=True,axis=0)
		r0_list.append(best_r0)
		if (remain_days-forecast_size + 1) < 2*forecast_size:
			print (df_location.head(forecast_size))
			print (full_D)
			print (full_I)
			
		remain_days = remain_days-forecast_size + 1

	df_location = df_location.tail(remain_days+1)

	t, best_D, best_I, best_R, best_r0 = getBestFit(df_location,
												x_num,
												population,
												mortality_rate = mortality_rate,
												disease_duration = disease_duration,
												first_pass=False,
												I_in=best_I.iloc[-1],
												R_in=best_R.iloc[-1],
												x_days=x_days)

	full_D = pd.concat([full_D, best_D.tail(-1)], ignore_index=True,axis=0)
	full_I = pd.concat([full_I, best_I.tail(-1)], ignore_index=True,axis=0)
	r0_list.append(best_r0)

	return full_D, full_I, r0_list
예제 #8
0
    for x in range(options[category_index]):
        country_choice = CountryInfo(country_pool[x])

        if category == "area":
            print('(' + choices[x] + ') ' + str(country_choice.area()) +
                  " sq kilometers")

        elif category == "subregion":
            print('(' + choices[x] + ') ' + subregion_pool[x])

        elif category == "calling code":
            print('(' + choices[x] + ') ' +
                  str(country_choice.calling_codes()[0]))

        elif category == "population":
            print('(' + choices[x] + ') ' + str(country_choice.population()))

        elif category == "capital":
            print('(' + choices[x] + ') ' + country_choice.capital())

        elif category == "currency":
            print('(' + choices[x] + ') ' + currencies_pool[x])

        elif category == "latitude":
            print('(' + choices[x] + ') ' + str(country_choice.latlng()[0]))

        elif category == "longitude":
            print('(' + choices[x] + ') ' + str(country_choice.latlng()[1]))

    answer_user = input("\nPlease choose an option: ")
    while answer_user not in choices[0:options[category_index]]:
def get_population_by_country(country):
    country = CountryInfo(country)
    return country.population()
예제 #10
0
def getMobilityPlots(locations, data_type, shift_days, smoothing_range,
                     mobility_type, pop_type, location_num):

    timeline = 'Days since X number of deaths/cases'
    x_num = 10
    if len(locations) <= location_num:
        return None
    else:
        mob_loc_df = getGoogleMobilityReportsFromCountry(
            locations[location_num])
        #print (mob_reports_df.head(10))
        #mob_loc_df = mob_reports_df[mob_reports_df['sub_region_1'].isnull()]
        if data_type == 'Deaths':
            df = getNewDeaths()
            df_total = getTotalDeaths()
        elif data_type == 'Cases':
            df = getNewCases()
            df_total = getTotalCases()
        else:
            return None

        data = []

        if not x_num: x_num = 0

        location = locations[location_num]
        location_key = location.lower().replace(' ', '_')

        if pop_type == 'Per Million':
            country = CountryInfo(location)
            population = country.population()
            area = country.area()
            pop_density = float(population) / area
            print(population)
            print(area)
            print(pop_density)
            df[location_key] = 1000000.0 * df[location_key] / population
        else:
            population = 1.0

        if timeline == 'Days since X number of deaths/cases':
            df_total_loc = df_total.fillna(0)
            df_total_loc['date'] = df_total_loc['date'] - datetime.timedelta(
                days=shift_days)
            df_total_loc = df_total_loc.drop(
                df_total_loc[(df_total_loc[location_key] < x_num)].index)
            df_total_loc = df_total_loc.reset_index()
            df_total_loc = df_total_loc.drop([location_key], axis=1)

            df[location_key] = df[location_key].fillna(0).rolling(
                smoothing_range).mean()
            df_loc = df[['date', location_key]].copy()
            df_loc['date'] = df_loc['date'] - datetime.timedelta(
                days=shift_days)

            df_loc = pd.merge(df_total_loc, df_loc, how='left', on='date')

            #mob_loc_df = mob_reports_df[mob_reports_df['country_region']==location]
            print(mob_loc_df.info())
            #print (mob_loc_df['sub_region_1'])
            #mob_loc_df = mob_loc_df[mob_loc_df['sub_region_1'].isnull()]
            mob_loc_df['date'] = pd.to_datetime(mob_loc_df.date)
            mob_loc_df.sort_values(by=['date'])
            mob_loc_df[mobility_type] = mob_loc_df[mobility_type].fillna(
                0).rolling(smoothing_range).mean()

            country = pycountry.countries.get(name=location).alpha_3
            stringency_df = getStringencyDataFrame(country)
            stringency_df['date'] = pd.to_datetime(stringency_df.date)
            stringency_df.sort_values(by=['date'])

            df_loc = pd.merge(df_loc, mob_loc_df, how='left', on='date')
            df_loc = pd.merge(df_loc, stringency_df, how='left', on='date')

            if mobility_type != 'residential_percent_change_from_baseline':
                df_loc[mobility_type] = -df_loc[mobility_type]
                mobility_name = '% Time less at ' + mobility_dict[mobility_type]
            else:
                mobility_name = '% Time more at ' + mobility_dict[mobility_type]

            #print (df_loc[mobility_type])

            data.append(
                go.Bar(
                    x=df_loc.index,
                    y=df_loc[location_key],
                    marker=dict(color=colour_palette[location_num], ),
                    opacity=0.7,
                    text=location,
                    #name=location + ' ' + data_type,
                    yaxis='y2',
                    showlegend=False))
            data.append(
                go.Scatter(x=df_loc.index,
                           y=df_loc['stringency'],
                           mode='lines',
                           marker=dict(color='rgb(0,0,0)', ),
                           line=dict(color='rgb(0,0,0)', dash='dot'),
                           opacity=1.0,
                           text=location,
                           name='Stringency Index',
                           yaxis='y1',
                           showlegend=True))
            data.append(
                go.Scatter(x=df_loc.index,
                           y=df_loc[mobility_type],
                           mode='lines',
                           marker=dict(color='rgb(0,0,0)', ),
                           line=dict(color='rgb(0,0,0)', dash='solid'),
                           opacity=1.0,
                           text=location,
                           name=mobility_name,
                           yaxis='y1',
                           showlegend=True))

        else:
            return None

        if mobility_type == 'residential_percent_change_from_baseline':
            y_range = [0, 100]
        else:
            y_range = [0, 100]

        if pop_type == "Per Million":
            title_sub = ' (per million)'
        else:
            title_sub = ''

        figure = {
            'data':
            data,
            'layout':
            go.Layout(
                title={
                    'text': location,
                    'y': 1.0,
                    'x': 0.5,
                    'xanchor': 'center',
                    'yanchor': 'top'
                },
                showlegend=True,  #show_legend,
                legend=dict(
                    orientation="h",
                    x=0,
                    y=1.1,
                    font=dict(family="Arial", size=14, color="#000000"),
                ),
                font=dict(family='Arial', size=12, color='#000000'),
                hovermode='closest',
                margin=dict(t=50),
                xaxis=dict(tickfont=dict(family='Arial',
                                         size=14,
                                         color='#000000'), ),
                yaxis2=dict(
                    #range=[0,1200],
                    rangemode="tozero",
                    tickfont=dict(family='Arial', size=14, color='#000000'),
                    side='left',
                    title=data_type + title_sub,
                    showgrid=False),
                yaxis=dict(

                    #autorange='reversed',
                    range=y_range,
                    rangemode='tozero',
                    anchor='x',
                    overlaying='y',
                    tickfont=dict(family='Arial', size=14, color='#000000'),
                    side='right',
                    title='Mobility/Stringency',
                    showgrid=False),
                height=400,
                autosize=True,
                paper_bgcolor='rgba(0,0,0,0)',
                plot_bgcolor='rgba(0,0,0,0)')
        }

        return dcc.Graph(figure=figure,
                         config={'displayModeBar': False},
                         id='reg-str-graph')
예제 #11
0
 def add_population(country, name=country):
     country_info = CountryInfo(name)
     countries[country][key_population] = country_info.population()
# coding=utf-8
from countryinfo import CountryInfo

country = CountryInfo('Austria')
print (country.population())

print (country.area())
예제 #13
0
def updateTotalDeathsTimeline(locations, timeline, data_type, x_num,
                              smoothing_range, x_days, pop_type):

    if locations:
        if data_type == 'Deaths':
            df = getTotalDeaths()
        elif data_type == 'Cases':
            df = getTotalCases()
        else:
            return None
        df['sum_data'] = df.apply(lambda x: sumLocations(x, locations), axis=1)
        df = df.drop(df[(df['sum_data'] == 0)].index)
        data = []
        count = 0
        for location in locations:
            location_key = location.lower().replace(' ', '_')
            if pop_type == '% of Population':
                country = CountryInfo(location)
                population = country.population()
                area = country.area()
                pop_density = float(population) / area
                print(population)
                print(area)
                print(pop_density)
                df[location_key] = 100.0 * df[location_key] / population
            else:
                population = 1.0

            if not x_num: x_num = 0

            if timeline == 'Days since X number of deaths/cases':
                df_location = df.fillna(0)
                df_location = df_location.drop(df_location[(
                    df_location[location_key] < x_num / population)].index)
                df_location = df_location.reset_index()
                data.append(
                    go.Scatter(x=df_location.index,
                               y=df_location[location_key],
                               mode='lines',
                               marker=dict(color=colour_palette[count], ),
                               opacity=1.0,
                               text=location,
                               name=location))

                prediction_df = df_location[['date', location_key]]
                prediction_df[
                    'rolling_mean'] = 1.0 + df_location[location_key].fillna(
                        0).pct_change().rolling(smoothing_range).mean()
                prediction_df = prediction_df.iloc[[-1]]
                r_index = prediction_df.index.values[0]

                r_mean = prediction_df['rolling_mean'].values[0]
                r_num = prediction_df[location_key].values[0]
                for x in range(1, x_days):
                    extra_df = pd.DataFrame(
                        [[float(r_num) * r_mean**x, r_mean]],
                        columns=[location_key, "rolling_mean"])
                    prediction_df = pd.concat([prediction_df, extra_df],
                                              ignore_index=True,
                                              axis=0)

                prediction_df.index = pd.RangeIndex(start=r_index,
                                                    stop=r_index + x_days,
                                                    step=1)

                data.append(
                    go.Scatter(x=prediction_df.index,
                               y=prediction_df[location_key],
                               mode='lines',
                               marker=dict(color=colour_palette[count], ),
                               line=dict(color=colour_palette[count],
                                         dash='dot'),
                               opacity=1.0,
                               text=location,
                               name=location,
                               showlegend=False))
            else:

                data.append(
                    go.Scatter(x=df['date'],
                               y=df[location_key].fillna(0),
                               mode='lines',
                               marker=dict(color=colour_palette[count], ),
                               opacity=1.0,
                               text=location,
                               name=location))
                prediction_df = df[['date', location_key]]
                prediction_df['rolling_mean'] = 1.0 + df[location_key].fillna(
                    0).pct_change().rolling(smoothing_range).mean()
                prediction_df = prediction_df.iloc[[-1]]
                r_date = prediction_df['date'].values[0]
                r_mean = prediction_df['rolling_mean'].values[0]
                r_num = prediction_df[location_key].values[0]

                for x in range(1, x_days):
                    r_dt = convert_to_datetime(
                        r_date
                    )  #datetime.datetime.strptime(r_date, '%Y-%m-%d')
                    extra_df = pd.DataFrame(
                        [[
                            r_dt + datetime.timedelta(days=x),
                            float(r_num) * r_mean**x, r_mean
                        ]],
                        columns=["date", location_key, "rolling_mean"])
                    prediction_df = pd.concat([prediction_df, extra_df],
                                              ignore_index=True,
                                              axis=0)

                data.append(
                    go.Scatter(x=prediction_df['date'],
                               y=prediction_df[location_key],
                               mode='lines',
                               marker=dict(color=colour_palette[count], ),
                               line=dict(color=colour_palette[count],
                                         dash='dot'),
                               opacity=1.0,
                               text=location,
                               name=location,
                               showlegend=False))

            count += 1
        if pop_type == "% of Population":
            title_sub = ' (% of population)'
        else:
            title_sub = ''
        figure = {
            'data':
            data,
            'layout':
            go.Layout(
                title='Cumulative ' + data_type + title_sub,
                legend=dict(orientation="h", x=0, y=1.1),
                font=dict(family='Arial', size=15, color='#000000'),
                hovermode='closest',
                margin=dict(t=50),
                xaxis=dict(tickfont=dict(family='Arial',
                                         size=14,
                                         color='#000000'), ),
                yaxis=dict(
                    #range=y_axis_range,
                    tickfont=dict(family='Arial', size=14, color='#000000'), ),
                height=400,
                autosize=True,
                paper_bgcolor='rgba(0,0,0,0)',
                plot_bgcolor='rgba(0,0,0,0)')
        }

        return dcc.Graph(figure=figure,
                         config={'displayModeBar': False},
                         id='total-deaths-t-graph')
예제 #14
0
print('\nBorders:')
for border in country_borders:
    print(border, end=', ')

calling_codes = country.calling_codes()
print('\n\nCall Code:')
for call_code in calling_codes:
    print(call_code)

country_region = country.region()
print(f'\nRegion:\n{country_region}')

sub_region = country.subregion()
print(f'\nSub-Region:\n{sub_region}')

country_population = country.population()
print(f'\nPopulation:\n{country_population}')

country_states = country.provinces()
print('\nStates/Provinces:')
for states in country_states:
    print(states, end=', ')

about_country = country.wiki()

country_map = country.capital_latlng()
map = folium.Map(location=(country_map))
print(
    f'\n\nCheck your directory for the map of  {user}, named: (mylocation.html)'
)
map.save("mylocation.html")
예제 #15
0
def getVariableBetaForecast(df_location,
							location,
							x_days,
							forecast_size,
							r0_shift,
							mortality_rate = 0.01,
							disease_duration = 14):

	location_key = location.lower().replace(' ','_')
	country = CountryInfo(location)
	population = country.population()

	x_num = df_location[location_key].iloc[0]
	df_location = df_location[location_key]

	num_days = df_location.shape[0]
	full_t = np.linspace(0, num_days, num_days)	
	full_loc = df_location
	r0_list = []

	t, best_D, best_I, best_R, best_S, best_r0 = getBestFit(df_location.head((forecast_size+1)), 
													x_num,
													population,
													mortality_rate = mortality_rate,
													disease_duration = disease_duration)
	
	full_D = best_D
	full_I = best_I
	r0_list.append(best_r0)

	print ("Num days = ", num_days)
	remain_days = num_days-(forecast_size+1)
	print ("0: remain_days = ", remain_days)
	debug_count = 1
	while remain_days > 2*(forecast_size):
		df_location = df_location.tail(remain_days+1)
		print (debug_count, ": df_location.shape = ", df_location.shape[0])
		print_bool = False
		'''if (remain_days-forecast_size + 1) < 2*forecast_size:
			print ("Best I = ", best_I.iloc[-1])
			print ("Best R = ", best_R.iloc[-1])
			print_bool = True'''
		t, best_D, best_I, best_R, best_S, best_r0 = getBestFit(df_location.head((forecast_size+1)),
													x_num,
													population,
													mortality_rate = mortality_rate,
													disease_duration = disease_duration,
													first_pass=False, 
													I_in=best_I.iloc[-1],
													R_in=best_R.iloc[-1],
													print_bool=print_bool)

		full_D = pd.concat([full_D, best_D.tail(forecast_size)], ignore_index=True,axis=0)
		full_I = pd.concat([full_I, best_I.tail(forecast_size)], ignore_index=True,axis=0)
		r0_list.append(best_r0)
		'''if (remain_days-forecast_size + 1) < 2*forecast_size:
			print (df_location.head(forecast_size))
			print (full_D)
			print (full_I)'''
			
		remain_days = remain_days-forecast_size
		print (debug_count,': remain_days = ',remain_days)

	df_location = df_location.tail(remain_days+1)
	print ("df_location.shape (last)= ", df_location.shape[0])
	t, best_D, best_I, best_R, best_S, best_r0 = getBestFit(df_location,
												x_num,
												population,
												mortality_rate = mortality_rate,
												disease_duration = disease_duration,
												first_pass=False,
												I_in=best_I.iloc[-1],
												R_in=best_R.iloc[-1],
												x_days=x_days,
												r0_shift=r0_shift)

	full_D = pd.concat([full_D, best_D.tail(-1)], ignore_index=True,axis=0)
	full_I = pd.concat([full_I, best_I.tail(-1)], ignore_index=True,axis=0)
	r0_list.append(best_r0)

	total_susceptible = int(best_S.iloc[-1])
	total_infected = population - total_susceptible
	print (total_infected, '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.' )
	

	return full_D, full_I, r0_list, total_infected, total_susceptible