{"cells":[{"metadata":{},"cell_type":"markdown","source":"## This Kernel is inspired by EDA kernel from Allunia [here](https://www.kaggle.com/allunia/ds4g-eda)"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n#import os\n\nfrom sklearn.linear_model import LinearRegression\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from matplotlib.image import imread\nimport matplotlib.pyplot as plt\nfrom skimage.io import imread\nimport seaborn as sns\nsns.set()\nimport os","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_data_dir = '/kaggle/input/ds4g-environmental-insights-explorer/eie_data/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(my_data_dir)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We can see several subfolders. By looking into the data description, we can find several sources:\n\n-Global power plant database (gppd)\n\n-Sentinal 5P OFFL NO2 (s5p_no2)\n\n-Global Forecast System 384-Hour Predicted Atmosphere Data (gfs)\n\n-Global Land Data Assimilation System (gldas)"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"### Lets see the GFS Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"gfs = my_data_dir+'gfs/'\nsample = os.listdir(gfs)[0:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The names look like some recent dates but theres a two digit code at the end which I cannot comprehend"},{"metadata":{"trusted":true},"cell_type":"code","source":"for n in range(5):\n    image = imread(gfs + sample[n])\n    print(image.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"6 channels :o"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1,6,figsize=(20,3))\n\nfor n in range(6):\n    ax[n].imshow(image[:,:,n], cmap=\"coolwarm\")\n    ax[n].grid(False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### I cant derive any insights from it"},{"metadata":{},"cell_type":"markdown","source":"Lets see the s5p data"},{"metadata":{"trusted":true},"cell_type":"code","source":"s5p = \"../input/ds4g-environmental-insights-explorer/eie_data/s5p_no2/\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = os.listdir(s5p)[0:5]\nsample","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for n in range(5):\n    image = imread(s5p + sample[n])\n    print(image.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1,6,figsize=(20,3))\n\nfor n in range(6):\n    ax[n].imshow(image[:,:,n], cmap=\"Blues\")\n    ax[n].grid(False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1,6,figsize=(20,3))\n\nfor n in range(6):\n    ax[n].imshow(image[:,:,n], cmap=\"coolwarm\")\n    ax[n].grid(False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### something's going on here but I still cant comprehend"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1,6,figsize=(20,3))\n\nfor n in range(6):\n    ax[n].imshow(image[:,:,n], cmap=\"Greens\")\n    ax[n].grid(False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1,6,figsize=(20,3))\n\nfor n in range(6):\n    ax[n].imshow(image[:,:,n], cmap=\"Reds\")\n    ax[n].grid(False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Okay, I cant deduct much here. Lets see the csv file"},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv('../input/ds4g-environmental-insights-explorer/eie_data/gppd/gppd_120_pr.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.isna().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(2,2,figsize=(20,12))\nsns.distplot(data.capacity_mw, kde=True, ax=ax[0,0], color=\"g\")\nax[0,0].set_ylabel(\"counts\")\nsns.distplot(data.estimated_generation_gwh.apply(np.log), kde=True, ax=ax[0,1], color=\"k\")\nax[0,1].set_xlabel(\"Log estimated generation gwh\")\nax[0,1].set_ylabel(\"counts\");\nsns.countplot(data.primary_fuel, ax=ax[1,0], palette=\"coolwarm\");\nsns.countplot(data.source, ax=ax[1,1], palette=\"Blues\");\nlabels = ax[1,1].get_xticklabels()\nax[1,1].set_xticklabels(labels, rotation=90);","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Lets see if we can go beyond from here."},{"metadata":{"trusted":true},"cell_type":"code","source":"data.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['total_generation'] = data['generation_gwh_2013'] + data['generation_gwh_2014'] + data['generation_gwh_2015'] + data['generation_gwh_2016'] + data['generation_gwh_2017'] ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = data.drop(['generation_gwh_2013','generation_gwh_2014','generation_gwh_2015','generation_gwh_2016','generation_gwh_2017'],axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ax = sns.scatterplot(x=\"capacity_mw\", y=\"estimated_generation_gwh\", data=data, color = 'm')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Looks like there a strong relation here between capacity and estimated generation"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nax = sns.barplot(x=\"primary_fuel\", y=\"estimated_generation_gwh\", data=data, color = 'k')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ax = sns.barplot(x=\"estimated_generation_gwh\", y=\"source\", data=data, color = 'g')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ax = sns.scatterplot(x=\"commissioning_year\", y=\"estimated_generation_gwh\", data=data, color = 'r')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fuel_mean = data.groupby('primary_fuel').mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fuel_mean","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = fuel_mean['capacity_mw']\ny = fuel_mean['estimated_generation_gwh']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X.values.reshape(-1,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"reg = LinearRegression()\nreg = reg.fit(X, y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = reg.predict(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.scatter(X, y, color = 'k')\nplt.plot(X, predictions, color = 'm')\nplt.title('capacity vs estimated gwh')\nplt.xlabel('capacity')\nplt.ylabel('estimated gwh')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Lets evaluate our model"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import r2_score, mean_squared_error","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"r2_score(y,predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mean_squared_error(y,predictions)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Lets see if can find a way to calculate coefficients"},{"metadata":{"trusted":true},"cell_type":"code","source":"fuel_mean = fuel_mean.sort_values('capacity_mw')\nfuel_mean['weights'] = list(fuel_mean['estimated_generation_gwh'] / fuel_mean['capacity_mw'])\nfuel_mean['weights'] = fuel_mean['weights'] / fuel_mean['weights'].sum() * 1000\nfuel_mean['the_adjusted_ratio'] = fuel_mean['weights'] * fuel_mean['capacity_mw']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fuel_mean","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = fuel_mean['the_adjusted_ratio']\ny = fuel_mean['estimated_generation_gwh']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"reg = LinearRegression()\nreg = reg.fit(X.values.reshape(-1,1),y)\npredictions = reg.predict(X.values.reshape(-1,1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"r2_score(y,predictions), mean_squared_error(y,predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"coefficients = dict(zip(fuel_mean.index, fuel_mean['the_adjusted_ratio']))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"coefficients","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Follow the link [here](http://open_jicareport.jica.go.jp/pdf/12339586_07.pdf)\n\nResearch by Record of JCC and TWG Workshop"},{"metadata":{},"cell_type":"markdown","source":"## exp_gwh = coefficient * capacity"},{"metadata":{"trusted":true},"cell_type":"code","source":"for index,row in data.iterrows():\n    for name in data.primary_fuel.unique():\n        if row['primary_fuel'] == name:\n            data.loc[index,'predicted_gwh'] = (coefficients[name] * row['capacity_mw'])\n            \nmean_squared_error(data['estimated_generation_gwh'], data['predicted_gwh'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ax = sns.scatterplot(x=\"estimated_generation_gwh\", y=\"predicted_gwh\", data=data, color= 'k')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Lets calculate the mean of primary fuel"},{"metadata":{"trusted":true},"cell_type":"code","source":"fuel_mean = data.groupby('primary_fuel').mean()\nfuel_mean['new_ratios'] = fuel_mean['predicted_gwh'] / fuel_mean['estimated_generation_gwh']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for name in fuel_mean.index:\n    coefficients[name] =  coefficients[name] / fuel_mean.loc[name,'new_ratios']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for index,row in data.iterrows():\n    for name in data.primary_fuel.unique():\n        if row['primary_fuel'] == name:\n            data.loc[index,'predicted_gwh'] = (coefficients[name] * row['capacity_mw'])\n            \n\nmean_squared_error(data['estimated_generation_gwh'], data['predicted_gwh'])","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}