Skip to content

Commit c9874a9

Browse files
committed
first files
Signed-off-by: Thijs Baaijen <[email protected]>
1 parent bd58e6d commit c9874a9

File tree

5 files changed

+27
-26
lines changed

5 files changed

+27
-26
lines changed

src/power_grid_model_ds/_core/data_source/generator/arrays/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
class BaseGenerator:
1313
"""Base class to build a generator for grid elements"""
1414

15-
def __init__(self, grid: Grid, seed: int) -> None:
15+
def __init__(self, grid: Grid, seed: int | None) -> None:
1616
"""Initializes generator with grid and amount"""
1717
self.grid = grid
1818

src/power_grid_model_ds/_core/model/arrays/base/_modify.py

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

1111
def re_order(array: np.ndarray, new_order: ArrayLike, column: str = "id") -> np.ndarray:
1212
"""Re-order an id-array by the id column so that it follows a new_order.
13-
Expects the new_order input to contain the same values as self.id
13+
Expects the new_order input to contain the same values as self["id"]
1414
"""
1515
if column not in (array.dtype.names or ()):
1616
raise ValueError(f"Cannot re-order array: column {column} does not exist.")

src/power_grid_model_ds/_core/model/containers/base.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import numpy as np
1414

1515
from power_grid_model_ds._core import fancypy as fp
16+
from power_grid_model_ds._core.model.arrays import IdArray
1617
from power_grid_model_ds._core.model.arrays.base.array import FancyArray
1718
from power_grid_model_ds._core.model.arrays.base.errors import RecordDoesNotExist
1819
from power_grid_model_ds._core.model.constants import EMPTY_ID
@@ -75,7 +76,7 @@ def find_array_field(cls, array_type: Type[FancyArray]) -> dataclasses.Field:
7576
@property
7677
def max_id(self) -> int:
7778
"""Returns the max id across all arrays within the container."""
78-
max_per_array = [np.max(array.id) if array.size > 0 else 0 for array in self.all_arrays()]
79+
max_per_array = [np.max(array["id"]) if array.size > 0 else 0 for array in self.all_arrays()]
7980
return int(max(max_per_array))
8081

8182
def check_ids(self, check_between_arrays: bool = True, check_within_arrays: bool = True) -> None:
@@ -89,7 +90,7 @@ def check_ids(self, check_between_arrays: bool = True, check_within_arrays: bool
8990
ValueError: if duplicates are found.
9091
"""
9192

92-
id_arrays = [array for array in self.all_arrays() if hasattr(array, "id")]
93+
id_arrays = [array for array in self.all_arrays() if isinstance(array, IdArray)]
9394
if not id_arrays:
9495
return # no arrays to check
9596

@@ -113,7 +114,7 @@ def append(self, array: FancyArray, check_max_id: bool = True) -> None:
113114
114115
Args:
115116
array(FancyArray): the asset_array to be appended (e.g. a NodeArray instance).
116-
check_max_id(bool): whether to check max(array.id) with the id counter
117+
check_max_id(bool): whether to check max(array["id"]) with the id counter
117118
118119
Returns:
119120
None
@@ -132,12 +133,12 @@ def attach_ids(self, array: FancyArray) -> FancyArray:
132133
if not array.size:
133134
return array
134135

135-
if (id_set := set(array.id)) != {array.get_empty_value("id")}:
136+
if (id_set := set(array["id"])) != {array.get_empty_value("id")}:
136137
raise ValueError(f"Cannot attach ids to array that contains non-empty ids: {id_set}")
137138

138139
start = self._id_counter + 1
139140
end = start + len(array)
140-
array.id = np.arange(start, end)
141+
array["id"] = np.arange(start, end)
141142
self._id_counter = max(self._id_counter, end - 1)
142143

143144
return array
@@ -175,15 +176,15 @@ def _append(self, array: FancyArray, check_max_id: bool = True) -> None:
175176
Append the given asset_array to the corresponding field of Grid and generate ids.
176177
Args:
177178
array: the asset_array to be appended (e.g. a KabelArray instance).
178-
check_max_id: whether to check max(array.id) with the id counter
179+
check_max_id: whether to check max(array["id"]) with the id counter
179180
Returns: None.
180181
"""
181182
if array.size == 0:
182183
return
183184

184185
array_field = self.find_array_field(array.__class__)
185186

186-
if hasattr(array, "id"):
187+
if isinstance(array, IdArray):
187188
self._update_id_counter(array, check_max_id)
188189

189190
# Add the given asset_array to the corresponding array in the Grid.
@@ -208,30 +209,30 @@ def _get_empty_arrays(cls) -> dict:
208209
}
209210

