コード例 #1
0
ファイル: views.py プロジェクト: cortex-labs/weather
def forecast(request):
    if not 'city' in request.GET:
        return JsonResponse({'message': 'Parameter "city" is required'}, status=400)
    if not 'days' in request.GET:
        return JsonResponse({'message': 'Parameter "days" is required'}, status=400)

    try:
        days = int(request.GET['days'])
    except ValueError:
        return JsonResponse({'message': 'Parameter "days" must be between 1 and 10'}, status=400)

    if not 0 < days <= 10:
        return JsonResponse({'message': 'Parameter "days" must be between 1 and 10'}, status=400)

    # Fetch (lat, lon) for given city.
    try:
        city = City.objects.get(name=request.GET['city'])
    except City.MultipleObjectsReturned:
        # XXX: Unfortunately the data we're using contains what appears to be
        # duplicates. Use the first result as a workaround for now.
        city = City.objects.filter(name=request.GET['city']).first()
    except City.DoesNotExist:
        return JsonResponse(
            {'message': 'City "{}" could not be found'.format(request.GET['city'])}, status=400)

    # Get weather for the given city.
    city = Place(city.name, city.lat, city.lon)
    forecast = Forecast(city,
        'metno-locationforecast/1.0 https://github.com/Rory-Sullivan/metno-locationforecast')
    forecast.update()

    # Collect temperature and humidity values for calculations and limit data
    # to the number of days given in the request.
    t, h = [], []
    for interval in forecast.data.intervals:
        if interval.end_time <= datetime.datetime.now() + datetime.timedelta(days=days):
            t.append(interval.variables['air_temperature'].value)
            h.append(interval.variables['relative_humidity'].value)

    temperature_min = min(t)
    temperature_max = max(t)
    temperature_average = statistics.mean(t)
    temperature_median = statistics.median(t)

    humidity_min = min(h)
    humidity_max = max(h)
    humidity_average = statistics.mean(h)
    humidity_median = statistics.median(h)

    return JsonResponse({
        'temperature_min': temperature_min,
        'temperature_max': temperature_max,
        'temperature_average': round(temperature_average, 2),
        'temperature_median': round(temperature_median, 2),
        'humidity_min': humidity_min,
        'humidity_max': humidity_max,
        'humidity_average': round(humidity_average, 2),
        'humidity_median': round(humidity_median, 2),
    })
コード例 #2
0
 def __init__(self, place_name, lat, long, altitude=0):
     self.place_name = place_name
     self.lat = lat
     self.long = long
     self.altitude = altitude
     self.home = Place(place_name, self.lat, self.long, self.altitude)
     self.forecast = Forecast(
         home, "github.com/FutureSharks/rpi-weather-display 1.0")
     self.forecast.update()
コード例 #3
0
def fetch_weather(lat, lon, address=""):
    ''' Get forecast data using metno-locationforecast'''

    location = Place(address, lat, lon)

    forecast = Forecast(location, user_agent=user_agent)
    updated = forecast.update()
    if forecast.json['status_code'] != 200:
        logger.error('Forecast response: %s', forecast.json['status_code'])
    return forecast, updated
コード例 #4
0
class metNorway(object):
    """
    An interface to the Norwegian Meteorological Institute API

    Example:
        home = Place("Berlin", 52.52437, 13.41053, 34)
        forecast = Forecast(home, "github.com/FutureSharks/rpi-weather-display 1.0")
        forecast.update()

    """
    def __init__(self, place_name, lat, long, altitude=0):
        self.place_name = place_name
        self.lat = lat
        self.long = long
        self.altitude = altitude
        self.home = Place(place_name, self.lat, self.long, self.altitude)
        self.forecast = Forecast(
            home, "github.com/FutureSharks/rpi-weather-display 1.0")
        self.forecast.update()

    def get_hourly_data(self, hours=24):
        """
        Returns a list of hourly rain and temperature values
        """
        self.forecast.update()

        results = []

        for hour in forecast.data.intervals[0:hours]:
            h = {
                "date":
                hour.start_time,
                "air_temperature":
                hour.variables["air_temperature"].value,
                "precipitation_amount":
                hour.variables["precipitation_amount"].value,
            }

            results.append(h)

        return results
