Skip to content

Commit 7722f8b

Browse files
committed
final check
Signed-off-by: zhen0427 <[email protected]>
1 parent 0f210dd commit 7722f8b

File tree

5 files changed

+55
-40
lines changed

5 files changed

+55
-40
lines changed

src/power_grid_model_io/converters/pandapower_converter.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ def _create_pgm_input_lines(self):
397397
Returns:
398398
a power-grid-model structured array for the Line component
399399
"""
400-
pp_lines = self.pp_input_data[ComponentType.line]
400+
pp_lines = self.pp_input_data["line"]
401401

402402
if pp_lines.empty:
403403
return
@@ -491,7 +491,7 @@ def _create_pgm_input_shunts(self):
491491
Returns:
492492
a power-grid-model structured array for the Shunt component
493493
"""
494-
pp_shunts = self.pp_input_data[ComponentType.shunt]
494+
pp_shunts = self.pp_input_data["shunt"]
495495

496496
if pp_shunts.empty:
497497
return
@@ -1900,7 +1900,7 @@ def _pp_lines_output_3ph(self):
19001900
"loading_b_percent",
19011901
"loading_c_percent",
19021902
],
1903-
index=self._get_pp_ids(ComponentType.line, pgm_output_lines["id"]),
1903+
index=self._get_pp_ids("line", pgm_output_lines["id"]),
19041904
)
19051905

19061906
pp_output_lines_3ph["p_a_from_mw"] = pgm_output_lines["p_from"][:, 0] * 1e-6

src/power_grid_model_io/converters/pgm_json_converter.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import json
99
import logging
1010
import warnings
11+
from enum import Enum
1112
from pathlib import Path
1213
from typing import Any, Dict, List, Optional, Union
1314

