File size: 4,379 Bytes
b9bd536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab8fc6e
b9bd536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9965d6
b9bd536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import datetime
import glob
import os
import branca.colormap as cm
import folium
import numpy as np
import pandas as pd
import plotly.express as px
import streamlit as st
from geopy.extra.rate_limiter import RateLimiter
from geopy.geocoders import Nominatim
from matplotlib import colors as colors
import rioxarray
import xarray as xr
import cdsapi
import os



def geocode(address):
    try:
        address2 = address.replace(' ', '+').replace(',', '%2C')
        df = pd.read_json(
            f'https://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address={address2}&benchmark=2020&format=json')
        results = df.iloc[:1, 0][0][0]['coordinates']
        lat, lon = results['y'], results['x']
    except:
        geolocator = Nominatim(user_agent="GTA Lookup")
        geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)
        location = geolocator.geocode(address)
        lat, lon = location.latitude, location.longitude
    return lat, lon




def get_weather_data(lat, lon, start_date, end_date):

    url = f'https://archive-api.open-meteo.com/v1/archive?latitude={lat}&longitude={lon}&start_date={start_date}&end_date={end_date}&hourly=temperature_2m,precipitation,windspeed_10m,windgusts_10m&models=best_match&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch'
    df = pd.read_json(url).reset_index()
    data = pd.DataFrame({c['index']: c['hourly'] for r, c in df.iterrows()})
    data['time'] = pd.to_datetime(data['time'])
    data['date'] = pd.to_datetime(data['time'].dt.date)
    data = data.query("temperature_2m==temperature_2m")

    data_agg = data.groupby(['date']).agg({'temperature_2m': ['min', 'mean', 'max'],
                                           'precipitation': ['sum'],
                                           'windspeed_10m': ['min', 'mean', 'max'],
                                           'windgusts_10m': ['min', 'mean', 'max']
                                           })
    data_agg.columns = data_agg.columns.to_series().str.join('_')
    data_agg = data_agg.query("temperature_2m_min==temperature_2m_min")
    return data.drop(columns=['date']), data_agg


@st.cache
def convert_df(df):
    return df.to_csv(index=0).encode('utf-8')


st.set_page_config(layout="wide")
col1, col2 = st.columns((2))


address = st.sidebar.text_input(
    "Address", "1000 Main St, Cincinnati, OH 45202")
start_date = st.sidebar.date_input("Start Date",  pd.Timestamp(2022, 9, 28))
end_date = st.sidebar.date_input("End Date",  pd.Timestamp(2022, 9, 30))
type_var = st.sidebar.selectbox(
    'Type:', ('Gust', 'Wind', 'Temp', 'Precipitation'))
hourly_daily = st.sidebar.radio('Aggregate Data', ('Hourly', 'Daily'))


start_date = start_date.strftime("%Y-%m-%d")
end_date = end_date.strftime("%Y-%m-%d")

lat, lon = geocode(address)

df_all, df_all_agg = get_weather_data(lat, lon, start_date, end_date)

# Keys
var_key = {'Gust': 'i10fg', 'Wind': 'wind10',
           'Temp': 't2m', 'Precipitation': 'tp'}

variable = var_key[type_var]

unit_key = {'Gust': 'MPH', 'Wind': 'MPH',
            'Temp': 'F', 'Precipitation': 'In.'}
unit = unit_key[type_var]

cols_key = {'Gust': ['windgusts_10m'], 'Wind': ['windspeed_10m'], 'Temp': ['temperature_2m'],
            'Precipitation': ['precipitation']}

cols_key_agg = {'Gust': ['windgusts_10m_min', 'windgusts_10m_mean',
                         'windgusts_10m_max'],
                'Wind': ['windspeed_10m_min', 'windspeed_10m_mean',
                         'windspeed_10m_max'],
                'Temp': ['temperature_2m_min', 'temperature_2m_mean', 'temperature_2m_max'],
                'Precipitation': ['precipitation_sum']}

if hourly_daily == 'Hourly':
    cols = cols_key[type_var]
else:
    cols = cols_key_agg[type_var]

if hourly_daily == 'Hourly':
    fig = px.line(df_all, x="time", y=cols[0])
    df_downloald = df_all
else:
    fig = px.line(df_all_agg.reset_index(), x="date", y=cols[0])
    df_downloald = df_all_agg.reset_index()

with col1:
    st.title('Weather Data')
    st.plotly_chart(fig)

    csv = convert_df(df_downloald)

    st.download_button(
        label="Download data as CSV",
        data=csv,
        file_name=f'{start_date}.csv',
        mime='text/csv')


with col2:
    st.title('')


st.markdown(""" <style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style> """, unsafe_allow_html=True)