power-grid-model-io 1.2.73__py3-none-any.whl → 1.2.74__py3-none-any.whl

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.

Potentially problematic release.


This version of power-grid-model-io might be problematic. Click here for more details.

@@ -11,6 +11,7 @@ from pathlib import Path
11
11
  from typing import Any, Mapping, Optional, Union
12
12
 
13
13
  from power_grid_model_io.converters.tabular_converter import TabularConverter
14
+ from power_grid_model_io.data_stores.base_data_store import LANGUAGE_EN
14
15
  from power_grid_model_io.data_stores.vision_excel_file_store import VisionExcelFileStore
15
16
 
16
17
  DEFAULT_MAPPING_FILE = Path(__file__).parent.parent / "config" / "excel" / "vision_{language:s}.yaml"
@@ -36,17 +37,22 @@ class VisionExcelConverter(TabularConverter):
36
37
  def __init__(
37
38
  self,
38
39
  source_file: Optional[Union[Path, str]] = None,
39
- language: str = "en",
40
- mapping_file: Optional[Path] = None,
40
+ language: str = LANGUAGE_EN,
41
+ terms_changed: Optional[dict] = None,
42
+ mapping_file: Optional[Union[Path, str]] = None,
41
43
  log_level: int = logging.INFO,
42
- ):
43
- _mapping_file = _mapping_file = (
44
- mapping_file if mapping_file is not None else Path(str(DEFAULT_MAPPING_FILE).format(language=language))
44
+ ): # pylint: disable=too-many-arguments
45
+ _mapping_file = Path(
46
+ mapping_file if mapping_file is not None else str(DEFAULT_MAPPING_FILE).format(language=language)
45
47
  )
46
48
  if not _mapping_file.exists():
47
49
  raise FileNotFoundError(f"No Vision Excel mapping available for language '{language}'")
48
50
  self._id_reference: Optional[IdReferenceFields] = None
49
- source = VisionExcelFileStore(file_path=Path(source_file)) if source_file else None
51
+ source = (
52
+ VisionExcelFileStore(file_path=Path(source_file), language=language, terms_changed=terms_changed)
53
+ if source_file
54
+ else None
55
+ )
50
56
  super().__init__(mapping_file=_mapping_file, source=source, log_level=log_level)
51
57
 
52
58
  def set_mapping(self, mapping: Mapping[str, Any]) -> None:
@@ -12,6 +12,21 @@ import structlog
12
12
 
13
13
  T = TypeVar("T")
14
14
 
15
+ LANGUAGE_EN = "en"
16
+ LANGUAGE_NL = "nl"
17
+ DICT_KEY_NUMBER = "key_number"
18
+ DICT_KEY_SUBNUMBER = "key_subnumber"
19
+ VISION_EXCEL_LAN_DICT = {
20
+ LANGUAGE_EN: {
21
+ DICT_KEY_NUMBER: "Number",
22
+ DICT_KEY_SUBNUMBER: "Subnumber",
23
+ },
24
+ LANGUAGE_NL: {
25
+ DICT_KEY_NUMBER: "Nummer",
26
+ DICT_KEY_SUBNUMBER: "Subnummer",
27
+ },
28
+ }
29
+
15
30
 
16
31
  class BaseDataStore(Generic[T], ABC):
