# ---
# 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
# ---

# # WeatherPy
# ----
#
# #### Note
# * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.

# +
#Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import time
from scipy.stats import linregress

# Import API key
from api_keys import api_key

# Incorporated citipy to determine city based on latitude and longitude
from citipy import citipy

# Output File (CSV)
output_data_file = "output_data/cities.csv"

# Range of latitudes and longitudes
lat_range = (-90, 90)
lng_range = (-180, 180)
# -

# ## Generate Cities List

# +
# List for holding lat_lngs and cities

lat_lngs = []
cities = []

# Create a set of random lat and lng combinations
lats = np.random.uniform(low=-90.000, high=90.000, size=1500)
lngs = np.random.uniform(low=-180.000, high=180.000, size=1500)
lat_lngs = zip(lats, lngs)

# Identify nearest city for each lat, lng combination
for lat_lng in lat_lngs:
    city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name
    city = city.replace(" ", "%20")
    # If the city is unique, then add it to a our cities list
    if city not in cities:
        
        cities.append(city)

# Print the city count to confirm sufficient count
len(cities)
# -

# ### Perform API Calls
# * Perform a weather check on each city using a series of successive API calls.
# * Include a print log of each city as it'sbeing processed (with the city number and city name).
#

#Name url and extract data
url = f"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q={city}&units=Imperial"
url

# +
#Create empty lists for for loop
city_name = []
cloudiness = []
country = []
date = []
humidity = []
lat = []
lng = []
maxTemp = []
windSpeed = []

record = 1

#creat a for loop that loops through data. Also creat try and except statement and append response/url data.

for city in cities:
    url = f"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q={city}&units=Imperial"
    try:
        response = requests.get(url).json()
        city_name.append(response["name"])
        cloudiness.append(response["clouds"]["all"])
        country.append(response["sys"]["country"])
        date.append(response["dt"])
        humidity.append(response["main"]["humidity"])
        lat.append(response["coord"]["lat"])
        lng.append(response["coord"]["lon"])
        maxTemp.append(response["main"]["temp"])
        windSpeed.append(response["wind"]["speed"])
        cityRecord = response["name"]
        print(f"Processing Record {record} | {cityRecord}")
        
        #Create a time function that will prevent you from being blocked for running the api too often.
        record= record + 1
        time.sleep(1.01)
    except:
        print("No City")
        print(response)
#g_key
# -

#Printed out cities to make sure there were multiple cities.
print(cities)

# ### Convert Raw Data to DataFrame
# * Export the city data into a .csv.
# * Display the DataFrame

#Create a dictionary with all columns inside for data frame.
weatherDict = {
    "City": city_name,
    "Cloudiness":cloudiness, 
    "Country":country,
    "Date":date, 
    "Humidity": humidity,
    "Lat":lat, 
    "Lng":lng, 
    "Max Temp": maxTemp,
    "Wind Speed":windSpeed
}
weatherData = pd.DataFrame(weatherDict)
weatherData



# ### Plotting the Data
# * Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.
# * Save the plotted figures as .pngs.

# +
#Create a scatter plot that shows Latitude vs Temperature.
plt.scatter(weatherData["Lat"], weatherData["Max Temp"], marker="o", s=10)

#Include other graph data
plt.title("Latitude vs. Temperature")
plt.ylabel("Max. Temperature (F)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()
# -

# #### Latitude vs. Temperature Plot

# #### Latitude vs. Humidity Plot

# +
# Build a scatter plot for Latitude vs Humidity
plt.scatter(weatherData["Lat"], weatherData["Humidity"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("City Latitude vs. Humidity")
plt.ylabel("Humidity (%)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()
# -

# #### Latitude vs. Cloudiness Plot

# +
# Build a scatter plot for Latitude vs Cloudiness

plt.scatter(weatherData["Lat"], weatherData["Cloudiness"], marker="o", s=10)
# Incorporate the other graph properties
plt.title("City Latitude vs. Cloudiness")
plt.ylabel("Cloudiness (%)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()
# -

# #### Latitude vs. Wind Speed Plot

# +
# Build a scatter plot for Latitude vs Wind Speed
plt.scatter(weatherData["Lat"], weatherData["Wind Speed"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("City Latitude vs. Wind Speed")
plt.ylabel("Wind Speed (mph)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()


# -

# ## Linear Regression

# OPTIONAL: Create a function to create Linear Regression plots
# That way you can call your function once.
def plotLinReg(x_values, y_values, label):
    (slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
    regress_values = x_values * slope + intercept
    line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
    plt.scatter(x_values,y_values)
    plt.plot(x_values,regress_values,"r-")
    plt.annotate(line_eq,(6,10),fontsize=15,color="red")
    plt.xlabel(label)
    plt.ylabel('Latitude')
    print(f"The r-squared is: {rvalue}")
    plt.show()


# +
# Create Northern and Southern Hemisphere DataFrames
#Create a northern hem Data Frame with appropriate columns
cityDataNorth = weatherData[weatherData["Lat"] > 0]


cloudinessNorth = cityDataNorth["Cloudiness"]
humidityNorth = cityDataNorth["Humidity"]
latitudeNorth = cityDataNorth["Lat"]
maxTempNorth = cityDataNorth["Max Temp"]
windSpeedNorth = cityDataNorth["Wind Speed"]

#Create a southern hem Data Frame with appropriate columns
cityDataSouth = weatherData[weatherData["Lat"] < 0]

cloudinessSouth = cityDataSouth["Cloudiness"]
humiditySouth = cityDataSouth["Humidity"]
latitudeSouth = cityDataSouth["Lat"]
maxTempSouth = cityDataSouth["Max Temp"]
windSpeedSouth = cityDataSouth["Wind Speed"]


# -

# ####  Northern Hemisphere - Max Temp vs. Latitude Linear Regression

#Create a linear regression that correlates the latitude(distance from sun) to the decrease in temperature. Repeat  this step for all other graphs.
x_values = maxTempNorth
y_values = latitudeNorth
label = "Max Temp"
plotLinReg(x_values, y_values, label)


# ####  Southern Hemisphere - Max Temp vs. Latitude Linear Regression

x_values = maxTempSouth
y_values = latitudeSouth
label = "Max Temp"
plotLinReg(x_values, y_values, label)

# ####  Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression

x_values = humidityNorth
y_values = latitudeNorth
label = "Humidity"
plotLinReg(x_values, y_values, label)

# ####  Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression

x_values = humiditySouth
y_values = latitudeSouth
label = "Humidity"
plotLinReg(x_values, y_values, label)

# ####  Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression

x_values = cloudinessNorth
y_values = latitudeNorth
label = "Cloudiness"
plotLinReg(x_values, y_values, label)

# ####  Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression

x_values = cloudinessSouth
y_values = latitudeSouth
label = "Cloudiness"
plotLinReg(x_values, y_values, label)

# ####  Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression

x_values = windSpeedNorth
y_values = latitudeNorth
label = "Wind Speed"
plotLinReg(x_values, y_values, label)

# ####  Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression

x_values = windSpeedSouth
y_values = latitudeSouth
label = "Wind Speed"
plotLinReg(x_values, y_values, label)



StarcoderdataJupyterScriptsDedupFiltered