Reference Guide  2.5.0
common_metadata.py
1 # -----------------------------------------------------------------------------
2 # BSD 3-Clause License
3 #
4 # Copyright (c) 2022-2024, Science and Technology Facilities Council
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are met:
9 #
10 # * Redistributions of source code must retain the above copyright notice, this
11 # list of conditions and the following disclaimer.
12 #
13 # * Redistributions in binary form must reproduce the above copyright notice,
14 # this list of conditions and the following disclaimer in the documentation
15 # and/or other materials provided with the distribution.
16 #
17 # * Neither the name of the copyright holder nor the names of its
18 # contributors may be used to endorse or promote products derived from
19 # this software without specific prior written permission.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 # POSSIBILITY OF SUCH DAMAGE.
33 # -----------------------------------------------------------------------------
34 # Author R. W. Ford, STFC Daresbury Lab
35 
36 '''Module containing the CommonMetadata base class which captures the
37 common functionality for LFRic kernel metadata.
38 
39 '''
40 from abc import ABC, abstractmethod
41 
42 from fparser.common.readfortran import FortranStringReader
43 from fparser.two.parser import ParserFactory
44 from fparser.two.utils import NoMatchError, FortranSyntaxError
45 
46 
47 # TODO issue #1886. This class and its subclasses may have
48 # commonalities with the GOcean metadata processing.
49 class CommonMetadata(ABC):
50  '''Abstract class to capture common LFRic kernel metadata.'''
51 
52  # The fparser2 class that captures this metadata.
53  fparser2_class = None
54 
55  @staticmethod
56  def check_fparser2(fparser2_tree, encoding):
57  '''Checks that the fparser2 tree is valid.
58 
59  :param fparser2_tree: fparser2 tree capturing a metadata argument.
60  :type fparser2_tree: :py:class:`fparser.two.Fortran2003.Base`
61  :param encoding: class in which the fparser2 tree should \
62  be encoded.
63  :type encoding: :py:class:`fparser.two.Fortran2003.Base`
64 
65  :raises TypeError: if the fparser2_tree argument is not of the \
66  type specified by the encoding argument.
67 
68  '''
69  if not isinstance(fparser2_tree, encoding):
70  raise TypeError(
71  f"Expected kernel metadata to be encoded as an "
72  f"fparser2 {encoding.__name__} object but found type "
73  f"'{type(fparser2_tree).__name__}' with value "
74  f"'{str(fparser2_tree)}'.")
75 
76  @staticmethod
77  def validate_scalar_value(value, valid_values, name):
78  '''Check that the value argument is one of the values supplied in the
79  valid_values list.
80 
81  :param str value: the value being checked.
82  :param List[str] valid_values: a list of valid values.
83  :param str name: the name of the metadata being checked
84 
85  :raises TypeError: if the value is not a string.
86  :raises ValueError: if the supplied value is not one of the \
87  values in the valid_values list.
88 
89  '''
90  if not isinstance(value, str):
91  raise TypeError(f"The '{name}' value should be of type str, but "
92  f"found '{type(value).__name__}'.")
93  if value.lower() not in valid_values:
94  raise ValueError(
95  f"The '{name}' metadata should be a recognised "
96  f"value (one of {valid_values}) "
97  f"but found '{value}'.")
98 
99  @staticmethod
100  def create_fparser2(fortran_string, encoding):
101  '''Creates an fparser2 tree from a Fortran string. The resultant
102  parent node of the tree will be the same type as the encoding
103  argument if the string conforms to the encoding, otherwise an
104  exception will be raised.
105 
106  TODO: issue #1965: relocate this method as it is not specific
107  to metadata processing.
108 
109  :param str fortran_string: a string containing the metadata in \
110  Fortran.
111  :param encoding: the parent class with which we will encode the \
112  Fortran string.
113  :type encoding: subclass of :py:class:`fparser.two.Fortran2003.Base`
114 
115  :returns: an fparser2 tree containing a metadata \
116  argument.
117  :rtype: subclass of :py:class:`fparser.two.Fortran2003.Base`
118 
119  :raises ValueError: if the Fortran string is not in the \
120  expected form.
121 
122  '''
123  _ = ParserFactory().create(std="f2003")
124  reader = FortranStringReader(fortran_string)
125  match = True
126  try:
127  fparser2_tree = encoding(reader)
128  except (NoMatchError, FortranSyntaxError):
129  match = False
130  if not match or not fparser2_tree:
131  raise ValueError(
132  f"Expected kernel metadata to be a Fortran "
133  f"{encoding.__name__}, but found '{fortran_string}'.")
134  return fparser2_tree
135 
136  @classmethod
137  def create_from_fortran_string(cls, fortran_string):
138  '''Create an instance of this class from Fortran.
139 
140  :param str fortran_string: a string containing the metadata in \
141  Fortran.
142 
143  :returns: an instance of this class.
144  :rtype: subclass of \
145  :py:class:`python.domain.lfric.kernel.CommonMetadata`
146 
147  '''
148  fparser2_tree = cls.create_fparser2create_fparser2(fortran_string, cls.fparser2_classfparser2_class)
149  return cls.create_from_fparser2create_from_fparser2(fparser2_tree)
150 
151  @staticmethod
152  @abstractmethod
153  def create_from_fparser2(fparser2_tree):
154  '''Create an instance of this class from an fparser2 tree.
155 
156  '''
157 
158 
159 __all__ = ["CommonMetadata"]