Ejemplo n.º 1
0
def weather_condition(req):
    """Returns a string containing a human-readable response to the user
    with the probability of the provided weather condition occurring
    or a prompt for more information

    Takes a city, condition and (optional) dates
    uses the template responses found in weather_responses.py as templates
    and the conditions listed in weather_entities.py
    """

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(req['queryResult']['parameters'])
    if error:
        return error

    # Check to make sure there is a activity, if not return an error
    if not forecast_params['condition']:
        return 'What weather condition would you like to check?'

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    # get the response
    return forecast.get_condition_response()
Ejemplo n.º 2
0
def weather_outfit(req):
    """Returns a string containing text with a response to the user
    with a indication if the outfit provided is appropriate for the
    current weather or a prompt for more information

    Takes a city, outfit and (optional) dates
    uses the template responses found in weather_responses.py as templates
    and the outfits listed in weather_entities.py
    """

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(req['queryResult']['parameters'])
    if error:
        return error

    # Validate that there are the required parameters to retrieve a forecast
    if not forecast_params['outfit']:
        return 'What are you planning on wearing?'

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    return forecast.get_outfit_response()
Ejemplo n.º 3
0
def weather_temperature(req):
    """Returns a string containing text with a response to the user
    with a indication if temperature provided is consisting with the
    current weather or a prompt for more information

    Takes a city, temperature and (optional) dates.  Temperature ranges for
    hot, cold, chilly and warm can be configured in config.py
    uses the template responses found in weather_responses.py as templates
    """

    parameters = req['queryResult']['parameters']

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(parameters)
    if error:
        return error

    # If the user didn't specify a temperature, get the weather for them
    if not forecast_params['temperature']:
        return weather(req)

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    return forecast.get_temperature_response()
Ejemplo n.º 4
0
def weather_activity(req):
    """Returns a string containing text with a response to the user
    with a indication if the activity provided is appropriate for the
    current weather or a prompt for more information

    Takes a city, activity and (optional) dates
    uses the template responses found in weather_responses.py as templates
    and the activities listed in weather_entities.py
    """

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(req['queryResult']['parameters'])
    if error:
        return error

    # Check to make sure there is a activity, if not return an error
    if not forecast_params['activity']:
        return 'What activity were you thinking of doing?'

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    # get the response
    return forecast.get_activity_response()
Ejemplo n.º 5
0
def weather():
    location = request.args['location']
    
    if location is not None:
        try:
            forecast = Forecast(location)
            forecast.retrieveForecast()

            return render_template('weather.html', forecast=forecast)
        except errors.GenericError as ge:
            return render_template('index.html', error=ge)
    else:
        return render_template('index.html', error=errors.GenericError(errno=constants.ERROR_NO_INPUT))
Ejemplo n.º 6
0
Archivo: data.py Proyecto: etharner/ice
    def data_processing(self, sea, year1, dec1, year2, dec2, prop, prec):
        forecast_data = {}
        season_data = {}
        data = self.sea_data['mean']
        for cur_sea in data.keys():
            for cur_year in sorted(data[cur_sea]):
                if cur_year > 1996:
                    for cur_month in sorted(data[cur_sea][cur_year]):
                        for cur_dec in sorted(data[cur_sea][cur_year][cur_month]):
                            season_date = Estimation.get_season_date(cur_year, cur_month, cur_dec)
                            if cur_sea not in season_data.keys():
                                season_data[cur_sea] = {}
                            if season_date['year'] not in season_data[cur_sea].keys():
                                season_data[cur_sea][season_date['year']] = {}
                            if season_date['month'] not in season_data[cur_sea][season_date['year']].keys():
                                season_data[cur_sea][season_date['year']][season_date['month']] = {}
                            if season_date['dec'] not in season_data[cur_sea][season_date['year']][
                                season_date['month']].keys():
                                season_data[cur_sea][season_date['year']][season_date['month']][
                                    season_date['dec']] = \
                                    data[cur_sea][cur_year][cur_month][cur_dec]

        for year in range(year1, year2 + 1):
            start_dec = dec1 if year == year1 else 1
            end_dec = dec2 if year == year2 else 36
            forecast_decs = {}

            for dec in range(start_dec, end_dec + 1):
                month_dec = Estimation.get_month_dec(dec)
                season_date = Estimation.get_season_date(year, month_dec['month'], month_dec['dec'])
                season_date_glob_dec = Estimation.get_year_dec(season_date['month'], season_date['dec'])
                f = Forecast()
                cur_data = f.forecast(season_data, prop, sea, season_date_glob_dec, season_date['year'], prec)

                if season_date['year'] not in season_data[sea]:
                    season_data[sea][season_date['year']] = {}
                if season_date['month'] not in season_data[sea][season_date['year']]:
                    season_data[sea][season_date['year']][season_date['month']] = {}
                if season_date['dec'] not in season_data[sea][season_date['year']][season_date['month']]:
                    season_data[sea][season_date['year']][season_date['month']][season_date['dec']] = {prop: cur_data[0]}


                if month_dec['month'] not in forecast_decs.keys():
                    forecast_decs[month_dec['month']] = {}
                forecast_decs[month_dec['month']][month_dec['dec']] = [cur_data[0], cur_data[1]]

            forecast_data[year] = forecast_decs

        print(forecast_data)
        return forecast_data
Ejemplo n.º 7
0
def get_currently_forecast():
    city = request.args.get('city')

    response = DarkSkyWeather.currently(city=city)
    forecast_data = Forecast(timestamp=response["currently"]["time"],
                             temperature=response["currently"]["temperature"])
    return str(forecast_data)
Ejemplo n.º 8
0
    def test_format_segments(self):
        segments = Forecast.from_json(
            read_file('./test/fixtures/sangre.segments.json'))
        segments = format_segments(segments, joined=True)
        expected_text = read_file('./test/fixtures/sangre.txt').strip()

        self.assertEqual(1, len(segments))
        self.assertEqual(expected_text, segments[0].strip())
