ods-tools 3.2.2__tar.gz → 3.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. {ods_tools-3.2.2 → ods_tools-3.2.4}/PKG-INFO +1 -1
  2. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/__init__.py +1 -1
  3. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/connector/csv.py +5 -2
  4. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/mapping/base.py +52 -10
  5. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/runner/base.py +11 -17
  6. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/runner/pandas.py +9 -21
  7. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/transformers/grammar.py +2 -2
  8. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/transformers/transform.py +6 -24
  9. ods_tools-3.2.4/ods_tools/odtf/transformers/transform_utils.py +44 -0
  10. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/__init__.py +2 -2
  11. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/common.py +14 -1
  12. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/exposure.py +2 -1
  13. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/oed_schema.py +20 -1
  14. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/setting_schema.py +27 -2
  15. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/source.py +4 -9
  16. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/validator.py +15 -10
  17. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools.egg-info/PKG-INFO +1 -1
  18. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools.egg-info/SOURCES.txt +1 -0
  19. {ods_tools-3.2.2 → ods_tools-3.2.4}/setup.py +1 -1
  20. {ods_tools-3.2.2 → ods_tools-3.2.4}/README.md +0 -0
  21. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/data/__init__.py +0 -0
  22. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/main.py +0 -0
  23. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/__init__.py +0 -0
  24. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/config.py +0 -0
  25. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/connector/__init__.py +0 -0
  26. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/connector/base.py +0 -0
  27. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/controller.py +0 -0
  28. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/data/__init__.py +0 -0
  29. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/errors.py +0 -0
  30. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/files/__init__.py +0 -0
  31. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/files/csv.py +0 -0
  32. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/files/yaml.py +0 -0
  33. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/log.py +0 -0
  34. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/mapping/__init__.py +0 -0
  35. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/mapping/errors.py +0 -0
  36. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/mapping/file.py +0 -0
  37. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/notset.py +0 -0
  38. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/runner/__init__.py +0 -0
  39. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/transformers/__init__.py +0 -0
  40. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/transformers/errors.py +0 -0
  41. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/validator_base.py +0 -0
  42. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/odtf/validator_pandas.py +0 -0
  43. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools/oed/forex.py +0 -0
  44. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools.egg-info/dependency_links.txt +0 -0
  45. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools.egg-info/entry_points.txt +0 -0
  46. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools.egg-info/requires.txt +0 -0
  47. {ods_tools-3.2.2 → ods_tools-3.2.4}/ods_tools.egg-info/top_level.txt +0 -0
  48. {ods_tools-3.2.2 → ods_tools-3.2.4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ods_tools
3
- Version: 3.2.2
3
+ Version: 3.2.4
4
4
  Summary: Tools to manage ODS files
5
5
  Home-page: https://github.com/OasisLMF/OpenDataStandards
6
6
  Author: Oasis LMF
@@ -1,4 +1,4 @@
1
- __version__ = '3.2.2'
1
+ __version__ = '3.2.4'
2
2
 
3
3
  import logging
4
4
 
@@ -70,7 +70,8 @@ class CsvConnector(BaseConnector):
70
70
 
71
71
  def _data_serializer(self, row):
72
72
  return {
73
- k: v if v is not None and not isinstance(v, NotSetType) else ""
73
+ k: f'"{v}"'.strip() if isinstance(v, str) and any(d in v for d in [',', ';', '\t', '\n', '"']) else (
74
+ v if v is not None and not isinstance(v, NotSetType) else "")
74
75
  for k, v in row.items()
75
76
  }
76
77
 
@@ -83,7 +84,9 @@ class CsvConnector(BaseConnector):
83
84
 
84
85
  with open(self.file_path, "w", newline="") as f:
85
86
  writer = csv.DictWriter(
86
- f, fieldnames=list(first_row.keys()), quoting=self.quoting
87
+ f,
88
+ fieldnames=list(first_row.keys()),
89
+ quoting=self.quoting
87
90
  )
88
91
 
89
92
  if self.write_header:
@@ -11,7 +11,7 @@ from typing import (
11
11
  )
12
12
 
13
13
  import networkx as nx
14
- from lark import Tree
14
+ from lark import Tree, Token
15
15
 
16
16
  from ..config import TransformationConfig
17
17
  from .errors import NoConversionPathError
@@ -234,23 +234,65 @@ class BaseMapping:
234
234
  )
