openrvdas.logger.transforms.qc_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 11 12from typing import Union 13from logger.utils.das_record import DASRecord # noqa: E402 14from logger.transforms.transform import Transform # noqa: E402 15 16 17################################################################################ 18# 19class QCFilterTransform(Transform): 20 """ 21 Transform that returns None unless values in passed DASRecord are out of 22 bounds, in which case return a warning message. Also return warning if 23 something other than a DASRecord or dict (or list of DASRecord or dict) 24 is passed. 25 26 Note that this module is due to be replaced by a more general value 27 matching transform, as per GitHub feature request: 28 29 https://github.com/OceanDataTools/openrvdas/issues/406 30 """ 31 def __init__(self, bounds, message=None, **kwargs): 32 """ 33 ``` 34 bounds A comma-separated list of conditions of the format 35 36 <field_name>:<lower_bound>:<upper_bound> 37 38 Either <lower_bound> or <upper_bound> may be empty. 39 40 message Optional string to be output instead of default when bounds 41 are violated 42 ``` 43 """ 44 super().__init__(**kwargs) # processes 'quiet' and type hints 45 46 self.message = message 47 self.bounds = {} 48 for condition in bounds.split(','): 49 try: 50 (var, lower_str, upper_str) = condition.split(':') 51 lower = None if lower_str == '' else float(lower_str) 52 upper = None if upper_str == '' else float(upper_str) 53 self.bounds[var] = (lower, upper) 54 except ValueError: 55 raise ValueError('QCFilterTransform bounds must be colon-separated ' 56 'triples of field_name:lower_bound:upper_bound. ' 57 'Found "%s" instead.' % condition) 58 59 ############################ 60 def transform(self, record: Union[DASRecord, dict]) -> str: 61 """Does record violate any bounds?""" 62 63 # See if it's something we can process, and if not, try digesting 64 if not self.can_process_record(record): # inherited from BaseModule() 65 return self.digest_record(record) # inherited from BaseModule() 66 67 # If here, we must be either a DASRecord or dict 68 if type(record) is DASRecord: 69 fields = record.fields 70 elif type(record) is dict: 71 if 'fields' in record: 72 fields = record['fields'] 73 else: 74 fields = record 75 else: 76 logging.warning(f'QCFilterTransform code error. Non-conforming record ' 77 f'of type {type(record)} got through checks: {record}') 78 79 errors = [] 80 for bound in self.bounds: 81 if bound not in fields: 82 continue 83 84 value = fields[bound] # Already checked for existence 85 lower, upper = self.bounds[bound] # Unpack bounds 86 87 if not isinstance(value, (int, float)): 88 err = f'{bound}: non-numeric value: "{value}"' 89 logging.warning(err) 90 errors.append(err) 91 elif lower is not None and value < lower: 92 err = f'{bound}: {value} < lower bound {lower}' 93 logging.warning(err) 94 errors.append(err) 95 elif upper is not None and value > upper: 96 err = f'{bound}: {value} > upper bound {upper}' 97 logging.warning(err) 98 errors.append(err) 99 100 # If no errors, return None. Otherwise either return the specified 101 # message (if we've been given one), or the joined string of 102 # specific failures. 103 if not errors: 104 return None 105 106 if self.message: 107 return self.message 108 else: 109 return '; '.join(errors)
class
QCFilterTransform(logger.transforms.transform.Transform):
20class QCFilterTransform(Transform): 21 """ 22 Transform that returns None unless values in passed DASRecord are out of 23 bounds, in which case return a warning message. Also return warning if 24 something other than a DASRecord or dict (or list of DASRecord or dict) 25 is passed. 26 27 Note that this module is due to be replaced by a more general value 28 matching transform, as per GitHub feature request: 29 30 https://github.com/OceanDataTools/openrvdas/issues/406 31 """ 32 def __init__(self, bounds, message=None, **kwargs): 33 """ 34 ``` 35 bounds A comma-separated list of conditions of the format 36 37 <field_name>:<lower_bound>:<upper_bound> 38 39 Either <lower_bound> or <upper_bound> may be empty. 40 41 message Optional string to be output instead of default when bounds 42 are violated 43 ``` 44 """ 45 super().__init__(**kwargs) # processes 'quiet' and type hints 46 47 self.message = message 48 self.bounds = {} 49 for condition in bounds.split(','): 50 try: 51 (var, lower_str, upper_str) = condition.split(':') 52 lower = None if lower_str == '' else float(lower_str) 53 upper = None if upper_str == '' else float(upper_str) 54 self.bounds[var] = (lower, upper) 55 except ValueError: 56 raise ValueError('QCFilterTransform bounds must be colon-separated ' 57 'triples of field_name:lower_bound:upper_bound. ' 58 'Found "%s" instead.' % condition) 59 60 ############################ 61 def transform(self, record: Union[DASRecord, dict]) -> str: 62 """Does record violate any bounds?""" 63 64 # See if it's something we can process, and if not, try digesting 65 if not self.can_process_record(record): # inherited from BaseModule() 66 return self.digest_record(record) # inherited from BaseModule() 67 68 # If here, we must be either a DASRecord or dict 69 if type(record) is DASRecord: 70 fields = record.fields 71 elif type(record) is dict: 72 if 'fields' in record: 73 fields = record['fields'] 74 else: 75 fields = record 76 else: 77 logging.warning(f'QCFilterTransform code error. Non-conforming record ' 78 f'of type {type(record)} got through checks: {record}') 79 80 errors = [] 81 for bound in self.bounds: 82 if bound not in fields: 83 continue 84 85 value = fields[bound] # Already checked for existence 86 lower, upper = self.bounds[bound] # Unpack bounds 87 88 if not isinstance(value, (int, float)): 89 err = f'{bound}: non-numeric value: "{value}"' 90 logging.warning(err) 91 errors.append(err) 92 elif lower is not None and value < lower: 93 err = f'{bound}: {value} < lower bound {lower}' 94 logging.warning(err) 95 errors.append(err) 96 elif upper is not None and value > upper: 97 err = f'{bound}: {value} > upper bound {upper}' 98 logging.warning(err) 99 errors.append(err) 100 101 # If no errors, return None. Otherwise either return the specified 102 # message (if we've been given one), or the joined string of 103 # specific failures. 104 if not errors: 105 return None 106 107 if self.message: 108 return self.message 109 else: 110 return '; '.join(errors)
Transform that returns None unless values in passed DASRecord are out of bounds, in which case return a warning message. Also return warning if something other than a DASRecord or dict (or list of DASRecord or dict) is passed.
Note that this module is due to be replaced by a more general value matching transform, as per GitHub feature request:
QCFilterTransform(bounds, message=None, **kwargs)
32 def __init__(self, bounds, message=None, **kwargs): 33 """ 34 ``` 35 bounds A comma-separated list of conditions of the format 36 37 <field_name>:<lower_bound>:<upper_bound> 38 39 Either <lower_bound> or <upper_bound> may be empty. 40 41 message Optional string to be output instead of default when bounds 42 are violated 43 ``` 44 """ 45 super().__init__(**kwargs) # processes 'quiet' and type hints 46 47 self.message = message 48 self.bounds = {} 49 for condition in bounds.split(','): 50 try: 51 (var, lower_str, upper_str) = condition.split(':') 52 lower = None if lower_str == '' else float(lower_str) 53 upper = None if upper_str == '' else float(upper_str) 54 self.bounds[var] = (lower, upper) 55 except ValueError: 56 raise ValueError('QCFilterTransform bounds must be colon-separated ' 57 'triples of field_name:lower_bound:upper_bound. ' 58 'Found "%s" instead.' % condition)
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.
message Optional string to be output instead of default when bounds
are violated
def
transform(self, record: Union[logger.utils.das_record.DASRecord, dict]) -> str:
61 def transform(self, record: Union[DASRecord, dict]) -> str: 62 """Does record violate any bounds?""" 63 64 # See if it's something we can process, and if not, try digesting 65 if not self.can_process_record(record): # inherited from BaseModule() 66 return self.digest_record(record) # inherited from BaseModule() 67 68 # If here, we must be either a DASRecord or dict 69 if type(record) is DASRecord: 70 fields = record.fields 71 elif type(record) is dict: 72 if 'fields' in record: 73 fields = record['fields'] 74 else: 75 fields = record 76 else: 77 logging.warning(f'QCFilterTransform code error. Non-conforming record ' 78 f'of type {type(record)} got through checks: {record}') 79 80 errors = [] 81 for bound in self.bounds: 82 if bound not in fields: 83 continue 84 85 value = fields[bound] # Already checked for existence 86 lower, upper = self.bounds[bound] # Unpack bounds 87 88 if not isinstance(value, (int, float)): 89 err = f'{bound}: non-numeric value: "{value}"' 90 logging.warning(err) 91 errors.append(err) 92 elif lower is not None and value < lower: 93 err = f'{bound}: {value} < lower bound {lower}' 94 logging.warning(err) 95 errors.append(err) 96 elif upper is not None and value > upper: 97 err = f'{bound}: {value} > upper bound {upper}' 98 logging.warning(err) 99 errors.append(err) 100 101 # If no errors, return None. Otherwise either return the specified 102 # message (if we've been given one), or the joined string of 103 # specific failures. 104 if not errors: 105 return None 106 107 if self.message: 108 return self.message 109 else: 110 return '; '.join(errors)
Does record violate any bounds?