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

# # WeatherPy
# ----
#
# ### Analysis
# * As expected, the weather becomes significantly warmer as one approaches the equator (0 Deg. Latitude). More interestingly, however, is the fact that the southern hemisphere tends to be warmer this time of year than the northern hemisphere. This may be due to the tilt of the earth, or more obviously - it is currently summer in the southern hemisphere.
# * There is no strong relationship between latitude and cloudiness. However, it is interesting to see that a strong band of cities sits at 0, 80, and 100% cloudiness.
# * There is no strong relationship between latitude and wind speed. However, in northern hemispheres there is a flurry of cities with over 20 mph of wind.
#
# ---
#
# #### 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
import json

from pprint import pprint

# Import API key
import api_keys

# 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
    
    # Replace spaces with %20, otherwise url may be incorrect 
    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).
#

# +
#Open API key
api_key = api_keys.api_key

# URL for Weather Map API call
url = 'http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=' + api_key

# +
# Create empty lists to append API data to

city_name = []
cloudiness = []
country = []
date = []
humidity = []
lat = []
lng = []
max_temp = []
wind_speed = []

# Start the call counter 
record = 1

# Log file print statement
print(f"Beginning Data Retrieval")
print(f"-------------------------------")

#Loop through the cities in the city list 
for city in cities:  
    
    # Try statement to append calls where value is found 
    # Not all calls will be successful as not all cities generated will have records
    try: 
        response = requests.get(f"{url}&q={city}").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"])
        max_temp.append(response["main"]["temp_max"])
        lat.append(response["coord"]["lat"])
        lng.append(response["coord"]["lon"])
        wind_speed.append(response["wind"]["speed"])
        city_record = response["name"]
        print(f"Processing Record {record} | {city_record}")
        print(f"{url}&q={city}")
        
        # Increase counter by one 
        record += 1
        
        # Wait a second in loop to not over exceed rate limit of API
        time.sleep(1.01)
        
    # If no record found "skip" to next call
    except:
        print("City not found. Skipping...")
    continue
# -

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

# Create dictionary to store lists
weather_dict = {
    "City": city_name,
    "Country": country,
    "Date": date,
    "Humidity": humidity,
    "Cloudiness": cloudiness,
    "Wind Speed": wind_speed,
    "Max Temp": max_temp,
    "Latitude": lat,
    "Longitude": lng
}

# Create dataframe
weather_data = pd.DataFrame(weather_dict)
weather_data.count()

# Export dataframe to CSV
weather_data.to_csv('Output_CSV/weather_data.csv')

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

# Show dataframe
weather_data.head()

# #### Latitude vs. Temperature Plot

# +
# Build scatterplot
plt.scatter(weather_data["Latitude"], weather_data["Max Temp"], marker="o", s=30, edgecolor="black", alpha=0.75)

# Set title, labels, grid
plt.title("City Latitude vs. Max Temperature (01/27/19)")
plt.xlabel("Latitude")
plt.ylabel("Max. Temperature (F)")
plt.grid(True)

# Export plot
plt.savefig("Output_Plots/MaxTemp_vs_Latitude.png")

# Show plot
plt.show()
# -

# #### Latitude vs. Humidity Plot

# +
# Build scatterplot
plt.scatter(weather_data["Latitude"], weather_data["Humidity"], marker="o", s=30, edgecolor="black", alpha=0.75)

# Set title, labels, grid
plt.title("City Latitude vs. Humidity (01/27/19)")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.grid(True)

# Export plot
plt.savefig("Output_Plots/Humidity_vs_Latitude.png")

# Show plot
plt.show()
# -

# #### Latitude vs. Cloudiness Plot

# +
# Build scatterplot
plt.scatter(weather_data["Latitude"], weather_data["Cloudiness"], marker="o", s=30, edgecolor="black", alpha=0.75)

#Set title, labels, grid
plt.title("City Latitude vs. Cloudiness (01/27/19)")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.grid(True)

# Export plot
plt.savefig("Output_Plots/Cloudiness_vs_Latitude.png")

# Show plot
plt.show()
# -

# #### Latitude vs. Wind Speed Plot

# +
# Build scatterplot
plt.scatter(weather_data["Latitude"], weather_data["Wind Speed"], marker="o", s=30, edgecolor="black", alpha=0.75)

# Set title, labels, grid
plt.title("City Latitude vs. Wind Speed (01/27/19)")
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.grid(True)

# Export
plt.savefig("Output_Plots/WindSpeed_vs_Latitude.png")

# Show plot
plt.show()
# -



StarcoderdataJupyterScriptsDedupFiltered