Returns the precipitation time series relative to the
        meteostation, in the form of a list of tuples, each one containing the
        couple timestamp-value

        :returns: a list of tuples
559254
def rain_series(self):
        
        return [(tstamp, \
                self._station_history.get_measurements()[tstamp]['rain']) \
                for tstamp in self._station_history.get_measurements()]
872446
def query_timeseries(self, query, from_time=None, to_time=None, by_post=False):
    
    return timeseries.query_timeseries(self, query, from_time, to_time, by_post=by_post)
630273
def to_dict(self):
        
        return {
            'station_id': self.station_id,
            'timestamp': self.timestamp,
            'temperature': self.temperature,
            'wind_speed': self.wind_speed,
            'wind_gust': self.wind_gust,
            'wind_deg': self.wind_deg,
            'pressure': self.pressure,
            'humidity': self.humidity,
            'rain_1h': self.rain_1h,
            'rain_6h': self.rain_6h,
            'rain_24h': self.rain_24h,
            'snow_1h': self.snow_1h,
            'snow_6h': self.snow_6h,
            'snow_24h': self.snow_24h,
            'dew_point': self.dew_point,
            'humidex': self.humidex,
            'heat_index': self.heat_index,
            'visibility_distance': self.visibility_distance,
            'visibility_prefix': self.visibility_prefix,
            'clouds_distance': self.clouds_distance,
            'clouds_condition': self.clouds_condition,
            'clouds_cumulus': self.clouds_cumulus,
            'weather_precipitation': self.weather_precipitation,
            'weather_descriptor': self.weather_descriptor,
            'weather_intensity': self.weather_intensity,
            'weather_proximity': self.weather_proximity,
            'weather_obscuration': self.weather_obscuration,
            'weather_other': self.weather_other}
825541
def get_forecast(self) -> List[SmhiForecast]:
        
        json_data = self._api.get_forecast_api(self._longitude, self._latitude)
        return _get_forecast(json_data)
562081
def getTimestampUTC():
    
    utc     = datetime.datetime.utcnow()
    ts_sec  = calendar.timegm( utc.timetuple() )
    ts_usec = utc.microsecond
    return ts_sec, ts_usec
1191665
def _format_return_timestamps(self, return_timestamps=None):
        
        if return_timestamps is None:
            # Build based upon model file Start, Stop times and Saveper
            # Vensim's standard is to expect that the data set includes the `final time`,
            # so we have to add an extra period to make sure we get that value in what
            # numpy's `arange` gives us.
            return_timestamps_array = np.arange(
                self.components.initial_time(),
                self.components.final_time() + self.components.saveper(),
                self.components.saveper(), dtype=np.float64
            )
        elif inspect.isclass(range) and isinstance(return_timestamps, range):
            return_timestamps_array = np.array(return_timestamps, ndmin=1)
        elif isinstance(return_timestamps, (list, int, float, np.ndarray)):
            return_timestamps_array = np.array(return_timestamps, ndmin=1)
        elif isinstance(return_timestamps, _pd.Series):
            return_timestamps_array = return_timestamps.as_matrix()
        else:
            raise TypeError('`return_timestamps` expects a list, array, pandas Series, '
                            'or numeric value')
        return return_timestamps_array
1358250
def fetch_raw_data(sql, connection, geometry):
    
    tmp_dc = {}
    weather_df = pd.DataFrame(
        connection.execute(sql).fetchall(), columns=[
            'gid', 'geom_point', 'geom_polygon', 'data_id', 'time_series',
            'dat_id', 'type_id', 'type', 'height', 'year', 'leap_year']).drop(
        'dat_id', 1)

    # Get the timezone of the geometry
    tz = tools.tz_from_geom(connection, geometry)

    for ix in weather_df.index:
        # Convert the point of the weather location to a shapely object
        weather_df.loc[ix, 'geom_point'] = wkt_loads(
            weather_df['geom_point'][ix])

        # Roll the dataset forward according to the timezone, because the
        # dataset is based on utc (Berlin +1, Kiev +2, London +0)
        utc = timezone('utc')
        offset = int(utc.localize(datetime(2002, 1, 1)).astimezone(
            timezone(tz)).strftime("%z")[:-2])

        # Get the year and the length of the data array
        db_year = weather_df.loc[ix, 'year']
        db_len = len(weather_df['time_series'][ix])

        # Set absolute time index for the data sets to avoid errors.
        tmp_dc[ix] = pd.Series(
            np.roll(np.array(weather_df['time_series'][ix]), offset),
            index=pd.date_range(pd.datetime(db_year, 1, 1, 0),
                                periods=db_len, freq='H', tz=tz))
    weather_df['time_series'] = pd.Series(tmp_dc)
    return weather_df
900705
def get_results(self, stream, time_interval):
        
        return [StreamInstance(t, self.data[stream.stream_id][t])
                for t in sorted(self.data[stream.stream_id]) if t in time_interval]
441877
def util_granulate_time_series(time_series, scale):
    
    n = len(time_series)
    b = int(np.fix(n / scale))
    temp = np.reshape(time_series[0:b*scale], (b, scale))
    cts = np.mean(temp, axis = 1)
    return cts
1140593
def date_to_timestamp(date):
    
    date_tuple = date.timetuple()
    timestamp = calendar.timegm(date_tuple) * 1000
    return timestamp
1055940
def group_by_day(self):
        
        data_by_day = OrderedDict()
        for d in xrange(1, 366):
            data_by_day[d] = []
        for v, dt in zip(self._values, self.datetimes):
            data_by_day[dt.doy].append(v)
        return data_by_day
