openrvdas.logger.transforms.interpolation_transform

Compute interpolations of input data.

  1#!/usr/bin/env python3
  2"""Compute interpolations of input data.
  3"""
  4
  5import logging
  6import bisect
  7
  8from math import degrees, radians, sin, cos, asin, atan2, exp, isnan, sqrt
  9from statistics import mean, median, stdev
 10from typing import Union, Any
 11
 12
 13from logger.utils.das_record import DASRecord  # noqa: E402
 14from logger.transforms.derived_data_transform import DerivedDataTransform  # noqa: E402
 15
 16
 17################################################################################
 18class InterpolationTransform(DerivedDataTransform):
 19    """Transform that computes interpolations of the specified variables.
 20    """
 21
 22    def __init__(self, field_spec, interval, window,
 23                 data_id=None, metadata_interval=None, **kwargs):
 24        """
 25        ```
 26        field_spec - a dict of interpolated variables that are to be created,
 27                where the key is the new variable's name, and the value is a dict
 28                specifying the source field name and the algorithm that is to be
 29                used to do the interpolation. E.g.:
 30
 31               {
 32                 'AvgCNAVCourseTrue': {
 33                   'source': 'CNAVCourseTrue',
 34                   'algorithm': {
 35                     'type': 'boxcar_average',
 36                     'window': 30
 37                   },
 38                 },
 39                 'AvgCNAVGPSDay': {
 40                   'source': 'CNAVGPSDay',
 41                   'algorithm': { 'type': 'nearest' },
 42                 },
 43                 ...
 44               }
 45
 46               To simplify templating, can also accept a spec of the form
 47               of a list:
 48
 49               [
 50                 { sources: [MwxAirTemp, RTMPTemp, ...],
 51                   algorithm: boxcar_average,
 52                   window: 10,
 53                   result_prefix: Avg
 54                 },
 55                 { sources: [PortTrueWindDir, StbdTrueWindDir],
 56                   algorithm: polar_average,
 57                   window: 10,
 58                   result_prefix: Avg
 59                 }
 60               ]
 61
 62               Any other keys in a list entry, such as min_count, are passed
 63               to the algorithm along with its window.
 64
 65               Algorithms:
 66
 67                 boxcar_average - mean of the values within the window,
 68                       centred on the output time
 69                 polar_average - mean direction of angles (in degrees)
 70                       within the window, so that 359 and 1 average to 0
 71                 nearest - the value nearest the output time
 72                 median - median of the values within the window; unlike a
 73                       mean, unaffected by a few spikes or dropouts
 74                 trimmed_mean - mean of the values within the window after
 75                       dropping the highest and lowest; the option 'trim'
 76                       (default 0.1) is the fraction dropped from each end
 77                 time_weighted_average - mean of the values within the window,
 78                       each weighted by the time it covers (integrating
 79                       linearly between readings), so that a burst of
 80                       readings, or a gap, doesn't skew the mean as it does a
 81                       boxcar_average's. Readings are joined across a gap
 82                       left by missing values.
 83                 gaussian_average - values within the window weighted by
 84                       exp(-dt**2 / 2 sigma**2), dt being their distance from
 85                       the output time. Smoother than a boxcar, and doesn't
 86                       jump as a value enters or leaves the window. The option
 87                       'sigma' defaults to a sixth of the window, so that the
 88                       window spans 3 sigma either side
 89                 triangular_average - values within the window weighted from
 90                       1 at the output time down to 0 at the window's edges;
 91                       much like gaussian_average, and simpler
 92                 exponential_average - an exponential moving average, with
 93                       the option 'time_constant' (in seconds, required): each
 94                       new value moves the average by 1 - exp(-dt /
 95                       time_constant) of the way towards it, dt being the time
 96                       since the previous value. Unlike the other algorithms
 97                       it uses only values up to the output time, and remembers
 98                       the average from one output to the next, so its time
 99                       constant can be longer than the window. Outputs are
100                       still delayed by half the transform's window, as all
101                       outputs are, so for a live display give it a transform
102                       of its own with a short window - but no shorter than
103                       twice the interval, or values may be discarded before
104                       it sees them. No value is output once the field's
105                       latest value is more than a window old.
106
107               Window statistics, for quality control. Each is an algorithm
108               of its own, so to output several statistics of a field, list
109               it once for each, with a different result_prefix:
110                 min, max - smallest and largest value within the window.
111                       max of a short-term average gives wind gusts: the
112                       WMO gust is the maximum 3-second average, i.e. max
113                       over the output of a 3-second boxcar_average
114                 std_dev - sample standard deviation of the values within
115                       the window; needs at least two values
116                 circular_std_dev - standard deviation of angles (in
117                       degrees) within the window, by the Yamartino method,
118                       so that values either side of 0/360 are close together
119                 count - how many valid values the window holds; 0, rather
120                       than no value, when it holds none
121
122               Missing values - None, or NaN as some instruments report when
123               they have no reading - are ignored by all of them, so one
124               missing reading doesn't make a whole average NaN. If a window
125               holds nothing but missing values, no value is output for it.
126
127               Every algorithm but nearest, count and exponential_average
128               also takes an optional
129               min_count (default 1): output no value for a window that holds
130               fewer than this many valid values, rather than reporting an
131               average of one or two readings as if the window were full.
132
133               boxcar_average, median, trimmed_mean, min, max and std_dev
134               also take an optional outlier_mads: before averaging, drop values more than this many
135               median absolute deviations (MADs) from the window's median.
136               It must be at least 1, so that at least half the window is
137               always kept; 3 is a common choice. If more than half the values in a window
138               are identical, the MAD is zero and any value that differs from
139               them is dropped. min_count counts values before outliers are
140               dropped.
141
142        interval - At what intervals (in seconds) should the interpolation
143               be computed?
144
145        window - Time window (in seconds) of data we should maintain
146               around the computation we're going to make.
147
148        data_id - What data id to assign to the output
149
150        metadata_interval - how many seconds between when we attach field metadata
151               to a record we send out.
152        ```
153
154        """
155        super().__init__(**kwargs)  # processes 'quiet' and type hints
156
157        self.field_spec = {}
158        self.source_fields = set()
159        if isinstance(field_spec, dict):
160            for result_field, entry in field_spec.items():
161                if 'source' in entry and 'algorithm' in entry:
162                    self.field_spec[result_field] = entry
163                    self.source_fields.add(entry.get('source'))
164                else:
165                    logging.warning('InterpolationTransform field definition for %s '
166                                    'must specify both "source" and "algorithm": %s',
167                                    result_field, entry)
168
169        # Alternate way of setting up a field spec that makes it easier to templatize.
170        # We'll expand the list of specs into a traditional field_spec
171        elif isinstance(field_spec, list):
172            for spec_instance in field_spec:
173                # Each spec_instance should be a dict of fields:, algorithm:,
174                # output_field_prefix: and window:
175                if not isinstance(spec_instance, dict):
176                    raise ValueError('InterpolationTransform: if field_spec is list, must be '
177                                     f'a list of dicts; found list of {type(spec_instance)}')
178                sources = spec_instance.get('sources')
179
180                if not isinstance(sources, list):
181                    raise ValueError('InterpolationTransform: sources for field spec must be '
182                                     f'a list; found {type(sources)}: {sources!r}')
183
184                # Expand source list into a traditional field_spec. Keys other
185                # than these (e.g. min_count) are options for the algorithm.
186                algorithm = spec_instance.get('algorithm')
187                window = spec_instance.get('window')
188                result_prefix = spec_instance.get('result_prefix')
189                options = {k: v for k, v in spec_instance.items()
190                           if k not in ('sources', 'algorithm', 'window', 'result_prefix')}
191                for source in sources:
192                    entry = {'source': source,
193                             'algorithm': {'type': algorithm, 'window': window, **options}}
194                    result_field = result_prefix + source
195                    self.field_spec[result_field] = entry
196
197                # Finally, stash sources so we know what to look for
198                self.source_fields.update(sources)
199
200        else:
201            raise ValueError('InterpolationTransform: field_spec must be either list '
202                             f'or dict. Found {type(field_spec)}')
203
204        for result_field, entry in self.field_spec.items():
205            _check_algorithm_options(result_field, entry.get('algorithm'))
206
207        self.interval = interval
208        self.window = window
209        self.data_id = data_id
210        self.metadata_interval = metadata_interval
211
212        # A dict of the cached values we're hanging onto - use sorted
213        # lists of (timestamp, value) pairs
214        self.cached_values = {f: [] for f in self.source_fields}
215
216        # The next timestamp we'd like to emit. Is set the first time we
217        # call transform().
218        self.next_timestamp = 0
219        self.earliest_timestamp = float('inf')  # Track earliest timestamp we've seen
220        self.latest_timestamp = 0
221        self.last_metadata_send = 0  # last time we've sent metadata
222
223        # For each exponential_average: (timestamp of the latest value it
224        # has taken in, the average then)
225        self.exponential_averages = {}
226
227    ############################
228    def fields(self):
229        """Which fields are we interested in to produce transformed data?"""
230        return list(self.source_fields)
231
232    ############################
233    def _metadata(self):
234        """Return a dict of metadata for our derived fields."""
235        metadata_fields = {
236            'field': {
237                'description':
238                    'Interpolated values of %s via %s' %
239                    (entry['source'], entry['algorithm']),
240                'device': 'InterpolationTransform',
241                'device_type': 'DerivedDataTransform',
242                'device_type_field': result_field
243            }
244            for result_field, entry in self.field_spec.items()
245        }
246        return metadata_fields
247
248    ############################
249    def _add_record(self, record):
250        """Cached the values contained in a new record, maintaining timestamp order."""
251        if type(record) not in [DASRecord, dict]:
252            logging.error('InterpolationTransform records must be dict or '
253                          'DASRecord. Received type %s: %s', type(record), record)
254            return 0
255
256        if type(record) is DASRecord:
257            timestamp = record.timestamp
258            fields = record.fields
259        else:
260            timestamp = record.get('timestamp', 0)
261            fields = record.get('fields')
262
263        if not fields:
264            logging.info('InterpolationTransform: record has no fields: %s', record)
265            return timestamp
266
267        # First, copy the new data into our cache.  NOTE: It's a judgment
268        # call whether it's more efficient to iterate over the fields
269        # we're looking for or the fields in the record.
270        for field, new_value in fields.items():
271            if field not in self.source_fields:
272                continue
273
274            # Examine the value we've gotten. If list, we assume it's [(ts,
275            # value), (ts, value),...]
276            if type(new_value) is list:
277                for ts, val in new_value.items():
278                    self._insert_sorted(field, ts, val)
279                    logging.debug(f'adding {ts}: {field} - {val}')
280
281            # If not list, assume DASRecord or simple field dict; add tuple
282            elif timestamp:
283                self._insert_sorted(field, timestamp, new_value)
284                logging.debug(f'adding {timestamp}: {field} - {new_value}')
285            else:
286                logging.warning('Interpolation found no timestamp in '
287                                'record: %s', record)
288
289        # Update our tracking of the earliest and latest timestamps we've seen
290        self.earliest_timestamp = min(self.earliest_timestamp, timestamp)
291        self.latest_timestamp = max(self.latest_timestamp, timestamp)
292
293        # Return the timestamp of the record
294        return timestamp
295
296    ############################
297    def _insert_sorted(self, field: str, timestamp: float, value: Any) -> None:
298        """Insert a (timestamp, value) pair into the sorted cached values for a field."""
299        cache = self.cached_values[field]
300
301        # Use binary search to find insertion position to maintain sorted order
302        timestamps = [ts for ts, _ in cache]
303        pos = bisect.bisect_left(timestamps, timestamp)
304
305        # Insert at correct position to maintain sort order
306        cache.insert(pos, (timestamp, value))
307
308    ############################
309    def _clean_cache(self):
310        """Remove values from cache that are too old to be useful."""
311        for field in self.source_fields:
312            # Iterate forward through field cache until we find a timestamp
313            # that is recent enough to keep
314            cache = self.cached_values[field]
315            lower_limit = self.next_timestamp - self.window / 2
316            keep_index = 0
317            while keep_index < len(cache) and cache[keep_index][0] < lower_limit:
318                keep_index += 1
319
320            # Throw away everything before that index
321            self.cached_values[field] = cache[keep_index:]
322
323    ############################
324    def _exponential_average(self, result_field, algorithm, values, timestamp):
325        """Bring result_field's exponential moving average up to timestamp,
326        taking in the values since the latest it has taken in, and return it
327        - or None if there is no recent value."""
328        latest, average = self.exponential_averages.get(result_field, (None, None))
329        time_constant = algorithm['time_constant']
330        try:
331            for ts, val in values:
332                if ts > timestamp:
333                    break
334                if _is_missing(val) or (latest is not None and ts <= latest):
335                    continue
336                if average is None:
337                    average = val
338                else:
339                    average += (1 - exp(-(ts - latest) / time_constant)) * (val - average)
340                latest = ts
341        except TypeError:
342            logging.error('Non-numeric value in interpolation list: %s', values)
343            return None
344        self.exponential_averages[result_field] = (latest, average)
345
346        # Don't go on reporting the average of a field that has stopped
347        if latest is None or timestamp - latest > (algorithm.get('window') or self.window):
348            return None
349        return average
350
351    ############################
352    def transform(self, record: Union[DASRecord, dict]):
353        """Incorporate any useable fields in this record, and if it gives
354        us any new interpolated values, aggregate and return them as a list of
355        dicts of the form:
356
357        [
358          {'timestamp': timestamp,
359           'fields': {
360             fieldname: value,
361             fieldname: value,
362             ...
363            }
364          },
365          {'timestamp': timestamp,
366           'fields': ...
367          }
368        ]
369
370        If there are insufficient data in the window to compute any
371        interpolation, return an empty list.
372        """
373        # See if it's something we can process, and if not, try digesting
374        if not self.can_process_record(record):  # inherited from BaseModule()
375            return self.digest_record(record)  # inherited from BaseModule()
376
377        # Add the record
378        self._add_record(record)
379
380        # First time through, our 'next_timestamp' will be zero. Set it to
381        # a good starting place.
382        if not self.next_timestamp:
383            self.next_timestamp = self.earliest_timestamp
384
385        # What fields do we have data for in our cache?
386        non_empty = {}
387        for dest, spec in self.field_spec.items():
388            source = spec.get('source')
389            if source:
390                values = self.cached_values.get(source, [])
391                if len(values):
392                    non_empty[dest] = [source, len(values)]
393
394        # Iterate through all timestamps up to the edge of what we can fit
395        # in our window without running into the edge of our latest timestamp.
396        results = []
397        logging.debug(f'latest timestamp: {self.latest_timestamp}, next: {self.next_timestamp}')
398        while self.next_timestamp < self.latest_timestamp - self.window / 2:
399            # Clean out old data
400            self._clean_cache()
401
402            result = {}
403            for result_field, entry in self.field_spec.items():
404                source = entry.get('source')
405                source_values = self.cached_values.get(source)
406                algorithm = entry.get('algorithm')
407                # logging.warning('%s->%s: %d values',
408                #                source, result_field, len(source_values))
409                if algorithm.get('type') == 'exponential_average':
410                    value = self._exponential_average(result_field, algorithm,
411                                                      source_values, self.next_timestamp)
412                else:
413                    value = interpolate(algorithm, source_values,
414                                        self.next_timestamp,
415                                        self.latest_timestamp)
416                if value is not None:
417                    result[result_field] = value
418            if result:
419                result_record = {'timestamp': self.next_timestamp, 'fields': result}
420                if self.data_id:
421                    result_record['data_id'] = self.data_id
422                results.append(result_record)
423            self.next_timestamp += self.interval
424
425        return results
426
427
428# Algorithms that take the outlier_mads option
429OUTLIER_ALGORITHMS = ('boxcar_average', 'median', 'trimmed_mean', 'min', 'max', 'std_dev')
430
431# Window statistics, each its own algorithm
432WINDOW_STATISTICS = ('min', 'max', 'std_dev', 'circular_std_dev', 'count')
433
434
435############################
436def _check_algorithm_options(result_field, algorithm):
437    """Raise ValueError if an algorithm is given an option it can't use, or
438    an invalid value for one."""
439    if not isinstance(algorithm, dict):
440        return
441    alg_type = algorithm.get('type')
442
443    outlier_mads = algorithm.get('outlier_mads')
444    if outlier_mads is not None:
445        if alg_type not in OUTLIER_ALGORITHMS:
446            raise ValueError(f'InterpolationTransform: {result_field}: outlier_mads '
447                             f'can be used with {", ".join(OUTLIER_ALGORITHMS)}, '
448                             f'not {alg_type}')
449        # At least 1, so that at least half of each window is always kept:
450        # by definition, half the values are within one MAD of the median.
451        if not isinstance(outlier_mads, (int, float)) or outlier_mads < 1:
452            raise ValueError(f'InterpolationTransform: {result_field}: outlier_mads '
453                             f'must be a number no less than 1; found {outlier_mads!r}')
454
455    # count reports however many values there are, and an exponential
456    # average carries on from one output to the next: a minimum makes no
457    # sense for either
458    if alg_type in ('count', 'exponential_average') and \
459            algorithm.get('min_count') is not None:
460        raise ValueError(f'InterpolationTransform: {result_field}: min_count '
461                         f'can not be used with {alg_type}')
462
463    for option, option_alg_type in (('sigma', 'gaussian_average'),
464                                    ('time_constant', 'exponential_average')):
465        value = algorithm.get(option)
466        if value is None:
467            if option == 'time_constant' and alg_type == option_alg_type:
468                raise ValueError(f'InterpolationTransform: {result_field}: '
469                                 f'exponential_average needs a time_constant')
470            continue
471        if alg_type != option_alg_type:
472            raise ValueError(f'InterpolationTransform: {result_field}: {option} can '
473                             f'only be used with {option_alg_type}, not {alg_type}')
474        if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
475            raise ValueError(f'InterpolationTransform: {result_field}: {option} must '
476                             f'be a number greater than 0; found {value!r}')
477
478    trim = algorithm.get('trim')
479    if trim is not None:
480        if alg_type != 'trimmed_mean':
481            raise ValueError(f'InterpolationTransform: {result_field}: trim can '
482                             f'only be used with trimmed_mean, not {alg_type}')
483        if not isinstance(trim, (int, float)) or not 0 <= trim < 0.5:
484            raise ValueError(f'InterpolationTransform: {result_field}: trim must '
485                             f'be at least 0 and less than 0.5; found {trim!r}')
486
487
488############################
489def _reject_outliers(vals, outlier_mads):
490    """Drop values more than outlier_mads median absolute deviations from
491    the median. If the MAD is zero, drop every value not equal to the median."""
492    center = median(vals)
493    deviations = [abs(val - center) for val in vals]
494    mad = median(deviations)
495    return [val for val, deviation in zip(vals, deviations)
496            if deviation <= outlier_mads * mad]
497
498
499############################
500def _circular_std_dev(angles):
501    """Standard deviation of angles in degrees, by the Yamartino method:
502    from how far the mean of their unit vectors falls short of length 1."""
503    val_radians = [radians(val) for val in angles]
504    sin_mean = mean([sin(val) for val in val_radians])
505    cos_mean = mean([cos(val) for val in val_radians])
506    # max() because rounding can take 1 - (length squared) just below zero
507    epsilon = sqrt(max(0.0, 1 - (sin_mean ** 2 + cos_mean ** 2)))
508    return degrees(asin(epsilon) * (1 + (2 / sqrt(3) - 1) * epsilon ** 3))
509
510
511############################
512def _is_missing(value):
513    """Is this a missing value: None, or a NaN?"""
514    return value is None or (isinstance(value, float) and isnan(value))
515
516
517############################
518def interpolate(algorithm, values, timestamp, now):
519    """An omnibus routine for taking a list of timestamped values, a
520    specification of an averaging algorithm, and returning a value
521    computed at the specified timestamp. Returns None if there aren't
522    enough data to compute a value.
523
524    algorithm    A dict specifying the algorithm to be used: its 'type', and
525                 options such as 'window' and 'min_count'
526
527                 Missing values (None or NaN) are ignored by every algorithm.
528
529    values       A list of [(timestamp, value),...] pairs
530
531    timestamp    The timestamp for which interpolation should be computed
532
533    now          Timestamp now. This should be used to determine whether
534                 we're far enough beyond our timestamp to compute a value.
535    """
536    if not type(algorithm) is dict:
537        logging.warning('Function interpolate() handed non-dict algorithm '
538                        'specification: %s', algorithm)
539        return None
540    # Ignore missing values: None, or NaN as some instruments send when
541    # they have no reading. Otherwise one of them would make a whole
542    # average NaN, or be returned as the nearest value.
543    values = [(ts, val) for ts, val in values if not _is_missing(val)]
544    if not values:
545        logging.debug('Function interpolate() has no values to work with')
546        # An empty window is exactly what count is there to report
547        return 0 if algorithm.get('type') == 'count' else None
548
549    ##################
550    # Select algorithm
551    alg_type = algorithm.get('type')
552    min_count = algorithm.get('min_count') or 1
553
554    # boxcar_average: all values within symmetric interval window get
555    # same weight.
556    if alg_type == 'boxcar_average':
557        window = algorithm.get('window', 10)  # How far back/forward to average
558        lower_limit = timestamp - window / 2
559        upper_limit = timestamp + window / 2
560        vals_to_average = [val for ts, val in values
561                           if ts >= lower_limit and ts <= upper_limit]
562        if len(vals_to_average) < min_count:
563            return None
564
565        try:
566            outlier_mads = algorithm.get('outlier_mads')
567            if outlier_mads:
568                vals_to_average = _reject_outliers(vals_to_average, outlier_mads)
569                if not vals_to_average:
570                    return None
571            return mean(vals_to_average)
572        except TypeError:
573            logging.error('Non-numeric value in interpolation list: %s', vals_to_average)
574            return None
575
576    # nearest: return value of nearest timestamp. Note that we assume
577    # timestamps are in order, so once distance starts going up, we're
578    # done.
579    if alg_type == 'nearest':
580        best_distance = float('inf')
581        value = None
582        for i in range(len(values)):
583            ts, ts_value = values[i]
584            distance = abs(ts - timestamp)
585            if distance <= best_distance:
586                best_distance = distance
587                value = ts_value
588            else:
589                break
590        return value
591
592    # polar_average: interpret as an angle in degrees. Convert to points
593    # on a unit circle and return the angle of their centroid from the origin.
594    if alg_type == 'polar_average':
595        window = algorithm.get('window', 10)  # How far back/forward to average
596        lower_limit = timestamp - window / 2
597        upper_limit = timestamp + window / 2
598        vals_to_average = [val for ts, val in values
599                           if ts >= lower_limit and ts <= upper_limit]
600        if len(vals_to_average) < min_count:
601            return None
602
603        try:
604            val_radians = [radians(val) for val in vals_to_average]
605            x_mean = mean([sin(val) for val in val_radians])
606            y_mean = mean([cos(val) for val in val_radians])
607            angle = degrees(atan2(x_mean, y_mean))
608            if angle < 0:
609                angle += 360
610            # A tiny negative angle (rounding error when angles cancel
611            # around north) plus 360 rounds to exactly 360.0
612            if angle >= 360:
613                angle -= 360
614            return angle
615        except (TypeError, ValueError):  # ValueError: sin() or cos() of inf
616            logging.error('Non-numeric or infinite value in interpolation list: %s',
617                          vals_to_average)
618            return None
619
620    # median and trimmed_mean: robust to a few spikes or dropouts.
621    if alg_type in ('median', 'trimmed_mean'):
622        window = algorithm.get('window', 10)  # How far back/forward to look
623        lower_limit = timestamp - window / 2
624        upper_limit = timestamp + window / 2
625        vals_to_average = [val for ts, val in values
626                           if ts >= lower_limit and ts <= upper_limit]
627        if len(vals_to_average) < min_count:
628            return None
629
630        try:
631            outlier_mads = algorithm.get('outlier_mads')
632            if outlier_mads:
633                vals_to_average = _reject_outliers(vals_to_average, outlier_mads)
634                if not vals_to_average:
635                    return None
636            if alg_type == 'median':
637                return median(vals_to_average)
638
639            vals_to_average = sorted(vals_to_average)
640            drop = int(len(vals_to_average) * algorithm.get('trim', 0.1))
641            if drop:
642                vals_to_average = vals_to_average[drop:-drop]
643            return mean(vals_to_average)
644        except TypeError:
645            logging.error('Non-numeric value in interpolation list: %s', vals_to_average)
646            return None
647
648    # time_weighted_average: integrate linearly between readings (the
649    # trapezoidal rule) and divide by the time they span, so each value
650    # counts for the time it covers rather than once.
651    if alg_type == 'time_weighted_average':
652        window = algorithm.get('window', 10)  # How far back/forward to average
653        lower_limit = timestamp - window / 2
654        upper_limit = timestamp + window / 2
655        in_window = [(ts, val) for ts, val in values
656                     if ts >= lower_limit and ts <= upper_limit]
657        if len(in_window) < min_count:
658            return None
659
660        try:
661            span = in_window[-1][0] - in_window[0][0]
662            if not span:  # all at one time, so no time to weight them by
663                return mean([val for ts, val in in_window])
664            area = sum((ts_1 - ts_0) * (val_0 + val_1) / 2
665                       for (ts_0, val_0), (ts_1, val_1) in zip(in_window, in_window[1:]))
666            return area / span
667        except TypeError:
668            logging.error('Non-numeric value in interpolation list: %s', in_window)
669            return None
670
671    # gaussian_average and triangular_average: weight values by their
672    # distance from the output time.
673    if alg_type in ('gaussian_average', 'triangular_average'):
674        window = algorithm.get('window', 10)  # How far back/forward to average
675        lower_limit = timestamp - window / 2
676        upper_limit = timestamp + window / 2
677        in_window = [(ts, val) for ts, val in values
678                     if ts >= lower_limit and ts <= upper_limit]
679        if len(in_window) < min_count:
680            return None
681
682        if alg_type == 'gaussian_average':
683            sigma = algorithm.get('sigma') or window / 6
684            weights = [exp(-(ts - timestamp) ** 2 / (2 * sigma ** 2))
685                       for ts, val in in_window]
686        else:
687            weights = [1 - abs(ts - timestamp) / (window / 2) for ts, val in in_window]
688        total_weight = sum(weights)
689        if not total_weight:  # e.g. a triangle's only values at its very edges
690            return None
691        try:
692            return sum(weight * val for weight, (ts, val)
693                       in zip(weights, in_window)) / total_weight
694        except TypeError:
695            logging.error('Non-numeric value in interpolation list: %s', in_window)
696            return None
697
698    # Window statistics, for quality control
699    if alg_type in WINDOW_STATISTICS:
700        window = algorithm.get('window', 10)  # How far back/forward to look
701        lower_limit = timestamp - window / 2
702        upper_limit = timestamp + window / 2
703        vals_in_window = [val for ts, val in values
704                          if ts >= lower_limit and ts <= upper_limit]
705        if alg_type == 'count':
706            return len(vals_in_window)
707        if len(vals_in_window) < min_count:
708            return None
709
710        try:
711            outlier_mads = algorithm.get('outlier_mads')
712            if outlier_mads:
713                vals_in_window = _reject_outliers(vals_in_window, outlier_mads)
714                if not vals_in_window:
715                    return None
716            if alg_type == 'min':
717                return min(vals_in_window)
718            if alg_type == 'max':
719                return max(vals_in_window)
720            if alg_type == 'std_dev':
721                return stdev(vals_in_window) if len(vals_in_window) > 1 else None
722            return _circular_std_dev(vals_in_window)
723        except (TypeError, ValueError):  # ValueError: sin() or cos() of inf
724            logging.error('Non-numeric or infinite value in interpolation list: %s',
725                          vals_in_window)
726            return None
727
728    # Not an algorithm we recognize
729    else:
730        logging.warning('Function interpolate() received unrecognized algorithm '
731                        'type: %s', alg_type)
732        return None
class InterpolationTransform(logger.transforms.derived_data_transform.DerivedDataTransform):
 19class InterpolationTransform(DerivedDataTransform):
 20    """Transform that computes interpolations of the specified variables.
 21    """
 22
 23    def __init__(self, field_spec, interval, window,
 24                 data_id=None, metadata_interval=None, **kwargs):
 25        """
 26        ```
 27        field_spec - a dict of interpolated variables that are to be created,
 28                where the key is the new variable's name, and the value is a dict
 29                specifying the source field name and the algorithm that is to be
 30                used to do the interpolation. E.g.:
 31
 32               {
 33                 'AvgCNAVCourseTrue': {
 34                   'source': 'CNAVCourseTrue',
 35                   'algorithm': {
 36                     'type': 'boxcar_average',
 37                     'window': 30
 38                   },
 39                 },
 40                 'AvgCNAVGPSDay': {
 41                   'source': 'CNAVGPSDay',
 42                   'algorithm': { 'type': 'nearest' },
 43                 },
 44                 ...
 45               }
 46
 47               To simplify templating, can also accept a spec of the form
 48               of a list:
 49
 50               [
 51                 { sources: [MwxAirTemp, RTMPTemp, ...],
 52                   algorithm: boxcar_average,
 53                   window: 10,
 54                   result_prefix: Avg
 55                 },
 56                 { sources: [PortTrueWindDir, StbdTrueWindDir],
 57                   algorithm: polar_average,
 58                   window: 10,
 59                   result_prefix: Avg
 60                 }
 61               ]
 62
 63               Any other keys in a list entry, such as min_count, are passed
 64               to the algorithm along with its window.
 65
 66               Algorithms:
 67
 68                 boxcar_average - mean of the values within the window,
 69                       centred on the output time
 70                 polar_average - mean direction of angles (in degrees)
 71                       within the window, so that 359 and 1 average to 0
 72                 nearest - the value nearest the output time
 73                 median - median of the values within the window; unlike a
 74                       mean, unaffected by a few spikes or dropouts
 75                 trimmed_mean - mean of the values within the window after
 76                       dropping the highest and lowest; the option 'trim'
 77                       (default 0.1) is the fraction dropped from each end
 78                 time_weighted_average - mean of the values within the window,
 79                       each weighted by the time it covers (integrating
 80                       linearly between readings), so that a burst of
 81                       readings, or a gap, doesn't skew the mean as it does a
 82                       boxcar_average's. Readings are joined across a gap
 83                       left by missing values.
 84                 gaussian_average - values within the window weighted by
 85                       exp(-dt**2 / 2 sigma**2), dt being their distance from
 86                       the output time. Smoother than a boxcar, and doesn't
 87                       jump as a value enters or leaves the window. The option
 88                       'sigma' defaults to a sixth of the window, so that the
 89                       window spans 3 sigma either side
 90                 triangular_average - values within the window weighted from
 91                       1 at the output time down to 0 at the window's edges;
 92                       much like gaussian_average, and simpler
 93                 exponential_average - an exponential moving average, with
 94                       the option 'time_constant' (in seconds, required): each
 95                       new value moves the average by 1 - exp(-dt /
 96                       time_constant) of the way towards it, dt being the time
 97                       since the previous value. Unlike the other algorithms
 98                       it uses only values up to the output time, and remembers
 99                       the average from one output to the next, so its time
100                       constant can be longer than the window. Outputs are
101                       still delayed by half the transform's window, as all
102                       outputs are, so for a live display give it a transform
103                       of its own with a short window - but no shorter than
104                       twice the interval, or values may be discarded before
105                       it sees them. No value is output once the field's
106                       latest value is more than a window old.
107
108               Window statistics, for quality control. Each is an algorithm
109               of its own, so to output several statistics of a field, list
110               it once for each, with a different result_prefix:
111                 min, max - smallest and largest value within the window.
112                       max of a short-term average gives wind gusts: the
113                       WMO gust is the maximum 3-second average, i.e. max
114                       over the output of a 3-second boxcar_average
115                 std_dev - sample standard deviation of the values within
116                       the window; needs at least two values
117                 circular_std_dev - standard deviation of angles (in
118                       degrees) within the window, by the Yamartino method,
119                       so that values either side of 0/360 are close together
120                 count - how many valid values the window holds; 0, rather
121                       than no value, when it holds none
122
123               Missing values - None, or NaN as some instruments report when
124               they have no reading - are ignored by all of them, so one
125               missing reading doesn't make a whole average NaN. If a window
126               holds nothing but missing values, no value is output for it.
127
128               Every algorithm but nearest, count and exponential_average
129               also takes an optional
130               min_count (default 1): output no value for a window that holds
131               fewer than this many valid values, rather than reporting an
132               average of one or two readings as if the window were full.
133
134               boxcar_average, median, trimmed_mean, min, max and std_dev
135               also take an optional outlier_mads: before averaging, drop values more than this many
136               median absolute deviations (MADs) from the window's median.
137               It must be at least 1, so that at least half the window is
138               always kept; 3 is a common choice. If more than half the values in a window
139               are identical, the MAD is zero and any value that differs from
140               them is dropped. min_count counts values before outliers are
141               dropped.
142
143        interval - At what intervals (in seconds) should the interpolation
144               be computed?
145
146        window - Time window (in seconds) of data we should maintain
147               around the computation we're going to make.
148
149        data_id - What data id to assign to the output
150
151        metadata_interval - how many seconds between when we attach field metadata
152               to a record we send out.
153        ```
154
155        """
156        super().__init__(**kwargs)  # processes 'quiet' and type hints
157
158        self.field_spec = {}
159        self.source_fields = set()
160        if isinstance(field_spec, dict):
161            for result_field, entry in field_spec.items():
162                if 'source' in entry and 'algorithm' in entry:
163                    self.field_spec[result_field] = entry
164                    self.source_fields.add(entry.get('source'))
165                else:
166                    logging.warning('InterpolationTransform field definition for %s '
167                                    'must specify both "source" and "algorithm": %s',
168                                    result_field, entry)
169
170        # Alternate way of setting up a field spec that makes it easier to templatize.
171        # We'll expand the list of specs into a traditional field_spec
172        elif isinstance(field_spec, list):
173            for spec_instance in field_spec:
174                # Each spec_instance should be a dict of fields:, algorithm:,
175                # output_field_prefix: and window:
176                if not isinstance(spec_instance, dict):
177                    raise ValueError('InterpolationTransform: if field_spec is list, must be '
178                                     f'a list of dicts; found list of {type(spec_instance)}')
179                sources = spec_instance.get('sources')
180
181                if not isinstance(sources, list):
182                    raise ValueError('InterpolationTransform: sources for field spec must be '
183                                     f'a list; found {type(sources)}: {sources!r}')
184
185                # Expand source list into a traditional field_spec. Keys other
186                # than these (e.g. min_count) are options for the algorithm.
187                algorithm = spec_instance.get('algorithm')
188                window = spec_instance.get('window')
189                result_prefix = spec_instance.get('result_prefix')
190                options = {k: v for k, v in spec_instance.items()
191                           if k not in ('sources', 'algorithm', 'window', 'result_prefix')}
192                for source in sources:
193                    entry = {'source': source,
194                             'algorithm': {'type': algorithm, 'window': window, **options}}
195                    result_field = result_prefix + source
196                    self.field_spec[result_field] = entry
197
198                # Finally, stash sources so we know what to look for
199                self.source_fields.update(sources)
200
201        else:
202            raise ValueError('InterpolationTransform: field_spec must be either list '
203                             f'or dict. Found {type(field_spec)}')
204
205        for result_field, entry in self.field_spec.items():
206            _check_algorithm_options(result_field, entry.get('algorithm'))
207
208        self.interval = interval
209        self.window = window
210        self.data_id = data_id
211        self.metadata_interval = metadata_interval
212
213        # A dict of the cached values we're hanging onto - use sorted
214        # lists of (timestamp, value) pairs
215        self.cached_values = {f: [] for f in self.source_fields}
216
217        # The next timestamp we'd like to emit. Is set the first time we
218        # call transform().
219        self.next_timestamp = 0
220        self.earliest_timestamp = float('inf')  # Track earliest timestamp we've seen
221        self.latest_timestamp = 0
222        self.last_metadata_send = 0  # last time we've sent metadata
223
224        # For each exponential_average: (timestamp of the latest value it
225        # has taken in, the average then)
226        self.exponential_averages = {}
227
228    ############################
229    def fields(self):
230        """Which fields are we interested in to produce transformed data?"""
231        return list(self.source_fields)
232
233    ############################
234    def _metadata(self):
235        """Return a dict of metadata for our derived fields."""
236        metadata_fields = {
237            'field': {
238                'description':
239                    'Interpolated values of %s via %s' %
240                    (entry['source'], entry['algorithm']),
241                'device': 'InterpolationTransform',
242                'device_type': 'DerivedDataTransform',
243                'device_type_field': result_field
244            }
245            for result_field, entry in self.field_spec.items()
246        }
247        return metadata_fields
248
249    ############################
250    def _add_record(self, record):
251        """Cached the values contained in a new record, maintaining timestamp order."""
252        if type(record) not in [DASRecord, dict]:
253            logging.error('InterpolationTransform records must be dict or '
254                          'DASRecord. Received type %s: %s', type(record), record)
255            return 0
256
257        if type(record) is DASRecord:
258            timestamp = record.timestamp
259            fields = record.fields
260        else:
261            timestamp = record.get('timestamp', 0)
262            fields = record.get('fields')
263
264        if not fields:
265            logging.info('InterpolationTransform: record has no fields: %s', record)
266            return timestamp
267
268        # First, copy the new data into our cache.  NOTE: It's a judgment
269        # call whether it's more efficient to iterate over the fields
270        # we're looking for or the fields in the record.
271        for field, new_value in fields.items():
272            if field not in self.source_fields:
273                continue
274
275            # Examine the value we've gotten. If list, we assume it's [(ts,
276            # value), (ts, value),...]
277            if type(new_value) is list:
278                for ts, val in new_value.items():
279                    self._insert_sorted(field, ts, val)
280                    logging.debug(f'adding {ts}: {field} - {val}')
281
282            # If not list, assume DASRecord or simple field dict; add tuple
283            elif timestamp:
284                self._insert_sorted(field, timestamp, new_value)
285                logging.debug(f'adding {timestamp}: {field} - {new_value}')
286            else:
287                logging.warning('Interpolation found no timestamp in '
288                                'record: %s', record)
289
290        # Update our tracking of the earliest and latest timestamps we've seen
291        self.earliest_timestamp = min(self.earliest_timestamp, timestamp)
292        self.latest_timestamp = max(self.latest_timestamp, timestamp)
293
294        # Return the timestamp of the record
295        return timestamp
296
297    ############################
298    def _insert_sorted(self, field: str, timestamp: float, value: Any) -> None:
299        """Insert a (timestamp, value) pair into the sorted cached values for a field."""
300        cache = self.cached_values[field]
301
302        # Use binary search to find insertion position to maintain sorted order
303        timestamps = [ts for ts, _ in cache]
304        pos = bisect.bisect_left(timestamps, timestamp)
305
306        # Insert at correct position to maintain sort order
307        cache.insert(pos, (timestamp, value))
308
309    ############################
310    def _clean_cache(self):
311        """Remove values from cache that are too old to be useful."""
312        for field in self.source_fields:
313            # Iterate forward through field cache until we find a timestamp
314            # that is recent enough to keep
315            cache = self.cached_values[field]
316            lower_limit = self.next_timestamp - self.window / 2
317            keep_index = 0
318            while keep_index < len(cache) and cache[keep_index][0] < lower_limit:
319                keep_index += 1
320
321            # Throw away everything before that index
322            self.cached_values[field] = cache[keep_index:]
323
324    ############################
325    def _exponential_average(self, result_field, algorithm, values, timestamp):
326        """Bring result_field's exponential moving average up to timestamp,
327        taking in the values since the latest it has taken in, and return it
328        - or None if there is no recent value."""
329        latest, average = self.exponential_averages.get(result_field, (None, None))
330        time_constant = algorithm['time_constant']
331        try:
332            for ts, val in values:
333                if ts > timestamp:
334                    break
335                if _is_missing(val) or (latest is not None and ts <= latest):
336                    continue
337                if average is None:
338                    average = val
339                else:
340                    average += (1 - exp(-(ts - latest) / time_constant)) * (val - average)
341                latest = ts
342        except TypeError:
343            logging.error('Non-numeric value in interpolation list: %s', values)
344            return None
345        self.exponential_averages[result_field] = (latest, average)
346
347        # Don't go on reporting the average of a field that has stopped
348        if latest is None or timestamp - latest > (algorithm.get('window') or self.window):
349            return None
350        return average
351
352    ############################
353    def transform(self, record: Union[DASRecord, dict]):
354        """Incorporate any useable fields in this record, and if it gives
355        us any new interpolated values, aggregate and return them as a list of
356        dicts of the form:
357
358        [
359          {'timestamp': timestamp,
360           'fields': {
361             fieldname: value,
362             fieldname: value,
363             ...
364            }
365          },
366          {'timestamp': timestamp,
367           'fields': ...
368          }
369        ]
370
371        If there are insufficient data in the window to compute any
372        interpolation, return an empty list.
373        """
374        # See if it's something we can process, and if not, try digesting
375        if not self.can_process_record(record):  # inherited from BaseModule()
376            return self.digest_record(record)  # inherited from BaseModule()
377
378        # Add the record
379        self._add_record(record)
380
381        # First time through, our 'next_timestamp' will be zero. Set it to
382        # a good starting place.
383        if not self.next_timestamp:
384            self.next_timestamp = self.earliest_timestamp
385
386        # What fields do we have data for in our cache?
387        non_empty = {}
388        for dest, spec in self.field_spec.items():
389            source = spec.get('source')
390            if source:
391                values = self.cached_values.get(source, [])
392                if len(values):
393                    non_empty[dest] = [source, len(values)]
394
395        # Iterate through all timestamps up to the edge of what we can fit
396        # in our window without running into the edge of our latest timestamp.
397        results = []
398        logging.debug(f'latest timestamp: {self.latest_timestamp}, next: {self.next_timestamp}')
399        while self.next_timestamp < self.latest_timestamp - self.window / 2:
400            # Clean out old data
401            self._clean_cache()
402
403            result = {}
404            for result_field, entry in self.field_spec.items():
405                source = entry.get('source')
406                source_values = self.cached_values.get(source)
407                algorithm = entry.get('algorithm')
408                # logging.warning('%s->%s: %d values',
409                #                source, result_field, len(source_values))
410                if algorithm.get('type') == 'exponential_average':
411                    value = self._exponential_average(result_field, algorithm,
412                                                      source_values, self.next_timestamp)
413                else:
414                    value = interpolate(algorithm, source_values,
415                                        self.next_timestamp,
416                                        self.latest_timestamp)
417                if value is not None:
418                    result[result_field] = value
419            if result:
420                result_record = {'timestamp': self.next_timestamp, 'fields': result}
421                if self.data_id:
422                    result_record['data_id'] = self.data_id
423                results.append(result_record)
424            self.next_timestamp += self.interval
425
426        return results