17
32
  """
@@ -11,8 +11,21 @@ from typing import Dict, List, Optional, Set, Tuple, Union
11
11
 
12
12
  import pandas as pd
13
13
 
14
- from power_grid_model_io.data_stores.base_data_store import BaseDataStore
14
+ from power_grid_model_io.data_stores.base_data_store import (
15
+ DICT_KEY_NUMBER,
16
+ DICT_KEY_SUBNUMBER,
17
+ VISION_EXCEL_LAN_DICT,
18
+ BaseDataStore,
19
+ )
15
20
  from power_grid_model_io.data_types import LazyDataFrame, TabularData
21
+ from power_grid_model_io.utils.uuid_excel_cvtr import (
22
+ UUID2IntCvtr,
23
+ add_guid_values_to_cvtr,
24
+ get_special_key_map,
25
+ special_nodes_en,
26
+ special_nodes_nl,
27
+ update_column_names,
28
+ )
16
29
 
17
30
 
18
31
  class ExcelFileStore(BaseDataStore[TabularData]):
@@ -28,9 +41,15 @@ class ExcelFileStore(BaseDataStore[TabularData]):
28
41
 
29
42
  _unnamed_pattern: re.Pattern = re.compile(r"Unnamed: \d+_level_\d+")
30
43
 
31
- def __init__(self, file_path: Optional[Path] = None, **extra_paths: Path):
44
+ def __init__(
45
+ self,
46
+ file_path: Optional[Path] = None,
47
+ *,
48
+ language: str = "en",
49
+ terms_changed: Optional[dict] = None,
50
+ **extra_paths: Path,
51
+ ):
32
52
  super().__init__()
33
-
34
53
  # Create a dictionary of all supplied file paths:
35
54
  # {"": file_path, extra_name[0]: extra_path[0], extra_name[1]: extra_path[1], ...}
36
55
  self._file_paths: Dict[str, Path] = {}
@@ -45,6 +64,10 @@ class ExcelFileStore(BaseDataStore[TabularData]):
45
64
  raise ValueError(f"{name} file should be a .xls or .xlsx file, {path.suffix} provided.")
46
65
 
47
66
  self._header_rows: List[int] = [0]
67
+ self._language = language
68
+ self._vision_excel_key_mapping = VISION_EXCEL_LAN_DICT[self._language]
69
+ self._terms_changed = terms_changed if terms_changed is not None else {}
70
+ self._uuid_cvtr = UUID2IntCvtr()
48
71
 
49
72
  def files(self) -> Dict[str, Path]:
50
73
  """
@@ -68,6 +91,8 @@ class ExcelFileStore(BaseDataStore[TabularData]):
68
91
  sheet_data = xls_file.parse(xls_sheet_name, header=self._header_rows)
69
92
  sheet_data = self._remove_unnamed_column_placeholders(data=sheet_data)
70
93
  sheet_data = self._handle_duplicate_columns(data=sheet_data, sheet_name=xls_sheet_name)
94
+ sheet_data = self._process_uuid_columns(data=sheet_data, sheet_name=xls_sheet_name)
95
+ sheet_data = self._update_column_names(data=sheet_data)
71
96
  return sheet_data
72
97
 
73
98
  return sheet_loader
@@ -197,6 +222,32 @@ class ExcelFileStore(BaseDataStore[TabularData]):
197
222
 
198
223
  return to_rename
199
224
 
225
+ def _process_uuid_columns(self, data: pd.DataFrame, sheet_name: str) -> pd.DataFrame:
226
+ first_level = data.columns.get_level_values(0)
227
+ guid_columns = first_level[first_level.str.endswith("GUID")]
228
+
229
+ sheet_key_mapping = get_special_key_map(
230
+ sheet_name=sheet_name, nodes_en=special_nodes_en, nodes_nl=special_nodes_nl
231
+ )
232
+
233
+ for guid_column in guid_columns:
234
+ nr = VISION_EXCEL_LAN_DICT[self._language][DICT_KEY_NUMBER]
235
+ add_guid_values_to_cvtr(data, guid_column, self._uuid_cvtr)
236
+ new_column_name = guid_column.replace("GUID", nr)
237
+ if guid_column == "GUID" and sheet_key_mapping not in (None, {}):
238
+ new_column_name = guid_column.replace("GUID", sheet_key_mapping[DICT_KEY_SUBNUMBER])
239
+ guid_column_pos = first_level.tolist().index(guid_column)
240
+ try:
241
+ data.insert(guid_column_pos + 1, new_column_name, data[guid_column].apply(self._uuid_cvtr.query))
242
+ except ValueError:
243
+ data[new_column_name] = data[guid_column].apply(self._uuid_cvtr.query)
244
+
245
+ return data
246
+
247
+ def _update_column_names(self, data: pd.DataFrame) -> pd.DataFrame:
248
+ update_column_names(data, self._terms_changed)
249
+ return data
250
+
200
251
  @staticmethod