235
235
  )
236
236
 
237
- def get_transformations(self) -> List[DirectionalMapping]:
237
+ @staticmethod
238
+ def has_missing_columns(node: Union[Tree, Token, int, None], missing_columns: List[str]) -> bool:
239
+ """
240
+ Recursively checks if a node in the transformation tree contains any missing columns.
241
+
242
+ Args:
243
+ node (Union[Tree, Token, int, None]): The node to check for missing columns.
244
+ missing_columns (List[str]): A list of missing column names.
245
+
246
+ Returns:
247
+ bool: True if the node contains any missing columns, False otherwise.
248
+ """
249
+ if node is None or isinstance(node, int):
250
+ return False
251
+ if isinstance(node, Token):
252
+ return node.type == 'IDENT' and node.value in missing_columns
253
+ if node.data == 'lookup' and BaseMapping.has_missing_columns(node.children[0], missing_columns):
254
+ return True
255
+ return any(BaseMapping.has_missing_columns(child, missing_columns) for child in node.children)
256
+
257
+ def get_transformations(self, available_columns: List[str]) -> List[DirectionalMapping]:
238
258
  """
239
259
  Gets a column transformations and full transformation set for the
240
- provided input and output paths.
260
+ provided input and output paths, filtered based on the available columns.
241
261
 
242
- :return: The mappings along the conversion path.
262
+ :param available_columns: List of available columns in the input data
263
+ :return: The filtered mappings along the conversion path.
243
264
  """
244
265
  path = self.path
245
266
  logger.info(
246
267
  f"Path found {' -> '.join(f'{n.name} v{n.version}' for n in path)}"
247
268
  )
248
- # parse the trees of the path so that is doesnt need
249
- # to be done for every row
250
269
  transformations = [edge["transform"] for edge in self.path_edges]
270
+
271
+ missing_columns = list(set(transformations[0].types.keys()) - set(available_columns))
272
+
273
+ doable_transformations = []
251
274
  for mapping in transformations:
252
- for transform in mapping.transformation_set.values():
253
- for case in transform:
254
- case.parse()
275
+ doable_transformation_set = {}
276
+ for col, transform_list in mapping.transformation_set.items():
277
+ valid_transforms = []
278
+ for transform in transform_list:
279
+ transform.parse()
280
+ if ((transform.transformation_tree is None or
281
+ not self.has_missing_columns(transform.transformation_tree, missing_columns)) and
282
+ (transform.when_tree is None or
283
+ not self.has_missing_columns(transform.when_tree, missing_columns))):
284
+ valid_transforms.append(transform)
285
+ if valid_transforms:
286
+ doable_transformation_set[col] = valid_transforms
287
+ if doable_transformation_set:
288
+ doable_transformations.append(
289
+ DirectionalMapping(
290
+ input_format=mapping.input_format,
291
+ output_format=mapping.output_format,
292
+ transformation_set=doable_transformation_set,
293
+ types=mapping.types,
294
+ null_values=mapping.null_values,
295
+ )
296
+ )
255
297
 
256
- return transformations
298
+ return doable_transformations
@@ -11,7 +11,6 @@ from typing import (
11
11
  List,
12
12
  TypedDict,
13
13
  Union,
14
- Set
15
14
  )
16
15
 
17
16
  from ..config import TransformationConfig
@@ -171,7 +170,6 @@ class _BaseRunner:
171
170
  self,
172
171
  row: RowType,
173
172
  entry_list: List[TransformationEntry],
174
- missing_columns: Set[str] = None,
175
173
  ):
176
174
  """
177
175
  Applies all the transformations for a single output column
@@ -182,25 +180,21 @@ class _BaseRunner:
182
180
 
183
181
  :return: The transformation result
184
182
  """
185
- if entry_list[0].transformation in missing_columns:
186
- return NotSet
187
- else:
188
- result = reduce(
189
- lambda current_column_value, entry: self.combine_column(
190
- row,
191
- current_column_value,
192
- entry,
193
- ),
194
- entry_list,
195
- NotSet,
196
- )
197
- return result
183
+ result = reduce(
184
+ lambda current_column_value, entry: self.combine_column(
185
+ row,
186
+ current_column_value,
187
+ entry,
188
+ ),
189
+ entry_list,
190
+ NotSet,
191
+ )
192
+ return result
198
193
 