Ejemplo n.º 9
0
def main():
    data_processor = ProcessData()
    forecast_util = Forecast()
    series,train, test = data_processor.read_data('shampoo-sales.csv')

    forecasts = forecast_util.make_forecasts(train,test, 1, 3)
    forecast_util.evaluate_forecasts(test, forecasts, 1, 3)
    forecast_util.plot_forecasts(series, forecasts, 12)
Ejemplo n.º 10
0
def main():
    sender, password = get_email_credentials()
    receivers = get_receivers()

    gmail = Gmail(sender, password)

    for locationName, emails in receivers.items():
        location = Location(locationName)

        if location.get_local_time().hour == SEND_EMAIL_HOUR:
            forecast = Forecast(location)

            if forecast.rain_today():
                message = forecast.get_forecast_message()

                for email in emails:
                    send_forecast_message(gmail, email, message)

    print('INFO: Done.')
Ejemplo n.º 11
0
    def __forecast(self, soup, num_of_days_of_forecast):
        keys = [
            "Date/Month:", "Wind:", "Weather:", "Temp range:", "R.H. range:"
        ]
        l = soup.get_text().split('\n')
        forecast_list = []
        # b = []
        # for a in l:
        date = ""
        wind = ""
        weather = ""
        temp = ""
        rh = ""
        last_date = ""
        is_first_date = True
        for i in range(0, len(l)):
            s = l[i].strip()
            if i + 2 < len(l):
                if s == keys[0]:
                    date = l[i + 1].strip()
                elif s == keys[1]:
                    wind = l[i + 1].strip()
                elif s == keys[3]:
                    temp = l[i + 1].strip() + " " + l[i + 2].strip()
                elif s == keys[4]:
                    rh = l[i + 1].strip() + " " + l[i + 2].strip()
                elif s == keys[2]:
                    weather = l[i + 1].strip()
                if len(
                    [x for x in [date, wind, weather, temp, rh]
                     if len(x) > 0]) == 5:
                    f = Forecast(date, wind, weather, temp, rh)
                    forecast_list.append(f.dict())
                    date = ""
                    wind = ""
                    weather = ""
                    temp = ""
                    rh = ""

        return {
            "general_situation": l[0].split(":")[1],
            "forecast": forecast_list[0:num_of_days_of_forecast]
        }
Ejemplo n.º 12
0
    def test_forecast_to_segments(self):
        forecast = Forecast.from_json(read_file('./test/fixtures/sangre.json'))
        actual_segments = forecast_to_segments(forecast)
        expected_segments = jsonpickle.decode(
            read_file('./test/fixtures/sangre.segments.json'))

        self.assertEqual(jsonpickle.encode(expected_segments),
                         jsonpickle.encode(actual_segments))

        self.assertEqual(jsonpickle.encode(expected_segments),
                         jsonpickle.encode(actual_segments))
Ejemplo n.º 13
0
def parse_forecast(html, zone=None):
    html_root = BeautifulSoup(html, 'html.parser')
    forecast_root = html_root.find(id="avalanche-forecast")

    zone = zone.name if zone is not None else None
    date = parse_forecast_date(forecast_root)
    description = parse_forecast_description(forecast_root)
    problems = parse_all_problems(forecast_root)
    warnings = parse_all_warnings(html_root)
    dangers = parse_all_dangers(forecast_root)

    return Forecast(zone, date, description, problems, warnings, dangers)
Ejemplo n.º 14
0
def weather(req):
    """Returns a string containing text with a response to the user
    with the weather forecast or a prompt for more information

    Takes the city for the forecast and (optional) dates
    uses the template responses found in weather_responses.py as templates
    """
    parameters = req['queryResult']['parameters']

    print('Dialogflow Parameters:')
    print(json.dumps(parameters, indent=4))

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(parameters)
    if error:
        print(error, forecast_params)
        return str(error)

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        print('Forecast error')
        print(error, forecast_params)
        return str(error)

    # If the user requests a datetime period (a date/time range), get the
    # response
    if forecast.datetime_start and forecast.datetime_end:
        response = forecast.get_datetime_period_response()
    # If the user requests a specific datetime, get the response
    elif forecast.datetime_start:
        response = forecast.get_datetime_response()
    # If the user doesn't request a date in the request get current conditions
    else:
        response = forecast.get_current_response()

    return response
Ejemplo n.º 15
0
def main():
    if len(argv) < 2:
        return
    try:
        ingredients = argv[1:]
        alt_names = {
            'cream': 'milk',
            'yam': 'sweet potato',
            'scallion': 'green onion',
            'armagnac': 'cognac',
            'stew': 'soup',
            'butterscotch': 'caramel',
            'jelly': 'jam'
        }
        ingredients, indeces = np.unique(np.array(
            [alt_names.get(n, n) for n in ingredients]),
                                         return_index=True)
        ingredients = ingredients[indeces.argsort()]
        names = np.loadtxt('data/names.csv', dtype='object', delimiter=',')
        for ing in ingredients:
            if ing not in names:
                print(f"""Ingredient '{ing}' not found in base.
Sorry forecast cannot be done, please try again""")
                exit()
        print('I. OUR FORECAST')
        fcst = Forecast(ingredients)
        print(fcst.predict_rating_category()[1])
        print('\n')
        print('II. NUTRITION FACTS')
        nf = NutritionFacts(ingredients)
        nf.retrieve()
        print(nf.filter(['Protein', 'Total Carbohydrate', 'Total Fat'], 30))
        print('\n')
        print('III. TOP-3 SIMILAR RECIPES')
        sr = SimilarRecipes(ingredients)
        print(sr.top_similar(3))
    except Exception:
        print('An error occured while executing, please reinstall the app')
