def test_get_aggregate_expression(self): """Test using an expression in an aggregate""" with weewx.manager.open_manager_with_config( self.config_dict, 'wx_binding') as db_manager: month_start_tt = (2010, 7, 1, 0, 0, 0, 0, 0, -1) month_stop_tt = (2010, 8, 1, 0, 0, 0, 0, 0, -1) start_ts = time.mktime(month_start_tt) stop_ts = time.mktime(month_stop_tt) # This one is a valid expression: value = weewx.xtypes.get_aggregate('rain-ET', TimeSpan(start_ts, stop_ts), 'sum', db_manager) self.assertAlmostEqual(value[0], 2.94, 2) # This one uses a nonsense variable: with self.assertRaises(weewx.UnknownAggregation): value = weewx.xtypes.get_aggregate('rain-foo', TimeSpan(start_ts, stop_ts), 'sum', db_manager) # A valid function value = weewx.xtypes.get_aggregate('max(rain-ET, 0)', TimeSpan(start_ts, stop_ts), 'sum', db_manager) self.assertAlmostEqual(value[0], 9.57, 2) # This one uses a nonsense function with self.assertRaises(weedb.OperationalError): value = weewx.xtypes.get_aggregate('foo(rain-ET)', TimeSpan(start_ts, stop_ts), 'sum', db_manager)
def test_get_aggregate_heatcool(self): with weewx.manager.open_manager_with_config( self.config_dict, 'wx_binding') as db_manager: month_start_tt = (2010, 3, 1, 0, 0, 0, 0, 0, -1) month_stop_tt = (2010, 4, 1, 0, 0, 0, 0, 0, -1) start_ts = time.mktime(month_start_tt) stop_ts = time.mktime(month_stop_tt) # First, with the default heating base: heatdeg = weewx.xtypes.AggregateHeatCool.get_aggregate( 'heatdeg', TimeSpan(start_ts, stop_ts), 'sum', db_manager) self.assertAlmostEqual(heatdeg[0], 1123.12, 2) # Now with an explicit heating base: heatdeg = weewx.xtypes.AggregateHeatCool.get_aggregate( 'heatdeg', TimeSpan(start_ts, stop_ts), 'sum', db_manager, skin_dict={ 'Units': { 'DegreeDays': { 'heating_base': (60.0, "degree_F", "group_temperature") } } }) self.assertAlmostEqual(heatdeg[0], 968.12, 2)
def test_rainYearSpan(self): os.environ['TZ'] = 'America/Los_Angeles' self.assertEqual( archiveRainYearSpan( time.mktime((2007, 2, 13, 10, 15, 0, 0, 0, -1)), 10), TimeSpan(time.mktime((2006, 10, 1, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 10, 1, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveRainYearSpan( time.mktime((2007, 12, 13, 10, 15, 0, 0, 0, -1)), 10), TimeSpan(time.mktime((2007, 10, 1, 0, 0, 0, 0, 0, -1)), time.mktime((2008, 10, 1, 0, 0, 0, 0, 0, -1))))
def get_extension_list(self, timespan, db_lookup): """Returns a search list extension with additions. timespan: An instance of weeutil.weeutil.TimeSpan. This holds the start and stop times of the domain of valid times. db_lookup: Function that returns a database manager given a data binding. """ # First, create a TimespanBinder object for all time. This one is easy # because the object timespan already holds all valid times to be # used in the report. all_stats = TimespanBinder(timespan, db_lookup, context='alltime', formatter=self.generator.formatter, converter=self.generator.converter) # Now create a TimespanBinder for the last seven days. This one we # will have to calculate. First, calculate the time at midnight, seven # days ago. The variable week_dt will be an instance of datetime.date. week_dt = datetime.date.fromtimestamp( timespan.stop) - datetime.timedelta(weeks=1) # Now convert it to unix epoch time: week_ts = time.mktime(week_dt.timetuple()) # Now form a TimeSpanStats object, using the time span just calculated: seven_day_stats = TimespanBinder(TimeSpan(week_ts, timespan.stop), db_lookup, context='seven_day', formatter=self.generator.formatter, converter=self.generator.converter) # Now use a similar process to get statistics for the last 30 days. days_dt = datetime.date.fromtimestamp( timespan.stop) - datetime.timedelta(days=30) days_ts = time.mktime(days_dt.timetuple()) thirty_day_stats = TimespanBinder(TimeSpan(days_ts, timespan.stop), db_lookup, context='thirty_day', formatter=self.generator.formatter, converter=self.generator.converter) return [{ 'alltime': all_stats, 'seven_day': seven_day_stats, 'thirty_day': thirty_day_stats }]
def test_last_wind(self): """Test getting the last non-null wind record in a time range.""" with weewx.manager.open_manager_with_config( self.config_dict, 'wx_binding') as db_manager: # Get the last value for 18-Apr-2010. This date was chosen because the wind speed of # the very last record of the day (at 19-Apr-2010 00:00:00) is actually null, so the # previous value (at 18-Apr-2010 23:30:00) should be the one chosen. day_start_tt = (2010, 4, 18, 0, 0, 0, 0, 0, -1) day_stop_tt = (2010, 4, 19, 0, 0, 0, 0, 0, -1) start_ts = time.mktime(day_start_tt) stop_ts = time.mktime(day_stop_tt) # Check the premise of the test, as well as get the expected results results = [ x for x in db_manager.genSql( "SELECT windSpeed, windDir FROM archive " "WHERE dateTime <= ? " "ORDER BY dateTime DESC LIMIT 2", (stop_ts, )) ] # We expect the first record (which is the last record of the day) to be null self.assertIsNone(results[0][0]) # This is the expected value: the 2nd record windSpeed, windDir = results[1] expected = complex( windSpeed * math.cos(math.radians(90.0 - windDir)), windSpeed * math.sin(math.radians(90.0 - windDir))) value = weewx.xtypes.WindVec.get_aggregate( 'windvec', TimeSpan(start_ts, stop_ts), 'last', db_manager) self.assertAlmostEqual(value[0], expected) self.assertEqual(value[1], 'mile_per_hour') self.assertEqual(value[2], 'group_speed')
def test_Accum_getRecord(self): """Test extraction of record from an accumulator.""" accum = weewx.accum.Accum(TimeSpan(start_ts, stop_ts)) for record in self.dataset: accum.addRecord(record) extracted = accum.getRecord() self.assertEqual(extracted['dateTime'], self.dataset[-1]['dateTime']) self.assertEqual(extracted['usUnits'], weewx.US) sum_t = 0 count_t = 0 for rec in self.dataset: if rec['outTemp'] is not None: sum_t += rec['outTemp'] count_t += 1 self.assertEqual(extracted['outTemp'], sum_t / count_t) max_wind = 0 max_dir = None for rec in self.dataset: if rec['windGust'] is not None and rec['windGust'] > max_wind: max_wind = rec['windGust'] max_dir = rec['windGustDir'] self.assertEqual(extracted['windGust'], max_wind) self.assertEqual(extracted['windGustDir'], max_dir) rain_sum = 0 for rec in self.dataset: if rec['rain'] is not None: rain_sum += rec['rain'] self.assertEqual(extracted['rain'], rain_sum)
def test_weekSpan(self): os.environ['TZ'] = 'America/Los_Angeles' self.assertEqual( archiveWeekSpan(time.mktime((2007, 12, 13, 10, 15, 0, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 9, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 16, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveWeekSpan(time.mktime((2007, 12, 9, 0, 0, 0, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 2, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 9, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveWeekSpan(time.mktime((2007, 12, 9, 0, 0, 1, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 9, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 16, 0, 0, 0, 0, 0, -1))))
def get_extension_list(self, timespan, db_lookup): # 3 """Returns a search list extension with two additions. Parameters: timespan: An instance of weeutil.weeutil.TimeSpan. This will hold the start and stop times of the domain of valid times. db_lookup: This is a function that, given a data binding as its only parameter, will return a database manager object. """ # Create a TimespanBinder object for the last seven days. First, calculate # the time at midnight, seven days ago. The variable week_dt will be an instance of # datetime.date. week_dt = datetime.date.fromtimestamp(timespan.stop) \ - datetime.timedelta(weeks=1) # 4 # Convert it to unix epoch time: week_ts = time.mktime(week_dt.timetuple()) # 5 # Form a TimespanBinder object, using the time span we just # calculated: seven_day_stats = TimespanBinder(TimeSpan(week_ts, timespan.stop), db_lookup, context='week', formatter=self.generator.formatter, converter=self.generator.converter, skin_dict=self.generator.skin_dict) # 6 # Now create a small dictionary with the key 'seven_day': search_list_extension = {'seven_day' : seven_day_stats} # 7 # Finally, return our extension as a list: return [search_list_extension] # 8
def daySpanTZ(tz, time_ts, grace=1, days_ago=0): """ Returns a TimeSpan representing a day in timezone tz that includes the given time.""" time_ts -= grace soy_ts = startOfYearTZ(time_ts, tz) sod_ts = startOfDayTZ(time_ts, soy_ts) - days_ago * 86400 return TimeSpan(sod_ts, sod_ts + 86400)
def test_issue_737(self): accum = weewx.accum.Accum(TimeSpan(start_ts, stop_ts)) for packet in self.dataset: packet['windrun'] = None accum.addRecord(packet) # Extract the record out of the accumulator record = accum.getRecord() self.assertIsNone(record['windrun'])
def test_series(self): """Check for calculating a series of vapor pressures.""" with weewx.manager.open_manager_with_config( self.config_dict, 'wx_binding') as db_manager: start_vec, stop_vec, data_vec = weewx.xtypes.get_series( 'vapor_p', TimeSpan(day_start_ts, day_stop_ts), db_manager) self.assertEqual([round(x, 4) for x in data_vec[0]], CommonTests.expected_vapor_p, 4)
def yearSpanTZ(tz, time_ts, grace=1, years_ago=0): """ Returns a TimeSpan representing a year in timezone tz that includes a given time.""" if time_ts is None: time_ts = time.time() time_ts -= grace soya_ts = startOfYearTZ(time_ts, tz) soye_ts = startOfYearTZ(soya_ts + 31968000, tz) return TimeSpan(int(soya_ts), int(soye_ts))
def test_get_series_archive_outTemp(self): """Test a series of outTemp with no aggregation""" with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: start_vec, stop_vec, data_vec = weewx.xtypes.get_series('outTemp', TimeSpan(start_ts, stop_ts), db_manager) self.assertEqual(len(start_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval) self.assertEqual(len(stop_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval) self.assertEqual(len(data_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval)
def test_get_series_archive_windvec(self): with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: # Get a series of wind values start_vec, stop_vec, data_vec = weewx.xtypes.get_series('windvec', TimeSpan(start_ts, stop_ts), db_manager) self.assertEqual(len(start_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval + 1) self.assertEqual(len(stop_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval + 1) self.assertEqual(len(data_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval + 1)
def hourSpanTZ(tz, time_ts, grace=1, hours_ago=0): """ Returns a TimeSpan for x hours ago """ if time_ts is None: return None time_ts -= grace dt = datetime.datetime.fromtimestamp(time_ts,tz) hour_start_dt = dt.replace(minute=0, second=0, microsecond=0) start_span_dt = hour_start_dt - datetime.timedelta(hours=hours_ago) stop_span_dt = start_span_dt + datetime.timedelta(hours=1) return TimeSpan(int(start_span_dt.timestamp()),int(stop_span_dt.timestamp()))
def test_Accum_unit_change(self): # Change the units used by a record mid-stream self.dataset[5]['usUnits'] = weewx.METRICWX # This should result in a ValueError with self.assertRaises(ValueError): accum = weewx.accum.Accum(TimeSpan(start_ts, stop_ts)) for record in self.dataset: accum.addRecord(record)
def test_Accum_with_string(self): """Test records with string literals in them.""" for i, record in enumerate(self.dataset): record['stringType'] = "AString%d" % i # As of V4.6, adding a string to the default accumulators should no longer result in an # exception accum = weewx.accum.Accum(TimeSpan(start_ts, stop_ts)) for record in self.dataset: accum.addRecord(record) # Try it again, but this time specifying a FirstLast accumulator for type 'stringType': weewx.accum.accum_dict.extend({'stringType': {'accumulator': 'firstlast', 'extractor': 'last'}}) accum = weewx.accum.Accum(TimeSpan(start_ts, stop_ts)) for record in self.dataset: accum.addRecord(record) # The value extracted for the string should be the last one seen rec = accum.getRecord() self.assertEqual(rec['stringType'], "AString%d" % (len(self.dataset) - 1))
def test_monthSpan(self): os.environ['TZ'] = 'America/Los_Angeles' self.assertEqual( archiveMonthSpan(time.mktime((2007, 12, 13, 10, 15, 0, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 1, 0, 0, 0, 0, 0, -1)), time.mktime((2008, 1, 1, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveMonthSpan(time.mktime((2007, 12, 1, 0, 0, 0, 0, 0, -1))), TimeSpan(time.mktime((2007, 11, 1, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 1, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveMonthSpan(time.mktime((2007, 12, 1, 0, 0, 1, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 1, 0, 0, 0, 0, 0, -1)), time.mktime((2008, 1, 1, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveMonthSpan(time.mktime((2008, 1, 1, 0, 0, 0, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 1, 0, 0, 0, 0, 0, -1)), time.mktime((2008, 1, 1, 0, 0, 0, 0, 0, -1))))
def test_get_series_archive_windvec(self): """Test a series of 'windvec', with no aggregation, run against the main archive table""" with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: # Get a series of wind values start_vec, stop_vec, data_vec \ = weewx.xtypes.WindVec.get_series('windvec', TimeSpan(start_ts, stop_ts), db_manager) self.assertEqual(len(start_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval + 1) self.assertEqual(len(stop_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval + 1) self.assertEqual(len(data_vec[0]), (stop_ts - start_ts) / gen_fake_data.interval + 1)
def test_TimeSpans(self): t = TimeSpan(1230000000, 1231000000) # Reflexive test: self.assertEqual(t, t) tsub = TimeSpan(1230500000, 1230600000) self.assertTrue(t.includes(tsub)) self.assertFalse(tsub.includes(t)) tleft = TimeSpan(1229000000, 1229100000) self.assertFalse(t.includes(tleft)) tright = TimeSpan(1232000000, 1233000000) self.assertFalse(t.includes(tright)) dic = {} dic[t] = 't' dic[tsub] = 'tsub' dic[tleft] = 'tleft' dic[tright] = 'tright' self.assertEqual(dic[t], 't')
def weekSpanTZ(tz, time_ts, startOfWeek=6, grace=1, weeks_ago=0): """Returns a TimeSpan representing a week that includes a given time. """ if time_ts is None: return None time_ts -= grace _day_date = datetime.datetime.fromtimestamp(time_ts,tz) _day_of_week = _day_date.weekday() _delta = _day_of_week - startOfWeek if _delta < 0: _delta += 7 _sunday_date = _day_date - datetime.timedelta(days=(_delta + 7 * weeks_ago)) _sunday_date = _sunday_date.replace(hour=0,minute=0,second=0,microsecond=0) _next_sunday_date = _sunday_date + datetime.timedelta(days=7) return TimeSpan(int(_sunday_date.timestamp()),int(_next_sunday_date.timestamp()))
def test_get_aggregate_windvec(self): """Test calculating special type 'windvec' using a variety of methods.""" with weewx.manager.open_manager_with_config( self.config_dict, 'wx_binding') as db_manager: month_start_tt = (2010, 3, 1, 0, 0, 0, 0, 0, -1) month_stop_tt = (2010, 3, 2, 0, 0, 0, 0, 0, -1) start_ts = time.mktime(month_start_tt) stop_ts = time.mktime(month_stop_tt) # Calculate the daily wind for 1-March-2010 using the daily summaries, the main archive # table, and letting get_aggregate() choose. for func in [ weewx.xtypes.WindVecDaily.get_aggregate, weewx.xtypes.WindVec.get_aggregate, weewx.xtypes.get_aggregate ]: windvec = func('windvec', TimeSpan(start_ts, stop_ts), 'avg', db_manager) self.assertAlmostEqual(windvec[0].real, -1.390, 3) self.assertAlmostEqual(windvec[0].imag, 3.250, 3) self.assertEqual(windvec[1:3], ('mile_per_hour', 'group_speed')) # Calculate the wind vector for the hour starting at 1-06-2010 15:00 hour_start_tt = (2010, 1, 6, 15, 0, 0, 0, 0, -1) hour_stop_tt = (2010, 1, 6, 16, 0, 0, 0, 0, -1) hour_start_ts = time.mktime(hour_start_tt) hour_stop_ts = time.mktime(hour_stop_tt) vt = weewx.xtypes.WindVec.get_aggregate( 'windvec', TimeSpan(hour_start_ts, hour_stop_ts), 'max', db_manager) self.assertAlmostEqual(abs(vt[0]), 15.281, 3) self.assertAlmostEqual(vt[0].real, 8.069, 3) self.assertAlmostEqual(vt[0].imag, -12.976, 3) vt = weewx.xtypes.WindVec.get_aggregate( 'windgustvec', TimeSpan(hour_start_ts, hour_stop_ts), 'max', db_manager) self.assertAlmostEqual(abs(vt[0]), 18.337, 3) self.assertAlmostEqual(vt[0].real, 9.683, 3) self.assertAlmostEqual(vt[0].imag, -15.572, 3)
def test_daySpan(self): os.environ['TZ'] = 'America/Los_Angeles' self.assertEqual( archiveDaySpan(time.mktime((2007, 12, 13, 10, 15, 0, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 13, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 14, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveDaySpan(time.mktime((2007, 12, 13, 0, 0, 0, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 12, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 13, 0, 0, 0, 0, 0, -1)))) # Try it again with grace=0 self.assertEqual( archiveDaySpan(time.mktime((2007, 12, 13, 0, 0, 0, 0, 0, -1)), grace=0), TimeSpan(time.mktime((2007, 12, 13, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 14, 0, 0, 0, 0, 0, -1)))) self.assertEqual( archiveDaySpan(time.mktime((2007, 12, 13, 0, 0, 1, 0, 0, -1))), TimeSpan(time.mktime((2007, 12, 13, 0, 0, 0, 0, 0, -1)), time.mktime((2007, 12, 14, 0, 0, 0, 0, 0, -1))))
def test_get_series_archive_agg_windvec_avg(self): with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: # Get a series of wind values start_vec, stop_vec, data_vec = weewx.xtypes.get_series('windvec', TimeSpan(start_ts, stop_ts), db_manager, 'avg', 24 * 3600) # March has 30 days. self.assertEqual(len(start_vec[0]), 30 + 1) self.assertEqual(len(stop_vec[0]), 30 + 1) self.assertEqual((["(%.2f, %.2f)" % (x.real, x.imag) for x in data_vec[0]]), (["(%.2f, %.2f)" % (x[0], x[1]) for x in Common.expected_daily_wind_avg]))
def test_AggregateDaily(self): """Test special aggregates that can be used against the daily summaries.""" with weewx.manager.open_manager_with_config( self.config_dict, 'wx_binding') as db_manager: month_start_tt = (2010, 3, 1, 0, 0, 0, 0, 0, -1) month_stop_tt = (2010, 4, 1, 0, 0, 0, 0, 0, -1) start_ts = time.mktime(month_start_tt) stop_ts = time.mktime(month_stop_tt) min_ge_vt = weewx.xtypes.DailySummaries.get_aggregate( 'outTemp', TimeSpan(start_ts, stop_ts), 'min_ge', db_manager, val=ValueTuple(15, 'degree_F', 'group_temperature')) self.assertEqual(min_ge_vt[0], 6) min_le_vt = weewx.xtypes.DailySummaries.get_aggregate( 'outTemp', TimeSpan(start_ts, stop_ts), 'min_le', db_manager, val=ValueTuple(0, 'degree_F', 'group_temperature')) self.assertEqual(min_le_vt[0], 2) minmax_vt = weewx.xtypes.DailySummaries.get_aggregate( 'outTemp', TimeSpan(start_ts, stop_ts), 'minmax', db_manager) self.assertAlmostEqual(minmax_vt[0], 39.28, 2) max_wind_vt = weewx.xtypes.DailySummaries.get_aggregate( 'wind', TimeSpan(start_ts, stop_ts), 'max', db_manager) self.assertAlmostEqual(max_wind_vt[0], 24.0, 2) avg_wind_vt = weewx.xtypes.DailySummaries.get_aggregate( 'wind', TimeSpan(start_ts, stop_ts), 'avg', db_manager) self.assertAlmostEqual(avg_wind_vt[0], 10.21, 2) # Double check this last one against the average calculated from the archive avg_wind_vt = weewx.xtypes.ArchiveTable.get_aggregate( 'windSpeed', TimeSpan(start_ts, stop_ts), 'avg', db_manager) self.assertAlmostEqual(avg_wind_vt[0], 10.21, 2) vecavg_wind_vt = weewx.xtypes.DailySummaries.get_aggregate( 'wind', TimeSpan(start_ts, stop_ts), 'vecavg', db_manager) self.assertAlmostEqual(vecavg_wind_vt[0], 5.14, 2) vecdir_wind_vt = weewx.xtypes.DailySummaries.get_aggregate( 'wind', TimeSpan(start_ts, stop_ts), 'vecdir', db_manager) self.assertAlmostEqual(vecdir_wind_vt[0], 88.77, 2)
def calc_gts(self, time_ts, dbmanager): """calculate Grünlandtemperatursumme GTS""" # needed timestamps _sod_ts = weeutil.weeutil.startOfDay(time_ts) # start of day _soy_ts = weeutil.weeutil.archiveYearSpan(time_ts)[0] # start of year _feb_ts = _soy_ts + 2678400 # Feb 1 _mar_ts = _feb_ts + 2419200 # Mar 1 (or Feb 29 in leap year) _end_ts = _mar_ts + 7948800 # Jun 1 (or May 31 in leap year) # initialize if program start or new year if self.last_gts_date is None or self.last_gts_date < _soy_ts: self.last_gts_date = _soy_ts self.gts_value = None self.gts_date = None loginf("GTS initialized %s" % time.strftime("%Y-%m-%d", time.localtime(_soy_ts))) # calculate # This runs one loop for every day since New Year at program # start and after that once a day one loop, only. After May 31th # no loop is executed. _loop_ct = 0 while self.last_gts_date < _sod_ts and self.last_gts_date < _end_ts: # the day the average is calculated for _today = TimeSpan(self.last_gts_date, self.last_gts_date + 86400) # calculate the average of the outside temperature _result = weewx.xtypes.get_aggregate('outTemp', _today, 'avg', dbmanager) # convert to centrigrade if _result is not None: _result = weewx.units.convert(_result, 'degree_C') # check condition and add to sum if _result is not None and _result[0] is not None: if self.gts_value is None: self.gts_value = 0 _dayavg = _result[0] if _dayavg > 0: if self.last_gts_date < _feb_ts: _dayavg *= 0.5 elif self.last_gts_date < _mar_ts: _dayavg *= 0.75 self.gts_value += _dayavg if self.gts_value >= 200 and self.gts_date is None: self.gts_date = self.last_gts_date # next day self.last_gts_date += 86400 _loop_ct += 1 loginf("GTS %s, %s loops" % (self.gts_value, _loop_ct))
def test_get_series_archive_agg_rain_sum(self): """Test a series of daily aggregated rain totals""" with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: # Calculate the total daily rain start_vec, stop_vec, data_vec = weewx.xtypes.get_series('rain', TimeSpan(start_ts, stop_ts), db_manager, 'sum', 24 * 3600) # March has 30 days. self.assertEqual(len(start_vec[0]), 30 + 1) self.assertEqual(len(stop_vec[0]), 30 + 1) self.assertEqual((["%.2f" % d for d in data_vec[0]], data_vec[1], data_vec[2]), (["%.2f" % d for d in Common.expected_daily_rain_sum], 'inch', 'group_rain'))
def test_get_series_archive_agg_windvec_last(self): with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: # Get a series of wind values start_vec, stop_vec, data_vec = weewx.xtypes.get_series('windvec', TimeSpan(start_ts, stop_ts), db_manager, 'last', 24 * 3600) # March has 30 days. self.assertEqual(len(start_vec[0]), 30 + 1) self.assertEqual(len(stop_vec[0]), 30 + 1) # The round(x, 2) + 0 is necessary to avoid 0.00 comparing different from -0.00. self.assertEqual((["(%.2f, %.2f)" % (round(x.real, 2) + 0, round(x.imag, 2) + 0) for x in data_vec[0]]), (["(%.2f, %.2f)" % (x[0], x[1]) for x in Common.expected_daily_wind_last]))
def test_null_wind_gust_dir(self): # If LOOP packets windGustDir=None, the accumulator should not substitute windDir. # This is a regression test that tests that. accum = weewx.accum.Accum(TimeSpan(start_ts, stop_ts)) # Add the dataset to the accumulator. Null out windGustDir first. for record in self.dataset: record_test = dict(record) record_test['windGustDir'] = None accum.addRecord(record_test) # Extract the record out of the accumulator accum_record = accum.getRecord() # windGustDir should match the windDir seen at max wind: self.assertIsNone(accum_record['windGustDir'])
def test_get_series_archive_agg_rain_cum(self): """Test a series of daily cumulative rain totals""" with weewx.manager.open_manager_with_config(self.config_dict, 'wx_binding') as db_manager: # Calculate the cumulative total daily rain start_vec, stop_vec, data_vec = weewx.xtypes.get_series('rain', TimeSpan(start_ts, stop_ts), db_manager, 'cumulative', 24 * 3600) # March has 30 days. self.assertEqual(len(start_vec[0]), 30 + 1) self.assertEqual(len(stop_vec[0]), 30 + 1) right_answer = functools.reduce(lambda v, x: v + [v[-1] + x], Common.expected_daily_rain_sum, [0])[1:] self.assertEqual((["%.2f" % d for d in data_vec[0]], data_vec[1], data_vec[2]), (["%.2f" % d for d in right_answer], 'inch', 'group_rain'))
def test_TimeSpans(self): t = TimeSpan(1230000000, 1231000000) # Reflexive test: self.assertEqual(t, t) tsub = TimeSpan(1230500000, 1230600000) self.assertTrue(t.includes(tsub)) self.assertFalse(tsub.includes(t)) tleft = TimeSpan(1229000000, 1229100000) self.assertFalse(t.includes(tleft)) tright = TimeSpan(1232000000, 1233000000) self.assertFalse(t.includes(tright)) dic={} dic[t] = 't' dic[tsub] = 'tsub' dic[tleft] = 'tleft' dic[tright] = 'tright' self.assertEqual(dic[t], 't')