{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sqlalchemy import create_engine\n",
    "import geopandas as gpd\n",
    "\n",
    "import os\n",
    "\n",
    "# Database connection details from zshrc environment variables\n",
    "db_name = 'colorado_spills'\n",
    "user = os.getenv('DB_USER')\n",
    "password = os.getenv('DB_PASSWORD')\n",
    "host = os.getenv('DB_HOST')\n",
    "port = os.getenv('DB_PORT')\n",
    "\n",
    "\n",
    "# Create an engine to connect to the PostgreSQL database\n",
    "engine = create_engine(f'postgresql+psycopg2://{user}:{password}@{host}:{port}/{db_name}')\n",
    "\n",
    "# Read in the spills_with_demographics as spills\n",
    "spills = pd.read_sql_table('spills_with_demographics', engine)\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# use longitude and latitude to create a GeoDataFrame from spills data\n",
    "spills['geometry'] = gpd.points_from_xy(spills['Longitude'], spills['Latitude'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a GeoDataFrame from spills\n",
    "spills_gdf = gpd.GeoDataFrame(spills, crs='EPSG:4326') \n",
    "\n",
    "# Write the GeoDataFrame to a new table in the database\n",
    "spills_gdf.to_postgis('spills_with_demographics_geog', engine, if_exists='replace')\n",
    "\n",
    "# Close the database connection\n",
    "engine.dispose()\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Spill Description</th>\n",
       "      <th>Sentiment</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Crews working on 6/11/14 in area of former pro...</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Historical release discovered during removal o...</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Historical release discovered during removal o...</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>The night operator noticed a high level alarm ...</td>\n",
       "      <td>-0.046667</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>On May 24, 2014, in anticipation of potential ...</td>\n",
       "      <td>0.151786</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                   Spill Description  Sentiment\n",
       "0  Crews working on 6/11/14 in area of former pro...   0.000000\n",
       "1  Historical release discovered during removal o...   0.000000\n",
       "2  Historical release discovered during removal o...   0.000000\n",
       "3  The night operator noticed a high level alarm ...  -0.046667\n",
       "4  On May 24, 2014, in anticipation of potential ...   0.151786"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from textblob import TextBlob\n",
    "\n",
    "# Function to get sentiment polarity\n",
    "def get_sentiment(text):\n",
    "    blob = TextBlob(text)\n",
    "    # Polarity ranges from -1 (negative) to +1 (positive)\n",
    "    return blob.sentiment.polarity\n",
    "\n",
    "# Apply sentiment analysis to each Spill Description\n",
    "spills_gdf['Sentiment'] = spills_gdf['Spill Description'].apply(get_sentiment)\n",
    "\n",
    "# Display the first few sentiment scores\n",
    "spills_gdf[['Spill Description', 'Sentiment']].head()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 119288 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Correlation between sentiment and poverty levels: -0.026246587095843262\n"
     ]
    }
   ],
   "source": [
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Example: Correlate sentiment with poverty levels\n",
    "sns.scatterplot(x=spills_gdf['percent_poverty'], y=spills_gdf['Sentiment'])\n",
    "plt.xlabel('Percent Poverty')\n",
    "plt.ylabel('Sentiment Polarity')\n",
    "plt.title('Correlation between Sentiment and Poverty Levels')\n",
    "plt.show()\n",
    "\n",
    "# Calculate correlation coefficient\n",
    "correlation = spills_gdf['percent_poverty'].corr(spills_gdf['Sentiment'])\n",
    "print(f\"Correlation between sentiment and poverty levels: {correlation}\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "funkyfunk",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