Ejemplo n.º 16
0
    def set_weather(self):
        """ Reads weather data and sets it in UI classes """

        self.util.set_url()
        weather = self.util.load_json()

        dark_light = self.util.weather_config[COLOR_DARK_LIGHT]
        semi_transparent_color = (dark_light[0], dark_light[1], dark_light[2],
                                  210)

        self.today = Today(self.util, self.images[0], semi_transparent_color)
        self.today.set_weather(weather)
        self.today.draw_weather()
        self.today.set_visible(False)

        self.forecast = Forecast(self.util, self.images[1],
                                 semi_transparent_color)
        self.forecast.set_weather(weather)
        self.forecast.draw_weather()
        self.forecast.set_visible(True)

        self.add_component(self.today)
        self.add_component(self.forecast)
Ejemplo n.º 17
0
def weather(req):
    """Returns a string containing text with a response to the user
    with the weather forecast or a prompt for more information

    Takes the city for the forecast and (optional) dates
    uses the template responses found in weather_responses.py as templates
    """
    parameters = req['queryResult']['parameters']

    print('Dialogflow Parameters:')
    print(json.dumps(parameters, indent=4))

    # validate request parameters, return an error if there are issues
    error, forecast_params = validate_params(parameters)
    if error:
        return error

    # create a forecast object which retrieves the forecast from a external API
    try:
        forecast = Forecast(forecast_params)
    # return an error if there is an error getting the forecast
    except (ValueError, IOError) as error:
        return error

    # If the user requests a datetime period (a date/time range), get the
    # response
    if forecast.datetime_start and forecast.datetime_end:
        response = forecast.get_datetime_period_response()
    # If the user requests a specific datetime, get the response
    elif forecast.datetime_start:
        response = forecast.get_datetime_response()
    # If the user doesn't request a date in the request get current conditions
    else:
        response = forecast.get_current_response()

    return response
Ejemplo n.º 18
0
def expected_positive_increase( current: pd.DataFrame, history: pd.DataFrame,
                                log: ResultLog, context: str, config: QCConfig=None):
    """
    Fit state-level daily positives data to an exponential and a linear curve.
    Get expected vs actual case increase to determine if current positives
    are within the expected ranges.

    The exponential is used as the upper bound. The linear is used as the lower bound.

    TODO: Eventually these curves will NOT be exp (perhaps logistic?)
          Useful to know which curves have been "leveled" but from a
          data quality perspective, this check would become annoying
    """

    if not config: config = QCConfig()

    forecast_date = current.lastUpdateEt.to_pydatetime().strftime('%Y%m%d')
    history = history.loc[history["date"].astype(str) != forecast_date]

    forecast = Forecast()
    forecast.fit(history)
    forecast.project(current)

    if config.save_results:
        save_forecast_hd5(forecast, config.results_dir)
    elif config.plot_models:
        plot_to_file(forecast, f"{config.images_dir}/{context}", FIT_THRESHOLDS)

    state = forecast.state
    date = forecast.date
    actual_value, expected_linear, expected_exp = forecast.results

    min_value = int(FIT_THRESHOLDS[0] * expected_linear)
    max_value = int(FIT_THRESHOLDS[1] * expected_exp)

    if not (min_value <= actual_value <=  max_value):
        direction = "increase"
        if actual_value < expected_linear:
            direction = "drop"

        log.error(state, f"unexpected {direction} in positive cases ({actual_value:,}) for {date}, expected between {min_value:,} and {max_value:,}")
Ejemplo n.º 19
0
# Call create table functions with the SQL queries
create_table(create_query_forecasts)
create_table(create_query_history)

# call getForecast function from Wunder_api.py to get the current 10 day forecast
forecastValues = getForecast()
# unpack the variables from the tuple
dates = forecastValues[0]
highs = forecastValues[1]
lows = forecastValues[2]

# insert all days of the forecast into the forecasts table
count = 0
for days in dates:
	fore = Forecast('Weather Underground', dates[0],dates[count],highs[count],lows[count])
	insert_forecast(fore)
	
	count = count + 1

# This section determines which dates to request from the historic weather API
# by checking the rows in the history table against the rows in the forecasts table	
# also checks date to make sure that it comes before todays date

# select all rows from history table and populate a list with the dates
records_in_historic = select_historic()
# create a list and extract dates from records_in_historic
dates_in_history = []
count = 0
for rows in records_in_historic:
	currentRow = records_in_historic[count]
Ejemplo n.º 20
0
from sys import argv, exit
from os import sys
import requests
from forecast import Forecast
user_forecast = Forecast()


def main():
    try:
        print(argv)
        api_key = argv[1]
    except IndexError:
        print("Please give correct API key")
        exit()

    print("\nWhat city, country?")
    print("\nUse the format: city, country")
    location = input("city, country: > ")

    print("0: exit")
    print("1: Daily Weather")
    print("2: 5-day Forecast")
    print("3: 10-day Forecast")

    choice = input("\n: > ")

    payload = {
        "appid": api_key,
        "q": location,  #city, country
        "units": "imperial",
    }
Ejemplo n.º 21
0
        data = dict(data.items() + res.items())
        start += datetime.timedelta(days = 1)
    return data

if __name__ == '__main__':
    data = eval(open(os.path.join('data', 'data')).read())
    testdata = eval(open(os.path.join('data', 'testdata')).read())

    #forecast = Forecast(data, testdata, scale = [7.0, 10.0, 2.0, 12.0, 5.0, 8.0, 16.0, 5.0, 6.0, 8.0, 1, 11.0, 3.0])
    #forecast = Forecast(data, testdata, scale = [42.0, 30.0, 0.0, 108.0, 60.0, 56.0, 144.0, 70.0, 42.0, 128.0, 20.0, 220.0, 36.0])
    #print forecast.annealing([(0, 20) for i in range(len(testdata.values()[0]['input']))], trial = 30)

    scale = dict([(-1 * i, []) for i in range(5)])
    veclen = len(testdata.values()[0]['input'])

    try:
        for vector in eval(open('../output').read()):
            forecast = Forecast(data, testdata, scale = vector)
            result = forecast.validation(trial = 100)

            if result in scale:
                scale[result].append(vector)
            elif sorted(scale.keys(), reverse = True)[-1] < result:
                del scale[sorted(scale.keys(), reverse = True)[-1]]
                scale[result] = [vector]
            print vector, result
    except:
        pass

    print scale