Transform that computes interpolations of the specified variables.

InterpolationTransform( field_spec, interval, window, data_id=None, metadata_interval=None, **kwargs)
 23    def __init__(self, field_spec, interval, window,
 24                 data_id=None, metadata_interval=None, **kwargs):
 25        """
 26        ```
 27        field_spec - a dict of interpolated variables that are to be created,
 28                where the key is the new variable's name, and the value is a dict
 29                specifying the source field name and the algorithm that is to be
 30                used to do the interpolation. E.g.:
 31
 32               {
 33                 'AvgCNAVCourseTrue': {
 34                   'source': 'CNAVCourseTrue',
 35                   'algorithm': {
 36                     'type': 'boxcar_average',
 37                     'window': 30
 38                   },
 39                 },
 40                 'AvgCNAVGPSDay': {
 41                   'source': 'CNAVGPSDay',
 42                   'algorithm': { 'type': 'nearest' },
 43                 },
 44                 ...
 45               }
 46
 47               To simplify templating, can also accept a spec of the form
 48               of a list:
 49
 50               [
 51                 { sources: [MwxAirTemp, RTMPTemp, ...],
 52                   algorithm: boxcar_average,
 53                   window: 10,
 54                   result_prefix: Avg
 55                 },
 56                 { sources: [PortTrueWindDir, StbdTrueWindDir],
 57                   algorithm: polar_average,
 58                   window: 10,
 59                   result_prefix: Avg
 60                 }
 61               ]
 62
 63               Any other keys in a list entry, such as min_count, are passed
 64               to the algorithm along with its window.
 65
 66               Algorithms:
 67
 68                 boxcar_average - mean of the values within the window,
 69                       centred on the output time
 70                 polar_average - mean direction of angles (in degrees)
 71                       within the window, so that 359 and 1 average to 0
 72                 nearest - the value nearest the output time
 73                 median - median of the values within the window; unlike a
 74                       mean, unaffected by a few spikes or dropouts
 75                 trimmed_mean - mean of the values within the window after
 76                       dropping the highest and lowest; the option 'trim'
 77                       (default 0.1) is the fraction dropped from each end
 78                 time_weighted_average - mean of the values within the window,
 79                       each weighted by the time it covers (integrating
 80                       linearly between readings), so that a burst of
 81                       readings, or a gap, doesn't skew the mean as it does a
 82                       boxcar_average's. Readings are joined across a gap
 83                       left by missing values.
 84                 gaussian_average - values within the window weighted by
 85                       exp(-dt**2 / 2 sigma**2), dt being their distance from
 86                       the output time. Smoother than a boxcar, and doesn't
 87                       jump as a value enters or leaves the window. The option
 88                       'sigma' defaults to a sixth of the window, so that the
 89                       window spans 3 sigma either side
 90                 triangular_average - values within the window weighted from
 91                       1 at the output time down to 0 at the window's edges;
 92                       much like gaussian_average, and simpler
 93                 exponential_average - an exponential moving average, with
 94                       the option 'time_constant' (in seconds, required): each
 95                       new value moves the average by 1 - exp(-dt /
 96                       time_constant) of the way towards it, dt being the time
 97                       since the previous value. Unlike the other algorithms
 98                       it uses only values up to the output time, and remembers
 99                       the average from one output to the next, so its time
100                       constant can be longer than the window. Outputs are
101                       still delayed by half the transform's window, as all
102                       outputs are, so for a live display give it a transform
103                       of its own with a short window - but no shorter than
104                       twice the interval, or values may be discarded before
105                       it sees them. No value is output once the field's
106                       latest value is more than a window old.
107
108               Window statistics, for quality control. Each is an algorithm
109               of its own, so to output several statistics of a field, list
110               it once for each, with a different result_prefix:
111                 min, max - smallest and largest value within the window.
112                       max of a short-term average gives wind gusts: the
113                       WMO gust is the maximum 3-second average, i.e. max
114                       over the output of a 3-second boxcar_average
115                 std_dev - sample standard deviation of the values within
116                       the window; needs at least two values
117                 circular_std_dev - standard deviation of angles (in
118                       degrees) within the window, by the Yamartino method,
119                       so that values either side of 0/360 are close together
120                 count - how many valid values the window holds; 0, rather
121                       than no value, when it holds none
122
123               Missing values - None, or NaN as some instruments report when
124               they have no reading - are ignored by all of them, so one
125               missing reading doesn't make a whole average NaN. If a window
126               holds nothing but missing values, no value is output for it.
127
128               Every algorithm but nearest, count and exponential_average
129               also takes an optional
130               min_count (default 1): output no value for a window that holds
131               fewer than this many valid values, rather than reporting an
132               average of one or two readings as if the window were full.
133
134               boxcar_average, median, trimmed_mean, min, max and std_dev
135               also take an optional outlier_mads: before averaging, drop values more than this many
136               median absolute deviations (MADs) from the window's median.
137               It must be at least 1, so that at least half the window is
138               always kept; 3 is a common choice. If more than half the values in a window
139               are identical, the MAD is zero and any value that differs from
140               them is dropped. min_count counts values before outliers are
141               dropped.
142
143        interval - At what intervals (in seconds) should the interpolation
144               be computed?
145
146        window - Time window (in seconds) of data we should maintain
147               around the computation we're going to make.
148
149        data_id - What data id to assign to the output
150
151        metadata_interval - how many seconds between when we attach field metadata
152               to a record we send out.
153        ```
154
155        """
156        super().__init__(**kwargs)  # processes 'quiet' and type hints
157
158        self.field_spec = {}
159        self.source_fields = set()
160        if isinstance(field_spec, dict):
161            for result_field, entry in field_spec.items():
162                if 'source' in entry and 'algorithm' in entry:
163                    self.field_spec[result_field] = entry
164                    self.source_fields.add(entry.get('source'))
165                else:
166                    logging.warning('InterpolationTransform field definition for %s '
167                                    'must specify both "source" and "algorithm": %s',
168                                    result_field, entry)
169
170        # Alternate way of setting up a field spec that makes it easier to templatize.
171        # We'll expand the list of specs into a traditional field_spec
172        elif isinstance(field_spec, list):
173            for spec_instance in field_spec:
174                # Each spec_instance should be a dict of fields:, algorithm:,
175                # output_field_prefix: and window:
176                if not isinstance(spec_instance, dict):
177                    raise ValueError('InterpolationTransform: if field_spec is list, must be '
178                                     f'a list of dicts; found list of {type(spec_instance)}')
179                sources = spec_instance.get('sources')
180
181                if not isinstance(sources, list):
182                    raise ValueError('InterpolationTransform: sources for field spec must be '
183                                     f'a list; found {type(sources)}: {sources!r}')
184
185                # Expand source list into a traditional field_spec. Keys other
186                # than these (e.g. min_count) are options for the algorithm.
187                algorithm = spec_instance.get('algorithm')
188                window = spec_instance.get('window')
189                result_prefix = spec_instance.get('result_prefix')
190                options = {k: v for k, v in spec_instance.items()
191                           if k not in ('sources', 'algorithm', 'window', 'result_prefix')}
192                for source in sources:
193                    entry = {'source': source,
194                             'algorithm': {'type': algorithm, 'window': window, **options}}
195                    result_field = result_prefix + source
196                    self.field_spec[result_field] = entry
197
198                # Finally, stash sources so we know what to look for
199                self.source_fields.update(sources)
200
201        else:
202            raise ValueError('InterpolationTransform: field_spec must be either list '
203                             f'or dict. Found {type(field_spec)}')
204
205        for result_field, entry in self.field_spec.items():
206            _check_algorithm_options(result_field, entry.get('algorithm'))
207
208        self.interval = interval
209        self.window = window
210        self.data_id = data_id
211        self.metadata_interval = metadata_interval
212
213        # A dict of the cached values we're hanging onto - use sorted
214        # lists of (timestamp, value) pairs
215        self.cached_values = {f: [] for f in self.source_fields}
216
217        # The next timestamp we'd like to emit. Is set the first time we
218        # call transform().
219        self.next_timestamp = 0
220        self.earliest_timestamp = float('inf')  # Track earliest timestamp we've seen
221        self.latest_timestamp = 0
222        self.last_metadata_send = 0  # last time we've sent metadata
223
224        # For each exponential_average: (timestamp of the latest value it
225        # has taken in, the average then)
226        self.exponential_averages = {}
field_spec - a dict of interpolated variables that are to be created,
        where the key is the new variable's name, and the value is a dict
        specifying the source field name and the algorithm that is to be
        used to do the interpolation. E.g.:

       {
         'AvgCNAVCourseTrue': {
           'source': 'CNAVCourseTrue',
           'algorithm': {
             'type': 'boxcar_average',
             'window': 30
           },
         },
         'AvgCNAVGPSDay': {
           'source': 'CNAVGPSDay',
           'algorithm': { 'type': 'nearest' },
         },
         ...
       }

       To simplify templating, can also accept a spec of the form
       of a list:

       [
         { sources: [MwxAirTemp, RTMPTemp, ...],
           algorithm: boxcar_average,
           window: 10,
           result_prefix: Avg
         },
         { sources: [PortTrueWindDir, StbdTrueWindDir],
           algorithm: polar_average,
           window: 10,
           result_prefix: Avg
         }
       ]

       Any other keys in a list entry, such as min_count, are passed
       to the algorithm along with its window.

       Algorithms:

         boxcar_average - mean of the values within the window,
               centred on the output time
         polar_average - mean direction of angles (in degrees)
               within the window, so that 359 and 1 average to 0
         nearest - the value nearest the output time
         median - median of the values within the window; unlike a
               mean, unaffected by a few spikes or dropouts
         trimmed_mean - mean of the values within the window after
               dropping the highest and lowest; the option 'trim'
               (default 0.1) is the fraction dropped from each end
         time_weighted_average - mean of the values within the window,
               each weighted by the time it covers (integrating
               linearly between readings), so that a burst of
               readings, or a gap, doesn't skew the mean as it does a
               boxcar_average's. Readings are joined across a gap
               left by missing values.
         gaussian_average - values within the window weighted by
               exp(-dt**2 / 2 sigma**2), dt being their distance from
               the output time. Smoother than a boxcar, and doesn't
               jump as a value enters or leaves the window. The option
               'sigma' defaults to a sixth of the window, so that the
               window spans 3 sigma either side
         triangular_average - values within the window weighted from
               1 at the output time down to 0 at the window's edges;
               much like gaussian_average, and simpler
         exponential_average - an exponential moving average, with
               the option 'time_constant' (in seconds, required): each
               new value moves the average by 1 - exp(-dt /
               time_constant) of the way towards it, dt being the time
               since the previous value. Unlike the other algorithms
               it uses only values up to the output time, and remembers
               the average from one output to the next, so its time
               constant can be longer than the window. Outputs are
               still delayed by half the transform's window, as all
               outputs are, so for a live display give it a transform
               of its own with a short window - but no shorter than
               twice the interval, or values may be discarded before
               it sees them. No value is output once the field's
               latest value is more than a window old.

       Window statistics, for quality control. Each is an algorithm
       of its own, so to output several statistics of a field, list
       it once for each, with a different result_prefix:
         min, max - smallest and largest value within the window.
               max of a short-term average gives wind gusts: the
               WMO gust is the maximum 3-second average, i.e. max
               over the output of a 3-second boxcar_average
         std_dev - sample standard deviation of the values within
               the window; needs at least two values
         circular_std_dev - standard deviation of angles (in
               degrees) within the window, by the Yamartino method,
               so that values either side of 0/360 are close together
         count - how many valid values the window holds; 0, rather
               than no value, when it holds none

       Missing values - None, or NaN as some instruments report when
       they have no reading - are ignored by all of them, so one
       missing reading doesn't make a whole average NaN. If a window
       holds nothing but missing values, no value is output for it.

       Every algorithm but nearest, count and exponential_average
       also takes an optional
       min_count (default 1): output no value for a window that holds
       fewer than this many valid values, rather than reporting an
       average of one or two readings as if the window were full.

       boxcar_average, median, trimmed_mean, min, max and std_dev
       also take an optional outlier_mads: before averaging, drop values more than this many
       median absolute deviations (MADs) from the window's median.
       It must be at least 1, so that at least half the window is
       always kept; 3 is a common choice. If more than half the values in a window
       are identical, the MAD is zero and any value that differs from
       them is dropped. min_count counts values before outliers are
       dropped.