199
194
  def apply_transformation_set(
200
195
  self,
201
196
  row: RowType,
202
197
  transformations: DirectionalMapping,
203
- missing_columns: Set[str] = None,
204
198
  ) -> RowType:
205
199
  """
206
200
  Applies all the transformations to produce the output row
@@ -221,7 +215,7 @@ class _BaseRunner:
221
215
  target,
222
216
  **{
223
217
  col_transforms[0]: self.apply_column_transformation(
224
- coerced_row, col_transforms[1], missing_columns=missing_columns
218
+ coerced_row, col_transforms[1]
225
219
  )
226
220
  },
227
221
  ),
@@ -12,7 +12,6 @@ from numpy import nan
12
12
  from ..connector.base import BaseConnector
13
13
  from ..mapping.base import (
14
14
  BaseMapping,
15
- DirectionalMapping,
16
15
  ColumnConversions,
17
16
  TransformationEntry
18
17
  )
@@ -22,9 +21,9 @@ from ..transformers.transform import (
22
21
  RowType,
23
22
  TransformerMapping,
24
23
  default_match,
25
- default_search,
26
- transform_loc_perils
24
+ default_search
27
25
  )
26
+ from ..transformers.transform_utils import replace_multiple
28
27
  from ..notset import NotSet, NotSetType
29
28
  from ..validator_pandas import PandasValidator
30
29
  from .base import BaseRunner
@@ -386,7 +385,7 @@ class PandasRunner(BaseRunner):
386
385
  "str_match": StrMatch(self.series_type),
387
386
  "str_search": StrSearch(self.series_type),
388
387
  "str_join": StrJoin(self.series_type),
389
- "transform_loc_perils": transform_loc_perils,
388
+ "replace_multiple": replace_multiple,
390
389
  }
391
390
 
392
391
  # process the when clause to get a filter series
@@ -423,35 +422,24 @@ class PandasRunner(BaseRunner):
423
422
  def transform(
424
423
  self, extractor: BaseConnector, mapping: BaseMapping
425
424
  ) -> Iterable[Dict[str, Any]]:
426
- transformations = mapping.get_transformations()
425
+ available_columns = set(pd.read_csv(extractor.file_path, nrows=1).columns)
426
+ transformations = mapping.get_transformations(available_columns=available_columns)
427
427
 
428
428
  validator = PandasValidator(search_paths=([os.path.dirname(self.config.path)] if self.config.path else []))
429
429
 
430
430
  logger.info(f"Running transformation set {transformations[0].input_format} -> {transformations[-1].output_format}")
431
431
  total_rows = 0
432
432
  runner_config = self.config.config.get('runner', None)
433
- batch_size = runner_config.get('batch_size', 10000)
433
+ batch_size = runner_config.get('batch_size', 50000)
434
434
 
435
435
  for batch in pd.read_csv(extractor.file_path, chunksize=batch_size, low_memory=False):
436
- # Check if all the columns necessary for the transformations are present. If not, drop the transformations we can't run
437
- missing_columns = set(transformations[0].types.keys()) - set(batch.columns)
438
- updated_transformations = [
439
- DirectionalMapping(
440
- input_format=t.input_format,
441
- output_format=t.output_format,
442
- transformation_set={k: v for k, v in t.transformation_set.items() if k not in missing_columns},
443
- types=t.types,
444
- null_values=t.null_values,
445
- )
446
- for t in transformations
447
- ]
448
436
 
449
- validator.run(self.coerce_row_types(batch, updated_transformations[0].types),
437
+ validator.run(self.coerce_row_types(batch, transformations[0].types),
450
438
  mapping.input_format.name, mapping.input_format.version, mapping.file_type)
451
439
 
452
440
  transformed = batch
453
- for transformation in updated_transformations:
454
- transformed = self.apply_transformation_set(transformed, transformation, missing_columns)
441
+ for transformation in transformations:
442
+ transformed = self.apply_transformation_set(transformed, transformation)
455
443
 
456
444
  validator.run(transformed, mapping.output_format.name, mapping.output_format.version, mapping.file_type)
457
445
  total_rows += len(batch)
@@ -1,6 +1,5 @@
1
1
  from lark import lark
2
2
 
3
-
4
3
  _grammar = r"""