Ejemplo n.º 22
0
 def __init__(self):
     self._id = datetime.today().strftime('%Y-%m-%d')
     self.bbc = Forecast()
     self.met = Forecast()
     self.actual = Forecast()
Ejemplo n.º 23
0
    if planet is None:
        raise ValueError(
            "You must indicate a planet contained on the solar system. Valid "
            "ones: %s" % available_planets)

    db = database.connect()

    if args.db_clean:
        db.flushall()

    total_days = args.days + planet.days_in_year() * args.years
    db.set('total', total_days)
    print("> Total days to calculate: %d (from %s point of view)" %
          (total_days, planet.name))

    fc = Forecast()
    totalized = {
        'total': total_days,
        'max_rain': {
            'day': None,
            'perimeter': 0
        }
    }

    for day in range(total_days):
        coords = solar.positions(day)
        prediction = fc.predict(coords)
        totalized.setdefault(prediction['name'], 0)
        totalized[prediction['name']] += 1

        db.set('%s%d' % (config.DB_DAY_PREFIX, day), json.dumps(prediction))
Ejemplo n.º 24
0
from forecast import Forecast
from real_environment import real_environment
import yopy
import json
import utils

# environment
renv = real_environment.RealEnvironment()

# forecast 
forecast = Forecast()

# register your func
functions_to_be_run = {
    'trend_by_perc': forecast.trend_by_perc,
    'trend_by_weekdays': forecast.trend_by_weekdays
}

# read weight json file. if not exist, redefine all weights
try:
    weight = utils.read_file(
        'weight_' + renv.get_env_or_default("coin_name", "bitcoin") + '.json')
except FileNotFoundError:
    weight = {}
    for key, value in functions_to_be_run.items():
        weight[key]=100/len(functions_to_be_run) # give a percantage value
    utils.write_file(
        'weight_' + renv.get_env_or_default("coin_name", "bitcoin") + '.json', weight)

# prophecy is old forecast. read prophecy data and update weights. escobar will smarter.
try:
Ejemplo n.º 25
0
 def init(self):
     self.__forecast = Forecast().forecast(Forecast.TODAY)
     self.setHasConfigurationInterface(False)
     self.resize(125, 125)
     self.setAspectRatioMode(Plasma.Square)
Ejemplo n.º 26
0
 def test_init(self):
     forecast = Forecast()
     self.assertEqual(forecast.df_sampled.values.shape, (333109, 20))
     self.assertEqual(forecast.df_filtered.values.shape, (333109, 18))
     self.assertEqual(forecast.df.values.shape, (333109, 20))
Ejemplo n.º 27
0
from forecast import Forecast

weather = Forecast()

# weather.clean_tmy('../data/golden.csv')
weather.load_tmy('../data/golden_clean.csv')

weather.add_predictor('Dry-bulb (C)').add_predictor('Dew-point (C)')

predictions = weather.auto_regressive(12, 2)
print(predictions)

weather.persist()
Ejemplo n.º 28
0
        start += datetime.timedelta(days=1)
    return data


if __name__ == '__main__':
    data = eval(open(os.path.join('data', 'data')).read())
    testdata = eval(open(os.path.join('data', 'testdata')).read())

    #forecast = Forecast(data, testdata, scale = [7.0, 10.0, 2.0, 12.0, 5.0, 8.0, 16.0, 5.0, 6.0, 8.0, 1, 11.0, 3.0])
    #forecast = Forecast(data, testdata, scale = [42.0, 30.0, 0.0, 108.0, 60.0, 56.0, 144.0, 70.0, 42.0, 128.0, 20.0, 220.0, 36.0])
    #print forecast.annealing([(0, 20) for i in range(len(testdata.values()[0]['input']))], trial = 30)

    scale = dict([(-1 * i, []) for i in range(5)])
    veclen = len(testdata.values()[0]['input'])

    try:
        for vector in eval(open('../output').read()):
            forecast = Forecast(data, testdata, scale=vector)
            result = forecast.validation(trial=100)

            if result in scale:
                scale[result].append(vector)
            elif sorted(scale.keys(), reverse=True)[-1] < result:
                del scale[sorted(scale.keys(), reverse=True)[-1]]
                scale[result] = [vector]
            print vector, result
    except:
        pass

    print scale
Ejemplo n.º 29
0
from forecast import Forecast
import matplotlib.pyplot as plot
import matplotlib.dates as mdates
import seaborn
import pandas
import numpy

# Create the forecast object (default horizon = 24 hours):
weather = Forecast() # set horizon with Forecast(horizon=48)

# load weather data:
#weather.clean_tmy('../data/houston.csv') # this saves a 'cleaned' tmy file
weather.load_tmy('../data/atlanta_clean.csv')

# set the simulation time if necessary:
weather.simulation_time = '07/01/1900 01:00'

# Set up the VAR model by adding variables:
weather.add_predictor('Dry-bulb (C)').add_predictor('RHum (%)')

# Make a number of predictions and capture the predictions and the test data:
predictions, test = weather.auto_regressive(72, 50, trim_data=False)

# Extract a variable of interest (index values correspond to the order the variables were added):
db = predictions[weather.predictor_variables[0]]
rh = predictions[weather.predictor_variables[1]]

