Skip to content

Commit d810df1

Browse files
authored
Merge pull request #169 from alliander-opensource/fix/code-smells
Fix Sonar Code Smells
2 parents 470e4ab + ab2b7ed commit d810df1

File tree

6 files changed

+27
-29
lines changed

6 files changed

+27
-29
lines changed

src/power_grid_model_io/converters/pandapower_converter.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -144,12 +144,13 @@ def _fill_extra_info(self, extra_info: ExtraInfo):
144144
extra_info[pgm_id] = {"id_reference": {"table": pp_table, "index": pp_idx}}
145145
for component_data in self.pgm_input_data.values():
146146
for attr_name in component_data.dtype.names:
147-
if NODE_REF_RE.fullmatch(attr_name):
148-
for pgm_id, node_id in component_data[["id", attr_name]]:
149-
if pgm_id not in extra_info:
150-
extra_info[pgm_id] = {attr_name: node_id}
151-
else:
152-
extra_info[pgm_id][attr_name] = node_id
147+
if not NODE_REF_RE.fullmatch(attr_name):
148+
continue
149+
for pgm_id, node_id in component_data[["id", attr_name]]:
150+
if pgm_id in extra_info:
151+
extra_info[pgm_id][attr_name] = node_id
152+
else:
153+
extra_info[pgm_id] = {attr_name: node_id}
153154