5
4
  ?start: expression
6
5
 
@@ -49,7 +48,7 @@ array: "[" [expression ("," expression)*] "]"
49
48
 
50
49
  ?string_manip: "join(" string [("," expression)*] ")" -> str_join
51
50
  | "replace(" expression [("," pattern "," expression)+] ")" -> str_replace
52
- | "transform_loc_perils(" expression [("," STRING)*] ")" -> transform_loc_perils
51
+ | "replace_multiple(" expression "," string "," string ("," string "," string)* ")" -> replace_multiple
53
52
  | "match(" expression "," pattern ")" -> str_match
54
53
  | "search(" expression "," pattern ")" -> str_search
55
54
 
@@ -60,6 +59,7 @@ array: "[" [expression ("," expression)*] "]"
60
59
  | "ire" string -> iregex
61
60
 
62
61
  ?string: "'" STRING "'" -> string
62
+ | "'''" STRING "'''" -> string
63
63
  | "''" -> string
64
64
 
65
65
  IDENT: /[a-zA-Z][a-zA-Z0-9_]*/
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import re
2
3
  from functools import partial
3
4
  from operator import add, mul, sub
@@ -8,12 +9,14 @@ from lark import Transformer as _LarkTransformer
8
9
  from lark import Tree
9
10
  from lark import exceptions as lark_exceptions
10
11
  from lark import v_args
12
+ from ..transformers.transform_utils import replace_multiple
11
13
 
12
14
  from .errors import UnexpectedCharacters
13
15
  from .grammar import parser
14
16
 
15
17
 
16
18
  RowType = Any
19
+ logger = logging.getLogger(__name__)
17
20
 
18
21
 
19
22
  class TransformerMapping(TypedDict, total=False):
@@ -375,28 +378,6 @@ def default_join(row, join, *elements):
375
378
  return str(join).join(map(str, elements))
376
379
 
377
380
 
378
- def transform_loc_perils(row: RowType, target, *pattern_repl):
379
- if isinstance(target, str):
380
- perils = [p.strip() for p in target.split(',')]
381
- transformed_perils = []
382
-
383
- # Convert the pattern_repl tuple to a list of pairs
384
- pattern_repl_list = list(zip(pattern_repl[::2], pattern_repl[1::2]))
385
-
386
- for peril in perils:
387
- for pattern, repl in pattern_repl_list:
388
- if peril == pattern.strip("'"):
389
- transformed_perils.append(repl.strip("'"))
390
- break
391
- else:
392
- transformed_perils.append(peril)
393
-
394
- # Join the transformed perils using a comma and space
395
- return ', '.join(transformed_perils)
396
- else:
397
- return target
398
-
399
-
400
381
  @v_args(inline=True)
401
382
  class BaseTreeTransformer(_LarkTransformer):