# ...and the test data:
dbtest = test[weather.predictor_variables[0]]
rhtest = test[weather.predictor_variables[1]]
Ejemplo n.º 30
0
 def calc_forecast(self):
     self.forecast = Forecast()
     self.forecast.calc_forecast(self.name)
Ejemplo n.º 31
0
def main():
    """
  - Parse user-specified data from YaML
  - Check to see that the needed graphics are available. If not, get them.
  - Get the radar imagery, complete with warnings graphics
  - Get today's hazardous weather outlook statement and parse it
  - Check for FTM outage notifications
  - Get, parse, and write out current weather conditions to specified locations.
  - TODO: should run the getweather.sh shell script, that overlays/composites
    the weather graphics. At present, that shell script calls this script
    and runs the overlays with -bash-.
  - Check for and acquire current multi-band GOES-x imagery of a given resolution.
  """
    if os.path.exists('weatherwidget.log'):
        os.remove('weatherwidget.log')
    logging.basicConfig(
        filename='weatherwidget.log',
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)s %(threadName)-10s %(message)s',
    )

    data = wf.load_settings_and_defaults(SETTINGS_DIR, 'settings.yml',
                                         'defaults.yml')
    if not data:
        logging.error('Unable to load settings files. These are required.')
        sys.exit(
            'settings files are required and could not be loaded successfully.'
        )

    logging.info('Checking for radar outage.')
    wf.outage_check(data)

    logging.info('Retrieving current weather observations.')
    right_now = Observation(data)
    right_now.get_current_conditions()
    right_now.get_backup_obs(use_json=False)
    right_now.merge_good_observations()
    logging.debug('Merged current conditions: %s', right_now.con1.obs)
    sum_con = right_now.conditions_summary()

    if right_now.con1.obs and sum_con:
        text_conditions, nice_con = right_now.format_current_conditions()
        logging.debug('Current conditions from primary source: %s', nice_con)
        wf.write_json(some_dict=nice_con,
                      outputdir=data['output_dir'],
                      filename='current_conditions.json')
    else:
        logging.error(
            'Something went wrong getting the current conditions. Halting.')
        return 1

    wf.write_text(os.path.join(data['output_dir'], 'current_conditions.txt'),
                  text_conditions)

    # Get radar image:
    current_radar = Radar(data)
    current_radar.check_assets()
    current_radar.get_radar()
    current_radar.get_warnings_box()
    if current_radar.problem:
        logging.error('Unable to retrieve weather radar image. Halting now.')

    # Hazardous Weather Outlook and alerts:
    today_alerts = Alerts(data)
    today_alerts.get_alerts()

    # Get hydrograph image.
    if wf.get_hydrograph(abbr=data['river_gauge_abbr'],
                         hydro_url=data['defaults']['water_url'],
                         outputdir=data['output_dir']).ok:
        logging.info('Requesting hydrograph for station %s, gauge "%s".',
                     data['radar_station'], data['river_gauge_abbr'])
    else:
        logging.error('Failed to get hydrograph information.')
        return 1

    forecast_obj = Forecast(data=data)
    logging.debug('Getting the forecasts.')
    forecast_obj.get_forecast()
    forecastdict = forecast_obj.parse_forecast()
    if forecastdict is None:
        logging.error('Unable to parse forecast!')
        return 1
    forecast_obj.write_forecast(outputdir=data['output_dir'])
    logging.debug('Getting area forecast discussion.')
    forecast_obj.get_afd()

    logging.debug('Getting zone forecast.')
    zoneforecast = ZoneForecast(data)
    zoneforecast.get()

    wf.write_json(some_dict=forecastdict,
                  outputdir=data['output_dir'],
                  filename='forecast.json')
    wsvg.make_forecast_icons(forecastdict, outputdir=data['output_dir'])

    # Satellite imagery:
    current_image = Imagery(band='GEOCOLOR', data=data)
    current_image.get_all()

    logging.info('Finished program run.')

    return 0
