openrvdas.logger.transforms.computed_fields_transform

Compute record fields from algebraic expressions over other fields.

See issue #643. This is the general case of ModifyValueTransform, which remains in place for the linear slope/offset case it already serves.

  1#!/usr/bin/env python3
  2"""Compute record fields from algebraic expressions over other fields.
  3
  4See issue #643. This is the general case of ModifyValueTransform, which
  5remains in place for the linear slope/offset case it already serves.
  6"""
  7
  8import copy
  9import logging
 10import math
 11import time
 12from typing import Union
 13
 14# Don't break the whole transforms package if this import somehow fails -
 15# logger/transforms/__init__.py imports this module unconditionally, so an
 16# import error here would take every transform down with it. Complain only
 17# when someone actually tries to use this transform.
 18#
 19# NOTE: ast is in the standard library, so unlike the guards around paho-mqtt
 20# or geopandas this is belt-and-braces rather than an optional dependency. It
 21# is here to keep the failure local, and so that the whitelist below has
 22# somewhere to degrade to.
 23try:
 24    import ast
 25    AST_MODULE_FOUND = True
 26except ModuleNotFoundError:
 27    AST_MODULE_FOUND = False
 28
 29from logger.utils.das_record import DASRecord  # noqa: E402
 30from logger.transforms.derived_data_transform import DerivedDataTransform  # noqa: E402
 31
 32
 33################################################################################
 34# Safe expression evaluation.
 35#
 36# There is no eval() anywhere else in logger/ or server/, so this is the
 37# codebase's first, and the bar is correspondingly high. The approach is an
 38# allowlist: parse to an AST, reject any node type not explicitly permitted,
 39# then evaluate with no builtins and only the names we supply.
 40#
 41# The single most important exclusion is ast.Attribute. Attribute access is
 42# the standard sandbox escape - (1).__class__.__mro__[1].__subclasses__()
 43# walks from a literal to arbitrary classes and from there to os - so an
 44# allowlist that permits it is not a sandbox at all. Emptying __builtins__ is
 45# necessary but nowhere near sufficient on its own.
 46
 47if AST_MODULE_FOUND:
 48    # Node types an expression may contain. Everything else is refused.
 49    ALLOWED_NODES = (
 50        ast.Expression,
 51        ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.Compare, ast.IfExp,
 52        ast.Call, ast.Name, ast.Load, ast.Constant,
 53    )
 54
 55    # Operators. Mod is here for angular wrapping, e.g. "(dir + offset) % 360".
 56    ALLOWED_OPS = (
 57        ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.Pow,
 58        ast.USub, ast.UAdd, ast.Not,
 59        ast.And, ast.Or,
 60        ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE,
 61    )
 62else:
 63    # Nothing is permitted without a parser to check it against.
 64    ALLOWED_NODES = ()
 65    ALLOWED_OPS = ()
 66
 67# Functions an expression may call. Chosen to cover the calibration maths
 68# that actually comes up: exp/log for dissolved oxygen saturation, sin and
 69# radians for the latitude term in pressure-to-depth, atan2 for angles.
 70SAFE_FUNCTIONS = {
 71    'abs': abs, 'min': min, 'max': max, 'round': round, 'pow': pow,
 72    'int': int, 'float': float,
 73    'exp': math.exp, 'log': math.log, 'log10': math.log10, 'sqrt': math.sqrt,
 74    'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
 75    'asin': math.asin, 'acos': math.acos, 'atan': math.atan,
 76    'atan2': math.atan2, 'hypot': math.hypot,
 77    'degrees': math.degrees, 'radians': math.radians,
 78    'floor': math.floor, 'ceil': math.ceil, 'fmod': math.fmod,
 79}
 80
 81SAFE_CONSTANTS = {'pi': math.pi, 'e': math.e}
 82
 83# Resource guards. An AST allowlist does not catch exhaustion: 9**9**9 is a
 84# perfectly ordinary BinOp that will hang the logger and eat all its memory.
 85MAX_EXPRESSION_LENGTH = 1000
 86MAX_EXPRESSION_NODES = 250
 87MAX_EXPONENT = 64
 88
 89
 90class UnsafeExpressionError(ValueError):
 91    """Raised when an expression contains something we refuse to evaluate."""
 92
 93
 94def validate_expression(expression, where='', functions=None):
 95    """Parse an expression and refuse anything not on the allowlist.
 96
 97    Returns the parsed ast.Expression. Raises UnsafeExpressionError with a
 98    message naming the offending construct otherwise.
 99
100    'functions' is the set of callable names the expression may use. It
101    defaults to SAFE_FUNCTIONS; a ComputedFieldsTransform subclass that widens
102    its FUNCTIONS table passes that in, so that validation and evaluation agree
103    about what exists. They must agree: a name permitted here but absent at
104    evaluation would fail per record instead of at startup, and a name
105    available at evaluation but refused here could never be reached.
106    """
107    if functions is None:
108        functions = SAFE_FUNCTIONS
109    if not AST_MODULE_FOUND:
110        raise RuntimeError('Expression evaluation is not available: could not '
111                           'import the standard library "ast" module, so there '
112                           'is no way to check an equation before running it.')
113
114    prefix = f'{where}: ' if where else ''
115
116    if not isinstance(expression, str):
117        raise UnsafeExpressionError(f'{prefix}equation must be a string, '
118                                    f'got {type(expression).__name__}')
119    if len(expression) > MAX_EXPRESSION_LENGTH:
120        raise UnsafeExpressionError(
121            f'{prefix}equation is {len(expression)} characters; the limit is '
122            f'{MAX_EXPRESSION_LENGTH}. A calibration this long probably wants '
123            f'to be several fields.')
124    try:
125        tree = ast.parse(expression, mode='eval')
126    except SyntaxError as e:
127        raise UnsafeExpressionError(f'{prefix}could not parse equation '
128                                    f'"{expression}": {e}')
129
130    nodes = list(ast.walk(tree))
131    if len(nodes) > MAX_EXPRESSION_NODES:
132        raise UnsafeExpressionError(
133            f'{prefix}equation has {len(nodes)} nodes; the limit is '
134            f'{MAX_EXPRESSION_NODES}')
135
136    for node in nodes:
137        if isinstance(node, ALLOWED_OPS):
138            continue
139        if not isinstance(node, ALLOWED_NODES):
140            raise UnsafeExpressionError(
141                f'{prefix}{type(node).__name__} is not allowed in an equation. '
142                f'Equations may use arithmetic, comparisons, conditional '
143                f'expressions and the functions '
144                f'{", ".join(sorted(functions))}.')
145
146        if isinstance(node, ast.Call):
147            # Only direct calls to whitelisted names. No attribute calls, no
148            # computed callables, no **kwargs smuggling.
149            if not isinstance(node.func, ast.Name):
150                raise UnsafeExpressionError(
151                    f'{prefix}only direct calls to named functions are allowed')
152            if node.func.id not in functions:
153                raise UnsafeExpressionError(
154                    f'{prefix}unknown function "{node.func.id}". Available: '
155                    f'{", ".join(sorted(functions))}')
156            if node.keywords:
157                raise UnsafeExpressionError(
158                    f'{prefix}keyword arguments are not allowed in equations')
159
160        if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
161            # Guard exhaustion. The exponent must be a literal number within
162            # reach, which rules out 9**9**9 (exponent is itself a BinOp) and
163            # 9**999999. Variable exponents are not supported; no calibration
164            # polynomial we have seen needs one.
165            exponent = node.right
166            if not (isinstance(exponent, ast.Constant)
167                    and isinstance(exponent.value, (int, float))):
168                raise UnsafeExpressionError(
169                    f'{prefix}the exponent of ** must be a literal number')
170            if abs(exponent.value) > MAX_EXPONENT:
171                raise UnsafeExpressionError(
172                    f'{prefix}exponent {exponent.value} exceeds the limit of '
173                    f'{MAX_EXPONENT}')
174
175    return tree
176
177
178def expression_names(tree):
179    """Every name an expression reads, in source order of first appearance."""
180    names = []
181    for node in ast.walk(tree):
182        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
183            if node.id not in names:
184                names.append(node.id)
185    return names
186
187
188################################################################################
189class ComputedFieldsTransform(DerivedDataTransform):
190    """Compute new record fields from algebraic expressions over existing ones.
191
192    The callables and named constants an equation may use are class attributes,
193    so a subclass can widen them without touching this module - and without
194    this module acquiring the subclass's dependencies:
195
196        class GSWComputedFieldsTransform(ComputedFieldsTransform):
197            FUNCTIONS = {**ComputedFieldsTransform.FUNCTIONS,
198                         'gsw_z_from_p': gsw.z_from_p}
199
200    Names must be flat. Attribute access is refused by the expression checker -
201    it is the main sandbox escape - so "gsw.z_from_p(...)" could never parse.
202
203    A subclass adding functions that can return NaN rather than raising, as the
204    TEOS-10 routines do, should guard against that: everything in the default
205    table raises on bad input, so a NaN would otherwise travel quietly into the
206    data stream.
207    """
208
209    # Widen these in a subclass, not in place.
210    FUNCTIONS = SAFE_FUNCTIONS
211    CONSTANTS = SAFE_CONSTANTS
212
213    def __init__(self, fields,
214                 delete_input_fields=False, delete_other_fields=False,
215                 warn_missing_inputs=False,
216                 cache_inputs=False, update_on_fields=None, max_field_age=None,
217                 data_id=None, metadata_interval=None, **kwargs):
218        """
219        ```
220        fields
221            A dict of the fields to compute, keyed by the name of the field to
222            be *produced*. Note that this is the opposite of
223            ModifyValueTransform, which keys by input field; keying by output
224            is what lets a single rule draw on several inputs.
225
226            fields:
227              SeawaterTempCorrected:
228                equation: "sbe38_slope * SeawaterTemp + sbe38_offset"
229                constants:
230                  sbe38_slope:  1.00021
231                  sbe38_offset: -0.0032
232                metadata: SBE38 with linear calibration applied
233
234              DepthCorrected:
235                equation: "(Pressure - (10.1325 if pressure_is_absolute else 0))
236                           * conv_coefficient"
237                constants:
238                  pressure_is_absolute: true
239                  conv_coefficient: 1.0
240
241              SoundVelocity:
242                equation: "1449.2 + 4.6*T - 0.055*T**2 + 1.39*(S-35) + 0.016*D"
243                inputs: {T: SeawaterTemp, S: Salinity, D: Depth}
244                delete_input_fields: true
245
246            Per-rule keys:
247
248            equation (required)
249                The expression to evaluate. Bare names refer to record fields,
250                to the results of rules listed before this one, to entries in
251                'constants', to entries in 'inputs', or to one of the functions
252                listed under "Writing equations" below.
253
254            constants (default {})
255                Values to make available to the equation by name. These may be
256                numbers, booleans or strings. A constant whose value is null
257                disables the rule - the usual way to say "this device is not
258                calibrated" without having to remove the logger.
259
260            inputs (default {})
261                Optional alias -> field name mapping, so that a standard formula
262                can be written in textbook notation and pointed at
263                differently-named fields. Purely for readability; bare field
264                names work without it.
265
266            delete_input_fields (default: the transform-wide setting)
267                Whether the fields this rule read should be dropped from the
268                result.
269
270            intermediate (default False)
271                If true, this rule's result is available to the rules listed
272                after it, but is not added to the output. See "Rules in
273                sequence" below.
274
275            metadata (default None)
276                Metadata to attach for the computed field. Ignored for an
277                intermediate rule.
278
279        delete_input_fields (default False)
280            Drop the fields that equations read from the result.
281
282        delete_other_fields (default False)
283            Drop the fields that no equation read from the result.
284
285            The two flags are independent, and all four combinations are
286            useful:
287
288              False/False  record plus computed values - enhancing an inline
289                           data stream, the default
290              True/False   calibrate in place, leaving the rest of the record
291              True/True    computed values only - reading from a CachedDataServer,
292                           computing, and writing back
293              False/True   computed values plus the inputs they used
294
295            If you want something in between - computed values plus a couple of
296            identifying fields - compose with SelectFieldsTransform downstream
297            rather than reaching for another option here.
298
299        warn_missing_inputs (default False)
300            Whether to warn when a rule cannot fire because its inputs are
301            absent. False by default because a stream may carry many record
302            types, only some of which have the fields a given rule wants; on a
303            mixed stream the normal case would otherwise warn on nearly every
304            record. Regardless of this setting, a debug message is emitted when
305            *some* of a rule's inputs are present and others are missing, which
306            is the genuinely suspicious case. 'quiet' suppresses the warning
307            even when this is set.
308
309        cache_inputs (default False)
310            Retain the most recent value of each input field across records, so
311            that an equation can combine readings that arrive in separate
312            records - which is what happens when inputs come from different
313            instruments by way of a CachedDataServer. Implied by
314            update_on_fields or max_field_age.
315
316        update_on_fields (default None)
317            A list of field names; compute only when a record carries one of
318            them. Without this, every record that completes a rule's inputs
319            produces a new value, so a correction drawing on a slow-moving
320            secondary input would re-emit each time that input ticked rather
321            than when a new primary reading arrived.
322
323        max_field_age (default None)
324            A dict of field name -> seconds. A cached value older than its
325            limit counts as missing, so a rule will not fire on it. Fields not
326            named here never expire.
327
328            update_on_fields and max_field_age follow TrueWindsTransform, which
329            has the same two options with the same meanings.
330
331        data_id (default None)
332            data_id to assign to the result, if the record does not carry one.
333
334        metadata_interval (default None)
335            If set, how often in seconds to attach field metadata to records.
336
337        Writing equations
338        -----------------
339        An equation may use arithmetic (+ - * / // % **), comparisons, boolean
340        operators, and conditional expressions ("x if cond else y"). Field
341        values are passed through as they arrive and are not coerced, so a
342        field holding 'N' or 'S' can be compared as a string.
343
344        These functions are available:
345
346                abs acos asin atan atan2 ceil cos degrees exp float floor
347                fmod hypot int log log10 max min pow radians round sin sqrt
348                tan
349
350        along with the constants pi and e.
351
352        The exponent of ** must be a literal number, and at most 64. This is a
353        deliberate guard rather than an oversight: "9**9**9" is otherwise an
354        ordinary expression that would hang the logger and exhaust its memory.
355
356        Rules in sequence
357        -----------------
358        Rules are evaluated in the order they are listed, and an equation can
359        use the result of any rule listed before it, by that rule's name (or
360        through an alias in 'inputs'). Mark a rule "intermediate: true" to use
361        its result in later rules without outputting it:
362
363            fields:
364              x:
365                equation: "wspd * cos(radians(270 - wdir))"
366                intermediate: true
367              y:
368                equation: "wspd * sin(radians(270 - wdir))"
369                intermediate: true
370              WindSpeed:
371                equation: "hypot(x, y)"
372
373        If an earlier rule produces no value for a record - because its inputs
374        are missing, or its equation gives None, or it is disabled by a null
375        constant - then no rule that uses its result fires either. So an
376        intermediate rule such as
377
378              valid:
379                equation: "True if 0 <= heading <= 360 else None"
380                intermediate: true
381
382        lets a later rule compute only from sensible inputs by mentioning it:
383        "(heading + offset) % 360 if valid else None".
384
385        A name matching a rule listed *after* the one using it is not that
386        rule's result: it is read from the record. That is what lets a rule
387        use a raw value that a later rule replaces in place, but as it is more
388        often a rule listed in the wrong order, it is logged as a warning when
389        the transform starts.
390
391        test/configs/computed_true_winds.yaml is a worked example: true winds,
392        computed with the formulas TrueWindsTransform uses.
393
394        Equations are checked when the transform is constructed, not per
395        record, so a typo or a refused construct stops the logger at startup
396        rather than failing quietly mid-cruise - and validate_config can catch
397        it before anyone sails. They are not eval()'d naively: the expression
398        is parsed and every construct checked against an allowlist, with no
399        builtins and no attribute access.
400
401        To make further functions available - the TEOS-10 routines in gsw, for
402        instance - subclass this transform and widen its FUNCTIONS table rather
403        than editing it in place. See the class docstring.
404        ```
405        """
406        super().__init__(**kwargs)  # processes 'quiet' and type hints
407
408        if not AST_MODULE_FOUND:
409            raise RuntimeError('ComputedFieldsTransform is not available: '
410                               'could not import the standard library "ast" '
411                               'module, which is needed to parse and check '
412                               'equations before they are evaluated.')
413
414        if not isinstance(fields, dict) or not fields:
415            raise ValueError('ComputedFieldsTransform requires a non-empty '
416                             '"fields" dict, keyed by the name of each field '
417                             'to be computed.')
418
419        self.delete_input_fields = delete_input_fields
420        self.delete_other_fields = delete_other_fields
421        self.warn_missing_inputs = warn_missing_inputs
422        self.data_id = data_id
423        self.metadata_interval = metadata_interval or 0
424        self.last_metadata_send = 0
425
426        self.update_on_fields = list(update_on_fields or [])
427        self.max_field_age = dict(max_field_age or {})
428        # Caching is what makes update_on_fields and max_field_age mean
429        # anything, so declaring either turns it on.
430        self.cache_inputs = bool(cache_inputs or self.update_on_fields
431                                 or self.max_field_age)
432        # field name -> (value, timestamp)
433        self.cache = {}
434
435        # Which (rule, missing-fields) combinations we have already mentioned.
436        # A rule perpetually missing the same field on a 10Hz stream would
437        # otherwise bury the log at exactly the moment someone raises
438        # verbosity to find out why.
439        self._reported_missing = set()
440
441        self.rules = {}
442        self.metadata = {}
443        # Every output named so far, including those of disabled rules: a
444        # rule that uses a disabled rule's result must not fire, rather than
445        # quietly reading a record field that happens to have the same name.
446        earlier_outputs = set()
447        for output_name, spec in fields.items():
448            rule = self._build_rule(output_name, spec)
449            if rule:
450                # Rules are evaluated in the order given, and a name that
451                # matches an earlier rule's output reads that rule's result
452                # rather than a record field.
453                rule['earlier_results'] = {
454                    name for name, field in rule['input_fields'].items()
455                    if field in earlier_outputs}
456                self.rules[output_name] = rule
457                if rule['metadata'] and not rule['intermediate']:
458                    self.metadata[output_name] = rule['metadata']
459            earlier_outputs.add(output_name)
460
461        # A name matching a *later* rule's output still reads a record field.
462        # That is right for a rule that uses a raw value which a later rule
463        # replaces, but is more often a rule listed in the wrong order, so say
464        # so at startup.
465        if not self.quiet:
466            outputs = list(fields)
467            for output_name, rule in self.rules.items():
468                later = outputs[outputs.index(output_name) + 1:]
469                for name, field in rule['input_fields'].items():
470                    if field in later:
471                        logging.warning(
472                            'ComputedFieldsTransform: "%s" uses "%s", which is '
473                            'also the output of a rule listed after it. Rules '
474                            'can use only the results of rules listed before '
475                            'them, so this reads the record field "%s". If you '
476                            'meant the computed value, move "%s" after "%s".',
477                            output_name, name, field, output_name, field)
478
479        # Every record field any rule might read. Used to tell an "input" from
480        # an "other" field when applying the two deletion flags, and to decide
481        # what is worth caching.
482        self.all_input_fields = set()
483        for rule in self.rules.values():
484            self.all_input_fields.update(
485                field for name, field in rule['input_fields'].items()
486                if name not in rule['earlier_results'])
487
488    ############################
489    def _build_rule(self, output_name, spec):
490        """Validate and compile one rule. Returns None if it is disabled."""
491        if not isinstance(spec, dict):
492            raise ValueError(f'ComputedFieldsTransform: spec for '
493                             f'"{output_name}" must be a dict, got '
494                             f'{type(spec).__name__}')
495
496        unknown = set(spec) - {'equation', 'constants', 'inputs',
497                               'delete_input_fields', 'metadata',
498                               'intermediate'}
499        if unknown:
500            raise ValueError(f'ComputedFieldsTransform: unrecognized key(s) '
501                             f'{sorted(unknown)} in spec for "{output_name}"')
502
503        equation = spec.get('equation')
504        if not equation:
505            raise ValueError(f'ComputedFieldsTransform: no "equation" given '
506                             f'for "{output_name}"')
507
508        constants = spec.get('constants') or {}
509        if not isinstance(constants, dict):
510            raise ValueError(f'ComputedFieldsTransform: "constants" for '
511                             f'"{output_name}" must be a dict')
512
513        aliases = spec.get('inputs') or {}
514        if not isinstance(aliases, dict):
515            raise ValueError(f'ComputedFieldsTransform: "inputs" for '
516                             f'"{output_name}" must be a dict of '
517                             f'alias -> field name')
518
519        # Parse and refuse anything unsafe. Doing this here rather than per
520        # record means a bad equation stops the logger at startup, where
521        # someone will see it, instead of silently mid-cruise - and lets
522        # validate_config catch it before anyone sails.
523        tree = validate_expression(equation, where=f'field "{output_name}"',
524                                   functions=self.FUNCTIONS)
525
526        # A null constant is how a config says "this device has no calibration".
527        # Disable the rule rather than computing something plausible-looking
528        # from a missing coefficient.
529        null_constants = [k for k, v in constants.items() if v is None]
530        if null_constants:
531            logging.info('ComputedFieldsTransform: not computing "%s" - '
532                         'constant(s) %s are null, so the device is '
533                         'presumably uncalibrated.',
534                         output_name, ', '.join(sorted(null_constants)))
535            return None
536
537        # Sort the names an equation reads into constants, functions and
538        # fields. Anything not otherwise accounted for is a field reference.
539        input_fields = {}
540        for name in expression_names(tree):
541            if name in constants or name in self.FUNCTIONS \
542               or name in self.CONSTANTS:
543                continue
544            # An alias resolves to the field it names; a bare name is the
545            # field name itself.
546            input_fields[name] = aliases.get(name, name)
547
548        unused_aliases = set(aliases) - set(input_fields)
549        if unused_aliases and not self.quiet:
550            logging.warning('ComputedFieldsTransform: "%s" declares input '
551                            'alias(es) %s that its equation never uses.',
552                            output_name, sorted(unused_aliases))
553
554        if not input_fields:
555            raise ValueError(f'ComputedFieldsTransform: equation for '
556                             f'"{output_name}" reads no record fields, so it '
557                             f'would compute the same constant forever: '
558                             f'"{equation}"')
559
560        return {
561            'equation': equation,
562            'code': compile(tree, filename=f'<equation {output_name}>',
563                            mode='eval'),
564            'constants': constants,
565            'input_fields': input_fields,     # name in equation -> record field
566            'delete_input_fields': spec.get('delete_input_fields',
567                                            self.delete_input_fields),
568            'metadata': spec.get('metadata'),
569            'intermediate': bool(spec.get('intermediate', False)),
570            'warned': False,
571        }
572
573    ############################
574    def _resolve_inputs(self, rule, fields, timestamp, computed):
575        """Gather a rule's inputs. Returns (values, missing) where missing maps
576        each unavailable field to why it is unavailable."""
577        values = {}
578        missing = {}
579        for name, field in rule['input_fields'].items():
580            value = None
581            found = False
582
583            if name in rule['earlier_results']:
584                if field in computed:
585                    values[name] = computed[field]
586                else:
587                    missing[field] = 'not computed for this record'
588                continue
589
590            if field in fields:
591                value = fields[field]
592                found = True
593            elif self.cache_inputs and field in self.cache:
594                cached_value, cached_time = self.cache[field]
595                max_age = self.max_field_age.get(field)
596                if max_age is not None and timestamp is not None \
597                   and timestamp - cached_time > max_age:
598                    missing[field] = (f'cached value is '
599                                      f'{timestamp - cached_time:.1f}s old, '
600                                      f'limit is {max_age}s')
601                    continue
602                value = cached_value
603                found = True
604
605            if not found:
606                missing[field] = 'not in record'
607            elif value is None:
608                # Absent and null both mean "no reading", but they point at
609                # different upstream problems, so say which.
610                missing[field] = 'present but null'
611            else:
612                values[name] = value
613
614        return values, missing
615
616    ############################
617    def _note_missing(self, output_name, rule, missing, present_count):
618        """Report inputs a rule could not get, without flooding the log."""
619        signature = (output_name, frozenset(missing))
620        already_reported = signature in self._reported_missing
621        self._reported_missing.add(signature)
622
623        detail = ', '.join(f'{f} ({why})' for f, why in sorted(missing.items()))
624
625        # Some inputs present and others not is the suspicious case: the record
626        # looks like it was meant for this rule but is incomplete. All of them
627        # absent usually just means this record is for some other instrument.
628        if present_count and not already_reported:
629            logging.debug('ComputedFieldsTransform: not computing "%s" - have '
630                          '%d of %d inputs, missing: %s',
631                          output_name, present_count,
632                          len(rule['input_fields']), detail)
633
634        if self.warn_missing_inputs and not self.quiet and not already_reported:
635            logging.warning('ComputedFieldsTransform: not computing "%s" - '
636                            'missing %s', output_name, detail)
637
638    ############################
639    def _evaluate(self, output_name, rule, values):
640        """Evaluate one rule. Returns None if it could not be computed."""
641        namespace = dict(self.CONSTANTS)
642        namespace.update(self.FUNCTIONS)
643        namespace.update(rule['constants'])
644        namespace.update(values)
645        try:
646            # No builtins: without this, __import__('os').system(...) is one
647            # call away. The node allowlist in validate_expression() is what
648            # actually carries the weight, but both matter.
649            return eval(rule['code'], {'__builtins__': {}}, namespace)  # noqa: S307
650        except Exception as e:  # noqa: BLE001 - a bad record must not kill a logger
651            # Division by zero, log of a negative, a field that arrived as a
652            # string. Report once per rule and then stay quiet: at 10Hz this
653            # would otherwise be a wall of identical messages.
654            if not rule['warned'] and not self.quiet:
655                rule['warned'] = True
656                logging.warning('ComputedFieldsTransform: could not compute '
657                                '"%s" from "%s": %s: %s. Suppressing further '
658                                'warnings for this field.',
659                                output_name, rule['equation'],
660                                type(e).__name__, e)
661            return None
662
663    ############################
664    def transform(self, record: Union[DASRecord, dict]):
665        """Compute the configured fields and return the record."""
666        # See if it's something we can process, and if not, try digesting
667        if not self.can_process_record(record):  # inherited from BaseModule()
668            return self.digest_record(record)  # inherited from BaseModule()
669
670        # Hand back the shape we were given, as SelectFieldsTransform and
671        # DeltaTransform do.
672        dict_input = isinstance(record, dict)
673        enveloped = False
674        if dict_input:
675            if isinstance(record.get('fields'), dict):
676                enveloped = True
677                record = DASRecord(fields=record['fields'],
678                                   data_id=record.get('data_id', self.data_id),
679                                   timestamp=record.get('timestamp', 0))
680            else:
681                record = DASRecord(fields=record, data_id=self.data_id)
682
683        fields = record.fields
684        timestamp = record.timestamp or time.time()
685
686        # Update the cache before evaluating, so a record carrying several
687        # inputs at once resolves all of them.
688        triggered = not self.update_on_fields
689        if self.cache_inputs:
690            for field, value in fields.items():
691                if field in self.all_input_fields:
692                    _, previous_time = self.cache.get(field, (None, 0))
693                    if timestamp >= previous_time:
694                        self.cache[field] = (value, timestamp)
695        for field in self.update_on_fields:
696            if field in fields:
697                triggered = True
698
699        result = copy.deepcopy(record)
700
701        computed = {}
702        consumed = set()
703        if triggered:
704            for output_name, rule in self.rules.items():
705                values, missing = self._resolve_inputs(rule, fields, timestamp,
706                                                       computed)
707                if missing:
708                    self._note_missing(output_name, rule, missing, len(values))
709                    continue
710                value = self._evaluate(output_name, rule, values)
711                if value is None:
712                    continue
713                computed[output_name] = value
714                if rule['delete_input_fields']:
715                    consumed.update(rule['input_fields'].values())
716            computed = {name: value for name, value in computed.items()
717                        if not self.rules[name]['intermediate']}
718        else:
719            logging.debug('ComputedFieldsTransform: no field in %s updated; '
720                          'not recomputing', self.update_on_fields)
721
722        # Apply the two deletion flags. Deletion happens only once every output
723        # has been computed - a field feeding two rules would otherwise vanish
724        # before the second one read it.
725        for field in list(result.fields):
726            if field in self.all_input_fields:
727                if field in consumed:
728                    del result.fields[field]
729            elif self.delete_other_fields and field not in computed:
730                del result.fields[field]
731
732        # If the caller asked for derived values only and this record did not
733        # produce any, there is nothing to publish. Returning the surviving
734        # input fields would republish raw readings under the derived
735        # measurement's name - in a CachedDataServer round-trip that means a
736        # CTD value reappearing as though it were an oxygen correction.
737        # DeltaTransform sets the precedent of returning None when it has
738        # nothing to say.
739        if self.delete_other_fields and not computed:
740            return None
741
742        for output_name, value in computed.items():
743            if output_name in fields and not self.quiet:
744                logging.warning('ComputedFieldsTransform overwriting existing '
745                                'field: %s', output_name)
746            result.fields[output_name] = value
747
748        if self._should_attach_metadata(timestamp):
749            result.metadata.update(self.metadata)
750
751        if dict_input:
752            if enveloped:
753                envelope = {'timestamp': result.timestamp,
754                            'fields': result.fields}
755                if result.data_id is not None:
756                    envelope['data_id'] = result.data_id
757                if result.metadata:
758                    envelope['metadata'] = result.metadata
759                return envelope
760            return result.fields
761
762        return result
763
764    ############################
765    def _should_attach_metadata(self, timestamp):
766        """Is it time to send metadata along again?"""
767        if not self.metadata_interval or not self.metadata:
768            return False
769        if timestamp > self.last_metadata_send + self.metadata_interval:
770            self.last_metadata_send = timestamp
771            return True
772        return False
SAFE_FUNCTIONS = {'abs': <built-in function abs>, 'min': <built-in function min>, 'max': <built-in function max>, 'round': <built-in function round>, 'pow': <built-in function pow>, 'int': <class 'int'>, 'float': <class 'float'>, 'exp': <built-in function exp>, 'log': <built-in function log>, 'log10': <built-in function log10>, 'sqrt': <built-in function sqrt>, 'sin': <built-in function sin>, 'cos': <built-in function cos>, 'tan': <built-in function tan>, 'asin': <built-in function asin>, 'acos': <built-in function acos>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'hypot': <built-in function hypot>, 'degrees': <built-in function degrees>, 'radians': <built-in function radians>, 'floor': <built-in function floor>, 'ceil': <built-in function ceil>, 'fmod': <built-in function fmod>}
SAFE_CONSTANTS = {'pi': 3.141592653589793, 'e': 2.718281828459045}
MAX_EXPRESSION_LENGTH = 1000
MAX_EXPRESSION_NODES = 250
MAX_EXPONENT = 64
class UnsafeExpressionError(builtins.ValueError):
91class UnsafeExpressionError(ValueError):
92    """Raised when an expression contains something we refuse to evaluate."""

Raised when an expression contains something we refuse to evaluate.

def validate_expression(expression, where='', functions=None):
 95def validate_expression(expression, where='', functions=None):
 96    """Parse an expression and refuse anything not on the allowlist.
 97
 98    Returns the parsed ast.Expression. Raises UnsafeExpressionError with a
 99    message naming the offending construct otherwise.
100
101    'functions' is the set of callable names the expression may use. It
102    defaults to SAFE_FUNCTIONS; a ComputedFieldsTransform subclass that widens
103    its FUNCTIONS table passes that in, so that validation and evaluation agree
104    about what exists. They must agree: a name permitted here but absent at
105    evaluation would fail per record instead of at startup, and a name
106    available at evaluation but refused here could never be reached.
107    """
108    if functions is None:
109        functions = SAFE_FUNCTIONS
110    if not AST_MODULE_FOUND:
111        raise RuntimeError('Expression evaluation is not available: could not '
112                           'import the standard library "ast" module, so there '
113                           'is no way to check an equation before running it.')
114
115    prefix = f'{where}: ' if where else ''
116
117    if not isinstance(expression, str):
118        raise UnsafeExpressionError(f'{prefix}equation must be a string, '
119                                    f'got {type(expression).__name__}')
120    if len(expression) > MAX_EXPRESSION_LENGTH:
121        raise UnsafeExpressionError(
122            f'{prefix}equation is {len(expression)} characters; the limit is '
123            f'{MAX_EXPRESSION_LENGTH}. A calibration this long probably wants '
124            f'to be several fields.')
125    try:
126        tree = ast.parse(expression, mode='eval')
127    except SyntaxError as e:
128        raise UnsafeExpressionError(f'{prefix}could not parse equation '
129                                    f'"{expression}": {e}')
130
131    nodes = list(ast.walk(tree))
132    if len(nodes) > MAX_EXPRESSION_NODES:
133        raise UnsafeExpressionError(
134            f'{prefix}equation has {len(nodes)} nodes; the limit is '
135            f'{MAX_EXPRESSION_NODES}')
136
137    for node in nodes:
138        if isinstance(node, ALLOWED_OPS):
139            continue
140        if not isinstance(node, ALLOWED_NODES):
141            raise UnsafeExpressionError(
142                f'{prefix}{type(node).__name__} is not allowed in an equation. '
143                f'Equations may use arithmetic, comparisons, conditional '
144                f'expressions and the functions '
145                f'{", ".join(sorted(functions))}.')
146
147        if isinstance(node, ast.Call):
148            # Only direct calls to whitelisted names. No attribute calls, no
149            # computed callables, no **kwargs smuggling.
150            if not isinstance(node.func, ast.Name):
151                raise UnsafeExpressionError(
152                    f'{prefix}only direct calls to named functions are allowed')
153            if node.func.id not in functions:
154                raise UnsafeExpressionError(
155                    f'{prefix}unknown function "{node.func.id}". Available: '
156                    f'{", ".join(sorted(functions))}')
157            if node.keywords:
158                raise UnsafeExpressionError(
159                    f'{prefix}keyword arguments are not allowed in equations')
160
161        if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
162            # Guard exhaustion. The exponent must be a literal number within
163            # reach, which rules out 9**9**9 (exponent is itself a BinOp) and
164            # 9**999999. Variable exponents are not supported; no calibration
165            # polynomial we have seen needs one.
166            exponent = node.right
167            if not (isinstance(exponent, ast.Constant)
168                    and isinstance(exponent.value, (int, float))):
169                raise UnsafeExpressionError(
170                    f'{prefix}the exponent of ** must be a literal number')
171            if abs(exponent.value) > MAX_EXPONENT:
172                raise UnsafeExpressionError(
173                    f'{prefix}exponent {exponent.value} exceeds the limit of '
174                    f'{MAX_EXPONENT}')
175
176    return tree

Parse an expression and refuse anything not on the allowlist.

Returns the parsed ast.Expression. Raises UnsafeExpressionError with a message naming the offending construct otherwise.

'functions' is the set of callable names the expression may use. It defaults to SAFE_FUNCTIONS; a ComputedFieldsTransform subclass that widens its FUNCTIONS table passes that in, so that validation and evaluation agree about what exists. They must agree: a name permitted here but absent at evaluation would fail per record instead of at startup, and a name available at evaluation but refused here could never be reached.

def expression_names(tree):
179def expression_names(tree):
180    """Every name an expression reads, in source order of first appearance."""
181    names = []
182    for node in ast.walk(tree):
183        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
184            if node.id not in names:
185                names.append(node.id)
186    return names

Every name an expression reads, in source order of first appearance.

class ComputedFieldsTransform(logger.transforms.derived_data_transform.DerivedDataTransform):
190class ComputedFieldsTransform(DerivedDataTransform):
191    """Compute new record fields from algebraic expressions over existing ones.
192
193    The callables and named constants an equation may use are class attributes,
194    so a subclass can widen them without touching this module - and without
195    this module acquiring the subclass's dependencies:
196
197        class GSWComputedFieldsTransform(ComputedFieldsTransform):
198            FUNCTIONS = {**ComputedFieldsTransform.FUNCTIONS,
199                         'gsw_z_from_p': gsw.z_from_p}
200
201    Names must be flat. Attribute access is refused by the expression checker -
202    it is the main sandbox escape - so "gsw.z_from_p(...)" could never parse.
203
204    A subclass adding functions that can return NaN rather than raising, as the
205    TEOS-10 routines do, should guard against that: everything in the default
206    table raises on bad input, so a NaN would otherwise travel quietly into the
207    data stream.
208    """
209
210    # Widen these in a subclass, not in place.
211    FUNCTIONS = SAFE_FUNCTIONS
212    CONSTANTS = SAFE_CONSTANTS
213
214    def __init__(self, fields,
215                 delete_input_fields=False, delete_other_fields=False,
216                 warn_missing_inputs=False,
217                 cache_inputs=False, update_on_fields=None, max_field_age=None,
218                 data_id=None, metadata_interval=None, **kwargs):
219        """
220        ```
221        fields
222            A dict of the fields to compute, keyed by the name of the field to
223            be *produced*. Note that this is the opposite of
224            ModifyValueTransform, which keys by input field; keying by output
225            is what lets a single rule draw on several inputs.
226
227            fields:
228              SeawaterTempCorrected:
229                equation: "sbe38_slope * SeawaterTemp + sbe38_offset"
230                constants:
231                  sbe38_slope:  1.00021
232                  sbe38_offset: -0.0032
233                metadata: SBE38 with linear calibration applied
234
235              DepthCorrected:
236                equation: "(Pressure - (10.1325 if pressure_is_absolute else 0))
237                           * conv_coefficient"
238                constants:
239                  pressure_is_absolute: true
240                  conv_coefficient: 1.0
241
242              SoundVelocity:
243                equation: "1449.2 + 4.6*T - 0.055*T**2 + 1.39*(S-35) + 0.016*D"
244                inputs: {T: SeawaterTemp, S: Salinity, D: Depth}
245                delete_input_fields: true
246
247            Per-rule keys:
248
249            equation (required)
250                The expression to evaluate. Bare names refer to record fields,
251                to the results of rules listed before this one, to entries in
252                'constants', to entries in 'inputs', or to one of the functions
253                listed under "Writing equations" below.
254
255            constants (default {})
256                Values to make available to the equation by name. These may be
257                numbers, booleans or strings. A constant whose value is null
258                disables the rule - the usual way to say "this device is not
259                calibrated" without having to remove the logger.
260
261            inputs (default {})
262                Optional alias -> field name mapping, so that a standard formula
263                can be written in textbook notation and pointed at
264                differently-named fields. Purely for readability; bare field
265                names work without it.
266
267            delete_input_fields (default: the transform-wide setting)
268                Whether the fields this rule read should be dropped from the
269                result.
270
271            intermediate (default False)
272                If true, this rule's result is available to the rules listed
273                after it, but is not added to the output. See "Rules in
274                sequence" below.
275
276            metadata (default None)
277                Metadata to attach for the computed field. Ignored for an
278                intermediate rule.
279
280        delete_input_fields (default False)
281            Drop the fields that equations read from the result.
282
283        delete_other_fields (default False)
284            Drop the fields that no equation read from the result.
285
286            The two flags are independent, and all four combinations are
287            useful:
288
289              False/False  record plus computed values - enhancing an inline
290                           data stream, the default
291              True/False   calibrate in place, leaving the rest of the record
292              True/True    computed values only - reading from a CachedDataServer,
293                           computing, and writing back
294              False/True   computed values plus the inputs they used
295
296            If you want something in between - computed values plus a couple of
297            identifying fields - compose with SelectFieldsTransform downstream
298            rather than reaching for another option here.
299
300        warn_missing_inputs (default False)
301            Whether to warn when a rule cannot fire because its inputs are
302            absent. False by default because a stream may carry many record
303            types, only some of which have the fields a given rule wants; on a
304            mixed stream the normal case would otherwise warn on nearly every
305            record. Regardless of this setting, a debug message is emitted when
306            *some* of a rule's inputs are present and others are missing, which
307            is the genuinely suspicious case. 'quiet' suppresses the warning
308            even when this is set.
309
310        cache_inputs (default False)
311            Retain the most recent value of each input field across records, so
312            that an equation can combine readings that arrive in separate
313            records - which is what happens when inputs come from different
314            instruments by way of a CachedDataServer. Implied by
315            update_on_fields or max_field_age.
316
317        update_on_fields (default None)
318            A list of field names; compute only when a record carries one of
319            them. Without this, every record that completes a rule's inputs
320            produces a new value, so a correction drawing on a slow-moving
321            secondary input would re-emit each time that input ticked rather
322            than when a new primary reading arrived.
323
324        max_field_age (default None)
325            A dict of field name -> seconds. A cached value older than its
326            limit counts as missing, so a rule will not fire on it. Fields not
327            named here never expire.
328
329            update_on_fields and max_field_age follow TrueWindsTransform, which
330            has the same two options with the same meanings.
331
332        data_id (default None)
333            data_id to assign to the result, if the record does not carry one.
334
335        metadata_interval (default None)
336            If set, how often in seconds to attach field metadata to records.
337
338        Writing equations
339        -----------------
340        An equation may use arithmetic (+ - * / // % **), comparisons, boolean
341        operators, and conditional expressions ("x if cond else y"). Field
342        values are passed through as they arrive and are not coerced, so a
343        field holding 'N' or 'S' can be compared as a string.
344
345        These functions are available:
346
347                abs acos asin atan atan2 ceil cos degrees exp float floor
348                fmod hypot int log log10 max min pow radians round sin sqrt
349                tan
350
351        along with the constants pi and e.
352
353        The exponent of ** must be a literal number, and at most 64. This is a
354        deliberate guard rather than an oversight: "9**9**9" is otherwise an
355        ordinary expression that would hang the logger and exhaust its memory.
356
357        Rules in sequence
358        -----------------
359        Rules are evaluated in the order they are listed, and an equation can
360        use the result of any rule listed before it, by that rule's name (or
361        through an alias in 'inputs'). Mark a rule "intermediate: true" to use
362        its result in later rules without outputting it:
363
364            fields:
365              x:
366                equation: "wspd * cos(radians(270 - wdir))"
367                intermediate: true
368              y:
369                equation: "wspd * sin(radians(270 - wdir))"
370                intermediate: true
371              WindSpeed:
372                equation: "hypot(x, y)"
373
374        If an earlier rule produces no value for a record - because its inputs
375        are missing, or its equation gives None, or it is disabled by a null
376        constant - then no rule that uses its result fires either. So an
377        intermediate rule such as
378
379              valid:
380                equation: "True if 0 <= heading <= 360 else None"
381                intermediate: true
382
383        lets a later rule compute only from sensible inputs by mentioning it:
384        "(heading + offset) % 360 if valid else None".
385
386        A name matching a rule listed *after* the one using it is not that
387        rule's result: it is read from the record. That is what lets a rule
388        use a raw value that a later rule replaces in place, but as it is more
389        often a rule listed in the wrong order, it is logged as a warning when
390        the transform starts.
391
392        test/configs/computed_true_winds.yaml is a worked example: true winds,
393        computed with the formulas TrueWindsTransform uses.
394
395        Equations are checked when the transform is constructed, not per
396        record, so a typo or a refused construct stops the logger at startup
397        rather than failing quietly mid-cruise - and validate_config can catch
398        it before anyone sails. They are not eval()'d naively: the expression
399        is parsed and every construct checked against an allowlist, with no
400        builtins and no attribute access.
401
402        To make further functions available - the TEOS-10 routines in gsw, for
403        instance - subclass this transform and widen its FUNCTIONS table rather
404        than editing it in place. See the class docstring.
405        ```
406        """
407        super().__init__(**kwargs)  # processes 'quiet' and type hints
408
409        if not AST_MODULE_FOUND:
410            raise RuntimeError('ComputedFieldsTransform is not available: '
411                               'could not import the standard library "ast" '
412                               'module, which is needed to parse and check '
413                               'equations before they are evaluated.')
414
415        if not isinstance(fields, dict) or not fields:
416            raise ValueError('ComputedFieldsTransform requires a non-empty '
417                             '"fields" dict, keyed by the name of each field '
418                             'to be computed.')
419
420        self.delete_input_fields = delete_input_fields
421        self.delete_other_fields = delete_other_fields
422        self.warn_missing_inputs = warn_missing_inputs
423        self.data_id = data_id
424        self.metadata_interval = metadata_interval or 0
425        self.last_metadata_send = 0
426
427        self.update_on_fields = list(update_on_fields or [])
428        self.max_field_age = dict(max_field_age or {})
429        # Caching is what makes update_on_fields and max_field_age mean
430        # anything, so declaring either turns it on.
431        self.cache_inputs = bool(cache_inputs or self.update_on_fields
432                                 or self.max_field_age)
433        # field name -> (value, timestamp)
434        self.cache = {}
435
436        # Which (rule, missing-fields) combinations we have already mentioned.
437        # A rule perpetually missing the same field on a 10Hz stream would
438        # otherwise bury the log at exactly the moment someone raises
439        # verbosity to find out why.
440        self._reported_missing = set()
441
442        self.rules = {}
443        self.metadata = {}
444        # Every output named so far, including those of disabled rules: a
445        # rule that uses a disabled rule's result must not fire, rather than
446        # quietly reading a record field that happens to have the same name.
447        earlier_outputs = set()
448        for output_name, spec in fields.items():
449            rule = self._build_rule(output_name, spec)
450            if rule:
451                # Rules are evaluated in the order given, and a name that
452                # matches an earlier rule's output reads that rule's result
453                # rather than a record field.
454                rule['earlier_results'] = {
455                    name for name, field in rule['input_fields'].items()
456                    if field in earlier_outputs}
457                self.rules[output_name] = rule
458                if rule['metadata'] and not rule['intermediate']:
459                    self.metadata[output_name] = rule['metadata']
460            earlier_outputs.add(output_name)
461
462        # A name matching a *later* rule's output still reads a record field.
463        # That is right for a rule that uses a raw value which a later rule
464        # replaces, but is more often a rule listed in the wrong order, so say
465        # so at startup.
466        if not self.quiet:
467            outputs = list(fields)
468            for output_name, rule in self.rules.items():
469                later = outputs[outputs.index(output_name) + 1:]
470                for name, field in rule['input_fields'].items():
471                    if field in later:
472                        logging.warning(
473                            'ComputedFieldsTransform: "%s" uses "%s", which is '
474                            'also the output of a rule listed after it. Rules '
475                            'can use only the results of rules listed before '
476                            'them, so this reads the record field "%s". If you '
477                            'meant the computed value, move "%s" after "%s".',
478                            output_name, name, field, output_name, field)
479
480        # Every record field any rule might read. Used to tell an "input" from
481        # an "other" field when applying the two deletion flags, and to decide
482        # what is worth caching.
483        self.all_input_fields = set()
484        for rule in self.rules.values():
485            self.all_input_fields.update(
486                field for name, field in rule['input_fields'].items()
487                if name not in rule['earlier_results'])
488
489    ############################
490    def _build_rule(self, output_name, spec):
491        """Validate and compile one rule. Returns None if it is disabled."""
492        if not isinstance(spec, dict):
493            raise ValueError(f'ComputedFieldsTransform: spec for '
494                             f'"{output_name}" must be a dict, got '
495                             f'{type(spec).__name__}')
496
497        unknown = set(spec) - {'equation', 'constants', 'inputs',
498                               'delete_input_fields', 'metadata',
499                               'intermediate'}
500        if unknown:
501            raise ValueError(f'ComputedFieldsTransform: unrecognized key(s) '
502                             f'{sorted(unknown)} in spec for "{output_name}"')
503
504        equation = spec.get('equation')
505        if not equation:
506            raise ValueError(f'ComputedFieldsTransform: no "equation" given '
507                             f'for "{output_name}"')
508
509        constants = spec.get('constants') or {}
510        if not isinstance(constants, dict):
511            raise ValueError(f'ComputedFieldsTransform: "constants" for '
512                             f'"{output_name}" must be a dict')
513
514        aliases = spec.get('inputs') or {}
515        if not isinstance(aliases, dict):
516            raise ValueError(f'ComputedFieldsTransform: "inputs" for '
517                             f'"{output_name}" must be a dict of '
518                             f'alias -> field name')
519
520        # Parse and refuse anything unsafe. Doing this here rather than per
521        # record means a bad equation stops the logger at startup, where
522        # someone will see it, instead of silently mid-cruise - and lets
523        # validate_config catch it before anyone sails.
524        tree = validate_expression(equation, where=f'field "{output_name}"',
525                                   functions=self.FUNCTIONS)
526
527        # A null constant is how a config says "this device has no calibration".
528        # Disable the rule rather than computing something plausible-looking
529        # from a missing coefficient.
530        null_constants = [k for k, v in constants.items() if v is None]
531        if null_constants:
532            logging.info('ComputedFieldsTransform: not computing "%s" - '
533                         'constant(s) %s are null, so the device is '
534                         'presumably uncalibrated.',
535                         output_name, ', '.join(sorted(null_constants)))
536            return None
537
538        # Sort the names an equation reads into constants, functions and
539        # fields. Anything not otherwise accounted for is a field reference.
540        input_fields = {}
541        for name in expression_names(tree):
542            if name in constants or name in self.FUNCTIONS \
543               or name in self.CONSTANTS:
544                continue
545            # An alias resolves to the field it names; a bare name is the
546            # field name itself.
547            input_fields[name] = aliases.get(name, name)
548
549        unused_aliases = set(aliases) - set(input_fields)
550        if unused_aliases and not self.quiet:
551            logging.warning('ComputedFieldsTransform: "%s" declares input '
552                            'alias(es) %s that its equation never uses.',
553                            output_name, sorted(unused_aliases))
554
555        if not input_fields:
556            raise ValueError(f'ComputedFieldsTransform: equation for '
557                             f'"{output_name}" reads no record fields, so it '
558                             f'would compute the same constant forever: '
559                             f'"{equation}"')
560
561        return {
562            'equation': equation,
563            'code': compile(tree, filename=f'<equation {output_name}>',
564                            mode='eval'),
565            'constants': constants,
566            'input_fields': input_fields,     # name in equation -> record field
567            'delete_input_fields': spec.get('delete_input_fields',
568                                            self.delete_input_fields),
569            'metadata': spec.get('metadata'),
570            'intermediate': bool(spec.get('intermediate', False)),
571            'warned': False,
572        }
573
574    ############################
575    def _resolve_inputs(self, rule, fields, timestamp, computed):
576        """Gather a rule's inputs. Returns (values, missing) where missing maps
577        each unavailable field to why it is unavailable."""
578        values = {}
579        missing = {}
580        for name, field in rule['input_fields'].items():
581            value = None
582            found = False
583
584            if name in rule['earlier_results']:
585                if field in computed:
586                    values[name] = computed[field]
587                else:
588                    missing[field] = 'not computed for this record'
589                continue
590
591            if field in fields:
592                value = fields[field]
593                found = True
594            elif self.cache_inputs and field in self.cache:
595                cached_value, cached_time = self.cache[field]
596                max_age = self.max_field_age.get(field)
597                if max_age is not None and timestamp is not None \
598                   and timestamp - cached_time > max_age:
599                    missing[field] = (f'cached value is '
600                                      f'{timestamp - cached_time:.1f}s old, '
601                                      f'limit is {max_age}s')
602                    continue
603                value = cached_value
604                found = True
605
606            if not found:
607                missing[field] = 'not in record'
608            elif value is None:
609                # Absent and null both mean "no reading", but they point at
610                # different upstream problems, so say which.
611                missing[field] = 'present but null'
612            else:
613                values[name] = value
614
615        return values, missing
616
617    ############################
618    def _note_missing(self, output_name, rule, missing, present_count):
619        """Report inputs a rule could not get, without flooding the log."""
620        signature = (output_name, frozenset(missing))
621        already_reported = signature in self._reported_missing
622        self._reported_missing.add(signature)
623
624        detail = ', '.join(f'{f} ({why})' for f, why in sorted(missing.items()))
625
626        # Some inputs present and others not is the suspicious case: the record
627        # looks like it was meant for this rule but is incomplete. All of them
628        # absent usually just means this record is for some other instrument.
629        if present_count and not already_reported:
630            logging.debug('ComputedFieldsTransform: not computing "%s" - have '
631                          '%d of %d inputs, missing: %s',
632                          output_name, present_count,
633                          len(rule['input_fields']), detail)
634
635        if self.warn_missing_inputs and not self.quiet and not already_reported:
636            logging.warning('ComputedFieldsTransform: not computing "%s" - '
637                            'missing %s', output_name, detail)
638
639    ############################
640    def _evaluate(self, output_name, rule, values):
641        """Evaluate one rule. Returns None if it could not be computed."""
642        namespace = dict(self.CONSTANTS)
643        namespace.update(self.FUNCTIONS)
644        namespace.update(rule['constants'])
645        namespace.update(values)
646        try:
647            # No builtins: without this, __import__('os').system(...) is one
648            # call away. The node allowlist in validate_expression() is what
649            # actually carries the weight, but both matter.
650            return eval(rule['code'], {'__builtins__': {}}, namespace)  # noqa: S307
651        except Exception as e:  # noqa: BLE001 - a bad record must not kill a logger
652            # Division by zero, log of a negative, a field that arrived as a
653            # string. Report once per rule and then stay quiet: at 10Hz this
654            # would otherwise be a wall of identical messages.
655            if not rule['warned'] and not self.quiet:
656                rule['warned'] = True
657                logging.warning('ComputedFieldsTransform: could not compute '
658                                '"%s" from "%s": %s: %s. Suppressing further '
659                                'warnings for this field.',
660                                output_name, rule['equation'],
661                                type(e).__name__, e)
662            return None
663
664    ############################
665    def transform(self, record: Union[DASRecord, dict]):
666        """Compute the configured fields and return the record."""
667        # See if it's something we can process, and if not, try digesting
668        if not self.can_process_record(record):  # inherited from BaseModule()
669            return self.digest_record(record)  # inherited from BaseModule()
670
671        # Hand back the shape we were given, as SelectFieldsTransform and
672        # DeltaTransform do.
673        dict_input = isinstance(record, dict)
674        enveloped = False
675        if dict_input:
676            if isinstance(record.get('fields'), dict):
677                enveloped = True
678                record = DASRecord(fields=record['fields'],
679                                   data_id=record.get('data_id', self.data_id),
680                                   timestamp=record.get('timestamp', 0))
681            else:
682                record = DASRecord(fields=record, data_id=self.data_id)
683
684        fields = record.fields
685        timestamp = record.timestamp or time.time()
686
687        # Update the cache before evaluating, so a record carrying several
688        # inputs at once resolves all of them.
689        triggered = not self.update_on_fields
690        if self.cache_inputs:
691            for field, value in fields.items():
692                if field in self.all_input_fields:
693                    _, previous_time = self.cache.get(field, (None, 0))
694                    if timestamp >= previous_time:
695                        self.cache[field] = (value, timestamp)
696        for field in self.update_on_fields:
697            if field in fields:
698                triggered = True
699
700        result = copy.deepcopy(record)
701
702        computed = {}
703        consumed = set()
704        if triggered:
705            for output_name, rule in self.rules.items():
706                values, missing = self._resolve_inputs(rule, fields, timestamp,
707                                                       computed)
708                if missing:
709                    self._note_missing(output_name, rule, missing, len(values))
710                    continue
711                value = self._evaluate(output_name, rule, values)
712                if value is None:
713                    continue
714                computed[output_name] = value
715                if rule['delete_input_fields']:
716                    consumed.update(rule['input_fields'].values())
717            computed = {name: value for name, value in computed.items()
718                        if not self.rules[name]['intermediate']}
719        else:
720            logging.debug('ComputedFieldsTransform: no field in %s updated; '
721                          'not recomputing', self.update_on_fields)
722
723        # Apply the two deletion flags. Deletion happens only once every output
724        # has been computed - a field feeding two rules would otherwise vanish
725        # before the second one read it.
726        for field in list(result.fields):
727            if field in self.all_input_fields:
728                if field in consumed:
729                    del result.fields[field]
730            elif self.delete_other_fields and field not in computed:
731                del result.fields[field]
732
733        # If the caller asked for derived values only and this record did not
734        # produce any, there is nothing to publish. Returning the surviving
735        # input fields would republish raw readings under the derived
736        # measurement's name - in a CachedDataServer round-trip that means a
737        # CTD value reappearing as though it were an oxygen correction.
738        # DeltaTransform sets the precedent of returning None when it has
739        # nothing to say.
740        if self.delete_other_fields and not computed:
741            return None
742
743        for output_name, value in computed.items():
744            if output_name in fields and not self.quiet:
745                logging.warning('ComputedFieldsTransform overwriting existing '
746                                'field: %s', output_name)
747            result.fields[output_name] = value
748
749        if self._should_attach_metadata(timestamp):
750            result.metadata.update(self.metadata)
751
752        if dict_input:
753            if enveloped:
754                envelope = {'timestamp': result.timestamp,
755                            'fields': result.fields}
756                if result.data_id is not None:
757                    envelope['data_id'] = result.data_id
758                if result.metadata:
759                    envelope['metadata'] = result.metadata
760                return envelope
761            return result.fields
762
763        return result
764
765    ############################
766    def _should_attach_metadata(self, timestamp):
767        """Is it time to send metadata along again?"""
768        if not self.metadata_interval or not self.metadata:
769            return False
770        if timestamp > self.last_metadata_send + self.metadata_interval:
771            self.last_metadata_send = timestamp
772            return True
773        return False

Compute new record fields from algebraic expressions over existing ones.

The callables and named constants an equation may use are class attributes, so a subclass can widen them without touching this module - and without this module acquiring the subclass's dependencies:

class GSWComputedFieldsTransform(ComputedFieldsTransform):
    FUNCTIONS = {**ComputedFieldsTransform.FUNCTIONS,
                 'gsw_z_from_p': gsw.z_from_p}

Names must be flat. Attribute access is refused by the expression checker - it is the main sandbox escape - so "gsw.z_from_p(...)" could never parse.

A subclass adding functions that can return NaN rather than raising, as the TEOS-10 routines do, should guard against that: everything in the default table raises on bad input, so a NaN would otherwise travel quietly into the data stream.

ComputedFieldsTransform( fields, delete_input_fields=False, delete_other_fields=False, warn_missing_inputs=False, cache_inputs=False, update_on_fields=None, max_field_age=None, data_id=None, metadata_interval=None, **kwargs)
214    def __init__(self, fields,
215                 delete_input_fields=False, delete_other_fields=False,
216                 warn_missing_inputs=False,
217                 cache_inputs=False, update_on_fields=None, max_field_age=None,
218                 data_id=None, metadata_interval=None, **kwargs):
219        """
220        ```
221        fields
222            A dict of the fields to compute, keyed by the name of the field to
223            be *produced*. Note that this is the opposite of
224            ModifyValueTransform, which keys by input field; keying by output
225            is what lets a single rule draw on several inputs.
226
227            fields:
228              SeawaterTempCorrected:
229                equation: "sbe38_slope * SeawaterTemp + sbe38_offset"
230                constants:
231                  sbe38_slope:  1.00021
232                  sbe38_offset: -0.0032
233                metadata: SBE38 with linear calibration applied
234
235              DepthCorrected:
236                equation: "(Pressure - (10.1325 if pressure_is_absolute else 0))
237                           * conv_coefficient"
238                constants:
239                  pressure_is_absolute: true
240                  conv_coefficient: 1.0
241
242              SoundVelocity:
243                equation: "1449.2 + 4.6*T - 0.055*T**2 + 1.39*(S-35) + 0.016*D"
244                inputs: {T: SeawaterTemp, S: Salinity, D: Depth}
245                delete_input_fields: true
246
247            Per-rule keys:
248
249            equation (required)
250                The expression to evaluate. Bare names refer to record fields,
251                to the results of rules listed before this one, to entries in
252                'constants', to entries in 'inputs', or to one of the functions
253                listed under "Writing equations" below.
254
255            constants (default {})
256                Values to make available to the equation by name. These may be
257                numbers, booleans or strings. A constant whose value is null
258                disables the rule - the usual way to say "this device is not
259                calibrated" without having to remove the logger.
260
261            inputs (default {})
262                Optional alias -> field name mapping, so that a standard formula
263                can be written in textbook notation and pointed at
264                differently-named fields. Purely for readability; bare field
265                names work without it.
266
267            delete_input_fields (default: the transform-wide setting)
268                Whether the fields this rule read should be dropped from the
269                result.
270
271            intermediate (default False)
272                If true, this rule's result is available to the rules listed
273                after it, but is not added to the output. See "Rules in
274                sequence" below.
275
276            metadata (default None)
277                Metadata to attach for the computed field. Ignored for an
278                intermediate rule.
279
280        delete_input_fields (default False)
281            Drop the fields that equations read from the result.
282
283        delete_other_fields (default False)
284            Drop the fields that no equation read from the result.
285
286            The two flags are independent, and all four combinations are
287            useful:
288
289              False/False  record plus computed values - enhancing an inline
290                           data stream, the default
291              True/False   calibrate in place, leaving the rest of the record
292              True/True    computed values only - reading from a CachedDataServer,
293                           computing, and writing back
294              False/True   computed values plus the inputs they used
295
296            If you want something in between - computed values plus a couple of
297            identifying fields - compose with SelectFieldsTransform downstream
298            rather than reaching for another option here.
299
300        warn_missing_inputs (default False)
301            Whether to warn when a rule cannot fire because its inputs are
302            absent. False by default because a stream may carry many record
303            types, only some of which have the fields a given rule wants; on a
304            mixed stream the normal case would otherwise warn on nearly every
305            record. Regardless of this setting, a debug message is emitted when
306            *some* of a rule's inputs are present and others are missing, which
307            is the genuinely suspicious case. 'quiet' suppresses the warning
308            even when this is set.
309
310        cache_inputs (default False)
311            Retain the most recent value of each input field across records, so
312            that an equation can combine readings that arrive in separate
313            records - which is what happens when inputs come from different
314            instruments by way of a CachedDataServer. Implied by
315            update_on_fields or max_field_age.
316
317        update_on_fields (default None)
318            A list of field names; compute only when a record carries one of
319            them. Without this, every record that completes a rule's inputs
320            produces a new value, so a correction drawing on a slow-moving
321            secondary input would re-emit each time that input ticked rather
322            than when a new primary reading arrived.
323
324        max_field_age (default None)
325            A dict of field name -> seconds. A cached value older than its
326            limit counts as missing, so a rule will not fire on it. Fields not
327            named here never expire.
328
329            update_on_fields and max_field_age follow TrueWindsTransform, which
330            has the same two options with the same meanings.
331
332        data_id (default None)
333            data_id to assign to the result, if the record does not carry one.
334
335        metadata_interval (default None)
336            If set, how often in seconds to attach field metadata to records.
337
338        Writing equations
339        -----------------
340        An equation may use arithmetic (+ - * / // % **), comparisons, boolean
341        operators, and conditional expressions ("x if cond else y"). Field
342        values are passed through as they arrive and are not coerced, so a
343        field holding 'N' or 'S' can be compared as a string.
344
345        These functions are available:
346
347                abs acos asin atan atan2 ceil cos degrees exp float floor
348                fmod hypot int log log10 max min pow radians round sin sqrt
349                tan
350
351        along with the constants pi and e.
352
353        The exponent of ** must be a literal number, and at most 64. This is a
354        deliberate guard rather than an oversight: "9**9**9" is otherwise an
355        ordinary expression that would hang the logger and exhaust its memory.
356
357        Rules in sequence
358        -----------------
359        Rules are evaluated in the order they are listed, and an equation can
360        use the result of any rule listed before it, by that rule's name (or
361        through an alias in 'inputs'). Mark a rule "intermediate: true" to use
362        its result in later rules without outputting it:
363
364            fields:
365              x:
366                equation: "wspd * cos(radians(270 - wdir))"
367                intermediate: true
368              y:
369                equation: "wspd * sin(radians(270 - wdir))"
370                intermediate: true
371              WindSpeed:
372                equation: "hypot(x, y)"
373
374        If an earlier rule produces no value for a record - because its inputs
375        are missing, or its equation gives None, or it is disabled by a null
376        constant - then no rule that uses its result fires either. So an
377        intermediate rule such as
378
379              valid:
380                equation: "True if 0 <= heading <= 360 else None"
381                intermediate: true
382
383        lets a later rule compute only from sensible inputs by mentioning it:
384        "(heading + offset) % 360 if valid else None".
385
386        A name matching a rule listed *after* the one using it is not that
387        rule's result: it is read from the record. That is what lets a rule
388        use a raw value that a later rule replaces in place, but as it is more
389        often a rule listed in the wrong order, it is logged as a warning when
390        the transform starts.
391
392        test/configs/computed_true_winds.yaml is a worked example: true winds,
393        computed with the formulas TrueWindsTransform uses.
394
395        Equations are checked when the transform is constructed, not per
396        record, so a typo or a refused construct stops the logger at startup
397        rather than failing quietly mid-cruise - and validate_config can catch
398        it before anyone sails. They are not eval()'d naively: the expression
399        is parsed and every construct checked against an allowlist, with no
400        builtins and no attribute access.
401
402        To make further functions available - the TEOS-10 routines in gsw, for
403        instance - subclass this transform and widen its FUNCTIONS table rather
404        than editing it in place. See the class docstring.
405        ```
406        """
407        super().__init__(**kwargs)  # processes 'quiet' and type hints
408
409        if not AST_MODULE_FOUND:
410            raise RuntimeError('ComputedFieldsTransform is not available: '
411                               'could not import the standard library "ast" '
412                               'module, which is needed to parse and check '
413                               'equations before they are evaluated.')
414
415        if not isinstance(fields, dict) or not fields:
416            raise ValueError('ComputedFieldsTransform requires a non-empty '
417                             '"fields" dict, keyed by the name of each field '
418                             'to be computed.')
419
420        self.delete_input_fields = delete_input_fields
421        self.delete_other_fields = delete_other_fields
422        self.warn_missing_inputs = warn_missing_inputs
423        self.data_id = data_id
424        self.metadata_interval = metadata_interval or 0
425        self.last_metadata_send = 0
426
427        self.update_on_fields = list(update_on_fields or [])
428        self.max_field_age = dict(max_field_age or {})
429        # Caching is what makes update_on_fields and max_field_age mean
430        # anything, so declaring either turns it on.
431        self.cache_inputs = bool(cache_inputs or self.update_on_fields
432                                 or self.max_field_age)
433        # field name -> (value, timestamp)
434        self.cache = {}
435
436        # Which (rule, missing-fields) combinations we have already mentioned.
437        # A rule perpetually missing the same field on a 10Hz stream would
438        # otherwise bury the log at exactly the moment someone raises
439        # verbosity to find out why.
440        self._reported_missing = set()
441
442        self.rules = {}
443        self.metadata = {}
444        # Every output named so far, including those of disabled rules: a
445        # rule that uses a disabled rule's result must not fire, rather than
446        # quietly reading a record field that happens to have the same name.
447        earlier_outputs = set()
448        for output_name, spec in fields.items():
449            rule = self._build_rule(output_name, spec)
450            if rule:
451                # Rules are evaluated in the order given, and a name that
452                # matches an earlier rule's output reads that rule's result
453                # rather than a record field.
454                rule['earlier_results'] = {
455                    name for name, field in rule['input_fields'].items()
456                    if field in earlier_outputs}
457                self.rules[output_name] = rule
458                if rule['metadata'] and not rule['intermediate']:
459                    self.metadata[output_name] = rule['metadata']
460            earlier_outputs.add(output_name)
461
462        # A name matching a *later* rule's output still reads a record field.
463        # That is right for a rule that uses a raw value which a later rule
464        # replaces, but is more often a rule listed in the wrong order, so say
465        # so at startup.
466        if not self.quiet:
467            outputs = list(fields)
468            for output_name, rule in self.rules.items():
469                later = outputs[outputs.index(output_name) + 1:]
470                for name, field in rule['input_fields'].items():
471                    if field in later:
472                        logging.warning(
473                            'ComputedFieldsTransform: "%s" uses "%s", which is '
474                            'also the output of a rule listed after it. Rules '
475                            'can use only the results of rules listed before '
476                            'them, so this reads the record field "%s". If you '
477                            'meant the computed value, move "%s" after "%s".',
478                            output_name, name, field, output_name, field)
479
480        # Every record field any rule might read. Used to tell an "input" from
481        # an "other" field when applying the two deletion flags, and to decide
482        # what is worth caching.
483        self.all_input_fields = set()
484        for rule in self.rules.values():
485            self.all_input_fields.update(
486                field for name, field in rule['input_fields'].items()
487                if name not in rule['earlier_results'])
fields
    A dict of the fields to compute, keyed by the name of the field to
    be *produced*. Note that this is the opposite of
    ModifyValueTransform, which keys by input field; keying by output
    is what lets a single rule draw on several inputs.

    fields:
      SeawaterTempCorrected:
        equation: "sbe38_slope * SeawaterTemp + sbe38_offset"
        constants:
          sbe38_slope:  1.00021
          sbe38_offset: -0.0032
        metadata: SBE38 with linear calibration applied

      DepthCorrected:
        equation: "(Pressure - (10.1325 if pressure_is_absolute else 0))
                   * conv_coefficient"
        constants:
          pressure_is_absolute: true
          conv_coefficient: 1.0

      SoundVelocity:
        equation: "1449.2 + 4.6*T - 0.055*T**2 + 1.39*(S-35) + 0.016*D"
        inputs: {T: SeawaterTemp, S: Salinity, D: Depth}
        delete_input_fields: true

    Per-rule keys:

    equation (required)
        The expression to evaluate. Bare names refer to record fields,
        to the results of rules listed before this one, to entries in
        'constants', to entries in 'inputs', or to one of the functions
        listed under "Writing equations" below.

    constants (default {})
        Values to make available to the equation by name. These may be
        numbers, booleans or strings. A constant whose value is null
        disables the rule - the usual way to say "this device is not
        calibrated" without having to remove the logger.

    inputs (default {})
        Optional alias -> field name mapping, so that a standard formula
        can be written in textbook notation and pointed at
        differently-named fields. Purely for readability; bare field
        names work without it.

    delete_input_fields (default: the transform-wide setting)
        Whether the fields this rule read should be dropped from the
        result.

    intermediate (default False)
        If true, this rule's result is available to the rules listed
        after it, but is not added to the output. See "Rules in
        sequence" below.

    metadata (default None)
        Metadata to attach for the computed field. Ignored for an
        intermediate rule.

delete_input_fields (default False)
    Drop the fields that equations read from the result.

delete_other_fields (default False)
    Drop the fields that no equation read from the result.

    The two flags are independent, and all four combinations are
    useful:

      False/False  record plus computed values - enhancing an inline
                   data stream, the default
      True/False   calibrate in place, leaving the rest of the record
      True/True    computed values only - reading from a CachedDataServer,
                   computing, and writing back
      False/True   computed values plus the inputs they used

    If you want something in between - computed values plus a couple of
    identifying fields - compose with SelectFieldsTransform downstream
    rather than reaching for another option here.

warn_missing_inputs (default False)
    Whether to warn when a rule cannot fire because its inputs are
    absent. False by default because a stream may carry many record
    types, only some of which have the fields a given rule wants; on a
    mixed stream the normal case would otherwise warn on nearly every
    record. Regardless of this setting, a debug message is emitted when
    *some* of a rule's inputs are present and others are missing, which
    is the genuinely suspicious case. 'quiet' suppresses the warning
    even when this is set.

cache_inputs (default False)
    Retain the most recent value of each input field across records, so
    that an equation can combine readings that arrive in separate
    records - which is what happens when inputs come from different
    instruments by way of a CachedDataServer. Implied by
    update_on_fields or max_field_age.

update_on_fields (default None)
    A list of field names; compute only when a record carries one of
    them. Without this, every record that completes a rule's inputs
    produces a new value, so a correction drawing on a slow-moving
    secondary input would re-emit each time that input ticked rather
    than when a new primary reading arrived.