402
383
  """
@@ -425,6 +406,7 @@ class BaseTreeTransformer(_LarkTransformer):
425
406
  str_replace: Callable[[RowType, Any, Pattern, Any], Any]
426
407
  str_match: Callable[[RowType, Any, Pattern, Any], Any]
427
408
  str_search: Callable[[RowType, Any, Pattern, Any], Any]
409
+ replace_multiple: Callable[..., Any]
428
410
 
429
411
  array = v_args(inline=False)(list)
430
412
  string_escape_re = re.compile(r"`([`'])")
@@ -529,7 +511,7 @@ def create_transformer_class(row, transformer_mapping):
529
511
  "str_replace": default_replace,
530
512
  "str_match": default_match,
531
513
  "str_search": default_search,
532
- "transform_loc_perils": transform_loc_perils,
514
+ "replace_multiple": replace_multiple,
533
515
  **(transformer_mapping or {}),
534
516
  }
535
517
 
@@ -560,7 +542,7 @@ def create_transformer_class(row, transformer_mapping):
560
542
  str_replace = partial(mapped_function, "str_replace")
561
543
  str_match = partial(mapped_function, "str_match")
562
544
  str_search = partial(mapped_function, "str_search")
563
-
545
+ replace_multiple = partial(mapped_function, "replace_multiple")
564
546
  return TreeTransformer
565
547
 
566
548
 
@@ -0,0 +1,44 @@
1
+ import logging
2
+ from typing import Any
3
+
4
+ import pandas as pd
5
+
6
+ logger = logging.getLogger(__name__)
7
+ RowType = Any
8
+
9
+
10
+ def replace_multiple(row: RowType, target, source_sep, target_sep, *pattern_repl):
11
+ """
12
+ Transform location perils from source to target perils.
13
+
14
+ Args:
15
+ row (RowType):
16
+ target (_type_): values to be transformed
17
+ source_sep (_type_): delimeter in source values
18
+ target_sep (_type_): delimeter in target values
19
+
20
+ Returns:
21
+ pd.Series: transformed values
22
+ """
23
+ if isinstance(target, pd.Series):
24
+ perils = target.apply(lambda x: [p.strip() for p in str(x).split(source_sep.strip("'"))])
25
+ else:
26
+ return target
27
+
28
+ # Create list of replacements
29
+ pattern_repl_list = list(zip(pattern_repl[::2], pattern_repl[1::2]))
30
+
31
+ def transform_peril(peril_list):
32
+ result = []
33
+ for peril in peril_list:
34
+ for pattern, repl in pattern_repl_list:
35
+ # Replace if our list of replacements contains the peril
36
+ if peril == pattern.strip("'"):
37
+ result.append(repl.strip("'"))
38
+ break
39
+ else:
40
+ result.append(peril)
41
+ return target_sep.strip("'").join(result)
42
+
43
+ result = perils.apply(transform_peril)
44
+ return result
@@ -5,7 +5,7 @@ from .source import OedSource
5
5
  from .common import (
6
6
  OdsException, PANDAS_COMPRESSION_MAP, PANDAS_DEFAULT_NULL_VALUES, USUAL_FILE_NAME, OED_TYPE_TO_NAME,
7
7
  OED_NAME_TO_TYPE, OED_IDENTIFIER_FIELDS, VALIDATOR_ON_ERROR_ACTION, DEFAULT_VALIDATION_CONFIG, OED_PERIL_COLUMNS, fill_empty,
8
- UnknownColumnSaveOption, BLANK_VALUES
8
+ UnknownColumnSaveOption, BLANK_VALUES, is_empty
9
9
  )
10
10
 
11
11
 
@@ -13,5 +13,5 @@ __all__ = [
13
13
  'OedExposure', 'OedSchema', 'OedSource', 'ModelSettingSchema', 'AnalysisSettingSchema',
14
14
  'OdsException', 'PANDAS_COMPRESSION_MAP', 'PANDAS_DEFAULT_NULL_VALUES', 'USUAL_FILE_NAME', 'OED_TYPE_TO_NAME',
15
15
  'OED_NAME_TO_TYPE', 'OED_IDENTIFIER_FIELDS', 'VALIDATOR_ON_ERROR_ACTION', 'DEFAULT_VALIDATION_CONFIG', 'OED_PERIL_COLUMNS', 'fill_empty',
16
- 'UnknownColumnSaveOption', 'BLANK_VALUES'
16
+ 'UnknownColumnSaveOption', 'BLANK_VALUES', 'is_empty'
17
17
  ]
@@ -143,6 +143,19 @@ OED_PERIL_COLUMNS = ['AccPeril', 'PolPerilsCovered', 'PolPeril', 'CondPeril', 'L
143
143
 
144
144
  BLANK_VALUES = {np.nan, '', None, pd.NA, pd.NaT}
145
145
 
146
+ dtype_to_python = {
147
+ 'Int8': int,
148
+ 'Int32': int,
149
+ 'Int64': int,
150
+ 'bytes': lambda x: bytes(x, 'utf-8'),
151
+ 'float64': float,
152
+ 'category': str
153
+ }
154
+
155
+
156
+ def is_empty(df, columns):
157
+ return (df[columns].isnull()) | (df[columns] == '')
158
+
146
159
 
147
160
  def fill_empty(df, columns, value):
148
161
  if isinstance(columns, str):
@@ -151,7 +164,7 @@ def fill_empty(df, columns, value):
151
164
  dtype = getattr(df[column], "dtypes", getattr(df[column], "dtype", None))
152
165
  if dtype.name == 'category' and value not in {None, np.nan}.union(df[column].cat.categories):
153
166
  df[column] = df[column].cat.add_categories(value)
154
- df.loc[df[column].isin(BLANK_VALUES), column] = value
167
+ df.loc[is_empty(df, column), column] = value
155
168
 
156
169
 
157
170
  class UnknownColumnSaveOption(Enum):
@@ -8,6 +8,7 @@ This package manage:
8
8
  import json
9
9
  from copy import deepcopy
10
10
  import logging
11
+ import numpy as np
11
12
  from packaging import version
12
13
  from pathlib import Path
13
14
 
@@ -80,7 +81,7 @@ class OedExposure:
80
81
  if column not in df.columns or not values:
81
82
  return df
82
83
 
83
- return df[df[column].isin(values)]
84
+ return df[np.isin(df[column], values)]
84
85
  return fn
85
86
 
86
87
  loc_filters = [
@@ -4,7 +4,7 @@ from pathlib import Path
4
4
  import numba as nb
5
5
  import numpy as np
6
6
 
7
- from .common import OdsException, BLANK_VALUES, cached_property
7
+ from .common import OdsException, BLANK_VALUES, cached_property, dtype_to_python
8
8
 
9
9
  ENV_ODS_SCHEMA_PATH = os.getenv('ODS_SCHEMA_PATH')
10
10
 
@@ -139,6 +139,25 @@ class OedSchema:
139
139
  return jit_peril_filtering(peril_ids.to_numpy().astype('str'), peril_filters.to_numpy().astype('str'),
140
140
  self.nb_peril_groups_dict if include_sub_group else self.nb_perils_dict)
141
141
 
142
+ @staticmethod
143
+ def get_default_from_ods_fields(ods_fields, field_name):
144
+ field_info = ods_fields.get(field_name.lower())
145
+ if field_info is None:
146
+ return ''
147
+ if field_info['pd_dtype'] == 'category':
148
+ if field_info['Default'] != 'n/a':
149
+ return field_info['Default']
150
+ else:
151
+ return ''
152
+ else:
153
+ if field_info['Default'] != 'n/a':
154
+ return dtype_to_python[field_info['pd_dtype']](field_info['Default'])
155
+ else:
156
+ return np.nan
157
+
158
+ def get_default(self, field_name, oed_type='null'):
159
+ return self.get_default_from_ods_fields(self.schema['input_fields'][oed_type], field_name)
160
+
142
161
  @staticmethod
143
162
  def to_universal_field_name(column: str):
144
163
  """