Ejemplo n.º 32
0
    def __init__(self, fullname: str, version: str, description: str,
                 shortname: str):
        """
        :param fullname: program name
        :param version: program version
        :param description: short description
        :param shortname: short name, mainly for logs
        """

        self.NAME = fullname
        self.SHORTNAME = shortname
        self.VERSION = version
        self.DESCRIPTION = description

        self.STATION_NAME = None
        self.ELEVATION = None
        self.P_INITIAL = None

        self.start_console()

        # starts logging
        self.LOG_FILENAME = self.SHORTNAME + ".log"
        logging.basicConfig(
            filename=self.LOG_FILENAME,
            level=logging.INFO,
            filemode="w",
            format="%(asctime)s %(levelname)s : %(message)s",
            datefmt="%Y-%m-%d %H:%M",
        )

        self.result = PredictionTable()
        self.forecast = Forecast()
        self.slack = slack.WebClient(token=environ["SLACK_API_TOKEN"])

        # reads configuration file and recreates missing values
        self.CONFIG_FILENAME = "config.ini"
        self.CS = "USER SETTINGS"
        self.cfg = ConfigParser()
        self.cfg.read(self.CONFIG_FILENAME)

        if self.CS not in self.cfg.sections():
            print80(_("Regenerating {}").format(self.CONFIG_FILENAME))
            print()
            self.cfg.add_section(self.CS)

        self.TIMEOUT_T = "short timeout"
        self.TIMEOUT = int(self.cfg.get(self.CS, self.TIMEOUT_T, fallback="5"))

        self.TIMEOUT_LONG_T = "long timeout"
        self.TIMEOUT_LONG = int(
            self.cfg.get(self.CS, self.TIMEOUT_LONG_T, fallback="10"))

        self.GEOLOCATION_ALWAYS_ON_T = "geolocation always on"
        self.GEOLOCATION_ALWAYS_ON = bool(
            int(
                self.cfg.get(self.CS,
                             self.GEOLOCATION_ALWAYS_ON_T,
                             fallback="0")))

        self.WAIT_FOR_KEY_T = "press any key"
        self.WAIT_FOR_KEY = bool(
            int(self.cfg.get(self.CS, self.WAIT_FOR_KEY_T, fallback="1")))
        self.PAUSE = (not args.no_key) and self.WAIT_FOR_KEY

        self.OVERRIDE_URL_T = "override url"
        self.OVERRIDE_URL_ = self.cfg.get(self.CS,
                                          self.OVERRIDE_URL_T,
                                          fallback="")
        if args.override_url is not None:
            self.OVERRIDE_URL = args.override_url
        else:
            self.OVERRIDE_URL = self.OVERRIDE_URL_

        self.OVERRIDE_URL_EXISTS = self.OVERRIDE_URL is not None and self.OVERRIDE_URL.startswith(
            "https://www.wunderground.com/hourly/")

        self.ANY_HTTPS_PAGE_T = "https page"
        self.ANY_HTTPS_PAGE = self.cfg.get(self.CS,
                                           self.ANY_HTTPS_PAGE_T,
                                           fallback="https://blank.org")

        self.GEOLOCATED_URL_T = "wunderground hourly url"
        self.GEOLOCATED_URL = self.cfg.get(
            self.CS,
            self.GEOLOCATED_URL_T,
            fallback="https://www.wunderground.com/hourly/ca/location/",
        )

        self.GRAPH_FILENAME_T = "autosave png-pdf-eps filename"
        self.GRAPH_FILENAME = self.cfg.get(self.CS,
                                           self.GRAPH_FILENAME_T,
                                           fallback="graph.png")

        self.GRAPH_DPI_T = "autosave dpi"
        self.GRAPH_DPI = int(
            self.cfg.get(self.CS, self.GRAPH_DPI_T, fallback="600"))

        self.GRAPH_ORIENTATION_T = "autosave orientation"
        self.GRAPH_ORIENTATION = self.cfg.get(self.CS,
                                              self.GRAPH_ORIENTATION_T,
                                              fallback="landscape")

        self.GRAPH_PAPERTYPE_T = "autosave papertype"
        self.GRAPH_PAPERTYPE = self.cfg.get(self.CS,
                                            self.GRAPH_PAPERTYPE_T,
                                            fallback="letter")

        self.VERBOSE_T = "verbose"
        self.VERBOSE_ = bool(
            int(self.cfg.get(self.CS, self.VERBOSE_T, fallback="0")))
        self.VERBOSE = self.VERBOSE_ or args.verbose

        self.SHOW_X_HOURS_T = "display x hours"
        self.SHOW_X_HOURS = max(
            int(self.cfg.get(self.CS, self.SHOW_X_HOURS_T, fallback="6")), 1)

        self.MIN_HOURS_T = "minimum hours"
        self.MIN_HOURS = max(
            int(self.cfg.get(self.CS, self.MIN_HOURS_T, fallback="8")),
            self.SHOW_X_HOURS,
        )

        self.save_ini()  # save immediately to renew all required values

        # optional values that can be missing
        self.LATITUDE_T = "latitude"
        self.LONGITUDE_T = "longitude"
        self.LATITUDE = None
        self.LONGITUDE = None

        if args.latitude is not None:
            self.LATITUDE = args.latitude
        elif self.cfg.has_option(self.CS, self.LATITUDE_T):
            self.LATITUDE = float(self.cfg.get(self.CS, self.LATITUDE_T))

        if args.longitude is not None:
            self.LONGITUDE = args.longitude
        elif self.cfg.has_option(self.CS, self.LONGITUDE_T):
            self.LONGITUDE = float(self.cfg.get(self.CS, self.LONGITUDE_T))

        self.MISSING_LATLONG = self.LATITUDE is None or self.LONGITUDE is None

        self.browser = ChromeBrowser()
Ejemplo n.º 33
0
def _forecast(net, temp):
    return None if net is None else Forecast(net, temp)
Ejemplo n.º 34
0
from forecast import Forecast, dictobj


if __name__ == '__main__':

    f = Forecast('3c70d6ecf5e1fdb93b6fbaed616daec6',47.5,19.05)
    cur_weather = f.get_cur_weather()
    o = dictobj(cur_weather)
    for i in o.currently:
        print (i, o.currently[i])
Ejemplo n.º 35
0
    time.sleep_ms(1000)
    now = time.ticks_ms()
    while True:
      if wifi.ifconfig()[0] != '0.0.0.0':
        print("Connected, IP: {}".format(wifi.ifconfig()[0]))
        break
      if time.ticks_ms() - now > timeout:
        break
  return wifi

wifi = init_wifi("signalhuset", "signal+huset2017")
# wifi = init_wifi("HomeBox-10E0_5G", "a6cfdf567")
# wifi = init_wifi("AndroidAPAD82", "odon3187")

status, header, data = curl.get('api.openweathermap.org/data/2.5/onecall?lat=55.6761&lon=12.5683&exclude=minutely,hourly,current&&units=metric&appid=4641ad3e90202b3e5b93bb82490ca04f')
weather = Forecast(json.loads(data)['daily'])

servo = machine.PWM(machine.Pin(17), freq=50)
pin_r = machine.PWM(machine.Pin(27))
pin_g = machine.PWM(machine.Pin(26))
pin_b = machine.PWM(machine.Pin(25))

def on_data(temp):
    print(temp[2])
    today = json.loads(data)['daily'][0]['weather'][0]
    print(today['main'])
    if today['main'] == 'Clear':
        servo.duty(7)
    elif today['main'] == 'Clouds':
        servo.duty(11)
    elif today['main'] == 'Rain':
Ejemplo n.º 36
0
# import libraries
from argument_parser import args
try:
    from config import app_id, default_country_code
except ImportError as import_error:
    print("An error ocurred while trying to import the config file: ")
    print(import_error)

from forecast import Forecast

