- 
                Notifications
    You must be signed in to change notification settings 
- Fork 297
Cellmethod tolerance #5126
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Draft
      
      
            pp-mo
  wants to merge
  5
  commits into
  SciTools:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
pp-mo:cellmethod_tolerance
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Draft
                    Cellmethod tolerance #5126
Changes from all commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      10af0c1
              
                Move cell-method parsing to own sourcefile, as it is not part of netc…
              
              
                pp-mo 78ad583
              
                Convert existing tests to pytest.
              
              
                pp-mo 63387d9
              
                Various 'empty' cell-method testcases: failing.
              
              
                pp-mo 2700ff1
              
                Tolerate and warn various 'empty' cell-methods.
              
              
                pp-mo 040dc91
              
                Snapshot some additional existing behaviours.
              
              
                pp-mo File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| # Copyright Iris contributors | ||
| # | ||
| # This file is part of Iris and is released under the LGPL license. | ||
| # See COPYING and COPYING.LESSER in the root of the repository for full | ||
| # licensing details. | ||
| """ | ||
| Helper routines specific to cell method parsing for netcdf-CF loading. | ||
|  | ||
| """ | ||
| import re | ||
| from typing import List | ||
| import warnings | ||
|  | ||
| from iris.coords import CellMethod | ||
|  | ||
| # Cell methods. | ||
| _CM_KNOWN_METHODS = [ | ||
| "point", | ||
| "sum", | ||
| "mean", | ||
| "maximum", | ||
| "minimum", | ||
| "mid_range", | ||
| "standard_deviation", | ||
| "variance", | ||
| "mode", | ||
| "median", | ||
| ] | ||
|  | ||
| _CM_COMMENT = "comment" | ||
| _CM_EXTRA = "extra" | ||
| _CM_INTERVAL = "interval" | ||
| _CM_METHOD = "method" | ||
| _CM_NAME = "name" | ||
| _CM_PARSE_NAME = re.compile(r"([\w_]+\s*?:\s+)+") | ||
| _CM_PARSE = re.compile( | ||
| r""" | ||
| (?P<name>([\w_]+\s*?:\s+)+) | ||
| (?P<method>[\w_\s]+(?![\w_]*\s*?:))\s* | ||
| (?: | ||
| \(\s* | ||
| (?P<extra>.+) | ||
| \)\s* | ||
| )? | ||
| """, | ||
| re.VERBOSE, | ||
| ) | ||
|  | ||
|  | ||
| class UnknownCellMethodWarning(Warning): | ||
| pass | ||
|  | ||
|  | ||
| def _split_cell_methods(nc_cell_methods: str) -> List[re.Match]: | ||
| """ | ||
| Split a CF cell_methods attribute string into a list of zero or more cell | ||
| methods, each of which is then parsed with a regex to return a list of match | ||
| objects. | ||
|  | ||
| Args: | ||
|  | ||
| * nc_cell_methods: The value of the cell methods attribute to be split. | ||
|  | ||
| Returns: | ||
|  | ||
| * nc_cell_methods_matches: A list of the re.Match objects associated with | ||
| each parsed cell method | ||
|  | ||
| Splitting is done based on words followed by colons outside of any brackets. | ||
| Validation of anything other than being laid out in the expected format is | ||
| left to the calling function. | ||
| """ | ||
|  | ||
| # Find name candidates | ||
| name_start_inds = [] | ||
| for m in _CM_PARSE_NAME.finditer(nc_cell_methods): | ||
| name_start_inds.append(m.start()) | ||
|  | ||
| # Remove those that fall inside brackets | ||
| bracket_depth = 0 | ||
| for ind, cha in enumerate(nc_cell_methods): | ||
| if cha == "(": | ||
| bracket_depth += 1 | ||
| elif cha == ")": | ||
| bracket_depth -= 1 | ||
| if bracket_depth < 0: | ||
| msg = ( | ||
| "Cell methods may be incorrectly parsed due to mismatched " | ||
| "brackets" | ||
| ) | ||
| warnings.warn(msg, UserWarning, stacklevel=2) | ||
| if bracket_depth > 0 and ind in name_start_inds: | ||
| name_start_inds.remove(ind) | ||
|  | ||
| # List tuples of indices of starts and ends of the cell methods in the string | ||
| name_start_inds.append(len(nc_cell_methods)) | ||
| method_indices = list(zip(name_start_inds[:-1], name_start_inds[1:])) | ||
|  | ||
| # Index the string and match against each substring | ||
| nc_cell_methods_matches = [] | ||
| for start_ind, end_ind in method_indices: | ||
| nc_cell_method_str = nc_cell_methods[start_ind:end_ind] | ||
| nc_cell_method_match = _CM_PARSE.match(nc_cell_method_str.strip()) | ||
| if not nc_cell_method_match: | ||
| msg = ( | ||
| f"Failed to fully parse cell method string: {nc_cell_methods}" | ||
| ) | ||
| warnings.warn(msg, UserWarning, stacklevel=2) | ||
| continue | ||
| nc_cell_methods_matches.append(nc_cell_method_match) | ||
|  | ||
| return nc_cell_methods_matches | ||
|  | ||
|  | ||
| def parse_cell_methods(nc_cell_methods): | ||
| """ | ||
| Parse a CF cell_methods attribute string into a tuple of zero or | ||
| more CellMethod instances. | ||
|  | ||
| Args: | ||
|  | ||
| * nc_cell_methods (str): | ||
| The value of the cell methods attribute to be parsed. | ||
|  | ||
| Returns: | ||
|  | ||
| * cell_methods | ||
| An iterable of :class:`iris.coords.CellMethod`. | ||
|  | ||
| Multiple coordinates, intervals and comments are supported. | ||
| If a method has a non-standard name a warning will be issued, but the | ||
| results are not affected. | ||
|  | ||
| """ | ||
|  | ||
| cell_methods = [] | ||
| if nc_cell_methods is not None: | ||
| splits = _split_cell_methods(nc_cell_methods) | ||
| if not splits: | ||
| msg = ( | ||
| f"NetCDF variable cell_methods of {nc_cell_methods!r} " | ||
| "contains no valid cell methods." | ||
| ) | ||
| warnings.warn(msg, UserWarning) | ||
| for m in splits: | ||
| d = m.groupdict() | ||
| method = d[_CM_METHOD] | ||
| method = method.strip() | ||
| # Check validity of method, allowing for multi-part methods | ||
| # e.g. mean over years. | ||
| method_words = method.split() | ||
| if method_words[0].lower() not in _CM_KNOWN_METHODS: | ||
| msg = "NetCDF variable contains unknown cell method {!r}" | ||
| warnings.warn( | ||
| msg.format("{}".format(method_words[0])), | ||
| UnknownCellMethodWarning, | ||
| ) | ||
| d[_CM_METHOD] = method | ||
| name = d[_CM_NAME] | ||
| name = name.replace(" ", "") | ||
| name = name.rstrip(":") | ||
| d[_CM_NAME] = tuple([n for n in name.split(":")]) | ||
| interval = [] | ||
| comment = [] | ||
| if d[_CM_EXTRA] is not None: | ||
| # | ||
| # tokenise the key words and field colon marker | ||
| # | ||
| d[_CM_EXTRA] = d[_CM_EXTRA].replace( | ||
| "comment:", "<<comment>><<:>>" | ||
| ) | ||
| d[_CM_EXTRA] = d[_CM_EXTRA].replace( | ||
| "interval:", "<<interval>><<:>>" | ||
| ) | ||
| d[_CM_EXTRA] = d[_CM_EXTRA].split("<<:>>") | ||
| if len(d[_CM_EXTRA]) == 1: | ||
| comment.extend(d[_CM_EXTRA]) | ||
| else: | ||
| next_field_type = comment | ||
| for field in d[_CM_EXTRA]: | ||
| field_type = next_field_type | ||
| index = field.rfind("<<interval>>") | ||
| if index == 0: | ||
| next_field_type = interval | ||
| continue | ||
| elif index > 0: | ||
| next_field_type = interval | ||
| else: | ||
| index = field.rfind("<<comment>>") | ||
| if index == 0: | ||
| next_field_type = comment | ||
| continue | ||
| elif index > 0: | ||
| next_field_type = comment | ||
| if index != -1: | ||
| field = field[:index] | ||
| field_type.append(field.strip()) | ||
| # | ||
| # cater for a shared interval over multiple axes | ||
| # | ||
| if len(interval): | ||
| if len(d[_CM_NAME]) != len(interval) and len(interval) == 1: | ||
| interval = interval * len(d[_CM_NAME]) | ||
| # | ||
| # cater for a shared comment over multiple axes | ||
| # | ||
| if len(comment): | ||
| if len(d[_CM_NAME]) != len(comment) and len(comment) == 1: | ||
| comment = comment * len(d[_CM_NAME]) | ||
| d[_CM_INTERVAL] = tuple(interval) | ||
| d[_CM_COMMENT] = tuple(comment) | ||
| cell_method = CellMethod( | ||
| d[_CM_METHOD], | ||
| coords=d[_CM_NAME], | ||
| intervals=d[_CM_INTERVAL], | ||
| comments=d[_CM_COMMENT], | ||
| ) | ||
| cell_methods.append(cell_method) | ||
| return tuple(cell_methods) | ||
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this should be an Error
#5067 (comment)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well I disagree, for all the reasons listed there.
I think it's just unhelpful to refuse to load a file, if the problem can be stepped around.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In order to work with data from ESGF, it is important for ESMValTool that we can load malformed data and correct the iris cube after loading the bits that are fine. The alternatives are less attractive:
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also recalling this passionate appeal ...
#4506 (comment)
!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But... we are really serious now about the approach (2.) "Use xarray ... convert"
Relating to #4994, proposals are still working up : see here
Current status : I have functional code, and we have pretty much decided now on a plan...
Frankly though, this will take a while to establish properly : I have as yet no home repo, no tests written + plenty of other priorities getting in the way.