コード例 #5
0
    def get_weather_data(self,
                         county='Dublin',
                         latitude=53.33,
                         longitude=-6.24,
                         altitude=10):
        self.dublin = Place(county, latitude, longitude, altitude)
        self.forecast = Forecast(self.dublin, self.USER_AGENT, 'complete')
        self.forecast.update()
        df = pd.DataFrame()
        for interval in self.forecast.data.intervals:
            row = pd.DataFrame.from_dict(interval.variables, orient='index')
            row['start_time'] = interval.start_time
            row['end_time'] = interval.end_time
            df = df.append(row)

        df.columns = ['weather_feeds', 'start_time', 'end_time']
        df['weather_feeds'] = df['weather_feeds'].apply(str)
        df[['header', 'value']] = df.weather_feeds.str.split(expand=True)
        df['header'] = df['header'].str.replace(':', '')
        df2 = df.pivot(index='start_time', columns='header', values='value')
        self.df2 = df2
コード例 #6
0
def værdata():
    USER_AGENT = "metno_locationforecast/1.0 [email protected]"

    Trondheim = Place("Trondheim", 63.42024, 10.40122)
    Trondheim_forecast = Forecast(Trondheim, USER_AGENT, "complete")
    Trondheim_forecast.update()
    #print(Trondheim_forecast)

    First_interval = Trondheim_forecast.data.intervals[0]
    Trondheim_forecast.update()

    tomorrow = dt.date.today() - dt.timedelta(days=30)
    print(dt.date.today())
    print(dt.timedelta(days=30))
    print(tomorrow)

    tomorrow_intervals = Trondheim_forecast.data.intervals_for(tomorrow)
    print(tomorrow_intervals)
    print("Forecast for tomorrow in Trondheim:\n")
    for interval in tomorrow_intervals:
        print(interval)

    #print(First_interval)

    #print(f"Duration: {First_interval.duration}")

    rain = First_interval.variables["precipitation_amount"]
    #print(rain)

    #print(f"Rain values: {rain.value}")
    #print(f"Rain units: {rain.units}")

    print(First_interval.variables.keys())
コード例 #7
0
"""Basic usage."""

from metno_locationforecast import Place, Forecast

# Add your own user agent here.
USER_AGENT = "metno_locationforecast/1.0 https://github.com/Rory-Sullivan/yrlocationforecast"

# Create a Place instance.
# Place(name, latitude, longitude, altitude)
new_york = Place("New York", 40.7, -74.0, 10)

# Create a Forecast instance for the place.
# Forecast(place, forecast_type, user_agent, save_location="./data/")
new_york_forecast = Forecast(new_york, USER_AGENT)

# Update the forecast. This requests data from the MET API and saves data to the
# save location.
new_york_forecast.update()

print(new_york_forecast)
コード例 #8
0
ファイル: weatherData.py プロジェクト: WilliamMRS/CoT
def Future_forecast():
    USER_AGENT = "metno_locationforecast/1.0 [email protected]"
    Trondheim = Place("Trondheim", 63.42024, 10.40122)
    Trondheim_forecast = Forecast(Trondheim, USER_AGENT)
    Trondheim_forecast.update()
    return (Trondheim_forecast)