country_code = default_country_code
if args.country is not None:
    country_code = args.country

weather = Forecast(args.city, country_code, app_id)
weather.get_tomorrow()
Ejemplo n.º 37
0
def main(cla):

    # Load the user-defined settings, and script settings
    # ----------------------------------------------------
    user_config = cla.user_config

    print(f"user config: {user_config}")
    script_config = cla.script_config
    print(f"script config: {script_config}")
    if not script_config:
        ushdir = os.path.join(user_config['paths']['homerrfs'], 'configs')
        script_config = checks.load_config_file(
            os.path.join(ushdir, 'fv3_script.yml'))

    # Update script config with user-supplied config file
    # ----------------------------------------------------
    utils.update_dict(script_config, user_config, quiet=cla.quiet)

    # Create Namespace of config for easier syntax
    # ---------------------------------------------
    config = argparse.Namespace()
    utils.namespace(config, script_config)

    # Now config and script_config contain identical information in Namespace
    # and dict formats, respectively.

    # Load each of the standard YAML config files
    # --------------------------------------------
    #
    # Reminder:
    # checks.load_config_section(arg) takes a two-element list as it's input.
    #    arg = [file_name, section_name(s)]
    #
    grid = cla.grid_config
    if not grid:
        grid = checks.load_config_section([
            config.paths.grid.format(n=config),
            [config.grid_name, config.grid_gen_method],
        ])

    machine = cla.machine_config
    if not machine:
        machine_path = config.paths.machine.format(n=config)
        machine = checks.load_config_section([
            machine_path,
            config.machine,
        ])

    namelist = cla.nml_config
    if not namelist:
        namelist = checks.load_config_section([
            config.paths.namelist.format(n=config),
            config.phys_pkg,
        ])

    # Update each of the provided configure files with user-supplied settings
    # ------------------------------------------------------------------------
    for cfg in ['grid', 'machine', 'namelist']:
        utils.update_dict(locals()[cfg][0],
                          script_config.get(cfg),
                          quiet=cla.quiet)

    # Set up a kwargs dict for Forecast object
    # -----------------------------------------
    fcst_kwargs = {
        'grid': grid[0],
        'nml': namelist[0],
        'overwrite': cla.overwrite,
    }

    # Create the Forecast object
    # ---------------------------
    fcst = Forecast(
        config=script_config,
        machine=machine[0],
        starttime=cla.start_date,
        **fcst_kwargs,
    )

    # Run the forecast job
    # ---------------------
    fcst.run(dry_run=cla.dry_run)
    def run(self,
            community_config,
            global_config=None,
            tag='',
            scalers=None,
            alt_save_name=None):
        """
        run the model for a community
        
        inputs:
            community: the community <string>
            c_config: (optional, default: none) alternate community config 
                file <string>
            g_config: (optional, default: none) alternat global confing 
                file <string>
            tag: (optional) tag for results dir <string>
            
        outputs:
            the model is run for a community/project/assigned 'name'
            
        preconditions:
            see invariants
            
        postconditions:
            None
        """
        #~ print community_config

        if scalers is None:
            scalers = default_scalers

        #~ if name is None:
        #~ name = community

        temp = tag
        #~ if img_dir is None:
        #~ if temp != '':
        #~ temp = '_' + tag
        #~ img_dir = os.path.join(self.model_root, 'results' + temp, 'plots')

        #~ cd, fc, diag = self.setup_community(community, i_dir, c_config,
        #~ g_config, c_mult, scalers)

        diagnostics = Diagnostics()
        community_data = CommunityData(community_config, global_config,
                                       diagnostics, scalers)
        name = community_data.get_item('community', 'file id')
        #~ print name
        forecast = Forecast(community_data, diagnostics, scalers)

        comps_used = self.run_components(community_data, forecast, diagnostics,
                                         scalers)

        #~ name = community_data.get_item('community', 'file id')
        self.save_components_output(comps_used,
                                    name,
                                    forecast,
                                    tag,
                                    alt_name=alt_save_name)
        #~ self.save_forecast_output(forecast, name, img_dir, plot, tag)
        self.save_input_files(community_data,
                              name,
                              tag,
                              alt_name=alt_save_name)
        self.save_diagnostics(diagnostics, name, tag, alt_name=alt_save_name)

        comps_used['community data'] = community_data
        comps_used['forecast'] = forecast

        #~ print name
        #~ print 'rb', alt_save_name
        self.store_results(comps_used, tag, name=alt_save_name)
Ejemplo n.º 39
0
from forecast import Forecast
import matplotlib.pyplot as plot
import seaborn
import pandas
import numpy

atlanta = Forecast()

#weather.clean_tmy('../data/lafayette.CSV')
atlanta.load_tmy('../data/atlanta_clean.csv')
atlanta.simulation_time = '07/01/1900 08:00'

#weather.add_predictor('GHI (W/m^2)').add_predictor('DNI (W/m^2)')
atlanta.add_predictor('Dry-bulb (C)').add_predictor('Dew-point (C)')

# now let's look at colorado:
golden = Forecast()
golden.load_tmy('../data/golden_clean.csv')
golden.simulation_time = '07/01/1900 08:00'

#weather.add_predictor('GHI (W/m^2)').add_predictor('DNI (W/m^2)')
golden.add_predictor('Dry-bulb (C)').add_predictor('Dew-point (C)')