83082
def taf(trans: TafLineTrans) -> str:
    
    summary = []
    if trans.wind:
        summary.append('Winds ' + trans.wind)
    if trans.visibility:
        summary.append('Vis ' + trans.visibility[:trans.visibility.find(' (')].lower())
    if trans.altimeter:
        summary.append('Alt ' + trans.altimeter[:trans.altimeter.find(' (')])
    if trans.other:
        summary.append(trans.other)
    if trans.clouds:
        summary.append(trans.clouds.replace(' - Reported AGL', ''))
    if trans.wind_shear:
        summary.append(trans.wind_shear)
    if trans.turbulance:
        summary.append(trans.turbulance)
    if trans.icing:
        summary.append(trans.icing)
    return ', '.join(summary)
535449
def _get_all_forecast_from_api(api_result: dict) -> OrderedDict:
    """"""
    # Total time in hours since last forecast
    total_hours_last_forecast = 1.0

    # Last forecast time
    last_time = None

    # Need the ordered dict to get
    # the days in order in next stage
    forecasts_ordered = OrderedDict()

    # Get the parameters
    for forecast in api_result['timeSeries']:

        valid_time = datetime.strptime(
            forecast['validTime'], "%Y-%m-%dT%H:%M:%SZ")
        for param in forecast['parameters']:
            if param['name'] == 't':
                temperature = float(param['values'][0])  # Celcisus
            elif param['name'] == 'r':
                humidity = int(param['values'][0])  # Percent
            elif param['name'] == 'msl':
                pressure = int(param['values'][0])  # hPa
            elif param['name'] == 'tstm':
                thunder = int(param['values'][0])  # Percent
            elif param['name'] == 'tcc_mean':
                octa = int(param['values'][0])  # Cloudiness in octas
                if 0 <= octa <= 8:  # Between 0 -> 8
                    cloudiness = round(100*octa/8)  # Convert octas to percent
                else:
                    cloudiness = 100  # If not determined use 100%
            elif param['name'] == 'Wsymb2':
                symbol = int(param['values'][0])  # category
            elif param['name'] == 'pcat':
                precipitation = int(param['values'][0])  # percipitation
            elif param['name'] == 'pmean':
                mean_precipitation = float(
                    param['values'][0])  # mean_percipitation
            elif param['name'] == 'ws':
                wind_speed = float(param['values'][0])  # wind speed
            elif param['name'] == 'wd':
                wind_direction = int(param['values'][0])  # wind direction
            elif param['name'] == 'vis':
                horizontal_visibility = float(param['values'][0])  # Visibility
            elif param['name'] == 'gust':
                wind_gust = float(param['values'][0])  # wind gust speed

        roundedTemp = int(round(temperature))

        if last_time is not None:
            total_hours_last_forecast = (valid_time - last_time).seconds/60/60

        # Total precipitation, have to calculate with the nr of
        # hours since last forecast to get correct total value
        tp = round(mean_precipitation*total_hours_last_forecast, 2)

        forecast = \
            SmhiForecast(roundedTemp, roundedTemp, roundedTemp,
                         humidity, pressure, thunder, cloudiness,
                         precipitation, wind_direction, wind_speed,
                         horizontal_visibility, wind_gust,
                         round(mean_precipitation, 1), tp, symbol,
                         valid_time)

        if valid_time.day not in forecasts_ordered:
            # add a new list
            forecasts_ordered[valid_time.day] = []

        forecasts_ordered[valid_time.day].append(forecast)

        last_time = valid_time

    return forecasts_ordered
1192681
def load_forecasts(self):
        
        run_date_str = self.run_date.strftime("%Y%m%d")
        for model_name in self.model_names:
            self.raw_forecasts[model_name] = {}
            forecast_file = self.forecast_path + run_date_str + "/" + \
                model_name.replace(" ", "-") + "_hailprobs_{0}_{1}.nc".format(self.ensemble_member, run_date_str)
            forecast_obj = Dataset(forecast_file)
            forecast_hours = forecast_obj.variables["forecast_hour"][:]
            valid_hour_indices = np.where((self.start_hour <= forecast_hours) & (forecast_hours <= self.end_hour))[0]
            for size_threshold in self.size_thresholds:
                self.raw_forecasts[model_name][size_threshold] = \
                    forecast_obj.variables["prob_hail_{0:02d}_mm".format(size_threshold)][valid_hour_indices]
            forecast_obj.close()
1268887
def metar(trans: MetarTrans) -> str:
    
    summary = []
    if trans.wind:
        summary.append('Winds ' + trans.wind)
    if trans.visibility:
        summary.append('Vis ' + trans.visibility[:trans.visibility.find(' (')].lower())
    if trans.temperature:
        summary.append('Temp ' + trans.temperature[:trans.temperature.find(' (')])
    if trans.dewpoint:
        summary.append('Dew ' + trans.dewpoint[:trans.dewpoint.find(' (')])
    if trans.altimeter:
        summary.append('Alt ' + trans.altimeter[:trans.altimeter.find(' (')])
    if trans.other:
        summary.append(trans.other)
    if trans.clouds:
        summary.append(trans.clouds.replace(' - Reported AGL', ''))
    return ', '.join(summary)
1017217
def to_JSON(self):
        
        last = None
        if self._last_weather:
            last = self._last_weather.to_JSON()
        return json.dumps({'name': self._name,
                           'station_ID': self._station_ID,
                           'station_type': self._station_type,
                           'status': self._status,
                           'lat': self._lat,
                           'lon': self._lon,
                           'distance': self._distance,
                           'weather': json.loads(last),
                           })
180362
def _load(self, time_series):
        
        if isinstance(time_series, TimeSeries):
            return time_series
        if isinstance(time_series, dict):
            return TimeSeries(time_series)
        return TimeSeries(utils.read_csv(time_series))