@@ -92,7 +93,7 @@ def _parse_data(self, data: StructuredData, data_type: str, extra_info: Optional
9293
return result
9394

9495
def _parse_dataset(
95-
self, data: SinglePythonDataset, data_type: str, extra_info: Optional[ExtraInfo]
96+
self, data: SinglePythonDataset, data_type: Enum, extra_info: Optional[ExtraInfo]
9697
) -> SingleDataset:
9798
"""This function parses a single Python dataset and returns a power-grid-model input or update dictionary
9899
@@ -119,7 +120,7 @@ def _parse_dataset(
119120

120121
@staticmethod
121122
def _parse_component(
122-
objects: ComponentList, component: str, data_type: str, extra_info: Optional[ExtraInfo]
123+
objects: ComponentList, component: Enum, data_type: Enum, extra_info: Optional[ExtraInfo]
123124
) -> np.ndarray:
124125
"""This function generates a structured numpy array (power-grid-model native) from a structured dataset
125126
@@ -152,13 +153,15 @@ def _parse_component(
152153
try:
153154
array[i][attribute] = value
154155
except ValueError as ex:
155-
raise ValueError(f"Invalid '{attribute}' value for {component} {data_type} data: {ex}") from ex
156+
raise ValueError(
157+
f"Invalid '{attribute}' value for {component.value} {data_type.value} data: {ex}"
158+
) from ex
156159

157160
# If an attribute doesn't exist, it is added to the extra_info lookup table
158161
elif extra_info is not None:
159162
obj_id = obj["id"]
160163
if not isinstance(obj_id, int):
161-
raise ValueError(f"Invalid 'id' value for {component} {data_type} data")
164+
raise ValueError(f"Invalid 'id' value for {component.value} {data_type.value} data")
162165
if obj_id not in extra_info:
163166
extra_info[obj_id] = {}
164167
extra_info[obj_id][attribute] = value
@@ -215,8 +218,9 @@ def _is_batch(data: Dataset) -> bool:
215218
is_sparse_batch = isinstance(array, dict) and "indptr" in array and "data" in array
216219
if is_batch is not None and is_batch != (is_dense_batch or is_sparse_batch):
217220
raise ValueError(
218-
f"Mixed {'' if is_batch else 'non-'}batch data "
219-
f"with {'non-' if is_batch else ''}batch data ({component})."
221+
f"Mixed {'' if is_batch else 'non-'}batch data with "
222+
f"{'non-' if is_batch else ''}batch data ("
223+
f"{component.value if isinstance(component, Enum) else component})."
220224
)
221225
is_batch = is_dense_batch or is_sparse_batch
222226
return bool(is_batch)

src/power_grid_model_io/converters/tabular_converter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77

88
import inspect
99
import logging
10+
from enum import Enum
1011
from pathlib import Path
1112
from typing import Any, Collection, Dict, List, Mapping, Optional, Union, cast
1213

1314
import numpy as np
1415
import pandas as pd
15-
from enum import Enum
1616
import yaml
1717
from power_grid_model import initialize_array
1818
from power_grid_model.data_types import Dataset

tests/unit/converters/test_pandapower_converter_input.py

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -197,15 +197,15 @@ def test_fill_pgm_extra_info():
197197
def test_fill_pp_extra_info():
198198
# Arrange
199199
converter = PandaPowerConverter()
200-
converter.idx_lookup[(ComponentType.line, None)] = pd.Series([102, 103], index=[1, 2])
200+
converter.idx_lookup[("line", None)] = pd.Series([102, 103], index=[1, 2])
201201
converter.idx_lookup[("trafo", None)] = pd.Series([201, 202, 203], index=[3, 4, 5])
202-
converter.idx[(ComponentType.line, None)] = pd.Series([1, 2], index=[102, 103])
202+
converter.idx[("line", None)] = pd.Series([1, 2], index=[102, 103])
203203
converter.idx[("trafo", None)] = pd.Series([3, 4, 5], index=[201, 202, 203])
204204

205205
converter.pp_input_data["trafo"] = pd.DataFrame(
206206
{"df": [0.1, 0.2, 0.3], "other": [0.1, 0.2, 0.3]}, index=[201, 202, 203]
207207
)
208-
converter.pp_input_data[ComponentType.line] = pd.DataFrame([10, 11, 12], columns=["df"], index=[201, 202, 203])
208+
converter.pp_input_data["line"] = pd.DataFrame([10, 11, 12], columns=["df"], index=[201, 202, 203])
209209

210210
# Act
211211
extra_info = {}
@@ -500,16 +500,16 @@ def test_create_pgm_input_nodes(mock_init_array: MagicMock, two_pp_objs: MockDf,
500500
@patch("power_grid_model_io.converters.pandapower_converter.initialize_array")
501501
def test_create_pgm_input_lines(mock_init_array: MagicMock, two_pp_objs, converter):
502502
# Arrange
503-
converter.pp_input_data[ComponentType.line] = two_pp_objs
503+
converter.pp_input_data["line"] = two_pp_objs
504504

505505
# Act
506506
converter._create_pgm_input_lines()
507507

508508
# Assert
509509

510510
# administration
511-
converter.get_switch_states.assert_called_once_with(ComponentType.line)
512-
converter._generate_ids.assert_called_once_with(ComponentType.line, two_pp_objs.index)
511+
converter.get_switch_states.assert_called_once_with("line")
512+
converter._generate_ids.assert_called_once_with("line", two_pp_objs.index)
513513
converter._get_pgm_ids.assert_any_call("bus", _get_pp_attr("line", "from_bus", expected_type="u4"))
514514
converter._get_pgm_ids.assert_any_call("bus", _get_pp_attr("line", "to_bus", expected_type="u4"))
515515

@@ -671,7 +671,9 @@ def test_create_pgm_input_sym_loads(mock_init_array: MagicMock, two_pp_objs, con
671671
# administration:
672672

673673
# initialization
674-
mock_init_array.assert_called_once_with(data_type=DatasetType.input, component_type=ComponentType.sym_load, shape=3 * 2)
674+
mock_init_array.assert_called_once_with(
675+
data_type=DatasetType.input, component_type=ComponentType.sym_load, shape=3 * 2
676+
)
675677

676678
# retrieval:
677679
converter._get_pp_attr.assert_any_call("load", "bus", expected_type="u4")
@@ -708,7 +710,9 @@ def test_create_pgm_input_asym_loads(mock_init_array: MagicMock, two_pp_objs, co
708710
converter._generate_ids.assert_called_once_with("asymmetric_load", two_pp_objs.index)
709711

710712
# initialization
711-
mock_init_array.assert_called_once_with(data_type=DatasetType.input, component_type=ComponentType.asym_load, shape=2)
713+
mock_init_array.assert_called_once_with(
714+
data_type=DatasetType.input, component_type=ComponentType.asym_load, shape=2
715+
)
712716

713717
# retrieval:
714718
converter._get_pp_attr.assert_any_call("asymmetric_load", "bus", expected_type="u4")
@@ -790,7 +794,7 @@ def test_create_pgm_input_transformers__tap_dependent_impedance() -> None:
790794
@patch("power_grid_model_io.converters.pandapower_converter.initialize_array")
791795
def test_create_pgm_input_shunts(mock_init_array: MagicMock, two_pp_objs, converter):
792796
# Arrange
793-
converter.pp_input_data[ComponentType.shunt] = two_pp_objs
797+
converter.pp_input_data["shunt"] = two_pp_objs
794798

795799
# Act
796800
converter._create_pgm_input_shunts()
@@ -804,12 +808,12 @@ def test_create_pgm_input_shunts(mock_init_array: MagicMock, two_pp_objs, conver
804808
mock_init_array.assert_called_once_with(data_type=DatasetType.input, component_type=ComponentType.shunt, shape=2)
805809

806810
# retrieval:
807-
converter._get_pp_attr.assert_any_call(ComponentType.shunt, "bus", expected_type="u4")
808-
converter._get_pp_attr.assert_any_call(ComponentType.shunt, "p_mw", expected_type="f8")
809-
converter._get_pp_attr.assert_any_call(ComponentType.shunt, "q_mvar", expected_type="f8")
810-
converter._get_pp_attr.assert_any_call(ComponentType.shunt, "vn_kv", expected_type="f8")
811-
converter._get_pp_attr.assert_any_call(ComponentType.shunt, "step", expected_type="u4", default=1)
812-
converter._get_pp_attr.assert_any_call(ComponentType.shunt, "in_service", expected_type="bool", default=True)
811+
converter._get_pp_attr.assert_any_call("shunt", "bus", expected_type="u4")
812+
converter._get_pp_attr.assert_any_call("shunt", "p_mw", expected_type="f8")
813+
converter._get_pp_attr.assert_any_call("shunt", "q_mvar", expected_type="f8")
814+
converter._get_pp_attr.assert_any_call("shunt", "vn_kv", expected_type="f8")
815+
converter._get_pp_attr.assert_any_call("shunt", "step", expected_type="u4", default=1)
816+
converter._get_pp_attr.assert_any_call("shunt", "in_service", expected_type="bool", default=True)
813817

814818
assert len(converter._get_pp_attr.call_args_list) == 6
815819

@@ -868,7 +872,9 @@ def test_create_pgm_input_transformers(mock_init_array: MagicMock, two_pp_objs,
868872
)
869873

870874
# initialization
871-
mock_init_array.assert_called_once_with(data_type=DatasetType.input, component_type=ComponentType.transformer, shape=2)
875+
mock_init_array.assert_called_once_with(
876+
data_type=DatasetType.input, component_type=ComponentType.transformer, shape=2
877+
)
872878

873879
# retrieval:
874880
converter._get_pp_attr.assert_any_call("trafo", "hv_bus", expected_type="u4")
@@ -1581,7 +1587,9 @@ def test_create_pgm_input_wards(mock_init_array: MagicMock, two_pp_objs, convert
15811587
# administration:
15821588

15831589
# initialization
1584-
mock_init_array.assert_called_once_with(data_type=DatasetType.input, component_type=ComponentType.sym_load, shape=2 * 2)
1590+
mock_init_array.assert_called_once_with(
1591+
data_type=DatasetType.input, component_type=ComponentType.sym_load, shape=2 * 2
1592+
)
15851593

15861594
# retrieval:
15871595
converter._get_pp_attr.assert_any_call("ward", "bus", expected_type="u4")
@@ -2034,7 +2042,7 @@ def test_get_switch_states_lines(mock_get_individual_switch_states: MagicMock):
20342042
# Arrange
20352043
converter = PandaPowerConverter()
20362044
converter.pp_input_data = {
2037-
ComponentType.line: pd.DataFrame(columns=["from_bus", "to_bus"], data=[[101, 102]], index=[1]),
2045+
"line": pd.DataFrame(columns=["from_bus", "to_bus"], data=[[101, 102]], index=[1]),
20382046
"switch": pd.DataFrame(
20392047
columns=["bus", "et", "element", "closed"],
20402048
data=[[101, "l", 1, False], [102, "x", 1, False]],
@@ -2108,7 +2116,7 @@ def test_get_switch_states__exception():
21082116

21092117
# Act / Assert
21102118
with pytest.raises(KeyError, match=r"link"):
2111-
converter.get_switch_states(ComponentType.link)
2119+
converter.get_switch_states("link")
21122120

21132121

21142122
@patch("power_grid_model_io.converters.pandapower_converter.PandaPowerConverter.get_individual_switch_states")
@@ -2138,11 +2146,11 @@ def test_lookup_id():
21382146
# Arrange
21392147
converter = PandaPowerConverter()
21402148
converter.idx_lookup = {
2141-
(ComponentType.line, None): pd.Series([0, 1, 2, 3, 4], index=[21, 345, 0, 3, 15]),
2149+
("line", None): pd.Series([0, 1, 2, 3, 4], index=[21, 345, 0, 3, 15]),
21422150
("load", "const_current"): pd.Series([5, 6, 7, 8, 9], index=[543, 14, 34, 48, 4]),
21432151
}
21442152

2145-
expected_line = {"table": ComponentType.line, "index": 4}
2153+
expected_line = {"table": "line", "index": 4}
21462154
expected_load = {"table": "load", "name": "const_current", "index": 8}
21472155

21482156
# Act
@@ -2157,7 +2165,7 @@ def test_lookup_id():
21572165
def test_lookup_id__value_error():
21582166
# Arrange
21592167
converter = PandaPowerConverter()
2160-
converter.idx_lookup = {(ComponentType.line, None): pd.Series([0, 1, 2, 3, 4], index=[21, 345, 0, 3, 15])}
2168+
converter.idx_lookup = {("line", None): pd.Series([0, 1, 2, 3, 4], index=[21, 345, 0, 3, 15])}
21612169

21622170
# Act / Assert
21632171
with pytest.raises(KeyError):

tests/unit/converters/test_pgm_json_converter.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def converter():
2727
@pytest.fixture
2828
def structured_input_data():
2929
input_data = {
30-
ComponentType.node: [
30+
"node": [
3131
{"id": 1, "u_rated": 400.0},
3232
{"id": 2, "u_rated": 400.0, "some_extra_info": 2.1},
3333
]
@@ -38,8 +38,8 @@ def structured_input_data():
3838
@pytest.fixture
3939
def structured_batch_data():
4040
batch_data = [
41-
{ComponentType.sym_load: [{"id": 3, "p_specified": 1.0}]},
42-
{ComponentType.sym_load: [{"id": 3, "p_specified": 2.0}, {"id": 4, "p_specified": 3.0}]},
41+
{"sym_load": [{"id": 3, "p_specified": 1.0}]},
42+
{"sym_load": [{"id": 3, "p_specified": 2.0}, {"id": 4, "p_specified": 3.0}]},
4343
]
4444
return batch_data
4545

@@ -111,9 +111,12 @@ def test_parse_component(converter: PgmJsonConverter, structured_input_data):
111111
node_with_wrong_attr_val = {"id": 3, "u_rated": "fault"}
112112
objects[0].append(node_with_wrong_attr_val) # type: ignore
113113
with pytest.raises(
114-
ValueError, match="Invalid 'u_rated' value for ComponentType.node DatasetType.input data: could not convert string to float: 'fault'"
114+
ValueError,
115+
match="Invalid 'u_rated' value for node input data: could not convert string to float: 'fault'",
115116
):
116-
converter._parse_component(objects=objects[0], component=component, data_type=DatasetType.input, extra_info=None)
117+
converter._parse_component(
118+
objects=objects[0], component=component, data_type=DatasetType.input, extra_info=None
119+
)
117120

118121

119122
def test_serialize_data(converter: PgmJsonConverter, pgm_input_data: SingleDataset, pgm_batch_data: BatchDataset):
@@ -122,9 +125,9 @@ def test_serialize_data(converter: PgmJsonConverter, pgm_input_data: SingleDatas
122125
with capture_logs() as cap_log:
123126
structured_batch_data = converter._serialize_data(data=pgm_batch_data, extra_info={})
124127
assert structured_batch_data == [
125-
{ComponentType.line: [{}, {}]},
126-
{ComponentType.line: [{}, {}]},
127-
{ComponentType.line: [{}, {}]},
128+
{"line": [{}, {}]},
129+
{"line": [{}, {}]},
130+
{"line": [{}, {}]},
128131
]
129132
assert_log_match(cap_log[0], "warning", "Extra info is not supported for batch data export")
130133

0 commit comments

Comments
 (0)