@@ -36,6 +36,7 @@ class SettingSchema:
36
36
  from_json(cls, setting_json): Creates a new instance of the `SettingSchema` class by loading a JSON file.
37
37
  compatibility(self, settings_data): Updates the loaded JSON data to account for deprecated keys.
38
38
  load(self, settings_fp): Loads the JSON data from a file path.
39
+ check_unique_summary_ids(self, setting_data): Ensures that the JSON data contains unique summary IDs for each runtype.
39
40
  validate(self, setting_data): Validates the loaded JSON data against the schema.
40
41
  get(self, settings_fp, key=None, validate=True): Gets a value from the loaded JSON data.
41
42
 
@@ -159,6 +160,30 @@ class SettingSchema:
159
160
  raise OdsException(f'Invalid {self.settings_type} file or file path: {settings_fp}')
160
161
  return settings_data
161
162
 
163
+ def check_unique_summary_ids(self, setting_data):
164
+ """
165
+ Ensures that the JSON data contains unique summary IDs for each
166
+ runtype.
167
+
168
+ Args:
169
+ setting_data (dict): The loaded JSON data.
170
+
171
+ Returns:
172
+ dict: Exception messages. Will be empty if there are no unique
173
+ summary IDs.
174
+
175
+ """
176
+ exception_msgs = {}
177
+ runtype_summaries = [f'{runtype}_summaries' for runtype in ['gul', 'il', 'ri']]
178
+ for runtype_summary in runtype_summaries:
179
+ summary_ids = [summary.get('id', []) for summary in setting_data.get(runtype_summary, [])]
180
+ duplicate_ids = set(summary_id for summary_id in summary_ids if summary_ids.count(summary_id) > 1)
181
+ if duplicate_ids:
182
+ error_msgs = [f'id {summary_id} is duplicated' for summary_id in duplicate_ids]
183
+ exception_msgs[runtype_summary] = error_msgs
184
+
185
+ return exception_msgs
186
+
162
187
  def validate(self, setting_data, raise_error=True):