コード例 #9
0
 suntime = (sunset-sunrise)
 print(suntime, "timer er solen oppe i løpet av en hel dag")
 
 sun_mid = (suntime/2) 
 suntop = sun_mid + sunrise
 suntop = suntop.strftime("%Y-%m-%d %H:%M:%S")
 print("Solen er på sitt høyeste", suntop)
 
 
 """
 Henter værdata fra metno!
 """
 
 user_agent = "metno_locationforecast/1.0 [email protected]"
 ntnu = Place("NTNU", 63.418, 10.406, 50)
 ntnu_forecast = Forecast(ntnu, user_agent)
 ntnu_forecast.update()
 interval = ntnu_forecast.data.intervals[1]
 clod_frac = interval.variables["cloud_area_fraction"]
 clod_frac = clod_frac.value
 print(clod_frac, "% skyer er det nå ")
 
 
 """
 150 kvm med tak. Heller 20 grader nord --> sør. Beregn oppladning av dette ved utnyttelse av sola.
 Med 75 kvm takflate beregner man 44 solcellepaneler. Effekt i kW er 13 420. Estimert årsproduksjon er 10 736 kWh.
 Premium svart 305 W panel. Ganger dette med 2 fordi det er 150 kvm tilgjengelig takoverflate.
 
 Setter forskjellige konstanter avhengig av hvor mye solenergi som produserers med x antall timer +/- når solen er på sitt høyeste.
 Dette beregnes utifra skyprosenten.
 """
コード例 #10
0
class WeatherDataFeed:
    '''
    Loading Current Weather Data from Met.no API

    Parameters
    ----------
    links : Locations
    symbol - Symbol of the Stock to extract the data
    
    Returns
    -------
    Integer
    DataFrame

    '''
    def __init__(self):
        self.USER_AGENT = 'metno_locationforecast/1.0'
        self.check_extention = ['.csv']
        self.sourceFolder = '/path/to/your/repo/weather_feeds/src'

    def get_weather_data(self,
                         county='Dublin',
                         latitude=53.33,
                         longitude=-6.24,
                         altitude=10):
        self.dublin = Place(county, latitude, longitude, altitude)
        self.forecast = Forecast(self.dublin, self.USER_AGENT, 'complete')
        self.forecast.update()
        df = pd.DataFrame()
        for interval in self.forecast.data.intervals:
            row = pd.DataFrame.from_dict(interval.variables, orient='index')
            row['start_time'] = interval.start_time
            row['end_time'] = interval.end_time
            df = df.append(row)

        df.columns = ['weather_feeds', 'start_time', 'end_time']
        df['weather_feeds'] = df['weather_feeds'].apply(str)
        df[['header', 'value']] = df.weather_feeds.str.split(expand=True)
        df['header'] = df['header'].str.replace(':', '')
        df2 = df.pivot(index='start_time', columns='header', values='value')
        self.df2 = df2

    def save_weather_data(self, file_name='default.csv'):
        weather_data = self.df2
        weather_data['Date_Time'] = weather_data.index
        weather_data = weather_data[[
            'Date_Time', 'air_pressure_at_sea_level', 'air_temperature',
            'air_temperature_max', 'air_temperature_min',
            'cloud_area_fraction', 'cloud_area_fraction_high',
            'cloud_area_fraction_low', 'cloud_area_fraction_medium',
            'dew_point_temperature', 'fog_area_fraction',
            'precipitation_amount', 'relative_humidity',
            'ultraviolet_index_clear_sky', 'wind_from_direction', 'wind_speed'
        ]]
        # Run First time like this to include headers and second time you can use append mode and not include headers
        # weather_data.to_csv(os.path.join(os.getcwd(),file_name), index = False)
        weather_data.to_csv(os.path.join(os.getcwd(), file_name),
                            mode='a',
                            header=False,
                            index=False)
        self.file_name = file_name

    def clean_up_weather_data(self):
        download_path = ''
        for filename in os.listdir(self.sourceFolder):
            if any(ext in filename for ext in self.check_extention):
                if filename == self.file_name:
                    print(filename)
                    download_path = (os.path.join(self.sourceFolder, filename))
                    data = pd.read_csv(download_path)
                    df = pd.DataFrame(data)
                    # Sort the values by Date Time
                    df = df.sort_values('Date_Time', ascending=True)
                    # De-duping the rows based on most up to date value
                    df = df.drop_duplicates(subset='Date_Time', keep='last')
                    df.to_csv(download_path, index=False)
                else:
                    pass
            else:
                pass
コード例 #11
0
"""Using a custom save location.

Note there is now support for home directory ('~/') and relative notation ('../').
"""

import os
from metno_locationforecast import Place, Forecast