interval - At what intervals (in seconds) should the interpolation
       be computed?

window - Time window (in seconds) of data we should maintain
       around the computation we're going to make.

data_id - What data id to assign to the output

metadata_interval - how many seconds between when we attach field metadata
       to a record we send out.
field_spec
source_fields
interval
window
data_id
metadata_interval
cached_values
next_timestamp
earliest_timestamp
latest_timestamp
last_metadata_send
exponential_averages
def fields(self):
229    def fields(self):
230        """Which fields are we interested in to produce transformed data?"""
231        return list(self.source_fields)

Which fields are we interested in to produce transformed data?

def transform(self, record: Union[logger.utils.das_record.DASRecord, dict]):
353    def transform(self, record: Union[DASRecord, dict]):
354        """Incorporate any useable fields in this record, and if it gives
355        us any new interpolated values, aggregate and return them as a list of
356        dicts of the form:
357
358        [
359          {'timestamp': timestamp,
360           'fields': {
361             fieldname: value,
362             fieldname: value,
363             ...
364            }
365          },
366          {'timestamp': timestamp,
367           'fields': ...
368          }
369        ]
370
371        If there are insufficient data in the window to compute any
372        interpolation, return an empty list.
373        """
374        # See if it's something we can process, and if not, try digesting
375        if not self.can_process_record(record):  # inherited from BaseModule()
376            return self.digest_record(record)  # inherited from BaseModule()
377
378        # Add the record
379        self._add_record(record)
380
381        # First time through, our 'next_timestamp' will be zero. Set it to
382        # a good starting place.
383        if not self.next_timestamp:
384            self.next_timestamp = self.earliest_timestamp
385
386        # What fields do we have data for in our cache?
387        non_empty = {}
388        for dest, spec in self.field_spec.items():
389            source = spec.get('source')
390            if source:
391                values = self.cached_values.get(source, [])
392                if len(values):
393                    non_empty[dest] = [source, len(values)]
394
395        # Iterate through all timestamps up to the edge of what we can fit
396        # in our window without running into the edge of our latest timestamp.
397        results = []
398        logging.debug(f'latest timestamp: {self.latest_timestamp}, next: {self.next_timestamp}')
399        while self.next_timestamp < self.latest_timestamp - self.window / 2:
400            # Clean out old data
401            self._clean_cache()
402
403            result = {}
404            for result_field, entry in self.field_spec.items():
405                source = entry.get('source')
406                source_values = self.cached_values.get(source)
407                algorithm = entry.get('algorithm')
408                # logging.warning('%s->%s: %d values',
409                #                source, result_field, len(source_values))
410                if algorithm.get('type') == 'exponential_average':
411                    value = self._exponential_average(result_field, algorithm,
412                                                      source_values, self.next_timestamp)
413                else:
414                    value = interpolate(algorithm, source_values,
415                                        self.next_timestamp,
416                                        self.latest_timestamp)
417                if value is not None:
418                    result[result_field] = value
419            if result:
420                result_record = {'timestamp': self.next_timestamp, 'fields': result}
421                if self.data_id:
422                    result_record['data_id'] = self.data_id
423                results.append(result_record)
424            self.next_timestamp += self.interval
425
426        return results