201
252
  def _group_columns_by_index(data: pd.DataFrame) -> Dict[Union[str, Tuple[str, ...]], Set[int]]:
202
253
  grouped: Dict[Union[str, Tuple[str, ...]], Set[int]] = {}
@@ -5,7 +5,9 @@
5
5
  Vision Excel file store
6
6
  """
7
7
  from pathlib import Path
8
+ from typing import Optional
8
9
 
10
+ from power_grid_model_io.data_stores.base_data_store import LANGUAGE_EN
9
11
  from power_grid_model_io.data_stores.excel_file_store import ExcelFileStore
10
12
 
11
13
 
@@ -17,10 +19,15 @@ class VisionExcelFileStore(ExcelFileStore):
17
19
  Therefore, row 1 (which is row 2 in Excel) is added to the header_rows in the constructor.
18
20
  """
19
21
 
20
- def __init__(self, file_path: Path):
22
+ def __init__(
23
+ self,
24
+ file_path: Path,
25
+ language: str = LANGUAGE_EN,
26
+ terms_changed: Optional[dict] = None,
27
+ ):
21
28
  """
22
29
  Args:
23
30
  file_path: The main Vision Excel export file
24
31
  """
25
- super().__init__(file_path)
32
+ super().__init__(file_path, language=language, terms_changed=terms_changed)
26
33
  self._header_rows.append(1) # Units are stored in the row below the column names
@@ -15,10 +15,19 @@
15
15
 
16
16
  import os
17
17
  import re
18
- from typing import Optional
18
+ from pathlib import Path
19
+ from typing import Optional, Union
19
20
 
20
21
  import pandas as pd
21
22
 