210211
def _update_id_counter(self, array, check_max_id: bool = True):
211-
if np.all(array.id == EMPTY_ID):
212+
if np.all(array["id"] == EMPTY_ID):
212213
array = self.attach_ids(array)
213-
elif np.any(array.id == EMPTY_ID):
214+
elif np.any(array["id"] == EMPTY_ID):
214215
raise ValueError(f"Cannot append: array contains empty [{EMPTY_ID}] and non-empty ids.")
215216
elif check_max_id and self.id_counter > 0:
216217
# Only check for overlaps when array has prescribed (non-empty) IDs
217218
# Check if any incoming ID might overlap with existing IDs
218219
# This prevents overlaps since counter tracks the highest used ID
219-
new_min_id = np.min(array.id)
220+
new_min_id = np.min(array["id"])
220221
if new_min_id <= self._id_counter:
221222
raise ValueError(
222223
f"Cannot append: minimum id {new_min_id} is not greater than "
223224
f"the current id counter {self._id_counter}"
224225
)
225226

226-
new_max_id = np.max(array.id)
227+
new_max_id = np.max(array["id"])
227228
# Update _id_counter
228229
self._id_counter = max(self._id_counter, new_max_id)
229230

230231
@staticmethod
231-
def _get_duplicates_between_arrays(id_arrays: list[FancyArray], check: bool) -> np.ndarray:
232+
def _get_duplicates_between_arrays(id_arrays: list[IdArray], check: bool) -> np.ndarray:
232233
if not check:
233234
return np.array([])
234-
unique_ids_per_array = [np.unique(array.id) for array in id_arrays]
235+
unique_ids_per_array = [np.unique(array["id"]) for array in id_arrays]
235236

236237
all_ids = np.concatenate(unique_ids_per_array)
237238

@@ -240,7 +241,7 @@ def _get_duplicates_between_arrays(id_arrays: list[FancyArray], check: bool) ->
240241
return unique_ids[duplicate_mask]
241242

242243
@staticmethod
243-
def _get_arrays_with_duplicates(id_arrays: list[FancyArray], check: bool) -> list:
244+
def _get_arrays_with_duplicates(id_arrays: list[IdArray], check: bool) -> list:
244245
arrays_with_duplicates: list[Type] = []
245246
if not check:
246247
return arrays_with_duplicates

src/power_grid_model_ds/_core/model/grids/_text_sources.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,13 @@ def add_nodes(self, nodes: set[str]):
7474

7575
for node_id in source_nodes:
7676
new_node = self.grid.node.empty(1)
77-
new_node.id = node_id
78-
new_node.node_type = NodeType.SUBSTATION_NODE
77+
new_node["id"] = node_id
78+
new_node["node_type"] = NodeType.SUBSTATION_NODE
7979
self.grid.append(new_node, check_max_id=False)
8080

8181
for node_id in regular_nodes:
8282
new_node = self.grid.node.empty(1)
83-
new_node.id = node_id
83+
new_node["id"] = node_id
8484
self.grid.append(new_node, check_max_id=False)
8585

8686
def add_branches(self, branches: dict[tuple[str, str], list[str]]):
@@ -105,13 +105,13 @@ def add_branch(self, branch: tuple[str, str], comments: list[str]):
105105
if branch_ids:
106106
if len(branch_ids) > 1:
107107
raise ValueError(f"Multiple branch ids found in row {branch} {','.join(comments)}")
108-
new_branch.id = int(branch_ids[0])
108+
new_branch["id"] = int(branch_ids[0])
109109

110-
new_branch.from_node = from_node
111-
new_branch.to_node = to_node
112-
new_branch.from_status = 1
110+
new_branch["from_node"] = from_node
111+
new_branch["to_node"] = to_node
112+
new_branch["from_status"] = 1
113113
if "open" in comments:
114-
new_branch.to_status = 0
114+
new_branch["to_status"] = 0
115115
else:
116-
new_branch.to_status = 1
116+
new_branch["to_status"] = 1
117117
self.grid.append(new_branch, check_max_id=False)

tests/performance/_constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"structured": "import numpy as np;" + NUMPY_DTYPE + "input_array = np.zeros({size}, dtype=dtype)",
1111
"rec": "import numpy as np;" + NUMPY_DTYPE + "input_array = np.recarray(({size},),dtype=dtype)",
1212
"fancy": "from tests.conftest import FancyTestArray; input_array=FancyTestArray.zeros({size});"
13-
+ "import numpy as np;input_array.id = np.arange({size})",
13+
+ "import numpy as np;input_array['id'] = np.arange({size})",
1414
}
1515

1616
GRAPH_SETUP_CODES = {

0 commit comments

Comments
 (0)