|
| 1 | +""" |
| 2 | +Define MeasureSet class. |
| 3 | +""" |
| 4 | + |
| 5 | +__all__ = ['MeasureSet', |
| 6 | + 'FILE_EXT'] |
| 7 | + |
| 8 | +import os |
| 9 | +import copy |
| 10 | +import logging |
| 11 | + |
| 12 | +from climada.entity.measures.base import Measure |
| 13 | +from climada.entity.measures.source import READ_SET |
| 14 | +from climada.util.files_handler import to_list, get_file_names |
| 15 | +from climada.entity.tag import Tag |
| 16 | + |
| 17 | +LOGGER = logging.getLogger(__name__) |
| 18 | + |
| 19 | +FILE_EXT = {'.mat': 'MAT', |
| 20 | + '.xls': 'XLS', |
| 21 | + '.xlsx': 'XLS' |
| 22 | + } |
| 23 | +""" Supported files format to read from """ |
| 24 | + |
| 25 | +class MeasureSet(): |
| 26 | + """Contains measures of type Measure. Loads from |
| 27 | + files with format defined in FILE_EXT. |
| 28 | +
|
| 29 | + Attributes: |
| 30 | + tag (Tag): information about the source data |
| 31 | + _data (dict): cotains Measure classes. It's not suppossed to be |
| 32 | + directly accessed. Use the class methods instead. |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__(self, file_name='', description=''): |
| 36 | + """Fill values from file, if provided. |
| 37 | +
|
| 38 | + Parameters: |
| 39 | + file_name (str or list(str), optional): absolute file name(s) or |
| 40 | + folder name containing the files to read |
| 41 | + description (str or list(str), optional): one description of the |
| 42 | + data or a description of each data file |
| 43 | +
|
| 44 | + Raises: |
| 45 | + ValueError |
| 46 | +
|
| 47 | + Examples: |
| 48 | + Fill MeasureSet with values and check consistency data: |
| 49 | +
|
| 50 | + >>> act_1 = Measure() |
| 51 | + >>> act_1.name = 'Seawall' |
| 52 | + >>> act_1.color_rgb = np.array([0.1529, 0.2510, 0.5451]) |
| 53 | + >>> act_1.hazard_intensity = (1, 0) |
| 54 | + >>> act_1.mdd_impact = (1, 0) |
| 55 | + >>> act_1.paa_impact = (1, 0) |
| 56 | + >>> meas = MeasureSet() |
| 57 | + >>> meas.add_Measure(act_1) |
| 58 | + >>> meas.tag.description = "my dummy MeasureSet." |
| 59 | + >>> meas.check() |
| 60 | +
|
| 61 | + Read measures from file and checks consistency data: |
| 62 | +
|
| 63 | + >>> meas = MeasureSet(ENT_TEMPLATE_XLS) |
| 64 | + """ |
| 65 | + self.clear() |
| 66 | + if file_name != '': |
| 67 | + self.read(file_name, description) |
| 68 | + |
| 69 | + def clear(self): |
| 70 | + """Reinitialize attributes.""" |
| 71 | + self.tag = Tag() |
| 72 | + self._data = dict() # {name: Measure()} |
| 73 | + |
| 74 | + def add_measure(self, meas): |
| 75 | + """Add an Measure. |
| 76 | +
|
| 77 | + Parameters: |
| 78 | + meas (Measure): Measure instance |
| 79 | +
|
| 80 | + Raises: |
| 81 | + ValueError |
| 82 | + """ |
| 83 | + if not isinstance(meas, Measure): |
| 84 | + LOGGER.error("Input value is not of type Measure.") |
| 85 | + raise ValueError |
| 86 | + if not meas.name: |
| 87 | + LOGGER.error("Input Measure's name not set.") |
| 88 | + raise ValueError |
| 89 | + self._data[meas.name] = meas |
| 90 | + |
| 91 | + def remove_measure(self, name=None): |
| 92 | + """Remove Measure with provided name. Delete all Measures if no input |
| 93 | + name |
| 94 | +
|
| 95 | + Parameters: |
| 96 | + name (str, optional): measure name |
| 97 | +
|
| 98 | + Raises: |
| 99 | + ValueError |
| 100 | + """ |
| 101 | + if name is not None: |
| 102 | + try: |
| 103 | + del self._data[name] |
| 104 | + except KeyError: |
| 105 | + LOGGER.warning('No Measure with name %s.', name) |
| 106 | + else: |
| 107 | + self._data = dict() |
| 108 | + |
| 109 | + def get_measure(self, name=None): |
| 110 | + """Get Measure with input name. Get all if no name provided. |
| 111 | +
|
| 112 | + Parameters: |
| 113 | + name (str, optional): measure name |
| 114 | +
|
| 115 | + Returns: |
| 116 | + list(Measure) |
| 117 | + """ |
| 118 | + if name is not None: |
| 119 | + try: |
| 120 | + return self._data[name] |
| 121 | + except KeyError: |
| 122 | + return list() |
| 123 | + else: |
| 124 | + return list(self._data.values()) |
| 125 | + |
| 126 | + def get_names(self): |
| 127 | + """Get all Measure names""" |
| 128 | + return list(self._data.keys()) |
| 129 | + |
| 130 | + def num_measures(self): |
| 131 | + """Get number of measures contained """ |
| 132 | + return len(self._data.keys()) |
| 133 | + |
| 134 | + def check(self): |
| 135 | + """Check instance attributes. |
| 136 | +
|
| 137 | + Raises: |
| 138 | + ValueError |
| 139 | + """ |
| 140 | + for act_name, act in self._data.items(): |
| 141 | + if (act_name != act.name) | (act.name == ''): |
| 142 | + raise ValueError('Wrong Measure.name: %s != %s' %\ |
| 143 | + (act_name, act.name)) |
| 144 | + act.check() |
| 145 | + |
| 146 | + def read(self, files, descriptions='', var_names=None): |
| 147 | + """Read and check MeasureSet. |
| 148 | +
|
| 149 | + Parameters: |
| 150 | + files (str or list(str)): absolute file name(s) or folder name |
| 151 | + containing the files to read |
| 152 | + descriptions (str or list(str), optional): one description of the |
| 153 | + data or a description of each data file |
| 154 | + var_names (dict or list(dict), default): name of the variables in |
| 155 | + the file (default: DEF_VAR_NAME defined in the source modules) |
| 156 | +
|
| 157 | + Raises: |
| 158 | + ValueError |
| 159 | + """ |
| 160 | + all_files = get_file_names(files) |
| 161 | + desc_list = to_list(len(all_files), descriptions, 'descriptions') |
| 162 | + var_list = to_list(len(all_files), var_names, 'var_names') |
| 163 | + self.clear() |
| 164 | + for file, desc, var in zip(all_files, desc_list, var_list): |
| 165 | + self.append(self._read_one(file, desc, var)) |
| 166 | + |
| 167 | + def append(self, meas): |
| 168 | + """Check and append measures of input MeasureSet to current MeasureSet. |
| 169 | + Overwrite Measure if same name. |
| 170 | +
|
| 171 | + Parameters: |
| 172 | + meas (MeasureSet): MeasureSet instance to append |
| 173 | +
|
| 174 | + Raises: |
| 175 | + ValueError |
| 176 | + """ |
| 177 | + meas.check() |
| 178 | + if self.num_measures() == 0: |
| 179 | + self.__dict__ = meas.__dict__.copy() |
| 180 | + return |
| 181 | + |
| 182 | + self.tag.append(meas.tag) |
| 183 | + for measure in meas.get_measure(): |
| 184 | + self.add_measure(measure) |
| 185 | + |
| 186 | + @staticmethod |
| 187 | + def get_sup_file_format(): |
| 188 | + """ Get supported file extensions that can be read. |
| 189 | +
|
| 190 | + Returns: |
| 191 | + list(str) |
| 192 | + """ |
| 193 | + return list(FILE_EXT.keys()) |
| 194 | + |
| 195 | + @staticmethod |
| 196 | + def get_def_file_var_names(src_format): |
| 197 | + """Get default variable names for given file format. |
| 198 | +
|
| 199 | + Parameters: |
| 200 | + src_format (str): extension of the file, e.g. '.xls', '.mat'. |
| 201 | +
|
| 202 | + Returns: |
| 203 | + dict: dictionary with variable names |
| 204 | + """ |
| 205 | + try: |
| 206 | + if '.' not in src_format: |
| 207 | + src_format = '.' + src_format |
| 208 | + return copy.deepcopy(READ_SET[FILE_EXT[src_format]][0]) |
| 209 | + except KeyError: |
| 210 | + LOGGER.error('File extension not supported: %s.', src_format) |
| 211 | + raise ValueError |
| 212 | + |
| 213 | + @staticmethod |
| 214 | + def _read_one(file_name, description='', var_names=None): |
| 215 | + """Read input file. |
| 216 | +
|
| 217 | + Parameters: |
| 218 | + file_name (str): name of the source file |
| 219 | + description (str, optional): description of the source data |
| 220 | + var_names (dict), optional): name of the variables in the file |
| 221 | +
|
| 222 | + Raises: |
| 223 | + ValueError |
| 224 | +
|
| 225 | + Returns: |
| 226 | + MeasureSet |
| 227 | + """ |
| 228 | + LOGGER.info('Reading file: %s', file_name) |
| 229 | + new_meas = MeasureSet() |
| 230 | + new_meas.tag = Tag(file_name, description) |
| 231 | + |
| 232 | + extension = os.path.splitext(file_name)[1] |
| 233 | + try: |
| 234 | + reader = READ_SET[FILE_EXT[extension]][1] |
| 235 | + except KeyError: |
| 236 | + LOGGER.error('Input file extension not supported: %s.', extension) |
| 237 | + raise ValueError |
| 238 | + reader(new_meas, file_name, var_names) |
| 239 | + |
| 240 | + return new_meas |
| 241 | + |
| 242 | + def __str__(self): |
| 243 | + return self.tag.__str__() |
| 244 | + |
| 245 | + __repr__ = __str__ |
0 commit comments