23
+ from power_grid_model_io.data_stores.base_data_store import (
24
+ DICT_KEY_NUMBER,
25
+ DICT_KEY_SUBNUMBER,
26
+ LANGUAGE_EN,
27
+ LANGUAGE_NL,
28
+ VISION_EXCEL_LAN_DICT,
29
+ )
30
+
22
31
  special_nodes_en = [
23
32
  "Transformer loads",
24
33
  "Sources",
@@ -111,7 +120,7 @@ class UUID2IntCvtr:
111
120
  return self._counter
112
121
 
113
122
 
114
- def load_excel_file(file_name: str) -> pd.ExcelFile:
123
+ def load_excel_file(file_name: Union[Path, str]) -> pd.ExcelFile:
115
124
  """Load an excel file
116
125
 
117
126
  Args:
@@ -147,6 +156,20 @@ def add_guid_values_to_cvtr(df: pd.DataFrame, guid_column: str, cvtr: UUID2IntCv
147
156
  cvtr.add_list(df[guid_column].tolist())
148
157
 
149
158
 
159
+ def get_special_key_map(sheet_name: str, nodes_en: list[str], nodes_nl: list[str]) -> dict:
160
+ """Get the special nodes for English and Dutch
161
+
162
+ Args:
163
+ sheet_name (str): the sheet name
164
+ mapping (dict): the mapping dictionary
165
+ """
166
+ if sheet_name in nodes_en:
167
+ return VISION_EXCEL_LAN_DICT[LANGUAGE_EN]
168
+ if sheet_name in nodes_nl:
169
+ return VISION_EXCEL_LAN_DICT[LANGUAGE_NL]
170
+ return {}
171
+
172
+
150
173
  def insert_or_update_number_column(
151
174
  df: pd.DataFrame, guid_column: str, sheet_name: str, cvtr: UUID2IntCvtr, number: str
152
175
  ) -> None:
@@ -159,11 +182,10 @@ def insert_or_update_number_column(
159
182
  number (str): "Number" or "Nummer" depending on the language
160
183
  """
161
184
  new_column_name = guid_column.replace("GUID", number)
162
- if guid_column == "GUID":
163
- if sheet_name in special_nodes_en:
164
- new_column_name = guid_column.replace("GUID", "Subnumber")
165
- elif sheet_name in special_nodes_nl:
166
- new_column_name = guid_column.replace("GUID", "Subnummer")
185
+ special_key_mapping = get_special_key_map(sheet_name, special_nodes_en, special_nodes_nl)
186
+
187
+ if guid_column == "GUID" and special_key_mapping not in (None, {}):
188
+ new_column_name = guid_column.replace("GUID", special_key_mapping[DICT_KEY_SUBNUMBER])
167
189
  try:
168
190
  df.insert(df.columns.get_loc(guid_column) + 1, new_column_name, df[guid_column].apply(cvtr.query))
169
191
  except ValueError:
@@ -196,11 +218,15 @@ def save_df_to_excel(df: pd.DataFrame, file_name: str, sheet_name: str, i: int)
196
218
  df.to_excel(writer, sheet_name=sheet_name, index=False)
197
219
 
198
220
 
199
- def convert_guid_vision_excel(excel_file: str, number: str = "Number", terms_changed: Optional[dict] = None) -> str:
221
+ def convert_guid_vision_excel(
222
+ excel_file: Union[Path, str],
223
+ number: str = VISION_EXCEL_LAN_DICT[LANGUAGE_EN][DICT_KEY_NUMBER],
224
+ terms_changed: Optional[dict] = None,
225
+ ) -> str:
200
226
  """Main entry function. Convert the GUID based Vision excel files to a number based format
201
227
 
202
228
  Args:
203
- excel_file (str): Vision excel file name
229
+ excel_file (Path | str): Vision excel file name
204
230
  number (str): "Number" or "Nummer" depending on the language. Defaults to "Number".
205
231
  terms_changed (dict): the dictionary containing the terms to be changed. Defaults to {}.
206
232
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: power-grid-model-io
3
- Version: 1.2.73
3
+ Version: 1.2.74
4
4
  Summary: Power Grid Model Input/Output
5
5
  Author-email: Contributors to the Power Grid Model project <powergridmodel@lfenergy.org>
6
6
  License: MPL-2.0
@@ -10,13 +10,13 @@ power_grid_model_io/converters/base_converter.py,sha256=TICEXyG7PtimAUvhAmpSoZUq
10
10
  power_grid_model_io/converters/pandapower_converter.py,sha256=6gY-mvbVLlKKBxGOM1024pekCtmMeGUxQunN19nYHio,113935
11
11
  power_grid_model_io/converters/pgm_json_converter.py,sha256=uqsDGhf4hilzUQdQXZEfOYXWJnUpMQqTNHXnWQUY-So,13158
12
12
  power_grid_model_io/converters/tabular_converter.py,sha256=_nTfAg88nxuHGqzYZRv0V8ZqUsQW8oKA4GwD15XTkXY,30760
13
- power_grid_model_io/converters/vision_excel_converter.py,sha256=08aRM9No_V3bBdd1uH7YSxBWYwxNG8mTOAn0SP99BkA,3876
13
+ power_grid_model_io/converters/vision_excel_converter.py,sha256=PSvbA5jKO-w7R7KIEstvx2pBjTgULoFU7SBG8MkAmSo,4129
14
14
  power_grid_model_io/data_stores/__init__.py,sha256=qwbj1j-Aa_yRB-E3j35pEVtF3mgH8CVIXAnog5mOry0,138
15
- power_grid_model_io/data_stores/base_data_store.py,sha256=XKdQY6Thrt_o7vtMXvTJFl1TCwBkSZVcImhbHXz23ls,1367
15
+ power_grid_model_io/data_stores/base_data_store.py,sha256=DJfLtRwvx_tXKnpjtBdfbMqPjWc324Eo5WeKTXjWXqc,1706
16
16
  power_grid_model_io/data_stores/csv_dir_store.py,sha256=H8ICXZRLDvp9OkbjkfHnoh4y7uNSXNepHAW6W53VsIw,1877
17
- power_grid_model_io/data_stores/excel_file_store.py,sha256=WI8pauQNYLOEu7hsrHU7o8yJ1tG3IAN2XUq920BQKps,8622
17
+ power_grid_model_io/data_stores/excel_file_store.py,sha256=Nl5GsC4N6Nf-PpC64wUcdWBgYv2xRt47Rc8CSOaeKi4,10704
18
18
  power_grid_model_io/data_stores/json_file_store.py,sha256=0njL2YZn_fImNcZqnIRpHp2UtIS6WGaQQ46TjIK8tyo,3954
19
- power_grid_model_io/data_stores/vision_excel_file_store.py,sha256=zU-zGktLmU7a808KwppiMc2YeCPfqjo03lRW0neEuQ4,805
19
+ power_grid_model_io/data_stores/vision_excel_file_store.py,sha256=85mZXoXaWpFHy_t-Ra0w4xCIjYK9b2Tr8cFZj3hPIbM,1059
20
20
  power_grid_model_io/data_types/__init__.py,sha256=63A_PkOsQkVd3To7Kl4FTUX7lbPG9BS9MSLzXTW6Ktk,383
21
21
  power_grid_model_io/data_types/_data_types.py,sha256=9xH5vBGrRVUSlPh4HXmORtKo3LFEhJEy3iTQqG7wsFA,1664
22
22
  power_grid_model_io/data_types/tabular_data.py,sha256=sV6S4kqCEuQiNZTOdKS7CiA2M8Ny1oGXvtFoN-xkYBg,8582
@@ -36,10 +36,10 @@ power_grid_model_io/utils/download.py,sha256=enEoj42ByC5j5rj_iZ1Y9we7t8Nmlwre0-9
36
36
  power_grid_model_io/utils/json.py,sha256=dQDRd2Vb8pfqLU2hTuWYv2cpSIBBbFhd0LOBP21YxJI,3327
37
37
  power_grid_model_io/utils/modules.py,sha256=a4IdozSL-sOZcmIQON_aQS7-cpnCyt-3p7zs40wRFkU,928
38
38
  power_grid_model_io/utils/parsing.py,sha256=XB1QSHnslIieFJBKFXZCtiydqpOqQBiX_CXDbItXgAQ,4522
39
- power_grid_model_io/utils/uuid_excel_cvtr.py,sha256=g4MC99Q_OBtcTHYzinX8ApokeMzhvvW-hCwoVz_fsDs,6902
39
+ power_grid_model_io/utils/uuid_excel_cvtr.py,sha256=H1iWhW_nluJBUJ3hK-Gc0xJjGnH5e35WrBz_fA3YXZs,7626
40
40
  power_grid_model_io/utils/zip.py,sha256=VXHX4xWPPZbhOlZUAbMDy3MgQFzK6_l7sRvGXihNUY4,3875
41
- power_grid_model_io-1.2.73.dist-info/LICENSE,sha256=7Pm2fWFFHHUG5lDHed1vl5CjzxObIXQglnYsEdtjo_k,14907
42
- power_grid_model_io-1.2.73.dist-info/METADATA,sha256=CnGExDWRfqOUocgFQ7rDC5yGhBSAEzPityMAixuDKzU,8041
43
- power_grid_model_io-1.2.73.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
44
- power_grid_model_io-1.2.73.dist-info/top_level.txt,sha256=7sq9VveemMm2R0RgTBa4tH8y_xF4_1hxbufmX9OjCTo,20
45
- power_grid_model_io-1.2.73.dist-info/RECORD,,
41
+ power_grid_model_io-1.2.74.dist-info/LICENSE,sha256=7Pm2fWFFHHUG5lDHed1vl5CjzxObIXQglnYsEdtjo_k,14907
42
+ power_grid_model_io-1.2.74.dist-info/METADATA,sha256=3_Q2OohsF0ey_-RdHfTydDSPeROZEhc7s3kJp4NY3SM,8041
43
+ power_grid_model_io-1.2.74.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
44
+ power_grid_model_io-1.2.74.dist-info/top_level.txt,sha256=7sq9VveemMm2R0RgTBa4tH8y_xF4_1hxbufmX9OjCTo,20
45
+ power_grid_model_io-1.2.74.dist-info/RECORD,,