163
188
  """
164
189
  Validates the loaded JSON data against the schema.
@@ -174,8 +199,8 @@ class SettingSchema:
174
199
  """
175
200
  validator = jsonschema.Draft4Validator(self.schema)
176
201
  validation_errors = [e for e in validator.iter_errors(setting_data)]
177
- exception_msgs = {}
178
- is_valid = validator.is_valid(setting_data)
202
+ exception_msgs = self.check_unique_summary_ids(setting_data)
203
+ is_valid = validator.is_valid(setting_data) and not exception_msgs
179
204
 
180
205
  if validation_errors:
181
206
  for err in validation_errors:
@@ -7,8 +7,8 @@ from oasis_data_manager.df_reader.config import get_df_reader
7
7
  import numpy as np
8
8
  from chardet.universaldetector import UniversalDetector
9
9
 
10
- from .common import (OED_TYPE_TO_NAME, OdsException, PANDAS_COMPRESSION_MAP, PANDAS_DEFAULT_NULL_VALUES, is_relative, BLANK_VALUES, fill_empty,
11
- UnknownColumnSaveOption, cached_property)
10
+ from .common import (OED_TYPE_TO_NAME, OdsException, PANDAS_COMPRESSION_MAP, PANDAS_DEFAULT_NULL_VALUES, is_relative, fill_empty,
11
+ UnknownColumnSaveOption, cached_property, is_empty)
12
12
  from .forex import convert_currency
13
13
  from .oed_schema import OedSchema
14
14
 
@@ -282,7 +282,7 @@ class OedSource:
282
282
  if oed_df[column].dtype.name == 'category' and '' not in oed_df[column].dtype.categories:
283
283
  oed_df[column] = oed_df[column].cat.add_categories('')
284
284
  oed_df[column] = oed_df[column] # make a copy f the col in case it is read_only
285
- oed_df.loc[oed_df[column].isin(BLANK_VALUES), column] = ''
285
+ oed_df.loc[is_empty(oed_df, column), column] = ''
286
286
  elif pd_dtype[column].startswith('Int'):
287
287
  to_tmp_dtype[column] = 'float'
288
288
 
