#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
from matplotlib.pylab import rcParams
rcParams['figure.figsize']=20,10
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn import linear_model
import numpy as np
import math


df_em = pd.read_csv('world_co2_em_sector_df.csv')
df_ppm = pd.read_csv('world_co2_ppm_df.csv')


# ### DataFrame [ World Annual CO2 emissions] 

# In[2]:


df_em.head()


# ### DataFrame [ Atmosphere CO2 concentrations (ppm) ]

# In[3]:


df_ppm.head()


# ### Let's merge our data 

# In[4]:


from functools import reduce
dfs = [df_em, df_ppm]
df_merged = reduce(lambda  left,right: pd.merge(left,right,on=['Year'], # merging the ppm datafram with the all the emissions 
                                            how='outer'), dfs)
# Some data cleaning
df_merged.pop('Unnamed: 0_x') 
df_merged.pop('Unnamed: 0_y')
df_merged = df_merged.dropna() 
df_merged.head()


# ### Let's see a correlation between all the variables using Seaborn

# In[5]:


heatmap = sns.heatmap(df_merged.corr(),vmin=-1, vmax=1, annot=True, cmap='YlOrBr')
heatmap.set_title('Correlation Heatmap', fontdict={'fontsize':20}, pad=20)
heatmap


# ## The Analysis
# ##### Electricity generation and Transportation emit the most CO2 in our atmosphere
# ##### The world produce about 90 million vehicles each year.
# ##### The best case scenerio is to have all future vehicle productions to become electric. 
# ##### If each EV (100kWh base) is charged twice a month. This will lead to an average of 216,000,000,000 kWh/year and 100,243,914 Metric tons of CO2/year
# ##### This will decrease the CO2 emissions due to the decline of fossil fuel powered vehicles

# ### Electricity/Heat & Transport Emissions Plots.

# In[6]:


df_merged.plot(x="Year", y=["Transport (GHG Emissions, CAIT)", "Electricity & Heat (GHG Emissions, CAIT)"], linewidth = 2)
plt.ylim([0, 1.6e10])


# ### Machine Learning prediction
# ##### We will be using a regression machine learning model to determine how our CO2 (ppm) will change over time (Current -2075).

# In[7]:


X = df_merged[['Transport (GHG Emissions, CAIT)', 'Electricity & Heat (GHG Emissions, CAIT)']]
y = df_merged['CO2 concentrations (NOAA, 2018)']


# In[8]:


regr = linear_model.LinearRegression()
regr.fit(X, y)


# ### Creating the new predicted dataframe if we act

# In[26]:


def diff(df_column): # creating a function that can calculate the increase or decrease difference of a column, then put the values into a list.
    df = df_column.diff().tolist()
    df = [x for x in df if math.isnan(x) == False]
    df = df * 3 
    return df

tr_diff = diff(df_merged['Transport (GHG Emissions, CAIT)'])
el_diff = diff(df_merged['Electricity & Heat (GHG Emissions, CAIT)'])

# adding those values from above to each year in the future for transportation and electricity where we make a 'change.' 
# That is if we have all future car production to be electric (starting 2018)
tr_change_list = [7.866e+09]
n = 7.866e+09
while n > 0:
    for i in tr_diff:
        n -= i
        tr_change_list.append(n)
    break
el_change_list = [1.50053e+10] 
m = (1.50053e+10 + 100243914)
while m > 0:
    for i in el_diff:
        m += i
        el_change_list.append(m)
    break 
    
    
def prediction(tr_list,el_list): # prediction function
    years = list(range(2018,2076))
    prediction = {y:regr.predict([[t, e ]]) for y,t,e in zip(years,tr_list, el_list)} # predicting CO2 ppm using regr.predict
    prediction = pd.DataFrame.from_dict(prediction) # Dictionary to dataframe
    prediction = prediction.transpose() # Data cleaning..
    prediction.columns = ['Predicted PPM']
    prediction = prediction.reset_index()
    prediction.rename(columns={'index' : 'Year'}, inplace = True)
    return prediction

predicted_change = prediction(tr_change_list, el_change_list)


def no_change(dif_list,value): # Creating a function of a 'no change' list
    no_change_list = [value]
    n = value
    while n > 0: 
        for i in dif_list:
            n += i 
            no_change_list.append(n)
        break
    return no_change_list
tr_no_change_list = no_change(tr_diff,7.866e+09)
el_no_change_list = no_change(el_diff,1.50053e+10)


predicted_no_change = prediction(tr_no_change_list, el_no_change_list)

dfs = [predicted_no_change, predicted_change,df_ppm ]
df_predictions = reduce(lambda  left,right: pd.merge(left,right,on=['Year'], # Merging Dataframes together.
                                            how='outer'), dfs)
# Data cleaning and minor changes.
df_predictions.rename(columns={"Predicted PPM_x": "PPM prediction with no change", "Predicted PPM_y": "PPM prediction with change"}, inplace = True)
df_predictions.pop('Unnamed: 0')
df_predictions["PPM prediction with no change"] = df_predictions["PPM prediction with no change"] +8 # Fixing gap error
df_predictions["PPM prediction with change"] = df_predictions["PPM prediction with change"] + 2  # Fixing gap error
df_predictions


# ### Predicted PPM by 2050

# In[31]:


df_predictions.plot(x="Year", y=["PPM prediction with no change","PPM prediction with change","CO2 concentrations (NOAA, 2018)"], linewidth = 2)
plt.ylim([0, 800])
print(df_predictions[df_predictions.Year == 1990])
print(df_predictions[df_predictions.Year == 2022])
print(df_predictions[df_predictions.Year == 2050])
print(df_predictions[df_predictions.Year == 2075])
df_predictions.to_csv('df_predictions.csv')


# In[ ]:




