openrvdas.logger.transforms.value_filter_transform

TODO: option to initialize with a message to be output in case of failure.

TODO: option to intialize with a flag saying whether records will be DASRecords or dictionary, or...?

  1#!/usr/bin/env python3
  2"""
  3TODO: option to initialize with a message to be output in case of failure.
  4
  5TODO: option to intialize with a flag saying whether records will be
  6DASRecords or dictionary, or...?
  7
  8"""
  9
 10import logging
 11from typing import Union
 12
 13from logger.utils.das_record import DASRecord  # noqa: E402
 14from logger.transforms.transform import Transform  # noqa: E402
 15
 16
 17################################################################################
 18#
 19class ValueFilterTransform(Transform):
 20    """
 21    Transform that filters out values in a passed DASRecord that are out of bounds."""
 22
 23    def __init__(self, bounds, log_level=logging.INFO, **kwargs):
 24        """
 25        ```
 26        bounds
 27                 A comma-separated list of conditions of the format
 28
 29                    <field_name>:<lower_bound>:<upper_bound>
 30
 31                 Either <lower_bound> or <upper_bound> may be empty. For example:
 32                    # No lower temp, no upper speed
 33                    'SeawaterTemp::50,SpeedOverGround:0:,CourseOverGround:0:360'
 34
 35        log_level
 36                 At what level the transform should log a message when it sees a value
 37                 that is out of bounds. Allowed values are log levels from the logging module,
 38                 e.g. logging.INFO, logging.DEBUG, logging.WARNING, etc.
 39
 40                 If the logger is running in normal mode, it will display messages that
 41                 have log level INFO and more severe (WARNING, ERROR, FATAL). Setting the
 42                 log_level parameter of this transform to logging.WARNING means that any time
 43                 a value falls out of its specified bounds, a WARNING message will be sent to
 44                 the console, appearing in yellow on the web console. logging.ERROR means it will
 45                 appear in red. Setting it to logging.DEBUG means that no message will appear on
 46                 the console.
 47
 48        ```
 49        """
 50        super().__init__(**kwargs)  # processes 'quiet' and type hints
 51
 52        self.bounds = {}
 53        for condition in bounds.split(','):
 54            try:
 55                (var, lower_str, upper_str) = condition.split(':')
 56                lower = None if lower_str == '' else float(lower_str)
 57                upper = None if upper_str == '' else float(upper_str)
 58                self.bounds[var] = (lower, upper)
 59            except ValueError:
 60                raise ValueError('ValueFilterTransform bounds must be colon-separated '
 61                                 'triples of field_name:lower_bound:upper_bound. '
 62                                 f'Found "{condition}" instead.')
 63        if log_level not in [logging.DEBUG, logging.INFO, logging.WARNING,
 64                             logging.ERROR, logging.FATAL]:
 65            raise ValueError('ValueFilterTransform log_level must be a logging module log '
 66                             'level, such as logging.DEBUG, logging.INFO or logging.WARNING. '
 67                             f'Found "{log_level}" instead.')
 68        self.log_level = log_level
 69
 70    ############################
 71    def transform(self, record: Union[dict, DASRecord]) -> Union[dict, DASRecord]:
 72        """Does record violate any bounds?"""
 73
 74        # See if it's something we can process, and if not, try digesting
 75        if not self.can_process_record(record):  # inherited from BaseModule()
 76            return self.digest_record(record)  # inherited from BaseModule()
 77
 78        if type(record) is DASRecord:
 79            fields = record.fields
 80        elif type(record) is dict:
 81            if 'fields' in record:
 82                fields = record['fields']
 83            else:
 84                fields = record
 85        else:
 86            logging.log(self.log_level,
 87                        f'Record passed to ValueFilterTransform was neither a dict nor a '
 88                        f'DASRecord. Type was {type(record)}: {str(record)[:80]}')
 89            return None
 90
 91        for bound in self.bounds:
 92            if bound not in fields:
 93                continue
 94            (lower, upper) = self.bounds[bound]  # what are the upper/lower bounds?
 95
 96            value = fields.get(bound)  # what is the record's value of this field?
 97
 98            # We expect field value to be numeric; if not, complain lightly and remove it
 99            if type(value) is not int and type(value) is not float:
100                logging.log(self.log_level,
101                            'ValueFilterTransform found non-numeric value for {bound}: {value}')
102                del fields[bound]
103
104            # If value exists and is out of bounds, delete it
105            elif lower is not None and value < lower:
106                logging.log(self.log_level,
107                            f'Value for {bound}: {value} less than lower bound {lower}')
108                del fields[bound]
109            elif upper is not None and value > upper:
110                logging.log(self.log_level,
111                            f'Value for {bound}: {value} greater than upper bound {upper}')
112                del fields[bound]
113
114        return record
class ValueFilterTransform(logger.transforms.transform.Transform):
 20class ValueFilterTransform(Transform):
 21    """
 22    Transform that filters out values in a passed DASRecord that are out of bounds."""
 23
 24    def __init__(self, bounds, log_level=logging.INFO, **kwargs):
 25        """
 26        ```
 27        bounds
 28                 A comma-separated list of conditions of the format
 29
 30                    <field_name>:<lower_bound>:<upper_bound>
 31
 32                 Either <lower_bound> or <upper_bound> may be empty. For example:
 33                    # No lower temp, no upper speed
 34                    'SeawaterTemp::50,SpeedOverGround:0:,CourseOverGround:0:360'
 35
 36        log_level
 37                 At what level the transform should log a message when it sees a value
 38                 that is out of bounds. Allowed values are log levels from the logging module,
 39                 e.g. logging.INFO, logging.DEBUG, logging.WARNING, etc.
 40
 41                 If the logger is running in normal mode, it will display messages that
 42                 have log level INFO and more severe (WARNING, ERROR, FATAL). Setting the
 43                 log_level parameter of this transform to logging.WARNING means that any time
 44                 a value falls out of its specified bounds, a WARNING message will be sent to
 45                 the console, appearing in yellow on the web console. logging.ERROR means it will
 46                 appear in red. Setting it to logging.DEBUG means that no message will appear on
 47                 the console.
 48
 49        ```
 50        """
 51        super().__init__(**kwargs)  # processes 'quiet' and type hints
 52
 53        self.bounds = {}
 54        for condition in bounds.split(','):
 55            try:
 56                (var, lower_str, upper_str) = condition.split(':')
 57                lower = None if lower_str == '' else float(lower_str)
 58                upper = None if upper_str == '' else float(upper_str)
 59                self.bounds[var] = (lower, upper)
 60            except ValueError:
 61                raise ValueError('ValueFilterTransform bounds must be colon-separated '
 62                                 'triples of field_name:lower_bound:upper_bound. '
 63                                 f'Found "{condition}" instead.')
 64        if log_level not in [logging.DEBUG, logging.INFO, logging.WARNING,
 65                             logging.ERROR, logging.FATAL]:
 66            raise ValueError('ValueFilterTransform log_level must be a logging module log '
 67                             'level, such as logging.DEBUG, logging.INFO or logging.WARNING. '
 68                             f'Found "{log_level}" instead.')
 69        self.log_level = log_level
 70
 71    ############################
 72    def transform(self, record: Union[dict, DASRecord]) -> Union[dict, DASRecord]:
 73        """Does record violate any bounds?"""
 74
 75        # See if it's something we can process, and if not, try digesting
 76        if not self.can_process_record(record):  # inherited from BaseModule()
 77            return self.digest_record(record)  # inherited from BaseModule()
 78
 79        if type(record) is DASRecord:
 80            fields = record.fields
 81        elif type(record) is dict:
 82            if 'fields' in record:
 83                fields = record['fields']
 84            else:
 85                fields = record
 86        else:
 87            logging.log(self.log_level,
 88                        f'Record passed to ValueFilterTransform was neither a dict nor a '
 89                        f'DASRecord. Type was {type(record)}: {str(record)[:80]}')
 90            return None
 91
 92        for bound in self.bounds:
 93            if bound not in fields:
 94                continue
 95            (lower, upper) = self.bounds[bound]  # what are the upper/lower bounds?
 96
 97            value = fields.get(bound)  # what is the record's value of this field?
 98
 99            # We expect field value to be numeric; if not, complain lightly and remove it
100            if type(value) is not int and type(value) is not float:
101                logging.log(self.log_level,
102                            'ValueFilterTransform found non-numeric value for {bound}: {value}')
103                del fields[bound]
104
105            # If value exists and is out of bounds, delete it
106            elif lower is not None and value < lower:
107                logging.log(self.log_level,
108                            f'Value for {bound}: {value} less than lower bound {lower}')
109                del fields[bound]
110            elif upper is not None and value > upper:
111                logging.log(self.log_level,
112                            f'Value for {bound}: {value} greater than upper bound {upper}')
113                del fields[bound]
114
115        return record

Transform that filters out values in a passed DASRecord that are out of bounds.

ValueFilterTransform(bounds, log_level=20, **kwargs)
24    def __init__(self, bounds, log_level=logging.INFO, **kwargs):
25        """
26        ```
27        bounds
28                 A comma-separated list of conditions of the format
29
30                    <field_name>:<lower_bound>:<upper_bound>
31
32                 Either <lower_bound> or <upper_bound> may be empty. For example:
33                    # No lower temp, no upper speed
34                    'SeawaterTemp::50,SpeedOverGround:0:,CourseOverGround:0:360'
35
36        log_level
37                 At what level the transform should log a message when it sees a value
38                 that is out of bounds. Allowed values are log levels from the logging module,
39                 e.g. logging.INFO, logging.DEBUG, logging.WARNING, etc.
40
41                 If the logger is running in normal mode, it will display messages that
42                 have log level INFO and more severe (WARNING, ERROR, FATAL). Setting the
43                 log_level parameter of this transform to logging.WARNING means that any time
44                 a value falls out of its specified bounds, a WARNING message will be sent to
45                 the console, appearing in yellow on the web console. logging.ERROR means it will
46                 appear in red. Setting it to logging.DEBUG means that no message will appear on
47                 the console.
48
49        ```
50        """
51        super().__init__(**kwargs)  # processes 'quiet' and type hints
52
53        self.bounds = {}
54        for condition in bounds.split(','):
55            try:
56                (var, lower_str, upper_str) = condition.split(':')
57                lower = None if lower_str == '' else float(lower_str)
58                upper = None if upper_str == '' else float(upper_str)
59                self.bounds[var] = (lower, upper)
60            except ValueError:
61                raise ValueError('ValueFilterTransform bounds must be colon-separated '
62                                 'triples of field_name:lower_bound:upper_bound. '
63                                 f'Found "{condition}" instead.')
64        if log_level not in [logging.DEBUG, logging.INFO, logging.WARNING,
65                             logging.ERROR, logging.FATAL]:
66            raise ValueError('ValueFilterTransform log_level must be a logging module log '
67                             'level, such as logging.DEBUG, logging.INFO or logging.WARNING. '
68                             f'Found "{log_level}" instead.')
69        self.log_level = log_level
bounds
         A comma-separated list of conditions of the format

            <field_name>:<lower_bound>:<upper_bound>

         Either <lower_bound> or <upper_bound> may be empty. For example:
            # No lower temp, no upper speed
            'SeawaterTemp::50,SpeedOverGround:0:,CourseOverGround:0:360'

log_level
         At what level the transform should log a message when it sees a value
         that is out of bounds. Allowed values are log levels from the logging module,
         e.g. logging.INFO, logging.DEBUG, logging.WARNING, etc.

         If the logger is running in normal mode, it will display messages that
         have log level INFO and more severe (WARNING, ERROR, FATAL). Setting the
         log_level parameter of this transform to logging.WARNING means that any time
         a value falls out of its specified bounds, a WARNING message will be sent to
         the console, appearing in yellow on the web console. logging.ERROR means it will
         appear in red. Setting it to logging.DEBUG means that no message will appear on
         the console.

bounds
log_level
def transform( self, record: Union[dict, logger.utils.das_record.DASRecord]) -> Union[dict, logger.utils.das_record.DASRecord]:
 72    def transform(self, record: Union[dict, DASRecord]) -> Union[dict, DASRecord]:
 73        """Does record violate any bounds?"""
 74
 75        # See if it's something we can process, and if not, try digesting
 76        if not self.can_process_record(record):  # inherited from BaseModule()
 77            return self.digest_record(record)  # inherited from BaseModule()
 78
 79        if type(record) is DASRecord:
 80            fields = record.fields
 81        elif type(record) is dict:
 82            if 'fields' in record:
 83                fields = record['fields']
 84            else:
 85                fields = record
 86        else:
 87            logging.log(self.log_level,
 88                        f'Record passed to ValueFilterTransform was neither a dict nor a '
 89                        f'DASRecord. Type was {type(record)}: {str(record)[:80]}')
 90            return None
 91
 92        for bound in self.bounds:
 93            if bound not in fields:
 94                continue
 95            (lower, upper) = self.bounds[bound]  # what are the upper/lower bounds?
 96
 97            value = fields.get(bound)  # what is the record's value of this field?
 98
 99            # We expect field value to be numeric; if not, complain lightly and remove it
100            if type(value) is not int and type(value) is not float:
101                logging.log(self.log_level,
102                            'ValueFilterTransform found non-numeric value for {bound}: {value}')
103                del fields[bound]
104
105            # If value exists and is out of bounds, delete it
106            elif lower is not None and value < lower:
107                logging.log(self.log_level,
108                            f'Value for {bound}: {value} less than lower bound {lower}')
109                del fields[bound]
110            elif upper is not None and value > upper:
111                logging.log(self.log_level,
112                            f'Value for {bound}: {value} greater than upper bound {upper}')
113                del fields[bound]
114
115        return record

Does record violate any bounds?