max_field_age (default None)
    A dict of field name -> seconds. A cached value older than its
    limit counts as missing, so a rule will not fire on it. Fields not
    named here never expire.

    update_on_fields and max_field_age follow TrueWindsTransform, which
    has the same two options with the same meanings.

data_id (default None)
    data_id to assign to the result, if the record does not carry one.

metadata_interval (default None)
    If set, how often in seconds to attach field metadata to records.

Writing equations
-----------------
An equation may use arithmetic (+ - * / // % **), comparisons, boolean
operators, and conditional expressions ("x if cond else y"). Field
values are passed through as they arrive and are not coerced, so a
field holding 'N' or 'S' can be compared as a string.

These functions are available:

        abs acos asin atan atan2 ceil cos degrees exp float floor
        fmod hypot int log log10 max min pow radians round sin sqrt
        tan

along with the constants pi and e.

The exponent of ** must be a literal number, and at most 64. This is a
deliberate guard rather than an oversight: "9**9**9" is otherwise an
ordinary expression that would hang the logger and exhaust its memory.

Rules in sequence
-----------------
Rules are evaluated in the order they are listed, and an equation can
use the result of any rule listed before it, by that rule's name (or
through an alias in 'inputs'). Mark a rule "intermediate: true" to use
its result in later rules without outputting it:

    fields:
      x:
        equation: "wspd * cos(radians(270 - wdir))"
        intermediate: true
      y:
        equation: "wspd * sin(radians(270 - wdir))"
        intermediate: true
      WindSpeed:
        equation: "hypot(x, y)"