Incorporate any useable fields in this record, and if it gives us any new interpolated values, aggregate and return them as a list of dicts of the form:

[ {'timestamp': timestamp, 'fields': { fieldname: value, fieldname: value, ... } }, {'timestamp': timestamp, 'fields': ... } ]

If there are insufficient data in the window to compute any interpolation, return an empty list.

OUTLIER_ALGORITHMS = ('boxcar_average', 'median', 'trimmed_mean', 'min', 'max', 'std_dev')
WINDOW_STATISTICS = ('min', 'max', 'std_dev', 'circular_std_dev', 'count')
def interpolate(algorithm, values, timestamp, now):
519def interpolate(algorithm, values, timestamp, now):
520    """An omnibus routine for taking a list of timestamped values, a
521    specification of an averaging algorithm, and returning a value
522    computed at the specified timestamp. Returns None if there aren't
523    enough data to compute a value.
524
525    algorithm    A dict specifying the algorithm to be used: its 'type', and
526                 options such as 'window' and 'min_count'
527
528                 Missing values (None or NaN) are ignored by every algorithm.
529
530    values       A list of [(timestamp, value),...] pairs
531
532    timestamp    The timestamp for which interpolation should be computed
533
534    now          Timestamp now. This should be used to determine whether
535                 we're far enough beyond our timestamp to compute a value.
536    """
537    if not type(algorithm) is dict:
538        logging.warning('Function interpolate() handed non-dict algorithm '
539                        'specification: %s', algorithm)
540        return None
541    # Ignore missing values: None, or NaN as some instruments send when
542    # they have no reading. Otherwise one of them would make a whole
543    # average NaN, or be returned as the nearest value.
544    values = [(ts, val) for ts, val in values if not _is_missing(val)]
545    if not values:
546        logging.debug('Function interpolate() has no values to work with')
547        # An empty window is exactly what count is there to report
548        return 0 if algorithm.get('type') == 'count' else None
549
550    ##################
551    # Select algorithm
552    alg_type = algorithm.get('type')
553    min_count = algorithm.get('min_count') or 1
554
555    # boxcar_average: all values within symmetric interval window get
556    # same weight.
557    if alg_type == 'boxcar_average':
558        window = algorithm.get('window', 10)  # How far back/forward to average
559        lower_limit = timestamp - window / 2
560        upper_limit = timestamp + window / 2
561        vals_to_average = [val for ts, val in values
562                           if ts >= lower_limit and ts <= upper_limit]
563        if len(vals_to_average) < min_count:
564            return None
565
566        try:
567            outlier_mads = algorithm.get('outlier_mads')
568            if outlier_mads:
569                vals_to_average = _reject_outliers(vals_to_average, outlier_mads)
570                if not vals_to_average:
571                    return None
572            return mean(vals_to_average)
573        except TypeError:
574            logging.error('Non-numeric value in interpolation list: %s', vals_to_average)
575            return None
576
577    # nearest: return value of nearest timestamp. Note that we assume
578    # timestamps are in order, so once distance starts going up, we're
579    # done.
580    if alg_type == 'nearest':
581        best_distance = float('inf')
582        value = None
583        for i in range(len(values)):
584            ts, ts_value = values[i]
585            distance = abs(ts - timestamp)
586            if distance <= best_distance:
587                best_distance = distance
588                value = ts_value
589            else:
590                break
591        return value
592
593    # polar_average: interpret as an angle in degrees. Convert to points
594    # on a unit circle and return the angle of their centroid from the origin.
595    if alg_type == 'polar_average':
596        window = algorithm.get('window', 10)  # How far back/forward to average
597        lower_limit = timestamp - window / 2
598        upper_limit = timestamp + window / 2
599        vals_to_average = [val for ts, val in values
600                           if ts >= lower_limit and ts <= upper_limit]
601        if len(vals_to_average) < min_count:
602            return None
603
604        try:
605            val_radians = [radians(val) for val in vals_to_average]
606            x_mean = mean([sin(val) for val in val_radians])
607            y_mean = mean([cos(val) for val in val_radians])
608            angle = degrees(atan2(x_mean, y_mean))
609            if angle < 0:
610                angle += 360
611            # A tiny negative angle (rounding error when angles cancel
612            # around north) plus 360 rounds to exactly 360.0
613            if angle >= 360:
614                angle -= 360
615            return angle
616        except (TypeError, ValueError):  # ValueError: sin() or cos() of inf
617            logging.error('Non-numeric or infinite value in interpolation list: %s',
618                          vals_to_average)
619            return None
620
621    # median and trimmed_mean: robust to a few spikes or dropouts.
622    if alg_type in ('median', 'trimmed_mean'):
623        window = algorithm.get('window', 10)  # How far back/forward to look
624        lower_limit = timestamp - window / 2
625        upper_limit = timestamp + window / 2
626        vals_to_average = [val for ts, val in values
627                           if ts >= lower_limit and ts <= upper_limit]
628        if len(vals_to_average) < min_count:
629            return None
630
631        try:
632            outlier_mads = algorithm.get('outlier_mads')
633            if outlier_mads:
634                vals_to_average = _reject_outliers(vals_to_average, outlier_mads)
635                if not vals_to_average:
636                    return None
637            if alg_type == 'median':
638                return median(vals_to_average)
639
640            vals_to_average = sorted(vals_to_average)
641            drop = int(len(vals_to_average) * algorithm.get('trim', 0.1))
642            if drop:
643                vals_to_average = vals_to_average[drop:-drop]
644            return mean(vals_to_average)
645        except TypeError:
646            logging.error('Non-numeric value in interpolation list: %s', vals_to_average)
647            return None
648
649    # time_weighted_average: integrate linearly between readings (the
650    # trapezoidal rule) and divide by the time they span, so each value
651    # counts for the time it covers rather than once.
652    if alg_type == 'time_weighted_average':
653        window = algorithm.get('window', 10)  # How far back/forward to average
654        lower_limit = timestamp - window / 2
655        upper_limit = timestamp + window / 2
656        in_window = [(ts, val) for ts, val in values
657                     if ts >= lower_limit and ts <= upper_limit]
658        if len(in_window) < min_count:
659            return None
660
661        try:
662            span = in_window[-1][0] - in_window[0][0]
663            if not span:  # all at one time, so no time to weight them by
664                return mean([val for ts, val in in_window])
665            area = sum((ts_1 - ts_0) * (val_0 + val_1) / 2
666                       for (ts_0, val_0), (ts_1, val_1) in zip(in_window, in_window[1:]))
667            return area / span
668        except TypeError:
669            logging.error('Non-numeric value in interpolation list: %s', in_window)
670            return None
671
672    # gaussian_average and triangular_average: weight values by their
673    # distance from the output time.
674    if alg_type in ('gaussian_average', 'triangular_average'):
675        window = algorithm.get('window', 10)  # How far back/forward to average
676        lower_limit = timestamp - window / 2
677        upper_limit = timestamp + window / 2
678        in_window = [(ts, val) for ts, val in values
679                     if ts >= lower_limit and ts <= upper_limit]
680        if len(in_window) < min_count:
681            return None
682
683        if alg_type == 'gaussian_average':
684            sigma = algorithm.get('sigma') or window / 6
685            weights = [exp(-(ts - timestamp) ** 2 / (2 * sigma ** 2))
686                       for ts, val in in_window]
687        else:
688            weights = [1 - abs(ts - timestamp) / (window / 2) for ts, val in in_window]
689        total_weight = sum(weights)
690        if not total_weight:  # e.g. a triangle's only values at its very edges
691            return None
692        try:
693            return sum(weight * val for weight, (ts, val)
694                       in zip(weights, in_window)) / total_weight
695        except TypeError:
696            logging.error('Non-numeric value in interpolation list: %s', in_window)
697            return None
698
699    # Window statistics, for quality control
700    if alg_type in WINDOW_STATISTICS:
701        window = algorithm.get('window', 10)  # How far back/forward to look
702        lower_limit = timestamp - window / 2
703        upper_limit = timestamp + window / 2
704        vals_in_window = [val for ts, val in values
705                          if ts >= lower_limit and ts <= upper_limit]
706        if alg_type == 'count':
707            return len(vals_in_window)
708        if len(vals_in_window) < min_count:
709            return None
710
711        try:
712            outlier_mads = algorithm.get('outlier_mads')
713            if outlier_mads:
714                vals_in_window = _reject_outliers(vals_in_window, outlier_mads)
715                if not vals_in_window:
716                    return None
717            if alg_type == 'min':
718                return min(vals_in_window)
719            if alg_type == 'max':
720                return max(vals_in_window)
721            if alg_type == 'std_dev':
722                return stdev(vals_in_window) if len(vals_in_window) > 1 else None
723            return _circular_std_dev(vals_in_window)
724        except (TypeError, ValueError):  # ValueError: sin() or cos() of inf
725            logging.error('Non-numeric or infinite value in interpolation list: %s',
726                          vals_in_window)
727            return None
728
729    # Not an algorithm we recognize
730    else:
731        logging.warning('Function interpolate() received unrecognized algorithm '
732                        'type: %s', alg_type)
733        return None

An omnibus routine for taking a list of timestamped values, a specification of an averaging algorithm, and returning a value computed at the specified timestamp. Returns None if there aren't enough data to compute a value.

algorithm A dict specifying the algorithm to be used: its 'type', and options such as 'window' and 'min_count'

         Missing values (None or NaN) are ignored by every algorithm.

values A list of [(timestamp, value),...] pairs

timestamp The timestamp for which interpolation should be computed

now Timestamp now. This should be used to determine whether we're far enough beyond our timestamp to compute a value.