@@ -302,12 +302,7 @@ class OedSource:
302
302
  """
303
303
  # set default values
304
304
  for col, field_info in column_to_field.items():
305
- if (field_info
306
- and field_info['Default'] != 'n/a'
307
- and (df[col].isna().any() or (field_info['pd_dtype'] == 'category' and df[col].isnull().any()))):
308
- fill_empty(df, col, df[col].dtype.type(field_info['Default']))
309
- elif df[col].dtype.name == 'category':
310
- fill_empty(df, col, '')
305
+ fill_empty(df, col, OedSchema.get_default_from_ods_fields(ods_fields, col))
311
306
 
312
307
  # add required columns that allow blank values if missing
313
308
  present_field = set(field_info['Input Field Name'] for field_info in column_to_field.values())
@@ -1,12 +1,13 @@
1
1
  import functools
2
2
  import json
3
+ import numpy as np
3
4
  import logging
4
5
 
5
6
  from pathlib import Path
6
7
  from collections.abc import Iterable
7
8
 
8
9
  from .common import (OdsException, OED_PERIL_COLUMNS, OED_IDENTIFIER_FIELDS, DEFAULT_VALIDATION_CONFIG,
9
- VALIDATOR_ON_ERROR_ACTION, BLANK_VALUES)
10
+ VALIDATOR_ON_ERROR_ACTION, BLANK_VALUES, is_empty)
10
11
  from .oed_schema import OedSchema
11
12
 
12
13
  logger = logging.getLogger(__name__)
@@ -134,7 +135,7 @@ class Validator:
134
135
  columns = [columns]
135
136
  for column in columns:
136
137
  if field_info.get("Allow blanks?").upper() == 'NO':
137
- missing_value_df = oed_source.dataframe[oed_source.dataframe[column].isin(BLANK_VALUES)]
138
+ missing_value_df = oed_source.dataframe[is_empty(oed_source.dataframe, column)]
138
139
  if not missing_value_df.empty:
139
140
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
140
141
  'msg': f"column '{column}' has missing values in \n"
@@ -222,8 +223,9 @@ class Validator:
222
223
  if occupancy_code_column is None:
223
224
  continue
224
225
  identifier_field = self.identifier_field_maps[oed_source]
225
- invalid_occupancy_code = oed_source.dataframe[~oed_source.dataframe[occupancy_code_column].astype(str).isin(
226
- set(self.exposure.oed_schema.schema['occupancy']) | BLANK_VALUES)]
226
+ invalid_occupancy_code = oed_source.dataframe[~(np.isin(oed_source.dataframe[occupancy_code_column].astype(str),
227
+ list(self.exposure.oed_schema.schema['occupancy']))
228
+ | is_empty(oed_source.dataframe, occupancy_code_column))]
227
229
  if not invalid_occupancy_code.empty:
228
230
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
229
231
  'msg': f"invalid OccupancyCode.\n"
@@ -242,8 +244,9 @@ class Validator:
242
244
  if construction_code_column is None:
243
245
  continue
244
246
  identifier_field = self.identifier_field_maps[oed_source]
245
- invalid_construction_code = oed_source.dataframe[~oed_source.dataframe[construction_code_column].astype(str).isin(
246
- set(self.exposure.oed_schema.schema['construction']) | BLANK_VALUES)]
247
+ invalid_construction_code = oed_source.dataframe[~(np.isin(oed_source.dataframe[construction_code_column].astype(str),
248
+ list(self.exposure.oed_schema.schema['construction']))
249
+ | is_empty(oed_source.dataframe, construction_code_column))]
247
250
  if not invalid_construction_code.empty:
248
251
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
249
252
  'msg': f"invalid ConstructionCode.\n"
@@ -265,8 +268,9 @@ class Validator:
265
268
  identifier_field = self.identifier_field_maps[oed_source]
266
269
  area_code_column = self.field_to_column_maps[oed_source].get('AreaCode')
267
270
  if area_code_column is not None:
268
- country_only_df = oed_source.dataframe[oed_source.dataframe[area_code_column].isin(BLANK_VALUES)]
269
- country_area_df = oed_source.dataframe[~oed_source.dataframe[area_code_column].isin(BLANK_VALUES)]
271
+ country_only_df = oed_source.dataframe[is_empty(oed_source.dataframe, area_code_column)]
272
+ country_area_df = oed_source.dataframe[~is_empty(oed_source.dataframe, area_code_column)]
273
+
270
274
  invalid_country_area = (country_area_df[
271
275
  ~(country_area_df[[country_code_column, area_code_column]]
272
276
  .apply(tuple, axis=1)
@@ -279,8 +283,9 @@ class Validator:
279
283
  f"{invalid_country_area[identifier_field + [country_code_column, area_code_column]]}"})
280
284
  else:
281
285
  country_only_df = oed_source.dataframe
282
- invalid_country = (country_only_df[~country_only_df[country_code_column]
283
- .isin(set(self.exposure.oed_schema.schema['country']) | BLANK_VALUES)])
286
+ invalid_country = (country_only_df[~(np.isin(country_only_df[country_code_column],
287
+ list(self.exposure.oed_schema.schema['country']))
288
+ | is_empty(country_only_df, country_code_column))])
284
289
  if not invalid_country.empty:
285
290
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
286
291
  'msg': f"invalid CountryCode.\n"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ods-tools
3
- Version: 3.2.2
3
+ Version: 3.2.4
4
4
  Summary: Tools to manage ODS files
5
5
  Home-page: https://github.com/OasisLMF/OpenDataStandards
6
6
  Author: Oasis LMF
@@ -35,6 +35,7 @@ ods_tools/odtf/transformers/__init__.py
35
35
  ods_tools/odtf/transformers/errors.py
36
36
  ods_tools/odtf/transformers/grammar.py
37
37
  ods_tools/odtf/transformers/transform.py
38
+ ods_tools/odtf/transformers/transform_utils.py
38
39
  ods_tools/oed/__init__.py
39
40
  ods_tools/oed/common.py
40
41
  ods_tools/oed/exposure.py
@@ -12,7 +12,7 @@ import json
12
12
 
13
13
  SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
14
14
 
15
- OED_VERSION = '3.1.0'
15
+ OED_VERSION = '3.2.0'
16
16
  # ORD_VERSION =
17
17
 
18
18
 
File without changes
File without changes
File without changes