If an earlier rule produces no value for a record - because its inputs
are missing, or its equation gives None, or it is disabled by a null
constant - then no rule that uses its result fires either. So an
intermediate rule such as

      valid:
        equation: "True if 0 <= heading <= 360 else None"
        intermediate: true

lets a later rule compute only from sensible inputs by mentioning it:
"(heading + offset) % 360 if valid else None".

A name matching a rule listed *after* the one using it is not that
rule's result: it is read from the record. That is what lets a rule
use a raw value that a later rule replaces in place, but as it is more
often a rule listed in the wrong order, it is logged as a warning when
the transform starts.

test/configs/computed_true_winds.yaml is a worked example: true winds,
computed with the formulas TrueWindsTransform uses.

Equations are checked when the transform is constructed, not per
record, so a typo or a refused construct stops the logger at startup
rather than failing quietly mid-cruise - and validate_config can catch
it before anyone sails. They are not eval()'d naively: the expression
is parsed and every construct checked against an allowlist, with no
builtins and no attribute access.

To make further functions available - the TEOS-10 routines in gsw, for
instance - subclass this transform and widen its FUNCTIONS table rather
than editing it in place. See the class docstring.
FUNCTIONS = {'abs': <built-in function abs>, 'min': <built-in function min>, 'max': <built-in function max>, 'round': <built-in function round>, 'pow': <built-in function pow>, 'int': <class 'int'>, 'float': <class 'float'>, 'exp': <built-in function exp>, 'log': <built-in function log>, 'log10': <built-in function log10>, 'sqrt': <built-in function sqrt>, 'sin': <built-in function sin>, 'cos': <built-in function cos>, 'tan': <built-in function tan>, 'asin': <built-in function asin>, 'acos': <built-in function acos>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'hypot': <built-in function hypot>, 'degrees': <built-in function degrees>, 'radians': <built-in function radians>, 'floor': <built-in function floor>, 'ceil': <built-in function ceil>, 'fmod': <built-in function fmod>}
CONSTANTS = {'pi': 3.141592653589793, 'e': 2.718281828459045}
delete_input_fields
delete_other_fields
warn_missing_inputs
data_id
metadata_interval
last_metadata_send
update_on_fields
max_field_age
cache_inputs
cache
rules
metadata
all_input_fields
def transform(self, record: Union[logger.utils.das_record.DASRecord, dict]):
665    def transform(self, record: Union[DASRecord, dict]):
666        """Compute the configured fields and return the record."""
667        # See if it's something we can process, and if not, try digesting
668        if not self.can_process_record(record):  # inherited from BaseModule()
669            return self.digest_record(record)  # inherited from BaseModule()
670
671        # Hand back the shape we were given, as SelectFieldsTransform and
672        # DeltaTransform do.
673        dict_input = isinstance(record, dict)
674        enveloped = False
675        if dict_input:
676            if isinstance(record.get('fields'), dict):
677                enveloped = True
678                record = DASRecord(fields=record['fields'],
679                                   data_id=record.get('data_id', self.data_id),
680                                   timestamp=record.get('timestamp', 0))
681            else:
682                record = DASRecord(fields=record, data_id=self.data_id)
683
684        fields = record.fields
685        timestamp = record.timestamp or time.time()
686
687        # Update the cache before evaluating, so a record carrying several
688        # inputs at once resolves all of them.
689        triggered = not self.update_on_fields
690        if self.cache_inputs:
691            for field, value in fields.items():
692                if field in self.all_input_fields:
693                    _, previous_time = self.cache.get(field, (None, 0))
694                    if timestamp >= previous_time:
695                        self.cache[field] = (value, timestamp)
696        for field in self.update_on_fields:
697            if field in fields:
698                triggered = True
699
700        result = copy.deepcopy(record)
701
702        computed = {}
703        consumed = set()
704        if triggered:
705            for output_name, rule in self.rules.items():
706                values, missing = self._resolve_inputs(rule, fields, timestamp,
707                                                       computed)
708                if missing:
709                    self._note_missing(output_name, rule, missing, len(values))
710                    continue
711                value = self._evaluate(output_name, rule, values)
712                if value is None:
713                    continue
714                computed[output_name] = value
715                if rule['delete_input_fields']:
716                    consumed.update(rule['input_fields'].values())
717            computed = {name: value for name, value in computed.items()
718                        if not self.rules[name]['intermediate']}
719        else:
720            logging.debug('ComputedFieldsTransform: no field in %s updated; '
721                          'not recomputing', self.update_on_fields)
722
723        # Apply the two deletion flags. Deletion happens only once every output
724        # has been computed - a field feeding two rules would otherwise vanish
725        # before the second one read it.
726        for field in list(result.fields):
727            if field in self.all_input_fields:
728                if field in consumed:
729                    del result.fields[field]
730            elif self.delete_other_fields and field not in computed:
731                del result.fields[field]
732
733        # If the caller asked for derived values only and this record did not
734        # produce any, there is nothing to publish. Returning the surviving
735        # input fields would republish raw readings under the derived
736        # measurement's name - in a CachedDataServer round-trip that means a
737        # CTD value reappearing as though it were an oxygen correction.
738        # DeltaTransform sets the precedent of returning None when it has
739        # nothing to say.
740        if self.delete_other_fields and not computed:
741            return None
742
743        for output_name, value in computed.items():
744            if output_name in fields and not self.quiet:
745                logging.warning('ComputedFieldsTransform overwriting existing '
746                                'field: %s', output_name)
747            result.fields[output_name] = value
748
749        if self._should_attach_metadata(timestamp):
750            result.metadata.update(self.metadata)
751
752        if dict_input:
753            if enveloped:
754                envelope = {'timestamp': result.timestamp,
755                            'fields': result.fields}
756                if result.data_id is not None:
757                    envelope['data_id'] = result.data_id
758                if result.metadata:
759                    envelope['metadata'] = result.metadata
760                return envelope
761            return result.fields
762
763        return result

Compute the configured fields and return the record.