"""
# Grab predictions for 10, 50 and 100 scenarios:
predictions, test = weather.auto_regressive(24, 10)
print('...predictions succeeded, now plotting...')

stuff = test[weather.predictor_variables[0]].T
junk = test[weather.predictor_variables[1]].T
Ejemplo n.º 40
0
class Peppyweather(Container, ScreensaverWeather):
    """ Main PeppyWeather class """
    def __init__(self, util=None):
        """ Initializer
        
        :param util: utility object
        """
        ScreensaverWeather.__init__(self)
        self.config = None
        self.set_util(util)
        self.update_period = self.util.weather_config[UPDATE_PERIOD]
        self.name = "peppyweather"

        if self.util.weather_config[USE_LOGGING]:
            logging.basicConfig(level=logging.NOTSET)
        else:
            logging.disable(logging.CRITICAL)

        if self.config != None:
            self.rect = util.screen_rect
            self.util.weather_config["screen.rect"] = util.screen_rect
        else:
            self.init_display()
            self.rect = self.util.weather_config["screen.rect"]

        plugin_folder = type(self).__name__.lower()
        images_folder = os.path.join(PACKAGE_SCREENSAVER, plugin_folder,
                                     DEFAULT_IMAGES_FOLDER)
        self.images = util.load_background_images(images_folder)
        self.indexes = cycle(range(len(self.images)))

        Container.__init__(self, self.util, self.rect, BLACK)

    def set_util(self, util):
        """ Set utility object
        
        :param util: external utility object
        """
        self.config = util.config
        self.util = WeatherUtil(util.k3, util.k4, util.k5)
        self.util.weather_config = util.weather_config
        path = os.path.join(os.getcwd(), SCREENSAVER, WEATHER)
        self.util.weather_config[BASE_PATH] = path
        self.util.pygame_screen = util.pygame_screen
        self.rect = util.screen_rect
        self.util.weather_config["screen.rect"] = self.rect
        self.util.get_font = util.get_font

    def init_display(self):
        """ Initialize display. Called if running stand-alone """

        screen_w = self.util.weather_config[SCREEN_INFO][WIDTH]
        screen_h = self.util.weather_config[SCREEN_INFO][HEIGHT]

        os.environ["SDL_FBDEV"] = "/dev/fb1"
        os.environ["SDL_MOUSEDEV"] = "/dev/input/touchscreen"
        os.environ["SDL_MOUSEDRV"] = "TSLIB"

        if "win" not in sys.platform:
            pygame.display.init()
            pygame.mouse.set_visible(False)
        else:
            pygame.init()
            pygame.display.set_caption("PeppyWeather")

        self.util.pygame_screen = pygame.display.set_mode((screen_w, screen_h))
        self.util.weather_config["screen.rect"] = pygame.Rect(
            0, 0, screen_w, screen_h)

    def set_weather(self):
        """ Reads weather data and sets it in UI classes """

        self.util.set_url()
        weather = self.util.load_json()

        dark_light = self.util.weather_config[COLOR_DARK_LIGHT]
        semi_transparent_color = (dark_light[0], dark_light[1], dark_light[2],
                                  210)

        self.today = Today(self.util, self.images[0], semi_transparent_color)
        self.today.set_weather(weather)
        self.today.draw_weather()
        self.today.set_visible(False)

        self.forecast = Forecast(self.util, self.images[1],
                                 semi_transparent_color)
        self.forecast.set_weather(weather)
        self.forecast.draw_weather()
        self.forecast.set_visible(True)

        self.add_component(self.today)
        self.add_component(self.forecast)

    def start(self):
        """ Start PeppyWeather screensaver """

        self.set_weather()
        self.clean_draw_update()
        pygame.event.clear()

    def start_standalone(self):
        """ Start PeppyWeather as a stand-alone app """

        self.start()
        count = 0
        delay = 0.2
        cycles = int(self.update_period / 0.2)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.exit()
                elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    keys = pygame.key.get_pressed()
                    if (keys[pygame.K_LCTRL] or
                            keys[pygame.K_RCTRL]) and event.key == pygame.K_c:
                        self.exit()

            count += 1

            if count >= cycles:
                self.refresh()
                count = 0

            time.sleep(0.2)

    def refresh(self):
        """ Refresh PeppyWeather. Used to switch between Today and Forecast screens. """

        i = next(self.indexes)
        image = self.images[i]

        if self.today.visible == True:
            self.today.set_visible(False)
            self.forecast.components[0].content = image
            self.forecast.set_visible(True)
        else:
            self.today.components[0].content = image
            self.today.set_visible(True)
            self.forecast.set_visible(False)

        self.clean_draw_update()

    def exit(self):
        """ Exit program """

        pygame.quit()
        os._exit(0)
Ejemplo n.º 41
0
def main():
    print(Forecast(sys.argv[1]).as_json())
Ejemplo n.º 42
0
                  'var': 'Temperature_height_above_ground',
                  'is_ensemble': False},
          'HRRR': {'name': 'NCEP HRRR CONUS 2.5km',
                   'var': 'Temperature_height_above_ground',
                   'is_ensemble': False},
          'NAM': {'name': 'NAM CONUS 12km from NOAAPORT',
                  'var': 'Temperature_height_above_ground',
                  'is_ensemble': False}}

for model in models:
    model_dataset = get_model_dataset(models[model]['name'])
    model_temp = retrieve_point_forecast(model_dataset,
                                         point.lat,
                                         point.lon,
                                         models[model]['var'],
                                         models[model]['is_ensemble'])

    if models[model]['is_ensemble']:
        for i, ens_temp in enumerate(model_temp):
            ens_forecast = Forecast(point.name, point.lat, point.lon,
                                    var='2m Temperature',
                                    source=models[model]['name'] + ' ' + str(i),
                                    series=ens_temp)
            ens_forecast.write_to_db()
    else:
        forecast = Forecast(point.name, point.lat, point.lon,
                            var='2m Temperature',
                            source=models[model]['name'],
                            series=model_temp)
        forecast.write_to_db()
Ejemplo n.º 43
0
 def test_parse_forecast(self):
     actual_forecast = dict(
         parse_forecast(read_file('./test/fixtures/sangre.html')))
     expected_forecast = dict(
         Forecast.from_json(read_file('./test/fixtures/sangre.json')))
     self.assertEqual(expected_forecast, actual_forecast)