# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernel_info:
#     name: python3
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# %matplotlib inline
from matplotlib import style
style.use('fivethirtyeight')
import matplotlib.pyplot as plt

import numpy as np
import pandas as pd
import datetime as dt

# import flask library
from flask import Flask, jsonify

# # Reflect Tables into SQLAlchemy ORM

# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

# create engine to hawaii.sqlite - thru Resources folder
engine = create_engine("sqlite:///Resources/hawaii.sqlite")

# reflect an existing database into a new model
base = automap_base()
# reflect the tables
base.prepare(engine, reflect = True)

# View all of the classes that automap found
base.classes.keys()

# Save references to each table - class names measurement and station
measure = base.classes.measurement
station = base.classes.station

# Create our session (link) from Python to the DB
session = Session(engine)

# Add flask setup
app = Flask(__name__)

## Get and test the class structure / table schema for measure
qury_measure = session.query(measure)
qury_measure.__dict__

## Get and test the class structure / table schema for station
qury_measure = session.query(station)
qury_measure.__dict__


# Setup all flask routes
@app.route("/")
def home():
    print("Server received request for 'Home' page...")
    return ("Welcome to my 'Home' page!"
        f"Available Routes:<br/>"
        f"/api/v1.0/precipitation<br/>"
        f"/api/v1.0/stations<br/>"
        f"/api/v1.0/tobs<br/>"
        f"/api/v1.0/<start><br/>"
        f"/api/v1.0/<start>/<end>")


# Precipitation Route, return JSON
@app.route("/api/v1.0/precipitation")
def precipitation():
    print("Server received request for 'Precipitation' page...")
    return "Welcome to my 'Precipitation' page!"


# # Exploratory Precipitation Analysis

# Find the most recent date in the data set.
starter_date = session.query(measure.date).order_by(measure.date.asc()).first()
print(starter_date)

# +
# Design a query to retrieve the last 12 months of precipitation data and plot the results. 
# Starting from the most recent data point in the database. 
# Starting from the most recent point means starting from the latest date, so same formula as above, but now desc instead of asc
end_date = session.query(measure.date).order_by(measure.date.desc()).first()
print(end_date)
# Not sure why end_date is returned as list, but converting to single date with datetime below

# Calculate the date one year from the last date in data set.
# Use datetime library imported
one_year = dt.timedelta(days = 365)
# print(one_year)
end_year = dt.date(2017,8,23)
end_date_minus_one = end_year - one_year
print(end_date_minus_one)
print(end_year)

# Perform a query to retrieve the data and precipitation scores
scores = session.query(measure.date, measure.prcp).\
    filter(measure.date >= end_date_minus_one).\
    filter(measure.date < end_year).\
    order_by(measure.date).all()
print(scores)

# Save the query results as a Pandas DataFrame and set the index to the date column
scores_df = pd.DataFrame(scores, columns = ["Date", "Precipitation"])
# print(scores_df)
scores_df_indexed = scores_df.set_index("Date")

# Sort the dataframe by date
scores_df_indexed.head()

# Use Pandas Plotting with Matplotlib to plot the data
scores_df.plot()
plt.xlabel("Date")
plt.ylabel("Inches")
plt.savefig("Images/precipitation-from-code.png")
plt.show()
# -

return jsonify(scores)

# Use Pandas to calcualte the summary statistics for the precipitation data
# Just use simple describe method
scores_df.describe()


# # Exploratory Station Analysis

# Assign station route
@app.route("/api/v1.0/stations")
def station():


# + active=""
# # Design a query to return all stations in the dataset
# session.query(station.station, station.name).all()
# -

return jsonify(station)

# Design a query to find the most active stations (i.e. what stations have the most rows?)
# List the stations and the counts in descending order.
session.query(measure.station, func.count(measure.station)).\
    group_by(measure.station).\
    order_by(func.count(measure.station)).all()
# Most active stations are at bottom of list

# Using the most active station id from the previous query, calculate the lowest, highest, and average temperature.
top_station = "USC00519281"
# Use func.min, func.max, and func.avg functions
# Min
top_station_min = session.query(func.min(measure.tobs)).\
    filter(measure.station == top_station).all()
top_station_min

# Max
top_station_max = session.query(func.max(measure.tobs)).\
    filter(measure.station == top_station).all()
top_station_max

# Avg
top_station_avg = session.query(func.avg(measure.tobs)).\
    filter(measure.station == top_station).all()
top_station_avg

# Using the most active station id
# Query the last 12 months of temperature observation data for this station and plot the results as a histogram
temp_data_filtered = session.query(measure.tobs).\
    filter(measure.date >= end_date_minus_one).\
    filter(measure.date < end_year).\
    filter(measure.station == top_station).\
    order_by(measure.date).all()
temp_df = pd.DataFrame(temp_data_filtered, columns = ["Temperature"])
temp_df.plot.hist()
plt.savefig("Images/station_histogram_from_code")
plt.show()

# # Close session

# Close Session
session.close()



StarcoderdataJupyterScriptsDedupFiltered