154155
def _extra_info_to_idx_lookup(self, extra_info: ExtraInfo):
155156
"""

src/power_grid_model_io/converters/tabular_converter.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ def _parse_col_def_filter(
478478
value_column=sub_def["value_column"],
479479
)
480480
elif isinstance(sub_def, list):
481-
col_data = self._parse_pandas_function(data=data, table=table, function=name, col_def=sub_def)
481+
col_data = self._parse_pandas_function(data=data, table=table, fn_name=name, col_def=sub_def)
482482
elif isinstance(sub_def, dict):
483483
col_data = self._parse_function(data=data, table=table, function=name, col_def=sub_def)
484484
else:
@@ -549,13 +549,13 @@ def auto_id(row: np.ndarray):
549549

550550
return col_data.apply(auto_id, axis=1, raw=True)
551551

552-
def _parse_pandas_function(self, data: TabularData, table: str, function: str, col_def: List[Any]) -> pd.DataFrame:
552+
def _parse_pandas_function(self, data: TabularData, table: str, fn_name: str, col_def: List[Any]) -> pd.DataFrame:
553553
"""Special vectorized functions.
554554
555555
Args:
556556
data: The data
557557
table: The name of the current table
558-
function: The name of the function.
558+
fn_name: The name of the function.
559559
col_def: The definition of the function arguments
560560
561561
Returns:
@@ -564,15 +564,15 @@ def _parse_pandas_function(self, data: TabularData, table: str, function: str, c
564564
assert isinstance(col_def, list)
565565

566566
# "multiply" is an alias for "prod"
567-
if function == "multiply":
568-
function = "prod"
567+
if fn_name == "multiply":
568+
fn_name = "prod"
569569

570570
col_data = self._parse_col_def(data=data, table=table, col_def=col_def, extra_info=None)
571571

572572
try:
573-
fn_ptr = getattr(col_data, function)
573+
fn_ptr = getattr(col_data, fn_name)
574574
except AttributeError as ex:
575-
raise ValueError(f"Pandas DataFrame has no function '{function}'") from ex
575+
raise ValueError(f"Pandas DataFrame has no function '{fn_name}'") from ex
576576

577577
# If the function expects an 'other' argument, apply the function per column (e.g. divide)
578578
empty = inspect.Parameter.empty
@@ -581,12 +581,12 @@ def _parse_pandas_function(self, data: TabularData, table: str, function: str, c
581581
n_columns = col_data.shape[1] if col_data.ndim > 1 else 1
582582
result = col_data.iloc[:, 0]
583583
for i in range(1, n_columns):
584-
result = getattr(result, function)(other=col_data.iloc[:, i])
584+
result = getattr(result, fn_name)(other=col_data.iloc[:, i])
585585
return pd.DataFrame(result)
586586

587587
# If the function expects any argument
588588
if any(param.default == empty for name, param in fn_sig.parameters.items() if name != "kwargs"):
589-
raise ValueError(f"Invalid pandas function DataFrame.{function}")
589+
raise ValueError(f"Invalid pandas function DataFrame.{fn_name}")
590590

591591
return pd.DataFrame(fn_ptr(axis=1))
592592

src/power_grid_model_io/data_types/tabular_data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ def items(self) -> Generator[Tuple[str, Union[pd.DataFrame, np.ndarray]], None,
203203
"""
204204
Mimic the dictionary .items() function
205205
206-
Returns: An generator of the table names and the raw table data
206+
Returns: A generator of the table names and the raw table data
207207
"""
208208

209209
# Note: PyCharm complains about the type, but it is correct, as an ItemsView extends from

src/power_grid_model_io/functions/_functions.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,7 @@ def both_zeros_to_nan(value: float, other_value: float) -> float:
100100
value 0 value nan
101101
nan nan value nan
102102
"""
103-
if value == 0:
104-
if other_value == 0 or not has_value(other_value):
105-
_LOG.warning("0 replaced to nan")
106-
return float("nan")
103+
if value == 0 and (other_value == 0 or not has_value(other_value)):
104+
_LOG.warning("0 replaced to nan")
105+
return float("nan")
107106
return value

src/power_grid_model_io/utils/regex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
$ End of the string
4343
"""
4444

45-
PVS_EFFICIENCY_TYPE_RE = re.compile(r"[ ,..]1 pu: (95|97) %")
45+
PVS_EFFICIENCY_TYPE_RE = re.compile(r"[ ,.]1 pu: (95|97) %")
4646
r"""
4747
Regular expressions to match the efficiency type percentage at 1 pu, eg:
4848
- 0,1 pu: 93 %; 1 pu: 97 %

tests/unit/converters/test_tabular_converter.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ def test_parse_col_def_filter__pandas_function(mock_parse_function: MagicMock, c
459459

460460
# Assert
461461
mock_parse_function.assert_called_once_with(
462-
data=data, table="nodes", function="multiply", col_def=["id_number", "u_nom"]
462+
data=data, table="nodes", fn_name="multiply", col_def=["id_number", "u_nom"]
463463
)
464464
pd.testing.assert_frame_equal(result, function_result)
465465

@@ -707,7 +707,7 @@ def test_parse_pandas_function(
707707
mock_parse_col_def.return_value = parse_col_def_data
708708

709709
# Act
710-
result = converter._parse_pandas_function(data=data, table="foo", function=function, col_def=col_def)
710+
result = converter._parse_pandas_function(data=data, table="foo", fn_name=function, col_def=col_def)
711711

712712
# Assert
713713
mock_parse_col_def.assert_called_once_with(data=data, table="foo", col_def=col_def, extra_info=None)
@@ -723,7 +723,7 @@ def test_parse_pandas_function__no_data(mock_parse_col_def: MagicMock, converter
723723
mock_parse_col_def.return_value = parse_col_def_data
724724

725725
# Act
726-
result = converter._parse_pandas_function(data=data, table="foo", function="multiply", col_def=col_def)
726+
result = converter._parse_pandas_function(data=data, table="foo", fn_name="multiply", col_def=col_def)
727727

728728
# Assert
729729
mock_parse_col_def.assert_called_once_with(data=data, table="foo", col_def=col_def, extra_info=None)
@@ -737,17 +737,15 @@ def test_parse_pandas_function__invalid(mock_parse_col_def: MagicMock, converter
737737

738738
# Act / Assert
739739
with pytest.raises(AssertionError):
740-
converter._parse_pandas_function(
741-
data=MagicMock(), table="foo", function="multiply", col_def=123 # type: ignore
742-
)
740+
converter._parse_pandas_function(data=MagicMock(), table="foo", fn_name="multiply", col_def=123) # type: ignore
743741

744742
# Act / Assert
745743
with pytest.raises(ValueError, match="Pandas DataFrame has no function 'bar'"):
746-
converter._parse_pandas_function(data=MagicMock(), table="foo", function="bar", col_def=[])
744+
converter._parse_pandas_function(data=MagicMock(), table="foo", fn_name="bar", col_def=[])
747745

748746
# Act / Assert
749747
with pytest.raises(ValueError, match="Invalid pandas function DataFrame.apply"):
750-
converter._parse_pandas_function(data=MagicMock(), table="foo", function="apply", col_def=[])
748+
converter._parse_pandas_function(data=MagicMock(), table="foo", fn_name="apply", col_def=[])
751749

752750

753751
@patch("power_grid_model_io.converters.tabular_converter.get_function")

0 commit comments

Comments
 (0)