# Add your own user agent here.
USER_AGENT = "metno_locationforecast/1.0 https://github.com/Rory-Sullivan/yrlocationforecast"

new_york = Place("New York", 40.7, -74.0, 10)

# Provide a custom save location
new_york_forecast = Forecast(new_york, USER_AGENT, save_location="~/forecast_data/")

# Here we can view the actual save location
save_location = str(new_york_forecast.save_location)
print(save_location)

# Update the forecast. This requests data from the MET API and saves data to the
# save location.
new_york_forecast.update()

print(os.listdir(save_location))
コード例 #12
0
ファイル: test_metno.py プロジェクト: ways/fingr
from metno_locationforecast import Place, Forecast
import datetime as dt

new_york = Place("Bergen/Norway", 60.3, 5.3)
ny_forecast = Forecast(new_york, forecast_type="complete", user_agent="fingr/1.0 https://graph.no")
ny_forecast.update()
# print(ny_forecast)

        # variables ['air_pressure_at_sea_level', 'air_temperature', 
        # 'cloud_area_fraction', 'relative_humidity', 'wind_from_direction', 
        # 'wind_speed', 'precipitation_amount'])

first_interval = ny_forecast.data.intervals[0]
print(first_interval)

# Access the interval's duration attribute.
print(f"Duration: {first_interval.duration} - {first_interval.symbol_code}")

print()  # Blank line

# Access a particular variable from the interval.
rain = first_interval.variables["precipitation_amount"]
print(rain)

# Access the variables value and unit attributes.
print(f"Rain value: {rain.value}")
print(f"Rain units: {rain.units}")

# Get a full list of variables available in the interval.
print(first_interval.variables.keys())
コード例 #13
0
"""An example of accessing individual forecast variables."""

from metno_locationforecast import Place, Forecast

USER_AGENT = "metno_locationforecast/1.0 https://github.com/Rory-Sullivan/yrlocationforecast"

new_york = Place("New York", 40.7, -74.0, 10)
new_york_forecast = Forecast(new_york, USER_AGENT, "complete")
new_york_forecast.update()

# Access a particular interval.
first_interval = new_york_forecast.data.intervals[0]
print(first_interval)

# Access the interval's duration attribute.
print(f"Duration: {first_interval.duration}")

print()  # Blank line

# Access a particular variable from the interval.
rain = first_interval.variables["precipitation_amount"]
print(rain)

# Access the variables value and unit attributes.
print(f"Rain value: {rain.value}")
print(f"Rain units: {rain.units}")

# Get a full list of variables available in the interval.
print(first_interval.variables.keys())
コード例 #14
0
"""Get forecast for a particular day."""

from metno_locationforecast import Place, Forecast
import datetime as dt

USER_AGENT = "metno_locationforecast/1.0 https://github.com/Rory-Sullivan/yrlocationforecast"
beijing = Place("Beijing", 39.9, 116.4)
beijing_forecast = Forecast(beijing, USER_AGENT)
beijing_forecast.update()

# Create a datetime.date object for the day in question.
tomorrow = dt.date.today() + dt.timedelta(days=1)

# Get intervals for that date.
tomorrows_intervals = beijing_forecast.data.intervals_for(tomorrow)

# Iterate through each of the returned intervals and print it.
print("Forecast for tomorrow in Beijing:\n")
for interval in tomorrows_intervals:
    print(interval)
コード例 #15
0
"""How to change the units of certain variables."""

from metno_locationforecast import Place, Forecast

USER_AGENT = "metno_locationforecast/1.0 https://github.com/Rory-Sullivan/yrlocationforecast"
london = Place("London", 51.5, -0.1, 25)
london_forecast = Forecast(london, USER_AGENT)
london_forecast.update()

# Iterate over all variables of every interval.
for interval in london_forecast.data.intervals:
    for variable in interval.variables.values():

        # Change temperature units to Fahrenheit
        if variable.name == "air_temperature":
            variable.convert_to("fahrenheit")

        # Change wind speed units to miles per hour.
        elif variable.name == "wind_speed":
            variable.convert_to("mph")

# Print forecast, notice the new variables.
print(london_forecast)